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 ScopedTypeVariables #-}
{-# LANGUAGE OverlappingInstances, UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts, FlexibleInstances, TypeSynonymInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
module Narradar.Types.Problem.Narrowing where
import Control.Applicative
import Control.Exception (assert)
import Control.Monad.Free
import Data.Foldable as F (Foldable(..), toList)
import Data.Traversable as T (Traversable(..), mapM)
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Text.XHtml (HTML(..), theclass)
import Data.Term
import Data.Term.Rules
import Narradar.Types.ArgumentFiltering (AF_, ApplyAF(..))
import qualified Narradar.Types.ArgumentFiltering as AF
import Narradar.Types.DPIdentifiers
import Narradar.Types.Problem
import Narradar.Types.Problem.Rewriting
import Narradar.Types.TRS
import Narradar.Types.Term
import Narradar.Types.Var
import Narradar.Utils
import Narradar.Framework
import Narradar.Framework.Ppr
data MkNarrowing base = MkNarrowing base deriving (Eq, Ord, Show)
type Narrowing = MkNarrowing Rewriting
type CNarrowing = MkNarrowing IRewriting
type INarrowing = MkNarrowing IRewriting
narrowing = MkNarrowing rewriting
cnarrowing = MkNarrowing irewriting
instance IsProblem b => IsProblem (MkNarrowing b) where
newtype Problem (MkNarrowing b) a = NarrowingProblem {baseProblem::Problem b a}
getFramework (NarrowingProblem p) = MkNarrowing (getFramework p)
getR (NarrowingProblem b) = getR b
instance IsDPProblem b => IsDPProblem (MkNarrowing b) where
getP (NarrowingProblem b) = getP b
instance MkProblem b trs => MkProblem (MkNarrowing b) trs where
mkProblem (MkNarrowing b) = NarrowingProblem . mkProblem b
mapR f (NarrowingProblem b) = NarrowingProblem (mapR f b)
instance (MkProblem (MkNarrowing b) trs, MkDPProblem b trs) => MkDPProblem (MkNarrowing b) trs where
mkDPProblem (MkNarrowing b) r p = NarrowingProblem $ mkDPProblem b r p
mapP f (NarrowingProblem b) = NarrowingProblem (mapP f b)
deriving instance (Eq (Problem p trs)) => Eq (Problem (MkNarrowing p) trs)
deriving instance (Ord (Problem p trs)) => Ord (Problem (MkNarrowing p) trs)
deriving instance (Show (Problem p trs)) => Show (Problem (MkNarrowing p) trs)
-- Functor
instance Functor (Problem p) => Functor (Problem (MkNarrowing p)) where fmap f (NarrowingProblem p) = NarrowingProblem (fmap f p)
instance Foldable (Problem p) => Foldable (Problem (MkNarrowing p)) where foldMap f (NarrowingProblem p) = foldMap f p
instance Traversable (Problem p) => Traversable (Problem (MkNarrowing p)) where traverse f (NarrowingProblem p) = NarrowingProblem <$> traverse f p
-- Data.Term instances
-- Output
instance HTML Narrowing where toHtml _ = toHtml "Narrowing Problem"
instance HTML CNarrowing where toHtml _ = toHtml "Constructor Narrowing Problem"
instance HTMLClass Narrowing where htmlClass _ = theclass "NDP"
instance HTMLClass CNarrowing where htmlClass _ = theclass "GNDP"
instance Pretty base => Pretty (MkNarrowing base) where
pPrint (MkNarrowing base) = text "Narrowing" <+> parens base
instance Pretty Narrowing where
pPrint (MkNarrowing (MkRewriting Standard M)) = text "Narrowing"
pPrint (MkNarrowing (MkRewriting Standard A)) = text "Narrowing (no minimality)"
instance Pretty INarrowing where
pPrint (MkNarrowing (MkRewriting Innermost M)) = text "Narrowing (innermost strategy)"
pPrint (MkNarrowing (MkRewriting Innermost A)) = text "Narrowing (innermost strategy, no minimality)"
instance (Monoid trs, HasRules t v trs, GetVars v trs, Pretty v, Pretty (t(Term t v))
,HasId t, Pretty (TermId t), Functor t, Foldable t, MkDPProblem Rewriting trs
) => PprTPDB (Problem Narrowing trs) where
pprTPDB p = pprTPDB (getBaseProblem p) $$ text "(STRATEGY NARROWING)"
instance (Monoid trs, HasRules t v trs, GetVars v trs, Pretty v, Pretty (t(Term t v))
,HasId t, Pretty (TermId t), Functor t, Foldable t, MkDPProblem Rewriting trs
) => PprTPDB (Problem CNarrowing trs) where
pprTPDB p = pprTPDB (getBaseProblem p) $$ text "(STRATEGY CNARROWING)"
-- Framework Extension
instance FrameworkExtension MkNarrowing where
getBaseFramework (MkNarrowing b) = b
getBaseProblem (NarrowingProblem p) = p
liftProblem f p = f (baseProblem p) >>= \p0' -> return p{baseProblem = p0'}
liftFramework f (MkNarrowing b) = MkNarrowing (f b)
liftProcessorS = liftProcessorSdefault
-- ICap
instance ICap t v (st, NarradarTRS t v) => ICap t v (MkNarrowing st, NarradarTRS t v) where icap = liftIcap
-- Usable Rules
instance (IUsableRules t v base trs) => IUsableRules t v (MkNarrowing base) trs where
iUsableRulesM = liftUsableRulesM
iUsableRulesVarM = liftUsableRulesVarM
-- Insert Pairs
instance (Pretty id, Ord id) =>InsertDPairs Narrowing (NTRS id) where
insertDPairs = insertDPairsDefault
instance (Pretty id, Ord id) =>InsertDPairs CNarrowing (NTRS id) where
insertDPairs = insertDPairsDefault
-- Get Pairs
instance GetPairs Narrowing where getPairs _ = getNPairs
getNPairs trs = getPairs rewriting trs ++ getLPairs trs
getLPairs trs = [ markDP l :-> markDP lp | l :-> _ <- rules trs, lp <- properSubterms l, isRootDefined trs lp]
| pepeiborra/narradar | src/Narradar/Types/Problem/Narrowing.hs | bsd-3-clause | 5,295 | 0 | 10 | 831 | 1,735 | 901 | 834 | 91 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
-- | Run commands in a nix-shell
module Stack.Nix
(reexecWithOptionalShell
,nixCmdName
,nixHelpOptName
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Catch (try,MonadCatch)
import Control.Monad.IO.Class (MonadIO,liftIO)
import Control.Monad.Logger (MonadLogger,logDebug)
import Control.Monad.Reader (MonadReader,asks)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Char (toUpper)
import Data.List (intercalate)
import Data.Maybe
import Data.Monoid
import Data.Streaming.Process (ProcessExitedUnsuccessfully(..))
import qualified Data.Text as T
import Data.Version (showVersion)
import Network.HTTP.Client.Conduit (HasHttpManager)
import qualified Paths_stack as Meta
import Prelude -- Fix redundant import warnings
import Stack.Constants (stackProgName,platformVariantEnvVar)
import Stack.Docker (reExecArgName)
import Stack.Exec (exec)
import System.Process.Read (getEnvOverride)
import Stack.Types
import Stack.Types.Internal
import System.Environment (lookupEnv,getArgs,getExecutablePath)
import System.Exit (exitSuccess, exitWith)
-- | If Nix is enabled, re-runs the currently running OS command in a Nix container.
-- Otherwise, runs the inner action.
reexecWithOptionalShell
:: M env m
=> IO ()
-> m ()
reexecWithOptionalShell inner =
do config <- asks getConfig
inShell <- getInShell
isReExec <- asks getReExec
if nixEnable (configNix config) && not inShell && not isReExec
then runShellAndExit getCmdArgs
else liftIO inner
where
getCmdArgs = do
args <-
fmap
(("--" ++ reExecArgName ++ "=" ++ showVersion Meta.version) :)
(liftIO getArgs)
exePath <- liftIO getExecutablePath
return (exePath, args)
runShellAndExit :: M env m
=> m (String, [String])
-> m ()
runShellAndExit getCmdArgs = do
config <- asks getConfig
envOverride <- getEnvOverride (configPlatform config)
(cmnd,args) <- getCmdArgs
let mshellFile = nixInitFile (configNix config)
pkgsInConfig = nixPackages (configNix config)
nixopts = case mshellFile of
Just filePath -> [filePath]
Nothing -> ["-E", T.unpack $ T.intercalate " " $ concat
[["with (import <nixpkgs> {});"
,"runCommand \"myEnv\" {"
,"buildInputs=lib.optional stdenv.isLinux glibcLocales ++ ["],pkgsInConfig,["];"
,T.pack platformVariantEnvVar <> "=''nix'';"
,T.pack inShellEnvVar <> "=1;"
,"STACK_IN_NIX_EXTRA_ARGS=''"]
, (map (\p -> T.concat
["--extra-lib-dirs=${",p,"}/lib"
," --extra-include-dirs=${",p,"}/include "])
pkgsInConfig), ["'' ;"
,"} \"\""]]]
-- glibcLocales is necessary on Linux to avoid warnings about GHC being incapable to set the locale.
fullArgs = concat [ -- ["--pure"],
map T.unpack (nixShellOptions (configNix config))
,nixopts
,["--command", intercalate " " (map escape (cmnd:args))
++ " $STACK_IN_NIX_EXTRA_ARGS"]
]
$logDebug $
"Using a nix-shell environment " <> (case mshellFile of
Just filePath -> "from file: " <> (T.pack filePath)
Nothing -> "with nix packages: " <> (T.intercalate ", " pkgsInConfig))
e <- try (exec envOverride "nix-shell" fullArgs)
case e of
Left (ProcessExitedUnsuccessfully _ ec) -> liftIO (exitWith ec)
Right () -> liftIO exitSuccess
-- | Shell-escape quotes inside the string and enclose it in quotes.
escape :: String -> String
escape str = "'" ++ foldr (\c -> if c == '\'' then
("'\"'\"'"++)
else (c:)) "" str
++ "'"
-- | 'True' if we are currently running inside a Nix.
getInShell :: (MonadIO m) => m Bool
getInShell = liftIO (isJust <$> lookupEnv inShellEnvVar)
-- | Environment variable used to indicate stack is running in container.
-- although we already have STACK_IN_NIX_EXTRA_ARGS that is set in the same conditions,
-- it can happen that STACK_IN_NIX_EXTRA_ARGS is set to empty.
inShellEnvVar :: String
inShellEnvVar = concat [map toUpper stackProgName,"_IN_NIXSHELL"]
-- | Command-line argument for "nix"
nixCmdName :: String
nixCmdName = "nix"
nixHelpOptName :: String
nixHelpOptName = nixCmdName ++ "-help"
type M env m =
(MonadIO m
,MonadReader env m
,MonadLogger m
,MonadBaseControl IO m
,MonadCatch m
,HasConfig env
,HasTerminal env
,HasReExec env
,HasHttpManager env
)
| rubik/stack | src/Stack/Nix.hs | bsd-3-clause | 5,344 | 0 | 22 | 1,733 | 1,119 | 613 | 506 | 109 | 4 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE TypeSynonymInstances, FlexibleContexts, OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable, ViewPatterns #-}
module Data.LLVM.Types.Referential (
-- * Basic Types
Type(..),
StructTypeNameError(..),
structTypeToName,
structBaseName,
stripPointerTypes,
UniqueId,
IsValue(..),
Value(..),
toValue,
valueContent',
stripBitcasts,
FromValue(..),
-- * Functions
Function(..),
HasFunction(..),
functionBody,
functionInstructions,
functionReturnType,
functionExitBlock,
functionExitBlocks,
functionIsVararg,
functionEntryInstruction,
functionExitInstruction,
functionExitInstructions,
-- * External Functions
ExternalFunction(..),
externalIsIntrinsic,
externalFunctionParameterTypes,
-- * Arguments
Argument(..),
argumentIndex,
-- * Basic Blocks
BasicBlock(..),
basicBlockInstructions,
basicBlockTerminatorInstruction,
firstNonPhiInstruction,
isFirstNonPhiInstruction,
basicBlockSplitPhiNodes,
-- * Instructions
Instruction(..),
instructionType,
instructionName,
instructionFunction,
instructionIsTerminator,
instructionIsEntry,
instructionIsPhiNode,
instructionOperands,
-- * Globals
GlobalVariable(..),
GlobalAlias(..),
ExternalValue(..),
-- * Constants
Constant(..),
-- * Metadata
Metadata(..),
-- * Debug info
llvmDebugVersion
) where
import Control.DeepSeq
import Control.Exception
import Control.Failure
import Data.Hashable
import Data.Int
import Data.List ( elemIndex )
import Data.Ord ( comparing )
import Data.Text ( Text, isPrefixOf )
import qualified Data.Text as T
import Data.Typeable
import Data.Vector ( Vector )
import qualified Data.Vector as V
import Data.Word ( Word64 )
import Text.Printf
import Text.Regex.TDFA
import Data.LLVM.Types.Attributes
import Data.LLVM.Types.Dwarf
import Data.LLVM.Types.Identifiers
-- | This is the version of LLVM's debug information that this library
-- supports.
llvmDebugVersion :: Integer
llvmDebugVersion = 524288
-- This isn't very honest, but Values are part of Modules and
-- are fully evaluated before the module is constructed.
instance NFData Instruction where
rnf _ = ()
instance NFData Value where
rnf _ = ()
instance NFData BasicBlock where
rnf _ = ()
instance NFData Function where
rnf _ = ()
instance NFData Argument where
rnf _ = ()
instance NFData Type where
rnf _ = ()
-- | The type system of LLVM
data Type = TypeInteger !Int
-- ^ Integral types; the parameter holds the number of
-- bits required to represent the type.
| TypeFloat
| TypeDouble
| TypeFP128
| TypeX86FP80
| TypePPCFP128
| TypeX86MMX
| TypeVoid
| TypeLabel
| TypeMetadata
| TypeArray !Int Type
-- ^ Fixed-length arrays, where the Int holds the number
-- of elements in arrays of this type.
| TypeVector !Int Type
-- ^ Vectors with a fixed length. These are vectors in
-- the SSE sense.
| TypeFunction Type [Type] !Bool
-- ^ Functions with a return type, list of argument types,
-- and a flag that denotes whether or not the function
-- accepts varargs
| TypePointer Type !Int
| TypeStruct (Either Word64 Text) [Type] !Bool
-- ^ Struct types have a list of types in thes struct and
-- a flag that is True if they are packed. Named structs
-- have a (Right stringName) as the name. Anonymous
-- structs have a meaningless (but unique within the
-- Module) integer identifier in the (Left structId).
data StructTypeNameError = NotStructType
deriving (Typeable, Show)
-- | Strip off the struct. prefix and any .NNN suffixes added by LLVM
-- to a struct type name. If the type is not a struct type, return
-- Nothing.
structTypeToName :: (Failure StructTypeNameError m) => Type -> m String
structTypeToName (TypeStruct (Right n) _ _) =
return $ structBaseName (T.unpack n)
structTypeToName _ = failure NotStructType
structBaseName :: String -> String
structBaseName s =
let pfx:_ = captures
in pfx
where
pattern :: String
pattern = "([[:alpha:]]+\\.[:<> [:alnum:]_]+)(\\.[[:digit:]]+)*"
m :: (String, String, String, [String])
m = s =~ pattern
(_, _, _, captures) = m
-- | Take a type and remove all of its pointer wrappers
stripPointerTypes :: Type -> Type
stripPointerTypes t =
case t of
TypePointer t' _ -> stripPointerTypes t'
_ -> t
-- Deriving an Ord instance won't work because Type is a cyclic data
-- structure and the derived instances end up stuck in infinite loops.
-- Defining a more traditional one that just breaks cycles is really
-- tedious here, so just base Ord off of equality and then make the
-- ordering arbitrary (but consistent) based on the Hashable instance.
instance Ord Type where
compare = compareType
compareType :: Type -> Type -> Ordering
compareType ty1 ty2
| ty1 == ty2 = EQ
| otherwise =
case (ty1, ty2) of
(TypeStruct (Right n1) _ _, TypeStruct (Right n2) _ _) ->
compare n1 n2
(TypeStruct (Left n1) _ _, TypeStruct (Left n2) _ _) ->
compare n1 n2
(TypePointer t1 p1, TypePointer t2 p2) -> compare (t1, p1) (t2, p2)
(TypeArray i1 t1, TypeArray i2 t2) -> compare (i1, t1) (i2, t2)
(TypeVector i1 t1, TypeVector i2 t2) -> compare (i1, t1) (i2, t2)
(TypeFunction r1 ts1 v1, TypeFunction r2 ts2 v2) ->
compare (r1, ts1, v1) (r2, ts2, v2)
_ -> compare (typeOrdKey ty1) (typeOrdKey ty2)
typeOrdKey :: Type -> Int
typeOrdKey (TypeInteger i) = negate i
typeOrdKey TypeFloat = 1
typeOrdKey TypeDouble = 2
typeOrdKey TypeFP128 = 3
typeOrdKey TypeX86MMX = 4
typeOrdKey TypeX86FP80 = 5
typeOrdKey TypePPCFP128 = 6
typeOrdKey TypeVoid = 7
typeOrdKey TypeLabel = 8
typeOrdKey TypeMetadata = 9
typeOrdKey (TypeArray _ _) = 10
typeOrdKey (TypeVector _ _) = 11
typeOrdKey (TypeFunction _ _ _) = 12
typeOrdKey (TypePointer _ _) = 13
typeOrdKey (TypeStruct (Right _) _ _) = 14
typeOrdKey (TypeStruct (Left _) _ _) = 15
instance Hashable Type where
hashWithSalt s (TypeInteger i) =
s `hashWithSalt` (1 :: Int) `hashWithSalt` i
hashWithSalt s TypeFloat = s `hashWithSalt` (2 :: Int)
hashWithSalt s TypeDouble = s `hashWithSalt` (3 :: Int)
hashWithSalt s TypeFP128 = s `hashWithSalt` (4 :: Int)
hashWithSalt s TypeX86FP80 = s `hashWithSalt` (5 :: Int)
hashWithSalt s TypePPCFP128 = s `hashWithSalt` (6 :: Int)
hashWithSalt s TypeX86MMX = s `hashWithSalt` (7 :: Int)
hashWithSalt s TypeVoid = s `hashWithSalt` (8 :: Int)
hashWithSalt s TypeLabel = s `hashWithSalt` (9 :: Int)
hashWithSalt s TypeMetadata = s `hashWithSalt` (10 :: Int)
hashWithSalt s (TypeArray i t) =
s `hashWithSalt` (11 :: Int) `hashWithSalt` i `hashWithSalt` t
hashWithSalt s (TypeVector i t) =
s `hashWithSalt` (12 :: Int) `hashWithSalt` i `hashWithSalt` t
hashWithSalt s (TypeFunction r ts v) =
s `hashWithSalt` (13 :: Int) `hashWithSalt` r `hashWithSalt` ts `hashWithSalt` v
hashWithSalt s (TypePointer t as) =
s `hashWithSalt` (15 :: Int) `hashWithSalt` t `hashWithSalt` as
hashWithSalt s (TypeStruct (Right n) _ _) =
s `hashWithSalt` (16 :: Int) `hashWithSalt` n
hashWithSalt s (TypeStruct (Left tid) _ p) =
s `hashWithSalt` (17 :: Int) `hashWithSalt` tid `hashWithSalt` p
instance Eq Type where
TypeInteger i1 == TypeInteger i2 = i1 == i2
TypeFloat == TypeFloat = True
TypeDouble == TypeDouble = True
TypeFP128 == TypeFP128 = True
TypeX86FP80 == TypeX86FP80 = True
TypePPCFP128 == TypePPCFP128 = True
TypeX86MMX == TypeX86MMX = True
TypeVoid == TypeVoid = True
TypeLabel == TypeLabel = True
TypeMetadata == TypeMetadata = True
TypeArray i1 t1 == TypeArray i2 t2 = i1 == i2 && t1 == t2
TypeVector i1 t1 == TypeVector i2 t2 = i1 == i2 && t1 == t2
TypeFunction r1 ts1 v1 == TypeFunction r2 ts2 v2 =
v1 == v2 && r1 == r2 && ts1 == ts2
TypePointer t1 as1 == TypePointer t2 as2 = t1 == t2 && as1 == as2
TypeStruct (Right n1) _ _ == TypeStruct (Right n2) _ _ = n1 == n2
TypeStruct (Left tid1) _ _ == TypeStruct (Left tid2) _ _ =
tid1 == tid2
_ == _ = False
data Metadata =
MetaSourceLocation { metaValueUniqueId :: UniqueId
, metaSourceRow :: !Int32
, metaSourceCol :: !Int32
, metaSourceScope :: Maybe Metadata
}
| MetaDWLexicalBlock { metaValueUniqueId :: UniqueId
, metaLexicalBlockRow :: !Int32
, metaLexicalBlockCol :: !Int32
, metaLexicalBlockContext :: Maybe Metadata
}
| MetaDWNamespace { metaValueUniqueId :: UniqueId
, metaNamespaceContext :: Maybe Metadata
, metaNamespaceName :: !Text
, metaNamespaceLine :: !Int32
}
| MetaDWCompileUnit { metaValueUniqueId :: UniqueId
, metaCompileUnitLanguage :: !DW_LANG
, metaCompileUnitSourceFile :: !Text
, metaCompileUnitCompileDir :: !Text
, metaCompileUnitProducer :: !Text
, metaCompileUnitIsMain :: !Bool
-- ^ This field is always False in LLVM >= 3.3
, metaCompileUnitIsOpt :: !Bool
, metaCompileUnitFlags :: !Text
, metaCompileUnitVersion :: !Int32
, metaCompileUnitEnumTypes :: [Maybe Metadata]
, metaCompileUnitRetainedTypes :: [Maybe Metadata]
, metaCompileUnitSubprograms :: [Maybe Metadata]
, metaCompileUnitGlobalVariables :: [Maybe Metadata]
}
| MetaDWFile { metaValueUniqueId :: UniqueId
, metaFileSourceFile :: !Text
, metaFileSourceDir :: !Text
}
| MetaDWVariable { metaValueUniqueId :: UniqueId
, metaGlobalVarContext :: Maybe Metadata
, metaGlobalVarName :: !Text
, metaGlobalVarDisplayName :: !Text
, metaGlobalVarLinkageName :: !Text
, metaGlobalVarLine :: !Int32
, metaGlobalVarType :: Maybe Metadata
, metaGlobalVarStatic :: !Bool
, metaGlobalVarNotExtern :: !Bool
}
| MetaDWSubprogram { metaValueUniqueId :: UniqueId
, metaSubprogramContext :: Maybe Metadata
, metaSubprogramName :: !Text
, metaSubprogramDisplayName :: !Text
, metaSubprogramLinkageName :: !Text
, metaSubprogramLine :: !Int32
, metaSubprogramType :: Maybe Metadata
, metaSubprogramIsExplicit :: !Bool
, metaSubprogramIsPrototyped :: !Bool
, metaSubprogramStatic :: !Bool
, metaSubprogramNotExtern :: !Bool
, metaSubprogramVirtuality :: !DW_VIRTUALITY
, metaSubprogramVirtIndex :: !Int32
, metaSubprogramBaseType :: Maybe Metadata
, metaSubprogramArtificial :: !Bool
, metaSubprogramOptimized :: !Bool
}
| MetaDWBaseType { metaValueUniqueId :: UniqueId
, metaBaseTypeContext :: Maybe Metadata
, metaBaseTypeName :: !Text
, metaBaseTypeFilename :: !Text
, metaBaseTypeDirectory :: !Text
, metaBaseTypeLine :: !Int32
, metaBaseTypeSize :: !Int64
, metaBaseTypeAlign :: !Int64
, metaBaseTypeOffset :: !Int64
, metaBaseTypeFlags :: !Int32
, metaBaseTypeEncoding :: !DW_ATE
}
| MetaDWDerivedType { metaValueUniqueId :: UniqueId
, metaDerivedTypeTag :: !DW_TAG
, metaDerivedTypeContext :: Maybe Metadata
, metaDerivedTypeName :: !Text
, metaDerivedTypeFilename :: !Text
, metaDerivedTypeDirectory :: !Text
, metaDerivedTypeLine :: !Int32
, metaDerivedTypeSize :: !Int64
, metaDerivedTypeAlign :: !Int64
, metaDerivedTypeOffset :: !Int64
, metaDerivedTypeIsArtificial :: !Bool
, metaDerivedTypeIsVirtual :: !Bool
, metaDerivedTypeIsForward :: !Bool
, metaDerivedTypeIsPrivate :: !Bool
, metaDerivedTypeIsProtected :: !Bool
, metaDerivedTypeParent :: Maybe Metadata
}
| MetaDWCompositeType { metaValueUniqueId :: UniqueId
, metaCompositeTypeTag :: !DW_TAG
, metaCompositeTypeContext :: Maybe Metadata
, metaCompositeTypeName :: !Text
, metaCompositeTypeFilename :: !Text
, metaCompositeTypeDirectory :: !Text
, metaCompositeTypeLine :: !Int32
, metaCompositeTypeSize :: !Int64
, metaCompositeTypeAlign :: !Int64
, metaCompositeTypeOffset :: !Int64
, metaCompositeTypeFlags :: !Int32
, metaCompositeTypeParent :: Maybe Metadata
, metaCompositeTypeMembers :: Maybe Metadata
, metaCompositeTypeRuntime :: !Int32
, metaCompositeTypeContainer :: Maybe Metadata
, metaCompositeTypeTemplateParams :: Maybe Metadata
, metaCompositeTypeIsArtificial :: !Bool
, metaCompositeTypeIsVirtual :: !Bool
, metaCompositeTypeIsForward :: !Bool
, metaCompositeTypeIsProtected :: !Bool
, metaCompositeTypeIsPrivate :: !Bool
, metaCompositeTypeIsByRefStruct :: !Bool
}
| MetaDWSubrange { metaValueUniqueId :: UniqueId
, metaSubrangeLow :: !Int64
, metaSubrangeHigh :: !Int64
}
| MetaDWEnumerator { metaValueUniqueId :: UniqueId
, metaEnumeratorName :: !Text
, metaEnumeratorValue :: !Int64
}
| MetaDWLocal { metaValueUniqueId :: UniqueId
, metaLocalTag :: !DW_TAG
, metaLocalContext :: Maybe Metadata
, metaLocalName :: !Text
, metaLocalLine :: !Int32
, metaLocalArgNo :: !Int32
, metaLocalType :: Maybe Metadata
, metaLocalIsArtificial :: !Bool
, metaLocalIsBlockByRefVar :: !Bool
, metaLocalAddrElements :: [Int64]
}
| MetaDWTemplateTypeParameter { metaValueUniqueId :: UniqueId
, metaTemplateTypeParameterContext :: Maybe Metadata
, metaTemplateTypeParameterType :: Maybe Metadata
, metaTemplateTypeParameterLine :: !Int32
, metaTemplateTypeParameterCol :: !Int32
, metaTemplateTypeParameterName :: !Text
}
| MetaDWTemplateValueParameter { metaValueUniqueId :: UniqueId
, metaTemplateValueParameterContext :: Maybe Metadata
, metaTemplateValueParameterType :: Maybe Metadata
, metaTemplateValueParameterLine :: !Int32
, metaTemplateValueParameterCol :: !Int32
, metaTemplateValueParameterValueInt :: !Int64
, metaTemplateValueParameterValueRef :: Maybe Value
, metaTemplateValueParameterName :: !Text
}
| MetadataUnknown { metaValueUniqueId :: UniqueId
, metaUnknownValue :: !Text
}
| MetadataList { metaValueUniqueId :: UniqueId
, metaListElements :: [Maybe Metadata]
}
-- | The type of the unique identifiers that let us to work with
-- 'Value's and 'Metadata`, despite the cycles in the object graph.
-- These ids are typically used as hash keys and give objects of these
-- types identity.
type UniqueId = Int
instance Eq Metadata where
mv1 == mv2 = metaValueUniqueId mv1 == metaValueUniqueId mv2
instance Ord Metadata where
compare = comparing metaValueUniqueId
instance Hashable Metadata where
hashWithSalt s = hashWithSalt s . metaValueUniqueId
-- | A wrapper around 'ValueT' values that tracks the 'Type', name,
-- and attached metadata. valueName is mostly informational at this
-- point. All references will be resolved as part of the graph, but
-- the name will be useful for visualization purposes and
-- serialization.
-- data Value = forall a . IsValue a => Value a
-- Functions have parameters if they are not external
data Value = FunctionC Function
| ArgumentC Argument
| BasicBlockC BasicBlock
| GlobalVariableC GlobalVariable
| GlobalAliasC GlobalAlias
| ExternalValueC ExternalValue
| ExternalFunctionC ExternalFunction
| InstructionC Instruction
| ConstantC Constant
class IsValue a where
valueType :: a -> Type
valueName :: a -> Maybe Identifier
valueMetadata :: a -> [Metadata]
valueContent :: a -> Value
valueUniqueId :: a -> UniqueId
instance IsValue Value where
valueType a =
case a of
FunctionC f -> functionType f
ArgumentC arg -> argumentType arg
BasicBlockC _ -> TypeLabel
GlobalVariableC g -> globalVariableType g
GlobalAliasC g -> valueType g
ExternalValueC e -> externalValueType e
ExternalFunctionC e -> externalFunctionType e
InstructionC i -> instructionType i
ConstantC c -> constantType c
valueName a =
case a of
FunctionC f -> valueName f
ArgumentC arg -> valueName arg
BasicBlockC b -> valueName b
GlobalVariableC g -> valueName g
GlobalAliasC g -> valueName g
ExternalValueC e -> valueName e
ExternalFunctionC e -> valueName e
InstructionC i -> valueName i
ConstantC _ -> Nothing
valueMetadata a =
case a of
FunctionC f -> functionMetadata f
ArgumentC arg -> argumentMetadata arg
BasicBlockC b -> basicBlockMetadata b
GlobalVariableC g -> globalVariableMetadata g
GlobalAliasC g -> valueMetadata g
ExternalValueC e -> externalValueMetadata e
ExternalFunctionC e -> externalFunctionMetadata e
InstructionC i -> instructionMetadata i
ConstantC _ -> []
valueContent = id
valueUniqueId a =
case a of
FunctionC f -> functionUniqueId f
ArgumentC arg -> argumentUniqueId arg
BasicBlockC b -> basicBlockUniqueId b
GlobalVariableC g -> globalVariableUniqueId g
GlobalAliasC g -> valueUniqueId g
ExternalValueC e -> externalValueUniqueId e
ExternalFunctionC e -> externalFunctionUniqueId e
InstructionC i -> instructionUniqueId i
ConstantC c -> constantUniqueId c
toValue :: (IsValue a) => a -> Value
toValue = valueContent
data FailedCast = FailedCast String
deriving (Typeable, Show)
instance Exception FailedCast
-- | Safely convert a 'Value' to a concrete type (like Argument or
-- Instruction). This is most useful in pure Monads that handle
-- failure, like Maybe, MaybeT, and Either. If the requested
-- conversion is not possible, the normal failure semantics are
-- provided. Example:
--
-- >
class FromValue a where
fromValue :: (Failure FailedCast f) => Value -> f a
instance FromValue Constant where
fromValue v =
case valueContent' v of
ConstantC c -> return c
_ -> failure $! FailedCast "Constant"
instance FromValue GlobalAlias where
fromValue v =
case valueContent' v of
GlobalAliasC g -> return g
_ -> failure $! FailedCast "GlobalAlias"
instance FromValue ExternalValue where
fromValue v =
case valueContent' v of
ExternalValueC e -> return e
_ -> failure $! FailedCast "ExternalValue"
instance FromValue GlobalVariable where
fromValue v =
case valueContent' v of
GlobalVariableC g -> return g
_ -> failure $! FailedCast "GlobalVariable"
instance FromValue Argument where
fromValue v =
case valueContent' v of
ArgumentC a -> return a
_ -> failure $! FailedCast "Argument"
instance FromValue Function where
fromValue v =
case valueContent' v of
FunctionC f -> return f
_ -> failure $! FailedCast "Function"
instance FromValue Instruction where
fromValue v =
case valueContent' v of
InstructionC i -> return i
_ -> failure $! FailedCast "Instruction"
instance FromValue ExternalFunction where
fromValue v =
case valueContent' v of
ExternalFunctionC f -> return f
_ -> failure $! FailedCast "ExternalFunction"
instance FromValue BasicBlock where
fromValue v =
case valueContent' v of
BasicBlockC b -> return b
_ -> failure $! FailedCast "BasicBlock"
instance Eq Value where
(==) = valueEq
{-# INLINE valueEq #-}
valueEq :: Value -> Value -> Bool
valueEq v1 v2 =
valueUniqueId v1 == valueUniqueId v2
instance Ord Value where
v1 `compare` v2 = comparing valueUniqueId v1 v2
instance Hashable Value where
hashWithSalt s = hashWithSalt s . valueUniqueId
class HasFunction a where
getFunction :: a -> Function
instance HasFunction Function where
getFunction = id
data Function = Function { functionType :: Type
, functionName :: !Identifier
, functionMetadata :: [Metadata]
, functionUniqueId :: UniqueId
, functionParameters :: [Argument]
, functionBodyVector :: Vector BasicBlock
, functionLinkage :: !LinkageType
, functionVisibility :: !VisibilityStyle
, functionCC :: !CallingConvention
, functionRetAttrs :: [ParamAttribute]
, functionAttrs :: [FunctionAttribute]
, functionSection :: !(Maybe Text)
, functionAlign :: !Int64
, functionGCName :: !(Maybe Text)
}
functionIsVararg :: Function -> Bool
functionIsVararg Function { functionType = TypeFunction _ _ isva } = isva
functionIsVararg v = error $ printf "Value %d is not a function" (valueUniqueId v)
{-# INLINABLE functionReturnType #-}
functionReturnType :: Function -> Type
functionReturnType f = rt where
TypeFunction rt _ _ = functionType f
{-# INLINABLE functionBody #-}
functionBody :: Function -> [BasicBlock]
functionBody = V.toList . functionBodyVector
{-# INLINABLE functionInstructions #-}
functionInstructions :: Function -> [Instruction]
functionInstructions = concatMap basicBlockInstructions . functionBody
functionEntryInstruction :: Function -> Instruction
functionEntryInstruction f = e1
where
(bb1:_) = functionBody f
(e1:_) = basicBlockInstructions bb1
-- | Get the ret instruction for a Function
functionExitInstruction :: Function -> Maybe Instruction
functionExitInstruction f =
case filter isRetInst is of
[] -> Nothing -- error $ "Function has no ret instruction: " ++ show (functionName f)
[ri] -> Just ri
_ -> Nothing -- error $ "Function has multiple ret instructions: " ++ show (functionName f)
where
is = concatMap basicBlockInstructions (functionBody f)
isRetInst RetInst {} = True
isRetInst _ = False
-- | Get all exit instructions for a Function (ret, unreachable, unwind)
functionExitInstructions :: Function -> [Instruction]
functionExitInstructions f = filter isRetInst is
where
is = concatMap basicBlockInstructions (functionBody f)
isRetInst RetInst {} = True
isRetInst UnreachableInst {} = True
isRetInst _ = False
functionExitBlock :: Function -> BasicBlock
functionExitBlock f =
case filter terminatorIsExitInst bbs of
[] -> error $ "Function has no ret instruction: " ++ show (functionName f)
[rb] -> rb
_ -> error $ "Function has multiple ret instructions: " ++ show (functionName f)
where
bbs = functionBody f
terminatorIsExitInst bb =
case basicBlockTerminatorInstruction bb of
RetInst {} -> True
_ -> False
functionExitBlocks :: Function -> [BasicBlock]
functionExitBlocks f =
case filter terminatorIsExitInst bbs of
[] -> error $ "Function has no ret instruction: " ++ show (functionName f)
rbs -> rbs
where
bbs = functionBody f
terminatorIsExitInst bb =
case basicBlockTerminatorInstruction bb of
RetInst {} -> True
UnreachableInst {} -> True
ResumeInst {} -> True
_ -> False
instance IsValue Function where
valueType = functionType
valueName = Just . functionName
valueMetadata = functionMetadata
valueContent = FunctionC
valueUniqueId = functionUniqueId
instance Eq Function where
f1 == f2 = functionUniqueId f1 == functionUniqueId f2
instance Hashable Function where
hashWithSalt s = hashWithSalt s . functionUniqueId
instance Ord Function where
f1 `compare` f2 = comparing functionUniqueId f1 f2
data Argument = Argument { argumentType :: Type
, argumentName :: !Identifier
, argumentMetadata :: [Metadata]
, argumentUniqueId :: UniqueId
, argumentParamAttrs :: [ParamAttribute]
, argumentFunction :: Function
}
instance IsValue Argument where
valueType = argumentType
valueName = Just . argumentName
valueMetadata = argumentMetadata
valueContent = ArgumentC
valueUniqueId = argumentUniqueId
instance Hashable Argument where
hashWithSalt s = hashWithSalt s . argumentUniqueId
instance Eq Argument where
a1 == a2 = argumentUniqueId a1 == argumentUniqueId a2
instance Ord Argument where
a1 `compare` a2 = comparing argumentUniqueId a1 a2
-- | Find the zero-based index into the argument list of the 'Function'
-- containing this 'Argument'.
argumentIndex :: Argument -> Int
argumentIndex a = ix
where
f = argumentFunction a
Just ix = elemIndex a (functionParameters f)
data BasicBlock = BasicBlock { basicBlockName :: !Identifier
, basicBlockMetadata :: [Metadata]
, basicBlockUniqueId :: UniqueId
, basicBlockInstructionVector :: Vector Instruction
, basicBlockFunction :: Function
}
{-# INLINABLE basicBlockInstructions #-}
basicBlockInstructions :: BasicBlock -> [Instruction]
basicBlockInstructions = V.toList . basicBlockInstructionVector
{-# INLINABLE basicBlockTerminatorInstruction #-}
basicBlockTerminatorInstruction :: BasicBlock -> Instruction
basicBlockTerminatorInstruction = V.last . basicBlockInstructionVector
{-# INLINABLE firstNonPhiInstruction #-}
-- | Get the first instruction in a basic block that is not a Phi
-- node. This is total because basic blocks cannot be empty and must
-- end in a terminator instruction (Phi nodes are not terminators).
firstNonPhiInstruction :: BasicBlock -> Instruction
firstNonPhiInstruction bb = i
where
i : _ = dropWhile instructionIsPhiNode (basicBlockInstructions bb)
{-# INLINABLE instructionIsPhiNode #-}
-- | Predicate to test an instruction to see if it is a phi node
instructionIsPhiNode :: Instruction -> Bool
instructionIsPhiNode v = case v of
PhiNode {} -> True
_ -> False
{-# INLINABLE isFirstNonPhiInstruction #-}
-- | Determine if @i@ is the first non-phi instruction in its block.
isFirstNonPhiInstruction :: Instruction -> Bool
isFirstNonPhiInstruction i = i == firstNonPhiInstruction bb
where
Just bb = instructionBasicBlock i
{-# INLINABLE basicBlockSplitPhiNodes #-}
-- | Split a block's instructions into phi nodes and the rest
basicBlockSplitPhiNodes :: BasicBlock -> ([Instruction], [Instruction])
basicBlockSplitPhiNodes = span instructionIsPhiNode . basicBlockInstructions
instance IsValue BasicBlock where
valueType _ = TypeLabel
valueName = Just . basicBlockName
valueMetadata = basicBlockMetadata
valueContent = BasicBlockC
valueUniqueId = basicBlockUniqueId
instance Hashable BasicBlock where
hashWithSalt s = hashWithSalt s . basicBlockUniqueId
instance Eq BasicBlock where
f1 == f2 = basicBlockUniqueId f1 == basicBlockUniqueId f2
instance Ord BasicBlock where
b1 `compare` b2 = comparing basicBlockUniqueId b1 b2
data GlobalVariable = GlobalVariable { globalVariableType :: Type
, globalVariableName :: !Identifier
, globalVariableMetadata :: [Metadata]
, globalVariableUniqueId :: UniqueId
, globalVariableLinkage :: !LinkageType
, globalVariableVisibility :: !VisibilityStyle
, globalVariableInitializer :: Maybe Value
, globalVariableAlignment :: !Int64
, globalVariableSection :: !(Maybe Text)
, globalVariableIsThreadLocal :: !Bool
, globalVariableIsConstant :: !Bool
}
instance IsValue GlobalVariable where
valueType = globalVariableType
valueName = Just . globalVariableName
valueMetadata = globalVariableMetadata
valueContent = GlobalVariableC
valueUniqueId = globalVariableUniqueId
instance Eq GlobalVariable where
f1 == f2 = globalVariableUniqueId f1 == globalVariableUniqueId f2
instance Hashable GlobalVariable where
hashWithSalt s = hashWithSalt s . globalVariableUniqueId
instance Ord GlobalVariable where
g1 `compare` g2 = comparing globalVariableUniqueId g1 g2
data GlobalAlias = GlobalAlias { globalAliasTarget :: Value
, globalAliasLinkage :: !LinkageType
, globalAliasName :: !Identifier
, globalAliasVisibility :: !VisibilityStyle
, globalAliasMetadata :: [Metadata]
, globalAliasUniqueId :: UniqueId
}
instance IsValue GlobalAlias where
valueType = valueType . globalAliasTarget
valueName = Just . globalAliasName
valueMetadata = globalAliasMetadata
valueContent = GlobalAliasC
valueUniqueId = globalAliasUniqueId
instance Eq GlobalAlias where
f1 == f2 = globalAliasUniqueId f1 == globalAliasUniqueId f2
instance Hashable GlobalAlias where
hashWithSalt s = hashWithSalt s . globalAliasUniqueId
instance Ord GlobalAlias where
g1 `compare` g2 = comparing globalAliasUniqueId g1 g2
data ExternalValue = ExternalValue { externalValueType :: Type
, externalValueName :: !Identifier
, externalValueMetadata :: [Metadata]
, externalValueUniqueId :: UniqueId
}
instance IsValue ExternalValue where
valueType = externalValueType
valueName = Just . externalValueName
valueMetadata = externalValueMetadata
valueContent = ExternalValueC
valueUniqueId = externalValueUniqueId
instance Eq ExternalValue where
f1 == f2 = externalValueUniqueId f1 == externalValueUniqueId f2
instance Hashable ExternalValue where
hashWithSalt s = hashWithSalt s . externalValueUniqueId
instance Ord ExternalValue where
e1 `compare` e2 = comparing externalValueUniqueId e1 e2
data ExternalFunction = ExternalFunction { externalFunctionType :: Type
, externalFunctionName :: !Identifier
, externalFunctionMetadata :: [Metadata]
, externalFunctionUniqueId :: UniqueId
, externalFunctionAttrs :: [FunctionAttribute]
}
instance Show ExternalFunction where
show = show . externalFunctionName
instance IsValue ExternalFunction where
valueType = externalFunctionType
valueName = Just . externalFunctionName
valueMetadata = externalFunctionMetadata
valueContent = ExternalFunctionC
valueUniqueId = externalFunctionUniqueId
instance Eq ExternalFunction where
f1 == f2 = externalFunctionUniqueId f1 == externalFunctionUniqueId f2
instance Hashable ExternalFunction where
hashWithSalt s = hashWithSalt s . externalFunctionUniqueId
instance Ord ExternalFunction where
f1 `compare` f2 = comparing externalFunctionUniqueId f1 f2
externalFunctionParameterTypes :: ExternalFunction -> [Type]
externalFunctionParameterTypes ef = ts
where
TypeFunction _ ts _ = externalFunctionType ef
externalIsIntrinsic :: ExternalFunction -> Bool
externalIsIntrinsic =
isPrefixOf "llvm." . identifierContent . externalFunctionName
{-# INLINABLE instructionIsTerminator #-}
-- | Determine if an instruction is a Terminator instruction (i.e.,
-- ends a BasicBlock)
instructionIsTerminator :: Instruction -> Bool
instructionIsTerminator RetInst {} = True
instructionIsTerminator UnconditionalBranchInst {} = True
instructionIsTerminator BranchInst {} = True
instructionIsTerminator SwitchInst {} = True
instructionIsTerminator IndirectBranchInst {} = True
instructionIsTerminator ResumeInst {} = True
instructionIsTerminator UnreachableInst {} = True
instructionIsTerminator InvokeInst {} = True
instructionIsTerminator _ = False
instructionIsEntry :: Instruction -> Bool
instructionIsEntry i = i == ei
where
ei = V.unsafeHead $ basicBlockInstructionVector bb
Just bb = instructionBasicBlock i
instructionFunction :: Instruction -> Maybe Function
instructionFunction i = do
bb <- instructionBasicBlock i
return $ basicBlockFunction bb
instructionType :: Instruction -> Type
instructionType i =
case i of
RetInst {} -> TypeVoid
UnconditionalBranchInst {} -> TypeVoid
BranchInst {} -> TypeVoid
SwitchInst {} -> TypeVoid
IndirectBranchInst {} -> TypeVoid
ResumeInst {} -> TypeVoid
UnreachableInst {} -> TypeVoid
StoreInst {} -> TypeVoid
FenceInst {} -> TypeVoid
AtomicCmpXchgInst {} -> TypeVoid
AtomicRMWInst {} -> TypeVoid
_ -> _instructionType i
instructionName :: Instruction -> Maybe Identifier
instructionName i =
case i of
RetInst {} -> Nothing
UnconditionalBranchInst {} -> Nothing
BranchInst {} -> Nothing
SwitchInst {} -> Nothing
IndirectBranchInst {} -> Nothing
ResumeInst {} -> Nothing
UnreachableInst {} -> Nothing
StoreInst {} -> Nothing
FenceInst {} -> Nothing
AtomicCmpXchgInst {} -> Nothing
AtomicRMWInst {} -> Nothing
_ -> _instructionName i
data Instruction = RetInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, retInstValue :: Maybe Value
}
| UnconditionalBranchInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, unconditionalBranchTarget :: BasicBlock
}
| BranchInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, branchCondition :: Value
, branchTrueTarget :: BasicBlock
, branchFalseTarget :: BasicBlock
}
| SwitchInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, switchValue :: Value
, switchDefaultTarget :: BasicBlock
, switchCases :: [(Value, BasicBlock)]
}
| IndirectBranchInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, indirectBranchAddress :: Value
, indirectBranchTargets :: [BasicBlock]
}
-- ^ The target must be derived from a blockaddress constant
-- The list is a list of possible target destinations
| ResumeInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, resumeException :: Value
}
| UnreachableInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
}
| ExtractElementInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, extractElementVector :: Value
, extractElementIndex :: Value
}
| InsertElementInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, insertElementVector :: Value
, insertElementValue :: Value
, insertElementIndex :: Value
}
| ShuffleVectorInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, shuffleVectorV1 :: Value
, shuffleVectorV2 :: Value
, shuffleVectorMask :: Value
}
| ExtractValueInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, extractValueAggregate :: Value
, extractValueIndices :: [Int]
}
| InsertValueInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, insertValueAggregate :: Value
, insertValueValue :: Value
, insertValueIndices :: [Int]
}
| AllocaInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, allocaNumElements :: Value
, allocaAlign :: !Int64
}
| LoadInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, loadIsVolatile :: !Bool
, loadAddress :: Value
, loadAlignment :: !Int64
}
| StoreInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, storeIsVolatile :: !Bool
, storeValue :: Value
, storeAddress :: Value
, storeAlignment :: !Int64
, storeAddressSpace :: !Int
}
| FenceInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, fenceOrdering :: !AtomicOrdering
, fenceScope :: !SynchronizationScope
}
| AtomicCmpXchgInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, atomicCmpXchgOrdering :: !AtomicOrdering
, atomicCmpXchgScope :: !SynchronizationScope
, atomicCmpXchgIsVolatile :: !Bool
, atomicCmpXchgAddressSpace :: !Int
, atomicCmpXchgPointer :: Value
, atomicCmpXchgComparison :: Value
, atomicCmpXchgNewValue :: Value
}
| AtomicRMWInst { instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, atomicRMWOrdering :: !AtomicOrdering
, atomicRMWScope :: !SynchronizationScope
, atomicRMWOperation :: !AtomicOperation
, atomicRMWIsVolatile :: !Bool
, atomicRMWPointer :: Value
, atomicRMWValue :: Value
, atomicRMWAddressSpace :: !Int
}
| AddInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryArithFlags :: !ArithFlags
, binaryLhs :: Value
, binaryRhs :: Value
}
| SubInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryArithFlags :: !ArithFlags
, binaryLhs :: Value
, binaryRhs :: Value
}
| MulInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryArithFlags :: !ArithFlags
, binaryLhs :: Value
, binaryRhs :: Value
}
| DivInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryLhs :: Value
, binaryRhs :: Value
}
| RemInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryLhs :: Value
, binaryRhs :: Value
}
| ShlInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryLhs :: Value
, binaryRhs :: Value
}
| LshrInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryLhs :: Value
, binaryRhs :: Value
}
| AshrInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryLhs :: Value
, binaryRhs :: Value
}
| AndInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryLhs :: Value
, binaryRhs :: Value
}
| OrInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryLhs :: Value
, binaryRhs :: Value
}
| XorInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, binaryLhs :: Value
, binaryRhs :: Value
}
| TruncInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| ZExtInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| SExtInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| FPTruncInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| FPExtInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| FPToSIInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| FPToUIInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| SIToFPInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| UIToFPInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| PtrToIntInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| IntToPtrInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| BitcastInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, castedValue :: Value
}
| ICmpInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, cmpPredicate :: !CmpPredicate
, cmpV1 :: Value
, cmpV2 :: Value
}
| FCmpInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, cmpPredicate :: !CmpPredicate
, cmpV1 :: Value
, cmpV2 :: Value
}
| SelectInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, selectCondition :: Value
, selectTrueValue :: Value
, selectFalseValue :: Value
}
| CallInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, callIsTail :: !Bool
, callConvention :: !CallingConvention
, callParamAttrs :: [ParamAttribute]
, callFunction :: Value
, callArguments :: [(Value, [ParamAttribute])]
, callAttrs :: [FunctionAttribute]
, callHasSRet :: !Bool
}
| GetElementPtrInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, getElementPtrInBounds :: !Bool
, getElementPtrValue :: Value
, getElementPtrIndices :: [Value]
, getElementPtrAddrSpace :: !Int
}
| InvokeInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, invokeConvention :: !CallingConvention
, invokeParamAttrs :: [ParamAttribute]
, invokeFunction :: Value
, invokeArguments :: [(Value, [ParamAttribute])]
, invokeAttrs :: [FunctionAttribute]
, invokeNormalLabel :: BasicBlock
, invokeUnwindLabel :: BasicBlock
, invokeHasSRet :: !Bool
}
| VaArgInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, vaArgValue :: Value
}
| LandingPadInst { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, landingPadPersonality :: Value
, landingPadIsCleanup :: !Bool
, landingPadClauses :: [(Value, LandingPadClause)]
}
| PhiNode { _instructionType :: Type
, _instructionName :: !(Maybe Identifier)
, instructionMetadata :: [Metadata]
, instructionUniqueId :: UniqueId
, instructionBasicBlock :: Maybe BasicBlock
, phiIncomingValues :: [(Value, Value)]
}
instance IsValue Instruction where
valueType = instructionType
valueName = instructionName
valueMetadata = instructionMetadata
valueContent = InstructionC
valueUniqueId = instructionUniqueId
instance Eq Instruction where
i1 == i2 = instructionUniqueId i1 == instructionUniqueId i2
instance Hashable Instruction where
hashWithSalt s = hashWithSalt s . instructionUniqueId
instance Ord Instruction where
i1 `compare` i2 = comparing instructionUniqueId i1 i2
-- | Return all of the operands for an instruction. Note that "special"
-- operands (like the 'Type' in a vararg inst) cannot be returned. For
-- Phi nodes, only the incoming values (not their sources) are returned.
instructionOperands :: Instruction -> [Value]
instructionOperands i =
case i of
RetInst { retInstValue = rv } -> maybe [] (:[]) rv
UnconditionalBranchInst { } -> []
BranchInst { branchCondition = c } -> [c]
SwitchInst { switchValue = v } -> [v]
IndirectBranchInst { indirectBranchAddress = a } -> [a]
ResumeInst { resumeException = e } -> [e]
UnreachableInst { } -> []
ExtractElementInst { extractElementVector = v
, extractElementIndex = ix
} -> [v, ix]
InsertElementInst { insertElementVector = v
, insertElementIndex = ix
, insertElementValue = val
} -> [v, ix, val]
ShuffleVectorInst { shuffleVectorV1 = v1
, shuffleVectorV2 = v2
, shuffleVectorMask = m
} -> [v1, v2, m]
ExtractValueInst { extractValueAggregate = a } -> [a]
InsertValueInst { insertValueAggregate = a
, insertValueValue = v
} -> [a, v]
AllocaInst { allocaNumElements = n } -> [n]
LoadInst { loadAddress = la } -> [la]
StoreInst { storeValue = sv, storeAddress = sa } -> [sv, sa]
FenceInst { } -> []
AtomicCmpXchgInst { atomicCmpXchgPointer = p
, atomicCmpXchgNewValue = nv
, atomicCmpXchgComparison = c
} -> [p, nv, c]
AtomicRMWInst { atomicRMWPointer = p
, atomicRMWValue = v
} -> [p, v]
AddInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
SubInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
MulInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
DivInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
RemInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
ShlInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
LshrInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
AshrInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
AndInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
OrInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
XorInst { binaryLhs = lhs
, binaryRhs = rhs
} -> [lhs, rhs]
TruncInst { castedValue = cv } -> [cv]
ZExtInst { castedValue = cv } -> [cv]
SExtInst { castedValue = cv } -> [cv]
FPTruncInst { castedValue = cv } -> [cv]
FPExtInst { castedValue = cv } -> [cv]
FPToSIInst { castedValue = cv } -> [cv]
FPToUIInst { castedValue = cv } -> [cv]
SIToFPInst { castedValue = cv } -> [cv]
UIToFPInst { castedValue = cv } -> [cv]
PtrToIntInst { castedValue = cv } -> [cv]
IntToPtrInst { castedValue = cv } -> [cv]
BitcastInst { castedValue = cv } -> [cv]
ICmpInst { cmpV1 = v1, cmpV2 = v2 } -> [v1, v2]
FCmpInst { cmpV1 = v1, cmpV2 = v2 } -> [v1, v2]
SelectInst { selectCondition = c
, selectTrueValue = t
, selectFalseValue = f
} -> [c, t, f]
CallInst { callFunction = cf
, callArguments = (map fst -> args)
} -> cf : args
GetElementPtrInst { getElementPtrValue = v
, getElementPtrIndices = ixs
} -> v : ixs
InvokeInst { invokeFunction = cf
, invokeArguments = (map fst -> args)
} -> cf : args
VaArgInst { vaArgValue = v } -> [v]
LandingPadInst { landingPadPersonality = p
, landingPadClauses = (map fst -> clauses)
} -> p : clauses
PhiNode { phiIncomingValues = (map fst -> ivs) } -> ivs
data Constant = UndefValue { constantType :: Type
, constantUniqueId :: UniqueId
}
| ConstantAggregateZero { constantType :: Type
, constantUniqueId :: UniqueId
}
| ConstantPointerNull { constantType :: Type
, constantUniqueId :: UniqueId
}
| BlockAddress { constantType :: Type
, constantUniqueId :: UniqueId
, blockAddressFunction :: Function
, blockAddressBlock :: BasicBlock
}
| ConstantArray { constantType :: Type
, constantUniqueId :: UniqueId
, constantArrayValues :: [Value]
}
| ConstantFP { constantType :: Type
, constantUniqueId :: UniqueId
, constantFPValue :: !Double
}
| ConstantInt { constantType :: Type
, constantUniqueId :: UniqueId
, constantIntValue :: !Integer
}
| ConstantString { constantType :: Type
, constantUniqueId :: UniqueId
, constantStringValue :: !Text
}
| ConstantStruct { constantType :: Type
, constantUniqueId :: UniqueId
, constantStructValues :: [Value]
}
| ConstantVector { constantType :: Type
, constantUniqueId :: UniqueId
, constantVectorValues :: [Value]
}
| ConstantValue { constantType :: Type
, constantUniqueId :: UniqueId
, constantInstruction :: Instruction
}
| InlineAsm { constantType :: Type
, constantUniqueId :: UniqueId
, inlineAsmString :: !Text
, inlineAsmConstraints :: !Text
}
instance IsValue Constant where
valueType = constantType
valueName _ = Nothing
valueMetadata _ = []
valueContent = ConstantC
valueUniqueId = constantUniqueId
instance Eq Constant where
c1 == c2 = constantUniqueId c1 == constantUniqueId c2
instance Hashable Constant where
hashWithSalt s = hashWithSalt s . constantUniqueId
instance Ord Constant where
c1 `compare` c2 = comparing constantUniqueId c1 c2
{-# INLINABLE valueContent' #-}
-- | A version of @valueContent@ that ignores (peeks through)
-- bitcasts. This is most useful in view patterns.
valueContent' :: IsValue a => a -> Value
valueContent' v =
case valueContent v of
InstructionC BitcastInst { castedValue = cv } -> valueContent' cv
ConstantC ConstantValue { constantInstruction = BitcastInst { castedValue = cv } } -> valueContent' cv
_ -> valueContent v
{-# INLINABLE stripBitcasts #-}
-- | Strip all wrapper bitcasts from a Value
stripBitcasts :: IsValue a => a -> Value
stripBitcasts v =
case valueContent v of
InstructionC BitcastInst { castedValue = cv } -> stripBitcasts cv
ConstantC ConstantValue { constantInstruction = BitcastInst { castedValue = cv } } -> stripBitcasts cv
_ -> valueContent v
| travitch/llvm-base-types | src/Data/LLVM/Types/Referential.hs | bsd-3-clause | 68,236 | 0 | 14 | 26,881 | 12,337 | 6,899 | 5,438 | 1,633 | 50 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
module Distribution.Client.GlobalFlags (
GlobalFlags(..)
, defaultGlobalFlags
, RepoContext(..)
, withRepoContext
) where
import Distribution.Client.Types
( Repo(..), RemoteRepo(..) )
import Distribution.Compat.Semigroup
import Distribution.Simple.Setup
( Flag(..), fromFlag, fromFlagOrDefault, flagToMaybe )
import Distribution.Utils.NubList
( NubList, fromNubList )
import Distribution.Client.HttpUtils
( HttpTransport, configureTransport )
import Distribution.Verbosity
( Verbosity )
import Distribution.Simple.Utils
( info )
import Control.Concurrent
( MVar, newMVar, modifyMVar )
import Control.Exception
( throwIO )
import Control.Monad
( when )
import System.FilePath
( (</>) )
import Network.URI
( uriScheme, uriPath )
import Data.Map
( Map )
import qualified Data.Map as Map
import GHC.Generics ( Generic )
import qualified Hackage.Security.Client as Sec
import qualified Hackage.Security.Util.Path as Sec
import qualified Hackage.Security.Util.Pretty as Sec
import qualified Hackage.Security.Client.Repository.Cache as Sec
import qualified Hackage.Security.Client.Repository.Local as Sec.Local
import qualified Hackage.Security.Client.Repository.Remote as Sec.Remote
import qualified Distribution.Client.Security.HTTP as Sec.HTTP
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------
-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
globalVersion :: Flag Bool,
globalNumericVersion :: Flag Bool,
globalConfigFile :: Flag FilePath,
globalSandboxConfigFile :: Flag FilePath,
globalConstraintsFile :: Flag FilePath,
globalRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers.
globalCacheDir :: Flag FilePath,
globalLocalRepos :: NubList FilePath,
globalLogsDir :: Flag FilePath,
globalWorldFile :: Flag FilePath,
globalRequireSandbox :: Flag Bool,
globalIgnoreSandbox :: Flag Bool,
globalIgnoreExpiry :: Flag Bool, -- ^ Ignore security expiry dates
globalHttpTransport :: Flag String
} deriving Generic
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags = GlobalFlags {
globalVersion = Flag False,
globalNumericVersion = Flag False,
globalConfigFile = mempty,
globalSandboxConfigFile = mempty,
globalConstraintsFile = mempty,
globalRemoteRepos = mempty,
globalCacheDir = mempty,
globalLocalRepos = mempty,
globalLogsDir = mempty,
globalWorldFile = mempty,
globalRequireSandbox = Flag False,
globalIgnoreSandbox = Flag False,
globalIgnoreExpiry = Flag False,
globalHttpTransport = mempty
}
instance Monoid GlobalFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup GlobalFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Repo context
-- ------------------------------------------------------------
-- | Access to repositories
data RepoContext = RepoContext {
-- | All user-specified repositories
repoContextRepos :: [Repo]
-- | Get the HTTP transport
--
-- The transport will be initialized on the first call to this function.
--
-- NOTE: It is important that we don't eagerly initialize the transport.
-- Initializing the transport is not free, and especially in contexts where
-- we don't know a-priori whether or not we need the transport (for instance
-- when using cabal in "nix mode") incurring the overhead of transport
-- initialization on _every_ invocation (eg @cabal build@) is undesirable.
, repoContextGetTransport :: IO HttpTransport
-- | Get the (initialized) secure repo
--
-- (the 'Repo' type itself is stateless and must remain so, because it
-- must be serializable)
, repoContextWithSecureRepo :: forall a.
Repo
-> (forall down. Sec.Repository down -> IO a)
-> IO a
-- | Should we ignore expiry times (when checking security)?
, repoContextIgnoreExpiry :: Bool
}
-- | Wrapper around 'Repository', hiding the type argument
data SecureRepo = forall down. SecureRepo (Sec.Repository down)
withRepoContext :: Verbosity -> GlobalFlags -> (RepoContext -> IO a) -> IO a
withRepoContext verbosity globalFlags = \callback -> do
transportRef <- newMVar Nothing
let httpLib = Sec.HTTP.transportAdapter
verbosity
(getTransport transportRef)
initSecureRepos verbosity httpLib secureRemoteRepos $ \secureRepos' ->
callback RepoContext {
repoContextRepos = allRemoteRepos ++ localRepos
, repoContextGetTransport = getTransport transportRef
, repoContextWithSecureRepo = withSecureRepo secureRepos'
, repoContextIgnoreExpiry = fromFlagOrDefault False
(globalIgnoreExpiry globalFlags)
}
where
secureRemoteRepos =
[ (remote, cacheDir)
| RepoSecure remote cacheDir <- allRemoteRepos ]
allRemoteRepos =
[ case remoteRepoSecure remote of
Just True -> RepoSecure remote cacheDir
_otherwise -> RepoRemote remote cacheDir
| remote <- fromNubList $ globalRemoteRepos globalFlags
, let cacheDir = fromFlag (globalCacheDir globalFlags)
</> remoteRepoName remote ]
localRepos =
[ RepoLocal local
| local <- fromNubList $ globalLocalRepos globalFlags ]
getTransport :: MVar (Maybe HttpTransport) -> IO HttpTransport
getTransport transportRef =
modifyMVar transportRef $ \mTransport -> do
transport <- case mTransport of
Just tr -> return tr
Nothing -> configureTransport
verbosity
(flagToMaybe (globalHttpTransport globalFlags))
return (Just transport, transport)
withSecureRepo :: Map Repo SecureRepo
-> Repo
-> (forall down. Sec.Repository down -> IO a)
-> IO a
withSecureRepo secureRepos repo callback =
case Map.lookup repo secureRepos of
Just (SecureRepo secureRepo) -> callback secureRepo
Nothing -> throwIO $ userError "repoContextWithSecureRepo: unknown repo"
-- | Initialize the provided secure repositories
--
-- Assumed invariant: `remoteRepoSecure` should be set for all these repos.
initSecureRepos :: forall a. Verbosity
-> Sec.HTTP.HttpLib
-> [(RemoteRepo, FilePath)]
-> (Map Repo SecureRepo -> IO a)
-> IO a
initSecureRepos verbosity httpLib repos callback = go Map.empty repos
where
go :: Map Repo SecureRepo -> [(RemoteRepo, FilePath)] -> IO a
go !acc [] = callback acc
go !acc ((r,cacheDir):rs) = do
cachePath <- Sec.makeAbsolute $ Sec.fromFilePath cacheDir
initSecureRepo verbosity httpLib r cachePath $ \r' ->
go (Map.insert (RepoSecure r cacheDir) r' acc) rs
-- | Initialize the given secure repo
--
-- The security library has its own concept of a "local" repository, distinct
-- from @cabal-install@'s; these are secure repositories, but live in the local
-- file system. We use the convention that these repositories are identified by
-- URLs of the form @file:/path/to/local/repo@.
initSecureRepo :: Verbosity
-> Sec.HTTP.HttpLib
-> RemoteRepo -- ^ Secure repo ('remoteRepoSecure' assumed)
-> Sec.Path Sec.Absolute -- ^ Cache dir
-> (SecureRepo -> IO a) -- ^ Callback
-> IO a
initSecureRepo verbosity httpLib RemoteRepo{..} cachePath = \callback -> do
withRepo $ \r -> do
requiresBootstrap <- Sec.requiresBootstrap r
when requiresBootstrap $ Sec.uncheckClientErrors $
Sec.bootstrap r
(map Sec.KeyId remoteRepoRootKeys)
(Sec.KeyThreshold (fromIntegral remoteRepoKeyThreshold))
callback $ SecureRepo r
where
-- Initialize local or remote repo depending on the URI
withRepo :: (forall down. Sec.Repository down -> IO a) -> IO a
withRepo callback | uriScheme remoteRepoURI == "file:" = do
dir <- Sec.makeAbsolute $ Sec.fromFilePath (uriPath remoteRepoURI)
Sec.Local.withRepository dir
cache
Sec.hackageRepoLayout
Sec.hackageIndexLayout
logTUF
callback
withRepo callback =
Sec.Remote.withRepository httpLib
[remoteRepoURI]
Sec.Remote.defaultRepoOpts
cache
Sec.hackageRepoLayout
Sec.hackageIndexLayout
logTUF
callback
cache :: Sec.Cache
cache = Sec.Cache {
cacheRoot = cachePath
, cacheLayout = Sec.cabalCacheLayout
}
-- We display any TUF progress only in verbose mode, including any transient
-- verification errors. If verification fails, then the final exception that
-- is thrown will of course be shown.
logTUF :: Sec.LogMessage -> IO ()
logTUF = info verbosity . Sec.pretty
| garetxe/cabal | cabal-install/Distribution/Client/GlobalFlags.hs | bsd-3-clause | 9,892 | 0 | 19 | 2,820 | 1,779 | 990 | 789 | 184 | 4 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-} -- for GHC.DataId
module Language.Haskell.Refact.Utils.Utils
(
-- * Managing the GHC / project environment
getModuleGhc
, getTargetGhc
, parseSourceFileGhc
-- , activateModule
, getModuleDetails
-- * The bits that do the work
, runRefacSession
, applyRefac
, refactDone
, Update(..)
-- , fileNameToModName
, fileNameFromModSummary
, getModuleName
, clientModsAndFiles
, serverModsAndFiles
-- * For testing
, initGhcSession
) where
import Control.Exception
import Control.Monad.State
import Data.List
import Data.Maybe
import Language.Haskell.GHC.ExactPrint
import Language.Haskell.GHC.ExactPrint.Utils
-- import Language.Haskell.GhcMod
import qualified Language.Haskell.GhcMod as GM
import qualified Language.Haskell.GhcMod.Internal as GM
-- import Language.Haskell.GhcMod.Internal hiding (MonadIO,liftIO)
import Language.Haskell.Refact.Utils.GhcModuleGraph
import Language.Haskell.Refact.Utils.GhcVersionSpecific
import Language.Haskell.Refact.Utils.Monad
import Language.Haskell.Refact.Utils.MonadFunctions
import Language.Haskell.Refact.Utils.Types
import Language.Haskell.Refact.Utils.Variables
import System.Directory
import System.FilePath.Posix
import qualified Data.Generics as SYB
import qualified Digraph as GHC
import qualified GHC as GHC
import qualified GHC.SYB.Utils as SYB
import qualified Outputable as GHC
import qualified Data.Map as Map
import qualified Data.Set as Set
-- import Debug.Trace
-- ---------------------------------------------------------------------
{-
-- | From file name to module name.
fileNameToModName :: FilePath -> RefactGhc GHC.ModuleName
fileNameToModName fileName = do
mm <- getModuleMaybe fileName
case mm of
Nothing -> error $ "Can't find module name"
Just ms -> return $ GHC.moduleName $ GHC.ms_mod ms
-}
-- ---------------------------------------------------------------------
{-
getModuleMaybe :: FilePath -> RefactGhc (Maybe GHC.ModSummary)
getModuleMaybe fileName = do
cfileName <- liftIO $ canonicalizePath fileName
logm $ "getModuleMaybe for (fileName,cfileName):" ++ show (fileName,cfileName)
graphs <- gets rsGraph
currentTgt <- gets rsCurrentTarget
logm $ "getModuleMaybe " ++ show fileName ++ ":" ++ show (length graphs,currentTgt)
let cgraph = concatMap (\(_,cg) -> cg) graphs
-- graph <- GHC.getModuleGraph
-- cgraph <- liftIO $ canonicalizeGraph graph
logm $ "getModuleMaybe: [mfn]=" ++ show (map (\(mfn,_ms) -> mfn) cgraph)
let mm = filter (\(mfn,_ms) -> mfn == Just cfileName) cgraph
logm $ "getModuleMaybe: mm=" ++ show mm
case mm of
[] -> return Nothing
_ -> do
let (_mfn,ms) = (ghead "getModuleMaybe" mm)
-- activateModule (fromJust mfn,ms)
return $ Just ms
-}
-- ---------------------------------------------------------------------
-- | Extract the module name from the parsed source, if there is one
getModuleName :: GHC.ParsedSource -> Maybe (GHC.ModuleName,String)
getModuleName (GHC.L _ modn) =
case (GHC.hsmodName modn) of
Nothing -> Nothing
Just (GHC.L _ modname) -> Just $ (modname,GHC.moduleNameString modname)
-- ---------------------------------------------------------------------
getTargetGhc :: TargetModule -> RefactGhc ()
getTargetGhc (GM.ModulePath mn fp) = getModuleGhc fp
-- ---------------------------------------------------------------------
-- | Once the module graph has been loaded, load the given module into
-- the RefactGhc monad
-- TODO: rename this to something like loadModuleGhc
getModuleGhc ::
FilePath -> RefactGhc ()
getModuleGhc targetFile = do
-- TODO: consult cached store of multiple module graphs, one for
-- each main file.
{-
mTarget <- identifyTargetModule targetFile
logm $ "getModuleGhc:mTarget=" ++ show mTarget
case mTarget of
Nothing -> return ()
Just tm -> do
void $ activateModule tm
return ()
-}
parseSourceFileGhc targetFile
{-
mm <- getModuleMaybe targetFile
case mm of
Just ms -> getModuleDetails ms
Nothing -> parseSourceFileGhc targetFile
-}
-- ---------------------------------------------------------------------
{-
identifyTargetModule :: FilePath -> RefactGhc (Maybe TargetModule)
identifyTargetModule targetFile = do
currentDirectory <- liftIO getCurrentDirectory
target1 <- liftIO $ canonicalizePath targetFile
target2 <- liftIO $ canonicalizePath (combine currentDirectory targetFile)
logm $ "identifyTargetModule:(targetFile,target1,target2)=" ++ show (targetFile,target1,target2)
-- graphs <- gets rsModuleGraph
graphs <- gets rsGraph
-- let graphs = concatMap (\(_,cg) -> cg) cgraphs
logm $ "identifyTargetModule:graphs=" ++ show graphs
let ff = catMaybes $ map (findInTarget target1 target2) graphs
logm $ "identifyTargetModule:ff=" ++ show ff
case ff of
[] -> return Nothing
ms -> return (Just (ghead ("identifyTargetModule:" ++ (show ms)) ms))
-}
-- ---------------------------------------------------------------------
{-
findInTarget :: FilePath -> FilePath -> ([FilePath],[(Maybe FilePath,GHC.ModSummary)])
-> Maybe TargetModule
findInTarget f1 f2 (fps,graph) = r'
where
-- We also need to process the case where it is a main file for an exe.
re :: Maybe TargetModule
re = case fps of
[x] -> re' -- single target, could be an exe
where
re' = case filter isMainModSummary graph of
[] -> Nothing
ms -> if x == f1 || x == f2 then Just (fps,ghead "findInTarget" ms)
else Nothing
_ -> Nothing
isMainModSummary (_,ms) = (show $ GHC.ms_mod ms) == "Main"
r = case filter (compModFiles f1 f2) graph of
[] -> Nothing
ms -> Just (fps,ghead "findInTarget.2" ms)
compModFiles :: FilePath-> FilePath -> (Maybe FilePath,GHC.ModSummary) -> Bool
compModFiles fileName1 fileName2 (mfp,ms) =
case GHC.ml_hs_file $ GHC.ms_location ms of
Nothing -> False
Just fn -> fn == fileName1 || fn == fileName2
|| mfp == Just fileName1
|| mfp == Just fileName2
r' = listToMaybe $ catMaybes [r,re]
-}
-- ---------------------------------------------------------------------
-- | In the existing GHC session, put the requested TypeCheckedModule
-- into the RefactGhc Monad, after ensuring that its originating
-- target is the currently loaded one
{-
activateModule :: TargetModule -> RefactGhc GHC.ModSummary
activateModule tm@(target, (mfp,modSum)) = do
logm $ "activateModule:" ++ show (target,mfp,GHC.ms_mod modSum)
newModSum <- ensureTargetLoaded tm
getModuleDetails newModSum
return newModSum
-}
-- ---------------------------------------------------------------------
-- | In the existing GHC session, put the requested TypeCheckedModule
-- into the RefactGhc monad
-- TODO: rename this function, it is not clear in a refactoring what
-- it does
getModuleDetails :: GHC.ModSummary -> RefactGhc ()
getModuleDetails modSum = do
logm $ "getModuleDetails:modSum=" ++ show modSum
p <- GHC.parseModule modSum
t <- GHC.typecheckModule p
logm $ "getModuleDetails:setting context.."
-- TODO:AZ: reinstate this, else inscope queries will fail. Or is there a better way to do those?
setGhcContext modSum
logm $ "getModuleDetails:context set"
(mfp,_modSum) <- canonicalizeModSummary modSum
newTargetModule <- case mfp of
Nothing -> error $ "HaRe:no file path for module:" ++ showGhc modSum
Just fp -> return $ GM.ModulePath (GHC.moduleName $ GHC.ms_mod modSum) fp
oldTargetModule <- gets rsCurrentTarget
let
putModule = do
putParsedModule t
settings <- get
put $ settings { rsCurrentTarget = Just newTargetModule }
mtm <- gets rsModule
case mtm of
Just tm -> if ((rsStreamModified tm == RefacUnmodifed)
&& oldTargetModule == Just newTargetModule)
then do
logm $ "getModuleDetails:not calling putParsedModule for targetModule=" ++ show newTargetModule
return ()
else if rsStreamModified tm == RefacUnmodifed
then putModule
else error $ "getModuleDetails: trying to load a module without finishing with active one."
Nothing -> putModule
return ()
-- ---------------------------------------------------------------------
-- | Parse a single source file into a GHC session
parseSourceFileGhc :: FilePath -> RefactGhc ()
parseSourceFileGhc targetFile = do
{-
-- currentDir <- liftIO getCurrentDirectory
-- logm $ "parseSourceFileGhc:currentDir=" ++ currentDir
logm $ "parseSourceFileGhc:about to loadModuleGraphGhc for" ++ (show targetFile)
loadModuleGraphGhc (Just [targetFile])
logm $ "parseSourceFileGhc:loadModuleGraphGhc done"
mm <- getModuleMaybe targetFile
case mm of
Nothing -> error $ "HaRe:unexpected error parsing " ++ targetFile
Just modSum -> getModuleDetails modSum
-}
loadTarget [targetFile]
graph <- GHC.getModuleGraph
cgraph <- canonicalizeGraph graph
cfileName <- liftIO $ canonicalizePath targetFile
let mm = filter (\(mfn,_ms) -> mfn == Just cfileName) cgraph
case mm of
[(_,modSum)] -> getModuleDetails modSum
_ -> error $ "HaRe:unexpected error parsing " ++ targetFile
-- ---------------------------------------------------------------------
-- | Manage a whole refactor session. Initialise the monad, load the
-- whole project if required, and then apply the individual
-- refactorings, and write out the resulting files.
--
-- It is intended that this forms the umbrella function, in which
-- applyRefac is called
--
runRefacSession ::
RefactSettings
-> GM.Options -- ^ ghc-mod options
-> Targets -- ^ files/modules to load for the session
-> RefactGhc [ApplyRefacResult] -- ^ The computation doing the
-- refactoring. Normally created
-- via 'applyRefac'
-> IO [FilePath]
runRefacSession settings opt targets comp = do
let
initialState = RefSt
{ rsSettings = settings
, rsUniqState = 1
, rsSrcSpanCol = 1
, rsFlags = RefFlags False
, rsStorage = StorageNone
-- , rsGraph = []
, rsCabalGraph = []
, rsModuleGraph = []
, rsCurrentTarget = Nothing
, rsModule = Nothing
}
comp' = initGhcSession targets >> comp
-- comp' = gmSetLogLevel GmError >> comp
(refactoredMods,_s) <- runRefactGhc comp' targets initialState opt
let verbosity = rsetVerboseLevel (rsSettings initialState)
writeRefactoredFiles verbosity refactoredMods
return $ modifiedFiles refactoredMods
-- ---------------------------------------------------------------------
-- TODO: the module should be stored in the state, and returned if it
-- has been modified in a prior refactoring, instead of being parsed
-- afresh each time.
-- | Apply a refactoring (or part of a refactoring) to a single module
applyRefac
:: RefactGhc a -- ^ The refactoring
-> RefacSource -- ^ where to get the module and toks
-> RefactGhc (ApplyRefacResult,a)
applyRefac refac source = do
-- TODO: currently a temporary, poor man's surrounding state
-- management: store state now, set it to fresh, run refac, then
-- restore the state. Fix this to store the modules in some kind of cache.
fileName <- case source of
RSFile fname -> do getModuleGhc fname
return fname
RSMod ms -> do getModuleGhc $ fileNameFromModSummary ms
return $ fileNameFromModSummary ms
RSAlreadyLoaded -> do mfn <- getRefactFileName
case mfn of
Just fname -> return fname
Nothing -> error "applyRefac RSAlreadyLoaded: nothing loaded"
res <- refac -- Run the refactoring, updating the state as required
-- mod' <- getRefactRenamed
mod' <- getRefactParsed
-- toks' <- fetchToksFinal
-- let toks' = []
-- pprVal <- fetchPprFinal
anns <- fetchAnnsFinal
m <- getRefactStreamModified
-- Clear the refactoring state
clearParsedModule
return (((fileName,m),(anns, mod')),res)
-- ---------------------------------------------------------------------
-- |Returns True if any of the results has its modified flag set
refactDone :: [ApplyRefacResult] -> Bool
refactDone rs = any (\((_,d),_) -> d == RefacModified) rs
-- ---------------------------------------------------------------------
modifiedFiles :: [ApplyRefacResult] -> [String]
modifiedFiles refactResult = map (\((s,_),_) -> s)
$ filter (\((_,b),_) -> b == RefacModified) refactResult
-- ---------------------------------------------------------------------
-- | Initialise the GHC session, when starting a refactoring.
-- This should never be called directly.
initGhcSession :: Targets -> RefactGhc ()
initGhcSession tgts = do
{-
settings <- getRefacSettings
df <- GHC.getSessionDynFlags
let df2 = GHC.gopt_set df GHC.Opt_KeepRawTokenStream
void $ GHC.setSessionDynFlags df2
-- liftIO $ putStrLn "initGhcSession:entered (IO)"
logm $ "initGhcSession:entered2"
cr <- cradle
logm $ "initGhcSession:cr=" ++ show cr
case cradleCabalFile cr of
Just _ -> do
(cabalGraph,targets) <- cabalAllTargets cr
logm $ "initGhcSession:targets=" ++ show targets
-- TODO: Cannot load multiple main modules, must try to load
-- each main module and retrieve its module graph, and then
-- set the targets to this superset.
let targets' = getEnabledTargets settings targets
case targets' of
([],[]) -> return ()
(libTgts,exeTgts) -> do
-- liftIO $ warningM "HaRe" $ "initGhcSession:tgts=" ++ (show (libTgts,exeTgts))
logm $ "initGhcSession:(libTgts,exeTgts)=" ++ (show (libTgts,exeTgts))
-- setTargetFiles tgts
-- void $ GHC.load GHC.LoadAllTargets
-- AZ: carry on here, store cabalGraph instead of loadModuleGraphGhc
mapM_ loadModuleGraphGhc $ map (\t -> Just [t]) exeTgts
-- Load the library last, most likely in context
case libTgts of
[] -> return ()
_ -> loadModuleGraphGhc (Just libTgts)
-- moduleGraph <- gets rsModuleGraph
-- logm $ "initGhcSession:rsModuleGraph=" ++ (show moduleGraph)
Nothing -> do
let maybeMainFile = rsetMainFile settings
loadModuleGraphGhc maybeMainFile
return()
-}
-- load the first target is specified
case tgts of
[] -> return ()
_ -> case head tgts of
Left filename -> getModuleGhc filename
Right modname -> getModuleGhc (GHC.moduleNameString modname)
return ()
-- ---------------------------------------------------------------------
{-
-- | Extracting all 'Module' 'FilePath's for libraries, executables,
-- tests and benchmarks.
cabalAllTargets :: Cradle -> RefactGhc (CabalGraph,([String],[String],[String],[String]))
cabalAllTargets crdl = RefactGhc (GmlT $ cabalOpts crdl)
where
-- Note: This runs inside ghc-mod's GmlT monad
cabalOpts :: Cradle -> GhcModT (StateT RefactState IO) (CabalGraph,([String],[String],[String],[String]))
cabalOpts Cradle{..} = do
comps <- mapM (resolveEntrypoint crdl) =<< getComponents
mcs <- cached cradleRootDir resolvedComponentsCache comps
let
-- foo :: Map.Map ChComponentName (Set.Set ModulePath)
-- foo = Map.map gmcEntrypoints mcs
-- bar :: Map.Map ChComponentName GmModuleGraph
-- bar = Map.map gmcHomeModuleGraph mcs
entries = Map.toList $ Map.map gmcEntrypoints mcs
isExe (ChExeName _,_) = True
isExe _ = False
isLib (ChLibName,_) = True
isLib _ = False
isTest (ChTestName _,_) = True
isTest _ = False
isBench (ChBenchName _,_) = True
isBench _ = False
getTgts :: (ChComponentName,Set.Set ModulePath) -> [String]
getTgts (_,mps) = map mpPath $ Set.toList mps
exeTargets = concatMap getTgts $ filter isExe entries
libTargets = concatMap getTgts $ filter isLib entries
testTargets = concatMap getTgts $ filter isTest entries
benchTargets = concatMap getTgts $ filter isBench entries
return (mcs,(libTargets,exeTargets,testTargets,benchTargets))
-}
-- ---------------------------------------------------------------------
{-
getEnabledTargets :: RefactSettings -> ([FilePath],[FilePath],[FilePath],[FilePath]) -> ([FilePath],[FilePath])
getEnabledTargets settings (libt,exet,testt,bencht) = (targetsLib,targetsExe)
where
(libEnabled, exeEnabled, testEnabled, benchEnabled) = rsetEnabledTargets settings
targetsLib = on libEnabled libt
targetsExe = on exeEnabled exet
++ on testEnabled testt
++ on benchEnabled bencht
on flag xs = if flag then xs else []
-}
-- ---------------------------------------------------------------------
class (SYB.Data t, SYB.Data t1) => Update t t1 where
-- | Update the occurrence of one syntax phrase in a given scope by
-- another syntax phrase of the same type
update:: t -- ^ The syntax phrase to be updated.
-> t -- ^ The new syntax phrase.
-> t1 -- ^ The contex where the old syntax phrase occurs.
-> RefactGhc t1 -- ^ The result.
instance (SYB.Data t, GHC.OutputableBndr n, GHC.DataId n)
=> Update (GHC.Located (GHC.HsExpr n)) t where
update oldExp newExp t
= SYB.everywhereMStaged SYB.Parser (SYB.mkM inExp) t
where
inExp (e::GHC.Located (GHC.HsExpr n))
| sameOccurrence e oldExp
= do
-- drawTokenTree "update Located HsExpr starting" -- ++AZ++
-- _ <- updateToks oldExp newExp prettyprint False
-- drawTokenTree "update Located HsExpr done" -- ++AZ++
-- error "update: updated tokens" -- ++AZ++ debug
-- TODO: make sure to call syncAST
return newExp
| otherwise = return e
instance (SYB.Data t, GHC.OutputableBndr n, GHC.DataId n)
=> Update (GHC.LPat n) t where
update oldPat newPat t
= SYB.everywhereMStaged SYB.Parser (SYB.mkM inPat) t
where
inPat (p::GHC.LPat n)
| sameOccurrence p oldPat
= do
-- _ <- updateToks oldPat newPat prettyprint False
-- TODO: make sure to call syncAST
return newPat
| otherwise = return p
instance (SYB.Data t, GHC.OutputableBndr n, GHC.DataId n)
=> Update (GHC.LHsType n) t where
update oldTy newTy t
= SYB.everywhereMStaged SYB.Parser (SYB.mkM inTyp) t
where
inTyp (t'::GHC.LHsType n)
| sameOccurrence t' oldTy
= do
-- _ <- updateToks oldTy newTy prettyprint False
-- TODO: make sure to call syncAST
return newTy
| otherwise = return t'
instance (SYB.Data t, GHC.OutputableBndr n1, GHC.OutputableBndr n2, GHC.DataId n1, GHC.DataId n2)
=> Update (GHC.LHsBindLR n1 n2) t where
update oldBind newBind t
= SYB.everywhereMStaged SYB.Parser (SYB.mkM inBind) t
where
inBind (t'::GHC.LHsBindLR n1 n2)
| sameOccurrence t' oldBind
= do
-- _ <- updateToks oldBind newBind prettyprint False
-- TODO: make sure to call syncAST
return newBind
| otherwise = return t'
-- ---------------------------------------------------------------------
-- | Write refactored program source to files.
writeRefactoredFiles ::
VerboseLevel -> [ApplyRefacResult] -> IO ()
writeRefactoredFiles verbosity files
= do let filesModified = filter (\((_f,m),_) -> m == RefacModified) files
-- TODO: restore the history function
-- ++AZ++ PFE0.addToHistory isSubRefactor (map (fst.fst) filesModified)
sequence_ (map modifyFile filesModified)
-- mapM_ writeTestDataForFile files -- This should be removed for the release version.
where
modifyFile ((fileName,_),(ann,parsed)) = do
let source = exactPrintWithAnns parsed ann
let (baseFileName,ext) = splitExtension fileName
seq (length source) (writeFile (baseFileName ++ ".refactored" ++ ext) source)
when (verbosity == Debug) $
do
writeFile (fileName ++ ".parsed_out") (showGhc parsed)
writeFile (fileName ++ ".AST_out") ((showGhc parsed) ++
"\n\n----------------------\n\n" ++
-- (SYB.showData SYB.Parser 0 parsed) ++
(showAnnData ann 0 parsed) ++
"\n\n----------------------\n\n" ++
(showGhc ann) ++
"\n\n----------------------\n\n"
-- (showAnnData (organiseAnns ann) 0 parsed)
)
-- ---------------------------------------------------------------------
-- | Return the client modules and file names. The client modules of
-- module, say m, are those modules which directly or indirectly
-- import module m.
-- clientModsAndFiles :: GHC.ModuleName -> RefactGhc [TargetModule]
clientModsAndFiles :: GM.ModulePath -> RefactGhc [TargetModule]
clientModsAndFiles m = do
mgs <- cabalModuleGraphs
-- mgs is [Map ModulePath (Set ModulePath)]
-- where eack key imports the corresponding set.
-- There are no cycles
-- We need the reverse of this, the transitive set of values where if the
-- ModulePath is in the set, then the key is of interest.
-- So
-- Flatten the module graph, reverse the dependencies, then rebuild it
let
flattenSwap (GM.GmModuleGraph mg)
= concatMap (\(k,vs) -> map (\v -> (v,Set.singleton k)) (Set.elems vs)) $ Map.toList mg
transposed = mgs'
where
kvs = concatMap flattenSwap mgs
mgs' = foldl' (\acc (k,v) -> Map.insertWith Set.union k v acc) Map.empty kvs
-- transposed is a map from each module to those that import it. We need the
-- transitive closure of all the importers of the given module.
check acc k =
case Map.lookup k transposed of
Nothing -> (acc,[])
Just s -> (Set.union acc s, Set.toList $ s Set.\\ acc)
go (acc,[]) = acc
go (acc,c:s) = go (acc',s')
where
(acc',q) = check acc c
s' = nub (q ++ s)
r = go (Set.empty, [m])
return $ Set.toList r
{-
-- TODO: deal with an anonymous main module, by taking Maybe GHC.ModuleName
clientModsAndFiles :: GHC.ModuleName -> RefactGhc [TargetModule]
clientModsAndFiles m = do
modsum <- GHC.getModSummary m
-- ms' <- GHC.getModuleGraph
ms' <- gets rsModuleGraph
-- target <- gets rsCurrentTarget
let getClients ms = clientMods
where
mg = getModulesAsGraph False ms Nothing
rg = GHC.transposeG mg
maybeModNode = find (\(msum',_,_) -> mycomp msum' modsum) (GHC.verticesG rg)
clientMods = case maybeModNode of
Nothing -> []
Just modNode ->
filter (\msum' -> not (mycomp msum' modsum))
$ map summaryNodeSummary $ GHC.reachableG rg modNode
let clients = concatMap (\(f,mg) -> zip (repeat f) (getClients mg)) ms'
-- Need to strip out duplicates, based on the snd of the tuple
clients' = nubBy cc clients
cc (_,mg1) (_,mg2)
= if (show $ GHC.ms_mod mg1) == "Main" || (show $ GHC.ms_mod mg2) == "Main"
then False
else mycomp mg1 mg2
cms (fps,ms) = do
-- ms1 <- canonicalizeModSummary ms
-- return (fps,ms1)
let ms1 = GHC.moduleName $ GHC.ms_mod ms
return (GM.ModulePath ms1 (ghead "clientModsAndFiles" fps))
logm $ "clientModsAndFiles:clients=" ++ show clients
logm $ "clientModsAndFiles:clients'=" ++ show clients'
clients'' <- mapM cms clients'
return clients''
-}
-- TODO : find decent name and place for this.
mycomp :: GHC.ModSummary -> GHC.ModSummary -> Bool
mycomp ms1 ms2 = (GHC.ms_mod ms1) == (GHC.ms_mod ms2)
-- ---------------------------------------------------------------------
-- | Return the server module and file names. The server modules of
-- module, say m, are those modules which are directly or indirectly
-- imported by module m. This can only be called in a live GHC session
-- TODO: make sure this works with multiple targets. Is that needed? No?
serverModsAndFiles
:: GHC.GhcMonad m => GHC.ModuleName -> m [GHC.ModSummary]
serverModsAndFiles m = do
ms <- GHC.getModuleGraph
modsum <- GHC.getModSummary m
let mg = getModulesAsGraph False ms Nothing
modNode = gfromJust "serverModsAndFiles" $ find (\(msum',_,_) -> mycomp msum' modsum) (GHC.verticesG mg)
serverMods = filter (\msum' -> not (mycomp msum' modsum))
$ map summaryNodeSummary $ GHC.reachableG mg modNode
return serverMods
| mpickering/HaRe | src/Language/Haskell/Refact/Utils/Utils.hs | bsd-3-clause | 26,255 | 0 | 20 | 6,924 | 3,021 | 1,611 | 1,410 | 244 | 5 |
{-# LANGUAGE GADTs, DataKinds, KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, StandaloneDeriving #-}
{-# LANGUAGE TypeOperators, TypeFamilies, FlexibleInstances, FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
module Language.Cypher where
import qualified Data.Aeson as A
import Data.List (intersperse)
import Data.Monoid (Monoid (..), (<>))
import Data.String (IsString (fromString))
import Data.Text (Text)
import qualified Data.Vector as V
import Database.Neo4j.Types (DValue (..))
data CType =
Number | Boolean | Str
| Identifier
| Collection CType
| CPattern
class Convert (a :: CType) where
data Value a :: *
convert :: DValue -> Maybe (Value a)
instance Convert Number where
newtype Value Number = VNum Double deriving (Eq, Show, Ord)
convert (Int x) = Just $ VNum (fromIntegral x)
convert (Float x) = Just $ VNum x
convert _ = Nothing
instance Convert Str where
newtype Value Str = VStr Text deriving (Eq, Show, Ord)
convert (String x) = Just $ VStr x
convert _ = Nothing
instance Convert Boolean where
newtype Value Boolean = VBool Bool deriving (Eq, Show, Ord)
convert (Bool x) = Just $ VBool x
convert _ = Nothing
instance Convert Identifier where
newtype Value Identifier = VIdent A.Object deriving (Eq, Show)
convert (DObj o) = Just $ VIdent o
convert _ = Nothing
instance Convert a => Convert (Collection a) where
newtype Value (Collection a) = VColl (V.Vector (Value a))
convert (DColl xs) = fmap VColl $ V.mapM convert xs
convert _ = Nothing
instance Show (Value a) => Show (Value (Collection a)) where
show (VColl xs) = "VColl " ++ show xs
class Case (a :: CType)
instance Case Number
instance Case Str
instance Case Boolean
class EOrd (a :: CType)
instance EOrd Number
newtype Label = Label String deriving (IsString)
newtype RelType = RelType String deriving (IsString)
data Range = Range (Maybe Int) (Maybe Int)
data RelDirection = RelLeft | RelRight | RelBoth
--data RelInfo = RelInfo (Maybe (E Identifier)) (Maybe Range)
sho :: (Show a, Monoid s, IsString s) => a -> s
sho = fromString . show
perhaps :: (Monoid s, IsString s) => (a -> s) -> Maybe a -> s
perhaps = maybe ""
writeAssocs :: (Monoid s, IsString s) => [Assoc] -> s
writeAssocs [] = ""
writeAssocs xs = "{ " <> mconcat (intersperse ", " (map f xs)) <> " }"
where
f (Assoc name expr) = fromString name <> ": '" <> writeExp expr <> "'"
writeRange :: (Monoid s, IsString s) => Range -> s
writeRange (Range ml mh) = case (ml, mh) of
(Just l, Just h) -> sho l <> (if l == h then "" else theDots <> sho h)
(Just l, Nothing) -> sho l <> theDots
(Nothing, Just h) -> theDots <> sho h
(Nothing, Nothing) -> ""
where
theDots = ".."
writeCases :: (Monoid s, IsString s) => [(E a, E b)] -> Maybe (E b) -> s
writeCases cases def =
mconcat ["WHEN " <> writeExp val <> " THEN " <> writeExp result
| (val, result) <- cases ]
<> perhaps (\e -> " ELSE " <> writeExp e) def
<> " END"
writeRelTypes :: (Monoid s, IsString s) => [RelType] -> s
writeRelTypes [] = mempty
writeRelTypes (x : xs) = ":" <> s x <> mconcat [ "|" <> s y | y <- xs ]
where
s :: (Monoid s, IsString s) => RelType -> s
s (RelType y) = fromString y
writePattern :: (Monoid s, IsString s) => Pattern -> s
writePattern p = case p of
PNode ident assocs labels -> paren $
perhaps writeExp ident
<> mconcat [ ":" <> fromString l | Label l <- labels ]
<> writeAssocs assocs
PRel left right ident mr dir assocs types ->
writePattern left <> leftArr dir <> sqbrack (
(perhaps writeExp ident <> writeRelTypes types <> perhaps (\r -> "*" <> writeRange r) mr)
<> writeAssocs assocs
) <> rightArr dir <> writePattern right
PAnd left right -> writePattern left <> " , " <> writePattern right
where
leftArr RelLeft = "<-"
leftArr _ = "-"
rightArr RelRight = "->"
rightArr _ = "-"
writeExp :: (Monoid s, IsString s) => E a -> s
writeExp e = case e of
EInt i -> sho i
EDouble d -> sho d
EBool b -> sho b
EString s -> sho s
EIdent i -> fromString i
EParam p -> "{" <> fromString p <> "}"
EProp i p -> writeExp i <> "." <> fromString p
EAbs i -> "abs(" <> writeExp i <> ")"
ESign i -> "sign(" <> writeExp i <> ")"
EColl xs -> sqbrack . mconcat . intersperse "," $
map writeExp xs
EIndex xs i -> writeExp xs <> sqbrack (sho i)
ESubColl xs range -> writeExp xs <> sqbrack (writeRange range)
EPlus l r -> binOp "+" l r
EMinus l r -> binOp "-" l r
ETimes l r -> binOp "*" l r
EDiv l r -> binOp "/" l r
EMod l r -> binOp "%" l r
EPow l r -> binOp "^" l r
EAnd l r -> binOp "AND" l r
EOr l r -> binOp "OR" l r
EXor l r -> binOp "XOR" l r
ENot x -> "NOT" <> paren (writeExp x)
ELT l r -> binOp "<" l r
ELTE l r -> binOp "<=" l r
EGT l r -> binOp ">" l r
EGTE l r -> binOp ">=" l r
EEQ l r -> binOp "=" l r
ERegExpEQ l r -> binOp "=~" l r
EConcat l r -> binOp "+" l r
EConcatStr l r -> binOp "+" l r
ESCase test cases def -> "CASE " <> writeExp test <> " "
<> writeCases cases def
EGCase cases def -> "CASE " <> writeCases cases def
EPattern pat -> writePattern pat
where
binOp :: (Monoid s, IsString s) => s -> E a -> E b -> s
binOp op l r = paren (writeExp l) <> " " <> op
<> " " <> paren (writeExp r)
bracket :: (Monoid s, IsString s) => s -> s -> s -> s
bracket open close x = open <> x <> close
sqbrack :: (Monoid s, IsString s) => s -> s
sqbrack = bracket "[" "]"
paren :: (Monoid s, IsString s) => s -> s
paren = bracket "(" ")"
data Assoc :: * where
Assoc :: String -> E a -> Assoc
instance Num (E Number) where
x + y = EPlus x y
x * y = ETimes x y
x - y = EMinus x y
negate x = EMinus (EDouble 0) x
fromInteger x = EInt (fromIntegral x)
abs x = EAbs x
signum x = ESign x
data E :: CType -> * where
-- literals
EInt :: Int -> E Number
EDouble :: Double -> E Number
EBool :: Bool -> E Boolean
EString :: String -> E Str
EIdent :: String -> E Identifier
EParam :: String -> E a
EProp :: E Identifier -> String -> E a
EColl :: [E a] -> E (Collection a)
EIndex :: E (Collection a) -> Int -> E a
ESubColl :: E (Collection a) -> Range -> E (Collection a)
ESCase :: Case a => E a -> [(E a, E b)] -> Maybe (E b) -> E b
EGCase :: [(E Boolean, E a)] -> Maybe (E a) -> E a
--operators
EPlus, EMinus, ETimes, EDiv, EPow, EMod
:: E Number -> E Number -> E Number
EAnd, EOr, EXor :: E Boolean -> E Boolean -> E Boolean
ENot :: E Boolean -> E Boolean
EConcatStr :: E Str -> E Str -> E Str
EConcat :: E (Collection a) -> E (Collection a) -> E (Collection a)
ELT, ELTE, EGT, EGTE :: EOrd a => E a -> E a -> E Boolean
--functions
EAbs, ESign :: E Number -> E Number
EEQ :: EEq a => E a -> E a -> E Boolean
ERegExpEQ :: E Str -> E Str -> E Boolean
EPattern :: Pattern -> E CPattern
class EEq (a :: CType) where
instance EEq Str
instance EEq Number
instance EEq Boolean
data EAs :: CType -> * where
EAs :: E a -> String -> EAs a
data RetE :: CType -> * where
RetE :: E a -> RetE a
RetEAs :: EAs a -> RetE a
writeAs :: (IsString s, Monoid s) => EAs a -> s
writeAs (EAs expr name) = writeExp expr <> " AS " <> fromString name
writeRetE :: (IsString s, Monoid s) => RetE a -> s
writeRetE x = case x of
RetE e -> writeExp e
RetEAs e -> writeAs e
data Pattern =
PNode (Maybe (E Identifier)) [Assoc] [Label]
| PRel Pattern Pattern (Maybe (E Identifier)) (Maybe Range) RelDirection [Assoc] [RelType]
| PAnd Pattern Pattern
data MatchType = RequiredMatch | OptionalMatch
data Match = Match MatchType Pattern (Maybe Where)
writeMatchType :: (IsString s, Monoid s) => MatchType -> s
writeMatchType x = case x of
RequiredMatch -> "MATCH"
OptionalMatch -> "OPTIONAL MATCH"
writeMatch :: (IsString s, Monoid s) => Match -> s
writeMatch (Match mt pat mwhere) = writeMatchType mt
<> " " <> writePattern pat <> perhaps (\w -> " " <> writeWhere w) mwhere
class WhereExp (e :: CType)
instance WhereExp Boolean
instance WhereExp CPattern
data Where where
Where :: WhereExp e => E e -> Where
writeWhere :: (IsString s, Monoid s) => Where -> s
writeWhere (Where expr) = "WHERE " <> writeExp expr
data Query (l :: [CType]) where
QReturn ::
[Match] -- ^ matches
-> HList RetE xs -- ^ return
-> Maybe (E ord) -- ^ order by
-> Maybe Int -- ^ skip
-> Maybe Int -- ^ limit
-> Query xs
QUnion :: Bool -> Query xs -> Query xs -> Query xs
QWith :: EAs a -> Query xs -> Query xs
infixr 5 :::
data HList f (as :: [CType]) where
HNil :: HList f '[]
(:::) :: f a -> HList f as -> HList f (a ': as)
instance Show (HList f '[]) where
show HNil = "HNil"
instance Eq (HList f '[]) where
HNil == HNil = True
instance (Show (f a), Show (HList f as)) => Show (HList f (a ': as)) where
show (x ::: xs) = show x ++ " ::: " ++ show xs
instance (Eq (f a), Eq (HList f as)) => Eq (HList f (a ': as)) where
(x ::: xs) == (y ::: ys) = x == y && xs == ys
foldrHList :: (forall a. RetE a -> b -> b) -> b -> HList RetE xs -> b
foldrHList _ z HNil = z
foldrHList f z (x ::: xs) = f x (foldrHList f z xs)
mapHList :: (forall a. RetE a -> b) -> HList RetE xs -> [b]
mapHList f = foldrHList ((:) . f) []
instance Show (Query xs) where
show = writeQuery :: Query xs -> String
class ConvertL (as :: [CType]) where
convertl :: [DValue] -> Maybe (HList Value as)
instance ConvertL '[] where
convertl [] = Just HNil
convertl _ = Nothing
instance (Convert a, ConvertL as) => ConvertL (a ': as) where
convertl (y : ys) = do
y' <- convert y
ys' <- convertl ys
return $ y' ::: ys'
convertl _ = Nothing
dresult :: [[DValue]]
dresult =
[ [Float 3 , Bool True , String "Hi!", DColl (V.fromList [Float 3, Float 4])]
, [Float 15, Bool False, String "HaskellDC", DColl V.empty]
]
-- an example of converting to our heterogenous list
typedResult :: [HList Value [Number, Boolean, Str, Collection Number]]
Just typedResult = mapM convertl dresult
writeQuery :: (Monoid s, IsString s) => Query xs -> s
writeQuery query = case query of
QReturn matches ret orderBy skip limit ->
mconcat (map writeMatch matches)
<> " RETURN " <> mconcat (intersperse ", " (mapHList writeRetE ret))
<> perhaps (\o -> " ORDER BY " <> writeExp o) orderBy
<> perhaps (\s -> " SKIP " <> sho s) skip
<> perhaps (\l -> " LIMIT " <> sho l) limit
QUnion uall left right ->
writeQuery left <> " UNION " <> (if uall then "ALL " else "")
<> writeQuery right
QWith asExpr q ->
"WITH " <> writeAs asExpr <> writeQuery q
simpleMatch :: Pattern -> HList RetE xs -> Query xs
simpleMatch matchPat ret =
QReturn [Match RequiredMatch matchPat Nothing]
ret (Nothing :: Maybe (E Number)) Nothing Nothing
| HaskellDC/neo4j-cypher | Language/Cypher.hs | bsd-3-clause | 10,838 | 15 | 20 | 2,688 | 4,847 | 2,427 | 2,420 | -1 | -1 |
module ABFA.Input where
-- the inputs from mouse and keyboard are processed
import Control.Monad.RWS.Strict (liftIO, asks, ask, gets, get, modify)
import Control.Monad (when)
import Data.Char (toUpper)
import qualified GLUtil.ABFA as GLFW
import qualified Data.ByteString.Lazy as BS
import ABFA.Game
import ABFA.State
import ABFA.Data
import ABFA.Event
import ABFA.World
import ABFA.Shell
import ABFA.Settings
import ABFA.Zone
import ABFA.Map
-- case function for all of the keys
evalKey :: GLFW.Window -> GLFW.Key -> GLFW.KeyState -> GLFW.ModifierKeys -> Game ()
evalKey window k ks mk = do
state <- get
env <- ask
inpkey <- liftIO $ calcInpKey k mk
let settings = stateSettings state
let keylayout = settingKeyLayout settings
let gs = stateGame state
-- quits from the menu
when ((gs == SMenu) && (keyCheck keylayout k "ESC")) $ do
liftIO $ GLFW.closeGLFW window
return ()
-- exits when in world view, in future should save game
when ((gs == SWorld) && (keyCheck keylayout k "ESC")) $ do
liftIO $ GLFW.closeGLFW window
return ()
-- returns to menu from zone view
when ((gs == SZone) && (keyCheck keylayout k "ESC")) $ do
liftIO $ loadedCallback (envEventsChan env) SMenu
return ()
-- creates world from the menu
when ((gs == SMenu) && (keyCheck keylayout k "C")) $ do
liftIO $ loadedCallback (envEventsChan env) SLoadWorld
let newstate = initGoodWorld state
-- let the timers know that we have generated a new state
liftIO $ atomically $ writeChan (envStateChan2 env) newstate
liftIO $ atomically $ writeChan (envStateChan4 env) newstate
modify $ \s -> newstate
return ()
-- regenerates the world from the world screen
when ((gs == SWorld) && (keyCheck keylayout k "R")) $ do
-- stop the timers
liftIO $ atomically $ writeChan (envWTimerChan env) TStop
liftIO $ atomically $ writeChan (envATimerChan env) TStop
-- ensure empty channels
liftIO $ emptyChan (envStateChan1 env)
liftIO $ emptyChan (envStateChan2 env)
liftIO $ emptyChan (envStateChan3 env)
liftIO $ emptyChan (envStateChan4 env)
-- create new world
let newstate = initWorldWithCheck state
-- just to be sure, empty the channels again
liftIO $ emptyChan (envStateChan1 env)
liftIO $ emptyChan (envStateChan2 env)
liftIO $ emptyChan (envStateChan3 env)
liftIO $ emptyChan (envStateChan4 env)
-- alert the timers of the new state
liftIO $ atomically $ writeChan (envStateChan2 env) newstate
liftIO $ atomically $ writeChan (envStateChan4 env) newstate
modify $ \s -> newstate
return ()
-- moves the cursor orthographically, shift will move 5...
when ((gs == SWorld) && ((keyCheck keylayout k "LFT") || (keyCheck keylayout k "RGT") || (keyCheck keylayout k "UPP") || (keyCheck keylayout k "DWN"))) $ do
when ((gs == SWorld) && (keyCheck keylayout k "LFT")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5 else 1
modify $ \s -> s { stateCursor = (moveCursor step (stateCursor state) (settingGridW settings) (settingGridH settings) West) }
when ((gs == SWorld) && (keyCheck keylayout k "RGT")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5 else 1
modify $ \s -> s { stateCursor = (moveCursor step (stateCursor state) (settingGridW settings) (settingGridH settings) East) }
when ((gs == SWorld) && (keyCheck keylayout k "UPP")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5 else 1
modify $ \s -> s { stateCursor = (moveCursor step (stateCursor state) (settingGridW settings) (settingGridH settings) North) }
when ((gs == SWorld) && (keyCheck keylayout k "DWN")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5 else 1
modify $ \s -> s { stateCursor = (moveCursor step (stateCursor state) (settingGridW settings) (settingGridH settings) South) }
return ()
-- enters zone state
when ((gs == SWorld) && (keyCheck keylayout k "RET")) $ do
let oldzs = stateZone state
z = generateZone state cx cy
ze = generateZone state (cx+1) cy
zw = generateZone state (cx-1) cy
zn = generateZone state cx (cy+1)
zs = generateZone state cx (cy-1)
znw = generateZone state (cx-1) (cy+1)
zne = generateZone state (cx+1) (cy+1)
zsw = generateZone state (cx-1) (cy-1)
zse = generateZone state (cx+1) (cy-1)
(cx, cy) = stateCursor state
liftIO $ loadedCallback (envEventsChan env) SLoadZone
--iftIO $ print $ "gbs: " ++ (show ((bsToList (cbs (zonechunk z)) 1)))
modify $ \s -> s { stateZone = znw:zn:zne:zw:z:ze:zsw:zs:zse:oldzs
--modify $ \s -> s { stateZone = z:oldzs
, stateEmbark = (cx, cy) }
return ()
-- moves the zone camera orthographically around the screen
when ((gs == SZone) && ((keyCheck keylayout k "CL") || (keyCheck keylayout k "CR") || (keyCheck keylayout k "CU") || (keyCheck keylayout k "CD"))) $ do
when ((gs == SZone) && (keyCheck keylayout k "CL")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5.0 else 1.0
let newcam = moveCam DLeft step (stateZoneCam state)
modify $ \s -> s { stateZoneCam = newcam }
when ((gs == SZone) && (keyCheck keylayout k "CR")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5.0 else 1.0
let newcam = moveCam DRight step (stateZoneCam state)
modify $ \s -> s { stateZoneCam = newcam }
when ((gs == SZone) && (keyCheck keylayout k "CU")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5.0 else 1.0
let newcam = moveCam DUp step (stateZoneCam state)
modify $ \s -> s { stateZoneCam = newcam }
when ((gs == SZone) && (keyCheck keylayout k "CD")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5.0 else 1.0
let newcam = moveCam DDown step (stateZoneCam state)
modify $ \s -> s { stateZoneCam = newcam }
return ()
-- opens a lua shell
when ((gs /= SShell) && (keyCheck keylayout k "`")) $ do
liftIO $ loadedCallback (envEventsChan env) SShell
return ()
-- closes the shell
when ((gs == SShell) && ((keyCheck keylayout k "`") || (keyCheck keylayout k "ESC"))) $ do
liftIO $ loadedCallback (envEventsChan env) $ stateGamePrev state
return ()
-- deletes stuff
when ((gs == SShell) && (keyCheck keylayout k "DEL")) $ do
modify $ \s -> s { stateShellInput = inputDelete (stateShellInput state) }
return ()
-- types a space
when ((gs == SShell) && (keyCheck keylayout k "SPC")) $ do
modify $ \s -> s { stateShellInput = (stateShellInput state) ++ " " }
return ()
-- runs a lua command
when ((gs == SShell) && (keyCheck keylayout k "RET")) $ do
outbuff <- liftIO $ execShell (stateLua state) (stateShellInput state)
newsets <- liftIO $ reimportSettings (stateLua state) "mods/config/"
let win = envWindow env
w = settingScreenW newsets
h = settingScreenH newsets
newbuff = (outbuff) : (" % " ++ (stateShellInput state)) : (tail (stateShellBuff state))
liftIO $ reshapeCallback (envEventsChan env) win w h
modify $ \s -> s { stateSettings = newsets
, stateShellBuff = " % " : newbuff
, stateShellInput = "" }
return ()
-- reads the users keyboard
when ((gs == SShell) && (not ((keyCheck keylayout k "`") || (keyCheck keylayout k "DEL") || (keyCheck keylayout k "ESC") || (keyCheck keylayout k "SPC") || (keyCheck keylayout k "RET")))) $ do
let newinp = (stateShellInput state) ++ inpkey
modify $ \s -> s { stateShellInput = newinp }
return ()
-- case function for when a key repeats
evalKeyHeld :: GLFW.Window -> GLFW.Key -> GLFW.KeyState -> GLFW.ModifierKeys -> Game ()
evalKeyHeld window k ks mk = do
state <- get
env <- ask
inpkey <- liftIO $ calcInpKey k mk
let settings = stateSettings state
let keylayout = settingKeyLayout settings
let gs = stateGame state
-- moves orthographically when the movement keys are held
when ((gs == SWorld) && ((keyCheck keylayout k "LFT") || (keyCheck keylayout k "RGT") || (keyCheck keylayout k "UPP") || (keyCheck keylayout k "DWN"))) $ do
when ((gs == SWorld) && (keyCheck keylayout k "LFT")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5 else 1
modify $ \s -> s { stateCursor = (moveCursor step (stateCursor state) (settingGridW settings) (settingGridH settings) West) }
when ((gs == SWorld) && (keyCheck keylayout k "RGT")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5 else 1
modify $ \s -> s { stateCursor = (moveCursor step (stateCursor state) (settingGridW settings) (settingGridH settings) East) }
when ((gs == SWorld) && (keyCheck keylayout k "UPP")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5 else 1
modify $ \s -> s { stateCursor = (moveCursor step (stateCursor state) (settingGridW settings) (settingGridH settings) North) }
when ((gs == SWorld) && (keyCheck keylayout k "DWN")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5 else 1
modify $ \s -> s { stateCursor = (moveCursor step (stateCursor state) (settingGridW settings) (settingGridH settings) South) }
return ()
-- moves orthographically when the camera keys are held
when ((gs == SZone) && ((keyCheck keylayout k "CL") || (keyCheck keylayout k "CR") || (keyCheck keylayout k "CU") || (keyCheck keylayout k "CD"))) $ do
when ((gs == SZone) && (keyCheck keylayout k "CL")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5.0 else 1.0
let newcam = moveCam DLeft step (stateZoneCam state)
modify $ \s -> s { stateZoneCam = newcam }
when ((gs == SZone) && (keyCheck keylayout k "CR")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5.0 else 1.0
let newcam = moveCam DRight step (stateZoneCam state)
modify $ \s -> s { stateZoneCam = newcam }
when ((gs == SZone) && (keyCheck keylayout k "CU")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5.0 else 1.0
let newcam = moveCam DUp step (stateZoneCam state)
modify $ \s -> s { stateZoneCam = newcam }
when ((gs == SZone) && (keyCheck keylayout k "CD")) $ do
let step = if (GLFW.modifierKeysShift mk) then 5.0 else 1.0
let newcam = moveCam DDown step (stateZoneCam state)
modify $ \s -> s { stateZoneCam = newcam }
return ()
-- checks key with settings
keyCheck :: KeyLayout -> GLFW.Key -> String -> Bool
keyCheck keylayout k str = (k == (GLFW.getGLFWKey nk))
where nk = getKey keylayout str
-- retrieves user key setting
getKey :: KeyLayout -> String -> String
getKey keylayout "ESC" = keyESC keylayout
getKey keylayout "RET" = keyRET keylayout
getKey keylayout "DEL" = keyDEL keylayout
getKey keylayout "SPC" = keySPC keylayout
getKey keylayout "C" = keyC keylayout
getKey keylayout "R" = keyR keylayout
getKey keylayout "`" = keySh keylayout
getKey keylayout "LFT" = keyLFT keylayout
getKey keylayout "RGT" = keyRGT keylayout
getKey keylayout "UPP" = keyUPP keylayout
getKey keylayout "DWN" = keyDWN keylayout
getKey keylayout "CL" = keyCL keylayout
getKey keylayout "CR" = keyCR keylayout
getKey keylayout "CU" = keyCU keylayout
getKey keylayout "CD" = keyCD keylayout
getKey keylayout _ = "NULL"
-- returns the char for a glkey
calcInpKey :: GLFW.Key -> GLFW.ModifierKeys -> IO String
calcInpKey k mk = do
inp <- GLFW.getKeyStr k
case (inp) of
Just str -> return $ applyMod mk str
Nothing -> return ""
-- makes letters capital when shift is held down
applyMod :: GLFW.ModifierKeys -> String -> String
applyMod mk str = if (GLFW.modifierKeysShift mk) then map myUpper str
else str
-- toUpper wrapper to add numeric keys
myUpper :: Char -> Char
myUpper '1' = '!'
myUpper '2' = '@'
myUpper '3' = '#'
myUpper '4' = '$'
myUpper '5' = '%'
myUpper '6' = '^'
myUpper '7' = '&'
myUpper '8' = '*'
myUpper '9' = '('
myUpper '0' = ')'
myUpper '-' = '_'
myUpper '=' = '+'
myUpper '[' = '{'
myUpper ']' = '}'
myUpper '\\' = '|'
myUpper ';' = ':'
myUpper '\'' = '"'
myUpper ',' = '<'
myUpper '.' = '>'
myUpper '/' = '?'
myUpper c = toUpper c
-- evaluates mouse input
evalMouse :: GLFW.Window -> GLFW.MouseButton -> GLFW.MouseButtonState -> GLFW.ModifierKeys -> Game ()
evalMouse win mb mbs mk = do
state <- get
when (((stateGame state) == SWorld) && (mb == GLFW.mousebutt1)) $ do
(x, y) <- liftIO $ GLFW.getCursorPos win
liftIO . print $ "x: " ++ (show x) ++ " y: " ++ (show y)
-- evaluates mouse scrolling
evalScroll :: GLFW.Window -> Double -> Double -> Game ()
evalScroll win x y = do
state <- get
when (((stateGame state) == SZone)) $ do
let zoom = (stateZoom state) + (10*(realToFrac y))
modify $ \s -> s { stateZoom = zoom }
| coghex/abridgefaraway | src/ABFA/Input.hs | bsd-3-clause | 12,920 | 0 | 22 | 3,082 | 4,849 | 2,431 | 2,418 | 234 | 9 |
{-# LANGUAGE TemplateHaskell #-}
module Control.Isomorphism.Partial.Constructors
( nil
, cons
, listCases
, left
, right
, nothing
, just
) where
import Prelude hiding ((.), id)
import Control.Category ((.), id)
import Data.Bool (Bool, otherwise)
import Data.Either (Either (Left, Right))
import Data.Eq (Eq ((==)))
import Data.Maybe (Maybe (Just, Nothing))
import Control.Isomorphism.Partial.Iso
import Control.Isomorphism.Partial.TH (defineIsomorphisms)
nil :: Iso () [alpha]
nil = unsafeMakeNamedIso "nil" f g where
f () = Just []
g [] = Just ()
g _ = Nothing
cons :: Iso (alpha, [alpha]) [alpha]
cons = unsafeMakeNamedIso "cons" f g where
f (x, xs) = Just (x : xs)
g (x : xs) = Just (x, xs)
g _ = Nothing
listCases :: Iso (Either () (alpha, [alpha])) [alpha]
listCases = unsafeMakeNamedIso "listCases" f g
where
f (Left ()) = Just []
f (Right (x, xs)) = Just (x : xs)
g [] = Just (Left ())
g (x:xs) = Just (Right (x, xs))
$(defineIsomorphisms ''Either)
$(defineIsomorphisms ''Maybe)
| skogsbaer/roundtrip | src/Control/Isomorphism/Partial/Constructors.hs | bsd-3-clause | 1,097 | 0 | 10 | 270 | 472 | 266 | 206 | 35 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{- |
Module : Example.LiftedTypes
Description : Lifted Types to make state machine functions more type safe
Copyright : (c) Plow Technologies
License : MIT License
Maintainer : Scott Murphy
Stability : unstable
Portability : non-portable (System.Posix)
-}
module Example.LiftedTypes (
Alive (..) ,
Dead (..) ,
OnScreen (..) ,
OffScreen (..) ,
Haunting (..) ,
Happy (..)
) where
data Status a s g = Status {
alive :: a ,
onScreen :: s,
ghost :: g
} deriving (Eq, Ord, Show)
data Alive = Alive deriving (Eq, Ord, Show, Bounded, Enum)
data Dead = Dead deriving (Eq, Ord, Show, Bounded, Enum)
data OnScreen = OnScreen deriving (Eq, Ord, Show, Bounded, Enum)
data OffScreen = OffScreen deriving (Eq, Ord, Show, Bounded, Enum)
data Haunting = Haunting deriving (Eq, Ord, Show, Bounded, Enum)
data Happy = Happy deriving (Eq, Ord, Show, Bounded, Enum)
| smurphy8/refactor-patternmatch-with-lens | src/Example/LiftedTypes.hs | bsd-3-clause | 990 | 0 | 8 | 257 | 277 | 161 | 116 | 19 | 0 |
{-# LANGUAGE TypeFamilies #-}
{-|
Module : Numeric.AERN.RealArithmetic.Basis.MPFR
Description : Instances for MPFR as interval endpoints.
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable (indirect FFI)
Instances of MPFR required for serving as interval endpoints,
namely providing granularity, Comparison, lattice, rounded field and
rounded elementary operations.
-}
module Numeric.AERN.RealArithmetic.Basis.MPFR
(
-- MPFR, MPFRPrec,
module Numeric.AERN.RealArithmetic.Basis.MPFR.Basics,
module Numeric.AERN.RealArithmetic.Basis.MPFR.ShowInternals,
module Numeric.AERN.RealArithmetic.Basis.MPFR.NumericOrder,
module Numeric.AERN.RealArithmetic.Basis.MPFR.Conversion,
module Numeric.AERN.RealArithmetic.Basis.MPFR.FieldOps,
module Numeric.AERN.RealArithmetic.Basis.MPFR.MixedFieldOps,
module Numeric.AERN.RealArithmetic.Basis.MPFR.SpecialConst,
module Numeric.AERN.RealArithmetic.Basis.MPFR.Elementary,
module Numeric.AERN.RealArithmetic.Basis.MPFR.Measures,
module Numeric.AERN.RealArithmetic.Basis.MPFR.ExactOps
)
where
import Numeric.AERN.RealArithmetic.Basis.MPFR.Basics
import Numeric.AERN.RealArithmetic.Basis.MPFR.ShowInternals
import Numeric.AERN.RealArithmetic.Basis.MPFR.NumericOrder
import Numeric.AERN.RealArithmetic.Basis.MPFR.Conversion
import Numeric.AERN.RealArithmetic.Basis.MPFR.FieldOps
import Numeric.AERN.RealArithmetic.Basis.MPFR.MixedFieldOps
import Numeric.AERN.RealArithmetic.Basis.MPFR.SpecialConst
import Numeric.AERN.RealArithmetic.Basis.MPFR.Elementary
import Numeric.AERN.RealArithmetic.Basis.MPFR.Measures
import Numeric.AERN.RealArithmetic.Basis.MPFR.ExactOps
import Numeric.AERN.RealArithmetic.NumericOrderRounding
import Numeric.AERN.Basics.Effort
import Numeric.AERN.Basics.Exception
import Data.Word
instance RoundedReal MPFR where
type RoundedRealEffortIndicator MPFR = ()
roundedRealDefaultEffort _ = ()
rrEffortComp _ _ = ()
rrEffortMinmax _ _ = ()
rrEffortDistance _ p = ()
rrEffortToSelf _ _ = ()
rrEffortToInt _ _ = ()
rrEffortFromInt _ p = ()
rrEffortToInteger _ _ = ()
rrEffortFromInteger _ p = ()
rrEffortToDouble _ _ = ()
rrEffortFromDouble _ p = ()
rrEffortToRational _ _ = ()
rrEffortFromRational _ p = ()
rrEffortAbs _ _ = ()
rrEffortField _ p = ()
rrEffortIntMixedField _ _ = ()
rrEffortIntegerMixedField _ _ = ()
rrEffortDoubleMixedField _ _ = ()
rrEffortRationalMixedField _ _ = ()
instance HasLegalValues MPFR where
maybeGetProblem d@(MPFR v)
| isNaN v = Just "A NaN MPFR"
-- | d == 1/0 = False
-- | d == -1/0 = False
| otherwise = Nothing
| michalkonecny/aern | aern-mpfr-rounded/src/Numeric/AERN/RealArithmetic/Basis/MPFR.hs | bsd-3-clause | 2,807 | 0 | 9 | 484 | 523 | 325 | 198 | 52 | 0 |
module Game
(play)
where
import ChessBoard
import Elements
import Input
turn :: Board -> Player -> IO ()
turn board player = do
showBoard board
putStrLn $ "Ruch mają "++ showPl player
-- TODO: catch exception
(from,to,mode) <- getCords board player
let newBoard = mkMove board from to mode
if (hasWinner newBoard) /= None
then
putStrLn $ "Zwyciezca sa " ++ showPl (hasWinner board)
else
turn newBoard (inverse player)
-- | Start game. Use standart initial board. White player begin
play :: IO ()
play = turn (readBoard initialBoardStr) WhitePl
initialBoardStr = [ " X X X X"
,"X X X X "
," "
," "
," "
," "
," O O O O"
,"O O O O "
]
| leskiw77/Checkers | src/Game.hs | bsd-3-clause | 862 | 0 | 11 | 350 | 211 | 111 | 100 | 24 | 2 |
{-| The Parser for the reflex-jsx language
Given a "String", @parseJsx@ outputs the AST for the language. Note that at
this point, we capture spliced expressions from the meta-language as
Strings, and parse them during the quasiquoting phase in @ReflexJsx.QQ@
-}
module ReflexJsx.Parser
( parseJsx
, Node(..)
, Attrs(..)
, AttrValue(..)
) where
import Text.Parsec (runParser, Parsec, try, eof, many, many1, between)
import Text.Parsec.Char (char, letter, noneOf, string, alphaNum, spaces)
import Control.Applicative ((<|>))
data AttrValue = TextVal String
| ExprVal String
data Attrs = SplicedAttrs String
| StaticAttrs [(String, AttrValue)]
data Node = Node String Attrs [Node]
| Text String
| SplicedNode String
parseJsx :: Monad m => String -> m Node
parseJsx s =
case runParser p () "" s of
Left err -> fail $ show err
Right e -> return e
where p = do
spaces
node <- jsxElement
spaces
eof
return node
jsxElement :: Parsec String u Node
jsxElement = do
try jsxSelfClosingElement <|> jsxNormalElement
jsxSelfClosingElement :: Parsec String u Node
jsxSelfClosingElement = do
_ <- char '<'
name <- jsxElementName
attrs <- jsxNodeAttrs
_ <- string "/>"
return (Node name attrs [])
jsxNormalElement :: Parsec String u Node
jsxNormalElement = do
(name, attrs) <- jsxOpeningElement
children <- many jsxChild
jsxClosingElement name
return (Node name attrs children)
jsxOpeningElement :: Parsec String u (String, Attrs)
jsxOpeningElement = do
_ <- char '<'
name <- jsxElementName
attrs <- jsxNodeAttrs
_ <- char '>'
return (name, attrs)
jsxNodeAttrs :: Parsec String u Attrs
jsxNodeAttrs = do
try jsxSplicedAttrMap <|> (StaticAttrs <$> many jsxNodeAttr)
jsxSplicedAttrMap :: Parsec String u Attrs
jsxSplicedAttrMap = do
name <- between (string "{...") (string "}") $ many (noneOf "}")
return $ SplicedAttrs name
jsxNodeAttr :: Parsec String u (String, AttrValue)
jsxNodeAttr = do
key <- jsxAttributeName
spaces
_ <- char '='
spaces
value <- jsxQuotedValue <|> jsxSplicedValue
spaces
return (key, value)
jsxAttributeName :: Parsec String u String
jsxAttributeName = do
many $ letter <|> char '-'
jsxQuotedValue :: Parsec String u AttrValue
jsxQuotedValue = do
contents <- between (char '"') (char '"') $ many (noneOf "\"")
return $ TextVal contents
jsxSplicedValue :: Parsec String u AttrValue
jsxSplicedValue = do
name <- between (char '{') (char '}') $ many (noneOf "}")
return $ ExprVal name
jsxClosingElement :: String -> Parsec String u ()
jsxClosingElement ele = do
_ <- string "</" *> string ele *> char '>'
return ()
jsxChild :: Parsec String u Node
jsxChild = do
try jsxText <|> try jsxSplicedNode <|> try jsxElement
jsxText :: Parsec String u Node
jsxText = do
contents <- many1 $ noneOf "{<>}"
return $ Text contents
jsxSplicedNode :: Parsec String u Node
jsxSplicedNode = do
exprString <- between (char '{') (char '}') $ many (noneOf "}")
return $ SplicedNode exprString
jsxElementName :: Parsec String u String
jsxElementName = jsxIdentifier
jsxIdentifier :: Parsec String u String
jsxIdentifier = do
name <- many1 alphaNum
spaces
return name
| dackerman/reflex-jsx | src/ReflexJsx/Parser.hs | bsd-3-clause | 3,327 | 0 | 11 | 756 | 1,073 | 527 | 546 | 98 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Desugaring exporessions.
-}
{-# LANGUAGE CPP #-}
module DsExpr ( dsExpr, dsLExpr, dsLocalBinds
, dsValBinds, dsLit, dsSyntaxExpr ) where
#include "HsVersions.h"
import Match
import MatchLit
import DsBinds
import DsGRHSs
import DsListComp
import DsUtils
import DsArrows
import DsMonad
import Name
import NameEnv
import FamInstEnv( topNormaliseType )
import DsMeta
import HsSyn
import Platform
-- NB: The desugarer, which straddles the source and Core worlds, sometimes
-- needs to see source types
import TcType
import TcEvidence
import TcRnMonad
import TcHsSyn
import Type
import CoreSyn
import CoreUtils
import MkCore
import DynFlags
import CostCentre
import Id
import Module
import ConLike
import DataCon
import TysWiredIn
import PrelNames
import BasicTypes
import Maybes
import VarEnv
import SrcLoc
import Util
import Bag
import Outputable
import FastString
import PatSyn
import IfaceEnv
import Data.IORef ( atomicModifyIORef', modifyIORef )
import Control.Monad
import GHC.Fingerprint
{-
************************************************************************
* *
dsLocalBinds, dsValBinds
* *
************************************************************************
-}
dsLocalBinds :: HsLocalBinds Id -> CoreExpr -> DsM CoreExpr
dsLocalBinds EmptyLocalBinds body = return body
dsLocalBinds (HsValBinds binds) body = dsValBinds binds body
dsLocalBinds (HsIPBinds binds) body = dsIPBinds binds body
-------------------------
dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr
dsValBinds (ValBindsOut binds _) body = foldrM ds_val_bind body binds
dsValBinds (ValBindsIn {}) _ = panic "dsValBinds ValBindsIn"
-------------------------
dsIPBinds :: HsIPBinds Id -> CoreExpr -> DsM CoreExpr
dsIPBinds (IPBinds ip_binds ev_binds) body
= do { ds_binds <- dsTcEvBinds ev_binds
; let inner = mkCoreLets ds_binds body
-- The dict bindings may not be in
-- dependency order; hence Rec
; foldrM ds_ip_bind inner ip_binds }
where
ds_ip_bind (L _ (IPBind ~(Right n) e)) body
= do e' <- dsLExpr e
return (Let (NonRec n e') body)
-------------------------
ds_val_bind :: (RecFlag, LHsBinds Id) -> CoreExpr -> DsM CoreExpr
-- Special case for bindings which bind unlifted variables
-- We need to do a case right away, rather than building
-- a tuple and doing selections.
-- Silently ignore INLINE and SPECIALISE pragmas...
ds_val_bind (NonRecursive, hsbinds) body
| [L loc bind] <- bagToList hsbinds,
-- Non-recursive, non-overloaded bindings only come in ones
-- ToDo: in some bizarre case it's conceivable that there
-- could be dict binds in the 'binds'. (See the notes
-- below. Then pattern-match would fail. Urk.)
unliftedMatchOnly bind
= putSrcSpanDs loc (dsUnliftedBind bind body)
-- Ordinary case for bindings; none should be unlifted
ds_val_bind (_is_rec, binds) body
= do { (force_vars,prs) <- dsLHsBinds binds
; let body' = foldr seqVar body force_vars
; ASSERT2( not (any (isUnliftedType . idType . fst) prs), ppr _is_rec $$ ppr binds )
case prs of
[] -> return body
_ -> return (Let (Rec prs) body') }
-- Use a Rec regardless of is_rec.
-- Why? Because it allows the binds to be all
-- mixed up, which is what happens in one rare case
-- Namely, for an AbsBind with no tyvars and no dicts,
-- but which does have dictionary bindings.
-- See notes with TcSimplify.inferLoop [NO TYVARS]
-- It turned out that wrapping a Rec here was the easiest solution
--
-- NB The previous case dealt with unlifted bindings, so we
-- only have to deal with lifted ones now; so Rec is ok
------------------
dsUnliftedBind :: HsBind Id -> CoreExpr -> DsM CoreExpr
dsUnliftedBind (AbsBinds { abs_tvs = [], abs_ev_vars = []
, abs_exports = exports
, abs_ev_binds = ev_binds
, abs_binds = lbinds }) body
= do { let body1 = foldr bind_export body exports
bind_export export b = bindNonRec (abe_poly export) (Var (abe_mono export)) b
; body2 <- foldlBagM (\body lbind -> dsUnliftedBind (unLoc lbind) body)
body1 lbinds
; ds_binds <- dsTcEvBinds_s ev_binds
; return (mkCoreLets ds_binds body2) }
dsUnliftedBind (AbsBindsSig { abs_tvs = []
, abs_ev_vars = []
, abs_sig_export = poly
, abs_sig_ev_bind = ev_bind
, abs_sig_bind = L _ bind }) body
= do { ds_binds <- dsTcEvBinds ev_bind
; body' <- dsUnliftedBind (bind { fun_id = noLoc poly }) body
; return (mkCoreLets ds_binds body') }
dsUnliftedBind (FunBind { fun_id = L _ fun
, fun_matches = matches
, fun_co_fn = co_fn
, fun_tick = tick }) body
-- Can't be a bang pattern (that looks like a PatBind)
-- so must be simply unboxed
= do { (args, rhs) <- matchWrapper (FunRhs (idName fun)) Nothing matches
; MASSERT( null args ) -- Functions aren't lifted
; MASSERT( isIdHsWrapper co_fn )
; let rhs' = mkOptTickBox tick rhs
; return (bindNonRec fun rhs' body) }
dsUnliftedBind (PatBind {pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }) body
= -- let C x# y# = rhs in body
-- ==> case rhs of C x# y# -> body
do { rhs <- dsGuarded grhss ty
; let upat = unLoc pat
eqn = EqnInfo { eqn_pats = [upat],
eqn_rhs = cantFailMatchResult body }
; var <- selectMatchVar upat
; result <- matchEquations PatBindRhs [var] [eqn] (exprType body)
; return (bindNonRec var rhs result) }
dsUnliftedBind bind body = pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
----------------------
unliftedMatchOnly :: HsBind Id -> Bool
unliftedMatchOnly (AbsBinds { abs_binds = lbinds })
= anyBag (unliftedMatchOnly . unLoc) lbinds
unliftedMatchOnly (AbsBindsSig { abs_sig_bind = L _ bind })
= unliftedMatchOnly bind
unliftedMatchOnly (PatBind { pat_lhs = lpat, pat_rhs_ty = rhs_ty })
= isUnliftedType rhs_ty
|| isUnliftedLPat lpat
|| any (isUnliftedType . idType) (collectPatBinders lpat)
unliftedMatchOnly (FunBind { fun_id = L _ id })
= isUnliftedType (idType id)
unliftedMatchOnly _ = False -- I hope! Checked immediately by caller in fact
{-
************************************************************************
* *
\subsection[DsExpr-vars-and-cons]{Variables, constructors, literals}
* *
************************************************************************
-}
dsLExpr :: LHsExpr Id -> DsM CoreExpr
dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e
dsExpr :: HsExpr Id -> DsM CoreExpr
dsExpr (HsPar e) = dsLExpr e
dsExpr (ExprWithTySigOut e _) = dsLExpr e
dsExpr (HsVar (L _ var)) = return (varToCoreExpr var)
-- See Note [Desugaring vars]
dsExpr (HsUnboundVar {}) = panic "dsExpr: HsUnboundVar" -- Typechecker eliminates them
dsExpr (HsIPVar _) = panic "dsExpr: HsIPVar"
dsExpr (HsOverLabel _) = panic "dsExpr: HsOverLabel"
dsExpr (HsLit lit) = dsLit lit
dsExpr (HsOverLit lit) = dsOverLit lit
dsExpr (HsWrap co_fn e)
= do { e' <- dsExpr e
; wrapped_e <- dsHsWrapper co_fn e'
; dflags <- getDynFlags
; warnAboutIdentities dflags e' (exprType wrapped_e)
; return wrapped_e }
dsExpr (NegApp expr neg_expr)
= do { expr' <- dsLExpr expr
; dsSyntaxExpr neg_expr [expr'] }
dsExpr (HsLam a_Match)
= uncurry mkLams <$> matchWrapper LambdaExpr Nothing a_Match
dsExpr (HsLamCase arg matches)
= do { arg_var <- newSysLocalDs arg
; ([discrim_var], matching_code) <- matchWrapper CaseAlt Nothing matches
; return $ Lam arg_var $ bindNonRec discrim_var (Var arg_var) matching_code }
dsExpr e@(HsApp fun arg)
= mkCoreAppDs (text "HsApp" <+> ppr e) <$> dsLExpr fun <*> dsLExpr arg
dsExpr (HsAppTypeOut e _)
-- ignore type arguments here; they're in the wrappers instead at this point
= dsLExpr e
{-
Note [Desugaring vars]
~~~~~~~~~~~~~~~~~~~~~~
In one situation we can get a *coercion* variable in a HsVar, namely
the support method for an equality superclass:
class (a~b) => C a b where ...
instance (blah) => C (T a) (T b) where ..
Then we get
$dfCT :: forall ab. blah => C (T a) (T b)
$dfCT ab blah = MkC ($c$p1C a blah) ($cop a blah)
$c$p1C :: forall ab. blah => (T a ~ T b)
$c$p1C ab blah = let ...; g :: T a ~ T b = ... } in g
That 'g' in the 'in' part is an evidence variable, and when
converting to core it must become a CO.
Operator sections. At first it looks as if we can convert
\begin{verbatim}
(expr op)
\end{verbatim}
to
\begin{verbatim}
\x -> op expr x
\end{verbatim}
But no! expr might be a redex, and we can lose laziness badly this
way. Consider
\begin{verbatim}
map (expr op) xs
\end{verbatim}
for example. So we convert instead to
\begin{verbatim}
let y = expr in \x -> op y x
\end{verbatim}
If \tr{expr} is actually just a variable, say, then the simplifier
will sort it out.
-}
dsExpr e@(OpApp e1 op _ e2)
= -- for the type of y, we need the type of op's 2nd argument
mkCoreAppsDs (text "opapp" <+> ppr e) <$> dsLExpr op <*> mapM dsLExpr [e1, e2]
dsExpr (SectionL expr op) -- Desugar (e !) to ((!) e)
= mkCoreAppDs (text "sectionl" <+> ppr expr) <$> dsLExpr op <*> dsLExpr expr
-- dsLExpr (SectionR op expr) -- \ x -> op x expr
dsExpr e@(SectionR op expr) = do
core_op <- dsLExpr op
-- for the type of x, we need the type of op's 2nd argument
let (x_ty:y_ty:_, _) = splitFunTys (exprType core_op)
-- See comment with SectionL
y_core <- dsLExpr expr
x_id <- newSysLocalDs x_ty
y_id <- newSysLocalDs y_ty
return (bindNonRec y_id y_core $
Lam x_id (mkCoreAppsDs (text "sectionr" <+> ppr e) core_op [Var x_id, Var y_id]))
dsExpr (ExplicitTuple tup_args boxity)
= do { let go (lam_vars, args) (L _ (Missing ty))
-- For every missing expression, we need
-- another lambda in the desugaring.
= do { lam_var <- newSysLocalDs ty
; return (lam_var : lam_vars, Var lam_var : args) }
go (lam_vars, args) (L _ (Present expr))
-- Expressions that are present don't generate
-- lambdas, just arguments.
= do { core_expr <- dsLExpr expr
; return (lam_vars, core_expr : args) }
; (lam_vars, args) <- foldM go ([], []) (reverse tup_args)
-- The reverse is because foldM goes left-to-right
; return $ mkCoreLams lam_vars $
mkCoreTupBoxity boxity args }
dsExpr (HsSCC _ cc expr@(L loc _)) = do
dflags <- getDynFlags
if gopt Opt_SccProfilingOn dflags
then do
mod_name <- getModule
count <- goptM Opt_ProfCountEntries
uniq <- newUnique
Tick (ProfNote (mkUserCC (sl_fs cc) mod_name loc uniq) count True)
<$> dsLExpr expr
else dsLExpr expr
dsExpr (HsCoreAnn _ _ expr)
= dsLExpr expr
dsExpr (HsCase discrim matches)
= do { core_discrim <- dsLExpr discrim
; ([discrim_var], matching_code) <- matchWrapper CaseAlt (Just discrim) matches
; return (bindNonRec discrim_var core_discrim matching_code) }
-- Pepe: The binds are in scope in the body but NOT in the binding group
-- This is to avoid silliness in breakpoints
dsExpr (HsLet (L _ binds) body) = do
body' <- dsLExpr body
dsLocalBinds binds body'
-- We need the `ListComp' form to use `deListComp' (rather than the "do" form)
-- because the interpretation of `stmts' depends on what sort of thing it is.
--
dsExpr (HsDo ListComp (L _ stmts) res_ty) = dsListComp stmts res_ty
dsExpr (HsDo PArrComp (L _ stmts) _) = dsPArrComp (map unLoc stmts)
dsExpr (HsDo DoExpr (L _ stmts) _) = dsDo stmts
dsExpr (HsDo GhciStmtCtxt (L _ stmts) _) = dsDo stmts
dsExpr (HsDo MDoExpr (L _ stmts) _) = dsDo stmts
dsExpr (HsDo MonadComp (L _ stmts) _) = dsMonadComp stmts
dsExpr (HsIf mb_fun guard_expr then_expr else_expr)
= do { pred <- dsLExpr guard_expr
; b1 <- dsLExpr then_expr
; b2 <- dsLExpr else_expr
; case mb_fun of
Just fun -> dsSyntaxExpr fun [pred, b1, b2]
Nothing -> return $ mkIfThenElse pred b1 b2 }
dsExpr (HsMultiIf res_ty alts)
| null alts
= mkErrorExpr
| otherwise
= do { match_result <- liftM (foldr1 combineMatchResults)
(mapM (dsGRHS IfAlt res_ty) alts)
; error_expr <- mkErrorExpr
; extractMatchResult match_result error_expr }
where
mkErrorExpr = mkErrorAppDs nON_EXHAUSTIVE_GUARDS_ERROR_ID res_ty
(text "multi-way if")
{-
\noindent
\underline{\bf Various data construction things}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-}
dsExpr (ExplicitList elt_ty wit xs)
= dsExplicitList elt_ty wit xs
-- We desugar [:x1, ..., xn:] as
-- singletonP x1 +:+ ... +:+ singletonP xn
--
dsExpr (ExplicitPArr ty []) = do
emptyP <- dsDPHBuiltin emptyPVar
return (Var emptyP `App` Type ty)
dsExpr (ExplicitPArr ty xs) = do
singletonP <- dsDPHBuiltin singletonPVar
appP <- dsDPHBuiltin appPVar
xs' <- mapM dsLExpr xs
let unary fn x = mkApps (Var fn) [Type ty, x]
binary fn x y = mkApps (Var fn) [Type ty, x, y]
return . foldr1 (binary appP) $ map (unary singletonP) xs'
dsExpr (ArithSeq expr witness seq)
= case witness of
Nothing -> dsArithSeq expr seq
Just fl -> do { newArithSeq <- dsArithSeq expr seq
; dsSyntaxExpr fl [newArithSeq] }
dsExpr (PArrSeq expr (FromTo from to))
= mkApps <$> dsExpr expr <*> mapM dsLExpr [from, to]
dsExpr (PArrSeq expr (FromThenTo from thn to))
= mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn, to]
dsExpr (PArrSeq _ _)
= panic "DsExpr.dsExpr: Infinite parallel array!"
-- the parser shouldn't have generated it and the renamer and typechecker
-- shouldn't have let it through
{-
\noindent
\underline{\bf Static Pointers}
~~~~~~~~~~~~~~~
\begin{verbatim}
g = ... static f ...
==>
sptEntry:N = StaticPtr
(fingerprintString "pkgKey:module.sptEntry:N")
(StaticPtrInfo "current pkg key" "current module" "sptEntry:0")
f
g = ... sptEntry:N
\end{verbatim}
-}
dsExpr (HsStatic expr@(L loc _)) = do
expr_ds <- dsLExpr expr
let ty = exprType expr_ds
n' <- mkSptEntryName loc
static_binds_var <- dsGetStaticBindsVar
staticPtrTyCon <- dsLookupTyCon staticPtrTyConName
staticPtrInfoDataCon <- dsLookupDataCon staticPtrInfoDataConName
staticPtrDataCon <- dsLookupDataCon staticPtrDataConName
fingerprintDataCon <- dsLookupDataCon fingerprintDataConName
dflags <- getDynFlags
let (line, col) = case loc of
RealSrcSpan r -> ( srcLocLine $ realSrcSpanStart r
, srcLocCol $ realSrcSpanStart r
)
_ -> (0, 0)
srcLoc = mkCoreConApps (tupleDataCon Boxed 2)
[ Type intTy , Type intTy
, mkIntExprInt dflags line, mkIntExprInt dflags col
]
info <- mkConApp staticPtrInfoDataCon <$>
(++[srcLoc]) <$>
mapM mkStringExprFS
[ unitIdFS $ moduleUnitId $ nameModule n'
, moduleNameFS $ moduleName $ nameModule n'
, occNameFS $ nameOccName n'
]
let tvars = tyCoVarsOfTypeWellScoped ty
speTy = ASSERT( all isTyVar tvars ) -- ty is top-level, so this is OK
mkInvForAllTys tvars $ mkTyConApp staticPtrTyCon [ty]
speId = mkExportedVanillaId n' speTy
fp@(Fingerprint w0 w1) = fingerprintName $ idName speId
fp_core = mkConApp fingerprintDataCon
[ mkWord64LitWordRep dflags w0
, mkWord64LitWordRep dflags w1
]
sp = mkConApp staticPtrDataCon [Type ty, fp_core, info, expr_ds]
liftIO $ modifyIORef static_binds_var ((fp, (speId, mkLams tvars sp)) :)
putSrcSpanDs loc $ return $ mkTyApps (Var speId) (mkTyVarTys tvars)
where
-- | Choose either 'Word64#' or 'Word#' to represent the arguments of the
-- 'Fingerprint' data constructor.
mkWord64LitWordRep dflags
| platformWordSize (targetPlatform dflags) < 8 = mkWord64LitWord64
| otherwise = mkWordLit dflags . toInteger
fingerprintName :: Name -> Fingerprint
fingerprintName n = fingerprintString $ unpackFS $ concatFS
[ unitIdFS $ moduleUnitId $ nameModule n
, fsLit ":"
, moduleNameFS (moduleName $ nameModule n)
, fsLit "."
, occNameFS $ occName n
]
{-
\noindent
\underline{\bf Record construction and update}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For record construction we do this (assuming T has three arguments)
\begin{verbatim}
T { op2 = e }
==>
let err = /\a -> recConErr a
T (recConErr t1 "M.hs/230/op1")
e
(recConErr t1 "M.hs/230/op3")
\end{verbatim}
@recConErr@ then converts its argument string into a proper message
before printing it as
\begin{verbatim}
M.hs, line 230: missing field op1 was evaluated
\end{verbatim}
We also handle @C{}@ as valid construction syntax for an unlabelled
constructor @C@, setting all of @C@'s fields to bottom.
-}
dsExpr (RecordCon { rcon_con_expr = con_expr, rcon_flds = rbinds
, rcon_con_like = con_like })
= do { con_expr' <- dsExpr con_expr
; let
(arg_tys, _) = tcSplitFunTys (exprType con_expr')
-- A newtype in the corner should be opaque;
-- hence TcType.tcSplitFunTys
mk_arg (arg_ty, fl)
= case findField (rec_flds rbinds) (flSelector fl) of
(rhs:rhss) -> ASSERT( null rhss )
dsLExpr rhs
[] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (ppr (flLabel fl))
unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty Outputable.empty
labels = conLikeFieldLabels con_like
; con_args <- if null labels
then mapM unlabelled_bottom arg_tys
else mapM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels)
; return (mkCoreApps con_expr' con_args) }
{-
Record update is a little harder. Suppose we have the decl:
\begin{verbatim}
data T = T1 {op1, op2, op3 :: Int}
| T2 {op4, op2 :: Int}
| T3
\end{verbatim}
Then we translate as follows:
\begin{verbatim}
r { op2 = e }
===>
let op2 = e in
case r of
T1 op1 _ op3 -> T1 op1 op2 op3
T2 op4 _ -> T2 op4 op2
other -> recUpdError "M.hs/230"
\end{verbatim}
It's important that we use the constructor Ids for @T1@, @T2@ etc on the
RHSs, and do not generate a Core constructor application directly, because the constructor
might do some argument-evaluation first; and may have to throw away some
dictionaries.
Note [Update for GADTs]
~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T a b where
T1 :: { f1 :: a } -> T a Int
Then the wrapper function for T1 has type
$WT1 :: a -> T a Int
But if x::T a b, then
x { f1 = v } :: T a b (not T a Int!)
So we need to cast (T a Int) to (T a b). Sigh.
-}
dsExpr expr@(RecordUpd { rupd_expr = record_expr, rupd_flds = fields
, rupd_cons = cons_to_upd
, rupd_in_tys = in_inst_tys, rupd_out_tys = out_inst_tys
, rupd_wrap = dict_req_wrap } )
| null fields
= dsLExpr record_expr
| otherwise
= ASSERT2( notNull cons_to_upd, ppr expr )
do { record_expr' <- dsLExpr record_expr
; field_binds' <- mapM ds_field fields
; let upd_fld_env :: NameEnv Id -- Maps field name to the LocalId of the field binding
upd_fld_env = mkNameEnv [(f,l) | (f,l,_) <- field_binds']
-- It's important to generate the match with matchWrapper,
-- and the right hand sides with applications of the wrapper Id
-- so that everything works when we are doing fancy unboxing on the
-- constructor aguments.
; alts <- mapM (mk_alt upd_fld_env) cons_to_upd
; ([discrim_var], matching_code)
<- matchWrapper RecUpd Nothing (MG { mg_alts = noLoc alts
, mg_arg_tys = [in_ty]
, mg_res_ty = out_ty, mg_origin = FromSource })
-- FromSource is not strictly right, but we
-- want incomplete pattern-match warnings
; return (add_field_binds field_binds' $
bindNonRec discrim_var record_expr' matching_code) }
where
ds_field :: LHsRecUpdField Id -> DsM (Name, Id, CoreExpr)
-- Clone the Id in the HsRecField, because its Name is that
-- of the record selector, and we must not make that a local binder
-- else we shadow other uses of the record selector
-- Hence 'lcl_id'. Cf Trac #2735
ds_field (L _ rec_field) = do { rhs <- dsLExpr (hsRecFieldArg rec_field)
; let fld_id = unLoc (hsRecUpdFieldId rec_field)
; lcl_id <- newSysLocalDs (idType fld_id)
; return (idName fld_id, lcl_id, rhs) }
add_field_binds [] expr = expr
add_field_binds ((_,b,r):bs) expr = bindNonRec b r (add_field_binds bs expr)
-- Awkwardly, for families, the match goes
-- from instance type to family type
(in_ty, out_ty) =
case (head cons_to_upd) of
RealDataCon data_con ->
let tycon = dataConTyCon data_con in
(mkTyConApp tycon in_inst_tys, mkFamilyTyConApp tycon out_inst_tys)
PatSynCon pat_syn ->
( patSynInstResTy pat_syn in_inst_tys
, patSynInstResTy pat_syn out_inst_tys)
mk_alt upd_fld_env con
= do { let (univ_tvs, ex_tvs, eq_spec,
prov_theta, _req_theta, arg_tys, _) = conLikeFullSig con
subst = zipTvSubst univ_tvs in_inst_tys
-- I'm not bothering to clone the ex_tvs
; eqs_vars <- mapM newPredVarDs (substTheta subst (eqSpecPreds eq_spec))
; theta_vars <- mapM newPredVarDs (substTheta subst prov_theta)
; arg_ids <- newSysLocalsDs (substTysUnchecked subst arg_tys)
; let field_labels = conLikeFieldLabels con
val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
field_labels arg_ids
mk_val_arg fl pat_arg_id
= nlHsVar (lookupNameEnv upd_fld_env (flSelector fl) `orElse` pat_arg_id)
-- SAFE: the typechecker will complain if the synonym is
-- not bidirectional
wrap_id = expectJust "dsExpr:mk_alt" (conLikeWrapId_maybe con)
inst_con = noLoc $ HsWrap wrap (HsVar (noLoc wrap_id))
-- Reconstruct with the WrapId so that unpacking happens
-- The order here is because of the order in `TcPatSyn`.
wrap = mkWpEvVarApps theta_vars <.>
dict_req_wrap <.>
mkWpTyApps (mkTyVarTys ex_tvs) <.>
mkWpTyApps [ ty
| (tv, ty) <- univ_tvs `zip` out_inst_tys
, not (tv `elemVarEnv` wrap_subst) ]
rhs = foldl (\a b -> nlHsApp a b) inst_con val_args
-- Tediously wrap the application in a cast
-- Note [Update for GADTs]
wrapped_rhs =
case con of
RealDataCon data_con ->
let
wrap_co =
mkTcTyConAppCo Nominal
(dataConTyCon data_con)
[ lookup tv ty
| (tv,ty) <- univ_tvs `zip` out_inst_tys ]
lookup univ_tv ty =
case lookupVarEnv wrap_subst univ_tv of
Just co' -> co'
Nothing -> mkTcReflCo Nominal ty
in if null eq_spec
then rhs
else mkLHsWrap (mkWpCastN wrap_co) rhs
-- eq_spec is always null for a PatSynCon
PatSynCon _ -> rhs
wrap_subst =
mkVarEnv [ (tv, mkTcSymCo (mkTcCoVarCo eq_var))
| (spec, eq_var) <- eq_spec `zip` eqs_vars
, let tv = eqSpecTyVar spec ]
req_wrap = dict_req_wrap <.> mkWpTyApps in_inst_tys
pat = noLoc $ ConPatOut { pat_con = noLoc con
, pat_tvs = ex_tvs
, pat_dicts = eqs_vars ++ theta_vars
, pat_binds = emptyTcEvBinds
, pat_args = PrefixCon $ map nlVarPat arg_ids
, pat_arg_tys = in_inst_tys
, pat_wrap = req_wrap }
; return (mkSimpleMatch [pat] wrapped_rhs) }
-- Here is where we desugar the Template Haskell brackets and escapes
-- Template Haskell stuff
dsExpr (HsRnBracketOut _ _) = panic "dsExpr HsRnBracketOut"
dsExpr (HsTcBracketOut x ps) = dsBracket x ps
dsExpr (HsSpliceE s) = pprPanic "dsExpr:splice" (ppr s)
-- Arrow notation extension
dsExpr (HsProc pat cmd) = dsProcExpr pat cmd
-- Hpc Support
dsExpr (HsTick tickish e) = do
e' <- dsLExpr e
return (Tick tickish e')
-- There is a problem here. The then and else branches
-- have no free variables, so they are open to lifting.
-- We need someway of stopping this.
-- This will make no difference to binary coverage
-- (did you go here: YES or NO), but will effect accurate
-- tick counting.
dsExpr (HsBinTick ixT ixF e) = do
e2 <- dsLExpr e
do { ASSERT(exprType e2 `eqType` boolTy)
mkBinaryTickBox ixT ixF e2
}
dsExpr (HsTickPragma _ _ _ expr) = do
dflags <- getDynFlags
if gopt Opt_Hpc dflags
then panic "dsExpr:HsTickPragma"
else dsLExpr expr
-- HsSyn constructs that just shouldn't be here:
dsExpr (ExprWithTySig {}) = panic "dsExpr:ExprWithTySig"
dsExpr (HsBracket {}) = panic "dsExpr:HsBracket"
dsExpr (HsArrApp {}) = panic "dsExpr:HsArrApp"
dsExpr (HsArrForm {}) = panic "dsExpr:HsArrForm"
dsExpr (EWildPat {}) = panic "dsExpr:EWildPat"
dsExpr (EAsPat {}) = panic "dsExpr:EAsPat"
dsExpr (EViewPat {}) = panic "dsExpr:EViewPat"
dsExpr (ELazyPat {}) = panic "dsExpr:ELazyPat"
dsExpr (HsAppType {}) = panic "dsExpr:HsAppType" -- removed by typechecker
dsExpr (HsDo {}) = panic "dsExpr:HsDo"
dsExpr (HsRecFld {}) = panic "dsExpr:HsRecFld"
------------------------------
dsSyntaxExpr :: SyntaxExpr Id -> [CoreExpr] -> DsM CoreExpr
dsSyntaxExpr (SyntaxExpr { syn_expr = expr
, syn_arg_wraps = arg_wraps
, syn_res_wrap = res_wrap })
arg_exprs
= do { args <- zipWithM dsHsWrapper arg_wraps arg_exprs
; fun <- dsExpr expr
; dsHsWrapper res_wrap $ mkApps fun args }
findField :: [LHsRecField Id arg] -> Name -> [arg]
findField rbinds sel
= [hsRecFieldArg fld | L _ fld <- rbinds
, sel == idName (unLoc $ hsRecFieldId fld) ]
{-
%--------------------------------------------------------------------
Note [Desugaring explicit lists]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Explicit lists are desugared in a cleverer way to prevent some
fruitless allocations. Essentially, whenever we see a list literal
[x_1, ..., x_n] we generate the corresponding expression in terms of
build:
Explicit lists (literals) are desugared to allow build/foldr fusion when
beneficial. This is a bit of a trade-off,
* build/foldr fusion can generate far larger code than the corresponding
cons-chain (e.g. see #11707)
* even when it doesn't produce more code, build can still fail to fuse,
requiring that the simplifier do more work to bring the expression
back into cons-chain form; this costs compile time
* when it works, fusion can be a significant win. Allocations are reduced
by up to 25% in some nofib programs. Specifically,
Program Size Allocs Runtime CompTime
rewrite +0.0% -26.3% 0.02 -1.8%
ansi -0.3% -13.8% 0.00 +0.0%
lift +0.0% -8.7% 0.00 -2.3%
At the moment we use a simple heuristic to determine whether build will be
fruitful: for small lists we assume the benefits of fusion will be worthwhile;
for long lists we assume that the benefits will be outweighted by the cost of
code duplication. This magic length threshold is @maxBuildLength@. Also, fusion
won't work at all if rewrite rules are disabled, so we don't use the build-based
desugaring in this case.
We used to have a more complex heuristic which would try to break the list into
"static" and "dynamic" parts and only build-desugar the dynamic part.
Unfortunately, determining "static-ness" reliably is a bit tricky and the
heuristic at times produced surprising behavior (see #11710) so it was dropped.
-}
{- | The longest list length which we will desugar using @build@.
This is essentially a magic number and its setting is unfortunate rather
arbitrary. The idea here, as mentioned in Note [Desugaring explicit lists],
is to avoid deforesting large static data into large(r) code. Ideally we'd
want a smaller threshold with larger consumers and vice-versa, but we have no
way of knowing what will be consuming our list in the desugaring impossible to
set generally correctly.
The effect of reducing this number will be that 'build' fusion is applied
less often. From a runtime performance perspective, applying 'build' more
liberally on "moderately" sized lists should rarely hurt and will often it can
only expose further optimization opportunities; if no fusion is possible it will
eventually get rule-rewritten back to a list). We do, however, pay in compile
time.
-}
maxBuildLength :: Int
maxBuildLength = 32
dsExplicitList :: Type -> Maybe (SyntaxExpr Id) -> [LHsExpr Id]
-> DsM CoreExpr
-- See Note [Desugaring explicit lists]
dsExplicitList elt_ty Nothing xs
= do { dflags <- getDynFlags
; xs' <- mapM dsLExpr xs
; if length xs' > maxBuildLength
-- Don't generate builds if the list is very long.
|| length xs' == 0
-- Don't generate builds when the [] constructor will do
|| not (gopt Opt_EnableRewriteRules dflags) -- Rewrite rules off
-- Don't generate a build if there are no rules to eliminate it!
-- See Note [Desugaring RULE left hand sides] in Desugar
then return $ mkListExpr elt_ty xs'
else mkBuildExpr elt_ty (mk_build_list xs') }
where
mk_build_list xs' (cons, _) (nil, _)
= return (foldr (App . App (Var cons)) (Var nil) xs')
dsExplicitList elt_ty (Just fln) xs
= do { list <- dsExplicitList elt_ty Nothing xs
; dflags <- getDynFlags
; dsSyntaxExpr fln [mkIntExprInt dflags (length xs), list] }
dsArithSeq :: PostTcExpr -> (ArithSeqInfo Id) -> DsM CoreExpr
dsArithSeq expr (From from)
= App <$> dsExpr expr <*> dsLExpr from
dsArithSeq expr (FromTo from to)
= do dflags <- getDynFlags
warnAboutEmptyEnumerations dflags from Nothing to
expr' <- dsExpr expr
from' <- dsLExpr from
to' <- dsLExpr to
return $ mkApps expr' [from', to']
dsArithSeq expr (FromThen from thn)
= mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn]
dsArithSeq expr (FromThenTo from thn to)
= do dflags <- getDynFlags
warnAboutEmptyEnumerations dflags from (Just thn) to
expr' <- dsExpr expr
from' <- dsLExpr from
thn' <- dsLExpr thn
to' <- dsLExpr to
return $ mkApps expr' [from', thn', to']
{-
Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're
handled in DsListComp). Basically does the translation given in the
Haskell 98 report:
-}
dsDo :: [ExprLStmt Id] -> DsM CoreExpr
dsDo stmts
= goL stmts
where
goL [] = panic "dsDo"
goL (L loc stmt:lstmts) = putSrcSpanDs loc (go loc stmt lstmts)
go _ (LastStmt body _ _) stmts
= ASSERT( null stmts ) dsLExpr body
-- The 'return' op isn't used for 'do' expressions
go _ (BodyStmt rhs then_expr _ _) stmts
= do { rhs2 <- dsLExpr rhs
; warnDiscardedDoBindings rhs (exprType rhs2)
; rest <- goL stmts
; dsSyntaxExpr then_expr [rhs2, rest] }
go _ (LetStmt (L _ binds)) stmts
= do { rest <- goL stmts
; dsLocalBinds binds rest }
go _ (BindStmt pat rhs bind_op fail_op res1_ty) stmts
= do { body <- goL stmts
; rhs' <- dsLExpr rhs
; var <- selectSimpleMatchVarL pat
; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
res1_ty (cantFailMatchResult body)
; match_code <- handle_failure pat match fail_op
; dsSyntaxExpr bind_op [rhs', Lam var match_code] }
go _ (ApplicativeStmt args mb_join body_ty) stmts
= do {
let
(pats, rhss) = unzip (map (do_arg . snd) args)
do_arg (ApplicativeArgOne pat expr) =
(pat, dsLExpr expr)
do_arg (ApplicativeArgMany stmts ret pat) =
(pat, dsDo (stmts ++ [noLoc $ mkLastStmt (noLoc ret)]))
arg_tys = map hsLPatType pats
; rhss' <- sequence rhss
; let body' = noLoc $ HsDo DoExpr (noLoc stmts) body_ty
; let fun = L noSrcSpan $ HsLam $
MG { mg_alts = noLoc [mkSimpleMatch pats body']
, mg_arg_tys = arg_tys
, mg_res_ty = body_ty
, mg_origin = Generated }
; fun' <- dsLExpr fun
; let mk_ap_call l (op,r) = dsSyntaxExpr op [l,r]
; expr <- foldlM mk_ap_call fun' (zip (map fst args) rhss')
; case mb_join of
Nothing -> return expr
Just join_op -> dsSyntaxExpr join_op [expr] }
go loc (RecStmt { recS_stmts = rec_stmts, recS_later_ids = later_ids
, recS_rec_ids = rec_ids, recS_ret_fn = return_op
, recS_mfix_fn = mfix_op, recS_bind_fn = bind_op
, recS_bind_ty = bind_ty
, recS_rec_rets = rec_rets, recS_ret_ty = body_ty }) stmts
= goL (new_bind_stmt : stmts) -- rec_ids can be empty; eg rec { print 'x' }
where
new_bind_stmt = L loc $ BindStmt (mkBigLHsPatTupId later_pats)
mfix_app bind_op
noSyntaxExpr -- Tuple cannot fail
bind_ty
tup_ids = rec_ids ++ filterOut (`elem` rec_ids) later_ids
tup_ty = mkBigCoreTupTy (map idType tup_ids) -- Deals with singleton case
rec_tup_pats = map nlVarPat tup_ids
later_pats = rec_tup_pats
rets = map noLoc rec_rets
mfix_app = nlHsSyntaxApps mfix_op [mfix_arg]
mfix_arg = noLoc $ HsLam
(MG { mg_alts = noLoc [mkSimpleMatch [mfix_pat] body]
, mg_arg_tys = [tup_ty], mg_res_ty = body_ty
, mg_origin = Generated })
mfix_pat = noLoc $ LazyPat $ mkBigLHsPatTupId rec_tup_pats
body = noLoc $ HsDo
DoExpr (noLoc (rec_stmts ++ [ret_stmt])) body_ty
ret_app = nlHsSyntaxApps return_op [mkBigLHsTupId rets]
ret_stmt = noLoc $ mkLastStmt ret_app
-- This LastStmt will be desugared with dsDo,
-- which ignores the return_op in the LastStmt,
-- so we must apply the return_op explicitly
go _ (ParStmt {}) _ = panic "dsDo ParStmt"
go _ (TransStmt {}) _ = panic "dsDo TransStmt"
handle_failure :: LPat Id -> MatchResult -> SyntaxExpr Id -> DsM CoreExpr
-- In a do expression, pattern-match failure just calls
-- the monadic 'fail' rather than throwing an exception
handle_failure pat match fail_op
| matchCanFail match
= do { dflags <- getDynFlags
; fail_msg <- mkStringExpr (mk_fail_msg dflags pat)
; fail_expr <- dsSyntaxExpr fail_op [fail_msg]
; extractMatchResult match fail_expr }
| otherwise
= extractMatchResult match (error "It can't fail")
mk_fail_msg :: DynFlags -> Located e -> String
mk_fail_msg dflags pat = "Pattern match failure in do expression at " ++
showPpr dflags (getLoc pat)
{-
************************************************************************
* *
\subsection{Errors and contexts}
* *
************************************************************************
-}
-- Warn about certain types of values discarded in monadic bindings (#3263)
warnDiscardedDoBindings :: LHsExpr Id -> Type -> DsM ()
warnDiscardedDoBindings rhs rhs_ty
| Just (m_ty, elt_ty) <- tcSplitAppTy_maybe rhs_ty
= do { warn_unused <- woptM Opt_WarnUnusedDoBind
; warn_wrong <- woptM Opt_WarnWrongDoBind
; when (warn_unused || warn_wrong) $
do { fam_inst_envs <- dsGetFamInstEnvs
; let norm_elt_ty = topNormaliseType fam_inst_envs elt_ty
-- Warn about discarding non-() things in 'monadic' binding
; if warn_unused && not (isUnitTy norm_elt_ty)
then warnDs (Reason Opt_WarnUnusedDoBind)
(badMonadBind rhs elt_ty)
else
-- Warn about discarding m a things in 'monadic' binding of the same type,
-- but only if we didn't already warn due to Opt_WarnUnusedDoBind
when warn_wrong $
do { case tcSplitAppTy_maybe norm_elt_ty of
Just (elt_m_ty, _)
| m_ty `eqType` topNormaliseType fam_inst_envs elt_m_ty
-> warnDs (Reason Opt_WarnWrongDoBind)
(badMonadBind rhs elt_ty)
_ -> return () } } }
| otherwise -- RHS does have type of form (m ty), which is weird
= return () -- but at lesat this warning is irrelevant
badMonadBind :: LHsExpr Id -> Type -> SDoc
badMonadBind rhs elt_ty
= vcat [ hang (text "A do-notation statement discarded a result of type")
2 (quotes (ppr elt_ty))
, hang (text "Suppress this warning by saying")
2 (quotes $ text "_ <-" <+> ppr rhs)
]
{-
************************************************************************
* *
\subsection{Static pointers}
* *
************************************************************************
-}
-- | Creates an name for an entry in the Static Pointer Table.
--
-- The name has the form @sptEntry:<N>@ where @<N>@ is generated from a
-- per-module counter.
--
mkSptEntryName :: SrcSpan -> DsM Name
mkSptEntryName loc = do
mod <- getModule
occ <- mkWrapperName "sptEntry"
newGlobalBinder mod occ loc
where
mkWrapperName what
= do dflags <- getDynFlags
thisMod <- getModule
let -- Note [Generating fresh names for ccall wrapper]
-- in compiler/typecheck/TcEnv.hs
wrapperRef = nextWrapperNum dflags
wrapperNum <- liftIO $ atomicModifyIORef' wrapperRef $ \mod_env ->
let num = lookupWithDefaultModuleEnv mod_env 0 thisMod
in (extendModuleEnv mod_env thisMod (num+1), num)
return $ mkVarOcc $ what ++ ":" ++ show wrapperNum
| GaloisInc/halvm-ghc | compiler/deSugar/DsExpr.hs | bsd-3-clause | 41,419 | 106 | 25 | 13,071 | 8,034 | 4,183 | 3,851 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}
{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}
module Paths_iterpret (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/i/workspace/4th/haskell/iterpret/.stack-work/install/x86_64-osx/lts-7.13/8.0.1/bin"
libdir = "/Users/i/workspace/4th/haskell/iterpret/.stack-work/install/x86_64-osx/lts-7.13/8.0.1/lib/x86_64-osx-ghc-8.0.1/iterpret-0.1.0.0-Jhbv6UyioYqGx7j9wV1pSI"
datadir = "/Users/i/workspace/4th/haskell/iterpret/.stack-work/install/x86_64-osx/lts-7.13/8.0.1/share/x86_64-osx-ghc-8.0.1/iterpret-0.1.0.0"
libexecdir = "/Users/i/workspace/4th/haskell/iterpret/.stack-work/install/x86_64-osx/lts-7.13/8.0.1/libexec"
sysconfdir = "/Users/i/workspace/4th/haskell/iterpret/.stack-work/install/x86_64-osx/lts-7.13/8.0.1/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "iterpret_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "iterpret_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "iterpret_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "iterpret_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "iterpret_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| irwingarry/iterpret | .stack-work/dist/x86_64-osx/Cabal-1.24.0.0/build/autogen/Paths_iterpret.hs | bsd-3-clause | 1,984 | 0 | 10 | 223 | 371 | 215 | 156 | 31 | 1 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}
module Xmpp (
inputBegin, inputFeature, inputP2, inputP3, input, output, outputS, inputMpi, outputMpi,
Mpi(..),
Xmpp(..), fromCommon,
Tags(..),
Jid(..), toJid, fromJid,
Side(..),
Feature(..), Tag(..),
Query(..), Bind(..), Requirement(..), toRequirement, fromRequirement,
voidM, hlpDebug, SHandle(..),
nullQ, tagsNull, tagsType,
fromHandleLike, toHandleLike,
) where
import Debug.Trace
import Data.Maybe
import Data.Pipe
import Text.XML.Pipe
import qualified Data.ByteString as BS
import XmppType
import Tools (voidM, hlpDebug, SHandle(..), fromHandleLike, toHandleLike)
tagsNull :: Tags
tagsNull = Tags Nothing Nothing Nothing Nothing Nothing []
tagsType :: BS.ByteString -> Tags
tagsType tp = tagsNull { tagType = Just tp }
inputP2 :: Monad m => Pipe BS.ByteString Xmpp m ()
inputP2 = xmlEvent =$= convert fromJust =$= mapOut toCommon xmlReborn
isSaslSuccess :: XmlNode -> Bool
isSaslSuccess (XmlNode ((_, Just "jabber:client"), "iq")
_ _ [XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-bind"), "bind") _ _ _]) = True
isSaslSuccess _ = False
isFeature :: XmlNode -> Bool
isFeature (XmlNode
((_, Just "http://etherx.jabber.org/streams"), "features") _ [] []) = True
isFeature n = trace ("isFeature: " ++ show n) False
inputBegin :: Monad m => Pipe BS.ByteString Xmpp m [Xmlns]
inputBegin = xmlEvent =$= convert fromJust =$= mapOut toCommon xmlBegin
inputFeature :: Monad m => Pipe BS.ByteString Xmpp m [Xmlns]
inputFeature = xmlEvent =$= convert fromJust =$= mapOut toCommon xmlFeature
inputP3 :: Monad m => Pipe BS.ByteString Xmpp m [Xmlns]
inputP3 = xmlEvent =$= convert fromJust =$= mapOut toCommon xmlPipe
xmlPipe :: Monad m => Pipe XmlEvent XmlNode m [Xmlns]
xmlPipe = xmlBegin >>= \ns -> xmlNodeUntil isSaslSuccess ns >> return ns
xmlFeature :: Monad m => Pipe XmlEvent XmlNode m [Xmlns]
xmlFeature = xmlBegin >>= \ns -> xmlNodeUntil isFeature ns >> return ns
input :: Monad m => [Xmlns] -> Pipe BS.ByteString Xmpp m ()
input ns = xmlEvent =$= convert fromJust =$= xmlNode ns =$= convert toCommon
inputMpi :: Monad m => [Xmlns] -> Pipe BS.ByteString Mpi m ()
inputMpi ns = xmlEvent =$= convert fromJust =$= xmlNode ns =$= convert toMpi
output :: Monad m => Pipe Xmpp BS.ByteString m ()
output = convert $ xmlString . (: []) . fromCommon Client
outputS :: Monad m => Pipe Xmpp BS.ByteString m ()
outputS = convert $ xmlString . (: []) . fromCommon Server
outputMpi :: Monad m => Pipe Mpi BS.ByteString m ()
outputMpi = convert $ xmlString . (: []) . fromMpi
| YoshikuniJujo/xmpipe | core/Xmpp.hs | bsd-3-clause | 2,554 | 28 | 12 | 418 | 996 | 539 | 457 | 54 | 1 |
import Test.Framework.Runners.Console
import Test.Handshakes
import Test.HybridEncrypt
import Test.TorCell
main :: IO ()
main =
defaultMain [
torCellTests
, hybridEncryptionTest
, handshakeTests
]
| GaloisInc/haskell-tor | test/Test.hs | bsd-3-clause | 210 | 0 | 7 | 35 | 55 | 30 | 25 | 10 | 1 |
{-# LANGUAGE RecordWildCards, OverloadedStrings, TypeSynonymInstances, MultiParamTypeClasses, FlexibleInstances #-}
module Network.ZDNS.Types.RRset where
import Data.Word
import Data.IP
import Data.Char (toUpper)
import Data.ByteString
import qualified Data.ByteString.Char8 as BC
import qualified Data.Vector as V
import qualified Data.List as L
import Network.ZDNS.Types.Name
import Network.ZDNS.Util
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Base16 as B16
----------------------------------------------------------------
data RRType = A | AAAA | NS | TXT | MX | CNAME | SOA | PTR | SRV | NAPTR
| OPT | DS | RRSIG | DNSKEY | NSEC3 | NSEC3PARAM
| UNKNOWNTYPE Word16 deriving (Eq, Show, Read)
instance CodeMapper RRType Word16 where
getMapper = [
(A, 1)
, (NS, 2)
, (CNAME, 5)
, (SOA, 6)
, (PTR, 12)
, (MX, 15)
, (TXT, 16)
, (AAAA, 28)
, (SRV, 33)
, (NAPTR, 35)
, (OPT, 41)
, (DS, 43)
, (RRSIG, 46)
, (DNSKEY, 48)
, (NSEC3, 50)
, (NSEC3PARAM, 51)
]
unknownCode = UNKNOWNTYPE
toWord (UNKNOWNTYPE t) = t
toWord ot = knownCodeToWord ot
----------------------------------------------------------------
data RRClass = IN | CS | CH | HS | UNKNOWNKLASS Word16 deriving (Eq, Show, Read)
instance CodeMapper RRClass Word16 where
getMapper = [
(IN, 1)
, (CS, 2)
, (CH, 3)
, (HS, 4)
]
unknownCode = UNKNOWNKLASS
toWord (UNKNOWNKLASS c) = c
toWord oc = knownCodeToWord oc
----------------------------------------------------------------
data RdataFieldType = RCompressedDomain
| RUnCompressedDomain
| RBinary
| RByteBinary
| RString
| RTXT
| RByte
| RShort
| RLong
| RIPv4
| RIPv6 deriving (Eq)
data RdataField = RDFCompressedDomain !Domain
| RDFUnCompressedDomain !Domain
| RDFByte !Word8
| RDFShort !Word16
| RDFLong !Word32
| RDFBinary !ByteString
| RDFByteBinary !(Word8, ByteString)
| RDFString !ByteString
| RDFTXT !(V.Vector ByteString)
| RDFIPv4 !IPv4
| RDFIPv6 !IPv6 deriving (Eq, Ord)
type Rdata = V.Vector RdataField
showRdata :: Rdata -> RRType -> String
showRdata rdata DS = let (tag:alg:digest_type:(RDFBinary digtest):_) = (V.toList rdata)
in L.intercalate " " [show tag
,show alg
,show digest_type
,L.map toUpper $ BC.unpack . B16.encode $ digtest]
showRdata rdata RRSIG = let ((RDFShort ct):alg:labels:ttl:expire:inception:key_tag:signer:(RDFBinary sig):_) = (V.toList rdata)
ctype = (fromWord ct) :: RRType
in L.intercalate " " [show ctype
,show alg
,show labels
,show ttl
,show expire
,show inception
,show key_tag
,show signer
,L.map toUpper $ BC.unpack . B64.encode $ sig]
showRdata rdata DNSKEY = let (flag:protocol:alg:(RDFBinary key):_) = (V.toList rdata)
in L.intercalate " " [show flag
,show protocol
,show alg
,L.map toUpper $ BC.unpack . B64.encode $ key]
showRdata rdata NSEC3PARAM = let (ht:flags:iteration:(RDFByteBinary (_, salt)):_) = (V.toList rdata)
in L.intercalate " " [show ht
,show flags
,show iteration
,L.map toUpper $ BC.unpack . B16.encode $ salt]
showRdata rdata _ = L.intercalate " " $ L.map show $ V.toList rdata
instance Show RdataField where
show (RDFCompressedDomain n) = show n
show (RDFUnCompressedDomain n) = show n
show (RDFByte w) = show w
show (RDFShort w) = show w
show (RDFLong w) = show w
show (RDFBinary b) = show b
show (RDFByteBinary (_, b)) = show b
show (RDFString s) = "\"" ++ show s ++ "\""
show (RDFTXT b) = show b
show (RDFIPv4 ip) = show ip
show (RDFIPv6 ip) = show ip
type RdataVec = V.Vector Rdata
type TTL = Word32
data RRset = RRset {
rrsetName :: Domain
, rrsetType :: RRType
, rrsetClass :: RRClass
, rrsetTTL :: TTL
, rrsetRdatas :: RdataVec
}
addRdata :: Rdata -> RRset -> RRset
addRdata rdata (RRset n t c ttl rdatas) =
RRset n t c ttl (V.snoc rdatas rdata)
showRRset :: RRset -> String
showRRset (RRset n t c ttl rdatas) =
L.intercalate "\n" $ L.map showRR (V.toList rdatas)
where showRR rdata = L.intercalate "\t" [show n
,show ttl
,show c
,show t
,showRdata rdata t]
instance Show RRset where
show = showRRset
type RdataDescriptor = [RdataFieldType]
getRdataDescriptor :: RRType -> RdataDescriptor
getRdataDescriptor NS = [RCompressedDomain]
getRdataDescriptor CNAME = [RCompressedDomain]
getRdataDescriptor MX = [RShort, RCompressedDomain]
getRdataDescriptor PTR = [RCompressedDomain]
getRdataDescriptor SOA = [RCompressedDomain
, RCompressedDomain
, RLong
, RLong
, RLong
, RLong
, RLong]
getRdataDescriptor A = [RIPv4]
getRdataDescriptor AAAA = [RIPv6]
getRdataDescriptor TXT = [RTXT]
getRdataDescriptor SRV = [RShort, RShort, RShort, RCompressedDomain]
getRdataDescriptor NAPTR = [RShort, RShort, RString, RString, RString, RCompressedDomain]
getRdataDescriptor DS = [RShort, RByte, RByte, RBinary]
getRdataDescriptor RRSIG = [RShort, RByte, RByte, RLong, RLong, RLong, RShort, RCompressedDomain, RBinary]
getRdataDescriptor DNSKEY = [RShort, RByte, RByte, RBinary]
getRdataDescriptor NSEC3 = [RByte, RByte, RShort, RByteBinary, RByteBinary, RBinary]
getRdataDescriptor NSEC3PARAM = [RByte, RByte, RShort, RByteBinary]
getRdataDescriptor OPT = [RBinary]
getRdataDescriptor (UNKNOWNTYPE _) = [RBinary]
| ben-han-cn/hdns | Network/ZDNS/Types/RRset.hs | bsd-3-clause | 7,280 | 0 | 20 | 3,000 | 1,921 | 1,060 | 861 | 178 | 1 |
module Game.LambdaPad.Pads
( module Game.LambdaPad.Core.Pads
) where
import Game.LambdaPad.Core.Pads
| zearen-wover/lambda-pad | src/lib/Game/LambdaPad/Pads.hs | bsd-3-clause | 106 | 0 | 5 | 14 | 24 | 17 | 7 | 3 | 0 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude (liquidAssert)
[lq| type OList a = [a]<{\fld v -> (v >= fld)}> |]
[lq| filterGt :: (Ord a) => x:Maybe a -> OList a -> OList {v:a | ((isJust(x)) => (fromJust(x) <= v)) } |]
filterGt :: Ord a => Maybe a -> [a] -> [a]
filterGt Nothing xs = xs
filterGt (Just x) xs = foo x xs
foo y xs = foo' y xs
foo' :: (Ord a) => a -> [a] -> [a]
foo' y [] = []
foo' y (x:xs)
= case compare y x of
GT -> foo' y xs
LT -> x:xs
EQ -> xs
[lq| bar :: (Ord a) => z:a -> OList a -> OList {v:a | z <= v} |]
bar y xs = bar' y xs
bar' y [] = []
bar' y (x:xs)
| y > x = bar' y xs
| y < x = x:xs
| y == x = xs
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/maybe.hs | bsd-3-clause | 733 | 5 | 10 | 227 | 332 | 159 | 173 | 23 | 3 |
module Evaluator.Object where
import Protolude hiding (Show, show)
import Data.IORef (IORef, newIORef, modifyIORef, readIORef)
import qualified Data.Map.Strict as M
import GHC.Show (Show(..))
import Parser.AST
data Object = OInt Integer
| OBool Bool
| OString Text
| OArray [Object]
| OHash (M.Map Hashable Object)
| ONull
| OFn { params :: [Ident]
, body :: BlockStmt
, env :: EnvRef
}
| OBuiltInFn { name :: Text
, numParams :: Int
, fn :: BuiltInFn
}
| OReturn Object
instance Show Object where
show (OInt x) = show x
show (OBool x) = if x then "true" else "false"
show (OString x) = show x
show (OArray x) = show x
show (OHash m) = "{" ++ go (M.toList m) ++ "}"
where
go [(l, o)] = show l ++ ":" ++ show o
go (x:xs) = go [x] ++ "," ++ go xs
show ONull = "null"
show (OFn _ _ _) = "[function]"
show (OBuiltInFn n _ _) = "[built-in function: " ++ toS n ++ "]"
show (OReturn o) = show o
instance Eq Object where
OInt x == OInt y = x == y
OBool x == OBool y = x == y
OString x == OString y = x == y
OArray x == OArray y = x == y
OHash x == OHash y = x == y
ONull == ONull = True
OFn p b e == OFn p' b' e' = p == p' && b == b' && e == e'
OReturn o == o' = o == o'
o == OReturn o' = o == o'
OBuiltInFn n p _ == OBuiltInFn n' p' _ = n == n' && p == p'
_ == _ = False
data Hashable = IntHash Integer
| BoolHash Bool
| StringHash Text
deriving (Eq, Ord)
instance Show Hashable where
show (IntHash i) = show $ OInt i
show (BoolHash b) = show $ OBool b
show (StringHash t) = show $ OString t
type BuiltInFnResult = Either Text Object
type BuiltInFn = [Object] -> IO BuiltInFnResult
true :: Object
true = OBool True
false :: Object
false = OBool False
nil :: Object
nil = ONull
ret :: Object -> Object
ret o = OReturn o
isReturned :: Object -> Bool
isReturned (OReturn _) = True
isReturned _ = False
returned :: Object -> Object
returned (OReturn o) = o
returned o = o
type EnvRef = IORef Environment
data Environment = Environment { varMap :: M.Map Ident Object
, parent :: Maybe EnvRef
}
deriving (Eq)
emptyEnv :: IO EnvRef
emptyEnv = newIORef $ Environment M.empty Nothing
wrapEnv :: EnvRef -> [(Ident, Object)] -> IO EnvRef
wrapEnv = (newIORef .) . flip (Environment . M.fromList) . Just
insertVar :: Ident -> Object -> EnvRef -> IO EnvRef
insertVar i o ref = modifyIORef ref (go i o) $> ref
where
go :: Ident -> Object -> Environment -> Environment
go i o (Environment m p) = Environment (M.insert i o m) p
getVar :: Ident -> EnvRef -> IO (Maybe Object)
getVar i ref = do
Environment m p <- readIORef ref
case M.lookup i m of
Just o -> return $ Just o
Nothing -> case p of
Just parent -> getVar i parent
Nothing -> return $ Nothing
| noraesae/monkey-hs | lib/Evaluator/Object.hs | bsd-3-clause | 3,155 | 0 | 13 | 1,073 | 1,255 | 640 | 615 | 87 | 3 |
--
--
--
----------------
-- Exercise 6.5.
----------------
--
--
--
module E'6''5 where
import E'6''4 ( superimposeChar )
superimposeLine :: [Char] -> [Char] -> [Char]
superimposeLine a b
= [ superimposeChar currentChar_a currentChar_b
| ( currentChar_a , currentChar_b ) <- zippedStrings ]
where
zippedStrings :: [(Char, Char)]
zippedStrings = zip a b
-- Other solution for "superimposeLine":
superimposeLine' :: String -> String -> String
superimposeLine' [] [] = []
superimposeLine' ( a : as ) [] = ( superimposeChar a '.' ) : superimposeLine as []
superimposeLine' [] ( b : bs ) = ( superimposeChar '.' b ) : superimposeLine [] bs
superimposeLine' ( a : as ) ( b : bs ) = ( superimposeChar a b ) : superimposeLine as bs
| pascal-knodel/haskell-craft | _/links/E'6''5.hs | mit | 800 | 0 | 8 | 200 | 248 | 137 | 111 | 13 | 1 |
{- |
Module : $Header$
Description : Basic analysis for common logic
Copyright : (c) Eugen Kuksa, Karl Luc, Uni Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : eugenk@informatik.uni-bremen.de
Stability : experimental
Portability : portable
Basic and static analysis for common logic
-}
module CommonLogic.Analysis
( basicCommonLogicAnalysis
, negForm
, symsOfTextMeta
, mkStatSymbItems
, mkStatSymbMapItem
, inducedFromMorphism
, inducedFromToMorphism
, signColimit
)
where
import Common.ExtSign
import Common.Result as Result
import Common.GlobalAnnotations
import qualified Common.AS_Annotation as AS_Anno
import Common.Id as Id
import Common.IRI (parseIRIReference)
import Common.DocUtils
import Common.Lib.Graph
import Common.SetColimit
import CommonLogic.Symbol as Symbol
import qualified CommonLogic.AS_CommonLogic as AS
import CommonLogic.Morphism as Morphism
import CommonLogic.Sign as Sign
import CommonLogic.ExpandCurie
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Common.Lib.MapSet as MapSet
import qualified Data.List as List
import Data.Graph.Inductive.Graph as Graph
data DIAG_FORM = DiagForm
{
formula :: AS_Anno.Named AS.TEXT_META,
diagnosis :: Result.Diagnosis
}
-- | retrieves the signature out of a basic spec
makeSig :: AS.BASIC_SPEC -> Sign.Sign -> Sign.Sign
makeSig (AS.Basic_spec spec) sig = List.foldl retrieveBasicItem sig spec
retrieveBasicItem :: Sign.Sign -> AS_Anno.Annoted AS.BASIC_ITEMS -> Sign.Sign
retrieveBasicItem sig x = case AS_Anno.item x of
AS.Axiom_items xs -> List.foldl retrieveSign sig xs
retrieveSign :: Sign.Sign -> AS_Anno.Annoted AS.TEXT_META -> Sign.Sign
retrieveSign sig (AS_Anno.Annoted tm _ _ _) =
Sign.unite (Sign.unite sig $ nondiscItems $ AS.nondiscourseNames tm)
(propsOfFormula $ AS.getText tm)
nondiscItems :: Maybe (Set.Set AS.NAME) -> Sign.Sign
nondiscItems s = case s of
Nothing -> Sign.emptySig
Just ns -> Sign.emptySig {Sign.nondiscourseNames = Set.map Id.simpleIdToId ns}
-- | retrieve sentences
makeFormulas :: AS.BASIC_SPEC -> Sign.Sign -> [DIAG_FORM]
makeFormulas (AS.Basic_spec bspec) sig =
List.foldl (\ xs bs -> retrieveFormulaItem xs bs sig) [] bspec
retrieveFormulaItem :: [DIAG_FORM] -> AS_Anno.Annoted AS.BASIC_ITEMS
-> Sign.Sign -> [DIAG_FORM]
retrieveFormulaItem axs x sig =
case AS_Anno.item x of
AS.Axiom_items ax ->
List.foldl (\ xs bs -> addFormula xs bs sig) axs $ numberFormulae ax 0
data NUM_FORM = NumForm
{
nfformula :: AS_Anno.Annoted AS.TEXT_META
, nfnum :: Int
}
numberFormulae :: [AS_Anno.Annoted AS.TEXT_META] -> Int -> [NUM_FORM]
numberFormulae [] _ = []
numberFormulae (x : xs) i =
if null $ AS_Anno.getRLabel x
then NumForm {nfformula = x, nfnum = i} : numberFormulae xs (i + 1)
else NumForm {nfformula = x, nfnum = 0} : numberFormulae xs i
addFormula :: [DIAG_FORM]
-> NUM_FORM
-> Sign.Sign
-> [DIAG_FORM]
addFormula formulae nf _ = formulae ++
[DiagForm {
formula = makeNamed (setTextIRI f) i
, diagnosis = Result.Diag
{
Result.diagKind = Result.Hint
, Result.diagString = "All fine"
, Result.diagPos = lnum
}
}]
where
f = nfformula nf
i = nfnum nf
lnum = AS_Anno.opt_pos f
-- | generates a named formula
makeNamed :: AS_Anno.Annoted AS.TEXT_META -> Int
-> AS_Anno.Named AS.TEXT_META
makeNamed f i =
(AS_Anno.makeNamed (
if null label
then case text of
AS.Named_text n _ _ -> Id.tokStr n
_ -> "Ax_" ++ show i
else label
) $ AS_Anno.item f)
{ AS_Anno.isAxiom = not isTheorem }
where
text = AS.getText $ AS_Anno.item f
label = AS_Anno.getRLabel f
annos = AS_Anno.r_annos f
isImplies = any AS_Anno.isImplies annos
isImplied = any AS_Anno.isImplied annos
isTheorem = isImplies || isImplied
setTextIRI :: AS_Anno.Annoted AS.TEXT_META -> AS_Anno.Annoted AS.TEXT_META
setTextIRI atm@(AS_Anno.Annoted { AS_Anno.item = tm }) =
let mi = case AS.getText tm of
AS.Named_text n _ _ -> parseIRIReference $ init $ tail $ Id.tokStr n
_ -> Nothing
in atm { AS_Anno.item = tm { AS.textIri = mi } }
-- | Retrives the signature of a sentence
propsOfFormula :: AS.TEXT -> Sign.Sign
propsOfFormula (AS.Named_text _ txt _) = propsOfFormula txt
propsOfFormula (AS.Text phrs _) = Sign.uniteL $ map propsOfPhrase phrs
propsOfPhrase :: AS.PHRASE -> Sign.Sign
propsOfPhrase (AS.Module m) = propsOfModule m
propsOfPhrase (AS.Sentence s) = propsOfSentence s
propsOfPhrase (AS.Comment_text _ txt _) = propsOfFormula txt
propsOfPhrase (AS.Importation _) = Sign.emptySig
propsOfModule :: AS.MODULE -> Sign.Sign
propsOfModule m = case m of
(AS.Mod n txt _) -> Sign.unite (propsOfFormula txt) $ nameToSign n
(AS.Mod_ex n exs txt _) -> Sign.unite (propsOfFormula txt)
$ Sign.uniteL $ nameToSign n : map nameToSign exs
where nameToSign x = Sign.emptySig {
Sign.discourseNames = Set.singleton $ Id.simpleIdToId x
}
propsOfSentence :: AS.SENTENCE -> Sign.Sign
propsOfSentence (AS.Atom_sent form _) = case form of
AS.Equation term1 term2 -> Sign.unite (propsOfTerm term1)
(propsOfTerm term2)
AS.Atom term ts -> Sign.unite (propsOfTerm term)
(uniteMap propsOfTermSeq ts)
propsOfSentence (AS.Quant_sent _ xs s _) =
Sign.sigDiff (propsOfSentence s) (uniteMap propsOfNames xs)
propsOfSentence (AS.Bool_sent bs _) = case bs of
AS.Junction _ xs -> uniteMap propsOfSentence xs
AS.Negation x -> propsOfSentence x
AS.BinOp _ s1 s2 -> Sign.unite (propsOfSentence s1) (propsOfSentence s2)
propsOfSentence (AS.Comment_sent _ s _) = propsOfSentence s
propsOfSentence (AS.Irregular_sent s _) = propsOfSentence s
propsOfTerm :: AS.TERM -> Sign.Sign
propsOfTerm term = case term of
AS.Name_term x -> Sign.emptySig {
Sign.discourseNames = Set.singleton $ Id.simpleIdToId x
}
AS.Funct_term t ts _ -> Sign.unite (propsOfTerm t)
(uniteMap propsOfTermSeq ts)
AS.Comment_term t _ _ -> propsOfTerm t -- fix
AS.That_term s _ -> propsOfSentence s
propsOfNames :: AS.NAME_OR_SEQMARK -> Sign.Sign
propsOfNames (AS.Name x) = Sign.emptySig {
Sign.discourseNames = Set.singleton $ Id.simpleIdToId x
}
propsOfNames (AS.SeqMark x) = Sign.emptySig {
Sign.sequenceMarkers = Set.singleton $ Id.simpleIdToId x
}
propsOfTermSeq :: AS.TERM_SEQ -> Sign.Sign
propsOfTermSeq s = case s of
AS.Term_seq term -> propsOfTerm term
AS.Seq_marks x -> Sign.emptySig {
Sign.sequenceMarkers = Set.singleton $ Id.simpleIdToId x
}
uniteMap :: (a -> Sign.Sign) -> [a] -> Sign
uniteMap p = List.foldl (\ sig -> Sign.unite sig . p)
Sign.emptySig
-- | Common Logic static analysis
basicCommonLogicAnalysis :: (AS.BASIC_SPEC, Sign.Sign, GlobalAnnos)
-> Result (AS.BASIC_SPEC,
ExtSign Sign.Sign Symbol.Symbol,
[AS_Anno.Named AS.TEXT_META])
basicCommonLogicAnalysis (bs', sig, ga) =
Result.Result [] $ if exErrs then Nothing else
Just (bs', ExtSign sigItems newSyms, sentences)
where
bs = expandCurieBS (prefix_map ga) bs'
sigItems = makeSig bs sig
newSyms = Set.map Symbol.Symbol
$ Set.difference (Sign.allItems sigItems) $ Sign.allItems sig
bsform = makeFormulas bs sigItems
-- [DIAG_FORM] signature and list of sentences
sentences = map formula bsform
-- Annoted Sentences (Ax_), numbering, DiagError
exErrs = False
-- | creates a morphism from a symbol map
inducedFromMorphism :: Map.Map Symbol.Symbol Symbol.Symbol
-> Sign.Sign
-> Result.Result Morphism.Morphism
inducedFromMorphism m s = let
p = Map.mapKeys symName $ Map.map symName m
t = Sign.emptySig { discourseNames = Set.map (applyMap p) $ discourseNames s
, nondiscourseNames = Set.map (applyMap p) $ nondiscourseNames s
, sequenceMarkers = Set.map (applyMap p) $ sequenceMarkers s
}
in return $ mkMorphism s t p
splitFragment :: Id -> (String, String)
splitFragment = span (/= '#') . show
inducedFromToMorphism :: Map.Map Symbol.Symbol Symbol.Symbol
-> ExtSign Sign.Sign Symbol.Symbol
-> ExtSign Sign.Sign Symbol.Symbol
-> Result.Result Morphism.Morphism
inducedFromToMorphism m (ExtSign s sys) (ExtSign t ty) = let
tsy = Set.fold (\ r -> let (q, f) = splitFragment $ symName r
in MapSet.insert f q) MapSet.empty ty
p = Set.fold (\ sy -> let n = symName sy in case Map.lookup sy m of
Just r -> Map.insert n $ symName r
Nothing -> if Set.member sy ty then id else
let (_, f) = splitFragment n
in case Set.toList $ MapSet.lookup f tsy of
[q] -> Map.insert n $ simpleIdToId
$ mkSimpleId $ q ++ f
_ -> id) Map.empty sys
t2 = Sign.emptySig
{ discourseNames = Set.map (applyMap p) $ discourseNames s
, nondiscourseNames = Set.map (applyMap p) $ nondiscourseNames s
, sequenceMarkers = Set.map (applyMap p) $ sequenceMarkers s
}
in if isSubSigOf t2 t then return $ mkMorphism s t p else
fail $ "cannot map symbols from\n" ++ showDoc (sigDiff t2 t) "\nto\n"
++ showDoc t ""
-- | negate sentence (text) - propagates negation to sentences
negForm :: AS.TEXT_META -> AS.TEXT_META
negForm tm = tm { AS.getText = negForm_txt $ AS.getText tm }
negForm_txt :: AS.TEXT -> AS.TEXT
negForm_txt t = case t of
AS.Text phrs r -> AS.Text (map negForm_phr phrs) r
AS.Named_text n txt r -> AS.Named_text n (negForm_txt txt) r
-- negate phrase - propagates negation to sentences
negForm_phr :: AS.PHRASE -> AS.PHRASE
negForm_phr phr = case phr of
AS.Module m -> AS.Module $ negForm_mod m
AS.Sentence s -> AS.Sentence $ negForm_sen s
AS.Comment_text c t r -> AS.Comment_text c (negForm_txt t) r
x -> x
-- negate module - propagates negation to sentences
negForm_mod :: AS.MODULE -> AS.MODULE
negForm_mod m = case m of
AS.Mod n t r -> AS.Mod n (negForm_txt t) r
AS.Mod_ex n exs t r -> AS.Mod_ex n exs (negForm_txt t) r
-- negate sentence
negForm_sen :: AS.SENTENCE -> AS.SENTENCE
negForm_sen f = case f of
AS.Quant_sent _ _ _ r -> AS.Bool_sent (AS.Negation f) r
AS.Bool_sent bs r -> case bs of
AS.Negation s -> s
_ -> AS.Bool_sent (AS.Negation f) r
_ -> AS.Bool_sent (AS.Negation f) Id.nullRange
-- | Static analysis for symbol maps
mkStatSymbMapItem :: [AS.SYMB_MAP_ITEMS]
-> Result.Result (Map.Map Symbol.Symbol Symbol.Symbol)
mkStatSymbMapItem xs =
Result.Result
{
Result.diags = []
, Result.maybeResult = Just $
foldl
(
\ smap x ->
case x of
AS.Symb_map_items sitem _ ->
Map.union smap $ statSymbMapItem sitem
)
Map.empty
xs
}
statSymbMapItem :: [AS.SYMB_OR_MAP] -> Map.Map Symbol.Symbol Symbol.Symbol
statSymbMapItem =
foldl
(
\ mmap x ->
case x of
AS.Symb sym -> Map.insert (nosToSymbol sym) (nosToSymbol sym) mmap
AS.Symb_mapN s1 s2 _
-> Map.insert (symbToSymbol s1) (symbToSymbol s2) mmap
AS.Symb_mapS s1 s2 _
-> Map.insert (symbToSymbol s1) (symbToSymbol s2) mmap
)
Map.empty
-- | Retrieve raw symbols
mkStatSymbItems :: [AS.SYMB_ITEMS] -> Result.Result [Symbol.Symbol]
mkStatSymbItems a = Result.Result
{
Result.diags = []
, Result.maybeResult = Just $ statSymbItems a
}
statSymbItems :: [AS.SYMB_ITEMS] -> [Symbol.Symbol]
statSymbItems = concatMap symbItemsToSymbol
symbItemsToSymbol :: AS.SYMB_ITEMS -> [Symbol.Symbol]
symbItemsToSymbol (AS.Symb_items syms _) = map nosToSymbol syms
nosToSymbol :: AS.NAME_OR_SEQMARK -> Symbol.Symbol
nosToSymbol nos = case nos of
AS.Name tok -> symbToSymbol tok
AS.SeqMark tok -> symbToSymbol tok
symbToSymbol :: Id.Token -> Symbol.Symbol
symbToSymbol tok = Symbol.Symbol {Symbol.symName = Id.simpleIdToId tok}
-- | retrieves all symbols from the text
symsOfTextMeta :: AS.TEXT_META -> [Symbol.Symbol]
symsOfTextMeta tm =
Set.toList $ Symbol.symOf $ retrieveSign Sign.emptySig $ AS_Anno.emptyAnno tm
-- | compute colimit of CL signatures
signColimit :: Gr Sign.Sign (Int, Morphism.Morphism)
-> Result (Sign.Sign, Map.Map Int Morphism.Morphism)
signColimit diag = do
let mor2fun (x,mor) = (x, Morphism.propMap mor)
dGraph = emap mor2fun $ nmap Sign.discourseNames diag
(dCol, dmap) = addIntToSymbols $ computeColimitSet dGraph
ndGraph = emap mor2fun $ nmap Sign.nondiscourseNames diag
(ndCol, ndmap) = addIntToSymbols $ computeColimitSet ndGraph
sGraph = emap mor2fun $ nmap Sign.sequenceMarkers diag
(sCol, smap) = addIntToSymbols $ computeColimitSet sGraph
sig = Sign { Sign.discourseNames = dCol
, Sign.nondiscourseNames = ndCol
, Sign.sequenceMarkers = sCol
}
mors = Map.unions $ map (\ (x, nsig) ->
let m = Morphism.Morphism {
Morphism.source = nsig
, Morphism.target = sig
, Morphism.propMap = Map.unions
[ Map.findWithDefault (error "dmap") x dmap,
Map.findWithDefault (error "ndmap") x ndmap,
Map.findWithDefault (error "smap") x smap]
}
in Map.insert x m Map.empty) $ labNodes diag
return (sig, mors)
| keithodulaigh/Hets | CommonLogic/Analysis.hs | gpl-2.0 | 14,370 | 0 | 28 | 4,010 | 4,376 | 2,239 | 2,137 | 285 | 5 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : ./QVTR/Sign.hs
Description : QVTR signature and sentences
Copyright : (c) Daniel Calegari Universidad de la Republica, Uruguay 2013
License : GPLv2 or higher, see LICENSE.txt
Maintainer : dcalegar@fing.edu.uy
Stability : provisional
Portability : portable
-}
module QVTR.Sign where
import QVTR.As
import QVTR.Print ()
import qualified CSMOF.Sign as CSMOF
import CSMOF.Print ()
import Common.Doc
import Common.DocUtils
import Common.Id
import Data.Data
import qualified Data.Map as Map
data RuleDef = RuleDef { name :: String
, top :: Bool
, parameters :: [CSMOF.TypeClass]
} deriving (Show, Eq, Ord, Typeable, Data)
instance Pretty RuleDef where
pretty (RuleDef nam to pars) =
let t = text $ if to
then "top relation"
else "relation"
in t <+> text nam <> lparen
<> foldr ((<+>) . pretty) empty pars
<> rparen
data Sign = Sign { sourceSign :: CSMOF.Sign
, targetSign :: CSMOF.Sign
, nonTopRelations :: Map.Map String RuleDef
, topRelations :: Map.Map String RuleDef
, keyDefs :: [(String, String)]
} deriving (Show, Eq, Ord, Typeable, Data)
instance GetRange Sign where
getRange _ = nullRange
rangeSpan _ = []
instance Pretty Sign where
pretty (Sign souS tarS nonRel topRel keyD) =
text "-- Source Metamodel"
$++$
pretty souS
$++$
text "-- Target Metamodel"
$++$
pretty tarS
$++$
text "-- Model Transformation"
$++$
text "Definition of Relations"
$+$
Map.fold (($+$) . pretty) empty topRel
$+$
Map.fold (($+$) . pretty) empty nonRel
$++$
text "Definition of Keys"
$+$
foldr (($+$) . pretty) empty keyD
emptySign :: Sign
emptySign = Sign { sourceSign = CSMOF.emptySign
, targetSign = CSMOF.emptySign
, nonTopRelations = Map.empty
, topRelations = Map.empty
, keyDefs = []
}
data Sen = KeyConstr { keyConst :: Key }
| QVTSen { rule :: RelationSen }
deriving (Show, Eq, Ord, Typeable, Data)
instance GetRange Sen where
getRange _ = nullRange
rangeSpan _ = []
instance Pretty Sen where
pretty (KeyConstr con) = pretty con
pretty (QVTSen rel) = pretty rel
data RelationSen = RelationSen { ruleDef :: RuleDef
, varSet :: [RelVar]
, parSet :: [RelVar]
, sourcePattern :: Pattern
, targetPattern :: Pattern
, whenClause :: Maybe WhenWhere
, whereClause :: Maybe WhenWhere
} deriving (Show, Eq, Ord, Typeable, Data)
instance GetRange RelationSen where
getRange _ = nullRange
rangeSpan _ = []
instance Pretty RelationSen where
pretty (RelationSen rD vS pS souP tarP whenC whereC) =
pretty rD
$++$
text "Variables" <> colon <+> foldr ((<+>) . pretty) empty vS
$++$
text "Parameters" <> colon <+> foldr ((<+>) . pretty) empty pS
$++$
pretty souP
$++$
pretty tarP
$++$
(case whenC of
Nothing -> text "When" <+> lbrace $+$ rbrace
Just w -> text "When" <+> lbrace $+$ pretty w $+$ rbrace)
$++$
(case whereC of
Nothing -> text "Where" <+> lbrace $+$ rbrace
Just w -> text "Where" <+> lbrace $+$ pretty w $+$ rbrace)
data Pattern = Pattern { patVarSet :: [RelVar]
, patRels :: [(CSMOF.PropertyT, RelVar, RelVar)]
, patPreds :: [(String, String, OCL)]
} deriving (Show, Eq, Ord, Typeable, Data)
instance GetRange Pattern where
getRange _ = nullRange
rangeSpan _ = []
instance Pretty Pattern where
pretty (Pattern patVS patRel patPre) =
text "Pattern" <+> lbrace
$+$
space <+> space <+> text "Variables" <> colon <+> foldr ((<+>) . pretty) empty patVS
$+$
space <+> space <+> text "Relations" <> colon <+> foldr (($+$) . pretty) empty patRel
$+$
space <+> space <+> text "Predicates" <> colon <+> foldr (($+$) . pretty) empty patPre
$+$
rbrace
| spechub/Hets | QVTR/Sign.hs | gpl-2.0 | 4,319 | 0 | 23 | 1,416 | 1,221 | 655 | 566 | 116 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Lambda.RemoveEventSource
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Removes an event source mapping. This means AWS Lambda will no longer invoke
-- the function for events in the associated source.
--
-- This operation requires permission for the 'lambda:RemoveEventSource' action.
--
-- <http://docs.aws.amazon.com/lambda/latest/dg/API_RemoveEventSource.html>
module Network.AWS.Lambda.RemoveEventSource
(
-- * Request
RemoveEventSource
-- ** Request constructor
, removeEventSource
-- ** Request lenses
, resUUID
-- * Response
, RemoveEventSourceResponse
-- ** Response constructor
, removeEventSourceResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.RestJSON
import Network.AWS.Lambda.Types
import qualified GHC.Exts
newtype RemoveEventSource = RemoveEventSource
{ _resUUID :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'RemoveEventSource' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'resUUID' @::@ 'Text'
--
removeEventSource :: Text -- ^ 'resUUID'
-> RemoveEventSource
removeEventSource p1 = RemoveEventSource
{ _resUUID = p1
}
-- | The event source mapping ID.
resUUID :: Lens' RemoveEventSource Text
resUUID = lens _resUUID (\s a -> s { _resUUID = a })
data RemoveEventSourceResponse = RemoveEventSourceResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'RemoveEventSourceResponse' constructor.
removeEventSourceResponse :: RemoveEventSourceResponse
removeEventSourceResponse = RemoveEventSourceResponse
instance ToPath RemoveEventSource where
toPath RemoveEventSource{..} = mconcat
[ "/2014-11-13/event-source-mappings/"
, toText _resUUID
]
instance ToQuery RemoveEventSource where
toQuery = const mempty
instance ToHeaders RemoveEventSource
instance ToJSON RemoveEventSource where
toJSON = const (toJSON Empty)
instance AWSRequest RemoveEventSource where
type Sv RemoveEventSource = Lambda
type Rs RemoveEventSource = RemoveEventSourceResponse
request = delete
response = nullResponse RemoveEventSourceResponse
| kim/amazonka | amazonka-lambda/gen/Network/AWS/Lambda/RemoveEventSource.hs | mpl-2.0 | 3,129 | 0 | 9 | 671 | 353 | 216 | 137 | 48 | 1 |
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
-- |
-- Module : Network.AWS.Data.Text
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.Data.Text
( Text
-- * Deserialisation
, FromText (..)
, fromText
, fromTextError
, takeLowerText
, takeText
-- * Serialisation
, ToText (..)
, toTextCI
, showText
) where
import Control.Applicative
import Data.Attoparsec.Text (Parser)
import qualified Data.Attoparsec.Text as A
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS8
import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI
import Data.Int
import Data.Monoid
import Data.Scientific
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Data.Text.Lazy as LText
import Data.Text.Lazy.Builder (Builder)
import qualified Data.Text.Lazy.Builder as Build
import qualified Data.Text.Lazy.Builder.Int as Build
import qualified Data.Text.Lazy.Builder.Scientific as Build
import Network.AWS.Data.Crypto
import Network.HTTP.Types
import Numeric
import Numeric.Natural
-- | Fail parsing with a 'Text' error.
--
-- Constrained to the actual attoparsec monad to avoid
-- exposing 'fail' usage directly.
fromTextError :: Text -> Parser a
fromTextError = fail . Text.unpack
fromText :: FromText a => Text -> Either String a
fromText = A.parseOnly parser
takeLowerText :: Parser Text
takeLowerText = Text.toLower <$> A.takeText
takeText :: Parser Text
takeText = A.takeText
class FromText a where
parser :: Parser a
instance FromText Text where
parser = A.takeText
instance FromText ByteString where
parser = Text.encodeUtf8 <$> A.takeText
instance FromText Char where
parser = A.anyChar <* A.endOfInput
instance FromText Int where
parser = A.signed A.decimal <* A.endOfInput
instance FromText Integer where
parser = A.signed A.decimal <* A.endOfInput
instance FromText Scientific where
parser = A.signed A.scientific <* A.endOfInput
instance FromText Natural where
parser = A.decimal <* A.endOfInput
instance FromText Double where
parser = A.signed A.rational <* A.endOfInput
instance FromText Bool where
parser = takeLowerText >>= \case
"true" -> pure True
"false" -> pure False
e -> fromTextError $ "Failure parsing Bool from '" <> e <> "'."
instance FromText StdMethod where
parser = do
bs <- Text.encodeUtf8 <$> A.takeText
either (fail . BS8.unpack) pure (parseMethod bs)
showText :: ToText a => a -> String
showText = Text.unpack . toText
class ToText a where
toText :: a -> Text
instance ToText a => ToText (CI a) where
toText = toText . CI.original
instance ToText Text where toText = id
instance ToText ByteString where toText = Text.decodeUtf8
instance ToText Char where toText = Text.singleton
instance ToText String where toText = Text.pack
instance ToText Int where toText = shortText . Build.decimal
instance ToText Int64 where toText = shortText . Build.decimal
instance ToText Integer where toText = shortText . Build.decimal
instance ToText Natural where toText = shortText . Build.decimal
instance ToText Scientific where toText = shortText . Build.scientificBuilder
instance ToText Double where toText = toText . ($ "") . showFFloat Nothing
instance ToText StdMethod where toText = toText . renderStdMethod
instance ToText (Digest a) where toText = toText . digestToBase Base16
instance ToText Bool where
toText True = "true"
toText False = "false"
shortText :: Builder -> Text
shortText = LText.toStrict . Build.toLazyTextWith 32
toTextCI :: ToText a => a -> CI Text
toTextCI = CI.mk . toText
| fmapfmapfmap/amazonka | core/src/Network/AWS/Data/Text.hs | mpl-2.0 | 4,385 | 0 | 12 | 1,107 | 1,019 | 572 | 447 | 97 | 1 |
-----------------------------------------------------------------------------------------
{-| Module : HaskellNames
Copyright : (c) Daan Leijen 2003
License : BSD-style
Maintainer : wxhaskell-devel@lists.sourceforge.net
Stability : provisional
Portability : portable
Utility module to create Haskell compatible names.
-}
-----------------------------------------------------------------------------------------
module HaskellNames( haskellDeclName
, haskellName, haskellTypeName, haskellUnBuiltinTypeName
, haskellUnderscoreName, haskellArgName
, isBuiltin
, getPrologue
) where
import qualified Data.Set as Set
import Data.Char( toLower, toUpper, isLower, isUpper )
import Data.List( isPrefixOf )
{-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------}
builtinObjects :: Set.Set String
builtinObjects
= Set.fromList ["wxColour","wxString"]
{-
[ "Bitmap"
, "Brush"
, "Colour"
, "Cursor"
, "DateTime"
, "Icon"
, "Font"
, "FontData"
, "ListItem"
, "PageSetupData"
, "Pen"
, "PrintData"
, "PrintDialogData"
, "TreeItemId"
]
-}
reservedVarNames :: Set.Set String
reservedVarNames
= Set.fromList
["data"
,"int"
,"init"
,"module"
,"raise"
,"type"
,"objectDelete"
]
reservedTypeNames :: Set.Set String
reservedTypeNames
= Set.fromList
[ "Object"
, "Managed"
, "ManagedPtr"
, "Array"
, "Date"
, "Dir"
, "DllLoader"
, "Expr"
, "File"
, "Point"
, "Size"
, "String"
, "Rect"
]
{-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------}
haskellDeclName :: String -> String
haskellDeclName name
| isPrefixOf "wxMDI" name = haskellName ("mdi" ++ drop 5 name)
| isPrefixOf "wxDC_" name = haskellName ("dc" ++ drop 5 name)
| isPrefixOf "wxGL" name = haskellName ("gl" ++ drop 4 name)
| isPrefixOf "wxSVG" name = haskellName ("svg" ++ drop 5 name)
| isPrefixOf "expEVT_" name = ("wxEVT_" ++ drop 7 name) -- keep underscores
| isPrefixOf "exp" name = ("wx" ++ drop 3 name)
| isPrefixOf "wxc" name = haskellName name
| isPrefixOf "wx" name = haskellName (drop 2 name)
| isPrefixOf "ELJ" name = haskellName ("wxc" ++ drop 3 name)
| isPrefixOf "DDE" name = haskellName ("dde" ++ drop 3 name)
| otherwise = haskellName name
haskellArgName :: String -> String
haskellArgName name
= haskellName (dropWhile (=='_') name)
haskellName :: String -> String
haskellName name
| Set.member suggested reservedVarNames = "wx" ++ suggested
| otherwise = suggested
where
suggested
= case name of
(c:cs) -> toLower c : filter (/='_') cs
[] -> "wx"
haskellUnderscoreName :: String -> String
haskellUnderscoreName name
| Set.member suggested reservedVarNames = "wx" ++ suggested
| otherwise = suggested
where
suggested
= case name of
('W':'X':cs) -> "wx" ++ cs
(c:cs) -> toLower c : cs
[] -> "wx"
haskellTypeName :: String -> String
haskellTypeName name
| isPrefixOf "ELJ" name = haskellTypeName ("WXC" ++ drop 3 name)
| Set.member suggested reservedTypeNames = "Wx" ++ suggested
| otherwise = suggested
where
suggested
= case name of
'W':'X':'C':cs -> "WXC" ++ cs
'w':'x':'c':cs -> "WXC" ++ cs
'w':'x':cs -> firstUpper cs
_ -> firstUpper name
firstUpper name'
= case name' of
c:cs | isLower c -> toUpper c : cs
| not (isUpper c) -> "Wx" ++ name'
| otherwise -> name'
[] -> "Wx"
haskellUnBuiltinTypeName :: String -> String
haskellUnBuiltinTypeName name
| isBuiltin name = haskellTypeName name ++ "Object"
| otherwise = haskellTypeName name
isBuiltin :: String -> Bool
isBuiltin name
= Set.member name builtinObjects
{-----------------------------------------------------------------------------------------
Haddock prologue
-----------------------------------------------------------------------------------------}
getPrologue :: String -> String -> String -> [String] -> [String]
getPrologue moduleName content contains inputFiles
= [line
,"{-|\tModule : " ++ moduleName
,"\tCopyright : Copyright (c) Daan Leijen 2003, 2004"
,"\tLicense : wxWidgets"
,""
,"\tMaintainer : wxhaskell-devel@lists.sourceforge.net"
,"\tStability : provisional"
,"\tPortability : portable"
,""
,"Haskell " ++ content ++ " definitions for the wxWidgets C library (@wxc.dll@)."
,""
,"Do not edit this file manually!"
,"This file was automatically generated by wxDirect."
]
++
(if (null inputFiles)
then []
else (["","From the files:"] ++ concatMap showFile inputFiles))
++
[""
,"And contains " ++ contains
,"-}"
,line
]
where
line = replicate 80 '-'
showFile fname
= [""," * @" ++ concatMap escapeSlash fname ++ "@"]
escapeSlash c
| c == '/' = "\\/"
| c == '\"' = "\\\""
| otherwise = [c]
| ekmett/wxHaskell | wxdirect/src/HaskellNames.hs | lgpl-2.1 | 5,640 | 0 | 15 | 1,576 | 1,255 | 640 | 615 | 125 | 5 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Handler.Browse
( getBrowseR
) where
import Wiki
import Handler.Labels (getLTree)
import Handler.Topic (showLTree)
import Data.Maybe (mapMaybe, catMaybes)
import qualified Data.Set as Set
import Data.List (sortBy)
import Data.Ord (comparing)
data Entry = Entry
{ etitle :: Text
, eauthor :: User
, eurl :: WikiRoute
}
getBrowseR :: Handler RepHtml
getBrowseR = do
ltree <- getLTree
sel <- mapMaybe (fromSinglePiece . fst) . reqGetParams <$> getRequest
let active = flip elem sel
entriesT <- catMaybes <$> (runDB $ selectList [] [] >>= mapM (\(tid, t) -> do
lids <- (map $ topicLabelLabel . snd) <$> selectList [TopicLabelTopic ==. tid] []
if applyFilter sel lids
then do
u <- get404 $ topicOwner t
return $ Just Entry
{ etitle = topicTitle t
, eauthor = u
, eurl = TopicR tid
}
else return Nothing))
entriesM <- catMaybes <$> (runDB $ selectList [] [] >>= mapM (\(mid, m) -> do
lids <- (map $ mapLabelLabel . snd) <$> selectList [MapLabelMap ==. mid] []
if applyFilter sel lids
then do
u <- get404 $ tMapOwner m
return $ Just Entry
{ etitle = tMapTitle m
, eauthor = u
, eurl = ShowMapR mid
}
else return Nothing))
let entries = sortBy (comparing etitle) $ entriesT ++ entriesM
defaultLayout $ do
addScript $ StaticR jquery_js
$(widgetFile "browse")
applyFilter :: [LabelId] -- ^ selected
-> [LabelId] -- ^ this topic
-> Bool
applyFilter sel top = Set.fromList sel `Set.isSubsetOf` Set.fromList top
| snoyberg/yesoddocs | Handler/Browse.hs | bsd-2-clause | 1,870 | 0 | 23 | 644 | 570 | 297 | 273 | 47 | 3 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Text/Appar/Parser.hs" #-}
{-# LANGUAGE OverloadedStrings #-}
{-|
This is subset of Parsec.
Parsec 3 provides features which Parsec 2 does not provide:
* Applicative style
* ByteString as input
But Haskell Platform includes Parsec 2, not Parsec 3. Installing
Parsec 3 to Haskell Platform environment makes it mess. So, this library
was implemented.
-}
module Text.Appar.Parser (
-- ** Running parser
parse
-- ** 'Char' parsers
, char
, anyChar
, oneOf
, noneOf
, alphaNum
, digit
, hexDigit
, space
-- ** 'String' parser
, string
-- ** Parser combinators
, try
, choice
, option
, skipMany
, skipSome
, sepBy1
, manyTill
-- ** 'Applicative' parser combinators
, (<$>)
, (<$)
, (<*>)
, (*>)
, (<*)
, (<**>)
, (<|>)
, some
, many
, pure
-- ** Internals
, MkParser(..)
, Input(..)
, satisfy
) where
import Control.Applicative
import Control.Monad
import Data.Char
import Text.Appar.Input
----------------------------------------------------------------
data MkParser inp a = P {
-- | Getting the internal parser.
runParser :: inp -> (Maybe a, inp)
}
----------------------------------------------------------------
instance Functor (MkParser inp) where
f `fmap` p = return f <*> p
instance Applicative (MkParser inp) where
pure = return
(<*>) = ap
instance Alternative (MkParser inp) where
empty = mzero
(<|>) = mplus
instance Monad (MkParser inp) where
return a = P $ \bs -> (Just a, bs)
p >>= f = P $ \bs -> case runParser p bs of
(Nothing, bs') -> (Nothing, bs')
(Just a, bs') -> runParser (f a) bs'
fail _ = P $ \bs -> (Nothing, bs)
instance MonadPlus (MkParser inp) where
mzero = P $ \bs -> (Nothing, bs)
p `mplus` q = P $ \bs -> case runParser p bs of
(Nothing, bs') -> runParser q bs'
(Just a, bs') -> (Just a, bs')
----------------------------------------------------------------
{-|
Run a parser.
-}
parse :: Input inp => MkParser inp a -> inp -> Maybe a
parse p bs = fst (runParser p bs)
----------------------------------------------------------------
{-|
The parser @satisfy f@ succeeds for any character for which the
supplied function @f@ returns 'True'. Returns the character that is
actually parsed.
-}
satisfy :: Input inp => (Char -> Bool) -> MkParser inp Char
satisfy predicate = P sat
where
sat bs
| isNil bs = (Nothing, nil)
| predicate b = (Just b, bs')
| otherwise = (Nothing, bs)
where
b = car bs
bs' = cdr bs
----------------------------------------------------------------
{-|
The parser try p behaves like parser p, except that it pretends
that it hasn't consumed any input when an error occurs.
-}
try :: MkParser inp a -> MkParser inp a
try p = P $ \bs -> case runParser p bs of
(Nothing, _ ) -> (Nothing, bs)
(Just a, bs') -> (Just a, bs')
----------------------------------------------------------------
{-|
@char c@ parses a single character @c@. Returns the parsed character.
-}
char :: Input inp => Char -> MkParser inp Char
char c = satisfy (c ==)
{-|
@string s@ parses a sequence of characters given by @s@. Returns
the parsed string
-}
string :: Input inp => String -> MkParser inp String
string [] = pure ""
string (c:cs) = (:) <$> char c <*> string cs
----------------------------------------------------------------
{-|
This parser succeeds for any character. Returns the parsed character.
-}
anyChar :: Input inp => MkParser inp Char
anyChar = satisfy (const True)
{-|
@oneOf cs@ succeeds if the current character is in the supplied list of
characters @cs@. Returns the parsed character.
-}
oneOf :: Input inp => String -> MkParser inp Char
oneOf cs = satisfy (`elem` cs)
{-|
As the dual of 'oneOf', @noneOf cs@ succeeds if the current
character /not/ in the supplied list of characters @cs@. Returns the
parsed character.
-}
noneOf :: Input inp => String -> MkParser inp Char
noneOf cs = satisfy (`notElem` cs)
{-|
Parses a letter or digit (a character between \'0\' and \'9\').
Returns the parsed character.
-}
alphaNum :: Input inp => MkParser inp Char
alphaNum = satisfy isAlphaNum
{-|
Parses a digit. Returns the parsed character.
-}
digit :: Input inp => MkParser inp Char
digit = satisfy isDigit
{-|
Parses a hexadecimal digit (a digit or a letter between \'a\' and
\'f\' or \'A\' and \'F\'). Returns the parsed character.
-}
hexDigit :: Input inp => MkParser inp Char
hexDigit = satisfy isHexDigit
{-|
Parses a white space character (any character which satisfies 'isSpace')
Returns the parsed character.
-}
space :: Input inp => MkParser inp Char
space = satisfy isSpace
----------------------------------------------------------------
{-|
@choice ps@ tries to apply the parsers in the list @ps@ in order,
until one of them succeeds. Returns the value of the succeeding
parser.
-}
choice :: [MkParser inp a] -> MkParser inp a
choice = foldr (<|>) mzero
{-|
@option x p@ tries to apply parser @p@. If @p@ fails without
consuming input, it returns the value @x@, otherwise the value
returned by @p@.
-}
option :: a -> MkParser inp a -> MkParser inp a
option x p = p <|> pure x
{-|
@skipMany p@ applies the parser @p@ /zero/ or more times, skipping
its result.
-}
skipMany :: MkParser inp a -> MkParser inp ()
skipMany p = () <$ many p
{-|
@skipSome p@ applies the parser @p@ /one/ or more times, skipping
its result.
-}
skipSome :: MkParser inp a -> MkParser inp ()
skipSome p = () <$ some p
{-|
@sepBy1 p sep@ parses /one/ or more occurrences of @p@, separated
by @sep@. Returns a list of values returned by @p@.
-}
sepBy1 :: MkParser inp a -> MkParser inp b -> MkParser inp [a]
sepBy1 p sep = (:) <$> p <*> many (sep *> p)
{-|
@manyTill p end@ applies parser @p@ /zero/ or more times until
parser @end@ succeeds. Returns the list of values returned by @p@.
-}
manyTill :: MkParser inp a -> MkParser inp b -> MkParser inp [a]
manyTill p end = scan
where
scan = [] <$ end <|> (:) <$> p <*> scan
| phischu/fragnix | tests/packages/scotty/Text.Appar.Parser.hs | bsd-3-clause | 6,137 | 0 | 13 | 1,363 | 1,378 | 749 | 629 | 105 | 2 |
{-| Utility functions for the maintenance daemon.
-}
{-
Copyright (C) 2015 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.MaintD.Utils
( annotateOpCode
, getRepairCommand
) where
import Control.Lens.Setter (over)
import qualified Text.JSON as J
import qualified Ganeti.Constants as C
import Ganeti.JQueue (reasonTrailTimestamp)
import Ganeti.JQueue.Objects (Timestamp)
import Ganeti.Objects.Maintenance (Incident(..))
import Ganeti.OpCodes (OpCode, MetaOpCode, wrapOpCode)
import Ganeti.OpCodes.Lens (metaParamsL, opReasonL)
-- | Wrap an `OpCode` into a `MetaOpCode` and adding an indication
-- that the `OpCode` was submitted by the maintenance daemon.
annotateOpCode :: String -> Timestamp -> OpCode -> MetaOpCode
annotateOpCode reason ts =
over (metaParamsL . opReasonL)
(++ [(C.opcodeReasonSrcMaintd, reason, reasonTrailTimestamp ts)])
. wrapOpCode
-- | Get the name of the repair command from a live-repair incident.
getRepairCommand :: Incident -> Maybe String
getRepairCommand incident
| J.JSObject obj <- incidentOriginal incident,
Just (J.JSString cmd) <- lookup "command" $ J.fromJSObject obj
= return $ J.fromJSString cmd
getRepairCommand _ = Nothing
| leshchevds/ganeti | src/Ganeti/MaintD/Utils.hs | bsd-2-clause | 2,437 | 0 | 12 | 372 | 263 | 150 | 113 | 22 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Пересмотреть | ZAP-расширение </title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Содержание</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Индекс</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Поиск</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Избранное</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/revisit/src/main/javahelp/org/zaproxy/zap/extension/revisit/resources/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 1,029 | 83 | 53 | 158 | 493 | 255 | 238 | -1 | -1 |
-- | This is a simple line-based protocol used for communication between
-- a local and remote propellor. It's sent over a ssh channel, and lines of
-- the protocol can be interspersed with other, non-protocol lines
-- that should be passed through to be displayed.
--
-- Avoid making backwards-incompatible changes to this protocol,
-- since propellor needs to use this protocol to update itself to new
-- versions speaking newer versions of the protocol.
module Propellor.Protocol where
import Data.List
import Propellor
data Stage = NeedGitClone | NeedRepoUrl | NeedPrivData | NeedGitPush | NeedPrecompiled
deriving (Read, Show, Eq)
type Marker = String
type Marked = String
statusMarker :: Marker
statusMarker = "STATUS"
privDataMarker :: String
privDataMarker = "PRIVDATA "
repoUrlMarker :: String
repoUrlMarker = "REPOURL "
gitPushMarker :: String
gitPushMarker = "GITPUSH"
toMarked :: Marker -> String -> String
toMarked = (++)
fromMarked :: Marker -> Marked -> Maybe String
fromMarked marker s
| marker `isPrefixOf` s = Just $ drop (length marker) s
| otherwise = Nothing
sendMarked :: Handle -> Marker -> String -> IO ()
sendMarked h marker s = do
debug ["sent marked", marker]
sendMarked' h marker s
sendMarked' :: Handle -> Marker -> String -> IO ()
sendMarked' h marker s = do
-- Prefix string with newline because sometimes a
-- incomplete line has been output, and the marker needs to
-- come at the start of a line.
hPutStrLn h ("\n" ++ toMarked marker s)
hFlush h
getMarked :: Handle -> Marker -> IO (Maybe String)
getMarked h marker = go =<< catchMaybeIO (hGetLine h)
where
go Nothing = return Nothing
go (Just l) = case fromMarked marker l of
Nothing -> do
unless (null l) $
hPutStrLn stderr l
getMarked h marker
Just v -> do
debug ["received marked", marker]
return (Just v)
req :: Stage -> Marker -> (String -> IO ()) -> IO ()
req stage marker a = do
debug ["requested marked", marker]
sendMarked' stdout statusMarker (show stage)
maybe noop a =<< getMarked stdin marker
| sjfloat/propellor | src/Propellor/Protocol.hs | bsd-2-clause | 2,043 | 4 | 15 | 389 | 553 | 283 | 270 | 45 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.ModuleName
-- Copyright : Duncan Coutts 2008
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- Data type for Haskell module names.
module Distribution.ModuleName (
ModuleName,
fromString,
components,
toFilePath,
main,
simple,
) where
import Distribution.Text
import Distribution.Compat.Binary
import qualified Distribution.Compat.ReadP as Parse
import qualified Data.Char as Char
( isAlphaNum, isUpper )
import Data.Data (Data)
import Data.Typeable (Typeable)
import qualified Text.PrettyPrint as Disp
import Data.List
( intercalate, intersperse )
import GHC.Generics (Generic)
import System.FilePath
( pathSeparator )
-- | A valid Haskell module name.
--
newtype ModuleName = ModuleName [String]
deriving (Eq, Generic, Ord, Read, Show, Typeable, Data)
instance Binary ModuleName
instance Text ModuleName where
disp (ModuleName ms) =
Disp.hcat (intersperse (Disp.char '.') (map Disp.text ms))
parse = do
ms <- Parse.sepBy1 component (Parse.char '.')
return (ModuleName ms)
where
component = do
c <- Parse.satisfy Char.isUpper
cs <- Parse.munch validModuleChar
return (c:cs)
validModuleChar :: Char -> Bool
validModuleChar c = Char.isAlphaNum c || c == '_' || c == '\''
validModuleComponent :: String -> Bool
validModuleComponent [] = False
validModuleComponent (c:cs) = Char.isUpper c
&& all validModuleChar cs
{-# DEPRECATED simple "use ModuleName.fromString instead" #-}
simple :: String -> ModuleName
simple str = ModuleName [str]
-- | Construct a 'ModuleName' from a valid module name 'String'.
--
-- This is just a convenience function intended for valid module strings. It is
-- an error if it is used with a string that is not a valid module name. If you
-- are parsing user input then use 'Distribution.Text.simpleParse' instead.
--
fromString :: String -> ModuleName
fromString string
| all validModuleComponent components' = ModuleName components'
| otherwise = error badName
where
components' = split string
badName = "ModuleName.fromString: invalid module name " ++ show string
split cs = case break (=='.') cs of
(chunk,[]) -> chunk : []
(chunk,_:rest) -> chunk : split rest
-- | The module name @Main@.
--
main :: ModuleName
main = ModuleName ["Main"]
-- | The individual components of a hierarchical module name. For example
--
-- > components (fromString "A.B.C") = ["A", "B", "C"]
--
components :: ModuleName -> [String]
components (ModuleName ms) = ms
-- | Convert a module name to a file path, but without any file extension.
-- For example:
--
-- > toFilePath (fromString "A.B.C") = "A/B/C"
--
toFilePath :: ModuleName -> FilePath
toFilePath = intercalate [pathSeparator] . components
| tolysz/prepare-ghcjs | spec-lts8/cabal/Cabal/Distribution/ModuleName.hs | bsd-3-clause | 3,084 | 0 | 12 | 668 | 647 | 359 | 288 | 59 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : Stack.Sig.GPG
Description : GPG Functions
Copyright : (c) FPComplete.com, 2015
License : BSD3
Maintainer : Tim Dysinger <tim@fpcomplete.com>
Stability : experimental
Portability : POSIX
-}
module Stack.Sig.GPG (gpgSign, gpgVerify) where
import Prelude ()
import Prelude.Compat
import Control.Monad (unless, when)
import Control.Monad.Catch (MonadThrow, throwM)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger (MonadLogger, logWarn)
import qualified Data.ByteString.Char8 as C
import Data.List (find, isPrefixOf)
import Data.Monoid ((<>))
import qualified Data.Text as T
import Path
import Stack.Types.Sig
import System.Directory (findExecutable)
import System.Environment (lookupEnv)
import System.Exit (ExitCode(..))
import System.IO (Handle, hGetContents, hPutStrLn)
import System.Info (os)
import System.Process (ProcessHandle, runInteractiveProcess,
waitForProcess)
-- | Sign a file path with GPG, returning the @Signature@.
gpgSign
:: (MonadIO m, MonadLogger m, MonadThrow m)
=> Path Abs File -> m Signature
gpgSign path = do
gpgWarnTTY
(_hIn,hOut,hErr,process) <-
gpg
[ "--output"
, "-"
, "--use-agent"
, "--detach-sig"
, "--armor"
, toFilePath path]
(out,err,code) <-
liftIO
((,,) <$>
hGetContents hOut <*>
hGetContents hErr <*>
waitForProcess process)
if code /= ExitSuccess
then throwM (GPGSignException $ out <> "\n" <> err)
else return (Signature $ C.pack out)
-- | Verify the @Signature@ of a file path returning the
-- @Fingerprint@.
gpgVerify
:: (MonadIO m, MonadThrow m)
=> Signature -> Path Abs File -> m Fingerprint
gpgVerify (Signature signature) path = do
(hIn,hOut,hErr,process) <-
gpg ["--verify", "--with-fingerprint", "-", toFilePath path]
(_in,out,err,code) <-
liftIO
((,,,) <$>
hPutStrLn hIn (C.unpack signature) <*>
hGetContents hOut <*>
hGetContents hErr <*>
waitForProcess process)
if code /= ExitSuccess
then throwM (GPGVerifyException (out ++ "\n" ++ err))
else maybe
(throwM
(GPGFingerprintException
("unable to extract fingerprint from output\n: " <>
out)))
return
(mkFingerprint . T.pack . concat . drop 3 <$>
find
((==) ["Primary", "key", "fingerprint:"] . take 3)
(map words (lines err)))
-- | Try to execute `gpg2` but fallback to `gpg` (as a backup)
gpg
:: (MonadIO m, MonadThrow m)
=> [String] -> m (Handle, Handle, Handle, ProcessHandle)
gpg args = do
mGpg2Path <- liftIO (findExecutable "gpg2")
case mGpg2Path of
Just _ -> liftIO (runInteractiveProcess "gpg2" args Nothing Nothing)
Nothing -> do
mGpgPath <- liftIO (findExecutable "gpg")
case mGpgPath of
Just _ ->
liftIO (runInteractiveProcess "gpg" args Nothing Nothing)
Nothing -> throwM GPGNotFoundException
-- | `man gpg-agent` shows that you need GPG_TTY environment variable set to
-- properly deal with interactions with gpg-agent. (Doesn't apply to Windows
-- though)
gpgWarnTTY :: (MonadIO m, MonadLogger m) => m ()
gpgWarnTTY =
unless
("ming" `isPrefixOf` os)
(do mTTY <- liftIO (lookupEnv "GPG_TTY")
when
(null mTTY)
($logWarn
"Environment variable GPG_TTY is not set (see `man gpg-agent`)"))
| mrkkrp/stack | src/Stack/Sig/GPG.hs | bsd-3-clause | 4,036 | 0 | 17 | 1,304 | 936 | 511 | 425 | 93 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- | Modified from cereal, which is
-- Copyright : Lennart Kolmodin, Galois Inc. 2009
-- License : BSD3-style
module T9630a (
Serialize(..), GSerialize (..), Putter, Get
) where
import Data.ByteString.Builder (Builder)
import Data.ByteString as B
import GHC.Generics
import Control.Applicative (Applicative (..), (<$>))
class Serialize t where
put :: Putter t
get :: Get t
instance Serialize () where
put () = pure ()
get = pure ()
-- Generics
class GSerialize f where
gPut :: Putter (f a)
gGet :: Get (f a)
instance (GSerialize a, GSerialize b) => GSerialize (a :*: b) where
gPut (a :*: b) = gPut a *> gPut b
gGet = (:*:) <$> gGet <*> gGet
instance GSerialize a => GSerialize (M1 i c a) where
gPut = gPut . unM1
gGet = M1 <$> gGet
instance Serialize a => GSerialize (K1 i a) where
gPut = put . unK1
gGet = K1 <$> get
-- Put
data PairS a = PairS a !Builder
newtype PutM a = Put { unPut :: PairS a }
type Put = PutM ()
type Putter a = a -> Put
instance Functor PutM where
fmap f m = Put $ let PairS a w = unPut m in PairS (f a) w
instance Applicative PutM where
pure a = Put (PairS a mempty)
m <*> k = Put $
let PairS f w = unPut m
PairS x w' = unPut k
in PairS (f x) (w `mappend` w')
-- Get
data Result r = Fail String B.ByteString
| Partial (B.ByteString -> Result r)
| Done r B.ByteString
newtype Get a = Get
{ unGet :: forall r. Input -> Buffer -> More
-> Failure r -> Success a r
-> Result r }
type Input = B.ByteString
type Buffer = Maybe B.ByteString
type Failure r = Input -> Buffer -> More -> [String] -> String -> Result r
type Success a r = Input -> Buffer -> More -> a -> Result r
data More
= Complete
| Incomplete (Maybe Int)
deriving (Eq)
instance Functor Get where
fmap p m = Get $ \ s0 b0 m0 kf ks ->
unGet m s0 b0 m0 kf $ \ s1 b1 m1 a -> ks s1 b1 m1 (p a)
instance Applicative Get where
pure a = Get $ \ s0 b0 m0 _ ks -> ks s0 b0 m0 a
f <*> x = Get $ \ s0 b0 m0 kf ks ->
unGet f s0 b0 m0 kf $ \ s1 b1 m1 g ->
unGet x s1 b1 m1 kf $ \ s2 b2 m2 y -> ks s2 b2 m2 (g y)
| ezyang/ghc | testsuite/tests/perf/compiler/T9630a.hs | bsd-3-clause | 2,472 | 0 | 14 | 772 | 937 | 496 | 441 | 64 | 0 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
module GenBigTypes where
import GHC.Generics
data BigSum =
C0 | C1 | C2 | C3 | C4 | C5 | C6 | C7 | C8 | C9
| C10 | C11 | C12 | C13 | C14 | C15 | C16 | C17 | C18 | C19
| C20 | C21 | C22 | C23 | C24 | C25 | C26 | C27 | C28 | C29
| C30 | C31 | C32 | C33 | C34 | C35 | C36 | C37 | C38 | C39
| C40 | C41 | C42 | C43 | C44 | C45 | C46 | C47 | C48 | C49
| C50 | C51 | C52 | C53 | C54 | C55 | C56 | C57 | C58 | C59
| C60 | C61 | C62 | C63 | C64 | C65 | C66 | C67 | C68 | C69
| C70 | C71 | C72 | C73 | C74 | C75 | C76 | C77 | C78 | C79
| C80 | C81 | C82 | C83 | C84 | C85 | C86 | C87 | C88 | C89
| C90 | C91 | C92 | C93 | C94 | C95 | C96 | C97 | C98 | C99
{-
| C100 | C101 | C102 | C103 | C104 | C105 | C106 | C107 | C108 | C109
| C110 | C111 | C112 | C113 | C114 | C115 | C116 | C117 | C118 | C119
| C120 | C121 | C122 | C123 | C124 | C125 | C126 | C127 | C128 | C129
| C130 | C131 | C132 | C133 | C134 | C135 | C136 | C137 | C138 | C139
| C140 | C141 | C142 | C143 | C144 | C145 | C146 | C147 | C148 | C149
| C150 | C151 | C152 | C153 | C154 | C155 | C156 | C157 | C158 | C159
| C160 | C161 | C162 | C163 | C164 | C165 | C166 | C167 | C168 | C169
| C170 | C171 | C172 | C173 | C174 | C175 | C176 | C177 | C178 | C179
| C180 | C181 | C182 | C183 | C184 | C185 | C186 | C187 | C188 | C189
| C190 | C191 | C192 | C193 | C194 | C195 | C196 | C197 | C198 | C199
| C200 | C201 | C202 | C203 | C204 | C205 | C206 | C207 | C208 | C209
| C210 | C211 | C212 | C213 | C214 | C215 | C216 | C217 | C218 | C219
| C220 | C221 | C222 | C223 | C224 | C225 | C226 | C227 | C228 | C229
| C230 | C231 | C232 | C233 | C234 | C235 | C236 | C237 | C238 | C239
| C240 | C241 | C242 | C243 | C244 | C245 | C246 | C247 | C248 | C249
| C250 | C251 | C252 | C253 | C254 | C255 | C256 | C257 | C258 | C259
| C260 | C261 | C262 | C263 | C264 | C265 | C266 | C267 | C268 | C269
| C270 | C271 | C272 | C273 | C274 | C275 | C276 | C277 | C278 | C279
| C280 | C281 | C282 | C283 | C284 | C285 | C286 | C287 | C288 | C289
| C290 | C291 | C292 | C293 | C294 | C295 | C296 | C297 | C298 | C299
--deriving Generic
-}
instance Generic BigSum where
type Rep BigSum = Rep_BigSum
from C0 = M1 (L1 (L1 (L1 (L1 (L1 (L1 (M1 U1)))))))
from C1 = M1 (L1 (L1 (L1 (L1 (L1 (R1 (L1 (M1 U1))))))))
from C2 = M1 (L1 (L1 (L1 (L1 (L1 (R1 (R1 (M1 U1))))))))
from C3 = M1 (L1 (L1 (L1 (L1 (R1 (L1 (M1 U1)))))))
from C4 = M1 (L1 (L1 (L1 (L1 (R1 (R1 (L1 (M1 U1))))))))
from C5 = M1 (L1 (L1 (L1 (L1 (R1 (R1 (R1 (M1 U1))))))))
from C6 = M1 (L1 (L1 (L1 (R1 (L1 (L1 (M1 U1)))))))
from C7 = M1 (L1 (L1 (L1 (R1 (L1 (R1 (L1 (M1 U1))))))))
from C8 = M1 (L1 (L1 (L1 (R1 (L1 (R1 (R1 (M1 U1))))))))
from C9 = M1 (L1 (L1 (L1 (R1 (R1 (L1 (M1 U1)))))))
from C10 = M1 (L1 (L1 (L1 (R1 (R1 (R1 (L1 (M1 U1))))))))
from C11 = M1 (L1 (L1 (L1 (R1 (R1 (R1 (R1 (M1 U1))))))))
from C12 = M1 (L1 (L1 (R1 (L1 (L1 (L1 (M1 U1)))))))
from C13 = M1 (L1 (L1 (R1 (L1 (L1 (R1 (L1 (M1 U1))))))))
from C14 = M1 (L1 (L1 (R1 (L1 (L1 (R1 (R1 (M1 U1))))))))
from C15 = M1 (L1 (L1 (R1 (L1 (R1 (L1 (M1 U1)))))))
from C16 = M1 (L1 (L1 (R1 (L1 (R1 (R1 (L1 (M1 U1))))))))
from C17 = M1 (L1 (L1 (R1 (L1 (R1 (R1 (R1 (M1 U1))))))))
from C18 = M1 (L1 (L1 (R1 (R1 (L1 (L1 (M1 U1)))))))
from C19 = M1 (L1 (L1 (R1 (R1 (L1 (R1 (L1 (M1 U1))))))))
from C20 = M1 (L1 (L1 (R1 (R1 (L1 (R1 (R1 (M1 U1))))))))
from C21 = M1 (L1 (L1 (R1 (R1 (R1 (L1 (L1 (M1 U1))))))))
from C22 = M1 (L1 (L1 (R1 (R1 (R1 (L1 (R1 (M1 U1))))))))
from C23 = M1 (L1 (L1 (R1 (R1 (R1 (R1 (L1 (M1 U1))))))))
from C24 = M1 (L1 (L1 (R1 (R1 (R1 (R1 (R1 (M1 U1))))))))
from C25 = M1 (L1 (R1 (L1 (L1 (L1 (L1 (M1 U1)))))))
from C26 = M1 (L1 (R1 (L1 (L1 (L1 (R1 (L1 (M1 U1))))))))
from C27 = M1 (L1 (R1 (L1 (L1 (L1 (R1 (R1 (M1 U1))))))))
from C28 = M1 (L1 (R1 (L1 (L1 (R1 (L1 (M1 U1)))))))
from C29 = M1 (L1 (R1 (L1 (L1 (R1 (R1 (L1 (M1 U1))))))))
from C30 = M1 (L1 (R1 (L1 (L1 (R1 (R1 (R1 (M1 U1))))))))
from C31 = M1 (L1 (R1 (L1 (R1 (L1 (L1 (M1 U1)))))))
from C32 = M1 (L1 (R1 (L1 (R1 (L1 (R1 (L1 (M1 U1))))))))
from C33 = M1 (L1 (R1 (L1 (R1 (L1 (R1 (R1 (M1 U1))))))))
from C34 = M1 (L1 (R1 (L1 (R1 (R1 (L1 (M1 U1)))))))
from C35 = M1 (L1 (R1 (L1 (R1 (R1 (R1 (L1 (M1 U1))))))))
from C36 = M1 (L1 (R1 (L1 (R1 (R1 (R1 (R1 (M1 U1))))))))
from C37 = M1 (L1 (R1 (R1 (L1 (L1 (L1 (M1 U1)))))))
from C38 = M1 (L1 (R1 (R1 (L1 (L1 (R1 (L1 (M1 U1))))))))
from C39 = M1 (L1 (R1 (R1 (L1 (L1 (R1 (R1 (M1 U1))))))))
from C40 = M1 (L1 (R1 (R1 (L1 (R1 (L1 (M1 U1)))))))
from C41 = M1 (L1 (R1 (R1 (L1 (R1 (R1 (L1 (M1 U1))))))))
from C42 = M1 (L1 (R1 (R1 (L1 (R1 (R1 (R1 (M1 U1))))))))
from C43 = M1 (L1 (R1 (R1 (R1 (L1 (L1 (M1 U1)))))))
from C44 = M1 (L1 (R1 (R1 (R1 (L1 (R1 (L1 (M1 U1))))))))
from C45 = M1 (L1 (R1 (R1 (R1 (L1 (R1 (R1 (M1 U1))))))))
from C46 = M1 (L1 (R1 (R1 (R1 (R1 (L1 (L1 (M1 U1))))))))
from C47 = M1 (L1 (R1 (R1 (R1 (R1 (L1 (R1 (M1 U1))))))))
from C48 = M1 (L1 (R1 (R1 (R1 (R1 (R1 (L1 (M1 U1))))))))
from C49 = M1 (L1 (R1 (R1 (R1 (R1 (R1 (R1 (M1 U1))))))))
from C50 = M1 (R1 (L1 (L1 (L1 (L1 (L1 (M1 U1)))))))
from C51 = M1 (R1 (L1 (L1 (L1 (L1 (R1 (L1 (M1 U1))))))))
from C52 = M1 (R1 (L1 (L1 (L1 (L1 (R1 (R1 (M1 U1))))))))
from C53 = M1 (R1 (L1 (L1 (L1 (R1 (L1 (M1 U1)))))))
from C54 = M1 (R1 (L1 (L1 (L1 (R1 (R1 (L1 (M1 U1))))))))
from C55 = M1 (R1 (L1 (L1 (L1 (R1 (R1 (R1 (M1 U1))))))))
from C56 = M1 (R1 (L1 (L1 (R1 (L1 (L1 (M1 U1)))))))
from C57 = M1 (R1 (L1 (L1 (R1 (L1 (R1 (L1 (M1 U1))))))))
from C58 = M1 (R1 (L1 (L1 (R1 (L1 (R1 (R1 (M1 U1))))))))
from C59 = M1 (R1 (L1 (L1 (R1 (R1 (L1 (M1 U1)))))))
from C60 = M1 (R1 (L1 (L1 (R1 (R1 (R1 (L1 (M1 U1))))))))
from C61 = M1 (R1 (L1 (L1 (R1 (R1 (R1 (R1 (M1 U1))))))))
from C62 = M1 (R1 (L1 (R1 (L1 (L1 (L1 (M1 U1)))))))
from C63 = M1 (R1 (L1 (R1 (L1 (L1 (R1 (L1 (M1 U1))))))))
from C64 = M1 (R1 (L1 (R1 (L1 (L1 (R1 (R1 (M1 U1))))))))
from C65 = M1 (R1 (L1 (R1 (L1 (R1 (L1 (M1 U1)))))))
from C66 = M1 (R1 (L1 (R1 (L1 (R1 (R1 (L1 (M1 U1))))))))
from C67 = M1 (R1 (L1 (R1 (L1 (R1 (R1 (R1 (M1 U1))))))))
from C68 = M1 (R1 (L1 (R1 (R1 (L1 (L1 (M1 U1)))))))
from C69 = M1 (R1 (L1 (R1 (R1 (L1 (R1 (L1 (M1 U1))))))))
from C70 = M1 (R1 (L1 (R1 (R1 (L1 (R1 (R1 (M1 U1))))))))
from C71 = M1 (R1 (L1 (R1 (R1 (R1 (L1 (L1 (M1 U1))))))))
from C72 = M1 (R1 (L1 (R1 (R1 (R1 (L1 (R1 (M1 U1))))))))
from C73 = M1 (R1 (L1 (R1 (R1 (R1 (R1 (L1 (M1 U1))))))))
from C74 = M1 (R1 (L1 (R1 (R1 (R1 (R1 (R1 (M1 U1))))))))
from C75 = M1 (R1 (R1 (L1 (L1 (L1 (L1 (M1 U1)))))))
from C76 = M1 (R1 (R1 (L1 (L1 (L1 (R1 (L1 (M1 U1))))))))
from C77 = M1 (R1 (R1 (L1 (L1 (L1 (R1 (R1 (M1 U1))))))))
from C78 = M1 (R1 (R1 (L1 (L1 (R1 (L1 (M1 U1)))))))
from C79 = M1 (R1 (R1 (L1 (L1 (R1 (R1 (L1 (M1 U1))))))))
from C80 = M1 (R1 (R1 (L1 (L1 (R1 (R1 (R1 (M1 U1))))))))
from C81 = M1 (R1 (R1 (L1 (R1 (L1 (L1 (M1 U1)))))))
from C82 = M1 (R1 (R1 (L1 (R1 (L1 (R1 (L1 (M1 U1))))))))
from C83 = M1 (R1 (R1 (L1 (R1 (L1 (R1 (R1 (M1 U1))))))))
from C84 = M1 (R1 (R1 (L1 (R1 (R1 (L1 (M1 U1)))))))
from C85 = M1 (R1 (R1 (L1 (R1 (R1 (R1 (L1 (M1 U1))))))))
from C86 = M1 (R1 (R1 (L1 (R1 (R1 (R1 (R1 (M1 U1))))))))
from C87 = M1 (R1 (R1 (R1 (L1 (L1 (L1 (M1 U1)))))))
from C88 = M1 (R1 (R1 (R1 (L1 (L1 (R1 (L1 (M1 U1))))))))
from C89 = M1 (R1 (R1 (R1 (L1 (L1 (R1 (R1 (M1 U1))))))))
from C90 = M1 (R1 (R1 (R1 (L1 (R1 (L1 (M1 U1)))))))
from C91 = M1 (R1 (R1 (R1 (L1 (R1 (R1 (L1 (M1 U1))))))))
from C92 = M1 (R1 (R1 (R1 (L1 (R1 (R1 (R1 (M1 U1))))))))
from C93 = M1 (R1 (R1 (R1 (R1 (L1 (L1 (M1 U1)))))))
from C94 = M1 (R1 (R1 (R1 (R1 (L1 (R1 (L1 (M1 U1))))))))
from C95 = M1 (R1 (R1 (R1 (R1 (L1 (R1 (R1 (M1 U1))))))))
from C96 = M1 (R1 (R1 (R1 (R1 (R1 (L1 (L1 (M1 U1))))))))
from C97 = M1 (R1 (R1 (R1 (R1 (R1 (L1 (R1 (M1 U1))))))))
from C98 = M1 (R1 (R1 (R1 (R1 (R1 (R1 (L1 (M1 U1))))))))
from C99 = M1 (R1 (R1 (R1 (R1 (R1 (R1 (R1 (M1 U1))))))))
to (M1 (L1 (L1 (L1 (L1 (L1 (L1 (M1 U1)))))))) = C0
to (M1 (L1 (L1 (L1 (L1 (L1 (R1 (L1 (M1 U1))))))))) = C1
to (M1 (L1 (L1 (L1 (L1 (L1 (R1 (R1 (M1 U1))))))))) = C2
to (M1 (L1 (L1 (L1 (L1 (R1 (L1 (M1 U1)))))))) = C3
to (M1 (L1 (L1 (L1 (L1 (R1 (R1 (L1 (M1 U1))))))))) = C4
to (M1 (L1 (L1 (L1 (L1 (R1 (R1 (R1 (M1 U1))))))))) = C5
to (M1 (L1 (L1 (L1 (R1 (L1 (L1 (M1 U1)))))))) = C6
to (M1 (L1 (L1 (L1 (R1 (L1 (R1 (L1 (M1 U1))))))))) = C7
to (M1 (L1 (L1 (L1 (R1 (L1 (R1 (R1 (M1 U1))))))))) = C8
to (M1 (L1 (L1 (L1 (R1 (R1 (L1 (M1 U1)))))))) = C9
to (M1 (L1 (L1 (L1 (R1 (R1 (R1 (L1 (M1 U1))))))))) = C10
to (M1 (L1 (L1 (L1 (R1 (R1 (R1 (R1 (M1 U1))))))))) = C11
to (M1 (L1 (L1 (R1 (L1 (L1 (L1 (M1 U1)))))))) = C12
to (M1 (L1 (L1 (R1 (L1 (L1 (R1 (L1 (M1 U1))))))))) = C13
to (M1 (L1 (L1 (R1 (L1 (L1 (R1 (R1 (M1 U1))))))))) = C14
to (M1 (L1 (L1 (R1 (L1 (R1 (L1 (M1 U1)))))))) = C15
to (M1 (L1 (L1 (R1 (L1 (R1 (R1 (L1 (M1 U1))))))))) = C16
to (M1 (L1 (L1 (R1 (L1 (R1 (R1 (R1 (M1 U1))))))))) = C17
to (M1 (L1 (L1 (R1 (R1 (L1 (L1 (M1 U1)))))))) = C18
to (M1 (L1 (L1 (R1 (R1 (L1 (R1 (L1 (M1 U1))))))))) = C19
to (M1 (L1 (L1 (R1 (R1 (L1 (R1 (R1 (M1 U1))))))))) = C20
to (M1 (L1 (L1 (R1 (R1 (R1 (L1 (L1 (M1 U1))))))))) = C21
to (M1 (L1 (L1 (R1 (R1 (R1 (L1 (R1 (M1 U1))))))))) = C22
to (M1 (L1 (L1 (R1 (R1 (R1 (R1 (L1 (M1 U1))))))))) = C23
to (M1 (L1 (L1 (R1 (R1 (R1 (R1 (R1 (M1 U1))))))))) = C24
to (M1 (L1 (R1 (L1 (L1 (L1 (L1 (M1 U1)))))))) = C25
to (M1 (L1 (R1 (L1 (L1 (L1 (R1 (L1 (M1 U1))))))))) = C26
to (M1 (L1 (R1 (L1 (L1 (L1 (R1 (R1 (M1 U1))))))))) = C27
to (M1 (L1 (R1 (L1 (L1 (R1 (L1 (M1 U1)))))))) = C28
to (M1 (L1 (R1 (L1 (L1 (R1 (R1 (L1 (M1 U1))))))))) = C29
to (M1 (L1 (R1 (L1 (L1 (R1 (R1 (R1 (M1 U1))))))))) = C30
to (M1 (L1 (R1 (L1 (R1 (L1 (L1 (M1 U1)))))))) = C31
to (M1 (L1 (R1 (L1 (R1 (L1 (R1 (L1 (M1 U1))))))))) = C32
to (M1 (L1 (R1 (L1 (R1 (L1 (R1 (R1 (M1 U1))))))))) = C33
to (M1 (L1 (R1 (L1 (R1 (R1 (L1 (M1 U1)))))))) = C34
to (M1 (L1 (R1 (L1 (R1 (R1 (R1 (L1 (M1 U1))))))))) = C35
to (M1 (L1 (R1 (L1 (R1 (R1 (R1 (R1 (M1 U1))))))))) = C36
to (M1 (L1 (R1 (R1 (L1 (L1 (L1 (M1 U1)))))))) = C37
to (M1 (L1 (R1 (R1 (L1 (L1 (R1 (L1 (M1 U1))))))))) = C38
to (M1 (L1 (R1 (R1 (L1 (L1 (R1 (R1 (M1 U1))))))))) = C39
to (M1 (L1 (R1 (R1 (L1 (R1 (L1 (M1 U1)))))))) = C40
to (M1 (L1 (R1 (R1 (L1 (R1 (R1 (L1 (M1 U1))))))))) = C41
to (M1 (L1 (R1 (R1 (L1 (R1 (R1 (R1 (M1 U1))))))))) = C42
to (M1 (L1 (R1 (R1 (R1 (L1 (L1 (M1 U1)))))))) = C43
to (M1 (L1 (R1 (R1 (R1 (L1 (R1 (L1 (M1 U1))))))))) = C44
to (M1 (L1 (R1 (R1 (R1 (L1 (R1 (R1 (M1 U1))))))))) = C45
to (M1 (L1 (R1 (R1 (R1 (R1 (L1 (L1 (M1 U1))))))))) = C46
to (M1 (L1 (R1 (R1 (R1 (R1 (L1 (R1 (M1 U1))))))))) = C47
to (M1 (L1 (R1 (R1 (R1 (R1 (R1 (L1 (M1 U1))))))))) = C48
to (M1 (L1 (R1 (R1 (R1 (R1 (R1 (R1 (M1 U1))))))))) = C49
to (M1 (R1 (L1 (L1 (L1 (L1 (L1 (M1 U1)))))))) = C50
to (M1 (R1 (L1 (L1 (L1 (L1 (R1 (L1 (M1 U1))))))))) = C51
to (M1 (R1 (L1 (L1 (L1 (L1 (R1 (R1 (M1 U1))))))))) = C52
to (M1 (R1 (L1 (L1 (L1 (R1 (L1 (M1 U1)))))))) = C53
to (M1 (R1 (L1 (L1 (L1 (R1 (R1 (L1 (M1 U1))))))))) = C54
to (M1 (R1 (L1 (L1 (L1 (R1 (R1 (R1 (M1 U1))))))))) = C55
to (M1 (R1 (L1 (L1 (R1 (L1 (L1 (M1 U1)))))))) = C56
to (M1 (R1 (L1 (L1 (R1 (L1 (R1 (L1 (M1 U1))))))))) = C57
to (M1 (R1 (L1 (L1 (R1 (L1 (R1 (R1 (M1 U1))))))))) = C58
to (M1 (R1 (L1 (L1 (R1 (R1 (L1 (M1 U1)))))))) = C59
to (M1 (R1 (L1 (L1 (R1 (R1 (R1 (L1 (M1 U1))))))))) = C60
to (M1 (R1 (L1 (L1 (R1 (R1 (R1 (R1 (M1 U1))))))))) = C61
to (M1 (R1 (L1 (R1 (L1 (L1 (L1 (M1 U1)))))))) = C62
to (M1 (R1 (L1 (R1 (L1 (L1 (R1 (L1 (M1 U1))))))))) = C63
to (M1 (R1 (L1 (R1 (L1 (L1 (R1 (R1 (M1 U1))))))))) = C64
to (M1 (R1 (L1 (R1 (L1 (R1 (L1 (M1 U1)))))))) = C65
to (M1 (R1 (L1 (R1 (L1 (R1 (R1 (L1 (M1 U1))))))))) = C66
to (M1 (R1 (L1 (R1 (L1 (R1 (R1 (R1 (M1 U1))))))))) = C67
to (M1 (R1 (L1 (R1 (R1 (L1 (L1 (M1 U1)))))))) = C68
to (M1 (R1 (L1 (R1 (R1 (L1 (R1 (L1 (M1 U1))))))))) = C69
to (M1 (R1 (L1 (R1 (R1 (L1 (R1 (R1 (M1 U1))))))))) = C70
to (M1 (R1 (L1 (R1 (R1 (R1 (L1 (L1 (M1 U1))))))))) = C71
to (M1 (R1 (L1 (R1 (R1 (R1 (L1 (R1 (M1 U1))))))))) = C72
to (M1 (R1 (L1 (R1 (R1 (R1 (R1 (L1 (M1 U1))))))))) = C73
to (M1 (R1 (L1 (R1 (R1 (R1 (R1 (R1 (M1 U1))))))))) = C74
to (M1 (R1 (R1 (L1 (L1 (L1 (L1 (M1 U1)))))))) = C75
to (M1 (R1 (R1 (L1 (L1 (L1 (R1 (L1 (M1 U1))))))))) = C76
to (M1 (R1 (R1 (L1 (L1 (L1 (R1 (R1 (M1 U1))))))))) = C77
to (M1 (R1 (R1 (L1 (L1 (R1 (L1 (M1 U1)))))))) = C78
to (M1 (R1 (R1 (L1 (L1 (R1 (R1 (L1 (M1 U1))))))))) = C79
to (M1 (R1 (R1 (L1 (L1 (R1 (R1 (R1 (M1 U1))))))))) = C80
to (M1 (R1 (R1 (L1 (R1 (L1 (L1 (M1 U1)))))))) = C81
to (M1 (R1 (R1 (L1 (R1 (L1 (R1 (L1 (M1 U1))))))))) = C82
to (M1 (R1 (R1 (L1 (R1 (L1 (R1 (R1 (M1 U1))))))))) = C83
to (M1 (R1 (R1 (L1 (R1 (R1 (L1 (M1 U1)))))))) = C84
to (M1 (R1 (R1 (L1 (R1 (R1 (R1 (L1 (M1 U1))))))))) = C85
to (M1 (R1 (R1 (L1 (R1 (R1 (R1 (R1 (M1 U1))))))))) = C86
to (M1 (R1 (R1 (R1 (L1 (L1 (L1 (M1 U1)))))))) = C87
to (M1 (R1 (R1 (R1 (L1 (L1 (R1 (L1 (M1 U1))))))))) = C88
to (M1 (R1 (R1 (R1 (L1 (L1 (R1 (R1 (M1 U1))))))))) = C89
to (M1 (R1 (R1 (R1 (L1 (R1 (L1 (M1 U1)))))))) = C90
to (M1 (R1 (R1 (R1 (L1 (R1 (R1 (L1 (M1 U1))))))))) = C91
to (M1 (R1 (R1 (R1 (L1 (R1 (R1 (R1 (M1 U1))))))))) = C92
to (M1 (R1 (R1 (R1 (R1 (L1 (L1 (M1 U1)))))))) = C93
to (M1 (R1 (R1 (R1 (R1 (L1 (R1 (L1 (M1 U1))))))))) = C94
to (M1 (R1 (R1 (R1 (R1 (L1 (R1 (R1 (M1 U1))))))))) = C95
to (M1 (R1 (R1 (R1 (R1 (R1 (L1 (L1 (M1 U1))))))))) = C96
to (M1 (R1 (R1 (R1 (R1 (R1 (L1 (R1 (M1 U1))))))))) = C97
to (M1 (R1 (R1 (R1 (R1 (R1 (R1 (L1 (M1 U1))))))))) = C98
to (M1 (R1 (R1 (R1 (R1 (R1 (R1 (R1 (M1 U1))))))))) = C99
instance Datatype D1BigSum where
datatypeName _ = "BigSum"
moduleName _ = "GenBigTypes"
packageName _ = "main"
instance Constructor C1_0BigSum where
conName _ = "C0"
instance Constructor C1_1BigSum where
conName _ = "C1"
instance Constructor C1_2BigSum where
conName _ = "C2"
instance Constructor C1_3BigSum where
conName _ = "C3"
instance Constructor C1_4BigSum where
conName _ = "C4"
instance Constructor C1_5BigSum where
conName _ = "C5"
instance Constructor C1_6BigSum where
conName _ = "C6"
instance Constructor C1_7BigSum where
conName _ = "C7"
instance Constructor C1_8BigSum where
conName _ = "C8"
instance Constructor C1_9BigSum where
conName _ = "C9"
instance Constructor C1_10BigSum where
conName _ = "C10"
instance Constructor C1_11BigSum where
conName _ = "C11"
instance Constructor C1_12BigSum where
conName _ = "C12"
instance Constructor C1_13BigSum where
conName _ = "C13"
instance Constructor C1_14BigSum where
conName _ = "C14"
instance Constructor C1_15BigSum where
conName _ = "C15"
instance Constructor C1_16BigSum where
conName _ = "C16"
instance Constructor C1_17BigSum where
conName _ = "C17"
instance Constructor C1_18BigSum where
conName _ = "C18"
instance Constructor C1_19BigSum where
conName _ = "C19"
instance Constructor C1_20BigSum where
conName _ = "C20"
instance Constructor C1_21BigSum where
conName _ = "C21"
instance Constructor C1_22BigSum where
conName _ = "C22"
instance Constructor C1_23BigSum where
conName _ = "C23"
instance Constructor C1_24BigSum where
conName _ = "C24"
instance Constructor C1_25BigSum where
conName _ = "C25"
instance Constructor C1_26BigSum where
conName _ = "C26"
instance Constructor C1_27BigSum where
conName _ = "C27"
instance Constructor C1_28BigSum where
conName _ = "C28"
instance Constructor C1_29BigSum where
conName _ = "C29"
instance Constructor C1_30BigSum where
conName _ = "C30"
instance Constructor C1_31BigSum where
conName _ = "C31"
instance Constructor C1_32BigSum where
conName _ = "C32"
instance Constructor C1_33BigSum where
conName _ = "C33"
instance Constructor C1_34BigSum where
conName _ = "C34"
instance Constructor C1_35BigSum where
conName _ = "C35"
instance Constructor C1_36BigSum where
conName _ = "C36"
instance Constructor C1_37BigSum where
conName _ = "C37"
instance Constructor C1_38BigSum where
conName _ = "C38"
instance Constructor C1_39BigSum where
conName _ = "C39"
instance Constructor C1_40BigSum where
conName _ = "C40"
instance Constructor C1_41BigSum where
conName _ = "C41"
instance Constructor C1_42BigSum where
conName _ = "C42"
instance Constructor C1_43BigSum where
conName _ = "C43"
instance Constructor C1_44BigSum where
conName _ = "C44"
instance Constructor C1_45BigSum where
conName _ = "C45"
instance Constructor C1_46BigSum where
conName _ = "C46"
instance Constructor C1_47BigSum where
conName _ = "C47"
instance Constructor C1_48BigSum where
conName _ = "C48"
instance Constructor C1_49BigSum where
conName _ = "C49"
instance Constructor C1_50BigSum where
conName _ = "C50"
instance Constructor C1_51BigSum where
conName _ = "C51"
instance Constructor C1_52BigSum where
conName _ = "C52"
instance Constructor C1_53BigSum where
conName _ = "C53"
instance Constructor C1_54BigSum where
conName _ = "C54"
instance Constructor C1_55BigSum where
conName _ = "C55"
instance Constructor C1_56BigSum where
conName _ = "C56"
instance Constructor C1_57BigSum where
conName _ = "C57"
instance Constructor C1_58BigSum where
conName _ = "C58"
instance Constructor C1_59BigSum where
conName _ = "C59"
instance Constructor C1_60BigSum where
conName _ = "C60"
instance Constructor C1_61BigSum where
conName _ = "C61"
instance Constructor C1_62BigSum where
conName _ = "C62"
instance Constructor C1_63BigSum where
conName _ = "C63"
instance Constructor C1_64BigSum where
conName _ = "C64"
instance Constructor C1_65BigSum where
conName _ = "C65"
instance Constructor C1_66BigSum where
conName _ = "C66"
instance Constructor C1_67BigSum where
conName _ = "C67"
instance Constructor C1_68BigSum where
conName _ = "C68"
instance Constructor C1_69BigSum where
conName _ = "C69"
instance Constructor C1_70BigSum where
conName _ = "C70"
instance Constructor C1_71BigSum where
conName _ = "C71"
instance Constructor C1_72BigSum where
conName _ = "C72"
instance Constructor C1_73BigSum where
conName _ = "C73"
instance Constructor C1_74BigSum where
conName _ = "C74"
instance Constructor C1_75BigSum where
conName _ = "C75"
instance Constructor C1_76BigSum where
conName _ = "C76"
instance Constructor C1_77BigSum where
conName _ = "C77"
instance Constructor C1_78BigSum where
conName _ = "C78"
instance Constructor C1_79BigSum where
conName _ = "C79"
instance Constructor C1_80BigSum where
conName _ = "C80"
instance Constructor C1_81BigSum where
conName _ = "C81"
instance Constructor C1_82BigSum where
conName _ = "C82"
instance Constructor C1_83BigSum where
conName _ = "C83"
instance Constructor C1_84BigSum where
conName _ = "C84"
instance Constructor C1_85BigSum where
conName _ = "C85"
instance Constructor C1_86BigSum where
conName _ = "C86"
instance Constructor C1_87BigSum where
conName _ = "C87"
instance Constructor C1_88BigSum where
conName _ = "C88"
instance Constructor C1_89BigSum where
conName _ = "C89"
instance Constructor C1_90BigSum where
conName _ = "C90"
instance Constructor C1_91BigSum where
conName _ = "C91"
instance Constructor C1_92BigSum where
conName _ = "C92"
instance Constructor C1_93BigSum where
conName _ = "C93"
instance Constructor C1_94BigSum where
conName _ = "C94"
instance Constructor C1_95BigSum where
conName _ = "C95"
instance Constructor C1_96BigSum where
conName _ = "C96"
instance Constructor C1_97BigSum where
conName _ = "C97"
instance Constructor C1_98BigSum where
conName _ = "C98"
instance Constructor C1_99BigSum where
conName _ = "C99"
data D1BigSum
data C1_0BigSum
data C1_1BigSum
data C1_2BigSum
data C1_3BigSum
data C1_4BigSum
data C1_5BigSum
data C1_6BigSum
data C1_7BigSum
data C1_8BigSum
data C1_9BigSum
data C1_10BigSum
data C1_11BigSum
data C1_12BigSum
data C1_13BigSum
data C1_14BigSum
data C1_15BigSum
data C1_16BigSum
data C1_17BigSum
data C1_18BigSum
data C1_19BigSum
data C1_20BigSum
data C1_21BigSum
data C1_22BigSum
data C1_23BigSum
data C1_24BigSum
data C1_25BigSum
data C1_26BigSum
data C1_27BigSum
data C1_28BigSum
data C1_29BigSum
data C1_30BigSum
data C1_31BigSum
data C1_32BigSum
data C1_33BigSum
data C1_34BigSum
data C1_35BigSum
data C1_36BigSum
data C1_37BigSum
data C1_38BigSum
data C1_39BigSum
data C1_40BigSum
data C1_41BigSum
data C1_42BigSum
data C1_43BigSum
data C1_44BigSum
data C1_45BigSum
data C1_46BigSum
data C1_47BigSum
data C1_48BigSum
data C1_49BigSum
data C1_50BigSum
data C1_51BigSum
data C1_52BigSum
data C1_53BigSum
data C1_54BigSum
data C1_55BigSum
data C1_56BigSum
data C1_57BigSum
data C1_58BigSum
data C1_59BigSum
data C1_60BigSum
data C1_61BigSum
data C1_62BigSum
data C1_63BigSum
data C1_64BigSum
data C1_65BigSum
data C1_66BigSum
data C1_67BigSum
data C1_68BigSum
data C1_69BigSum
data C1_70BigSum
data C1_71BigSum
data C1_72BigSum
data C1_73BigSum
data C1_74BigSum
data C1_75BigSum
data C1_76BigSum
data C1_77BigSum
data C1_78BigSum
data C1_79BigSum
data C1_80BigSum
data C1_81BigSum
data C1_82BigSum
data C1_83BigSum
data C1_84BigSum
data C1_85BigSum
data C1_86BigSum
data C1_87BigSum
data C1_88BigSum
data C1_89BigSum
data C1_90BigSum
data C1_91BigSum
data C1_92BigSum
data C1_93BigSum
data C1_94BigSum
data C1_95BigSum
data C1_96BigSum
data C1_97BigSum
data C1_98BigSum
data C1_99BigSum
type Rep_BigSum = D1
D1BigSum
((((((C1 C1_0BigSum U1
:+: (C1
C1_1BigSum U1
:+: C1
C1_2BigSum
U1))
:+: (C1
C1_3BigSum U1
:+: (C1
C1_4BigSum
U1
:+: C1
C1_5BigSum
U1)))
:+: ((C1
C1_6BigSum U1
:+: (C1
C1_7BigSum
U1
:+: C1
C1_8BigSum
U1))
:+: (C1
C1_9BigSum
U1
:+: (C1
C1_10BigSum
U1
:+: C1
C1_11BigSum
U1))))
:+: (((C1
C1_12BigSum U1
:+: (C1
C1_13BigSum
U1
:+: C1
C1_14BigSum
U1))
:+: (C1
C1_15BigSum
U1
:+: (C1
C1_16BigSum
U1
:+: C1
C1_17BigSum
U1)))
:+: ((C1
C1_18BigSum
U1
:+: (C1
C1_19BigSum
U1
:+: C1
C1_20BigSum
U1))
:+: ((C1
C1_21BigSum
U1
:+: C1
C1_22BigSum
U1)
:+: (C1
C1_23BigSum
U1
:+: C1
C1_24BigSum
U1)))))
:+: ((((C1
C1_25BigSum U1
:+: (C1
C1_26BigSum
U1
:+: C1
C1_27BigSum
U1))
:+: (C1
C1_28BigSum
U1
:+: (C1
C1_29BigSum
U1
:+: C1
C1_30BigSum
U1)))
:+: ((C1
C1_31BigSum
U1
:+: (C1
C1_32BigSum
U1
:+: C1
C1_33BigSum
U1))
:+: (C1
C1_34BigSum
U1
:+: (C1
C1_35BigSum
U1
:+: C1
C1_36BigSum
U1))))
:+: (((C1
C1_37BigSum
U1
:+: (C1
C1_38BigSum
U1
:+: C1
C1_39BigSum
U1))
:+: (C1
C1_40BigSum
U1
:+: (C1
C1_41BigSum
U1
:+: C1
C1_42BigSum
U1)))
:+: ((C1
C1_43BigSum
U1
:+: (C1
C1_44BigSum
U1
:+: C1
C1_45BigSum
U1))
:+: ((C1
C1_46BigSum
U1
:+: C1
C1_47BigSum
U1)
:+: (C1
C1_48BigSum
U1
:+: C1
C1_49BigSum
U1))))))
:+: (((((C1
C1_50BigSum U1
:+: (C1
C1_51BigSum
U1
:+: C1
C1_52BigSum
U1))
:+: (C1
C1_53BigSum
U1
:+: (C1
C1_54BigSum
U1
:+: C1
C1_55BigSum
U1)))
:+: ((C1
C1_56BigSum
U1
:+: (C1
C1_57BigSum
U1
:+: C1
C1_58BigSum
U1))
:+: (C1
C1_59BigSum
U1
:+: (C1
C1_60BigSum
U1
:+: C1
C1_61BigSum
U1))))
:+: (((C1
C1_62BigSum
U1
:+: (C1
C1_63BigSum
U1
:+: C1
C1_64BigSum
U1))
:+: (C1
C1_65BigSum
U1
:+: (C1
C1_66BigSum
U1
:+: C1
C1_67BigSum
U1)))
:+: ((C1
C1_68BigSum
U1
:+: (C1
C1_69BigSum
U1
:+: C1
C1_70BigSum
U1))
:+: ((C1
C1_71BigSum
U1
:+: C1
C1_72BigSum
U1)
:+: (C1
C1_73BigSum
U1
:+: C1
C1_74BigSum
U1)))))
:+: ((((C1
C1_75BigSum
U1
:+: (C1
C1_76BigSum
U1
:+: C1
C1_77BigSum
U1))
:+: (C1
C1_78BigSum
U1
:+: (C1
C1_79BigSum
U1
:+: C1
C1_80BigSum
U1)))
:+: ((C1
C1_81BigSum
U1
:+: (C1
C1_82BigSum
U1
:+: C1
C1_83BigSum
U1))
:+: (C1
C1_84BigSum
U1
:+: (C1
C1_85BigSum
U1
:+: C1
C1_86BigSum
U1))))
:+: (((C1
C1_87BigSum
U1
:+: (C1
C1_88BigSum
U1
:+: C1
C1_89BigSum
U1))
:+: (C1
C1_90BigSum
U1
:+: (C1
C1_91BigSum
U1
:+: C1
C1_92BigSum
U1)))
:+: ((C1
C1_93BigSum
U1
:+: (C1
C1_94BigSum
U1
:+: C1
C1_95BigSum
U1))
:+: ((C1
C1_96BigSum
U1
:+: C1
C1_97BigSum
U1)
:+: (C1
C1_98BigSum
U1
:+: C1
C1_99BigSum
U1)))))))
{-
data BigProduct = C
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
() () () () () () () () () ()
deriving Generic
-}
| urbanslug/ghc | testsuite/tests/perf/compiler/T5642.hs | bsd-3-clause | 54,453 | 0 | 24 | 35,184 | 15,238 | 7,674 | 7,564 | -1 | -1 |
module T12063 where
import T12063a
x :: S
x = undefined
| olsner/ghc | testsuite/tests/typecheck/should_fail/T12063.hs | bsd-3-clause | 56 | 0 | 4 | 11 | 17 | 11 | 6 | 4 | 1 |
module DataTypes where
import GenUtils
import Data.Array -- 1.3
import Data.Ix
import Data.Char
infix 1 =: -- 1.3
(=:) a b = (a,b)
class Presentable a where
userFormat :: a -> String -- in prefered display format
instance (Presentable a) => Presentable [a] where
userFormat xs = unlines (map userFormat xs)
data Piece
= King
| Queen
| Rook
| Knight
| Bishop
| Pawn deriving(Eq)
instance Presentable Piece where
userFormat King = "K"
userFormat Queen = "Q"
userFormat Rook = "R"
userFormat Knight = "N"
userFormat Bishop = "B"
userFormat Pawn = "P"
castleK = "O-O"
castleQ = "O-O-O"
data Colour = Black | White deriving (Eq)
instance Presentable Colour where
userFormat White = "White"
userFormat Black = "Black"
changeColour :: Colour -> Colour
changeColour White = Black
changeColour Black = White
type ChessRank = Int -- 1-8
type ChessFile = Int -- 1-8
type BoardPos = (ChessFile,ChessRank) -- ChessFile (0-7) and ChessRank (0-7)
type ExBoardPos = (Maybe ChessFile,Maybe ChessRank)
extendBP :: BoardPos -> ExBoardPos
extendBP (a,b) = (Just a,Just b)
compExBPandBP :: ExBoardPos -> BoardPos -> Bool
compExBPandBP (a,b) (c,d) = a `cmp` c && b `cmp` d
where
cmp Nothing _ = True
cmp (Just x) y = x == y
userFormatBoardPos :: BoardPos -> String
userFormatBoardPos (f,r) = userFormatFile f ++ userFormatRank r
userFormatExBoardPos :: ExBoardPos -> String
userFormatExBoardPos (Just f,Just r) = userFormatFile f ++ userFormatRank r
userFormatExBoardPos (Just f,Nothing) = userFormatFile f
userFormatExBoardPos (Nothing,Just r) = userFormatRank r
userFormatExBoardPos _ = ""
userFormatRank r = [toEnum (r + 48)]
userFormatFile f = [toEnum (f + 96)]
data MoveTok
= PieceTok Piece -- Q,K,R,B,N
| RankTok ChessRank -- 1 .. 8
| FileTok ChessFile -- a .. h
| PartCastleTok -- 0 | O | o
| CaptureTok -- x
| MoveToTok -- -
| QueensWith -- =
| CheckTok -- +
| MateTok -- #
charToMoveTok 'Q' = Just (PieceTok Queen)
charToMoveTok 'K' = Just (PieceTok King)
charToMoveTok 'R' = Just (PieceTok Rook)
charToMoveTok 'B' = Just (PieceTok Bishop)
charToMoveTok 'N' = Just (PieceTok Knight)
charToMoveTok '1' = Just (RankTok 1)
charToMoveTok '2' = Just (RankTok 2)
charToMoveTok '3' = Just (RankTok 3)
charToMoveTok '4' = Just (RankTok 4)
charToMoveTok '5' = Just (RankTok 5)
charToMoveTok '6' = Just (RankTok 6)
charToMoveTok '7' = Just (RankTok 7)
charToMoveTok '8' = Just (RankTok 8)
charToMoveTok 'a' = Just (FileTok 1)
charToMoveTok 'b' = Just (FileTok 2)
charToMoveTok 'c' = Just (FileTok 3)
charToMoveTok 'd' = Just (FileTok 4)
charToMoveTok 'e' = Just (FileTok 5)
charToMoveTok 'f' = Just (FileTok 6)
charToMoveTok 'g' = Just (FileTok 7)
charToMoveTok 'h' = Just (FileTok 8)
charToMoveTok '0' = Just (PartCastleTok)
charToMoveTok 'O' = Just (PartCastleTok)
charToMoveTok 'o' = Just (PartCastleTok)
charToMoveTok 'x' = Just (CaptureTok)
charToMoveTok '-' = Just (MoveToTok)
charToMoveTok '=' = Just (QueensWith)
charToMoveTok '+' = Just (CheckTok)
charToMoveTok '#' = Just (MateTok)
charToMoveTok _ = Nothing
data Quantum
= QuantumMove String -- Short Description of move
String -- Check or Mate (+ or #)
String -- !,??,?!, etc
Board -- Snap Shot of Board
| QuantumNAG Int -- !,??,?! stuff
| QuantumComment [String] -- { comment }
| QuantumResult String -- 1-0, etc (marks end of game)
| QuantumAnalysis [Quantum] -- ( analysis )
| QuantumPrintBoard -- {^D}
instance Presentable Quantum where
userFormat (QuantumMove mv ch ann _)
= mv ++ ch ++ ann
userFormat (QuantumNAG nag) = "$" ++ show nag
userFormat (QuantumComment comment)
= "[" ++ unwords comment ++ "]"
--userFormat (QuantumNumber num) = userFormat num
userFormat (QuantumResult str) = str
userFormat (QuantumAnalysis anal) =
"( " ++ unwords (map userFormat anal) ++ " )"
data Result = Win | Draw | Loss | Unknown
instance Presentable Result where
userFormat Win = "1-0"
userFormat Draw = "1/2-1/2"
userFormat Loss = "0-1"
userFormat Unknown = "*"
mkResult :: String -> Result
mkResult "1-0" = Win
mkResult "1/2-1/2" = Draw
mkResult "0-1" = Loss
mkResult _ = Unknown
data TagStr = TagStr String String
instance Presentable TagStr where
userFormat (TagStr tag str) = "[" ++ tag ++ " \"" ++ str ++ "\"]"
getTagStr :: String -> String -> [TagStr] -> String
getTagStr str def [] = def
getTagStr str def (TagStr st ans:rest)
| str == st = ans
| otherwise = getTagStr str def rest
getHeaderInfo
:: [TagStr]
-> (
String, -- Date
String, -- Site
Maybe Int, -- Game Number
Result, -- W/D/L
String, -- White
String, -- Black
String -- Opening
)
getHeaderInfo tags = (
date,
site,
gameno,
result,
white `par` whiteElo,
black `par` blackElo,
opening)
where
date = case getTagStr "Date" "?" tags of
[a,b,c,d,'.','?','?','.','?','?'] -> [a,b,c,d]
[a,b,c,d,'.',x,y,'.','?','?'] -> getMonth [x,y] ++ " " ++ [a,b,c,d]
def -> "?"
site = getTagStr "Site" "?" tags
gameno = case getTagStr "GameNumber" "" tags of
xs | all isDigit xs && not (null xs) -> Just (read xs)
_ -> Nothing
result = mkResult (getTagStr "Result" "*" tags)
white = canon (getTagStr "White" "?" tags)
whiteElo = getTagStr "WhiteElo" "" tags
black = canon (getTagStr "Black" "?" tags)
blackElo = getTagStr "BlackElo" "" tags
opening = getOpening (getTagStr "ECO" "" tags)
par xs "" = xs
par xs ys = xs ++ " (" ++ ys ++ ")"
getMonth "01" = "Jan"
getMonth "02" = "Feb"
getMonth "03" = "Mar"
getMonth "04" = "Apr"
getMonth "05" = "May"
getMonth "06" = "Jun"
getMonth "07" = "Jul"
getMonth "08" = "Aug"
getMonth "09" = "Sep"
getMonth "10" = "Oct"
getMonth "11" = "Nov"
getMonth "12" = "Dec"
canon name = case span (/= ',') name of
(a,[',',' ',b]) -> b : ". " ++ a
(a,[',',b]) -> b : ". " ++ a
(a,',':' ':b) -> b ++ " " ++ a
(a,',':b) -> b ++ " " ++ a
_ -> name
getOpening eco@[a,b,c] | a >= 'A' && a <= 'E' && isDigit b && isDigit c
= getOpenName ((fromEnum a - fromEnum 'A') * 100
+ (fromEnum b - fromEnum '0') * 10
+ (fromEnum c - fromEnum '0')) ++ " " ++ eco
getOpening other = other
getOpenName :: Int -> String
getOpenName eco
| otherwise = "Foo"
{-
| eco == 000 = "Irregular Openings"
| eco == 001 = "Larsen Opening"
| eco == 002 = "From's Gambit and Bird's Open"
| eco == 003 = "Bird's Opening"
| eco == 004 = "Dutch System"
| eco == 005 = "Transposition to various Open"
| eco == 006 = "Zukertort Opening"
| eco >= 007 && eco <= 008
= "Barcza System"
| eco == 009 = "Reti Opening"
| eco == 010 = "Variations of Dutch, QI, KI"
| eco >= 011 && eco <= 014
= "Reti Opening"
| eco == 015 = "English counter King's Fianch"
| eco >= 016 && eco <= 039
= "English Opening"
| eco == 040 = "Unusual replies to 1.d4"
| eco == 041 = "Modern Defence counter 1.d4"
| eco == 042 = "Modern Defence with c2-c4"
| eco >= 043 && eco <= 044
= "Old Benoni"
| eco == 045 = "Queen's Pawn-Trompowski Var"
| eco == 046 = "Queen's Pawn Opening"
| eco == 047 = "Queen's Indian"
| eco >= 048 && eco <= 049
= "King's Indian"
| eco == 050 = "Queen's Indian"
| eco >= 051 && eco <= 052
= "Budapest Defence"
| eco >= 053 && eco <= 056
= "Old Indian Defence"
| eco >= 057 && eco <= 059
= "Volga-Benko Gambit"
| eco >= 060 && eco <= 079
= "Benoni"
| eco >= 080 && eco <= 099
= "Dutch Defence"
| eco == 100 = "Owen Def, Nimzowitsch Def"
| eco == 101 = "Center Counter"
| eco >= 102 && eco <= 105
= "Alekhine's Defence"
| eco == 106 = "Modern Defence"
| eco >= 107 && eco <= 109
= "Pirc Defence"
| eco >= 110 && eco <= 119
= "Caro-Kann Defence"
| eco >= 120 && eco <= 199
= "Sicilian Defence"
| eco >= 200 && eco <= 219
= "French Defence"
| eco == 220 = "Rare moves"
| eco == 221 = "Nordic Gambit"
| eco == 222 = "Central Gambit"
| eco >= 223 && eco <= 224
= "Bishop's Opening"
| eco >= 225 && eco <= 229
= "Vienna Game"
| eco == 230 = "King's Gambit Declined"
| eco >= 231 && eco <= 232
= "Falkbeer Counter Gambit"
| eco >= 233 && eco <= 239
= "King's Gambit"
| eco == 240 = "Latvian Gambit"
| eco == 241 = "Philidor Defence"
| eco >= 242 && eco <= 243
= "Russian Defence-Petrov"
| eco >= 244 && eco <= 245
= "Scotch Opening"
| eco >= 246 && eco <= 249
= "Four Knight's"
| eco == 250 = "Italian Opening"
| eco >= 251 && eco <= 252
= "Evans Gambit"
| eco >= 253 && eco <= 254
= "Italian Opening"
| eco >= 255 && eco <= 259
= "Two Knight's Play"
| eco >= 260 && eco <= 299
= "Ruy Lopez"
| eco >= 300 && eco <= 305
= "Queen Pawn's Opening"
| eco >= 306 && eco <= 307
= "Queen's Gambit"
| eco >= 308 && eco <= 309
= "Albins Counter Gambit"
| eco >= 310 && eco <= 319
= "Slav Defence"
| eco >= 320 && eco <= 329
= "Queen's Gambit Accepted"
| eco >= 330 && eco <= 369
= "Queen's Gambit"
| eco >= 370 && eco <= 399
= "Gruenfeld Defence"
| eco >= 400 && eco <= 409
= "Catalan"
| eco == 410 = "Blumenfeld Gambit"
| eco >= 411 && eco <= 419
= "Queen's Indian"
| eco >= 420 && eco <= 459
= "Nimzo Indian"
| eco >= 460 && eco <= 499
= "King's Indian"
-}
data MoveNumber = MoveNumber Int Colour
instance Presentable MoveNumber where
userFormat (MoveNumber n White) = show n ++ "."
userFormat (MoveNumber n Black) = show n ++ "..."
initMoveNumber = MoveNumber 1 White
incMove (MoveNumber i White) = MoveNumber i Black
incMove (MoveNumber i Black) = MoveNumber (i+1) White
decMove (MoveNumber i White) = MoveNumber (i-1) Black
decMove (MoveNumber i Black) = MoveNumber i White
getMoveColour :: MoveNumber -> Colour
getMoveColour (MoveNumber _ c) = c
data Token
= StringToken String
| AsterixToken
| LeftABToken -- ??
| RightABToken -- ??
| NAGToken Int -- `normal' NAGS
| NAGAnnToken Int String
-- `special' move annotating NAGS (1-6)
| SymbolToken String
| CommentToken [String] -- list of words
| LeftSBToken
| RightSBToken
| LeftRBToken
| RightRBToken
| IntToken Int
| PeriodToken
| AnalToken [Token]
instance Presentable Token where
userFormat (StringToken str) = show str
userFormat (IntToken n) = show n
userFormat (PeriodToken) = "."
userFormat (AsterixToken) = "*"
userFormat (LeftSBToken) = "["
userFormat (RightSBToken) = "]"
userFormat (LeftRBToken) = "("
userFormat (RightRBToken) = ")"
userFormat (LeftABToken) = "<"
userFormat (RightABToken) = ">"
userFormat (NAGToken i) = "$" ++ show i
userFormat (NAGAnnToken i s) = "$" ++ show i
userFormat (SymbolToken str) = str
userFormat (CommentToken str) = "{" ++ unwords str ++ "}"
userFormat (AnalToken toks) = "( " ++ unwords (map userFormat toks)
++ " )"
data Game a = Game [TagStr] [a]
type AbsGame = Game Token
type RealGame = Game Quantum
instance (Presentable a) => Presentable (Game a) where
userFormat (Game tags toks) =
unlines (map userFormat tags
++ formatText 78 (map userFormat toks))
data PlayMove
= PlayMove
Piece -- with this
BoardPos -- from here
BoardPos -- to here (possibly capturing)
SpecialMove
mkPlayMove p f t = PlayMove p f t NothingSpecial
data SpecialMove
= NothingSpecial
| BigPawnMove -- allows e.p. next move
| Queening Piece -- queen with this
| EnPassant -- capture e.p.
deriving (Eq)
instance Presentable PlayMove where
userFormat (PlayMove piece pos pos' sp) =
userFormat piece ++
userFormatBoardPos pos ++ "-" ++
userFormatBoardPos pos' ++
userFormat sp
instance Presentable SpecialMove where
userFormat (NothingSpecial) = ""
userFormat (BigPawnMove) = "{b.p.m.}"
userFormat (Queening p) = "=" ++ userFormat p
userFormat (EnPassant) = "e.p."
extractSrcFromPlayMove :: PlayMove -> BoardPos
extractSrcFromPlayMove (PlayMove _ src _ _) = src
extractDestFromPlayMove :: PlayMove -> BoardPos
extractDestFromPlayMove (PlayMove _ _ dest _) = dest
extractSpecialFromPlayMove :: PlayMove -> SpecialMove
extractSpecialFromPlayMove (PlayMove _ _ _ sp) = sp
data BoardSquare
= VacantSq
| WhitesSq Piece
| BlacksSq Piece
data SquareContent
= Vacant
| Friendly
| Baddy
| OffBoard deriving (Eq)
instance Presentable SquareContent where
userFormat Vacant = "."
userFormat Friendly = "*"
userFormat Baddy = "#"
userFormat OffBoard = "?"
data Board
= Board (Array BoardPos BoardSquare)
MoveNumber -- current player & and move
(Maybe ChessFile) -- e.p. possibilities.
displayBoard :: Colour -> Board -> [String]
displayBoard col (Board arr _ ep) =
([cjustify 33 (userFormat (changeColour col)),""] ++
[
concat [ (case (even x,even y) of
(True,True) -> showSq (x `div` 2) (y `div` 2)
(False,False) -> "+"
(True,False) -> "---"
(False,True) -> (if x == 17 then "| " ++ show (y `div` 2) else "|"))
| x <- [1..17::Int]]
| y <- reverse [1..17::Int]] ++
[concat [ " " ++ [x] ++ " " | x <- "abcdefgh" ]] ++
["",cjustify 33 (userFormat col),"",
case ep of
Nothing -> ""
Just p -> "EnPassant:" ++ userFormatFile p ])
where
make n str = take n (str ++ repeat ' ')
lookupPlace :: Int -> Int -> BoardSquare
lookupPlace x' y' = arr ! (x',y')
bold :: String -> String
bold str = map toLower str
showSq x y = case lookupPlace x y of
VacantSq -> [if_dot,if_dot,if_dot]
(WhitesSq p) -> (if_dot : userFormat p) ++ [if_dot]
(BlacksSq p) -> (if_dot : bold (userFormat p)) ++ [if_dot]
where
if_dot = if (x - y) `rem` 2 == 0 then '.' else ' '
instance Presentable Board where
userFormat = unlines . displayBoard White
boardSize :: (BoardPos,BoardPos)
boardSize = ((1,1),(8,8))
buildBoard :: String -> Board
buildBoard str = Board brd initMoveNumber Nothing
where
brd = array boardSize (zipWith (=:) allSq (mkPieces str))
allSq = [ (x,y) | y <- reverse [1..8::Int],x <- [1..8::Int]]
mkPieces :: String -> [BoardSquare]
mkPieces (hd:rest) | hd `elem` "KQRNBPkqrnbp" = pc : mkPieces rest
where
pc = case hd of
'K' -> WhitesSq King
'Q' -> WhitesSq Queen
'R' -> WhitesSq Rook
'N' -> WhitesSq Knight
'B' -> WhitesSq Bishop
'P' -> WhitesSq Pawn
'k' -> BlacksSq King
'q' -> BlacksSq Queen
'r' -> BlacksSq Rook
'n' -> BlacksSq Knight
'b' -> BlacksSq Bishop
'p' -> BlacksSq Pawn
mkPieces ('/':rest) = mkPieces rest
mkPieces (c:rest) | isDigit c =
case span isDigit rest of
(cs,rest') -> take (read (c:cs)) (repeat VacantSq)
++ mkPieces rest'
mkPieces [] = []
startBoard :: Board -- the uni before the big bang.
startBoard = buildBoard "rnbqkbnr/pppppppp/32/PPPPPPPP/RNBQKBNR"
lookupSquare :: Colour -> BoardSquare -> SquareContent
lookupSquare _ VacantSq = Vacant
lookupSquare White (WhitesSq p) = Friendly
lookupSquare Black (WhitesSq p) = Baddy
lookupSquare White (BlacksSq p) = Baddy
lookupSquare Black (BlacksSq p) = Friendly
lookupBoard :: Board -> BoardPos -> SquareContent
lookupBoard (Board arr col _) pos =
if inRange boardSize pos
then lookupSquare (getMoveColour col) (arr ! pos)
else OffBoard
lookupBoardSquare :: Board -> BoardPos -> BoardSquare
lookupBoardSquare (Board arr _ _) pos = arr ! pos
getSquarePiece :: BoardSquare -> Maybe Piece
getSquarePiece VacantSq = Nothing
getSquarePiece (WhitesSq p) = Just p
getSquarePiece (BlacksSq p) = Just p
lookupBoardPiece :: Board -> BoardPos -> Maybe Piece
lookupBoardPiece (Board arr _ _) pos =
case arr ! pos of
VacantSq -> Nothing
WhitesSq piece -> Just piece
BlacksSq piece -> Just piece
{-# INLINE mkColBoardSq #-}
mkColBoardSq :: Colour -> Piece -> BoardSquare
mkColBoardSq White p = WhitesSq p
mkColBoardSq Black p = BlacksSq p
getBoardColour (Board _ mv _) = getMoveColour mv
| olsner/ghc | testsuite/tests/programs/andy_cherry/DataTypes.hs | bsd-3-clause | 19,294 | 0 | 21 | 7,095 | 4,685 | 2,458 | 2,227 | 375 | 20 |
-- Made GHC 6.10.2 go into a loop in substRecBndrs
{-# OPTIONS_GHC -w #-}
module T10627 where
import Data.Word
class C a where
splitFraction :: a -> (b,a)
roundSimple :: (C a) => a -> b
roundSimple x = error "rik"
{-# RULES
"rs" roundSimple = (fromIntegral :: Int -> Word) . roundSimple;
#-}
| urbanslug/ghc | testsuite/tests/simplCore/should_compile/T10627.hs | bsd-3-clause | 313 | 0 | 8 | 75 | 65 | 37 | 28 | 9 | 1 |
module Mod132_A where
data Foo = Foo
| urbanslug/ghc | testsuite/tests/module/Mod132_A.hs | bsd-3-clause | 38 | 0 | 5 | 8 | 11 | 7 | 4 | 2 | 0 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Scrabble where
-- Exercise 3
import Data.Char
newtype Score = Score Int
deriving (Eq, Show, Num)
instance Monoid Score where
mempty = Score 0
mappend = (+)
score :: Char -> Score
score c
| c_lower `elem` "aeilnorstu" = Score 1
| c_lower `elem` "dg" = Score 2
| c_lower `elem` "bcmp" = Score 3
| c_lower `elem` "fhvwy" = Score 4
| c_lower `elem` "k" = Score 5
| c_lower `elem` "jx" = Score 8
| c_lower `elem` "qz" = Score 10
| otherwise = Score 0
where c_lower = toLower c
scoreString :: String -> Score
scoreString = foldl (\n c -> n + score c) (Score 0)
| harry830622/cis194-solutions | 07-folds-monoids/Scrabble.hs | mit | 724 | 0 | 9 | 211 | 262 | 137 | 125 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Yesod.Auth.OAuth2.ClassLink
( oauth2ClassLink
, oauth2ClassLinkScoped
)
where
import Yesod.Auth.OAuth2.Prelude
import qualified Data.Text as T
newtype User = User Int
instance FromJSON User where
parseJSON = withObject "User" $ \o -> User <$> o .: "UserId"
pluginName :: Text
pluginName = "classlink"
defaultScopes :: [Text]
defaultScopes = ["profile", "oneroster"]
oauth2ClassLink :: YesodAuth m => Text -> Text -> AuthPlugin m
oauth2ClassLink = oauth2ClassLinkScoped defaultScopes
oauth2ClassLinkScoped :: YesodAuth m => [Text] -> Text -> Text -> AuthPlugin m
oauth2ClassLinkScoped scopes clientId clientSecret =
authOAuth2 pluginName oauth2 $ \manager token -> do
(User userId, userResponse) <- authGetProfile
pluginName
manager
token
"https://nodeapi.classlink.com/v2/my/info"
pure Creds
{ credsPlugin = pluginName
, credsIdent = T.pack $ show userId
, credsExtra = setExtra token userResponse
}
where
oauth2 = OAuth2
{ oauthClientId = clientId
, oauthClientSecret = Just clientSecret
, oauthOAuthorizeEndpoint =
"https://launchpad.classlink.com/oauth2/v2/auth"
`withQuery` [scopeParam "," scopes]
, oauthAccessTokenEndpoint =
"https://launchpad.classlink.com/oauth2/v2/token"
, oauthCallback = Nothing
}
| thoughtbot/yesod-auth-oauth2 | src/Yesod/Auth/OAuth2/ClassLink.hs | mit | 1,487 | 0 | 13 | 389 | 312 | 174 | 138 | 36 | 1 |
module Bonawitz_3_18b
where
import Blaze
import Tree
sr :: State
sr = collectStates dummyState $ csx : sps
-- Real data from N(3,12)
csx :: State
csx = collectStates dummyCState $
zipWith (flip tagNode) (show `fmap` [1..]) $
map (mkDoubleData . read) $
words "25.8 11.3 -12.7 -3.2 -29.6 2.1 21.8 -5.2 14.2 -2.7 -0.7 -7.1 18.1"
sps :: [State]
sps = mkDoubleParams ["mu","sigma"] [1.0,1.0]
dr :: Density
dr = productDensity [dmu,dsigma,dnorm]
where dmu = mkDensity [] [["mu"]] [] vague
dsigma = mkDensity [] [["sigma"]] [] vaguePositive
dnorm = mkACDensity cd [""] [["mu"],["sigma"]]
cd = mkDensity [] [[]] [["dso","mu"],["dso","sigma"]] normal
buildMachine :: Entropy -> Machine
buildMachine e = Machine sr dr kr e
where kmu = mkGPKernel 1.0 ["mu"]
ksigma = mkGPKernel 0.5 ["sigma"]
kr = mkMHKernel $ mkCCKernel [kmu,ksigma]
main :: IO ()
main = run buildMachine 5000 [ trace paramLocs, burnin 500 $ dump paramLocs ]
where paramLocs = [ ([],"mu")
, ([],"sigma") ] | othercriteria/blaze | Bonawitz_3_18b.hs | mit | 1,090 | 0 | 11 | 283 | 403 | 224 | 179 | 27 | 1 |
-- The following iterative sequence is defined for the set of positive
-- integers:
-- n → n/2 (n is even)
-- n → 3n + 1 (n is odd)
-- Using the rule above and starting with 13, we generate the
-- following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
-- It can be seen that this sequence (starting at 13 and finishing at
-- 1) contains 10 terms. Although it has not been proved yet (Collatz
-- Problem), it is thought that all starting numbers finish at 1.
-- Which starting number, under one million, produces the longest
-- chain?
-- NOTE: Once the chain starts the terms are allowed to go above one
-- million.
module Euler.Problem014
( solution
, collatzSequenceLength
) where
import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.Function.Memoize
-- https://wiki.haskell.org/Euler_problems/11_to_20#Problem_14
solution :: Int -> Int
solution = maximumBy (comparing collatzSequenceLength) . enumFromTo 1
--solution ceil = snd . maximum . map (\n -> (chainLength n, n)) $ [1..(ceil - 1)]
collatzSequenceLength :: Int -> Int
collatzSequenceLength = memoize collatzSequenceLength'
collatzSequenceLength' :: Int -> Int
collatzSequenceLength' 1 = 1
collatzSequenceLength' n = succ $ collatzSequenceLength $ step n
-- collatzSequenceLength' :: Int -> Int
-- collatzSequenceLength' = helper 1
-- where helper k 1 = k
-- helper k n = helper (succ k) $ step n
-- collatzSequenceLength' :: Int -> Int
-- collatzSequenceLength' = length . collatzSequenceFrom
-- collatzSequenceFrom :: Int -> [Int]
-- collatzSequenceFrom = memoize collatzSequenceFrom'
-- collatzSequenceFrom' :: Int -> [Int]
-- collatzSequenceFrom' 1 = [1]
-- collatzSequenceFrom' n = n : collatzSequenceFrom (step n)
-- chainLength :: Integer -> Integer
-- chainLength = memoize chainLength'
-- chainLength' :: Integer -> Integer
-- chainLength' 1 = 1
-- chainLength' n = (1 +) . chainLength . step $ n
step :: Int -> Int
step n | even n = n `quot` 2
| otherwise = 3 * n + 1
| whittle/euler | src/Euler/Problem014.hs | mit | 2,041 | 0 | 8 | 393 | 203 | 122 | 81 | 16 | 1 |
{-# LANGUAGE JavaScriptFFI #-}
-- | A wrapper over the Electron global shortcut API, as documented
-- <https://electron.atom.io/docs/api/global-shortcut here>.
module GHCJS.Electron.GlobalShortcut
( module Exported
, unsafeGetGlobalShortcut
, unsafeRegister
, unsafeUnregister
, unsafeUnregisterAll
, unsafeIsRegistered
) where
import GHCJS.Electron.Types
import GHCJS.Electron.Types as Exported (GlobalShortcut (..))
-- | Get the canonical 'GlobalShortcut' object, i.e.: the value of
-- @require('electron').globalShortcut@.
foreign import javascript safe
"$r = require('electron').globalShortcut;"
unsafeGetGlobalShortcut :: IO GlobalShortcut
-- | Register a callback for the given 'Accelerator'.
foreign import javascript safe
"$1.register($2, $3);"
unsafeRegister :: GlobalShortcut
-> Accelerator
-> Callback ()
-> IO ()
-- | Deregister any callbacks registered to the given 'Accelerator'.
foreign import javascript safe
"$1.unregister($2);"
unsafeUnregister :: GlobalShortcut
-> Accelerator
-> IO ()
-- | Deregister all global shortcut callbacks.
foreign import javascript safe
"$1.unregisterAll();"
unsafeUnregisterAll :: GlobalShortcut
-> IO ()
-- | Check if the given 'Accelerator' is has been registered.
foreign import javascript safe
"$1.isRegistered($2);"
unsafeIsRegistered :: GlobalShortcut
-> Accelerator
-> IO Bool
| taktoa/ghcjs-electron | src/GHCJS/Electron/GlobalShortcut.hs | mit | 1,550 | 15 | 7 | 378 | 190 | 110 | 80 | 28 | 0 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
-- Run as: pv cur/sentences.lang.tsv | ./tat-count-words
-- Run as: pv cur/sentences.tsv | ./tat-count-words
import Control.Exception (bracket)
import Control.Monad (liftM2)
import Data.Char (isAlpha)
import Data.Hashable (Hashable, hashWithSalt)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.List (foldl', sortBy)
import Data.Maybe (fromMaybe)
import Data.Ord (comparing)
--import qualified Data.Text as T
import qualified Data.Text.Lazy as T
--import qualified Data.Text.IO as T
import qualified Data.Text.Lazy.IO as T
import System.Directory (getHomeDirectory)
import System.FilePath ((</>))
import System.IO (hClose, hGetLine, hIsEOF, openFile, readFile, stdin, Handle, IOMode(ReadMode))
type I = Int
type L = T -- Lang abbrs are just used directly.
type T = T.Text
data P2 a = P2 {i1 :: !a, i2 :: !a} deriving (Eq, Ord, Show)
instance Hashable a => Hashable (P2 a) where
hashWithSalt s (P2 a b) = hashWithSalt s (a, b)
--type Count = HashMap (P2 L) [P2 I]
type Count = HashMap (P2 L) I
--type Count = I
{-# INLINE test #-}
--test = take 1000
test = id
sentToWords :: T -> [T]
sentToWords = filter (not . T.null) .
map (T.toLower . T.filter isAlpha) . T.words
main :: IO ()
main = do
wordCounts <- HM.fromListWith (+) . map (\w -> (w, 1)) .
concatMap ((\(_id:_lang:sent:_) -> sentToWords sent) . T.split (== '\t')) .
test . T.lines <$> T.getContents
mapM_ (\(w, c) ->
T.putStrLn $ T.pack (show c) <> "\t" <> w
) . sortBy (comparing snd) $ HM.toList wordCounts
| dancor/melang | src/Main/tat-count-words.hs | mit | 1,709 | 0 | 20 | 309 | 573 | 332 | 241 | 42 | 1 |
{-
Module : CSH.Eval.Frontend.Members
Description : The route handler for the members page
Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015
License : MIT
Maintainer : pvals@csh.rit.edu
Stability : Provisional
Portability : POSIX
DOCUMENT THIS!
-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ViewPatterns #-}
module CSH.Eval.Frontend.Members (
getMembersR
, getMemberR
) where
import qualified Data.ByteString.Char8 as B
import CSH.Eval.Frontend.Data
import qualified CSH.Eval.LDAP as LD
import Yesod
dummyMembers :: [(String, String, Int, Bool, Bool)]
dummyMembers = take 100 . cycle $
[("harlan", "Harlan Haskins", 4, True, True)
,("dag10", "Drew Gottlieb", 4, True, False)
,("tmobile", "Travis Whitaker", 8, True, False)
]
charFor :: Bool -> String
charFor True = "✅"
charFor False = "❌"
-- | The handler for a single member's page
getMemberR :: String -> Handler Html
getMemberR user = do
let usr = B.pack user
nameEither <- liftIO $ LD.lookup "cn" usr
let name = B.unpack $ case nameEither of
(Just n) -> n
Nothing -> usr
let attendance = [("Evals", "Committee", "10/13/2015"), ("Financial", "Committee", "10/13/2015")]
let access = Member
defaultLayout $(whamletFile "frontend/templates/index.hamlet")
-- | The handler for the members listing page
getMembersR :: Handler Html
getMembersR = do
defaultLayout $(whamletFile "frontend/templates/members/index.hamlet")
| gambogi/csh-eval | src/CSH/Eval/Frontend/Members.hs | mit | 1,773 | 0 | 15 | 446 | 341 | 196 | 145 | 34 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module ProcNum where
str2dbl :: Maybe String -> Maybe Double
str2dbl Nothing = Nothing
str2dbl (Just v) = Just d
where
d = case (last v) of
'%' -> (read $ init v :: Double) / 100.0
_ -> read v :: Double
prtperc :: Double -> String
prtperc d = prtdbl 2 (d*100.0) ++ "%"
prtdbl2 :: Double -> String
prtdbl2 d = prtdbl 2 d
prtdbl3 :: Double -> String
prtdbl3 d = prtdbl 3 d
prtdbl4 :: Double -> String
prtdbl4 d = prtdbl 4 d
prtdbl :: Int -> Double -> String
prtdbl n d =
pre ++ "." ++ (take n post)
where
p = 10**(fromIntegral n)
d' = (fromIntegral $ round(d * p)) / p
(pre,post) = splitdot $ show d'
splitdot :: String -> (String, String)
splitdot s = splitdota' s ([],[])
splitdota' [] (as',bs') = (reverse as', reverse bs')
splitdota' ('.':r) (as',bs') = splitdotb' r (as', [])
splitdota' (a:r) (as',bs') = splitdota' r (a:as',bs')
splitdotb' [] (as,bs) = (reverse as, reverse bs)
splitdotb' (b:r) (as,bs) = splitdotb' r (as,b:bs)
| CodiePP/Hedge-o-Mat | hs/src/calculators/lib/ProcNum.hs | mit | 1,041 | 0 | 13 | 255 | 507 | 268 | 239 | 29 | 2 |
module Passes (matrix) where
import Ast
---------------------------------
-- Pass 1 : Recognise matrices --
---------------------------------
-- main function
matrix :: Code -> Code
matrix = map matrixExpr
matrixExpr :: Expr -> Expr
matrixExpr (Expr e pos) = Expr (matrixExpr_ e) pos
matrixExpr_ :: Expr_ -> Expr_
matrixExpr_ (Simple e) = Simple $ matrixSE e
matrixExpr_ (Frac e1 e2) = Frac (matrixSE e1) (matrixSE e2)
matrixExpr_ (Under e1 e2) = Under (matrixSE e1) (matrixSE e2)
matrixExpr_ (Super e1 e2) = Super (matrixSE e1) (matrixSE e2)
matrixExpr_ (SubSuper e1 e2 e3) = SubSuper (matrixSE e1) (matrixSE e2) (matrixSE e3)
matrixSE :: SimpleExpr -> SimpleExpr
matrixSE (SimpleExpr e pos) = SimpleExpr (matrixSE_ e) pos
matrixSE_ :: SimpleExpr_ -> SimpleExpr_
matrixSE_ (Delimited (LBracket LCro lpos) c (RBracket RCro rpos)) =
case parseSeq c of
Nothing -> Delimited (LBracket LCro lpos)
(matrix c)
(RBracket RCro rpos)
Just m -> Matrix RawMatrix m
matrixSE_ (Delimited (LBracket LPar lpos) c (RBracket RPar rpos)) =
case parseSeq c of
Nothing -> Delimited (LBracket LPar lpos)
(matrix c)
(RBracket RPar rpos)
Just m -> Matrix ColMatrix m
matrixSE_ (UnaryApp o e) = UnaryApp o (matrixSE e)
matrixSE_ (BinaryApp o e1 e2) = BinaryApp o (matrixSE e1) (matrixSE e2)
matrixSE_ x = x
-- Usefull predicates
com :: SimpleExpr -> Bool
com (SimpleExpr (SEConst (Constant Comma _)) _) = True
com _ = False
comma :: Expr -> Bool
comma (Expr (Simple e) _) | com e = True
comma _ = False
-- like unwords but cuts at the symbols matching p
split :: (a -> Bool) -> [a] -> [[a]]
split p l = case break p l of
(_, []) -> [l]
(l1, l2) -> l1 : split p (drop 1 l2)
-- First step of parseSeq : match a sequence of comma-separated bracketed
-- expression
unbracket :: [Code] -> Maybe [(LBracket_, Code)]
unbracket [] = Just []
unbracket ([Expr (Simple (SimpleExpr (Delimited lb c rb) _)) _]:cs) =
case (lb, rb, unbracket cs) of
(LBracket LCro _, RBracket RCro _, Just l) -> Just ((LCro, c):l)
(LBracket LPar _, RBracket RPar _, Just l) -> Just ((LPar, c):l)
_ -> Nothing
unbracket _ = Nothing
parseSeq1 :: Code -> Maybe [(LBracket_, Code)]
parseSeq1 = unbracket . split comma
-- Second step of parseSeq : check if all the delimiters used are similars
parseSeq2 :: Maybe [(LBracket_, Code)] -> Maybe [[Code]]
parseSeq2 Nothing = Nothing
parseSeq2 (Just cs) =
let (lb, _) = head cs in
if all (\(lb', _) -> lb' == lb) cs then
let res = map (split comma . snd) cs in
let n = length . head $ res in
if all (\l -> n == length l) res then
Just res
else
Nothing
else
Nothing
-- ParseSeq
parseSeq :: Code -> Maybe [[Code]]
parseSeq = parseSeq2 . parseSeq1
| Kerl13/AsciiMath | src/lib/Passes.hs | mit | 2,873 | 0 | 17 | 711 | 1,177 | 604 | 573 | 63 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
module Arbre.Event
(
applyEvent
)
where
import Arbre.Expressions
import Arbre.View
import Arbre.Native
applyEvent :: EventType -> Value -> IO()
applyEvent Print value = do
let maybeString = unboxString value
case maybeString of
Just s -> putStrLn s
-- Nothing -> putStrLn $ printValue value
| blanu/arbre-go | Arbre/Event.hs | gpl-2.0 | 344 | 0 | 10 | 65 | 87 | 45 | 42 | 12 | 1 |
-- <<all
import Sudoku
import Control.Exception
import System.Environment
import Data.Maybe
import Control.Parallel.Strategies
import Control.DeepSeq
main :: IO ()
main = do
[f] <- getArgs -- <1>
file <- readFile f -- <2>
let puzzles = lines file
(as, bs) = splitAt (length puzzles `div` 2) puzzles
solutions = runEval $ do
as' <- rpar (force $ map solve as)
bs' <- rpar (force $ map solve bs)
rseq as'
rseq bs'
return (as' ++ bs')
print (length (filter isJust solutions)) -- <5>
-- >>
| y-kamiya/parallel-concurrent-haskell | src/Sudoku-sample/sudoku2.hs | gpl-2.0 | 597 | 0 | 17 | 195 | 209 | 105 | 104 | 19 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.GUI.GUIState
(
GUIState (..),
GUITick,
GUIShape (..),
GUIPos (..),
) where
import MyPrelude
import Game.GUI.GUIShade
import OpenGL
import OpenGL.Helpers
-- (fixme: verify this)
-- INVARIANTS WHEN DRAWING A NEW WIDGET
--
-- * GUIState resembles GL-state, except FillTex
-- * all textures used shall be upside down (consistent with 2D drawing (FillTex))
-- * Program == ShadeGUI
-- * DepthTest enabled
-- * DepthFunc == GL_LEQUAL
-- * StencilTest disabled
-- * FrontFace == GL_CCW ? (vs 3D)
-- * CullFace disabled ? (vs 3D)
-- * y-direction is top to bottom
data GUIState =
GUIState
{
-- time
guistateTick :: !GUITick,
-- GL
guistateGUIShade :: GUIShade,
guistateAlpha :: !Float,
guistateProjModv :: !Mat4,
guistateWth :: !Float,
guistateHth :: !Float,
-- (fixme: more general, ProjModv :: Mat4)
guistatePos :: !GUIPos,
guistateScaleX :: !Float,
guistateScaleY :: !Float,
guistateDepth :: !Float,
guistateFocus :: !Float,
guistateFillTex :: !GLuint
}
-- | GUIShape's are relative to vertex xy-space
data GUIShape =
GUIShape
{
shapeWth :: !Float,
shapeHth :: !Float
}
-- | GUIPos's are relative to vertex xy-space
data GUIPos =
GUIPos
{
posX :: !Float,
posY :: !Float
}
type GUITick =
Double
| karamellpelle/grid | source/Game/GUI/GUIState.hs | gpl-3.0 | 2,191 | 0 | 9 | 567 | 230 | 153 | 77 | 64 | 0 |
module Lib
( someFunc
, module A
, module B
) where
import A (A (A))
import B
someFunc :: IO ()
someFunc = putStrLn "someFunc"
| capitanbatata/sandbox | haddock-re-exports/src/Lib.hs | gpl-3.0 | 165 | 0 | 6 | 64 | 50 | 31 | 19 | 8 | 1 |
import Language.Distfix
add = distfix OpenLeft [(== "+")]
cat = distfix OpenRight [(=="++")]
inc = distfix HalfOpenRight [(=="++")]
lt = distfix OpenNon [(=="<")]
ltlt = distfix OpenNon [(=="<"), (=="<")]
fac = distfix HalfOpenLeft [(=="!")]
ite = distfix HalfOpenRight [(=="if"), (=="then"), (=="else")]
mag = distfix Closed [(=="|"), (=="|")]
tup = distfix Closed [(=="<"), (==">")]
braket = distfix Closed [(=="<"), (=="|"), (==">")]
main = do
test [add] ["a", "+", "b", "+", "c"]
test [add] ["+", "c"]
test [cat] ["a", "++", "b", "++", "c"]
test [lt] ["a", "<", "b", "c"]
test [lt] ["a", "<", "b", "<", "c"]
test [fac] ["a", "!", "!", ".foo"]
test [ite] ["if", "p1", "then", "c1", "else", "if", "p2", "then", "c2", "else", "alt"]
test [mag] ["|", "a", "|", "|", "b", "|" ]
test [lt, ltlt] ["a", "<", "b", "<", "c"]
test [mag, tup, braket] ["<", "|", "a", "|", "|", "b", ">"]
test [cat, inc] ["++", "a", "++", "c"]
test :: [Distfix String] -> [String] -> IO ()
test dfs text = print $ findDistfixes dfs text | Zankoku-Okuno/ammonite | TestDistfixes.hs | gpl-3.0 | 1,057 | 0 | 8 | 212 | 583 | 343 | 240 | 25 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Users.Controller where
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import Network.HTTP.Types (StdMethod (..))
import Network.Wai (Response)
import Web.Fn
import Web.Larceny hiding (renderWith)
import Ctxt
import Sets.Controller
import Users.Model
import Users.View
usersRoutes :: Ctxt -> IO (Maybe Response)
usersRoutes ctxt =
route ctxt [ (end ==> usersHandler)
, (method POST // path "create"
// param "username"
// param "email"
// param "password"
// param "password-confirmation" !=> usersCreateHandler)
, (segment ==> requireAuthentication loggedInUserRoutes)]
usersHandler :: Ctxt -> IO (Maybe Response)
usersHandler ctxt = do
users <- getUsers ctxt
renderWith ctxt ["users", "index"] (usersSplices users)
requireAuthentication :: (Ctxt -> User -> k -> IO (Maybe Response))
-> Ctxt -> k -> IO (Maybe Response)
-- This is a weird type signature! Here's what is going on.
-- `k` is the type of any params or segment arguments.
-- For example, `(segment ==> requireAuthentication userHandler)`
-- passes one `Text` argument, so `k` is `Text`. But if it was
-- `(segment // path "id" ==> requireAuthentication otherHandler)`
-- then `k` might be `Text -> Int`. Keeping `k` abstract lets us
-- handle all sorts of different types of arguments to our handlers.
requireAuthentication handler = \ctxt k -> do
mUser <- getLoggedInUser ctxt
case mUser of
Just user -> handler ctxt user k
Nothing -> errText "you're not logged in"
loggedInUserRoutes :: Ctxt -> User -> Text -> IO (Maybe Response)
loggedInUserRoutes ctxt loggedInUser username = do
if userUsername loggedInUser == username
then route ctxt [ end ==> userHandler loggedInUser
, path "upload" // method POST
// file "kissfile"
!=> userUploadHandler loggedInUser
, path "sets" // segment
// end
==> userSetHandler loggedInUser ]
else return Nothing
userHandler :: User -> Ctxt -> IO (Maybe Response)
userHandler loggedInUser ctxt = do
renderWith ctxt ["users", "show"] (userSplices loggedInUser)
usersCreateHandler :: Ctxt -> Text -> Text -> Text -> Text -> IO (Maybe Response)
usersCreateHandler ctxt username email password passwordConfirmation = do
eNewUser <-
validateNewUser ctxt username email password passwordConfirmation
case eNewUser of
Left errors ->
renderWith ctxt ["index"] (errorSplices errors)
Right newUser -> do
success <- createUser ctxt newUser
if success
then okHtml "created!"
else errHtml "couldn't create user"
where errorSplices errors =
newErrorSplices errors <> createUserErrorSplices
newErrorSplices errors =
(subs $ map (\(k,v) -> (k <> "Errors", textFill v)) errors)
type Errors = [(Text, Text)]
validateNewUser :: Ctxt -> Text -> Text -> Text -> Text -> IO (Either Errors NewUser)
validateNewUser ctxt username email password passwordConfirmation = do
let pwMissing =
errBool "password" "Please enter a password."
(password == "")
let emailMissing =
errBool "email" "Please enter your email."
(email == "")
let usernameMissing =
errBool "username" "Please enter a username."
(username == "")
let passwordsDontMatch =
errBool "password" "Your passwords don't match."
(password /= passwordConfirmation)
usernameTaken <-
errMaybe "username" "That username is already in use."
(getUserByUsername ctxt username)
emailTaken <-
errMaybe "email" "That email is already in use."
(getUserByEmail ctxt email)
let emailInvalid =
errBool "email" "Please enter a valid email."
(not $ "@" `T.isInfixOf` email)
let errors = catMaybes [passwordsDontMatch, usernameTaken,
emailTaken, emailInvalid, pwMissing,
emailMissing, usernameMissing]
if null errors
then return $ Right $ NewUser username email password
else return $ Left errors
where errBool field msg cond =
if cond then Just (field, msg) else Nothing
errMaybe field msg maybeAction =
(fmap . fmap)
(const (field, msg))
maybeAction
createUserErrorSplices :: Substitutions Ctxt
createUserErrorSplices =
subs [ ("usernameErrors", textFill "")
, ("emailErrors", textFill "")
, ("passwordErrors", textFill "")]
| huggablemonad/smooch | app/src/Users/Controller.hs | gpl-3.0 | 4,952 | 0 | 14 | 1,483 | 1,180 | 605 | 575 | -1 | -1 |
module BrowserX.Network (fetchURL,checkProtocol,downloadfile) where
import Network.Browser
import Network.HTTP
import Network.URI
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as S
import Data.Conduit
import Data.Conduit.Binary as CB
import Network.HTTP.Conduit
import Data.List.Split
import BrowserX.Db
import BrowserX.Options
import BrowserX.Plugin
import Database.HDBC.Sqlite3
import Database.HDBC
fetchURL :: Options -> String -> IO String
fetchURL settings url = do
con <- connectSqlite3 "test.db"
g <- run con "CREATE TABLE IF NOT EXISTS cookies (name VARCHAR(1000), domain VARCHAR(1000), value VARCHAR(1000), path VARCHAR(1000), comment VARCHAR(1000), version VARCHAR(1000))" []
r <- quickQuery con "SELECT * from cookies" []
disconnect con
let prev_cookies = get_cookie_format r
(cookies,rsp) <- browse $ do
setAllowRedirects True
setProxy (optProxy settings)
setCookies prev_cookies
(_,rsp) <- request $ getRequest url
cookies <- getCookies
addCookies cookies
return (cookies,rsp)
put_cookieDB cookies
return $ rspBody rsp
--plugin "scss" (rspBody rsp)
checkProtocol :: String -> String
checkProtocol url =
case (parseURI url) of
Nothing -> "http://" ++ url
Just uri ->
if (scheme == "http:") then url
else
error (scheme ++ "Protocol not supported")
where scheme = uriScheme uri
downloadfile url path = withManager $ \manager -> do
req <- parseUrl url
res <- http req manager
responseBody res $$+- printProgress =$ CB.sinkFile path
printProgress :: Conduit S.ByteString (ResourceT IO) S.ByteString
printProgress =
loop 0
where
loop len = await >>= maybe (return ()) (\bs -> do
let len' = len + S.length bs
liftIO $ putStrLn $ "Bytes consumed: " ++ show len'
yield bs
loop len') | rabisg/BrowserX | BrowserX/Network.hs | gpl-3.0 | 1,968 | 0 | 18 | 491 | 546 | 273 | 273 | 52 | 3 |
{-# 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.DFAReporting.AdvertiserGroups.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets one advertiser group by ID.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.advertiserGroups.get@.
module Network.Google.Resource.DFAReporting.AdvertiserGroups.Get
(
-- * REST Resource
AdvertiserGroupsGetResource
-- * Creating a Request
, advertiserGroupsGet
, AdvertiserGroupsGet
-- * Request Lenses
, agggXgafv
, agggUploadProtocol
, agggAccessToken
, agggUploadType
, agggProFileId
, agggId
, agggCallback
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.advertiserGroups.get@ method which the
-- 'AdvertiserGroupsGet' request conforms to.
type AdvertiserGroupsGetResource =
"dfareporting" :>
"v3.5" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"advertiserGroups" :>
Capture "id" (Textual Int64) :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] AdvertiserGroup
-- | Gets one advertiser group by ID.
--
-- /See:/ 'advertiserGroupsGet' smart constructor.
data AdvertiserGroupsGet =
AdvertiserGroupsGet'
{ _agggXgafv :: !(Maybe Xgafv)
, _agggUploadProtocol :: !(Maybe Text)
, _agggAccessToken :: !(Maybe Text)
, _agggUploadType :: !(Maybe Text)
, _agggProFileId :: !(Textual Int64)
, _agggId :: !(Textual Int64)
, _agggCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AdvertiserGroupsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'agggXgafv'
--
-- * 'agggUploadProtocol'
--
-- * 'agggAccessToken'
--
-- * 'agggUploadType'
--
-- * 'agggProFileId'
--
-- * 'agggId'
--
-- * 'agggCallback'
advertiserGroupsGet
:: Int64 -- ^ 'agggProFileId'
-> Int64 -- ^ 'agggId'
-> AdvertiserGroupsGet
advertiserGroupsGet pAgggProFileId_ pAgggId_ =
AdvertiserGroupsGet'
{ _agggXgafv = Nothing
, _agggUploadProtocol = Nothing
, _agggAccessToken = Nothing
, _agggUploadType = Nothing
, _agggProFileId = _Coerce # pAgggProFileId_
, _agggId = _Coerce # pAgggId_
, _agggCallback = Nothing
}
-- | V1 error format.
agggXgafv :: Lens' AdvertiserGroupsGet (Maybe Xgafv)
agggXgafv
= lens _agggXgafv (\ s a -> s{_agggXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
agggUploadProtocol :: Lens' AdvertiserGroupsGet (Maybe Text)
agggUploadProtocol
= lens _agggUploadProtocol
(\ s a -> s{_agggUploadProtocol = a})
-- | OAuth access token.
agggAccessToken :: Lens' AdvertiserGroupsGet (Maybe Text)
agggAccessToken
= lens _agggAccessToken
(\ s a -> s{_agggAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
agggUploadType :: Lens' AdvertiserGroupsGet (Maybe Text)
agggUploadType
= lens _agggUploadType
(\ s a -> s{_agggUploadType = a})
-- | User profile ID associated with this request.
agggProFileId :: Lens' AdvertiserGroupsGet Int64
agggProFileId
= lens _agggProFileId
(\ s a -> s{_agggProFileId = a})
. _Coerce
-- | Advertiser group ID.
agggId :: Lens' AdvertiserGroupsGet Int64
agggId
= lens _agggId (\ s a -> s{_agggId = a}) . _Coerce
-- | JSONP
agggCallback :: Lens' AdvertiserGroupsGet (Maybe Text)
agggCallback
= lens _agggCallback (\ s a -> s{_agggCallback = a})
instance GoogleRequest AdvertiserGroupsGet where
type Rs AdvertiserGroupsGet = AdvertiserGroup
type Scopes AdvertiserGroupsGet =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient AdvertiserGroupsGet'{..}
= go _agggProFileId _agggId _agggXgafv
_agggUploadProtocol
_agggAccessToken
_agggUploadType
_agggCallback
(Just AltJSON)
dFAReportingService
where go
= buildClient
(Proxy :: Proxy AdvertiserGroupsGetResource)
mempty
| brendanhay/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/AdvertiserGroups/Get.hs | mpl-2.0 | 5,209 | 0 | 19 | 1,264 | 821 | 474 | 347 | 119 | 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.YouTube.PlayLists.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a playlist.
--
-- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.playlists.insert@.
module Network.Google.Resource.YouTube.PlayLists.Insert
(
-- * REST Resource
PlayListsInsertResource
-- * Creating a Request
, playListsInsert
, PlayListsInsert
-- * Request Lenses
, pliPart
, pliPayload
, pliOnBehalfOfContentOwner
, pliOnBehalfOfContentOwnerChannel
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.playlists.insert@ method which the
-- 'PlayListsInsert' request conforms to.
type PlayListsInsertResource =
"youtube" :>
"v3" :>
"playlists" :>
QueryParam "part" Text :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "onBehalfOfContentOwnerChannel" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] PlayList :> Post '[JSON] PlayList
-- | Creates a playlist.
--
-- /See:/ 'playListsInsert' smart constructor.
data PlayListsInsert = PlayListsInsert'
{ _pliPart :: !Text
, _pliPayload :: !PlayList
, _pliOnBehalfOfContentOwner :: !(Maybe Text)
, _pliOnBehalfOfContentOwnerChannel :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'PlayListsInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pliPart'
--
-- * 'pliPayload'
--
-- * 'pliOnBehalfOfContentOwner'
--
-- * 'pliOnBehalfOfContentOwnerChannel'
playListsInsert
:: Text -- ^ 'pliPart'
-> PlayList -- ^ 'pliPayload'
-> PlayListsInsert
playListsInsert pPliPart_ pPliPayload_ =
PlayListsInsert'
{ _pliPart = pPliPart_
, _pliPayload = pPliPayload_
, _pliOnBehalfOfContentOwner = Nothing
, _pliOnBehalfOfContentOwnerChannel = Nothing
}
-- | The part parameter serves two purposes in this operation. It identifies
-- the properties that the write operation will set as well as the
-- properties that the API response will include.
pliPart :: Lens' PlayListsInsert Text
pliPart = lens _pliPart (\ s a -> s{_pliPart = a})
-- | Multipart request metadata.
pliPayload :: Lens' PlayListsInsert PlayList
pliPayload
= lens _pliPayload (\ s a -> s{_pliPayload = a})
-- | Note: This parameter is intended exclusively for YouTube content
-- partners. The onBehalfOfContentOwner parameter indicates that the
-- request\'s authorization credentials identify a YouTube CMS user who is
-- acting on behalf of the content owner specified in the parameter value.
-- This parameter is intended for YouTube content partners that own and
-- manage many different YouTube channels. It allows content owners to
-- authenticate once and get access to all their video and channel data,
-- without having to provide authentication credentials for each individual
-- channel. The CMS account that the user authenticates with must be linked
-- to the specified YouTube content owner.
pliOnBehalfOfContentOwner :: Lens' PlayListsInsert (Maybe Text)
pliOnBehalfOfContentOwner
= lens _pliOnBehalfOfContentOwner
(\ s a -> s{_pliOnBehalfOfContentOwner = a})
-- | This parameter can only be used in a properly authorized request. Note:
-- This parameter is intended exclusively for YouTube content partners. The
-- onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID
-- of the channel to which a video is being added. This parameter is
-- required when a request specifies a value for the onBehalfOfContentOwner
-- parameter, and it can only be used in conjunction with that parameter.
-- In addition, the request must be authorized using a CMS account that is
-- linked to the content owner that the onBehalfOfContentOwner parameter
-- specifies. Finally, the channel that the onBehalfOfContentOwnerChannel
-- parameter value specifies must be linked to the content owner that the
-- onBehalfOfContentOwner parameter specifies. This parameter is intended
-- for YouTube content partners that own and manage many different YouTube
-- channels. It allows content owners to authenticate once and perform
-- actions on behalf of the channel specified in the parameter value,
-- without having to provide authentication credentials for each separate
-- channel.
pliOnBehalfOfContentOwnerChannel :: Lens' PlayListsInsert (Maybe Text)
pliOnBehalfOfContentOwnerChannel
= lens _pliOnBehalfOfContentOwnerChannel
(\ s a -> s{_pliOnBehalfOfContentOwnerChannel = a})
instance GoogleRequest PlayListsInsert where
type Rs PlayListsInsert = PlayList
type Scopes PlayListsInsert =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl",
"https://www.googleapis.com/auth/youtubepartner"]
requestClient PlayListsInsert'{..}
= go (Just _pliPart) _pliOnBehalfOfContentOwner
_pliOnBehalfOfContentOwnerChannel
(Just AltJSON)
_pliPayload
youTubeService
where go
= buildClient
(Proxy :: Proxy PlayListsInsertResource)
mempty
| rueshyna/gogol | gogol-youtube/gen/Network/Google/Resource/YouTube/PlayLists/Insert.hs | mpl-2.0 | 6,106 | 0 | 15 | 1,286 | 580 | 353 | 227 | 85 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Route53Domains.DeleteTagsForDomain
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation deletes the specified tags for a domain.
--
-- All tag operations are eventually consistent; subsequent operations may not
-- immediately represent all issued operations.
--
-- <http://docs.aws.amazon.com/Route53/latest/APIReference/api-DeleteTagsForDomain.html>
module Network.AWS.Route53Domains.DeleteTagsForDomain
(
-- * Request
DeleteTagsForDomain
-- ** Request constructor
, deleteTagsForDomain
-- ** Request lenses
, dtfdDomainName
, dtfdTagsToDelete
-- * Response
, DeleteTagsForDomainResponse
-- ** Response constructor
, deleteTagsForDomainResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.Route53Domains.Types
import qualified GHC.Exts
data DeleteTagsForDomain = DeleteTagsForDomain
{ _dtfdDomainName :: Text
, _dtfdTagsToDelete :: List "TagsToDelete" Text
} deriving (Eq, Ord, Read, Show)
-- | 'DeleteTagsForDomain' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dtfdDomainName' @::@ 'Text'
--
-- * 'dtfdTagsToDelete' @::@ ['Text']
--
deleteTagsForDomain :: Text -- ^ 'dtfdDomainName'
-> DeleteTagsForDomain
deleteTagsForDomain p1 = DeleteTagsForDomain
{ _dtfdDomainName = p1
, _dtfdTagsToDelete = mempty
}
-- | The domain for which you want to delete one or more tags.
--
-- The name of a domain.
--
-- Type: String
--
-- Default: None
--
-- Constraints: The domain name can contain only the letters a through z, the
-- numbers 0 through 9, and hyphen (-). Hyphens are allowed only when theyaposre
-- surrounded by letters, numbers, or other hyphens. You canapost specify a
-- hyphen at the beginning or end of a label. To specify an Internationalized
-- Domain Name, you must convert the name to Punycode.
--
-- Required: Yes
dtfdDomainName :: Lens' DeleteTagsForDomain Text
dtfdDomainName = lens _dtfdDomainName (\s a -> s { _dtfdDomainName = a })
-- | A list of tag keys to delete.
--
-- Type: A list that contains the keys of the tags that you want to delete.
--
-- Default: None
--
-- Required: No
--
-- '>
dtfdTagsToDelete :: Lens' DeleteTagsForDomain [Text]
dtfdTagsToDelete = lens _dtfdTagsToDelete (\s a -> s { _dtfdTagsToDelete = a }) . _List
data DeleteTagsForDomainResponse = DeleteTagsForDomainResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteTagsForDomainResponse' constructor.
deleteTagsForDomainResponse :: DeleteTagsForDomainResponse
deleteTagsForDomainResponse = DeleteTagsForDomainResponse
instance ToPath DeleteTagsForDomain where
toPath = const "/"
instance ToQuery DeleteTagsForDomain where
toQuery = const mempty
instance ToHeaders DeleteTagsForDomain
instance ToJSON DeleteTagsForDomain where
toJSON DeleteTagsForDomain{..} = object
[ "DomainName" .= _dtfdDomainName
, "TagsToDelete" .= _dtfdTagsToDelete
]
instance AWSRequest DeleteTagsForDomain where
type Sv DeleteTagsForDomain = Route53Domains
type Rs DeleteTagsForDomain = DeleteTagsForDomainResponse
request = post "DeleteTagsForDomain"
response = nullResponse DeleteTagsForDomainResponse
| dysinger/amazonka | amazonka-route53-domains/gen/Network/AWS/Route53Domains/DeleteTagsForDomain.hs | mpl-2.0 | 4,217 | 0 | 10 | 854 | 439 | 275 | 164 | 53 | 1 |
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
module Main
( main
, test1
, test2
, test3
, test4
, test5
, test6
, test7
, test8
, test9
) where
| lspitzner/brittany | data/Test452.hs | agpl-3.0 | 235 | 0 | 4 | 57 | 37 | 25 | 12 | 11 | 0 |
-- |Wrappers for libdvb. I'm not sure how it should be done so this
-- may contain fatal errors. Feel free to fix my code if it's broken.
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}
module Dvb where
import Control.Monad
import Foreign.C
import Foreign.Ptr
import Foreign.Marshal.Alloc
import System.IO
import System.Posix.IO (fdToHandle)
import System.Posix.Types
data DvbDeviceStruct
type DvbDevice = Ptr DvbDeviceStruct
foreign import ccall unsafe "new_dvb_device" new_dvb_device :: IO DvbDevice
foreign import ccall unsafe "dvb_open" dvb_open :: DvbDevice -> CInt -> CInt -> CInt -> IO CInt
foreign import ccall unsafe "dvb_get_error" dvb_get_error :: DvbDevice -> IO CString
foreign import ccall unsafe "dvb_tune" dvb_tune :: DvbDevice -> CSize -> IO CInt
foreign import ccall unsafe "dvb_init_pes_stream" dvb_init_pes_stream :: DvbDevice -> CInt -> CInt -> IO CInt
foreign import ccall unsafe "dvb_stop_stream" dvb_stop_stream :: DvbDevice -> IO CInt
foreign import ccall unsafe "dvb_get_demuxer_fd" dvb_get_demuxer_fd :: DvbDevice -> IO CInt
openDvb :: Int -> Int -> Int -> Int -> Int -> IO (Handle,DvbDevice)
openDvb devId frontendId demuxerId frequency pid = do
dev <- new_dvb_device
when (dev==nullPtr) $ fail "Unable to allocate memory"
openStatus <- dvb_open dev (fromIntegral devId) (fromIntegral frontendId) (fromIntegral demuxerId)
case openStatus of
0 -> do
tuneStatus <- dvb_tune dev (fromIntegral frequency)
case tuneStatus of
0 -> do
initStatus <- dvb_init_pes_stream dev (fromIntegral pid) 5
case initStatus of
0 -> do
fd <- dvb_get_demuxer_fd dev
h <- fdToHandle $ Fd fd
return (h,dev)
_ -> cleanupAndFail dev
_ -> cleanupAndFail dev
_ -> cleanupAndFail dev
cleanupAndFail :: DvbDevice -> IO a
cleanupAndFail dev = do
msg <- dvb_get_error dev >>= peekCString
free dev
error msg
closeDvb :: DvbDevice -> IO ()
closeDvb dev = do
status <- dvb_stop_stream dev
case status of
0 -> free dev
_ -> cleanupAndFail dev
| koodilehto/kryptoradio | receiver/Dvb.hs | agpl-3.0 | 2,100 | 0 | 24 | 444 | 583 | 290 | 293 | -1 | -1 |
{-
Habit of Fate, a game to incentivize habit formation.
Copyright (C) 2019 Gregory Crosswhite
This program is free software: you can redistribute it and/or modify
it under version 3 of the terms of the GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE UnicodeSyntax #-}
{-# OPTIONS_GHC -Wno-missing-signatures #-}
module HabitOfFate.Quests.Forest where
import HabitOfFate.Prelude
import Data.Vector (Vector)
import HabitOfFate.Data.Gender
import HabitOfFate.Quest
import HabitOfFate.Story
--------------------------------------------------------------------------------
--------------------------------- Intro Stories --------------------------------
--------------------------------------------------------------------------------
intro = Narrative
{ title = "The Wicked Forest"
, content = [story|
The Wicked Forest: frightful enough during the day, full of even greater terrors
by night. Unfortunately, it is also the only place where a healing *|Plant*
plant can be obtained, so a brave man/woman| is about to enter it.
|]}
intro_parent = Narrative
{ title = "A Parent Enters The Woods"
, content = [story|
The last thing in the world that **|Searcher** wanted to do was to wander alone
in the Wicked Forest at night, but his/her|Searcher son/daughter|Child, little
**|Child**, was sick and would not live through the night unless |Searcher could
find an **|Plant** plant to give to the healer to make a potion, as the healer
refused to enter the forest himself/herself| at night. It is a hopeless task,
but he/she| has no other choice.
He/she| enters the forest.
|]}
intro_healer = Narrative
{ title = "A Healer Enters The Woods"
, content = [story|
There were times when **|Searcher**, the village healer, cursed himself/herself|
for deciding to become a healer, and this was one of them. Little **|Child** had
brain fever, and the only way he/she|Child would survive the night is if he/she|
could make a potion with **a |Plant** plant. Unfortunately, she was out of this
herb, and the only way to get more of it was to search the Wicket Forest.
He/she| considered telling the family that they would have to be the ones to do
this, but his/her| conscience told him/her| that it was his/her| duty, besides
which they might not recognize it and pick the wrong plant. Also the gold
helped.
He/she| entered the forest.
|]}
--------------------------------------------------------------------------------
-------------------------------- Status Stories --------------------------------
--------------------------------------------------------------------------------
looking_for_herb_story = [story|
|Searcher continues to search in the dark for an |Plant plant.
|]
returning_home_story = [story|
An |Plant plant in hand, **|Searcher** continues towards home.
|]
--------------------------------------------------------------------------------
------------------------------- Wandering Stories ------------------------------
--------------------------------------------------------------------------------
wander_stories = [stories|
================================ Nothing Happens ===============================
Nothing happens as |Searcher wanders through the forest.
================================== Wolves Howl =================================
As |Searcher continues to search he/she| hears the howling of wolves, which makes
him/her| shiver. Thank goodness they seem to be in the distance!
================================ Candle Goes Out ===============================
|Searcher's candle goes out; the resulting darkness is oppressive. Fortunately,
he/she| had prepared for this. He/she| reached into his/her| pack and drew out
flintstone, which he/she| uses to re-light the candle.
============================== Shadow Stops Moving =============================
|Searcher can feel that something is amiss, but he/she| can't figure out what.
He/she| pauses for a moment and looks around. After a moment, he/she| realizes
that his/her| shadow didn't stop walking when he/she| did. He/she| backs away
slowly as his/her| shadow gets further and further away from him/her|. He/she|
decides to start searching in a different direction.
=================================== Full Moon ==================================
|Searcher looks up at the Moon. For reasons that nobody understands, the Moon is
always full in the Wicked Forest. The good news is that this makes it easier to
search for |Plant, but the bad news is that he/she| has to worry about
werewolves...
================================= Talking Tree =================================
“Hello, human. It isn't often that I get to see one of your kind here.”
|Searcher jumped and looked around for the source of the voice. He/she| heard it
laugh. “You are just as stupid as the rest of your kind. Look, I am over here.”
|Searcher finally realized that the voice was coming from the tree right next to
him/her|.
“Why are you here?” it asked. |Searcher replied, “I am looking for an |Plant
plant. I down't suppose you have seen one?” It laughed. “Do I look like I have
legs?” |Searcher replied, “Umm, no, I guess not; I guess I'll just be going on my
way then...”
|Searcher resumed searching, the laugher of the tree receding as he/she| left it
behind.
|]
--------------------------------------------------------------------------------
-------------------------------- Event Stories -------------------------------
--------------------------------------------------------------------------------
gingerbread_house = SuccessDangerAvertedFailure
{ common_title = "The Gingerbread House"
, common_story = [story|
|Searcher sees a house made out of... gingerbread? He/she| feels a strange
compulsion to approach it.
|]
, common_question = [s|Where do You guide |Searcher?|]
, success_choice = "Away from the gingerbread house."
, success_title = "Even Gingerbread Cannot Slow The Search"
, success_story = [story|
He/she| fights the compulsion, and continues on his/her| search.
|]
, danger_choice = "Towards the gingerbread house."
, danger_title = "The Gingerbread Compulsion is Too Great"
, danger_story = [story|
As he/she| gets closer, the door opens and an old woman beckons him/her| in.
“You've arrived just in time!” she says. “Dinner has just finished cooking. Come
on in!”
|]
, danger_question = [s|How do you have |Searcher react?|]
, averted_choice = [s|He/She| runs away!|]
, averted_title = "Escaping The Gingerbread House"
, averted_story = [story|
The smell from the cottage is overwhelming, and shocks |Searcher to his/her|
senses. He/she| sprints away from the cottage as fast as he/she| can.
|]
, failure_choice = [s|He/She| enters the house.|]
, failure_title = "Entering The Gingerbread House"
, failure_story = [story|
Not knowing why he/she| was doing this, |Searcher enters the... cottage? The woman
leads her to an oven. “Here, look inside.”
|Searcher looks inside the oven and sees... little |Child? he/she| screams, and
faints.
Daylight awakens her. He/she|Searcher looks around, but the gingerbread house is
nowhere to be found.
He/she| sobs -- there is no way that he/she| will be able to make it home in
time now.
|]
, shames = [stories|
================================================================================
The sweet smell of gingerbread was just too alluring for |Searcher.
================================================================================
|Child was completely forgotten as |Searcher was drawn into a gingerbread house.
|]}
found = Narrative
{ title = "Some Help Arrives?"
, content = [story|
Finally, just when all hope is lost, a creature arrives to help |Searcher.
|]}
found_by_fairy = [outcomes|
================================= Common Title =================================
Running After a Fairy
================================= Common Story =================================
|Searcher starts to hear a sound and he/she| can't tell whether it is a buzzing or
the most beautiful music he/she| has ever heard. As it gets louder he/she|
notices the area around him/her| starting to get brighter. He/she| looks around
and sees a fairy, glowing brightly in the dark. The fairy beckons to him/her|,
and then flies away. |Searcher hesitates briefly, and then runs after the fairy.
================================ Common Question ===============================
How fast does the fairy make Andrea chase her?
================================ Success Choice ================================
Running speed
================================= Success Title ================================
A Successful Chase
================================= Success Story ================================
|Searcher chases the fairy for about an hour, starting to doubt whether this is
such a good idea, when the fairy stops. He/she| catches up to it and sees an
|Plant plant under it. Carefully, he/she| reaches down and picks it. When
he/she| looks up, the fairy is gone.
He/she| falls to his/her| knees and thanks you for guiding him/her| to the plant.
He/she| then gets up and starts heading back to his/her| home.
================================= Danger Choice ================================
Ludicious speed
================================= Danger Title =================================
Can't Stop Chasing
================================= Danger Story =================================
The chase after the fairy becomes faster and faster, but unfortunately |Searcher
does not seem to be able to break free of its grip.
================================ Danger Question ===============================
What stops Andrea's chase?
================================ Averted Choice ================================
A tree.
================================= Averted Title ================================
Slammed Into a Tree
================================= Averted Story ================================
Suddenly the run ends with |Searcher slamming into a tree. She falls to the
ground. After a few moments, she gets up, nursing splitting headache.
Miracuously, she finds a |Plant at the bottom of the tree. She picks it and
returns home.
================================ Failure Choice ================================
Time.
================================= Failure Title ================================
Passage of Time
================================= Failure Story ================================
|Searcher runs faster and faster to catch up with the fairy. Everything starts
to blur until there is only him/her| and the fairy. Eventually it all fades to
black.
|Searcher wakes up to the sounds of birds singing. After a moment of
disorientation, he/she| realizes that he/she| is still in the forest, and it is
now morning. She weeps, for surely by now |Child is dead.
===================================== Shame ====================================
In retrospect, |Searcher realized that chasing after a random fairy was a bad
idea.
--------------------------------------------------------------------------------
|Searcher learned the hard way that not all fairies are good fairies.
|]
found_by_cat = [outcomes|
================================= Common Title =================================
Chance Encounter with a Cat
================================= Common Story =================================
|Searcher hears a meow. He/she| looks to the source, and sees a forest cat. It
is hard to see the color of the cat, which is a problem because green cats are
good but blue cats are evil.
The cat beckons to him/her| and starts walking. Should he/she| follow the cat?
As trepidatious as he/she| is feeling about the situation, he/she| does really
need to get the herb as soon as he/she| can, and this is the best lead he/she|
has had all night. He/she| decides to roll the dice and follow the cat.
================================ Common Question ===============================
What color is the cat?
================================ Success Choice ================================
Blue
================================= Success Title ================================
Following the Cat
================================= Success Story ================================
He/she| follows the cat for some time, and eventually it stops. It picks
something up and brings it to him/her|. Excitedly, she bends down to look at it.
It is a mouse.
He/she| growls and tosses the mouse to the side. He/she| starts to walk away
when he/she| realizes that the cat is sitting right next to a |Plant plant.
A beam of moonlight reveals that the cat has green fur.
Well, cats are cats, even the good ones.
He/she| walks over and picks the plant, and then scratches the cat. “Good
kitty!” he/she| says. It purrs.
He/she| starts to journey home.
================================= Danger Choice ================================
Green
================================= Danger Title =================================
Following The Cat
================================= Danger Story =================================
|Searcher chases after the cat, barely able to keep up. It is because of this
that she does not notice that she is stepping into a pit.
================================ Danger Question ===============================
Is she hurt?
================================ Averted Choice ================================
No.
================================= Averted Title ================================
Missed Getting Hurt
================================= Averted Story ================================
|Searcher follows into the pit but somehow avoids getting any broken bones.
He/she| looks up in time to see the cat, its blue fur finally shown clearly in a
beam of moonlight, flash him/her| a cheshire grin and vanish.
|Searcher grumbles at the existence of mischievous malevolent cats, but at least
he/she| notices a |Plant herb at the bottom so she can start heading home.
================================ Failure Choice ================================
Yes.
================================= Failure Title ================================
Can't Get Up
================================= Failure Story ================================
|Searcher follows the cat for some time before he/she|Searcher realizes too late
that he/she| is stepping into a pit. Unable to catch himself/herself| in time,
he/she| falls into the put, breaking a leg. The cat looks down into the pit,
its fur not clearly revealed to be blue in the moonlight, and flashes him/her|
a cheshire grin, after which it vanishes. |Searcher growls in anger and then
faints in pain. |Child will not be getting the medicine that he desperately
needs tonight...
===================================== Shame ====================================
|Searcher should have known better than to follow a forest cat at night without
knowing its color.
--------------------------------------------------------------------------------
|Searcher learned the hard way that chasing after random forest cats in the
middle of the night is a bad plan.
|]
fairy_circle = [outcomes|
================================= Common Title =================================
The Mushroom Circle
================================= Common Story =================================
A mushroom circle lies just along |Searcher's path, but he/she| is so busy
looking for a |Plant plant that he/she| walks straight towards it.
================================ Common Question ===============================
Does she see it in time?
================================ Success Choice ================================
Yes.
================================= Success Title ================================
Mushroom Circle Averted
================================= Success Story ================================
Fortunately, |Searcher sees it just before stepping inside. After a moment of
letting his/her| heart calm down, he/she| says a prayer of thanks to you and
resumes searching in a different direction.
================================= Danger Choice ================================
No.
================================= Danger Title =================================
|Searcher Steps Inside
================================= Danger Story =================================
Unfortunately, by the time |Searcher notices it she was already inside.
Desperately, he/she| turns around and starts to run out of it.
================================ Danger Question ===============================
Does she make it out in time?
================================ Averted Choice ================================
Yes.
================================= Averted Title ================================
Escaping The Fairy Ring
================================= Averted Story ================================
Miraculously, he/she| makes it out. He/she| continues the search.
================================ Failure Choice ================================
No.
================================= Failure Title ================================
Traped in the Fairy Circle
================================= Failure Story ================================
Unfortunately, he/she| sees a leprechaun between him/her| and the mushroom
border. “Welcome, mortal!” it says to him/her| cheerfully. “I am sure you will
have a wonderful time in our land.”
********************************************************************************
His/her| times in the fairy world all felt like a dream; when it was all over,
he/she| could hardly remember what it had been like. He/she| found
himself/herself| standing in the forest in the bright light of day, with
mushrooms nowhere to be seen. He/she| ran back to the village, but it was no
longer there -- at least, as she remembered it. The houses were not in the same
place and were larger, the dirt roads were now covered with some black material
and had strange shiny creatures on them, and branchless trees were everywhere
with black rope strung between them. He/she| had no idea how much time he/she|
had spent away from the world, but she knew that |Child, as well as everyone
else he/she| had known and loved, was certainly dead.
===================================== Shame ====================================
Next time |Searcher needs to watch where she is stepping lest she step into a fairy
circle again... if there is a next time.
--------------------------------------------------------------------------------
Having been mysteriously teleported to a distant realm by the enigmatic magic of
the fairies, there was no way |Searcher could make it back in time to save |Child.
|]
conclusion_parent = [outcomes|
================================= Common Title =================================
He/she| has made it home!
================================= Common Story =================================
|Searcher is starting to feel like he/she| will never make it back when he/she|
notices that things are starting to get brighter--he/she| must be getting
close to the village! He/she| gives you thanks for guiding him/her| home.
================================ Common Question ===============================
What plant Did Andrea bring the right herb to the healer?
================================ Success Choice ================================
A |Plant plant.
================================= Success Title ================================
The Long Quest is Over!
================================= Success Story ================================
A little bit further, and he/she| is back to to the healer. He/she| pounds on
the door. When the healer opens it, |Searcher gives him/her| the plant. The
healer looks surprised. “I didn’t think that you would make it, let alone bring
me the correct plant. Come in and sit; this won’t take long.” |Searcher enters
the hut and sits. A moment latter he/she| feels himself/herself| being shaken.
“Don’t fall asleep now, fool, take this potion home and give it to |Child.
Quickly!”
|Searcher rushes home and wakes up |Child long enough to ladle the potion down this
throat; he/she|Child immediately falls back asleep. Exhausted himself/herself|,
he/she| falls asleep on the floor; he/she| sleeps peacefully, with a smile on
him/her| face. The next day, he/she| builds an altar to you out of gratitude.
================================= Danger Choice ================================
A |WrongPlant plant.
================================= Danger Title =================================
The Wrong Plant
================================= Danger Story =================================
A little bit further, and he/she| is back to to the healer. He/she| pounds on
the door. When the healer opens it, |Searcher gives her/ the plant. The healer
looks surprised. “I didn’t think that you would make it, but unfortunately you
have brought me the wrong plant.”
“I… I did?” asked |Searcher, tears starting to form in her eyes.
The healer looked at the plant more closely. “Well… this isn’t what I asked for,
but I might be able to improvise something that will work with this. Come in and
sit; this won’t take long.” |Searcher enters the hut and sits. A moment latter
he/she| feels himself/herself| being shaken. “Don’t fall asleep now, fool, take
this potion home and give it to |Child. Quickly!”
|Searcher rushes home and wakes up |Child long enough to ladle the potion down this
throat; he/she|Child immediately falls back asleep. Exhausted himself/herself|,
he/she| falls asleep on the floor; he/she| sleeps fitfully.
================================ Danger Question ===============================
Does the wrong herb work well enough?
================================ Averted Choice ================================
Yes.
================================= Averted Title ================================
A Close Call
================================= Averted Story ================================
The next day, he/she| wakes up and quickly looks over at |Child. To his/her|
immense relief, |Child is snoring peacefully. Filled with immense gratitude,
he/she| builds an altar to you.
================================ Failure Choice ================================
No.
================================= Failure Title ================================
All Is For Naught
================================= Failure Story ================================
The next day, he/she| wakes up and quickly looks over at |Child. At first
he/she| thinks that |Child is sleeping peacefully and starts to breathe a sigh
of relief, but then he/she| realizes that |Child is not breathing at all.
|Searcher falls to the ground and weeps. If only she had gotten the correct plant!
===================================== Shame ====================================
After a hard night wandering through the Wicked Forest, |Searcher has nothing to
show for it but a dead child.
|]
fames_parent = [stories|
Against all odds, |Searcher was able to find the correct plant that was needed
to mix a potion to save her sick son/daughter|Child.
|]
conclusion_healer = [outcomes|
================================= Common Title =================================
Finally Back Home
================================= Common Story =================================
|Searcher is starting to feel like he/she| will never make it back in time when
he/she| sees the shapes of the huts of her village not far in the distance.
================================ Common Question ===============================
Is there anything strange about the town?
================================ Success Choice ================================
Nope, everything is fine.
================================= Success Title ================================
Victory!
================================= Success Story ================================
Not long after arriving, he/she| makes it back to his/her| hut and immediately
starts brewing medicine for |Child. He/she| takes it to the family’s hut and
gives it to them to administer to |Child. It is true that he/she| had just
risked life and limb to save a single person, but he/she| considered it to be
well worth it. Also they gave her a bonus.
He/she| returned to his/her| own hut and did not even have enough energy to make
it to the bed; she fell asleep on the floor, though with a smile on his/her|
face. The next day, he/she| builds an altar to you out of gratitude.
================================= Danger Choice ================================
Yes, come to think of it...
================================= Danger Title =================================
Something Is Odd Here
================================= Danger Story =================================
He/she starts to breathe a sigh of relief when he/she| realizes that something
is off that he/she| cannot quite place. As he/she| got closer, he/she| realized
that the doors to the huts were all facing him/her|, and that they seemed to
always be facing him/her| no matter how close he/she| got to the village. Had
they always been that way? Or was something strange going on.
================================ Danger Question ===============================
Where will you guide him/her|?
================================ Averted Choice ================================
Away from the village.
================================= Averted Title ================================
Keeping a Safe Distance
================================= Averted Story ================================
When in or close to the Wicked Forest, it is best to trust one’s instincts.
Thus, even though it was the last thing that |Searcher wanted to do, he/she|
turned around and walked back into the forest.
After wandering for another hour, he/she| again saw huts, but this time he/she|
did not get the same feeling of wrongness so he/she| cautiously approached them.
Again, nothing seemed amiss so he/she| entered the village and headed towards
his/her| hut. He/she| immediately starts brewing medicine for |Child and then
takes it to the family’s hut and gives it to them to administer to |Child. It is
true that he/she| had just risked life and limb to save a single person, but
he/she| considered it to be well worth it. Also they gave him/her| a bonus.
He/she| returned to his/her| own hut and did not even have enough energy to make
it to the bed; he/she| fell asleep on the floor, though with a smile on his/her|
face. The next day, he/she| builds an altar to you out of gratitude.
================================ Failure Choice ================================
Towards the village.
================================= Failure Title ================================
There Is No Time to Wait
================================= Failure Story ================================
He/she| dismissed the notion; it had been a long night and the most likely
explanation was that his/her| mind was going after his/her| long search in the
Wicked Forest. Besides which, most importantly, he/she| needed to prepare the
medication for |Child as quickly as possible. He/she| headed quickly to his/her|
hut and opened the door. To His/her| shock, he/she| saw himself/herself|
inside--but it wasn’t quite him/her|. After a moment, he/she| realized what was
wrong: the thing inside was flat, as if it were made of paper. Both |Searcher
and the thing said simultaneously, “What are you?”
|Searcher yelped in pain. He/she| looked down at his/her| arms and saw that they
were getting flatter. The thing smiled, “I guess you are one of us now.”
|Searcher noticed that he/she| could see straight through his/her| own mouth
whenever it opened.
Well, maybe in this world he/she| could at least do some good. He/she| asked,
“How is |Child?”
The thing frowned. “Who is |Child?”
|Searcher starts to weep in pain and anguish but as his/her| head flattens the
tears were unable to push themselves out of his/her| tear ducts.
“Don’t worry,” said the thing. “You will be safe here... forever... with us.”
===================================== Shame ====================================
|Searcher's story goes flat as he/she| is sent to an alternate dimension and is
unable to return to the village to make the potion for |Child.
--------------------------------------------------------------------------------
|Searcher found herself trapped in a land of cardboard cutouts.
|]
fames_healer = [stories|
After a long and difficulty journey, |Searcher returned triumphantly with the
final herb she needed to save |Child.
|]
--------------------------------------------------------------------------------
------------------------------------- Quest ------------------------------------
--------------------------------------------------------------------------------
right_plants, wrong_plants ∷ Vector Text
right_plants = ["Illsbane"]
wrong_plants = ["Tigerlamp"]
quest ∷ Quest
quest = Quest
"forest"
"A prayer from someone searching for an herb in the Wicked Forest."
[ SP "Searcher" [("Andrea",Female)]
, S "Child" [("Tommy",Male)]
, S "Plant" [("Illsbane",Neuter)]
, S "WrongPlant" [("Tigerlamp",Neuter)]
]
( LineEntry
NoShuffle
"root"
[ RandomStoriesEntry wander_stories
, SplitEntry
"who"
intro
"Who shall we follow into the Wicked Forest?"
[ Branch
"The village healer."
mempty
(LineEntry NoShuffle "healer" $
[ FamesEntry fames_healer
, StatusEntry looking_for_herb_story
, NarrativeEntry
"intro"
intro_healer
, LineEntry Shuffle "events" shared_story_entries
, EventEntry
"conclusion"
conclusion_healer
])
, Branch
"The parent of the sick child."
mempty
(LineEntry NoShuffle "parent" $
[ FamesEntry fames_parent
, StatusEntry looking_for_herb_story
, NarrativeEntry
"intro"
intro_parent
, LineEntry Shuffle "events" shared_story_entries
, EventEntry
"conclusion"
conclusion_parent
])
]
]
)
shared_story_entries =
[ EventEntry
"gingerbread"
gingerbread_house
, LineEntry NoShuffle
"found"
[ SplitEntry
"by"
found
"Who is this?"
[ Branch
"A cat."
mempty
(EventEntry
"cat"
found_by_cat)
, Branch
"A fairy."
mempty
(EventEntry
"fairy"
found_by_fairy)
]
, StatusEntry returning_home_story
]
, EventEntry
"fairy-circle"
fairy_circle
]
| gcross/habit-of-fate | sources/library/HabitOfFate/Quests/Forest.hs | agpl-3.0 | 31,438 | 0 | 15 | 4,921 | 737 | 475 | 262 | 123 | 1 |
-- {-# LANGUAGE #-}
{-# OPTIONS_GHC -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : Shady.MechanicsGL
-- Copyright : (c) Conal Elliott
-- License : AGPLv3
--
-- Maintainer : conal@conal.net
-- Stability : experimental
--
-- Some utilities for shader generation
----------------------------------------------------------------------
module Shady.MechanicsGLGlut (shadyInit) where
import Prelude
import Control.Exception (SomeException(..), catch)
import Graphics.Rendering.OpenGL hiding (Shader,Program,Index,Sink)
import Graphics.UI.GLUT
( getArgsAndInitialize, createWindow, windowSize, initialDisplayMode
, DisplayMode(DoubleBuffered,RGBAMode,WithDepthBuffer,WithAlphaComponent)
, ActionOnWindowClose(MainLoopReturns)
, displayCallback, actionOnWindowClose, swapBuffers
, mainLoop, addTimerCallback
)
import Graphics.Glew
import Shady.Misc (Sink,Action)
-- | Initialize Shady and return a wrapper for a drawing command.
-- Supplying that drawing command will cause it to be invoked regularly.
shadyInit :: String -> IO (Sink Action)
shadyInit title =
do putStrLn "getArgsAndInitialize"
_ <- getArgsAndInitialize
-- putStrLn "IL.init"
-- IL.init
putStrLn "createWindow"
_ <- createWindow title
windowSize $= Size 600 600
-- fullScreen
initialDisplayMode $= [ DoubleBuffered, RGBAMode, WithDepthBuffer, WithAlphaComponent ]
putStrLn "depthFunc"
depthFunc $= Just Less -- defaults to Nothing / Just Always
putStrLn "glewInit"
_ <- glewInit -- must come after createWindow -- otherwise segfault
putStrLn "survived glewInit"
-- Experimenting with transparency. OpenGL (really, z-buffering)
-- doesn't handle transparency sensibly. Rendering is order-dependent.
-- blend $= Enabled >> blendFunc $= (SrcAlpha, One)
-- Hm. The transparency in lesson08 in Lispy's nehe translations
-- looks good. Oh. It's a hack, turning off depth-writing. See
-- <http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=08>
-- End of experiments
putStrLn "glEnableVSync"
glEnableVSync True
-- Hm. These two queries tell me "2.1.2 NVIDIA 180.11, 1.20 NVIDIA
-- via Cg compiler", but I am getting hyperbolic trig functions.
-- What gives? Oh -- maybe HOpenGL was compiled against OpenGL
-- 2.1.2 & 1.20, although I'm really running 3.0 and 1.20. I don't know.
-- get glVersion >>= putStr . (++ ", ")
-- get shadingLanguageVersion >>= putStrLn
displayCallback $= return () -- real update via timer.
catch (actionOnWindowClose $= MainLoopReturns)
(\ (SomeException _) -> return ())
putStrLn "finished shadyInit"
return $ timedDisplay . display
-- From MechanicsGLGtk (in shady-tv)
-- timedDisplay :: Gtk.Window -> GtkGL.GLDrawingArea -> Action -> IO ()
-- timedDisplay window canvas render =
-- do timeout <- Gtk.timeoutAddFull (display canvas render >> return True)
-- Gtk.priorityDefaultIdle period
-- Gtk.onDestroy window (Gtk.timeoutRemove timeout >> Gtk.mainQuit)
-- Gtk.mainGUI
-- where
-- period = 1000 `div` 60 -- milliseconds
timedDisplay :: Sink Action
timedDisplay disp =
do timedCallback period disp
mainLoop
where
period = 1000 `div` 60 -- milliseconds
display :: Sink Action
display render =
do clear [ColorBuffer, DepthBuffer]
render
glWaitVSync
finish
-- flush
swapBuffers
timedCallback :: Int -> Sink Action
timedCallback ms act = loop
where
loop = addTimerCallback ms (act >> loop)
-- Alternatively:
--
-- idleCallback $= Just act
| conal/shady-render | src/Shady/MechanicsGLGlut.hs | agpl-3.0 | 3,707 | 0 | 11 | 773 | 490 | 277 | 213 | 48 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Main where
import Control.Monad
import Data.List
import qualified Data.Map as M
import QuantLib.Methods.MonteCarlo
import QuantLib.Methods.Pricer (MaxMinClosePricer (..))
import QuantLib.Stochastic
newtype HistoSummary = HS (M.Map Double Int)
deriving (Show)
toDouble :: Int -> Double
toDouble = fromIntegral
addOnePath :: HistoSummary->MaxMinClosePricer->HistoSummary
addOnePath (HS m) (MMCP _ _ close) = HS newM
where (_, !newM) = M.insertLookupWithKey inserter roundedClose 1 m
!roundedClose = toDouble (round (close*10000))/10000
inserter _ new_value old_value = old_value+new_value
instance Summary HistoSummary MaxMinClosePricer where
sNorm _ _ = 0.0 -- we don't care about convergence now
sSummarize = foldl' addOnePath
printMap :: HistoSummary->IO ()
printMap (HS m) = forM_ list printPlain
where
printPlain (a, b) = putStrLn $ show a ++ "," ++ show b
list = M.toList m
getHsSize :: HistoSummary -> Int
getHsSize (HS m) = M.size m
main :: IO ()
main = do
let summary = HS M.empty
let mmcp = MMCP 0.0 0.0 0.0
let start = Dot 0.0 1.0
let sp = GeometricBrownian 0.0 0.005
let discrete= Euler 0.01
rng <- mkInverseNormal :: IO (InverseNormal PureMT)
let pg = ProcessGenerator start 1000 sp rng discrete
let pmc = PathMonteCarlo summary mmcp pg
let s = monteCarlo pmc 1000
printMap s
print (getHsSize s)
| paulrzcz/hquantlib | src/Tests/McTest.hs | lgpl-3.0 | 1,732 | 0 | 12 | 526 | 507 | 255 | 252 | 41 | 1 |
module Lupo.Navigation where
import qualified Data.Time as Time
import Lupo.Import
data Navigation m = Navigation
{ _getNextDay :: m (Maybe Time.Day)
, _getPreviousDay :: m (Maybe Time.Day)
, _getThisMonth :: Time.Day
, _getNextPageTop :: Integer -> m (Maybe Time.Day)
, _getPreviousPageTop :: Integer -> m (Maybe Time.Day)
, _getNextMonth :: m (Maybe Time.Day)
, _getPreviousMonth :: m (Maybe Time.Day)
}
getNextDay :: Action m (Navigation m) (Maybe Time.Day)
getNextDay = act _getNextDay
getPreviousDay :: Action m (Navigation m) (Maybe Time.Day)
getPreviousDay = act _getPreviousDay
getThisMonth :: Getter (Navigation m) Time.Day
getThisMonth = to _getThisMonth
getNextPageTop :: Integer -> Action m (Navigation m) (Maybe Time.Day)
getNextPageTop n = act $ \self ->
_getNextPageTop self n
getPreviousPageTop :: Integer -> Action m (Navigation m) (Maybe Time.Day)
getPreviousPageTop n = act $ \self ->
_getPreviousPageTop self n
getNextMonth :: Action m (Navigation m) (Maybe Time.Day)
getNextMonth = act _getNextMonth
getPreviousMonth :: Action m (Navigation m) (Maybe Time.Day)
getPreviousMonth = act _getPreviousMonth
| keitax/lupo | src/Lupo/Navigation.hs | lgpl-3.0 | 1,153 | 0 | 13 | 188 | 413 | 215 | 198 | 27 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Haskoin.Script.SigHash
Copyright : No rights reserved
License : MIT
Maintainer : jprupp@protonmail.ch
Stability : experimental
Portability : POSIX
Transaction signatures and related functions.
-}
module Haskoin.Script.SigHash
( -- * Script Signatures
SigHash(..)
, SigHashFlag(..)
, sigHashAll
, sigHashNone
, sigHashSingle
, hasAnyoneCanPayFlag
, hasForkIdFlag
, setAnyoneCanPayFlag
, setForkIdFlag
, isSigHashAll
, isSigHashNone
, isSigHashSingle
, isSigHashUnknown
, sigHashAddForkId
, sigHashGetForkId
, sigHashAddNetworkId
, txSigHash
, txSigHashForkId
, TxSignature(..)
, encodeTxSig
, decodeTxSig
) where
import Control.DeepSeq
import Control.Monad
import qualified Data.Aeson as J
import Data.Bits
import qualified Data.ByteString as BS
import Data.Bytes.Get
import Data.Bytes.Put
import Data.Bytes.Serial
import Data.Hashable
import Data.Maybe
import Data.Scientific
import Data.Word
import GHC.Generics (Generic)
import Haskoin.Constants
import Haskoin.Crypto
import Haskoin.Crypto.Hash
import Haskoin.Network.Common
import Haskoin.Script.Common
import Haskoin.Transaction.Common
import Haskoin.Util
-- | Constant representing a SIGHASH flag that controls what is being signed.
data SigHashFlag
= SIGHASH_ALL
-- ^ sign all outputs
| SIGHASH_NONE
-- ^ sign no outputs
| SIGHASH_SINGLE
-- ^ sign the output index corresponding to the input
| SIGHASH_FORKID
-- ^ replay protection for Bitcoin Cash transactions
| SIGHASH_ANYONECANPAY
-- ^ new inputs can be added
deriving (Eq, Ord, Show, Read, Generic)
instance NFData SigHashFlag
instance Hashable SigHashFlag
instance Enum SigHashFlag where
fromEnum SIGHASH_ALL = 0x01
fromEnum SIGHASH_NONE = 0x02
fromEnum SIGHASH_SINGLE = 0x03
fromEnum SIGHASH_FORKID = 0x40
fromEnum SIGHASH_ANYONECANPAY = 0x80
toEnum 0x01 = SIGHASH_ALL
toEnum 0x02 = SIGHASH_NONE
toEnum 0x03 = SIGHASH_SINGLE
toEnum 0x40 = SIGHASH_FORKID
toEnum 0x80 = SIGHASH_ANYONECANPAY
toEnum _ = error "Not a valid sighash flag"
-- | Data type representing the different ways a transaction can be signed.
-- When producing a signature, a hash of the transaction is used as the message
-- to be signed. The 'SigHash' parameter controls which parts of the
-- transaction are used or ignored to produce the transaction hash. The idea is
-- that if some part of a transaction is not used to produce the transaction
-- hash, then you can change that part of the transaction after producing a
-- signature without invalidating that signature.
--
-- If the 'SIGHASH_ANYONECANPAY' flag is set (true), then only the current input
-- is signed. Otherwise, all of the inputs of a transaction are signed. The
-- default value for 'SIGHASH_ANYONECANPAY' is unset (false).
newtype SigHash =
SigHash Word32
deriving ( Eq
, Ord
, Bits
, Enum
, Integral
, Num
, Real
, Show
, Read
, Generic
, Hashable
, NFData
)
instance J.FromJSON SigHash where
parseJSON =
J.withScientific "sighash" $
maybe mzero (return . SigHash) . toBoundedInteger
instance J.ToJSON SigHash where
toJSON = J.Number . fromIntegral
toEncoding (SigHash n) = J.toEncoding n
-- | SIGHASH_NONE as a byte.
sigHashNone :: SigHash
sigHashNone = fromIntegral $ fromEnum SIGHASH_NONE
-- | SIGHASH_ALL as a byte.
sigHashAll :: SigHash
sigHashAll = fromIntegral $ fromEnum SIGHASH_ALL
-- | SIGHASH_SINGLE as a byte.
sigHashSingle :: SigHash
sigHashSingle = fromIntegral $ fromEnum SIGHASH_SINGLE
-- | SIGHASH_FORKID as a byte.
sigHashForkId :: SigHash
sigHashForkId = fromIntegral $ fromEnum SIGHASH_FORKID
-- | SIGHASH_ANYONECANPAY as a byte.
sigHashAnyoneCanPay :: SigHash
sigHashAnyoneCanPay = fromIntegral $ fromEnum SIGHASH_ANYONECANPAY
-- | Set SIGHASH_FORKID flag.
setForkIdFlag :: SigHash -> SigHash
setForkIdFlag = (.|. sigHashForkId)
-- | Set SIGHASH_ANYONECANPAY flag.
setAnyoneCanPayFlag :: SigHash -> SigHash
setAnyoneCanPayFlag = (.|. sigHashAnyoneCanPay)
-- | Is the SIGHASH_FORKID flag set?
hasForkIdFlag :: SigHash -> Bool
hasForkIdFlag = (/= 0) . (.&. sigHashForkId)
-- | Is the SIGHASH_ANYONECANPAY flag set?
hasAnyoneCanPayFlag :: SigHash -> Bool
hasAnyoneCanPayFlag = (/= 0) . (.&. sigHashAnyoneCanPay)
-- | Returns 'True' if the 'SigHash' has the value 'SIGHASH_ALL'.
isSigHashAll :: SigHash -> Bool
isSigHashAll = (== sigHashAll) . (.&. 0x1f)
-- | Returns 'True' if the 'SigHash' has the value 'SIGHASH_NONE'.
isSigHashNone :: SigHash -> Bool
isSigHashNone = (== sigHashNone) . (.&. 0x1f)
-- | Returns 'True' if the 'SigHash' has the value 'SIGHASH_SINGLE'.
isSigHashSingle :: SigHash -> Bool
isSigHashSingle = (== sigHashSingle) . (.&. 0x1f)
-- | Returns 'True' if the 'SigHash' has the value 'SIGHASH_UNKNOWN'.
isSigHashUnknown :: SigHash -> Bool
isSigHashUnknown =
(`notElem` [sigHashAll, sigHashNone, sigHashSingle]) . (.&. 0x1f)
-- | Add a fork id to a 'SigHash'.
sigHashAddForkId :: SigHash -> Word32 -> SigHash
sigHashAddForkId sh w = (fromIntegral w `shiftL` 8) .|. (sh .&. 0x000000ff)
-- | Add fork id of a particular network to a 'SigHash'.
sigHashAddNetworkId :: Network -> SigHash -> SigHash
sigHashAddNetworkId net =
(`sigHashAddForkId` fromMaybe 0 (getSigHashForkId net))
-- | Get fork id from 'SigHash'.
sigHashGetForkId :: SigHash -> Word32
sigHashGetForkId (SigHash n) = fromIntegral $ n `shiftR` 8
-- | Computes the hash that will be used for signing a transaction.
txSigHash :: Network
-> Tx -- ^ transaction to sign
-> Script -- ^ script from output being spent
-> Word64 -- ^ value of output being spent
-> Int -- ^ index of input being signed
-> SigHash -- ^ what to sign
-> Hash256 -- ^ hash to be signed
txSigHash net tx out v i sh
| hasForkIdFlag sh && isJust (getSigHashForkId net) =
txSigHashForkId net tx out v i sh
| otherwise = do
let newIn = buildInputs (txIn tx) fout i sh
-- When SigSingle and input index > outputs, then sign integer 1
fromMaybe one $ do
newOut <- buildOutputs (txOut tx) i sh
let newTx = Tx (txVersion tx) newIn newOut [] (txLockTime tx)
return $
doubleSHA256 $
runPutS $ do
serialize newTx
putWord32le $ fromIntegral sh
where
fout = Script $ filter (/= OP_CODESEPARATOR) $ scriptOps out
one = "0100000000000000000000000000000000000000000000000000000000000000"
-- | Build transaction inputs for computing sighashes.
buildInputs :: [TxIn] -> Script -> Int -> SigHash -> [TxIn]
buildInputs txins out i sh
| hasAnyoneCanPayFlag sh =
[ (txins !! i) { scriptInput = runPutS $ serialize out } ]
| isSigHashAll sh || isSigHashUnknown sh = single
| otherwise = zipWith noSeq single [0 ..]
where
emptyIn = map (\ti -> ti { scriptInput = BS.empty }) txins
single =
updateIndex i emptyIn $ \ti -> ti { scriptInput = runPutS $ serialize out }
noSeq ti j =
if i == j
then ti
else ti { txInSequence = 0 }
-- | Build transaction outputs for computing sighashes.
buildOutputs :: [TxOut] -> Int -> SigHash -> Maybe [TxOut]
buildOutputs txos i sh
| isSigHashAll sh || isSigHashUnknown sh = return txos
| isSigHashNone sh = return []
| i >= length txos = Nothing
| otherwise = return $ buffer ++ [txos !! i]
where
buffer = replicate i $ TxOut maxBound BS.empty
-- | Compute the hash that will be used for signing a transaction. This
-- function is used when the 'SIGHASH_FORKID' flag is set.
txSigHashForkId
:: Network
-> Tx -- ^ transaction to sign
-> Script -- ^ script from output being spent
-> Word64 -- ^ value of output being spent
-> Int -- ^ index of input being signed
-> SigHash -- ^ what to sign
-> Hash256 -- ^ hash to be signed
txSigHashForkId net tx out v i sh =
doubleSHA256 . runPutS $ do
putWord32le $ txVersion tx
serialize hashPrevouts
serialize hashSequence
serialize $ prevOutput $ txIn tx !! i
putScript out
putWord64le v
putWord32le $ txInSequence $ txIn tx !! i
serialize hashOutputs
putWord32le $ txLockTime tx
putWord32le $ fromIntegral $ sigHashAddNetworkId net sh
where
hashPrevouts
| not $ hasAnyoneCanPayFlag sh =
doubleSHA256 $ runPutS $ mapM_ (serialize . prevOutput) $ txIn tx
| otherwise = zeros
hashSequence
| not (hasAnyoneCanPayFlag sh) &&
not (isSigHashSingle sh) && not (isSigHashNone sh) =
doubleSHA256 $ runPutS $ mapM_ (putWord32le . txInSequence) $ txIn tx
| otherwise = zeros
hashOutputs
| not (isSigHashSingle sh) && not (isSigHashNone sh) =
doubleSHA256 $ runPutS $ mapM_ serialize $ txOut tx
| isSigHashSingle sh && i < length (txOut tx) =
doubleSHA256 $ runPutS $ serialize $ txOut tx !! i
| otherwise = zeros
putScript s = do
let encodedScript = runPutS $ serialize s
putVarInt $ BS.length encodedScript
putByteString encodedScript
zeros :: Hash256
zeros = "0000000000000000000000000000000000000000000000000000000000000000"
-- | Data type representing a signature together with a 'SigHash'. The 'SigHash'
-- is serialized as one byte at the end of an ECDSA 'Sig'. All signatures in
-- transaction inputs are of type 'TxSignature'.
data TxSignature
= TxSignature
{ txSignature :: !Sig
, txSignatureSigHash :: !SigHash
}
| TxSignatureEmpty
deriving (Eq, Show, Generic)
instance NFData TxSignature
-- | Serialize a 'TxSignature'.
encodeTxSig :: TxSignature -> BS.ByteString
encodeTxSig TxSignatureEmpty = error "Can not encode an empty signature"
encodeTxSig (TxSignature sig (SigHash n)) =
runPutS $ putSig sig >> putWord8 (fromIntegral n)
-- | Deserialize a 'TxSignature'.
decodeTxSig :: Network -> BS.ByteString -> Either String TxSignature
decodeTxSig _ bs | BS.null bs = Left "Empty signature candidate"
decodeTxSig net bs =
case decodeStrictSig $ BS.init bs of
Just sig -> do
let sh = fromIntegral $ BS.last bs
when (isSigHashUnknown sh) $
Left "Non-canonical signature: unknown hashtype byte"
when (isNothing (getSigHashForkId net) && hasForkIdFlag sh) $
Left "Non-canonical signature: invalid network for forkId"
return $ TxSignature sig sh
Nothing -> Left "Non-canonical signature: could not parse signature"
| haskoin/haskoin | src/Haskoin/Script/SigHash.hs | unlicense | 11,281 | 0 | 16 | 2,989 | 2,274 | 1,198 | 1,076 | 232 | 2 |
module FractalFlame.Generator.Types.Generator where
import System.Random
type Generator a = StdGen -> (a, StdGen)
| anthezium/fractal_flame_renderer_haskell | FractalFlame/Generator/Types/Generator.hs | bsd-2-clause | 116 | 0 | 6 | 15 | 30 | 20 | 10 | 3 | 0 |
-- http://www.codewars.com/kata/55147ff29cd40b43c600058b
module Codewars.Kata.Catenation where
charConcat :: String -> String
charConcat word = concat $ zipWith3 (\a b c -> a:b:c) word (reverse word) ns where
ns = map show [1 .. length word `div` 2]
| Bodigrim/katas | src/haskell/7-Character-Concatenation.hs | bsd-2-clause | 253 | 0 | 10 | 39 | 91 | 50 | 41 | 4 | 1 |
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, GADTs #-}
module Model where
import Yesod
import Data.Text (Text)
import Database.Persist.MongoDB
import Language.Haskell.TH.Syntax
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [mkPersist MkPersistSettings { mpsBackend = ConT ''Action }, mkMigrate "migrateAll"] $(persistFile "config/models")
| konn/BottleStory | Model.hs | bsd-2-clause | 537 | 0 | 11 | 65 | 75 | 44 | 31 | 7 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Common
import Web.Twitter.Conduit
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.Environment
main :: IO ()
main = do
status <- T.concat . map T.pack <$> getArgs
T.putStrLn $ "Post message: " <> status
twInfo <- getTWInfoFromEnv
mgr <- newManager tlsManagerSettings
res <- call twInfo mgr $ statusesUpdate status
print res
| himura/twitter-conduit | sample/post.hs | bsd-2-clause | 444 | 0 | 11 | 90 | 128 | 67 | 61 | 15 | 1 |
module Data.Time.Convenience (
timeFor
,timeSince
,module Data.Time.Convenience.Data
) where
import Data.Time.Clock
import Control.Applicative ((<$>))
import Data.Time.Convenience.Data
import Data.Time.Convenience.Calculators
-- | Produce the time following the specified offset. For example, to get
-- the date and time from two weeks from right now:
--
-- > timeFor 1 Fortnight FromNow
timeFor :: NominalDiffTime -> Unit -> Direction -> IO UTCTime
timeFor n unit direction = do
currentTime <- getCurrentTime
return $ timeSince currentTime n unit direction
-- | Given a time, produce a new time offset from that time. For example,
-- to get the date and time from a month after two weeks ago:
--
-- > do
-- > twoWeeksAgo <- timeFor 1 Fortnight Ago
-- > return $ timeSince twoWeeksAgo 1 Month FromThat
timeSince :: UTCTime -> NominalDiffTime -> Unit -> Direction -> UTCTime
timeSince base n unit direction =
addUTCTime ((calculator unit) n direction) base
-- | Given a Unit, produce the function that takes a number and a direction and
-- produces the number of seconds to offset the current time.
calculator :: (Num i) => Unit -> (i -> Direction -> i)
calculator Second = seconds
calculator Seconds = seconds
calculator Minute = minutes
calculator Minutes = minutes
calculator Hour = hours
calculator Hours = hours
calculator Day = days
calculator Days = days
calculator Week = weeks
calculator Weeks = weeks
calculator Fortnight = fortnights
calculator Fortnights = fortnights
| mike-burns/timing-convenience | Data/Time/Convenience.hs | bsd-3-clause | 1,494 | 0 | 9 | 250 | 301 | 167 | 134 | 28 | 1 |
--
-- Adapted from the program "infer", believed to have been originally
-- authored by Philip Wadler, and used in the nofib benchmark suite
-- since at least the late 90s.
--
module InferMonad (Infer, returnI, eachI, thenI, guardI, useI, getSubI,
substituteI, unifyI, freshI, freshesI)
where
import MaybeM
import StateX (StateX, returnSX, eachSX, thenSX, toSX, putSX, getSX, useSX)
import Type
import Substitution
type Counter = Int
data Infer x = MkI (StateX Sub (StateX Counter (Maybe ((x, Sub), Counter))))
rep (MkI xJ) = xJ
returnI :: x -> Infer x
returnI x = MkI (returnSX (returnSX returnM) x)
eachI :: Infer x -> (x -> y) -> Infer y
xI `eachI` f = MkI (eachSX (eachSX eachM) (rep xI) f)
thenI :: Infer x -> (x -> Infer y) -> Infer y
xI `thenI` kI = MkI (thenSX (thenSX thenM) (rep xI) (rep . kI))
failI :: Infer x
failI = MkI (toSX (eachSX eachM) (toSX eachM failM))
useI :: x -> Infer x -> x
useI xfail = useM xfail
. useSX eachM 0
. useSX (eachSX eachM) emptySub
. rep
guardI :: Bool -> Infer x -> Infer x
guardI b xI = if b then xI else failI
putSubI :: Sub -> Infer ()
putSubI s = MkI (putSX (returnSX returnM) s)
getSubI :: Infer Sub
getSubI = MkI (getSX (returnSX returnM))
putCounterI :: Counter -> Infer ()
putCounterI c = MkI (toSX (eachSX eachM) (putSX returnM c))
getCounterI :: Infer Counter
getCounterI = MkI (toSX (eachSX eachM) (getSX returnM))
substituteI :: MonoType -> Infer MonoType
substituteI t = getSubI `thenI` (\ s ->
returnI (applySub s t))
unifyI :: MonoType -> MonoType -> Infer ()
unifyI t u = getSubI `thenI` (\ s ->
let sM = unifySub t u s
in
existsM sM `guardI` (
putSubI (theM sM) `thenI` (\ () ->
returnI ())))
freshI :: Infer MonoType
freshI = getCounterI `thenI` (\c ->
putCounterI (c+1) `thenI` (\() ->
returnI (TVar ("a" ++ show c))))
freshesI :: Int -> Infer [MonoType]
freshesI 0 = returnI []
freshesI n = freshI `thenI` (\x ->
freshesI (n-1) `thenI` (\xs ->
returnI (x:xs)))
instance Monad Infer where
return = returnI
(>>=) = thenI
instance Functor Infer where
fmap f x = x >>= return . f
| mono0926/ParallelConcurrentHaskell | parinfer/InferMonad.hs | bsd-3-clause | 2,979 | 2 | 16 | 1,319 | 952 | 507 | 445 | 55 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Servant.Tpl where
import Control.Lens
import qualified Data.ByteString.Char8 as BSC
import Data.Proxy
import Data.Typeable
import GHC.TypeLits
import Servant.API
import Servant.Server
import Servant.Server.Internal
import Servant.Server.Internal.SnapShims
import qualified Snap.Snaplet.Heist as Snaplet
import Heist.Interpreted
import Snap
data HTML deriving Typeable
data KnownSymbol a => Tpl (a :: Symbol)
deriving Typeable
instance Accept HTML where
contentType _ = "text/html; charset=utf-8"
instance (KnownSymbol a) => HasServer (Tpl a) where
type ServerT (Tpl sym) (Handler b v) = (Handler b v) ()
route Proxy rawApplication = LeafRouter $ \request respond -> do
r <- rawApplication
case r of
RR (Right rawApp) -> snapToApplication'' rawApp request
(respond . succeedWith)
RR (Left err) -> respond $ failWith err
class KnownSymbol a => Describe (f :: Symbol -> *) a where
describe :: Proxy (f sym) -> String
instance KnownSymbol sym => Describe Tpl sym where
describe _ = symbolVal (Proxy :: Proxy sym)
servantRender :: (Snaplet.HasHeist app, KnownSymbol sym, Tpl sym ~ Tpl userSym)
=> Proxy userSym
-> Server (Tpl userSym) (Handler app app)
servantRender p = do
let filename = symbolVal p
hs <- Snaplet.getHeistState
a <- renderTemplate hs (BSC.pack filename)
case a of
Just (x,_) -> writeBuilder x
Nothing -> pass
type MyTest = "template" :> Tpl "testp"
server :: Server MyTest (Handler App App)
server = servantRender (Proxy :: Proxy "testp")
myAPI :: Proxy MyTest
myAPI = Proxy
data App = App
{ _heist :: Snaplet (Snaplet.Heist App)}
makeLenses ''App
instance Snaplet.HasHeist App where heistLens = subSnaplet heist
appInit :: SnapletInit App App
appInit = makeSnaplet "app" "" Nothing $ do
h <- nestSnaplet "heist" heist $ Snaplet.heistInit "templates"
addRoutes [("api", server)]
return $ App h
type AppHandler = Handler App App
test :: IO ()
test = serveSnaplet mempty appInit
| imalsogreg/servant-heist | src/Servant/Tpl.hs | bsd-3-clause | 2,474 | 0 | 15 | 526 | 717 | 374 | 343 | -1 | -1 |
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is distributed under the terms of a BSD license,
-- found in the LICENSE file. An additional grant of patent rights can
-- be found in the PATENTS file.
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | A cache mapping data requests to their results.
module Haxl.Core.DataCache
( DataCache
, empty
, insert
, lookup
, showCache
) where
import Data.HashMap.Strict (HashMap)
import Data.Hashable
import Prelude hiding (lookup)
import Unsafe.Coerce
import qualified Data.HashMap.Strict as HashMap
import Data.Typeable.Internal
import Data.Maybe
import Control.Applicative hiding (empty)
import Control.Exception
import Haxl.Core.Types
-- | The 'DataCache' maps things of type @f a@ to @'ResultVar' a@, for
-- any @f@ and @a@ provided @f a@ is an instance of 'Typeable'. In
-- practice @f a@ will be a request type parameterised by its result.
--
-- See the definition of 'ResultVar' for more details.
newtype DataCache res = DataCache (HashMap TypeRep (SubCache res))
-- | The implementation is a two-level map: the outer level maps the
-- types of requests to 'SubCache', which maps actual requests to their
-- results. So each 'SubCache' contains requests of the same type.
-- This works well because we only have to store the dictionaries for
-- 'Hashable' and 'Eq' once per request type.
data SubCache res =
forall req a . (Hashable (req a), Eq (req a), Show (req a), Show a) =>
SubCache ! (HashMap (req a) (res a))
-- NB. the inner HashMap is strict, to avoid building up
-- a chain of thunks during repeated insertions.
-- | A new, empty 'DataCache'.
empty :: DataCache res
empty = DataCache HashMap.empty
-- | Inserts a request-result pair into the 'DataCache'.
insert
:: (Hashable (req a), Typeable (req a), Eq (req a), Show (req a), Show a)
=> req a
-- ^ Request
-> res a
-- ^ Result
-> DataCache res
-> DataCache res
insert req result (DataCache m) =
DataCache $
HashMap.insertWith fn (typeOf req)
(SubCache (HashMap.singleton req result)) m
where
fn (SubCache new) (SubCache old) =
SubCache (unsafeCoerce new `HashMap.union` old)
-- | Looks up the cached result of a request.
lookup
:: Typeable (req a)
=> req a
-- ^ Request
-> DataCache res
-> Maybe (res a)
lookup req (DataCache m) =
case HashMap.lookup (typeOf req) m of
Nothing -> Nothing
Just (SubCache sc) ->
unsafeCoerce (HashMap.lookup (unsafeCoerce req) sc)
-- | Dumps the contents of the cache, with requests and responses
-- converted to 'String's using 'show'. The entries are grouped by
-- 'TypeRep'.
--
showCache
:: DataCache ResultVar
-> IO [(TypeRep, [(String, Either SomeException String)])]
showCache (DataCache cache) = mapM goSubCache (HashMap.toList cache)
where
goSubCache
:: (TypeRep,SubCache ResultVar)
-> IO (TypeRep,[(String, Either SomeException String)])
goSubCache (ty, SubCache hmap) = do
elems <- catMaybes <$> mapM go (HashMap.toList hmap)
return (ty, elems)
go :: (Show (req a), Show a)
=> (req a, ResultVar a)
-> IO (Maybe (String, Either SomeException String))
go (req, rvar) = do
maybe_r <- tryReadResult rvar
case maybe_r of
Nothing -> return Nothing
Just (Left e) -> return (Just (show req, Left e))
Just (Right result) -> return (Just (show req, Right (show result)))
| kantp/Haxl | Haxl/Core/DataCache.hs | bsd-3-clause | 3,546 | 5 | 18 | 769 | 873 | 474 | 399 | 68 | 3 |
module AST.Term(
SortName(..),
VarName(..),
Name(..),
ContextDepth(..),
DefaultErr(..),
Sort(..),
Ctx(..),
FunctionalSymbol(..),
MetaVar(..),
Term(..),
isMeta,
unMeta,
varSort,
tyName,
tmName,
getSortName,
getSortDepth,
addToCtx,
lowerCtx,
zero,
isDepSort,
lookupName,
lookupName',
isFunSym,
isVar,
identicalMV,
allUnique,
isSubset,
toListM,
changeError,
Stab,
deStab,
addStab
) where
import qualified Data.Set as Set
import Data.List(intercalate, sort)
type SortName = String
type VarName = String
type Name = String
type ContextDepth = Int
type DefaultErr = Either String
-- Nothing - means stable
-- else stable only for x in (Just x)
type Stab = Maybe [Term]
changeError :: String -> DefaultErr a -> DefaultErr a
changeError msg (Left x) = Left (msg ++ "\n\t" ++ x)
changeError _ x = x
data Sort = DepSort SortName !ContextDepth | SimpleSort SortName
deriving (Eq)
type Ctx = [VarName]
bracket :: String -> String
bracket s = "(" ++ s ++ ")"
instance Show Sort where
show (DepSort nm dp) = bracket $ nm ++ "," ++ show dp
show (SimpleSort nm) = nm
varSort :: Sort
varSort = DepSort tmName 0
tyName :: SortName
tyName = "ty"
tmName :: SortName
tmName = "tm"
getSortName :: Sort -> SortName
getSortName (DepSort nm _) = nm
getSortName (SimpleSort nm) = nm
getSortDepth :: Sort -> ContextDepth
getSortDepth (SimpleSort _) = 0
getSortDepth (DepSort _ x) = x
zero :: Sort -> Sort
zero (DepSort nm _) = DepSort nm 0
zero x = x
addToCtx :: ContextDepth -> Sort -> DefaultErr Sort
addToCtx _ (SimpleSort _) = Left "Simple sorts can't have context"
addToCtx n (DepSort nm num) | num + n >= 0 = return (DepSort nm $ num + n)
| otherwise = Left "Context is empty already"
lowerCtx :: Sort -> DefaultErr Sort
lowerCtx = addToCtx (-1)
isDepSort :: Sort -> Bool
isDepSort (DepSort _ _) = True
isDepSort _ = False
data FunctionalSymbol = FunSym {
name :: Name
, arguments :: [Sort]
, result :: Sort --- hack in the parser that gets solved in the checking stage
} deriving (Eq)
instance Show FunctionalSymbol where
show (FunSym nm [] res) = nm ++ ": " ++ show res
show (FunSym nm args res) =
nm ++ ": " ++ intercalate "*" (map show args) ++ "->" ++ show res
data MetaVar = MetaVar {
mContext :: [VarName]
, mName :: VarName
}
instance Eq MetaVar where
m == m' = (mName m) == (mName m')
identicalMV :: MetaVar -> MetaVar -> Bool
identicalMV (MetaVar ct1 vn1) (MetaVar ct2 vn2) = (sort ct1) == (sort ct2) && vn1 == vn2
instance Ord MetaVar where
m `compare` m' = (mName m) `compare` (mName m')
showCtxVar :: [Name] -> String -> String
showCtxVar [] y = y
showCtxVar [x] y = x ++ "." ++ y
showCtxVar args y = bracket (unwords args) ++ "." ++ y
instance Show MetaVar where
show (MetaVar x y) = showCtxVar x y
data Term = Var VarName -- xyz
| Meta MetaVar
| FunApp Name [(Ctx, Term)]
| Subst Term VarName Term
deriving (Eq)
toListM :: Term -> [MetaVar]
toListM (Var _) = []
toListM (Meta mv) = [mv]
toListM (Subst tm1 _ tm2) = toListM tm1 ++ toListM tm2
toListM (FunApp _ lst) = concat (toListM . snd <$> lst)
isMeta :: Term -> Bool
isMeta (Meta _) = True
isMeta _ = False
unMeta :: Term -> MetaVar
unMeta (Meta mv) = mv
instance Show Term where
show (Var nm) = nm
show (Meta vr) = mName vr ++ "-m"
show (FunApp nm []) = nm ++ "-f"
show (FunApp nm args) = nm ++ bracket (intercalate ", " (map (\(x, y) -> showCtxVar x (show y)) args))
show (Subst into vn what) = show into ++ "[" ++ vn ++ ":= " ++ show what ++ "]"
isFunSym :: Term -> Bool
isFunSym FunApp{} = True
isFunSym _ = False
isVar :: Term -> Bool
isVar Var{} = True
isVar _ = False
lookupName :: (a -> Name) -> Name -> [a] -> DefaultErr a
lookupName f = lookupName' (\x y -> f x == y)
-- f : tm + name = equal?
lookupName' :: (a -> Name -> Bool) -> Name -> [a] -> DefaultErr a
lookupName' idf name (x : xs) | idf x name = return x
| otherwise = lookupName' idf name xs
lookupName' _ name _ = Left $ "Name " ++ show name ++ " not found!"
allUnique :: Ord a => [a] -> Bool
allUnique a = length a == Set.size (Set.fromList a)
isSubset :: Ord a => [a] -> [a] -> Bool
isSubset a b = 0 == Set.size (Set.difference (Set.fromList a) (Set.fromList b))
deStab :: Stab -> Stab
deStab Nothing = Just []
deStab x = x
addStab :: Stab -> Stab -> Stab
addStab x Nothing = x
addStab Nothing x = x
addStab (Just x) (Just y) = Just (x ++ y)
--
| esengie/fpl-exploration-tool | src/specLang/AST/Term.hs | bsd-3-clause | 4,499 | 0 | 16 | 1,045 | 1,901 | 1,007 | 894 | 147 | 1 |
{-# LANGUAGE BangPatterns #-}
module Data.UnorderedMap
(
UnorderedMap
, empty
, emptySized
, insert
, lookup
, delete
, size
, foldM
, foldM'
, toList
, fromList
) where
import Control.Monad hiding (foldM)
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as Bi
import Data.IORef
import Data.Serialize
import Data.UnorderedMap.Internal
import Foreign hiding (unsafeForeignPtrToPtr)
import Prelude hiding (lookup)
-- data UnorderedMap k v = UM {-# UNPACK #-} !UnorderedMap_
data UnorderedMap k v = UM {-# UNPACK #-} !(ForeignPtr UMO)
empty :: IO (UnorderedMap k v)
empty = hashmap_create >>= liftM UM . newForeignPtr hashmap_destroy
emptySized :: Int -> IO (UnorderedMap k v)
emptySized s = hashmap_create_sized (fromIntegral s) >>= liftM UM . newForeignPtr hashmap_destroy
insertB :: ForeignPtr UMO -> B.ByteString -> B.ByteString -> IO ()
insertB umap0 (Bi.PS key0 offK lenK) (Bi.PS val0 offV lenV) =
withForeignPtr umap0 $ \umap ->
withForeignPtr key0 $ \key ->
withForeignPtr val0 $ \val ->
hashmap_insert umap (key `plusPtr` offK) (fromIntegral lenK) (val `plusPtr` offV) (fromIntegral lenV)
lookupB :: ForeignPtr UMO -> B.ByteString -> IO (Maybe B.ByteString)
lookupB umap0 (Bi.PS key0 offK lenK) =
withForeignPtr umap0 $ \umap ->
withForeignPtr key0 $ \key ->
with 0 $ \pNV ->
with nullPtr $ \ppVal -> do
hashmap_lookup umap (key `plusPtr` offK) (fromIntegral lenK) ppVal pNV
nV <- peek pNV
if nV == 0
then return Nothing
else do pVal <- peek ppVal
liftM Just $ Bi.create (fromIntegral nV) (\dst -> copyBytes dst pVal (fromIntegral nV))
deleteB :: ForeignPtr UMO -> B.ByteString -> IO ()
deleteB umap0 (Bi.PS key0 offK lenK) =
withForeignPtr umap0 $ \umap ->
withForeignPtr key0 $ \key ->
hashmap_delete umap (key `plusPtr` offK) (fromIntegral lenK)
foldMB :: (a -> (B.ByteString, B.ByteString) -> IO a) -> a -> ForeignPtr UMO -> IO a
foldMB f acc0 umap0 = withForeignPtr umap0 $ \umap -> do
acc <- newIORef acc0
it <- iter_create umap
loop umap it acc
iter_destroy it
readIORef acc
where
loop umap it acc = do
hasNext <- iter_hasNext umap it
if not hasNext
then return ()
else do
with 2 $ \pNK -> with 2 $ \pNV ->
with nullPtr $ \ppKey -> with nullPtr $ \ppVal -> do
iter_next umap it ppKey pNK ppVal pNV
nK <- peek pNK
nV <- peek pNV
pKey <- peek ppKey
pVal <- peek ppVal
key <- Bi.create (fromIntegral nK) (\dst -> copyBytes dst pKey (fromIntegral nK))
val <- Bi.create (fromIntegral nV) (\dst -> copyBytes dst pVal (fromIntegral nV))
readIORef acc >>= (`f` (key, val)) >>= (writeIORef acc)
loop umap it acc
insert :: (Serialize k, Serialize v) => UnorderedMap k v -> k -> v -> IO ()
insert (UM umap) key val = insertB umap (encode key) (encode val)
lookup :: (Serialize k, Serialize v) => UnorderedMap k v -> k -> IO (Maybe v)
lookup (UM umap) key = do
res <- lookupB umap (encode key)
case res of
Nothing -> return Nothing
Just val -> either (const (return Nothing)) (return . Just) (decode val)
delete :: (Serialize k) => UnorderedMap k v -> k -> IO ()
delete (UM umap) key = deleteB umap (encode key)
size :: (Integral a) => UnorderedMap k v -> IO a
size (UM umap0) = withForeignPtr umap0 $ \umap -> liftM fromIntegral (hashmap_size umap)
foldM :: (Serialize k, Serialize v) => (a -> (k, v) -> IO a) -> a -> UnorderedMap k v -> IO a
foldM f acc (UM umap) = foldMB f' acc umap
where f' a (k, v) = f a (right . decode $ k, right . decode $ v)
right (Right x) = x
right _ = error "cereal decode failed."
foldM' :: (Serialize k, Serialize v) => (a -> (k, v) -> IO a) -> a -> UnorderedMap k v -> IO a
foldM' f = foldM (\ !a -> f a)
toList :: (Serialize k, Serialize v) => UnorderedMap k v -> IO [(k, v)]
toList = foldM f []
where f list entry = return (entry:list)
fromList :: (Serialize k, Serialize v) => [(k, v)] -> IO (UnorderedMap k v)
fromList list = do
um <- empty
mapM_ (uncurry (insert um)) list
return um
| comatose/stl-container | src/Data/UnorderedMap.hs | bsd-3-clause | 4,383 | 0 | 28 | 1,220 | 1,774 | 892 | 882 | 100 | 2 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Fragment.TmApp (
module X
, TmAppTag
) where
import GHC.Exts (Constraint)
import Ast
import Rules.Type
import Rules.Type.Infer.Common
import Rules.Term
import Fragment.TmApp.Ast as X
import Fragment.TmApp.Helpers as X
import Fragment.TyArr.Ast.Type
import Fragment.TyArr.Ast.Error
import Fragment.TmApp.Rules.Type.Infer.Common
import Fragment.TmApp.Rules.Term
data TmAppTag
instance AstIn TmAppTag where
type KindList TmAppTag = '[]
type TypeList TmAppTag = '[TyFArr]
type TypeSchemeList TmAppTag = '[]
type PatternList TmAppTag = '[]
type TermList TmAppTag = '[TmFApp]
instance EvalRules EStrict TmAppTag where
type EvalConstraint ki ty pt tm a EStrict TmAppTag =
TmAppEvalConstraint ki ty pt tm a
evalInput _ _ =
tmAppEvalRulesStrict
instance EvalRules ELazy TmAppTag where
type EvalConstraint ki ty pt tm a ELazy TmAppTag =
TmAppEvalConstraint ki ty pt tm a
evalInput _ _ =
tmAppEvalRulesLazy
instance NormalizeRules TmAppTag where
type NormalizeConstraint ki ty a TmAppTag =
(() :: Constraint)
normalizeInput _ =
mempty
instance MkInferType i => InferTypeRules i TmAppTag where
type InferTypeConstraint e w s r m ki ty pt tm a i TmAppTag =
TmAppInferTypeConstraint e w s r m ki ty pt tm a i
type InferTypeErrorList ki ty pt tm a i TmAppTag =
'[ ErrExpectedTyArr ki ty a ]
type InferTypeWarningList ki ty pt tm a i TmAppTag =
'[]
inferTypeInput m i _ =
tmAppInferTypeInput m i
| dalaing/type-systems | src/Fragment/TmApp.hs | bsd-3-clause | 1,764 | 1 | 8 | 345 | 465 | 257 | 208 | -1 | -1 |
{-
Bitwise.hs, bitwise operations.
There are many other bitwise operations implemented
in for example Exp.hs that should probably be moved here.
Joel Svensson
Last Edited: 13 Mar 2009 (Friday the 13th)
-}
module Obsidian.ArrowObsidian.Bitwise where
import Obsidian.ArrowObsidian.Exp
import Data.Bits
-- rotLocalL rotates a subword 1 bit left
rotLocalL :: Bits a => a -> Int -> a
rotLocalL a bits= (a `shiftR` 1) .|. (b `shiftL` (bits - 1))
where
b = (a .&. 1) -- is bit 1 set ?
rotLocalR :: Bits a => a -> Int -> a
rotLocalR a bits = (a') .|. (b `shiftR` (bits - 1))
where
b = a .&. (fromIntegral (shiftL (1::Int) (bits - 1)))
a' = (a `shiftL` 1) .&. max
max = fromIntegral ((2^bits) - 1)
-- bit = fromIntegral (2^(bits-1))
-- bit = fromIntegral (2^(bits-1))
--------------------------------------------------------------------------------
{- Unsigned Integers -}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
{- signed Integers -}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
{- signed/unsigned Integers -}
--------------------------------------------------------------------------------
| svenssonjoel/ArrowObsidian | Obsidian/ArrowObsidian/Bitwise.hs | bsd-3-clause | 1,407 | 0 | 13 | 238 | 236 | 140 | 96 | 11 | 1 |
-----------------------------------------------------------------------------
--
-- Stg to C-- code generation:
--
-- The types LambdaFormInfo
-- ClosureInfo
--
-- Nothing monadic in here!
--
-----------------------------------------------------------------------------
{-# LANGUAGE RecordWildCards #-}
module StgCmmClosure (
DynTag, tagForCon, isSmallFamily,
ConTagZ, dataConTagZ,
idPrimRep, isVoidRep, isGcPtrRep, addIdReps, addArgReps,
argPrimRep,
-- * LambdaFormInfo
LambdaFormInfo, -- Abstract
StandardFormInfo, -- ...ditto...
mkLFThunk, mkLFReEntrant, mkConLFInfo, mkSelectorLFInfo,
mkApLFInfo, mkLFImported, mkLFArgument, mkLFLetNoEscape,
mkLFBlackHole,
lfDynTag,
maybeIsLFCon, isLFThunk, isLFReEntrant, lfUpdatable,
-- * Used by other modules
CgLoc(..), SelfLoopInfo, CallMethod(..),
nodeMustPointToIt, isKnownFun, funTag, tagForArity, getCallMethod,
-- * ClosureInfo
ClosureInfo,
mkClosureInfo,
mkCmmInfo,
-- ** Inspection
closureLFInfo, closureName,
-- ** Labels
-- These just need the info table label
closureInfoLabel, staticClosureLabel,
closureSlowEntryLabel, closureLocalEntryLabel,
-- ** Predicates
-- These are really just functions on LambdaFormInfo
closureUpdReqd, closureSingleEntry,
closureReEntrant, closureFunInfo,
isToplevClosure,
blackHoleOnEntry, -- Needs LambdaFormInfo and SMRep
isStaticClosure, -- Needs SMPre
-- * InfoTables
mkDataConInfoTable,
cafBlackHoleInfoTable,
indStaticInfoTable,
staticClosureNeedsLink,
) where
#include "../includes/MachDeps.h"
#define FAST_STRING_NOT_NEEDED
#include "HsVersions.h"
import StgSyn
import SMRep
import Cmm
import PprCmmExpr()
import BlockId
import CLabel
import Id
import IdInfo
import DataCon
import FastString
import Name
import Type
import TypeRep
import TcType
import TyCon
import BasicTypes
import Outputable
import DynFlags
import Util
-----------------------------------------------------------------------------
-- Data types and synonyms
-----------------------------------------------------------------------------
-- These data types are mostly used by other modules, especially StgCmmMonad,
-- but we define them here because some functions in this module need to
-- have access to them as well
data CgLoc
= CmmLoc CmmExpr -- A stable CmmExpr; that is, one not mentioning
-- Hp, so that it remains valid across calls
| LneLoc BlockId [LocalReg] -- A join point
-- A join point (= let-no-escape) should only
-- be tail-called, and in a saturated way.
-- To tail-call it, assign to these locals,
-- and branch to the block id
instance Outputable CgLoc where
ppr (CmmLoc e) = ptext (sLit "cmm") <+> ppr e
ppr (LneLoc b rs) = ptext (sLit "lne") <+> ppr b <+> ppr rs
type SelfLoopInfo = (Id, BlockId, [LocalReg])
-- used by ticky profiling
isKnownFun :: LambdaFormInfo -> Bool
isKnownFun (LFReEntrant _ _ _ _) = True
isKnownFun LFLetNoEscape = True
isKnownFun _ = False
-----------------------------------------------------------------------------
-- Representations
-----------------------------------------------------------------------------
-- Why are these here?
-- NB: this is reliable because by StgCmm no Ids have unboxed tuple type
idPrimRep :: Id -> PrimRep
idPrimRep id = typePrimRep (idType id)
addIdReps :: [Id] -> [(PrimRep, Id)]
addIdReps ids = [(idPrimRep id, id) | id <- ids]
addArgReps :: [StgArg] -> [(PrimRep, StgArg)]
addArgReps args = [(argPrimRep arg, arg) | arg <- args]
argPrimRep :: StgArg -> PrimRep
argPrimRep arg = typePrimRep (stgArgType arg)
isVoidRep :: PrimRep -> Bool
isVoidRep VoidRep = True
isVoidRep _other = False
isGcPtrRep :: PrimRep -> Bool
isGcPtrRep PtrRep = True
isGcPtrRep _ = False
-----------------------------------------------------------------------------
-- LambdaFormInfo
-----------------------------------------------------------------------------
-- Information about an identifier, from the code generator's point of
-- view. Every identifier is bound to a LambdaFormInfo in the
-- environment, which gives the code generator enough info to be able to
-- tail call or return that identifier.
data LambdaFormInfo
= LFReEntrant -- Reentrant closure (a function)
TopLevelFlag -- True if top level
!RepArity -- Arity. Invariant: always > 0
!Bool -- True <=> no fvs
ArgDescr -- Argument descriptor (should really be in ClosureInfo)
| LFThunk -- Thunk (zero arity)
TopLevelFlag
!Bool -- True <=> no free vars
!Bool -- True <=> updatable (i.e., *not* single-entry)
StandardFormInfo
!Bool -- True <=> *might* be a function type
| LFCon -- A saturated constructor application
DataCon -- The constructor
| LFUnknown -- Used for function arguments and imported things.
-- We know nothing about this closure.
-- Treat like updatable "LFThunk"...
-- Imported things which we *do* know something about use
-- one of the other LF constructors (eg LFReEntrant for
-- known functions)
!Bool -- True <=> *might* be a function type
-- The False case is good when we want to enter it,
-- because then we know the entry code will do
-- For a function, the entry code is the fast entry point
| LFUnLifted -- A value of unboxed type;
-- always a value, needs evaluation
| LFLetNoEscape -- See LetNoEscape module for precise description
| LFBlackHole -- Used for the closures allocated to hold the result
-- of a CAF. We want the target of the update frame to
-- be in the heap, so we make a black hole to hold it.
-- XXX we can very nearly get rid of this, but
-- allocDynClosure needs a LambdaFormInfo
-------------------------
-- StandardFormInfo tells whether this thunk has one of
-- a small number of standard forms
data StandardFormInfo
= NonStandardThunk
-- The usual case: not of the standard forms
| SelectorThunk
-- A SelectorThunk is of form
-- case x of
-- con a1,..,an -> ak
-- and the constructor is from a single-constr type.
WordOff -- 0-origin offset of ak within the "goods" of
-- constructor (Recall that the a1,...,an may be laid
-- out in the heap in a non-obvious order.)
| ApThunk
-- An ApThunk is of form
-- x1 ... xn
-- The code for the thunk just pushes x2..xn on the stack and enters x1.
-- There are a few of these (for 1 <= n <= MAX_SPEC_AP_SIZE) pre-compiled
-- in the RTS to save space.
RepArity -- Arity, n
------------------------------------------------------
-- Building LambdaFormInfo
------------------------------------------------------
mkLFArgument :: Id -> LambdaFormInfo
mkLFArgument id
| isUnLiftedType ty = LFUnLifted
| might_be_a_function ty = LFUnknown True
| otherwise = LFUnknown False
where
ty = idType id
-------------
mkLFLetNoEscape :: LambdaFormInfo
mkLFLetNoEscape = LFLetNoEscape
-------------
mkLFReEntrant :: TopLevelFlag -- True of top level
-> [Id] -- Free vars
-> [Id] -- Args
-> ArgDescr -- Argument descriptor
-> LambdaFormInfo
mkLFReEntrant top fvs args arg_descr
= LFReEntrant top (length args) (null fvs) arg_descr
-------------
mkLFThunk :: Type -> TopLevelFlag -> [Id] -> UpdateFlag -> LambdaFormInfo
mkLFThunk thunk_ty top fvs upd_flag
= ASSERT( not (isUpdatable upd_flag) || not (isUnLiftedType thunk_ty) )
LFThunk top (null fvs)
(isUpdatable upd_flag)
NonStandardThunk
(might_be_a_function thunk_ty)
--------------
might_be_a_function :: Type -> Bool
-- Return False only if we are *sure* it's a data type
-- Look through newtypes etc as much as poss
might_be_a_function ty
| UnaryRep rep <- repType ty
, Just tc <- tyConAppTyCon_maybe rep
, isDataTyCon tc
= False
| otherwise
= True
-------------
mkConLFInfo :: DataCon -> LambdaFormInfo
mkConLFInfo con = LFCon con
-------------
mkSelectorLFInfo :: Id -> Int -> Bool -> LambdaFormInfo
mkSelectorLFInfo id offset updatable
= LFThunk NotTopLevel False updatable (SelectorThunk offset)
(might_be_a_function (idType id))
-------------
mkApLFInfo :: Id -> UpdateFlag -> Arity -> LambdaFormInfo
mkApLFInfo id upd_flag arity
= LFThunk NotTopLevel (arity == 0) (isUpdatable upd_flag) (ApThunk arity)
(might_be_a_function (idType id))
-------------
mkLFImported :: Id -> LambdaFormInfo
mkLFImported id
| Just con <- isDataConWorkId_maybe id
, isNullaryRepDataCon con
= LFCon con -- An imported nullary constructor
-- We assume that the constructor is evaluated so that
-- the id really does point directly to the constructor
| arity > 0
= LFReEntrant TopLevel arity True (panic "arg_descr")
| otherwise
= mkLFArgument id -- Not sure of exact arity
where
arity = idRepArity id
------------
mkLFBlackHole :: LambdaFormInfo
mkLFBlackHole = LFBlackHole
-----------------------------------------------------
-- Dynamic pointer tagging
-----------------------------------------------------
type ConTagZ = Int -- A *zero-indexed* contructor tag
type DynTag = Int -- The tag on a *pointer*
-- (from the dynamic-tagging paper)
-- Note [Data constructor dynamic tags]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- The family size of a data type (the number of constructors
-- or the arity of a function) can be either:
-- * small, if the family size < 2**tag_bits
-- * big, otherwise.
--
-- Small families can have the constructor tag in the tag bits.
-- Big families only use the tag value 1 to represent evaluatedness.
-- We don't have very many tag bits: for example, we have 2 bits on
-- x86-32 and 3 bits on x86-64.
isSmallFamily :: DynFlags -> Int -> Bool
isSmallFamily dflags fam_size = fam_size <= mAX_PTR_TAG dflags
-- We keep the *zero-indexed* tag in the srt_len field of the info
-- table of a data constructor.
dataConTagZ :: DataCon -> ConTagZ
dataConTagZ con = dataConTag con - fIRST_TAG
tagForCon :: DynFlags -> DataCon -> DynTag
tagForCon dflags con
| isSmallFamily dflags fam_size = con_tag + 1
| otherwise = 1
where
con_tag = dataConTagZ con
fam_size = tyConFamilySize (dataConTyCon con)
tagForArity :: DynFlags -> RepArity -> DynTag
tagForArity dflags arity
| isSmallFamily dflags arity = arity
| otherwise = 0
lfDynTag :: DynFlags -> LambdaFormInfo -> DynTag
-- Return the tag in the low order bits of a variable bound
-- to this LambdaForm
lfDynTag dflags (LFCon con) = tagForCon dflags con
lfDynTag dflags (LFReEntrant _ arity _ _) = tagForArity dflags arity
lfDynTag _ _other = 0
-----------------------------------------------------------------------------
-- Observing LambdaFormInfo
-----------------------------------------------------------------------------
-------------
maybeIsLFCon :: LambdaFormInfo -> Maybe DataCon
maybeIsLFCon (LFCon con) = Just con
maybeIsLFCon _ = Nothing
------------
isLFThunk :: LambdaFormInfo -> Bool
isLFThunk (LFThunk {}) = True
isLFThunk LFBlackHole = True
-- return True for a blackhole: this function is used to determine
-- whether to use the thunk header in SMP mode, and a blackhole
-- must have one.
isLFThunk _ = False
isLFReEntrant :: LambdaFormInfo -> Bool
isLFReEntrant (LFReEntrant {}) = True
isLFReEntrant _ = False
-----------------------------------------------------------------------------
-- Choosing SM reps
-----------------------------------------------------------------------------
lfClosureType :: LambdaFormInfo -> ClosureTypeInfo
lfClosureType (LFReEntrant _ arity _ argd) = Fun arity argd
lfClosureType (LFCon con) = Constr (dataConTagZ con)
(dataConIdentity con)
lfClosureType (LFThunk _ _ _ is_sel _) = thunkClosureType is_sel
lfClosureType _ = panic "lfClosureType"
thunkClosureType :: StandardFormInfo -> ClosureTypeInfo
thunkClosureType (SelectorThunk off) = ThunkSelector off
thunkClosureType _ = Thunk
-- We *do* get non-updatable top-level thunks sometimes. eg. f = g
-- gets compiled to a jump to g (if g has non-zero arity), instead of
-- messing around with update frames and PAPs. We set the closure type
-- to FUN_STATIC in this case.
-----------------------------------------------------------------------------
-- nodeMustPointToIt
-----------------------------------------------------------------------------
nodeMustPointToIt :: DynFlags -> LambdaFormInfo -> Bool
-- If nodeMustPointToIt is true, then the entry convention for
-- this closure has R1 (the "Node" register) pointing to the
-- closure itself --- the "self" argument
nodeMustPointToIt _ (LFReEntrant top _ no_fvs _)
= not no_fvs -- Certainly if it has fvs we need to point to it
|| isNotTopLevel top -- See Note [GC recovery]
-- For lex_profiling we also access the cost centre for a
-- non-inherited (i.e. non-top-level) function.
-- The isNotTopLevel test above ensures this is ok.
nodeMustPointToIt dflags (LFThunk top no_fvs updatable NonStandardThunk _)
= not no_fvs -- Self parameter
|| isNotTopLevel top -- Note [GC recovery]
|| updatable -- Need to push update frame
|| gopt Opt_SccProfilingOn dflags
-- For the non-updatable (single-entry case):
--
-- True if has fvs (in which case we need access to them, and we
-- should black-hole it)
-- or profiling (in which case we need to recover the cost centre
-- from inside it) ToDo: do we need this even for
-- top-level thunks? If not,
-- isNotTopLevel subsumes this
nodeMustPointToIt _ (LFThunk {}) -- Node must point to a standard-form thunk
= True
nodeMustPointToIt _ (LFCon _) = True
-- Strictly speaking, the above two don't need Node to point
-- to it if the arity = 0. But this is a *really* unlikely
-- situation. If we know it's nil (say) and we are entering
-- it. Eg: let x = [] in x then we will certainly have inlined
-- x, since nil is a simple atom. So we gain little by not
-- having Node point to known zero-arity things. On the other
-- hand, we do lose something; Patrick's code for figuring out
-- when something has been updated but not entered relies on
-- having Node point to the result of an update. SLPJ
-- 27/11/92.
nodeMustPointToIt _ (LFUnknown _) = True
nodeMustPointToIt _ LFUnLifted = False
nodeMustPointToIt _ LFBlackHole = True -- BH entry may require Node to point
nodeMustPointToIt _ LFLetNoEscape = False
{- Note [GC recovery]
~~~~~~~~~~~~~~~~~~~~~
If we a have a local let-binding (function or thunk)
let f = <body> in ...
AND <body> allocates, then the heap-overflow check needs to know how
to re-start the evaluation. It uses the "self" pointer to do this.
So even if there are no free variables in <body>, we still make
nodeMustPointToIt be True for non-top-level bindings.
Why do any such bindings exist? After all, let-floating should have
floated them out. Well, a clever optimiser might leave one there to
avoid a space leak, deliberately recomputing a thunk. Also (and this
really does happen occasionally) let-floating may make a function f smaller
so it can be inlined, so now (f True) may generate a local no-fv closure.
This actually happened during bootsrapping GHC itself, with f=mkRdrFunBind
in TcGenDeriv.) -}
-----------------------------------------------------------------------------
-- getCallMethod
-----------------------------------------------------------------------------
{- The entry conventions depend on the type of closure being entered,
whether or not it has free variables, and whether we're running
sequentially or in parallel.
Closure Node Argument Enter
Characteristics Par Req'd Passing Via
-------------------------------------------------------------------------------
Unknown & no & yes & stack & node
Known fun (>1 arg), no fvs & no & no & registers & fast entry (enough args)
& slow entry (otherwise)
Known fun (>1 arg), fvs & no & yes & registers & fast entry (enough args)
0 arg, no fvs \r,\s & no & no & n/a & direct entry
0 arg, no fvs \u & no & yes & n/a & node
0 arg, fvs \r,\s & no & yes & n/a & direct entry
0 arg, fvs \u & no & yes & n/a & node
Unknown & yes & yes & stack & node
Known fun (>1 arg), no fvs & yes & no & registers & fast entry (enough args)
& slow entry (otherwise)
Known fun (>1 arg), fvs & yes & yes & registers & node
0 arg, no fvs \r,\s & yes & no & n/a & direct entry
0 arg, no fvs \u & yes & yes & n/a & node
0 arg, fvs \r,\s & yes & yes & n/a & node
0 arg, fvs \u & yes & yes & n/a & node
When black-holing, single-entry closures could also be entered via node
(rather than directly) to catch double-entry. -}
data CallMethod
= EnterIt -- No args, not a function
| JumpToIt BlockId [LocalReg] -- A join point or a header of a local loop
| ReturnIt -- It's a value (function, unboxed value,
-- or constructor), so just return it.
| SlowCall -- Unknown fun, or known fun with
-- too few args.
| DirectEntry -- Jump directly, with args in regs
CLabel -- The code label
RepArity -- Its arity
getCallMethod :: DynFlags
-> Name -- Function being applied
-> Id -- Function Id used to chech if it can refer to
-- CAF's and whether the function is tail-calling
-- itself
-> LambdaFormInfo -- Its info
-> RepArity -- Number of available arguments
-> CgLoc -- Passed in from cgIdApp so that we can
-- handle let-no-escape bindings and self-recursive
-- tail calls using the same data constructor,
-- JumpToIt. This saves us one case branch in
-- cgIdApp
-> Maybe SelfLoopInfo -- can we perform a self-recursive tail call?
-> CallMethod
getCallMethod dflags _ id _ n_args _cg_loc (Just (self_loop_id, block_id, args))
| gopt Opt_Loopification dflags, id == self_loop_id, n_args == length args
-- If these patterns match then we know that:
-- * loopification optimisation is turned on
-- * function is performing a self-recursive call in a tail position
-- * number of parameters of the function matches functions arity.
-- See Note [Self-recursive tail calls] in StgCmmExpr for more details
= JumpToIt block_id args
getCallMethod dflags _name _ lf_info _n_args _cg_loc _self_loop_info
| nodeMustPointToIt dflags lf_info && gopt Opt_Parallel dflags
= -- If we're parallel, then we must always enter via node.
-- The reason is that the closure may have been
-- fetched since we allocated it.
EnterIt
getCallMethod dflags name id (LFReEntrant _ arity _ _) n_args _cg_loc _self_loop_info
| n_args == 0 = ASSERT( arity /= 0 )
ReturnIt -- No args at all
| n_args < arity = SlowCall -- Not enough args
| otherwise = DirectEntry (enterIdLabel dflags name (idCafInfo id)) arity
getCallMethod _ _name _ LFUnLifted n_args _cg_loc _self_loop_info
= ASSERT( n_args == 0 ) ReturnIt
getCallMethod _ _name _ (LFCon _) n_args _cg_loc _self_loop_info
= ASSERT( n_args == 0 ) ReturnIt
getCallMethod dflags name id (LFThunk _ _ updatable std_form_info is_fun) n_args _cg_loc _self_loop_info
| is_fun -- it *might* be a function, so we must "call" it (which is always safe)
= SlowCall -- We cannot just enter it [in eval/apply, the entry code
-- is the fast-entry code]
-- Since is_fun is False, we are *definitely* looking at a data value
| updatable || gopt Opt_Ticky dflags -- to catch double entry
{- OLD: || opt_SMP
I decided to remove this, because in SMP mode it doesn't matter
if we enter the same thunk multiple times, so the optimisation
of jumping directly to the entry code is still valid. --SDM
-}
= EnterIt
-- We used to have ASSERT( n_args == 0 ), but actually it is
-- possible for the optimiser to generate
-- let bot :: Int = error Int "urk"
-- in (bot `cast` unsafeCoerce Int (Int -> Int)) 3
-- This happens as a result of the case-of-error transformation
-- So the right thing to do is just to enter the thing
| otherwise -- Jump direct to code for single-entry thunks
= ASSERT( n_args == 0 )
DirectEntry (thunkEntryLabel dflags name (idCafInfo id) std_form_info updatable) 0
getCallMethod _ _name _ (LFUnknown True) _n_arg _cg_locs _self_loop_info
= SlowCall -- might be a function
getCallMethod _ name _ (LFUnknown False) n_args _cg_loc _self_loop_info
= ASSERT2( n_args == 0, ppr name <+> ppr n_args )
EnterIt -- Not a function
getCallMethod _ _name _ LFBlackHole _n_args _cg_loc _self_loop_info
= SlowCall -- Presumably the black hole has by now
-- been updated, but we don't know with
-- what, so we slow call it
getCallMethod _ _name _ LFLetNoEscape _n_args (LneLoc blk_id lne_regs) _self_loop_info
= JumpToIt blk_id lne_regs
getCallMethod _ _ _ _ _ _ _ = panic "Unknown call method"
-----------------------------------------------------------------------------
-- staticClosureRequired
-----------------------------------------------------------------------------
{- staticClosureRequired is never called (hence commented out)
SimonMar writes (Sept 07) It's an optimisation we used to apply at
one time, I believe, but it got lost probably in the rewrite of
the RTS/code generator. I left that code there to remind me to
look into whether it was worth doing sometime
{- Avoiding generating entries and info tables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At present, for every function we generate all of the following,
just in case. But they aren't always all needed, as noted below:
[NB1: all of this applies only to *functions*. Thunks always
have closure, info table, and entry code.]
[NB2: All are needed if the function is *exported*, just to play safe.]
* Fast-entry code ALWAYS NEEDED
* Slow-entry code
Needed iff (a) we have any un-saturated calls to the function
OR (b) the function is passed as an arg
OR (c) we're in the parallel world and the function has free vars
[Reason: in parallel world, we always enter functions
with free vars via the closure.]
* The function closure
Needed iff (a) we have any un-saturated calls to the function
OR (b) the function is passed as an arg
OR (c) if the function has free vars (ie not top level)
Why case (a) here? Because if the arg-satis check fails,
UpdatePAP stuffs a pointer to the function closure in the PAP.
[Could be changed; UpdatePAP could stuff in a code ptr instead,
but doesn't seem worth it.]
[NB: these conditions imply that we might need the closure
without the slow-entry code. Here's how.
f x y = let g w = ...x..y..w...
in
...(g t)...
Here we need a closure for g which contains x and y,
but since the calls are all saturated we just jump to the
fast entry point for g, with R1 pointing to the closure for g.]
* Standard info table
Needed iff (a) we have any un-saturated calls to the function
OR (b) the function is passed as an arg
OR (c) the function has free vars (ie not top level)
NB. In the sequential world, (c) is only required so that the function closure has
an info table to point to, to keep the storage manager happy.
If (c) alone is true we could fake up an info table by choosing
one of a standard family of info tables, whose entry code just
bombs out.
[NB In the parallel world (c) is needed regardless because
we enter functions with free vars via the closure.]
If (c) is retained, then we'll sometimes generate an info table
(for storage mgr purposes) without slow-entry code. Then we need
to use an error label in the info table to substitute for the absent
slow entry code.
-}
staticClosureRequired
:: Name
-> StgBinderInfo
-> LambdaFormInfo
-> Bool
staticClosureRequired binder bndr_info
(LFReEntrant top_level _ _ _) -- It's a function
= ASSERT( isTopLevel top_level )
-- Assumption: it's a top-level, no-free-var binding
not (satCallsOnly bndr_info)
staticClosureRequired binder other_binder_info other_lf_info = True
-}
-----------------------------------------------------------------------------
-- Data types for closure information
-----------------------------------------------------------------------------
{- ClosureInfo: information about a binding
We make a ClosureInfo for each let binding (both top level and not),
but not bindings for data constructors: for those we build a CmmInfoTable
directly (see mkDataConInfoTable).
To a first approximation:
ClosureInfo = (LambdaFormInfo, CmmInfoTable)
A ClosureInfo has enough information
a) to construct the info table itself, and build other things
related to the binding (e.g. slow entry points for a function)
b) to allocate a closure containing that info pointer (i.e.
it knows the info table label)
-}
data ClosureInfo
= ClosureInfo {
closureName :: !Name, -- The thing bound to this closure
-- we don't really need this field: it's only used in generating
-- code for ticky and profiling, and we could pass the information
-- around separately, but it doesn't do much harm to keep it here.
closureLFInfo :: !LambdaFormInfo, -- NOTE: not an LFCon
-- this tells us about what the closure contains: it's right-hand-side.
-- the rest is just an unpacked CmmInfoTable.
closureInfoLabel :: !CLabel,
closureSMRep :: !SMRep, -- representation used by storage mgr
closureProf :: !ProfilingInfo
}
-- | Convert from 'ClosureInfo' to 'CmmInfoTable'.
mkCmmInfo :: ClosureInfo -> CmmInfoTable
mkCmmInfo ClosureInfo {..}
= CmmInfoTable { cit_lbl = closureInfoLabel
, cit_rep = closureSMRep
, cit_prof = closureProf
, cit_srt = NoC_SRT }
--------------------------------------
-- Building ClosureInfos
--------------------------------------
mkClosureInfo :: DynFlags
-> Bool -- Is static
-> Id
-> LambdaFormInfo
-> Int -> Int -- Total and pointer words
-> String -- String descriptor
-> ClosureInfo
mkClosureInfo dflags is_static id lf_info tot_wds ptr_wds val_descr
= ClosureInfo { closureName = name
, closureLFInfo = lf_info
, closureInfoLabel = info_lbl -- These three fields are
, closureSMRep = sm_rep -- (almost) an info table
, closureProf = prof } -- (we don't have an SRT yet)
where
name = idName id
sm_rep = mkHeapRep dflags is_static ptr_wds nonptr_wds (lfClosureType lf_info)
prof = mkProfilingInfo dflags id val_descr
nonptr_wds = tot_wds - ptr_wds
info_lbl = mkClosureInfoTableLabel id lf_info
--------------------------------------
-- Other functions over ClosureInfo
--------------------------------------
-- Eager blackholing is normally disabled, but can be turned on with
-- -feager-blackholing. When it is on, we replace the info pointer of
-- the thunk with stg_EAGER_BLACKHOLE_info on entry.
-- If we wanted to do eager blackholing with slop filling,
-- we'd need to do it at the *end* of a basic block, otherwise
-- we overwrite the free variables in the thunk that we still
-- need. We have a patch for this from Andy Cheadle, but not
-- incorporated yet. --SDM [6/2004]
--
--
-- Previously, eager blackholing was enabled when ticky-ticky
-- was on. But it didn't work, and it wasn't strictly necessary
-- to bring back minimal ticky-ticky, so now EAGER_BLACKHOLING
-- is unconditionally disabled. -- krc 1/2007
-- Static closures are never themselves black-holed.
blackHoleOnEntry :: ClosureInfo -> Bool
blackHoleOnEntry cl_info
| isStaticRep (closureSMRep cl_info)
= False -- Never black-hole a static closure
| otherwise
= case closureLFInfo cl_info of
LFReEntrant _ _ _ _ -> False
LFLetNoEscape -> False
LFThunk _ _no_fvs _updatable _ _ -> True
_other -> panic "blackHoleOnEntry" -- Should never happen
isStaticClosure :: ClosureInfo -> Bool
isStaticClosure cl_info = isStaticRep (closureSMRep cl_info)
closureUpdReqd :: ClosureInfo -> Bool
closureUpdReqd ClosureInfo{ closureLFInfo = lf_info } = lfUpdatable lf_info
lfUpdatable :: LambdaFormInfo -> Bool
lfUpdatable (LFThunk _ _ upd _ _) = upd
lfUpdatable LFBlackHole = True
-- Black-hole closures are allocated to receive the results of an
-- alg case with a named default... so they need to be updated.
lfUpdatable _ = False
closureSingleEntry :: ClosureInfo -> Bool
closureSingleEntry (ClosureInfo { closureLFInfo = LFThunk _ _ upd _ _}) = not upd
closureSingleEntry _ = False
closureReEntrant :: ClosureInfo -> Bool
closureReEntrant (ClosureInfo { closureLFInfo = LFReEntrant _ _ _ _ }) = True
closureReEntrant _ = False
closureFunInfo :: ClosureInfo -> Maybe (RepArity, ArgDescr)
closureFunInfo (ClosureInfo { closureLFInfo = lf_info }) = lfFunInfo lf_info
lfFunInfo :: LambdaFormInfo -> Maybe (RepArity, ArgDescr)
lfFunInfo (LFReEntrant _ arity _ arg_desc) = Just (arity, arg_desc)
lfFunInfo _ = Nothing
funTag :: DynFlags -> ClosureInfo -> DynTag
funTag dflags (ClosureInfo { closureLFInfo = lf_info })
= lfDynTag dflags lf_info
isToplevClosure :: ClosureInfo -> Bool
isToplevClosure (ClosureInfo { closureLFInfo = lf_info })
= case lf_info of
LFReEntrant TopLevel _ _ _ -> True
LFThunk TopLevel _ _ _ _ -> True
_other -> False
--------------------------------------
-- Label generation
--------------------------------------
staticClosureLabel :: ClosureInfo -> CLabel
staticClosureLabel = toClosureLbl . closureInfoLabel
closureSlowEntryLabel :: ClosureInfo -> CLabel
closureSlowEntryLabel = toSlowEntryLbl . closureInfoLabel
closureLocalEntryLabel :: DynFlags -> ClosureInfo -> CLabel
closureLocalEntryLabel dflags
| tablesNextToCode dflags = toInfoLbl . closureInfoLabel
| otherwise = toEntryLbl . closureInfoLabel
mkClosureInfoTableLabel :: Id -> LambdaFormInfo -> CLabel
mkClosureInfoTableLabel id lf_info
= case lf_info of
LFBlackHole -> mkCAFBlackHoleInfoTableLabel
LFThunk _ _ upd_flag (SelectorThunk offset) _
-> mkSelectorInfoLabel upd_flag offset
LFThunk _ _ upd_flag (ApThunk arity) _
-> mkApInfoTableLabel upd_flag arity
LFThunk{} -> std_mk_lbl name cafs
LFReEntrant{} -> std_mk_lbl name cafs
_other -> panic "closureInfoTableLabel"
where
name = idName id
std_mk_lbl | is_local = mkLocalInfoTableLabel
| otherwise = mkInfoTableLabel
cafs = idCafInfo id
is_local = isDataConWorkId id
-- Make the _info pointer for the implicit datacon worker
-- binding local. The reason we can do this is that importing
-- code always either uses the _closure or _con_info. By the
-- invariants in CorePrep anything else gets eta expanded.
thunkEntryLabel :: DynFlags -> Name -> CafInfo -> StandardFormInfo -> Bool -> CLabel
-- thunkEntryLabel is a local help function, not exported. It's used from
-- getCallMethod.
thunkEntryLabel dflags _thunk_id _ (ApThunk arity) upd_flag
= enterApLabel dflags upd_flag arity
thunkEntryLabel dflags _thunk_id _ (SelectorThunk offset) upd_flag
= enterSelectorLabel dflags upd_flag offset
thunkEntryLabel dflags thunk_id c _ _
= enterIdLabel dflags thunk_id c
enterApLabel :: DynFlags -> Bool -> Arity -> CLabel
enterApLabel dflags is_updatable arity
| tablesNextToCode dflags = mkApInfoTableLabel is_updatable arity
| otherwise = mkApEntryLabel is_updatable arity
enterSelectorLabel :: DynFlags -> Bool -> WordOff -> CLabel
enterSelectorLabel dflags upd_flag offset
| tablesNextToCode dflags = mkSelectorInfoLabel upd_flag offset
| otherwise = mkSelectorEntryLabel upd_flag offset
enterIdLabel :: DynFlags -> Name -> CafInfo -> CLabel
enterIdLabel dflags id c
| tablesNextToCode dflags = mkInfoTableLabel id c
| otherwise = mkEntryLabel id c
--------------------------------------
-- Profiling
--------------------------------------
-- Profiling requires two pieces of information to be determined for
-- each closure's info table --- description and type.
-- The description is stored directly in the @CClosureInfoTable@ when the
-- info table is built.
-- The type is determined from the type information stored with the @Id@
-- in the closure info using @closureTypeDescr@.
mkProfilingInfo :: DynFlags -> Id -> String -> ProfilingInfo
mkProfilingInfo dflags id val_descr
| not (gopt Opt_SccProfilingOn dflags) = NoProfilingInfo
| otherwise = ProfilingInfo ty_descr_w8 val_descr_w8
where
ty_descr_w8 = stringToWord8s (getTyDescription (idType id))
val_descr_w8 = stringToWord8s val_descr
getTyDescription :: Type -> String
getTyDescription ty
= case (tcSplitSigmaTy ty) of { (_, _, tau_ty) ->
case tau_ty of
TyVarTy _ -> "*"
AppTy fun _ -> getTyDescription fun
FunTy _ res -> '-' : '>' : fun_result res
TyConApp tycon _ -> getOccString tycon
ForAllTy _ ty -> getTyDescription ty
LitTy n -> getTyLitDescription n
}
where
fun_result (FunTy _ res) = '>' : fun_result res
fun_result other = getTyDescription other
getTyLitDescription :: TyLit -> String
getTyLitDescription l =
case l of
NumTyLit n -> show n
StrTyLit n -> show n
--------------------------------------
-- CmmInfoTable-related things
--------------------------------------
mkDataConInfoTable :: DynFlags -> DataCon -> Bool -> Int -> Int -> CmmInfoTable
mkDataConInfoTable dflags data_con is_static ptr_wds nonptr_wds
= CmmInfoTable { cit_lbl = info_lbl
, cit_rep = sm_rep
, cit_prof = prof
, cit_srt = NoC_SRT }
where
name = dataConName data_con
info_lbl | is_static = mkStaticInfoTableLabel name NoCafRefs
| otherwise = mkConInfoTableLabel name NoCafRefs
sm_rep = mkHeapRep dflags is_static ptr_wds nonptr_wds cl_type
cl_type = Constr (dataConTagZ data_con) (dataConIdentity data_con)
prof | not (gopt Opt_SccProfilingOn dflags) = NoProfilingInfo
| otherwise = ProfilingInfo ty_descr val_descr
ty_descr = stringToWord8s $ occNameString $ getOccName $ dataConTyCon data_con
val_descr = stringToWord8s $ occNameString $ getOccName data_con
-- We need a black-hole closure info to pass to @allocDynClosure@ when we
-- want to allocate the black hole on entry to a CAF.
cafBlackHoleInfoTable :: CmmInfoTable
cafBlackHoleInfoTable
= CmmInfoTable { cit_lbl = mkCAFBlackHoleInfoTableLabel
, cit_rep = blackHoleRep
, cit_prof = NoProfilingInfo
, cit_srt = NoC_SRT }
indStaticInfoTable :: CmmInfoTable
indStaticInfoTable
= CmmInfoTable { cit_lbl = mkIndStaticInfoLabel
, cit_rep = indStaticRep
, cit_prof = NoProfilingInfo
, cit_srt = NoC_SRT }
staticClosureNeedsLink :: Bool -> CmmInfoTable -> Bool
-- A static closure needs a link field to aid the GC when traversing
-- the static closure graph. But it only needs such a field if either
-- a) it has an SRT
-- b) it's a constructor with one or more pointer fields
-- In case (b), the constructor's fields themselves play the role
-- of the SRT.
--
-- At this point, the cit_srt field has not been calculated (that
-- happens right at the end of the Cmm pipeline), but we do have the
-- VarSet of CAFs that CoreToStg attached, and if that is empty there
-- will definitely not be an SRT.
--
staticClosureNeedsLink has_srt CmmInfoTable{ cit_rep = smrep }
| isConRep smrep = not (isStaticNoCafCon smrep)
| otherwise = has_srt -- needsSRT (cit_srt info_tbl)
| ekmett/ghc | compiler/codeGen/StgCmmClosure.hs | bsd-3-clause | 38,975 | 0 | 12 | 10,584 | 4,738 | 2,577 | 2,161 | 443 | 7 |
module IRC.Network(write
,reader
,newConnection
,closeConn) where
import System.IO (Handle
,hGetLine
,hSetBuffering
,BufferMode(NoBuffering)
,hClose)
import Network (PortID, HostName, connectTo)
import Text.Printf (hPrintf)
import IRC.Agent
-- reads from the socket.
reader :: Agent -> IO String
reader a =
case conn a of
Nothing -> return ""
Just c -> hGetLine c
-- Writes messages to the socket
write :: String -> String -> Maybe Handle -> IO ()
write com param mh =
case mh of
Nothing -> return()
Just h -> hPrintf h "%s %s\r\n" com param
newConnection :: Agent -> IO Agent
newConnection a = do
h <- connectTo (hostname a) (portNumber a)
hSetBuffering h NoBuffering
return $ a { conn = Just h }
closeConn :: Agent -> IO Agent
closeConn a = do
case conn a of
Nothing -> return a
Just c -> do
hClose c
return $ a { conn = Nothing }
| TheRedPepper/YBot | src/IRC/Network.hs | bsd-3-clause | 1,049 | 0 | 14 | 364 | 334 | 170 | 164 | 34 | 2 |
{-# LANGUAGE TypeFamilies, DeriveGeneric, DuplicateRecordFields #-}
module YandexDirect.Entity.Dictionary where
import YandexDirect.Lib
import YandexDirect.Entity.Core
instance Entity DictionaryNames where
entityName _ = "dictionaries"
instance Item DictionaryNameEnum where
type PackItems DictionaryNameEnum = DictionaryNames
packItems = DictionaryNames
newtype DictionaryNames = DictionaryNames
{ getDictionaryNames :: [DictionaryNameEnum]
} deriving (Generic)
data DictionaryNameEnum
= Currencies
| MetroStations
| GeoRegions
| TimeZones
| Constants
| AdCategories
| OperationSystemVersions
| ProductivityAssertions
| SupplySidePlatforms
deriving (Generic)
instance ToJSON DictionaryNames where
toJSON = deriveToJSONcamelOmit
instance ToJSON DictionaryNameEnum
instance TextShow DictionaryNames where
showbPrec = genericShowbPrec
instance TextShow DictionaryNameEnum where
showbPrec = genericShowbPrec
| effectfully/YandexDirect | src/YandexDirect/Entity/Dictionary.hs | bsd-3-clause | 955 | 0 | 7 | 140 | 164 | 96 | 68 | 30 | 0 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.BlendMinmax
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.BlendMinmax (
-- * Extension Support
glGetEXTBlendMinmax,
gl_EXT_blend_minmax,
-- * Enums
pattern GL_BLEND_EQUATION_EXT,
pattern GL_FUNC_ADD_EXT,
pattern GL_MAX_EXT,
pattern GL_MIN_EXT,
-- * Functions
glBlendEquationEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/EXT/BlendMinmax.hs | bsd-3-clause | 783 | 0 | 5 | 113 | 72 | 52 | 20 | 12 | 0 |
-- Utility infixes
module Data.Map.Function (
(<$$>),
(<$$$>),
(<$$$$>),
(<&>),
(<&&>),
(<&&&>),
(<&&&&>),
) where
infixl 4 <$$> -- same binding as (Data.Functor.<$>)
infixl 4 <$$$>
infixl 4 <$$$$>
infixl 1 <&> -- same binding as (Data.Function.&)
infixl 1 <&&>
infixl 1 <&&&>
infixl 1 <&&&&>
(<$$>) :: (Functor f, Functor g)
=> (a -> b)
-> f (g a)
-> f (g b)
(<$$>) = fmap . fmap
(<$$$>) :: (Functor f, Functor g, Functor h)
=> (a -> b)
-> f (g (h a))
-> f (g (h b))
(<$$$>) = fmap . fmap . fmap
(<$$$$>) :: (Functor f, Functor g, Functor h, Functor i)
=> (a -> b)
-> f (g (h (i a)))
-> f (g (h (i b)))
(<$$$$>) = fmap . fmap . fmap . fmap
(<&>) :: (Functor f)
=> f a
-> (a -> b)
-> f b
(<&>) = flip (<$>)
(<&&>) :: (Functor f, Functor g)
=> f (g a)
-> (a -> b)
-> f (g b)
(<&&>) = flip (<$$>)
(<&&&>) :: (Functor f, Functor g, Functor h)
=> f (g (h a))
-> (a -> b)
-> f (g (h b))
(<&&&>) = flip (<$$$>)
(<&&&&>) :: (Functor f, Functor g, Functor h, Functor i)
=> f (g (h (i a)))
-> (a -> b)
-> f (g (h (i b)))
(<&&&&>) = flip (<$$$$>)
| elsen-trading/map-extensions | src/Data/Map/Function.hs | bsd-3-clause | 1,105 | 0 | 14 | 297 | 651 | 366 | 285 | 50 | 1 |
module Statement ( Statement(..)) where
import Expression (Expression(..), Value(..))
data Statement
= Assign String Expression
| If Expression Statement Statement
| While Expression Statement
| Print Expression
| Seq Statement Statement
deriving (Show, Read)
| c-brenn/kronos | src/Statement.hs | bsd-3-clause | 274 | 0 | 6 | 48 | 82 | 50 | 32 | 9 | 0 |
module Algw.InferSpec where
import Algw.Ast
import Algw.Type
import Algw.Infer
import Algw.Env
import qualified Text.PrettyPrint as PP
import qualified Data.Map as M
import Test.Hspec
runInferSpecCase :: Expr -> String -> IO ()
runInferSpecCase expr expect = do
t <- infer assumptions expr
let gt = generalize M.empty t
(PP.text . show $ gt) `shouldBe` PP.text expect
failInferSpecCase :: Expr -> String -> IO ()
failInferSpecCase expr error = infer assumptions expr `shouldThrow` errorCall error
spec :: Spec
spec = do
describe "unification test" $
it "should find mgu" $ do
let mono1 = TArrow (TVar "a") TInt
let mono2 = TArrow (TVar "b") $ TVar "b"
let mono3 = TArrow (TVar "a") $ TVar "b"
let mono4 = TArrow (TArrow (TVar "b") $ TVar "c") $ TVar "c"
subrule1 <- unify mono1 mono2
subrule2 <- unify mono3 mono4
subrule1 `shouldBe` M.fromList [("a", TInt), ("b", TInt)]
subrule2 `shouldBe` M.fromList [("a", TArrow (TVar "c") $ TVar "c"), ("b", TVar "c")]
describe "inference test" $
it "should infer most general or principal types for given expression" $ do
runInferSpecCase (EVar "id") "∀a. a → a"
runInferSpecCase (EApp (EVar "id") $ EApp (EVar "id") (EVar "one")) "int"
runInferSpecCase (EApp (EApp (EVar "eq") (EVar "false")) (EVar "true")) "bool"
runInferSpecCase (EVar "compose") "∀a. ∀b. ∀c. (b → c) → (a → b) → a → c"
runInferSpecCase (EApp (EVar "compose") (EVar "not")) "∀a. (a → bool) → a → bool"
runInferSpecCase (EApp (EApp (EVar "compose") (EVar "not")) (EApp (EVar "eq") (EVar "one"))) "int → bool"
runInferSpecCase (EApp (EVar "compose") (EApp (EVar "add") (EVar "one"))) "∀a. (a → int) → a → int"
runInferSpecCase (EApp (EApp (EApp (EVar "compose") (EVar "eq")) (EVar "add")) (EVar "one")) "(int → int) → bool" -- a really interesting case
runInferSpecCase (EApp (EVar "compose") (EVar "compose")) "∀a. ∀d. ∀e. ∀f. (a → e → f) → a → (d → e) → d → f"
failInferSpecCase (EApp (EVar "one") (EVar "one")) "types do not unify: int vs. int → a"
failInferSpecCase (EAbs "f" $ EApp (EVar "f") (EVar "f")) "occurs check fails"
failInferSpecCase (EApp (EApp (EVar "add") (EVar "true")) (EVar "false")) "types do not unify: int vs. bool"
failInferSpecCase (EVar "x") "unbound variable: x"
runInferSpecCase (EAbs "a"
(ELet "x"
(EAbs "b"
(ELet "y"
(EAbs "c" (EApp (EVar "a") (EVar "zero")))
(EApp (EVar "y") (EVar "one"))))
(EApp (EVar "x") (EVar "one")))) "∀h. (int → h) → h"
failInferSpecCase (EAbs "a" (EAbs "b"
(EApp (EVar "b")
(EApp (EVar "a")
(EApp (EVar "a") (EVar "b")))))) "occurs check fails"
runInferSpecCase (EApp (EApp (EVar "choose")
(EAbs "a"
(EAbs "b"
(EVar "a"))))
(EAbs "a"
(EAbs "b"
(EVar "b")))) "∀f. f → f → f"
runInferSpecCase (EAbs "x"
(EAbs "y"
(ELet "x"
(EApp (EVar "x")
(EVar "y"))
(EAbs "x"
(EApp (EVar "y")
(EVar "x")))))) "∀c. ∀d. ∀e. ((d → e) → c) → (d → e) → d → e"
| zjhmale/HMF | test/Algw/InferSpec.hs | bsd-3-clause | 4,011 | 0 | 24 | 1,580 | 1,212 | 589 | 623 | 68 | 1 |
module Main where
import Graphics.UI.WXCore
import Graphics.UI.WX
main :: IO ()
main
= start gui
gui :: IO ()
gui
= do f <- frame [text := "Paint demo", fullRepaintOnResize := False]
sw <- scrolledWindow f [ on paint := onpaint
, virtualSize := sz 500 500, scrollRate := sz 10 10
, fullRepaintOnResize := False]
set f [clientSize := sz 150 150, layout := fill $ widget sw]
return ()
where
onpaint dc _viewArea
= do circle dc (pt 200 200) 20 [penKind := PenDash DashDot]
arc dc (pt 100 100) 20 90 230 [color := red, penWidth :~ (+1), penKind := PenSolid]
ellipticArc dc (rect (pt 20 20) (sz 60 30)) 90 230 [color := blue, penWidth :~ (*2)]
c <- get dc color
-- set dc [font := fontDefault{ fontFace = "Courier New", fontSize = 16, fontWeight = WeightBold }]
set dc [fontFace := "Courier New", fontSize := 16, fontWeight := WeightBold ]
drawText dc (show c) (pt 50 50) []
rotatedText dc "rotated text" (pt 80 160) 45 [textColor := green]
| jacekszymanski/wxHaskell | samples/wx/Paint.hs | lgpl-2.1 | 1,116 | 0 | 13 | 355 | 414 | 208 | 206 | 22 | 1 |
partition :: Int -> [Int] -> ([Int], [Int])
partition _ [] = ([], [])
partition p (t:q)
|t < p = let
(a, b) = partition p q
in
(t:a, b)
|otherwise = let
(a, b) = partition p q
in
(a, t:b)
quicksort :: [Int] -> [Int]
quicksort [] = []
quicksort (t:q) = let
(a, b) = partition t q
in
(quicksort a) ++ (t:quicksort b)
main = print(quicksort [18, 21, 3, 54, 21, 22, 4, 32, 17, 28, 2, 31, 74, 30])
| alok760/Algorithms_Example | QuickSort/Haskell/quicksort.hs | apache-2.0 | 488 | 0 | 10 | 180 | 294 | 159 | 135 | 15 | 1 |
{-# LANGUAGE CPP
, GADTs
, KindSignatures
, DataKinds
, TypeOperators
, Rank2Types
, BangPatterns
, FlexibleContexts
, MultiParamTypeClasses
, FunctionalDependencies
, FlexibleInstances
, UndecidableInstances
, EmptyCase
, ScopedTypeVariables
#-}
{-# OPTIONS_GHC -Wall -fwarn-tabs #-}
----------------------------------------------------------------
-- 2016.05.24
-- |
-- Module : Language.Hakaru.Evaluation.PEvalMonad
-- Copyright : Copyright (c) 2016 the Hakaru team
-- License : BSD3
-- Maintainer : wren@community.haskell.org
-- Stability : experimental
-- Portability : GHC-only
--
-- A unified 'EvaluationMonad' for pure evaluation, expect, and
-- disintegrate.
----------------------------------------------------------------
module Language.Hakaru.Evaluation.PEvalMonad
(
-- * The unified 'PEval' monad
-- ** List-based version
ListContext(..), PAns, PEval(..)
, runPureEval, runImpureEval, runExpectEval
-- ** TODO: IntMap-based version
-- * Operators on the disintegration monad
-- ** The \"zero\" and \"one\"
, bot
--, reject
-- ** Emitting code
, emit
, emitMBind
, emitLet
, emitLet'
, emitUnpair
-- TODO: emitUneither
-- emitCaseWith
, emit_
, emitMBind_
, emitGuard
, emitWeight
, emitFork_
, emitSuperpose
, choose
) where
import Prelude hiding (id, (.))
import Control.Category (Category(..))
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid (Monoid(..))
import Data.Functor ((<$>))
import Control.Applicative (Applicative(..))
#endif
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import qualified Data.List.NonEmpty as NE
import Control.Applicative (Alternative(..))
import Control.Monad (MonadPlus(..))
import Data.Text (Text)
import qualified Data.Text as Text
import Language.Hakaru.Syntax.IClasses
import Data.Number.Nat
import Language.Hakaru.Types.DataKind
import Language.Hakaru.Types.Sing (Sing, sUnMeasure, sUnPair)
import Language.Hakaru.Syntax.AST
import Language.Hakaru.Syntax.TypeOf
import Language.Hakaru.Syntax.ABT
import Language.Hakaru.Syntax.Datum
import Language.Hakaru.Syntax.DatumABT
import qualified Language.Hakaru.Syntax.Prelude as P
import Language.Hakaru.Evaluation.Types
import Language.Hakaru.Evaluation.Lazy (reifyPair)
#ifdef __TRACE_DISINTEGRATE__
import Debug.Trace (trace)
#endif
----------------------------------------------------------------
----------------------------------------------------------------
-- | An ordered collection of statements representing the context
-- surrounding the current focus of our program transformation.
-- That is, since some transformations work from the bottom up, we
-- need to keep track of the statements we passed along the way
-- when reaching for the bottom.
--
-- The tail of the list takes scope over the head of the list. Thus,
-- the back\/end of the list is towards the top of the program,
-- whereas the front of the list is towards the bottom.
--
-- This type was formerly called @Heap@ (presumably due to the
-- 'Statement' type being called @Binding@) but that seems like a
-- misnomer to me since this really has nothing to do with allocation.
-- However, it is still like a heap inasmuch as it's a dependency
-- graph and we may wish to change the topological sorting or remove
-- \"garbage\" (subject to correctness criteria).
--
-- TODO: Figure out what to do with 'SWeight', 'SGuard', 'SStuff',
-- etc, so that we can use an @IntMap (Statement abt)@ in order to
-- speed up the lookup times in 'select'. (Assuming callers don't
-- use 'unsafePush' unsafely: we can recover the order things were
-- inserted from their 'varID' since we've freshened them all and
-- therefore their IDs are monotonic in the insertion order.)
data ListContext (abt :: [Hakaru] -> Hakaru -> *) (p :: Purity) =
ListContext
{ nextFreshNat :: {-# UNPACK #-} !Nat
, statements :: [Statement abt Location p]
}
-- HACK: we can't use a type family and do @abt xs (P p a)@ because
-- of non-injectivity. So we make this a GADT instead. Because it's
-- a GADT, there's a bunch of ugly rewrapping required; but everything
-- seems to work out just fine...
data P :: Purity -> ([Hakaru] -> Hakaru -> *) -> [Hakaru] -> Hakaru -> *
where
PPure :: !(abt xs a) -> P 'Pure abt xs a
PImpure :: !(abt xs ('HMeasure a)) -> P 'Impure abt xs a
PExpect :: !(abt xs 'HProb) -> P 'ExpectP abt xs a
unPPure :: P 'Pure abt xs a -> abt xs a
unPPure (PPure e) = e
unPImpure :: P 'Impure abt xs a -> abt xs ('HMeasure a)
unPImpure (PImpure e) = e
unPExpect :: P 'ExpectP abt xs a -> abt xs 'HProb
unPExpect (PExpect e) = e
mapPPure :: (abt xs a -> abt ys b) -> P 'Pure abt xs a -> P 'Pure abt ys b
mapPPure f (PPure e) = PPure (f e)
mapPImpure
:: (abt xs ('HMeasure a) -> abt ys ('HMeasure b))
-> P 'Impure abt xs a
-> P 'Impure abt ys b
mapPImpure f (PImpure e) = PImpure (f e)
mapPExpect
:: (abt xs 'HProb -> abt ys 'HProb)
-> P 'ExpectP abt xs a
-> P 'ExpectP abt ys b
mapPExpect f (PExpect e) = PExpect (f e)
mapP
:: (forall a. abt xs a -> abt ys a)
-> P p abt xs b
-> P p abt ys b
mapP f (PPure e) = PPure $ f e
mapP f (PImpure e) = PImpure $ f e
mapP f (PExpect e) = PExpect $ f e
-- | Plug a term into a context. That is, the 'statements' of the
-- context specifies a program with a hole in it; so we plug the
-- given term into that hole, returning the complete program.
residualizeListContext
:: forall abt p a
. (ABT Term abt)
=> ListContext abt p
-> P p abt '[] a
-> P p abt '[] a
residualizeListContext =
-- N.B., we use a left fold because the head of the list of
-- statements is the one closest to the hole.
\ss e0 -> foldl (flip step) e0 (statements ss)
where
step
:: Statement abt Location p
-> P p abt '[] a
-> P p abt '[] a
step (SLet (Location x) body _) = mapP $ residualizeLet x body
step (SBind (Location x) body _) = mapPImpure $ \e ->
-- TODO: if @body@ is dirac, then treat as 'SLet'
syn (MBind :$ fromLazy body :* bind x e :* End)
step (SGuard xs pat scrutinee _) = mapPImpure $ \e ->
-- TODO: avoid adding the 'PWild' branch if we know @pat@ covers the type
syn $ Case_ (fromLazy scrutinee)
[ Branch pat $ binds_ (fromLocations1 xs) e
, Branch PWild $ P.reject (typeOf e)
]
step (SWeight body _) = mapPImpure $ P.withWeight (fromLazy body)
step (SStuff0 f _) = mapPExpect f
step (SStuff1 _x f _) = mapPExpect f
-- TODO: move this to Prelude? Is there anyone else that actually needs these smarts?
residualizeLet
:: (ABT Term abt) => Variable a -> Lazy abt a -> abt '[] b -> abt '[] b
residualizeLet x body scope
-- Drop unused bindings
| not (x `memberVarSet` freeVars scope) = scope
-- TODO: if used exactly once in @e@, then inline.
| otherwise =
case getLazyVariable body of
Just y -> subst x (var y) scope
Nothing ->
case getLazyLiteral body of
Just v -> subst x (syn $ Literal_ v) scope
Nothing ->
syn (Let_ :$ fromLazy body :* bind x scope :* End)
----------------------------------------------------------------
type PAns p abt m a = ListContext abt p -> m (P p abt '[] a)
----------------------------------------------------------------
-- TODO: defunctionalize the continuation. In particular, the only
-- heap modifications we need are 'push' and a variant of 'update'
-- for finding\/replacing a binding once we have the value in hand;
-- and the only 'freshNat' modifications are to allocate new 'Nat'.
-- We could defunctionalize the second arrow too by relying on the
-- @Codensity (ReaderT e m) ~= StateT e (Codensity m)@ isomorphism,
-- which makes explicit that the only thing other than 'ListContext'
-- updates is emitting something like @[Statement]@ to serve as the
-- beginning of the final result.
--
-- | TODO: give this a better, more informative name!
newtype PEval abt p m x =
PEval { unPEval :: forall a. (x -> PAns p abt m a) -> PAns p abt m a }
-- == Codensity (PAns p abt m)
-- | Run an 'Impure' computation in the 'PEval' monad, residualizing
-- out all the statements in the final evaluation context. The
-- second argument should include all the terms altered by the
-- 'PEval' expression; this is necessary to ensure proper hygiene;
-- for example(s):
--
-- > runPEval (perform e) [Some2 e]
-- > runPEval (constrainOutcome e v) [Some2 e, Some2 v]
--
-- We use 'Some2' on the inputs because it doesn't matter what their
-- type or locally-bound variables are, so we want to allow @f@ to
-- contain terms with different indices.
runImpureEval
:: (ABT Term abt, Applicative m, F.Foldable f)
=> PEval abt 'Impure m (abt '[] a)
-> f (Some2 abt)
-> m (abt '[] ('HMeasure a))
runImpureEval m es =
unPImpure <$> unPEval m c0 h0
where
i0 = maxNextFree es -- TODO: is maxNextFreeOrBind better here?
h0 = ListContext i0 []
-- TODO: we only use dirac because 'residualizeListContext'
-- requires it to already be a measure; unfortunately this can
-- result in an extraneous @(>>= \x -> dirac x)@ redex at the
-- end of the program. In principle, we should be able to
-- eliminate that redex by changing the type of
-- 'residualizeListContext'...
c0 e ss =
pure
. residualizeListContext ss
. PImpure
$ syn(Dirac :$ e :* End)
runPureEval
:: (ABT Term abt, Applicative m, F.Foldable f)
=> PEval abt 'Pure m (abt '[] a)
-> f (Some2 abt)
-> m (abt '[] a)
runPureEval m es =
unPPure <$> unPEval m c0 h0
where
i0 = maxNextFree es -- TODO: is maxNextFreeOrBind better here?
h0 = ListContext i0 []
c0 e ss = pure . residualizeListContext ss $ PPure e
runExpectEval
:: (ABT Term abt, Applicative m, F.Foldable f)
=> PEval abt 'ExpectP m (abt '[] a)
-> abt '[a] 'HProb
-> f (Some2 abt)
-> m (abt '[] 'HProb)
runExpectEval m f es =
unPExpect <$> unPEval m c0 h0
where
i0 = nextFreeOrBind f `max` maxNextFreeOrBind es
h0 = ListContext i0 []
c0 e ss =
pure
. residualizeListContext ss
. PExpect
$ caseVarSyn e
(\x -> caseBind f $ \y f' -> subst y (var x) f')
(\_ -> syn (Let_ :$ e :* f :* End))
-- TODO: make this smarter still, to drop the let-binding entirely if it's not used in @f@.
instance Functor (PEval abt p m) where
fmap f m = PEval $ \c -> unPEval m (c . f)
instance Applicative (PEval abt p m) where
pure x = PEval $ \c -> c x
mf <*> mx = PEval $ \c -> unPEval mf $ \f -> unPEval mx $ \x -> c (f x)
instance Monad (PEval abt p m) where
return = pure
mx >>= k = PEval $ \c -> unPEval mx $ \x -> unPEval (k x) c
instance Alternative m => Alternative (PEval abt p m) where
empty = PEval $ \_ _ -> empty
m <|> n = PEval $ \c h -> unPEval m c h <|> unPEval n c h
instance Alternative m => MonadPlus (PEval abt p m) where
mzero = empty -- aka "bot"
mplus = (<|>) -- aka "lub"
instance (ABT Term abt) => EvaluationMonad abt (PEval abt p m) p where
freshNat =
PEval $ \c (ListContext i ss) ->
c i (ListContext (i+1) ss)
unsafePush s =
PEval $ \c (ListContext i ss) ->
c () (ListContext i (s:ss))
-- N.B., the use of 'reverse' is necessary so that the order
-- of pushing matches that of 'pushes'
unsafePushes ss =
PEval $ \c (ListContext i ss') ->
c () (ListContext i (reverse ss ++ ss'))
select x p = loop []
where
-- TODO: use a DList to avoid reversing inside 'unsafePushes'
loop ss = do
ms <- unsafePop
case ms of
Nothing -> do
unsafePushes ss
return Nothing
Just s ->
-- Alas, @p@ will have to recheck 'isBoundBy'
-- in order to grab the 'Refl' proof we erased;
-- but there's nothing to be done for it.
case x `isBoundBy` s >> p s of
Nothing -> loop (s:ss) -- BUG: we only want to loop if @x@ isn't bound by @s@; if it is bound but @p@ fails (e.g., because @s@ is 'Stuff1'), then we should fail/stop (thus the return type should be @2+r@ to distinguish no-match = free vs failed-match = bound-but-inalterable)
Just mr -> do
r <- mr
unsafePushes ss
return (Just r)
-- | Not exported because we only need it for defining 'select' on 'PEval'.
unsafePop :: PEval abt p m (Maybe (Statement abt Location p))
unsafePop =
PEval $ \c h@(ListContext i ss) ->
case ss of
[] -> c Nothing h
s:ss' -> c (Just s) (ListContext i ss')
----------------------------------------------------------------
----------------------------------------------------------------
-- | It is impossible to satisfy the constraints, or at least we
-- give up on trying to do so. This function is identical to 'empty'
-- and 'mzero' for 'PEval'; we just give it its own name since this is
-- the name used in our papers.
--
-- TODO: add some sort of trace information so we can get a better
-- idea what caused a disintegration to fail.
bot :: (ABT Term abt, Alternative m) => PEval abt p m a
bot = empty
{-
-- BUG: no longer typechecks after splitting 'Reject_' out from 'Superpose_'
-- | The empty measure is a solution to the constraints.
reject :: (ABT Term abt) => PEval abt p m a
reject = PEval $ \_ _ -> return . P.reject $ SMeasure sing
-}
-- Something essentially like this function was called @insert_@
-- in the finally-tagless code.
--
-- | Emit some code that binds a variable, and return the variable
-- thus bound. The function says what to wrap the result of the
-- continuation with; i.e., what we're actually emitting.
emit
:: (ABT Term abt, Functor m)
=> Text
-> Sing a
-> (forall r. P p abt '[a] r -> P p abt '[] r)
-> PEval abt p m (Variable a)
emit hint typ f = do
x <- freshVar hint typ
PEval $ \c h -> (f . mapP (bind x)) <$> c x h
-- This function was called @lift@ in the finally-tagless code.
-- | Emit an 'MBind' (i.e., \"@m >>= \x ->@\") and return the
-- variable thus bound (i.e., @x@).
emitMBind
:: (ABT Term abt, Functor m)
=> abt '[] ('HMeasure a)
-> PEval abt 'Impure m (Variable a)
emitMBind m =
emit Text.empty (sUnMeasure $ typeOf m) $ \(PImpure e) ->
PImpure $ syn (MBind :$ m :* e :* End)
-- | A smart constructor for emitting let-bindings. If the input
-- is already a variable then we just return it; otherwise we emit
-- the let-binding. N.B., this function provides the invariant that
-- the result is in fact a variable; whereas 'emitLet'' does not.
emitLet
:: (ABT Term abt, Functor m) => abt '[] a -> PEval abt p m (Variable a)
emitLet e =
caseVarSyn e return $ \_ ->
-- N.B., must use the second @($)@ here because rank-2 polymorphism
emit Text.empty (typeOf e) $ mapP $ \m ->
syn (Let_ :$ e :* m :* End)
-- | A smart constructor for emitting let-bindings. If the input
-- is already a variable or a literal constant, then we just return
-- it; otherwise we emit the let-binding. N.B., this function
-- provides weaker guarantees on the type of the result; if you
-- require the result to always be a variable, then see 'emitLet'
-- instead.
emitLet'
:: (ABT Term abt, Functor m) => abt '[] a -> PEval abt p m (abt '[] a)
emitLet' e =
caseVarSyn e (const $ return e) $ \t ->
case t of
Literal_ _ -> return e
_ -> do
-- N.B., must use the second @($)@ here because rank-2 polymorphism
x <- emit Text.empty (typeOf e) $ mapP $ \m ->
syn (Let_ :$ e :* m :* End)
return (var x)
-- | A smart constructor for emitting \"unpair\". If the input
-- argument is actually a constructor then we project out the two
-- components; otherwise we emit the case-binding and return the
-- two variables.
emitUnpair
:: (ABT Term abt, Applicative m)
=> Whnf abt (HPair a b)
-> PEval abt p m (abt '[] a, abt '[] b)
emitUnpair (Head_ w) = return $ reifyPair w
emitUnpair (Neutral e) = do
let (a,b) = sUnPair (typeOf e)
x <- freshVar Text.empty a
y <- freshVar Text.empty b
emitUnpair_ x y e
emitUnpair_
:: forall abt p m a b
. (ABT Term abt, Applicative m)
=> Variable a
-> Variable b
-> abt '[] (HPair a b)
-> PEval abt p m (abt '[] a, abt '[] b)
emitUnpair_ x y = loop
where
done :: abt '[] (HPair a b) -> PEval abt p m (abt '[] a, abt '[] b)
done e =
#ifdef __TRACE_DISINTEGRATE__
trace "-- emitUnpair: done (term is not Datum_ nor Case_)" $
#endif
PEval $ \c h ->
mapP ( syn
. Case_ e
. (:[])
. Branch (pPair PVar PVar)
. bind x
. bind y
) <$> c (var x, var y) h
loop :: abt '[] (HPair a b) -> PEval abt p m (abt '[] a, abt '[] b)
loop e0 =
caseVarSyn e0 (done . var) $ \t ->
case t of
Datum_ d -> do
#ifdef __TRACE_DISINTEGRATE__
trace "-- emitUnpair: found Datum_" $ return ()
#endif
return $ reifyPair (WDatum d)
Case_ e bs -> do
#ifdef __TRACE_DISINTEGRATE__
trace "-- emitUnpair: going under Case_" $ return ()
#endif
-- TODO: we want this to duplicate the current
-- continuation for (the evaluation of @loop@ in)
-- all branches. So far our traces all end up
-- returning @bot@ on the first branch, and hence
-- @bot@ for the whole case-expression, so we can't
-- quite tell whether it does what is intended.
--
-- N.B., the only 'PEval'-effects in 'applyBranch'
-- are to freshen variables; thus this use of
-- 'traverse' is perfectly sound.
emitCaseWith loop e bs
_ -> done e0
-- TODO: emitUneither
-- This function was called @insert_@ in the old finally-tagless code.
-- | Emit some code that doesn't bind any variables. This function
-- provides an optimisation over using 'emit' and then discarding
-- the generated variable.
emit_
:: (ABT Term abt, Functor m)
=> (forall r. P p abt '[] r -> P p abt '[] r)
-> PEval abt p m ()
emit_ f = PEval $ \c h -> f <$> c () h
-- | Emit an 'MBind' that discards its result (i.e., \"@m >>@\").
-- We restrict the type of the argument to be 'HUnit' so as to avoid
-- accidentally dropping things.
emitMBind_
:: (ABT Term abt, Functor m)
=> abt '[] ('HMeasure HUnit)
-> PEval abt 'Impure m ()
emitMBind_ m = emit_ $ mapPImpure (m P.>>)
-- TODO: if the argument is a value, then we can evaluate the 'P.if_' immediately rather than emitting it.
-- | Emit an assertion that the condition is true.
emitGuard
:: (ABT Term abt, Functor m)
=> abt '[] HBool
-> PEval abt 'Impure m ()
emitGuard b = emit_ $ mapPImpure (P.withGuard b)
-- == emit_ $ \m -> P.if_ b m P.reject
-- TODO: if the argument is the literal 1, then we can avoid emitting anything.
emitWeight
:: (ABT Term abt, Functor m)
=> abt '[] 'HProb
-> PEval abt 'Impure m ()
emitWeight w = emit_ $ mapPImpure (P.withWeight w)
-- N.B., this use of 'T.traverse' is definitely correct. It's
-- sequentializing @t [abt '[] ('HMeasure a)]@ into @[t (abt '[]
-- ('HMeasure a))]@ by chosing one of the possibilities at each
-- position in @t@. No heap\/context effects can escape to mess
-- things up. In contrast, using 'T.traverse' to sequentialize @t
-- (PEval abt a)@ as @PEval abt (t a)@ is /wrong/! Doing that would give
-- the conjunctive semantics where we have effects from one position
-- in @t@ escape to affect the other positions. This has to do with
-- the general issue in partial evaluation where we need to duplicate
-- downstream work (as we do by passing the same heap to everyone)
-- because there's no general way to combing the resulting heaps
-- for each branch.
--
-- | Run each of the elements of the traversable using the same
-- heap and continuation for each one, then pass the results to a
-- function for emitting code.
emitFork_
:: (ABT Term abt, Applicative m, T.Traversable t)
=> (forall r. t (P p abt '[] r) -> P p abt '[] r)
-> t (PEval abt p m a)
-> PEval abt p m a
emitFork_ f ms =
PEval $ \c h -> f <$> T.traverse (\m -> unPEval m c h) ms
-- | Emit a 'Superpose_' of the alternatives, each with unit weight.
emitSuperpose
:: (ABT Term abt, Functor m)
=> [abt '[] ('HMeasure a)]
-> PEval abt 'Impure m (Variable a)
emitSuperpose [] = error "BUG: emitSuperpose: can't use Prelude.superpose because it'll throw an error"
emitSuperpose [e] = emitMBind e
emitSuperpose es =
emitMBind . P.superpose . fmap ((,) P.one) $ NE.fromList es
-- | Emit a 'Superpose_' of the alternatives, each with unit weight.
choose
:: (ABT Term abt, Applicative m)
=> [PEval abt 'Impure m a]
-> PEval abt 'Impure m a
choose [] = error "BUG: choose: can't use Prelude.superpose because it'll throw an error"
choose [m] = m
choose ms =
emitFork_
(PImpure . P.superpose . fmap ((,) P.one . unPImpure) . NE.fromList)
ms
-- | Given some function we can call on the bodies of the branches,
-- freshen all the pattern-bound variables and then run the function
-- on all the branches in parallel (i.e., with the same continuation
-- and heap) and then emit a case-analysis expression with the
-- results of the continuations as the bodies of the branches. This
-- function is useful for when we really do want to emit a 'Case_'
-- expression, rather than doing the superpose of guard patterns
-- thing that 'constrainValue' does.
--
-- N.B., this function assumes (and does not verify) that the second
-- argument is emissible. So callers must guarantee this invariant,
-- by calling 'atomize' as necessary.
--
-- TODO: capture the emissibility requirement on the second argument
-- in the types.
emitCaseWith
:: (ABT Term abt, Applicative m)
=> (abt '[] b -> PEval abt p m r)
-> abt '[] a
-> [Branch a abt b]
-> PEval abt p m r
emitCaseWith f e bs = do
error "TODO: emitCaseWith"
{-
-- BUG: this doesn't typecheck with keeping @p@ polymorphic...
gms <- T.for bs $ \(Branch pat body) ->
let (vars, body') = caseBinds body
in (\vars' ->
let rho = toAssocs vars (fmap11 var vars')
in GBranch pat vars' (f $ substs rho body')
) <$> freshenVars vars
PEval $ \c h ->
(syn . Case_ e) <$> T.for gms (\gm ->
fromGBranch <$> T.for gm (\m ->
unPEval m c h))
{-# INLINE emitCaseWith #-}
-}
-- HACK: to get the one case we really need to work at least.
emitCaseWith_Impure
:: (ABT Term abt, Applicative m)
=> (abt '[] b -> PEval abt 'Impure m r)
-> abt '[] a
-> [Branch a abt b]
-> PEval abt 'Impure m r
emitCaseWith_Impure f e bs = do
gms <- T.for bs $ \(Branch pat body) ->
let (vars, body') = caseBinds body
in (\vars' ->
let rho = toAssocs1 vars (fmap11 var vars')
in GBranch pat vars' (f $ substs rho body')
) <$> freshenVars vars
PEval $ \c h ->
(PImpure . syn . Case_ e) <$> T.for gms (\gm ->
fromGBranch <$> T.for gm (\m ->
unPImpure <$> unPEval m c h))
{-# INLINE emitCaseWith_Impure #-}
----------------------------------------------------------------
----------------------------------------------------------- fin.
| zachsully/hakaru | haskell/Language/Hakaru/Evaluation/PEvalMonad.hs | bsd-3-clause | 24,323 | 0 | 21 | 6,637 | 5,569 | 2,925 | 2,644 | 359 | 6 |
module Main where
import Idris.AbsSyntax
import Idris.Core.TT
import Idris.ElabDecls
import Idris.Main
import Idris.Options
import IRTS.CodegenC
import IRTS.Compiler
import Util.System
import Paths_idris
import Control.Monad
import System.Environment
import System.Exit
data Opts = Opts { inputs :: [FilePath],
interface :: Bool,
output :: FilePath }
showUsage = do putStrLn "A code generator which is intended to be called by the compiler, not by a user."
putStrLn "Usage: idris-codegen-c <ibc-files> [-o <output-file>]"
exitWith ExitSuccess
getOpts :: IO Opts
getOpts = do xs <- getArgs
return $ process (Opts [] False "a.out") xs
where
process opts ("-o":o:xs) = process (opts { output = o }) xs
process opts ("--interface":xs) = process (opts { interface = True }) xs
process opts (x:xs) = process (opts { inputs = x:inputs opts }) xs
process opts [] = opts
c_main :: Opts -> Idris ()
c_main opts = do runIO setupBundledCC
elabPrims
loadInputs (inputs opts) Nothing
mainProg <- if interface opts
then liftM Just elabMain
else return Nothing
ir <- compile (Via IBCFormat "c") (output opts) mainProg
runIO $ codegenC ir
main :: IO ()
main = do opts <- getOpts
if (null (inputs opts))
then showUsage
else runMain (c_main opts)
| markuspf/Idris-dev | codegen/idris-codegen-c/Main.hs | bsd-3-clause | 1,524 | 0 | 12 | 489 | 447 | 230 | 217 | 40 | 4 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
module VarEnv (
-- * Var, Id and TyVar environments (maps)
VarEnv, IdEnv, TyVarEnv, CoVarEnv, TyCoVarEnv,
-- ** Manipulating these environments
emptyVarEnv, unitVarEnv, mkVarEnv, mkVarEnv_Directly,
elemVarEnv, varEnvElts, varEnvKeys, varEnvToList,
extendVarEnv, extendVarEnv_C, extendVarEnv_Acc, extendVarEnv_Directly,
extendVarEnvList,
plusVarEnv, plusVarEnv_C, plusVarEnv_CD, alterVarEnv,
delVarEnvList, delVarEnv, delVarEnv_Directly,
minusVarEnv, intersectsVarEnv,
lookupVarEnv, lookupVarEnv_NF, lookupWithDefaultVarEnv,
mapVarEnv, zipVarEnv,
modifyVarEnv, modifyVarEnv_Directly,
isEmptyVarEnv, foldVarEnv, foldVarEnv_Directly,
elemVarEnvByKey, lookupVarEnv_Directly,
filterVarEnv, filterVarEnv_Directly, restrictVarEnv,
partitionVarEnv,
-- * Deterministic Var environments (maps)
DVarEnv,
-- ** Manipulating these environments
emptyDVarEnv,
extendDVarEnv,
lookupDVarEnv,
foldDVarEnv,
-- * The InScopeSet type
InScopeSet,
-- ** Operations on InScopeSets
emptyInScopeSet, mkInScopeSet, delInScopeSet,
extendInScopeSet, extendInScopeSetList, extendInScopeSetSet,
getInScopeVars, lookupInScope, lookupInScope_Directly,
unionInScope, elemInScopeSet, uniqAway,
varSetInScope,
-- * The RnEnv2 type
RnEnv2,
-- ** Operations on RnEnv2s
mkRnEnv2, rnBndr2, rnBndrs2, rnBndr2_var,
rnOccL, rnOccR, inRnEnvL, inRnEnvR, rnOccL_maybe, rnOccR_maybe,
rnBndrL, rnBndrR, nukeRnEnvL, nukeRnEnvR, rnSwap,
delBndrL, delBndrR, delBndrsL, delBndrsR,
addRnInScopeSet,
rnEtaL, rnEtaR,
rnInScope, rnInScopeSet, lookupRnInScope,
rnEnvL, rnEnvR,
-- * TidyEnv and its operation
TidyEnv,
emptyTidyEnv
) where
import OccName
import Var
import VarSet
import UniqFM
import UniqDFM
import Unique
import Util
import Maybes
import Outputable
import StaticFlags
{-
************************************************************************
* *
In-scope sets
* *
************************************************************************
-}
-- | A set of variables that are in scope at some point
-- "Secrets of the Glasgow Haskell Compiler inliner" Section 3. provides
-- the motivation for this abstraction.
data InScopeSet = InScope (VarEnv Var) {-# UNPACK #-} !Int
-- The (VarEnv Var) is just a VarSet. But we write it like
-- this to remind ourselves that you can look up a Var in
-- the InScopeSet. Typically the InScopeSet contains the
-- canonical version of the variable (e.g. with an informative
-- unfolding), so this lookup is useful.
--
-- INVARIANT: the VarEnv maps (the Unique of) a variable to
-- a variable with the same Unique. (This was not
-- the case in the past, when we had a grevious hack
-- mapping var1 to var2.
--
-- The Int is a kind of hash-value used by uniqAway
-- For example, it might be the size of the set
-- INVARIANT: it's not zero; we use it as a multiplier in uniqAway
instance Outputable InScopeSet where
ppr (InScope s _) = text "InScope"
<+> braces (fsep (map (ppr . Var.varName) (varSetElems s)))
-- In-scope sets get big, and with -dppr-debug
-- the output is overwhelming
emptyInScopeSet :: InScopeSet
emptyInScopeSet = InScope emptyVarSet 1
getInScopeVars :: InScopeSet -> VarEnv Var
getInScopeVars (InScope vs _) = vs
mkInScopeSet :: VarEnv Var -> InScopeSet
mkInScopeSet in_scope = InScope in_scope 1
extendInScopeSet :: InScopeSet -> Var -> InScopeSet
extendInScopeSet (InScope in_scope n) v = InScope (extendVarEnv in_scope v v) (n + 1)
extendInScopeSetList :: InScopeSet -> [Var] -> InScopeSet
extendInScopeSetList (InScope in_scope n) vs
= InScope (foldl (\s v -> extendVarEnv s v v) in_scope vs)
(n + length vs)
extendInScopeSetSet :: InScopeSet -> VarEnv Var -> InScopeSet
extendInScopeSetSet (InScope in_scope n) vs
= InScope (in_scope `plusVarEnv` vs) (n + sizeUFM vs)
delInScopeSet :: InScopeSet -> Var -> InScopeSet
delInScopeSet (InScope in_scope n) v = InScope (in_scope `delVarEnv` v) n
elemInScopeSet :: Var -> InScopeSet -> Bool
elemInScopeSet v (InScope in_scope _) = v `elemVarEnv` in_scope
-- | Look up a variable the 'InScopeSet'. This lets you map from
-- the variable's identity (unique) to its full value.
lookupInScope :: InScopeSet -> Var -> Maybe Var
lookupInScope (InScope in_scope _) v = lookupVarEnv in_scope v
lookupInScope_Directly :: InScopeSet -> Unique -> Maybe Var
lookupInScope_Directly (InScope in_scope _) uniq
= lookupVarEnv_Directly in_scope uniq
unionInScope :: InScopeSet -> InScopeSet -> InScopeSet
unionInScope (InScope s1 _) (InScope s2 n2)
= InScope (s1 `plusVarEnv` s2) n2
varSetInScope :: VarSet -> InScopeSet -> Bool
varSetInScope vars (InScope s1 _) = vars `subVarSet` s1
-- | @uniqAway in_scope v@ finds a unique that is not used in the
-- in-scope set, and gives that to v.
uniqAway :: InScopeSet -> Var -> Var
-- It starts with v's current unique, of course, in the hope that it won't
-- have to change, and thereafter uses a combination of that and the hash-code
-- found in the in-scope set
uniqAway in_scope var
| var `elemInScopeSet` in_scope = uniqAway' in_scope var -- Make a new one
| otherwise = var -- Nothing to do
uniqAway' :: InScopeSet -> Var -> Var
-- This one *always* makes up a new variable
uniqAway' (InScope set n) var
= try 1
where
orig_unique = getUnique var
try k
| debugIsOn && (k > 1000)
= pprPanic "uniqAway loop:" (ppr k <+> text "tries" <+> ppr var <+> int n)
| uniq `elemVarSetByKey` set = try (k + 1)
| debugIsOn && opt_PprStyle_Debug && (k > 3)
= pprTrace "uniqAway:" (ppr k <+> text "tries" <+> ppr var <+> int n)
setVarUnique var uniq
| otherwise = setVarUnique var uniq
where
uniq = deriveUnique orig_unique (n * k)
{-
************************************************************************
* *
Dual renaming
* *
************************************************************************
-}
-- | When we are comparing (or matching) types or terms, we are faced with
-- \"going under\" corresponding binders. E.g. when comparing:
--
-- > \x. e1 ~ \y. e2
--
-- Basically we want to rename [@x@ -> @y@] or [@y@ -> @x@], but there are lots of
-- things we must be careful of. In particular, @x@ might be free in @e2@, or
-- y in @e1@. So the idea is that we come up with a fresh binder that is free
-- in neither, and rename @x@ and @y@ respectively. That means we must maintain:
--
-- 1. A renaming for the left-hand expression
--
-- 2. A renaming for the right-hand expressions
--
-- 3. An in-scope set
--
-- Furthermore, when matching, we want to be able to have an 'occurs check',
-- to prevent:
--
-- > \x. f ~ \y. y
--
-- matching with [@f@ -> @y@]. So for each expression we want to know that set of
-- locally-bound variables. That is precisely the domain of the mappings 1.
-- and 2., but we must ensure that we always extend the mappings as we go in.
--
-- All of this information is bundled up in the 'RnEnv2'
data RnEnv2
= RV2 { envL :: VarEnv Var -- Renaming for Left term
, envR :: VarEnv Var -- Renaming for Right term
, in_scope :: InScopeSet } -- In scope in left or right terms
-- The renamings envL and envR are *guaranteed* to contain a binding
-- for every variable bound as we go into the term, even if it is not
-- renamed. That way we can ask what variables are locally bound
-- (inRnEnvL, inRnEnvR)
mkRnEnv2 :: InScopeSet -> RnEnv2
mkRnEnv2 vars = RV2 { envL = emptyVarEnv
, envR = emptyVarEnv
, in_scope = vars }
addRnInScopeSet :: RnEnv2 -> VarEnv Var -> RnEnv2
addRnInScopeSet env vs
| isEmptyVarEnv vs = env
| otherwise = env { in_scope = extendInScopeSetSet (in_scope env) vs }
rnInScope :: Var -> RnEnv2 -> Bool
rnInScope x env = x `elemInScopeSet` in_scope env
rnInScopeSet :: RnEnv2 -> InScopeSet
rnInScopeSet = in_scope
-- | Retrieve the left mapping
rnEnvL :: RnEnv2 -> VarEnv Var
rnEnvL = envL
-- | Retrieve the right mapping
rnEnvR :: RnEnv2 -> VarEnv Var
rnEnvR = envR
rnBndrs2 :: RnEnv2 -> [Var] -> [Var] -> RnEnv2
-- ^ Applies 'rnBndr2' to several variables: the two variable lists must be of equal length
rnBndrs2 env bsL bsR = foldl2 rnBndr2 env bsL bsR
rnBndr2 :: RnEnv2 -> Var -> Var -> RnEnv2
-- ^ @rnBndr2 env bL bR@ goes under a binder @bL@ in the Left term,
-- and binder @bR@ in the Right term.
-- It finds a new binder, @new_b@,
-- and returns an environment mapping @bL -> new_b@ and @bR -> new_b@
rnBndr2 env bL bR = fst $ rnBndr2_var env bL bR
rnBndr2_var :: RnEnv2 -> Var -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but returns the new variable as well as the
-- new environment
rnBndr2_var (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL bR
= (RV2 { envL = extendVarEnv envL bL new_b -- See Note
, envR = extendVarEnv envR bR new_b -- [Rebinding]
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
-- Find a new binder not in scope in either term
new_b | not (bL `elemInScopeSet` in_scope) = bL
| not (bR `elemInScopeSet` in_scope) = bR
| otherwise = uniqAway' in_scope bL
-- Note [Rebinding]
-- If the new var is the same as the old one, note that
-- the extendVarEnv *deletes* any current renaming
-- E.g. (\x. \x. ...) ~ (\y. \z. ...)
--
-- Inside \x \y { [x->y], [y->y], {y} }
-- \x \z { [x->x], [y->y, z->x], {y,x} }
rnBndrL :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but used when there's a binder on the left
-- side only.
rnBndrL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL
= (RV2 { envL = extendVarEnv envL bL new_b
, envR = envR
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bL
rnBndrR :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but used when there's a binder on the right
-- side only.
rnBndrR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR
= (RV2 { envR = extendVarEnv envR bR new_b
, envL = envL
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bR
rnEtaL :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndrL' but used for eta expansion
-- See Note [Eta expansion]
rnEtaL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL
= (RV2 { envL = extendVarEnv envL bL new_b
, envR = extendVarEnv envR new_b new_b -- Note [Eta expansion]
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bL
rnEtaR :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but used for eta expansion
-- See Note [Eta expansion]
rnEtaR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR
= (RV2 { envL = extendVarEnv envL new_b new_b -- Note [Eta expansion]
, envR = extendVarEnv envR bR new_b
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bR
delBndrL, delBndrR :: RnEnv2 -> Var -> RnEnv2
delBndrL rn@(RV2 { envL = env, in_scope = in_scope }) v
= rn { envL = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v }
delBndrR rn@(RV2 { envR = env, in_scope = in_scope }) v
= rn { envR = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v }
delBndrsL, delBndrsR :: RnEnv2 -> [Var] -> RnEnv2
delBndrsL rn@(RV2 { envL = env, in_scope = in_scope }) v
= rn { envL = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v }
delBndrsR rn@(RV2 { envR = env, in_scope = in_scope }) v
= rn { envR = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v }
rnOccL, rnOccR :: RnEnv2 -> Var -> Var
-- ^ Look up the renaming of an occurrence in the left or right term
rnOccL (RV2 { envL = env }) v = lookupVarEnv env v `orElse` v
rnOccR (RV2 { envR = env }) v = lookupVarEnv env v `orElse` v
rnOccL_maybe, rnOccR_maybe :: RnEnv2 -> Var -> Maybe Var
-- ^ Look up the renaming of an occurrence in the left or right term
rnOccL_maybe (RV2 { envL = env }) v = lookupVarEnv env v
rnOccR_maybe (RV2 { envR = env }) v = lookupVarEnv env v
inRnEnvL, inRnEnvR :: RnEnv2 -> Var -> Bool
-- ^ Tells whether a variable is locally bound
inRnEnvL (RV2 { envL = env }) v = v `elemVarEnv` env
inRnEnvR (RV2 { envR = env }) v = v `elemVarEnv` env
lookupRnInScope :: RnEnv2 -> Var -> Var
lookupRnInScope env v = lookupInScope (in_scope env) v `orElse` v
nukeRnEnvL, nukeRnEnvR :: RnEnv2 -> RnEnv2
-- ^ Wipe the left or right side renaming
nukeRnEnvL env = env { envL = emptyVarEnv }
nukeRnEnvR env = env { envR = emptyVarEnv }
rnSwap :: RnEnv2 -> RnEnv2
-- ^ swap the meaning of left and right
rnSwap (RV2 { envL = envL, envR = envR, in_scope = in_scope })
= RV2 { envL = envR, envR = envL, in_scope = in_scope }
{-
Note [Eta expansion]
~~~~~~~~~~~~~~~~~~~~
When matching
(\x.M) ~ N
we rename x to x' with, where x' is not in scope in
either term. Then we want to behave as if we'd seen
(\x'.M) ~ (\x'.N x')
Since x' isn't in scope in N, the form (\x'. N x') doesn't
capture any variables in N. But we must nevertheless extend
the envR with a binding [x' -> x'], to support the occurs check.
For example, if we don't do this, we can get silly matches like
forall a. (\y.a) ~ v
succeeding with [a -> v y], which is bogus of course.
************************************************************************
* *
Tidying
* *
************************************************************************
-}
-- | When tidying up print names, we keep a mapping of in-scope occ-names
-- (the 'TidyOccEnv') and a Var-to-Var of the current renamings
type TidyEnv = (TidyOccEnv, VarEnv Var)
emptyTidyEnv :: TidyEnv
emptyTidyEnv = (emptyTidyOccEnv, emptyVarEnv)
{-
************************************************************************
* *
\subsection{@VarEnv@s}
* *
************************************************************************
-}
type VarEnv elt = UniqFM elt
type IdEnv elt = VarEnv elt
type TyVarEnv elt = VarEnv elt
type TyCoVarEnv elt = VarEnv elt
type CoVarEnv elt = VarEnv elt
emptyVarEnv :: VarEnv a
mkVarEnv :: [(Var, a)] -> VarEnv a
mkVarEnv_Directly :: [(Unique, a)] -> VarEnv a
zipVarEnv :: [Var] -> [a] -> VarEnv a
unitVarEnv :: Var -> a -> VarEnv a
alterVarEnv :: (Maybe a -> Maybe a) -> VarEnv a -> Var -> VarEnv a
extendVarEnv :: VarEnv a -> Var -> a -> VarEnv a
extendVarEnv_C :: (a->a->a) -> VarEnv a -> Var -> a -> VarEnv a
extendVarEnv_Acc :: (a->b->b) -> (a->b) -> VarEnv b -> Var -> a -> VarEnv b
extendVarEnv_Directly :: VarEnv a -> Unique -> a -> VarEnv a
plusVarEnv :: VarEnv a -> VarEnv a -> VarEnv a
extendVarEnvList :: VarEnv a -> [(Var, a)] -> VarEnv a
lookupVarEnv_Directly :: VarEnv a -> Unique -> Maybe a
filterVarEnv_Directly :: (Unique -> a -> Bool) -> VarEnv a -> VarEnv a
delVarEnv_Directly :: VarEnv a -> Unique -> VarEnv a
partitionVarEnv :: (a -> Bool) -> VarEnv a -> (VarEnv a, VarEnv a)
restrictVarEnv :: VarEnv a -> VarSet -> VarEnv a
delVarEnvList :: VarEnv a -> [Var] -> VarEnv a
delVarEnv :: VarEnv a -> Var -> VarEnv a
minusVarEnv :: VarEnv a -> VarEnv b -> VarEnv a
intersectsVarEnv :: VarEnv a -> VarEnv a -> Bool
plusVarEnv_C :: (a -> a -> a) -> VarEnv a -> VarEnv a -> VarEnv a
plusVarEnv_CD :: (a -> a -> a) -> VarEnv a -> a -> VarEnv a -> a -> VarEnv a
mapVarEnv :: (a -> b) -> VarEnv a -> VarEnv b
modifyVarEnv :: (a -> a) -> VarEnv a -> Var -> VarEnv a
varEnvElts :: VarEnv a -> [a]
varEnvKeys :: VarEnv a -> [Unique]
varEnvToList :: VarEnv a -> [(Unique, a)]
isEmptyVarEnv :: VarEnv a -> Bool
lookupVarEnv :: VarEnv a -> Var -> Maybe a
filterVarEnv :: (a -> Bool) -> VarEnv a -> VarEnv a
lookupVarEnv_NF :: VarEnv a -> Var -> a
lookupWithDefaultVarEnv :: VarEnv a -> a -> Var -> a
elemVarEnv :: Var -> VarEnv a -> Bool
elemVarEnvByKey :: Unique -> VarEnv a -> Bool
foldVarEnv :: (a -> b -> b) -> b -> VarEnv a -> b
foldVarEnv_Directly :: (Unique -> a -> b -> b) -> b -> VarEnv a -> b
elemVarEnv = elemUFM
elemVarEnvByKey = elemUFM_Directly
alterVarEnv = alterUFM
extendVarEnv = addToUFM
extendVarEnv_C = addToUFM_C
extendVarEnv_Acc = addToUFM_Acc
extendVarEnv_Directly = addToUFM_Directly
extendVarEnvList = addListToUFM
plusVarEnv_C = plusUFM_C
plusVarEnv_CD = plusUFM_CD
delVarEnvList = delListFromUFM
delVarEnv = delFromUFM
minusVarEnv = minusUFM
intersectsVarEnv e1 e2 = not (isEmptyVarEnv (e1 `intersectUFM` e2))
plusVarEnv = plusUFM
lookupVarEnv = lookupUFM
filterVarEnv = filterUFM
lookupWithDefaultVarEnv = lookupWithDefaultUFM
mapVarEnv = mapUFM
mkVarEnv = listToUFM
mkVarEnv_Directly= listToUFM_Directly
emptyVarEnv = emptyUFM
varEnvElts = eltsUFM
varEnvKeys = keysUFM
varEnvToList = ufmToList
unitVarEnv = unitUFM
isEmptyVarEnv = isNullUFM
foldVarEnv = foldUFM
foldVarEnv_Directly = foldUFM_Directly
lookupVarEnv_Directly = lookupUFM_Directly
filterVarEnv_Directly = filterUFM_Directly
delVarEnv_Directly = delFromUFM_Directly
partitionVarEnv = partitionUFM
restrictVarEnv env vs = filterVarEnv_Directly keep env
where
keep u _ = u `elemVarSetByKey` vs
zipVarEnv tyvars tys = mkVarEnv (zipEqual "zipVarEnv" tyvars tys)
lookupVarEnv_NF env id = case lookupVarEnv env id of
Just xx -> xx
Nothing -> panic "lookupVarEnv_NF: Nothing"
{-
@modifyVarEnv@: Look up a thing in the VarEnv,
then mash it with the modify function, and put it back.
-}
modifyVarEnv mangle_fn env key
= case (lookupVarEnv env key) of
Nothing -> env
Just xx -> extendVarEnv env key (mangle_fn xx)
modifyVarEnv_Directly :: (a -> a) -> UniqFM a -> Unique -> UniqFM a
modifyVarEnv_Directly mangle_fn env key
= case (lookupUFM_Directly env key) of
Nothing -> env
Just xx -> addToUFM_Directly env key (mangle_fn xx)
-- Deterministic VarEnv
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need
-- DVarEnv.
type DVarEnv elt = UniqDFM elt
emptyDVarEnv :: DVarEnv a
emptyDVarEnv = emptyUDFM
extendDVarEnv :: DVarEnv a -> Var -> a -> DVarEnv a
extendDVarEnv = addToUDFM
lookupDVarEnv :: DVarEnv a -> Var -> Maybe a
lookupDVarEnv = lookupUDFM
foldDVarEnv :: (a -> b -> b) -> b -> DVarEnv a -> b
foldDVarEnv = foldUDFM
| oldmanmike/ghc | compiler/basicTypes/VarEnv.hs | bsd-3-clause | 19,905 | 0 | 14 | 5,290 | 4,299 | 2,385 | 1,914 | 283 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Trans.State
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : ross@soi.city.ac.uk
-- Stability : experimental
-- Portability : portable
--
-- State monads, passing an updatable state through a computation.
--
-- Some computations may not require the full power of state transformers:
--
-- * For a read-only state, see "Control.Monad.Trans.Reader".
--
-- * To accumulate a value without using it on the way, see
-- "Control.Monad.Trans.Writer".
--
-- This version is lazy; for a strict version, see
-- "Control.Monad.Trans.State.Strict", which has the same interface.
-----------------------------------------------------------------------------
module Control.Monad.Trans.State (
module Control.Monad.Trans.State.Lazy
) where
import Control.Monad.Trans.State.Lazy
| DavidAlphaFox/ghc | libraries/transformers/Control/Monad/Trans/State.hs | bsd-3-clause | 1,032 | 0 | 5 | 165 | 50 | 43 | 7 | 3 | 0 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pt-BR">
<title>Directory List v2.3</title>
<maps>
<homeID>directorylistv2_3</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/directorylistv2_3/src/main/javahelp/help_pt_BR/helpset_pt_BR.hs | apache-2.0 | 978 | 78 | 66 | 157 | 412 | 209 | 203 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Test.Ganeti.Query.Language
( testQuery_Language
, genFilter
, genJSValue
) where
import Test.QuickCheck
import Control.Applicative
import Control.Arrow (second)
import Text.JSON
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Ganeti.Query.Language
-- | Custom 'Filter' generator (top-level), which enforces a
-- (sane) limit on the depth of the generated filters.
genFilter :: Gen (Filter FilterField)
genFilter = choose (0, 10) >>= genFilter'
-- | Custom generator for filters that correctly halves the state of
-- the generators at each recursive step, per the QuickCheck
-- documentation, in order not to run out of memory.
genFilter' :: Int -> Gen (Filter FilterField)
genFilter' 0 =
oneof [ pure EmptyFilter
, TrueFilter <$> genName
, EQFilter <$> genName <*> value
, LTFilter <$> genName <*> value
, GTFilter <$> genName <*> value
, LEFilter <$> genName <*> value
, GEFilter <$> genName <*> value
, RegexpFilter <$> genName <*> arbitrary
, ContainsFilter <$> genName <*> value
]
where value = oneof [ QuotedString <$> genName
, NumericValue <$> arbitrary
]
genFilter' n =
oneof [ AndFilter <$> vectorOf n'' (genFilter' n')
, OrFilter <$> vectorOf n'' (genFilter' n')
, NotFilter <$> genFilter' n'
]
where n' = n `div` 2 -- sub-filter generator size
n'' = max n' 2 -- but we don't want empty or 1-element lists,
-- so use this for and/or filter list length
$(genArbitrary ''QueryTypeOp)
$(genArbitrary ''QueryTypeLuxi)
$(genArbitrary ''ItemType)
instance Arbitrary FilterRegex where
arbitrary = genName >>= mkRegex -- a name should be a good regex
$(genArbitrary ''ResultStatus)
$(genArbitrary ''FieldType)
$(genArbitrary ''FieldDefinition)
-- | Generates an arbitrary JSValue. We do this via a function a not
-- via arbitrary instance since that would require us to define an
-- arbitrary for JSValue, which can be recursive, entering the usual
-- problems with that; so we only generate the base types, not the
-- recursive ones, and not 'JSNull', which we can't use in a
-- 'RSNormal' 'ResultEntry'.
genJSValue :: Gen JSValue
genJSValue =
oneof [ JSBool <$> arbitrary
, JSRational <$> pure False <*> arbitrary
, JSString <$> (toJSString <$> arbitrary)
, (JSArray . map showJSON) <$> (arbitrary::Gen [Int])
, JSObject . toJSObject . map (second showJSON) <$>
(arbitrary::Gen [(String, Int)])
]
-- | Generates a 'ResultEntry' value.
genResultEntry :: Gen ResultEntry
genResultEntry = do
rs <- arbitrary
rv <- case rs of
RSNormal -> Just <$> genJSValue
_ -> pure Nothing
return $ ResultEntry rs rv
$(genArbitrary ''QueryFieldsResult)
-- | Tests that serialisation/deserialisation of filters is
-- idempotent.
prop_filter_serialisation :: Property
prop_filter_serialisation = forAll genFilter testSerialisation
-- | Tests that filter regexes are serialised correctly.
prop_filterregex_instances :: FilterRegex -> Property
prop_filterregex_instances rex =
printTestCase "failed JSON encoding" (testSerialisation rex)
-- | Tests 'ResultStatus' serialisation.
prop_resultstatus_serialisation :: ResultStatus -> Property
prop_resultstatus_serialisation = testSerialisation
-- | Tests 'FieldType' serialisation.
prop_fieldtype_serialisation :: FieldType -> Property
prop_fieldtype_serialisation = testSerialisation
-- | Tests 'FieldDef' serialisation.
prop_fielddef_serialisation :: FieldDefinition -> Property
prop_fielddef_serialisation = testSerialisation
-- | Tests 'ResultEntry' serialisation. Needed especially as this is
-- done manually, and not via buildObject (different serialisation
-- format).
prop_resultentry_serialisation :: Property
prop_resultentry_serialisation = forAll genResultEntry testSerialisation
-- | Tests 'FieldDef' serialisation. We use a made-up maximum limit of
-- 20 for the generator, since otherwise the lists become too long and
-- we don't care so much about list length but rather structure.
prop_fieldsresult_serialisation :: Property
prop_fieldsresult_serialisation =
forAll (resize 20 arbitrary::Gen QueryFieldsResult) testSerialisation
-- | Tests 'ItemType' serialisation.
prop_itemtype_serialisation :: ItemType -> Property
prop_itemtype_serialisation = testSerialisation
testSuite "Query/Language"
[ 'prop_filter_serialisation
, 'prop_filterregex_instances
, 'prop_resultstatus_serialisation
, 'prop_fieldtype_serialisation
, 'prop_fielddef_serialisation
, 'prop_resultentry_serialisation
, 'prop_fieldsresult_serialisation
, 'prop_itemtype_serialisation
]
| vladimir-ipatov/ganeti | test/hs/Test/Ganeti/Query/Language.hs | gpl-2.0 | 5,636 | 0 | 11 | 1,090 | 818 | 450 | 368 | 85 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
module Stack.Options.GhcBuildParser where
import Options.Applicative
import Options.Applicative.Types
import Stack.Options.Utils
import Stack.Prelude
import Stack.Types.CompilerBuild
-- | GHC build parser
ghcBuildParser :: Bool -> Parser CompilerBuild
ghcBuildParser hide =
option
readGHCBuild
(long "ghc-build" <> metavar "BUILD" <>
completeWith ["standard", "gmp4", "nopie", "tinfo6", "tinfo6-nopie", "ncurses6", "integersimple"] <>
help
"Specialized GHC build, e.g. 'gmp4' or 'standard' (usually auto-detected)" <>
hideMods hide
)
where
readGHCBuild = do
s <- readerAsk
case parseCompilerBuild s of
Left e -> readerError (show e)
Right v -> return v
| MichielDerhaeg/stack | src/Stack/Options/GhcBuildParser.hs | bsd-3-clause | 854 | 0 | 14 | 250 | 171 | 90 | 81 | 21 | 2 |
{-# OPTIONS_GHC -fdefer-typed-holes #-}
module T11274 where
data Asd = Asd
someHole = _asd
missingInstance :: Asd -> Asd -> Bool
missingInstance x y = x == y
| ezyang/ghc | testsuite/tests/typecheck/should_fail/T11274.hs | bsd-3-clause | 162 | 0 | 6 | 32 | 44 | 25 | 19 | 6 | 1 |
module T7164 where
class Foo m where
herp :: (a -> a) -> m b -> m b
derp :: m a
derp :: Int
derp = 123
| ghc-android/ghc | testsuite/tests/rename/should_fail/T7164.hs | bsd-3-clause | 113 | 0 | 9 | 38 | 57 | 30 | 27 | 6 | 1 |
{-# LANGUAGE MagicHash, UnboxedTuples, NoImplicitPrelude #-}
module GHC.Integer.Logarithms
( integerLogBase#
, integerLog2#
, wordLog2#
) where
import GHC.Prim
import GHC.Integer
import qualified GHC.Integer.Logarithms.Internals as I
-- | Calculate the integer logarithm for an arbitrary base.
-- The base must be greater than 1, the second argument, the number
-- whose logarithm is sought, should be positive, otherwise the
-- result is meaningless.
--
-- > base ^ integerLogBase# base m <= m < base ^ (integerLogBase# base m + 1)
--
-- for @base > 1@ and @m > 0@.
integerLogBase# :: Integer -> Integer -> Int#
integerLogBase# b m = case step b of
(# _, e #) -> e
where
step pw =
if m `ltInteger` pw
then (# m, 0# #)
else case step (pw `timesInteger` pw) of
(# q, e #) ->
if q `ltInteger` pw
then (# q, 2# *# e #)
else (# q `quotInteger` pw, 2# *# e +# 1# #)
-- | Calculate the integer base 2 logarithm of an 'Integer'.
-- The calculation is more efficient than for the general case,
-- on platforms with 32- or 64-bit words much more efficient.
--
-- The argument must be strictly positive, that condition is /not/ checked.
integerLog2# :: Integer -> Int#
integerLog2# = I.integerLog2#
-- | This function calculates the integer base 2 logarithm of a 'Word#'.
wordLog2# :: Word# -> Int#
wordLog2# = I.wordLog2#
| alexander-at-github/eta | libraries/integer/GHC/Integer/Logarithms.hs | bsd-3-clause | 1,466 | 0 | 14 | 386 | 224 | 137 | 87 | 23 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Monoid
import Web.Spock.Safe
import Lucid
import qualified Data.Text.Lazy as L
import Templates.Helpers (renderHtmlStrict)
main :: IO ()
main =
runSpock 3000 $ spockT id $ do
get root $ -- equivalent of get "/"
renderHtmlStrict $ p_ "Hello"
get ("hello" <//> var) $ \name ->
text ("Hello " <> name <> "!")
getpost "param" $ do
p <- param "url"
case p of
Nothing -> html "<form method='post'><input type='text' name='url' value='hello hi' /><button type='submit'>Submit</button></form>"
Just url -> renderHtmlStrict $ ullis_ $ toHtml (url :: L.Text)
ullis_ :: (Monoid s, Term arg s, Term s result) => arg -> result
ullis_ p = ul_ $ li_ p
<> li_ p
<> li_ p
getpost url action = do
get url action
post url action
| ifo/haskell-spock-lucid-url-shortener | src/Main.hs | isc | 869 | 0 | 17 | 225 | 274 | 137 | 137 | 26 | 2 |
module Simple where
import Protolude
import Data.Aeson (Value(..), decodeStrict, toJSON)
import qualified Data.ByteString as BS
import qualified Data.List.NonEmpty as NE
import Data.Maybe (fromMaybe)
import qualified JSONSchema.Draft4 as D4
badData :: Value
badData = toJSON [True, True]
example :: IO ()
example = do
bts <- BS.readFile "./examples/json/unique.json"
let schema = fromMaybe (panic "Invalid schema JSON.") (decodeStrict bts)
schemaWithURI = D4.SchemaWithURI
schema
Nothing -- This would be the URI of the schema
-- if it had one. It's used if the schema
-- has relative references to other
-- schemas.
-- Fetch any referenced schemas over HTTP, check that our original schema
-- itself is valid, and validate the data.
res <- D4.fetchHTTPAndValidate schemaWithURI badData
case res of
Right () -> panic "We validated bad data."
Left (D4.HVRequest _) -> panic ("Error fetching a referenced schema"
<> " (either during IO or parsing).")
Left (D4.HVSchema _) -> panic "Our 'schema' itself was invalid."
Left (D4.HVData (D4.Invalid _ _ failures)) ->
case NE.toList failures of
[D4.FailureUniqueItems _] -> pure () -- Success.
_ -> panic "We got a different failure than expected."
| seagreen/hjsonschema | examples/Simple.hs | mit | 1,569 | 0 | 15 | 558 | 301 | 160 | 141 | 26 | 5 |
module Hummingbird.Terminator ( run ) where
import Control.Concurrent (threadDelay)
import Control.Monad (forever)
import Network.MQTT.Broker
run :: Broker auth -> IO ()
run broker = forever $ do
terminateExpiredSessions broker
threadDelay 10000000
| lpeterse/haskell-hummingbird | src/Hummingbird/Terminator.hs | mit | 292 | 0 | 8 | 74 | 78 | 41 | 37 | 8 | 1 |
module Euler.Problem003Test (suite) where
import Test.Tasty (testGroup, TestTree)
import Test.Tasty.HUnit
import Euler.Problem003
suite :: TestTree
suite = testGroup "Problem003"
[ testCase "with composite 13195" test13195
]
test13195 :: Assertion
test13195 = 29 @=? solution 13195
| whittle/euler | test/Euler/Problem003Test.hs | mit | 322 | 0 | 7 | 75 | 75 | 43 | 32 | 9 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.