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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Com.Mysql.Cj.Mysqlx.Protobuf.ViewSqlSecurity (ViewSqlSecurity(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified GHC.Generics as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data ViewSqlSecurity = INVOKER
| DEFINER
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data,
Prelude'.Generic)
instance P'.Mergeable ViewSqlSecurity
instance Prelude'.Bounded ViewSqlSecurity where
minBound = INVOKER
maxBound = DEFINER
instance P'.Default ViewSqlSecurity where
defaultValue = INVOKER
toMaybe'Enum :: Prelude'.Int -> P'.Maybe ViewSqlSecurity
toMaybe'Enum 1 = Prelude'.Just INVOKER
toMaybe'Enum 2 = Prelude'.Just DEFINER
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum ViewSqlSecurity where
fromEnum INVOKER = 1
fromEnum DEFINER = 2
toEnum
= P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ViewSqlSecurity") .
toMaybe'Enum
succ INVOKER = DEFINER
succ _ = Prelude'.error "hprotoc generated code: succ failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ViewSqlSecurity"
pred DEFINER = INVOKER
pred _ = Prelude'.error "hprotoc generated code: pred failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ViewSqlSecurity"
instance P'.Wire ViewSqlSecurity where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB ViewSqlSecurity
instance P'.MessageAPI msg' (msg' -> ViewSqlSecurity) ViewSqlSecurity where
getVal m' f' = f' m'
instance P'.ReflectEnum ViewSqlSecurity where
reflectEnum = [(1, "INVOKER", INVOKER), (2, "DEFINER", DEFINER)]
reflectEnumInfo _
= P'.EnumInfo
(P'.makePNF (P'.pack ".Mysqlx.Crud.ViewSqlSecurity") [] ["Com", "Mysql", "Cj", "Mysqlx", "Protobuf"] "ViewSqlSecurity")
["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "ViewSqlSecurity.hs"]
[(1, "INVOKER"), (2, "DEFINER")]
instance P'.TextType ViewSqlSecurity where
tellT = P'.tellShow
getT = P'.getRead | naoto-ogawa/h-xproto-mysql | src/Com/Mysql/Cj/Mysqlx/Protobuf/ViewSqlSecurity.hs | mit | 2,561 | 0 | 11 | 417 | 631 | 347 | 284 | 53 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html
module Stratosphere.Resources.SSMPatchBaseline where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.SSMPatchBaselineRuleGroup
import Stratosphere.ResourceProperties.SSMPatchBaselinePatchFilterGroup
import Stratosphere.ResourceProperties.SSMPatchBaselinePatchSource
-- | Full data type definition for SSMPatchBaseline. See 'ssmPatchBaseline'
-- for a more convenient constructor.
data SSMPatchBaseline =
SSMPatchBaseline
{ _sSMPatchBaselineApprovalRules :: Maybe SSMPatchBaselineRuleGroup
, _sSMPatchBaselineApprovedPatches :: Maybe (ValList Text)
, _sSMPatchBaselineApprovedPatchesComplianceLevel :: Maybe (Val Text)
, _sSMPatchBaselineApprovedPatchesEnableNonSecurity :: Maybe (Val Bool)
, _sSMPatchBaselineDescription :: Maybe (Val Text)
, _sSMPatchBaselineGlobalFilters :: Maybe SSMPatchBaselinePatchFilterGroup
, _sSMPatchBaselineName :: Val Text
, _sSMPatchBaselineOperatingSystem :: Maybe (Val Text)
, _sSMPatchBaselinePatchGroups :: Maybe (ValList Text)
, _sSMPatchBaselineRejectedPatches :: Maybe (ValList Text)
, _sSMPatchBaselineRejectedPatchesAction :: Maybe (Val Text)
, _sSMPatchBaselineSources :: Maybe [SSMPatchBaselinePatchSource]
} deriving (Show, Eq)
instance ToResourceProperties SSMPatchBaseline where
toResourceProperties SSMPatchBaseline{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::SSM::PatchBaseline"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ fmap (("ApprovalRules",) . toJSON) _sSMPatchBaselineApprovalRules
, fmap (("ApprovedPatches",) . toJSON) _sSMPatchBaselineApprovedPatches
, fmap (("ApprovedPatchesComplianceLevel",) . toJSON) _sSMPatchBaselineApprovedPatchesComplianceLevel
, fmap (("ApprovedPatchesEnableNonSecurity",) . toJSON) _sSMPatchBaselineApprovedPatchesEnableNonSecurity
, fmap (("Description",) . toJSON) _sSMPatchBaselineDescription
, fmap (("GlobalFilters",) . toJSON) _sSMPatchBaselineGlobalFilters
, (Just . ("Name",) . toJSON) _sSMPatchBaselineName
, fmap (("OperatingSystem",) . toJSON) _sSMPatchBaselineOperatingSystem
, fmap (("PatchGroups",) . toJSON) _sSMPatchBaselinePatchGroups
, fmap (("RejectedPatches",) . toJSON) _sSMPatchBaselineRejectedPatches
, fmap (("RejectedPatchesAction",) . toJSON) _sSMPatchBaselineRejectedPatchesAction
, fmap (("Sources",) . toJSON) _sSMPatchBaselineSources
]
}
-- | Constructor for 'SSMPatchBaseline' containing required fields as
-- arguments.
ssmPatchBaseline
:: Val Text -- ^ 'ssmpbName'
-> SSMPatchBaseline
ssmPatchBaseline namearg =
SSMPatchBaseline
{ _sSMPatchBaselineApprovalRules = Nothing
, _sSMPatchBaselineApprovedPatches = Nothing
, _sSMPatchBaselineApprovedPatchesComplianceLevel = Nothing
, _sSMPatchBaselineApprovedPatchesEnableNonSecurity = Nothing
, _sSMPatchBaselineDescription = Nothing
, _sSMPatchBaselineGlobalFilters = Nothing
, _sSMPatchBaselineName = namearg
, _sSMPatchBaselineOperatingSystem = Nothing
, _sSMPatchBaselinePatchGroups = Nothing
, _sSMPatchBaselineRejectedPatches = Nothing
, _sSMPatchBaselineRejectedPatchesAction = Nothing
, _sSMPatchBaselineSources = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvalrules
ssmpbApprovalRules :: Lens' SSMPatchBaseline (Maybe SSMPatchBaselineRuleGroup)
ssmpbApprovalRules = lens _sSMPatchBaselineApprovalRules (\s a -> s { _sSMPatchBaselineApprovalRules = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvedpatches
ssmpbApprovedPatches :: Lens' SSMPatchBaseline (Maybe (ValList Text))
ssmpbApprovedPatches = lens _sSMPatchBaselineApprovedPatches (\s a -> s { _sSMPatchBaselineApprovedPatches = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvedpatchescompliancelevel
ssmpbApprovedPatchesComplianceLevel :: Lens' SSMPatchBaseline (Maybe (Val Text))
ssmpbApprovedPatchesComplianceLevel = lens _sSMPatchBaselineApprovedPatchesComplianceLevel (\s a -> s { _sSMPatchBaselineApprovedPatchesComplianceLevel = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvedpatchesenablenonsecurity
ssmpbApprovedPatchesEnableNonSecurity :: Lens' SSMPatchBaseline (Maybe (Val Bool))
ssmpbApprovedPatchesEnableNonSecurity = lens _sSMPatchBaselineApprovedPatchesEnableNonSecurity (\s a -> s { _sSMPatchBaselineApprovedPatchesEnableNonSecurity = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-description
ssmpbDescription :: Lens' SSMPatchBaseline (Maybe (Val Text))
ssmpbDescription = lens _sSMPatchBaselineDescription (\s a -> s { _sSMPatchBaselineDescription = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-globalfilters
ssmpbGlobalFilters :: Lens' SSMPatchBaseline (Maybe SSMPatchBaselinePatchFilterGroup)
ssmpbGlobalFilters = lens _sSMPatchBaselineGlobalFilters (\s a -> s { _sSMPatchBaselineGlobalFilters = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-name
ssmpbName :: Lens' SSMPatchBaseline (Val Text)
ssmpbName = lens _sSMPatchBaselineName (\s a -> s { _sSMPatchBaselineName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-operatingsystem
ssmpbOperatingSystem :: Lens' SSMPatchBaseline (Maybe (Val Text))
ssmpbOperatingSystem = lens _sSMPatchBaselineOperatingSystem (\s a -> s { _sSMPatchBaselineOperatingSystem = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-patchgroups
ssmpbPatchGroups :: Lens' SSMPatchBaseline (Maybe (ValList Text))
ssmpbPatchGroups = lens _sSMPatchBaselinePatchGroups (\s a -> s { _sSMPatchBaselinePatchGroups = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-rejectedpatches
ssmpbRejectedPatches :: Lens' SSMPatchBaseline (Maybe (ValList Text))
ssmpbRejectedPatches = lens _sSMPatchBaselineRejectedPatches (\s a -> s { _sSMPatchBaselineRejectedPatches = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-rejectedpatchesaction
ssmpbRejectedPatchesAction :: Lens' SSMPatchBaseline (Maybe (Val Text))
ssmpbRejectedPatchesAction = lens _sSMPatchBaselineRejectedPatchesAction (\s a -> s { _sSMPatchBaselineRejectedPatchesAction = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-sources
ssmpbSources :: Lens' SSMPatchBaseline (Maybe [SSMPatchBaselinePatchSource])
ssmpbSources = lens _sSMPatchBaselineSources (\s a -> s { _sSMPatchBaselineSources = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/SSMPatchBaseline.hs | mit | 7,439 | 0 | 15 | 768 | 1,177 | 668 | 509 | 83 | 1 |
{-# LANGUAGE CPP #-}
{- |
Module : $Header$
Description : Writing various formats, according to Hets options
Copyright : (c) Klaus Luettich, C.Maeder, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable(DevGraph)
Writing various formats, according to Hets options
-}
module Driver.WriteFn
( writeSpecFiles
, writeVerbFile
, writeLG
) where
import Text.ParserCombinators.Parsec
import Text.XML.Light
import Control.Monad
import Data.List (partition, (\\))
import Data.Maybe
import Common.AS_Annotation
import Common.Id
import Common.IRI (IRI, simpleIdToIRI, iriToStringShortUnsecure)
import Common.DocUtils
import Common.ExtSign
import Common.LibName
import Common.Result
import Common.Parsec (forget)
import Common.GlobalAnnotations (GlobalAnnos)
import qualified Data.Map as Map
import Common.SExpr
import Common.IO
import Comorphisms.LogicGraph
import Logic.Coerce
import Logic.Comorphism (targetLogic)
import Logic.Grothendieck
import Logic.LGToXml
import Logic.Logic
import Logic.Prover
import Proofs.StatusUtils
import Static.GTheory
import Static.DevGraph
import Static.CheckGlobalContext
import Static.DotGraph
import qualified Static.PrintDevGraph as DG
import Static.ComputeTheory
import qualified Static.ToXml as ToXml
import CASL.Logic_CASL
import CASL.CompositionTable.Pretty2
import CASL.CompositionTable.ToXml
import CASL.CompositionTable.ComputeTable
import CASL.CompositionTable.ModelChecker
import CASL.CompositionTable.ParseTable2
#ifdef PROGRAMATICA
import Haskell.CreateModules
#endif
import Isabelle.CreateTheories
import Isabelle.IsaParse
import Isabelle.IsaPrint (printIsaTheory)
import SoftFOL.CreateDFGDoc
import SoftFOL.DFGParser
import SoftFOL.ParseTPTP
import FreeCAD.XMLPrinter (exportXMLFC)
import FreeCAD.Logic_FreeCAD
import VSE.Logic_VSE
import VSE.ToSExpr
#ifndef NOOWLLOGIC
import OWL2.CreateOWL
import OWL2.Logic_OWL2
import qualified OWL2.ManchesterPrint as OWL2 (prepareBasicTheory)
import qualified OWL2.ManchesterParser as OWL2 (basicSpec)
#endif
#ifdef RDFLOGIC
import RDF.Logic_RDF
import qualified RDF.Print as RDF (printRDFBasicTheory)
#endif
import CommonLogic.Logic_CommonLogic
import qualified CommonLogic.AS_CommonLogic as CL_AS (exportCLIF)
import qualified CommonLogic.Parse_CLIF as CL_Parse (cltext)
import qualified CommonLogic.Print_KIF as Print_KIF (exportKIF)
import Driver.Options
import Driver.ReadFn (libNameToFile)
import Driver.WriteLibDefn
import OMDoc.XmlInterface (xmlOut)
import OMDoc.Export (exportLibEnv)
writeVerbFile :: HetcatsOpts -> FilePath -> String -> IO ()
writeVerbFile opts f str = do
putIfVerbose opts 2 $ "Writing file: " ++ f
writeEncFile (ioEncoding opts) f str
-- | compute for each LibName in the List a path relative to the given FilePath
writeVerbFiles :: HetcatsOpts -- ^ Hets options
-> String -- ^ A suffix to be combined with the libname
-> [(LibName, String)] -- ^ An output list
-> IO ()
writeVerbFiles opts suffix = mapM_ f
where f (ln, s) = writeVerbFile opts (libNameToFile ln ++ suffix) s
writeLibEnv :: HetcatsOpts -> FilePath -> LibEnv -> LibName -> OutType
-> IO ()
writeLibEnv opts filePrefix lenv ln ot =
let f = filePrefix ++ "." ++ show ot
dg = lookupDGraph ln lenv in case ot of
Prf -> toShATermString (ln, lookupHistory ln lenv)
>>= writeVerbFile opts f
XmlOut -> writeVerbFile opts f $ ppTopElement
$ ToXml.dGraph opts lenv ln dg
SymsXml -> writeVerbFile opts f $ ppTopElement
$ ToXml.dgSymbols dg
OmdocOut -> do
let Result ds mOmd = exportLibEnv (recurse opts) (outdir opts) ln lenv
showDiags opts ds
case mOmd of
Just omd -> writeVerbFiles opts ".omdoc"
$ map (\ (libn, od) -> (libn, xmlOut od)) omd
Nothing -> putIfVerbose opts 0 "could not translate to OMDoc"
GraphOut (Dot showInternalNodeLabels) -> writeVerbFile opts f
$ dotGraph f showInternalNodeLabels "" dg
_ -> return ()
writeSoftFOL :: HetcatsOpts -> FilePath -> G_theory -> IRI
-> SPFType -> Int -> String -> IO ()
writeSoftFOL opts f gTh i c n msg = do
let cc = case c of
ConsistencyCheck -> True
ProveTheory -> False
mDoc <- printTheoryAsSoftFOL i n cc
$ (if cc then theoremsToAxioms else id) gTh
maybe (putIfVerbose opts 0 $
"could not translate to " ++ msg ++ " file: " ++ f)
( \ d -> do
let str = shows d "\n"
case parse (if n == 0 then forget parseSPASS else forget tptp)
f str of
Left err -> putIfVerbose opts 0 $ show err
_ -> putIfVerbose opts 3 $ "reparsed: " ++ f
writeVerbFile opts f str) mDoc
writeFreeCADFile :: HetcatsOpts -> FilePath -> G_theory -> IO ()
writeFreeCADFile opts filePrefix (G_theory lid _ (ExtSign sign _) _ _ _) = do
fcSign <- coercePlainSign lid FreeCAD
"Expecting a FreeCAD signature for writing FreeCAD xml" sign
writeVerbFile opts (filePrefix ++ ".xml") $ exportXMLFC fcSign
writeIsaFile :: HetcatsOpts -> FilePath -> G_theory -> LibName -> IRI
-> IO ()
writeIsaFile opts filePrefix raw_gTh ln i = do
let Result ds mTh = createIsaTheory raw_gTh
addThn = (++ '_' : iriToStringShortUnsecure i)
fp = addThn filePrefix
showDiags opts ds
case mTh of
Nothing ->
putIfVerbose opts 0 $ "could not translate to Isabelle theory: " ++ fp
Just (sign, sens) -> do
let tn = addThn . reverse . takeWhile (/= '/') . reverse $ case
libToFileName ln of
[] -> filePrefix
lstr -> lstr
sf = shows (printIsaTheory tn sign sens) "\n"
f = fp ++ ".thy"
case parse parseTheory f sf of
Left err -> putIfVerbose opts 0 $ show err
_ -> putIfVerbose opts 3 $ "reparsed: " ++ f
writeVerbFile opts f sf
when (hasPrfOut opts && verbose opts >= 3) $ let
(axs, rest) = partition ( \ s -> isAxiom s || isDef s) sens
in mapM_ ( \ s -> let
tnf = tn ++ "_" ++ senAttr s
tf = fp ++ "_" ++ senAttr s ++ ".thy"
in writeVerbFile opts tf $ shows
(printIsaTheory tnf sign $ s : axs) "\n") rest
writeTheory :: [String] -> String -> HetcatsOpts -> FilePath -> GlobalAnnos
-> G_theory -> LibName -> IRI -> OutType -> IO ()
writeTheory ins nam opts filePrefix ga
raw_gTh@(G_theory lid _ (ExtSign sign0 _) _ sens0 _) ln i ot =
let fp = filePrefix ++ "_" ++ iriToStringShortUnsecure i
f = fp ++ "." ++ show ot
th = (sign0, toNamedList sens0)
lang = language_name lid
in case ot of
FreeCADOut -> writeFreeCADFile opts filePrefix raw_gTh
ThyFile -> writeIsaFile opts filePrefix raw_gTh ln i
DfgFile c -> writeSoftFOL opts f raw_gTh i c 0 "DFG"
TPTPFile c -> writeSoftFOL opts f raw_gTh i c 1 "TPTP"
TheoryFile d -> do
if null $ show d then
writeVerbFile opts f $ shows (DG.printTh ga i raw_gTh) "\n"
else putIfVerbose opts 0 "printing theory delta is not implemented"
when (lang == language_name VSE) $ do
(sign, sens) <- coerceBasicTheory lid VSE "" th
let (sign', sens') = addUniformRestr sign sens
lse = map (namedSenToSExpr sign') sens'
unless (null lse) $ writeVerbFile opts (fp ++ ".sexpr")
$ shows (prettySExpr $ SList lse) "\n"
SigFile d -> do
if null $ show d then
writeVerbFile opts f $ shows (pretty $ signOf raw_gTh) "\n"
else putIfVerbose opts 0 "printing signature delta is not implemented"
when (lang == language_name VSE) $ do
(sign, sens) <- coerceBasicTheory lid VSE "" th
let (sign', _sens') = addUniformRestr sign sens
writeVerbFile opts (f ++ ".sexpr")
$ shows (prettySExpr $ vseSignToSExpr sign') "\n"
SymXml -> writeVerbFile opts f $ ppTopElement
$ ToXml.showSymbolsTh ins nam ga raw_gTh
#ifdef PROGRAMATICA
HaskellOut -> case printModule raw_gTh of
Nothing ->
putIfVerbose opts 0 $ "could not translate to Haskell file: " ++ f
Just d -> writeVerbFile opts f $ shows d "\n"
#endif
ComptableXml -> if lang == language_name CASL then do
th2 <- coerceBasicTheory lid CASL "" th
let Result ds res = computeCompTable i th2
showDiags opts ds
case res of
Just td -> writeVerbFile opts f $ tableXmlStr td
Nothing -> return ()
else putIfVerbose opts 0 $ "expected CASL theory for: " ++ f
#ifndef NOOWLLOGIC
OWLOut -> case createOWLTheory raw_gTh of
Result _ Nothing ->
putIfVerbose opts 0 $ "expected OWL theory for: " ++ f
Result ds (Just th2) -> do
let sy = defSyntax opts
ms = if null sy then Nothing
else Just $ simpleIdToIRI $ mkSimpleId sy
owltext = shows
(printTheory ms OWL2 $ OWL2.prepareBasicTheory th2) "\n"
showDiags opts ds
when (null sy)
$ case parse (OWL2.basicSpec Map.empty >> eof) f owltext of
Left err -> putIfVerbose opts 0 $ show err
_ -> putIfVerbose opts 3 $ "reparsed: " ++ f
writeVerbFile opts f owltext
#endif
#ifdef RDFLOGIC
RDFOut
| lang == language_name RDF -> do
th2 <- coerceBasicTheory lid RDF "" th
let rdftext = shows (RDF.printRDFBasicTheory th2) "\n"
writeVerbFile opts f rdftext
| otherwise -> putIfVerbose opts 0 $ "expected RDF theory for: " ++ f
#endif
CLIFOut
| lang == language_name CommonLogic -> do
(_, th2) <- coerceBasicTheory lid CommonLogic "" th
let cltext = shows (CL_AS.exportCLIF th2) "\n"
case parse (many (CL_Parse.cltext Map.empty) >> eof) f cltext of
Left err -> putIfVerbose opts 0 $ show err
_ -> putIfVerbose opts 3 $ "reparsed: " ++ f
writeVerbFile opts f cltext
| otherwise -> putIfVerbose opts 0 $ "expected Common Logic theory for: "
++ f
KIFOut
| lang == language_name CommonLogic -> do
(_, th2) <- coerceBasicTheory lid CommonLogic "" th
let kiftext = shows (Print_KIF.exportKIF th2) "\n"
writeVerbFile opts f kiftext
| otherwise -> putIfVerbose opts 0 $ "expected Common Logic theory for: "
++ f
_ -> return () -- ignore other file types
modelSparQCheck :: HetcatsOpts -> G_theory -> IO ()
modelSparQCheck opts gTh@(G_theory lid _ (ExtSign sign0 _) _ sens0 _) =
case coerceBasicTheory lid CASL "" (sign0, toNamedList sens0) of
Just th2 -> do
table <- parseSparQTableFromFile $ modelSparQ opts
case table of
Left err -> putIfVerbose opts 0
$ "could not parse SparQTable from file: " ++ modelSparQ opts
++ "\n" ++ show err
Right y -> do
putIfVerbose opts 4 $ unlines
["lisp file content:", show $ table2Doc y, "lisp file end."]
let Result d _ = modelCheck (counterSparQ opts) th2 y
if null d then
putIfVerbose opts 0 "Modelcheck succeeded, no errors found"
else showDiags
(if verbose opts >= 2 then opts else opts {verbose = 2}) d
_ ->
putIfVerbose opts 0 $ "could not translate Theory to CASL:\n "
++ showDoc gTh ""
writeTheoryFiles :: HetcatsOpts -> [OutType] -> FilePath -> LibEnv
-> GlobalAnnos -> LibName -> IRI -> Int -> IO ()
writeTheoryFiles opts specOutTypes filePrefix lenv ga ln i n =
let dg = lookupDGraph ln lenv
nam = getDGNodeName $ labDG dg n
ins = getImportNames dg n
in case globalNodeTheory dg n of
Nothing -> putIfVerbose opts 0 $ "could not compute theory of spec "
++ show i
Just raw_gTh0 -> do
let tr = transNames opts
Result es mTh = if null tr then return (raw_gTh0, "") else do
comor <- lookupCompComorphism (map tokStr tr) logicGraph
tTh <- mapG_theory comor raw_gTh0
return (tTh, "Translated using comorphism " ++ show comor)
(raw_gTh, tStr) =
fromMaybe (raw_gTh0, "Keeping untranslated theory") mTh
showDiags opts $ map (updDiagKind
(\ k -> if k == Error then Warning else k)) es
unless (null tStr) $ putIfVerbose opts 2 tStr
putIfVerbose opts 4 $ "Sublogic of " ++ show i ++ ": " ++
show (sublogicOfTh raw_gTh)
unless (modelSparQ opts == "") $
modelSparQCheck opts (theoremsToAxioms raw_gTh)
mapM_ (writeTheory ins nam opts filePrefix ga raw_gTh ln i)
specOutTypes
writeSpecFiles :: HetcatsOpts -> FilePath -> LibEnv -> LibName -> DGraph
-> IO ()
writeSpecFiles opts file lenv ln dg = do
let gctx = globalEnv dg
gns = Map.keys gctx
mns = map $ \ t -> Map.findWithDefault (simpleIdToIRI t) (tokStr t)
$ Map.fromList $ map (\ i -> (iriToStringShortUnsecure i, i)) gns
ga = globalAnnos dg
ns = mns $ specNames opts
vs = mns $ viewNames opts
filePrefix = snd $ getFilePrefix opts file
outTypes = outtypes opts
specOutTypes = filter ( \ ot -> case ot of
ThyFile -> True
DfgFile _ -> True
TPTPFile _ -> True
XmlOut -> True
OmdocOut -> True
TheoryFile _ -> True
SigFile _ -> True
OWLOut -> True
CLIFOut -> True
KIFOut -> True
FreeCADOut -> True
HaskellOut -> True
ComptableXml -> True
SymXml -> True
_ -> False) outTypes
allSpecs = null ns
noViews = null vs
ignore = null specOutTypes && modelSparQ opts == ""
mapM_ (writeLibEnv opts filePrefix lenv ln) $
if null $ dumpOpts opts then outTypes else EnvOut : outTypes
mapM_ ( \ i -> case Map.lookup i gctx of
Just (SpecEntry (ExtGenSig _ (NodeSig n _))) ->
writeTheoryFiles opts specOutTypes filePrefix lenv ga ln i n
_ -> unless allSpecs
$ putIfVerbose opts 0 $ "Unknown spec name: " ++ show i
) $ if ignore then [] else
if allSpecs then gns else ns
unless noViews $
mapM_ ( \ i -> case Map.lookup i gctx of
Just (ViewOrStructEntry _ (ExtViewSig _ (GMorphism cid _ _ m _) _)) ->
writeVerbFile opts (filePrefix ++ "_" ++ show i ++ ".view")
$ shows (pretty $ Map.toList $ symmap_of (targetLogic cid) m) "\n"
_ -> putIfVerbose opts 0 $ "Unknown view name: " ++ show i
) vs
mapM_ ( \ n ->
writeTheoryFiles opts specOutTypes filePrefix lenv ga ln
(simpleIdToIRI $ genToken $ 'n' : show n) n)
$ if ignore || not allSpecs then [] else
nodesDG dg
\\ Map.fold ( \ e l -> case e of
SpecEntry (ExtGenSig _ (NodeSig n _)) -> n : l
_ -> l) [] gctx
doDump opts "GlobalAnnos" $ putStrLn $ showGlobalDoc ga ga ""
doDump opts "PrintStat" $ putStrLn $ printStatistics dg
doDump opts "DGraph" $ putStrLn $ showDoc dg ""
doDump opts "DuplicateDefEdges" $ let es = duplicateDefEdges dg in
unless (null es) $ print es
doDump opts "LibEnv" $ writeVerbFile opts (filePrefix ++ ".lenv")
$ shows (DG.prettyLibEnv lenv) "\n"
writeLG :: HetcatsOpts -> IO ()
writeLG opts = do
doDump opts "LogicGraph" $ putStrLn $ showDoc logicGraph ""
writeVerbFile opts { verbose = 2 } "LogicGraph.xml" $ ppTopElement
$ lGToXml logicGraph
| nevrenato/HetsAlloy | Driver/WriteFn.hs | gpl-2.0 | 16,131 | 0 | 25 | 4,842 | 4,832 | 2,380 | 2,452 | 335 | 22 |
module Main where
import Test.Framework (defaultMain)
main :: IO ()
main = defaultMain Data.KDTree.Test.tests
| kaoskorobase/mescaline | lib/mescaline-patterns/runtests.hs | gpl-3.0 | 113 | 0 | 6 | 17 | 36 | 21 | 15 | 4 | 1 |
module Eksamen2012 where
import Data.List
import Data.Char
{-Programmer en Haskell funksjon posteval::String->[String]->Int (helst uten noen hjelpefunksjoner)
som evaluerer slike postfiks uttrykk, gitt som streng i første argumentet, ved ˚a
bruke stabel [String] som forklart over. Funksjonen kalles initielt med tom stabel og returnerer
tallet som ligger p˚a toppen av stabelen ved avsluttet evaluering, f.eks.,
(a) posteval "11 2 3 * + 4 -" [] skal gi 13, mens
(b) posteval "4 11 2 3 * + -" [] skal gi -13.-}
posteval :: String -> [String] -> Int
posteval (x:xs) stc = case x of
' ' -> posteval xs stc
'*' -> read (head stc) * read (stc!!1)
_ -> posteval rest (takers : stc)
where
(takers, rest) = span isDigit (x : xs)
| RakNoel/INF122 | src/Eksamen2012.hs | gpl-3.0 | 752 | 0 | 11 | 152 | 136 | 72 | 64 | 9 | 3 |
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Copyright : (c) 2010, 2011 Benedikt Schmidt
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Benedikt Schmidt <[email protected]>
--
-- Pretty printing and parsing of Maude terms and replies.
module Term.Maude.Parser (
-- * pretty printing of terms for Maude
ppMaude
, ppTheory
-- * parsing of Maude replies
, parseUnifyReply
, parseMatchReply
, parseReduceReply
) where
import Term.LTerm
import Term.Maude.Types
import Term.Maude.Signature
import Term.Rewriting.Definitions
import Control.Monad.Bind
import Control.Basics
import qualified Data.Set as S
import qualified Data.ByteString as B
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
import Data.Attoparsec.ByteString.Char8
-- import Extension.Data.Monoid
------------------------------------------------------------------------------
-- Pretty printing of Maude terms.
------------------------------------------------------------------------
-- | Pretty print an 'LSort'.
ppLSort :: LSort -> ByteString
ppLSort s = case s of
LSortPub -> "Pub"
LSortFresh -> "Fresh"
LSortMsg -> "Msg"
LSortNode -> "Node"
ppLSortSym :: LSort -> ByteString
ppLSortSym lsort = case lsort of
LSortFresh -> "f"
LSortPub -> "p"
LSortMsg -> "c"
LSortNode -> "n"
parseLSortSym :: ByteString -> Maybe LSort
parseLSortSym s = case s of
"f" -> Just LSortFresh
"p" -> Just LSortPub
"c" -> Just LSortMsg
"n" -> Just LSortNode
_ -> Nothing
-- | Used to prevent clashes with predefined Maude function symbols
-- like @true@
funSymPrefix :: ByteString
funSymPrefix = "tamX"
-- | Prefix for private function symbols.
funSymPrefixPriv :: ByteString
funSymPrefixPriv = "tamP"
-- | Replace underscores "_" with minus "-" for Maude.
replaceUnderscore :: ByteString -> ByteString
replaceUnderscore s = BC.map f s
where
f x | x == '_' = '-'
f x | otherwise = x
-- | Replace underscores "_" with minus "-" for Maude.
replaceUnderscoreFun :: NoEqSym -> NoEqSym
replaceUnderscoreFun (s, p) = (replaceUnderscore s, p)
-- | Replace minus "-" with underscores "_" when parsing back from Maude.
replaceMinus :: ByteString -> ByteString
replaceMinus s = BC.map f s
where
f x | x == '-' = '_'
f x | otherwise = x
-- | Replace minus "-" with underscores "_" when parsing back from Maude.
replaceMinusFun :: NoEqSym -> NoEqSym
replaceMinusFun (s, p) = (replaceMinus s, p)
-- | Pretty print an AC symbol for Maude.
ppMaudeACSym :: ACSym -> ByteString
ppMaudeACSym o =
funSymPrefix <> case o of
Mult -> "mult"
Union -> "mun"
Xor -> "xor"
-- | Pretty print a non-AC symbol for Maude.
ppMaudeNoEqSym :: NoEqSym -> ByteString
ppMaudeNoEqSym (o,(_,Private)) = funSymPrefixPriv <> replaceUnderscore o
ppMaudeNoEqSym (o,(_,Public)) = funSymPrefix <> replaceUnderscore o
-- | Pretty print a C symbol for Maude.
ppMaudeCSym :: CSym -> ByteString
ppMaudeCSym EMap = funSymPrefix <> emapSymString
-- | @ppMaude t@ pretty prints the term @t@ for Maude.
ppMaude :: Term MaudeLit -> ByteString
ppMaude t = case viewTerm t of
Lit (MaudeVar i lsort) -> "x" <> ppInt i <> ":" <> ppLSort lsort
Lit (MaudeConst i lsort) -> ppLSortSym lsort <> "(" <> ppInt i <> ")"
Lit (FreshVar _ _) -> error "Term.Maude.Types.ppMaude: FreshVar not allowed"
FApp (NoEq fsym) [] -> ppMaudeNoEqSym fsym
FApp (NoEq fsym) as -> ppMaudeNoEqSym fsym <> ppArgs as
FApp (C fsym) as -> ppMaudeCSym fsym <> ppArgs as
FApp (AC op) as -> ppMaudeACSym op <> ppArgs as
FApp List as -> "list(" <> ppList as <> ")"
where
ppArgs as = "(" <> (B.intercalate "," (map ppMaude as)) <> ")"
ppInt = BC.pack . show
ppList [] = "nil"
ppList (x:xs) = "cons(" <> ppMaude x <> "," <> ppList xs <> ")"
------------------------------------------------------------------------------
-- Pretty printing a 'MaudeSig' as a Maude functional module.
------------------------------------------------------------------------------
-- | The term algebra and rewriting rules as a functional module in Maude.
ppTheory :: MaudeSig -> ByteString
ppTheory msig = BC.unlines $
[ "fmod MSG is"
, " protecting NAT ."
, " sort Pub Fresh Msg Node TOP ."
, " subsort Pub < Msg ."
, " subsort Fresh < Msg ."
, " subsort Msg < TOP ."
, " subsort Node < TOP ."
-- constants
, " op f : Nat -> Fresh ."
, " op p : Nat -> Pub ."
, " op c : Nat -> Msg ."
, " op n : Nat -> Node ."
-- used for encoding FApp List [t1,..,tk]
-- list(cons(t1,cons(t2,..,cons(tk,nil)..)))
, " op list : TOP -> TOP ."
, " op cons : TOP TOP -> TOP ."
, " op nil : -> TOP ." ]
++
(if enableMSet msig
then
[ theoryOp "mun : Msg Msg -> Msg [comm assoc]" ]
else [])
++
(if enableDH msig
then
[ theoryOp "one : -> Msg"
, theoryOp "exp : Msg Msg -> Msg"
, theoryOp "mult : Msg Msg -> Msg [comm assoc]"
, theoryOp "inv : Msg -> Msg" ]
else [])
++
(if enableBP msig
then
[ theoryOp "pmult : Msg Msg -> Msg"
, theoryOp "em : Msg Msg -> Msg [comm]" ]
else [])
++
(if enableXor msig
then
[ theoryOp "zero : -> Msg"
, theoryOp "xor : Msg Msg -> Msg [comm assoc]" ]
else [])
++
map theoryFunSym (S.toList $ stFunSyms msig)
++
map theoryRule (S.toList $ rrulesForMaudeSig msig)
++
[ "endfm" ]
where
theoryOpNoEq priv fsort =
" op " <> (if (priv==Private) then funSymPrefixPriv else funSymPrefix) <> fsort <>" ."
theoryOp = theoryOpNoEq Public
theoryFunSym (s,(ar,priv)) =
theoryOpNoEq priv (replaceUnderscore s <> " : " <> (B.concat $ replicate ar "Msg ") <> " -> Msg")
theoryRule (l `RRule` r) =
" eq " <> ppMaude lm <> " = " <> ppMaude rm <> " ."
where (lm,rm) = evalBindT ((,) <$> lTermToMTerm' l <*> lTermToMTerm' r) noBindings
`evalFresh` nothingUsed
-- Parser for Maude output
------------------------------------------------------------------------
-- | @parseUnifyReply reply@ takes a @reply@ to a unification query
-- returned by Maude and extracts the unifiers.
parseUnifyReply :: MaudeSig -> ByteString -> Either String [MSubst]
parseUnifyReply msig reply = flip parseOnly reply $
choice [ string "No unifier." *> endOfLine *> pure []
, many1 (parseSubstitution msig) ]
<* endOfInput
-- | @parseMatchReply reply@ takes a @reply@ to a match query
-- returned by Maude and extracts the unifiers.
parseMatchReply :: MaudeSig -> ByteString -> Either String [MSubst]
parseMatchReply msig reply = flip parseOnly reply $
choice [ string "No match." *> endOfLine *> pure []
, many1 (parseSubstitution msig) ]
<* endOfInput
-- | @parseSubstitution l@ parses a single substitution returned by Maude.
parseSubstitution :: MaudeSig -> Parser MSubst
parseSubstitution msig = do
endOfLine *> string "Solution " *> takeWhile1 isDigit *> endOfLine
choice [ string "empty substitution" *> endOfLine *> pure []
, many1 parseEntry]
where
parseEntry = (,) <$> (flip (,) <$> (string "x" *> decimal <* string ":") <*> parseSort)
<*> (string " --> " *> parseTerm msig <* endOfLine)
-- | @parseReduceReply l@ parses a single solution returned by Maude.
parseReduceReply :: MaudeSig -> ByteString -> Either String MTerm
parseReduceReply msig reply = flip parseOnly reply $ do
string "result " *> choice [ string "TOP" *> pure LSortMsg, parseSort ] -- we ignore the sort
*> string ": " *> parseTerm msig <* endOfLine <* endOfInput
-- | Parse an 'MSort'.
parseSort :: Parser LSort
parseSort = string "Pub" *> return LSortPub
<|> string "Fresh" *> return LSortFresh
<|> string "Node" *> return LSortNode
<|> string "M" *> -- FIXME: why?
( string "sg" *> return LSortMsg )
-- | @parseTerm@ is a parser for Maude terms.
parseTerm :: MaudeSig -> Parser MTerm
parseTerm msig = choice
[ string "#" *> (lit <$> (FreshVar <$> (decimal <* string ":") <*> parseSort))
, do ident <- takeWhile1 (`BC.notElem` (":(,)\n " :: B.ByteString))
choice [ do _ <- string "("
case parseLSortSym ident of
Just s -> parseConst s
Nothing -> parseFApp ident
, string ":" *> parseMaudeVariable ident
, parseFAppConst ident
]
]
where
consSym = ("cons",(2,Public))
nilSym = ("nil",(0,Public))
parseFunSym ident args
| op `elem` allowedfunSyms = replaceMinusFun op
| otherwise =
error $ "Maude.Parser.parseTerm: unknown function "
++ "symbol `"++ show op ++"', not in "
++ show allowedfunSyms
where prefixLen = BC.length funSymPrefix
special = ident `elem` ["list", "cons", "nil" ]
priv = if (not special) && BC.isPrefixOf funSymPrefixPriv ident
then Private else Public
op = (if special then ident else BC.drop prefixLen ident
, ( length args, priv))
allowedfunSyms = [consSym, nilSym]
++ (map replaceUnderscoreFun $ S.toList $ noEqFunSyms msig)
parseConst s = lit <$> (flip MaudeConst s <$> decimal) <* string ")"
parseFApp ident =
appIdent <$> sepBy1 (parseTerm msig) (string ", ") <* string ")"
where
appIdent args | ident == ppMaudeACSym Mult = fAppAC Mult args
| ident == ppMaudeACSym Union = fAppAC Union args
| ident == ppMaudeACSym Xor = fAppAC Xor args
| ident == ppMaudeCSym EMap = fAppC EMap args
appIdent [arg] | ident == "list" = fAppList (flattenCons arg)
appIdent args = fAppNoEq op args
where op = parseFunSym ident args
flattenCons (viewTerm -> FApp (NoEq s) [x,xs]) | s == consSym = x:flattenCons xs
flattenCons (viewTerm -> FApp (NoEq s) []) | s == nilSym = []
flattenCons t = [t]
parseFAppConst ident = return $ fAppNoEq (parseFunSym ident []) []
parseMaudeVariable ident =
case BC.uncons ident of
Just ('x', num) -> lit <$> (MaudeVar (read (BC.unpack num)) <$> parseSort)
_ -> fail "invalid variable"
| rsasse/tamarin-prover | lib/term/src/Term/Maude/Parser.hs | gpl-3.0 | 10,870 | 0 | 18 | 3,146 | 2,661 | 1,369 | 1,292 | 202 | 9 |
module Problem003 (answer) where
import Primes (factorize)
answer :: Int
answer = maximum $ factorize 600851475143
| geekingfrog/project-euler | Problem003.hs | gpl-3.0 | 117 | 0 | 6 | 18 | 34 | 20 | 14 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module FuncTorrent.PeerThreadMain
( peerThreadMain
) where
import Prelude hiding (readFile)
import Control.Concurrent
import Control.Monad hiding (
forM , forM_ , mapM , mapM_ , msum , sequence , sequence_ )
import Control.Lens
import Data.IORef
import FuncTorrent.PeerThreadData
-- Sequence of events in the life of a peer thread
-- 1. Initiate hand-shake and set bit field?
-- 2. Send peer our status (choked/interested)
-- 3. Wait for peer status.
-- 4. If the peer is interested, then do further communication.
-- Else show that we are interested and wait.
-- 5. Send the 'have' message.
-- 6. Recieve the 'have' message.
-- 7. Report the peer status to the main thread.
-- 8. If needed initiate request or seed.
peerThreadMain :: PeerThread -> IO ()
peerThreadMain pt = do
toDoAction <- getAction
case toDoAction of
InitPeerConnection -> do
response <- doHandShake pt
if not response
then setStatus PeerCommError
else setStatus InitDone
GetPeerStatus ->
setStatus PeerReady
GetPieces _ -> do
startDownload pt
setStatus Downloading
Seed ->
setStatus Seeding
StayIdle ->
setStatus PeerReady
Stop -> stopDownload pt
unless (toDoAction == Stop) $ peerThreadMain pt
where setStatus = putMVar (pt^.peerTStatus)
getAction = takeMVar (pt^.peerTAction)
-- Fork a thread to get pieces from the peer.
-- The incoming requests from this peer will be handled
-- By IncomingConnThread.
--
startDownload :: PeerThread -> IO ()
startDownload pt = do
tid <- forkIO $ downloadData pt
writeIORef (pt^.downloadThread) (Just tid)
stopDownload :: PeerThread -> IO ()
stopDownload pt = putStrLn $ "Stopping peer-thread " ++ show (pt^.peer)
-- This will do the actual data communication with peer
downloadData :: PeerThread -> IO ()
downloadData _ = undefined
-- Hand-Shake details
-- 1. Verify the Info Hash recieved from the peer.
-- 2. Client connections start out as "choked" and "not interested". In other words:
--
-- am_choking = 1
-- am_interested = 0
-- peer_choking = 1
-- peer_interested = 0
-- 3. Send bit-field message
doHandShake :: PeerThread -> IO Bool
doHandShake pt = do
putStrLn $ "HandShake with " ++ show (pt^.peer)
return True
-- timeout (10*1000*1000) handShake
| dfordivam/functorrent | src/FuncTorrent/PeerThreadMain.hs | gpl-3.0 | 2,358 | 0 | 13 | 505 | 442 | 233 | 209 | 44 | 7 |
{- ============================================================================
| Copyright 2010 Matthew D. Steele <[email protected]> |
| |
| This file is part of Pylos. |
| |
| Pylos is free software: you can redistribute it and/or modify it |
| under the terms of the GNU General Public License as published by the Free |
| Software Foundation, either version 3 of the License, or (at your option) |
| any later version. |
| |
| Pylos is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY |
| or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
| for more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with Pylos. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Pylos.Data.TotalMap
(TotalMap, makeTotalMap, makeTotalMap_, tmGet, tmSet)
where
import Control.Applicative (Applicative(pure, (<*>)))
import Control.Arrow ((***))
import Control.Exception (assert)
import Data.Array ((!), (//), Array, listArray)
import qualified Data.Foldable as Fold
import qualified Data.Traversable as Trav
-------------------------------------------------------------------------------
-- | A 'TotalMap' is a key-value map whose key space is a finite set --
-- specifically, a type that is an instance of the 'Enum' and 'Bounded'
-- classes. The abstraction guarantees that a value will always be present
-- in the 'TotalMap' for every element of the key space, and that lookup is
-- constant-time.
newtype TotalMap a b = TotalMap (Array Int b)
deriving (Eq, Ord, Show)
instance Functor (TotalMap a) where
fmap fn (TotalMap arr) = TotalMap (fmap fn arr)
instance (Bounded a, Enum a) => Applicative (TotalMap a) where
pure = makeTotalMap_
(TotalMap arr1) <*> (TotalMap arr2) =
let apply ix = (arr1 ! ix) (arr2 ! ix)
create rng = map apply $ uncurry enumFromTo rng
in makeTotalMap' create
instance Fold.Foldable (TotalMap a) where
foldr fn start (TotalMap arr) = Fold.foldr fn start arr
instance Trav.Traversable (TotalMap a) where
traverse fn (TotalMap arr) = fmap TotalMap $ Trav.traverse fn arr
-- | Create a new 'TotalMap' with each item initialized by applying the
-- function to the corresponding key. This function is strict in the return
-- values of the function passed (to ensure that 'tmGet' never evaluates to
-- bottom).
makeTotalMap :: (Bounded a, Enum a) => (a -> b) -> TotalMap a b
makeTotalMap fn = makeTotalMap' create
where create rng = map (force . fn) $ uncurry enumFromTo $
(toEnum *** toEnum) rng
force x = x `seq` x
-- | Create a new 'TotalMap' with all items set to the initial value.
-- Equivalent to @'makeTotalMap' . const@. This function is strict in the
-- value passed (to ensure that 'tmGet' never evaluates to bottom).
makeTotalMap_ :: (Bounded a, Enum a) => b -> TotalMap a b
makeTotalMap_ value = value `seq` (makeTotalMap' $ const $ repeat value)
-- | Get an item from a 'TotalMap'. Assuming that the key type is
-- well-behaved, this function will never fail or return bottom.
tmGet :: (Bounded a, Enum a) => a -> TotalMap a b -> b
tmGet key (TotalMap arr) = assert (inRange key) $ arr ! fromEnum key
-- | Set an item in a 'TotalMap'. Assuming that the key type is well-behaved,
-- this function will never fail or return bottom.
tmSet :: (Bounded a, Enum a) => b -> a -> TotalMap a b -> TotalMap a b
tmSet value key (TotalMap arr) =
assert (inRange key) $ TotalMap $ arr // [(fromEnum key, value)]
-------------------------------------------------------------------------------
-- Private utility functions:
inRange :: (Bounded a, Enum a) => a -> Bool
inRange key =
let getBounds :: (Bounded a) => a -> (a, a)
getBounds _ = (minBound, maxBound)
ix = fromEnum key
in uncurry (&&) $ (((ix >=) . fromEnum) *** ((ix <=) . fromEnum)) $
getBounds key
makeTotalMap' :: (Bounded a, Enum a) => ((Int, Int) -> [b]) -> TotalMap a b
makeTotalMap' fn =
let getBounds :: (Bounded a) => TotalMap a b -> (a, a)
getBounds _ = (minBound, maxBound)
rng = (fromEnum *** fromEnum) (getBounds tm)
tm = TotalMap $ listArray rng $ fn rng
in tm
-------------------------------------------------------------------------------
| mdsteele/pylos | src/Pylos/Data/TotalMap.hs | gpl-3.0 | 4,952 | 0 | 13 | 1,388 | 990 | 537 | 453 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Algebra.Morphism.Ratio where
import Algebra.Classes
import Prelude (Ord(..), Eq(..),Integer,Show(..), error, otherwise, (.), Int, ($))
import Text.Show (showParen, showString)
import qualified Data.Ratio
------------------------------------------------------------------------
-- Divide by zero and arithmetic overflow
------------------------------------------------------------------------
-- We put them here because they are needed relatively early
-- in the libraries before the Exception type has been defined yet.
{-# NOINLINE divZeroError #-}
divZeroError :: a
divZeroError = error "division by zero"
{-# NOINLINE ratioZeroDenominatorError #-}
ratioZeroDenominatorError :: a
ratioZeroDenominatorError = error "ratioZeroDenomException"
{-# NOINLINE overflowError #-}
overflowError :: a
overflowError = error "overflowException"
{-# NOINLINE underflowError #-}
underflowError :: a
underflowError = error "underflowException"
data Ratio a = !a :% !a deriving Eq -- ^ @since 2.01
type Rational = Ratio Integer
--------------------------------------------------------------
-- Instances for @Ratio@
--------------------------------------------------------------
-- | @since 2.0.1
instance (Integral a) => Ord (Ratio a) where
{-# SPECIALIZE instance Ord Rational #-}
(x:%y) <= (x':%y') = x * y' <= x' * y
(x:%y) < (x':%y') = x * y' < x' * y
-- | @since 2.0.1
instance EuclideanDomain a => Additive (Ratio a) where
zero = zero :% one
(x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
instance EuclideanDomain a => Multiplicative (Ratio a) where
one = one :% one
(x:%y) * (x':%y') = reduce (x * x') (y * y')
instance EuclideanDomain a => Group (Ratio a) where
(x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y')
negate (x:%y) = (negate x) :% y
-- abs (x:%y) = abs x :% y
-- signum (x:%_) = signum x :% 1
-- fromInteger x = fromInteger x :% 1
instance EuclideanDomain a => AbelianAdditive (Ratio a)
instance EuclideanDomain a => Ring (Ratio a)
instance EuclideanDomain a => Scalable (Ratio a) (Ratio a) where
(*^) = (*)
-- | @since 2.0.1
instance (EuclideanDomain a) => Division (Ratio a) where
{-# SPECIALIZE instance Division Rational #-}
(x:%y) / (x':%y') = (x*y') % (y*x')
-- recip (x:%y)
-- | isZero x = ratioZeroDenominatorError
-- | x < 0 = negate y :% negate x
-- | otherwise = y :% x
instance EuclideanDomain a => Field (Ratio a) where
fromRational x = fromInteger (Data.Ratio.numerator x) % fromInteger (Data.Ratio.denominator x)
-- | @since 2.0.1
-- instance (Integral a) => Real (Ratio a) where
-- {-# SPECIALIZE instance Real Rational #-}
-- toRational (x:%y) = toInteger x :% toInteger y
-- -- | @since 2.0.1
-- instance (Integral a) => RealFrac (Ratio a) where
-- {-# SPECIALIZE instance RealFrac Rational #-}
-- properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
-- where (q,r) = quotRem x y
-- round r =
-- let
-- (n, f) = properFraction r
-- x = if r < 0 then -1 else 1
-- in
-- case (compare (abs f) 0.5, odd n) of
-- (LT, _) -> n
-- (EQ, False) -> n
-- (EQ, True) -> n + x
-- (GT, _) -> n + x
-- | @since 2.0.1
instance (Show a) => Show (Ratio a) where
{-# SPECIALIZE instance Show Rational #-}
showsPrec p (x:%y) = showParen (p > ratioPrec) $
showsPrec ratioPrec1 x .
showString " % " .
showsPrec ratioPrec1 y
-- | 'reduce' is a subsidiary function used only in this module.
-- It normalises a ratio by dividing both numerator and denominator by
-- their greatest common divisor.
reduce :: (EuclideanDomain a) => a -> a -> Ratio a
{-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}
reduce x y | isZero y = ratioZeroDenominatorError
| otherwise = (x `quot` d) :% (y `quot` d)
where d = gcd x y
(%) :: EuclideanDomain a => a -> a -> Ratio a
x % y = reduce (x * sign) a
where (a,sign) = normalize y
ratioPrec, ratioPrec1 :: Int
ratioPrec = 7 -- Precedence of ':%' constructor
ratioPrec1 = ratioPrec + 1
| jyp/gasp | Algebra/Morphism/Ratio.hs | gpl-3.0 | 4,315 | 0 | 11 | 1,079 | 1,009 | 558 | 451 | 63 | 1 |
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses, ConstraintKinds, FlexibleContexts, FlexibleInstances, DeriveGeneric #-}
module Algebra.Morphism.Exponential where
import Prelude (Show,Eq,Ord,Integer,Functor,Foldable)
import Data.Traversable
import Algebra.Classes
newtype Exp a = Exp a deriving (Show,Eq,Ord,Foldable,Traversable,Functor)
fromExp :: Exp a -> a
fromExp (Exp x) = x
instance Additive a => Multiplicative (Exp a) where
Exp a * Exp b = Exp (a + b)
one = Exp zero
Exp a ^+ n = Exp (times n a)
instance Group a => Division (Exp a) where
recip (Exp a) = Exp (negate a)
Exp a / Exp b = Exp (a - b)
instance Field a => Roots (Exp a) where
root n (Exp x) = Exp (x / fromInteger n)
newtype Log a = Log a deriving (Show,Eq,Ord)
fromLog :: Log a -> a
fromLog (Log x) = x
instance Multiplicative a => Additive (Log a) where
Log a + Log b = Log (a * b)
zero = Log one
times n (Log a) = Log (a ^+ n)
instance Multiplicative a => Scalable Integer (Log a) where
n *^ Log x = Log (x ^+ n)
instance Division a => Group (Log a) where
negate (Log a) = Log (recip a)
Log a - Log b = Log (a / b)
-- instance Roots a => Field (Log a) where
-- fromRational x = Log (root (denominator x) (fromInteger (numerator x)))
| jyp/gasp | Algebra/Morphism/Exponential.hs | gpl-3.0 | 1,431 | 0 | 9 | 289 | 563 | 283 | 280 | 35 | 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.AdSenseHost.Accounts.AdUnits.GetAdCode
-- 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)
--
-- Get ad code for the specified ad unit, attaching the specified host
-- custom channels.
--
-- /See:/ <https://developers.google.com/adsense/host/ AdSense Host API Reference> for @adsensehost.accounts.adunits.getAdCode@.
module Network.Google.Resource.AdSenseHost.Accounts.AdUnits.GetAdCode
(
-- * REST Resource
AccountsAdUnitsGetAdCodeResource
-- * Creating a Request
, accountsAdUnitsGetAdCode
, AccountsAdUnitsGetAdCode
-- * Request Lenses
, aaugacAdUnitId
, aaugacAdClientId
, aaugacAccountId
, aaugacHostCustomChannelId
) where
import Network.Google.AdSenseHost.Types
import Network.Google.Prelude
-- | A resource alias for @adsensehost.accounts.adunits.getAdCode@ method which the
-- 'AccountsAdUnitsGetAdCode' request conforms to.
type AccountsAdUnitsGetAdCodeResource =
"adsensehost" :>
"v4.1" :>
"accounts" :>
Capture "accountId" Text :>
"adclients" :>
Capture "adClientId" Text :>
"adunits" :>
Capture "adUnitId" Text :>
"adcode" :>
QueryParams "hostCustomChannelId" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] AdCode
-- | Get ad code for the specified ad unit, attaching the specified host
-- custom channels.
--
-- /See:/ 'accountsAdUnitsGetAdCode' smart constructor.
data AccountsAdUnitsGetAdCode = AccountsAdUnitsGetAdCode'
{ _aaugacAdUnitId :: !Text
, _aaugacAdClientId :: !Text
, _aaugacAccountId :: !Text
, _aaugacHostCustomChannelId :: !(Maybe [Text])
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AccountsAdUnitsGetAdCode' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aaugacAdUnitId'
--
-- * 'aaugacAdClientId'
--
-- * 'aaugacAccountId'
--
-- * 'aaugacHostCustomChannelId'
accountsAdUnitsGetAdCode
:: Text -- ^ 'aaugacAdUnitId'
-> Text -- ^ 'aaugacAdClientId'
-> Text -- ^ 'aaugacAccountId'
-> AccountsAdUnitsGetAdCode
accountsAdUnitsGetAdCode pAaugacAdUnitId_ pAaugacAdClientId_ pAaugacAccountId_ =
AccountsAdUnitsGetAdCode'
{ _aaugacAdUnitId = pAaugacAdUnitId_
, _aaugacAdClientId = pAaugacAdClientId_
, _aaugacAccountId = pAaugacAccountId_
, _aaugacHostCustomChannelId = Nothing
}
-- | Ad unit to get the code for.
aaugacAdUnitId :: Lens' AccountsAdUnitsGetAdCode Text
aaugacAdUnitId
= lens _aaugacAdUnitId
(\ s a -> s{_aaugacAdUnitId = a})
-- | Ad client with contains the ad unit.
aaugacAdClientId :: Lens' AccountsAdUnitsGetAdCode Text
aaugacAdClientId
= lens _aaugacAdClientId
(\ s a -> s{_aaugacAdClientId = a})
-- | Account which contains the ad client.
aaugacAccountId :: Lens' AccountsAdUnitsGetAdCode Text
aaugacAccountId
= lens _aaugacAccountId
(\ s a -> s{_aaugacAccountId = a})
-- | Host custom channel to attach to the ad code.
aaugacHostCustomChannelId :: Lens' AccountsAdUnitsGetAdCode [Text]
aaugacHostCustomChannelId
= lens _aaugacHostCustomChannelId
(\ s a -> s{_aaugacHostCustomChannelId = a})
. _Default
. _Coerce
instance GoogleRequest AccountsAdUnitsGetAdCode where
type Rs AccountsAdUnitsGetAdCode = AdCode
type Scopes AccountsAdUnitsGetAdCode =
'["https://www.googleapis.com/auth/adsensehost"]
requestClient AccountsAdUnitsGetAdCode'{..}
= go _aaugacAccountId _aaugacAdClientId
_aaugacAdUnitId
(_aaugacHostCustomChannelId ^. _Default)
(Just AltJSON)
adSenseHostService
where go
= buildClient
(Proxy :: Proxy AccountsAdUnitsGetAdCodeResource)
mempty
| rueshyna/gogol | gogol-adsense-host/gen/Network/Google/Resource/AdSenseHost/Accounts/AdUnits/GetAdCode.hs | mpl-2.0 | 4,651 | 0 | 18 | 1,085 | 562 | 333 | 229 | 92 | 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.DoubleClickBidManager.Reports.Listreports
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves stored reports.
--
-- /See:/ <https://developers.google.com/bid-manager/ DoubleClick Bid Manager API Reference> for @doubleclickbidmanager.reports.listreports@.
module Network.Google.Resource.DoubleClickBidManager.Reports.Listreports
(
-- * REST Resource
ReportsListreportsResource
-- * Creating a Request
, reportsListreports
, ReportsListreports
-- * Request Lenses
, rlQueryId
) where
import Network.Google.DoubleClickBids.Types
import Network.Google.Prelude
-- | A resource alias for @doubleclickbidmanager.reports.listreports@ method which the
-- 'ReportsListreports' request conforms to.
type ReportsListreportsResource =
"doubleclickbidmanager" :>
"v1" :>
"queries" :>
Capture "queryId" (Textual Int64) :>
"reports" :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListReportsResponse
-- | Retrieves stored reports.
--
-- /See:/ 'reportsListreports' smart constructor.
newtype ReportsListreports = ReportsListreports'
{ _rlQueryId :: Textual Int64
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ReportsListreports' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rlQueryId'
reportsListreports
:: Int64 -- ^ 'rlQueryId'
-> ReportsListreports
reportsListreports pRlQueryId_ =
ReportsListreports'
{ _rlQueryId = _Coerce # pRlQueryId_
}
-- | Query ID with which the reports are associated.
rlQueryId :: Lens' ReportsListreports Int64
rlQueryId
= lens _rlQueryId (\ s a -> s{_rlQueryId = a}) .
_Coerce
instance GoogleRequest ReportsListreports where
type Rs ReportsListreports = ListReportsResponse
type Scopes ReportsListreports = '[]
requestClient ReportsListreports'{..}
= go _rlQueryId (Just AltJSON) doubleClickBidsService
where go
= buildClient
(Proxy :: Proxy ReportsListreportsResource)
mempty
| rueshyna/gogol | gogol-doubleclick-bids/gen/Network/Google/Resource/DoubleClickBidManager/Reports/Listreports.hs | mpl-2.0 | 2,890 | 0 | 13 | 643 | 319 | 193 | 126 | 50 | 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.BigtableAdmin.Projects.Instances.PartialUpdateInstance
-- 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)
--
-- Partially updates an instance within a project. This method can modify
-- all fields of an Instance and is the preferred way to update an
-- Instance.
--
-- /See:/ <https://cloud.google.com/bigtable/ Cloud Bigtable Admin API Reference> for @bigtableadmin.projects.instances.partialUpdateInstance@.
module Network.Google.Resource.BigtableAdmin.Projects.Instances.PartialUpdateInstance
(
-- * REST Resource
ProjectsInstancesPartialUpdateInstanceResource
-- * Creating a Request
, projectsInstancesPartialUpdateInstance
, ProjectsInstancesPartialUpdateInstance
-- * Request Lenses
, pipuiXgafv
, pipuiUploadProtocol
, pipuiUpdateMask
, pipuiAccessToken
, pipuiUploadType
, pipuiPayload
, pipuiName
, pipuiCallback
) where
import Network.Google.BigtableAdmin.Types
import Network.Google.Prelude
-- | A resource alias for @bigtableadmin.projects.instances.partialUpdateInstance@ method which the
-- 'ProjectsInstancesPartialUpdateInstance' request conforms to.
type ProjectsInstancesPartialUpdateInstanceResource =
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "updateMask" GFieldMask :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Instance :> Patch '[JSON] Operation
-- | Partially updates an instance within a project. This method can modify
-- all fields of an Instance and is the preferred way to update an
-- Instance.
--
-- /See:/ 'projectsInstancesPartialUpdateInstance' smart constructor.
data ProjectsInstancesPartialUpdateInstance =
ProjectsInstancesPartialUpdateInstance'
{ _pipuiXgafv :: !(Maybe Xgafv)
, _pipuiUploadProtocol :: !(Maybe Text)
, _pipuiUpdateMask :: !(Maybe GFieldMask)
, _pipuiAccessToken :: !(Maybe Text)
, _pipuiUploadType :: !(Maybe Text)
, _pipuiPayload :: !Instance
, _pipuiName :: !Text
, _pipuiCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsInstancesPartialUpdateInstance' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pipuiXgafv'
--
-- * 'pipuiUploadProtocol'
--
-- * 'pipuiUpdateMask'
--
-- * 'pipuiAccessToken'
--
-- * 'pipuiUploadType'
--
-- * 'pipuiPayload'
--
-- * 'pipuiName'
--
-- * 'pipuiCallback'
projectsInstancesPartialUpdateInstance
:: Instance -- ^ 'pipuiPayload'
-> Text -- ^ 'pipuiName'
-> ProjectsInstancesPartialUpdateInstance
projectsInstancesPartialUpdateInstance pPipuiPayload_ pPipuiName_ =
ProjectsInstancesPartialUpdateInstance'
{ _pipuiXgafv = Nothing
, _pipuiUploadProtocol = Nothing
, _pipuiUpdateMask = Nothing
, _pipuiAccessToken = Nothing
, _pipuiUploadType = Nothing
, _pipuiPayload = pPipuiPayload_
, _pipuiName = pPipuiName_
, _pipuiCallback = Nothing
}
-- | V1 error format.
pipuiXgafv :: Lens' ProjectsInstancesPartialUpdateInstance (Maybe Xgafv)
pipuiXgafv
= lens _pipuiXgafv (\ s a -> s{_pipuiXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pipuiUploadProtocol :: Lens' ProjectsInstancesPartialUpdateInstance (Maybe Text)
pipuiUploadProtocol
= lens _pipuiUploadProtocol
(\ s a -> s{_pipuiUploadProtocol = a})
-- | Required. The subset of Instance fields which should be replaced. Must
-- be explicitly set.
pipuiUpdateMask :: Lens' ProjectsInstancesPartialUpdateInstance (Maybe GFieldMask)
pipuiUpdateMask
= lens _pipuiUpdateMask
(\ s a -> s{_pipuiUpdateMask = a})
-- | OAuth access token.
pipuiAccessToken :: Lens' ProjectsInstancesPartialUpdateInstance (Maybe Text)
pipuiAccessToken
= lens _pipuiAccessToken
(\ s a -> s{_pipuiAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pipuiUploadType :: Lens' ProjectsInstancesPartialUpdateInstance (Maybe Text)
pipuiUploadType
= lens _pipuiUploadType
(\ s a -> s{_pipuiUploadType = a})
-- | Multipart request metadata.
pipuiPayload :: Lens' ProjectsInstancesPartialUpdateInstance Instance
pipuiPayload
= lens _pipuiPayload (\ s a -> s{_pipuiPayload = a})
-- | The unique name of the instance. Values are of the form
-- \`projects\/{project}\/instances\/a-z+[a-z0-9]\`.
pipuiName :: Lens' ProjectsInstancesPartialUpdateInstance Text
pipuiName
= lens _pipuiName (\ s a -> s{_pipuiName = a})
-- | JSONP
pipuiCallback :: Lens' ProjectsInstancesPartialUpdateInstance (Maybe Text)
pipuiCallback
= lens _pipuiCallback
(\ s a -> s{_pipuiCallback = a})
instance GoogleRequest
ProjectsInstancesPartialUpdateInstance
where
type Rs ProjectsInstancesPartialUpdateInstance =
Operation
type Scopes ProjectsInstancesPartialUpdateInstance =
'["https://www.googleapis.com/auth/bigtable.admin",
"https://www.googleapis.com/auth/bigtable.admin.cluster",
"https://www.googleapis.com/auth/bigtable.admin.instance",
"https://www.googleapis.com/auth/cloud-bigtable.admin",
"https://www.googleapis.com/auth/cloud-bigtable.admin.cluster",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsInstancesPartialUpdateInstance'{..}
= go _pipuiName _pipuiXgafv _pipuiUploadProtocol
_pipuiUpdateMask
_pipuiAccessToken
_pipuiUploadType
_pipuiCallback
(Just AltJSON)
_pipuiPayload
bigtableAdminService
where go
= buildClient
(Proxy ::
Proxy ProjectsInstancesPartialUpdateInstanceResource)
mempty
| brendanhay/gogol | gogol-bigtableadmin/gen/Network/Google/Resource/BigtableAdmin/Projects/Instances/PartialUpdateInstance.hs | mpl-2.0 | 6,785 | 0 | 17 | 1,444 | 876 | 513 | 363 | 134 | 1 |
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------------------
-- See end of this file for licence information.
--------------------------------------------------------------------------------
-- |
-- Module : QName
-- Copyright : (c) 2003, Graham Klyne, 2009 Vasili I Galchin, 2011, 2012, 2013 Douglas Burke
-- License : GPL V2
--
-- Maintainer : Douglas Burke
-- Stability : experimental
-- Portability : OverloadedStrings
--
-- This module defines an algebraic datatype for qualified names (QNames),
-- which represents a 'URI' as the combination of a namespace 'URI'
-- and a local component ('LName'), which can be empty.
--
-- Although RDF supports using IRIs, the use of 'URI' here precludes this,
-- which means that, for instance, 'LName' only accepts a subset of valid
-- characters. There is currently no attempt to convert from an IRI into a URI.
--
--------------------------------------------------------------------------------
-- At present we support using URI references rather than forcing an absolute
-- URI. This is partly to support the existing tests (too lazy to resolve whether
-- the tests really should be using relative URIs in this case).
module Swish.QName
( QName
, LName
, emptyLName
, newLName
, getLName
, newQName
, qnameFromURI
, getNamespace
, getLocalName
, getQNameURI
, qnameFromFilePath
)
where
import Control.Monad (liftM)
import Data.Char (isAscii)
import Data.Maybe (fromMaybe)
import Data.Interned (intern, unintern)
import Data.Interned.URI (InternedURI)
import Data.Ord (comparing)
import Data.String (IsString(..))
import Network.URI (URI(..), URIAuth(..), parseURIReference)
import System.Directory (canonicalizePath)
import System.FilePath (splitFileName)
import qualified Data.Text as T
------------------------------------------------------------
-- Qualified name
------------------------------------------------------------
--
-- These are RDF QNames rather than XML ones (as much as
-- RDF can claim to have them).
--
{-| A local name, which can be empty.
At present, the local name can not contain a space character and can only
contain ascii characters (those that match 'Data.Char.isAscii').
In version @0.9.0.3@ and earlier, the following characters were not
allowed in local names: \'#\', \':\', or \'/\' characters.
This is all rather experimental.
-}
newtype LName = LName T.Text
deriving (Eq, Ord)
instance Show LName where
show (LName t) = show t
-- | This is not total since attempting to convert a string
-- containing invalid characters will cause an error.
instance IsString LName where
fromString s =
fromMaybe (error ("Invalid local name: " ++ s)) $
newLName (T.pack s)
-- | The empty local name.
emptyLName :: LName
emptyLName = LName ""
-- | Create a local name.
newLName :: T.Text -> Maybe LName
-- newLName l = if T.any (`elem` " #:/") l then Nothing else Just (LName l) -- 0.7.0.1 and earlier
-- newLName l = if T.any (\c -> c `elem` " #:/" || not (isAscii c)) l then Nothing else Just (LName l) -- 0.9.0.3 and earlier
newLName l = if T.any (\c -> c == ' ' || not (isAscii c)) l then Nothing else Just (LName l)
-- | Extract the local name.
getLName :: LName -> T.Text
getLName (LName l) = l
{-|
A qualified name, consisting of a namespace URI
and the local part of the identifier, which can be empty.
The serialisation of a QName is formed by concatanating the
two components.
> Prelude> :set prompt "swish> "
> swish> :set -XOverloadedStrings
> swish> :m + Swish.QName
> swish> let qn1 = "http://example.com/" :: QName
> swish> let qn2 = "http://example.com/bob" :: QName
> swish> let qn3 = "http://example.com/bob/fred" :: QName
> swish> let qn4 = "http://example.com/bob/fred#x" :: QName
> swish> let qn5 = "http://example.com/bob/fred:joe" :: QName
> swish> map getLocalName [qn1, qn2, qn3, qn4, qn5]
> ["","bob","fred","x","fred:joe"]
> swish> getNamespace qn1
> http://example.com/
> swish> getNamespace qn2
> http://example.com/
> swish> getNamespace qn3
> http://example.com/bob/
> swish> getNamespace qn4
> http://example.com/bob/fred#
-}
{-
For now I have added in storing the actual URI
as well as the namespace component. This may or
may not be a good idea (space vs time saving).
-}
data QName = QName !InternedURI URI LName
-- | This is not total since it will fail if the input string is not a valid URI.
instance IsString QName where
fromString s =
fromMaybe (error ("QName conversion given an invalid URI: " ++ s))
(parseURIReference s >>= qnameFromURI)
-- | Equality is determined by a case sensitive comparison of the
-- URI.
instance Eq QName where
u1 == u2 = getQNameURI u1 == getQNameURI u2
-- | In @0.8.0.0@ the ordering now uses the ordering defined in
-- "Network.URI.Ord" rather than the @Show@
-- instance. This should make no difference unless a password
-- was included in the URI when using basic access authorization.
--
instance Ord QName where
compare = comparing getQNameURI
-- | The format used to display the URI is @\<uri\>@, and does not
-- include the password if using basic access authorization.
instance Show QName where
show (QName u _ _) = "<" ++ show u ++ ">"
{-
The assumption in QName is that the validation done in creating
the local name is sufficient to ensure that the combined
URI is syntactically valid. Is this true?
-}
-- | Create a new qualified name with an explicit local component.
--
newQName ::
URI -- ^ Namespace
-> LName -- ^ Local component
-> QName
newQName ns l@(LName local) =
-- Until profiling shows that this is a time/space issue, we use
-- the following code rather than trying to deconstruct the URI
-- directly
let lstr = T.unpack local
uristr = show ns ++ lstr
in case parseURIReference uristr of
Just uri -> QName (intern uri) ns l
_ -> error $ "Unable to combine " ++ show ns ++ " with " ++ lstr
{-
old behavior
splitQname "http://example.org/aaa#bbb" = ("http://example.org/aaa#","bbb")
splitQname "http://example.org/aaa/bbb" = ("http://example.org/aaa/","bbb")
splitQname "http://example.org/aaa/" = ("http://example.org/aaa/","")
Should "urn:foo:bar" have a local name of "" or "foo:bar"? For now go
with the first option.
-}
-- | Create a new qualified name.
qnameFromURI ::
URI -- ^ The URI will be deconstructed to find if it contains a local component.
-> Maybe QName -- ^ The failure case may be removed.
qnameFromURI uri =
let uf = uriFragment uri
up = uriPath uri
q0 = Just $ start uri emptyLName
start = QName (intern uri)
in case uf of
"#" -> q0
'#':xs -> start (uri {uriFragment = "#"}) `liftM` newLName (T.pack xs)
"" -> case break (=='/') (reverse up) of
("",_) -> q0 -- path ends in / or is empty
(_,"") -> q0 -- path contains no /
(rlname,rpath) ->
start (uri {uriPath = reverse rpath}) `liftM`
newLName (T.pack (reverse rlname))
-- e -> error $ "Unexpected: uri=" ++ show uri ++ " has fragment='" ++ show e ++ "'"
_ -> Nothing
-- | Return the URI of the namespace stored in the QName.
-- This does not contain the local component.
--
getNamespace :: QName -> URI
getNamespace (QName _ ns _) = ns
-- | Return the local component of the QName.
getLocalName :: QName -> LName
getLocalName (QName _ _ l) = l
-- | Returns the full URI of the QName (ie the combination of the
-- namespace and local components).
getQNameURI :: QName -> URI
getQNameURI (QName u _ _) = unintern u
{-|
Convert a filepath to a file: URI stored in a QName. If the
input file path is relative then the current working directory is used
to convert it into an absolute path.
If the input represents a directory then it *must* end in
the directory separator - so for Posix systems use
@\"\/foo\/bar\/\"@ rather than
@\"\/foo\/bar\"@.
This has not been tested on Windows.
-}
{-
NOTE: not sure why I say directories should end in the path
seperator since
ghci> System.Directory.canonicalizePath "/Users/dburke/haskell/swish-text"
"/Users/dburke/haskell/swish-text"
ghci> System.Directory.canonicalizePath "/Users/dburke/haskell/swish-text/"
"/Users/dburke/haskell/swish-text"
-}
qnameFromFilePath :: FilePath -> IO QName
qnameFromFilePath fname = do
ipath <- canonicalizePath fname
let (dname, lname) = splitFileName ipath
nsuri = URI "file:" emptyAuth dname "" ""
uri = URI "file:" emptyAuth ipath "" ""
case lname of
"" -> return $ QName (intern nsuri) nsuri emptyLName
_ -> return $ QName (intern uri) nsuri (LName (T.pack lname))
emptyAuth :: Maybe URIAuth
emptyAuth = Just $ URIAuth "" "" ""
--------------------------------------------------------------------------------
--
-- Copyright (c) 2003, Graham Klyne, 2009 Vasili I Galchin,
-- 2011, 2012, 2013 Douglas Burke
-- All rights reserved.
--
-- This file is part of Swish.
--
-- Swish is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- Swish is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Swish; if not, write to:
-- The Free Software Foundation, Inc.,
-- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
--------------------------------------------------------------------------------
| DougBurke/swish | src/Swish/QName.hs | lgpl-2.1 | 9,947 | 0 | 18 | 2,047 | 1,210 | 679 | 531 | 96 | 6 |
module Network.Haskoin.Crypto.ExtendedKeys.Tests (tests) where
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Data.String (fromString)
import Data.String.Conversions (cs)
import Data.Word (Word32)
import Data.Bits ((.&.))
import Network.Haskoin.Test
import Network.Haskoin.Crypto
tests :: [Test]
tests =
[ testGroup "HDW Extended Keys"
[ testProperty "prvSubKey(k,c)*G = pubSubKey(k*G,c)" subkeyTest
, testProperty "fromB58 . toB58 prvKey" b58PrvKey
, testProperty "fromB58 . toB58 pubKey" b58PubKey
]
, testGroup "From/To strings"
[ testProperty "Read/Show extended public key" testReadShowPubKey
, testProperty "Read/Show extended private key" testReadShowPrvKey
, testProperty "Read/Show derivation path" testReadShowDerivPath
, testProperty "Read/Show hard derivation path" testReadShowAllHardPath
, testProperty "Read/Show soft derivation path" testReadShowSoftPath
, testProperty "From string extended public key" testFromStringPubKey
, testProperty "From string extended private key" testFromStringPrvKey
, testProperty "From string derivation path" testFromStringDerivPath
, testProperty "From string hard derivation path" testFromStringAllHardPath
, testProperty "From string soft derivation path" testFromStringSoftPath
]
]
{- HDW Extended Keys -}
subkeyTest :: ArbitraryXPrvKey -> Word32 -> Bool
subkeyTest (ArbitraryXPrvKey k) i =
(deriveXPubKey $ prvSubKey k i') == (pubSubKey (deriveXPubKey k) i')
where
i' = fromIntegral $ i .&. 0x7fffffff -- make it a public derivation
b58PrvKey :: ArbitraryXPrvKey -> Bool
b58PrvKey (ArbitraryXPrvKey k) = (xPrvImport $ xPrvExport k) == Just k
b58PubKey :: ArbitraryXPubKey -> Bool
b58PubKey (ArbitraryXPubKey _ k) = (xPubImport $ xPubExport k) == Just k
{- Strings -}
testReadShowPubKey :: ArbitraryXPubKey -> Bool
testReadShowPubKey (ArbitraryXPubKey _ k) = read (show k) == k
testReadShowPrvKey :: ArbitraryXPrvKey -> Bool
testReadShowPrvKey (ArbitraryXPrvKey k) = read (show k) == k
testFromStringPubKey :: ArbitraryXPubKey -> Bool
testFromStringPubKey (ArbitraryXPubKey _ k) = fromString (cs $ xPubExport k) == k
testFromStringPrvKey :: ArbitraryXPrvKey -> Bool
testFromStringPrvKey (ArbitraryXPrvKey k) = fromString (cs $ xPrvExport k) == k
testReadShowDerivPath :: ArbitraryDerivPath -> Bool
testReadShowDerivPath (ArbitraryDerivPath p) = read (show p) == p
testReadShowAllHardPath :: ArbitraryAllHardPath -> Bool
testReadShowAllHardPath (ArbitraryAllHardPath p) = read (show p) == p
testReadShowSoftPath :: ArbitrarySoftPath -> Bool
testReadShowSoftPath (ArbitrarySoftPath p) = read (show p) == p
testFromStringDerivPath :: ArbitraryDerivPath -> Bool
testFromStringDerivPath (ArbitraryDerivPath k) = fromString (cs $ pathToStr k) == k
testFromStringAllHardPath :: ArbitraryAllHardPath -> Bool
testFromStringAllHardPath (ArbitraryAllHardPath k) = fromString (cs $ pathToStr k) == k
testFromStringSoftPath :: ArbitrarySoftPath -> Bool
testFromStringSoftPath (ArbitrarySoftPath k) = fromString (cs $ pathToStr k) == k
| tphyahoo/haskoin | haskoin-core/tests/Network/Haskoin/Crypto/ExtendedKeys/Tests.hs | unlicense | 3,194 | 0 | 9 | 527 | 770 | 403 | 367 | 54 | 1 |
qs1 [] = []
qs1 (x : xs) = qs1 larger ++ [x] ++ qs1 smaller
where smaller = [a | a <- xs, a <= x]
larger = [b | b <- xs, b > x]
qs2 [] = []
qs2 (x : xs) = reverse (qs2 smaller ++ [x] ++ qs2 larger)
where smaller = [a | a <- xs, a <= x]
larger = [b | b <- xs, b > x]
qs4 [] = []
qs4 (x : xs) = reverse (qs4 smaller) ++ [x] ++ reverse(qs4 larger)
where smaller = [a | a <- xs, a <= x]
larger = [b | b <- xs, b > x]
qs5 [] = []
qs5 (x : xs) = qs5 larger ++ [x] ++ qs5 smaller
where smaller = [a | a <- xs, a < x]
larger = [b | b <- xs, b > x || b == x]
qs6 [] = []
qs6 (x : xs) = qs6 larger ++ [x] ++ qs6 smaller
where smaller = [a | a <- xs, a < x]
larger = [b | b <- xs, b > x]
main = do
let one = [1]
let many = [4, 1, 2, 1, 7, 3, 5, 4, 5, 5, 7, 7]
print("### qs1")
print(qs1 one)
print(qs1 many)
print("### qs2")
print(qs2 one)
print(qs2 many)
print("### qs4")
print(qs4 one)
print(qs4 many)
print("### qs5")
print(qs5 one)
print(qs5 many)
print("### qs6")
print(qs6 one)
print(qs6 many)
| rabbitonweb/fp101x | w01/qs.hs | apache-2.0 | 1,250 | 0 | 11 | 504 | 724 | 365 | 359 | 38 | 1 |
{-# LANGUAGE CPP #-}
module System.Console.Hawk.PackageDbs.TH
( compileTimeEnvVar
, compileTimeWorkingDirectory
) where
import Language.Haskell.TH.Syntax (TExp(TExp), Q, lift, runIO)
#if MIN_VERSION_template_haskell(2,17,0)
import Language.Haskell.TH.Syntax (Code, liftCode)
#endif
import System.Directory (getCurrentDirectory)
import System.Environment (getEnvironment)
#if !MIN_VERSION_template_haskell(2,17,0)
type Code m a = m (TExp a)
liftCode :: m (TExp a) -> Code m a
liftCode = id
#endif
compileTimeEnvVar :: String -> Code Q (Maybe String)
compileTimeEnvVar varname = liftCode $ do
env <- runIO getEnvironment
let r :: Maybe String
r = lookup varname env
TExp <$> lift r
compileTimeWorkingDirectory :: Code Q String
compileTimeWorkingDirectory = liftCode $ do
pwd <- runIO getCurrentDirectory
TExp <$> lift pwd
| gelisam/hawk | src/System/Console/Hawk/PackageDbs/TH.hs | apache-2.0 | 854 | 0 | 11 | 138 | 240 | 132 | 108 | 20 | 1 |
module TextToys.Utils
( takeTo
) where
import Control.Arrow (first)
takeTo :: (a -> Bool) -> [a] -> ([a], [a])
takeTo _ [] = ([], [])
takeTo p (x:xs) | p x = ([x], xs)
| otherwise = first (x:) $ takeTo p xs
| erochest/text-toys | src/TextToys/Utils.hs | apache-2.0 | 263 | 0 | 8 | 99 | 138 | 76 | 62 | 7 | 1 |
module Main where
import Test.Hspec
import Test.Hspec.Contrib.HUnit
import Test.HUnit
-- (1) Import your test module qualified here.
import qualified System.IO.FileSync.Tests.Join as Join
import qualified System.IO.FileSync.Tests.Tree as Tree
import qualified System.IO.FileSync.Tests.TreeT as TreeT
-- (2) Insert its test list qualified here.
main :: IO ()
main = runTests [Join.tests,
Tree.tests,
TreeT.tests]
runTests :: [Test] -> IO ()
runTests ts = hspec . fromHUnitTest . TestList $ ts
| jtapolczai/FileSync | tests/System/IO/FileSync/Tests.hs | apache-2.0 | 530 | 0 | 7 | 104 | 126 | 80 | 46 | 13 | 1 |
module Main (main) where
import Control.Applicative ((<$>))
import Control.Monad (forever)
import Data.Data (toConstr)
import Data.Function (on)
import Data.List (groupBy)
import System.IO (hFlush, hPutStrLn, stdout)
import Poker.Cards
import Poker.Hands
main :: IO ()
main = do
let ghs = groupBy (\h1 h2 -> h1 `compare` h2 == EQ) $ map fst $ hands deck
putStrLn $ show $ length ghs
let gghs = groupBy ((==) `on` (toConstr . head)) ghs
putStrLn $ show $ length gghs
putHand :: Hand -> IO ()
putHand h = do
hPutStrLn stdout $ unwords $ map show $ cardList h
hFlush stdout
getCards :: IO [Card]
getCards = map read . words <$> getLine
bestThree :: [Card] -> (Hand, Hand, Hand)
bestThree = head . allThrees
allThrees :: [Card] -> [(Hand, Hand, Hand)]
allThrees cs = do
(h1, cs') <- hands cs
(h2, cs'') <- hands cs'
(h3, _) <- hands cs''
return (h1, h2, h3)
| mkscrg/chinese-poker | smart-player/main.hs | bsd-2-clause | 882 | 0 | 16 | 179 | 412 | 221 | 191 | 29 | 1 |
{-# LANGUAGE BangPatterns, CPP, MagicHash, Rank2Types,
RecordWildCards, UnboxedTuples, UnliftedFFITypes #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- |
-- Module : Data.Text.Array
-- Copyright : (c) 2009, 2010, 2011 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : [email protected]
-- Portability : portable
--
-- Packed, unboxed, heap-resident arrays. Suitable for performance
-- critical use, both in terms of large data quantities and high
-- speed.
--
-- This module is intended to be imported @qualified@, to avoid name
-- clashes with "Prelude" functions, e.g.
--
-- > import qualified Data.Text.Array as A
--
-- The names in this module resemble those in the 'Data.Array' family
-- of modules, but are shorter due to the assumption of qualified
-- naming.
module Data.Text.Array
(
-- * Types
Array(..)
, MArray(..)
-- * Functions
, copyM
, copyI
, empty
, equal
, run
, run2
, toList
, unsafeFreeze
, unsafeIndex
, new
, unsafeWrite
) where
#if defined(ASSERTS)
import Control.Exception (assert)
#endif
#if MIN_VERSION_base(4,4,0)
import Control.Monad.ST.Unsafe (unsafeIOToST)
#else
import Control.Monad.ST (unsafeIOToST)
#endif
import Data.Bits ((.&.), xor)
import Data.Text.Internal.Unsafe (inlinePerformIO)
import Data.Text.Internal.Unsafe.Shift (shiftL, shiftR)
#if MIN_VERSION_base(4,5,0)
import Foreign.C.Types (CInt(CInt), CSize(CSize))
#else
import Foreign.C.Types (CInt, CSize)
#endif
import GHC.Base (ByteArray#, MutableByteArray#, Int(..),
indexWord16Array#, newByteArray#,
unsafeFreezeByteArray#, writeWord16Array#, sizeofByteArray#, sizeofMutableByteArray#)
import GHC.ST (ST(..), runST)
import GHC.Word (Word16(..))
import Prelude hiding (length, read)
-- | Immutable array type.
--
-- The 'Array' constructor is exposed since @text-1.1.1.3@
data Array = Array { aBA :: ByteArray# }
-- | Mutable array type, for use in the ST monad.
--
-- The 'MArray' constructor is exposed since @text-1.1.1.3@
data MArray s = MArray { maBA :: MutableByteArray# s }
-- | Create an uninitialized mutable array.
new :: forall s. Int -> ST s (MArray s)
new n
| n < 0 || n .&. highBit /= 0 = array_size_error
| otherwise = ST $ \s1# ->
case newByteArray# len# s1# of
(# s2#, marr# #) -> (# s2#, MArray marr# #)
where !(I# len#) = bytesInArray n
highBit = maxBound `xor` (maxBound `shiftR` 1)
{-# INLINE new #-}
array_size_error :: a
array_size_error = error "Data.Text.Array.new: size overflow"
-- | Freeze a mutable array. Do not mutate the 'MArray' afterwards!
unsafeFreeze :: MArray s -> ST s Array
unsafeFreeze MArray{..} = ST $ \s1# ->
case unsafeFreezeByteArray# maBA s1# of
(# s2#, ba# #) -> (# s2#, Array ba# #)
{-# INLINE unsafeFreeze #-}
-- | Indicate how many bytes would be used for an array of the given
-- size.
bytesInArray :: Int -> Int
bytesInArray n = n `shiftL` 1
{-# INLINE bytesInArray #-}
-- | Unchecked read of an immutable array. May return garbage or
-- crash on an out-of-bounds access.
unsafeIndex :: Array -> Int -> Word16
unsafeIndex a@Array{..} i@(I# i#) =
#if defined(ASSERTS)
let word16len = I# (sizeofByteArray# aBA) `quot` 2 in
if i < 0 || i >= word16len
then error ("Data.Text.Array.unsafeIndex: bounds error, offset " ++ show i ++ ", length " ++ show word16len)
else
#endif
case indexWord16Array# aBA i# of r# -> (W16# r#)
{-# INLINE unsafeIndex #-}
-- | Unchecked write of a mutable array. May return garbage or crash
-- on an out-of-bounds access.
unsafeWrite :: MArray s -> Int -> Word16 -> ST s ()
unsafeWrite ma@MArray{..} i@(I# i#) (W16# e#) = ST $ \s1# ->
#if defined(ASSERTS)
let word16len = I# (sizeofMutableByteArray# maBA) `quot` 2 in
if i < 0 || i >= word16len then error ("Data.Text.Array.unsafeWrite: bounds error, offset " ++ show i ++ ", length " ++ show word16len) else
#endif
case writeWord16Array# maBA i# e# s1# of
s2# -> (# s2#, () #)
{-# INLINE unsafeWrite #-}
-- | Convert an immutable array to a list.
toList :: Array -> Int -> Int -> [Word16]
toList ary off len = loop 0
where loop i | i < len = unsafeIndex ary (off+i) : loop (i+1)
| otherwise = []
-- | An empty immutable array.
empty :: Array
empty = runST (new 0 >>= unsafeFreeze)
-- | Run an action in the ST monad and return an immutable array of
-- its result.
run :: (forall s. ST s (MArray s)) -> Array
run k = runST (k >>= unsafeFreeze)
-- | Run an action in the ST monad and return an immutable array of
-- its result paired with whatever else the action returns.
run2 :: (forall s. ST s (MArray s, a)) -> (Array, a)
run2 k = runST (do
(marr,b) <- k
arr <- unsafeFreeze marr
return (arr,b))
{-# INLINE run2 #-}
-- | Copy some elements of a mutable array.
copyM :: MArray s -- ^ Destination
-> Int -- ^ Destination offset
-> MArray s -- ^ Source
-> Int -- ^ Source offset
-> Int -- ^ Count
-> ST s ()
copyM dest didx src sidx count
| count <= 0 = return ()
| otherwise =
#if defined(ASSERTS)
assert (sidx + count <= I# (sizeofMutableByteArray# (maBA src)) `quot` 2) .
assert (didx + count <= I# (sizeofMutableByteArray# (maBA dest)) `quot` 2) .
#endif
unsafeIOToST $ memcpyM (maBA dest) (fromIntegral didx)
(maBA src) (fromIntegral sidx)
(fromIntegral count)
{-# INLINE copyM #-}
-- | Copy some elements of an immutable array.
copyI :: MArray s -- ^ Destination
-> Int -- ^ Destination offset
-> Array -- ^ Source
-> Int -- ^ Source offset
-> Int -- ^ First offset in destination /not/ to
-- copy (i.e. /not/ length)
-> ST s ()
copyI dest i0 src j0 top
| i0 >= top = return ()
| otherwise = unsafeIOToST $
memcpyI (maBA dest) (fromIntegral i0)
(aBA src) (fromIntegral j0)
(fromIntegral (top-i0))
{-# INLINE copyI #-}
-- | Compare portions of two arrays for equality. No bounds checking
-- is performed.
equal :: Array -- ^ First
-> Int -- ^ Offset into first
-> Array -- ^ Second
-> Int -- ^ Offset into second
-> Int -- ^ Count
-> Bool
equal arrA offA arrB offB count = inlinePerformIO $ do
i <- memcmp (aBA arrA) (fromIntegral offA)
(aBA arrB) (fromIntegral offB) (fromIntegral count)
return $! i == 0
{-# INLINE equal #-}
foreign import ccall unsafe "_hs_text_memcpy" memcpyI
:: MutableByteArray# s -> CSize -> ByteArray# -> CSize -> CSize -> IO ()
foreign import ccall unsafe "_hs_text_memcmp" memcmp
:: ByteArray# -> CSize -> ByteArray# -> CSize -> CSize -> IO CInt
foreign import ccall unsafe "_hs_text_memcpy" memcpyM
:: MutableByteArray# s -> CSize -> MutableByteArray# s -> CSize -> CSize
-> IO ()
| bos/text | src/Data/Text/Array.hs | bsd-2-clause | 7,210 | 0 | 17 | 1,943 | 1,691 | 931 | 760 | 117 | 1 |
-- |
-- Module : Data.Packer.Endian
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
-- Simple module to handle endianness swapping,
-- but GHC should provide (some day) primitives to call
-- into a cpu optimised version (e.g. bswap for x86)
--
{-# LANGUAGE CPP #-}
module Data.Packer.Endian
( le16Host
, le32Host
, le64Host
, be16Host
, be32Host
, be64Host
) where
import Data.Bits
import Data.Word
#if MIN_VERSION_base(4,7,0)
-- | swap endianness on a Word16
swap16 :: Word16 -> Word16
swap16 = byteSwap16
-- | Transform a 32 bit value bytes from a.b.c.d to d.c.b.a
swap32 :: Word32 -> Word32
swap32 = byteSwap32
-- | Transform a 64 bit value bytes from a.b.c.d.e.f.g.h to h.g.f.e.d.c.b.a
swap64 :: Word64 -> Word64
swap64 = byteSwap64
#else
#if BITS_IS_OLD
shr :: Bits a => a -> Int -> a
shr = shiftR
shl :: Bits a => a -> Int -> a
shl = shiftL
#else
shr :: Bits a => a -> Int -> a
shr = unsafeShiftR
shl :: Bits a => a -> Int -> a
shl = unsafeShiftL
#endif
-- | swap endianness on a Word64
-- 56 48 40 32 24 16 8 0
-- a b c d e f g h
-- h g f e d c b a
swap64 :: Word64 -> Word64
swap64 w =
(w `shr` 56) .|. (w `shl` 56)
.|. ((w `shr` 40) .&. 0xff00) .|. ((w .&. 0xff00) `shl` 40)
.|. ((w `shr` 24) .&. 0xff0000) .|. ((w .&. 0xff0000) `shl` 24)
.|. ((w `shr` 8) .&. 0xff000000) .|. ((w .&. 0xff000000) `shl` 8)
-- | swap endianness on a Word32
swap32 :: Word32 -> Word32
swap32 w =
(w `shr` 24) .|. (w `shl` 24)
.|. ((w `shr` 8) .&. 0xff00) .|. ((w .&. 0xff00) `shl` 8)
-- | swap endianness on a Word16
swap16 :: Word16 -> Word16
swap16 w = (w `shr` 8) .|. (w `shl` 8)
#endif
#ifdef CPU_BIG_ENDIAN
-- | 16 bit big endian to host endian
{-# INLINE be16Host #-}
be16Host :: Word16 -> Word16
be16Host = id
-- | 32 bit big endian to host endian
{-# INLINE be32Host #-}
be32Host :: Word32 -> Word32
be32Host = id
-- | 64 bit big endian to host endian
{-# INLINE be64Host #-}
be64Host :: Word64 -> Word64
be64Host = id
-- | 16 bit little endian to host endian
le16Host :: Word16 -> Word16
le16Host w = swap16 w
-- | 32 bit little endian to host endian
le32Host :: Word32 -> Word32
le32Host w = swap32 w
-- | 64 bit little endian to host endian
le64Host :: Word64 -> Word64
le64Host w = swap64 w
#else
-- | 16 bit little endian to host endian
{-# INLINE le16Host #-}
le16Host :: Word16 -> Word16
le16Host = id
-- | 32 bit little endian to host endian
{-# INLINE le32Host #-}
le32Host :: Word32 -> Word32
le32Host = id
-- | 64 bit little endian to host endian
{-# INLINE le64Host #-}
le64Host :: Word64 -> Word64
le64Host = id
-- | 16 bit big endian to host endian
be16Host :: Word16 -> Word16
be16Host w = swap16 w
-- | 32 bit big endian to host endian
be32Host :: Word32 -> Word32
be32Host w = swap32 w
-- | 64 bit big endian to host endian
be64Host :: Word64 -> Word64
be64Host w = swap64 w
#endif
| vincenthz/hs-packer | Data/Packer/Endian.hs | bsd-2-clause | 3,015 | 0 | 14 | 713 | 495 | 304 | 191 | 41 | 1 |
{-# LANGUAGE TypeOperators, DataKinds, PolyKinds, TypeFamilies,
TemplateHaskell, GADTs, UndecidableInstances, RankNTypes,
ScopedTypeVariables, MultiWayIf #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Promotion.Prelude.List
-- Copyright : (C) 2014 Jan Stolarek
-- License : BSD-style (see LICENSE)
-- Maintainer : Jan Stolarek ([email protected])
-- Stability : experimental
-- Portability : non-portable
--
-- Defines promoted functions and datatypes relating to 'List',
-- including a promoted version of all the definitions in @Data.List@.
--
-- Because many of these definitions are produced by Template Haskell,
-- it is not possible to create proper Haddock documentation. Please look
-- up the corresponding operation in @Data.List@. Also, please excuse
-- the apparent repeated variable names. This is due to an interaction
-- between Template Haskell and Haddock.
--
----------------------------------------------------------------------------
module Data.Promotion.Prelude.List (
-- * Basic functions
(:++), Head, Last, Tail, Init, Null, Length,
-- * List transformations
Map, Reverse, Intersperse, Intercalate, Transpose, Subsequences, Permutations,
-- * Reducing lists (folds)
Foldl, Foldl', Foldl1, Foldl1', Foldr, Foldr1,
-- ** Special folds
Concat, ConcatMap, And, Or, Any_, All, Sum, Product, Maximum, Minimum,
any_, -- equivalent of Data.List `any`. Avoids name clash with Any type
-- * Building lists
-- ** Scans
Scanl, Scanl1, Scanr, Scanr1,
-- ** Accumulating maps
MapAccumL, MapAccumR,
-- ** Infinite lists
Replicate,
-- ** Unfolding
Unfoldr,
-- * Sublists
-- ** Extracting sublists
Take, Drop, SplitAt,
TakeWhile, DropWhile, DropWhileEnd, Span, Break,
StripPrefix,
Group,
Inits, Tails,
-- ** Predicates
IsPrefixOf, IsSuffixOf, IsInfixOf,
-- * Searching lists
-- ** Searching by equality
Elem, NotElem, Lookup,
-- ** Searching with a predicate
Find, Filter, Partition,
-- * Indexing lists
(:!!), ElemIndex, ElemIndices, FindIndex, FindIndices,
-- * Zipping and unzipping lists
Zip, Zip3, Zip4, Zip5, Zip6, Zip7,
ZipWith, ZipWith3, ZipWith4, ZipWith5, ZipWith6, ZipWith7,
Unzip, Unzip3, Unzip4, Unzip5, Unzip6, Unzip7,
-- * Special lists
-- ** \"Set\" operations
Nub, Delete, (:\\), Union, Intersect,
-- ** Ordered lists
Sort, Insert,
-- * Generalized functions
-- ** The \"@By@\" operations
-- *** User-supplied equality (replacing an @Eq@ context)
NubBy, DeleteBy, DeleteFirstsBy, UnionBy, GroupBy, IntersectBy,
-- *** User-supplied comparison (replacing an @Ord@ context)
SortBy, InsertBy,
MaximumBy, MinimumBy,
-- ** The \"@generic@\" operations
GenericLength, GenericTake, GenericDrop,
GenericSplitAt, GenericIndex, GenericReplicate,
-- * Defunctionalization symbols
NilSym0,
(:$), (:$$), (:$$$),
(:++$$$), (:++$$), (:++$), HeadSym0, HeadSym1, LastSym0, LastSym1,
TailSym0, TailSym1, InitSym0, InitSym1, NullSym0, NullSym1,
MapSym0, MapSym1, MapSym2, ReverseSym0, ReverseSym1,
IntersperseSym0, IntersperseSym1, IntersperseSym2,
IntercalateSym0, IntercalateSym1, IntercalateSym2,
SubsequencesSym0, SubsequencesSym1,
PermutationsSym0, PermutationsSym1,
FoldlSym0, FoldlSym1, FoldlSym2, FoldlSym3,
Foldl'Sym0, Foldl'Sym1, Foldl'Sym2, Foldl'Sym3,
Foldl1Sym0, Foldl1Sym1, Foldl1Sym2,
Foldl1'Sym0, Foldl1'Sym1, Foldl1'Sym2,
FoldrSym0, FoldrSym1, FoldrSym2, FoldrSym3,
Foldr1Sym0, Foldr1Sym1, Foldr1Sym2,
ConcatSym0, ConcatSym1,
ConcatMapSym0, ConcatMapSym1, ConcatMapSym2,
AndSym0, AndSym1, OrSym0, OrSym1,
Any_Sym0, Any_Sym1, Any_Sym2,
AllSym0, AllSym1, AllSym2,
ScanlSym0, ScanlSym1, ScanlSym2, ScanlSym3,
Scanl1Sym0, Scanl1Sym1, Scanl1Sym2,
ScanrSym0, ScanrSym1, ScanrSym2, ScanrSym3,
Scanr1Sym0, Scanr1Sym1, Scanr1Sym2,
MapAccumLSym0, MapAccumLSym1, MapAccumLSym2, MapAccumLSym3,
MapAccumRSym0, MapAccumRSym1, MapAccumRSym2, MapAccumRSym3,
UnfoldrSym0, UnfoldrSym1, UnfoldrSym2,
InitsSym0, InitsSym1, TailsSym0, TailsSym1,
IsPrefixOfSym0, IsPrefixOfSym1, IsPrefixOfSym2,
IsSuffixOfSym0, IsSuffixOfSym1, IsSuffixOfSym2,
IsInfixOfSym0, IsInfixOfSym1, IsInfixOfSym2,
ElemSym0, ElemSym1, ElemSym2,
NotElemSym0, NotElemSym1, NotElemSym2,
ZipSym0, ZipSym1, ZipSym2,
Zip3Sym0, Zip3Sym1, Zip3Sym2, Zip3Sym3,
ZipWithSym0, ZipWithSym1, ZipWithSym2, ZipWithSym3,
ZipWith3Sym0, ZipWith3Sym1, ZipWith3Sym2, ZipWith3Sym3, ZipWith3Sym4,
UnzipSym0, UnzipSym1,
Unzip3Sym0, Unzip3Sym1,
Unzip4Sym0, Unzip4Sym1,
Unzip5Sym0, Unzip5Sym1,
Unzip6Sym0, Unzip6Sym1,
Unzip7Sym0, Unzip7Sym1,
DeleteSym0, DeleteSym1, DeleteSym2,
(:\\$), (:\\$$), (:\\$$$),
IntersectSym0, IntersectSym1, IntersectSym2,
InsertSym0, InsertSym1, InsertSym2,
SortSym0, SortSym1,
DeleteBySym0, DeleteBySym1, DeleteBySym2, DeleteBySym3,
DeleteFirstsBySym0, DeleteFirstsBySym1, DeleteFirstsBySym2, DeleteFirstsBySym3,
IntersectBySym0, IntersectBySym1, IntersectBySym2,
SortBySym0, SortBySym1, SortBySym2,
InsertBySym0, InsertBySym1, InsertBySym2, InsertBySym3,
MaximumBySym0, MaximumBySym1, MaximumBySym2,
MinimumBySym0, MinimumBySym1, MinimumBySym2,
LengthSym0, LengthSym1,
SumSym0, SumSym1, ProductSym0, ProductSym1,
ReplicateSym0, ReplicateSym1, ReplicateSym2,
TransposeSym0, TransposeSym1,
TakeSym0, TakeSym1, TakeSym2,
DropSym0, DropSym1, DropSym2,
SplitAtSym0, SplitAtSym1, SplitAtSym2,
TakeWhileSym0, TakeWhileSym1, TakeWhileSym2,
DropWhileSym0, DropWhileSym1, DropWhileSym2,
DropWhileEndSym0, DropWhileEndSym1, DropWhileEndSym2,
SpanSym0, SpanSym1, SpanSym2,
BreakSym0, BreakSym1, BreakSym2,
StripPrefixSym0, StripPrefixSym1, StripPrefixSym2,
MaximumSym0, MaximumSym1,
MinimumSym0, MinimumSym1,
GroupSym0, GroupSym1,
GroupBySym0, GroupBySym1, GroupBySym2,
LookupSym0, LookupSym1, LookupSym2,
FindSym0, FindSym1, FindSym2,
FilterSym0, FilterSym1, FilterSym2,
PartitionSym0, PartitionSym1, PartitionSym2,
(:!!$), (:!!$$), (:!!$$$),
ElemIndexSym0, ElemIndexSym1, ElemIndexSym2,
ElemIndicesSym0, ElemIndicesSym1, ElemIndicesSym2,
FindIndexSym0, FindIndexSym1, FindIndexSym2,
FindIndicesSym0, FindIndicesSym1, FindIndicesSym2,
Zip4Sym0, Zip4Sym1, Zip4Sym2, Zip4Sym3, Zip4Sym4,
Zip5Sym0, Zip5Sym1, Zip5Sym2, Zip5Sym3, Zip5Sym4, Zip5Sym5,
Zip6Sym0, Zip6Sym1, Zip6Sym2, Zip6Sym3, Zip6Sym4, Zip6Sym5, Zip6Sym6,
Zip7Sym0, Zip7Sym1, Zip7Sym2, Zip7Sym3, Zip7Sym4, Zip7Sym5, Zip7Sym6, Zip7Sym7,
ZipWith4Sym0, ZipWith4Sym1, ZipWith4Sym2, ZipWith4Sym3, ZipWith4Sym4, ZipWith4Sym5,
ZipWith5Sym0, ZipWith5Sym1, ZipWith5Sym2, ZipWith5Sym3, ZipWith5Sym4, ZipWith5Sym5, ZipWith5Sym6,
ZipWith6Sym0, ZipWith6Sym1, ZipWith6Sym2, ZipWith6Sym3, ZipWith6Sym4, ZipWith6Sym5, ZipWith6Sym6, ZipWith6Sym7,
ZipWith7Sym0, ZipWith7Sym1, ZipWith7Sym2, ZipWith7Sym3, ZipWith7Sym4, ZipWith7Sym5, ZipWith7Sym6, ZipWith7Sym7, ZipWith7Sym8,
NubSym0, NubSym1,
NubBySym0, NubBySym1, NubBySym2,
UnionSym0, UnionSym1, UnionSym2,
UnionBySym0, UnionBySym1, UnionBySym2, UnionBySym3,
GenericLengthSym0, GenericLengthSym1,
GenericTakeSym0, GenericTakeSym1, GenericTakeSym2,
GenericDropSym0, GenericDropSym1, GenericDropSym2,
GenericSplitAtSym0, GenericSplitAtSym1, GenericSplitAtSym2,
GenericIndexSym0, GenericIndexSym1, GenericIndexSym2,
GenericReplicateSym0, GenericReplicateSym1, GenericReplicateSym2,
) where
import Data.Singletons.Prelude.Base
import Data.Singletons.Prelude.Eq
import Data.Singletons.Prelude.List
import Data.Singletons.Prelude.Maybe
import Data.Singletons.TH
$(promoteOnly [d|
-- Overlapping patterns don't singletonize
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
stripPrefix [] ys = Just ys
stripPrefix (x:xs) (y:ys)
| x == y = stripPrefix xs ys
stripPrefix _ _ = Nothing
-- To singletonize these we would need to rewrite all patterns
-- as non-overlapping. This means 2^7 equations for zipWith7.
zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
zip4 = zipWith4 (,,,)
zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
zip5 = zipWith5 (,,,,)
zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
[(a,b,c,d,e,f)]
zip6 = zipWith6 (,,,,,)
zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
[g] -> [(a,b,c,d,e,f,g)]
zip7 = zipWith7 (,,,,,,)
zipWith4 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
= z a b c d : zipWith4 z as bs cs ds
zipWith4 _ _ _ _ _ = []
zipWith5 :: (a->b->c->d->e->f) ->
[a]->[b]->[c]->[d]->[e]->[f]
zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
= z a b c d e : zipWith5 z as bs cs ds es
zipWith5 _ _ _ _ _ _ = []
zipWith6 :: (a->b->c->d->e->f->g) ->
[a]->[b]->[c]->[d]->[e]->[f]->[g]
zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
= z a b c d e f : zipWith6 z as bs cs ds es fs
zipWith6 _ _ _ _ _ _ _ = []
zipWith7 :: (a->b->c->d->e->f->g->h) ->
[a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
= z a b c d e f g : zipWith7 z as bs cs ds es fs gs
zipWith7 _ _ _ _ _ _ _ _ = []
-- These functions use Integral or Num typeclass instead of Int.
--
-- genericLength, genericTake, genericDrop, genericSplitAt, genericIndex
-- genericReplicate
--
-- We provide aliases below to improve compatibility
genericTake :: (Integral i) => i -> [a] -> [a]
genericTake = take
genericDrop :: (Integral i) => i -> [a] -> [a]
genericDrop = drop
genericSplitAt :: (Integral i) => i -> [a] -> ([a], [a])
genericSplitAt = splitAt
genericIndex :: (Integral i) => [a] -> i -> a
genericIndex = (!!)
genericReplicate :: (Integral i) => i -> a -> [a]
genericReplicate = replicate
|])
| int-index/singletons | src/Data/Promotion/Prelude/List.hs | bsd-3-clause | 10,266 | 0 | 7 | 2,065 | 1,465 | 1,003 | 462 | 181 | 0 |
module Horbits.UI.Camera.Zoom (ZoomModel(..), linearZoom, geometricZoom, maxZoom) where
import Control.Applicative
import Control.Lens
import Control.Monad
import Data.List.NonEmpty as NE
newtype ZoomModel a = ZoomModel (NonEmpty a) deriving (Show, Eq)
maxZoom :: Getting a (ZoomModel a) a
maxZoom = to $ \(ZoomModel zooms) -> NE.last zooms
linearZoom :: (Num a, Ord a) => a -> (a, a) -> ZoomModel a
linearZoom step = ZoomModel . unfoldZooms (+ step)
geometricZoom :: (Num a, Ord a) => a -> (a, a) -> ZoomModel a
geometricZoom step = ZoomModel . unfoldZooms (* step)
unfoldZooms :: Ord a => (a -> a) -> (a, a) -> NonEmpty a
unfoldZooms nextScale (minScale, maxScale) = NE.unfold f minScale
where
f s = (s, nextScale <$> mfilter (< maxScale) (Just s))
| chwthewke/horbits | src/horbits/Horbits/UI/Camera/Zoom.hs | bsd-3-clause | 805 | 0 | 11 | 175 | 324 | 180 | 144 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import System.FilePath.FindCompat((||?),always,extension,find,(==?))
import qualified Data.ByteString as BS
import Control.Applicative((<$>))
import qualified Data.ByteString.Char8 as BSC
import Text.Regex
import Maybe(isJust,fromJust)
import System(getArgs)
import qualified Data.List as L
import Data.List(foldl')
import Data.Char(toLower)
(=~) :: String -> String -> Bool
(=~) inp pat = isJust $ matchRegex (mkRegex pat) inp
headerFiles = find always (extension ==? ".h")
headerAndSourceFiles = find always (extension ==? ".h" ||? extension ==? ".c")
main = do
(p:ws:_) <- getArgs
hss <- headerFiles ws
headersAndSources <- headerAndSourceFiles p
mapM_ (fixIncludes hss) headersAndSources
fixIncludes :: [FilePath] -> FilePath -> IO ()
fixIncludes allPaths p = do
allLines <- BSC.lines <$> BS.readFile p
BS.writeFile p (BSC.unlines $ map fixLine allLines)
where fixLine x = if BSC.unpack x =~ "^#include\\s"
then correctCases x
else x
correctCases x = let include = (BSC.unpack . head . tail . BSC.splitWith (== '"')) x in
BSC.pack $ "#include \"" ++ findMatching include ++ "\""
findMatching :: FilePath -> FilePath
findMatching i = let mm = L.findIndex (== cI) cAllPaths in
if isJust mm then allPaths!!fromJust mm else i
where cI = map toLower i
cAllPaths = [map toLower p | p <- allPaths]
| marcmo/includeSpellChecker | old/checker_old.hs | bsd-3-clause | 1,497 | 0 | 16 | 358 | 509 | 273 | 236 | 34 | 3 |
-- 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 OverloadedStrings #-}
module Duckling.Temperature.TR.Rules
( rules ) where
import Data.Maybe
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Temperature.Helpers
import qualified Duckling.Temperature.Types as TTemperature
import Duckling.Temperature.Types (TemperatureData(..))
import Duckling.Types
ruleTemperatureDegrees :: Rule
ruleTemperatureDegrees = Rule
{ name = "<latent temp> degrees"
, pattern =
[ Predicate $ isValueOnly False
, regex "derece|°"
]
, prod = \case
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Degree td
_ -> Nothing
}
ruleTemperatureCelsius :: Rule
ruleTemperatureCelsius = Rule
{ name = "<temp> Celsius"
, pattern =
[ Predicate $ isValueOnly True
, regex "c|santigrat"
]
, prod = \case
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Celsius td
_ -> Nothing
}
ruleTemperatureFahrenheit :: Rule
ruleTemperatureFahrenheit = Rule
{ name = "<temp> Fahrenheit"
, pattern =
[ Predicate $ isValueOnly True
, regex "f(ahrenh?ayt)?"
]
, prod = \case
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Fahrenheit td
_ -> Nothing
}
ruleTemperatureBelowZero :: Rule
ruleTemperatureBelowZero = Rule
{ name = "below zero <temp>"
, pattern =
[ regex "s\305f\305r\305n alt\305nda"
, Predicate $ isValueOnly True
]
, prod = \case
(_:Token Temperature td@TemperatureData{TTemperature.value = Just v}:_) ->
case TTemperature.unit td of
Nothing -> Just . Token Temperature . withUnit TTemperature.Degree $
td {TTemperature.value = Just (- v)}
_ -> Just . Token Temperature $ td {TTemperature.value = Just (- v)}
_ -> Nothing
}
ruleTemperatureBelowZeroReverse :: Rule
ruleTemperatureBelowZeroReverse = Rule
{ name = "<temp> below zero"
, pattern =
[ Predicate $ isValueOnly True
, regex "s\305f\305r\305n alt\305nda"
]
, prod = \case
(Token Temperature td@TemperatureData{TTemperature.value = Just v}:_) ->
case TTemperature.unit td of
Nothing -> Just . Token Temperature . withUnit TTemperature.Degree $
td {TTemperature.value = Just (- v)}
_ -> Just . Token Temperature $ td {TTemperature.value = Just (- v)}
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleTemperatureDegrees
, ruleTemperatureCelsius
, ruleTemperatureFahrenheit
, ruleTemperatureBelowZero
, ruleTemperatureBelowZeroReverse
]
| facebookincubator/duckling | Duckling/Temperature/TR/Rules.hs | bsd-3-clause | 2,859 | 0 | 18 | 636 | 731 | 403 | 328 | 76 | 3 |
{-# LANGUAGE QuasiQuotes #-}
module ApiSpecSpec (main,spec) where
import Control.Lens hiding ((.=))
import Data.Aeson
import Data.Aeson.QQ
import qualified Data.ByteString.Lazy as LazyBytes
import qualified Data.HashMap.Strict as Map
import Data.Text (Text)
import Lib.Swagger.ApiSpec
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
petStoreJson <- runIO $ LazyBytes.readFile "test/pet-store-1.2.json"
let Right v = eitherDecode' petStoreJson
describe "meh" $ do
let o = object [ "code" .= (400 :: Int)
, "message" .= ("message" :: Text)
, "responseModel" .= ("model" :: Text) ]
Success resp = fromJSON o :: Result ApiSpecResponseMessage
it "does something" $
resp ^. apiSpecResponseMessageCode `shouldBe` 400
it "does something" $
resp ^. apiSpecResponseMessageMessage `shouldBe` "message"
it "does something" $
resp ^. apiSpecResponseMessageResponseModel `shouldBe` Just "model"
describe "meh" $ do
it "does something" $
fromJSON respMessageJson `shouldBe` Success respVal
describe "api spec" $ do
it "parses swagger version" $
v ^. apiSpecSwaggerVersion `shouldBe`
"1.2"
it "parses api version" $
v ^. apiSpecApiVersion `shouldBe`
Just "1.0.0"
it "parses api base path" $
v ^. apiSpecBasePath `shouldBe`
"http://petstore.swagger.wordnik.com/api"
it "parses resource path" $
v ^. apiSpecResourcePath `shouldBe`
Just "/pet"
it "parses what api consumes" $
v ^. apiSpecConsumes `shouldBe`
Nothing
it "parses what api produces" $
v ^. apiSpecProduces `shouldBe`
Just
[ "application/json"
, "application/xml"
, "text/plain"
, "text/html"]
describe "api spec - apis" $
it "parses apis" $
v ^. apiSpecApis ^.. each . apiSpecApiPath `shouldBe`
[ "/pet/{petId}"
, "/pet"
, "/pet/findByStatus"
, "/pet/findByTags"
, "/pet/uploadImage"]
describe "api spec - /pet/{petId} endpoint" $ do
let api = v ^. apiSpecApis
^.. folded
. filtered (\ x -> x ^. apiSpecApiPath == "/pet/{petId}")
^. singular _head
it "has correct path" $
api ^. apiSpecApiPath `shouldBe` "/pet/{petId}"
it "has correct description" $
api ^. apiSpecApiDescription `shouldBe` Nothing
context "operations - GET" $ do
let getOp = api ^. apiSpecOperation
^.. folded
. filtered (\ x -> x ^. apiSpecOperationMethod == "GET")
^. singular _head
it "has correct method" $
getOp ^. apiSpecOperationMethod `shouldBe` "GET"
it "has correct summary" $
getOp ^. apiSpecOperationSummary `shouldBe`
Just "Find pet by ID"
it "has correct notes" $
getOp ^. apiSpecOperationNotes `shouldBe`
Just "Returns a pet based on ID"
it "has correct nickname" $
getOp ^. apiSpecOperationNickname `shouldBe` "getPetById"
it "has correct authorizations" $
getOp ^. apiSpecOperationAuthorizations `shouldBe`
Just Map.empty
context "parameters" $ do
let params = getOp ^. apiSpecOperationParameters
context "petId" $ do
let petIdParam = params ^.. folded
. filtered (\ x -> x ^. apiSpecParameterName == "petId")
^. singular _head
it "has correct param type" $
petIdParam ^. apiSpecParameterParamType `shouldBe` "path"
it "has correct name" $
petIdParam ^. apiSpecParameterName `shouldBe` "petId"
it "has correct description" $
petIdParam ^. apiSpecParameterDescription `shouldBe`
Just "ID of pet that needs to be fetched"
it "has correct required attribute" $
petIdParam ^. apiSpecParameterRequired `shouldBe`
Just True
it "has correct allowMultiple attribute" $
petIdParam ^. apiSpecParameterAllowMultiple `shouldBe`
Just False
it "has correct field type" $
petIdParam ^. apiSpecParameterDataTypeFieldType `shouldBe`
Just "integer"
it "has correct field format" $
petIdParam ^. apiSpecParameterDataTypeFieldFormat `shouldBe`
Just "int64"
it "has correct field default value" $
petIdParam ^. apiSpecParameterDataTypeFieldDefaultValue `shouldBe`
Nothing
it "has correct field enum" $
petIdParam ^. apiSpecParameterDataTypeFieldEnum `shouldBe`
Nothing
it "has correct field minimum" $
petIdParam ^. apiSpecParameterDataTypeFieldMinimum `shouldBe`
Just "1.0"
it "has correct field maximum" $
petIdParam ^. apiSpecParameterDataTypeFieldMaximum `shouldBe`
Just "100000.0"
context "response messages" $ do
context "400" $ do
let resp400 = getOp ^. apiSpecOperationResponseMessages
^. _Just
^.. folded
. filtered (\ x -> x ^. apiSpecResponseMessageCode == 400)
^. singular _head
it "has correct code" $
resp400 ^. apiSpecResponseMessageCode `shouldBe` 400
it "has correct message" $
resp400 ^. apiSpecResponseMessageMessage `shouldBe`
"Invalid ID supplied"
it "has correct model" $
resp400 ^. apiSpecResponseMessageResponseModel `shouldBe`
Nothing
context "404" $ do
let resp404 = getOp ^. apiSpecOperationResponseMessages
^. _Just
^.. folded
. filtered (\ x -> x ^. apiSpecResponseMessageCode == 404)
^. singular _head
it "has correct code" $
resp404 ^. apiSpecResponseMessageCode `shouldBe` 404
it "has correct message" $
resp404 ^. apiSpecResponseMessageMessage `shouldBe`
"Pet not found"
it "has correct model" $
resp404 ^. apiSpecResponseMessageResponseModel `shouldBe`
Nothing
respVal :: ApiSpecResponseMessage
respVal = mempty & apiSpecResponseMessageCode .~ 400
& apiSpecResponseMessageMessage .~ "Invalid ID supplied"
& apiSpecResponseMessageResponseModel .~ Nothing
respMessageJson :: Value
respMessageJson = [aesonQQ|
{
"code": 400,
"message": "Invalid ID supplied"
}
|]
| pbogdan/swagger | test/ApiSpecSpec.hs | bsd-3-clause | 7,996 | 0 | 28 | 3,472 | 1,393 | 698 | 695 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Prelude hiding (reverse)
foo :: Int -> Int -> Int
[lq| foo :: n:Nat -> m:Nat -> Nat /[n+m] |]
foo n m
| cond 1 = 0
| cond 2 && n > 1 = foo (n-1) m
| cond 3 && m > 2 = foo (n+1) (m-2)
[lq| cond :: Int -> Bool |]
cond :: Int -> Bool
cond _ = undefined
data L a = N | C a (L a)
[lq| data L [llen] |]
[lq| measure llen :: (L a) -> Int
llen(N) = 0
llen(C x xs) = 1 + (llen xs)
|]
[lq| invariant {v: L a | (llen v) >= 0} |]
[lq| reverse :: xs: L a -> ys : L a -> L a / [(llen ys)] |]
reverse :: L a -> L a -> L a
reverse xs N = xs
reverse xs (C y ys) = reverse (C y xs) ys
merge :: Ord a => L a -> L a -> L a
[lq| merge :: Ord a => xs:L a -> ys:L a -> L a /[(llen xs) + (llen ys)]|]
merge (C x xs) (C y ys) | x > y = C x $ merge xs (C y ys)
| otherwise = C y $ merge (C x xs) ys
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/GeneralizedTermination.hs | bsd-3-clause | 898 | 0 | 10 | 294 | 381 | 196 | 185 | 24 | 1 |
module Main (main) where
import Criterion.Main (bgroup, defaultMain)
import qualified MVC.ServiceBench
main :: IO ()
main = defaultMain
[ bgroup "MVC.Service" MVC.ServiceBench.benchmarks
]
| cmahon/mvc-service | benchmark/Bench.hs | bsd-3-clause | 209 | 0 | 8 | 43 | 57 | 33 | 24 | 6 | 1 |
-- |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
module WebApi.Schema where
import Data.Proxy
import WebApi.Docs
import Language.Haskell.TH.Quote
import Language.Haskell.TH
import Data.Text (Text)
discovery :: Proxy api -> ()
discovery = undefined
| byteally/webapi | webapi-docs/src/WebApi/Schema.hs | bsd-3-clause | 339 | 0 | 6 | 81 | 62 | 39 | 23 | 11 | 1 |
{-# Language OverloadedStrings #-}
--------------------------------------------------------------------
-- |
-- Module : Utils.Katt.Utils
--
-- Contains shared type declarations and various utility functions.
--
module
Utils.Katt.Utils
where
import Control.Error hiding (tryIO)
import qualified Control.Exception as E
import Control.Lens
import Control.Monad (liftM)
import Control.Monad.Trans (lift)
import qualified Control.Monad.State as S
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Monoid ((<>))
import qualified Network.Wreq as W
import qualified Network.Wreq.Session as WS
import System.Exit (exitFailure)
import System.IO (stderr)
-- | Configuration layer consisting of configuration state.
type ConfigEnvInternal m = S.StateT ConfigState m
-- | Configuration layer wrapped with error handling.
type ConfigEnv m = EitherT ErrorDesc (ConfigEnvInternal m)
-- | Submissions consist of a problem identifier and a set of file paths.
type Submission = (KattisProblem, [FilePath])
-- | Error description alias.
type ErrorDesc = B.ByteString
-- | Submissions are identified with an integer id.
type SubmissionId = Integer
--
-- | Problem sessions are identified with an integer id.
type ProblemSession = Integer
-- | Project-specific state consists of the problem name.
type ProjectState = (KattisProblem)
-- | Global configuration, initialized from the /.kattisrc/ file.
data ConfigState =
ConfigState {
-- | Username.
user :: B.ByteString,
-- | API token (hash).
apiKey :: B.ByteString,
-- | Host to be considered as service.
host :: B.ByteString,
-- | URL to login page, relative 'host'.
loginPage :: B.ByteString,
-- | URL to submit page, relative 'host'.
submitPage :: B.ByteString,
-- | Project-specific state, optionally loaded.
project :: Maybe ProjectState
}
deriving Show
-- | HTTP client session and the host path.
type Session = (WS.Session, B.ByteString)
-- | A Kattis problem.
data KattisProblem
-- | Problem ID, unique.
= ProblemId Integer
-- | Associated name of the problem.
| ProblemName B.ByteString
deriving (Eq, Show)
-- | Language used in submission.
data KattisLanguage
-- | C++.
= LangCplusplus
-- | Java.
| LangJava
-- | C.
| LangC
-- | Haskell.
| LangHaskell
deriving (Eq, Show)
-- | Server response indicating successful login.
loginSuccess :: B.ByteString
loginSuccess = "Login successful"
-- | Extension of input test files.
inputTestExtension :: FilePath
inputTestExtension = ".in"
-- | Extension of reference ouput test files.
outputTestExtension :: FilePath
outputTestExtension = ".ans"
-- | Name of this program.
programName :: B.ByteString
programName = "katt"
-- | Relative path to project-specific configuration directory.
configDir :: B.ByteString
configDir = "." <> programName
-- | Relative path to folder containing tests.
testFolder :: FilePath
testFolder = "tests"
-- | URL to page with problem information, relative to 'host'.
problemAddress :: B.ByteString
problemAddress = "/problems/"
-- | Lift some error monad one layer.
unWrapTrans :: (Monad m, S.MonadTrans t) => EitherT e m a -> EitherT e (t m) a
unWrapTrans = EitherT . lift . runEitherT
-- | Execute an IO action and catch any exceptions.
tryIO :: S.MonadIO m => IO a -> EitherT ErrorDesc m a
tryIO = EitherT . S.liftIO . liftM (fmapL (B.pack . show)) .
(E.try :: (IO a -> IO (Either E.SomeException a)))
-- | Execute an IO action and catch any exceptions, tagged with description.
tryIOMsg :: S.MonadIO m => B.ByteString -> IO a -> EitherT ErrorDesc m a
tryIOMsg msg = EitherT . S.liftIO . liftM (fmapL $ const msg) .
(E.try :: (IO a -> IO (Either E.SomeException a)))
-- | Evaluate an error action and terminate process upon failure.
terminateOnFailure :: S.MonadIO m => ErrorDesc -> EitherT ErrorDesc m a -> m a
terminateOnFailure msg state = do
res <- runEitherT state
S.liftIO $ case res of
Left errorMessage -> do
B.hPutStrLn stderr $ msg <> ", error: " <> errorMessage
exitFailure
Right success -> return success
-- | Default HTTP options.
defaultOpts :: W.Options
defaultOpts = W.defaults
& W.header "User-Agent" .~ [programName]
-- | Retrieve a publicly available page, using HTTP GET.
retrievePublicPage :: B.ByteString -> ConfigEnv IO B.ByteString
retrievePublicPage path = do
host' <- S.gets host
reply <- tryIO $ W.getWith defaultOpts $ buildURL host' path
return . B.concat . BL.toChunks $ reply ^. W.responseBody
-- | Retrieve a page requiring authentication, using HTTP GET.
retrievePrivatePage :: Session -> B.ByteString -> EitherT ErrorDesc IO B.ByteString
retrievePrivatePage (sess, host') page = do
reply <- tryIO $ WS.getWith defaultOpts sess (buildURL host' page)
return . B.concat . BL.toChunks $ reply ^. W.responseBody
-- | Construct URL from host path (e.g. /http:\/\/x.com\/) and path (e.g. //).
buildURL :: B.ByteString -> B.ByteString -> String
buildURL host' path = B.unpack $ host' <> "/" <> path
-- | Authenticate and run the provided action.
withAuth :: (WS.Session -> EitherT ErrorDesc IO a) -> ConfigEnv IO a
withAuth action = do
conf <- S.get
EitherT . S.liftIO . WS.withSession $ \sess -> runEitherT $ do
let formData = [("token" :: B.ByteString, apiKey conf),
("user", user conf),
("script", "true")]
url = buildURL (host conf) (loginPage conf)
reply <- tryIO $ WS.postWith defaultOpts sess url formData
let response = B.concat . BL.toChunks $ reply ^. W.responseBody
tryAssert ("Login failure. Server returned: '" <> response <> "'")
(response == loginSuccess)
action sess
-- | Retrieve problem ID of a Kattis problem.
retrieveProblemId :: KattisProblem -> IO Integer
retrieveProblemId (ProblemId id') = return id'
retrieveProblemId (ProblemName _) = undefined
-- | Retrieve problem name of a Kattis problem.
retrieveProblemName :: KattisProblem -> IO B.ByteString
retrieveProblemName (ProblemId _) = undefined
retrieveProblemName (ProblemName name) = return name
| davnils/katt | katt-lib/src/Utils/Katt/Utils.hs | bsd-3-clause | 6,195 | 1 | 18 | 1,205 | 1,397 | 767 | 630 | 106 | 2 |
module Day12 (part1,part2,test1) where
import Control.Applicative
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Text.Trifecta
type Register = Char
data Instruction = CpyI Integer Register | CpyR Register Register | Inc Register | Dec Register | JnzR Register Integer | JnzI Integer Integer
deriving (Eq, Ord, Show)
type CurrentPosition = Int
data ProgramState = ProgramState CurrentPosition [Instruction] (Map Register Integer)
deriving (Eq, Ord, Show)
startState :: [Instruction] -> ProgramState
startState is = ProgramState 0 is Map.empty
startState2 :: [Instruction] -> ProgramState
startState2 is = ProgramState 0 is $ Map.fromList [('c',1)]
instructionParser :: Parser Instruction
instructionParser = try cpyIParser <|> try cpyRParser <|> try incParser <|> try decParser <|> try jnzRParser <|> jnzIParser
where
cpyIParser = string "cpy " *> (CpyI <$> integer <*> letter)
cpyRParser = string "cpy " *> (CpyR <$> letter <*> (space *> letter))
incParser = string "inc " *> (Inc <$> letter)
decParser = string "dec " *> (Dec <$> letter)
jnzRParser = string "jnz " *> (JnzR <$> letter <*> (space *> integer ))
jnzIParser = string "jnz " *> (JnzI <$> integer <*> integer)
fromSuccess :: Result x -> x
fromSuccess (Success x) = x
fromSuccess (Failure x) = error (show x)
parseInput :: String -> [Instruction]
parseInput = fromSuccess . parseString (some (instructionParser <* skipOptional windowsNewLine)) mempty
where windowsNewLine = const () <$ skipOptional newline <*> skipOptional (char '\r')
doNextInstruction :: ProgramState -> ProgramState
doNextInstruction ps@(ProgramState i instructions rMap)
| i >= length instructions = ps
| otherwise = ProgramState (newI currInstruction) instructions (newMap currInstruction)
where
currInstruction = instructions !! i
newI (JnzR r x)
| currVal r > 0 = i + fromIntegral x
| otherwise = i+1
newI (JnzI x y)
| x > 0 = i + fromIntegral y
| otherwise = i+1
newI _ = i+1
currVal r = Map.findWithDefault 0 r rMap
newMap (CpyI x r) = Map.insert r x rMap
newMap (CpyR x y) = Map.insert y (currVal x) rMap
newMap (Inc r) = Map.insert r (currVal r + 1) rMap
newMap (Dec r) = Map.insert r (currVal r - 1) rMap
newMap (JnzR _ _) = rMap
newMap (JnzI _ _) = rMap
endOfInstruction :: ProgramState -> Bool
endOfInstruction (ProgramState i instructions _) = i >= length instructions
getRegister :: Register -> ProgramState -> Integer
getRegister r (ProgramState _ _ rMap) = Map.findWithDefault 0 r rMap
part1 :: Char -> String -> Integer
part1 c = getRegister c . last . takeWhile (not . endOfInstruction) . iterate doNextInstruction . startState . parseInput
part2 :: Char -> String -> Integer
part2 c = getRegister c . last . takeWhile (not . endOfInstruction) . iterate doNextInstruction . startState2 . parseInput
part1Solution :: IO Integer
part1Solution = part1 'a' <$> readFile "./data/Day12.txt"
part2Solution :: IO Integer
part2Solution = part2 'a' <$> readFile "./data/Day12.txt"
test1 :: String
test1="cpy 41 a\ninc a\ninc a\ndec a\njnz a 2\ndec a"
| z0isch/aoc2016 | src/Day12.hs | bsd-3-clause | 3,240 | 0 | 11 | 699 | 1,148 | 583 | 565 | 62 | 8 |
#!/usr/bin/runhaskell
module Main where
import GameLoader
import Data.String.Utils
import Website
main = do
putStrLn "Welcome to the HSB.\nPlease standby..."
putStrLn "Loading Team Info"
teamInfos <- loadTeams
writeFile "teamdata.csv" . join "\n" . map show $ teamInfos --Write the main team info out for AO
putStrLn "Finished loading team info. CSV was written to 'teamdata.csv'"
--Build Website--
putStrLn "Building the Static Website..."
generateSite teamInfos | TheGreenMachine/Scouting-Backend | src/Main.hs | bsd-3-clause | 479 | 0 | 10 | 78 | 85 | 40 | 45 | 12 | 1 |
{-# LANGUAGE TemplateHaskell #-}
-----------------------------------------------------------------------------
-- |
-- Licence : BSD-style (see LICENSE)
--
-- Embeded driver assembly that helps in generating bindings.
--
-----------------------------------------------------------------------------
module Foreign.Salsa.Driver (driverData) where
import qualified Data.ByteString.Char8 as B
import Data.FileEmbed
{-# NOINLINE driverData #-}
driverData :: B.ByteString
driverData = $(embedFile "Driver/Salsa.dll")
| tim-m89/Salsa | Foreign/Salsa/Driver.hs | bsd-3-clause | 524 | 0 | 7 | 59 | 54 | 37 | 17 | 7 | 1 |
module Language.Haskell.Stepeval (Scope, eval, itereval, printeval, stepeval) where
import Control.Arrow (first)
import Control.Applicative ((<$), (<$>), (<*>), (<|>))
import Control.Monad (guard, join, replicateM)
import Data.Foldable (foldMap)
import Data.List (delete, find, partition, unfoldr)
import Data.Maybe (fromMaybe, mapMaybe)
import Data.Monoid (Endo (Endo, appEndo))
import Data.Generics (Data, Typeable,
everything, everywhereBut, extQ, extT, gmapQ, gmapT, listify, mkQ, mkT)
import qualified Data.Set as Set (fromList, toList)
import Language.Haskell.Exts (
Alt (Alt),
Binds (BDecls), Boxed (Boxed), Decl (PatBind, FunBind, InfixDecl),
Exp (App, Case, Con, Do, If, InfixApp, Lambda, LeftSection,
Let, List, Lit, Paren, RightSection, Tuple, TupleSection, Var),
GuardedAlt (GuardedAlt), GuardedAlts (UnGuardedAlt, GuardedAlts),
Literal (Char, Frac, Int, String),
Match (Match),
Op (ConOp, VarOp),
Pat (PApp, PAsPat, PInfixApp, PList, PLit, PParen, PTuple, PVar,
PWildCard),
Name (Ident, Symbol), QName (Special, Qual, UnQual), QOp (QConOp, QVarOp),
Rhs (UnGuardedRhs),
SpecialCon (Cons, TupleCon),
SrcLoc (), -- (SrcLoc),
Stmt (Generator, LetStmt, Qualifier),
preludeFixities, prettyPrint)
import Parenthise (deparen, enparenWith, scopeToFixities)
-- | Evaluate an expression as completely as possible.
eval :: Scope -> Exp -> Exp
eval s = last . itereval s
-- | Print each step of the evaluation of an expression.
printeval :: Scope -> Exp -> IO ()
printeval s = mapM_ (putStrLn . prettyPrint) . itereval s
-- | Make a list of the evaluation steps of an expression.
-- Note that @head (itereval s exp) == exp@
itereval :: Scope -> Exp -> [Exp]
itereval s e = e : unfoldr (fmap (join (,)) . stepeval s) e
-- The use of preludeFixities here is questionable, since we don't use
-- prelude functions, but it's more convenient in general.
-- When we grow a proper Prelude of our own, it would be nice to use that
-- instead.
-- | Evaluate an expression by a single step, or give 'Nothing' if the
-- evaluation failed (either because an error ocurred, or the expression was
-- already as evaluated as possible)
stepeval :: Scope -> Exp -> Maybe Exp
stepeval s e = case step [s] e of
Step (Eval e') -> Just (enparenWith fixes . deparen $ e')
_ -> Nothing
where
fixes = scopeToFixities s ++ preludeFixities
data Eval = EnvEval Decl | Eval Exp
deriving Show
data EvalStep = Failure | Done | Step Eval
deriving Show
data PatternMatch = NoMatch | MatchEval Eval | Matched [MatchResult]
deriving Show
-- | The result of a successful pattern match. The third field is meant to
-- put the 'Exp' that was matched back into the context it came from, e.g.
-- if you matched @[a,b,c]@ against @[1,2,3]@ then one of the 'MatchResult's
-- would be approximately @'MatchResult' \"b\" 2 (\x -> [1,x,3])@
data MatchResult = MatchResult {
mrName :: Name,
mrExp :: Exp,
mrFunc :: (Exp -> Exp) }
type Scope = [Decl]
type Env = [Scope]
-- Involves an evil hack, but only useful for debugging anyway.
instance Show MatchResult where
showsPrec p (MatchResult n e f) = showParen (p >= 11) $
showString "MatchResult " . showN . sp . showE . sp . showF
where
sp = showString " "
showN = showsPrec 11 n
showE = showsPrec 11 e
-- We assume a sensible function would not produce variables with
-- empty names
showF = showParen True $ showString "\\arg -> " . fixVar .
shows (f (Var (UnQual (Ident ""))))
-- Find and replace all instances of the empty variable with 'arg'
fixVar s = case break (`elem` "(V") s of
(r, "") -> r
(r, '(':s') -> r ++ dropEq s' "Var (UnQual (Ident \"\")))" ('(':)
(r, 'V':s') -> r ++ dropEq s' "ar (UnQual (Ident \"\"))" ('V':)
_ -> error "MatchResult.Show: hack a splode"
dropEq s "" _ = "arg" ++ fixVar s
dropEq (x:xs) (d:ds) f
| x == d = dropEq xs ds (f . (x:))
dropEq s _ f = f (fixVar s)
-- | Map over e in @'Step' ('Eval' e)@
liftE :: (Exp -> Exp) -> EvalStep -> EvalStep
liftE f (Step (Eval e)) = Step (Eval (f e))
liftE _ e = e
-- | If either argument is a 'Step', return it, otherwise return the first.
orE :: EvalStep -> EvalStep -> EvalStep
orE r@(Step _) _ = r
orE _ r@(Step _) = r
orE r _ = r
infixr 3 `orE`
-- | Infix liftE.
(|$|) :: (Exp -> Exp) -> EvalStep -> EvalStep
(|$|) = liftE
infix 4 |$|
-- | @'Step' . 'Eval'@
yield :: Exp -> EvalStep
yield = Step . Eval
-- | The basic workhorse of the module - step the given expression in the
-- given environment.
step :: Env -> Exp -> EvalStep
-- Variables
step v (Var n) = need v (fromQName n)
-- Function application
step v e@(App f x) = magic v e `orE` case argList e of
LeftSection e o : x : xs -> yield $ unArgList (InfixApp e o x) xs
RightSection o e : x : xs -> yield $ unArgList (InfixApp x o e) xs
f@(TupleSection _) : xs -> yield $ unArgList f xs
f@(Con (Special (TupleCon _ _))) : xs -> yield $ unArgList f xs
-- note that since we matched against an App, es should be non-empty
Lambda s ps e : es -> applyLambda s ps e es
where
applyLambda _ [] _ _ = error "Lambda with no patterns?"
applyLambda s ps e [] = yield $ Lambda s ps e
applyLambda s ps@(p:qs) e (x:xs) = case patternMatch v p x of
NoMatch -> Failure
MatchEval r -> (\x -> unArgList (Lambda s ps e) $ x : xs) |$| Step r
Matched ms -> case qs of
[] -> yield $ unArgList (applyMatches ms e) xs
qs
| anywhere (`elem` mnames) qs ->
yield . unArgList newLambda $ x : xs
| otherwise -> applyLambda s qs (applyMatches ms e) xs
where
newLambda = Lambda s (fixNames ps) (fixNames e)
fixNames :: Data a => a -> a -- the DMR strikes again
-- The first pattern in the lambda is about to be gobbled.
-- Rename every other pattern that will conflict with any of the
-- names introduced by the pattern match. We avoid names already
-- existing in the lambda, except for the one we're in the process
-- of renaming (that would be silly)
fixNames = appEndo $ foldMap
(\n -> Endo $ alpha n (delete n lnames ++ mnames))
(freeNames qs)
lnames = freeNames ps ++ freeNames e
mnames = Set.toList . foldMap (Set.fromList . freeNames . mrExp)
$ ms
f@(Var q) : es -> case envLookup v (fromQName q) of
Nothing -> Done
Just (PatBind _ _ _ _ _) -> (\f' -> unArgList f' es) |$| step v f
Just (FunBind ms)
| null . drop (pred arity) $ es -> fallback
| otherwise -> foldr (orE . app) fallback ms
where
arity = funArity ms
(xs, r) = splitAt arity es
app (Match _ _ ps _ (UnGuardedRhs e') (BDecls ds)) =
case matches v ps xs (unArgList f) of
NoMatch -> Failure
MatchEval (Eval e') -> yield $ unArgList e' r
MatchEval e -> Step e
Matched ms -> yield . applyMatches ms . mkLet ds $
unArgList e' r
app m = todo "step App Var app" m
Just d -> todo "step App Var" d
l@(Let (BDecls bs) f) : e : es ->
foldr (orE . alphaBind) fallback incomingNames
where
incomingNames = freeNames e
avoidNames = incomingNames ++ freeNames f
alphaBind n
| shadows n l = flip unArgList (e : es) |$|
yield (uncurry mkLet (alpha n avoidNames (tidyBinds f bs, f)))
| otherwise = yield $ unArgList (Let (BDecls bs) (App f e)) es
_ -> fallback
where
fallback = flip app x |$| step v f `orE` app f |$| step v x
step v e@(InfixApp p o q) = case o of
QVarOp n -> magic v e `orE`
step v (App (App (Var n) p) q)
QConOp _ -> (\p' -> InfixApp p' o q) |$| step v p `orE`
InfixApp p o |$| step v q
-- Case
step _ (Case _ []) = error "Case with no branches?"
step v (Case e alts@(Alt l p a bs@(BDecls ds) : as)) =
case patternMatch v p e of
Matched rs -> case a of
UnGuardedAlt x -> yield . applyMatches rs $ mkLet ds x
-- here we apply the matches over all the guard bodies, which may not
-- always have the most intuitive results
GuardedAlts (GuardedAlt m ss x : gs) -> case ss of
[] -> error "GuardedAlt with no body?"
[Qualifier (Con (UnQual (Ident s)))]
| s == "True" -> yield . applyMatches rs $ mkLet ds x
| s == "False" -> if null gs
-- no more guards, drop this alt
then if not (null as) then yield $ Case e as else Failure
-- drop this guard and move to the next
else yield $ mkCase (GuardedAlts gs)
| otherwise -> Failure
-- Okay this is a bit evil. Basically we pretend the guard is being
-- evaluated in a let-scope generated from the result of the pattern
-- match. This allows us to use the same code that is supposed to
-- implement sharing to work out if the scrutinee needs evaluation.
-- If it does then we can step the bit that matched specifically
-- (rather than the whole expression) and then use the laboriously-
-- (but, with any luck, lazily-) constructed third field of
-- MatchResult to recreate the rest of the scrutinee around it.
[Qualifier q] -> case step (matchesToScope rs:ds:v) q of
Step (Eval q') -> yield . mkCase . newAlt $ q'
-- pattern matching nested this deeply is bad for readability
r@(Step (EnvEval
b@(PatBind _ (PVar n) _ (UnGuardedRhs e) (BDecls [])))) ->
case mlookup n rs of
Nothing -> case updateBind b ds of
Nothing -> r
Just ds' -> yield $ Case e (Alt l p a (BDecls ds') : as)
Just (MatchResult _ _ r) -> yield $ Case (r e) alts
r -> r
a -> todo "step Case GuardedAlts" a
where
newAlt q = GuardedAlts (GuardedAlt m [Qualifier q] x : gs)
mkCase a = Case e (Alt l p a bs : as)
GuardedAlts [] -> error "Case branch with no expression?"
MatchEval e -> case e of
Eval e' -> yield $ Case e' alts
r -> Step r
NoMatch
| null as -> Failure
| otherwise -> yield $ Case e as
step _ e@(Case _ _) = todo "step Case" e
-- Let
step _ (Let (BDecls []) e) = yield e
step v (Let (BDecls bs) e) = case step (bs : v) e of
Step (Eval e') -> yield $ mkLet bs e'
Step (EnvEval e') -> Step $ tryUpdateBind e' e bs
r -> r
-- If
step _ (If (Con (UnQual (Ident i))) t f) = case i of
"True" -> yield t
"False" -> yield f
_ -> Failure
step v (If e t f) = (\e -> If e t f) |$| step v e
-- Desugarings
step _ (Do []) = error "Empty do?"
step _ (Do [Qualifier e]) = yield e
step _ (Do [_]) = Failure
step _ (Do (s:ss)) = case s of
Qualifier e -> yield $ InfixApp e (op ">>") (Do ss)
Generator s p e -> yield $ InfixApp e (op ">>=")
(Lambda s [p] (Do ss))
LetStmt bs -> yield $ Let bs (Do ss)
s -> todo "step Do" s
where
op = QVarOp . UnQual . Symbol
-- Trivialities
step v (Paren p) = step v p
step v (Tuple xs) = case xs of
[] -> error "Empty tuple?"
[_] -> error "Singleton tuple?"
es -> liststep v Tuple es
-- Base cases
step _ (LeftSection _ _) = Done
step _ (RightSection _ _) = Done
step _ (TupleSection _) = Done
step _ (Lit _) = Done
step _ (List []) = Done
step _ (Con _) = Done
step _ (Lambda _ _ _) = Done
step _ e = todo "step _" e
-- | Apply the function to the argument as neatly as possible - i.e. infix
-- or make a section if the function's an operator
app :: Exp -> Exp -> Exp
app (Con q) x | isOperator q = LeftSection x (QConOp q)
app (Var q) x | isOperator q = LeftSection x (QVarOp q)
app (LeftSection x op) y = InfixApp x op y
app (RightSection op y) x = InfixApp x op y
app (TupleSection es) x = go es id
where
go (Nothing : es) f = case sequence es of
Just es' -> Tuple $ f (x : es')
Nothing -> TupleSection $ map Just (f [x]) ++ es
go (Just e : es) f = go es (f . (e :))
go [] _ = error "app TupleSection: full section"
app (Con (Special (TupleCon b i))) x
| i <= 1 = error "app TupleCon: i <= 0"
| b /= Boxed = todo "app TupleCon" b
| otherwise = TupleSection (Just x : replicate (i - 1) Nothing)
app f x = App f x
-- | 'True' if the name refers to a non-tuple operator. Tuples are excluded
-- because they're "mixfix" and therefore need to be considered separately
-- anyway.
isOperator :: QName -> Bool
isOperator (Special Cons) = True
isOperator (UnQual (Symbol _)) = True
isOperator (Qual _ (Symbol _)) = True
isOperator _ = False
-- | Given a list of expressions, evaluate the first one that isn't already
-- evaluated and then recombine them with the given function.
liststep :: Env -> ([Exp] -> Exp) -> [Exp] -> EvalStep
liststep v f es = go es id
where
go es g = case es of
[] -> Done
e:es -> case step v e of
Step (Eval e') -> yield . f . g $ e':es
Done -> go es (g . (e:))
r -> r
-- | Make a let-expression from a list of bindings and an expression. The
-- list of bindings has unused members removed; if this results in an empty
-- list, the expression is returned unaltered.
mkLet :: Scope -> Exp -> Exp
mkLet ds x = case tidyBinds x ds of
[] -> x
ds' -> Let (BDecls ds') x
-- | Create a list of 'Decl' that bind the patterns of the 'MatchResult's
-- to their corresponding expressions.
matchesToScope :: [MatchResult] -> Scope
matchesToScope = map $ \(MatchResult n e _) ->
PatBind nowhere (PVar n) Nothing (UnGuardedRhs e) (BDecls [])
-- this shouldn't really exist
nowhere :: SrcLoc
nowhere = undefined
-- nowhere = SrcLoc "<nowhere>" 0 0 -- for when Show needs to not choke
-- This code isn't very nice, largely because I anticipate it all being
-- replaced eventually anyway.
-- | Implements primitives like addition and comparison.
magic :: Env -> Exp -> EvalStep
magic v e = case e of
App (App (Var p) x) y -> rhs (fromQName p) x y
InfixApp x (QVarOp o) y -> rhs (fromQName o) x y
_ -> Done
where
rhs p x y = case lookup p primitives of
Just (+*) -> case (step v x, step v y) of
(Done, Done) -> x +* y
(Done, y') -> InfixApp x op |$| y'
(x', _) -> (\e -> InfixApp e op y) |$| x'
where
op = QVarOp (UnQual p)
Nothing -> Done
lit x = case properFraction (toRational x) of
(i, 0) -> Lit (Int i)
(i, r) -> Lit (Frac (toRational i + r))
con = Con . UnQual . Ident
unlit (Lit (Int i)) = Just $ toRational i
unlit (Lit (Frac r)) = Just r
unlit _ = Nothing
primitives = map (first Symbol) ops ++
map (first Ident) funs
ops = [
("+", num (+)),
("*", num (*)),
("-", num (-)),
("<", bool (<)),
("<=", bool (<=)),
(">", bool (>)),
(">=", bool (>=)),
("==", bool (==)),
("/=", bool (/=))]
funs = [
("div", mkOp (Lit . Int . floor) (/))]
num op = mkOp lit op
bool op = mkOp (con . show) op
mkOp f g m n = maybe Done (yield . f) $ g <$> unlit m <*> unlit n
-- | Given an expression and a list of bindings, filter out bindings that
-- aren't used in the expression.
tidyBinds :: Exp -> Scope -> Scope
tidyBinds e v = filter (`elem` keep) v
where
keep = go (usedIn e) v
go p ds = case partition p ds of
([], _) -> []
(ys, xs) -> ys ++ go ((||) <$> p <*> usedIn ys) xs
binds (PatBind _ (PVar n) _ _ _) = [n]
binds (FunBind ms) = [funName ms]
-- FIXME: an InfixDecl can specify multiple ops, and we keep all or
-- none - should drop the ones we no longer need
binds (InfixDecl _ _ _ os) = map unOp os
binds l = todo "tidyBinds binds" l
usedIn es d = any (\n -> isFreeIn n es) (binds d)
unOp (VarOp n) = n
unOp (ConOp n) = n
-- | Continuing evaluation requires the value of the given name from the
-- environment, so try to look it up and step it or substitute it.
need :: Env -> Name -> EvalStep
need v n = case envBreak ((Just n ==) . declName) v of
(_, _, [], _) -> Done
(as, bs, c : cs, ds) -> case c of
PatBind s (PVar n) t (UnGuardedRhs e) (BDecls []) ->
case step ((bs ++ cs) : ds) e of
Done -> case mapMaybe (envLookup as) $ freeNames e of
[] -> yield e
xs -> todo "panic" xs
Step (Eval e') -> Step . EnvEval $
PatBind s (PVar n) t (UnGuardedRhs e') (BDecls [])
f -> f
FunBind _ -> Done
b -> todo "need case" b
-- | Name bound by the equations. Error if not all the matches are for the
-- same function.
funName :: [Match] -> Name
funName [] = error "No matches?"
funName (Match _ n _ _ _ _ : ms) = foldr match n ms
where
match (Match _ m _ _ _ _) n | m == n = n
match m n = error $ "Match names don't? " ++ show (m, n)
-- | Counts the number of patterns on the LHS of function equations.
-- Error if the patterns have different numbers of arguments
funArity :: [Match] -> Int
funArity [] = error "No matches?"
funArity (Match _ n ps _ _ _ : ms) = foldr match (length ps) ms
where
match (Match _ _ ps _ _ _) l | length ps == l = l
match _ _ = error $ "Matches of different arity? " ++ show n
{- Doubtful if this is useful, but I'm keeping it anyway
funToCase :: [Match] -> Exp
funToCase [] = error "No matches?"
-- unsure of whether this is the right SrcLoc
funToCase [Match s _ ps _ (UnGuardedRhs e) (BDecls [])] = Lambda s ps e
funToCase ms@(Match s _ ps _ _ _ : _) = Lambda s qs $ Case e as
where
qs = map (PVar . Ident) names
e = tuple $ map (Var . UnQual . Ident) names
as = map matchToAlt ms
tuple [] = error "No patterns in match?"
tuple [x] = x
tuple xs = Tuple xs
names = zipWith const (concatMap (\i -> nameslen i) [1 ..]) ps
nameslen i = replicateM i ['a' .. 'z']
matchToAlt (Match s _ ps _ r bs) = Alt s (ptuple ps) (rhsToAlt r) bs
ptuple [] = error "No patterns in match?"
ptuple [x] = x
ptuple xs = PTuple xs
rhsToAlt (UnGuardedRhs e) = UnGuardedAlt e
rhsToAlt (GuardedRhss rs) = GuardedAlts $
map (\(GuardedRhs s t e) -> GuardedAlt s t e) rs
-}
-- | Given a pattern binding, an expression, and a scope, try to update the
-- scope with the binding (cf. 'updateBind') - if succesful construct an
-- updated let-expression, otherwise produce an EnvEval with the binding.
tryUpdateBind :: Decl -> Exp -> Scope -> Eval
tryUpdateBind e' e = maybe (EnvEval e') (Eval . flip mkLet e) . updateBind e'
-- | Given a pattern binding, replace one of the same name in the given
-- scope, or 'Nothing' if it wasn't there.
updateBind :: Decl -> Scope -> Maybe Scope
updateBind p@(PatBind _ (PVar n) _ _ _) v = case break match v of
(_, []) -> Nothing
(h, _ : t) -> Just $ h ++ p : t
where
match (PatBind _ (PVar m) _ _ _) = n == m
match (FunBind _) = False
match (InfixDecl _ _ _ _) = False
match d = todo "updateBind match" d
updateBind l _ = todo "updateBind" l
-- | Find a declaration in the environment by matching on its 'declName'.
envLookup :: Env -> Name -> Maybe Decl
envLookup v n = case envBreak ((Just n ==) . declName) v of
(_, _, [], _) -> Nothing
(_, _, c : _, _) -> Just c
-- | If the decl binds a pattern or function, return its name.
declName :: Decl -> Maybe Name
declName (PatBind _ (PVar m) _ _ _) = Just m
declName (FunBind ms) = Just (funName ms)
declName (InfixDecl _ _ _ _) = Nothing
declName d = todo "declName" d
-- | Given a list of lists, find the first item matching the predicate and
-- return
-- (lists with no match, takeWhile p list, dropWhile p list, lists remaining)
envBreak :: (a -> Bool) -> [[a]] -> ([[a]], [a], [a], [[a]])
envBreak _ [] = ([], [], [], [])
envBreak p (x:xs) = case break p x of
(_, []) -> (x:as, bs, cs, ds)
(ys, zs) -> ([], ys, zs, xs)
where
(as, bs, cs, ds) = envBreak p xs
-- | Assume the name is unqualified, and fetch the name in that case.
-- Error otherwise.
fromQName :: QName -> Name
fromQName (UnQual n) = n
fromQName q = error $ "fromQName: " ++ show q
-- | Given a list of 'MatchResult', substitute the bindings wherever they
-- are not shadowed.
applyMatches :: Data a => [MatchResult] -> a -> a
-- If it's not an Exp, just recurse into it, otherwise try to substitute...
applyMatches ms x = recurse `extT` replaceOne $ x
where
replaceOne e@(Var (UnQual m)) = maybe e mrExp $ mlookup m ms
replaceOne (InfixApp x o@(QVarOp (UnQual m)) y) =
fromMaybe (InfixApp rx o ry) (mkApp . mrExp <$> mlookup m ms)
where
(rx, ry) = (replaceOne x, replaceOne y)
mkApp f = app (app f rx) ry
-- ...or else recurse anyway
replaceOne e = recurse e
recurse e = gmapT (applyMatches (notShadowed e)) e
-- Parameter here might be redundant - it's only called on x anyway
notShadowed e = filter (not . flip shadows e . mrName) ms
-- | Find a 'MatchResult' by name.
mlookup :: Name -> [MatchResult] -> Maybe MatchResult
mlookup m = foldr (\x r -> x <$ guard (m == mrName x) <|> r) Nothing
-- | Produce a 'GenericT' that renames all instances of the given 'Name' to
-- something else that isn't any of the given @['Name']@. Does not apply the
-- rename where the name is shadowed.
alpha :: Data a => Name -> [Name] -> a -> a
alpha n avoid = everywhereBut (shadows n) (mkT $ replaceOne n m)
where
-- genNames produces an infinite list, so find cannot give Nothing
Just m = find (`notElem` avoid) $ case n of
Ident i -> map Ident $ genNames i ['0' .. '9'] 1
Symbol s -> map Symbol $ genNames s "!?*#+&$%@." 1
genNames n xs i = map (n ++) (replicateM i xs) ++ genNames n xs (succ i)
replaceOne n m r | n == r = m | otherwise = r
-- | Returns 'True' if the 'Name' appears without a corresponding binding
-- anywhere in the structure.
-- Always returns 'True' for @>>=@ and @>>@ if there are any do-expressions
-- present.
isFreeIn :: Data a => Name -> a -> Bool
isFreeIn n x = not (shadows n x) && (is n x || or (gmapQ (isFreeIn n) x))
where
is n@(Symbol s)
| s == ">>" || s == ">>=" = mkQ False (== n) `extQ` isDo
is n = mkQ False (== n)
isDo (Do _) = True
isDo _ = False
-- | Fetches a list of all 'Name's present but not bound in the argument.
freeNames :: Data a => a -> [Name]
freeNames e = filter (`isFreeIn` e) . Set.toList . Set.fromList $
listify (const True) e
-- | If the argument is 'Step', turn it into a 'MatchEval', else 'NoMatch'.
peval :: EvalStep -> PatternMatch
peval (Step e) = MatchEval e
peval _ = NoMatch
-- | Match a single pattern against a single expression.
patternMatch :: Env -> Pat -> Exp -> PatternMatch
-- Strip parentheses
patternMatch v (PParen p) x = patternMatch v p x
patternMatch v p (Paren x) = patternMatch v p x
-- Patterns that always match
patternMatch _ (PWildCard) _ = Matched []
patternMatch _ (PVar n) x = Matched [MatchResult n x id]
-- As-patterns
patternMatch v (PAsPat n p) x = case patternMatch v p x of
Matched ms -> Matched (MatchResult n x id : ms)
r -> r
-- Let-expressions should skip right to the interesting bit
patternMatch v p (Let (BDecls ds) x) = case patternMatch (ds:v) p x of
MatchEval (Eval e) -> MatchEval . Eval $ mkLet ds e
MatchEval (EnvEval e) -> MatchEval $ tryUpdateBind e x ds
r -> r
patternMatch _ _ (Let bs _) = todo "patternMatch Let" bs
-- Variables can only match trivial patterns
patternMatch v p (Var q) = case envBreak ((Just n ==) . declName) v of
(_, _, [], _) -> NoMatch
(_, xs, y : ys, zs) -> case y of
PatBind s q t (UnGuardedRhs e) bs -> case patternMatch v' p e of
MatchEval (Eval e') ->
MatchEval (EnvEval (PatBind s q t (UnGuardedRhs e') bs))
Matched _ -> MatchEval (Eval e)
r -> r
where
v' = (xs ++ ys) : zs
FunBind _ -> NoMatch
l -> todo "patternMatch Var" l
where
n = fromQName q
-- Desugar infix applications and lists
patternMatch v (PInfixApp p q r) s = patternMatch v (PApp q [p, r]) s
patternMatch v p e@(InfixApp a n b) = case n of
QVarOp _ -> peval $ step v e
QConOp q -> patternMatch v p (App (App (Con q) a) b)
patternMatch _ _ (List (x:xs)) = MatchEval . Eval $
InfixApp x (QConOp (Special Cons)) (List xs)
patternMatch _ _ (Lit (String (x:xs))) = MatchEval . Eval $
InfixApp (Lit (Char x)) (QConOp (Special Cons)) (Lit (String xs))
-- Literal match
patternMatch _ (PLit p) (Lit q)
| p == q = Matched []
| otherwise = NoMatch
patternMatch v (PLit _) s = peval $ step v s
patternMatch v (PList []) x = case argList x of
[List []] -> Matched []
[List _] -> NoMatch
Con _ : _ -> NoMatch
_ -> peval $ step v x
-- Lists of patterns
patternMatch v (PList (p:ps)) q =
patternMatch v (PApp (Special Cons) [p, PList ps]) q
-- Tuples
patternMatch v (PTuple ps) q = case q of
Tuple qs -> matches v ps qs Tuple
_ -> peval $ step v q
-- Constructor matches
patternMatch v (PApp n ps) q = case argList q of
(Con c:xs)
| c == n -> matches v ps xs (unArgList (Con c))
| otherwise -> NoMatch
_ -> peval $ step v q
-- Fallback case
patternMatch _ p q = todo "patternMatch _" (p, q)
-- | Map over the function field of a 'MatchResult'.
onMRFunc :: ((Exp -> Exp) -> (Exp -> Exp)) -> MatchResult -> MatchResult
onMRFunc f m@(MatchResult { mrFunc = g }) = m { mrFunc = f g }
-- The tricky part about this is the third field of PatternMatch, which
-- contains a function to put the matchresult - perhaps after some
-- modification - back into its original context.
-- This is something that is mostly best understood by example. Luckily I've
-- provided an evil Show instance for Exp -> Exp so you should be able to
-- see its purpose in a bit of mucking about with ghci :)
-- Obviously it starts off as id.
-- | Carry out several simultaneous pattern matches, e.g. for lists or
-- tuples of patterns. The given function is used to restore the list of
-- expressions to their original context if necessary (so it might be the
-- Tuple constructor, for example).
matches :: Env -> [Pat] -> [Exp] -> ([Exp] -> Exp) -> PatternMatch
matches _ [] [] _ = Matched []
matches v ps xs f = go v ps xs id
where
go _ [] [] _ = Matched []
go v (p:ps) (e:es) g =
-- We rely on laziness here to not recurse if the first match fails.
-- If we do recurse, then the reconstruction function needs to
-- put the current expression on the end.
case (patternMatch v p e, go v ps es (g . (e:))) of
(NoMatch, _) -> NoMatch
(MatchEval (Eval e'), _) -> MatchEval . Eval . f . g $ e' : es
(r@(MatchEval _), _) -> r
(Matched xs, Matched ys) ->
-- great, everything worked fine. Now we assume the recursive case
-- has everything worked out and we just need to apply the final
-- touches to the reconstruction function.
-- So far it'll be a [Exp] -> [Exp] that basically consists of
-- everything we've skipped to get this far in the pattern match.
-- We want to also append everything we haven't met yet (making
-- an Exp -> [Exp]) and then apply the combination function given
-- as a parameter (making Exp -> Exp, which is what we need). We
-- do this for every pattern match item.
Matched (map (onMRFunc ((f . g . (: es)) .)) xs ++ ys)
(_, r) -> r
-- Ran out of patterns before expressions or vice versa, fail
-- TODO: matches should get a [(Pat, Exp)] so the equality of length
-- is statically enforced.
go _ _ _ _ = NoMatch
-- | Deconstruct an infix or prefix application into
-- @[function, arg1, arg2, ...]@. Spine-strict by the nature of application.
argList :: Exp -> [Exp]
argList = reverse . atl
where
atl (App f x) = x : atl f
atl (Paren p) = atl p
atl (InfixApp p o q) = [q, p, case o of
QVarOp n -> Var n
QConOp n -> Con n]
atl e = [e]
-- This could be optimised because app checks for atomic functions but we
-- know after the first app that none of the subsequent functions are so.
-- | @'foldl' 'app'@. Apply a function to a list of arguments, neatly.
unArgList :: Exp -> [Exp] -> Exp
unArgList = foldl app
-- | Return 'True' if the argument binds the given 'Name'
shadows :: Typeable a => Name -> a -> Bool
shadows n = mkQ False exprS `extQ` altS `extQ` matchS
where
exprS (Lambda _ ps _) = any patS ps
exprS (Let (BDecls bs) _) = any letS bs
exprS _ = False
altS (Alt _ p _ (BDecls bs)) = patS p || any letS bs
altS a = todo "shadows altS" a
matchS (Match _ _ ps _ _ _) = any patS ps
patS (PVar m) = m == n
patS (PAsPat m p) = m == n || patS p
patS p = or $ gmapQ (mkQ False patS) p
letS (PatBind _ p _ _ _) = patS p
letS _ = False
-- | 'True' if the predicate holds anywhere inside the structure.
anywhere :: (Typeable a, Data b) => (a -> Bool) -> b -> Bool
anywhere p = everything (||) (mkQ False p)
todo :: (Show s) => String -> s -> a
todo s = error . (s ++) . (": Not implemented: " ++) . show
| bmillwood/stepeval | src/Language/Haskell/Stepeval.hs | bsd-3-clause | 28,500 | 0 | 29 | 7,210 | 9,972 | 5,188 | 4,784 | 475 | 44 |
-- ^
-- Handlers for Lono endpoints
module Handlers.Lono where
import Api.Lono
import Handlers.Common
import qualified Handlers.RssReaders.Feeds as F
import qualified Handlers.RssReaders.Subscriptions as S
import qualified Handlers.RssReaders.UserPosts as U
import Persistence.Lono.Common
import Persistence.RssReaders.Common
import Servant
import Types.Common
-- ^
-- Create an application containing all Lono API endpoints
app :: ApiConfig -> Application
app = app' apiProxy handlers
-- ^
-- Lono API handlers
handlers :: ServerT LonoApi Api
handlers =
userHandlers :<|>
feedHandlers :<|>
postHandlers :<|>
subscriptionHandlers :<|>
userPostHandlers :<|>
postQueryHandlers :<|>
tagsHandlers
where
userHandlers :: ServerT LonoUserApi Api
userHandlers = mkHandlers userDefinition mkUserGetSingleLink mkUserGetMultipleLink
postHandlers :: ServerT LonoPostApi Api
postHandlers = mkHandlers postDefinition mkPostGetSingleLink mkPostGetMultipleLink
postQueryHandlers :: ServerT LonoPostQueryApi Api
postQueryHandlers = mkHandlers postQueryDefinition mkPostQueryGetSingleLink mkPostQueryGetMultipleLink
tagsHandlers :: ServerT LonoTagsApi Api
tagsHandlers = mkHandlers tagsDefinition mkTagsGetSingleLink mkTagsGetMultipleLink
mkHandlers def mkGetSingleLink mkGetMultipleLink =
getMultiple mkGetMultipleLink def :<|>
getSingle def :<|>
deleteSingle def :<|>
createSingleOrMultiple def mkGetSingleLink :<|>
replaceSingle def :<|>
replaceMultiple def :<|>
modifySingle def :<|>
modifyMultiple def :<|>
optionsSingle :<|>
optionsMultiple
feedHandlers =
getMultiple mkFeedGetMultipleLink feedDefinition :<|>
getSingle feedDefinition :<|>
F.deleteSingle :<|>
createSingleOrMultiple feedDefinition mkFeedGetSingleLink :<|>
replaceSingle feedDefinition :<|>
replaceMultiple feedDefinition :<|>
modifySingle feedDefinition :<|>
modifyMultiple feedDefinition :<|>
optionsSingle :<|>
optionsMultiple
userPostHandlers =
U.getMultiple mkUserPostGetMultipleLink :<|>
U.getSingle :<|>
U.deleteSingle :<|>
U.createSingleOrMultiple mkUserPostGetSingleLink :<|>
U.replaceSingle :<|>
U.replaceMultiple :<|>
U.modifySingle :<|>
U.modifyMultiple :<|>
U.optionsSingle :<|>
U.optionsMultiple
subscriptionHandlers :: ServerT LonoSubscriptionApi Api
subscriptionHandlers =
S.getMultiple mkSubscriptionGetMultipleLink :<|>
S.getSingle :<|>
S.deleteSingle :<|>
S.createSingleOrMultiple mkSubscriptionGetSingleLink :<|>
S.replaceSingle :<|>
S.replaceMultiple :<|>
S.modifySingle :<|>
S.modifyMultiple :<|>
optionsSingle :<|>
optionsMultiple
-- ^
-- Perform any initialization to be done on server start
appInit :: ApiConfig -> IO ()
appInit =
addDbIndices userIndices >>
addDbIndices feedIndices >>
addDbIndices postIndices >>
addDbIndices subscriptionIndices >>
addDbIndices postQueryIndices >>
addDbIndices tagsIndices
| gabesoft/kapi | src/Handlers/Lono.hs | bsd-3-clause | 3,126 | 0 | 17 | 619 | 560 | 287 | 273 | 82 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE Trustworthy #-}
module Sigym4.Units.Accelerate (
(*~)
, (/~)
, module Sigym4.Units.Meteo
, module Sigym4.Units
) where
import Sigym4.Units.Accelerate.Internal ( (*~), (/~) )
import Sigym4.Units hiding ( (*~), (/~) )
import Sigym4.Units.Meteo
| meteogrid/sigym4-units-accelerate | src/Sigym4/Units/Accelerate.hs | bsd-3-clause | 679 | 0 | 5 | 111 | 87 | 66 | 21 | 20 | 0 |
-- |
-- This module contains functions which help when unmarshalling query responses
module Network.TableStorage.Query (
edmBinary, edmBoolean, edmDateTime, edmDouble,
edmGuid, edmInt32, edmInt64, edmString
) where
import Data.Time ( UTCTime )
import Network.TableStorage.Types
( Entity(entityColumns),
EntityColumn(EdmBinary, EdmBoolean, EdmDateTime, EdmDouble,
EdmGuid, EdmInt32, EdmInt64, EdmString) )
-- |
-- Find the value in a binary-valued column or return Nothing if no such column exists
edmBinary :: String -> Entity -> Maybe String
edmBinary key en = do
col <- lookup key $ entityColumns en
case col of
EdmBinary s -> s
_ -> Nothing
-- |
-- Find the value in a string-valued column or return Nothing if no such column exists
edmString :: String -> Entity -> Maybe String
edmString key en = do
col <- lookup key $ entityColumns en
case col of
EdmString s -> s
_ -> Nothing
-- |
-- Find the value in a boolean-valued column or return Nothing if no such column exists
edmBoolean :: String -> Entity -> Maybe Bool
edmBoolean key en = do
col <- lookup key $ entityColumns en
case col of
EdmBoolean s -> s
_ -> Nothing
-- |
-- Find the value in a date-valued column or return Nothing if no such column exists
edmDateTime :: String -> Entity -> Maybe UTCTime
edmDateTime key en = do
col <- lookup key $ entityColumns en
case col of
EdmDateTime s -> s
_ -> Nothing
-- |
-- Find the value in a double-valued column or return Nothing if no such column exists
edmDouble :: String -> Entity -> Maybe Double
edmDouble key en = do
col <- lookup key $ entityColumns en
case col of
EdmDouble s -> s
_ -> Nothing
-- |
-- Find the value in a Guid-valued column or return Nothing if no such column exists
edmGuid :: String -> Entity -> Maybe String
edmGuid key en = do
col <- lookup key $ entityColumns en
case col of
EdmGuid s -> s
_ -> Nothing
-- |
-- Find the value in an integer-valued column or return Nothing if no such column exists
edmInt32 :: String -> Entity -> Maybe Int
edmInt32 key en = do
col <- lookup key $ entityColumns en
case col of
EdmInt32 s -> s
_ -> Nothing
-- |
-- Find the value in an integer-valued column or return Nothing if no such column exists
edmInt64 :: String -> Entity -> Maybe Int
edmInt64 key en = do
col <- lookup key $ entityColumns en
case col of
EdmInt64 s -> s
_ -> Nothing | paf31/tablestorage | src/Network/TableStorage/Query.hs | bsd-3-clause | 2,446 | 0 | 10 | 566 | 617 | 315 | 302 | 56 | 2 |
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, TypeFamilies #-}
import qualified Common.Matrix.Matrix as M
import Common.NumMod.MkNumMod
mkNumMod True 100000000
type Zn = Int100000000
solve :: Integer -> Zn
solve n = (((mat `M.power` p) `M.multiply` initial) M.! (1, 1)) - 1
where
p = 987654321 :: Int
mat = M.fromList 3 3 [0, 1, 0, 0, 0, 1, fromInteger $ -n, 0, 2^n]
initial = M.fromList 3 1 [3, 2^n, 4^n]
main = print $ sum [ solve i | i <- [1 .. 30] ]
| foreverbell/project-euler-solutions | src/356.hs | bsd-3-clause | 490 | 0 | 11 | 112 | 213 | 123 | 90 | 11 | 1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Network
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/network/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- This module is kept for backwards-compatibility. New users are
-- encouraged to use "Network.Socket" instead.
--
-- "Network" was intended as a \"higher-level\" interface to networking
-- facilities, and only supports TCP.
--
-----------------------------------------------------------------------------
#include "HsNetworkConfig.h"
#ifdef HAVE_GETADDRINFO
-- Use IPv6-capable function definitions if the OS supports it.
#define IPV6_SOCKET_SUPPORT 1
#endif
module Network
(
-- * Basic data types
Socket
, PortID(..)
, HostName
, PortNumber
-- * Initialisation
, withSocketsDo
-- * Server-side connections
, listenOn
, accept
, sClose
-- * Client-side connections
, connectTo
-- * Simple sending and receiving
{-$sendrecv-}
, sendTo
, recvFrom
-- * Miscellaneous
, socketPort
-- * Networking Issues
-- ** Buffering
{-$buffering-}
-- ** Improving I\/O Performance over sockets
{-$performance-}
-- ** @SIGPIPE@
{-$sigpipe-}
) where
import Control.Monad (liftM)
import Data.Maybe (fromJust)
import Network.BSD
import Network.Socket hiding (accept, socketPort, recvFrom,
sendTo, PortNumber, sClose)
import qualified Network.Socket as Socket (accept)
import System.IO
import Prelude
import qualified Control.Exception as Exception
-- ---------------------------------------------------------------------------
-- High Level ``Setup'' functions
-- If the @PortID@ specifies a unix family socket and the @Hostname@
-- differs from that returned by @getHostname@ then an error is
-- raised. Alternatively an empty string may be given to @connectTo@
-- signalling that the current hostname applies.
data PortID =
Service String -- Service Name eg "ftp"
| PortNumber PortNumber -- User defined Port Number
#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)
| UnixSocket String -- Unix family socket in file system
#endif
deriving (Show, Eq)
-- | Calling 'connectTo' creates a client side socket which is
-- connected to the given host and port. The Protocol and socket type is
-- derived from the given port identifier. If a port number is given
-- then the result is always an internet family 'Stream' socket.
connectTo :: HostName -- Hostname
-> PortID -- Port Identifier
-> IO Handle -- Connected Socket
#if defined(IPV6_SOCKET_SUPPORT)
-- IPv6 and IPv4.
connectTo hostname (Service serv) = connect' hostname serv
connectTo hostname (PortNumber port) = connect' hostname (show port)
#else
-- IPv4 only.
connectTo hostname (Service serv) = do
proto <- getProtocolNumber "tcp"
bracketOnError
(socket AF_INET Stream proto)
(sClose) -- only done if there's an error
(\sock -> do
port <- getServicePortNumber serv
he <- getHostByName hostname
connect sock (SockAddrInet port (hostAddress he))
socketToHandle sock ReadWriteMode
)
connectTo hostname (PortNumber port) = do
proto <- getProtocolNumber "tcp"
bracketOnError
(socket AF_INET Stream proto)
(sClose) -- only done if there's an error
(\sock -> do
he <- getHostByName hostname
connect sock (SockAddrInet port (hostAddress he))
socketToHandle sock ReadWriteMode
)
#endif
#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)
connectTo _ (UnixSocket path) = do
bracketOnError
(socket AF_UNIX Stream 0)
(sClose)
(\sock -> do
connect sock (SockAddrUnix path)
socketToHandle sock ReadWriteMode
)
#endif
#if defined(IPV6_SOCKET_SUPPORT)
connect' :: HostName -> ServiceName -> IO Handle
connect' host serv = do
proto <- getProtocolNumber "tcp"
let hints = defaultHints { addrFlags = [AI_ADDRCONFIG]
, addrProtocol = proto
, addrSocketType = Stream }
addrs <- getAddrInfo (Just hints) (Just host) (Just serv)
firstSuccessful $ map tryToConnect addrs
where
tryToConnect addr =
bracketOnError
(socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr))
(sClose) -- only done if there's an error
(\sock -> do
connect sock (addrAddress addr)
socketToHandle sock ReadWriteMode
)
#endif
-- | Creates the server side socket which has been bound to the
-- specified port.
--
-- 'maxListenQueue' (typically 128) is specified to the listen queue.
-- This is good enough for normal network servers but is too small
-- for high performance servers.
--
-- To avoid the \"Address already in use\" problems,
-- the 'ReuseAddr' socket option is set on the listening socket.
--
-- If available, the 'IPv6Only' socket option is set to 0
-- so that both IPv4 and IPv6 can be accepted with this socket.
--
-- If you don't like the behavior above, please use the lower level
-- 'Network.Socket.listen' instead.
listenOn :: PortID -- ^ Port Identifier
-> IO Socket -- ^ Listening Socket
#if defined(IPV6_SOCKET_SUPPORT)
-- IPv6 and IPv4.
listenOn (Service serv) = listen' serv
listenOn (PortNumber port) = listen' (show port)
#else
-- IPv4 only.
listenOn (Service serv) = do
proto <- getProtocolNumber "tcp"
bracketOnError
(socket AF_INET Stream proto)
(sClose)
(\sock -> do
port <- getServicePortNumber serv
setSocketOption sock ReuseAddr 1
bindSocket sock (SockAddrInet port iNADDR_ANY)
listen sock maxListenQueue
return sock
)
listenOn (PortNumber port) = do
proto <- getProtocolNumber "tcp"
bracketOnError
(socket AF_INET Stream proto)
(sClose)
(\sock -> do
setSocketOption sock ReuseAddr 1
bindSocket sock (SockAddrInet port iNADDR_ANY)
listen sock maxListenQueue
return sock
)
#endif
#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)
listenOn (UnixSocket path) =
bracketOnError
(socket AF_UNIX Stream 0)
(sClose)
(\sock -> do
setSocketOption sock ReuseAddr 1
bindSocket sock (SockAddrUnix path)
listen sock maxListenQueue
return sock
)
#endif
#if defined(IPV6_SOCKET_SUPPORT)
listen' :: ServiceName -> IO Socket
listen' serv = do
proto <- getProtocolNumber "tcp"
-- We should probably specify addrFamily = AF_INET6 and the filter
-- code below should be removed. AI_ADDRCONFIG is probably not
-- necessary. But this code is well-tested. So, let's keep it.
let hints = defaultHints { addrFlags = [AI_ADDRCONFIG, AI_PASSIVE]
, addrSocketType = Stream
, addrProtocol = proto }
addrs <- getAddrInfo (Just hints) Nothing (Just serv)
-- Choose an IPv6 socket if exists. This ensures the socket can
-- handle both IPv4 and IPv6 if v6only is false.
let addrs' = filter (\x -> addrFamily x == AF_INET6) addrs
addr = if null addrs' then head addrs else head addrs'
bracketOnError
(socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr))
(sClose)
(\sock -> do
setSocketOption sock ReuseAddr 1
bindSocket sock (addrAddress addr)
listen sock maxListenQueue
return sock
)
#endif
-- -----------------------------------------------------------------------------
-- accept
-- | Accept a connection on a socket created by 'listenOn'. Normal
-- I\/O operations (see "System.IO") can be used on the 'Handle'
-- returned to communicate with the client.
-- Notice that although you can pass any Socket to Network.accept,
-- only sockets of either AF_UNIX, AF_INET, or AF_INET6 will work
-- (this shouldn't be a problem, though). When using AF_UNIX, HostName
-- will be set to the path of the socket and PortNumber to -1.
--
accept :: Socket -- ^ Listening Socket
-> IO (Handle,
HostName,
PortNumber) -- ^ Triple of: read\/write 'Handle' for
-- communicating with the client,
-- the 'HostName' of the peer socket, and
-- the 'PortNumber' of the remote connection.
accept sock@(MkSocket _ AF_INET _ _ _) = do
~(sock', (SockAddrInet port haddr)) <- Socket.accept sock
peer <- catchIO
(do
(HostEntry peer _ _ _) <- getHostByAddr AF_INET haddr
return peer
)
(\_e -> inet_ntoa haddr)
-- if getHostByName fails, we fall back to the IP address
handle <- socketToHandle sock' ReadWriteMode
return (handle, peer, port)
#if defined(IPV6_SOCKET_SUPPORT)
accept sock@(MkSocket _ AF_INET6 _ _ _) = do
(sock', addr) <- Socket.accept sock
peer <- catchIO ((fromJust . fst) `liftM` getNameInfo [] True False addr) $
\_ -> case addr of
SockAddrInet _ a -> inet_ntoa a
SockAddrInet6 _ _ a _ -> return (show a)
# if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)
SockAddrUnix a -> return a
# endif
handle <- socketToHandle sock' ReadWriteMode
let port = case addr of
SockAddrInet p _ -> p
SockAddrInet6 p _ _ _ -> p
_ -> -1
return (handle, peer, port)
#endif
#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)
accept sock@(MkSocket _ AF_UNIX _ _ _) = do
~(sock', (SockAddrUnix path)) <- Socket.accept sock
handle <- socketToHandle sock' ReadWriteMode
return (handle, path, -1)
#endif
accept (MkSocket _ family _ _ _) =
error $ "Sorry, address family " ++ (show family) ++ " is not supported!"
-- | Close the socket. All future operations on the socket object will fail.
-- The remote end will receive no more data (after queued data is flushed).
sClose :: Socket -> IO ()
sClose = close -- Explicit redefinition because Network.sClose is deperecated,
-- hence the re-export would also be marked as such.
-- -----------------------------------------------------------------------------
-- sendTo/recvFrom
{-$sendrecv
Send and receive data from\/to the given host and port number. These
should normally only be used where the socket will not be required for
further calls. Also, note that due to the use of 'hGetContents' in 'recvFrom'
the socket will remain open (i.e. not available) even if the function already
returned. Their use is strongly discouraged except for small test-applications
or invocations from the command line.
-}
sendTo :: HostName -- Hostname
-> PortID -- Port Number
-> String -- Message to send
-> IO ()
sendTo h p msg = do
s <- connectTo h p
hPutStr s msg
hClose s
recvFrom :: HostName -- Hostname
-> PortID -- Port Number
-> IO String -- Received Data
#if defined(IPV6_SOCKET_SUPPORT)
recvFrom host port = do
proto <- getProtocolNumber "tcp"
let hints = defaultHints { addrFlags = [AI_ADDRCONFIG]
, addrProtocol = proto
, addrSocketType = Stream }
allowed <- map addrAddress `liftM` getAddrInfo (Just hints) (Just host)
Nothing
s <- listenOn port
let waiting = do
(s', addr) <- Socket.accept s
if not (addr `oneOf` allowed)
then sClose s' >> waiting
else socketToHandle s' ReadMode >>= hGetContents
waiting
where
a@(SockAddrInet _ ha) `oneOf` ((SockAddrInet _ hb):bs)
| ha == hb = True
| otherwise = a `oneOf` bs
a@(SockAddrInet6 _ _ ha _) `oneOf` ((SockAddrInet6 _ _ hb _):bs)
| ha == hb = True
| otherwise = a `oneOf` bs
_ `oneOf` _ = False
#else
recvFrom host port = do
ip <- getHostByName host
let ipHs = hostAddresses ip
s <- listenOn port
let
waiting = do
~(s', SockAddrInet _ haddr) <- Socket.accept s
he <- getHostByAddr AF_INET haddr
if not (any (`elem` ipHs) (hostAddresses he))
then do
sClose s'
waiting
else do
h <- socketToHandle s' ReadMode
msg <- hGetContents h
return msg
message <- waiting
return message
#endif
-- ---------------------------------------------------------------------------
-- Access function returning the port type/id of socket.
-- | Returns the 'PortID' associated with a given socket.
socketPort :: Socket -> IO PortID
socketPort s = do
sockaddr <- getSocketName s
return (portID sockaddr)
where
portID sa =
case sa of
SockAddrInet port _ -> PortNumber port
#if defined(IPV6_SOCKET_SUPPORT)
SockAddrInet6 port _ _ _ -> PortNumber port
#endif
#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)
SockAddrUnix path -> UnixSocket path
#endif
-- ---------------------------------------------------------------------------
-- Utils
-- Like bracket, but only performs the final action if there was an
-- exception raised by the middle bit.
bracketOnError
:: IO a -- ^ computation to run first (\"acquire resource\")
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracketOnError = Exception.bracketOnError
-----------------------------------------------------------------------------
-- Extra documentation
{-$buffering
The 'Handle' returned by 'connectTo' and 'accept' is block-buffered by
default. For an interactive application you may want to set the
buffering mode on the 'Handle' to
'LineBuffering' or 'NoBuffering', like so:
> h <- connectTo host port
> hSetBuffering h LineBuffering
-}
{-$performance
For really fast I\/O, it might be worth looking at the 'hGetBuf' and
'hPutBuf' family of functions in "System.IO".
-}
{-$sigpipe
On Unix, when writing to a socket and the reading end is
closed by the remote client, the program is normally sent a
@SIGPIPE@ signal by the operating system. The
default behaviour when a @SIGPIPE@ is received is
to terminate the program silently, which can be somewhat confusing
if you haven't encountered this before. The solution is to
specify that @SIGPIPE@ is to be ignored, using
the POSIX library:
> import Posix
> main = do installHandler sigPIPE Ignore Nothing; ...
-}
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#if MIN_VERSION_base(4,0,0)
catchIO = Exception.catch
#else
catchIO = Exception.catchJust Exception.ioErrors
#endif
-- Returns the first action from a list which does not throw an exception.
-- If all the actions throw exceptions (and the list of actions is not empty),
-- the last exception is thrown.
firstSuccessful :: [IO a] -> IO a
firstSuccessful [] = error "firstSuccessful: empty list"
firstSuccessful (p:ps) = catchIO p $ \e ->
case ps of
[] -> Exception.throwIO e
_ -> firstSuccessful ps
| bjornbm/network | Network.hs | bsd-3-clause | 15,722 | 0 | 15 | 4,103 | 2,174 | 1,167 | 1,007 | 162 | 2 |
module Chp84
where
{-- Functor typeclass --}
{--
And now, we're going to take a look at the Functor typeclass, which is basically for things that can be mapped over.
You're probably thinking about lists now, since mapping over lists is such a dominant idiom in Haskell. And you're right, the list type is part of the Functor typeclass.
class Functor f where
fmap :: (a -> b) -> f a -> f b
quick refresher example: Maybe Int is a concrete type, but Maybe is a type constructor that takes one type as the parameter.
Anyway, we see that fmap takes a function from one type to another, a functor applied with one type, and returns a functor applied with another type.
--}
{--
this type declaration for fmap reminds me of something. If you don't know what the type signature of map is, it's: map :: (a -> b) -> [a] -> [b]
map is just a fmap that works only on lists. Here's how the list is an instance of the Functor typeclass:
instance Functor [] where
fmap = map
--}
{--
What happens when we map or fmap over an empty list? Well, of course, we get an empty list.
It just turns an empty list of type [a] into an empty list of type [b].
--}
{--
Types that can act like a box can be functors.
You can think of a list as a box that has an infinite amount of little compartments and they can all be empty, one can be full and the others empty or a number of them can be full.
So, what else has the properties of being like a box? For one, the "Maybe a" type.
instance Functor Maybe where
fmap f (Just x) = Just (f x)
fmap f Nothing = Nothing
--}
res1 = fmap (++ " HEY GUYS IM INSIDE THE JUST") (Just "Something serious.")
{--
Again, notice how we wrote instance Functor Maybe where instead of instance Functor (Maybe m) where, like we did when we were dealing with Maybe and YesNo. Then Functor wants a type constructor that takes one type and not a concrete type.
class Functor f where
fmap :: (a -> b) -> f a -> f b
If you mentally replace the f to Maybe, fmap acts like a (a -> b) -> Maybe a -> Maybe b for this particular type, which looks OK.
But if you replace f with (Maybe m), then it would seem to act like a (a -> b) -> Maybe m a -> Maybe m b, which doesn't make any damn sense because Maybe takes just one type parameter.
invalid
instance Functor (Maybe m) where
fmap ???
fmap ???
--}
{--
If you look at fmap as if it were a function made only for Tree, its type signature would look like (a -> b) -> Tree a -> Tree b.
We're going to use recursion on this one.
1. Mapping over an empty tree will produce an empty tree.
2. Mapping over a non-empty tree will be a tree consisting of our function applied to the root value and its left and right sub-trees will be the previous sub-trees, only our function will be mapped over them.
--}
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
instance Functor Tree where
fmap f EmptyTree = EmptyTree
fmap f (Node x leftsub rightsub) = Node (f x) (fmap f leftsub) (fmap f rightsub)
{--
Now how about Either a b? Can this be made a functor? The Functor typeclass wants a type constructor that takes only one type parameter but Either takes two.
Hmmm! I know, we'll partially apply Either by feeding it only one parameter so that it has one free parameter.
Here's how Either a is a functor in the standard libraries:
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
--}
{--
Functors should obey some laws so that they may have some properties that we can depend on and not think about too much.
If we use fmap (+1) over the list [1,2,3,4], we expect the result to be [2,3,4,5] and not its reverse, [5,4,3,2].
If we use fmap (\a -> a) (the identity function, which just returns its parameter) over some list, we expect to get back the same list as a result.
--}
{-- Kinds and some type-foo
Type constructors take other types as parameters to eventually produce concrete types. That kind of reminds me of functions, which take values as parameters to produce values.
We've seen that type constructors can be partially applied (Either String is a type that takes one type and produces a concrete type, like Either String Int), just like functions can.
--}
{--
So, values like 3, "YEAH" or takeWhile (functions are also values, because we can pass them around and such) each have their own type.
Types are little labels that values carry so that we can reason about the values. But types have their own little labels, called kinds.
A kind is more or less the type of a type.
let's examine the kind of a type by using the :k command in GHCI.
ghci> :k Int
Int :: *
A * means that the type is a concrete type. A concrete type is a type that doesn't take any type parameters and values can only have types that are concrete types.
ghci> :k Maybe
Maybe :: * -> *
The Maybe type constructor takes one concrete type (like Int) and then returns a concrete type like Maybe Int.
And that's what this kind tells us. Just like Int -> Int means that a function takes an Int and returns an Int, * -> * means that the type constructor takes one concrete type and returns a concrete type.
ghci> :k Maybe Int
Maybe Int :: *
We applied the type parameter to Maybe and got back a concrete type (that's what * -> * means.
A parallel (although not equivalent, types and kinds are two different things) to this is if we do :t isUpper and :t isUpper 'A'.
isUpper has a type of Char -> Bool and isUpper 'A' has a type of Bool,
We used :k on a type to get its kind, just like we can use :t on a value to get its type. Like we said, types are the labels of values and kinds are the labels of types and there are parallels between the two.
--}
{--
ghci> :k Either
Either :: * -> * -> *
It also looks kind of like a type declaration of a function that takes two values and returns something.
Type constructors are curried (just like functions), so we can partially apply them.
ghci> :k Either String
Either String :: * -> *
ghci> :k Either String Int
Either String Int :: *
--}
{--
When we wanted to make Either a part of the Functor typeclass, we had to partially apply it because Functor wants types that take only one parameter while Either takes two.
In other words, Functor wants types of kind * -> * and so we had to partially apply Either to get a type of kind * -> * instead of its original kind * -> * -> *. If we look at the definition of Functor again
class Functor f where
fmap :: (a -> b) -> f a -> f b
we see that the f type variable is used as a type that takes one concrete type to produce a concrete type. We know it has to produce a concrete type because it's used as the type of a value in a function.
And from that, we can deduce that types that want to be friends with Functor have to be of kind * -> *. (imply by f a, or f b)
--}
{--
class Tofu t where
tofu :: j a -> t a j
Because j a is used as the type of a value that the tofu function takes as its parameter, j a has to have a kind of *
So kind:
j :: * -> *
t :: * -> (* -> *) -> *
We assume * for a and so we can infer that j has to have a kind of * -> *.
We see that t has to produce a concrete value too and that it takes two types. And knowing that a has a kind of * and j has a kind of * -> *, we infer that t has to have a kind of * -> (* -> *) -> *.
So it takes a concrete type (a), a type constructor that takes one concrete type (j), and produces a concrete type.
so let's make a type with a kind of * -> (* -> *) -> *. Here's one way of going about it.
data Frank a b = Frank {frankField :: b a} deriving (Show)
How do we know this type has a kind of * -> (* -> *) - > *?
Well, fields in ADTs are made to hold values, so they must be of kind *, obviously.
We assume * for a, which means that b takes one type parameter and so its kind is * -> *.
Now we know the kinds of both a and b and because they're parameters for Frank, we see that Frank has a kind of * -> (* -> *) -> * The first * represents a and the (* -> *) represents b.
Let's make some Frank values and check out their types.
:t Frank {frankField = Just "HAHA"}
-- Frank {frankField = Just "HAHA"} :: Frank [Char] Maybe
:t Frank {frankField = "YES"}
-- Frank {frankField = "YES"} :: Frank Char []
--}
{--
Making Frank an instance of Tofu is pretty simple. We see that tofu takes a "j a" (so an example type of that form would be Maybe Int) and returns a "t a j".
So if we replace Frank with j, the result type would be Frank Int Maybe.
instance Tofu Frank where
tofu x = Frank x
ghci> tofu (Just 'a') :: Frank Char Maybe
Frank {frankField = Just 'a'}
ghci> tofu ["HELLO"] :: Frank [Char] []
Frank {frankField = ["HELLO"]}
--}
{--
Example:
data Barry t k p = Barry { yabba :: p, dabba :: t k }
ghci> :k Barry
Barry :: (* -> *) -> * -> * -> *
Now, to make this type a part of Functor we have to partially apply the first two type parameters so that we're left with * -> *.
That means that the start of the instance declaration will be: instance Functor (Barry a b) where.
If we look at fmap as if it was made specifically for Barry, it would have a type of fmap :: (a -> b) -> Barry c d a -> Barry c d b, because we just replace the Functor's "f" with "Barry c d". The third type parameter from Barry will have to change and we see that it's conviniently in its own field.
instance Functor (Barry a b) where
fmap f (Barry {yabba = x, dabba = y}) = Barry {yabba = f x, dabba = y}
--}
| jamesyang124/haskell-playground | src/Chp84.hs | bsd-3-clause | 9,801 | 0 | 8 | 2,173 | 312 | 163 | 149 | 14 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Cloud.AWS.RDS.Event
( describeEvents
, describeEventCategories
) where
import Cloud.AWS.Lib.Parser.Unordered (XmlElement, (.<), content)
import Control.Applicative
import Control.Monad.Trans.Resource (MonadThrow, MonadResource, MonadBaseControl)
import Data.Text (Text)
import Data.Time (UTCTime)
import Cloud.AWS.Lib.Query
import Cloud.AWS.RDS.Internal
import Cloud.AWS.RDS.Types
describeEvents
:: (MonadBaseControl IO m, MonadResource m)
=> Maybe Text -- ^ SourceIdentifier
-> Maybe SourceType -- ^ SourceType
-> Maybe Int -- ^ Duration
-> Maybe UTCTime -- ^ StartTime
-> Maybe UTCTime -- ^ EndTime
-> [Text] -- ^ EventCategories.member
-> Maybe Text -- ^ Marker
-> Maybe Int -- ^ MaxRecords
-> RDS m [Event]
describeEvents sid stype d start end categories marker maxRecords =
rdsQuery "DescribeEvents" params $
elements "Event" eventSink
where
params =
[ "SourceIdentifier" |=? sid
, "SourceType" |=? stype
, "Duration" |=? d
, "StartTime" |=? start
, "EndTime" |=? end
, "EventCategories" |.+ "member" |.#= categories
, "Marker" |=? marker
, "MaxRecords" |=? maxRecords
]
eventSink
:: (MonadThrow m, Applicative m)
=> XmlElement -> m Event
eventSink xml = Event
<$> xml .< "Message"
<*> xml .< "SourceType"
<*> elements' "EventCategories" "EventCategory" content xml
<*> xml .< "Date"
<*> xml .< "SourceIdentifier"
describeEventCategories
:: (MonadBaseControl IO m, MonadResource m)
=> Maybe SourceType -- ^ SourceType
-> RDS m [EventCategoriesMap]
describeEventCategories stype =
rdsQuery "DescribeEventCategories" params $
elements' "EventCategoriesMapList" "EventCategoriesMap" eventCategoriesMapSink
where
params = [ "SourceType" |=? stype ]
eventCategoriesMapSink
:: (MonadThrow m, Applicative m)
=> XmlElement -> m EventCategoriesMap
eventCategoriesMapSink xml = EventCategoriesMap
<$> xml .< "SourceType"
<*> elements' "EventCategories" "EventCategory" content xml
| worksap-ate/aws-sdk | Cloud/AWS/RDS/Event.hs | bsd-3-clause | 2,140 | 0 | 15 | 470 | 511 | 280 | 231 | 58 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.NV.PixelDataRange
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/NV/pixel_data_range.txt NV_pixel_data_range> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.NV.PixelDataRange (
-- * Enums
gl_READ_PIXEL_DATA_RANGE_LENGTH_NV,
gl_READ_PIXEL_DATA_RANGE_NV,
gl_READ_PIXEL_DATA_RANGE_POINTER_NV,
gl_WRITE_PIXEL_DATA_RANGE_LENGTH_NV,
gl_WRITE_PIXEL_DATA_RANGE_NV,
gl_WRITE_PIXEL_DATA_RANGE_POINTER_NV,
-- * Functions
glFlushPixelDataRangeNV,
glPixelDataRangeNV
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/NV/PixelDataRange.hs | bsd-3-clause | 963 | 0 | 4 | 106 | 67 | 52 | 15 | 11 | 0 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
-- |
-- Module: Graphics.ChalkBoard.Types
-- Copyright: (c) 2009 Andy Gill
-- License: BSD3
--
-- Maintainer: Andy Gill <[email protected]>
-- Stability: unstable
-- Portability: ghc
--
-- This module contains the types used by chalkboard, except Board itself.
--
module Graphics.ChalkBoard.Types
( -- * Basic types
UI, R, Point, Radian,
-- * Overlaying
Over(..),
stack,
-- * Scaling
Scale(..),
-- * Linear Interpolation
Lerp(..),
-- * Averaging
Average(..),
{-
-- * Alpha Channel support
Alpha(..),
alpha, transparent, withAlpha, unAlpha,
-- * Z buffer support
Z(..),
-}
-- * Constants
nearZero
-- * Colors
, Gray
, RGB(..)
, RGBA(..)
) where
import Data.Binary
import Control.Monad
import Data.Ratio
-- | A real number.
type R = Float
-- | Unit Interval: value between 0 and 1, inclusive.
type UI = R
-- | A point in R2.
type Point = (R,R)
-- | Angle units
type Radian = Float
-- | Close to zero; needed for @Over (Alpha c)@ instance.
nearZero :: R
nearZero = 0.0000001
------------------------------------------------------------------------------
infixr 5 `over`
-- | For placing a value literally /over/ another value. The 2nd value /might/ shine through.
-- The operation /must/ be associative.
class Over c where
over :: c -> c -> c
instance Over Bool where
over = (||)
instance Over (a -> a) where
over = (.)
instance Over (Maybe a) where
(Just a) `over` _ = Just a
Nothing `over` other = other
-- | 'stack' stacks a list of things over each other,
-- where earlier elements are 'over' later elements.
-- Requires non empty lists, which can be satisfied by using an explicitly
-- transparent @Board@ as one of the elements.
stack :: (Over c) => [c] -> c
stack = foldr1 over
------------------------------------------------------------------------------
-- | 'Scale' something by a value. scaling value can be bigger than 1.
class Scale c where
scale :: R -> c -> c
instance Scale R where
scale u v = u * v
instance (Scale a,Scale b) => Scale (a,b) where
scale u (x,y) = (scale u x,scale u y)
instance Scale Rational where
scale u r = toRational u * r
------------------------------------------------------------------------------
-- | Linear interpolation between two values.
class Lerp a where
lerp :: UI -> a -> a -> a
instance Lerp R where
lerp s v v' = v + (s * (v' - v))
instance Lerp Rational where
lerp s v v' = v + (toRational s * (v' - v))
-- | 'Lerp' over pairs
instance (Lerp a,Lerp b) => Lerp (a,b) where
lerp s (a,b) (a',b') = (lerp s a a',lerp s b b')
instance (Lerp a) => Lerp (Maybe a) where
lerp _ Nothing Nothing = Nothing
lerp _ (Just a) Nothing = Just a
lerp _ Nothing (Just b) = Just b
lerp s (Just a) (Just b) = Just (lerp s a b)
------------------------------------------------------------------------------
-- | 'Average' a set of values. weighting can be achived using multiple entries.
class Average a where
-- | average is not defined for empty list
average :: [a] -> a
instance Average R where
average xs = sum xs / fromIntegral (length xs)
instance (Average a,Average b) => Average (a,b) where
average xs = (average $ map fst xs,average $ map snd xs)
------------------------------------------------------------------------------
-- | 'Gray' is just a value between 0 and 1, inclusive.
-- Be careful to consider if this is pre or post gamma.
type Gray = UI
instance Over Gray where
over r _ = r
------------------------------------------------------------------------------
-- Simple colors
-- | 'RGB' is our color, with values between 0 and 1, inclusive.
data RGB = RGB !UI !UI !UI deriving Show
instance Over RGB where
-- simple overwriting
over x _y = x
instance Lerp RGB where
lerp s (RGB r g b) (RGB r' g' b')
= RGB (lerp s r r')
(lerp s g g')
(lerp s b b')
instance Scale RGB where
scale s (RGB r g b)
= RGB (scale s r)
(scale s g)
(scale s b)
instance Average RGB where
average cs = RGB (average reds) (average greens) (average blues)
where
reds = [ r | RGB r _ _ <- cs ]
greens = [ g | RGB _ g _ <- cs ]
blues = [ b | RGB _ _ b <- cs ]
-- Consider using 4 bytes for color, rather than 32 bytes for the double (or are they floats?)
instance Binary RGB where
put (RGB r g b) = put r >> put g >> put b
get = liftM3 RGB get get get
------------------------------------------------------------------------------------------
-- Colors with alpha
-- | 'RGBA' is our color, with values between 0 and 1, inclusive.
-- These values are *not* prenormalized
data RGBA = RGBA !UI !UI !UI !UI deriving Show
-- Todo: rethink what this means
instance Over RGBA where
over (RGBA r g b a) (RGBA r' g' b' a') =
RGBA (f r r') -- (SrcAlpha, OneMinusSrcAlpha)
(f g g')
(f b b')
(a + a' * (1 - a)) -- (One, OneMinusSrcAlpha)
where f x y = a * y + (1 - a) * x
{-
-- An associative algorithm for handling the alpha channel
-- Associative; please reinstate later
| a <= nearZero = RGBA r' g' b' a_new
| otherwise = RGBA
(lerp r' (scale (1/a) r) a)
(lerp g' (scale (1/a) g) a)
(lerp b' (scale (1/a) b) a)
a_new
where
-- can a_new be 0? only if a == 0 and a' == 0
a_new = a + a' * (1 - a)
-}
instance Binary RGBA where
put (RGBA r g b a) = put r >> put g >> put b >> put a
get = liftM4 RGBA get get get get
| andygill/chalkboard2 | Graphics/ChalkBoard/Types.hs | bsd-3-clause | 5,487 | 39 | 11 | 1,269 | 1,482 | 802 | 680 | 110 | 1 |
-- | Tools to build and access an AO dictionary.
module AO.Dict
( AODef, AODictMap, AODict
, buildAODict, cleanAODict, emptyAODict
, readAODict, updateAODict, unsafeUpdateAODict
, AODictIssue(..)
) where
import Control.Monad ((>=>))
import Data.Maybe (fromJust)
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as Set
import AO.InnerDict
import AO.Code
-- | An AO definition is a trivial pairing of a word with the AO code
-- that is inlined wherever the word is used. In practice, we want some
-- extra metadata with each definition (e.g. source location).
type AODef meta = (Word,(AO_Code,meta))
-- | A dictionary map is simply a map formed of AO definitions.
type AODictMap meta = M.Map Word (AO_Code,meta)
-- | Access the clean definitions within an AO dictionary.
readAODict :: AODict meta -> AODictMap meta
readAODict (AODict d) = d
-- | update metadata for a word (if it exists)
updateAODict :: (AO_Code -> meta -> meta) -> Word -> AODict meta -> AODict meta
updateAODict fn w (AODict d) = case M.lookup w d of
Nothing -> (AODict d)
Just (code,meta) ->
let meta' = fn code meta in
AODict (M.insert w (code,meta') d)
-- | allow arbitrary manipulations if we really want them
-- but at least mark them clearly. Try to use safely - i.e.
-- adding annotations, inlining and partial evaluations, etc.
unsafeUpdateAODict :: (AODictMap m -> AODictMap m) -> (AODict m -> AODict m)
unsafeUpdateAODict f (AODict d) = AODict (f d)
-- | useful for initializations
emptyAODict :: AODict meta
emptyAODict = AODict (M.empty)
-- | to report problems with a dictionary while cleaning it up.
--
-- Override: multiple definitions are provided for a word, in the
-- order given. The last definition in this list is kept in the
-- dictionary, unless there's some other issue with it.
--
-- Cycle: a word is transitively part of a cycle, and thus its
-- definition cannot be fully inlined (as per AO semantics). Where
-- conventional languages use recursion, AO uses explicit fixpoint.
-- A good fixpoint combinator is: %r [%^'wol] %rwo^'wol
--
-- Cycles are removed from the dictionary after being recognized,
-- such that any given word is recognized as part of at most one
-- cycle. This may result in missing definition warnings.
--
-- Missing: a definition uses words that are not part of the
-- dictionary. All such definitions are removed from the dictionary.
--
data AODictIssue meta
= AODefOverride Word [(AO_Code,meta)] -- multiple definitions for one word.
| AODefCycle [AODef meta] -- a cycle of words
| AODefMissing (AODef meta) [Word] -- definition is missing words in list
-- a warning capability
type ReportIssue m meta = AODictIssue meta -> m ()
-- | given a list of definitions, produce a 'clean' dictionary (no cycles,
-- no incompletely defined words) and also generate some warnings or errors.
buildAODict :: (Monad m) => ReportIssue m meta -> [AODef meta] -> m (AODict meta)
buildAODict warn = getFinalDefs warn >=> cleanAODict warn
-- build a map and report overrides
getFinalDefs :: (Monad m) => ReportIssue m meta -> [AODef meta] -> m (AODictMap meta)
getFinalDefs warn defs =
let mdict = L.foldl mmins M.empty defs in -- (word,(cm,[cm]))
let dictOfFinalDefs = fmap fst mdict in -- (word,cm)
let lOverrides = M.toList $ fmap (L.reverse . uncurry (:))
$ M.filter (not . null . snd) mdict
in
mapM_ (warn . uncurry AODefOverride) lOverrides >>
return dictOfFinalDefs
mmins :: (Ord k) => M.Map k (a,[a]) -> (k,a) -> M.Map k (a,[a])
mmins d (k,a) = M.alter (mmcons a) k d where
mmcons a0 Nothing = Just (a0,[])
mmcons a0 (Just (a1,as)) = Just (a0,(a1:as))
-- | cleanup a map by removing words with cyclic or incomplete definitions
cleanAODict :: (Monad m) => ReportIssue m meta -> AODictMap meta -> m (AODict meta)
cleanAODict warn = clearCycles warn >=> clearMissing warn >=> return . AODict
clearCycles :: (Monad m) => ReportIssue m meta -> AODictMap meta -> m (AODictMap meta)
clearCycles warn d0 = emitErrors >> return cycleFree where
g0 = fmap (aoWords . fst) d0 -- M.Map Word [Word]
cycles = detectCycles g0 -- [[Word]]
cycleFree = L.foldr M.delete d0 (L.concat cycles)
emitErrors = mapM_ reportCycle cycles
reportCycle = warn . AODefCycle . fmap getData
getData w = (w, fromJust (M.lookup w d0)) -- recover def & meta
-- by nature, any word in a cycle must be defined
-- so 'fromJust' is safe here
-- detect cycles in an abstract directed graph
-- using a depth-first search
detectCycles :: (Ord v) => M.Map v [v] -> [[v]]
detectCycles = deforest where
deforest g = case M.minViewWithKey g of
Nothing -> []
Just ((v0,vs),_) ->
let (visited, cycles) = dfs g [v0] [v0] vs in
let g' = L.foldr M.delete g visited in
cycles ++ deforest g'
dfs _ cx _ [] = (cx, [])
dfs g cx p (v:vs) =
case (L.elemIndex v p) of
Nothing -> -- no loop; may need to visit 'v'
if L.elem v cx then dfs g cx p vs else
let (cxd,cycd) = dfs g (v:cx) (v:p) (edgesFrom g v) in
let (cxw,cycw) = dfs g cxd p vs in
(cxw, cycd ++ cycw)
Just n -> -- loop found; 'v' necessarily has been visited
let cyc0 = L.reverse (L.take (n + 1) p) in
let (cxw,cycw) = dfs g cx p vs in
(cxw,(cyc0:cycw))
edgesFrom g v = maybe [] id $ M.lookup v g
-- keep only words whose definitions are transitively fully defined
clearMissing :: (Monad m) => ReportIssue m meta -> AODictMap meta -> m (AODictMap meta)
clearMissing warn d0 = emitErrors >> return fullyDefined where
g0 = fmap (aoWords . fst) d0 --
mwMap = incompleteWords g0
fullyDefined = L.foldr M.delete d0 (M.keys mwMap)
emitErrors = mapM_ reportError (M.toList mwMap)
reportError = warn . mkWarning
mkWarning (w,mws) = -- w is in dictionary; mws aren't
let defW = fromJust (M.lookup w d0) in
AODefMissing (w,defW) mws
-- find incomplete words based on missing transitive dependencies
-- the result is a map of word -> missing words.
incompleteWords :: (Ord w) => M.Map w [w] -> M.Map w [w]
incompleteWords dict = dictMW where
(dictMW, _okSet) = L.foldl cw (M.empty, Set.empty) (M.keys dict)
cw r w =
if (M.member w (fst r) || Set.member w (snd r)) then r else
case M.lookup w dict of
Nothing -> r -- w is missing word; will capture in 'mdeps' below
Just deps ->
let (dmw, dok) = L.foldl cw r deps in
let mdeps = L.filter (`Set.notMember` dok) deps in
if null mdeps
then (dmw, Set.insert w dok) -- add word to OK set
else (M.insert w mdeps dmw, dok) -- add word to missing words map
| dmbarbour/awelon | hsrc/AO/Dict.hs | bsd-3-clause | 6,940 | 0 | 18 | 1,726 | 1,976 | 1,052 | 924 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : Morphism of Common Logic
Copyright : (c) Uni Bremen DFKI 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (via Logic.Logic)
Morphism of Common Logic
-}
module CommonLogic.Morphism
( Morphism (..)
, pretty -- pretty printing
, idMor -- identity morphism
, isLegalMorphism -- check if morhpism is ok
, composeMor -- composition
, inclusionMap -- inclusion map
, mkMorphism -- create Morphism
, mapSentence -- map of sentences
, applyMap -- application function for maps
, applyMorphism -- application function for morphism
, morphismUnion
) where
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Common.Result as Result
import Common.Id as Id
import Common.Result
import Common.Doc
import Common.DocUtils
import CommonLogic.AS_CommonLogic as AS
import CommonLogic.Sign as Sign
import Control.Monad (unless)
import Data.Data
-- maps of sets
data Morphism = Morphism
{ source :: Sign
, target :: Sign
, propMap :: Map.Map Id Id
} deriving (Eq, Ord, Show, Typeable)
instance Pretty Morphism where
pretty = printMorphism
-- | Constructs an id-morphism
idMor :: Sign -> Morphism
idMor a = inclusionMap a a
-- | Determines whether a morphism is valid
isLegalMorphism :: Morphism -> Result ()
isLegalMorphism pmor =
let psource = allItems $ source pmor
ptarget = allItems $ target pmor
pdom = Map.keysSet $ propMap pmor
pcodom = Set.map (applyMorphism pmor) psource
in unless (Set.isSubsetOf pcodom ptarget && Set.isSubsetOf pdom psource) $
fail "illegal CommonLogic morphism"
-- | Application funtion for morphisms
applyMorphism :: Morphism -> Id -> Id
applyMorphism mor idt = Map.findWithDefault idt idt $ propMap mor
-- | Application function for propMaps
applyMap :: Map.Map Id Id -> Id -> Id
applyMap pmap idt = Map.findWithDefault idt idt pmap
-- | Composition of morphisms in propositional Logic
composeMor :: Morphism -> Morphism -> Result Morphism
composeMor f g =
let fSource = source f
gTarget = target g
fMap = propMap f
gMap = propMap g
in return Morphism
{ source = fSource
, target = gTarget
, propMap = if Map.null gMap then fMap else
Set.fold ( \ i -> let j = applyMap gMap (applyMap fMap i) in
if i == j then id else Map.insert i j)
Map.empty $ allItems fSource }
-- | Pretty printing for Morphisms
printMorphism :: Morphism -> Doc
printMorphism m = pretty (source m) <> text "-->" <> pretty (target m)
<> vcat (map ( \ (x, y) -> lparen <> pretty x <> text ","
<> pretty y <> rparen) $ Map.assocs $ propMap m)
-- | Inclusion map of a subsig into a supersig
inclusionMap :: Sign.Sign -> Sign.Sign -> Morphism
inclusionMap s1 s2 = Morphism
{ source = s1
, target = s2
, propMap = Map.empty }
-- | creates a Morphism
mkMorphism :: Sign.Sign -> Sign.Sign -> Map.Map Id Id -> Morphism
mkMorphism s t p =
Morphism { source = s
, target = t
, propMap = p }
{- | sentence (text) translation along signature morphism
here just the renaming of formulae -}
mapSentence :: Morphism -> AS.TEXT_META -> Result.Result AS.TEXT_META
mapSentence mor tm =
return $ tm { getText = mapSen_txt mor $ getText tm }
-- propagates the translation to sentences
mapSen_txt :: Morphism -> AS.TEXT -> AS.TEXT
mapSen_txt mor txt = case txt of
AS.Text phrs r -> AS.Text (map (mapSen_phr mor) phrs) r
AS.Named_text n t r -> AS.Named_text n (mapSen_txt mor t) r
-- propagates the translation to sentences
mapSen_phr :: Morphism -> AS.PHRASE -> AS.PHRASE
mapSen_phr mor phr = case phr of
AS.Module m -> AS.Module $ mapSen_mod mor m
AS.Sentence s -> AS.Sentence $ mapSen_sen mor s
AS.Comment_text c t r -> AS.Comment_text c (mapSen_txt mor t) r
x -> x
-- propagates the translation to sentences
mapSen_mod :: Morphism -> AS.MODULE -> AS.MODULE
mapSen_mod mor m = case m of
AS.Mod n t rn -> AS.Mod n (mapSen_txt mor t) rn
AS.Mod_ex n exs t rn -> AS.Mod_ex n exs (mapSen_txt mor t) rn
mapSen_sen :: Morphism -> AS.SENTENCE -> AS.SENTENCE
mapSen_sen mor frm = case frm of
AS.Quant_sent q vs is rn ->
AS.Quant_sent q (map (mapSen_nos mor) vs) (mapSen_sen mor is) rn
AS.Bool_sent bs rn -> AS.Bool_sent (case bs of
AS.Junction j sens -> AS.Junction j (map (mapSen_sen mor) sens)
AS.Negation sen -> AS.Negation (mapSen_sen mor sen)
AS.BinOp op s1 s2 ->
AS.BinOp op (mapSen_sen mor s1) (mapSen_sen mor s2)
) rn
AS.Atom_sent atom rn -> AS.Atom_sent (case atom of
AS.Equation t1 t2 -> AS.Equation (mapSen_trm mor t1) (mapSen_trm mor t2)
AS.Atom t tss -> AS.Atom (mapSen_trm mor t) (map (mapSen_trmSeq mor) tss)
) rn
AS.Comment_sent cm sen rn -> AS.Comment_sent cm (mapSen_sen mor sen) rn
AS.Irregular_sent sen rn -> AS.Irregular_sent (mapSen_sen mor sen) rn
mapSen_trm :: Morphism -> AS.TERM -> AS.TERM
mapSen_trm mor trm = case trm of
AS.Name_term n -> AS.Name_term (mapSen_tok mor n)
AS.Funct_term t ts rn ->
AS.Funct_term (mapSen_trm mor t) (map (mapSen_trmSeq mor) ts) rn
AS.Comment_term t c rn -> AS.Comment_term (mapSen_trm mor t) c rn
AS.That_term s rn -> AS.That_term (mapSen_sen mor s) rn
mapSen_nos :: Morphism -> AS.NAME_OR_SEQMARK -> AS.NAME_OR_SEQMARK
mapSen_nos mor nos = case nos of
AS.Name n -> AS.Name (mapSen_tok mor n)
AS.SeqMark s -> AS.SeqMark (mapSen_tok mor s)
mapSen_trmSeq :: Morphism -> AS.TERM_SEQ -> AS.TERM_SEQ
mapSen_trmSeq mor ts = case ts of
AS.Term_seq t -> AS.Term_seq (mapSen_trm mor t)
AS.Seq_marks s -> AS.Seq_marks (mapSen_tok mor s)
mapSen_tok :: Morphism -> Id.Token -> Id.Token
mapSen_tok mor tok = Id.idToSimpleId $ applyMorphism mor $ Id.simpleIdToId tok
-- | Union of two morphisms.
morphismUnion :: Morphism -> Morphism -> Result.Result Morphism
morphismUnion mor1 mor2 =
let pmap1 = propMap mor1
pmap2 = propMap mor2
p1 = source mor1
p2 = source mor2
up1 = Set.difference (allItems p1) $ Map.keysSet pmap1
up2 = Set.difference (allItems p2) $ Map.keysSet pmap2
(pds, pmap) = foldr ( \ (i, j) (ds, m) -> case Map.lookup i m of
Nothing -> (ds, Map.insert i j m)
Just k -> if j == k then (ds, m) else
(Diag Error
("incompatible mapping of prop " ++ showId i " to "
++ showId j " and " ++ showId k "")
nullRange : ds, m))
([], pmap1)
(Map.toList pmap2 ++ map (\ a -> (a, a))
(Set.toList $ Set.union up1 up2))
in if null pds then return Morphism
{ source = unite p1 p2
, target = unite (target mor1) $ target mor2
, propMap = pmap } else Result pds Nothing
| keithodulaigh/Hets | CommonLogic/Morphism.hs | gpl-2.0 | 7,047 | 0 | 23 | 1,770 | 2,287 | 1,169 | 1,118 | 144 | 8 |
data A = A Int
| B Char
deriving (Eq, Show)
main = (A 3 == A 3, show (B 'q'))
| roberth/uu-helium | test/correct/EqAndShow.hs | gpl-3.0 | 96 | 0 | 8 | 39 | 56 | 29 | 27 | 4 | 1 |
-- |
-- Module: BDCS.Utils.Error
-- Copyright: (c) 2016-2017 Red Hat, Inc.
-- License: LGPL
--
-- Maintainer: https://github.com/weldr
-- Stability: alpha
-- Portability: portable
--
-- Functions to help with errors
module BDCS.Utils.Error(errorToEither,
errorToMaybe,
mapError)
where
import Control.Monad.Except(ExceptT(..), MonadError, catchError, runExceptT, throwError)
-- | Convert an error action into an Either
-- This is essentially 'runExceptT' generalized to 'MonadError'
errorToEither :: MonadError e m => m a -> m (Either e a)
errorToEither action = (Right <$> action) `catchError` (return . Left)
-- | Convert an error into into nothing
errorToMaybe :: MonadError e m => m a -> m (Maybe a)
errorToMaybe action = (Just <$> action) `catchError` (const . return) Nothing
-- | Run an 'ExceptT' action. On error, run a supplied function to convert the error into
-- some type that can be thrown with 'throwError' in 'MonadError'. On success, simply
-- return the value of the action.
mapError :: MonadError e' m => (e -> e') -> ExceptT e m a -> m a
mapError f action = runExceptT action >>= either (throwError . f) return
| atodorov/bdcs | src/BDCS/Utils/Error.hs | lgpl-2.1 | 1,187 | 0 | 9 | 238 | 250 | 141 | 109 | 10 | 1 |
-- Tests for Statistics.Test.NonParametric
module Tests.NonParametric (tests) where
import Statistics.Distribution.Normal (standard)
import Statistics.Test.KolmogorovSmirnov
import Statistics.Test.MannWhitneyU
import Statistics.Test.KruskalWallis
import Statistics.Test.WilcoxonT
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit
import Test.HUnit (assertEqual)
import Tests.ApproxEq (eq)
import Tests.Helpers (testAssertion, testEquality)
import Tests.NonParametric.Table (tableKSD, tableKS2D)
import qualified Data.Vector.Unboxed as U
tests :: Test
tests = testGroup "Nonparametric tests"
$ concat [ mannWhitneyTests
, wilcoxonSumTests
, wilcoxonPairTests
, kruskalWallisRankTests
, kruskalWallisTests
, kolmogorovSmirnovDTest
]
----------------------------------------------------------------
mannWhitneyTests :: [Test]
mannWhitneyTests = zipWith test [(0::Int)..] testData ++
[ testEquality "Mann-Whitney U Critical Values, m=1"
(replicate (20*3) Nothing)
[mannWhitneyUCriticalValue (1,x) p | x <- [1..20], p <- [0.005,0.01,0.025]]
, testEquality "Mann-Whitney U Critical Values, m=2, p=0.025"
(replicate 7 Nothing ++ map Just [0,0,0,0,1,1,1,1,1,2,2,2,2])
[mannWhitneyUCriticalValue (2,x) 0.025 | x <- [1..20]]
, testEquality "Mann-Whitney U Critical Values, m=6, p=0.05"
(replicate 1 Nothing ++ map Just [0, 2,3,5,7,8,10,12,14,16,17,19,21,23,25,26,28,30,32])
[mannWhitneyUCriticalValue (6,x) 0.05 | x <- [1..20]]
, testEquality "Mann-Whitney U Critical Values, m=20, p=0.025"
(replicate 1 Nothing ++ map Just [2,8,14,20,27,34,41,48,55,62,69,76,83,90,98,105,112,119,127])
[mannWhitneyUCriticalValue (20,x) 0.025 | x <- [1..20]]
]
where
test n (a, b, c, d)
= testCase "Mann-Whitney" $ do
assertEqual ("Mann-Whitney U " ++ show n) c us
assertEqual ("Mann-Whitney U Sig " ++ show n) d ss
where
us = mannWhitneyU (U.fromList a) (U.fromList b)
ss = mannWhitneyUSignificant TwoTailed (length a, length b) 0.05 us
-- List of (Sample A, Sample B, (Positive Rank, Negative Rank))
testData :: [([Double], [Double], (Double, Double), Maybe TestResult)]
testData = [ ( [3,4,2,6,2,5]
, [9,7,5,10,6,8]
, (2, 34)
, Just Significant
)
, ( [540,480,600,590,605]
, [760,890,1105,595,940]
, (2, 23)
, Just Significant
)
, ( [19,22,16,29,24]
, [20,11,17,12]
, (17, 3)
, Just NotSignificant
)
, ( [126,148,85,61, 179,93, 45,189,85,93]
, [194,128,69,135,171,149,89,248,79,137]
, (35,65)
, Just NotSignificant
)
, ( [1..30]
, [1..30]
, (450,450)
, Just NotSignificant
)
, ( [1 .. 30]
, [11.5 .. 40 ]
, (190.0,710.0)
, Just Significant
)
]
wilcoxonSumTests :: [Test]
wilcoxonSumTests = zipWith test [(0::Int)..] testData
where
test n (a, b, c) = testCase "Wilcoxon Sum"
$ assertEqual ("Wilcoxon Sum " ++ show n) c (wilcoxonRankSums (U.fromList a) (U.fromList b))
-- List of (Sample A, Sample B, (Positive Rank, Negative Rank))
testData :: [([Double], [Double], (Double, Double))]
testData = [ ( [8.50,9.48,8.65,8.16,8.83,7.76,8.63]
, [8.27,8.20,8.25,8.14,9.00,8.10,7.20,8.32,7.70]
, (75, 61)
)
, ( [0.45,0.50,0.61,0.63,0.75,0.85,0.93]
, [0.44,0.45,0.52,0.53,0.56,0.58,0.58,0.65,0.79]
, (71.5, 64.5)
)
]
wilcoxonPairTests :: [Test]
wilcoxonPairTests = zipWith test [(0::Int)..] testData ++
-- Taken from the Mitic paper:
[ testAssertion "Sig 16, 35" (to4dp 0.0467 $ wilcoxonMatchedPairSignificance 16 35)
, testAssertion "Sig 16, 36" (to4dp 0.0523 $ wilcoxonMatchedPairSignificance 16 36)
, testEquality "Wilcoxon critical values, p=0.05"
(replicate 4 Nothing ++ map Just [0,2,3,5,8,10,13,17,21,25,30,35,41,47,53,60,67,75,83,91,100,110,119])
[wilcoxonMatchedPairCriticalValue x 0.05 | x <- [1..27]]
, testEquality "Wilcoxon critical values, p=0.025"
(replicate 5 Nothing ++ map Just [0,2,3,5,8,10,13,17,21,25,29,34,40,46,52,58,65,73,81,89,98,107])
[wilcoxonMatchedPairCriticalValue x 0.025 | x <- [1..27]]
, testEquality "Wilcoxon critical values, p=0.01"
(replicate 6 Nothing ++ map Just [0,1,3,5,7,9,12,15,19,23,27,32,37,43,49,55,62,69,76,84,92])
[wilcoxonMatchedPairCriticalValue x 0.01 | x <- [1..27]]
, testEquality "Wilcoxon critical values, p=0.005"
(replicate 7 Nothing ++ map Just [0,1,3,5,7,9,12,15,19,23,27,32,37,42,48,54,61,68,75,83])
[wilcoxonMatchedPairCriticalValue x 0.005 | x <- [1..27]]
]
where
test n (a, b, c) = testEquality ("Wilcoxon Paired " ++ show n) c res
where res = (wilcoxonMatchedPairSignedRank (U.fromList a) (U.fromList b))
-- List of (Sample A, Sample B, (Positive Rank, Negative Rank))
testData :: [([Double], [Double], (Double, Double))]
testData = [ ([1..10], [1..10], (0, 0 ))
, ([1..5], [6..10], (0, 5*(-3)))
-- Worked example from the Internet:
, ( [125,115,130,140,140,115,140,125,140,135]
, [110,122,125,120,140,124,123,137,135,145]
, ( sum $ filter (> 0) [7,-3,1.5,9,0,-4,8,-6,1.5,-5]
, sum $ filter (< 0) [7,-3,1.5,9,0,-4,8,-6,1.5,-5]
)
)
-- Worked examples from books/papers:
, ( [2.4,1.9,2.3,1.9,2.4,2.5]
, [2.0,2.1,2.0,2.0,1.8,2.0]
, (18, -3)
)
, ( [130,170,125,170,130,130,145,160]
, [120,163,120,135,143,136,144,120]
, (27, -9)
)
, ( [540,580,600,680,430,740,600,690,605,520]
, [760,710,1105,880,500,990,1050,640,595,520]
, (3, -42)
)
]
to4dp tgt x = x >= tgt - 0.00005 && x < tgt + 0.00005
----------------------------------------------------------------
kruskalWallisRankTests :: [Test]
kruskalWallisRankTests = zipWith test [(0::Int)..] testData
where
test n (a, b) = testCase "Kruskal-Wallis Ranking"
$ assertEqual ("Kruskal-Wallis " ++ show n) (map U.fromList b) (kruskalWallisRank $ map U.fromList a)
testData = [ ( [ [68,93,123,83,108,122]
, [119,116,101,103,113,84]
, [70,68,54,73,81,68]
, [61,54,59,67,59,70]
]
, [ [8.0,14.0,16.0,19.0,23.0,24.0]
, [15.0,17.0,18.0,20.0,21.0,22.0]
, [1.5,8.0,8.0,10.5,12.0,13.0]
, [1.5,3.5,3.5,5.0,6.0,10.5]
]
)
]
kruskalWallisTests :: [Test]
kruskalWallisTests = zipWith test [(0::Int)..] testData
where
test n (a, b, c) = testCase "Kruskal-Wallis" $ do
assertEqual ("Kruskal-Wallis " ++ show n) (round100 b) (round100 kw)
assertEqual ("Kruskal-Wallis Sig " ++ show n) c kwt
where
kw = kruskalWallis $ map U.fromList a
kwt = kruskalWallisTest 0.05 $ map U.fromList a
round100 :: Double -> Integer
round100 = round . (*100)
testData = [ ( [ [68,93,123,83,108,122]
, [119,116,101,103,113,84]
, [70,68,54,73,81,68]
, [61,54,59,67,59,70]
]
, 16.03
, Just Significant
)
, ( [ [5,5,3,5,5,5,5]
, [5,5,5,5,7,5,5]
, [5,5,6,5,5,5,5]
, [4,5,5,5,6,5,5]
]
, 2.24
, Just NotSignificant
)
, ( [ [36,48,5,67,53]
, [49,33,60,2,55]
, [71,31,140,59,42]
]
, 1.22
, Just NotSignificant
)
, ( [ [6,38,3,17,11,30,15,16,25,5]
, [34,28,42,13,40,31,9,32,39,27]
, [13,35,19,4,29,0,7,33,18,24]
]
, 6.10
, Just Significant
)
]
----------------------------------------------------------------
-- K-S test
----------------------------------------------------------------
kolmogorovSmirnovDTest :: [Test]
kolmogorovSmirnovDTest =
[ testAssertion "K-S D statistics" $
and [ eq 1e-6 (kolmogorovSmirnovD standard (toU sample)) reference
| (reference,sample) <- tableKSD
]
, testAssertion "K-S 2-sample statistics" $
and [ eq 1e-6 (kolmogorovSmirnov2D (toU xs) (toU ys)) reference
| (reference,xs,ys) <- tableKS2D
]
, testAssertion "K-S probability" $
and [ eq 1e-14 (kolmogorovSmirnovProbability n d) p
| (d,n,p) <- testData
]
]
where
toU = U.fromList
-- Test data for the calculation of cumulative probability
-- P(D[n] < d).
--
-- Test data is:
-- (D[n], n, p)
-- Table is generated using sample program from paper
testData :: [(Double,Int,Double)]
testData =
[ (0.09 , 3, 0 )
, (0.2 , 3, 0.00177777777777778 )
, (0.301 , 3, 0.116357025777778 )
, (0.392 , 3, 0.383127210666667 )
, (0.5003 , 3, 0.667366306558667 )
, (0.604 , 3, 0.861569877333333 )
, (0.699 , 3, 0.945458198 )
, (0.802 , 3, 0.984475216 )
, (0.9 , 3, 0.998 )
, (0.09 , 5, 0 )
, (0.2 , 5, 0.0384 )
, (0.301 , 5, 0.33993786080016 )
, (0.392 , 5, 0.66931908083712 )
, (0.5003 , 5, 0.888397260183794 )
, (0.604 , 5, 0.971609957879808 )
, (0.699 , 5, 0.994331075994008 )
, (0.802 , 5, 0.999391366368064 )
, (0.9 , 5, 0.99998 )
, (0.09 , 8, 3.37615237575e-06 )
, (0.2 , 8, 0.151622071801758 )
, (0.301 , 8, 0.613891042670582 )
, (0.392 , 8, 0.871491561427005 )
, (0.5003 , 8, 0.977534089199071 )
, (0.604 , 8, 0.997473116268255 )
, (0.699 , 8, 0.999806082005123 )
, (0.802 , 8, 0.999995133786947 )
, (0.9 , 8, 0.99999998 )
, (0.09 , 10, 3.89639433093119e-05)
, (0.2 , 10, 0.25128096 )
, (0.301 , 10, 0.732913126355935 )
, (0.392 , 10, 0.932185254518767 )
, (0.5003 , 10, 0.992276179340446 )
, (0.604 , 10, 0.999495533516769 )
, (0.699 , 10, 0.999979691783985 )
, (0.802 , 10, 0.999999801409237 )
, (0.09 , 20, 0.00794502217168886 )
, (0.2 , 20, 0.647279826376584 )
, (0.301 , 20, 0.958017466965765 )
, (0.392 , 20, 0.997206424843499 )
, (0.5003 , 20, 0.999962641414228 )
, (0.09 , 30, 0.0498147538075168 )
, (0.2 , 30, 0.842030838984526 )
, (0.301 , 30, 0.993403560017612 )
, (0.392 , 30, 0.99988478803318 )
, (0.09 , 100, 0.629367974413669 )
]
| fpco/statistics | tests/Tests/NonParametric.hs | bsd-2-clause | 12,172 | 0 | 13 | 4,508 | 4,040 | 2,477 | 1,563 | 214 | 1 |
-- %************************************************************************
-- %* *
-- The known-key names for Template Haskell
-- %* *
-- %************************************************************************
module THNames where
import PrelNames( mk_known_key_name )
import Module( Module, mkModuleNameFS, mkModule, thPackageKey )
import Name( Name )
import OccName( tcName, clsName, dataName, varName )
import RdrName( RdrName, nameRdrName )
import Unique
import FastString
-- To add a name, do three things
--
-- 1) Allocate a key
-- 2) Make a "Name"
-- 3) Add the name to templateHaskellNames
templateHaskellNames :: [Name]
-- The names that are implicitly mentioned by ``bracket''
-- Should stay in sync with the import list of DsMeta
templateHaskellNames = [
returnQName, bindQName, sequenceQName, newNameName, liftName,
mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName,
liftStringName,
unTypeName,
unTypeQName,
unsafeTExpCoerceName,
-- Lit
charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
floatPrimLName, doublePrimLName, rationalLName, stringPrimLName,
charPrimLName,
-- Pat
litPName, varPName, tupPName, unboxedTupPName,
conPName, tildePName, bangPName, infixPName,
asPName, wildPName, recPName, listPName, sigPName, viewPName,
-- FieldPat
fieldPatName,
-- Match
matchName,
-- Clause
clauseName,
-- Exp
varEName, conEName, litEName, appEName, infixEName,
infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName,
tupEName, unboxedTupEName,
condEName, multiIfEName, letEName, caseEName, doEName, compEName,
fromEName, fromThenEName, fromToEName, fromThenToEName,
listEName, sigEName, recConEName, recUpdEName, staticEName,
-- FieldExp
fieldExpName,
-- Body
guardedBName, normalBName,
-- Guard
normalGEName, patGEName,
-- Stmt
bindSName, letSName, noBindSName, parSName,
-- Dec
funDName, valDName, dataDName, newtypeDName, tySynDName,
classDName, instanceDName, standaloneDerivDName, sigDName, forImpDName,
pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName,
pragRuleDName, pragAnnDName, defaultSigDName,
dataFamilyDName, openTypeFamilyDName, closedTypeFamilyDName,
dataInstDName, newtypeInstDName, tySynInstDName,
infixLDName, infixRDName, infixNDName,
roleAnnotDName,
-- Cxt
cxtName,
-- Strict
isStrictName, notStrictName, unpackedName,
-- Con
normalCName, recCName, infixCName, forallCName,
-- StrictType
strictTypeName,
-- VarStrictType
varStrictTypeName,
-- Type
forallTName, varTName, conTName, appTName, equalityTName,
tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName,
promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName,
wildCardTName, namedWildCardTName,
-- TyLit
numTyLitName, strTyLitName,
-- TyVarBndr
plainTVName, kindedTVName,
-- Role
nominalRName, representationalRName, phantomRName, inferRName,
-- Kind
varKName, conKName, tupleKName, arrowKName, listKName, appKName,
starKName, constraintKName,
-- FamilyResultSig
noSigName, kindSigName, tyVarSigName,
-- InjectivityAnn
injectivityAnnName,
-- Callconv
cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName,
-- Safety
unsafeName,
safeName,
interruptibleName,
-- Inline
noInlineDataConName, inlineDataConName, inlinableDataConName,
-- RuleMatch
conLikeDataConName, funLikeDataConName,
-- Phases
allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName,
-- TExp
tExpDataConName,
-- RuleBndr
ruleVarName, typedRuleVarName,
-- FunDep
funDepName,
-- FamFlavour
typeFamName, dataFamName,
-- TySynEqn
tySynEqnName,
-- AnnTarget
valueAnnotationName, typeAnnotationName, moduleAnnotationName,
-- The type classes
liftClassName,
-- And the tycons
qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName,
clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName,
stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName,
varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName,
typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName,
patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName,
predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName,
roleTyConName, tExpTyConName, injAnnTyConName, kindTyConName,
-- Quasiquoting
quoteDecName, quoteTypeName, quoteExpName, quotePatName]
thSyn, thLib, qqLib :: Module
thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax")
thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib")
qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote")
mkTHModule :: FastString -> Module
mkTHModule m = mkModule thPackageKey (mkModuleNameFS m)
libFun, libTc, thFun, thTc, thCls, thCon, qqFun :: FastString -> Unique -> Name
libFun = mk_known_key_name OccName.varName thLib
libTc = mk_known_key_name OccName.tcName thLib
thFun = mk_known_key_name OccName.varName thSyn
thTc = mk_known_key_name OccName.tcName thSyn
thCls = mk_known_key_name OccName.clsName thSyn
thCon = mk_known_key_name OccName.dataName thSyn
qqFun = mk_known_key_name OccName.varName qqLib
-------------------- TH.Syntax -----------------------
liftClassName :: Name
liftClassName = thCls (fsLit "Lift") liftClassKey
qTyConName, nameTyConName, fieldExpTyConName, patTyConName,
fieldPatTyConName, expTyConName, decTyConName, typeTyConName,
tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName,
predTyConName, tExpTyConName, injAnnTyConName, kindTyConName :: Name
qTyConName = thTc (fsLit "Q") qTyConKey
nameTyConName = thTc (fsLit "Name") nameTyConKey
fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey
patTyConName = thTc (fsLit "Pat") patTyConKey
fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey
expTyConName = thTc (fsLit "Exp") expTyConKey
decTyConName = thTc (fsLit "Dec") decTyConKey
typeTyConName = thTc (fsLit "Type") typeTyConKey
tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey
matchTyConName = thTc (fsLit "Match") matchTyConKey
clauseTyConName = thTc (fsLit "Clause") clauseTyConKey
funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey
predTyConName = thTc (fsLit "Pred") predTyConKey
tExpTyConName = thTc (fsLit "TExp") tExpTyConKey
injAnnTyConName = thTc (fsLit "InjectivityAnn") injAnnTyConKey
kindTyConName = thTc (fsLit "Kind") kindTyConKey
returnQName, bindQName, sequenceQName, newNameName, liftName,
mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName,
mkNameLName, liftStringName, unTypeName, unTypeQName,
unsafeTExpCoerceName :: Name
returnQName = thFun (fsLit "returnQ") returnQIdKey
bindQName = thFun (fsLit "bindQ") bindQIdKey
sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey
newNameName = thFun (fsLit "newName") newNameIdKey
liftName = thFun (fsLit "lift") liftIdKey
liftStringName = thFun (fsLit "liftString") liftStringIdKey
mkNameName = thFun (fsLit "mkName") mkNameIdKey
mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey
mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey
mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey
mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey
unTypeName = thFun (fsLit "unType") unTypeIdKey
unTypeQName = thFun (fsLit "unTypeQ") unTypeQIdKey
unsafeTExpCoerceName = thFun (fsLit "unsafeTExpCoerce") unsafeTExpCoerceIdKey
-------------------- TH.Lib -----------------------
-- data Lit = ...
charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
floatPrimLName, doublePrimLName, rationalLName, stringPrimLName,
charPrimLName :: Name
charLName = libFun (fsLit "charL") charLIdKey
stringLName = libFun (fsLit "stringL") stringLIdKey
integerLName = libFun (fsLit "integerL") integerLIdKey
intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey
wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey
floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey
doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey
rationalLName = libFun (fsLit "rationalL") rationalLIdKey
stringPrimLName = libFun (fsLit "stringPrimL") stringPrimLIdKey
charPrimLName = libFun (fsLit "charPrimL") charPrimLIdKey
-- data Pat = ...
litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName,
asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name
litPName = libFun (fsLit "litP") litPIdKey
varPName = libFun (fsLit "varP") varPIdKey
tupPName = libFun (fsLit "tupP") tupPIdKey
unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey
conPName = libFun (fsLit "conP") conPIdKey
infixPName = libFun (fsLit "infixP") infixPIdKey
tildePName = libFun (fsLit "tildeP") tildePIdKey
bangPName = libFun (fsLit "bangP") bangPIdKey
asPName = libFun (fsLit "asP") asPIdKey
wildPName = libFun (fsLit "wildP") wildPIdKey
recPName = libFun (fsLit "recP") recPIdKey
listPName = libFun (fsLit "listP") listPIdKey
sigPName = libFun (fsLit "sigP") sigPIdKey
viewPName = libFun (fsLit "viewP") viewPIdKey
-- type FieldPat = ...
fieldPatName :: Name
fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey
-- data Match = ...
matchName :: Name
matchName = libFun (fsLit "match") matchIdKey
-- data Clause = ...
clauseName :: Name
clauseName = libFun (fsLit "clause") clauseIdKey
-- data Exp = ...
varEName, conEName, litEName, appEName, infixEName, infixAppName,
sectionLName, sectionRName, lamEName, lamCaseEName, tupEName,
unboxedTupEName, condEName, multiIfEName, letEName, caseEName,
doEName, compEName, staticEName :: Name
varEName = libFun (fsLit "varE") varEIdKey
conEName = libFun (fsLit "conE") conEIdKey
litEName = libFun (fsLit "litE") litEIdKey
appEName = libFun (fsLit "appE") appEIdKey
infixEName = libFun (fsLit "infixE") infixEIdKey
infixAppName = libFun (fsLit "infixApp") infixAppIdKey
sectionLName = libFun (fsLit "sectionL") sectionLIdKey
sectionRName = libFun (fsLit "sectionR") sectionRIdKey
lamEName = libFun (fsLit "lamE") lamEIdKey
lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey
tupEName = libFun (fsLit "tupE") tupEIdKey
unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey
condEName = libFun (fsLit "condE") condEIdKey
multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey
letEName = libFun (fsLit "letE") letEIdKey
caseEName = libFun (fsLit "caseE") caseEIdKey
doEName = libFun (fsLit "doE") doEIdKey
compEName = libFun (fsLit "compE") compEIdKey
-- ArithSeq skips a level
fromEName, fromThenEName, fromToEName, fromThenToEName :: Name
fromEName = libFun (fsLit "fromE") fromEIdKey
fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey
fromToEName = libFun (fsLit "fromToE") fromToEIdKey
fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey
-- end ArithSeq
listEName, sigEName, recConEName, recUpdEName :: Name
listEName = libFun (fsLit "listE") listEIdKey
sigEName = libFun (fsLit "sigE") sigEIdKey
recConEName = libFun (fsLit "recConE") recConEIdKey
recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey
staticEName = libFun (fsLit "staticE") staticEIdKey
-- type FieldExp = ...
fieldExpName :: Name
fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey
-- data Body = ...
guardedBName, normalBName :: Name
guardedBName = libFun (fsLit "guardedB") guardedBIdKey
normalBName = libFun (fsLit "normalB") normalBIdKey
-- data Guard = ...
normalGEName, patGEName :: Name
normalGEName = libFun (fsLit "normalGE") normalGEIdKey
patGEName = libFun (fsLit "patGE") patGEIdKey
-- data Stmt = ...
bindSName, letSName, noBindSName, parSName :: Name
bindSName = libFun (fsLit "bindS") bindSIdKey
letSName = libFun (fsLit "letS") letSIdKey
noBindSName = libFun (fsLit "noBindS") noBindSIdKey
parSName = libFun (fsLit "parS") parSIdKey
-- data Dec = ...
funDName, valDName, dataDName, newtypeDName, tySynDName, classDName,
instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName,
pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName,
standaloneDerivDName, defaultSigDName,
dataInstDName, newtypeInstDName, tySynInstDName,
dataFamilyDName, openTypeFamilyDName, closedTypeFamilyDName,
infixLDName, infixRDName, infixNDName, roleAnnotDName :: Name
funDName = libFun (fsLit "funD") funDIdKey
valDName = libFun (fsLit "valD") valDIdKey
dataDName = libFun (fsLit "dataD") dataDIdKey
newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey
tySynDName = libFun (fsLit "tySynD") tySynDIdKey
classDName = libFun (fsLit "classD") classDIdKey
instanceDName = libFun (fsLit "instanceD") instanceDIdKey
standaloneDerivDName = libFun (fsLit "standaloneDerivD") standaloneDerivDIdKey
sigDName = libFun (fsLit "sigD") sigDIdKey
defaultSigDName = libFun (fsLit "defaultSigD") defaultSigDIdKey
forImpDName = libFun (fsLit "forImpD") forImpDIdKey
pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey
pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey
pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey
pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey
pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey
pragAnnDName = libFun (fsLit "pragAnnD") pragAnnDIdKey
dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey
newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey
tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey
openTypeFamilyDName = libFun (fsLit "openTypeFamilyD") openTypeFamilyDIdKey
closedTypeFamilyDName= libFun (fsLit "closedTypeFamilyD") closedTypeFamilyDIdKey
dataFamilyDName = libFun (fsLit "dataFamilyD") dataFamilyDIdKey
infixLDName = libFun (fsLit "infixLD") infixLDIdKey
infixRDName = libFun (fsLit "infixRD") infixRDIdKey
infixNDName = libFun (fsLit "infixND") infixNDIdKey
roleAnnotDName = libFun (fsLit "roleAnnotD") roleAnnotDIdKey
-- type Ctxt = ...
cxtName :: Name
cxtName = libFun (fsLit "cxt") cxtIdKey
-- data Strict = ...
isStrictName, notStrictName, unpackedName :: Name
isStrictName = libFun (fsLit "isStrict") isStrictKey
notStrictName = libFun (fsLit "notStrict") notStrictKey
unpackedName = libFun (fsLit "unpacked") unpackedKey
-- data Con = ...
normalCName, recCName, infixCName, forallCName :: Name
normalCName = libFun (fsLit "normalC") normalCIdKey
recCName = libFun (fsLit "recC") recCIdKey
infixCName = libFun (fsLit "infixC") infixCIdKey
forallCName = libFun (fsLit "forallC") forallCIdKey
-- type StrictType = ...
strictTypeName :: Name
strictTypeName = libFun (fsLit "strictType") strictTKey
-- type VarStrictType = ...
varStrictTypeName :: Name
varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey
-- data Type = ...
forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName,
listTName, appTName, sigTName, equalityTName, litTName,
promotedTName, promotedTupleTName,
promotedNilTName, promotedConsTName,
wildCardTName, namedWildCardTName :: Name
forallTName = libFun (fsLit "forallT") forallTIdKey
varTName = libFun (fsLit "varT") varTIdKey
conTName = libFun (fsLit "conT") conTIdKey
tupleTName = libFun (fsLit "tupleT") tupleTIdKey
unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey
arrowTName = libFun (fsLit "arrowT") arrowTIdKey
listTName = libFun (fsLit "listT") listTIdKey
appTName = libFun (fsLit "appT") appTIdKey
sigTName = libFun (fsLit "sigT") sigTIdKey
equalityTName = libFun (fsLit "equalityT") equalityTIdKey
litTName = libFun (fsLit "litT") litTIdKey
promotedTName = libFun (fsLit "promotedT") promotedTIdKey
promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey
promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey
promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey
wildCardTName = libFun (fsLit "wildCardT") wildCardTIdKey
namedWildCardTName = libFun (fsLit "namedWildCardT") namedWildCardTIdKey
-- data TyLit = ...
numTyLitName, strTyLitName :: Name
numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey
strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey
-- data TyVarBndr = ...
plainTVName, kindedTVName :: Name
plainTVName = libFun (fsLit "plainTV") plainTVIdKey
kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey
-- data Role = ...
nominalRName, representationalRName, phantomRName, inferRName :: Name
nominalRName = libFun (fsLit "nominalR") nominalRIdKey
representationalRName = libFun (fsLit "representationalR") representationalRIdKey
phantomRName = libFun (fsLit "phantomR") phantomRIdKey
inferRName = libFun (fsLit "inferR") inferRIdKey
-- data Kind = ...
varKName, conKName, tupleKName, arrowKName, listKName, appKName,
starKName, constraintKName :: Name
varKName = libFun (fsLit "varK") varKIdKey
conKName = libFun (fsLit "conK") conKIdKey
tupleKName = libFun (fsLit "tupleK") tupleKIdKey
arrowKName = libFun (fsLit "arrowK") arrowKIdKey
listKName = libFun (fsLit "listK") listKIdKey
appKName = libFun (fsLit "appK") appKIdKey
starKName = libFun (fsLit "starK") starKIdKey
constraintKName = libFun (fsLit "constraintK") constraintKIdKey
-- data FamilyResultSig = ...
noSigName, kindSigName, tyVarSigName :: Name
noSigName = libFun (fsLit "noSig") noSigIdKey
kindSigName = libFun (fsLit "kindSig") kindSigIdKey
tyVarSigName = libFun (fsLit "tyVarSig") tyVarSigIdKey
-- data InjectivityAnn = ...
injectivityAnnName :: Name
injectivityAnnName = libFun (fsLit "injectivityAnn") injectivityAnnIdKey
-- data Callconv = ...
cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName :: Name
cCallName = libFun (fsLit "cCall") cCallIdKey
stdCallName = libFun (fsLit "stdCall") stdCallIdKey
cApiCallName = libFun (fsLit "cApi") cApiCallIdKey
primCallName = libFun (fsLit "prim") primCallIdKey
javaScriptCallName = libFun (fsLit "javaScript") javaScriptCallIdKey
-- data Safety = ...
unsafeName, safeName, interruptibleName :: Name
unsafeName = libFun (fsLit "unsafe") unsafeIdKey
safeName = libFun (fsLit "safe") safeIdKey
interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey
-- data Inline = ...
noInlineDataConName, inlineDataConName, inlinableDataConName :: Name
noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey
inlineDataConName = thCon (fsLit "Inline") inlineDataConKey
inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey
-- data RuleMatch = ...
conLikeDataConName, funLikeDataConName :: Name
conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey
funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey
-- data Phases = ...
allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name
allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey
fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey
beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey
-- newtype TExp a = ...
tExpDataConName :: Name
tExpDataConName = thCon (fsLit "TExp") tExpDataConKey
-- data RuleBndr = ...
ruleVarName, typedRuleVarName :: Name
ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey
typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey
-- data FunDep = ...
funDepName :: Name
funDepName = libFun (fsLit "funDep") funDepIdKey
-- data FamFlavour = ...
typeFamName, dataFamName :: Name
typeFamName = libFun (fsLit "typeFam") typeFamIdKey
dataFamName = libFun (fsLit "dataFam") dataFamIdKey
-- data TySynEqn = ...
tySynEqnName :: Name
tySynEqnName = libFun (fsLit "tySynEqn") tySynEqnIdKey
-- data AnnTarget = ...
valueAnnotationName, typeAnnotationName, moduleAnnotationName :: Name
valueAnnotationName = libFun (fsLit "valueAnnotation") valueAnnotationIdKey
typeAnnotationName = libFun (fsLit "typeAnnotation") typeAnnotationIdKey
moduleAnnotationName = libFun (fsLit "moduleAnnotation") moduleAnnotationIdKey
matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName,
decQTyConName, conQTyConName, strictTypeQTyConName,
varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName,
patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName,
ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName :: Name
matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey
clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey
expQTyConName = libTc (fsLit "ExpQ") expQTyConKey
stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey
decQTyConName = libTc (fsLit "DecQ") decQTyConKey
decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec]
conQTyConName = libTc (fsLit "ConQ") conQTyConKey
strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey
varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey
typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey
fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey
patQTyConName = libTc (fsLit "PatQ") patQTyConKey
fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey
predQTyConName = libTc (fsLit "PredQ") predQTyConKey
ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey
tySynEqnQTyConName = libTc (fsLit "TySynEqnQ") tySynEqnQTyConKey
roleTyConName = libTc (fsLit "Role") roleTyConKey
-- quasiquoting
quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name
quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey
quotePatName = qqFun (fsLit "quotePat") quotePatKey
quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey
quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey
-- ClassUniques available: 200-299
-- Check in PrelNames if you want to change this
liftClassKey :: Unique
liftClassKey = mkPreludeClassUnique 200
-- TyConUniques available: 200-299
-- Check in PrelNames if you want to change this
expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey,
decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey,
stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey,
decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey,
fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey,
fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey,
predQTyConKey, decsQTyConKey, ruleBndrQTyConKey, tySynEqnQTyConKey,
roleTyConKey, tExpTyConKey, injAnnTyConKey, kindTyConKey :: Unique
expTyConKey = mkPreludeTyConUnique 200
matchTyConKey = mkPreludeTyConUnique 201
clauseTyConKey = mkPreludeTyConUnique 202
qTyConKey = mkPreludeTyConUnique 203
expQTyConKey = mkPreludeTyConUnique 204
decQTyConKey = mkPreludeTyConUnique 205
patTyConKey = mkPreludeTyConUnique 206
matchQTyConKey = mkPreludeTyConUnique 207
clauseQTyConKey = mkPreludeTyConUnique 208
stmtQTyConKey = mkPreludeTyConUnique 209
conQTyConKey = mkPreludeTyConUnique 210
typeQTyConKey = mkPreludeTyConUnique 211
typeTyConKey = mkPreludeTyConUnique 212
decTyConKey = mkPreludeTyConUnique 213
varStrictTypeQTyConKey = mkPreludeTyConUnique 214
strictTypeQTyConKey = mkPreludeTyConUnique 215
fieldExpTyConKey = mkPreludeTyConUnique 216
fieldPatTyConKey = mkPreludeTyConUnique 217
nameTyConKey = mkPreludeTyConUnique 218
patQTyConKey = mkPreludeTyConUnique 219
fieldPatQTyConKey = mkPreludeTyConUnique 220
fieldExpQTyConKey = mkPreludeTyConUnique 221
funDepTyConKey = mkPreludeTyConUnique 222
predTyConKey = mkPreludeTyConUnique 223
predQTyConKey = mkPreludeTyConUnique 224
tyVarBndrTyConKey = mkPreludeTyConUnique 225
decsQTyConKey = mkPreludeTyConUnique 226
ruleBndrQTyConKey = mkPreludeTyConUnique 227
tySynEqnQTyConKey = mkPreludeTyConUnique 228
roleTyConKey = mkPreludeTyConUnique 229
tExpTyConKey = mkPreludeTyConUnique 230
injAnnTyConKey = mkPreludeTyConUnique 231
kindTyConKey = mkPreludeTyConUnique 232
-- IdUniques available: 200-499
-- If you want to change this, make sure you check in PrelNames
returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey,
mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey,
mkNameLIdKey, unTypeIdKey, unTypeQIdKey, unsafeTExpCoerceIdKey :: Unique
returnQIdKey = mkPreludeMiscIdUnique 200
bindQIdKey = mkPreludeMiscIdUnique 201
sequenceQIdKey = mkPreludeMiscIdUnique 202
liftIdKey = mkPreludeMiscIdUnique 203
newNameIdKey = mkPreludeMiscIdUnique 204
mkNameIdKey = mkPreludeMiscIdUnique 205
mkNameG_vIdKey = mkPreludeMiscIdUnique 206
mkNameG_dIdKey = mkPreludeMiscIdUnique 207
mkNameG_tcIdKey = mkPreludeMiscIdUnique 208
mkNameLIdKey = mkPreludeMiscIdUnique 209
unTypeIdKey = mkPreludeMiscIdUnique 210
unTypeQIdKey = mkPreludeMiscIdUnique 211
unsafeTExpCoerceIdKey = mkPreludeMiscIdUnique 212
-- data Lit = ...
charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey,
floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey, stringPrimLIdKey,
charPrimLIdKey:: Unique
charLIdKey = mkPreludeMiscIdUnique 220
stringLIdKey = mkPreludeMiscIdUnique 221
integerLIdKey = mkPreludeMiscIdUnique 222
intPrimLIdKey = mkPreludeMiscIdUnique 223
wordPrimLIdKey = mkPreludeMiscIdUnique 224
floatPrimLIdKey = mkPreludeMiscIdUnique 225
doublePrimLIdKey = mkPreludeMiscIdUnique 226
rationalLIdKey = mkPreludeMiscIdUnique 227
stringPrimLIdKey = mkPreludeMiscIdUnique 228
charPrimLIdKey = mkPreludeMiscIdUnique 229
liftStringIdKey :: Unique
liftStringIdKey = mkPreludeMiscIdUnique 230
-- data Pat = ...
litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey,
asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique
litPIdKey = mkPreludeMiscIdUnique 240
varPIdKey = mkPreludeMiscIdUnique 241
tupPIdKey = mkPreludeMiscIdUnique 242
unboxedTupPIdKey = mkPreludeMiscIdUnique 243
conPIdKey = mkPreludeMiscIdUnique 244
infixPIdKey = mkPreludeMiscIdUnique 245
tildePIdKey = mkPreludeMiscIdUnique 246
bangPIdKey = mkPreludeMiscIdUnique 247
asPIdKey = mkPreludeMiscIdUnique 248
wildPIdKey = mkPreludeMiscIdUnique 249
recPIdKey = mkPreludeMiscIdUnique 250
listPIdKey = mkPreludeMiscIdUnique 251
sigPIdKey = mkPreludeMiscIdUnique 252
viewPIdKey = mkPreludeMiscIdUnique 253
-- type FieldPat = ...
fieldPatIdKey :: Unique
fieldPatIdKey = mkPreludeMiscIdUnique 260
-- data Match = ...
matchIdKey :: Unique
matchIdKey = mkPreludeMiscIdUnique 261
-- data Clause = ...
clauseIdKey :: Unique
clauseIdKey = mkPreludeMiscIdUnique 262
-- data Exp = ...
varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey,
sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey,
unboxedTupEIdKey, condEIdKey, multiIfEIdKey,
letEIdKey, caseEIdKey, doEIdKey, compEIdKey,
fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey,
listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey, staticEIdKey :: Unique
varEIdKey = mkPreludeMiscIdUnique 270
conEIdKey = mkPreludeMiscIdUnique 271
litEIdKey = mkPreludeMiscIdUnique 272
appEIdKey = mkPreludeMiscIdUnique 273
infixEIdKey = mkPreludeMiscIdUnique 274
infixAppIdKey = mkPreludeMiscIdUnique 275
sectionLIdKey = mkPreludeMiscIdUnique 276
sectionRIdKey = mkPreludeMiscIdUnique 277
lamEIdKey = mkPreludeMiscIdUnique 278
lamCaseEIdKey = mkPreludeMiscIdUnique 279
tupEIdKey = mkPreludeMiscIdUnique 280
unboxedTupEIdKey = mkPreludeMiscIdUnique 281
condEIdKey = mkPreludeMiscIdUnique 282
multiIfEIdKey = mkPreludeMiscIdUnique 283
letEIdKey = mkPreludeMiscIdUnique 284
caseEIdKey = mkPreludeMiscIdUnique 285
doEIdKey = mkPreludeMiscIdUnique 286
compEIdKey = mkPreludeMiscIdUnique 287
fromEIdKey = mkPreludeMiscIdUnique 288
fromThenEIdKey = mkPreludeMiscIdUnique 289
fromToEIdKey = mkPreludeMiscIdUnique 290
fromThenToEIdKey = mkPreludeMiscIdUnique 291
listEIdKey = mkPreludeMiscIdUnique 292
sigEIdKey = mkPreludeMiscIdUnique 293
recConEIdKey = mkPreludeMiscIdUnique 294
recUpdEIdKey = mkPreludeMiscIdUnique 295
staticEIdKey = mkPreludeMiscIdUnique 296
-- type FieldExp = ...
fieldExpIdKey :: Unique
fieldExpIdKey = mkPreludeMiscIdUnique 310
-- data Body = ...
guardedBIdKey, normalBIdKey :: Unique
guardedBIdKey = mkPreludeMiscIdUnique 311
normalBIdKey = mkPreludeMiscIdUnique 312
-- data Guard = ...
normalGEIdKey, patGEIdKey :: Unique
normalGEIdKey = mkPreludeMiscIdUnique 313
patGEIdKey = mkPreludeMiscIdUnique 314
-- data Stmt = ...
bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique
bindSIdKey = mkPreludeMiscIdUnique 320
letSIdKey = mkPreludeMiscIdUnique 321
noBindSIdKey = mkPreludeMiscIdUnique 322
parSIdKey = mkPreludeMiscIdUnique 323
-- data Dec = ...
funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey,
classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey,
pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey,
pragAnnDIdKey, defaultSigDIdKey, dataFamilyDIdKey, openTypeFamilyDIdKey,
closedTypeFamilyDIdKey, dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey,
standaloneDerivDIdKey, infixLDIdKey, infixRDIdKey, infixNDIdKey,
roleAnnotDIdKey :: Unique
funDIdKey = mkPreludeMiscIdUnique 330
valDIdKey = mkPreludeMiscIdUnique 331
dataDIdKey = mkPreludeMiscIdUnique 332
newtypeDIdKey = mkPreludeMiscIdUnique 333
tySynDIdKey = mkPreludeMiscIdUnique 334
classDIdKey = mkPreludeMiscIdUnique 335
instanceDIdKey = mkPreludeMiscIdUnique 336
sigDIdKey = mkPreludeMiscIdUnique 337
forImpDIdKey = mkPreludeMiscIdUnique 338
pragInlDIdKey = mkPreludeMiscIdUnique 339
pragSpecDIdKey = mkPreludeMiscIdUnique 340
pragSpecInlDIdKey = mkPreludeMiscIdUnique 341
pragSpecInstDIdKey = mkPreludeMiscIdUnique 342
pragRuleDIdKey = mkPreludeMiscIdUnique 343
pragAnnDIdKey = mkPreludeMiscIdUnique 344
dataFamilyDIdKey = mkPreludeMiscIdUnique 345
openTypeFamilyDIdKey = mkPreludeMiscIdUnique 346
dataInstDIdKey = mkPreludeMiscIdUnique 347
newtypeInstDIdKey = mkPreludeMiscIdUnique 348
tySynInstDIdKey = mkPreludeMiscIdUnique 349
closedTypeFamilyDIdKey = mkPreludeMiscIdUnique 350
infixLDIdKey = mkPreludeMiscIdUnique 352
infixRDIdKey = mkPreludeMiscIdUnique 353
infixNDIdKey = mkPreludeMiscIdUnique 354
roleAnnotDIdKey = mkPreludeMiscIdUnique 355
standaloneDerivDIdKey = mkPreludeMiscIdUnique 356
defaultSigDIdKey = mkPreludeMiscIdUnique 357
-- type Cxt = ...
cxtIdKey :: Unique
cxtIdKey = mkPreludeMiscIdUnique 360
-- data Strict = ...
isStrictKey, notStrictKey, unpackedKey :: Unique
isStrictKey = mkPreludeMiscIdUnique 363
notStrictKey = mkPreludeMiscIdUnique 364
unpackedKey = mkPreludeMiscIdUnique 365
-- data Con = ...
normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique
normalCIdKey = mkPreludeMiscIdUnique 370
recCIdKey = mkPreludeMiscIdUnique 371
infixCIdKey = mkPreludeMiscIdUnique 372
forallCIdKey = mkPreludeMiscIdUnique 373
-- type StrictType = ...
strictTKey :: Unique
strictTKey = mkPreludeMiscIdUnique 374
-- type VarStrictType = ...
varStrictTKey :: Unique
varStrictTKey = mkPreludeMiscIdUnique 375
-- data Type = ...
forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey,
listTIdKey, appTIdKey, sigTIdKey, equalityTIdKey, litTIdKey,
promotedTIdKey, promotedTupleTIdKey,
promotedNilTIdKey, promotedConsTIdKey,
wildCardTIdKey, namedWildCardTIdKey :: Unique
forallTIdKey = mkPreludeMiscIdUnique 380
varTIdKey = mkPreludeMiscIdUnique 381
conTIdKey = mkPreludeMiscIdUnique 382
tupleTIdKey = mkPreludeMiscIdUnique 383
unboxedTupleTIdKey = mkPreludeMiscIdUnique 384
arrowTIdKey = mkPreludeMiscIdUnique 385
listTIdKey = mkPreludeMiscIdUnique 386
appTIdKey = mkPreludeMiscIdUnique 387
sigTIdKey = mkPreludeMiscIdUnique 388
equalityTIdKey = mkPreludeMiscIdUnique 389
litTIdKey = mkPreludeMiscIdUnique 390
promotedTIdKey = mkPreludeMiscIdUnique 391
promotedTupleTIdKey = mkPreludeMiscIdUnique 392
promotedNilTIdKey = mkPreludeMiscIdUnique 393
promotedConsTIdKey = mkPreludeMiscIdUnique 394
wildCardTIdKey = mkPreludeMiscIdUnique 395
namedWildCardTIdKey = mkPreludeMiscIdUnique 396
-- data TyLit = ...
numTyLitIdKey, strTyLitIdKey :: Unique
numTyLitIdKey = mkPreludeMiscIdUnique 400
strTyLitIdKey = mkPreludeMiscIdUnique 401
-- data TyVarBndr = ...
plainTVIdKey, kindedTVIdKey :: Unique
plainTVIdKey = mkPreludeMiscIdUnique 402
kindedTVIdKey = mkPreludeMiscIdUnique 403
-- data Role = ...
nominalRIdKey, representationalRIdKey, phantomRIdKey, inferRIdKey :: Unique
nominalRIdKey = mkPreludeMiscIdUnique 404
representationalRIdKey = mkPreludeMiscIdUnique 405
phantomRIdKey = mkPreludeMiscIdUnique 406
inferRIdKey = mkPreludeMiscIdUnique 407
-- data Kind = ...
varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey,
starKIdKey, constraintKIdKey :: Unique
varKIdKey = mkPreludeMiscIdUnique 408
conKIdKey = mkPreludeMiscIdUnique 409
tupleKIdKey = mkPreludeMiscIdUnique 410
arrowKIdKey = mkPreludeMiscIdUnique 411
listKIdKey = mkPreludeMiscIdUnique 412
appKIdKey = mkPreludeMiscIdUnique 413
starKIdKey = mkPreludeMiscIdUnique 414
constraintKIdKey = mkPreludeMiscIdUnique 415
-- data FamilyResultSig = ...
noSigIdKey, kindSigIdKey, tyVarSigIdKey :: Unique
noSigIdKey = mkPreludeMiscIdUnique 416
kindSigIdKey = mkPreludeMiscIdUnique 417
tyVarSigIdKey = mkPreludeMiscIdUnique 418
-- data InjectivityAnn = ...
injectivityAnnIdKey :: Unique
injectivityAnnIdKey = mkPreludeMiscIdUnique 419
-- data Callconv = ...
cCallIdKey, stdCallIdKey, cApiCallIdKey, primCallIdKey,
javaScriptCallIdKey :: Unique
cCallIdKey = mkPreludeMiscIdUnique 420
stdCallIdKey = mkPreludeMiscIdUnique 421
cApiCallIdKey = mkPreludeMiscIdUnique 422
primCallIdKey = mkPreludeMiscIdUnique 423
javaScriptCallIdKey = mkPreludeMiscIdUnique 424
-- data Safety = ...
unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique
unsafeIdKey = mkPreludeMiscIdUnique 430
safeIdKey = mkPreludeMiscIdUnique 431
interruptibleIdKey = mkPreludeMiscIdUnique 432
-- data Inline = ...
noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique
noInlineDataConKey = mkPreludeDataConUnique 40
inlineDataConKey = mkPreludeDataConUnique 41
inlinableDataConKey = mkPreludeDataConUnique 42
-- data RuleMatch = ...
conLikeDataConKey, funLikeDataConKey :: Unique
conLikeDataConKey = mkPreludeDataConUnique 43
funLikeDataConKey = mkPreludeDataConUnique 44
-- data Phases = ...
allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique
allPhasesDataConKey = mkPreludeDataConUnique 45
fromPhaseDataConKey = mkPreludeDataConUnique 46
beforePhaseDataConKey = mkPreludeDataConUnique 47
-- newtype TExp a = ...
tExpDataConKey :: Unique
tExpDataConKey = mkPreludeDataConUnique 48
-- data FunDep = ...
funDepIdKey :: Unique
funDepIdKey = mkPreludeMiscIdUnique 440
-- data FamFlavour = ...
typeFamIdKey, dataFamIdKey :: Unique
typeFamIdKey = mkPreludeMiscIdUnique 450
dataFamIdKey = mkPreludeMiscIdUnique 451
-- data TySynEqn = ...
tySynEqnIdKey :: Unique
tySynEqnIdKey = mkPreludeMiscIdUnique 460
-- quasiquoting
quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique
quoteExpKey = mkPreludeMiscIdUnique 470
quotePatKey = mkPreludeMiscIdUnique 471
quoteDecKey = mkPreludeMiscIdUnique 472
quoteTypeKey = mkPreludeMiscIdUnique 473
-- data RuleBndr = ...
ruleVarIdKey, typedRuleVarIdKey :: Unique
ruleVarIdKey = mkPreludeMiscIdUnique 480
typedRuleVarIdKey = mkPreludeMiscIdUnique 481
-- data AnnTarget = ...
valueAnnotationIdKey, typeAnnotationIdKey, moduleAnnotationIdKey :: Unique
valueAnnotationIdKey = mkPreludeMiscIdUnique 490
typeAnnotationIdKey = mkPreludeMiscIdUnique 491
moduleAnnotationIdKey = mkPreludeMiscIdUnique 492
{-
************************************************************************
* *
RdrNames
* *
************************************************************************
-}
lift_RDR, mkNameG_dRDR, mkNameG_vRDR :: RdrName
lift_RDR = nameRdrName liftName
mkNameG_dRDR = nameRdrName mkNameG_dName
mkNameG_vRDR = nameRdrName mkNameG_vName
-- data Exp = ...
conE_RDR, litE_RDR, appE_RDR, infixApp_RDR :: RdrName
conE_RDR = nameRdrName conEName
litE_RDR = nameRdrName litEName
appE_RDR = nameRdrName appEName
infixApp_RDR = nameRdrName infixAppName
-- data Lit = ...
stringL_RDR, intPrimL_RDR, wordPrimL_RDR, floatPrimL_RDR,
doublePrimL_RDR, stringPrimL_RDR, charPrimL_RDR :: RdrName
stringL_RDR = nameRdrName stringLName
intPrimL_RDR = nameRdrName intPrimLName
wordPrimL_RDR = nameRdrName wordPrimLName
floatPrimL_RDR = nameRdrName floatPrimLName
doublePrimL_RDR = nameRdrName doublePrimLName
stringPrimL_RDR = nameRdrName stringPrimLName
charPrimL_RDR = nameRdrName charPrimLName
| ml9951/ghc | compiler/prelude/THNames.hs | bsd-3-clause | 39,682 | 0 | 8 | 7,971 | 7,465 | 4,331 | 3,134 | 680 | 1 |
{-# LANGUAGE MagicHash #-}
-----------------------------------------------------------------------------
--
-- GHCi Interactive debugging commands
--
-- Pepe Iborra (supported by Google SoC) 2006
--
-- ToDo: lots of violation of layering here. This module should
-- decide whether it is above the GHC API (import GHC and nothing
-- else) or below it.
--
-----------------------------------------------------------------------------
module ETA.Interactive.Debugger where --(pprintClosureCommand, showTerm, pprTypeAndContents) where
-- import ETA.Interactive.Linker
-- import ETA.Interactive.RtClosureInspect
--
-- import ETA.Main.GhcMonad
-- import ETA.Main.HscTypes
-- import ETA.BasicTypes.Id
-- import ETA.BasicTypes.Name
-- import ETA.BasicTypes.Var hiding ( varName )
-- import ETA.BasicTypes.VarSet
-- import ETA.BasicTypes.UniqSupply
-- import ETA.Types.Type
-- import ETA.Types.Kind
-- import ETA.Main.GHC
-- import qualified ETA.Main.GHC as GHC
-- import ETA.Utils.Outputable
-- import ETA.Main.PprTyThing
-- import ETA.Main.ErrUtils
-- import ETA.Utils.MonadUtils
-- import ETA.Main.DynFlags
-- import ETA.Utils.Exception
--
-- import Control.Monad
-- import Data.List
-- import Data.Maybe
-- import Data.IORef
--
-- import GHC.Exts
-- -------------------------------------
-- -- | The :print & friends commands
-- -------------------------------------
-- pprintClosureCommand :: GhcMonad m => Bool -> Bool -> String -> m ()
-- pprintClosureCommand bindThings force str = do
-- tythings <- (catMaybes . concat) `liftM`
-- mapM (\w -> GHC.parseName w >>=
-- mapM GHC.lookupName)
-- (words str)
-- let ids = [id | AnId id <- tythings]
-- -- Obtain the terms and the recovered type information
-- (subst, terms) <- mapAccumLM go emptyTvSubst ids
-- -- Apply the substitutions obtained after recovering the types
-- modifySession $ \hsc_env ->
-- hsc_env{hsc_IC = substInteractiveContext (hsc_IC hsc_env) subst}
-- -- Finally, print the Terms
-- unqual <- GHC.getPrintUnqual
-- docterms <- mapM showTerm terms
-- dflags <- getDynFlags
-- liftIO $ (printOutputForUser dflags unqual . vcat)
-- (zipWith (\id docterm -> ppr id <+> char '=' <+> docterm)
-- ids
-- docterms)
-- where
-- -- Do the obtainTerm--bindSuspensions-computeSubstitution dance
-- go :: GhcMonad m => TvSubst -> Id -> m (TvSubst, Term)
-- go subst id = do
-- let id' = id `setIdType` substTy subst (idType id)
-- term_ <- GHC.obtainTermFromId maxBound force id'
-- term <- tidyTermTyVars term_
-- term' <- if bindThings &&
-- False == isUnliftedTypeKind (termType term)
-- then bindSuspensions term
-- else return term
-- -- Before leaving, we compare the type obtained to see if it's more specific
-- -- Then, we extract a substitution,
-- -- mapping the old tyvars to the reconstructed types.
-- let reconstructed_type = termType term
-- hsc_env <- getSession
-- case (improveRTTIType hsc_env (idType id) (reconstructed_type)) of
-- Nothing -> return (subst, term')
-- Just subst' -> do { traceOptIf Opt_D_dump_rtti
-- (fsep $ [text "RTTI Improvement for", ppr id,
-- text "is the substitution:" , ppr subst'])
-- ; return (subst `unionTvSubst` subst', term')}
-- tidyTermTyVars :: GhcMonad m => Term -> m Term
-- tidyTermTyVars t =
-- withSession $ \hsc_env -> do
-- let env_tvs = tyThingsTyVars $ ic_tythings $ hsc_IC hsc_env
-- my_tvs = termTyVars t
-- tvs = env_tvs `minusVarSet` my_tvs
-- tyvarOccName = nameOccName . tyVarName
-- tidyEnv = (initTidyOccEnv (map tyvarOccName (varSetElems tvs))
-- , env_tvs `intersectVarSet` my_tvs)
-- return$ mapTermType (snd . tidyOpenType tidyEnv) t
-- -- | Give names, and bind in the interactive environment, to all the suspensions
-- -- included (inductively) in a term
-- bindSuspensions :: GhcMonad m => Term -> m Term
-- bindSuspensions t = do
-- hsc_env <- getSession
-- inScope <- GHC.getBindings
-- let ictxt = hsc_IC hsc_env
-- prefix = "_t"
-- alreadyUsedNames = map (occNameString . nameOccName . getName) inScope
-- availNames = map ((prefix++) . show) [(1::Int)..] \\ alreadyUsedNames
-- availNames_var <- liftIO $ newIORef availNames
-- (t', stuff) <- liftIO $ foldTerm (nameSuspensionsAndGetInfos availNames_var) t
-- let (names, tys, hvals) = unzip3 stuff
-- let ids = [ mkVanillaGlobal name ty
-- | (name,ty) <- zip names tys]
-- new_ic = extendInteractiveContextWithIds ictxt ids
-- liftIO $ extendLinkEnv (zip names hvals)
-- modifySession $ \_ -> hsc_env {hsc_IC = new_ic }
-- return t'
-- where
-- -- Processing suspensions. Give names and recopilate info
-- nameSuspensionsAndGetInfos :: IORef [String] ->
-- TermFold (IO (Term, [(Name,Type,HValue)]))
-- nameSuspensionsAndGetInfos freeNames = TermFold
-- {
-- fSuspension = doSuspension freeNames
-- , fTerm = \ty dc v tt -> do
-- tt' <- sequence tt
-- let (terms,names) = unzip tt'
-- return (Term ty dc v terms, concat names)
-- , fPrim = \ty n ->return (Prim ty n,[])
-- , fNewtypeWrap =
-- \ty dc t -> do
-- (term, names) <- t
-- return (NewtypeWrap ty dc term, names)
-- , fRefWrap = \ty t -> do
-- (term, names) <- t
-- return (RefWrap ty term, names)
-- }
-- doSuspension freeNames ct ty hval _name = do
-- name <- atomicModifyIORef freeNames (\x->(tail x, head x))
-- n <- newGrimName name
-- return (Suspension ct ty hval (Just n), [(n,ty,hval)])
-- -- A custom Term printer to enable the use of Show instances
-- showTerm :: GhcMonad m => Term -> m SDoc
-- showTerm term = do
-- dflags <- GHC.getSessionDynFlags
-- if gopt Opt_PrintEvldWithShow dflags
-- then cPprTerm (liftM2 (++) (\_y->[cPprShowable]) cPprTermBase) term
-- else cPprTerm cPprTermBase term
-- where
-- cPprShowable prec t@Term{ty=ty, val=val} =
-- if not (isFullyEvaluatedTerm t)
-- then return Nothing
-- else do
-- hsc_env <- getSession
-- dflags <- GHC.getSessionDynFlags
-- do
-- (new_env, bname) <- bindToFreshName hsc_env ty "showme"
-- setSession new_env
-- -- XXX: this tries to disable logging of errors
-- -- does this still do what it is intended to do
-- -- with the changed error handling and logging?
-- let noop_log _ _ _ _ _ = return ()
-- expr = "show " ++ showPpr dflags bname
-- _ <- GHC.setSessionDynFlags dflags{log_action=noop_log}
-- txt_ <- withExtendedLinkEnv [(bname, val)]
-- (GHC.compileExpr expr)
-- let myprec = 10 -- application precedence. TODO Infix constructors
-- let txt = unsafeCoerce# txt_ :: [a]
-- if not (null txt) then
-- return $ Just $ cparen (prec >= myprec && needsParens txt)
-- (text txt)
-- else return Nothing
-- `gfinally` do
-- setSession hsc_env
-- GHC.setSessionDynFlags dflags
-- cPprShowable prec NewtypeWrap{ty=new_ty,wrapped_term=t} =
-- cPprShowable prec t{ty=new_ty}
-- cPprShowable _ _ = return Nothing
-- needsParens ('"':_) = False -- some simple heuristics to see whether parens
-- -- are redundant in an arbitrary Show output
-- needsParens ('(':_) = False
-- needsParens txt = ' ' `elem` txt
-- bindToFreshName hsc_env ty userName = do
-- name <- newGrimName userName
-- let id = mkVanillaGlobal name ty
-- new_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) [id]
-- return (hsc_env {hsc_IC = new_ic }, name)
-- -- Create new uniques and give them sequentially numbered names
-- newGrimName :: MonadIO m => String -> m Name
-- newGrimName userName = do
-- us <- liftIO $ mkSplitUniqSupply 'b'
-- let unique = uniqFromSupply us
-- occname = mkOccName varName userName
-- name = mkInternalName unique occname noSrcSpan
-- return name
-- pprTypeAndContents :: GhcMonad m => Id -> m SDoc
-- pprTypeAndContents id = do
-- dflags <- GHC.getSessionDynFlags
-- let pcontents = gopt Opt_PrintBindContents dflags
-- pprdId = (PprTyThing.pprTyThing . AnId) id
-- if pcontents
-- then do
-- let depthBound = 100
-- -- If the value is an exception, make sure we catch it and
-- -- show the exception, rather than propagating the exception out.
-- e_term <- gtry $ GHC.obtainTermFromId depthBound False id
-- docs_term <- case e_term of
-- Right term -> showTerm term
-- Left exn -> return (text "*** Exception:" <+>
-- text (show (exn :: SomeException)))
-- return $ pprdId <+> equals <+> docs_term
-- else return pprdId
-- --------------------------------------------------------------
-- -- Utils
-- traceOptIf :: GhcMonad m => DumpFlag -> SDoc -> m ()
-- traceOptIf flag doc = do
-- dflags <- GHC.getSessionDynFlags
-- when (dopt flag dflags) $ liftIO $ printInfoForUser dflags alwaysQualify doc
| pparkkin/eta | compiler/ETA/Interactive/Debugger.hs | bsd-3-clause | 10,188 | 0 | 3 | 3,169 | 222 | 220 | 2 | 2 | 0 |
{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving, StandaloneDeriving #-}
import Prelude hiding (mapM)
import Options.Applicative
import Data.Monoid ((<>))
import Control.Monad.Trans.Class
import Data.Vector (Vector)
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Generic as V
import Statistics.Sample (mean)
import Data.Traversable (mapM)
import qualified Data.Set as S
import Data.Set (Set)
import qualified Data.Map as M
import ReadData
import SerializeText
import qualified RunSampler as Sampler
import BayesStack.DirMulti
import BayesStack.Models.Topic.CitationInfluence
import BayesStack.UniqueKey
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import System.FilePath.Posix ((</>))
import Data.Binary
import qualified Data.ByteString as BS
import Text.Printf
import Data.Random
import System.Random.MWC
data RunOpts = RunOpts { arcsFile :: FilePath
, nodesFile :: FilePath
, stopwords :: Maybe FilePath
, nTopics :: Int
, samplerOpts :: Sampler.SamplerOpts
, hyperParams :: HyperParams
, noClean :: Bool
}
runOpts = RunOpts
<$> strOption ( long "arcs"
<> short 'a'
<> metavar "FILE"
<> help "File containing arcs"
)
<*> strOption ( long "nodes"
<> short 'n'
<> metavar "FILE"
<> help "File containing nodes' items"
)
<*> nullOption ( long "stopwords"
<> short 's'
<> metavar "FILE"
<> reader (pure . Just)
<> value Nothing
<> help "Stop words list"
)
<*> option ( long "topics"
<> short 't'
<> metavar "N"
<> value 20
<> help "Number of topics"
)
<*> Sampler.samplerOpts
<*> hyperOpts
<*> flag False True ( long "no-clean"
<> short 'c'
<> help "Don't attempt to sanitize input data. Among other things, nodes without friends will not be discarded"
)
hyperOpts = HyperParams
<$> option ( long "prior-psi"
<> value 1
<> help "Dirichlet parameter for prior on psi"
)
<*> option ( long "prior-lambda"
<> value 0.1
<> help "Dirichlet parameter for prior on lambda"
)
<*> option ( long "prior-phi"
<> value 0.01
<> help "Dirichlet parameter for prior on phi"
)
<*> option ( long "prior-omega"
<> value 0.01
<> help "Dirichlet parameter for prior on omega"
)
<*> option ( long "prior-gamma-shared"
<> value 0.9
<> help "Beta parameter for prior on gamma (shared)"
)
<*> option ( long "prior-gamma-own"
<> value 0.1
<> help "Beta parameter for prior on gamma (own)"
)
mapMKeys :: (Ord k, Ord k', Monad m, Applicative m)
=> (a -> m a') -> (k -> m k') -> M.Map k a -> m (M.Map k' a')
mapMKeys f g x = M.fromList <$> (mapM (\(k,v)->(,) <$> g k <*> f v) $ M.assocs x)
termsToItems :: M.Map NodeName [Term] -> Set (NodeName, NodeName)
-> ( (M.Map Node [Item], Set (Node, Node))
, (M.Map Item Term, M.Map Node NodeName))
termsToItems nodes arcs =
let ((d', nodeMap), itemMap) =
runUniqueKey' [Item i | i <- [0..]] $
runUniqueKeyT' [Node i | i <- [0..]] $ do
a <- mapMKeys (mapM (lift . getUniqueKey)) getUniqueKey nodes
b <- S.fromList <$> mapM (\(x,y)->(,) <$> getUniqueKey x <*> getUniqueKey y)
(S.toList arcs)
return (a,b)
in (d', (itemMap, nodeMap))
makeNetData :: HyperParams -> M.Map Node [Item] -> Set Arc -> Int -> NetData
makeNetData hp nodeItems arcs nTopics =
netData hp arcs nodeItems' topics
where topics = S.fromList [Topic i | i <- [1..nTopics]]
nodeItems' = M.fromList
$ zip [NodeItem i | i <- [0..]]
$ do (n,items) <- M.assocs nodeItems
item <- items
return (n, item)
opts = info runOpts
( fullDesc
<> progDesc "Learn citation influence model"
<> header "run-ci - learn citation influence model"
)
edgesToArcs :: Set (Node, Node) -> Set Arc
edgesToArcs = S.map (\(a,b)->Arc (Citing a) (Cited b))
instance Sampler.SamplerModel MState where
estimateHypers = id -- reestimate -- FIXME
modelLikelihood = modelLikelihood
summarizeHypers ms = "" -- FIXME
main = do
args <- execParser opts
stopWords <- case stopwords args of
Just f -> S.fromList . T.words <$> TIO.readFile f
Nothing -> return S.empty
printf "Read %d stopwords\n" (S.size stopWords)
((nodeItems, a), (itemMap, nodeMap)) <- termsToItems
<$> readNodeItems stopWords (nodesFile args)
<*> readEdges (arcsFile args)
let arcs = edgesToArcs a
Sampler.createSweeps $ samplerOpts args
let sweepsDir = Sampler.sweepsDir $ samplerOpts args
encodeFile (sweepsDir </> "item-map") itemMap
encodeFile (sweepsDir </> "node-map") nodeMap
let termCounts = V.fromListN (M.size nodeItems)
$ map length $ M.elems nodeItems :: Vector Int
printf "Read %d arcs, %d nodes, %d node-items\n" (S.size arcs) (M.size nodeItems) (V.sum termCounts)
printf "Mean items per node: %1.2f\n" (mean $ V.map realToFrac termCounts)
withSystemRandom $ \mwc->do
let nd = (if noClean args then id else cleanNetData)
$ makeNetData (hyperParams args) nodeItems arcs (nTopics args)
mapM_ putStrLn $ verifyNetData (\n->maybe (show n) show $ M.lookup n nodeMap) nd
let nCitingNodes = VU.fromList $ M.elems $ M.unionsWith (+)
$ map (\a->M.singleton (citingNode a) 1)
$ S.toList $ dArcs nd
nCitedNodes = VU.fromList $ M.elems $ M.unionsWith (+)
$ map (\a->M.singleton (citedNode a) 1)
$ S.toList $ dArcs nd
printf "After cleaning: %d cited nodes, %d citing nodes, %d arcs, %d node-items\n"
(S.size $ S.map citedNode $ dArcs nd) (S.size $ S.map citingNode $ dArcs nd)
(S.size $ dArcs nd) (M.size $ dNodeItems nd)
printf "In degree: mean=%3.1f, maximum=%3.1f\n"
(mean nCitedNodes) (V.maximum nCitedNodes)
printf "Out degree: mean=%3.1f, maximum=%3.1f\n"
(mean nCitingNodes) (V.maximum nCitingNodes)
encodeFile (sweepsDir </> "data") nd
mInit <- runRVar (randomInitialize nd) mwc
let m = model nd mInit
Sampler.runSampler (samplerOpts args) m (updateUnits nd)
return ()
| beni55/bayes-stack | network-topic-models/RunCI.hs | bsd-3-clause | 7,455 | 0 | 22 | 2,770 | 2,085 | 1,057 | 1,028 | -1 | -1 |
module Boo where
{-@ incr :: Int -> Bool @-}
incr :: Int -> Int
incr x = x + 1
| ssaavedra/liquidhaskell | tests/crash/errmsg-mismatch.hs | bsd-3-clause | 81 | 0 | 5 | 23 | 26 | 15 | 11 | 3 | 1 |
-- |
-- This module contains the Relapse type expression.
module Data.Katydid.Relapse.Exprs.Type
( mkTypeExpr
, typeExpr
)
where
import Data.Katydid.Relapse.Expr
-- |
-- mkTypeExpr is used by the parser to create a type expression for the specific input type.
mkTypeExpr :: [AnyExpr] -> Either String AnyExpr
mkTypeExpr es = do
e <- assertArgs1 "type" es
case e of
(AnyExpr _ (BoolFunc _)) -> mkBoolExpr . typeExpr <$> assertBool e
(AnyExpr _ (IntFunc _)) -> mkBoolExpr . typeExpr <$> assertInt e
(AnyExpr _ (UintFunc _)) -> mkBoolExpr . typeExpr <$> assertUint e
(AnyExpr _ (DoubleFunc _)) -> mkBoolExpr . typeExpr <$> assertDouble e
(AnyExpr _ (StringFunc _)) -> mkBoolExpr . typeExpr <$> assertString e
(AnyExpr _ (BytesFunc _)) -> mkBoolExpr . typeExpr <$> assertBytes e
-- |
-- typeExpr creates an expression that returns true if the containing expression does not return an error.
-- For example: `(typeExpr varBoolExpr)` will ony return true is the field value is a bool.
typeExpr :: Expr a -> Expr Bool
typeExpr e = Expr
{ desc = mkDesc "type" [desc e]
, eval = \v -> case eval e v of
(Left _) -> return False
(Right _) -> return True
}
| katydid/haslapse | src/Data/Katydid/Relapse/Exprs/Type.hs | bsd-3-clause | 1,218 | 0 | 13 | 271 | 353 | 181 | 172 | 20 | 6 |
{-# LANGUAGE TemplateHaskell, Rank2Types, CPP #-}
#ifndef NO_SAFE_HASKELL
{-# LANGUAGE Trustworthy #-}
#endif
-- | Test all properties in the current module, using Template Haskell.
-- You need to have a @{-\# LANGUAGE TemplateHaskell \#-}@ pragma in
-- your module for any of these to work.
module Test.QuickCheck.All(
-- ** Testing all properties in a module
quickCheckAll,
verboseCheckAll,
forAllProperties,
-- ** Testing polymorphic properties
polyQuickCheck,
polyVerboseCheck,
monomorphic) where
import Language.Haskell.TH
import Test.QuickCheck.Property hiding (Result)
import Test.QuickCheck.Test
import Data.Char
import Data.List
import Control.Monad
import qualified System.IO as S
-- | Test a polymorphic property, defaulting all type variables to 'Integer'.
--
-- Invoke as @$('polyQuickCheck' 'prop)@, where @prop@ is a property.
-- Note that just evaluating @'quickCheck' prop@ in GHCi will seem to
-- work, but will silently default all type variables to @()@!
--
-- @$('polyQuickCheck' \'prop)@ means the same as
-- @'quickCheck' $('monomorphic' \'prop)@.
-- If you want to supply custom arguments to 'polyQuickCheck',
-- you will have to combine 'quickCheckWith' and 'monomorphic' yourself.
--
-- If you want to use 'polyQuickCheck' in the same file where you defined the
-- property, the same scoping problems pop up as in 'quickCheckAll':
-- see the note there about @return []@.
polyQuickCheck :: Name -> ExpQ
polyQuickCheck x = [| quickCheck $(monomorphic x) |]
-- | Test a polymorphic property, defaulting all type variables to 'Integer'.
-- This is just a convenience function that combines 'verboseCheck' and 'monomorphic'.
--
-- If you want to use 'polyVerboseCheck' in the same file where you defined the
-- property, the same scoping problems pop up as in 'quickCheckAll':
-- see the note there about @return []@.
polyVerboseCheck :: Name -> ExpQ
polyVerboseCheck x = [| verboseCheck $(monomorphic x) |]
type Error = forall a. String -> a
-- | Monomorphise an arbitrary property by defaulting all type variables to 'Integer'.
--
-- For example, if @f@ has type @'Ord' a => [a] -> [a]@
-- then @$('monomorphic' 'f)@ has type @['Integer'] -> ['Integer']@.
--
-- If you want to use 'monomorphic' in the same file where you defined the
-- property, the same scoping problems pop up as in 'quickCheckAll':
-- see the note there about @return []@.
monomorphic :: Name -> ExpQ
monomorphic t = do
ty0 <- fmap infoType (reify t)
let err msg = error $ msg ++ ": " ++ pprint ty0
(polys, ctx, ty) <- deconstructType err ty0
case polys of
[] -> return (VarE t)
_ -> do
integer <- [t| Integer |]
ty' <- monomorphiseType err integer ty
return (SigE (VarE t) ty')
infoType :: Info -> Type
infoType (ClassOpI _ ty _ _) = ty
infoType (DataConI _ ty _ _) = ty
infoType (VarI _ ty _ _) = ty
deconstructType :: Error -> Type -> Q ([Name], Cxt, Type)
deconstructType err ty0@(ForallT xs ctx ty) = do
let plain (PlainTV _) = True
#ifndef MIN_VERSION_template_haskell
plain (KindedTV _ StarT) = True
#else
#if MIN_VERSION_template_haskell(2,8,0)
plain (KindedTV _ StarT) = True
#else
plain (KindedTV _ StarK) = True
#endif
#endif
plain _ = False
unless (all plain xs) $ err "Higher-kinded type variables in type"
return (map (\(PlainTV x) -> x) xs, ctx, ty)
deconstructType _ ty = return ([], [], ty)
monomorphiseType :: Error -> Type -> Type -> TypeQ
monomorphiseType err mono ty@(VarT n) = return mono
monomorphiseType err mono (AppT t1 t2) = liftM2 AppT (monomorphiseType err mono t1) (monomorphiseType err mono t2)
monomorphiseType err mono ty@(ForallT _ _ _) = err $ "Higher-ranked type"
monomorphiseType err mono ty = return ty
-- | Test all properties in the current module, using a custom
-- 'quickCheck' function. The same caveats as with 'quickCheckAll'
-- apply.
--
-- @$'forAllProperties'@ has type @('Property' -> 'IO' 'Result') -> 'IO' 'Bool'@.
-- An example invocation is @$'forAllProperties' 'quickCheckResult'@,
-- which does the same thing as @$'quickCheckAll'@.
--
-- 'forAllProperties' has the same issue with scoping as 'quickCheckAll':
-- see the note there about @return []@.
forAllProperties :: Q Exp -- :: (Property -> IO Result) -> IO Bool
forAllProperties = do
Loc { loc_filename = filename } <- location
when (filename == "<interactive>") $ error "don't run this interactively"
ls <- runIO (fmap lines (readUTF8File filename))
let prefixes = map (takeWhile (\c -> isAlphaNum c || c == '_' || c == '\'') . dropWhile (\c -> isSpace c || c == '>')) ls
idents = nubBy (\x y -> snd x == snd y) (filter (("prop_" `isPrefixOf`) . snd) (zip [1..] prefixes))
#if __GLASGOW_HASKELL__ > 705
warning x = reportWarning ("Name " ++ x ++ " found in source file but was not in scope")
#else
warning x = report False ("Name " ++ x ++ " found in source file but was not in scope")
#endif
quickCheckOne :: (Int, String) -> Q [Exp]
quickCheckOne (l, x) = do
exists <- (warning x >> return False) `recover` (reify (mkName x) >> return True)
if exists then sequence [ [| ($(stringE $ x ++ " from " ++ filename ++ ":" ++ show l),
property $(monomorphic (mkName x))) |] ]
else return []
[| runQuickCheckAll $(fmap (ListE . concat) (mapM quickCheckOne idents)) |]
readUTF8File name = S.openFile name S.ReadMode >>=
set_utf8_io_enc >>=
S.hGetContents
-- Deal with UTF-8 input and output.
set_utf8_io_enc :: S.Handle -> IO S.Handle
#if __GLASGOW_HASKELL__ > 611
-- possibly if MIN_VERSION_base(4,2,0)
set_utf8_io_enc h = do S.hSetEncoding h S.utf8; return h
#else
set_utf8_io_enc h = return h
#endif
-- | Test all properties in the current module.
-- The name of the property must begin with @prop_@.
-- Polymorphic properties will be defaulted to 'Integer'.
-- Returns 'True' if all tests succeeded, 'False' otherwise.
--
-- To use 'quickCheckAll', add a definition to your module along
-- the lines of
--
-- > return []
-- > runTests = $quickCheckAll
--
-- and then execute @runTests@.
--
-- Note: the bizarre @return []@ in the example above is needed on
-- GHC 7.8; without it, 'quickCheckAll' will not be able to find
-- any of the properties. For the curious, the @return []@ is a
-- Template Haskell splice that makes GHC insert the empty list
-- of declarations at that point in the program; GHC typechecks
-- everything before the @return []@ before it starts on the rest
-- of the module, which means that the later call to 'quickCheckAll'
-- can see everything that was defined before the @return []@. Yikes!
quickCheckAll :: Q Exp
quickCheckAll = [| $(forAllProperties) quickCheckResult |]
-- | Test all properties in the current module.
-- This is just a convenience function that combines 'quickCheckAll' and 'verbose'.
--
-- 'verboseCheckAll' has the same issue with scoping as 'quickCheckAll':
-- see the note there about @return []@.
verboseCheckAll :: Q Exp
verboseCheckAll = [| $(forAllProperties) verboseCheckResult |]
runQuickCheckAll :: [(String, Property)] -> (Property -> IO Result) -> IO Bool
runQuickCheckAll ps qc =
fmap and . forM ps $ \(xs, p) -> do
putStrLn $ "=== " ++ xs ++ " ==="
r <- qc p
putStrLn ""
return $ case r of
Success { } -> True
Failure { } -> False
NoExpectedFailure { } -> False
GaveUp { } -> False
InsufficientCoverage { } -> False
| soenkehahn/quickcheck | Test/QuickCheck/All.hs | bsd-3-clause | 7,492 | 0 | 20 | 1,509 | 1,353 | 743 | 610 | 85 | 5 |
{- |
Module : $Header$
Copyright : (c) Klaus Hartke, Uni Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module Main where
import Control.Monad (when)
import Data.List (intersperse)
import System.Directory (doesFileExist)
import System.Environment (getArgs)
import System.Exit (exitFailure)
import System.IO (getContents, hReady, stdin)
import Text.ParserCombinators.Parsec (parse)
import ModalCasl as Casl
import ModalCaslToNuSmvLtl as CaslToLtl
import NuSmv
main :: IO ()
main = do args <- getArgs
file <- if length args == 1 then doesFileExist (head args)
else return False
formula <- if file then readFile (head args)
else return (unwords args)
let filename = if file then head args
else "<<arguments>>"
case parse (Casl.parser CaslToLtl.expr) filename formula of
Left e1 -> do print e1
exitFailure
Right cf -> case CaslToLtl.convert cf of
Nothing -> do putStrLn "Not a LTL formula."
exitFailure
Just lf -> do i <- hReady stdin
when i $
do contents <- getContents
case parse NuSmv.program "<<input>>"
contents of
Left e2 -> do print e2
exitFailure
Right model -> print model
print lf
| mariefarrell/Hets | Temporal/Main.hs | gpl-2.0 | 1,776 | 0 | 23 | 769 | 367 | 182 | 185 | 34 | 7 |
{-# LANGUAGE FlexibleInstances, FlexibleContexts, TypeSynonymInstances
, UndecidableInstances, OverlappingInstances, MultiParamTypeClasses #-}
{- |
Module : $Header$
Description : Reduce instance for the AssignmentStore class
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (various glasgow extensions)
Reduce as AssignmentStore
-}
module CSL.ReduceInterpreter where
import Common.ProverTools (missingExecutableInPath)
import Common.Utils (getEnvDef, trimLeft)
import Common.IOS
import Common.ResultT
import CSL.Reduce_Interface ( evalString, exportExp, connectCAS, disconnectCAS
, lookupRedShellCmd, Session (..), cslReduceDefaultMapping)
import CSL.AS_BASIC_CSL
import CSL.Parse_AS_Basic (parseExpression)
import CSL.Transformation
import CSL.Interpreter
-- the process communication interface
import qualified Interfaces.Process as PC
import Control.Monad.Trans (MonadTrans (..), MonadIO (..))
import Control.Monad.State (MonadState (..))
import Data.Maybe
import System.IO (Handle)
import System.Process (ProcessHandle)
import System.Exit (ExitCode)
import Prelude hiding (lookup)
{- ----------------------------------------------------------------------
Reduce Calculator Instances
---------------------------------------------------------------------- -}
data ReduceInterpreter = ReduceInterpreter { inh :: Handle
, outh :: Handle
, ph :: ProcessHandle
, varcounter :: Int }
-- | ReduceInterpreter with Translator based on the CommandState
data RITrans = RITrans { getBMap :: BMap
, getRI :: PC.CommandState }
-- Types for two alternative reduce interpreter
-- Reds as (Red)uce (s)tandard interface
type RedsIO = ResultT (IOS ReduceInterpreter)
-- Redc as (Red)uce (c)ommand interface (it is built on CommandState)
type RedcIO = ResultT (IOS RITrans)
instance AssignmentStore RedsIO where
assign = redAssign evalRedsString redsTransS return
lookup = redLookup evalRedsString redsTransS
eval = redEval evalRedsString return
check = redCheck evalRedsString return
names = error "ReduceInterpreter as CS: names are unsupported"
instance VarGen RedsIO where
genVar = do
s <- get
let i = varcounter s
put $ s { varcounter = i + 1 }
return $ '?' : show i
instance AssignmentStore RedcIO where
assign = redAssign evalRedcString redcTransS redcTransE
lookup = redLookup evalRedcString redcTransS
eval = redEval evalRedcString redcTransE
check = redCheck evalRedcString redcTransE
names = liftM (SMem . getBMap) get
instance VarGen RedcIO where
genVar = do
s <- get
let i = newkey $ getBMap s
put $ s { getBMap = (getBMap s) { newkey = i + 1 } }
return $ '?' : show i
{- ----------------------------------------------------------------------
Reduce syntax functions
---------------------------------------------------------------------- -}
printAssignment :: String -> EXPRESSION -> String
printAssignment n e = concat [n, ":=", exportExp e, ";"]
printEvaluation :: EXPRESSION -> String
printEvaluation e = exportExp e ++ ";"
printLookup :: String -> String
printLookup n = n ++ ";"
{- As reduce does not support boolean expressions as first class citizens
we encode them in an if-stmt and transform the numeric response back. -}
printBooleanExpr :: EXPRESSION -> String
printBooleanExpr e = concat [ "on rounded;"
, " if "
, exportExp e, " then 1 else 0;"
, " off rounded;"
]
getBooleanFromExpr :: EXPRESSION -> Bool
getBooleanFromExpr (Int 1 _) = True
getBooleanFromExpr (Int 0 _) = False
getBooleanFromExpr e =
error $ "getBooleanFromExpr: can't translate expression to boolean: "
++ show e
{- ----------------------------------------------------------------------
Generic Communication Interface
---------------------------------------------------------------------- -}
{- |
The generic interface abstracts over the concrete evaluation function
-}
redAssign :: (AssignmentStore s, MonadResult s) =>
(String -> s [EXPRESSION])
-> (ConstantName -> s String)
-> (EXPRESSION -> s EXPRESSION)
-> ConstantName -> AssDefinition -> s ()
redAssign ef trans transE n def =
let e = getDefiniens def
args = getArguments def
in if null args then
do
e' <- transE e
n' <- trans n
ef $ printAssignment n' e'
return ()
else error $ "redAssign: functional assignments unsupported: " ++ show n
redLookup :: (AssignmentStore s, MonadResult s) =>
(String -> s [EXPRESSION])
-> (ConstantName -> s String)
-> ConstantName -> s (Maybe EXPRESSION)
redLookup ef trans n = do
n' <- trans n
el <- ef $ printLookup n'
return $ listToMaybe el
{- we don't want to return nothing on id-lookup: "x; --> x"
if e == mkOp n [] then return Nothing else return $ Just e -}
redEval :: (AssignmentStore s, MonadResult s) =>
(String -> s [EXPRESSION])
-> (EXPRESSION -> s EXPRESSION)
-> EXPRESSION -> s EXPRESSION
redEval ef trans e = do
e' <- trans e
el <- ef $ printEvaluation e'
if null el
then error $ "redEval: expression " ++ show e' ++ " couldn't be evaluated"
else return $ head el
redCheck :: (AssignmentStore s, MonadResult s) =>
(String -> s [EXPRESSION])
-> (EXPRESSION -> s EXPRESSION)
-> EXPRESSION -> s Bool
redCheck ef trans e = do
e' <- trans e
el <- ef $ printBooleanExpr e'
if null el
then error $ "redCheck: expression " ++ show e' ++ " couldn't be evaluated"
else return $ getBooleanFromExpr $ head el
{- ----------------------------------------------------------------------
The Standard Communication Interface
---------------------------------------------------------------------- -}
instance Session ReduceInterpreter where
inp = inh
outp = outh
proch = Just . ph
redsTransS :: ConstantName -> RedsIO String
redsTransS = return . show
evalRedsString :: String -> RedsIO [EXPRESSION]
evalRedsString s = do
r <- get
liftIO $ evalString r s
redsInit :: IO ReduceInterpreter
redsInit = do
putStr "Connecting CAS.."
reducecmd <- getEnvDef "HETS_REDUCE" "redcsl"
-- check that prog exists
noProg <- missingExecutableInPath reducecmd
if noProg
then error $ "Could not find reduce under " ++ reducecmd
else do
(inpt, out, _, pid) <- connectCAS reducecmd
return ReduceInterpreter
{ inh = inpt, outh = out, ph = pid, varcounter = 1 }
redsExit :: ReduceInterpreter -> IO ()
redsExit = disconnectCAS
{- ----------------------------------------------------------------------
An alternative Communication Interface
---------------------------------------------------------------------- -}
wrapCommand :: IOS PC.CommandState a -> IOS RITrans a
wrapCommand ios = do
r <- get
let map' x = r { getRI = x }
stmap map' getRI ios
-- | A direct way to communicate with Reduce
redcDirect :: RITrans -> String -> IO String
redcDirect rit s = do
(res, _) <- runIOS (getRI rit) (PC.call 0.5 s)
return res
redcTransE :: EXPRESSION -> RedcIO EXPRESSION
redcTransE e = do
r <- get
let bm = getBMap r
(bm', e') = translateExpr bm e
put r { getBMap = bm' }
return e'
redcTransS :: ConstantName -> RedcIO String
redcTransS s = do
r <- get
let bm = getBMap r
(bm', s') = lookupOrInsert bm $ Left s
put r { getBMap = bm' }
return s'
evalRedcString :: String -> RedcIO [EXPRESSION]
evalRedcString s = do
-- 0.09 seconds is a critical value for the accepted response time of Reduce
res <- lift $ wrapCommand $ PC.call 0.5 s
r <- get
let bm = getBMap r
trans = revtranslateExpr bm
{- don't need to skip the reducelinenr here, because the Command-Interface
cleans the outpipe before sending (hence removes the reduce line nr) -}
return $ map trans $ maybeToList $ parseExpression operatorInfoMap
$ trimLeft res
-- | init the reduce communication
redcInit :: Int -- ^ Verbosity level
-> IO RITrans
redcInit v = do
rc <- lookupRedShellCmd
case rc of
Left redcmd -> do
cs <- PC.start redcmd v Nothing
(_, cs') <- runIOS cs $ PC.send $ "off nat; load redlog; "
++ "rlset reals; " -- on rounded; precision 30;"
return RITrans { getBMap = initWithDefault cslReduceDefaultMapping
, getRI = cs' }
_ -> error "Could not find reduce shell command!"
redcExit :: RITrans -> IO (Maybe ExitCode)
redcExit r = do
(ec, _) <- runIOS (getRI r) $ PC.close $ Just "quit;"
return ec
| keithodulaigh/Hets | CSL/ReduceInterpreter.hs | gpl-2.0 | 8,987 | 0 | 16 | 2,154 | 2,102 | 1,076 | 1,026 | 183 | 2 |
-- Module : Network.AWS.EMR
-- 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.
-- | Amazon Elastic MapReduce (Amazon EMR) is a web service that makes it easy to
-- process large amounts of data efficiently. Amazon EMR uses Hadoop processing
-- combined with several AWS products to do such tasks as web indexing, data
-- mining, log file analysis, machine learning, scientific simulation, and data
-- warehousing.
module Network.AWS.EMR
( module Network.AWS.EMR.AddInstanceGroups
, module Network.AWS.EMR.AddJobFlowSteps
, module Network.AWS.EMR.AddTags
, module Network.AWS.EMR.DescribeCluster
, module Network.AWS.EMR.DescribeJobFlows
, module Network.AWS.EMR.DescribeStep
, module Network.AWS.EMR.ListBootstrapActions
, module Network.AWS.EMR.ListClusters
, module Network.AWS.EMR.ListInstanceGroups
, module Network.AWS.EMR.ListInstances
, module Network.AWS.EMR.ListSteps
, module Network.AWS.EMR.ModifyInstanceGroups
, module Network.AWS.EMR.RemoveTags
, module Network.AWS.EMR.RunJobFlow
, module Network.AWS.EMR.SetTerminationProtection
, module Network.AWS.EMR.SetVisibleToAllUsers
, module Network.AWS.EMR.TerminateJobFlows
, module Network.AWS.EMR.Types
, module Network.AWS.EMR.Waiters
) where
import Network.AWS.EMR.AddInstanceGroups
import Network.AWS.EMR.AddJobFlowSteps
import Network.AWS.EMR.AddTags
import Network.AWS.EMR.DescribeCluster
import Network.AWS.EMR.DescribeJobFlows
import Network.AWS.EMR.DescribeStep
import Network.AWS.EMR.ListBootstrapActions
import Network.AWS.EMR.ListClusters
import Network.AWS.EMR.ListInstanceGroups
import Network.AWS.EMR.ListInstances
import Network.AWS.EMR.ListSteps
import Network.AWS.EMR.ModifyInstanceGroups
import Network.AWS.EMR.RemoveTags
import Network.AWS.EMR.RunJobFlow
import Network.AWS.EMR.SetTerminationProtection
import Network.AWS.EMR.SetVisibleToAllUsers
import Network.AWS.EMR.TerminateJobFlows
import Network.AWS.EMR.Types
import Network.AWS.EMR.Waiters
| kim/amazonka | amazonka-emr/gen/Network/AWS/EMR.hs | mpl-2.0 | 2,495 | 0 | 5 | 372 | 310 | 231 | 79 | 39 | 0 |
{-# language ViewPatterns #-}
module Physics.Chipmunk.StickyEdges.Tests.Rendering where
import Prelude hiding (catch)
import Data.Abelian
import Control.Exception
import System.Random
import Graphics.Qt hiding (scale)
import Physics.Chipmunk
import Utils
import Physics.Chipmunk.StickyEdges.Tests.Properties
-- * drawing of offending values
catcher :: IO () -> IO ()
catcher cmd =
catch cmd drawOffender
-- | scale a Vector that it will be visible on the screen
scaleVector :: Size Double -> Vector -> Vector
scaleVector (Size width height) = (+~ Vector rectLimit rectLimit) >>> (flip scale factor) >>> (+~ Vector padding padding)
where
factor = min xFactor yFactor
xFactor = (width - (2 * padding)) / (4 * rectLimit)
yFactor = (height - (2 * padding)) / (2 * rectLimit)
padding = 30
drawOffender :: TestPolygons -> IO ()
drawOffender (fromTestPolygons -> offender) = do
print $ map vertices offender
withQApplication $ \ qApp ->
withMainWindow 0 1000 500 $ \ window -> do
keyPoller <- newKeyPoller window []
randoms <- generateRandoms
setDrawingCallbackMainWindow window $ Just (render (cycle randoms))
setWindowSize window $ Windowed (Size 1000 500)
showMainWindow window
execQApplication qApp
return ()
where
traversed = removeStickyEdges testEpsilon offender
render randoms ptr = do
resetMatrix ptr
windowSize <- sizeQPainter ptr
fillRect ptr zero windowSize (QtColor 55 55 55 255)
setPenColor ptr lightYellow 1
drawText ptr (Position 30 30) False (show (length offender))
mapM_ id $ zipWith (renderShape ptr) randoms $ map (mapVectors (scaleVector windowSize)) offender
resetMatrix ptr
drawText ptr (Position 60 30) False (show (length traversed))
mapM_ (mapM_ (uncurry (renderPolygonLine ptr)) . adjacentCyclic . vertices) $
map (mapVectors (scaleVector windowSize . (+~ Vector (rectLimit * 2) 0))) $
traversed
generateRandoms :: IO [(Int, Int, Int)]
generateRandoms =
mapM (const inner) [1 .. 1000]
where
inner = do
let rand = randomRIO (0, 255)
r <- rand
g <- rand
b <- rand
if r + g + b > 127 then
return (r, g, b)
else
inner
renderShape ptr (r, g, b) (Polygon vertices) = do
resetMatrix ptr
translate ptr (vector2position $ head vertices)
let Vector w h = vertices !! 2 -~ head vertices
fillRect ptr zero (Size w h) (QtColor r g b 55)
resetMatrix ptr
mapM_ (uncurry (renderPolygonLine ptr)) (adjacentCyclic vertices)
renderPolygonLine ptr a b = do
renderCorner ptr a
renderVectorLine ptr a b
renderCorner ptr (Vector x y) = do
setPenColor ptr lightYellow 1
drawCircle ptr (Position x y) 3
renderVectorLine :: Ptr QPainter -> Vector -> Vector -> IO ()
renderVectorLine ptr (Vector x1 y1) (Vector x2 y2) = do
setPenColor ptr green 1
drawLine ptr (Position x1 y1) (Position x2 y2)
renderStickyVectorLine :: Ptr QPainter -> Vector -> Vector -> IO ()
renderStickyVectorLine ptr (Vector x1 y1) (Vector x2 y2) = do
setPenColor ptr signalRed 1
drawLine ptr (Position x1 y1) (Position x2 y2)
| geocurnoff/nikki | src/testsuite/Physics/Chipmunk/StickyEdges/Tests/Rendering.hs | lgpl-3.0 | 3,253 | 0 | 19 | 812 | 1,171 | 573 | 598 | 76 | 2 |
{-# LANGUAGE CPP #-}
import Data.Function
import System.Environment
import System.FilePath
import Test.Haddock
import Test.Haddock.Utils
checkConfig :: CheckConfig String
checkConfig = CheckConfig
{ ccfgRead = Just
, ccfgClean = \_ -> id
, ccfgDump = id
, ccfgEqual = (==) `on` crlfToLf
}
dirConfig :: DirConfig
dirConfig = defaultDirConfig $ takeDirectory __FILE__
main :: IO ()
main = do
cfg <- parseArgs checkConfig dirConfig =<< getArgs
runAndCheck $ cfg
{ cfgHaddockArgs = cfgHaddockArgs cfg ++ ["--latex"]
}
| Fuuzetsu/haddock | latex-test/Main.hs | bsd-2-clause | 567 | 0 | 11 | 129 | 153 | 87 | 66 | 19 | 1 |
{-| ConstantUtils contains the helper functions for constants
This module cannot be merged with 'Ganeti.Utils' because it would
create a circular dependency if imported, for example, from
'Ganeti.Constants'.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.ConstantUtils where
import Prelude ()
import Ganeti.Prelude
import Data.Char (ord)
import Data.Set (Set)
import qualified Data.Set as Set (difference, fromList, toList, union)
import Ganeti.PyValue
-- | 'PythonChar' wraps a Python 'char'
newtype PythonChar = PythonChar { unPythonChar :: Char }
deriving (Show)
instance PyValue PythonChar where
showValue c = "chr(" ++ show (ord (unPythonChar c)) ++ ")"
-- | 'PythonNone' wraps Python 'None'
data PythonNone = PythonNone
instance PyValue PythonNone where
showValue _ = "None"
-- | FrozenSet wraps a Haskell 'Set'
--
-- See 'PyValue' instance for 'FrozenSet'.
newtype FrozenSet a = FrozenSet { unFrozenSet :: Set a }
deriving (Eq, Ord, Show)
instance (Ord a) => Monoid (FrozenSet a) where
mempty = FrozenSet mempty
mappend (FrozenSet s) (FrozenSet t) = FrozenSet (mappend s t)
-- | Converts a Haskell 'Set' into a Python 'frozenset'
--
-- This instance was supposed to be for 'Set' instead of 'FrozenSet'.
-- However, 'ghc-6.12.1' seems to be crashing with 'segmentation
-- fault' due to the presence of more than one instance of 'Set',
-- namely, this one and the one in 'Ganeti.OpCodes'. For this reason,
-- we wrap 'Set' into 'FrozenSet'.
instance PyValue a => PyValue (FrozenSet a) where
showValue s = "frozenset(" ++ showValue (Set.toList (unFrozenSet s)) ++ ")"
mkSet :: Ord a => [a] -> FrozenSet a
mkSet = FrozenSet . Set.fromList
toList :: FrozenSet a -> [a]
toList = Set.toList . unFrozenSet
union :: Ord a => FrozenSet a -> FrozenSet a -> FrozenSet a
union x y = FrozenSet (unFrozenSet x `Set.union` unFrozenSet y)
difference :: Ord a => FrozenSet a -> FrozenSet a -> FrozenSet a
difference x y = FrozenSet (unFrozenSet x `Set.difference` unFrozenSet y)
-- | 'Protocol' represents the protocols used by the daemons
data Protocol = Tcp | Udp
deriving (Show)
-- | 'PyValue' instance of 'Protocol'
--
-- This instance is used by the Haskell to Python constants
instance PyValue Protocol where
showValue Tcp = "\"tcp\""
showValue Udp = "\"udp\""
-- | Failure exit code
--
-- These are defined here and not in 'Ganeti.Constants' together with
-- the other exit codes in order to avoid a circular dependency
-- between 'Ganeti.Constants' and 'Ganeti.Runtime'
exitFailure :: Int
exitFailure = 1
-- | Console device
--
-- This is defined here and not in 'Ganeti.Constants' order to avoid a
-- circular dependency between 'Ganeti.Constants' and 'Ganeti.Logging'
devConsole :: String
devConsole = "/dev/console"
-- | Random uuid generator
--
-- This is defined here and not in 'Ganeti.Constants' order to avoid a
-- circular dependendy between 'Ganeti.Constants' and 'Ganeti.Types'
randomUuidFile :: String
randomUuidFile = "/proc/sys/kernel/random/uuid"
-- * Priority levels
--
-- This is defined here and not in 'Ganeti.Types' in order to avoid a
-- GHC stage restriction and because there is no suitable 'declareADT'
-- variant that handles integer values directly.
priorityLow :: Int
priorityLow = 10
priorityNormal :: Int
priorityNormal = 0
priorityHigh :: Int
priorityHigh = -10
-- | Calculates int version number from major, minor and revision
-- numbers.
buildVersion :: Int -> Int -> Int -> Int
buildVersion major minor revision =
1000000 * major + 10000 * minor + 1 * revision
-- | Confd protocol version
--
-- This is defined here in order to avoid a circular dependency
-- between 'Ganeti.Confd.Types' and 'Ganeti.Constants'.
confdProtocolVersion :: Int
confdProtocolVersion = 1
-- * Confd request query fields
--
-- These are defined here and not in 'Ganeti.Types' due to GHC stage
-- restrictions concerning Template Haskell. They are also not
-- defined in 'Ganeti.Constants' in order to avoid a circular
-- dependency between that module and 'Ganeti.Types'.
confdReqqLink :: String
confdReqqLink = "0"
confdReqqIp :: String
confdReqqIp = "1"
confdReqqIplist :: String
confdReqqIplist = "2"
confdReqqFields :: String
confdReqqFields = "3"
-- * ISpec
ispecMemSize :: String
ispecMemSize = "memory-size"
ispecCpuCount :: String
ispecCpuCount = "cpu-count"
ispecDiskCount :: String
ispecDiskCount = "disk-count"
ispecDiskSize :: String
ispecDiskSize = "disk-size"
ispecNicCount :: String
ispecNicCount = "nic-count"
ispecSpindleUse :: String
ispecSpindleUse = "spindle-use"
ispecsMinmax :: String
ispecsMinmax = "minmax"
ispecsStd :: String
ispecsStd = "std"
ipolicyDts :: String
ipolicyDts = "disk-templates"
ipolicyVcpuRatio :: String
ipolicyVcpuRatio = "vcpu-ratio"
ipolicySpindleRatio :: String
ipolicySpindleRatio = "spindle-ratio"
ipolicyMemoryRatio :: String
ipolicyMemoryRatio = "memory-ratio"
ipolicyDefaultsVcpuRatio :: Double
ipolicyDefaultsVcpuRatio = 4.0
ipolicyDefaultsSpindleRatio :: Double
ipolicyDefaultsSpindleRatio = 32.0
ipolicyDefaultsMemoryRatio :: Double
ipolicyDefaultsMemoryRatio = 1.0
-- * Hypervisor state default parameters
hvstDefaultCpuNode :: Int
hvstDefaultCpuNode = 1
hvstDefaultCpuTotal :: Int
hvstDefaultCpuTotal = 1
hvstDefaultMemoryHv :: Int
hvstDefaultMemoryHv = 1024
hvstDefaultMemoryTotal :: Int
hvstDefaultMemoryTotal = 1024
hvstDefaultMemoryNode :: Int
hvstDefaultMemoryNode = 4096
| andir/ganeti | src/Ganeti/ConstantUtils.hs | bsd-2-clause | 6,686 | 0 | 12 | 1,061 | 925 | 533 | 392 | 99 | 1 |
module Models.NRS where
import BasicPrelude ( Show )
import Data.Aeson ( ToJSON )
import Data.Time ( Day )
import GHC.Generics ( Generic )
import Models.Tree
import Year
data NRS =
NRS {
statuteTree :: Tree,
nominalDate :: Year, -- The "date" of this edition
dateAccessed :: Day
} deriving (Generic, Show)
instance ToJSON NRS
| dogweather/nevada-revised-statutes-parser | src/Models/NRS.hs | bsd-3-clause | 489 | 0 | 8 | 217 | 98 | 59 | 39 | 14 | 0 |
module WhereBind where
main :: Fay ()
main =
let x = 10 :: Int
in print $ x + y
where y = 20
| fpco/fay | tests/whereBind.hs | bsd-3-clause | 104 | 0 | 8 | 36 | 48 | 26 | 22 | 6 | 1 |
{-# LANGUAGE BangPatterns #-}
module ArgParse (
mkArgSpecs,
parseArgs,
flagSpan,
ArgSpec(..),
boolFlagSpec,
argParseTests ) where
import qualified Data.Map as Map
import qualified TclObj as T
import qualified Data.ByteString.Char8 as B
import Util (commaList)
import Test.HUnit
data ArgSpec t a = NoArg String (a -> a) | OneArg String (t -> a -> a)
argLabel (NoArg s _) = s
argLabel (OneArg s _) = s
mkArgSpecs keep al = (Map.fromList (map pairup al), keep)
where pairup x = (B.pack (argLabel x), x)
choiceList m = commaList "or" (map (('-':) . B.unpack) (reverse (Map.keys m)))
boolFlagSpec name keep = mkArgSpecs keep [NoArg name (const True)]
flagSpan :: [T.TclObj] -> ([T.TclObj], [T.TclObj])
flagSpan = go []
where go y [] = (reverse y,[])
go y (x:xs) = case B.uncons (T.asBStr x) of
Just ('-',r) -> if r /= B.pack "-"
then go (x:y) xs
else (reverse y, xs)
_ -> (reverse y, (x:xs))
parseArgs (as,keep) i al = inner (length al) al i
where badOpt n = fail $ "bad option " ++ show (T.asBStr n) ++ ": must be " ++ choiceList as
inner _ [] !acc = return (acc,[])
inner !r xl@(x:xs) !acc
| r <= keep = return (acc,xl)
| otherwise = do
let badopt = badOpt x
case B.uncons (T.asBStr x) of
Just ('-',rs) ->
case Map.lookup rs as of
Nothing -> badopt
Just (NoArg _ f) -> inner (r-1) xs (f acc)
Just (OneArg n f) ->
case xs of
(b:xxs) -> inner (r-2) xxs (f b acc)
_ -> fail $ "flag requires argument: -" ++ n
_ -> badopt
argParseTests = TestList [
"boolFlagSpec" ~: boolFlagTests
,(s2l "-a -b", s2l "c") ~=? flagSpan (s2l "-a -b -- c")
]
boolFlagTests = TestList [
(noCase,False,"candy shop") `should_be` (False, "candy shop")
,(noCase,False,"-nocase candy shop") `should_be` (True, "candy shop")
,(noCase,False,"shop") `should_be` (False, "shop")
,(noCase,False,"-nocase candy") `should_be` (False, "-nocase candy")
,(noCase,False,"nocase candy shop") `should_fail` ()
,(noCase,False,"-eatpie candy shop") `should_fail` ()
]
where noCase = boolFlagSpec "nocase" 2
should_be (spec,i,l) (r,al) = Right (r, s2l al) ~=? (parseArgs spec i (s2l l) :: Either String (Bool, [T.TclObj]))
should_fail (spec,i,l) _ = Nothing ~=? parseArgs spec i (s2l l)
s2l :: String -> [T.TclObj]
s2l s = map T.fromStr (words s)
| tolysz/hiccup | ArgParse.hs | lgpl-2.1 | 2,801 | 0 | 21 | 973 | 1,114 | 605 | 509 | 60 | 6 |
{-# LANGUAGE UnboxedTuples, CPP #-}
module State where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative
#endif
newtype State s a = State { runState' :: s -> (# a, s #) }
instance Functor (State s) where
fmap f m = State $ \s -> case runState' m s of
(# r, s' #) -> (# f r, s' #)
instance Applicative (State s) where
pure x = State $ \s -> (# x, s #)
m <*> n = State $ \s -> case runState' m s of
(# f, s' #) -> case runState' n s' of
(# x, s'' #) -> (# f x, s'' #)
instance Monad (State s) where
return = pure
m >>= n = State $ \s -> case runState' m s of
(# r, s' #) -> runState' (n r) s'
get :: State s s
get = State $ \s -> (# s, s #)
gets :: (s -> a) -> State s a
gets f = State $ \s -> (# f s, s #)
put :: s -> State s ()
put s' = State $ \_ -> (# (), s' #)
modify :: (s -> s) -> State s ()
modify f = State $ \s -> (# (), f s #)
evalState :: State s a -> s -> a
evalState s i = case runState' s i of
(# a, _ #) -> a
execState :: State s a -> s -> s
execState s i = case runState' s i of
(# _, s' #) -> s'
runState :: State s a -> s -> (a, s)
runState s i = case runState' s i of
(# a, s' #) -> (a, s')
| siddhanathan/ghc | compiler/utils/State.hs | bsd-3-clause | 1,332 | 0 | 15 | 503 | 592 | 311 | 281 | 33 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Mode.Latex
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Collection of 'Mode's for working with LaTeX.
module Yi.Mode.Latex (latexMode3, latexMode2, fastMode) where
import Data.Text ()
import Yi.Buffer
import qualified Yi.IncrementalParse as IncrParser (scanner)
import Yi.Lexer.Alex (AlexState, CharScanner, Tok, commonLexer, lexScanner)
import qualified Yi.Lexer.Latex as Latex (HlState, Token, alexScanToken, initState)
import Yi.Mode.Common (anyExtension, fundamentalMode)
import Yi.Syntax (ExtHL (ExtHL), Scanner, mkHighlighter)
import qualified Yi.Syntax.Driver as Driver (mkHighlighter)
import qualified Yi.Syntax.Latex as Latex (TT, Tree, getStrokes, parse, tokenToStroke)
import Yi.Syntax.OnlineTree (Tree, manyToks)
import Yi.Syntax.Tree (tokenBasedStrokes)
abstract :: Mode syntax
abstract = fundamentalMode
{
modeApplies = anyExtension ["tex", "sty", "ltx"],
modeToggleCommentSelection = Just (toggleCommentB "%")
}
fastMode :: Mode (Tree Latex.TT)
fastMode = abstract
{
modeName = "fast latex",
modeHL = ExtHL $ mkHighlighter (IncrParser.scanner manyToks . latexLexer),
modeGetStrokes = tokenBasedStrokes Latex.tokenToStroke
}
-- | syntax-based latex mode
latexMode2 :: Mode (Latex.Tree Latex.TT)
latexMode2 = abstract
{
modeName = "latex",
modeHL = ExtHL $
mkHighlighter (IncrParser.scanner Latex.parse . latexLexer),
modeGetStrokes = \t point begin end -> Latex.getStrokes point begin end t
}
-- | syntax-based latex mode
latexMode3 :: Mode (Latex.Tree Latex.TT)
latexMode3 = abstract
{
modeName = "latex",
modeHL = ExtHL $
Driver.mkHighlighter (IncrParser.scanner Latex.parse . latexLexer),
modeGetStrokes = \t point begin end -> Latex.getStrokes point begin end t
}
latexLexer :: CharScanner -> Scanner (AlexState Latex.HlState) (Tok Latex.Token)
latexLexer = lexScanner (commonLexer Latex.alexScanToken Latex.initState)
| siddhanathan/yi | yi-misc-modes/src/Yi/Mode/Latex.hs | gpl-2.0 | 2,230 | 0 | 12 | 467 | 538 | 318 | 220 | 37 | 1 |
{-# LANGUAGE Trustworthy #-}
-- ----------------------------------------------------------------------------
-- | This module provides scalable event notification for file
-- descriptors and timeouts.
--
-- This module should be considered GHC internal.
--
-- ----------------------------------------------------------------------------
module GHC.Event
( -- * Types
EventManager
, TimerManager
-- * Creation
, getSystemEventManager
, new
, getSystemTimerManager
-- * Registering interest in I/O events
, Event
, evtRead
, evtWrite
, IOCallback
, FdKey(keyFd)
, registerFd
, registerFd_
, unregisterFd
, unregisterFd_
, closeFd
-- * Registering interest in timeout events
, TimeoutCallback
, TimeoutKey
, registerTimeout
, updateTimeout
, unregisterTimeout
) where
import GHC.Event.Manager
import GHC.Event.TimerManager (TimeoutCallback, TimeoutKey, registerTimeout,
updateTimeout, unregisterTimeout, TimerManager)
import GHC.Event.Thread (getSystemEventManager, getSystemTimerManager)
| spacekitteh/smcghc | libraries/base/GHC/Event.hs | bsd-3-clause | 1,132 | 0 | 5 | 256 | 130 | 90 | 40 | 30 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.TagWindows
-- Copyright : (c) Karsten Schoelzel <[email protected]>
-- License : BSD
--
-- Maintainer : Karsten Schoelzel <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- Functions for tagging windows and selecting them by tags.
-----------------------------------------------------------------------------
module XMonad.Actions.TagWindows (
-- * Usage
-- $usage
addTag, delTag, unTag,
setTags, getTags, hasTag,
withTaggedP, withTaggedGlobalP, withFocusedP,
withTagged , withTaggedGlobal ,
focusUpTagged, focusUpTaggedGlobal,
focusDownTagged, focusDownTaggedGlobal,
shiftHere, shiftToScreen,
tagPrompt,
tagDelPrompt,
TagPrompt,
) where
import Data.List (nub,sortBy)
import Control.Monad
import Control.Exception as E
import XMonad.StackSet hiding (filter)
import XMonad.Prompt
import XMonad hiding (workspaces)
econst :: Monad m => a -> IOException -> m a
econst = const . return
-- $usage
--
-- To use window tags, import this module into your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.TagWindows
-- > import XMonad.Prompt -- to use tagPrompt
--
-- and add keybindings such as the following:
--
-- > , ((modm, xK_f ), withFocused (addTag "abc"))
-- > , ((modm .|. controlMask, xK_f ), withFocused (delTag "abc"))
-- > , ((modm .|. shiftMask, xK_f ), withTaggedGlobalP "abc" W.sink)
-- > , ((modm, xK_d ), withTaggedP "abc" (W.shiftWin "2"))
-- > , ((modm .|. shiftMask, xK_d ), withTaggedGlobalP "abc" shiftHere)
-- > , ((modm .|. controlMask, xK_d ), focusUpTaggedGlobal "abc")
-- > , ((modm, xK_g ), tagPrompt def (\s -> withFocused (addTag s)))
-- > , ((modm .|. controlMask, xK_g ), tagDelPrompt def)
-- > , ((modm .|. shiftMask, xK_g ), tagPrompt def (\s -> withTaggedGlobal s float))
-- > , ((modWinMask, xK_g ), tagPrompt def (\s -> withTaggedP s (W.shiftWin "2")))
-- > , ((modWinMask .|. shiftMask, xK_g ), tagPrompt def (\s -> withTaggedGlobalP s shiftHere))
-- > , ((modWinMask .|. controlMask, xK_g ), tagPrompt def (\s -> focusUpTaggedGlobal s))
--
-- NOTE: Tags are saved as space separated strings and split with
-- 'unwords'. Thus if you add a tag \"a b\" the window will have
-- the tags \"a\" and \"b\" but not \"a b\".
--
-- For detailed instructions on editing your key bindings, see
-- "XMonad.Doc.Extending#Editing_key_bindings".
-- | set multiple tags for a window at once (overriding any previous tags)
setTags :: [String] -> Window -> X ()
setTags = setTag . unwords
-- | set a tag for a window (overriding any previous tags)
-- writes it to the \"_XMONAD_TAGS\" window property
setTag :: String -> Window -> X ()
setTag s w = withDisplay $ \d ->
io $ internAtom d "_XMONAD_TAGS" False >>= setTextProperty d w s
-- | read all tags of a window
-- reads from the \"_XMONAD_TAGS\" window property
getTags :: Window -> X [String]
getTags w = withDisplay $ \d ->
io $ E.catch (internAtom d "_XMONAD_TAGS" False >>=
getTextProperty d w >>=
wcTextPropertyToTextList d)
(econst [[]])
>>= return . words . unwords
-- | check a window for the given tag
hasTag :: String -> Window -> X Bool
hasTag s w = (s `elem`) `fmap` getTags w
-- | add a tag to the existing ones
addTag :: String -> Window -> X ()
addTag s w = do
tags <- getTags w
if (s `notElem` tags) then setTags (s:tags) w else return ()
-- | remove a tag from a window, if it exists
delTag :: String -> Window -> X ()
delTag s w = do
tags <- getTags w
setTags (filter (/= s) tags) w
-- | remove all tags
unTag :: Window -> X ()
unTag = setTag ""
-- | Move the focus in a group of windows, which share the same given tag.
-- The Global variants move through all workspaces, whereas the other
-- ones operate only on the current workspace
focusUpTagged, focusDownTagged, focusUpTaggedGlobal, focusDownTaggedGlobal :: String -> X ()
focusUpTagged = focusTagged' (reverse . wsToList)
focusDownTagged = focusTagged' wsToList
focusUpTaggedGlobal = focusTagged' (reverse . wsToListGlobal)
focusDownTaggedGlobal = focusTagged' wsToListGlobal
wsToList :: (Ord i) => StackSet i l a s sd -> [a]
wsToList ws = crs ++ cls
where
(crs, cls) = (cms down, cms (reverse . up))
cms f = maybe [] f (stack . workspace . current $ ws)
wsToListGlobal :: (Ord i) => StackSet i l a s sd -> [a]
wsToListGlobal ws = concat ([crs] ++ rws ++ lws ++ [cls])
where
curtag = currentTag ws
(crs, cls) = (cms down, cms (reverse . up))
cms f = maybe [] f (stack . workspace . current $ ws)
(lws, rws) = (mws (<), mws (>))
mws cmp = map (integrate' . stack) . sortByTag . filter (\w -> tag w `cmp` curtag) . workspaces $ ws
sortByTag = sortBy (\x y -> compare (tag x) (tag y))
focusTagged' :: (WindowSet -> [Window]) -> String -> X ()
focusTagged' wl t = gets windowset >>= findM (hasTag t) . wl >>=
maybe (return ()) (windows . focusWindow)
findM :: (Monad m) => (a -> m Bool) -> [a] -> m (Maybe a)
findM _ [] = return Nothing
findM p (x:xs) = do b <- p x
if b then return (Just x) else findM p xs
-- | apply a pure function to windows with a tag
withTaggedP, withTaggedGlobalP :: String -> (Window -> WindowSet -> WindowSet) -> X ()
withTaggedP t f = withTagged' t (winMap f)
withTaggedGlobalP t f = withTaggedGlobal' t (winMap f)
winMap :: (Window -> WindowSet -> WindowSet) -> [Window] -> X ()
winMap f tw = when (tw /= []) (windows $ foldl1 (.) (map f tw))
withTagged, withTaggedGlobal :: String -> (Window -> X ()) -> X ()
withTagged t f = withTagged' t (mapM_ f)
withTaggedGlobal t f = withTaggedGlobal' t (mapM_ f)
withTagged' :: String -> ([Window] -> X ()) -> X ()
withTagged' t m = gets windowset >>= filterM (hasTag t) . index >>= m
withTaggedGlobal' :: String -> ([Window] -> X ()) -> X ()
withTaggedGlobal' t m = gets windowset >>=
filterM (hasTag t) . concat . map (integrate' . stack) . workspaces >>= m
withFocusedP :: (Window -> WindowSet -> WindowSet) -> X ()
withFocusedP f = withFocused $ windows . f
shiftHere :: (Ord a, Eq s, Eq i) => a -> StackSet i l a s sd -> StackSet i l a s sd
shiftHere w s = shiftWin (currentTag s) w s
shiftToScreen :: (Ord a, Eq s, Eq i) => s -> a -> StackSet i l a s sd -> StackSet i l a s sd
shiftToScreen sid w s = case filter (\m -> sid /= screen m) ((current s):(visible s)) of
[] -> s
(t:_) -> shiftWin (tag . workspace $ t) w s
data TagPrompt = TagPrompt
instance XPrompt TagPrompt where
showXPrompt TagPrompt = "Select Tag: "
tagPrompt :: XPConfig -> (String -> X ()) -> X ()
tagPrompt c f = do
sc <- tagComplList
mkXPrompt TagPrompt c (mkComplFunFromList' sc) f
tagComplList :: X [String]
tagComplList = gets (concat . map (integrate' . stack) . workspaces . windowset) >>=
mapM getTags >>=
return . nub . concat
tagDelPrompt :: XPConfig -> X ()
tagDelPrompt c = do
sc <- tagDelComplList
if (sc /= [])
then mkXPrompt TagPrompt c (mkComplFunFromList' sc) (\s -> withFocused (delTag s))
else return ()
tagDelComplList :: X [String]
tagDelComplList = gets windowset >>= maybe (return []) getTags . peek
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Actions/TagWindows.hs | bsd-2-clause | 7,669 | 0 | 16 | 1,943 | 2,134 | 1,132 | 1,002 | 107 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.ParseUtils
-- Copyright : (c) The University of Glasgow 2004
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- Utilities for parsing 'PackageDescription' and 'InstalledPackageInfo'.
--
-- The @.cabal@ file format is not trivial, especially with the introduction
-- of configurations and the section syntax that goes with that. This module
-- has a bunch of parsing functions that is used by the @.cabal@ parser and a
-- couple others. It has the parsing framework code and also little parsers for
-- many of the formats we get in various @.cabal@ file fields, like module
-- names, comma separated lists etc.
-- This module is meant to be local-only to Distribution...
{-# OPTIONS_HADDOCK hide #-}
module Distribution.ParseUtils (
LineNo, PError(..), PWarning(..), locatedErrorMsg, syntaxError, warning,
runP, runE, ParseResult(..), catchParseError, parseFail, showPWarning,
Field(..), fName, lineNo,
FieldDescr(..), ppField, ppFields, readFields, readFieldsFlat,
showFields, showSingleNamedField, showSimpleSingleNamedField,
parseFields, parseFieldsFlat,
parseFilePathQ, parseTokenQ, parseTokenQ',
parseModuleNameQ, parseBuildTool, parsePkgconfigDependency,
parseOptVersion, parsePackageNameQ, parseVersionRangeQ,
parseTestedWithQ, parseLicenseQ, parseLanguageQ, parseExtensionQ,
parseSepList, parseCommaList, parseOptCommaList,
showFilePath, showToken, showTestedWith, showFreeText, parseFreeText,
field, simpleField, listField, listFieldWithSep, spaceListField,
commaListField, commaListFieldWithSep, commaNewLineListField,
optsField, liftField, boolField, parseQuoted, indentWith,
UnrecFieldParser, warnUnrec, ignoreUnrec,
) where
import Distribution.Compiler
import Distribution.License
import Distribution.Version
import Distribution.Package
import Distribution.ModuleName
import qualified Distribution.Compat.MonadFail as Fail
import Distribution.Compat.ReadP as ReadP hiding (get)
import Distribution.ReadE
import Distribution.Text
import Distribution.Simple.Utils
import Language.Haskell.Extension
import Text.PrettyPrint hiding (braces)
import Data.Char (isSpace, toLower, isAlphaNum, isDigit)
import Data.Maybe (fromMaybe)
import Data.Tree as Tree (Tree(..), flatten)
import qualified Data.Map as Map
import Control.Monad (foldM, ap)
import Control.Applicative as AP (Applicative(..))
import System.FilePath (normalise)
import Data.List (sortBy)
-- -----------------------------------------------------------------------------
type LineNo = Int
type Separator = ([Doc] -> Doc)
data PError = AmbiguousParse String LineNo
| NoParse String LineNo
| TabsError LineNo
| FromString String (Maybe LineNo)
deriving (Eq, Show)
data PWarning = PWarning String
| UTFWarning LineNo String
deriving (Eq, Show)
showPWarning :: FilePath -> PWarning -> String
showPWarning fpath (PWarning msg) =
normalise fpath ++ ": " ++ msg
showPWarning fpath (UTFWarning line fname) =
normalise fpath ++ ":" ++ show line
++ ": Invalid UTF-8 text in the '" ++ fname ++ "' field."
data ParseResult a = ParseFailed PError | ParseOk [PWarning] a
deriving Show
instance Functor ParseResult where
fmap _ (ParseFailed err) = ParseFailed err
fmap f (ParseOk ws x) = ParseOk ws $ f x
instance Applicative ParseResult where
pure = ParseOk []
(<*>) = ap
instance Monad ParseResult where
return = AP.pure
ParseFailed err >>= _ = ParseFailed err
ParseOk ws x >>= f = case f x of
ParseFailed err -> ParseFailed err
ParseOk ws' x' -> ParseOk (ws'++ws) x'
fail = Fail.fail
instance Fail.MonadFail ParseResult where
fail s = ParseFailed (FromString s Nothing)
catchParseError :: ParseResult a -> (PError -> ParseResult a)
-> ParseResult a
p@(ParseOk _ _) `catchParseError` _ = p
ParseFailed e `catchParseError` k = k e
parseFail :: PError -> ParseResult a
parseFail = ParseFailed
runP :: LineNo -> String -> ReadP a a -> String -> ParseResult a
runP line fieldname p s =
case [ x | (x,"") <- results ] of
[a] -> ParseOk (utf8Warnings line fieldname s) a
--TODO: what is this double parse thing all about?
-- Can't we just do the all isSpace test the first time?
[] -> case [ x | (x,ys) <- results, all isSpace ys ] of
[a] -> ParseOk (utf8Warnings line fieldname s) a
[] -> ParseFailed (NoParse fieldname line)
_ -> ParseFailed (AmbiguousParse fieldname line)
_ -> ParseFailed (AmbiguousParse fieldname line)
where results = readP_to_S p s
runE :: LineNo -> String -> ReadE a -> String -> ParseResult a
runE line fieldname p s =
case runReadE p s of
Right a -> ParseOk (utf8Warnings line fieldname s) a
Left e -> syntaxError line $
"Parse of field '" ++ fieldname ++ "' failed (" ++ e ++ "): " ++ s
utf8Warnings :: LineNo -> String -> String -> [PWarning]
utf8Warnings line fieldname s =
take 1 [ UTFWarning n fieldname
| (n,l) <- zip [line..] (lines s)
, '\xfffd' `elem` l ]
locatedErrorMsg :: PError -> (Maybe LineNo, String)
locatedErrorMsg (AmbiguousParse f n) = (Just n,
"Ambiguous parse in field '"++f++"'.")
locatedErrorMsg (NoParse f n) = (Just n,
"Parse of field '"++f++"' failed.")
locatedErrorMsg (TabsError n) = (Just n, "Tab used as indentation.")
locatedErrorMsg (FromString s n) = (n, s)
syntaxError :: LineNo -> String -> ParseResult a
syntaxError n s = ParseFailed $ FromString s (Just n)
tabsError :: LineNo -> ParseResult a
tabsError ln = ParseFailed $ TabsError ln
warning :: String -> ParseResult ()
warning s = ParseOk [PWarning s] ()
-- | Field descriptor. The parameter @a@ parameterizes over where the field's
-- value is stored in.
data FieldDescr a
= FieldDescr
{ fieldName :: String
, fieldGet :: a -> Doc
, fieldSet :: LineNo -> String -> a -> ParseResult a
-- ^ @fieldSet n str x@ Parses the field value from the given input
-- string @str@ and stores the result in @x@ if the parse was
-- successful. Otherwise, reports an error on line number @n@.
}
field :: String -> (a -> Doc) -> ReadP a a -> FieldDescr a
field name showF readF =
FieldDescr name showF (\line val _st -> runP line name readF val)
-- Lift a field descriptor storing into an 'a' to a field descriptor storing
-- into a 'b'.
liftField :: (b -> a) -> (a -> b -> b) -> FieldDescr a -> FieldDescr b
liftField get set (FieldDescr name showF parseF)
= FieldDescr name (showF . get)
(\line str b -> do
a <- parseF line str (get b)
return (set a b))
-- Parser combinator for simple fields. Takes a field name, a pretty printer,
-- a parser function, an accessor, and a setter, returns a FieldDescr over the
-- compoid structure.
simpleField :: String -> (a -> Doc) -> ReadP a a
-> (b -> a) -> (a -> b -> b) -> FieldDescr b
simpleField name showF readF get set
= liftField get set $ field name showF readF
commaListFieldWithSep :: Separator -> String -> (a -> Doc) -> ReadP [a] a
-> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
commaListFieldWithSep separator name showF readF get set =
liftField get set' $
field name showF' (parseCommaList readF)
where
set' xs b = set (get b ++ xs) b
showF' = separator . punctuate comma . map showF
commaListField :: String -> (a -> Doc) -> ReadP [a] a
-> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
commaListField = commaListFieldWithSep fsep
commaNewLineListField :: String -> (a -> Doc) -> ReadP [a] a
-> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
commaNewLineListField = commaListFieldWithSep sep
spaceListField :: String -> (a -> Doc) -> ReadP [a] a
-> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
spaceListField name showF readF get set =
liftField get set' $
field name showF' (parseSpaceList readF)
where
set' xs b = set (get b ++ xs) b
showF' = fsep . map showF
listFieldWithSep :: Separator -> String -> (a -> Doc) -> ReadP [a] a
-> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
listFieldWithSep separator name showF readF get set =
liftField get set' $
field name showF' (parseOptCommaList readF)
where
set' xs b = set (get b ++ xs) b
showF' = separator . map showF
listField :: String -> (a -> Doc) -> ReadP [a] a
-> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
listField = listFieldWithSep fsep
optsField :: String -> CompilerFlavor -> (b -> [(CompilerFlavor,[String])])
-> ([(CompilerFlavor,[String])] -> b -> b) -> FieldDescr b
optsField name flavor get set =
liftField (fromMaybe [] . lookup flavor . get)
(\opts b -> set (reorder (update flavor opts (get b))) b) $
field name showF (sepBy parseTokenQ' (munch1 isSpace))
where
update _ opts l | all null opts = l --empty opts as if no opts
update f opts [] = [(f,opts)]
update f opts ((f',opts'):rest)
| f == f' = (f, opts' ++ opts) : rest
| otherwise = (f',opts') : update f opts rest
reorder = sortBy (comparing fst)
showF = hsep . map text
-- TODO: this is a bit smelly hack. It's because we want to parse bool fields
-- liberally but not accept new parses. We cannot do that with ReadP
-- because it does not support warnings. We need a new parser framework!
boolField :: String -> (b -> Bool) -> (Bool -> b -> b) -> FieldDescr b
boolField name get set = liftField get set (FieldDescr name showF readF)
where
showF = text . show
readF line str _
| str == "True" = ParseOk [] True
| str == "False" = ParseOk [] False
| lstr == "true" = ParseOk [caseWarning] True
| lstr == "false" = ParseOk [caseWarning] False
| otherwise = ParseFailed (NoParse name line)
where
lstr = lowercase str
caseWarning = PWarning $
"The '" ++ name ++ "' field is case sensitive, use 'True' or 'False'."
ppFields :: [FieldDescr a] -> a -> Doc
ppFields fields x =
vcat [ ppField name (getter x) | FieldDescr name getter _ <- fields ]
ppField :: String -> Doc -> Doc
ppField name fielddoc
| isEmpty fielddoc = empty
| name `elem` nestedFields = text name <> colon $+$ nest indentWith fielddoc
| otherwise = text name <> colon <+> fielddoc
where
nestedFields =
[ "description"
, "build-depends"
, "data-files"
, "extra-source-files"
, "extra-tmp-files"
, "exposed-modules"
, "c-sources"
, "js-sources"
, "extra-libraries"
, "includes"
, "install-includes"
, "other-modules"
, "depends"
]
showFields :: [FieldDescr a] -> a -> String
showFields fields = render . ($+$ text "") . ppFields fields
showSingleNamedField :: [FieldDescr a] -> String -> Maybe (a -> String)
showSingleNamedField fields f =
case [ get | (FieldDescr f' get _) <- fields, f' == f ] of
[] -> Nothing
(get:_) -> Just (render . ppField f . get)
showSimpleSingleNamedField :: [FieldDescr a] -> String -> Maybe (a -> String)
showSimpleSingleNamedField fields f =
case [ get | (FieldDescr f' get _) <- fields, f' == f ] of
[] -> Nothing
(get:_) -> Just (renderStyle myStyle . get)
where myStyle = style { mode = LeftMode }
parseFields :: [FieldDescr a] -> a -> String -> ParseResult a
parseFields fields initial str =
readFields str >>= accumFields fields initial
parseFieldsFlat :: [FieldDescr a] -> a -> String -> ParseResult a
parseFieldsFlat fields initial str =
readFieldsFlat str >>= accumFields fields initial
accumFields :: [FieldDescr a] -> a -> [Field] -> ParseResult a
accumFields fields = foldM setField
where
fieldMap = Map.fromList
[ (name, f) | f@(FieldDescr name _ _) <- fields ]
setField accum (F line name value) = case Map.lookup name fieldMap of
Just (FieldDescr _ _ set) -> set line value accum
Nothing -> do
warning ("Unrecognized field " ++ name ++ " on line " ++ show line)
return accum
setField accum f = do
warning ("Unrecognized stanza on line " ++ show (lineNo f))
return accum
-- | The type of a function which, given a name-value pair of an
-- unrecognized field, and the current structure being built,
-- decides whether to incorporate the unrecognized field
-- (by returning Just x, where x is a possibly modified version
-- of the structure being built), or not (by returning Nothing).
type UnrecFieldParser a = (String,String) -> a -> Maybe a
-- | A default unrecognized field parser which simply returns Nothing,
-- i.e. ignores all unrecognized fields, so warnings will be generated.
warnUnrec :: UnrecFieldParser a
warnUnrec _ _ = Nothing
-- | A default unrecognized field parser which silently (i.e. no
-- warnings will be generated) ignores unrecognized fields, by
-- returning the structure being built unmodified.
ignoreUnrec :: UnrecFieldParser a
ignoreUnrec _ = Just
------------------------------------------------------------------------------
-- The data type for our three syntactic categories
data Field
= F LineNo String String
-- ^ A regular @<property>: <value>@ field
| Section LineNo String String [Field]
-- ^ A section with a name and possible parameter. The syntactic
-- structure is:
--
-- @
-- <sectionname> <arg> {
-- <field>*
-- }
-- @
| IfBlock LineNo String [Field] [Field]
-- ^ A conditional block with an optional else branch:
--
-- @
-- if <condition> {
-- <field>*
-- } else {
-- <field>*
-- }
-- @
deriving (Show
,Eq) -- for testing
lineNo :: Field -> LineNo
lineNo (F n _ _) = n
lineNo (Section n _ _ _) = n
lineNo (IfBlock n _ _ _) = n
fName :: Field -> String
fName (F _ n _) = n
fName (Section _ n _ _) = n
fName _ = error "fname: not a field or section"
readFields :: String -> ParseResult [Field]
readFields input = ifelse
=<< mapM (mkField 0)
=<< mkTree tokens
where ls = (lines . normaliseLineEndings) input
tokens = (concatMap tokeniseLine . trimLines) ls
readFieldsFlat :: String -> ParseResult [Field]
readFieldsFlat input = mapM (mkField 0)
=<< mkTree tokens
where ls = (lines . normaliseLineEndings) input
tokens = (concatMap tokeniseLineFlat . trimLines) ls
-- attach line number and determine indentation
trimLines :: [String] -> [(LineNo, Indent, HasTabs, String)]
trimLines ls = [ (lineno, indent, hastabs, trimTrailing l')
| (lineno, l) <- zip [1..] ls
, let (sps, l') = span isSpace l
indent = length sps
hastabs = '\t' `elem` sps
, validLine l' ]
where validLine ('-':'-':_) = False -- Comment
validLine [] = False -- blank line
validLine _ = True
-- | We parse generically based on indent level and braces '{' '}'. To do that
-- we split into lines and then '{' '}' tokens and other spans within a line.
data Token =
-- | The 'Line' token is for bits that /start/ a line, eg:
--
-- > "\n blah blah { blah"
--
-- tokenises to:
--
-- > [Line n 2 False "blah blah", OpenBracket, Span n "blah"]
--
-- so lines are the only ones that can have nested layout, since they
-- have a known indentation level.
--
-- eg: we can't have this:
--
-- > if ... {
-- > } else
-- > other
--
-- because other cannot nest under else, since else doesn't start a line
-- so cannot have nested layout. It'd have to be:
--
-- > if ... {
-- > }
-- > else
-- > other
--
-- but that's not so common, people would normally use layout or
-- brackets not both in a single @if else@ construct.
--
-- > if ... { foo : bar }
-- > else
-- > other
--
-- this is OK
Line LineNo Indent HasTabs String
| Span LineNo String -- ^ span in a line, following brackets
| OpenBracket LineNo | CloseBracket LineNo
type Indent = Int
type HasTabs = Bool
-- | Tokenise a single line, splitting on '{' '}' and the spans in between.
-- Also trims leading & trailing space on those spans within the line.
tokeniseLine :: (LineNo, Indent, HasTabs, String) -> [Token]
tokeniseLine (n0, i, t, l) = case split n0 l of
(Span _ l':ss) -> Line n0 i t l' :ss
cs -> cs
where split _ "" = []
split n s = case span (\c -> c /='}' && c /= '{') s of
("", '{' : s') -> OpenBracket n : split n s'
(w , '{' : s') -> mkspan n w (OpenBracket n : split n s')
("", '}' : s') -> CloseBracket n : split n s'
(w , '}' : s') -> mkspan n w (CloseBracket n : split n s')
(w , _) -> mkspan n w []
mkspan n s ss | null s' = ss
| otherwise = Span n s' : ss
where s' = trimTrailing (trimLeading s)
tokeniseLineFlat :: (LineNo, Indent, HasTabs, String) -> [Token]
tokeniseLineFlat (n0, i, t, l)
| null l' = []
| otherwise = [Line n0 i t l']
where
l' = trimTrailing (trimLeading l)
trimLeading, trimTrailing :: String -> String
trimLeading = dropWhile isSpace
trimTrailing = dropWhileEndLE isSpace
type SyntaxTree = Tree (LineNo, HasTabs, String)
-- | Parse the stream of tokens into a tree of them, based on indent \/ layout
mkTree :: [Token] -> ParseResult [SyntaxTree]
mkTree toks =
layout 0 [] toks >>= \(trees, trailing) -> case trailing of
[] -> return trees
OpenBracket n:_ -> syntaxError n "mismatched brackets, unexpected {"
CloseBracket n:_ -> syntaxError n "mismatched brackets, unexpected }"
-- the following two should never happen:
Span n l :_ -> syntaxError n $ "unexpected span: " ++ show l
Line n _ _ l :_ -> syntaxError n $ "unexpected line: " ++ show l
-- | Parse the stream of tokens into a tree of them, based on indent
-- This parse state expect to be in a layout context, though possibly
-- nested within a braces context so we may still encounter closing braces.
layout :: Indent -- ^ indent level of the parent\/previous line
-> [SyntaxTree] -- ^ accumulating param, trees in this level
-> [Token] -- ^ remaining tokens
-> ParseResult ([SyntaxTree], [Token])
-- ^ collected trees on this level and trailing tokens
layout _ a [] = return (reverse a, [])
layout i a (s@(Line _ i' _ _):ss) | i' < i = return (reverse a, s:ss)
layout i a (Line n _ t l:OpenBracket n':ss) = do
(sub, ss') <- braces n' [] ss
layout i (Node (n,t,l) sub:a) ss'
layout i a (Span n l:OpenBracket n':ss) = do
(sub, ss') <- braces n' [] ss
layout i (Node (n,False,l) sub:a) ss'
-- look ahead to see if following lines are more indented, giving a sub-tree
layout i a (Line n i' t l:ss) = do
lookahead <- layout (i'+1) [] ss
case lookahead of
([], _) -> layout i (Node (n,t,l) [] :a) ss
(ts, ss') -> layout i (Node (n,t,l) ts :a) ss'
layout _ _ ( OpenBracket n :_) = syntaxError n "unexpected '{'"
layout _ a (s@(CloseBracket _):ss) = return (reverse a, s:ss)
layout _ _ ( Span n l : _) = syntaxError n $ "unexpected span: "
++ show l
-- | Parse the stream of tokens into a tree of them, based on explicit braces
-- This parse state expects to find a closing bracket.
braces :: LineNo -- ^ line of the '{', used for error messages
-> [SyntaxTree] -- ^ accumulating param, trees in this level
-> [Token] -- ^ remaining tokens
-> ParseResult ([SyntaxTree],[Token])
-- ^ collected trees on this level and trailing tokens
braces m a (Line n _ t l:OpenBracket n':ss) = do
(sub, ss') <- braces n' [] ss
braces m (Node (n,t,l) sub:a) ss'
braces m a (Span n l:OpenBracket n':ss) = do
(sub, ss') <- braces n' [] ss
braces m (Node (n,False,l) sub:a) ss'
braces m a (Line n i t l:ss) = do
lookahead <- layout (i+1) [] ss
case lookahead of
([], _) -> braces m (Node (n,t,l) [] :a) ss
(ts, ss') -> braces m (Node (n,t,l) ts :a) ss'
braces m a (Span n l:ss) = braces m (Node (n,False,l) []:a) ss
braces _ a (CloseBracket _:ss) = return (reverse a, ss)
braces n _ [] = syntaxError n $ "opening brace '{'"
++ "has no matching closing brace '}'"
braces _ _ (OpenBracket n:_) = syntaxError n "unexpected '{'"
-- | Convert the parse tree into the Field AST
-- Also check for dodgy uses of tabs in indentation.
mkField :: Int -> SyntaxTree -> ParseResult Field
mkField d (Node (n,t,_) _) | d >= 1 && t = tabsError n
mkField d (Node (n,_,l) ts) = case span (\c -> isAlphaNum c || c == '-') l of
([], _) -> syntaxError n $ "unrecognised field or section: " ++ show l
(name, rest) -> case trimLeading rest of
(':':rest') -> do let followingLines = concatMap Tree.flatten ts
tabs = not (null [()| (_,True,_) <- followingLines ])
if tabs && d >= 1
then tabsError n
else return $ F n (map toLower name)
(fieldValue rest' followingLines)
rest' -> do ts' <- mapM (mkField (d+1)) ts
return (Section n (map toLower name) rest' ts')
where fieldValue firstLine followingLines =
let firstLine' = trimLeading firstLine
followingLines' = map (\(_,_,s) -> stripDot s) followingLines
allLines | null firstLine' = followingLines'
| otherwise = firstLine' : followingLines'
in intercalate "\n" allLines
stripDot "." = ""
stripDot s = s
-- | Convert if/then/else 'Section's to 'IfBlock's
ifelse :: [Field] -> ParseResult [Field]
ifelse [] = return []
ifelse (Section n "if" cond thenpart
:Section _ "else" as elsepart:fs)
| null cond = syntaxError n "'if' with missing condition"
| null thenpart = syntaxError n "'then' branch of 'if' is empty"
| not (null as) = syntaxError n "'else' takes no arguments"
| null elsepart = syntaxError n "'else' branch of 'if' is empty"
| otherwise = do tp <- ifelse thenpart
ep <- ifelse elsepart
fs' <- ifelse fs
return (IfBlock n cond tp ep:fs')
ifelse (Section n "if" cond thenpart:fs)
| null cond = syntaxError n "'if' with missing condition"
| null thenpart = syntaxError n "'then' branch of 'if' is empty"
| otherwise = do tp <- ifelse thenpart
fs' <- ifelse fs
return (IfBlock n cond tp []:fs')
ifelse (Section n "else" _ _:_) = syntaxError n
"stray 'else' with no preceding 'if'"
ifelse (Section n s a fs':fs) = do fs'' <- ifelse fs'
fs''' <- ifelse fs
return (Section n s a fs'' : fs''')
ifelse (f:fs) = do fs' <- ifelse fs
return (f : fs')
------------------------------------------------------------------------------
-- |parse a module name
parseModuleNameQ :: ReadP r ModuleName
parseModuleNameQ = parseQuoted parse <++ parse
parseFilePathQ :: ReadP r FilePath
parseFilePathQ = parseTokenQ
-- removed until normalise is no longer broken, was:
-- liftM normalise parseTokenQ
betweenSpaces :: ReadP r a -> ReadP r a
betweenSpaces act = do skipSpaces
res <- act
skipSpaces
return res
parseBuildTool :: ReadP r Dependency
parseBuildTool = do name <- parseBuildToolNameQ
ver <- betweenSpaces $
parseVersionRangeQ <++ return anyVersion
return $ Dependency name ver
parseBuildToolNameQ :: ReadP r PackageName
parseBuildToolNameQ = parseQuoted parseBuildToolName <++ parseBuildToolName
-- like parsePackageName but accepts symbols in components
parseBuildToolName :: ReadP r PackageName
parseBuildToolName = do ns <- sepBy1 component (ReadP.char '-')
return (PackageName (intercalate "-" ns))
where component = do
cs <- munch1 (\c -> isAlphaNum c || c == '+' || c == '_')
if all isDigit cs then pfail else return cs
-- pkg-config allows versions and other letters in package names,
-- eg "gtk+-2.0" is a valid pkg-config package _name_.
-- It then has a package version number like 2.10.13
parsePkgconfigDependency :: ReadP r Dependency
parsePkgconfigDependency = do name <- munch1
(\c -> isAlphaNum c || c `elem` "+-._")
ver <- betweenSpaces $
parseVersionRangeQ <++ return anyVersion
return $ Dependency (PackageName name) ver
parsePackageNameQ :: ReadP r PackageName
parsePackageNameQ = parseQuoted parse <++ parse
parseVersionRangeQ :: ReadP r VersionRange
parseVersionRangeQ = parseQuoted parse <++ parse
parseOptVersion :: ReadP r Version
parseOptVersion = parseQuoted ver <++ ver
where ver :: ReadP r Version
ver = parse <++ return (Version [] [])
parseTestedWithQ :: ReadP r (CompilerFlavor,VersionRange)
parseTestedWithQ = parseQuoted tw <++ tw
where
tw :: ReadP r (CompilerFlavor,VersionRange)
tw = do compiler <- parseCompilerFlavorCompat
version <- betweenSpaces $ parse <++ return anyVersion
return (compiler,version)
parseLicenseQ :: ReadP r License
parseLicenseQ = parseQuoted parse <++ parse
-- urgh, we can't define optQuotes :: ReadP r a -> ReadP r a
-- because the "compat" version of ReadP isn't quite powerful enough. In
-- particular, the type of <++ is ReadP r r -> ReadP r a -> ReadP r a
-- Hence the trick above to make 'lic' polymorphic.
parseLanguageQ :: ReadP r Language
parseLanguageQ = parseQuoted parse <++ parse
parseExtensionQ :: ReadP r Extension
parseExtensionQ = parseQuoted parse <++ parse
parseHaskellString :: ReadP r String
parseHaskellString = readS_to_P reads
parseTokenQ :: ReadP r String
parseTokenQ = parseHaskellString <++ munch1 (\x -> not (isSpace x) && x /= ',')
parseTokenQ' :: ReadP r String
parseTokenQ' = parseHaskellString <++ munch1 (not . isSpace)
parseSepList :: ReadP r b
-> ReadP r a -- ^The parser for the stuff between commas
-> ReadP r [a]
parseSepList sepr p = sepBy p separator
where separator = betweenSpaces sepr
parseSpaceList :: ReadP r a -- ^The parser for the stuff between commas
-> ReadP r [a]
parseSpaceList p = sepBy p skipSpaces
parseCommaList :: ReadP r a -- ^The parser for the stuff between commas
-> ReadP r [a]
parseCommaList = parseSepList (ReadP.char ',')
parseOptCommaList :: ReadP r a -- ^The parser for the stuff between commas
-> ReadP r [a]
parseOptCommaList = parseSepList (optional (ReadP.char ','))
parseQuoted :: ReadP r a -> ReadP r a
parseQuoted = between (ReadP.char '"') (ReadP.char '"')
parseFreeText :: ReadP.ReadP s String
parseFreeText = ReadP.munch (const True)
-- --------------------------------------------
-- ** Pretty printing
showFilePath :: FilePath -> Doc
showFilePath "" = empty
showFilePath x = showToken x
showToken :: String -> Doc
showToken str
| not (any dodgy str) &&
not (null str) = text str
| otherwise = text (show str)
where dodgy c = isSpace c || c == ','
showTestedWith :: (CompilerFlavor,VersionRange) -> Doc
showTestedWith (compiler, version) = text (show compiler) <+> disp version
-- | Pretty-print free-format text, ensuring that it is vertically aligned,
-- and with blank lines replaced by dots for correct re-parsing.
showFreeText :: String -> Doc
showFreeText "" = empty
showFreeText s = vcat [text (if null l then "." else l) | l <- lines_ s]
-- | 'lines_' breaks a string up into a list of strings at newline
-- characters. The resulting strings do not contain newlines.
lines_ :: String -> [String]
lines_ [] = [""]
lines_ s = let (l, s') = break (== '\n') s
in l : case s' of
[] -> []
(_:s'') -> lines_ s''
-- | the indentation used for pretty printing
indentWith :: Int
indentWith = 4
| tolysz/prepare-ghcjs | spec-lts8/cabal/Cabal/Distribution/ParseUtils.hs | bsd-3-clause | 29,528 | 0 | 22 | 8,429 | 8,453 | 4,399 | 4,054 | 495 | 7 |
-- Test case of known literal with wraparound
test = case 1 :: Int of
0x10000000000000001 -> "A"
_ -> "B"
test2 = case 0x10000000000000001 :: Int of
1 -> "A"
_ -> "B"
main = putStrLn $ test ++ test2
| ezyang/ghc | testsuite/tests/codeGen/should_run/T9533b.hs | bsd-3-clause | 237 | 0 | 7 | 79 | 63 | 34 | 29 | 7 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, MagicHash
, UnboxedTuples
#-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.TopHandler
-- Copyright : (c) The University of Glasgow, 2001-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Support for catching exceptions raised during top-level computations
-- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports)
--
-----------------------------------------------------------------------------
module GHC.TopHandler (
runMainIO, runIO, runIOFastExit, runNonIO,
topHandler, topHandlerFastExit,
reportStackOverflow, reportError,
flushStdHandles
) where
#include "HsBaseConfig.h"
import Control.Exception
import Data.Maybe
import Foreign
import Foreign.C
import GHC.Base
import GHC.Conc hiding (throwTo)
import GHC.Real
import GHC.IO
import GHC.IO.Handle.FD
import GHC.IO.Handle
import GHC.IO.Exception
import GHC.Weak
#if defined(mingw32_HOST_OS)
import GHC.ConsoleHandler
#else
import Data.Dynamic (toDyn)
#endif
-- | 'runMainIO' is wrapped around 'Main.main' (or whatever main is
-- called in the program). It catches otherwise uncaught exceptions,
-- and also flushes stdout\/stderr before exiting.
runMainIO :: IO a -> IO a
runMainIO main =
do
main_thread_id <- myThreadId
weak_tid <- mkWeakThreadId main_thread_id
install_interrupt_handler $ do
m <- deRefWeak weak_tid
case m of
Nothing -> return ()
Just tid -> throwTo tid (toException UserInterrupt)
main -- hs_exit() will flush
`catch`
topHandler
install_interrupt_handler :: IO () -> IO ()
#ifdef mingw32_HOST_OS
install_interrupt_handler handler = do
_ <- GHC.ConsoleHandler.installHandler $
Catch $ \event ->
case event of
ControlC -> handler
Break -> handler
Close -> handler
_ -> return ()
return ()
#else
#include "rts/Signals.h"
-- specialised version of System.Posix.Signals.installHandler, which
-- isn't available here.
install_interrupt_handler handler = do
let sig = CONST_SIGINT :: CInt
_ <- setHandler sig (Just (const handler, toDyn handler))
_ <- stg_sig_install sig STG_SIG_RST nullPtr
-- STG_SIG_RST: the second ^C kills us for real, just in case the
-- RTS or program is unresponsive.
return ()
foreign import ccall unsafe
stg_sig_install
:: CInt -- sig no.
-> CInt -- action code (STG_SIG_HAN etc.)
-> Ptr () -- (in, out) blocked
-> IO CInt -- (ret) old action code
#endif
-- | 'runIO' is wrapped around every @foreign export@ and @foreign
-- import \"wrapper\"@ to mop up any uncaught exceptions. Thus, the
-- result of running 'System.Exit.exitWith' in a foreign-exported
-- function is the same as in the main thread: it terminates the
-- program.
--
runIO :: IO a -> IO a
runIO main = catch main topHandler
-- | Like 'runIO', but in the event of an exception that causes an exit,
-- we don't shut down the system cleanly, we just exit. This is
-- useful in some cases, because the safe exit version will give other
-- threads a chance to clean up first, which might shut down the
-- system in a different way. For example, try
--
-- main = forkIO (runIO (exitWith (ExitFailure 1))) >> threadDelay 10000
--
-- This will sometimes exit with "interrupted" and code 0, because the
-- main thread is given a chance to shut down when the child thread calls
-- safeExit. There is a race to shut down between the main and child threads.
--
runIOFastExit :: IO a -> IO a
runIOFastExit main = catch main topHandlerFastExit
-- NB. this is used by the testsuite driver
-- | The same as 'runIO', but for non-IO computations. Used for
-- wrapping @foreign export@ and @foreign import \"wrapper\"@ when these
-- are used to export Haskell functions with non-IO types.
--
runNonIO :: a -> IO a
runNonIO a = catch (a `seq` return a) topHandler
topHandler :: SomeException -> IO a
topHandler err = catch (real_handler safeExit err) topHandler
topHandlerFastExit :: SomeException -> IO a
topHandlerFastExit err =
catchException (real_handler fastExit err) topHandlerFastExit
-- Make sure we handle errors while reporting the error!
-- (e.g. evaluating the string passed to 'error' might generate
-- another error, etc.)
--
real_handler :: (Int -> IO a) -> SomeException -> IO a
real_handler exit se = do
flushStdHandles -- before any error output
case fromException se of
Just StackOverflow -> do
reportStackOverflow
exit 2
Just UserInterrupt -> exitInterrupted
_ -> case fromException se of
-- only the main thread gets ExitException exceptions
Just ExitSuccess -> exit 0
Just (ExitFailure n) -> exit n
-- EPIPE errors received for stdout are ignored (#2699)
_ -> catch (case fromException se of
Just IOError{ ioe_type = ResourceVanished,
ioe_errno = Just ioe,
ioe_handle = Just hdl }
| Errno ioe == ePIPE, hdl == stdout -> exit 0
_ -> do reportError se
exit 1
) (disasterHandler exit) -- See Note [Disaster with iconv]
-- don't use errorBelch() directly, because we cannot call varargs functions
-- using the FFI.
foreign import ccall unsafe "HsBase.h errorBelch2"
errorBelch :: CString -> CString -> IO ()
disasterHandler :: (Int -> IO a) -> IOError -> IO a
disasterHandler exit _ =
withCAString "%s" $ \fmt ->
withCAString msgStr $ \msg ->
errorBelch fmt msg >> exit 1
where
msgStr =
"encountered an exception while trying to report an exception." ++
"One possible reason for this is that we failed while trying to " ++
"encode an error message. Check that your locale is configured " ++
"properly."
{- Note [Disaster with iconv]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When using iconv, it's possible for things like iconv_open to fail in
restricted environments (like an initram or restricted container), but
when this happens the error raised inevitably calls `peekCString`,
which depends on the users locale, which depends on using
`iconv_open`... which causes an infinite loop.
This occurrence is also known as tickets #10298 and #7695. So to work
around it we just set _another_ error handler and bail directly by
calling the RTS, without iconv at all.
-}
-- try to flush stdout/stderr, but don't worry if we fail
-- (these handles might have errors, and we don't want to go into
-- an infinite loop).
flushStdHandles :: IO ()
flushStdHandles = do
hFlush stdout `catchAny` \_ -> return ()
hFlush stderr `catchAny` \_ -> return ()
safeExit, fastExit :: Int -> IO a
safeExit = exitHelper useSafeExit
fastExit = exitHelper useFastExit
unreachable :: IO a
unreachable = fail "If you can read this, shutdownHaskellAndExit did not exit."
exitHelper :: CInt -> Int -> IO a
#ifdef mingw32_HOST_OS
exitHelper exitKind r =
shutdownHaskellAndExit (fromIntegral r) exitKind >> unreachable
#else
-- On Unix we use an encoding for the ExitCode:
-- 0 -- 255 normal exit code
-- -127 -- -1 exit by signal
-- For any invalid encoding we just use a replacement (0xff).
exitHelper exitKind r
| r >= 0 && r <= 255
= shutdownHaskellAndExit (fromIntegral r) exitKind >> unreachable
| r >= -127 && r <= -1
= shutdownHaskellAndSignal (fromIntegral (-r)) exitKind >> unreachable
| otherwise
= shutdownHaskellAndExit 0xff exitKind >> unreachable
foreign import ccall "shutdownHaskellAndSignal"
shutdownHaskellAndSignal :: CInt -> CInt -> IO ()
#endif
exitInterrupted :: IO a
exitInterrupted =
#ifdef mingw32_HOST_OS
safeExit 252
#else
-- we must exit via the default action for SIGINT, so that the
-- parent of this process can take appropriate action (see #2301)
safeExit (-CONST_SIGINT)
#endif
-- NOTE: shutdownHaskellAndExit must be called "safe", because it *can*
-- re-enter Haskell land through finalizers.
foreign import ccall "Rts.h shutdownHaskellAndExit"
shutdownHaskellAndExit :: CInt -> CInt -> IO ()
useFastExit, useSafeExit :: CInt
useFastExit = 1
useSafeExit = 0
| urbanslug/ghc | libraries/base/GHC/TopHandler.hs | bsd-3-clause | 8,607 | 0 | 22 | 2,018 | 1,081 | 577 | 504 | 118 | 6 |
{-# LANGUAGE DataKinds #-}
module T8455 where
ty = [t| 5 |]
| ghc-android/ghc | testsuite/tests/quotes/T8455.hs | bsd-3-clause | 62 | 0 | 4 | 14 | 14 | 11 | 3 | -1 | -1 |
import System.Environment
import System.IO
import System.Directory
import Control.Monad
import Shake
import JsonSettings
import RevReport
import WithLatestLogs
import Summary
import GraphReport
import BenchNames
import GraphSummaries
import GHC.IO.Encoding
{-
We want to build everything into one executable, bit still treat
it as multiple tools. Hence the main function
here calls the various real main functions, defaulting to the shake tool.
-}
main :: IO ()
main = do
-- Make us locale-independent
setLocaleEncoding utf8
args <- getArgs
ex <- doesFileExist "gipeda.yaml"
unless ex $ do
hPutStr stderr "Please run this from the same directory as the gipeda.yaml file.\n"
case args of
"JsonSettings":_ -> jsonSettingsMain
"Summary":opts -> summaryMain opts
"RevReport":opts -> revReportMain opts
"BranchReport":opts -> branchReportMain opts
"GraphReport":opts -> graphReportMain opts
"WithLatestLogs":opts -> withLatestLogsMain opts
"BenchNames":opts -> benchNamesMain opts
"GraphSummaries":opts -> graphSummaries opts
_ -> shakeMain -- shake will take the arguments from getArgs
| nomeata/gipeda | src/gipeda.hs | mit | 1,225 | 0 | 10 | 284 | 224 | 112 | 112 | 30 | 9 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-pointintimerecoveryspecification.html
module Stratosphere.ResourceProperties.DynamoDBTablePointInTimeRecoverySpecification where
import Stratosphere.ResourceImports
-- | Full data type definition for
-- DynamoDBTablePointInTimeRecoverySpecification. See
-- 'dynamoDBTablePointInTimeRecoverySpecification' for a more convenient
-- constructor.
data DynamoDBTablePointInTimeRecoverySpecification =
DynamoDBTablePointInTimeRecoverySpecification
{ _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled :: Maybe (Val Bool)
} deriving (Show, Eq)
instance ToJSON DynamoDBTablePointInTimeRecoverySpecification where
toJSON DynamoDBTablePointInTimeRecoverySpecification{..} =
object $
catMaybes
[ fmap (("PointInTimeRecoveryEnabled",) . toJSON) _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled
]
-- | Constructor for 'DynamoDBTablePointInTimeRecoverySpecification'
-- containing required fields as arguments.
dynamoDBTablePointInTimeRecoverySpecification
:: DynamoDBTablePointInTimeRecoverySpecification
dynamoDBTablePointInTimeRecoverySpecification =
DynamoDBTablePointInTimeRecoverySpecification
{ _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-pointintimerecoveryspecification.html#cfn-dynamodb-table-pointintimerecoveryspecification-pointintimerecoveryenabled
ddbtpitrsPointInTimeRecoveryEnabled :: Lens' DynamoDBTablePointInTimeRecoverySpecification (Maybe (Val Bool))
ddbtpitrsPointInTimeRecoveryEnabled = lens _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled (\s a -> s { _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/DynamoDBTablePointInTimeRecoverySpecification.hs | mit | 2,017 | 0 | 12 | 159 | 175 | 102 | 73 | 22 | 1 |
-- This file is part of the 'union-find-array' library. It is licensed
-- under an MIT license. See the accompanying 'LICENSE' file for details.
--
-- Authors: Bertram Felgenhauer
{-# LANGUAGE RankNTypes, FlexibleContexts, CPP #-}
-- |
-- Low-level interface for managing a disjoint set data structure, based on
-- 'Control.Monad.ST'. For a higher level convenience interface, look at
-- 'Control.Monad.Union'.
module Data.Union.ST (
UnionST,
runUnionST,
new,
grow,
copy,
lookup,
annotate,
merge,
flatten,
size,
unsafeFreeze,
) where
import qualified Data.Union.Type as U
import Prelude hiding (lookup)
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import Data.Array.Base hiding (unsafeFreeze)
import Data.Array.ST hiding (unsafeFreeze)
import qualified Data.Array.Base as A (unsafeFreeze)
-- | A disjoint set forest, with nodes numbered from 0, which can carry labels.
data UnionST s l = UnionST {
up :: STUArray s Int Int,
rank :: STUArray s Int Int,
label :: STArray s Int l,
size :: !Int,
def :: l
}
#if __GLASGOW_HASKELL__ < 702
instance Applicative (ST s) where
(<*>) = ap
pure = return
#endif
-- Use http://www.haskell.org/pipermail/libraries/2008-March/009465.html ?
-- | Analogous to 'Data.Array.ST.runSTArray'.
runUnionST :: (forall s. ST s (UnionST s l)) -> U.Union l
runUnionST a = runST $ a >>= unsafeFreeze
-- | Analogous to 'Data.Array.Base.unsafeFreeze'
unsafeFreeze :: UnionST s l -> ST s (U.Union l)
unsafeFreeze u =
U.Union (size u) <$> A.unsafeFreeze (up u) <*> A.unsafeFreeze (label u)
-- What about thawing?
-- | Create a new disjoint set forest, of given capacity.
new :: Int -> l -> ST s (UnionST s l)
new size def = do
up <- newListArray (0, size-1) [0..]
rank <- newArray (0, size-1) 0
label <- newArray (0, size-1) def
return UnionST{ up = up, rank = rank, label = label, size = size, def = def }
-- | Grow the capacity of a disjoint set forest. Shrinking is not possible.
-- Trying to shrink a disjoint set forest will return the same forest
-- unmodified.
grow :: UnionST s l -> Int -> ST s (UnionST s l)
grow u size' | size' <= size u = return u
grow u size' = grow' u size'
-- | Copy a disjoint set forest.
copy :: UnionST s l -> ST s (UnionST s l)
copy u = grow' u (size u)
grow' :: UnionST s l -> Int -> ST s (UnionST s l)
grow' u size' = do
up' <- newListArray (0, size'-1) [0..]
rank' <- newArray (0, size'-1) 0
label' <- newArray (0, size'-1) (def u)
forM_ [0..size u - 1] $ \i -> do
readArray (up u) i >>= writeArray up' i
readArray (rank u) i >>= writeArray rank' i
readArray (label u) i >>= writeArray label' i
return u{ up = up', rank = rank', label = label', size = size' }
-- | Annotate a node with a new label.
annotate :: UnionST s l -> Int -> l -> ST s ()
annotate u i v = writeArray (label u) i v
-- | Look up the representative of a given node.
--
-- lookup' does path compression.
lookup' :: UnionST s l -> Int -> ST s Int
lookup' u i = do
i' <- readArray (up u) i
if i == i' then return i else do
i'' <- lookup' u i'
writeArray (up u) i i''
return i''
-- | Look up the representative of a given node and its label.
lookup :: UnionST s l -> Int -> ST s (Int, l)
lookup u i = do
i' <- lookup' u i
l' <- readArray (label u) i'
return (i', l')
-- | Check whether two nodes are in the same set.
equals :: UnionST s l -> Int -> Int -> ST s Bool
equals u a b = do
a' <- lookup' u a
b' <- lookup' u b
return (a' == b')
-- | Merge two nodes if they are in distinct equivalence classes. The
-- passed function is used to combine labels, if a merge happens.
merge :: UnionST s l -> (l -> l -> (l, a)) -> Int -> Int -> ST s (Maybe a)
merge u f a b = do
(a', va) <- lookup u a
(b', vb) <- lookup u b
if a' == b' then return Nothing else do
ra <- readArray (rank u) a'
rb <- readArray (rank u) b'
let cont x vx y vy = do
writeArray (label u) y (error "invalid entry")
let (v, w) = f vx vy
writeArray (label u) x v
return (Just w)
case ra `compare` rb of
LT -> do
writeArray (up u) a' b'
cont b' vb a' va
GT -> do
writeArray (up u) b' a'
cont a' va b' vb
EQ -> do
writeArray (up u) a' b'
writeArray (rank u) b' (ra + 1)
cont b' vb a' va
-- | Flatten a disjoint set forest, for faster lookups.
flatten :: UnionST s l -> ST s ()
flatten u = forM_ [0..size u - 1] $ lookup' u
| haskell-rewriting/union-find-array | src/Data/Union/ST.hs | mit | 4,700 | 0 | 18 | 1,307 | 1,616 | 824 | 792 | 102 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RankNTypes #-}
module Crud.Core where
-- import Data.Generics
import qualified Language.Haskell.TH as TH
-- import Language.Haskell.TH.Quote
-- import Data.Data
import Import
import Yesod.Form.Bootstrap3
import Text.Blaze
{-
Este conjunto de operaciones permite al programador realizar
las operaciones de crear
-}
getNewRoute :: String -> String -> TH.Q [TH.Dec]
getNewRoute name formName = do
let method = TH.mkName $ "get" ++ name ++ "NewR"
getNew name formName method
getNewMethod :: String -> String -> TH.Q [TH.Dec]
getNewMethod name formName = do
let method = TH.mkName $ "get" ++ name ++ "New"
getNew name formName method
postNewRoute :: String -> String -> String -> TH.Q [TH.Dec]
postNewRoute name formName redirectName = do
let method = TH.mkName $ "post" ++ name ++ "NewR"
postNew name formName redirectName method
postNewMethod :: String -> String -> String -> TH.Q [TH.Dec]
postNewMethod name formName redirectName = do
let method = TH.mkName $ "post" ++ name ++ "New"
postNew name formName redirectName method
{-
Este conjunto de operaciones permite al programador realizar
las operaciones de Editar
-}
getEditRoute :: String -> String -> TH.Q [TH.Dec]
getEditRoute name formName = do
let method = TH.mkName $ "get" ++ name ++ "EditR"
getEdit name formName method
getEditMethod :: String -> String -> TH.Q [TH.Dec]
getEditMethod name formName = do
let method = TH.mkName $ "get" ++ name ++ "Edit"
getEdit name formName method
postEditRoute :: String -> String -> String -> TH.Q [TH.Dec]
postEditRoute name formName redirectName = do
let method = TH.mkName $ "post" ++ name ++ "EditR"
postEdit name formName redirectName method
postEditMethod :: String -> String -> String -> TH.Q [TH.Dec]
postEditMethod name formName redirectName = do
let method = TH.mkName $ "post" ++ name ++ "Edit"
postEdit name formName redirectName method
{-
Este conjunto de operaciones permite al programador realizar
las operaciones de eliminar
-}
deleteCrudRoute :: String -> String -> TH.Q [TH.Dec]
deleteCrudRoute name redirectName = do
let method = TH.mkName $ "delete" ++ name ++ "DeleteR"
deleteCrud name redirectName method
deleteCrudMethod :: String -> String -> TH.Q [TH.Dec]
deleteCrudMethod name redirectName = do
let method = TH.mkName $ "delete" ++ name ++ "Delete"
deleteCrud name redirectName method
{-
Este conjunto de operaciones permite al programador realizar
las operaciones de listar
-}
listCrudRoute :: String -> String -> TH.Q [TH.Dec]
listCrudRoute name fieldListName = do
let method = TH.mkName $ "get" ++ name ++ "ListR"
listCrud name fieldListName method
listCrudMethod :: String -> String -> TH.Q [TH.Dec]
listCrudMethod name fieldListName = do
let method = TH.mkName $ "get" ++ name ++ "List"
listCrud name fieldListName method
{-
Este conjunto de operaciones desarrolla la logica de los hamlet
-}
getNew :: String -> String -> TH.Name -> TH.Q [TH.Dec]
getNew name formName method = do
let form = TH.varE $ TH.mkName formName
action = TH.conE $ TH.mkName $ name ++ "NewR"
body = [| do
(widget, encoding) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm $ $form Nothing
defaultLayout $ do
let actionR = $action
formHamlet widget encoding actionR |]
typ <- TH.sigD method [t| HandlerT App IO Html |]
fun <- TH.funD method [TH.clause [] (TH.normalB body) []]
return [typ,fun]
postNew :: String -> String -> String -> TH.Name -> TH.Q [TH.Dec]
postNew name formName redirectName method = do
let form = TH.varE $ TH.mkName formName
action = TH.conE $ TH.mkName $ name ++ "NewR"
redirectAction = TH.conE $ TH.mkName redirectName
body = [| do
((result,widget), encoding) <- runFormPost $ renderBootstrap3 BootstrapBasicForm $ $form Nothing
case result of
FormSuccess entity -> do
_ <- runDB $ insert entity
redirect $redirectAction
_ -> defaultLayout $ do
let actionR = $action
formHamlet widget encoding actionR|]
typ <- TH.sigD method [t| HandlerT App IO Html |]
fun <- TH.funD method [TH.clause [] (TH.normalB body) []]
return [typ,fun]
getEdit :: String -> String -> TH.Name -> TH.Q [TH.Dec]
getEdit name formName method = do
entityName <- TH.newName "eId"
let form = TH.varE $ TH.mkName formName
action = TH.conE $ TH.mkName $ name ++ "EditR"
entityId = TH.varE entityName
entityParam = TH.varP entityName
entityType = TH.conT $ TH.mkName $ name ++ "Id"
body = [| do
entity <- runDB $ get404 $entityId
(widget, encoding) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm $ $form (Just entity)
defaultLayout $ do
let actionR = $action $entityId
formHamlet widget encoding actionR |]
typ <- TH.sigD method [t| $entityType -> HandlerT App IO Html |]
fun <- TH.funD method [TH.clause [entityParam] (TH.normalB body) []]
return [typ,fun]
postEdit :: String -> String -> String -> TH.Name -> TH.Q [TH.Dec]
postEdit name formName redirectName method= do
entityName <- TH.newName "eId"
let form = TH.varE $ TH.mkName formName
action = TH.conE $ TH.mkName $ name ++ "EditR"
entityId = TH.varE entityName
entityParam = TH.varP entityName
entityType = TH.conT $ TH.mkName $ name ++ "Id"
redirectAction = TH.conE $ TH.mkName redirectName
body = [| do
entity <- runDB $ get404 $entityId
((result,widget), encoding) <- runFormPost $ renderBootstrap3 BootstrapBasicForm $ $form (Just entity)
case result of
FormSuccess resultForm -> do
_ <- runDB $ replace $entityId resultForm
redirect $redirectAction
_ -> defaultLayout $ do
let actionR = $action $entityId
formHamlet widget encoding actionR |]
typ <- TH.sigD method [t| $entityType -> HandlerT App IO Html |]
fun <- TH.funD method [TH.clause [entityParam] (TH.normalB body) []]
return [typ,fun]
deleteCrud :: String -> String -> TH.Name -> TH.Q [TH.Dec]
deleteCrud name redirectName method= do
entityName <- TH.newName "eId"
let entityId = TH.varE entityName
entityParam = TH.varP entityName
entityType = TH.conT $ TH.mkName $ name ++ "Id"
redirectAction = TH.conE $ TH.mkName redirectName
body = [| do
runDB $ delete $entityId
redirect $redirectAction |]
typ <- TH.sigD method [t| $entityType -> HandlerT App IO Html |]
fun <- TH.funD method [TH.clause [entityParam] (TH.normalB body) []]
return [typ,fun]
listCrud :: String -> String -> TH.Name -> TH.Q [TH.Dec]
listCrud name fieldListName method= do
let fieldList = TH.varE $ TH.mkName fieldListName
newAction = TH.conE $ TH.mkName (name ++ "NewR")
editAction = TH.conE $ TH.mkName (name ++ "EditR")
deleteAction = TH.conE $ TH.mkName (name ++ "DeleteR")
body = [| do list <- runDB $ selectList [] []
defaultLayout $ do
listHamlet list $fieldList $newAction $editAction $deleteAction
toWidgetBody deleteJulius|]
typ <- TH.sigD method [t| HandlerT App IO Html |]
fun <- TH.funD method [TH.clause [] (TH.normalB body) []]
return [typ,fun]
{-
Este conjunto de operaciones general lo interfaz para crear editar y listar
y el javascript para eliminar
-}
formHamlet :: forall site (m :: * -> *) a a1.
(ToMarkup a, MonadThrow m,
MonadBaseControl IO m, MonadIO m, ToWidget site a1) =>
a1 -> a -> Route site -> WidgetT site m ()
formHamlet widget encoding actionR = [whamlet|
<div .container>
<form method=post action=@{actionR} encType=#{encoding}>
<div .row>
^{widget}
<div .row .clearfix .visible-xs-block>
<button .btn .btn-success>
<span .glyphicon .glyphicon-floppy-saved>
submit
|]
listHamlet :: forall site (m :: * -> *) (t :: * -> *) t1 a.
(ToMarkup a, MonadThrow m, MonadBaseControl IO m,
MonoFoldable (t (Entity t1)), MonadIO m, Foldable t) =>
t (Entity t1)
-> (t1 -> a)
-> Route site
-> (Key t1 -> Route site)
-> (Key t1 -> Route site)
-> WidgetT site m ()
listHamlet list identificateAtribute new edit deleteRoute= [whamlet|
<div>
<h1> DATA
$if null list
<p> There are no data
$else
<table .table .table-responsive .table-hover>
<thead>
<th> identificate
<th> edit
<th> delete
$forall Entity entityId entity <- list
<tbody>
<tr>
<td>
#{identificateAtribute entity}
<td >
<button onclick=deletePost('@{deleteRoute entityId}') .btn .btn-danger>
<span .glyphicon .glyphicon-trash>
delete
<td>
<a href=@{edit entityId} .btn .btn-warning .pull-right>
<span .glyphicon .glyphicon-edit>
edit
<a href=@{new} .btn .btn-primary .pull-right>
<span .glyphicon .glyphicon-plus>
create
|]
deleteJulius :: forall url. JavascriptUrl url
deleteJulius = [julius|
function deletePost(deleteUrl) {
$.ajax({
url: deleteUrl,
type: 'DELETE',
success: function(result) {
location.reload();
}
});
}
|]
-- formParam :: [String] -> [(TH.Exp, TH.Pat,TH.Type)]
{- formParam [] = []
formParam (x:[]) = do
entityName <- TH.newName $ "e" ++ x
let entityId = TH.varE entityName
entityParam = TH.varP entityName
entityType = TH.conT $ TH.mkName $ x
[(entityId,entityParam,entityType)]
formParam (x:xs) = []
-} | jairoGilC/Yesod-CRUD-Generator | Crud/Core.hs | mit | 10,805 | 0 | 14 | 3,469 | 2,350 | 1,201 | 1,149 | -1 | -1 |
module GUBS.Solver.Formula where
import Data.Foldable (toList)
import GUBS.Algebra
data Atom e = Geq e e | Eq e e
deriving (Functor, Foldable, Traversable)
data BoolLit l = BoolLit l | NegBoolLit l
deriving (Functor, Foldable, Traversable)
-- TODO gadtify
data Formula l e =
Top
| Bot
| Lit (BoolLit l)
| Atom (Atom e)
| Or (Formula l e) (Formula l e)
| And (Formula l e) (Formula l e)
| Iff (Formula l e) (Formula l e)
| LetB (Formula l e) (l -> Formula l e)
subst :: (Atom e -> Formula l e') -> Formula l e -> Formula l e'
subst _ Top = Top
subst _ Bot = Bot
subst _ (Lit l) = Lit l
subst f (Atom a) = f a
subst f (Or e1 e2) = Or (subst f e1) (subst f e2)
subst f (And e1 e2) = And (subst f e1) (subst f e2)
subst f (LetB e1 e2) = LetB (subst f e1) (subst f . e2)
subst f (Iff e1 e2) = Iff (subst f e1) (subst f e2)
literal :: l -> Formula l e
literal = Lit . BoolLit
atoms :: Formula l e -> [Atom e]
atoms (Atom a) = [a]
atoms Top = []
atoms Bot = []
atoms Lit{} = []
atoms (Or f1 f2) = atoms f1 ++ atoms f2
atoms (And f1 f2) = atoms f1 ++ atoms f2
atoms (Iff f1 f2) = atoms f1 ++ atoms f2
atoms (LetB f1 f2) = atoms f1 ++ atoms (f2 undefined)
negLiteral :: l -> Formula l e
negLiteral = Lit . NegBoolLit
gtA,eqA,geqA :: (IsNat e, Additive e) => e -> e -> Formula l e
gtA e1 e2 = Atom (Geq e1 (e2 .+ fromNatural 1))
eqA e1 e2 = Atom (Eq e1 e2)
geqA e1 e2 = Atom (Geq e1 e2)
smtTop, smtBot :: Formula b e
smtTop = Top
smtBot = Bot
smtBool :: Bool -> Formula b e
smtBool True = Top
smtBool False = Bot
-- smtNot :: (IsNat e, Additive e) => Formula l e -> Formula l e
-- smtNot Top = Bot
-- smtNot Bot = Top
-- smtNot (Lit (BoolLit l)) = smtNot (Lit (NegBoolLit l))
-- smtNot (Lit (NegBoolLit l)) = smtNot (Lit (BoolLit l))
-- smtNot (Atom (Geq e1 e2)) = e2 `gtA` e1
-- smtNot (Atom (Eq e1 e2)) = Or (e1 `gtA` e2) (e2 `gtA` e1)
-- smtNot (Or f1 f2) = And (smtNot f1) (smtNot f2)
-- smtNot (And f1 f2) = Or (smtNot f1) (smtNot f2)
-- smtNot (Iff f1 f2) = Iff (smtNot f1) f2
-- smtNot (LetB f1 f2) = LetB f1 (smtNot . f2)
smtAnd, smtOr :: Formula l e -> Formula l e -> Formula l e
Top `smtAnd` f2 = f2
f1 `smtAnd` Top = f1
Bot `smtAnd` _ = Bot
_ `smtAnd` Bot = Bot
f1 `smtAnd` f2 = And f1 f2
Bot `smtOr` f2 = f2
f1 `smtOr` Bot = f1
Top `smtOr` _ = Top
_ `smtOr` Top = Top
f1 `smtOr` f2 = Or f1 f2
smtBigOr, smtBigAnd :: [Formula l e] -> Formula l e
smtBigOr = foldr smtOr smtBot
smtBigAnd = foldr smtAnd smtTop
smtAll, smtAny :: Foldable t => (a -> Formula l e) -> t a -> Formula l e
smtAll f t = smtBigAnd [ f a | a <- toList t]
smtAny f t = smtBigOr [ f a | a <- toList t]
letB :: Formula l e -> (l -> Formula l e) -> Formula l e
letB = LetB
letB' :: [Formula l e] -> ([l] -> Formula l e) -> Formula l e
letB' = walk [] where
walk ls [] f = f (reverse ls)
walk ls (e:es) f = LetB e (\ l -> walk (l:ls) es f)
| mzini/gubs | src/GUBS/Solver/Formula.hs | mit | 2,876 | 0 | 12 | 712 | 1,349 | 693 | 656 | 71 | 2 |
-- The sum of the squares of the first ten natural numbers is,
-- 1^2 + 2^2 + ... + 10^2 = 385
-- The square of the sum of the first ten natural numbers is,
-- (1 + 2 + ... + 10)^2 = 55^2 = 3025
-- Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
-- Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
calc :: Integer
calc = ((sum [1..100]) ^ 2) - (sum [x^2 | x <- [1..100]])
main :: IO ()
main = print calc | daniel-beard/projecteulerhaskell | Problems/p6.hs | mit | 565 | 0 | 11 | 127 | 83 | 47 | 36 | 4 | 1 |
data MyType = MyType
deriving (Show)
| zhangjiji/real-world-haskell | ch6/ch6.hs | mit | 49 | 0 | 6 | 18 | 15 | 8 | 7 | 2 | 0 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.EXTsRGB
(pattern SRGB_EXT, pattern SRGB_ALPHA_EXT,
pattern SRGB8_ALPHA8_EXT,
pattern FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT, EXTsRGB,
castToEXTsRGB, gTypeEXTsRGB)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
pattern SRGB_EXT = 35904
pattern SRGB_ALPHA_EXT = 35906
pattern SRGB8_ALPHA8_EXT = 35907
pattern FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 33296 | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/EXTsRGB.hs | mit | 1,204 | 0 | 6 | 142 | 335 | 217 | 118 | 24 | 0 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLEmbedElement
(js_getSVGDocument, getSVGDocument, js_setAlign, setAlign,
js_getAlign, getAlign, js_setHeight, setHeight, js_getHeight,
getHeight, js_setName, setName, js_getName, getName, js_setSrc,
setSrc, js_getSrc, getSrc, js_setType, setType, js_getType,
getType, js_setWidth, setWidth, js_getWidth, getWidth,
HTMLEmbedElement, castToHTMLEmbedElement, gTypeHTMLEmbedElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"getSVGDocument\"]()"
js_getSVGDocument :: HTMLEmbedElement -> IO (Nullable SVGDocument)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.getSVGDocument Mozilla HTMLEmbedElement.getSVGDocument documentation>
getSVGDocument ::
(MonadIO m) => HTMLEmbedElement -> m (Maybe SVGDocument)
getSVGDocument self
= liftIO (nullableToMaybe <$> (js_getSVGDocument (self)))
foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign
:: HTMLEmbedElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.align Mozilla HTMLEmbedElement.align documentation>
setAlign ::
(MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m ()
setAlign self val = liftIO (js_setAlign (self) (toJSString val))
foreign import javascript unsafe "$1[\"align\"]" js_getAlign ::
HTMLEmbedElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.align Mozilla HTMLEmbedElement.align documentation>
getAlign ::
(MonadIO m, FromJSString result) => HTMLEmbedElement -> m result
getAlign self = liftIO (fromJSString <$> (js_getAlign (self)))
foreign import javascript unsafe "$1[\"height\"] = $2;"
js_setHeight :: HTMLEmbedElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.height Mozilla HTMLEmbedElement.height documentation>
setHeight ::
(MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m ()
setHeight self val = liftIO (js_setHeight (self) (toJSString val))
foreign import javascript unsafe "$1[\"height\"]" js_getHeight ::
HTMLEmbedElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.height Mozilla HTMLEmbedElement.height documentation>
getHeight ::
(MonadIO m, FromJSString result) => HTMLEmbedElement -> m result
getHeight self = liftIO (fromJSString <$> (js_getHeight (self)))
foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName ::
HTMLEmbedElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.name Mozilla HTMLEmbedElement.name documentation>
setName ::
(MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m ()
setName self val = liftIO (js_setName (self) (toJSString val))
foreign import javascript unsafe "$1[\"name\"]" js_getName ::
HTMLEmbedElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.name Mozilla HTMLEmbedElement.name documentation>
getName ::
(MonadIO m, FromJSString result) => HTMLEmbedElement -> m result
getName self = liftIO (fromJSString <$> (js_getName (self)))
foreign import javascript unsafe "$1[\"src\"] = $2;" js_setSrc ::
HTMLEmbedElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.src Mozilla HTMLEmbedElement.src documentation>
setSrc ::
(MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m ()
setSrc self val = liftIO (js_setSrc (self) (toJSString val))
foreign import javascript unsafe "$1[\"src\"]" js_getSrc ::
HTMLEmbedElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.src Mozilla HTMLEmbedElement.src documentation>
getSrc ::
(MonadIO m, FromJSString result) => HTMLEmbedElement -> m result
getSrc self = liftIO (fromJSString <$> (js_getSrc (self)))
foreign import javascript unsafe "$1[\"type\"] = $2;" js_setType ::
HTMLEmbedElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.type Mozilla HTMLEmbedElement.type documentation>
setType ::
(MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m ()
setType self val = liftIO (js_setType (self) (toJSString val))
foreign import javascript unsafe "$1[\"type\"]" js_getType ::
HTMLEmbedElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.type Mozilla HTMLEmbedElement.type documentation>
getType ::
(MonadIO m, FromJSString result) => HTMLEmbedElement -> m result
getType self = liftIO (fromJSString <$> (js_getType (self)))
foreign import javascript unsafe "$1[\"width\"] = $2;" js_setWidth
:: HTMLEmbedElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.width Mozilla HTMLEmbedElement.width documentation>
setWidth ::
(MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m ()
setWidth self val = liftIO (js_setWidth (self) (toJSString val))
foreign import javascript unsafe "$1[\"width\"]" js_getWidth ::
HTMLEmbedElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.width Mozilla HTMLEmbedElement.width documentation>
getWidth ::
(MonadIO m, FromJSString result) => HTMLEmbedElement -> m result
getWidth self = liftIO (fromJSString <$> (js_getWidth (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLEmbedElement.hs | mit | 6,343 | 90 | 10 | 944 | 1,457 | 806 | 651 | 88 | 1 |
module GetOpt.Declarative.UtilSpec (spec) where
import Prelude ()
import Helper
import System.Console.GetOpt
import GetOpt.Declarative.Util
spec :: Spec
spec = do
describe "mkUsageInfo" $ do
it "restricts output size to 80 characters" $ do
let options = [
Option "" ["color"] (NoArg ()) (unwords $ replicate 3 "some very long and verbose help text")
]
mkUsageInfo "" options `shouldBe` unlines [
""
, " --color some very long and verbose help text some very long and verbose"
, " help text some very long and verbose help text"
]
it "condenses help for --no-options" $ do
let options = [
Option "" ["color"] (NoArg ()) "some help"
, Option "" ["no-color"] (NoArg ()) "some other help"
]
mkUsageInfo "" options `shouldBe` unlines [
""
, " --[no-]color some help"
]
| hspec/hspec | hspec-core/test/GetOpt/Declarative/UtilSpec.hs | mit | 987 | 0 | 20 | 351 | 221 | 116 | 105 | 22 | 1 |
module Rebase.GHC.IO.Encoding.Types
(
module GHC.IO.Encoding.Types
)
where
import GHC.IO.Encoding.Types
| nikita-volkov/rebase | library/Rebase/GHC/IO/Encoding/Types.hs | mit | 107 | 0 | 5 | 12 | 26 | 19 | 7 | 4 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot1click-project-placementtemplate.html
module Stratosphere.ResourceProperties.IoT1ClickProjectPlacementTemplate where
import Stratosphere.ResourceImports
-- | Full data type definition for IoT1ClickProjectPlacementTemplate. See
-- 'ioT1ClickProjectPlacementTemplate' for a more convenient constructor.
data IoT1ClickProjectPlacementTemplate =
IoT1ClickProjectPlacementTemplate
{ _ioT1ClickProjectPlacementTemplateDefaultAttributes :: Maybe Object
, _ioT1ClickProjectPlacementTemplateDeviceTemplates :: Maybe Object
} deriving (Show, Eq)
instance ToJSON IoT1ClickProjectPlacementTemplate where
toJSON IoT1ClickProjectPlacementTemplate{..} =
object $
catMaybes
[ fmap (("DefaultAttributes",) . toJSON) _ioT1ClickProjectPlacementTemplateDefaultAttributes
, fmap (("DeviceTemplates",) . toJSON) _ioT1ClickProjectPlacementTemplateDeviceTemplates
]
-- | Constructor for 'IoT1ClickProjectPlacementTemplate' containing required
-- fields as arguments.
ioT1ClickProjectPlacementTemplate
:: IoT1ClickProjectPlacementTemplate
ioT1ClickProjectPlacementTemplate =
IoT1ClickProjectPlacementTemplate
{ _ioT1ClickProjectPlacementTemplateDefaultAttributes = Nothing
, _ioT1ClickProjectPlacementTemplateDeviceTemplates = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot1click-project-placementtemplate.html#cfn-iot1click-project-placementtemplate-defaultattributes
itcpptDefaultAttributes :: Lens' IoT1ClickProjectPlacementTemplate (Maybe Object)
itcpptDefaultAttributes = lens _ioT1ClickProjectPlacementTemplateDefaultAttributes (\s a -> s { _ioT1ClickProjectPlacementTemplateDefaultAttributes = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot1click-project-placementtemplate.html#cfn-iot1click-project-placementtemplate-devicetemplates
itcpptDeviceTemplates :: Lens' IoT1ClickProjectPlacementTemplate (Maybe Object)
itcpptDeviceTemplates = lens _ioT1ClickProjectPlacementTemplateDeviceTemplates (\s a -> s { _ioT1ClickProjectPlacementTemplateDeviceTemplates = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/IoT1ClickProjectPlacementTemplate.hs | mit | 2,300 | 0 | 12 | 201 | 240 | 139 | 101 | 27 | 1 |
-- Copyright (c) 2014 Contributors as noted in the AUTHORS file
--
-- This file is part of frp-arduino.
--
-- frp-arduino is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- frp-arduino is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with frp-arduino. If not, see <http://www.gnu.org/licenses/>.
module Arduino.Uno
( module Arduino.Language
, module Arduino.Library
-- * Uno outputs and streams
, module Arduino.Uno
) where
import Arduino.Internal.DAG (Bit)
import Arduino.Internal.DSL
import Arduino.Language
import Arduino.Library
import CCodeGen
import Data.Bits (shiftR, (.&.))
import Prelude hiding (const)
-- For mappings, see http://arduino.cc/en/Hacking/PinMapping168
data GPIO = GPIO
{ name :: String
, directionRegister :: String
, portRegister :: String
, pinRegister :: String
, bitName :: String
}
pin10GPIO = GPIO "pin10" "DDRB" "PORTB" "PINB" "PB2"
pin11GPIO = GPIO "pin11" "DDRB" "PORTB" "PINB" "PB3"
pin12GPIO = GPIO "pin12" "DDRB" "PORTB" "PINB" "PB4"
pin13GPIO = GPIO "pin13" "DDRB" "PORTB" "PINB" "PB5"
pin13 :: Output Bit
pin13 = gpioOutput pin13GPIO
pin12 :: Output Bit
pin12 = gpioOutput pin12GPIO
pin11 :: Output Bit
pin11 = gpioOutput pin11GPIO
pin10 :: Output Bit
pin10 = gpioOutput pin10GPIO
pin12in :: Stream Bit
pin12in = gpioInput pin12GPIO
clock :: Stream Int
clock = every 10000
every :: Expression Int -> Stream Int
every limit = timerDelta ~> accumulate ~> keepOverflowing ~> count
where
accumulate = foldpS (\delta total -> if_ (greater total limit)
(delta + total - limit)
(delta + total))
0
keepOverflowing = filterS (\value -> greater value limit)
uart :: Output Char
uart =
let ubrr = floor ((16000000 / (16 * 9600)) - 1)
ubrrlValue = ubrr .&. 0xFF :: Int
ubrrhValue = shiftR ubrr 8 .&. 0xFF :: Int
in
createOutput
"uart"
(writeByte "UBRR0H" (const $ show ubrrhValue) $
writeByte "UBRR0L" (const $ show ubrrlValue) $
setBit "UCSR0C" "UCSZ01" $
setBit "UCSR0C" "UCSZ00" $
setBit "UCSR0B" "RXEN0" $
setBit "UCSR0B" "TXEN0" $
end)
(waitBitSet "UCSR0A" "UDRE0" $
writeByte "UDR0" inputValue $
end)
gpioOutput :: GPIO -> Output Bit
gpioOutput gpio =
createOutput
(name gpio)
(setBit (directionRegister gpio) (bitName gpio) $
end)
(switch
inputValue
(setBit (portRegister gpio) (bitName gpio) end)
(clearBit (portRegister gpio) (bitName gpio) end) $
end)
gpioInput :: GPIO -> Stream Bit
gpioInput gpio = createInput
(name gpio)
(clearBit (directionRegister gpio) (bitName gpio) $
setBit (portRegister gpio) (bitName gpio) $
end)
(readBit (pinRegister gpio) (bitName gpio))
timerDelta :: Stream Int
timerDelta = createInput
"timer"
(setBit "TCCR1B" "CS12" $
setBit "TCCR1B" "CS10" $
end)
(readWord "TCNT1" $
writeWord "TCNT1" (const "0") $
end)
| rickardlindberg/frp-arduino-old | src/Arduino/Uno.hs | gpl-3.0 | 3,628 | 0 | 18 | 987 | 869 | 459 | 410 | 84 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module Granada.Ast where
-- |Given
{--
nonExistantActions :: Expr.Program -> [Expr.Action]
nonExistantActions program = map nonExistantActions characters
where characters = charactersInProgram program
as = actionsInProgram program
nonExistantActions' :: Expr.Character -> [Expr.Action] -> (Expr.Character, [Expr.Action])
nonExistantActions' character acts = (character, S.toList $ as S.\\ S.fromList acts)
where as = S.fromList $ Expr.actions character
--}
{--
type Warning = String
type Error = String
unusedDefinition :: Warning
unusedDefinition = undefined
warnings :: [Warning]
warnings = [unusedDefinition]
errors :: [Error]
errors = [nonExistantActions]
data S = Err Error | Wrn Warning deriving (Show, Eq)
--}
| adolfosilva/granada | library/Granada/Ast.hs | gpl-3.0 | 797 | 0 | 3 | 120 | 10 | 8 | 2 | 2 | 0 |
{-# LANGUAGE ExistentialQuantification #-}
module HEP.Physics.TTBar.Reconstruction.Combined where
import HEP.Parser.LHCOAnalysis.PhysObj hiding (fourmomfrometaphipt, FourMomentum)
import Numeric.LinearAlgebra
import Numeric.GSL.Minimization
import HEP.Util.Functions
import HEP.Util.Combinatorics
import Data.List
import Data.Function
import HEP.Physics.TTBar.Print
import HEP.Physics.TTBar.Error
import HEP.Minimizer.GSLSimulatedAnnealing
import Control.Monad
data LepTopJetInfo = LepTopJetInfo {
leptop_lcharge :: ChargeSign,
leptop_b :: EtaPhiPTM,
leptop_l :: EtaPhiPT,
leptop_misspt :: PXPY
} deriving (Show,Eq)
data HadTopJetInfo = HadTopJetInfo {
hadtop_Wj1 :: EtaPhiPTM,
hadtop_Wj2 :: EtaPhiPTM,
hadtop_b :: EtaPhiPTM
} deriving (Show,Eq)
data TheOthers = TheOthers {
theothers_jets :: [EtaPhiPTM],
theothers_leptons :: [EtaPhiPT]
} deriving (Show,Eq)
data ChargeSign = Plus | Minus
deriving (Show,Eq)
chargesign :: forall a . (Num a, Ord a) => a -> ChargeSign
chargesign ch
| ch >= 0 = Plus
| ch < 0 = Minus
| otherwise = Plus
data SemiLepTopBothInfo = SemiLepTopBothInfo {
info_charge_l :: ChargeSign,
info_lep_b :: EtaPhiPTM,
info_lep_l :: EtaPhiPT,
info_lep_missPT :: PXPY,
info_had_Wj1 :: EtaPhiPTM,
info_had_Wj2 :: EtaPhiPTM,
info_had_b :: EtaPhiPTM,
info_otherjets :: [EtaPhiPTM] ,
info_otherleptons :: [EtaPhiPT]
} deriving (Show, Eq)
data SemiLepTopBothMom = SemiLepTopBothMom {
mom_lep_b :: FourMomentum,
mom_lep_l :: FourMomentum,
mom_lep_n :: FourMomentum,
mom_had_Wj1 :: FourMomentum,
mom_had_Wj2 :: FourMomentum,
mom_had_b :: FourMomentum
} deriving (Show,Eq)
data CorrelationMatrix = CorrMat {
corr_pp_b :: Matrix Double
, corr_pp_l :: Matrix Double
, corr_pp_hb :: Matrix Double
, corr_pp_j1 :: Matrix Double
, corr_pp_j2 :: Matrix Double
, corr_pm_b :: Matrix Double
, corr_pm_l :: Matrix Double
, corr_pm_hb :: Matrix Double
, corr_pm_j1 :: Matrix Double
, corr_pm_j2 :: Matrix Double
, corr_merr :: Matrix Double
, corr_mm :: Matrix Double
} deriving Show
data ChiSqrMinResultSet = ChiSqrMinResultSet {
csmrs_p0p3 :: (Double,Double)
, csmrs_chisqr :: Double
, csmrs_info :: SemiLepTopBothInfo
} deriving Show
mkPnumu :: PXPY -> (Double,Double) -> FourMomentum
mkPnumu (pxmiss, pymiss) (p0miss, p3miss) = (p0miss,pxmiss,pymiss,p3miss)
mkSemiLepTopBothMom :: SemiLepTopBothInfo -> (Double,Double) -> SemiLepTopBothMom
mkSemiLepTopBothMom tinfo (p0miss,p3miss) =
SemiLepTopBothMom {
mom_lep_b = momb,
mom_lep_l = moml,
mom_lep_n = momn,
mom_had_Wj1 = momWj1,
mom_had_Wj2 = momWj2,
mom_had_b = momhadb
}
where momb = fourmomfrometaphiptm_new $ info_lep_b tinfo
moml = fourmomfrometaphipt $ info_lep_l tinfo
momn = mkPnumu (info_lep_missPT tinfo) (p0miss,p3miss)
momWj1 = fourmomfrometaphiptm_new $ info_had_Wj1 tinfo
momWj2 = fourmomfrometaphiptm_new $ info_had_Wj2 tinfo
momhadb = fourmomfrometaphiptm_new $ info_had_b tinfo
y1 :: SemiLepTopBothMom -> Double
y1 einfo = sqr4 (mom_lep_n einfo)
y2 :: SemiLepTopBothMom -> Double
y2 einfo = sqr4 (mom_lep_l einfo `plus` mom_lep_n einfo ) - mw^(2 :: Int)
y3 :: SemiLepTopBothMom -> Double
y3 einfo = sqr4 (mom_lep_b einfo `plus` mom_lep_l einfo `plus` mom_lep_n einfo) - mt^(2 :: Int)
y4 :: SemiLepTopBothMom -> Double
y4 einfo = sqr4 (mom_had_Wj1 einfo `plus` mom_had_Wj2 einfo) - mw^(2 :: Int)
y5 :: SemiLepTopBothMom -> Double
y5 einfo = sqr4 (mom_had_b einfo `plus` mom_had_Wj1 einfo `plus` mom_had_Wj2 einfo) - mt^(2 :: Int)
yVec :: SemiLepTopBothMom -> Vector Double
yVec einfo = 5 |> [ y1 einfo, y2 einfo, y3 einfo, y4 einfo, y5 einfo]
mkCorrMat :: JetError -> LeptonError -> SemiLepTopBothInfo
-> CorrelationMatrix
mkCorrMat jeterr lerr sinfo = CorrMat {
corr_pp_b = pp_corr b (errorJet jeterr b)
, corr_pp_l = pp_corr l (errorLepton lerr l)
, corr_pp_hb = pp_corr hb (errorJet jeterr hb)
, corr_pp_j1 = pp_corr j1 (errorJet jeterr j1)
, corr_pp_j2 = pp_corr j2 (errorJet jeterr j2)
, corr_pm_b = pmissp_corr b (errorJet jeterr b)
, corr_pm_l = pmissp_corr l (errorLepton lerr l)
, corr_pm_hb = pmissp_corr hb (errorJet jeterr hb)
, corr_pm_j1 = pmissp_corr j1 (errorJet jeterr j1)
, corr_pm_j2 = pmissp_corr j2 (errorJet jeterr j2)
, corr_merr = masserr
, corr_mm = pmisspmiss_corr (jswitherr ++ lswitherr)
}
where b = dropm $ info_lep_b sinfo
l = info_lep_l sinfo
hb = dropm $ info_had_b sinfo
j1 = dropm $ info_had_Wj1 sinfo
j2 = dropm $ info_had_Wj2 sinfo
js = b : hb : j1 : j2 : map dropm (info_otherjets sinfo)
ls = l : info_otherleptons sinfo
jswitherr = map (\x -> (x,errorJet jeterr x)) js
lswitherr = map (\x -> (x,errorLepton lerr x)) ls
uMatrix :: CorrelationMatrix -> Matrix Double
uMatrix (CorrMat pp_b pp_l pp_hb pp_j1 pp_j2
pm_b pm_l pm_hb pm_j1 pm_j2
merr mm )
= fromBlocks [ [ pp_b , 0 , 0 , 0 , 0 , pm_b , 0 ]
, [ 0 , pp_l , 0 , 0 , 0 , pm_l , 0 ]
, [ 0 , 0 , pp_hb , 0 , 0 , pm_hb, 0 ]
, [ 0 , 0 , 0 , pp_j1 , 0 , pm_j1, 0 ]
, [ 0 , 0 , 0 , 0 , pp_j2 , pm_j2, 0 ]
, [ t_pm_b, t_pm_l, t_pm_hb, t_pm_j1, t_pm_j2, mm , 0 ]
, [ 0 , 0 , 0 , 0 , 0 , 0 , merr ]
]
where t_pm_b = trans pm_b
t_pm_l = trans pm_l
t_pm_hb = trans pm_hb
t_pm_j1 = trans pm_j1
t_pm_j2 = trans pm_j2
dydp :: SemiLepTopBothMom -> Matrix Double
dydp einfo =
(5><24) [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , etx1, ety1, 0 , 0
, 0 , 0 , 0 , 0 , l20, l21, l22, l23, 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , etx2, ety2, mw1, 0
, b30, b31, b32, b33, l30, l31, l32, l33, 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , etx3, ety3, 0 , mt1
, 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , j140, j141, j142, j143, j240, j241, j242, j243, 0 , 0 , mw1, 0
, 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , hb50, hb51, hb52, hb53, j150, j151, j152, j153, j250, j251, j252, j253, 0 , 0 , 0 , mt1
]
where {
(pb0,pb1,pb2,pb3) = mom_lep_b einfo ;
(pl0,pl1,pl2,pl3) = mom_lep_l einfo ;
(pn0,pn1,pn2,pn3) = mom_lep_n einfo ;
(phb0,phb1,phb2,phb3) = mom_had_b einfo ;
(pj10,pj11,pj12,pj13) = mom_had_Wj1 einfo ;
(pj20,pj21,pj22,pj23) = mom_had_Wj2 einfo ;
etx1 = -2.0 * pn1 ; ety1 = -2.0 * pn2 ;
etx2 = -2.0 * (pl1 + pn1) ; ety2 = -2.0 * (pl2 + pn2) ;
etx3 = -2.0 * (pb1 + pl1 + pn1) ; ety3 = -2.0 * (pb2 + pl2 + pn2) ;
l20 = 2.0 * (pl0 + pn0) ; l21 = -2.0 * (pl1 + pn1) ;
l22 = -2.0 * (pl2 + pn2) ; l23 = -2.0 * (pl3 + pn3) ;
b30 = 2.0 * (pb0 + pl0 + pn0) ; b31 = -2.0 * (pb1 + pl1 + pn1) ;
b32 = -2.0 * (pb2 + pl2 + pn2) ; b33 = -2.0 * (pb3 + pl3 + pn3) ;
l30 = 2.0 * (pb0 + pl0 + pn0) ; l31 = -2.0 * (pb1 + pl1 + pn1) ;
l32 = -2.0 * (pb2 + pl2 + pn2) ; l33 = -2.0 * (pb3 + pl3 + pn3) ;
j140 = 2.0 * (pj10 + pj20) ; j141 = -2.0 * (pj11 + pj21) ;
j142 = -2.0 * (pj12 + pj22) ; j143 = -2.0 * (pj13 + pj23) ;
j240 = 2.0 * (pj10 + pj20) ; j241 = -2.0 * (pj11 + pj21) ;
j242 = -2.0 * (pj12 + pj22) ; j243 = -2.0 * (pj13 + pj23) ;
hb50 = 2.0 * (phb0 + pj10 + pj20) ; hb51 = -2.0 * (phb1 + pj11 + pj21) ;
hb52 = -2.0 * (phb2 + pj12 + pj22) ; hb53 = -2.0 * (phb3 + pj13 + pj23) ;
j150 = 2.0 * (phb0 + pj10 + pj20) ; j151 = -2.0 * (phb1 + pj11 + pj21) ;
j152 = -2.0 * (phb2 + pj12 + pj22) ; j153 = -2.0 * (phb3 + pj13 + pj23) ;
j250 = 2.0 * (phb0 + pj10 + pj20) ; j251 = -2.0 * (phb1 + pj11 + pj21) ;
j252 = -2.0 * (phb2 + pj12 + pj22) ; j253 = -2.0 * (phb3 + pj13 + pj23) ;
mw1 = -2.0 * mw ; mt1 = -2.0 * mt ;
}
vMatrix :: Matrix Double -> Matrix Double -> Matrix Double
vMatrix u dydpmat = dydpmat <> u <> trans dydpmat
chiSqr :: Vector Double -> Matrix Double -> Double
chiSqr y v = y <.> (vinv <> y)
where vinv = inv v
chiSqrMinimizable :: SemiLepTopBothInfo -> Matrix Double -> (Double,Double) -> Double
chiSqrMinimizable sinfo umat (p0,p3) =
let einfo = mkSemiLepTopBothMom sinfo (p0,p3)
vmat = vMatrix umat (dydp einfo)
yvec = yVec einfo
in chiSqr yvec vmat
minimizeChiSqrSimple :: JetError
-> LeptonError
-> SemiLepTopBothInfo
-> MinimizeMethod -- ^ MinimizeMethod (defined in hmatrix )
-> (Double,Double) -- ^ initial guess
-> ChiSqrMinResultSet
minimizeChiSqrSimple jeterr lerr sinfo minmethod (ip0, ip3) =
let umat = uMatrix . (mkCorrMat jeterr lerr) $ sinfo
tempChiSqr :: [Double] -> Double
tempChiSqr [p0,p3] = chiSqrMinimizable sinfo umat (p0,p3)
tempChiSqr _ = error "no double list : tempChiSqr"
([x0,x3],_) = minimize minmethod 1E-3 30 [100,100] tempChiSqr [ip0,ip3]
y = tempChiSqr [x0,x3]
in ChiSqrMinResultSet {
csmrs_p0p3 = (x0,x3)
, csmrs_chisqr = y
, csmrs_info = sinfo
}
minimizeChiSqrSimAnn :: JetError -> LeptonError -> SemiLepTopBothInfo
-> (Double,Double)
-> IO ChiSqrMinResultSet
minimizeChiSqrSimAnn jeterr lerr sinfo (ip0,ip3) =
do let umat = uMatrix . (mkCorrMat jeterr lerr) $ sinfo
e1 = chiSqrMinimizable sinfo umat
m1 (x1,y1) (x2,y2) = (x1-x2)^(2 :: Int) + (y1-y2)^(2 :: Int)
param= SAParam {
saparam'n_tries = 200,
saparam'iters_fixed_t = 100,
saparam'step_size = 300.0,
saparam'k = 1.0,
saparam't_initial = 0.1,
saparam'mu_t = 2.0,
saparam't_min = 1.0e-3
}
func = SAFunc2D {
safunc2d'energy = e1,
safunc2d'measure = m1
}
r <- simanSolve2d (ip0, ip3) func param
return $ ChiSqrMinResultSet {
csmrs_p0p3 = r
, csmrs_chisqr = e1 r
, csmrs_info = sinfo
}
stagedMinimizer4ChiSqrUsingSimpleAndSA :: SemiLepTopBothInfo -> IO ChiSqrMinResultSet
stagedMinimizer4ChiSqrUsingSimpleAndSA sinfo = do
let (ip0,ip3) = (0,0) -- I don't want to deal with initial guess now. I will come back later
result1 <- minimizeChiSqrSimAnn jetError lepError sinfo (ip0,ip3)
let newp0p3 = csmrs_p0p3 result1
return $ minimizeChiSqrSimple jetError lepError sinfo NMSimplex2 newp0p3
action4AllComb :: (PhyEventClassified -> IO ()) -- ^ starter
-> (SemiLepTopBothInfo -> IO a) -- ^ main
-> PhyEventClassified -> IO [a]
action4AllComb starter iofunc p = do
starter p
case cnstrctCombinatorics p of
Nothing -> return []
Just r -> do let comb = (map mkSemiLepTopBothInfo) r
hline
putStrLn $ "chisqr minimum for all comb by Simulated Annealing"
mapM iofunc comb
showEventNum :: PhyEventClassified -> IO ()
showEventNum p = do
hline
putStrLn $ "event : " ++ (show . eventid $ p )
hline
minChiSqr4AllComb :: ( SemiLepTopBothInfo -> IO ChiSqrMinResultSet )
-> PhyEventClassified -> IO [ChiSqrMinResultSet]
minChiSqr4AllComb minimizer p = action4AllComb showEventNum minimizer p
minimizerComparison :: SemiLepTopBothInfo -> IO (ChiSqrMinResultSet,ChiSqrMinResultSet,ChiSqrMinResultSet)
minimizerComparison sinfo = do
putStrLn "Minimizer Comparison"
let simpleMinimizerResult = minimizeChiSqrSimple jetError lepError sinfo NMSimplex2 (0,0)
simannMinimizerResult <- minimizeChiSqrSimAnn jetError lepError sinfo (0,0)
combinedMinimizerResult <- stagedMinimizer4ChiSqrUsingSimpleAndSA sinfo
return (simpleMinimizerResult, simannMinimizerResult, combinedMinimizerResult )
showComparison :: (ChiSqrMinResultSet, ChiSqrMinResultSet, ChiSqrMinResultSet) -> IO ()
showComparison (r1,r2,r3) = do
putStrLn $ "simple : " ++ (show (csmrs_chisqr r1))
putStrLn $ "simann : " ++ (show (csmrs_chisqr r2))
putStrLn $ "combin : " ++ (show (csmrs_chisqr r3))
findMinFrmChiSqrResultSetLst :: [ChiSqrMinResultSet] -> ChiSqrMinResultSet
findMinFrmChiSqrResultSetLst lst
= head $ sortBy (compare `on` csmrs_chisqr) lst
testeventToInfo :: PhyEventClassified -> SemiLepTopBothInfo
testeventToInfo p = let blst = bjetlst p
leptonic_bs = filter (\x->fst x == 5) blst
hadronic_bs = filter (\x->fst x == 1) blst
jlst = jetlst p
wjets = filter (\x->fst x == 2 || fst x == 4) jlst
ojets = filter (\x->fst x == 3) jlst
llst = muonlst p
leptonic_ls = filter (\x->fst x == 6) llst
in SemiLepTopBothInfo {
info_lep_b = etaphiptm . snd $ head leptonic_bs,
info_lep_l = etaphipt . snd $ head leptonic_ls,
info_charge_l = undefined,
info_lep_missPT = pxpyFromPhiPT . phiptmet $ met p,
info_had_Wj1 = etaphiptm . snd $ wjets !! 0,
info_had_Wj2 = etaphiptm . snd $ wjets !! 1,
info_had_b = etaphiptm . snd $ head hadronic_bs,
info_otherjets = map (etaphiptm . snd) ojets,
info_otherleptons = []
}
mkSemiLepTopBothInfo :: (LepTopJetInfo, HadTopJetInfo, TheOthers)
-> SemiLepTopBothInfo
mkSemiLepTopBothInfo (linfo,hinfo,oinfo) =
SemiLepTopBothInfo {
info_charge_l = leptop_lcharge linfo,
info_lep_b = leptop_b linfo,
info_lep_l = leptop_l linfo,
info_lep_missPT = leptop_misspt linfo,
info_had_Wj1 = hadtop_Wj1 hinfo,
info_had_Wj2 = hadtop_Wj2 hinfo,
info_had_b = hadtop_b hinfo,
info_otherjets = theothers_jets oinfo,
info_otherleptons = theothers_leptons oinfo
}
cnstrctCombinatorics :: PhyEventClassified
-> Maybe [(LepTopJetInfo, HadTopJetInfo, TheOthers)]
cnstrctCombinatorics p = do
guard (nleptons == 1)
guard ((nbjets == 1 && njets >= 3) || (nbjets == 2 && njets >= 2) )
case nbjets of
1 -> return singleBjetCase
2 -> return doubleBjetCase
_ -> error "more than 2 jet or 0 jet? in cnstrctCombinatorics"
where leptons = map (\x->((etaphipt.snd) x,(chargesign.charge.snd) x)) (leptonlst p)
bjets = map (etaphiptm.snd) (bjetlst p)
jets = map (etaphiptm.snd) (jetlst p)
misspt = (pxpyFromPhiPT . phiptmet . met) p
nleptons = length leptons
nbjets = length bjets
njets = length jets
-- n_bjets_or_jets = nbjets + njets
mkTriple (lcharge,b,l,wj1,wj2,hb,others) = (linfo,hinfo,oinfo)
where linfo = LepTopJetInfo { leptop_lcharge = lcharge,
leptop_b = b, leptop_l = l, leptop_misspt = misspt }
hinfo = HadTopJetInfo { hadtop_Wj1 = wj1, hadtop_Wj2 = wj2, hadtop_b = hb }
oinfo = TheOthers { theothers_jets = others, theothers_leptons = [] }
singleBjetCase =
let [b] = bjets
[l] = map fst leptons
[lcharge] = map snd leptons
wjets_bjet_in_tjets_and_others =
[(lcharge,b,l,wj1,wj2,hb,others) |
(tjet,others) <- combSep 3 jets,
([wj1,wj2],[hb]) <- combSep 2 tjet ]
in map mkTriple wjets_bjet_in_tjets_and_others
doubleBjetCase =
let [b1,b2] = bjets
[l] = map fst leptons
[lcharge] = map snd leptons
bjets_perm = [(b1,b2),(b2,b1)]
wjets_in_tjets_and_others =
[(lcharge,b,l,wj1,wj2,hb,others) |
([wj1,wj2],others) <- combSep 2 jets,
(b,hb) <- bjets_perm ]
in map mkTriple wjets_in_tjets_and_others
| wavewave/ttbar | lib/HEP/Physics/TTBar/Reconstruction/Combined.hs | gpl-3.0 | 17,125 | 0 | 17 | 5,722 | 5,417 | 3,041 | 2,376 | 339 | 3 |
module HEP.Automation.MadGraph.Dataset.Set20110717set7ATLAS where
import HEP.Storage.WebDAV.Type
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Model.C8V
import HEP.Automation.MadGraph.Dataset.Processes
import HEP.Automation.JobQueue.JobType
processSetup :: ProcessSetup C8V
processSetup = PS {
model = C8V
, process = preDefProcess TTBar0or1J
, processBrief = "TTBar0or1J"
, workname = "717_C8V_TTBar0or1J_LHC"
}
paramSet :: [ModelParam C8V]
paramSet = [ C8VParam { mnp = m, gnpR = g, gnpL = 0 }
| (m,g) <- [ (400,0.75), (800,1.4) ] ]
sets :: [Int]
sets = [1..50]
ucut :: UserCut
ucut = UserCut {
uc_metcut = 15.0
, uc_etacutlep = 2.7
, uc_etcutlep = 18.0
, uc_etacutjet = 2.7
, uc_etcutjet = 15.0
}
eventsets :: [EventSet]
eventsets =
[ EventSet processSetup
(RS { param = p
, numevent = 100000
, machine = LHC7 ATLAS
, rgrun = Fixed
, rgscale = 200.0
, match = MLM
, cut = DefCut
, pythia = RunPYTHIA
, usercut = UserCutDef ucut
, pgs = RunPGS
, jetalgo = AntiKTJet 0.4
, uploadhep = NoUploadHEP
, setnum = num
})
| p <- paramSet , num <- sets ]
webdavdir :: WebDAVRemoteDir
webdavdir = WebDAVRemoteDir "paper3/ttbar_LHC_c8v_big"
| wavewave/madgraph-auto-dataset | src/HEP/Automation/MadGraph/Dataset/Set20110717set7ATLAS.hs | gpl-3.0 | 1,615 | 0 | 10 | 527 | 382 | 241 | 141 | 46 | 1 |
module Hammertime.CLI (
Action(..)
, cliParserInfo
, cliParserPrefs
) where
import Data.Char (toLower)
import Data.List (find, intercalate)
import Options.Applicative
import Options.Applicative.Types
import qualified Hammertime.Types as Types
data Action = Start { project :: String
, name :: String
, tags :: [String]
}
| Stop
| Report { span_ :: Types.TimeSpan
, project_ :: Maybe String
, name_ :: Maybe String
, tag_ :: Maybe String
, type_ :: Types.ReportType
}
| Current
deriving (Eq, Show)
parseKeyword :: (Bounded a, Enum a, Show a) => String -> (Either ParseError a)
parseKeyword string = maybe (Left helpText) Right $ matching
where
matching = find (match string . show) values
match s s' = map toLower s == map toLower s'
values = [minBound..maxBound]
helpText = ErrorMsg $ "Possible values: " ++ (intercalate "|" . map show $ values)
argumentBuilder :: (Bounded a, Enum a, Show a) => String -> Maybe a
argumentBuilder string = case parseKeyword string of
Left _ -> Nothing
Right a -> Just a
cliParserPrefs :: ParserPrefs
cliParserPrefs = prefs showHelpOnError
cliParserInfo :: ParserInfo Action
cliParserInfo = info
( helper
<*> cliParser)
( fullDesc
<> header "Hammertime -- Lightweight time tracker"
)
cliParser :: Parser Action
cliParser = subparser
( command "start"
(info startParser
(progDesc "Start a new activity" <> fullDesc))
<> command "stop"
(info (pure Stop)
(progDesc "Stop current activity" <> fullDesc))
<> command "report"
(info (helper <*> reportParser)
(progDesc "Generate report for a given time span (default: day)" <> fullDesc))
<> command "current"
(info (pure Current)
(progDesc "Display current activity" <> fullDesc))
)
startParser :: Parser Action
startParser =
Start <$>
argument str ( metavar "PROJECT" ) <*>
argument str ( metavar "ACTIVITY" ) <*>
arguments str (metavar "TAGS")
reportParser :: Parser Action
reportParser =
Report <$>
spanParser <*>
projectFilterParser <*>
activityFilterParser <*>
tagFilterParser <*>
reportTypeParser
spanParser :: Parser Types.TimeSpan
spanParser =
argument argumentBuilder
( metavar "month|week|day"
<> completeWith ["month","week","day"]
<> value Types.Day)
mStr :: String -> Either ParseError (Maybe String)
mStr = fmap Just . str
projectFilterParser :: Parser (Maybe String)
projectFilterParser = option
( long "project"
<> short 'p'
<> reader mStr
<> value Nothing
<> metavar "PROJECT"
<> help "Filter by project")
activityFilterParser :: Parser (Maybe String)
activityFilterParser = option
( long "activity"
<> short 'a'
<> reader mStr
<> value Nothing
<> metavar "ACTIVITY"
<> help "Filter by activity")
tagFilterParser :: Parser (Maybe String)
tagFilterParser = option
( long "tag"
<> reader mStr
<> value Nothing
<> metavar "TAG"
<> help "Filter by tag")
reportTypeParser :: Parser Types.ReportType
reportTypeParser = option
( long "type"
<> short 't'
<> reader parseKeyword
<> value Types.Simple
<> completeWith ["simple", "totaltime"]
<> metavar "SIMPLE|TOTALTIME"
<> help "Report Type (default: simple)")
| divarvel/hammertime | lib/Hammertime/CLI.hs | gpl-3.0 | 3,600 | 0 | 15 | 1,045 | 994 | 506 | 488 | 106 | 2 |
module Network where
import Control.Applicative (pure, (<$>), (<*>))
import Data.Binary
import Data.Binary.Get
import Data.ByteString.Lazy (ByteString, empty)
import Ethernet (EtherFrame(..), EtherType(..), fromEtherType)
import Datalink
import IP4
data Network = IP4 Packet
| UnsupportedNetwork !Integer ByteString
deriving (Show)
network :: Datalink -> Get Network
network (Ethernet frame) =
case _ethertype frame of
Ethernet.IP4 -> ip4
ftype -> UnsupportedNetwork <$> (pure . fromIntegral . fromEtherType) ftype <*> getRemainingLazyByteString
network UnsupportedDatalink{} = return $! UnsupportedNetwork 0 empty
ip4 :: Get Network
ip4 = Network.IP4 <$> get
| bflyblue/parse-quote | Network.hs | unlicense | 703 | 0 | 13 | 125 | 210 | 119 | 91 | 21 | 2 |
module GuiHCPN(simMain) where
import Control.Concurrent
import Data.Maybe (fromMaybe)
import Graphics.UI.WX
import Graphics.UI.WXCore (windowRaise)
import NetEdit hiding (version)
import qualified SimpleHCPN as S
version = "NetSim v0.1"
data SimState t n m w ti = SimState{tick :: ti
,outM :: m -> IO ()
,outT :: (String,t) -> IO ()
,outS :: String -> IO ()
,flush :: IO ()
,simOut:: w
,net :: n
,marking:: m
,initial:: m
}
-- simulation setup --{{{
simMain name showMarking' netNoInfo mark = start $ simFrame init
where
init vContext = do
importNet (Just name) vContext
Context{vNet=vNet,f=f,p=p} <- varGet vContext
net' <- varGet vNet
tmap <- mapM getName $ trans net'
pmap <- mapM getName $ places net'
let net = netNoInfo{S.trans=
map (\t->t{S.info=fromMaybe (error "unknown transition")
$ lookup (S.name t) tmap})
(S.trans netNoInfo)}
showMarking = showMarking' pmap
-- a window for textual simulation output
sft <- frameTool [text := "Simulation output",visible:=True,closeable:=False] f
s <- textCtrl sft [enabled:=True]
set sft [layout :=dynamic $ fill $ widget s
,clientSize:=sz 600 400]
-- a timer to drive the simulation
tick <- timer p [enabled := False
,interval := 500
]
simState <- newMVar SimState{tick = tick
,outM =outMarking showMarking s True
,outT =outTrans vContext s True
,outS =appendText s . (++"\n")
,flush =repaint p
,simOut=s
,net =net
,marking=mark
,initial=mark
}
set tick [ on command := runGEvent simState ]
set p [on keyboard :~ sim vContext tick simState
]
return ()
-- simulation control and visualisation
sim vContext tick simState previous k
| keyKey k == KeyChar 'i' = do
modifyMVar_ simState $ \s@SimState{simOut=simOut
,outM=outM
,flush=flush
,initial=initial}->do
set simOut [text := "", visible := True]
outM initial
flush
return s{marking=initial}
sim vContext tick simState previous k
| keyKey k == KeyChar 's' = do
Context{p=p} <- varGet vContext
set tick [enabled :~ not]
return ()
sim vContext tick simState previous k
| keyKey k == KeyChar 'S' = do
Context{p=p} <- varGet vContext
runGEvent simState
return ()
sim vContext tick simState previous k
| keyKey k == KeyChar '+' = do
Context{p=p} <- varGet vContext
set tick [interval :~ \i->min (i+100) 1000]
sim vContext tick simState previous k
| keyKey k == KeyChar '-' = do
Context{p=p} <- varGet vContext
set tick [interval :~ \i->max (i-100) 1]
sim vContext tick simState previous k
= previous k
outMarking showMarking s False m = do
showMarking setPlaceMark m
outMarking showMarking s True m = do
showMarking setPlaceMark m
appendText s $ show m++"\n"
outTrans vContext s False (name,t) = do
appendText s $ name++"\n"
outTrans vContext s True (name,t) = do
varUpdate vContext $ \c->c{selected=
(\(ts,ps,as)->([t],[],[])) $ selected c }
appendText s $ name++"\n"
-- }}}
-- net simulation window -- {{{
simFrame init = do
f <- frame [text := version, visible := False]
p <- panel f []
hft <- frameTool [text := "Help",visible:=False,closeable:=False] f
h <- textCtrl hft [text:=helpText,enabled:=False]
set hft [layout :=dynamic $ fill $ widget h
,clientSize:=sz 250 80]
dft <- frameTool [text := "Declarations",visible:=False] f
t <- textCtrl dft [wrap := WrapLine]
-- lists of net elements
vNet <- varCreate $
Net{trans=[],places=[],arcs=[],decls=""}
-- editing context
vContext <- varCreate $
Context{wStatus=version
,vNet=vNet,current=Nothing
,mPos=pointZero,mDownPos=pointZero,mDragPos=pointZero
,selected=([],[],[])
,history=[]
,p=p
,f=f
,t=t
,h=h
,currentFile="unnamed.hcpn"
}
set f [layout := fill $ widget p
,clientSize := sz 600 400
,visible := True
]
windowRaise hft
windowRaise f
set p [on paint := paintNet vContext
,on keyboard := keyHandler vContext
-- ,on click := selectionHandler vContext p
,on motion := recordMousePos vContext
,on drag := dragHandler vContext
,on mouse :~ addHandler1 (selectionHandler vContext)
]
init vContext
return ()
-- }}}
-- simulation "loop"-- {{{
-- inverted simulation loop, for event handler
runGEvent simState = do
modifyMVar_ simState $ \old->do
new <- stepG old
maybe (return old) return new
-- single simulation step, parameterised by visualisation
stepG s@SimState{tick=tick,outM=outM,outT=outT,outS=outS,flush=flush
,net=net,marking=marking} = do
if null enabledTs
then do outS "no more enabled transitions!"
set tick [enabled := False]
return Nothing
else do trans <- S.choose enabledTs
outT (fst trans)
let newMarking = snd trans
outM newMarking
flush
return $ Just s{marking=newMarking}
where
enabledTs = S.enabled net marking
-- }}}
| haroldcarr/learn-haskell-coq-ml-etc | haskell/playpen/hcpn/src/GuiHCPN.hs | unlicense | 6,174 | 0 | 23 | 2,361 | 1,995 | 1,016 | 979 | 139 | 2 |
--
import Data.Char
data Operator = Plus | Minus | Times | Div deriving (Show,Eq)
opToChar :: Operator -> Char
-- opToChar = undefined
opToChar Plus = '+'
opToChar Minus = '-'
opToChar Times = '*'
opToChar Div = '/'
opToStr :: Operator -> String
opToStr Plus = "+"
opToStr Minus = "-"
opToStr Times = "*"
opToStr Div = "/"
data Token = TokOp Operator
| TokIdent String
| TokNum Int
| TokSpace
deriving (Show,Eq)
showContent :: Token -> String
showContent (TokOp op) = opToStr op
showContent (TokIdent str) = str
showContent (TokNum i) = show i
token :: Token
token = TokIdent "x"
operator :: Char -> Operator
operator c | c == '+' = Plus
| c == '-' = Minus
| c == '*' = Times
| c == '/' = Div
tokenizeChar :: Char -> Token
tokenizeChar c
| elem c "+/-*" = TokOp (operator c)
| isDigit c = TokNum (digitToInt c)
| isAlpha c = TokIdent [c]
| isSpace c = TokSpace
| otherwise = error $ "Cannot tokenizeChar " ++ [c]
tokenize :: String -> [Token]
tokenize = map tokenizeChar
-- isDigit :: Char -> Bool
-- isDigit c = elem c ['0'..'9']
-- isAlpha :: Char -> Bool
-- isAlpha c = elem c $ ['a'..'z'] ++ ['A'..'Z']
-- isSpace :: Char -> Bool
-- isSpace c = elem c $ " "
-- digitToInt :: Char -> Int
-- digitToInt c | isDigit c = fromEnum c - 48
digitToInts :: String -> [Int]
digitToInts = map digitToInt
deSpace :: [Token] -> [Token]
deSpace = filter (\t -> t /= TokSpace)
alnums :: String -> (String, String)
alnums str = als "" str
where
als acc [] = (acc, [])
als acc (c:cs) | isAlphaNum c = als (c:acc) cs
| otherwise = (reverse(acc), c:cs)
-- Scales with O(N^2), N = len(str)
type Accum = (Bool, String, String)
alnums' :: String -> (String,String)
alnums' str = let (_, als, rest) = foldl f (True, [], []) str
in (als, rest)
where
f(True, als, rest) c | isAlphaNum c = (True, als ++ [c], rest)
| otherwise = (False, als, [c])
f(False, als, rest) c = (False, als, rest ++ [c])
digits :: String -> (String, String)
digits str = digs [] str
where
digs acc [] = (acc, [])
digs acc (c:cs) | isDigit c = digs (c:acc) cs
| otherwise = (reverse(acc), c:cs)
rev :: String -> String
rev = foldl (\acc a -> a:acc) []
cpy :: String -> String
cpy = foldr (\a acc -> a:acc) []
span' :: (a->Bool) -> [a] -> ([a],[a])
span' pred str = spanAcc [] str
where
spanAcc acc [] = (acc, [])
spanAcc acc (c:cs) | pred c = spanAcc (c:acc) cs
| otherwise = (reverse(acc), c:cs)
span'' :: (a->Bool) -> [a] -> ([a],[a])
span'' pred str =
let -- define helper
spanAcc acc [] = (acc, [])
spanAcc acc (c:cs) | pred c = spanAcc (c:acc) cs
| otherwise = (reverse(acc), c:cs)
in
spanAcc [] str
main = do
putStrLn $ showContent token
print token
print $ operator '*'
print $ tokenize "**/+"
print $ deSpace $ tokenize "1 + 4 / x"
print $ digitToInts "1234"
print $ alnums "R2D2+C3Po"
print $ alnums "a14"
print $ alnums' "R2D2+C3Po"
print $ alnums' "a14"
print $ rev "1234"
print $ cpy "1234"
print $ digits "1234abc 5678"
print $ span' (\c -> isAlphaNum c) "R2D2+C3Po"
print $ span' isAlphaNum "R2D2+C3Po"
print $ span'' isDigit "1234abc 5678"
| egaburov/funstuff | Haskell/BartoszBofH/7_TokenizerHOF/tokenize.hs | apache-2.0 | 3,402 | 0 | 12 | 979 | 1,424 | 732 | 692 | 91 | 2 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Utils
-- Copyright : (c) The University of Glasgow 2001-2002,
-- Simon Marlow 2003-2006,
-- David Waern 2006-2009
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Haddock.Utils (
-- * Misc utilities
restrictTo, emptyHsQTvs,
toDescription, toInstalledDescription,
-- * Filename utilities
moduleHtmlFile, moduleHtmlFile',
contentsHtmlFile, indexHtmlFile,
frameIndexHtmlFile,
moduleIndexFrameName, mainFrameName, synopsisFrameName,
subIndexHtmlFile,
jsFile, framesFile,
-- * Anchor and URL utilities
moduleNameUrl, moduleNameUrl', moduleUrl,
nameAnchorId,
makeAnchorId,
-- * Miscellaneous utilities
getProgramName, bye, die, dieMsg, noDieMsg, mapSnd, mapMaybeM, escapeStr,
-- * HTML cross reference mapping
html_xrefs_ref, html_xrefs_ref',
-- * Doc markup
markup,
idMarkup,
mkMeta,
-- * List utilities
replace,
spanWith,
-- * MTL stuff
MonadIO(..),
-- * Logging
parseVerbosity,
out,
-- * System tools
getProcessID
) where
import Documentation.Haddock.Doc (emptyMetaDoc)
import Haddock.Types
import Haddock.GhcUtils
import GHC
import Name
import Control.Monad ( liftM )
import Data.Char ( isAlpha, isAlphaNum, isAscii, ord, chr )
import Numeric ( showIntAtBase )
import Data.Map ( Map )
import qualified Data.Map as Map hiding ( Map )
import Data.IORef ( IORef, newIORef, readIORef )
import Data.List ( isSuffixOf )
import Data.Maybe ( mapMaybe )
import System.Environment ( getProgName )
import System.Exit
import System.IO ( hPutStr, stderr )
import System.IO.Unsafe ( unsafePerformIO )
import qualified System.FilePath.Posix as HtmlPath
import Distribution.Verbosity
import Distribution.ReadE
#ifndef mingw32_HOST_OS
import qualified System.Posix.Internals
#endif
import MonadUtils ( MonadIO(..) )
--------------------------------------------------------------------------------
-- * Logging
--------------------------------------------------------------------------------
parseVerbosity :: String -> Either String Verbosity
parseVerbosity = runReadE flagToVerbosity
-- | Print a message to stdout, if it is not too verbose
out :: MonadIO m
=> Verbosity -- ^ program verbosity
-> Verbosity -- ^ message verbosity
-> String -> m ()
out progVerbosity msgVerbosity msg
| msgVerbosity <= progVerbosity = liftIO $ putStrLn msg
| otherwise = return ()
--------------------------------------------------------------------------------
-- * Some Utilities
--------------------------------------------------------------------------------
-- | Extract a module's short description.
toDescription :: Interface -> Maybe (MDoc Name)
toDescription = fmap mkMeta . hmi_description . ifaceInfo
-- | Extract a module's short description.
toInstalledDescription :: InstalledInterface -> Maybe (MDoc Name)
toInstalledDescription = fmap mkMeta . hmi_description . instInfo
mkMeta :: Doc a -> MDoc a
mkMeta x = emptyMetaDoc { _doc = x }
--------------------------------------------------------------------------------
-- * Making abstract declarations
--------------------------------------------------------------------------------
restrictTo :: [Name] -> LHsDecl Name -> LHsDecl Name
restrictTo names (L loc decl) = L loc $ case decl of
TyClD d | isDataDecl d ->
TyClD (d { tcdDataDefn = restrictDataDefn names (tcdDataDefn d) })
TyClD d | isClassDecl d ->
TyClD (d { tcdSigs = restrictDecls names (tcdSigs d),
tcdATs = restrictATs names (tcdATs d) })
_ -> decl
restrictDataDefn :: [Name] -> HsDataDefn Name -> HsDataDefn Name
restrictDataDefn names defn@(HsDataDefn { dd_ND = new_or_data, dd_cons = cons })
| DataType <- new_or_data
= defn { dd_cons = restrictCons names cons }
| otherwise -- Newtype
= case restrictCons names cons of
[] -> defn { dd_ND = DataType, dd_cons = [] }
[con] -> defn { dd_cons = [con] }
_ -> error "Should not happen"
restrictCons :: [Name] -> [LConDecl Name] -> [LConDecl Name]
restrictCons names decls = [ L p d | L p (Just d) <- map (fmap keep) decls ]
where
keep d | any (\n -> n `elem` names) (map unLoc $ con_names d) =
case con_details d of
PrefixCon _ -> Just d
RecCon fields
| all field_avail fields -> Just d
| otherwise -> Just (d { con_details = PrefixCon (field_types (map unL fields)) })
-- if we have *all* the field names available, then
-- keep the record declaration. Otherwise degrade to
-- a constructor declaration. This isn't quite right, but
-- it's the best we can do.
InfixCon _ _ -> Just d
where
field_avail (L _ (ConDeclField ns _ _)) = all (\n -> unLoc n `elem` names) ns
field_types flds = [ t | ConDeclField _ t _ <- flds ]
keep _ = Nothing
restrictDecls :: [Name] -> [LSig Name] -> [LSig Name]
restrictDecls names = mapMaybe (filterLSigNames (`elem` names))
restrictATs :: [Name] -> [LFamilyDecl Name] -> [LFamilyDecl Name]
restrictATs names ats = [ at | at <- ats , unL (fdLName (unL at)) `elem` names ]
emptyHsQTvs :: LHsTyVarBndrs Name
-- This function is here, rather than in HsTypes, because it *renamed*, but
-- does not necessarily have all the rigt kind variables. It is used
-- in Haddock just for printing, so it doesn't matter
emptyHsQTvs = HsQTvs { hsq_kvs = error "haddock:emptyHsQTvs", hsq_tvs = [] }
--------------------------------------------------------------------------------
-- * Filename mangling functions stolen from s main/DriverUtil.lhs.
--------------------------------------------------------------------------------
baseName :: ModuleName -> FilePath
baseName = map (\c -> if c == '.' then '-' else c) . moduleNameString
moduleHtmlFile :: Module -> FilePath
moduleHtmlFile mdl =
case Map.lookup mdl html_xrefs of
Nothing -> baseName mdl' ++ ".html"
Just fp0 -> HtmlPath.joinPath [fp0, baseName mdl' ++ ".html"]
where
mdl' = moduleName mdl
moduleHtmlFile' :: ModuleName -> FilePath
moduleHtmlFile' mdl =
case Map.lookup mdl html_xrefs' of
Nothing -> baseName mdl ++ ".html"
Just fp0 -> HtmlPath.joinPath [fp0, baseName mdl ++ ".html"]
contentsHtmlFile, indexHtmlFile :: String
contentsHtmlFile = "index.html"
indexHtmlFile = "doc-index.html"
-- | The name of the module index file to be displayed inside a frame.
-- Modules are display in full, but without indentation. Clicking opens in
-- the main window.
frameIndexHtmlFile :: String
frameIndexHtmlFile = "index-frames.html"
moduleIndexFrameName, mainFrameName, synopsisFrameName :: String
moduleIndexFrameName = "modules"
mainFrameName = "main"
synopsisFrameName = "synopsis"
subIndexHtmlFile :: String -> String
subIndexHtmlFile ls = "doc-index-" ++ b ++ ".html"
where b | all isAlpha ls = ls
| otherwise = concatMap (show . ord) ls
-------------------------------------------------------------------------------
-- * Anchor and URL utilities
--
-- NB: Anchor IDs, used as the destination of a link within a document must
-- conform to XML's NAME production. That, taken with XHTML and HTML 4.01's
-- various needs and compatibility constraints, means these IDs have to match:
-- [A-Za-z][A-Za-z0-9:_.-]*
-- Such IDs do not need to be escaped in any way when used as the fragment part
-- of a URL. Indeed, %-escaping them can lead to compatibility issues as it
-- isn't clear if such fragment identifiers should, or should not be unescaped
-- before being matched with IDs in the target document.
-------------------------------------------------------------------------------
moduleUrl :: Module -> String
moduleUrl = moduleHtmlFile
moduleNameUrl :: Module -> OccName -> String
moduleNameUrl mdl n = moduleUrl mdl ++ '#' : nameAnchorId n
moduleNameUrl' :: ModuleName -> OccName -> String
moduleNameUrl' mdl n = moduleHtmlFile' mdl ++ '#' : nameAnchorId n
nameAnchorId :: OccName -> String
nameAnchorId name = makeAnchorId (prefix : ':' : occNameString name)
where prefix | isValOcc name = 'v'
| otherwise = 't'
-- | Takes an arbitrary string and makes it a valid anchor ID. The mapping is
-- identity preserving.
makeAnchorId :: String -> String
makeAnchorId [] = []
makeAnchorId (f:r) = escape isAlpha f ++ concatMap (escape isLegal) r
where
escape p c | p c = [c]
| otherwise = '-' : show (ord c) ++ "-"
isLegal ':' = True
isLegal '_' = True
isLegal '.' = True
isLegal c = isAscii c && isAlphaNum c
-- NB: '-' is legal in IDs, but we use it as the escape char
-------------------------------------------------------------------------------
-- * Files we need to copy from our $libdir
-------------------------------------------------------------------------------
jsFile, framesFile :: String
jsFile = "haddock-util.js"
framesFile = "frames.html"
-------------------------------------------------------------------------------
-- * Misc.
-------------------------------------------------------------------------------
getProgramName :: IO String
getProgramName = liftM (`withoutSuffix` ".bin") getProgName
where str `withoutSuffix` suff
| suff `isSuffixOf` str = take (length str - length suff) str
| otherwise = str
bye :: String -> IO a
bye s = putStr s >> exitSuccess
dieMsg :: String -> IO ()
dieMsg s = getProgramName >>= \prog -> die (prog ++ ": " ++ s)
noDieMsg :: String -> IO ()
noDieMsg s = getProgramName >>= \prog -> hPutStr stderr (prog ++ ": " ++ s)
mapSnd :: (b -> c) -> [(a,b)] -> [(a,c)]
mapSnd _ [] = []
mapSnd f ((x,y):xs) = (x,f y) : mapSnd f xs
mapMaybeM :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b)
mapMaybeM _ Nothing = return Nothing
mapMaybeM f (Just a) = liftM Just (f a)
escapeStr :: String -> String
escapeStr = escapeURIString isUnreserved
-- Following few functions are copy'n'pasted from Network.URI module
-- to avoid depending on the network lib, since doing so gives a
-- circular build dependency between haddock and network
-- (at least if you want to build network with haddock docs)
escapeURIChar :: (Char -> Bool) -> Char -> String
escapeURIChar p c
| p c = [c]
| otherwise = '%' : myShowHex (ord c) ""
where
myShowHex :: Int -> ShowS
myShowHex n r = case showIntAtBase 16 toChrHex n r of
[] -> "00"
[a] -> ['0',a]
cs -> cs
toChrHex d
| d < 10 = chr (ord '0' + fromIntegral d)
| otherwise = chr (ord 'A' + fromIntegral (d - 10))
escapeURIString :: (Char -> Bool) -> String -> String
escapeURIString = concatMap . escapeURIChar
isUnreserved :: Char -> Bool
isUnreserved c = isAlphaNumChar c || (c `elem` "-_.~")
isAlphaChar, isDigitChar, isAlphaNumChar :: Char -> Bool
isAlphaChar c = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
isDigitChar c = c >= '0' && c <= '9'
isAlphaNumChar c = isAlphaChar c || isDigitChar c
-----------------------------------------------------------------------------
-- * HTML cross references
--
-- For each module, we need to know where its HTML documentation lives
-- so that we can point hyperlinks to it. It is extremely
-- inconvenient to plumb this information to all the places that need
-- it (basically every function in HaddockHtml), and furthermore the
-- mapping is constant for any single run of Haddock. So for the time
-- being I'm going to use a write-once global variable.
-----------------------------------------------------------------------------
{-# NOINLINE html_xrefs_ref #-}
html_xrefs_ref :: IORef (Map Module FilePath)
html_xrefs_ref = unsafePerformIO (newIORef (error "module_map"))
{-# NOINLINE html_xrefs_ref' #-}
html_xrefs_ref' :: IORef (Map ModuleName FilePath)
html_xrefs_ref' = unsafePerformIO (newIORef (error "module_map"))
{-# NOINLINE html_xrefs #-}
html_xrefs :: Map Module FilePath
html_xrefs = unsafePerformIO (readIORef html_xrefs_ref)
{-# NOINLINE html_xrefs' #-}
html_xrefs' :: Map ModuleName FilePath
html_xrefs' = unsafePerformIO (readIORef html_xrefs_ref')
-----------------------------------------------------------------------------
-- * List utils
-----------------------------------------------------------------------------
replace :: Eq a => a -> a -> [a] -> [a]
replace a b = map (\x -> if x == a then b else x)
spanWith :: (a -> Maybe b) -> [a] -> ([b],[a])
spanWith _ [] = ([],[])
spanWith p xs@(a:as)
| Just b <- p a = let (bs,cs) = spanWith p as in (b:bs,cs)
| otherwise = ([],xs)
-----------------------------------------------------------------------------
-- * Put here temporarily
-----------------------------------------------------------------------------
markup :: DocMarkup id a -> Doc id -> a
markup m DocEmpty = markupEmpty m
markup m (DocAppend d1 d2) = markupAppend m (markup m d1) (markup m d2)
markup m (DocString s) = markupString m s
markup m (DocParagraph d) = markupParagraph m (markup m d)
markup m (DocIdentifier x) = markupIdentifier m x
markup m (DocIdentifierUnchecked x) = markupIdentifierUnchecked m x
markup m (DocModule mod0) = markupModule m mod0
markup m (DocWarning d) = markupWarning m (markup m d)
markup m (DocEmphasis d) = markupEmphasis m (markup m d)
markup m (DocBold d) = markupBold m (markup m d)
markup m (DocMonospaced d) = markupMonospaced m (markup m d)
markup m (DocUnorderedList ds) = markupUnorderedList m (map (markup m) ds)
markup m (DocOrderedList ds) = markupOrderedList m (map (markup m) ds)
markup m (DocDefList ds) = markupDefList m (map (markupPair m) ds)
markup m (DocCodeBlock d) = markupCodeBlock m (markup m d)
markup m (DocHyperlink l) = markupHyperlink m l
markup m (DocAName ref) = markupAName m ref
markup m (DocPic img) = markupPic m img
markup m (DocProperty p) = markupProperty m p
markup m (DocExamples e) = markupExample m e
markup m (DocHeader (Header l t)) = markupHeader m (Header l (markup m t))
markupPair :: DocMarkup id a -> (Doc id, Doc id) -> (a, a)
markupPair m (a,b) = (markup m a, markup m b)
-- | The identity markup
idMarkup :: DocMarkup a (Doc a)
idMarkup = Markup {
markupEmpty = DocEmpty,
markupString = DocString,
markupParagraph = DocParagraph,
markupAppend = DocAppend,
markupIdentifier = DocIdentifier,
markupIdentifierUnchecked = DocIdentifierUnchecked,
markupModule = DocModule,
markupWarning = DocWarning,
markupEmphasis = DocEmphasis,
markupBold = DocBold,
markupMonospaced = DocMonospaced,
markupUnorderedList = DocUnorderedList,
markupOrderedList = DocOrderedList,
markupDefList = DocDefList,
markupCodeBlock = DocCodeBlock,
markupHyperlink = DocHyperlink,
markupAName = DocAName,
markupPic = DocPic,
markupProperty = DocProperty,
markupExample = DocExamples,
markupHeader = DocHeader
}
-----------------------------------------------------------------------------
-- * System tools
-----------------------------------------------------------------------------
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
#else
getProcessID :: IO Int
getProcessID = fmap fromIntegral System.Posix.Internals.c_getpid
#endif
| jstolarek/haddock | haddock-api/src/Haddock/Utils.hs | bsd-2-clause | 15,975 | 0 | 20 | 3,378 | 3,904 | 2,089 | 1,815 | 251 | 4 |
{-# LANGUAGE ScopedTypeVariables #-}
module Import
( module Prelude
, module Foundation
, (<>)
, Text
, module Data.Monoid
, module Control.Applicative
, module Gitolite
, module Data.Maybe
, module Settings.StaticFiles
, getGitolite
, withRepo
, withRepoObj
, isBlob
, repoLayout
, treeLink
, isTree
, module Yesod.Auth
, module ContentTypes
, isRegularFile
, isDirectory
, renderPath
, module Encodings
) where
import Yesod.Auth hiding (Route)
import Yesod.Default.Config
import Prelude hiding (writeFile, readFile, catch)
import Foundation
import Text.Hamlet (hamletFile)
import Data.Monoid (Monoid (mappend, mempty, mconcat))
import Control.Applicative ((<$>), (<*>), pure)
import Data.Text (Text)
import Gitolite hiding (User)
import qualified Data.Git as Git
import qualified System.Git as Git
import qualified Data.ByteString.Char8 as BS
import Data.List
import qualified Settings
import Settings.StaticFiles
import Data.Maybe (fromMaybe, listToMaybe)
import Database.Persist.Store
import qualified Data.Text as T
import Encodings
import ContentTypes
import Control.Exception (try, SomeException(..))
import System.FilePath
import System.Directory
isBlob, isTree :: Git.GitObject -> Bool
isBlob (Git.GoBlob _ _) = True
isBlob _ = False
isTree (Git.GoTree _ _) = True
isTree _ = False
isRegularFile :: Git.GitTreeEntry -> Bool
isRegularFile (Git.GitTreeEntry (Git.RegularFile _) _ _) = True
isRegularFile _ = False
isDirectory :: Git.GitTreeEntry -> Bool
isDirectory (Git.GitTreeEntry Git.Directory _ _) = True
isDirectory _ = False
withRepoObj :: String
-> ObjPiece
-> (Gitolite -> Repository -> Git.GitObject -> Handler a)
-> Handler a
withRepoObj repon (ObjPiece commit path) act = do
withRepo repon $ \git repo -> do
let gitDir = repoDir git repo
(prefix, rest) = splitAt 2 commit
root <- liftIO $ do
isHash <- doesFileExist $ gitDir </> "objects" </> prefix </> rest
if isHash
then Git.sha1ToObj (Git.SHA1 commit) gitDir
else repoBranch git repo commit >>= flip Git.sha1ToObj gitDir . commitRef . branchHEAD
let curPath = intercalate "/" (commit:path)
obj <- liftIO $ traverseGoTree git repo path root
setSessionBS "curPath" (BS.pack curPath)
ans <- act git repo obj
deleteSession "curPath"
return ans
withRepo :: String -> (Gitolite -> Repository -> Handler a) -> Handler a
withRepo repon act = do
git <- getGitolite
let mrep = find ((== repon) . repoName) $ repositories git
case mrep of
Nothing -> notFound
Just repo -> do
mu <- maybeAuth
let uName = maybe Settings.guestName (userIdent . entityVal) mu
if repo `isReadableFor` uName
then act git repo
else permissionDenied $ T.pack $
"You don't have permission for repository " ++ repon
getGitolite :: Handler Gitolite
getGitolite = liftIO $ parseGitolite repositoriesPath
renderPath :: ObjPiece -> String
renderPath (ObjPiece a b) = intercalate "/" (a:b)
infixr 5 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
treeLink :: String -> ObjPiece -> Widget
treeLink repon (ObjPiece c as) =
let ents = if null as then [[]] else init $ inits as
in [whamlet|
<ul .breadcrumb>
$forall e <- ents
<li>
<span .divider>/
<a href=@{TreeR repon (ObjPiece c e)}>
$if null e
#{c}
$else
#{last e}
$if (not (null as))
<li>
<span .divider>/ #
#{last as}
|]
repoLayout :: String -> ObjPiece -> Widget -> Handler RepHtml
repoLayout repon op@(ObjPiece commit ps) widget = withRepoObj repon op $ \git repo obj -> do
master <- getYesod
mmsg <- getMessage
route <- getCurrentRoute
let curTab = case route of
Just (TreeR _ _) -> "tab_files" :: String
Just (BlobR _ _) -> "tab_files"
Just (TagsR _) -> "tab_tags"
Just (CommitsR _ _) -> "tab_commits"
Just (CommitR _ _) -> "tab_commits"
_ -> "tab_files"
description <- liftIO $ getDescription git repo
branches <- liftIO $ repoBranches git repo
musr <- fmap entityVal <$> maybeAuth
let curPath = treeLink repon op
pc <- widgetToPageContent $ do
addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
addScript $ StaticR js_bootstrap_dropdown_js
addStylesheet $ StaticR css_bootstrap_responsive_css
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "normalize")
$(widgetFile "repo-layout")
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
| konn/gitolist | Import.hs | bsd-2-clause | 4,831 | 0 | 20 | 1,261 | 1,380 | 726 | 654 | -1 | -1 |
{-# LANGUAGE TupleSections #-}
module Driver where
import Control.Applicative ((<$>),(<*>))
import Control.Monad (when)
import Data.Foldable (forM_)
import Distribution.Package
import Distribution.PackageDescription
import Distribution.ModuleName
import Distribution.PackageDescription.Parse
import Distribution.Verbosity
import System.FilePath ((</>))
import System.Process (system)
--
import MetaPackage
cabalFile :: AProject -> FilePath
cabalFile (AProject pname ppath) = ppath </> (pname ++ ".cabal")
parseAProject :: AProject -> IO GenericPackageDescription
parseAProject proj =
let cabal = cabalFile proj
in readPackageDescription normal cabal
-- | relative path info to absolute path info for modules
absolutePathModule :: AProject -> (FilePath,ModuleName) -> (FilePath,ModuleName)
absolutePathModule proj (fp,modname) =
let absolutify dir = projloc proj </> dir
in (absolutify fp,modname)
hyphenToUnderscore :: String -> String
hyphenToUnderscore = map (\x -> if x == '-' then '_' else x)
-- | driver IO action for make a meta package
makeMetaPackage :: MetaProject -> String -> IO FilePath
makeMetaPackage mp extra = do
parsedpkgs <- mapM (\x -> (x,) <$> parseAProject x) (metaProjectPkg mp)
let allmodules = getAllModules parsedpkgs
(pkgpath,srcpath) <- initializeMetaPackage mp
forM_ parsedpkgs $ \x ->
let xname = (projname . fst) x
xpath = (projloc . fst) x
in linkDirectory xpath (pkgpath </> "data_" ++ (hyphenToUnderscore xname))
mapM_ (linkMod srcpath) . concatMap (\(proj,lst) -> map (absolutePathModule proj) lst) $ allmodules
let allmodnames = do (_,ns) <- allmodules
(_,m) <- ns
return m
allothermodnames = do (_,ns) <- getAllOtherModules parsedpkgs
(_,m) <- ns
return m
allothermodnamestrings = map components allothermodnames
pathsAction strs = when (take 6 (head strs) == "Paths_") $ do
let pname = drop 6 (head strs)
makePaths_xxxHsFile pkgpath mp pname
mapM_ pathsAction (allothermodnamestrings ++ map components allmodnames)
{-
let exelst = getExeFileAndCabalString bc mp pkgpath pkgs
exestr = concatMap snd exelst
mapM_ (linkExeSrcFile . fst) exelst
-}
makeCabalFile pkgpath mp parsedpkgs allmodnames allothermodnames extra -- "" -- exestr
return pkgpath
| wavewave/metapackage | src/Driver.hs | bsd-2-clause | 2,470 | 0 | 18 | 581 | 689 | 358 | 331 | 48 | 2 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, CPP #-}
module Network.DNS.StateBinary where
import Control.Monad.State (State, StateT)
import qualified Control.Monad.State as ST
import Control.Monad.Trans.Resource (ResourceT)
import qualified Data.Attoparsec.ByteString as A
import qualified Data.Attoparsec.Types as T
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.ByteString.Builder (Builder)
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Conduit (Sink)
import Data.Conduit.Attoparsec (sinkParser)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
import Data.Map (Map)
import qualified Data.Map as M
import Data.Word (Word8, Word16, Word32)
import Network.DNS.Types
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>), (<*))
import Data.Monoid (Monoid, mconcat, mappend, mempty)
#endif
----------------------------------------------------------------
type SPut = State WState Builder
data WState = WState {
wsDomain :: Map Domain Int
, wsPosition :: Int
}
initialWState :: WState
initialWState = WState M.empty 0
instance Monoid SPut where
mempty = return mempty
mappend a b = mconcat <$> sequence [a, b]
put8 :: Word8 -> SPut
put8 = fixedSized 1 BB.word8
put16 :: Word16 -> SPut
put16 = fixedSized 2 BB.word16BE
put32 :: Word32 -> SPut
put32 = fixedSized 4 BB.word32BE
putInt8 :: Int -> SPut
putInt8 = fixedSized 1 (BB.int8 . fromIntegral)
putInt16 :: Int -> SPut
putInt16 = fixedSized 2 (BB.int16BE . fromIntegral)
putInt32 :: Int -> SPut
putInt32 = fixedSized 4 (BB.int32BE . fromIntegral)
putByteString :: ByteString -> SPut
putByteString = writeSized BS.length BB.byteString
addPositionW :: Int -> State WState ()
addPositionW n = do
(WState m cur) <- ST.get
ST.put $ WState m (cur+n)
fixedSized :: Int -> (a -> Builder) -> a -> SPut
fixedSized n f a = do addPositionW n
return (f a)
writeSized :: (a -> Int) -> (a -> Builder) -> a -> SPut
writeSized n f a = do addPositionW (n a)
return (f a)
wsPop :: Domain -> State WState (Maybe Int)
wsPop dom = do
doms <- ST.gets wsDomain
return $ M.lookup dom doms
wsPush :: Domain -> Int -> State WState ()
wsPush dom pos = do
(WState m cur) <- ST.get
ST.put $ WState (M.insert dom pos m) cur
----------------------------------------------------------------
type SGet = StateT PState (T.Parser ByteString)
data PState = PState {
psDomain :: IntMap Domain
, psPosition :: Int
}
----------------------------------------------------------------
getPosition :: SGet Int
getPosition = psPosition <$> ST.get
addPosition :: Int -> SGet ()
addPosition n = do
PState dom pos <- ST.get
ST.put $ PState dom (pos + n)
push :: Int -> Domain -> SGet ()
push n d = do
PState dom pos <- ST.get
ST.put $ PState (IM.insert n d dom) pos
pop :: Int -> SGet (Maybe Domain)
pop n = IM.lookup n . psDomain <$> ST.get
----------------------------------------------------------------
get8 :: SGet Word8
get8 = ST.lift A.anyWord8 <* addPosition 1
get16 :: SGet Word16
get16 = ST.lift getWord16be <* addPosition 2
where
word8' = fromIntegral <$> A.anyWord8
getWord16be = do
a <- word8'
b <- word8'
return $ a * 0x100 + b
get32 :: SGet Word32
get32 = ST.lift getWord32be <* addPosition 4
where
word8' = fromIntegral <$> A.anyWord8
getWord32be = do
a <- word8'
b <- word8'
c <- word8'
d <- word8'
return $ a * 0x1000000 + b * 0x10000 + c * 0x100 + d
getInt8 :: SGet Int
getInt8 = fromIntegral <$> get8
getInt16 :: SGet Int
getInt16 = fromIntegral <$> get16
getInt32 :: SGet Int
getInt32 = fromIntegral <$> get32
----------------------------------------------------------------
getNBytes :: Int -> SGet [Int]
getNBytes len = toInts <$> getNByteString len
where
toInts = map fromIntegral . BS.unpack
getNByteString :: Int -> SGet ByteString
getNByteString n = ST.lift (A.take n) <* addPosition n
----------------------------------------------------------------
initialState :: PState
initialState = PState IM.empty 0
sinkSGet :: SGet a -> Sink ByteString (ResourceT IO) (a, PState)
sinkSGet parser = sinkParser (ST.runStateT parser initialState)
runSGet :: SGet a -> ByteString -> Either String (a, PState)
runSGet parser bs = A.eitherResult $ A.parse (ST.runStateT parser initialState) bs
runSGetWithLeftovers :: SGet a -> ByteString -> Either String ((a, PState), ByteString)
runSGetWithLeftovers parser bs = toResult $ A.parse (ST.runStateT parser initialState) bs
where
toResult :: A.Result r -> Either String (r, ByteString)
toResult (A.Done i r) = Right (r, i)
toResult (A.Partial f) = toResult $ f BS.empty
toResult (A.Fail _ _ err) = Left err
runSPut :: SPut -> ByteString
runSPut = LBS.toStrict . BB.toLazyByteString . flip ST.evalState initialWState
| greydot/dns | Network/DNS/StateBinary.hs | bsd-3-clause | 4,973 | 0 | 15 | 965 | 1,699 | 895 | 804 | 122 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{- |
Module: Main
Maintainer: Thomas Sutton
This module implements a command-line tool to perform formal concept analysis
on data sets.
-}
module Main where
import Control.Applicative
import qualified Data.ByteString.Lazy as BL
import Data.Csv hiding (Name, Parser)
import qualified Data.Text.Lazy.IO as T
import Options.Applicative
import System.IO
import Data.FCA
-- | Options for invocation, generally constructed from command-line options.
data Options = Options
{ optVerbose :: Bool -- ^ Be verbose.
, optHeader :: Bool -- ^ Data includes headers.
, optFormat :: Format -- ^ Input data format.
, optOutput :: Maybe String -- ^ Output to file.
, optInput :: Maybe String -- ^ Input from file.
}
deriving (Eq, Ord, Show)
-- | Formats for input data.
data Format
= EA -- ^ Data is in entity/attribute pairs.
| EAV -- ^ Data is in entity, attribute, value triples.
| Tabular -- ^ Data is in column-per-attribute.
deriving (Show, Ord, Eq)
-- | Parser 'Options' from command-line arguments.
optionsP :: Parser Options
optionsP = Options <$> pure False
<*> pure True
<*> formatP
<*> outputP
<*> inputP
where
verboseP = switch $
long "verbose"
<> short 'v'
<> help "Produce verbose output."
headerP = switch $
long "header"
<> short 'H'
<> help "Input contains headers."
outputP = option (Just <$> str) $
long "output"
<> short 'o'
<> help "Write output to FILE. (default: stdout)"
<> metavar "FILE"
<> value Nothing
inputP = argument (Just <$> str) $
metavar "FILE"
<> help "Read input from FILE. (default: stdin)"
<> value Nothing
formatP = option (eitherReader readFmt) $
long "format"
<> short 'f'
<> help "Input data format."
<> metavar "ea|eav|tab"
<> value EAV
<> showDefault
readFmt :: String -> Either String Format
readFmt "ea" = Right EA
readFmt "eav" = Right EAV
readFmt "tab" = Right Tabular
readFmt "tabular" = Right Tabular
readFmt _ = Left "Format must be: ea, eav, tabular"
-- | Open input and output handles based on command-line options.
getHandles :: Options -> IO (Handle, Handle)
getHandles Options{..} = do
inH <- maybe (return stdin) (`openFile` ReadMode) optInput
outH <- maybe (return stdout) (`openFile` WriteMode) optOutput
return (inH, outH)
-- | Get a function to read data in the specified format.
getReader :: Options -> Handle -> IO Frame
getReader opt =
case optFormat opt of
EAV -> readEAV opt
EA -> readEA opt
Tabular -> readTabular opt
where
-- | Read data in entity-attribute-value format.
readEAV :: Options -> Handle -> IO Frame
readEAV _ inH = do
input <- BL.hGetContents inH
case decode NoHeader input of
Left err -> error err
Right csv -> return $ parseEAV csv
-- | Read data in entity-attribute format.
readEA :: Options -> Handle -> IO Frame
readEA _ inH = do
input <- BL.hGetContents inH
case decode NoHeader input of
Left err -> error err
Right csv -> return $ parseEA csv
-- | Read data in tabular format.
readTabular :: Options -> Handle -> IO Frame
readTabular _ inH = do
input <- BL.hGetContents inH
case decode NoHeader input of
Left err -> error err
Right csv -> return $ parseTabular csv
main :: IO ()
main = do
opt <- execParser opts
(inH, outH) <- getHandles opt
-- Read the input data.
Frame ctx omap amap <- getReader opt inH
hClose inH
-- Run the FCA algorithm on the context.
let table = buildAETable ctx
let graph = generateGraph table omap amap
-- Output the graph.
T.hPutStrLn outH graph
hClose outH
where
opts = info (helper <*> optionsP)
( fullDesc
<> progDesc "Generate the concept lattice which describs a data set."
<> header "fca - formal concept analysis"
)
| thsutton/fca | src/Main.hs | bsd-3-clause | 4,322 | 0 | 15 | 1,344 | 1,004 | 502 | 502 | 102 | 6 |
{-# OPTIONS_GHC -Wall #-}
module Classy.Casadi.Integrator where
import Control.Applicative ( (<$>) )
import Python.Exceptions
import Python.Interpreter
import Python.Objects
import Foreign.C.Types ( CDouble )
import qualified Classy.Convenience as CC
import Classy.State hiding ( run )
import Classy.Types
import Classy.Casadi.DAE
import Classy.Casadi.Bindings
newtype Integrator = Integrator PyObject
instance ToPyObject Integrator where toPyObject (Integrator p) = return p
instance FromPyObject Integrator where fromPyObject = return . Integrator
run :: IO ()
run = do
casadiModule <- casadiInit
dae <- mkDae casadiModule someSys
int <- mkIdasIntegrator casadiModule dae
setOption int "fsens_err_con" True
setOption int "quad_err_con" True
setOption int "abstol" (1e-12::CDouble)
setOption int "reltol" (1e-12::CDouble)
setOption int "fsens_abstol" (1e-6::CDouble)
setOption int "fsens_reltol" (1e-6::CDouble)
setOption int "asens_abstol" (1e-6::CDouble)
setOption int "asens_reltol" (1e-6::CDouble)
-- setOption int "exact_jacobian" exact_jacobian
-- setOption int "finite_difference_fsens" finite_difference_fsens
setOption int "max_num_steps" (100000 :: Integer)
setOption int "t0" (0::Integer)
setOption int "tf" (5::Integer)
-- showPyObject integrator >>= putStrLn
-- Set parameters
setParams casadiModule int [10,1,9.8]
--
-- Set inital state
setX0 casadiModule int [10, 0.5, 0, 0.1]
--
-- # Integrate
ret <- evaluate int
showPyObject ret >>= putStrLn
evaluate :: Integrator -> IO PyObject
evaluate (Integrator int) =
handlePy (\x -> ("evaluate: " ++) . show <$> formatException x >>= error) $ do
runMethodHs int "evaluate" noParms noKwParms
callMethodHs int "output" noParms noKwParms
setX0 :: CasadiModule -> Integrator -> [CDouble] -> IO ()
setX0 (CasadiModule cm) (Integrator int) x0s =
handlePy (\x -> ("setX0: " ++) . show <$> formatException x >>= error) $ do
d <- getattr cm "INTEGRATOR_X0"
x0s' <- toPyObject x0s
runMethodHs int "setInput" [x0s', d] noKwParms
setParams :: CasadiModule -> Integrator -> [CDouble] -> IO ()
setParams (CasadiModule cm) (Integrator int) ps =
handlePy (\x -> ("setParams: " ++) . show <$> formatException x >>= error) $ do
d <- getattr cm "INTEGRATOR_P"
ps' <- toPyObject ps
runMethodHs int "setInput" [ps', d] noKwParms
mkIdasIntegrator :: CasadiModule -> DAE -> IO Integrator
mkIdasIntegrator (CasadiModule casadiModule) dae =
handlePy (\x -> ("mkIdasIntegrator: " ++) . show <$> formatException x >>= error) $ do
int@(Integrator i) <- callMethodHs casadiModule "IdasIntegrator" [dae] noKwParms
runMethodHs i "init" noParms noKwParms
return int
setOption :: ToPyObject a => Integrator -> String -> a -> IO ()
setOption (Integrator i) option value =
handlePy (\x -> ("setOption: " ++) . show <$> formatException x >>= error) $ do
opt <- toPyObject option
val <- toPyObject value
runMethodHs i "setOption" [opt, val] noKwParms
someSys :: System
someSys = getSystem $ do
n <- newtonianBases
q <- addCoord "q"
r <- addCoord "r"
derivIsSpeed q
derivIsSpeed r
mass <- addParam "m"
g <- addParam "g"
tension <- addAction "T"
b <- rotY n q "B"
let r_b_n0 = CC.relativePoint N0 (CC.zVec r b)
basket <- addParticle mass r_b_n0
addForceAtCm basket (CC.zVec (mass*g) n)
addForceAtCm basket (CC.zVec (-tension) b)
| ghorn/classy-dvda | src/Classy/Casadi/Integrator.hs | bsd-3-clause | 3,400 | 0 | 14 | 610 | 1,155 | 576 | 579 | 79 | 1 |
#!/usr/bin/env stack
-- stack --install-ghc runghc --package turtle
{-# LANGUAGE OverloadedStrings #-}
import Turtle
import Filesystem.Path.CurrentOS
import Data.Text
main = sh $
do m <- using $ mktempfile "." "m.pdf"
sr <- using $ mktempfile "." "sr.pdf"
let p1 = ["bbc-oca/msr/79ths.score"]
p2 = ["bbc-oca/msr/dorrator.score", "bbc-oca/msr/lexy.score"]
p1f <- encode <$> using (mktempfile "." "march.score")
p2f <- encode <$> using (mktempfile "." "s-r.score")
shells ("cat " <> (intercalate " " p1) <> " > " <> p1f) mempty
shells ("cat " <> "styles/landscape.score " <> (intercalate " " p2) <> " > " <> p2f) mempty
procs "score-writer" ["render", "--score-file", p1f, "--output-file", encode m] mempty
procs "score-writer" ["render", "--score-file", p2f, "--output-file", encode sr] mempty
shells ("/usr/local/bin/gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=msr.pdf " <> encode m <> " " <> encode sr) mempty
| nkpart/score-writer | library/make-msr.hs | bsd-3-clause | 1,005 | 0 | 14 | 213 | 277 | 139 | 138 | 16 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.