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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances, GADTs, OverloadedStrings, CPP #-}
module Haste.AST.Print () where
import Prelude hiding (LT, GT)
import Haste.Config
import Haste.AST.Syntax
import Haste.AST.Op
import Haste.AST.PP as PP
import Haste.AST.PP.Opts as PP
import Data.ByteString.Builder
import Control.Monad
import Data.Char
import Numeric (showHex)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.UTF8 as BS
instance Pretty Var where
pp (Foreign name) = do
put name
doComment <- getOpt externalAnnotation
when doComment . put $ byteString "/* EXTERNAL */"
pp (Internal name@(Name u _) comment _) = do
hsnames <- getOpt preserveNames
if hsnames
then put $ buildStgName name
else do
pp name
doComment <- getOpt nameComments
when doComment $ do
put $ byteString "/* "
if BS.null comment
then put u
else put comment
put $ byteString " */"
instance Pretty Name where
pp name = finalNameFor name >>= put . buildFinalName
instance Pretty LHS where
pp (NewVar _ v) = "var " .+. pp v
pp (LhsExp _ ex) = pp ex
instance Pretty Lit where
pp (LNum d) = put d
pp (LStr s) = "\"" .+. put (fixQuotes $ BS.toString s) .+. "\""
where
fixQuotes ('\\':xs) = "\\\\" ++ fixQuotes xs
fixQuotes ('"':xs) = '\\':'"' : fixQuotes xs
fixQuotes ('\'':xs) = '\\':'\'' : fixQuotes xs
fixQuotes ('\r':xs) = '\\':'r' : fixQuotes xs
fixQuotes ('\n':xs) = '\\':'n' : fixQuotes xs
fixQuotes (x:xs)
| ord x <= 127 = x : fixQuotes xs
| otherwise = toHex x ++ fixQuotes xs
fixQuotes _ = []
pp (LBool b) = put b
pp (LInt n) = put n
pp (LNull) = "null"
-- | Generate a Haskell \uXXXX escape sequence for a char if it's >127.
toHex :: Char -> String
toHex c =
case ord c of
n | n < 127 -> [c]
| otherwise -> "\\u" ++ exactlyFour (showHex (n `rem` 65536) "")
-- | Truncate and pad a string to exactly four characters. '0' is used for padding.
exactlyFour :: String -> String
exactlyFour s =
pad (4-len) $ drop (len-4) s
where
len = length s
pad 0 cs = cs
pad n cs = '0' : pad (n-1) cs
-- | Default separator; comma followed by space, if spaces are enabled.
sep :: PP ()
sep = "," .+. sp
instance Pretty Exp where
pp (Var v) =
pp v
pp (Lit l) =
pp l
pp (JSLit l) =
put l
pp (Not ex) = do
case neg ex of
Just ex' -> pp ex'
_ -> if expPrec (Not ex) > expPrec ex
then "!(" .+. pp ex .+. ")"
else "!" .+. pp ex
pp bop@(BinOp _ _ _) =
case norm bop of
BinOp op a b -> opParens op a b
ex -> pp ex
pp (Fun args body) = do
"function(" .+. ppList sep args .+. "){" .+. newl
indent $ pp body
ind .+. "}"
pp (Call _ call f args) = do
case call of
Normal True -> "B(" .+. normalCall .+. ")"
Normal False -> normalCall
Fast True -> "B(" .+. fastCall .+. ")"
Fast False -> fastCall
Method m ->
pp f .+. put (BS.cons '.' m) .+. "(" .+. ppList sep args .+. ")"
where
normalCall =
case args of
[x] -> "A1(" .+. pp f .+. "," .+. pp x .+. ")"
[_,_] -> "A2(" .+. pp f .+. "," .+. ppList sep args .+. ")"
[_,_,_] -> "A3(" .+. pp f .+. "," .+. ppList sep args .+. ")"
_ -> "A(" .+. pp f .+. ",[" .+. ppList sep args .+. "])"
fastCall = ppCallFun f .+. "(" .+. ppList sep args .+. ")"
ppCallFun fun@(Fun _ _) = "(" .+. pp fun .+. ")"
ppCallFun fun = pp fun
pp e@(Index arr ix) = do
if expPrec e > expPrec arr
then "(" .+. pp arr .+. ")"
else pp arr
"[" .+. pp ix .+. "]"
pp (Member obj m) = do
pp obj .+. "." .+. put m
pp (Obj ms) | and $ zipWith (==) ["_","a","b","c","d","e"] (map fst ms) =
ppADT ms
pp (Obj members) = do
"{" .+. ppList "," members .+. "}"
pp (Arr exs) = do
"[" .+. ppList sep exs .+. "]"
pp (AssignEx l r) = do
pp l .+. sp .+. "=" .+. sp .+. pp r
pp e@(IfEx c th el) = do
if expPrec e > expPrec c
then "(" .+. pp c .+. ")"
else pp c
sp .+. "?" .+. sp .+. pp th .+. sp .+. ":" .+. sp .+. pp el
pp (Eval x) = do
"E(" .+. pp x .+. ")"
pp (Thunk True x) = do
"new T(function(){" .+. newl .+. indent (pp x) .+. ind .+. "})"
pp (Thunk False x) = do
"new T(function(){" .+. newl .+. indent (pp x) .+. ind .+. "},1)"
-- | Pretty-print an object representing an ADT.
ppADT :: [(BS.ByteString, Exp)] -> PP ()
ppADT ms = do
useClassy <- getCfg useClassyObjects
if useClassy && args <= 6
then "new T" .+. put args .+. "(" .+. ppList "," (map snd ms) .+. ")"
else "{" .+. ppList "," ms .+. "}"
where
args = length ms-1
instance Pretty (BS.ByteString, Exp) where
pp (n, x) = put n .+. ":" .+. pp x
instance Pretty (Var, Exp) where
pp (v, ex) = pp v .+. sp .+. "=" .+. sp .+. pp ex
instance Pretty Bool where
pp True = "true"
pp False = "false"
-- | Print a series of NewVars at once, to avoid unnecessary "var" keywords.
ppAssigns :: Stm -> PP ()
ppAssigns stm = do
line $ "var " .+. ppList ("," .+. newl .+. ind) assigns .+. ";"
pp next
where
(assigns, next) = gather [] stm
gather as (Assign (NewVar _ v) ex nxt) = gather ((v, ex):as) nxt
gather as nxt = (reverse as, nxt)
-- | Returns the final statement in a case branch.
finalStm :: Stm -> PP Stm
finalStm s =
case s of
Assign _ _ s' -> finalStm s'
Case _ _ _ next -> finalStm next
Forever s' -> finalStm s'
_ -> return s
instance Pretty Stm where
pp (Case cond def alts next) = do
prettyCase cond def alts
pp next
pp (Forever stm) = do
line "while(1){"
indent $ pp stm
line "}"
pp s@(Assign lhs ex next) = do
case lhs of
_ | lhs == blackHole ->
line (pp ex .+. ";") >> pp next
NewVar _ _ ->
ppAssigns s
LhsExp _ _ ->
line (pp lhs .+. sp .+. "=" .+. sp .+. pp ex .+. ";") >> pp next
pp (Return ex) = do
line $ "return " .+. pp ex .+. ";"
pp (Cont) = do
line "continue;"
pp (Stop) = do
return ()
pp (Tailcall call) = do
b <- getCfg tailChainBound
if b <= 1
then line $ "return new F(function(){return " .+. pp call .+. ";});"
else line $ "return C > " .+. put (b-1) .+. " ? new F(function(){return "
.+. pp call .+. ";}) : (++C," .+. pp call .+. ");"
pp (ThunkRet ex) = do
line $ "return " .+. pp ex .+. ";"
neg :: Exp -> Maybe Exp
neg (BinOp Eq a b) = Just $ BinOp Neq a b
neg (BinOp Neq a b) = Just $ BinOp Eq a b
neg (BinOp GT a b) = Just $ BinOp LTE a b
neg (BinOp LT a b) = Just $ BinOp GTE a b
neg (BinOp GTE a b) = Just $ BinOp LT a b
neg (BinOp LTE a b) = Just $ BinOp GT a b
neg _ = Nothing
-- | Turn eligible case statements into if statements.
prettyCase :: Exp -> Stm -> [Alt] -> PP ()
prettyCase cond def [(con, branch)] = do
case (def, branch) of
(_, Stop) -> do
line $ "if(" .+. pp (neg' (test con)) .+. "){"
indent $ pp def
line "}"
(Stop, _) -> do
line $ "if(" .+. pp (test con) .+. "){"
indent $ pp branch
line "}"
_ -> do
line $ "if(" .+. pp (test con) .+."){"
indent $ pp branch
line "}else{"
indent $ pp def
line "}"
where
test (Lit (LBool True)) = cond
test (Lit (LBool False)) = Not cond
test (Lit (LNum 0)) = Not cond
test c = BinOp Eq cond c
neg' c = maybe (Not c) id (neg c)
prettyCase _ def [] = do
pp def
prettyCase cond def alts = do
line $ "switch(" .+. pp cond .+. "){"
indent $ do
mapM_ pp alts
line $ "default:"
indent $ pp def
line "}"
instance Pretty Alt where
pp (con, branch) = do
line $ "case " .+. pp con .+. ":"
indent $ do
pp branch
s <- finalStm branch
case s of
Return _ -> return ()
Cont -> return ()
_ -> line "break;";
opParens :: BinOp -> Exp -> Exp -> PP ()
opParens Sub a (BinOp Sub (Lit (LNum 0)) b) =
opParens Add a b
opParens Sub a (Lit (LNum n)) | n < 0 =
opParens Add a (Lit (LNum (-n)))
opParens Sub (Lit (LNum 0)) b =
case b of
BinOp _ _ _ -> " -(" .+. pp b .+. ")"
_ -> " -" .+. pp b
opParens op a b = do
let bparens = case b of
Lit (LNum n) | n < 0 -> \x -> "(".+. pp x .+. ")"
_ -> parensR
parensL a .+. put (stringUtf8 $ show op) .+. bparens b
where
parensL x = if expPrec x < opPrec op
then "(" .+. pp x .+. ")"
else pp x
parensR x = if expPrec x <= opPrec op
then "(" .+. pp x .+. ")"
else pp x
-- | Normalize an operator expression by shifting parentheses to the left for
-- all associative operators and eliminating comparisons with true/false.
norm :: Exp -> Exp
norm (BinOp op a (BinOp op' b c)) | op == op' && opIsAssoc op =
norm (BinOp op (BinOp op a b) c)
norm (BinOp Eq a (Lit (LBool True))) = norm a
norm (BinOp Eq (Lit (LBool True)) b) = norm b
norm (BinOp Eq a (Lit (LBool False))) = Not (norm a)
norm (BinOp Eq (Lit (LBool False)) b) = Not (norm b)
norm (BinOp Neq a (Lit (LBool True))) = Not (norm a)
norm (BinOp Neq (Lit (LBool True)) b) = Not (norm b)
norm (BinOp Neq a (Lit (LBool False))) = norm a
norm (BinOp Neq (Lit (LBool False)) b) = norm b
norm e = e
| nyson/haste-compiler | src/Haste/AST/Print.hs | bsd-3-clause | 9,616 | 0 | 19 | 3,101 | 4,237 | 2,050 | 2,187 | 269 | 6 |
module Tandoori.Typing.DataType (constructorsFromDecl) where
import Tandoori
import Tandoori.Typing
import Tandoori.Typing.Error
import Tandoori.Typing.Monad
import Tandoori.GHC.Internals
import Tandoori.Typing.Repr
import Control.Monad
constructorsFromDecl :: TyClDecl Name -> Typing [(ConName, Ty)]
constructorsFromDecl decl | isDataDecl decl = do
let nameData = tcdName decl
αs = hsTyVarNames $ map unLoc $ tcdTyVars decl
τData = tyCurryApp $ (TyCon nameData):(map TyVar αs)
forM (map unLoc $ tcdCons decl) $ \ con -> do
let tys = map unLoc $ hsConDeclArgTys $ con_details con
σArgs <- mapM fromHsType tys
τArgs <- forM σArgs $ \ σ -> do
case σ of
PolyTy [] τ -> return τ
PolyTy ctx τ -> raiseError $ InvalidCon σ
let τ = tyCurryFun (τArgs ++ [τData])
return (unLoc $ con_name con, τ)
constructorsFromDecl _ = return []
| bitemyapp/tandoori | src/Tandoori/Typing/DataType.hs | bsd-3-clause | 934 | 0 | 21 | 220 | 325 | 161 | 164 | 23 | 2 |
{-# LANGUAGE TemplateHaskell, OverloadedStrings, GeneralizedNewtypeDeriving #-}
module SecondTransfer.Socks5.Session (
tlsSOCKS5Serve'
, ConnectOrForward (..)
, Socks5ServerState
, initSocks5ServerState
, targetAddress_S5
, socket_S5
) where
import Control.Concurrent
import qualified Control.Exception as E
import Control.Lens ( makeLenses, (^.), set)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import Data.ByteString.Char8 ( unpack, pack)
import qualified Data.Attoparsec.ByteString as P
import qualified Data.Binary as U
import qualified Data.Binary.Put as U
import Data.Word (Word16)
import Data.Int (Int64)
import qualified Network.Socket as NS
import SecondTransfer.Exception (
SOCKS5ProtocolException (..),
NoMoreDataException,
forkIOExc )
import SecondTransfer.Socks5.Types
import SecondTransfer.Socks5.Parsers
import SecondTransfer.Socks5.Serializers
import SecondTransfer.IOCallbacks.Types
import SecondTransfer.IOCallbacks.SocketServer
import SecondTransfer.IOCallbacks.Coupling (couple)
import SecondTransfer.IOCallbacks.WrapSocket (
HasSocketPeer(..),
AcceptErrorCondition
)
-- For debugging purposes
--import SecondTransfer.IOCallbacks.Botcher
data Socks5ServerState = Socks5ServerState {
_nextConnection_S5S :: !Int64
}
makeLenses ''Socks5ServerState
initSocks5ServerState :: Socks5ServerState
initSocks5ServerState = Socks5ServerState 0
data ConnectOrForward =
Connect_COF B.ByteString IOCallbacks IndicatedAddress
| Forward_COF B.ByteString Word16
| Drop_COF B.ByteString
tryRead :: IOCallbacks -> String -> B.ByteString -> P.Parser a -> IO (a,B.ByteString)
tryRead iocallbacks what_doing leftovers p = do
let
react (P.Done i r) = return (r, i)
react (P.Fail i contexts msg) =
E.throwIO $ SOCKS5ProtocolException
("/" ++
what_doing ++
"/" ++
"parseFailed: Left #" ++
show (B.length i) ++
" bytes to parse ( " ++
show (B.unpack i) ++
") " ++ " contexts: " ++
(show contexts) ++
" message: " ++
msg
)
react (P.Partial f) =
go f
go f = do
fragment <- (iocallbacks ^. bestEffortPullAction_IOC) True
--
react (f $ LB.toStrict fragment)
react $ P.parse p leftovers
pushDatum :: IOCallbacks -> (a -> U.Put) -> a -> IO ()
pushDatum iocallbacks putthing x = do
let
datum = U.runPut (putthing x)
(iocallbacks ^. pushAction_IOC) datum
-- | Forwards a set of IOCallbacks (actually, it is exactly the same passed in) after the
-- SOCKS5 negotiation, if the negotiation succeeds and the indicated "host" is approved
-- by the first parameter. Quite simple.
negotiateSocksAndForward :: (B.ByteString -> Bool) -> IOCallbacks -> IO ConnectOrForward
negotiateSocksAndForward approver socks_here =
do
let
tr = tryRead socks_here
ps = pushDatum socks_here
-- Start by reading the standard socks5 header
ei <- E.try $ do
(_auth, next1) <- tr "client-auth-methods" "" parseClientAuthMethods_Packet
-- I will ignore the auth methods for now
let
server_selects = ServerSelectsMethod_Packet ProtocolVersion 0 -- No auth
ps putServerSelectsMethod_Packet server_selects
(req_packet, _next2) <- tr "client-request" next1 parseClientRequest_Packet
case req_packet ^. cmd_SP3 of
Connect_S5PC -> do
-- Can accept a connect, to what?
let
address = req_packet ^. address_SP3
port = req_packet ^. port_SP3
named_host = case address of
DomainName_IA name -> name
_ -> E.throw . SOCKS5ProtocolException $ "UnsupportedAddress " ++ show address
if approver named_host && port == 443 then
do
-- First I need to answer to the client that we are happy and ready
let
server_reply = ServerReply_Packet {
_version_SP4 = ProtocolVersion
, _replyField_SP4 = Succeeded_S5RF
, _reservedField_SP4 = 0
, _address_SP4 = IPv4_IA 0x7f000001
, _port_SP4 = 10001
}
ps putServerReply_Packet server_reply
-- Now that I have the attendant, let's just activate it ...
-- CORRECT WAY:
return $ Connect_COF named_host socks_here address
else do
-- Logging? We need to get that real right.
return $ Drop_COF named_host
-- Other commands not handled for now
_ -> do
return $ Drop_COF "<socks5-unimplemented-command>"
case ei of
Left (SOCKS5ProtocolException msg) -> return $ Drop_COF (pack msg)
Right result -> return result
-- | Forwards a set of IOCallbacks (actually, it is exactly the same passed in) after the
-- SOCKS5 negotiation, if the negotiation succeeds and the indicated "host" is approved
-- by the first parameter. If the approver returns false, this function will try to
-- actually connect to the host and let the software act as a true proxy.
negotiateSocksForwardOrConnect :: (B.ByteString -> Bool) -> IOCallbacks -> IO ConnectOrForward
negotiateSocksForwardOrConnect approver socks_here =
do
let
tr = tryRead socks_here
ps = pushDatum socks_here
-- Start by reading the standard socks5 header
ei <- E.try $ do
(_auth, next1) <- tr "client-auth-methods" "" parseClientAuthMethods_Packet
-- I will ignore the auth methods for now
let
server_selects = ServerSelectsMethod_Packet ProtocolVersion 0 -- No auth
ps putServerSelectsMethod_Packet server_selects
(req_packet, _next2) <- tr "client-request" next1 parseClientRequest_Packet
let
target_port_number = req_packet ^. port_SP3
case req_packet ^. cmd_SP3 of
Connect_S5PC -> do
-- Can accept a connect, to what?
let
address = req_packet ^. address_SP3
externalConnectProcessing =
do
maybe_forwarding_callbacks <- connectOnBehalfOfClient address target_port_number
case maybe_forwarding_callbacks of
Just (_indicated_address, io_callbacks) -> do
let
server_reply = ServerReply_Packet {
_version_SP4 = ProtocolVersion
, _replyField_SP4 = Succeeded_S5RF
, _reservedField_SP4 = 0
, _address_SP4 = IPv4_IA 0x7f000001
-- Wrong port, but...
, _port_SP4 = 10001
}
E.catch
(do
ps putServerReply_Packet server_reply
-- Now couple the two streams ...
_ <- couple socks_here io_callbacks
return $ Forward_COF (pack . show $ address) (fromIntegral target_port_number)
)
(
(\ _e ->
return . Drop_COF . pack $
"Connection truncated by forwarding target " ++ show address
) :: NoMoreDataException -> IO ConnectOrForward
)
_ ->
return $ Drop_COF (pack . show $ address)
-- /let
case address of
DomainName_IA named_host
| target_port_number == 443 ->
if approver named_host
then do
-- First I need to answer to the client that we are happy and ready
let
server_reply = ServerReply_Packet {
_version_SP4 = ProtocolVersion
, _replyField_SP4 = Succeeded_S5RF
, _reservedField_SP4 = 0
, _address_SP4 = IPv4_IA 0x7f000001
, _port_SP4 = 10001
}
ps putServerReply_Packet server_reply
-- Now that I have the attendant, let's just activate it ...
return $ Connect_COF named_host socks_here address
else do
-- Forward to an external host
externalConnectProcessing
| otherwise ->
if not (approver named_host)
then
externalConnectProcessing
else
return . Drop_COF . pack$
"Connections to port other than 443 are rejected by SOCKS5"
IPv4_IA _ -> do
-- TODO: Some address sanitization
externalConnectProcessing
IPv6_IA _ ->
error "IPv6NotHandledYet"
-- Other commands not handled for now
_ -> do
--putStrLn "SOCKS5 HAS NEGLECTED TO REJECT A CONNECTION"
return $ Drop_COF "<socks5-unimplemented>"
case ei of
Left (SOCKS5ProtocolException msg) -> return . Drop_COF . pack $ msg
Right result -> return result
connectOnBehalfOfClient :: IndicatedAddress -> Word16 -> IO (Maybe (IndicatedAddress , IOCallbacks))
connectOnBehalfOfClient address port_number =
do
maybe_sock_addr <- case address of
IPv4_IA addr ->
return . Just $ NS.SockAddrInet (fromIntegral port_number) addr
DomainName_IA dn -> do
-- Let's try to connect on behalf of the client...
let
hints = NS.defaultHints {
NS.addrFlags = [NS.AI_ADDRCONFIG]
}
addrs <- E.catch
( NS.getAddrInfo (Just hints) (Just . unpack $ dn) Nothing )
((\_ -> return [])::E.IOException -> IO [NS.AddrInfo])
case addrs of
( first : _) -> do
return . Just $ NS.addrAddress first
_ ->
return Nothing
-- TODO: Implement other address formats
_ -> return Nothing
case maybe_sock_addr of
Just _sock_addr@(NS.SockAddrInet _ ha) -> do
E.catches
(do
client_socket <- NS.socket NS.AF_INET NS.Stream NS.defaultProtocol
let
translated_address = (NS.SockAddrInet (fromIntegral port_number) ha)
NS.connect client_socket translated_address
_is_connected <- NS.isConnected client_socket
_peer_name <- NS.getPeerName client_socket
socket_io_callbacks <- socketIOCallbacks client_socket
io_callbacks <- handshake socket_io_callbacks
return . Just $ (toSocks5Addr translated_address , io_callbacks)
)
[
E.Handler
(
(\_ -> do
return Nothing
)::E.IOException -> IO (Maybe (IndicatedAddress , IOCallbacks))
),
E.Handler
(
(\_ -> do
return Nothing
)::NoMoreDataException -> IO (Maybe (IndicatedAddress , IOCallbacks))
)
]
_ -> do
-- Temporary message
-- putStrLn "SOCKS5 could not be forwarded/address not resolved, or resolved to strange format"
return Nothing
toSocks5Addr:: NS.SockAddr -> IndicatedAddress
toSocks5Addr (NS.SockAddrInet _ ha) = IPv4_IA ha
toSocks5Addr _ = error "toSocks5Addr not fully implemented"
-- | Simple alias to SocketIOCallbacks where we expect
-- encrypted contents over a SOCKS5 Socket
data TLSServerSOCKS5Callbacks = TLSServerSOCKS5Callbacks {
_socket_S5 :: SocketIOCallbacks,
_targetAddress_S5 :: IndicatedAddress
}
makeLenses ''TLSServerSOCKS5Callbacks
-- type TLSServerSOCKS5AcceptResult = Either AcceptErrorCondition TLSServerSOCKS5Callbacks
instance IOChannels TLSServerSOCKS5Callbacks where
handshake s = handshake (s ^. socket_S5)
instance TLSEncryptedIO TLSServerSOCKS5Callbacks
instance TLSServerIO TLSServerSOCKS5Callbacks
instance HasSocketPeer TLSServerSOCKS5Callbacks where
getSocketPeerAddress s = getSocketPeerAddress (s ^. socket_S5)
-- | tlsSOCKS5Serve approver listening_socket onsocks5_action
-- The approver should return True for host names that are served by this software (otherwise the connection will be closed, just for now,
-- in the close future we will implement a way to forward requests to external Internet hosts.)
-- Pass a bound and listening TCP socket where you expect a SOCKS5 exchange to have to tke place.
-- And pass an action that can do something with the callbacks. The passed-in action is expected to fork a thread and return
-- inmediately.
tlsSOCKS5Serve' ::
MVar Socks5ServerState
-> Socks5ConnectionCallbacks
-> (B.ByteString -> Bool)
-> Bool
-> NS.Socket
-> ( Either AcceptErrorCondition TLSServerSOCKS5Callbacks -> IO () )
-> IO ()
tlsSOCKS5Serve' s5s_mvar socks5_callbacks approver forward_connections listen_socket onsocks5_action =
tcpServe listen_socket service_is_closing socks_action
where
service_is_closing = case socks5_callbacks ^. serviceIsClosing_S5CC of
Nothing -> return False
Just clbk -> clbk
socks_action either_condition_active_socket = do
_ <- forkIOExc "tlsSOCKS5Serve/negotiation" $
case either_condition_active_socket of
Left condition ->
process_condition condition
Right cc ->
process_connection cc
return ()
process_condition accept_condition = do
case (socks5_callbacks ^. logEvents_S5CC) of
Nothing -> return ()
Just lgfn -> lgfn $ AcceptCondition_S5Ev accept_condition
onsocks5_action $ Left accept_condition
process_connection active_socket = do
conn_id <- modifyMVar s5s_mvar $ \ s5s -> do
let
conn_id = s5s ^. nextConnection_S5S
new_s5s = set nextConnection_S5S (conn_id + 1) s5s
return $ new_s5s `seq` (new_s5s, conn_id)
let
log_events_maybe = socks5_callbacks ^. logEvents_S5CC
log_event :: Socks5ConnectEvent -> IO ()
log_event ev = case log_events_maybe of
Nothing -> return ()
Just c -> c ev
wconn_id = S5ConnectionId conn_id
either_peer_address <- E.try (NS.getPeerName active_socket)
case either_peer_address :: Either E.IOException NS.SockAddr of
Left _e -> return ()
Right peer_address -> do
log_event $ Established_S5Ev peer_address wconn_id
socket_io_callbacks <- socketIOCallbacks active_socket
io_callbacks <- handshake socket_io_callbacks
E.catch
(do
maybe_negotiated_io <-
if forward_connections
then negotiateSocksForwardOrConnect approver io_callbacks
else negotiateSocksAndForward approver io_callbacks
case maybe_negotiated_io of
Connect_COF fate _negotiated_io address -> do
let
tls_server_socks5_callbacks = TLSServerSOCKS5Callbacks {
_socket_S5 = socket_io_callbacks,
_targetAddress_S5 = address
}
log_event $ HandlingHere_S5Ev fate wconn_id
onsocks5_action . Right $ tls_server_socks5_callbacks
Drop_COF fate -> do
log_event $ Dropped_S5Ev fate wconn_id
(io_callbacks ^. closeAction_IOC)
return ()
Forward_COF fate port -> do
-- TODO: More data needs to come here
-- Do not close
log_event $ ToExternal_S5Ev fate port wconn_id
return ()
)
(( \ _e -> do
log_event $ Dropped_S5Ev "Peer errored" wconn_id
(io_callbacks ^. closeAction_IOC)
):: NoMoreDataException -> IO () )
return ()
| shimmercat/second-transfer | hs-src/SecondTransfer/Socks5/Session.hs | bsd-3-clause | 19,315 | 0 | 34 | 8,438 | 3,029 | 1,533 | 1,496 | 312 | 9 |
module EnumFrom where
main :: Fay ()
main = do
forM_ [1..5] $ \i -> print i
forM_ (take 5 [1..]) $ \i -> print i
forM_ [1,3..9] $ \i -> print i
forM_ (take 3 [1,3..]) $ \i -> print i
| fpco/fay | tests/enumFrom.hs | bsd-3-clause | 200 | 0 | 11 | 59 | 129 | 65 | 64 | 7 | 1 |
module Options.Language where
import Types
languageOptions :: [Flag]
languageOptions =
[ flag { flagName = "-fconstraint-solver-iterations=⟨n⟩"
, flagDescription =
"*default: 4.* Set the iteration limit for the type-constraint "++
"solver. Typically one iteration suffices; so please "++
"yell if you find you need to set it higher than the default. "++
"Zero means infinity."
, flagType = DynamicFlag
}
, flag { flagName = "-freduction-depth=⟨n⟩"
, flagDescription =
"*default: 200.* Set the :ref:`limit for type simplification "++
"<undecidable-instances>`. Zero means infinity."
, flagType = DynamicFlag
}
, flag { flagName = "-fcontext-stack=⟨n⟩"
, flagDescription =
"Deprecated. Use ``-freduction-depth=⟨n⟩`` instead."
, flagType = DynamicFlag
}
, flag { flagName = "-fglasgow-exts"
, flagDescription =
"Deprecated. Enable most language extensions; "++
"see :ref:`options-language` for exactly which ones."
, flagType = DynamicFlag
, flagReverse = "-fno-glasgow-exts"
}
, flag { flagName = "-firrefutable-tuples"
, flagDescription = "Make tuple pattern matching irrefutable"
, flagType = DynamicFlag
, flagReverse = "-fno-irrefutable-tuples"
}
, flag { flagName = "-fpackage-trust"
, flagDescription =
"Enable :ref:`Safe Haskell <safe-haskell>` trusted package "++
"requirement for trustworthy modules."
, flagType = DynamicFlag
}
, flag { flagName = "-ftype-function-depth=⟨n⟩"
, flagDescription = "Deprecated. Use ``-freduction-depth=⟨n⟩`` instead."
, flagType = DynamicFlag
}
, flag { flagName = "-XAllowAmbiguousTypes"
, flagDescription =
"Allow the user to write :ref:`ambiguous types <ambiguity>`, and "++
"the type inference engine to infer them."
, flagType = DynamicFlag
, flagReverse = "-XNoAllowAmbiguousTypes"
, flagSince = "7.8.1"
}
, flag { flagName = "-XArrows"
, flagDescription =
"Enable :ref:`arrow notation <arrow-notation>` extension"
, flagType = DynamicFlag
, flagReverse = "-XNoArrows"
, flagSince = "6.8.1"
}
, flag { flagName = "-XApplicativeDo"
, flagDescription =
"Enable :ref:`Applicative do-notation desugaring <applicative-do>`"
, flagType = DynamicFlag
, flagReverse = "-XNoApplicativeDo"
, flagSince = "8.0.1"
}
, flag { flagName = "-XAutoDeriveTypeable"
, flagDescription =
"As of GHC 7.10, this option is not needed, and should not be "++
"used. Previously this would automatically :ref:`derive Typeable "++
"instances for every datatype and type class declaration "++
"<deriving-typeable>`. Implies :ghc-flag:`-XDeriveDataTypeable`."
, flagType = DynamicFlag
, flagReverse = "-XNoAutoDeriveTypeable"
, flagSince = "7.8.1"
}
, flag { flagName = "-XBangPatterns"
, flagDescription = "Enable :ref:`bang patterns <bang-patterns>`."
, flagType = DynamicFlag
, flagReverse = "-XNoBangPatterns"
, flagSince = "6.8.1"
}
, flag { flagName = "-XBinaryLiterals"
, flagDescription =
"Enable support for :ref:`binary literals <binary-literals>`."
, flagType = DynamicFlag
, flagReverse = "-XNoBinaryLiterals"
, flagSince = "7.10.1"
}
, flag { flagName = "-XCApiFFI"
, flagDescription =
"Enable :ref:`the CAPI calling convention <ffi-capi>`."
, flagType = DynamicFlag
, flagReverse = "-XNoCAPIFFI"
, flagSince = "7.10.1"
}
, flag { flagName = "-XConstrainedClassMethods"
, flagDescription =
"Enable :ref:`constrained class methods <class-method-types>`."
, flagType = DynamicFlag
, flagReverse = "-XNoConstrainedClassMethods"
, flagSince = "6.8.1"
}
, flag { flagName = "-XConstraintKinds"
, flagDescription =
"Enable a :ref:`kind of constraints <constraint-kind>`."
, flagType = DynamicFlag
, flagReverse = "-XNoConstraintKinds"
, flagSince = "7.4.1"
}
, flag { flagName = "-XCPP"
, flagDescription =
"Enable the :ref:`C preprocessor <c-pre-processor>`."
, flagType = DynamicFlag
, flagReverse = "-XNoCPP"
, flagSince = "6.8.1"
}
, flag { flagName = "-XDataKinds"
, flagDescription = "Enable :ref:`datatype promotion <promotion>`."
, flagType = DynamicFlag
, flagReverse = "-XNoDataKinds"
, flagSince = "7.4.1"
}
, flag { flagName = "-XDefaultSignatures"
, flagDescription =
"Enable :ref:`default signatures <class-default-signatures>`."
, flagType = DynamicFlag
, flagReverse = "-XNoDefaultSignatures"
, flagSince = "7.2.1"
}
, flag { flagName = "-XDeriveAnyClass"
, flagDescription =
"Enable :ref:`deriving for any class <derive-any-class>`."
, flagType = DynamicFlag
, flagReverse = "-XNoDeriveAnyClass"
, flagSince = "7.10.1"
}
, flag { flagName = "-XDeriveDataTypeable"
, flagDescription =
"Enable ``deriving`` for the :ref:`Data class "++
"<deriving-typeable>`. Implied by :ghc-flag:`-XAutoDeriveTypeable`."
, flagType = DynamicFlag
, flagReverse = "-XNoDeriveDataTypeable"
, flagSince = "6.8.1"
}
, flag { flagName = "-XDeriveFunctor"
, flagDescription =
"Enable :ref:`deriving for the Functor class <deriving-extra>`. "++
"Implied by :ghc-flag:`-XDeriveTraversable`."
, flagType = DynamicFlag
, flagReverse = "-XNoDeriveFunctor"
, flagSince = "7.10.1"
}
, flag { flagName = "-XDeriveFoldable"
, flagDescription =
"Enable :ref:`deriving for the Foldable class <deriving-extra>`. "++
"Implied by :ghc-flag:`-XDeriveTraversable`."
, flagType = DynamicFlag
, flagReverse = "-XNoDeriveFoldable"
, flagSince = "7.10.1"
}
, flag { flagName = "-XDeriveGeneric"
, flagDescription =
"Enable :ref:`deriving for the Generic class <deriving-typeable>`."
, flagType = DynamicFlag
, flagReverse = "-XNoDeriveGeneric"
, flagSince = "7.2.1"
}
, flag { flagName = "-XDeriveGeneric"
, flagDescription =
"Enable :ref:`deriving for the Generic class <deriving-typeable>`."
, flagType = DynamicFlag
, flagReverse = "-XNoDeriveGeneric"
, flagSince = "7.2.1"
}
, flag { flagName = "-XDeriveLift"
, flagDescription =
"Enable :ref:`deriving for the Lift class <deriving-lift>`"
, flagType = DynamicFlag
, flagReverse = "-XNoDeriveLift"
, flagSince = "7.2.1"
}
, flag { flagName = "-XDeriveTraversable"
, flagDescription =
"Enable :ref:`deriving for the Traversable class <deriving-extra>`. "++
"Implies :ghc-flag:`-XDeriveFunctor` and :ghc-flag:`-XDeriveFoldable`."
, flagType = DynamicFlag
, flagReverse = "-XNoDeriveTraversable"
, flagSince = "7.10.1"
}
, flag { flagName = "-XDerivingStrategies"
, flagDescription =
"Enables :ref:`deriving strategies <deriving-strategies>`."
, flagType = DynamicFlag
, flagReverse = "-XNoDerivingStrategies"
, flagSince = "8.2.1"
}
, flag { flagName = "-XDisambiguateRecordFields"
, flagDescription =
"Enable :ref:`record field disambiguation <disambiguate-fields>`. "++
"Implied by :ghc-flag:`-XRecordWildCards`."
, flagType = DynamicFlag
, flagReverse = "-XNoDisambiguateRecordFields"
, flagSince = "6.8.1"
}
, flag { flagName = "-XEmptyCase"
, flagDescription =
"Allow :ref:`empty case alternatives <empty-case>`."
, flagType = DynamicFlag
, flagReverse = "-XNoEmptyCase"
, flagSince = "7.8.1"
}
, flag { flagName = "-XEmptyDataDecls"
, flagDescription = "Enable empty data declarations."
, flagType = DynamicFlag
, flagReverse = "-XNoEmptyDataDecls"
, flagSince = "6.8.1"
}
, flag { flagName = "-XExistentialQuantification"
, flagDescription =
"Enable :ref:`existential quantification <existential-quantification>`."
, flagType = DynamicFlag
, flagReverse = "-XNoExistentialQuantification"
, flagSince = "6.8.1"
}
, flag { flagName = "-XExplicitForAll"
, flagDescription =
"Enable :ref:`explicit universal quantification <explicit-foralls>`."++
" Implied by :ghc-flag:`-XScopedTypeVariables`, :ghc-flag:`-XLiberalTypeSynonyms`,"++
" :ghc-flag:`-XRankNTypes` and :ghc-flag:`-XExistentialQuantification`."
, flagType = DynamicFlag
, flagReverse = "-XNoExplicitForAll"
, flagSince = "6.12.1"
}
, flag { flagName = "-XExplicitNamespaces"
, flagDescription =
"Enable using the keyword ``type`` to specify the namespace of "++
"entries in imports and exports (:ref:`explicit-namespaces`). "++
"Implied by :ghc-flag:`-XTypeOperators` and :ghc-flag:`-XTypeFamilies`."
, flagType = DynamicFlag
, flagReverse = "-XNoExplicitNamespaces"
, flagSince = "7.6.1"
}
, flag { flagName = "-XExtendedDefaultRules"
, flagDescription =
"Use GHCi's :ref:`extended default rules <extended-default-rules>` "++
"in a normal module."
, flagType = DynamicFlag
, flagReverse = "-XNoExtendedDefaultRules"
, flagSince = "6.8.1"
}
, flag { flagName = "-XFlexibleContexts"
, flagDescription =
"Enable :ref:`flexible contexts <flexible-contexts>`. Implied by "++
":ghc-flag:`-XImplicitParams`."
, flagType = DynamicFlag
, flagReverse = "-XNoFlexibleContexts"
, flagSince = "6.8.1"
}
, flag { flagName = "-XFlexibleInstances"
, flagDescription =
"Enable :ref:`flexible instances <instance-rules>`. "++
"Implies :ghc-flag:`-XTypeSynonymInstances`. "++
"Implied by :ghc-flag:`-XImplicitParams`."
, flagType = DynamicFlag
, flagReverse = "-XNoFlexibleInstances"
, flagSince = "6.8.1"
}
, flag { flagName = "-XForeignFunctionInterface"
, flagDescription =
"Enable :ref:`foreign function interface <ffi>`."
, flagType = DynamicFlag
, flagReverse = "-XNoForeignFunctionInterface"
, flagSince = "6.8.1"
}
, flag { flagName = "-XFunctionalDependencies"
, flagDescription =
"Enable :ref:`functional dependencies <functional-dependencies>`. "++
"Implies :ghc-flag:`-XMultiParamTypeClasses`."
, flagType = DynamicFlag
, flagReverse = "-XNoFunctionalDependencies"
, flagSince = "6.8.1"
}
, flag { flagName = "-XGADTs"
, flagDescription =
"Enable :ref:`generalised algebraic data types <gadt>`. "++
"Implies :ghc-flag:`-XGADTSyntax` and :ghc-flag:`-XMonoLocalBinds`."
, flagType = DynamicFlag
, flagReverse = "-XNoGADTs"
, flagSince = "6.8.1"
}
, flag { flagName = "-XGADTSyntax"
, flagDescription =
"Enable :ref:`generalised algebraic data type syntax <gadt-style>`."
, flagType = DynamicFlag
, flagReverse = "-XNoGADTSyntax"
, flagSince = "7.2.1"
}
, flag { flagName = "-XGeneralizedNewtypeDeriving"
, flagDescription =
"Enable :ref:`newtype deriving <newtype-deriving>`."
, flagType = DynamicFlag
, flagReverse = "-XNoGeneralizedNewtypeDeriving"
, flagSince = "6.8.1"
}
, flag { flagName = "-XGenerics"
, flagDescription =
"Deprecated, does nothing. No longer enables "++
":ref:`generic classes <generic-classes>`. See also GHC's support "++
"for :ref:`generic programming <generic-programming>`."
, flagType = DynamicFlag
, flagReverse = "-XNoGenerics"
, flagSince = "6.8.1"
}
, flag { flagName = "-XImplicitParams"
, flagDescription =
"Enable :ref:`Implicit Parameters <implicit-parameters>`. "++
"Implies :ghc-flag:`-XFlexibleContexts` and :ghc-flag:`-XFlexibleInstances`."
, flagType = DynamicFlag
, flagReverse = "-XNoImplicitParams"
, flagSince = "6.8.1"
}
, flag { flagName = "-XNoImplicitPrelude"
, flagDescription =
"Don't implicitly ``import Prelude``. "++
"Implied by :ghc-flag:`-XRebindableSyntax`."
, flagType = DynamicFlag
, flagReverse = "-XImplicitPrelude"
, flagSince = "6.8.1"
}
, flag { flagName = "-XImpredicativeTypes"
, flagDescription =
"Enable :ref:`impredicative types <impredicative-polymorphism>`. "++
"Implies :ghc-flag:`-XRankNTypes`."
, flagType = DynamicFlag
, flagReverse = "-XNoImpredicativeTypes"
, flagSince = "6.10.1"
}
, flag { flagName = "-XIncoherentInstances"
, flagDescription =
"Enable :ref:`incoherent instances <instance-overlap>`. "++
"Implies :ghc-flag:`-XOverlappingInstances`."
, flagType = DynamicFlag
, flagReverse = "-XNoIncoherentInstances"
, flagSince = "6.8.1"
}
, flag { flagName = "-XTypeFamilyDependencies"
, flagDescription =
"Enable :ref:`injective type families <injective-ty-fams>`. "++
"Implies :ghc-flag:`-XTypeFamilies`."
, flagType = DynamicFlag
, flagReverse = "-XNoTypeFamilyDependencies"
, flagSince = "8.0.1"
}
, flag { flagName = "-XInstanceSigs"
, flagDescription =
"Enable :ref:`instance signatures <instance-sigs>`."
, flagType = DynamicFlag
, flagReverse = "-XNoInstanceSigs"
, flagSince = "7.10.1"
}
, flag { flagName = "-XInterruptibleFFI"
, flagDescription = "Enable interruptible FFI."
, flagType = DynamicFlag
, flagReverse = "-XNoInterruptibleFFI"
, flagSince = "7.2.1"
}
, flag { flagName = "-XKindSignatures"
, flagDescription =
"Enable :ref:`kind signatures <kinding>`. "++
"Implied by :ghc-flag:`-XTypeFamilies` and :ghc-flag:`-XPolyKinds`."
, flagType = DynamicFlag
, flagReverse = "-XNoKindSignatures"
, flagSince = "6.8.1"
}
, flag { flagName = "-XLambdaCase"
, flagDescription =
"Enable :ref:`lambda-case expressions <lambda-case>`."
, flagType = DynamicFlag
, flagReverse = "-XNoLambdaCase"
, flagSince = "7.6.1"
}
, flag { flagName = "-XLiberalTypeSynonyms"
, flagDescription =
"Enable :ref:`liberalised type synonyms <type-synonyms>`."
, flagType = DynamicFlag
, flagReverse = "-XNoLiberalTypeSynonyms"
, flagSince = "6.8.1"
}
, flag { flagName = "-XMagicHash"
, flagDescription =
"Allow ``#`` as a :ref:`postfix modifier on identifiers <magic-hash>`."
, flagType = DynamicFlag
, flagReverse = "-XNoMagicHash"
, flagSince = "6.8.1"
}
, flag { flagName = "-XMonadComprehensions"
, flagDescription =
"Enable :ref:`monad comprehensions <monad-comprehensions>`."
, flagType = DynamicFlag
, flagReverse = "-XNoMonadComprehensions"
, flagSince = "7.2.1"
}
, flag { flagName = "-XMonoLocalBinds"
, flagDescription =
"Enable :ref:`do not generalise local bindings <mono-local-binds>`. "++
"Implied by :ghc-flag:`-XTypeFamilies` and :ghc-flag:`-XGADTs`."
, flagType = DynamicFlag
, flagReverse = "-XNoMonoLocalBinds"
, flagSince = "6.12.1"
}
, flag { flagName = "-XNoMonomorphismRestriction"
, flagDescription =
"Disable the :ref:`monomorphism restriction <monomorphism>`."
, flagType = DynamicFlag
, flagReverse = "-XMonomorphismRestriction"
, flagSince = "6.8.1"
}
, flag { flagName = "-XMultiParamTypeClasses"
, flagDescription =
"Enable :ref:`multi parameter type classes "++
"<multi-param-type-classes>`. Implied by "++
":ghc-flag:`-XFunctionalDependencies`."
, flagType = DynamicFlag
, flagReverse = "-XNoMultiParamTypeClasses"
, flagSince = "6.8.1"
}
, flag { flagName = "-XMultiWayIf"
, flagDescription =
"Enable :ref:`multi-way if-expressions <multi-way-if>`."
, flagType = DynamicFlag
, flagReverse = "-XNoMultiWayIf"
, flagSince = "7.6.1"
}
, flag { flagName = "-XNamedFieldPuns"
, flagDescription = "Enable :ref:`record puns <record-puns>`."
, flagType = DynamicFlag
, flagReverse = "-XNoNamedFieldPuns"
, flagSince = "6.10.1"
}
, flag { flagName = "-XNamedWildCards"
, flagDescription = "Enable :ref:`named wildcards <named-wildcards>`."
, flagType = DynamicFlag
, flagReverse = "-XNoNamedWildCards"
, flagSince = "7.10.1"
}
, flag { flagName = "-XNegativeLiterals"
, flagDescription =
"Enable support for :ref:`negative literals <negative-literals>`."
, flagType = DynamicFlag
, flagReverse = "-XNoNegativeLiterals"
, flagSince = "7.8.1"
}
, flag { flagName = "-XNPlusKPatterns"
, flagDescription = "Enable support for ``n+k`` patterns. "++
"Implied by :ghc-flag:`-XHaskell98`."
, flagType = DynamicFlag
, flagReverse = "-XNoNPlusKPatterns"
, flagSince = "6.12.1"
}
, flag { flagName = "-XNullaryTypeClasses"
, flagDescription =
"Deprecated, does nothing. :ref:`nullary (no parameter) type "++
"classes <nullary-type-classes>` are now enabled using "++
":ghc-flag:`-XMultiParamTypeClasses`."
, flagType = DynamicFlag
, flagReverse = "-XNoNullaryTypeClasses"
, flagSince = "7.8.1"
}
, flag { flagName = "-XNumDecimals"
, flagDescription =
"Enable support for 'fractional' integer literals."
, flagType = DynamicFlag
, flagReverse = "-XNoNumDecimals"
, flagSince = "7.8.1"
}
, flag { flagName = "-XOverlappingInstances"
, flagDescription =
"Enable :ref:`overlapping instances <instance-overlap>`."
, flagType = DynamicFlag
, flagReverse = "-XNoOverlappingInstances"
, flagSince = "6.8.1"
}
, flag { flagName = "-XOverloadedLists"
, flagDescription =
"Enable :ref:`overloaded lists <overloaded-lists>`."
, flagType = DynamicFlag
, flagReverse = "-XNoOverloadedLists"
, flagSince = "7.8.1"
}
, flag { flagName = "-XOverloadedStrings"
, flagDescription =
"Enable :ref:`overloaded string literals <overloaded-strings>`."
, flagType = DynamicFlag
, flagReverse = "-XNoOverloadedStrings"
, flagSince = "6.8.1"
}
, flag { flagName = "-XPackageImports"
, flagDescription =
"Enable :ref:`package-qualified imports <package-imports>`."
, flagType = DynamicFlag
, flagReverse = "-XNoPackageImports"
, flagSince = "6.10.1"
}
, flag { flagName = "-XParallelArrays"
, flagDescription =
"Enable parallel arrays. Implies :ghc-flag:`-XParallelListComp`."
, flagType = DynamicFlag
, flagReverse = "-XNoParallelArrays"
, flagSince = "7.4.1"
}
, flag { flagName = "-XParallelListComp"
, flagDescription =
"Enable :ref:`parallel list comprehensions "++
"<parallel-list-comprehensions>`. "++
"Implied by :ghc-flag:`-XParallelArrays`."
, flagType = DynamicFlag
, flagReverse = "-XNoParallelListComp"
, flagSince = "6.8.1"
}
, flag { flagName = "-XPartialTypeSignatures"
, flagDescription =
"Enable :ref:`partial type signatures <partial-type-signatures>`."
, flagType = DynamicFlag
, flagReverse = "-XNoPartialTypeSignatures"
, flagSince = "7.10.1"
}
, flag { flagName = "-XNoPatternGuards"
, flagDescription = "Disable :ref:`pattern guards <pattern-guards>`. "++
"Implied by :ghc-flag:`-XHaskell98`."
, flagType = DynamicFlag
, flagReverse = "-XPatternGuards"
, flagSince = "6.8.1"
}
, flag { flagName = "-XPatternSynonyms"
, flagDescription =
"Enable :ref:`pattern synonyms <pattern-synonyms>`."
, flagType = DynamicFlag
, flagReverse = "-XNoPatternSynonyms"
, flagSince = "7.10.1"
}
, flag { flagName = "-XPolyKinds"
, flagDescription =
"Enable :ref:`kind polymorphism <kind-polymorphism>`. "++
"Implies :ghc-flag:`-XKindSignatures`."
, flagType = DynamicFlag
, flagReverse = "-XNoPolyKinds"
, flagSince = "7.4.1"
}
, flag { flagName = "-XPolymorphicComponents"
, flagDescription =
"Enable :ref:`polymorphic components for data constructors "++
"<universal-quantification>`. Synonym for :ghc-flag:`-XRankNTypes`."
, flagType = DynamicFlag
, flagReverse = "-XNoPolymorphicComponents"
, flagSince = "6.8.1"
}
, flag { flagName = "-XPostfixOperators"
, flagDescription =
"Enable :ref:`postfix operators <postfix-operators>`."
, flagType = DynamicFlag
, flagReverse = "-XNoPostfixOperators"
, flagSince = "7.10.1"
}
, flag { flagName = "-XQuasiQuotes"
, flagDescription = "Enable :ref:`quasiquotation <th-quasiquotation>`."
, flagType = DynamicFlag
, flagReverse = "-XNoQuasiQuotes"
, flagSince = "6.10.1"
}
, flag { flagName = "-XRank2Types"
, flagDescription =
"Enable :ref:`rank-2 types <universal-quantification>`. "++
"Synonym for :ghc-flag:`-XRankNTypes`."
, flagType = DynamicFlag
, flagReverse = "-XNoRank2Types"
, flagSince = "6.8.1"
}
, flag { flagName = "-XRankNTypes"
, flagDescription =
"Enable :ref:`rank-N types <universal-quantification>`. "++
"Implied by :ghc-flag:`-XImpredicativeTypes`."
, flagType = DynamicFlag
, flagReverse = "-XNoRankNTypes"
, flagSince = "6.8.1"
}
, flag { flagName = "-XRebindableSyntax"
, flagDescription =
"Employ :ref:`rebindable syntax <rebindable-syntax>`. "++
"Implies :ghc-flag:`-XNoImplicitPrelude`."
, flagType = DynamicFlag
, flagReverse = "-XNoRebindableSyntax"
, flagSince = "7.0.1"
}
, flag { flagName = "-XRecordWildCards"
, flagDescription =
"Enable :ref:`record wildcards <record-wildcards>`. "++
"Implies :ghc-flag:`-XDisambiguateRecordFields`."
, flagType = DynamicFlag
, flagReverse = "-XNoRecordWildCards"
, flagSince = "6.8.1"
}
, flag { flagName = "-XRecursiveDo"
, flagDescription =
"Enable :ref:`recursive do (mdo) notation <recursive-do-notation>`."
, flagType = DynamicFlag
, flagReverse = "-XNoRecursiveDo"
, flagSince = "6.8.1"
}
, flag { flagName = "-XRoleAnnotations"
, flagDescription =
"Enable :ref:`role annotations <role-annotations>`."
, flagType = DynamicFlag
, flagReverse = "-XNoRoleAnnotations"
, flagSince = "7.10.1"
}
, flag { flagName = "-XSafe"
, flagDescription =
"Enable the :ref:`Safe Haskell <safe-haskell>` Safe mode."
, flagType = DynamicFlag
, flagSince = "7.2.1"
}
, flag { flagName = "-XScopedTypeVariables"
, flagDescription =
"Enable :ref:`lexically-scoped type variables "++
"<scoped-type-variables>`."
, flagType = DynamicFlag
, flagReverse = "-XNoScopedTypeVariables"
, flagSince = "6.8.1"
}
, flag { flagName = "-XStandaloneDeriving"
, flagDescription =
"Enable :ref:`standalone deriving <stand-alone-deriving>`."
, flagType = DynamicFlag
, flagReverse = "-XNoStandaloneDeriving"
, flagSince = "6.8.1"
}
, flag { flagName = "-XStaticPointers"
, flagDescription =
"Enable :ref:`static pointers <static-pointers>`."
, flagType = DynamicFlag
, flagReverse = "-XNoStaticPointers"
, flagSince = "7.10.1"
}
, flag { flagName = "-XStrictData"
, flagDescription =
"Enable :ref:`default strict datatype fields <strict-data>`."
, flagType = DynamicFlag
, flagReverse = "-XNoStrictData"
}
, flag { flagName = "-XTemplateHaskell"
, flagDescription =
"Enable :ref:`Template Haskell <template-haskell>`."
, flagType = DynamicFlag
, flagReverse = "-XNoTemplateHaskell"
, flagSince = "6.8.1"
}
, flag { flagName = "-XTemplateHaskellQuotes"
, flagDescription = "Enable quotation subset of "++
":ref:`Template Haskell <template-haskell>`."
, flagType = DynamicFlag
, flagReverse = "-XNoTemplateHaskellQuotes"
, flagSince = "8.0.1"
}
, flag { flagName = "-XNoTraditionalRecordSyntax"
, flagDescription =
"Disable support for traditional record syntax "++
"(as supported by Haskell 98) ``C {f = x}``"
, flagType = DynamicFlag
, flagReverse = "-XTraditionalRecordSyntax"
, flagSince = "7.4.1"
}
, flag { flagName = "-XTransformListComp"
, flagDescription =
"Enable :ref:`generalised list comprehensions "++
"<generalised-list-comprehensions>`."
, flagType = DynamicFlag
, flagReverse = "-XNoTransformListComp"
, flagSince = "6.10.1"
}
, flag { flagName = "-XTrustworthy"
, flagDescription =
"Enable the :ref:`Safe Haskell <safe-haskell>` Trustworthy mode."
, flagType = DynamicFlag
, flagSince = "7.2.1"
}
, flag { flagName = "-XTupleSections"
, flagDescription = "Enable :ref:`tuple sections <tuple-sections>`."
, flagType = DynamicFlag
, flagReverse = "-XNoTupleSections"
, flagSince = "7.10.1"
}
, flag { flagName = "-XTypeFamilies"
, flagDescription =
"Enable :ref:`type families <type-families>`. "++
"Implies :ghc-flag:`-XExplicitNamespaces`, :ghc-flag:`-XKindSignatures`, "++
"and :ghc-flag:`-XMonoLocalBinds`."
, flagType = DynamicFlag
, flagReverse = "-XNoTypeFamilies"
, flagSince = "6.8.1"
}
, flag { flagName = "-XTypeOperators"
, flagDescription =
"Enable :ref:`type operators <type-operators>`. "++
"Implies :ghc-flag:`-XExplicitNamespaces`."
, flagType = DynamicFlag
, flagReverse = "-XNoTypeOperators"
, flagSince = "6.8.1"
}
, flag { flagName = "-XTypeSynonymInstances"
, flagDescription =
"Enable :ref:`type synonyms in instance heads "++
"<flexible-instance-head>`. Implied by :ghc-flag:`-XFlexibleInstances`."
, flagType = DynamicFlag
, flagReverse = "-XNoTypeSynonymInstances"
, flagSince = "6.8.1"
}
, flag { flagName = "-XUnboxedTuples"
, flagDescription = "Enable :ref:`unboxed tuples <unboxed-tuples>`."
, flagType = DynamicFlag
, flagReverse = "-XNoUnboxedTuples"
, flagSince = "6.8.1"
}
, flag { flagName ="-XUnboxedSums"
, flagDescription = "Enable :ref: `unboxed sums <unboxed-sums>`."
, flagType = DynamicFlag
, flagReverse = "-XNoUnboxedSums"
, flagSince = "8.2.1"
}
, flag { flagName = "-XUndecidableInstances"
, flagDescription =
"Enable :ref:`undecidable instances <undecidable-instances>`."
, flagType = DynamicFlag
, flagReverse = "-XNoUndecidableInstances"
, flagSince = "6.8.1"
}
, flag { flagName = "-XUnicodeSyntax"
, flagDescription = "Enable :ref:`unicode syntax <unicode-syntax>`."
, flagType = DynamicFlag
, flagReverse = "-XNoUnicodeSyntax"
, flagSince = "6.8.1"
}
, flag { flagName = "-XUnliftedFFITypes"
, flagDescription = "Enable unlifted FFI types."
, flagType = DynamicFlag
, flagReverse = "-XNoUnliftedFFITypes"
, flagSince = "6.8.1"
}
, flag { flagName = "-XUnsafe"
, flagDescription =
"Enable :ref:`Safe Haskell <safe-haskell>` Unsafe mode."
, flagType = DynamicFlag
, flagSince = "7.4.1"
}
, flag { flagName = "-XViewPatterns"
, flagDescription = "Enable :ref:`view patterns <view-patterns>`."
, flagType = DynamicFlag
, flagReverse = "-XNoViewPatterns"
, flagSince = "6.10.1"
}
]
| olsner/ghc | utils/mkUserGuidePart/Options/Language.hs | bsd-3-clause | 30,401 | 0 | 10 | 9,447 | 3,825 | 2,477 | 1,348 | 656 | 1 |
{- $Id: AFRPTestsAccum.hs,v 1.2 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* A F R P *
* *
* Module: AFRPTestsAccum *
* Purpose: Test cases for accumulators *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* University of Nottingham, 2005 *
* *
******************************************************************************
-}
module AFRPTestsAccum (
accum_tr,
accum_trs,
accum_st0,
accum_st0r,
accum_st1,
accum_st1r
) where
import Data.Maybe (fromJust)
import FRP.Yampa
import FRP.Yampa.Internals (Event(NoEvent, Event))
import AFRPTestsCommon
------------------------------------------------------------------------------
-- Test cases for accumulators
------------------------------------------------------------------------------
accum_inp1 = (fromJust (head delta_inp), zip (repeat 1.0) (tail delta_inp))
where
delta_inp =
[Just NoEvent, Nothing, Just (Event (+1.0)), Just NoEvent,
Just (Event (+2.0)), Just NoEvent, Nothing, Nothing,
Just (Event (*3.0)), Just (Event (+5.0)), Nothing, Just NoEvent,
Just (Event (/2.0)), Just NoEvent, Nothing, Nothing]
++ repeat Nothing
accum_inp2 = (fromJust (head delta_inp), zip (repeat 1.0) (tail delta_inp))
where
delta_inp =
[Just (Event (+1.0)), Just NoEvent, Nothing, Nothing,
Just (Event (+2.0)), Just NoEvent, Nothing, Nothing,
Just (Event (*3.0)), Just (Event (+5.0)), Nothing, Just NoEvent,
Just (Event (/2.0)), Just NoEvent, Nothing, Nothing]
++ repeat Nothing
accum_inp3 = deltaEncode 1.0 $
[NoEvent, NoEvent, Event 1.0, NoEvent,
Event 2.0, NoEvent, NoEvent, NoEvent,
Event 3.0, Event 5.0, Event 5.0, NoEvent,
Event 0.0, NoEvent, NoEvent, NoEvent]
++ repeat NoEvent
accum_inp4 = deltaEncode 1.0 $
[Event 1.0, NoEvent, NoEvent, NoEvent,
Event 2.0, NoEvent, NoEvent, NoEvent,
Event 3.0, Event 5.0, Event 5.0, NoEvent,
Event 0.0, NoEvent, NoEvent, NoEvent]
++ repeat NoEvent
accum_inp5 = deltaEncode 0.25 (repeat ())
accum_t0 :: [Event Double]
accum_t0 = take 16 $ embed (accum 0.0) accum_inp1
accum_t0r =
[NoEvent, NoEvent, Event 1.0, NoEvent,
Event 3.0, NoEvent, NoEvent, NoEvent,
Event 9.0, Event 14.0, Event 19.0, NoEvent,
Event 9.5, NoEvent, NoEvent, NoEvent]
accum_t1 :: [Event Double]
accum_t1 = take 16 $ embed (accum 0.0) accum_inp2
accum_t1r =
[Event 1.0, NoEvent, NoEvent, NoEvent,
Event 3.0, NoEvent, NoEvent, NoEvent,
Event 9.0, Event 14.0, Event 19.0, NoEvent,
Event 9.5, NoEvent, NoEvent, NoEvent]
accum_t2 :: [Event Int]
accum_t2 = take 16 $ embed (accumBy (\a d -> a + floor d) 0) accum_inp3
accum_t2r :: [Event Int]
accum_t2r =
[NoEvent, NoEvent, Event 1, NoEvent,
Event 3, NoEvent, NoEvent, NoEvent,
Event 6, Event 11, Event 16, NoEvent,
Event 16, NoEvent, NoEvent, NoEvent]
accum_t3 :: [Event Int]
accum_t3 = take 16 $ embed (accumBy (\a d -> a + floor d) 0) accum_inp4
accum_t3r :: [Event Int]
accum_t3r =
[Event 1, NoEvent, NoEvent, NoEvent,
Event 3, NoEvent, NoEvent, NoEvent,
Event 6, Event 11, Event 16, NoEvent,
Event 16, NoEvent, NoEvent, NoEvent]
accum_accFiltFun1 a d =
let a' = a + floor d
in
if even a' then
(a', Just (a' > 10, a'))
else
(a', Nothing)
accum_t4 :: [Event (Bool,Int)]
accum_t4 = take 16 $ embed (accumFilter accum_accFiltFun1 0) accum_inp3
accum_t4r :: [Event (Bool,Int)]
accum_t4r =
[NoEvent, NoEvent, NoEvent, NoEvent,
NoEvent, NoEvent, NoEvent, NoEvent,
Event (False,6), NoEvent, Event (True,16), NoEvent,
Event (True,16), NoEvent, NoEvent, NoEvent]
accum_accFiltFun2 a d =
let a' = a + floor d
in
if odd a' then
(a', Just (a' > 10, a'))
else
(a', Nothing)
accum_t5 :: [Event (Bool,Int)]
accum_t5 = take 16 $ embed (accumFilter accum_accFiltFun2 0) accum_inp4
accum_t5r :: [Event (Bool,Int)]
accum_t5r =
[Event (False,1), NoEvent, NoEvent, NoEvent,
Event (False,3), NoEvent, NoEvent, NoEvent,
NoEvent, Event (True,11), NoEvent, NoEvent,
NoEvent, NoEvent, NoEvent, NoEvent]
-- This can be seen as the definition of accumFilter
accumFilter2 :: (c -> a -> (c, Maybe b)) -> c -> SF (Event a) (Event b)
accumFilter2 f c_init =
switch (never &&& attach c_init) afAux
where
afAux (c, a) =
case f c a of
(c', Nothing) -> switch (never &&& (notYet>>>attach c')) afAux
(c', Just b) -> switch (now b &&& (notYet>>>attach c')) afAux
attach :: b -> SF (Event a) (Event (b, a))
attach c = arr (fmap (\a -> (c, a)))
accum_t6 :: [Event (Bool,Int)]
accum_t6 = take 16 $ embed (accumFilter2 accum_accFiltFun1 0) accum_inp3
accum_t6r = accum_t4 -- Should agree!
accum_t7 :: [Event (Bool,Int)]
accum_t7 = take 16 $ embed (accumFilter2 accum_accFiltFun2 0) accum_inp4
accum_t7r = accum_t5 -- Should agree!
accum_t8 :: [Event Int]
accum_t8 = take 40 $ embed (repeatedly 1.0 1
>>> accumBy (+) 0
>>> accumBy (+) 0)
accum_inp5
accum_t8r :: [Event Int]
accum_t8r = [NoEvent, NoEvent, NoEvent, NoEvent,
Event 1, NoEvent, NoEvent, NoEvent,
Event 3, NoEvent, NoEvent, NoEvent,
Event 6, NoEvent, NoEvent, NoEvent,
Event 10, NoEvent, NoEvent, NoEvent,
Event 15, NoEvent, NoEvent, NoEvent,
Event 21, NoEvent, NoEvent, NoEvent,
Event 28, NoEvent, NoEvent, NoEvent,
Event 36, NoEvent, NoEvent, NoEvent,
Event 45, NoEvent, NoEvent, NoEvent]
accum_t9 :: [Int]
accum_t9 = take 40 $ embed (repeatedly 1.0 1
>>> accumBy (+) 0
>>> accumBy (+) 0
>>> hold 0)
accum_inp5
accum_t9r :: [Int]
accum_t9r = [0,0,0,0,1,1,1,1,3,3,3,3,6,6,6,6,10,10,10,10,15,15,15,15,
21,21,21,21,28,28,28,28,36,36,36,36,45,45,45,45]
accum_t10 :: [Int]
accum_t10 = take 40 $ embed (repeatedly 1.0 1
>>> accumBy (+) 0
>>> accumHoldBy (+) 0)
accum_inp5
accum_t10r :: [Int]
accum_t10r = accum_t9 -- Should agree!
accum_t11 :: [Int]
accum_t11 = take 40 $ embed (repeatedly 1.0 1
>>> accumBy (+) 0
>>> accumBy (+) 0
>>> dHold 0)
accum_inp5
accum_t11r :: [Int]
accum_t11r = [0,0,0,0,0,1,1,1,1,3,3,3,3,6,6,6,6,10,10,10,10,15,15,15,
15,21,21,21,21,28,28,28,28,36,36,36,36,45,45,45]
accum_t12 :: [Int]
accum_t12 = take 40 $ embed (repeatedly 1.0 1
>>> accumBy (+) 0
>>> dAccumHoldBy (+) 0)
accum_inp5
accum_t12r :: [Int]
accum_t12r = accum_t11 -- Should agree!
accum_accFiltFun3 :: Int -> Int -> (Int, Maybe Int)
accum_accFiltFun3 s a =
let s' = s + a
in
if odd s' then
(s', Just s')
else
(s', Nothing)
accum_t13 :: [Event Int]
accum_t13 = take 40 $ embed (repeatedly 1.0 1
>>> accumFilter accum_accFiltFun3 0
>>> accumBy (+) 0
>>> accumBy (+) 0)
accum_inp5
accum_t13r :: [Event Int]
accum_t13r = [NoEvent, NoEvent, NoEvent, NoEvent,
Event 1, NoEvent, NoEvent, NoEvent,
NoEvent, NoEvent, NoEvent, NoEvent,
Event 5, NoEvent, NoEvent, NoEvent,
NoEvent, NoEvent, NoEvent, NoEvent,
Event 14, NoEvent, NoEvent, NoEvent,
NoEvent, NoEvent, NoEvent, NoEvent,
Event 30, NoEvent, NoEvent, NoEvent,
NoEvent, NoEvent, NoEvent, NoEvent,
Event 55, NoEvent, NoEvent, NoEvent]
accum_t14 :: [Int]
accum_t14 = take 40 $ embed (repeatedly 1.0 1
>>> accumFilter accum_accFiltFun3 0
>>> accumBy (+) 0
>>> accumBy (+) 0
>>> hold 0)
accum_inp5
accum_t14r :: [Int]
accum_t14r = [0,0,0,0,1,1,1,1,1,1,1,1,5,5,5,5,5,5,5,5,14,14,14,14,
14,14,14,14,30,30,30,30,30,30,30,30,55,55,55,55]
accum_t15 :: [Int]
accum_t15 = take 40 $ embed (repeatedly 1.0 1
>>> accumFilter accum_accFiltFun3 0
>>> accumBy (+) 0
>>> accumHoldBy (+) 0)
accum_inp5
accum_t15r :: [Int]
accum_t15r = accum_t14 -- Should agree!
accum_t16 :: [Int]
accum_t16 = take 40 $ embed (repeatedly 1.0 1
>>> accumFilter accum_accFiltFun3 0
>>> accumBy (+) 0
>>> accumBy (+) 0
>>> dHold 0)
accum_inp5
accum_t16r :: [Int]
accum_t16r = [0,0,0,0,0,1,1,1,1,1,1,1,1,5,5,5,5,5,5,5,5,14,14,14,
14,14,14,14,14,30,30,30,30,30,30,30,30,55,55,55]
accum_t17 :: [Int]
accum_t17 = take 40 $ embed (repeatedly 1.0 1
>>> accumFilter accum_accFiltFun3 0
>>> accumBy (+) 0
>>> dAccumHoldBy (+) 0)
accum_inp5
accum_t17r :: [Int]
accum_t17r = accum_t16 -- Should agree!
accum_trs =
[ accum_t0 == accum_t0r,
accum_t1 == accum_t1r,
accum_t2 == accum_t2r,
accum_t3 == accum_t3r,
accum_t4 == accum_t4r,
accum_t5 == accum_t5r,
accum_t6 == accum_t6r,
accum_t7 == accum_t7r,
accum_t8 == accum_t8r,
accum_t9 == accum_t9r,
accum_t10 == accum_t10r,
accum_t11 == accum_t11r,
accum_t12 == accum_t12r,
accum_t13 == accum_t13r,
accum_t14 == accum_t14r,
accum_t15 == accum_t15r,
accum_t16 == accum_t16r,
accum_t17 == accum_t17r
]
accum_tr = and accum_trs
accum_st0 :: Double
accum_st0 = testSFSpaceLeak 1000000
(repeatedly 1.0 1.0
>>> accumBy (+) 0.0
>>> hold (-99.99))
accum_st0r = 249999.0
accum_st1 :: Double
accum_st1 = testSFSpaceLeak 1000000
(arr dup
>>> first (repeatedly 1.0 1.0)
>>> arr (\(e,a) -> tag e a)
>>> accumFilter accumFun 0.0
>>> hold (-99.99))
where
accumFun c a | even (floor a) = (c+a, Just (c+a))
| otherwise = (c, Nothing)
accum_st1r = 6.249975e10
| ony/Yampa-core | tests/AFRPTestsAccum.hs | bsd-3-clause | 11,437 | 28 | 15 | 4,076 | 3,799 | 2,152 | 1,647 | 252 | 2 |
-- | Simple example of storing a file on a server using Haste.App.
-- Please remember to never, ever, use unsanitized file names received from
-- a client on the server, as is done in this example!
import Haste.App
import Haste.Binary
import Haste.DOM
import Haste.Events
import qualified Data.ByteString.Lazy as BS
main = runApp defaultConfig $ do
upload <- remote $ \name file -> do
filedata <- getBlobData file
liftIO $ BS.writeFile name (toByteString filedata)
runClient $ withElems ["file","upload"] $ \[file,btn] -> do
btn `onEvent` Click $ \_ -> do
mfd <- getFileData file 0
case mfd of
Just fd -> do
fn <- getFileName file
onServer $ upload <.> fn <.> fd
alert "File uploaded!"
_ -> do
alert "You need to specify a file first."
return ()
| beni55/haste-compiler | examples/sendfile/sendfile.hs | bsd-3-clause | 840 | 0 | 23 | 222 | 221 | 110 | 111 | 20 | 2 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TypeSynonymInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.FixedColumn
-- Copyright : (c) 2008 Justin Bogner <[email protected]>
-- License : BSD3-style (as xmonad)
--
-- Maintainer : Justin Bogner <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- A layout much like Tall, but using a multiple of a window's minimum
-- resize amount instead of a percentage of screen to decide where to
-- split. This is useful when you usually leave a text editor or
-- terminal in the master pane and like it to be 80 columns wide.
--
-----------------------------------------------------------------------------
module XMonad.Layout.FixedColumn (
-- * Usage
-- $usage
FixedColumn(..)
) where
import Control.Monad (msum)
import Data.Maybe (fromMaybe)
import Graphics.X11.Xlib (Window, rect_width)
import Graphics.X11.Xlib.Extras ( getWMNormalHints
, getWindowAttributes
, sh_base_size
, sh_resize_inc
, wa_border_width)
import XMonad.Core (X, LayoutClass(..), fromMessage, io, withDisplay)
import XMonad.Layout (Resize(..), IncMasterN(..), tile)
import XMonad.StackSet as W
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Layout.FixedColumn
--
-- Then edit your @layoutHook@ by adding the FixedColumn layout:
--
-- > myLayout = FixedColumn 1 20 80 10 ||| Full ||| etc..
-- > main = xmonad defaultConfig { layoutHook = myLayout }
--
-- For more detailed instructions on editing the layoutHook see:
--
-- "XMonad.Doc.Extending#Editing_the_layout_hook"
-- | A tiling mode based on preserving a nice fixed width
-- window. Supports 'Shrink', 'Expand' and 'IncMasterN'.
data FixedColumn a = FixedColumn !Int -- Number of windows in the master pane
!Int -- Number to increment by when resizing
!Int -- Default width of master pane
!Int -- Column width for normal windows
deriving (Read, Show)
instance LayoutClass FixedColumn Window where
doLayout (FixedColumn nmaster _ ncol fallback) r s = do
fws <- mapM (widthCols fallback ncol) ws
let frac = maximum (take nmaster fws) // rect_width r
rs = tile frac r nmaster (length ws)
return $ (zip ws rs, Nothing)
where ws = W.integrate s
x // y = fromIntegral x / fromIntegral y
pureMessage (FixedColumn nmaster delta ncol fallback) m =
msum [fmap resize (fromMessage m)
,fmap incmastern (fromMessage m)]
where resize Shrink
= FixedColumn nmaster delta (max 0 $ ncol - delta) fallback
resize Expand
= FixedColumn nmaster delta (ncol + delta) fallback
incmastern (IncMasterN d)
= FixedColumn (max 0 (nmaster+d)) delta ncol fallback
description _ = "FixedColumn"
-- | Determine the width of @w@ given that we would like it to be @n@
-- columns wide, using @inc@ as a resize increment for windows that
-- don't have one
widthCols :: Int -> Int -> Window -> X Int
widthCols inc n w = withDisplay $ \d -> io $ do
sh <- getWMNormalHints d w
bw <- fmap (fromIntegral . wa_border_width) $ getWindowAttributes d w
let widthHint f = f sh >>= return . fromIntegral . fst
oneCol = fromMaybe inc $ widthHint sh_resize_inc
base = fromMaybe 0 $ widthHint sh_base_size
return $ 2 * bw + base + n * oneCol
| adinapoli/xmonad-contrib | XMonad/Layout/FixedColumn.hs | bsd-3-clause | 3,802 | 0 | 16 | 1,058 | 674 | 368 | 306 | -1 | -1 |
{-# LANGUAGE PatternGuards #-}
-- Some things could be improved, e.g.:
-- * Check that each file given contains at least one instance of the
-- function
-- * Check that we are testing all functions
-- * If a problem is found, give better location information, e.g.
-- which problem the file is in
module Main (main) where
import Control.Concurrent
import Control.Exception
import Control.Monad
import Control.Monad.State
import Data.Char
import Data.Set (Set)
import qualified Data.Set as Set
import System.Environment
import System.Exit
import System.IO
import System.Process
main :: IO ()
main = do args <- getArgs
case args of
function : files ->
doit function files
die :: String -> IO a
die err = do hPutStrLn stderr err
exitFailure
type M = StateT St IO
data St = St {
stSeen :: Set Int,
stLast :: Maybe Int,
stHadAProblem :: Bool
}
emptyState :: St
emptyState = St {
stSeen = Set.empty,
stLast = Nothing,
stHadAProblem = False
}
use :: Int -> M ()
use n = do st <- get
let seen = stSeen st
put $ st { stSeen = Set.insert n seen, stLast = Just n }
if (n `Set.member` seen)
then problem ("Duplicate " ++ show n)
else case stLast st of
Just l
| (l > n) ->
problem ("Decreasing order for " ++ show l
++ " -> " ++ show n)
_ ->
return ()
problem :: String -> M ()
problem str = do lift $ putStrLn str
st <- get
put $ st { stHadAProblem = True }
doit :: String -> [FilePath] -> IO ()
doit function files
= do (hIn, hOut, hErr, ph) <- runInteractiveProcess
"grep" ("-h" : function : files)
Nothing Nothing
hClose hIn
strOut <- hGetContents hOut
strErr <- hGetContents hErr
forkIO $ do evaluate (length strOut)
return ()
forkIO $ do evaluate (length strErr)
return ()
ec <- waitForProcess ph
case (ec, strErr) of
(ExitSuccess, "") ->
check function strOut
_ ->
error "grep failed"
check :: String -> String -> IO ()
check function str
= do let ls = lines str
-- filter out lines that start with whitespace. They're
-- from things like:
-- import M ( ...,
-- ..., <function>, ...
ls' = filter (not . all isSpace . take 1) ls
ns <- mapM (parseLine function) ls'
st <- execStateT (do mapM_ use ns
st <- get
when (Set.null (stSeen st)) $
problem "No values found")
emptyState
when (stHadAProblem st) exitFailure
parseLine :: String -> String -> IO Int
parseLine function str
= -- words isn't necessarily quite right, e.g. we could have
-- "var=" rather than "var =", but it works for the code
-- we have
case words str of
_var : "=" : fun : numStr : rest
| fun == function,
null rest || "--" == head rest,
[(num, "")] <- reads numStr
-> return num
_ -> error ("Bad line: " ++ show str)
| ekmett/ghc | utils/checkUniques/checkUniques.hs | bsd-3-clause | 3,507 | 0 | 17 | 1,416 | 943 | 473 | 470 | 87 | 3 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
module T7332 where
import GHC.Exts( IsString(..) )
import Data.Monoid
newtype DC d = DC d
deriving (Show, Monoid)
instance IsString (DC String) where
fromString = DC
class Monoid acc => Build acc r where
type BuildR r :: * -- Result type
build :: (acc -> BuildR r) -> acc -> r
instance Monoid dc => Build dc (DC dx) where
type BuildR (DC dx) = DC dx
build tr acc = tr acc
instance (Build dc r, a ~ dc) => Build dc (a->r) where
type BuildR (a->r) = BuildR r
build tr acc s = build tr (acc `mappend` s)
-- The type is inferred
-- tspan :: (Monoid d, Build (DC d) r, BuildR r ~ DC d) => r
tspan :: (Build (DC d) r, BuildR r ~ DC d) => r
tspan = build (id :: DC d -> DC d) mempty
{- Solving 'tspan'
Given: Build (DC d) r, BuildR r ~ DC d
(by sc) Monoid (DC d)
Wanted:
Build acc0 r0
Monid acc0
acc0 ~ DC d0
DC d0 ~ BuildR r0
r ~ r0
==>
Build (DC d0) r
Monoid (DC d0) --> Monoid d0
DC d0 ~ BuildR r
From Given: BuildR r = DC d, hence
DC d0 ~ DC d
hence
d0 ~ d
===>
Build (DC d) r
Monoid (DC d)
Now things are delicate. Either the instance Monoid (DC d) will fire or,
if we are lucky, we might spot that (Monoid (DC d)) is a superclass of
a given. But now (Decl 15) we add superclasses lazily, so that is less
likely to happen, and was always fragile. So include (MOnoid d) in the
signature, as was the case in the orignal ticket.
-}
foo = tspan "aa"
foo1 = tspan (tspan "aa")
bar = tspan "aa" :: DC String
| oldmanmike/ghc | testsuite/tests/polykinds/T7332.hs | bsd-3-clause | 1,802 | 0 | 10 | 488 | 353 | 190 | 163 | 27 | 1 |
import Safe
main :: IO ()
main = print $ headMay ([] :: [Int])
| AndreasPK/stack | test/integration/tests/444-package-option/files/Test.hs | bsd-3-clause | 64 | 0 | 8 | 15 | 37 | 20 | 17 | 3 | 1 |
module Main where
import Data.IORef
loop r 0 = return ()
loop r c = loop r (c-1) >> writeIORef r 42
main = newIORef 0 >>= \r -> loop r 1000000 >> putStrLn "done"
| beni55/ghcjs | test/pkg/base/ioref001.hs | mit | 166 | 0 | 8 | 39 | 84 | 42 | 42 | 5 | 1 |
module SpaceState.City(gotoCity, catapult)
where
import Data.List hiding (concat)
import Data.Maybe
import Data.Foldable
import Control.Monad hiding (mapM_)
import Control.Monad.State as State hiding (mapM_)
import Prelude hiding (catch, concat, mapM_)
import Text.Printf
import Graphics.Rendering.OpenGL as OpenGL
import Graphics.Rendering.FTGL as FTGL
import Graphics.UI.SDL as SDL hiding (flip)
import Statistics
import OpenGLUtils
import Politics
import Entity
import AObject
import Cargo
import Utils
import TextScreen
import Mission
import SpaceState.Game
updateAvailableMission :: AObject -> StateT SpaceState IO ()
updateAvailableMission lc = do
state <- State.get
let malleg = colonyOwner lc
case malleg of
Nothing -> return ()
Just alleg -> do
case possibleMissionType (allegAttitude alleg state) of
Nothing -> return ()
Just m -> createMission m alleg lc
createMission :: MissionCategory -> String -> AObject -> StateT SpaceState IO ()
createMission Messenger alleg lc = do
let planetname = aobjName lc
state <- State.get
let otherplanets = fmap aobjName $ filter (hasOwner alleg) (toList $ aobjects state)
when (not (null otherplanets)) $ do
n <- liftIO $ chooseIO otherplanets
when (n /= planetname) $
modify $ modAvailMission $ const $ Just $ MessengerMission n
createMission SecretMessage alleg lc = do
let planetname = aobjName lc
state <- State.get
let otherplanets = map aobjName $ filter (\a -> hasSomeOwner a && (not . hasOwner alleg) a) (toList $ aobjects state)
when (not (null otherplanets)) $ do
n <- liftIO $ chooseIO otherplanets
when (n /= planetname) $
modify $ modAvailMission $ const $ Just $ SecretMessageMission n
gotoCity :: AObject -> StateT SpaceState IO ()
gotoCity lc = do
let planetname = aobjName lc
state <- State.get
nmarket <- if planetname == fst (lastmarket state)
then return $ lastmarket state
else do
m <- liftIO $ randomMarket
return (planetname, m)
modify $ modMarket $ const nmarket
handleArrival lc
updateAvailableMission lc
cityLoop lc
catapult lc
cityLoop :: AObject -> StateT SpaceState IO ()
cityLoop lc = do
let planetname = aobjName lc
state <- State.get
let f = gamefont state
alleg = getAllegiance lc
leave = "Leave " ++ planetname
cangovernor = isJust $ possibleMissionType (allegAttitude alleg state)
options = "Market" : "Shipyard" : "Foreign affairs" : (if cangovernor then "Governor" : [leave] else [leave])
n <- liftIO $ menu 1 (f, Color4 1.0 1.0 1.0 1.0,
concat ["Starport on " ++ planetname,
if alleg == planetname then "" else "\nThis planet belongs to the country of " ++ alleg ++ "."])
(map (\s -> (f, Color4 1.0 1.0 0.0 1.0, s)) options)
(f, Color4 1.0 1.0 0.0 1.0, "=>")
case n of
1 -> gotoMarket planetname >> cityLoop lc
2 -> gotoShipyard >> cityLoop lc
3 -> liftIO (showForeignAffairs (colonyOwner lc) (gamefont state)) >> cityLoop lc
4 -> if cangovernor then gotoGovernor lc >> cityLoop lc else return ()
_ -> return ()
showForeignAffairs :: Maybe String -> Font -> IO ()
showForeignAffairs mst f =
let strs =
case mst of
Nothing -> ["This colony is in anarchy!"]
Just st -> map relToStr rs
where rs = relationshipsOf st
relToStr (l, v) | v <= (-4) = printf "We despise the state of %s." l
relToStr (l, v) | v <= (-1) = printf "We are not very fond of %s." l
relToStr (l, v) | v <= 1 = printf "Our relationship with the state of %s is neutral." l
relToStr (l, v) | v <= 4 = printf "%s is a friend of ours." l
relToStr (l, _) | otherwise = printf "We are allied with the state of %s." l
drawfunc = makeTextScreen (100, 420)
(map (\s -> (f, Color4 1.0 1.0 1.0 1.0, s))
(strs ++ ["\n\nPress any key to continue"]))
(return ())
in pressAnyKeyScreen drawfunc
gotoShipyard :: StateT SpaceState IO ()
gotoShipyard = do
state <- State.get
let f = gamefont state
let damages = startPlHealth - plhealth state
let cost = damages * 20
let repairtext =
if damages == 0
then "Repair (no damages)"
else "Repair ship (Cost: " ++ show cost ++ ")"
n <- liftIO $ menu 1 (f, Color4 1.0 1.0 1.0 1.0, "Shipyard")
[(f, Color4 1.0 1.0 0.0 1.0, repairtext),
(f, Color4 1.0 1.0 0.0 1.0, "Exit")]
(f, Color4 1.0 1.0 0.0 1.0, "=>")
case n of
1 -> do
when (cost > 0 && plcash state >= cost) $ do
modify $ modPlCash $ (subtract cost)
modify $ modPlHealth $ const startPlHealth
gotoShipyard
_ -> return ()
gotoMarket :: String -> StateT SpaceState IO ()
gotoMarket planetname = do
state <- State.get
let market = snd . lastmarket $ state
(m', cargo', cash', hold') <- liftIO $ execStateT
(tradeScreen ("Market on " ++ planetname)
(gamefont state) (monofont state))
(market, plcargo state, plcash state, plholdspace state)
modify $ modMarket $ modSnd $ const m'
modify $ modPlCargo $ const cargo'
modify $ modPlCash $ const cash'
modify $ modPlHoldspace $ const hold'
catapult :: AObject -> StateT SpaceState IO ()
catapult lc = do
state <- State.get
let objpos = AObject.getPosition lc
dist = AObject.size lc
plloc = Entity.position (tri state)
pldir = OpenGLUtils.normalize (plloc *-* objpos)
modify $ modTri $ modifyPosition $ const $ objpos *+* (pldir *** (dist + 5))
modify $ modTri $ modifyVelocity $ const $ pldir *** 0.2
modify $ modTri $ resetAcceleration
modify $ modTri $ modifyRotation $ (+180)
gotoGovernor :: AObject -> StateT SpaceState IO ()
gotoGovernor lc = do
state <- State.get
let alleg = getAllegiance lc
case missionFor alleg (plmissions state) of
Nothing ->
case availmission state of
Nothing -> noMissionsScreen
Just mis -> offerMission mis lc
Just currmission -> missionDisplay (gamefont state) alleg currmission
missionDisplay f alleg (MessengerMission tgt) = do
missionDisplayGeneric f alleg ["You have an important message that you need to",
"bring to the planet of " ++ tgt ++ "."]
missionDisplay f alleg (SecretMessageMission tgt) = do
missionDisplayGeneric f alleg ["There's a spy of ours currently residing",
"on the foreign planet of " ++ tgt ++ ".",
"You must bring him a secret message."]
missionDisplayGeneric f alleg msg =
pressAnyKeyScreen
(liftIO $ makeTextScreen (100, 500)
[(f, Color4 1.0 0.2 0.2 1.0,
intercalate "\n" (["Your current mission for " ++ alleg ++ ":", ""]
++ msg ++ ["", "Press any key to continue"]))]
(return ()))
handleArrival :: AObject -> StateT SpaceState IO ()
handleArrival lc = do
state <- State.get
mapM_ (flip handleArrival' lc) (missions (plmissions state))
noMissionsScreen :: StateT SpaceState IO ()
noMissionsScreen = do
state <- State.get
let plname = playername state
pressAnyKeyScreen
(liftIO $ makeTextScreen (100, 500)
[(gamefont state, Color4 1.0 0.2 0.2 1.0,
intercalate "\n" ["\"Dear " ++ plname ++ ", we currently have",
"no tasks for you.\"",
"",
"",
"Press any key to continue"])]
(return ()))
offerMission :: Mission -> AObject -> StateT SpaceState IO ()
offerMission mis@(MessengerMission tgt) lc = do
state <- State.get
let plname = playername state
let txt = ["\"Dear " ++ plname ++ ", I welcome you to my",
"residence. I have an important mission that",
"needs to be taken care of by a trustworthy",
"adventurer like yourself.",
"",
"The mission requires you to deliver an",
"important message from here to the planet",
"of " ++ tgt ++ ".",
"Will you accept?\" (y/n)"]
offerMissionGeneric mis lc txt
offerMission mis@(SecretMessageMission tgt) lc = do
state <- State.get
let plname = playername state
let txt = ["\"Dear " ++ plname ++ ", I welcome you to my",
"residence. I have a very important mission that",
"needs to be taken care of by a competent",
"adventurer like yourself.",
"",
"The mission requires you to deliver a message",
"to a spy of ours hidden on the foreign planet",
"of " ++ tgt ++ ".",
"Will you accept?\" (y/n)"]
offerMissionGeneric mis lc txt
offerMissionGeneric :: Mission -> AObject -> [String] -> StateT SpaceState IO ()
offerMissionGeneric mis lc msg = do
state <- State.get
let alleg = getAllegiance lc
let txt = intercalate "\n" msg
c <- pressOneOfScreen
(liftIO $ makeTextScreen (100, 500)
[(gamefont state, Color4 1.0 1.0 1.0 1.0, txt)]
(return ()))
[SDLK_y, SDLK_n, SDLK_ESCAPE]
modify $ modAvailMission (const Nothing)
case c of
SDLK_y -> modify $ modPlMissions $ setMission alleg mis
_ -> return ()
handleArrival' :: (String, Mission) -> AObject -> StateT SpaceState IO ()
handleArrival' (alleg, MessengerMission tgt) lc = do
state <- State.get
let plname = playername state
planetname = aobjName lc
checkArrived tgt planetname alleg pointsForMessengerMission
["\"Thank you, " ++ plname ++ ", for serving our great",
"country of " ++ alleg ++ " by delivering this important",
"message to us.\"",
"",
"Mission accomplished!",
"",
"",
"Press Enter to continue"]
handleArrival' (alleg, SecretMessageMission tgt) lc = do
state <- State.get
let plname = playername state
planetname = aobjName lc
checkArrived tgt planetname alleg pointsForSecretMessage
["\"Thank you, " ++ plname ++ ", for serving our great",
"country of " ++ alleg ++ " by delivering this important",
"message to us here on " ++ planetname ++ ".\"",
"",
"Mission accomplished!",
"",
"",
"Press Enter to continue"]
onActualArrival :: String -> Int -> [String] -> StateT SpaceState IO ()
onActualArrival alleg pts str = do
state <- State.get
let txt = intercalate "\n" str
modify $ modAvailMission (const Nothing)
modify $ modAllegAttitudes $ modAttitude (+pts) alleg
modify $ modPlMissions $ removeMission alleg
pressKeyScreen
(liftIO $ makeTextScreen (100, 500)
[(gamefont state, Color4 1.0 0.2 0.2 1.0, txt)]
(return ())) SDLK_RETURN
checkArrived :: String -> String -> String -> Int -> [String] -> StateT SpaceState IO ()
checkArrived tgt planetname alleg pts str =
when (tgt == planetname) (onActualArrival alleg pts str)
| anttisalonen/starrover2 | src/SpaceState/City.hs | mit | 11,240 | 0 | 19 | 3,253 | 3,478 | 1,739 | 1,739 | 266 | 8 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
module Bank.ReadModels.CustomerAccounts
( CustomerAccounts (..)
, customerAccountsAccountsById
, customerAccountsCustomerAccounts
, customerAccountsCustomerIdsByName
, getCustomerAccountsFromName
, customerAccountsProjection
) where
import Control.Lens
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe, mapMaybe)
import Eventful
import Bank.Models
-- | Groups account info by customer so it's easy to see all of a customer's
-- accounts
data CustomerAccounts
= CustomerAccounts
{ _customerAccountsAccountsById :: Map UUID Account
, _customerAccountsCustomerAccounts :: Map UUID [UUID]
, _customerAccountsCustomerIdsByName :: Map String UUID
-- NOTE: This assumes all customer names are unique. Obviously not true in
-- the real world.
} deriving (Show, Eq)
makeLenses ''CustomerAccounts
getCustomerAccountsFromName :: CustomerAccounts -> String -> [(UUID, Account)]
getCustomerAccountsFromName CustomerAccounts{..} name = fromMaybe [] $ do
customerId <- Map.lookup name _customerAccountsCustomerIdsByName
accountIds <- Map.lookup customerId _customerAccountsCustomerAccounts
let lookupAccount uuid = (uuid,) <$> Map.lookup uuid _customerAccountsAccountsById
return $ mapMaybe lookupAccount accountIds
handleCustomerAccountsEvent :: CustomerAccounts -> VersionedStreamEvent BankEvent -> CustomerAccounts
handleCustomerAccountsEvent accounts (StreamEvent uuid _ (CustomerCreatedEvent (CustomerCreated name))) =
accounts
& customerAccountsCustomerIdsByName %~ Map.insert name uuid
handleCustomerAccountsEvent accounts (StreamEvent uuid _ (AccountOpenedEvent event@(AccountOpened customerId _))) =
accounts
& customerAccountsAccountsById %~ Map.insert uuid account
& customerAccountsCustomerAccounts %~ Map.insertWith (++) customerId [uuid]
where
account = projectionEventHandler accountProjection (projectionSeed accountProjection) (AccountOpenedAccountEvent event)
-- Assume it's an account event. If it isn't it won't get handled, no biggy.
handleCustomerAccountsEvent accounts (StreamEvent uuid _ event) =
accounts
& customerAccountsAccountsById %~ Map.adjust modifyAccount uuid
where
modifyAccount account =
maybe account (projectionEventHandler accountProjection account) (deserialize accountEventSerializer event)
customerAccountsProjection :: Projection CustomerAccounts (VersionedStreamEvent BankEvent)
customerAccountsProjection =
Projection
(CustomerAccounts Map.empty Map.empty Map.empty)
handleCustomerAccountsEvent
| jdreaver/eventful | examples/bank/src/Bank/ReadModels/CustomerAccounts.hs | mit | 2,658 | 0 | 13 | 349 | 536 | 284 | 252 | 48 | 1 |
{-# htermination replicateM_ :: Monad m => Int -> m a -> m () #-}
import Monad
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Monad_replicateM__1.hs | mit | 79 | 0 | 3 | 17 | 5 | 3 | 2 | 1 | 0 |
module Example2 where
import qualified WeightedLPA as WLPA
import Graph
import qualified Data.Map as M
import qualified Data.Set as S
import FiniteFields
weighted_example :: WeightedGraph String String
weighted_example = WeightedGraph (buildGraphFromEdges [("e",("v","u"))]) (M.fromList [("e",2)])
unweighted_equivalent_example :: Graph String String
unweighted_equivalent_example = (buildGraphFromEdges [("e1",("u","v")), ("e2",("u","v"))])
vertex = WLPA.atom . WLPA.vertex
edge = WLPA.atom . (flip WLPA.edge 1)
ghostEdge = WLPA.atom . (flip WLPA.ghostEdge 1)
u = vertex "v"
v = vertex "u"
e1 = WLPA.adjoint $ edge "e1"
e2 = WLPA.adjoint $ edge "e2"
twos = map (WLPA.pathToNormalForm weighted_example) $ S.toList $ paths (doubleGraph (directedGraphAssociatedToWeightedGraph weighted_example)) 2
zeros = filter (WLPA.equal_wrt_graph weighted_example WLPA.Zero . WLPA.convertTerm) twos
non_zeros = filter (not . WLPA.equal_wrt_graph weighted_example WLPA.Zero . WLPA.convertTerm) twos
nods = filter (WLPA.isNodPath weighted_example) twos
non_nods = filter (not . WLPA.isNodPath weighted_example) twos
non_nods_reduced = map (WLPA.convertToBasisForm weighted_example . WLPA.convertTerm) non_nods
showMapping = putStrLn $ unlines (zipWith (\a b -> a ++ " --> " ++ b) (map show non_nods) (map show non_nods_reduced))
| rzil/honours | LeavittPathAlgebras/Example2.hs | mit | 1,324 | 0 | 12 | 171 | 463 | 251 | 212 | 24 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Data.Vinyl.Core where
import Data.Monoid
import Foreign.Ptr (castPtr, plusPtr)
import Foreign.Storable (Storable(..))
import Data.Vinyl.Functor
import Control.Applicative hiding (Const(..))
import Data.Typeable (Proxy(..))
import Data.List (intercalate)
import Data.Vinyl.TypeLevel
-- | A record is parameterized by a universe @u@, an interpretation @f@ and a
-- list of rows @rs@. The labels or indices of the record are given by
-- inhabitants of the kind @u@; the type of values at any label @r :: u@ is
-- given by its interpretation @f r :: *@.
data Rec :: (u -> *) -> [u] -> * where
RNil :: Rec f '[]
(:&) :: !(f r) -> !(Rec f rs) -> Rec f (r ': rs)
infixr 7 :&
infixr 5 <+>
infixl 8 <<$>>
infixl 8 <<*>>
-- | Two records may be pasted together.
rappend
:: Rec f as
-> Rec f bs
-> Rec f (as ++ bs)
rappend RNil ys = ys
rappend (x :& xs) ys = x :& (xs `rappend` ys)
-- | A shorthand for 'rappend'.
(<+>)
:: Rec f as
-> Rec f bs
-> Rec f (as ++ bs)
(<+>) = rappend
-- | 'Rec' @_ rs@ with labels in kind @u@ gives rise to a functor @Hask^u ->
-- Hask@; that is, a natural transformation between two interpretation functors
-- @f,g@ may be used to transport a value from 'Rec' @f rs@ to 'Rec' @g rs@.
rmap
:: (forall x. f x -> g x)
-> Rec f rs
-> Rec g rs
rmap _ RNil = RNil
rmap η (x :& xs) = η x :& (η `rmap` xs)
{-# INLINE rmap #-}
-- | A shorthand for 'rmap'.
(<<$>>)
:: (forall x. f x -> g x)
-> Rec f rs
-> Rec g rs
(<<$>>) = rmap
{-# INLINE (<<$>>) #-}
-- | An inverted shorthand for 'rmap'.
(<<&>>)
:: Rec f rs
-> (forall x. f x -> g x)
-> Rec g rs
xs <<&>> f = rmap f xs
{-# INLINE (<<&>>) #-}
-- | A record of components @f r -> g r@ may be applied to a record of @f@ to
-- get a record of @g@.
rapply
:: Rec (Lift (->) f g) rs
-> Rec f rs
-> Rec g rs
rapply RNil RNil = RNil
rapply (f :& fs) (x :& xs) = getLift f x :& (fs `rapply` xs)
{-# INLINE rapply #-}
-- | A shorthand for 'rapply'.
(<<*>>)
:: Rec (Lift (->) f g) rs
-> Rec f rs
-> Rec g rs
(<<*>>) = rapply
{-# INLINE (<<*>>) #-}
-- | Given a section of some functor, records in that functor of any size are
-- inhabited.
class RecApplicative rs where
rpure
:: (forall x. f x)
-> Rec f rs
instance RecApplicative '[] where
rpure _ = RNil
{-# INLINE rpure #-}
instance RecApplicative rs => RecApplicative (r ': rs) where
rpure s = s :& rpure s
{-# INLINE rpure #-}
-- | A record may be traversed with respect to its interpretation functor. This
-- can be used to yank (some or all) effects from the fields of the record to
-- the outside of the record.
rtraverse
:: Applicative h
=> (forall x. f x -> h (g x))
-> Rec f rs
-> h (Rec g rs)
rtraverse _ RNil = pure RNil
rtraverse f (x :& xs) = (:&) <$> f x <*> rtraverse f xs
{-# INLINABLE rtraverse #-}
-- | A record with uniform fields may be turned into a list.
recordToList
:: Rec (Const a) rs
-> [a]
recordToList RNil = []
recordToList (x :& xs) = getConst x : recordToList xs
-- | Wrap up a value with a capability given by its type
data Dict c a where
Dict
:: c a
=> a
-> Dict c a
-- | Sometimes we may know something for /all/ fields of a record, but when
-- you expect to be able to /each/ of the fields, you are then out of luck.
-- Surely given @∀x:u.φ(x)@ we should be able to recover @x:u ⊢ φ(x)@! Sadly,
-- the constraint solver is not quite smart enough to realize this and we must
-- make it patently obvious by reifying the constraint pointwise with proof.
reifyConstraint
:: RecAll f rs c
=> proxy c
-> Rec f rs
-> Rec (Dict c :. f) rs
reifyConstraint prx rec =
case rec of
RNil -> RNil
(x :& xs) -> Compose (Dict x) :& reifyConstraint prx xs
-- | Records may be shown insofar as their points may be shown.
-- 'reifyConstraint' is used to great effect here.
instance RecAll f rs Show => Show (Rec f rs) where
show xs =
(\str -> "{" <> str <> "}")
. intercalate ", "
. recordToList
. rmap (\(Compose (Dict x)) -> Const $ show x)
$ reifyConstraint (Proxy :: Proxy Show) xs
instance Monoid (Rec f '[]) where
mempty = RNil
RNil `mappend` RNil = RNil
instance (Monoid (f r), Monoid (Rec f rs)) => Monoid (Rec f (r ': rs)) where
mempty = mempty :& mempty
(x :& xs) `mappend` (y :& ys) = (x <> y) :& (xs <> ys)
instance Eq (Rec f '[]) where
_ == _ = True
instance (Eq (f r), Eq (Rec f rs)) => Eq (Rec f (r ': rs)) where
(x :& xs) == (y :& ys) = (x == y) && (xs == ys)
instance Storable (Rec f '[]) where
sizeOf _ = 0
alignment _ = 0
peek _ = return RNil
poke _ RNil = return ()
instance (Storable (f r), Storable (Rec f rs)) => Storable (Rec f (r ': rs)) where
sizeOf _ = sizeOf (undefined :: f r) + sizeOf (undefined :: Rec f rs)
{-# INLINABLE sizeOf #-}
alignment _ = alignment (undefined :: f r)
{-# INLINABLE alignment #-}
peek ptr = do !x <- peek (castPtr ptr)
!xs <- peek (ptr `plusPtr` sizeOf (undefined :: f r))
return $ x :& xs
{-# INLINABLE peek #-}
poke ptr (!x :& xs) = poke (castPtr ptr) x >> poke (ptr `plusPtr` sizeOf (undefined :: f r)) xs
{-# INLINEABLE poke #-}
| plow-technologies/Vinyl | Data/Vinyl/Core.hs | mit | 5,674 | 0 | 14 | 1,426 | 1,774 | 945 | 829 | 141 | 2 |
module Chip8.Memory where
import Data.Word (Word8, Word16)
import Data.STRef
import Data.Array.ST (STUArray, newArray, readArray, writeArray)
import System.Random (StdGen)
import Control.Monad (foldM_)
import Control.Monad.ST (ST)
import Chip8.Event
import Chip8.VideoMemory (VideoMemory, newVideoMemory)
data Address = Register Register
| Pc
| Sp
| Stack
| Ram Word16
deriving (Show)
data Register = V0 | V1 | V2 | V3
| V4 | V5 | V6 | V7
| V8 | V9 | VA | VB
| VC | VD | VE | VF
| DT | ST | I
deriving (Enum, Show)
toRegister :: Integral a => a -> Register
toRegister = toEnum . fromIntegral
data MemoryValue = MemoryValue8 Word8
| MemoryValue16 Word16
deriving (Show)
data Memory s = Memory { memory :: STUArray s Word16 Word8
, registers :: STUArray s Word8 Word8
, registerI :: STRef s Word16
, delayTimer :: STRef s Word8
, soundTimer :: STRef s Word8
, pc :: STRef s Word16
, sp :: STRef s Word8
, stack :: STUArray s Word8 Word16
, eventState :: EventState s
, videoMemory :: VideoMemory s
, stdGen :: STRef s StdGen
}
new :: StdGen -> ST s (Memory s)
new rndGen = do
memory' <- newArray (0x000, 0xFFF) 0
registers' <- newArray (0x0, 0xF) 0
registerI' <- newSTRef 0
delayTimer' <- newSTRef 0
soundTimer' <- newSTRef 0
pc' <- newSTRef 0x200
sp' <- newSTRef 0
stack' <- newArray (0x0, 0xF) 0
eventState' <- newEventState
videoMemory' <- newVideoMemory
stdGen' <- newSTRef rndGen
foldM_ (\a x -> do -- load font
writeArray memory' a x
return $ a + 1
) 0 font
return Memory { memory = memory'
, registers = registers'
, registerI = registerI'
, delayTimer = delayTimer'
, soundTimer = soundTimer'
, pc = pc'
, sp = sp'
, stack = stack'
, eventState = eventState'
, videoMemory = videoMemory'
, stdGen = stdGen'
}
store :: Memory s -> Address -> MemoryValue -> ST s ()
store mem Pc (MemoryValue16 v) = writeSTRef (pc mem) v
store mem Sp (MemoryValue8 v) = writeSTRef (sp mem) v
store mem (Register I) (MemoryValue16 v) = writeSTRef (registerI mem) v
store mem (Register DT) (MemoryValue8 v) = writeSTRef (delayTimer mem) v
store mem (Register ST) (MemoryValue8 v) = writeSTRef (soundTimer mem) v
store mem (Register r) (MemoryValue8 v) = writeArray (registers mem) (fromIntegral $ fromEnum r) v
store mem (Ram addr) (MemoryValue8 v) = writeArray (memory mem) addr v
store mem Stack (MemoryValue16 v) = do
(MemoryValue8 sp') <- load mem Sp
store mem Sp (MemoryValue8 $ sp' + 1)
writeArray (stack mem) sp' v
store _ _ _ = error "Incorrect Memory 'store' command"
load :: Memory s -> Address -> ST s MemoryValue
load mem Pc = readSTRef (pc mem) >>= \v -> return $ MemoryValue16 v
load mem Sp = readSTRef (sp mem) >>= \v -> return $ MemoryValue8 v
load mem (Register I) = readSTRef (registerI mem) >>= \v -> return $ MemoryValue16 v
load mem (Register DT) = readSTRef (delayTimer mem) >>= \v -> return $ MemoryValue8 v
load mem (Register ST) = readSTRef (soundTimer mem) >>= \v -> return $ MemoryValue8 v
load mem (Register r) = readArray (registers mem) (fromIntegral $ fromEnum r) >>= \v -> return $ MemoryValue8 v
load mem (Ram addr) = readArray (memory mem) addr >>= \v -> return $ MemoryValue8 v
load mem Stack = do
(MemoryValue8 sp') <- load mem Sp
store mem Sp (MemoryValue8 $ sp' - 1)
readArray (stack mem) (sp' - 1) >>= \v -> return $ MemoryValue16 v
font :: [Word8]
font = [ 0xF0, 0x90, 0x90, 0x90, 0xF0 -- 0
, 0x20, 0x60, 0x20, 0x20, 0x70 -- 1
, 0xF0, 0x10, 0xF0, 0x80, 0xF0 -- 2
, 0xF0, 0x10, 0xF0, 0x10, 0xF0 -- 3
, 0x90, 0x90, 0xF0, 0x10, 0x10 -- 4
, 0xF0, 0x80, 0xF0, 0x10, 0xF0 -- 5
, 0xF0, 0x80, 0xF0, 0x90, 0xF0 -- 6
, 0xF0, 0x10, 0x20, 0x40, 0x40 -- 7
, 0xF0, 0x90, 0xF0, 0x90, 0xF0 -- 8
, 0xF0, 0x90, 0xF0, 0x10, 0xF0 -- 9
, 0xF0, 0x90, 0xF0, 0x90, 0x90 -- A
, 0xE0, 0x90, 0xE0, 0x90, 0xE0 -- B
, 0xF0, 0x80, 0x80, 0x80, 0xF0 -- C
, 0xE0, 0x90, 0x90, 0x90, 0xE0 -- D
, 0xF0, 0x80, 0xF0, 0x80, 0xF0 -- E
, 0xF0, 0x80, 0xF0, 0x80, 0x80 -- F
]
| ksaveljev/chip-8-emulator | Chip8/Memory.hs | mit | 4,789 | 0 | 13 | 1,655 | 1,673 | 908 | 765 | 107 | 1 |
module Database.Siege.DBNode where
import Control.Monad.Trans.Store
import Control.Monad.Error
import Data.Word
import qualified Data.ByteString as B
-- TODO: move this into the distributed backend
newtype Ref = Ref {
unRef :: B.ByteString
} deriving (Read, Show, Eq, Ord)
validRef :: Ref -> Bool
validRef = (== 20) . B.length . unRef
data Node r =
Branch [(Word8, r)] |
Shortcut B.ByteString r |
StringValue B.ByteString |
Label B.ByteString r |
Array [r] deriving (Read, Show, Eq)
data DBError =
TypeError |
OtherError deriving (Eq)
instance Error DBError where
noMsg = OtherError
type RawDBOperation r m = ErrorT DBError (StoreT r (Node r) m)
createValue :: Monad m => B.ByteString -> RawDBOperation r m r
createValue dat =
lift $ store $ StringValue dat
getValue :: Monad m => r -> RawDBOperation r m B.ByteString
getValue ref = do
node <- lift $ get ref
case node of
StringValue st -> return st
_ -> throwError TypeError
createLabel :: Monad m => B.ByteString -> r -> RawDBOperation r m r
createLabel label ref =
lift $ store $ Label label ref
unlabel :: Monad m => B.ByteString -> r -> RawDBOperation r m r
unlabel label ref = do
node <- lift $ get ref
case node of
Label label' ref' ->
if label' == label then
return ref'
else
throwError TypeError
_ ->
throwError TypeError
getLabel :: Monad m => r -> RawDBOperation r m (B.ByteString, r)
getLabel ref = do
node <- lift $ get ref
case node of
Label l r ->
return (l, r)
_ ->
throwError TypeError
traverse :: Node r -> [r]
traverse (Branch options) = map snd options
traverse (Shortcut _ r) = [r]
traverse (StringValue _) = []
traverse (Label _ r) = [r]
traverse (Array r) = r
| DanielWaterworth/siege | src/Database/Siege/DBNode.hs | mit | 1,752 | 0 | 11 | 413 | 682 | 353 | 329 | 58 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Y2020.M10.D16.Solution where
{--
`sequence` is really cool: a neat trick.
The problem is that we have to use it in the first place. The question becomes
if the data structure you are using doesn't give you what you need, then you
need to move to a better data model. Data.Map isn't bidirecional, and that's
fine in many cases, but isn't in this case where we needed to key from the
country to the continent, and not the waythe original structure was built.
So. What data structure?
Hello, Graph.
--}
import Graph.Query
import Graph.JSON.Cypher
import Graph.JSON.Cypher.Read.Rows (justRows, QueryResult)
import Data.Relation
import qualified Data.Map as Map
import qualified Data.Text as T
import Y2020.M10.D12.Solution -- for Country-type
import Y2020.M10.D14.Solution
import Y2020.M10.D15.Solution
{--
Take the countries and continents from before and structure these data in a
graph.
In which continent is Andorra?
What are the countries in ... 'Oceania'?
What are all the continents? What is each continent's countries?
--}
-- Geo is actually a dependently-typed family of types, but oh, well.
data Geo = Country Country | Continent Continent
deriving (Eq, Show)
instance Node Geo where
asNode (Country coun) = T.concat ["Country { name: \"", coun, "\" }"]
asNode (Continent cont) = T.concat ["Continent { name: '", cont, "' }"]
data IN = IN
deriving Show
instance Edge IN where
asEdge = const "IN"
type Cy = Relation Geo IN Geo
-- type Cy should be stricter: A continent cannot be in a country, but oh, well.
type Graph = Endpoint -- ... *cough*
relationalize :: CountryMap -> [Cy]
relationalize = map relit . Map.toList
relit :: (Country, Continent) -> Cy
relit (country, continent) = Rel (Country country) IN (Continent continent)
{--
>>> countriesByContinent (Y2020.M10.D14.Solution.workingDir ++ cbc)
>>> let m = it
>>> let cm = countryMap m
>>> graphEndpoint
>>> let url = it
>>> take 2 $ relationalize cm
[Rel (Country "Afghanistan") IN (Continent "Asia"),
Rel (Country "Albania (Shqip\235ria)") IN (Continent "Europe")]
>>> cyphIt url (relationalize cm)
--}
continentOf :: Graph -> Country -> IO QueryResult
continentOf url countr = getGraphResponse url (query (Country countr))
{--
>>> justRows <$> continentOf url "Andorra"
[TR {row = Array [Object (fromList [("name",String "Europe")])]}]
--}
query :: Geo -> [Cypher]
query a = [T.concat ["MATCH (", asNode a, ")-[:IN]-(b) RETURN b"]]
countriesOf :: Graph -> Continent -> IO QueryResult
countriesOf url conti = getGraphResponse url (query (Continent conti))
{--
>>> take 3 . justRows <$> countriesOf url "Oceania"
[TR {row = Array [Object (fromList [("name",String "Nauru")])]},
TR {row = Array [Object (fromList [("name",String "Tonga")])]},
TR {row = Array [Object (fromList [("name",String "Tuvalu")])]}]
--}
| geophf/1HaskellADay | exercises/HAD/Y2020/M10/D16/Solution.hs | mit | 2,870 | 0 | 9 | 485 | 421 | 241 | 180 | 32 | 1 |
module AST where
data BinOp
= Extend
| Plus
| Minus
| Mul
| Div
| Eq
| NonEq
| And
| Or
deriving Show
data Expression
= BinaryExpression BinOp Expression Expression
| PrimaryExpression PrimaryExpression
deriving Show
data PrimaryExpression
= Expression Expression
| PrefixedExpression Prefix Expression
| BlockExpression [Statement]
| Literal Literal
| Variable Variable
| Function [Variable] [Statement]
| PropertyAccess PrimaryExpression String
| Call PrimaryExpression [Expression]
| If Expression Expression Expression
| Null
deriving Show
data Prefix = Not
deriving Show
data Literal
= String String
| Integer Integer
| List [Expression]
| Object [(String, Expression)]
deriving Show
type Variable = String
data Statement
= Assign Variable Expression
| Return Expression
| EmptyStatement
deriving Show
data TopStatement
= Statement Statement
| Import ModuleName
deriving Show
data Module
= Module [TopStatement]
deriving Show
type ModuleName = [String]
| jinjor/poorscript | src/AST.hs | mit | 1,046 | 0 | 8 | 225 | 256 | 156 | 100 | 50 | 0 |
-- playing around with STRefs - BST example etc
import Control.Monad.ST
import Data.STRef
-- items in tree (monomorphic, no separate key+value currently)
type Item = Int
-- tree of ints (for simple BST)
-- with STRefs so we can use (monadic) destructive update
-- This leads to an extra level of indirection in data structure plus
-- explicit dealing with refs in all the code traversing trees plus
-- the need for the ST monad everywhere the tree is used:-(
-- Note: the Item in nodes here is not wrapped in a ref (not quite the
-- same as Pawns version)
data DUTree s =
DUEmpty | DUNode (STRef s (DUTree s)) Item (STRef s (DUTree s))
-- high level version
data Tree = Empty | Node Tree Item Tree
deriving Show
-- convert list to BST (using destructive insert)
list_dubst :: [Item] -> ST s (DUTree s)
list_dubst xs =
do
tp <- newSTRef DUEmpty
list_dubst_du xs tp
readSTRef tp
-- As above with (ref to) tree passed in
list_dubst_du :: [Item] -> STRef t (DUTree t) -> ST t ()
list_dubst_du xs tp =
case xs of
(x:xs1) ->
do
dubst_insert_du x tp
list_dubst_du xs1 tp
[] ->
return ()
-- destructively insert element x into (ref to) BST
dubst_insert_du :: Item -> STRef t (DUTree t) -> ST t ()
dubst_insert_du x tp =
do
t <- readSTRef tp
case t of
DUEmpty -> -- tp := Node Empty x Empty
do
e1 <- newSTRef DUEmpty
e2 <- newSTRef DUEmpty
writeSTRef tp (DUNode e1 x e2)
(DUNode lp n rp) ->
if x <= n then
dubst_insert_du x lp
else
dubst_insert_du x rp
-- size of tree
-- (doesn't update tree, though this isn't obvious from the type signature)
dubst_size :: DUTree s -> ST s Int
dubst_size t =
case t of
DUEmpty ->
return 0
(DUNode lp n rp) ->
do
l <- readSTRef lp
sl <- dubst_size l
r <- readSTRef rp
sr <- dubst_size r
return (sl + sr + 1)
-- tests for membership of tree
-- (doesn't update tree, though this isn't obvious from the type signature)
dubst_member :: Item -> DUTree s -> ST s Bool
dubst_member x t =
case t of
DUEmpty ->
return False
(DUNode lp n rp) ->
if x == n then
return True
else if x <= n then
do
l <- readSTRef lp
dubst_member x l
else
do
r <- readSTRef rp
dubst_member x r
test1 =
runST $
do
tp <- newSTRef DUEmpty
dubst_insert_du 3 tp
dubst_insert_du 5 tp
t <- readSTRef tp
dubst_size t
test2 =
runST $
do
t <- list_dubst [3,4,2,5,1]
dubst_size t
-- illustrates how sharing of (even empty) subtrees breaks insertion
test3 =
runST $
do
tp <- newSTRef DUEmpty -- could be anything
e1 <- newSTRef DUEmpty
writeSTRef tp (DUNode e1 5 e1) -- tree with Empty subtree refs shared
dubst_insert_du 3 tp -- clobbers both occurrences of e1 - oops!
t <- readSTRef tp
dubst_size t
test4 =
runST $
do
t <- list_dubst [3,6,2,5,1]
-- dubst_member 5 t
dubst_member 4 t
-- convert from DU tree to high level tree
dubst_bst :: DUTree s -> ST s Tree
dubst_bst t =
case t of
DUEmpty ->
return Empty
(DUNode lp n rp) ->
do
l <- readSTRef lp
hl <- dubst_bst l
r <- readSTRef rp
hr <- dubst_bst r
return (Node hl n hr)
-- size of high level tree
bst_size :: Tree -> Int
bst_size t =
case t of
Empty -> 0
(Node l _ r) -> (bst_size l) + (bst_size r) + 1
-- size of tree, using conversion to high level tree
dubst_size' :: DUTree s -> ST s Int
dubst_size' t =
do
ht <- dubst_bst t
return (bst_size ht)
-- length of list
len l =
runST $
do
dut <- list_dubst l
t <- dubst_bst dut
return $ bst_size t
tst30000 =
runST $
do
t <- list_dubst [1..30000]
dubst_size t
main = do print tst30000
-- :l "hsrbst"
-- len [3,4,2,5,1]
| lee-naish/Pawns | bench/hsrbst.hs | mit | 4,082 | 0 | 14 | 1,350 | 1,137 | 549 | 588 | 124 | 4 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{- This example shows how to extract all
- user friends, get their similarity score and
- then sort them based on it outputting top 5
-
- User friends of which are searched is 'target'
-
- Most of hard work there is on 'aeson-lens' actually :)
-
- Sample output:
-
- % ./examples/sort-friends.hs
- Artvart: 0.9969767332077
- smpcln: 0.9965825676918
- nv0id: 0.86804795265198
- QueenrXy: 0.5932799577713
- GhostOsaka: 0.2875879406929
-
- Notice: you may want to adjust maximum open files limit
- if testing on users with relatively large friends count
-}
import Control.Concurrent.Async -- async
import Control.Lens -- lens
import Data.Aeson.Lens -- lens-aeson
import Data.Aeson (Value) -- aeson
import Data.Function (on) -- base
import Data.List (sortBy) -- base
import Data.Maybe (fromMaybe) -- base
import Data.Monoid ((<>)) -- base
import Data.Text (Text) -- text
import Data.Text.Lens (unpacked) -- lens
import qualified Data.Text.IO as Text -- text
import Lastfm hiding (to) -- liblastfm
import qualified Lastfm.User as User -- liblastfm
import qualified Lastfm.Tasteometer as Tasteometer -- liblastfm
import Text.Read (readMaybe) -- base
type Score = Text
main :: IO ()
main = withConnection $ \conn ->
pages conn >>= scores conn . names >>= pretty
where
names x = x ^.. folded.folded.key "friends".key "user"._Array.folded.key "name"._String
pages :: Connection -> IO [Either LastfmError Value]
pages conn = do
first <- query conn (User.getFriends <*> user target)
let ps = fromMaybe 1 (preview total first)
(first :) <$> forConcurrently [2..ps] (\p -> query conn (User.getFriends <*> user target <* page p))
where
total = folded.key "friends".key "@attr".key "totalPages"._String.unpacked.to readMaybe.folded
scores :: Connection -> [Text] -> IO [(Text, Score)]
scores conn xs = zip xs <$> forConcurrently xs (\x -> do
r <- query conn (Tasteometer.compare (user target) (user x))
return (fromMaybe "0" (preview score r)))
where
score = folded.key "comparison".key "result".key "score"._String
pretty :: [(Text, Score)] -> IO ()
pretty = mapM_ (\(n,s) -> Text.putStrLn $ n <> ": " <> s) . take 5 . sortBy (flip compare `on` snd)
query :: Connection -> Request 'JSON (APIKey -> Ready) -> IO (Either LastfmError Value)
query conn r = lastfm conn (r <*> apiKey "234fc6e0f41f6ef99b7bd62ebaf8d318" <* json)
target :: Text
target = "MCDOOMDESTROYER"
| supki/liblastfm | example/sort-friends.hs | mit | 2,780 | 0 | 16 | 737 | 691 | 377 | 314 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
module Main where
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Char (isSpace, toLower)
import Control.Monad.State
import Data.Maybe (fromJust)
import System.IO (Handle, hFlush, hIsEOF, isEOF, openFile, IOMode(WriteMode, ReadMode), hTell, hSeek, SeekMode(AbsoluteSeek))
import Data.Char (ord)
import Data.Binary (decode, encode)
import System.Environment (getArgs)
import Data.Functor ((<$>))
boolean :: a -> a -> Bool -> a
boolean a _ True = a
boolean _ a False = a
main :: IO ()
main = do
(word:_) <- getArgs
if word == "build-index" then do
p <- openFiles WriteMode
runStateT (buildIndex ("", "") >> writePos positionH (-1)) p
hFlush $ lazyH p
hFlush $ wordH p
hFlush $ positionH p
else do
p <- openFiles ReadMode
t <- openFile "korpus" ReadMode
hSeek (lazyH p) AbsoluteSeek . toInteger . (*8) . hash $ BS.pack word
wordPointer <- hIsEOF (lazyH p) >>= boolean (return $ -1) (readInt $ lazyH p)
pointerPointer <- linsearch (wordH p) wordPointer $ BS.pack word
case pointerPointer of
Nothing -> putStrLn $ "Hittade inte " ++ word
Just a -> do
hSeek (positionH p) AbsoluteSeek $ toInteger a
occurrences <- printOccurrences (positionH p) t (length word)
putStrLn $ "Det finns " ++ show (length occurrences) ++ " förekomster av ordet."
if length occurrences > 25
then do
putStrLn "Oj! Det var många. Vill du printa dem?"
res <- getLine
case map toLower res of
'y':_ -> sequence_ occurrences
_ -> return ()
else sequence_ occurrences
printOccurrences :: Handle -> Handle -> Int -> IO [IO ()]
printOccurrences positionHandle textHandle l = do
p <- readInt positionHandle
let postpos = - 30 - (min (p - 30) 0)
if p == -1 then return [] else do
hSeek textHandle AbsoluteSeek $ toInteger (p + postpos)
text <- BS.hGet textHandle (30 - postpos + l)
let printWord = putStrLn . BS.unpack . BS.map (\c -> if c == '\n' then ' ' else c) $ text
let padding = replicateM_ (30 + postpos) (putStr " ")
printOccurrences positionHandle textHandle l >>= return . ((padding >> printWord) :)
linsearch :: Handle -> Int -> BS.ByteString -> IO (Maybe Int)
linsearch _ (-1) _ = return Nothing
linsearch index start word = do
hSeek index AbsoluteSeek $ toInteger start
nothingIfEnd
where
nothingIfEnd = hIsEOF index >>= boolean (return Nothing) linsearchRec
linsearchRec = do
testWord <- BS.hGetLine index
case compare testWord word of
GT -> return Nothing
EQ -> Just <$> readInt index
LT -> readInt index >> nothingIfEnd
{-binsearch :: Handle -> Int -> Int -> BS.ByteString -> IO (Maybe Int)
binsearch index start end word = do
hSeek index AbsoluteSeek ((end - start)/2)
BS.hGetLine index >> readInt index
wordPos <- hTell -}
readInt :: Handle -> IO Int
readInt h = decode <$> LBS.hGet h 8
openFiles :: IOMode -> IO Positions
openFiles mode = do
l <- openFile "index/lazyH" mode
w <- openFile "index/wordH" mode
p <- openFile "index/positionH" mode
return $ Positions l w p
type Worker a = StateT Positions IO a
data Positions = Positions {lazyH::Handle, wordH::Handle, positionH::Handle} deriving Show
buildIndex :: (BS.ByteString, BS.ByteString) -> Worker ()
buildIndex prevData = liftIO isEOF >>= \end -> if end then return () else do
line <- liftIO BS.getLine
let (word, pos) = BS.break isSpace line
key <- checkWordAndKey prevData word
writePos positionH . fst . fromJust . BS.readInt . BS.tail $ pos
buildIndex (key, word)
checkWordAndKey :: (BS.ByteString, BS.ByteString) -> BS.ByteString -> Worker BS.ByteString
checkWordAndKey (lastKey, lastWord) word =
if lastWord == word then return lastKey
else do
writeKey lastKey key
writePos positionH (-1)
writeWord word
return key
where
key = BS.take 3 word
writeKey :: BS.ByteString -> BS.ByteString -> Worker ()
writeKey lastKey key = if lastKey == key then return ()
else do
wordPointer <- fromInteger <$> (get >>= liftIO . hTell . wordH)
replicateM_ ((hash key) - (hash lastKey) - 1) $ writePos lazyH (-1)
writePos lazyH wordPointer
writePos :: (Positions -> Handle) -> Int -> Worker ()
writePos h p = do
handle <- get >>= return . h
liftIO . writeInt handle $ p
writeWord :: BS.ByteString -> Worker ()
writeWord word = do
handle <- get >>= return . wordH
liftIO $ BS.hPut handle word
liftIO $ BS.hPut handle "\n"
get >>= liftIO . hTell . positionH >>= liftIO . writeInt handle . fromInteger
writeInt :: Handle -> Int -> IO ()
writeInt handle = LBS.hPut handle . encode
hash :: BS.ByteString -> Int
hash = (+(-1)) . sum . zipWith (*) [900, 30, 1] . map chash . BS.unpack
where
chash ' ' = 0
chash 'ä' = (chash 'z') + 1
chash 'å' = (chash 'z') + 2
chash 'ö' = (chash 'z') + 3
chash c = (ord c) - (ord 'a') + 1
| elegios/konkordans-haskell | src/main.hs | mit | 4,857 | 8 | 22 | 989 | 1,907 | 950 | 957 | 117 | 5 |
{-# LANGUAGE DeriveFunctor #-}
------------------------------------------------------------------------------
-- |
-- Module : Hajong.Game.Yaku.Builder
-- Copyright : (C) 2014 Samuli Thomasson
-- License : MIT (see the file LICENSE)
-- Maintainer : Samuli Thomasson <[email protected]>
-- Stability : experimental
-- Portability : non-portable
------------------------------------------------------------------------------
module Mahjong.Hand.Yaku.Builder
( YakuCheck, runYakuCheck
-- * Checkers
, concealedHandDegrade, concealedHand, openHand, yakuState, allMentsuOfKind, yakuFail
, requireFlag
-- * Matching mentsu
-- ** Any
, anyKoutsu, anyKantsu, anyShuntsu, anyJantou, anyMentsu
, anyKoutsuKantsu, anyMentsuJantou
-- *** Stateful
, anyShuntsu', anyMentsu', anyKoutsuKantsu', anyMentsuJantou'
-- ** Tile-based
, terminal, honor, sangenpai, kazehai, suited, anyTile, concealed
, sameTile, containsTile, sameNumber, sameSuit, ofNumber, valueless
-- ** Combinators
, (&.), (|.), propNot, tileGroupHead, tileGroupTiles
) where
------------------------------------------------------------------------------
import Import
import Mahjong.Tiles (Tile(..), Number(..))
import qualified Mahjong.Tiles as T
import Mahjong.Hand.Mentsu
import Mahjong.Hand.Algo
------------------------------------------------------------------------------
import Mahjong.Hand.Internal
import Mahjong.Kyoku.Internal
import Mahjong.Kyoku.Flags
------------------------------------------------------------------------------
import Control.Monad.Free
import Control.Monad.State
------------------------------------------------------------------------------
type YakuCheck = Free Check
data Check next = YakuMentsu MentsuProp next
-- ^ Require a simple mentsu property. Requiring this
-- first could allow for simple optimization by
-- removing some repeated checking.
| YakuMentsu' MentsuProp (TileGroup -> next)
-- ^ Require a mentsu property, but allow upcoming
-- properties depend on the matched TileGroup.
| YakuStateful (ValueInfo -> next)
-- ^ Depend on game state.
| YakuHandConcealedDegrades next
| YakuHandConcealed next
| YakuHandOpen next
| YakuRequireFlag Flag next
| YakuFailed
deriving (Functor)
-- | Run the yaku checker with the given grouping.
runYakuCheck :: ValueInfo -> Grouping -> YakuCheck Yaku -> Maybe Yaku
runYakuCheck info grouping = fmap fst . (`runStateT` grouping) . iterM f
where
f :: Check (StateT Grouping Maybe Yaku) -> StateT Grouping Maybe Yaku
f (YakuMentsu mp s) = get >>= lift . findMatch mp >>= putRes >> s
f (YakuMentsu' mp s) = get >>= lift . findMatch mp >>= putRes >>= s
f (YakuStateful s) = s info
f (YakuHandConcealedDegrades s) = if isConcealed then s else s <&> (yHan -~ 1)
f (YakuHandConcealed s) = if isConcealed then s else lift Nothing
f (YakuHandOpen s) = if isConcealed then lift Nothing else s
f (YakuRequireFlag flag s) = if hasFlag flag then s else lift Nothing
f YakuFailed = lift Nothing
putRes (tg, g) = put g >> return tg
isConcealed = null $ info^..vHand.handCalled.each.filtered
(maybe True ((`onotElem` [Ron, Chankan]) . shoutKind) . mentsuShout)
hasFlag flag = elem flag $ info^.vKyoku.pFlags
-- @MentsuProp@s
data MentsuProp = TileTerminal
| TileSameAs Tile
| TileContained Tile
| TileSuited
| TileSameSuit Tile
| TileSameNumber Tile
| TileNumber Number
| TileHonor
| TileSangenpai
| TileKazehai
| TileAnd MentsuProp MentsuProp -- ^ &&
| TileOr MentsuProp MentsuProp -- ^ ||
| TileNot MentsuProp -- ^ not
| TileConcealed
| MentsuJantou
| MentsuOrJantou
| MentsuShuntsu
| MentsuKoutsu
| MentsuKantsu
| MentsuKoutsuKantsu
| PropAny -- ^ Match anything
-- | Binary combinations of mentsu porperties.
(&.), (|.) :: MentsuProp -> MentsuProp -> MentsuProp
(&.) = TileAnd
(|.) = TileOr
infixl 1 &., |.
-- @Check@ primitives
-- | Value degrades by one if open.
concealedHandDegrade :: YakuCheck ()
concealedHandDegrade = liftF $ YakuHandConcealedDegrades ()
-- | Must be concealed
concealedHand :: YakuCheck ()
concealedHand = liftF $ YakuHandConcealed ()
-- | Must be open
openHand :: YakuCheck ()
openHand = liftF $ YakuHandOpen ()
requireFlag :: Flag -> YakuCheck ()
requireFlag flag = liftF $ YakuRequireFlag flag ()
-- | Yaku that depends on something else than the mentsu; see "ValueInfo"
-- for available properties.
yakuState :: YakuCheck ValueInfo
yakuState = liftF (YakuStateful id)
-- | Simple yaku helper to require some same property from the four mentsu
-- and the pair.
allMentsuOfKind :: MentsuProp -> YakuCheck ()
allMentsuOfKind tkind = do
anyJantou tkind
replicateM_ 4 $ anyMentsu tkind
-- | Fail the hand
yakuFail :: YakuCheck a
yakuFail = liftF YakuFailed -- (error "Not used"))
-- | Require any mentsu with a property.
anyKoutsu, anyKantsu, anyShuntsu, anyJantou, anyMentsu, anyKoutsuKantsu, anyMentsuJantou :: MentsuProp -> YakuCheck ()
anyMentsu tkind = liftF $ YakuMentsu (propNot MentsuJantou &. tkind) ()
anyKoutsu tkind = liftF $ YakuMentsu (MentsuKoutsu &. tkind) ()
anyShuntsu tkind = liftF $ YakuMentsu (MentsuShuntsu &. tkind) ()
anyKantsu tkind = liftF $ YakuMentsu (MentsuKantsu &. tkind) ()
anyJantou tkind = liftF $ YakuMentsu (MentsuJantou &. tkind) ()
anyKoutsuKantsu tkind = liftF $ YakuMentsu (MentsuKoutsuKantsu &. tkind) ()
anyMentsuJantou tkind = liftF $ YakuMentsu (MentsuOrJantou &. tkind) ()
-- | Require any mentsu with a property. Rest of the definition may depend
-- on the matched tile.
anyShuntsu', anyKoutsuKantsu', anyMentsu', anyMentsuJantou' :: MentsuProp -> YakuCheck TileGroup
anyMentsu' tkind = liftF $ YakuMentsu' tkind id
anyKoutsuKantsu' tkind = liftF $ YakuMentsu' (MentsuKoutsuKantsu &. tkind) id
anyShuntsu' tkind = liftF $ YakuMentsu' (MentsuShuntsu &. tkind) id
anyMentsuJantou' tkind = liftF $ YakuMentsu' (MentsuOrJantou &. tkind) id
tileGroupHead :: TileGroup -> Tile
tileGroupHead = headEx . tileGroupTiles
-- Mentsu properties
-- | Tile kinds.
terminal, honor, sangenpai, kazehai, suited, anyTile, concealed :: MentsuProp
terminal = TileTerminal
honor = TileHonor
sangenpai = TileSangenpai
kazehai = TileKazehai
suited = TileSuited
anyTile = PropAny
concealed = TileConcealed
-- | A tile which has no intrinsic fu value i.e. is suited or not round or
-- player kaze. Depends on the kyoku state.
valueless :: YakuCheck MentsuProp
valueless = do
vi <- yakuState
let valuedKaze = [ vi^.vPlayer, vi^.vKyoku.pRound._1 ]
valueless = map (sameTile . T.kaze) $ filter (`onotElem` valuedKaze) [T.Ton .. T.Pei]
return $ foldr (|.) suited valueless
sameTile, containsTile, sameNumber, sameSuit :: Tile -> MentsuProp
sameTile = TileSameAs
containsTile = TileContained
sameNumber = TileSameNumber
sameSuit = TileSameSuit
ofNumber :: Number -> MentsuProp
ofNumber = TileNumber
-- | Negation of a MentsuProp.
propNot :: MentsuProp -> MentsuProp
propNot = TileNot
-- Check MentsuProps directly.
-- | Find a match in a list of mentsu. Returns the matches identifier tile and leftovers.
findMatch :: MentsuProp -> Grouping -> Maybe (TileGroup, Grouping)
findMatch _ [] = Nothing
findMatch mp (x:xs)
| matchProp mp x = Just (x, xs)
| otherwise = findMatch mp xs & _Just._2 %~ (x:)
-- | Match a property on a TileGroup. GroupLeftOver's always result False.
matchProp :: MentsuProp -> TileGroup -> Bool
matchProp _ GroupLeftover{} = False
matchProp tt tg = case tt of
MentsuJantou -> isPair tg
MentsuOrJantou -> True
MentsuShuntsu -> case tg of
GroupComplete mentsu -> isShuntsu mentsu
_ -> False
MentsuKoutsu -> case tg of
GroupComplete mentsu -> isKoutsu mentsu
_ -> False
MentsuKantsu -> case tg of
GroupComplete mentsu -> isKantsu mentsu
_ -> False
MentsuKoutsuKantsu -> case tg of
GroupComplete mentsu -> isKantsu mentsu || isKoutsu mentsu
_ -> False
TileTerminal -> any T.terminal tiles
TileSameAs tile -> headEx tiles == tile
TileContained tile -> tile `elem` tiles
TileSuited -> T.isSuited (headEx tiles)
TileSameSuit tile -> T.suitedSame tile (headEx tiles)
TileSameNumber tile -> isJust (T.tileNumber tile) && T.tileNumber tile == T.tileNumber (headEx tiles)
TileNumber n -> T.tileNumber (headEx tiles) == Just n
TileHonor -> not $ T.isSuited (headEx tiles)
TileSangenpai -> T.sangenpai (headEx tiles)
TileKazehai -> T.kazehai (headEx tiles)
TileAnd x y -> matchProp x tg && matchProp y tg
TileOr x y -> matchProp x tg || matchProp y tg
TileNot x -> not $ matchProp x tg
TileConcealed -> case tg of
GroupComplete mentsu -> isNothing $ mentsuShout mentsu
_ -> True
PropAny -> True
where
tiles = tileGroupTiles tg
| SimSaladin/hajong | hajong-server/src/Mahjong/Hand/Yaku/Builder.hs | mit | 9,974 | 0 | 15 | 2,768 | 2,195 | 1,199 | 996 | -1 | -1 |
f::(a,b)->(c,d)->((b,d),(a,c))
f a b = (,) ((,) (snd a) (snd b)) ((,) (fst a) (fst b))
| Numberartificial/workflow | haskell-first-principles/haskell-from-first-principles-master/04/04.09.03-function.hs | mit | 87 | 0 | 9 | 16 | 108 | 60 | 48 | 2 | 1 |
{-# LANGUAGE TupleSections #-}
module Akari where
import Control.Applicative
import Data.Attoparsec.ByteString
import Data.Attoparsec.ByteString.Char8
import Data.Char (ord)
import Data.SBV
import Control.Monad.Writer
import Data.Map (Map, (!))
import Data.List (transpose)
import Data.Maybe (fromJust, catMaybes)
import Util
-- Akari (or Light Up)
-- Light Up is played on a rectangular grid of white and black cells.
-- The player places light bulbs in white cells such that no two bulbs shine on each other,
-- until the entire grid is lit up. A bulb sends rays of light horizontally and vertically,
-- illuminating its entire row and column unless its light is blocked by a black cell.
-- A black cell may have a number on it from 0 to 4, indicating how many bulbs must be
-- placed adjacent to its four sides; for example, a cell with a 4 must have four bulbs around it,
-- one on each side, and a cell with a 0 cannot have a bulb next to any of its sides.
-- An unnumbered black cell may have any number of light bulbs adjacent to it, or none.
-- Bulbs placed diagonally adjacent to a numbered cell do not contribute to the bulb count.
data AkariType = Wall | Space
type AkariInst = [[(AkariType, Maybe Integer)]]
type Elem = SWord32
type Row = [Elem]
type Board = [Row]
rules :: AkariInst -> Symbolic SBool
rules inst = do
let width = length (head inst)
let height = length inst
board <-
forM [0..height-1] $ \r ->
forM [0..width-1] $ \c ->
(symbolic (show r ++ "-" ++ show c) :: Symbolic SBool)
let getVar r c = if r >= 0 && r < height && c >= 0 && c < width then Just $ (board !! r) !! c else Nothing
addConstraints $ do
forM_ (zip3 [0 .. ] inst board) $ \(r, instRow, boardRow) ->
forM_ (zip3 [0 .. ] instRow boardRow) $ \(c, instCell, var) ->
do
-- constraints to match input numbers
case instCell
of (_, Just i) -> do
-- number of bulbs adjacent to this square are correct
addConstraint $ literal i .==
(sum $ map (\var -> ite var (literal 1) (literal 0)) $
catMaybes $ [getVar (r+1) c, getVar (r-1) c, getVar r (c-1), getVar r (c+1)])
(_, Nothing) ->
return ()
-- general bulb constraints
case instCell
of (Wall, _) -> do
-- no bulb on a wall
addConstraint $ var .== literal False
(Space, _) -> do
-- this space is LIT
let visibleSpaceInclusive = getVisibleSpace inst (r, c)
addConstraint $ orList $ map (\(r, c) -> (board !! r) !! c) visibleSpaceInclusive
-- this space cannot simulatenously have a bulb if it is otherwise lit
let visibleSpaceExclusive = filter (/= (r, c)) visibleSpaceInclusive
forM_ visibleSpaceExclusive $ \(r1, c1) -> do
addConstraint $ bnot $ var &&& ((board !! r1) !! c1)
where
getVisibleSpace inst (r, c) =
let
width = length (head inst)
height = length inst
getRun r c deltaR deltaC =
let
r1 = r + deltaR
c1 = c + deltaC
isSpace = if r1 >= 0 && c1 >= 0 && r1 < height && c1 < width then
case (inst !! r1) !! c1 of (Wall, _) -> False
(Space, _) -> True
else False
in
if isSpace then (r1, c1) : getRun r1 c1 deltaR deltaC
else []
in
[(r,c)] ++ getRun r c 0 (-1) ++ getRun r c 0 1 ++ getRun r c 1 0 ++ getRun r c (-1) 0
getSolution :: AkariInst -> Map String CW -> String
getSolution inst m =
let
width = length (head inst)
height = length inst
in
concat $ map (++ "\n") $ map concat $
map (\i ->
map (\j ->
if (fromCW $ m ! (show i ++ "-" ++ show j) :: Bool) then
"+" -- light bulb
else
case ((inst !! i) !! j) of (_, Just i) -> show i
(Space, Nothing) -> " "
(Wall, Nothing) -> "#"
) [0..width-1]
) [0..height-1]
solvePuzzle :: Symbolic SBool -> (Map String CW -> a) -> IO [a]
solvePuzzle prob fn = do
res <- allSat prob
return $ map fn (getModelDictionaries res)
akari :: AkariInst -> IO ()
akari puzzle = do
res <- solvePuzzle (rules puzzle) (getSolution puzzle)
putStrLn $ (show $ length res) ++ " solution(s)"
forM_ res $ \soln ->
putStrLn $ soln
-- Note that there needs to be an empty line to signal the end of the puzzle.
akariParser :: Parser AkariInst
akariParser = do
puz <- many $ do
row <- many1 cellParser
endOfLine
pure row
endOfLine
pure puz
where
cellParser :: Parser (AkariType, Maybe Integer)
cellParser =
((Wall,) . Just . subtract 48 . toInteger . ord <$> digit)
<|> (char '#' *> pure (Wall, Nothing))
<|> (char '.' *> pure (Space, Nothing))
| tjhance/logic-puzzles | src/Akari.hs | mit | 5,390 | 0 | 31 | 1,996 | 1,564 | 826 | 738 | 99 | 7 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : $Header$
Description : translating a HasCASL subset to Isabelle
Copyright : (c) C. Maeder, DFKI 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (imports Logic.Logic)
The embedding comorphism from HasCASL without subtypes to
Isabelle-HOL. Partial functions yield an option or bool result in
Isabelle. Case-terms and constructor classes are not supported yet.
-}
module Comorphisms.MonadicHasCASLTranslation
(MonadicHasCASL2IsabelleHOL(..)) where
import Comorphisms.PPolyTyConsHOL2IsaUtils
import Logic.Logic as Logic
import Logic.Comorphism
import HasCASL.Logic_HasCASL
import HasCASL.Sublogic
import HasCASL.As
import HasCASL.Le as Le
import Isabelle.IsaSign as Isa
import Isabelle.Logic_Isabelle
-- | The identity of the comorphism
data MonadicHasCASL2IsabelleHOL = MonadicHasCASL2IsabelleHOL deriving Show
instance Language MonadicHasCASL2IsabelleHOL where
language_name MonadicHasCASL2IsabelleHOL = "MonadicTranslation"
instance Comorphism MonadicHasCASL2IsabelleHOL
HasCASL Sublogic
BasicSpec Le.Sentence SymbItems SymbMapItems
Env Morphism
Symbol RawSymbol ()
Isabelle () () Isa.Sentence () ()
Isa.Sign
IsabelleMorphism () () () where
sourceLogic MonadicHasCASL2IsabelleHOL = HasCASL
sourceSublogic MonadicHasCASL2IsabelleHOL = noSubtypes
targetLogic MonadicHasCASL2IsabelleHOL = Isabelle
mapSublogic cid sl = if sl `isSubElem` sourceSublogic cid
then Just () else Nothing
map_theory MonadicHasCASL2IsabelleHOL =
mapTheory (Old NoSimpLift) simpForOption
map_sentence MonadicHasCASL2IsabelleHOL sign phi =
transSentence sign (typeToks sign) (Old NoSimpLift) simpForOption phi
isInclusionComorphism MonadicHasCASL2IsabelleHOL = True
has_model_expansion MonadicHasCASL2IsabelleHOL = True
| nevrenato/Hets_Fork | Comorphisms/MonadicHasCASLTranslation.hs | gpl-2.0 | 2,087 | 0 | 8 | 415 | 295 | 160 | 135 | 34 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module IRCSpec where
import Data.Attoparsec.Text (parseOnly)
import Data.Text as T
import Test.Hspec
import Test.QuickCheck
import IRC
import Default
-- | main spec
spec :: Spec
spec = toIrcSpec
-- = specs
toIrcSpec :: Spec
toIrcSpec = describe "toIrc" $ do
it "adds correct newlines" $ property $
\c -> let r = toIrc c
in T.last r == '\n' && T.last (T.init r) == '\r'
it "contains a colon before the last argument" $ property $
forAll sendableCommands $
(/= 1) . Prelude.length . splitOn " :" . toIrc
it "is well-behaved towards our parser" $ property $
forAll bijectiveCommands $
(==) <$> parseOnly command . T.init . toIrc <*> Right
| ibabushkin/wormbot | test/IRCSpec.hs | gpl-3.0 | 745 | 0 | 17 | 189 | 217 | 113 | 104 | 21 | 1 |
module Config (
parseConfigXML,
showConfig
) where
import Text.XML.HXT.Core
---------------------------------------------
-- types
-- TODO nasty things (does it have to be like this?):
-- 1. lack of type unions (lots of nested constructors instead)
-- 2. record field names must be unique globally?? => bad names
---------------------------------------------
data TParam = Param {
pnam :: String,
pval :: String
} deriving (Show)
data TApplyTpl = ApplyTpl {
tpl :: String,
output :: Maybe String,
ovar :: Maybe String,
params :: [TParam]
} deriving (Show)
data TCopy = Copy {
src :: String,
dst :: String
} deriving (Show)
data TSave = Save {
svvar :: String,
svfile :: String
} deriving (Show)
data TSelect = Select {
sfile :: String,
sxpath :: String,
svar :: String
} deriving (Show)
data TMatchChild = MatchApplyTpl TApplyTpl | MatchCopy TCopy | MatchSave TSave
deriving (Show)
data TMatch = Match {
mfile :: String,
mxpath :: Maybe String,
mitems :: [TMatchChild]
} deriving (Show)
data TCreateChild = CreateSelect TSelect | CreateApplyTpl TApplyTpl
deriving (Show)
data TCreate = Create {
cfile :: Maybe String,
citems :: [TCreateChild]
} deriving (Show)
data TConfigChild = ConfigMatch TMatch | ConfigCreate TCreate
deriving (Show)
data TConfig = Config {
directives :: [TConfigChild]
} deriving (Show)
indent :: [String] -> [String]
indent = map (" "++)
showMaybeStr :: Maybe String -> String
showMaybeStr Nothing = "-"
showMaybeStr (Just s) = s
showApplyTpl :: TApplyTpl -> [String]
showApplyTpl a = ["Apply-Template: " ++ (tpl a) ++ " -> file: " ++ (showMaybeStr $ output a) ++ " var: " ++ (showMaybeStr $ ovar a)]
showCopy :: TCopy -> String
showCopy c = "Copy: " ++ (src c) ++ " -> " ++ (dst c)
showSave :: TSave -> String
showSave c = "Save: " ++ (svvar c) ++ " -> " ++ (svfile c)
showSelect :: TSelect -> String
showSelect s = "Select: file: " ++ (sfile s) ++ " xpath: " ++ (sxpath s) ++ " var: " ++ (svar s)
showMatchChild :: TMatchChild -> [String]
showMatchChild (MatchApplyTpl a) = showApplyTpl a
showMatchChild (MatchCopy c) = [showCopy c]
showMatchChild (MatchSave s) = [showSave s]
showMatch :: TMatch -> [String]
showMatch m =
("Match file: " ++ (mfile m) ++ " xpath: " ++ (showMaybeStr $ mxpath m)) : (indent . concat $ map showMatchChild (mitems m))
showCreateChild :: TCreateChild -> [String]
showCreateChild (CreateApplyTpl a) = showApplyTpl a
showCreateChild (CreateSelect s) = [showSelect s]
showCreate :: TCreate -> [String]
showCreate c =
("Create file: " ++ (showMaybeStr $ cfile c)) : (indent . concat $ map showCreateChild (citems c))
showCfgChild :: TConfigChild -> [String]
showCfgChild (ConfigMatch m) = showMatch m
showCfgChild (ConfigCreate c) = showCreate c
showConfig :: TConfig -> String
showConfig c =
case directives c of
[] -> "Config is empty!"
(h:t) -> unlines . indent . concat $ map showCfgChild (h:t)
parseMaybeAttr :: (ArrowXml a) => String -> a XmlTree (Maybe String)
parseMaybeAttr s = withDefault (getAttrValue0 s >>^ Just) Nothing
-- parse create element (return a singleton list)
parseCreate :: (ArrowXml a) => a XmlTree TCreate
parseCreate =
(parseMaybeAttr "file") &&& ((getChildren >>> isElem >>>
((hasName "select" >>> parseSelect >>^ CreateSelect)
<+>
(hasName "apply-template" >>> parseApplyTemplate >>^ CreateApplyTpl))) >. id)
>>^
(\(x,y) -> Create {cfile=x, citems=y})
-- parse match element (return a singleton list)
parseMatch :: (ArrowXml a) => a XmlTree TMatch
parseMatch =
(parseMaybeAttr "xpath") &&& (getAttrValue0 "file")
&&&
((getChildren >>> isElem >>>
((hasName "apply-template" >>> parseApplyTemplate >>^ MatchApplyTpl)
<+>
(hasName "save" >>> parseSave >>^ MatchSave)
<+>
(hasName "copy" >>> parseCopy >>^ MatchCopy))) >. id)
>>^
(\(x,(y,z)) -> Match {mfile=y, mxpath=x, mitems=z})
parseSave :: (ArrowXml a) => a XmlTree TSave
parseSave =
(getAttrValue0 "src") &&& (getAttrValue0 "file")
>>^
(\(x,y) -> Save {svvar=x, svfile=y})
parseCopy :: (ArrowXml a) => a XmlTree TCopy
parseCopy =
(getAttrValue0 "src") &&& (getAttrValue0 "dst")
>>^
(\(x,y) -> Copy {src=x, dst=y})
parseSelect :: (ArrowXml a) => a XmlTree TSelect
parseSelect =
(getAttrValue0 "file") &&& (getAttrValue0 "xpath") &&& (getAttrValue0 "var")
>>^
(\(x,(y,z)) -> Select {sfile=x, sxpath=y, svar=z})
-- parse apply-template element (return a singleton list)
parseApplyTemplate :: (ArrowXml a) => a XmlTree TApplyTpl
parseApplyTemplate =
((hasAttr "output") <+> (hasAttr "var")) >>. (take 1)
>>>
((parseMaybeAttr "output") &&& (parseMaybeAttr "var") &&& (getAttrValue0 "template")
&&&
((getChildren >>> isElem >>> hasName "param"
>>>
((getAttrValue0 "name") &&& (getAttrValue0 "value"))
>>^
(\(x,y) -> Param {pnam=x, pval=y})) >. id))
>>^
(\(u,(w,(x,z))) -> ApplyTpl {tpl=x, output=u, ovar=w, params=z})
parseConfig :: (ArrowXml a) => a XmlTree TConfig
parseConfig =
-- When using readDocument, we must start with getChildren >>>
-- This is not the case with xreadDoc!
isElem >>> hasName "xtiles-config" >>> ((getChildren >>> isElem
>>>
((hasName "match" >>> parseMatch >>^ ConfigMatch)
<+>
(hasName "create" >>> parseCreate >>^ ConfigCreate)))
>. id)
>>^
(\x -> Config {directives=x})
-- parse config from XML String
parseConfigXML :: String -> TConfig
parseConfigXML cfgStr =
let cfg = runLA (xreadDoc >>> parseConfig) cfgStr
in
case cfg of
[h] -> h
[] -> error "Config error (no root)"
_ -> error "Config error (multiple roots)"
| sfindeisen/xtiles | src/Config.hs | gpl-3.0 | 5,849 | 0 | 17 | 1,302 | 1,976 | 1,090 | 886 | 146 | 3 |
{-# LANGUAGE TemplateHaskell #-}
module Vdv.Settings where
import ClassyPrelude hiding(FilePath,(<>))
import System.FilePath
import Options.Applicative(strOption,long,help,option,(<>),Parser,execParser,helper,fullDesc,progDesc,header,info,switch)
import Control.Lens(makeLenses)
import Vdv.Filter
import Vdv.Exclusions
import Vdv.Service
data Settings = Settings {
_settingsInputFile :: FilePath
, _settingsFilters :: [Filter]
, _settingsService :: Service
, _settingsInvert :: Bool
, _settingsCondenseOutput :: Bool
, _settingsExclusions :: Exclusions
} deriving(Show,Eq)
$(makeLenses ''Settings)
parseSettings' :: Parser Settings
parseSettings' = Settings
<$> strOption (long "input-file" <> help "Logdatei zum Einlesen")
<*> (option filtersOpt (long "filters" <> help "Kommaserparierte Liste von Filtern, Format <pfad>[=~]<wert> ist hierbei ein Pfad tagname1/tagname2/...") <|> pure mempty)
<*> option serviceOpt (long "service" <> help "Dienst (AUS/DFI/...)")
<*> switch (long "invert" <> help "Outputfahrten umdrehen")
<*> switch (long "condense" <> help "Nur Halte mit Zeiten ausgeben (nur für AUS interessant)")
<*> (option exclusionsOpt (long "exclusions" <> help "Welche Tags bei der Ausgabe weggetan werden sollen (kommaseparierte Liste von Pfaden a la <pfad> ist hierbei ein Pfad tagname1/tagname2/...)") <|> pure mempty)
parseSettings :: MonadIO m => m Settings
parseSettings = liftIO (execParser opts)
where
opts = info (helper <*> parseSettings')
(fullDesc <> progDesc "Parsen, filter und analysieren von VDV-Logdateien" <> header "Parsen, filter und analysieren von VDV-Logdateien")
| pmiddend/vdvanalyze | src/Vdv/Settings.hs | gpl-3.0 | 1,728 | 0 | 15 | 318 | 394 | 213 | 181 | 30 | 1 |
module Demo where
-- Ðåàëèçóéòå êëàññ òèïîâ
class (Eq a, Enum a, Bounded a) => SafeEnum a where
ssucc :: a -> a
ssucc x | x == maxBound = minBound
| otherwise = succ x
spred :: a -> a
spred x | x == minBound = maxBound
| otherwise = pred x
{- îáå ôóíêöèè êîòîðîãî âåäóò ñåáÿ êàê succ è pred ñòàíäàðòíîãî êëàññà Enum, îäíàêî ÿâëÿþòñÿ òîòàëüíûìè, òî åñòü íå îñòàíàâëèâàþòñÿ ñ îøèáêîé íà íàèáîëüøåì è íàèìåíüøåì çíà÷åíèÿõ òèïà-ïåðå÷èñëåíèÿ ñîîòâåòñòâåííî, à îáåñïå÷èâàþò öèêëè÷åñêîå ïîâåäåíèå. Âàø êëàññ äîëæåí áûòü ðàñøèðåíèåì ðÿäà êëàññîâ òèïîâ ñòàíäàðòíîé áèáëèîòåêè, òàê ÷òîáû ìîæíî áûëî íàïèñàòü ðåàëèçàöèþ ïî óìîë÷àíèþ åãî ìåòîäîâ, ïîçâîëÿþùóþ îáúÿâëÿòü åãî ïðåäñòàâèòåëåé áåç íåîáõîäèìîñòè ïèñàòü êàêîé áû òî íè áûëî êîä. Íàïðèìåð, äëÿ òèïà Bool äîëæíî áûòü äîñòàòî÷íî íàïèñàòü ñòðîêó -}
{- Òàêîé êîä íå êàíàåò:
ssucc maxBound = minBound
ssucc x = succ x
ïîòîìó ÷òî maxBound - ýòî íå îáðàçåö, à îáû÷íûé èäåíòèôèêàòîð, êîòîðûé ðàññìàòðèâàåòñÿ êàê èìÿ ôîðìàëüíîãî ïàðàìåòðà ôóíêöèè. Òî ÷òî ýòî èìÿ ñîâïàäàåò ñ èìåíåì ôóíêöèè (êîíñòàíòû) ïðèâîäèò ëèøü ê òîìó, ÷òî èìÿ ýòîé ôóíêöèè çàòåíÿåòñÿ â âûðàæåíèè ñïðàâà îò çíàêà ðàâåíñòâà.  êà÷åñòâå îáðàçöîâ (îïðîâåðæèìûõ) ìîãóò èñïîëüçîâàòüñÿ òîëüêî èìåíà êîíñòðóêòîðîâ äàííûõ. -}
instance SafeEnum Bool
{- è ïîëó÷èòü âîçìîæíîñòü âûçûâàòü
GHCi> ssucc False
True
GHCi> ssucc True
False
-}
instance SafeEnum Char
instance SafeEnum Int
instance SafeEnum ()
| devtype-blogspot-com/Haskell-Examples | SafeEnum/Demo.hs | gpl-3.0 | 1,442 | 0 | 10 | 265 | 146 | 71 | 75 | 12 | 0 |
module Events where
import GHC.IO.Handle
import Control.Concurrent.STM.TChan
import Text.Parsec
data EventPackage = EventPackage EventPrinter EventParser
-- for getting from the wire
data EventParser = EventParser (Parsec String () Event)
-- for printing on the wire
data EventPrinter = EventPrinter (Event -> String)
-- Internal Event Representation
data Event = KeyPress Char
-- list of some events
parsers = [keyPress]
-- KeyPress
unKeyPress (KeyPress c) = "KeyPress:\0" ++ c:"\0\0"
keyPress :: Parsec String () Event
keyPress = do string "KeyPress"
char '\0'
c <- option '\0' (noneOf "\0")
return (KeyPress c)
keyPressHandler (KeyPress c) = putStrLn $ "keypress: " ++ show c
lookupHandler (KeyPress _) = keyPressHandler
lookupParser (KeyPress _) = keyPress
lookupUnHandler (KeyPress _) = unKeyPress
| RocketPuppy/PupEvents | Events.hs | gpl-3.0 | 855 | 0 | 10 | 168 | 242 | 127 | 115 | 19 | 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.Container.Projects.Zones.Clusters.NodePools.SetSize
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Sets the size for a specific node pool. The new size will be used for
-- all replicas, including future replicas created by modifying
-- NodePool.locations.
--
-- /See:/ <https://cloud.google.com/container-engine/ Kubernetes Engine API Reference> for @container.projects.zones.clusters.nodePools.setSize@.
module Network.Google.Resource.Container.Projects.Zones.Clusters.NodePools.SetSize
(
-- * REST Resource
ProjectsZonesClustersNodePoolsSetSizeResource
-- * Creating a Request
, projectsZonesClustersNodePoolsSetSize
, ProjectsZonesClustersNodePoolsSetSize
-- * Request Lenses
, pzcnpssXgafv
, pzcnpssUploadProtocol
, pzcnpssAccessToken
, pzcnpssUploadType
, pzcnpssZone
, pzcnpssPayload
, pzcnpssNodePoolId
, pzcnpssClusterId
, pzcnpssProjectId
, pzcnpssCallback
) where
import Network.Google.Container.Types
import Network.Google.Prelude
-- | A resource alias for @container.projects.zones.clusters.nodePools.setSize@ method which the
-- 'ProjectsZonesClustersNodePoolsSetSize' request conforms to.
type ProjectsZonesClustersNodePoolsSetSizeResource =
"v1" :>
"projects" :>
Capture "projectId" Text :>
"zones" :>
Capture "zone" Text :>
"clusters" :>
Capture "clusterId" Text :>
"nodePools" :>
Capture "nodePoolId" Text :>
"setSize" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SetNodePoolSizeRequest :>
Post '[JSON] Operation
-- | Sets the size for a specific node pool. The new size will be used for
-- all replicas, including future replicas created by modifying
-- NodePool.locations.
--
-- /See:/ 'projectsZonesClustersNodePoolsSetSize' smart constructor.
data ProjectsZonesClustersNodePoolsSetSize =
ProjectsZonesClustersNodePoolsSetSize'
{ _pzcnpssXgafv :: !(Maybe Xgafv)
, _pzcnpssUploadProtocol :: !(Maybe Text)
, _pzcnpssAccessToken :: !(Maybe Text)
, _pzcnpssUploadType :: !(Maybe Text)
, _pzcnpssZone :: !Text
, _pzcnpssPayload :: !SetNodePoolSizeRequest
, _pzcnpssNodePoolId :: !Text
, _pzcnpssClusterId :: !Text
, _pzcnpssProjectId :: !Text
, _pzcnpssCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsZonesClustersNodePoolsSetSize' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pzcnpssXgafv'
--
-- * 'pzcnpssUploadProtocol'
--
-- * 'pzcnpssAccessToken'
--
-- * 'pzcnpssUploadType'
--
-- * 'pzcnpssZone'
--
-- * 'pzcnpssPayload'
--
-- * 'pzcnpssNodePoolId'
--
-- * 'pzcnpssClusterId'
--
-- * 'pzcnpssProjectId'
--
-- * 'pzcnpssCallback'
projectsZonesClustersNodePoolsSetSize
:: Text -- ^ 'pzcnpssZone'
-> SetNodePoolSizeRequest -- ^ 'pzcnpssPayload'
-> Text -- ^ 'pzcnpssNodePoolId'
-> Text -- ^ 'pzcnpssClusterId'
-> Text -- ^ 'pzcnpssProjectId'
-> ProjectsZonesClustersNodePoolsSetSize
projectsZonesClustersNodePoolsSetSize pPzcnpssZone_ pPzcnpssPayload_ pPzcnpssNodePoolId_ pPzcnpssClusterId_ pPzcnpssProjectId_ =
ProjectsZonesClustersNodePoolsSetSize'
{ _pzcnpssXgafv = Nothing
, _pzcnpssUploadProtocol = Nothing
, _pzcnpssAccessToken = Nothing
, _pzcnpssUploadType = Nothing
, _pzcnpssZone = pPzcnpssZone_
, _pzcnpssPayload = pPzcnpssPayload_
, _pzcnpssNodePoolId = pPzcnpssNodePoolId_
, _pzcnpssClusterId = pPzcnpssClusterId_
, _pzcnpssProjectId = pPzcnpssProjectId_
, _pzcnpssCallback = Nothing
}
-- | V1 error format.
pzcnpssXgafv :: Lens' ProjectsZonesClustersNodePoolsSetSize (Maybe Xgafv)
pzcnpssXgafv
= lens _pzcnpssXgafv (\ s a -> s{_pzcnpssXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pzcnpssUploadProtocol :: Lens' ProjectsZonesClustersNodePoolsSetSize (Maybe Text)
pzcnpssUploadProtocol
= lens _pzcnpssUploadProtocol
(\ s a -> s{_pzcnpssUploadProtocol = a})
-- | OAuth access token.
pzcnpssAccessToken :: Lens' ProjectsZonesClustersNodePoolsSetSize (Maybe Text)
pzcnpssAccessToken
= lens _pzcnpssAccessToken
(\ s a -> s{_pzcnpssAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pzcnpssUploadType :: Lens' ProjectsZonesClustersNodePoolsSetSize (Maybe Text)
pzcnpssUploadType
= lens _pzcnpssUploadType
(\ s a -> s{_pzcnpssUploadType = a})
-- | Deprecated. The name of the Google Compute Engine
-- [zone](https:\/\/cloud.google.com\/compute\/docs\/zones#available) in
-- which the cluster resides. This field has been deprecated and replaced
-- by the name field.
pzcnpssZone :: Lens' ProjectsZonesClustersNodePoolsSetSize Text
pzcnpssZone
= lens _pzcnpssZone (\ s a -> s{_pzcnpssZone = a})
-- | Multipart request metadata.
pzcnpssPayload :: Lens' ProjectsZonesClustersNodePoolsSetSize SetNodePoolSizeRequest
pzcnpssPayload
= lens _pzcnpssPayload
(\ s a -> s{_pzcnpssPayload = a})
-- | Deprecated. The name of the node pool to update. This field has been
-- deprecated and replaced by the name field.
pzcnpssNodePoolId :: Lens' ProjectsZonesClustersNodePoolsSetSize Text
pzcnpssNodePoolId
= lens _pzcnpssNodePoolId
(\ s a -> s{_pzcnpssNodePoolId = a})
-- | Deprecated. The name of the cluster to update. This field has been
-- deprecated and replaced by the name field.
pzcnpssClusterId :: Lens' ProjectsZonesClustersNodePoolsSetSize Text
pzcnpssClusterId
= lens _pzcnpssClusterId
(\ s a -> s{_pzcnpssClusterId = a})
-- | Deprecated. The Google Developers Console [project ID or project
-- number](https:\/\/support.google.com\/cloud\/answer\/6158840). This
-- field has been deprecated and replaced by the name field.
pzcnpssProjectId :: Lens' ProjectsZonesClustersNodePoolsSetSize Text
pzcnpssProjectId
= lens _pzcnpssProjectId
(\ s a -> s{_pzcnpssProjectId = a})
-- | JSONP
pzcnpssCallback :: Lens' ProjectsZonesClustersNodePoolsSetSize (Maybe Text)
pzcnpssCallback
= lens _pzcnpssCallback
(\ s a -> s{_pzcnpssCallback = a})
instance GoogleRequest
ProjectsZonesClustersNodePoolsSetSize
where
type Rs ProjectsZonesClustersNodePoolsSetSize =
Operation
type Scopes ProjectsZonesClustersNodePoolsSetSize =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsZonesClustersNodePoolsSetSize'{..}
= go _pzcnpssProjectId _pzcnpssZone _pzcnpssClusterId
_pzcnpssNodePoolId
_pzcnpssXgafv
_pzcnpssUploadProtocol
_pzcnpssAccessToken
_pzcnpssUploadType
_pzcnpssCallback
(Just AltJSON)
_pzcnpssPayload
containerService
where go
= buildClient
(Proxy ::
Proxy ProjectsZonesClustersNodePoolsSetSizeResource)
mempty
| brendanhay/gogol | gogol-container/gen/Network/Google/Resource/Container/Projects/Zones/Clusters/NodePools/SetSize.hs | mpl-2.0 | 8,216 | 0 | 24 | 1,869 | 1,033 | 604 | 429 | 161 | 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.Coordinate.Schedule.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the schedule for a job.
--
-- /See:/ <https://developers.google.com/coordinate/ Google Maps Coordinate API Reference> for @coordinate.schedule.get@.
module Network.Google.Resource.Coordinate.Schedule.Get
(
-- * REST Resource
ScheduleGetResource
-- * Creating a Request
, scheduleGet
, ScheduleGet
-- * Request Lenses
, sgJobId
, sgTeamId
) where
import Network.Google.MapsCoordinate.Types
import Network.Google.Prelude
-- | A resource alias for @coordinate.schedule.get@ method which the
-- 'ScheduleGet' request conforms to.
type ScheduleGetResource =
"coordinate" :>
"v1" :>
"teams" :>
Capture "teamId" Text :>
"jobs" :>
Capture "jobId" (Textual Word64) :>
"schedule" :>
QueryParam "alt" AltJSON :> Get '[JSON] Schedule
-- | Retrieves the schedule for a job.
--
-- /See:/ 'scheduleGet' smart constructor.
data ScheduleGet = ScheduleGet'
{ _sgJobId :: !(Textual Word64)
, _sgTeamId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ScheduleGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sgJobId'
--
-- * 'sgTeamId'
scheduleGet
:: Word64 -- ^ 'sgJobId'
-> Text -- ^ 'sgTeamId'
-> ScheduleGet
scheduleGet pSgJobId_ pSgTeamId_ =
ScheduleGet'
{ _sgJobId = _Coerce # pSgJobId_
, _sgTeamId = pSgTeamId_
}
-- | Job number
sgJobId :: Lens' ScheduleGet Word64
sgJobId
= lens _sgJobId (\ s a -> s{_sgJobId = a}) . _Coerce
-- | Team ID
sgTeamId :: Lens' ScheduleGet Text
sgTeamId = lens _sgTeamId (\ s a -> s{_sgTeamId = a})
instance GoogleRequest ScheduleGet where
type Rs ScheduleGet = Schedule
type Scopes ScheduleGet =
'["https://www.googleapis.com/auth/coordinate",
"https://www.googleapis.com/auth/coordinate.readonly"]
requestClient ScheduleGet'{..}
= go _sgTeamId _sgJobId (Just AltJSON)
mapsCoordinateService
where go
= buildClient (Proxy :: Proxy ScheduleGetResource)
mempty
| rueshyna/gogol | gogol-maps-coordinate/gen/Network/Google/Resource/Coordinate/Schedule/Get.hs | mpl-2.0 | 3,012 | 0 | 15 | 742 | 408 | 243 | 165 | 62 | 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.Content.FreeListingsprogram.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the status and review eligibility for the free listing
-- program.
--
-- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.freelistingsprogram.get@.
module Network.Google.Resource.Content.FreeListingsprogram.Get
(
-- * REST Resource
FreeListingsprogramGetResource
-- * Creating a Request
, freeListingsprogramGet
, FreeListingsprogramGet
-- * Request Lenses
, flgXgafv
, flgMerchantId
, flgUploadProtocol
, flgAccessToken
, flgUploadType
, flgCallback
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.freelistingsprogram.get@ method which the
-- 'FreeListingsprogramGet' request conforms to.
type FreeListingsprogramGetResource =
"content" :>
"v2.1" :>
Capture "merchantId" (Textual Int64) :>
"freelistingsprogram" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] FreeListingsProgramStatus
-- | Retrieves the status and review eligibility for the free listing
-- program.
--
-- /See:/ 'freeListingsprogramGet' smart constructor.
data FreeListingsprogramGet =
FreeListingsprogramGet'
{ _flgXgafv :: !(Maybe Xgafv)
, _flgMerchantId :: !(Textual Int64)
, _flgUploadProtocol :: !(Maybe Text)
, _flgAccessToken :: !(Maybe Text)
, _flgUploadType :: !(Maybe Text)
, _flgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FreeListingsprogramGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'flgXgafv'
--
-- * 'flgMerchantId'
--
-- * 'flgUploadProtocol'
--
-- * 'flgAccessToken'
--
-- * 'flgUploadType'
--
-- * 'flgCallback'
freeListingsprogramGet
:: Int64 -- ^ 'flgMerchantId'
-> FreeListingsprogramGet
freeListingsprogramGet pFlgMerchantId_ =
FreeListingsprogramGet'
{ _flgXgafv = Nothing
, _flgMerchantId = _Coerce # pFlgMerchantId_
, _flgUploadProtocol = Nothing
, _flgAccessToken = Nothing
, _flgUploadType = Nothing
, _flgCallback = Nothing
}
-- | V1 error format.
flgXgafv :: Lens' FreeListingsprogramGet (Maybe Xgafv)
flgXgafv = lens _flgXgafv (\ s a -> s{_flgXgafv = a})
-- | Required. The ID of the account.
flgMerchantId :: Lens' FreeListingsprogramGet Int64
flgMerchantId
= lens _flgMerchantId
(\ s a -> s{_flgMerchantId = a})
. _Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
flgUploadProtocol :: Lens' FreeListingsprogramGet (Maybe Text)
flgUploadProtocol
= lens _flgUploadProtocol
(\ s a -> s{_flgUploadProtocol = a})
-- | OAuth access token.
flgAccessToken :: Lens' FreeListingsprogramGet (Maybe Text)
flgAccessToken
= lens _flgAccessToken
(\ s a -> s{_flgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
flgUploadType :: Lens' FreeListingsprogramGet (Maybe Text)
flgUploadType
= lens _flgUploadType
(\ s a -> s{_flgUploadType = a})
-- | JSONP
flgCallback :: Lens' FreeListingsprogramGet (Maybe Text)
flgCallback
= lens _flgCallback (\ s a -> s{_flgCallback = a})
instance GoogleRequest FreeListingsprogramGet where
type Rs FreeListingsprogramGet =
FreeListingsProgramStatus
type Scopes FreeListingsprogramGet =
'["https://www.googleapis.com/auth/content"]
requestClient FreeListingsprogramGet'{..}
= go _flgMerchantId _flgXgafv _flgUploadProtocol
_flgAccessToken
_flgUploadType
_flgCallback
(Just AltJSON)
shoppingContentService
where go
= buildClient
(Proxy :: Proxy FreeListingsprogramGetResource)
mempty
| brendanhay/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/FreeListingsprogram/Get.hs | mpl-2.0 | 4,936 | 0 | 17 | 1,143 | 724 | 421 | 303 | 107 | 1 |
-- Introduction
-- This is Vocabulink, the SCGI program that handles all web requests for
-- http://www.vocabulink.com/. The site helps people learn languages through
-- fiction. It provides a mnemonics database and spaced repetion (review)
-- tools.
-- Architecture
-- Requests arrive via a webserver. (I'm currently using lighttpd, but it
-- should work with any server that supports SCGI.) They are passed to the
-- vocabulink.cgi process (this program) on TCP port 10033 of the local
-- loopback interface.
-- Upon receiving a request (connection), we immediately fork a new thread. In
-- this thread, we establish a connection to a PostgreSQL server (for each
-- request). We then examine the request for an authentication cookie. If it
-- exists and is valid, we consider the request to have originated from an
-- authenticated member. We pack both the database handle and the authenticated
-- member information into our App monad and then pass control to a function
-- based on the request method and URI.
module Main where
import Vocabulink.API
import Vocabulink.Article
import Vocabulink.CGI
import Vocabulink.Comment
import Vocabulink.Env
import Vocabulink.Html hiding (method, dl)
import Vocabulink.Link
import Vocabulink.Member
import Vocabulink.Member.Html
import Vocabulink.Member.Registration
import Vocabulink.Page
import Vocabulink.Reader
import Vocabulink.Review
import Vocabulink.Utils
import Prelude hiding (div, span, id, words)
import Control.Exception (bracket, SomeException, Handler(..), catches, try)
import Data.Bits ((.|.))
import Data.String.Conv (toS)
import Database.PostgreSQL.Typed (PGDatabase(pgDBAddr, pgDBName, pgDBUser), pgConnect, pgDisconnect, defaultPGDatabase)
import Network.HTTP.Types (status500, status302)
import Network.Socket (socket, bind, listen, close, SockAddr(SockAddrUnix), Family(AF_UNIX), SocketType(Stream))
import Network.Wai (requestHeaders, requestHeaderReferer, responseLBS)
import Network.Wai.Handler.Warp (runSettingsSocket, defaultSettings, setServerName)
import Servant (Proxy(Proxy), serve, (:<|>) ((:<|>)), NoContent(NoContent))
import System.Directory (removeFile)
import System.Environment (getArgs, getProgName)
import System.IO (hPutStrLn, stderr)
import System.Posix.Files (setFileMode, ownerReadMode, ownerWriteMode, groupReadMode, groupWriteMode, otherReadMode, otherWriteMode)
import Web.Cookie (parseCookies)
main = do
args <- getArgs
case args of
[staticPath, sendmail, tokenKey] -> do
bracket
(socket AF_UNIX Stream 0)
(\ sock -> do
close sock
try' (removeFile "vocabulink.sock"))
(\ sock -> do
bind sock (SockAddrUnix "vocabulink.sock")
setFileMode "vocabulink.sock" (ownerReadMode .|. ownerWriteMode .|. groupReadMode .|. groupWriteMode .|. otherReadMode .|. otherWriteMode)
listen sock 1024
runSettingsSocket (setServerName "" defaultSettings) sock (handleRequest staticPath sendmail tokenKey))
_ -> do
progName <- getProgName
hPutStrLn stderr ("Usage: " ++ progName ++ " static-dir sendmail token-key")
where try' :: IO a -> IO (Either SomeException a)
try' = try
handleRequest staticPath sendmail tokenKey req sendResponse = do
bracket
(pgConnect defaultPGDatabase {pgDBAddr = Right (SockAddrUnix "/var/run/postgresql/.s.PGSQL.5432"), pgDBName = "vocabulink", pgDBUser = "vocabulink"})
pgDisconnect
(\ db -> do
member <- loggedIn db
let ?db = db
?static = staticPath
?sendmail = sendmail
?tokenKey = tokenKey
?member = member
?referrer = (toS `fmap` requestHeaderReferer req) :: Maybe String
vocabulinkApp req sendResponse `catches` [Handler (vocabulinkHandler sendResponse), Handler defaultHandler])
where loggedIn db = do
let auth = (lookup "auth" . parseCookies) =<< (lookup "Cookie" (requestHeaders req))
token' <- maybe (return Nothing) (validAuth tokenKey . toS) auth
case token' of
Nothing -> return Nothing
Just token -> do
row <- $(queryTuple
"SELECT username, email FROM member \
\WHERE member_no = {authMemberNumber token}") db
return ((\(username, email) -> Member { memberNumber = authMemberNumber token
, memberName = username
, memberEmail = email
}) `fmap` row)
defaultHandler :: SomeException -> _
defaultHandler _ = sendResponse $ responseLBS status500 [] "An error occurred."
vocabulinkHandler sendResponse (VError msg) =
let (headers, body) = redirectWithMsg' referrerOrVocabulink [] MsgError msg
in sendResponse (responseLBS status302 headers body)
vocabulinkApp = serve (Proxy :: Proxy VocabulinkAPI) app
where app = liftIO frontPage
:<|> redirect "https://github.com/jekor/vocabulink/tarball/master"
-- Some permanent URIs are essentially static files. To display them, we make
-- use of the article system (formatting, metadata, etc). You could call these
-- elevated articles. We use articles because the system for managing them
-- exists already (revision control, etc)
-- Each @.html@ file is actually an HTML fragment. These happen to be generated
-- from Muse Mode files by Emacs, but we don't really care where they come
-- from.
-- Other articles are dynamic and can be created without recompilation. We just
-- have to rescan the filesystem for them. They also live in the @/article@
-- namespace (specifically at @/article/title@).
:<|> ((maybeNotFound . liftIO . articlePage)
-- We have 1 page for getting a listing of all published articles.
:<|> liftIO articlesPage
:<|> maybeNotFound (liftIO (articlePage "help"))
:<|> maybeNotFound (liftIO (articlePage "privacy"))
:<|> maybeNotFound (liftIO (articlePage "terms-of-use"))
:<|> maybeNotFound (liftIO (articlePage "source"))
:<|> maybeNotFound (liftIO (articlePage "api")))
-- Link Pages
-- Vocabulink revolves around links---the associations between words or ideas. As
-- with articles, we have different functions for retrieving a single link or a
-- listing of links. However, the dispatching is complicated by the fact that
-- members can operate upon links (we need to handle the @POST@ method).
-- For clarity, this dispatches:
-- GET /link/10 → link page
-- POST /link/10/stories → add a linkword story
:<|> ((\ n -> maybeNotFound (liftIO (getStory n))
:<|> (\ story -> liftIO (editStory n story) >> return NoContent)
:<|> (\ data' -> do
let story = bodyVarRequired "story" data'
liftIO $ editStory n story
-- TODO: This redirect masks the result of editStory
redirect (toS referrerOrVocabulink)))
-- TODO: Find a way to negotiate content types without always rendering the link HTML
-- (which is not needed for the JSON case).
:<|> (\ n -> maybeNotFound (liftIO ((\ l -> case l of Nothing -> return Nothing; Just l' -> (Just . LinkOutput l') `fmap` linkPage l') =<< linkDetails n))
:<|> maybeNotFound (liftIO ((\ l -> case l of Nothing -> return Nothing; Just l' -> Just `fmap` compactLinkPage l') =<< linkDetails n))
-- TODO: 404 when link number doesn't exist
:<|> liftIO (linkStories n)
:<|> (\ data' -> do
let story = bodyVarRequired "story" data'
liftIO $ addStory n story
-- TODO: This redirect masks the result of editStory
redirect (toS ("/link/" ++ show n)))))
-- Retrieving a listing of links is easier.
:<|> (\ (Language ol) (Language dl) -> do
links <- liftIO (languagePairLinks ol dl)
liftIO (linksPage ("Links from " ++ ol ++ " to " ++ dl) links))
-- Readers
:<|> (\ lang name' page -> maybeNotFound (liftIO (readerPage lang name' page)))
-- Searching
:<|> (\ q -> do
links <- if q == ""
then return []
else liftIO (linksContaining q)
liftIO (linksPage ("Search Results for \"" <> q <> "\"") links))
-- Review
-- Members review their links by interacting with the site in a vaguely
-- REST-ish way. The intent behind this is that in the future they will be able
-- to review their links through different means such as a desktop program or a
-- phone application.
-- GET /review → review page (app)
-- PUT /review/n → add a link for review
-- GET /review/next → retrieve the next links for review
-- POST /review/n → mark link as reviewed
-- (where n is the link number)
-- Reviewing links is one of the only things that logged-in-but-unverified
-- members are allowed to do.
:<|> ((\ (Language learn) (Language known) -> liftIO (reviewPage learn known))
:<|> (\ n -> withLoggedInMember (\ m -> liftIO (newReview m n) >> return NoContent))
:<|> withLoggedInMember (liftIO . reviewStats)
:<|> (\ statType start end tzOffset ->
withLoggedInMember (\ m -> liftIO ((case statType of StatTypeDaily -> dailyReviewStats; StatTypeDetailed -> detailedReviewStats) m start end tzOffset)))
:<|> (\ n data' ->
do let grade = read (bodyVarRequired "grade" data')
recallTime = read (bodyVarRequired "time" data')
reviewedAt' = maybe Nothing readMaybe (bodyVar "when" data')
reviewedAt <- case reviewedAt' of
Nothing -> liftIO epochTime
Just ra -> return ra
-- TODO: Sanity-check this time. It should at least not be in the future.
withLoggedInMember (\ m -> liftIO $ scheduleNextReview m n grade recallTime reviewedAt >> return NoContent)))
-- Dashboard
:<|> withLoggedInMember (const (liftIO dashboardPage))
-- Membership
-- Becoming a member is simply a matter of filling out a form.
-- Note that in some places where I would use a PUT I've had to append a verb
-- to the URL and use a POST instead because these requests are often made to
-- HTTPS pages from HTTP pages and can't be done in JavaScript without a lot of
-- not-well-supported cross-domain policy hacking.
:<|> ((\ data' ->
let username = bodyVarRequired "username" data'
email = bodyVarRequired "email" data'
password = bodyVarRequired "password" data'
learned = bodyVar "learned" data'
in liftIO (signup username email password learned) >>= \ c -> cookieBounce [c] MsgSuccess "Welcome! Please check your email to confirm your account.")
-- But to use most of the site, we require email confirmation.
:<|> (\ hash -> liftIO (confirmEmail hash) >>= \case
Left pg -> return pg
Right c -> cookieBounce [c] MsgSuccess "Congratulations! You've confirmed your account.")
:<|> (case ?member of
Nothing -> do
liftIO (simplePage "Please Login to Resend Your Confirmation Email" [ReadyJS "V.loginPopup();"] mempty)
Just m -> do
liftIO $ resendConfirmEmail m
bounce MsgSuccess "Your confirmation email has been sent.")
-- Logging in is a similar process.
:<|> (\ data' -> do
let userid = bodyVarRequired "userid" data'
password = bodyVarRequired "password" data'
liftIO (login userid password) >>= \ c -> cookieBounce [c] MsgSuccess "Login successful.")
-- Logging out can be done without a form.
:<|> cookieRedirect [emptyAuthCookie {setCookieMaxAge = Just (secondsToDiffTime 0)}] "https://www.vocabulink.com/"
:<|> (\ data' -> do
let password = bodyVarRequired "password" data'
liftIO (deleteAccount password)
cookieBounce [emptyAuthCookie {setCookieMaxAge = Just $ secondsToDiffTime 0}] MsgSuccess "Your account was successfully deleted.")
:<|> ((\ data' -> do
let email = bodyVarRequired "email" data'
liftIO (sendPasswordReset email)
bounce MsgSuccess "Password reset instructions have been sent to your email.")
:<|> (liftIO . passwordResetPage)
:<|> (\ hash data' -> do
let password = bodyVarRequired "password" data'
liftIO (passwordReset hash password) >>= \ c -> cookieBounce [c] MsgSuccess "Password reset successfully.")
:<|> (\ data' -> do
let oldPassword = bodyVarRequired "old-password" data'
newPassword = bodyVarRequired "new-password" data'
liftIO (changePassword oldPassword newPassword)
bounce MsgSuccess "Password changed successfully."))
:<|> (\ data' -> do
let email = bodyVarRequired "email" data'
password = bodyVarRequired "password" data'
liftIO (changeEmail email password)
bounce MsgSuccess "Email address changed successfully. Please check your email to confirm the change."))
-- Member Pages
:<|> (\ username ->
maybeNotFound (liftIO (maybe (return Nothing) (\ m -> memberPage m >>= \ m' -> return (Just m')) =<< memberByName username))
:<|> liftIO (usernameAvailable username))
:<|> (liftIO . emailAvailable)
-- ``reply'' is used here as a noun.
:<|> (\ n data' -> do
let body = bodyVarRequired "body" data'
liftIO $ withVerifiedMember (\m -> storeComment (memberNumber m) body (Just n))
redirect (toS referrerOrVocabulink))
-- Everything Else
-- For Google Webmaster Tools, we need to respond to a certain URI that acts as
-- a kind of ``yes, we really do run this site''.
:<|> return (unlines [ "User-agent: *"
, "Disallow:" ])
:<|> return "google-site-verification: google1e7c25c4bdfc5be7.html"
-- Finally, we get to an actual page of the site: the front page.
frontPage = do
mainButton <- case ?member of
Nothing -> return buyButton
Just m -> do
row <- $(queryTuple "SELECT page_no \
\FROM member_reader \
\INNER JOIN reader USING (reader_no) \
\WHERE short_name = 'para-bailar' AND lang = 'es' AND member_no = {memberNumber m}") ?db
return $ case row of
Nothing -> buyButton
Just pageNo -> div ! class_ "button_buy" $ do
a ! href (toValue $ "/reader/es/para-bailar/" ++ show (pageNo :: Int32)) ! class_ "gradient" ! title "Continue Reading" $ do
span ! class_ "button_price" $ "Continue"
span ! class_ "button_text" $ "Reading"
stdPage ("Learn Spanish Through Fiction - Vocabulink") [] (do
meta ! name "viewport" ! content "width=device-width, initial-scale=1.0, user-scalable=no"
preEscapedToMarkup ("<link rel=\"stylesheet\" href=\"//s.vocabulink.com/css/off-the-shelf.css\" media=\"screen, projection\"> \
\<link href=\"//netdna.bootstrapcdn.com/font-awesome/3.2.0/css/font-awesome.css\" rel=\"stylesheet\">"::String)) $ do
section ! id "banner" $ do
div ! class_ "row" $ do
div ! id "shelf" ! class_ "one_half" $ do
img ! alt "book cover" ! width "331" ! height "497" ! src "//s.vocabulink.com/img/reader/es/para-bailar.jpg"
div ! class_ "one_half last" $ do
hgroup $ do
h1 $ "Learn Spanish Through Fiction"
h2 ! class_ "subheader" $ "Read real everyday Spanish. Learn new words in context. Designed for beginners, written for adults."
p $ "Learning doesn't have to be boring. Stories have entertained and educated for centuries. This book is a collection of stories that will teach you some of the basics of Spanish."
p $ "This isn't like any language reader you've seen before. We've designed it by mixing 4 modern accelerated language learning techniques."
mainButton
article $ do
div ! id "main_content" $ do
section ! id "features" $ do
div ! class_ "row" $ do
h2 ! class_ "section_title" $ do
span $ "Accelerated Learning Features"
ul $ do
li ! class_ "one_half" $ do
i ! class_ "icon-road icon-4x" $ mempty
h4 "Gradual Progression"
p "Have you ever tried reading Spanish but just go frustrated and gave up? Our stories start with very simple sentences. Then, gradually over time we introduce new words and new grammar."
li ! class_ "one_half last" $ do
i ! class_ "icon-magic icon-4x" $ mempty
h4 "Linkword Mnemonics"
p "Instead of staring at a list of vocabulary or writing words out 100 times, wouldn't it be nice to have a trick to remember each word by? We thought so too. That's why we've included mnemonics for each word we introduce you to."
li ! class_ "one_half" $ do
i ! class_ "icon-sort-by-attributes-alt icon-4x" $ mempty
h4 "Words Selected by Frequency"
p "Why waste time learning words you're rarely, if ever, going to use? We analyzed how frequently words occur in written and spoken Spanish and use only words among the most common 3,000."
li ! class_ "one_half last" $ do
i ! class_ "icon-bar-chart icon-4x" $ mempty
h4 "Spaced Repetition"
p "Flashcards are great, but we have better technology today. We use a special algorithm to schedule optimal times for you to review each word that you learn. This algorithm adapts to your memory and the difficulty of each word."
where buyButton = div ! class_ "button_buy" $ do
a ! href "/reader/es/para-bailar/1" ! class_ "gradient" ! title "Preview for Free" $ do
span ! class_ "button_price" $ "Start"
span ! class_ "button_text" $ "Reading"
| jekor/vocabulink | hs/Vocabulink.hs | agpl-3.0 | 18,955 | 0 | 39 | 5,583 | 3,566 | 1,816 | 1,750 | -1 | -1 |
-----------------------------------------------------------------------------------------
{-| Module : CompileClassInfo
Copyright : (c) Daan Leijen 2003, 2004
License : BSD-style
Maintainer : [email protected]
Stability : provisional
Portability : portable
Module that compiles class types to a Haskell module for safe casting
-}
-----------------------------------------------------------------------------------------
module CompileClassInfo( compileClassInfo ) where
import Data.Char( toLower )
import Data.List( sortBy {-, sort-} )
-- import Types
import HaskellNames
import Classes
import IOExtra
{-----------------------------------------------------------------------------------------
Compile
-----------------------------------------------------------------------------------------}
compileClassInfo :: Bool -> String -> String -> String -> String -> FilePath -> IO ()
compileClassInfo _verbose moduleRoot moduleClassesName moduleClassTypesName moduleName outputFile
= do let classNames' = sortBy cmpName objectClassNames
(classExports,classDefs) = unzip (map toHaskellClassType classNames')
(downcExports,downcDefs) = unzip (map toHaskellDowncast classNames')
defCount = length classNames'
export = concat [ ["module " ++ moduleRoot ++ moduleName
, " ( -- * Class Info"
, " ClassType, classInfo, instanceOf, instanceOfName"
, " -- * Safe casts"
, " , safeCast, ifInstanceOf, whenInstanceOf, whenValidInstanceOf"
, " -- * Class Types"
]
, map (exportComma++) classExports
, [ " -- * Down casts" ]
, map (exportComma++) downcExports
, [ " ) where"
, ""
, "import System.IO.Unsafe( unsafePerformIO )"
, "import " ++ moduleRoot ++ moduleClassTypesName
, "import " ++ moduleRoot ++ "WxcTypes"
, "import " ++ moduleRoot ++ moduleClassesName
, ""
, "-- | The type of a class."
, "data ClassType a = ClassType (ClassInfo ())"
, ""
, "-- | Return the 'ClassInfo' belonging to a class type. (Do not delete this object, it is statically allocated)"
, "{-# NOINLINE classInfo #-}"
, "classInfo :: ClassType a -> ClassInfo ()"
, "classInfo (ClassType info) = info"
, ""
, "-- | Test if an object is of a certain kind. (Returns also 'True' when the object is null.)"
, "{-# NOINLINE instanceOf #-}"
, "instanceOf :: WxObject b -> ClassType a -> Bool"
, "instanceOf obj (ClassType classInfo') "
, " = if (objectIsNull obj)"
, " then True"
, " else unsafePerformIO (objectIsKindOf obj classInfo')"
, ""
, "-- | Test if an object is of a certain kind, based on a full wxWidgets class name. (Use with care)."
, "{-# NOINLINE instanceOfName #-}"
, "instanceOfName :: WxObject a -> String -> Bool"
, "instanceOfName obj className "
, " = if (objectIsNull obj)"
, " then True"
, " else unsafePerformIO ("
, " do classInfo' <- classInfoFindClass className"
, " if (objectIsNull classInfo')"
, " then return False"
, " else objectIsKindOf obj classInfo')"
, ""
, "-- | A safe object cast. Returns 'Nothing' if the object is of the wrong type. Note that a null object can always be cast."
, "safeCast :: WxObject b -> ClassType (WxObject a) -> Maybe (WxObject a)"
, "safeCast obj classType"
, " | instanceOf obj classType = Just (objectCast obj)"
, " | otherwise = Nothing"
, ""
, "-- | Perform an action when the object has the right type /and/ is not null."
, "whenValidInstanceOf :: WxObject a -> ClassType (WxObject b) -> (WxObject b -> IO ()) -> IO ()"
, "whenValidInstanceOf obj classType f"
, " = whenInstanceOf obj classType $ \\object ->"
, " if (object==objectNull) then return () else f object"
, ""
, "-- | Perform an action when the object has the right kind. Note that a null object has always the right kind."
, "whenInstanceOf :: WxObject a -> ClassType (WxObject b) -> (WxObject b -> IO ()) -> IO ()"
, "whenInstanceOf obj classType f"
, " = ifInstanceOf obj classType f (return ())"
, ""
, "-- | Perform an action when the object has the right kind. Perform the default action if the kind is not correct. Note that a null object has always the right kind."
, "ifInstanceOf :: WxObject a -> ClassType (WxObject b) -> (WxObject b -> c) -> c -> c"
, "ifInstanceOf obj classType yes no"
, " = case safeCast obj classType of"
, " Just object -> yes object"
, " Nothing -> no"
, ""
]
]
prologue = getPrologue moduleName "class info"
(show defCount ++ " class info definitions.") []
putStrLn ("generating: " ++ outputFile)
writeFileLazy outputFile (unlines (prologue ++ export ++ classDefs ++ downcDefs))
putStrLn ("generated " ++ show defCount ++ " class info definitions")
putStrLn "ok."
cmpName :: String -> String -> Ordering
cmpName s1 s2
= compare (map toLower (haskellTypeName s1)) (map toLower (haskellTypeName s2))
{-
cmpDef :: Def -> Def -> Ordering
cmpDef def1 def2
= compare (defName def1) (defName def2)
-}
exportComma :: String
exportComma = exportSpaces ++ ","
exportSpaces :: String
exportSpaces = " "
{-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------}
toHaskellClassType :: String -> (String,String)
toHaskellClassType className
= (classTypeDeclName
,"{-# NOINLINE " ++ classTypeDeclName ++ " #-}\n" ++
classTypeDeclName ++ " :: ClassType (" ++ classTypeName' ++ " ())\n" ++
classTypeDeclName ++ " = ClassType (unsafePerformIO (classInfoFindClass " ++ classTypeString ++ "))\n\n"
)
where
classTypeDeclName :: String
classTypeDeclName = haskellDeclName ("class" ++ classTypeName')
classTypeName' :: String
classTypeName' = haskellTypeName className
classTypeString :: String
classTypeString = "\"" ++ className ++ "\""
{-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------}
toHaskellDowncast :: String -> (String,String)
toHaskellDowncast className
= (downcastName
,downcastName ++ " :: " ++ classTypeName' ++ " a -> " ++ classTypeName' ++ " ()\n" ++
downcastName ++ " obj = objectCast obj\n\n"
)
where
classTypeName' = haskellTypeName className
downcastName = haskellDeclName ("downcast" ++ classTypeName')
| sherwoodwang/wxHaskell | wxdirect/src/CompileClassInfo.hs | lgpl-2.1 | 8,756 | 0 | 15 | 3,538 | 816 | 461 | 355 | 112 | 1 |
-- mapM & mapM_
-- Because mapping a function that returns an I/O action over a list and then sequencing
-- it is so common, the utility functions mapM and mapM_ were introduced.
-- mapM takes a function and a list, maps the function over the list and sequence it.
-- mapM_ does the same thing but throws away the result later | Ketouem/learn-you-a-haskell | src/chapter-8-input-and-output/useful-io-fns/mapM.hs | unlicense | 327 | 0 | 2 | 62 | 7 | 6 | 1 | 1 | 0 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Handler.Root
( getRootR
) where
import Foundation
import Handler.Page (getPageR')
getRootR :: Handler RepHtml
getRootR = getPageR' []
| snoyberg/yesodcms | Handler/Root.hs | bsd-2-clause | 216 | 0 | 6 | 35 | 43 | 25 | 18 | 7 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Yesod.Default.Main
( defaultMain
, defaultRunner
, defaultDevelApp
) where
import Yesod.Default.Config
import Yesod.Logger (Logger, defaultDevelopmentLogger, logString)
import Network.Wai (Application)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import System.Directory (doesDirectoryExist, removeDirectoryRecursive)
import Network.Wai.Middleware.Gzip (gzip, GzipFiles (GzipCacheFolder), gzipFiles, def)
import Network.Wai.Middleware.Autohead (autohead)
import Network.Wai.Middleware.Jsonp (jsonp)
import Control.Monad (when)
#ifndef WINDOWS
import qualified System.Posix.Signals as Signal
import Control.Concurrent (forkIO, killThread)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
#endif
-- | Run your app, taking environment and port settings from the
-- commandline.
--
-- Use @'fromArgs'@ when using the provided @'DefaultEnv'@ type, or
-- @'fromArgsWith'@ when using a custom type
--
-- > main :: IO ()
-- > main = defaultMain fromArgs withMySite
--
-- or
--
-- > main :: IO ()
-- > main = defaultMain (fromArgsWith customArgConfig) withMySite
--
defaultMain :: (Show env, Read env)
=> IO (AppConfig env extra)
-> (AppConfig env extra -> Logger -> IO Application)
-> IO ()
defaultMain load getApp = do
config <- load
logger <- defaultDevelopmentLogger
app <- getApp config logger
runSettings defaultSettings
{ settingsPort = appPort config
} app
-- | Run your application continously, listening for SIGINT and exiting
-- when recieved
--
-- > withYourSite :: AppConfig DefaultEnv -> Logger -> (Application -> IO a) -> IO ()
-- > withYourSite conf logger f = do
-- > Settings.withConnectionPool conf $ \p -> do
-- > runConnectionPool (runMigration yourMigration) p
-- > defaultRunner f $ YourSite conf logger p
defaultRunner :: (Application -> IO ()) -> Application -> IO ()
defaultRunner f app = do
-- clear the .static-cache so we don't have stale content
exists <- doesDirectoryExist staticCache
when exists $ removeDirectoryRecursive staticCache
#ifdef WINDOWS
f (middlewares app)
#else
tid <- forkIO $ f (middlewares app) >> return ()
flag <- newEmptyMVar
_ <- Signal.installHandler Signal.sigINT (Signal.CatchOnce $ do
putStrLn "Caught an interrupt"
killThread tid
putMVar flag ()) Nothing
takeMVar flag
#endif
where
middlewares = gzip gset . jsonp . autohead
gset = def { gzipFiles = GzipCacheFolder staticCache }
staticCache = ".static-cache"
-- | Run your development app using a custom environment type and loader
-- function
defaultDevelApp
:: (Show env, Read env)
=> IO (AppConfig env extra) -- ^ A means to load your development @'AppConfig'@
-> (AppConfig env extra -> Logger -> IO Application) -- ^ Get your @Application@
-> IO (Int, Application)
defaultDevelApp load getApp = do
conf <- load
logger <- defaultDevelopmentLogger
let p = appPort conf
logString logger $ "Devel application launched, listening on port " ++ show p
app <- getApp conf logger
return (p, app)
| chreekat/yesod | yesod-default/Yesod/Default/Main.hs | bsd-2-clause | 3,276 | 0 | 11 | 701 | 589 | 330 | 259 | 56 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
------------------------------------------------------------------------------
module OpenArms.Types.AttendeePrivateNote
( -- * Types
AttendeePrivateNote (..)
, columnOffsetsAttendeePrivateNote
, tableOfAttendeePrivateNote
, attendeePrivateNote
, insertAttendeePrivateNote
, insertQueryAttendeePrivateNote
, selectAttendeePrivateNote
, updateAttendeePrivateNote
, fromSqlOfAttendeePrivateNote
, toSqlOfAttendeePrivateNote
, id'
, attendeeId'
, createdBy'
, note'
, created'
, deleted'
) where
------------------------------------------------------------------------------
import OpenArms.Util
------------------------------------------------------------------------------
$(defineTable "attendee_private_note")
| dmjio/openarms | src/OpenArms/Types/AttendeePrivateNote.hs | bsd-2-clause | 957 | 0 | 7 | 198 | 83 | 55 | 28 | 23 | 0 |
module WASH.HTML.HTMLTemplates where
import WASH.HTML.HTMLBase
import WASH.Utility.SHA1
import WASH.Utility.JavaScript
import qualified WASH.Utility.Base32 as Base32
import Control.Monad (unless)
import Data.List ((\\))
data ST s a = ST { unST :: s -> (a, s) }
instance Monad (ST s) where
return x = ST (\s -> (x, s))
m >>= f = ST (\s -> let (x', s') = unST m s
in unST (f x') s')
runST :: s -> ST s a -> a
runST s m = fst (unST m s)
getST :: ST s s
getST = ST (\s -> (s, s))
setST :: s -> ST s ()
setST s = ST (const ((), s))
data Names = Names { ntable :: [(String, Int)], nseen :: [Int] }
----------------------------------------------------------------------
-- template generation
----------------------------------------------------------------------
showTemplatified :: ELEMENT_ -> ShowS
showTemplatified = showTemplate . analyze
showTemplate :: (Template, Mt) -> ShowS
showTemplate (tis, mt) =
let ts = closed mt
ndefs = length ts
at = actuals mt
st = buildStringTableArgs at
cst = cleanupStringTable ndefs st
shownargs = runST (Names { ntable = cst, nseen = [] })
(showActualArgs at)
in
showDefinitions ndefs ts .
showString "<script name=\"BODY\">\n" .
-- showStringTable cst .
showString "S(" . shownargs . showString ",document)" .
showString "\n</script>\n"
showDefinitions n [] =
let scriptName = "STRINGBASE"
in
showString "<script name=\"" . showString scriptName . showString "\">\n" .
showString "function S (template, out) {\n" .
showString " var ty = typeof template;\n" .
showString " if (ty == \"string\") out.write (template);\n" .
showString " else if (ty == \"object\")\n" .
showString " for (var i = 0; i<template.length; i++)\n" .
showString " S (template[i], out);\n" .
showString "}\n" .
showString "</script>\n"
showDefinitions n ((scriptName, (nr, nformals, t1)) :ts) =
showString "<script name=\"" . showString scriptName . showString "\">\n" .
(if nformals==0 then showString "var " else showString "function ") . showsIdent n .
(if nformals==0 then showString "=" else showString "(" . showFormals nformals . showString ")" .
showString "{return") .
showString "[" .
showBody t1 .
showString "]" .
(if nformals==0 then id else showString "}\n") .
showString "</script>\n" .
showDefinitions (n-1) ts
showsIdent n = showString (identlist !! n)
charlist = (['A'..'Z'] ++ ['a'..'z'])
alphanumlist = ['0'..'9'] ++ charlist
identlist = ([ [c] | c <- charlist ]
++ [ [c,d] | c <- charlist, d <- alphanumlist ])
\\ ["S","o","v"]
showBody [] =
id
showBody [ti] =
showStatement ti
showBody (ti:tis) =
showBody tis .
showString "," .
showStatement ti
showStatement (TOut str) =
showString (jsShow str)
showStatement (TVar n) =
showsIdent n
showStatement (TCall fname args) =
error "this should not happen"
showFormals 0 =
id
showFormals n =
(if n>1 then showFormals (n-1) . showString "," else id) .
showsIdent n
showActual (TOut str) =
do names <- getST
let cst = ntable names
seen = nseen names
case lookup str cst of
Nothing ->
return $ showString (jsShow str)
Just strident ->
if strident `elem` seen
then return $ showsIdent strident
else
do setST (names { nseen = strident : seen })
return $
(showsIdent strident . showChar '=' . showString (jsShow str))
showActual (TVar n) =
error "this should not happen"
showActual (TCall fname []) =
return $ showsIdent fname
showActual (TCall fname args) =
do saa <- showActualArgs args
return (showsIdent fname . showString "(" .
saa .
showString ")")
showActualArgs [] =
return id
showActualArgs [arg] =
showActualArg arg
showActualArgs (arg: args) =
do x1 <- showActualArgs args
x2 <- showActualArg arg
return (x1 . showString "," . x2)
showActualArg [x] =
showActual x
showActualArg xs =
do hxs <- h xs
return (showString "[" . hxs . showString "]")
where
h [] = return id
h [x] = showActual x
h (x:xs) = do sax <- showActual x
hxs <- h xs
return (sax . showChar ',' . hxs)
showStringTable =
foldr g id
where
g (str, n) showrest =
showString "var " . showsIdent n . showString "=" . showString (jsShow str) .
showString ";\n" . showrest
cleanupStringTable ndefs st =
zip [str | (str, n) <- st, n > 3 || length str > 2 && n > 1]
[(ndefs+1) ..]
unite st1 st2 =
foldr g st1 st2
where g p@(str,i) st1 =
case lookup str st1 of
Nothing -> p:st1
Just j -> (str, i+j):[ p | (p@(str',_)) <- st1, str' /= str ]
buildStringTableArgs =
foldr unite [] . map buildStringTableArg
buildStringTableArg =
foldr unite [] . map buildStringTableActual
buildStringTableActual (TOut str) =
[(str, 1)]
buildStringTableActual (TVar n) =
error "this should not happen"
buildStringTableActual (TCall fname args) =
buildStringTableArgs args
----------------------------------------------------------------------
-- template analysis
----------------------------------------------------------------------
analyze :: ELEMENT_ -> (Template, Mt)
analyze e = unM (collect e STATIC []) mt0
data Mt = Mt
{ open :: Templates
, closed :: [(String, (Int, Int, Template))]
, dynamics :: [Templates]
, actuals :: Templates
, count :: Int
}
deriving Show
mt0 = Mt { open = []
, closed = []
, dynamics = []
, actuals = []
, count = 0
}
type Templates = [Template]
type Template = [TemplateItem]
data TemplateItem
= TOut String
| TVar Int
| TCall Int [Template]
deriving Show
tout :: String -> [TemplateItem] -> [TemplateItem]
tout s (TOut s' : rest) = (TOut (s'++s) : rest)
tout s tis = TOut s : tis
data M a = M { unM :: Mt -> (a, Mt) }
instance Monad M where
return a = M (\t -> (a, t))
m >>= f = M (\t -> let (a,t') = unM m t in unM (f a) t')
pushOpen :: Template -> M ()
pushOpen t = M (\mt -> ((), mt { open = t : open mt
, dynamics = actuals mt : dynamics mt
, actuals = []
} ))
popOpen :: M Template
popOpen = M (\mt -> (head (open mt), mt { open = tail (open mt)
, actuals = head (dynamics mt)
, dynamics = tail (dynamics mt)
}))
pushClosed :: Template -> M Int
pushClosed tis =
M (\mt ->
let defs = closed mt
name = Base32.encode (sha1 (show tis))
in
case lookup name defs of
Nothing ->
let next = length (closed mt) + 1 in
(next, mt { closed = (name, (next, length (actuals mt), tis)) : defs })
Just (last, nargs, _) ->
(last, mt))
pushActuals :: Template -> M Int
pushActuals tis =
M (\mt -> (length (actuals mt) + 1, mt { actuals = tis : actuals mt }))
getActuals :: M Templates
getActuals = M (\mt -> (actuals mt, mt))
get :: (Mt -> x) -> M x
get f = M (\mt -> (f mt, mt))
mergeActuals :: Template -> M ()
mergeActuals tis =
M (\mt ->
let act0 : acts = actuals mt in
((), mt { actuals = (act0 ++ tis) : actuals mt }))
maybePushActuals :: Template -> Template -> M Template
maybePushActuals cur tis =
case cur of
TVar _ : _ ->
do mergeActuals tis
return cur
_ ->
do vname <- pushActuals tis
return (TVar vname : cur)
-- |collect takes an element, a list of open templates, a list of finished
-- templates, and returns a pair (open templates, finished templates).
collect :: ELEMENT_ -> BT -> Template -> M Template
collect (EMPTY_ bt tag atts) cbt cur =
let t1 = TOut ('<' : tag)
t2 = tout "/>"
in
case bt of
TOPLEVEL ->
do pushOpen cur
ts <- collectAttrs atts STATIC [t1]
fname <- pushClosed (t2 ts)
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
DYNAMIC ->
case cbt of
STATIC ->
do ts <- collectAttrs atts DYNAMIC [t1]
maybePushActuals cur (t2 ts)
DYNAMIC ->
do ts <- collectAttrs atts DYNAMIC (t1 : cur)
return (t2 ts)
STATIC ->
case cbt of
STATIC ->
do ts <- collectAttrs atts STATIC (t1 : cur)
return (t2 ts)
DYNAMIC ->
do pushOpen cur
ts <- collectAttrs atts STATIC [t1]
fname <- pushClosed (t2 ts)
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
collect (ELEMENT_ bt tag atts elems) cbt cur =
let t1 = TOut ('<' : tag)
t1' = tout ('<' : tag)
t2 = tout ">"
t3 = tout ("</" ++ tag ++ ">")
in
case bt of
TOPLEVEL ->
do pushOpen cur
ts1 <- collectAttrs atts STATIC [t1]
ts2 <- collectElems elems STATIC (t2 ts1)
fname <- pushClosed (t3 ts2)
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
DYNAMIC ->
case cbt of
STATIC ->
do ts1 <- collectAttrs atts DYNAMIC [t1]
ts2 <- collectElems elems DYNAMIC (t2 ts1)
maybePushActuals cur (t3 ts2)
DYNAMIC ->
do ts1 <- collectAttrs atts DYNAMIC (t1' cur)
ts2 <- collectElems elems DYNAMIC (t2 ts1)
return (t3 ts2)
STATIC ->
case cbt of
STATIC ->
do ts1 <- collectAttrs atts STATIC (t1' cur)
ts2 <- collectElems elems STATIC (t2 ts1)
return (t3 ts2)
DYNAMIC ->
do pushOpen cur
ts1 <- collectAttrs atts STATIC [t1]
ts2 <- collectElems elems STATIC (t2 ts1)
fname <- pushClosed (t3 ts2)
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
collect (DOCTYPE_ bt strs elems) cbt cur =
let t1 = TOut ("<!DOCTYPE" ++
(foldr (\str f -> showChar ' ' . showString str . f) id strs .
showString ">")
"<!-- generated by WASH/HTML 0.11\n-->")
in
case bt of
TOPLEVEL ->
do pushOpen cur
ts2 <- collectElems elems STATIC [t1]
fname <- pushClosed ts2
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
DYNAMIC ->
case cbt of
STATIC ->
do ts2 <- collectElems elems DYNAMIC [t1]
maybePushActuals cur ts2
DYNAMIC ->
do collectElems elems DYNAMIC (t1 : cur)
STATIC ->
case cbt of
STATIC ->
do collectElems elems STATIC (t1 : cur)
DYNAMIC ->
do pushOpen cur
ts2 <- collectElems elems STATIC [t1]
fname <- pushClosed ts2
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
collect (CDATA_ bt str) cbt cur =
let t0 = TOut str
t0' = tout str in
case bt of
TOPLEVEL ->
do pushOpen cur
fname <- pushClosed [t0]
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
DYNAMIC ->
case cbt of
STATIC ->
do maybePushActuals cur [t0]
DYNAMIC ->
do return [t0]
STATIC ->
case cbt of
STATIC ->
do return (t0' cur)
DYNAMIC ->
do pushOpen cur
fname <- pushClosed [t0]
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
collect (COMMENT_ bt str) cbt cur =
let t0 = TOut str
t0' = tout str in
case bt of
TOPLEVEL ->
do pushOpen cur
fname <- pushClosed [t0]
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
DYNAMIC ->
case cbt of
STATIC ->
do maybePushActuals cur [t0]
DYNAMIC ->
do return [t0]
STATIC ->
case cbt of
STATIC ->
do return (t0' cur)
DYNAMIC ->
do pushOpen cur
fname <- pushClosed [t0]
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
collectElems [] cbt cur =
return cur
collectElems (at:ats) cbt cur =
do ts <- collectElems ats cbt cur
collect at cbt ts
collectAttrs [] cbt cur =
return cur
collectAttrs (at:ats) cbt cur =
do ts <- collectAttr at cbt cur
collectAttrs ats cbt ts
collectAttr
ATTR_ { attr_BT = bt
, attr_value_BT = vbt
, attr_name = aname
, attr_value = aval
}
cbt
cur = let { t1 = TOut (' ' : aname ++ "=\"") ; t2 = TOut "\"";
t1' = tout (' ' : aname ++ "=\"") ; t2' = tout "\""; } in
case bt of
TOPLEVEL ->
do pushOpen cur
ts <- collectAttrValue aval vbt STATIC [t1]
fname <- pushClosed (t2' ts)
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
DYNAMIC ->
case cbt of
STATIC ->
do ts <- collectAttrValue aval vbt DYNAMIC [t1]
maybePushActuals cur (t2' ts)
DYNAMIC ->
do ts <- collectAttrValue aval vbt DYNAMIC (t1' cur)
return (t2' ts)
STATIC ->
case cbt of
STATIC ->
do ts <- collectAttrValue aval vbt STATIC (t1' cur)
return (t2' ts)
DYNAMIC ->
do pushOpen cur
ts <- collectAttrValue aval vbt STATIC [t1]
fname <- pushClosed (t2' ts)
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
collectAttrValue aval bt cbt cur =
let encVal = (htmlAttr aval "")
t0 = TOut encVal
t0' = tout encVal in
case bt of
TOPLEVEL ->
do pushOpen cur
fname <- pushClosed [t0]
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
DYNAMIC ->
case cbt of
STATIC ->
do maybePushActuals cur [t0]
DYNAMIC ->
do return [t0]
STATIC ->
case cbt of
STATIC ->
do return (t0' cur)
DYNAMIC ->
do pushOpen cur
fname <- pushClosed [t0]
parms <- get actuals
cur' <- popOpen
maybePushActuals cur' [TCall fname parms]
-- Local Variables:
-- haskell-prog-switches: ("/home/thiemann/src/haskell/Utility/sha1lib.o")
-- End:
| nh2/WashNGo | WASH/HTML/HTMLTemplates.hs | bsd-3-clause | 13,411 | 507 | 21 | 3,530 | 4,805 | 2,614 | 2,191 | 439 | 21 |
{-# LANGUAGE DeriveGeneric #-}
-- |
-- Copyright : Anders Claesson 2014-2016
-- Maintainer : Anders Claesson <[email protected]>
--
-- TODO: Generalize interface and share with Sym.Perm.Pattern
module Sym.Perm.MeshPattern
( MeshPattern (..)
, Mesh
, Box
, mkPattern
, pattern
, mesh
, cols
, rows
, col
, row
, box
, copiesOf
, contains
, avoids
, avoidsAll
, avoiders
, kVincular
, vincular
, bivincular
, meshPatterns
) where
import Data.List hiding (union)
import Sym.Internal.Size
import Sym.Perm
import Sym.Internal.SubSeq
import Data.Set (Set)
import qualified Data.Set as Set
import Sym.Internal.Util
-- | A mesh is a, possibly empty, set of shaded boxes.
type Mesh = Set Box
-- | A box is represented by the coordinates of its southwest corner.
type Box = (Int, Int)
type Point = (Int, Int)
type PermTwoLine = [Point]
data MeshPattern = MP
{ getPerm :: Perm
, getMesh :: Mesh
} deriving (Show, Eq, Ord)
instance Size MeshPattern where
size = size . getPerm
mkPattern :: Ord a => [a] -> MeshPattern
mkPattern w = MP (mkPerm w) Set.empty
pattern :: Perm -> MeshPattern
pattern w = MP w Set.empty
mesh :: [Box] -> MeshPattern -> MeshPattern
mesh r (MP w s) = MP w . Set.union s $ Set.fromList r
cols :: [Int] -> MeshPattern -> MeshPattern
cols xs p@(MP w _) = mesh [ (x,y) | y <- [0..size w], x <- xs ] p
rows :: [Int] -> MeshPattern -> MeshPattern
rows ys p@(MP w _) = mesh [ (x,y) | x <- [0..size w], y <- ys ] p
col :: Int -> MeshPattern -> MeshPattern
col y = cols [y]
row :: Int -> MeshPattern -> MeshPattern
row x = rows [x]
box :: Box -> MeshPattern -> MeshPattern
box xy = mesh [xy]
kVincular :: Int -> Perm -> [MeshPattern]
kVincular k w = (flip cols (pattern w) . toList) `fmap` ((1+size w) `choose` k)
vincular :: Perm -> [MeshPattern]
vincular w = [0..1+size w] >>= flip kVincular w
bivincular :: Perm -> [MeshPattern]
bivincular w =
[ foldr ((.) . either col row) id c $ pattern w | c <- choices ]
where
choices = powerset' $ [0..size w] >>= \z -> [Left z, Right z]
powerset' = fmap Set.toList . powerset . Set.fromList
fullMesh :: Int -> Mesh
fullMesh n = let zs = [0..n] in Set.fromList [ (x,y) | x <- zs, y <- zs ]
meshPatterns :: Perm -> [MeshPattern]
meshPatterns w = [ MP w r | r <- powerset (fullMesh (size w)) ]
match' :: MeshPattern -> PermTwoLine -> PermTwoLine -> Bool
match' (MP u r) v w =
and $ (u2==v2) : [ not $ f i j x y | (i,j) <- Set.toList r, (x,y) <- w ]
where
(v1, v2) = unzip v
m = 1 + length w
xs = 0 : v1 ++ [m]
ys = 0 : sort v2 ++ [m]
u2 = map ((ys!!) . (+1)) (toList u)
f i j x y = xs!!i < x && x < xs!!(i+1) && ys!!j < y && y < ys!!(j+1)
-- | @match p w m@ determines whether the subword in @w@ specified by
-- @m@ is an occurrence of @p@.
match :: MeshPattern -> Perm -> SubSeq -> Bool
match p w m = match' p v w'
where
w' = twoLine w
v = [ pt | pt@(x,_) <- w', x-1 `elem` toList m ]
twoLine :: Perm -> PermTwoLine
twoLine = zip [1..] . map (+1) . toList
-- | @copiesOf p w@ is the list of sets that represent copies of @p@ in @w@.
copiesOf :: MeshPattern -> Perm -> [SubSeq]
copiesOf p w = filter (match p w) $ size w `choose` size p
{-# INLINE copiesOf #-}
-- | @w `contains` p@ is a predicate determining if @w@ contains the pattern @p@.
contains :: Perm -> MeshPattern -> Bool
w `contains` p = not $ w `avoids` p
-- | @w `avoids` p@ is a predicate determining if @w@ avoids the pattern @p@.
avoids :: Perm -> MeshPattern -> Bool
w `avoids` p = null $ copiesOf p w
-- | @w `avoidsAll` ps@ is a predicate determining if @w@ avoids the patterns @ps@.
avoidsAll :: Perm -> [MeshPattern] -> Bool
w `avoidsAll` ps = all (w `avoids`) ps
-- | @avoiders ps ws@ is the list of permutations in @ws@ avoiding the
-- patterns in @ps@.
avoiders :: [MeshPattern] -> [Perm] -> [Perm]
avoiders ps ws = foldl (flip avoiders1) ws ps
-- @avoiders1 p ws@ is the list of permutations in @ws@ avoiding the
-- pattern @p@.
avoiders1 :: MeshPattern -> [Perm] -> [Perm]
avoiders1 _ [] = []
avoiders1 q vs@(v:_) = filter avoids_q us ++ filter (`avoids` q) ws
where
n = size v
k = size q
(us, ws) = span (\u -> size u == n) vs
xs = n `choose` k
avoids_q u = not $ any (match q u) xs
| akc/sym | Sym/Perm/MeshPattern.hs | bsd-3-clause | 4,338 | 2 | 17 | 1,056 | 1,696 | 927 | 769 | 102 | 1 |
module Utils where
import SFML.Window
-- Utility functions
multVec :: Vec2f -> Float -> Vec2f
multVec (Vec2f x y) n = Vec2f (x * n) (y * n)
divVec :: Vec2f -> Float -> Vec2f
divVec v f = multVec v (1/f)
toVec2f :: Vec2u -> Vec2f
toVec2f (Vec2u x y) = Vec2f (fromIntegral x) (fromIntegral y)
vecLength :: Vec2f -> Float
vecLength (Vec2f x y) = sqrt ((x * x) + (y * y))
vecNormalise :: Vec2f -> Vec2f
vecNormalise v = divVec v (vecLength v)
toDegrees :: Float -> Float
toDegrees a = (a / (2 * pi)) * 360
getForwardVecFromRotation :: Float -> Vec2f
getForwardVecFromRotation a = Vec2f (sin (-a)) (cos (-a))
| bombpersons/HaskellAsteroids | src/Utils.hs | bsd-3-clause | 621 | 0 | 9 | 132 | 293 | 154 | 139 | 16 | 1 |
halve :: Double -> Double
halve = (/ 2)
seven :: Integer
seven = 7
convert :: (Double -> Double) -> Integer -> Double
convert f n = f $ fromIntegral n
| YoshikuniJujo/funpaala | samples/09_tuple/convert.hs | bsd-3-clause | 153 | 0 | 7 | 34 | 78 | 38 | 40 | 6 | 1 |
module Language.JsLib
( module Language.JsLib.AST
, module Language.JsLib.Scanner
, module Language.JsLib.Parser
, module Language.JsLib.Printer
) where
import Language.JsLib.AST
import Language.JsLib.Scanner
import Language.JsLib.Parser
import Language.JsLib.Printer
| JeanJoskin/JsLib | src/Language/JsLib.hs | bsd-3-clause | 269 | 0 | 5 | 25 | 60 | 41 | 19 | 9 | 0 |
module ApiSpec (spec) where
import Test.Hspec
spec :: Spec
spec = return ()
| channable/icepeak | server/tests/ApiSpec.hs | bsd-3-clause | 78 | 0 | 6 | 15 | 29 | 17 | 12 | 4 | 1 |
-- | Convenience module to import everything except a specific
-- rewriting combinator implementation. See "ADP.Multi.Rewriting.All"
-- for that.
module ADP.Multi.All (module X) where
import ADP.Multi.Parser as X
import ADP.Multi.ElementaryParsers as X
import ADP.Multi.Combinators as X
import ADP.Multi.TabulationTriangle as X
import ADP.Multi.Helpers as X | adp-multi/adp-multi | src/ADP/Multi/All.hs | bsd-3-clause | 362 | 0 | 4 | 48 | 56 | 42 | 14 | 6 | 0 |
{-# LANGUAGE CPP #-}
{- |
Module : $Header$
Description : Writing various formats, according to Hets options
Copyright : (c) Klaus Luettich, C.Maeder, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable(DevGraph)
Writing various formats, according to Hets options
-}
module Driver.WriteFn
( writeSpecFiles
, writeVerbFile
, writeLG
) where
import Text.ParserCombinators.Parsec
import Text.XML.Light
import System.FilePath
import Control.Monad
import Data.List (partition, (\\), intercalate)
import Data.Maybe
import Common.AS_Annotation
import Common.Id
import Common.IRI (IRI, simpleIdToIRI, iriToStringShortUnsecure, setAngles)
import Common.Json (ppJson)
import Common.DocUtils
import Common.ExtSign
import Common.LibName
import Common.Result
import Common.Parsec (forget)
import Common.Percent
import Common.GlobalAnnotations (GlobalAnnos)
import qualified Data.Map as Map
import Common.SExpr
import Common.IO
import Comorphisms.LogicGraph
import Logic.Coerce
import Logic.Comorphism (targetLogic)
import Logic.Grothendieck
import Logic.LGToXml
import Logic.LGToJson
import Logic.Logic
import Logic.Prover
import Proofs.StatusUtils
import Static.GTheory
import Static.DevGraph
import Static.CheckGlobalContext
import Static.DotGraph
import qualified Static.PrintDevGraph as DG
import Static.ComputeTheory
import qualified Static.ToXml as ToXml
import qualified Static.ToJson as ToJson
import CASL.Logic_CASL
import CASL.CompositionTable.Pretty2
import CASL.CompositionTable.ToXml
import CASL.CompositionTable.ComputeTable
import CASL.CompositionTable.ModelChecker
import CASL.CompositionTable.ParseTable2
#ifdef PROGRAMATICA
import Haskell.CreateModules
#endif
import Isabelle.CreateTheories
import Isabelle.IsaParse
import Isabelle.IsaPrint (printIsaTheory)
import SoftFOL.CreateDFGDoc
import SoftFOL.DFGParser
import SoftFOL.ParseTPTP
import FreeCAD.XMLPrinter (exportXMLFC)
import FreeCAD.Logic_FreeCAD
import VSE.Logic_VSE
import VSE.ToSExpr
#ifndef NOOWLLOGIC
import OWL2.CreateOWL
import OWL2.Logic_OWL2
import OWL2.ParseOWLAsLibDefn (convertOWL)
import qualified OWL2.ManchesterPrint as OWL2 (prepareBasicTheory)
import qualified OWL2.ManchesterParser as OWL2 (basicSpec)
#endif
#ifdef RDFLOGIC
import RDF.Logic_RDF
import qualified RDF.Print as RDF (printRDFBasicTheory)
#endif
import CommonLogic.Logic_CommonLogic
import qualified CommonLogic.AS_CommonLogic as CL_AS (exportCLIF)
import qualified CommonLogic.Parse_CLIF as CL_Parse (cltext)
import qualified CommonLogic.Print_KIF as Print_KIF (exportKIF)
import Driver.Options
import Driver.ReadFn (libNameToFile)
import Driver.WriteLibDefn
import OMDoc.XmlInterface (xmlOut)
import OMDoc.Export (exportLibEnv)
writeVerbFile :: HetcatsOpts -> FilePath -> String -> IO ()
writeVerbFile opts f str = do
putIfVerbose opts 2 $ "Writing file: " ++ f
writeEncFile (ioEncoding opts) f str
-- | compute for each LibName in the List a path relative to the given FilePath
writeVerbFiles :: HetcatsOpts -- ^ Hets options
-> String -- ^ A suffix to be combined with the libname
-> [(LibName, String)] -- ^ An output list
-> IO ()
writeVerbFiles opts suffix = mapM_ f
where f (ln, s) = writeVerbFile opts (libNameToFile ln ++ suffix) s
writeLibEnv :: HetcatsOpts -> FilePath -> LibEnv -> LibName -> OutType
-> IO ()
writeLibEnv opts filePrefix lenv ln ot =
let f = filePrefix ++ "." ++ show ot
dg = lookupDGraph ln lenv in case ot of
Prf -> toShATermString (ln, lookupHistory ln lenv)
>>= writeVerbFile opts f
XmlOut -> writeVerbFile opts f $ ppTopElement
$ ToXml.dGraph opts lenv ln dg
JsonOut -> writeVerbFile opts f $ ppJson
$ ToJson.dGraph opts lenv ln dg
SymsXml -> writeVerbFile opts f $ ppTopElement
$ ToXml.dgSymbols dg
OmdocOut -> do
let Result ds mOmd = exportLibEnv (recurse opts) (outdir opts) ln lenv
showDiags opts ds
case mOmd of
Just omd -> writeVerbFiles opts ".omdoc"
$ map (\ (libn, od) -> (libn, xmlOut od)) omd
Nothing -> putIfVerbose opts 0 "could not translate to OMDoc"
GraphOut (Dot showInternalNodeLabels) -> writeVerbFile opts f
$ dotGraph f showInternalNodeLabels "" dg
_ -> return ()
writeSoftFOL :: HetcatsOpts -> FilePath -> G_theory -> IRI
-> SPFType -> Int -> String -> IO ()
writeSoftFOL opts f gTh i c n msg = do
let cc = case c of
ConsistencyCheck -> True
ProveTheory -> False
mDoc <- printTheoryAsSoftFOL i n cc
$ (if cc then theoremsToAxioms else id) gTh
maybe (putIfVerbose opts 0 $
"could not translate to " ++ msg ++ " file: " ++ f)
( \ d -> do
let str = shows d "\n"
case parse (if n == 0 then forget parseSPASS else forget tptp)
f str of
Left err -> putIfVerbose opts 0 $ show err
_ -> putIfVerbose opts 3 $ "reparsed: " ++ f
writeVerbFile opts f str) mDoc
writeFreeCADFile :: HetcatsOpts -> FilePath -> G_theory -> IO ()
writeFreeCADFile opts filePrefix (G_theory lid _ (ExtSign sign _) _ _ _) = do
fcSign <- coercePlainSign lid FreeCAD
"Expecting a FreeCAD signature for writing FreeCAD xml" sign
writeVerbFile opts (filePrefix ++ ".xml") $ exportXMLFC fcSign
writeIsaFile :: HetcatsOpts -> FilePath -> G_theory -> LibName -> IRI
-> IO ()
writeIsaFile opts filePrefix raw_gTh ln i = do
let Result ds mTh = createIsaTheory raw_gTh
addThn = (++ '_' : iriToStringShortUnsecure i)
fp = addThn filePrefix
showDiags opts ds
case mTh of
Nothing ->
putIfVerbose opts 0 $ "could not translate to Isabelle theory: " ++ fp
Just (sign, sens) -> do
let tn = addThn . reverse . takeWhile (/= '/') . reverse $ case
libToFileName ln of
[] -> filePrefix
lstr -> lstr
sf = shows (printIsaTheory tn sign sens) "\n"
f = fp ++ ".thy"
case parse parseTheory f sf of
Left err -> putIfVerbose opts 0 $ show err
_ -> putIfVerbose opts 3 $ "reparsed: " ++ f
writeVerbFile opts f sf
when (hasPrfOut opts && verbose opts >= 3) $ let
(axs, rest) = partition ( \ s -> isAxiom s || isDef s) sens
in mapM_ ( \ s -> let
tnf = tn ++ "_" ++ senAttr s
tf = fp ++ "_" ++ senAttr s ++ ".thy"
in writeVerbFile opts tf $ shows
(printIsaTheory tnf sign $ s : axs) "\n") rest
writeTheory :: [String] -> String -> HetcatsOpts -> FilePath -> GlobalAnnos
-> G_theory -> LibName -> IRI -> OutType -> IO ()
writeTheory ins nam opts filePrefix ga
raw_gTh@(G_theory lid _ (ExtSign sign0 _) _ sens0 _) ln i ot =
let fp = filePrefix ++ "_" ++ i'
i' = encode (iriToStringShortUnsecure $ setAngles False i)
f = fp ++ "." ++ show ot
th = (sign0, toNamedList sens0)
lang = language_name lid
in case ot of
FreeCADOut -> writeFreeCADFile opts filePrefix raw_gTh
ThyFile -> writeIsaFile opts filePrefix raw_gTh ln i
DfgFile c -> writeSoftFOL opts f raw_gTh i c 0 "DFG"
TPTPFile c -> writeSoftFOL opts f raw_gTh i c 1 "TPTP"
TheoryFile d -> do
if null $ show d then
writeVerbFile opts f $ shows (DG.printTh ga i raw_gTh) "\n"
else putIfVerbose opts 0 "printing theory delta is not implemented"
when (lang == language_name VSE) $ do
(sign, sens) <- coerceBasicTheory lid VSE "" th
let (sign', sens') = addUniformRestr sign sens
lse = map (namedSenToSExpr sign') sens'
unless (null lse) $ writeVerbFile opts (fp ++ ".sexpr")
$ shows (prettySExpr $ SList lse) "\n"
SigFile d -> do
if null $ show d then
writeVerbFile opts f $ shows (pretty $ signOf raw_gTh) "\n"
else putIfVerbose opts 0 "printing signature delta is not implemented"
when (lang == language_name VSE) $ do
(sign, sens) <- coerceBasicTheory lid VSE "" th
let (sign', _sens') = addUniformRestr sign sens
writeVerbFile opts (f ++ ".sexpr")
$ shows (prettySExpr $ vseSignToSExpr sign') "\n"
SymXml -> writeVerbFile opts f $ ppTopElement
$ ToXml.showSymbolsTh ins nam ga raw_gTh
#ifdef PROGRAMATICA
HaskellOut -> case printModule raw_gTh of
Nothing ->
putIfVerbose opts 0 $ "could not translate to Haskell file: " ++ f
Just d -> writeVerbFile opts f $ shows d "\n"
#endif
ComptableXml -> if lang == language_name CASL then do
th2 <- coerceBasicTheory lid CASL "" th
let Result ds res = computeCompTable i th2
showDiags opts ds
case res of
Just td -> writeVerbFile opts f $ tableXmlStr td
Nothing -> return ()
else putIfVerbose opts 0 $ "expected CASL theory for: " ++ f
#ifdef RDFLOGIC
RDFOut
| lang == language_name RDF -> do
th2 <- coerceBasicTheory lid RDF "" th
let rdftext = shows (RDF.printRDFBasicTheory th2) "\n"
writeVerbFile opts f rdftext
| otherwise -> putIfVerbose opts 0 $ "expected RDF theory for: " ++ f
#endif
#ifndef NOOWLLOGIC
OWLOut ty -> case ty of
Manchester -> case createOWLTheory raw_gTh of
Result _ Nothing ->
putIfVerbose opts 0 $ "expected OWL theory for: " ++ f
Result ds (Just th2) -> do
let sy = defSyntax opts
ms = if null sy then Nothing
else Just $ simpleIdToIRI $ mkSimpleId sy
owltext = shows
(printTheory ms OWL2 $ OWL2.prepareBasicTheory th2) "\n"
showDiags opts ds
when (null sy)
$ case parse (OWL2.basicSpec Map.empty >> eof) f owltext of
Left err -> putIfVerbose opts 0 $ show err
_ -> putIfVerbose opts 3 $ "reparsed: " ++ f
writeVerbFile opts f owltext
_ -> let flp = getFilePath ln in case guess flp GuessIn of
OWLIn _ -> writeVerbFile opts f =<< convertOWL flp (show ty)
_ -> putIfVerbose opts 0
$ "OWL output only supported for owl input types ("
++ intercalate ", " (map show plainOwlFormats) ++ ")"
#endif
CLIFOut
| lang == language_name CommonLogic -> do
(_, th2) <- coerceBasicTheory lid CommonLogic "" th
let cltext = shows (CL_AS.exportCLIF th2) "\n"
case parse (many (CL_Parse.cltext Map.empty) >> eof) f cltext of
Left err -> putIfVerbose opts 0 $ show err
_ -> putIfVerbose opts 3 $ "reparsed: " ++ f
writeVerbFile opts f cltext
| otherwise -> putIfVerbose opts 0 $ "expected Common Logic theory for: "
++ f
KIFOut
| lang == language_name CommonLogic -> do
(_, th2) <- coerceBasicTheory lid CommonLogic "" th
let kiftext = shows (Print_KIF.exportKIF th2) "\n"
writeVerbFile opts f kiftext
| otherwise -> putIfVerbose opts 0 $ "expected Common Logic theory for: "
++ f
_ -> return () -- ignore other file types
modelSparQCheck :: HetcatsOpts -> G_theory -> IO ()
modelSparQCheck opts gTh@(G_theory lid _ (ExtSign sign0 _) _ sens0 _) =
case coerceBasicTheory lid CASL "" (sign0, toNamedList sens0) of
Just th2 -> do
table <- parseSparQTableFromFile $ modelSparQ opts
case table of
Left err -> putIfVerbose opts 0
$ "could not parse SparQTable from file: " ++ modelSparQ opts
++ "\n" ++ show err
Right y -> do
putIfVerbose opts 4 $ unlines
["lisp file content:", show $ table2Doc y, "lisp file end."]
let Result d _ = modelCheck (counterSparQ opts) th2 y
if null d then
putIfVerbose opts 0 "Modelcheck succeeded, no errors found"
else showDiags
(if verbose opts >= 2 then opts else opts {verbose = 2}) d
_ ->
putIfVerbose opts 0 $ "could not translate Theory to CASL:\n "
++ showDoc gTh ""
writeTheoryFiles :: HetcatsOpts -> [OutType] -> FilePath -> LibEnv
-> GlobalAnnos -> LibName -> IRI -> Int -> IO ()
writeTheoryFiles opts specOutTypes filePrefix lenv ga ln i n =
let dg = lookupDGraph ln lenv
nam = getDGNodeName $ labDG dg n
ins = getImportNames dg n
in case globalNodeTheory dg n of
Nothing -> putIfVerbose opts 0 $ "could not compute theory of spec "
++ show i
Just raw_gTh0 -> do
let tr = transNames opts
Result es mTh = if null tr then return (raw_gTh0, "") else do
comor <- lookupCompComorphism (map tokStr tr) logicGraph
tTh <- mapG_theory comor raw_gTh0
return (tTh, "Translated using comorphism " ++ show comor)
(raw_gTh, tStr) =
fromMaybe (raw_gTh0, "Keeping untranslated theory") mTh
showDiags opts $ map (updDiagKind
(\ k -> if k == Error then Warning else k)) es
unless (null tStr) $ putIfVerbose opts 2 tStr
putIfVerbose opts 4 $ "Sublogic of " ++ show i ++ ": " ++
show (sublogicOfTh raw_gTh)
unless (modelSparQ opts == "") $
modelSparQCheck opts (theoremsToAxioms raw_gTh)
mapM_ (writeTheory ins nam opts filePrefix ga raw_gTh ln i)
specOutTypes
writeSpecFiles :: HetcatsOpts -> FilePath -> LibEnv -> LibName -> DGraph
-> IO ()
writeSpecFiles opts file lenv ln dg = do
let gctx = globalEnv dg
gns = Map.keys gctx
mns = map $ \ t -> Map.findWithDefault (simpleIdToIRI t) (tokStr t)
$ Map.fromList $ map (\ i -> (iriToStringShortUnsecure i, i)) gns
ga = globalAnnos dg
ns = mns $ specNames opts
vs = mns $ viewNames opts
filePrefix = snd $ getFilePrefix opts file
outTypes = outtypes opts
specOutTypes = filter ( \ ot -> case ot of
ThyFile -> True
DfgFile _ -> True
TPTPFile _ -> True
XmlOut -> True
JsonOut -> True
OmdocOut -> True
TheoryFile _ -> True
SigFile _ -> True
OWLOut _ -> True
CLIFOut -> True
KIFOut -> True
FreeCADOut -> True
HaskellOut -> True
ComptableXml -> True
SymXml -> True
_ -> False) outTypes
allSpecs = null ns
noViews = null vs
ignore = null specOutTypes && modelSparQ opts == ""
mapM_ (writeLibEnv opts filePrefix lenv ln) $
if null $ dumpOpts opts then outTypes else EnvOut : outTypes
mapM_ ( \ i -> case Map.lookup i gctx of
Just (SpecEntry (ExtGenSig _ (NodeSig n _))) ->
writeTheoryFiles opts specOutTypes filePrefix lenv ga ln i n
_ -> unless allSpecs
$ putIfVerbose opts 0 $ "Unknown spec name: " ++ show i
) $ if ignore then [] else
if allSpecs then gns else ns
unless noViews $
mapM_ ( \ i -> case Map.lookup i gctx of
Just (ViewOrStructEntry _ (ExtViewSig _ (GMorphism cid _ _ m _) _)) ->
writeVerbFile opts (filePrefix ++ "_" ++ show i ++ ".view")
$ shows (pretty $ Map.toList $ symmap_of (targetLogic cid) m) "\n"
_ -> putIfVerbose opts 0 $ "Unknown view name: " ++ show i
) vs
mapM_ ( \ n ->
writeTheoryFiles opts specOutTypes filePrefix lenv ga ln
(simpleIdToIRI $ genToken $ 'n' : show n) n)
$ if ignore || not allSpecs then [] else
nodesDG dg
\\ Map.fold ( \ e l -> case e of
SpecEntry (ExtGenSig _ (NodeSig n _)) -> n : l
_ -> l) [] gctx
doDump opts "GlobalAnnos" $ putStrLn $ showGlobalDoc ga ga ""
doDump opts "PrintStat" $ putStrLn $ printStatistics dg
doDump opts "DGraph" $ putStrLn $ showDoc dg ""
doDump opts "DuplicateDefEdges" $ let es = duplicateDefEdges dg in
unless (null es) $ print es
doDump opts "LibEnv" $ writeVerbFile opts (filePrefix ++ ".lenv")
$ shows (DG.prettyLibEnv lenv) "\n"
writeLG :: HetcatsOpts -> IO ()
writeLG opts = do
doDump opts "LogicGraph" $ putStrLn $ showDoc logicGraph ""
if elem JsonOut $ outtypes opts then do
lG <- lGToJson logicGraph
writeVerbFile opts { verbose = 2 } (outdir opts </> "LogicGraph.json")
$ ppJson lG
else do
lG <- lGToXml logicGraph
writeVerbFile opts { verbose = 2 } (outdir opts </> "LogicGraph.xml")
$ ppTopElement lG
| keithodulaigh/Hets | Driver/WriteFn.hs | gpl-2.0 | 17,052 | 0 | 25 | 5,103 | 5,124 | 2,524 | 2,600 | 357 | 23 |
{- |
Module : ./Comorphisms/DynLogicList.hs
Description : Automatically modified file, includes the user-defined
logics in the Hets logic list. Do not change.
Copyright : (c) Kristina Sojakova, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable -}
module Comorphisms.DynLogicList where
import Logic.Logic
dynLogicList :: [AnyLogic]
dynLogicList = []
| spechub/Hets | Comorphisms/DynLogicList.hs | gpl-2.0 | 492 | 0 | 5 | 98 | 27 | 17 | 10 | 4 | 1 |
import qualified UI.HSCurses.Curses as Curses
import qualified UI.HSCurses.CursesHelper as CursesH
import UI.HSCurses.Widgets
import Control.Exception
import System.Exit
draw s =
do (h, w) <- Curses.scrSize
CursesH.gotoTop
CursesH.drawLine w s
Curses.refresh
done = return ()
forever :: Monad m => m t -> m t
forever x = x >> forever x
exit ew _ _ = return (Done ew)
options stys =
let dsty = (mkDrawingStyle (stys!!1)) { dstyle_active = stys!!1 }
in defaultEWOptions {ewopt_style = dsty }
editWidget stys = newEditWidget (options stys) ""
edit ew =
do (ew', s) <- activateEditWidget done (1, 10) (1, 10) ew
Curses.wMove Curses.stdScr 5 0
CursesH.drawLine 60 ("saved: " ++ s)
Curses.refresh
return ew'
loop ew =
do c <- CursesH.getKey done
ew' <- case c of
Curses.KeyChar 'q' -> exitWith ExitSuccess
Curses.KeyChar 'e' -> edit ew
_ -> return ew
loop ew'
styles = [CursesH.defaultStyle,
CursesH.Style CursesH.CyanF CursesH.PurpleB]
main :: IO ()
main =
do CursesH.start
cstyles <- CursesH.convertStyles styles
Curses.cursSet Curses.CursorInvisible
CursesH.gotoTop
CursesH.drawLine 20 "Hit 'e'!"
Curses.wMove Curses.stdScr 1 0
CursesH.drawLine 9 "Input: "
Curses.refresh
loop (editWidget cstyles)
`finally` CursesH.end | beni55/hscurses | tests/widget-test/EditTest.hs | lgpl-2.1 | 1,436 | 4 | 13 | 398 | 521 | 247 | 274 | 45 | 3 |
{- Parsec parser for fullerror. The sole expected method, parseFullError,
takes a string as input, and returns a list of terms, where each term
was separated by a semicolon in the input.
-}
module Parser ( parseFullError ) where
import Text.ParserCombinators.Parsec
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language
import Control.Monad
import Control.Monad.Error
import Control.Monad.State
import Data.Char
import Syntax
import Typing
import TaplError
import SimpleContext
{- ------------------------------
Lexer, making use of the Parsec.Token and Language
modules for ease of lexing programming language constructs
------------------------------ -}
fullErrorDef = LanguageDef
{ commentStart = "/*"
, commentEnd = "*/"
, commentLine = ""
, nestedComments = False
, identStart = letter
, identLetter = letter <|> digit
, opStart = fail "no operators"
, opLetter = fail "no operators"
, reservedOpNames = []
, caseSensitive = True
, reservedNames = ["inert", "true", "false", "if", "then", "else", "Bool", "Nat", "String", "Unit", "Float", "case", "of", "as", "lambda", "let", "in", "fix", "letrec", "timesfloat", "succ", "pred", "iszero", "unit", "try", "with", "error", "Bot"]
}
lexer = P.makeTokenParser fullErrorDef
parens = P.parens lexer
braces = P.braces lexer
squares = P.squares lexer
identifier = P.identifier lexer
reserved = P.reserved lexer
symbol = P.symbol lexer
whiteSpace = P.whiteSpace lexer
float = P.float lexer
semi = P.semi lexer
comma = P.comma lexer
colon = P.colon lexer
stringLiteral = P.stringLiteral lexer
natural = P.natural lexer
{- ------------------------------
Parsing Binders
------------------------------ -}
-- due to the definition of "identState" in fullErrorDef,
-- this is the only way that an underscore can enter our system,
-- and thus there is no chance of it being misused as a variable elsewhere
parseVarBind = do var <- identifier <|> symbol "_"
symbol ":"
ty <- parseType
let binding = VarBind ty
updateState $ appendBinding var binding
return $ TmBind var binding
parseAbbBind forLetrec
= do var <- identifier <|> symbol "_"
-- For a letrec, we need to temporarily add a binding, so that
-- we can lookup this variable while parsing the body.
-- Note that both setState calls use the original Context
ctx <- getState
when forLetrec $ setState $ appendBinding var NameBind ctx
binding <- getBinding var
setState $ appendBinding var binding ctx
return $ TmBind var binding
where getBinding var = if (isUpper $ var !! 0)
then (try $ completeTyAbbBind var) <|>
(return TyVarBind)
else withType <|> withoutType
withoutType = do symbol "="
t <- parseTerm
liftM (TmAbbBind t) (getType t)
withType = do symbol ":"
ty <- parseType
symbol "="
liftM ((flip TmAbbBind) (Just ty)) parseTerm
completeTyAbbBind var
= do symbol "="
ty <- parseType
return $ TyAbbBind ty
getType t = do ctx <- getState
case evalState (runErrorT (typeof t)) ctx of
Left err -> return Nothing
Right ty -> return $ Just ty
parseBinder = (try parseVarBind) <|> (parseAbbBind False)
{- ------------------------------
Parsing Types
------------------------------ -}
parseTypeBool = reserved "Bool" >> return TyBool
parseTypeNat = reserved "Nat" >> return TyNat
parseTypeFloat = reserved "Float" >> return TyFloat
parseTypeUnit = reserved "Unit" >> return TyUnit
parseTypeString = reserved "String" >> return TyString
parseTypeBot = reserved "Bot" >> return TyBot
parseNamedType = do ty <- identifier
if isUpper $ ty !! 0
then makeNamedType ty
else fail "types must start with an uppercase letter"
where makeNamedType ty = do ctx <- getState
throwsToParser $ makeTyVarOrTyId ty ctx
makeTyVarOrTyId ty ctx = catchError (makeTyVar ty ctx)
(\e -> return $ TyId ty)
makeTyVar ty ctx = do idx <- indexOf ty ctx
return $ TyVar $ TmVar idx (ctxLength ctx)
parseVariantType = do symbol "<"
fields <- sepBy1 parseField comma
symbol ">"
return $ TyVariant fields
where parseField = do var <- identifier
colon
ty <- parseType
return (var, ty)
parseTypeArr = parseTypeBool <|>
parseTypeNat <|>
parseTypeFloat <|>
parseTypeUnit <|>
parseTypeString <|>
parseTypeBot <|>
parseNamedType <|>
parseVariantType <|>
braces parseType
parseType = parseTypeArr `chainr1` (symbol "->" >> return TyArr)
{- ------------------------------
Parsing zero-arg terms
------------------------------ -}
parseTrue = reserved "true" >> return TmTrue
parseFalse = reserved "false" >> return TmFalse
parseUnit = reserved "unit" >> return TmUnit
parseNat = liftM numToSucc natural
where numToSucc 0 = TmZero
numToSucc n = TmSucc $ numToSucc (n - 1)
{- ------------------------------
Arith Parsers
------------------------------ -}
parseOneArg keyword constructor = reserved keyword >>
liftM constructor parseTerm
parseSucc = parseOneArg "succ" TmSucc
parsePred = parseOneArg "pred" TmPred
parseIsZero = parseOneArg "iszero" TmIsZero
{- ------------------------------
Other Parsers
------------------------------ -}
parseString = liftM TmString stringLiteral
parseFloat = liftM TmFloat float
parseTimesFloat = reserved "timesfloat" >>
liftM2 TmTimesFloat parseNonApp parseNonApp
parseIf = do reserved "if"
t1 <- parseTerm
reserved "then"
t2 <- parseTerm
reserved "else"
liftM (TmIf t1 t2) parseTerm
parseVar = do var <- identifier
if (isUpper $ var !! 0)
then fail "variables must start with a lowercase letter"
else do ctx <- getState
idx <- throwsToParser $ indexOf var ctx
return $ TmVar idx (ctxLength ctx)
parseInert = reserved "inert" >> squares (liftM TmInert parseType)
{- ------------------------------
let/lambda
------------------------------ -}
-- for both let and lambda, we need to make sure we restore the
-- state after parsing the body, so that the lexical binding doesn't leak
parseAbs = do reserved "lambda"
ctx <- getState
(TmBind var (VarBind ty)) <- parseVarBind
symbol "."
body <- parseTerm
setState ctx
return $ TmAbs var ty body
parseLet = do reserved "let"
ctx <- getState
(TmBind var binding) <- (parseAbbBind False)
reserved "in"
body <- parseTerm
setState ctx
case binding of
TmAbbBind t ty -> return $ TmLet var t body
otherwise -> fail "malformed let statement"
{- ------------------------------
Fix and Letrec
------------------------------ -}
parseLetrec = do reserved "letrec"
ctx <- getState
(TmBind var binding) <- (parseAbbBind True)
reserved "in"
body <- parseTerm
setState ctx
case binding of
TmAbbBind t (Just ty)
-> return $ TmLet var (TmFix (TmAbs var ty t)) body
otherwise
-> fail "malformed letrec statement"
parseFix = reserved "fix" >> liftM TmFix parseTerm
{- ------------------------------
Records and Projections
------------------------------ -}
-- Fields can either be named or not. If they are not, then they
-- are numbered starting with 1. To keep parsing the fields simple,
-- we label them with -1 at first if they have no name. We then
-- replace the -1's with the correct index as a post-processing step.
parseRecord = braces $ liftM TmRecord $ liftM (addNumbers 1) $
sepBy parseRecordField comma
where addNumbers _ [] = []
addNumbers i (("-1",t):fs) = (show i, t) : (addNumbers (i+1) fs)
addNumbers i ( f:fs) = f : (addNumbers (i+1) fs)
parseRecordField = liftM2 (,) parseName parseTerm
where parseName = (try (do {name <- identifier; symbol "="; return name}))
<|> return "-1"
parseProj = do t <- parseRecord <|> parens parseTerm
symbol "."
liftM (TmProj t) (identifier <|> (liftM show natural))
{- ------------------------------
Variants and Cases
------------------------------ -}
parseVariant = do symbol "<"
var <- identifier
symbol "="
t <- parseTerm
symbol ">"
reserved "as"
liftM (TmTag var t) parseType
parseCase = do reserved "case"
t <- parseTerm
reserved "of"
liftM (TmCase t) $ sepBy1 parseBranch (symbol "|")
where parseBranch = do symbol "<"
label <- identifier
symbol "="
var <- identifier
symbol ">"
symbol "==>"
ctx <- getState
setState $ appendBinding var NameBind ctx
t <- parseTerm
setState ctx
return (label, (var,t))
{- ------------------------------
Exceptions
------------------------------ -}
parseError = reserved "error" >> return (TmError TyBot)
parseTryWith = do reserved "try"
t1 <- parseTerm
reserved "with"
liftM (TmTry t1) parseTerm
{- ------------------------------
Putting it all together
------------------------------ -}
parseNonApp = parseTrue <|>
parseFalse <|>
parseSucc <|>
parsePred <|>
parseIsZero <|>
parseIf <|>
(try parseFloat) <|>
parseTimesFloat <|>
parseNat <|>
parseAbs <|>
parseLet <|>
(try parseBinder) <|>
parseVar <|>
parseUnit <|>
parseString <|>
(try parseProj) <|>
parseRecord <|>
parseCase <|>
parseVariant <|>
parseInert <|>
parseFix <|>
parseLetrec <|>
parseError <|>
parseTryWith <|>
parens parseTerm
-- parses a non-application which could be an ascription
-- (the non-application parsing is left-factored)
parseNonAppOrAscribe = do t <- parseNonApp
(do reserved "as"
ty <- parseType
return $ TmAscribe t ty) <|> return t
-- For non-applications, we don't need to deal with associativity,
-- but we need to special handling (in the form of 'chainl1' here)
-- so that we enforce left-associativity as we aggregate a list of terms
parseTerm = chainl1 parseNonAppOrAscribe $ return TmApp
parseTerms = do whiteSpace -- lexer handles whitespace everywhere except here
ts <- endBy1 parseTerm semi
eof
return ts
parseFullError :: String -> ThrowsError [Term]
parseFullError str
= case runParser parseTerms newContext "fullerror Parser" str of
Left err -> throwError $ ParserError $ show err
Right ts -> return ts
{- ------------------------------
Helpers
------------------------------ -}
throwsToParser action = case action of
Left err -> fail $ sho | markwatkinson/luminous | tests/regression/haskell/Parser.hs | lgpl-2.1 | 13,038 | 0 | 28 | 4,874 | 2,660 | 1,298 | 1,362 | 240 | 3 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
{-
Copyright 2016 The CodeWorld Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Blockly.DesignBlock (Type(..)
,FieldType(..)
,BlockType(..)
,Input(..)
,Field(..)
,Inline(..)
,Connection(..)
,DesignBlock(..)
,Color(..)
,Tooltip(..)
,setBlockType)
where
import GHCJS.Types
import Data.JSString.Text
import GHCJS.Marshal
import GHCJS.Foreign hiding (Number, String, Function)
import GHCJS.Foreign.Callback
import Data.Monoid
import Control.Monad
import Data.Ord (comparing)
import Data.List (maximumBy)
import qualified Data.Text as T
import Data.Maybe (fromJust)
import Data.List (intercalate)
import qualified Blockly.TypeExpr as TE
import qualified JavaScript.Array as JA
import Blockly.Block as B
pack = textToJSString
unpack = textFromJSString
-- Low level bindings to construction of various different type of Blockly
-- blocks
data ADT = Product String [Type]
| Sum [ADT]
data User = User String ADT
instance Show User where
show (User name adt) = name
data Type = Arrow [Type]
| Number
| Str -- Actually Text
| Truth
| Picture
| Col -- Actually Color
| List Type -- Have to define kinded types
| Custom User
| Poly T.Text
| Program -- For top level blocks
| Comment
instance Show Type where
show Number = "Number"
show Picture = "Picture"
show (Custom (User name adt)) = name
show (Poly c) = T.unpack c
show (Str) = "Text"
show (Truth) = "Truth"
show (Col) = "Color"
show (Comment) = ""
show (Program) = "Program"
show (Arrow tps) = intercalate " -> " $ map show tps
data FieldType = LeftField | RightField | CentreField
data Input = Value T.Text [Field]
-- | Statement T.Text [Field] Type
| Dummy [Field]
data Field = Text T.Text
| TextE T.Text -- Emphasized Text, for titles
| TextInput T.Text T.Text -- displayname, value
| FieldImage T.Text Int Int -- src, width, height
data Connection = TopCon | BotCon | TopBotCon | LeftCon
newtype Inline = Inline Bool
-- Name functionName inputs connectiontype color outputType tooltip
-- name funcName
data BlockType = Literal T.Text
| Function T.Text [Type]
| Top T.Text [Type]
| None -- do nothing !
-- DesignBlock name type inputs isInline Color Tooltip
data DesignBlock = DesignBlock T.Text BlockType [Input] Inline Color Tooltip
newtype Color = Color Int
newtype Tooltip = Tooltip T.Text
fieldCode :: FieldInput -> Field -> IO FieldInput
fieldCode field (Text str) = js_appendTextField field (pack str)
fieldCode field (TextE str) = js_appendTextFieldEmph field (pack str)
fieldCode field (TextInput text name) = js_appendTextInputField field (pack text) (pack name)
fieldCode field (FieldImage src width height) = js_appendFieldImage field (pack src) width height
inputCode :: Bool -> Block -> Input -> IO ()
inputCode rightAlign block (Dummy fields) = do
fieldInput <- js_appendDummyInput block
when rightAlign $ js_setAlignRight fieldInput
foldr (\ field fi -> do
fi_ <- fi
fieldCode fi_ field) (return fieldInput) fields
return ()
inputCode rightAlign block (Value name fields) = do
fieldInput <- js_appendValueInput block (pack name)
when rightAlign $ js_setAlignRight fieldInput
foldr (\ field fi -> do
fi_ <- fi
fieldCode fi_ field) (return fieldInput) fields
return ()
typeToTypeExpr :: Type -> TE.Type_
typeToTypeExpr (Poly a) = TE.createType $ TE.TypeVar a
typeToTypeExpr t = TE.createType $ TE.Lit (T.pack $ show t ) [] -- Currently still a hack
-- set block
setBlockType :: DesignBlock -> IO ()
setBlockType (DesignBlock name blockType inputs (Inline inline) (Color color) (Tooltip tooltip) ) = do
cb <- syncCallback1 ContinueAsync (\this -> do
let block = B.Block this
js_setColor block color
forM_ (zip inputs (False : repeat True)) $ \(inp, rightAlign) -> do
inputCode rightAlign block inp
case blockType of
None -> js_disableOutput block
Top _ _ -> js_disableOutput block
_ -> js_enableOutput block
assignBlockType block blockType
when inline $ js_setInputsInline block True
return ()
)
js_setGenFunction (pack name) cb
typeToType :: Type -> TE.Type
typeToType (Poly a) = TE.TypeVar a
typeToType lit = TE.Lit (T.pack $ show lit) []
assignBlockType :: Block -> BlockType -> IO ()
assignBlockType block (Literal name) = B.setAsLiteral block name
assignBlockType block (Function name tps) = do
js_defineFunction (pack name) (TE.fromList tp)
B.setAsFunction block name
where tp = map typeToType tps
assignBlockType block (Top name tps) = assignBlockType block (Function name tps)
assignBlockType _ _ = return ()
newtype FieldInput = FieldInput JSVal
-- setArrows :: Block -> [Type] -> IO ()
-- setArrows block tps = js_setArrows block typeExprs
-- where
-- typeExprs = TE.toJSArray $ map typeToTypeExpr tps
foreign import javascript unsafe "Blockly.Blocks[$1] = { init: function() { $2(this); }}"
js_setGenFunction :: JSString -> Callback a -> IO ()
foreign import javascript unsafe "$1.setColour($2)"
js_setColor :: Block -> Int -> IO ()
foreign import javascript unsafe "$1.setOutput(true)"
js_enableOutput :: Block -> IO ()
foreign import javascript unsafe "$1.setOutput(false)"
js_disableOutput:: Block -> IO ()
foreign import javascript unsafe "$1.setTooltip($2)"
js_setTooltip :: Block -> JSString -> IO ()
foreign import javascript unsafe "$1.appendDummyInput()"
js_appendDummyInput :: Block -> IO FieldInput
foreign import javascript unsafe "Blockly.TypeInf.defineFunction($1, $2)"
js_defineFunction :: JSString -> TE.Type_ -> IO ()
foreign import javascript unsafe "$1.appendValueInput($2)"
js_appendValueInput :: Block -> JSString -> IO FieldInput
foreign import javascript unsafe "$1.appendField($2)"
js_appendTextField :: FieldInput -> JSString -> IO FieldInput
foreign import javascript unsafe "$1.appendField(new Blockly.FieldLabel($2, 'blocklyTextEmph'))"
js_appendTextFieldEmph :: FieldInput -> JSString -> IO FieldInput
foreign import javascript unsafe "$1.appendField(new Blockly.FieldImage($2, $3, $4))"
js_appendFieldImage:: FieldInput -> JSString -> Int -> Int -> IO FieldInput
foreign import javascript unsafe "$1.appendField(new Blockly.FieldTextInput($2), $3)"
js_appendTextInputField :: FieldInput -> JSString -> JSString -> IO FieldInput
foreign import javascript unsafe "$1.setCheck($2)"
js_setCheck :: FieldInput -> JSString -> IO ()
foreign import javascript unsafe "$1.setAlign(Blockly.ALIGN_RIGHT)"
js_setAlignRight :: FieldInput -> IO ()
foreign import javascript unsafe "$1.setInputsInline($2)"
js_setInputsInline :: Block -> Bool -> IO ()
| nomeata/codeworld | funblocks-client/src/Blockly/DesignBlock.hs | apache-2.0 | 8,059 | 46 | 20 | 2,129 | 1,948 | 1,020 | 928 | 153 | 3 |
module Help where
import Euphs.Bot (Net, botName)
import Control.Monad.Reader (asks)
--import Options.Applicative
--import Safe
import Data.List
helpIntro :: String -> String
helpIntro bn =
"I am @" ++ bn ++ ", a bot created by viviff for use with rooms with video players.\n\
\This bot continues the work of NeonDJBot, the original &music bot by Drex."
helpCommands :: String
helpCommands =
"COMMANDS:\n\
\‣ Commands are case insensitive and ignore suffixes.\n\
\‣ Youtube.com links or ytLink's are of the form:\n youtube.com/watch?v=FTQbiNvZqaY\n or simply the ytid, FTQbiNvZqaY, separated by a space or a comma.\n\
\‣ Some link shorteners are accepted, like:\n youtu.be/FTQbiNvZqaY\n\
\‣ Not accepted in links: playlists or start-times."
helpHelp :: String -> String
helpHelp botName' = "Help:\n• !help @" ++ botName' ++" : This very help."
helpQ :: String
helpQ = "Queue Operation:\n\
\• !q <ytLink> <ytLink> [-id or -ytid] (!queue):\n Queues single or multiple ytLinks at the queue's end.\n\
\• !qf <ytLink> <ytLink> [-id or -ytid] (!queuefirst):\n Same as !q but queues at the start of the queue.\n\
\• !list [-v or -verbose][-r or -restricted][-id or -ytid][-links][-comma][-space]:\n Shows a list of the songs currently in the queue,\n\
\ -verbose adds ytLinks while keeping the titles.\n\
\ -links and -id show only the links or ids without other info, separated by -comma and/or -space [default]."
helpQAdv :: String
helpQAdv = "Advanced Queue Operation:\n\
\• !ins <pos> <ytLink> <ytLink> [-id or -ytid] (!insert):\n Inserts the song(s) at position <pos>,\n moving the existing songs down.\n\
\• !sub <pos> <ytLink> (!substitute):\n Substitutes the song at position <pos>\n with the new ytLink.\n\
\• !del <pos> <num> (!delete or !rem, !rm, !remove):\n Deletes <num> songs from the queue\n starting from the <pos> position.\n\
\• !switch <pos1> <pos2> (!swap):\n Swaps the position of the two songs in the queue."
helpPlay :: String
helpPlay = "Playback Operation:\n\
\• !skip:\n Skips the currently playing song,\n if there is a next song in the queue.\n\
\• !dskip (!dramaticskip):\n Skips in any case, humorously, like the old times :D\n\
\• !dumpq (!dumpqueue):\n Dumps the queue.\n\
\• !play <ytLink>:\n If no bots are present, this plays a single song.\n It interrupts any current song,\n no link shorteners allowed."
helpCountry :: String
helpCountry = "Country Restrictions:\n\
\Shows information for the current song, or optionally for one at position <pos>.\n\
\• !restrict [<pos> or <ytLink>](!restrictions or !restricted):\n Shows the countries in which the song is not playable.\n\
\• !allowed [<pos>]:\n Shows the countries in which the song is playable."
helpExtra :: String
helpExtra = "Extras:\n\
\• !nls (!neonlightshow): Light Show!"
helpBot :: String
helpBot = "Bot Operation:\n\
\• !pause: Pauses the bot, temporarily.\n\
\• !restore: Restores the bot, from a pause.\n\
\• !kill: Kills the bot, forever.\n\
\• !ping: Pong!"
helpIss :: String
helpIss = "Feel free to report a problem here -> https://gitreports.com/issue/MicheleCastrovilli/Euphs\n\
\See the current status and issues here -> https://github.com/MicheleCastrovilli/Euphs/issues"
helpFun :: Net String
helpFun = do
botName' <- asks botName
return $ intercalate "\n\n" [helpIntro botName', helpCommands, helpHelp botName',
helpQ, helpQAdv, helpPlay, helpCountry, helpExtra, helpBot, helpIss]
helpFunShort :: Net String
helpFunShort = do
botName' <- asks botName
return $ "◉ :arrow_forward: To play a song: !q <youtube.com link> (now accepts youtu.be !)\n\
\◉ Use !help @" ++ botName' ++ " for more options ('tab' will auto-complete)"
| MicheleCastrovilli/Euphs | Bots/MusicBot/Help.hs | bsd-3-clause | 3,874 | 0 | 10 | 733 | 274 | 153 | 121 | 36 | 1 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Hakyll.Core.Dependencies.Tests
( tests
) where
--------------------------------------------------------------------------------
import Data.List (delete)
import qualified Data.Map as M
import qualified Data.Set as S
import Test.Framework (Test, testGroup)
import Test.HUnit (Assertion, (@=?))
--------------------------------------------------------------------------------
import Hakyll.Core.Dependencies
import Hakyll.Core.Identifier
import TestSuite.Util
--------------------------------------------------------------------------------
tests :: Test
tests = testGroup "Hakyll.Core.Dependencies.Tests" $
fromAssertions "analyze" [case01, case02, case03]
--------------------------------------------------------------------------------
oldUniverse :: [Identifier]
oldUniverse = M.keys oldFacts
--------------------------------------------------------------------------------
oldFacts :: DependencyFacts
oldFacts = M.fromList
[ ("posts/01.md",
[])
, ("posts/02.md",
[])
, ("index.md",
[ PatternDependency "posts/*" ["posts/01.md", "posts/02.md"]
, IdentifierDependency "posts/01.md"
, IdentifierDependency "posts/02.md"
])
]
--------------------------------------------------------------------------------
-- | posts/02.md has changed
case01 :: Assertion
case01 = S.fromList ["posts/02.md", "index.md"] @=? ood
where
(ood, _, _) = outOfDate oldUniverse (S.singleton "posts/02.md") oldFacts
--------------------------------------------------------------------------------
-- | about.md was added
case02 :: Assertion
case02 = S.singleton "about.md" @=? ood
where
(ood, _, _) = outOfDate ("about.md" : oldUniverse) S.empty oldFacts
--------------------------------------------------------------------------------
-- | posts/01.md was removed
case03 :: Assertion
case03 = S.singleton "index.md" @=? ood
where
(ood, _, _) =
outOfDate ("posts/01.md" `delete` oldUniverse) S.empty oldFacts
| bergmark/hakyll | tests/Hakyll/Core/Dependencies/Tests.hs | bsd-3-clause | 2,255 | 0 | 10 | 417 | 381 | 227 | 154 | 36 | 1 |
{-# OPTIONS -cpp #-}
------------------------------------------------------------------------
-- Program for converting .hsc files to .hs files, by converting the
-- file into a C program which is run to generate the Haskell source.
-- Certain items known only to the C compiler can then be used in
-- the Haskell module; for example #defined constants, byte offsets
-- within structures, etc.
--
-- See the documentation in the Users' Guide for more details.
import Control.Monad ( MonadPlus(..), liftM, liftM2, when )
import Data.Char ( isAlpha, isAlphaNum, isSpace, isDigit,
toUpper, intToDigit, ord )
import Data.List ( intersperse, isSuffixOf )
import System.Cmd ( system, rawSystem )
import System.Console.GetOpt
import System.Directory ( removeFile, doesFileExist )
import System.Environment ( getProgName, getArgs )
import System.Exit ( ExitCode(..), exitWith )
import System.IO ( hPutStr, hPutStrLn, stderr )
#if __GLASGOW_HASKELL__ >= 604 || defined(__NHC__) || defined(__HUGS__)
import System.Directory ( findExecutable )
#else
import System.Directory ( getPermissions, executable )
import System.Environment ( getEnv )
import Control.Monad ( foldM )
#endif
#if __GLASGOW_HASKELL__ >= 604
import System.Process ( runProcess, waitForProcess )
import System.IO ( openFile, IOMode(..), hClose )
#define HAVE_runProcess
#endif
#if ! BUILD_NHC
import Paths_hsc2hs ( getDataFileName )
#else
import System.Directory ( getCurrentDirectory )
getDataFileName s = do here <- getCurrentDirectory
return (here++"/"++s)
#endif
#ifdef __GLASGOW_HASKELL__
default_compiler = "ghc"
#else
default_compiler = "gcc"
#endif
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ < 604)
findExecutable :: String -> IO (Maybe FilePath)
findExecutable cmd =
let dir = dirname cmd
in case dir of
"" -> do -- search the shell environment PATH variable for candidates
val <- getEnv "PATH"
let psep = pathSep val
dirs = splitPath psep "" val
foldM (\a dir-> testFile a (dir++'/':cmd)) Nothing dirs
_ -> do testFile Nothing cmd
where
splitPath :: Char -> String -> String -> [String]
splitPath sep acc [] = [reverse acc]
splitPath sep acc (c:path) | c==sep = reverse acc : splitPath sep "" path
splitPath sep acc (c:path) = splitPath sep (c:acc) path
pathSep s = if length (filter (==';') s) >0 then ';' else ':'
testFile :: Maybe String -> String -> IO (Maybe String)
testFile gotit@(Just _) path = return gotit
testFile Nothing path = do
ok <- doesFileExist path
if ok then perms path else return Nothing
perms file = do
p <- getPermissions file
return (if executable p then Just file else Nothing)
dirname = reverse . safetail . dropWhile (not.(`elem`"\\/")) . reverse
where safetail [] = []
safetail (_:x) = x
#endif
version :: String
version = "hsc2hs version 0.66\n"
data Flag
= Help
| Version
| Template String
| Compiler String
| Linker String
| CompFlag String
| LinkFlag String
| NoCompile
| Include String
| Define String (Maybe String)
| Output String
| Verbose
template_flag :: Flag -> Bool
template_flag (Template _) = True
template_flag _ = False
include :: String -> Flag
include s@('\"':_) = Include s
include s@('<' :_) = Include s
include s = Include ("\""++s++"\"")
define :: String -> Flag
define s = case break (== '=') s of
(name, []) -> Define name Nothing
(name, _:value) -> Define name (Just value)
options :: [OptDescr Flag]
options = [
Option ['o'] ["output"] (ReqArg Output "FILE")
"name of main output file",
Option ['t'] ["template"] (ReqArg Template "FILE")
"template file",
Option ['c'] ["cc"] (ReqArg Compiler "PROG")
"C compiler to use",
Option ['l'] ["ld"] (ReqArg Linker "PROG")
"linker to use",
Option ['C'] ["cflag"] (ReqArg CompFlag "FLAG")
"flag to pass to the C compiler",
Option ['I'] [] (ReqArg (CompFlag . ("-I"++)) "DIR")
"passed to the C compiler",
Option ['L'] ["lflag"] (ReqArg LinkFlag "FLAG")
"flag to pass to the linker",
Option ['i'] ["include"] (ReqArg include "FILE")
"as if placed in the source",
Option ['D'] ["define"] (ReqArg define "NAME[=VALUE]")
"as if placed in the source",
Option [] ["no-compile"] (NoArg NoCompile)
"stop after writing *_hsc_make.c",
Option ['v'] ["verbose"] (NoArg Verbose)
"dump commands to stderr",
Option ['?'] ["help"] (NoArg Help)
"display this help and exit",
Option ['V'] ["version"] (NoArg Version)
"output version information and exit" ]
main :: IO ()
main = do
prog <- getProgramName
let header = "Usage: "++prog++" [OPTIONS] INPUT.hsc [...]\n"
args <- getArgs
let (flags, files, errs) = getOpt Permute options args
-- If there is no Template flag explicitly specified,
-- use the file placed by the Cabal installation.
flags_w_tpl <-
if any template_flag flags then
return flags
else do
templ <- getDataFileName "template-hsc.h"
return (Template templ : flags)
case (files, errs) of
(_, _)
| any isHelp flags_w_tpl -> bye (usageInfo header options)
| any isVersion flags_w_tpl -> bye version
where
isHelp Help = True; isHelp _ = False
isVersion Version = True; isVersion _ = False
((_:_), []) -> mapM_ (processFile flags_w_tpl) files
(_, _ ) -> die (concat errs ++ usageInfo header options)
getProgramName :: IO String
getProgramName = liftM (`withoutSuffix` "-bin") getProgName
where str `withoutSuffix` suff
| suff `isSuffixOf` str = take (length str - length suff) str
| otherwise = str
bye :: String -> IO a
bye s = putStr s >> exitWith ExitSuccess
die :: String -> IO a
die s = hPutStr stderr s >> exitWith (ExitFailure 1)
processFile :: [Flag] -> String -> IO ()
processFile flags name
= do let file_name = dosifyPath name
s <- readFile file_name
case parser of
Parser p -> case p (SourcePos file_name 1) s of
Success _ _ _ toks -> output flags file_name toks
Failure (SourcePos name' line) msg ->
die (name'++":"++show line++": "++msg++"\n")
------------------------------------------------------------------------
-- A deterministic parser which remembers the text which has been parsed.
newtype Parser a = Parser (SourcePos -> String -> ParseResult a)
data ParseResult a = Success !SourcePos String String a
| Failure !SourcePos String
data SourcePos = SourcePos String !Int
updatePos :: SourcePos -> Char -> SourcePos
updatePos pos@(SourcePos name line) ch = case ch of
'\n' -> SourcePos name (line + 1)
_ -> pos
instance Monad Parser where
return a = Parser $ \pos s -> Success pos [] s a
Parser m >>= k =
Parser $ \pos s -> case m pos s of
Success pos' out1 s' a -> case k a of
Parser k' -> case k' pos' s' of
Success pos'' out2 imp'' b ->
Success pos'' (out1++out2) imp'' b
Failure pos'' msg -> Failure pos'' msg
Failure pos' msg -> Failure pos' msg
fail msg = Parser $ \pos _ -> Failure pos msg
instance MonadPlus Parser where
mzero = fail "mzero"
Parser m `mplus` Parser n =
Parser $ \pos s -> case m pos s of
success@(Success _ _ _ _) -> success
Failure _ _ -> n pos s
getPos :: Parser SourcePos
getPos = Parser $ \pos s -> Success pos [] s pos
setPos :: SourcePos -> Parser ()
setPos pos = Parser $ \_ s -> Success pos [] s ()
message :: Parser a -> String -> Parser a
Parser m `message` msg =
Parser $ \pos s -> case m pos s of
success@(Success _ _ _ _) -> success
Failure pos' _ -> Failure pos' msg
catchOutput_ :: Parser a -> Parser String
catchOutput_ (Parser m) =
Parser $ \pos s -> case m pos s of
Success pos' out s' _ -> Success pos' [] s' out
Failure pos' msg -> Failure pos' msg
fakeOutput :: Parser a -> String -> Parser a
Parser m `fakeOutput` out =
Parser $ \pos s -> case m pos s of
Success pos' _ s' a -> Success pos' out s' a
Failure pos' msg -> Failure pos' msg
lookAhead :: Parser String
lookAhead = Parser $ \pos s -> Success pos [] s s
satisfy :: (Char -> Bool) -> Parser Char
satisfy p =
Parser $ \pos s -> case s of
c:cs | p c -> Success (updatePos pos c) [c] cs c
_ -> Failure pos "Bad character"
char_ :: Char -> Parser ()
char_ c = do
satisfy (== c) `message` (show c++" expected")
return ()
anyChar_ :: Parser ()
anyChar_ = do
satisfy (const True) `message` "Unexpected end of file"
return ()
any2Chars_ :: Parser ()
any2Chars_ = anyChar_ >> anyChar_
many :: Parser a -> Parser [a]
many p = many1 p `mplus` return []
many1 :: Parser a -> Parser [a]
many1 p = liftM2 (:) p (many p)
many_ :: Parser a -> Parser ()
many_ p = many1_ p `mplus` return ()
many1_ :: Parser a -> Parser ()
many1_ p = p >> many_ p
manySatisfy, manySatisfy1 :: (Char -> Bool) -> Parser String
manySatisfy = many . satisfy
manySatisfy1 = many1 . satisfy
manySatisfy_, manySatisfy1_ :: (Char -> Bool) -> Parser ()
manySatisfy_ = many_ . satisfy
manySatisfy1_ = many1_ . satisfy
------------------------------------------------------------------------
-- Parser of hsc syntax.
data Token
= Text SourcePos String
| Special SourcePos String String
parser :: Parser [Token]
parser = do
pos <- getPos
t <- catchOutput_ text
s <- lookAhead
rest <- case s of
[] -> return []
_:_ -> liftM2 (:) (special `fakeOutput` []) parser
return (if null t then rest else Text pos t : rest)
text :: Parser ()
text = do
s <- lookAhead
case s of
[] -> return ()
c:_ | isAlpha c || c == '_' -> do
anyChar_
manySatisfy_ (\c' -> isAlphaNum c' || c' == '_' || c' == '\'')
text
c:_ | isHsSymbol c -> do
symb <- catchOutput_ (manySatisfy_ isHsSymbol)
case symb of
"#" -> return ()
'-':'-':symb' | all (== '-') symb' -> do
return () `fakeOutput` symb
manySatisfy_ (/= '\n')
text
_ -> do
return () `fakeOutput` unescapeHashes symb
text
'\"':_ -> do anyChar_; hsString '\"'; text
'\'':_ -> do anyChar_; hsString '\''; text
'{':'-':_ -> do any2Chars_; linePragma `mplus` hsComment; text
_:_ -> do anyChar_; text
hsString :: Char -> Parser ()
hsString quote = do
s <- lookAhead
case s of
[] -> return ()
c:_ | c == quote -> anyChar_
'\\':c:_
| isSpace c -> do
anyChar_
manySatisfy_ isSpace
char_ '\\' `mplus` return ()
hsString quote
| otherwise -> do any2Chars_; hsString quote
_:_ -> do anyChar_; hsString quote
hsComment :: Parser ()
hsComment = do
s <- lookAhead
case s of
[] -> return ()
'-':'}':_ -> any2Chars_
'{':'-':_ -> do any2Chars_; hsComment; hsComment
_:_ -> do anyChar_; hsComment
linePragma :: Parser ()
linePragma = do
char_ '#'
manySatisfy_ isSpace
satisfy (\c -> c == 'L' || c == 'l')
satisfy (\c -> c == 'I' || c == 'i')
satisfy (\c -> c == 'N' || c == 'n')
satisfy (\c -> c == 'E' || c == 'e')
manySatisfy1_ isSpace
line <- liftM read $ manySatisfy1 isDigit
manySatisfy1_ isSpace
char_ '\"'
name <- manySatisfy (/= '\"')
char_ '\"'
manySatisfy_ isSpace
char_ '#'
char_ '-'
char_ '}'
setPos (SourcePos name (line - 1))
isHsSymbol :: Char -> Bool
isHsSymbol '!' = True; isHsSymbol '#' = True; isHsSymbol '$' = True
isHsSymbol '%' = True; isHsSymbol '&' = True; isHsSymbol '*' = True
isHsSymbol '+' = True; isHsSymbol '.' = True; isHsSymbol '/' = True
isHsSymbol '<' = True; isHsSymbol '=' = True; isHsSymbol '>' = True
isHsSymbol '?' = True; isHsSymbol '@' = True; isHsSymbol '\\' = True
isHsSymbol '^' = True; isHsSymbol '|' = True; isHsSymbol '-' = True
isHsSymbol '~' = True
isHsSymbol _ = False
unescapeHashes :: String -> String
unescapeHashes [] = []
unescapeHashes ('#':'#':s) = '#' : unescapeHashes s
unescapeHashes (c:s) = c : unescapeHashes s
lookAheadC :: Parser String
lookAheadC = liftM joinLines lookAhead
where
joinLines [] = []
joinLines ('\\':'\n':s) = joinLines s
joinLines (c:s) = c : joinLines s
satisfyC :: (Char -> Bool) -> Parser Char
satisfyC p = do
s <- lookAhead
case s of
'\\':'\n':_ -> do any2Chars_ `fakeOutput` []; satisfyC p
_ -> satisfy p
charC_ :: Char -> Parser ()
charC_ c = do
satisfyC (== c) `message` (show c++" expected")
return ()
anyCharC_ :: Parser ()
anyCharC_ = do
satisfyC (const True) `message` "Unexpected end of file"
return ()
any2CharsC_ :: Parser ()
any2CharsC_ = anyCharC_ >> anyCharC_
manySatisfyC :: (Char -> Bool) -> Parser String
manySatisfyC = many . satisfyC
manySatisfyC_ :: (Char -> Bool) -> Parser ()
manySatisfyC_ = many_ . satisfyC
special :: Parser Token
special = do
manySatisfyC_ (\c -> isSpace c && c /= '\n')
s <- lookAheadC
case s of
'{':_ -> do
anyCharC_
manySatisfyC_ isSpace
sp <- keyArg (== '\n')
charC_ '}'
return sp
_ -> keyArg (const False)
keyArg :: (Char -> Bool) -> Parser Token
keyArg eol = do
pos <- getPos
key <- keyword `message` "hsc keyword or '{' expected"
manySatisfyC_ (\c' -> isSpace c' && c' /= '\n' || eol c')
arg <- catchOutput_ (argument eol)
return (Special pos key arg)
keyword :: Parser String
keyword = do
c <- satisfyC (\c' -> isAlpha c' || c' == '_')
cs <- manySatisfyC (\c' -> isAlphaNum c' || c' == '_')
return (c:cs)
argument :: (Char -> Bool) -> Parser ()
argument eol = do
s <- lookAheadC
case s of
[] -> return ()
c:_ | eol c -> do anyCharC_; argument eol
'\n':_ -> return ()
'\"':_ -> do anyCharC_; cString '\"'; argument eol
'\'':_ -> do anyCharC_; cString '\''; argument eol
'(':_ -> do anyCharC_; nested ')'; argument eol
')':_ -> return ()
'/':'*':_ -> do any2CharsC_; cComment; argument eol
'/':'/':_ -> do
any2CharsC_; manySatisfyC_ (/= '\n'); argument eol
'[':_ -> do anyCharC_; nested ']'; argument eol
']':_ -> return ()
'{':_ -> do anyCharC_; nested '}'; argument eol
'}':_ -> return ()
_:_ -> do anyCharC_; argument eol
nested :: Char -> Parser ()
nested c = do argument (== '\n'); charC_ c
cComment :: Parser ()
cComment = do
s <- lookAheadC
case s of
[] -> return ()
'*':'/':_ -> do any2CharsC_
_:_ -> do anyCharC_; cComment
cString :: Char -> Parser ()
cString quote = do
s <- lookAheadC
case s of
[] -> return ()
c:_ | c == quote -> anyCharC_
'\\':_:_ -> do any2CharsC_; cString quote
_:_ -> do anyCharC_; cString quote
------------------------------------------------------------------------
-- Write the output files.
splitName :: String -> (String, String)
splitName name =
case break (== '/') name of
(file, []) -> ([], file)
(dir, sep:rest) -> (dir++sep:restDir, restFile)
where
(restDir, restFile) = splitName rest
splitExt :: String -> (String, String)
splitExt name =
case break (== '.') name of
(base, []) -> (base, [])
(base, sepRest@(sep:rest))
| null restExt -> (base, sepRest)
| otherwise -> (base++sep:restBase, restExt)
where
(restBase, restExt) = splitExt rest
output :: [Flag] -> String -> [Token] -> IO ()
output flags name toks = do
(outName, outDir, outBase) <- case [f | Output f <- flags] of
[] -> if not (null ext) && last ext == 'c'
then return (dir++base++init ext, dir, base)
else
if ext == ".hs"
then return (dir++base++"_out.hs", dir, base)
else return (dir++base++".hs", dir, base)
where
(dir, file) = splitName name
(base, ext) = splitExt file
[f] -> let
(dir, file) = splitName f
(base, _) = splitExt file
in return (f, dir, base)
_ -> onlyOne "output file"
let cProgName = outDir++outBase++"_hsc_make.c"
oProgName = outDir++outBase++"_hsc_make.o"
progName = outDir++outBase++"_hsc_make"
#if defined(mingw32_HOST_OS) || defined(__CYGWIN32__)
-- This is a real hack, but the quoting mechanism used for calling the C preprocesseor
-- via GHC has changed a few times, so this seems to be the only way... :-P * * *
++ ".exe"
#endif
outHFile = outBase++"_hsc.h"
outHName = outDir++outHFile
outCName = outDir++outBase++"_hsc.c"
beVerbose = any (\ x -> case x of { Verbose -> True; _ -> False}) flags
let execProgName
| null outDir = dosifyPath ("./" ++ progName)
| otherwise = progName
let specials = [(pos, key, arg) | Special pos key arg <- toks]
let needsC = any (\(_, key, _) -> key == "def") specials
needsH = needsC
let includeGuard = map fixChar outHName
where
fixChar c | isAlphaNum c = toUpper c
| otherwise = '_'
compiler <- case [c | Compiler c <- flags] of
[] -> do
mb_path <- findExecutable default_compiler
case mb_path of
Nothing -> die ("Can't find "++default_compiler++"\n")
Just path -> return path
[c] -> return c
_ -> onlyOne "compiler"
linker <- case [l | Linker l <- flags] of
[] -> return compiler
[l] -> return l
_ -> onlyOne "linker"
writeFile cProgName $
concatMap outFlagHeaderCProg flags++
concatMap outHeaderCProg specials++
"\nint main (int argc, char *argv [])\n{\n"++
outHeaderHs flags (if needsH then Just outHName else Nothing) specials++
outHsLine (SourcePos name 0)++
concatMap outTokenHs toks++
" return 0;\n}\n"
-- NOTE: hbc compiles "[() | NoCompile <- flags]" into wrong code,
-- so we use something slightly more complicated. :-P
when (any (\x -> case x of NoCompile -> True; _ -> False) flags) $
exitWith ExitSuccess
rawSystemL ("compiling " ++ cProgName) beVerbose compiler
( ["-c"]
++ [f | CompFlag f <- flags]
++ [cProgName]
++ ["-o", oProgName]
)
removeFile cProgName
rawSystemL ("linking " ++ oProgName) beVerbose linker
( [f | LinkFlag f <- flags]
++ [oProgName]
++ ["-o", progName]
)
removeFile oProgName
rawSystemWithStdOutL ("running " ++ execProgName) beVerbose execProgName [] outName
removeFile progName
when needsH $ writeFile outHName $
"#ifndef "++includeGuard++"\n" ++
"#define "++includeGuard++"\n" ++
"#if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 409\n" ++
"#include <Rts.h>\n" ++
"#endif\n" ++
"#include <HsFFI.h>\n" ++
"#if __NHC__\n" ++
"#undef HsChar\n" ++
"#define HsChar int\n" ++
"#endif\n" ++
concatMap outFlagH flags++
concatMap outTokenH specials++
"#endif\n"
when needsC $ writeFile outCName $
"#include \""++outHFile++"\"\n"++
concatMap outTokenC specials
-- NB. outHFile not outHName; works better when processed
-- by gcc or mkdependC.
rawSystemL :: String -> Bool -> FilePath -> [String] -> IO ()
rawSystemL action flg prog args = do
let cmdLine = prog++" "++unwords args
when flg $ hPutStrLn stderr ("Executing: " ++ cmdLine)
#ifndef HAVE_rawSystem
exitStatus <- system cmdLine
#else
exitStatus <- rawSystem prog args
#endif
case exitStatus of
ExitFailure _ -> die $ action ++ " failed\ncommand was: " ++ cmdLine ++ "\n"
_ -> return ()
rawSystemWithStdOutL :: String -> Bool -> FilePath -> [String] -> FilePath -> IO ()
rawSystemWithStdOutL action flg prog args outFile = do
let cmdLine = prog++" "++unwords args++" >"++outFile
when flg (hPutStrLn stderr ("Executing: " ++ cmdLine))
#ifndef HAVE_runProcess
exitStatus <- system cmdLine
#else
hOut <- openFile outFile WriteMode
process <- runProcess prog args Nothing Nothing Nothing (Just hOut) Nothing
exitStatus <- waitForProcess process
hClose hOut
#endif
case exitStatus of
ExitFailure _ -> die $ action ++ " failed\ncommand was: " ++ cmdLine ++ "\n"
_ -> return ()
onlyOne :: String -> IO a
onlyOne what = die ("Only one "++what++" may be specified\n")
outFlagHeaderCProg :: Flag -> String
outFlagHeaderCProg (Template t) = "#include \""++t++"\"\n"
outFlagHeaderCProg (Include f) = "#include "++f++"\n"
outFlagHeaderCProg (Define n Nothing) = "#define "++n++" 1\n"
outFlagHeaderCProg (Define n (Just v)) = "#define "++n++" "++v++"\n"
outFlagHeaderCProg _ = ""
outHeaderCProg :: (SourcePos, String, String) -> String
outHeaderCProg (pos, key, arg) = case key of
"include" -> outCLine pos++"#include "++arg++"\n"
"define" -> outCLine pos++"#define "++arg++"\n"
"undef" -> outCLine pos++"#undef "++arg++"\n"
"def" -> case arg of
's':'t':'r':'u':'c':'t':' ':_ -> outCLine pos++arg++"\n"
't':'y':'p':'e':'d':'e':'f':' ':_ -> outCLine pos++arg++"\n"
_ -> ""
_ | conditional key -> outCLine pos++"#"++key++" "++arg++"\n"
"let" -> case break (== '=') arg of
(_, "") -> ""
(header, _:body) -> case break isSpace header of
(name, args) ->
outCLine pos++
"#define hsc_"++name++"("++dropWhile isSpace args++") " ++
"printf ("++joinLines body++");\n"
_ -> ""
where
joinLines = concat . intersperse " \\\n" . lines
outHeaderHs :: [Flag] -> Maybe String -> [(SourcePos, String, String)] -> String
outHeaderHs flags inH toks =
"#if " ++
"__GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 409\n" ++
" printf (\"{-# OPTIONS -optc-D" ++
"__GLASGOW_HASKELL__=%d #-}\\n\", " ++
"__GLASGOW_HASKELL__);\n" ++
"#endif\n"++
case inH of
Nothing -> concatMap outFlag flags++concatMap outSpecial toks
Just f -> outInclude ("\""++f++"\"")
where
outFlag (Include f) = outInclude f
outFlag (Define n Nothing) = outOption ("-optc-D"++n)
outFlag (Define n (Just v)) = outOption ("-optc-D"++n++"="++v)
outFlag _ = ""
outSpecial (pos, key, arg) = case key of
"include" -> outInclude arg
"define" | goodForOptD arg -> outOption ("-optc-D"++toOptD arg)
| otherwise -> ""
_ | conditional key -> outCLine pos++"#"++key++" "++arg++"\n"
_ -> ""
goodForOptD arg = case arg of
"" -> True
c:_ | isSpace c -> True
'(':_ -> False
_:s -> goodForOptD s
toOptD arg = case break isSpace arg of
(name, "") -> name
(name, _:value) -> name++'=':dropWhile isSpace value
outOption s =
"#if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 603\n" ++
" printf (\"{-# OPTIONS %s #-}\\n\", \""++
showCString s++"\");\n"++
"#else\n"++
" printf (\"{-# OPTIONS_GHC %s #-}\\n\", \""++
showCString s++"\");\n"++
"#endif\n"
outInclude s =
"#if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 603\n" ++
" printf (\"{-# OPTIONS -#include %s #-}\\n\", \""++
showCString s++"\");\n"++
"#else\n"++
" printf (\"{-# INCLUDE %s #-}\\n\", \""++
showCString s++"\");\n"++
"#endif\n"
outTokenHs :: Token -> String
outTokenHs (Text pos txt) =
case break (== '\n') txt of
(allTxt, []) -> outText allTxt
(first, _:rest) ->
outText (first++"\n")++
outHsLine pos++
outText rest
where
outText s = " fputs (\""++showCString s++"\", stdout);\n"
outTokenHs (Special pos key arg) =
case key of
"include" -> ""
"define" -> ""
"undef" -> ""
"def" -> ""
_ | conditional key -> outCLine pos++"#"++key++" "++arg++"\n"
"let" -> ""
"enum" -> outCLine pos++outEnum arg
_ -> outCLine pos++" hsc_"++key++" ("++arg++");\n"
outEnum :: String -> String
outEnum arg =
case break (== ',') arg of
(_, []) -> ""
(t, _:afterT) -> case break (== ',') afterT of
(f, afterF) -> let
enums [] = ""
enums (_:s) = case break (== ',') s of
(enum, rest) -> let
this = case break (== '=') $ dropWhile isSpace enum of
(name, []) ->
" hsc_enum ("++t++", "++f++", " ++
"hsc_haskellize (\""++name++"\"), "++
name++");\n"
(hsName, _:cName) ->
" hsc_enum ("++t++", "++f++", " ++
"printf (\"%s\", \""++hsName++"\"), "++
cName++");\n"
in this++enums rest
in enums afterF
outFlagH :: Flag -> String
outFlagH (Include f) = "#include "++f++"\n"
outFlagH (Define n Nothing) = "#define "++n++" 1\n"
outFlagH (Define n (Just v)) = "#define "++n++" "++v++"\n"
outFlagH _ = ""
outTokenH :: (SourcePos, String, String) -> String
outTokenH (pos, key, arg) =
case key of
"include" -> outCLine pos++"#include "++arg++"\n"
"define" -> outCLine pos++"#define " ++arg++"\n"
"undef" -> outCLine pos++"#undef " ++arg++"\n"
"def" -> outCLine pos++case arg of
's':'t':'r':'u':'c':'t':' ':_ -> arg++"\n"
't':'y':'p':'e':'d':'e':'f':' ':_ -> arg++"\n"
'i':'n':'l':'i':'n':'e':' ':_ ->
"#ifdef __GNUC__\n" ++
"extern\n" ++
"#endif\n"++
arg++"\n"
_ -> "extern "++header++";\n"
where header = takeWhile (\c -> c /= '{' && c /= '=') arg
_ | conditional key -> outCLine pos++"#"++key++" "++arg++"\n"
_ -> ""
outTokenC :: (SourcePos, String, String) -> String
outTokenC (pos, key, arg) =
case key of
"def" -> case arg of
's':'t':'r':'u':'c':'t':' ':_ -> ""
't':'y':'p':'e':'d':'e':'f':' ':_ -> ""
'i':'n':'l':'i':'n':'e':' ':arg' ->
case span (\c -> c /= '{' && c /= '=') arg' of
(header, body) ->
outCLine pos++
"#ifndef __GNUC__\n" ++
"extern inline\n" ++
"#endif\n"++
header++
"\n#ifndef __GNUC__\n" ++
";\n" ++
"#else\n"++
body++
"\n#endif\n"
_ -> outCLine pos++arg++"\n"
_ | conditional key -> outCLine pos++"#"++key++" "++arg++"\n"
_ -> ""
conditional :: String -> Bool
conditional "if" = True
conditional "ifdef" = True
conditional "ifndef" = True
conditional "elif" = True
conditional "else" = True
conditional "endif" = True
conditional "error" = True
conditional "warning" = True
conditional _ = False
outCLine :: SourcePos -> String
outCLine (SourcePos name line) =
"#line "++show line++" \""++showCString (snd (splitName name))++"\"\n"
outHsLine :: SourcePos -> String
outHsLine (SourcePos name line) =
" hsc_line ("++show (line + 1)++", \""++
showCString name++"\");\n"
showCString :: String -> String
showCString = concatMap showCChar
where
showCChar '\"' = "\\\""
showCChar '\'' = "\\\'"
showCChar '?' = "\\?"
showCChar '\\' = "\\\\"
showCChar c | c >= ' ' && c <= '~' = [c]
showCChar '\a' = "\\a"
showCChar '\b' = "\\b"
showCChar '\f' = "\\f"
showCChar '\n' = "\\n\"\n \""
showCChar '\r' = "\\r"
showCChar '\t' = "\\t"
showCChar '\v' = "\\v"
showCChar c = ['\\',
intToDigit (ord c `quot` 64),
intToDigit (ord c `quot` 8 `mod` 8),
intToDigit (ord c `mod` 8)]
-----------------------------------------
-- Modified version from ghc/compiler/SysTools
-- Convert paths foo/baz to foo\baz on Windows
subst :: Char -> Char -> String -> String
#if defined(mingw32_HOST_OS) || defined(__CYGWIN32__)
subst a b = map (\x -> if x == a then b else x)
#else
subst _ _ = id
#endif
dosifyPath :: String -> String
dosifyPath = subst '/' '\\'
| alekar/hugs | hsc2hs/Main.hs | bsd-3-clause | 29,871 | 733 | 41 | 9,360 | 9,964 | 5,088 | 4,876 | 672 | 14 |
module Chip8.OpCode
( Fun(..), Op(..)
, decode
) where
import Chip8.Utils
import Chip8.Types
data Fun = Id
| Or
| And
| XOr
| Add
| Subtract
| ShiftRight
| SubtractFlip
| ShiftLeft
deriving (Show)
data Op = ClearScreen
| Ret
| Sys Addr
| Jump Addr
| Call Addr
| SkipEqImm Reg Word8 Bool -- True if skip on eq
| SkipEqReg Reg Reg Bool
| PutImm Reg Word8
| AddImm Reg Word8
| Move Reg Reg Fun
| SetPtr Addr
| JumpPlusR0 Addr
| Randomize Reg Word8
| DrawSprite Reg Reg Nibble
| SkipKey Reg Bool -- True if skip on key pressed
| GetTimer Reg
| WaitKey Reg
| SetTimer Reg
| SetSound Reg
| AddPtr Reg
| LoadFont Reg
| StoreBCD Reg
| StoreRegs Reg
| LoadRegs Reg
deriving (Show)
unpack :: (Word8, Word8) -> (Nibble, Nibble, Nibble, Nibble)
unpack xy = case both unpackWord xy of
((h, l), (h', l')) -> (h, l, h', l')
where
unpackWord :: Word8 -> (Nibble, Nibble)
unpackWord x = both fromIntegral $ x `divMod` 16
packAddr :: Nibble -> Nibble -> Nibble -> Addr
packAddr a1 a2 a3 = sum [ fromIntegral a1 * 256
, fromIntegral a2 * 16
, fromIntegral a3
]
decode :: (Word8, Word8) -> Op
decode code@(hi, lo) = case codes of
(0x0, 0x0, 0xe, 0x0) -> ClearScreen
(0x0, 0x0, 0xe, 0xe) -> Ret
(0x0, _, _, _) -> Sys addr
(0x1, _, _, _) -> Jump addr
(0x2, _, _, _) -> Call addr
(0x3, x, _, _) -> SkipEqImm (R x) imm True
(0x4, x, _, _) -> SkipEqImm (R x) imm False
(0x5, x, y, 0x0) -> SkipEqReg (R x) (R y) True
(0x6, x, _, _) -> PutImm (R x) imm
(0x7, x, _, _) -> AddImm (R x) imm
(0x8, x, y, fun) -> Move (R x) (R y) (decodeFun fun)
(0x9, x, y, 0x0) -> SkipEqReg (R x) (R y) False
(0xa, _, _, _) -> SetPtr addr
(0xb, _, _, _) -> JumpPlusR0 addr
(0xc, x, _, _) -> Randomize (R x) imm
(0xd, x, y, n) -> DrawSprite (R x) (R y) n
(0xe, x, 0x9, 0xe) -> SkipKey (R x) True
(0xe, x, 0xa, 0x1) -> SkipKey (R x) False
(0xf, x, 0x0, 0x7) -> GetTimer (R x)
(0xf, x, 0x0, 0xa) -> WaitKey (R x)
(0xf, x, 0x1, 0x5) -> SetTimer (R x)
(0xf, x, 0x1, 0x8) -> SetSound (R x)
(0xf, x, 0x1, 0xe) -> AddPtr (R x)
(0xf, x, 0x2, 0x9) -> LoadFont (R x)
(0xf, x, 0x3, 0x3) -> StoreBCD (R x)
(0xf, x, 0x5, 0x5) -> StoreRegs (R x)
(0xf, x, 0x6, 0x5) -> LoadRegs (R x)
_ -> fatal "Unknown opcode" code
where
codes@(a1, a2, a3, a4) = unpack code
addr = packAddr a2 a3 a4
imm = lo
decodeFun :: Nibble -> Fun
decodeFun 0x0 = Id
decodeFun 0x1 = Or
decodeFun 0x2 = And
decodeFun 0x3 = XOr
decodeFun 0x4 = Add
decodeFun 0x5 = Subtract
decodeFun 0x6 = ShiftRight
decodeFun 0x7 = SubtractFlip
decodeFun 0xe = ShiftLeft
decodeFun n = fatal "Unknown Move function" n
fatal :: (Show a) => String -> a -> b
fatal s x = error $ s ++ ": " ++ show x
| gergoerdi/chip8-haskell | src/Chip8/OpCode.hs | bsd-3-clause | 3,272 | 0 | 10 | 1,227 | 1,378 | 770 | 608 | 95 | 37 |
-- Copyright (c) 2015 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -funbox-strict-fields -Wall -Werror #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- | A module defining a monad class for implementing the type checker
module Control.Monad.TypeCheck.Class(
MonadProofObligations(..),
MonadTypeCheck(..),
MonadTypeErrors(..)
) where
import Control.Monad.ProofObligations.Class
import Control.Monad.TypeErrors.Class
import Language.Salt.Core.Syntax
-- | A monad class encapsulating all context information needed by the
-- type checker
class (MonadProofObligations m, MonadTypeErrors sym m) =>
MonadTypeCheck sym m where
-- | The type of propositions
propType :: m (Term sym sym)
-- | The type of types
typeType :: m (Term sym sym)
| emc2/saltlang | src/salt/Control/Monad/TypeCheck/Class.hs | bsd-3-clause | 2,278 | 0 | 9 | 398 | 148 | 103 | 45 | 13 | 0 |
{- Image.hs
- Write an image to PPM (Portable Pixmap) format.
- http://en.wikipedia.org/wiki/Portable_pixmap
-
- Timothy A. Chagnon
- CS 636 - Spring 2009
-}
module Image where
import Color
import Math
import Scene
-- Convert a pixel to PPM P3 format
p3color :: Color -> String
p3color (Vec3f r g b) = unwords [showC r, showC g, showC b] where
showC c = show $ floor $ 255 * (min 1 c)
writeImage :: Scene -> [(Color,Int)] -> IO ()
writeImage scene pixels = do
let (w, h) = (width scene, height scene)
let file = outfile scene
let sf = 2^(superSample scene)
let maxC = 4*((fromIntegral sf)^2) :: RealT
let (pix, cnts) = unzip pixels
if outputSampleMap scene
then do
putStrLn $ "Total samples: " ++ (show (sum cnts))
writePPM file w h (map (cnt2pix maxC) cnts)
else
writePPM file w h pix
-- Write pixels to PPM file
writePPM :: String -> Int -> Int -> [Color] -> IO ()
writePPM file width height pixels = do
let magic = "P3"
let params = unwords [show x | x <- [width, height, 255]]
let p3pixels = map p3color pixels
let outData = unlines ([magic, params] ++ p3pixels)
writeFile file outData
return ()
cnt2pix :: RealT -> Int -> Color
cnt2pix sf cnt =
let c = (fromIntegral cnt)/sf in
Vec3f c c c
| tchagnon/cs636-raytracer | a6/Image.hs | apache-2.0 | 1,358 | 0 | 14 | 389 | 503 | 251 | 252 | 31 | 2 |
{-
(c) The AQUA Project, Glasgow University, 1993-1998
\section[Simplify]{The main module of the simplifier}
-}
{-# LANGUAGE CPP #-}
module Simplify ( simplTopBinds, simplExpr ) where
#include "HsVersions.h"
import DynFlags
import SimplMonad
import Type hiding ( substTy, extendTvSubst, substTyVar )
import SimplEnv
import SimplUtils
import FamInstEnv ( FamInstEnv )
import Literal ( litIsLifted ) --, mkMachInt ) -- temporalily commented out. See #8326
import Id
import MkId ( seqId, voidPrimId )
import MkCore ( mkImpossibleExpr, castBottomExpr )
import IdInfo
import Name ( mkSystemVarName, isExternalName )
import Coercion hiding ( substCo, substTy, substCoVar, extendTvSubst )
import OptCoercion ( optCoercion )
import FamInstEnv ( topNormaliseType_maybe )
import DataCon ( DataCon, dataConWorkId, dataConRepStrictness
, isMarkedStrict ) --, dataConTyCon, dataConTag, fIRST_TAG )
--import TyCon ( isEnumerationTyCon ) -- temporalily commented out. See #8326
import CoreMonad ( Tick(..), SimplifierMode(..) )
import CoreSyn
import Demand ( StrictSig(..), dmdTypeDepth, isStrictDmd )
import PprCore ( pprCoreExpr )
import CoreUnfold
import CoreUtils
import CoreArity
--import PrimOp ( tagToEnumKey ) -- temporalily commented out. See #8326
import Rules ( lookupRule, getRules )
import TysPrim ( voidPrimTy ) --, intPrimTy ) -- temporalily commented out. See #8326
import BasicTypes ( TopLevelFlag(..), isTopLevel, RecFlag(..) )
import MonadUtils ( foldlM, mapAccumLM, liftIO )
import Maybes ( orElse )
--import Unique ( hasKey ) -- temporalily commented out. See #8326
import Control.Monad
import Data.List ( mapAccumL )
import Outputable
import FastString
import Pair
import Util
import ErrUtils
{-
The guts of the simplifier is in this module, but the driver loop for
the simplifier is in SimplCore.hs.
-----------------------------------------
*** IMPORTANT NOTE ***
-----------------------------------------
The simplifier used to guarantee that the output had no shadowing, but
it does not do so any more. (Actually, it never did!) The reason is
documented with simplifyArgs.
-----------------------------------------
*** IMPORTANT NOTE ***
-----------------------------------------
Many parts of the simplifier return a bunch of "floats" as well as an
expression. This is wrapped as a datatype SimplUtils.FloatsWith.
All "floats" are let-binds, not case-binds, but some non-rec lets may
be unlifted (with RHS ok-for-speculation).
-----------------------------------------
ORGANISATION OF FUNCTIONS
-----------------------------------------
simplTopBinds
- simplify all top-level binders
- for NonRec, call simplRecOrTopPair
- for Rec, call simplRecBind
------------------------------
simplExpr (applied lambda) ==> simplNonRecBind
simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
------------------------------
simplRecBind [binders already simplfied]
- use simplRecOrTopPair on each pair in turn
simplRecOrTopPair [binder already simplified]
Used for: recursive bindings (top level and nested)
top-level non-recursive bindings
Returns:
- check for PreInlineUnconditionally
- simplLazyBind
simplNonRecBind
Used for: non-top-level non-recursive bindings
beta reductions (which amount to the same thing)
Because it can deal with strict arts, it takes a
"thing-inside" and returns an expression
- check for PreInlineUnconditionally
- simplify binder, including its IdInfo
- if strict binding
simplStrictArg
mkAtomicArgs
completeNonRecX
else
simplLazyBind
addFloats
simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
Used for: binding case-binder and constr args in a known-constructor case
- check for PreInLineUnconditionally
- simplify binder
- completeNonRecX
------------------------------
simplLazyBind: [binder already simplified, RHS not]
Used for: recursive bindings (top level and nested)
top-level non-recursive bindings
non-top-level, but *lazy* non-recursive bindings
[must not be strict or unboxed]
Returns floats + an augmented environment, not an expression
- substituteIdInfo and add result to in-scope
[so that rules are available in rec rhs]
- simplify rhs
- mkAtomicArgs
- float if exposes constructor or PAP
- completeBind
completeNonRecX: [binder and rhs both simplified]
- if the the thing needs case binding (unlifted and not ok-for-spec)
build a Case
else
completeBind
addFloats
completeBind: [given a simplified RHS]
[used for both rec and non-rec bindings, top level and not]
- try PostInlineUnconditionally
- add unfolding [this is the only place we add an unfolding]
- add arity
Right hand sides and arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In many ways we want to treat
(a) the right hand side of a let(rec), and
(b) a function argument
in the same way. But not always! In particular, we would
like to leave these arguments exactly as they are, so they
will match a RULE more easily.
f (g x, h x)
g (+ x)
It's harder to make the rule match if we ANF-ise the constructor,
or eta-expand the PAP:
f (let { a = g x; b = h x } in (a,b))
g (\y. + x y)
On the other hand if we see the let-defns
p = (g x, h x)
q = + x
then we *do* want to ANF-ise and eta-expand, so that p and q
can be safely inlined.
Even floating lets out is a bit dubious. For let RHS's we float lets
out if that exposes a value, so that the value can be inlined more vigorously.
For example
r = let x = e in (x,x)
Here, if we float the let out we'll expose a nice constructor. We did experiments
that showed this to be a generally good thing. But it was a bad thing to float
lets out unconditionally, because that meant they got allocated more often.
For function arguments, there's less reason to expose a constructor (it won't
get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
So for the moment we don't float lets out of function arguments either.
Eta expansion
~~~~~~~~~~~~~~
For eta expansion, we want to catch things like
case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
If the \x was on the RHS of a let, we'd eta expand to bring the two
lambdas together. And in general that's a good thing to do. Perhaps
we should eta expand wherever we find a (value) lambda? Then the eta
expansion at a let RHS can concentrate solely on the PAP case.
************************************************************************
* *
\subsection{Bindings}
* *
************************************************************************
-}
simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
simplTopBinds env0 binds0
= do { -- Put all the top-level binders into scope at the start
-- so that if a transformation rule has unexpectedly brought
-- anything into scope, then we don't get a complaint about that.
-- It's rather as if the top-level binders were imported.
-- See note [Glomming] in OccurAnal.
; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
; env2 <- simpl_binds env1 binds0
; freeTick SimplifierDone
; return env2 }
where
-- We need to track the zapped top-level binders, because
-- they should have their fragile IdInfo zapped (notably occurrence info)
-- That's why we run down binds and bndrs' simultaneously.
--
simpl_binds :: SimplEnv -> [InBind] -> SimplM SimplEnv
simpl_binds env [] = return env
simpl_binds env (bind:binds) = do { env' <- simpl_bind env bind
; simpl_binds env' binds }
simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel NonRecursive b b' r
where
(env', b') = addBndrRules env b (lookupRecBndr env b)
{-
************************************************************************
* *
\subsection{Lazy bindings}
* *
************************************************************************
simplRecBind is used for
* recursive bindings only
-}
simplRecBind :: SimplEnv -> TopLevelFlag
-> [(InId, InExpr)]
-> SimplM SimplEnv
simplRecBind env0 top_lvl pairs0
= do { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
; env1 <- go (zapFloats env_with_info) triples
; return (env0 `addRecFloats` env1) }
-- addFloats adds the floats from env1,
-- _and_ updates env0 with the in-scope set from env1
where
add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
-- Add the (substituted) rules to the binder
add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
where
(env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
go env [] = return env
go env ((old_bndr, new_bndr, rhs) : pairs)
= do { env' <- simplRecOrTopPair env top_lvl Recursive old_bndr new_bndr rhs
; go env' pairs }
{-
simplOrTopPair is used for
* recursive bindings (whether top level or not)
* top-level non-recursive bindings
It assumes the binder has already been simplified, but not its IdInfo.
-}
simplRecOrTopPair :: SimplEnv
-> TopLevelFlag -> RecFlag
-> InId -> OutBndr -> InExpr -- Binder and rhs
-> SimplM SimplEnv -- Returns an env that includes the binding
simplRecOrTopPair env top_lvl is_rec old_bndr new_bndr rhs
= do { dflags <- getDynFlags
; trace_bind dflags $
if preInlineUnconditionally dflags env top_lvl old_bndr rhs
-- Check for unconditional inline
then do tick (PreInlineUnconditionally old_bndr)
return (extendIdSubst env old_bndr (mkContEx env rhs))
else simplLazyBind env top_lvl is_rec old_bndr new_bndr rhs env }
where
trace_bind dflags thing_inside
| not (dopt Opt_D_verbose_core2core dflags)
= thing_inside
| otherwise
= pprTrace "SimplBind" (ppr old_bndr) thing_inside
-- trace_bind emits a trace for each top-level binding, which
-- helps to locate the tracing for inlining and rule firing
{-
simplLazyBind is used for
* [simplRecOrTopPair] recursive bindings (whether top level or not)
* [simplRecOrTopPair] top-level non-recursive bindings
* [simplNonRecE] non-top-level *lazy* non-recursive bindings
Nota bene:
1. It assumes that the binder is *already* simplified,
and is in scope, and its IdInfo too, except unfolding
2. It assumes that the binder type is lifted.
3. It does not check for pre-inline-unconditionally;
that should have been done already.
-}
simplLazyBind :: SimplEnv
-> TopLevelFlag -> RecFlag
-> InId -> OutId -- Binder, both pre-and post simpl
-- The OutId has IdInfo, except arity, unfolding
-> InExpr -> SimplEnv -- The RHS and its environment
-> SimplM SimplEnv
-- Precondition: rhs obeys the let/app invariant
simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
= -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$ ppr rhs $$ ppr (seIdSubst rhs_se)) $
do { let rhs_env = rhs_se `setInScope` env
(tvs, body) = case collectTyBinders rhs of
(tvs, body) | not_lam body -> (tvs,body)
| otherwise -> ([], rhs)
not_lam (Lam _ _) = False
not_lam (Tick t e) | not (tickishFloatable t)
= not_lam e -- eta-reduction could float
not_lam _ = True
-- Do not do the "abstract tyyvar" thing if there's
-- a lambda inside, because it defeats eta-reduction
-- f = /\a. \x. g a x
-- should eta-reduce.
; (body_env, tvs') <- simplBinders rhs_env tvs
-- See Note [Floating and type abstraction] in SimplUtils
-- Simplify the RHS
; let rhs_cont = mkRhsStop (substTy body_env (exprType body))
; (body_env1, body1) <- simplExprF body_env body rhs_cont
-- ANF-ise a constructor or PAP rhs
; (body_env2, body2) <- prepareRhs top_lvl body_env1 bndr1 body1
; (env', rhs')
<- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
then -- No floating, revert to body1
do { rhs' <- mkLam tvs' (wrapFloats body_env1 body1) rhs_cont
; return (env, rhs') }
else if null tvs then -- Simple floating
do { tick LetFloatFromLet
; return (addFloats env body_env2, body2) }
else -- Do type-abstraction first
do { tick LetFloatFromLet
; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
; rhs' <- mkLam tvs' body3 rhs_cont
; env' <- foldlM (addPolyBind top_lvl) env poly_binds
; return (env', rhs') }
; completeBind env' top_lvl bndr bndr1 rhs' }
{-
A specialised variant of simplNonRec used when the RHS is already simplified,
notably in knownCon. It uses case-binding where necessary.
-}
simplNonRecX :: SimplEnv
-> InId -- Old binder
-> OutExpr -- Simplified RHS
-> SimplM SimplEnv
-- Precondition: rhs satisfies the let/app invariant
simplNonRecX env bndr new_rhs
| isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of c { (p,q) -> p }
= return env -- Here c is dead, and we avoid creating
-- the binding c = (a,b)
| Coercion co <- new_rhs
= return (extendCvSubst env bndr co)
| otherwise
= do { (env', bndr') <- simplBinder env bndr
; completeNonRecX NotTopLevel env' (isStrictId bndr) bndr bndr' new_rhs }
-- simplNonRecX is only used for NotTopLevel things
completeNonRecX :: TopLevelFlag -> SimplEnv
-> Bool
-> InId -- Old binder
-> OutId -- New binder
-> OutExpr -- Simplified RHS
-> SimplM SimplEnv
-- Precondition: rhs satisfies the let/app invariant
-- See Note [CoreSyn let/app invariant] in CoreSyn
completeNonRecX top_lvl env is_strict old_bndr new_bndr new_rhs
= do { (env1, rhs1) <- prepareRhs top_lvl (zapFloats env) new_bndr new_rhs
; (env2, rhs2) <-
if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
then do { tick LetFloatFromLet
; return (addFloats env env1, rhs1) } -- Add the floats to the main env
else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
{-
{- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
Doing so risks exponential behaviour, because new_rhs has been simplified once already
In the cases described by the folowing commment, postInlineUnconditionally will
catch many of the relevant cases.
-- This happens; for example, the case_bndr during case of
-- known constructor: case (a,b) of x { (p,q) -> ... }
-- Here x isn't mentioned in the RHS, so we don't want to
-- create the (dead) let-binding let x = (a,b) in ...
--
-- Similarly, single occurrences can be inlined vigourously
-- e.g. case (f x, g y) of (a,b) -> ....
-- If a,b occur once we can avoid constructing the let binding for them.
Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
-- Consider case I# (quotInt# x y) of
-- I# v -> let w = J# v in ...
-- If we gaily inline (quotInt# x y) for v, we end up building an
-- extra thunk:
-- let w = J# (quotInt# x y) in ...
-- because quotInt# can fail.
| preInlineUnconditionally env NotTopLevel bndr new_rhs
= thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
-}
----------------------------------
prepareRhs takes a putative RHS, checks whether it's a PAP or
constructor application and, if so, converts it to ANF, so that the
resulting thing can be inlined more easily. Thus
x = (f a, g b)
becomes
t1 = f a
t2 = g b
x = (t1,t2)
We also want to deal well cases like this
v = (f e1 `cast` co) e2
Here we want to make e1,e2 trivial and get
x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
That's what the 'go' loop in prepareRhs does
-}
prepareRhs :: TopLevelFlag -> SimplEnv -> OutId -> OutExpr -> SimplM (SimplEnv, OutExpr)
-- Adds new floats to the env iff that allows us to return a good RHS
prepareRhs top_lvl env id (Cast rhs co) -- Note [Float coercions]
| Pair ty1 _ty2 <- coercionKind co -- Do *not* do this if rhs has an unlifted type
, not (isUnLiftedType ty1) -- see Note [Float coercions (unlifted)]
= do { (env', rhs') <- makeTrivialWithInfo top_lvl env sanitised_info rhs
; return (env', Cast rhs' co) }
where
sanitised_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info
`setDemandInfo` demandInfo info
info = idInfo id
prepareRhs top_lvl env0 _ rhs0
= do { (_is_exp, env1, rhs1) <- go 0 env0 rhs0
; return (env1, rhs1) }
where
go n_val_args env (Cast rhs co)
= do { (is_exp, env', rhs') <- go n_val_args env rhs
; return (is_exp, env', Cast rhs' co) }
go n_val_args env (App fun (Type ty))
= do { (is_exp, env', rhs') <- go n_val_args env fun
; return (is_exp, env', App rhs' (Type ty)) }
go n_val_args env (App fun arg)
= do { (is_exp, env', fun') <- go (n_val_args+1) env fun
; case is_exp of
True -> do { (env'', arg') <- makeTrivial top_lvl env' arg
; return (True, env'', App fun' arg') }
False -> return (False, env, App fun arg) }
go n_val_args env (Var fun)
= return (is_exp, env, Var fun)
where
is_exp = isExpandableApp fun n_val_args -- The fun a constructor or PAP
-- See Note [CONLIKE pragma] in BasicTypes
-- The definition of is_exp should match that in
-- OccurAnal.occAnalApp
go n_val_args env (Tick t rhs)
-- We want to be able to float bindings past this
-- tick. Non-scoping ticks don't care.
| tickishScoped t == NoScope
= do { (is_exp, env', rhs') <- go n_val_args env rhs
; return (is_exp, env', Tick t rhs') }
-- On the other hand, for scoping ticks we need to be able to
-- copy them on the floats, which in turn is only allowed if
-- we can obtain non-counting ticks.
| not (tickishCounts t) || tickishCanSplit t
= do { (is_exp, env', rhs') <- go n_val_args (zapFloats env) rhs
; let tickIt (id, expr) = (id, mkTick (mkNoCount t) expr)
floats' = seFloats $ env `addFloats` mapFloats env' tickIt
; return (is_exp, env' { seFloats = floats' }, Tick t rhs') }
go _ env other
= return (False, env, other)
{-
Note [Float coercions]
~~~~~~~~~~~~~~~~~~~~~~
When we find the binding
x = e `cast` co
we'd like to transform it to
x' = e
x = x `cast` co -- A trivial binding
There's a chance that e will be a constructor application or function, or something
like that, so moving the coercion to the usage site may well cancel the coercions
and lead to further optimisation. Example:
data family T a :: *
data instance T Int = T Int
foo :: Int -> Int -> Int
foo m n = ...
where
x = T m
go 0 = 0
go n = case x of { T m -> go (n-m) }
-- This case should optimise
Note [Preserve strictness when floating coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the Note [Float coercions] transformation, keep the strictness info.
Eg
f = e `cast` co -- f has strictness SSL
When we transform to
f' = e -- f' also has strictness SSL
f = f' `cast` co -- f still has strictness SSL
Its not wrong to drop it on the floor, but better to keep it.
Note [Float coercions (unlifted)]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BUT don't do [Float coercions] if 'e' has an unlifted type.
This *can* happen:
foo :: Int = (error (# Int,Int #) "urk")
`cast` CoUnsafe (# Int,Int #) Int
If do the makeTrivial thing to the error call, we'll get
foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
But 'v' isn't in scope!
These strange casts can happen as a result of case-of-case
bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
(# p,q #) -> p+q
-}
makeTrivialArg :: SimplEnv -> ArgSpec -> SimplM (SimplEnv, ArgSpec)
makeTrivialArg env (ValArg e) = do { (env', e') <- makeTrivial NotTopLevel env e
; return (env', ValArg e') }
makeTrivialArg env arg = return (env, arg) -- CastBy, TyArg
makeTrivial :: TopLevelFlag -> SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
-- Binds the expression to a variable, if it's not trivial, returning the variable
makeTrivial top_lvl env expr = makeTrivialWithInfo top_lvl env vanillaIdInfo expr
makeTrivialWithInfo :: TopLevelFlag -> SimplEnv -> IdInfo
-> OutExpr -> SimplM (SimplEnv, OutExpr)
-- Propagate strictness and demand info to the new binder
-- Note [Preserve strictness when floating coercions]
-- Returned SimplEnv has same substitution as incoming one
makeTrivialWithInfo top_lvl env info expr
| exprIsTrivial expr -- Already trivial
|| not (bindingOk top_lvl expr expr_ty) -- Cannot trivialise
-- See Note [Cannot trivialise]
= return (env, expr)
| otherwise -- See Note [Take care] below
= do { uniq <- getUniqueM
; let name = mkSystemVarName uniq (fsLit "a")
var = mkLocalIdWithInfo name expr_ty info
; env' <- completeNonRecX top_lvl env False var var expr
; expr' <- simplVar env' var
; return (env', expr') }
-- The simplVar is needed becase we're constructing a new binding
-- a = rhs
-- And if rhs is of form (rhs1 |> co), then we might get
-- a1 = rhs1
-- a = a1 |> co
-- and now a's RHS is trivial and can be substituted out, and that
-- is what completeNonRecX will do
-- To put it another way, it's as if we'd simplified
-- let var = e in var
where
expr_ty = exprType expr
bindingOk :: TopLevelFlag -> CoreExpr -> Type -> Bool
-- True iff we can have a binding of this expression at this level
-- Precondition: the type is the type of the expression
bindingOk top_lvl _ expr_ty
| isTopLevel top_lvl = not (isUnLiftedType expr_ty)
| otherwise = True
{-
Note [Cannot trivialise]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider tih
f :: Int -> Addr#
foo :: Bar
foo = Bar (f 3)
Then we can't ANF-ise foo, even though we'd like to, because
we can't make a top-level binding for the Addr# (f 3). And if
so we don't want to turn it into
foo = let x = f 3 in Bar x
because we'll just end up inlining x back, and that makes the
simplifier loop. Better not to ANF-ise it at all.
A case in point is literal strings (a MachStr is not regarded as
trivial):
foo = Ptr "blob"#
We don't want to ANF-ise this.
************************************************************************
* *
\subsection{Completing a lazy binding}
* *
************************************************************************
completeBind
* deals only with Ids, not TyVars
* takes an already-simplified binder and RHS
* is used for both recursive and non-recursive bindings
* is used for both top-level and non-top-level bindings
It does the following:
- tries discarding a dead binding
- tries PostInlineUnconditionally
- add unfolding [this is the only place we add an unfolding]
- add arity
It does *not* attempt to do let-to-case. Why? Because it is used for
- top-level bindings (when let-to-case is impossible)
- many situations where the "rhs" is known to be a WHNF
(so let-to-case is inappropriate).
Nor does it do the atomic-argument thing
-}
completeBind :: SimplEnv
-> TopLevelFlag -- Flag stuck into unfolding
-> InId -- Old binder
-> OutId -> OutExpr -- New binder and RHS
-> SimplM SimplEnv
-- completeBind may choose to do its work
-- * by extending the substitution (e.g. let x = y in ...)
-- * or by adding to the floats in the envt
--
-- Precondition: rhs obeys the let/app invariant
completeBind env top_lvl old_bndr new_bndr new_rhs
| isCoVar old_bndr
= case new_rhs of
Coercion co -> return (extendCvSubst env old_bndr co)
_ -> return (addNonRec env new_bndr new_rhs)
| otherwise
= ASSERT( isId new_bndr )
do { let old_info = idInfo old_bndr
old_unf = unfoldingInfo old_info
occ_info = occInfo old_info
-- Do eta-expansion on the RHS of the binding
-- See Note [Eta-expanding at let bindings] in SimplUtils
; (new_arity, final_rhs) <- tryEtaExpandRhs env new_bndr new_rhs
-- Simplify the unfolding
; new_unfolding <- simplUnfolding env top_lvl old_bndr final_rhs old_unf
; dflags <- getDynFlags
; if postInlineUnconditionally dflags env top_lvl new_bndr occ_info
final_rhs new_unfolding
-- Inline and discard the binding
then do { tick (PostInlineUnconditionally old_bndr)
; return (extendIdSubst env old_bndr (DoneEx final_rhs)) }
-- Use the substitution to make quite, quite sure that the
-- substitution will happen, since we are going to discard the binding
else
do { let info1 = idInfo new_bndr `setArityInfo` new_arity
-- Unfolding info: Note [Setting the new unfolding]
info2 = info1 `setUnfoldingInfo` new_unfolding
-- Demand info: Note [Setting the demand info]
--
-- We also have to nuke demand info if for some reason
-- eta-expansion *reduces* the arity of the binding to less
-- than that of the strictness sig. This can happen: see Note [Arity decrease].
info3 | isEvaldUnfolding new_unfolding
|| (case strictnessInfo info2 of
StrictSig dmd_ty -> new_arity < dmdTypeDepth dmd_ty)
= zapDemandInfo info2 `orElse` info2
| otherwise
= info2
final_id = new_bndr `setIdInfo` info3
; -- pprTrace "Binding" (ppr final_id <+> ppr new_unfolding) $
return (addNonRec env final_id final_rhs) } }
-- The addNonRec adds it to the in-scope set too
------------------------------
addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
-- Add a new binding to the environment, complete with its unfolding
-- but *do not* do postInlineUnconditionally, because we have already
-- processed some of the scope of the binding
-- We still want the unfolding though. Consider
-- let
-- x = /\a. let y = ... in Just y
-- in body
-- Then we float the y-binding out (via abstractFloats and addPolyBind)
-- but 'x' may well then be inlined in 'body' in which case we'd like the
-- opportunity to inline 'y' too.
--
-- INVARIANT: the arity is correct on the incoming binders
addPolyBind top_lvl env (NonRec poly_id rhs)
= do { unfolding <- simplUnfolding env top_lvl poly_id rhs noUnfolding
-- Assumes that poly_id did not have an INLINE prag
-- which is perhaps wrong. ToDo: think about this
; let final_id = setIdInfo poly_id $
idInfo poly_id `setUnfoldingInfo` unfolding
; return (addNonRec env final_id rhs) }
addPolyBind _ env bind@(Rec _)
= return (extendFloats env bind)
-- Hack: letrecs are more awkward, so we extend "by steam"
-- without adding unfoldings etc. At worst this leads to
-- more simplifier iterations
------------------------------
simplUnfolding :: SimplEnv-> TopLevelFlag
-> InId
-> OutExpr
-> Unfolding -> SimplM Unfolding
-- Note [Setting the new unfolding]
simplUnfolding env top_lvl id new_rhs unf
= case unf of
DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args }
-> do { (env', bndrs') <- simplBinders rule_env bndrs
; args' <- mapM (simplExpr env') args
; return (mkDFunUnfolding bndrs' con args') }
CoreUnfolding { uf_tmpl = expr, uf_src = src, uf_guidance = guide }
| isStableSource src
-> do { expr' <- simplExpr rule_env expr
; case guide of
UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok } -- Happens for INLINE things
-> let guide' = UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok
, ug_boring_ok = inlineBoringOk expr' }
-- Refresh the boring-ok flag, in case expr'
-- has got small. This happens, notably in the inlinings
-- for dfuns for single-method classes; see
-- Note [Single-method classes] in TcInstDcls.
-- A test case is Trac #4138
in return (mkCoreUnfolding src is_top_lvl expr' guide')
-- See Note [Top-level flag on inline rules] in CoreUnfold
_other -- Happens for INLINABLE things
-> bottoming `seq` -- See Note [Force bottoming field]
do { dflags <- getDynFlags
; return (mkUnfolding dflags src is_top_lvl bottoming expr') } }
-- If the guidance is UnfIfGoodArgs, this is an INLINABLE
-- unfolding, and we need to make sure the guidance is kept up
-- to date with respect to any changes in the unfolding.
_other -> bottoming `seq` -- See Note [Force bottoming field]
do { dflags <- getDynFlags
; return (mkUnfolding dflags InlineRhs is_top_lvl bottoming new_rhs) }
-- We make an unfolding *even for loop-breakers*.
-- Reason: (a) It might be useful to know that they are WHNF
-- (b) In TidyPgm we currently assume that, if we want to
-- expose the unfolding then indeed we *have* an unfolding
-- to expose. (We could instead use the RHS, but currently
-- we don't.) The simple thing is always to have one.
where
bottoming = isBottomingId id
is_top_lvl = isTopLevel top_lvl
act = idInlineActivation id
rule_env = updMode (updModeForStableUnfoldings act) env
-- See Note [Simplifying inside stable unfoldings] in SimplUtils
{-
Note [Force bottoming field]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to force bottoming, or the new unfolding holds
on to the old unfolding (which is part of the id).
Note [Arity decrease]
~~~~~~~~~~~~~~~~~~~~~
Generally speaking the arity of a binding should not decrease. But it *can*
legitimately happen because of RULES. Eg
f = g Int
where g has arity 2, will have arity 2. But if there's a rewrite rule
g Int --> h
where h has arity 1, then f's arity will decrease. Here's a real-life example,
which is in the output of Specialise:
Rec {
$dm {Arity 2} = \d.\x. op d
{-# RULES forall d. $dm Int d = $s$dm #-}
dInt = MkD .... opInt ...
opInt {Arity 1} = $dm dInt
$s$dm {Arity 0} = \x. op dInt }
Here opInt has arity 1; but when we apply the rule its arity drops to 0.
That's why Specialise goes to a little trouble to pin the right arity
on specialised functions too.
Note [Setting the new unfolding]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* If there's an INLINE pragma, we simplify the RHS gently. Maybe we
should do nothing at all, but simplifying gently might get rid of
more crap.
* If not, we make an unfolding from the new RHS. But *only* for
non-loop-breakers. Making loop breakers not have an unfolding at all
means that we can avoid tests in exprIsConApp, for example. This is
important: if exprIsConApp says 'yes' for a recursive thing, then we
can get into an infinite loop
If there's an stable unfolding on a loop breaker (which happens for
INLINEABLE), we hang on to the inlining. It's pretty dodgy, but the
user did say 'INLINE'. May need to revisit this choice.
Note [Setting the demand info]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the unfolding is a value, the demand info may
go pear-shaped, so we nuke it. Example:
let x = (a,b) in
case x of (p,q) -> h p q x
Here x is certainly demanded. But after we've nuked
the case, we'll get just
let x = (a,b) in h a b x
and now x is not demanded (I'm assuming h is lazy)
This really happens. Similarly
let f = \x -> e in ...f..f...
After inlining f at some of its call sites the original binding may
(for example) be no longer strictly demanded.
The solution here is a bit ad hoc...
************************************************************************
* *
\subsection[Simplify-simplExpr]{The main function: simplExpr}
* *
************************************************************************
The reason for this OutExprStuff stuff is that we want to float *after*
simplifying a RHS, not before. If we do so naively we get quadratic
behaviour as things float out.
To see why it's important to do it after, consider this (real) example:
let t = f x
in fst t
==>
let t = let a = e1
b = e2
in (a,b)
in fst t
==>
let a = e1
b = e2
t = (a,b)
in
a -- Can't inline a this round, cos it appears twice
==>
e1
Each of the ==> steps is a round of simplification. We'd save a
whole round if we float first. This can cascade. Consider
let f = g d
in \x -> ...f...
==>
let f = let d1 = ..d.. in \y -> e
in \x -> ...f...
==>
let d1 = ..d..
in \x -> ...(\y ->e)...
Only in this second round can the \y be applied, and it
might do the same again.
-}
simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
simplExpr env expr = simplExprC env expr (mkBoringStop expr_out_ty)
where
expr_out_ty :: OutType
expr_out_ty = substTy env (exprType expr)
simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
-- Simplify an expression, given a continuation
simplExprC env expr cont
= -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
do { (env', expr') <- simplExprF (zapFloats env) expr cont
; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
-- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
-- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
return (wrapFloats env' expr') }
--------------------------------------------------
simplExprF :: SimplEnv -> InExpr -> SimplCont
-> SimplM (SimplEnv, OutExpr)
simplExprF env e cont
= {- pprTrace "simplExprF" (vcat
[ ppr e
, text "cont =" <+> ppr cont
, text "inscope =" <+> ppr (seInScope env)
, text "tvsubst =" <+> ppr (seTvSubst env)
, text "idsubst =" <+> ppr (seIdSubst env)
, text "cvsubst =" <+> ppr (seCvSubst env)
{- , ppr (seFloats env) -}
]) $ -}
simplExprF1 env e cont
simplExprF1 :: SimplEnv -> InExpr -> SimplCont
-> SimplM (SimplEnv, OutExpr)
simplExprF1 env (Var v) cont = simplIdF env v cont
simplExprF1 env (Lit lit) cont = rebuild env (Lit lit) cont
simplExprF1 env (Tick t expr) cont = simplTick env t expr cont
simplExprF1 env (Cast body co) cont = simplCast env body co cont
simplExprF1 env (Coercion co) cont = simplCoercionF env co cont
simplExprF1 env (Type ty) cont = ASSERT( contIsRhsOrArg cont )
rebuild env (Type (substTy env ty)) cont
simplExprF1 env (App fun arg) cont
= simplExprF env fun $
case arg of
Type ty -> ApplyToTy { sc_arg_ty = substTy env ty
, sc_hole_ty = substTy env (exprType fun)
, sc_cont = cont }
_ -> ApplyToVal { sc_arg = arg, sc_env = env
, sc_dup = NoDup, sc_cont = cont }
simplExprF1 env expr@(Lam {}) cont
= simplLam env zapped_bndrs body cont
-- The main issue here is under-saturated lambdas
-- (\x1. \x2. e) arg1
-- Here x1 might have "occurs-once" occ-info, because occ-info
-- is computed assuming that a group of lambdas is applied
-- all at once. If there are too few args, we must zap the
-- occ-info, UNLESS the remaining binders are one-shot
where
(bndrs, body) = collectBinders expr
zapped_bndrs | need_to_zap = map zap bndrs
| otherwise = bndrs
need_to_zap = any zappable_bndr (drop n_args bndrs)
n_args = countArgs cont
-- NB: countArgs counts all the args (incl type args)
-- and likewise drop counts all binders (incl type lambdas)
zappable_bndr b = isId b && not (isOneShotBndr b)
zap b | isTyVar b = b
| otherwise = zapLamIdInfo b
simplExprF1 env (Case scrut bndr _ alts) cont
= simplExprF env scrut (Select NoDup bndr alts env cont)
simplExprF1 env (Let (Rec pairs) body) cont
= do { env' <- simplRecBndrs env (map fst pairs)
-- NB: bndrs' don't have unfoldings or rules
-- We add them as we go down
; env'' <- simplRecBind env' NotTopLevel pairs
; simplExprF env'' body cont }
simplExprF1 env (Let (NonRec bndr rhs) body) cont
= simplNonRecE env bndr (rhs, env) ([], body) cont
---------------------------------
simplType :: SimplEnv -> InType -> SimplM OutType
-- Kept monadic just so we can do the seqType
simplType env ty
= -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
seqType new_ty `seq` return new_ty
where
new_ty = substTy env ty
---------------------------------
simplCoercionF :: SimplEnv -> InCoercion -> SimplCont
-> SimplM (SimplEnv, OutExpr)
simplCoercionF env co cont
= do { co' <- simplCoercion env co
; rebuild env (Coercion co') cont }
simplCoercion :: SimplEnv -> InCoercion -> SimplM OutCoercion
simplCoercion env co
= let opt_co = optCoercion (getCvSubst env) co
in seqCo opt_co `seq` return opt_co
-----------------------------------
-- | Push a TickIt context outwards past applications and cases, as
-- long as this is a non-scoping tick, to let case and application
-- optimisations apply.
simplTick :: SimplEnv -> Tickish Id -> InExpr -> SimplCont
-> SimplM (SimplEnv, OutExpr)
simplTick env tickish expr cont
-- A scoped tick turns into a continuation, so that we can spot
-- (scc t (\x . e)) in simplLam and eliminate the scc. If we didn't do
-- it this way, then it would take two passes of the simplifier to
-- reduce ((scc t (\x . e)) e').
-- NB, don't do this with counting ticks, because if the expr is
-- bottom, then rebuildCall will discard the continuation.
-- XXX: we cannot do this, because the simplifier assumes that
-- the context can be pushed into a case with a single branch. e.g.
-- scc<f> case expensive of p -> e
-- becomes
-- case expensive of p -> scc<f> e
--
-- So I'm disabling this for now. It just means we will do more
-- simplifier iterations that necessary in some cases.
-- | tickishScoped tickish && not (tickishCounts tickish)
-- = simplExprF env expr (TickIt tickish cont)
-- For unscoped or soft-scoped ticks, we are allowed to float in new
-- cost, so we simply push the continuation inside the tick. This
-- has the effect of moving the tick to the outside of a case or
-- application context, allowing the normal case and application
-- optimisations to fire.
| tickish `tickishScopesLike` SoftScope
= do { (env', expr') <- simplExprF env expr cont
; return (env', mkTick tickish expr')
}
-- Push tick inside if the context looks like this will allow us to
-- do a case-of-case - see Note [case-of-scc-of-case]
| Select {} <- cont, Just expr' <- push_tick_inside
= simplExprF env expr' cont
-- We don't want to move the tick, but we might still want to allow
-- floats to pass through with appropriate wrapping (or not, see
-- wrap_floats below)
--- | not (tickishCounts tickish) || tickishCanSplit tickish
-- = wrap_floats
| otherwise
= no_floating_past_tick
where
-- Try to push tick inside a case, see Note [case-of-scc-of-case].
push_tick_inside =
case expr0 of
Case scrut bndr ty alts
-> Just $ Case (tickScrut scrut) bndr ty (map tickAlt alts)
_other -> Nothing
where (ticks, expr0) = stripTicksTop movable (Tick tickish expr)
movable t = not (tickishCounts t) ||
t `tickishScopesLike` NoScope ||
tickishCanSplit t
tickScrut e = foldr mkTick e ticks
-- Alternatives get annotated with all ticks that scope in some way,
-- but we don't want to count entries.
tickAlt (c,bs,e) = (c,bs, foldr mkTick e ts_scope)
ts_scope = map mkNoCount $
filter (not . (`tickishScopesLike` NoScope)) ticks
no_floating_past_tick =
do { let (inc,outc) = splitCont cont
; (env', expr') <- simplExprF (zapFloats env) expr inc
; let tickish' = simplTickish env tickish
; (env'', expr'') <- rebuild (zapFloats env')
(wrapFloats env' expr')
(TickIt tickish' outc)
; return (addFloats env env'', expr'')
}
-- Alternative version that wraps outgoing floats with the tick. This
-- results in ticks being duplicated, as we don't make any attempt to
-- eliminate the tick if we re-inline the binding (because the tick
-- semantics allows unrestricted inlining of HNFs), so I'm not doing
-- this any more. FloatOut will catch any real opportunities for
-- floating.
--
-- wrap_floats =
-- do { let (inc,outc) = splitCont cont
-- ; (env', expr') <- simplExprF (zapFloats env) expr inc
-- ; let tickish' = simplTickish env tickish
-- ; let wrap_float (b,rhs) = (zapIdStrictness (setIdArity b 0),
-- mkTick (mkNoCount tickish') rhs)
-- -- when wrapping a float with mkTick, we better zap the Id's
-- -- strictness info and arity, because it might be wrong now.
-- ; let env'' = addFloats env (mapFloats env' wrap_float)
-- ; rebuild env'' expr' (TickIt tickish' outc)
-- }
simplTickish env tickish
| Breakpoint n ids <- tickish
= Breakpoint n (map (getDoneId . substId env) ids)
| otherwise = tickish
-- Push type application and coercion inside a tick
splitCont :: SimplCont -> (SimplCont, SimplCont)
splitCont cont@(ApplyToTy { sc_cont = tail }) = (cont { sc_cont = inc }, outc)
where (inc,outc) = splitCont tail
splitCont (CastIt co c) = (CastIt co inc, outc)
where (inc,outc) = splitCont c
splitCont other = (mkBoringStop (contHoleType other), other)
getDoneId (DoneId id) = id
getDoneId (DoneEx e) = getIdFromTrivialExpr e -- Note [substTickish] in CoreSubst
getDoneId other = pprPanic "getDoneId" (ppr other)
-- Note [case-of-scc-of-case]
-- It's pretty important to be able to transform case-of-case when
-- there's an SCC in the way. For example, the following comes up
-- in nofib/real/compress/Encode.hs:
--
-- case scctick<code_string.r1>
-- case $wcode_string_r13s wild_XC w1_s137 w2_s138 l_aje
-- of _ { (# ww1_s13f, ww2_s13g, ww3_s13h #) ->
-- (ww1_s13f, ww2_s13g, ww3_s13h)
-- }
-- of _ { (ww_s12Y, ww1_s12Z, ww2_s130) ->
-- tick<code_string.f1>
-- (ww_s12Y,
-- ww1_s12Z,
-- PTTrees.PT
-- @ GHC.Types.Char @ GHC.Types.Int wild2_Xj ww2_s130 r_ajf)
-- }
--
-- We really want this case-of-case to fire, because then the 3-tuple
-- will go away (indeed, the CPR optimisation is relying on this
-- happening). But the scctick is in the way - we need to push it
-- inside to expose the case-of-case. So we perform this
-- transformation on the inner case:
--
-- scctick c (case e of { p1 -> e1; ...; pn -> en })
-- ==>
-- case (scctick c e) of { p1 -> scc c e1; ...; pn -> scc c en }
--
-- So we've moved a constant amount of work out of the scc to expose
-- the case. We only do this when the continuation is interesting: in
-- for now, it has to be another Case (maybe generalise this later).
{-
************************************************************************
* *
\subsection{The main rebuilder}
* *
************************************************************************
-}
rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
-- At this point the substitution in the SimplEnv should be irrelevant
-- only the in-scope set and floats should matter
rebuild env expr cont
= case cont of
Stop {} -> return (env, expr)
TickIt t cont -> rebuild env (mkTick t expr) cont
CastIt co cont -> rebuild env (mkCast expr co) cont
-- NB: mkCast implements the (Coercion co |> g) optimisation
Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
StrictArg info _ cont -> rebuildCall env (info `addValArgTo` expr) cont
StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
-- expr satisfies let/app since it started life
-- in a call to simplNonRecE
; simplLam env' bs body cont }
ApplyToTy { sc_arg_ty = ty, sc_cont = cont}
-> rebuild env (App expr (Type ty)) cont
ApplyToVal { sc_arg = arg, sc_env = se, sc_dup = dup_flag, sc_cont = cont}
-- See Note [Avoid redundant simplification]
| isSimplified dup_flag -> rebuild env (App expr arg) cont
| otherwise -> do { arg' <- simplExpr (se `setInScope` env) arg
; rebuild env (App expr arg') cont }
{-
************************************************************************
* *
\subsection{Lambdas}
* *
************************************************************************
-}
simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
-> SimplM (SimplEnv, OutExpr)
simplCast env body co0 cont0
= do { co1 <- simplCoercion env co0
; -- pprTrace "simplCast" (ppr co1) $
simplExprF env body (addCoerce co1 cont0) }
where
addCoerce co cont = add_coerce co (coercionKind co) cont
add_coerce _co (Pair s1 k1) cont -- co :: ty~ty
| s1 `eqType` k1 = cont -- is a no-op
add_coerce co1 (Pair s1 _k2) (CastIt co2 cont)
| (Pair _l1 t1) <- coercionKind co2
-- e |> (g1 :: S1~L) |> (g2 :: L~T1)
-- ==>
-- e, if S1=T1
-- e |> (g1 . g2 :: S1~T1) otherwise
--
-- For example, in the initial form of a worker
-- we may find (coerce T (coerce S (\x.e))) y
-- and we'd like it to simplify to e[y/x] in one round
-- of simplification
, s1 `eqType` t1 = cont -- The coerces cancel out
| otherwise = CastIt (mkTransCo co1 co2) cont
add_coerce co (Pair s1s2 _t1t2) cont@(ApplyToTy { sc_arg_ty = arg_ty, sc_cont = tail })
-- (f |> g) ty ---> (f ty) |> (g @ ty)
-- This implements the PushT rule from the paper
| Just (tyvar,_) <- splitForAllTy_maybe s1s2
= ASSERT( isTyVar tyvar )
cont { sc_cont = addCoerce new_cast tail }
where
new_cast = mkInstCo co arg_ty
add_coerce co (Pair s1s2 t1t2) (ApplyToVal { sc_arg = arg, sc_env = arg_se
, sc_dup = dup, sc_cont = cont })
| isFunTy s1s2 -- This implements the Push rule from the paper
, isFunTy t1t2 -- Check t1t2 to ensure 'arg' is a value arg
-- (e |> (g :: s1s2 ~ t1->t2)) f
-- ===>
-- (e (f |> (arg g :: t1~s1))
-- |> (res g :: s2->t2)
--
-- t1t2 must be a function type, t1->t2, because it's applied
-- to something but s1s2 might conceivably not be
--
-- When we build the ApplyTo we can't mix the out-types
-- with the InExpr in the argument, so we simply substitute
-- to make it all consistent. It's a bit messy.
-- But it isn't a common case.
--
-- Example of use: Trac #995
= ApplyToVal { sc_arg = mkCast arg' (mkSymCo co1)
, sc_env = zapSubstEnv arg_se
, sc_dup = dup
, sc_cont = addCoerce co2 cont }
where
-- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
-- t2 ~ s2 with left and right on the curried form:
-- (->) t1 t2 ~ (->) s1 s2
[co1, co2] = decomposeCo 2 co
arg' = substExpr (text "move-cast") arg_se' arg
arg_se' = arg_se `setInScope` env
add_coerce co _ cont = CastIt co cont
{-
************************************************************************
* *
\subsection{Lambdas}
* *
************************************************************************
Note [Zap unfolding when beta-reducing]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lambda-bound variables can have stable unfoldings, such as
$j = \x. \b{Unf=Just x}. e
See Note [Case binders and join points] below; the unfolding for lets
us optimise e better. However when we beta-reduce it we want to
revert to using the actual value, otherwise we can end up in the
stupid situation of
let x = blah in
let b{Unf=Just x} = y
in ...b...
Here it'd be far better to drop the unfolding and use the actual RHS.
-}
simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
-> SimplM (SimplEnv, OutExpr)
simplLam env [] body cont = simplExprF env body cont
-- Beta reduction
simplLam env (bndr:bndrs) body (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
= do { tick (BetaReduction bndr)
; simplLam (extendTvSubst env bndr arg_ty) bndrs body cont }
simplLam env (bndr:bndrs) body (ApplyToVal { sc_arg = arg, sc_env = arg_se
, sc_cont = cont })
= do { tick (BetaReduction bndr)
; simplNonRecE env (zap_unfolding bndr) (arg, arg_se) (bndrs, body) cont }
where
zap_unfolding bndr -- See Note [Zap unfolding when beta-reducing]
| isId bndr, isStableUnfolding (realIdUnfolding bndr)
= setIdUnfolding bndr NoUnfolding
| otherwise = bndr
-- discard a non-counting tick on a lambda. This may change the
-- cost attribution slightly (moving the allocation of the
-- lambda elsewhere), but we don't care: optimisation changes
-- cost attribution all the time.
simplLam env bndrs body (TickIt tickish cont)
| not (tickishCounts tickish)
= simplLam env bndrs body cont
-- Not enough args, so there are real lambdas left to put in the result
simplLam env bndrs body cont
= do { (env', bndrs') <- simplLamBndrs env bndrs
; body' <- simplExpr env' body
; new_lam <- mkLam bndrs' body' cont
; rebuild env' new_lam cont }
------------------
simplNonRecE :: SimplEnv
-> InBndr -- The binder
-> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
-> ([InBndr], InExpr) -- Body of the let/lambda
-- \xs.e
-> SimplCont
-> SimplM (SimplEnv, OutExpr)
-- simplNonRecE is used for
-- * non-top-level non-recursive lets in expressions
-- * beta reduction
--
-- It deals with strict bindings, via the StrictBind continuation,
-- which may abort the whole process
--
-- Precondition: rhs satisfies the let/app invariant
-- Note [CoreSyn let/app invariant] in CoreSyn
--
-- The "body" of the binding comes as a pair of ([InId],InExpr)
-- representing a lambda; so we recurse back to simplLam
-- Why? Because of the binder-occ-info-zapping done before
-- the call to simplLam in simplExprF (Lam ...)
-- First deal with type applications and type lets
-- (/\a. e) (Type ty) and (let a = Type ty in e)
simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
= ASSERT( isTyVar bndr )
do { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
= do dflags <- getDynFlags
case () of
_ | preInlineUnconditionally dflags env NotTopLevel bndr rhs
-> do { tick (PreInlineUnconditionally bndr)
; -- pprTrace "preInlineUncond" (ppr bndr <+> ppr rhs) $
simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
| isStrictId bndr -- Includes coercions
-> simplExprF (rhs_se `setFloats` env) rhs
(StrictBind bndr bndrs body env cont)
| otherwise
-> ASSERT( not (isTyVar bndr) )
do { (env1, bndr1) <- simplNonRecBndr env bndr
; let (env2, bndr2) = addBndrRules env1 bndr bndr1
; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
; simplLam env3 bndrs body cont }
{-
************************************************************************
* *
Variables
* *
************************************************************************
-}
simplVar :: SimplEnv -> InVar -> SimplM OutExpr
-- Look up an InVar in the environment
simplVar env var
| isTyVar var = return (Type (substTyVar env var))
| isCoVar var = return (Coercion (substCoVar env var))
| otherwise
= case substId env var of
DoneId var1 -> return (Var var1)
DoneEx e -> return e
ContEx tvs cvs ids e -> simplExpr (setSubstEnv env tvs cvs ids) e
simplIdF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplEnv, OutExpr)
simplIdF env var cont
= case substId env var of
DoneEx e -> simplExprF (zapSubstEnv env) e cont
ContEx tvs cvs ids e -> simplExprF (setSubstEnv env tvs cvs ids) e cont
DoneId var1 -> completeCall env var1 cont
-- Note [zapSubstEnv]
-- The template is already simplified, so don't re-substitute.
-- This is VITAL. Consider
-- let x = e in
-- let y = \z -> ...x... in
-- \ x -> ...y...
-- We'll clone the inner \x, adding x->x' in the id_subst
-- Then when we inline y, we must *not* replace x by x' in
-- the inlined copy!!
---------------------------------------------------------
-- Dealing with a call site
completeCall :: SimplEnv -> OutId -> SimplCont -> SimplM (SimplEnv, OutExpr)
completeCall env var cont
= do { ------------- Try inlining ----------------
dflags <- getDynFlags
; let (lone_variable, arg_infos, call_cont) = contArgs cont
n_val_args = length arg_infos
interesting_cont = interestingCallContext call_cont
unfolding = activeUnfolding env var
maybe_inline = callSiteInline dflags var unfolding
lone_variable arg_infos interesting_cont
; case maybe_inline of {
Just expr -- There is an inlining!
-> do { checkedTick (UnfoldingDone var)
; dump_inline dflags expr cont
; simplExprF (zapSubstEnv env) expr cont }
; Nothing -> do -- No inlining!
{ rule_base <- getSimplRules
; let info = mkArgInfo var (getRules rule_base var) n_val_args call_cont
; rebuildCall env info cont
}}}
where
dump_inline dflags unfolding cont
| not (dopt Opt_D_dump_inlinings dflags) = return ()
| not (dopt Opt_D_verbose_core2core dflags)
= when (isExternalName (idName var)) $
liftIO $ printOutputForUser dflags alwaysQualify $
sep [text "Inlining done:", nest 4 (ppr var)]
| otherwise
= liftIO $ printOutputForUser dflags alwaysQualify $
sep [text "Inlining done: " <> ppr var,
nest 4 (vcat [text "Inlined fn: " <+> nest 2 (ppr unfolding),
text "Cont: " <+> ppr cont])]
rebuildCall :: SimplEnv
-> ArgInfo
-> SimplCont
-> SimplM (SimplEnv, OutExpr)
rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont
-- When we run out of strictness args, it means
-- that the call is definitely bottom; see SimplUtils.mkArgInfo
-- Then we want to discard the entire strict continuation. E.g.
-- * case (error "hello") of { ... }
-- * (error "Hello") arg
-- * f (error "Hello") where f is strict
-- etc
-- Then, especially in the first of these cases, we'd like to discard
-- the continuation, leaving just the bottoming expression. But the
-- type might not be right, so we may have to add a coerce.
| not (contIsTrivial cont) -- Only do this if there is a non-trivial
= return (env, castBottomExpr res cont_ty) -- contination to discard, else we do it
where -- again and again!
res = argInfoExpr fun rev_args
cont_ty = contResultType cont
rebuildCall env info (CastIt co cont)
= rebuildCall env (addCastTo info co) cont
rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
= rebuildCall env (info `addTyArgTo` arg_ty) cont
rebuildCall env info@(ArgInfo { ai_encl = encl_rules, ai_type = fun_ty
, ai_strs = str:strs, ai_discs = disc:discs })
(ApplyToVal { sc_arg = arg, sc_env = arg_se
, sc_dup = dup_flag, sc_cont = cont })
| isSimplified dup_flag -- See Note [Avoid redundant simplification]
= rebuildCall env (addValArgTo info' arg) cont
| str -- Strict argument
= -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
simplExprF (arg_se `setFloats` env) arg
(StrictArg info' cci cont)
-- Note [Shadowing]
| otherwise -- Lazy argument
-- DO NOT float anything outside, hence simplExprC
-- There is no benefit (unlike in a let-binding), and we'd
-- have to be very careful about bogus strictness through
-- floating a demanded let.
= do { arg' <- simplExprC (arg_se `setInScope` env) arg
(mkLazyArgStop (funArgTy fun_ty) cci)
; rebuildCall env (addValArgTo info' arg') cont }
where
info' = info { ai_strs = strs, ai_discs = discs }
cci | encl_rules = RuleArgCtxt
| disc > 0 = DiscArgCtxt -- Be keener here
| otherwise = BoringCtxt -- Nothing interesting
rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_rules = rules }) cont
| null rules
= rebuild env (argInfoExpr fun rev_args) cont -- No rules, common case
| otherwise
= do { -- We've accumulated a simplified call in <fun,rev_args>
-- so try rewrite rules; see Note [RULEs apply to simplified arguments]
-- See also Note [Rules for recursive functions]
; let env' = zapSubstEnv env -- See Note [zapSubstEnv];
-- and NB that 'rev_args' are all fully simplified
; mb_rule <- tryRules env' rules fun (reverse rev_args) cont
; case mb_rule of {
Just (rule_rhs, cont') -> simplExprF env' rule_rhs cont'
-- Rules don't match
; Nothing -> rebuild env (argInfoExpr fun rev_args) cont -- No rules
} }
{-
Note [RULES apply to simplified arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's very desirable to try RULES once the arguments have been simplified, because
doing so ensures that rule cascades work in one pass. Consider
{-# RULES g (h x) = k x
f (k x) = x #-}
...f (g (h x))...
Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
we match f's rules against the un-simplified RHS, it won't match. This
makes a particularly big difference when superclass selectors are involved:
op ($p1 ($p2 (df d)))
We want all this to unravel in one sweeep.
Note [Avoid redundant simplification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Because RULES apply to simplified arguments, there's a danger of repeatedly
simplifying already-simplified arguments. An important example is that of
(>>=) d e1 e2
Here e1, e2 are simplified before the rule is applied, but don't really
participate in the rule firing. So we mark them as Simplified to avoid
re-simplifying them.
Note [Shadowing]
~~~~~~~~~~~~~~~~
This part of the simplifier may break the no-shadowing invariant
Consider
f (...(\a -> e)...) (case y of (a,b) -> e')
where f is strict in its second arg
If we simplify the innermost one first we get (...(\a -> e)...)
Simplifying the second arg makes us float the case out, so we end up with
case y of (a,b) -> f (...(\a -> e)...) e'
So the output does not have the no-shadowing invariant. However, there is
no danger of getting name-capture, because when the first arg was simplified
we used an in-scope set that at least mentioned all the variables free in its
static environment, and that is enough.
We can't just do innermost first, or we'd end up with a dual problem:
case x of (a,b) -> f e (...(\a -> e')...)
I spent hours trying to recover the no-shadowing invariant, but I just could
not think of an elegant way to do it. The simplifier is already knee-deep in
continuations. We have to keep the right in-scope set around; AND we have
to get the effect that finding (error "foo") in a strict arg position will
discard the entire application and replace it with (error "foo"). Getting
all this at once is TOO HARD!
************************************************************************
* *
Rewrite rules
* *
************************************************************************
-}
tryRules :: SimplEnv -> [CoreRule]
-> Id -> [ArgSpec] -> SimplCont
-> SimplM (Maybe (CoreExpr, SimplCont))
-- The SimplEnv already has zapSubstEnv applied to it
tryRules env rules fn args call_cont
| null rules
= return Nothing
{- Disabled until we fix #8326
| fn `hasKey` tagToEnumKey -- See Note [Optimising tagToEnum#]
, [_type_arg, val_arg] <- args
, Select dup bndr ((_,[],rhs1) : rest_alts) se cont <- call_cont
, isDeadBinder bndr
= do { dflags <- getDynFlags
; let enum_to_tag :: CoreAlt -> CoreAlt
-- Takes K -> e into tagK# -> e
-- where tagK# is the tag of constructor K
enum_to_tag (DataAlt con, [], rhs)
= ASSERT( isEnumerationTyCon (dataConTyCon con) )
(LitAlt tag, [], rhs)
where
tag = mkMachInt dflags (toInteger (dataConTag con - fIRST_TAG))
enum_to_tag alt = pprPanic "tryRules: tagToEnum" (ppr alt)
new_alts = (DEFAULT, [], rhs1) : map enum_to_tag rest_alts
new_bndr = setIdType bndr intPrimTy
-- The binder is dead, but should have the right type
; return (Just (val_arg, Select dup new_bndr new_alts se cont)) }
-}
| otherwise
= do { dflags <- getDynFlags
; case lookupRule dflags (getUnfoldingInRuleMatch env) (activeRule env)
fn (argInfoAppArgs args) rules of {
Nothing -> return Nothing ; -- No rule matches
Just (rule, rule_rhs) ->
do { checkedTick (RuleFired (ru_name rule))
; let cont' = pushSimplifiedArgs env
(drop (ruleArity rule) args)
call_cont
-- (ruleArity rule) says how many args the rule consumed
; dump dflags rule rule_rhs
; return (Just (rule_rhs, cont')) }}}
where
dump dflags rule rule_rhs
| dopt Opt_D_dump_rule_rewrites dflags
= log_rule dflags Opt_D_dump_rule_rewrites "Rule fired" $ vcat
[ text "Rule:" <+> ftext (ru_name rule)
, text "Before:" <+> hang (ppr fn) 2 (sep (map ppr args))
, text "After: " <+> pprCoreExpr rule_rhs
, text "Cont: " <+> ppr call_cont ]
| dopt Opt_D_dump_rule_firings dflags
= log_rule dflags Opt_D_dump_rule_firings "Rule fired:" $
ftext (ru_name rule)
| otherwise
= return ()
log_rule dflags flag hdr details
= liftIO . dumpSDoc dflags alwaysQualify flag "" $
sep [text hdr, nest 4 details]
{-
Note [Optimising tagToEnum#]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have an enumeration data type:
data Foo = A | B | C
Then we want to transform
case tagToEnum# x of ==> case x of
A -> e1 DEFAULT -> e1
B -> e2 1# -> e2
C -> e3 2# -> e3
thereby getting rid of the tagToEnum# altogether. If there was a DEFAULT
alternative we retain it (remember it comes first). If not the case must
be exhaustive, and we reflect that in the transformed version by adding
a DEFAULT. Otherwise Lint complains that the new case is not exhaustive.
See #8317.
Note [Rules for recursive functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You might think that we shouldn't apply rules for a loop breaker:
doing so might give rise to an infinite loop, because a RULE is
rather like an extra equation for the function:
RULE: f (g x) y = x+y
Eqn: f a y = a-y
But it's too drastic to disable rules for loop breakers.
Even the foldr/build rule would be disabled, because foldr
is recursive, and hence a loop breaker:
foldr k z (build g) = g k z
So it's up to the programmer: rules can cause divergence
************************************************************************
* *
Rebuilding a case expression
* *
************************************************************************
Note [Case elimination]
~~~~~~~~~~~~~~~~~~~~~~~
The case-elimination transformation discards redundant case expressions.
Start with a simple situation:
case x# of ===> let y# = x# in e
y# -> e
(when x#, y# are of primitive type, of course). We can't (in general)
do this for algebraic cases, because we might turn bottom into
non-bottom!
The code in SimplUtils.prepareAlts has the effect of generalise this
idea to look for a case where we're scrutinising a variable, and we
know that only the default case can match. For example:
case x of
0# -> ...
DEFAULT -> ...(case x of
0# -> ...
DEFAULT -> ...) ...
Here the inner case is first trimmed to have only one alternative, the
DEFAULT, after which it's an instance of the previous case. This
really only shows up in eliminating error-checking code.
Note that SimplUtils.mkCase combines identical RHSs. So
case e of ===> case e of DEFAULT -> r
True -> r
False -> r
Now again the case may be elminated by the CaseElim transformation.
This includes things like (==# a# b#)::Bool so that we simplify
case ==# a# b# of { True -> x; False -> x }
to just
x
This particular example shows up in default methods for
comparison operations (e.g. in (>=) for Int.Int32)
Note [Case elimination: lifted case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a case over a lifted type has a single alternative, and is being used
as a strict 'let' (all isDeadBinder bndrs), we may want to do this
transformation:
case e of r ===> let r = e in ...r...
_ -> ...r...
(a) 'e' is already evaluated (it may so if e is a variable)
Specifically we check (exprIsHNF e). In this case
we can just allocate the WHNF directly with a let.
or
(b) 'x' is not used at all and e is ok-for-speculation
The ok-for-spec bit checks that we don't lose any
exceptions or divergence.
NB: it'd be *sound* to switch from case to let if the
scrutinee was not yet WHNF but was guaranteed to
converge; but sticking with case means we won't build a
thunk
or
(c) 'x' is used strictly in the body, and 'e' is a variable
Then we can just substitute 'e' for 'x' in the body.
See Note [Eliminating redundant seqs]
For (b), the "not used at all" test is important. Consider
case (case a ># b of { True -> (p,q); False -> (q,p) }) of
r -> blah
The scrutinee is ok-for-speculation (it looks inside cases), but we do
not want to transform to
let r = case a ># b of { True -> (p,q); False -> (q,p) }
in blah
because that builds an unnecessary thunk.
Note [Eliminating redundant seqs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have this:
case x of r { _ -> ..r.. }
where 'r' is used strictly in (..r..), the case is effectively a 'seq'
on 'x', but since 'r' is used strictly anyway, we can safely transform to
(...x...)
Note that this can change the error behaviour. For example, we might
transform
case x of { _ -> error "bad" }
--> error "bad"
which is might be puzzling if 'x' currently lambda-bound, but later gets
let-bound to (error "good").
Nevertheless, the paper "A semantics for imprecise exceptions" allows
this transformation. If you want to fix the evaluation order, use
'pseq'. See Trac #8900 for an example where the loss of this
transformation bit us in practice.
See also Note [Empty case alternatives] in CoreSyn.
Just for reference, the original code (added Jan 13) looked like this:
|| case_bndr_evald_next rhs
case_bndr_evald_next :: CoreExpr -> Bool
-- See Note [Case binder next]
case_bndr_evald_next (Var v) = v == case_bndr
case_bndr_evald_next (Cast e _) = case_bndr_evald_next e
case_bndr_evald_next (App e _) = case_bndr_evald_next e
case_bndr_evald_next (Case e _ _ _) = case_bndr_evald_next e
case_bndr_evald_next _ = False
(This came up when fixing Trac #7542. See also Note [Eta reduction of
an eval'd function] in CoreUtils.)
Note [Case elimination: unlifted case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
case a +# b of r -> ...r...
Then we do case-elimination (to make a let) followed by inlining,
to get
.....(a +# b)....
If we have
case indexArray# a i of r -> ...r...
we might like to do the same, and inline the (indexArray# a i).
But indexArray# is not okForSpeculation, so we don't build a let
in rebuildCase (lest it get floated *out*), so the inlining doesn't
happen either.
This really isn't a big deal I think. The let can be
Further notes about case elimination
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider: test :: Integer -> IO ()
test = print
Turns out that this compiles to:
Print.test
= \ eta :: Integer
eta1 :: Void# ->
case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
case hPutStr stdout
(PrelNum.jtos eta ($w[] @ Char))
eta1
of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
Notice the strange '<' which has no effect at all. This is a funny one.
It started like this:
f x y = if x < 0 then jtos x
else if y==0 then "" else jtos x
At a particular call site we have (f v 1). So we inline to get
if v < 0 then jtos x
else if 1==0 then "" else jtos x
Now simplify the 1==0 conditional:
if v<0 then jtos v else jtos v
Now common-up the two branches of the case:
case (v<0) of DEFAULT -> jtos v
Why don't we drop the case? Because it's strict in v. It's technically
wrong to drop even unnecessary evaluations, and in practice they
may be a result of 'seq' so we *definitely* don't want to drop those.
I don't really know how to improve this situation.
-}
---------------------------------------------------------
-- Eliminate the case if possible
rebuildCase, reallyRebuildCase
:: SimplEnv
-> OutExpr -- Scrutinee
-> InId -- Case binder
-> [InAlt] -- Alternatives (inceasing order)
-> SimplCont
-> SimplM (SimplEnv, OutExpr)
--------------------------------------------------
-- 1. Eliminate the case if there's a known constructor
--------------------------------------------------
rebuildCase env scrut case_bndr alts cont
| Lit lit <- scrut -- No need for same treatment as constructors
-- because literals are inlined more vigorously
, not (litIsLifted lit)
= do { tick (KnownBranch case_bndr)
; case findAlt (LitAlt lit) alts of
Nothing -> missingAlt env case_bndr alts cont
Just (_, bs, rhs) -> simple_rhs bs rhs }
| Just (con, ty_args, other_args) <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
-- Works when the scrutinee is a variable with a known unfolding
-- as well as when it's an explicit constructor application
= do { tick (KnownBranch case_bndr)
; case findAlt (DataAlt con) alts of
Nothing -> missingAlt env case_bndr alts cont
Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
Just (_, bs, rhs) -> knownCon env scrut con ty_args other_args
case_bndr bs rhs cont
}
where
simple_rhs bs rhs = ASSERT( null bs )
do { env' <- simplNonRecX env case_bndr scrut
-- scrut is a constructor application,
-- hence satisfies let/app invariant
; simplExprF env' rhs cont }
--------------------------------------------------
-- 2. Eliminate the case if scrutinee is evaluated
--------------------------------------------------
rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
-- See if we can get rid of the case altogether
-- See Note [Case elimination]
-- mkCase made sure that if all the alternatives are equal,
-- then there is now only one (DEFAULT) rhs
-- 2a. Dropping the case altogether, if
-- a) it binds nothing (so it's really just a 'seq')
-- b) evaluating the scrutinee has no side effects
| is_plain_seq
, exprOkForSideEffects scrut
-- The entire case is dead, so we can drop it
-- if the scrutinee converges without having imperative
-- side effects or raising a Haskell exception
-- See Note [PrimOp can_fail and has_side_effects] in PrimOp
= simplExprF env rhs cont
-- 2b. Turn the case into a let, if
-- a) it binds only the case-binder
-- b) unlifted case: the scrutinee is ok-for-speculation
-- lifted case: the scrutinee is in HNF (or will later be demanded)
| all_dead_bndrs
, if is_unlifted
then exprOkForSpeculation scrut -- See Note [Case elimination: unlifted case]
else exprIsHNF scrut -- See Note [Case elimination: lifted case]
|| scrut_is_demanded_var scrut
= do { tick (CaseElim case_bndr)
; env' <- simplNonRecX env case_bndr scrut
; simplExprF env' rhs cont }
-- 2c. Try the seq rules if
-- a) it binds only the case binder
-- b) a rule for seq applies
-- See Note [User-defined RULES for seq] in MkId
| is_plain_seq
= do { let rhs' = substExpr (text "rebuild-case") env rhs
env' = zapSubstEnv env
scrut_ty = substTy env (idType case_bndr)
out_args = [ TyArg { as_arg_ty = scrut_ty
, as_hole_ty = seq_id_ty }
, TyArg { as_arg_ty = exprType rhs'
, as_hole_ty = applyTy seq_id_ty scrut_ty }
, ValArg scrut, ValArg rhs']
-- Lazily evaluated, so we don't do most of this
; rule_base <- getSimplRules
; mb_rule <- tryRules env' (getRules rule_base seqId) seqId out_args cont
; case mb_rule of
Just (rule_rhs, cont') -> simplExprF env' rule_rhs cont'
Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
where
is_unlifted = isUnLiftedType (idType case_bndr)
all_dead_bndrs = all isDeadBinder bndrs -- bndrs are [InId]
is_plain_seq = all_dead_bndrs && isDeadBinder case_bndr -- Evaluation *only* for effect
seq_id_ty = idType seqId
scrut_is_demanded_var :: CoreExpr -> Bool
-- See Note [Eliminating redundant seqs]
scrut_is_demanded_var (Cast s _) = scrut_is_demanded_var s
scrut_is_demanded_var (Var _) = isStrictDmd (idDemandInfo case_bndr)
scrut_is_demanded_var _ = False
rebuildCase env scrut case_bndr alts cont
= reallyRebuildCase env scrut case_bndr alts cont
--------------------------------------------------
-- 3. Catch-all case
--------------------------------------------------
reallyRebuildCase env scrut case_bndr alts cont
= do { -- Prepare the continuation;
-- The new subst_env is in place
(env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
-- Simplify the alternatives
; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
; dflags <- getDynFlags
; let alts_ty' = contResultType dup_cont
; case_expr <- mkCase dflags scrut' case_bndr' alts_ty' alts'
-- Notice that rebuild gets the in-scope set from env', not alt_env
-- (which in any case is only build in simplAlts)
-- The case binder *not* scope over the whole returned case-expression
; rebuild env' case_expr nodup_cont }
{-
simplCaseBinder checks whether the scrutinee is a variable, v. If so,
try to eliminate uses of v in the RHSs in favour of case_bndr; that
way, there's a chance that v will now only be used once, and hence
inlined.
Historical note: we use to do the "case binder swap" in the Simplifier
so there were additional complications if the scrutinee was a variable.
Now the binder-swap stuff is done in the occurrence analyer; see
OccurAnal Note [Binder swap].
Note [knownCon occ info]
~~~~~~~~~~~~~~~~~~~~~~~~
If the case binder is not dead, then neither are the pattern bound
variables:
case <any> of x { (a,b) ->
case x of { (p,q) -> p } }
Here (a,b) both look dead, but come alive after the inner case is eliminated.
The point is that we bring into the envt a binding
let x = (a,b)
after the outer case, and that makes (a,b) alive. At least we do unless
the case binder is guaranteed dead.
Note [Case alternative occ info]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we are simply reconstructing a case (the common case), we always
zap the occurrence info on the binders in the alternatives. Even
if the case binder is dead, the scrutinee is usually a variable, and *that*
can bring the case-alternative binders back to life.
See Note [Add unfolding for scrutinee]
Note [Improving seq]
~~~~~~~~~~~~~~~~~~~
Consider
type family F :: * -> *
type instance F Int = Int
... case e of x { DEFAULT -> rhs } ...
where x::F Int. Then we'd like to rewrite (F Int) to Int, getting
case e `cast` co of x'::Int
I# x# -> let x = x' `cast` sym co
in rhs
so that 'rhs' can take advantage of the form of x'.
Notice that Note [Case of cast] (in OccurAnal) may then apply to the result.
Nota Bene: We only do the [Improving seq] transformation if the
case binder 'x' is actually used in the rhs; that is, if the case
is *not* a *pure* seq.
a) There is no point in adding the cast to a pure seq.
b) There is a good reason not to: doing so would interfere
with seq rules (Note [Built-in RULES for seq] in MkId).
In particular, this [Improving seq] thing *adds* a cast
while [Built-in RULES for seq] *removes* one, so they
just flip-flop.
You might worry about
case v of x { __DEFAULT ->
... case (v `cast` co) of y { I# -> ... }}
This is a pure seq (since x is unused), so [Improving seq] won't happen.
But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
case v of x { __DEFAULT ->
... case (x `cast` co) of y { I# -> ... }}
Now the outer case is not a pure seq, so [Improving seq] will happen,
and then the inner case will disappear.
The need for [Improving seq] showed up in Roman's experiments. Example:
foo :: F Int -> Int -> Int
foo t n = t `seq` bar n
where
bar 0 = 0
bar n = bar (n - case t of TI i -> i)
Here we'd like to avoid repeated evaluating t inside the loop, by
taking advantage of the `seq`.
At one point I did transformation in LiberateCase, but it's more
robust here. (Otherwise, there's a danger that we'll simply drop the
'seq' altogether, before LiberateCase gets to see it.)
-}
simplAlts :: SimplEnv
-> OutExpr
-> InId -- Case binder
-> [InAlt] -- Non-empty
-> SimplCont
-> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
-- Like simplExpr, this just returns the simplified alternatives;
-- it does not return an environment
-- The returned alternatives can be empty, none are possible
simplAlts env scrut case_bndr alts cont'
= do { let env0 = zapFloats env
; (env1, case_bndr1) <- simplBinder env0 case_bndr
; fam_envs <- getFamEnvs
; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut
case_bndr case_bndr1 alts
; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
-- NB: it's possible that the returned in_alts is empty: this is handled
-- by the caller (rebuildCase) in the missingAlt function
; alts' <- mapM (simplAlt alt_env' (Just scrut') imposs_deflt_cons case_bndr' cont') in_alts
; -- pprTrace "simplAlts" (ppr case_bndr $$ ppr alts_ty $$ ppr alts_ty' $$ ppr alts $$ ppr cont') $
return (scrut', case_bndr', alts') }
------------------------------------
improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
-> OutExpr -> InId -> OutId -> [InAlt]
-> SimplM (SimplEnv, OutExpr, OutId)
-- Note [Improving seq]
improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
| not (isDeadBinder case_bndr) -- Not a pure seq! See Note [Improving seq]
, Just (co, ty2) <- topNormaliseType_maybe fam_envs (idType case_bndr1)
= do { case_bndr2 <- newId (fsLit "nt") ty2
; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCo co)
env2 = extendIdSubst env case_bndr rhs
; return (env2, scrut `Cast` co, case_bndr2) }
improveSeq _ env scrut _ case_bndr1 _
= return (env, scrut, case_bndr1)
------------------------------------
simplAlt :: SimplEnv
-> Maybe OutExpr -- The scrutinee
-> [AltCon] -- These constructors can't be present when
-- matching the DEFAULT alternative
-> OutId -- The case binder
-> SimplCont
-> InAlt
-> SimplM OutAlt
simplAlt env _ imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
= ASSERT( null bndrs )
do { let env' = addBinderUnfolding env case_bndr'
(mkOtherCon imposs_deflt_cons)
-- Record the constructors that the case-binder *can't* be.
; rhs' <- simplExprC env' rhs cont'
; return (DEFAULT, [], rhs') }
simplAlt env scrut' _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
= ASSERT( null bndrs )
do { env' <- addAltUnfoldings env scrut' case_bndr' (Lit lit)
; rhs' <- simplExprC env' rhs cont'
; return (LitAlt lit, [], rhs') }
simplAlt env scrut' _ case_bndr' cont' (DataAlt con, vs, rhs)
= do { -- Deal with the pattern-bound variables
-- Mark the ones that are in ! positions in the
-- data constructor as certainly-evaluated.
-- NB: simplLamBinders preserves this eval info
; let vs_with_evals = add_evals (dataConRepStrictness con)
; (env', vs') <- simplLamBndrs env vs_with_evals
-- Bind the case-binder to (con args)
; let inst_tys' = tyConAppArgs (idType case_bndr')
con_app :: OutExpr
con_app = mkConApp2 con inst_tys' vs'
; env'' <- addAltUnfoldings env' scrut' case_bndr' con_app
; rhs' <- simplExprC env'' rhs cont'
; return (DataAlt con, vs', rhs') }
where
-- add_evals records the evaluated-ness of the bound variables of
-- a case pattern. This is *important*. Consider
-- data T = T !Int !Int
--
-- case x of { T a b -> T (a+1) b }
--
-- We really must record that b is already evaluated so that we don't
-- go and re-evaluate it when constructing the result.
-- See Note [Data-con worker strictness] in MkId.hs
add_evals the_strs
= go vs the_strs
where
go [] [] = []
go (v:vs') strs | isTyVar v = v : go vs' strs
go (v:vs') (str:strs)
| isMarkedStrict str = evald_v : go vs' strs
| otherwise = zapped_v : go vs' strs
where
zapped_v = zapIdOccInfo v -- See Note [Case alternative occ info]
evald_v = zapped_v `setIdUnfolding` evaldUnfolding
go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
addAltUnfoldings :: SimplEnv -> Maybe OutExpr -> OutId -> OutExpr -> SimplM SimplEnv
addAltUnfoldings env scrut case_bndr con_app
= do { dflags <- getDynFlags
; let con_app_unf = mkSimpleUnfolding dflags con_app
env1 = addBinderUnfolding env case_bndr con_app_unf
-- See Note [Add unfolding for scrutinee]
env2 = case scrut of
Just (Var v) -> addBinderUnfolding env1 v con_app_unf
Just (Cast (Var v) co) -> addBinderUnfolding env1 v $
mkSimpleUnfolding dflags (Cast con_app (mkSymCo co))
_ -> env1
; traceSmpl "addAltUnf" (vcat [ppr case_bndr <+> ppr scrut, ppr con_app])
; return env2 }
addBinderUnfolding :: SimplEnv -> Id -> Unfolding -> SimplEnv
addBinderUnfolding env bndr unf
| debugIsOn, Just tmpl <- maybeUnfoldingTemplate unf
= WARN( not (eqType (idType bndr) (exprType tmpl)),
ppr bndr $$ ppr (idType bndr) $$ ppr tmpl $$ ppr (exprType tmpl) )
modifyInScope env (bndr `setIdUnfolding` unf)
| otherwise
= modifyInScope env (bndr `setIdUnfolding` unf)
zapBndrOccInfo :: Bool -> Id -> Id
-- Consider case e of b { (a,b) -> ... }
-- Then if we bind b to (a,b) in "...", and b is not dead,
-- then we must zap the deadness info on a,b
zapBndrOccInfo keep_occ_info pat_id
| keep_occ_info = pat_id
| otherwise = zapIdOccInfo pat_id
{-
Note [Add unfolding for scrutinee]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In general it's unlikely that a variable scrutinee will appear
in the case alternatives case x of { ...x unlikely to appear... }
because the binder-swap in OccAnal has got rid of all such occcurrences
See Note [Binder swap] in OccAnal.
BUT it is still VERY IMPORTANT to add a suitable unfolding for a
variable scrutinee, in simplAlt. Here's why
case x of y
(a,b) -> case b of c
I# v -> ...(f y)...
There is no occurrence of 'b' in the (...(f y)...). But y gets
the unfolding (a,b), and *that* mentions b. If f has a RULE
RULE f (p, I# q) = ...
we want that rule to match, so we must extend the in-scope env with a
suitable unfolding for 'y'. It's *essential* for rule matching; but
it's also good for case-elimintation -- suppose that 'f' was inlined
and did multi-level case analysis, then we'd solve it in one
simplifier sweep instead of two.
Exactly the same issue arises in SpecConstr;
see Note [Add scrutinee to ValueEnv too] in SpecConstr
HOWEVER, given
case x of y { Just a -> r1; Nothing -> r2 }
we do not want to add the unfolding x -> y to 'x', which might seem cool,
since 'y' itself has different unfoldings in r1 and r2. Reason: if we
did that, we'd have to zap y's deadness info and that is a very useful
piece of information.
So instead we add the unfolding x -> Just a, and x -> Nothing in the
respective RHSs.
************************************************************************
* *
\subsection{Known constructor}
* *
************************************************************************
We are a bit careful with occurrence info. Here's an example
(\x* -> case x of (a*, b) -> f a) (h v, e)
where the * means "occurs once". This effectively becomes
case (h v, e) of (a*, b) -> f a)
and then
let a* = h v; b = e in f a
and then
f (h v)
All this should happen in one sweep.
-}
knownCon :: SimplEnv
-> OutExpr -- The scrutinee
-> DataCon -> [OutType] -> [OutExpr] -- The scrutinee (in pieces)
-> InId -> [InBndr] -> InExpr -- The alternative
-> SimplCont
-> SimplM (SimplEnv, OutExpr)
knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
= do { env' <- bind_args env bs dc_args
; env'' <- bind_case_bndr env'
; simplExprF env'' rhs cont }
where
zap_occ = zapBndrOccInfo (isDeadBinder bndr) -- bndr is an InId
-- Ugh!
bind_args env' [] _ = return env'
bind_args env' (b:bs') (Type ty : args)
= ASSERT( isTyVar b )
bind_args (extendTvSubst env' b ty) bs' args
bind_args env' (b:bs') (arg : args)
= ASSERT( isId b )
do { let b' = zap_occ b
-- Note that the binder might be "dead", because it doesn't
-- occur in the RHS; and simplNonRecX may therefore discard
-- it via postInlineUnconditionally.
-- Nevertheless we must keep it if the case-binder is alive,
-- because it may be used in the con_app. See Note [knownCon occ info]
; env'' <- simplNonRecX env' b' arg -- arg satisfies let/app invariant
; bind_args env'' bs' args }
bind_args _ _ _ =
pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
text "scrut:" <+> ppr scrut
-- It's useful to bind bndr to scrut, rather than to a fresh
-- binding x = Con arg1 .. argn
-- because very often the scrut is a variable, so we avoid
-- creating, and then subsequently eliminating, a let-binding
-- BUT, if scrut is a not a variable, we must be careful
-- about duplicating the arg redexes; in that case, make
-- a new con-app from the args
bind_case_bndr env
| isDeadBinder bndr = return env
| exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut))
| otherwise = do { dc_args <- mapM (simplVar env) bs
-- dc_ty_args are aready OutTypes,
-- but bs are InBndrs
; let con_app = Var (dataConWorkId dc)
`mkTyApps` dc_ty_args
`mkApps` dc_args
; simplNonRecX env bndr con_app }
-------------------
missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
-- This isn't strictly an error, although it is unusual.
-- It's possible that the simplifer might "see" that
-- an inner case has no accessible alternatives before
-- it "sees" that the entire branch of an outer case is
-- inaccessible. So we simply put an error case here instead.
missingAlt env case_bndr _ cont
= WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr )
return (env, mkImpossibleExpr (contResultType cont))
{-
************************************************************************
* *
\subsection{Duplicating continuations}
* *
************************************************************************
-}
prepareCaseCont :: SimplEnv
-> [InAlt] -> SimplCont
-> SimplM (SimplEnv,
SimplCont, -- Dupable part
SimplCont) -- Non-dupable part
-- We are considering
-- K[case _ of { p1 -> r1; ...; pn -> rn }]
-- where K is some enclosing continuation for the case
-- Goal: split K into two pieces Kdup,Knodup so that
-- a) Kdup can be duplicated
-- b) Knodup[Kdup[e]] = K[e]
-- The idea is that we'll transform thus:
-- Knodup[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }
--
-- We may also return some extra bindings in SimplEnv (that scope over
-- the entire continuation)
--
-- When case-of-case is off, just make the entire continuation non-dupable
prepareCaseCont env alts cont
| not (sm_case_case (getMode env)) = return (env, mkBoringStop (contHoleType cont), cont)
| not (many_alts alts) = return (env, cont, mkBoringStop (contResultType cont))
| otherwise = mkDupableCont env cont
where
many_alts :: [InAlt] -> Bool -- True iff strictly > 1 non-bottom alternative
many_alts [] = False -- See Note [Bottom alternatives]
many_alts [_] = False
many_alts (alt:alts)
| is_bot_alt alt = many_alts alts
| otherwise = not (all is_bot_alt alts)
is_bot_alt (_,_,rhs) = exprIsBottom rhs
{-
Note [Bottom alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~
When we have
case (case x of { A -> error .. ; B -> e; C -> error ..)
of alts
then we can just duplicate those alts because the A and C cases
will disappear immediately. This is more direct than creating
join points and inlining them away; and in some cases we would
not even create the join points (see Note [Single-alternative case])
and we would keep the case-of-case which is silly. See Trac #4930.
-}
mkDupableCont :: SimplEnv -> SimplCont
-> SimplM (SimplEnv, SimplCont, SimplCont)
mkDupableCont env cont
| contIsDupable cont
= return (env, cont, mkBoringStop (contResultType cont))
mkDupableCont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
mkDupableCont env (CastIt ty cont)
= do { (env', dup, nodup) <- mkDupableCont env cont
; return (env', CastIt ty dup, nodup) }
-- Duplicating ticks for now, not sure if this is good or not
mkDupableCont env cont@(TickIt{})
= return (env, mkBoringStop (contHoleType cont), cont)
mkDupableCont env cont@(StrictBind {})
= return (env, mkBoringStop (contHoleType cont), cont)
-- See Note [Duplicating StrictBind]
mkDupableCont env (StrictArg info cci cont)
-- See Note [Duplicating StrictArg]
= do { (env', dup, nodup) <- mkDupableCont env cont
; (env'', args') <- mapAccumLM makeTrivialArg env' (ai_args info)
; return (env'', StrictArg (info { ai_args = args' }) cci dup, nodup) }
mkDupableCont env cont@(ApplyToTy { sc_cont = tail })
= do { (env', dup_cont, nodup_cont) <- mkDupableCont env tail
; return (env', cont { sc_cont = dup_cont }, nodup_cont ) }
mkDupableCont env (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = cont })
= -- e.g. [...hole...] (...arg...)
-- ==>
-- let a = ...arg...
-- in [...hole...] a
do { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
; arg' <- simplExpr (se `setInScope` env') arg
; (env'', arg'') <- makeTrivial NotTopLevel env' arg'
; let app_cont = ApplyToVal { sc_arg = arg'', sc_env = zapSubstEnv env''
, sc_dup = OkToDup, sc_cont = dup_cont }
; return (env'', app_cont, nodup_cont) }
mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
-- See Note [Single-alternative case]
-- | not (exprIsDupable rhs && contIsDupable case_cont)
-- | not (isDeadBinder case_bndr)
| all isDeadBinder bs -- InIds
&& not (isUnLiftedType (idType case_bndr))
-- Note [Single-alternative-unlifted]
= return (env, mkBoringStop (contHoleType cont), cont)
mkDupableCont env (Select _ case_bndr alts se cont)
= -- e.g. (case [...hole...] of { pi -> ei })
-- ===>
-- let ji = \xij -> ei
-- in case [...hole...] of { pi -> ji xij }
do { tick (CaseOfCase case_bndr)
; (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
-- NB: We call prepareCaseCont here. If there is only one
-- alternative, then dup_cont may be big, but that's ok
-- because we push it into the single alternative, and then
-- use mkDupableAlt to turn that simplified alternative into
-- a join point if it's too big to duplicate.
-- And this is important: see Note [Fusing case continuations]
; let alt_env = se `setInScope` env'
; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
; alts' <- mapM (simplAlt alt_env' Nothing [] case_bndr' dup_cont) alts
-- Safe to say that there are no handled-cons for the DEFAULT case
-- NB: simplBinder does not zap deadness occ-info, so
-- a dead case_bndr' will still advertise its deadness
-- This is really important because in
-- case e of b { (# p,q #) -> ... }
-- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
-- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
-- In the new alts we build, we have the new case binder, so it must retain
-- its deadness.
-- NB: we don't use alt_env further; it has the substEnv for
-- the alternatives, and we don't want that
; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
; return (env'', -- Note [Duplicated env]
Select OkToDup case_bndr' alts'' (zapSubstEnv env'')
(mkBoringStop (contHoleType nodup_cont)),
nodup_cont) }
mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
-> SimplM (SimplEnv, [InAlt])
-- Absorbs the continuation into the new alternatives
mkDupableAlts env case_bndr' the_alts
= go env the_alts
where
go env0 [] = return (env0, [])
go env0 (alt:alts)
= do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
; (env2, alts') <- go env1 alts
; return (env2, alt' : alts' ) }
mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
-> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
mkDupableAlt env case_bndr (con, bndrs', rhs') = do
dflags <- getDynFlags
if exprIsDupable dflags rhs' -- Note [Small alternative rhs]
then return (env, (con, bndrs', rhs'))
else
do { let rhs_ty' = exprType rhs'
scrut_ty = idType case_bndr
case_bndr_w_unf
= case con of
DEFAULT -> case_bndr
DataAlt dc -> setIdUnfolding case_bndr unf
where
-- See Note [Case binders and join points]
unf = mkInlineUnfolding Nothing rhs
rhs = mkConApp2 dc (tyConAppArgs scrut_ty) bndrs'
LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt")
<+> ppr case_bndr <+> ppr con )
case_bndr
-- The case binder is alive but trivial, so why has
-- it not been substituted away?
used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs'
| otherwise = bndrs' ++ [case_bndr_w_unf]
abstract_over bndr
| isTyVar bndr = True -- Abstract over all type variables just in case
| otherwise = not (isDeadBinder bndr)
-- The deadness info on the new Ids is preserved by simplBinders
; (final_bndrs', final_args) -- Note [Join point abstraction]
<- if (any isId used_bndrs')
then return (used_bndrs', varsToCoreExprs used_bndrs')
else do { rw_id <- newId (fsLit "w") voidPrimTy
; return ([setOneShotLambda rw_id], [Var voidPrimId]) }
; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
-- Note [Funky mkPiTypes]
; let -- We make the lambdas into one-shot-lambdas. The
-- join point is sure to be applied at most once, and doing so
-- prevents the body of the join point being floated out by
-- the full laziness pass
really_final_bndrs = map one_shot final_bndrs'
one_shot v | isId v = setOneShotLambda v
| otherwise = v
join_rhs = mkLams really_final_bndrs rhs'
join_arity = exprArity join_rhs
join_call = mkApps (Var join_bndr) final_args
; env' <- addPolyBind NotTopLevel env (NonRec (join_bndr `setIdArity` join_arity) join_rhs)
; return (env', (con, bndrs', join_call)) }
-- See Note [Duplicated env]
{-
Note [Fusing case continuations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's important to fuse two successive case continuations when the
first has one alternative. That's why we call prepareCaseCont here.
Consider this, which arises from thunk splitting (see Note [Thunk
splitting] in WorkWrap):
let
x* = case (case v of {pn -> rn}) of
I# a -> I# a
in body
The simplifier will find
(Var v) with continuation
Select (pn -> rn) (
Select [I# a -> I# a] (
StrictBind body Stop
So we'll call mkDupableCont on
Select [I# a -> I# a] (StrictBind body Stop)
There is just one alternative in the first Select, so we want to
simplify the rhs (I# a) with continuation (StricgtBind body Stop)
Supposing that body is big, we end up with
let $j a = <let x = I# a in body>
in case v of { pn -> case rn of
I# a -> $j a }
This is just what we want because the rn produces a box that
the case rn cancels with.
See Trac #4957 a fuller example.
Note [Case binders and join points]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
case (case .. ) of c {
I# c# -> ....c....
If we make a join point with c but not c# we get
$j = \c -> ....c....
But if later inlining scrutines the c, thus
$j = \c -> ... case c of { I# y -> ... } ...
we won't see that 'c' has already been scrutinised. This actually
happens in the 'tabulate' function in wave4main, and makes a significant
difference to allocation.
An alternative plan is this:
$j = \c# -> let c = I# c# in ...c....
but that is bad if 'c' is *not* later scrutinised.
So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
(a stable unfolding) that it's really I# c#, thus
$j = \c# -> \c[=I# c#] -> ...c....
Absence analysis may later discard 'c'.
NB: take great care when doing strictness analysis;
see Note [Lamba-bound unfoldings] in DmdAnal.
Also note that we can still end up passing stuff that isn't used. Before
strictness analysis we have
let $j x y c{=(x,y)} = (h c, ...)
in ...
After strictness analysis we see that h is strict, we end up with
let $j x y c{=(x,y)} = ($wh x y, ...)
and c is unused.
Note [Duplicated env]
~~~~~~~~~~~~~~~~~~~~~
Some of the alternatives are simplified, but have not been turned into a join point
So they *must* have an zapped subst-env. So we can't use completeNonRecX to
bind the join point, because it might to do PostInlineUnconditionally, and
we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
but zapping it (as we do in mkDupableCont, the Select case) is safe, and
at worst delays the join-point inlining.
Note [Small alternative rhs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is worth checking for a small RHS because otherwise we
get extra let bindings that may cause an extra iteration of the simplifier to
inline back in place. Quite often the rhs is just a variable or constructor.
The Ord instance of Maybe in PrelMaybe.hs, for example, took several extra
iterations because the version with the let bindings looked big, and so wasn't
inlined, but after the join points had been inlined it looked smaller, and so
was inlined.
NB: we have to check the size of rhs', not rhs.
Duplicating a small InAlt might invalidate occurrence information
However, if it *is* dupable, we return the *un* simplified alternative,
because otherwise we'd need to pair it up with an empty subst-env....
but we only have one env shared between all the alts.
(Remember we must zap the subst-env before re-simplifying something).
Rather than do this we simply agree to re-simplify the original (small) thing later.
Note [Funky mkPiTypes]
~~~~~~~~~~~~~~~~~~~~~~
Notice the funky mkPiTypes. If the contructor has existentials
it's possible that the join point will be abstracted over
type variables as well as term variables.
Example: Suppose we have
data T = forall t. C [t]
Then faced with
case (case e of ...) of
C t xs::[t] -> rhs
We get the join point
let j :: forall t. [t] -> ...
j = /\t \xs::[t] -> rhs
in
case (case e of ...) of
C t xs::[t] -> j t xs
Note [Join point abstraction]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Join points always have at least one value argument,
for several reasons
* If we try to lift a primitive-typed something out
for let-binding-purposes, we will *caseify* it (!),
with potentially-disastrous strictness results. So
instead we turn it into a function: \v -> e
where v::Void#. The value passed to this function is void,
which generates (almost) no code.
* CPR. We used to say "&& isUnLiftedType rhs_ty'" here, but now
we make the join point into a function whenever used_bndrs'
is empty. This makes the join-point more CPR friendly.
Consider: let j = if .. then I# 3 else I# 4
in case .. of { A -> j; B -> j; C -> ... }
Now CPR doesn't w/w j because it's a thunk, so
that means that the enclosing function can't w/w either,
which is a lose. Here's the example that happened in practice:
kgmod :: Int -> Int -> Int
kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
then 78
else 5
* Let-no-escape. We want a join point to turn into a let-no-escape
so that it is implemented as a jump, and one of the conditions
for LNE is that it's not updatable. In CoreToStg, see
Note [What is a non-escaping let]
* Floating. Since a join point will be entered once, no sharing is
gained by floating out, but something might be lost by doing
so because it might be allocated.
I have seen a case alternative like this:
True -> \v -> ...
It's a bit silly to add the realWorld dummy arg in this case, making
$j = \s v -> ...
True -> $j s
(the \v alone is enough to make CPR happy) but I think it's rare
There's a slight infelicity here: we pass the overall
case_bndr to all the join points if it's used in *any* RHS,
because we don't know its usage in each RHS separately
Note [Duplicating StrictArg]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The original plan had (where E is a big argument)
e.g. f E [..hole..]
==> let $j = \a -> f E a
in $j [..hole..]
But this is terrible! Here's an example:
&& E (case x of { T -> F; F -> T })
Now, && is strict so we end up simplifying the case with
an ArgOf continuation. If we let-bind it, we get
let $j = \v -> && E v
in simplExpr (case x of { T -> F; F -> T })
(ArgOf (\r -> $j r)
And after simplifying more we get
let $j = \v -> && E v
in case x of { T -> $j F; F -> $j T }
Which is a Very Bad Thing
What we do now is this
f E [..hole..]
==> let a = E
in f a [..hole..]
Now if the thing in the hole is a case expression (which is when
we'll call mkDupableCont), we'll push the function call into the
branches, which is what we want. Now RULES for f may fire, and
call-pattern specialisation. Here's an example from Trac #3116
go (n+1) (case l of
1 -> bs'
_ -> Chunk p fpc (o+1) (l-1) bs')
If we can push the call for 'go' inside the case, we get
call-pattern specialisation for 'go', which is *crucial* for
this program.
Here is the (&&) example:
&& E (case x of { T -> F; F -> T })
==> let a = E in
case x of { T -> && a F; F -> && a T }
Much better!
Notice that
* Arguments to f *after* the strict one are handled by
the ApplyToVal case of mkDupableCont. Eg
f [..hole..] E
* We can only do the let-binding of E because the function
part of a StrictArg continuation is an explicit syntax
tree. In earlier versions we represented it as a function
(CoreExpr -> CoreEpxr) which we couldn't take apart.
Do *not* duplicate StrictBind and StritArg continuations. We gain
nothing by propagating them into the expressions, and we do lose a
lot.
The desire not to duplicate is the entire reason that
mkDupableCont returns a pair of continuations.
Note [Duplicating StrictBind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unlike StrictArg, there doesn't seem anything to gain from
duplicating a StrictBind continuation, so we don't.
Note [Single-alternative cases]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This case is just like the ArgOf case. Here's an example:
data T a = MkT !a
...(MkT (abs x))...
Then we get
case (case x of I# x' ->
case x' <# 0# of
True -> I# (negate# x')
False -> I# x') of y {
DEFAULT -> MkT y
Because the (case x) has only one alternative, we'll transform to
case x of I# x' ->
case (case x' <# 0# of
True -> I# (negate# x')
False -> I# x') of y {
DEFAULT -> MkT y
But now we do *NOT* want to make a join point etc, giving
case x of I# x' ->
let $j = \y -> MkT y
in case x' <# 0# of
True -> $j (I# (negate# x'))
False -> $j (I# x')
In this case the $j will inline again, but suppose there was a big
strict computation enclosing the orginal call to MkT. Then, it won't
"see" the MkT any more, because it's big and won't get duplicated.
And, what is worse, nothing was gained by the case-of-case transform.
So, in circumstances like these, we don't want to build join points
and push the outer case into the branches of the inner one. Instead,
don't duplicate the continuation.
When should we use this strategy? We should not use it on *every*
single-alternative case:
e.g. case (case ....) of (a,b) -> (# a,b #)
Here we must push the outer case into the inner one!
Other choices:
* Match [(DEFAULT,_,_)], but in the common case of Int,
the alternative-filling-in code turned the outer case into
case (...) of y { I# _ -> MkT y }
* Match on single alternative plus (not (isDeadBinder case_bndr))
Rationale: pushing the case inwards won't eliminate the construction.
But there's a risk of
case (...) of y { (a,b) -> let z=(a,b) in ... }
Now y looks dead, but it'll come alive again. Still, this
seems like the best option at the moment.
* Match on single alternative plus (all (isDeadBinder bndrs))
Rationale: this is essentially seq.
* Match when the rhs is *not* duplicable, and hence would lead to a
join point. This catches the disaster-case above. We can test
the *un-simplified* rhs, which is fine. It might get bigger or
smaller after simplification; if it gets smaller, this case might
fire next time round. NB also that we must test contIsDupable
case_cont *too, because case_cont might be big!
HOWEVER: I found that this version doesn't work well, because
we can get let x = case (...) of { small } in ...case x...
When x is inlined into its full context, we find that it was a bad
idea to have pushed the outer case inside the (...) case.
Note [Single-alternative-unlifted]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here's another single-alternative where we really want to do case-of-case:
data Mk1 = Mk1 Int# | Mk2 Int#
M1.f =
\r [x_s74 y_s6X]
case
case y_s6X of tpl_s7m {
M1.Mk1 ipv_s70 -> ipv_s70;
M1.Mk2 ipv_s72 -> ipv_s72;
}
of
wild_s7c
{ __DEFAULT ->
case
case x_s74 of tpl_s7n {
M1.Mk1 ipv_s77 -> ipv_s77;
M1.Mk2 ipv_s79 -> ipv_s79;
}
of
wild1_s7b
{ __DEFAULT -> ==# [wild1_s7b wild_s7c];
};
};
So the outer case is doing *nothing at all*, other than serving as a
join-point. In this case we really want to do case-of-case and decide
whether to use a real join point or just duplicate the continuation:
let $j s7c = case x of
Mk1 ipv77 -> (==) s7c ipv77
Mk1 ipv79 -> (==) s7c ipv79
in
case y of
Mk1 ipv70 -> $j ipv70
Mk2 ipv72 -> $j ipv72
Hence: check whether the case binder's type is unlifted, because then
the outer case is *not* a seq.
-}
| christiaanb/ghc | compiler/simplCore/Simplify.hs | bsd-3-clause | 118,610 | 18 | 25 | 36,268 | 14,240 | 7,535 | 6,705 | -1 | -1 |
module Generate.JavaScript.Port (inbound, outbound, task) where
import qualified Data.List as List
import qualified Data.Map as Map
import Language.ECMAScript3.Syntax
import qualified AST.Type as T
import qualified AST.Variable as Var
import Generate.JavaScript.Helpers
import qualified Reporting.Render.Type as RenderType
-- TASK
task :: String -> Expression () -> T.Port t -> Expression ()
task name expr portType =
case portType of
T.Normal _ ->
_Task "perform" `call` [ expr ]
T.Signal _ _ ->
_Task "performSignal" `call` [ StringLit () name, expr ]
-- HELPERS
data JSType
= JSNumber
| JSInt
| JSBoolean
| JSString
| JSArray
| JSObject [String]
typeToString :: JSType -> String
typeToString tipe =
case tipe of
JSNumber -> "a number"
JSInt -> "an integer"
JSBoolean -> "a boolean (true or false)"
JSString -> "a string"
JSArray -> "an array"
JSObject fields ->
"an object with fields `" ++ List.intercalate "`, `" fields ++ "`"
_Array :: String -> Expression ()
_Array functionName =
useLazy ["Elm","Native","Array"] functionName
_List :: String -> Expression ()
_List functionName =
useLazy ["Elm","Native","List"] functionName
_Maybe :: String -> Expression ()
_Maybe functionName =
useLazy ["Elm","Maybe"] functionName
_Port :: String -> Expression ()
_Port functionName =
useLazy ["Elm","Native","Port"] functionName
_Task :: String -> Expression ()
_Task functionName =
useLazy ["Elm","Native","Task"] functionName
check :: Expression () -> JSType -> Expression () -> Expression ()
check x jsType continue =
CondExpr () (jsFold OpLOr checks x) continue throw
where
jsFold op checks value =
foldl1 (InfixExpr () op) (map ($ value) checks)
throw =
obj ["_U","badPort"] `call` [ StringLit () (typeToString jsType), x ]
checks =
case jsType of
JSNumber ->
[typeof "number"]
JSInt ->
[jsFold OpLAnd intChecks]
JSBoolean ->
[typeof "boolean"]
JSString ->
[typeof "string", instanceof "String"]
JSArray ->
[instanceof "Array"]
JSObject fields ->
[jsFold OpLAnd (typeof "object" : map member fields)]
intChecks :: [Expression () -> Expression ()]
intChecks =
[ typeof "number"
, \x -> ref "isFinite" <| x
, \x -> equal (obj ["Math","floor"] <| x) x
]
-- INBOUND
inbound :: String -> T.Port T.Canonical -> Expression ()
inbound name portType =
case portType of
T.Normal tipe ->
_Port "inbound" `call`
[ StringLit () name
, StringLit () (show (RenderType.toDoc Map.empty tipe))
, toTypeFunction tipe
]
T.Signal _root arg ->
_Port "inboundSignal" `call`
[ StringLit () name
, StringLit () (show (RenderType.toDoc Map.empty arg))
, toTypeFunction arg
]
toTypeFunction :: T.Canonical -> Expression ()
toTypeFunction tipe =
function ["v"] [ ReturnStmt () (Just (toType tipe (ref "v"))) ]
toType :: T.Canonical -> Expression () -> Expression ()
toType tipe x =
case tipe of
T.Lambda _ _ ->
error "functions should not be allowed through input ports"
T.Var _ ->
error "type variables should not be allowed through input ports"
T.Aliased _ args t ->
toType (T.dealias args t) x
T.Type (Var.Canonical Var.BuiltIn name)
| name == "Float" -> from JSNumber
| name == "Int" -> from JSInt
| name == "Bool" -> from JSBoolean
| name == "String" -> from JSString
where
from checks = check x checks x
T.Type name
| Var.isJson name ->
x
| Var.isTuple name ->
toTuple [] x
| otherwise ->
error "bad type got to foreign input conversion"
T.App f args ->
case f : args of
T.Type name : [t]
| Var.isMaybe name ->
CondExpr ()
(equal x (NullLit ()))
(_Maybe "Nothing")
(_Maybe "Just" <| toType t x)
| Var.isList name ->
check x JSArray (_List "fromArray" <| array)
| Var.isArray name ->
check x JSArray (_Array "fromJSArray" <| array)
where
array = DotRef () x (var "map") <| toTypeFunction t
T.Type name : ts
| Var.isTuple name ->
toTuple ts x
_ -> error "bad ADT got to foreign input conversion"
T.Record _ (Just _) ->
error "bad record got to foreign input conversion"
T.Record fields Nothing ->
check x (JSObject (map fst fields)) object
where
object = ObjectLit () $ (prop "_", ObjectLit () []) : keys
keys = map convert fields
convert (f,t) = (prop f, toType t (DotRef () x (var f)))
toTuple :: [T.Canonical] -> Expression () -> Expression ()
toTuple types x =
check x JSArray (ObjectLit () fields)
where
fields =
(prop "ctor", ctor) : zipWith convert [0..] types
ctor =
StringLit () ("_Tuple" ++ show (length types))
convert n t =
( prop ('_':show n)
, toType t (BracketRef () x (IntLit () n))
)
-- OUTBOUND
outbound :: String -> Expression () -> T.Port T.Canonical -> Expression ()
outbound name expr portType =
case portType of
T.Normal tipe ->
_Port "outbound" `call` [ StringLit () name, fromTypeFunction tipe, expr ]
T.Signal _ arg ->
_Port "outboundSignal" `call` [ StringLit () name, fromTypeFunction arg, expr ]
fromTypeFunction :: T.Canonical -> Expression ()
fromTypeFunction tipe =
function ["v"] [ ReturnStmt () (Just (fromType tipe (ref "v"))) ]
fromType :: T.Canonical -> Expression () -> Expression ()
fromType tipe x =
case tipe of
T.Aliased _ args t ->
fromType (T.dealias args t) x
T.Lambda _ _
| numArgs > 1 && numArgs < 10 ->
func (ref ('A':show numArgs) `call` (x:values))
| otherwise ->
func (foldl (<|) x values)
where
ts = T.collectLambdas tipe
numArgs = length ts - 1
args = map (\n -> '_' : show n) [0..]
values = zipWith toType (init ts) (map ref args)
func body =
function (take numArgs args)
[ VarDeclStmt () [VarDecl () (var "_r") (Just body)]
, ReturnStmt () (Just (fromType (last ts) (ref "_r")))
]
T.Var _ ->
error "type variables should not be allowed through outputs"
T.Type (Var.Canonical Var.BuiltIn name)
| name `elem` ["Int","Float","Bool","String"] ->
x
T.Type name
| Var.isJson name -> x
| Var.isTuple name -> ArrayLit () []
| otherwise -> error "bad type got to an output"
T.App f args ->
case f : args of
T.Type name : [t]
| Var.isMaybe name ->
CondExpr ()
(equal (DotRef () x (var "ctor")) (StringLit () "Nothing"))
(NullLit ())
(fromType t (DotRef () x (var "_0")))
| Var.isArray name ->
DotRef () (_Array "toJSArray" <| x) (var "map") <| fromTypeFunction t
| Var.isList name ->
DotRef () (_List "toArray" <| x) (var "map") <| fromTypeFunction t
T.Type name : ts
| Var.isTuple name ->
let convert n t = fromType t $ DotRef () x $ var ('_':show n)
in ArrayLit () $ zipWith convert [0..] ts
_ -> error "bad ADT got to an output"
T.Record _ (Just _) ->
error "bad record got to an output"
T.Record fields Nothing ->
ObjectLit () keys
where
keys = map convert fields
convert (f,t) =
(PropId () (var f), fromType t (DotRef () x (var f)))
| laszlopandy/elm-compiler | src/Generate/JavaScript/Port.hs | bsd-3-clause | 8,276 | 0 | 20 | 2,905 | 2,894 | 1,433 | 1,461 | 206 | 10 |
{-# OPTIONS_JHC -fm4 -fno-prelude -fffi -funboxed-values #-}
module Jhc.Enum(Enum(..),Bounded(..)) where
-- Enumeration and Bounded classes
import Jhc.Basics
import Jhc.Inst.PrimEnum()
import Jhc.Int
m4_include(Jhc/Enum.m4)
class Enum a where
succ, pred :: a -> a
toEnum :: Int -> a
fromEnum :: a -> Int
enumFrom :: a -> [a] -- [n..]
enumFromThen :: a -> a -> [a] -- [n,n'..]
enumFromTo :: a -> a -> [a] -- [n..m]
enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m]
-- Minimal complete definition:
-- toEnum, fromEnum
--
-- NOTE: these default methods only make sense for types
-- that map injectively into Int using fromEnum
-- and toEnum.
succ = toEnum . increment . fromEnum
pred = toEnum . decrement . fromEnum
enumFrom x = map toEnum [fromEnum x ..]
enumFromTo x y = map toEnum [fromEnum x .. fromEnum y]
enumFromThen x y = map toEnum [fromEnum x, fromEnum y ..]
enumFromThenTo x y z =
map toEnum [fromEnum x, fromEnum y .. fromEnum z]
class Bounded a where
minBound :: a
maxBound :: a
instance Enum Int where
succ = increment
pred = decrement
toEnum x = x
fromEnum x = x
enumFrom x | x `seq` True = enumFromTo x maxBound
enumFromThen c c' = [c, c' .. lastInt]
where lastInt | c' `intLt` c = minBound
| otherwise = maxBound
enumFromTo x y = f x where
f x | x `intGt` y = []
| otherwise = x:f (increment x)
enumFromThenTo x y z | y `intGte` x = f x where
inc = y `minus` x
f x | x `intLte` z = x:f (x `plus` inc)
| otherwise = []
enumFromThenTo x y z = f x where
inc = y `minus` x
f x | x `intGte` z = x:f (x `plus` inc)
| otherwise = []
foreign import primitive "box" boxBool :: Bool_ -> Bool
foreign import primitive "Gte" intGte' :: Int -> Int -> Bool_
foreign import primitive "Gt" intGt' :: Int -> Int -> Bool_
foreign import primitive "Lte" intLte' :: Int -> Int -> Bool_
foreign import primitive "Lt" intLt' :: Int -> Int -> Bool_
foreign import primitive "Lt" charLt' :: Char -> Char -> Bool_
intGte x y = boxBool (intGte' x y)
intGt x y = boxBool (intGt' x y)
intLte x y = boxBool (intLte' x y)
intLt x y = boxBool (intLt' x y)
charLt x y = boxBool (charLt' x y)
instance Enum Char where
toEnum = chr
fromEnum = ord
enumFrom c = [c .. maxBound::Char]
enumFromThen c c' = [c, c' .. lastChar]
where lastChar :: Char
lastChar | c' `charLt` c = minBound
| otherwise = maxBound
-- enumFromTo (Char x) (Char y) = f x where
-- f x = case x `bits32UGt` y of
-- 0# -> []
-- 1# -> Char x:f (bits32Increment x)
-- enumFromThenTo (Char x) (Char y) (Char z) =
-- case y `bits32Sub` x of
-- inc -> let f x = case x `bits32UGte` z of
-- 1# -> Char x:f (x `bits32Add` inc)
-- 0# -> []
-- in f x
deriving instance Enum Bool
deriving instance Enum Ordering
instance Bounded Bool where
minBound = False
maxBound = True
instance Bounded Ordering where
minBound = LT
maxBound = GT
instance Bounded () where
minBound = ()
maxBound = ()
instance Bounded Char where
minBound = Char 0#
maxBound = Char 0x10ffff#
BOUNDED(Int)
BOUNDED(Integer)
--foreign import primitive "UGt" bits32UGt :: Bits32_ -> Bits32_ -> Bool__
--foreign import primitive "UGte" bits32UGte :: Bits32_ -> Bits32_ -> Bool__
--foreign import primitive "increment" bits32Increment :: Bits32_ -> Bits32_
--foreign import primitive "Add" bits32Add :: Bits32_ -> Bits32_ -> Bits32_
--foreign import primitive "Sub" bits32Sub :: Bits32_ -> Bits32_ -> Bits32_
| hvr/jhc | lib/jhc/Jhc/Enum.hs | mit | 4,047 | 6 | 12 | 1,363 | 1,036 | 563 | 473 | -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="fr-FR">
<title>Regular Expression Tester</title>
<maps>
<homeID>regextester</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/regextester/src/main/javahelp/help_fr_FR/helpset_fr_FR.hs | apache-2.0 | 978 | 77 | 66 | 157 | 409 | 207 | 202 | -1 | -1 |
module Guards4In where
f x@(Left a) = case x of
(Left x)
| x == 1 -> Right x
| otherwise -> Left x
(Right b) -> Left b
| kmate/HaRe | old/testing/simplifyExpr/GuardsIn4.hs | bsd-3-clause | 209 | 0 | 11 | 119 | 77 | 37 | 40 | 6 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash, UnboxedTuples,
StandaloneDeriving, AutoDeriveTypeable, NegativeLiterals #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Int
-- Copyright : (c) The University of Glasgow 1997-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The sized integral datatypes, 'Int8', 'Int16', 'Int32', and 'Int64'.
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module GHC.Int (
Int8(..), Int16(..), Int32(..), Int64(..),
uncheckedIShiftL64#, uncheckedIShiftRA64#
) where
import Data.Bits
import Data.Maybe
#if WORD_SIZE_IN_BITS < 64
import GHC.IntWord64
#endif
import GHC.Base
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Read
import GHC.Arr
import GHC.Word hiding (uncheckedShiftL64#, uncheckedShiftRL64#)
import GHC.Show
import GHC.Float () -- for RealFrac methods
import Data.Typeable
------------------------------------------------------------------------
-- type Int8
------------------------------------------------------------------------
-- Int8 is represented in the same way as Int. Operations may assume
-- and must ensure that it holds only values from its logical range.
data {-# CTYPE "HsInt8" #-} Int8 = I8# Int# deriving (Eq, Ord, Typeable)
-- ^ 8-bit signed integer type
instance Show Int8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int8 where
(I8# x#) + (I8# y#) = I8# (narrow8Int# (x# +# y#))
(I8# x#) - (I8# y#) = I8# (narrow8Int# (x# -# y#))
(I8# x#) * (I8# y#) = I8# (narrow8Int# (x# *# y#))
negate (I8# x#) = I8# (narrow8Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger i = I8# (narrow8Int# (integerToInt i))
instance Real Int8 where
toRational x = toInteger x % 1
instance Enum Int8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int8"
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int8) && i <= fromIntegral (maxBound::Int8)
= I8# i#
| otherwise = toEnumError "Int8" i (minBound::Int8, maxBound::Int8)
fromEnum (I8# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int8 where
quot x@(I8# x#) y@(I8# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I8# (narrow8Int# (x# `quotInt#` y#))
rem (I8# x#) y@(I8# y#)
| y == 0 = divZeroError
| otherwise = I8# (narrow8Int# (x# `remInt#` y#))
div x@(I8# x#) y@(I8# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I8# (narrow8Int# (x# `divInt#` y#))
mod (I8# x#) y@(I8# y#)
| y == 0 = divZeroError
| otherwise = I8# (narrow8Int# (x# `modInt#` y#))
quotRem x@(I8# x#) y@(I8# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = case x# `quotRemInt#` y# of
(# q, r #) ->
(I8# (narrow8Int# q),
I8# (narrow8Int# r))
divMod x@(I8# x#) y@(I8# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = case x# `divModInt#` y# of
(# d, m #) ->
(I8# (narrow8Int# d),
I8# (narrow8Int# m))
toInteger (I8# x#) = smallInteger x#
instance Bounded Int8 where
minBound = -0x80
maxBound = 0x7F
instance Ix Int8 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral i - fromIntegral m
inRange (m,n) i = m <= i && i <= n
instance Read Int8 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int8 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(I8# x#) .&. (I8# y#) = I8# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I8# x#) .|. (I8# y#) = I8# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I8# x#) `xor` (I8# y#) = I8# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I8# x#) = I8# (word2Int# (not# (int2Word# x#)))
(I8# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = I8# (narrow8Int# (x# `iShiftL#` i#))
| otherwise = I8# (x# `iShiftRA#` negateInt# i#)
(I8# x#) `shiftL` (I# i#) = I8# (narrow8Int# (x# `iShiftL#` i#))
(I8# x#) `unsafeShiftL` (I# i#) = I8# (narrow8Int# (x# `uncheckedIShiftL#` i#))
(I8# x#) `shiftR` (I# i#) = I8# (x# `iShiftRA#` i#)
(I8# x#) `unsafeShiftR` (I# i#) = I8# (x# `uncheckedIShiftRA#` i#)
(I8# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#)
= I8# x#
| otherwise
= I8# (narrow8Int# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#`
(x'# `uncheckedShiftRL#` (8# -# i'#)))))
where
!x'# = narrow8Word# (int2Word# x#)
!i'# = word2Int# (int2Word# i# `and#` 7##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = True
popCount (I8# x#) = I# (word2Int# (popCnt8# (int2Word# x#)))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Int8 where
finiteBitSize _ = 8
{-# RULES
"fromIntegral/Int8->Int8" fromIntegral = id :: Int8 -> Int8
"fromIntegral/a->Int8" fromIntegral = \x -> case fromIntegral x of I# x# -> I8# (narrow8Int# x#)
"fromIntegral/Int8->a" fromIntegral = \(I8# x#) -> fromIntegral (I# x#)
#-}
{-# RULES
"properFraction/Float->(Int8,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Int8) n, y :: Float) }
"truncate/Float->Int8"
truncate = (fromIntegral :: Int -> Int8) . (truncate :: Float -> Int)
"floor/Float->Int8"
floor = (fromIntegral :: Int -> Int8) . (floor :: Float -> Int)
"ceiling/Float->Int8"
ceiling = (fromIntegral :: Int -> Int8) . (ceiling :: Float -> Int)
"round/Float->Int8"
round = (fromIntegral :: Int -> Int8) . (round :: Float -> Int)
#-}
{-# RULES
"properFraction/Double->(Int8,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Int8) n, y :: Double) }
"truncate/Double->Int8"
truncate = (fromIntegral :: Int -> Int8) . (truncate :: Double -> Int)
"floor/Double->Int8"
floor = (fromIntegral :: Int -> Int8) . (floor :: Double -> Int)
"ceiling/Double->Int8"
ceiling = (fromIntegral :: Int -> Int8) . (ceiling :: Double -> Int)
"round/Double->Int8"
round = (fromIntegral :: Int -> Int8) . (round :: Double -> Int)
#-}
------------------------------------------------------------------------
-- type Int16
------------------------------------------------------------------------
-- Int16 is represented in the same way as Int. Operations may assume
-- and must ensure that it holds only values from its logical range.
data {-# CTYPE "HsInt16" #-} Int16 = I16# Int# deriving (Eq, Ord, Typeable)
-- ^ 16-bit signed integer type
instance Show Int16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int16 where
(I16# x#) + (I16# y#) = I16# (narrow16Int# (x# +# y#))
(I16# x#) - (I16# y#) = I16# (narrow16Int# (x# -# y#))
(I16# x#) * (I16# y#) = I16# (narrow16Int# (x# *# y#))
negate (I16# x#) = I16# (narrow16Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger i = I16# (narrow16Int# (integerToInt i))
instance Real Int16 where
toRational x = toInteger x % 1
instance Enum Int16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int16"
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int16) && i <= fromIntegral (maxBound::Int16)
= I16# i#
| otherwise = toEnumError "Int16" i (minBound::Int16, maxBound::Int16)
fromEnum (I16# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int16 where
quot x@(I16# x#) y@(I16# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I16# (narrow16Int# (x# `quotInt#` y#))
rem (I16# x#) y@(I16# y#)
| y == 0 = divZeroError
| otherwise = I16# (narrow16Int# (x# `remInt#` y#))
div x@(I16# x#) y@(I16# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I16# (narrow16Int# (x# `divInt#` y#))
mod (I16# x#) y@(I16# y#)
| y == 0 = divZeroError
| otherwise = I16# (narrow16Int# (x# `modInt#` y#))
quotRem x@(I16# x#) y@(I16# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = case x# `quotRemInt#` y# of
(# q, r #) ->
(I16# (narrow16Int# q),
I16# (narrow16Int# r))
divMod x@(I16# x#) y@(I16# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = case x# `divModInt#` y# of
(# d, m #) ->
(I16# (narrow16Int# d),
I16# (narrow16Int# m))
toInteger (I16# x#) = smallInteger x#
instance Bounded Int16 where
minBound = -0x8000
maxBound = 0x7FFF
instance Ix Int16 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral i - fromIntegral m
inRange (m,n) i = m <= i && i <= n
instance Read Int16 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int16 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(I16# x#) .&. (I16# y#) = I16# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I16# x#) .|. (I16# y#) = I16# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I16# x#) `xor` (I16# y#) = I16# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I16# x#) = I16# (word2Int# (not# (int2Word# x#)))
(I16# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = I16# (narrow16Int# (x# `iShiftL#` i#))
| otherwise = I16# (x# `iShiftRA#` negateInt# i#)
(I16# x#) `shiftL` (I# i#) = I16# (narrow16Int# (x# `iShiftL#` i#))
(I16# x#) `unsafeShiftL` (I# i#) = I16# (narrow16Int# (x# `uncheckedIShiftL#` i#))
(I16# x#) `shiftR` (I# i#) = I16# (x# `iShiftRA#` i#)
(I16# x#) `unsafeShiftR` (I# i#) = I16# (x# `uncheckedIShiftRA#` i#)
(I16# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#)
= I16# x#
| otherwise
= I16# (narrow16Int# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#`
(x'# `uncheckedShiftRL#` (16# -# i'#)))))
where
!x'# = narrow16Word# (int2Word# x#)
!i'# = word2Int# (int2Word# i# `and#` 15##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = True
popCount (I16# x#) = I# (word2Int# (popCnt16# (int2Word# x#)))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Int16 where
finiteBitSize _ = 16
{-# RULES
"fromIntegral/Word8->Int16" fromIntegral = \(W8# x#) -> I16# (word2Int# x#)
"fromIntegral/Int8->Int16" fromIntegral = \(I8# x#) -> I16# x#
"fromIntegral/Int16->Int16" fromIntegral = id :: Int16 -> Int16
"fromIntegral/a->Int16" fromIntegral = \x -> case fromIntegral x of I# x# -> I16# (narrow16Int# x#)
"fromIntegral/Int16->a" fromIntegral = \(I16# x#) -> fromIntegral (I# x#)
#-}
{-# RULES
"properFraction/Float->(Int16,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Int16) n, y :: Float) }
"truncate/Float->Int16"
truncate = (fromIntegral :: Int -> Int16) . (truncate :: Float -> Int)
"floor/Float->Int16"
floor = (fromIntegral :: Int -> Int16) . (floor :: Float -> Int)
"ceiling/Float->Int16"
ceiling = (fromIntegral :: Int -> Int16) . (ceiling :: Float -> Int)
"round/Float->Int16"
round = (fromIntegral :: Int -> Int16) . (round :: Float -> Int)
#-}
{-# RULES
"properFraction/Double->(Int16,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Int16) n, y :: Double) }
"truncate/Double->Int16"
truncate = (fromIntegral :: Int -> Int16) . (truncate :: Double -> Int)
"floor/Double->Int16"
floor = (fromIntegral :: Int -> Int16) . (floor :: Double -> Int)
"ceiling/Double->Int16"
ceiling = (fromIntegral :: Int -> Int16) . (ceiling :: Double -> Int)
"round/Double->Int16"
round = (fromIntegral :: Int -> Int16) . (round :: Double -> Int)
#-}
------------------------------------------------------------------------
-- type Int32
------------------------------------------------------------------------
-- Int32 is represented in the same way as Int.
#if WORD_SIZE_IN_BITS > 32
-- Operations may assume and must ensure that it holds only values
-- from its logical range.
#endif
data {-# CTYPE "HsInt32" #-} Int32 = I32# Int# deriving (Eq, Ord, Typeable)
-- ^ 32-bit signed integer type
instance Show Int32 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int32 where
(I32# x#) + (I32# y#) = I32# (narrow32Int# (x# +# y#))
(I32# x#) - (I32# y#) = I32# (narrow32Int# (x# -# y#))
(I32# x#) * (I32# y#) = I32# (narrow32Int# (x# *# y#))
negate (I32# x#) = I32# (narrow32Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger i = I32# (narrow32Int# (integerToInt i))
instance Enum Int32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int32"
#if WORD_SIZE_IN_BITS == 32
toEnum (I# i#) = I32# i#
#else
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int32) && i <= fromIntegral (maxBound::Int32)
= I32# i#
| otherwise = toEnumError "Int32" i (minBound::Int32, maxBound::Int32)
#endif
fromEnum (I32# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int32 where
quot x@(I32# x#) y@(I32# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I32# (narrow32Int# (x# `quotInt#` y#))
rem (I32# x#) y@(I32# y#)
| y == 0 = divZeroError
-- The quotRem CPU instruction fails for minBound `quotRem` -1,
-- but minBound `rem` -1 is well-defined (0). We therefore
-- special-case it.
| y == (-1) = 0
| otherwise = I32# (narrow32Int# (x# `remInt#` y#))
div x@(I32# x#) y@(I32# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I32# (narrow32Int# (x# `divInt#` y#))
mod (I32# x#) y@(I32# y#)
| y == 0 = divZeroError
-- The divMod CPU instruction fails for minBound `divMod` -1,
-- but minBound `mod` -1 is well-defined (0). We therefore
-- special-case it.
| y == (-1) = 0
| otherwise = I32# (narrow32Int# (x# `modInt#` y#))
quotRem x@(I32# x#) y@(I32# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = case x# `quotRemInt#` y# of
(# q, r #) ->
(I32# (narrow32Int# q),
I32# (narrow32Int# r))
divMod x@(I32# x#) y@(I32# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = case x# `divModInt#` y# of
(# d, m #) ->
(I32# (narrow32Int# d),
I32# (narrow32Int# m))
toInteger (I32# x#) = smallInteger x#
instance Read Int32 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int32 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(I32# x#) .&. (I32# y#) = I32# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I32# x#) .|. (I32# y#) = I32# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I32# x#) `xor` (I32# y#) = I32# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I32# x#) = I32# (word2Int# (not# (int2Word# x#)))
(I32# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = I32# (narrow32Int# (x# `iShiftL#` i#))
| otherwise = I32# (x# `iShiftRA#` negateInt# i#)
(I32# x#) `shiftL` (I# i#) = I32# (narrow32Int# (x# `iShiftL#` i#))
(I32# x#) `unsafeShiftL` (I# i#) =
I32# (narrow32Int# (x# `uncheckedIShiftL#` i#))
(I32# x#) `shiftR` (I# i#) = I32# (x# `iShiftRA#` i#)
(I32# x#) `unsafeShiftR` (I# i#) = I32# (x# `uncheckedIShiftRA#` i#)
(I32# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#)
= I32# x#
| otherwise
= I32# (narrow32Int# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#`
(x'# `uncheckedShiftRL#` (32# -# i'#)))))
where
!x'# = narrow32Word# (int2Word# x#)
!i'# = word2Int# (int2Word# i# `and#` 31##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = True
popCount (I32# x#) = I# (word2Int# (popCnt32# (int2Word# x#)))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Int32 where
finiteBitSize _ = 32
{-# RULES
"fromIntegral/Word8->Int32" fromIntegral = \(W8# x#) -> I32# (word2Int# x#)
"fromIntegral/Word16->Int32" fromIntegral = \(W16# x#) -> I32# (word2Int# x#)
"fromIntegral/Int8->Int32" fromIntegral = \(I8# x#) -> I32# x#
"fromIntegral/Int16->Int32" fromIntegral = \(I16# x#) -> I32# x#
"fromIntegral/Int32->Int32" fromIntegral = id :: Int32 -> Int32
"fromIntegral/a->Int32" fromIntegral = \x -> case fromIntegral x of I# x# -> I32# (narrow32Int# x#)
"fromIntegral/Int32->a" fromIntegral = \(I32# x#) -> fromIntegral (I# x#)
#-}
{-# RULES
"properFraction/Float->(Int32,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Int32) n, y :: Float) }
"truncate/Float->Int32"
truncate = (fromIntegral :: Int -> Int32) . (truncate :: Float -> Int)
"floor/Float->Int32"
floor = (fromIntegral :: Int -> Int32) . (floor :: Float -> Int)
"ceiling/Float->Int32"
ceiling = (fromIntegral :: Int -> Int32) . (ceiling :: Float -> Int)
"round/Float->Int32"
round = (fromIntegral :: Int -> Int32) . (round :: Float -> Int)
#-}
{-# RULES
"properFraction/Double->(Int32,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Int32) n, y :: Double) }
"truncate/Double->Int32"
truncate = (fromIntegral :: Int -> Int32) . (truncate :: Double -> Int)
"floor/Double->Int32"
floor = (fromIntegral :: Int -> Int32) . (floor :: Double -> Int)
"ceiling/Double->Int32"
ceiling = (fromIntegral :: Int -> Int32) . (ceiling :: Double -> Int)
"round/Double->Int32"
round = (fromIntegral :: Int -> Int32) . (round :: Double -> Int)
#-}
instance Real Int32 where
toRational x = toInteger x % 1
instance Bounded Int32 where
minBound = -0x80000000
maxBound = 0x7FFFFFFF
instance Ix Int32 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral i - fromIntegral m
inRange (m,n) i = m <= i && i <= n
------------------------------------------------------------------------
-- type Int64
------------------------------------------------------------------------
#if WORD_SIZE_IN_BITS < 64
data {-# CTYPE "HsInt64" #-} Int64 = I64# Int64# deriving( Typeable )
-- ^ 64-bit signed integer type
instance Eq Int64 where
(I64# x#) == (I64# y#) = isTrue# (x# `eqInt64#` y#)
(I64# x#) /= (I64# y#) = isTrue# (x# `neInt64#` y#)
instance Ord Int64 where
(I64# x#) < (I64# y#) = isTrue# (x# `ltInt64#` y#)
(I64# x#) <= (I64# y#) = isTrue# (x# `leInt64#` y#)
(I64# x#) > (I64# y#) = isTrue# (x# `gtInt64#` y#)
(I64# x#) >= (I64# y#) = isTrue# (x# `geInt64#` y#)
instance Show Int64 where
showsPrec p x = showsPrec p (toInteger x)
instance Num Int64 where
(I64# x#) + (I64# y#) = I64# (x# `plusInt64#` y#)
(I64# x#) - (I64# y#) = I64# (x# `minusInt64#` y#)
(I64# x#) * (I64# y#) = I64# (x# `timesInt64#` y#)
negate (I64# x#) = I64# (negateInt64# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger i = I64# (integerToInt64 i)
instance Enum Int64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int64"
toEnum (I# i#) = I64# (intToInt64# i#)
fromEnum x@(I64# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= I# (int64ToInt# x#)
| otherwise = fromEnumError "Int64" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Int64 where
quot x@(I64# x#) y@(I64# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I64# (x# `quotInt64#` y#)
rem (I64# x#) y@(I64# y#)
| y == 0 = divZeroError
-- The quotRem CPU instruction fails for minBound `quotRem` -1,
-- but minBound `rem` -1 is well-defined (0). We therefore
-- special-case it.
| y == (-1) = 0
| otherwise = I64# (x# `remInt64#` y#)
div x@(I64# x#) y@(I64# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I64# (x# `divInt64#` y#)
mod (I64# x#) y@(I64# y#)
| y == 0 = divZeroError
-- The divMod CPU instruction fails for minBound `divMod` -1,
-- but minBound `mod` -1 is well-defined (0). We therefore
-- special-case it.
| y == (-1) = 0
| otherwise = I64# (x# `modInt64#` y#)
quotRem x@(I64# x#) y@(I64# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = (I64# (x# `quotInt64#` y#),
I64# (x# `remInt64#` y#))
divMod x@(I64# x#) y@(I64# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = (I64# (x# `divInt64#` y#),
I64# (x# `modInt64#` y#))
toInteger (I64# x) = int64ToInteger x
divInt64#, modInt64# :: Int64# -> Int64# -> Int64#
-- Define div in terms of quot, being careful to avoid overflow (#7233)
x# `divInt64#` y#
| isTrue# (x# `gtInt64#` zero) && isTrue# (y# `ltInt64#` zero)
= ((x# `minusInt64#` one) `quotInt64#` y#) `minusInt64#` one
| isTrue# (x# `ltInt64#` zero) && isTrue# (y# `gtInt64#` zero)
= ((x# `plusInt64#` one) `quotInt64#` y#) `minusInt64#` one
| otherwise
= x# `quotInt64#` y#
where
!zero = intToInt64# 0#
!one = intToInt64# 1#
x# `modInt64#` y#
| isTrue# (x# `gtInt64#` zero) && isTrue# (y# `ltInt64#` zero) ||
isTrue# (x# `ltInt64#` zero) && isTrue# (y# `gtInt64#` zero)
= if isTrue# (r# `neInt64#` zero) then r# `plusInt64#` y# else zero
| otherwise = r#
where
!zero = intToInt64# 0#
!r# = x# `remInt64#` y#
instance Read Int64 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
instance Bits Int64 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(I64# x#) .&. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `and64#` int64ToWord64# y#))
(I64# x#) .|. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `or64#` int64ToWord64# y#))
(I64# x#) `xor` (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `xor64#` int64ToWord64# y#))
complement (I64# x#) = I64# (word64ToInt64# (not64# (int64ToWord64# x#)))
(I64# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = I64# (x# `iShiftL64#` i#)
| otherwise = I64# (x# `iShiftRA64#` negateInt# i#)
(I64# x#) `shiftL` (I# i#) = I64# (x# `iShiftL64#` i#)
(I64# x#) `unsafeShiftL` (I# i#) = I64# (x# `uncheckedIShiftL64#` i#)
(I64# x#) `shiftR` (I# i#) = I64# (x# `iShiftRA64#` i#)
(I64# x#) `unsafeShiftR` (I# i#) = I64# (x# `uncheckedIShiftRA64#` i#)
(I64# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#)
= I64# x#
| otherwise
= I64# (word64ToInt64# ((x'# `uncheckedShiftL64#` i'#) `or64#`
(x'# `uncheckedShiftRL64#` (64# -# i'#))))
where
!x'# = int64ToWord64# x#
!i'# = word2Int# (int2Word# i# `and#` 63##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = True
popCount (I64# x#) =
I# (word2Int# (popCnt64# (int64ToWord64# x#)))
bit = bitDefault
testBit = testBitDefault
-- give the 64-bit shift operations the same treatment as the 32-bit
-- ones (see GHC.Base), namely we wrap them in tests to catch the
-- cases when we're shifting more than 64 bits to avoid unspecified
-- behaviour in the C shift operations.
iShiftL64#, iShiftRA64# :: Int64# -> Int# -> Int64#
a `iShiftL64#` b | isTrue# (b >=# 64#) = intToInt64# 0#
| otherwise = a `uncheckedIShiftL64#` b
a `iShiftRA64#` b | isTrue# (b >=# 64#) = if isTrue# (a `ltInt64#` (intToInt64# 0#))
then intToInt64# (-1#)
else intToInt64# 0#
| otherwise = a `uncheckedIShiftRA64#` b
{-# RULES
"fromIntegral/Int->Int64" fromIntegral = \(I# x#) -> I64# (intToInt64# x#)
"fromIntegral/Word->Int64" fromIntegral = \(W# x#) -> I64# (word64ToInt64# (wordToWord64# x#))
"fromIntegral/Word64->Int64" fromIntegral = \(W64# x#) -> I64# (word64ToInt64# x#)
"fromIntegral/Int64->Int" fromIntegral = \(I64# x#) -> I# (int64ToInt# x#)
"fromIntegral/Int64->Word" fromIntegral = \(I64# x#) -> W# (int2Word# (int64ToInt# x#))
"fromIntegral/Int64->Word64" fromIntegral = \(I64# x#) -> W64# (int64ToWord64# x#)
"fromIntegral/Int64->Int64" fromIntegral = id :: Int64 -> Int64
#-}
-- No RULES for RealFrac methods if Int is smaller than Int64, we can't
-- go through Int and whether going through Integer is faster is uncertain.
#else
-- Int64 is represented in the same way as Int.
-- Operations may assume and must ensure that it holds only values
-- from its logical range.
data {-# CTYPE "HsInt64" #-} Int64 = I64# Int# deriving (Eq, Ord, Typeable)
-- ^ 64-bit signed integer type
instance Show Int64 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int64 where
(I64# x#) + (I64# y#) = I64# (x# +# y#)
(I64# x#) - (I64# y#) = I64# (x# -# y#)
(I64# x#) * (I64# y#) = I64# (x# *# y#)
negate (I64# x#) = I64# (negateInt# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger i = I64# (integerToInt i)
instance Enum Int64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int64"
toEnum (I# i#) = I64# i#
fromEnum (I64# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int64 where
quot x@(I64# x#) y@(I64# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I64# (x# `quotInt#` y#)
rem (I64# x#) y@(I64# y#)
| y == 0 = divZeroError
-- The quotRem CPU instruction fails for minBound `quotRem` -1,
-- but minBound `rem` -1 is well-defined (0). We therefore
-- special-case it.
| y == (-1) = 0
| otherwise = I64# (x# `remInt#` y#)
div x@(I64# x#) y@(I64# y#)
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError -- Note [Order of tests]
| otherwise = I64# (x# `divInt#` y#)
mod (I64# x#) y@(I64# y#)
| y == 0 = divZeroError
-- The divMod CPU instruction fails for minBound `divMod` -1,
-- but minBound `mod` -1 is well-defined (0). We therefore
-- special-case it.
| y == (-1) = 0
| otherwise = I64# (x# `modInt#` y#)
quotRem x@(I64# x#) y@(I64# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = case x# `quotRemInt#` y# of
(# q, r #) ->
(I64# q, I64# r)
divMod x@(I64# x#) y@(I64# y#)
| y == 0 = divZeroError
-- Note [Order of tests]
| y == (-1) && x == minBound = (overflowError, 0)
| otherwise = case x# `divModInt#` y# of
(# d, m #) ->
(I64# d, I64# m)
toInteger (I64# x#) = smallInteger x#
instance Read Int64 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int64 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(I64# x#) .&. (I64# y#) = I64# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I64# x#) .|. (I64# y#) = I64# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I64# x#) `xor` (I64# y#) = I64# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I64# x#) = I64# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I64# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = I64# (x# `iShiftL#` i#)
| otherwise = I64# (x# `iShiftRA#` negateInt# i#)
(I64# x#) `shiftL` (I# i#) = I64# (x# `iShiftL#` i#)
(I64# x#) `unsafeShiftL` (I# i#) = I64# (x# `uncheckedIShiftL#` i#)
(I64# x#) `shiftR` (I# i#) = I64# (x# `iShiftRA#` i#)
(I64# x#) `unsafeShiftR` (I# i#) = I64# (x# `uncheckedIShiftRA#` i#)
(I64# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#)
= I64# x#
| otherwise
= I64# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#`
(x'# `uncheckedShiftRL#` (64# -# i'#))))
where
!x'# = int2Word# x#
!i'# = word2Int# (int2Word# i# `and#` 63##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = True
popCount (I64# x#) = I# (word2Int# (popCnt64# (int2Word# x#)))
bit = bitDefault
testBit = testBitDefault
{-# RULES
"fromIntegral/a->Int64" fromIntegral = \x -> case fromIntegral x of I# x# -> I64# x#
"fromIntegral/Int64->a" fromIntegral = \(I64# x#) -> fromIntegral (I# x#)
#-}
{-# RULES
"properFraction/Float->(Int64,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Int64) n, y :: Float) }
"truncate/Float->Int64"
truncate = (fromIntegral :: Int -> Int64) . (truncate :: Float -> Int)
"floor/Float->Int64"
floor = (fromIntegral :: Int -> Int64) . (floor :: Float -> Int)
"ceiling/Float->Int64"
ceiling = (fromIntegral :: Int -> Int64) . (ceiling :: Float -> Int)
"round/Float->Int64"
round = (fromIntegral :: Int -> Int64) . (round :: Float -> Int)
#-}
{-# RULES
"properFraction/Double->(Int64,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Int64) n, y :: Double) }
"truncate/Double->Int64"
truncate = (fromIntegral :: Int -> Int64) . (truncate :: Double -> Int)
"floor/Double->Int64"
floor = (fromIntegral :: Int -> Int64) . (floor :: Double -> Int)
"ceiling/Double->Int64"
ceiling = (fromIntegral :: Int -> Int64) . (ceiling :: Double -> Int)
"round/Double->Int64"
round = (fromIntegral :: Int -> Int64) . (round :: Double -> Int)
#-}
uncheckedIShiftL64# :: Int# -> Int# -> Int#
uncheckedIShiftL64# = uncheckedIShiftL#
uncheckedIShiftRA64# :: Int# -> Int# -> Int#
uncheckedIShiftRA64# = uncheckedIShiftRA#
#endif
instance FiniteBits Int64 where
finiteBitSize _ = 64
instance Real Int64 where
toRational x = toInteger x % 1
instance Bounded Int64 where
minBound = -0x8000000000000000
maxBound = 0x7FFFFFFFFFFFFFFF
instance Ix Int64 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral i - fromIntegral m
inRange (m,n) i = m <= i && i <= n
{-
Note [Order of tests]
Suppose we had a definition like:
quot x y
| y == 0 = divZeroError
| x == minBound && y == (-1) = overflowError
| otherwise = x `primQuot` y
Note in particular that the
x == minBound
test comes before the
y == (-1)
test.
this expands to something like:
case y of
0 -> divZeroError
_ -> case x of
-9223372036854775808 ->
case y of
-1 -> overflowError
_ -> x `primQuot` y
_ -> x `primQuot` y
Now if we have the call (x `quot` 2), and quot gets inlined, then we get:
case 2 of
0 -> divZeroError
_ -> case x of
-9223372036854775808 ->
case 2 of
-1 -> overflowError
_ -> x `primQuot` 2
_ -> x `primQuot` 2
which simplifies to:
case x of
-9223372036854775808 -> x `primQuot` 2
_ -> x `primQuot` 2
Now we have a case with two identical branches, which would be
eliminated (assuming it doesn't affect strictness, which it doesn't in
this case), leaving the desired:
x `primQuot` 2
except in the minBound branch we know what x is, and GHC cleverly does
the division at compile time, giving:
case x of
-9223372036854775808 -> -4611686018427387904
_ -> x `primQuot` 2
So instead we use a definition like:
quot x y
| y == 0 = divZeroError
| y == (-1) && x == minBound = overflowError
| otherwise = x `primQuot` y
which gives us:
case y of
0 -> divZeroError
-1 ->
case x of
-9223372036854775808 -> overflowError
_ -> x `primQuot` y
_ -> x `primQuot` y
for which our call (x `quot` 2) expands to:
case 2 of
0 -> divZeroError
-1 ->
case x of
-9223372036854775808 -> overflowError
_ -> x `primQuot` 2
_ -> x `primQuot` 2
which simplifies to:
x `primQuot` 2
as required.
But we now have the same problem with a constant numerator: the call
(2 `quot` y) expands to
case y of
0 -> divZeroError
-1 ->
case 2 of
-9223372036854775808 -> overflowError
_ -> 2 `primQuot` y
_ -> 2 `primQuot` y
which simplifies to:
case y of
0 -> divZeroError
-1 -> 2 `primQuot` y
_ -> 2 `primQuot` y
which simplifies to:
case y of
0 -> divZeroError
-1 -> -2
_ -> 2 `primQuot` y
However, constant denominators are more common than constant numerators,
so the
y == (-1) && x == minBound
order gives us better code in the common case.
-}
| tibbe/ghc | libraries/base/GHC/Int.hs | bsd-3-clause | 39,413 | 4 | 17 | 13,284 | 8,464 | 4,369 | 4,095 | 560 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Yesod.Form.I18n.Portuguese where
import Yesod.Form.Types (FormMessage (..))
import Data.Monoid (mappend)
import Data.Text (Text)
portugueseFormMessage :: FormMessage -> Text
portugueseFormMessage (MsgInvalidInteger t) = "Número inteiro inválido: " `mappend` t
portugueseFormMessage (MsgInvalidNumber t) = "Número inválido: " `mappend` t
portugueseFormMessage (MsgInvalidEntry t) = "Entrada inválida: " `mappend` t
portugueseFormMessage MsgInvalidTimeFormat = "Hora inválida, deve estar no formato HH:MM[:SS]"
portugueseFormMessage MsgInvalidDay = "Data inválida, deve estar no formado AAAA-MM-DD"
portugueseFormMessage (MsgInvalidUrl t) = "URL inválida: " `mappend` t
portugueseFormMessage (MsgInvalidEmail t) = "Endereço de e-mail inválido: " `mappend` t
portugueseFormMessage (MsgInvalidHour t) = "Hora inválida: " `mappend` t
portugueseFormMessage (MsgInvalidMinute t) = "Minutos inválidos: " `mappend` t
portugueseFormMessage (MsgInvalidSecond t) = "Segundos inválidos: " `mappend` t
portugueseFormMessage MsgCsrfWarning = "Como uma proteção contra ataques CSRF, por favor confirme a submissão do seu formulário."
portugueseFormMessage MsgValueRequired = "Preenchimento obrigatório"
portugueseFormMessage (MsgInputNotFound t) = "Entrada não encontrada: " `mappend` t
portugueseFormMessage MsgSelectNone = "<Nenhum>"
portugueseFormMessage (MsgInvalidBool t) = "Booleano inválido: " `mappend` t
portugueseFormMessage MsgBoolYes = "Sim"
portugueseFormMessage MsgBoolNo = "Não"
portugueseFormMessage MsgDelete = "Remover?"
| ygale/yesod | yesod-form/Yesod/Form/I18n/Portuguese.hs | mit | 1,588 | 0 | 7 | 176 | 317 | 176 | 141 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
------------------------------------------------------------------------
-- |
-- Module : Yeast.Parse
-- Copyright : (c) 2015-2016 Stevan Andjelkovic
-- License : ISC (see the file LICENSE)
-- Maintainer : Stevan Andjelkovic
-- Stability : experimental
-- Portability : non-portable
--
-- This module contains functions for parsing news feeds.
--
------------------------------------------------------------------------
module Yeast.Parse (
-- * Parsing
-- $ parsing
parseFile
, parseLBS
, parseText
-- * Parse errors
-- $errors
, ParseError(..)
)
where
import Control.Applicative ((<|>))
import Control.DeepSeq (deepseq)
import Control.Exception (SomeException)
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as LBS
import Data.Monoid ((<>))
import qualified Data.Text as T
import Data.Text.Lazy (Text)
import Data.Text.Lazy.Encoding (decodeLatin1, decodeUtf8')
import qualified Text.XML as XML
import Text.XML.Lens (Document, Element,
(^?), (^..), (&), (.~), (%~),
(./), root, el, ell, entire,
text, localName, attributeIs,
attr, to, mapped, bimap)
import Yeast.Feed
------------------------------------------------------------------------
-- $parsing
-- Feeds can be parsed from different sources.
-- | Parse feed from file.
parseFile :: FilePath -> IO (Either ParseError Feed)
parseFile fp = parseLBS <$> LBS.readFile fp
-- | Parse feed from (lazy) byte string.
parseLBS :: ByteString -> Either ParseError Feed
parseLBS bs =
parseText $ either (const (decodeLatin1 bs)) id (decodeUtf8' bs)
-- | Parse feed from (lazy) text.
parseText :: Text -> Either ParseError Feed
parseText txt = do
doc <- bimap XMLConduitError id $ XML.parseText XML.def txt
k <- parseKind doc
deepseq doc $ return $ fromXML doc k
where
parseKind :: Document -> Either ParseError FeedKind
parseKind doc = case doc^?root.localName of
Just "RDF" -> return RSS1Kind
Just "rss" -> return RSS2Kind
Just "feed" -> return AtomKind
_ -> Left UnknownFeedKind
fromXML :: Document -> FeedKind -> Feed
fromXML doc k = emptyFeed k
& title .~ case k of
RSS1Kind -> doc^?root./ell "channel"./ell "title".text.to T.strip
RSS2Kind -> doc^?root./el "channel"./el "title".text.to T.strip
AtomKind -> doc^?root./ell "title".text.to T.strip
& feedHome .~ case k of
RSS1Kind -> Nothing
RSS2Kind -> Nothing
AtomKind -> doc^?root.ell "feed"./ell "link".
attributeIs "type" "application/atom+xml".
attr "href".to T.strip
& feedHtml .~ case k of
RSS1Kind -> doc^?root./ell "channel"./ell "link".text.to T.strip
RSS2Kind -> doc^?root./ell "channel"./ell "link".text.to T.strip
AtomKind -> doc^?root.ell "feed"./ell "link".
attributeIs "type" "text/html".attr "href".to T.strip
& description .~ case k of
RSS1Kind -> doc^?root.entire.ell "channel"./
ell "description".text.to T.strip
RSS2Kind -> doc^?root.entire.ell "channel"./
ell "description".text.to T.strip
AtomKind -> doc^?root.entire.ell "subtitle".text.to T.strip
& date .~ case k of
RSS1Kind -> doc^?root.entire./ell "date".text.to T.strip
RSS2Kind -> Nothing
AtomKind -> doc^?root.entire.ell "updated".text.to T.strip
& items .~ case k of
RSS1Kind -> doc^..root./ell "item" & mapped %~ parseItem
RSS2Kind ->
doc^..root./el "channel"./el "item" & mapped %~ parseItem
AtomKind -> doc^..root./ell "entry" & mapped %~ parseItem
where
parseItem :: Element -> Item
parseItem e = emptyItem
& title .~ case k of
RSS1Kind -> e^?entire.ell "title".text.to T.strip
RSS2Kind -> e^?entire.el "title".text.to T.strip
AtomKind -> e^?entire.ell "title".text.to T.strip
& link .~ case k of
RSS1Kind -> e^?entire.ell "link".text.to T.strip
RSS2Kind -> e^?entire.el "link".text.to T.strip
AtomKind -> e^?entire.ell "link".attr "href".to T.strip
& date .~ case k of
RSS1Kind -> Nothing
RSS2Kind -> e^?entire.el "pubDate".text
AtomKind -> e^?entire.ell "published".text <|>
e^?entire.ell "updated".text
& author .~ case k of
RSS1Kind -> e^?entire.ell "creator".text.to T.strip
RSS2Kind -> e^?entire.el "author".text.to T.strip
AtomKind -> e^?entire.ell "author"./ell "name".text.to T.strip
& description .~ case k of
RSS1Kind -> e^?entire.ell "description".text.to T.strip
RSS2Kind -> e^?entire.el "description".text.to T.strip
AtomKind -> e^?entire.ell "summary".text.to T.strip <>
e^?entire.ell "content".text.to T.strip
------------------------------------------------------------------------
-- $errors
-- Sometimes errors occur when we parse.
-- | Datatype that captures all ways parsing can fail.
data ParseError
= UnknownFeedKind
-- ^ The feed does not appear to be of RSS1, RSS2, nor Atom kind.
| XMLConduitError SomeException
-- ^ An error occured in the underlying parser, 'XML.parseText'
-- from "Text.XML".
deriving Show
| stevana/yeast | src/Yeast/Parse.hs | isc | 5,803 | 0 | 24 | 1,684 | 1,518 | 785 | 733 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}
import Data.List
import Data.Char
import Numeric (readHex)
import qualified Data.Map as Map
import qualified Data.Text as T
import System.Environment (getArgs)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.UTF8 as BSLU
import Codec.Compression.GZip
import Data.Binary (encode, decode)
import Debug.Trace
data FFE = Range Int Int | CID Int
deriving (Show)
data FFC = Uni Char | Variation [Char] | Dup Char Int | Vert Char | Hw Char | NOTDEF
deriving (Show)
main :: IO ()
main = do
(f:fs) <- getArgs
cont <- readFile f
let ffmap = tail $ lines cont
expanded = nub $ concatMap (fromFF . expandEntry ffmap) ffmap
BSL.putStr $ compress . encode $ Map.fromList $ expanded ++ redundantKana expanded
return ()
fromFF :: (FFE, FFC) -> [(Int, BSLU.ByteString)]
fromFF (Range begin end, Uni code) = zipWith
(\cid unicode -> (cid, textize $ chr unicode))
[begin..end] [(ord code)..]
fromFF (Range _ _, _) = error ""
fromFF (CID cid, Variation vs) = map (\v -> (cid, textize v)) vs
fromFF (CID cid, NOTDEF) = [(cid, BSLU.fromString "[NOTDEF]")]
fromFF (CID cid, a) = [(cid, textize $ fromFFC a)]
textize chrcode = BSLU.fromString [chrcode]
fromFFC :: FFC -> Char
fromFFC (Uni code) = code
fromFFC (Variation vs) = head vs
fromFFC (Dup code i) = code
fromFFC (Vert code) = code
fromFFC (Hw code) = code
-- | Expand FontForge .cidmap entry
--
-- Examples:
--
-- >>> expandEntry [] "62..63 005d"
-- (Range 62 63,Uni ']')
--
-- >>> expandEntry [] "0 /.notdef"
-- (CID 0,NOTDEF)
--
-- >>> expandEntry [] "1 0020,00a0"
-- (CID 1,Variation "\160 ")
--
-- >>> expandEntry [] "124 /uni2026.dup1"
-- (CID 124,Dup '\8230' 1)
--
-- >>> expandEntry ["646 ff40"] "390 /Japan1.646.hw"
-- (CID 390,Hw '\65344')
expandEntry :: [String] -> String -> (FFE, FFC)
expandEntry ffmap s = let (cids, val) = break (==' ') s
ffe = if ".." `isInfixOf` cids
then mkrange
(takeWhile isDigit cids) $
(dropWhile (=='.') . dropWhile isDigit) cids
else CID (read cids :: Int)
ffc = readFFValue ffmap $ dropWhile (==' ') val
in (ffe, ffc)
where mkrange s s' = Range (read s :: Int) (read s' :: Int)
readFFValue ffmap s
| "/uni" `isPrefixOf` s && "dup1" `isSuffixOf` s = Dup (unicode s) 1
| "/uni" `isPrefixOf` s && "dup2" `isSuffixOf` s = Dup (unicode s) 2
| "/uni" `isPrefixOf` s && "vert" `isSuffixOf` s = Vert (unicode s)
| "/uni" `isPrefixOf` s && "hw" `isSuffixOf` s = Hw (unicode s)
| "/uni" `isPrefixOf` s = Uni (unicode s)
| "/Japan1" `isPrefixOf` s && "vert" `isSuffixOf` s = Vert (jpncode s)
| "/Japan1" `isPrefixOf` s && "hw" `isSuffixOf` s = Hw (jpncode s)
| "/Japan1" `isPrefixOf` s = Uni (jpncode s)
| "," `isInfixOf` s = let (a,b) = break (==',') s
in Variation [hexcode (dropWhile (==',') b), hexcode a]
| "/.notdef" == s = NOTDEF
| otherwise = Uni (hexcode s)
where cidcode s = case find ((s++" ") `isPrefixOf`) ffmap of
Just e -> (fromFFC . snd) $ expandEntry [] e
Nothing -> ' ' -- error $ "No CID code for "++s
hexcode = chr . fst . head . readHex
unicode = hexcode . takeWhile isHexDigit . (\\ "/uni")
jpncode = cidcode . takeWhile isDigit . (\\ "/Japan1.")
fromKana :: [(Int, BSLU.ByteString)] -> (Int, [Int]) -> [(Int, BSLU.ByteString)]
fromKana expandedMap (maybeExist, cs) = nub $ map (\c -> (c, extraKana expandedMap maybeExist)) cs
extraKana emap v = case lookup v emap of
Just c -> c
Nothing -> "????"
redundantKana expandedMap = concatMap (fromKana expandedMap)
-- exerpt from https://gist.github.com/zr-tex8r/527b977dec4165934d31
[ (651, [651,12362,12545,12649,12649])
, (652, [652,12363,12546,12650,12650])
, (653, [653,12273,12456,12651,12651])
, (654, [654,12274,12457,12652,12652])
, (660, [7891,12364,12547,12867,12868])
, (842, [7918,12275,12458,12671,12757])
, (843, [843,12276,12459,12672,12672])
, (844, [7919,12277,12460,12673,12758])
, (845, [845,12278,12461,12674,12674])
, (846, [7920,12279,12462,12675,12759])
, (847, [847,12280,12463,12676,12676])
, (848, [7921,12281,12464,12677,12760])
, (849, [849,12282,12465,12678,12678])
, (850, [7922,12283,12466,12679,12761])
, (851, [851,12284,12467,12680,12680])
, (852, [852,12286,12469,12681,12681])
, (853, [853,12287,12470,12683,12683])
, (854, [854,12288,12471,12684,12684])
, (855, [855,12289,12472,12685,12685])
, (856, [856,12290,12473,12686,12686])
, (857, [857,12291,12474,12687,12687])
, (858, [858,12293,12476,12688,12688])
, (859, [859,12294,12477,12690,12690])
, (860, [860,12296,12479,12691,12691])
, (861, [861,12297,12480,12692,12692])
, (862, [862,12298,12481,12693,12693])
, (863, [863,12299,12482,12694,12694])
, (864, [864,12300,12483,12695,12695])
, (865, [865,12301,12484,12696,12696])
, (866, [866,12302,12485,12697,12697])
, (867, [867,12303,12486,12698,12698])
, (868, [868,12304,12487,12699,12699])
, (869, [869,12305,12488,12700,12700])
, (870, [870,12306,12489,12701,12701])
, (871, [871,12307,12490,12702,12702])
, (872, [872,12308,12491,12703,12703])
, (873, [873,12309,12492,12704,12704])
, (874, [874,12310,12493,12705,12705])
, (875, [875,12311,12494,12706,12706])
, (876, [7923,12312,12495,12707,12764])
, (877, [877,12313,12496,12708,12708])
, (878, [878,12314,12497,12709,12709])
, (879, [879,12315,12498,12710,12710])
, (880, [880,12316,12499,12711,12711])
, (881, [881,12317,12500,12712,12712])
, (882, [882,12318,12501,12713,12713])
, (883, [883,12319,12502,12714,12714])
, (884, [884,12320,12503,12715,12715])
, (885, [885,12321,12504,12716,12716])
, (886, [886,12322,12505,12717,12717])
, (887, [887,12323,12506,12718,12718])
, (888, [888,12324,12507,12719,12719])
, (889, [889,12325,12508,12720,12720])
, (890, [890,12326,12509,12721,12721])
, (891, [891,12327,12510,12722,12722])
, (892, [892,12328,12511,12723,12723])
, (893, [893,12329,12512,12724,12724])
, (894, [894,12330,12513,12725,12725])
, (895, [895,12331,12514,12726,12726])
, (896, [896,12332,12515,12727,12727])
, (897, [897,12333,12516,12728,12728])
, (898, [898,12334,12517,12729,12729])
, (899, [899,12335,12518,12730,12730])
, (900, [900,12336,12519,12731,12731])
, (901, [901,12337,12520,12732,12732])
, (902, [902,12338,12521,12733,12733])
, (903, [903,12339,12522,12734,12734])
, (904, [904,12340,12523,12735,12735])
, (905, [905,12341,12524,12736,12736])
, (906, [906,12342,12525,12737,12737])
, (907, [907,12343,12526,12738,12738])
, (908, [7924,12344,12527,12739,12765])
, (909, [909,12345,12528,12740,12740])
, (910, [7925,12346,12529,12741,12766])
, (911, [911,12347,12530,12742,12742])
, (912, [7926,12348,12531,12743,12767])
, (913, [913,12349,12532,12744,12744])
, (914, [914,12350,12533,12745,12745])
, (915, [915,12351,12534,12746,12746])
, (916, [916,12352,12535,12747,12747])
, (917, [917,12353,12536,12748,12748])
, (918, [918,12354,12537,12749,12749])
, (919, [7927,12355,12538,12750,12768])
, (920, [920,12356,12539,12751,12751])
, (921, [921,12357,12540,12752,12752])
, (922, [922,12358,12541,12753,12753])
, (923, [923,12359,12542,12754,12754])
, (924, [924,12360,12543,12755,12755])
, (7958, [7958,12361,12544,12756,12756])
, (7959, [8264,12285,12468,12682,12762])
, (7960, [8265,12292,12475,12689,12763])
, (16209, [16209,16352,16382,16414,16414])
, (16210, [16210,16353,16383,16415,16415])
, (16211, [16211,16354,16384,16416,16416])
, (16212, [16212,16355,16385,16417,16417])
, (16213, [16213,16356,16386,16418,16418])
, (925, [7928,12365,12548,12769,12855])
, (926, [926,12366,12549,12770,12770])
, (927, [7929,12367,12550,12771,12856])
, (928, [928,12368,12551,12772,12772])
, (929, [7930,12369,12552,12773,12857])
, (930, [930,12370,12553,12774,12774])
, (931, [7931,12371,12554,12775,12858])
, (932, [932,12372,12555,12776,12776])
, (933, [7932,12373,12556,12777,12859])
, (934, [934,12374,12557,12778,12778])
, (935, [935,12376,12559,12779,12779])
, (936, [936,12377,12560,12781,12781])
, (937, [937,12378,12561,12782,12782])
, (938, [938,12379,12562,12783,12783])
, (939, [939,12380,12563,12784,12784])
, (940, [940,12381,12564,12785,12785])
, (941, [941,12383,12566,12786,12786])
, (942, [942,12384,12567,12788,12788])
, (943, [943,12386,12569,12789,12789])
, (944, [944,12387,12570,12790,12790])
, (945, [945,12388,12571,12791,12791])
, (946, [946,12389,12572,12792,12792])
, (947, [947,12390,12573,12793,12793])
, (948, [948,12391,12574,12794,12794])
, (949, [949,12392,12575,12795,12795])
, (950, [950,12393,12576,12796,12796])
, (951, [951,12394,12577,12797,12797])
, (952, [952,12395,12578,12798,12798])
, (953, [953,12396,12579,12799,12799])
, (954, [954,12397,12580,12800,12800])
, (955, [955,12398,12581,12801,12801])
, (956, [956,12399,12582,12802,12802])
, (957, [957,12400,12583,12803,12803])
, (958, [958,12401,12584,12804,12804])
, (959, [7933,12402,12585,12805,12862])
, (960, [960,12403,12586,12806,12806])
, (961, [961,12404,12587,12807,12807])
, (962, [962,12405,12588,12808,12808])
, (963, [963,12406,12589,12809,12809])
, (964, [964,12407,12590,12810,12810])
, (965, [965,12408,12591,12811,12811])
, (966, [966,12409,12592,12812,12812])
, (967, [967,12410,12593,12813,12813])
, (968, [968,12411,12594,12814,12814])
, (969, [969,12412,12595,12815,12815])
, (970, [970,12413,12596,12816,12816])
, (971, [971,12414,12597,12817,12817])
, (972, [972,12415,12598,12818,12818])
, (973, [973,12416,12599,12819,12819])
, (974, [974,12417,12600,12820,12820])
, (975, [975,12418,12601,12821,12821])
, (976, [976,12419,12602,12822,12822])
, (977, [977,12420,12603,12823,12823])
, (978, [978,12421,12604,12824,12824])
, (979, [979,12422,12605,12825,12825])
, (980, [980,12423,12606,12826,12826])
, (981, [981,12424,12607,12827,12827])
, (982, [982,12425,12608,12828,12828])
, (983, [983,12426,12609,12829,12829])
, (984, [984,12427,12610,12830,12830])
, (985, [985,12428,12611,12831,12831])
, (986, [986,12429,12612,12832,12832])
, (987, [987,12430,12613,12833,12833])
, (988, [988,12431,12614,12834,12834])
, (989, [989,12432,12615,12835,12835])
, (990, [990,12433,12616,12836,12836])
, (991, [7934,12434,12617,12837,12863])
, (992, [992,12435,12618,12838,12838])
, (993, [7935,12436,12619,12839,12864])
, (994, [994,12437,12620,12840,12840])
, (995, [7936,12438,12621,12841,12865])
, (996, [996,12439,12622,12842,12842])
, (997, [997,12440,12623,12843,12843])
, (998, [998,12441,12624,12844,12844])
, (999, [999,12442,12625,12845,12845])
, (1000, [1000,12443,12626,12846,12846])
, (1001, [1001,12444,12627,12847,12847])
, (1002, [7937,12445,12628,12848,12866])
, (1003, [1003,12446,12629,12849,12849])
, (1004, [1004,12447,12630,12850,12850])
, (1005, [1005,12448,12631,12851,12851])
, (1006, [1006,12449,12632,12852,12852])
, (1007, [1007,12450,12633,12853,12853])
, (1008, [1008,12451,12634,12854,12854])
, (1009, [7938,12375,12558,12780,12860])
, (1010, [7939,12382,12565,12787,12861])
, (16214, [16214,16357,16387,16419,16419])
, (16215, [16215,16358,16388,16420,16420])
, (16216, [16216,16359,16389,16421,16421])
, (16217, [16217,16360,16390,16422,16422])
, (16218, [16218,16361,16391,16423,16423])
, (16219, [16219,16362,16392,16424,16424])
, (16220, [16220,16363,16393,16425,16425])
, (16221, [16221,16364,16394,16426,16426])
, (16236, [16333,16365,16395,16427,16450])
, (16237, [16334,16366,16396,16428,16451])
, (16238, [16335,16367,16397,16429,16452])
, (16239, [16336,16368,16398,16430,16453])
, (16240, [16337,16369,16399,16431,16454])
, (16241, [16338,16370,16400,16432,16455])
, (16242, [16339,16371,16401,16433,16456])
, (16243, [16340,16372,16402,16434,16457])
, (16244, [16341,16373,16403,16435,16458])
, (16245, [16342,16374,16404,16436,16459])
, (16246, [16343,16375,16405,16437,16460])
, (16247, [16344,16376,16406,16438,16461])
, (16248, [16345,16377,16407,16439,16462])
, (16249, [16346,16378,16408,16440,16463])
, (16250, [16347,16379,16409,16441,16464])
, (16251, [16348,16380,16410,16442,16465])
, (16252, [16349,16381,16411,16443,16466])
, (8313, [8313,12452,12635,16444,16444])
, (8314, [8314,12453,12636,16445,16445])
, (8315, [8315,12454,12637,16446,16446])
, (8316, [8316,12455,12638,16447,16447])
] | k16shikano/hpdft | data/map/cidmapToList.hs | mit | 12,822 | 0 | 15 | 2,141 | 6,490 | 4,147 | 2,343 | 285 | 2 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.SVGTransformList (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.SVGTransformList
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.SVGTransformList
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/SVGTransformList.hs | mit | 361 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
{-# LANGUAGE FlexibleInstances #-}
module Pianola.Geometry (
Interval,
Point1d,
inside1d,
before1d,
after1d,
Point2d,
Dimensions2d,
mid,
Geometrical (..),
sameLevelRightOf
) where
import Prelude hiding (catch,(.),id)
import Control.Category
import Control.Comonad
type Interval = (Int,Int)
type Point1d = Int
inside1d :: Interval -> Point1d -> Bool
inside1d (x1,x2) u = x1 <= u && u <= x2
before1d :: Interval -> Point1d -> Bool
before1d (x1,_) x = x <= x1
after1d :: Interval -> Point1d -> Bool
after1d (_,x2) x = x2 <= x
-- | (x,y)
type Point2d = (Int,Int)
-- | (width,height)
type Dimensions2d = (Int,Int)
mid :: Interval -> Point1d
mid (x1,x2) = div (x1+x2) 2
-- | Class of objects with rectangular shape and located in a two-dimensional
-- plane.
class Geometrical g where
-- | Position of the north-west corner.
nwcorner :: g -> Point2d
dimensions :: g -> Dimensions2d
width :: g -> Int
width = fst . dimensions
height :: g -> Int
height = snd . dimensions
minX :: g -> Int
minX = fst . nwcorner
midX :: g -> Int
midX = mid . yband
minY :: g -> Int
minY = snd . nwcorner
midY :: g -> Int
midY = mid . yband
xband :: g -> Interval
xband g =
let gminX = minX g
in (gminX, gminX + (fst . dimensions) g)
yband :: g -> Interval
yband g =
let gminY = minY g
in (gminY, gminY + (snd . dimensions) g)
area :: g -> Int
area g = width g * height g
midpoint :: g -> Point2d
midpoint g = (midX g, midY g)
instance (Comonad c, Geometrical g) => Geometrical (c g) where
nwcorner = nwcorner . extract
dimensions = dimensions . extract
-- | True if the second object is roughly at the same height and to the right
-- of the first object.
sameLevelRightOf :: (Geometrical g1, Geometrical g2) => g1 -> g2 -> Bool
sameLevelRightOf ref c =
inside1d (yband c) (midY ref) && after1d (xband ref) (minX c)
| danidiaz/pianola | src/Pianola/Geometry.hs | mit | 2,049 | 0 | 13 | 600 | 677 | 376 | 301 | 60 | 1 |
module Main where
import Language.Haskell.Exts
import Language.Haskell.Exts.GenericPretty.Instances
import Shared
import System.Environment
import System.IO
uglyPrintHs :: String -> IO ()
uglyPrintHs path = do
result <- parseFileWithMode myParseMode path
case result of
ParseOk ast -> putStrLn $ show ast
ParseFailed srcLoc err -> putStrLn $ show err
main :: IO ()
main = do
argv <- getArgs
case argv of
[path] -> uglyPrintHs path
_ -> putStrLn "usage: pretty-ast <file.hs>"
| adarqui/haskell-src-exts-genericpretty | examples/ugly-ast.hs | mit | 568 | 0 | 11 | 162 | 156 | 79 | 77 | 18 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE AutoDeriveTypeable #-}
{-# LANGUAGE ViewPatterns #-}
module Graphics.UI.GroupBox
( createGroupBox
, groupBoxAlignment
, flat
, checked
, checkable
, GroupBox() )
where
import Graphics.UI.Internal.Common
import Graphics.UI.UIVar
import Graphics.UI.Widget
foreign import ccall create_groupbox :: FunPtr (CInt -> IO ())
-> IO (Ptr QGroupBox)
foreign import ccall set_groupbox_title :: Ptr QGroupBox -> Ptr QString -> IO ()
foreign import ccall get_groupbox_title :: Ptr QGroupBox -> IO (Ptr QString)
foreign import ccall set_groupbox_flat :: Ptr QGroupBox -> CInt -> IO ()
foreign import ccall get_groupbox_flat :: Ptr QGroupBox -> IO CInt
foreign import ccall set_groupbox_checked :: Ptr QGroupBox -> CInt -> IO ()
foreign import ccall get_groupbox_checked :: Ptr QGroupBox -> IO CInt
foreign import ccall set_groupbox_checkable :: Ptr QGroupBox -> CInt -> IO ()
foreign import ccall get_groupbox_checkable :: Ptr QGroupBox -> IO CInt
foreign import ccall set_groupbox_alignment :: Ptr QGroupBox -> CInt -> IO ()
foreign import ccall get_groupbox_alignment :: Ptr QGroupBox -> IO CInt
foreign import ccall "wrapper" wrapToggled
:: (CInt -> IO ()) -> IO (FunPtr (CInt -> IO ()))
newtype GroupBox = GroupBox (ManagedQObject QGroupBox)
deriving ( Eq, Typeable, Touchable, HasQObject )
instance CentralWidgetable GroupBox
instance Titleable GroupBox where
setTitle _ p = set_groupbox_title (castPtr p)
getTitle _ p = get_groupbox_title (castPtr p)
instance IsWidget GroupBox where
getWidget = coerceManagedQObject . getManagedQObject
instance HasManagedQObject GroupBox QGroupBox where
getManagedQObject (GroupBox man) = man
createGroupBox :: (Bool -> UIAction ()) -> UIAction GroupBox
createGroupBox event = liftIO $ mask_ $ do
wrapped <- wrapToggled $ \b -> let UIAction action =
event (if b /= 0
then True
else False)
in insulateExceptions action
GroupBox <$> (manageQObject =<<
createTrackedQObject =<<
create_groupbox wrapped)
data GroupBoxAlignment
= GBAlignLeft
| GBAlignRight
| GBAlignHCenter
deriving ( Eq, Ord, Show, Read, Typeable, Enum )
toConstantG :: GroupBoxAlignment -> CInt
toConstantG GBAlignLeft = 0x1
toConstantG GBAlignRight = 0x2
toConstantG GBAlignHCenter = 0x4
fromConstantG :: CInt -> GroupBoxAlignment
fromConstantG 0x1 = GBAlignLeft
fromConstantG 0x2 = GBAlignRight
fromConstantG 0x4 = GBAlignHCenter
fromConstantG _ = error "fromConstantG: invalid value."
groupBoxAlignment :: GroupBox -> UIVar' GroupBoxAlignment
groupBoxAlignment gb = uivar set_it get_it
where
set_it (toConstantG -> c) = liftIO $
withManagedQObject gb $ \gb_ptr ->
set_groupbox_alignment gb_ptr c
get_it = liftIO $ withManagedQObject gb $ \gb_ptr ->
fromConstantG <$> get_groupbox_alignment gb_ptr
flat :: GroupBox -> UIVar' Bool
flat gb = uivar set_it get_it
where
set_it s = liftIO $
withManagedQObject gb $ \gb_ptr ->
set_groupbox_flat gb_ptr (if s then 1 else 0)
get_it = liftIO $
withManagedQObject gb $ \gb_ptr -> do
r <- get_groupbox_flat gb_ptr
return $ if r /= 0 then True else False
checked :: GroupBox -> UIVar' Bool
checked gb = uivar set_it get_it
where
set_it s = liftIO $
withManagedQObject gb $ \gb_ptr ->
set_groupbox_checked gb_ptr (if s then 1 else 0)
get_it = liftIO $
withManagedQObject gb $ \gb_ptr -> do
r <- get_groupbox_checked gb_ptr
return $ if r /= 0 then True else False
checkable :: GroupBox -> UIVar' Bool
checkable gb = uivar set_it get_it
where
set_it s = liftIO $
withManagedQObject gb $ \gb_ptr ->
set_groupbox_checkable gb_ptr (if s then 1 else 0)
get_it = liftIO $
withManagedQObject gb $ \gb_ptr -> do
r <- get_groupbox_checkable gb_ptr
return $ if r /= 0 then True else False
| Noeda/userinterface | src/Graphics/UI/GroupBox.hs | mit | 4,294 | 0 | 18 | 1,136 | 1,178 | 602 | 576 | 99 | 3 |
module Web.Stripe.Client.Stripe (stripe) where
import Web.Stripe.Client.HttpStreams (stripe)
| dmjio/stripe | stripe-haskell/src-http-streams/Web/Stripe/Client/Stripe.hs | mit | 94 | 0 | 5 | 8 | 25 | 17 | 8 | 2 | 0 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ConstraintKinds #-}
import Prelude hiding (repeat)
repeat :: Int -> (a -> a) -> a -> a
repeat 1 f x = f x
repeat n f x = n `seq` x `seq` repeat (n-1) f $ f x
---- Buggy version
------------------
type Numerical a = (Fractional a, Real a)
data Box a = Box
{ func :: forall num. (Numerical num) => num -> a -> a
, obj :: !a }
do_step :: (Numerical num) => num -> Box a -> Box a
do_step number Box{..} = Box{ obj = func number obj, .. }
start :: Box Double
start = Box { func = \x y -> realToFrac x + y
, obj = 0 }
test :: Int -> IO ()
test steps = putStrLn $ show $ obj $ repeat steps (do_step 1) start
---- Driver
-----------
main :: IO ()
main = test 20000 -- compare test2 10000000 or test3 10000000, but test4 20000
---- No tuple constraint synonym is better
------------------------------------------
data Box2 a = Box2
{ func2 :: forall num. (Fractional num, Real num) => num -> a -> a
, obj2 :: !a }
do_step2 :: (Fractional num, Real num) => num -> Box2 a -> Box2 a
do_step2 number Box2{..} = Box2{ obj2 = func2 number obj2, ..}
start2 :: Box2 Double
start2 = Box2 { func2 = \x y -> realToFrac x + y
, obj2 = 0 }
test2 :: Int -> IO ()
test2 steps = putStrLn $ show $ obj2 $ repeat steps (do_step2 1) start2
---- Not copying the function field works too
---------------------------------------------
do_step3 :: (Numerical num) => num -> Box a -> Box a
do_step3 number b@Box{..} = b{ obj = func number obj }
test3 :: Int -> IO ()
test3 steps = putStrLn $ show $ obj $ repeat steps (do_step3 1) start
---- But record wildcards are not at fault
------------------------------------------
do_step4 :: (Numerical num) => num -> Box a -> Box a
do_step4 number Box{func = f, obj = x} = Box{ obj = f number x, func = f }
test4 :: Int -> IO ()
test4 steps = putStrLn $ show $ obj $ repeat steps (do_step4 1) start
| vladfi1/hs-misc | Bug.hs | mit | 1,947 | 15 | 9 | 446 | 804 | 419 | 385 | 42 | 1 |
-- Each well-formed expression in Haskell has a well-formed type.
-- Each well-formed expression has a value.
-- Names for functions and values begin with a lowercase letter, except for data constructors
-- which begin with an uppercase letter.
-- 3 + 4 is the same as (+) 3 4
-- div 15 3 is the same as 15 `div` 3
-- Functional applications associate to the left
-- a b c ==== (a b) c
-- You can declare new operators
(+++) :: Int -> Int -> Int
x +++ y = if even x then y else x + y
-- Section: One of the arguments of an operator is included with the operator:
-- (+1)
-- (2*)
-- lambda expression:
-- \n -> 2 * n + 1
-- map (\n -> 2 * n + 1) [1..5]
-- The type `Bool` has three values: `True`, `False`, and `undefined`.
-- take :: Int -> [a] -> [a]
-- a is a type variable. — Type variables begin with a lowercase letter.
-- Type variables can be instantiated to any type.
-- (+) :: Num a = > a -> a -> a
-- Type Classes:
-- (+) is of type `a -> a -> a` for any a of type `Num` | v0lkan/learning-haskell | expressions.hs | mit | 990 | 0 | 9 | 221 | 69 | 45 | 24 | 2 | 2 |
module Codewars.G964.Countdig where
import Data.Char
nbDig :: Int -> Int -> Int
nbDig n d = sum (map (\a -> stringDigits (show (a^2)) d) [0..n])
stringDigits :: String -> Int -> Int
stringDigits num digit = length (filter (== intToDigit digit) num)
nbDig2 :: Int -> Int -> Int
nbDig2 n d = sum [length $ filter (==c) $ show (x*x) | x <- [0..n]]
where c = intToDigit d | pasaunders/code-katas | src/count_digit.hs | mit | 374 | 0 | 14 | 76 | 195 | 103 | 92 | 9 | 1 |
module SignalProperties where
import qualified Data.ByteString.Lazy.Char8 as LBS
import Network.Linx.Gateway.Signal
import Network.Linx.Gateway.Types
import Generators ()
prop_signal :: Signal -> Bool
prop_signal sig =
let encodedSignal = encode sig
len = payloadSize sig
in (asInt len) == LBS.length encodedSignal
&& sig == decode encodedSignal
prop_signalSelector :: SignalSelector -> Bool
prop_signalSelector selector =
let encodedSelector = encode selector
len = payloadSize selector
in (asInt len) == LBS.length encodedSelector
&& selector == decode encodedSelector
| kosmoskatten/linx-gateway | test/SignalProperties.hs | mit | 638 | 0 | 11 | 138 | 164 | 87 | 77 | 17 | 1 |
{-# LANGUAGE UnicodeSyntax #-}
module Data.Poset.Semilattice where
import Data.Maybe (isJust)
import Data.Poset
-- | Semilattice is a Poset if infimum for every two elements exists
--
isSemilattice ∷ Eq α ⇒ Poset α → Bool
isSemilattice p@(Poset es _) = and
[ isJust $ infimum' p a b | a ← es, b ← es ]
| dmalikov/posets | src/Data/Poset/Semilattice.hs | mit | 319 | 0 | 8 | 61 | 96 | 52 | 44 | 7 | 1 |
module Main where
import Test.HUnit
import Chapter2_Tests
import qualified System.Exit as Exit
testsSuite = TestList [
Chapter2_Tests.tests
]
main :: IO ()
main = do count <- runTestTT $ testsSuite
if failures count > 0 then Exit.exitFailure else return ()
| omelhoro/haskell-hutton | Main.hs | mit | 309 | 0 | 9 | 92 | 84 | 46 | 38 | 9 | 2 |
{-# htermination range :: (Char,Char) -> [Char] #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_range_3.hs | mit | 52 | 0 | 2 | 8 | 3 | 2 | 1 | 1 | 0 |
-- | Defines the StlImporter.
module Codec.Soten.Importer.StlImporter (
StlImporter(..)
) where
import Control.Monad
( liftM2
)
import qualified Data.ByteString.Lazy as BS
import Data.Maybe
( isJust
, fromJust
)
import qualified Data.Vector as V
import Data.Binary.Get (runGet, getWord32le)
import Control.Lens ((&), (^.), (.~))
import Linear
( V3(..)
)
import Codec.Soten.BaseImporter
( BaseImporter(..)
, searchFileHeaderForToken
)
import Codec.Soten.Data.StlData
( Model
, modelName
, modelFacets
, facetNormal
, facetVertices
)
import Codec.Soten.Parser.StlParser
( parseASCII
, parseBinary
)
import Codec.Soten.Scene.Material
( MaterialProperty(..)
, addProperty
, newMaterial
)
import Codec.Soten.Scene.Mesh
( Mesh
, meshFaces
, meshMaterialIndex
, meshName
, meshNormals
, meshVertices
, newMesh
, Face(..)
)
import Codec.Soten.Scene
( Scene(..)
, sceneMeshes
, sceneMaterials
, sceneRootNode
, newScene
, nodeMeshes
, newNode
)
import Codec.Soten.Util
( CheckType(..)
, DeadlyImporterError(..)
, throw
, hasExtention
)
-- | Importer for the sterolithography STL file format.
data StlImporter =
StlImporter
deriving Show
instance BaseImporter StlImporter where
canImport _ filePath CheckExtension = return $ hasExtention filePath [".stl"]
canImport p filePath CheckHeader =
liftM2 (||)
(canImport p filePath CheckExtension)
(searchFileHeaderForToken filePath ["solid", "STL"])
readModel _ = internalReadFile
-- | Reads file content and parsers it into the 'Scene'. Returns error messages
-- as 'String's.
internalReadFile :: FilePath -> IO (Either String Scene)
internalReadFile filePath = do
-- TODO: Catch exceptions here.
model <- getModel filePath
let scene = newScene & sceneMaterials .~ V.singleton mat
& sceneMeshes .~ V.singleton mesh
& sceneRootNode .~ node
mesh = getMesh model
node = newNode & nodeMeshes .~ V.singleton 0
in return $ Right scene
where
-- TODO: Move DefaultMaterial to constants
mat = foldl addProperty newMaterial
[ MaterialName "DefaultMaterial"
, MaterialColorDiffuse clrDiffuseColor
, MaterialColorSpecular clrDiffuseColor
, MaterialColorAmbient (V3 0.5 0.5 0.5)
]
clrDiffuseColor = V3 0.6 0.6 0.6
-- | Creates mesh according to the 'Facet' data.
getMesh :: Model -> Mesh
getMesh model = newMesh
& meshName .~ (model ^. modelName)
& meshNormals .~ normals
& meshVertices .~ vertices
& meshFaces .~ faces
& meshMaterialIndex .~ Just 0
where
vertices = foldl (\ vp facet -> vp V.++ (facet ^. facetVertices))
V.empty (model ^. modelFacets)
normals = foldl (\ vn facet -> V.snoc vn (facet ^. facetNormal))
V.empty (model ^. modelFacets)
faces = V.imap (\ i _ -> Face (V.fromList [3 * i, 3 * i + 1, 3 * i + 2 ]))
(V.take (V.length vertices `div` 3) vertices)
-- | Checks which wheter file has binary or ascii representation.
getModel :: FilePath -> IO Model
getModel fileName = do
binary <- isBinary fileName
ascii <- isAscii fileName
if isJust binary
then return $ parseBinary (fromJust binary)
else if isJust ascii
then return $ parseASCII (fromJust ascii)
else throw $ DeadlyImporterError $
"Failed to determine STL storage representation for "
++ fileName ++ "."
-- | Checks if file starts with "solid" token. Note: this check is not
-- sufficient, binary format could also begin with "solid".
isAscii :: FilePath -> IO (Maybe String)
isAscii fileName = do
content <- readFile fileName
if take 5 content == "solid"
then return (Just content)
else return Nothing
-- | Checks if file size matching the formula:
-- 80 byte header, 4 byte face count, 50 bytes per face
isBinary :: FilePath -> IO (Maybe BS.ByteString )
isBinary fileName = do
content <- BS.readFile fileName
if BS.length content < 84
then return Nothing
else
let facetsCount = runGet getWord32le $ BS.take 4 (BS.drop 80 content)
in if BS.length content == 84 + fromIntegral facetsCount * 50
then return (Just content)
else return Nothing
| triplepointfive/soten | src/Codec/Soten/Importer/StlImporter.hs | mit | 5,140 | 0 | 17 | 1,882 | 1,125 | 616 | 509 | 115 | 3 |
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
module Hablog.Data.Markup
( MarkupEngine(..)
, convertToHtml
) where
import Database.Persist
import Database.Persist.TH
import Text.Pandoc
import qualified Data.Text as T
data MarkupEngine = Markdown deriving (Show, Read, Eq)
derivePersistField "MarkupEngine"
convertToHtml :: MarkupEngine -> T.Text -> T.Text
convertToHtml engine = case engine of
Markdown -> T.pack . writeHtmlString def . readMarkdown def . T.unpack
| garrettpauls/Hablog | src/Hablog/Data/Markup.hs | mit | 477 | 0 | 11 | 64 | 129 | 72 | 57 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.AMQP.Internal.Producer
( produceTopicMessage
) where
import Config.Config as Config (RabbitMQConfig (..))
import Control.Monad.Reader
import Data.Aeson as Aeson
import Network.AMQP.Internal.Types
import qualified Network.AMQP as AMQP
produceTopicMessage :: ToJSON a => TopicName -> Message a -> WithConn ()
produceTopicMessage topic msg = ask >>= \conn ->
let exchangeName = ExchangeName $ Config.getExchangeName (getConfig conn)
message = buildMessage msg
channel = getChannel conn
in liftIO $ publishMessage channel exchangeName topic message
buildMessage :: ToJSON a => Message a -> AMQP.Message
buildMessage (Message msg) =
AMQP.newMsg { AMQP.msgBody = Aeson.encode msg
, AMQP.msgDeliveryMode = Just AMQP.NonPersistent
}
publishMessage :: AMQP.Channel -> ExchangeName -> TopicName -> AMQP.Message -> IO ()
publishMessage channel (ExchangeName exchName) (TopicName topic) message =
AMQP.publishMsg channel exchName topic message
| gust/feature-creature | legacy/lib/Network/AMQP/Internal/Producer.hs | mit | 1,046 | 0 | 14 | 187 | 292 | 156 | 136 | 21 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html
module Stratosphere.ResourceProperties.KinesisAnalyticsApplicationInput where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationInputParallelism
import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationInputProcessingConfiguration
import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationInputSchema
import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationKinesisFirehoseInput
import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationKinesisStreamsInput
-- | Full data type definition for KinesisAnalyticsApplicationInput. See
-- 'kinesisAnalyticsApplicationInput' for a more convenient constructor.
data KinesisAnalyticsApplicationInput =
KinesisAnalyticsApplicationInput
{ _kinesisAnalyticsApplicationInputInputParallelism :: Maybe KinesisAnalyticsApplicationInputParallelism
, _kinesisAnalyticsApplicationInputInputProcessingConfiguration :: Maybe KinesisAnalyticsApplicationInputProcessingConfiguration
, _kinesisAnalyticsApplicationInputInputSchema :: KinesisAnalyticsApplicationInputSchema
, _kinesisAnalyticsApplicationInputKinesisFirehoseInput :: Maybe KinesisAnalyticsApplicationKinesisFirehoseInput
, _kinesisAnalyticsApplicationInputKinesisStreamsInput :: Maybe KinesisAnalyticsApplicationKinesisStreamsInput
, _kinesisAnalyticsApplicationInputNamePrefix :: Val Text
} deriving (Show, Eq)
instance ToJSON KinesisAnalyticsApplicationInput where
toJSON KinesisAnalyticsApplicationInput{..} =
object $
catMaybes
[ fmap (("InputParallelism",) . toJSON) _kinesisAnalyticsApplicationInputInputParallelism
, fmap (("InputProcessingConfiguration",) . toJSON) _kinesisAnalyticsApplicationInputInputProcessingConfiguration
, (Just . ("InputSchema",) . toJSON) _kinesisAnalyticsApplicationInputInputSchema
, fmap (("KinesisFirehoseInput",) . toJSON) _kinesisAnalyticsApplicationInputKinesisFirehoseInput
, fmap (("KinesisStreamsInput",) . toJSON) _kinesisAnalyticsApplicationInputKinesisStreamsInput
, (Just . ("NamePrefix",) . toJSON) _kinesisAnalyticsApplicationInputNamePrefix
]
-- | Constructor for 'KinesisAnalyticsApplicationInput' containing required
-- fields as arguments.
kinesisAnalyticsApplicationInput
:: KinesisAnalyticsApplicationInputSchema -- ^ 'kaaiInputSchema'
-> Val Text -- ^ 'kaaiNamePrefix'
-> KinesisAnalyticsApplicationInput
kinesisAnalyticsApplicationInput inputSchemaarg namePrefixarg =
KinesisAnalyticsApplicationInput
{ _kinesisAnalyticsApplicationInputInputParallelism = Nothing
, _kinesisAnalyticsApplicationInputInputProcessingConfiguration = Nothing
, _kinesisAnalyticsApplicationInputInputSchema = inputSchemaarg
, _kinesisAnalyticsApplicationInputKinesisFirehoseInput = Nothing
, _kinesisAnalyticsApplicationInputKinesisStreamsInput = Nothing
, _kinesisAnalyticsApplicationInputNamePrefix = namePrefixarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-inputparallelism
kaaiInputParallelism :: Lens' KinesisAnalyticsApplicationInput (Maybe KinesisAnalyticsApplicationInputParallelism)
kaaiInputParallelism = lens _kinesisAnalyticsApplicationInputInputParallelism (\s a -> s { _kinesisAnalyticsApplicationInputInputParallelism = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-inputprocessingconfiguration
kaaiInputProcessingConfiguration :: Lens' KinesisAnalyticsApplicationInput (Maybe KinesisAnalyticsApplicationInputProcessingConfiguration)
kaaiInputProcessingConfiguration = lens _kinesisAnalyticsApplicationInputInputProcessingConfiguration (\s a -> s { _kinesisAnalyticsApplicationInputInputProcessingConfiguration = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-inputschema
kaaiInputSchema :: Lens' KinesisAnalyticsApplicationInput KinesisAnalyticsApplicationInputSchema
kaaiInputSchema = lens _kinesisAnalyticsApplicationInputInputSchema (\s a -> s { _kinesisAnalyticsApplicationInputInputSchema = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-kinesisfirehoseinput
kaaiKinesisFirehoseInput :: Lens' KinesisAnalyticsApplicationInput (Maybe KinesisAnalyticsApplicationKinesisFirehoseInput)
kaaiKinesisFirehoseInput = lens _kinesisAnalyticsApplicationInputKinesisFirehoseInput (\s a -> s { _kinesisAnalyticsApplicationInputKinesisFirehoseInput = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-kinesisstreamsinput
kaaiKinesisStreamsInput :: Lens' KinesisAnalyticsApplicationInput (Maybe KinesisAnalyticsApplicationKinesisStreamsInput)
kaaiKinesisStreamsInput = lens _kinesisAnalyticsApplicationInputKinesisStreamsInput (\s a -> s { _kinesisAnalyticsApplicationInputKinesisStreamsInput = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-nameprefix
kaaiNamePrefix :: Lens' KinesisAnalyticsApplicationInput (Val Text)
kaaiNamePrefix = lens _kinesisAnalyticsApplicationInputNamePrefix (\s a -> s { _kinesisAnalyticsApplicationInputNamePrefix = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsApplicationInput.hs | mit | 5,819 | 0 | 13 | 410 | 599 | 346 | 253 | 54 | 1 |
{-# language UndecidableInstances #-}
-- | this is the general module (top module after refactoring)
module Rewriting.Derive where
import Rewriting.Apply
import Rewriting.Derive.Instance
{-
import Rewriting.Step
import Rewriting.Steps
import Rewriting.Derive.Quiz
import Rewriting.Derive.Config
-}
import Autolib.Reporter
import Autolib.ToDoc
import Autolib.Reader
import Autolib.FiniteMap
import Challenger.Partial
import Inter.Types
import Inter.Quiz
import Control.Monad
import Data.Typeable
data Derive tag = Derive tag
deriving ( Eq, Ord, Typeable )
instance OrderScore ( Derive tag ) where
scoringOrder _ = Increasing
instance ToDoc tag => ToDoc ( Derive tag ) where
toDoc ( Derive t ) = text "Derive-" <> toDoc t
instance Reader tag => Reader ( Derive tag ) where
reader = do
my_symbol "Derive-"
tag <- reader
return $ Derive tag
class ( Reader x, ToDoc x, Typeable x ) => RDT x
instance ( Reader x, ToDoc x, Typeable x ) => RDT x
instance ( RDT tag, RDT action, RDT object , RDT system
, Eq object
, Apply tag system object action
)
=> Partial ( Derive tag ) ( Instance system object ) [ action ] where
report ( Derive tag ) inst = do
inform $ vcat
[ text "gesucht ist für das System"
, nest 4 $ toDoc $ system inst
, text "eine Folge von Schritten, die"
, nest 4 $ toDoc $ from inst
, text "überführt in"
, nest 4 $ toDoc $ to inst
]
-- peng $ from inst
-- peng $ to inst
initial ( Derive tag ) inst =
take 1 $ actions tag ( system inst ) ( from inst )
total ( Derive tag ) inst steps = do
let sys = system inst
t <- foldM ( apply tag sys ) ( from inst ) steps
assert ( t == to inst )
$ text "stimmt mit Ziel überein?"
instance Measure ( Derive tag ) ( Instance system object ) [ action ] where
measure ( Derive tag ) inst actions = fromIntegral $ length actions
make_fixed :: ( RDT tag, RDT action, RDT object , RDT system
, Eq object
, Apply tag system object action
)
=> tag -> Make
make_fixed tag = direct ( Derive tag ) ( example tag )
{-
make_quiz :: Make
make_quiz = quiz Derive Rewriting.Derive.Config.example
instance (Symbol v, Symbol c, Reader ( TRS v c ) )
=> Generator Derive ( Config v c ) ( Instance v c ) where
generator Derive conf key = roll conf
instance (Symbol v, Symbol c, Reader ( TRS v c ) )
=> Project Derive ( Instance v c ) ( Instance v c ) where
project Derive inst = inst
firstvar trs = take 1 $ do
r <- regeln trs
t <- [ lhs r, rhs r ]
lvars t
-}
| florianpilz/autotool | src/Rewriting/Derive.hs | gpl-2.0 | 2,743 | 0 | 13 | 813 | 690 | 347 | 343 | -1 | -1 |
-- OmegaGB Copyright 2007 Bit Connor
-- This program is distributed under the terms of the GNU General Public License
-----------------------------------------------------------------------------
-- |
-- Module : Display
-- Copyright : (c) Bit Connor 2007 <[email protected]>
-- License : GPL
-- Maintainer : [email protected]
-- Stability : in-progress
--
-- OmegaGB
-- Game Boy Emulator
--
-- This module defines the Display type that represents the Game Boy's LCD
-- display. The Game Boy LCD display has a resolution of 144x160 and 4
-- colors,
--
-----------------------------------------------------------------------------
module Display where
import Data.Array.Unboxed
import Data.Word
type Display = UArray (Int, Int) Word8
blankDisplay :: Display
blankDisplay = array ((0, 0), (143, 159)) (map (\i -> (i, 0)) (range ((0, 0), (143, 159))))
| bitc/omegagb | src/Display.hs | gpl-2.0 | 877 | 0 | 11 | 144 | 129 | 86 | 43 | 6 | 1 |
{-
Copyright (C) 2006-2010 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Parsing
Copyright : Copyright (C) 2006-2010 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
A utility library with parsers used in pandoc readers.
-}
module Text.Pandoc.Parsing ( (>>~),
anyLine,
many1Till,
notFollowedBy',
oneOfStrings,
spaceChar,
nonspaceChar,
skipSpaces,
blankline,
blanklines,
enclosed,
stringAnyCase,
parseFromString,
lineClump,
charsInBalanced,
romanNumeral,
emailAddress,
uri,
withHorizDisplacement,
withRaw,
nullBlock,
failIfStrict,
failUnlessLHS,
escaped,
characterReference,
anyOrderedListMarker,
orderedListMarker,
charRef,
tableWith,
gridTableWith,
readWith,
testStringWith,
ParserState (..),
defaultParserState,
HeaderType (..),
ParserContext (..),
QuoteContext (..),
NoteTable,
KeyTable,
Key,
toKey,
fromKey,
lookupKeySrc,
smartPunctuation,
macro,
applyMacros' )
where
import Text.Pandoc.Definition
import Text.Pandoc.Generic
import qualified Text.Pandoc.UTF8 as UTF8 (putStrLn)
import Text.ParserCombinators.Parsec
import Data.Char ( toLower, toUpper, ord, isAscii, isAlphaNum, isDigit, isPunctuation )
import Data.List ( intercalate, transpose )
import Network.URI ( parseURI, URI (..), isAllowedInURI )
import Control.Monad ( join, liftM, guard )
import Text.Pandoc.Shared
import qualified Data.Map as M
import Text.TeXMath.Macros (applyMacros, Macro, parseMacroDefinitions)
import Text.HTML.TagSoup.Entity ( lookupEntity )
-- | Like >>, but returns the operation on the left.
-- (Suggested by Tillmann Rendel on Haskell-cafe list.)
(>>~) :: (Monad m) => m a -> m b -> m a
a >>~ b = a >>= \x -> b >> return x
-- | Parse any line of text
anyLine :: GenParser Char st [Char]
anyLine = manyTill anyChar newline
-- | Like @manyTill@, but reads at least one item.
many1Till :: GenParser tok st a
-> GenParser tok st end
-> GenParser tok st [a]
many1Till p end = do
first <- p
rest <- manyTill p end
return (first:rest)
-- | A more general form of @notFollowedBy@. This one allows any
-- type of parser to be specified, and succeeds only if that parser fails.
-- It does not consume any input.
notFollowedBy' :: Show b => GenParser a st b -> GenParser a st ()
notFollowedBy' p = try $ join $ do a <- try p
return (unexpected (show a))
<|>
return (return ())
-- (This version due to Andrew Pimlott on the Haskell mailing list.)
-- | Parses one of a list of strings (tried in order).
oneOfStrings :: [String] -> GenParser Char st String
oneOfStrings listOfStrings = choice $ map (try . string) listOfStrings
-- | Parses a space or tab.
spaceChar :: CharParser st Char
spaceChar = satisfy $ \c -> c == ' ' || c == '\t'
-- | Parses a nonspace, nonnewline character.
nonspaceChar :: CharParser st Char
nonspaceChar = satisfy $ \x -> x /= '\t' && x /= '\n' && x /= ' ' && x /= '\r'
-- | Skips zero or more spaces or tabs.
skipSpaces :: GenParser Char st ()
skipSpaces = skipMany spaceChar
-- | Skips zero or more spaces or tabs, then reads a newline.
blankline :: GenParser Char st Char
blankline = try $ skipSpaces >> newline
-- | Parses one or more blank lines and returns a string of newlines.
blanklines :: GenParser Char st [Char]
blanklines = many1 blankline
-- | Parses material enclosed between start and end parsers.
enclosed :: GenParser Char st t -- ^ start parser
-> GenParser Char st end -- ^ end parser
-> GenParser Char st a -- ^ content parser (to be used repeatedly)
-> GenParser Char st [a]
enclosed start end parser = try $
start >> notFollowedBy space >> many1Till parser end
-- | Parse string, case insensitive.
stringAnyCase :: [Char] -> CharParser st String
stringAnyCase [] = string ""
stringAnyCase (x:xs) = do
firstChar <- char (toUpper x) <|> char (toLower x)
rest <- stringAnyCase xs
return (firstChar:rest)
-- | Parse contents of 'str' using 'parser' and return result.
parseFromString :: GenParser tok st a -> [tok] -> GenParser tok st a
parseFromString parser str = do
oldPos <- getPosition
oldInput <- getInput
setInput str
result <- parser
setInput oldInput
setPosition oldPos
return result
-- | Parse raw line block up to and including blank lines.
lineClump :: GenParser Char st String
lineClump = blanklines
<|> (many1 (notFollowedBy blankline >> anyLine) >>= return . unlines)
-- | Parse a string of characters between an open character
-- and a close character, including text between balanced
-- pairs of open and close, which must be different. For example,
-- @charsInBalanced '(' ')' anyChar@ will parse "(hello (there))"
-- and return "hello (there)".
charsInBalanced :: Char -> Char -> GenParser Char st Char
-> GenParser Char st String
charsInBalanced open close parser = try $ do
char open
let isDelim c = c == open || c == close
raw <- many $ many1 (notFollowedBy (satisfy isDelim) >> parser)
<|> (do res <- charsInBalanced open close parser
return $ [open] ++ res ++ [close])
char close
return $ concat raw
-- old charsInBalanced would be:
-- charsInBalanced open close (noneOf "\n" <|> char '\n' >> notFollowedBy blankline)
-- old charsInBalanced' would be:
-- charsInBalanced open close anyChar
-- Auxiliary functions for romanNumeral:
lowercaseRomanDigits :: [Char]
lowercaseRomanDigits = ['i','v','x','l','c','d','m']
uppercaseRomanDigits :: [Char]
uppercaseRomanDigits = map toUpper lowercaseRomanDigits
-- | Parses a roman numeral (uppercase or lowercase), returns number.
romanNumeral :: Bool -- ^ Uppercase if true
-> GenParser Char st Int
romanNumeral upperCase = do
let romanDigits = if upperCase
then uppercaseRomanDigits
else lowercaseRomanDigits
lookAhead $ oneOf romanDigits
let [one, five, ten, fifty, hundred, fivehundred, thousand] =
map char romanDigits
thousands <- many thousand >>= (return . (1000 *) . length)
ninehundreds <- option 0 $ try $ hundred >> thousand >> return 900
fivehundreds <- many fivehundred >>= (return . (500 *) . length)
fourhundreds <- option 0 $ try $ hundred >> fivehundred >> return 400
hundreds <- many hundred >>= (return . (100 *) . length)
nineties <- option 0 $ try $ ten >> hundred >> return 90
fifties <- many fifty >>= (return . (50 *) . length)
forties <- option 0 $ try $ ten >> fifty >> return 40
tens <- many ten >>= (return . (10 *) . length)
nines <- option 0 $ try $ one >> ten >> return 9
fives <- many five >>= (return . (5 *) . length)
fours <- option 0 $ try $ one >> five >> return 4
ones <- many one >>= (return . length)
let total = thousands + ninehundreds + fivehundreds + fourhundreds +
hundreds + nineties + fifties + forties + tens + nines +
fives + fours + ones
if total == 0
then fail "not a roman numeral"
else return total
-- Parsers for email addresses and URIs
emailChar :: GenParser Char st Char
emailChar = alphaNum <|>
satisfy (\c -> c == '-' || c == '+' || c == '_' || c == '.')
domainChar :: GenParser Char st Char
domainChar = alphaNum <|> char '-'
domain :: GenParser Char st [Char]
domain = do
first <- many1 domainChar
dom <- many1 $ try (char '.' >> many1 domainChar )
return $ intercalate "." (first:dom)
-- | Parses an email address; returns original and corresponding
-- escaped mailto: URI.
emailAddress :: GenParser Char st (String, String)
emailAddress = try $ do
firstLetter <- alphaNum
restAddr <- many emailChar
let addr = firstLetter:restAddr
char '@'
dom <- domain
let full = addr ++ '@':dom
return (full, escapeURI $ "mailto:" ++ full)
-- | Parses a URI. Returns pair of original and URI-escaped version.
uri :: GenParser Char st (String, String)
uri = try $ do
let protocols = [ "http:", "https:", "ftp:", "file:", "mailto:",
"news:", "telnet:" ]
lookAhead $ oneOfStrings protocols
-- Scan non-ascii characters and ascii characters allowed in a URI.
-- We allow punctuation except when followed by a space, since
-- we don't want the trailing '.' in 'http://google.com.'
let innerPunct = try $ satisfy isPunctuation >>~
notFollowedBy (newline <|> spaceChar)
let uriChar = innerPunct <|>
satisfy (\c -> not (isPunctuation c) &&
(not (isAscii c) || isAllowedInURI c))
-- We want to allow
-- http://en.wikipedia.org/wiki/State_of_emergency_(disambiguation)
-- as a URL, while NOT picking up the closing paren in
-- (http://wikipedia.org)
-- So we include balanced parens in the URL.
let inParens = try $ do char '('
res <- many uriChar
char ')'
return $ '(' : res ++ ")"
str <- liftM concat $ many1 $ inParens <|> count 1 (innerPunct <|> uriChar)
-- now see if they amount to an absolute URI
case parseURI (escapeURI str) of
Just uri' -> if uriScheme uri' `elem` protocols
then return (str, show uri')
else fail "not a URI"
Nothing -> fail "not a URI"
-- | Applies a parser, returns tuple of its results and its horizontal
-- displacement (the difference between the source column at the end
-- and the source column at the beginning). Vertical displacement
-- (source row) is ignored.
withHorizDisplacement :: GenParser Char st a -- ^ Parser to apply
-> GenParser Char st (a, Int) -- ^ (result, displacement)
withHorizDisplacement parser = do
pos1 <- getPosition
result <- parser
pos2 <- getPosition
return (result, sourceColumn pos2 - sourceColumn pos1)
-- | Applies a parser and returns the raw string that was parsed,
-- along with the value produced by the parser.
withRaw :: GenParser Char st a -> GenParser Char st (a, [Char])
withRaw parser = do
pos1 <- getPosition
inp <- getInput
result <- parser
pos2 <- getPosition
let (l1,c1) = (sourceLine pos1, sourceColumn pos1)
let (l2,c2) = (sourceLine pos2, sourceColumn pos2)
let inplines = take ((l2 - l1) + 1) $ lines inp
let raw = case inplines of
[] -> error "raw: inplines is null" -- shouldn't happen
[l] -> take (c2 - c1) l
ls -> unlines (init ls) ++ take (c2 - 1) (last ls)
return (result, raw)
-- | Parses a character and returns 'Null' (so that the parser can move on
-- if it gets stuck).
nullBlock :: GenParser Char st Block
nullBlock = anyChar >> return Null
-- | Fail if reader is in strict markdown syntax mode.
failIfStrict :: GenParser a ParserState ()
failIfStrict = do
state <- getState
if stateStrict state then fail "strict mode" else return ()
-- | Fail unless we're in literate haskell mode.
failUnlessLHS :: GenParser tok ParserState ()
failUnlessLHS = getState >>= guard . stateLiterateHaskell
-- | Parses backslash, then applies character parser.
escaped :: GenParser Char st Char -- ^ Parser for character to escape
-> GenParser Char st Char
escaped parser = try $ char '\\' >> parser
-- | Parse character entity.
characterReference :: GenParser Char st Char
characterReference = try $ do
char '&'
ent <- many1Till nonspaceChar (char ';')
case lookupEntity ent of
Just c -> return c
Nothing -> fail "entity not found"
-- | Parses an uppercase roman numeral and returns (UpperRoman, number).
upperRoman :: GenParser Char st (ListNumberStyle, Int)
upperRoman = do
num <- romanNumeral True
return (UpperRoman, num)
-- | Parses a lowercase roman numeral and returns (LowerRoman, number).
lowerRoman :: GenParser Char st (ListNumberStyle, Int)
lowerRoman = do
num <- romanNumeral False
return (LowerRoman, num)
-- | Parses a decimal numeral and returns (Decimal, number).
decimal :: GenParser Char st (ListNumberStyle, Int)
decimal = do
num <- many1 digit
return (Decimal, read num)
-- | Parses a '@' and optional label and
-- returns (DefaultStyle, [next example number]). The next
-- example number is incremented in parser state, and the label
-- (if present) is added to the label table.
exampleNum :: GenParser Char ParserState (ListNumberStyle, Int)
exampleNum = do
char '@'
lab <- many (alphaNum <|> satisfy (\c -> c == '_' || c == '-'))
st <- getState
let num = stateNextExample st
let newlabels = if null lab
then stateExamples st
else M.insert lab num $ stateExamples st
updateState $ \s -> s{ stateNextExample = num + 1
, stateExamples = newlabels }
return (Example, num)
-- | Parses a '#' returns (DefaultStyle, 1).
defaultNum :: GenParser Char st (ListNumberStyle, Int)
defaultNum = do
char '#'
return (DefaultStyle, 1)
-- | Parses a lowercase letter and returns (LowerAlpha, number).
lowerAlpha :: GenParser Char st (ListNumberStyle, Int)
lowerAlpha = do
ch <- oneOf ['a'..'z']
return (LowerAlpha, ord ch - ord 'a' + 1)
-- | Parses an uppercase letter and returns (UpperAlpha, number).
upperAlpha :: GenParser Char st (ListNumberStyle, Int)
upperAlpha = do
ch <- oneOf ['A'..'Z']
return (UpperAlpha, ord ch - ord 'A' + 1)
-- | Parses a roman numeral i or I
romanOne :: GenParser Char st (ListNumberStyle, Int)
romanOne = (char 'i' >> return (LowerRoman, 1)) <|>
(char 'I' >> return (UpperRoman, 1))
-- | Parses an ordered list marker and returns list attributes.
anyOrderedListMarker :: GenParser Char ParserState ListAttributes
anyOrderedListMarker = choice $
[delimParser numParser | delimParser <- [inPeriod, inOneParen, inTwoParens],
numParser <- [decimal, exampleNum, defaultNum, romanOne,
lowerAlpha, lowerRoman, upperAlpha, upperRoman]]
-- | Parses a list number (num) followed by a period, returns list attributes.
inPeriod :: GenParser Char st (ListNumberStyle, Int)
-> GenParser Char st ListAttributes
inPeriod num = try $ do
(style, start) <- num
char '.'
let delim = if style == DefaultStyle
then DefaultDelim
else Period
return (start, style, delim)
-- | Parses a list number (num) followed by a paren, returns list attributes.
inOneParen :: GenParser Char st (ListNumberStyle, Int)
-> GenParser Char st ListAttributes
inOneParen num = try $ do
(style, start) <- num
char ')'
return (start, style, OneParen)
-- | Parses a list number (num) enclosed in parens, returns list attributes.
inTwoParens :: GenParser Char st (ListNumberStyle, Int)
-> GenParser Char st ListAttributes
inTwoParens num = try $ do
char '('
(style, start) <- num
char ')'
return (start, style, TwoParens)
-- | Parses an ordered list marker with a given style and delimiter,
-- returns number.
orderedListMarker :: ListNumberStyle
-> ListNumberDelim
-> GenParser Char ParserState Int
orderedListMarker style delim = do
let num = defaultNum <|> -- # can continue any kind of list
case style of
DefaultStyle -> decimal
Example -> exampleNum
Decimal -> decimal
UpperRoman -> upperRoman
LowerRoman -> lowerRoman
UpperAlpha -> upperAlpha
LowerAlpha -> lowerAlpha
let context = case delim of
DefaultDelim -> inPeriod
Period -> inPeriod
OneParen -> inOneParen
TwoParens -> inTwoParens
(start, _, _) <- context num
return start
-- | Parses a character reference and returns a Str element.
charRef :: GenParser Char st Inline
charRef = do
c <- characterReference
return $ Str [c]
-- | Parse a table using 'headerParser', 'rowParser',
-- 'lineParser', and 'footerParser'.
tableWith :: GenParser Char ParserState ([[Block]], [Alignment], [Int])
-> ([Int] -> GenParser Char ParserState [[Block]])
-> GenParser Char ParserState sep
-> GenParser Char ParserState end
-> GenParser Char ParserState [Inline]
-> GenParser Char ParserState Block
tableWith headerParser rowParser lineParser footerParser captionParser = try $ do
caption' <- option [] captionParser
(heads, aligns, indices) <- headerParser
lines' <- rowParser indices `sepEndBy` lineParser
footerParser
caption <- if null caption'
then option [] captionParser
else return caption'
state <- getState
let numColumns = stateColumns state
let widths = widthsFromIndices numColumns indices
return $ Table caption aligns widths heads lines'
-- Calculate relative widths of table columns, based on indices
widthsFromIndices :: Int -- Number of columns on terminal
-> [Int] -- Indices
-> [Double] -- Fractional relative sizes of columns
widthsFromIndices _ [] = []
widthsFromIndices numColumns' indices =
let numColumns = max numColumns' (if null indices then 0 else last indices)
lengths' = zipWith (-) indices (0:indices)
lengths = reverse $
case reverse lengths' of
[] -> []
[x] -> [x]
-- compensate for the fact that intercolumn
-- spaces are counted in widths of all columns
-- but the last...
(x:y:zs) -> if x < y && y - x <= 2
then y:y:zs
else x:y:zs
totLength = sum lengths
quotient = if totLength > numColumns
then fromIntegral totLength
else fromIntegral numColumns
fracs = map (\l -> (fromIntegral l) / quotient) lengths in
tail fracs
-- Parse a grid table: starts with row of '-' on top, then header
-- (which may be grid), then the rows,
-- which may be grid, separated by blank lines, and
-- ending with a footer (dashed line followed by blank line).
gridTableWith :: GenParser Char ParserState Block -- ^ Block parser
-> GenParser Char ParserState [Inline] -- ^ Caption parser
-> Bool -- ^ Headerless table
-> GenParser Char ParserState Block
gridTableWith block tableCaption headless =
tableWith (gridTableHeader headless block) (gridTableRow block) (gridTableSep '-') gridTableFooter tableCaption
gridTableSplitLine :: [Int] -> String -> [String]
gridTableSplitLine indices line = map removeFinalBar $ tail $
splitStringByIndices (init indices) $ removeTrailingSpace line
gridPart :: Char -> GenParser Char st (Int, Int)
gridPart ch = do
dashes <- many1 (char ch)
char '+'
return (length dashes, length dashes + 1)
gridDashedLines :: Char -> GenParser Char st [(Int,Int)]
gridDashedLines ch = try $ char '+' >> many1 (gridPart ch) >>~ blankline
removeFinalBar :: String -> String
removeFinalBar =
reverse . dropWhile (`elem` " \t") . dropWhile (=='|') . reverse
-- | Separator between rows of grid table.
gridTableSep :: Char -> GenParser Char ParserState Char
gridTableSep ch = try $ gridDashedLines ch >> return '\n'
-- | Parse header for a grid table.
gridTableHeader :: Bool -- ^ Headerless table
-> GenParser Char ParserState Block
-> GenParser Char ParserState ([[Block]], [Alignment], [Int])
gridTableHeader headless block = try $ do
optional blanklines
dashes <- gridDashedLines '-'
rawContent <- if headless
then return $ repeat ""
else many1
(notFollowedBy (gridTableSep '=') >> char '|' >>
many1Till anyChar newline)
if headless
then return ()
else gridTableSep '=' >> return ()
let lines' = map snd dashes
let indices = scanl (+) 0 lines'
let aligns = replicate (length lines') AlignDefault
-- RST does not have a notion of alignments
let rawHeads = if headless
then replicate (length dashes) ""
else map (intercalate " ") $ transpose
$ map (gridTableSplitLine indices) rawContent
heads <- mapM (parseFromString $ many block) $
map removeLeadingTrailingSpace rawHeads
return (heads, aligns, indices)
gridTableRawLine :: [Int] -> GenParser Char ParserState [String]
gridTableRawLine indices = do
char '|'
line <- many1Till anyChar newline
return (gridTableSplitLine indices line)
-- | Parse row of grid table.
gridTableRow :: GenParser Char ParserState Block
-> [Int]
-> GenParser Char ParserState [[Block]]
gridTableRow block indices = do
colLines <- many1 (gridTableRawLine indices)
let cols = map ((++ "\n") . unlines . removeOneLeadingSpace) $
transpose colLines
mapM (liftM compactifyCell . parseFromString (many block)) cols
removeOneLeadingSpace :: [String] -> [String]
removeOneLeadingSpace xs =
if all startsWithSpace xs
then map (drop 1) xs
else xs
where startsWithSpace "" = True
startsWithSpace (y:_) = y == ' '
compactifyCell :: [Block] -> [Block]
compactifyCell bs = head $ compactify [bs]
-- | Parse footer for a grid table.
gridTableFooter :: GenParser Char ParserState [Char]
gridTableFooter = blanklines
---
-- | Parse a string with a given parser and state.
readWith :: GenParser t ParserState a -- ^ parser
-> ParserState -- ^ initial state
-> [t] -- ^ input
-> a
readWith parser state input =
case runParser parser state "source" input of
Left err' -> error $ "\nError:\n" ++ show err'
Right result -> result
-- | Parse a string with @parser@ (for testing).
testStringWith :: (Show a) => GenParser Char ParserState a
-> String
-> IO ()
testStringWith parser str = UTF8.putStrLn $ show $
readWith parser defaultParserState str
-- | Parsing options.
data ParserState = ParserState
{ stateParseRaw :: Bool, -- ^ Parse raw HTML and LaTeX?
stateParserContext :: ParserContext, -- ^ Inside list?
stateQuoteContext :: QuoteContext, -- ^ Inside quoted environment?
stateMaxNestingLevel :: Int, -- ^ Max # of nested Strong/Emph
stateLastStrPos :: Maybe SourcePos, -- ^ Position after last str parsed
stateKeys :: KeyTable, -- ^ List of reference keys
stateCitations :: [String], -- ^ List of available citations
stateNotes :: NoteTable, -- ^ List of notes
stateTabStop :: Int, -- ^ Tab stop
stateStandalone :: Bool, -- ^ Parse bibliographic info?
stateTitle :: [Inline], -- ^ Title of document
stateAuthors :: [[Inline]], -- ^ Authors of document
stateDate :: [Inline], -- ^ Date of document
stateStrict :: Bool, -- ^ Use strict markdown syntax?
stateSmart :: Bool, -- ^ Use smart typography?
stateOldDashes :: Bool, -- ^ Use pandoc <= 1.8.2.1 behavior
-- in parsing dashes; -- is em-dash;
-- before numeral is en-dash
stateLiterateHaskell :: Bool, -- ^ Treat input as literate haskell
stateColumns :: Int, -- ^ Number of columns in terminal
stateHeaderTable :: [HeaderType], -- ^ Ordered list of header types used
stateIndentedCodeClasses :: [String], -- ^ Classes to use for indented code blocks
stateNextExample :: Int, -- ^ Number of next example
stateExamples :: M.Map String Int, -- ^ Map from example labels to numbers
stateHasChapters :: Bool, -- ^ True if \chapter encountered
stateApplyMacros :: Bool, -- ^ Apply LaTeX macros?
stateMacros :: [Macro], -- ^ List of macros defined so far
stateRstDefaultRole :: String -- ^ Current rST default interpreted text role
}
deriving Show
defaultParserState :: ParserState
defaultParserState =
ParserState { stateParseRaw = False,
stateParserContext = NullState,
stateQuoteContext = NoQuote,
stateMaxNestingLevel = 6,
stateLastStrPos = Nothing,
stateKeys = M.empty,
stateCitations = [],
stateNotes = [],
stateTabStop = 4,
stateStandalone = False,
stateTitle = [],
stateAuthors = [],
stateDate = [],
stateStrict = False,
stateSmart = False,
stateOldDashes = False,
stateLiterateHaskell = False,
stateColumns = 80,
stateHeaderTable = [],
stateIndentedCodeClasses = [],
stateNextExample = 1,
stateExamples = M.empty,
stateHasChapters = False,
stateApplyMacros = True,
stateMacros = [],
stateRstDefaultRole = "title-reference"}
data HeaderType
= SingleHeader Char -- ^ Single line of characters underneath
| DoubleHeader Char -- ^ Lines of characters above and below
deriving (Eq, Show)
data ParserContext
= ListItemState -- ^ Used when running parser on list item contents
| NullState -- ^ Default state
deriving (Eq, Show)
data QuoteContext
= InSingleQuote -- ^ Used when parsing inside single quotes
| InDoubleQuote -- ^ Used when parsing inside double quotes
| NoQuote -- ^ Used when not parsing inside quotes
deriving (Eq, Show)
type NoteTable = [(String, String)]
newtype Key = Key [Inline] deriving (Show, Read, Eq, Ord)
toKey :: [Inline] -> Key
toKey = Key . bottomUp lowercase
where lowercase :: Inline -> Inline
lowercase (Str xs) = Str (map toLower xs)
lowercase (Math t xs) = Math t (map toLower xs)
lowercase (Code attr xs) = Code attr (map toLower xs)
lowercase (RawInline f xs) = RawInline f (map toLower xs)
lowercase LineBreak = Space
lowercase x = x
fromKey :: Key -> [Inline]
fromKey (Key xs) = xs
type KeyTable = M.Map Key Target
-- | Look up key in key table and return target object.
lookupKeySrc :: KeyTable -- ^ Key table
-> Key -- ^ Key
-> Maybe Target
lookupKeySrc table key = case M.lookup key table of
Nothing -> Nothing
Just src -> Just src
-- | Fail unless we're in "smart typography" mode.
failUnlessSmart :: GenParser tok ParserState ()
failUnlessSmart = getState >>= guard . stateSmart
smartPunctuation :: GenParser Char ParserState Inline
-> GenParser Char ParserState Inline
smartPunctuation inlineParser = do
failUnlessSmart
choice [ quoted inlineParser, apostrophe, dash, ellipses ]
apostrophe :: GenParser Char ParserState Inline
apostrophe = (char '\'' <|> char '\8217') >> return (Str "\x2019")
quoted :: GenParser Char ParserState Inline
-> GenParser Char ParserState Inline
quoted inlineParser = doubleQuoted inlineParser <|> singleQuoted inlineParser
withQuoteContext :: QuoteContext
-> (GenParser Char ParserState Inline)
-> GenParser Char ParserState Inline
withQuoteContext context parser = do
oldState <- getState
let oldQuoteContext = stateQuoteContext oldState
setState oldState { stateQuoteContext = context }
result <- parser
newState <- getState
setState newState { stateQuoteContext = oldQuoteContext }
return result
singleQuoted :: GenParser Char ParserState Inline
-> GenParser Char ParserState Inline
singleQuoted inlineParser = try $ do
singleQuoteStart
withQuoteContext InSingleQuote $ many1Till inlineParser singleQuoteEnd >>=
return . Quoted SingleQuote . normalizeSpaces
doubleQuoted :: GenParser Char ParserState Inline
-> GenParser Char ParserState Inline
doubleQuoted inlineParser = try $ do
doubleQuoteStart
withQuoteContext InDoubleQuote $ do
contents <- manyTill inlineParser doubleQuoteEnd
return . Quoted DoubleQuote . normalizeSpaces $ contents
failIfInQuoteContext :: QuoteContext -> GenParser tok ParserState ()
failIfInQuoteContext context = do
st <- getState
if stateQuoteContext st == context
then fail "already inside quotes"
else return ()
charOrRef :: [Char] -> GenParser Char st Char
charOrRef cs =
oneOf cs <|> try (do c <- characterReference
guard (c `elem` cs)
return c)
singleQuoteStart :: GenParser Char ParserState ()
singleQuoteStart = do
failIfInQuoteContext InSingleQuote
pos <- getPosition
st <- getState
-- single quote start can't be right after str
guard $ stateLastStrPos st /= Just pos
try $ do charOrRef "'\8216\145"
notFollowedBy (oneOf ")!],;:-? \t\n")
notFollowedBy (char '.') <|> lookAhead (string "..." >> return ())
notFollowedBy (try (oneOfStrings ["s","t","m","ve","ll","re"] >>
satisfy (not . isAlphaNum)))
-- possess/contraction
return ()
singleQuoteEnd :: GenParser Char st ()
singleQuoteEnd = try $ do
charOrRef "'\8217\146"
notFollowedBy alphaNum
doubleQuoteStart :: GenParser Char ParserState ()
doubleQuoteStart = do
failIfInQuoteContext InDoubleQuote
try $ do charOrRef "\"\8220\147"
notFollowedBy (satisfy (\c -> c == ' ' || c == '\t' || c == '\n'))
doubleQuoteEnd :: GenParser Char st ()
doubleQuoteEnd = do
charOrRef "\"\8221\148"
return ()
ellipses :: GenParser Char st Inline
ellipses = do
try (charOrRef "\8230\133") <|> try (string "..." >> return '…')
return (Str "\8230")
dash :: GenParser Char ParserState Inline
dash = do
oldDashes <- stateOldDashes `fmap` getState
if oldDashes
then emDashOld <|> enDashOld
else Str `fmap` (hyphenDash <|> emDash <|> enDash)
-- Two hyphens = en-dash, three = em-dash
hyphenDash :: GenParser Char st String
hyphenDash = do
try $ string "--"
option "\8211" (char '-' >> return "\8212")
emDash :: GenParser Char st String
emDash = do
try (charOrRef "\8212\151")
return "\8212"
enDash :: GenParser Char st String
enDash = do
try (charOrRef "\8212\151")
return "\8211"
enDashOld :: GenParser Char st Inline
enDashOld = do
try (charOrRef "\8211\150") <|>
try (char '-' >> lookAhead (satisfy isDigit) >> return '–')
return (Str "\8211")
emDashOld :: GenParser Char st Inline
emDashOld = do
try (charOrRef "\8212\151") <|> (try $ string "--" >> optional (char '-') >> return '-')
return (Str "\8212")
--
-- Macros
--
-- | Parse a \newcommand or \renewcommand macro definition.
macro :: GenParser Char ParserState Block
macro = do
getState >>= guard . stateApplyMacros
inp <- getInput
case parseMacroDefinitions inp of
([], _) -> pzero
(ms, rest) -> do count (length inp - length rest) anyChar
updateState $ \st ->
st { stateMacros = ms ++ stateMacros st }
return Null
-- | Apply current macros to string.
applyMacros' :: String -> GenParser Char ParserState String
applyMacros' target = do
apply <- liftM stateApplyMacros getState
if apply
then do macros <- liftM stateMacros getState
return $ applyMacros macros target
else return target
| castaway/pandoc | src/Text/Pandoc/Parsing.hs | gpl-2.0 | 34,269 | 0 | 21 | 10,379 | 8,006 | 4,132 | 3,874 | 649 | 10 |
{- |
Module : $Header$
Description : Symbols of propositional logic
Copyright : (c) Dominik Luecke, Uni Bremen 2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Definition of symbols for propositional logic
-}
module Propositional.Symbol
(
Symbol (..) -- Symbol type
, pretty -- pretty printing for Symbols
, symOf -- Extracts the symbols out of a signature
, getSymbolMap -- Determines the symbol map
, getSymbolName -- Determines the name of a symbol
, idToRaw -- Creates a raw symbol
, symbolToRaw -- Convert symbol to raw symbol
, matches -- does a symbol match a raw symbol?
, applySymMap -- application function for symbol maps
) where
import qualified Common.Id as Id
import Common.Doc
import Common.DocUtils
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Propositional.Sign as Sign
import Propositional.Morphism as Morphism
-- | Datatype for symbols
newtype Symbol = Symbol {symName :: Id.Id}
deriving (Show, Eq, Ord)
instance Id.GetRange Symbol where
getRange = Id.getRange . symName
instance Pretty Symbol where
pretty = printSymbol
printSymbol :: Symbol -> Doc
printSymbol x = pretty $ symName x
-- | Extraction of symbols from a signature
symOf :: Sign.Sign -> Set.Set Symbol
symOf x = Set.fold (\ y -> Set.insert Symbol {symName = y}) Set.empty $
Sign.items x
-- | Determines the symbol map of a morhpism
getSymbolMap :: Morphism.Morphism -> Map.Map Symbol Symbol
getSymbolMap f =
foldr (\ x -> Map.insert (Symbol x) (Symbol $ applyMap (propMap f) x))
Map.empty $ Set.toList $ Sign.items $ source f
-- | Determines the name of a symbol
getSymbolName :: Symbol -> Id.Id
getSymbolName = symName
-- | make a raw_symbol
idToRaw :: Id.Id -> Symbol
idToRaw mid = Symbol {symName = mid}
-- | convert to raw symbol
symbolToRaw :: Symbol -> Symbol
symbolToRaw = id
-- | does a smybol match a raw symbol?
matches :: Symbol -> Symbol -> Bool
matches s1 s2 = s1 == s2
-- | application function for Symbol Maps
applySymMap :: Map.Map Symbol Symbol -> Symbol -> Symbol
applySymMap smap idt = Map.findWithDefault idt idt smap
| nevrenato/HetsAlloy | Propositional/Symbol.hs | gpl-2.0 | 2,366 | 0 | 16 | 569 | 471 | 269 | 202 | 43 | 1 |
module Access.Data.Time.Clock.POSIX
( module Data.Time.Clock.POSIX
) where
import Data.Time.Clock.POSIX
import Access.Core
class Access io => POSIXTimeAccess io where
getPOSIXTime' :: io POSIXTime
instance POSIXTimeAccess IO where
getPOSIXTime' = getPOSIXTime
| bheklilr/time-io-access | Access/Data/Time/Clock/POSIX.hs | gpl-2.0 | 282 | 0 | 7 | 51 | 68 | 40 | 28 | 8 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Monad
import Control.Monad.Trans (liftIO)
import Control.Monad.Trans.Either (EitherT(..),left,right)
import Control.Monad.Trans.Maybe
-- import Data.Attoparsec.Lazy
import qualified Data.Aeson.Generic as G
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Foldable (foldrM)
import Data.Maybe
import System.Environment
import System.IO
--
import HEP.Storage.WebDAV.CURL
import HEP.Storage.WebDAV.Type
-- import HEP.Storage.WebDAV.Util
import HEP.Util.Either
--
import HEP.Physics.Analysis.ATLAS.Common
import HEP.Physics.Analysis.ATLAS.SUSY.SUSY_1to2L2to6JMET_8TeV
import HEP.Physics.Analysis.Common.XSecNTotNum
import HEP.Physics.Analysis.Common.Prospino
import HEP.Util.Work
--
import Util
import Debug.Trace
m_neutralino :: Double
m_neutralino = 500
datalst :: [ (Double,Double) ]
datalst = [ (mg,mn) | mg <- [ 200,250..1500 ], mn <- [ 50,100..mg-50] ]
-- datalst = [ (mq,mn) | mq <- [ 200,250..1300], mn <- [ 50,100..mq-50 ] ]
-- datalst = [ (1300,300) ]
checkFiles :: DataFileClass -> String -> IO (Either String ())
checkFiles c procname = do
rs <- forM datalst (\s -> (doJob (checkFileExistInDAV_lep c) . createRdirBName procname) s
>>= return . maybe (show s) (const []) . head)
let missinglst = filter (not.null) rs
nmiss = length missinglst
mapM_ (\x -> putStrLn (" , " ++ x)) missinglst
if null missinglst then return (Right ()) else return (Left (show nmiss ++ " files are missing"))
minfty :: Double
minfty = 50000.0
-- kFactor = 2.0
-- | in pb^-1 unit
luminosity = 20300
createRdirBName procname (mg,mn) =
let rdir = "montecarlo/admproject/SimplifiedSUSYlep/8TeV/scan_" ++ procname
basename = "SimplifiedSUSYlepN" ++ show mn ++ "G"++show mg ++ "QL" ++ show minfty ++ "C"++show (0.5*(mn+mg))++ "L" ++ show minfty ++ "NN" ++ show minfty ++ "_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set"
in (rdir,basename)
dirset = [ "1step_2sg" ]
atlas_20_3_fbinv_at_8_TeV :: WebDAVConfig -> WebDAVRemoteDir -> String
-> EitherT String IO (CrossSectionAndCount,HistEType,[(EType,Double)],Double)
atlas_20_3_fbinv_at_8_TeV wdavcfg wdavrdir bname = do
let fp1 = bname ++ "_ATLAS_1to2L2to6JMET_8TeV.json"
fp2 = bname ++ "_total_count.json"
kfactorfp = bname ++ "_xsecKfactor.json"
--
guardEitherM (fp1 ++ " not exist!") (doesFileExistInDAV wdavcfg wdavrdir fp1)
(_,mr1) <- liftIO (downloadFile True wdavcfg wdavrdir fp1)
r1 <- (liftM LB.pack . EitherT . return . maybeToEither (fp1 ++ " is not downloaded ")) mr1
(result :: HistEType) <- (EitherT . return . maybeToEither (fp1 ++ " JSON cannot be decoded") . G.decode) r1
--
guardEitherM (fp2 ++ " not exist") (doesFileExistInDAV wdavcfg wdavrdir fp2)
(_,mr2) <- liftIO (downloadFile True wdavcfg wdavrdir fp2)
r2 <- (liftM LB.pack . EitherT . return . maybeToEither (fp2 ++ " is not downloaded ")) mr2
(xsec :: CrossSectionAndCount)
<- (EitherT . return . maybeToEither (fp2 ++ " JSON cannot be decoded") .G.decode) r2
--
guardEitherM (kfactorfp ++ " not exist") (doesFileExistInDAV wdavcfg wdavrdir kfactorfp)
(_,mrk) <- liftIO (downloadFile True wdavcfg wdavrdir kfactorfp)
rk <- (liftM LB.pack . EitherT . return . maybeToEither (kfactorfp ++ " is not downloaded ")) mrk
liftIO$ print rk
(result_kfactor :: CrossSectionResult)
<- (EitherT . return . maybeToEither (kfactorfp ++ " JSON cannot be decoded") .G.decode) rk
--
let kFactor = xsecKFactor result_kfactor
weight = crossSectionInPb xsec * luminosity * kFactor / fromIntegral (numberOfEvent xsec)
hist = map (\(x,y) -> (x,fromIntegral y * weight)) result
getratio (x,y) = do y' <- lookup x limitOfNBSM
return (y/ y')
maxf (x,y) acc = do r <- getratio (x,y)
return (max acc r)
--
maxratio <- (EitherT . return . maybeToEither "in atlas_xx:foldrM" . foldrM maxf 0) hist
return (xsec, result, hist, maxratio)
getResult f (rdir,basename) = do
let nlst = [1]
fileWork f "config1.txt" rdir basename nlst
mainAnalysis = do
outh <- openFile ("simplifiedsusylep_1step_2sg_8TeV.dat") WriteMode
mapM_ (\(mg,mn,r) -> hPutStrLn outh (show mg ++ ", " ++ show mn ++ ", " ++ show r))
=<< forM datalst ( \(x,y) -> do
r <- runEitherT $ do
let analysis = getResult atlas_20_3_fbinv_at_8_TeV . createRdirBName "1step_2sg"
-- simplify = fmap head . fmap catMaybes . EitherT
takeHist (_,_,h,_) = h
t_2sg <- (fmap head . analysis) (x,y)
let h_2sg = takeHist t_2sg
totalsr = mkTotalSR [h_2sg]
r_ratio = getRFromSR totalsr
return (x :: Double, y :: Double, r_ratio)
case r of
Left err -> error err
Right result -> return result
)
hClose outh
mainCheck = do
r <- runEitherT $ mapM_ (EitherT . checkFiles {- ChanCount -} Prospino) dirset
print r
mainCount = do
r <- runEitherT (countEvent "1step_2sg")
case r of
Left err -> putStrLn err
Right _ -> return ()
main = do
args <- getArgs
case args !! 0 of
"count" -> mainCount
"check" -> mainCheck
"analysis" -> mainAnalysis
countEvent :: String -> EitherT String IO ()
countEvent str = do
EitherT (checkFiles RawData str)
liftIO $ forM_ datalst (getCount.createRdirBName str)
getCount (rdir,basename) = do
let nlst = [1]
r1 <- work (\wdavcfg wdavrdir nm -> getXSecNCount XSecLHE wdavcfg wdavrdir nm >>= getJSONFileAndUpload wdavcfg wdavrdir nm)
"config1.txt"
rdir
basename
nlst
print r1
r2 <- work atlas_SUSY_1to2L2to6JMET_8TeV "config1.txt" rdir basename nlst
print r2
| wavewave/lhc-analysis-collection | analysis/SimplifiedSUSY_ATLAS1to2L2to6JMET_8TeV.hs | gpl-3.0 | 6,020 | 2 | 23 | 1,423 | 1,937 | 1,002 | 935 | 121 | 3 |
{-|
Module: Ice.Gauss
Description: Functions for Gaussian elimination used in Ice.
-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Ice.Gauss
(
-- * Forward elimination
performElimination
-- * Backward elimination
, performBackElim
-- * Auxiliary functions
, choosePoints)
where
import Control.Arrow
import Control.Monad.RWS
import Control.Monad.Random
import qualified Data.Array.Repa as R
import Data.Array.Repa hiding (map, (++))
import Data.Int (Int64)
import Data.List
import qualified Data.Map.Strict as Map
import Data.Proxy
import Data.Reflection
import qualified Data.Vector as BV
import qualified Data.Vector.Unboxed as V
import Ice.Fp
import Ice.Types
-- | Perform forward elimination, either once or many times, depending
-- on the desired upper bound for the probability of failure.
performElimination :: IceMonad ()
performElimination = do
s <- gets system
c <- ask
(p, rs', _, j, i) <- case s of
FpSystem p _ rs -> return $ withMod p $ probeStep [] (buildRowTree (eqsToRows rs)) 1 [] []
PolynomialSystem _ -> iteratedForwardElim
FpSolved _ _ _ _ -> error "Internal error: tried solving a solved system. Please report this as a bug."
let i' = (if sortList c then sort else id) (V.toList i)
modify (\ x -> x {system = FpSolved p rs' i' j})
where
-- | Inject modulus to be used in the forward elimination.
withMod :: Int64
-> (forall s . Reifies s Int64 => EliminationResult s)
-> (Int64, [V.Vector (Int, Int64)], Int64, V.Vector Int, V.Vector Int)
withMod m x = reify m (\ (_ :: Proxy s) -> (unwrap (x :: EliminationResult s)))
where unwrap (EliminationResult p rs d j i) = (p,map (V.map (second unFp)) rs, unFp d, j, i)
eqsToRows :: forall s . Reifies s Int64 => [Equation Int64] -> BV.Vector (Row s)
eqsToRows = BV.fromList . map (V.convert . BV.map (second fromIntegral))
-- | Performs forward elimination on a linear system over F_p.
probeStep :: forall s . Reifies s Int64
=> [Row s]
-> RowTree s
-> Fp s Int64
-> [Int]
-> [Int]
-> EliminationResult s
probeStep !rsDone !rs !d !j !i
| Map.null rs = EliminationResult p rsDone d (V.fromList . reverse $ j) (V.fromList . reverse $ i)
| otherwise =
probeStep rsDone' rows' d' j' i'
where
(pivotRow, otherRows) = Map.deleteFindMin rs
(RowKey _ _ _ pivotRowNumber) = fst pivotRow
(pivotColumn, pivotElement) = (V.head . snd) pivotRow
(rowsToModify, ignoreRows) = Map.split (RowKey (pivotColumn+1) 0 0 0) otherRows
invPivotElement = recip pivotElement
!normalisedPivotRow = second (multRow invPivotElement) pivotRow
d' = d * pivotElement
j' = pivotColumn:j
pivotOperation !row =
let (_,x) = V.head row
in addRows (multRow (-x) (snd normalisedPivotRow)) row
modifiedRows = updateRowTree pivotOperation rowsToModify
rows' = foldl' (\ m (k, v) -> Map.insert k v m) ignoreRows modifiedRows
i' = pivotRowNumber:i
rsDone' = snd normalisedPivotRow:rsDone
p = getModulus d
-- | This function solves multiple images of the original system, in
-- order to reduce the bound on the probability of failure below the
-- value specified by the --failbound option.
iteratedForwardElim :: IceMonad (Int64, [V.Vector (Int, Int64)], Int64, V.Vector Int, V.Vector Int)
iteratedForwardElim = do
PolynomialSystem eqs <- gets system
goal <- asks failBound
(p0, xs0) <- choosePoints
let (!rs',_,!j,!i) = withMod p0 $ oneForwardElim xs0 eqs
r0 = V.length i
bound0 = getBound (fromIntegral r0) p0
showBound b = info $ "The probability that too many equations were discarded is less than " ++ show b ++ "\n"
showBound bound0
if bound0 < goal
then return (p0, rs', undefined, j, i)
else let redoTest r bound rs = do
info "Iterating to decrease probability of failure."
(p, xs) <- choosePoints
let (_,_,_,i') = withMod p $ oneForwardElim xs eqs
r' = V.length i'
result = case compare (r,i) (r',i') of
EQ -> Good (getBound (fromIntegral r) p)
LT -> Restart
GT -> Unlucky
case result of
Good bound' -> let bound'' = bound * bound'
in
showBound bound'' >>
if bound'' < goal then return (p, rs', undefined, j, i)
else redoTest r bound'' rs
Restart -> info "Unlucky evaluation point(s), restarting." >>
iteratedForwardElim
Unlucky -> info "Unlucky evaluation point, discarding." >>
redoTest r bound splitRows
splitRows = partitionEqs (V.toList i) eqs
in redoTest r0 bound0 splitRows
where
withMod :: Int64
-> (forall s . Reifies s Int64
=> ([Row s], Fp s Int64, V.Vector Int, V.Vector Int))
-> ([V.Vector (Int, Int64)], Int64, V.Vector Int, V.Vector Int)
withMod m x = reify m (\ (_ :: Proxy s) -> (unwrap (x :: ([Row s], Fp s Int64, V.Vector Int, V.Vector Int))))
unwrap (rs,d,j,i) = (map (V.map (second unFp)) rs,unFp d,j,i)
-- | Given the supposed rank of the system and the prime number used,
-- calculate an upper bound on the probability of failure.
getBound :: Int64 -> Int64 -> Double
getBound r p = 1 - product [1- (fromIntegral x / fromIntegral p) | x <- [1..r]]
-- | split equations into linearly independent and linealy dependent
-- ones (given the list i of linearly independent equations),
-- preserving the permutation.
partitionEqs :: [Int] -> [a] -> ([a], [a])
partitionEqs is rs = first reverse . (map snd *** map snd) $ foldl' step ([], rs') is
where
rs' = [(i,rs Data.List.!! i) | i <- [0..length rs - 1]]
step (indep, dep) i = (eq:indep, dep')
where ([eq], dep') = partition ((==i) . fst) dep
-- | Maps a linear system over polynomials to F_p, and performs forward elimination.
oneForwardElim :: forall s . Reifies s Int64
=> V.Vector Int64
-> [Equation MPoly]
-> ([Row s], Fp s Int64, V.Vector Int, V.Vector Int)
oneForwardElim xs rs = (rs',d,j,i) where
(EliminationResult _ rs' d j i) = probeStep [] (buildRowTree m) 1 [] []
m = evalIbps xs' rs
xs' = fromUnboxed (Z :. V.length xs) (V.map normalise xs :: V.Vector (Fp s Int64))
-- | Evaluate the polynomials in the IBP equations.
evalIbps :: forall s . Reifies s Int64
=> Array U DIM1 (Fp s Int64)
-> [Equation MPoly]
-> BV.Vector (Row s)
evalIbps xs rs = BV.fromList (map treatRow rs) where
{-# INLINE toPoly #-}
toPoly (MPoly (cs, es)) = Poly (R.fromUnboxed (Z :. BV.length cs) $ (V.convert . BV.map fromInteger) cs) es
treatRow r = V.filter ((/=0) . snd) $ V.zip (V.convert (BV.map fst r)) (multiEvalBulk xs (BV.map (toPoly . snd) r))
performBackElim :: IceMonad ()
performBackElim = do
info "Perform Backwards elimination.\n"
forward@(FpSolved p rs _ _) <- gets system
nOuter <- liftM (Map.size . fst) $ gets integralMaps
let rs' = withMod p $
backGauss ([], map (V.map (second normalise))
((reverse
. dropWhile ((< nOuter) . fst . V.head)
. reverse) rs))
modify (\ x -> x { system = forward {image = rs'} })
where
withMod :: Int64
-> (forall s . Reifies s Int64 => (Fp s Int64, [V.Vector (Int, Fp s Int64)]))
-> [V.Vector (Int, Int64)]
withMod p rs =
let (_, res) = reify p (\ (_ :: Proxy s) -> (unFp *** map (V.map (second unFp))) (rs :: (Fp s Int64, [V.Vector (Int, Fp s Int64)])))
in res
-- | Inject a concrete value for the prime number used as modulus in backwards elimination.
-- | Backwards Gaussian elimination.
backGauss :: forall s . Reifies s Int64
=> ([Row s], [Row s])
-> (Fp s Int64, [Row s])
backGauss (!rsDone, []) = (1, rsDone)
backGauss (!rsDone, !pivotRow:(!rs)) = backGauss (pivotRow:rsDone, rs')
where
(pivotColumn, invPivot) = second recip (V.head pivotRow)
rs' = map pivotOperation rs
pivotOperation row = case V.find ((==pivotColumn) . fst) row of
Nothing -> row
Just (_, elt) -> addRows (multRow (-elt*invPivot) pivotRow) row
-- | A list of pre-generated prime numbers such that the square just fits into a 64bit Integer.
pList :: [Int64]
pList = [3036998333,3036998347,3036998381,3036998401,3036998429,3036998449,3036998477
,3036998537,3036998561,3036998563,3036998567,3036998599,3036998611,3036998717
,3036998743,3036998759,3036998761,3036998777,3036998803,3036998837,3036998843
,3036998849,3036998857,3036998873,3036998903,3036998933,3036998957,3036998963
,3036998977,3036998989,3036998999,3036999001,3036999019,3036999023,3036999061
,3036999067,3036999079,3036999089,3036999101,3036999113,3036999137,3036999157
,3036999167,3036999209,3036999233,3036999271,3036999283,3036999293,3036999307
,3036999319,3036999341,3036999379,3036999403,3036999431,3036999439,3036999443
,3036999457,3036999467,3036999473,3036999487,3036999499,3036999727,3036999733
,3036999737,3036999739,3036999761,3036999769,3036999773,3036999803,3036999811
,3036999817,3036999821,3036999841,3036999877,3036999887,3036999899,3036999941
,3036999983,3036999991,3037000013,3037000039,3037000069,3037000103,3037000111
,3037000121,3037000159,3037000177,3037000181,3037000193,3037000249,3037000289
,3037000303,3037000331,3037000333,3037000391,3037000399,3037000427,3037000429
,3037000453,3037000493]
-- | Choose a large prime and an evaluation point randomly.
choosePoints :: IceMonad (Int64, V.Vector Int64)
choosePoints = do
nInvs <- asks (length . invariants)
p <- liftIO $ liftM2 (!!) (return pList) (getRandomR (0,length pList - 1))
xs <- liftIO $ V.generateM nInvs (\_ -> getRandomR (1,p))
info $ "Probing for p = " ++ show p ++ "\n"
info $ "Random points: " ++ show (V.toList xs) ++ "\n"
return (p, xs)
| kantp/ice | Ice/Gauss.hs | gpl-3.0 | 10,497 | 103 | 16 | 2,769 | 3,386 | 1,854 | 1,532 | 179 | 7 |
module Plugins.Sql where
import Database.HDBC
import Database.HDBC.Sqlite3
import Plugins.Html
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html4.Transitional.Attributes as A
import qualified Data.ByteString
import Data.Char
fun = do
conn <- connectSqlite3 "new.db"
quickQuery' conn "SELECT * from mytable" []
unSql (SqlByteString x) = x
sqlite_query db str = do
conn <- connectSqlite3 db
statement <- prepare conn str
-- results <- quickQuery' conn str []
i <- execute statement []
i2 <- getColumnNames statement
results <- fetchAllRows' statement
return ( [i2] ++ (map (map ( map (chr. fromIntegral). Data.ByteString.unpack . unSql)) results))
| xpika/interpreter-haskell | Plugins/Sql.hs | gpl-3.0 | 697 | 0 | 19 | 120 | 215 | 113 | 102 | 19 | 1 |
module Tile.Query (evalTileQuery) where
import Declare
import Dir
import History
import State
import Types
import Data.List hiding (filter, lookup)
import Data.Maybe
type TileQueryResult = [(TileRef, Maybe (History TileRef))]
evalTileQuery :: TileQuery -> Config -> World -> TileQueryResult
evalTileQuery tq c wo = nubBy (\a b -> fst a == fst b) $ eval tq c wo
nonHist :: TileRef -> TileQueryResult
nonHist = nonHists . (: [])
nonHists :: [TileRef] -> TileQueryResult
nonHists = map (, Nothing)
evalSR :: Config -> World -> QuerySpaceRef -> [SpaceRef]
evalSR c _ QRAllSpaces = keys $ cSpaces c
evalSR _ w QRCurSpace = [getSpaceRef $ wFocus w]
evalSR c _ (QROneSpace sr) = filter (== sr) $ keys $ cSpaces c
evalTR :: Config -> World -> SpaceRef -> QueryTileRef -> [TileRef]
evalTR c w sr QRAllTiles = mkFloatRef sr : evalTR c w sr QRAllNonFloatTiles
evalTR c _ sr QRAllNonFloatTiles =
concatMap (keys . laTiles . spLayout)
$ maybeToList
$ lookup sr
$ cSpaces c
evalTR _ w sr QRCurTile =
maybeToList
$ lookup sr
$ wFocuses w
evalTR _ w sr (QROneTile n) = case lookup tr $ wTiles w of
Nothing -> []
Just _ -> [tr]
where
tr = mkTileFloatRef sr n
eval :: TileQuery -> Config -> World -> TileQueryResult
eval (QRef sr tr) c wo = nonHists $ do
sr' <- evalSR c wo sr
evalTR c wo sr' tr
eval QHistBack _ wo = evalHist histBack wo
eval QHistFwd _ wo = evalHist histFwd wo
eval (QDir dir) c wo =
nonHists $ maybeToList $ followDir c dir (getFocusTile wo) $ wHistory wo
eval (QDisjunct tqs) c wo = tqs >>= \tq -> eval tq c wo
eval (QDifference as bs) c wo =
deleteFirstsBy (\a b -> fst a == fst b) as' bs'
where
as' = eval as c wo
bs' = eval bs c wo
eval (QEmptiest tq) c wo =
-- TODO is the built-in sortBy stable?
map snd
$ sortBy (\a b -> compare (fst a) (fst b))
$ map (\(tr, h) -> (size $ wTiles wo ! tr, (tr, h)))
$ eval tq c wo
evalHist
:: (TileRef -> History TileRef -> Maybe (TileRef, History TileRef))
-> World
-> TileQueryResult
evalHist f wo = case f (wFocus wo) (wHistory wo) of
Nothing -> []
Just (tr, h) -> [(tr, Just h)]
| ktvoelker/argon | src/Tile/Query.hs | gpl-3.0 | 2,110 | 0 | 13 | 476 | 941 | 480 | 461 | -1 | -1 |
module Object
( Object()
, newObject
, newObjectIO
, readObject
, readObjectIO
, writeObject
, modifyObject
, modifyObject'
, swapObject
, useObject
, overObject
, overObject'
) where
import Control.Concurrent.STM
import Control.Lens
import Control.Monad.STM.Class
import H.IO
import H.Prelude
import System.IO.Unsafe
data Object a = Object { objectNumber :: Integer, objectVar :: (TVar a) }
deriving (Eq)
instance Ord (Object a) where
compare (Object m _) (Object n _) = compare m n
{-# NOINLINE counter #-}
counter :: TVar Integer
counter = unsafePerformIO $ newTVarIO 0
newObject :: (MonadSTM m) => a -> m (Object a)
newObject x = liftSTM $ do
n <- readTVar counter
v <- newTVar x
writeTVar counter $ n + 1
pure $ Object { objectNumber = n, objectVar = v }
newObjectIO :: a -> IO (Object a)
newObjectIO = atomically . newObject
readObject :: (MonadSTM m) => Object a -> m a
readObject = liftSTM . readTVar . objectVar
readObjectIO :: Object a -> IO a
readObjectIO = readTVarIO . objectVar
writeObject :: (MonadSTM m) => Object a -> a -> m ()
writeObject obj = liftSTM . writeTVar (objectVar obj)
modifyObject :: (MonadSTM m) => Object a -> (a -> a) -> m ()
modifyObject obj = liftSTM . modifyTVar (objectVar obj)
modifyObject' :: (MonadSTM m) => Object a -> (a -> a) -> m ()
modifyObject' obj = liftSTM . modifyTVar' (objectVar obj)
swapObject :: (MonadSTM m) => Object a -> a -> m a
swapObject obj = liftSTM . swapTVar (objectVar obj)
useObject :: (MonadSTM m) => Getting a s a -> Object s -> m a
useObject q obj = liftSTM $ view q <$> readObject obj
overObject :: (MonadSTM m) => ASetter s s a b -> (a -> b) -> Object s -> m ()
overObject q f obj = liftSTM $ modifyObject obj $ over q f
overObject' :: (MonadSTM m) => ASetter s s a b -> (a -> b) -> Object s -> m ()
overObject' q f obj = liftSTM $ modifyObject' obj $ over q f
| ktvoelker/airline | src/Object.hs | gpl-3.0 | 1,887 | 0 | 10 | 399 | 793 | 408 | 385 | 54 | 1 |
module TestParse
(tests)
where
import Test.HUnit(Assertion,Test(..),assertFailure)
import Ast(Identifier(..),PartialDef(..),Param(..),Unparsed(..))
import Compile(compile)
import Parse(parse)
tests :: Test
tests = TestList [
TestCase testSimple,
TestCase testTwo,
TestCase testComment,
TestCase testLiteral,
TestCase testLiteral2,
TestCase testBoundParameter,
TestCase testLiteralParameter,
TestCase testIgnoreParameter,
TestCase testImplicitParameter,
TestCase testTwoParameters
]
testParse :: String -> String -> ([PartialDef] -> Bool) -> Assertion
testParse label code checkResult =
either (assertFailure . ((label ++ ":") ++) . show)
(\ result ->
if checkResult result then return () else assertFailure label)
(compile (parse "(test)" code))
testSimple :: Assertion
testSimple = testParse "testSimple" "f=." checkResult
where
checkResult [PartialDef (Identifier _ "f") [] []] = True
checkResult _ = False
testTwo :: Assertion
testTwo = testParse "testTwo" "f=.g=." checkResult
where
checkResult [PartialDef (Identifier _ "f") [] [],
PartialDef (Identifier _ "g") [] []] = True
checkResult _ = False
testComment :: Assertion
testComment = testParse "testComment" "f==.g=.\n1=1." checkResult
where
checkResult [PartialDef (Identifier _ "f")
[ParamIgnored _ [True]]
[UnparsedLiteral _ [True]]] = True
checkResult _ = False
testLiteral :: Assertion
testLiteral = testParse "testLiteral" "f=0110." checkResult
where
checkResult [PartialDef (Identifier _ "f") []
[UnparsedLiteral _ [False,True,True,False]]] = True
checkResult _ = False
testLiteral2 :: Assertion
testLiteral2 = testParse "testLiteral2" "f=0101_ 011." checkResult
where
checkResult [PartialDef (Identifier _ "f") []
[UnparsedLiteral _ [False,True,False,True],
UnparsedLiteral _ [False,True,True]]] = True
checkResult _ = False
testBoundParameter :: Assertion
testBoundParameter = testParse "testBoundParameter" "f 01a=10a." checkResult
where
checkResult [PartialDef (Identifier _ "f")
[ParamBound _ [False,True] (Identifier _ "a")]
[UnparsedLiteral _ [True,False],
UnparsedIdentifier (Identifier _ "a")]] = True
checkResult _ = False
testLiteralParameter :: Assertion
testLiteralParameter =
testParse "testImplicitParameter" "f 01_=f 01." checkResult
where
checkResult [PartialDef (Identifier _ "f")
[ParamLiteral _ [False,True]]
[UnparsedIdentifier (Identifier _ "f"),
UnparsedLiteral _ [False,True]]] = True
checkResult _ = False
testIgnoreParameter :: Assertion
testIgnoreParameter =
testParse "testImplicitParameter" "f 01.=f 01." checkResult
where
checkResult [PartialDef (Identifier _ "f")
[ParamIgnored _ [False,True]]
[UnparsedIdentifier (Identifier _ "f"),
UnparsedLiteral _ [False,True]]] = True
checkResult _ = False
testImplicitParameter :: Assertion
testImplicitParameter =
testParse "testImplicitParameter" "f 01=f 01." checkResult
where
checkResult [PartialDef (Identifier _ "f")
[ParamIgnored _ [False,True]]
[UnparsedIdentifier (Identifier _ "f"),
UnparsedLiteral _ [False,True]]] = True
checkResult _ = False
testTwoParameters :: Assertion
testTwoParameters = testParse "testTwoParameters" "f 01a b=10a b." checkResult
where
checkResult [PartialDef (Identifier _ "f")
[ParamBound _ [False,True] (Identifier _ "a"),
ParamBound _ [] (Identifier _ "b")]
[UnparsedLiteral _ [True,False],
UnparsedIdentifier (Identifier _ "a"),
UnparsedIdentifier (Identifier _ "b")]] = True
checkResult _ = False
| qpliu/esolang | 01_/hs/compiler2/TestParse.hs | gpl-3.0 | 4,231 | 0 | 13 | 1,252 | 1,167 | 622 | 545 | 90 | 2 |
-- -*-haskell-*-
-- Vision (for the Voice): an XMMS2 client.
--
-- Author: Oleg Belozeorov
-- Created: 10 Sep. 2010
--
-- Copyright (C) 2010 Oleg Belozeorov
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3 of
-- the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- General Public License for more details.
--
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module Properties.Order
( OrderDialog
, makeOrderDialog
, showOrderDialog
, encodeOrder
) where
import Control.Monad
import Graphics.UI.Gtk
import UI
import Editor
import Properties.Property
import Properties.Model
import Properties.View
type OrderDialog = EditorDialog (PropertyView Bool)
showOrderDialog ::
WithUI
=> OrderDialog
-> IO [(Property, Bool)]
-> ([(Property, Bool)] -> IO ())
-> IO ()
showOrderDialog dialog getOrder setOrder =
runEditorDialog dialog getOrder setOrder False window
makeOrderDialog :: WithModel => (OrderDialog -> IO a) -> IO OrderDialog
makeOrderDialog =
makeEditorDialog [(stockApply, ResponseApply)] makeOrderView
makeOrderView :: WithModel => t -> IO () -> IO (PropertyView Bool)
makeOrderView parent onState = do
view <- makePropertyView (, False) parent onState
let store = propertyViewStore view
right = propertyViewRight view
treeViewSetRulesHint right True
column <- treeViewColumnNew
treeViewColumnSetTitle column "Order"
treeViewAppendColumn right column
cell <- cellRendererComboNew
treeViewColumnPackStart column cell True
cellLayoutSetAttributes column cell store $ \(_, dir) ->
[ cellText := dirToString dir ]
cmod <- listStoreNewDND [False, True] Nothing Nothing
let clid = makeColumnIdString 0
customStoreSetColumn cmod clid dirToString
cell `set` [ cellTextEditable := True
, cellComboHasEntry := False
, cellComboTextModel := (cmod, clid) ]
cell `on` edited $ \[n] str -> do
(prop, dir) <- listStoreGetValue store n
let dir' = stringToDir str
unless (dir' == dir) $
listStoreSetValue store n (prop, dir')
return view
dirToString :: Bool -> String
dirToString False = "Ascending"
dirToString True = "Descending"
stringToDir :: String -> Bool
stringToDir = ("Descending" ==)
encodeOrder :: [(Property, Bool)] -> [String]
encodeOrder = map enc
where enc (prop, False) = propKey prop
enc (prop, True) = '-' : propKey prop
| upwawet/vision | src/Properties/Order.hs | gpl-3.0 | 2,763 | 0 | 14 | 532 | 658 | 349 | 309 | -1 | -1 |
module HFlint.FMPZPoly.Base
where
import Control.DeepSeq ( NFData(..) )
import Data.Composition ( (.:) )
import qualified Data.Vector as V
import Data.Vector ( Vector )
import Foreign.C.String ( peekCString
, withCString
)
import Foreign.Marshal ( free )
import System.IO.Unsafe ( unsafePerformIO )
import HFlint.Internal.Lift
import HFlint.FMPZ ()
import HFlint.FMPZ.FFI
import HFlint.FMPZPoly.FFI
--------------------------------------------------------------------------------
-- Show, Eq, NFData
--------------------------------------------------------------------------------
instance Show FMPZPoly where
show a = unsafePerformIO $
withCString "T" $ \cvar -> do
(_,cstr) <- withFMPZPoly a $ \aptr ->
fmpz_poly_get_str_pretty aptr cvar
str <- peekCString cstr
free cstr
return str
instance Eq FMPZPoly where
(==) = (1==) .: (lift2Flint0 fmpz_poly_equal)
instance NFData FMPZPoly where
rnf _ = ()
--------------------------------------------------------------------------------
-- coefficient access
--------------------------------------------------------------------------------
(!) :: FMPZPoly -> Int -> FMPZ
(!) a n = unsafePerformIO $
withNewFMPZ_ $ \bptr ->
withFMPZPoly a $ \aptr ->
fmpz_poly_get_coeff_fmpz bptr aptr (fromIntegral n)
--------------------------------------------------------------------------------
-- conversion
--------------------------------------------------------------------------------
fromFMPZ :: FMPZ -> FMPZPoly
fromFMPZ a = unsafePerformIO $
withNewFMPZPoly_ $ \bptr ->
withFMPZ_ a $ \aptr ->
fmpz_poly_set_fmpz bptr aptr
fromVector :: Vector FMPZ -> FMPZPoly
fromVector as = unsafePerformIO $
withNewFMPZPoly_ $ \bptr -> do
fmpz_poly_realloc bptr (fromIntegral $ V.length as)
sequence_ $ flip V.imap as $ \ix a ->
withFMPZ_ a $ \aptr ->
fmpz_poly_set_coeff_fmpz bptr (fromIntegral ix) aptr
toVector :: FMPZPoly -> Vector FMPZ
toVector a = unsafePerformIO $ fmap snd $
withFMPZPoly a $ \aptr -> do
deg <- fromIntegral <$> fmpz_poly_degree aptr
V.generateM (deg+1) $ \ix ->
withNewFMPZ_ $ \bptr ->
fmpz_poly_get_coeff_fmpz bptr aptr (fromIntegral ix)
where
fromList :: [FMPZ] -> FMPZPoly
fromList = fromVector . V.fromList
toList :: FMPZPoly -> [FMPZ]
toList = V.toList . toVector
fromIntegers :: [Integer] -> FMPZPoly
fromIntegers = fromVector . V.map fromInteger . V.fromList
toIntegers :: FMPZPoly -> [Integer]
toIntegers = V.toList . V.map toInteger . toVector
--------------------------------------------------------------------------------
-- composition
--------------------------------------------------------------------------------
compose :: FMPZPoly -> FMPZPoly -> FMPZPoly
compose = lift2Flint_ fmpz_poly_compose
| martinra/hflint | src/HFlint/FMPZPoly/Base.hs | gpl-3.0 | 2,827 | 0 | 15 | 470 | 705 | 381 | 324 | 59 | 1 |
module Nucleic.IO (
Signal,
Edge,
signal,
behS,
pushS,
edge,
evtE,
pushE
) where
import Control.Monad.Trans ( liftIO )
import qualified FRP.Sodium as FRP
import FRP.Sodium (Behavior)
data Signal a = Signal (FRP.Behavior a) (a -> FRP.Reactive ())
data Edge a = Edge (FRP.Event a) (a -> FRP.Reactive ())
--data Port a = Port (FRP.Behavior a) (IO a)
signal :: a -> IO (Signal a)
signal x = do
(b, pb) <- liftIO $ FRP.sync $ FRP.newBehavior x
return $ Signal b pb
behS :: Signal a -> Behavior a
behS (Signal b _) = b
pushS :: Signal a -> a -> IO ()
pushS (Signal _ pB) = FRP.sync . pB
edge :: IO (Edge a)
edge = do
(e, pe) <- liftIO $ FRP.sync $ FRP.newEvent
return $ Edge e pe
evtE :: Edge a -> FRP.Event a
evtE (Edge e _) = e
pushE :: Edge a -> (a -> IO ())
pushE (Edge _ pe) = FRP.sync . pe
-- port :: FRP.Behavior a -> (a -> IO ()) -> Port a
-- port b out =
-- Port b out
-- portB :: Port a -> Behavior a
-- portB (Port b _) = b
-- outP :: Port a -> IO a
-- outP (Port pB pO) =
-- FRP.sync $ FRP.sample pB
| RayRacine/nucleic | Nucleic/IO.hs | gpl-3.0 | 1,079 | 0 | 10 | 292 | 413 | 220 | 193 | 30 | 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.Webmasters.Sitemaps.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists the [sitemaps-entries](\/webmaster-tools\/v3\/sitemaps) submitted
-- for this site, or included in the sitemap index file (if
-- \`sitemapIndex\` is specified in the request).
--
-- /See:/ <https://developers.google.com/webmaster-tools/search-console-api/ Google Search Console API Reference> for @webmasters.sitemaps.list@.
module Network.Google.Resource.Webmasters.Sitemaps.List
(
-- * REST Resource
SitemapsListResource
-- * Creating a Request
, sitemapsList
, SitemapsList
-- * Request Lenses
, slXgafv
, slUploadProtocol
, slSiteURL
, slAccessToken
, slUploadType
, slSitemapIndex
, slCallback
) where
import Network.Google.Prelude
import Network.Google.SearchConsole.Types
-- | A resource alias for @webmasters.sitemaps.list@ method which the
-- 'SitemapsList' request conforms to.
type SitemapsListResource =
"webmasters" :>
"v3" :>
"sites" :>
Capture "siteUrl" Text :>
"sitemaps" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "sitemapIndex" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] SitemapsListResponse
-- | Lists the [sitemaps-entries](\/webmaster-tools\/v3\/sitemaps) submitted
-- for this site, or included in the sitemap index file (if
-- \`sitemapIndex\` is specified in the request).
--
-- /See:/ 'sitemapsList' smart constructor.
data SitemapsList =
SitemapsList'
{ _slXgafv :: !(Maybe Xgafv)
, _slUploadProtocol :: !(Maybe Text)
, _slSiteURL :: !Text
, _slAccessToken :: !(Maybe Text)
, _slUploadType :: !(Maybe Text)
, _slSitemapIndex :: !(Maybe Text)
, _slCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SitemapsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'slXgafv'
--
-- * 'slUploadProtocol'
--
-- * 'slSiteURL'
--
-- * 'slAccessToken'
--
-- * 'slUploadType'
--
-- * 'slSitemapIndex'
--
-- * 'slCallback'
sitemapsList
:: Text -- ^ 'slSiteURL'
-> SitemapsList
sitemapsList pSlSiteURL_ =
SitemapsList'
{ _slXgafv = Nothing
, _slUploadProtocol = Nothing
, _slSiteURL = pSlSiteURL_
, _slAccessToken = Nothing
, _slUploadType = Nothing
, _slSitemapIndex = Nothing
, _slCallback = Nothing
}
-- | V1 error format.
slXgafv :: Lens' SitemapsList (Maybe Xgafv)
slXgafv = lens _slXgafv (\ s a -> s{_slXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
slUploadProtocol :: Lens' SitemapsList (Maybe Text)
slUploadProtocol
= lens _slUploadProtocol
(\ s a -> s{_slUploadProtocol = a})
-- | The site\'s URL, including protocol. For example:
-- \`http:\/\/www.example.com\/\`.
slSiteURL :: Lens' SitemapsList Text
slSiteURL
= lens _slSiteURL (\ s a -> s{_slSiteURL = a})
-- | OAuth access token.
slAccessToken :: Lens' SitemapsList (Maybe Text)
slAccessToken
= lens _slAccessToken
(\ s a -> s{_slAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
slUploadType :: Lens' SitemapsList (Maybe Text)
slUploadType
= lens _slUploadType (\ s a -> s{_slUploadType = a})
-- | A URL of a site\'s sitemap index. For example:
-- \`http:\/\/www.example.com\/sitemapindex.xml\`.
slSitemapIndex :: Lens' SitemapsList (Maybe Text)
slSitemapIndex
= lens _slSitemapIndex
(\ s a -> s{_slSitemapIndex = a})
-- | JSONP
slCallback :: Lens' SitemapsList (Maybe Text)
slCallback
= lens _slCallback (\ s a -> s{_slCallback = a})
instance GoogleRequest SitemapsList where
type Rs SitemapsList = SitemapsListResponse
type Scopes SitemapsList =
'["https://www.googleapis.com/auth/webmasters",
"https://www.googleapis.com/auth/webmasters.readonly"]
requestClient SitemapsList'{..}
= go _slSiteURL _slXgafv _slUploadProtocol
_slAccessToken
_slUploadType
_slSitemapIndex
_slCallback
(Just AltJSON)
searchConsoleService
where go
= buildClient (Proxy :: Proxy SitemapsListResource)
mempty
| brendanhay/gogol | gogol-searchconsole/gen/Network/Google/Resource/Webmasters/Sitemaps/List.hs | mpl-2.0 | 5,284 | 0 | 19 | 1,268 | 795 | 464 | 331 | 115 | 1 |
Subsets and Splits