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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- | Data.TSTP.F module
{-# LANGUAGE UnicodeSyntax #-}
module Data.TSTP.F where
import Data.TSTP.Formula (Formula (..))
import Data.TSTP.Role (Role (..))
import Data.TSTP.Source (Source (..))
-- | Main formula type, it contains all the elements and information
-- of a TSTP formula definition. While 'name', 'role', and 'formula'
-- are self-explanatory, 'source' is a messy meta-language in itself,
-- different ATPs may embed different amounts of information in it.
data F = F
{ formula ∷ Formula
, name ∷ String
, role ∷ Role
, source ∷ Source
}
deriving (Eq, Ord, Show, Read)
| agomezl/tstp2agda | src/Data/TSTP/F.hs | mit | 664 | 0 | 8 | 168 | 110 | 72 | 38 | 11 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-|
Module : Builtins
Description : Built-in components of the langauge and the intial context.
Copyright : (c) Michael Lopez, 2017
License : MIT
Maintainer : m-lopez (github)
Stability : unstable
Portability : non-portable
-}
module Builtins ( builtinsCtx ) where
import Expressions (
ExprName(..),
QType(..),
CType(..),
Expr(..) )
import Context ( Ctx(Ctx), Binding(BVar) )
import Util.DebugOr ( DebugOr, mkSuccess )
import Data.Int ( Int32 )
-- | Builders for unary intrinsics.
class AsUnaryIntrinsicData a where
asUnaryIntrinsic :: String -> String -> a -> Binding
-- | A builder for integer transformation intrinsics.
instance AsUnaryIntrinsicData (Int32 -> Int32) where
asUnaryIntrinsic sym id op = BVar (ExprName sym) t (Just $ EUnBuiltin sym id f)
where
t = Unquantified $ CTArrow [ CTI32 ] CTI32
f :: Expr -> DebugOr Expr
f arg = case arg of
ELitInt n -> mkSuccess $ ELitInt $ op n
_ -> fail "expected an integer value; found something else"
-- | A builder for Boolean transformation intrinsics.
instance AsUnaryIntrinsicData (Bool -> Bool) where
asUnaryIntrinsic sym id op = BVar (ExprName sym) t (Just $ EUnBuiltin sym id f)
where
t = Unquantified $ CTArrow [ CTBool ] CTBool
f arg = case arg of
ELitBool b -> mkSuccess $ ELitBool $ op b
_ -> fail "expected an Boolean value; found something else"
-- | Builders for binary intrinsics.
class AsBinaryIntrinsicData a where
asBinaryIntrinsic :: String -> String -> a -> Binding
-- | A binary operation binding builder.
instance AsBinaryIntrinsicData (Int32 -> Int32 -> Int32) where
asBinaryIntrinsic sym id op = BVar (ExprName sym) t (Just $ EBinBuiltin sym id f)
where
t = Unquantified $ CTArrow [ CTI32, CTI32 ] CTI32
f args = case args of
(ELitInt n, ELitInt m) -> mkSuccess $ ELitInt $ op n m
_ -> fail "expected an integer values; found something else"
-- | A binary integer predicate binding builder.
instance AsBinaryIntrinsicData (Int32 -> Int32 -> Bool) where
asBinaryIntrinsic sym id op = BVar (ExprName sym) t (Just $ EBinBuiltin sym id f)
where
t = Unquantified $ CTArrow [ CTI32, CTI32 ] CTBool
f args = case args of
(ELitInt n, ELitInt m) -> mkSuccess $ ELitBool $ op n m
_ -> fail "expected an integer values; found something else"
-- | A binary Boolean predicate binding builder.
instance AsBinaryIntrinsicData (Bool -> Bool -> Bool) where
asBinaryIntrinsic sym id op = BVar (ExprName sym) t (Just $ EBinBuiltin sym id f)
where
t = Unquantified $ CTArrow [ CTI32, CTI32 ] CTBool
f args = case args of
(ELitBool x, ELitBool y) -> mkSuccess $ ELitBool $ op x y
_ -> fail "expected an integer values; found something else"
-- | Builtin context.
builtinsCtx :: Ctx
builtinsCtx = Ctx [
asUnaryIntrinsic "-" "-_I32" ((\x -> -x) :: Int32 -> Int32),
asUnaryIntrinsic "not" "not" not,
asBinaryIntrinsic "+" "+_I32" ((+) :: Int32 -> Int32 -> Int32),
asBinaryIntrinsic "-" "-_I32" ((-) :: Int32 -> Int32 -> Int32),
asBinaryIntrinsic "*" "*_I32" ((*) :: Int32 -> Int32 -> Int32),
asBinaryIntrinsic "/" "/_I32" (div :: Int32 -> Int32 -> Int32),
asBinaryIntrinsic "rem" "rem_I32" (rem :: Int32 -> Int32 -> Int32),
asBinaryIntrinsic "or" "or" (||),
asBinaryIntrinsic "and" "and" (&&),
asBinaryIntrinsic "=" "=_I32" ((==) :: Int32 -> Int32 -> Bool),
asBinaryIntrinsic "<>" "<>_I32" ((/=) :: Int32 -> Int32 -> Bool),
asBinaryIntrinsic "<" "<_I32" ((<) :: Int32 -> Int32 -> Bool),
asBinaryIntrinsic "<=" "<=_I32" ((<=) :: Int32 -> Int32 -> Bool),
asBinaryIntrinsic ">" ">_I32" ((>) :: Int32 -> Int32 -> Bool),
asBinaryIntrinsic ">=" ">=_I32" ((>=) :: Int32 -> Int32 -> Bool) ]
| m-lopez/jack | src/Builtins.hs | mit | 3,872 | 0 | 12 | 899 | 1,141 | 612 | 529 | 62 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2018.M06.D22.Exercise where
import Data.Aeson
import Network.HTTP.Conduit
-- below import available via 1HaskellADay git repository
import Y2018.M06.D19.Exercise
{--
Okay, a rather simple exercise today involving a REST call.
You have an AWS Lambda function at:
--}
type Endpoint = FilePath
rpc :: Endpoint
rpc = "https://ukbj6r6veg.execute-api.us-east-1.amazonaws.com/echo-chamber"
{--
That takes an article ID and article text and returns a set of entities, or
key phrases of that article (... this is the work that it does ... in theory).
You have a set of article ids and texts extracted from the data archive that
we did analysis on before (see above import)
--}
-- Read in the articles and send them, one at a time, to the endpoint.
-- What is the response for each article?
processArticle :: Endpoint -> Article -> IO Value
processArticle endpoint art = undefined
| geophf/1HaskellADay | exercises/HAD/Y2018/M06/D22/Exercise.hs | mit | 927 | 0 | 7 | 155 | 74 | 47 | 27 | 10 | 1 |
import Text.ParserCombinators.Parsec hiding (spaces)
import System.Environment
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
spaces :: Parser ()
spaces = skipMany1 space
readExpr :: String -> String
readExpr input = case parse (spaces >> symbol) "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"
main :: IO ()
main = do
(expr:_) <- getArgs
putStrLn (readExpr expr)
| kenwilcox/WyScheme | parse.hs | mit | 428 | 0 | 9 | 85 | 153 | 77 | 76 | 14 | 2 |
import Data.Array
ts = [0,3,5,8,13]::[Double]
xs = [0,225,385,623,993]
x's= [75,77,80,74,72]
[t,x,x'] = [(listArray (0,4) l!) | l<-[ts,xs,x's]]
l::Int->(Int->Double)->Int->Double->Double
l n xs k x = product [(x-xs i)/(xs k-xs i)|i<-[0..(k-1)]++[(k+1)..n]]
alpha n xs j x = (1-2*(x-xs j)*sum[1/(xs j-xs k)|k<-filter (/=j) [0..n]])*(l n xs j x)^2::Double
beta n xs j x = (x-xs j)*(l n xs j x)^2::Double
h::Int->(Int->Double)->(Int->Double)->(Int->Double)->Double->Double
h n is os ms x = sum [os j*(alpha n is j x)+ms j*(beta n is j x)|j<-[0..n]]
| ducis/haskell-numerical-analysis-examples | A/hm.hs | mit | 561 | 0 | 14 | 92 | 510 | 276 | 234 | 11 | 1 |
module Handler.MentorProfile where
import Import
getMentorProfileR :: Handler Html
getMentorProfileR = do
defaultLayout $ do
setTitleI MsgSiteTitle
$(widgetFile "mentorprofile")
| silky/foot-in-the-door | Handler/MentorProfile.hs | mit | 200 | 0 | 12 | 41 | 45 | 22 | 23 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-snapshotoptions.html
module Stratosphere.ResourceProperties.ElasticsearchDomainSnapshotOptions where
import Stratosphere.ResourceImports
-- | Full data type definition for ElasticsearchDomainSnapshotOptions. See
-- 'elasticsearchDomainSnapshotOptions' for a more convenient constructor.
data ElasticsearchDomainSnapshotOptions =
ElasticsearchDomainSnapshotOptions
{ _elasticsearchDomainSnapshotOptionsAutomatedSnapshotStartHour :: Maybe (Val Integer)
} deriving (Show, Eq)
instance ToJSON ElasticsearchDomainSnapshotOptions where
toJSON ElasticsearchDomainSnapshotOptions{..} =
object $
catMaybes
[ fmap (("AutomatedSnapshotStartHour",) . toJSON) _elasticsearchDomainSnapshotOptionsAutomatedSnapshotStartHour
]
-- | Constructor for 'ElasticsearchDomainSnapshotOptions' containing required
-- fields as arguments.
elasticsearchDomainSnapshotOptions
:: ElasticsearchDomainSnapshotOptions
elasticsearchDomainSnapshotOptions =
ElasticsearchDomainSnapshotOptions
{ _elasticsearchDomainSnapshotOptionsAutomatedSnapshotStartHour = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-snapshotoptions.html#cfn-elasticsearch-domain-snapshotoptions-automatedsnapshotstarthour
edsoAutomatedSnapshotStartHour :: Lens' ElasticsearchDomainSnapshotOptions (Maybe (Val Integer))
edsoAutomatedSnapshotStartHour = lens _elasticsearchDomainSnapshotOptionsAutomatedSnapshotStartHour (\s a -> s { _elasticsearchDomainSnapshotOptionsAutomatedSnapshotStartHour = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/ElasticsearchDomainSnapshotOptions.hs | mit | 1,776 | 0 | 12 | 157 | 173 | 100 | 73 | 22 | 1 |
{-# OPTIONS -w -O0 #-}
{- |
Module : Modal/ATC_Modal.der.hs
Description : generated Typeable, ShATermConvertible instances
Copyright : (c) DFKI Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable(overlapping Typeable instances)
Automatic derivation of instances via DrIFT-rule Typeable, ShATermConvertible
for the type(s):
'Modal.AS_Modal.M_BASIC_ITEM'
'Modal.AS_Modal.RIGOR'
'Modal.AS_Modal.M_SIG_ITEM'
'Modal.AS_Modal.MODALITY'
'Modal.AS_Modal.M_FORMULA'
'Modal.ModalSign.ModalSign'
-}
{-
Generated by 'genRules' (automatic rule generation for DrIFT). Don't touch!!
dependency files:
Modal/AS_Modal.hs
Modal/ModalSign.hs
-}
module Modal.ATC_Modal () where
import ATerm.Lib
import CASL.AS_Basic_CASL
import CASL.ATC_CASL
import CASL.Sign
import Common.AS_Annotation
import Common.Id
import Data.Typeable
import Modal.AS_Modal
import Modal.ModalSign
import qualified Common.Lib.MapSet as MapSet
import qualified Data.List as List
import qualified Data.Map as Map
{-! for Modal.AS_Modal.M_BASIC_ITEM derive : Typeable !-}
{-! for Modal.AS_Modal.RIGOR derive : Typeable !-}
{-! for Modal.AS_Modal.M_SIG_ITEM derive : Typeable !-}
{-! for Modal.AS_Modal.MODALITY derive : Typeable !-}
{-! for Modal.AS_Modal.M_FORMULA derive : Typeable !-}
{-! for Modal.ModalSign.ModalSign derive : Typeable !-}
{-! for Modal.AS_Modal.M_BASIC_ITEM derive : ShATermConvertible !-}
{-! for Modal.AS_Modal.RIGOR derive : ShATermConvertible !-}
{-! for Modal.AS_Modal.M_SIG_ITEM derive : ShATermConvertible !-}
{-! for Modal.AS_Modal.MODALITY derive : ShATermConvertible !-}
{-! for Modal.AS_Modal.M_FORMULA derive : ShATermConvertible !-}
{-! for Modal.ModalSign.ModalSign derive : ShATermConvertible !-}
-- Generated by DrIFT, look but don't touch!
instance ShATermConvertible M_FORMULA where
toShATermAux att0 xv = case xv of
BoxOrDiamond a b c d -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
(att3, c') <- toShATerm' att2 c
(att4, d') <- toShATerm' att3 d
return $ addATerm (ShAAppl "BoxOrDiamond" [a', b', c', d'] []) att4
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "BoxOrDiamond" [a, b, c, d] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
case fromShATerm' b att1 of
{ (att2, b') ->
case fromShATerm' c att2 of
{ (att3, c') ->
case fromShATerm' d att3 of
{ (att4, d') ->
(att4, BoxOrDiamond a' b' c' d') }}}}
u -> fromShATermError "M_FORMULA" u
instance ShATermConvertible MODALITY where
toShATermAux att0 xv = case xv of
Simple_mod a -> do
(att1, a') <- toShATerm' att0 a
return $ addATerm (ShAAppl "Simple_mod" [a'] []) att1
Term_mod a -> do
(att1, a') <- toShATerm' att0 a
return $ addATerm (ShAAppl "Term_mod" [a'] []) att1
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "Simple_mod" [a] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
(att1, Simple_mod a') }
ShAAppl "Term_mod" [a] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
(att1, Term_mod a') }
u -> fromShATermError "MODALITY" u
instance ShATermConvertible M_SIG_ITEM where
toShATermAux att0 xv = case xv of
Rigid_op_items a b c -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
(att3, c') <- toShATerm' att2 c
return $ addATerm (ShAAppl "Rigid_op_items" [a', b', c'] []) att3
Rigid_pred_items a b c -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
(att3, c') <- toShATerm' att2 c
return $ addATerm (ShAAppl "Rigid_pred_items" [a', b', c'] []) att3
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "Rigid_op_items" [a, b, c] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
case fromShATerm' b att1 of
{ (att2, b') ->
case fromShATerm' c att2 of
{ (att3, c') ->
(att3, Rigid_op_items a' b' c') }}}
ShAAppl "Rigid_pred_items" [a, b, c] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
case fromShATerm' b att1 of
{ (att2, b') ->
case fromShATerm' c att2 of
{ (att3, c') ->
(att3, Rigid_pred_items a' b' c') }}}
u -> fromShATermError "M_SIG_ITEM" u
instance ShATermConvertible RIGOR where
toShATermAux att0 xv = case xv of
Rigid -> return $ addATerm (ShAAppl "Rigid" [] []) att0
Flexible -> return $ addATerm (ShAAppl "Flexible" [] []) att0
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "Rigid" [] _ -> (att0, Rigid)
ShAAppl "Flexible" [] _ -> (att0, Flexible)
u -> fromShATermError "RIGOR" u
instance ShATermConvertible M_BASIC_ITEM where
toShATermAux att0 xv = case xv of
Simple_mod_decl a b c -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
(att3, c') <- toShATerm' att2 c
return $ addATerm (ShAAppl "Simple_mod_decl" [a', b', c'] []) att3
Term_mod_decl a b c -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
(att3, c') <- toShATerm' att2 c
return $ addATerm (ShAAppl "Term_mod_decl" [a', b', c'] []) att3
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "Simple_mod_decl" [a, b, c] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
case fromShATerm' b att1 of
{ (att2, b') ->
case fromShATerm' c att2 of
{ (att3, c') ->
(att3, Simple_mod_decl a' b' c') }}}
ShAAppl "Term_mod_decl" [a, b, c] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
case fromShATerm' b att1 of
{ (att2, b') ->
case fromShATerm' c att2 of
{ (att3, c') ->
(att3, Term_mod_decl a' b' c') }}}
u -> fromShATermError "M_BASIC_ITEM" u
_tcM_FORMULATc :: TyCon
_tcM_FORMULATc = mkTyCon "Modal.AS_Modal.M_FORMULA"
instance Typeable M_FORMULA where
typeOf _ = mkTyConApp _tcM_FORMULATc []
_tcMODALITYTc :: TyCon
_tcMODALITYTc = mkTyCon "Modal.AS_Modal.MODALITY"
instance Typeable MODALITY where
typeOf _ = mkTyConApp _tcMODALITYTc []
_tcM_SIG_ITEMTc :: TyCon
_tcM_SIG_ITEMTc = mkTyCon "Modal.AS_Modal.M_SIG_ITEM"
instance Typeable M_SIG_ITEM where
typeOf _ = mkTyConApp _tcM_SIG_ITEMTc []
_tcRIGORTc :: TyCon
_tcRIGORTc = mkTyCon "Modal.AS_Modal.RIGOR"
instance Typeable RIGOR where
typeOf _ = mkTyConApp _tcRIGORTc []
_tcM_BASIC_ITEMTc :: TyCon
_tcM_BASIC_ITEMTc = mkTyCon "Modal.AS_Modal.M_BASIC_ITEM"
instance Typeable M_BASIC_ITEM where
typeOf _ = mkTyConApp _tcM_BASIC_ITEMTc []
_tcModalSignTc :: TyCon
_tcModalSignTc = mkTyCon "Modal.ModalSign.ModalSign"
instance Typeable ModalSign where
typeOf _ = mkTyConApp _tcModalSignTc []
instance ShATermConvertible ModalSign where
toShATermAux att0 xv = case xv of
ModalSign a b c d -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
(att3, c') <- toShATerm' att2 c
(att4, d') <- toShATerm' att3 d
return $ addATerm (ShAAppl "ModalSign" [a', b', c', d'] []) att4
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "ModalSign" [a, b, c, d] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
case fromShATerm' b att1 of
{ (att2, b') ->
case fromShATerm' c att2 of
{ (att3, c') ->
case fromShATerm' d att3 of
{ (att4, d') ->
(att4, ModalSign a' b' c' d') }}}}
u -> fromShATermError "ModalSign" u
| nevrenato/Hets_Fork | Modal/ATC_Modal.hs | gpl-2.0 | 7,539 | 0 | 22 | 1,734 | 2,253 | 1,184 | 1,069 | 164 | 1 |
{-# LANGUAGE ImpredicativeTypes #-}
module Quenelle.Rule (
ExprPred,
ExprRule(..),
RuleBinding(..),
parseExprRule,
runExprRule
) where
import Control.Exception.Base
import Control.Lens
import Control.Monad.State.Strict
import Data.Maybe
import Language.Python.Common.AST
import Language.Python.Common.ParseError
import Language.Python.Version2
import Quenelle.Lens
import Quenelle.Normalize
import Quenelle.Var
type ArgumentPred = QArgument -> Bool
type ArgumentsPred = [QArgument] -> Bool
type ExprPred = QExpr -> Bool
type ComprehensionPred = QComprehension -> Bool
type ComprehensionExprPred = QComprehensionExpr -> Bool
type CompIfPred = QCompIf -> Bool
type CompForPred = QCompFor -> Bool
type IdentPred = QIdent -> Bool
type ParameterPred = QParameter -> Bool
type ParametersPred = [QParameter] -> Bool
data RuleBinding =
RuleVariableBinding VariableID QIdentPath
| RuleExpressionBinding ExpressionID QExprPath
data ExprRule = ExprRule {
exprRuleName :: String,
exprRuleExpr :: QExpr,
exprRulePred :: ExprPred,
exprRuleBindings :: [RuleBinding]
}
runExprRule :: ExprRule -> QExpr -> Maybe [Binding]
runExprRule rule expr =
if exprRulePred rule expr then
readExprExprs expr (exprRuleBindings rule) else Nothing
readExprExprs :: QExpr -> [RuleBinding] -> Maybe [Binding]
readExprExprs expr = mapM (readPath expr)
-- If exprRulePred succeeds, then every path should be valid
where readPath :: QExpr -> RuleBinding -> Maybe Binding
readPath e (RuleVariableBinding name path) = assert (has path e) $ VariableBinding name <$> e ^? path
readPath e (RuleExpressionBinding name path) = assert (has path e) $ ExpressionBinding name <$> e ^? path
parseExprRule :: String -> Either ParseError ExprRule
parseExprRule str =
case parseExprPred str of
Left err -> Left err
Right (expr, pred, state) -> Right ExprRule {
exprRuleName = "rule",
exprRuleExpr = expr,
exprRulePred = pred,
exprRuleBindings = ruleBindings state
}
parseExprPred :: String -> Either ParseError (QExpr, ExprPred, RuleState)
parseExprPred str =
case parseExpr str "rule" of
Left err -> Left err
Right (e, _) -> Right $ runExprToPred e
runExprToPred e = (e', pred, state)
where (pred, state) = runState (exprToPred id e') emptyRuleState
e' = normalizeExpr e
--------------------------------------------------------------------------------
data RuleState = RuleState {
ruleBindings :: [RuleBinding]
}
emptyRuleState = RuleState { ruleBindings = [] }
bindVariable :: VariableID -> QIdentPath -> State RuleState ()
bindVariable name path = modify $ \s -> s {
ruleBindings = ruleBindings s ++ [RuleVariableBinding name path]
}
bindExpression :: ExpressionID -> QExprPath -> State RuleState ()
bindExpression name path = modify $ \s -> s {
ruleBindings = ruleBindings s ++ [RuleExpressionBinding name path]
}
--------------------------------------------------------------------------------
exprsToPred :: Traversal' QExpr [QExpr] -> [QExpr] -> State RuleState [ExprPred]
exprsToPred path es = sequence [exprToPred (path.ix i) e | (e, i) <- zip es [0..]]
exprToPred :: QExprPath -> QExpr -> State RuleState ExprPred
exprToPred path (Var x _) =
case classifyVar x of
Expression -> return pExpr'
(BoundExpression name) -> do
bindExpression name path
return pExpr'
Variable -> return pVar'
(BoundVariable name) -> do
bindVariable name (path.var_identL)
return pVar'
Normal -> return $ pVar (pIdent x)
exprToPred path (Int x _ _) = return $ pInt x
exprToPred path (LongInt x _ _) = return $ pLongInt x
exprToPred path (Float x _ _) = return $ pFloat x
exprToPred path (Imaginary x _ _) = return $ pImaginary x
exprToPred path (Bool x _) = return $ pBool x
exprToPred path (ByteStrings ss _) = return $ pByteStrings ss
exprToPred path (Strings ss _) = return $ pStrings ss
exprToPred path (UnicodeStrings ss _) = return $ pUnicodeStrings ss
exprToPred path (BinaryOp op l r _) = do
lp <- exprToPred (path.left_op_argL) l
rp <- exprToPred (path.right_op_argL) r
return $ pBinaryOp (pOp op) lp rp
exprToPred path (UnaryOp op arg _) = do
argp <- exprToPred (path.op_argL) arg
return $ pUnaryOp (pOp op) argp
exprToPred path (Dot e ident _) = do
ep <- exprToPred (path.dot_exprL) e
case classifyVar ident of
Expression -> return pExpr'
(BoundExpression name) -> do
-- TODO: this doesn't seem right and might explain why
-- the this test fails in TestRepace.hs:
-- "x.y" "V1.E1" "E1.V1" "y.x"
bindExpression name path
return pExpr'
Variable -> return $ pDot ep (const True)
(BoundVariable name) -> do
bindVariable name (path.dot_attributeL)
return $ pDot ep (const True)
Normal -> return $ pDot ep (pIdent ident)
exprToPred path (Lambda params body _) = do
paramsp <- parametersToPred (path.lambda_argsL) params
bodyp <- exprToPred (path.lambda_bodyL) body
return $ pLambda paramsp bodyp
exprToPred path (Call fun args _) = do
funp <- exprToPred (path.call_funL) fun
argsp <- argumentsToPred (path.call_argsL) args
return $ pCall funp argsp
exprToPred path (Subscript subscriptee subscript_expr _) = do
subscripteep <- exprToPred (path.subscripteeL) subscriptee
subscript_exprp <- exprToPred (path.subscript_exprL) subscript_expr
return $ pSubscript subscripteep subscript_exprp
exprToPred path (SlicedExpr expr slices _) = do
exprp <- exprToPred (path.sliceeL) expr
slicesp <- slicesToPred (path.slicesL) slices
return $ pSlicedExpr exprp slicesp
exprToPred path (CondExpr t c f _) = do
tp <- exprToPred (path.ce_true_branchL) t
cp <- exprToPred (path.ce_conditionL) c
fp <- exprToPred (path.ce_false_branchL) f
return $ pCondExpr tp cp fp
exprToPred path (Paren e _) = pParen <$> exprToPred (path.paren_exprL) e
exprToPred path (StringConversion e _) = pStringConversion <$> exprToPred (path.backquoted_exprL) e
exprToPred path (Tuple es _) =
pTuple <$> exprsToPred (path.tuple_exprsL) es
exprToPred path (ListComp comp _) = pListComp <$> comprehensionToPred (path.list_comprehensionL) comp
--------------------------------------------------------------------------------
argumentsToPred :: Traversal' QExpr [QArgument] -> [QArgument] -> State RuleState ArgumentsPred
argumentsToPred path args =
allApply <$> sequence [argumentToPred (path.ix i) arg | (arg, i) <- zip args [0..]]
argumentToPred :: Traversal' QExpr QArgument -> QArgument -> State RuleState ArgumentPred
argumentToPred path (ArgExpr expr _) = pArgExpr <$> exprToPred (path.arg_exprL) expr
argumentToPred path (ArgVarArgsPos expr _) = pArgVarArgsPosExpr <$> exprToPred (path.arg_exprL) expr
--------------------------------------------------------------------------------
parametersToPred :: Traversal' QExpr [QParameter] -> [QParameter] -> State RuleState ParametersPred
parametersToPred path params =
allApply <$> sequence [parameterToPred (path.ix i) param | (param, i) <- zip params [0..]]
parameterToPred :: Traversal' QExpr QParameter -> QParameter -> State RuleState ParameterPred
parameterToPred path (Param x Nothing Nothing _) =
case classifyVar x of
Variable -> return pParam'
(BoundVariable name) -> do
bindVariable name (path.param_nameL)
return pParam'
Normal -> return $ pParam (pIdent x)
--------------------------------------------------------------------------------
comprehensionExprToPred :: Traversal' QExpr QComprehensionExpr -> QComprehensionExpr -> State RuleState ComprehensionExprPred
comprehensionExprToPred path (ComprehensionExpr expr) = pComprehensionExpr <$> exprToPred (path._ComprehensionExpr) expr
comprehensionExprToPres path (ComprehensionDict dict) = error "ComprehensionDict is unsupported"
--------------------------------------------------------------------------------
comprehensionToPred :: Traversal' QExpr QComprehension -> QComprehension -> State RuleState ComprehensionPred
comprehensionToPred path (Comprehension e for _) = do
ep <- comprehensionExprToPred (path.comprehension_exprL) e
forp <- compForToPred (path.comprehension_forL) for
return $ pComprehension ep forp
compForToPred :: Traversal' QExpr QCompFor -> QCompFor -> State RuleState CompForPred
compForToPred path (CompFor fores ine iter _) = do
foresp <- exprsToPred (path.comp_for_exprsL) fores
inep <- exprToPred (path.comp_in_exprL) ine
iterp <- compIterToPred (path.comp_for_iterL) iter
return $ pCompFor foresp inep iterp
compIfToPred :: Traversal' QExpr QCompIf -> QCompIf -> State RuleState CompIfPred
compIfToPred path (CompIf if_ iter _) = do
ifp <- exprToPred (path.comp_ifL) if_
iterp <- compIterToPred (path.comp_if_iterL) iter
return $ pCompIf ifp iterp
compIterToPred :: Traversal' QExpr (Maybe QCompIter) -> Maybe QCompIter -> State RuleState (Maybe QCompIter -> Bool)
compIterToPred path (Just (IterFor for _)) = pJustIterFor <$> compForToPred (path._Just.comp_iter_forL) for
compIterToPred path (Just (IterIf if_ _)) = pJustIterIf <$> compIfToPred (path._Just.comp_iter_ifL) if_
compIterToPred path Nothing = return isNothing
slicesToPred :: Traversal' QExpr [QSlice] -> [QSlice] -> State RuleState ([QSlice] -> Bool)
slicesToPred path slices =
allApply <$> sequence [sliceToPred (path.ix i) slice | (slice, i) <- zip slices [0..]]
sliceToPred :: Traversal' QExpr QSlice -> QSlice -> State RuleState (QSlice -> Bool)
sliceToPred path (SliceProper lower upper (Just stride) _) =
pSliceProper <$>
maybeExprToPred (path.slice_lowerL) lower <*>
maybeExprToPred (path.slice_upperL) upper <*>
(pJust <$> maybeExprToPred (path.slice_strideL._Just) stride)
sliceToPred path (SliceProper lower upper Nothing _) =
pSliceProper <$>
maybeExprToPred (path.slice_lowerL) lower <*>
maybeExprToPred (path.slice_upperL) upper <*>
return isNothing
maybeExprToPred :: Traversal' QExpr (Maybe QExpr) -> Maybe QExpr -> State RuleState (Maybe QExpr -> Bool)
maybeExprToPred path (Just e) = pJust <$> exprToPred (path._Just) e
maybeExprToPred path Nothing = return isNothing
--------------------------------------------------------------------------------
pJust :: (a -> Bool) -> Maybe a -> Bool
pJust xp (Just x) = xp x
pJust _ _ = False
pExpr' :: ExprPred
pExpr' _ = True
pIdent :: QIdent -> IdentPred
pIdent x (Ident y _) = ident_string x == y
pVar' :: ExprPred
pVar' Var{} = True
pVar' _ = False
pVar :: IdentPred -> ExprPred
pVar namep (Var name _) = namep name
pVar _ _ = False
pInt :: Integer -> ExprPred
pInt x (Int y _ _) = x == y
pInt _ _ = False
pLongInt :: Integer -> ExprPred
pLongInt x (LongInt y _ _) = x == y
pLongInt _ _ = False
pFloat :: Double -> ExprPred
pFloat x (Float y _ _) = x == y
pFloat _ _ = False
pImaginary :: Double -> ExprPred
pImaginary x (Imaginary y _ _) = x == y
pImaginary _ _ = False
pBool :: Bool -> ExprPred
pBool x (Bool y _) = x == y
pBool _ _ = False
pByteStrings :: [String] -> ExprPred
pByteStrings ss' (ByteStrings ss _) = ss == ss'
pByteStrings _ _ = False
pStrings :: [String] -> ExprPred
pStrings ss' (Strings ss _) = ss == ss'
pStrings _ _ = False
pUnicodeStrings :: [String] -> ExprPred
pUnicodeStrings ss' (UnicodeStrings ss _) = ss == ss'
pUnicodeStrings _ _ = False
pOp :: QOp -> QOp -> Bool
pOp x y = x == y
pBinaryOp :: (QOp -> Bool) -> ExprPred -> ExprPred -> ExprPred
pBinaryOp opp lp rp (BinaryOp op l r _) = opp op && lp l && rp r
pBinaryOp _ _ _ _ = False
pUnaryOp :: (QOp -> Bool) -> ExprPred -> ExprPred
pUnaryOp opp argp (UnaryOp op arg _) = opp op && argp arg
pUnaryOp _ _ _ = False
pDot :: ExprPred -> (QIdent -> Bool) -> ExprPred
pDot ep identp (Dot e ident _) = identp ident && ep e
pDot _ _ _ = False
pLambda :: ([QParameter] -> Bool) -> (QExpr -> Bool) -> ExprPred
pLambda paramsp bodyp (Lambda params body _) = paramsp params && bodyp body
pLambda _ _ _ = False
pCall :: ExprPred -> ArgumentsPred -> ExprPred
pCall funp argsp (Call fun args _) = funp fun && argsp args
pCall _ _ _ = False
pSubscript :: ExprPred -> ExprPred -> ExprPred
pSubscript sp sep (Subscript s se _) = sp s && sep se
pSubscript _ _ _ = False
pSlicedExpr :: ExprPred -> ([QSlice] -> Bool) -> ExprPred
pSlicedExpr exprp slicesp (SlicedExpr expr slices _) = exprp expr && slicesp slices
pSlicedExpr _ _ _ = False
pCondExpr :: ExprPred -> ExprPred -> ExprPred -> ExprPred
pCondExpr tp cp fp (CondExpr t c f _) = tp t && cp c && fp f
pCondExpr _ _ _ _ = False
pSliceProper :: (Maybe QExpr -> Bool) -> (Maybe QExpr -> Bool) -> (Maybe (Maybe QExpr) -> Bool) -> QSlice -> Bool
pSliceProper lowerp upperp stridep (SliceProper lower upper stride _) = lowerp lower && upperp upper && stridep stride
pSliceProper _ _ _ _ = False
pParen :: ExprPred -> ExprPred
pParen ep (Paren e _) = ep e
pParen _ _ = False
pArgExpr :: ExprPred -> ArgumentPred
pArgExpr argp (ArgExpr arg _) = argp arg
pArgExpr _ _ = False
pArgVarArgsPosExpr :: ExprPred -> ArgumentPred
pArgVarArgsPosExpr argp (ArgVarArgsPos arg _) = argp arg
pArgVarArgsPosExpr _ _ = False
pTuple :: [ExprPred] -> QExpr -> Bool
pTuple esp (Tuple es _) = allApply esp es
pTuple _ _ = False
pListComp compp (ListComp comp _) = compp comp
pListComp _ _ = False
pComprehension ep forp (Comprehension e for _) = ep e && forp for
pComprehensionExpr ep (ComprehensionExpr e) = ep e
pComprehensionExpr _ _ = False
pCompFor foresp inep iterp (CompFor fores ine iter _) = inep ine && iterp iter && allApply foresp fores
pCompIf ifp iterp (CompIf if_ iter _) = ifp if_ && iterp iter
pJustIterFor :: CompForPred -> Maybe QCompIter -> Bool
pJustIterFor forp (Just (IterFor for _)) = forp for
pJustIterFor _ _ = False
pJustIterIf :: CompIfPred -> Maybe QCompIter -> Bool
pJustIterIf ifp (Just (IterIf if_ _)) = ifp if_
pJustIterIf _ _ = False
pStringConversion :: ExprPred -> ExprPred
pStringConversion exprp (StringConversion expr _) = exprp expr
pStringConversion _ _ = False
pParam' :: ParameterPred
pParam' (Param _ Nothing Nothing _) = True
pParam' _ = False
pParam :: IdentPred -> QParameter -> Bool
pParam identp (Param ident _ _ _) = identp ident
pParam _ _ = False
--------------------------------------------------------------------------------
allApply fs xs = (length fs == length xs) && all (\(f, x) -> f x) (zip fs xs)
| philipturnbull/quenelle | src/Quenelle/Rule.hs | gpl-2.0 | 14,645 | 0 | 15 | 2,891 | 5,055 | 2,535 | 2,520 | 295 | 9 |
module Match (Team, Match(..), toCsv) where
import qualified Data.List
type Team = String
data Match = Match {
first_team :: Team,
second_team :: Team,
first_team_goals :: Int,
second_team_goals :: Int,
penalty_winner :: Maybe Team
} deriving (Show)
toCsv :: Match -> String
toCsv m = Data.List.intercalate "," [first_team m, second_team m,
show $ first_team_goals m,
show $ second_team_goals m]
| pikma/world_cup | Match.hs | gpl-2.0 | 484 | 0 | 9 | 147 | 137 | 80 | 57 | 14 | 1 |
{-# LANGUAGE DeriveDataTypeable, MagicHash, PolymorphicComponents, RoleAnnotations, UnboxedTuples #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.Haskell.Syntax
-- Copyright : (c) The University of Glasgow 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Abstract syntax definitions for Template Haskell.
--
-----------------------------------------------------------------------------
module Language.Haskell.TH.Syntax where
import GHC.Exts
import Data.Data (Data(..), Typeable, mkConstr, mkDataType, constrIndex)
import qualified Data.Data as Data
import Control.Applicative( Applicative(..) )
import Data.IORef
import System.IO.Unsafe ( unsafePerformIO )
import Control.Monad (liftM)
import System.IO ( hPutStrLn, stderr )
import Data.Char ( isAlpha, isAlphaNum, isUpper )
import Data.Word ( Word8 )
-----------------------------------------------------
--
-- The Quasi class
--
-----------------------------------------------------
class (Monad m, Applicative m) => Quasi m where
qNewName :: String -> m Name
-- ^ Fresh names
-- Error reporting and recovery
qReport :: Bool -> String -> m () -- ^ Report an error (True) or warning (False)
-- ...but carry on; use 'fail' to stop
qRecover :: m a -- ^ the error handler
-> m a -- ^ action which may fail
-> m a -- ^ Recover from the monadic 'fail'
-- Inspect the type-checker's environment
qLookupName :: Bool -> String -> m (Maybe Name)
-- True <=> type namespace, False <=> value namespace
qReify :: Name -> m Info
qReifyInstances :: Name -> [Type] -> m [Dec]
-- Is (n tys) an instance?
-- Returns list of matching instance Decs
-- (with empty sub-Decs)
-- Works for classes and type functions
qReifyRoles :: Name -> m [Role]
qReifyAnnotations :: Data a => AnnLookup -> m [a]
qReifyModule :: Module -> m ModuleInfo
qLocation :: m Loc
qRunIO :: IO a -> m a
-- ^ Input/output (dangerous)
qAddDependentFile :: FilePath -> m ()
qAddTopDecls :: [Dec] -> m ()
qAddModFinalizer :: Q () -> m ()
qGetQ :: Typeable a => m (Maybe a)
qPutQ :: Typeable a => a -> m ()
-----------------------------------------------------
-- The IO instance of Quasi
--
-- This instance is used only when running a Q
-- computation in the IO monad, usually just to
-- print the result. There is no interesting
-- type environment, so reification isn't going to
-- work.
--
-----------------------------------------------------
instance Quasi IO where
qNewName s = do { n <- readIORef counter
; writeIORef counter (n+1)
; return (mkNameU s n) }
qReport True msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
qReport False msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
qLookupName _ _ = badIO "lookupName"
qReify _ = badIO "reify"
qReifyInstances _ _ = badIO "reifyInstances"
qReifyRoles _ = badIO "reifyRoles"
qReifyAnnotations _ = badIO "reifyAnnotations"
qReifyModule _ = badIO "reifyModule"
qLocation = badIO "currentLocation"
qRecover _ _ = badIO "recover" -- Maybe we could fix this?
qAddDependentFile _ = badIO "addDependentFile"
qAddTopDecls _ = badIO "addTopDecls"
qAddModFinalizer _ = badIO "addModFinalizer"
qGetQ = badIO "getQ"
qPutQ _ = badIO "putQ"
qRunIO m = m
badIO :: String -> IO a
badIO op = do { qReport True ("Can't do `" ++ op ++ "' in the IO monad")
; fail "Template Haskell failure" }
-- Global variable to generate unique symbols
counter :: IORef Int
{-# NOINLINE counter #-}
counter = unsafePerformIO (newIORef 0)
-----------------------------------------------------
--
-- The Q monad
--
-----------------------------------------------------
newtype Q a = Q { unQ :: forall m. Quasi m => m a }
-- \"Runs\" the 'Q' monad. Normal users of Template Haskell
-- should not need this function, as the splice brackets @$( ... )@
-- are the usual way of running a 'Q' computation.
--
-- This function is primarily used in GHC internals, and for debugging
-- splices by running them in 'IO'.
--
-- Note that many functions in 'Q', such as 'reify' and other compiler
-- queries, are not supported when running 'Q' in 'IO'; these operations
-- simply fail at runtime. Indeed, the only operations guaranteed to succeed
-- are 'newName', 'runIO', 'reportError' and 'reportWarning'.
runQ :: Quasi m => Q a -> m a
runQ (Q m) = m
instance Monad Q where
return x = Q (return x)
Q m >>= k = Q (m >>= \x -> unQ (k x))
Q m >> Q n = Q (m >> n)
fail s = report True s >> Q (fail "Q monad failure")
instance Functor Q where
fmap f (Q x) = Q (fmap f x)
instance Applicative Q where
pure x = Q (pure x)
Q f <*> Q x = Q (f <*> x)
-----------------------------------------------------
--
-- The TExp type
--
-----------------------------------------------------
type role TExp nominal -- See Note [Role of TExp]
newtype TExp a = TExp { unType :: Exp }
unTypeQ :: Q (TExp a) -> Q Exp
unTypeQ m = do { TExp e <- m
; return e }
unsafeTExpCoerce :: Q Exp -> Q (TExp a)
unsafeTExpCoerce m = do { e <- m
; return (TExp e) }
{- Note [Role of TExp]
~~~~~~~~~~~~~~~~~~~~~~
TExp's argument must have a nominal role, not phantom as would
be inferred (Trac #8459). Consider
e :: TExp Age
e = MkAge 3
foo = $(coerce e) + 4::Int
The splice will evaluate to (MkAge 3) and you can't add that to
4::Int. So you can't coerce a (TExp Age) to a (TExp Int). -}
----------------------------------------------------
-- Packaged versions for the programmer, hiding the Quasi-ness
{- |
Generate a fresh name, which cannot be captured.
For example, this:
@f = $(do
nm1 <- newName \"x\"
let nm2 = 'mkName' \"x\"
return ('LamE' ['VarP' nm1] (LamE [VarP nm2] ('VarE' nm1)))
)@
will produce the splice
>f = \x0 -> \x -> x0
In particular, the occurrence @VarE nm1@ refers to the binding @VarP nm1@,
and is not captured by the binding @VarP nm2@.
Although names generated by @newName@ cannot /be captured/, they can
/capture/ other names. For example, this:
>g = $(do
> nm1 <- newName "x"
> let nm2 = mkName "x"
> return (LamE [VarP nm2] (LamE [VarP nm1] (VarE nm2)))
> )
will produce the splice
>g = \x -> \x0 -> x0
since the occurrence @VarE nm2@ is captured by the innermost binding
of @x@, namely @VarP nm1@.
-}
newName :: String -> Q Name
newName s = Q (qNewName s)
-- | Report an error (True) or warning (False),
-- but carry on; use 'fail' to stop.
report :: Bool -> String -> Q ()
report b s = Q (qReport b s)
{-# DEPRECATED report "Use reportError or reportWarning instead" #-} -- deprecated in 7.6
-- | Report an error to the user, but allow the current splice's computation to carry on. To abort the computation, use 'fail'.
reportError :: String -> Q ()
reportError = report True
-- | Report a warning to the user, and carry on.
reportWarning :: String -> Q ()
reportWarning = report False
-- | Recover from errors raised by 'reportError' or 'fail'.
recover :: Q a -- ^ handler to invoke on failure
-> Q a -- ^ computation to run
-> Q a
recover (Q r) (Q m) = Q (qRecover r m)
-- We don't export lookupName; the Bool isn't a great API
-- Instead we export lookupTypeName, lookupValueName
lookupName :: Bool -> String -> Q (Maybe Name)
lookupName ns s = Q (qLookupName ns s)
-- | Look up the given name in the (type namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
lookupTypeName :: String -> Q (Maybe Name)
lookupTypeName s = Q (qLookupName True s)
-- | Look up the given name in the (value namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
lookupValueName :: String -> Q (Maybe Name)
lookupValueName s = Q (qLookupName False s)
{-
Note [Name lookup]
~~~~~~~~~~~~~~~~~~
-}
{- $namelookup #namelookup#
The functions 'lookupTypeName' and 'lookupValueName' provide
a way to query the current splice's context for what names
are in scope. The function 'lookupTypeName' queries the type
namespace, whereas 'lookupValueName' queries the value namespace,
but the functions are otherwise identical.
A call @lookupValueName s@ will check if there is a value
with name @s@ in scope at the current splice's location. If
there is, the @Name@ of this value is returned;
if not, then @Nothing@ is returned.
The returned name cannot be \"captured\".
For example:
> f = "global"
> g = $( do
> Just nm <- lookupValueName "f"
> [| let f = "local" in $( varE nm ) |]
In this case, @g = \"global\"@; the call to @lookupValueName@
returned the global @f@, and this name was /not/ captured by
the local definition of @f@.
The lookup is performed in the context of the /top-level/ splice
being run. For example:
> f = "global"
> g = $( [| let f = "local" in
> $(do
> Just nm <- lookupValueName "f"
> varE nm
> ) |] )
Again in this example, @g = \"global\"@, because the call to
@lookupValueName@ queries the context of the outer-most @$(...)@.
Operators should be queried without any surrounding parentheses, like so:
> lookupValueName "+"
Qualified names are also supported, like so:
> lookupValueName "Prelude.+"
> lookupValueName "Prelude.map"
-}
{- | 'reify' looks up information about the 'Name'.
It is sometimes useful to construct the argument name using 'lookupTypeName' or 'lookupValueName'
to ensure that we are reifying from the right namespace. For instance, in this context:
> data D = D
which @D@ does @reify (mkName \"D\")@ return information about? (Answer: @D@-the-type, but don't rely on it.)
To ensure we get information about @D@-the-value, use 'lookupValueName':
> do
> Just nm <- lookupValueName "D"
> reify nm
and to get information about @D@-the-type, use 'lookupTypeName'.
-}
reify :: Name -> Q Info
reify v = Q (qReify v)
{- | @reifyInstances nm tys@ returns a list of visible instances of @nm tys@. That is,
if @nm@ is the name of a type class, then all instances of this class at the types @tys@
are returned. Alternatively, if @nm@ is the name of a data family or type family,
all instances of this family at the types @tys@ are returned.
-}
reifyInstances :: Name -> [Type] -> Q [InstanceDec]
reifyInstances cls tys = Q (qReifyInstances cls tys)
{- | @reifyRoles nm@ returns the list of roles associated with the parameters of
the tycon @nm@. Fails if @nm@ cannot be found or is not a tycon.
The returned list should never contain 'InferR'.
-}
reifyRoles :: Name -> Q [Role]
reifyRoles nm = Q (qReifyRoles nm)
-- | @reifyAnnotations target@ returns the list of annotations
-- associated with @target@. Only the annotations that are
-- appropriately typed is returned. So if you have @Int@ and @String@
-- annotations for the same target, you have to call this function twice.
reifyAnnotations :: Data a => AnnLookup -> Q [a]
reifyAnnotations an = Q (qReifyAnnotations an)
-- | @reifyModule mod@ looks up information about module @mod@. To
-- look up the current module, call this function with the return
-- value of @thisModule@.
reifyModule :: Module -> Q ModuleInfo
reifyModule m = Q (qReifyModule m)
-- | Is the list of instances returned by 'reifyInstances' nonempty?
isInstance :: Name -> [Type] -> Q Bool
isInstance nm tys = do { decs <- reifyInstances nm tys
; return (not (null decs)) }
-- | The location at which this computation is spliced.
location :: Q Loc
location = Q qLocation
-- |The 'runIO' function lets you run an I\/O computation in the 'Q' monad.
-- Take care: you are guaranteed the ordering of calls to 'runIO' within
-- a single 'Q' computation, but not about the order in which splices are run.
--
-- Note: for various murky reasons, stdout and stderr handles are not
-- necesarily flushed when the compiler finishes running, so you should
-- flush them yourself.
runIO :: IO a -> Q a
runIO m = Q (qRunIO m)
-- | Record external files that runIO is using (dependent upon).
-- The compiler can then recognize that it should re-compile the file using this TH when the external file changes.
-- Note that ghc -M will still not know about these dependencies - it does not execute TH.
-- Expects an absolute file path.
addDependentFile :: FilePath -> Q ()
addDependentFile fp = Q (qAddDependentFile fp)
-- | Add additional top-level declarations. The added declarations will be type
-- checked along with the current declaration group.
addTopDecls :: [Dec] -> Q ()
addTopDecls ds = Q (qAddTopDecls ds)
-- | Add a finalizer that will run in the Q monad after the current module has
-- been type checked. This only makes sense when run within a top-level splice.
addModFinalizer :: Q () -> Q ()
addModFinalizer act = Q (qAddModFinalizer (unQ act))
-- | Get state from the Q monad.
getQ :: Typeable a => Q (Maybe a)
getQ = Q qGetQ
-- | Replace the state in the Q monad.
putQ :: Typeable a => a -> Q ()
putQ x = Q (qPutQ x)
instance Quasi Q where
qNewName = newName
qReport = report
qRecover = recover
qReify = reify
qReifyInstances = reifyInstances
qReifyRoles = reifyRoles
qReifyAnnotations = reifyAnnotations
qReifyModule = reifyModule
qLookupName = lookupName
qLocation = location
qRunIO = runIO
qAddDependentFile = addDependentFile
qAddTopDecls = addTopDecls
qAddModFinalizer = addModFinalizer
qGetQ = getQ
qPutQ = putQ
----------------------------------------------------
-- The following operations are used solely in DsMeta when desugaring brackets
-- They are not necessary for the user, who can use ordinary return and (>>=) etc
returnQ :: a -> Q a
returnQ = return
bindQ :: Q a -> (a -> Q b) -> Q b
bindQ = (>>=)
sequenceQ :: [Q a] -> Q [a]
sequenceQ = sequence
-----------------------------------------------------
--
-- The Lift class
--
-----------------------------------------------------
class Lift t where
lift :: t -> Q Exp
instance Lift Integer where
lift x = return (LitE (IntegerL x))
instance Lift Int where
lift x= return (LitE (IntegerL (fromIntegral x)))
instance Lift Char where
lift x = return (LitE (CharL x))
instance Lift Bool where
lift True = return (ConE trueName)
lift False = return (ConE falseName)
instance Lift a => Lift (Maybe a) where
lift Nothing = return (ConE nothingName)
lift (Just x) = liftM (ConE justName `AppE`) (lift x)
instance (Lift a, Lift b) => Lift (Either a b) where
lift (Left x) = liftM (ConE leftName `AppE`) (lift x)
lift (Right y) = liftM (ConE rightName `AppE`) (lift y)
instance Lift a => Lift [a] where
lift xs = do { xs' <- mapM lift xs; return (ListE xs') }
liftString :: String -> Q Exp
-- Used in TcExpr to short-circuit the lifting for strings
liftString s = return (LitE (StringL s))
instance (Lift a, Lift b) => Lift (a, b) where
lift (a, b)
= liftM TupE $ sequence [lift a, lift b]
instance (Lift a, Lift b, Lift c) => Lift (a, b, c) where
lift (a, b, c)
= liftM TupE $ sequence [lift a, lift b, lift c]
instance (Lift a, Lift b, Lift c, Lift d) => Lift (a, b, c, d) where
lift (a, b, c, d)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d]
instance (Lift a, Lift b, Lift c, Lift d, Lift e)
=> Lift (a, b, c, d, e) where
lift (a, b, c, d, e)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e]
instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f)
=> Lift (a, b, c, d, e, f) where
lift (a, b, c, d, e, f)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f]
instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f, Lift g)
=> Lift (a, b, c, d, e, f, g) where
lift (a, b, c, d, e, f, g)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f, lift g]
-- TH has a special form for literal strings,
-- which we should take advantage of.
-- NB: the lhs of the rule has no args, so that
-- the rule will apply to a 'lift' all on its own
-- which happens to be the way the type checker
-- creates it.
{-# RULES "TH:liftString" lift = \s -> return (LitE (StringL s)) #-}
trueName, falseName :: Name
trueName = mkNameG DataName "ghc-prim" "GHC.Types" "True"
falseName = mkNameG DataName "ghc-prim" "GHC.Types" "False"
nothingName, justName :: Name
nothingName = mkNameG DataName "base" "Data.Maybe" "Nothing"
justName = mkNameG DataName "base" "Data.Maybe" "Just"
leftName, rightName :: Name
leftName = mkNameG DataName "base" "Data.Either" "Left"
rightName = mkNameG DataName "base" "Data.Either" "Right"
-----------------------------------------------------
-- Names and uniques
-----------------------------------------------------
newtype ModName = ModName String -- Module name
deriving (Show,Eq,Ord,Typeable,Data)
newtype PkgName = PkgName String -- package name
deriving (Show,Eq,Ord,Typeable,Data)
-- | Obtained from 'reifyModule' and 'thisModule'.
data Module = Module PkgName ModName -- package qualified module name
deriving (Show,Eq,Ord,Typeable,Data)
newtype OccName = OccName String
deriving (Show,Eq,Ord,Typeable,Data)
mkModName :: String -> ModName
mkModName s = ModName s
modString :: ModName -> String
modString (ModName m) = m
mkPkgName :: String -> PkgName
mkPkgName s = PkgName s
pkgString :: PkgName -> String
pkgString (PkgName m) = m
-----------------------------------------------------
-- OccName
-----------------------------------------------------
mkOccName :: String -> OccName
mkOccName s = OccName s
occString :: OccName -> String
occString (OccName occ) = occ
-----------------------------------------------------
-- Names
-----------------------------------------------------
--
-- For "global" names ('NameG') we need a totally unique name,
-- so we must include the name-space of the thing
--
-- For unique-numbered things ('NameU'), we've got a unique reference
-- anyway, so no need for name space
--
-- For dynamically bound thing ('NameS') we probably want them to
-- in a context-dependent way, so again we don't want the name
-- space. For example:
--
-- > let v = mkName "T" in [| data $v = $v |]
--
-- Here we use the same Name for both type constructor and data constructor
--
--
-- NameL and NameG are bound *outside* the TH syntax tree
-- either globally (NameG) or locally (NameL). Ex:
--
-- > f x = $(h [| (map, x) |])
--
-- The 'map' will be a NameG, and 'x' wil be a NameL
--
-- These Names should never appear in a binding position in a TH syntax tree
{- $namecapture #namecapture#
Much of 'Name' API is concerned with the problem of /name capture/, which
can be seen in the following example.
> f expr = [| let x = 0 in $expr |]
> ...
> g x = $( f [| x |] )
> h y = $( f [| y |] )
A naive desugaring of this would yield:
> g x = let x = 0 in x
> h y = let x = 0 in y
All of a sudden, @g@ and @h@ have different meanings! In this case,
we say that the @x@ in the RHS of @g@ has been /captured/
by the binding of @x@ in @f@.
What we actually want is for the @x@ in @f@ to be distinct from the
@x@ in @g@, so we get the following desugaring:
> g x = let x' = 0 in x
> h y = let x' = 0 in y
which avoids name capture as desired.
In the general case, we say that a @Name@ can be captured if
the thing it refers to can be changed by adding new declarations.
-}
{- |
An abstract type representing names in the syntax tree.
'Name's can be constructed in several ways, which come with different
name-capture guarantees (see "Language.Haskell.TH.Syntax#namecapture" for
an explanation of name capture):
* the built-in syntax @'f@ and @''T@ can be used to construct names,
The expression @'f@ gives a @Name@ which refers to the value @f@
currently in scope, and @''T@ gives a @Name@ which refers to the
type @T@ currently in scope. These names can never be captured.
* 'lookupValueName' and 'lookupTypeName' are similar to @'f@ and
@''T@ respectively, but the @Name@s are looked up at the point
where the current splice is being run. These names can never be
captured.
* 'newName' monadically generates a new name, which can never
be captured.
* 'mkName' generates a capturable name.
Names constructed using @newName@ and @mkName@ may be used in bindings
(such as @let x = ...@ or @\x -> ...@), but names constructed using
@lookupValueName@, @lookupTypeName@, @'f@, @''T@ may not.
-}
data Name = Name OccName NameFlavour deriving (Typeable, Data)
data NameFlavour
= NameS -- ^ An unqualified name; dynamically bound
| NameQ ModName -- ^ A qualified name; dynamically bound
| NameU Int# -- ^ A unique local name
| NameL Int# -- ^ Local name bound outside of the TH AST
| NameG NameSpace PkgName ModName -- ^ Global name bound outside of the TH AST:
-- An original name (occurrences only, not binders)
-- Need the namespace too to be sure which
-- thing we are naming
deriving ( Typeable )
-- |
-- Although the NameFlavour type is abstract, the Data instance is not. The reason for this
-- is that currently we use Data to serialize values in annotations, and in order for that to
-- work for Template Haskell names introduced via the 'x syntax we need gunfold on NameFlavour
-- to work. Bleh!
--
-- The long term solution to this is to use the binary package for annotation serialization and
-- then remove this instance. However, to do _that_ we need to wait on binary to become stable, since
-- boot libraries cannot be upgraded separately from GHC itself.
--
-- This instance cannot be derived automatically due to bug #2701
instance Data NameFlavour where
gfoldl _ z NameS = z NameS
gfoldl k z (NameQ mn) = z NameQ `k` mn
gfoldl k z (NameU i) = z (\(I# i') -> NameU i') `k` (I# i)
gfoldl k z (NameL i) = z (\(I# i') -> NameL i') `k` (I# i)
gfoldl k z (NameG ns p m) = z NameG `k` ns `k` p `k` m
gunfold k z c = case constrIndex c of
1 -> z NameS
2 -> k $ z NameQ
3 -> k $ z (\(I# i) -> NameU i)
4 -> k $ z (\(I# i) -> NameL i)
5 -> k $ k $ k $ z NameG
_ -> error "gunfold: NameFlavour"
toConstr NameS = con_NameS
toConstr (NameQ _) = con_NameQ
toConstr (NameU _) = con_NameU
toConstr (NameL _) = con_NameL
toConstr (NameG _ _ _) = con_NameG
dataTypeOf _ = ty_NameFlavour
con_NameS, con_NameQ, con_NameU, con_NameL, con_NameG :: Data.Constr
con_NameS = mkConstr ty_NameFlavour "NameS" [] Data.Prefix
con_NameQ = mkConstr ty_NameFlavour "NameQ" [] Data.Prefix
con_NameU = mkConstr ty_NameFlavour "NameU" [] Data.Prefix
con_NameL = mkConstr ty_NameFlavour "NameL" [] Data.Prefix
con_NameG = mkConstr ty_NameFlavour "NameG" [] Data.Prefix
ty_NameFlavour :: Data.DataType
ty_NameFlavour = mkDataType "Language.Haskell.TH.Syntax.NameFlavour"
[con_NameS, con_NameQ, con_NameU,
con_NameL, con_NameG]
data NameSpace = VarName -- ^ Variables
| DataName -- ^ Data constructors
| TcClsName -- ^ Type constructors and classes; Haskell has them
-- in the same name space for now.
deriving( Eq, Ord, Data, Typeable )
type Uniq = Int
-- | The name without its module prefix
nameBase :: Name -> String
nameBase (Name occ _) = occString occ
-- | Module prefix of a name, if it exists
nameModule :: Name -> Maybe String
nameModule (Name _ (NameQ m)) = Just (modString m)
nameModule (Name _ (NameG _ _ m)) = Just (modString m)
nameModule _ = Nothing
{- |
Generate a capturable name. Occurrences of such names will be
resolved according to the Haskell scoping rules at the occurrence
site.
For example:
> f = [| pi + $(varE (mkName "pi")) |]
> ...
> g = let pi = 3 in $f
In this case, @g@ is desugared to
> g = Prelude.pi + 3
Note that @mkName@ may be used with qualified names:
> mkName "Prelude.pi"
See also 'Language.Haskell.TH.Lib.dyn' for a useful combinator. The above example could
be rewritten using 'dyn' as
> f = [| pi + $(dyn "pi") |]
-}
mkName :: String -> Name
-- The string can have a '.', thus "Foo.baz",
-- giving a dynamically-bound qualified name,
-- in which case we want to generate a NameQ
--
-- Parse the string to see if it has a "." in it
-- so we know whether to generate a qualified or unqualified name
-- It's a bit tricky because we need to parse
--
-- > Foo.Baz.x as Qual Foo.Baz x
--
-- So we parse it from back to front
mkName str
= split [] (reverse str)
where
split occ [] = Name (mkOccName occ) NameS
split occ ('.':rev) | not (null occ)
, is_rev_mod_name rev
= Name (mkOccName occ) (NameQ (mkModName (reverse rev)))
-- The 'not (null occ)' guard ensures that
-- mkName "&." = Name "&." NameS
-- The 'is_rev_mod' guards ensure that
-- mkName ".&" = Name ".&" NameS
-- mkName "^.." = Name "^.." NameS -- Trac #8633
-- mkName "Data.Bits..&" = Name ".&" (NameQ "Data.Bits")
-- This rather bizarre case actually happened; (.&.) is in Data.Bits
split occ (c:rev) = split (c:occ) rev
-- Recognises a reversed module name xA.yB.C,
-- with at least one component,
-- and each component looks like a module name
-- (i.e. non-empty, starts with capital, all alpha)
is_rev_mod_name rev_mod_str
| (compt, rest) <- break (== '.') rev_mod_str
, not (null compt), isUpper (last compt), all is_mod_char compt
= case rest of
[] -> True
(_dot : rest') -> is_rev_mod_name rest'
| otherwise
= False
is_mod_char c = isAlphaNum c || c == '_' || c == '\''
-- | Only used internally
mkNameU :: String -> Uniq -> Name
mkNameU s (I# u) = Name (mkOccName s) (NameU u)
-- | Only used internally
mkNameL :: String -> Uniq -> Name
mkNameL s (I# u) = Name (mkOccName s) (NameL u)
-- | Used for 'x etc, but not available to the programmer
mkNameG :: NameSpace -> String -> String -> String -> Name
mkNameG ns pkg modu occ
= Name (mkOccName occ) (NameG ns (mkPkgName pkg) (mkModName modu))
mkNameG_v, mkNameG_tc, mkNameG_d :: String -> String -> String -> Name
mkNameG_v = mkNameG VarName
mkNameG_tc = mkNameG TcClsName
mkNameG_d = mkNameG DataName
instance Eq Name where
v1 == v2 = cmpEq (v1 `compare` v2)
instance Ord Name where
(Name o1 f1) `compare` (Name o2 f2) = (f1 `compare` f2) `thenCmp`
(o1 `compare` o2)
instance Eq NameFlavour where
f1 == f2 = cmpEq (f1 `compare` f2)
instance Ord NameFlavour where
-- NameS < NameQ < NameU < NameL < NameG
NameS `compare` NameS = EQ
NameS `compare` _ = LT
(NameQ _) `compare` NameS = GT
(NameQ m1) `compare` (NameQ m2) = m1 `compare` m2
(NameQ _) `compare` _ = LT
(NameU _) `compare` NameS = GT
(NameU _) `compare` (NameQ _) = GT
(NameU u1) `compare` (NameU u2) | isTrue# (u1 <# u2) = LT
| isTrue# (u1 ==# u2) = EQ
| otherwise = GT
(NameU _) `compare` _ = LT
(NameL _) `compare` NameS = GT
(NameL _) `compare` (NameQ _) = GT
(NameL _) `compare` (NameU _) = GT
(NameL u1) `compare` (NameL u2) | isTrue# (u1 <# u2) = LT
| isTrue# (u1 ==# u2) = EQ
| otherwise = GT
(NameL _) `compare` _ = LT
(NameG ns1 p1 m1) `compare` (NameG ns2 p2 m2) = (ns1 `compare` ns2) `thenCmp`
(p1 `compare` p2) `thenCmp`
(m1 `compare` m2)
(NameG _ _ _) `compare` _ = GT
data NameIs = Alone | Applied | Infix
showName :: Name -> String
showName = showName' Alone
showName' :: NameIs -> Name -> String
showName' ni nm
= case ni of
Alone -> nms
Applied
| pnam -> nms
| otherwise -> "(" ++ nms ++ ")"
Infix
| pnam -> "`" ++ nms ++ "`"
| otherwise -> nms
where
-- For now, we make the NameQ and NameG print the same, even though
-- NameQ is a qualified name (so what it means depends on what the
-- current scope is), and NameG is an original name (so its meaning
-- should be independent of what's in scope.
-- We may well want to distinguish them in the end.
-- Ditto NameU and NameL
nms = case nm of
Name occ NameS -> occString occ
Name occ (NameQ m) -> modString m ++ "." ++ occString occ
Name occ (NameG _ _ m) -> modString m ++ "." ++ occString occ
Name occ (NameU u) -> occString occ ++ "_" ++ show (I# u)
Name occ (NameL u) -> occString occ ++ "_" ++ show (I# u)
pnam = classify nms
-- True if we are function style, e.g. f, [], (,)
-- False if we are operator style, e.g. +, :+
classify "" = False -- shouldn't happen; . operator is handled below
classify (x:xs) | isAlpha x || (x `elem` "_[]()") =
case dropWhile (/='.') xs of
(_:xs') -> classify xs'
[] -> True
| otherwise = False
instance Show Name where
show = showName
-- Tuple data and type constructors
-- | Tuple data constructor
tupleDataName :: Int -> Name
-- | Tuple type constructor
tupleTypeName :: Int -> Name
tupleDataName 0 = mk_tup_name 0 DataName
tupleDataName 1 = error "tupleDataName 1"
tupleDataName n = mk_tup_name (n-1) DataName
tupleTypeName 0 = mk_tup_name 0 TcClsName
tupleTypeName 1 = error "tupleTypeName 1"
tupleTypeName n = mk_tup_name (n-1) TcClsName
mk_tup_name :: Int -> NameSpace -> Name
mk_tup_name n_commas space
= Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
where
occ = mkOccName ('(' : replicate n_commas ',' ++ ")")
tup_mod = mkModName "GHC.Tuple"
-- Unboxed tuple data and type constructors
-- | Unboxed tuple data constructor
unboxedTupleDataName :: Int -> Name
-- | Unboxed tuple type constructor
unboxedTupleTypeName :: Int -> Name
unboxedTupleDataName 0 = error "unboxedTupleDataName 0"
unboxedTupleDataName 1 = error "unboxedTupleDataName 1"
unboxedTupleDataName n = mk_unboxed_tup_name (n-1) DataName
unboxedTupleTypeName 0 = error "unboxedTupleTypeName 0"
unboxedTupleTypeName 1 = error "unboxedTupleTypeName 1"
unboxedTupleTypeName n = mk_unboxed_tup_name (n-1) TcClsName
mk_unboxed_tup_name :: Int -> NameSpace -> Name
mk_unboxed_tup_name n_commas space
= Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
where
occ = mkOccName ("(#" ++ replicate n_commas ',' ++ "#)")
tup_mod = mkModName "GHC.Tuple"
-----------------------------------------------------
-- Locations
-----------------------------------------------------
data Loc
= Loc { loc_filename :: String
, loc_package :: String
, loc_module :: String
, loc_start :: CharPos
, loc_end :: CharPos }
type CharPos = (Int, Int) -- ^ Line and character position
-----------------------------------------------------
--
-- The Info returned by reification
--
-----------------------------------------------------
-- | Obtained from 'reify' in the 'Q' Monad.
data Info
=
-- | A class, with a list of its visible instances
ClassI
Dec
[InstanceDec]
-- | A class method
| ClassOpI
Name
Type
ParentName
Fixity
-- | A \"plain\" type constructor. \"Fancier\" type constructors are returned using 'PrimTyConI' or 'FamilyI' as appropriate
| TyConI
Dec
-- | A type or data family, with a list of its visible instances. A closed
-- type family is returned with 0 instances.
| FamilyI
Dec
[InstanceDec]
-- | A \"primitive\" type constructor, which can't be expressed with a 'Dec'. Examples: @(->)@, @Int#@.
| PrimTyConI
Name
Arity
Unlifted
-- | A data constructor
| DataConI
Name
Type
ParentName
Fixity
{- |
A \"value\" variable (as opposed to a type variable, see 'TyVarI').
The @Maybe Dec@ field contains @Just@ the declaration which
defined the variable -- including the RHS of the declaration --
or else @Nothing@, in the case where the RHS is unavailable to
the compiler. At present, this value is _always_ @Nothing@:
returning the RHS has not yet been implemented because of
lack of interest.
-}
| VarI
Name
Type
(Maybe Dec)
Fixity
{- |
A type variable.
The @Type@ field contains the type which underlies the variable.
At present, this is always @'VarT' theName@, but future changes
may permit refinement of this.
-}
| TyVarI -- Scoped type variable
Name
Type -- What it is bound to
deriving( Show, Data, Typeable )
-- | Obtained from 'reifyModule' in the 'Q' Monad.
data ModuleInfo =
-- | Contains the import list of the module.
ModuleInfo [Module]
deriving( Show, Data, Typeable )
{- |
In 'ClassOpI' and 'DataConI', name of the parent class or type
-}
type ParentName = Name
-- | In 'PrimTyConI', arity of the type constructor
type Arity = Int
-- | In 'PrimTyConI', is the type constructor unlifted?
type Unlifted = Bool
-- | 'InstanceDec' desribes a single instance of a class or type function.
-- It is just a 'Dec', but guaranteed to be one of the following:
--
-- * 'InstanceD' (with empty @['Dec']@)
--
-- * 'DataInstD' or 'NewtypeInstD' (with empty derived @['Name']@)
--
-- * 'TySynInstD'
type InstanceDec = Dec
data Fixity = Fixity Int FixityDirection
deriving( Eq, Show, Data, Typeable )
data FixityDirection = InfixL | InfixR | InfixN
deriving( Eq, Show, Data, Typeable )
-- | Highest allowed operator precedence for 'Fixity' constructor (answer: 9)
maxPrecedence :: Int
maxPrecedence = (9::Int)
-- | Default fixity: @infixl 9@
defaultFixity :: Fixity
defaultFixity = Fixity maxPrecedence InfixL
{-
Note [Unresolved infix]
~~~~~~~~~~~~~~~~~~~~~~~
-}
{- $infix #infix#
When implementing antiquotation for quasiquoters, one often wants
to parse strings into expressions:
> parse :: String -> Maybe Exp
But how should we parse @a + b * c@? If we don't know the fixities of
@+@ and @*@, we don't know whether to parse it as @a + (b * c)@ or @(a
+ b) * c@.
In cases like this, use 'UInfixE' or 'UInfixP', which stand for
\"unresolved infix expression\" and \"unresolved infix pattern\". When
the compiler is given a splice containing a tree of @UInfixE@
applications such as
> UInfixE
> (UInfixE e1 op1 e2)
> op2
> (UInfixE e3 op3 e4)
it will look up and the fixities of the relevant operators and
reassociate the tree as necessary.
* trees will not be reassociated across 'ParensE' or 'ParensP',
which are of use for parsing expressions like
> (a + b * c) + d * e
* 'InfixE' and 'InfixP' expressions are never reassociated.
* The 'UInfixE' constructor doesn't support sections. Sections
such as @(a *)@ have no ambiguity, so 'InfixE' suffices. For longer
sections such as @(a + b * c -)@, use an 'InfixE' constructor for the
outer-most section, and use 'UInfixE' constructors for all
other operators:
> InfixE
> Just (UInfixE ...a + b * c...)
> op
> Nothing
Sections such as @(a + b +)@ and @((a + b) +)@ should be rendered
into 'Exp's differently:
> (+ a + b) ---> InfixE Nothing + (Just $ UInfixE a + b)
> -- will result in a fixity error if (+) is left-infix
> (+ (a + b)) ---> InfixE Nothing + (Just $ ParensE $ UInfixE a + b)
> -- no fixity errors
* Quoted expressions such as
> [| a * b + c |] :: Q Exp
> [p| a : b : c |] :: Q Pat
will never contain 'UInfixE', 'UInfixP', 'ParensE', or 'ParensP'
constructors.
-}
-----------------------------------------------------
--
-- The main syntax data types
--
-----------------------------------------------------
data Lit = CharL Char
| StringL String
| IntegerL Integer -- ^ Used for overloaded and non-overloaded
-- literals. We don't have a good way to
-- represent non-overloaded literals at
-- the moment. Maybe that doesn't matter?
| RationalL Rational -- Ditto
| IntPrimL Integer
| WordPrimL Integer
| FloatPrimL Rational
| DoublePrimL Rational
| StringPrimL [Word8] -- ^ A primitive C-style string, type Addr#
deriving( Show, Eq, Data, Typeable )
-- We could add Int, Float, Double etc, as we do in HsLit,
-- but that could complicate the
-- suppposedly-simple TH.Syntax literal type
-- | Pattern in Haskell given in @{}@
data Pat
= LitP Lit -- ^ @{ 5 or 'c' }@
| VarP Name -- ^ @{ x }@
| TupP [Pat] -- ^ @{ (p1,p2) }@
| UnboxedTupP [Pat] -- ^ @{ (# p1,p2 #) }@
| ConP Name [Pat] -- ^ @data T1 = C1 t1 t2; {C1 p1 p1} = e@
| InfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
| UInfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
--
-- See "Language.Haskell.TH.Syntax#infix"
| ParensP Pat -- ^ @{(p)}@
--
-- See "Language.Haskell.TH.Syntax#infix"
| TildeP Pat -- ^ @{ ~p }@
| BangP Pat -- ^ @{ !p }@
| AsP Name Pat -- ^ @{ x \@ p }@
| WildP -- ^ @{ _ }@
| RecP Name [FieldPat] -- ^ @f (Pt { pointx = x }) = g x@
| ListP [ Pat ] -- ^ @{ [1,2,3] }@
| SigP Pat Type -- ^ @{ p :: t }@
| ViewP Exp Pat -- ^ @{ e -> p }@
deriving( Show, Eq, Data, Typeable )
type FieldPat = (Name,Pat)
data Match = Match Pat Body [Dec] -- ^ @case e of { pat -> body where decs }@
deriving( Show, Eq, Data, Typeable )
data Clause = Clause [Pat] Body [Dec]
-- ^ @f { p1 p2 = body where decs }@
deriving( Show, Eq, Data, Typeable )
data Exp
= VarE Name -- ^ @{ x }@
| ConE Name -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @
| LitE Lit -- ^ @{ 5 or 'c'}@
| AppE Exp Exp -- ^ @{ f x }@
| InfixE (Maybe Exp) Exp (Maybe Exp) -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@
-- It's a bit gruesome to use an Exp as the
-- operator, but how else can we distinguish
-- constructors from non-constructors?
-- Maybe there should be a var-or-con type?
-- Or maybe we should leave it to the String itself?
| UInfixE Exp Exp Exp -- ^ @{x + y}@
--
-- See "Language.Haskell.TH.Syntax#infix"
| ParensE Exp -- ^ @{ (e) }@
--
-- See "Language.Haskell.TH.Syntax#infix"
| LamE [Pat] Exp -- ^ @{ \ p1 p2 -> e }@
| LamCaseE [Match] -- ^ @{ \case m1; m2 }@
| TupE [Exp] -- ^ @{ (e1,e2) } @
| UnboxedTupE [Exp] -- ^ @{ (# e1,e2 #) } @
| CondE Exp Exp Exp -- ^ @{ if e1 then e2 else e3 }@
| MultiIfE [(Guard, Exp)] -- ^ @{ if | g1 -> e1 | g2 -> e2 }@
| LetE [Dec] Exp -- ^ @{ let x=e1; y=e2 in e3 }@
| CaseE Exp [Match] -- ^ @{ case e of m1; m2 }@
| DoE [Stmt] -- ^ @{ do { p <- e1; e2 } }@
| CompE [Stmt] -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@
--
-- The result expression of the comprehension is
-- the /last/ of the @'Stmt'@s, and should be a 'NoBindS'.
--
-- E.g. translation:
--
-- > [ f x | x <- xs ]
--
-- > CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))]
| ArithSeqE Range -- ^ @{ [ 1 ,2 .. 10 ] }@
| ListE [ Exp ] -- ^ @{ [1,2,3] }@
| SigE Exp Type -- ^ @{ e :: t }@
| RecConE Name [FieldExp] -- ^ @{ T { x = y, z = w } }@
| RecUpdE Exp [FieldExp] -- ^ @{ (f x) { z = w } }@
deriving( Show, Eq, Data, Typeable )
type FieldExp = (Name,Exp)
-- Omitted: implicit parameters
data Body
= GuardedB [(Guard,Exp)] -- ^ @f p { | e1 = e2
-- | e3 = e4 }
-- where ds@
| NormalB Exp -- ^ @f p { = e } where ds@
deriving( Show, Eq, Data, Typeable )
data Guard
= NormalG Exp -- ^ @f x { | odd x } = x@
| PatG [Stmt] -- ^ @f x { | Just y <- x, Just z <- y } = z@
deriving( Show, Eq, Data, Typeable )
data Stmt
= BindS Pat Exp
| LetS [ Dec ]
| NoBindS Exp
| ParS [[Stmt]]
deriving( Show, Eq, Data, Typeable )
data Range = FromR Exp | FromThenR Exp Exp
| FromToR Exp Exp | FromThenToR Exp Exp Exp
deriving( Show, Eq, Data, Typeable )
data Dec
= FunD Name [Clause] -- ^ @{ f p1 p2 = b where decs }@
| ValD Pat Body [Dec] -- ^ @{ p = b where decs }@
| DataD Cxt Name [TyVarBndr]
[Con] [Name] -- ^ @{ data Cxt x => T x = A x | B (T x)
-- deriving (Z,W)}@
| NewtypeD Cxt Name [TyVarBndr]
Con [Name] -- ^ @{ newtype Cxt x => T x = A (B x)
-- deriving (Z,W)}@
| TySynD Name [TyVarBndr] Type -- ^ @{ type T x = (x,x) }@
| ClassD Cxt Name [TyVarBndr]
[FunDep] [Dec] -- ^ @{ class Eq a => Ord a where ds }@
| InstanceD Cxt Type [Dec] -- ^ @{ instance Show w => Show [w]
-- where ds }@
| SigD Name Type -- ^ @{ length :: [a] -> Int }@
| ForeignD Foreign -- ^ @{ foreign import ... }
--{ foreign export ... }@
| InfixD Fixity Name -- ^ @{ infix 3 foo }@
-- | pragmas
| PragmaD Pragma -- ^ @{ {\-# INLINE [1] foo #-\} }@
-- | type families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
| FamilyD FamFlavour Name
[TyVarBndr] (Maybe Kind) -- ^ @{ type family T a b c :: * }@
| DataInstD Cxt Name [Type]
[Con] [Name] -- ^ @{ data instance Cxt x => T [x] = A x
-- | B (T x)
-- deriving (Z,W)}@
| NewtypeInstD Cxt Name [Type]
Con [Name] -- ^ @{ newtype instance Cxt x => T [x] = A (B x)
-- deriving (Z,W)}@
| TySynInstD Name TySynEqn -- ^ @{ type instance ... }@
| ClosedTypeFamilyD Name
[TyVarBndr] (Maybe Kind)
[TySynEqn] -- ^ @{ type family F a b :: * where ... }@
| RoleAnnotD Name [Role] -- ^ @{ type role T nominal representational }@
deriving( Show, Eq, Data, Typeable )
-- | One equation of a type family instance or closed type family. The
-- arguments are the left-hand-side type patterns and the right-hand-side
-- result.
data TySynEqn = TySynEqn [Type] Type
deriving( Show, Eq, Data, Typeable )
data FunDep = FunDep [Name] [Name]
deriving( Show, Eq, Data, Typeable )
data FamFlavour = TypeFam | DataFam
deriving( Show, Eq, Data, Typeable )
data Foreign = ImportF Callconv Safety String Name Type
| ExportF Callconv String Name Type
deriving( Show, Eq, Data, Typeable )
data Callconv = CCall | StdCall
deriving( Show, Eq, Data, Typeable )
data Safety = Unsafe | Safe | Interruptible
deriving( Show, Eq, Data, Typeable )
data Pragma = InlineP Name Inline RuleMatch Phases
| SpecialiseP Name Type (Maybe Inline) Phases
| SpecialiseInstP Type
| RuleP String [RuleBndr] Exp Exp Phases
| AnnP AnnTarget Exp
deriving( Show, Eq, Data, Typeable )
data Inline = NoInline
| Inline
| Inlinable
deriving (Show, Eq, Data, Typeable)
data RuleMatch = ConLike
| FunLike
deriving (Show, Eq, Data, Typeable)
data Phases = AllPhases
| FromPhase Int
| BeforePhase Int
deriving (Show, Eq, Data, Typeable)
data RuleBndr = RuleVar Name
| TypedRuleVar Name Type
deriving (Show, Eq, Data, Typeable)
data AnnTarget = ModuleAnnotation
| TypeAnnotation Name
| ValueAnnotation Name
deriving (Show, Eq, Data, Typeable)
type Cxt = [Pred] -- ^ @(Eq a, Ord b)@
data Pred = ClassP Name [Type] -- ^ @Eq (Int, a)@
| EqualP Type Type -- ^ @F a ~ Bool@
deriving( Show, Eq, Data, Typeable )
data Strict = IsStrict | NotStrict | Unpacked
deriving( Show, Eq, Data, Typeable )
data Con = NormalC Name [StrictType] -- ^ @C Int a@
| RecC Name [VarStrictType] -- ^ @C { v :: Int, w :: a }@
| InfixC StrictType Name StrictType -- ^ @Int :+ a@
| ForallC [TyVarBndr] Cxt Con -- ^ @forall a. Eq a => C [a]@
deriving( Show, Eq, Data, Typeable )
type StrictType = (Strict, Type)
type VarStrictType = (Name, Strict, Type)
data Type = ForallT [TyVarBndr] Cxt Type -- ^ @forall \<vars\>. \<ctxt\> -> \<type\>@
| AppT Type Type -- ^ @T a b@
| SigT Type Kind -- ^ @t :: k@
| VarT Name -- ^ @a@
| ConT Name -- ^ @T@
| PromotedT Name -- ^ @'T@
-- See Note [Representing concrete syntax in types]
| TupleT Int -- ^ @(,), (,,), etc.@
| UnboxedTupleT Int -- ^ @(#,#), (#,,#), etc.@
| ArrowT -- ^ @->@
| ListT -- ^ @[]@
| PromotedTupleT Int -- ^ @'(), '(,), '(,,), etc.@
| PromotedNilT -- ^ @'[]@
| PromotedConsT -- ^ @(':)@
| StarT -- ^ @*@
| ConstraintT -- ^ @Constraint@
| LitT TyLit -- ^ @0,1,2, etc.@
deriving( Show, Eq, Data, Typeable )
data TyVarBndr = PlainTV Name -- ^ @a@
| KindedTV Name Kind -- ^ @(a :: k)@
deriving( Show, Eq, Data, Typeable )
data TyLit = NumTyLit Integer -- ^ @2@
| StrTyLit String -- ^ @"Hello"@
deriving ( Show, Eq, Data, Typeable )
-- | Role annotations
data Role = NominalR -- ^ @nominal@
| RepresentationalR -- ^ @representational@
| PhantomR -- ^ @phantom@
| InferR -- ^ @_@
deriving( Show, Eq, Data, Typeable )
-- | Annotation target for reifyAnnotations
data AnnLookup = AnnLookupModule Module
| AnnLookupName Name
deriving( Show, Eq, Data, Typeable )
-- | To avoid duplication between kinds and types, they
-- are defined to be the same. Naturally, you would never
-- have a type be 'StarT' and you would never have a kind
-- be 'SigT', but many of the other constructors are shared.
-- Note that the kind @Bool@ is denoted with 'ConT', not
-- 'PromotedT'. Similarly, tuple kinds are made with 'TupleT',
-- not 'PromotedTupleT'.
type Kind = Type
{- Note [Representing concrete syntax in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Haskell has a rich concrete syntax for types, including
t1 -> t2, (t1,t2), [t], and so on
In TH we represent all of this using AppT, with a distinguished
type constructor at the head. So,
Type TH representation
-----------------------------------------------
t1 -> t2 ArrowT `AppT` t2 `AppT` t2
[t] ListT `AppT` t
(t1,t2) TupleT 2 `AppT` t1 `AppT` t2
'(t1,t2) PromotedTupleT 2 `AppT` t1 `AppT` t2
But if the original HsSyn used prefix application, we won't use
these special TH constructors. For example
[] t ConT "[]" `AppT` t
(->) t ConT "->" `AppT` t
In this way we can faithfully represent in TH whether the original
HsType used concrete syntax or not.
The one case that doesn't fit this pattern is that of promoted lists
'[ Maybe, IO ] PromotedListT 2 `AppT` t1 `AppT` t2
but it's very smelly because there really is no type constructor
corresponding to PromotedListT. So we encode HsExplicitListTy with
PromotedConsT and PromotedNilT (which *do* have underlying type
constructors):
'[ Maybe, IO ] PromotedConsT `AppT` Maybe `AppT`
(PromotedConsT `AppT` IO `AppT` PromotedNilT)
-}
-----------------------------------------------------
-- Internal helper functions
-----------------------------------------------------
cmpEq :: Ordering -> Bool
cmpEq EQ = True
cmpEq _ = False
thenCmp :: Ordering -> Ordering -> Ordering
thenCmp EQ o2 = o2
thenCmp o1 _ = o1
| jwiegley/ghc-release | libraries/template-haskell/Language/Haskell/TH/Syntax.hs | gpl-3.0 | 49,509 | 36 | 14 | 13,669 | 8,738 | 4,805 | 3,933 | 623 | 9 |
{-# LANGUAGE NoImplicitPrelude #-}
module Bamboo.Theme.MiniHTML5.Widget.Helper where
import Bamboo.Theme.MiniHTML5.Env hiding (link, p)
import qualified Bamboo.Model.Tag as Tag
import qualified Bamboo.Type as C
import qualified Bamboo.Type.State as State
import MPS
import Data.Maybe
rss_url_link_pair :: State.State -> (String, MoeUnit)
rss_url_link_pair s =
if tagged
then link ( s.config.tag_id / tag_name) tag_name
else link "" home_nav
where
tag_name = Tag.get_name uid
uid = State.uid s
tagged = uid.match "^tag/.+" .isJust
url r = s.env.slashed_script_name / r / "rss.xml"
link r x = (url r, a [href - url r, _class "feed"] - div [_class "feedlink"] - str x)
tag_link :: State -> String -> MoeUnit
tag_link s x = a [href - s.env.slashed_script_name / s.config.tag_id / x ] - str x
nav :: Pager -> String -> MoeUnit
nav p r = nav' - do
nav_previous
nav_next
where
r' = if r.ends_with "&" then r else r ++ "?"
space_html = str " "
nav_previous =
if p.has_previous
then
a [_class "previous", href - r' ++ "page=" ++ p.previous.show] -
str "« Next Entries"
else space_html
nav_next =
if p.has_next
then
a [_class "next", href - r' ++ "page=" ++ p.next.show] -
str "Previous Entries »"
else space_html
| nfjinjing/bamboo-theme-mini-html5 | src/Bamboo/Theme/MiniHTML5/Widget/Helper.hs | gpl-3.0 | 1,359 | 1 | 13 | 348 | 449 | 242 | 207 | 36 | 4 |
import Types
import Process (runProgram)
import FileIO (loadFile)
import Errors (showError)
import System.Exit (exitFailure, exitSuccess)
import Data.Maybe (fromJust)
goal = "A"
file = "extra/simple.pco"
tape = Tape {
bytes = [(Cell 0) | x <- [0..]],
cursor = 0
}
checkResult :: String -> IO()
checkResult x
| x == goal = exitSuccess
| otherwise = do putStrLn $ showError ("Simple Test DID NOT return the goal value!\nReturned: " ++ x ++ "\nInstead of: " ++ goal)
exitFailure
main = do prg <- loadFile (file)
checkResult $ runProgram prg tape (-1) | toish/Pico | test/simple.hs | gpl-3.0 | 598 | 0 | 13 | 141 | 206 | 110 | 96 | 18 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
module Hkl.Detector
( Detector(..)
, coordinates
) where
import Hkl.PyFAI.Npt
import Numeric.LinearAlgebra
data ImXpadS140
data Xpad32
data ZeroD
data Detector a where
ImXpadS140 :: Detector ImXpadS140
Xpad32 :: Detector Xpad32
ZeroD :: Detector ZeroD
deriving instance Show (Detector a)
-- | Xpad Family
type Gap = Double
type Width = Int
type Index = Int
-- an xpad line is like this (pixel size, index)
-- | s 0 | s 1 | s 2 | ... | 5/2 s (w - 1) || 5/2 s w | s (w + 1) | ...
xpadLine :: Width -> Index -> Double
xpadLine w i'
| i' == 0 = s / 2
| i' == 1 = s * 3 / 2
| idx == 0 = s * (fromIntegral i' + 3 * fromIntegral c - 1 / 4)
| idx <= (w - 2) = s * (fromIntegral i' + 3 * fromIntegral c + 1 / 2)
| idx == (w - 1) = s * (fromIntegral i' + 3 * fromIntegral c + 5 / 4)
| otherwise = error $ "wront coordinates" ++ show i'
where
s = 130e-6
(c, idx) = divMod i' w
xpadLineWithGap :: Width -> Gap -> Index -> Double
xpadLineWithGap w g i' = s / 2 + (s * fromIntegral i') + g * fromIntegral (div i' w)
where
s = 130e-6
interp :: (Int -> Double) -> Double -> Double
interp f p
| p0 == p1 = f p0
| otherwise = (p - fromIntegral p0) * (f p1 - f p0) + f p0
where
p0 :: Int
p0 = floor p
p1 :: Int
p1 = ceiling p
-- compute the coordinated at a given point
coordinates :: Detector a -> NptPoint -> Vector Double
coordinates ZeroD (NptPoint 0 0) = fromList [0, 0, 0]
coordinates ZeroD _ = error "No coordinates in a ZeroD detecteor"
coordinates ImXpadS140 (NptPoint x y) =
fromList [ interp (xpadLine 120) y
, interp (xpadLine 80) x
, 0
]
coordinates Xpad32 (NptPoint x y) =
fromList [ interp (xpadLineWithGap 120 3.57e-3) y
, interp (xpadLine 80) x
, 0]
| picca/hkl | contrib/haskell/src/Hkl/Detector.hs | gpl-3.0 | 1,949 | 0 | 12 | 580 | 703 | 362 | 341 | -1 | -1 |
-- sth-charfullwidth: replace characters with fullwidth equivalents
module Main where
import System.Exit (exitSuccess)
import STH.Lib (charFilter, toFullwidth)
main :: IO ()
main = do
charFilter (map toFullwidth)
exitSuccess
| nbloomf/st-haskell | src/STH/CharFullwidth/Main.hs | gpl-3.0 | 233 | 0 | 9 | 36 | 58 | 32 | 26 | 7 | 1 |
import Control.Monad as M
import Control.Monad.IO.Class
import Data.Char
import Data.Conduit
import Data.Conduit.List as CL
import Data.List as L
import Data.Text.Lazy as TL
import Data.Text.Lazy.IO as TL
import Data.Text.Lazy.Read as TL
import Graphics.Rendering.Chart.Backend.Cairo
import Graphics.Rendering.Chart.Easy
import System.Environment
import System.IO as IO
data L1NormInfo =
L1NormInfo !Int
!Int
!Int
!Double
deriving (Show)
{-# INLINE parseL1NormInfo #-}
parseL1NormInfo :: Text -> L1NormInfo
parseL1NormInfo txt =
case (double . TL.dropWhile (not . isDigit) $ txt) of
Left msg1 -> error msg1
Right (time, txt1) ->
case (decimal . TL.dropWhile (not . isDigit) $ txt1) of
Left msg2 -> error msg2
Right (batchNum, txt2) ->
case (decimal . TL.dropWhile (not . isDigit) $ txt2) of
Left msg3 -> error msg3
Right (numNeurons, txt3) ->
case (double .
TL.dropWhile (not . isDigit) .
TL.drop 1 . TL.dropWhile (not . isDigit) $
txt3) of
Left msg4 -> error msg4
Right (l1, txt4) ->
L1NormInfo (round time) batchNum numNeurons l1
energyFileSource :: FilePath -> Source IO L1NormInfo
energyFileSource filePath = do
h <- liftIO $ openFile filePath ReadMode
x <- liftIO $ TL.hGetLine h
xs <- liftIO $ TL.hGetContents h
sourceList . L.map parseL1NormInfo . TL.lines $ xs
liftIO $ hClose h
sink :: Int -> Double -> Sink L1NormInfo IO [(Int,Double)]
sink n m = do
CL.drop n
xs <- CL.consume
return $!
L.map
(\(L1NormInfo t _ _ e) ->
if e > m
then (t, m)
else (t, e))
xs
takeOdd :: Int -> [a] -> [a]
takeOdd 0 xs = xs
takeOdd _ [] = []
takeOdd n xs = (L.take n xs) L.++ (takeOdd n . L.drop (2 * n) $ xs)
takeEven :: Int -> [a] -> [a]
takeEven 0 xs = xs
takeEven _ [] = []
takeEven n xs =
(L.drop n . L.take (2 * n) $ xs) L.++ (takeEven n . L.drop (2 * n) $ xs)
main = do
(folderPath:numBatchStr:numLastTakeStr:displayPeriodStr:thresholdStr:_) <- getArgs
let str = "S3_L1ProbeTop"
fileNames =
L.map
(\i -> folderPath L.++ "/" L.++ str
L.++ ".txt")
[0 .. (read numBatchStr :: Int) - 1]
print (L.head fileNames)
numLines <- fmap (L.length . L.lines) . IO.readFile $ (L.head fileNames)
print numLines
xs <-
M.mapM
(\path -> energyFileSource path $$ sink (numLines - (read numLastTakeStr :: Int)) (read thresholdStr :: Double))
fileNames
print . L.length . takeEven (read displayPeriodStr :: Int) . L.head $ xs
toFile def "l1norm.png" $ do
layout_title .= "L1Norm"
M.zipWithM_ (\i x -> plot (line (show i) [takeOdd (read displayPeriodStr :: Int) x])) [0 ..] xs
| XinhuaZhang/PetaVisionHaskell | Application/PVPAnalysis/PlotL1Norm.hs | gpl-3.0 | 3,123 | 0 | 22 | 1,084 | 1,150 | 594 | 556 | 92 | 5 |
module OutputParsers
( MachineInfo(..)
, MachineName
, parseMachineInfo
) where
import Prelude hiding (takeWhile)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
import Data.Attoparsec.ByteString.Char8
type MachineName = ByteString
data MachineInfo = MachineInfo
{ mi_name :: MachineName
, mi_memory :: Integer
, mi_ncpus :: Int
, mi_productName :: ByteString
} deriving (Eq, Ord, Show, Read)
machineInfoParser :: MachineName -> Parser MachineInfo
machineInfoParser mName = do
string "MemTotal:"
skipSpace
mem <- decimal
string " kB\n"
ncpus <- decimal
char '\n'
productName <- takeWhile (/= '\n')
char '\n'
return $ MachineInfo mName (mem * 1024) ncpus productName
parseMachineInfo :: MachineName -> ByteString -> Either String MachineInfo
parseMachineInfo mName = parseOnly (machineInfoParser mName)
| mjansen/remote-command | OutputParsers.hs | gpl-3.0 | 896 | 0 | 10 | 170 | 245 | 132 | 113 | 28 | 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.Compute.RegionDisks.GetIAMPolicy
-- 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)
--
-- Gets the access control policy for a resource. May be empty if no such
-- policy or resource exists.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionDisks.getIamPolicy@.
module Network.Google.Resource.Compute.RegionDisks.GetIAMPolicy
(
-- * REST Resource
RegionDisksGetIAMPolicyResource
-- * Creating a Request
, regionDisksGetIAMPolicy
, RegionDisksGetIAMPolicy
-- * Request Lenses
, rdgipProject
, rdgipResource
, rdgipOptionsRequestedPolicyVersion
, rdgipRegion
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.regionDisks.getIamPolicy@ method which the
-- 'RegionDisksGetIAMPolicy' request conforms to.
type RegionDisksGetIAMPolicyResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"disks" :>
Capture "resource" Text :>
"getIamPolicy" :>
QueryParam "optionsRequestedPolicyVersion"
(Textual Int32)
:> QueryParam "alt" AltJSON :> Get '[JSON] Policy
-- | Gets the access control policy for a resource. May be empty if no such
-- policy or resource exists.
--
-- /See:/ 'regionDisksGetIAMPolicy' smart constructor.
data RegionDisksGetIAMPolicy =
RegionDisksGetIAMPolicy'
{ _rdgipProject :: !Text
, _rdgipResource :: !Text
, _rdgipOptionsRequestedPolicyVersion :: !(Maybe (Textual Int32))
, _rdgipRegion :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RegionDisksGetIAMPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rdgipProject'
--
-- * 'rdgipResource'
--
-- * 'rdgipOptionsRequestedPolicyVersion'
--
-- * 'rdgipRegion'
regionDisksGetIAMPolicy
:: Text -- ^ 'rdgipProject'
-> Text -- ^ 'rdgipResource'
-> Text -- ^ 'rdgipRegion'
-> RegionDisksGetIAMPolicy
regionDisksGetIAMPolicy pRdgipProject_ pRdgipResource_ pRdgipRegion_ =
RegionDisksGetIAMPolicy'
{ _rdgipProject = pRdgipProject_
, _rdgipResource = pRdgipResource_
, _rdgipOptionsRequestedPolicyVersion = Nothing
, _rdgipRegion = pRdgipRegion_
}
-- | Project ID for this request.
rdgipProject :: Lens' RegionDisksGetIAMPolicy Text
rdgipProject
= lens _rdgipProject (\ s a -> s{_rdgipProject = a})
-- | Name or id of the resource for this request.
rdgipResource :: Lens' RegionDisksGetIAMPolicy Text
rdgipResource
= lens _rdgipResource
(\ s a -> s{_rdgipResource = a})
-- | Requested IAM Policy version.
rdgipOptionsRequestedPolicyVersion :: Lens' RegionDisksGetIAMPolicy (Maybe Int32)
rdgipOptionsRequestedPolicyVersion
= lens _rdgipOptionsRequestedPolicyVersion
(\ s a -> s{_rdgipOptionsRequestedPolicyVersion = a})
. mapping _Coerce
-- | The name of the region for this request.
rdgipRegion :: Lens' RegionDisksGetIAMPolicy Text
rdgipRegion
= lens _rdgipRegion (\ s a -> s{_rdgipRegion = a})
instance GoogleRequest RegionDisksGetIAMPolicy where
type Rs RegionDisksGetIAMPolicy = Policy
type Scopes RegionDisksGetIAMPolicy =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient RegionDisksGetIAMPolicy'{..}
= go _rdgipProject _rdgipRegion _rdgipResource
_rdgipOptionsRequestedPolicyVersion
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy RegionDisksGetIAMPolicyResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/RegionDisks/GetIAMPolicy.hs | mpl-2.0 | 4,698 | 0 | 18 | 1,073 | 571 | 336 | 235 | 92 | 1 |
import System.Plugins
main = do loadPackage "base"
unloadPackage "base"
loadPackage "base"
| Changaco/haskell-plugins | testsuite/load/unloadpkg/Main.hs | lgpl-2.1 | 114 | 0 | 7 | 34 | 29 | 12 | 17 | 4 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE BangPatterns,OverloadedStrings, FlexibleContexts #-}
module Proc.CodeBlock (toCodeBlock, runCodeBlock, CodeBlock) where
import Control.Monad.State
import Control.Monad.Except
import Data.Array.IO
import qualified Data.Map as M
import VarName (arrName, NSQual(..), VarName, NSTag)
import qualified Data.ByteString.Char8 as B
import Core
import qualified RToken as R
-- import RToken (asParsed,Cmd(..), RTokCmd)
import RToken (Cmd(..))
import Common
import qualified TclObj as T
import Util
type CmdName = NSQual BString
data CmdTag = CmdTag !Int !CmdName
data CompCmd = CompCmd (Maybe CmdTag) (Either [R.RTokCmd] [CToken]) Cmd
data CodeBlock = CodeBlock CmdCache [CompCmd]
type TclCmd = [T.TclObj] -> TclM T.TclObj
type CacheEntry = (Maybe TclCmd, CmdName)
data CmdCache = CmdCache !(IOArray Int CacheEntry)
type CmdIds = M.Map CmdName Int
data CState = CState Int CmdIds deriving (Show)
type CErr = String
newtype CompM a = CompM { unCompM :: ExceptT CErr (StateT CState IO) a }
deriving (MonadState CState, MonadError CErr, MonadIO, Monad, Applicative,Functor)
runCompM code s = runStateT (runExceptT (unCompM code)) s
toCodeBlock :: T.TclObj -> TclM CodeBlock
toCodeBlock o = do
(e_cmds,st) <- R.asParsed o >>= liftIO . compile
carr <- makeCmdArray st >>= return . CmdCache
registerWatcher (invalidateCache carr)
case e_cmds of
Left e -> tclErr e
Right cmds -> return (CodeBlock carr cmds)
compile p = runCompM (mapM compCmd p) (CState 0 M.empty)
makeCmdArray :: CState -> TclM (IOArray Int (Maybe TclCmd, CmdName))
makeCmdArray (CState _ m) = do
let size = M.size m
liftIO $ newListArray (0,size-1) (map (\k -> (Nothing,k))(M.keys m))
getTag :: CmdName -> CompM CmdTag
getTag cn = do
(CState i mi) <- get
case M.lookup cn mi of
Just ct -> return (CmdTag ct cn)
Nothing -> do
put (CState (succ i) (M.insert cn i mi))
return (CmdTag i cn)
compCmd :: Cmd -> CompM CompCmd
compCmd c@(Cmd (R.BasicCmd cn) args) = do
ti <- getTag cn
nargs <- (mapM compToken args >>= return . Right) `ifFails` (Left args)
return $ CompCmd (Just ti) nargs c
compCmd a = fail $ "no compile" ++ show a
data CToken
= Lit !T.TclObj
| CatLst [CToken]
| CmdTok [CompCmd]
| ExpTok CToken
| VarRef !(NSQual VarName)
| ArrRef !(Maybe NSTag) !BString CToken
| Block !T.TclObj
compToken tok = case tok of
R.CmdTok t -> mapM compCmd t >>= return . CmdTok
R.ExpTok t -> ExpTok <$> compToken t
R.ArrRef mtag n t -> compToken t >>= \nt -> return $ ArrRef mtag n nt
R.VarRef v -> return $ VarRef v
R.Block s p -> return (Block (T.fromBlock s p))
R.Lit s -> return $! Lit (T.fromBStr s)
R.LitInt i -> return $! Lit (T.fromInt i)
R.CatLst lst -> mapM compToken lst >>= return . CatLst
invalidateCache (CmdCache carr) = do
(a,z) <- liftIO $ getBounds carr
mapM_ (\i -> modInd i (\(_,cn) -> (Nothing,cn))) [a..z]
where modInd i f = readArray carr i >>= writeArray carr i . f
getCacheCmd (CmdCache carr) (CmdTag cind cn) = do
(mcmd,_) <- liftIO $! readArray carr cind
case mcmd of
Just _ -> return mcmd
Nothing -> do
mcmd2 <- getCmdNS cn
case mcmd2 of
Nothing -> return Nothing
Just cmd -> do
let act al = cmd `applyTo` al
let jact = Just act
liftIO $ writeArray carr cind (jact,cn)
return jact
evalCompCmd cc (CompCmd mct nargs c) =
case mct of
Nothing -> evalTcl c
Just ct -> do
mcmd <- getCacheCmd cc ct
case mcmd of
Just cmd -> eArgs >>= cmd
Nothing -> evalTcl c
where eArgs = case nargs of
Left args -> evalArgs args
Right al -> evalCompArgs (evalThem cc) al
evalCompArgs cmdFn al = evalCTokens al [] where
evalCTokens [] !acc = return $ reverse acc
evalCTokens (x:xs) !acc = case x of
Lit s -> next s
CmdTok t -> cmdFn t >>= next
Block o -> next o
VarRef vn -> varGetNS vn >>= next
ArrRef ns n i -> do
ni <- evalArgs_ [i] >>= return . T.asBStr . head
varGetNS (NSQual ns (arrName n ni)) >>= next
CatLst l -> evalArgs_ l >>= next . T.fromBStr . B.concat . map T.asBStr
ExpTok t -> do
[rs] <- evalArgs_ [t]
l <- T.asList rs
evalCTokens xs ((reverse l) ++ acc)
where next !r = evalCTokens xs (r:acc)
{-# INLINE next #-}
evalArgs_ args = evalCTokens args []
evalThem cc = go
where run_eval = evalCompCmd cc
go [] = ret
go [x] = run_eval x
go (x:xs) = run_eval x >> go xs
instance Runnable CodeBlock where
evalTcl = runCodeBlock
runCodeBlock (CodeBlock cc cl) = evalThem cc cl
| tolysz/hiccup | Proc/CodeBlock.hs | lgpl-2.1 | 4,923 | 0 | 20 | 1,378 | 1,964 | 978 | 986 | 142 | 8 |
{- nbd - A Haskell library to implement NBD servers
-
- Copyright (C) 2012 Nicolas Trangez
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-}
{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables #-}
module Network.NBD.Server.Simple (
-- * Action result representations
Response(..)
, ReadResponse(..)
, FileRange(..)
-- * Action handlers
, ExportHandler(..)
, FileOffset, ByteCount
, NbdCommandFlag(..)
, Flags
, ReadHandler
, WriteHandler
, FlushHandler
, TrimHandler
, DisconnectHandler
, CommandId, UnknownCommandHandler
-- * Server execution
, ExportMaker
, ServerSettings(..)
, HostPreference(..)
, nBD_DEFAULT_PORT
, runServer
-- * Utilities
, withBoundsCheck
) where
import Control.Exception (catch)
import Control.Exception.Base (Exception, SomeException, throwIO, try)
import GHC.IO.Exception (ioe_errno)
import Control.Monad.Trans (lift)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Maybe (isJust, isNothing)
import Data.Conduit hiding (Flush)
import Data.Conduit.Network hiding (ServerSettings)
import Data.Conduit.Network.Basic (ServerSettings(..))
import qualified Data.Conduit.Network.Basic as NB
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Typeable (Typeable)
import Data.Word (Word32)
import Network.Socket (Socket)
import qualified Network.Socket as NS
import Network.Sendfile (FileRange(..), sendfileFdWithHeader)
import Foreign.C.Error (Errno(Errno), eINVAL, eOPNOTSUPP, getErrno)
import System.Posix.Types (Fd)
import Network.NBD (ExportName, Handle, ByteCount, FileOffset, NbdCommandFlag(..), NbdExportFlag(..), nBD_DEFAULT_PORT)
import Network.NBD.Server
data NbdAppData m = NbdAppData { nbdAppSource :: Source m BS.ByteString
, nbdAppSink :: Sink BS.ByteString m ()
, nbdAppSockAddr :: NS.SockAddr
, nbdAppSocket :: Socket
}
-- | Response data returned by a 'ReadHandler'
data ReadResponse = Data LBS.ByteString -- ^ Return given data as request reply
| Sendfile Fd FileRange -- ^ Use sendfile to return some data
-- | Success indicator returned by action handlers
data Response a = OK a -- ^ Success
| Error Errno -- ^ Failure. The given 'Errno' will be returned to the client
-- | Command identifier for requests received from a client
type CommandId = Word32
-- | Type synonym for a list of 'NbdCommandFlag's
type Flags = [NbdCommandFlag]
-- | 'Read' request handler prototype
type ReadHandler = FileOffset -> ByteCount -> Flags -> IO (Response ReadResponse)
-- | 'Write' request handler prototype
type WriteHandler = FileOffset -> LBS.ByteString -> Flags -> IO (Response ())
-- | 'Flush' request handler prototype
type FlushHandler = Flags -> IO (Response ())
-- | 'Trim' request handler prototype
type TrimHandler = FileOffset -> ByteCount -> Flags -> IO (Response ())
-- | Disconnect request handler prototype. Note the connection will be
-- closed by the server when receiving a 'Disconnect' request, after
-- executing any given handler, even if the handler throws an 'Exception'.
type DisconnectHandler = Flags -> IO ()
-- | Unknown request handler prototype
type UnknownCommandHandler = CommandId -> FileOffset -> ByteCount -> Flags -> IO (Response ())
-- | Action vtable to handle client requests. Any 'Maybe' field can be set
-- to 'Nothing', which implies the given feature is not available on the
-- server. The feature flags sent to a client during protocol negotiation
-- will be based on this.
data ExportHandler = ExportHandler { handleRead :: ReadHandler -- ^ Handle a 'Read' request
, handleWrite :: Maybe WriteHandler -- ^ Handle a 'Write' request
, handleFlush :: Maybe FlushHandler -- ^ Handle a 'Flush' request
, handleTrim :: Maybe TrimHandler -- ^ Handle a 'Trim' request
, handleDisconnect :: Maybe DisconnectHandler -- ^ Action to run prior to disconnecting a client due to a 'Disconnect' request
, handleUnknownCommand :: Maybe UnknownCommandHandler -- ^ Handle an unknown request
, handleSize :: ByteCount -- ^ Size of the export
, handleHasFUA :: Bool -- ^ Server supports the 'ForceUnitAccess' request flag
, handleIsRotational :: Bool -- ^ Server exposes a rotational device (which might impact the client IO scheduler)
}
-- | Prototype of an action turning a 'SockAddr' and 'ExportName' into an
-- export, or rather its 'ExportHandler' vtable. If 'Nothing' is returned,
-- this implies the given 'ExportName' was invalid, and the server should
-- act accordingly.
type ExportMaker = NS.SockAddr -> ExportName -> IO (Maybe ExportHandler)
-- | Exceptions generated by the server
data ServerError = InvalidExport ExportName -- ^ Client requested an unknown or invalid export
deriving (Show, Typeable)
instance Exception ServerError
data Forever a = Loop
| Return a
forever' :: Monad m => m (Forever a) -> m a
forever' act = loop Loop
where
loop Loop = act >>= loop
loop (Return a) = return a
application :: Maybe [ExportName]
-> ExportMaker
-> NbdAppData IO
-> IO ()
application exportNames exportMaker client =
nbdAppSource client $= handler $$ nbdAppSink client
where
handler = do
target <- negotiateNewstyle exportNames
maybeHandler <- lift $ exportMaker (nbdAppSockAddr client) target
case maybeHandler of
Nothing -> liftIO $ throwIO $ InvalidExport target
Just handler' -> do
sendExportInformation (handleSize handler') (calculateFlags handler')
loop handler'
calculateFlags :: ExportHandler -> [NbdExportFlag]
calculateFlags handler' = HasFlags : map snd (filter fst flags)
where
flags = [ (isNothing $ handleWrite handler', ReadOnly)
, (isJust $ handleFlush handler', SendFlush)
, (handleHasFUA handler', SendFua)
, (handleIsRotational handler', Rotational)
, (isJust $ handleTrim handler', SendTrim)
]
loop = forever' . loop'
loop' handler' = do
req <- getCommand
case req of
Read h o l f -> do
handleErrno h
(maybe (return ()) (\v -> case v of
Error e -> sendError h e
OK d -> sendReplyData h d))
(do
val <- handleRead handler' o l f
case val of
Error e -> return $ Just $ Error e
OK (Data d) -> return $ Just $ OK d
OK (Sendfile fd r) -> do
sendReplyData' h (\header ->
liftIO $ sendfileFdWithHeader (nbdAppSocket client) fd r (return ()) [header])
return Nothing)
return Loop
Write h o d f -> do
ifSupported h handler' handleWrite $ \act ->
handleErrno h
(handleGenericResponse h)
(act o d f)
return Loop
Disconnect f -> case handleDisconnect handler' of
Nothing -> return $ Return ()
Just g -> liftIO $ Control.Exception.catch
(liftIO (g f) >> return (Return ()))
(\(_ :: SomeException) -> return $ Return ())
Flush h f -> do
ifSupported h handler' handleFlush $ \act ->
handleErrno h
(handleGenericResponse h)
(act f)
return Loop
Trim h o l f -> do
ifSupported h handler' handleTrim $ \act ->
handleErrno h
(handleGenericResponse h)
(act o l f)
return Loop
UnknownCommand i h o l f -> do
ifSupported h handler' handleUnknownCommand $ \act ->
handleErrno h
(handleGenericResponse h)
(act i o l f)
return Loop
ifSupported h handler' f act =
case f handler' of
Nothing -> sendError h eOPNOTSUPP
Just g -> act g
handleErrno :: MonadIO m
=> Handle
-> (a -> Pipe l i BS.ByteString u m ())
-> IO a
-> Pipe l i BS.ByteString u m ()
handleErrno h act go = do
res <- liftIO $ try go
case res of
Left (exc :: IOError) ->
case ioe_errno exc of
Nothing -> liftIO getErrno >>= sendError h
Just e -> sendError h (Errno e)
Right val -> act val
handleGenericResponse :: Monad m
=> Handle
-> Response ()
-> Pipe l i BS.ByteString u m ()
handleGenericResponse h resp = case resp of
OK () -> sendReply h
Error e -> sendError h e
makeServer :: Monad m
=> Maybe [ExportName]
-> ExportMaker
-> (Socket, NS.SockAddr)
-> m (IO ())
makeServer exportNames exportMaker (sock, addr) = return $
application exportNames exportMaker NbdAppData { nbdAppSource = sourceSocket sock
, nbdAppSink = sinkSocket sock
, nbdAppSockAddr = addr
, nbdAppSocket = sock
}
-- | Run an NBD server
runServer :: ServerSettings -- ^ Listen address
-> Maybe [ExportName] -- ^ Optional list of export names to expose to the client. If 'Nothing', export listing is disabled.
-> ExportMaker -- ^ Action to retrieve an 'ExportHandler' for a given client connection
-> IO ()
runServer settings exportNames exportMaker =
NB.runServer settings $ makeServer exportNames exportMaker
-- | Utility action to validate request boundaries. This action will return
-- 'eINVAL' to the client if an out-of-bounds request was received
withBoundsCheck :: Monad m
=> ByteCount -- ^ Size of the export we're dealing with
-> FileOffset -- ^ Offset of the request
-> ByteCount -- ^ Length of the request
-> m (Response a) -- ^ Action to execute if request is within bounds
-> m (Response a)
withBoundsCheck size o l act =
if (o >= maxBound - fromIntegral l) || (fromIntegral o + l > size)
then return (Error eINVAL)
else act
| NicolasT/nbd | src/Network/NBD/Server/Simple.hs | lgpl-2.1 | 11,918 | 0 | 30 | 4,045 | 2,357 | 1,259 | 1,098 | 196 | 15 |
module Main where
import Options.Applicative
import Pagure.Command
main :: IO ()
main = execParser opts >>= runPagureCli
where
opts = info (helper <*> options)
( fullDesc
<> progDesc "pagure.io command-line interface"
<> header "pg - interact with pagure.io from the command-line" )
| fedora-infra/pagure-cli | src/Main.hs | bsd-2-clause | 307 | 0 | 11 | 66 | 72 | 38 | 34 | 9 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QLabel.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:26
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QLabel (
QqLabel(..)
,hasScaledContents
,movie
,picture
,setBuddy
,setMovie
,QsetNum(..)
,setPicture
,setScaledContents
,qLabel_delete
,qLabel_deleteLater
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QLabel ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QLabel_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QLabel_userMethod" qtc_QLabel_userMethod :: Ptr (TQLabel a) -> CInt -> IO ()
instance QuserMethod (QLabelSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QLabel_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QLabel ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QLabel_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QLabel_userMethodVariant" qtc_QLabel_userMethodVariant :: Ptr (TQLabel a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QLabelSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QLabel_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqLabel x1 where
qLabel :: x1 -> IO (QLabel ())
instance QqLabel (()) where
qLabel ()
= withQLabelResult $
qtc_QLabel
foreign import ccall "qtc_QLabel" qtc_QLabel :: IO (Ptr (TQLabel ()))
instance QqLabel ((QWidget t1)) where
qLabel (x1)
= withQLabelResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel1 cobj_x1
foreign import ccall "qtc_QLabel1" qtc_QLabel1 :: Ptr (TQWidget t1) -> IO (Ptr (TQLabel ()))
instance QqLabel ((String)) where
qLabel (x1)
= withQLabelResult $
withCWString x1 $ \cstr_x1 ->
qtc_QLabel2 cstr_x1
foreign import ccall "qtc_QLabel2" qtc_QLabel2 :: CWString -> IO (Ptr (TQLabel ()))
instance QqLabel ((QWidget t1, WindowFlags)) where
qLabel (x1, x2)
= withQLabelResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel3 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QLabel3" qtc_QLabel3 :: Ptr (TQWidget t1) -> CLong -> IO (Ptr (TQLabel ()))
instance QqLabel ((String, QWidget t2)) where
qLabel (x1, x2)
= withQLabelResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QLabel4 cstr_x1 cobj_x2
foreign import ccall "qtc_QLabel4" qtc_QLabel4 :: CWString -> Ptr (TQWidget t2) -> IO (Ptr (TQLabel ()))
instance QqLabel ((String, QWidget t2, WindowFlags)) where
qLabel (x1, x2, x3)
= withQLabelResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QLabel5 cstr_x1 cobj_x2 (toCLong $ qFlags_toInt x3)
foreign import ccall "qtc_QLabel5" qtc_QLabel5 :: CWString -> Ptr (TQWidget t2) -> CLong -> IO (Ptr (TQLabel ()))
instance Qalignment (QLabel a) (()) where
alignment x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_alignment cobj_x0
foreign import ccall "qtc_QLabel_alignment" qtc_QLabel_alignment :: Ptr (TQLabel a) -> IO CLong
instance Qbuddy (QLabel a) (()) (IO (QWidget ())) where
buddy x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_buddy cobj_x0
foreign import ccall "qtc_QLabel_buddy" qtc_QLabel_buddy :: Ptr (TQLabel a) -> IO (Ptr (TQWidget ()))
instance QchangeEvent (QLabel ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_changeEvent_h" qtc_QLabel_changeEvent_h :: Ptr (TQLabel a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QLabelSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_changeEvent_h cobj_x0 cobj_x1
instance Qclear (QLabel a) (()) where
clear x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_clear cobj_x0
foreign import ccall "qtc_QLabel_clear" qtc_QLabel_clear :: Ptr (TQLabel a) -> IO ()
instance QcontextMenuEvent (QLabel ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_contextMenuEvent_h" qtc_QLabel_contextMenuEvent_h :: Ptr (TQLabel a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QLabelSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_contextMenuEvent_h cobj_x0 cobj_x1
instance Qevent (QLabel ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_event_h" qtc_QLabel_event_h :: Ptr (TQLabel a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QLabelSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_event_h cobj_x0 cobj_x1
instance QfocusInEvent (QLabel ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_focusInEvent_h" qtc_QLabel_focusInEvent_h :: Ptr (TQLabel a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QLabelSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextPrevChild (QLabel ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLabel_focusNextPrevChild" qtc_QLabel_focusNextPrevChild :: Ptr (TQLabel a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QLabelSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QLabel ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_focusOutEvent_h" qtc_QLabel_focusOutEvent_h :: Ptr (TQLabel a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QLabelSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_focusOutEvent_h cobj_x0 cobj_x1
hasScaledContents :: QLabel a -> (()) -> IO (Bool)
hasScaledContents x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_hasScaledContents cobj_x0
foreign import ccall "qtc_QLabel_hasScaledContents" qtc_QLabel_hasScaledContents :: Ptr (TQLabel a) -> IO CBool
instance QheightForWidth (QLabel ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QLabel_heightForWidth_h" qtc_QLabel_heightForWidth_h :: Ptr (TQLabel a) -> CInt -> IO CInt
instance QheightForWidth (QLabelSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_heightForWidth_h cobj_x0 (toCInt x1)
instance Qindent (QLabel a) (()) where
indent x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_indent cobj_x0
foreign import ccall "qtc_QLabel_indent" qtc_QLabel_indent :: Ptr (TQLabel a) -> IO CInt
instance QkeyPressEvent (QLabel ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_keyPressEvent_h" qtc_QLabel_keyPressEvent_h :: Ptr (TQLabel a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QLabelSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_keyPressEvent_h cobj_x0 cobj_x1
instance Qmargin (QLabel a) (()) (IO (Int)) where
margin x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_margin cobj_x0
foreign import ccall "qtc_QLabel_margin" qtc_QLabel_margin :: Ptr (TQLabel a) -> IO CInt
instance QqminimumSizeHint (QLabel ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QLabel_minimumSizeHint_h" qtc_QLabel_minimumSizeHint_h :: Ptr (TQLabel a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QLabelSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QLabel ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QLabel_minimumSizeHint_qth_h" qtc_QLabel_minimumSizeHint_qth_h :: Ptr (TQLabel a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QLabelSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QmouseMoveEvent (QLabel ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_mouseMoveEvent_h" qtc_QLabel_mouseMoveEvent_h :: Ptr (TQLabel a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QLabelSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QLabel ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_mousePressEvent_h" qtc_QLabel_mousePressEvent_h :: Ptr (TQLabel a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QLabelSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QLabel ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_mouseReleaseEvent_h" qtc_QLabel_mouseReleaseEvent_h :: Ptr (TQLabel a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QLabelSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_mouseReleaseEvent_h cobj_x0 cobj_x1
movie :: QLabel a -> (()) -> IO (QMovie ())
movie x0 ()
= withQMovieResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_movie cobj_x0
foreign import ccall "qtc_QLabel_movie" qtc_QLabel_movie :: Ptr (TQLabel a) -> IO (Ptr (TQMovie ()))
instance QopenExternalLinks (QLabel a) (()) where
openExternalLinks x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_openExternalLinks cobj_x0
foreign import ccall "qtc_QLabel_openExternalLinks" qtc_QLabel_openExternalLinks :: Ptr (TQLabel a) -> IO CBool
instance QpaintEvent (QLabel ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_paintEvent_h" qtc_QLabel_paintEvent_h :: Ptr (TQLabel a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QLabelSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_paintEvent_h cobj_x0 cobj_x1
picture :: QLabel a -> (()) -> IO (QPicture ())
picture x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_picture cobj_x0
foreign import ccall "qtc_QLabel_picture" qtc_QLabel_picture :: Ptr (TQLabel a) -> IO (Ptr (TQPicture ()))
instance Qpixmap (QLabel a) (()) where
pixmap x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_pixmap cobj_x0
foreign import ccall "qtc_QLabel_pixmap" qtc_QLabel_pixmap :: Ptr (TQLabel a) -> IO (Ptr (TQPixmap ()))
instance Qpixmap_nf (QLabel a) (()) where
pixmap_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_pixmap cobj_x0
instance QsetAlignment (QLabel a) ((Alignment)) (IO ()) where
setAlignment x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setAlignment cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QLabel_setAlignment" qtc_QLabel_setAlignment :: Ptr (TQLabel a) -> CLong -> IO ()
setBuddy :: QLabel a -> ((QWidget t1)) -> IO ()
setBuddy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_setBuddy cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_setBuddy" qtc_QLabel_setBuddy :: Ptr (TQLabel a) -> Ptr (TQWidget t1) -> IO ()
instance QsetIndent (QLabel a) ((Int)) where
setIndent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setIndent cobj_x0 (toCInt x1)
foreign import ccall "qtc_QLabel_setIndent" qtc_QLabel_setIndent :: Ptr (TQLabel a) -> CInt -> IO ()
instance QsetMargin (QLabel a) ((Int)) where
setMargin x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setMargin cobj_x0 (toCInt x1)
foreign import ccall "qtc_QLabel_setMargin" qtc_QLabel_setMargin :: Ptr (TQLabel a) -> CInt -> IO ()
setMovie :: QLabel a -> ((QMovie t1)) -> IO ()
setMovie x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_setMovie cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_setMovie" qtc_QLabel_setMovie :: Ptr (TQLabel a) -> Ptr (TQMovie t1) -> IO ()
class QsetNum x1 where
setNum :: QLabel a -> x1 -> IO ()
instance QsetNum ((Double)) where
setNum x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setNum cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QLabel_setNum" qtc_QLabel_setNum :: Ptr (TQLabel a) -> CDouble -> IO ()
instance QsetNum ((Int)) where
setNum x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setNum1 cobj_x0 (toCInt x1)
foreign import ccall "qtc_QLabel_setNum1" qtc_QLabel_setNum1 :: Ptr (TQLabel a) -> CInt -> IO ()
instance QsetOpenExternalLinks (QLabel a) ((Bool)) where
setOpenExternalLinks x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setOpenExternalLinks cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLabel_setOpenExternalLinks" qtc_QLabel_setOpenExternalLinks :: Ptr (TQLabel a) -> CBool -> IO ()
setPicture :: QLabel a -> ((QPicture t1)) -> IO ()
setPicture x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_setPicture cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_setPicture" qtc_QLabel_setPicture :: Ptr (TQLabel a) -> Ptr (TQPicture t1) -> IO ()
instance QsetPixmap (QLabel a) ((QPixmap t1)) where
setPixmap x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_setPixmap cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_setPixmap" qtc_QLabel_setPixmap :: Ptr (TQLabel a) -> Ptr (TQPixmap t1) -> IO ()
setScaledContents :: QLabel a -> ((Bool)) -> IO ()
setScaledContents x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setScaledContents cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLabel_setScaledContents" qtc_QLabel_setScaledContents :: Ptr (TQLabel a) -> CBool -> IO ()
instance QsetText (QLabel a) ((String)) where
setText x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QLabel_setText cobj_x0 cstr_x1
foreign import ccall "qtc_QLabel_setText" qtc_QLabel_setText :: Ptr (TQLabel a) -> CWString -> IO ()
instance QsetTextFormat (QLabel a) ((TextFormat)) where
setTextFormat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setTextFormat cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QLabel_setTextFormat" qtc_QLabel_setTextFormat :: Ptr (TQLabel a) -> CLong -> IO ()
instance QsetTextInteractionFlags (QLabel a) ((TextInteractionFlags)) where
setTextInteractionFlags x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setTextInteractionFlags cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QLabel_setTextInteractionFlags" qtc_QLabel_setTextInteractionFlags :: Ptr (TQLabel a) -> CLong -> IO ()
instance QsetWordWrap (QLabel a) ((Bool)) where
setWordWrap x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setWordWrap cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLabel_setWordWrap" qtc_QLabel_setWordWrap :: Ptr (TQLabel a) -> CBool -> IO ()
instance QqsizeHint (QLabel ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_sizeHint_h cobj_x0
foreign import ccall "qtc_QLabel_sizeHint_h" qtc_QLabel_sizeHint_h :: Ptr (TQLabel a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QLabelSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_sizeHint_h cobj_x0
instance QsizeHint (QLabel ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QLabel_sizeHint_qth_h" qtc_QLabel_sizeHint_qth_h :: Ptr (TQLabel a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QLabelSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance Qtext (QLabel a) (()) (IO (String)) where
text x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_text cobj_x0
foreign import ccall "qtc_QLabel_text" qtc_QLabel_text :: Ptr (TQLabel a) -> IO (Ptr (TQString ()))
instance QtextFormat (QLabel a) (()) where
textFormat x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_textFormat cobj_x0
foreign import ccall "qtc_QLabel_textFormat" qtc_QLabel_textFormat :: Ptr (TQLabel a) -> IO CLong
instance QtextInteractionFlags (QLabel a) (()) where
textInteractionFlags x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_textInteractionFlags cobj_x0
foreign import ccall "qtc_QLabel_textInteractionFlags" qtc_QLabel_textInteractionFlags :: Ptr (TQLabel a) -> IO CLong
instance QwordWrap (QLabel a) (()) where
wordWrap x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_wordWrap cobj_x0
foreign import ccall "qtc_QLabel_wordWrap" qtc_QLabel_wordWrap :: Ptr (TQLabel a) -> IO CBool
qLabel_delete :: QLabel a -> IO ()
qLabel_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_delete cobj_x0
foreign import ccall "qtc_QLabel_delete" qtc_QLabel_delete :: Ptr (TQLabel a) -> IO ()
qLabel_deleteLater :: QLabel a -> IO ()
qLabel_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_deleteLater cobj_x0
foreign import ccall "qtc_QLabel_deleteLater" qtc_QLabel_deleteLater :: Ptr (TQLabel a) -> IO ()
instance QdrawFrame (QLabel ()) ((QPainter t1)) where
drawFrame x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_drawFrame cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_drawFrame" qtc_QLabel_drawFrame :: Ptr (TQLabel a) -> Ptr (TQPainter t1) -> IO ()
instance QdrawFrame (QLabelSc a) ((QPainter t1)) where
drawFrame x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_drawFrame cobj_x0 cobj_x1
instance QactionEvent (QLabel ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_actionEvent_h" qtc_QLabel_actionEvent_h :: Ptr (TQLabel a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QLabelSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QLabel ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_addAction" qtc_QLabel_addAction :: Ptr (TQLabel a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QLabelSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_addAction cobj_x0 cobj_x1
instance QcloseEvent (QLabel ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_closeEvent_h" qtc_QLabel_closeEvent_h :: Ptr (TQLabel a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QLabelSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_closeEvent_h cobj_x0 cobj_x1
instance Qcreate (QLabel ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_create cobj_x0
foreign import ccall "qtc_QLabel_create" qtc_QLabel_create :: Ptr (TQLabel a) -> IO ()
instance Qcreate (QLabelSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_create cobj_x0
instance Qcreate (QLabel ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_create1" qtc_QLabel_create1 :: Ptr (TQLabel a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QLabelSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_create1 cobj_x0 cobj_x1
instance Qcreate (QLabel ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QLabel_create2" qtc_QLabel_create2 :: Ptr (TQLabel a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QLabelSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QLabel ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QLabel_create3" qtc_QLabel_create3 :: Ptr (TQLabel a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QLabelSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QLabel ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_destroy cobj_x0
foreign import ccall "qtc_QLabel_destroy" qtc_QLabel_destroy :: Ptr (TQLabel a) -> IO ()
instance Qdestroy (QLabelSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_destroy cobj_x0
instance Qdestroy (QLabel ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLabel_destroy1" qtc_QLabel_destroy1 :: Ptr (TQLabel a) -> CBool -> IO ()
instance Qdestroy (QLabelSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QLabel ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QLabel_destroy2" qtc_QLabel_destroy2 :: Ptr (TQLabel a) -> CBool -> CBool -> IO ()
instance Qdestroy (QLabelSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QLabel ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_devType_h cobj_x0
foreign import ccall "qtc_QLabel_devType_h" qtc_QLabel_devType_h :: Ptr (TQLabel a) -> IO CInt
instance QdevType (QLabelSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_devType_h cobj_x0
instance QdragEnterEvent (QLabel ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_dragEnterEvent_h" qtc_QLabel_dragEnterEvent_h :: Ptr (TQLabel a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QLabelSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QLabel ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_dragLeaveEvent_h" qtc_QLabel_dragLeaveEvent_h :: Ptr (TQLabel a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QLabelSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QLabel ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_dragMoveEvent_h" qtc_QLabel_dragMoveEvent_h :: Ptr (TQLabel a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QLabelSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QLabel ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_dropEvent_h" qtc_QLabel_dropEvent_h :: Ptr (TQLabel a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QLabelSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QLabel ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLabel_enabledChange" qtc_QLabel_enabledChange :: Ptr (TQLabel a) -> CBool -> IO ()
instance QenabledChange (QLabelSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QLabel ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_enterEvent_h" qtc_QLabel_enterEvent_h :: Ptr (TQLabel a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QLabelSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_enterEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QLabel ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_focusNextChild cobj_x0
foreign import ccall "qtc_QLabel_focusNextChild" qtc_QLabel_focusNextChild :: Ptr (TQLabel a) -> IO CBool
instance QfocusNextChild (QLabelSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_focusNextChild cobj_x0
instance QfocusPreviousChild (QLabel ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_focusPreviousChild cobj_x0
foreign import ccall "qtc_QLabel_focusPreviousChild" qtc_QLabel_focusPreviousChild :: Ptr (TQLabel a) -> IO CBool
instance QfocusPreviousChild (QLabelSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_focusPreviousChild cobj_x0
instance QfontChange (QLabel ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_fontChange" qtc_QLabel_fontChange :: Ptr (TQLabel a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QLabelSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_fontChange cobj_x0 cobj_x1
instance QhideEvent (QLabel ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_hideEvent_h" qtc_QLabel_hideEvent_h :: Ptr (TQLabel a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QLabelSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_hideEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QLabel ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_inputMethodEvent" qtc_QLabel_inputMethodEvent :: Ptr (TQLabel a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QLabelSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QLabel ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QLabel_inputMethodQuery_h" qtc_QLabel_inputMethodQuery_h :: Ptr (TQLabel a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QLabelSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyReleaseEvent (QLabel ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_keyReleaseEvent_h" qtc_QLabel_keyReleaseEvent_h :: Ptr (TQLabel a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QLabelSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QLabel ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_languageChange cobj_x0
foreign import ccall "qtc_QLabel_languageChange" qtc_QLabel_languageChange :: Ptr (TQLabel a) -> IO ()
instance QlanguageChange (QLabelSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_languageChange cobj_x0
instance QleaveEvent (QLabel ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_leaveEvent_h" qtc_QLabel_leaveEvent_h :: Ptr (TQLabel a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QLabelSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QLabel ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QLabel_metric" qtc_QLabel_metric :: Ptr (TQLabel a) -> CLong -> IO CInt
instance Qmetric (QLabelSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance QmouseDoubleClickEvent (QLabel ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_mouseDoubleClickEvent_h" qtc_QLabel_mouseDoubleClickEvent_h :: Ptr (TQLabel a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QLabelSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance Qmove (QLabel ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QLabel_move1" qtc_QLabel_move1 :: Ptr (TQLabel a) -> CInt -> CInt -> IO ()
instance Qmove (QLabelSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QLabel ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QLabel_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QLabel_move_qth" qtc_QLabel_move_qth :: Ptr (TQLabel a) -> CInt -> CInt -> IO ()
instance Qmove (QLabelSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QLabel_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QLabel ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_move cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_move" qtc_QLabel_move :: Ptr (TQLabel a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QLabelSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_move cobj_x0 cobj_x1
instance QmoveEvent (QLabel ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_moveEvent_h" qtc_QLabel_moveEvent_h :: Ptr (TQLabel a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QLabelSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QLabel ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_paintEngine_h cobj_x0
foreign import ccall "qtc_QLabel_paintEngine_h" qtc_QLabel_paintEngine_h :: Ptr (TQLabel a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QLabelSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_paintEngine_h cobj_x0
instance QpaletteChange (QLabel ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_paletteChange" qtc_QLabel_paletteChange :: Ptr (TQLabel a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QLabelSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QLabel ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_repaint cobj_x0
foreign import ccall "qtc_QLabel_repaint" qtc_QLabel_repaint :: Ptr (TQLabel a) -> IO ()
instance Qrepaint (QLabelSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_repaint cobj_x0
instance Qrepaint (QLabel ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QLabel_repaint2" qtc_QLabel_repaint2 :: Ptr (TQLabel a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QLabelSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QLabel ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_repaint1" qtc_QLabel_repaint1 :: Ptr (TQLabel a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QLabelSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QLabel ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_resetInputContext cobj_x0
foreign import ccall "qtc_QLabel_resetInputContext" qtc_QLabel_resetInputContext :: Ptr (TQLabel a) -> IO ()
instance QresetInputContext (QLabelSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_resetInputContext cobj_x0
instance Qresize (QLabel ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QLabel_resize1" qtc_QLabel_resize1 :: Ptr (TQLabel a) -> CInt -> CInt -> IO ()
instance Qresize (QLabelSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QLabel ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_resize" qtc_QLabel_resize :: Ptr (TQLabel a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QLabelSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_resize cobj_x0 cobj_x1
instance Qresize (QLabel ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QLabel_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QLabel_resize_qth" qtc_QLabel_resize_qth :: Ptr (TQLabel a) -> CInt -> CInt -> IO ()
instance Qresize (QLabelSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QLabel_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QresizeEvent (QLabel ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_resizeEvent_h" qtc_QLabel_resizeEvent_h :: Ptr (TQLabel a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QLabelSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_resizeEvent_h cobj_x0 cobj_x1
instance QsetGeometry (QLabel ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QLabel_setGeometry1" qtc_QLabel_setGeometry1 :: Ptr (TQLabel a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QLabelSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QLabel ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_setGeometry" qtc_QLabel_setGeometry :: Ptr (TQLabel a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QLabelSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QLabel ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QLabel_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QLabel_setGeometry_qth" qtc_QLabel_setGeometry_qth :: Ptr (TQLabel a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QLabelSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QLabel_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QLabel ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLabel_setMouseTracking" qtc_QLabel_setMouseTracking :: Ptr (TQLabel a) -> CBool -> IO ()
instance QsetMouseTracking (QLabelSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setMouseTracking cobj_x0 (toCBool x1)
instance QsetVisible (QLabel ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLabel_setVisible_h" qtc_QLabel_setVisible_h :: Ptr (TQLabel a) -> CBool -> IO ()
instance QsetVisible (QLabelSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QLabel ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_showEvent_h" qtc_QLabel_showEvent_h :: Ptr (TQLabel a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QLabelSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_showEvent_h cobj_x0 cobj_x1
instance QtabletEvent (QLabel ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_tabletEvent_h" qtc_QLabel_tabletEvent_h :: Ptr (TQLabel a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QLabelSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QLabel ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_updateMicroFocus cobj_x0
foreign import ccall "qtc_QLabel_updateMicroFocus" qtc_QLabel_updateMicroFocus :: Ptr (TQLabel a) -> IO ()
instance QupdateMicroFocus (QLabelSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_updateMicroFocus cobj_x0
instance QwheelEvent (QLabel ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_wheelEvent_h" qtc_QLabel_wheelEvent_h :: Ptr (TQLabel a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QLabelSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_wheelEvent_h cobj_x0 cobj_x1
instance QwindowActivationChange (QLabel ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLabel_windowActivationChange" qtc_QLabel_windowActivationChange :: Ptr (TQLabel a) -> CBool -> IO ()
instance QwindowActivationChange (QLabelSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QLabel ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_childEvent" qtc_QLabel_childEvent :: Ptr (TQLabel a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QLabelSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QLabel ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QLabel_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QLabel_connectNotify" qtc_QLabel_connectNotify :: Ptr (TQLabel a) -> CWString -> IO ()
instance QconnectNotify (QLabelSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QLabel_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QLabel ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_customEvent" qtc_QLabel_customEvent :: Ptr (TQLabel a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QLabelSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QLabel ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QLabel_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QLabel_disconnectNotify" qtc_QLabel_disconnectNotify :: Ptr (TQLabel a) -> CWString -> IO ()
instance QdisconnectNotify (QLabelSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QLabel_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QLabel ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QLabel_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QLabel_eventFilter_h" qtc_QLabel_eventFilter_h :: Ptr (TQLabel a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QLabelSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QLabel_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QLabel ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QLabel_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QLabel_receivers" qtc_QLabel_receivers :: Ptr (TQLabel a) -> CWString -> IO CInt
instance Qreceivers (QLabelSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QLabel_receivers cobj_x0 cstr_x1
instance Qsender (QLabel ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_sender cobj_x0
foreign import ccall "qtc_QLabel_sender" qtc_QLabel_sender :: Ptr (TQLabel a) -> IO (Ptr (TQObject ()))
instance Qsender (QLabelSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLabel_sender cobj_x0
instance QtimerEvent (QLabel ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLabel_timerEvent" qtc_QLabel_timerEvent :: Ptr (TQLabel a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QLabelSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLabel_timerEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Gui/QLabel.hs | bsd-2-clause | 50,247 | 0 | 14 | 8,711 | 17,570 | 8,907 | 8,663 | -1 | -1 |
{-# LANGUAGE Haskell2010 #-}
{-# OPTIONS_HADDOCK hide #-}
module Ticket61_Hidden where
class C a where
-- | A comment about f
f :: a
| haskell/haddock | html-test/src/Ticket61_Hidden.hs | bsd-2-clause | 139 | 0 | 6 | 30 | 21 | 13 | 8 | 5 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTextTableFormat.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:16
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTextTableFormat (
QqTextTableFormat(..)
,QqTextTableFormat_nf(..)
,cellPadding
,cellSpacing
,clearColumnWidthConstraints
,headerRowCount
,setCellPadding
,setCellSpacing
,setColumns
,setHeaderRowCount
,qTextTableFormat_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqTextTableFormat x1 where
qTextTableFormat :: x1 -> IO (QTextTableFormat ())
instance QqTextTableFormat (()) where
qTextTableFormat ()
= withQTextTableFormatResult $
qtc_QTextTableFormat
foreign import ccall "qtc_QTextTableFormat" qtc_QTextTableFormat :: IO (Ptr (TQTextTableFormat ()))
instance QqTextTableFormat ((QTextTableFormat t1)) where
qTextTableFormat (x1)
= withQTextTableFormatResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextTableFormat1 cobj_x1
foreign import ccall "qtc_QTextTableFormat1" qtc_QTextTableFormat1 :: Ptr (TQTextTableFormat t1) -> IO (Ptr (TQTextTableFormat ()))
class QqTextTableFormat_nf x1 where
qTextTableFormat_nf :: x1 -> IO (QTextTableFormat ())
instance QqTextTableFormat_nf (()) where
qTextTableFormat_nf ()
= withObjectRefResult $
qtc_QTextTableFormat
instance QqTextTableFormat_nf ((QTextTableFormat t1)) where
qTextTableFormat_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextTableFormat1 cobj_x1
instance Qalignment (QTextTableFormat a) (()) where
alignment x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_alignment cobj_x0
foreign import ccall "qtc_QTextTableFormat_alignment" qtc_QTextTableFormat_alignment :: Ptr (TQTextTableFormat a) -> IO CLong
cellPadding :: QTextTableFormat a -> (()) -> IO (Double)
cellPadding x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_cellPadding cobj_x0
foreign import ccall "qtc_QTextTableFormat_cellPadding" qtc_QTextTableFormat_cellPadding :: Ptr (TQTextTableFormat a) -> IO CDouble
cellSpacing :: QTextTableFormat a -> (()) -> IO (Double)
cellSpacing x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_cellSpacing cobj_x0
foreign import ccall "qtc_QTextTableFormat_cellSpacing" qtc_QTextTableFormat_cellSpacing :: Ptr (TQTextTableFormat a) -> IO CDouble
clearColumnWidthConstraints :: QTextTableFormat a -> (()) -> IO ()
clearColumnWidthConstraints x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_clearColumnWidthConstraints cobj_x0
foreign import ccall "qtc_QTextTableFormat_clearColumnWidthConstraints" qtc_QTextTableFormat_clearColumnWidthConstraints :: Ptr (TQTextTableFormat a) -> IO ()
instance Qcolumns (QTextTableFormat a) (()) where
columns x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_columns cobj_x0
foreign import ccall "qtc_QTextTableFormat_columns" qtc_QTextTableFormat_columns :: Ptr (TQTextTableFormat a) -> IO CInt
headerRowCount :: QTextTableFormat a -> (()) -> IO (Int)
headerRowCount x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_headerRowCount cobj_x0
foreign import ccall "qtc_QTextTableFormat_headerRowCount" qtc_QTextTableFormat_headerRowCount :: Ptr (TQTextTableFormat a) -> IO CInt
instance QqisValid (QTextTableFormat ()) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_isValid cobj_x0
foreign import ccall "qtc_QTextTableFormat_isValid" qtc_QTextTableFormat_isValid :: Ptr (TQTextTableFormat a) -> IO CBool
instance QqisValid (QTextTableFormatSc a) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_isValid cobj_x0
instance QsetAlignment (QTextTableFormat a) ((Alignment)) (IO ()) where
setAlignment x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setAlignment cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QTextTableFormat_setAlignment" qtc_QTextTableFormat_setAlignment :: Ptr (TQTextTableFormat a) -> CLong -> IO ()
setCellPadding :: QTextTableFormat a -> ((Double)) -> IO ()
setCellPadding x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setCellPadding cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QTextTableFormat_setCellPadding" qtc_QTextTableFormat_setCellPadding :: Ptr (TQTextTableFormat a) -> CDouble -> IO ()
setCellSpacing :: QTextTableFormat a -> ((Double)) -> IO ()
setCellSpacing x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setCellSpacing cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QTextTableFormat_setCellSpacing" qtc_QTextTableFormat_setCellSpacing :: Ptr (TQTextTableFormat a) -> CDouble -> IO ()
setColumns :: QTextTableFormat a -> ((Int)) -> IO ()
setColumns x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setColumns cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextTableFormat_setColumns" qtc_QTextTableFormat_setColumns :: Ptr (TQTextTableFormat a) -> CInt -> IO ()
setHeaderRowCount :: QTextTableFormat a -> ((Int)) -> IO ()
setHeaderRowCount x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setHeaderRowCount cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextTableFormat_setHeaderRowCount" qtc_QTextTableFormat_setHeaderRowCount :: Ptr (TQTextTableFormat a) -> CInt -> IO ()
qTextTableFormat_delete :: QTextTableFormat a -> IO ()
qTextTableFormat_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_delete cobj_x0
foreign import ccall "qtc_QTextTableFormat_delete" qtc_QTextTableFormat_delete :: Ptr (TQTextTableFormat a) -> IO ()
| keera-studios/hsQt | Qtc/Gui/QTextTableFormat.hs | bsd-2-clause | 6,225 | 0 | 12 | 889 | 1,597 | 824 | 773 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Parsing carma logs
module System.Log.Carma (
LogMessage(..),
LogEntry(..),
parseLog,
parseMessage,
groupRequestsOn, groupRequests, groupLinedRequests
) where
import Control.Arrow
import Control.Applicative
import Data.Aeson
import Data.Aeson.Types (Parser, parseMaybe)
import Data.List
import Data.Maybe
import Data.Text.Lazy (pack)
import Data.Text.Lazy.Encoding (encodeUtf8)
import Data.String (fromString)
import Text.Regex.Posix ((=~))
-- | Log message
data LogMessage = LogMessage {
logThreadId :: String,
logEntry :: LogEntry }
deriving (Eq, Show)
-- | Log entry
data LogEntry =
LogRequest (Maybe String) String String Value |
-- ^ User, URL, method and data
LogResponse Value |
-- ^ Response value
LogTrigger String Value
-- ^ Trigger entry
deriving (Eq, Show)
instance FromJSON LogMessage where
parseJSON (Object v) = LogMessage <$>
(v .: "threadId") <*>
(parseJSON (Object v))
parseJSON _ = empty
instance FromJSON LogEntry where
parseJSON (Object v) = req <|> resp <|> trig where
req = do
(Object inner) <- v .: "request"
LogRequest <$>
(inner .: "user") <*>
(inner .: "uri") <*>
(inner .: "method") <*>
(inner .: "body")
resp = LogResponse <$> (v .: "response")
trig = LogTrigger <$> (v .: "trigger") <*> (v .: "data")
parseJSON _ = empty
-- | Read messages from log
parseLog :: String -> [(Int, LogMessage)]
parseLog = map (second fromJust) . filter (isJust . snd) . zip [1..] . map parseMessage . lines
-- | Read one message
parseMessage :: String -> Maybe LogMessage
parseMessage line = do
(name, val) <- parseValue line
if any ($name) [(== "detail/req"), (== "detail/resp"), isPrefixOf "update/detail/trigger/"]
then parseMaybe parseJSON val
else Nothing
-- | Group requests
-- Every request is followed with several trigger messages and ends with response
-- Function returns list of such groups
groupRequestsOn :: (a -> LogMessage) -> [a] -> [[a]]
groupRequestsOn f = go . dropWhile (not . isRequest . logEntry . f) where
go (x : xs) = if null respAndRest then [] else thisGroup : go tailMsgs where
(msg@(LogMessage thId req)) = f x
(beforeresp, (respAndRest@(~(resp : afterresp)))) = break (myResponse . f) xs
(myBefore, otherBefore) = partition ((== thId) . logThreadId . f) beforeresp
thisGroup = x : (myBefore ++ [resp])
tailMsgs = otherBefore ++ afterresp
myResponse (LogMessage thId' (LogResponse _)) = thId == thId'
myResponse _ = False
go [] = []
isRequest :: LogEntry -> Bool
isRequest (LogRequest {}) = True
isRequest _ = False
groupRequests :: [LogMessage] -> [[LogMessage]]
groupRequests = groupRequestsOn id
groupLinedRequests :: [(Int, LogMessage)] -> [[(Int, LogMessage)]]
groupLinedRequests = groupRequestsOn snd
parseValue :: String -> Maybe (String, Value)
parseValue line = extract $ line =~ logRegex where
extract:: [[String]] -> Maybe (String, Value)
extract [[_, name, msg]] = do
val <- decode . encodeUtf8 . pack $ msg
return (name, val)
extract _ = Nothing
logRegex :: String
logRegex = "^[0-9]+/[0-9]+/[0-9]+ [0-9]+:[0-9]+:[0-9]+ \\+[0-9]+[ \t]+TRACE[ \t]+([a-z/]+)> (.*)$"
| f-me/carma-test | src/System/Log/Carma.hs | bsd-3-clause | 3,416 | 0 | 15 | 820 | 1,061 | 591 | 470 | 78 | 5 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.EN.NZ.Corpus
( allExamples
) where
import Data.String
import Prelude
import Duckling.Testing.Types hiding (examples)
import Duckling.Time.Corpus
import Duckling.Time.Types hiding (Month)
import Duckling.TimeGrain.Types hiding (add)
allExamples :: [Example]
allExamples = concat
[ examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "15/2"
, "on 15/2"
, "15 / 2"
, "15-2"
, "15 - 2"
]
, examples (datetime (1974, 10, 31, 0, 0, 0) Day)
[ "31/10/1974"
, "31/10/74"
, "31-10-74"
, "31.10.1974"
, "31 10 1974"
]
, examples (datetime (2013, 4, 25, 16, 0, 0) Minute)
[ "25/4 at 4:00pm"
]
, examples (datetime (2013, 10, 10, 0, 0, 0) Day)
[ "10/10"
, "10/10/2013"
]
, examples (datetimeHoliday (2013, 11, 28, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving day"
, "thanksgiving"
, "thanksgiving 2013"
, "this thanksgiving"
, "next thanksgiving day"
]
, examples (datetimeHoliday (2014, 11, 27, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving of next year"
, "thanksgiving 2014"
]
, examples (datetimeHoliday (2012, 11, 22, 0, 0, 0) Day "Thanksgiving Day")
[ "last thanksgiving"
, "thanksgiving day 2012"
]
, examples (datetimeHoliday (2016, 11, 24, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving 2016"
]
, examples (datetimeHoliday (2017, 11, 23, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving 2017"
]
, examples (datetimeHoliday (2013, 4, 25, 0, 0, 0) Day "ANZAC Day")
[ "ANZAC day"
]
, examples (datetimeHoliday (2013, 9, 1, 0, 0, 0) Day "Father's Day")
[ "Father's Day"
]
, examples (datetimeHoliday (2012, 9, 2, 0, 0, 0) Day "Father's Day")
[ "last fathers day"
]
, examples (datetimeHoliday (1996, 9, 1, 0, 0, 0) Day "Father's Day")
[ "fathers day 1996"
]
, examples (datetimeHoliday (2013, 5, 12, 0, 0, 0) Day "Mother's Day")
[ "Mother's Day"
, "next mothers day"
]
, examples (datetimeHoliday (2012, 5, 13, 0, 0, 0) Day "Mother's Day")
[ "last mothers day"
]
, examples (datetimeHoliday (2014, 5, 11, 0, 0, 0) Day "Mother's Day")
[ "mothers day 2014"
]
, examples (datetimeHoliday (2013, 10, 28, 0, 0, 0) Day "Labour Day")
[ "labour day"
]
, examples (datetimeHoliday (2012, 10, 22, 0, 0, 0) Day "Labour Day")
[ "labour day of last year"
, "Labour Day 2012"
]
, examples (datetimeHoliday (2013, 4, 17, 0, 0, 0) Day "Administrative Professionals' Day")
[ "admin day"
]
]
| facebookincubator/duckling | Duckling/Time/EN/NZ/Corpus.hs | bsd-3-clause | 3,298 | 0 | 10 | 1,191 | 870 | 525 | 345 | 66 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
import Servant
import Transaction
import Network.Wai.Handler.Warp
import Network.Wai
import Control.Monad.Trans (liftIO)
type API = "account" :> Get '[JSON] [Transaction]
databasePath :: FilePath
databasePath = "test.db"
main :: IO ()
main = run 8081 app
getTransactions' :: IO [Transaction]
getTransactions' = do
ts <- getTransactions databasePath
-- putStrLn $ show (length ts)
return ts
server :: Server API
server = liftIO $ getTransactions databasePath
api :: Proxy API
api = Proxy
app :: Application
app = serve api server
| bartfrenk/haskell-transaction | app/Server.hs | bsd-3-clause | 822 | 0 | 8 | 124 | 172 | 97 | 75 | 28 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | Haskell to JavaScript compiler.
module Fore where
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Trans
import CoreSyn
import Data.Aeson (Value)
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as L
import Data.Char
import Data.Data hiding (tyConName)
import Data.Generics.Aliases
import Data.List
import Data.Maybe
import Data.Monoid
import Data.String
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import Data.Text.Lazy.Builder
import qualified Data.Text.Lazy.Encoding as T
import qualified Data.Text.Lazy.IO as T
import Data.Time
import DataCon
import Debug.Trace
import DynFlags
import Encoding
import FastString
import GHC
import GHC.Paths (libdir)
import GHC.Real
import HscTypes
import qualified Language.ECMAScript3.Parser as ECMA
import qualified Language.ECMAScript3.PrettyPrint as ECMA
import qualified Language.ECMAScript3.Syntax as ECMA
import Literal
import Module
import Name hiding (varName)
import OccName hiding (varName)
import Outputable hiding ((<>))
import Prelude hiding (exp)
import qualified SourceMap as SourceMap
import SourceMap.Types
import System.Exit
import System.IO
import System.Process.Text.Lazy
import qualified Text.PrettyPrint as Doc
import TyCon
import TypeRep
import Var
--------------------------------------------------------------------------------
-- Top-level compilers
getCore :: FilePath -> IO CoreModule
getCore = getCoreAst
getJs :: CoreModule -> IO [Statement]
getJs = flip runReaderT Nothing . runCompile . compileModule
getTextMappings :: Text -> [Statement] -> IO (Text,[Mapping])
getTextMappings name stmts = do
forejs <- getForeJs name
let (text,mappings) = renderStatements (length (T.lines forejs) + 1) stmts
return (forejs <> text <> run,mappings)
getCode :: [Statement] -> IO Text
getCode stmts = do
beautify $ fst $ renderStatements 0 stmts
getMappingsJson :: String -> [Mapping] -> Value
getMappingsJson name mappings =
SourceMap.generate SourceMapping
{ smFile = name ++ ".js"
, smSourceRoot = Nothing
, smMappings = mappings
}
writeFileMapping :: FilePath -> IO ()
writeFileMapping fp = do
stmts <- getCore fp >>= getJs
(text,mappings) <- getTextMappings (T.pack name) stmts
T.writeFile (name ++ ".js") text
L.writeFile (name ++ mapExt) (Aeson.encode (getMappingsJson name mappings))
where name = reverse . dropWhile (=='.') . dropWhile (/='.') . reverse $ fp
interp :: Text -> IO ()
interp input = do
result <- readAllFromProcess "node" [] input
case result of
Left err -> error (T.unpack err)
Right (stderr,stdout) -> do T.putStrLn stderr
T.putStrLn stdout
run :: Text
run = "var start = new Date();" <>
"__(main$ZCMain$main);" <>
"var end = new Date();" <>
"console.log((end-start)+'ms')"
getForeJs :: Text -> IO Text
getForeJs name = do
let sourceMapRef = "//@ sourceMappingURL=" <> name <> T.pack mapExt <> "\n"
rts <- T.readFile "../js/rts.js"
base <- T.readFile "../js/base.js"
classes <- T.readFile "../js/classes.js"
instances <- T.readFile "../js/instances.js"
io <- T.readFile "../js/io.js"
primitives <- T.readFile "../js/primitives.js"
let header = T.pack (replicate 80 '/') <> "\n// Application/library code\n"
beautify (T.concat [sourceMapRef
,rts
,base
,classes
,instances
,io
,primitives
,header])
mapExt = ".json"
--------------------------------------------------------------------------------
-- Compilers
-- | The compilation monad.
newtype Compile a = Compile { runCompile :: ReaderT (Maybe Original) IO a }
deriving (Monad,Functor,MonadIO,Applicative,MonadReader (Maybe Original))
compileModule :: CoreModule -> Compile [Statement]
compileModule (CoreModule{cm_binds=binds}) =
fmap concat (mapM compileBind binds)
compileBind :: Bind Var -> Compile [Statement]
compileBind bind =
case bind of
NonRec var exp -> fmap return (compileGeneralBind var exp)
Rec defs -> mapM (uncurry compileGeneralBind) defs
compileGeneralBind :: Var -> Expr Var -> Compile Statement
compileGeneralBind var exp = do
v <- compileVar var
e <- local (const orig)
(compileExp exp)
return (Declaration v orig (thunk e))
where orig = original (varName var)
compileExp :: Expr Var -> Compile Expression
compileExp exp = (>>= optimizeApp) $
case exp of
Var var -> fmap Variable (compileVar var)
Lit lit -> compileLit lit
App op arg -> compileApp op arg
Lam var exp -> compileLam var exp
Let bind exp -> compileLet bind exp
Cast exp _ -> compileExp exp
Case exp var typ alts -> compileCase exp var typ alts
compileVar :: Var -> Compile Identifier
compileVar var = compileName (varName var)
compileName :: Name -> Compile Identifier
compileName name = do
case nameModule_maybe name of
Just mname -> compileQVar mname name
Nothing -> return (translateName name)
compileQVar :: Module -> Name -> Compile Identifier
compileQVar mod name = do
when (elem (modulePackageId mod) wiredInPackages &&
not (elem (printName name) (map printNameParts supported))) $
error $ "Unsupported built-in identifier: " ++
T.unpack (printName name) ++
" (" ++ T.unpack (encodeName name) ++ ")"
return (translateName name)
compileLit :: Literal -> Compile Expression
compileLit lit = return $
case lit of
MachInt i -> Integer (fromIntegral i)
MachDouble (n :% d) -> Double (fromIntegral n/fromIntegral d)
MachFloat (n :% d) -> Double (fromIntegral n/fromIntegral d)
MachChar c -> String [c]
MachStr s -> String (unpackFS s)
compileApp :: Expr Var -> Expr Var -> Compile Expression
compileApp op arg = do
case arg of
Type{} -> compileExp op
_ -> do
case op of
Var v | any ((== printName (varName v)) . printNameParts) noops -> compileExp arg
(App (Var v') Type{})
| printName (varName v') == "base:Control.Exception.Base.patError"
, Lit (MachStr fs) <- arg -> compilePatError (fastStringToText fs)
| printName (varName v') == "base:GHC.Err.error" -> compileUserError arg
_ -> do
o <- compileExp op
a <- compileExp arg
case o of
Apply (Variable ident) [_]
| elem ident (map (Identifier . encodeNameParts) methods) -> return (Apply o [a])
_ -> return (Apply (force o) [a])
compilePatError err =
return $ throwExp loc (String (T.unpack ("Non-exhaustive patterns in " <> typ)))
where
loc = Loc (file,line)
file = T.takeWhile (/=':') err
line = read . T.unpack . T.takeWhile isDigit . T.drop 1 . T.dropWhile (/=':') $ err
typ = T.drop 1 . T.dropWhile (/='|') $ err
compileUserError err = do
e <- compileExp err
decl <- ask
let line = maybe 0 (srcLocLine . snd . unOriginal) decl
return $ throwExp (Loc ("X.hs",line))
(force (Apply (Variable (Identifier "ghczmprim$GHC$CString$packCStringzh"))
[e]))
-- | Optimize nested IO actions like a>>b>>c to __(a),__(b),c
optimizeApp e =
case e of
(Apply (Apply (Variable (Identifier "_"))
[(Apply (Apply (Variable (Identifier "base$GHC$Base$zgzg"))
[Variable (Identifier "base$GHC$Base$zdfMonadIO")])
[a])])
[b]) -> return $ Sequence [act a,b]
e -> return e
compileLam :: Var -> Expr Var -> Compile Expression
compileLam var exp = do
v <- compileVar var
e <- compileExp exp
return (lambda [v] (thunk e))
compileLet :: Bind Var -> Expr Var -> Compile Expression
compileLet bind body = do
case bind of
NonRec var exp -> compileNonRecLet var exp body
Rec binds -> compileRecLet binds body
compileNonRecLet :: Var -> Expr Var -> Expr Var -> Compile Expression
compileNonRecLet var exp body = do
v <- compileVar var
e <- compileExp exp
b <- compileExp body
return (Apply (Function [v] b)
[e])
compileRecLet :: [(Var,Expr Var)] -> Expr Var -> Compile Expression
compileRecLet binds body = do
b <- compileExp body
decls <- mapM compileVarDecl binds
let closure = Procedure [] (decls ++ [Return b])
return (Apply closure [])
compileVarDecl :: (Var,Expr Var) -> Compile Statement
compileVarDecl (var,exp) = do
v <- compileVar var
e <- compileExp exp
return (Declaration v Nothing (thunk e))
compileCase :: Expr Var -> Var -> t -> [(AltCon,[Var],Expr Var)] -> Compile Expression
compileCase exp var typ alts = do
e <- compileExp exp
v <- compileVar var
fmap (bind [v] e)
(foldM (matchCon (Variable v)) (error "unhandled case")
-- I have no idea why the DEFAULT case comes first from Core.
(reverse (filter (not.isDefault) alts ++ filter isDefault alts)))
where isDefault (con,_,_) = con == DEFAULT
matchCon :: Expression -> Expression -> (AltCon,[Var],Expr Var) -> Compile Expression
matchCon object inner (con,vars,exp) = do
case con of
DataAlt con -> matchData object inner vars exp con
LitAlt lit -> matchLit object inner vars exp lit
DEFAULT -> compileExp exp
matchData :: Expression -> Expression -> [Var] -> Expr Var -> DataCon -> Compile Expression
matchData object inner vars exp con = do
if printName (dataConName con) == "ghc-prim:GHC.Types.I#"
then do vs <- mapM compileVar vars
fmap (bind vs (force object)) (compileExp exp)
else if printName (dataConName con) == "ghc-prim:GHC.Types.True"
then do vs <- mapM compileVar vars
fmap (bind vs (force object)) (compileExp exp)
else if printName (dataConName con) == "ghc-prim:GHC.Types.False"
then do vs <- mapM compileVar vars
fmap (bind vs (force object)) (compileExp exp)
else do error ("no-o: " ++ T.unpack (printName (dataConName con)))
return inner
matchLit :: Expression -> Expression -> t -> Expr Var -> Literal -> Compile Expression
matchLit object inner vars exp lit =
case lit of
MachInt i -> do
e <- compileExp exp
return (Conditional (StrictEqual (Integer (fromIntegral i))
(object))
e
inner)
bind :: [Identifier] -> Expression -> Expression -> Expression
bind vs e = (\i -> Apply (lambda vs i) [e])
-- --------------------------------------------------------------------------------
-- -- Supported stuff
wiredInPackages =
[primPackageId
,integerPackageId
,basePackageId
,rtsPackageId
,thPackageId
,dphSeqPackageId
,dphParPackageId]
noops =
[("ghc-prim","GHC.Types","I#")
,("ghc-prim","GHC.Types","C#")]
supported =
methods ++
rest
isMethod = flip elem (map encodeNameParts methods)
methods =
[("base","System.IO","print")
,("base","GHC.Base",">>")
,("base","GHC.Show","show")
-- ,("ghc-prim","GHC.Classes","==")
,("ghc-prim","GHC.Classes","<")
,("base","GHC.Num","+")
,("base","GHC.Num","-")]
rest =
[("base","System.IO","putStrLn")
,("base","GHC.TopHandler","runMainIO")
,("base","GHC.Err","undefined")
,("base","GHC.Base","$")
-- Primitives
,("ghc-prim","GHC.CString","unpackCString#")
,("ghc-prim","GHC.CString","packCString#")
,("ghc-prim","GHC.Tuple","(,)")
,("ghc-prim","GHC.Tuple","()")
,("ghc-prim","GHC.Types",":")
,("ghc-prim","GHC.Types","C#")
,("ghc-prim","GHC.Types","I#")
,("ghc-prim","GHC.Types","[]")
,("ghc-prim","GHC.Classes","$fOrdInt")
,("ghc-prim","GHC.Classes","$fEqInt")
-- Instances
,("base","GHC.Show","$fShow[]")
,("base","GHC.Show","$fShowChar")
,("base","GHC.Show","$fShowInt")
,("base","GHC.Show","$fShow(,)")
,("base","GHC.Base","$fMonadIO")
,("base","GHC.Num","$fNumInt")
,("base","GHC.Base","return")
]
--------------------------------------------------------------------------------
-- Compiler combinators
-- | Maybe generate an original name/position value.
original :: Name -> Maybe Original
original name =
case nameSrcLoc name of
RealSrcLoc loc -> Just (Original (name,loc))
_ -> Nothing
-- | Throw an exception as an expression.
throwExp :: Loc -> Expression -> Expression
throwExp loc e = Apply (Procedure [] [Throw loc e])
[]
-- | Make a lambda.
lambda :: [Identifier] -> Expression -> Expression
lambda vs e
| map Variable vs == [e] = e
| otherwise = Function vs e
-- | Translate a GHC name to a JS identifier.
translateName :: Name -> Identifier
translateName = Identifier . encodeName
-- | Encode a GHC name to an identifier.
encodeName :: Name -> Text
encodeName name = T.pack encoded where
encoded = case nameModule_maybe name of
Nothing -> zEncodeString (occNameString (nameOccName name))
Just mod ->
zEncodeString (packageIdString (modulePackageId mod)) ++ "$" ++
intercalate "$" (map zEncodeString (words (dotsToSpace (moduleNameString (moduleName mod))))) ++ "$" ++
zEncodeString (occNameString (nameOccName name))
-- | Convert dots to spaces.
dotsToSpace :: String -> String
dotsToSpace = map replace where
replace '.' = ' '
replace c = c
-- | Print a GHC name to some text.
printName :: Name -> Text
printName name = printed where
printed = case nameModule_maybe name of
Nothing -> fastStringToText $ occNameFS (nameOccName name)
Just mod -> moduleText mod <> "." <> fastStringToText (occNameFS (nameOccName name))
-- | Convert a GHC FastString to a Text. There should be a fast way to
-- convert these.
fastStringToText :: FastString -> Text
fastStringToText = T.decodeUtf8 . L.pack . bytesFS
-- | Print the parts of a name to text.
printNameParts :: (String,String,String) -> Text
printNameParts (package,mod,ident) = T.pack $
package <> ":" <> mod <> "." <> ident
-- | Encode the parts (package, module, identifier) to text.
encodeNameParts :: (String,String,String) -> Text
encodeNameParts (package,mod,ident) = T.pack $
zEncodeString (package) ++ "$" ++
intercalate "$" (map zEncodeString (words (dotsToSpace mod))) ++ "$" ++
zEncodeString ident
-- | Print the module name (and package) to text.
moduleText :: Module -> Text
moduleText mod = T.pack $
packageIdString (modulePackageId mod) ++ ":" ++
moduleNameString (moduleName mod)
-- | Force an expression, unless it's a built-in function which
-- doesn't need to be forced.
force :: Expression -> Expression
force e
-- | Known function name?
| any ((e==) . Variable . Identifier . encodeNameParts) supported = e
-- | It's a method call on a dictionary, which don't need to be forced.
| Apply (Variable (Identifier name)) _ <- e,
isMethod name = e
--
| otherwise = Apply (Variable (Identifier "_"))
[e]
-- | Force an IO action.
act :: Expression -> Expression
act e = Apply (Variable (Identifier "__"))
[e]
-- | Make a thunk for an expression, unless it's a constant or a
-- function, in which case it's not necessary.
thunk :: Expression -> Expression
thunk e =
if isFunction e
then e
else if isConstant e
then e
else New (Identifier "$")
(Function [] e)
-- | Is the given expression a constant e.g. a literal or w/e.
isConstant :: Expression -> Bool
isConstant Integer{} = True
isConstant Double{} = True
isConstant String{} = True
isConstant Variable{} = True
isConstant _ = False
-- | Is the given expression a function?
isFunction :: Expression -> Bool
isFunction Function{} = True
isFunction _ = False
--------------------------------------------------------------------------------
-- Working with Core
-- | Get the core AST of a Haskell file.
getCoreAst :: FilePath -> IO CoreModule
getCoreAst fp = do
defaultErrorHandler defaultLogAction $ do
runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
let dflags' = foldl xopt_set dflags [Opt_Cpp,Opt_ImplicitPrelude,Opt_MagicHash]
setSessionDynFlags dflags' { optLevel = 2 }
cm <- compileToCoreSimplified fp
return cm
--------------------------------------------------------------------------------
-- Printing
-- | Beautify the given JS.
beautify :: Text -> IO Text
beautify src = do
result <- readAllFromProcess "/home/chris/Projects/js-beautify/python/js-beautify"
["-i","-s","2","-d","-w","80"]
src
case result of
Left err -> error (T.unpack err)
Right (_,out) -> return out
-- | Compress the given JS with Closure with advanced compilation.
compress :: Text -> IO Text
compress src = do
result <- readAllFromProcess "java"
["-jar"
,"/home/chris/Projects/fpco/learning-site/tools/closure-compiler.jar"
,"--compilation_level=ADVANCED_OPTIMIZATIONS"]
src
case result of
Left err -> error (T.unpack err)
Right (_,out) -> return out
--------------------------------------------------------------------------------
-- Utilities that should be moved to other modules
-- | Read all stuff from a process.
readAllFromProcess :: FilePath -> [String] -> Text -> IO (Either Text (Text,Text))
readAllFromProcess program flags input = do
(code,out,err) <- readProcessWithExitCode program flags input
return $ case code of
ExitFailure _ -> Left err
ExitSuccess -> Right (err, out)
-- | Generically show something.
gshow :: Data a => a -> String
gshow x = gshows x ""
-- | A shows printer which is good for printing Core.
gshows :: Data a => a -> ShowS
gshows = render `extQ` (shows :: String -> ShowS) where
render t
| isTuple = showChar '('
. drop 1
. commaSlots
. showChar ')'
| isNull = showString "[]"
| isList = showChar '['
. drop 1
. listSlots
. showChar ']'
| otherwise = showChar '('
. constructor
. slots
. showChar ')'
where constructor = showString . showConstr . toConstr $ t
slots = foldr (.) id . gmapQ ((showChar ' ' .) . gshows) $ t
commaSlots = foldr (.) id . gmapQ ((showChar ',' .) . gshows) $ t
listSlots = foldr (.) id . init . gmapQ ((showChar ',' .) . gshows) $ t
isTuple = all (==',') (filter (not . flip elem "()") (constructor ""))
isNull = null (filter (not . flip elem "[]") (constructor ""))
isList = constructor "" == "(:)"
-- | Simple shortcut.
io :: MonadIO m => IO a -> m a
io = liftIO
-- | Traverse a data type, left to stop, right to keep going after updating the value.
gtraverseT :: (Data a,Typeable b) => (b -> b) -> a -> a
gtraverseT f =
gmapT (\x -> case cast x of
Nothing -> gtraverseT f x
Just b -> fromMaybe x (cast (f b)))
-- | Something like Show but for things which annoyingly do not have
-- Show but Outputable instead.
showppr :: Outputable a => a -> String
showppr = showSDoc . ppr
--------------------------------------------------------------------------------
-- AST
-- | JavaScript statement.
data Statement
= Declaration !Identifier !(Maybe Original) !Expression
| Return !Expression
| Throw !Loc !Expression
deriving (Eq,Show)
-- | JavaScript expression.
data Expression
= Variable !Identifier
| New !Identifier !Expression
| Sequence [Expression]
| Function ![Identifier] !Expression
| Procedure ![Identifier] ![Statement]
| Apply !Expression ![Expression]
| Conditional !Expression !Expression !Expression
| StrictEqual !Expression !Expression
| Integer !Integer
| Double !Double
| String !String
deriving (Eq,Show)
-- | Variable name.
newtype Identifier
= Identifier Text
deriving (Eq,Show)
-- | State of the JS printer.
data PrintState
= PrintState { psBuilder :: !Builder
, psLine :: !Int
, psColumn :: !Int
, psMappings :: ![Mapping]
}
-- | A source location (line,col).
newtype Loc = Loc (Text,Int)
deriving (Show,Eq)
-- | Original Haskell name.
newtype Original = Original { unOriginal :: (Name,RealSrcLoc) }
deriving (Eq)
instance Show Original where
show (Original name) = showppr name
--------------------------------------------------------------------------------
-- Pretty printer
-- | JS pretty printer.
newtype PP a = PP { runPP :: State PrintState a }
deriving (Functor,Monad,MonadState PrintState)
-- | Render the JS AST to text.
renderStatements :: Int -> [Statement] -> (Text,[Mapping])
renderStatements line = (write &&& mappings) . pp where
pp = flip execState state . runPP . ppStatements
write = toLazyText . psBuilder
state = PrintState mempty line 0 []
mappings = reverse . psMappings
-- | Pretty print statements.
ppStatements :: [Statement] -> PP ()
ppStatements = mapM_ ppStatement
-- | A pretty printer for the JS.
ppStatement :: Statement -> PP ()
ppStatement s =
case s of
Declaration i pos e ->
do maybe (return ()) (mapping i) pos
write "var "
ppIdentifier i
write " = "
ppExpression e
write ";"
newline
Return e ->
do write "return ("
ppExpression e
write ");"
Throw loc e ->
do mapFrom loc
write "throw ("
ppExpression e
write ");"
-- | Pretty print expressions.
ppExpression :: Expression -> PP ()
ppExpression e =
case e of
Variable i -> ppIdentifier i
New i e ->
do write "new "
ppIdentifier i
write "("
ppExpression e
write ")"
Function is e -> ppProcedure is [Return e]
Procedure is ss -> ppProcedure is ss
Apply e es ->
do ppExpression e
write "("
intercalateM ", " (map ppExpression es)
write ")"
Conditional p y n ->
do write "("
ppExpression p
write " ? "
ppExpression y
write " : "
ppExpression n
write ")"
StrictEqual a b ->
do ppExpression a
write " === "
ppExpression b
Sequence es ->
do write "("
intercalateM ", " (map ppExpression es)
write ")"
Integer i -> write (T.pack (show i))
Double d -> write (T.pack (show d))
String s -> write (T.pack (ECMA.renderExpression (ECMA.StringLit () s)))
-- | Pretty print a function closure.
ppProcedure :: [Identifier] -> [Statement] -> PP ()
ppProcedure is ss =
do write "function("
intercalateM ", " (map ppIdentifier is)
write "){"
intercalateM ";" (map ppStatement ss)
write "}"
-- | Pretty print an identifier.
ppIdentifier :: Identifier -> PP ()
ppIdentifier i =
case i of
Identifier text -> write text
--------------------------------------------------------------------------------
-- Utilities for the pretty printer
-- | Intercalate monadic action.
intercalateM :: Text -> [PP a] -> PP ()
intercalateM _ [] = return ()
intercalateM _ [x] = x >> return ()
intercalateM str (x:xs) = do
x
write str
intercalateM str xs
-- | Something to write to the printer builder.
data Write
= WriteNewline
| WriteText Text
-- | Write something to the output builder.
build :: Write -> PP ()
build x = do
ps <- get
case x of
WriteNewline ->
let !column = 0
!line = psLine ps + 1
in put ps { psBuilder = psBuilder ps <> fromLazyText "\n"
, psColumn = column
, psLine = line
}
WriteText text ->
let !column = psColumn ps + fromIntegral (T.length text)
!builder = psBuilder ps <> fromLazyText text
in put ps { psBuilder = builder
, psColumn = column
}
-- | Write some text to the builder. Shouldn't contain newlines.
write :: Text -> PP ()
write = build . WriteText
-- | Write a newline to the output builder.
newline :: PP ()
newline = build WriteNewline
-- | Generate a mapping.
mapping :: Identifier -> Original -> PP ()
mapping (Identifier identifier) (Original (name,loc)) = modify $ \ps ->
ps { psMappings = m ps : psMappings ps
}
where m ps = Mapping { mapGenerated = Pos (fromIntegral (psLine ps))
(fromIntegral (psColumn ps))
, mapOriginal = Just (Pos (fromIntegral line)
(fromIntegral col - 1))
, mapSourceFile = Just (T.unpack (fastStringToText file))
, mapName = Just (T.toStrict (printName name))
}
line = srcLocLine loc
col = srcLocCol loc
file = srcLocFile loc
-- | Generate a mapping just for a location.
mapFrom :: Loc -> PP ()
mapFrom (Loc (file,line)) = modify $ \ps ->
ps { psMappings = m ps : psMappings ps
}
where m ps = Mapping { mapGenerated = Pos (fromIntegral (psLine ps))
(fromIntegral (psColumn ps))
, mapOriginal = Just (Pos (fromIntegral line)
0)
, mapSourceFile = Just (T.unpack file)
, mapName = Nothing
}
| chrisdone/fore | src/Main.hs | bsd-3-clause | 26,422 | 0 | 27 | 7,008 | 7,909 | 4,037 | 3,872 | 670 | 11 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import GHC.Float
import Graphics.EasyPlot
import qualified Sound.File.Sndfile as Snd
import qualified Sound.File.Sndfile.Buffer.Vector as B
import qualified Data.Vector.Generic as V
import qualified Data.Sequence as S
import qualified Data.Foldable as F
import Sound.Analysis.Spectrum
import Sound.Analysis.SpectralFlux
import Sound.Analysis.Onset
import Sound.Analysis.Filters
import Sound.Data.Buffers
--RUN WITH OPTIONS
-- +RTS -N2 -s -qg2 -A1024k
main = do
--bs holds our BufferS
(info, Just (bs :: B.Buffer Double)) <- Snd.readFile "./shpongle.ogg"
--Convert to an unboxed array
let b = sterilize bs
--Grab all of the sound file
let ct = (truncate $ (fromIntegral $ Snd.frames info)/2048.0)-2
let i = StreamInfo 1024 44100 2
let b' = sampleRawPCM 0 ct (i, b)
let s = pcmStream b'
let (i, freqs) = freqStream s
let fluxes = onsetStream 12 ( fluxStream (i, freqs) 32)
let bins = [86, 172..]
let freqBins = [43, 86..]
--let sPlot = streamPlot $ zip bins (F.toList fluxes)
let onsetL = fmap (S.length) (bands fluxes)
print $ "Onsets: "++(show onsetL)
print $ "total Onsets: "++ (show $ sumS onsetL)
--plot X11 $ Data2D [Color Magenta, Style Lines] [Step 43] (sPlot)
plot X11 $ Data2D [Color DarkGreen, Style Impulses] [Step 1] (toPlot (bands fluxes) 0)
print $ show "done"
--plot a single frame of onsets
toPlot :: S.Seq (S.Seq Onset) -> Int -> [(Double, Double)]
toPlot fs n = snd $ F.foldl step (0.0, []) fs'
where fs' = fmap (flip S.index $ n) fs
--step :: (Int, [(Int, Double)]) -> Double -> (Int, [(Int, Double)])
step (i, es) e = (i+1.0, es++[(i, power e)])
| Smurf/Tempoist | Examples/OnsetExample.hs | bsd-3-clause | 1,759 | 0 | 17 | 396 | 566 | 306 | 260 | 34 | 1 |
module Main where
import Test.Hspec
import Test.QuickCheck
sayHello :: IO ()
sayHello = putStrLn "hello!"
dividedBy :: Integral a => a -> a -> (a, a)
dividedBy num denom = go num denom 0
where go n d count
| n < d = (count, n)
| otherwise = go (n - d) d (count + 1)
someInts = sample (arbitrary :: Gen Int)
someDoubles = sample (arbitrary :: Gen Double)
genIntStrings = fmap show (arbitrary :: Gen Int)
genDoubleStrings = fmap show (arbitrary :: Gen Double)
mixedNumbers :: Gen String
mixedNumbers = oneof [genIntStrings, genDoubleStrings]
someMixedNumbers = sample mixedNumbers
oneToThree :: Gen Int
oneToThree = elements [1, 2, 3]
sampleOneToThree = sample oneToThree
data Die = Heads | Tails deriving Show
weightedDie :: Gen Die
weightedDie = elements [Heads, Tails, Tails, Tails]
throwWeightedDie = sample weightedDie
main :: IO ()
main = hspec $ do
describe "Addition" $ do
it "1 + 1 is greater than 1" $ do
(1 + 1) > 1 `shouldBe` True
it "2 + 2 is greater than 3" $ do
(2 + 2) > 3 `shouldBe` True
it "x + 1 is always greater than x" $ do
property $ \x -> x + 1 > (x :: Int)
it "x + 1 is always greater than x" $ do
property $ \x -> (x + 1 > (x :: Int)) && (x < 4)
describe "Division" $ do
it "15 divided by 5 is 3" $ do
dividedBy 15 5 == (3, 0) `shouldBe` True
dividedBy 15 5 /= (3, 0) `shouldBe` False
| peterbecich/haskell-programming-first-principles | subprojects/additionHspec/Main.hs | bsd-3-clause | 1,408 | 0 | 19 | 360 | 562 | 292 | 270 | 39 | 1 |
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module Schema
( MatchesGenes
, Schema (..)
, order
, matches
) where
import Data.List
import Genes
class MatchesGenes a where
matches :: a -> DnaString -> DnaString -> Bool
class HasOrder a where
order :: a -> Int
newtype Schema = Schema
{ schemaElements :: [Maybe Allele]
} deriving (Eq)
shortRepr :: Maybe Allele -> String
shortRepr Nothing = "*"
shortRepr (Just b) = show b
instance Show Schema
where
show (Schema elems) = "<" ++ intercalate "" (map shortRepr elems) ++ ">"
instance HasOrder Schema
where
order = length . filter (/= Nothing) . schemaElements
instance MatchesGenes Schema
where
matches (Schema s) (DnaString d1) (DnaString d2) =
if length s == length d1 && length d1 == length d2
then matches' s d1 d2
else error "Incompatible Schema and DNA"
where
matches' :: [Maybe Allele] -> [Allele] -> [Allele] -> Bool
matches' [] [] [] = True
matches' (Nothing : bs) (_ : b1s) (_ : b2s) = matches' bs b1s b2s
matches' (Just b : bs) (b1 : b1s) (b2 : b2s) = (b == b1 || b == b2) && matches' bs b1s b2s | satai/FrozenBeagle | Simulation/Lib/src/Schema.hs | bsd-3-clause | 1,221 | 0 | 12 | 354 | 440 | 230 | 210 | 31 | 1 |
module Types.Job
( module RPC.Util
, JobMap
, JobName (..)
, JobURIPath (..)
, JobId (..)
, JobInfo (..)
) where
import RPC.Util
import Control.Applicative ((<$>),(<*>),(<|>))
import qualified Data.Map as Map
--------------------------------------------------------------------------------
newtype JobName = JobName
{ getJobName :: String
} deriving (Show,Eq,Ord)
instance FromObject JobName where
fromObject obj = JobName <$> fromObject obj
--------------------------------------------------------------------------------
newtype JobURIPath = JobURIPath
{ getJobURIPath :: String
} deriving (Show,Eq,Ord)
instance FromObject JobURIPath where
fromObject obj = JobURIPath <$> fromObject obj
--------------------------------------------------------------------------------
newtype JobId = JobId
{ getJobId :: String
} deriving (Show,Eq,Ord)
instance ToObject JobId where
toObject (JobId i) = toObject i
instance FromObject JobId where
fromObject obj = asInt <|> asString
where
asInt = JobId . show <$> (fromObject obj :: Maybe Int)
asString = JobId <$> fromObject obj
--------------------------------------------------------------------------------
data JobInfo = JobInfo
{ jobId :: JobId
, jobName :: JobName
, jobStartTime :: Int
, jobUriPath :: Optional JobURIPath
, jobDataStore :: Optional String
} deriving (Show,Eq,Ord)
instance FromObject JobInfo where
fromObject obj = JobInfo <$>
lookupField "jid" obj <*>
lookupField "name" obj <*>
lookupField "start_time" obj <*>
lookupField "uripath" obj <*>
lookupField "datastore" obj
--------------------------------------------------------------------------------
type JobMap = Map.Map JobId String
| GaloisInc/msf-haskell | src/Types/Job.hs | bsd-3-clause | 1,788 | 0 | 11 | 332 | 433 | 246 | 187 | 44 | 0 |
{- PiForall language, OPLSS, Summer 2013 -}
{-# LANGUAGE FlexibleInstances, FlexibleContexts, TupleSections,
ExplicitForAll #-}
{-# OPTIONS_GHC -Wall -fno-warn-unused-matches -fno-warn-orphans #-}
-- | A parsec-based parser for the concrete syntax.
module Parser
(
parseModuleFile,
parseModuleImports,
parseExpr
)
where
import Syntax hiding (moduleImports)
import Unbound.LocallyNameless hiding (Data,Refl,Infix,join,name)
import Unbound.LocallyNameless.Ops (unsafeUnbind)
import Text.Parsec hiding (State,Empty)
import Text.Parsec.Expr(Operator(..),Assoc(..),buildExpressionParser)
import qualified LayoutToken as Token
import Control.Monad.State.Lazy hiding (join)
import Control.Applicative ((<$>), (<*>), (<*), (*>), (<$))
import Control.Monad.Error hiding (join)
import Data.List
import qualified Data.Set as S
{-
Concrete syntax for the language:
Optional components in this BNF are marked with < >
levels:
l ::= natural numbers
terms:
a,b,A,B ::=
Type <l> Universes
| x Variables (start with lowercase)
| \ x . a Function definition
| a b Application
| (x : A) -> B Pi type
| A / R Quotient type
| <x:Q> Quotient introduction
| expose x P p rsp Quotient elimination
expose : (P : A / R -> Type i) (s : (a : A) -> P <a>) (rsp : (x : A) (y : A) -> R x y -> (s x = s y)) (x : A / R) -> P x
| (a : A) Annotations
| (a) Parens
| TRUSTME An axiom 'TRUSTME', inhabits all types
| {?x} A hole named x
| let x = a in b Let expression
| Zero Empty type
| One Unit type
| tt Unit value
| { x : A | B } Dependent pair type
| (a, b) Prod introduction
| pcase a of (x,y) -> b Prod elimination
| a = b Equality type
| subst a by b <at x.c> Type conversion
| contra a Contra
| refl p Equality proof with evidence
| trivial Trivial tactic
| induction [x,...y] Induction tactic
| C a ... Type / Term constructors
| case a [y] of Pattern matching
C1 [x] y z -> b1
C2 x [y] -> b2
| ind f x = a Induction
| ( x : A | C) -> B Constrained type
| a < b Ordering constrant
declarations:
foo : A
foo = a
axiom foo : A
data T D : Type <l> where
C1 of D1
...
Cn of Dn
telescopes:
D ::=
Empty
| (x : A) D cons
| (A) D
Syntax sugar:
- You can collapse lambdas, like:
\ x [y] z . a
This gets parsed as \ x . \ [y] . \ z . a
- You can make a top level declaration an ind:
foo : (n : Nat) -> A
ind foo x = ...
-}
liftError :: (MonadError e m) => Either e a -> m a
liftError (Left e) = throwError e
liftError (Right a) = return a
-- | Parse a module declaration from the given filepath.
parseModuleFile :: (MonadError ParseError m, MonadIO m) => ConstructorNames -> String -> m Module
parseModuleFile cnames name = do
liftIO $ putStrLn $ "Parsing File " ++ show name
contents <- liftIO $ readFile name
liftError $ runFreshM $
flip evalStateT cnames $
runParserT (whiteSpace *> moduleDef <* eof) [] name contents
-- | Parse only the imports part of a module from the given filepath.
parseModuleImports :: (MonadError ParseError m, MonadIO m) => String -> m Module
parseModuleImports name = do
contents <- liftIO $ readFile name
liftError $ runFreshM $
flip evalStateT emptyConstructorNames $
runParserT (whiteSpace *> moduleImports) [] name contents
-- | Test an 'LParser' on a String.
--
-- E.g., do
--
-- > testParser decl "axiom fix : (aTy : Type 0) -> (f : ((a:aTy) -> aTy)) -> aTy"
--
-- to parse an axiom declaration of a logical fixpoint combinator.
testParser :: LParser t -> String -> Either ParseError t
testParser parser str = runFreshM $
flip evalStateT emptyConstructorNames $
runParserT (do { whiteSpace; v <- parser; eof; return v}) [] "<interactive>" str
-- | Parse an expression.
parseExpr :: String -> Either ParseError Term
parseExpr = testParser expr
-- * Lexer definitions
type LParser a = ParsecT
String -- The input is a sequence of Char
[Column] -- The internal state for Layout tabs
(StateT ConstructorNames
FreshM) -- The internal state for generating fresh names,
-- and for remembering which names are constructors.
a -- the type of the object being parsed
instance Fresh (ParsecT s u (StateT ConstructorNames FreshM)) where
fresh = lift . lift . fresh
-- Based on Parsec's haskellStyle (which we can not use directly since
-- Parsec gives it a too specific type).
trellysStyle :: (Stream s m Char, Monad m) => Token.GenLanguageDef s u m
trellysStyle = Token.LanguageDef
{ Token.commentStart = "{-"
, Token.commentEnd = "-}"
, Token.commentLine = "--"
, Token.nestedComments = True
, Token.identStart = letter <|> oneOf "~"
, Token.identLetter = alphaNum <|> oneOf "_'⁺~"
, Token.opStart = oneOf ":!#$%&*+.,/<=>?@\\^|-"
, Token.opLetter = oneOf ":!#$%&*+.,/<=>?@\\^|-"
, Token.caseSensitive = True
, Token.reservedNames =
["refl"
,"ind"
,"Type"
,"data"
,"where"
,"case"
,"of"
,"with"
,"under"
,"by"
,"contra"
,"subst", "by", "at"
,"let", "in"
,"axiom"
,"TRUSTME"
,"ord"
,"pcase"
,"expose"
,"trivial"
,"induction"
,"Zero","One", "tt"
]
, Token.reservedOpNames =
["!","?","\\",":",".",",","<", "=", "+", "-", "^", "()", "_", "[|", "|]", "|", "{", "}"]
}
tokenizer :: Token.GenTokenParser String [Column] (StateT ConstructorNames FreshM)
layout :: forall a t. LParser a -> LParser t -> LParser [a]
(tokenizer, layout) =
let (t, Token.LayFun l) = Token.makeTokenParser trellysStyle "{" ";" "}"
in (t, l)
identifier :: LParser String
identifier = Token.identifier tokenizer
whiteSpace :: LParser ()
whiteSpace = Token.whiteSpace tokenizer
variable :: LParser TName
variable =
do i <- identifier
cnames <- get
if string2Name i `S.member` tconNames cnames || i `S.member` dconNames cnames
then fail "Expected a variable, but a constructor was found"
else return $ string2Name i
wildcard :: LParser TName
wildcard = reservedOp "_" >> return wildcardName
varOrWildcard :: LParser TName
varOrWildcard = try wildcard <|> variable
dconstructor :: LParser DCName
dconstructor =
do i <- identifier
cnames <- get
if i `S.member` dconNames cnames
then return i
else fail $ if string2Name i `S.member` tconNames cnames
then "Expected a data constructor, but a type constructor was found."
else "Expected a constructor, but a variable was found"
tconstructor :: LParser TCName
tconstructor =
do i <- identifier
cnames <- get
if string2Name i `S.member` tconNames cnames
then return $ string2Name i
else fail $ if i `S.member` dconNames cnames
then "Expected a type constructor, but a data constructor was found."
else "Expected a constructor, but a variable was found"
-- variables or zero-argument constructors
varOrCon :: LParser Term
varOrCon = do i <- identifier
cnames <- get
return $ if i `S.member` dconNames cnames
then DCon i [] $ Annot Nothing
else if string2Name i `S.member` tconNames cnames
then TCon (string2Name i) []
else Var $ string2Name i
colon, dot, comma :: LParser ()
colon = () <$ Token.colon tokenizer
dot = () <$ Token.dot tokenizer
comma = () <$ Token.comma tokenizer
reserved,reservedOp :: String -> LParser ()
reserved = Token.reserved tokenizer
reservedOp = Token.reservedOp tokenizer
parens,brackets,braces :: LParser a -> LParser a
parens = Token.parens tokenizer
brackets = Token.brackets tokenizer
braces = Token.braces tokenizer
natural :: LParser Int
natural = fromInteger <$> Token.natural tokenizer
natenc :: LParser Term
natenc =
do n <- natural
return $ encode n
where encode 0 = DCon "zero" [] natty
encode n = DCon "succ" [encode (n-1)] natty
natty = Annot $ Just (TCon (string2Name "ℕ") [])
moduleImports :: LParser Module
moduleImports = do
reserved "module"
modName <- identifier
reserved "where"
imports <- layout importDef (return ())
return $ Module (string2Name modName) imports [] emptyConstructorNames
moduleDef :: LParser Module
moduleDef = do
reserved "module"
modName <- identifier
reserved "where"
imports <- layout importDef (return ())
decls <- layout decl (return ())
cnames <- get
return $ Module (string2Name modName) imports decls cnames
importDef :: LParser ModuleImport
importDef = reserved "import" >> ModuleImport <$> importName
where importName = liftM string2Name identifier
telescope :: LParser Telescope
telescope = do
bindings <- telebindings
return $ foldr g Empty bindings where
g (n, t) rst = Cons (rebind (n, embed t) rst)
telebindings :: LParser [(TName, Term)]
telebindings = many teleBinding
where
annot :: LParser (TName, Term)
annot = do
(x,ty) <- try ((,) <$> varOrWildcard <*> (colon >> expr))
<|> ((,) <$> fresh wildcardName <*> expr)
return (x,ty)
teleBinding :: LParser (TName, Term)
teleBinding =
( parens annot
<|> brackets annot) <?> "binding"
---
--- Top level declarations
---
decl,dataDef,sigDef,valDef,indDef :: LParser Decl
decl = try dataDef <|> sigDef <|> valDef <|> indDef
-- datatype declarations.
dataDef = do
reserved "data"
name <- identifier
params <- telescope
colon
Type level <- typen
modify (\cnames ->
cnames{ tconNames = S.insert (string2Name name)
(tconNames cnames) })
reserved "where"
cs <- layout constructorDef (return ())
forM_ cs
(\(ConstructorDef _ cname _) ->
modify (\cnames -> cnames{ dconNames = S.insert cname (dconNames cnames)}))
return $ Data (string2Name name) params level cs
constructorDef :: LParser ConstructorDef
constructorDef = (ConstructorDef <$> getPosition <*> identifier <*> option Empty (reserved "of" *> telescope))
<?> "Constructor"
sigDef = do
axOrSig <- option Sig $ reserved "axiom" >> return Axiom
axOrSig <$> try (variable <* colon) <*> expr
valDef = Def <$> try (variable <* reservedOp "=") <*> expr
indDef = do
r@(Ind b _) <- ind
let ((n,_),_) = unsafeUnbind b
return $ Def n r
------------------------
------------------------
-- Terms
------------------------
------------------------
trustme :: LParser Term
trustme = TrustMe (Annot Nothing) <$ reserved "TRUSTME"
hole :: LParser Term
hole = Hole <$> name <*> return (Annot Nothing)
where
name = braces $ string2Name <$> (reservedOp "?" *> many (noneOf "{}"))
trivialTactic :: LParser Term
trivialTactic = Trivial (Annot Nothing) <$ (reserved "trivial" <|> reservedOp "_")
inductionTactic :: LParser Term
inductionTactic = reserved "induction" *> (Induction (Annot Nothing) <$> brackets scrutinees)
where
scrutinees = expr `sepBy1` comma
refl :: LParser Term
refl = do
reserved "refl"
evidence <- option LitUnit expr
annot <- optionMaybe (colon >> expr)
return $ Refl (Annot annot) evidence
-- Expressions
expr,term,factor :: LParser Term
-- expr is the toplevel expression grammar
expr = Pos <$> getPosition <*> buildExpressionParser table term
where table = [[ifix AssocLeft "<" Smaller],
[ifix AssocLeft "=" mkEq],
[ifix AssocLeft "//" Quotient],
[ifixM AssocRight "->" mkArrow]
]
ifix assoc op f = Infix (reservedOp op >> return f) assoc
ifixM assoc op f = Infix (reservedOp op >> f) assoc
mkEq a b = TyEq a b (Annot Nothing) (Annot Nothing)
mkArrow =
do n <- fresh wildcardName
return $ \tyA tyB ->
Pi (bind (n,embed tyA) tyB)
-- A "term" is either a function application or a constructor
-- application. Breaking it out as a seperate category both
-- eliminates left-recursion in (<expr> := <expr> <expr>) and
-- allows us to keep constructors fully applied in the abstract syntax.
term = try dconapp <|> try tconapp <|> funapp
arg :: LParser Term
arg = brackets expr <|> factor
dconapp :: LParser Term
dconapp = DCon <$> dconstructor <*> many arg <*> return (Annot Nothing)
tconapp :: LParser Term
tconapp = TCon <$> tconstructor <*> many factor
funapp :: LParser Term
funapp = do
f <- factor
foldl' App f <$> many factor
factor = choice [ varOrCon <?> "a variable or nullary data constructor"
, typen <?> "Type n"
, natenc <?> "a literal"
, lambda <?> "a lambda"
, ind <?> "ind"
, letExpr <?> "a let"
, contra <?> "a contra"
, caseExpr <?> "a case"
, pcaseExpr <?> "a pcase"
, exposeExpr <?> "an expose"
, sigmaTy <?> "a sigma type"
, squashTy <?> "a squash type"
, qboxExpr <?> "a quotient box"
, substExpr <?> "a subst"
, refl <?> "refl"
, trivialTactic <?> "the trivial tactic"
, inductionTactic <?> "the induction tactic"
, trustme <?> "TRUSTME"
, hole <?> "hole"
, impProd <?> "an implicit function type"
, bconst <?> "a constant"
, expProdOrAnnotOrParens
<?> "an explicit function type or annotated expression"
]
typen :: LParser Term
typen = Type <$> (reserved "Type" *> (try natural <|> return 0))
-- Lambda abstractions have the syntax '\x . e'
lambda :: LParser Term
lambda = do reservedOp "\\"
binds <- many1 variable
dot
body <- expr
return $ foldr lam body binds where
lam x m = Lam (bind (x, embed $ Annot Nothing) m)
-- recursive abstractions, with the syntax 'ind f x = e', no type annotation.
ind :: LParser Term
ind = do
reserved "ind"
f <- variable
x <- variable
reservedOp "="
body <- expr
return $ Ind (bind (f,x) body) $ Annot Nothing
bconst :: LParser Term
bconst = choice [TyEmpty <$ reserved "Zero",
TyUnit <$ reserved "One",
LitUnit <$ reserved "tt"]
--
letExpr :: LParser Term
letExpr =
do reserved "let"
x <- variable
reservedOp "="
boundExp <- expr
reserved "in"
body <- expr
return $ Let $ bind (x,embed boundExp) body
-- impProd - implicit dependent products
-- These have the syntax [x:a] -> b or [a] -> b .
impProd :: LParser Term
impProd =
do (x,tyA, mc) <- brackets
(try ((,,) <$> variable <*> (colon >> expr) <*> return Nothing)
<|> ((,,) <$> fresh wildcardName <*> expr) <*> return Nothing)
optional (reservedOp "->")
tyB <- expr
return $ case mc of
Just c -> PiC (bind (x,embed tyA) (c,tyB))
Nothing -> Pi (bind (x,embed tyA) tyB)
qboxExpr :: LParser Term
qboxExpr = do
reservedOp "<"
x <- expr
mty <- optionMaybe (reservedOp ":" *> expr)
reservedOp ">"
return $ QBox x (Annot $ mty)
exposeExpr :: LParser Term
exposeExpr = do
reserved "expose"
q <- expr
reserved "under"
p <- expr
reserved "with"
s <- expr
reserved "by"
rsp <- expr
return $ QElim p s rsp q
-- Function types have the syntax '(x:A) -> B'. This production deals
-- with the ambiguity caused because these types, annotations and
-- regular old parens all start with parens.
data InParens = Colon Term Term | Comma Term Term | Nope Term
expProdOrAnnotOrParens :: LParser Term
expProdOrAnnotOrParens =
let
-- afterBinder picks up the return type of a pi
afterBinder :: LParser Term
afterBinder = optional (reservedOp "->") *> expr
-- before binder parses an expression in parens
-- If it doesn't involve a colon, you get (Right tm)
-- If it does, you get (Left tm1 tm2). tm1 might be a variable,
-- in which case you might be looking at an explicit pi type.
beforeBinder :: LParser InParens
beforeBinder = parens $
choice [ Colon <$> try (term <* colon) <*> expr
, Comma <$> try (term <* comma) <*> expr
, Nope <$> expr]
in
do bd <- beforeBinder
case bd of
Colon (Var x) a ->
option (Ann (Var x) a)
(Pi <$> (bind (x, embed a) <$> afterBinder))
Colon a b -> return $ Ann a b
Comma a b -> return $ Prod a b (Annot Nothing)
Nope a -> return $ a
pattern :: LParser Pattern
-- Note that 'dconstructor' and 'variable' overlaps, annoyingly.
pattern = try (PatCon <$> dconstructor <*> many atomic_pattern)
<|> atomic_pattern
where
atomic_pattern = parens pattern
<|> (PatVar <$> wildcard)
<|> do t <- varOrCon
case t of
(Var x) -> return $ PatVar x
(DCon c [] _) -> return $ PatCon c []
(TCon c []) -> fail "expected a data constructor but a type constructor was found"
_ -> error "internal error in atomic_pattern"
match :: LParser Match
match = Match <$> (bind <$> pattern <* reservedOp "->" <*> term)
caseExpr :: LParser Term
caseExpr = Case
<$> (reserved "case" *> factor)
<*> (reserved "of" *> layout match (return ()))
<*> return (Annot Nothing)
pcaseExpr :: LParser Term
pcaseExpr = do
reserved "pcase"
scrut <- expr
reserved "of"
reservedOp "("
x <- variable
reservedOp ","
y <- variable
reservedOp ")"
reservedOp "->"
a <- expr
return $ Pcase scrut (bind (x,y) a) (Annot Nothing)
-- subst e0 by e1 { at [x.t] }
substExpr :: LParser Term
substExpr = do
reserved "subst"
a <- expr
reserved "by"
b <- expr
ctx <- option Nothing (try (do
reserved "at"
x <- variable
dot
c <- expr
return (Just (bind x c))))
return $ Subst a b ctx
contra :: LParser Term
contra = Contra <$> (reserved "contra" *> expr) <*> return (Annot Nothing)
squashTy :: LParser Term
squashTy = do
x <- between (reservedOp "[|") (reservedOp "|]") expr
return (TySquash x) <?> "Squash"
sigmaTy :: LParser Term
sigmaTy = do
reservedOp "{"
x <- variable
colon
a <- expr
reservedOp "&"
b <- expr
reservedOp "}"
return (Sigma (bind (x, embed a) b))
| jonsterling/Luitzen | src/Parser.hs | bsd-3-clause | 19,753 | 61 | 19 | 6,300 | 4,924 | 2,542 | 2,382 | 413 | 4 |
module Core.Core where
type Name = String
type Program = [Toplevel]
data Toplevel
= Declare Name Expression
deriving (Eq, Show, Ord, Read)
data Expression
= Var Name
| Lambda Pat Expression
| Let Pat Expression Expression
| If Expression Expression Expression
| Case [CaseArm] Expression
| Literal Literal
| Apply Expression Expression
| List [Expression]
| BinOp Expression Expression Expression
| Unbox Literal
deriving (Eq, Show, Ord, Read)
data Literal
= LString String
| LNumber Double
| LTrue | LFalse
| LUnit
deriving (Eq, Show, Ord, Read)
data CaseArm
= CaseArm { pat :: Pat
, res :: Expression }
deriving (Eq, Show, Ord, Read)
data Pat
= Wildcard
| Bound Name Pat
| PList [Pat]
| PLit Literal
| Capture Name
| Cons Pat Pat
| Constructor { tag :: String
, arity :: Int
, vals :: [Pat] }
deriving (Eq, Show, Ord, Read)
isNestedLam :: Expression -> Bool
isNestedLam Var{} = False
isNestedLam Literal{} = False
isNestedLam Unbox{} = False
isNestedLam Lambda{} = False
isNestedLam (Let _ e e') = isNestedLam e || isNestedLam e'
isNestedLam (If c t e) = isNestedLam c || isNestedLam t || isNestedLam e
isNestedLam (Case ca e) = any canl ca || isNestedLam e
where canl (CaseArm _ r) = isNestedLam r
isNestedLam (Apply e _) = isNestedLam e
isNestedLam (List xs) = any isNestedLam xs
isNestedLam (BinOp o l r) = any isNestedLam [o, l, r]
| demhydraz/waffle | src/Core/Core.hs | bsd-3-clause | 1,457 | 0 | 9 | 355 | 553 | 298 | 255 | 51 | 1 |
{-| Representation of musical instruments.
The 'Instrument' type represent any instrument in the MusicXML Standard Sounds 3.0 set,
with some extensions. See <http://www.musicxml.com/for-developers/standard-sounds>.
-}
module Music.Parts.Instrument (
Instrument,
-- * Name
-- instrumentName,
fullName,
shortName,
fromMidiProgram,
toMidiProgram,
fromMusicXmlSoundId,
toMusicXmlSoundId,
-- * Clefs and transposition
transposition,
transpositionString,
standardClef,
allowedClefs,
-- * Playing range
playableRange,
comfortableRange,
-- playableDynamics,
-- * Legacy
gmClef,
gmMidiChannel,
gmScoreOrder,
-- gmInstrName,
) where
import Control.Applicative
import Control.Lens (toListOf)
import Data.Aeson (ToJSON (..), FromJSON(..))
import qualified Data.Aeson
import Data.Default
import Data.Functor.Adjunction (unzipR)
import qualified Data.List
import Data.Map (Map)
import qualified Data.Maybe
import Data.Semigroup
import Data.Semigroup.Option.Instances
import Data.Set (Set)
import qualified Data.Set
import Data.Traversable (traverse)
import Data.Typeable
import Text.Numeral.Roman (toRoman)
import Music.Dynamics (Dynamics)
import Music.Parts.Internal.Data (InstrumentDef)
import qualified Music.Parts.Internal.Data as Data
import Music.Pitch
{-
Instrument is represented either by instrument ID or (more concisely) as GM program number.
The first GM program match in the data table is used.
Instruments not in the MusicXML 3 standard has has ".x." as part of their ID.
-}
-- | An 'Instrument' represents the set of all instruments of a given type.
data Instrument
= StdInstrument Int
| OtherInstrument String
instance Show Instrument where
show x = Data.Maybe.fromMaybe "(unknown)" $ fullName x
-- TODO remove this instrance
instance Enum Instrument where
toEnum = StdInstrument
fromEnum (StdInstrument x) = x
fromEnum (OtherInstrument _) = error "Instrument.fromEnum used on unknown instrument"
instance Eq Instrument where
x == y = soundId x == soundId y
instance Ord Instrument where
compare x y = compare (scoreOrder x) (scoreOrder y)
-- | This instance is quite arbitrary but very handy.
instance Default Instrument where
def = StdInstrument 0
instance ToJSON Instrument where
toJSON (StdInstrument x) = Data.Aeson.object [("midi-instrument", toJSON x)]
toJSON (OtherInstrument x) = Data.Aeson.object [("instrument-id", toJSON x)]
instance FromJSON Instrument where
parseJSON (Data.Aeson.Object v) = do
mi <- v Data.Aeson..:? "midi-instrument"
ii <- v Data.Aeson..:? "instrument-id"
case (mi,ii) of
(Just mi,_) -> return $ fromMidiProgram mi
(Nothing,Just ii) -> return $ fromMusicXmlSoundId ii
_ -> empty
parseJSON _ = empty
-- | Create an instrument from a MIDI program number.
-- Given number should be in the range 0 - 127.
fromMidiProgram :: Int -> Instrument
fromMidiProgram = StdInstrument
-- | Convert an instrument to a MIDI program number.
-- If the given instrument is not representable as a MIDI program, return @Nothing@.
toMidiProgram :: Instrument -> Maybe Int
toMidiProgram = fmap pred . Data.Maybe.listToMaybe . Data._generalMidiProgram . fetchInstrumentDef
-- | Create an instrument from a MusicXML Standard Sound ID.
fromMusicXmlSoundId :: String -> Instrument
fromMusicXmlSoundId = OtherInstrument
-- | Convert an instrument to a MusicXML Standard Sound ID.
-- If the given instrument is not in the MusicXMl standard, return @Nothing@.
toMusicXmlSoundId :: Instrument -> Maybe String
toMusicXmlSoundId = Just . soundId
-- TODO filter everything with .x. in them
soundId :: Instrument -> String
soundId = Data._soundId . fetchInstrumentDef
-- | Clefs allowed for this instrument.
allowedClefs :: Instrument -> Set Clef
allowedClefs = Data.Set.fromList . Data._allowedClefs . fetchInstrumentDef
-- | Standard clef used for this instrument.
standardClef :: Instrument -> Maybe Clef
standardClef = Data.Maybe.listToMaybe . Data._standardClef . fetchInstrumentDef
-- TODO what about multi-staves?
data BracketType = Bracket | Brace | SubBracket
data StaffLayout = Staff Clef | Staves BracketType [StaffLayout]
pianoStaff :: StaffLayout
pianoStaff = Staves Brace [Staff trebleClef, Staff bassClef]
-- | Playable range for this instrument.
playableRange :: Instrument -> Ambitus Pitch
playableRange = Data.Maybe.fromMaybe (error "Missing comfortableRange for instrument") . Data._playableRange . fetchInstrumentDef
-- | Comfortable range for this instrument.
comfortableRange :: Instrument -> Ambitus Pitch
comfortableRange = Data.Maybe.fromMaybe (error "Missing comfortableRange for instrument") . Data._comfortableRange . fetchInstrumentDef
-- playableDynamics :: Instrument -> Pitch -> Dynamics
-- playableDynamics = error "No playableDynamics"
-- instrumentName :: Instrument -> String
-- instrumentName = error "No name"
-- | Full instrument name.
fullName :: Instrument -> Maybe String
-- for now use _sibeliusName if present
fullName x = Data._sibeliusName (fetchInstrumentDef x) `first` Data._longName (fetchInstrumentDef x)
where
first (Just x) _ = Just x
first _ (Just x) = Just x
first Nothing Nothing = Nothing
-- | Instrument name abbrevation.
shortName :: Instrument -> Maybe String
shortName = Data._shortName . fetchInstrumentDef
-- sounding .-. written, i.e. -P5 for horn
-- | Transposition interval.
transposition :: Instrument -> Interval
transposition = Data._transposition . fetchInstrumentDef
where
-- | A string representing transposition such as "Bb" or "F".
transpositionString :: Instrument -> String
transpositionString x = pitchToPCString (c .+^ transposition x)
-- pitch class sounding when c is notated (i.e. F for Horn in F)
-- TODO move
pitchToPCString :: Pitch -> String
pitchToPCString x = show (name x) ++ showA (accidental x)
where
showA 1 = "#"
showA 0 = ""
showA (-1) = "b"
scoreOrder :: Instrument -> Double
scoreOrder = Data._scoreOrder . fetchInstrumentDef
-- internal
fetchInstrumentDef :: Instrument -> InstrumentDef
fetchInstrumentDef (StdInstrument x) = Data.Maybe.fromMaybe (error "Bad instr") $ Data.getInstrumentDefByGeneralMidiProgram (x + 1)
fetchInstrumentDef (OtherInstrument x) = Data.Maybe.fromMaybe (error "Bad instr") $ Data.getInstrumentDefById x
-- Legacy
-- TODO remove
gmClef :: Int -> Int
gmMidiChannel :: Int -> Int
gmScoreOrder :: Int -> Double
gmInstrName :: Int -> Maybe String
gmClef x = Data.Maybe.fromMaybe 0 $ fmap (go . Data._standardClef) $ Data.getInstrumentDefByGeneralMidiProgram (x + 1)
where
go cs | head cs == trebleClef = 0
| head cs == altoClef = 1
| head cs == bassClef = 2
| otherwise = error "gmClef: Unknown clef"
gmScoreOrder x = Data.Maybe.fromMaybe 0 $ fmap (Data._scoreOrder) $ Data.getInstrumentDefByGeneralMidiProgram (x + 1)
gmMidiChannel x = Data.Maybe.fromMaybe 0 $ (=<<) (Data._defaultMidiChannel) $ Data.getInstrumentDefByGeneralMidiProgram (x + 1)
gmInstrName x = (=<<) (Data._longName) $ Data.getInstrumentDefByGeneralMidiProgram (x + 1)
| music-suite/music-parts | src/Music/Parts/Instrument.hs | bsd-3-clause | 7,597 | 0 | 12 | 1,669 | 1,555 | 845 | 710 | 119 | 3 |
module Main2 where
import System.IO
import Data.List
import Data.Char
import Data.Tuple
import CaesarEncode
import CaesarDecode
englishData = [
('A',8.167), ('B',1.492), ('C',2.782), ('D',4.253), ('E',12.702),
('F',2.228), ('G',2.015), ('H',6.094), ('I',6.996), ('J',0.153),
('K',0.772), ('L',4.025), ('M',2.406), ('N',6.749), ('O',7.507),
('P',1.929), ('Q',0.095), ('R',5.987), ('S',6.327), ('T',9.056),
('U',2.758), ('V',0.978), ('W',2.360), ('X',0.150), ('Y',1.974),
('Z',0.074),
('a',8.167), ('b',1.492), ('c',2.782), ('d',4.253), ('e',12.702),
('f',2.228), ('g',2.015), ('h',6.094), ('i',6.996), ('j',0.153),
('k',0.772), ('l',4.025), ('m',2.406), ('n',6.749), ('o',7.507),
('p',1.929), ('q',0.095), ('r',5.987), ('s',6.327), ('t',9.056),
('u',2.758), ('v',0.978), ('w',2.360), ('x',0.150), ('y',1.974),
('z',0.074)
]
main :: IO()
main = do
data1 <- hGetContents =<< openFile "american-english" ReadMode
data2 <- hGetContents =<< openFile "cracklib-small" ReadMode
let bigData = sort $ (words $ map cleaner data1) ++ (words $ map cleaner data2)
raw <-getLine
let raw2 = words $ map cleaner raw
putStrLn (decrypt bigData raw2)
decrypt :: [String] -> [String] -> String
decrypt bigData raw = caesarDecode t2 $ unwords raw
where
t1 = fmax $ matchNumber [0, 1.. 25] bigData raw
where
fmax k = maximum (map fst k)
t2 = sfmax (matchNumber [0, 1.. 25] bigData raw) t1
where
sfmax [] _ = 0
sfmax (x:xs) t1 | fst x == t1 = snd x
| True = sfmax xs t1
matchNumber :: [Int] -> [String] -> [String] -> [(Int,Int)]
matchNumber [] _ _ = []
matchNumber (t:ts) bigData raw = (sum $ map (match t bigData) raw, t) : matchNumber ts bigData raw
match :: Int -> [String] -> String -> Int
match t bigData raw
| decrypted `elem` bigData = 1
| True = 0
where
decrypted = caesarDecode t raw
cleaner :: Char -> Char
cleaner x
| isAlpha x || x=='\'' = x
| True = ' '
| abhinav-mehta/CipherSolver | src/mainVigenere.hs | bsd-3-clause | 2,166 | 10 | 15 | 592 | 1,002 | 587 | 415 | 48 | 2 |
module Main where
import Attestation
import VChanUtil
import Demo3Shared
import TPM
import qualified Data.ByteString.Lazy as L
import System.IO
import Control.Monad
import Control.Monad.Trans
main :: IO ()
main = do
putStrLn "START main of Attestation"
--putStrLn "OPENING CHAN(Server chan for Appraiser)"
apprChan <- server_init appId
measChan <- client_init meaId
priCaChan <- client_init caId
forever $ runAtt attLoop $ AttState checksInit measChan apprChan priCaChan True
putStrLn "CLOSING CHAN"
close apprChan
return ()
attLoop :: Att ()
attLoop = do
liftIO takeInit
mapM_ (attProcess)
(map buildX ( map listUp [0..7]))
--Helper Functions...
checksInit :: [Bool]
checksInit = replicate 7 True
listUp :: Int -> [Int]
listUp x = [x]
buildX :: [Int] -> [Bool]
buildX [] = []
buildX xs = buildX' allTrue xs
where allTrue = replicate numChecks True
numChecks = 7
buildX' :: [Bool] -> [Int] -> [Bool]
buildX' inits xs
| (null xs) = inits
| otherwise = let x = head xs
xs' = tail xs
new = updateFalse x inits in
buildX' new xs'
--One-time use exports...
exportEKBytes :: String -> TPM_PUBKEY -> IO ()
exportEKBytes fileName pubKey = do
let (TPM_STORE_PUBKEY bs) = tpmPubKeyData pubKey
L.writeFile fileName bs
exportEK :: String -> TPM_PUBKEY -> IO () --One-time use func to export pubEK
exportEK fileName pubKey = do
handle <- openFile fileName WriteMode
hPutStrLn handle $ show pubKey
hClose handle
--pubEk <- takeInit
--putStrLn $ show pubEk
--let fileName = "pubEkBytes.txt"
--exportEKBytes fileName pubEk
--exportEK exportEKFileName pubEk --Export pubEk (for now, manually transmit)
--putStrLn "tpm ownership taken"
--chan <- server_init appId
--Attester errors: tpm_fail after ~13,500 iterations
--Appraiser errors:
--Appraiser: signature representative out of range (Only happens when we use a signing key(not identity key) to produce the fake quote signature. Does not appear to cause problems when the other key is an identity key, and doesn't cause problems if we sign the QUOTE_INFO completely outside of the tpm.)
{-VChan errors: (Note, all vchan errors eliminated when we keep the same channel open between seperate runs of the protocol. Still need a more robust way to initiate communication, and to maintain(or re-connect) communication between seperate runs.)
1) transmitChan: vchan init for xs=/local/domain/19/data/serverVchan_20 to domId=20,
vchan to serverExp1 write: Invalid argument
2) Error: Too many open files: libxenvchan_client_init: domId=21, xsPath=/local/domain/21/data/serverVchan_19.
3) transmitChan: vchan init for xs=/local/domain/22/data/serverVchan_19 to domId=19,
Error: Interrupted system call: libxenvchan_client_init: domId=22, xsPath=/local/domain/22/data/serverVchan_19.
4) vchan to serverExp1 write: Inappropriate ioctl for device
-}
| armoredsoftware/protocol | tpm/mainline/attestation/AttestationMain.hs | bsd-3-clause | 2,950 | 6 | 13 | 572 | 502 | 257 | 245 | 49 | 1 |
module Lib.List (filterA, unprefixed, unsuffixed, partitionA) where
import Data.List (isPrefixOf, isSuffixOf)
import Prelude.Compat
filterA :: Applicative f => (a -> f Bool) -> [a] -> f [a]
filterA p = go
where
go [] = pure []
go (x:xs) = combine <$> p x <*> go xs
where
combine True rest = x : rest
combine False rest = rest
partitionA :: Applicative f => (a -> f Bool) -> [a] -> f ([a], [a])
partitionA p =
fmap mconcat . traverse onEach
where
onEach x = partitionOne x <$> p x
partitionOne x True = ([x], [])
partitionOne x False = ([], [x])
unprefixed :: Eq a => [a] -> [a] -> Maybe [a]
unprefixed prefix full
| prefix `isPrefixOf` full = Just $ drop (length prefix) full
| otherwise = Nothing
unsuffixed :: Eq a => [a] -> [a] -> Maybe [a]
unsuffixed suffix full
| suffix `isSuffixOf` full = Just $ take (length full - length suffix) full
| otherwise = Nothing
| buildsome/buildsome | src/Lib/List.hs | gpl-2.0 | 929 | 0 | 10 | 229 | 448 | 231 | 217 | 23 | 3 |
module Haddock.Utf8Spec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Haddock.Utf8
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "decodeUtf8" $ do
it "is inverse to encodeUtf8" $ do
property $ \xs -> (decodeUtf8 . encodeUtf8) xs `shouldBe` xs
| jwiegley/ghc-release | utils/haddock/test/Haddock/Utf8Spec.hs | gpl-3.0 | 328 | 0 | 18 | 92 | 105 | 56 | 49 | 11 | 1 |
{-# LANGUAGE OverloadedStrings, GADTs, ScopedTypeVariables #-}
{-|
Description: Generate a new SVG file from the database graph representation.
This module is responsible for taking the database representation of a graph
and creating a new SVG file.
This functionality is used both to create SVG for the Graph component,
as well as generating images on the fly for Facebook posting.
-}
module Svg.Generator
(buildSVG) where
import Svg.Builder
import Database.Tables
import Database.DataType
import Control.Monad.IO.Class (liftIO)
import Database.Persist.Sqlite
import Data.List hiding (map, filter)
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import Text.Blaze.Svg11 ((!))
import qualified Text.Blaze.Svg11 as S
import qualified Text.Blaze.Svg11.Attributes as A
import Text.Blaze.Svg.Renderer.String (renderSvg)
import Text.Blaze.Internal (stringValue)
import Text.Blaze (toMarkup)
import Css.Constants (theoryDark,
seDark,
systemsDark,
hciDark,
graphicsDark,
numDark,
aiDark,
introDark,
mathDark,
nodeFontSize,
hybridFontSize,
boolFontSize,
regionFontSize)
import qualified Data.Map.Strict as M
import Data.Monoid (mempty, mappend, mconcat)
import Config (databasePath)
-- | This is the main function that retrieves a stored graph
-- from the database and creates a new SVG file for it.
buildSVG :: GraphId -- ^ The ID of the graph that is being built.
-> M.Map String String -- ^ A map of courses that holds the course
-- ID as a key, and the data-active
-- attribute as the course's value.
-- The data-active attribute is used in the
-- interactive graph to indicate which
-- courses the user has selected.
-> String -- ^ The filename that this graph will be
-- written to.
-> Bool -- ^ Whether to include inline styles.
-> IO ()
buildSVG gId courseMap filename styled =
runSqlite databasePath $ do
sqlRects :: [Entity Shape] <- selectList
[ShapeType_ <-. [Node, Hybrid],
ShapeGraph ==. gId] []
sqlTexts :: [Entity Text] <- selectList [TextGraph ==. gId] []
sqlPaths :: [Entity Path] <- selectList [PathGraph ==. gId] []
sqlEllipses :: [Entity Shape] <- selectList
[ShapeType_ ==. BoolNode,
ShapeGraph ==. gId] []
sqlGraph :: [Entity Graph] <- selectList [GraphId ==. gId] []
let courseStyleMap = M.map convertSelectionToStyle courseMap
texts = map entityVal sqlTexts
-- TODO: Ideally, we would do these "build" steps *before*
-- inserting these values into the database.
rects = zipWith (buildRect texts)
(map entityVal sqlRects)
(map keyAsInt sqlRects)
ellipses = zipWith (buildEllipses texts)
(map entityVal sqlEllipses)
(map keyAsInt sqlEllipses)
paths = zipWith (buildPath rects ellipses)
(map entityVal sqlPaths)
(map keyAsInt sqlPaths)
regions = filter pathIsRegion paths
edges = filter (not . pathIsRegion) paths
regionTexts = filter (not .
intersectsWithShape (rects ++ ellipses))
texts
width = graphWidth $ entityVal (head sqlGraph)
height = graphHeight $ entityVal (head sqlGraph)
stringSVG = renderSvg $ makeSVGDoc courseStyleMap
rects
ellipses
edges
regions
regionTexts
styled
width
height
liftIO $ writeFile filename stringSVG
where
keyAsInt :: PersistEntity a => Entity a -> Integer
keyAsInt = fromIntegral . (\(PersistInt64 x) -> x) . head . keyToValues . entityKey
convertSelectionToStyle :: String -> String
convertSelectionToStyle courseStatus =
if isSelected courseStatus
then "stroke-width:4;"
else "opacity:0.5;stroke-dasharray:8,5;"
isSelected :: String -> Bool
isSelected courseStatus =
isPrefixOf "active" courseStatus ||
isPrefixOf "overridden" courseStatus
-- * SVG Creation
-- | This function does the heavy lifting to actually create
-- a new SVG value given the graph components.
makeSVGDoc :: M.Map String String
-> [Shape] -- ^ A list of the Nodes that will be included
-- in the graph. This includes both Hybrids and
-- course nodes.
-> [Shape] -- ^ A list of the Ellipses that will be included
-- in the graph.
-> [Path] -- ^ A list of the Edges that will be included
-- in the graph.
-> [Path] -- ^ A list of the Regions that will be included
-- in the graph.
-> [Text] -- ^ A list of the 'Text' elements that will be included
-- in the graph.
-> Bool -- ^ Whether to include inline styles in the graph.
-> Double -- ^ The width dimension of the graph.
-> Double -- ^ The height dimension of the graph.
-> S.Svg -- ^ The completed SVG document.
makeSVGDoc courseMap rects ellipses edges regions regionTexts styled width height =
S.docTypeSvg ! A.width "100%"
! A.height "100%"
! A.preserveaspectratio "xMinYMin"
! A.viewbox (stringValue $ "0 0 " ++ (show width) ++ " " ++ (show height))
! S.customAttribute "xmlns:svg" "http://www.w3.org/2000/svg"
! S.customAttribute "xmlns:dc" "http://purl.org/dc/elements/1.1/"
! S.customAttribute "xmlns:cc" "http://creativecommons.org/ns#"
! S.customAttribute "xmlns:rdf"
"http://www.w3.org/1999/02/22-rdf-syntax-ns#"
! A.version "1.1" $ do
makeSVGDefs
S.g ! A.id_ "regions" $
sequence_ $ map (regionToSVG styled)
regions
S.g ! A.id_ "nodes"
! A.stroke "black" $
sequence_ $ map (rectToSVG styled courseMap)
rects
S.g ! A.id_ "bools" $
sequence_ $ map (ellipseToSVG styled)
ellipses
S.g ! A.id_ "edges"
! A.stroke "black" $
sequence_ $ map (edgeToSVG styled)
edges
S.g ! A.id_ "region-labels" $
sequence_ $ map (textToSVG styled Region 0)
regionTexts
-- | Builds the SVG defs. Currently, we only use a single one, for the arrowheads.
makeSVGDefs :: S.Svg
makeSVGDefs =
S.defs $
S.marker ! A.id_ "arrow"
! A.viewbox "0 0 10 10"
! A.refx "4"
! A.refy "5"
! A.markerunits "strokeWidth"
! A.orient "auto"
! A.markerwidth "7"
! A.markerheight "7" $
S.polyline ! A.points "0,1 10,5 0,9"
! A.fill "black"
-- | Converts a node to SVG.
rectToSVG :: Bool -> M.Map String String -> Shape -> S.Svg
rectToSVG styled courseMap rect
| shapeFill rect == "none" = S.rect
| otherwise =
let style = case shapeType_ rect of
Node -> fromMaybe "" $ M.lookup (shapeId_ rect)
courseMap
_ -> ""
class_ = case shapeType_ rect of
Node -> "node"
Hybrid -> "hybrid"
in S.g ! A.id_ (stringValue $ sanitizeId $ shapeId_ rect)
! A.class_ (stringValue class_)
! S.customAttribute "data-group" (stringValue
(getArea (shapeId_ rect)))
! S.customAttribute "text-rendering" "geometricPrecision"
! S.customAttribute "shape-rendering" "geometricPrecision"
-- TODO: Remove the reliance on the colours here
! (if styled || class_ /= "hybrid"
then
A.style (stringValue style)
else
mempty)
$
do S.rect ! A.rx "4"
! A.ry "4"
! A.x (stringValue . show . fst $ shapePos rect)
! A.y (stringValue . show . snd $ shapePos rect)
! A.width (stringValue . show $ shapeWidth rect)
! A.height (stringValue . show $ shapeHeight rect)
! A.style (stringValue $ "fill:" ++ shapeFill rect ++ ";")
sequence_ $ map
(textToSVG
styled
(shapeType_ rect)
(fst (shapePos rect) + (shapeWidth rect / 2)))
(shapeText rect)
-- | Converts an ellipse to SVG.
ellipseToSVG :: Bool -> Shape -> S.Svg
ellipseToSVG styled ellipse =
S.g ! A.id_ (stringValue (shapeId_ ellipse))
! A.class_ "bool" $ do
S.ellipse ! A.cx (stringValue . show . fst $ shapePos ellipse)
! A.cy (stringValue . show . snd $ shapePos ellipse)
! A.rx (stringValue . show $ shapeWidth ellipse / 2)
! A.ry (stringValue . show $ shapeHeight ellipse / 2)
! if styled
then
A.stroke "black" `mappend`
A.fill "none"
else mempty
sequence_ $ map
(textToSVG styled BoolNode (fst $ shapePos ellipse))
(shapeText ellipse)
-- | Converts a text value to SVG.
textToSVG :: Bool -> ShapeType -> Double -> Text -> S.Svg
textToSVG styled type_ xPos' text =
S.text_ ! A.x (stringValue $ show $
if type_ == Region
then xPos
else xPos')
! A.y (stringValue $ show yPos)
! (if styled then allStyles else baseStyles)
$ toMarkup $ textText text
where
(xPos, yPos) = textPos text
align = case type_ of
Region -> textAlign text
_ -> "middle"
fontSize = case type_ of
Hybrid -> hybridFontSize
BoolNode -> boolFontSize
Region -> regionFontSize
_ -> nodeFontSize
fill =
if type_ == Hybrid
then A.fill "white"
else
if null $ textFill text
then mempty
else A.fill $ stringValue $ textFill text
baseStyles = mconcat
[A.stroke "none",
fill,
A.textAnchor $ stringValue align]
allStyles = mconcat
[A.fontFamily "'Trebuchet MS', 'Arial', sans-serif",
A.fontSize (stringValue $ show fontSize ++ "pt")] `mappend`
baseStyles
-- | Converts a path to SVG.
edgeToSVG :: Bool -> Path -> S.Svg
edgeToSVG styled path =
S.path ! A.id_ (stringValue $ "path" ++ pathId_ path)
! A.class_ "path"
! A.d (stringValue $ 'M' : buildPathString (pathPoints path))
! A.markerEnd "url(#arrow)"
! S.customAttribute "data-source-node" (stringValue $ sanitizeId
$ pathSource path)
! S.customAttribute "data-target-node" (stringValue $ sanitizeId
$ pathTarget path)
! if styled
then
mappend
(A.strokeWidth "2px") $
A.style (stringValue $ "fill:" ++
pathFill path ++
";fill-opacity:1;")
else
mempty
-- | Converts a region to SVG.
regionToSVG :: Bool -> Path -> S.Svg
regionToSVG styled path =
S.path ! A.id_ (stringValue $ "region" ++ pathId_ path)
! A.class_ "region"
! A.d (stringValue $ 'M' : buildPathString (pathPoints path))
! A.style (stringValue $ "fill:" ++ pathFill path ++ ";" ++
if styled
then
";opacity:0.7;fill-opacity:0.58;"
else "")
-- ** Hard-coded map definitions (should be removed, eventually)
-- | Gets a tuple from areaMap where id_ is in the list of courses for that
-- tuple.
getTuple :: String -- ^ The course's ID.
-> Maybe (T.Text, String)
getTuple id_
| M.null tuples = Nothing
| otherwise = Just $ snd $ M.elemAt 0 tuples
where tuples = M.filterWithKey (\k _ -> id_ `elem` k) areaMap
-- | Gets an area from areaMap where id_ is in the list of courses for the
-- corresponding tuple.
getArea :: String -> String
getArea id_ = maybe "" snd $ getTuple id_
-- | A list of tuples that contain disciplines (areas), fill values, and courses
-- that are in the areas.
-- TODO: Remove colour dependencies, and probably the whole map.
areaMap :: M.Map [String] (T.Text, String)
areaMap = M.fromList
[
(["csc165", "csc236", "csc240", "csc263", "csc265",
"csc310", "csc373", "csc438", "csc448",
"csc463"], (theoryDark, "theory")),
(["csc207", "csc301", "csc302", "csc410", "csc465",
"csc324"], (seDark, "se")),
(["csc209", "csc258", "csc358", "csc369", "csc372",
"csc458", "csc469", "csc488", "ece385", "ece489",
"csc309", "csc343", "csc443"],
(systemsDark, "systems")),
(["csc200", "csc300", "csc318", "csc404", "csc428",
"csc454"], (hciDark, "hci")),
(["csc320", "csc418", "csc420"], (graphicsDark, "graphics")),
(["csc336", "csc436", "csc446", "csc456", "csc466"],
(numDark, "num")),
(["csc321", "csc384", "csc401", "csc411", "csc412",
"csc485", "csc486"], (aiDark, "ai")),
(["csc104", "csc120", "csc108", "csc148"], (introDark, "intro")),
(["calc1", "lin1", "sta1", "sta2"], (mathDark, "math"))]
| alexbaluta/courseography | app/Svg/Generator.hs | gpl-3.0 | 15,754 | 0 | 20 | 6,722 | 3,216 | 1,696 | 1,520 | 276 | 9 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Glacier.ListVaults
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation lists all vaults owned by the calling user\'s account.
-- The list returned in the response is ASCII-sorted by vault name.
--
-- By default, this operation returns up to 1,000 items. If there are more
-- vaults to list, the response 'marker' field contains the vault Amazon
-- Resource Name (ARN) at which to continue the list with a new List Vaults
-- request; otherwise, the 'marker' field is 'null'. To return a list of
-- vaults that begins at a specific vault, set the 'marker' request
-- parameter to the vault ARN you obtained from a previous List Vaults
-- request. You can also limit the number of vaults returned in the
-- response by specifying the 'limit' parameter in the request.
--
-- An AWS account has full permission to perform all operations (actions).
-- However, AWS Identity and Access Management (IAM) users don\'t have any
-- permissions by default. You must grant them explicit permission to
-- perform specific actions. For more information, see
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identity and Access Management (IAM)>.
--
-- For conceptual information and underlying REST API, go to
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/retrieving-vault-info.html Retrieving Vault Metadata in Amazon Glacier>
-- and
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-vaults-get.html List Vaults>
-- in the /Amazon Glacier Developer Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-ListVaults.html AWS API Reference> for ListVaults.
module Network.AWS.Glacier.ListVaults
(
-- * Creating a Request
listVaults
, ListVaults
-- * Request Lenses
, lvMarker
, lvLimit
, lvAccountId
-- * Destructuring the Response
, listVaultsResponse
, ListVaultsResponse
-- * Response Lenses
, lvrsMarker
, lvrsVaultList
, lvrsResponseStatus
) where
import Network.AWS.Glacier.Types
import Network.AWS.Glacier.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Provides options to retrieve the vault list owned by the calling user\'s
-- account. The list provides metadata information for each vault.
--
-- /See:/ 'listVaults' smart constructor.
data ListVaults = ListVaults'
{ _lvMarker :: !(Maybe Text)
, _lvLimit :: !(Maybe Text)
, _lvAccountId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListVaults' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lvMarker'
--
-- * 'lvLimit'
--
-- * 'lvAccountId'
listVaults
:: Text -- ^ 'lvAccountId'
-> ListVaults
listVaults pAccountId_ =
ListVaults'
{ _lvMarker = Nothing
, _lvLimit = Nothing
, _lvAccountId = pAccountId_
}
-- | A string used for pagination. The marker specifies the vault ARN after
-- which the listing of vaults should begin.
lvMarker :: Lens' ListVaults (Maybe Text)
lvMarker = lens _lvMarker (\ s a -> s{_lvMarker = a});
-- | The maximum number of items returned in the response. If you don\'t
-- specify a value, the List Vaults operation returns up to 1,000 items.
lvLimit :: Lens' ListVaults (Maybe Text)
lvLimit = lens _lvLimit (\ s a -> s{_lvLimit = a});
-- | The 'AccountId' value is the AWS account ID. This value must match the
-- AWS account ID associated with the credentials used to sign the request.
-- You can either specify an AWS account ID or optionally a single
-- apos'-'apos (hyphen), in which case Amazon Glacier uses the AWS account
-- ID associated with the credentials used to sign the request. If you
-- specify your account ID, do not include any hyphens (apos-apos) in the
-- ID.
lvAccountId :: Lens' ListVaults Text
lvAccountId = lens _lvAccountId (\ s a -> s{_lvAccountId = a});
instance AWSRequest ListVaults where
type Rs ListVaults = ListVaultsResponse
request = get glacier
response
= receiveJSON
(\ s h x ->
ListVaultsResponse' <$>
(x .?> "Marker") <*> (x .?> "VaultList" .!@ mempty)
<*> (pure (fromEnum s)))
instance ToHeaders ListVaults where
toHeaders = const mempty
instance ToPath ListVaults where
toPath ListVaults'{..}
= mconcat ["/", toBS _lvAccountId, "/vaults"]
instance ToQuery ListVaults where
toQuery ListVaults'{..}
= mconcat
["marker" =: _lvMarker, "limit" =: _lvLimit]
-- | Contains the Amazon Glacier response to your request.
--
-- /See:/ 'listVaultsResponse' smart constructor.
data ListVaultsResponse = ListVaultsResponse'
{ _lvrsMarker :: !(Maybe Text)
, _lvrsVaultList :: !(Maybe [DescribeVaultOutput])
, _lvrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListVaultsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lvrsMarker'
--
-- * 'lvrsVaultList'
--
-- * 'lvrsResponseStatus'
listVaultsResponse
:: Int -- ^ 'lvrsResponseStatus'
-> ListVaultsResponse
listVaultsResponse pResponseStatus_ =
ListVaultsResponse'
{ _lvrsMarker = Nothing
, _lvrsVaultList = Nothing
, _lvrsResponseStatus = pResponseStatus_
}
-- | The vault ARN at which to continue pagination of the results. You use
-- the marker in another List Vaults request to obtain more vaults in the
-- list.
lvrsMarker :: Lens' ListVaultsResponse (Maybe Text)
lvrsMarker = lens _lvrsMarker (\ s a -> s{_lvrsMarker = a});
-- | List of vaults.
lvrsVaultList :: Lens' ListVaultsResponse [DescribeVaultOutput]
lvrsVaultList = lens _lvrsVaultList (\ s a -> s{_lvrsVaultList = a}) . _Default . _Coerce;
-- | The response status code.
lvrsResponseStatus :: Lens' ListVaultsResponse Int
lvrsResponseStatus = lens _lvrsResponseStatus (\ s a -> s{_lvrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-glacier/gen/Network/AWS/Glacier/ListVaults.hs | mpl-2.0 | 6,772 | 0 | 13 | 1,359 | 819 | 499 | 320 | 93 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.OpsWorks.DescribeLoadBasedAutoScaling
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes load-based auto scaling configurations for specified layers.
--
-- You must specify at least one of the parameters.
--
-- Required Permissions: To use this action, an IAM user must have a Show,
-- Deploy, or Manage permissions level for the stack, or an attached policy that
-- explicitly grants permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>.
--
-- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DescribeLoadBasedAutoScaling.html>
module Network.AWS.OpsWorks.DescribeLoadBasedAutoScaling
(
-- * Request
DescribeLoadBasedAutoScaling
-- ** Request constructor
, describeLoadBasedAutoScaling
-- ** Request lenses
, dlbasLayerIds
-- * Response
, DescribeLoadBasedAutoScalingResponse
-- ** Response constructor
, describeLoadBasedAutoScalingResponse
-- ** Response lenses
, dlbasrLoadBasedAutoScalingConfigurations
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
newtype DescribeLoadBasedAutoScaling = DescribeLoadBasedAutoScaling
{ _dlbasLayerIds :: List "LayerIds" Text
} deriving (Eq, Ord, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeLoadBasedAutoScaling where
type Item DescribeLoadBasedAutoScaling = Text
fromList = DescribeLoadBasedAutoScaling . GHC.Exts.fromList
toList = GHC.Exts.toList . _dlbasLayerIds
-- | 'DescribeLoadBasedAutoScaling' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dlbasLayerIds' @::@ ['Text']
--
describeLoadBasedAutoScaling :: DescribeLoadBasedAutoScaling
describeLoadBasedAutoScaling = DescribeLoadBasedAutoScaling
{ _dlbasLayerIds = mempty
}
-- | An array of layer IDs.
dlbasLayerIds :: Lens' DescribeLoadBasedAutoScaling [Text]
dlbasLayerIds = lens _dlbasLayerIds (\s a -> s { _dlbasLayerIds = a }) . _List
newtype DescribeLoadBasedAutoScalingResponse = DescribeLoadBasedAutoScalingResponse
{ _dlbasrLoadBasedAutoScalingConfigurations :: List "LoadBasedAutoScalingConfigurations" LoadBasedAutoScalingConfiguration
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeLoadBasedAutoScalingResponse where
type Item DescribeLoadBasedAutoScalingResponse = LoadBasedAutoScalingConfiguration
fromList = DescribeLoadBasedAutoScalingResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _dlbasrLoadBasedAutoScalingConfigurations
-- | 'DescribeLoadBasedAutoScalingResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dlbasrLoadBasedAutoScalingConfigurations' @::@ ['LoadBasedAutoScalingConfiguration']
--
describeLoadBasedAutoScalingResponse :: DescribeLoadBasedAutoScalingResponse
describeLoadBasedAutoScalingResponse = DescribeLoadBasedAutoScalingResponse
{ _dlbasrLoadBasedAutoScalingConfigurations = mempty
}
-- | An array of 'LoadBasedAutoScalingConfiguration' objects that describe each
-- layer's configuration.
dlbasrLoadBasedAutoScalingConfigurations :: Lens' DescribeLoadBasedAutoScalingResponse [LoadBasedAutoScalingConfiguration]
dlbasrLoadBasedAutoScalingConfigurations =
lens _dlbasrLoadBasedAutoScalingConfigurations
(\s a -> s { _dlbasrLoadBasedAutoScalingConfigurations = a })
. _List
instance ToPath DescribeLoadBasedAutoScaling where
toPath = const "/"
instance ToQuery DescribeLoadBasedAutoScaling where
toQuery = const mempty
instance ToHeaders DescribeLoadBasedAutoScaling
instance ToJSON DescribeLoadBasedAutoScaling where
toJSON DescribeLoadBasedAutoScaling{..} = object
[ "LayerIds" .= _dlbasLayerIds
]
instance AWSRequest DescribeLoadBasedAutoScaling where
type Sv DescribeLoadBasedAutoScaling = OpsWorks
type Rs DescribeLoadBasedAutoScaling = DescribeLoadBasedAutoScalingResponse
request = post "DescribeLoadBasedAutoScaling"
response = jsonResponse
instance FromJSON DescribeLoadBasedAutoScalingResponse where
parseJSON = withObject "DescribeLoadBasedAutoScalingResponse" $ \o -> DescribeLoadBasedAutoScalingResponse
<$> o .:? "LoadBasedAutoScalingConfigurations" .!= mempty
| romanb/amazonka | amazonka-opsworks/gen/Network/AWS/OpsWorks/DescribeLoadBasedAutoScaling.hs | mpl-2.0 | 5,382 | 0 | 10 | 888 | 563 | 340 | 223 | 66 | 1 |
module RecursiveRef where
{-# ANN module "HLint: ignore Eta reduce" #-}
recNoSig x = recNoSig x
dummy = localRecNoSig
where
localRecNoSig x = localRecNoSig x
recWithSig :: a -> a
recWithSig x = recWithSig x
mutualNoSigA = mutualNoSigB
mutualNoSigB = mutualNoSigA
etaNoSig = etaNoSig
| robinp/haskell-indexer | haskell-indexer-backend-ghc/testdata/basic/RecursiveRef.hs | apache-2.0 | 294 | 0 | 7 | 55 | 69 | 37 | 32 | 10 | 1 |
{-# LANGUAGE RecordWildCards, ScopedTypeVariables, BangPatterns, CPP #-}
--
-- | Interacting with the interpreter, whether it is running on an
-- external process or in the current process.
--
module Eta.REPL
( -- * High-level interface to the interpreter
evalStmt, EvalStatus_(..), EvalStatus, EvalResult(..), EvalExpr(..)
, evalIO
, evalString
, evalStringToIOString
-- * The classloader linker
, addDynamicClassPath
, addModuleClassPath
, loadClasses
, newInstance
, resetClasses
, setClassInfoPath
, getClassInfo
-- * Lower-level API using messages
, iservCmd, Message(..), withIServ, stopIServ
, iservCall, readIServ, writeIServ
, freeHValueRefs
, mkFinalizedHValue
, wormhole, wormholeRef
, mkEvalOpts
, fromEvalResult
) where
import Eta.REPL.Message
import Eta.REPL.ClassInfo
import Eta.REPL.RemoteTypes
import Eta.Main.HscTypes
import Eta.Utils.UniqFM
import Eta.Utils.Panic
import Eta.Main.DynFlags
import Eta.Main.ErrUtils
import Eta.Utils.Outputable
import Eta.Utils.Exception
import Eta.Utils.Digraph
import Eta.Main.Hooks
import Control.Concurrent
import Control.DeepSeq
import Control.Monad
import Control.Monad.IO.Class
import Data.Binary
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.IORef
import System.Exit
import Data.Maybe
import Data.List
import System.FilePath
import System.Directory
import System.Process
import System.IO
{- Note [Remote Eta REPL]
When the flag -fexternal-interpreter is given to GHC, interpreted code
is run in a separate process called iserv, and we communicate with the
external process over a pipe using Binary-encoded messages.
Motivation
~~~~~~~~~~
When the interpreted code is running in a separate process, it can
use a different "way", e.g. profiled or dynamic. This means
- compiling Template Haskell code with -prof does not require
building the code without -prof first
- when GHC itself is profiled, it can interpret unprofiled code,
and the same applies to dynamic linking.
- An unprofiled GHCi can load and run profiled code, which means it
can use the stack-trace functionality provided by profiling without
taking the performance hit on the compiler that profiling would
entail.
For other reasons see RemoteGHCi on the wiki.
Implementation Overview
~~~~~~~~~~~~~~~~~~~~~~~
The main pieces are:
- libraries/ghci, containing:
- types for talking about remote values (GHCi.RemoteTypes)
- the message protocol (GHCi.Message),
- implementation of the messages (GHCi.Run)
- implementation of Template Haskell (GHCi.TH)
- a few other things needed to run interpreted code
- top-level iserv directory, containing the codefor the external
server. This is a fairly simple wrapper, most of the functionality
is provided by modules in libraries/ghci.
- This module (GHCi) which provides the interface to the server used
by the rest of GHC.
GHC works with and without -fexternal-interpreter. With the flag, all
interpreted code is run by the iserv binary. Without the flag,
interpreted code is run in the same process as GHC.
Things that do not work with -fexternal-interpreter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
dynCompileExpr cannot work, because we have no way to run code of an
unknown type in the remote process. This API fails with an error
message if it is used with -fexternal-interpreter.
Other Notes on Remote Eta REPL
~~~~~~~~~~~~~~~~~~~~~~~~~~
* This wiki page has an implementation overview:
https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/ExternalInterpreter
* Note [External GHCi pointers] in compiler/ghci/GHCi.hs
* Note [Remote Template Haskell] in libraries/ghci/GHCi/TH.hs
-}
needExtInt :: IO a
needExtInt = throwIO
(InstallationError "this operation requires -fexternal-interpreter")
-- | Run a command in the interpreter's context. With
-- @-fexternal-interpreter@, the command is serialized and sent to an
-- external iserv process, and the response is deserialized (hence the
-- @Binary@ constraint). With @-fno-external-interpreter@ we execute
-- the command directly here.
iservCmd :: Binary a => HscEnv -> Message a -> IO a
iservCmd hsc_env@HscEnv{..} msg
| gopt Opt_ExternalInterpreter hsc_dflags =
withIServ hsc_env $ \iserv ->
uninterruptibleMask_ $ do -- Note [uninterruptibleMask_]
iservCall iserv msg
| otherwise = needExtInt
-- Note [uninterruptibleMask_ and iservCmd]
--
-- If we receive an async exception, such as ^C, while communicating
-- with the iserv process then we will be out-of-sync and not be able
-- to recoever. Thus we use uninterruptibleMask_ during
-- communication. A ^C will be delivered to the iserv process (because
-- signals get sent to the whole process group) which will interrupt
-- the running computation and return an EvalException result.
-- | Grab a lock on the 'IServ' and do something with it.
-- Overloaded because this is used from TcM as well as IO.
withIServ
:: (MonadIO m, ExceptionMonad m)
=> HscEnv -> (IServ -> m a) -> m a
withIServ HscEnv{..} action =
gmask $ \restore -> do
m <- liftIO $ takeMVar hsc_iserv
-- start the iserv process if we haven't done so yet
iserv <- maybe (liftIO $ startIServ hsc_dflags) return m
`gonException` (liftIO $ putMVar hsc_iserv Nothing)
-- free any ForeignHValues that have been garbage collected.
let iserv' = iserv{ iservPendingFrees = [] }
a <- (do
liftIO $ when (not (null (iservPendingFrees iserv))) $
iservCall iserv (FreeHValueRefs (iservPendingFrees iserv))
-- run the inner action
restore $ action iserv)
`gonException` (liftIO $ putMVar hsc_iserv (Just iserv'))
liftIO $ putMVar hsc_iserv (Just iserv')
return a
-- -----------------------------------------------------------------------------
-- Wrappers around messages
-- | Execute an action of type @IO [a]@, returning 'ForeignHValue's for
-- each of the results.
evalStmt
:: HscEnv -> Bool -> EvalExpr ForeignHValue
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
evalStmt hsc_env step foreign_expr = do
let dflags = hsc_dflags hsc_env
status <- withExpr foreign_expr $ \expr ->
iservCmd hsc_env (EvalStmt (mkEvalOpts dflags step) expr)
handleEvalStatus hsc_env status
where
withExpr :: EvalExpr ForeignHValue -> (EvalExpr HValueRef -> IO a) -> IO a
withExpr (EvalThis fhv) cont =
withForeignRef fhv $ \hvref -> cont (EvalThis hvref)
withExpr (EvalApp fl fr) cont =
withExpr fl $ \fl' ->
withExpr fr $ \fr' ->
cont (EvalApp fl' fr')
handleEvalStatus
:: HscEnv -> EvalStatus [HValueRef]
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
handleEvalStatus hsc_env status =
case status of
EvalBreak a b c d e -> return (EvalBreak a b c d e)
EvalComplete alloc res ->
EvalComplete alloc <$> addFinalizer res
where
addFinalizer (EvalException bytes e) = do
printBytes bytes
return (EvalException bytes e)
addFinalizer (EvalSuccess bytes rs) = do
printBytes bytes
EvalSuccess bytes <$> mapM (mkFinalizedHValue hsc_env) rs
printBytes :: ByteString -> IO ()
printBytes bytes = do
B.putStr bytes
hFlush stdout
-- | Execute an action of type @IO ()@
evalIO :: HscEnv -> ForeignHValue -> IO ()
evalIO hsc_env fhv = do
liftIO $ withForeignRef fhv $ \fhv ->
iservCmd hsc_env (EvalIO fhv) >>= fromEvalResult
-- | Execute an action of type @IO String@
evalString :: HscEnv -> ForeignHValue -> IO String
evalString hsc_env fhv = do
liftIO $ withForeignRef fhv $ \fhv ->
iservCmd hsc_env (EvalString fhv) >>= fromEvalResult
-- | Execute an action of type @String -> IO String@
evalStringToIOString :: HscEnv -> ForeignHValue -> String -> IO String
evalStringToIOString hsc_env fhv str = do
liftIO $ withForeignRef fhv $ \fhv ->
iservCmd hsc_env (EvalStringToString fhv str) >>= fromEvalResult
loadClasses :: HscEnv -> [(String, String, ByteString)] -> IO ()
loadClasses hsc_env classes = when (not (null classes)) $ do
dumpClassesIfSet hsc_env classes
let dflags = hsc_dflags hsc_env
components = stronglyConnCompFromEdgedVertices [ ((a, c), a, [b]) | (a, b, c) <- classes]
f (AcyclicSCC c) = c
f (CyclicSCC cs) = panic $ "loadClasses: Found impossible set of cyclic classes: "
++ show (map (\(a,_) -> a) cs)
classes' = map f components
classesNames = map fst classes'
debugTraceMsg dflags 3 $ text ( "Loading classes: " ++ (show classesNames))
iservCmd hsc_env (LoadClasses classesNames (map snd classes'))
dumpClassesIfSet :: HscEnv -> [(String, String, ByteString)] -> IO ()
dumpClassesIfSet hsc_env classes =
when (dopt Opt_D_dump_interpreted_classes dflags) $ do
let clsPaths = map (\(a,_,c) -> (toClassFilePath a, c)) classes
forM_ clsPaths $ \(p, c) -> do
createDirectoryIfMissing True (takeDirectory p)
B.writeFile p c
where dflags = hsc_dflags hsc_env
dump = fromMaybe "." (dumpDir dflags)
toClassFilePath c = dump </> "interpreted" </> c <.> ".class"
newInstance :: HscEnv -> String -> String -> IO HValueRef
newInstance hsc_env className methodName = iservCmd hsc_env (NewInstance className methodName)
resetClasses :: HscEnv -> IO ()
resetClasses hsc_env = iservCmd hsc_env ResetClasses
addDynamicClassPath :: HscEnv -> [FilePath] -> IO ()
addDynamicClassPath hsc_env cp = do
debugTraceMsg (hsc_dflags hsc_env) 3 $ text ( "Adding dynamic classpath: " ++ (show cp) )
iservCmd hsc_env (AddDynamicClassPath cp)
addModuleClassPath :: HscEnv -> [FilePath] -> IO ()
addModuleClassPath hsc_env cp = do
debugTraceMsg (hsc_dflags hsc_env) 3 $ text ( "Adding module classpath: " ++ (show cp) )
when (not (null cp)) $
iservCmd hsc_env (AddModuleClassPath cp)
setClassInfoPath :: HscEnv -> [FilePath] -> IO ()
setClassInfoPath hsc_env cp = do
debugTraceMsg (hsc_dflags hsc_env) 3 $ text ( "Setting class info path: " ++ (show cp) )
when (not (null cp)) $
iservCmd hsc_env (SetClassInfoPath cp)
getClassInfo :: HscEnv -> [FilePath] -> IO [String]
getClassInfo hsc_env cp = do
cp <- findInClassIndex hsc_env cp
if null cp
then return []
else do
jresult <- iservCmd hsc_env (GetClassInfo cp)
let (notFounds, classInfos) = handleJResult jresult
addToClassIndex hsc_env classInfos
return notFounds
handleJResult :: JResult ([String], [PreClassInfo]) -> ([String], [PreClassInfo])
handleJResult (JDone x) = x
handleJResult (JException msg) =
throw (InstallationError ("While in operation 'handleJResult':\nException: " ++ msg))
-- -----------------------------------------------------------------------------
-- Raw calls and messages
-- | Send a 'Message' and receive the response from the iserv process
iservCall :: Binary a => IServ -> Message a -> IO a
iservCall iserv@IServ{..} msg =
remoteCall iservPipe msg
`catch` \(e :: SomeException) -> handleIServFailure iserv "Call" e
-- | Read a value from the iserv process
readIServ :: IServ -> Get a -> IO a
readIServ iserv@IServ{..} get =
readPipe iservPipe get
`catch` \(e :: SomeException) -> handleIServFailure iserv "Read" e
-- | Send a value to the iserv process
writeIServ :: IServ -> Put -> IO ()
writeIServ iserv@IServ{..} put =
writePipe iservPipe put
`catch` \(e :: SomeException) -> handleIServFailure iserv "Write" e
handleIServFailure :: IServ -> String -> SomeException -> IO a
handleIServFailure IServ{..} op e = do
ex <- getProcessExitCode iservProcess
case ex of
Just (ExitFailure n) -> do
errorContents <- maybe (return "") hGetContents iservErrors
res <- evaluate (force errorContents)
throw (InstallationError ("While in operation " ++ op
++ ":\nException: " ++ show e
++ "\neta-serv terminated (" ++ show n ++ ")\n" ++ res))
_ | Just (MessageParseFailure msg left off) <- fromException e -> do
errorContents <- maybe (return "") hGetContents iservErrors
res <- evaluate (force errorContents)
throw (InstallationError ("While in operation " ++ op
++ ":\nFailed to parse: " ++ msg
++ "\nRemaining: " ++ left
++ "\nOffset: " ++ show off ++ "\n" ++ res))
| otherwise -> do
{- TODO: When debugging JVM exit code 143's
putStrLn $ "TERMINATING PROCESS:\nSomeException: " ++ show e
++ "\nProcess Exit Code: " ++ show ex -}
terminateProcess iservProcess
_ <- waitForProcess iservProcess
throw e
-- -----------------------------------------------------------------------------
-- Starting and stopping the iserv process
startIServ :: DynFlags -> IO IServ
startIServ dflags = do
let prog = pgm_i dflags
opts = getOpts dflags opt_i
(javaProg, defaultJavaOpts) = pgm_java dflags
javaOpts = getOpts dflags opt_java
realProg = javaProg
realOpts = defaultJavaOpts ++ javaOpts ++ ["-jar", prog] ++ opts
debugTraceMsg dflags 3 $ text "Starting " <>
text (realProg ++ " " ++ intercalate " " realOpts)
let createProc = lookupHook createIservProcessHook
(\cp -> do { (mstdin,mstdout,mstderr,ph) <- createProcess cp
; return (mstdin, mstdout, mstderr, ph) })
dflags
(ph, rh, wh, errh) <- runWithPipes dflags createProc realProg realOpts
hSetEncoding rh latin1
hSetEncoding wh latin1
lo_ref <- newIORef Nothing
cache_ref <- newIORef emptyUFM
return $ IServ
{ iservPipe = Pipe { pipeRead = rh
, pipeWrite = wh
, pipeLeftovers = lo_ref }
, iservProcess = ph
, iservErrors = errh
, iservLookupSymbolCache = cache_ref
, iservPendingFrees = []
}
stopIServ :: HscEnv -> IO ()
stopIServ HscEnv{..} =
gmask $ \_restore -> do
m <- takeMVar hsc_iserv
maybe (return ()) stop m
putMVar hsc_iserv Nothing
where
stop iserv = do
ex <- getProcessExitCode (iservProcess iserv)
if isJust ex
then return ()
else iservCall iserv Shutdown
runWithPipes :: DynFlags
-> (CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle))
-> FilePath -> [String] -> IO (ProcessHandle, Handle, Handle,
Maybe Handle)
runWithPipes dflags createProc prog opts = do
(mstdin, mstdout, mstderr, ph) <-
createProc (proc prog opts) {
std_in = CreatePipe,
std_out = CreatePipe,
std_err = if verbosity dflags > 2 then Inherit else CreatePipe
}
return (ph, fromJust mstdout, fromJust mstdin, mstderr)
-- -----------------------------------------------------------------------------
{- Note [External Eta REPL References]
We have the following ways to reference things in GHCi:
HValue
------
HValue is a direct reference to a value in the local heap. Obviously
we cannot use this to refer to things in the external process.
RemoteRef
---------
RemoteRef is a StablePtr to a heap-resident value. When
-fexternal-interpreter is used, this value resides in the external
process's heap. RemoteRefs are mostly used to send pointers in
messages between GHC and iserv.
A RemoteRef must be explicitly freed when no longer required, using
freeHValueRefs, or by attaching a finalizer with mkForeignHValue.
To get from a RemoteRef to an HValue you can use 'wormholeRef', which
fails with an error message if -fexternal-interpreter is in use.
ForeignRef
----------
A ForeignRef is a RemoteRef with a finalizer that will free the
'RemoteRef' when it is garbage collected. We mostly use ForeignHValue
on the GHC side.
The finalizer adds the RemoteRef to the iservPendingFrees list in the
IServ record. The next call to iservCmd will free any RemoteRefs in
the list. It was done this way rather than calling iservCmd directly,
because I didn't want to have arbitrary threads calling iservCmd. In
principle it would probably be ok, but it seems less hairy this way.
-}
-- | Creates a 'ForeignRef' that will automatically release the
-- 'RemoteRef' when it is no longer referenced.
mkFinalizedHValue :: HscEnv -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue HscEnv{..} rref = mkForeignRef rref free
where
!external = gopt Opt_ExternalInterpreter hsc_dflags
hvref = toHValueRef rref
free :: IO ()
free
| not external = panic "Eta does not support an internal compiler."
| otherwise =
modifyMVar_ hsc_iserv $ \mb_iserv ->
case mb_iserv of
Nothing -> return Nothing -- already shut down
Just iserv@IServ{..} ->
return (Just iserv{iservPendingFrees = hvref : iservPendingFrees})
freeHValueRefs :: HscEnv -> [HValueRef] -> IO ()
freeHValueRefs _ [] = return ()
freeHValueRefs hsc_env refs = iservCmd hsc_env (FreeHValueRefs refs)
-- | Convert a 'ForeignRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
wormhole :: DynFlags -> ForeignRef a -> IO a
wormhole dflags r = wormholeRef dflags (unsafeForeignRefToRemoteRef r)
-- | Convert an 'RemoteRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
wormholeRef :: DynFlags -> RemoteRef a -> IO a
wormholeRef dflags _r
| gopt Opt_ExternalInterpreter dflags
= throwIO (InstallationError
"this operation requires -fno-external-interpreter")
| otherwise
= throwIO (InstallationError
"can't wormhole a value in the Eta compiler right now")
-- -----------------------------------------------------------------------------
-- Misc utils
mkEvalOpts :: DynFlags -> Bool -> EvalOpts
mkEvalOpts dflags step =
EvalOpts
{ useSandboxThread = gopt Opt_GhciSandbox dflags
, singleStep = step
, breakOnException = gopt Opt_BreakOnException dflags
, breakOnError = gopt Opt_BreakOnError dflags }
fromEvalResult :: EvalResult a -> IO a
fromEvalResult (EvalException bytes e) = do
printBytes bytes
throwIO (fromSerializableException e)
fromEvalResult (EvalSuccess bytes a) = do
printBytes bytes
return a
| rahulmutt/ghcvm | compiler/Eta/REPL.hs | bsd-3-clause | 18,381 | 0 | 25 | 3,836 | 3,937 | 2,004 | 1,933 | 295 | 3 |
module Test006 where
import qualified Data.Text as T
import Kask.Print
import Prelude hiding (print)
test1 :: String
test1 = strCat ["aaa", "bbb", "ccc"]
test2 :: ShowS
test2 = strCat [showString "aaa", showString "bbb", showString "ccc"]
test3 :: T.Text
test3 = strCat ["aaa", "bbb", "ccc"]
test :: IO ()
test = do
printLn test1
printLn test2
printLn test3
| kongra/kask-base | app/Test006.hs | bsd-3-clause | 369 | 0 | 7 | 68 | 136 | 75 | 61 | 15 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Fog
-- Copyright : (c) Sven Panne 2002-2013
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- This module corresponds to section 3.10 (Fog) of the OpenGL 2.1 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Fog (
fog,
FogMode(..), fogMode,
fogColor, fogIndex,
FogCoordSrc(..), fogCoordSrc,
FogDistanceMode(..), fogDistanceMode
) where
import Foreign.Marshal.Utils
import Foreign.Ptr
import Graphics.Rendering.OpenGL.GL.StateVar
import Graphics.Rendering.OpenGL.GL.Capability
import Graphics.Rendering.OpenGL.GL.QueryUtils
import Graphics.Rendering.OpenGL.GL.VertexSpec
import Graphics.Rendering.OpenGL.Raw
--------------------------------------------------------------------------------
fog :: StateVar Capability
fog = makeCapability CapFog
--------------------------------------------------------------------------------
data FogParameter =
FogIndex
| FogDensity
| FogStart
| FogEnd
| FogMode
| FogColor
| FogCoordSrc
| FogDistanceMode
marshalFogParameter :: FogParameter -> GLenum
marshalFogParameter x = case x of
FogIndex -> gl_FOG_INDEX
FogDensity -> gl_FOG_DENSITY
FogStart -> gl_FOG_START
FogEnd -> gl_FOG_END
FogMode -> gl_FOG_MODE
FogColor -> gl_FOG_COLOR
FogCoordSrc -> gl_FOG_COORD_SRC
-- TODO: Use FOG_DISTANCE_MODE_NV from NV_fog_distance extension
FogDistanceMode -> 0x855a
--------------------------------------------------------------------------------
data FogMode' =
Linear'
| Exp'
| Exp2'
marshalFogMode' :: FogMode' -> GLint
marshalFogMode' x = fromIntegral $ case x of
Linear' -> gl_LINEAR
Exp' -> gl_EXP
Exp2' -> gl_EXP2
unmarshalFogMode' :: GLint -> FogMode'
unmarshalFogMode' x
| y == gl_LINEAR = Linear'
| y == gl_EXP = Exp'
| y == gl_EXP2 = Exp2'
| otherwise = error ("unmarshalFogMode': illegal value " ++ show x)
where y = fromIntegral x
--------------------------------------------------------------------------------
data FogMode =
Linear GLfloat GLfloat
| Exp GLfloat
| Exp2 GLfloat
deriving ( Eq, Ord, Show )
--------------------------------------------------------------------------------
fogMode :: StateVar FogMode
fogMode = makeStateVar getFogMode setFogMode
getFogMode :: IO FogMode
getFogMode = do
mode <- getInteger1 unmarshalFogMode' GetFogMode
case mode of
Linear' -> do
start <- getFloat1 id GetFogStart
end <- getFloat1 id GetFogEnd
return $ Linear start end
Exp' -> getFloat1 Exp GetFogDensity
Exp2' -> getFloat1 Exp2 GetFogDensity
setFogMode :: FogMode -> IO ()
setFogMode (Linear start end) = do
fogi FogMode (marshalFogMode' Linear')
fogf FogStart start
fogf FogEnd end
setFogMode (Exp density) = do
fogi FogMode (marshalFogMode' Exp')
fogf FogDensity density
setFogMode (Exp2 density) = do
fogi FogMode (marshalFogMode' Exp2')
fogf FogDensity density
--------------------------------------------------------------------------------
fogi :: FogParameter -> GLint -> IO ()
fogi = glFogi . marshalFogParameter
fogf :: FogParameter -> GLfloat -> IO ()
fogf = glFogf . marshalFogParameter
fogfv :: FogParameter -> Ptr (Color4 GLfloat) -> IO ()
fogfv param ptr = glFogfv (marshalFogParameter param) (castPtr ptr)
--------------------------------------------------------------------------------
fogColor :: StateVar (Color4 GLclampf)
fogColor =
makeStateVar
(getClampf4 Color4 GetFogColor)
(\c -> with c $ (fogfv FogColor . castPtr))
--------------------------------------------------------------------------------
fogIndex :: StateVar (Index1 GLint)
fogIndex =
makeStateVar
(getInteger1 Index1 GetFogIndex)
(\(Index1 i) -> fogi FogIndex i)
--------------------------------------------------------------------------------
data FogCoordSrc =
FogCoord
| FragmentDepth
deriving ( Eq, Ord, Show )
marshalFogCoordSrc :: FogCoordSrc -> GLint
marshalFogCoordSrc x = fromIntegral $ case x of
FogCoord -> gl_FOG_COORD
FragmentDepth -> gl_FRAGMENT_DEPTH
unmarshalFogCoordSrc :: GLint -> FogCoordSrc
unmarshalFogCoordSrc x
| y == gl_FOG_COORD = FogCoord
| y == gl_FRAGMENT_DEPTH = FragmentDepth
| otherwise = error ("unmarshalFogCoordSrc: illegal value " ++ show x)
where y = fromIntegral x
--------------------------------------------------------------------------------
fogCoordSrc :: StateVar FogCoordSrc
fogCoordSrc =
makeStateVar
(getInteger1 unmarshalFogCoordSrc GetFogCoordSrc)
(fogi FogCoordSrc . marshalFogCoordSrc)
--------------------------------------------------------------------------------
data FogDistanceMode =
EyeRadial
| EyePlaneSigned
| EyePlaneAbsolute
deriving ( Eq, Ord, Show )
marshalFogDistanceMode :: FogDistanceMode -> GLint
marshalFogDistanceMode x = fromIntegral $ case x of
-- TODO: Use EYE_RADIAL_NV from NV_fog_distance extension
EyeRadial -> 0x855b
EyePlaneSigned ->gl_EYE_PLANE
-- TODO: Use EYE_PLANE_ABSOLUTE_NV from NV_fog_distance extension
EyePlaneAbsolute -> 0x855c
unmarshalFogDistanceMode :: GLint -> FogDistanceMode
unmarshalFogDistanceMode x
-- TODO: Use EYE_RADIAL_NV from NV_fog_distance extension
| y == 0x855b = EyeRadial
| y == gl_EYE_PLANE = EyePlaneSigned
-- TODO: Use EYE_PLANE_ABSOLUTE_NV from NV_fog_distance extension
| y == 0x855c = EyePlaneAbsolute
| otherwise = error ("unmarshalFogDistanceMode: illegal value " ++ show x)
where y = fromIntegral x
--------------------------------------------------------------------------------
fogDistanceMode :: StateVar FogDistanceMode
fogDistanceMode =
makeStateVar
(getInteger1 unmarshalFogDistanceMode GetFogDistanceMode)
(fogi FogDistanceMode . marshalFogDistanceMode)
| IreneKnapp/direct-opengl | Graphics/Rendering/OpenGL/GL/Fog.hs | bsd-3-clause | 6,064 | 0 | 13 | 1,010 | 1,244 | 653 | 591 | 135 | 8 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.RDS.DeleteEventSubscription
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes an RDS event notification subscription.
--
-- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DeleteEventSubscription.html>
module Network.AWS.RDS.DeleteEventSubscription
(
-- * Request
DeleteEventSubscription
-- ** Request constructor
, deleteEventSubscription
-- ** Request lenses
, desSubscriptionName
-- * Response
, DeleteEventSubscriptionResponse
-- ** Response constructor
, deleteEventSubscriptionResponse
-- ** Response lenses
, desrEventSubscription
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.RDS.Types
import qualified GHC.Exts
newtype DeleteEventSubscription = DeleteEventSubscription
{ _desSubscriptionName :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteEventSubscription' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'desSubscriptionName' @::@ 'Text'
--
deleteEventSubscription :: Text -- ^ 'desSubscriptionName'
-> DeleteEventSubscription
deleteEventSubscription p1 = DeleteEventSubscription
{ _desSubscriptionName = p1
}
-- | The name of the RDS event notification subscription you want to delete.
desSubscriptionName :: Lens' DeleteEventSubscription Text
desSubscriptionName =
lens _desSubscriptionName (\s a -> s { _desSubscriptionName = a })
newtype DeleteEventSubscriptionResponse = DeleteEventSubscriptionResponse
{ _desrEventSubscription :: Maybe EventSubscription
} deriving (Eq, Read, Show)
-- | 'DeleteEventSubscriptionResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'desrEventSubscription' @::@ 'Maybe' 'EventSubscription'
--
deleteEventSubscriptionResponse :: DeleteEventSubscriptionResponse
deleteEventSubscriptionResponse = DeleteEventSubscriptionResponse
{ _desrEventSubscription = Nothing
}
desrEventSubscription :: Lens' DeleteEventSubscriptionResponse (Maybe EventSubscription)
desrEventSubscription =
lens _desrEventSubscription (\s a -> s { _desrEventSubscription = a })
instance ToPath DeleteEventSubscription where
toPath = const "/"
instance ToQuery DeleteEventSubscription where
toQuery DeleteEventSubscription{..} = mconcat
[ "SubscriptionName" =? _desSubscriptionName
]
instance ToHeaders DeleteEventSubscription
instance AWSRequest DeleteEventSubscription where
type Sv DeleteEventSubscription = RDS
type Rs DeleteEventSubscription = DeleteEventSubscriptionResponse
request = post "DeleteEventSubscription"
response = xmlResponse
instance FromXML DeleteEventSubscriptionResponse where
parseXML = withElement "DeleteEventSubscriptionResult" $ \x -> DeleteEventSubscriptionResponse
<$> x .@? "EventSubscription"
| romanb/amazonka | amazonka-rds/gen/Network/AWS/RDS/DeleteEventSubscription.hs | mpl-2.0 | 3,859 | 0 | 9 | 744 | 421 | 257 | 164 | 55 | 1 |
module Generate.JavaScript.Variable
( fresh
, canonical
, modulePrefix
, define
, safe
)
where
import qualified Control.Monad.State as State
import qualified Data.List as List
import qualified Data.Set as Set
import qualified Language.ECMAScript3.Syntax as JS
import qualified AST.Helpers as Help
import qualified AST.Module.Name as ModuleName
import qualified AST.Variable as Var
import qualified Generate.JavaScript.Helpers as JS
-- FRESH NAMES
fresh :: State.State Int String
fresh =
do n <- State.get
State.modify (+1)
return ("_v" ++ show n)
-- DEF NAMES
define :: String -> JS.Expression () -> JS.Statement ()
define name body =
if Help.isOp name then
let
root =
JS.VarRef () (JS.Id () "_op")
lvalue =
JS.LBracket () root (JS.StringLit () name)
in
JS.ExprStmt () (JS.AssignExpr () JS.OpAssign lvalue body)
else
JS.VarDeclStmt () [ JS.VarDecl () (JS.Id () (safe name)) (Just body) ]
-- INSTANTIATE VARIABLES
canonical :: Var.Canonical -> JS.Expression ()
canonical (Var.Canonical home name) =
if Help.isOp name then
JS.BracketRef () (addRoot home "_op") (JS.StringLit () name)
else
addRoot home (safe name)
addRoot :: Var.Home -> String -> JS.Expression ()
addRoot home name =
case home of
Var.Local ->
JS.ref name
Var.TopLevel _moduleName ->
JS.ref name
Var.BuiltIn ->
JS.ref name
Var.Module (ModuleName.Canonical _ moduleName) ->
JS.DotRef () (JS.ref (modulePrefix moduleName)) (JS.Id () name)
modulePrefix :: ModuleName.Raw -> String
modulePrefix moduleName =
'$' : List.intercalate "$" moduleName
swap :: Char -> Char -> Char -> Char
swap from to c =
if c == from then to else c
-- SAFE NAMES
safe :: String -> String
safe name =
let saferName =
if Set.member name jsReserveds then '$' : name else name
in
map (swap '\'' '$') saferName
jsReserveds :: Set.Set String
jsReserveds =
Set.fromList
-- JS reserved words
[ "null", "undefined", "Nan", "Infinity", "true", "false", "eval"
, "arguments", "int", "byte", "char", "goto", "long", "final", "float"
, "short", "double", "native", "throws", "boolean", "abstract", "volatile"
, "transient", "synchronized", "function", "break", "case", "catch"
, "continue", "debugger", "default", "delete", "do", "else", "finally"
, "for", "function", "if", "in", "instanceof", "new", "return", "switch"
, "this", "throw", "try", "typeof", "var", "void", "while", "with", "class"
, "const", "enum", "export", "extends", "import", "super", "implements"
, "interface", "let", "package", "private", "protected", "public"
, "static", "yield"
-- reserved by the Elm runtime system
, "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"
, "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"
, JS.localRuntime
]
| laszlopandy/elm-compiler | src/Generate/JavaScript/Variable.hs | bsd-3-clause | 2,916 | 0 | 13 | 664 | 968 | 546 | 422 | 72 | 4 |
module Main where
import qualified Streaming.Prelude as Str
import qualified System.IO.Streams as IOS
import Conduit.Simple as S
import Control.Exception
import Criterion.Main
import Data.Conduit as C
import Data.Conduit.Combinators as C
--
-- import Fusion as F hiding ((&))
-- import Data.Function ((&))
import Pipes as P
import qualified Pipes.Prelude as P
import Test.Hspec
import Test.Hspec.Expectations
main :: IO ()
main = do
-- hspec $ do
-- describe "basic tests" $
-- it "passes tests" $ True `shouldBe` True
defaultMain [
bgroup "basic" [ bench "stream" $ nfIO stream_basic
, bench "iostreams" $ nfIO iostreams_basic
, bench "pipes" $ nfIO pipes_basic
, bench "conduit" $ nfIO conduit_basic
-- , bench "simple-conduit" $ nfIO simple_conduit_basic
-- , bench "fusion" $ nfIO fusion_basic
]
]
pipes_basic :: IO Int
pipes_basic = do
xs <- P.toListM $ P.each [1..1000000]
>-> P.filter even
>-> P.map (+1)
>-> P.drop 1000
>-> P.map (+1)
>-> P.filter (\x -> x `mod` 2 == 0)
assert (Prelude.length xs == 499000) $
return (Prelude.length xs)
conduit_basic :: IO Int
conduit_basic = do
xs <- C.yieldMany [1..1000000]
C.$= C.filter even
C.$= C.map ((+1) :: Int -> Int)
C.$= (C.drop 1000 >> C.awaitForever C.yield)
C.$= C.map ((+1) :: Int -> Int)
C.$= C.filter (\x -> x `mod` 2 == 0)
C.$$ C.sinkList
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
simple_conduit_basic :: IO Int
simple_conduit_basic = do
xs <- S.sourceList [1..1000000]
S.$= S.filterC even
S.$= S.mapC ((+1) :: Int -> Int)
S.$= S.dropC 1000
S.$= S.mapC ((+1) :: Int -> Int)
S.$= S.filterC (\x -> x `mod` 2 == 0)
S.$$ S.sinkList
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
fusion_basic :: IO Int
fusion_basic = do
xs <- F.toListM $ F.each [1..1000000]
& F.filter even
& F.map (+1)
& F.drop 1000
& F.map (+1)
& F.filter (\x -> x `mod` 2 == 0)
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
stream_basic :: IO Int
stream_basic = do
xs <- Str.toListM $ Str.each [1..1000000]
& Str.filter even
& Str.map (+1)
& Str.drop 1000
& Str.map (+1)
& Str.filter (\x -> x `mod` 2 == 0)
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
iostreams_basic :: IO Int
iostreams_basic = do
s0 <- IOS.fromList [1..1000000]
s1 <- IOS.filter even s0
s2 <- IOS.map (+1) s1
s3 <- IOS.drop 1000 s2
s4 <- IOS.map (+1) s3
s5 <- IOS.filter (\x -> x `mod` 2 == 0) s4
xs <- IOS.toList s5
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
| m0ar/safe-streaming | benchmarks/StreamingTest.hs | bsd-3-clause | 3,149 | 0 | 15 | 1,052 | 1,160 | 606 | 554 | 82 | 1 |
module Let1 where
data T1 a b = C2 b a
data T2 a = C3 a
res1
= let
in error
"f (C1 1 2) no longer defined for T1 at line: 3"
| kmate/HaRe | old/testing/removeCon/Let1AST.hs | bsd-3-clause | 159 | 0 | 7 | 68 | 40 | 23 | 17 | 7 | 1 |
{-# LANGUAGE GADTs #-}
-- Test for #1396
-- Panics in GHC 6.6.1
module ShouldCompile where
data Right provides final where
RightNull :: Right final final
RightCons :: b -> Right a final -> Right (b -> a) final
collapse_right :: right -> Right right final -> final
--collapse_right f (RightNull) = f
collapse_right f (RightCons b r) = collapse_right (f b) r
| sdiehl/ghc | testsuite/tests/gadt/gadt24.hs | bsd-3-clause | 369 | 0 | 10 | 75 | 101 | 55 | 46 | 7 | 1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- $Id: DriverPhases.hs,v 1.38 2005/05/17 11:01:59 simonmar Exp $
--
-- GHC Driver
--
-- (c) The University of Glasgow 2002
--
-----------------------------------------------------------------------------
module DriverPhases (
HscSource(..), isHsBootOrSig, hscSourceString,
Phase(..),
happensBefore, eqPhase, anyHsc, isStopLn,
startPhase,
phaseInputExt,
isHaskellishSuffix,
isHaskellSrcSuffix,
isObjectSuffix,
isCishSuffix,
isDynLibSuffix,
isHaskellUserSrcSuffix,
isHaskellSigSuffix,
isSourceSuffix,
isHaskellishTarget,
isHaskellishFilename,
isHaskellSrcFilename,
isHaskellSigFilename,
isObjectFilename,
isCishFilename,
isDynLibFilename,
isHaskellUserSrcFilename,
isSourceFilename
) where
#include "HsVersions.h"
import {-# SOURCE #-} DynFlags
import Outputable
import Platform
import System.FilePath
import Binary
import Util
-----------------------------------------------------------------------------
-- Phases
{-
Phase of the | Suffix saying | Flag saying | (suffix of)
compilation system | ``start here''| ``stop after''| output file
literate pre-processor | .lhs | - | -
C pre-processor (opt.) | - | -E | -
Haskell compiler | .hs | -C, -S | .hc, .s
C compiler (opt.) | .hc or .c | -S | .s
assembler | .s or .S | -c | .o
linker | other | - | a.out
-}
-- Note [HscSource types]
-- ~~~~~~~~~~~~~~~~~~~~~~
-- There are three types of source file for Haskell code:
--
-- * HsSrcFile is an ordinary hs file which contains code,
--
-- * HsBootFile is an hs-boot file, which is used to break
-- recursive module imports (there will always be an
-- HsSrcFile associated with it), and
--
-- * HsigFile is an hsig file, which contains only type
-- signatures and is used to specify signatures for
-- modules.
--
-- Syntactically, hs-boot files and hsig files are quite similar: they
-- only include type signatures and must be associated with an
-- actual HsSrcFile. isHsBootOrSig allows us to abstract over code
-- which is indifferent to which. However, there are some important
-- differences, mostly owing to the fact that hsigs are proper
-- modules (you `import Sig` directly) whereas HsBootFiles are
-- temporary placeholders (you `import {-# SOURCE #-} Mod).
-- When we finish compiling the true implementation of an hs-boot,
-- we replace the HomeModInfo with the real HsSrcFile. An HsigFile, on the
-- other hand, is never replaced (in particular, we *cannot* use the
-- HomeModInfo of the original HsSrcFile backing the signature, since it
-- will export too many symbols.)
--
-- Additionally, while HsSrcFile is the only Haskell file
-- which has *code*, we do generate .o files for HsigFile, because
-- this is how the recompilation checker figures out if a file
-- needs to be recompiled. These are fake object files which
-- should NOT be linked against.
data HscSource
= HsSrcFile | HsBootFile | HsigFile
deriving( Eq, Ord, Show )
-- Ord needed for the finite maps we build in CompManager
instance Binary HscSource where
put_ bh HsSrcFile = putByte bh 0
put_ bh HsBootFile = putByte bh 1
put_ bh HsigFile = putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> return HsSrcFile
1 -> return HsBootFile
_ -> return HsigFile
hscSourceString :: HscSource -> String
hscSourceString HsSrcFile = ""
hscSourceString HsBootFile = "[boot]"
hscSourceString HsigFile = "[sig]"
-- See Note [isHsBootOrSig]
isHsBootOrSig :: HscSource -> Bool
isHsBootOrSig HsBootFile = True
isHsBootOrSig HsigFile = True
isHsBootOrSig _ = False
data Phase
= Unlit HscSource
| Cpp HscSource
| HsPp HscSource
| Hsc HscSource
| Ccxx -- Compile C++
| Cc -- Compile C
| Cobjc -- Compile Objective-C
| Cobjcxx -- Compile Objective-C++
| HCc -- Haskellised C (as opposed to vanilla C) compilation
| Splitter -- Assembly file splitter (part of '-split-objs')
| SplitAs -- Assembler for split assembly files (part of '-split-objs')
| As Bool -- Assembler for regular assembly files (Bool: with-cpp)
| LlvmOpt -- Run LLVM opt tool over llvm assembly
| LlvmLlc -- LLVM bitcode to native assembly
| LlvmMangle -- Fix up TNTC by processing assembly produced by LLVM
| CmmCpp -- pre-process Cmm source
| Cmm -- parse & compile Cmm code
| MergeStub -- merge in the stub object file
-- The final phase is a pseudo-phase that tells the pipeline to stop.
-- There is no runPhase case for it.
| StopLn -- Stop, but linking will follow, so generate .o file
deriving (Eq, Show)
instance Outputable Phase where
ppr p = text (show p)
anyHsc :: Phase
anyHsc = Hsc (panic "anyHsc")
isStopLn :: Phase -> Bool
isStopLn StopLn = True
isStopLn _ = False
eqPhase :: Phase -> Phase -> Bool
-- Equality of constructors, ignoring the HscSource field
-- NB: the HscSource field can be 'bot'; see anyHsc above
eqPhase (Unlit _) (Unlit _) = True
eqPhase (Cpp _) (Cpp _) = True
eqPhase (HsPp _) (HsPp _) = True
eqPhase (Hsc _) (Hsc _) = True
eqPhase Cc Cc = True
eqPhase Cobjc Cobjc = True
eqPhase HCc HCc = True
eqPhase Splitter Splitter = True
eqPhase SplitAs SplitAs = True
eqPhase (As x) (As y) = x == y
eqPhase LlvmOpt LlvmOpt = True
eqPhase LlvmLlc LlvmLlc = True
eqPhase LlvmMangle LlvmMangle = True
eqPhase CmmCpp CmmCpp = True
eqPhase Cmm Cmm = True
eqPhase MergeStub MergeStub = True
eqPhase StopLn StopLn = True
eqPhase Ccxx Ccxx = True
eqPhase Cobjcxx Cobjcxx = True
eqPhase _ _ = False
{- Note [Partial ordering on phases]
We want to know which phases will occur before which others. This is used for
sanity checking, to ensure that the pipeline will stop at some point (see
DriverPipeline.runPipeline).
A < B iff A occurs before B in a normal compilation pipeline.
There is explicitly not a total ordering on phases, because in registerised
builds, the phase `HsC` doesn't happen before nor after any other phase.
Although we check that a normal user doesn't set the stop_phase to HsC through
use of -C with registerised builds (in Main.checkOptions), it is still
possible for a ghc-api user to do so. So be careful when using the function
happensBefore, and don't think that `not (a <= b)` implies `b < a`.
-}
happensBefore :: DynFlags -> Phase -> Phase -> Bool
happensBefore dflags p1 p2 = p1 `happensBefore'` p2
where StopLn `happensBefore'` _ = False
x `happensBefore'` y = after_x `eqPhase` y
|| after_x `happensBefore'` y
where after_x = nextPhase dflags x
nextPhase :: DynFlags -> Phase -> Phase
nextPhase dflags p
-- A conservative approximation to the next phase, used in happensBefore
= case p of
Unlit sf -> Cpp sf
Cpp sf -> HsPp sf
HsPp sf -> Hsc sf
Hsc _ -> maybeHCc
Splitter -> SplitAs
LlvmOpt -> LlvmLlc
LlvmLlc -> LlvmMangle
LlvmMangle -> As False
SplitAs -> MergeStub
As _ -> MergeStub
Ccxx -> As False
Cc -> As False
Cobjc -> As False
Cobjcxx -> As False
CmmCpp -> Cmm
Cmm -> maybeHCc
HCc -> As False
MergeStub -> StopLn
StopLn -> panic "nextPhase: nothing after StopLn"
where maybeHCc = if platformUnregisterised (targetPlatform dflags)
then HCc
else As False
-- the first compilation phase for a given file is determined
-- by its suffix.
startPhase :: String -> Phase
startPhase "lhs" = Unlit HsSrcFile
startPhase "lhs-boot" = Unlit HsBootFile
startPhase "lhsig" = Unlit HsigFile
startPhase "hs" = Cpp HsSrcFile
startPhase "hs-boot" = Cpp HsBootFile
startPhase "hsig" = Cpp HsigFile
startPhase "hscpp" = HsPp HsSrcFile
startPhase "hspp" = Hsc HsSrcFile
startPhase "hc" = HCc
startPhase "c" = Cc
startPhase "cpp" = Ccxx
startPhase "C" = Cc
startPhase "m" = Cobjc
startPhase "M" = Cobjcxx
startPhase "mm" = Cobjcxx
startPhase "cc" = Ccxx
startPhase "cxx" = Ccxx
startPhase "split_s" = Splitter
startPhase "s" = As False
startPhase "S" = As True
startPhase "ll" = LlvmOpt
startPhase "bc" = LlvmLlc
startPhase "lm_s" = LlvmMangle
startPhase "o" = StopLn
startPhase "cmm" = CmmCpp
startPhase "cmmcpp" = Cmm
startPhase _ = StopLn -- all unknown file types
-- This is used to determine the extension for the output from the
-- current phase (if it generates a new file). The extension depends
-- on the next phase in the pipeline.
phaseInputExt :: Phase -> String
phaseInputExt (Unlit HsSrcFile) = "lhs"
phaseInputExt (Unlit HsBootFile) = "lhs-boot"
phaseInputExt (Unlit HsigFile) = "lhsig"
phaseInputExt (Cpp _) = "lpp" -- intermediate only
phaseInputExt (HsPp _) = "hscpp" -- intermediate only
phaseInputExt (Hsc _) = "hspp" -- intermediate only
-- NB: as things stand, phaseInputExt (Hsc x) must not evaluate x
-- because runPipeline uses the StopBefore phase to pick the
-- output filename. That could be fixed, but watch out.
phaseInputExt HCc = "hc"
phaseInputExt Ccxx = "cpp"
phaseInputExt Cobjc = "m"
phaseInputExt Cobjcxx = "mm"
phaseInputExt Cc = "c"
phaseInputExt Splitter = "split_s"
phaseInputExt (As True) = "S"
phaseInputExt (As False) = "s"
phaseInputExt LlvmOpt = "ll"
phaseInputExt LlvmLlc = "bc"
phaseInputExt LlvmMangle = "lm_s"
phaseInputExt SplitAs = "split_s"
phaseInputExt CmmCpp = "cmm"
phaseInputExt Cmm = "cmmcpp"
phaseInputExt MergeStub = "o"
phaseInputExt StopLn = "o"
haskellish_src_suffixes, haskellish_suffixes, cish_suffixes,
haskellish_user_src_suffixes, haskellish_sig_suffixes
:: [String]
-- When a file with an extension in the haskellish_src_suffixes group is
-- loaded in --make mode, its imports will be loaded too.
haskellish_src_suffixes = haskellish_user_src_suffixes ++
[ "hspp", "hscpp" ]
haskellish_suffixes = haskellish_src_suffixes ++
[ "hc", "cmm", "cmmcpp" ]
cish_suffixes = [ "c", "cpp", "C", "cc", "cxx", "s", "S", "ll", "bc", "lm_s", "m", "M", "mm" ]
-- Will not be deleted as temp files:
haskellish_user_src_suffixes =
haskellish_sig_suffixes ++ [ "hs", "lhs", "hs-boot", "lhs-boot" ]
haskellish_sig_suffixes = [ "hsig", "lhsig" ]
objish_suffixes :: Platform -> [String]
-- Use the appropriate suffix for the system on which
-- the GHC-compiled code will run
objish_suffixes platform = case platformOS platform of
OSMinGW32 -> [ "o", "O", "obj", "OBJ" ]
_ -> [ "o" ]
dynlib_suffixes :: Platform -> [String]
dynlib_suffixes platform = case platformOS platform of
OSMinGW32 -> ["dll", "DLL"]
OSDarwin -> ["dylib", "so"]
_ -> ["so"]
isHaskellishSuffix, isHaskellSrcSuffix, isCishSuffix,
isHaskellUserSrcSuffix, isHaskellSigSuffix
:: String -> Bool
isHaskellishSuffix s = s `elem` haskellish_suffixes
isHaskellSigSuffix s = s `elem` haskellish_sig_suffixes
isHaskellSrcSuffix s = s `elem` haskellish_src_suffixes
isCishSuffix s = s `elem` cish_suffixes
isHaskellUserSrcSuffix s = s `elem` haskellish_user_src_suffixes
isObjectSuffix, isDynLibSuffix :: Platform -> String -> Bool
isObjectSuffix platform s = s `elem` objish_suffixes platform
isDynLibSuffix platform s = s `elem` dynlib_suffixes platform
isSourceSuffix :: String -> Bool
isSourceSuffix suff = isHaskellishSuffix suff || isCishSuffix suff
-- | When we are given files (modified by -x arguments) we need
-- to determine if they are Haskellish or not to figure out
-- how we should try to compile it. The rules are:
--
-- 1. If no -x flag was specified, we check to see if
-- the file looks like a module name, has no extension,
-- or has a Haskell source extension.
--
-- 2. If an -x flag was specified, we just make sure the
-- specified suffix is a Haskell one.
isHaskellishTarget :: (String, Maybe Phase) -> Bool
isHaskellishTarget (f,Nothing) =
looksLikeModuleName f || isHaskellSrcFilename f || not (hasExtension f)
isHaskellishTarget (_,Just phase) =
phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcxx, CmmCpp, Cmm
, StopLn]
isHaskellishFilename, isHaskellSrcFilename, isCishFilename,
isHaskellUserSrcFilename, isSourceFilename, isHaskellSigFilename
:: FilePath -> Bool
-- takeExtension return .foo, so we drop 1 to get rid of the .
isHaskellishFilename f = isHaskellishSuffix (drop 1 $ takeExtension f)
isHaskellSrcFilename f = isHaskellSrcSuffix (drop 1 $ takeExtension f)
isCishFilename f = isCishSuffix (drop 1 $ takeExtension f)
isHaskellUserSrcFilename f = isHaskellUserSrcSuffix (drop 1 $ takeExtension f)
isSourceFilename f = isSourceSuffix (drop 1 $ takeExtension f)
isHaskellSigFilename f = isHaskellSigSuffix (drop 1 $ takeExtension f)
isObjectFilename, isDynLibFilename :: Platform -> FilePath -> Bool
isObjectFilename platform f = isObjectSuffix platform (drop 1 $ takeExtension f)
isDynLibFilename platform f = isDynLibSuffix platform (drop 1 $ takeExtension f)
| snoyberg/ghc | compiler/main/DriverPhases.hs | bsd-3-clause | 14,219 | 0 | 11 | 3,862 | 2,379 | 1,302 | 1,077 | 233 | 20 |
{-# LANGUAGE CPP #-}
module Tests.DoubleDiv where
str = show . (round :: Double -> Int)
{-# NOINLINE a #-}
a :: Double
a = 1000000000
{-# NOINLINE b #-}
b :: Double
b = 34029340939
{-# NOINLINE c #-}
c :: Double
c = 234
runTest :: IO [String]
runTest = return [
str (a/a), str (a/b), str (a/c),
str (b/a), str (b/b), str (b/c),
str (c/a), str (c/b), str (c/c)]
| joelburget/haste-compiler | Tests/DoubleDiv.hs | bsd-3-clause | 371 | 0 | 9 | 82 | 195 | 110 | 85 | 17 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module T12444 where
data Nat = Zero | Succ Nat
data SNat (n :: Nat) where
SZero :: SNat Zero
SSucc :: SNat n -> SNat (Succ n)
type family (:+:) (a :: Nat) (b :: Nat) :: Nat where
m :+: Zero = m
m :+: (Succ n) = Succ (m :+: n)
foo :: SNat (Succ c) -> SNat b -> SNat (Succ (c :+: b))
foo _ x = x
{-
sadd :: ((Succ n1 :+: n) ~ Succ (n1 :+: n), (Succ n1) ~ m)
=> SNat m -> SNat n -> SNat (m :+: n)
sadd SZero n = n
-}
{- [G] a ~ Succ c
Succ c + b ~ Succ (c+b)
a ~ Zero
-->
Zero ~ Succ c TyEq
fsk1 ~ Succ fsk2 TyEq
fsk1 ~ (Succ c) + b FunEq
fsk2 ~ c+b FunEq
----
[W] b ~ a+b ---> b ~ Succ (c+b)
Derived
a ~ Succ c
fsk1 ~ Succ fsk2
b ~ Succ fsk2
work (Succ c) + b ~ fsk1
c+b ~ fsk2
-}
{-
[G] a ~ [b]
--> Derived shadow [D] a ~ [b]
When adding this to the model
don't kick out a derived shadow again!
[G] (a ~ b) --> sc a ~~ b, a ~# b
Silly to then kick out (a~b) and (a~~b)
and rewrite them to (a~a) and (a~~a)
Insoluble constraint does not halt solving;
indeed derived version stays. somehow
-}
| olsner/ghc | testsuite/tests/polykinds/T12444.hs | bsd-3-clause | 1,267 | 0 | 11 | 424 | 175 | 100 | 75 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module App (withApp) where
import Network.Wai
import Network.HTTP.Types
import Data.ByteString.Lazy.Char8 ()
withApp :: (Application -> IO ()) -> IO ()
withApp handler = handler app
app :: Application
app Request{requestMethod = m, pathInfo = p} = do
case (m, p) of
("GET", []) -> return index
_ -> return notFound
index = responseLBS
status200
[("Content-Type", "application/json")]
"{\"msg\":\"JSON, Motherfucker -- Do you speak it?\"}"
notFound = responseLBS
status404
[("Content-Type", "text/plain")]
"404 Not Found"
| martinrehfeld/wai-example | App.hs | mit | 619 | 0 | 11 | 139 | 177 | 99 | 78 | 20 | 2 |
module Main (main) where
import GameObject
import Graphics.Gloss
import Graphics.Gloss.Game as Game
import Data.List
window :: Display
window = InWindow "Asteroid run" (1000,700) (10,10)
background :: Color
background = black
fps :: Int
fps = 200
render :: GameWorld -> Picture
render gameWorld =
pictures ([ backgroundImage]++
( map (drawGameObject) (lasersPlayer1 gameWorld))++
( map (drawGameObject) (lasersPlayer2 gameWorld))++
(if (length (player1Lives gameWorld))>0 then [ drawGameObject $ player1 gameWorld] else [])++
(if (length (player2Lives gameWorld))>0 then [ drawGameObject $ player2 gameWorld] else [])
++ ( map (drawGameObject) (asteroids gameWorld))++
[translate (-476.5) 140 $ color white $ scale 0.3 0.3 $ text ( show (pointsPlayer1 gameWorld))]++
[translate 438 140 $ color white $ scale 0.3 0.3 $ text ( show (pointsPlayer2 gameWorld))]++
( map (drawGameObject) (player1Lives gameWorld))++
( map (drawGameObject) (player2Lives gameWorld))++
(if (length (player1Lives gameWorld))>0 && (player1Cooldown gameWorld)>0 then [drawAura (player1 gameWorld) (player1Aura gameWorld)] else [])++
(if (length (player2Lives gameWorld))>0 && (player2Cooldown gameWorld)>0 then [drawAura (player2 gameWorld) (player2Aura gameWorld)] else [])++
(if ((length (player1Lives gameWorld))==0) && ((length (player2Lives gameWorld))==0) then [gameOverImg] else [])++
(if (gamePaused gameWorld) then [gamePausedImg] else []))
drawAura :: GameObject->GameObject->Picture
drawAura player playerAura = translate pX pY ( drawGameObject playerAura)
where
(pX,pY) = getGameObjectCoordinates player
processEvent :: Event -> GameWorld -> GameWorld
-- prvi igrac
processEvent (EventKey (SpecialKey KeyLeft) Down _ _) world = world { player2Left = True }
processEvent (EventKey (SpecialKey KeyRight) Down _ _) world = world { player2Right = True }
processEvent (EventKey (SpecialKey KeyLeft) Up _ _) world = world { player2Left = False }
processEvent (EventKey (SpecialKey KeyRight) Up _ _) world = world { player2Right = False }
processEvent (EventKey (SpecialKey KeyUp) Down _ _) world = world { player2Up = True }
processEvent (EventKey (SpecialKey KeyDown) Down _ _) world = world { player2Down = True }
processEvent (EventKey (SpecialKey KeyUp) Up _ _) world = world { player2Up = False }
processEvent (EventKey (SpecialKey KeyDown) Up _ _) world = world { player2Down = False }
processEvent (EventKey (SpecialKey KeySpace) Down _ _) world = world { lasersPlayer1 = if (length (player1Lives world))>0 then addLaser (lasersPlayer1 world) (getGameObjectCoordinates (player1 world)) laserGreenImage else (lasersPlayer1 world) }
processEvent (EventKey (SpecialKey KeyEnter) Down _ _) world = world { lasersPlayer2 = if (length (player2Lives world))>0 then addLaser (lasersPlayer2 world) (getGameObjectCoordinates (player2 world)) laserRedImage else (lasersPlayer2 world) }
-- drugi igrac
processEvent (EventKey (Char 'a') Down _ _) world = world { player1Left = True }
processEvent (EventKey (Char 'd') Down _ _) world = world { player1Right = True }
processEvent (EventKey (Char 'a') Up _ _) world = world { player1Left = False }
processEvent (EventKey (Char 'd') Up _ _) world = world { player1Right = False }
processEvent (EventKey (Char 'w') Down _ _) world = world { player1Up = True }
processEvent (EventKey (Char 's') Down _ _) world = world { player1Down = True }
processEvent (EventKey (Char 'w') Up _ _) world = world { player1Up = False }
processEvent (EventKey (Char 's') Up _ _) world = world { player1Down = False }
processEvent (EventKey (Char 'r') Down _ _) world = initialWorld
processEvent (EventKey (Char 'p') Down _ _) world = world { gamePaused = newGamePaused }
where
newGamePaused = not (gamePaused world)
processEvent _ world = world
addLaser :: [GameObject]->(Float,Float)->Picture->[GameObject]
addLaser laserArray (x,y) laserImage = laserArray ++ [(createGameObjectImgObject (x, y+40) (14, 37) laserImage)]
updateCounter :: GameWorld->GameWorld
updateCounter world = world {frameCounter = ((frameCounter world)+1)}
moveObjects :: GameWorld -> GameWorld
moveObjects world = world { player1 = newPlayer1 , player2 = newPlayer2
, lasersPlayer1 = newLasersPlayer1, lasersPlayer2 = newLasersPlayer2 , asteroids=newAsteroids
, player1Lives=newPlayer1Lives, player2Lives=newPlayer2Lives
, pointsPlayer1 = newPointsPlayer1, pointsPlayer2 = newPointsPlayer2
, player1Cooldown=newPlayer1Cooldown, player2Cooldown=newPlayer2Cooldown }
where
step = 1.5
(player1X,player1Y) = getGameObjectCoordinates (player1 world)
(player2X,player2Y) = getGameObjectCoordinates (player2 world)
dx1 = if ((player1Left world) && (not $ player1X - 40 < -500)) then -step
else if ((player1Right world) && (not $ player1X + 40 > 500)) then step
else 0.0
dx2 = if ((player2Left world) && (not $ player2X - 40 < -500)) then - step
else if ((player2Right world) && (not $ player2X + 40 > 500)) then step
else 0.0
dy1 = if ((player1Up world) && (not $ player1Y + 40 > 350)) then step
else if ((player1Down world) && (not $ player1Y - 40 < -350)) then -step
else 0.0
dy2 = if ((player2Up world) && (not $ player2Y + 40 > 350)) then step
else if ((player2Down world) && (not $ player2Y - 40 < -350)) then -step
else 0.0
p1Cooldown=(player1Cooldown world)
p1Lives = (player1Lives world)
(newPlayer1Lives,newPlayer1Cooldown) =
if((length p1Lives)>0 && (playerAsteroidCollision (player1 world) (asteroids world)) && (p1Cooldown==0))
then ((init p1Lives),600)
else (p1Lives,updatePlayerCooldown p1Cooldown)
p2Cooldown=(player2Cooldown world)
p2Lives = (player2Lives world)
(newPlayer2Lives,newPlayer2Cooldown) =
if((length p2Lives)>0 && (playerAsteroidCollision (player2 world) (asteroids world)) && (p2Cooldown==0))
then ((init p2Lives),600)
else (p2Lives,updatePlayerCooldown p2Cooldown)
p1 = moveGameObject (player1 world) dx1 dy1
p2 = moveGameObject (player2 world) dx2 dy2
newPlayer1 = if (dx1 > 0 || (player1Right world)) then changeGameObjectImage p1 player1RightImg
else if (dx1 < 0 || (player1Left world)) then changeGameObjectImage p1 player1LeftImg
else changeGameObjectImage p1 player1BasicImg
newPlayer2 = if (dx2 > 0 || (player2Right world)) then changeGameObjectImage p2 player2RightImg
else if (dx2 < 0 || (player2Left world)) then changeGameObjectImage p2 player2LeftImg
else changeGameObjectImage p2 player2BasicImg
astep = 2.0
movedLasersPlayer1 = laserOrAsteroidOutOfBound $ map (\x -> moveGameObject x 0 1.6) (lasersPlayer1 world)
movedLasersPlayer2 = laserOrAsteroidOutOfBound $ map (\x -> moveGameObject x 0 1.6) (lasersPlayer2 world)
movedAsteroids = laserOrAsteroidOutOfBound $ map (\x -> moveGameObject x (-1 * astep) (-0.7 * astep)) (asteroids world)
(newLasersPlayer1, survivedAsteroids) = laserAsteroidCollision (movedLasersPlayer1, movedAsteroids)
newPointsPlayer1 = (pointsPlayer1 world) + if (asteroiDifference) < 0 then asteroiDifference + 4
else asteroiDifference
where asteroiDifference = length movedAsteroids - length survivedAsteroids
(newLasersPlayer2, newAsteroids) = laserAsteroidCollision (movedLasersPlayer2, survivedAsteroids)
newPointsPlayer2 = (pointsPlayer2 world) + if (asteroiDifference) < 0 then asteroiDifference + 4
else asteroiDifference
where asteroiDifference = length survivedAsteroids - length newAsteroids
createLives (_,_) _ 3 = []
createLives (x,y) playerPicture i = let
lives1 = createLives (x,y) playerPicture (i+1)
in
(createGameObjectImgObject (x,y-i*50) (30,50) playerPicture): lives1
--createBothLives :: Float->([GameObject],[GameObject])
--createBothLives 3 = ([],[])
--createBothLives i =
laserOrAsteroidOutOfBound :: [GameObject] -> [GameObject]
laserOrAsteroidOutOfBound objects = filter (\x ->not $ objectOutOfBound x) objects
objectOutOfBound :: GameObject -> Bool
objectOutOfBound obj = let
(objX,objY)=getGameObjectCoordinates obj
in
(objX>600)||(objX< -600)||(objY>450)||(objY< -450)
laserAsteroidCollision :: ([GameObject],[GameObject])->([GameObject],[GameObject])
laserAsteroidCollision (lasers,asteroids) = let
lasersId = zip [1..] lasers
asteroidsId = zip [1..] asteroids
cartesianList = [(x,y) | x<-lasersId,y<-asteroidsId]
collisions = filter (\(x,y) -> collisionExists (snd x) (snd y)) cartesianList
(lasersRemoveId,_) = unzip $ map (fst) collisions
(asteroidsRemoveId, asteroidsRemove) = unzip $ map (snd) collisions
replacedBigAsteroids = foldr (\asteroid asteroids ->
(separateAsteroid asteroid) ++ asteroids
) []
(filter (\x -> fst(getGameObjectSize x) == 200.0) asteroidsRemove)
in
( map snd (filter (\(x,y) -> notElem x lasersRemoveId) lasersId )
, map snd (filter (\(x,y) -> notElem x asteroidsRemoveId) asteroidsId ) ++ replacedBigAsteroids)
updatePlayerCooldown p1Cooldown = if p1Cooldown>0 then p1Cooldown-1 else p1Cooldown
playerAsteroidCollision :: GameObject->[GameObject]->Bool
playerAsteroidCollision player asteroids = length (filter (\x-> collisionExists player x) asteroids) >0
collisionExists obj1 obj2 = let
(colType,_,_,_,_) = detectCollision obj1 obj2
in
colType /= NoCollision
separateAsteroid :: GameObject -> [GameObject]
separateAsteroid asteroid = [ createGameObjectImgObject (x' + 50 , y' + 50) (80,80) (rotate 15 asteroidSmallImage)
, createGameObjectImgObject (x' + 50 , y' - 50) (80,80) (rotate 345 asteroidSmallImage)
, createGameObjectImgObject (x' - 50 , y' + 50) (80,80) (rotate 345 asteroidSmallImage)
, createGameObjectImgObject (x' - 50 , y' - 50) (80,80) (rotate 15 asteroidSmallImage)
] where (x', y') = getGameObjectCoordinates asteroid
createAsteroid::Float->GameWorld->GameWorld
createAsteroid sec world = world { asteroids=newAsteroids }
where
seed = (frameCounter world) * (ceiling (sec + 1))
randX = nextRand seed
randY = nextRand randX
x' = randX `mod` 1000 - 400
y' = randY `mod` 700 - 200
randStep = nextRand randY
step = randStep `mod` 250
step1 = nextRand step `mod` 300
(newAsteroidImg, w', h') = if mod randY 100 > 95 then (asteroidBigImage, 200, 180)
else (asteroidSmallImage, 80, 80)
newAsteroids = if (0 == mod (frameCounter world) step) then
(createGameObjectImgObject ( fromInteger $ toInteger x' , 450) (w', h') newAsteroidImg) : (asteroids world)
else if (0 == mod (frameCounter world) step1) then
(createGameObjectImgObject (600 , fromInteger $ toInteger y' ) (w', h') newAsteroidImg) : (asteroids world)
else asteroids world
update :: Float -> GameWorld -> GameWorld
update sec world = if( not (gamePaused world)) then
(moveObjects $ updateCounter $ createAsteroid sec world)
else world
-- ucitavanje svih slika
player1BasicImg = png "images/greenBasic.png"
player1RightImg = png "images/greenRight.png"
player1LeftImg = png "images/greenLeft.png"
player2BasicImg = png "images/orangeBasic.png"
player2RightImg = png "images/orangeRight.png"
player2LeftImg = png "images/orangeLeft.png"
orangeLife = png "images/orangeLife.png"
greenLife = png "images/greenLife.png"
backgroundImage = png "images/sky.png"
laserRedImage = png "images/laserRed.png"
laserGreenImage = png "images/laserGreen.png"
asteroidBigImage = png "images/asteroidBig.png"
asteroidSmallImage = png "images/asteroidSmall.png"
playerTimeoutImg = png "images/playerTimeout.png"
gameOverImg = png "images/gameOver.png"
gamePausedImg = png "images/gamePaused.png"
-- kod preuzet sa vezbi prethodnih godina
randMultiplier = 25173
randIncrement = 13849
randModulus = 65536
nextRand :: Int -> Int
nextRand n = (randMultiplier * n + randIncrement) `mod` randModulus
data GameWorld = GameWorld { player1 :: GameObject
, player1Down :: Bool
, player1Up :: Bool
, player1Left :: Bool
, player1Right :: Bool
, player2 :: GameObject
, player2Down :: Bool
, player2Up :: Bool
, player2Left :: Bool
, player2Right :: Bool
, asteroids :: [GameObject]
, lasersPlayer1 :: [GameObject]
, lasersPlayer2 :: [GameObject]
, frameCounter :: Int
, pointsPlayer1 :: Int
, pointsPlayer2 :: Int
, player2Lives :: [GameObject]
, player1Lives :: [GameObject]
, player1Cooldown :: Int
, player2Cooldown :: Int
, player1Aura :: GameObject
, player2Aura :: GameObject
, gamePaused :: Bool
}
initialWorld = GameWorld { player1 = createGameObjectImgObject (0, 0) (80, 80) player1BasicImg
, player2 = createGameObjectImgObject (0, -310) (80, 80) player2BasicImg
, asteroids = []
, lasersPlayer1 = []
, lasersPlayer2 = []
, player1Down = False
, player1Up = False
, player1Left = False
, player1Right = False
, player2Down = False
, player2Up = False
, player2Left = False
, player2Right = False
, frameCounter = 0
, pointsPlayer1 = 0
, pointsPlayer2 = 0
, player2Lives = createLives (475,310) orangeLife 0
, player1Lives = createLives (-475,310) greenLife 0
, player1Cooldown = 1000
, player2Cooldown = 1000
, player1Aura = createGameObjectImgObject (0, 0) (100, 100) playerTimeoutImg
, player2Aura = createGameObjectImgObject (0, 0) (100, 100) playerTimeoutImg
, gamePaused = False
}
--(((createGameObjectImgObject (-475,330-i*40) (30,40) orangeLife): lives1),((createGameObjectImgObject (475,330-i*40) (30,40) greenLife): lives2))
main :: IO ()
main = Game.play
window
background
fps
initialWorld
render
processEvent
[update] | nsub93/asteroid-run | src/Main.hs | mit | 17,609 | 0 | 24 | 6,355 | 4,679 | 2,565 | 2,114 | 243 | 17 |
fib n = fibs !! n
where fibs = 0 : 1 : next fibs
next (a : t@(b:_)) = (a + b) : next t
| theDrake/haskell-experiments | fibonacci.hs | mit | 109 | 0 | 12 | 48 | 70 | 36 | 34 | 3 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -Wall #-}
module Main where
import BasicPrelude hiding (Word, liftIO, lift)
import CommandLine
import TreeGenerator
main :: IO ()
main = do
(search_word, depth, sourcelines, output_fname, wdir) <- getOpt
(jsn, err_files) <- searchAndGetTree wdir depth sourcelines search_word
case output_fname of
Just fname -> writeFile fname jsn
Nothing -> putStrLn jsn
when (0 < length err_files) $ do
putStrLn "Error at:"
forM_ err_files print
| mathfur/grep-tree | src/Main.hs | mit | 632 | 0 | 11 | 126 | 153 | 81 | 72 | 19 | 2 |
module StartupHook (getStartupHook) where
import XMonad
import XMonad.ManageHook (composeAll)
import Data.Foldable
import SessionType
import Commands
getStartupHook sessionType = basicDesktopSetupCommands
basicDesktopSetupCommands :: X ()
basicDesktopSetupCommands = composeAll $ map spawn [ "wmname LG3D"
, "xsetroot -cursor_name left_ptr"
, "setxkbmap -layoubt gb"
, "xmodmap ~/.Xmodmap"
]
| willprice/dotfiles-xmonad | lib/StartupHook.hs | mit | 601 | 0 | 7 | 253 | 77 | 45 | 32 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Settings.Style where
import Common.CssClass
import Common.CommonClasses
import Data.Monoid
import Clay
import Prelude hiding ((**))
settingsIconClassSymbol :: CssClass
settingsIconClassSymbol = CssClass "fa fa-cog"
settingsIconClassInternal :: CssClass
settingsIconClassInternal = CssClass "settings-icon"
settingsIconClass :: CssClass
settingsIconClass = settingsIconClassSymbol <> settingsIconClassInternal
settingsPopupClass :: CssClass
settingsPopupClass = CssClass "settings-popup"
settingsPopupCloseInternal :: CssClass
settingsPopupCloseInternal = CssClass "settings-popup-close"
settingsPopupClose :: CssClass
settingsPopupClose = settingsPopupCloseInternal <> faClass <> faTimesClass
shroudClass :: CssClass
shroudClass = CssClass "shroud"
settingsLineClass :: CssClass
settingsLineClass = CssClass "settings-line"
boardSettingsStyle :: Css
boardSettingsStyle = do
star # classSelector settingsIconClassInternal ? do
position fixed
fontSize (em 3)
cursor pointer
right nil
top nil
textAlign end
paddingRight (em 0.3)
paddingTop (em 0.3)
boxSizing borderBox
star # classSelector settingsPopupClass ? do
position fixed
left (pct 50)
top (pct 50)
marginTop (em (-15))
height (em 30)
marginLeft (em (-24))
width (em 48)
backgroundImage $ url "data/background.png"
borderWidth (px 3)
borderStyle solid
borderColor "#222222"
padding (em 3) (em 3) (em 3) (em 3)
borderRadius (px 15) (px 15) (px 15) (px 15)
zIndex 2
star # classSelector settingsPopupCloseInternal ? do
position absolute
right (pt 10)
top (pt 10)
fontSize (pt 20)
cursor pointer
star # classSelector shroudClass ? do
zIndex 1
position fixed
width (pct 100)
height (pct 100)
left nil
top nil
margin nil nil nil nil
opacity 0.6
backgroundColor black
star # classSelector settingsLineClass ? do
height (em 4.4)
lineHeight (em 4.4)
margin (em 0.8) (em 0.8) (em 0.8) (em 0.8)
star # classSelector settingsLineClass ** input ? do
verticalAlign middle
marginRight (em 3)
| martin-kolinek/some-board-game | src/Settings/Style.hs | mit | 2,163 | 0 | 14 | 441 | 714 | 322 | 392 | 73 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Wai.Twilio.RequestValidatorMiddlewareSpec where
import Test.Hspec
import Network.Wai.Twilio.RequestValidatorMiddleware
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as BL
import Network.HTTP.Types
import Network.Wai
import Network.Wai.Test
trivialApp :: Application
trivialApp req f =
f $
responseLBS
ok200
[ ("content-type", "text/plain") ]
"Trivial App"
-- https://mycompany.com/myapp.php?foo=1&bar=2
req1 = SRequest defaultRequest
{ requestMethod = "POST"
, rawPathInfo = "/myapp.php"
, rawQueryString = "?foo=1&bar=2"
, isSecure = True
, requestHeaderHost = Just "mycompany.com"
, requestHeaders = [("X-Twilio-Signature", "RSOYDt4T1cUTdK1PDd93/VVr8B8=")]
} "Digits=1234&To=%2B18005551212&From=%2B14158675309&Caller=%2B14158675309&CallSid=CA1234567890ABCDE"
spec :: Spec
spec = do
describe "requestValidator" $ do
it "validates correct requests" $ do
(SResponse status _ msg) <- runSession (srequest req1) (requestValidator "12345" trivialApp)
msg `shouldBe` "Trivial App"
status `shouldBe` ok200
it "rejects incorrect requests" $ do
(SResponse status _ msg) <- runSession (srequest req1) (requestValidator "1234" trivialApp)
msg `shouldBe` "Invalid X-Twilio-Signature"
status `shouldBe` unauthorized401
| steven777400/TwilioIVR | test/Network/Wai/Twilio/RequestValidatorMiddlewareSpec.hs | mit | 1,496 | 0 | 16 | 338 | 300 | 169 | 131 | 35 | 1 |
----------------------------------------------------------------------------------------------------
{- |
Module : InterfaceQAWindows
Copyright : (c) Rawle Prince 2012
License : GPL-style
Maintainer : Rawle Prince (rawle DOT prince at GMAIL dot com )
Stability : provisional
Portability : uses gtk2hs
Interface for analysis funcitons in PPDL
-}
----------------------------------------------------------------------------------------------------
-- TO DO:
-- 1. scheme box
-- 2. network analysis box
-- 3. redo the analysis box to omit the analysis of individual secttions
-- (the individual section option shold not be on the top-level options window)
----------------------------------------------------------------------------------------------------
module InterfaceQAWindows (analysisBoxForAFrame--globalAnalysisTop
,fillPreviewBox
-- ,mkResultBox --
,schemAnl)
where -- topOfWindow,schemePrepAndAnanlysis,
----------- native haskell modules ------------------------
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Graphics.UI.Gtk as G
import Numeric.LinearAlgebra (fromList)
import Data.Ord (comparing)
import Data.IORef
import Data.List (find, delete,deleteBy,intersectBy, intersect, findIndex, nub,foldl', nubBy,maximumBy,sortBy)
import System.Directory (doesDirectoryExist,createDirectory) -- doesFileExist,removeFile)
import Data.Char (isDigit,isAlpha,isAlphaNum)
import Data.Maybe (isJust,fromMaybe,maybe,listToMaybe)
--import Control.Monad.Trans (liftIO)
import Control.Parallel (pseq)
import Control.Monad (liftM,liftM2)
import Control.Concurrent (forkIO,killThread)
import System.Random (newStdGen) -- , randomRs)
import System.Directory (doesFileExist)
--import Control.Monad (when)
---- specific modules
import ProcessFile (Display, display,readRoadTypeSL,intercalateFormList,getRoadClasses,
getRoadNamesAndSections,getRoadNames)
import HMDIFPrelude (Defect (..) , typesAndDetails,scode2align,(<>))
import GlobalParameters -- (AddedCombos,labelLeftofWidget,labelLeftofWidgetE)
import RprGD2 (mml2DsGD, OptimisationType(..))
import LMisc (myTake,force,mkIntervals)
import ReadFromDataFiles2
import RprMix2 (OModel,printElm,Mmodel (MkModel),r_n)
import Parallel
import FileIO
import ResultTypes (TdsParms (..))
import DrawingFrame (getDrawingCanvas,fileBrowser,isValid,mkDnaDisplayFrame
,comboText,updateDrawingArea,mkProgressionGroupList,mkDnaTable) -- vals2drwRef,mkDnaBase,
--
----------------------------------------------------------------------------------------------------
setName string | firstletter == 'R' = Rutting
| firstletter == 'C' = Cracking
| firstletter == 'T' = Texture
| otherwise = Profile
where firstletter = head string
-- emptying a text buffet
myEmptyTextBuffer buffer = do
(start,end) <- G.textBufferGetBounds buffer
G.textBufferDelete buffer start end
----------------------------------------------------------------------------------------------------
-- Interface for global analysis options
--
data AWin = AWin {
-- the file path to open
fPath :: String,
-- the list of selected condition condes
sList :: [Defect],
-- a list of options corresponding to the selected condition codes
-- i.e. (years, distance, negslopes) for each condition
options :: [(Int,Int,Bool)],
fType :: FileType
}
--- parameter to pass to the preview box
data PreviewParms = PreviewParms {
wrtFun :: (String -> IO()),
yrsEnt :: G.Entry,
distEnt :: G.Entry,
nSpopes :: G.CheckButton,
schemAnl :: G.RadioButton
}
--}
---------------------------------------------
--- flags for the extract or analyze buttons
--- extract, analyse, extNotAnl
extract :: Maybe Bool
extract = Just False
analyse :: Maybe Bool
analyse = Just True
extNorAnl :: Maybe Bool
extNorAnl = Nothing
---------------------------------------------
--- the geberal interface for analysis
--[G.RadioButton]
analysisBoxForAFrame :: Bool -> [G.RadioButton] ->
G.Entry -> [G.VBox] -> IO G.VBox
analysisBoxForAFrame tf rbutts fe boxes = do
aBox <- G.vBoxNew False 5
selectBox <- getSelectBox tf rbutts fe -- this comes from another function
detailsFrame <- G.frameNew
G.set detailsFrame [G.frameLabel G.:= " Condition parameters" ]
table <- tableWithWidgetList False boxes False 2
--table <- hPanedArea (boxes !! 0) (boxes !! 1) 100
G.containerAdd detailsFrame selectBox
G.boxPackStart aBox detailsFrame G.PackNatural 5
G.boxPackStart aBox table G.PackGrow 2 -- detailsFrame
return aBox
--
where
getSelectBox :: Bool -> [G.RadioButton] -> G.Entry -> IO G.HBox
getSelectBox sE rbutts fileEntry = do
[thbox,entryBox, tablesBox] <- sequence $ replicate 3 (G.hBoxNew False 2)
browseButton <- G.buttonNewWithLabel " Load data file "
--- pack the entry box
G.boxPackEnd entryBox fileEntry G.PackGrow 4
G.boxPackStart entryBox browseButton G.PackNatural 2
G.on browseButton G.buttonActivated $ do
fileBrowser (Just fileEntry) >>= G.dialogRun >>= \_ -> return () -- ) >> return ()
--- put the condition chooser in a box
let n = length rbutts
let (condTypes, scnSem) = splitAt (n-2) rbutts
condBox <- tableWithWidgetList False condTypes False 3
vButtonTable <- tableWithWidgetList True scnSem True 3
G.vSeparatorNew >>= \sep -> do
sep1 <- G.vSeparatorNew
G.boxPackStart tablesBox sep1 G.PackNatural 0
G.boxPackStart tablesBox vButtonTable G.PackNatural 8
G.boxPackStart tablesBox sep G.PackNatural 0
G.boxPackStart tablesBox condBox G.PackGrow 5
--
--G.containerAdd tablesFrame tablesBox
if sE then do
G.boxPackStart thbox entryBox G.PackGrow 2
G.boxPackStart thbox tablesBox G.PackGrow 0
else do
G.boxPackStart thbox tablesBox G.PackGrow 2
G.boxPackStart thbox entryBox G.PackGrow 0
--
--detailsFrame <- G.frameNew
return thbox
--}
{-
--------------------------------------------------------------------------------------------------
-- Dialog to initialize the network level analyis and related dialiogos and datatypes
--------------------------------------------------------------------------------------------------
--- the maybe here should be a pair of tracking panes
globalAnalysisTop :: Maybe G.Window ->
Maybe (IORef [Road]) ->
IO (G.VBox, Maybe AWin,[G.RadioButton], G.Entry , PreviewParms)
globalAnalysisTop mwin strAndChn = do
[mainVBox,listsVBox] <- sequence $ replicate 2 (G.vBoxNew False 1)
[bottomHBox,topHBox, -- condsVBox, topHBox,bottomOBox,
buttsVBox] <- sequence $ replicate 3 (G.hBoxNew False 1)
comboList <- sequence $ replicate 5 G.comboBoxNewText
vsep <- G.vSeparatorNew
[hsep, hsep1, hsep2] <- sequence $ replicate 3 G.hSeparatorNew
[yearsEntry, distEntry, fileEntry] <- sequence $ replicate 3 G.entryNew
-- fileEntry is the entry for the file Path. set the size of the entry
G.widgetSetSizeRequest fileEntry 360 (-1)
-------------------------------------------------------------------
prevAnalFrame <- G.frameNew
-- condTypes
------------------------------------------------------------------------------------
-- the display window
-- the progress and display buffers
(scrwin,progressBuffer) <- makeScrolledEntryArea BScroll False True
G.widgetSetSizeRequest scrwin 60 (-1)
-------- and updating chains will be added here
(selectedCondsTable, dispBuffer) <- getSelectedConditionsTable
---
let logProgress = updateBufferAtEnd progressBuffer
let add2SeletList = updateBufferAtEnd dispBuffer
----- check for extracted conditons
checkIfExtracted False True logProgress
-------------------------------------------------------------------
G.set prevAnalFrame [G.frameLabel G.:= " Condition attribures" ]
G.containerAdd prevAnalFrame listsVBox -- listsVBox
G.boxPackStart topHBox prevAnalFrame G.PackGrow 6
-------------------------------------------------------------------
mapM_ (\ent -> do
G.entrySetWidthChars ent 6
G.entrySetMaxLength ent 6) [yearsEntry, distEntry]
let [detailsCombo,rNameCombo,rClassCombo,rCodeCombo,srCodeCombo] = comboList
-- fillToMaxLegth :: [String] -> [String]mapM (G.labelNew . Just)
let comboNames = ["Road Class: ", "Road Name: ", "SCANNER Section Code: "," SCRIM Section Code: "]
--mapM_ (\w -> G.miscSetAlignment w 1 0.5) comboNames
let schms = zip (fillToMaxLegth comboNames) [rClassCombo,rNameCombo,rCodeCombo,srCodeCombo]
--let labelAndWidget m a b = labelLeftofWidget a b m
comboBoxesWithLables <- mapM (\(l,w) -> labelLeftofWidget l w False ) (take 2 schms)
comboBoxesWithLables1 <- mapM (\(l,w) -> labelLeftofWidget l w False ) (drop 2 schms)
-- create table
row1 <- tableWithWidgetList False comboBoxesWithLables False 2
row2 <- tableWithWidgetList False comboBoxesWithLables1 False 2
--schmAndClass <- tableWithWidgetList True [row1,row2] True 2
------------------------------------ }
comboRef <- newIORef [] --- the a record to toggle the condition details
--roadConditionRef
--- selected,
detailsListRef <- newIORef ([],[],[])
advancedRef <- newIORef ([],Nothing)
dataTypeRef <- newIORef SCANNER -- toggles the curreltly selected data type
countRef <- newIORef 1 -- a counter ref track what is happings
rNameRef <- newIORef []
extractAnal <- newIORef Nothing --- flag to toggle extraction or analysys
------------------------------------
let comboLabels = [" Condition Detail: "]
let comboLabelPairs = zip comboLabels comboList
vBoxesWithLabels <- mapM (\(st,w) -> labelLeftofWidget st w False) comboLabelPairs
---
[rcl,rsc] <- mapM G.radioButtonNewWithLabel ["Road Class","Section Code"]
G.radioButtonSetGroup rcl rsc
--mapM_ (\b -> G.boxPackEnd (vBoxesWithLabels !! 0) b G.PackNatural 6) [rcl,rsc]
-------------------------------------------------------------------------------
---- fork the population of the roads, etc
--- We will need to put each road class in a separate file. This wouuld be done when
--- When the details of the roas is added
-- desensetise the combos :
mapM_ (flip G.widgetSetSensitive False) (map snd schms)
rtypes <- getRoadClasses >>= return . filter (isAlpha . snd)
let roadTypes = map snd $ nubBy (\a b -> snd a == snd b) rtypes
----- extract the road classes
let getClasses = mapM_ (G.comboBoxAppendText rClassCombo) $ map ( :"-roads") roadTypes
--let getNames = mapM_ (G.comboBoxAppendText rNameRef) $ map L.unpack rNames
--forkIO $ mapM_ (G.comboBoxAppendText rCodeCombo) $ map (\(a,_,_) -> L.unpack a) secAndTypes
-- clearAdd cRef combo list
-- let schms = zip comboNames [rNameCombo,rClassCombo,rCodeCombo,srCodeCombo]
rCodesComboRef <- newIORef [] --- the a record to toggle the condition details
roadClassAdded <- newIORef False
{--- fix this
let getCodesFromClass = do
index <- G.comboBoxGetActive rClassCombo
if index >= 0 then do
let !codes = [bs | (bs,c) <- rtypes, c == (roadTypes !! index)]
clearAdd rCodesComboRef rCodeCombo $ map L.unpack codes --
else return ()
--}
G.on rClassCombo G.changed $ do
rclsAdded <- readIORef roadClassAdded
index <- G.comboBoxGetActive rClassCombo
if rclsAdded then do
let des = "Extracting classes for "++[roadTypes !! index]++"-roads"
logProgress (des ++ " ... ")
-- forkProcess (Just des) logProgress getCodesFromClass Nothing
else do
let rtyp = roadTypes !! index
let mkRN1 (a,b,c) = L.unpack c
let mkSC1 (a,b,c) = L.unpack b
logProgress ([rtyp] ++"-roads selected")
rname <- getRoadNamesAndSections (map fst $ filter ((== rtyp) . snd) rtypes) -- >>= return $ map mkSt1
clearAdd rNameRef rNameCombo (map mkRN1 rname)
clearAdd rCodesComboRef rCodeCombo (map mkSC1 rname)
G.widgetSetSensitive rNameCombo True
--sensetize the combos once the road classes have been extracted
forkProcess Nothing logProgress getClasses
(Just $ mapM_ (flip G.widgetSetSensitive True) [rClassCombo,rCodeCombo])
--forkProcess Nothing (updateBufferAtEnd progressBuffer) getNames
-- (Just $ mapM_ (flip G.widgetSetSensitive True) [rNameCombo,rCodeCombo])
-- let schms = zip comboNames [rNameCombo,rClassCombo,rCodeCombo,srCodeCombo]
-- clearAdd comboRef detailsCombo (map display lst)
--- update the road class names,codes and section codes upon a election of a road class
-------------------------------------------------------------------------
[addButton,analButton,previewButt,clrButt] <- mapM G.buttonNewWithLabel
[" Add condition details ",
" Analyse ", " Extract ",
" Edit List "]
--advOptions <- advancedOptionsWin -- (Just advancedRef)
-- file entry box vBoxesWithLabels <- mapM (\(st,w) -> labelLeftofWidget st w False) comboLabelPairs
let entryLabels = [" Average maintenance frequency in years: ",
" Average treatment length in kilometers: "]
let entryPairs = zip entryLabels [yearsEntry, distEntry]
entryTable <- mapM (\(l,w) -> labelLeftofWidget l w True) entryPairs >>= \eb ->
tableWithWidgetList False eb False 10
-- [yearsEntry, distEntry]
-- use the dummy do that none will be set on start up
dummy <- G.radioButtonNew -- WithLabel "
[nl, sl] <- mapM G.radioButtonNewWithLabel [" Network Level Analysis "," Scheme/road Level Analysis "]
G.radioButtonSetGroup dummy nl
G.radioButtonSetGroup nl sl
---
---
--- negative slopes
negativeSlopes <- G.checkButtonNew -- WithLabel "
optsBox <- labelLeftofWidgetE' "Include negative slopes " 1 negativeSlopes True
--
mapM_ (\w -> G.boxPackStart optsBox w G.PackGrow 2) [nl,sl]
--G.boxPackEnd optsBox negativeSlopes' G.PackGrow 2
-------------------------------------------------------------------------------------
G.on addButton G.buttonActivated $ do
-- need here: read inout parameter file
[str1,str2] <- mapM G.entryGetText [yearsEntry, distEntry]
negSlope <- G.toggleButtonGetActive negativeSlopes
-- return () -- temporary
--
case (validateEntries [str1,str2] ["years","distance"]) of
Left [e1,e2] -> do
index <- G.comboBoxGetActive detailsCombo -- >>= \index ->
if index >= 0 then do
(selected,_,dlist) <- readIORef detailsListRef -- >>= \ -> do
let sel = (dlist !! index)
let str = (display sel) -- ++ (" yrs: "++str1 ++ " dist: "++str2)
let message = "You have already added \'" ++ display sel ++ "\' to\
\ the list of selected conditions."
--
if sel `elem` selected then
runMsgDialog Nothing message Info
else do
let pm = (fromIntegral e1, fromIntegral e2,negSlope)
add2SeletList str
modifyIORef detailsListRef (\(a,ps,b) -> (sel : a,pm:ps,b))
-- clear the entries and neg slope
mapM_ (\ent -> G.entrySetText ent "") [yearsEntry, distEntry]
G.toggleButtonSetActive negativeSlopes False
else
runMsgDialog Nothing "Negative index at condition details combo box" Error
Right string -> runMsgDialog Nothing string Error
------------------------------------------------------------------------------------ }
---- the scanner or scrim radio butttons
[d1,d2] <- mapM (\st -> G.radioButtonNewWithLabel st) ["", ""]
condTypes <- mapM (G.radioButtonNewWithLabelFromWidget d1 )
(map fst $ init typesAndDetails)
scnSem <- mapM (G.radioButtonNewWithLabelFromWidget d2) [" SCANNER Data "," SCRIM Data "]
let ontoggle butt = G.on butt G.toggled $ do
G.toggleButtonGetActive butt >>= \b ->
--- need special case for RCI
if b then
G.buttonGetLabel butt >>=
(\str ->
case find ((== str) . fst) typesAndDetails of
Nothing -> return ()
Just (_,lst) -> do
clearAdd comboRef detailsCombo (map display lst)
modifyIORef detailsListRef (\(a,b,_) -> (a,b,lst))
let profileFile = "./mmlTdsFiles/Profile/currProfile.txt"
L.writeFile profileFile (L.pack str)
)
else
return ()
mapM ontoggle condTypes
------------------------------------------------------------------------------------
--- need to desensitive some stuff when SCRIM is selected
let desensetiveForScrim butt = G.on butt G.toggled $ do
G.toggleButtonGetActive butt >>= \b ->
if b then do
mapM_ (flip G.widgetSetSensitive False) condTypes
modifyIORef dataTypeRef (\_ -> SCRIM)
else do
mapM_ (flip G.widgetSetSensitive True) condTypes
modifyIORef dataTypeRef (\_ -> SCANNER)
desensetiveForScrim (scnSem !! 1)
------------------------------------------------------------------------------------
-- The operation we want here is to opena a dialog with options to remove
-- entries from the list. Either indivdually selected items or all items can
-- be removed from the list
G.on clrButt G.buttonActivated $
openEditDialog comboRef detailsCombo detailsListRef dispBuffer
---------------- PACKING ------------------------------------------------
G.boxPackStart listsVBox optsBox G.PackNatural 5
G.boxPackStart listsVBox (vBoxesWithLabels !! 0) G.PackNatural 5
G.boxPackStart listsVBox entryTable G.PackNatural 5
G.boxPackStart listsVBox hsep1 G.PackNatural 5
--G.boxPackStart listsVBox schmAndClass G.PackNatural 2
---
G.boxPackStart listsVBox hsep G.PackNatural 5
mapM_ (\b -> G.boxPackStart buttsVBox b G.PackNatural 2) [analButton,previewButt ]
mapM_ (\b -> G.boxPackEnd buttsVBox b G.PackNatural 4) [addButton,clrButt]
-- put the options here
G.boxPackStart listsVBox buttsVBox G.PackGrow 0
--
G.boxPackStart mainVBox topHBox G.PackNatural 6
------------- the bottom of the left pane -----------------------------------------.
--- the left side has a frame highlighting the selected condition
---- the right the progress log
-------- first get the table for the selected conditions. The handles for adding
---- this comes from the main display?
[selectedConditions, progressLog] <- sequence $ replicate 2 G.frameNew
G.set progressLog [G.frameLabel G.:= " Progress log" ]
G.set selectedConditions [G.frameLabel G.:= " Selected conditions" ]
G.containerAdd progressLog scrwin
G.containerAdd selectedConditions selectedCondsTable
-- tableWithWidgetList isVertical widgets homo spacing
displayLogs <- tableWithWidgetList False [selectedConditions, progressLog] True 5
G.boxPackStart bottomHBox displayLogs G.PackGrow 6
G.boxPackStart mainVBox bottomHBox G.PackGrow 6
-------------------------
--G.widgetModifyBg mainVBox G.StateActive (G.Color 190 190 190)
let rbutts = condTypes ++ scnSem
-- check what has been extracted already
--checkIfExtracted logProgress
G.on previewButt G.buttonActivated $ do
-- extract and align the file, bot do not analyse
handleForAnalAndExtract extractAnal fileEntry detailsListRef dataTypeRef logProgress (analButton,False)
--
G.on analButton G.buttonActivated $ do
--let btyp = (analButton,True)
handleForAnalAndExtract extractAnal fileEntry detailsListRef dataTypeRef logProgress (analButton,True)
------------------------------------------------------------------------------------
let pParms = PreviewParms logProgress yearsEntry distEntry negativeSlopes sl
readIORef detailsListRef >>= \(sels,pms,_) -> do
return (mainVBox, Nothing, rbutts, fileEntry,pParms)
where
getSelectedConditionsTable = do
labels <- mapM (G.labelNew . Just) [" No."," Description "]
headBox <- G.hBoxNew False 1
displayBox <- G.vBoxNew False 1
---
G.boxPackStart headBox (labels !! 0) G.PackNatural 1
G.boxPackEnd headBox (labels !! 1) G.PackGrow 1
G.vSeparatorNew >>= \sep -> G.boxPackEnd headBox sep G.PackNatural 0
---
(display, dispBuffer) <- makeScrolledEntryArea HScroll False False
G.boxPackStart displayBox headBox G.PackNatural 1
G.boxPackStart displayBox display G.PackGrow 1
return (displayBox , dispBuffer)
--G.tableAttachDefaults entryTable (entryPairs !! 0) 0 1 0 1
--
validateFilePath str =
let string = "The name entered is not a valid file path." in
if isValid str then Nothing else (Just string)
-- countRef
write2Buffer tbuffer wrt string = do
let wrds = words string
if not (null wrds) && head wrds == "Finished" then
G.textBufferGetEndIter tbuffer >>= \iter ->
G.textBufferInsert tbuffer iter (string ++"\n")
else
wrt string
-- handle for analayis and Extraction --- extract, analyse, extNorAnl
handleForAnalAndExtract extAnal fileEnt deatilsLstRef dataTypRef wrt butType = do
extnl <- readIORef extAnal
let (button,isAnal) = butType
case extnl of
Nothing -> do
-- Just _ -
--let senstize = G.widgetSetSensitive button True
--let deSenstize = G.widgetSetSensitive button False
let reSetFlag = do
modifyIORef extAnal (\_ -> Nothing)
check <- readIORef extAnal
print (show check)
filePath <- G.entryGetText fileEnt
case validateFilePath filePath of
Just errString ->
runMsgDialog Nothing errString Error
Nothing -> do
-- forkIO $ copty file to the files folder. Useful for extracting HMDIF
--(sl,_,_) <- readIORef detailsListRef
(sels,pms,_) <- readIORef deatilsLstRef
if null sels then
runMsgDialog Nothing "You have not selected any parameter investigate" Error
else do
-- parse the file for scrim or scanner
fileOk <- readIORef dataTypRef >>= parseFile filePath -- fKind
case fileOk of
Nothing -> do
----
let line chr = '\n' : replicate 40 chr ++"\n"
let toAnalyse (sc, (ye,dst,ns)) = display sc ++ ": \n\t-\
\ Maint. frequency: "++show ye++"\
\ years; \n\t- Dist. between maint. works: "++ show dst ++ "\
\ Km; \n\t- Negative slopes: "++ show ns ++ line '-'
let list = concatMap toAnalyse $ zip sels pms
let st = "You have choosen to Analyse the following:"++ line '='
let qt = line '=' ++ "\n\nDo you wish to proceed? "
----- need a decision dialog here with the stuff being done
let labelInfo = "Running MML2DS on the selected conditions. "
--- set up the progress buffer ------------------------
let runAnalysis = do
g <- newStdGen
let anF dp ye dst ns dk n m = exF dp ye dst ns dk n m
--let anF tds = mml2DsGD g tds
-- mml2DsGD g dp ye dst ns dk n m wrt
--let exF _ _ _ _ _ _ _ = return (([],[]) :: ([(OModel, ([Double], [Int]))], [Int]))
let analFun = if isAnal then anF else exF
runAnalysisFromWindow filePath wrt analFun $ zip sels pms -- >> reSetFlag
wrt labelInfo -- show what process is being done
modifyIORef extAnal (\_ -> Just isAnal)
forkProcess (Just labelInfo) wrt runAnalysis (Just reSetFlag)
-- deSenstize
Just errString -> runMsgDialog Nothing errString Error
Just ea -> do
-- show a message if analysis or extract is clicked when a process is already running
let exOrAn = if ea then "analysis" else "extraction"
let errString = "An "++exOrAn++ " process is currently running, which \
\ muct be completed before you can proceed with this action."
runMsgDialog Nothing errString Error
where
exF :: Int -> Double -> Double -> Bool -> Int
-> Int -> Int -> [[Double]]
-> IO [([(OModel, ([Double], [Int]))], [Int])]
exF _ _ _ _ _ _ _ _ = return []
---
-------------------------------------------------------------------------------------
-- test: running the analysis on all the data from the analyisis window
-------------------------------------------------------------------------------------
type Data = [[Double]]
runAnalysisFromWindow :: String ->
(String -> IO ()) ->
--(Double -> Double -> Bool -> Data -> IO ([([(OModel, ([Double], [Int]))], [Int])])) ->
( Int -> -- search depth
Double -> -- range in years
Double -> -- range in distance
--g -> -- random starting value
Bool -> -- ignore negative slopes
--Int -> -- the maximum number of possible cuts for the segment. See QueryDialog for details
Int -> -- the maximum number of chains to align
Int -> -- the minimum number of chains to align
Int -> -- the minimum number of points to trend
[[Double]] ->
IO [([(OModel, ([Double], [Int]))], [Int]) ]) ->
[(Defect,(Double,Double,Bool))] -> IO ()
runAnalysisFromWindow fileName write2B anlF options = do
let runAnalysis (sc ,(yr, ds, ns)) = -- (anlF yr ds ns) -- (\a -> anlF a yr ds ns)
bs2HMDIF2bs_aux Nothing fileName write2B Nothing Rapid (show sc, scode2align sc) (5,35) Nothing
mapM_ runAnalysis options
return () -- force a return
------------------------------------------------------------------------------------}
--
------------------------------------------------------------------------------------
validateEntries entries names =
foldl' (\bs (v,st) ->
--let st' = "maintenance works in "++ st
if v >= 0 then bs
else (Right ("The value entered for "++ st ++ " is not valid"))) (Left uevls) evals
where evals = zip (map entVal entries) names
(uevls,_) = unzip evals
-------------------------------------------------------------------------------------
-- advanced options box for the display
--- tis shoulw be loaded from settings
advOptionsBox :: G.WindowClass window => window -> IO G.VBox
advOptionsBox win = do
vbox <- G.vBoxNew False 4
----
okButton <- G.buttonNewFromStock G.stockOk
cancelButton <- G.buttonNewFromStock G.stockCancel
bottomBox <- G.hBoxNew False 2
sep <- G.hSeparatorNew
mapM_ (\b -> G.boxPackEnd bottomBox b G.PackNatural 2) [okButton,cancelButton]
----
G.on cancelButton G.buttonActivated $ G.widgetDestroy win
pms <- getInputPrms
case pms of
Right advpms -> do
[sdEntry,aMxEnt, aMnEnt,mTrdEnt] <- sequence $ replicate 4 G.entryNew
let entries = [sdEntry,aMxEnt, aMnEnt,mTrdEnt]
mapM_ (\ent -> do
G.entrySetWidthChars ent 4
G.entrySetMaxLength ent 4) entries
let values = [searchDepth advpms, alignMax advpms, alignMin advpms, minTrend advpms]
mapM (uncurry G.entrySetText) $ zip entries (map show values)
let sdText = "Determines the number of refinements to parameters."
let maxTxt = "The maximum number of adjacent chains to align."
let minTxt = "The minimum number of adjacent chains to align."
let trdTxt = "The minimum number of points to which a trend can be fitted."
buttons <- mapM G.buttonNewWithLabel $ replicate 4 "What is This"
mapM_ (uncurry onButtDo) $ zip buttons [sdText,maxTxt,minTxt,trdTxt]
let strings = [" Search dept ", "Alignment maximum ","Alignment minimum ", "Trend minimum " ]
otheBoxes <- mapM (\(str,w) -> labelLeftofWidgetE (str++" ") 2 w True) $ zip strings buttons
let hBoxes = otheBoxes
mapM_ (\(b,w) -> G.boxPackEnd b w G.PackNatural 2) $ zip hBoxes entries
tableWithList <- tableWithWidgetList True hBoxes True 3
G.boxPackStart vbox tableWithList G.PackNatural 4
mapM_ (ioButtAct okButton advpms entries) [strings]
---
Left str -> print str
G.boxPackEnd vbox bottomBox G.PackNatural 0
G.boxPackEnd vbox sep G.PackNatural 2
return vbox
where
onButtDo butt str = G.on butt G.buttonActivated $ runMsgDialog Nothing str Info
ioButtAct okButton advpms entries strings = do
G.on okButton G.buttonActivated $ do
--sdE <- G.entryGetText sdEntry [sdEntry,aMxEnt, aMnEnt,mTrdEnt]
entered <- mapM G.entryGetText entries
case validateEntries entered strings of
Left [ev,aMx,aMn,mTd] -> do
updateSDepth ev advpms
updateAlignMax aMx advpms
updateAlignMin aMn advpms
updateMinTrend mTd advpms
Right string -> runMsgDialog Nothing string Error
-- advanced option window
advancedOptionsWin :: IO G.Window
advancedOptionsWin = do
win <- G.windowNew
opsBox <- advOptionsBox win
G.set win [G.containerChild G.:= opsBox]
G.widgetShow opsBox
return win
--- dialog to edit the selected list
--drawingCanvas <- getDrawingCanvas tabRef -- the drawing canvas --
-- openEditDialog :: [String] -> IO ([String], Bool)
openEditDialog comboRef detailsCombo detailsListRef inputBuffer = do
(selList,_,_) <- readIORef detailsListRef
let len = length selList
if len < 1 then
runMsgDialog Nothing "There is nothing in the list to edit" Info
else
G.dialogNew >>= \dia -> do
if len > 4 then G.widgetSetSizeRequest dia (-1) 250 else return ()
deleteRef <- newIORef ([],True)
table <- G.tableNew len 1 True
-- add the table to a scrolled window
selectedScrollWin <- vScrolledWinWithWgtList [table] VScroll
-- pack stuff to the table let
let selectedList = map display selList
cbList <- mapM G.checkButtonNewWithLabel selectedList
mapM_ (handleForCbuttons deleteRef) (zip selectedList cbList)
let list = zip cbList [0..]
mapM_ (\(bu, x) -> G.tableAttachDefaults table bu 0 1 x (x+1)) list
-- add the scrolled window to the upper part of the dailog
G.dialogGetUpper dia >>= \vbox -> do
instructionLabel <- G.labelNew (Just " Select Conditions to remove " )
G.boxPackStart vbox instructionLabel G.PackNatural 3
G.boxPackStart vbox selectedScrollWin G.PackGrow 2
G.dialogGetActionArea dia >>= \hbox -> -- do
mapM G.buttonNewWithLabel ["Select All", "Remove Selected"] >>=
\buttons -> do
G.on (buttons !! 0) G.buttonActivated $ do
mapM_ (\cb -> G.toggleButtonSetActive cb True) cbList
G.on (buttons !! 1) G.buttonActivated $ do
readIORef deleteRef >>= \(toRemoveList,clear) -> do -- inputBuffer
if clear then do
--mapM_ print toRemoveList
if null toRemoveList then
return () -- do nothing detailsListRef inputBuffer
else do
G.textBufferSetText inputBuffer ""
--
let selListNew = removeSel display toRemoveList selList
--
G.textBufferGetEndIter inputBuffer >>= \iter -> do
let toBuffer = G.textBufferInsert inputBuffer iter
mapM_ (\st -> toBuffer (display st ++"\n")) selListNew
modifyIORef detailsListRef (\(_,xs,ys) -> (selListNew ,xs,ys))
--
else do
G.textBufferSetText inputBuffer ""
--clearComboList comboRef detailsCombo
modifyIORef detailsListRef (\(_,xs,ys) -> ([],xs,ys))
--
G.widgetDestroy dia
--
mapM_ (\b -> G.boxPackEnd hbox b G.PackNatural 1) buttons
--
G.widgetShowAll dia
where
removeSel f [] ys = ys
removeSel f (x:xs) ys = removeSel f xs (filter ((x /=) . f ) ys)
--
handleForCbuttons delRef (string , cb) =
G.on cb G.toggled $ do
G.toggleButtonGetActive cb >>= \isSelected ->
if isSelected then do
modifyIORef delRef (\(xs,_) -> (string : xs,True))
else
modifyIORef delRef (\(xs,_) ->
let ys = delete string xs in
(ys, not $ null ys))
----------------------------------------------------------------------------------------------
-- set preview display
fillPreviewBox :: G.VBox -> PreviewParms -> IORef [(String,DrawRef)] -> IO ()
fillPreviewBox pBox pprms drawRefList = do
--wrt get the top part: a horizontal box with two combo boxes and
-- two buttons, as well as a radio button group to choose whether
-- to view available schemes or sections
optionsBox <- G.hBoxNew False 0
sep <- G.hSeparatorNew
--[lframe ,rframe] <- sequence . replicate 2 $ G.hBoxNew False 2
--[schmRButt, sectRButt] <- mapM G.radioButtonNewWithLabel ["Schemes","Sections"]
--------- **** need handles for schmRButt and sectRButt
-- output these buttons in a vertical table
--rButtstable <- tableWithWidgetList False [schmRButt, sectRButt] True 3
--
chainEntry <- G.entryNew
mapM_ (\ent -> do
G.entrySetWidthChars ent 4
G.entrySetMaxLength ent 4) [chainEntry]
-- let buttLables = ["Add selection","Show subsections","Show all","Analyse selected subsections"]
let buttLables = ["Add selection","Show subsections","Add all","Analyse selected subsections"]
[lAnalButt, addButt, remButt,stackButt] <- mapM G.buttonNewWithLabel buttLables
-- flip (horizontalWidgetList True) False
G.widgetSetSensitive optionsBox False
--G.containerAdd rframe rbox
sectsRef <- newIORef [] -- an IOref for defects to be used by the clearAdd function
drawRef <- newIORef emptyDrawRwf -- emptyDrawRwf
indexRef <- newIORef [] -- ^ the indexes in the notebook
-- HANDLE FOR STAKING -----------
G.on stackButt G.buttonActivated $ do
drf <- readIORef drawRef
let ln = length ( chnLabel drf)
addedChains <- G.entryGetText chainEntry >>= return . entVal
if all (> 0) [ln , addedChains] then do
let name = caption drf
let fromTo from to = myTake to . drop from
let currData = fromTo (currChain drf) (addChain drf) (chnLabel drf)
let range = " chains" ++ (head currData) ++ " to " ++ last currData
wrtFun pprms (name ++ range)
else
return () -- a message here?
--avlLabel <- G.labelNew (Just "Available conditions/schemes: ")
[avlCombo,sectionsCombo] <- sequence $ replicate 2 G.comboBoxNewText
----- add options to the avlCombo
----- get the list for avlCombo by checking to see what ahs been extracted
----- The conditions alaready extracted, but not necessarily, analysed, are added to the list
----- The same is done for available schemes
--let extract = (checkIfExtracted (\_ -> return ())) `seq` getAlreadyExtracted
getAlreadyExtracted True >>= mapM_ (G.comboBoxAppendText avlCombo)
G.on avlCombo G.changed $ handleForCondComboSelection sectsRef avlCombo sectionsCombo
avlBox <- labelLeftofWidget "Extracted: " avlCombo False
G.widgetSetSizeRequest sectionsCombo 130 (-1)
sectBox <- labelLeftofWidget "Sections: " sectionsCombo False
-- now pack the boxes at the top
comboBoxes <- tableWithWidgetList False [avlBox,sectBox] False 4
G.set comboBoxes [G.tableChildXPadding avlBox G.:= 2]
-- now pack the bottom bit, omitting the external option for the time being
mapM_ (\w -> G.boxPackEnd optionsBox w G.PackNatural 3) [lAnalButt,stackButt]
G.boxPackStart optionsBox chainEntry G.PackNatural 2
--G.boxPackStart topBox sectBox G.PackGrow 3
mapM_ (\t -> G.boxPackStart optionsBox t G.PackNatural 2) [addButt, remButt]
---
--------------------------------------------------------
------ now get the bottom notebook
(_,ntbk) <- notebookWithScrollWin False ([] :: [(G.VBox,String)]) False
-- now handle selection of sections using, placing the chains in the notebook
let sensAndHandles = (optionsBox,chainEntry,addButt, remButt,lAnalButt )
G.on sectionsCombo G.changed $ do
sectComboHandle ntbk indexRef drawRef avlCombo sectionsCombo sensAndHandles
-- handle for local analysis
--G.on lAnalButt G.buttonActivated $ lAnalButtHandle drawRef pprms True
G.on stackButt G.buttonActivated $ lAnalButtHandle drawRef pprms False
--------------------------------------------------------------------------------------
-- packing into the box for display
G.boxPackStart pBox comboBoxes G.PackNatural 3
G.boxPackStart pBox optionsBox G.PackNatural 3
G.boxPackStart pBox sep G.PackNatural 0
G.boxPackStart pBox ntbk G.PackGrow 0
G.widgetShowAll pBox
where
handleForCondComboSelection cRef condCombo sectsCombo = do
-- will need to put options for sections or scehmes here
mtext <- G.comboBoxGetActiveText condCombo
case mtext of
Just text -> do
-- add options to the sections combo
let defectCR = takeWhile (/= ' ') text
let outfile = "./Defects/"++"out"++ defectCR ++".txt"
fileExists <- doesFileExist outfile
if fileExists then do
-- let extractSects = map (snd . break isDigit . fst)
--let extractSections = do
getSectionsAndSorrogateS outfile >>= clearAdd cRef sectsCombo
else do
let string = "Data for "++ defectCR ++ " have not been \
\extracted. Would you like to extact them now?"
--let fileName = (show defect) ++".txt"
runDecisionMessageWindow Nothing string (return ())
Nothing -> return ()
-- handle for sections combos (need to update the notebook here)
sectComboHandle ntbk indRef dref avlCombo sectionsCombo opts = do
--let title = maybe "" id $G.comboBoxGetActiveText avlCombo
defectCR <- G.comboBoxGetActiveText avlCombo >>= return . maybe "" (takeWhile isAlphaNum)
let (optsBox,chnEnt,addButt, remButt,lAnalButt ) = opts
let outFile = "./Defects/"++"out"++ defectCR ++".txt"
validOption <- doesFileExist outFile
if validOption then do
--print "enter valid file"
mtext <- G.comboBoxGetActiveText sectionsCombo
case mtext of
Just text -> do
canvas <- getDrawingCanvas (Just dref)
---------- sensetise and respond to ---------------------
G.widgetSetSensitive optsBox True
-- handle for add chain
G.on addButt G.buttonActivated $ do
G.entryGetText chnEnt >>= \s ->
modifyIORef dref (updateAddChain True $ entVal s)
G.widgetQueueDraw canvas
-- handle for remove chain
G.on remButt G.buttonActivated $ do
G.entryGetText chnEnt >>= \s ->
modifyIORef dref (updateAddChain False $ entVal s)
G.widgetQueueDraw canvas
----------------------------------------------------------
let (snm, srg) = span isAlphaNum text
let sectSrg' = words srg -- dropWhile (not . isDigit) srg
let srg = if length sectSrg' <= 1 then "" else (last sectSrg')
--chD <- getSectionData sname srg outFile -- >>= \ -> do -- liftM unzip .
(bCD,dds) <- getSectionData snm srg outFile >>= liftM unzip . mapMPair G.buttonNewWithLabel
modifyIORef dref (updateDrawData dds)
mapM G.buttonGetLabel bCD >>= modifyIORef dref . curryRev updatePtsLabel
let title = defectCR ++ ": "++text
modifyIORef dref (updateCaption title)
mapM_ (updatePlot canvas dref) (zip bCD [0 .. ])
--
let ff = onSwith dref
G.hBoxNew False 0 >>= add2nbk indRef title ntbk canvas ff dref bCD -- butts
--print "not boos houls have been added"
Nothing -> print "No selection recorded for sectionCombo"
else return ()
where
---
curryRev :: (a -> b -> c) -> (a -> (b -> c))
curryRev f a = f a
-- actions to do on a swith page or a delete
onSwith ref i = do -- switch
dlist <- readIORef drawRefList
modifyIORef ref (\_ -> snd (dlist !! i))
readIORef drawRefList >>= print . show . length
--print ("page: " ++ show i)
--
mapMPair :: Monad m => (a -> m b) -> [(a,c)] -> m [(b,c)]
mapMPair f xs = sequence [liftM2 (,) (f a) (return c) | (a,c) <- xs ]
-- update the values to plot
updatePlot canvas dref (button, index) =
G.on button G.buttonActivated $ do
modifyIORef dref (updateCurrChain index)
updateDrawingArea canvas dref >> return ()
--
setDispFrame widget frame =
G.set frame [G.containerBorderWidth G.:= 0, G.frameLabelYAlign G.:= 0.5,
G.frameLabelXAlign G.:= 0.5,G.containerChild G.:= widget]
--
add2nbk indexRef tabTitle noteb canvas ff dref buttons rHBox = do
lHBox <- G.hBoxNew False 0
--lVBox <- G.vBoxNew False 1
[chainsFrame,groupsFrame] <- sequence $ replicate 2 G.frameNew
vsep <- G.vSeparatorNew
if null buttons then
-- message here that there is nothing to add
return ()
else do
buttSclArea <- vScrolledWinWithWgtList buttons VScroll
---
G.boxPackStart lHBox buttSclArea G.PackNatural 0
G.boxPackStart lHBox vsep G.PackNatural 0
G.boxPackEnd lHBox canvas G.PackGrow 1
---
let fs = filter ((/= tabTitle) . fst)
readIORef dref >>= \dr -> modifyIORef drawRefList ((++ [(tabTitle,dr)]) . fs)
---
setDispFrame lHBox chainsFrame
--- note the results go in rbox
--print "notebook should be added"
setDispFrame rHBox groupsFrame
hPanedArea groupsFrame chainsFrame 0 >>=
noteBookAddWidget noteb tabTitle indexRef (Just drawRefList) ff
G.widgetQueueDraw canvas
--- handle for local analysis
lAnalButtHandle :: IORef DrawRef -> PreviewParms -> Bool -> IO ()
lAnalButtHandle drwRef pprms allSect = do
[str1,str2] <- mapM G.entryGetText [yrsEnt pprms, distEnt pprms]
let prt = wrtFun pprms
let fromTo from to = myTake to . drop from
let datYrs a b = if allSect then unzip . map unzip else unzip . map unzip . fromTo a b
negSlope <- G.toggleButtonGetActive (nSpopes pprms)
case (validateEntries [str1,str2] ["years","distance"]) of
Left [e1,e2] -> do
-- do the analysis on the selected block
dr <- readIORef drwRef
--let n = lengt (chnLabel dr)
let (yr,dst,ns) = (fromIntegral e1, fromIntegral e2,negSlope)
let (yrs, dat) = datYrs (currChain dr) (addChain dr) (drawData dr)
let chns = if allSect then (chnLabel dr) else fromTo (currChain dr) (addChain dr) (chnLabel dr)
let title = caption dr
let title' = filter isAlphaNum title
let jt = Just ("Analysing "++ title)
jtt <- G.labelNew jt
let writr = G.labelSetText jtt
let anal = analyseData drwRef yr dst ns prt dat yrs chns title'
let anal' = forkProcessWithScroll (Just jtt) writr anal Nothing
proceedAfterConsent negSlope title (anal' >> return ())
Right string ->
runMsgDialog Nothing string Error
where
---- need to remove the analysis (should only
analyseData drwRef yr dist nslp pf daTa yrs chains title = do
inputParms <- getInputPrms
case inputParms of
Right iprs -> do
g <- newStdGen
let dpt = searchDepth iprs -- search depth
let aMx = alignMax iprs -- maximum number of chains to align
let aMn = alignMin iprs -- minimum number of chains to align
let mTd = minTrend iprs -- minimum number of points to trend
--- use a depth of 5 instead of in excess of 100 for more powerful machines
let anl _ = return [] -- mml2DsGD g 100 yr dist (not nslp) aMx aMn mTd pf
let resultDir = "./LocalAnalyais"
let chnn = if null chains then "" else takeWhile (/= '-') (head chains) ++"--" ++ takeWhile (/= '-') (last chains)
let resultFile = resultDir++('/' : title)++".txt"
let resultRecFile = resultDir++"/schemeResults.txt"
let chainsHeader = L.pack "chains:"-- L.pack "-------CHAINS---------\n"
let yearsHeader = L.pack "years:"-- L.pack "-------YEARS---------\n"
let rHdr = L.pack "-------RESULTS--------\n"
let chans = chainsHeader <> (L.pack (printElm chains)) <> (L.pack "\n")
--let yrsSS = L.intercalate (L.pack "\n") $ map (L.pack . printElm) yrs
let yrsSS = (L.pack . printElm) (take 1 yrs)
let yrss = yearsHeader <> yrsSS <> (L.pack "\n")
--- debug "./LocalAnalyais/schemeResults.txt"
let dataVals = L.pack (printElm $ concat daTa)
let dataa = (L.pack "data:") <> dataVals <> (L.pack "\n")
print (show $ concat daTa)
--print $ show [show dpt, show yr, show dist, show nslp, show aMx, show aMn, show mTd ]
-- calculat the results and logg it ----(rHdr <>) .
yn <- doesDirectoryExist resultDir
if yn then return () else createDirectory resultDir
let !prtResults = ((chans <> yrss) <>) . (dataa <> ) . results2BS'
--let chnn = if null chains then "" else takeWhile (/= '-') (head chains) ++"--" ++ takeWhile (/= '-') (last chains)
-- print (show anl)
anl daTa >>= \rlt -> do
(L.writeFile resultFile . prtResults) rlt
(modifyIORef drwRef . omod2derf) rlt
let record = L.snoc (L.pack (title )) '\n' --- ++":"++chnn
L.appendFile resultRecFile record
--addSchemeResults (L.pack title) resultRecFile
-- print . show -- mapM_ (L.writeFile resultFile . prtResults)
Left string -> print ("error reading parameter file: "++string)
--- infp for dialog
proceedAfterConsent ng capt anal = do
let mainStr = "You have chosen to analyse "++capt
let endStr = if ng then
", and have opted to include negative slopes. Are\
\ you sure you want to include negative slopes?"
else
". Do you wish to proceed?"
runDecisionMessageWindow Nothing (mainStr++endStr) anal
---
omod2derf :: [([(OModel, ([Double], [Int]))], [Int])] -> DrawRef -> DrawRef
omod2derf xs = updateResults rr
where ks = concatMap (concatMap (fst . snd) . fst) xs
rr = Results 0 0 0 [] 0 ks []
--
addSchemeResults :: L.ByteString -> FilePath -> IO ()
addSchemeResults result fileName = do
-- have to change the result filename so it reflects the chains in the schemeas well
schmResults <- L.readFile fileName >>= return . L.lines
print "got here"
if any (== result) schmResults then
return ()
else
L.appendFile fileName result
----------------------------------------------------------------------------------------------
-- End of Network Level Dialog Construction and related windows
----------------------------------------------------------------------------------------------}
| rawlep/EQS | sourceCode/InterfaceQAWindows.hs | mit | 54,692 | 0 | 41 | 18,794 | 6,769 | 3,398 | 3,371 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
module Handlers where
import Greet
import Servant.Server
import Servant.API
import GHC.Generics
import Data.Aeson
import Data.Monoid
import Data.Proxy
import Data.Text
-- Server-side handlers.
--
-- There's one handler per endpoint, which, just like in the type
-- that represents the API, are glued together using :<|>.
--
-- Each handler runs in the 'EitherT (Int, String) IO' monad.
handlers :: Server HaskApi
handlers = helloH :<|> postGreetH :<|> deleteGreetH
where helloH name Nothing = helloH name (Just False)
helloH name (Just False) = return . Greet $ "Hello, " <> name
helloH name (Just True) = return . Greet . toUpper $ "Hello, " <> name
postGreetH greet = return greet
deleteGreetH _ = return ()
-- Turn the handlers into a WAI app. 'serve' is provided by servant,
-- more precisely by the Servant.Server module. | mooreniemi/haskapi | handlers.hs | mit | 1,050 | 0 | 10 | 201 | 184 | 103 | 81 | 22 | 3 |
module Main where
import System.Exit (exitFailure)
import Test.QuickCheck
import LynCrypt
{-
tests = [
-- Test the chinese remainder theorem
\xs -> map (\(a,b) -> (chineseRemainder a b) == a `mod` b),
-- Test to see if the decryption function is an inverse
-- of the encryption function with all k
\xs n k -> do
(shares,m0s) <- makeShares xs n k
decrypted <- decryptShares shares m0s
return $ xs == decrypted,
-- Test to see if the decryption function is an inverse
-- of the encryption function iff there are k or more shares.]
-}
main = do
--mapM_ quickCheck tests
exitFailure
| Sintrastes/LynCrypt | tests/tests.hs | mit | 644 | 0 | 6 | 168 | 32 | 20 | 12 | 6 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module DailyFeeling.Common.Types (Mood(..), Entry(..)) where
import GHC.Generics
import Data.Aeson
data Mood = Happy
| Normal
| Sad deriving (Generic, Show, Read, Ord, Eq)
instance ToJSON Mood
instance FromJSON Mood
data Entry = Entry { mood :: Mood
, name :: String
, description :: String
} deriving (Generic, Show, Read)
instance ToJSON Entry
instance FromJSON Entry
| Denommus/DailyFeeling | Common/DailyFeeling/Common/Types.hs | mit | 497 | 0 | 8 | 156 | 140 | 80 | 60 | 15 | 0 |
-- 1
f :: Int -> String
f = undefined
g :: String -> Char
g = undefined
h :: Int -> Char
h = g . f
-- 2
data A
data B
data C
q :: A -> B
q = undefined
w :: B -> C
w = undefined
e :: A -> C
e = w . q
-- 3
data X
data Y
data Z
xz :: X -> Z
xz = undefined
yz :: Y -> Z
yz = undefined
xform :: (X, Y) -> (Z, Z)
xform (x, y) = (xz x, yz y)
-- 4
munge :: (x -> y) -> (y -> (w,z)) -> x -> w
{-
my 'brute force' approach:
munge xToY yToWZ x = fst (yToWZ (xToY x))
or more elegant composition:
-}
munge f g = fst . g . f
| Numberartificial/workflow | haskell-first-principles/haskell-from-first-principles-master/05/05.08.10-type-kwon-do.hs | mit | 524 | 0 | 9 | 156 | 246 | 142 | 104 | -1 | -1 |
import Test.Tasty
import IntMap
import List
import Map
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [listProps, mapProps, intMapProps]
| phadej/range-set-list | tests/Tests.hs | mit | 176 | 0 | 6 | 29 | 57 | 32 | 25 | 8 | 1 |
module J2S.AI.Random
( rand
) where
import Control.Monad.Random
import qualified Data.Foldable as F
import J2S.AI.Types
-- | A 'Player' strategy that choose randomly one of the available action.
rand :: (ListableActions b, MonadRandom m)
=> Strategy m b
rand = uniform . fmap fst . F.toList . listActions
| berewt/J2S | src/J2S/AI/Random.hs | mit | 345 | 0 | 8 | 88 | 80 | 47 | 33 | 8 | 1 |
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RecordWildCards, ScopedTypeVariables, OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.LogRef
-- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GNU-GPL
--
-- Maintainer : <maintainer at leksah.org>
-- Stability : provisional
-- Portability : portable
--
--
-- |
--
---------------------------------------------------------------------------------
module IDE.LogRef (
nextError
, previousError
, nextBreakpoint
, previousBreakpoint
, markLogRefs
, unmarkLogRefs
, defaultLineLogger
, defaultLineLogger'
, logOutputLines
, logOutputLines_
, logOutputLinesDefault_
, logOutput
, logOutputDefault
, logOutputPane
, logOutputForBuild
, logOutputForBreakpoints
, logOutputForSetBreakpoint
, logOutputForSetBreakpointDefault
, logOutputForLiveContext
, logOutputForLiveContextDefault
, logOutputForHistoricContext
, logOutputForHistoricContextDefault
, selectRef
, setBreakpointList
, showSourceSpan
, srcSpanParser
) where
import Graphics.UI.Gtk
import Control.Monad.Reader
import Text.ParserCombinators.Parsec.Language
import Text.ParserCombinators.Parsec hiding(Parser)
import qualified Text.ParserCombinators.Parsec.Token as P
import IDE.Core.State
import IDE.TextEditor
import IDE.Pane.SourceBuffer
import qualified IDE.Pane.Log as Log
import IDE.Utils.Tool
import System.FilePath (equalFilePath)
import Data.List (partition, stripPrefix, elemIndex, isPrefixOf)
import Data.Maybe (catMaybes, isJust)
import System.Exit (ExitCode(..))
import System.Log.Logger (debugM)
import IDE.Utils.FileUtils(myCanonicalizePath)
import IDE.Pane.Log (getDefaultLogLaunch, IDELog(..), getLog)
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import Data.Conduit ((=$))
import IDE.Pane.WebKit.Output(setOutput)
import Data.IORef (atomicModifyIORef, IORef, readIORef)
import Data.Text (Text)
import Control.Applicative ((<$>))
import qualified Data.Text as T
(length, stripPrefix, isPrefixOf, unpack, unlines, pack, null)
import Data.Monoid ((<>))
import qualified Data.Set as S (notMember, member, insert, empty)
import Data.Set (Set)
import System.FilePath.Windows ((</>))
import Data.Sequence (ViewR(..), Seq)
import qualified Data.Foldable as F (toList, forM_)
import qualified Data.Sequence as Seq
(null, singleton, viewr, reverse, fromList)
showSourceSpan :: LogRef -> Text
showSourceSpan = T.pack . displaySrcSpan . logRefSrcSpan
selectRef :: Maybe LogRef -> IDEAction
selectRef (Just ref) = do
mbBuf <- selectSourceBuf (logRefFullFilePath ref)
case mbBuf of
Just buf -> markRefInSourceBuf buf ref True
Nothing -> liftIO . void $ debugM "leksah" "no buf"
log :: Log.IDELog <- Log.getLog
maybe (return ()) (Log.markErrorInLog log) (logLines ref)
selectRef Nothing = return ()
forOpenLogRefs :: (LogRef -> IDEBuffer -> IDEAction) -> IDEAction
forOpenLogRefs f = do
logRefs <- readIDE allLogRefs
allBufs <- allBuffers
F.forM_ logRefs $ \ref -> do
let fp = logRefFullFilePath ref
fpc <- liftIO $ myCanonicalizePath fp
forM_ (filter (\buf -> case fileName buf of
Just fn -> equalFilePath fpc fn
Nothing -> False) allBufs) (f ref)
markLogRefs :: IDEAction
markLogRefs =
forOpenLogRefs $ \logRef buf -> markRefInSourceBuf buf logRef False
unmarkLogRefs :: IDEAction
unmarkLogRefs =
forOpenLogRefs $ \logRef (IDEBuffer {sourceView = sv}) -> do
buf <- getBuffer sv
removeTagByName buf (T.pack $ show (logRefType logRef))
setBreakpointList :: Seq LogRef -> IDEAction
setBreakpointList breaks = do
ideR <- ask
unmarkLogRefs
errs <- readIDE errorRefs
contexts <- readIDE contextRefs
modifyIDE_ (\ide -> ide{allLogRefs = errs <> breaks <> contexts})
setCurrentBreak Nothing
markLogRefs
triggerEventIDE BreakpointChanged
return ()
addLogRefs :: Seq LogRef -> IDEAction
addLogRefs refs = do
ideR <- ask
unmarkLogRefs
modifyIDE_ (\ide -> ide{allLogRefs = allLogRefs ide <> refs})
setCurrentError Nothing
markLogRefs
triggerEventIDE (ErrorChanged False)
triggerEventIDE BreakpointChanged
triggerEventIDE TraceChanged
return ()
next :: (IDE -> Seq LogRef)
-> (IDE -> Maybe LogRef)
-> (Maybe LogRef -> IDEAction)
-> IDEAction
next all current set = do
all <- F.toList <$> readIDE all
current <- readIDE current
let isCurrent = (== current) . Just
case dropWhile isCurrent (dropWhile (not . isCurrent) all) <> all of
(n:_) -> do
set (Just n)
selectRef (Just n)
_ -> return ()
nextError :: IDEAction
nextError = next errorRefs currentError setCurrentError
previousError :: IDEAction
previousError = next (Seq.reverse . errorRefs) currentError setCurrentError
nextBreakpoint :: IDEAction
nextBreakpoint = next breakpointRefs currentBreak setCurrentBreak
previousBreakpoint :: IDEAction
previousBreakpoint = next (Seq.reverse . breakpointRefs) currentBreak setCurrentBreak
nextContext :: IDEAction
nextContext = next contextRefs currentContext setCurrentContext
previousContext :: IDEAction
previousContext = next (Seq.reverse . contextRefs) currentContext setCurrentContext
lastContext :: IDEAction
lastContext = do
contexts <- readIDE contextRefs
currentContext <- readIDE currentContext
case contexts of
(Seq.viewr -> _ :> l) -> do
setCurrentContext $ Just l
selectRef $ Just l
_ -> return ()
fixColumn c = max 0 (c - 1)
srcPathParser :: CharParser () FilePath
srcPathParser = try (do
symbol "dist/build/tmp-" -- Support for cabal haddock
many digit
char '/'
many (noneOf ":"))
<|> many (noneOf ":")
srcSpanParser :: CharParser () SrcSpan
srcSpanParser = try (do
filePath <- srcPathParser
char ':'
char '('
beginLine <- int
char ','
beginCol <- int
char ')'
char '-'
char '('
endLine <- int
char ','
endCol <- int
char ')'
return $ SrcSpan filePath beginLine (fixColumn beginCol) endLine (fixColumn endCol))
<|> try (do
filePath <- srcPathParser
char ':'
line <- int
char ':'
beginCol <- int
char '-'
endCol <- int
return $ SrcSpan filePath line (fixColumn beginCol) line (fixColumn endCol))
<|> try (do
filePath <- srcPathParser
char ':'
line <- int
char ':'
col <- int
return $ SrcSpan filePath line (fixColumn col) line (fixColumn col))
<?> "srcSpanParser"
data BuildOutput = BuildProgress Int Int FilePath
| DocTestFailure SrcSpan Text
buildOutputParser :: CharParser () BuildOutput
buildOutputParser = try (do
char '['
n <- int
whiteSpace
symbol "of"
whiteSpace
total <- int
char ']'
whiteSpace
symbol "Compiling"
many (noneOf "(")
char '('
whiteSpace
file <- many (noneOf ",")
char ','
many anyChar
return $ BuildProgress n total file)
<|> try (do
symbol "###"
whiteSpace
symbol "Failure"
whiteSpace
symbol "in"
whiteSpace
file <- many (noneOf ":")
char ':'
line <- int
char ':'
whiteSpace
text <- T.pack <$> many anyChar
return $ DocTestFailure (SrcSpan file line 7 line (T.length text - 7)) $ "Failure in " <> text)
<?> "buildOutputParser"
data BuildError = BuildLine
| EmptyLine
| ErrorLine SrcSpan LogRefType Text
| WarningLine Text
| OtherLine Text
buildErrorParser :: CharParser () BuildError
buildErrorParser = try (do
char '['
int
symbol "of"
int
char ']'
many anyChar
return BuildLine)
<|> try (do
whiteSpace
span <- srcSpanParser
char ':'
whiteSpace
refType <- try (do
symbol "Warning:"
return WarningRef)
<|> return ErrorRef
text <- T.pack <$> many anyChar
return (ErrorLine span refType text))
<|> try (do
whiteSpace
eof
return EmptyLine)
<|> try (do
whiteSpace
symbol "Warning:"
text <- T.pack <$> many anyChar
return (WarningLine ("Warning:" <> text)))
<|> try (do
text <- T.pack <$> many anyChar
eof
return (OtherLine text))
<?> "buildLineParser"
data BreakpointDescription = BreakpointDescription Int SrcSpan
breaksLineParser :: CharParser () BreakpointDescription
breaksLineParser = try (do
char '['
n <- int
char ']'
whiteSpace
many (noneOf " ")
whiteSpace
span <- srcSpanParser
return (BreakpointDescription n span))
<?> "breaksLineParser"
setBreakpointLineParser :: CharParser () BreakpointDescription
setBreakpointLineParser = try (do
symbol "Breakpoint"
whiteSpace
n <- int
whiteSpace
symbol "activated"
whiteSpace
symbol "at"
whiteSpace
span <- srcSpanParser
return (BreakpointDescription n span))
<?> "setBreakpointLineParser"
lexer = P.makeTokenParser emptyDef
lexeme = P.lexeme lexer
whiteSpace = P.whiteSpace lexer
hexadecimal = P.hexadecimal lexer
symbol = P.symbol lexer
identifier = P.identifier lexer
colon = P.colon lexer
int = fromInteger <$> P.integer lexer
defaultLineLogger :: IDELog -> LogLaunch -> ToolOutput -> IDEM Int
defaultLineLogger log logLaunch out = liftIO $ defaultLineLogger' log logLaunch out
defaultLineLogger' :: IDELog -> LogLaunch -> ToolOutput -> IO Int
defaultLineLogger' log logLaunch out =
case out of
ToolInput line -> appendLog' (line <> "\n") InputTag
ToolOutput line -> appendLog' (line <> "\n") LogTag
ToolError line -> appendLog' (line <> "\n") ErrorTag
ToolPrompt line -> do
unless (T.null line) $ void (appendLog' (line <> "\n") LogTag)
appendLog' (T.pack (concat (replicate 20 "- ")) <> "-\n") FrameTag
ToolExit ExitSuccess -> appendLog' (T.pack (replicate 41 '-') <> "\n") FrameTag
ToolExit (ExitFailure 1) -> appendLog' (T.pack (replicate 41 '=') <> "\n") FrameTag
ToolExit (ExitFailure n) -> appendLog' (T.pack (take 41 ("========== " ++ show n <> " " ++ repeat '=')) <> "\n") FrameTag
where
appendLog' = Log.appendLog log logLaunch
paneLineLogger :: IDELog -> LogLaunch -> ToolOutput -> IDEM (Maybe Text)
paneLineLogger log logLaunch out = liftIO $ paneLineLogger' log logLaunch out
paneLineLogger' :: IDELog -> LogLaunch -> ToolOutput -> IO (Maybe Text)
paneLineLogger' log logLaunch out =
case out of
ToolInput line -> appendLog' (line <> "\n") InputTag >> return Nothing
ToolOutput line -> appendLog' (line <> "\n") LogTag >> return (Just line)
ToolError line -> appendLog' (line <> "\n") ErrorTag >> return Nothing
ToolPrompt line -> do
unless (T.null line) $ void (appendLog' (line <> "\n") LogTag)
appendLog' (T.pack (concat (replicate 20 "- ")) <> "-\n") FrameTag
return Nothing
ToolExit ExitSuccess -> appendLog' (T.pack (replicate 41 '-') <> "\n") FrameTag >> return Nothing
ToolExit (ExitFailure 1) -> appendLog' (T.pack (replicate 41 '=') <> "\n") FrameTag >> return Nothing
ToolExit (ExitFailure n) -> appendLog' (T.pack (take 41 ("========== " ++ show n ++ " " ++ repeat '=')) <> "\n") FrameTag >> return Nothing
where
appendLog' = Log.appendLog log logLaunch
logOutputLines :: LogLaunch -- ^ logLaunch
-> (IDELog -> LogLaunch -> ToolOutput -> IDEM a)
-> C.Sink ToolOutput IDEM [a]
logOutputLines logLaunch lineLogger = do
log :: Log.IDELog <- lift $ postSyncIDE Log.getLog
results <- CL.mapM (postSyncIDE . lineLogger log logLaunch) =$ CL.consume
lift $ triggerEventIDE (StatusbarChanged [CompartmentState "", CompartmentBuild False])
return results
logOutputLines_ :: LogLaunch
-> (IDELog -> LogLaunch -> ToolOutput -> IDEM a)
-> C.Sink ToolOutput IDEM ()
logOutputLines_ logLaunch lineLogger = do
logOutputLines logLaunch lineLogger
return ()
logOutputLinesDefault_ :: (IDELog -> LogLaunch -> ToolOutput -> IDEM a)
-> C.Sink ToolOutput IDEM ()
logOutputLinesDefault_ lineLogger = do
defaultLogLaunch <- lift getDefaultLogLaunch
logOutputLines_ defaultLogLaunch lineLogger
logOutput :: LogLaunch
-> C.Sink ToolOutput IDEM ()
logOutput logLaunch = do
logOutputLines logLaunch defaultLineLogger
return ()
logOutputDefault :: C.Sink ToolOutput IDEM ()
logOutputDefault = do
defaultLogLaunch <- lift getDefaultLogLaunch
logOutput defaultLogLaunch
logOutputPane :: Text -> IORef [Text] -> C.Sink ToolOutput IDEM ()
logOutputPane command buffer = do
defaultLogLaunch <- lift getDefaultLogLaunch
result <- catMaybes <$> logOutputLines defaultLogLaunch paneLineLogger
unless (null result) $ do
new <- liftIO . atomicModifyIORef buffer $ \x -> let new = x ++ result in (new, new)
mbURI <- lift $ readIDE autoURI
unless (isJust mbURI) . lift . postSyncIDE . setOutput command $ T.unlines new
data BuildOutputState = BuildOutputState { log :: IDELog
, inError :: Bool
, inDocTest :: Bool
, errs :: [LogRef]
, testFails :: [LogRef]
, filesCompiled :: Set FilePath
}
-- Not quite a Monoid
initialState :: IDELog -> BuildOutputState
initialState log = BuildOutputState log False False [] [] S.empty
logOutputForBuild :: IDEPackage
-> Bool
-> Bool
-> C.Sink ToolOutput IDEM [LogRef]
logOutputForBuild package backgroundBuild jumpToWarnings = do
liftIO $ debugM "leksah" "logOutputForBuild"
log <- lift getLog
logLaunch <- lift Log.getDefaultLogLaunch
BuildOutputState {..} <- CL.foldM (readAndShow logLaunch) $ initialState log
ideR <- lift ask
liftIO $ postGUISync $ reflectIDE (do
allErrorLikeRefs <- readIDE errorRefs
triggerEventIDE (Sensitivity [(SensitivityError,not (Seq.null allErrorLikeRefs))])
let errorNum = length (filter isError errs)
let warnNum = length errs - errorNum
triggerEventIDE (StatusbarChanged [CompartmentState
(T.pack $ show errorNum ++ " Errors, " ++ show warnNum ++ " Warnings"), CompartmentBuild False])
return errs) ideR
where
readAndShow :: LogLaunch -> BuildOutputState -> ToolOutput -> IDEM BuildOutputState
readAndShow logLaunch state@BuildOutputState {..} output = do
ideR <- ask
let logPrevious (previous:_) = reflectIDE (addLogRef False backgroundBuild previous) ideR
logPrevious _ = return ()
liftIO $ postGUISync $ case output of
ToolError line -> do
let parsed = parse buildErrorParser "" $ T.unpack line
let nonErrorPrefixes = ["Linking ", "ar:", "ld:", "ld warning:"]
tag <- case parsed of
Right BuildLine -> return InfoTag
Right (OtherLine text) | "Linking " `T.isPrefixOf` text ->
-- when backgroundBuild $ lift interruptProcess
return InfoTag
Right (OtherLine text) | any (`T.isPrefixOf` text) nonErrorPrefixes ->
return InfoTag
_ -> return ErrorTag
lineNr <- Log.appendLog log logLaunch (line <> "\n") tag
case (parsed, errs) of
(Left e,_) -> do
sysMessage Normal . T.pack $ show e
return state { inError = False }
(Right ne@(ErrorLine span refType str),_) -> do
let ref = LogRef span package str Nothing (Just (lineNr,lineNr)) refType
root = logRefRootPath ref
file = logRefFilePath ref
fullFilePath = logRefFullFilePath ref
unless (fullFilePath `S.member` filesCompiled) $
reflectIDE (removeBuildLogRefs root file) ideR
when inError $ logPrevious errs
return state { inError = True
, errs = ref:errs
, filesCompiled = S.insert fullFilePath filesCompiled
}
(Right (OtherLine str1), ref@(LogRef span rootPath str Nothing (Just (l1,l2)) refType):tl) ->
if inError
then return state { errs = LogRef span rootPath
(if T.null str then line else str <> "\n" <> line)
Nothing
(Just (l1, lineNr))
refType
: tl
}
else return state
(Right (WarningLine str1),LogRef span rootPath str Nothing (Just (l1, l2)) isError : tl) ->
if inError
then return state { errs = LogRef span rootPath
(if T.null str then line else str <> "\n" <> line)
Nothing
(Just (l1, lineNr))
WarningRef
: tl
}
else return state
_ -> do
when inError $ logPrevious errs
return state { inError = False }
ToolOutput line ->
case (parse buildOutputParser "" $ T.unpack line, inDocTest, testFails) of
(Right (BuildProgress n total file), _, _) -> do
logLn <- Log.appendLog log logLaunch (line <> "\n") LogTag
reflectIDE (triggerEventIDE (StatusbarChanged [CompartmentState
(T.pack $ "Compiling " ++ show n ++ " of " ++ show total), CompartmentBuild False])) ideR
let root = ipdBuildDir package
fullFilePath = root </> file
reflectIDE (removeBuildLogRefs root file) ideR
when inDocTest $ logPrevious testFails
return state { inDocTest = False }
(Right (DocTestFailure span exp), _, _) -> do
logLn <- Log.appendLog log logLaunch (line <> "\n") ErrorTag
when inDocTest $ logPrevious testFails
return state { inDocTest = True
, testFails = LogRef span
package
exp
Nothing (Just (logLn,logLn)) TestFailureRef : testFails
}
(_, True, LogRef span rootPath str Nothing (Just (l1, l2)) refType : tl) -> do
logLn <- Log.appendLog log logLaunch (line <> "\n") ErrorTag
return state { testFails = LogRef span
rootPath
(str <> "\n" <> line)
Nothing (Just (l1,logLn)) TestFailureRef : tl
}
_ -> do
Log.appendLog log logLaunch (line <> "\n") LogTag
when inDocTest $ logPrevious testFails
return state { inDocTest = False }
ToolInput line -> do
Log.appendLog log logLaunch (line <> "\n") InputTag
return state
ToolPrompt line -> do
unless (T.null line) . void $ Log.appendLog log logLaunch (line <> "\n") LogTag
when inError $ logPrevious errs
when inDocTest $ logPrevious testFails
let errorNum = length (filter isError errs)
let warnNum = length errs - errorNum
case errs of
[] -> defaultLineLogger' log logLaunch output
_ -> Log.appendLog log logLaunch (T.pack $ "- - - " ++ show errorNum ++ " errors - "
++ show warnNum ++ " warnings - - -\n") FrameTag
return state { inError = False, inDocTest = False }
ToolExit _ -> do
let errorNum = length (filter isError errs)
warnNum = length errs - errorNum
when inError $ logPrevious errs
when inDocTest $ logPrevious testFails
case (errs, testFails) of
([], []) -> defaultLineLogger' log logLaunch output
_ -> Log.appendLog log logLaunch (T.pack $ "----- " ++ show errorNum ++ " errors -- "
++ show warnNum ++ " warnings -- "
++ show (length testFails) ++ " doctest failures -----\n") FrameTag
return state { inError = False, inDocTest = False }
--logOutputLines :: Text -- ^ logLaunch
-- -> (LogLaunch -> ToolOutput -> IDEM a)
-- -> [ToolOutput]
-- -> IDEM [a]
logOutputForBreakpoints :: IDEPackage
-> LogLaunch -- ^ loglaunch
-> C.Sink ToolOutput IDEM ()
logOutputForBreakpoints package logLaunch = do
breaks <- logOutputLines logLaunch (\log logLaunch out ->
case out of
ToolOutput line -> do
logLineNumber <- liftIO $ Log.appendLog log logLaunch (line <> "\n") LogTag
case parse breaksLineParser "" $ T.unpack line of
Right (BreakpointDescription n span) ->
return $ Just $ LogRef span package line Nothing (Just (logLineNumber, logLineNumber)) BreakpointRef
_ -> return Nothing
_ -> do
defaultLineLogger log logLaunch out
return Nothing)
lift . setBreakpointList . Seq.fromList $ catMaybes breaks
logOutputForSetBreakpoint :: IDEPackage
-> LogLaunch -- ^ loglaunch
-> C.Sink ToolOutput IDEM ()
logOutputForSetBreakpoint package logLaunch = do
breaks <- logOutputLines logLaunch (\log logLaunch out ->
case out of
ToolOutput line -> do
logLineNumber <- liftIO $ Log.appendLog log logLaunch (line <> "\n") LogTag
case parse setBreakpointLineParser "" $ T.unpack line of
Right (BreakpointDescription n span) ->
return $ Just $ LogRef span package line Nothing (Just (logLineNumber, logLineNumber)) BreakpointRef
_ -> return Nothing
_ -> do
defaultLineLogger log logLaunch out
return Nothing)
lift . addLogRefs . Seq.fromList $ catMaybes breaks
logOutputForSetBreakpointDefault :: IDEPackage
-> C.Sink ToolOutput IDEM ()
logOutputForSetBreakpointDefault package = do
defaultLogLaunch <- lift getDefaultLogLaunch
logOutputForSetBreakpoint package defaultLogLaunch
logOutputForContext :: IDEPackage
-> LogLaunch -- ^ loglaunch
-> (Text -> [SrcSpan])
-> C.Sink ToolOutput IDEM ()
logOutputForContext package loglaunch getContexts = do
refs <- catMaybes <$> logOutputLines loglaunch (\log logLaunch out ->
case out of
ToolOutput line -> do
logLineNumber <- liftIO $ Log.appendLog log logLaunch (line <> "\n") LogTag
let contexts = getContexts line
if null contexts
then return Nothing
else return $ Just $ LogRef (last contexts) package line Nothing (Just (logLineNumber, logLineNumber)) ContextRef
_ -> do
defaultLineLogger log logLaunch out
return Nothing)
lift $ unless (null refs) $ do
addLogRefs . Seq.singleton $ last refs
lastContext
contextParser :: CharParser () SrcSpan
contextParser = try (do
whiteSpace
symbol "Logged breakpoint at" <|> symbol "Stopped at"
whiteSpace
srcSpanParser)
<?> "historicContextParser"
logOutputForLiveContext :: IDEPackage
-> LogLaunch -- ^ loglaunch
-> C.Sink ToolOutput IDEM ()
logOutputForLiveContext package logLaunch = logOutputForContext package logLaunch (getContexts . T.unpack)
where
getContexts [] = []
getContexts line@(x:xs) = case parse contextParser "" line of
Right desc -> desc : getContexts xs
_ -> getContexts xs
logOutputForLiveContextDefault :: IDEPackage
-> C.Sink ToolOutput IDEM ()
logOutputForLiveContextDefault package = do
defaultLogLaunch <- lift getDefaultLogLaunch
logOutputForLiveContext package defaultLogLaunch
logOutputForHistoricContext :: IDEPackage
-> LogLaunch -- ^ loglaunch
-> C.Sink ToolOutput IDEM ()
logOutputForHistoricContext package logLaunch = logOutputForContext package logLaunch getContexts
where
getContexts line = case parse contextParser "" $ T.unpack line of
Right desc -> [desc]
_ -> []
logOutputForHistoricContextDefault :: IDEPackage
-> C.Sink ToolOutput IDEM ()
logOutputForHistoricContextDefault package = do
defaultLogLaunch <- lift getDefaultLogLaunch
logOutputForHistoricContext package defaultLogLaunch
| cocreature/leksah | src/IDE/LogRef.hs | gpl-2.0 | 27,303 | 0 | 30 | 9,555 | 7,285 | 3,554 | 3,731 | 584 | 22 |
#!/usr/bin/env runhaskell
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
module Main where
import System.Process
import System.Exit
import Text.Printf (printf)
import System.Environment (getArgs)
import qualified Data.Text.Internal.Lazy
import qualified Data.Text.Lazy
import Data.Time
import Text.Shakespeare.Text
import qualified Data.Text.Lazy.IO as TLIO
import Data.Text
timeCommand :: FilePath -> [String] -> IO (Double, (ExitCode, String, String))
timeCommand f a = do
start <- getCurrentTime
x <- readProcessWithExitCode f a []
end <- getCurrentTime
let t = diffUTCTime end start
return (realToFrac t, x)
dt :: Double -> Text
dt = Data.Text.pack . printf "%f"
data CommandResult = CommandResult {
runTime :: Double,
exitStatus :: ExitCode,
stdOut :: String,
stdErr :: String,
commandName :: String
} deriving (Show)
toCommandResult :: (Double, (ExitCode, String, String)) -> String -> CommandResult
toCommandResult (t, (ex, o, err)) c = CommandResult {
runTime=t, exitStatus = ex, stdOut = o, stdErr = err, commandName=c}
makeError :: CommandResult -> Data.Text.Internal.Lazy.Text
makeError cr@CommandResult {exitStatus = ExitFailure e} = [lt|<?xml version="1.0" encoding="UTF-8" ?>
<prtg>
<error>1</error>
<text>
Command Name: #{commandName cr}
Exit Status: #{e}
StdOut: #{stdOut cr}
StdErr: #{stdErr cr}
</text>
</prtg>
|]
makeError _ = [lt|Unknown Error|] -- Should never occur
isError :: CommandResult -> Bool
isError CommandResult {exitStatus = ExitFailure _} = True
isError _ = False
makeResult :: CommandResult -> Data.Text.Internal.Lazy.Text
makeResult cr = [lt|<result>
<channel>#{commandName cr}</channel>
<unit>TimeSeconds</unit>
<showChart>1</showChart>
<showTable>1</showTable>
<float>1</float>
<value>#{dt $ runTime cr}</value>
</result>
|]
makeResults :: [CommandResult] -> Data.Text.Internal.Lazy.Text
makeResults cr = [lt|<?xml version="1.0" encoding="UTF-8" ?>
<prtg>#{r}</prtg>
|]
where r = Prelude.foldl Data.Text.Lazy.append "" (Prelude.map makeResult cr)
cleanup :: String -> IO (ExitCode, String, String)
cleanup drive = readProcessWithExitCode "cmd" ["/c net use /delete /y " ++ drive] []
-- command line arguments, hostanme, drive letter to use while mapping, file to read without drive letter
go :: [String] -> IO ()
go [host, share, drive, fileName] = do --(host:(share:(drive:(fileName:[]))))
_ <- cleanup drive
x1 <- timeCommand "cmd" ["/c net use " ++ drive ++ " \\\\" ++ host ++ "\\" ++ share]
--print x1
let r1 = toCommandResult x1 "Map Share"
if isError r1 then
TLIO.putStr $ makeError r1
else do
x2 <- timeCommand "cmd" ["/c dir " ++ drive]
--print x2
let r2 = toCommandResult x2 "List Dir"
if isError r2 then
TLIO.putStr $ makeError r2
else do
x3 <- timeCommand "cmd" ["/c type " ++ drive ++ "\\" ++ fileName]
--print x3
let r3 = toCommandResult x3 "Read File"
if isError r3 then
TLIO.putStr $ makeError r3
else
TLIO.putStr $ makeResults [r1,r2,r3]
_ <- cleanup drive
return ()
go _ = putStrLn "Please provide a host name, drive letter, and file name."
main :: IO ()
main = do
args <- getArgs
go args
| individuwill/share_monitor | src/Main.hs | gpl-2.0 | 3,266 | 0 | 18 | 634 | 876 | 483 | 393 | 70 | 4 |
-- This is test file to demonstrate use of Linear 2-class SVM Library and its inbuilt kernel functions.
module Main where
import Svm
import Kernel_functions
import Cga_code
import Data.Array.Unboxed
import System.IO
import Text.ParserCombinators.Parsec
import Data.CSV
svm1 = LeastSquareSVM { kf=radialKernelFunction , param_list=[2.0] , cost = 1.0 } -- to pass kernel-function as 'datatype KernelFunction' constructor 'KernelFunction' is called here.
read_data_points:: Either a [[String]] -> Array_doublesList
read_data_points list =
let read_aux [] count listL = listArray (1,count) listL
read_aux (h:t) count listL = read_aux t (count+1) (listL++[l']) -- Count is no. of elements in array, listL is list of doubles_list
where l' = map read h :: [Double]
in
case list of
Right val -> read_aux val 0 []
Left _ -> listArray (1,1) [[0.0]] -- error case
read_labels:: Either a [[String]] -> Array_doubles
read_labels list =
let read_aux (h:t) count listL = read_aux t (count+1) (listL++[l'])
where l' = read (head h) :: Double
read_aux [] count listL = listArray (1,count) listL
in
case list of
Right val -> read_aux val 0 []
Left _ -> listArray (1,1) [0.0] -- error case
accuracy:: [Int] -> [Int] -> Double -> Double -> [Double]
accuracy (x1:x1s) (x2:x2s) count total | x1==x2 = accuracy x1s x2s count (total+1.0)
| otherwise = accuracy x1s x2s (count+1.0) (total+1.0)
accuracy _ _ count total = [count,total,((total-count)*100.0)/total]
main = do
data_points_train <- parseFromFile csvFile "train_data.csv"
labels_train <- parseFromFile csvFile "train_data_labels.csv"
data_points_test <- parseFromFile csvFile "test_data.csv"
labels_test <- parseFromFile csvFile "test_data_labels.csv"
--print "data_points_test :"
--print data_points_test
--print "labels_test :"
--print labels_test
let dp_train = read_data_points data_points_train
let dp_test = read_data_points data_points_test
let lb_train = read_labels labels_train
let lb_test = read_labels labels_test
let sol = train_svm (DataSet dp_train lb_train) 0.1 (10^6) svm1
let lb_test_out = test_svm sol dp_test svm1
let lb_test_out_rounded = map round lb_test_out
putStrLn "test labels [original] :"
let original_lb_test = map round (elems lb_test)
print original_lb_test
--putStrLn "test output decimal :"
--print lb_test_out
putStrLn ""
putStrLn "test labels generated [rounded] :"
print lb_test_out_rounded
putStrLn ""
putStrLn "Accuracy of System :"
let x1:x2:x3:xs = accuracy original_lb_test lb_test_out_rounded 0.0 0.0
putStr "Total : "
print x2
putStr "Incorrectly Classified : "
print x1
putStr "%age Accuracy : "
print x3
-- print (accuracy original_lb_test lb_test_out_rounded 0.0 0.0)
| rahulaaj/ML-Library | src/Svm/test_file.hs | gpl-3.0 | 2,913 | 13 | 12 | 631 | 874 | 436 | 438 | 56 | 3 |
{-# LANGUAGE OverloadedStrings #-}
-- | Properties from the org.mpris.MediaPlayer2 interface
--
-- More information at <http://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html>
module DBus.Mpris.MediaPlayer2.Properties
( canQuit
, fullscreen
, identity
, canSetFullscreen
, canRaise
, hasTrackList
, desktopEntry
) where
import DBus
import DBus.Mpris.Properties
import DBus.Mpris.Monad
property :: IsVariant a => String -> BusName -> Mpris (Maybe a)
property = getProperty "org.mpris.MediaPlayer2"
-- | Report if the player can quit. If 'False', calling 'quit' will have no effect.
canQuit :: BusName -> Mpris (Maybe Bool)
canQuit = property "CanQuit"
-- | Whether the media player is occupying the fullscreen.
fullscreen :: BusName -> Mpris (Maybe Bool)
fullscreen = property "Fullscreen"
-- | If 'False', attempting to set Fullscreen will have no effect.
canSetFullscreen :: BusName -> Mpris (Maybe Bool)
canSetFullscreen = property "CanSetFullscreen"
-- | If 'False', calling 'raise' will have no effect.
canRaise :: BusName -> Mpris (Maybe Bool)
canRaise = property "CanRaise"
-- | Indicates whether the /org/mpris/MediaPlayer2 object implements the org.mpris.MediaPlayer2.TrackList interface.
hasTrackList :: BusName -> Mpris (Maybe Bool)
hasTrackList = property "HasTrackList"
-- | A friendly name to identify the media player to users.
identity :: BusName -> Mpris (Maybe String)
identity = property "Identity"
-- | The basename of an installed .desktop file which complies with the Desktop entry specification, with the ".desktop" extension stripped.
desktopEntry :: BusName -> Mpris (Maybe String)
desktopEntry = property "DesktopEntry"
| Fuco1/mpris | src/DBus/Mpris/MediaPlayer2/Properties.hs | gpl-3.0 | 1,732 | 0 | 10 | 294 | 276 | 151 | 125 | 28 | 1 |
duplicate :: w a -> w (w a) | hmemcpy/milewski-ctfp-pdf | src/content/3.7/code/haskell/snippet14.hs | gpl-3.0 | 27 | 0 | 8 | 7 | 22 | 10 | 12 | 1 | 0 |
-- Copyright © 2014 Bart Massey
-- Based on material Copyright © 2013 School of Haskell
-- https://www.fpcomplete.com/school/advanced-haskell/
-- building-a-file-hosting-service-in-yesod
-- This work is made available under the "GNU AGPL v3", as
-- specified the terms in the file COPYING in this
-- distribution.
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
module Handler.Home where
import Control.Monad.Trans.Resource
import Data.Conduit
import Data.Conduit.Binary
import Data.Text (unpack)
import Data.Default
import Yesod
import Yesod.Default.Util
import Foundation
getHomeR :: Handler Html
getHomeR = do
(formWidget, formEncType) <- generateFormPost uploadForm
galleries <- getFAList
defaultLayout $ do
setTitle "HGallery"
$(widgetFileNoReload def "home")
postHomeR :: Handler Html
postHomeR = do
((result, _), _) <- runFormPost uploadForm
case result of
FormSuccess fi -> do
app <- getYesod
fileBytes <- runResourceT $ fileSource fi $$ sinkLbs
let mime = unpack $ fileContentType fi
let fileAssoc = FileAssoc { fileAssocName = unpack $ fileName fi,
fileAssocContents = fileBytes,
fileAssocMime = mime,
fileAssocType = parseFiletype mime,
fileAssocId = 0 }
addFile app fileAssoc
_ -> return ()
redirect HomeR
uploadForm = renderDivs $ fileAFormReq "file"
| BartMassey/hgallery | Handler/Home.hs | agpl-3.0 | 1,521 | 0 | 18 | 382 | 302 | 160 | 142 | 36 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Topical.Text.Regex
( Replace
, rgroup
, rtext
, rstring
, rfn
, rtfn
, rbuilder
, replace
, replace'
, replaceAll
, replaceAll'
, parseReplace
) where
import Control.Applicative
import Data.Attoparsec.Text
import qualified Data.Text as T
import Data.Text.ICU.Replace
parseReplace :: T.Text -> Replace
parseReplace t = either (const $ rtext t) id
$ parseOnly (replacement <* endOfInput) t
replacement :: Parser Replace
replacement = mconcat <$> many (dollarGroup <|> raw)
dollarGroup :: Parser Replace
dollarGroup = char '$' *> (grp <|> escaped)
where curly = char '{' *> decimal <* char '}'
grp = rgroup <$> (decimal <|> curly)
escaped = rtext . T.singleton <$> char '$'
raw :: Parser Replace
raw = rtext <$> takeWhile1 (/= '$')
| erochest/topical | src/Topical/Text/Regex.hs | apache-2.0 | 922 | 0 | 9 | 274 | 255 | 143 | 112 | 30 | 1 |
module Util where
import Data.List
import System.Directory
import Control.Monad
import System.FilePath
findIndexValue :: (a -> Bool) -> [a] -> Maybe (Int, a)
findIndexValue f xs = find (f . snd) $ zip [0..] xs
copyDirectory :: FilePath -> FilePath -> IO ()
copyDirectory from to = do
xs <- getDirectoryContentsRecursive from
forM_ xs $ \x -> do
let dest = to ++ drop (length from) x
createDirectoryIfMissing True $ takeDirectory dest
copyFile x dest
getDirectoryContentsRecursive :: FilePath -> IO [FilePath]
getDirectoryContentsRecursive dir = do
xs <- getDirectoryContents dir
(dirs,files) <- partitionM doesDirectoryExist [dir </> x | x <- xs, not $ isBadDir x]
rest <- concatMapM getDirectoryContentsRecursive $ sort dirs
return $ sort files ++ rest
where
isBadDir x = "." `isPrefixOf` x || "_" `isPrefixOf` x
partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM f [] = return ([], [])
partitionM f (x:xs) = do
res <- f x
(as,bs) <- partitionM f xs
return ([x | res]++as, [x | not res]++bs)
concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM f = liftM concat . mapM f
fst3 (x,y,z) = x
snd3 (x,y,z) = y
thd3 (x,y,z) = z
| ndmitchell/fossilizer | Util.hs | apache-2.0 | 1,240 | 0 | 17 | 288 | 586 | 299 | 287 | 32 | 1 |
module TAParser (
parseExpr
) where
import CalcSyntax
import Text.Parsec
import Text.Parsec.String (Parser)
import Text.Parsec.Language (emptyDef)
import qualified Text.Parsec.Expr as Ex
import qualified Text.Parsec.Token as Tok
import Data.Functor.Identity
lexer :: Tok.TokenParser ()
lexer = Tok.makeTokenParser emptyDef
parens :: Parser a -> Parser a
parens = Tok.parens lexer
reserved :: String -> Parser ()
reserved = Tok.reserved lexer
semiSep :: Parser a -> Parser [a]
semiSep = Tok.semiSep lexer
reservedOp :: String -> Parser ()
reservedOp = Tok.reservedOp lexer
infixOp :: String -> (a -> a) -> Ex.Operator String () Identity a
infixOp s f = Ex.Prefix (reservedOp s >> return f)
table :: Ex.OperatorTable String () Identity Expr
table = [[
infixOp "succ" Succ
, infixOp "pred" Pred
, infixOp "iszero" IsZero
]]
expr :: Parser Expr
expr = Ex.buildExpressionParser table factor
ifthen :: Parser Expr
ifthen = do
reserved "if"
cond <- expr
reservedOp "then"
tr <- expr
reserved "else"
fl <- expr
return (If cond tr fl)
true, false, zero :: Parser Expr
true = reserved "true" >> return Tr
false = reserved "false" >> return Fl
zero = reservedOp "0" >> return Zero
factor :: Parser Expr
factor = true
<|> false
<|> zero
<|> ifthen
<|> parens expr
contents :: Parser a -> Parser a
contents p = do
Tok.whiteSpace lexer
r <- p
eof
return r
parseExpr :: String -> Either ParseError Expr
parseExpr = parse (contents expr) "<stdin>"
| toonn/wyah | src/TAParser.hs | bsd-2-clause | 1,531 | 0 | 9 | 333 | 551 | 279 | 272 | 55 | 1 |
-- | A collection of parsing algorithms with a common interface, operating on grammars represented as records with
-- rank-2 field types.
{-# LANGUAGE FlexibleContexts, KindSignatures, OverloadedStrings, RankNTypes, ScopedTypeVariables #-}
module Text.Grampa (
-- * Applying parsers
failureDescription, simply,
-- * Types
Grammar, GrammarBuilder, ParseResults, ParseFailure(..), FailureDescription(..), Ambiguous(..), Pos,
-- * Classes
-- ** Parsing
DeterministicParsing(..), AmbiguousParsing(..), CommittedParsing(..), TraceableParsing(..),
LexicalParsing(..),
-- ** Grammars
MultiParsing(..), GrammarParsing(..),
-- ** From the [input-parsers](http://hackage.haskell.org/package/input-parsers) library
InputParsing(..), InputCharParsing(..), ConsumedInputParsing(..), Position(..),
-- ** From the [parsers](http://hackage.haskell.org/package/parsers) library
module Text.Parser.Char,
module Text.Parser.Combinators,
module Text.Parser.LookAhead,
TokenParsing(..),
-- * Other combinators
module Text.Grampa.Combinators)
where
import Data.List (intersperse)
import Data.Monoid ((<>))
import Data.Monoid.Factorial (drop)
import Data.Monoid.Null (null)
import Data.Monoid.Textual (TextualMonoid)
import Data.String (IsString(fromString))
import Text.Parser.Char (CharParsing(char, notChar, anyChar))
import Text.Parser.Combinators (Parsing((<?>), notFollowedBy, skipMany, skipSome, unexpected))
import Text.Parser.LookAhead (LookAheadParsing(lookAhead))
import Text.Parser.Token (TokenParsing(..))
import Text.Parser.Input.Position (Position)
import qualified Text.Parser.Input.Position as Position
import Text.Grampa.Combinators (concatMany, concatSome)
import qualified Rank2
import Text.Grampa.Class (MultiParsing(..), GrammarParsing(..),
InputParsing(..), InputCharParsing(..),
ConsumedInputParsing(..), LexicalParsing(..),
CommittedParsing(..), DeterministicParsing(..),
AmbiguousParsing(..), Ambiguous(..),
ParseResults, ParseFailure(..), FailureDescription(..), Pos)
import Text.Grampa.Internal (TraceableParsing(..))
import Prelude hiding (drop, null)
-- | A type synonym for a fixed grammar record type @g@ with a given parser type @p@ on input streams of type @s@
type Grammar (g :: (* -> *) -> *) p s = g (p g s)
-- | A type synonym for an endomorphic function on a grammar record type @g@, whose parsers of type @p@ build grammars
-- of type @g'@, parsing input streams of type @s@
type GrammarBuilder (g :: (* -> *) -> *)
(g' :: (* -> *) -> *)
(p :: ((* -> *) -> *) -> * -> * -> *)
(s :: *)
= g (p g' s) -> g (p g' s)
-- | Apply the given parsing function (typically `parseComplete` or `parsePrefix`) to the given grammar-agnostic
-- parser and its input. A typical invocation might be
--
-- > getCompose $ simply parsePrefix myParser myInput
simply :: (Rank2.Only r (p (Rank2.Only r) s) -> s -> Rank2.Only r f) -> p (Rank2.Only r) s r -> s -> f r
simply parseGrammar p input = Rank2.fromOnly (parseGrammar (Rank2.Only p) input)
-- | Given the textual parse input, the parse failure on the input, and the number of lines preceding the failure to
-- show, produce a human-readable failure description.
failureDescription :: forall s pos. (Ord s, TextualMonoid s, Position pos) => s -> ParseFailure pos s -> Int -> s
failureDescription input (ParseFailure pos expected erroneous) contextLineCount =
Position.context input pos contextLineCount
<> mconcat
(intersperse ", but " $ filter (not . null)
[onNonEmpty ("expected " <>) $ oxfordComma " or " (fromDescription <$> expected),
oxfordComma " and " (fromDescription <$> erroneous)])
where oxfordComma :: s -> [s] -> s
oxfordComma _ [] = ""
oxfordComma _ [x] = x
oxfordComma conjunction [x, y] = x <> conjunction <> y
oxfordComma conjunction (x:y:rest) = mconcat (intersperse ", " (x : y : onLast (drop 1 conjunction <>) rest))
onNonEmpty f x = if null x then x else f x
onLast _ [] = []
onLast f [x] = [f x]
onLast f (x:xs) = x : onLast f xs
fromDescription (StaticDescription s) = fromString s
fromDescription (LiteralDescription s) = "string \"" <> s <> "\""
| blamario/grampa | grammatical-parsers/src/Text/Grampa.hs | bsd-2-clause | 4,402 | 0 | 14 | 920 | 1,137 | 685 | 452 | 61 | 8 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoRebindableSyntax #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.KA.Rules
( rules
) where
import Control.Applicative ((<|>))
import Data.HashMap.Strict (HashMap)
import Data.Maybe
import Data.String
import Data.Text (Text)
import Prelude
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers
import Duckling.Numeral.Types (NumeralData (..))
import Duckling.Regex.Types
import Duckling.Types
import qualified Duckling.Numeral.Types as TNumeral
zeroNineteenMap :: HashMap Text Integer
zeroNineteenMap = HashMap.fromList
[ ( "ნოლ" , 0 )
, ( "ნულ" , 0 )
, ( "ნული" , 0 )
, ( "ნოლ" , 0 )
, ( "ნოლი" , 0 )
, ( "ერთი" , 1 )
, ( "ორი" , 2 )
, ( "ორ" , 2 )
, ( "სამი" , 3 )
, ( "სამ" , 3 )
, ( "ოთხი" , 4 )
, ( "ოთხ" , 4 )
, ( "ხუთი" , 5 )
, ( "ხუთ" , 5 )
, ( "ექვსი" , 6 )
, ( "ექვს" , 6 )
, ( "შვიდი" , 7 )
, ( "შვიდ" , 7 )
, ( "რვა" , 8 )
, ( "რვ" , 8 )
, ( "ცხრა" , 9 )
, ( "ცხრ" , 9 )
, ( "ათი" , 10 )
, ( "აათი" , 10 )
, ( "თერთმეტი" , 11 )
, ( "თერთმეტ" , 11 )
, ( "თორმეტი" , 12 )
, ( "თორმეტ" , 12 )
, ( "ცამეტი" , 13 )
, ( "ცამეტ" , 13 )
, ( "თოთხმეტი" , 14 )
, ( "თოთხმეტ" , 14 )
, ( "თხუთმეტი" , 15 )
, ( "თხუთმეტ" , 15 )
, ( "თექვსმეტი" , 16 )
, ( "თექვსმეტ" , 16 )
, ( "ჩვიდმეტი" , 17 )
, ( "ჩვიდმეტ" , 17 )
, ( "თვრამეტი" , 18 )
, ( "თვრამეტ" , 18 )
, ( "ცხრამეტი" , 19 )
, ( "ცხრამეტ" , 19 )
]
informalMap :: HashMap Text Integer
informalMap = HashMap.fromList
[ ( "ერთი" , 1 )
, ( "წყვილი" , 2 )
, ( "წყვილები" , 2 )
, ( "ცოტა" , 3 )
, ( "რამდენიმე" , 3 )
, ( "რამოდენიმე" , 3 )
]
ruleToNineteen :: Rule
ruleToNineteen = Rule
{ name = "integer (0..19)"
, pattern =
[ regex "(წყვილ(ებ)?ი|ცოტა|რამდენიმე|რამოდენიმე|ნოლი?|ნული?|ერთი|ორი?|სამი?|ოთხი?|ხუთი?|ექვსი?|შვიდი?|რვა|თერთმეტი?|თორმეტი?|ცამეტი?|თოთხმეტი?|თხუთმეტი?|თექვსმეტი?|ჩვიდმეტი?|თვრამეტი?|ცხრამეტი?|ცხრა|ა?ათი)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
let x = Text.toLower match in
(HashMap.lookup x zeroNineteenMap >>= integer) <|>
(HashMap.lookup x informalMap >>= integer >>= notOkForAnyTime)
_ -> Nothing
}
tensMap :: HashMap Text Integer
tensMap = HashMap.fromList
[ ( "ოცი" , 20 )
, ( "ოცდა" , 20 )
, ( "ოც" , 20 )
, ( "ოცდაათ" , 30 )
, ( "ოცდაათი" , 30 )
, ( "ორმოც" , 40 )
, ( "ორმოცი" , 40 )
, ( "ორმოცდა" , 40 )
, ( "ორმოცდაათ" , 50 )
, ( "ორმოცდაათი" , 50 )
, ( "სამოც" , 60 )
, ( "სამოცი" , 60 )
, ( "სამოცდა" , 60 )
, ( "სამოცდაათ" , 70 )
, ( "სამოცდაათი" , 70 )
, ( "ოთხმოც" , 80 )
, ( "ოთხმოცი" , 80 )
, ( "ოთხმოცდა" , 80 )
, ( "ოთხმოცდაათ" , 90 )
, ( "ოთხმოცდაათი" , 90 )
]
ruleTens :: Rule
ruleTens = Rule
{ name = "integer (20..90)"
, pattern =
[ regex "(ოცდაათი?|ორმოცდაათი?|სამოცდაათი?|ოთხმოცდაათი?|ოცდა|ორმოცდა|სამოცდა|ოთხმოცდა|ოცი?|ორმოცი?|სამოცი?|ოთხმოცი?)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
HashMap.lookup (Text.toLower match) tensMap >>= integer
_ -> Nothing
}
hundredsMap :: HashMap Text Integer
hundredsMap = HashMap.fromList
[ ( "ასი" , 100 )
, ( "ორასი" , 200 )
, ( "სამასი" , 300 )
, ( "ოთხასი" , 400 )
, ( "ხუთასი" , 500 )
, ( "ექვსასი" , 600 )
, ( "შვიდასი" , 700 )
, ( "რვაასი" , 800 )
, ( "ცხრაასი" , 900 )
, ( "ას" , 100 )
, ( "ორას" , 200 )
, ( "სამას" , 300 )
, ( "ოთხას" , 400 )
, ( "ხუთას" , 500 )
, ( "ექვსას" , 600 )
, ( "შვიდას" , 700 )
, ( "რვაას" , 800 )
, ( "ცხრაას" , 900 )
, ( "ორ ას" , 200 )
, ( "სამ ას" , 300 )
, ( "ოთხ ას" , 400 )
, ( "ხუთ ას" , 500 )
, ( "ექვს ას" , 600 )
, ( "შვიდ ას" , 700 )
, ( "რვა ას" , 800 )
, ( "ცხრა ას" , 900 )
, ( "ორ ასი" , 200 )
, ( "სამ ასი" , 300 )
, ( "ოთხ ასი" , 400 )
, ( "ხუთ ასი" , 500 )
, ( "ექვს ასი" , 600 )
, ( "შვიდ ასი" , 700 )
, ( "რვა ასი" , 800 )
, ( "ცხრა ასი" , 900 )
]
ruleHundreds :: Rule
ruleHundreds = Rule
{ name = "integer (800..900)"
, pattern =
[ regex "(ასი?|ორ ?ასი?|სამ ?ასი?|ოთხ ?ასი?|ხუთ ?ასი?|ექვს ?ასი?|შვიდ ?ასი?|რვა ?ასი?|ცხრა ?ასი?)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
HashMap.lookup (Text.toLower match) hundredsMap >>= integer
_ -> Nothing
}
rulePowersOfTen :: Rule
rulePowersOfTen = Rule
{ name = "powers of tens"
, pattern =
[ regex "(ათასი?|მილიონი?|მილიარდი?)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"ათასი" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"ათას" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"მილიონი" -> double 1e6 >>= withGrain 6 >>= withMultipliable
"მილიონ" -> double 1e6 >>= withGrain 6 >>= withMultipliable
"მილიარდი" -> double 1e9 >>= withGrain 9 >>= withMultipliable
"მილიარდ" -> double 1e9 >>= withGrain 9 >>= withMultipliable
_ -> Nothing
_ -> Nothing
}
ruleCompositeTens :: Rule
ruleCompositeTens = Rule
{ name = "integer 21..99"
, pattern =
[ oneOf [20,40..90]
, numberBetween 1 20
]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = tens}:
Token Numeral NumeralData{TNumeral.value = units}:
_) -> double $ tens + units
_ -> Nothing
}
ruleCompositeHundreds :: Rule
ruleCompositeHundreds = Rule
{ name = "integer 100..999"
, pattern =
[ oneOf [100,200..900]
, oneOf [20,40..90]
, numberBetween 1 20
]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = hundreds}:
Token Numeral NumeralData{TNumeral.value = tens}:
Token Numeral NumeralData{TNumeral.value = units}:
_) -> double $ hundreds + tens + units
_ -> Nothing
}
ruleCompositeHundredsAndUnits :: Rule
ruleCompositeHundredsAndUnits = Rule
{ name = "integer 100..999"
, pattern =
[ oneOf [100,200..900]
, numberBetween 1 20
]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = hundreds}:
Token Numeral NumeralData{TNumeral.value = units}:
_) -> double $ hundreds + units
_ -> Nothing
}
ruleCompositeHundredsAndTens :: Rule
ruleCompositeHundredsAndTens = Rule
{ name = "integer 100..999"
, pattern =
[ oneOf [100,200..900]
, oneOf [10,20..90]
]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = hundreds}:
Token Numeral NumeralData{TNumeral.value = tens}:
_) -> double $ hundreds + tens
_ -> Nothing
}
ruleDotSpelledOut :: Rule
ruleDotSpelledOut = Rule
{ name = "one point 2"
, pattern =
[ dimension Numeral
, regex "წერტილი|მთელი"
, Predicate $ not . hasGrain
]
, prod = \case
(Token Numeral nd1:_:Token Numeral nd2:_) ->
double $ TNumeral.value nd1 + decimalsToDouble (TNumeral.value nd2)
_ -> Nothing
}
ruleLeadingDotSpelledOut :: Rule
ruleLeadingDotSpelledOut = Rule
{ name = "point 77"
, pattern =
[ regex "წერტილი|მთელი"
, Predicate $ not . hasGrain
]
, prod = \case
(_:Token Numeral nd:_) -> double . decimalsToDouble $ TNumeral.value nd
_ -> Nothing
}
ruleDecimals :: Rule
ruleDecimals = Rule
{ name = "decimal number"
, pattern =
[ regex "(\\d*\\.\\d+)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) -> parseDecimal True match
_ -> Nothing
}
ruleCommas :: Rule
ruleCommas = Rule
{ name = "comma-separated numbers"
, pattern =
[ regex "(\\d+(,\\d\\d\\d)+(\\.\\d+)?)"
]
, prod = \case
(Token RegexMatch (GroupMatch (match:_)):_) ->
parseDouble (Text.replace "," Text.empty match) >>= double
_ -> Nothing
}
ruleSuffixes :: Rule
ruleSuffixes = Rule
{ name = "suffixes (K,M,G))"
, pattern =
[ dimension Numeral
, regex "(k|m|g)(?=[\\W$€¢£]|$)"
]
, prod = \case
(Token Numeral nd : Token RegexMatch (GroupMatch (match : _)):_) -> do
x <- case Text.toLower match of
"k" -> Just 1e3
"m" -> Just 1e6
"g" -> Just 1e9
_ -> Nothing
double $ TNumeral.value nd * x
_ -> Nothing
}
ruleNegative :: Rule
ruleNegative = Rule
{ name = "negative numbers"
, pattern =
[ regex "(-|მინუს|მინ)(?!\\s*-)"
, Predicate isPositive
]
, prod = \case
(_:Token Numeral nd:_) -> double (TNumeral.value nd * (-1))
_ -> Nothing
}
ruleSum :: Rule
ruleSum = Rule
{ name = "intersect 2 numbers"
, pattern =
[ Predicate $ and . sequence [hasGrain, isPositive]
, Predicate $ and . sequence [not . isMultipliable, isPositive]
]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = val1, TNumeral.grain = Just g}:
Token Numeral NumeralData{TNumeral.value = val2}:
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleSumAnd :: Rule
ruleSumAnd = Rule
{ name = "intersect 2 numbers (with and)"
, pattern =
[ Predicate $ and . sequence [hasGrain, isPositive]
, regex "და"
, Predicate $ and . sequence [not . isMultipliable, isPositive]
]
, prod = \case
(Token Numeral NumeralData{TNumeral.value = val1, TNumeral.grain = Just g}:
_:
Token Numeral NumeralData{TNumeral.value = val2}:
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleMultiply :: Rule
ruleMultiply = Rule
{ name = "compose by multiplication"
, pattern =
[ dimension Numeral
, Predicate isMultipliable
]
, prod = \case
(token1:token2:_) -> multiply token1 token2
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleToNineteen
, ruleHundreds
, ruleCompositeHundreds
, ruleCompositeHundredsAndUnits
, ruleCompositeHundredsAndTens
, ruleTens
, rulePowersOfTen
, ruleCompositeTens
, ruleDotSpelledOut
, ruleLeadingDotSpelledOut
, ruleDecimals
, ruleCommas
, ruleSuffixes
, ruleNegative
, ruleSum
, ruleSumAnd
, ruleMultiply
]
| facebookincubator/duckling | Duckling/Numeral/KA/Rules.hs | bsd-3-clause | 12,616 | 0 | 17 | 3,119 | 3,282 | 1,899 | 1,383 | 333 | 8 |
farey (a,b) n = if r == 0
then (k, n)
else farey (a,b) (n - 1)
where (k, r) = divMod (1 + a * n) b
farey2 (a,b) (c,d) n = (p,q) where
k = (n + b) `div` d
p = k * c - a
q = k * d - b
count a b n = go a (farey a n) b n 0 where
go a b f n r = if b == f
then r
else go b next f n $! (r + 1) -- strict
where next = farey2 a b n
main = print $ count (1,3) (1,2) 12000
-- http://en.wikipedia.org/wiki/Farey_sequence
| foreverbell/project-euler-solutions | src/73.hs | bsd-3-clause | 466 | 0 | 10 | 169 | 284 | 156 | 128 | 14 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS -Wall #-}
-- |
-- Module : Data.Time.Cube.Zones
-- Copyright : Copyright (c) 2015, Alpha Heavy Industries, Inc. All rights reserved.
-- License : BSD3
-- Maintainer : Enzo Haussecker <[email protected]>
-- Stability : Experimental
-- Portability : Portable
--
-- This module provides time zone data types and related parameterizations.
module Data.Time.Cube.Zones (
-- ** Time Zones
TimeZone(..)
-- ** Parameterizations
, None
, UTC
, Offset
, SomeOffset(..)
, Olson
, SomeOlson(..)
-- ** Abbreviations
, Abbreviate(..)
-- ** Utilities
, normalizeOffset
, promoteOffset
, promoteOlson
, promoteTimeZone
) where
import Control.Applicative ((<|>), (*>))
import Control.DeepSeq (NFData(..))
import Control.Monad (replicateM)
import Data.Attoparsec.Text (char, digit, parseOnly)
import Data.ByteString.Char8 as B (unpack)
import Data.Int (Int16)
import Data.Proxy (Proxy(..))
import Data.Text as T (Text, pack, unpack)
import Data.Time.Zones (TZ, diffForAbbr)
import Data.Time.Zones.DB (TZLabel, toTZName)
import Foreign.Ptr (castPtr)
import Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.TypeLits
import GHC.TypeLits.SigNat
import Text.Printf (printf)
-- |
-- A uniform standard for time.
data family TimeZone :: * -> *
data None :: *
data UTC :: *
data Offset :: SigNat -> *
data SomeOffset =
forall signat . KnownSigNat signat =>
SomeOffset (Proxy signat)
data family Olson :: Symbol -> Symbol -> SigNat -> *
data SomeOlson =
forall symbol signat . (KnownSymbol symbol, KnownSigNat signat) =>
SomeOlson String (Proxy symbol) (Proxy signat)
data instance TimeZone None =
NoTimeZone
deriving (Eq, Generic, Show)
data instance TimeZone UTC =
UTC
deriving (Eq, Generic, Show)
data instance TimeZone (Offset signat) =
TimeZoneOffset
deriving (Eq, Generic, Show)
data instance TimeZone SomeOffset =
forall signat . KnownSigNat signat =>
SomeTimeZoneOffset (Proxy signat)
data instance TimeZone (Olson region symbol signat) =
TimeZoneOlson
deriving (Eq, Generic, Show)
data instance TimeZone SomeOlson =
forall symbol signat . (KnownSymbol symbol, KnownSigNat signat) =>
SomeTimeZoneOlson String (Proxy symbol) (Proxy signat)
instance Eq (SomeOffset) where
(==) (SomeOffset x1)
(SomeOffset y1) = sigNatVal x1 ==
sigNatVal y1
instance Eq (SomeOlson) where
(==) (SomeOlson x1 x2 x3)
(SomeOlson y1 y2 y3) = x1 ==
y1 && symbolVal x2 ==
symbolVal y2 && sigNatVal x3 ==
sigNatVal y3
instance Eq (TimeZone SomeOffset) where
(==) (SomeTimeZoneOffset x1)
(SomeTimeZoneOffset y1) = sigNatVal x1 ==
sigNatVal y1
instance Eq (TimeZone SomeOlson) where
(==) (SomeTimeZoneOlson x1 x2 x3)
(SomeTimeZoneOlson y1 y2 y3) = x1 ==
y1 && symbolVal x2 ==
symbolVal y2 && sigNatVal x3 ==
sigNatVal y3
deriving instance Show (SomeOffset)
deriving instance Show (SomeOlson)
deriving instance Show (TimeZone SomeOffset)
deriving instance Show (TimeZone SomeOlson)
instance Storable (TimeZone SomeOffset) where
-- |
-- Size of a time zone offset that is unknown at compile time.
sizeOf = const 2
-- |
-- Alignment of a time zone offset that is unknown at compile time.
alignment = sizeOf
-- |
-- Read a time zone offset that is unknown at compile time from an array.
peekElemOff ptr n = do
val <- peekElemOff (castPtr ptr) n :: IO Int16
case someSigNatVal $ toInteger val
of SomeSigNat proxy -> return $! SomeTimeZoneOffset proxy
-- |
-- Write a time zone offset that is unknown at compile time to an array.
pokeElemOff ptr n (SomeTimeZoneOffset proxy) =
pokeElemOff (castPtr ptr) n val
where val = fromInteger . normalizeOffset $ sigNatVal proxy :: Int16
class Abbreviate tz where
-- |
-- Get the abbreviation text for the given time zone.
abbreviate :: tz -> Text
-- |
-- Get the time zone for the given abbreviation text.
unabbreviate :: Maybe (TZLabel, TZ) -> Text -> Either String tz
instance Abbreviate (TimeZone None) where
-- |
-- Abbreviate a time zone with no parameterization.
abbreviate NoTimeZone = ""
-- |
-- Unabbreviate a time zone with no parameterization.
unabbreviate _ = \ case
"" -> Right NoTimeZone
text -> Left $ "unabbreviate{TimeZone None}: unmatched text: " ++ T.unpack text
instance Abbreviate (TimeZone UTC) where
-- |
-- Abbreviate the UTC time zone.
abbreviate UTC = "UTC"
-- |
-- Unabbreviate the UTC time zone.
unabbreviate _ = \ case
"UTC" -> Right UTC
text -> Left $ "unabbreviate{TimeZone UTC}: unmatched text: " ++ T.unpack text
instance KnownSigNat signat => Abbreviate (TimeZone (Offset signat)) where
-- |
-- Abbreviate a time zone offset that is known at compile time.
abbreviate TimeZoneOffset =
pack $ sign : hours ++ minutes
where
sign = if signat < 0 then '-' else '+'
hours = printf "%02d" $ div nat 60
minutes = printf "%02d" $ mod nat 60
nat = abs signat
signat = normalizeOffset $ sigNatVal (Proxy :: Proxy signat)
-- |
-- Unabbreviate a time zone offset that is known at compile time.
unabbreviate _ =
parseOnly $ do
sign <- plus <|> minus
hours <- replicateM 2 digit
minutes <- replicateM 2 digit
let proxy = Proxy :: Proxy signat
signat = normalizeOffset . sign $ read hours * 60 + read minutes
if normalizeOffset (sigNatVal proxy) == signat
then return TimeZoneOffset
else fail $ "unabbreviate{TimeZone (Offset signat)}: unmatched type signature: " ++ show signat
where plus = char '+' *> return id
minus = char '-' *> return negate
instance Abbreviate (TimeZone SomeOffset) where
-- |
-- Abbreviate a time zone offset that is unknown at compile time.
abbreviate (SomeTimeZoneOffset proxy) =
pack $ sign : hours ++ minutes
where
sign = if signat < 0 then '-' else '+'
hours = printf "%02d" $ div nat 60
minutes = printf "%02d" $ mod nat 60
nat = abs signat
signat = normalizeOffset $ sigNatVal proxy
-- |
-- Unabbreviate a time zone offset that is unknown at compile time.
unabbreviate _ =
parseOnly $ do
sign <- plus <|> minus
hours <- replicateM 2 digit
minutes <- replicateM 2 digit
let signat = normalizeOffset . sign $ read hours * 60 + read minutes
case someSigNatVal signat
of SomeSigNat proxy -> return $! promoteOffset proxy SomeTimeZoneOffset
where plus = char '+' *> return id
minus = char '-' *> return negate
instance KnownSymbol symbol => Abbreviate (TimeZone (Olson region symbol signat)) where
-- |
-- Abbreviate an Olson time zone that is known at compile time.
abbreviate TimeZoneOlson = pack $ symbolVal (Proxy :: Proxy symbol)
-- |
-- Unabbreviate an Olson time zone that is known at compile time.
unabbreviate _ text =
if T.unpack text == symbolVal (Proxy :: Proxy symbol)
then Right TimeZoneOlson
else Left $ "unabbreviate{TimeZone (Olson region symbol signat)}: unmatched type signature: " ++ T.unpack text
instance Abbreviate (TimeZone SomeOlson) where
-- |
-- Abbreviate an Olson time zone that is unknown at compile time.
--
-- > λ> :set -XDataKinds
-- > λ> :module + Data.Proxy GHC.TypeLits.SigNat
-- > λ> let abbreviation = Proxy :: Proxy "CEST"
-- > λ> let offset = Proxy :: Proxy (Plus 120)
-- > λ> abbreviate $ SomeTimeZoneOlson "Europe/Paris" abbreviation offset
-- > "CEST"
--
abbreviate (SomeTimeZoneOlson _ proxy _) = pack $ symbolVal proxy
-- |
-- Unabbreviate an Olson time zone that is unknown at compile time.
--
-- > λ> :set -XOverloadedStrings -XTupleSections
-- > λ> :module + Control.Applicative Data.Time.Zones Data.Time.Zones.DB
-- > λ> tzdata <- Just . (Europe__Paris, ) <$> loadTZFromDB "Europe/Paris"
-- > λ> unabbreviate tzdata "CEST" :: Either String (TimeZone SomeOlson)
-- > Right (SomeTimeZoneOlson "Europe/Paris" Proxy Proxy)
--
unabbreviate mval text =
case mval
of Nothing -> Left "unabbreviate{TimeZone SomeOlson}: no Olson data to match text"
Just (label, tz) ->
let symbol = T.unpack text
in case diffForAbbr tz symbol
of Nothing -> Left "unabbreviate{TimeZone SomeOlson}: unmatched text"
Just diff ->
case someSymbolVal symbol
of SomeSymbol proxy1 ->
case someSigNatVal . toInteger $ div diff 60
of SomeSigNat proxy2 ->
let region = B.unpack $ toTZName label
in Right . promoteOlson proxy1 proxy2 $ SomeTimeZoneOlson region
instance NFData (TimeZone (None)) where rnf _ = ()
instance NFData (TimeZone (UTC)) where rnf _ = ()
instance NFData (TimeZone (Offset signat)) where rnf _ = ()
instance NFData (TimeZone (SomeOffset)) where rnf _ = ()
instance NFData (TimeZone (Olson region symbol signat)) where rnf _ = ()
instance NFData (TimeZone (SomeOlson)) where rnf _ = ()
-- |
-- Map a time zone offset to the interval (-720, 720].
normalizeOffset :: Integer -> Integer
normalizeOffset = pivot . flip mod 1440
where pivot n = if -720 < n && n <= 720 then n else n - signum n * 1440
-- |
-- Promote a time zone offset to the type level.
promoteOffset
:: forall proxy signat a . KnownSigNat signat
=> proxy signat
-> (Proxy signat -> a)
-> a
promoteOffset = promoteSigNat
-- |
-- Promote a time zone abbreviation and offset to the type level.
promoteOlson
:: forall proxy1 proxy2 symbol signat a . (KnownSymbol symbol, KnownSigNat signat)
=> proxy1 symbol
-> proxy2 signat
-> (Proxy symbol -> Proxy signat -> a)
-> a
promoteOlson _ _ f = f Proxy Proxy
-- |
-- Promote a time zone to the type level.
promoteTimeZone
:: forall proxy param a . proxy (TimeZone param)
-> (Proxy (TimeZone param) -> a)
-> a
promoteTimeZone _ f = f Proxy | time-cube/time-cube | src/Data/Time/Cube/Zones.hs | bsd-3-clause | 11,110 | 0 | 25 | 3,180 | 2,548 | 1,352 | 1,196 | -1 | -1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.PolygonOffsetClamp
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.PolygonOffsetClamp (
-- * Extension Support
glGetEXTPolygonOffsetClamp,
gl_EXT_polygon_offset_clamp,
-- * Enums
pattern GL_POLYGON_OFFSET_CLAMP_EXT,
-- * Functions
glPolygonOffsetClampEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/EXT/PolygonOffsetClamp.hs | bsd-3-clause | 752 | 0 | 5 | 101 | 57 | 43 | 14 | 9 | 0 |
{-|
Module : Util.Other
Description : Hopefully useful utility functions.
Copyright : (c) Andrew Michaud, 2015
License : BSD3
Maintainer : [email protected]
Stability : experimental
This module houses any methods that don't quite fit in anywhere else (or are generic enough to
deserve placement in a separate module). Currently, there are two methods for incrementing
tuples, two methods for generating lists of IO objects, and a method for converting a string
into an integer conditionally.
-}
module Util.Other (
-- * Lists
zipLists
-- * Tuples
, addToTupleIf
, incrementTupleIf
-- * Monads
, getMonadicGrid
-- * Strings
, sToIntRange
) where
import Control.Monad (replicateM)
import Text.Read (readMaybe)
-- For lists.
-- | Helper function for check functions. Given two lists of lists, returns a list
-- of lists of pairs.
zipLists :: [[a]] -> [[b]] -> [[(a, b)]]
zipLists [] _ = []
zipLists _ [] = []
zipLists (a:as) (b:bs) = zip a b : zipLists as bs
-- For tuples.
-- | Add int to tuple of int if the first condition is true for the first element of
-- the tuple and the second is true for the second element.
addToTupleIf :: Int -> (Int -> Bool) -> (Int -> Bool) -> (Int, Int) -> (Int, Int)
addToTupleIf new fstCond sndCond (f, s) = result
where condition = fstCond f && sndCond s
result = if condition then (f + new, s + new) else (f, s)
-- | Special case for adding one to tuple.
incrementTupleIf :: (Int -> Bool) -> (Int -> Bool) -> (Int, Int) -> (Int, Int)
incrementTupleIf = addToTupleIf 1
-- For Monads.
-- | Given an Int n and a monad a, return a monadic list of n lists of n a.
getMonadicGrid :: (Monad m) => Int -> m a -> m [[a]]
getMonadicGrid count func = replicateM count (replicateM count func)
-- For Strings.
-- | Given a string and a range, return either Just the string converted to an Int if it is in
-- range, or Nothing.
sToIntRange :: String -> [Int] -> Maybe Int
sToIntRange str range
| val `elem` mRange = val
| otherwise = Nothing
where val = readMaybe str
mRange = map Just range
| andrewmichaud/JustSudoku | src/Util/Other.hs | bsd-3-clause | 2,109 | 0 | 10 | 462 | 458 | 259 | 199 | 26 | 2 |
{-
TestErrorStuff.hs (adapted from test_errorstuff.c in freealut)
Copyright (c) Sven Panne 2005 <[email protected]>
This file is part of the ALUT package & distributed under a BSD-style license
See the file libraries/ALUT/LICENSE
-}
import Sound.ALUT
import System.Exit ( exitFailure, exitWith, ExitCode(ExitSuccess) )
import System.IO ( hPutStrLn, stderr )
-- This is a minimal test for error handling.
main :: IO ()
main = do
withProgNameAndArgs runALUT $ \_progName _args ->
createBuffer (File "no_such_file_in_existance.wav")
`catch` const (exitWith ExitSuccess)
hPutStrLn stderr "expected an I/O error"
exitFailure
| FranklinChen/hugs98-plus-Sep2006 | packages/ALUT/examples/TestSuite/TestErrorStuff.hs | bsd-3-clause | 659 | 0 | 12 | 119 | 108 | 58 | 50 | 10 | 1 |
module Handler.Add (handleAdd) where
import Kerchief.Prelude
import Network.API.GoogleDictionary (Entry(..), lookupWord)
import Text.Parsec (ParseError, parse)
import Text.Parsec.Char (char, noneOf, spaces)
import Text.Parsec.Combinator (between, choice)
import Text.Parsec.String (Parser)
import Card (Card, newCard, reverseCard)
import Deck
import Handler.Utils (printNoDeckLoadedError)
import Kerchief
import Utils (askYesNo, printNumberedWith, reads')
import Prelude hiding (getLine, putStr, putStrLn)
handleAdd :: [String] -> Kerchief ()
handleAdd ["--help"] = io printAddUsage
handleAdd [word] = handleAddWord word
handleAdd xs = handleAddFrontBack (join xs)
printAddUsage :: IO ()
printAddUsage = mapM_ putStrLn
[ "Usage: add [word|\"front text\" \"back text\"]"
, " add word"
, " look up |word|, pick a definition, and add it to the current deck"
, " add \"front text\" \"back text\""
, " add a new card with front |front text| and back |back text|"
]
handleAddWord :: String -> Kerchief ()
handleAddWord word = getDeck >>= maybe printNoDeckLoadedError (handleAddWord' word)
handleAddWord' :: String -> Deck -> Kerchief ()
handleAddWord' word deck = io (lookupWord word) >>= selectEntry
where
selectEntry :: [Entry] -> Kerchief ()
selectEntry [] = putStrLn "No definition found."
selectEntry es = do
printNumberedWith (\(Entry word def mpos phonetic _) ->
word ++ " " ++ phonetic ++ maybe " " (\pos -> " (" ++ pos ++ ") ") mpos ++ def) es
putStrLn "Which definition? (\"-\" to go back)"
getLine >>= \ms -> case ms of
"-" -> putStrLn "No card added."
s -> maybe badInput selectEntry' (reads' s)
where
selectEntry' :: Int -> Kerchief ()
selectEntry' n
| n < 1 || n > length es = badInput
| otherwise = doAddCard (entryToFront entry) (entryDefinition entry) (entrySoundUrl entry) deck
where
entry :: Entry
entry = es !! (n-1)
badInput :: Kerchief ()
badInput = putStrLn "Please pick a valid integer."
doAddCard :: String -> String -> Maybe String -> Deck -> Kerchief ()
doAddCard front back soundUrl deck = do
card <- io $ newCard front back soundUrl
putStrLn "Card added."
let deck' = addCard card deck
askYesNo "Add reverse card as well? (y/n) "
(return $ addCard (reverseCard card) deck') -- Either add two cards to the deck...
(return deck') -- ...or only one
>>= setDeck
handleAddFrontBack :: String -> Kerchief ()
handleAddFrontBack line = getDeck >>= maybe printNoDeckLoadedError (handleAddFrontBack' line)
handleAddFrontBack' :: String -> Deck -> Kerchief ()
handleAddFrontBack' line deck = either left right . parse parseFrontBack "" $ line
where
left :: ParseError -> Kerchief ()
left _ = io printAddUsage
right :: (String, String) -> Kerchief ()
right (front, back) = doAddCard front back Nothing deck
parseFrontBack :: Parser (String, String)
parseFrontBack = (,) <$> parseQuotedString <*> (spaces *> parseQuotedString)
parseQuotedString :: Parser String
parseQuotedString = quoted $ many stringChar
where
quoted :: Parser a -> Parser a
quoted = between (char '\"') (char '\"')
stringChar :: Parser Char
stringChar = escapedChar <|> noneOf "\""
escapedChar :: Parser Char
escapedChar = char '\\' *> choice (zipWith escape codes replacements)
escape :: Char -> Char -> Parser Char
escape code replacement = replacement <$ char code
codes, replacements :: [Char]
codes = ['b', 'n', 'f', 'r', 't', '\\', '\"', '/']
replacements = ['\b', '\n', '\f', '\r', '\t', '\\', '\"', '/']
entryToFront :: Entry -> String
entryToFront (Entry word defn mpos phonetic _) = word ++ " " ++ phonetic ++ maybe "" (\pos -> " (" ++ pos++")") mpos
| mitchellwrosen/kerchief | src/Handler/Add.hs | bsd-3-clause | 4,050 | 0 | 18 | 1,059 | 1,194 | 626 | 568 | 79 | 3 |
{-# LANGUAGE FlexibleContexts, TemplateHaskell #-}
module HNN.Optimize (
module HNN.Optimize.Momentum
, module HNN.Optimize.Vanilla
, sgd
) where
import Control.Monad.Morph
import Control.Monad.Trans
import Control.Monad.State
import Data.VectorSpace
import HNN.Optimize.Momentum
import HNN.Optimize.Vanilla
import Pipes
import Pipes.Lift
sgd :: (Monad m, MonadTrans t, Monad (t (Pipe a (Scalar w, w) m)), Monad (t m), MFunctor t, VectorSpace w)
=> (Scalar w -> w -> w -> t m w) -- update function
-> (w -> a -> m (Scalar w, w)) -- cost function gradient
-> w -- initial weights
-> t (Pipe a (Scalar w, w) m) () -- streams out cost weights for each iteration
sgd update cost_grad w_0 =
distribute $ sgd' update cost_grad w_0
sgd' :: (Monad m, MonadTrans t, Monad (t m), VectorSpace w)
=> (Scalar w -> w -> w -> t m w) -- update function
-> (w -> a -> m (Scalar w, w)) -- cost function gradient
-> w -- initial weights
-> Pipe a (Scalar w, w) (t m) () -- streams out cost weights for each iteration
sgd' update cost_grad w_0 = evalStateT action w_0
where action = forever $ do
w_t <- get
batch <- lift $ await
(cost, grad) <- lift $ lift $ lift $ cost_grad w_t batch
w_tp1 <- lift $ lift $ update cost grad w_t
lift $ yield (cost, w_tp1)
put w_tp1
| alexisVallet/hnn | src/HNN/Optimize.hs | bsd-3-clause | 1,362 | 0 | 13 | 340 | 501 | 265 | 236 | 33 | 1 |
-- Copyright 2019 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- https://developers.google.com/open-source/licenses/bsd
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE ViewPatterns #-}
module Type (
HasType (..), CheckableE (..), CheckableB (..),
checkTypes, checkTypesM,
getType, getAppType, getTypeSubst, litType, getBaseMonoidType,
instantiatePi, instantiateDepPairTy,
checkExtends, checkedApplyDataDefParams,
instantiateDataDef,
caseAltsBinderTys, tryGetType, projectLength,
sourceNameType,
checkUnOp, checkBinOp,
oneEffect, lamExprTy, isData, asFirstOrderFunction, asFFIFunType,
isSingletonType, singletonTypeVal, asNaryPiType, NaryPiFlavor (..),
numNaryPiArgs, naryLamExprType,
extendEffect, exprEffects, getReferentTy) where
import Prelude hiding (id)
import Control.Category ((>>>))
import Control.Monad
import Control.Monad.Reader
import Data.Maybe (isJust)
import Data.Foldable (toList)
import Data.Functor
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import LabeledItems
import Err
import Util (forMZipped, forMZipped_, iota)
import CheapReduction
import {-# SOURCE #-} Interpreter
import Syntax
import Name
import PPrint ()
-- === top-level API ===
checkTypes :: (EnvReader m, CheckableE e) => e n -> m n (Except ())
checkTypes e = liftTyperT $ void $ checkE e
checkTypesM :: (EnvReader m, Fallible1 m, CheckableE e) => e n -> m n ()
checkTypesM e = liftExcept =<< checkTypes e
getType :: (EnvReader m, HasType e) => e n -> m n (Type n)
getType e = liftHardFailTyperT $ getTypeE e
getAppType :: EnvReader m => Type n -> [Atom n] -> m n (Type n)
getAppType f xs = case nonEmpty xs of
Nothing -> getType f
Just xs' -> liftHardFailTyperT $ checkApp f xs'
getTypeSubst :: (SubstReader Name m, EnvReader2 m, HasType e)
=> e i -> m i o (Type o)
getTypeSubst e = do
subst <- getSubst
liftM runHardFail $ liftEnvReaderT $
runSubstReaderT subst $
runTyperT' $ getTypeE e
tryGetType :: (EnvReader m, Fallible1 m, HasType e) => e n -> m n (Type n)
tryGetType e = liftExcept =<< liftTyperT (getTypeE e)
depPairLeftTy :: DepPairType n -> Type n
depPairLeftTy (DepPairType (_:>ty) _) = ty
instantiateDepPairTy :: ScopeReader m => DepPairType n -> Atom n -> m n (Type n)
instantiateDepPairTy (DepPairType b rhsTy) x = applyAbs (Abs b rhsTy) (SubstVal x)
instantiatePi :: ScopeReader m => PiType n -> Atom n -> m n (EffectRow n, Type n)
instantiatePi (PiType b eff body) x = do
PairE eff' body' <- applyAbs (Abs b (PairE eff body)) (SubstVal x)
return (eff', body')
sourceNameType :: (EnvReader m, Fallible1 m)
=> SourceName -> m n (Type n)
sourceNameType v = do
lookupSourceMap v >>= \case
Nothing -> throw UnboundVarErr $ pprint v
Just uvar -> case uvar of
UAtomVar v' -> getType $ Var v'
UTyConVar v' -> lookupEnv v' >>= \case TyConBinding _ e -> getType e
UDataConVar v' -> lookupEnv v' >>= \case DataConBinding _ _ e -> getType e
UClassVar v' -> lookupEnv v' >>= \case ClassBinding _ e -> getType e
UMethodVar v' -> lookupEnv v' >>= \case MethodBinding _ _ e -> getType e
getReferentTy :: MonadFail m => EmptyAbs (PairB LamBinder LamBinder) n -> m (Type n)
getReferentTy (Abs (PairB hB refB) UnitE) = do
RefTy _ ty <- return $ binderType refB
HoistSuccess ty' <- return $ hoist hB ty
return ty'
-- === querying effects ===
exprEffects :: (MonadFail1 m, EnvReader m) => Expr n -> m n (EffectRow n)
exprEffects expr = case expr of
Atom _ -> return $ Pure
App f xs -> do
fTy <- getType f
case fromNaryPiType (length xs) fTy of
Just (NaryPiType bs effs _) -> do
let subst = bs @@> fmap SubstVal xs
applySubst subst effs
Nothing -> error $
"Not a " ++ show (length xs + 1) ++ "-argument pi type: " ++ pprint fTy
Op op -> case op of
PrimEffect ref m -> do
RefTy (Var h) _ <- getType ref
return $ case m of
MGet -> oneEffect (RWSEffect State $ Just h)
MPut _ -> oneEffect (RWSEffect State $ Just h)
MAsk -> oneEffect (RWSEffect Reader $ Just h)
-- XXX: We don't verify the base monoid. See note about RunWriter.
MExtend _ _ -> oneEffect (RWSEffect Writer $ Just h)
ThrowException _ -> return $ oneEffect ExceptionEffect
IOAlloc _ _ -> return $ oneEffect IOEffect
IOFree _ -> return $ oneEffect IOEffect
PtrLoad _ -> return $ oneEffect IOEffect
PtrStore _ _ -> return $ oneEffect IOEffect
_ -> return Pure
Hof hof -> case hof of
For _ f -> functionEffs f
Tile _ _ _ -> error "not implemented"
While body -> functionEffs body
Linearize _ -> return Pure -- Body has to be a pure function
Transpose _ -> return Pure -- Body has to be a pure function
RunWriter _ f -> rwsFunEffects Writer f
RunReader _ f -> rwsFunEffects Reader f
RunState _ f -> rwsFunEffects State f
PTileReduce _ _ _ -> return mempty
RunIO f -> do
effs <- functionEffs f
return $ deleteEff IOEffect effs
CatchException f -> do
effs <- functionEffs f
return $ deleteEff ExceptionEffect effs
Case _ _ _ effs -> return effs
functionEffs :: EnvReader m => Atom n -> m n (EffectRow n)
functionEffs f = getType f >>= \case
Pi (PiType b effs _) -> return $ ignoreHoistFailure $ hoist b effs
_ -> error "Expected a function type"
rwsFunEffects :: EnvReader m => RWS -> Atom n -> m n (EffectRow n)
rwsFunEffects rws f = getType f >>= \case
BinaryFunTy h ref effs _ -> do
let effs' = ignoreHoistFailure $ hoist ref effs
let effs'' = deleteEff (RWSEffect rws (Just (binderName h))) effs'
return $ ignoreHoistFailure $ hoist h effs''
_ -> error "Expected a binary function type"
deleteEff :: Effect n -> EffectRow n -> EffectRow n
deleteEff eff (EffectRow effs t) = EffectRow (S.delete eff effs) t
-- === the type checking/querying monad ===
-- TODO: not clear why we need the explicit `Monad2` here since it should
-- already be a superclass, transitively, through both Fallible2 and
-- MonadAtomSubst.
class ( Monad2 m, Fallible2 m, SubstReader Name m
, EnvReader2 m, EnvExtender2 m)
=> Typer (m::MonadKind2)
newtype TyperT (m::MonadKind) (i::S) (o::S) (a :: *) =
TyperT { runTyperT' :: SubstReaderT Name (EnvReaderT m) i o a }
deriving ( Functor, Applicative, Monad
, SubstReader Name
, MonadFail
, Fallible
, ScopeReader
, EnvReader, EnvExtender)
liftTyperT :: (EnvReader m', Fallible m) => TyperT m n n a -> m' n (m a)
liftTyperT cont =
liftEnvReaderT $
runSubstReaderT idSubst $
runTyperT' cont
liftHardFailTyperT :: EnvReader m' => TyperT HardFailM n n a -> m' n a
liftHardFailTyperT cont = liftM runHardFail $ liftTyperT cont
instance Fallible m => Typer (TyperT m)
-- === typeable things ===
-- Minimal complete definition: getTypeE | getTypeAndSubstE
-- (Usually we just implement `getTypeE` but for big things like blocks it can
-- be worth implementing the specialized versions too, as optimizations.)
class (SinkableE e, SubstE Name e, PrettyE e) => HasType (e::E) where
getTypeE :: Typer m => e i -> m i o (Type o)
getTypeE e = snd <$> getTypeAndSubstE e
getTypeAndSubstE :: Typer m => e i -> m i o (e o, Type o)
getTypeAndSubstE e = (,) <$> substM e <*> getTypeE e
checkTypeE :: Typer m => Type o -> e i -> m i o (e o)
checkTypeE reqTy e = do
(e', ty) <- getTypeAndSubstE e
-- TODO: Write an alphaEq variant that works modulo an equivalence
-- relation on names.
alphaEq reqTy ty >>= \case
True -> return ()
False -> do
reqTy' <- cheapNormalize reqTy
ty' <- cheapNormalize ty
alphaEq reqTy' ty' >>= \case
True -> return ()
False -> throw TypeErr $ pprint reqTy' ++ " != " ++ pprint ty'
return e'
class SinkableE e => CheckableE (e::E) where
checkE :: Typer m => e i -> m i o (e o)
checkFromHasType :: HasType e => Typer m => e i -> m i o (e o)
checkFromHasType e = fst <$> getTypeAndSubstE e
class HasNamesB b => CheckableB (b::B) where
checkB :: Typer m
=> b i i'
-> (forall o'. Ext o o' => b o o' -> m i' o' a)
-> m i o a
checkBEvidenced :: (CheckableB b, Typer m)
=> b i i'
-> (forall o'. ExtEvidence o o' -> b o o' -> m i' o' a)
-> m i o a
checkBEvidenced b cont = checkB b \b' -> cont getExtEvidence b'
-- === convenience functions ===
infixr 7 |:
(|:) :: (Typer m, HasType e) => e i -> Type o -> m i o ()
(|:) x reqTy = void $ checkTypeE reqTy x
-- === top-level env ===
instance CheckableE Block where
checkE = checkFromHasType
instance CheckableE SourceMap where
checkE sourceMap = substM sourceMap
instance CheckableE SynthCandidates where
checkE (SynthCandidates xs ys zs) =
SynthCandidates <$> mapM checkE xs
<*> mapM checkE ys
<*> (M.fromList <$> forM (M.toList zs) \(k, vs) ->
(,) <$> substM k <*> mapM checkE vs)
instance CheckableB (RecSubstFrag Binding) where
checkB frag cont = do
substBinders frag \frag' -> do
void $ dropSubst $ traverseSubstFrag checkE $ fromRecSubstFrag frag'
cont frag'
instance CheckableB EnvFrag where
checkB (EnvFrag frag effs) cont = do
checkB frag \frag' -> do
effs' <- mapM checkE effs
cont $ EnvFrag frag' effs'
instance Color c => CheckableE (Binding c) where
checkE binding = case binding of
AtomNameBinding atomNameBinding -> AtomNameBinding <$> checkE atomNameBinding
DataDefBinding dataDef -> DataDefBinding <$> checkE dataDef
TyConBinding dataDefName e -> TyConBinding <$> substM dataDefName <*> substM e
DataConBinding dataDefName idx e -> DataConBinding <$> substM dataDefName <*> pure idx <*> substM e
ClassBinding classDef e -> ClassBinding <$> substM classDef <*> substM e
SuperclassBinding className idx e -> SuperclassBinding <$> substM className <*> pure idx <*> substM e
MethodBinding className idx e -> MethodBinding <$> substM className <*> pure idx <*> substM e
ImpFunBinding f -> ImpFunBinding <$> substM f
ObjectFileBinding objfile -> ObjectFileBinding <$> substM objfile
ModuleBinding md -> ModuleBinding <$> substM md
PtrBinding ptr -> PtrBinding <$> return ptr
instance CheckableE AtomBinding where
checkE binding = case binding of
LetBound letBinding -> LetBound <$> checkE letBinding
LamBound lamBinding -> LamBound <$> checkE lamBinding
PiBound piBinding -> PiBound <$> checkE piBinding
MiscBound ty -> MiscBound <$> checkTypeE TyKind ty
SolverBound b -> SolverBound <$> checkE b
PtrLitBound ty ptr -> PtrLitBound ty <$> substM ptr
-- TODO: check the type actually matches the lambda term
SimpLamBound ty lam -> do
lam' <- substM lam
ty' <- substM ty
dropSubst $ checkNaryLamExpr lam' ty'
return $ SimpLamBound ty' lam'
FFIFunBound ty name -> do
_ <- checkFFIFunTypeM ty
FFIFunBound <$> substM ty <*> substM name
instance CheckableE SolverBinding where
checkE (InfVarBound ty ctx) = InfVarBound <$> checkTypeE TyKind ty <*> pure ctx
checkE (SkolemBound ty ) = SkolemBound <$> checkTypeE TyKind ty
instance CheckableE DataDef where
checkE = substM -- TODO
instance (CheckableE e1, CheckableE e2) => CheckableE (PairE e1 e2) where
checkE (PairE e1 e2) = PairE <$> checkE e1 <*> checkE e2
instance (CheckableB b, CheckableE e) => CheckableE (Abs b e) where
checkE (Abs b e) = checkB b \b' -> Abs b' <$> checkE e
-- === type checking core ===
instance CheckableE Atom where
checkE atom = fst <$> getTypeAndSubstE atom
instance CheckableE Expr where
checkE expr = fst <$> getTypeAndSubstE expr
instance HasType AtomName where
getTypeE name = do
name' <- substM name
atomBindingType <$> lookupEnv name'
instance HasType Atom where
getTypeE atom = case atom of
Var name -> getTypeE name
Lam lamExpr -> getTypeE lamExpr
Pi piType -> getTypeE piType
DepPair l r ty -> do
ty' <- checkTypeE TyKind ty
l' <- checkTypeE (depPairLeftTy ty') l
rTy <- instantiateDepPairTy ty' l'
r |: rTy
return $ DepPairTy ty'
DepPairTy ty -> getTypeE ty
Con con -> typeCheckPrimCon con
TC tyCon -> typeCheckPrimTC tyCon
Eff eff -> checkE eff $> EffKind
DataCon _ defName params conIx args -> do
defName' <- substM defName
(DataDef sourceName tyParamNest' absCons') <- lookupDataDef defName'
params' <- traverse checkE params
ListE cons' <- checkedApplyNaryAbs (Abs tyParamNest' (ListE absCons')) params'
let DataConDef _ conParamAbs' = cons' !! conIx
args' <- traverse checkE args
void $ checkedApplyNaryAbs conParamAbs' args'
return $ TypeCon sourceName defName' params'
TypeCon _ defName params -> do
DataDef _ tyParamNest' absCons' <- lookupDataDef =<< substM defName
params' <- traverse checkE params
void $ checkedApplyNaryAbs (Abs tyParamNest' (ListE absCons')) params'
return TyKind
LabeledRow elems -> checkFieldRowElems elems $> LabeledRowKind
Record items -> StaticRecordTy <$> mapM getTypeE items
RecordTy elems -> checkFieldRowElems elems $> TyKind
Variant vtys@(Ext (LabeledItems types) _) label i arg -> do
let ty = VariantTy vtys
let argTy = do
labelTys <- M.lookup label types
guard $ i < length labelTys
return $ labelTys NE.!! i
case argTy of
Just argType -> do
argType' <- substM argType
arg |: argType'
Nothing -> throw TypeErr $ "Bad variant: " <> pprint atom
<> " with type " <> pprint ty
checkTypeE TyKind ty
VariantTy row -> checkLabeledRow row $> TyKind
ACase e alts resultTy -> checkCase e alts resultTy Pure
DataConRef defName params args -> do
defName' <- substM defName
DataDef sourceName paramBs [DataConDef _ argBs] <- lookupDataDef defName'
paramTys <- nonDepBinderNestTypes paramBs
params' <- forMZipped paramTys params checkTypeE
argBs' <- applyNaryAbs (Abs paramBs argBs) (map SubstVal params')
checkDataConRefEnv argBs' args
return $ RawRefTy $ TypeCon sourceName defName' params'
DepPairRef l (Abs b r) ty -> do
ty' <- checkTypeE TyKind ty
l |: RawRefTy (depPairLeftTy ty')
checkB b \b' -> do
ty'' <- sinkM ty'
rTy <- instantiateDepPairTy ty'' $ Var (binderName b')
r |: RawRefTy rTy
return $ RawRefTy $ DepPairTy ty'
BoxedRef ptrsAndSizes (Abs bs body) -> do
ptrTys <- forM ptrsAndSizes \(ptr, numel) -> do
numel |: IdxRepTy
ty@(PtrTy _) <- getTypeE ptr
return ty
withFreshBinders ptrTys \bs' vs -> do
extendSubst (bs @@> vs) do
bodyTy <- getTypeE body
liftHoistExcept $ hoist bs' bodyTy
ProjectElt (i NE.:| is) v -> do
ty <- getTypeE $ case NE.nonEmpty is of
Nothing -> Var v
Just is' -> ProjectElt is' v
case ty of
TypeCon _ defName params -> do
v' <- substM v
def <- lookupDataDef defName
[DataConDef _ (Abs bs' UnitE)] <- checkedApplyDataDefParams def params
PairB bsInit (Nest (_:>bTy) _) <- return $ splitNestAt i bs'
-- `ty` can depends on earlier binders from this constructor. Rewrite
-- it to also use projections.
dropSubst $
applyNaryAbs (Abs bsInit bTy) [ SubstVal (ProjectElt (j NE.:| is) v')
| j <- iota $ nestLength bsInit]
StaticRecordTy types -> return $ toList types !! i
RecordTy _ -> throw CompilerErr "Can't project partially-known records"
ProdTy xs -> return $ xs !! i
DepPairTy t | i == 0 -> return $ depPairLeftTy t
DepPairTy t | i == 1 -> do v' <- substM v
instantiateDepPairTy t (ProjectElt (0 NE.:| is) v')
Var _ -> throw CompilerErr $ "Tried to project value of unreduced type " <> pprint ty
_ -> throw TypeErr $
"Only single-member ADTs and record types can be projected. Got " <> pprint ty <> " " <> pprint v
instance (Color c, ToBinding ann c, CheckableE ann)
=> CheckableB (BinderP c ann) where
checkB (b:>ann) cont = do
ann' <- checkE ann
withFreshBinder (getNameHint b) (toBinding ann') \b' ->
extendRenamer (b@>binderName b') $
cont $ b' :> ann'
instance HasType Expr where
getTypeE expr = case expr of
App f xs -> do
fTy <- getTypeE f
checkApp fTy xs
Atom x -> getTypeE x
Op op -> typeCheckPrimOp op
Hof hof -> typeCheckPrimHof hof
Case e alts resultTy effs -> checkCase e alts resultTy effs
instance HasType Block where
getTypeE (Block NoBlockAnn Empty expr) = do
getTypeE expr
getTypeE (Block (BlockAnn ty) decls expr) = do
tyReq <- substM ty
checkB decls \_ -> do
tyReq' <- sinkM tyReq
expr |: tyReq'
return tyReq
getTypeE _ = error "impossible"
instance CheckableB Decl where
checkB (Let b binding) cont =
checkB (b:>binding) \(b':>binding') -> cont $ Let b' binding'
instance CheckableE DeclBinding where
checkE rhs@(DeclBinding ann ty expr) = addContext msg do
ty' <- checkTypeE TyKind ty
expr' <- checkTypeE ty' expr
return $ DeclBinding ann ty' expr'
where msg = "Checking decl rhs:\n" ++ pprint rhs
instance CheckableE LamBinding where
checkE (LamBinding arr ty) = do
ty' <- checkTypeE TyKind ty
return $ LamBinding arr ty'
instance CheckableE PiBinding where
checkE (PiBinding arr ty) = do
ty' <- checkTypeE TyKind ty
return $ PiBinding arr ty'
instance CheckableB LamBinder where
checkB (LamBinder b ty arr effs) cont = do
ty' <- checkTypeE TyKind ty
let binding = toBinding $ LamBinding arr ty'
withFreshBinder (getNameHint b) binding \b' -> do
extendRenamer (b@>binderName b') do
effs' <- checkE effs
withAllowedEffects effs' $
cont $ LamBinder b' ty' arr effs'
instance HasType LamExpr where
getTypeE (LamExpr b body) = do
checkB b \b' -> do
bodyTy <- getTypeE body
return $ lamExprTy b' bodyTy
instance HasType DepPairType where
getTypeE (DepPairType b ty) = do
checkB b \_ -> ty |: TyKind
return TyKind
lamExprTy :: LamBinder n l -> Type l -> Type n
lamExprTy (LamBinder b ty arr eff) bodyTy =
Pi $ PiType (PiBinder b ty arr) eff bodyTy
instance HasType PiType where
getTypeE (PiType b@(PiBinder _ _ arr) eff resultTy) = do
checkArrowAndEffects arr eff
checkB b \_ -> do
void $ checkE eff
resultTy|:TyKind
return TyKind
instance CheckableB PiBinder where
checkB (PiBinder b ty arr) cont = do
ty' <- checkTypeE TyKind ty
let binding = toBinding $ PiBinding arr ty'
withFreshBinder (getNameHint b) binding \b' -> do
extendRenamer (b@>binderName b') do
withAllowedEffects Pure do
cont $ PiBinder b' ty' arr
instance (BindsNames b, CheckableB b) => CheckableB (Nest b) where
checkB nest cont = case nest of
Empty -> cont Empty
Nest b rest ->
checkBEvidenced b \ext1 b' ->
checkBEvidenced rest \ext2 rest' ->
withExtEvidence (ext1 >>> ext2) $
cont $ Nest b' rest'
typeCheckPrimTC :: Typer m => PrimTC (Atom i) -> m i o (Type o)
typeCheckPrimTC tc = case tc of
BaseType _ -> return TyKind
IntRange a b -> a|:IdxRepTy >> b|:IdxRepTy >> return TyKind
IndexRange t a b -> do
t' <- checkTypeE TyKind t
mapM_ (|:t') a >> mapM_ (|:t') b >> return TyKind
IndexSlice n l -> n|:TyKind >> l|:TyKind >> return TyKind
ProdType tys -> mapM_ (|:TyKind) tys >> return TyKind
SumType cs -> mapM_ (|:TyKind) cs >> return TyKind
RefType r a -> mapM_ (|:TyKind) r >> a|:TyKind >> return TyKind
TypeKind -> return TyKind
EffectRowKind -> return TyKind
LabeledRowKindTC -> return TyKind
ParIndexRange t gtid nthr -> gtid|:IdxRepTy >> nthr|:IdxRepTy >> t|:TyKind >> return TyKind
LabelType -> return TyKind
typeCheckPrimCon :: Typer m => PrimCon (Atom i) -> m i o (Type o)
typeCheckPrimCon con = case con of
Lit l -> return $ BaseTy $ litType l
ProdCon xs -> ProdTy <$> mapM getTypeE xs
SumCon ty tag payload -> do
ty'@(SumTy caseTys) <- substM ty
unless (0 <= tag && tag < length caseTys) $ throw TypeErr "Invalid SumType tag"
payload |: (caseTys !! tag)
return ty'
SumAsProd ty tag _ -> tag |:TagRepTy >> substM ty -- TODO: check!
ClassDictHole _ ty -> ty |:TyKind >> substM ty
IntRangeVal l h i -> i|:IdxRepTy >> substM (TC $ IntRange l h)
IndexRangeVal t l h i -> i|:IdxRepTy >> substM (TC $ IndexRange t l h)
IndexSliceVal _ _ _ -> error "not implemented"
BaseTypeRef p -> do
(PtrTy (_, b)) <- getTypeE p
return $ RawRefTy $ BaseTy b
TabRef tabTy -> do
Pi (PiType binder Pure (RawRefTy a)) <- getTypeE tabTy
PiBinder _ _ TabArrow <- return binder
return $ RawRefTy $ Pi $ PiType binder Pure a
ConRef conRef -> case conRef of
ProdCon xs -> RawRefTy <$> (ProdTy <$> mapM typeCheckRef xs)
IntRangeVal l h i -> do
l' <- substM l
h' <- substM h
i|:(RawRefTy IdxRepTy) >> return (RawRefTy $ TC $ IntRange l' h')
IndexRangeVal t l h i -> do
t' <- substM t
l' <- mapM substM l
h' <- mapM substM h
i|:(RawRefTy IdxRepTy)
return $ RawRefTy $ TC $ IndexRange t' l' h'
SumAsProd ty tag _ -> do -- TODO: check args!
tag |:(RawRefTy TagRepTy)
RawRefTy <$> substM ty
_ -> error $ "Not a valid ref: " ++ pprint conRef
ParIndexCon t v -> t|:TyKind >> v|:IdxRepTy >> substM t
RecordRef xs -> (RawRefTy . StaticRecordTy) <$> traverse typeCheckRef xs
LabelCon _ -> return $ TC $ LabelType
typeCheckPrimOp :: Typer m => PrimOp (Atom i) -> m i o (Type o)
typeCheckPrimOp op = case op of
TabCon ty xs -> do
ty'@(TabTyAbs piTy) <- checkTypeE TyKind ty
idxs <- indices $ piArgType piTy
forMZipped_ xs idxs \x i -> do
(_, eltTy) <- instantiatePi piTy i
x |: eltTy
return ty'
ScalarBinOp binop x y -> do
xTy <- typeCheckBaseType x
yTy <- typeCheckBaseType y
TC <$> BaseType <$> checkBinOp binop xTy yTy
ScalarUnOp unop x -> do
xTy <- typeCheckBaseType x
TC <$> BaseType <$> checkUnOp unop xTy
Select p x y -> do
p |: (BaseTy $ Scalar Word8Type)
ty <- getTypeE x
y |: ty
return ty
UnsafeFromOrdinal ty i -> ty|:TyKind >> i|:IdxRepTy >> substM ty
ToOrdinal i -> getTypeE i $> IdxRepTy
IdxSetSize i -> getTypeE i $> IdxRepTy
Inject i -> do
TC tc <- getTypeE i
case tc of
IndexRange ty _ _ -> return ty
ParIndexRange ty _ _ -> return ty
_ -> throw TypeErr $ "Unsupported inject argument type: " ++ pprint (TC tc)
PrimEffect ref m -> do
TC (RefType ~(Just (Var h')) s) <- getTypeE ref
case m of
MGet -> declareEff (RWSEffect State $ Just h') $> s
MPut x -> x|:s >> declareEff (RWSEffect State $ Just h') $> UnitTy
MAsk -> declareEff (RWSEffect Reader $ Just h') $> s
MExtend _ x -> x|:s >> declareEff (RWSEffect Writer $ Just h') $> UnitTy
IndexRef ref i -> do
getTypeE ref >>= \case
RefTy h (Pi (PiType (PiBinder b iTy TabArrow) Pure eltTy)) -> do
i' <- checkTypeE iTy i
eltTy' <- applyAbs (Abs b eltTy) (SubstVal i')
return $ RefTy h eltTy'
ty -> error $ "Not a reference to a table: " ++
pprint (Op op) ++ " : " ++ pprint ty
ProjRef i ref -> do
getTypeE ref >>= \case
RefTy h (ProdTy tys) -> return $ RefTy h $ tys !! i
ty -> error $ "Not a reference to a product: " ++ pprint ty
IOAlloc t n -> do
n |: IdxRepTy
declareEff IOEffect
return $ PtrTy (Heap CPU, t)
IOFree ptr -> do
PtrTy _ <- getTypeE ptr
declareEff IOEffect
return UnitTy
PtrOffset arr off -> do
PtrTy (a, b) <- getTypeE arr
off |: IdxRepTy
return $ PtrTy (a, b)
PtrLoad ptr -> do
PtrTy (_, t) <- getTypeE ptr
declareEff IOEffect
return $ BaseTy t
PtrStore ptr val -> do
PtrTy (_, t) <- getTypeE ptr
val |: BaseTy t
declareEff IOEffect
return $ UnitTy
SliceOffset s i -> do
TC (IndexSlice n l) <- getTypeE s
l' <- getTypeE i
checkAlphaEq l l'
return n
SliceCurry s i -> do
TC (IndexSlice n (PairTy u v)) <- getTypeE s
u' <- getTypeE i
checkAlphaEq u u'
return $ TC $ IndexSlice n v
VectorBinOp _ _ _ -> throw CompilerErr "Vector operations are not supported at the moment"
VectorPack xs -> do
unless (length xs == vectorWidth) $ throw TypeErr lengthMsg
BaseTy (Scalar sb) <- getTypeE $ head xs
mapM_ (|: (BaseTy (Scalar sb))) xs
return $ BaseTy $ Vector sb
where lengthMsg = "VectorBroadcast should have exactly " ++ show vectorWidth ++
" elements: " ++ pprint op
VectorIndex x i -> do
BaseTy (Vector sb) <- getTypeE x
i |: TC (IntRange (IdxRepVal 0) (IdxRepVal $ fromIntegral vectorWidth))
return $ BaseTy $ Scalar sb
ThrowError ty -> ty|:TyKind >> substM ty
ThrowException ty -> do
declareEff ExceptionEffect
ty|:TyKind >> substM ty
CastOp t@(Var _) _ -> t |: TyKind >> substM t
CastOp destTy e -> do
sourceTy' <- getTypeE e
destTy |: TyKind
destTy' <- substM destTy
checkValidCast sourceTy' destTy'
return $ destTy'
RecordCons l r -> do
lty <- getTypeE l
rty <- getTypeE r
case (lty, rty) of
(RecordTyWithElems lelems, RecordTyWithElems relems) ->
return $ RecordTyWithElems $ lelems ++ relems
_ -> throw TypeErr $ "Can't concatenate " <> pprint lty <> " and " <> pprint rty <> " as records"
RecordConsDynamic lab val record -> do
lab' <- checkTypeE (TC LabelType) lab
vty <- getTypeE val
rty <- getTypeE record
case rty of
RecordTy rest -> case lab' of
Con (LabelCon l) -> return $ RecordTy $ prependFieldRowElem (StaticFields (labeledSingleton l vty)) rest
Var labVar -> return $ RecordTy $ prependFieldRowElem (DynField labVar vty) rest
_ -> error "Unexpected label atom"
_ -> throw TypeErr $ "Can't add a dynamic field to a non-record value of type " <> pprint rty
RecordSplitDynamic lab record -> do
lab' <- cheapNormalize =<< checkTypeE (TC LabelType) lab
rty <- getTypeE record
case (lab', rty) of
(Con (LabelCon l), RecordTyWithElems (StaticFields items:rest)) -> do
-- We could cheap normalize the rest to increase the chance of this
-- succeeding, but no need to for now.
unless (isJust $ lookupLabelHead items l) $ throw TypeErr "Label not immediately present in record"
let (h, items') = splitLabeledItems (labeledSingleton l ()) items
return $ PairTy (head $ toList h) $ RecordTyWithElems (StaticFields items':rest)
(Var labVar', RecordTyWithElems (DynField labVar'' ty:rest)) | labVar' == labVar'' ->
return $ PairTy ty $ RecordTyWithElems rest
-- There are more cases we could implement, but do we need to?
_ -> throw TypeErr $ "Can't split a label " <> pprint lab' <> " from atom of type " <> pprint rty
RecordSplit fields record -> do
fields' <- cheapNormalize =<< checkTypeE LabeledRowKind fields
fullty <- cheapNormalize =<< getTypeE record
let splitFailed = throw TypeErr $ "Invalid record split: " <> pprint fields' <> " from " <> pprint fullty
case (fields', fullty) of
(LabeledRow els, RecordTyWithElems els') ->
stripPrefix (fromFieldRowElems els) els' >>= \case
Just rest -> return $ StaticRecordTy $ Unlabeled
[ RecordTy els, RecordTyWithElems rest ]
Nothing -> splitFailed
(Var v, RecordTyWithElems (DynFields v':rest)) | v == v' ->
return $ StaticRecordTy $ Unlabeled
[ RecordTyWithElems [DynFields v'], RecordTyWithElems rest ]
_ -> splitFailed
where
stripPrefix = curry \case
([] , ys ) -> return $ Just ys
(x:xs, y:ys) -> alphaEq x y >>= \case
True -> stripPrefix xs ys
False -> case (x, y) of
(StaticFields xf, StaticFields yf) -> do
NoExt rest <- labeledRowDifference (NoExt yf) (NoExt xf)
return $ Just $ StaticFields rest : ys
_ -> return Nothing
_ -> return Nothing
VariantLift types variant -> do
mapM_ (|: TyKind) types
types' <- mapM substM types
rty <- getTypeE variant
rest <- case rty of
VariantTy rest -> return rest
_ -> throw TypeErr $ "Can't add alternatives to a non-variant object "
<> pprint variant <> " (of type " <> pprint rty <> ")"
return $ VariantTy $ prefixExtLabeledItems types' rest
VariantSplit types variant -> do
mapM_ (|: TyKind) types
types' <- mapM substM types
fullty <- getTypeE variant
full <- case fullty of
VariantTy full -> return full
_ -> throw TypeErr $ "Can't split a non-variant object "
<> pprint variant <> " (of type " <> pprint fullty
<> ")"
diff <- labeledRowDifference full (NoExt types')
return $ VariantTy $ NoExt $
Unlabeled [ VariantTy $ NoExt types', VariantTy diff ]
DataConTag x -> do
TypeCon _ _ _ <- getTypeE x
return TagRepTy
ToEnum t x -> do
x |: Word8Ty
t' <- checkTypeE TyKind t
case t' of
TypeCon _ dataDefName [] -> do
DataDef _ _ dataConDefs <- lookupDataDef dataDefName
forM_ dataConDefs \(DataConDef _ (Abs binders _)) -> checkEmptyNest binders
VariantTy _ -> return () -- TODO: check empty payload
SumTy cases -> forM_ cases \cty -> checkAlphaEq cty UnitTy
_ -> error $ "Not a sum type: " ++ pprint t'
return t'
SumToVariant x -> getTypeE x >>= \case
SumTy cases -> return $ VariantTy $ NoExt $ foldMap (labeledSingleton "c") cases
ty -> error $ "Not a sum type: " ++ pprint ty
OutputStreamPtr ->
return $ BaseTy $ hostPtrTy $ hostPtrTy $ Scalar Word8Type
where hostPtrTy ty = PtrType (Heap CPU, ty)
SynthesizeDict _ ty -> checkTypeE TyKind ty
typeCheckPrimHof :: Typer m => PrimHof (Atom i) -> m i o (Type o)
typeCheckPrimHof hof = addContext ("Checking HOF:\n" ++ pprint hof) case hof of
For _ f -> do
Pi (PiType (PiBinder b argTy PlainArrow) eff eltTy) <- getTypeE f
eff' <- liftHoistExcept $ hoist b eff
declareEffs eff'
return $ Pi $ PiType (PiBinder b argTy TabArrow) Pure eltTy
Tile dim fT fS -> do
(TC (IndexSlice n l), effT, tr) <- getTypeE fT >>= fromNonDepPiType PlainArrow
(sTy , effS, sr) <- getTypeE fS >>= fromNonDepPiType PlainArrow
checkAlphaEq n sTy
checkAlphaEq effT effS
declareEffs effT
(leadingIdxTysT, Pure, resultTyT) <- fromNaryNonDepPiType (replicate dim TabArrow) tr
(leadingIdxTysS, Pure, resultTyS) <- fromNaryNonDepPiType (replicate dim TabArrow) sr
(dvTy, Pure, resultTyT') <- fromNonDepPiType TabArrow resultTyT
checkAlphaEq l dvTy
checkAlphaEq (ListE leadingIdxTysT) (ListE leadingIdxTysS)
checkAlphaEq resultTyT' resultTyS
naryNonDepPiType TabArrow Pure (leadingIdxTysT ++ [n]) resultTyT'
PTileReduce baseMonoids n mapping -> do
-- mapping : gtid:IdxRepTy -> nthr:IdxRepTy -> (...((ParIndexRange n gtid nthr)=>a, acc{n})..., acc1)
([_gtid, _nthr], Pure, mapResultTy) <-
getTypeE mapping >>= fromNaryNonDepPiType [PlainArrow, PlainArrow]
(tiledArrTy, accTys) <- fromLeftLeaningConsListTy (length baseMonoids) mapResultTy
(_, tileElemTy) <- fromNonDepTabTy tiledArrTy
-- TOOD: figure out what's going on with threadRange
-- let threadRange = TC $ ParIndexRange n (binderAsVar gtid) (binderAsVar nthr)
-- checkAlphaEq threadRange threadRange'
-- TODO: Check compatibility of baseMonoids and accTys (need to be careful about lifting!)
-- PTileReduce n mapping : (n=>a, (acc1, ..., acc{n}))
n' <- substM n
tabTy <- n' ==> tileElemTy
-- PTileReduce n mapping : (n=>a, (acc1, ..., acc{n}))
return $ PairTy tabTy $ mkConsListTy accTys
While body -> do
Pi (PiType (PiBinder b UnitTy PlainArrow) eff condTy) <- getTypeE body
PairE eff' condTy' <- liftHoistExcept $ hoist b $ PairE eff condTy
declareEffs eff'
checkAlphaEq (BaseTy $ Scalar Word8Type) condTy'
return UnitTy
Linearize f -> do
Pi (PiType (PiBinder binder a PlainArrow) Pure b) <- getTypeE f
b' <- liftHoistExcept $ hoist binder b
fLinTy <- a --@ b'
a --> PairTy b' fLinTy
Transpose f -> do
Pi (PiType (PiBinder binder a LinArrow) Pure b) <- getTypeE f
b' <- liftHoistExcept $ hoist binder b
b' --@ a
RunReader r f -> do
(resultTy, readTy) <- checkRWSAction Reader f
r |: readTy
return resultTy
RunWriter _ f -> do
-- XXX: We can't verify compatibility between the base monoid and f, because
-- the only way in which they are related in the runAccum definition is via
-- the AccumMonoid typeclass. The frontend constraints should be sufficient
-- to ensure that only well typed programs are accepted, but it is a bit
-- disappointing that we cannot verify that internally. We might want to consider
-- e.g. only disabling this check for prelude.
uncurry PairTy <$> checkRWSAction Writer f
RunState s f -> do
(resultTy, stateTy) <- checkRWSAction State f
s |: stateTy
return $ PairTy resultTy stateTy
RunIO f -> do
Pi (PiType (PiBinder b UnitTy PlainArrow) eff resultTy) <- getTypeE f
PairE eff' resultTy' <- liftHoistExcept $ hoist b $ PairE eff resultTy
extendAllowedEffect IOEffect $ declareEffs eff'
return resultTy'
CatchException f -> do
Pi (PiType (PiBinder b UnitTy PlainArrow) eff resultTy) <- getTypeE f
PairE eff' resultTy' <- liftHoistExcept $ hoist b $ PairE eff resultTy
extendAllowedEffect ExceptionEffect $ declareEffs eff'
return $ MaybeTy resultTy'
checkRWSAction :: Typer m => RWS -> Atom i -> m i o (Type o, Type o)
checkRWSAction rws f = do
BinaryFunTy regionBinder refBinder eff resultTy <- getTypeE f
allowed <- getAllowedEffects
dropSubst $
substBinders regionBinder \regionBinder' -> do
substBinders refBinder \_ -> do
allowed' <- sinkM allowed
eff' <- substM eff
regionName <- sinkM $ binderName regionBinder'
withAllowedEffects allowed' $
extendAllowedEffect (RWSEffect rws $ Just regionName) $
declareEffs eff'
PiBinder _ (RefTy _ referentTy) _ <- return refBinder
referentTy' <- liftHoistExcept $ hoist regionBinder referentTy
resultTy' <- liftHoistExcept $ hoist (PairB regionBinder refBinder) resultTy
return (resultTy', referentTy')
-- Having this as a separate helper function helps with "'b0' is untouchable" errors
-- from GADT+monad type inference.
checkEmptyNest :: Fallible m => Nest b n l -> m ()
checkEmptyNest Empty = return ()
checkEmptyNest _ = throw TypeErr "Not empty"
nonDepBinderNestTypes :: Typer m => Nest Binder o o' -> m i o [Type o]
nonDepBinderNestTypes Empty = return []
nonDepBinderNestTypes (Nest (b:>ty) rest) = do
Abs rest' UnitE <- liftHoistExcept $ hoist b $ Abs rest UnitE
restTys <- nonDepBinderNestTypes rest'
return $ ty : restTys
checkCase :: Typer m => HasType body
=> Atom i -> [AltP body i] -> Type i -> EffectRow i -> m i o (Type o)
checkCase scrut alts resultTy effs = do
declareEffs =<< substM effs
resultTy' <- substM resultTy
scrutTy <- getTypeE scrut
altsBinderTys <- caseAltsBinderTys scrutTy
forMZipped_ alts altsBinderTys \alt bs ->
checkAlt resultTy' bs alt
return resultTy'
caseAltsBinderTys :: (Fallible1 m, EnvReader m)
=> Type n -> m n [EmptyAbs (Nest Binder) n]
caseAltsBinderTys ty = case ty of
TypeCon _ defName params -> do
def <- lookupDataDef defName
cons <- checkedApplyDataDefParams def params
return [bs | DataConDef _ bs <- cons]
VariantTy (NoExt types) -> do
mapM typeAsBinderNest $ toList types
VariantTy _ -> fail "Can't pattern-match partially-known variants"
SumTy cases -> mapM typeAsBinderNest cases
_ -> fail $ "Case analysis only supported on ADTs and variants, not on " ++ pprint ty
checkDataConRefEnv :: Typer m
=> EmptyAbs (Nest Binder) o
-> EmptyAbs (Nest DataConRefBinding) i
-> m i o ()
checkDataConRefEnv (EmptyAbs Empty) (Abs Empty UnitE) = return ()
checkDataConRefEnv (EmptyAbs (Nest b restBs)) (EmptyAbs (Nest refBinding restRefs)) = do
let DataConRefBinding b' ref = refBinding
ref |: RawRefTy (binderAnn b)
bAnn' <- substM $ binderAnn b'
checkAlphaEq (binderAnn b) bAnn'
checkB b' \b'' -> do
ab <- sinkM $ Abs b (EmptyAbs restBs)
restBs' <- applyAbs ab (binderName b'')
checkDataConRefEnv restBs' (EmptyAbs restRefs)
checkDataConRefEnv _ _ = throw CompilerErr $ "Mismatched args and binders"
typeAsBinderNest :: ScopeReader m => Type n -> m n (Abs (Nest Binder) UnitE n)
typeAsBinderNest ty = do
Abs ignored body <- toConstAbs UnitE
return $ Abs (Nest (ignored:>ty) Empty) body
checkAlt :: HasType body => Typer m
=> Type o -> EmptyAbs (Nest Binder) o -> AltP body i -> m i o ()
checkAlt resultTyReq reqBs (Abs bs body) = do
bs' <- substM (EmptyAbs bs)
checkAlphaEq reqBs bs'
substBinders bs \_ -> do
resultTyReq' <- sinkM resultTyReq
body |: resultTyReq'
checkApp :: Typer m => Type o -> NonEmpty (Atom i) -> m i o (Type o)
checkApp fTy xs = case fromNaryPiType (length xs) fTy of
Just (NaryPiType bs effs resultTy) -> do
xs' <- mapM substM xs
checkArgTys (nonEmptyToNest bs) (toList xs')
let subst = bs @@> fmap SubstVal xs'
PairE effs' resultTy' <- applySubst subst $ PairE effs resultTy
declareEffs effs'
return resultTy'
Nothing -> throw TypeErr $
"Not a " ++ show (length xs) ++ "-argument pi type: " ++ pprint fTy
++ " (tried to apply it to: " ++ pprint xs ++ ")"
numNaryPiArgs :: NaryPiType n -> Int
numNaryPiArgs (NaryPiType (NonEmptyNest _ bs) _ _) = 1 + nestLength bs
naryLamExprType :: EnvReader m => NaryLamExpr n -> m n (NaryPiType n)
naryLamExprType (NaryLamExpr (NonEmptyNest b bs) eff body) = liftHardFailTyperT do
substBinders b \b' -> do
substBinders bs \bs' -> do
let b'' = binderToPiBinder b'
let bs'' = fmapNest binderToPiBinder bs'
eff' <- substM eff
bodyTy <- getTypeE body
return $ NaryPiType (NonEmptyNest b'' bs'') eff' bodyTy
where
binderToPiBinder :: Binder n l -> PiBinder n l
binderToPiBinder (nameBinder:>ty) = PiBinder nameBinder ty PlainArrow
checkNaryLamExpr :: Typer m => NaryLamExpr i -> NaryPiType o -> m i o ()
checkNaryLamExpr lam ty = naryLamExprAsAtom lam |: naryPiTypeAsType ty
data NaryPiFlavor = TabOnlyFlavor -- nary pi nest of TabArrows
| NonTabFlavor -- nary pi nest of non-table arrows
| AnyFlavor -- nary pi nest of either only tab arrow or only non-tab arrows
asNaryPiType :: NaryPiFlavor -> Type n -> Maybe (NaryPiType n)
asNaryPiType flavor ty = case ty of
Pi (PiType b@(PiBinder _ _ arr) effs resultTy) | matchesFlavor arr -> case effs of
Pure -> case asNaryPiType (inferFlavor arr) resultTy of
Just (NaryPiType (NonEmptyNest b' bs) effs' resultTy') ->
Just $ NaryPiType (NonEmptyNest b (Nest b' bs)) effs' resultTy'
Nothing -> Just $ NaryPiType (NonEmptyNest b Empty) Pure resultTy
_ -> Just $ NaryPiType (NonEmptyNest b Empty) effs resultTy
_ -> Nothing
where
matchesFlavor arr = case flavor of
AnyFlavor -> True
TabOnlyFlavor -> arr == TabArrow
NonTabFlavor -> arr /= TabArrow
inferFlavor arr = case flavor of
AnyFlavor -> if arr == TabArrow then TabOnlyFlavor else NonTabFlavor
_ -> flavor
checkArgTys
:: Typer m
=> Nest PiBinder o o'
-> [Atom o]
-> m i o ()
checkArgTys Empty [] = return ()
checkArgTys (Nest b bs) (x:xs) = do
dropSubst $ x |: binderType b
Abs bs' UnitE <- applySubst (b@>SubstVal x) (EmptyAbs bs)
checkArgTys bs' xs
checkArgTys _ _ = throw TypeErr $ "wrong number of args"
typeCheckRef :: Typer m => HasType e => e i -> m i o (Type o)
typeCheckRef x = do
TC (RefType _ a) <- getTypeE x
return a
checkArrowAndEffects :: Fallible m => Arrow -> EffectRow n -> m ()
checkArrowAndEffects PlainArrow _ = return ()
checkArrowAndEffects _ Pure = return ()
checkArrowAndEffects _ _ = throw TypeErr $ "Only plain arrows may have effects"
checkIntBaseType :: Fallible m => Bool -> BaseType -> m ()
checkIntBaseType allowVector t = case t of
Scalar sbt -> checkSBT sbt
Vector sbt | allowVector -> checkSBT sbt
_ -> notInt
where
checkSBT sbt = case sbt of
Int64Type -> return ()
Int32Type -> return ()
Word8Type -> return ()
Word32Type -> return ()
Word64Type -> return ()
_ -> notInt
notInt = throw TypeErr $ "Expected a fixed-width " ++ (if allowVector then "" else "scalar ") ++
"integer type, but found: " ++ pprint t
checkFloatBaseType :: Fallible m => Bool -> BaseType -> m ()
checkFloatBaseType allowVector t = case t of
Scalar sbt -> checkSBT sbt
Vector sbt | allowVector -> checkSBT sbt
_ -> notFloat
where
checkSBT sbt = case sbt of
Float64Type -> return ()
Float32Type -> return ()
_ -> notFloat
notFloat = throw TypeErr $ "Expected a fixed-width " ++ (if allowVector then "" else "scalar ") ++
"floating-point type, but found: " ++ pprint t
checkValidCast :: Fallible1 m => Type n -> Type n -> m n ()
checkValidCast (TC (IntRange _ _)) IdxRepTy = return ()
checkValidCast IdxRepTy (TC (IntRange _ _)) = return ()
checkValidCast (TC (IndexRange _ _ _)) IdxRepTy = return ()
checkValidCast IdxRepTy (TC (IndexRange _ _ _)) = return ()
checkValidCast (BaseTy l) (BaseTy r) = checkValidBaseCast l r
checkValidCast sourceTy destTy =
throw TypeErr $ "Can't cast " ++ pprint sourceTy ++ " to " ++ pprint destTy
checkValidBaseCast :: Fallible m => BaseType -> BaseType -> m ()
checkValidBaseCast (PtrType _) (PtrType _) = return ()
checkValidBaseCast (PtrType _) (Scalar Int64Type) = return ()
checkValidBaseCast (Scalar Int64Type) (PtrType _) = return ()
checkValidBaseCast sourceTy destTy =
checkScalarType sourceTy >> checkScalarType destTy
where
checkScalarType ty = case ty of
Scalar Int64Type -> return ()
Scalar Int32Type -> return ()
Scalar Word8Type -> return ()
Scalar Word32Type -> return ()
Scalar Word64Type -> return ()
Scalar Float64Type -> return ()
Scalar Float32Type -> return ()
_ -> throw TypeErr $ "Can't cast " ++ pprint sourceTy ++ " to " ++ pprint destTy
typeCheckBaseType :: Typer m => HasType e => e i -> m i o BaseType
typeCheckBaseType e =
getTypeE e >>= \case
TC (BaseType b) -> return b
ty -> throw TypeErr $ "Expected a base type. Got: " ++ pprint ty
litType :: LitVal -> BaseType
litType v = case v of
Int64Lit _ -> Scalar Int64Type
Int32Lit _ -> Scalar Int32Type
Word8Lit _ -> Scalar Word8Type
Word32Lit _ -> Scalar Word32Type
Word64Lit _ -> Scalar Word64Type
Float64Lit _ -> Scalar Float64Type
Float32Lit _ -> Scalar Float32Type
PtrLit (PtrSnapshot t _) -> PtrType t
PtrLit (PtrLitVal t _) -> PtrType t
VecLit l -> Vector sb
where Scalar sb = litType $ head l
data ArgumentType = SomeFloatArg | SomeIntArg | SomeUIntArg
data ReturnType = SameReturn | Word8Return
checkOpArgType :: Fallible m => ArgumentType -> BaseType -> m ()
checkOpArgType argTy x =
case argTy of
SomeIntArg -> checkIntBaseType True x
SomeUIntArg -> assertEq x (Scalar Word8Type) ""
SomeFloatArg -> checkFloatBaseType True x
checkBinOp :: Fallible m => BinOp -> BaseType -> BaseType -> m BaseType
checkBinOp op x y = do
checkOpArgType argTy x
assertEq x y ""
return $ case retTy of
SameReturn -> x
Word8Return -> Scalar Word8Type
where
(argTy, retTy) = case op of
IAdd -> (ia, sr); ISub -> (ia, sr)
IMul -> (ia, sr); IDiv -> (ia, sr)
IRem -> (ia, sr);
ICmp _ -> (ia, br)
FAdd -> (fa, sr); FSub -> (fa, sr)
FMul -> (fa, sr); FDiv -> (fa, sr);
FPow -> (fa, sr)
FCmp _ -> (fa, br)
BAnd -> (ia, sr); BOr -> (ia, sr)
BXor -> (ia, sr)
BShL -> (ia, sr); BShR -> (ia, sr)
where
ia = SomeIntArg; fa = SomeFloatArg
br = Word8Return; sr = SameReturn
checkUnOp :: Fallible m => UnOp -> BaseType -> m BaseType
checkUnOp op x = do
checkOpArgType argTy x
return $ case retTy of
SameReturn -> x
Word8Return -> Scalar Word8Type
where
(argTy, retTy) = case op of
Exp -> (f, sr)
Exp2 -> (f, sr)
Log -> (f, sr)
Log2 -> (f, sr)
Log10 -> (f, sr)
Log1p -> (f, sr)
Sin -> (f, sr)
Cos -> (f, sr)
Tan -> (f, sr)
Sqrt -> (f, sr)
Floor -> (f, sr)
Ceil -> (f, sr)
Round -> (f, sr)
LGamma -> (f, sr)
FNeg -> (f, sr)
BNot -> (u, sr)
where
u = SomeUIntArg; f = SomeFloatArg; sr = SameReturn
-- === singleton types ===
-- TODO: the following implementation should be valid:
-- isSingletonType :: EnvReader m => Type n -> m n Bool
-- isSingletonType ty =
-- singletonTypeVal ty >>= \case
-- Nothing -> return False
-- Just _ -> return True
-- But we want to be able to query the singleton-ness of types that we haven't
-- implemented tangent types for. So instead we do a separate case analysis.
isSingletonType :: EnvReader m => Type n -> m n Bool
isSingletonType topTy =
case checkIsSingleton topTy of
Just () -> return True
Nothing -> return False
where
checkIsSingleton :: Type n -> Maybe ()
checkIsSingleton ty = case ty of
Pi (PiType _ _ body) -> checkIsSingleton body
StaticRecordTy items -> mapM_ checkIsSingleton items
TC con -> case con of
ProdType tys -> mapM_ checkIsSingleton tys
_ -> Nothing
_ -> Nothing
singletonTypeVal :: EnvReader m => Type n -> m n (Maybe (Atom n))
singletonTypeVal ty = liftTyperT do
singletonTypeVal' ty
-- TODO: TypeCon with a single case?
singletonTypeVal'
:: (MonadFail2 m, SubstReader Name m, EnvReader2 m, EnvExtender2 m)
=> Type i -> m i o (Atom o)
singletonTypeVal' ty = case ty of
Pi (PiType b@(PiBinder _ _ TabArrow) Pure body) ->
substBinders b \b' -> do
body' <- singletonTypeVal' body
return $ Pi $ PiType b' Pure body'
StaticRecordTy items -> Record <$> traverse singletonTypeVal' items
TC con -> case con of
ProdType tys -> ProdVal <$> traverse singletonTypeVal' tys
_ -> notASingleton
_ -> notASingleton
where notASingleton = fail "not a singleton type"
-- === various helpers for querying types ===
getBaseMonoidType :: Fallible1 m => ScopeReader m => Type n -> m n (Type n)
getBaseMonoidType ty = case ty of
Pi (PiType b _ resultTy) -> liftHoistExcept $ hoist b resultTy
_ -> return ty
instantiateDataDef :: ScopeReader m => DataDef n -> [Type n] -> m n [DataConDef n]
instantiateDataDef (DataDef _ bs cons) params =
fromListE <$> applyNaryAbs (Abs bs (ListE cons)) (map SubstVal params)
checkedApplyDataDefParams :: (EnvReader m, Fallible1 m) => DataDef n -> [Type n] -> m n [DataConDef n]
checkedApplyDataDefParams (DataDef _ bs cons) params =
fromListE <$> checkedApplyNaryAbs (Abs bs (ListE cons)) params
-- TODO: Subst all at once, not one at a time!
checkedApplyNaryAbs :: (EnvReader m, Fallible1 m, SinkableE e, SubstE AtomSubstVal e)
=> Abs (Nest Binder) e o -> [Atom o] -> m o (e o)
checkedApplyNaryAbs (Abs nest e) args = case (nest, args) of
(Empty , []) -> return e
(Nest b@(_:>bTy) bs, x:t) -> do
xTy <- getType x
checkAlphaEq bTy xTy
flip checkedApplyNaryAbs t =<< applyAbs (Abs b $ Abs bs e) (SubstVal x)
(_ , _ ) -> throw CompilerErr $ "Length mismatch in checkedApplyNaryAbs"
-- === effects ===
instance CheckableE EffectRow where
checkE effRow@(EffectRow effs effTail) = do
forM_ effs \eff -> case eff of
RWSEffect _ (Just v) -> Var v |: TyKind
RWSEffect _ Nothing -> return ()
ExceptionEffect -> return ()
IOEffect -> return ()
forM_ effTail \v -> do
v' <- substM v
ty <- atomBindingType <$> lookupEnv v'
checkAlphaEq EffKind ty
substM effRow
declareEff :: Typer m => Effect o -> m i o ()
declareEff eff = declareEffs $ oneEffect eff
declareEffs :: Typer m => EffectRow o -> m i o ()
declareEffs effs = do
allowed <- getAllowedEffects
checkExtends allowed effs
extendAllowedEffect :: Typer m => Effect o -> m i o () -> m i o ()
extendAllowedEffect newEff cont = do
effs <- getAllowedEffects
withAllowedEffects (extendEffect newEff effs) cont
checkExtends :: Fallible m => EffectRow n -> EffectRow n -> m ()
checkExtends allowed (EffectRow effs effTail) = do
let (EffectRow allowedEffs allowedEffTail) = allowed
case effTail of
Just _ -> assertEq allowedEffTail effTail ""
Nothing -> return ()
forM_ effs \eff -> unless (eff `elem` allowedEffs) $
throw CompilerErr $ "Unexpected effect: " ++ pprint eff ++
"\nAllowed: " ++ pprint allowed
extendEffect :: Effect n -> EffectRow n -> EffectRow n
extendEffect eff (EffectRow effs t) = EffectRow (S.insert eff effs) t
oneEffect :: Effect n -> EffectRow n
oneEffect eff = EffectRow (S.singleton eff) Nothing
-- === labeled row types ===
checkFieldRowElems :: Typer m => FieldRowElems i -> m i o ()
checkFieldRowElems els = mapM_ checkElem elemList
where
elemList = fromFieldRowElems els
checkElem = \case
StaticFields items -> checkLabeledRow $ NoExt items
DynField labVar ty -> do
Var labVar |: TC LabelType
ty |: TyKind
DynFields row -> checkLabeledRow $ Ext mempty $ Just row
checkLabeledRow :: Typer m => ExtLabeledItems (Type i) (AtomName i) -> m i o ()
checkLabeledRow (Ext items rest) = do
mapM_ (|: TyKind) items
forM_ rest \name -> do
name' <- lookupSubstM name
ty <- atomBindingType <$> lookupEnv name'
checkAlphaEq LabeledRowKind ty
labeledRowDifference :: Typer m
=> ExtLabeledItems (Type o) (AtomName o)
-> ExtLabeledItems (Type o) (AtomName o)
-> m i o (ExtLabeledItems (Type o) (AtomName o))
labeledRowDifference (Ext (LabeledItems items) rest)
(Ext (LabeledItems subitems) subrest) = do
-- Check types in the right.
_ <- flip M.traverseWithKey subitems \label subtypes ->
case M.lookup label items of
Just types -> forMZipped_
subtypes
(NE.fromList $ NE.take (length subtypes) types)
checkAlphaEq
Nothing -> throw TypeErr $ "Extracting missing label " ++ show label
-- Extract remaining types from the left.
let
neDiff xs ys = NE.nonEmpty $ NE.drop (length ys) xs
diffitems = M.differenceWith neDiff items subitems
-- Check tail.
diffrest <- case (subrest, rest) of
(Nothing, _) -> return rest
(Just v, Just v') | v == v' -> return Nothing
_ -> throw TypeErr $ "Row tail " ++ pprint subrest
++ " is not known to be a subset of " ++ pprint rest
return $ Ext (LabeledItems diffitems) diffrest
projectLength :: (Fallible1 m, EnvReader m) => Type n -> m n Int
projectLength ty = case ty of
TypeCon _ defName params -> do
def <- lookupDataDef defName
[DataConDef _ (Abs bs UnitE)] <- instantiateDataDef def params
return $ nestLength bs
StaticRecordTy types -> return $ length types
ProdTy tys -> return $ length tys
_ -> error $ "Projecting a type that doesn't support projecting: " ++ pprint ty
-- === "Data" type class ===
runCheck
:: (EnvReader m, SinkableE e)
=> (forall l. DExt n l => TyperT Maybe l l (e l))
-> m n (Maybe (e n))
runCheck cont = do
Distinct <- getDistinct
liftTyperT $ cont
asFFIFunType :: EnvReader m => Type n -> m n (Maybe (IFunType, NaryPiType n))
asFFIFunType ty = return do
naryPiTy <- asNaryPiType NonTabFlavor ty
impTy <- checkFFIFunTypeM naryPiTy
return (impTy, naryPiTy)
checkFFIFunTypeM :: Fallible m => NaryPiType n -> m IFunType
checkFFIFunTypeM (NaryPiType (NonEmptyNest b bs) eff resultTy) = do
argTy <- checkScalar $ binderType b
case bs of
Empty -> do
assertEq eff (oneEffect IOEffect) ""
resultTys <- checkScalarOrPairType resultTy
let cc = case length resultTys of
0 -> error "Not implemented"
1 -> FFIFun
_ -> FFIMultiResultFun
return $ IFunType cc [argTy] resultTys
Nest b' rest -> do
let naryPiRest = NaryPiType (NonEmptyNest b' rest) eff resultTy
IFunType cc argTys resultTys <- checkFFIFunTypeM naryPiRest
return $ IFunType cc (argTy:argTys) resultTys
checkScalar :: Fallible m => Type n -> m BaseType
checkScalar (BaseTy ty) = return ty
checkScalar ty = throw TypeErr $ pprint ty
checkScalarOrPairType :: Fallible m => Type n -> m [BaseType]
checkScalarOrPairType (PairTy a b) = do
tys1 <- checkScalarOrPairType a
tys2 <- checkScalarOrPairType b
return $ tys1 ++ tys2
checkScalarOrPairType (BaseTy ty) = return [ty]
checkScalarOrPairType ty = throw TypeErr $ pprint ty
-- TODO: consider effects
asFirstOrderFunction :: EnvReader m => Type n -> m n (Maybe (NaryPiType n))
asFirstOrderFunction ty = runCheck $ asFirstOrderFunctionM (sink ty)
asFirstOrderFunctionM :: Typer m => Type i -> m i o (NaryPiType o)
asFirstOrderFunctionM ty = do
naryPi@(NaryPiType bs eff resultTy) <- liftMaybe $ asNaryPiType NonTabFlavor ty
substBinders bs \(NonEmptyNest b' bs') -> do
ts <- mapM sinkM $ bindersTypes $ Nest b' bs'
dropSubst $ mapM_ checkDataLike ts
Pure <- return eff
checkDataLike resultTy
substM naryPi
isData :: EnvReader m => Type n -> m n Bool
isData ty = liftM isJust $ runCheck do
checkDataLike (sink ty)
return UnitE
checkDataLike :: Typer m => Type i -> m i o ()
checkDataLike ty = case ty of
Var _ -> error "Not implemented"
TabTy b eltTy -> do
substBinders b \_ ->
checkDataLike eltTy
StaticRecordTy items -> mapM_ recur items
VariantTy (NoExt items) -> mapM_ recur items
DepPairTy (DepPairType b@(_:>l) r) -> do
recur l
substBinders b \_ -> checkDataLike r
TypeCon _ defName params -> do
params' <- mapM substM params
def <- lookupDataDef =<< substM defName
dataCons <- instantiateDataDef def params'
dropSubst $ forM_ dataCons \(DataConDef _ bs) ->
checkDataLikeBinderNest bs
TC con -> case con of
BaseType _ -> return ()
ProdType as -> mapM_ recur as
SumType cs -> mapM_ recur cs
IntRange _ _ -> return ()
IndexRange _ _ _ -> return ()
IndexSlice _ _ -> return ()
_ -> throw TypeErr $ pprint ty
_ -> throw TypeErr $ pprint ty
where recur = checkDataLike
checkDataLikeBinderNest :: Typer m => EmptyAbs (Nest Binder) i -> m i o ()
checkDataLikeBinderNest (Abs Empty UnitE) = return ()
checkDataLikeBinderNest (Abs (Nest b rest) UnitE) = do
checkDataLike $ binderType b
substBinders b \_ -> checkDataLikeBinderNest $ Abs rest UnitE
| google-research/dex-lang | src/lib/Type.hs | bsd-3-clause | 56,361 | 0 | 26 | 14,784 | 19,933 | 9,355 | 10,578 | -1 | -1 |
module Main where
import Ivory.Tower.Config
import Ivory.Tower.Options
import Ivory.OS.FreeRTOS.Tower.STM32
import BSP.Tests.Platforms
import BSP.Tests.LED.TestApp (app)
main :: IO ()
main = compileTowerSTM32FreeRTOS testplatform_stm32 p $
app testplatform_leds
where
p :: TOpts -> IO TestPlatform
p topts = getConfig topts testPlatformParser
| GaloisInc/ivory-tower-stm32 | ivory-bsp-tests/tests/LEDTest.hs | bsd-3-clause | 356 | 0 | 8 | 52 | 96 | 55 | 41 | 11 | 1 |
module TiNameMaps(module TiNameMaps,AccNames(..)) where
import List(nub)
import NameMaps(AccNames(..))
import TypedIds(IdTy(..),TypeInfo(..),idTy)
import HsIdent(HsIdentI(..))
allTypeNames ds = nub (accNames typeName ds [])
where
typeName x =
case idTy x of
Class {} -> (HsCon x:)
Type TypeInfo{defType=Nothing} -> (HsVar x:)
Type {} -> (HsCon x:)
_ -> id
| forste/haReFork | tools/base/TI/TiNameMaps.hs | bsd-3-clause | 430 | 7 | 13 | 120 | 178 | 103 | 75 | 12 | 4 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# LANGUAGE TemplateHaskell #-}
module Telly.Tests where
import Multiarg.Examples.Telly
import Test.QuickCheck
import Control.Applicative
import Ernie
import Multiarg.Internal
import Test.Tasty
import Test.Tasty.TH
import Test.Tasty.QuickCheck
tests :: TestTree
tests = $(testGroupGenerator)
-- | Generates any option.
option :: Gen Telly
option = oneof
[ return Empty
, Single <$> optArg
, Double <$> optArg <*> optArg
, Triple <$> optArg <*> optArg <*> optArg
, return Zero
, One <$> optArg
, Two <$> optArg <*> optArg
, Three <$> optArg <*> optArg <*> optArg
, return Cero
, Uno <$> optArg
, Dos <$> optArg <*> optArg
, Tres <$> optArg <*> optArg <*> optArg
]
tellyToNestedList :: Telly -> [[String]]
tellyToNestedList telly = case telly of
PosArg s -> [[s]]
Empty -> long "empty" [] ++ short 'e' []
Single s -> long "single" [s] ++ short 's' [s]
Double s1 s2 -> long "double" [s1, s2] ++ short 'd' [s1, s2]
Triple s1 s2 s3 -> long "triple" [s1, s2, s3]
++ short 't' [s1, s2, s3]
Zero -> short '0' []
One s -> short '1' [s]
Two s1 s2 -> short '2' [s1, s2]
Three s1 s2 s3 -> short '3' [s1, s2, s3]
Cero -> long "cero" []
Uno s -> long "uno" [s]
Dos s1 s2 -> long "dos" [s1, s2]
Tres s1 s2 s3 -> long "tres" [s1, s2, s3]
tellyToStrings :: Telly -> Gen [String]
tellyToStrings = pickItem . tellyToNestedList
validTellyStrings :: Gen ([Telly], [String])
validTellyStrings = do
unneededStopper <- arbitrary
(start, end) <- interspersedLine option PosArg
let startStrings = map tellyToNestedList start
endStrings = map tellyToNestedList end
startList <- fmap concat $ mapM pickItem startStrings
endList <- fmap concat $ mapM pickItem endStrings
let endList'
| null end && not unneededStopper = endList
| otherwise = "--" : endList
return (start ++ end, startList ++ endList')
prop_parseStringsYieldsTellies
= forAll validTellyStrings $ \(tellies, strings) ->
let ParsedCommandLine ls _
= parseCommandLinePure optSpecs PosArg strings
in map Right tellies === ls
prop_parseStringsYieldsNoEndError
= forAll validTellyStrings $ \(_, strings) ->
let ParsedCommandLine _ mayOpt
= parseCommandLinePure optSpecs PosArg strings
in mayOpt === Nothing
| massysett/multiarg | tests/Telly/Tests.hs | bsd-3-clause | 2,320 | 0 | 14 | 484 | 833 | 426 | 407 | 67 | 13 |
module ASTConvert where
import qualified EvalAST as E
import qualified ParseAST as P
import Control.Monad.State
-- function taking blockbody and prepending a statement or multiple statements
type StatementWrapper = E.BlockBody -> E.BlockBody
type ConvState = (StatementWrapper, Int)
gensym :: State ConvState String
gensym = do
(stmts, n) <- get
put (stmts, n + 1)
return $ "_" ++ show n
pushStatement :: StatementWrapper -> State ConvState ()
pushStatement stmt = do
(stmts, n) <- get
put (stmts . stmt, n)
return ()
----------
convertExpr :: P.Expr -> State ConvState E.Expr
convertExpr (P.IntLiteral n) = return $ E.IntLiteral n
convertExpr (P.StringLiteral n) = return $ E.StringLiteral n
convertExpr (P.BoolLiteral n) = return $ E.BoolLiteral n
convertExpr (P.VarAccess n) = return $ E.VarAccess n
convertExpr (P.BlockLiteral b) = return $ E.BlockLiteral $ convertBlock b
convertExpr (P.TupleLiteral exprs) = do
converted <- mapM convertExpr exprs
return $ E.TupleLiteral converted
convertExpr (P.IfElse cond ifTrue ifFalse) = do
convertedCond <- convertExpr cond
convertedTrue <- convertExpr ifTrue
convertedFalse <- convertExpr ifFalse
return $ E.IfElse convertedCond convertedTrue convertedFalse
convertExpr (P.PrefixOperation operator operand) = do
convertedOperand <- convertExpr operand
return $ E.PrefixOperation operator convertedOperand
convertExpr (P.InfixOperation op l r) = do
convertedL <- convertExpr l
convertedR <- convertExpr r
return $ E.InfixOperation op convertedL convertedR
convertExpr (P.Yield listenerName arg) = do
convertedArg <- convertExpr arg
temporaryName <- gensym
pushStatement $ \body -> E.Yield listenerName convertedArg (E.Block Nothing (E.VarBind temporaryName) body)
return $ E.VarAccess temporaryName
convertExpr (P.QualifiedYield id listenerName arg) = do
convertedId <- convertExpr id
convertedArg <- convertExpr arg
temporaryName <- gensym
pushStatement $ \body -> E.QualifiedYield convertedId listenerName convertedArg (E.Block Nothing (E.VarBind temporaryName) body)
return $ E.VarAccess temporaryName
convertExpr (P.FCall func arg) = do
convertedFunc <- convertExpr func
convertedArg <- convertExpr arg
temporaryName <- gensym
pushStatement $ \body -> E.Advance convertedFunc convertedArg [("return", E.Block Nothing (E.TuplePattern [(E.VarBind temporaryName), E.NobodyCares]) body)]
return $ E.VarAccess temporaryName
convertLValue :: P.LValue -> E.LValue
convertLValue P.NobodyCares = E.NobodyCares
convertLValue (P.VarBind varName) = E.VarBind varName
convertLValue (P.TuplePattern patterns) = E.TuplePattern $ map convertLValue patterns
convertStmt :: P.Statement -> StatementWrapper
convertStmt (P.Bind lval (P.Yield listenerName arg)) =
let (convertedArg, (stmts, _)) = runState (convertExpr arg) (id, 1)
convertedLVal = convertLValue lval
in stmts . \body -> E.Yield listenerName convertedArg (E.Block Nothing convertedLVal body)
convertStmt (P.Bind lval (P.QualifiedYield idExpr listenerName arg)) =
let (convertedId, (stmts, n)) = runState (convertExpr idExpr) (id, 1)
(convertedArg, (stmts2, _)) = runState (convertExpr arg) (id, n)
convertedLVal = convertLValue lval
in stmts . stmts2 . \body -> E.QualifiedYield convertedId listenerName convertedArg (E.Block Nothing convertedLVal body)
convertStmt (P.Bind lval (P.FCall func arg)) =
let (convertedFunc, (stmts, n)) = runState (convertExpr func) (id, 1)
(convertedArg, (stmts2, _)) = runState (convertExpr arg) (id, n)
convertedLVal = convertLValue lval
in stmts . stmts2 . \body -> E.Advance convertedFunc convertedArg [("return", E.Block Nothing (E.TuplePattern [convertedLVal, E.NobodyCares]) body)]
convertStmt (P.Bind lval expr) =
let (convertedExpr, (stmts, _)) = runState (convertExpr expr) (id, 1)
convertedLVal = convertLValue lval
in stmts . \body -> E.Bind convertedExpr (E.Block Nothing convertedLVal body)
convertStmt (P.Advance func arg listeners) =
let (convertedFunc, (stmts, n)) = runState (convertExpr func) (id, 1)
(convertedArg, (stmts2, _)) = runState (convertExpr arg) (id, n)
in stmts . stmts2 . \body -> E.Advance convertedFunc convertedArg (map (convertListener body) listeners)
where
convertListener :: E.BlockBody -> (String, P.LValue, [P.Statement]) -> (String, E.Block)
convertListener body (listenerName, lval, statements) =
let convertedLVal = convertLValue lval
in (listenerName, E.Block Nothing convertedLVal (foldr ($) body (map convertStmt statements)))
convertStmt (P.ExprStatement expr) = convertStmt (P.Bind P.NobodyCares expr)
convertStmts :: [P.Statement] -> E.BlockBody
convertStmts statements = foldr ($) E.EmptyBlock (map convertStmt statements)
convertBlock :: P.Block -> E.Block
convertBlock (P.Block maybeIdName arg statements) = E.Block maybeIdName (convertLValue arg) (convertStmts statements)
| cg5-/continue | src/ASTConvert.hs | bsd-3-clause | 4,926 | 0 | 18 | 776 | 1,803 | 912 | 891 | 90 | 1 |
{-# LANGUAGE BangPatterns, DeriveFunctor #-}
-- | This module allows for incremental decoding of CSV data. This is
-- useful if you e.g. want to interleave I\/O with parsing or if you
-- want finer grained control over how you deal with type conversion
-- errors.
module Data.Csv.Incremental
(
-- * Decoding headers
HeaderParser(..)
, decodeHeader
, decodeHeaderWith
-- ** Providing input
-- $feed-header
, feedChunkH
, feedEndOfInputH
-- * Decoding records
-- $typeconversion
, Parser(..)
-- ** Index-based record conversion
-- $indexbased
, decode
, decodeWith
-- ** Name-based record conversion
-- $namebased
, decodeByName
, decodeByNameWith
-- ** Providing input
-- $feed-records
, feedChunk
, feedEndOfInput
) where
import Control.Applicative ((<*), (<|>))
import qualified Data.Attoparsec as A
import Data.Attoparsec.Char8 (endOfInput, endOfLine)
import qualified Data.ByteString as B
import qualified Data.HashMap.Strict as HM
import qualified Data.Vector as V
import Data.Csv.Conversion hiding (Parser, record, toNamedRecord)
import qualified Data.Csv.Conversion as Conversion
import Data.Csv.Parser
import Data.Csv.Types
-- $feed-header
--
-- These functions are sometimes convenient when working with
-- 'HeaderParser', but don't let you do anything you couldn't already
-- do using the 'HeaderParser' constructors directly.
-- $indexbased
--
-- See documentation on index-based conversion in "Data.Csv" for more
-- information.
-- $namebased
--
-- See documentation on name-based conversion in "Data.Csv" for more
-- information.
-- $feed-records
--
-- These functions are sometimes convenient when working with
-- 'Parser', but don't let you do anything you couldn't already do
-- using the 'Parser' constructors directly.
------------------------------------------------------------------------
-- * Decoding headers
-- | An incremental parser that when fed data eventually returns a
-- parsed 'Header', or an error.
data HeaderParser a =
-- | The input data was malformed. The first field contains any
-- unconsumed input and second field contains information about
-- the parse error.
FailH !B.ByteString String
-- | The parser needs more input data before it can produce a
-- result. Use an 'B.empty' string to indicate that no more
-- input data is available. If fed an 'B.empty string', the
-- continuation is guaranteed to return either 'FailH' or
-- 'DoneH'.
| PartialH (B.ByteString -> HeaderParser a)
-- | The parse succeeded and produced the given 'Header'.
| DoneH !Header a
deriving Functor
instance Show a => Show (HeaderParser a) where
showsPrec d (FailH rest msg) = showParen (d > appPrec) showStr
where
showStr = showString "FailH " . showsPrec (appPrec+1) rest .
showString " " . showsPrec (appPrec+1) msg
showsPrec _ (PartialH _) = showString "PartialH <function>"
showsPrec d (DoneH hdr x) = showParen (d > appPrec) showStr
where
showStr = showString "DoneH " . showsPrec (appPrec+1) hdr .
showString " " . showsPrec (appPrec+1) x
-- Application has precedence one more than the most tightly-binding
-- operator
appPrec :: Int
appPrec = 10
-- | Feed a 'HeaderParser' with more input. If the 'HeaderParser' is
-- 'FailH' it will add the input to 'B.ByteString' of unconsumed
-- input. If the 'HeaderParser' is 'DoneH' it will drop the extra
-- input on the floor.
feedChunkH :: HeaderParser a -> B.ByteString -> HeaderParser a
feedChunkH (FailH rest err) s = FailH (B.append rest s) err
feedChunkH (PartialH k) s = k s
feedChunkH d@(DoneH _ _) _s = d
-- | Tell a 'HeaderParser' that there is no more input. This passes
-- 'B.empty' to a 'PartialH' parser, otherwise returns the parser
-- unchanged.
feedEndOfInputH :: HeaderParser a -> HeaderParser a
feedEndOfInputH (PartialH k) = k B.empty
feedEndOfInputH p = p
-- | Parse a CSV header in an incremental fashion. When done, the
-- 'HeaderParser' returns any unconsumed input in the second field of
-- the 'DoneH' constructor.
decodeHeader :: HeaderParser B.ByteString
decodeHeader = decodeHeaderWith defaultDecodeOptions
-- | Like 'decodeHeader', but lets you customize how the CSV data is
-- parsed.
decodeHeaderWith :: DecodeOptions -> HeaderParser B.ByteString
decodeHeaderWith !opts = PartialH (go . parser)
where
parser = A.parse (header $ decDelimiter opts)
go (A.Fail rest _ msg) = FailH rest err
where err = "parse error (" ++ msg ++ ")"
-- TODO: Check empty and give attoparsec one last chance to return
-- something:
go (A.Partial k) = PartialH $ \ s -> go (k s)
go (A.Done rest r) = DoneH r rest
------------------------------------------------------------------------
-- * Decoding records
-- $typeconversion
--
-- Just like in the case of non-incremental decoding, there are two
-- ways to convert CSV records to and from and user-defined data
-- types: index-based conversion and name-based conversion.
-- | An incremental parser that when fed data eventually produces some
-- parsed records, converted to the desired type, or an error in case
-- of malformed input data.
data Parser a =
-- | The input data was malformed. The first field contains any
-- unconsumed input and second field contains information about
-- the parse error.
Fail !B.ByteString String
-- | The parser needs more input data before it can produce a
-- result. Use an 'B.empty' string to indicate that no more
-- input data is available. If fed an 'B.empty' string, the
-- continuation is guaranteed to return either 'Fail' or 'Done'.
| Partial (B.ByteString -> Parser a)
-- | The parser parsed and converted some records. Any records
-- that failed type conversion are returned as @'Left' errMsg@
-- and the rest as @'Right' val@. Feed a 'B.ByteString' to the
-- continuation to continue parsing. Use an 'B.empty' string to
-- indicate that no more input data is available. If fed an
-- 'B.empty' string, the continuation is guaranteed to return
-- either 'Fail' or 'Done'.
| Some [Either String a] (B.ByteString -> Parser a)
-- | The parser parsed and converted some records. Any records
-- that failed type conversion are returned as @'Left' errMsg@
-- and the rest as @'Right' val@.
| Done [Either String a]
deriving Functor
instance Show a => Show (Parser a) where
showsPrec d (Fail rest msg) = showParen (d > appPrec) showStr
where
showStr = showString "Fail " . showsPrec (appPrec+1) rest .
showString " " . showsPrec (appPrec+1) msg
showsPrec _ (Partial _) = showString "Partial <function>"
showsPrec d (Some rs _) = showParen (d > appPrec) showStr
where
showStr = showString "Some " . showsPrec (appPrec+1) rs .
showString " <function>"
showsPrec d (Done rs) = showParen (d > appPrec) showStr
where
showStr = showString "Done " . showsPrec (appPrec+1) rs
-- | Feed a 'Parser' with more input. If the 'Parser' is 'Fail' it
-- will add the input to 'B.ByteString' of unconsumed input. If the
-- 'Parser' is 'Done' it will drop the extra input on the floor.
feedChunk :: Parser a -> B.ByteString -> Parser a
feedChunk (Fail rest err) s = Fail (B.append rest s) err
feedChunk (Partial k) s = k s
feedChunk (Some xs k) s = Some xs (\ s' -> k s `feedChunk` s')
feedChunk (Done xs) _s = Done xs
-- | Tell a 'Parser' that there is no more input. This passes 'empty'
-- to a 'Partial' parser, otherwise returns the parser unchanged.
feedEndOfInput :: Parser a -> Parser a
feedEndOfInput (Partial k) = k B.empty
feedEndOfInput p = p
-- | Have we read all available input?
data More = Incomplete | Complete
deriving (Eq, Show)
-- | Efficiently deserialize CSV in an incremental fashion. Equivalent
-- to @'decodeWith' 'defaultDecodeOptions'@.
decode :: FromRecord a
=> Bool -- ^ Data contains header that should be
-- skipped
-> Parser a
decode = decodeWith defaultDecodeOptions
-- | Like 'decode', but lets you customize how the CSV data is parsed.
decodeWith :: FromRecord a
=> DecodeOptions -- ^ Decoding options
-> Bool -- ^ Data contains header that should be
-- skipped
-> Parser a
decodeWith !opts skipHeader
| skipHeader = Partial $ \ s -> go (decodeHeaderWith opts `feedChunkH` s)
| otherwise = Partial (decodeWithP parseRecord opts)
where go (FailH rest msg) = Fail rest msg
go (PartialH k) = Partial $ \ s' -> go (k s')
go (DoneH _ rest) = decodeWithP parseRecord opts rest
------------------------------------------------------------------------
-- | Efficiently deserialize CSV in an incremental fashion. The data
-- is assumed to be preceeded by a header. Returns a 'HeaderParser'
-- that when done produces a 'Parser' for parsing the actual records.
-- Equivalent to @'decodeByNameWith' 'defaultDecodeOptions'@.
decodeByName :: FromNamedRecord a
=> HeaderParser (Parser a)
decodeByName = decodeByNameWith defaultDecodeOptions
-- | Like 'decodeByName', but lets you customize how the CSV data is
-- parsed.
decodeByNameWith :: FromNamedRecord a
=> DecodeOptions -- ^ Decoding options
-> HeaderParser (Parser a)
decodeByNameWith !opts =
PartialH (go . (decodeHeaderWith opts `feedChunkH`))
where
go (FailH rest msg) = FailH rest msg
go (PartialH k) = PartialH $ \ s -> go (k s)
go (DoneH hdr rest) =
DoneH hdr (decodeWithP (parseNamedRecord . toNamedRecord hdr) opts rest)
-- Copied from Data.Csv.Parser
toNamedRecord :: Header -> Record -> NamedRecord
toNamedRecord hdr v = HM.fromList . V.toList $ V.zip hdr v
------------------------------------------------------------------------
-- | Like 'decode', but lets you customize how the CSV data is parsed.
decodeWithP :: (Record -> Conversion.Parser a) -> DecodeOptions -> B.ByteString
-> Parser a
decodeWithP p !opts = go Incomplete [] . parser
where
go !_ !acc (A.Fail rest _ msg)
| null acc = Fail rest err
| otherwise = Some (reverse acc) (\ s -> Fail (rest `B.append` s) err)
where err = "parse error (" ++ msg ++ ")"
go Incomplete acc (A.Partial k)
| null acc = Partial cont
| otherwise = Some (reverse acc) cont
where cont s = go m [] (k s)
where m | B.null s = Complete
| otherwise = Incomplete
go Complete _ (A.Partial _) = moduleError "decodeWithP" msg
where msg = "attoparsec should never return Partial in this case"
go m acc (A.Done rest r)
| B.null rest = case m of
Complete -> Done (reverse acc')
Incomplete
| null acc' -> Partial (cont acc')
| otherwise -> Some (reverse acc') (cont [])
| otherwise = go m acc' (parser rest)
where cont acc'' s
| B.null s = Done (reverse acc'')
| otherwise = go Incomplete acc'' (parser s)
acc' | blankLine r = acc
| otherwise = convert r : acc
parser = A.parse (record (decDelimiter opts) <* (endOfLine <|> endOfInput))
convert = runParser . p
{-# INLINE decodeWithP #-}
blankLine :: V.Vector B.ByteString -> Bool
blankLine v = V.length v == 1 && (B.null (V.head v))
moduleError :: String -> String -> a
moduleError func msg = error $ "Data.Csv.Incremental." ++ func ++ ": " ++ msg
{-# NOINLINE moduleError #-}
| edtsech/cassava | Data/Csv/Incremental.hs | bsd-3-clause | 11,811 | 0 | 15 | 2,863 | 2,382 | 1,256 | 1,126 | 151 | 5 |
module Util.Hash (
sha1,
sha1Lazy,
sha1Text
) where
import ClassyPrelude.Yesod hiding (unpack, hash)
import Text.Printf (printf)
import Data.ByteString (unpack)
import qualified Data.ByteString.Lazy as L
import Crypto.Hash.SHA1 (hash, hashlazy)
sha1 :: ByteString -> Text
sha1 bytes = pack $ unpack (hash bytes) >>= printf "%02x"
sha1Lazy :: L.ByteString -> Text
sha1Lazy bytes = pack $ unpack (hashlazy bytes) >>= printf "%02x"
sha1Text :: Text -> Text
sha1Text = sha1 . encodeUtf8
| vinnymac/glot-www | Util/Hash.hs | mit | 499 | 0 | 9 | 86 | 168 | 95 | 73 | 15 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async
import Control.Concurrent.MVar
import Control.Monad
import Data.IORef
import Data.Time.Clock.POSIX
import Data.Time.Units
import Data.Vector (Vector, fromList)
import qualified Data.Vector as V (length)
import Data.Word (Word32)
import Network.QDisc.Fair
import Network.Transport.TCP (QDisc (..), simpleOnePlaceQDisc,
simpleUnboundedQDisc)
import Statistics.Distribution
import Statistics.Distribution.Exponential
import Statistics.Distribution.Normal
import Statistics.Distribution.Uniform
import qualified Statistics.Sample as Sample
import System.Environment (getArgs)
import System.Random.MWC
-- | A writer is determined by some continuous distribution giving the duration
-- (in microseconds) between successive data being made available.
data SimulationWriter = forall distr . ContGen distr => SimulationWriter distr
-- | A reader is determined by some continuous distribution giving the duration
-- (in microseconds) between successive reads (how long the reader thread
-- works between taking events).
data SimulationReader = forall distr . ContGen distr => SimulationReader distr
data Scenario = Scenario {
sim_reader :: SimulationReader
, sim_writers :: [SimulationWriter]
}
data SimulationParameters = SimulationParameters {
sim_scenario :: Scenario
-- | How long the simulation should run.
, sim_duration :: Second
-- | The QDisc to use.
, sim_qdisc :: QDisc ()
-- | A seed for randomness.
, sim_seed :: Word32
}
type Latency = Double
-- | The output of a simulation is, for each writer, the samples of actual
-- delays observed when trying to write: how long it was blocked on
-- trying to enqueue. The number of samples is the number of writes it
-- made.
data SimulationOutput = SimulationOutput {
sim_writer_outputs :: [Vector Latency]
}
instance Show SimulationOutput where
show (SimulationOutput vecs) = concat $ flip fmap vecs $ \vec -> concat [
"Samples (writes): ", show (V.length vec), "\n"
, "Latency (microseconds):\n"
, " Mean: ", show (Sample.mean vec), "\n"
, " Std. Dev.: ", show (Sample.stdDev vec), "\n\n"
]
data QDiscChoice = Fair | OnePlace | Unbounded
makeQDisc :: QDiscChoice -> IO (QDisc t)
makeQDisc choice = case choice of
Fair -> fairQDisc (const (return Nothing))
Unbounded -> simpleUnboundedQDisc
OnePlace -> simpleOnePlaceQDisc
unfairScenario :: Scenario
unfairScenario = Scenario {
-- Difference between fair and one-place is very clear here.
-- The two fast writers get the same number of writes in either case.
-- One-place gives the slow writer half as many writes, but fair gives
-- it a lot more. The cycle time (time to read from all 3 writers) is
-- the slow writer's write delay, so we expect that the slow writer
-- should be able to write on every cycle.
sim_reader = SimulationReader (uniformDistr 5000 5001)
, sim_writers = [
SimulationWriter (uniformDistr 4999 5000)
, SimulationWriter (uniformDistr 4999 5000)
, SimulationWriter (uniformDistr 14999 15000)
]
}
-- | A normally-distributed reader (mean and std. dev. configurable) and
-- n exponentially-distributed writers (means configurable).
typicalScenario :: (Double, Double) -> [Double] -> Scenario
typicalScenario (rmean, rstd_dev) writers = Scenario {
sim_reader = SimulationReader (normalDistr rmean rstd_dev)
, sim_writers = flip fmap writers $ \wmean -> SimulationWriter (exponential (1/wmean))
}
simpleSimulationParameters :: QDisc () -> Second -> Scenario -> SimulationParameters
simpleSimulationParameters qdisc duration scenario = SimulationParameters {
sim_scenario = scenario
, sim_duration = duration
, sim_qdisc = qdisc
, sim_seed = 42
}
-- | Run a simulation.
simulate :: SimulationParameters -> IO SimulationOutput
simulate SimulationParameters{..} = do
let Scenario{..} = sim_scenario
-- All threads will wait on this.
-- Threads will loop, and at each iteration will read it. If it's True,
-- they'll stop.
startStop :: MVar Bool <- newEmptyMVar
-- Spawn the reader.
refs <- withAsync (reader 0 sim_reader) $ \readerThread -> do
-- Spawn the writers.
writerThreadsAndRefs <- forM (zip [1..] sim_writers) $ \(seed', sim_writer) -> do
(ref, doWrites) <- writer startStop seed' sim_writer
--withAsync doWrites $ \thread -> return (ref, thread)
thread <- async doWrites
return (ref, thread)
-- Duration is in seconds.
putMVar startStop False
threadDelay $ fromIntegral sim_duration * 1000000
swapMVar startStop True
forM writerThreadsAndRefs $ \(ref, thread) -> do
wait thread
return ref
-- Reader and writers are all killed. Results available in the IORefs.
vectors <- forM refs (fmap fromList . readIORef)
return $ SimulationOutput ((fmap . fmap) fromIntegral vectors)
where
reader :: Word32 -> SimulationReader -> IO ()
reader seed' (SimulationReader distribution) = do
gen <- initialize (fromList [sim_seed, seed'])
let readLoop = do
() <- qdiscDequeue sim_qdisc
-- Unlike for writers, the reader delays are always respected,
-- as the delay is independent of how long the reader waits for
-- a value from qdiscDequeue.
delay :: Microsecond <- fromIntegral . round <$> genContVar distribution gen
threadDelay (fromIntegral delay)
readLoop
readLoop
writer :: MVar Bool -> Word32 -> SimulationWriter -> IO (IORef [Microsecond], IO ())
writer control seed' (SimulationWriter distribution) = do
ref <- newIORef []
gen <- initialize (fromList [sim_seed, seed'])
-- The writer's distribution determines the duration between the points
-- in time when new data are made available, and this is independent
-- of how long it takes to actually do the write. For instance, if
-- the writer is blocked on enqueue for 2 seconds, and the distribution
-- says there will be data available every 1 second, then 2 data will
-- be immediately available after the enqueue finishes.
let writeLoop :: Microsecond -> IO ()
writeLoop surplusWait = do
stop <- readMVar control
unless stop $ do
nextDelay :: Microsecond <- fromIntegral . round <$> genContVar distribution gen
let actualDelay = nextDelay - surplusWait
when (actualDelay > 0) $ do
threadDelay (fromIntegral actualDelay)
start <- getPOSIXTime
qdiscEnqueue sim_qdisc undefined undefined ()
end <- getPOSIXTime
let latency :: Microsecond
!latency = fromIntegral . round $ (realToFrac (end - start) :: Double) * 1000000
modifyIORef' ref ((:) latency)
let !surplusWait' = max 0 (surplusWait + latency - nextDelay)
writeLoop surplusWait'
return (ref, writeLoop 0)
main :: IO ()
main = do
args <- getArgs
qdiscChoice <- case args of
"unbounded" : _ -> putStrLn "Using unbounded QDisc" >> return Unbounded
"one_place" : _ -> putStrLn "Using one-place QDisc" >> return OnePlace
_ -> putStrLn "Using fair QDisc" >> return Fair
duration :: Int <- case args of
_ : n : _ -> case reads n of
[(n', "")] -> return n'
_ -> return 10
qdisc <- makeQDisc qdiscChoice
--let scenario = typicalScenario (1000, 25) [800, 900, 1000, 1100, 1200]
let scenario = unfairScenario
results <- simulate $ simpleSimulationParameters qdisc (fromIntegral duration) scenario
putStrLn ""
print results
| input-output-hk/pos-haskell-prototype | networking/src/Network/QDisc/Simulation.hs | mit | 8,531 | 0 | 25 | 2,395 | 1,685 | 881 | 804 | 131 | 4 |
{-# language RankNTypes #-}
module Database.Persist.SqlBackend.Internal.Statement where
import Data.Acquire
import Database.Persist.Types.Base
import Data.Int
import Conduit
-- | A 'Statement' is a representation of a database query that has been
-- prepared and stored on the server side.
data Statement = Statement
{ stmtFinalize :: IO ()
, stmtReset :: IO ()
, stmtExecute :: [PersistValue] -> IO Int64
, stmtQuery :: forall m. MonadIO m
=> [PersistValue]
-> Acquire (ConduitM () [PersistValue] m ())
}
| yesodweb/persistent | persistent/Database/Persist/SqlBackend/Internal/Statement.hs | mit | 561 | 0 | 15 | 130 | 126 | 74 | 52 | 13 | 0 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
{- |
Module : ./Temporal/Ctl.hs
Copyright : (c) Klaus Hartke, Uni Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (MPTC-FD)
-}
module Ctl where
import Data.Set as Set
exists :: (a -> Bool) -> Set a -> Bool
exists f = Set.fold ((||) . f) False
infixr 3 `And`
infixr 2 `Or`
infixr 1 `Implies`
infixl 1 `AU`, `EU`
infix 0 |=
-- ctl formulas
data Formula a =
Top
| Bottom
| Atom a
| Not (Formula a)
| (Formula a) `And` (Formula a)
| (Formula a) `Or` (Formula a)
| (Formula a) `Implies` (Formula a)
| AX (Formula a)
| EX (Formula a)
| AF (Formula a)
| EF (Formula a)
| AG (Formula a)
| EG (Formula a)
| (Formula a) `AU` (Formula a)
| (Formula a) `EU` (Formula a)
deriving Show
-- ctl class
class CTL m a s | m -> a s where
states :: m -> Set s
next :: m -> s -> Set s
labels :: m -> s -> Set a
-- satisfaction relation
(|=) :: (CTL m a s, Ord a, Ord s) => (m, s) -> Formula a -> Bool
(m, s) |= phi = Set.member s (sat m phi)
sat :: (CTL m a s, Ord a, Ord s) => m -> Formula a -> Set s
sat m Top = states m
sat m Bottom = Set.empty
sat m (Atom a) = Set.filter (Set.member a . labels m) (states m)
sat m (Not phi) = Set.difference (states m) (sat m phi)
sat m (phi `And` psi) = Set.intersection (sat m phi) (sat m psi)
sat m (phi `Or` psi) = Set.union (sat m phi) (sat m psi)
sat m (phi `Implies` psi) = sat m (Not phi `Or` psi)
sat m (AX phi) = sat m (Not (EX (Not phi)))
sat m (EX phi) = satEX m phi
sat m (phi `AU` psi) = sat m (Not (Not psi `EU` (Not phi `And` Not psi) `Or`
EG (Not psi)))
sat m (phi `EU` psi) = satEU m phi psi
sat m (EF phi) = sat m (Top `EU` phi)
sat m (EG phi) = sat m (Not (AF (Not phi)))
sat m (AF phi) = satAF m phi
sat m (AG phi) = sat m (Not (EF (Not phi)))
satEX :: (CTL m a s, Ord a, Ord s) => m -> Formula a -> Set s
satEX m phi = preE m (sat m phi)
satAF :: (CTL m a s, Ord a, Ord s) => m -> Formula a -> Set s
satAF m phi = satAF' (states m) (sat m phi)
where
satAF' x y = if x == y then y else satAF' y (Set.union y (preA m y))
satEU :: (CTL m a s, Ord a, Ord s) => m -> Formula a -> Formula a -> Set s
satEU m phi psi = satEU' (sat m phi) (states m) (sat m psi)
where
satEU' w x y = if x == y then y else satEU' w y
(Set.union y (Set.intersection w (preE m y)))
preE :: (CTL m a s, Ord a, Ord s) => m -> Set s -> Set s
preE m y = Set.filter (\ s -> exists (`Set.member` next m s) y) (states m)
preA :: (CTL m a s, Ord a, Ord s) => m -> Set s -> Set s
preA m y = Set.difference (states m) (preE m (Set.difference (states m) y))
-- test model
data My = My
data MyAtoms = P | Q | R deriving (Eq, Ord, Show)
data MyStates = S0 | S1 | S2 deriving (Eq, Ord, Show)
instance CTL My MyAtoms MyStates where
states My = Set.fromList [S0, S1, S2]
next My S0 = Set.fromList [S1, S2]
next My S1 = Set.fromList [S0, S2]
next My S2 = Set.fromList [S2]
labels My S0 = Set.fromList [P, Q]
labels My S1 = Set.fromList [Q, R]
labels My S2 = Set.fromList [R]
| spechub/Hets | Temporal/Ctl.hs | gpl-2.0 | 3,245 | 0 | 14 | 896 | 1,741 | 917 | 824 | 74 | 2 |
{- |
Module : ./CASL/Freeness.hs
Description : Computation of the constraints needed for free definition links.
Copyright : (c) Adrian Riesco, Facultad de Informatica UCM 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Computation of the constraints needed for free definition links.
-}
module CASL.Freeness (quotientTermAlgebra) where
import CASL.Sign
import CASL.Morphism
import CASL.StaticAna
import CASL.AS_Basic_CASL
import Logic.Prover ()
import Common.Id
import Common.Result
import Common.AS_Annotation
import qualified Common.Lib.Rel as Rel
import qualified Common.Lib.MapSet as MapSet
import Data.Char
import Data.Maybe
import Data.List (groupBy, elemIndex)
import qualified Data.Map as Map
import qualified Data.Set as Set
-- | main function, in charge of computing the quotient term algebra
quotientTermAlgebra :: CASLMor -- sigma : Sigma -> SigmaM
-> [Named CASLFORMULA] -- Th(M)
-> Result (CASLSign, {- SigmaK
CASLMor, -- iota : SigmaM' -> SigmaK -}
[Named CASLFORMULA] -- Ax(K)
)
quotientTermAlgebra sigma sens =
let
sigma_0 = msource sigma
ss_0 = sortSet sigma_0
sigma_m = mtarget sigma
sigma_k = create_sigma_k ss_0 sigma_m
axs = create_axs ss_0 sigma_m sigma_k sens
in return (sigma_k, axs)
-- | generates the axioms of the module K
create_axs :: Set.Set SORT -> CASLSign -> CASLSign -> [Named CASLFORMULA]
-> [Named CASLFORMULA]
create_axs sg_ss sg_m sg_k sens = forms
where ss_m = sortSet sg_m
ss = Set.map mkFreeName $ Set.difference ss_m sg_ss
sr = sortRel sg_k
comps = ops2comp $ opMap sg_k
ss' = filterNoCtorSorts (opMap sg_k) ss
ctor_sen = freeCons (ss', sr, comps)
make_axs = make_forms sg_ss ++ make_hom_forms sg_ss
h_axs_ops = homomorphism_axs_ops $ opMap sg_m
h_axs_preds = homomorphism_axs_preds $ predMap sg_m
h_axs_surj = hom_surjectivity $ sortSet sg_m
q_axs = quotient_axs sens
symm_ax = symmetry_axs ss_m
tran_ax = transitivity_axs ss_m
cong_ax = congruence_axs (opMap sg_m)
satThM = sat_thm_ax sens
prems = conjunct [symm_ax, tran_ax, cong_ax, satThM]
ltkh = larger_than_ker_h ss_m (predMap sg_m)
krnl_axs = [mkKernelAx ss_m (predMap sg_m) prems ltkh]
forms = concat [ctor_sen, make_axs, h_axs_ops, h_axs_preds,
h_axs_surj, q_axs, krnl_axs]
filterNoCtorSorts :: OpMap -> Set.Set SORT -> Set.Set SORT
filterNoCtorSorts om = Set.filter (filterNoCtorSort om)
filterNoCtorSort :: OpMap -> SORT -> Bool
filterNoCtorSort om s = any (resultTypeSet s) . Map.elems $ MapSet.toMap om
resultTypeSet :: SORT -> Set.Set OpType -> Bool
resultTypeSet s = any (resultType s) . Set.toList
resultType :: SORT -> OpType -> Bool
resultType s = (s ==) . opRes
{- | generates formulas of the form make(h(x)) =e= x,
for any x of sort gn_free_s -}
make_hom_forms :: Set.Set SORT -> [Named CASLFORMULA]
make_hom_forms = Set.fold ((:) . make_hom_form) []
{- | generates a formula of the form make(h(x)) =e= x,
for gn_free_s given the SORT s -}
make_hom_form :: SORT -> Named CASLFORMULA
make_hom_form s = makeNamed ("ga_make_hom_" ++ show s) q_eq
where free_s = mkFreeName s
v = newVar free_s
ot_hom = Op_type Partial [free_s] s nullRange
os_hom = mkQualOp homId ot_hom
term_hom = mkAppl os_hom [v]
ot_mk = Op_type Total [s] free_s nullRange
os_mk = mkQualOp makeId ot_mk
term_mk = mkAppl os_mk [term_hom]
eq = mkExEq term_mk v
q_eq = quantifyUniversally eq
-- | generates the formulas relating the make functions with the homomorphism
make_forms :: Set.Set SORT -> [Named CASLFORMULA]
make_forms = Set.fold ((:) . make_form) []
{- | generates the formulas relating the make function for this sort
with the homomorphism -}
make_form :: SORT -> Named CASLFORMULA
make_form s = makeNamed ("ga_hom_make_" ++ show s) q_eq
where free_s = mkFreeName s
v = newVar s
ot_mk = Op_type Total [s] free_s nullRange
os_mk = mkQualOp makeId ot_mk
term_mk = mkAppl os_mk [v]
ot_hom = Op_type Partial [free_s] s nullRange
os_hom = mkQualOp homId ot_hom
term_hom = mkAppl os_hom [term_mk]
eq = mkStEq term_hom v
q_eq = quantifyUniversally eq
-- | computes the last part of the axioms to assert the kernel of h
larger_than_ker_h :: Set.Set SORT -> PredMap -> CASLFORMULA
larger_than_ker_h ss mis = conj
where ltkhs = ltkh_sorts ss
ltkhp = ltkh_preds mis
conj = conjunct (ltkhs ++ ltkhp)
{- | computes the second part of the conjunction of the formula "largerThanKerH"
from the kernel of H -}
ltkh_preds :: PredMap -> [CASLFORMULA]
ltkh_preds = MapSet.foldWithKey (\ name -> (:) . ltkh_preds_aux name) []
{- | computes the second part of the conjunction of the formula "largerThanKerH"
from the kernel of H for a concrete predicate profile -}
ltkh_preds_aux :: Id -> PredType -> CASLFORMULA
ltkh_preds_aux name (PredType args) = imp'
where free_name = mkFreeName name
free_args = map mkFreeName args
psi = psiName name
pt = Pred_type free_args nullRange
ps_name = mkQualPred free_name pt
ps_psi = mkQualPred psi pt
vars = createVars 1 free_args
prem = mkPredication ps_name vars
concl = mkPredication ps_psi vars
imp = mkImpl prem concl
imp' = quantifyUniversally imp
{- | computes the first part of the conjunction of the formula "largerThanKerH"
from the kernel of H -}
ltkh_sorts :: Set.Set SORT -> [CASLFORMULA]
ltkh_sorts = Set.fold ((:) . ltkh_sort) []
{- | computes the first part of the conjunction of the formula "largerThanKerH"
from the kernel of H for a concrete sort -}
ltkh_sort :: SORT -> CASLFORMULA
ltkh_sort s = imp'
where free_s = mkFreeName s
v1 = newVarIndex 1 free_s
v2 = newVarIndex 2 free_s
phi = phiName s
pt = Pred_type [free_s, free_s] nullRange
ps = mkQualPred phi pt
ot_hom = Op_type Partial [free_s] s nullRange
name_hom = mkQualOp homId ot_hom
t1 = mkAppl name_hom [v1]
t2 = mkAppl name_hom [v2]
prem = mkExEq t1 t2
concl = mkPredication ps [v1, v2]
imp = mkImpl prem concl
imp' = quantifyUniversally imp
-- | generates the axioms for satThM
sat_thm_ax :: [Named CASLFORMULA] -> CASLFORMULA
sat_thm_ax forms = final_form
where forms' = map (free_formula . sentence)
$ filter (no_gen . sentence) forms
final_form = conjunct forms'
-- | checks if the formula is a sort generation constraint
no_gen :: CASLFORMULA -> Bool
no_gen (Sort_gen_ax _ _) = False
no_gen _ = True
-- | computes the axiom for the congruence of the kernel of h
congruence_axs :: OpMap -> CASLFORMULA
congruence_axs om = conj
where axs = MapSet.foldWithKey (\ name -> (:) . congruence_ax_aux name)
[] om
conj = conjunct axs
{- | computes the axiom for the congruence of the kernel of h
for a single type of an operator id -}
congruence_ax_aux :: Id -> OpType -> CASLFORMULA
congruence_ax_aux name ot = cong_form'
where OpType _ args res = ot
free_name = mkFreeName name
free_args = map mkFreeName args
free_res = mkFreeName res
free_ot = Op_type Total free_args free_res nullRange
free_os = mkQualOp free_name free_ot
lgth = length free_args
xs = createVars 1 free_args
ys = createVars (1 + lgth) free_args
fst_term = mkAppl free_os xs
snd_term = mkAppl free_os ys
phi = phiName res
pt = Pred_type [free_res, free_res] nullRange
ps = mkQualPred phi pt
fst_form = mkPredication ps [fst_term, fst_term]
snd_form = mkPredication ps [snd_term, snd_term]
vars_forms = congruence_ax_vars args xs ys
conj = conjunct $ fst_form : snd_form : vars_forms
concl = mkPredication ps [fst_term, snd_term]
cong_form = mkImpl conj concl
cong_form' = quantifyUniversally cong_form
freePredNameAndType :: SORT -> (Id, PRED_TYPE)
freePredNameAndType s = let
phi = phiName s
free_s = mkFreeName s
pt = Pred_type [free_s, free_s] nullRange
in (phi, pt)
freePredSymb :: SORT -> PRED_SYMB
freePredSymb = uncurry mkQualPred . freePredNameAndType
-- | computes the formulas for the relations between variables
congruence_ax_vars :: [SORT] -> [CASLTERM] -> [CASLTERM] -> [CASLFORMULA]
congruence_ax_vars (s : ss) (x : xs) (y : ys) = form : forms
where
form = mkPredication (freePredSymb s) [x, y]
forms = congruence_ax_vars ss xs ys
congruence_ax_vars _ _ _ = []
-- | computes the transitivity axioms for the kernel of h
transitivity_axs :: Set.Set SORT -> CASLFORMULA
transitivity_axs ss = conj
where axs = Set.fold ((:) . transitivity_ax) [] ss
conj = conjunct axs
twoFreeVars :: SORT -> (SORT, TERM (), TERM (), VAR, VAR, PRED_SYMB, FORMULA ())
twoFreeVars s = let
free_sort = mkFreeName s
v1@(Qual_var n1 _ _) = newVarIndex 1 free_sort
v2@(Qual_var n2 _ _) = newVarIndex 2 free_sort
ps = freePredSymb s
fst_form = mkPredication ps [v1, v2]
in (free_sort, v1, v2, n1, n2, ps, fst_form)
{- | computes the transitivity axiom of a concrete sort for
the kernel of h -}
transitivity_ax :: SORT -> CASLFORMULA
transitivity_ax s = quant
where (free_sort, v1, v2, n1, n2, ps, fst_form) = twoFreeVars s
v3@(Qual_var n3 _ _) = newVarIndex 3 free_sort
snd_form = mkPredication ps [v2, v3]
thr_form = mkPredication ps [v1, v3]
conj = conjunct [fst_form, snd_form]
imp = mkImpl conj thr_form
vd = [Var_decl [n1, n2, n3] free_sort nullRange]
quant = mkForall vd imp
-- | computes the symmetry axioms for the kernel of h
symmetry_axs :: Set.Set SORT -> CASLFORMULA
symmetry_axs ss = conj
where axs = Set.fold ((:) . symmetry_ax) [] ss
conj = conjunct axs
-- | computes the symmetry axiom of a concrete sort for the kernel of h
symmetry_ax :: SORT -> CASLFORMULA
symmetry_ax s = quant
where (free_sort, v1, v2, n1, n2, ps, lhs) = twoFreeVars s
rhs = mkPredication ps [v2, v1]
inner_form = mkImpl lhs rhs
vd = [Var_decl [n1, n2] free_sort nullRange]
quant = mkForall vd inner_form
-- | generates the name of the phi variable of a concrete sort
phiName :: SORT -> Id
phiName s = mkId [mkSimpleId $ "Phi_" ++ show s]
-- | generates the name of the phi variable of a concrete predicate
psiName :: Id -> Id
psiName s = mkId [mkSimpleId $ "Psi_" ++ show s]
{- | creates the axiom for the kernel of h given the sorts and the predicates
in M, the premises and the conclusion -}
mkKernelAx :: Set.Set SORT -> PredMap -> CASLFORMULA
-> CASLFORMULA -> Named CASLFORMULA
mkKernelAx ss preds prem conc = makeNamed "freeness_kernel" q2
where imp = mkImpl prem conc
q1 = quantifyPredsSorts ss imp
q2 = quantifyPredsPreds preds q1
{- | applies the second order quantification to the formula for the given
set of sorts -}
quantifyPredsSorts :: Set.Set SORT -> CASLFORMULA -> CASLFORMULA
quantifyPredsSorts ss f = Set.fold quantifyPredsSort f ss
{- | applies the second order quantification to the formula for the given
sort -}
quantifyPredsSort :: SORT -> CASLFORMULA -> CASLFORMULA
quantifyPredsSort = uncurry QuantPred . freePredNameAndType
{- | applies the second order quantification to the formula for the given
predicates -}
quantifyPredsPreds :: PredMap -> CASLFORMULA -> CASLFORMULA
quantifyPredsPreds = flip $ MapSet.foldWithKey quantifyPredsPred
{- | applies the second order quantification to the formula for the given
predicate -}
quantifyPredsPred :: Id -> PredType -> CASLFORMULA -> CASLFORMULA
quantifyPredsPred name (PredType args) f = q_form
where psi = psiName name
free_args = map mkFreeName args
pt = Pred_type free_args nullRange
q_form = QuantPred psi pt f
{- | given the axioms in the module M, the function computes the
axioms obtained for the homomorphisms -}
quotient_axs :: [Named CASLFORMULA] -> [Named CASLFORMULA]
quotient_axs = map quotient_ax
{- | given an axiom in the module M, the function computes the
axioms obtained for the homomorphisms -}
quotient_ax :: Named CASLFORMULA -> Named CASLFORMULA
quotient_ax nsen = nsen'
where sen = sentence nsen
sen' = homomorphy_form sen
nsen' = nsen { sentence = sen' }
-- | applies the homomorphism operator to the terms of the given formula
homomorphy_form :: CASLFORMULA -> CASLFORMULA
homomorphy_form (Quantification q _ f r) = Quantification q var_decl f' r
where f' = homomorphy_form f
vars = getVars f'
var_decl = listVarDecl vars
homomorphy_form (Junction j fs r) = Junction j fs' r
where fs' = map homomorphy_form fs
homomorphy_form (Relation f1 c f2 r) = Relation f1' c f2' r
where f1' = homomorphy_form f1
f2' = homomorphy_form f2
homomorphy_form (Negation f r) = Negation f' r
where f' = homomorphy_form f
homomorphy_form (Predication ps ts r) = Predication ps ts' r
where ts' = map homomorphy_term ts
homomorphy_form (Definedness t r) = Definedness t' r
where t' = homomorphy_term t
homomorphy_form (Equation t1 e t2 r) = Equation t1' e t2' r
where t1' = homomorphy_term t1
t2' = homomorphy_term t2
homomorphy_form (Membership t s r) = Membership t' s r
where t' = homomorphy_term t
homomorphy_form (Mixfix_formula t) = Mixfix_formula t'
where t' = homomorphy_term t
homomorphy_form f = f
-- | applies the homomorphism operator to the term when possible
homomorphy_term :: CASLTERM -> CASLTERM
homomorphy_term (Qual_var v s r) = t
where free_s = mkFreeName s
v' = Qual_var v free_s r
ot_hom = Op_type Partial [free_s] s nullRange
name_hom = mkQualOp homId ot_hom
t = mkAppl name_hom [v']
homomorphy_term (Application os ts r) = t'
where ts' = map free_term ts
Qual_op_name op_name ot op_r = os
Op_type _ ar co ot_r = ot
op_name' = mkFreeName op_name
ar' = map mkFreeName ar
co' = mkFreeName co
ot' = Op_type Total ar' co' ot_r
os' = Qual_op_name op_name' ot' op_r
t = Application os' ts' r
ot_hom = Op_type Partial [co'] co nullRange
name_hom = mkQualOp homId ot_hom
t' = mkAppl name_hom [t]
homomorphy_term t = t
hom_surjectivity :: Set.Set SORT -> [Named CASLFORMULA]
hom_surjectivity = Set.fold f []
where f x = (sort_surj x :)
-- | generates the formula to state the homomorphism is surjective
sort_surj :: SORT -> Named CASLFORMULA
sort_surj s = form'
where v1 = newVarIndex 0 $ mkFreeName s
id_v1 = mkSimpleId "V0"
vd1 = mkVarDecl id_v1 (mkFreeName s)
v2 = newVarIndex 1 s
id_v2 = mkSimpleId "V1"
vd2 = mkVarDecl id_v2 s
ot_hom = Op_type Partial [mkFreeName s] s nullRange
name_hom = mkQualOp homId ot_hom
lhs = mkAppl name_hom [v1]
inner_form = mkExEq lhs v2
inner_form' = mkExist [vd1] inner_form
form = mkForall [vd2] inner_form'
form' = makeNamed ("ga_hom_surj_" ++ show s) form
-- | generates the axioms for the homomorphisms applied to the predicates
homomorphism_axs_preds :: PredMap -> [Named CASLFORMULA]
homomorphism_axs_preds =
MapSet.foldWithKey (\ p_name -> (:) . homomorphism_form_pred p_name) []
-- | generates the axioms for the homomorphisms applied to a predicate
homomorphism_form_pred :: Id -> PredType -> Named CASLFORMULA
homomorphism_form_pred name (PredType args) = named_form
where free_args = map mkFreeName args
vars_lhs = createVars 0 free_args
lhs_pt = Pred_type free_args nullRange
lhs_pred_name = mkQualPred (mkFreeName name) lhs_pt
lhs = mkPredication lhs_pred_name vars_lhs
inner_rhs = apply_hom_vars args vars_lhs
pt_rhs = Pred_type args nullRange
name_rhs = mkQualPred name pt_rhs
rhs = mkPredication name_rhs inner_rhs
form = mkEqv lhs rhs
form' = quantifyUniversally form
named_form = makeNamed "" form'
-- | generates the axioms for the homomorphisms applied to the operators
homomorphism_axs_ops :: OpMap -> [Named CASLFORMULA]
homomorphism_axs_ops =
MapSet.foldWithKey (\ op_name -> (:) . homomorphism_form_op op_name) []
-- | generates the axiom for the homomorphism applied to a concrete op
homomorphism_form_op :: Id -> OpType -> Named CASLFORMULA
homomorphism_form_op name (OpType _ args res) = named_form
where free_args = map mkFreeName args
vars_lhs = createVars 0 free_args
ot_lhs = Op_type Total free_args (mkFreeName res) nullRange
ot_hom = Op_type Partial [mkFreeName res] res nullRange
name_hom = mkQualOp homId ot_hom
name_lhs = mkQualOp (mkFreeName name) ot_lhs
inner_lhs = mkAppl name_lhs vars_lhs
lhs = mkAppl name_hom [inner_lhs]
ot_rhs = Op_type Total args res nullRange
name_rhs = mkQualOp name ot_rhs
inner_rhs = apply_hom_vars args vars_lhs
rhs = mkAppl name_rhs inner_rhs
form = mkStEq lhs rhs
form' = quantifyUniversally form
named_form = makeNamed "" form'
-- | generates the variables for the homomorphisms
apply_hom_vars :: [SORT] -> [CASLTERM] -> [CASLTERM]
apply_hom_vars (s : ss) (t : ts) = t' : ts'
where ot_hom = Op_type Partial [mkFreeName s] s nullRange
name_hom = mkQualOp homId ot_hom
t' = mkAppl name_hom [t]
ts' = apply_hom_vars ss ts
apply_hom_vars _ _ = []
-- | generates a list of differents variables of the given sorts
createVars :: Int -> [SORT] -> [CASLTERM]
createVars _ [] = []
createVars i (s : ss) = var : ts
where var = newVarIndex i s
ts = createVars (i + 1) ss
-- | computes the set of components from the map of operators
ops2comp :: OpMap -> Set.Set Component
ops2comp = MapSet.foldWithKey (\ n -> Set.insert . Component n) Set.empty
-- | computes the sentence for the constructors
freeCons :: GenAx -> [Named CASLFORMULA]
freeCons (sorts, rel, ops) =
let sortList = Set.toList sorts
opSyms = map ( \ c -> let iden = compId c in Qual_op_name iden
(toOP_TYPE $ compType c) $ posOfId iden) $ Set.toList ops
injSyms = map ( \ (s, t) -> let p = posOfId s in
Qual_op_name (mkUniqueInjName s t)
(Op_type Total [s] t p) p)
$ Rel.toList $ Rel.irreflex rel
allSyms = opSyms ++ injSyms
resType _ (Op_name _) = False
resType s (Qual_op_name _ t _) = res_OP_TYPE t == s
getIndex s = fromMaybe (-1) $ elemIndex s sortList
addIndices (Op_name _) =
error "CASL/StaticAna: Internal error in function addIndices"
addIndices os@(Qual_op_name _ t _) =
(os, map getIndex $ args_OP_TYPE t)
collectOps s =
Constraint s (map addIndices $ filter (resType s) allSyms) s
constrs = map collectOps sortList
f = mkSort_gen_ax constrs True
-- added by me:
nonSub (Qual_op_name n _ _) = not $ isInjName n
nonSub _ = error "use qualified names"
consSymbs = map (filter nonSub . map fst . opSymbs) constrs
toTuple (Qual_op_name n ot@(Op_type _ args _ _) _) =
(n, toOpType ot, map Sort args)
toTuple _ = error "use qualified names"
consSymbs' = map (map toTuple) consSymbs
sortSymbs = map (filter (not . nonSub) . map fst . opSymbs) constrs
getSubsorts (Qual_op_name _ (Op_type _ [ss] _ _) _) = ss
getSubsorts _ = error "error in injSyms"
sortSymbs' = map (\ l ->
case l of
Qual_op_name _ (Op_type _ _ rs _) _ : _ ->
(rs, map getSubsorts l)
_ -> error "empty list filtered")
$ filter (not . null) sortSymbs
sortAx = concatMap (uncurry makeDisjSubsorts) sortSymbs'
freeAx = concatMap (\ l -> makeDisjoint l ++
map makeInjective (
filter (\ (_, _, x) -> not $ null x) l))
consSymbs'
sameSort (Constraint s _ _) (Constraint s' _ _) = s == s'
disjToSortAx = concatMap (\ ctors -> let
cs = map (map fst . opSymbs) ctors
cSymbs = concatMap (map toTuple
. filter nonSub) cs
sSymbs = concatMap (map getSubsorts
. filter (not . nonSub)) cs
in
concatMap (\ c -> map (makeDisjToSort c) sSymbs)
cSymbs) $ groupBy sameSort constrs
in case constrs of
[] -> []
_ -> [toSortGenNamed f sortList]
++ freeAx ++ sortAx ++ disjToSortAx
-- | given the signature in M the function computes the signature K
create_sigma_k :: Set.Set SORT -> CASLSign -> CASLSign
create_sigma_k ss sg_m = usg'
where iota_sg = totalSignCopy sg_m
usg = addSig const sg_m iota_sg
om' = homomorphism_ops (sortSet sg_m) (opMap usg)
om'' = make_ops ss om'
usg' = usg { opMap = om'' }
{- | adds the make functions for the sorts in the initial module to the
operator map -}
make_ops :: Set.Set SORT -> OpMap -> OpMap
make_ops ss om = Set.fold make_op om ss
-- | adds the make functions for the sort to the operator map
make_op :: SORT -> OpMap -> OpMap
make_op s = MapSet.insert makeId $ mkTotOpType [s] $ mkFreeName s
-- | identifier of the make function
makeId :: Id
makeId = mkId [mkSimpleId "make"]
-- | identifier of the homomorphism function
homId :: Id
homId = mkId [mkSimpleId "hom"]
-- | creates the homomorphism operators and adds it to the given operator map
homomorphism_ops :: Set.Set SORT -> OpMap -> OpMap
homomorphism_ops ss om = Set.fold f om ss
where ot sort = OpType Partial [mkFreeName sort] sort
f = MapSet.insert homId . ot
-- | applies the iota renaming to a signature
totalSignCopy :: CASLSign -> CASLSign
totalSignCopy sg = sg {
emptySortSet = ess,
sortRel = sr,
opMap = om,
assocOps = aom,
predMap = pm,
varMap = vm,
sentences = [],
declaredSymbols = sms,
annoMap = am
}
where ess = iota_sort_set $ emptySortSet sg
sr = iota_sort_rel $ sortRel sg
om = iota_op_map $ opMap sg
aom = iota_op_map $ assocOps sg
pm = iota_pred_map $ predMap sg
vm = iota_var_map $ varMap sg
sms = iota_syms $ declaredSymbols sg
am = iota_anno_map $ annoMap sg
-- | applies the iota renaming to a set of sorts
iota_sort_set :: Set.Set SORT -> Set.Set SORT
iota_sort_set = Set.map mkFreeName
-- | applies the iota renaming to a sort relation
iota_sort_rel :: Rel.Rel SORT -> Rel.Rel SORT
iota_sort_rel = Rel.map mkFreeName
-- | applies the iota renaming to an operator map
iota_op_map :: OpMap -> OpMap
iota_op_map = MapSet.foldWithKey
(\ op (OpType _ args res) -> MapSet.insert (mkFreeName op)
$ mkTotOpType (map mkFreeName args) (mkFreeName res)) MapSet.empty
-- | applies the iota renaming to a predicate map
iota_pred_map :: PredMap -> PredMap
iota_pred_map = MapSet.foldWithKey
(\ p (PredType args) -> MapSet.insert (mkFreeName p)
$ PredType $ map mkFreeName args) MapSet.empty
-- | applies the iota renaming to a variable map
iota_var_map :: Map.Map SIMPLE_ID SORT -> Map.Map SIMPLE_ID SORT
iota_var_map = Map.map mkFreeName
-- | applies the iota renaming to symbols
iota_syms :: Set.Set Symbol -> Set.Set Symbol
iota_syms = Set.map iota_symbol
-- | applies the iota renaming to a symbol
iota_symbol :: Symbol -> Symbol
iota_symbol (Symbol name ty) = Symbol (mkFreeName name) $ case ty of
SortAsItemType -> SortAsItemType
SubsortAsItemType s -> SubsortAsItemType $ mkFreeName s
OpAsItemType (OpType _ args res) -> OpAsItemType
$ mkTotOpType (map mkFreeName args) (mkFreeName res)
PredAsItemType (PredType args) -> PredAsItemType
$ PredType $ map mkFreeName args
-- | applies the iota renaming to the annotations
iota_anno_map :: MapSet.MapSet Symbol Annotation
-> MapSet.MapSet Symbol Annotation
iota_anno_map = MapSet.fromMap . Map.mapKeys iota_symbol . MapSet.toMap
-- Some auxiliary functions
-- | create a new name for the iota morphism
mkFreeName :: Id -> Id
mkFreeName i@(Id ts cs r) = case ts of
t : s -> let st = tokStr t in case st of
c : _ | isAlphaNum c -> Id (freeToken st : s) cs r
| otherwise -> Id [mkSimpleId "gn_free"] [i] r
_ -> Id (mkSimpleId "gn_free_f" : ts) cs r
_ -> i
-- | a prefix for free names
freeNamePrefix :: String
freeNamePrefix = "gn_free_"
-- | create a generated simple identifier
freeToken :: String -> Token
freeToken str = mkSimpleId $ freeNamePrefix ++ str
-- | obtains the sorts of the given list of term
getSorts :: [CASLTERM] -> [SORT]
getSorts = mapMaybe getSort
-- | compute the sort of the term, if possible
getSort :: CASLTERM -> Maybe SORT
getSort (Qual_var _ kind _) = Just kind
getSort (Application op _ _) = case op of
Qual_op_name _ (Op_type _ _ kind _) _ -> Just kind
_ -> Nothing
getSort _ = Nothing
-- | extracts the predicate name from the predicate symbol
pred_symb_name :: PRED_SYMB -> PRED_NAME
pred_symb_name (Pred_name pn) = pn
pred_symb_name (Qual_pred_name pn _ _) = pn
{- | extract the variables from a CASL formula and put them in a map
with keys the sort of the variables and value the set of variables
in this sort -}
getVars :: CASLFORMULA -> Map.Map Id (Set.Set Token)
getVars (Quantification _ _ f _) = getVars f
getVars (QuantOp _ _ f) = getVars f
getVars (QuantPred _ _ f) = getVars f
getVars (Junction _ fs _) =
foldr (Map.unionWith Set.union . getVars) Map.empty fs
getVars (Relation f1 _ f2 _) = Map.unionWith Set.union v1 v2
where v1 = getVars f1
v2 = getVars f2
getVars (Negation f _) = getVars f
getVars (Predication _ ts _) =
foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts
getVars (Definedness t _) = getVarsTerm t
getVars (Equation t1 _ t2 _) = Map.unionWith Set.union v1 v2
where v1 = getVarsTerm t1
v2 = getVarsTerm t2
getVars (Membership t _ _) = getVarsTerm t
getVars (Mixfix_formula t) = getVarsTerm t
getVars _ = Map.empty
-- | extract the variables of a CASL term
getVarsTerm :: CASLTERM -> Map.Map Id (Set.Set Token)
getVarsTerm (Qual_var var sort _) =
Map.insert sort (Set.singleton var) Map.empty
getVarsTerm (Application _ ts _) =
foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts
getVarsTerm (Sorted_term t _ _) = getVarsTerm t
getVarsTerm (Cast t _ _) = getVarsTerm t
getVarsTerm (Conditional t1 f t2 _) = Map.unionWith Set.union v3 m
where v1 = getVarsTerm t1
v2 = getVarsTerm t2
v3 = getVars f
m = Map.unionWith Set.union v1 v2
getVarsTerm (Mixfix_term ts) =
foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts
getVarsTerm (Mixfix_parenthesized ts _) =
foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts
getVarsTerm (Mixfix_bracketed ts _) =
foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts
getVarsTerm (Mixfix_braced ts _) =
foldr (Map.unionWith Set.union . getVarsTerm) Map.empty ts
getVarsTerm _ = Map.empty
-- | add universal quantification of all variables in the formula
quantifyUniversally :: CASLFORMULA -> CASLFORMULA
quantifyUniversally form = if null var_decl
then form
else Quantification Universal var_decl form nullRange
where vars = getVars form
var_decl = listVarDecl vars
{- | traverses a map with sorts as keys and sets of variables as value
and creates a list of variable declarations -}
listVarDecl :: Map.Map Id (Set.Set Token) -> [VAR_DECL]
listVarDecl = Map.foldWithKey f []
where f sort var_set = (Var_decl (Set.toList var_set) sort nullRange :)
-- | generates a new variable qualified with the given number
newVarIndex :: Int -> SORT -> CASLTERM
newVarIndex i sort = Qual_var var sort nullRange
where var = mkSimpleId $ 'V' : show i
-- | generates a new variable
newVar :: SORT -> CASLTERM
newVar sort = Qual_var var sort nullRange
where var = mkSimpleId "V"
-- | generates the free representation of an OP_SYMB
free_op_sym :: OP_SYMB -> OP_SYMB
free_op_sym (Op_name on) = Op_name $ mkFreeName on
free_op_sym (Qual_op_name on ot r) = Qual_op_name on' ot' r
where on' = mkFreeName on
ot' = free_op_type ot
-- | generates the free representation of an OP_TYPE
free_op_type :: OP_TYPE -> OP_TYPE
free_op_type (Op_type _ args res r) = Op_type Total args' res' r
where args' = map mkFreeName args
res' = mkFreeName res
-- | generates the free representation of a PRED_SYMB
free_pred_sym :: PRED_SYMB -> PRED_SYMB
free_pred_sym (Pred_name pn) = Pred_name $ mkFreeName pn
free_pred_sym (Qual_pred_name pn pt r) = Qual_pred_name pn' pt' r
where pn' = mkFreeName pn
pt' = free_pred_type pt
-- | generates the free representation of a PRED_TYPE
free_pred_type :: PRED_TYPE -> PRED_TYPE
free_pred_type (Pred_type args r) = Pred_type args' r
where args' = map mkFreeName args
-- | generates the free representation of a CASLTERM
free_term :: CASLTERM -> CASLTERM
free_term (Qual_var v s r) = Qual_var v (mkFreeName s) r
free_term (Application os ts r) = Application os' ts' r
where ts' = map free_term ts
os' = free_op_sym os
free_term (Sorted_term t s r) = Sorted_term t' s' r
where t' = free_term t
s' = mkFreeName s
free_term (Cast t s r) = Cast t' s' r
where t' = free_term t
s' = mkFreeName s
free_term (Conditional t1 f t2 r) = Conditional t1' f' t2' r
where t1' = free_term t1
t2' = free_term t2
f' = free_formula f
free_term (Mixfix_qual_pred ps) = Mixfix_qual_pred ps'
where ps' = free_pred_sym ps
free_term (Mixfix_term ts) = Mixfix_term ts'
where ts' = map free_term ts
free_term (Mixfix_sorted_term s r) = Mixfix_sorted_term s' r
where s' = mkFreeName s
free_term (Mixfix_cast s r) = Mixfix_cast s' r
where s' = mkFreeName s
free_term (Mixfix_parenthesized ts r) = Mixfix_parenthesized ts' r
where ts' = map free_term ts
free_term (Mixfix_bracketed ts r) = Mixfix_bracketed ts' r
where ts' = map free_term ts
free_term (Mixfix_braced ts r) = Mixfix_braced ts' r
where ts' = map free_term ts
free_term t = t
-- | generates the free representation of a list of variable declarations
free_var_decls :: [VAR_DECL] -> [VAR_DECL]
free_var_decls = map free_var_decl
-- | generates the free representation of a variable declaration
free_var_decl :: VAR_DECL -> VAR_DECL
free_var_decl (Var_decl vs s r) = Var_decl vs s' r
where s' = mkFreeName s
{- | computes the substitution needed for the kernel of h to the
sentences of the theory of M -}
free_formula :: CASLFORMULA -> CASLFORMULA
free_formula (Quantification q vs f r) = Quantification q vs' f' r
where vs' = free_var_decls vs
f' = free_formula f
free_formula (Junction j fs r) = Junction j fs' r
where fs' = map free_formula fs
free_formula (Relation f1 c f2 r) = Relation f1' c f2' r
where f1' = free_formula f1
f2' = free_formula f2
free_formula (Negation f r) = Negation f' r
where f' = free_formula f
free_formula (Predication ps ts r) = pr
where ss = getSorts ts
free_ss = map mkFreeName ss
ts' = map free_term ts
psi = psiName $ pred_symb_name ps
pt = Pred_type free_ss nullRange
ps' = Qual_pred_name psi pt nullRange
pr = Predication ps' ts' r
free_formula (Definedness t r) = case sort of
Nothing -> Definedness t' r
Just s -> mkPredication (freePredSymb s) [t', t']
where t' = free_term t
sort = getSort t
free_formula (Equation t1 e t2 r) = let
t1' = free_term t1
t2' = free_term t2
sort = getSort t1
in case sort of
Nothing -> Equation t1' e t2' r
Just s -> let
ps = freePredSymb s
pred1 = mkPredication ps [t1', t2']
pred2 = mkNeg $ mkPredication ps [t1', t1']
pred3 = mkNeg $ mkPredication ps [t2', t2']
pred4 = conjunct [pred2, pred3]
pred5 = disjunct [pred1, pred4]
in if e == Existl then pred1 else pred5
free_formula (Membership t s r) = Membership t' s' r
where t' = free_term t
s' = mkFreeName s
free_formula (Mixfix_formula t) = Mixfix_formula t'
where t' = free_term t
free_formula (QuantOp on ot f) = QuantOp on' ot' f'
where on' = mkFreeName on
ot' = free_op_type ot
f' = free_formula f
free_formula (QuantPred pn pt f) = QuantPred pn' pt' f'
where pn' = mkFreeName pn
pt' = free_pred_type pt
f' = free_formula f
free_formula f = f
| spechub/Hets | CASL/Freeness.hs | gpl-2.0 | 34,230 | 0 | 22 | 9,502 | 9,398 | 4,820 | 4,578 | 651 | 8 |
-- Class may not be nested in a class
class X a where
j :: a -> a
class Y b where
i :: b ->b
| roberth/uu-helium | test/typeClassesParse/Nonnesting1.hs | gpl-3.0 | 105 | 3 | 6 | 37 | 39 | 19 | 20 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Glacier.AbortMultipartUpload
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation aborts a multipart upload identified by the upload ID.
--
-- After the Abort Multipart Upload request succeeds, you cannot upload any
-- more parts to the multipart upload or complete the multipart upload.
-- Aborting a completed upload fails. However, aborting an already-aborted
-- upload will succeed, for a short time. For more information about
-- uploading a part and completing a multipart upload, see
-- UploadMultipartPart and CompleteMultipartUpload.
--
-- This operation is idempotent.
--
-- An AWS account has full permission to perform all operations (actions).
-- However, AWS Identity and Access Management (IAM) users don\'t have any
-- permissions by default. You must grant them explicit permission to
-- perform specific actions. For more information, see
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identity and Access Management (IAM)>.
--
-- For conceptual information and underlying REST API, go to
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/working-with-archives.html Working with Archives in Amazon Glacier>
-- and
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-multipart-abort-upload.html Abort Multipart Upload>
-- in the /Amazon Glacier Developer Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-AbortMultipartUpload.html AWS API Reference> for AbortMultipartUpload.
module Network.AWS.Glacier.AbortMultipartUpload
(
-- * Creating a Request
abortMultipartUpload
, AbortMultipartUpload
-- * Request Lenses
, amuAccountId
, amuVaultName
, amuUploadId
-- * Destructuring the Response
, abortMultipartUploadResponse
, AbortMultipartUploadResponse
) where
import Network.AWS.Glacier.Types
import Network.AWS.Glacier.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Provides options to abort a multipart upload identified by the upload
-- ID.
--
-- For information about the underlying REST API, go to
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-multipart-abort-upload.html Abort Multipart Upload>.
-- For conceptual information, go to
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/working-with-archives.html Working with Archives in Amazon Glacier>.
--
-- /See:/ 'abortMultipartUpload' smart constructor.
data AbortMultipartUpload = AbortMultipartUpload'
{ _amuAccountId :: !Text
, _amuVaultName :: !Text
, _amuUploadId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'AbortMultipartUpload' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'amuAccountId'
--
-- * 'amuVaultName'
--
-- * 'amuUploadId'
abortMultipartUpload
:: Text -- ^ 'amuAccountId'
-> Text -- ^ 'amuVaultName'
-> Text -- ^ 'amuUploadId'
-> AbortMultipartUpload
abortMultipartUpload pAccountId_ pVaultName_ pUploadId_ =
AbortMultipartUpload'
{ _amuAccountId = pAccountId_
, _amuVaultName = pVaultName_
, _amuUploadId = pUploadId_
}
-- | The 'AccountId' value is the AWS account ID of the account that owns the
-- vault. You can either specify an AWS account ID or optionally a single
-- apos'-'apos (hyphen), in which case Amazon Glacier uses the AWS account
-- ID associated with the credentials used to sign the request. If you use
-- an account ID, do not include any hyphens (apos-apos) in the ID.
amuAccountId :: Lens' AbortMultipartUpload Text
amuAccountId = lens _amuAccountId (\ s a -> s{_amuAccountId = a});
-- | The name of the vault.
amuVaultName :: Lens' AbortMultipartUpload Text
amuVaultName = lens _amuVaultName (\ s a -> s{_amuVaultName = a});
-- | The upload ID of the multipart upload to delete.
amuUploadId :: Lens' AbortMultipartUpload Text
amuUploadId = lens _amuUploadId (\ s a -> s{_amuUploadId = a});
instance AWSRequest AbortMultipartUpload where
type Rs AbortMultipartUpload =
AbortMultipartUploadResponse
request = delete glacier
response = receiveNull AbortMultipartUploadResponse'
instance ToHeaders AbortMultipartUpload where
toHeaders = const mempty
instance ToPath AbortMultipartUpload where
toPath AbortMultipartUpload'{..}
= mconcat
["/", toBS _amuAccountId, "/vaults/",
toBS _amuVaultName, "/multipart-uploads/",
toBS _amuUploadId]
instance ToQuery AbortMultipartUpload where
toQuery = const mempty
-- | /See:/ 'abortMultipartUploadResponse' smart constructor.
data AbortMultipartUploadResponse =
AbortMultipartUploadResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'AbortMultipartUploadResponse' with the minimum fields required to make a request.
--
abortMultipartUploadResponse
:: AbortMultipartUploadResponse
abortMultipartUploadResponse = AbortMultipartUploadResponse'
| fmapfmapfmap/amazonka | amazonka-glacier/gen/Network/AWS/Glacier/AbortMultipartUpload.hs | mpl-2.0 | 5,741 | 0 | 9 | 994 | 523 | 328 | 195 | 70 | 1 |
Subsets and Splits