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 DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module YX.Type.ConfigFile
(
-- * Executable
ExecutableName
, Executable(..)
-- * Environment
, EnvironmentName
, Environment(..)
-- * ProjectConfig
, ProjectConfig(..)
, parseProjectConfig
, defaultEnvironment
, getEnvironment
)
where
import Control.Applicative ((<*>), pure)
import Control.Monad (join)
import Control.Monad.Fail (fail)
import Data.Bool (Bool(False))
import Data.Either (Either)
import Data.Eq (Eq)
import Data.Function (($))
import Data.Functor ((<$>))
import Data.Maybe (Maybe(Just, Nothing))
import Data.Monoid ((<>))
import Data.Tuple (uncurry)
import GHC.Generics (Generic)
import Text.Show (Show)
import System.IO (FilePath, IO)
import Data.Aeson
( FromJSON(parseJSON)
, ToJSON(toJSON)
, (.!=)
, (.:)
, (.:?)
, (.=)
)
import qualified Data.Aeson as Aeson (object, withObject)
import Data.Default (def)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap (empty, filter, lookup, toList)
import Data.Text (Text)
import qualified Data.Yaml as Yaml (ParseException, decodeFileEither)
import YX.Type.BuildTool (SomeBuildTool)
import YX.Type.CommandType (CommandType(Command))
import YX.Type.EnvVarTemplate (EnvVarTemplate)
import YX.Type.Scm (SomeScm)
-- {{{ Executable -------------------------------------------------------------
-- TODO: Move to a separate file.
type ExecutableName = Text
data Executable = Executable
{ _type :: CommandType
, _command :: Text
, _environment :: Maybe Environment
-- TODO:
--, _preHook :: Text
--, _postHook :: Text
}
deriving (Eq, Generic, Show)
instance FromJSON Executable where
parseJSON = Aeson.withObject "Executable" $ \o -> join $ mk
<$> o .:? "type" .!= def
<*> o .: "command"
<*> o .:? "env"
where
mk t c e = uncurry (\t' -> Executable t' c) <$> case (t, e) of
(Command, _) -> pure (t, e)
(_, Nothing) -> pure (t, e)
(_, Just _) -> fail "\"env\" can only be used wiht type=command"
instance ToJSON Executable where
toJSON Executable{..} = Aeson.object
[ "type" .= _type
, "command" .= _command
, "env" .= _environment
]
-- }}} Executable -------------------------------------------------------------
-- {{{ Environment ------------------------------------------------------------
-- TODO: Move to a separate file.
type EnvironmentName = Text
data Environment = Environment
{ _env :: [(EnvironmentName, Maybe EnvVarTemplate)]
, _bin :: HashMap ExecutableName Executable
, _isDefault :: Bool
}
deriving (Eq, Generic, Show)
instance FromJSON Environment where
parseJSON = Aeson.withObject "Environment" $ \o -> Environment
<$> o .:? "env" .!= []
<*> o .:? "bin" .!= HashMap.empty
<*> o .:? "is-default" .!= False
instance ToJSON Environment where
toJSON Environment{..} = Aeson.object
[ "env" .= _env
, "bin" .= _bin
, "is-default" .= _isDefault
]
-- }}} Environment ------------------------------------------------------------
-- {{{ ProjectConfig ----------------------------------------------------------
data ProjectConfig = ProjectConfig
{ _scm :: SomeScm
, _buildTool :: SomeBuildTool -- TODO: consider multiple build tools.
, _environments :: HashMap Text Environment
-- TODO:
--, _global :: GlobalEnvironment
}
deriving (Eq, Generic, Show)
instance FromJSON ProjectConfig where
parseJSON = Aeson.withObject "ProjectConfig" $ \o -> join $ mk
<$> o .:? "scm" .!= def
<*> o .:? "build-tool" .!= def
<*> o .:? "environment" .!= HashMap.empty
where
mk s b e = case HashMap.toList $ HashMap.filter _isDefault e of
[] -> err "no such environment was found"
[_] -> pure $ ProjectConfig s b e
_ -> err "multiple such environments were found"
err rest = fail
$ "Exactly one environment has to have 'is-default: true', but "
<> rest <> "."
instance ToJSON ProjectConfig where
toJSON ProjectConfig{..} = Aeson.object
[ "scm" .= _scm
, "build-tool" .= _buildTool
, "environment" .= _environments
]
parseProjectConfig :: FilePath -> IO (Either Yaml.ParseException ProjectConfig)
parseProjectConfig = Yaml.decodeFileEither
defaultEnvironment :: ProjectConfig -> Maybe (Text, Environment)
defaultEnvironment p = case HashMap.toList defaultEnvs of
[] -> Nothing
[x] -> Just x
_ -> Nothing
where
defaultEnvs = HashMap.filter _isDefault $ _environments p
getEnvironment :: ProjectConfig -> Text -> Maybe Environment
getEnvironment ProjectConfig{_environments = envs} name =
HashMap.lookup name envs
-- }}} ProjectConfig ----------------------------------------------------------
|
trskop/yx
|
src/YX/Type/ConfigFile.hs
|
bsd-3-clause
| 5,033 | 0 | 17 | 1,134 | 1,254 | 720 | 534 | 114 | 3 |
module Syntax where
import Data.Char(chr, ord)
import Data.List(find, nub, union, intersect, (\\))
import SCC
type Id = String
type Alt = ([Pat], Rhs)
type Expl = (Id, Scheme, [Alt])
type Impl = (Id, [Alt])
type BindGroup = ([Expl], [[Impl]])
type Program = [BindGroup]
data Kind = Star | Kfun Kind Kind
deriving (Eq, Show)
class Assoc a where
assocKey :: a -> String
assoc :: String -> [a] -> Maybe a
assoc key [] = Nothing
assoc key (x:xs) = if assocKey x == key then Just x else assoc key xs
-----------------------------------------------------------------------------
-- Type: Types
-----------------------------------------------------------------------------
data Type = TVar Tyvar
| TCon Tycon
| TAp Type Type
| TGen Int
| TSynonym Synonym [Type]
deriving Eq
instance Show Type where
showsPrec _ (TVar v) = shows v
showsPrec _ (TCon c) = shows c
showsPrec _ (TSynonym syn []) = shows syn
showsPrec p (TSynonym syn ts) = showParen (p > 2) f
where f = shows syn . (' ':) . g
g = foldr1 (\l r -> l . (' ':) . r) (map (showsPrec 3) ts)
showsPrec _ (TGen n) = (chr (ord 'a' + n) :)
showsPrec p tap@(TAp _ _) =
case t of
TCon tc | tyconName tc == "[]"
-> ('[':) . showsPrec 0 t1 . (']':)
where [t1] = ts
TCon tc | tyconName tc == "(->)"
-> showParen (p > 0) $
showsPrec 1 t1 . (" -> " ++) . showsPrec 0 t2
where [t1, t2] = ts
TCon tc | tyconName tc == "(,)"
-> showParen True $
foldr1 (\f g -> f . (", " ++) . g)
(map (showsPrec 0) ts)
_ -> showParen (p > 2) $
foldr1 (\f g -> f . (' ':) . g)
(map (showsPrec 3) (t:ts))
where (t:ts) = fromTAp tap
fromTAp :: Type -> [Type]
fromTAp (TAp t1 t2) = fromTAp t1 ++ [t2]
fromTAp t = [t]
data Tyvar = Tyvar Id Kind deriving Eq
instance Show Tyvar where
show (Tyvar id _) = id
data Tycon = Tycon { tyconName::Id,
tyconKind::Kind,
tyconNumCon::Int,
tyconArities::[Int]
} deriving Eq
instance Show Tycon where
show tc = tyconName tc
data Synonym = Synonym Id Kind [Tyvar] Type deriving Eq
instance Show Synonym where
show (Synonym id _ _ _) = id
instance Assoc Tycon where
assocKey tc = tyconName tc
instance Assoc Synonym where
assocKey (Synonym i _ _ _) = i
unsynonym :: Synonym -> [Type] -> Type
unsynonym (Synonym _ _ vs t) ts = apply s t
where s = zip vs ts
tChar = TCon (Tycon "Char" Star 0 [])
tInt = TCon (Tycon "Int" Star 0 [])
tBool = TCon (Tycon "Bool" Star 2 [0,0])
tUnit = TCon (Tycon "()" Star 1 [0])
tList = TCon (Tycon "[]" (Kfun Star Star) 2 [2,0])
tArrow = TCon (Tycon "(->)" (Kfun Star (Kfun Star Star)) 0 [])
tString :: Type
tString = list tChar
preludeTycons :: [Tycon]
preludeTycons = [Tycon "()" Star 1 [0],
Tycon "Char" Star 0 [],
Tycon "Int" Star 0 [],
Tycon "Bool" Star 2 [0,0],
Tycon "[]" (Kfun Star Star) 2 [2,0],
Tycon "(->)" (Kfun Star (Kfun Star Star)) 0 []
]
preludeSynonyms :: [Synonym]
preludeSynonyms = [Synonym "String" Star [] (list tChar)
]
preludeConstrs :: [Const]
preludeConstrs = [Const { conName = i,
conArity = a,
conTag = tag,
conTycon = tycon,
conScheme = quantifyAll' t }
| (i, a, tag, TCon tycon, t) <- constrs]
where a = TVar (Tyvar "a" Star)
constrs = [("True", 0, 1, tBool, tBool),
("False", 0, 2, tBool, tBool),
(":", 2, 1, tList, a `fn` list a `fn` list a),
("[]", 0, 2, tList, list a)]
eTrue = Con con
where Just con = find (\c -> conName c == "True") preludeConstrs
eFalse = Con con
where Just con = find (\c -> conName c == "False") preludeConstrs
eCons = Con con
where Just con = find (\c -> conName c == ":") preludeConstrs
eNil = Con con
where Just con = find (\c -> conName c == "[]") preludeConstrs
pCons x y = PCon con [x, y]
where Just con = find (\c -> conName c == ":") preludeConstrs
pNil = PCon con []
where Just con = find (\c -> conName c == "[]") preludeConstrs
infixr 4 `fn`
fn :: Type -> Type -> Type
a `fn` b = TAp (TAp tArrow a) b
list :: Type -> Type
list t = TAp tList t
pair :: Type -> Type -> Type
pair a b = TCon (tupTycon 2) `fn` a `fn` b
class HasKind t where
kind :: t -> Kind
instance HasKind Tyvar where
kind (Tyvar v k) = k
instance HasKind Tycon where
kind tc = tyconKind tc
instance HasKind Synonym where
kind (Synonym _ k _ _) = k
instance HasKind Type where
kind (TCon tc) = kind tc
kind (TVar u) = kind u
kind (TAp t _) = case (kind t) of
(Kfun _ k) -> k
kind (TSynonym syn ts) = kind (unsynonym syn ts)
type Subst = [(Tyvar, Type)]
class Types t where
apply :: Subst -> t -> t
tv :: t -> [Tyvar]
instance Types Type where
apply s (TVar u) = case lookup u s of
Just t -> t
Nothing -> TVar u
apply s (TAp l r) = TAp (apply s l) (apply s r)
apply s t = t
tv (TVar u) = [u]
tv (TAp l r) = tv l `union` tv r
tv t = []
instance Types a => Types [a] where
apply s = map (apply s)
tv = nub . concat . map tv
-- Predicates
data Qual t = [Pred] :=> t
deriving Eq
data Pred = IsIn Id Type
deriving Eq
instance Types t => Types (Qual t) where
apply s (ps :=> t) = apply s ps :=> apply s t
tv (ps :=> t) = tv ps `union` tv t
instance Types Pred where
apply s (IsIn i t) = IsIn i (apply s t)
tv (IsIn i t) = tv t
instance (Show t) => Show (Qual t) where
showsPrec _ ([] :=> t) = shows t
showsPrec _ (p :=> t) = showsContext . (" => " ++) . shows t
where showsContext = showParen True $
foldr1 (\f g -> f . (", " ++) . g) (map shows p)
instance Show Pred where
showsPrec _ (IsIn id t) = (id ++) . (' ':) . shows t
-- Type schemes
data Scheme = Forall [Kind] (Qual Type)
deriving Eq
instance Show Scheme where
showsPrec _ (Forall _ qt) = shows qt
instance Types Scheme where
apply s (Forall ks t) = Forall ks (apply s t)
tv (Forall ks t) = tv t
quantify :: [Tyvar] -> Qual Type -> Scheme
quantify vs qt = Forall ks (apply s qt)
where vs' = [ v | v <- tv qt, v `elem` vs ]
ks = map kind vs'
s = zip vs' (map TGen [0..])
quantifyAll :: Qual Type -> Scheme
quantifyAll t = quantify (tv t) t
quantifyAll' :: Type -> Scheme
quantifyAll' t = quantify (tv t) ([] :=> t)
toScheme :: Type -> Scheme
toScheme t = Forall [] ([] :=> t)
-- Assumptions
data Assump = Id :>: Scheme
instance Show Assump where
show (i :>: sc) = show i ++ " :: " ++ show sc
instance Types Assump where
apply s (i :>: sc) = i :>: (apply s sc)
tv (i :>: sc) = tv sc
findAssump :: Monad m => Id -> [Assump] -> m Scheme
findAssump id [] = fail ("unbound identifier: " ++ id)
findAssump id ((i:>:sc):as) = if i == id then return sc else findAssump id as
-- Literals
data Literal = LitInt Int
| LitChar String
| LitStr String
deriving Eq
instance Show Literal where
show (LitInt n) = show n
show (LitChar c) = c
show (LitStr s) = s
-- Patterns
data Pat = PVar Id
| PWildcard
| PAs Id Pat
| PLit Literal
| PCon Const [Pat]
data Expr = Var Id
| Lit Literal
| Con Const
| Ap Expr Expr
| Let BindGroup Expr
| Case Expr [(Pat, Rhs)]
| Lambda Alt
| ESign Expr Scheme
| RecPH Id
| ClassPH Pred
data Rhs = Rhs Expr
| Where BindGroup Rhs
| Guarded [(Expr, Expr)]
data Const = Const { conName::Id,
conArity::Int,
conTag::Int,
conTycon::Tycon,
conScheme::Scheme }
instance Eq Const where
c1 == c2 = conName c1 == conName c2
ap :: Expr -> [Expr] -> Expr
ap = foldl Ap
bindings :: BindGroup -> [Impl]
bindings (es, iss) = [(i, as) | (i, _, as) <- es] ++ concat iss
class HasVar t where
freeVars :: t -> [Id]
instance HasVar Expr where
freeVars (Var i) = [i]
freeVars (Ap e1 e2) = freeVars e1 `union` freeVars e2
freeVars (Let bg e) = fvBindGroup bg `union`
(freeVars e \\ map fst (bindings bg))
freeVars (Case e pses) = foldr union fve fvas
where fve = freeVars e
fvas = [freeVars e' \\ patVars p | (p, e') <- pses]
freeVars (Lambda a) = fvAlt a
freeVars (ESign e _) = freeVars e
freeVars _ = []
instance HasVar Rhs where
freeVars (Rhs e) = freeVars e
freeVars (Where bg rhs) =
fvBindGroup bg `union` (freeVars rhs \\ map fst (bindings bg))
freeVars (Guarded pairs) =
foldr union [] [freeVars e `union` freeVars e' | (e, e') <- pairs]
fvBindGroup :: BindGroup -> [Id]
fvBindGroup bg = fvAlts (concat altss) \\ is
where (is, altss) = unzip (bindings bg)
fvAlts :: [Alt] -> [Id]
fvAlts alts = foldl1 union (map fvAlt alts)
fvAlt :: Alt -> [Id]
fvAlt (ps, rhs) = freeVars rhs \\ concat (map patVars ps)
patVars :: Pat -> [Id]
patVars (PVar i) = [i]
patVars (PAs i p) = i : patVars p
patVars (PCon _ ps) = concat (map patVars ps)
patVars _ = []
tupcon :: Int -> Const
tupcon n = Const "(,)" n 1 tycon sc
where tycon = tupTycon n
tuptype = foldl TAp (TCon tycon) tvars
{-
tvars = [TVar (Tyvar ('v' : show i) Star) | i <- [0..n-1]]
scheme = quantifyAll (foldr fn tuptype tvars)
-}
tvars = [TGen i | i <- [0..n-1]]
sc = Forall (replicate n Star) ([] :=> foldr fn tuptype tvars)
tupTycon :: Int -> Tycon
tupTycon n = Tycon "(,)" (foldr Kfun Star (replicate n Star)) 1 [0]
tuple :: [Expr] -> Expr
tuple es = foldl Ap (Con $ tupcon $ length es) es
tupleSelector :: String -> Int -> Int -> Impl
tupleSelector id k n = (id, [([pat], Rhs expr)])
where pat = PCon (tupcon n) [PVar ('e' : show i) | i <- [0..n-1]]
expr = Var ('e' : show k)
-- type class
type Class = ([Id], [Inst], [Assump])
type Inst = (Qual Pred, Expr)
data ClassEnv = ClassEnv { classes :: Id -> Maybe Class,
defaults :: [Type],
impls :: [Impl],
expls :: [Expl],
assumps :: [Assump] }
type EnvTransformer = ClassEnv -> Maybe ClassEnv
idEnvTransformer :: EnvTransformer
idEnvTransformer ce = Just ce
infixr 5 <:>
(<:>) :: EnvTransformer -> EnvTransformer -> EnvTransformer
(f <:> g) ce = do ce' <- f ce
g ce'
-- SKI expression
data SKI = SAp SKI SKI
| SLit Literal
| SVar Id
| SCon Int Int
sap :: SKI -> [SKI] -> SKI
sap = foldl SAp
instance Show SKI where
show e = showsPrec 1 e ""
showsPrec _ (SVar i) = (i++)
showsPrec _ (SLit l) = shows l
showsPrec _ (SCon k n) = ('@':) . shows k . ('_':) . shows n
showsPrec _ (SAp e1 e2) = ('`':) . shows e1 . shows e2
-- showsPrec p (SAp e1 e2) = showParen (p > 0) $
-- showsPrec 0 e1 . (' ':) . showsPrec 1 e2
dependency :: [Impl] -> [[Impl]]
dependency bs = (map . map) (\v -> (v, lookup' v bs)) (reverse vss)
where vs = map fst bs
vss = scc [(v, fvAlts alts `intersect` vs) | (v, alts) <- bs]
lookup' key xs = case lookup key xs of
Just x -> x
Nothing -> error "cannot occur"
|
irori/hs2lazy
|
Syntax.hs
|
bsd-3-clause
| 11,654 | 31 | 17 | 3,759 | 5,055 | 2,671 | 2,384 | 308 | 2 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Reflex.Dom.Builder.Static where
import Data.IORef (IORef)
import Blaze.ByteString.Builder.Html.Utf8
import Control.Lens hiding (element)
import Control.Monad.Exception
import Control.Monad.Identity
import Control.Monad.Primitive
import Control.Monad.Ref
import Control.Monad.State.Strict
import Control.Monad.Trans.Reader
import Data.ByteString (ByteString)
import Data.ByteString.Builder (Builder, byteString, toLazyByteString)
import qualified Data.ByteString.Lazy as LBS
import Data.Default
import Data.Dependent.Map (DMap)
import qualified Data.Dependent.Map as DMap
import Data.Dependent.Sum (DSum (..))
import Data.Functor.Compose
import Data.Functor.Constant
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.Map as Map
import Data.Map.Misc (applyMap)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding
import Data.Tuple
import GHC.Generics
import Reflex.Adjustable.Class
import Reflex.Class
import Reflex.Dom.Main (DomHost, DomTimeline, runDomHost)
import Reflex.Dom.Builder.Class
import Reflex.Dynamic
import Reflex.Host.Class
import Reflex.PerformEvent.Base
import Reflex.PerformEvent.Class
import Reflex.PostBuild.Base
import Reflex.PostBuild.Class
import Reflex.TriggerEvent.Class
data StaticDomBuilderEnv t = StaticDomBuilderEnv
{ _staticDomBuilderEnv_shouldEscape :: Bool
, _staticDomBuilderEnv_selectValue :: Maybe (Behavior t Text)
-- ^ When the parent element is a "select" whose value has been set, this value tells us the current value.
-- We use this to add a "selected" attribute to the appropriate "option" child element.
-- This is not yet a perfect simulation of what the browser does, but it is much closer than doing nothing.
-- TODO: Handle edge cases, e.g. setting to a value for which there is no option, then adding that option dynamically afterwards.
, _staticDomBuilderEnv_nextRunWithReplaceKey :: IORef Int
}
newtype StaticDomBuilderT t m a = StaticDomBuilderT
{ unStaticDomBuilderT :: ReaderT (StaticDomBuilderEnv t) (StateT [Behavior t Builder] m) a -- Accumulated Html will be in reversed order
}
deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
instance PrimMonad m => PrimMonad (StaticDomBuilderT x m) where
type PrimState (StaticDomBuilderT x m) = PrimState m
primitive = lift . primitive
instance MonadTrans (StaticDomBuilderT t) where
lift = StaticDomBuilderT . lift . lift
runStaticDomBuilderT :: (Monad m, Reflex t) => StaticDomBuilderT t m a -> StaticDomBuilderEnv t -> m (a, Behavior t Builder)
runStaticDomBuilderT (StaticDomBuilderT a) e = do
(result, a') <- runStateT (runReaderT a e) []
return (result, mconcat $ reverse a')
instance PostBuild t m => PostBuild t (StaticDomBuilderT t m) where
{-# INLINABLE getPostBuild #-}
getPostBuild = lift getPostBuild
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (StaticDomBuilderT t m) where
{-# INLINABLE newEventWithTrigger #-}
newEventWithTrigger = lift . newEventWithTrigger
{-# INLINABLE newFanEventWithTrigger #-}
newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
instance PerformEvent t m => PerformEvent t (StaticDomBuilderT t m) where
type Performable (StaticDomBuilderT t m) = Performable m
{-# INLINABLE performEvent_ #-}
performEvent_ e = lift $ performEvent_ e
{-# INLINABLE performEvent #-}
performEvent e = lift $ performEvent e
instance MonadSample t m => MonadSample t (StaticDomBuilderT t m) where
{-# INLINABLE sample #-}
sample = lift . sample
instance MonadHold t m => MonadHold t (StaticDomBuilderT t m) where
{-# INLINABLE hold #-}
hold v0 v' = lift $ hold v0 v'
{-# INLINABLE holdDyn #-}
holdDyn v0 v' = lift $ holdDyn v0 v'
{-# INLINABLE holdIncremental #-}
holdIncremental v0 v' = lift $ holdIncremental v0 v'
{-# INLINABLE buildDynamic #-}
buildDynamic a0 = lift . buildDynamic a0
{-# INLINABLE headE #-}
headE = lift . headE
instance (Monad m, Ref m ~ Ref IO, Reflex t) => TriggerEvent t (StaticDomBuilderT t m) where
{-# INLINABLE newTriggerEvent #-}
newTriggerEvent = return (never, const $ return ())
{-# INLINABLE newTriggerEventWithOnComplete #-}
newTriggerEventWithOnComplete = return (never, \_ _ -> return ())
{-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
newEventWithLazyTriggerWithOnComplete _ = return never
instance MonadRef m => MonadRef (StaticDomBuilderT t m) where
type Ref (StaticDomBuilderT t m) = Ref m
newRef = lift . newRef
readRef = lift . readRef
writeRef r = lift . writeRef r
instance MonadAtomicRef m => MonadAtomicRef (StaticDomBuilderT t m) where
atomicModifyRef r = lift . atomicModifyRef r
type SupportsStaticDomBuilder t m = (Reflex t, MonadIO m, MonadHold t m, MonadFix m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO, Adjustable t m)
data StaticDomSpace
-- | Static documents never produce any events, so this type has no inhabitants
data StaticDomEvent (a :: k)
-- | Static documents don't process events, so all handlers are equivalent
data StaticDomHandler (a :: k) (b :: k) = StaticDomHandler
data StaticEventSpec (er :: EventTag -> *) = StaticEventSpec deriving (Generic)
instance Default (StaticEventSpec er)
instance DomSpace StaticDomSpace where
type EventSpec StaticDomSpace = StaticEventSpec
type RawDocument StaticDomSpace = ()
type RawTextNode StaticDomSpace = ()
type RawCommentNode StaticDomSpace = ()
type RawElement StaticDomSpace = ()
type RawInputElement StaticDomSpace = ()
type RawTextAreaElement StaticDomSpace = ()
type RawSelectElement StaticDomSpace = ()
addEventSpecFlags _ _ _ _ = StaticEventSpec
instance (SupportsStaticDomBuilder t m, Monad m) => HasDocument (StaticDomBuilderT t m) where
askDocument = pure ()
instance (Reflex t, Adjustable t m, MonadHold t m, SupportsStaticDomBuilder t m) => Adjustable t (StaticDomBuilderT t m) where
runWithReplace a0 a' = do
e <- StaticDomBuilderT ask
key <- replaceStart e
(result0, result') <- lift $ runWithReplace (runStaticDomBuilderT a0 e) (flip runStaticDomBuilderT e <$> a')
o <- hold (snd result0) $ fmapCheap snd result'
StaticDomBuilderT $ modify $ (:) $ join o
replaceEnd key
return (fst result0, fmapCheap fst result')
traverseIntMapWithKeyWithAdjust = hoistIntMapWithKeyWithAdjust traverseIntMapWithKeyWithAdjust
traverseDMapWithKeyWithAdjust = hoistDMapWithKeyWithAdjust traverseDMapWithKeyWithAdjust mapPatchDMap
traverseDMapWithKeyWithAdjustWithMove = hoistDMapWithKeyWithAdjust traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove
replaceStart :: (DomBuilder t m, MonadIO m) => StaticDomBuilderEnv t -> m Text
replaceStart env = do
str <- show <$> liftIO (atomicModifyRef (_staticDomBuilderEnv_nextRunWithReplaceKey env) $ \k -> (succ k, k))
let key = "-" <> T.pack str
_ <- commentNode $ def { _commentNodeConfig_initialContents = "replace-start" <> key }
pure key
replaceEnd :: DomBuilder t m => Text -> m ()
replaceEnd key = void $ commentNode $ def { _commentNodeConfig_initialContents = "replace-end" <> key }
hoistIntMapWithKeyWithAdjust :: forall t m p a b.
( Adjustable t m
, MonadHold t m
, Patch (p a)
, Functor p
, Patch (p (Behavior t Builder))
, PatchTarget (p (Behavior t Builder)) ~ IntMap (Behavior t Builder)
, Ref m ~ IORef, MonadIO m, MonadFix m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadRef m -- TODO remove
)
=> (forall x. (IntMap.Key -> a -> m x)
-> IntMap a
-> Event t (p a)
-> m (IntMap x, Event t (p x))
) -- ^ The base monad's traversal
-> (IntMap.Key -> a -> StaticDomBuilderT t m b)
-> IntMap a
-> Event t (p a)
-> StaticDomBuilderT t m (IntMap b, Event t (p b))
hoistIntMapWithKeyWithAdjust base f im0 im' = do
e <- StaticDomBuilderT ask
(children0, children') <- lift $ base (\k v -> runStaticDomBuilderT (f k v) e) im0 im'
let result0 = IntMap.map fst children0
result' = (fmap . fmap) fst children'
outputs0 :: IntMap (Behavior t Builder)
outputs0 = IntMap.map snd children0
outputs' :: Event t (p (Behavior t Builder))
outputs' = (fmap . fmap) snd children'
outputs <- holdIncremental outputs0 outputs'
StaticDomBuilderT $ modify $ (:) $ pull $ do
os <- sample $ currentIncremental outputs
fmap mconcat $ forM (IntMap.toList os) $ \(_, o) -> do
sample o
return (result0, result')
hoistDMapWithKeyWithAdjust :: forall (k :: * -> *) v v' t m p.
( Adjustable t m
, MonadHold t m
, PatchTarget (p k (Constant (Behavior t Builder))) ~ DMap k (Constant (Behavior t Builder))
, Patch (p k (Constant (Behavior t Builder)))
, Ref m ~ IORef, MonadIO m, MonadFix m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadRef m -- TODO remove
)
=> (forall vv vv'.
(forall a. k a -> vv a -> m (vv' a))
-> DMap k vv
-> Event t (p k vv)
-> m (DMap k vv', Event t (p k vv'))
) -- ^ The base monad's traversal
-> (forall vv vv'. (forall a. vv a -> vv' a) -> p k vv -> p k vv') -- ^ A way of mapping over the patch type
-> (forall a. k a -> v a -> StaticDomBuilderT t m (v' a))
-> DMap k v
-> Event t (p k v)
-> StaticDomBuilderT t m (DMap k v', Event t (p k v'))
hoistDMapWithKeyWithAdjust base mapPatch f dm0 dm' = do
e <- StaticDomBuilderT ask
(children0, children') <- lift $ base (\k v -> fmap (Compose . swap) (runStaticDomBuilderT (f k v) e)) dm0 dm'
let result0 = DMap.map (snd . getCompose) children0
result' = ffor children' $ mapPatch $ snd . getCompose
outputs0 :: DMap k (Constant (Behavior t Builder))
outputs0 = DMap.map (Constant . fst . getCompose) children0
outputs' :: Event t (p k (Constant (Behavior t Builder)))
outputs' = ffor children' $ mapPatch $ Constant . fst . getCompose
outputs <- holdIncremental outputs0 outputs'
StaticDomBuilderT $ modify $ (:) $ pull $ do
os <- sample $ currentIncremental outputs
fmap mconcat $ forM (DMap.toList os) $ \(_ :=> Constant o) -> do
sample o
return (result0, result')
instance SupportsStaticDomBuilder t m => NotReady t (StaticDomBuilderT t m) where
notReadyUntil _ = pure ()
notReady = pure ()
-- TODO: the uses of illegal lenses in this instance causes it to be somewhat less efficient than it can be. replacing them with explicit cases to get the underlying Maybe Event and working with those is ideal.
instance SupportsStaticDomBuilder t m => DomBuilder t (StaticDomBuilderT t m) where
type DomBuilderSpace (StaticDomBuilderT t m) = StaticDomSpace
{-# INLINABLE textNode #-}
textNode (TextNodeConfig initialContents mSetContents) = StaticDomBuilderT $ do
--TODO: Do not escape quotation marks; see https://stackoverflow.com/questions/25612166/what-characters-must-be-escaped-in-html-5
shouldEscape <- asks _staticDomBuilderEnv_shouldEscape
let escape = if shouldEscape then fromHtmlEscapedText else byteString . encodeUtf8
modify . (:) =<< case mSetContents of
Nothing -> return (pure (escape initialContents))
Just setContents -> hold (escape initialContents) $ fmapCheap escape setContents --Only because it doesn't get optimized when profiling is on
return $ TextNode ()
{-# INLINABLE commentNode #-}
commentNode (CommentNodeConfig initialContents mSetContents) = StaticDomBuilderT $ do
--TODO: Do not escape quotation marks; see https://stackoverflow.com/questions/25612166/what-characters-must-be-escaped-in-html-5
shouldEscape <- asks _staticDomBuilderEnv_shouldEscape
let escape = if shouldEscape then fromHtmlEscapedText else byteString . encodeUtf8
(modify . (:)) . (\c -> "<!--" <> c <> "-->") =<< case mSetContents of
Nothing -> return (pure (escape initialContents))
Just setContents -> hold (escape initialContents) $ fmapCheap escape setContents --Only because it doesn't get optimized when profiling is on
return $ CommentNode ()
{-# INLINABLE element #-}
element elementTag cfg child = do
-- https://www.w3.org/TR/html-markup/syntax.html#syntax-elements
let voidElements = Set.fromList ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]
let noEscapeElements = Set.fromList ["style", "script"]
let toAttr (AttributeName _mns k) v = byteString (encodeUtf8 k) <> byteString "=\"" <> fromHtmlEscapedText v <> byteString "\""
es <- newFanEventWithTrigger $ \_ _ -> return (return ())
StaticDomBuilderT $ do
let shouldEscape = elementTag `Set.notMember` noEscapeElements
nextRunWithReplaceKey <- asks _staticDomBuilderEnv_nextRunWithReplaceKey
(result, innerHtml) <- lift $ lift $ runStaticDomBuilderT child $ StaticDomBuilderEnv shouldEscape Nothing nextRunWithReplaceKey
attrs0 <- foldDyn applyMap (cfg ^. initialAttributes) (cfg ^. modifyAttributes)
selectValue <- asks _staticDomBuilderEnv_selectValue
let addSelectedAttr attrs sel = case Map.lookup "value" attrs of
Just v | v == sel -> attrs <> Map.singleton "selected" ""
_ -> Map.delete "selected" attrs
let attrs1 = case (elementTag, selectValue) of
("option", Just sv) -> pull $ addSelectedAttr <$> sample (current attrs0) <*> sample sv
_ -> current attrs0
let attrs2 = ffor attrs1 $ mconcat . fmap (\(k, v) -> " " <> toAttr k v) . Map.toList
let tagBS = encodeUtf8 elementTag
if Set.member elementTag voidElements
then modify $ (:) $ mconcat [constant ("<" <> byteString tagBS), attrs2, constant (byteString " />")]
else do
let open = mconcat [constant ("<" <> byteString tagBS), attrs2, constant (byteString ">")]
let close = constant $ byteString $ "</" <> tagBS <> ">"
modify $ (:) $ mconcat [open, innerHtml, close]
let e = Element
{ _element_events = es
, _element_raw = ()
}
return (e, result)
{-# INLINABLE inputElement #-}
inputElement cfg = do
-- Tweak the config to update the "value" and "checked" attributes appropriately.
-- TODO: warn upon overwriting values.
let setInitialValue = Map.insert "value" (_inputElementConfig_initialValue cfg)
setUpdatedValue updatedAttrs = case _inputElementConfig_setValue cfg of
Nothing -> updatedAttrs
Just e -> (Map.singleton "value" . Just <$> e) <> updatedAttrs
setInitialChecked = case _inputElementConfig_initialChecked cfg of
True -> Map.insert "checked" "checked"
False -> id
setUpdatedChecked updatedAttrs = case _inputElementConfig_setChecked cfg of
Nothing -> updatedAttrs
Just e -> (Map.singleton "checked" (Just "checked") <$ e) <> updatedAttrs
adjustedConfig = _inputElementConfig_elementConfig cfg
& elementConfig_initialAttributes %~ setInitialValue . setInitialChecked
& elementConfig_modifyAttributes %~ setUpdatedValue . setUpdatedChecked
(e, _result) <- element "input" adjustedConfig $ return ()
v <- case _inputElementConfig_setValue cfg of
Nothing -> pure $ constDyn (cfg ^. inputElementConfig_initialValue)
Just ev -> holdDyn (cfg ^. inputElementConfig_initialValue) ev
c <- case _inputElementConfig_setChecked cfg of
Nothing -> pure $ constDyn $ _inputElementConfig_initialChecked cfg
Just ev -> holdDyn (_inputElementConfig_initialChecked cfg) ev
let hasFocus = constDyn False -- TODO should this be coming from initialAtttributes
return $ InputElement
{ _inputElement_value = v
, _inputElement_checked = c
, _inputElement_checkedChange = never
, _inputElement_input = never
, _inputElement_hasFocus = hasFocus
, _inputElement_element = e
, _inputElement_raw = ()
, _inputElement_files = constDyn mempty
}
{-# INLINABLE textAreaElement #-}
textAreaElement cfg = do
(e, _domElement) <- element "textarea" (_textAreaElementConfig_elementConfig cfg) $ do
-- Set the initial value
void $ textNode $ def
& textNodeConfig_initialContents .~ _textAreaElementConfig_initialValue cfg
& textNodeConfig_setContents .~ fromMaybe never (_textAreaElementConfig_setValue cfg)
v <- case _textAreaElementConfig_setValue cfg of
Nothing -> pure $ constDyn (cfg ^. textAreaElementConfig_initialValue)
Just ev -> holdDyn (cfg ^. textAreaElementConfig_initialValue) ev
let hasFocus = constDyn False -- TODO should this be coming from initialAtttributes
return $ TextAreaElement
{ _textAreaElement_value = v
, _textAreaElement_input = never
, _textAreaElement_hasFocus = hasFocus
, _textAreaElement_element = e
, _textAreaElement_raw = ()
}
selectElement cfg child = do
v <- holdDyn (cfg ^. selectElementConfig_initialValue) (cfg ^. selectElementConfig_setValue)
(e, result) <- element "select" (_selectElementConfig_elementConfig cfg) $ do
(a, innerHtml) <- StaticDomBuilderT $ do
nextRunWithReplaceKey <- asks _staticDomBuilderEnv_nextRunWithReplaceKey
lift $ lift $ runStaticDomBuilderT child $ StaticDomBuilderEnv False (Just $ current v) nextRunWithReplaceKey
StaticDomBuilderT $ lift $ modify $ (:) innerHtml
return a
let wrapped = SelectElement
{ _selectElement_value = v
, _selectElement_change = never
, _selectElement_hasFocus = constDyn False --TODO: How do we make sure this is correct?
, _selectElement_element = e
, _selectElement_raw = ()
}
return (wrapped, result)
placeRawElement () = return ()
wrapRawElement () _ = return $ Element (EventSelector $ const never) ()
--TODO: Make this more abstract --TODO: Put the WithWebView underneath PerformEventT - I think this would perform better
type StaticWidget x = PostBuildT DomTimeline (StaticDomBuilderT DomTimeline (PerformEventT DomTimeline DomHost))
{-# INLINE renderStatic #-}
renderStatic :: StaticWidget x a -> IO (a, ByteString)
renderStatic w = do
runDomHost $ do
(postBuild, postBuildTriggerRef) <- newEventWithTriggerRef
nextRunWithReplaceKey <- newRef 0
let env0 = StaticDomBuilderEnv True Nothing nextRunWithReplaceKey
((res, bs), FireCommand fire) <- hostPerformEventT $ runStaticDomBuilderT (runPostBuildT w postBuild) env0
mPostBuildTrigger <- readRef postBuildTriggerRef
forM_ mPostBuildTrigger $ \postBuildTrigger -> fire [postBuildTrigger :=> Identity ()] $ return ()
bs' <- sample bs
return (res, LBS.toStrict $ toLazyByteString bs')
|
reflex-frp/reflex-dom
|
reflex-dom-core/src/Reflex/Dom/Builder/Static.hs
|
bsd-3-clause
| 19,245 | 0 | 22 | 3,720 | 5,391 | 2,775 | 2,616 | -1 | -1 |
-- |
-- Module : Control.Monad.Trans.Loop
-- Copyright : (c) Joseph Adams 2012
-- License : BSD3
-- Maintainer : [email protected]
--
{-# LANGUAGE Rank2Types #-}
-- Needed for the MonadBase instance
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
module Control.Monad.Trans.Loop (
-- * The LoopT monad transformer
LoopT(..),
stepLoopT,
-- * continue and exit
continue,
exit,
continueWith,
exitWith,
-- * Looping constructs
foreach,
while,
doWhile,
once,
repeatLoopT,
iterateLoopT,
-- * Lifting other operations
liftLocalLoopT,
) where
import Control.Applicative (Applicative(pure, (<*>)))
import Control.Monad.Base (MonadBase(liftBase), liftBaseDefault)
import Control.Monad.IO.Class (MonadIO(liftIO))
import Control.Monad.Trans.Class (MonadTrans(lift))
import Data.Foldable (Foldable)
import qualified Data.Foldable as Foldable
------------------------------------------------------------------------
-- The LoopT monad transformer
-- | 'LoopT' is a monad transformer for the loop body. It provides two
-- capabilities:
--
-- * 'continue' to the next iteration.
--
-- * 'exit' the whole loop.
newtype LoopT c e m a = LoopT
{ runLoopT :: forall r. -- This universal quantification forces the
-- LoopT computation to call one of the
-- following continuations.
(c -> m r) -- continue
-> (e -> m r) -- exit
-> (a -> m r) -- return a value
-> m r
}
instance Functor (LoopT c e m) where
fmap f m = LoopT $ \next fin cont -> runLoopT m next fin (cont . f)
instance Applicative (LoopT c e m) where
pure a = LoopT $ \_ _ cont -> cont a
f1 <*> f2 = LoopT $ \next fin cont ->
runLoopT f1 next fin $ \f ->
runLoopT f2 next fin (cont . f)
instance Monad (LoopT c e m) where
return a = LoopT $ \_ _ cont -> cont a
m >>= k = LoopT $ \next fin cont ->
runLoopT m next fin $ \a ->
runLoopT (k a) next fin cont
instance MonadTrans (LoopT c e) where
lift m = LoopT $ \_ _ cont -> m >>= cont
instance MonadIO m => MonadIO (LoopT c e m) where
liftIO = lift . liftIO
instance MonadBase b m => MonadBase b (LoopT c e m) where
liftBase = liftBaseDefault
-- | Call a loop body, passing it a continuation for the next iteration.
-- This can be used to construct custom looping constructs. For example,
-- here is how 'foreach' could be defined:
--
-- >foreach :: Monad m => [a] -> (a -> LoopT c () m c) -> m ()
-- >foreach list body = loop list
-- > where loop [] = return ()
-- > loop (x:xs) = stepLoopT (body x) (\_ -> loop xs)
stepLoopT :: Monad m => LoopT c e m c -> (c -> m e) -> m e
stepLoopT body next = runLoopT body next return next
------------------------------------------------------------------------
-- continue and exit
-- | Skip the rest of the loop body and go to the next iteration.
continue :: LoopT () e m a
continue = continueWith ()
-- | Break out of the loop entirely.
exit :: LoopT c () m a
exit = exitWith ()
-- | Like 'continue', but return a value from the loop body.
continueWith :: c -> LoopT c e m a
continueWith c = LoopT $ \next _ _ -> next c
-- | Like 'exit', but return a value from the loop as a whole.
-- See the documentation of 'iterateLoopT' for an example.
exitWith :: e -> LoopT c e m a
exitWith e = LoopT $ \_ fin _ -> fin e
------------------------------------------------------------------------
-- Looping constructs
-- | Call the loop body with each item in the collection.
--
-- If you do not need to 'continue' or 'exit' the loop, consider using
-- 'Foldable.forM_' instead.
foreach :: (Foldable f, Monad m) => f a -> (a -> LoopT c () m c) -> m ()
foreach list body =
Foldable.foldr
(\x next -> stepLoopT (body x) (\_ -> next))
(return ())
list
-- | Repeat the loop body while the predicate holds. Like a @while@ loop in C,
-- the condition is tested first.
while :: Monad m => m Bool -> LoopT c () m c -> m ()
while cond body = loop
where loop = do b <- cond
if b then stepLoopT body (\_ -> loop)
else return ()
-- | Like a @do while@ loop in C, where the condition is tested after
-- the loop body.
--
-- 'doWhile' returns the result of the last iteration. This is possible
-- because, unlike 'foreach' and 'while', the loop body is guaranteed to be
-- executed at least once.
doWhile :: Monad m => LoopT a a m a -> m Bool -> m a
doWhile body cond = loop
where loop = stepLoopT body $ \a -> do
b <- cond
if b then loop
else return a
-- | Execute the loop body once. This is a convenient way to introduce early
-- exit support to a block of code.
--
-- 'continue' and 'exit' do the same thing inside of 'once'.
once :: Monad m => LoopT a a m a -> m a
once body = runLoopT body return return return
-- | Execute the loop body again and again. The only way to exit 'repeatLoopT'
-- is to call 'exit' or 'exitWith'.
repeatLoopT :: Monad m => LoopT c e m a -> m e
repeatLoopT body = loop
where loop = runLoopT body (\_ -> loop) return (\_ -> loop)
-- | Call the loop body again and again, passing it the result of the previous
-- iteration each time around. The only way to exit 'iterateLoopT' is to call
-- 'exit' or 'exitWith'.
--
-- Example:
--
-- >count :: Int -> IO Int
-- >count n = iterateLoopT 0 $ \i ->
-- > if i < n
-- > then do
-- > lift $ print i
-- > return $ i+1
-- > else exitWith i
iterateLoopT :: Monad m => c -> (c -> LoopT c e m c) -> m e
iterateLoopT z body = loop z
where loop c = stepLoopT (body c) loop
------------------------------------------------------------------------
-- Lifting other operations
-- | Lift a function like 'Control.Monad.Trans.Reader.local' or
-- 'Control.Exception.mask_'.
liftLocalLoopT :: Monad m => (forall a. m a -> m a) -> LoopT c e m b -> LoopT c e m b
liftLocalLoopT f cb = LoopT $ \next fin cont -> do
m <- f $ runLoopT cb (return . next) (return . fin) (return . cont)
m
|
joeyadams/haskell-control-monad-loop
|
Control/Monad/Trans/Loop.hs
|
bsd-3-clause
| 6,317 | 0 | 13 | 1,684 | 1,442 | 787 | 655 | 87 | 2 |
{-# LANGUAGE TypeOperators #-}
module TypeOperatorOperator where
data (:><:) a b = (:><:) a b
f :: a :><: b -> b :><: a
f (a :><: b) = b :><: a
|
phischu/fragnix
|
tests/quick/TypeOperatorOperator/TypeOperatorOperator.hs
|
bsd-3-clause
| 146 | 10 | 7 | 34 | 59 | 35 | 24 | 5 | 1 |
-- |
-- Module : Core.Primitive
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : portable
--
-- Different collections (list, vector, string, ..) unified under 1 API.
-- an API to rules them all, and in the darkness bind them.
--
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleInstances #-}
module Core.Primitive
( PrimType(..)
, PrimMonad(..)
) where
import Core.Primitive.Types
import Core.Primitive.Monad
|
vincenthz/hs-xyz-test
|
Core/Primitive.hs
|
bsd-3-clause
| 512 | 0 | 5 | 95 | 46 | 35 | 11 | 7 | 0 |
module PixeloSolver.Game.Nonogram(
PixeloTile (..)
, PixeloTileFill(..)
, PixeloGame(..)
, emptyGameBoard
, solvePixeloGame
, generateSolutions
) where
import Control.Arrow
import Control.Monad
import Data.Array
import PixeloSolver.Data.Array.Extra
-- Data and Show instance definitions
-- | Single tile of Nonogram board
data PixeloTile = Done PixeloTileFill | Unknown deriving Eq
instance Show PixeloTile where
show (Done Empty) = "_"
show (Done Full) = "#"
show Unknown = "?"
data PixeloTileFill = Empty | Full deriving (Eq, Show)
data PixeloGame = PixeloGame {
pixeloGameGetBoard :: (Array (Int, Int) PixeloTile),
pixeloGameGetRowHints :: [[Int]] ,
pixeloGameGetColHints :: [[Int]]
} deriving (Eq)
instance Show PixeloGame where
show (PixeloGame board rowHints columnHints) =
(charArrayToColumnHintsString rowHintsStringLength . columnHintsToCharArray
$ columnHints)
++ (concat . map (showRow rowHintsStringLength)
$ (map (\i -> (rowHints !! i, getRow i board)) [0..height]))
where
height = fst . snd . bounds $ board
rowHintsFieldLength = getMaxHintFieldLength rowHints
rowHintsStringLength :: Int
rowHintsStringLength = maximum
. map (hintsStringLength rowHintsFieldLength)
$ rowHints
showRow :: Int -> ([Int], Array Int PixeloTile) -> String
showRow stringLength =
(++ "\n")
. (uncurry (++))
. (showRowHints stringLength *** showBoardRow)
showRowHints :: Int -> [Int] -> String
showRowHints stringLength row =
replicate prefixLength ' ' ++ hintsToString rowHintsFieldLength row
where
prefixLength = stringLength
- hintsStringLength rowHintsFieldLength row
showBoardRow :: Array Int PixeloTile -> String
showBoardRow = concat . map show . elems
intLength :: Int -> Int
intLength = ceiling . (logBase (10 :: Double)) . fromIntegral . (+ 1)
hintFieldLength :: Int -> Int
hintFieldLength = (+ 1) . intLength
getMaxHintFieldLength :: [[Int]] -> Int
getMaxHintFieldLength = maximum . map (maximum . map hintFieldLength)
hintsStringLength :: Int -> [Int] -> Int
hintsStringLength fieldLength = (* fieldLength) . length
columnHintsToCharArray :: [[Int]] -> Array (Int, Int) Char
columnHintsToCharArray hss =
initialArray // arrAssocs
where
maxHintFieldLength = getMaxHintFieldLength hss
height = maximum
. map (hintsStringLength maxHintFieldLength)
$ hss
width = length hss
initialArray = listArray
((0, 0), (height - 1, width - 1))
(replicate (width * height) ' ')
columnStrings = map (hintsToString maxHintFieldLength) hss
arrAssocs = concat
. map
(\(x, columnString) ->
let
prefixLength = height - length columnString
enumString = zip [0..] columnString
in
map (\(i, c) -> ((prefixLength + i, x), c)) enumString)
$ zip [0..] columnStrings
charArrayToColumnHintsString :: Int -> Array (Int, Int) Char -> String
charArrayToColumnHintsString = charArrayToColumnHintsString' (0, 0)
charArrayToColumnHintsString' :: (Int, Int) -> Int -> Array (Int, Int) Char -> String
charArrayToColumnHintsString' (y, x) prefixLength charArray =
if y > height
then ""
else
if x == 0
then replicate prefixLength ' '
++ charArrayToColumnHintsString' (y, 1) prefixLength charArray
else
if x > width + 1
then '\n' : charArrayToColumnHintsString' (y + 1, 0) prefixLength
charArray
else (charArray ! (y, x - 1))
: charArrayToColumnHintsString' (y, x + 1) prefixLength charArray
where
(height, width) = snd . bounds $ charArray
hintsToString :: Int -> [Int] -> String
hintsToString _ [] = ""
hintsToString fieldLength (h : hs) =
(prefix ++ hint ++ " ") ++ hintsToString fieldLength hs
where
hint = show h
prefixLength = fieldLength - 1 - length hint
prefix = replicate prefixLength ' '
prettyPrintBoard :: Array (Int, Int) PixeloTile -> String
prettyPrintBoard board = concat
$ map (\i -> concat (map show $ elems (getRow i board)) ++ ['\n']) [0..height]
where
height = snd . snd . bounds $ board
-- Solver functions
-- | generate possible solutions for a row/columns
generateSolutions :: [Int] -- ^ hints for this row/column
-> [PixeloTile] -- ^ partially filled row/column
-> [[PixeloTileFill]] -- ^ possible solutions
generateSolutions [] cs =
if any (== Done Full) cs
then []
else [replicate (length cs) Empty]
generateSolutions [0] cs =
if any (== Done Full) cs
then []
else [replicate (length cs) Empty]
generateSolutions _ [] = []
generateSolutions hints@(h : hs) constraints@(c : cs) =
delayedSolutions ++ eagerSolutions
where
delayedSolutions =
if c == Done Full
then []
else do
solution <- generateSolutions hints cs
return $ Empty : solution
eagerSolutions = case maybeApplied of
Nothing -> []
Just (appliedHint, restOfConstraints) -> do
solution <- generateSolutions hs restOfConstraints
return $ appliedHint ++ solution
where
maybeApplied = applyHint h constraints
applyHint :: Int -> [PixeloTile] -> Maybe ([PixeloTileFill], [PixeloTile])
applyHint hint currentTiles =
if doesHintAgree hint front
then Just $ (take (length front) (replicate hint Full ++ [Empty]), rest)
else Nothing
where
(front, rest) = splitAt (hint + 1) currentTiles
doesHintAgree :: Int -> [PixeloTile] -> Bool
doesHintAgree hint currentTiles =
not
$ length currentTiles < hint
|| any (== Done Empty) front
|| (length rest > 0 && head rest == Done Full)
where
(front, rest) = splitAt hint currentTiles
-- | Given solutions return their intersection
mergeSolutions :: [[PixeloTileFill]] -> [PixeloTile]
mergeSolutions [] = undefined
mergeSolutions (s : ss) = mergeSolutions' (map Done s) ss
mergeSolutions' :: [PixeloTile] -> [[PixeloTileFill]] -> [PixeloTile]
mergeSolutions' constraints [] = constraints
mergeSolutions' constraints (s : ss) =
if all (== Unknown) constraints
then constraints
else mergeSolutions' (mergeSolution constraints s) ss
mergeSolution :: [PixeloTile] -> [PixeloTileFill] -> [PixeloTile]
mergeSolution [] [] = []
mergeSolution (Unknown : cs) (_ : ss) = Unknown : (mergeSolution cs ss)
mergeSolution (Done a : cs) (s : ss) =
if a == s
then Done a : (mergeSolution cs ss)
else Unknown : (mergeSolution cs ss)
mergeSolution _ _ = undefined
-- | Solve given row/column as much as possible. Return Nothing if solution is
-- impossible
stepSolvePixeloGameDim ::
(Int -> Array (Int, Int) PixeloTile -> Array Int PixeloTile)
-> (Int
-> Array Int PixeloTile
-> Array (Int, Int) PixeloTile
-> Array (Int, Int) PixeloTile)
-> (PixeloGame -> [[Int]])
-> Int
-> PixeloGame
-> Maybe PixeloGame
stepSolvePixeloGameDim getDim setDim getHints dimId game =
case generatedSolutions of
[] -> Nothing
_ -> Just
$ PixeloGame
newBoard
(pixeloGameGetRowHints game)
(pixeloGameGetColHints game)
where
dimHints = getHints game !! dimId
board = pixeloGameGetBoard game
dimList = elems $ getDim dimId board
generatedSolutions = generateSolutions dimHints dimList
newDimList = mergeSolutions generatedSolutions
newDim = listArray (0, length dimList - 1) newDimList
newBoard = setDim dimId newDim board
stepSolvePixeloGameRow :: Int -> PixeloGame -> Maybe PixeloGame
stepSolvePixeloGameRow =
stepSolvePixeloGameDim getRow setRow pixeloGameGetRowHints
stepSolvePixeloGameCol :: Int -> PixeloGame -> Maybe PixeloGame
stepSolvePixeloGameCol =
stepSolvePixeloGameDim getColumn setColumn pixeloGameGetColHints
stepSolvePixeloGameDims ::
(Int -> PixeloGame -> Maybe PixeloGame)
-> Int
-> PixeloGame
-> Maybe PixeloGame
stepSolvePixeloGameDims stepDimSolve dimSize =
foldr1 (>=>) funs
where
funs = map stepDimSolve [0..dimSize]
stepSolvePixeloGameRows :: PixeloGame -> Maybe PixeloGame
stepSolvePixeloGameRows game =
stepSolvePixeloGameDims stepSolvePixeloGameRow height game
where
height = fst . snd . bounds $ pixeloGameGetBoard game
stepSolvePixeloGameCols :: PixeloGame -> Maybe PixeloGame
stepSolvePixeloGameCols game =
stepSolvePixeloGameDims stepSolvePixeloGameCol width game
where
width = snd . snd . bounds $ pixeloGameGetBoard game
emptyGameBoard :: Int -> Int -> Array (Int, Int) PixeloTile
emptyGameBoard height width = listArray ((0, 0), (height - 1, width - 1))
$ replicate (height * width) Unknown
stepSolvePixeloGame :: PixeloGame -> Maybe PixeloGame
stepSolvePixeloGame = stepSolvePixeloGameCols <=< stepSolvePixeloGameRows
-- | Solves the puzzle if it is solvable
solvePixeloGame :: PixeloGame -> Maybe PixeloGame
solvePixeloGame pixeloGame =
let
iteratedSols = iterate (>>= stepSolvePixeloGame) $ Just pixeloGame
pairedSkewedSols = zip iteratedSols (tail iteratedSols)
terminatingSols = takeWhile (\(sol0, sol1) -> sol0 /= sol1) pairedSkewedSols
in
snd . last $ terminatingSols
|
gregorias/pixelosolver
|
src/PixeloSolver/Game/Nonogram.hs
|
bsd-3-clause
| 9,090 | 0 | 19 | 1,932 | 2,798 | 1,495 | 1,303 | 215 | 5 |
{- |
Module : SAWScript.Crucible.LLVM.X86
Description : Implements a SAWScript primitive for verifying x86_64 functions
against LLVM specifications.
Maintainer : sbreese
Stability : provisional
-}
{-# Language OverloadedStrings #-}
{-# Language FlexibleContexts #-}
{-# Language ScopedTypeVariables #-}
{-# Language TypeOperators #-}
{-# Language PatternSynonyms #-}
{-# Language LambdaCase #-}
{-# Language MultiWayIf #-}
{-# Language TupleSections #-}
{-# Language ImplicitParams #-}
{-# Language TypeApplications #-}
{-# Language GADTs #-}
{-# Language DataKinds #-}
{-# Language RankNTypes #-}
{-# Language ConstraintKinds #-}
{-# Language GeneralizedNewtypeDeriving #-}
{-# Language TemplateHaskell #-}
module SAWScript.Crucible.LLVM.X86
( llvm_verify_x86
, defaultStackBaseAlign
) where
import Control.Lens.TH (makeLenses)
import System.IO (stdout)
import Control.Exception (throw)
import Control.Lens (Getter, to, view, use, (&), (^.), (.~), (%~), (.=))
import Control.Monad.State
import Control.Monad.Catch (MonadThrow)
import qualified Data.BitVector.Sized as BV
import Data.Foldable (foldlM)
import qualified Data.List.NonEmpty as NE
import qualified Data.Vector as Vector
import qualified Data.Text as Text
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe
import qualified Text.LLVM.AST as LLVM
import Data.Parameterized.Some
import Data.Parameterized.NatRepr
import Data.Parameterized.Context hiding (view)
import Verifier.SAW.CryptolEnv
import Verifier.SAW.FiniteValue
import Verifier.SAW.Name (toShortName)
import Verifier.SAW.SharedTerm
import Verifier.SAW.TypedTerm
import Verifier.SAW.Simulator.What4.ReturnTrip
import SAWScript.Proof
import SAWScript.Prover.SolverStats
import SAWScript.TopLevel
import SAWScript.Value
import SAWScript.Options
import SAWScript.X86 hiding (Options)
import SAWScript.X86Spec
import SAWScript.Crucible.Common
import qualified SAWScript.Crucible.Common as Common
import qualified SAWScript.Crucible.Common.MethodSpec as MS
import qualified SAWScript.Crucible.Common.Override as O
import qualified SAWScript.Crucible.Common.Setup.Type as Setup
import SAWScript.Crucible.LLVM.Builtins
import SAWScript.Crucible.LLVM.MethodSpecIR hiding (LLVM)
import SAWScript.Crucible.LLVM.ResolveSetupValue
import qualified SAWScript.Crucible.LLVM.Override as LO
import qualified SAWScript.Crucible.LLVM.MethodSpecIR as LMS (LLVM)
import qualified What4.Concrete as W4
import qualified What4.Config as W4
import qualified What4.Expr as W4
import qualified What4.FunctionName as W4
import qualified What4.Interface as W4
import qualified What4.LabeledPred as W4
import qualified What4.ProgramLoc as W4
import qualified What4.Expr.Builder as W4.B
import qualified Lang.Crucible.Analysis.Postdom as C
import qualified Lang.Crucible.Backend as C
import qualified Lang.Crucible.Backend.Online as C
import qualified Lang.Crucible.CFG.Core as C
import qualified Lang.Crucible.FunctionHandle as C
import qualified Lang.Crucible.Simulator.EvalStmt as C
import qualified Lang.Crucible.Simulator.ExecutionTree as C
import qualified Lang.Crucible.Simulator.GlobalState as C
import qualified Lang.Crucible.Simulator.Operations as C
import qualified Lang.Crucible.Simulator.OverrideSim as C
import qualified Lang.Crucible.Simulator.RegMap as C
import qualified Lang.Crucible.Simulator.SimError as C
import qualified Lang.Crucible.Simulator.PathSatisfiability as C
import qualified Lang.Crucible.LLVM.Bytes as C.LLVM
import qualified Lang.Crucible.LLVM.DataLayout as C.LLVM
import qualified Lang.Crucible.LLVM.Extension as C.LLVM
import qualified Lang.Crucible.LLVM.Intrinsics as C.LLVM
import qualified Lang.Crucible.LLVM.MemModel as C.LLVM
import qualified Lang.Crucible.LLVM.MemType as C.LLVM
import qualified Lang.Crucible.LLVM.Translation as C.LLVM
import qualified Lang.Crucible.LLVM.TypeContext as C.LLVM
import qualified Data.Macaw.Types as Macaw
import qualified Data.Macaw.Discovery as Macaw
import qualified Data.Macaw.Memory as Macaw
import qualified Data.Macaw.Symbolic as Macaw
import qualified Data.Macaw.Symbolic.Backend as Macaw
import qualified Data.Macaw.X86.Symbolic as Macaw
import qualified Data.Macaw.X86 as Macaw
import qualified Data.Macaw.X86.X86Reg as Macaw
import qualified Data.ElfEdit as Elf
-------------------------------------------------------------------------------
-- ** Utility type synonyms and functions
type LLVMArch = C.LLVM.X86 64
type LLVM = LMS.LLVM LLVMArch
type LLVMOverrideMatcher rorw a = O.OverrideMatcher LLVM rorw a
type Regs = Assignment (C.RegValue' Sym) (Macaw.MacawCrucibleRegTypes Macaw.X86_64)
type Register = Macaw.X86Reg (Macaw.BVType 64)
type Mem = C.LLVM.MemImpl Sym
type Ptr = C.LLVM.LLVMPtr Sym 64
type X86Constraints =
( C.LLVM.HasPtrWidth (C.LLVM.ArchWidth LLVMArch)
, C.LLVM.HasLLVMAnn Sym
, ?memOpts :: C.LLVM.MemOptions
, ?lc :: C.LLVM.TypeContext
, ?w4EvalTactic :: W4EvalTactic
)
newtype X86Sim a = X86Sim { unX86Sim :: StateT X86State IO a }
deriving (Functor, Applicative, Monad, MonadIO, MonadState X86State, MonadThrow)
data X86State = X86State
{ _x86Backend :: SomeOnlineBackend
, _x86Options :: Options
, _x86SharedContext :: SharedContext
, _x86CrucibleContext :: LLVMCrucibleContext LLVMArch
, _x86ElfSymtab :: Elf.Symtab 64
, _x86RelevantElf :: RelevantElf
, _x86MethodSpec :: MS.CrucibleMethodSpecIR LLVM
, _x86Mem :: Mem
, _x86Regs :: Regs
, _x86GlobalBase :: Ptr
}
makeLenses ''X86State
runX86Sim :: X86State -> X86Sim a -> IO (a, X86State)
runX86Sim st m = runStateT (unX86Sim m) st
throwX86 :: MonadThrow m => String -> m a
throwX86 = throw . X86Error
x86Sym :: Getter X86State Sym
x86Sym = to (\st -> case _x86Backend st of SomeOnlineBackend bak -> backendGetSym bak)
defaultStackBaseAlign :: Integer
defaultStackBaseAlign = 16
integerToAlignment ::
(MonadIO m, MonadThrow m) =>
Integer ->
m C.LLVM.Alignment
integerToAlignment i
| Just ba <- C.LLVM.toAlignment (C.LLVM.toBytes i) = pure ba
| otherwise = throwX86 $ mconcat ["Invalid alignment specified: ", show i]
setReg ::
(MonadIO m, MonadThrow m) =>
Register ->
C.RegValue Sym (C.LLVM.LLVMPointerType 64) ->
Regs ->
m Regs
setReg reg val regs
| Just regs' <- Macaw.updateX86Reg reg (C.RV . const val) regs = pure regs'
| otherwise = throwX86 $ mconcat ["Invalid register: ", show reg]
getReg ::
(MonadIO m, MonadThrow m) =>
Register ->
Regs ->
m (C.RegValue Sym (C.LLVM.LLVMPointerType 64))
getReg reg regs = case Macaw.lookupX86Reg reg regs of
Just (C.RV val) -> pure val
Nothing -> throwX86 $ mconcat ["Invalid register: ", show reg]
-- TODO: extend to more than general purpose registers
stringToReg :: Text -> Maybe (Some Macaw.X86Reg)
stringToReg s = case s of
"rax" -> Just $ Some Macaw.RAX
"rbx" -> Just $ Some Macaw.RBX
"rcx" -> Just $ Some Macaw.RCX
"rdx" -> Just $ Some Macaw.RDX
"rsp" -> Just $ Some Macaw.RSP
"rbp" -> Just $ Some Macaw.RBP
"rsi" -> Just $ Some Macaw.RSI
"rdi" -> Just $ Some Macaw.RDI
"r8" -> Just $ Some Macaw.R8
"r9" -> Just $ Some Macaw.R9
"r10" -> Just $ Some Macaw.R10
"r11" -> Just $ Some Macaw.R11
"r12" -> Just $ Some Macaw.R12
"r13" -> Just $ Some Macaw.R13
"r14" -> Just $ Some Macaw.R14
"r15" -> Just $ Some Macaw.R15
_ -> Nothing
cryptolUninterpreted ::
(MonadIO m, MonadThrow m) =>
CryptolEnv ->
String ->
SharedContext ->
[Term] ->
m Term
cryptolUninterpreted env nm sc xs =
case lookupIn nm $ eTermEnv env of
Left _err -> throwX86 $ mconcat
[ "Failed to lookup Cryptol name \"", nm
, "\" in Cryptol environment"
]
Right t -> liftIO $ scApplyAll sc t xs
llvmPointerBlock :: C.LLVM.LLVMPtr sym w -> W4.SymNat sym
llvmPointerBlock = fst . C.LLVM.llvmPointerView
llvmPointerOffset :: C.LLVM.LLVMPtr sym w -> W4.SymBV sym w
llvmPointerOffset = snd . C.LLVM.llvmPointerView
-- | Compare pointers that are not valid LLVM pointers. Comparing the offsets
-- as unsigned bitvectors is not sound, because of overflow (e.g. `base - 1` is
-- less than `base`, but -1 is not less than 0 when compared as unsigned). It
-- is safe to allow a small negative offset, because each pointer base is
-- mapped to an address that is not in the first page (4K), which is never
-- mapped on X86_64 Linux. Specifically, assume pointer1 = (base1, offset1) and
-- pointer2 = (base2, offset2), and size1 is the size of the allocation of
-- base1 and size2 is the size of the allocation of base2. If offset1 is in the
-- interval [-4096, size1], and offset2 is in the interval [-4096, size2], then
-- the unsigned comparison between pointer1 and pointer2 is equivalent with the
-- unsigned comparison between offset1 + 4096 and offset2 + 4096.
doPtrCmp ::
(sym -> W4.SymBV sym w -> W4.SymBV sym w -> IO (W4.Pred sym)) ->
Macaw.PtrOp sym w (C.RegValue sym C.BoolType)
doPtrCmp f = Macaw.ptrOp $ \bak mem w xPtr xBits yPtr yBits x y -> do
let sym = backendGetSym bak
let ptr_as_bv_for_cmp ptr = do
page_size <- W4.bvLit sym (W4.bvWidth $ llvmPointerOffset ptr) $
BV.mkBV (W4.bvWidth $ llvmPointerOffset ptr) 4096
ptr_as_bv <- W4.bvAdd sym (llvmPointerOffset ptr) page_size
is_valid <- Macaw.isValidPtr sym mem w ptr
is_negative_offset <- W4.bvIsNeg sym (llvmPointerOffset ptr)
is_not_overflow <- W4.notPred sym =<< W4.bvIsNeg sym ptr_as_bv
ok <- W4.orPred sym is_valid
=<< W4.andPred sym is_negative_offset is_not_overflow
return (ptr_as_bv, ok)
both_bits <- W4.andPred sym xBits yBits
both_ptrs <- W4.andPred sym xPtr yPtr
same_region <- W4.natEq sym (llvmPointerBlock x) (llvmPointerBlock y)
(x_ptr_as_bv, ok_x) <- ptr_as_bv_for_cmp x
(y_ptr_as_bv, ok_y) <- ptr_as_bv_for_cmp y
ok_both_ptrs <- W4.andPred sym both_ptrs
=<< W4.andPred sym same_region
=<< W4.andPred sym ok_x ok_y
res_both_bits <- f sym (llvmPointerOffset x) (llvmPointerOffset y)
res_both_ptrs <- f sym x_ptr_as_bv y_ptr_as_bv
undef <- Macaw.mkUndefinedBool sym "ptr_cmp"
W4.itePred sym both_bits res_both_bits
=<< W4.itePred sym ok_both_ptrs res_both_ptrs undef
-------------------------------------------------------------------------------
-- ** Entrypoint
-- | Verify that an x86_64 function (following the System V AMD64 ABI) conforms
-- to an LLVM specification. This allows for compositional verification of LLVM
-- functions that call x86_64 functions (but not the other way around).
llvm_verify_x86 ::
Some LLVMModule {- ^ Module to associate with method spec -} ->
FilePath {- ^ Path to ELF file -} ->
String {- ^ Function's symbol in ELF file -} ->
[(String, Integer)] {- ^ Global variable symbol names and sizes (in bytes) -} ->
Bool {- ^ Whether to enable path satisfiability checking -} ->
LLVMCrucibleSetupM () {- ^ Specification to verify against -} ->
ProofScript () {- ^ Tactic used to use when discharging goals -} ->
TopLevel (SomeLLVM MS.ProvedSpec)
llvm_verify_x86 (Some (llvmModule :: LLVMModule x)) path nm globsyms checkSat setup tactic
| Just Refl <- testEquality (C.LLVM.X86Repr $ knownNat @64) . C.LLVM.llvmArch
$ modTrans llvmModule ^. C.LLVM.transContext = do
start <- io getCurrentTime
laxLoadsAndStores <- gets rwLaxLoadsAndStores
let ?ptrWidth = knownNat @64
let ?memOpts = C.LLVM.defaultMemOptions
{ C.LLVM.laxLoadsAndStores = laxLoadsAndStores
}
let ?recordLLVMAnnotation = \_ _ _ -> return ()
sc <- getSharedContext
opts <- getOptions
basic_ss <- getBasicSS
rw <- getTopLevelRW
sym <- liftIO $ newSAWCoreExprBuilder sc
SomeOnlineBackend bak <- liftIO $ newSAWCoreBackendWithTimeout sym $ rwCrucibleTimeout rw
cacheTermsSetting <- liftIO $ W4.getOptionSetting W4.B.cacheTerms $ W4.getConfiguration sym
_ <- liftIO $ W4.setOpt cacheTermsSetting $ rwWhat4HashConsingX86 rw
liftIO $ W4.extendConfig
[ W4.opt
LO.enableSMTArrayMemoryModel
(W4.ConcreteBool $ rwSMTArrayMemoryModel rw)
("Enable SMT array memory model" :: Text)
]
(W4.getConfiguration sym)
let ?w4EvalTactic = W4EvalTactic { doW4Eval = rwWhat4Eval rw }
sawst <- liftIO $ sawCoreState sym
halloc <- getHandleAlloc
let mvar = C.LLVM.llvmMemVar . view C.LLVM.transContext $ modTrans llvmModule
sfs <- liftIO $ Macaw.newSymFuns sym
let cenv = rwCryptol rw
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnAesEnc sfs) $ cryptolUninterpreted cenv "aesenc"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnAesEncLast sfs) $ cryptolUninterpreted cenv "aesenclast"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnAesDec sfs) $ cryptolUninterpreted cenv "aesdec"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnAesDecLast sfs) $ cryptolUninterpreted cenv "aesdeclast"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnAesKeyGenAssist sfs) $ cryptolUninterpreted cenv "aeskeygenassist"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnAesIMC sfs) $ cryptolUninterpreted cenv "aesimc"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnClMul sfs) $ cryptolUninterpreted cenv "clmul"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnShasigma0 sfs) $ cryptolUninterpreted cenv "sigma_0"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnShasigma1 sfs) $ cryptolUninterpreted cenv "sigma_1"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnShaSigma0 sfs) $ cryptolUninterpreted cenv "SIGMA_0"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnShaSigma1 sfs) $ cryptolUninterpreted cenv "SIGMA_1"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnShaCh sfs) $ cryptolUninterpreted cenv "Ch"
liftIO $ sawRegisterSymFunInterp sawst (Macaw.fnShaMaj sfs) $ cryptolUninterpreted cenv "Maj"
let preserved = Set.fromList . catMaybes $ stringToReg . Text.toLower . Text.pack <$> rwPreservedRegs rw
(C.SomeCFG cfg, elf, relf, addr, cfgs) <- io $ buildCFG opts halloc preserved path nm
addrInt <- if Macaw.segmentBase (Macaw.segoffSegment addr) == 0
then pure . toInteger $ Macaw.segmentOffset (Macaw.segoffSegment addr) + Macaw.segoffOffset addr
else fail $ mconcat ["Address of \"", nm, "\" is not an absolute address"]
let maxAddr = addrInt + toInteger (Macaw.segmentSize $ Macaw.segoffSegment addr)
let
cc :: LLVMCrucibleContext x
cc = LLVMCrucibleContext
{ _ccLLVMModule = llvmModule
, _ccBackend = SomeOnlineBackend bak
, _ccBasicSS = basic_ss
-- It's unpleasant that we need to do this to use resolveSetupVal.
, _ccLLVMSimContext = error "Attempted to access ccLLVMSimContext"
, _ccLLVMGlobals = error "Attempted to access ccLLVMGlobals"
}
liftIO . printOutLn opts Info $ mconcat
[ "Simulating function \""
, nm
, "\" (at address "
, show addr
, ")"
]
liftIO $ printOutLn opts Info "Examining specification to determine preconditions"
methodSpec <- buildMethodSpec llvmModule nm (show addr) checkSat setup
let ?lc = modTrans llvmModule ^. C.LLVM.transContext . C.LLVM.llvmTypeCtx
emptyState <- io $ initialState bak opts sc cc elf relf methodSpec globsyms maxAddr
balign <- integerToAlignment $ rwStackBaseAlign rw
(env, preState) <- io . runX86Sim emptyState $ setupMemory globsyms balign
let
funcLookup = Macaw.LookupFunctionHandle $ \st _mem regs -> do
C.LLVM.LLVMPointer _base off <- getReg Macaw.X86_IP regs
case BV.asUnsigned <$> W4.asBV off of
Nothing -> fail $ mconcat
[ "Attempted to call a function with non-concrete address "
, show $ W4.ppExpr off
]
Just funcAddr -> do
case Macaw.resolveRegionOff (memory relf) 0 $ fromIntegral funcAddr of
Nothing -> fail $ mconcat
[ "Failed to resolve function address "
, show $ W4.ppExpr off
]
Just funcAddrOff -> do
case Map.lookup funcAddrOff cfgs of
Just (C.SomeCFG funcCFG) ->
pure
( C.cfgHandle funcCFG
, st & C.stateContext . C.functionBindings
%~ C.FnBindings . C.insertHandleMap (C.cfgHandle funcCFG) (C.UseCFG funcCFG $ C.postdomInfo funcCFG) . C.fnBindings
)
Nothing -> fail $ mconcat
[ "Unable to find CFG for function at address "
, show $ W4.ppExpr off
]
archEvalFns = Macaw.x86_64MacawEvalFn sfs Macaw.defaultMacawArchStmtExtensionOverride
lookupSyscall = Macaw.unsupportedSyscalls "saw-script"
noExtraValidityPred _ _ _ _ = return Nothing
defaultMacawExtensions_x86_64 =
Macaw.macawExtensions
archEvalFns mvar
(mkGlobalMap . Map.singleton 0 $ preState ^. x86GlobalBase)
funcLookup
lookupSyscall
noExtraValidityPred
sawMacawExtensions = defaultMacawExtensions_x86_64
{ C.extensionExec = \s0 st -> case s0 of
Macaw.PtrLt w x y -> doPtrCmp W4.bvUlt st mvar w x y
Macaw.PtrLeq w x y -> doPtrCmp W4.bvUle st mvar w x y
_ -> (C.extensionExec defaultMacawExtensions_x86_64) s0 st
}
ctx :: C.SimContext (Macaw.MacawSimulatorState Sym) Sym (Macaw.MacawExt Macaw.X86_64)
ctx = C.SimContext
{ C._ctxBackend = SomeBackend bak
, C.ctxSolverProof = \x -> x
, C.ctxIntrinsicTypes = C.LLVM.llvmIntrinsicTypes
, C.simHandleAllocator = halloc
, C.printHandle = stdout
, C.extensionImpl = sawMacawExtensions
, C._functionBindings = C.FnBindings $ C.insertHandleMap (C.cfgHandle cfg) (C.UseCFG cfg $ C.postdomInfo cfg) C.emptyHandleMap
, C._cruciblePersonality = Macaw.MacawSimulatorState
, C._profilingMetrics = Map.empty
}
globals = C.insertGlobal mvar (preState ^. x86Mem) C.emptyGlobals
macawStructRepr = C.StructRepr $ Macaw.crucArchRegTypes Macaw.x86_64MacawSymbolicFns
initial = C.InitialState ctx globals C.defaultAbortHandler macawStructRepr
$ C.runOverrideSim macawStructRepr
$ Macaw.crucGenArchConstraints Macaw.x86_64MacawSymbolicFns
$ do
r <- C.callCFG cfg . C.RegMap . singleton . C.RegEntry macawStructRepr $ preState ^. x86Regs
globals' <- C.readGlobals
mem' <- C.readGlobal mvar
let finalState = preState
{ _x86Mem = mem'
, _x86Regs = C.regValue r
, _x86CrucibleContext = cc & ccLLVMGlobals .~ globals'
}
liftIO $ printOutLn opts Info
"Examining specification to determine postconditions"
liftIO . void . runX86Sim finalState $ assertPost globals' env (preState ^. x86Mem) (preState ^. x86Regs)
pure $ C.regValue r
liftIO $ printOutLn opts Info "Simulating function"
psatf <-
if checkSat then
do f <- liftIO (C.pathSatisfiabilityFeature sym (C.considerSatisfiability bak))
pure [C.genericToExecutionFeature f]
else
pure []
let execFeatures = psatf
liftIO $ C.executeCrucible execFeatures initial >>= \case
C.FinishedResult{} -> pure ()
C.AbortedResult _ ar -> do
printOutLn opts Warn "Warning: function never returns"
print $ Common.ppAbortedResult
( \gp ->
case C.lookupGlobal mvar $ gp ^. C.gpGlobals of
Nothing -> "LLVM memory global variable not initialized"
Just mem -> C.LLVM.ppMem $ C.LLVM.memImplHeap mem
)
ar
C.TimeoutResult{} -> fail "Execution timed out"
(stats,thms) <- checkGoals bak opts sc tactic
end <- io getCurrentTime
let diff = diffUTCTime end start
ps <- io (MS.mkProvedSpec MS.SpecProved methodSpec stats thms mempty diff)
returnProof $ SomeLLVM ps
| otherwise = fail "LLVM module must be 64-bit"
--------------------------------------------------------------------------------
-- ** Computing the CFG
-- | Load the given ELF file and use Macaw to construct a Crucible CFG.
buildCFG ::
Options ->
C.HandleAllocator ->
Set (Some Macaw.X86Reg) {- ^ Registers to treat as callee-saved -} ->
String {- ^ Path to ELF file -} ->
String {- ^ Function's symbol in ELF file -} ->
IO ( C.SomeCFG
(Macaw.MacawExt Macaw.X86_64)
(EmptyCtx ::> Macaw.ArchRegStruct Macaw.X86_64)
(Macaw.ArchRegStruct Macaw.X86_64)
, Elf.ElfHeaderInfo 64
, RelevantElf
, Macaw.MemSegmentOff 64
, Map
(Macaw.MemSegmentOff 64)
(C.SomeCFG
(Macaw.MacawExt Macaw.X86_64)
(EmptyCtx ::> Macaw.ArchRegStruct Macaw.X86_64)
(Macaw.ArchRegStruct Macaw.X86_64))
)
buildCFG opts halloc preserved path nm = do
printOutLn opts Info $ mconcat ["Finding symbol for \"", nm, "\""]
elf <- getElf path
relf <- getRelevant elf
(addr :: Macaw.MemSegmentOff 64) <-
case findSymbols (symMap relf) . encodeUtf8 $ Text.pack nm of
(addr:_) -> pure addr
_ -> fail $ mconcat ["Could not find symbol \"", nm, "\""]
printOutLn opts Info $ mconcat ["Found symbol at address ", show addr, ", building CFG"]
let
preservedRegs = Set.union preserved Macaw.x86CalleeSavedRegs
preserveFn :: forall t. Macaw.X86Reg t -> Bool
preserveFn r = Set.member (Some r) preservedRegs
macawCallParams = Macaw.x86_64CallParams { Macaw.preserveReg = preserveFn }
macawArchInfo = (Macaw.x86_64_info preserveFn)
{ Macaw.archCallParams = macawCallParams
}
initialDiscoveryState =
Macaw.emptyDiscoveryState (memory relf) (funSymMap relf) macawArchInfo
-- "inline" any function addresses that we happen to jump to
& Macaw.trustedFunctionEntryPoints .~ Map.empty
finalState = Macaw.cfgFromAddrsAndState initialDiscoveryState [addr] []
finfos = finalState ^. Macaw.funInfo
cfgs <- forM finfos $ \(Some finfo) ->
Macaw.mkFunCFG Macaw.x86_64MacawSymbolicFns halloc
(W4.functionNameFromText . decodeUtf8 $ Macaw.discoveredFunName finfo)
posFn finfo
case Map.lookup addr cfgs of
Nothing -> throwX86 $ "Unable to discover CFG from address " <> show addr
Just scfg -> pure (scfg, elf, relf, addr, cfgs)
--------------------------------------------------------------------------------
-- ** Computing the specification
-- | Construct the method spec like we normally would in llvm_verify.
-- Unlike in llvm_verify, we can't reuse the simulator state (due to the
-- different memory layout / RegMap).
buildMethodSpec ::
LLVMModule LLVMArch ->
String {- ^ Name of method -} ->
String {- ^ Source location for method spec (here, we use the address) -} ->
Bool {- ^ check sat -} ->
LLVMCrucibleSetupM () ->
TopLevel (MS.CrucibleMethodSpecIR LLVM)
buildMethodSpec lm nm loc checkSat setup =
setupLLVMCrucibleContext checkSat lm $ \cc -> do
let methodId = LLVMMethodId nm Nothing
let programLoc =
W4.mkProgramLoc (W4.functionNameFromText $ Text.pack nm)
. W4.OtherPos $ Text.pack loc
let lc = modTrans lm ^. C.LLVM.transContext . C.LLVM.llvmTypeCtx
opts <- getOptions
(args, ret) <- case llvmSignature opts lm nm of
Left err -> fail $ mconcat ["Could not find declaration for \"", nm, "\": ", err]
Right x -> pure x
(mtargs, mtret) <- case (,) <$> mapM (llvmTypeToMemType lc) args <*> mapM (llvmTypeToMemType lc) ret of
Left err -> fail err
Right x -> pure x
let initialMethodSpec = MS.makeCrucibleMethodSpecIR @LLVM
methodId mtargs mtret programLoc lm
view Setup.csMethodSpec <$> execStateT (runLLVMCrucibleSetupM setup)
(Setup.makeCrucibleSetupState emptyResolvedState cc initialMethodSpec)
llvmTypeToMemType ::
C.LLVM.TypeContext ->
LLVM.Type ->
Either String C.LLVM.MemType
llvmTypeToMemType lc t = let ?lc = lc in C.LLVM.liftMemType t
-- | Find a function declaration in the LLVM AST and return its signature.
llvmSignature ::
Options ->
LLVMModule LLVMArch ->
String ->
Either String ([LLVM.Type], Maybe LLVM.Type)
llvmSignature opts llvmModule nm =
case findDecl (modAST llvmModule) nm of
Left err -> case findDefMaybeStatic (modAST llvmModule) nm of
Left _ -> Left $ displayVerifExceptionOpts opts err
Right defs -> pure
( LLVM.typedType <$> LLVM.defArgs (NE.head defs)
, case LLVM.defRetType $ NE.head defs of
LLVM.PrimType LLVM.Void -> Nothing
x -> Just x
)
Right decl -> pure
( LLVM.decArgs decl
, case LLVM.decRetType decl of
LLVM.PrimType LLVM.Void -> Nothing
x -> Just x
)
--------------------------------------------------------------------------------
-- ** Building the initial state
initialState ::
(X86Constraints, OnlineSolver solver) =>
Backend solver ->
Options ->
SharedContext ->
LLVMCrucibleContext LLVMArch ->
Elf.ElfHeaderInfo 64 ->
RelevantElf ->
MS.CrucibleMethodSpecIR LLVM ->
[(String, Integer)] {- ^ Global variable symbol names and sizes (in bytes) -} ->
Integer {- ^ Minimum size of the global allocation (here, the end of the .text segment -} ->
IO X86State
initialState bak opts sc cc elf relf ms globs maxAddr = do
let sym = backendGetSym bak
emptyMem <- C.LLVM.emptyMem C.LLVM.LittleEndian
emptyRegs <- traverseWithIndex (freshRegister sym) C.knownRepr
symTab <- case Elf.decodeHeaderSymtab elf of
Nothing -> throwX86 "Elf file has no symbol table"
Just (Left _err) -> throwX86 "Failed to decode symbol table"
Just (Right st) -> pure st
let
align = C.LLVM.exponentToAlignment 4
allocGlobalEnd :: MS.AllocGlobal LLVM -> Integer
allocGlobalEnd (LLVMAllocGlobal _ (LLVM.Symbol nm)) = globalEnd nm
globalEnd :: String -> Integer
globalEnd nm = maybe 0 (\entry -> fromIntegral $ Elf.steValue entry + Elf.steSize entry) $
(Vector.!? 0)
. Vector.filter (\e -> Elf.steName e == encodeUtf8 (Text.pack nm))
$ Elf.symtabEntries symTab
sz <- W4.bvLit sym knownNat . BV.mkBV knownNat . maximum $ mconcat
[ [maxAddr, globalEnd "_end"]
, globalEnd . fst <$> globs
, allocGlobalEnd <$> ms ^. MS.csGlobalAllocs
]
(base, mem) <- C.LLVM.doMalloc bak C.LLVM.GlobalAlloc C.LLVM.Immutable
"globals" emptyMem sz align
pure $ X86State
{ _x86Backend = SomeOnlineBackend bak
, _x86Options = opts
, _x86SharedContext = sc
, _x86CrucibleContext = cc
, _x86ElfSymtab = symTab
, _x86RelevantElf = relf
, _x86MethodSpec = ms
, _x86Mem = mem
, _x86Regs = emptyRegs
, _x86GlobalBase = base
}
--------------------------------------------------------------------------------
-- ** Precondition
-- | Given the method spec, build the initial memory, register map, and global map.
setupMemory ::
X86Constraints =>
[(String, Integer)] {- ^ Global variable symbol names and sizes (in bytes) -} ->
C.LLVM.Alignment {- ^ Stack base alignment -} ->
X86Sim (Map MS.AllocIndex Ptr)
setupMemory globsyms balign = do
setupGlobals globsyms
-- Allocate a reasonable amount of stack (4 KiB + 0b10000 for least valid alignment + 1 qword for IP)
allocateStack (4096 + 16) balign
ms <- use x86MethodSpec
let
tyenv = ms ^. MS.csPreState . MS.csAllocs
nameEnv = MS.csTypeNames ms
env <- foldlM assumeAllocation Map.empty . Map.assocs $ tyenv
mapM_ (assumePointsTo env tyenv nameEnv) $ ms ^. MS.csPreState . MS.csPointsTos
setArgs env tyenv nameEnv . fmap snd . Map.elems $ ms ^. MS.csArgBindings
pure env
-- | Given an alist of symbol names and sizes (in bytes), allocate space and copy
-- the corresponding globals from the Macaw memory to the Crucible LLVM memory model.
setupGlobals ::
X86Constraints =>
[(String, Integer)] {- ^ Global variable symbol names and sizes (in bytes) -} ->
X86Sim ()
setupGlobals globsyms = do
SomeOnlineBackend bak <- use x86Backend
sym <- use x86Sym
mem <- use x86Mem
relf <- use x86RelevantElf
base <- use x86GlobalBase
let
readInitialGlobal :: (String, Integer) -> IO [(String, Integer, [Integer])]
readInitialGlobal (nm, sz) = do
res <- loadGlobal relf (encodeUtf8 $ Text.pack nm, sz, Bytes)
pure $ (\(name, addr, _unit, bytes) -> (name, addr, bytes)) <$> res
convertByte :: Integer -> IO (C.LLVM.LLVMVal Sym)
convertByte byte =
C.LLVM.LLVMValInt <$> W4.natLit sym 0 <*> W4.bvLit sym (knownNat @8) (BV.mkBV knownNat byte)
writeGlobal :: Mem -> (String, Integer, [Integer]) -> IO Mem
writeGlobal m (_nm, addr, bytes) = do
ptr <- C.LLVM.doPtrAddOffset bak m base =<< W4.bvLit sym knownNat (BV.mkBV knownNat addr)
v <- Vector.fromList <$> mapM convertByte bytes
let st = C.LLVM.arrayType (fromIntegral $ length bytes) $ C.LLVM.bitvectorType 1
C.LLVM.storeConstRaw bak m ptr st C.LLVM.noAlignment
$ C.LLVM.LLVMValArray (C.LLVM.bitvectorType 1) v
globs <- liftIO $ mconcat <$> mapM readInitialGlobal globsyms
mem' <- liftIO $ foldlM writeGlobal mem globs
x86Mem .= mem'
-- | Allocate memory for the stack, and pushes a fresh pointer as the return
-- address.
allocateStack ::
X86Constraints =>
Integer {- ^ Stack size in bytes -} ->
C.LLVM.Alignment {- ^ Stack base alignment -} ->
X86Sim ()
allocateStack szInt balign = do
SomeOnlineBackend bak <- use x86Backend
sym <- use x86Sym
mem <- use x86Mem
regs <- use x86Regs
sz <- liftIO $ W4.bvLit sym knownNat $ BV.mkBV knownNat $ szInt + 8
(base, mem') <- liftIO $ C.LLVM.doMalloc bak C.LLVM.HeapAlloc C.LLVM.Mutable "stack_alloc" mem sz balign
sn <- case W4.userSymbol "stack" of
Left err -> throwX86 $ "Invalid symbol for stack: " <> show err
Right sn -> pure sn
fresh <- liftIO $ C.LLVM.LLVMPointer
<$> W4.natLit sym 0
<*> W4.freshConstant sym sn (W4.BaseBVRepr $ knownNat @64)
ptr <- liftIO $ C.LLVM.doPtrAddOffset bak mem' base =<< W4.bvLit sym knownNat (BV.mkBV knownNat szInt)
writeAlign <- integerToAlignment defaultStackBaseAlign
finalMem <- liftIO $ C.LLVM.doStore bak mem' ptr
(C.LLVM.LLVMPointerRepr $ knownNat @64)
(C.LLVM.bitvectorType 8) writeAlign fresh
x86Mem .= finalMem
finalRegs <- setReg Macaw.RSP ptr regs
x86Regs .= finalRegs
-- | Process an llvm_alloc statement, allocating the requested memory and
-- associating a pointer to that memory with the appropriate index.
assumeAllocation ::
X86Constraints =>
Map MS.AllocIndex Ptr ->
(MS.AllocIndex, LLVMAllocSpec) {- ^ llvm_alloc statement -} ->
X86Sim (Map MS.AllocIndex Ptr)
assumeAllocation env (i, LLVMAllocSpec mut _memTy align sz loc False initialization) = do
SomeOnlineBackend bak <- use x86Backend
cc <- use x86CrucibleContext
mem <- use x86Mem
sz' <- liftIO $ resolveSAWSymBV cc knownNat sz
(ptr, mem') <- liftIO $ LO.doAllocSymInit bak mem mut align sz' (show $ W4.plSourceLoc loc) initialization
x86Mem .= mem'
pure $ Map.insert i ptr env
assumeAllocation env _ = pure env
-- no allocation is done for llvm_fresh_pointer
-- TODO: support llvm_fresh_pointer in x86 verification
-- | Process an llvm_points_to statement, writing some SetupValue to a pointer.
assumePointsTo ::
X86Constraints =>
Map MS.AllocIndex Ptr {- ^ Associates each AllocIndex with the corresponding allocation -} ->
Map MS.AllocIndex LLVMAllocSpec {- ^ Associates each AllocIndex with its specification -} ->
Map MS.AllocIndex C.LLVM.Ident {- ^ Associates each AllocIndex with its name -} ->
LLVMPointsTo LLVMArch {- ^ llvm_points_to statement from the precondition -} ->
X86Sim ()
assumePointsTo env tyenv nameEnv (LLVMPointsTo _ cond tptr tptval) = do
opts <- use x86Options
cc <- use x86CrucibleContext
mem <- use x86Mem
ptr <- resolvePtrSetupValue env tyenv nameEnv tptr
cond' <- liftIO $ mapM (resolveSAWPred cc . ttTerm) cond
mem' <- liftIO $ LO.storePointsToValue opts cc env tyenv nameEnv mem cond' ptr tptval Nothing
x86Mem .= mem'
assumePointsTo env tyenv nameEnv (LLVMPointsToBitfield _ tptr fieldName tptval) = do
opts <- use x86Options
cc <- use x86CrucibleContext
mem <- use x86Mem
(bfIndex, ptr) <- resolvePtrSetupValueBitfield env tyenv nameEnv tptr fieldName
mem' <- liftIO $ LO.storePointsToBitfieldValue opts cc env tyenv nameEnv mem ptr bfIndex tptval
x86Mem .= mem'
resolvePtrSetupValue ::
X86Constraints =>
Map MS.AllocIndex Ptr ->
Map MS.AllocIndex LLVMAllocSpec ->
Map MS.AllocIndex C.LLVM.Ident {- ^ Associates each AllocIndex with its name -} ->
MS.SetupValue LLVM ->
X86Sim Ptr
resolvePtrSetupValue env tyenv nameEnv tptr = do
SomeOnlineBackend bak <- use x86Backend
sym <- use x86Sym
cc <- use x86CrucibleContext
mem <- use x86Mem
symTab <- use x86ElfSymtab
base <- use x86GlobalBase
case tptr of
MS.SetupGlobal () nm -> case
(Vector.!? 0)
. Vector.filter (\e -> Elf.steName e == encodeUtf8 (Text.pack nm))
$ Elf.symtabEntries symTab of
Nothing -> throwX86 $ mconcat ["Global symbol \"", nm, "\" not found"]
Just entry -> do
let addr = fromIntegral $ Elf.steValue entry
liftIO $ C.LLVM.doPtrAddOffset bak mem base =<< W4.bvLit sym knownNat (BV.mkBV knownNat addr)
_ -> liftIO $ C.LLVM.unpackMemValue sym (C.LLVM.LLVMPointerRepr $ knownNat @64)
=<< resolveSetupVal cc mem env tyenv nameEnv tptr
-- | Like 'resolvePtrSetupValue', but specifically geared towards the needs of
-- fields within bitfields. In addition to returning the resolved 'Ptr', this
-- also returns the 'BitfieldIndex' for the field within the bitfield. This
-- ends up being useful for call sites to this function so that they do not
-- have to recompute it.
resolvePtrSetupValueBitfield ::
X86Constraints =>
Map MS.AllocIndex Ptr ->
Map MS.AllocIndex LLVMAllocSpec ->
Map MS.AllocIndex C.LLVM.Ident {- ^ Associates each AllocIndex with its name -} ->
MS.SetupValue LLVM ->
String ->
X86Sim (BitfieldIndex, Ptr)
resolvePtrSetupValueBitfield env tyenv nameEnv tptr fieldName = do
sym <- use x86Sym
cc <- use x86CrucibleContext
mem <- use x86Mem
-- symTab <- use x86ElfSymtab
-- base <- use x86GlobalBase
case tptr of
-- TODO RGS: What should we do about the SetupGlobal case?
{-
MS.SetupGlobal () nm -> case
(Vector.!? 0)
. Vector.filter (\e -> Elf.steName e == encodeUtf8 (Text.pack nm))
$ Elf.symtabEntries symTab of
Nothing -> throwX86 $ mconcat ["Global symbol \"", nm, "\" not found"]
Just entry -> do
let addr = fromIntegral $ Elf.steValue entry
liftIO $ C.LLVM.doPtrAddOffset sym mem base =<< W4.bvLit sym knownNat (BV.mkBV knownNat addr)
-}
_ -> do
(bfIndex, lval) <- liftIO $ resolveSetupValBitfield cc mem env tyenv nameEnv tptr fieldName
val <- liftIO $ C.LLVM.unpackMemValue sym (C.LLVM.LLVMPointerRepr $ knownNat @64) lval
pure (bfIndex, val)
-- | Write each SetupValue passed to llvm_execute_func to the appropriate
-- x86_64 register from the calling convention.
setArgs ::
X86Constraints =>
Map MS.AllocIndex Ptr {- ^ Associates each AllocIndex with the corresponding allocation -} ->
Map MS.AllocIndex LLVMAllocSpec {- ^ Associates each AllocIndex with its specification -} ->
Map MS.AllocIndex C.LLVM.Ident {- ^ Associates each AllocIndex with its name -} ->
[MS.SetupValue LLVM] {- ^ Arguments passed to llvm_execute_func -} ->
X86Sim ()
setArgs env tyenv nameEnv args
| length args > length argRegs = throwX86 "More arguments than would fit into general-purpose registers"
| otherwise = do
sym <- use x86Sym
cc <- use x86CrucibleContext
mem <- use x86Mem
let
setRegSetupValue rs (reg, sval) =
exceptToFail (typeOfSetupValue cc tyenv nameEnv sval) >>= \case
C.LLVM.PtrType _ -> do
val <- C.LLVM.unpackMemValue sym (C.LLVM.LLVMPointerRepr $ knownNat @64)
=<< resolveSetupVal cc mem env tyenv nameEnv sval
setReg reg val rs
C.LLVM.IntType 64 -> do
val <- C.LLVM.unpackMemValue sym (C.LLVM.LLVMPointerRepr $ knownNat @64)
=<< resolveSetupVal cc mem env tyenv nameEnv sval
setReg reg val rs
C.LLVM.IntType _ -> do
C.LLVM.LLVMValInt base off <- resolveSetupVal cc mem env tyenv nameEnv sval
case testLeq (incNat $ W4.bvWidth off) (knownNat @64) of
Nothing -> fail "Argument bitvector does not fit in a single general-purpose register"
Just LeqProof -> do
off' <- W4.bvZext sym (knownNat @64) off
val <- C.LLVM.unpackMemValue sym (C.LLVM.LLVMPointerRepr $ knownNat @64)
$ C.LLVM.LLVMValInt base off'
setReg reg val rs
_ -> fail "Argument does not fit into a single general-purpose register"
regs <- use x86Regs
newRegs <- liftIO . foldlM setRegSetupValue regs $ zip argRegs args
x86Regs .= newRegs
where argRegs = [Macaw.RDI, Macaw.RSI, Macaw.RDX, Macaw.RCX, Macaw.R8, Macaw.R9]
--------------------------------------------------------------------------------
-- ** Postcondition
-- | Assert the postcondition for the spec, given the final memory and register map.
assertPost ::
X86Constraints =>
C.SymGlobalState Sym ->
Map MS.AllocIndex Ptr ->
Mem {- ^ The state of memory before simulation -} ->
Regs {- ^ The state of the registers before simulation -} ->
X86Sim ()
assertPost globals env premem preregs = do
SomeOnlineBackend bak <- use x86Backend
sym <- use x86Sym
opts <- use x86Options
sc <- use x86SharedContext
cc <- use x86CrucibleContext
ms <- use x86MethodSpec
postregs <- use x86Regs
let
tyenv = ms ^. MS.csPreState . MS.csAllocs
nameEnv = MS.csTypeNames ms
prersp <- getReg Macaw.RSP preregs
expectedIP <- liftIO $ C.LLVM.doLoad bak premem prersp (C.LLVM.bitvectorType 8)
(C.LLVM.LLVMPointerRepr $ knownNat @64) C.LLVM.noAlignment
actualIP <- getReg Macaw.X86_IP postregs
correctRetAddr <- liftIO $ C.LLVM.ptrEq sym C.LLVM.PtrWidth actualIP expectedIP
liftIO . C.addAssertion bak . C.LabeledPred correctRetAddr . C.SimError W4.initializationLoc
$ C.AssertFailureSimError "Instruction pointer not set to return address" ""
stack <- liftIO $ C.LLVM.doPtrAddOffset bak premem prersp =<< W4.bvLit sym knownNat (BV.mkBV knownNat 8)
postrsp <- getReg Macaw.RSP postregs
correctStack <- liftIO $ C.LLVM.ptrEq sym C.LLVM.PtrWidth stack postrsp
liftIO $ C.addAssertion bak . C.LabeledPred correctStack . C.SimError W4.initializationLoc
$ C.AssertFailureSimError "Stack not preserved" ""
returnMatches <- case (ms ^. MS.csRetValue, ms ^. MS.csRet) of
(Just expectedRet, Just retTy) -> do
postRAX <- C.LLVM.ptrToPtrVal <$> getReg Macaw.RAX postregs
case (postRAX, C.LLVM.memTypeBitwidth retTy) of
(C.LLVM.LLVMValInt base off, Just retTyBits) -> do
let
truncateRAX :: forall r. NatRepr r -> X86Sim (C.LLVM.LLVMVal Sym)
truncateRAX rsz =
case (testLeq (knownNat @1) rsz, testLeq rsz (W4.bvWidth off)) of
(Just LeqProof, Just LeqProof) ->
case testStrictLeq rsz (W4.bvWidth off) of
Left LeqProof -> do
offTrunc <- liftIO $ W4.bvTrunc sym rsz off
pure $ C.LLVM.LLVMValInt base offTrunc
_ -> pure $ C.LLVM.LLVMValInt base off
_ -> throwX86 "Width of return type is zero bits"
postRAXTrunc <- viewSome truncateRAX (mkNatRepr retTyBits)
pure [LO.matchArg opts sc cc ms MS.PostState postRAXTrunc retTy expectedRet]
_ -> throwX86 $ "Invalid return type: " <> show (C.LLVM.ppMemType retTy)
_ -> pure []
pointsToMatches <- forM (ms ^. MS.csPostState . MS.csPointsTos)
$ assertPointsTo env tyenv nameEnv
let setupConditionMatchesPre = fmap -- assume preconditions
(LO.executeSetupCondition opts sc cc ms)
$ ms ^. MS.csPreState . MS.csConditions
let setupConditionMatchesPost = fmap -- assert postconditions
(LO.learnSetupCondition opts sc cc ms MS.PostState)
$ ms ^. MS.csPostState . MS.csConditions
let
initialECs = Map.fromList
[ (ecVarIndex ec, ec)
| tt <- ms ^. MS.csPreState . MS.csFreshVars
, let ec = tecExt tt
]
initialFree = Set.fromList . fmap (ecVarIndex . tecExt) $ ms ^. MS.csPostState . MS.csFreshVars
initialTerms <- liftIO $ traverse (scExtCns sc) initialECs
result <- liftIO
. O.runOverrideMatcher sym globals env initialTerms initialFree (ms ^. MS.csLoc)
. sequence_ $ mconcat
[ returnMatches
, pointsToMatches
, setupConditionMatchesPre
, setupConditionMatchesPost
, [LO.assertTermEqualities sc cc]
]
st <- case result of
Left err -> throwX86 $ show err
Right (_, st) -> pure st
liftIO . forM_ (view O.osAssumes st) $
C.addAssumption bak . C.GenericAssumption (st ^. O.osLocation) "precondition"
liftIO . forM_ (view LO.osAsserts st) $ \(W4.LabeledPred p r) ->
C.addAssertion bak $ C.LabeledPred p r
-- | Assert that a points-to postcondition holds.
assertPointsTo ::
X86Constraints =>
Map MS.AllocIndex Ptr {- ^ Associates each AllocIndex with the corresponding allocation -} ->
Map MS.AllocIndex LLVMAllocSpec {- ^ Associates each AllocIndex with its specification -} ->
Map MS.AllocIndex C.LLVM.Ident {- ^ Associates each AllocIndex with its name -} ->
LLVMPointsTo LLVMArch {- ^ llvm_points_to statement from the precondition -} ->
X86Sim (LLVMOverrideMatcher md ())
assertPointsTo env tyenv nameEnv pointsTo@(LLVMPointsTo loc cond tptr tptval) = do
opts <- use x86Options
sc <- use x86SharedContext
cc <- use x86CrucibleContext
ms <- use x86MethodSpec
ptr <- resolvePtrSetupValue env tyenv nameEnv tptr
pure $ do
err <- LO.matchPointsToValue opts sc cc ms MS.PostState loc cond ptr tptval
case err of
Just msg -> do
doc <- LO.ppPointsToAsLLVMVal opts cc sc ms pointsTo
O.failure loc (O.BadPointerLoad (Right doc) msg)
Nothing -> pure ()
assertPointsTo env tyenv nameEnv pointsTo@(LLVMPointsToBitfield loc tptr fieldName tptval) = do
opts <- use x86Options
sc <- use x86SharedContext
cc <- use x86CrucibleContext
ms <- use x86MethodSpec
(bfIndex, ptr) <- resolvePtrSetupValueBitfield env tyenv nameEnv tptr fieldName
pure $ do
err <- LO.matchPointsToBitfieldValue opts sc cc ms MS.PostState loc ptr bfIndex tptval
case err of
Just msg -> do
doc <- LO.ppPointsToAsLLVMVal opts cc sc ms pointsTo
O.failure loc (O.BadPointerLoad (Right doc) msg)
Nothing -> pure ()
-- | Gather and run the solver on goals from the simulator.
checkGoals ::
IsSymBackend Sym bak =>
bak ->
Options ->
SharedContext ->
ProofScript () ->
TopLevel (SolverStats, Set TheoremNonce)
checkGoals bak opts sc tactic = do
gs <- liftIO $ getGoals (SomeBackend bak)
liftIO . printOutLn opts Info $ mconcat
[ "Simulation finished, running solver on "
, show $ length gs
, " goals"
]
outs <- forM (zip [0..] gs) $ \(n, g) -> do
term <- liftIO $ gGoal sc g
let proofgoal = ProofGoal n "vc" (show $ gMessage g) term
res <- runProofScript tactic proofgoal (Just (gLoc g)) $ Text.unwords
["X86 verification condition", Text.pack (show n), Text.pack (show (gMessage g))]
case res of
ValidProof stats thm -> return (stats, thmNonce thm)
UnfinishedProof pst -> do
printOutLnTop Info $ unwords ["Subgoal failed:", show $ gMessage g]
printOutLnTop Info (show (psStats pst))
throwTopLevel $ "Proof failed: " ++ show (length (psGoals pst)) ++ " goals remaining."
InvalidProof stats vals _pst -> do
printOutLnTop Info $ unwords ["Subgoal failed:", show $ gMessage g]
printOutLnTop Info (show stats)
printOutLnTop OnlyCounterExamples "----------Counterexample----------"
ppOpts <- sawPPOpts . rwPPOpts <$> getTopLevelRW
case vals of
[] -> printOutLnTop OnlyCounterExamples "<<All settings of the symbolic variables constitute a counterexample>>"
_ -> let showEC ec = Text.unpack (toShortName (ecName ec)) in
let showAssignment (ec, val) =
mconcat [ " ", showEC ec, ": ", show $ ppFirstOrderValue ppOpts val ]
in mapM_ (printOutLnTop OnlyCounterExamples . showAssignment) vals
printOutLnTop OnlyCounterExamples "----------------------------------"
throwTopLevel "Proof failed."
liftIO $ printOutLn opts Info "All goals succeeded"
let stats = mconcat (map fst outs)
let thms = mconcat (map (Set.singleton . snd) outs)
return (stats, thms)
|
GaloisInc/saw-script
|
src/SAWScript/Crucible/LLVM/X86.hs
|
bsd-3-clause
| 45,464 | 0 | 36 | 10,129 | 12,220 | 6,151 | 6,069 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Kmip.ServerSpec where
import Test.Hspec
import Test.Hspec.Wai
import Kmip10Data
import qualified Kmip.Server
import qualified Web.Scotty as S
import Data.ByteString.Lazy (fromStrict)
spec :: Spec
spec = with (S.scottyApp Kmip.Server.server) $
describe "Server" $ do
it "should respond to hello" $
get "/" `shouldRespondWith` 200
-- run through all data
describe "Validate" $
let runTest x = it ("should validate " ++ fst x) $
post "/validate" (fromStrict $ snd x) `shouldRespondWith` "ok" { matchStatus = 200 }
in mapM_ runTest kmip_1_0__all
|
nymacro/hs-kmip
|
tests/Kmip/ServerSpec.hs
|
bsd-3-clause
| 697 | 0 | 18 | 197 | 176 | 95 | 81 | 17 | 1 |
{-
(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 ) 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 Coercion ( Role(..) )
import TcEvidence
import TcRnMonad
import TcHsSyn
import Type
import CoreSyn
import CoreUtils
import CoreFVs
import MkCore
import DynFlags
import CostCentre
import Id
import Module
import VarSet
import VarEnv
import ConLike
import DataCon
import TysWiredIn
import PrelNames
import BasicTypes
import Maybes
import SrcLoc
import Util
import Bag
import Outputable
import FastString
import IfaceEnv
import IdInfo
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.)
strictMatchOnly bind
= putSrcSpanDs loc (dsStrictBind bind body)
-- Ordinary case for bindings; none should be unlifted
ds_val_bind (_is_rec, binds) body
= do { prs <- dsLHsBinds binds
; 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
------------------
dsStrictBind :: HsBind Id -> CoreExpr -> DsM CoreExpr
dsStrictBind (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 -> dsStrictBind (unLoc lbind) body)
body1 lbinds
; ds_binds <- dsTcEvBinds_s ev_binds
; return (mkCoreLets ds_binds body2) }
dsStrictBind (FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn
, fun_tick = tick, fun_infix = inf }) body
-- Can't be a bang pattern (that looks like a PatBind)
-- so must be simply unboxed
= do { (args, rhs) <- matchWrapper (FunRhs (idName fun ) inf) matches
; MASSERT( null args ) -- Functions aren't lifted
; MASSERT( isIdHsWrapper co_fn )
; let rhs' = mkOptTickBox tick rhs
; return (bindNonRec fun rhs' body) }
dsStrictBind (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) }
dsStrictBind bind body = pprPanic "dsLet: unlifted" (ppr bind $$ ppr body)
----------------------
strictMatchOnly :: HsBind Id -> Bool
strictMatchOnly (AbsBinds { abs_binds = lbinds })
= anyBag (strictMatchOnly . unLoc) lbinds
strictMatchOnly (PatBind { pat_lhs = lpat, pat_rhs_ty = rhs_ty })
= isUnLiftedType rhs_ty
|| isStrictLPat lpat
|| any (isUnLiftedType . idType) (collectPatBinders lpat)
strictMatchOnly (FunBind { fun_id = L _ id })
= isUnLiftedType (idType id)
strictMatchOnly _ = 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 var) = return (varToCoreExpr var) -- See Note [Desugaring vars]
dsExpr (HsUnboundVar {}) = panic "dsExpr: HsUnboundVar" -- Typechecker eliminates them
dsExpr (HsIPVar _) = panic "dsExpr: HsIPVar"
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)
= App <$> dsExpr neg_expr <*> dsLExpr expr
dsExpr (HsLam a_Match)
= uncurry mkLams <$> matchWrapper LambdaExpr a_Match
dsExpr (HsLamCase arg matches)
= do { arg_var <- newSysLocalDs arg
; ([discrim_var], matching_code) <- matchWrapper CaseAlt matches
; return $ Lam arg_var $ bindNonRec discrim_var (Var arg_var) matching_code }
dsExpr (HsApp fun arg)
= mkCoreAppDs <$> dsLExpr fun <*> dsLExpr arg
{-
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 (OpApp e1 op _ e2)
= -- for the type of y, we need the type of op's 2nd argument
mkCoreAppsDs <$> dsLExpr op <*> mapM dsLExpr [e1, e2]
dsExpr (SectionL expr op) -- Desugar (e !) to ((!) e)
= mkCoreAppDs <$> dsLExpr op <*> dsLExpr expr
-- dsLExpr (SectionR op expr) -- \ x -> op x expr
dsExpr (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 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 $
mkCoreConApps (tupleDataCon boxity (length tup_args))
(map (Type . exprType) args ++ 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 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 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 stmts res_ty) = dsListComp stmts res_ty
dsExpr (HsDo PArrComp stmts _) = dsPArrComp (map unLoc stmts)
dsExpr (HsDo DoExpr stmts _) = dsDo stmts
dsExpr (HsDo GhciStmtCtxt stmts _) = dsDo stmts
dsExpr (HsDo MDoExpr stmts _) = dsDo stmts
dsExpr (HsDo MonadComp 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 -> do { core_fun <- dsExpr fun
; return (mkCoreApps core_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
(ptext (sLit "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
return . foldr1 (binary appP) $ map (unary singletonP) xs'
where
unary fn x = mkApps (Var fn) [Type ty, x]
binary fn x y = mkApps (Var fn) [Type ty, x, y]
dsExpr (ArithSeq expr witness seq)
= case witness of
Nothing -> dsArithSeq expr seq
Just fl -> do {
; fl' <- dsExpr fl
; newArithSeq <- dsArithSeq expr seq
; return (App 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 = varSetElems $ tyVarsOfType ty
speTy = mkForAllTys tvars $ mkTyConApp staticPtrTyCon [ty]
speId = mkExportedLocalId VanillaId 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) (map mkTyVarTy 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 (L _ data_con_id) con_expr rbinds) = 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 = dataConFieldLabels (idDataCon data_con_id)
-- The data_con_id is guaranteed to be the wrapper id of the constructor
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 record_expr fields
cons_to_upd in_inst_tys out_inst_tys)
| 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 (MG { mg_alts = 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
tycon = dataConTyCon (head cons_to_upd)
in_ty = mkTyConApp tycon in_inst_tys
out_ty = mkFamilyTyConApp tycon out_inst_tys
mk_alt upd_fld_env con
= do { let (univ_tvs, ex_tvs, eq_spec,
theta, arg_tys, _) = dataConFullSig con
subst = mkTopTvSubst (univ_tvs `zip` 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 theta)
; arg_ids <- newSysLocalsDs (substTys subst arg_tys)
; let val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg
(dataConFieldLabels con) arg_ids
mk_val_arg fl pat_arg_id
= nlHsVar (lookupNameEnv upd_fld_env (flSelector fl) `orElse` pat_arg_id)
inst_con = noLoc $ HsWrap wrap (HsVar (dataConWrapId con))
-- Reconstruct with the WrapId so that unpacking happens
wrap = mkWpEvVarApps theta_vars <.>
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]
wrap_co = mkTcTyConAppCo Nominal tycon
[ 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
wrap_subst = mkVarEnv [ (tv, mkTcSymCo (mkTcCoVarCo eq_var))
| ((tv,_),eq_var) <- eq_spec `zip` eqs_vars ]
pat = noLoc $ ConPatOut { pat_con = noLoc (RealDataCon 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 = idHsWrapper }
; let wrapped_rhs | null eq_spec = rhs
| otherwise = mkLHsWrap (mkWpCast (mkTcSubCo wrap_co)) rhs
; 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 (HsType {}) = panic "dsExpr:HsType"
dsExpr (HsDo {}) = panic "dsExpr:HsDo"
dsExpr (HsSingleRecFld{}) = panic "dsExpr: HsSingleRecFld"
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:
1. Find the tail of the list that can be allocated statically (say
[x_k, ..., x_n]) by later stages and ensure we desugar that
normally: this makes sure that we don't cause a code size increase
by having the cons in that expression fused (see later) and hence
being unable to statically allocate any more
2. For the prefix of the list which cannot be allocated statically,
say [x_1, ..., x_(k-1)], we turn it into an expression involving
build so that if we find any foldrs over it it will fuse away
entirely!
So in this example we will desugar to:
build (\c n -> x_1 `c` x_2 `c` .... `c` foldr c n [x_k, ..., x_n]
If fusion fails to occur then build will get inlined and (since we
defined a RULE for foldr (:) []) we will get back exactly the
normal desugaring for an explicit list.
This optimisation can be worth a lot: up to 25% of the total
allocation 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%
Of course, if rules aren't turned on then there is pretty much no
point doing this fancy stuff, and it may even be harmful.
=======> Note by SLPJ Dec 08.
I'm unconvinced that we should *ever* generate a build for an explicit
list. See the comments in GHC.Base about the foldr/cons rule, which
points out that (foldr k z [a,b,c]) may generate *much* less code than
(a `k` b `k` c `k` z).
Furthermore generating builds messes up the LHS of RULES.
Example: the foldr/single rule in GHC.Base
foldr k z [x] = ...
We do not want to generate a build invocation on the LHS of this RULE!
We fix this by disabling rules in rule LHSs, and testing that
flag here; see Note [Desugaring RULE left hand sides] in Desugar
To test this I've added a (static) flag -fsimple-list-literals, which
makes all list literals be generated via the simple route.
-}
dsExplicitList :: PostTc Id 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
; let (dynamic_prefix, static_suffix) = spanTail is_static xs'
; if gopt Opt_SimpleListLiterals dflags -- -fsimple-list-literals
|| 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
|| null dynamic_prefix -- Avoid build (\c n. foldr c n xs)!
then return $ mkListExpr elt_ty xs'
else mkBuildExpr elt_ty (mkSplitExplicitList dynamic_prefix static_suffix) }
where
is_static :: CoreExpr -> Bool
is_static e = all is_static_var (varSetElems (exprFreeVars e))
is_static_var :: Var -> Bool
is_static_var v
| isId v = isExternalName (idName v) -- Top-level things are given external names
| otherwise = False -- Type variables
mkSplitExplicitList prefix suffix (c, _) (n, n_ty)
= do { let suffix' = mkListExpr elt_ty suffix
; folded_suffix <- mkFoldrExpr elt_ty n_ty (Var c) (Var n) suffix'
; return (foldr (App . App (Var c)) folded_suffix prefix) }
dsExplicitList elt_ty (Just fln) xs
= do { fln' <- dsExpr fln
; list <- dsExplicitList elt_ty Nothing xs
; dflags <- getDynFlags
; return (App (App fln' (mkIntExprInt dflags (length xs))) list) }
spanTail :: (a -> Bool) -> [a] -> ([a], [a])
spanTail f xs = (reverse rejected, reverse satisfying)
where (satisfying, rejected) = span f $ reverse xs
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)
; then_expr2 <- dsExpr then_expr
; rest <- goL stmts
; return (mkApps then_expr2 [rhs2, rest]) }
go _ (LetStmt binds) stmts
= do { rest <- goL stmts
; dsLocalBinds binds rest }
go _ (BindStmt pat rhs bind_op fail_op) stmts
= do { body <- goL stmts
; rhs' <- dsLExpr rhs
; bind_op' <- dsExpr bind_op
; var <- selectSimpleMatchVarL pat
; let bind_ty = exprType bind_op' -- rhs -> (pat -> res1) -> res2
res1_ty = funResultTy (funArgTy (funResultTy bind_ty))
; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
res1_ty (cantFailMatchResult body)
; match_code <- handle_failure pat match fail_op
; return (mkApps 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
; ops' <- mapM dsExpr (map fst args)
; let body' = noLoc $ HsDo DoExpr stmts body_ty
; let fun = L noSrcSpan $ HsLam $
MG { mg_alts = [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) = mkApps op [l,r]
expr = foldl mk_ap_call fun' (zip ops' rhss')
; case mb_join of
Nothing -> return expr
Just join_op ->
do { join_op' <- dsExpr join_op
; return (App 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_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
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 = nlHsApp (noLoc mfix_op) mfix_arg
mfix_arg = noLoc $ HsLam (MG { mg_alts = [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 (rec_stmts ++ [ret_stmt]) body_ty
ret_app = nlHsApp (noLoc 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 { fail_op' <- dsExpr fail_op
; dflags <- getDynFlags
; fail_msg <- mkStringExpr (mk_fail_msg dflags pat)
; extractMatchResult match (App fail_op' fail_msg) }
| 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 (badMonadBind rhs elt_ty
(ptext (sLit "-fno-warn-unused-do-bind")))
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 (badMonadBind rhs elt_ty
(ptext (sLit "-fno-warn-wrong-do-bind")))
_ -> 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 -> SDoc
badMonadBind rhs elt_ty flag_doc
= vcat [ hang (ptext (sLit "A do-notation statement discarded a result of type"))
2 (quotes (ppr elt_ty))
, hang (ptext (sLit "Suppress this warning by saying"))
2 (quotes $ ptext (sLit "_ <-") <+> ppr rhs)
, ptext (sLit "or by using the flag") <+> flag_doc ]
{-
************************************************************************
* *
\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
|
siddhanathan/ghc
|
compiler/deSugar/DsExpr.hs
|
bsd-3-clause
| 39,165 | 43 | 25 | 11,931 | 8,302 | 4,222 | 4,080 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Script1 (
script
) where
import qualified Data.Text.Lazy as L
import qualified Data.Version as V
import Marvin.Handler
import Marvin.Prelude
import qualified Paths_marvin_integration as P
script :: (IsAdapter a, SupportsFiles a) => ScriptInit a
script = defineScript "test" $ do
hear (r [CaseInsensitive] "^ping$") $ do
msg <- getMessage
logInfoN $(isT "#{msg}")
send "Pong"
respond "hello" $
reply "Hello to you too"
exit $ do
user <- getUser
username <- getUsername user
send $(isL "Goodbye #{username}")
topic $ do
t <- getTopic
send $(isL "The new topic is #{t}")
respond "^where are you\\?$" $ do
loc <- requireConfigVal "location"
send $(isL "I am running on #{loc :: L.Text}")
topicIn "testing" $ do
t <- getTopic
messageChannel "#random" $(isL "The new topic in testing is \"#{t}\"")
enterIn "random" $ do
u <- getUser
username <- getUsername user
send $(isL "#{username} just entered random")
respond "^version\\??$" echoVersion
hear "^bot name\\??$" $ do
n <- getBotName
send $(isL "My name is #{n}, nice to meet you.")
fileShared $ do
f <- getRemoteFile
content <- readTextFile f
send $(isL "A file of name #{f^.name}")
maybe (return ()) send content
|
JustusAdam/marvin
|
test/integration/old-api/Script1.hs
|
bsd-3-clause
| 1,476 | 0 | 14 | 463 | 400 | 180 | 220 | 42 | 1 |
{-
Suggest removal of unnecessary extensions
i.e. They have {-# LANGUAGE RecursiveDo #-} but no mdo keywords
<TEST>
{-# LANGUAGE Arrows #-} \
f = id --
{-# LANGUAGE TotallyUnknown #-} \
f = id
{-# LANGUAGE Foo, ParallelListComp, ImplicitParams #-} \
f = [(a,c) | a <- b | c <- d] -- {-# LANGUAGE Foo, ParallelListComp #-}
{-# LANGUAGE EmptyDataDecls #-} \
data Foo
{-# LANGUAGE TemplateHaskell #-} \
$(deriveNewtypes typeInfo)
{-# LANGUAGE TemplateHaskell #-} \
main = foo ''Bar
{-# LANGUAGE PatternGuards #-} \
test = case x of _ | y <- z -> w
{-# LANGUAGE TemplateHaskell,EmptyDataDecls #-} \
$(fmap return $ dataD (return []) (mkName "Void") [] [] [])
{-# LANGUAGE RecursiveDo #-} \
main = mdo x <- y; return y
{-# LANGUAGE ImplicitParams, BangPatterns #-} \
sort :: (?cmp :: a -> a -> Bool) => [a] -> [a] \
sort !f = undefined
{-# LANGUAGE KindSignatures #-} \
data Set (cxt :: * -> *) a = Set [a]
{-# LANGUAGE RecordWildCards #-} \
record field = Record{..}
{-# LANGUAGE RecordWildCards #-} \
record = 1 --
{-# LANGUAGE UnboxedTuples #-} \
record = 1 --
{-# LANGUAGE TemplateHaskell #-} \
foo
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-} \
record = 1 --
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-} \
newtype Foo = Foo Int deriving Data -- {-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-} \
data Foo = Foo Int deriving Data -- {-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-} \
newtype Foo = Foo Int deriving Class -- {-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-} \
data Foo = Foo Int deriving Class --
{-# LANGUAGE DeriveFunctor #-} \
data Foo = Foo Int deriving Functor
{-# LANGUAGE DeriveFunctor #-} \
newtype Foo = Foo Int deriving Functor
{-# LANGUAGE GeneralizedNewtypeDeriving #-} \
newtype Foo = Foo Int deriving Functor
{-# LANGUAGE GeneralizedNewtypeDeriving #-} \
newtype Foo = Foo Int deriving Data --
{-# LANGUAGE DeriveFunctor, GeneralizedNewtypeDeriving, StandaloneDeriving #-} \
deriving instance Functor Bar
{-# LANGUAGE DeriveFunctor, GeneralizedNewtypeDeriving, StandaloneDeriving #-} \
deriving instance Show Bar -- {-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveGeneric, GeneralizedNewtypeDeriving #-} \
newtype Micro = Micro Int deriving Generic -- {-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE UnboxedTuples #-} \
f :: Int -> (# Int, Int #)
{-# LANGUAGE UnboxedTuples #-} \
f :: x -> (x, x); f x = (x, x) --
</TEST>
-}
module Hint.Extensions where
import Hint.Type
import Data.Maybe
import Data.List
import Util
extensionsHint :: ModuHint
extensionsHint _ x = [rawIdea Error "Unused LANGUAGE pragma" (toSrcSpan sl)
(prettyPrint o) (Just $ if null new then "" else prettyPrint $ LanguagePragma sl $ map (toNamed . prettyExtension) new)
(warnings old new)
| not $ used TemplateHaskell x -- if TH is on, can use all other extensions programmatically
, o@(LanguagePragma sl exts) <- modulePragmas x
, let old = map (parseExtension . prettyPrint) exts
, let new = minimalExtensions x old
, sort new /= sort old]
minimalExtensions :: Module_ -> [Extension] -> [Extension]
minimalExtensions x es = nub $ concatMap f es
where f e = [e | usedExt e x]
-- RecordWildCards implies DisambiguateRecordFields, but most people probably don't want it
warnings old new | wildcards `elem` old && wildcards `notElem` new = [Note "you may need to add DisambiguateRecordFields"]
where wildcards = EnableExtension RecordWildCards
warnings _ _ = []
-- | Classes that don't work with newtype deriving
noNewtypeDeriving :: [String]
noNewtypeDeriving = ["Read","Show","Data","Typeable","Generic","Generic1"]
usedExt :: Extension -> Module_ -> Bool
usedExt (UnknownExtension "DeriveGeneric") = hasDerive ["Generic","Generic1"]
usedExt (EnableExtension x) = used x
usedExt _ = const True
used :: KnownExtension -> Module_ -> Bool
used RecursiveDo = hasS isMDo
used ParallelListComp = hasS isParComp
used FunctionalDependencies = hasT (un :: FunDep S)
used ImplicitParams = hasT (un :: IPName S)
used EmptyDataDecls = hasS f
where f (DataDecl _ _ _ _ [] _) = True
f (GDataDecl _ _ _ _ _ [] _) = True
f _ = False
used KindSignatures = hasT (un :: Kind S)
used BangPatterns = hasS isPBangPat
used TemplateHaskell = hasT2 (un :: (Bracket S, Splice S)) & hasS f & hasS isSpliceDecl
where f VarQuote{} = True
f TypQuote{} = True
f _ = False
used ForeignFunctionInterface = hasT (un :: CallConv S)
used PatternGuards = hasS f1 & hasS f2
where f1 (GuardedRhs _ xs _) = g xs
f2 (GuardedAlt _ xs _) = g xs
g [] = False
g [Qualifier{}] = False
g _ = True
used StandaloneDeriving = hasS isDerivDecl
used PatternSignatures = hasS isPatTypeSig
used RecordWildCards = hasS isPFieldWildcard & hasS isFieldWildcard
used RecordPuns = hasS isPFieldPun & hasS isFieldPun
used UnboxedTuples = has (not . isBoxed)
used PackageImports = hasS (isJust . importPkg)
used QuasiQuotes = hasS isQuasiQuote
used ViewPatterns = hasS isPViewPat
used DeriveDataTypeable = hasDerive ["Data","Typeable"]
used DeriveFunctor = hasDerive ["Functor"]
used DeriveFoldable = hasDerive ["Foldable"]
used DeriveTraversable = hasDerive ["Traversable"]
used GeneralizedNewtypeDeriving = any (`notElem` noNewtypeDeriving) . fst . derives
used Arrows = hasS f
where f Proc{} = True
f LeftArrApp{} = True
f RightArrApp{} = True
f LeftArrHighApp{} = True
f RightArrHighApp{} = True
f _ = False
used TransformListComp = hasS f
where f QualStmt{} = False
f _ = True
-- for forwards compatibility, if things ever get added to the extension enumeration
used x = usedExt $ UnknownExtension $ show x
hasDerive :: [String] -> Module_ -> Bool
hasDerive want m = any (`elem` want) $ new ++ dat
where (new,dat) = derives m
-- | What is derived on newtype, and on data type
-- 'deriving' declarations may be on either, so we approximate as both newtype and data
derives :: Module_ -> ([String],[String])
derives = concatUnzip . map f . childrenBi
where
f :: Decl_ -> ([String], [String])
f (DataDecl _ dn _ _ _ ds) = g dn ds
f (GDataDecl _ dn _ _ _ _ ds) = g dn ds
f (DataInsDecl _ dn _ _ ds) = g dn ds
f (GDataInsDecl _ dn _ _ _ ds) = g dn ds
f (DerivDecl _ _ hd) = (xs, xs) -- don't know whether this was on newtype or not
where xs = [h hd]
f _ = ([], [])
g dn ds = if isNewType dn then (xs,[]) else ([],xs)
where xs = maybe [] (map h . fromDeriving) ds
h (IHead _ a _) = prettyPrint $ unqual a
h (IHInfix _ _ a _) = prettyPrint $ unqual a
h (IHParen _ a) = h a
un = undefined
(&) f g x = f x || g x
hasT t x = notNull (universeBi x `asTypeOf` [t])
hasT2 ~(t1,t2) = hasT t1 & hasT t2
hasS :: Biplate x (f S) => (f S -> Bool) -> x -> Bool
hasS test = any test . universeBi
has f = any f . universeBi
|
bergmark/hlint
|
src/Hint/Extensions.hs
|
bsd-3-clause
| 7,115 | 0 | 13 | 1,520 | 1,706 | 868 | 838 | 97 | 13 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Numeral.AF.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Numeral.AF.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "AF Tests"
[ makeCorpusTest [Seal Numeral] corpus
]
|
facebookincubator/duckling
|
tests/Duckling/Numeral/AF/Tests.hs
|
bsd-3-clause
| 505 | 0 | 9 | 79 | 79 | 50 | 29 | 11 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Configure
-- Copyright : Isaac Jones 2003-2005
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This deals with the /configure/ phase. It provides the 'configure' action
-- which is given the package description and configure flags. It then tries
-- to: configure the compiler; resolves any conditionals in the package
-- description; resolve the package dependencies; check if all the extensions
-- used by this package are supported by the compiler; check that all the build
-- tools are available (including version checks if appropriate); checks for
-- any required @pkg-config@ packages (updating the 'BuildInfo' with the
-- results)
--
-- Then based on all this it saves the info in the 'LocalBuildInfo' and writes
-- it out to the @dist\/setup-config@ file. It also displays various details to
-- the user, the amount of information displayed depending on the verbosity
-- level.
module Distribution.Simple.Configure (configure,
writePersistBuildConfig,
getConfigStateFile,
getPersistBuildConfig,
checkPersistBuildConfigOutdated,
tryGetPersistBuildConfig,
maybeGetPersistBuildConfig,
localBuildInfoFile,
getInstalledPackages, getPackageDBContents,
configCompiler, configCompilerAux,
configCompilerEx, configCompilerAuxEx,
ccLdOptionsBuildInfo,
checkForeignDeps,
interpretPackageDbFlags,
ConfigStateFileError(..),
tryGetConfigStateFile,
platformDefines,
)
where
import Distribution.Compiler
( CompilerId(..) )
import Distribution.Utils.NubList
import Distribution.Simple.Compiler
( CompilerFlavor(..), Compiler(..), compilerFlavor, compilerVersion
, compilerInfo
, showCompilerId, unsupportedLanguages, unsupportedExtensions
, PackageDB(..), PackageDBStack, reexportedModulesSupported
, packageKeySupported, renamingPackageFlagsSupported )
import Distribution.Simple.PreProcess ( platformDefines )
import Distribution.Package
( PackageName(PackageName), PackageIdentifier(..), PackageId
, packageName, packageVersion, Package(..)
, Dependency(Dependency), simplifyDependency
, InstalledPackageId(..), thisPackageVersion
, mkPackageKey, PackageKey(..) )
import qualified Distribution.InstalledPackageInfo as Installed
import Distribution.InstalledPackageInfo (InstalledPackageInfo, emptyInstalledPackageInfo)
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import Distribution.PackageDescription as PD
( PackageDescription(..), specVersion, GenericPackageDescription(..)
, Library(..), hasLibs, Executable(..), BuildInfo(..), allExtensions
, HookedBuildInfo, updatePackageDescription, allBuildInfo
, Flag(flagName), FlagName(..), TestSuite(..), Benchmark(..)
, ModuleReexport(..) , defaultRenaming )
import Distribution.ModuleName
( ModuleName )
import Distribution.PackageDescription.Configuration
( finalizePackageDescription, mapTreeData )
import Distribution.PackageDescription.Check
( PackageCheck(..), checkPackage, checkPackageFiles )
import Distribution.Simple.Program
( Program(..), ProgramLocation(..), ConfiguredProgram(..)
, ProgramConfiguration, defaultProgramConfiguration
, ProgramSearchPathEntry(..), getProgramSearchPath, setProgramSearchPath
, configureAllKnownPrograms, knownPrograms, lookupKnownProgram
, userSpecifyArgss, userSpecifyPaths
, lookupProgram, requireProgram, requireProgramVersion
, pkgConfigProgram, gccProgram, rawSystemProgramStdoutConf )
import Distribution.Simple.Setup
( ConfigFlags(..), buildCompilerFlavor,
CopyDest(..), Flag(..), fromFlag, fromFlagOrDefault, flagToMaybe )
import Distribution.Simple.InstallDirs
( InstallDirs(..), defaultInstallDirs, combineInstallDirs )
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), Component(..), ComponentLocalBuildInfo(..)
, LibraryName(..)
, absoluteInstallDirs, prefixRelativeInstallDirs, inplacePackageId
, ComponentName(..), showComponentName, pkgEnabledComponents
, componentBuildInfo, componentName, checkComponentsCyclic )
import Distribution.Simple.BuildPaths
( autogenModulesDir )
import Distribution.Simple.Utils
( die, warn, info, setupMessage
, createDirectoryIfMissingVerbose, moreRecentFile
, intercalate, cabalVersion
, writeFileAtomic
, withTempFile )
import Distribution.System
( OS(..), buildOS, Platform (..), buildPlatform )
import Distribution.Version
( Version(..), anyVersion, orLaterVersion, withinRange, isAnyVersion )
import Distribution.Verbosity
( Verbosity, lessVerbose )
import qualified Distribution.Simple.GHC as GHC
import qualified Distribution.Simple.GHCJS as GHCJS
import qualified Distribution.Simple.JHC as JHC
import qualified Distribution.Simple.LHC as LHC
import qualified Distribution.Simple.UHC as UHC
import qualified Distribution.Simple.HaskellSuite as HaskellSuite
-- Prefer the more generic Data.Traversable.mapM to Prelude.mapM
import Prelude hiding ( mapM )
import Control.Exception
( ErrorCall(..), Exception, evaluate, throw, throwIO, try )
import Control.Monad
( liftM, when, unless, foldM, filterM )
import Distribution.Compat.Binary ( decodeOrFailIO, encode )
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy.Char8 as BLC8
import Data.List
( (\\), nub, partition, isPrefixOf, inits, stripPrefix )
import Data.Maybe
( isNothing, catMaybes, fromMaybe, isJust )
import Data.Either
( partitionEithers )
import qualified Data.Set as Set
import Data.Monoid
( Monoid(..) )
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Traversable
( mapM )
import Data.Typeable
import System.Directory
( doesFileExist, createDirectoryIfMissing, getTemporaryDirectory )
import System.FilePath
( (</>), isAbsolute )
import qualified System.Info
( compilerName, compilerVersion )
import System.IO
( hPutStrLn, hClose )
import Distribution.Text
( Text(disp), display, simpleParse )
import Text.PrettyPrint
( render, (<>), ($+$), char, text, comma
, quotes, punctuate, nest, sep, hsep )
import Distribution.Compat.Exception ( catchExit, catchIO )
-- | The errors that can be thrown when reading the @setup-config@ file.
data ConfigStateFileError
= ConfigStateFileNoHeader -- ^ No header found.
| ConfigStateFileBadHeader -- ^ Incorrect header.
| ConfigStateFileNoParse -- ^ Cannot parse file contents.
| ConfigStateFileMissing -- ^ No file!
| ConfigStateFileBadVersion PackageIdentifier PackageIdentifier (Either ConfigStateFileError LocalBuildInfo) -- ^ Mismatched version.
deriving (Typeable)
instance Show ConfigStateFileError where
show ConfigStateFileNoHeader =
"Saved package config file header is missing. "
++ "Try re-running the 'configure' command."
show ConfigStateFileBadHeader =
"Saved package config file header is corrupt. "
++ "Try re-running the 'configure' command."
show ConfigStateFileNoParse =
"Saved package config file body is corrupt. "
++ "Try re-running the 'configure' command."
show ConfigStateFileMissing = "Run the 'configure' command first."
show (ConfigStateFileBadVersion oldCabal oldCompiler _) =
"You need to re-run the 'configure' command. "
++ "The version of Cabal being used has changed (was "
++ display oldCabal ++ ", now "
++ display currentCabalId ++ ")."
++ badCompiler
where
badCompiler
| oldCompiler == currentCompilerId = ""
| otherwise =
" Additionally the compiler is different (was "
++ display oldCompiler ++ ", now "
++ display currentCompilerId
++ ") which is probably the cause of the problem."
instance Exception ConfigStateFileError
-- | Read the 'localBuildInfoFile'. Throw an exception if the file is
-- missing, if the file cannot be read, or if the file was created by an older
-- version of Cabal.
getConfigStateFile :: FilePath -- ^ The file path of the @setup-config@ file.
-> IO LocalBuildInfo
getConfigStateFile filename = do
exists <- doesFileExist filename
unless exists $ throwIO ConfigStateFileMissing
-- Read the config file into a strict ByteString to avoid problems with
-- lazy I/O, then convert to lazy because the binary package needs that.
contents <- BS.readFile filename
let (header, body) = BLC8.span (/='\n') (BLC8.fromChunks [contents])
headerParseResult <- try $ evaluate $ parseHeader header
let (cabalId, compId) =
case headerParseResult of
Left (ErrorCall _) -> throw ConfigStateFileBadHeader
Right x -> x
let getStoredValue = do
result <- decodeOrFailIO (BLC8.tail body)
case result of
Left _ -> throw ConfigStateFileNoParse
Right x -> return x
deferErrorIfBadVersion act
| cabalId /= currentCabalId = do
eResult <- try act
throw $ ConfigStateFileBadVersion cabalId compId eResult
| otherwise = act
deferErrorIfBadVersion getStoredValue
-- | Read the 'localBuildInfoFile', returning either an error or the local build info.
tryGetConfigStateFile :: FilePath -- ^ The file path of the @setup-config@ file.
-> IO (Either ConfigStateFileError LocalBuildInfo)
tryGetConfigStateFile = try . getConfigStateFile
-- | Try to read the 'localBuildInfoFile'.
tryGetPersistBuildConfig :: FilePath -- ^ The @dist@ directory path.
-> IO (Either ConfigStateFileError LocalBuildInfo)
tryGetPersistBuildConfig = try . getPersistBuildConfig
-- | Read the 'localBuildInfoFile'. Throw an exception if the file is
-- missing, if the file cannot be read, or if the file was created by an older
-- version of Cabal.
getPersistBuildConfig :: FilePath -- ^ The @dist@ directory path.
-> IO LocalBuildInfo
getPersistBuildConfig = getConfigStateFile . localBuildInfoFile
-- | Try to read the 'localBuildInfoFile'.
maybeGetPersistBuildConfig :: FilePath -- ^ The @dist@ directory path.
-> IO (Maybe LocalBuildInfo)
maybeGetPersistBuildConfig =
liftM (either (const Nothing) Just) . tryGetPersistBuildConfig
-- | After running configure, output the 'LocalBuildInfo' to the
-- 'localBuildInfoFile'.
writePersistBuildConfig :: FilePath -- ^ The @dist@ directory path.
-> LocalBuildInfo -- ^ The 'LocalBuildInfo' to write.
-> IO ()
writePersistBuildConfig distPref lbi = do
createDirectoryIfMissing False distPref
writeFileAtomic (localBuildInfoFile distPref) $
BLC8.unlines [showHeader pkgId, encode lbi]
where
pkgId = packageId $ localPkgDescr lbi
-- | Identifier of the current Cabal package.
currentCabalId :: PackageIdentifier
currentCabalId = PackageIdentifier (PackageName "Cabal") cabalVersion
-- | Identifier of the current compiler package.
currentCompilerId :: PackageIdentifier
currentCompilerId = PackageIdentifier (PackageName System.Info.compilerName)
System.Info.compilerVersion
-- | Parse the @setup-config@ file header, returning the package identifiers
-- for Cabal and the compiler.
parseHeader :: ByteString -- ^ The file contents.
-> (PackageIdentifier, PackageIdentifier)
parseHeader header = case BLC8.words header of
["Saved", "package", "config", "for", pkgId, "written", "by", cabalId, "using", compId] ->
fromMaybe (throw ConfigStateFileBadHeader) $ do
_ <- simpleParse (BLC8.unpack pkgId) :: Maybe PackageIdentifier
cabalId' <- simpleParse (BLC8.unpack cabalId)
compId' <- simpleParse (BLC8.unpack compId)
return (cabalId', compId')
_ -> throw ConfigStateFileNoHeader
-- | Generate the @setup-config@ file header.
showHeader :: PackageIdentifier -- ^ The processed package.
-> ByteString
showHeader pkgId = BLC8.unwords
[ "Saved", "package", "config", "for"
, BLC8.pack $ display pkgId
, "written", "by"
, BLC8.pack $ display currentCabalId
, "using"
, BLC8.pack $ display currentCompilerId
]
-- | Check that localBuildInfoFile is up-to-date with respect to the
-- .cabal file.
checkPersistBuildConfigOutdated :: FilePath -> FilePath -> IO Bool
checkPersistBuildConfigOutdated distPref pkg_descr_file = do
pkg_descr_file `moreRecentFile` (localBuildInfoFile distPref)
-- | Get the path of @dist\/setup-config@.
localBuildInfoFile :: FilePath -- ^ The @dist@ directory path.
-> FilePath
localBuildInfoFile distPref = distPref </> "setup-config"
-- -----------------------------------------------------------------------------
-- * Configuration
-- -----------------------------------------------------------------------------
-- |Perform the \"@.\/setup configure@\" action.
-- Returns the @.setup-config@ file.
configure :: (GenericPackageDescription, HookedBuildInfo)
-> ConfigFlags -> IO LocalBuildInfo
configure (pkg_descr0, pbi) cfg
= do let distPref = fromFlag (configDistPref cfg)
buildDir' = distPref </> "build"
verbosity = fromFlag (configVerbosity cfg)
setupMessage verbosity "Configuring" (packageId pkg_descr0)
unless (configProfExe cfg == NoFlag) $ do
let enable | fromFlag (configProfExe cfg) = "enable"
| otherwise = "disable"
warn verbosity
("The flag --" ++ enable ++ "-executable-profiling is deprecated. "
++ "Please use --" ++ enable ++ "-profiling instead.")
unless (configLibCoverage cfg == NoFlag) $ do
let enable | fromFlag (configLibCoverage cfg) = "enable"
| otherwise = "disable"
warn verbosity
("The flag --" ++ enable ++ "-library-coverage is deprecated. "
++ "Please use --" ++ enable ++ "-coverage instead.")
createDirectoryIfMissingVerbose (lessVerbose verbosity) True distPref
let programsConfig = mkProgramsConfig cfg (configPrograms cfg)
userInstall = fromFlag (configUserInstall cfg)
packageDbs = interpretPackageDbFlags userInstall
(configPackageDBs cfg)
-- detect compiler
(comp, compPlatform, programsConfig') <- configCompilerEx
(flagToMaybe $ configHcFlavor cfg)
(flagToMaybe $ configHcPath cfg) (flagToMaybe $ configHcPkg cfg)
programsConfig (lessVerbose verbosity)
let version = compilerVersion comp
flavor = compilerFlavor comp
-- Create a PackageIndex that makes *any libraries that might be*
-- defined internally to this package look like installed packages, in
-- case an executable should refer to any of them as dependencies.
--
-- It must be *any libraries that might be* defined rather than the
-- actual definitions, because these depend on conditionals in the .cabal
-- file, and we haven't resolved them yet. finalizePackageDescription
-- does the resolution of conditionals, and it takes internalPackageSet
-- as part of its input.
--
-- Currently a package can define no more than one library (which has
-- the same name as the package) but we could extend this later.
-- If we later allowed private internal libraries, then here we would
-- need to pre-scan the conditional data to make a list of all private
-- libraries that could possibly be defined by the .cabal file.
let pid = packageId pkg_descr0
internalPackage = emptyInstalledPackageInfo {
--TODO: should use a per-compiler method to map the source
-- package ID into an installed package id we can use
-- for the internal package set. The open-codes use of
-- InstalledPackageId . display here is a hack.
Installed.installedPackageId =
InstalledPackageId $ display $ pid,
Installed.sourcePackageId = pid
}
internalPackageSet = PackageIndex.fromList [internalPackage]
installedPackageSet <- getInstalledPackages (lessVerbose verbosity) comp
packageDbs programsConfig'
(allConstraints, requiredDepsMap) <- either die return $
combinedConstraints (configConstraints cfg)
(configDependencies cfg)
installedPackageSet
let exactConf = fromFlagOrDefault False (configExactConfiguration cfg)
-- Constraint test function for the solver
dependencySatisfiable d@(Dependency depName verRange)
| exactConf =
-- When we're given '--exact-configuration', we assume that all
-- dependencies and flags are exactly specified on the command
-- line. Thus we only consult the 'requiredDepsMap'. Note that
-- we're not doing the version range check, so if there's some
-- dependency that wasn't specified on the command line,
-- 'finalizePackageDescription' will fail.
--
-- TODO: mention '--exact-configuration' in the error message
-- when this fails?
(depName `Map.member` requiredDepsMap) || isInternalDep
| otherwise =
-- Normal operation: just look up dependency in the package
-- index.
not . null . PackageIndex.lookupDependency pkgs' $ d
where
pkgs' = PackageIndex.insert internalPackage installedPackageSet
isInternalDep = pkgName pid == depName
&& pkgVersion pid `withinRange` verRange
enableTest t = t { testEnabled = fromFlag (configTests cfg) }
flaggedTests = map (\(n, t) -> (n, mapTreeData enableTest t))
(condTestSuites pkg_descr0)
enableBenchmark bm = bm { benchmarkEnabled =
fromFlag (configBenchmarks cfg) }
flaggedBenchmarks = map (\(n, bm) ->
(n, mapTreeData enableBenchmark bm))
(condBenchmarks pkg_descr0)
pkg_descr0'' = pkg_descr0 { condTestSuites = flaggedTests
, condBenchmarks = flaggedBenchmarks }
(pkg_descr0', flags) <-
case finalizePackageDescription
(configConfigurationsFlags cfg)
dependencySatisfiable
compPlatform
(compilerInfo comp)
allConstraints
pkg_descr0''
of Right r -> return r
Left missing ->
die $ "At least the following dependencies are missing:\n"
++ (render . nest 4 . sep . punctuate comma
. map (disp . simplifyDependency)
$ missing)
-- Sanity check: if '--exact-configuration' was given, ensure that the
-- complete flag assignment was specified on the command line.
when exactConf $ do
let cmdlineFlags = map fst (configConfigurationsFlags cfg)
allFlags = map flagName . genPackageFlags $ pkg_descr0
diffFlags = allFlags \\ cmdlineFlags
when (not . null $ diffFlags) $
die $ "'--exact-conf' was given, "
++ "but the following flags were not specified: "
++ intercalate ", " (map show diffFlags)
-- add extra include/lib dirs as specified in cfg
-- we do it here so that those get checked too
let pkg_descr = addExtraIncludeLibDirs pkg_descr0'
unless (renamingPackageFlagsSupported comp ||
and [ rn == defaultRenaming
| bi <- allBuildInfo pkg_descr
, rn <- Map.elems (targetBuildRenaming bi)]) $
die $ "Your compiler does not support thinning and renaming on "
++ "package flags. To use this feature you probably must use "
++ "GHC 7.9 or later."
when (not (null flags)) $
info verbosity $ "Flags chosen: "
++ intercalate ", " [ name ++ "=" ++ display value
| (FlagName name, value) <- flags ]
when (maybe False (not.null.PD.reexportedModules) (PD.library pkg_descr)
&& not (reexportedModulesSupported comp)) $ do
die $ "Your compiler does not support module re-exports. To use "
++ "this feature you probably must use GHC 7.9 or later."
checkPackageProblems verbosity pkg_descr0
(updatePackageDescription pbi pkg_descr)
-- Handle hole instantiation
(holeDeps, hole_insts) <- configureInstantiateWith pkg_descr cfg installedPackageSet
let selectDependencies :: [Dependency] ->
([FailedDependency], [ResolvedDependency])
selectDependencies =
(\xs -> ([ x | Left x <- xs ], [ x | Right x <- xs ]))
. map (selectDependency internalPackageSet installedPackageSet
requiredDepsMap)
(failedDeps, allPkgDeps) =
selectDependencies (buildDepends pkg_descr)
internalPkgDeps = [ pkgid
| InternalDependency _ pkgid <- allPkgDeps ]
externalPkgDeps = [ pkg
| ExternalDependency _ pkg <- allPkgDeps ]
when (not (null internalPkgDeps)
&& not (newPackageDepsBehaviour pkg_descr)) $
die $ "The field 'build-depends: "
++ intercalate ", " (map (display . packageName) internalPkgDeps)
++ "' refers to a library which is defined within the same "
++ "package. To use this feature the package must specify at "
++ "least 'cabal-version: >= 1.8'."
reportFailedDependencies failedDeps
reportSelectedDependencies verbosity allPkgDeps
let installDeps = Map.elems
. Map.fromList
. map (\v -> (Installed.installedPackageId v, v))
$ externalPkgDeps ++ holeDeps
packageDependsIndex <-
case PackageIndex.dependencyClosure installedPackageSet
(map Installed.installedPackageId installDeps) of
Left packageDependsIndex -> return packageDependsIndex
Right broken ->
die $ "The following installed packages are broken because other"
++ " packages they depend on are missing. These broken "
++ "packages must be rebuilt before they can be used.\n"
++ unlines [ "package "
++ display (packageId pkg)
++ " is broken due to missing package "
++ intercalate ", " (map display deps)
| (pkg, deps) <- broken ]
let pseudoTopPkg = emptyInstalledPackageInfo {
Installed.installedPackageId =
InstalledPackageId (display (packageId pkg_descr)),
Installed.sourcePackageId = packageId pkg_descr,
Installed.depends =
map Installed.installedPackageId installDeps
}
case PackageIndex.dependencyInconsistencies
. PackageIndex.insert pseudoTopPkg
$ packageDependsIndex of
[] -> return ()
inconsistencies ->
warn verbosity $
"This package indirectly depends on multiple versions of the same "
++ "package. This is highly likely to cause a compile failure.\n"
++ unlines [ "package " ++ display pkg ++ " requires "
++ display (PackageIdentifier name ver)
| (name, uses) <- inconsistencies
, (pkg, ver) <- uses ]
-- Calculate the package key. We're going to store it in LocalBuildInfo
-- canonically, but ComponentsLocalBuildInfo also needs to know about it
-- XXX Do we need the internal deps?
-- NB: does *not* include holeDeps!
let pkg_key = mkPackageKey (packageKeySupported comp)
(package pkg_descr)
(map Installed.packageKey externalPkgDeps)
(map (\(k,(p,m)) -> (k,(Installed.packageKey p,m))) hole_insts)
-- internal component graph
buildComponents <-
case mkComponentsGraph pkg_descr internalPkgDeps of
Left componentCycle -> reportComponentCycle componentCycle
Right components ->
case mkComponentsLocalBuildInfo packageDependsIndex pkg_descr
internalPkgDeps externalPkgDeps holeDeps
(Map.fromList hole_insts)
pkg_key components of
Left problems -> reportModuleReexportProblems problems
Right components' -> return components'
-- installation directories
defaultDirs <- defaultInstallDirs flavor userInstall (hasLibs pkg_descr)
let installDirs = combineInstallDirs fromFlagOrDefault
defaultDirs (configInstallDirs cfg)
-- check languages and extensions
let langlist = nub $ catMaybes $ map defaultLanguage
(allBuildInfo pkg_descr)
let langs = unsupportedLanguages comp langlist
when (not (null langs)) $
die $ "The package " ++ display (packageId pkg_descr0)
++ " requires the following languages which are not "
++ "supported by " ++ display (compilerId comp) ++ ": "
++ intercalate ", " (map display langs)
let extlist = nub $ concatMap allExtensions (allBuildInfo pkg_descr)
let exts = unsupportedExtensions comp extlist
when (not (null exts)) $
die $ "The package " ++ display (packageId pkg_descr0)
++ " requires the following language extensions which are not "
++ "supported by " ++ display (compilerId comp) ++ ": "
++ intercalate ", " (map display exts)
-- configured known/required programs & external build tools
-- exclude build-tool deps on "internal" exes in the same package
let requiredBuildTools =
[ buildTool
| let exeNames = map exeName (executables pkg_descr)
, bi <- allBuildInfo pkg_descr
, buildTool@(Dependency (PackageName toolName) reqVer)
<- buildTools bi
, let isInternal =
toolName `elem` exeNames
-- we assume all internal build-tools are
-- versioned with the package:
&& packageVersion pkg_descr `withinRange` reqVer
, not isInternal ]
programsConfig'' <-
configureAllKnownPrograms (lessVerbose verbosity) programsConfig'
>>= configureRequiredPrograms verbosity requiredBuildTools
(pkg_descr', programsConfig''') <-
configurePkgconfigPackages verbosity pkg_descr programsConfig''
split_objs <-
if not (fromFlag $ configSplitObjs cfg)
then return False
else case flavor of
GHC | version >= Version [6,5] [] -> return True
GHCJS -> return True
_ -> do warn verbosity
("this compiler does not support " ++
"--enable-split-objs; ignoring")
return False
let ghciLibByDefault =
case compilerId comp of
CompilerId GHC _ ->
-- If ghc is non-dynamic, then ghci needs object files,
-- so we build one by default.
--
-- Technically, archive files should be sufficient for ghci,
-- but because of GHC bug #8942, it has never been safe to
-- rely on them. By the time that bug was fixed, ghci had
-- been changed to read shared libraries instead of archive
-- files (see next code block).
not (GHC.isDynamic comp)
CompilerId GHCJS _ ->
not (GHCJS.isDynamic comp)
_ -> False
let sharedLibsByDefault
| fromFlag (configDynExe cfg) =
-- build a shared library if dynamically-linked
-- executables are requested
True
| otherwise = case compilerId comp of
CompilerId GHC _ ->
-- if ghc is dynamic, then ghci needs a shared
-- library, so we build one by default.
GHC.isDynamic comp
CompilerId GHCJS _ ->
GHCJS.isDynamic comp
_ -> False
withSharedLib_ =
-- build shared libraries if required by GHC or by the
-- executable linking mode, but allow the user to force
-- building only static library archives with
-- --disable-shared.
fromFlagOrDefault sharedLibsByDefault $ configSharedLib cfg
withDynExe_ = fromFlag $ configDynExe cfg
when (withDynExe_ && not withSharedLib_) $ warn verbosity $
"Executables will use dynamic linking, but a shared library "
++ "is not being built. Linking will fail if any executables "
++ "depend on the library."
let withProf_ = fromFlagOrDefault False (configProf cfg)
withProfExe_ = fromFlagOrDefault withProf_ $ configProfExe cfg
withProfLib_ = fromFlagOrDefault withProfExe_ $ configProfLib cfg
when (withProfExe_ && not withProfLib_) $ warn verbosity $
"Executables will be built with profiling, but library "
++ "profiling is disabled. Linking will fail if any executables "
++ "depend on the library."
let configCoverage_ =
mappend (configCoverage cfg) (configLibCoverage cfg)
cfg' = cfg { configCoverage = configCoverage_ }
reloc <-
if not (fromFlag $ configRelocatable cfg)
then return False
else return True
-- detect compiler for build process artifacts
(buildCompiler', buildCompPlatform', buildCompProgsCfg') <-
configCompilerEx
(Just buildCompilerFlavor)
(flagToMaybe $ configBuildHc cfg)
(flagToMaybe $ configBuildHcPkg cfg)
programsConfig
verbosity
let lbi = LocalBuildInfo {
configFlags = cfg',
extraConfigArgs = [], -- Currently configure does not
-- take extra args, but if it
-- did they would go here.
installDirTemplates = installDirs,
compiler = comp,
hostPlatform = compPlatform,
buildCompiler = buildCompiler',
buildCompPlatform = buildCompPlatform',
buildCompProgsCfg = buildCompProgsCfg',
buildDir = buildDir',
componentsConfigs = buildComponents,
installedPkgs = packageDependsIndex,
pkgDescrFile = Nothing,
localPkgDescr = pkg_descr',
pkgKey = pkg_key,
instantiatedWith = hole_insts,
withPrograms = programsConfig''',
withVanillaLib = fromFlag $ configVanillaLib cfg,
withProfLib = withProfLib_,
withSharedLib = withSharedLib_,
withDynExe = withDynExe_,
withProfExe = withProfExe_,
withOptimization = fromFlag $ configOptimization cfg,
withDebugInfo = fromFlag $ configDebugInfo cfg,
withGHCiLib = fromFlagOrDefault ghciLibByDefault $
configGHCiLib cfg,
splitObjs = split_objs,
stripExes = fromFlag $ configStripExes cfg,
stripLibs = fromFlag $ configStripLibs cfg,
withPackageDB = packageDbs,
progPrefix = fromFlag $ configProgPrefix cfg,
progSuffix = fromFlag $ configProgSuffix cfg,
relocatable = reloc
}
when reloc (checkRelocatable verbosity pkg_descr lbi)
let dirs = absoluteInstallDirs pkg_descr lbi NoCopyDest
relative = prefixRelativeInstallDirs (packageId pkg_descr) lbi
unless (isAbsolute (prefix dirs)) $ die $
"expected an absolute directory name for --prefix: " ++ prefix dirs
info verbosity $ "Using " ++ display currentCabalId
++ " compiled by " ++ display currentCompilerId
info verbosity $ "Using compiler: " ++ showCompilerId comp
info verbosity $ "Using install prefix: " ++ prefix dirs
let dirinfo name dir isPrefixRelative =
info verbosity $ name ++ " installed in: " ++ dir ++ relNote
where relNote = case buildOS of
Windows | not (hasLibs pkg_descr)
&& isNothing isPrefixRelative
-> " (fixed location)"
_ -> ""
dirinfo "Binaries" (bindir dirs) (bindir relative)
dirinfo "Libraries" (libdir dirs) (libdir relative)
dirinfo "Private binaries" (libexecdir dirs) (libexecdir relative)
dirinfo "Data files" (datadir dirs) (datadir relative)
dirinfo "Documentation" (docdir dirs) (docdir relative)
dirinfo "Configuration files" (sysconfdir dirs) (sysconfdir relative)
sequence_ [ reportProgram verbosity prog configuredProg
| (prog, configuredProg) <- knownPrograms programsConfig''' ]
return lbi
where
addExtraIncludeLibDirs pkg_descr =
let extraBi = mempty { extraLibDirs = configExtraLibDirs cfg
, PD.includeDirs = configExtraIncludeDirs cfg}
modifyLib l = l{ libBuildInfo = libBuildInfo l
`mappend` extraBi }
modifyExecutable e = e{ buildInfo = buildInfo e
`mappend` extraBi}
in pkg_descr{ library = modifyLib `fmap` library pkg_descr
, executables = modifyExecutable `map`
executables pkg_descr}
mkProgramsConfig :: ConfigFlags -> ProgramConfiguration -> ProgramConfiguration
mkProgramsConfig cfg initialProgramsConfig = programsConfig
where
programsConfig = userSpecifyArgss (configProgramArgs cfg)
. userSpecifyPaths (configProgramPaths cfg)
. setProgramSearchPath searchpath
$ initialProgramsConfig
searchpath = getProgramSearchPath (initialProgramsConfig)
++ map ProgramSearchPathDir (fromNubList $ configProgramPathExtra cfg)
-- -----------------------------------------------------------------------------
-- Configuring package dependencies
reportProgram :: Verbosity -> Program -> Maybe ConfiguredProgram -> IO ()
reportProgram verbosity prog Nothing
= info verbosity $ "No " ++ programName prog ++ " found"
reportProgram verbosity prog (Just configuredProg)
= info verbosity $ "Using " ++ programName prog ++ version ++ location
where location = case programLocation configuredProg of
FoundOnSystem p -> " found on system at: " ++ p
UserSpecified p -> " given by user at: " ++ p
version = case programVersion configuredProg of
Nothing -> ""
Just v -> " version " ++ display v
hackageUrl :: String
hackageUrl = "http://hackage.haskell.org/package/"
data ResolvedDependency = ExternalDependency Dependency InstalledPackageInfo
| InternalDependency Dependency PackageId -- should be a
-- lib name
data FailedDependency = DependencyNotExists PackageName
| DependencyNoVersion Dependency
-- | Test for a package dependency and record the version we have installed.
selectDependency :: InstalledPackageIndex -- ^ Internally defined packages
-> InstalledPackageIndex -- ^ Installed packages
-> Map PackageName InstalledPackageInfo
-- ^ Packages for which we have been given specific deps to use
-> Dependency
-> Either FailedDependency ResolvedDependency
selectDependency internalIndex installedIndex requiredDepsMap
dep@(Dependency pkgname vr) =
-- If the dependency specification matches anything in the internal package
-- index, then we prefer that match to anything in the second.
-- For example:
--
-- Name: MyLibrary
-- Version: 0.1
-- Library
-- ..
-- Executable my-exec
-- build-depends: MyLibrary
--
-- We want "build-depends: MyLibrary" always to match the internal library
-- even if there is a newer installed library "MyLibrary-0.2".
-- However, "build-depends: MyLibrary >= 0.2" should match the installed one.
case PackageIndex.lookupPackageName internalIndex pkgname of
[(_,[pkg])] | packageVersion pkg `withinRange` vr
-> Right $ InternalDependency dep (packageId pkg)
_ -> case Map.lookup pkgname requiredDepsMap of
-- If we know the exact pkg to use, then use it.
Just pkginstance -> Right (ExternalDependency dep pkginstance)
-- Otherwise we just pick an arbitrary instance of the latest version.
Nothing -> case PackageIndex.lookupDependency installedIndex dep of
[] -> Left $ DependencyNotExists pkgname
pkgs -> Right $ ExternalDependency dep $
case last pkgs of
(_ver, pkginstances) -> head pkginstances
reportSelectedDependencies :: Verbosity
-> [ResolvedDependency] -> IO ()
reportSelectedDependencies verbosity deps =
info verbosity $ unlines
[ "Dependency " ++ display (simplifyDependency dep)
++ ": using " ++ display pkgid
| resolved <- deps
, let (dep, pkgid) = case resolved of
ExternalDependency dep' pkg' -> (dep', packageId pkg')
InternalDependency dep' pkgid' -> (dep', pkgid') ]
reportFailedDependencies :: [FailedDependency] -> IO ()
reportFailedDependencies [] = return ()
reportFailedDependencies failed =
die (intercalate "\n\n" (map reportFailedDependency failed))
where
reportFailedDependency (DependencyNotExists pkgname) =
"there is no version of " ++ display pkgname ++ " installed.\n"
++ "Perhaps you need to download and install it from\n"
++ hackageUrl ++ display pkgname ++ "?"
reportFailedDependency (DependencyNoVersion dep) =
"cannot satisfy dependency " ++ display (simplifyDependency dep) ++ "\n"
-- | List all installed packages in the given package databases.
getInstalledPackages :: Verbosity -> Compiler
-> PackageDBStack -- ^ The stack of package databases.
-> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity comp packageDBs progconf = do
when (null packageDBs) $
die $ "No package databases have been specified. If you use "
++ "--package-db=clear, you must follow it with --package-db= "
++ "with 'global', 'user' or a specific file."
info verbosity "Reading installed packages..."
case compilerFlavor comp of
GHC -> GHC.getInstalledPackages verbosity packageDBs progconf
GHCJS -> GHCJS.getInstalledPackages verbosity packageDBs progconf
JHC -> JHC.getInstalledPackages verbosity packageDBs progconf
LHC -> LHC.getInstalledPackages verbosity packageDBs progconf
UHC -> UHC.getInstalledPackages verbosity comp packageDBs progconf
HaskellSuite {} ->
HaskellSuite.getInstalledPackages verbosity packageDBs progconf
flv -> die $ "don't know how to find the installed packages for "
++ display flv
-- | Like 'getInstalledPackages', but for a single package DB.
getPackageDBContents :: Verbosity -> Compiler
-> PackageDB -> ProgramConfiguration
-> IO InstalledPackageIndex
getPackageDBContents verbosity comp packageDB progconf = do
info verbosity "Reading installed packages..."
case compilerFlavor comp of
GHC -> GHC.getPackageDBContents verbosity packageDB progconf
GHCJS -> GHCJS.getPackageDBContents verbosity packageDB progconf
-- For other compilers, try to fall back on 'getInstalledPackages'.
_ -> getInstalledPackages verbosity comp [packageDB] progconf
-- | The user interface specifies the package dbs to use with a combination of
-- @--global@, @--user@ and @--package-db=global|user|clear|$file@.
-- This function combines the global/user flag and interprets the package-db
-- flag into a single package db stack.
--
interpretPackageDbFlags :: Bool -> [Maybe PackageDB] -> PackageDBStack
interpretPackageDbFlags userInstall specificDBs =
extra initialStack specificDBs
where
initialStack | userInstall = [GlobalPackageDB, UserPackageDB]
| otherwise = [GlobalPackageDB]
extra dbs' [] = dbs'
extra _ (Nothing:dbs) = extra [] dbs
extra dbs' (Just db:dbs) = extra (dbs' ++ [db]) dbs
newPackageDepsBehaviourMinVersion :: Version
newPackageDepsBehaviourMinVersion = Version [1,7,1] []
-- In older cabal versions, there was only one set of package dependencies for
-- the whole package. In this version, we can have separate dependencies per
-- target, but we only enable this behaviour if the minimum cabal version
-- specified is >= a certain minimum. Otherwise, for compatibility we use the
-- old behaviour.
newPackageDepsBehaviour :: PackageDescription -> Bool
newPackageDepsBehaviour pkg =
specVersion pkg >= newPackageDepsBehaviourMinVersion
-- We are given both --constraint="foo < 2.0" style constraints and also
-- specific packages to pick via --dependency="foo=foo-2.0-177d5cdf20962d0581".
--
-- When finalising the package we have to take into account the specific
-- installed deps we've been given, and the finalise function expects
-- constraints, so we have to translate these deps into version constraints.
--
-- But after finalising we then have to make sure we pick the right specific
-- deps in the end. So we still need to remember which installed packages to
-- pick.
combinedConstraints :: [Dependency] ->
[(PackageName, InstalledPackageId)] ->
InstalledPackageIndex ->
Either String ([Dependency],
Map PackageName InstalledPackageInfo)
combinedConstraints constraints dependencies installedPackages = do
when (not (null badInstalledPackageIds)) $
Left $ render $ text "The following package dependencies were requested"
$+$ nest 4 (dispDependencies badInstalledPackageIds)
$+$ text "however the given installed package instance does not exist."
when (not (null badNames)) $
Left $ render $ text "The following package dependencies were requested"
$+$ nest 4 (dispDependencies badNames)
$+$ text "however the installed package's name does not match the name given."
--TODO: we don't check that all dependencies are used!
return (allConstraints, idConstraintMap)
where
allConstraints :: [Dependency]
allConstraints = constraints
++ [ thisPackageVersion (packageId pkg)
| (_, _, Just pkg) <- dependenciesPkgInfo ]
idConstraintMap :: Map PackageName InstalledPackageInfo
idConstraintMap = Map.fromList
[ (packageName pkg, pkg)
| (_, _, Just pkg) <- dependenciesPkgInfo ]
-- The dependencies along with the installed package info, if it exists
dependenciesPkgInfo :: [(PackageName, InstalledPackageId,
Maybe InstalledPackageInfo)]
dependenciesPkgInfo =
[ (pkgname, ipkgid, mpkg)
| (pkgname, ipkgid) <- dependencies
, let mpkg = PackageIndex.lookupInstalledPackageId
installedPackages ipkgid
]
-- If we looked up a package specified by an installed package id
-- (i.e. someone has written a hash) and didn't find it then it's
-- an error.
badInstalledPackageIds =
[ (pkgname, ipkgid)
| (pkgname, ipkgid, Nothing) <- dependenciesPkgInfo ]
-- If someone has written e.g.
-- --dependency="foo=MyOtherLib-1.0-07...5bf30" then they have
-- probably made a mistake.
badNames =
[ (requestedPkgName, ipkgid)
| (requestedPkgName, ipkgid, Just pkg) <- dependenciesPkgInfo
, let foundPkgName = packageName pkg
, requestedPkgName /= foundPkgName ]
dispDependencies deps =
hsep [ text "--dependency="
<> quotes (disp pkgname <> char '=' <> disp ipkgid)
| (pkgname, ipkgid) <- deps ]
-- -----------------------------------------------------------------------------
-- Configuring hole instantiation
configureInstantiateWith :: PackageDescription
-> ConfigFlags
-> InstalledPackageIndex -- ^ installed packages
-> IO ([InstalledPackageInfo],
[(ModuleName, (InstalledPackageInfo, ModuleName))])
configureInstantiateWith pkg_descr cfg installedPackageSet = do
-- Holes: First, check and make sure the provided instantiation covers
-- all the holes we know about. Indefinite package installation is
-- not handled at all at this point.
-- NB: We union together /all/ of the requirements when calculating
-- the package key.
-- NB: For now, we assume that dependencies don't contribute signatures.
-- This will be handled by cabal-install; as far as ./Setup is
-- concerned, the most important thing is to be provided correctly
-- built dependencies.
let signatures =
maybe [] (\lib -> requiredSignatures lib ++ exposedSignatures lib)
(PD.library pkg_descr)
signatureSet = Set.fromList signatures
instantiateMap = Map.fromList (configInstantiateWith cfg)
missing_impls = filter (not . flip Map.member instantiateMap) signatures
hole_insts0 = filter (\(k,_) -> Set.member k signatureSet) (configInstantiateWith cfg)
when (not (null missing_impls)) $
die $ "Missing signature implementations for these modules: "
++ intercalate ", " (map display missing_impls)
-- Holes: Next, we need to make sure we have packages to actually
-- provide the implementations we're talking about. This is on top
-- of the normal dependency resolution process.
-- TODO: internal dependencies (e.g. the test package depending on the
-- main library) is not currently supported
let selectHoleDependency (k,(i,m)) =
case PackageIndex.lookupInstalledPackageId installedPackageSet i of
Just pkginst -> Right (k,(pkginst, m))
Nothing -> Left i
(failed_hmap, hole_insts) = partitionEithers (map selectHoleDependency hole_insts0)
holeDeps = map (fst.snd) hole_insts -- could have dups
-- Holes: Finally, any dependencies selected this way have to be
-- included in the allPkgs index, as well as the buildComponents.
-- But don't report these as potential inconsistencies!
when (not (null failed_hmap)) $
die $ "Could not resolve these package IDs (from signature implementations): "
++ intercalate ", " (map display failed_hmap)
return (holeDeps, hole_insts)
-- -----------------------------------------------------------------------------
-- Configuring program dependencies
configureRequiredPrograms :: Verbosity -> [Dependency] -> ProgramConfiguration
-> IO ProgramConfiguration
configureRequiredPrograms verbosity deps conf =
foldM (configureRequiredProgram verbosity) conf deps
configureRequiredProgram :: Verbosity -> ProgramConfiguration -> Dependency
-> IO ProgramConfiguration
configureRequiredProgram verbosity conf
(Dependency (PackageName progName) verRange) =
case lookupKnownProgram progName conf of
Nothing -> die ("Unknown build tool " ++ progName)
Just prog
-- requireProgramVersion always requires the program have a version
-- but if the user says "build-depends: foo" ie no version constraint
-- then we should not fail if we cannot discover the program version.
| verRange == anyVersion -> do
(_, conf') <- requireProgram verbosity prog conf
return conf'
| otherwise -> do
(_, _, conf') <- requireProgramVersion verbosity prog verRange conf
return conf'
-- -----------------------------------------------------------------------------
-- Configuring pkg-config package dependencies
configurePkgconfigPackages :: Verbosity -> PackageDescription
-> ProgramConfiguration
-> IO (PackageDescription, ProgramConfiguration)
configurePkgconfigPackages verbosity pkg_descr conf
| null allpkgs = return (pkg_descr, conf)
| otherwise = do
(_, _, conf') <- requireProgramVersion
(lessVerbose verbosity) pkgConfigProgram
(orLaterVersion $ Version [0,9,0] []) conf
mapM_ requirePkg allpkgs
lib' <- mapM addPkgConfigBILib (library pkg_descr)
exes' <- mapM addPkgConfigBIExe (executables pkg_descr)
tests' <- mapM addPkgConfigBITest (testSuites pkg_descr)
benches' <- mapM addPkgConfigBIBench (benchmarks pkg_descr)
let pkg_descr' = pkg_descr { library = lib', executables = exes',
testSuites = tests', benchmarks = benches' }
return (pkg_descr', conf')
where
allpkgs = concatMap pkgconfigDepends (allBuildInfo pkg_descr)
pkgconfig = rawSystemProgramStdoutConf (lessVerbose verbosity)
pkgConfigProgram conf
requirePkg dep@(Dependency (PackageName pkg) range) = do
version <- pkgconfig ["--modversion", pkg]
`catchIO` (\_ -> die notFound)
`catchExit` (\_ -> die notFound)
case simpleParse version of
Nothing -> die "parsing output of pkg-config --modversion failed"
Just v | not (withinRange v range) -> die (badVersion v)
| otherwise -> info verbosity (depSatisfied v)
where
notFound = "The pkg-config package '" ++ pkg ++ "'"
++ versionRequirement
++ " is required but it could not be found."
badVersion v = "The pkg-config package '" ++ pkg ++ "'"
++ versionRequirement
++ " is required but the version installed on the"
++ " system is version " ++ display v
depSatisfied v = "Dependency " ++ display dep
++ ": using version " ++ display v
versionRequirement
| isAnyVersion range = ""
| otherwise = " version " ++ display range
-- Adds pkgconfig dependencies to the build info for a component
addPkgConfigBI compBI setCompBI comp = do
bi <- pkgconfigBuildInfo (pkgconfigDepends (compBI comp))
return $ setCompBI comp (compBI comp `mappend` bi)
-- Adds pkgconfig dependencies to the build info for a library
addPkgConfigBILib = addPkgConfigBI libBuildInfo $
\lib bi -> lib { libBuildInfo = bi }
-- Adds pkgconfig dependencies to the build info for an executable
addPkgConfigBIExe = addPkgConfigBI buildInfo $
\exe bi -> exe { buildInfo = bi }
-- Adds pkgconfig dependencies to the build info for a test suite
addPkgConfigBITest = addPkgConfigBI testBuildInfo $
\test bi -> test { testBuildInfo = bi }
-- Adds pkgconfig dependencies to the build info for a benchmark
addPkgConfigBIBench = addPkgConfigBI benchmarkBuildInfo $
\bench bi -> bench { benchmarkBuildInfo = bi }
pkgconfigBuildInfo :: [Dependency] -> IO BuildInfo
pkgconfigBuildInfo [] = return mempty
pkgconfigBuildInfo pkgdeps = do
let pkgs = nub [ display pkg | Dependency pkg _ <- pkgdeps ]
ccflags <- pkgconfig ("--cflags" : pkgs)
ldflags <- pkgconfig ("--libs" : pkgs)
return (ccLdOptionsBuildInfo (words ccflags) (words ldflags))
-- | Makes a 'BuildInfo' from C compiler and linker flags.
--
-- This can be used with the output from configuration programs like pkg-config
-- and similar package-specific programs like mysql-config, freealut-config etc.
-- For example:
--
-- > ccflags <- rawSystemProgramStdoutConf verbosity prog conf ["--cflags"]
-- > ldflags <- rawSystemProgramStdoutConf verbosity prog conf ["--libs"]
-- > return (ccldOptionsBuildInfo (words ccflags) (words ldflags))
--
ccLdOptionsBuildInfo :: [String] -> [String] -> BuildInfo
ccLdOptionsBuildInfo cflags ldflags =
let (includeDirs', cflags') = partition ("-I" `isPrefixOf`) cflags
(extraLibs', ldflags') = partition ("-l" `isPrefixOf`) ldflags
(extraLibDirs', ldflags'') = partition ("-L" `isPrefixOf`) ldflags'
in mempty {
PD.includeDirs = map (drop 2) includeDirs',
PD.extraLibs = map (drop 2) extraLibs',
PD.extraLibDirs = map (drop 2) extraLibDirs',
PD.ccOptions = cflags',
PD.ldOptions = ldflags''
}
-- -----------------------------------------------------------------------------
-- Determining the compiler details
configCompilerAuxEx :: ConfigFlags
-> IO (Compiler, Platform, ProgramConfiguration)
configCompilerAuxEx cfg = configCompilerEx (flagToMaybe $ configHcFlavor cfg)
(flagToMaybe $ configHcPath cfg)
(flagToMaybe $ configHcPkg cfg)
programsConfig
(fromFlag (configVerbosity cfg))
where
programsConfig = mkProgramsConfig cfg defaultProgramConfiguration
configCompilerEx :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> Verbosity
-> IO (Compiler, Platform, ProgramConfiguration)
configCompilerEx Nothing _ _ _ _ = die "Unknown compiler"
configCompilerEx (Just hcFlavor) hcPath hcPkg conf verbosity = do
(comp, maybePlatform, programsConfig) <- case hcFlavor of
GHC -> GHC.configure verbosity hcPath hcPkg conf
GHCJS -> GHCJS.configure verbosity hcPath hcPkg conf
JHC -> JHC.configure verbosity hcPath hcPkg conf
LHC -> do (_, _, ghcConf) <- GHC.configure verbosity Nothing hcPkg conf
LHC.configure verbosity hcPath Nothing ghcConf
UHC -> UHC.configure verbosity hcPath hcPkg conf
HaskellSuite {} -> HaskellSuite.configure verbosity hcPath hcPkg conf
_ -> die "Unknown compiler"
return (comp, fromMaybe buildPlatform maybePlatform, programsConfig)
-- Ideally we would like to not have separate configCompiler* and
-- configCompiler*Ex sets of functions, but there are many custom setup scripts
-- in the wild that are using them, so the versions with old types are kept for
-- backwards compatibility. Platform was added to the return triple in 1.18.
{-# DEPRECATED configCompiler
"'configCompiler' is deprecated. Use 'configCompilerEx' instead." #-}
configCompiler :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> Verbosity
-> IO (Compiler, ProgramConfiguration)
configCompiler mFlavor hcPath hcPkg conf verbosity =
fmap (\(a,_,b) -> (a,b)) $ configCompilerEx mFlavor hcPath hcPkg conf verbosity
{-# DEPRECATED configCompilerAux
"configCompilerAux is deprecated. Use 'configCompilerAuxEx' instead." #-}
configCompilerAux :: ConfigFlags
-> IO (Compiler, ProgramConfiguration)
configCompilerAux = fmap (\(a,_,b) -> (a,b)) . configCompilerAuxEx
-- -----------------------------------------------------------------------------
-- Making the internal component graph
mkComponentsGraph :: PackageDescription
-> [PackageId]
-> Either [ComponentName]
[(Component, [ComponentName])]
mkComponentsGraph pkg_descr internalPkgDeps =
let graph = [ (c, componentName c, componentDeps c)
| c <- pkgEnabledComponents pkg_descr ]
in case checkComponentsCyclic graph of
Just ccycle -> Left [ cname | (_,cname,_) <- ccycle ]
Nothing -> Right [ (c, cdeps) | (c, _, cdeps) <- graph ]
where
-- The dependencies for the given component
componentDeps component =
[ CExeName toolname | Dependency (PackageName toolname) _
<- buildTools bi
, toolname `elem` map exeName
(executables pkg_descr) ]
++ [ CLibName | Dependency pkgname _ <- targetBuildDepends bi
, pkgname `elem` map packageName internalPkgDeps ]
where
bi = componentBuildInfo component
reportComponentCycle :: [ComponentName] -> IO a
reportComponentCycle cnames =
die $ "Components in the package depend on each other in a cyclic way:\n "
++ intercalate " depends on "
[ "'" ++ showComponentName cname ++ "'"
| cname <- cnames ++ [head cnames] ]
mkComponentsLocalBuildInfo :: InstalledPackageIndex
-> PackageDescription
-> [PackageId] -- internal package deps
-> [InstalledPackageInfo] -- external package deps
-> [InstalledPackageInfo] -- hole package deps
-> Map ModuleName (InstalledPackageInfo, ModuleName)
-> PackageKey
-> [(Component, [ComponentName])]
-> Either [(ModuleReexport, String)] -- errors
[(ComponentName, ComponentLocalBuildInfo,
[ComponentName])] -- ok
mkComponentsLocalBuildInfo installedPackages pkg_descr
internalPkgDeps externalPkgDeps holePkgDeps hole_insts
pkg_key graph =
sequence
[ do clbi <- componentLocalBuildInfo c
return (componentName c, clbi, cdeps)
| (c, cdeps) <- graph ]
where
-- The allPkgDeps contains all the package deps for the whole package
-- but we need to select the subset for this specific component.
-- we just take the subset for the package names this component
-- needs. Note, this only works because we cannot yet depend on two
-- versions of the same package.
componentLocalBuildInfo component =
case component of
CLib lib -> do
let exports = map (\n -> Installed.ExposedModule n Nothing Nothing)
(PD.exposedModules lib)
esigs = map (\n -> Installed.ExposedModule n Nothing
(fmap (\(pkg,m) -> Installed.OriginalModule
(Installed.installedPackageId pkg) m)
(Map.lookup n hole_insts)))
(PD.exposedSignatures lib)
reexports <- resolveModuleReexports installedPackages
(packageId pkg_descr)
externalPkgDeps lib
return LibComponentLocalBuildInfo {
componentPackageDeps = cpds,
componentLibraries = [LibraryName ("HS" ++ display pkg_key)],
componentPackageRenaming = cprns,
componentExposedModules = exports ++ reexports ++ esigs
}
CExe _ ->
return ExeComponentLocalBuildInfo {
componentPackageDeps = cpds,
componentPackageRenaming = cprns
}
CTest _ ->
return TestComponentLocalBuildInfo {
componentPackageDeps = cpds,
componentPackageRenaming = cprns
}
CBench _ ->
return BenchComponentLocalBuildInfo {
componentPackageDeps = cpds,
componentPackageRenaming = cprns
}
where
bi = componentBuildInfo component
dedup = Map.toList . Map.fromList
cpds = if newPackageDepsBehaviour pkg_descr
then dedup $
[ (Installed.installedPackageId pkg, packageId pkg)
| pkg <- selectSubset bi externalPkgDeps ]
++ [ (inplacePackageId pkgid, pkgid)
| pkgid <- selectSubset bi internalPkgDeps ]
++ [ (Installed.installedPackageId pkg, packageId pkg)
| pkg <- holePkgDeps ]
else [ (Installed.installedPackageId pkg, packageId pkg)
| pkg <- externalPkgDeps ]
cprns = if newPackageDepsBehaviour pkg_descr
then Map.unionWith mappend
-- We need hole dependencies passed to GHC, so add them here
-- (but note that they're fully thinned out. If they
-- appeared legitimately the monoid instance will
-- fill them out.
(Map.fromList [(packageName pkg, mempty) | pkg <- holePkgDeps])
(targetBuildRenaming bi)
-- Hack: if we have old package-deps behavior, it's impossible
-- for non-default renamings to be used, because the Cabal
-- version is too early. This is a good, because while all the
-- deps were bundled up in buildDepends, we didn't do this for
-- renamings, so it's not even clear how to get the merged
-- version. So just assume that all of them are the default..
else Map.fromList (map (\(_,pid) -> (packageName pid, defaultRenaming)) cpds)
selectSubset :: Package pkg => BuildInfo -> [pkg] -> [pkg]
selectSubset bi pkgs =
[ pkg | pkg <- pkgs, packageName pkg `elem` names bi ]
names bi = [ name | Dependency name _ <- targetBuildDepends bi ]
-- | Given the author-specified re-export declarations from the .cabal file,
-- resolve them to the form that we need for the package database.
--
-- An invariant of the package database is that we always link the re-export
-- directly to its original defining location (rather than indirectly via a
-- chain of re-exporting packages).
--
resolveModuleReexports :: InstalledPackageIndex
-> PackageId
-> [InstalledPackageInfo]
-> Library
-> Either [(ModuleReexport, String)] -- errors
[Installed.ExposedModule] -- ok
resolveModuleReexports installedPackages srcpkgid externalPkgDeps lib =
case partitionEithers (map resolveModuleReexport (PD.reexportedModules lib)) of
([], ok) -> Right ok
(errs, _) -> Left errs
where
-- A mapping from visible module names to their original defining
-- module name. We also record the package name of the package which
-- *immediately* provided the module (not the original) to handle if the
-- user explicitly says which build-depends they want to reexport from.
visibleModules :: Map ModuleName [(PackageName, Installed.ExposedModule)]
visibleModules =
Map.fromListWith (++) $
[ (Installed.exposedName exposedModule, [(exportingPackageName,
exposedModule)])
-- The package index here contains all the indirect deps of the
-- package we're configuring, but we want just the direct deps
| let directDeps = Set.fromList (map Installed.installedPackageId externalPkgDeps)
, pkg <- PackageIndex.allPackages installedPackages
, Installed.installedPackageId pkg `Set.member` directDeps
, let exportingPackageName = packageName pkg
, exposedModule <- visibleModuleDetails pkg
]
++ [ (visibleModuleName, [(exportingPackageName, exposedModule)])
| visibleModuleName <- PD.exposedModules lib
++ otherModules (libBuildInfo lib)
, let exportingPackageName = packageName srcpkgid
definingModuleName = visibleModuleName
-- we don't know the InstalledPackageId of this package yet
-- we will fill it in later, before registration.
definingPackageId = InstalledPackageId ""
originalModule = Installed.OriginalModule definingPackageId
definingModuleName
exposedModule = Installed.ExposedModule visibleModuleName
(Just originalModule)
Nothing
]
-- All the modules exported from this package and their defining name and
-- package (either defined here in this package or re-exported from some
-- other package). Return an ExposedModule because we want to hold onto
-- signature information.
visibleModuleDetails :: InstalledPackageInfo -> [Installed.ExposedModule]
visibleModuleDetails pkg = do
exposedModule <- Installed.exposedModules pkg
case Installed.exposedReexport exposedModule of
-- The first case is the modules actually defined in this package.
-- In this case the reexport will point to this package.
Nothing -> return exposedModule { Installed.exposedReexport =
Just (Installed.OriginalModule (Installed.installedPackageId pkg)
(Installed.exposedName exposedModule)) }
-- On the other hand, a visible module might actually be itself
-- a re-export! In this case, the re-export info for the package
-- doing the re-export will point us to the original defining
-- module name and package, so we can reuse the entry.
Just _ -> return exposedModule
resolveModuleReexport reexport@ModuleReexport {
moduleReexportOriginalPackage = moriginalPackageName,
moduleReexportOriginalName = originalName,
moduleReexportName = newName
} =
let filterForSpecificPackage =
case moriginalPackageName of
Nothing -> id
Just originalPackageName ->
filter (\(pkgname, _) -> pkgname == originalPackageName)
matches = filterForSpecificPackage
(Map.findWithDefault [] originalName visibleModules)
in
case (matches, moriginalPackageName) of
((_, exposedModule):rest, _)
-- TODO: Refine this check for signatures
| all (\(_, exposedModule') -> Installed.exposedReexport exposedModule
== Installed.exposedReexport exposedModule') rest
-> Right exposedModule { Installed.exposedName = newName }
([], Just originalPackageName)
-> Left $ (,) reexport
$ "The package " ++ display originalPackageName
++ " does not export a module " ++ display originalName
([], Nothing)
-> Left $ (,) reexport
$ "The module " ++ display originalName
++ " is not exported by any suitable package (this package "
++ "itself nor any of its 'build-depends' dependencies)."
(ms, _)
-> Left $ (,) reexport
$ "The module " ++ display originalName ++ " is exported "
++ "by more than one package ("
++ intercalate ", " [ display pkgname | (pkgname,_) <- ms ]
++ ") and so the re-export is ambiguous. The ambiguity can "
++ "be resolved by qualifying by the package name. The "
++ "syntax is 'packagename:moduleName [as newname]'."
-- Note: if in future Cabal allows directly depending on multiple
-- instances of the same package (e.g. backpack) then an additional
-- ambiguity case is possible here: (_, Just originalPackageName)
-- with the module being ambiguous despite being qualified by a
-- package name. Presumably by that time we'll have a mechanism to
-- qualify the instance we're referring to.
reportModuleReexportProblems :: [(ModuleReexport, String)] -> IO a
reportModuleReexportProblems reexportProblems =
die $ unlines
[ "Problem with the module re-export '" ++ display reexport ++ "': " ++ msg
| (reexport, msg) <- reexportProblems ]
-- -----------------------------------------------------------------------------
-- Testing C lib and header dependencies
-- Try to build a test C program which includes every header and links every
-- lib. If that fails, try to narrow it down by preprocessing (only) and linking
-- with individual headers and libs. If none is the obvious culprit then give a
-- generic error message.
-- TODO: produce a log file from the compiler errors, if any.
checkForeignDeps :: PackageDescription -> LocalBuildInfo -> Verbosity -> IO ()
checkForeignDeps pkg lbi verbosity = do
ifBuildsWith allHeaders (commonCcArgs ++ makeLdArgs allLibs) -- I'm feeling
-- lucky
(return ())
(do missingLibs <- findMissingLibs
missingHdr <- findOffendingHdr
explainErrors missingHdr missingLibs)
where
allHeaders = collectField PD.includes
allLibs = collectField PD.extraLibs
ifBuildsWith headers args success failure = do
ok <- builds (makeProgram headers) args
if ok then success else failure
findOffendingHdr =
ifBuildsWith allHeaders ccArgs
(return Nothing)
(go . tail . inits $ allHeaders)
where
go [] = return Nothing -- cannot happen
go (hdrs:hdrsInits) =
-- Try just preprocessing first
ifBuildsWith hdrs cppArgs
-- If that works, try compiling too
(ifBuildsWith hdrs ccArgs
(go hdrsInits)
(return . Just . Right . last $ hdrs))
(return . Just . Left . last $ hdrs)
cppArgs = "-E":commonCppArgs -- preprocess only
ccArgs = "-c":commonCcArgs -- don't try to link
findMissingLibs = ifBuildsWith [] (makeLdArgs allLibs)
(return [])
(filterM (fmap not . libExists) allLibs)
libExists lib = builds (makeProgram []) (makeLdArgs [lib])
commonCppArgs = platformDefines lbi
++ [ "-I" ++ autogenModulesDir lbi ]
++ [ "-I" ++ dir | dir <- collectField PD.includeDirs ]
++ ["-I."]
++ collectField PD.cppOptions
++ collectField PD.ccOptions
++ [ "-I" ++ dir
| dep <- deps
, dir <- Installed.includeDirs dep ]
++ [ opt
| dep <- deps
, opt <- Installed.ccOptions dep ]
commonCcArgs = commonCppArgs
++ collectField PD.ccOptions
++ [ opt
| dep <- deps
, opt <- Installed.ccOptions dep ]
commonLdArgs = [ "-L" ++ dir | dir <- collectField PD.extraLibDirs ]
++ collectField PD.ldOptions
++ [ "-L" ++ dir
| dep <- deps
, dir <- Installed.libraryDirs dep ]
--TODO: do we also need dependent packages' ld options?
makeLdArgs libs = [ "-l"++lib | lib <- libs ] ++ commonLdArgs
makeProgram hdrs = unlines $
[ "#include \"" ++ hdr ++ "\"" | hdr <- hdrs ] ++
["int main(int argc, char** argv) { return 0; }"]
collectField f = concatMap f allBi
allBi = allBuildInfo pkg
deps = PackageIndex.topologicalOrder (installedPkgs lbi)
builds program args = do
tempDir <- getTemporaryDirectory
withTempFile tempDir ".c" $ \cName cHnd ->
withTempFile tempDir "" $ \oNname oHnd -> do
hPutStrLn cHnd program
hClose cHnd
hClose oHnd
_ <- rawSystemProgramStdoutConf verbosity
gccProgram (withPrograms lbi) (cName:"-o":oNname:args)
return True
`catchIO` (\_ -> return False)
`catchExit` (\_ -> return False)
explainErrors Nothing [] = return () -- should be impossible!
explainErrors _ _
| isNothing . lookupProgram gccProgram . withPrograms $ lbi
= die $ unlines $
[ "No working gcc",
"This package depends on foreign library but we cannot "
++ "find a working C compiler. If you have it in a "
++ "non-standard location you can use the --with-gcc "
++ "flag to specify it." ]
explainErrors hdr libs = die $ unlines $
[ if plural
then "Missing dependencies on foreign libraries:"
else "Missing dependency on a foreign library:"
| missing ]
++ case hdr of
Just (Left h) -> ["* Missing (or bad) header file: " ++ h ]
_ -> []
++ case libs of
[] -> []
[lib] -> ["* Missing C library: " ++ lib]
_ -> ["* Missing C libraries: " ++ intercalate ", " libs]
++ [if plural then messagePlural else messageSingular | missing]
++ case hdr of
Just (Left _) -> [ headerCppMessage ]
Just (Right h) -> [ (if missing then "* " else "")
++ "Bad header file: " ++ h
, headerCcMessage ]
_ -> []
where
plural = length libs >= 2
-- Is there something missing? (as opposed to broken)
missing = not (null libs)
|| case hdr of Just (Left _) -> True; _ -> False
messageSingular =
"This problem can usually be solved by installing the system "
++ "package that provides this library (you may need the "
++ "\"-dev\" version). If the library is already installed "
++ "but in a non-standard location then you can use the flags "
++ "--extra-include-dirs= and --extra-lib-dirs= to specify "
++ "where it is."
messagePlural =
"This problem can usually be solved by installing the system "
++ "packages that provide these libraries (you may need the "
++ "\"-dev\" versions). If the libraries are already installed "
++ "but in a non-standard location then you can use the flags "
++ "--extra-include-dirs= and --extra-lib-dirs= to specify "
++ "where they are."
headerCppMessage =
"If the header file does exist, it may contain errors that "
++ "are caught by the C compiler at the preprocessing stage. "
++ "In this case you can re-run configure with the verbosity "
++ "flag -v3 to see the error messages."
headerCcMessage =
"The header file contains a compile error. "
++ "You can re-run configure with the verbosity flag "
++ "-v3 to see the error messages from the C compiler."
-- | Output package check warnings and errors. Exit if any errors.
checkPackageProblems :: Verbosity
-> GenericPackageDescription
-> PackageDescription
-> IO ()
checkPackageProblems verbosity gpkg pkg = do
ioChecks <- checkPackageFiles pkg "."
let pureChecks = checkPackage gpkg (Just pkg)
errors = [ e | PackageBuildImpossible e <- pureChecks ++ ioChecks ]
warnings = [ w | PackageBuildWarning w <- pureChecks ++ ioChecks ]
if null errors
then mapM_ (warn verbosity) warnings
else die (intercalate "\n\n" errors)
-- | Preform checks if a relocatable build is allowed
checkRelocatable :: Verbosity
-> PackageDescription
-> LocalBuildInfo
-> IO ()
checkRelocatable verbosity pkg lbi
= sequence_ [ checkOS
, checkCompiler
, packagePrefixRelative
, depsPrefixRelative
]
where
-- Check if the OS support relocatable builds.
--
-- If you add new OS' to this list, and your OS supports dynamic libraries
-- and RPATH, make sure you add your OS to RPATH-support list of:
-- Distribution.Simple.GHC.getRPaths
checkOS
= unless (os `elem` [ OSX, Linux ])
$ die $ "Operating system: " ++ display os ++
", does not support relocatable builds"
where
(Platform _ os) = hostPlatform lbi
-- Check if the Compiler support relocatable builds
checkCompiler
= unless (compilerFlavor comp `elem` [ GHC ])
$ die $ "Compiler: " ++ show comp ++
", does not support relocatable builds"
where
comp = compiler lbi
-- Check if all the install dirs are relative to same prefix
packagePrefixRelative
= unless (relativeInstallDirs installDirs)
$ die $ "Installation directories are not prefix_relative:\n" ++
show installDirs
where
installDirs = absoluteInstallDirs pkg lbi NoCopyDest
p = prefix installDirs
relativeInstallDirs (InstallDirs {..}) =
all isJust
(fmap (stripPrefix p)
[ bindir, libdir, dynlibdir, libexecdir, includedir, datadir
, docdir, mandir, htmldir, haddockdir, sysconfdir] )
-- Check if the library dirs of the dependencies that are in the package
-- database to which the package is installed are relative to the
-- prefix of the package
depsPrefixRelative = do
pkgr <- GHC.pkgRoot verbosity lbi (last (withPackageDB lbi))
mapM_ (doCheck pkgr) ipkgs
where
doCheck pkgr ipkg
| maybe False (== pkgr) (Installed.pkgRoot ipkg)
= mapM_ (\l -> when (isNothing $ stripPrefix p l) (die (msg l)))
(Installed.libraryDirs ipkg)
| otherwise
= return ()
installDirs = absoluteInstallDirs pkg lbi NoCopyDest
p = prefix installDirs
ipkgs = PackageIndex.allPackages (installedPkgs lbi)
msg l = "Library directory of a dependency: " ++ show l ++
"\nis not relative to the installation prefix:\n" ++
show p
|
plumlife/cabal
|
Cabal/Distribution/Simple/Configure.hs
|
bsd-3-clause
| 82,365 | 1 | 26 | 26,288 | 14,167 | 7,473 | 6,694 | 1,204 | 15 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
module Category.TypedGraph.FinalPullbackComplementSpec where
import Test.Hspec
import Abstract.Category
import Abstract.Category.Adhesive
import Abstract.Rewriting.DPO
import Category.TypedGraph ()
import Data.TypedGraph as TG
import Data.TypedGraph.Morphism
import qualified Data.Graphs as G
import qualified Data.Graphs.Morphism as G
import qualified XML.GGXReader as XML
spec :: Spec
spec = context "Final Pullback Complement" fpbcTest
fpbcTest :: Spec
fpbcTest =
it "Should return precalculated results" $ do
let fileName = "tests/grammars/fpbc.ggx"
(gg,_,_) <- XML.readGrammar fileName False undefined
let (r1:r2:r3:_) = map snd (productions gg)
test1 = prepareTest1 r1
test2 = prepareTest2 r2
test3 = prepareTest3 r3
verifyAnyPullback test1
verifyR1 test1
verifyAnyPullback test2
verifyR2 test2
verifyAnyPullback test3
verifyR3 test3
-- Gets rules and set them to appropriated morphisms tests
prepareTest1 r1 = (m,l,k,l')
where
m = leftMorphism r1
l = invert (rightMorphism r1)
(k,l') = calculateFinalPullbackComplement m l
prepareTest2 r2 = (m,l,k,l')
where
m = leftMorphism r2
l = foldr
removeNodeFromDomain
(invert (rightMorphism r2))
(nodeIds . codomain $ rightMorphism r2)
(k,l') = calculateFinalPullbackComplement m l
prepareTest3 r3 = (m,l,k,l')
where
m = leftMorphism r3
node = head (nodeIds . codomain $ rightMorphism r3)
l = createNodeOnDomain
(node + G.NodeId 1)
(G.applyNodeIdUnsafe (rightObject r3) node)
(head (nodeIds . domain $ rightMorphism r3))
(invert (rightMorphism r3))
(k,l') = calculateFinalPullbackComplement m l
-- Generic tests for any pullback square
verifyAnyPullback (m,l,k,l') =
do
domain l `shouldBe` domain k
codomain l `shouldBe` domain m
codomain k `shouldBe` domain l'
codomain m `shouldBe` codomain l'
m <&> l `shouldBe` l' <&> k
isMonic l `shouldBe` isMonic l'
isMonic m `shouldBe` isMonic k
-- Specific tests
verifyR1 (_,_,k,l') =
do
length (nodeIds $ codomain k) `shouldBe` 1
length (edgeIds $ codomain k) `shouldBe` 1
isIsomorphism l' `shouldBe` True
verifyR2 (_,_,k,l') = TG.null (codomain k) `shouldBe` True
verifyR3 (_,_,k,l') =
do
length (nodeIds $ codomain k) `shouldBe` 2
length (edgeIds $ codomain k) `shouldBe` 4
|
rodrigo-machado/verigraph
|
tests/Category/TypedGraph/FinalPullbackComplementSpec.hs
|
gpl-3.0
| 2,559 | 0 | 14 | 633 | 835 | 442 | 393 | 69 | 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.CloudSearchDomains.Suggest
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Retrieves autocomplete suggestions for a partial query string. You can use
-- suggestions enable you to display likely matches before users finish typing.
-- In Amazon CloudSearch, suggestions are based on the contents of a particular
-- text field. When you request suggestions, Amazon CloudSearch finds all of the
-- documents whose values in the suggester field start with the specified query
-- string. The beginning of the field must match the query string to be
-- considered a match.
--
-- For more information about configuring suggesters and retrieving
-- suggestions, see <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html Getting Suggestions> in the /Amazon CloudSearch Developer Guide/
-- .
--
-- The endpoint for submitting 'Suggest' requests is domain-specific. You submit
-- suggest requests to a domain's search endpoint. To get the search endpoint
-- for your domain, use the Amazon CloudSearch configuration service 'DescribeDomains' action. A domain's endpoints are also displayed on the domain dashboard in
-- the Amazon CloudSearch console.
--
-- <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/API_Suggest.html>
module Network.AWS.CloudSearchDomains.Suggest
(
-- * Request
Suggest
-- ** Request constructor
, suggest
-- ** Request lenses
, sQuery
, sSize
, sSuggester
-- * Response
, SuggestResponse
-- ** Response constructor
, suggestResponse
-- ** Response lenses
, srStatus
, srSuggest
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.RestJSON
import Network.AWS.CloudSearchDomains.Types
import qualified GHC.Exts
data Suggest = Suggest
{ _sQuery :: Text
, _sSize :: Maybe Integer
, _sSuggester :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'Suggest' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'sQuery' @::@ 'Text'
--
-- * 'sSize' @::@ 'Maybe' 'Integer'
--
-- * 'sSuggester' @::@ 'Text'
--
suggest :: Text -- ^ 'sQuery'
-> Text -- ^ 'sSuggester'
-> Suggest
suggest p1 p2 = Suggest
{ _sQuery = p1
, _sSuggester = p2
, _sSize = Nothing
}
-- | Specifies the string for which you want to get suggestions.
sQuery :: Lens' Suggest Text
sQuery = lens _sQuery (\s a -> s { _sQuery = a })
-- | Specifies the maximum number of suggestions to return.
sSize :: Lens' Suggest (Maybe Integer)
sSize = lens _sSize (\s a -> s { _sSize = a })
-- | Specifies the name of the suggester to use to find suggested matches.
sSuggester :: Lens' Suggest Text
sSuggester = lens _sSuggester (\s a -> s { _sSuggester = a })
data SuggestResponse = SuggestResponse
{ _srStatus :: Maybe SuggestStatus
, _srSuggest :: Maybe SuggestModel
} deriving (Eq, Read, Show)
-- | 'SuggestResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'srStatus' @::@ 'Maybe' 'SuggestStatus'
--
-- * 'srSuggest' @::@ 'Maybe' 'SuggestModel'
--
suggestResponse :: SuggestResponse
suggestResponse = SuggestResponse
{ _srStatus = Nothing
, _srSuggest = Nothing
}
-- | The status of a 'SuggestRequest'. Contains the resource ID ('rid') and how long
-- it took to process the request ('timems').
srStatus :: Lens' SuggestResponse (Maybe SuggestStatus)
srStatus = lens _srStatus (\s a -> s { _srStatus = a })
-- | Container for the matching search suggestion information.
srSuggest :: Lens' SuggestResponse (Maybe SuggestModel)
srSuggest = lens _srSuggest (\s a -> s { _srSuggest = a })
instance ToPath Suggest where
toPath = const "/2013-01-01/suggest"
instance ToQuery Suggest where
toQuery Suggest{..} = mconcat
[ "q" =? _sQuery
, "size" =? _sSize
, "suggester" =? _sSuggester
]
instance ToHeaders Suggest
instance ToJSON Suggest where
toJSON = const (toJSON Empty)
instance AWSRequest Suggest where
type Sv Suggest = CloudSearchDomains
type Rs Suggest = SuggestResponse
request = get
response = jsonResponse
instance FromJSON SuggestResponse where
parseJSON = withObject "SuggestResponse" $ \o -> SuggestResponse
<$> o .:? "status"
<*> o .:? "suggest"
|
kim/amazonka
|
amazonka-cloudsearch-domains/gen/Network/AWS/CloudSearchDomains/Suggest.hs
|
mpl-2.0
| 5,316 | 0 | 11 | 1,169 | 679 | 413 | 266 | 75 | 1 |
{-# LANGUAGE ScopedTypeVariables #-} -- We will explain why we need this later
module GettingStarted where
runTests = do
putStrLn "something along the lines of: quickCheck prop_SquareRootOfNSquaredEqualsN goes here"
|
qwaneu/property-based-tutorial
|
exercises/hs/src/GettingStarted.hs
|
bsd-3-clause
| 220 | 0 | 7 | 33 | 17 | 10 | 7 | 4 | 1 |
module DeleteWebhook where
import Github.Repos.Webhooks
import qualified Github.Auth as Auth
main :: IO ()
main = do
let auth = Auth.OAuth "oauthtoken"
resp <- deleteRepoWebhook' auth "repoOwner" "repoName" 123
case resp of
(Left err) -> putStrLn $ "Error: " ++ (show err)
(Right stat) -> putStrLn $ "Resp: " ++ (show stat)
|
jwiegley/github
|
samples/Repos/Webhooks/DeleteWebhook.hs
|
bsd-3-clause
| 340 | 0 | 12 | 68 | 122 | 63 | 59 | 10 | 2 |
module Test.SwiftNav.SBP.Piksi
( tests
) where
import BasicPrelude
import SwiftNav.SBP.Piksi
import Test.SwiftNav.SBP.Utils
import Test.Tasty
import Test.Tasty.HUnit
testParse :: TestTree
testParse =
testGroup "Package tests"
[ testCase "Parsing tests" $ do
let filepath = "../spec/tests/yaml/swiftnav/sbp/test_piksi.yaml"
moduleName = "sbp.piksi"
val <- assertPackage filepath moduleName
assertBool "Fail" val
]
tests :: TestTree
tests =
testGroup "Piksi Tests"
[ testParse
]
|
mookerji/libsbp
|
haskell/test/Test/SwiftNav/SBP/Piksi.hs
|
lgpl-3.0
| 540 | 0 | 12 | 120 | 117 | 65 | 52 | 19 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
-- | A wrapper around hoogle.
module Stack.Hoogle
( hoogleCmd
) where
import Stack.Prelude
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.Char (isSpace)
import Data.List (find)
import qualified Data.Set as Set
import qualified Data.Text as T
import Lens.Micro
import Path.IO hiding (findExecutable)
import qualified Stack.Build
import Stack.Fetch
import Stack.Runners
import Stack.Types.Config
import Stack.Types.PackageIdentifier
import Stack.Types.PackageName
import Stack.Types.Version
import System.Exit
import RIO.Process
-- | Hoogle command.
hoogleCmd :: ([String],Bool,Bool) -> GlobalOpts -> IO ()
hoogleCmd (args,setup,rebuild) go = withBuildConfig go $ do
hooglePath <- ensureHoogleInPath
generateDbIfNeeded hooglePath
runHoogle hooglePath args
where
generateDbIfNeeded :: Path Abs File -> RIO EnvConfig ()
generateDbIfNeeded hooglePath = do
databaseExists <- checkDatabaseExists
if databaseExists && not rebuild
then return ()
else if setup || rebuild
then do
logWarn
(if rebuild
then "Rebuilding database ..."
else "No Hoogle database yet. Automatically building haddocks and hoogle database (use --no-setup to disable) ...")
buildHaddocks
logInfo "Built docs."
generateDb hooglePath
logInfo "Generated DB."
else do
logError
"No Hoogle database. Not building one due to --no-setup"
bail
generateDb :: Path Abs File -> RIO EnvConfig ()
generateDb hooglePath = do
do dir <- hoogleRoot
createDirIfMissing True dir
runHoogle hooglePath ["generate", "--local"]
buildHaddocks :: RIO EnvConfig ()
buildHaddocks =
liftIO
(catch
(withBuildConfigAndLock
(set
(globalOptsBuildOptsMonoidL . buildOptsMonoidHaddockL)
(Just True)
go)
(\lk ->
Stack.Build.build
(const (return ()))
lk
defaultBuildOptsCLI))
(\(_ :: ExitCode) ->
return ()))
hooglePackageName = $(mkPackageName "hoogle")
hoogleMinVersion = $(mkVersion "5.0")
hoogleMinIdent =
PackageIdentifier hooglePackageName hoogleMinVersion
installHoogle :: RIO EnvConfig ()
installHoogle = do
hooglePackageIdentifier <-
do (_,_,resolved) <-
resolvePackagesAllowMissing
-- FIXME this Nothing means "do not follow any
-- specific snapshot", which matches old
-- behavior. However, since introducing the
-- logic to pin a name to a package in a
-- snapshot, we may arguably want to ensure
-- that we're grabbing the version of Hoogle
-- present in the snapshot currently being
-- used.
Nothing
mempty
(Set.fromList [hooglePackageName])
return
(case find
((== hooglePackageName) . packageIdentifierName)
(map rpIdent resolved) of
Just ident@(PackageIdentifier _ ver)
| ver >= hoogleMinVersion -> Right ident
_ -> Left hoogleMinIdent)
case hooglePackageIdentifier of
Left{} ->
logInfo
("Minimum " <> packageIdentifierText hoogleMinIdent <>
" is not in your index. Installing the minimum version.")
Right ident ->
logInfo
("Minimum version is " <> packageIdentifierText hoogleMinIdent <>
". Found acceptable " <>
packageIdentifierText ident <>
" in your index, installing it.")
config <- view configL
menv <- liftIO $ configEnvOverrideSettings config envSettings
liftIO
(catch
(withBuildConfigAndLock
go
(\lk ->
Stack.Build.build
(const (return ()))
lk
defaultBuildOptsCLI
{ boptsCLITargets = [ packageIdentifierText
(either
id
id
hooglePackageIdentifier)]
}))
(\(e :: ExitCode) ->
case e of
ExitSuccess -> resetExeCache menv
_ -> throwIO e))
runHoogle :: Path Abs File -> [String] -> RIO EnvConfig ()
runHoogle hooglePath hoogleArgs = do
config <- view configL
menv <- liftIO $ configEnvOverrideSettings config envSettings
dbpath <- hoogleDatabasePath
let databaseArg = ["--database=" ++ toFilePath dbpath]
withEnvOverride menv $ withProc
(toFilePath hooglePath)
(hoogleArgs ++ databaseArg)
runProcess_
bail :: RIO EnvConfig a
bail = liftIO (exitWith (ExitFailure (-1)))
checkDatabaseExists = do
path <- hoogleDatabasePath
liftIO (doesFileExist path)
ensureHoogleInPath :: RIO EnvConfig (Path Abs File)
ensureHoogleInPath = do
config <- view configL
menv <- liftIO $ configEnvOverrideSettings config envSettings
mhooglePath <- findExecutable menv "hoogle"
eres <- case mhooglePath of
Nothing -> return $ Left "Hoogle isn't installed."
Just hooglePath -> do
result <- withEnvOverride menv
$ withProc (toFilePath hooglePath) ["--numeric-version"]
$ tryAny . readProcessStdout_
let unexpectedResult got = Left $ T.concat
[ "'"
, T.pack (toFilePath hooglePath)
, " --numeric-version' did not respond with expected value. Got: "
, got
]
return $ case result of
Left err -> unexpectedResult $ T.pack (show err)
Right bs -> case parseVersionFromString (takeWhile (not . isSpace) (BL8.unpack bs)) of
Nothing -> unexpectedResult $ T.pack (BL8.unpack bs)
Just ver
| ver >= hoogleMinVersion -> Right hooglePath
| otherwise -> Left $ T.concat
[ "Installed Hoogle is too old, "
, T.pack (toFilePath hooglePath)
, " is version "
, versionText ver
, " but >= 5.0 is required."
]
case eres of
Right hooglePath -> return hooglePath
Left err
| setup -> do
logWarn $ err <> " Automatically installing (use --no-setup to disable) ..."
installHoogle
mhooglePath' <- findExecutable menv "hoogle"
case mhooglePath' of
Just hooglePath -> return hooglePath
Nothing -> do
logWarn "Couldn't find hoogle in path after installing. This shouldn't happen, may be a bug."
bail
| otherwise -> do
logWarn $ err <> " Not installing it due to --no-setup."
bail
envSettings =
EnvSettings
{ esIncludeLocals = True
, esIncludeGhcPackagePath = True
, esStackExe = True
, esLocaleUtf8 = False
, esKeepGhcRts = False
}
|
anton-dessiatov/stack
|
src/Stack/Hoogle.hs
|
bsd-3-clause
| 8,868 | 0 | 28 | 4,060 | 1,567 | 785 | 782 | 183 | 12 |
module Foo where
{-@ LIQUID "--totality" @-}
data F a b = F {fx :: a, fy :: b} | G {fx :: a}
{-@ data F a b = F {fx :: a, fy :: b} | G {fx :: a} @-}
{-@ measure isF :: F a b -> Prop
isF (F x y) = true
isF (G x) = false
@-}
-- Record's selector type is defaulted to true as imported
{-@ fy :: {v:F a b | (isF v)} -> b @-}
{-@ bar :: {v:F a b | (isF v)} -> b @-}
bar :: F a b -> b
bar = fy
|
mightymoose/liquidhaskell
|
tests/pos/RecordSelectorError.hs
|
bsd-3-clause
| 407 | 0 | 8 | 127 | 63 | 41 | 22 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Lamdu.GUI.ExpressionEdit.HoleEdit.Open.EventMap
( make, blockDownEvents, disallowChars
) where
import Control.Applicative (Applicative(..), (<$), liftA2)
import Control.Lens.Operators
import Control.MonadA (MonadA)
import Data.List.Utils (nonEmptyAll)
import Data.Monoid (Monoid(..))
import Data.Store.Guid (Guid)
import Data.Store.Property (Property(..))
import Graphics.UI.Bottle.Widget (Widget)
import Lamdu.CharClassification (operatorChars, alphaNumericChars)
import Lamdu.Config (Config)
import Lamdu.GUI.ExpressionEdit.HoleEdit.Info (HoleInfo(..))
import Lamdu.GUI.ExpressionEdit.HoleEdit.Open.ShownResult (ShownResult(..), srPick)
import Lamdu.GUI.ExpressionEdit.HoleEdit.State (HoleState(..))
import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM)
import qualified Data.Store.Property as Property
import qualified Data.Store.Transaction as Transaction
import qualified Graphics.UI.Bottle.EventMap as E
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Lamdu.Config as Config
import qualified Lamdu.GUI.ExpressionEdit.EventMap as ExprEventMap
import qualified Lamdu.GUI.ExpressionEdit.HoleEdit.Info as HoleInfo
import qualified Lamdu.GUI.ExpressionEdit.HoleEdit.State as HoleState
import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM
import qualified Lamdu.GUI.WidgetEnvT as WE
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import qualified Lamdu.Sugar.Types as Sugar
type T = Transaction.Transaction
blockDownEvents :: Monad f => Widget f -> Widget f
blockDownEvents =
Widget.weakerEvents $
E.keyPresses
[E.ModKey E.noMods E.Key'Down]
(E.Doc ["Navigation", "Move", "down (blocked)"]) $
return mempty
closeEventMap :: MonadA m => HoleInfo m -> Widget.EventHandlers (T m)
closeEventMap holeInfo =
Widget.keysEventMapMovesCursor [E.ModKey E.noMods E.Key'Escape]
(E.Doc ["Navigation", "Hole", "Close"]) . pure $
Widget.joinId (hiId holeInfo) ["closed"]
pasteEventMap ::
Functor m => Config -> HoleInfo m -> Widget.EventHandlers (T m)
pasteEventMap config holeInfo =
maybe mempty
(Widget.keysEventMapMovesCursor
(Config.pasteKeys config) (E.Doc ["Edit", "Paste"]) .
fmap WidgetIds.fromGuid) $ hiActions holeInfo ^. Sugar.holePaste
adHocTextEditEventMap :: MonadA m => Property m String -> Widget.EventHandlers m
adHocTextEditEventMap searchTermProp =
mconcat . concat $
[ [ disallowChars (Property.value searchTermProp) .
E.simpleChars "Character"
(E.Doc ["Edit", "Search Term", "Append character"]) $
changeText . flip (++) . (: [])
]
, [ E.keyPresses (map (E.ModKey E.noMods) [E.Key'Backspace])
(E.Doc ["Edit", "Search Term", "Delete backwards"]) $
changeText init
| (not . null . Property.value) searchTermProp
]
]
where
changeText f = mempty <$ Property.pureModify searchTermProp f
disallowedHoleChars :: [(Char, E.IsShifted)]
disallowedHoleChars =
E.anyShiftedChars ",`\n() " ++
[ ('0', E.Shifted)
, ('9', E.Shifted)
]
disallowChars :: String -> E.EventMap a -> E.EventMap a
disallowChars searchTerm =
E.filterSChars (curry (`notElem` disallowedHoleChars)) .
E.deleteKey (keyPress E.Key'Space) .
E.deleteKey (keyPress E.Key'Enter) .
disallowMix
where
disallowMix
| nonEmptyAll (`notElem` operatorChars) searchTerm =
E.filterSChars (curry (`notElem` E.anyShiftedChars operatorChars))
| nonEmptyAll (`elem` operatorChars) searchTerm =
E.filterSChars (curry (`notElem` E.anyShiftedChars alphaNumericChars))
| otherwise = id
keyPress = E.KeyEvent E.Press . E.ModKey E.noMods
-- This relies on pickBefore being applied to it in the event map
-- buildup to do the actual picking
pickPlaceholderEventMap ::
MonadA m => Config -> HoleInfo m -> ShownResult m ->
Widget.EventHandlers (T m)
pickPlaceholderEventMap config holeInfo shownResult =
-- TODO: Does this guid business make sense?
case hiHoleGuids holeInfo ^. ExprGuiM.hgMNextHole of
Just nextHoleGuid | holeResultHasHoles ->
mappend
(simplePickRes (Config.pickResultKeys config))
(pickAndMoveToNextHole nextHoleGuid)
_ ->
simplePickRes $
Config.pickResultKeys config ++
Config.pickAndMoveToNextHoleKeys config
where
pickAndMoveToNextHole nextHoleGuid =
Widget.keysEventMapMovesCursor
(Config.pickAndMoveToNextHoleKeys config)
(E.Doc ["Edit", "Result", "Pick and move to next hole"]) .
return $ WidgetIds.fromGuid nextHoleGuid
holeResultHasHoles = not $ srHoleResult shownResult ^. Sugar.holeResultHasHoles
simplePickRes keys = Widget.keysEventMap keys (E.Doc ["Edit", "Result", "Pick"]) $ return ()
setNextHoleState ::
MonadA m =>
String -> (Maybe Guid, Widget.EventResult) -> T m Widget.EventResult
setNextHoleState _ (Nothing, eventResult) = return eventResult
setNextHoleState searchTerm (Just newHoleGuid, eventResult) =
eventResult <$
Transaction.setP (HoleState.assocStateRef newHoleGuid)
(HoleState searchTerm)
alphaNumericAfterOperator :: MonadA m => HoleInfo m -> ShownResult m -> Widget.EventHandlers (T m)
alphaNumericAfterOperator holeInfo shownResult
| nonEmptyAll (`elem` operatorChars) searchTerm =
E.charGroup "Letter/digit"
(E.Doc ["Edit", "Result", "Pick and resume"]) alphaNumericChars $
\c _ -> setNextHoleState [c] =<< srPickTo shownResult
| otherwise = mempty
where
searchTerm = HoleInfo.hiSearchTerm holeInfo
make ::
MonadA m =>
Sugar.Payload Sugar.Name m ExprGuiM.Payload ->
HoleInfo m -> Maybe (ShownResult m) ->
ExprGuiM m
( Widget.EventHandlers (T m)
, Widget.EventHandlers (T m)
)
make pl holeInfo mShownResult = do
config <- ExprGuiM.widgetEnv WE.readConfig
jumpHoles <- ExprEventMap.jumpHolesEventMapIfSelected [] pl
replace <- ExprEventMap.replaceOrComeToParentEventMap True pl
let
applyOp = actionsEventMap $ ExprEventMap.applyOperatorEventMap []
close = closeEventMap holeInfo
cut = actionsEventMap $ ExprEventMap.cutEventMap config
paste = pasteEventMap config holeInfo
pick = shownResultEventMap $ pickPlaceholderEventMap config holeInfo
alphaAfterOp = onShownResult $ alphaNumericAfterOperator holeInfo
fromResult = shownResultEventMap srEventMap
adHocEdit = adHocTextEditEventMap $ HoleInfo.hiSearchTermProperty holeInfo
strongEventMap =
mconcat $
jumpHoles : close : pick : alphaAfterOp :
[ applyOp | null searchTerm ]
weakEventMap =
mconcat $ concat
[ [ applyOp | not (null searchTerm) ]
, [ cut, paste, replace
-- includes overlapping events like "cut" of sub-expressions
-- (since top-level expression gets its actions cut), so put
-- at lowest precedence:
, fromResult
]
]
-- Used with weaker events, TextEdit events above:
searchTermEventMap = mappend strongEventMap weakEventMap
-- Used with stronger events, Grid events underneath:
resultsEventMap =
mconcat [ strongEventMap, adHocEdit, weakEventMap ]
pure (searchTermEventMap, resultsEventMap)
where
searchTerm = HoleInfo.hiSearchTerm holeInfo
onShownResult f = maybe mempty f mShownResult
shownResultEventMapH f shownResult = pickBefore shownResult $ f shownResult
pickBefore shownResult = fmap . liftA2 mappend $ srPick shownResult
shownResultEventMap = onShownResult . shownResultEventMapH
actionsEventMap f =
shownResultEventMap $ \shownResult ->
let
mActions =
srHoleResult shownResult ^.
Sugar.holeResultConverted . Sugar.rPayload . Sugar.plActions
in case mActions of
Nothing -> mempty
Just actions -> f actions
|
clawplach/lamdu
|
Lamdu/GUI/ExpressionEdit/HoleEdit/Open/EventMap.hs
|
gpl-3.0
| 7,660 | 0 | 17 | 1,337 | 2,081 | 1,117 | 964 | -1 | -1 |
-----------------------------------------------------------------------------
--
-- Module : Connections.Tree
-- Copyright :
-- License : AllRightsReserved
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module Connections.Tree (
treeG
) where
import Connections
import Direction
treeG :: ConnectionsGen
treeG = ConnectionsGen tree'
tree' :: Int -> Connections
tree' levels = Connections num cs
where num = 2 ^ levels - 1
cs = concatMap connections [0 .. levels - 1]
bounds :: Int -> (Int, Int)
bounds level = (fid, lid)
where fid = 2 ^ level - 1
lid = 2 ^ (level + 1) - 2
parent :: Integral a => a -> a
parent idx = (idx - 1) `div` 2
connections :: Int -> [ClusterConnection]
connections 0 = []
connections level | even level = evenConns level
| otherwise = oddConns level
evenConns :: Int -> [ClusterConnection]
evenConns level = fc : lc : parents
where [(ppfid, pplid), (fid, lid)] = map bounds [level - 2, level]
fc = (fid, ppfid, FromDown)
lc = (lid, pplid, FromDown)
connParent idx = (parent idx, idx, FromUp)
parents = map connParent [fid .. lid]
oddConns :: Int -> [ClusterConnection]
oddConns level = inLevel ++ parents
where (fid, lid) = bounds level
inLevel = (lid, fid, FromLeft) : map connLeft [fid + 1 .. lid]
parents = map connParent [fid .. lid]
connLeft idx = (idx - 1, idx, FromLeft)
connParent idx = (parent idx, idx, FromUp)
|
uvNikita/TopologyCalc
|
src/Connections/Tree.hs
|
mit
| 1,605 | 0 | 10 | 408 | 519 | 292 | 227 | 34 | 1 |
-- |
-- Module: Math.NumberTheory.Moduli.Singleton
-- Copyright: (c) 2019 Andrew Lelechenko
-- Licence: MIT
-- Maintainer: Andrew Lelechenko <[email protected]>
--
-- Singleton data types.
--
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
module Math.NumberTheory.Moduli.Singleton
( -- * SFactors singleton
SFactors
, sfactors
, someSFactors
, unSFactors
, proofFromSFactors
-- * CyclicGroup singleton
, CyclicGroup
, cyclicGroup
, cyclicGroupFromFactors
, cyclicGroupFromModulo
, proofFromCyclicGroup
, pattern CG2
, pattern CG4
, pattern CGOddPrimePower
, pattern CGDoubleOddPrimePower
-- * SFactors \<=\> CyclicGroup
, cyclicGroupToSFactors
, sfactorsToCyclicGroup
-- * Some wrapper
, Some(..)
) where
import Control.DeepSeq
import Data.Constraint
import Data.Kind
import Data.List (sort)
import qualified Data.Map as M
import Data.Proxy
#if __GLASGOW_HASKELL__ < 803
import Data.Semigroup
#endif
import GHC.Generics
import GHC.TypeNats (KnownNat, Nat, natVal)
import Numeric.Natural
import Unsafe.Coerce
import Math.NumberTheory.Roots (highestPower)
import Math.NumberTheory.Primes
import Math.NumberTheory.Primes.Types
import Math.NumberTheory.Utils.FromIntegral
-- | Wrapper to hide an unknown type-level natural.
data Some (a :: Nat -> Type) where
Some :: a m -> Some a
-- | From "Data.Constraint.Nat".
newtype Magic n = Magic (KnownNat n => Dict (KnownNat n))
-- | This singleton data type establishes a correspondence
-- between a modulo @m@ on type level
-- and its factorisation on term level.
newtype SFactors a (m :: Nat) = SFactors
{ unSFactors :: [(Prime a, Word)]
-- ^ Factors of @m@.
} deriving (Show, Generic)
instance Eq (SFactors a m) where
_ == _ = True
instance Ord (SFactors a m) where
_ `compare` _ = EQ
instance NFData a => NFData (SFactors a m)
instance Ord a => Eq (Some (SFactors a)) where
Some (SFactors xs) == Some (SFactors ys) =
xs == ys
instance Ord a => Ord (Some (SFactors a)) where
Some (SFactors xs) `compare` Some (SFactors ys) =
xs `compare` ys
instance Show a => Show (Some (SFactors a)) where
showsPrec p (Some x) = showsPrec p x
instance NFData a => NFData (Some (SFactors a)) where
rnf (Some x) = rnf x
-- | Create a singleton from a type-level positive modulo @m@,
-- passed in a constraint.
--
-- >>> :set -XDataKinds
-- >>> sfactors :: SFactors Integer 13
-- SFactors {unSFactors = [(Prime 13,1)]}
sfactors :: forall a m. (Ord a, UniqueFactorisation a, KnownNat m) => SFactors a m
sfactors = if m == 0
then error "sfactors: modulo must be positive"
else SFactors (sort (factorise m))
where
m = fromIntegral (natVal (Proxy :: Proxy m))
-- | Create a singleton from factors of @m@.
-- Factors must be distinct, as in output of 'factorise'.
--
-- >>> import Math.NumberTheory.Primes
-- >>> someSFactors (factorise 98)
-- SFactors {unSFactors = [(Prime 2,1),(Prime 7,2)]}
someSFactors :: (Ord a, Num a) => [(Prime a, Word)] -> Some (SFactors a)
someSFactors
= Some
. SFactors
-- Just a precaution against ill-formed lists of factors
. M.assocs
. M.fromListWith (+)
-- | Convert a singleton to a proof that @m@ is known. Usage example:
--
-- > toModulo :: SFactors Integer m -> Natural
-- > toModulo t = case proofFromSFactors t of Sub Dict -> natVal t
proofFromSFactors :: Integral a => SFactors a m -> (() :- KnownNat m)
proofFromSFactors (SFactors fs) = Sub $ unsafeCoerce (Magic Dict) (fromIntegral' (factorBack fs) :: Natural)
-- | This singleton data type establishes a correspondence
-- between a modulo @m@ on type level
-- and a cyclic group of the same order on term level.
data CyclicGroup a (m :: Nat)
= CG2' -- ^ Residues modulo 2.
| CG4' -- ^ Residues modulo 4.
| CGOddPrimePower' (Prime a) Word
-- ^ Residues modulo @p@^@k@ for __odd__ prime @p@.
| CGDoubleOddPrimePower' (Prime a) Word
-- ^ Residues modulo 2@p@^@k@ for __odd__ prime @p@.
deriving (Show, Generic)
instance Eq (CyclicGroup a m) where
_ == _ = True
instance Ord (CyclicGroup a m) where
_ `compare` _ = EQ
instance NFData a => NFData (CyclicGroup a m)
instance Eq a => Eq (Some (CyclicGroup a)) where
Some CG2' == Some CG2' = True
Some CG4' == Some CG4' = True
Some (CGOddPrimePower' p1 k1) == Some (CGOddPrimePower' p2 k2) =
p1 == p2 && k1 == k2
Some (CGDoubleOddPrimePower' p1 k1) == Some (CGDoubleOddPrimePower' p2 k2) =
p1 == p2 && k1 == k2
_ == _ = False
instance Ord a => Ord (Some (CyclicGroup a)) where
compare (Some x) (Some y) = case x of
CG2' -> case y of
CG2' -> EQ
_ -> LT
CG4' -> case y of
CG2' -> GT
CG4' -> EQ
_ -> LT
CGOddPrimePower' p1 k1 -> case y of
CGDoubleOddPrimePower'{} -> LT
CGOddPrimePower' p2 k2 ->
p1 `compare` p2 <> k1 `compare` k2
_ -> GT
CGDoubleOddPrimePower' p1 k1 -> case y of
CGDoubleOddPrimePower' p2 k2 ->
p1 `compare` p2 <> k1 `compare` k2
_ -> GT
instance Show a => Show (Some (CyclicGroup a)) where
showsPrec p (Some x) = showsPrec p x
instance NFData a => NFData (Some (CyclicGroup a)) where
rnf (Some x) = rnf x
-- | Create a singleton from a type-level positive modulo @m@,
-- passed in a constraint.
--
-- >>> :set -XDataKinds
-- >>> import Data.Maybe
-- >>> cyclicGroup :: Maybe (CyclicGroup Integer 169)
-- Just (CGOddPrimePower' (Prime 13) 2)
--
-- >>> :set -XTypeOperators -XNoStarIsType
-- >>> import GHC.TypeNats
-- >>> sfactorsToCyclicGroup (sfactors :: SFactors Integer 4)
-- Just CG4'
-- >>> sfactorsToCyclicGroup (sfactors :: SFactors Integer (2 * 13 ^ 3))
-- Just (CGDoubleOddPrimePower' (Prime 13) 3)
-- >>> sfactorsToCyclicGroup (sfactors :: SFactors Integer (4 * 13))
-- Nothing
cyclicGroup
:: forall a m.
(Integral a, UniqueFactorisation a, KnownNat m)
=> Maybe (CyclicGroup a m)
cyclicGroup = fromModuloInternal m
where
m = fromIntegral (natVal (Proxy :: Proxy m))
-- | Create a singleton from factors.
-- Factors must be distinct, as in output of 'factorise'.
cyclicGroupFromFactors
:: (Eq a, Num a)
=> [(Prime a, Word)]
-> Maybe (Some (CyclicGroup a))
cyclicGroupFromFactors = \case
[(unPrime -> 2, 1)] -> Just $ Some CG2'
[(unPrime -> 2, 2)] -> Just $ Some CG4'
[(unPrime -> 2, _)] -> Nothing
[(p, k)] -> Just $ Some $ CGOddPrimePower' p k
[(unPrime -> 2, 1), (p, k)] -> Just $ Some $ CGDoubleOddPrimePower' p k
[(p, k), (unPrime -> 2, 1)] -> Just $ Some $ CGDoubleOddPrimePower' p k
_ -> Nothing
-- | Similar to 'cyclicGroupFromFactors' . 'factorise',
-- but much faster, because it
-- but performes only one primality test instead of full
-- factorisation.
cyclicGroupFromModulo
:: (Integral a, UniqueFactorisation a)
=> a
-> Maybe (Some (CyclicGroup a))
cyclicGroupFromModulo = fmap Some . fromModuloInternal
fromModuloInternal
:: (Integral a, UniqueFactorisation a)
=> a
-> Maybe (CyclicGroup a m)
fromModuloInternal = \case
2 -> Just CG2'
4 -> Just CG4'
n
| even n -> uncurry CGDoubleOddPrimePower' <$> isOddPrimePower (n `div` 2)
| otherwise -> uncurry CGOddPrimePower' <$> isOddPrimePower n
isOddPrimePower
:: (Integral a, UniqueFactorisation a)
=> a
-> Maybe (Prime a, Word)
isOddPrimePower n
| even n = Nothing
| otherwise = (, k) <$> isPrime p
where
(p, k) = highestPower n
-- | Convert a cyclic group to a proof that @m@ is known. Usage example:
--
-- > toModulo :: CyclicGroup Integer m -> Natural
-- > toModulo t = case proofFromCyclicGroup t of Sub Dict -> natVal t
proofFromCyclicGroup :: Integral a => CyclicGroup a m -> (() :- KnownNat m)
proofFromCyclicGroup = proofFromSFactors . cyclicGroupToSFactors
-- | Check whether a multiplicative group of residues,
-- characterized by its modulo, is cyclic and, if yes, return its form.
--
-- >>> :set -XTypeOperators -XNoStarIsType
-- >>> import GHC.TypeNats
-- >>> sfactorsToCyclicGroup (sfactors :: SFactors Integer 4)
-- Just CG4'
-- >>> sfactorsToCyclicGroup (sfactors :: SFactors Integer (2 * 13 ^ 3))
-- Just (CGDoubleOddPrimePower' (Prime 13) 3)
-- >>> sfactorsToCyclicGroup (sfactors :: SFactors Integer (4 * 13))
-- Nothing
sfactorsToCyclicGroup :: (Eq a, Num a) => SFactors a m -> Maybe (CyclicGroup a m)
sfactorsToCyclicGroup (SFactors fs) = case fs of
[(unPrime -> 2, 1)] -> Just CG2'
[(unPrime -> 2, 2)] -> Just CG4'
[(unPrime -> 2, _)] -> Nothing
[(p, k)] -> Just $ CGOddPrimePower' p k
[(p, k), (unPrime -> 2, 1)] -> Just $ CGDoubleOddPrimePower' p k
[(unPrime -> 2, 1), (p, k)] -> Just $ CGDoubleOddPrimePower' p k
_ -> Nothing
-- | Invert 'sfactorsToCyclicGroup'.
--
-- >>> import Data.Maybe
-- >>> cyclicGroupToSFactors (fromJust (sfactorsToCyclicGroup (sfactors :: SFactors Integer 4)))
-- SFactors {unSFactors = [(Prime 2,2)]}
cyclicGroupToSFactors :: Num a => CyclicGroup a m -> SFactors a m
cyclicGroupToSFactors = SFactors . \case
CG2' -> [(Prime 2, 1)]
CG4' -> [(Prime 2, 2)]
CGOddPrimePower' p k -> [(p, k)]
CGDoubleOddPrimePower' p k -> [(Prime 2, 1), (p, k)]
-- | Unidirectional pattern for residues modulo 2.
pattern CG2 :: CyclicGroup a m
pattern CG2 <- CG2'
-- | Unidirectional pattern for residues modulo 4.
pattern CG4 :: CyclicGroup a m
pattern CG4 <- CG4'
-- | Unidirectional pattern for residues modulo @p@^@k@ for __odd__ prime @p@.
pattern CGOddPrimePower :: Prime a -> Word -> CyclicGroup a m
pattern CGOddPrimePower p k <- CGOddPrimePower' p k
-- | Unidirectional pattern for residues modulo 2@p@^@k@ for __odd__ prime @p@.
pattern CGDoubleOddPrimePower :: Prime a -> Word -> CyclicGroup a m
pattern CGDoubleOddPrimePower p k <- CGDoubleOddPrimePower' p k
#if __GLASGOW_HASKELL__ > 801
{-# COMPLETE CG2, CG4, CGOddPrimePower, CGDoubleOddPrimePower #-}
#endif
|
Bodigrim/arithmoi
|
Math/NumberTheory/Moduli/Singleton.hs
|
mit
| 10,232 | 0 | 14 | 2,136 | 2,610 | 1,411 | 1,199 | 188 | 7 |
module Graphics.Rendering.WebGL.Raw (
module Graphics.Rendering.WebGL.Types,
module Graphics.Rendering.WebGL.Raw
) where
import GHCJS.Types
import Data.Word
import Data.Int
import GHCJS.TypedArray (TypedArray, ArrayBufferView)
import Graphics.Rendering.WebGL.Types
-- | [WebGLHandlesContextLoss] WebGLContextAttributes? getContextAttributes();
foreign import javascript unsafe "$1['getContextAttributes']();"
js_getContextAttributes :: WebGLContext -> IO WebGLContextAttributes
-- | [WebGLHandlesContextLoss] boolean isContextLost();
foreign import javascript unsafe "$1['isContextLost']();"
js_isContextLost :: WebGLContext -> IO Bool
-- | sequence<DOMString>? getSupportedExtensions();
foreign import javascript unsafe "$1['getSupportedExtensions']();"
js_getSupportedExtensions :: WebGLContext -> IO (JSArray JSString)
-- | object? getExtension(DOMString name);
foreign import javascript unsafe "$2['getExtension']($1);"
js_getExtension :: JSString -> WebGLContext -> IO WebGLExtension
-- | void activeTexture(GLenum texture);
foreign import javascript unsafe "$2['activeTexture']($1);"
js_activeTexture :: GLenum -> WebGLContext -> IO ()
-- | void attachShader(WebGLProgram? program, WebGLShader? shader);
foreign import javascript unsafe "$3['attachShader']($1, $2);"
js_attachShader :: WebGLProgram -> WebGLShader a -> WebGLContext -> IO ()
-- | void bindAttribLocation(WebGLProgram? program, GLuint index, DOMString name);
foreign import javascript unsafe "$4['bindAttribLocation']($1, $2, $3);"
js_bindAttribLocation :: WebGLProgram -> GLuint -> JSString -> WebGLContext -> IO ()
-- | void bindBuffer(GLenum target, WebGLBuffer? buffer);
foreign import javascript unsafe "$3['bindBuffer']($1, $2);"
js_bindBuffer :: GLenum -> WebGLBuffer -> WebGLContext -> IO ()
-- | void bindFramebuffer(GLenum target, WebGLFramebuffer? framebuffer);
foreign import javascript unsafe "$3['bindFramebuffer']($1, $2);"
js_bindFramebuffer :: GLenum -> WebGLFramebuffer -> WebGLContext -> IO ()
-- | void bindRenderbuffer(GLenum target, WebGLRenderbuffer? renderbuffer);
foreign import javascript unsafe "$3['bindRenderbuffer']($1, $2);"
js_bindRenderbuffer :: GLenum -> WebGLRenderbuffer -> WebGLContext -> IO ()
-- | void bindTexture(GLenum target, WebGLTexture? texture);
foreign import javascript unsafe "$3['bindTexture']($1, $2);"
js_bindTexture :: GLenum -> WebGLTexture -> WebGLContext -> IO ()
-- | void bindTexture(GLenum target, null);
foreign import javascript unsafe "$2['bindTexture']($1, null);"
js_unbindTexture :: GLenum -> WebGLContext -> IO ()
-- | void blendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
foreign import javascript unsafe "$2['blendColor']($1[0], $1[1], $1[2], $1[3]);"
js_blendColor :: TypedArray Float -> WebGLContext -> IO ()
-- | void blendEquation(GLenum mode);
foreign import javascript unsafe "$2['blendEquation']($1);"
js_blendEquation :: GLenum -> WebGLContext -> IO ()
-- | void blendEquationSeparate(GLenum modeRGB, GLenum modeAlpha);
foreign import javascript unsafe "$3['blendEquationSeparate']($1, $2);"
js_blendEquationSeparate :: GLenum -> GLenum -> WebGLContext -> IO ()
-- | void blendFunc(GLenum sfactor, GLenum dfactor);
foreign import javascript unsafe "$3['blendFunc']($1, $2);"
js_blendFunc :: GLenum -> GLenum -> WebGLContext -> IO ()
-- | void blendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
foreign import javascript unsafe "$5['blendFuncSeparate']($1, $2, $3, $4);"
js_blendFuncSeparate :: GLenum -> GLenum -> GLenum -> GLenum -> WebGLContext -> IO ()
-- | void bufferData(GLenum target, GLsizeiptr size, GLenum usage);
foreign import javascript unsafe "$4['bufferData']($1, $2, $3);"
js_bufferData_empty :: GLenum -> GLsizeiptr -> GLenum -> WebGLContext -> IO ()
-- | void bufferData(GLenum target, ArrayBufferView data, GLenum usage);
-- | void bufferData(GLenum target, ArrayBuffer? data, GLenum usage);
foreign import javascript unsafe "$4['bufferData']($1, $2, $3);"
js_bufferData :: GLenum -> TypedArray a -> GLenum -> WebGLContext -> IO ()
-- | void bufferSubData(GLenum target, GLintptr offset, ArrayBufferView data);
-- | void bufferSubData(GLenum target, GLintptr offset, ArrayBuffer? data);
foreign import javascript unsafe "$4['bufferSubData']($1, $2, $3);"
js_bufferSubData :: GLenum -> GLintptr -> TypedArray a -> WebGLContext -> IO ()
-- | [WebGLHandlesContextLoss] GLenum checkFramebufferStatus(GLenum target);
foreign import javascript unsafe "$2['checkFramebufferStatus']($1);"
js_checkFramebufferStatus :: GLenum -> WebGLContext -> IO GLenum
-- | void clear(GLbitfield mask);
foreign import javascript unsafe "$2['clear']($1);"
js_clear :: GLbitfield -> WebGLContext -> IO ()
-- | void clearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
foreign import javascript unsafe "$2['clearColor']($1[0], $1[1], $1[2], $1[3]);"
js_clearColor :: TypedArray Float -> WebGLContext -> IO ()
-- | void clearDepth(GLclampf depth);
foreign import javascript unsafe "$2['clearDepth']($1);"
js_clearDepth :: GLfloat -> WebGLContext -> IO ()
-- | void clearStencil(GLint s);
foreign import javascript unsafe "$2['clearStencil']($1);"
js_clearStencil :: GLint -> WebGLContext -> IO ()
-- | void colorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
foreign import javascript unsafe "$5['colorMask']($1, $2, $3, $4);"
js_colorMask :: GLboolean -> GLboolean -> GLboolean -> GLboolean -> WebGLContext -> IO ()
-- | void compileShader(WebGLShader? shader);
foreign import javascript unsafe "$2['compileShader']($1);"
js_compileShader :: WebGLShader a -> WebGLContext -> IO ()
{- default WebGL doesn't support compressed textures I think, so skipping these for now
-- | void compressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, ArrayBufferView data);
foreign import javascript unsafe "$8['compressedTexImage2D']($1, $2, $3, $4, $5, $6, $7);"
js_compressedTexImage2D :: GLenum -> GLint -> GLenum -> GLsizei -> GLsizei -> GLint -> ArrayBufferView -> WebGLContext -> IO ()
-- | void compressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, ArrayBufferView data);
foreign import javascript unsafe "$9['compressedTexSubImage2D']($1, $2, $3, $4, $5, $6, $7, $8);"
js_compressedTexSubImage2D :: GLenum -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> GLenum -> ArrayBufferView -> WebGLContext -> IO ()
-}
-- | void copyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
foreign import javascript unsafe "$9['copyTexImage2D']($1, $2, $3, $4, $5, $6, $7, $8);"
js_copyTexImage2D :: GLenum -> GLint -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> GLint -> WebGLContext -> IO ()
-- | void copyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
foreign import javascript unsafe "$9['copyTexSubImage2D']($1, $2, $3, $4, $5, $6, $7, $8);"
js_copyTexSubImage2D :: GLenum -> GLint -> GLint -> GLint -> GLint -> GLint -> GLsizei -> GLsizei -> WebGLContext -> IO ()
-- | WebGLBuffer? createBuffer();
foreign import javascript unsafe "$1['createBuffer']()"
js_createBuffer :: WebGLContext -> IO WebGLBuffer
-- | WebGLFramebuffer? createFramebuffer();
foreign import javascript unsafe "$1['createFramebuffer']()"
js_createFramebuffer :: WebGLContext -> IO WebGLFramebuffer
-- | WebGLProgram? createProgram();
foreign import javascript unsafe "$1['createProgram']()"
js_createProgram :: WebGLContext -> IO WebGLProgram
-- | WebGLRenderbuffer? createRenderbuffer();
foreign import javascript unsafe "$1['createRenderbuffer']()"
js_createRenderbuffer :: WebGLContext -> IO WebGLRenderbuffer
-- | WebGLShader? createShader(GLenum type);
foreign import javascript unsafe "$2['createShader']($1)"
js_createShader :: GLenum -> WebGLContext -> IO (WebGLShader a)
-- | WebGLTexture? createTexture();
foreign import javascript unsafe "$1['createTexture']()"
js_createTexture :: WebGLContext -> IO WebGLTexture
-- | void cullFace(GLenum mode);
foreign import javascript unsafe "$2['cullFace']($1);"
js_cullFace :: GLenum -> WebGLContext -> IO ()
-- | void deleteBuffer(WebGLBuffer? buffer);
foreign import javascript unsafe "$2['deleteBuffer']($1)"
js_deleteBuffer :: WebGLBuffer -> WebGLContext -> IO ()
-- | void deleteFramebuffer(WebGLFramebuffer? framebuffer);
foreign import javascript unsafe "$2['deleteFramebuffer']($1)"
js_deleteFramebuffer :: WebGLFramebuffer -> WebGLContext -> IO ()
-- | void deleteProgram(WebGLProgram? program);
foreign import javascript unsafe "$2['deleteProgram']($1)"
js_deleteProgram :: WebGLProgram -> WebGLContext -> IO ()
-- | void deleteRenderbuffer(WebGLRenderbuffer? renderbuffer);
foreign import javascript unsafe "$2['deleteRenderbuffer']($1)"
js_deleteRenderbuffer :: WebGLRenderbuffer -> WebGLContext -> IO ()
-- | void deleteShader(WebGLShader? shader);
foreign import javascript unsafe "$2['deleteShader']($1)"
js_deleteShader :: WebGLShader a -> WebGLContext -> IO ()
-- | void deleteTexture(WebGLTexture? texture);
foreign import javascript unsafe "$2['deleteTexture']($1)"
js_deleteTexture :: WebGLTexture -> WebGLContext -> IO ()
-- | void depthFunc(GLenum func);
foreign import javascript unsafe "$2['depthFunc']($1)"
js_depthFunc :: GLenum -> WebGLContext -> IO ()
-- | void depthMask(GLboolean flag);
foreign import javascript unsafe "$2['depthMask']($1)"
js_depthMask :: GLboolean -> WebGLContext -> IO ()
-- | void depthRange(GLclampf zNear, GLclampf zFar);
foreign import javascript unsafe "$3['depthRange']($1, $2)"
js_depthRange :: GLfloat -> GLfloat -> WebGLContext -> IO ()
-- | void detachShader(WebGLProgram? program, WebGLShader? shader);
foreign import javascript unsafe "$2['detachShader']($1)"
js_detachShader :: WebGLProgram -> WebGLShader a -> WebGLContext -> IO ()
-- | void disable(GLenum cap);
foreign import javascript unsafe "$2['disable']($1);"
js_disable :: GLenum -> WebGLContext -> IO ()
-- | void disableVertexAttribArray(GLuint index);
foreign import javascript unsafe "$2['disableVertexAttribArray']($1)"
js_disableVertexAttribArray :: GLuint -> WebGLContext -> IO ()
-- | void drawArrays(GLenum mode, GLint first, GLsizei count);
foreign import javascript unsafe "$4['drawArrays']($1, $2, $3);"
js_drawArrays :: GLenum -> GLint -> GLsizei -> WebGLContext -> IO ()
-- | void drawElements(GLenum mode, GLsizei count, GLenum type, GLintptr offset);
foreign import javascript unsafe "$5['drawElements']($1, $2, $3, $4);"
js_drawElements :: GLenum -> GLsizei -> GLenum -> GLintptr -> WebGLContext -> IO ()
-- | void enable(GLenum cap);
foreign import javascript unsafe "$2['enable']($1);"
js_enable :: GLenum -> WebGLContext -> IO ()
-- | void enableVertexAttribArray(GLuint index);
foreign import javascript unsafe "$2['enableVertexAttribArray']($1);"
js_enableVertexAttribArray :: GLuint -> WebGLContext -> IO ()
-- | void finish();
foreign import javascript unsafe "$1['finish']();"
js_finish :: WebGLContext -> IO ()
-- | void flush();
foreign import javascript unsafe "$1['flush']();"
js_flush :: WebGLContext -> IO ()
-- | void framebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, WebGLRenderbuffer? renderbuffer);
foreign import javascript unsafe "$5['framebufferRenderbuffer']($1, $2, $3, $4);"
js_framebufferRenderbuffer :: GLenum -> GLenum -> GLenum -> WebGLRenderbuffer -> WebGLContext -> IO ()
-- | void framebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, WebGLTexture? texture, GLint level);
foreign import javascript unsafe "$6['framebufferTexture2D']($1, $2, $3, $4, $5);"
js_framebufferTexture2D :: GLenum -> GLenum -> GLenum -> WebGLTexture -> GLint -> WebGLContext -> IO ()
-- | void frontFace(GLenum mode);
foreign import javascript unsafe "$2['frontFace']($1);"
js_frontFace :: GLenum -> WebGLContext -> IO ()
-- | void generateMipmap(GLenum target);
foreign import javascript unsafe "$2['generateMipmap']($1);"
js_generateMipmap :: GLenum -> WebGLContext -> IO ()
-- | WebGLActiveInfo? getActiveAttrib(WebGLProgram? program, GLuint index);
foreign import javascript unsafe "$3['getActiveAttrib']($1, $2);"
js_getActiveAttrib :: WebGLProgram -> GLuint -> WebGLContext -> IO WebGLActiveInfo
-- | WebGLActiveInfo? getActiveUniform(WebGLProgram? program, GLuint index);
foreign import javascript unsafe "$3['getActiveUniform']($1, $2);"
js_getActiveUniform :: WebGLProgram -> GLuint -> WebGLContext -> IO WebGLActiveInfo
-- | sequence<WebGLShader>? getAttachedShaders(WebGLProgram? program);
foreign import javascript unsafe "$2['getAttachedShaders']($1);"
js_getAttachedShaders :: WebGLProgram -> WebGLContext -> IO (JSArray (WebGLShader ()))
-- | [WebGLHandlesContextLoss] GLint getAttribLocation(WebGLProgram? program, DOMString name);
foreign import javascript unsafe "$3['getAttribLocation']($1, $2)"
js_getAttribLocation :: WebGLProgram -> JSString -> WebGLContext -> IO GLint
-- | any getBufferParameter(GLenum target, GLenum pname);
foreign import javascript unsafe "$2['getBufferParameter']($1, $2['BUFFER_SIZE'])"
js_getBufferSize :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getBufferParameter']($1, $2['BUFFER_USAGE'])"
js_getBufferUsage :: GLenum -> WebGLContext -> IO GLenum
-- | any getParameter(GLenum pname);
-- this is so terrible
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_GLboolean :: GLenum -> WebGLContext -> IO GLboolean
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_GLenum :: GLenum -> WebGLContext -> IO GLenum
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_GLuint :: GLenum -> WebGLContext -> IO GLuint
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_GLint :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_GLfloat :: GLenum -> WebGLContext -> IO GLfloat
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_string :: GLenum -> WebGLContext -> IO JSString
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_GLbooleanArray :: GLenum -> WebGLContext -> IO (JSArray GLboolean)
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_Uint32Array :: GLenum -> WebGLContext -> IO (TypedArray Word32)
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_Int32Array :: GLenum -> WebGLContext -> IO (TypedArray Int32)
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_Float32Array :: GLenum -> WebGLContext -> IO (TypedArray Float)
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_buffer :: GLenum -> WebGLContext -> IO WebGLBuffer
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_framebuffer :: GLenum -> WebGLContext -> IO WebGLFramebuffer
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_renderbuffer :: GLenum -> WebGLContext -> IO WebGLRenderbuffer
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_program :: GLenum -> WebGLContext -> IO WebGLProgram
foreign import javascript unsafe "$2['getParameter']($1)" js_getParameter_texture :: GLenum -> WebGLContext -> IO WebGLTexture
-- | [WebGLHandlesContextLoss] GLenum getError();
foreign import javascript unsafe "$1['getError']();"
js_getError :: WebGLContext -> IO GLenum
-- | any getFramebufferAttachmentParameter(GLenum target, GLenum attachment, GLenum pname);
foreign import javascript unsafe "$3['getFramebufferAttachmentParameter']($1, $2, $3['FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE'])"
js_getFramebufferAttachmentParameter_objType :: GLenum -> GLenum -> WebGLContext -> IO GLint
-- foreign import javascript unsafe "$3['getFramebufferAttachmentParameter']($1, $2, $3['FRAMEBUFFER_ATTACHMENT_OBJECT_NAME'])"
-- js_getFramebufferAttachmentParameter_objName :: GLenum -> GLenum -> WebGLContext -> IO ??
-- this can be either a WebGLRenderbuffer or WebGLTexture apparently?
foreign import javascript unsafe "$3['getFramebufferAttachmentParameter']($1, $2, $3['FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL'])"
js_getFramebufferAttachmentParameter_texLevel :: GLenum -> GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$3['getFramebufferAttachmentParameter']($1, $2, $3['FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE'])"
js_getFramebufferAttachmentParameter_cubeFace :: GLenum -> GLenum -> WebGLContext -> IO GLint
-- | any getProgramParameter(WebGLProgram? program, GLenum pname);
foreign import javascript unsafe "$2['getProgramParameter']($1, $2['DELETE_STATUS'])"
js_getProgramParameter_delete :: WebGLProgram -> WebGLContext -> IO GLboolean
foreign import javascript unsafe "$2['getProgramParameter']($1, $2['LINK_STATUS'])"
js_getProgramParameter_link :: WebGLProgram -> WebGLContext -> IO GLboolean
foreign import javascript unsafe "$2['getProgramParameter']($1, $2['VALIDATE_STATUS'])"
js_getProgramParameter_validate :: WebGLProgram -> WebGLContext -> IO GLboolean
foreign import javascript unsafe "$2['getProgramParameter']($1, $2['ATTACHED_SHADERS'])"
js_getProgramParameter_shaders :: WebGLProgram -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getProgramParameter']($1, $2['ATTACHED_ATTRIBUTES'])"
js_getProgramParameter_attributes :: WebGLProgram -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getProgramParameter']($1, $2['ATTACHED_UNIFORMS'])"
js_getProgramParameter_uniforms :: WebGLProgram -> WebGLContext -> IO GLint
-- | DOMString? getProgramInfoLog(WebGLProgram? program);
foreign import javascript unsafe "$2['getProgramInfoLog']($1)"
js_getProgramInfoLog :: WebGLProgram -> WebGLContext -> IO JSString
-- | any getRenderbufferParameter(GLenum target, GLenum pname);
foreign import javascript unsafe "$2['getRenderbufferParameter']($1, $2['RENDERBUFFER_WIDTH'])"
js_getRenderbufferParameter_width :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getRenderbufferParameter']($1, $2['RENDERBUFFER_HEIGHT'])"
js_getRenderbufferParameter_height :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getRenderbufferParameter']($1, $2['RENDERBUFFER_RED_SIZE'])"
js_getRenderbufferParameter_redSize :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getRenderbufferParameter']($1, $2['RENDERBUFFER_GREEN_SIZE'])"
js_getRenderbufferParameter_greenSize :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getRenderbufferParameter']($1, $2['RENDERBUFFER_BLUE_SIZE'])"
js_getRenderbufferParameter_blueSize :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getRenderbufferParameter']($1, $2['RENDERBUFFER_ALPHA_SIZE'])"
js_getRenderbufferParameter_alphaSize :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getRenderbufferParameter']($1, $2['RENDERBUFFER_DEPTH_SIZE'])"
js_getRenderbufferParameter_depthSize :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getRenderbufferParameter']($1, $2['RENDERBUFFER_STENCIL_SIZE'])"
js_getRenderbufferParameter_stencilSize :: GLenum -> WebGLContext -> IO GLint
foreign import javascript unsafe "$2['getRenderbufferParameter']($1, $2['RENDERBUFFER_INTERNAL_FORMAT'])"
js_getRenderbufferParameter_format :: GLenum -> WebGLContext -> IO GLenum
-- | any getShaderParameter(WebGLShader? shader, GLenum pname);
foreign import javascript unsafe "$2['getShaderParameter']($1, $2['SHADER_TYPE'])"
js_getShaderParameter_shaderType :: WebGLShader a -> WebGLContext -> IO GLenum
foreign import javascript unsafe "$2['getShaderParameter']($1, $2['DELETE_STATUS'])"
js_getShaderParameter_deleteStatus :: WebGLShader a -> WebGLContext -> IO GLboolean
foreign import javascript unsafe "$2['getShaderParameter']($1, $2['COMPILE_STATUS'])"
js_getShaderParameter_compileStatus :: WebGLShader a -> WebGLContext -> IO GLboolean
-- | WebGLShaderPrecisionFormat? getShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype);
foreign import javascript unsafe "$3['getShaderPrecisionFormat']($1, $2)"
js_getShaderPrecisionFormat :: GLenum -> GLenum -> WebGLContext -> IO WebGLShaderPrecisionFormat
-- | DOMString? getShaderInfoLog(WebGLShader? shader);
foreign import javascript unsafe "$2['getShaderInfoLog']($1)"
js_getShaderInfoLog :: WebGLShader a -> WebGLContext -> IO JSString
-- | DOMString? getShaderSource(WebGLShader? shader);
foreign import javascript unsafe "$2['getShaderSource']($1)"
js_getShaderSource :: WebGLShader a -> WebGLContext -> IO JSString
-- | any getTexParameter(GLenum target, GLenum pname);
foreign import javascript unsafe "$2['getTexParameter']($1, $2['TEXTURE_MAG_FILTER'])"
js_getTexParameter_magFilter :: GLenum -> WebGLContext -> IO GLenum
foreign import javascript unsafe "$2['getTexParameter']($1, $2['TEXTURE_MIN_FILTER'])"
js_getTexParameter_minFilter :: GLenum -> WebGLContext -> IO GLenum
foreign import javascript unsafe "$2['getTexParameter']($1, $2['TEXTURE_WRAP_S'])"
js_getTexParameter_wrapS :: GLenum -> WebGLContext -> IO GLenum
foreign import javascript unsafe "$2['getTexParameter']($1, $2['TEXTURE_WRAP_T'])"
js_getTexParameter_wrapT :: GLenum -> WebGLContext -> IO GLenum
-- | any getUniform(WebGLProgram? program, WebGLUniformLocation? location);
foreign import javascript unsafe "$3['getUniform']($1, $2)"
js_getUniform :: WebGLProgram -> WebGLUniformLocation -> WebGLContext -> IO WebGLUniformValue
-- | WebGLUniformLocation? getUniformLocation(WebGLProgram? program, DOMString name);
foreign import javascript unsafe "$3['getUniformLocation']($1, $2)"
js_getUniformLocation :: WebGLProgram -> JSString -> WebGLContext -> IO WebGLUniformLocation
-- | any getVertexAttrib(GLuint index, GLenum pname);
-- | [WebGLHandlesContextLoss] GLsizeiptr getVertexAttribOffset(GLuint index, GLenum pname);
foreign import javascript unsafe "$3['getVertexAttribOffset']($1, $2)"
js_getVertexAttribOffset :: GLuint -> GLenum -> WebGLContext -> IO GLsizeiptr
-- | void hint(GLenum target, GLenum mode);
foreign import javascript unsafe "$3['hint']($1, $2);"
js_hint :: GLenum -> GLenum -> WebGLContext -> IO ()
-- | [WebGLHandlesContextLoss] GLboolean isBuffer(WebGLBuffer? buffer);
foreign import javascript unsafe "$2['isBuffer']($1)"
js_isBuffer :: WebGLBuffer -> WebGLContext -> IO Bool
-- | [WebGLHandlesContextLoss] GLboolean isEnabled(GLenum cap);
foreign import javascript unsafe "$2['isEnabled']($1)"
js_isEnabled :: GLenum -> WebGLContext -> IO Bool
-- | [WebGLHandlesContextLoss] GLboolean isFramebuffer(WebGLFramebuffer? framebuffer);
foreign import javascript unsafe "$2['isFramebuffer']($1)"
js_isFramebuffer :: WebGLFramebuffer -> WebGLContext -> IO Bool
-- | [WebGLHandlesContextLoss] GLboolean isProgram(WebGLProgram? program);
foreign import javascript unsafe "$2['isProgram']($1)"
js_isProgram :: WebGLProgram -> WebGLContext -> IO Bool
-- | [WebGLHandlesContextLoss] GLboolean isRenderbuffer(WebGLRenderbuffer? renderbuffer);
foreign import javascript unsafe "$2['isRenderbuffer']($1)"
js_isRenderbuffer :: WebGLRenderbuffer -> WebGLContext -> IO Bool
-- | [WebGLHandlesContextLoss] GLboolean isShader(WebGLShader? shader);
foreign import javascript unsafe "$2['isShader']($1)"
js_isShader :: WebGLShader t -> WebGLContext -> IO Bool
-- | [WebGLHandlesContextLoss] GLboolean isTexture(WebGLTexture? texture);
foreign import javascript unsafe "$2['isTexture']($1)"
js_isTexture :: WebGLTexture -> WebGLContext -> IO Bool
-- | void lineWidth(GLfloat width);
foreign import javascript unsafe "$2['lineWidth']($1);"
js_lineWidth :: GLfloat -> WebGLContext -> IO ()
-- | void linkProgram(WebGLProgram? program);
foreign import javascript unsafe "$2['linkProgram']($1);"
js_linkProgram :: WebGLProgram -> WebGLContext -> IO ()
-- | void pixelStorei(GLenum pname, GLint param);
foreign import javascript unsafe "$3['pixelStorei']($1, $2);"
js_pixelStorei :: GLenum -> GLint -> WebGLContext -> IO ()
-- foreign import javascript unsafe "$3['pixelStorei']($1, $2 ? 1 : 0);"
-- js_pixelStorei_bool :: GLenum -> GLboolean -> WebGLContext -> IO ()
-- | void polygonOffset(GLfloat factor, GLfloat units);
foreign import javascript unsafe "$3['polygonOffset']($1, $2);"
js_polygonOffset :: GLfloat -> GLfloat -> WebGLContext -> IO ()
-- | void readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, ArrayBufferView? pixels);
-- | void renderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
-- | void sampleCoverage(GLclampf value, GLboolean invert);
-- | void scissor(GLint x, GLint y, GLsizei width, GLsizei height);
foreign import javascript unsafe "$5['scissor']($1, $2, $3, $4);"
js_scissor :: GLint -> GLint -> GLsizei -> GLsizei -> WebGLContext -> IO ()
-- | void shaderSource(WebGLShader? shader, DOMString source);
foreign import javascript unsafe "$3['shaderSource']($1, $2);"
js_shaderSource :: WebGLShader a -> JSString -> WebGLContext -> IO ()
-- | void stencilFunc(GLenum func, GLint ref, GLuint mask);
-- | void stencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask);
-- | void stencilMask(GLuint mask);
-- | void stencilMaskSeparate(GLenum face, GLuint mask);
-- | void stencilOp(GLenum fail, GLenum zfail, GLenum zpass);
-- | void stencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
-- | void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels);
-- | void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, TexImageSource? source);
foreign import javascript unsafe "$7['texImage2D']($1, $2, $3, $4, $5, $6);"
js_texImage2D :: GLenum -> GLint -> GLenum -> GLenum -> GLenum -> Image -> WebGLContext -> IO ()
-- | void texParameterf(GLenum target, GLenum pname, GLfloat param);
foreign import javascript unsafe "$4['texParameterf']($1, $2, $3);"
js_texParameterf :: GLenum -> GLenum -> GLfloat -> WebGLContext -> IO ()
-- | void texParameteri(GLenum target, GLenum pname, GLint param);
foreign import javascript unsafe "$4['texParameteri']($1, $2, $3);"
-- js_texParameteri :: GLenum -> GLenum -> GLint -> WebGLContext -> IO ()
js_texParameteri :: GLenum -> GLenum -> GLenum -> WebGLContext -> IO ()
-- foreign import javascript unsafe "$4['texParameteri']($1, $2, $3);"
-- js_texParameteri_enum :: GLenum -> GLenum -> GLenum -> WebGLContext -> IO ()
-- | void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, ArrayBufferView? pixels);
-- | void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, ImageData? pixels);
-- | void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, HTMLImageElement image); // May throw DOMException
-- | void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, HTMLCanvasElement canvas); // May throw DOMException
-- | void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, HTMLVideoElement video); // May throw DOMException
foreign import javascript unsafe "$7['texSubImage2D']($1, $2, $3, $4, $5, $6);"
js_texSubImage2D :: GLenum -> GLint -> GLint -> GLint -> GLenum -> GLenum -> Image -> WebGLContext -> IO ()
-- | void uniform1f(WebGLUniformLocation? location, GLfloat x);
foreign import javascript unsafe "$3['uniform1f']($1, $2);"
js_uniform1f :: WebGLUniformLocation -> GLfloat -> WebGLContext -> IO ()
-- | void uniform1fv(WebGLUniformLocation? location, Float32Array v);
-- | void uniform1fv(WebGLUniformLocation? location, sequence<GLfloat> v);
foreign import javascript unsafe "$3['uniform1fv']($1, $2);"
js_uniform1fv :: WebGLUniformLocation -> TypedArray Float -> WebGLContext -> IO ()
-- | void uniform1i(WebGLUniformLocation? location, GLint x);
foreign import javascript unsafe "$3['uniform1i']($1, $2);"
js_uniform1i :: WebGLUniformLocation -> GLint -> WebGLContext -> IO ()
-- | void uniform1iv(WebGLUniformLocation? location, Int32Array v);
-- | void uniform1iv(WebGLUniformLocation? location, sequence<long> v);
foreign import javascript unsafe "$3['uniform1iv']($1, $2);"
js_uniform1iv :: WebGLUniformLocation -> TypedArray Int32 -> WebGLContext -> IO ()
-- | void uniform2f(WebGLUniformLocation? location, GLfloat x, GLfloat y);
foreign import javascript unsafe "$4['uniform2f']($1, $2, $3);"
js_uniform2f :: WebGLUniformLocation -> GLfloat -> GLfloat -> WebGLContext -> IO ()
-- | void uniform2fv(WebGLUniformLocation? location, Float32Array v);
-- | void uniform2fv(WebGLUniformLocation? location, sequence<GLfloat> v);
foreign import javascript unsafe "$3['uniform2fv']($1, $2);"
js_uniform2fv :: WebGLUniformLocation -> TypedArray Float -> WebGLContext -> IO ()
-- | void uniform2i(WebGLUniformLocation? location, GLint x, GLint y);
foreign import javascript unsafe "$4['uniform2i']($1, $2, $3);"
js_uniform2i :: WebGLUniformLocation -> GLint -> GLint -> WebGLContext -> IO ()
-- | void uniform2iv(WebGLUniformLocation? location, Int32Array v);
-- | void uniform2iv(WebGLUniformLocation? location, sequence<long> v);
foreign import javascript unsafe "$3['uniform2iv']($1, $2);"
js_uniform2iv :: WebGLUniformLocation -> TypedArray Int32 -> WebGLContext -> IO ()
-- | void uniform3f(WebGLUniformLocation? location, GLfloat x, GLfloat y, GLfloat z);
foreign import javascript unsafe "$5['uniform3f']($1, $2, $3, $4);"
js_uniform3f :: WebGLUniformLocation -> GLfloat -> GLfloat -> GLfloat -> WebGLContext -> IO ()
-- | void uniform3fv(WebGLUniformLocation? location, Float32Array v);
-- | void uniform3fv(WebGLUniformLocation? location, sequence<GLfloat> v);
foreign import javascript unsafe "$3['uniform3fv']($1, $2);"
js_uniform3fv :: WebGLUniformLocation -> TypedArray Float -> WebGLContext -> IO ()
-- | void uniform3i(WebGLUniformLocation? location, GLint x, GLint y, GLint z);
foreign import javascript unsafe "$5['uniform3i']($1, $2, $3, $4);"
js_uniform3i :: WebGLUniformLocation -> GLint -> GLint -> GLint -> WebGLContext -> IO ()
-- | void uniform3iv(WebGLUniformLocation? location, Int32Array v);
-- | void uniform3iv(WebGLUniformLocation? location, sequence<long> v);
foreign import javascript unsafe "$3['uniform3iv']($1, $2);"
js_uniform3iv :: WebGLUniformLocation -> TypedArray Int32 -> WebGLContext -> IO ()
-- | void uniform4f(WebGLUniformLocation? location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
foreign import javascript unsafe "$6['uniform4f']($1, $2, $3, $4, $5);"
js_uniform4f :: WebGLUniformLocation -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> WebGLContext -> IO ()
-- | void uniform4fv(WebGLUniformLocation? location, Float32Array v);
-- | void uniform4fv(WebGLUniformLocation? location, sequence<GLfloat> v);
foreign import javascript unsafe "$3['uniform4fv']($1, $2);"
js_uniform4fv :: WebGLUniformLocation -> TypedArray Float -> WebGLContext -> IO ()
-- | void uniform4i(WebGLUniformLocation? location, GLint x, GLint y, GLint z, GLint w);
foreign import javascript unsafe "$5['uniform4i']($1, $2, $3, $4);"
js_uniform4i :: WebGLUniformLocation -> GLint -> GLint -> GLint -> GLint -> WebGLContext -> IO ()
-- | void uniform4iv(WebGLUniformLocation? location, Int32Array v);
-- | void uniform4iv(WebGLUniformLocation? location, sequence<long> v);
foreign import javascript unsafe "$3['uniform4iv']($1, $2);"
js_uniform4iv :: WebGLUniformLocation -> TypedArray Int32 -> WebGLContext -> IO ()
-- | void uniformMatrix2fv(WebGLUniformLocation? location, GLboolean transpose, Float32Array value);
-- | void uniformMatrix2fv(WebGLUniformLocation? location, GLboolean transpose, sequence<GLfloat> value);
foreign import javascript unsafe "$4['uniformMatrix2fv']($1, $2, $3);"
js_uniformMatrix2fv :: WebGLUniformLocation -> GLboolean -> TypedArray Float -> WebGLContext -> IO ()
-- | void uniformMatrix3fv(WebGLUniformLocation? location, GLboolean transpose, Float32Array value);
-- | void uniformMatrix3fv(WebGLUniformLocation? location, GLboolean transpose, sequence<GLfloat> value);
foreign import javascript unsafe "$4['uniformMatrix3fv']($1, $2, $3);"
js_uniformMatrix3fv :: WebGLUniformLocation -> GLboolean -> TypedArray Float -> WebGLContext -> IO ()
-- | void uniformMatrix4fv(WebGLUniformLocation? location, GLboolean transpose, Float32Array value);
-- | void uniformMatrix4fv(WebGLUniformLocation? location, GLboolean transpose, sequence<GLfloat> value);
foreign import javascript unsafe "$4['uniformMatrix4fv']($1, $2, $3);"
js_uniformMatrix4fv :: WebGLUniformLocation -> GLboolean -> TypedArray Float -> WebGLContext -> IO ()
-- | void useProgram(WebGLProgram? program);
foreign import javascript unsafe "$2['useProgram']($1);"
js_useProgram :: WebGLProgram -> WebGLContext -> IO ()
-- | void validateProgram(WebGLProgram? program);
foreign import javascript unsafe "$2['validateProgram']($1);"
js_validateProgram :: WebGLProgram -> WebGLContext -> IO ()
-- | void vertexAttrib1f(GLuint indx, GLfloat x);
foreign import javascript unsafe "$3['vertexAttrib1f']($1, $2);"
js_vertexAttrib1f :: GLuint -> GLfloat -> WebGLContext -> IO ()
-- | void vertexAttrib1fv(GLuint indx, Float32Array values);
-- | void vertexAttrib1fv(GLuint indx, sequence<GLfloat> values);
foreign import javascript unsafe "$3['vertexAttrib1fv']($1, $2);"
js_vertexAttrib1fv :: GLuint -> TypedArray Float -> WebGLContext -> IO ()
-- | void vertexAttrib2f(GLuint indx, GLfloat x, GLfloat y);
foreign import javascript unsafe "$4['vertexAttrib2f']($1, $2, $3);"
js_vertexAttrib2f :: GLuint -> GLfloat -> GLfloat -> WebGLContext -> IO ()
-- | void vertexAttrib2fv(GLuint indx, Float32Array values);
-- | void vertexAttrib2fv(GLuint indx, sequence<GLfloat> values);
foreign import javascript unsafe "$3['vertexAttrib2fv']($1, $2);"
js_vertexAttrib2fv :: GLuint -> TypedArray Float -> WebGLContext -> IO ()
-- | void vertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z);
foreign import javascript unsafe "$5['vertexAttrib3f']($1, $2, $3, $4);"
js_vertexAttrib3f :: GLuint -> GLfloat -> GLfloat -> GLfloat -> WebGLContext -> IO ()
-- | void vertexAttrib3fv(GLuint indx, Float32Array values);
-- | void vertexAttrib3fv(GLuint indx, sequence<GLfloat> values);
foreign import javascript unsafe "$3['vertexAttrib3fv']($1, $2);"
js_vertexAttrib3fv :: GLuint -> TypedArray Float -> WebGLContext -> IO ()
-- | void vertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
foreign import javascript unsafe "$6['vertexAttrib4f']($1, $2, $3, $4, $5);"
js_vertexAttrib4f :: GLuint -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> WebGLContext -> IO ()
-- | void vertexAttrib4fv(GLuint indx, Float32Array values);
-- | void vertexAttrib4fv(GLuint indx, sequence<GLfloat> values);
foreign import javascript unsafe "$3['vertexAttrib4fv']($1, $2);"
js_vertexAttrib4fv :: GLuint -> TypedArray Float -> WebGLContext -> IO ()
-- | void vertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset);
foreign import javascript unsafe "$7['vertexAttribPointer']($1, $2, $3, $4, $5, $6);"
js_vertexAttribPointer :: GLuint -> GLint -> GLenum -> GLboolean -> GLsizei -> GLintptr -> WebGLContext -> IO ()
-- | void viewport(GLint x, GLint y, GLsizei width, GLsizei height);
foreign import javascript unsafe "$5['viewport']($1, $2, $3, $4);"
js_setViewport :: GLint -> GLint -> GLsizei -> GLsizei -> WebGLContext -> IO ()
|
isomorphism/webgl
|
src/Graphics/Rendering/WebGL/Raw.hs
|
mit
| 36,382 | 611 | 10 | 4,817 | 5,207 | 2,698 | 2,509 | 315 | 0 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.EventSource
(newEventSource, close, pattern CONNECTING, pattern OPEN,
pattern CLOSED, getUrl, getWithCredentials, getReadyState, open,
message, error, EventSource(..), gTypeEventSource)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource Mozilla EventSource documentation>
newEventSource ::
(MonadDOM m, ToJSString url) =>
url -> Maybe EventSourceInit -> m EventSource
newEventSource url eventSourceInitDict
= liftDOM
(EventSource <$>
new (jsg "EventSource") [toJSVal url, toJSVal eventSourceInitDict])
-- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.close Mozilla EventSource.close documentation>
close :: (MonadDOM m) => EventSource -> m ()
close self = liftDOM (void (self ^. jsf "close" ()))
pattern CONNECTING = 0
pattern OPEN = 1
pattern CLOSED = 2
-- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.url Mozilla EventSource.url documentation>
getUrl ::
(MonadDOM m, FromJSString result) => EventSource -> m result
getUrl self = liftDOM ((self ^. js "url") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.withCredentials Mozilla EventSource.withCredentials documentation>
getWithCredentials :: (MonadDOM m) => EventSource -> m Bool
getWithCredentials self
= liftDOM ((self ^. js "withCredentials") >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.readyState Mozilla EventSource.readyState documentation>
getReadyState :: (MonadDOM m) => EventSource -> m Word
getReadyState self
= liftDOM (round <$> ((self ^. js "readyState") >>= valToNumber))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.onopen Mozilla EventSource.onopen documentation>
open :: EventName EventSource Event
open = unsafeEventNameAsync (toJSString "open")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.onmessage Mozilla EventSource.onmessage documentation>
message :: EventName EventSource MessageEvent
message = unsafeEventNameAsync (toJSString "message")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/EventSource.onerror Mozilla EventSource.onerror documentation>
error :: EventName EventSource UIEvent
error = unsafeEventNameAsync (toJSString "error")
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/EventSource.hs
|
mit
| 3,253 | 0 | 12 | 419 | 726 | 424 | 302 | 47 | 1 |
#!/usr/bin/env stack
{- stack
--resolver lts-9.14
--install-ghc runghc
--package base
--package protolude
--package text
--package aeson
--package yaml
--package unordered-containers
--package case-insensitive
--package regex-compat
--
-hide-all-packages
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -fno-warn-unused-top-binds #-}
-- Serverless.yml reference: https://serverless.com/framework/docs/providers/aws/guide/serverless.yml/
module ServerlessValidator ( main
, toSemVer
, FrameworkVersion(..)
, Runtime(..)
, Event(..)
, AwsService(..)
)
where
import GHC.Show (show)
import Protolude hiding (Prefix, show)
import Data.Text (Text)
import Data.Traversable (for)
import Data.Aeson.Types (Object, typeMismatch, withObject)
import Data.Yaml (FromJSON, Value (String, Object), Parser, ParseException, (.:), (.:?), (.!=))
import Control.Monad (forM_, fail)
import qualified Data.Yaml as YML (decodeFileEither, parseJSON)
import qualified Data.HashMap.Strict as Map (toList)
import qualified Data.Text as T (unpack, splitOn, pack)
import qualified Data.Text.Lazy.Read as TLR (decimal)
import qualified Data.Text.Lazy as TL (fromStrict, unpack, toStrict)
import qualified Data.CaseInsensitive as CI (mk)
import qualified System.Environment as S (getArgs)
import qualified Text.Regex as Regex (mkRegex, matchRegex)
import qualified Data.Maybe as Maybe (fromJust, isJust, fromMaybe)
import qualified Data.Text.Lazy.Builder as TLB (toLazyText, fromString)
type ErrorMsg =
Text
type ServiceName =
Text
data Serverless
= S { service :: ServiceName
, frameworkVersion :: FrameworkVersion
, provider :: Provider
, functions :: Functions
}
deriving Show
mkServerless :: ServiceName -> Maybe FrameworkVersion -> Provider -> Functions -> Either ErrorMsg Serverless
mkServerless s fv p fs =
Right S { service = s
, frameworkVersion = Maybe.fromMaybe frameworkVersionLatestSupported fv
, provider = p
, functions = fs
}
instance FromJSON Serverless where
parseJSON (Object o) =
do
res <- mkServerless <$> o .: "service"
<*> o .:? "frameworkVersion"
<*> o .: "provider"
<*> o .: "functions"
either (fail . T.unpack) return res
parseJSON invalid =
typeMismatch "Serverless" invalid
data FrameworkVersion =
FV { frameworkVersionMin :: SemVer
, frameworkVersionMax :: SemVer
}
deriving (Show, Eq)
mkFrameworkVersion :: Text -> Either ErrorMsg FrameworkVersion
mkFrameworkVersion version =
let
-- TODO[1]: is this re-compiled each time? Shall it be moved this to the outer scope?!
fVRegex =
Regex.mkRegex "^>=([0-9]+\\.[0-9]+\\.[0-9]+) <([0-9]+\\.[0-9]+\\.[0-9]+)$"
in
case Regex.matchRegex fVRegex (T.unpack version) of
Just [minVer, maxVer] ->
let
minSemVer =
toSemVer $ T.pack minVer
maxSemVer =
toSemVer $ T.pack maxVer
in
if all Maybe.isJust [minSemVer, maxSemVer]
then validateFrameworkVersionRange (Maybe.fromJust minSemVer) (Maybe.fromJust maxSemVer)
else Left "Framework version must be a string of the form: >=x.x.x <x.x.x"
_ ->
Left "Framework version must be a string of the form: >=x.x.x <x.x.x"
type MinSemVer =
SemVer
type MaxSemVer =
SemVer
validateFrameworkVersionRange :: MinSemVer -> MaxSemVer -> Either ErrorMsg FrameworkVersion
validateFrameworkVersionRange minSV maxSV =
let
minOrd =
compare frameworkVersionMinSupported minSV
maxOrd =
compare maxSV frameworkVersionMaxSupported
in
case minOrd of
LT ->
Left minimumVersionNotSupported
GT ->
Left minimumVersionNotSupported
_ ->
case maxOrd of
GT ->
let
err =
TLB.toLazyText $ "Maximum version '" <> TLB.fromString (show maxSV) <> "' is not supported, '" <> TLB.fromString (show frameworkVersionMaxSupported) <> "' the maximum supported version (exclusive)"
in
Left . TL.toStrict $ err
_ ->
Right FV { frameworkVersionMin = minSV
, frameworkVersionMax = maxSV
}
where
minimumVersionNotSupported =
TL.toStrict (TLB.toLazyText $ "Minimum version '" <> TLB.fromString (show minSV) <> "' is not supported, '" <> TLB.fromString (show frameworkVersionMinSupported) <> "' is the minimum supported version (inclusive)")
instance FromJSON FrameworkVersion where
parseJSON (String version) =
either (fail . T.unpack) return $ mkFrameworkVersion version
parseJSON invalid =
typeMismatch "Framework version" invalid
frameworkVersionLatestSupported :: FrameworkVersion
frameworkVersionLatestSupported =
FV { frameworkVersionMin = frameworkVersionMinSupported
, frameworkVersionMax = frameworkVersionMaxSupported
}
data SemVer =
SemVer { svMajor :: Int
, svMinor :: Int
, svPatch :: Int
}
deriving Eq
instance Show SemVer where
show sv =
show (svMajor sv) ++ "." ++ show (svMinor sv) ++ "." ++ show (svPatch sv)
instance Ord SemVer where
compare a b =
case compare (svMajor a) (svMajor b) of
EQ ->
case compare (svMinor a) (svMinor b) of
EQ ->
compare (svPatch a) (svPatch b)
ord' ->
ord'
ord' ->
ord'
frameworkVersionMinSupported :: SemVer
frameworkVersionMinSupported =
Maybe.fromJust $ toSemVer "1.0.0"
frameworkVersionMaxSupported :: SemVer
frameworkVersionMaxSupported =
Maybe.fromJust $ toSemVer "2.0.0"
toSemVer :: Text -> Maybe SemVer
toSemVer t =
case map (TLR.decimal . TL.fromStrict) $ T.splitOn "." t of
[Right (major, _), Right (minor, _), Right (patch, _)] ->
Just SemVer { svMajor = major
, svMinor = minor
, svPatch = patch
}
_ ->
Nothing
data Runtime
= NodeJs
| Python
| Java
deriving (Show, Eq)
mkRuntime :: Text -> Either ErrorMsg Runtime
mkRuntime "nodejs6.10" =
Right NodeJs
mkRuntime "nodejs4.3" =
Right NodeJs
mkRuntime "java8" =
Right Java
mkRuntime "python2.7" =
Right Python
mkRuntime unknown =
Left $ "Unsupported runtime '" <> unknown <> "'. Choose one among: 'nodejs6.10', 'nodejs4.3', 'java8', 'python2.8'"
instance FromJSON Runtime where
parseJSON (String rt) =
either (fail . T.unpack) return $ mkRuntime rt
parseJSON invalid =
typeMismatch "Runtime" invalid
type Environment =
(Text, Text)
data Provider
= P { name :: Text
, globalRuntime :: Runtime
, globalMemorySize :: Maybe Int
, globalTimeout :: Maybe Int
, globalEnvironment :: [Environment]
}
deriving Show
instance FromJSON Provider where
parseJSON (Object o) =
P <$> o .: "name"
<*> o .: "runtime"
<*> o .:? "memorySize"
<*> o .:? "timeout"
<*> o .:? "environment" .!= []
parseJSON invalid =
typeMismatch "Provider" invalid
newtype Functions =
FS { getFunctions :: [Function] }
deriving Show
instance FromJSON Functions where
parseJSON =
withObject "Functions" parseFunctions
where
parseFunctions :: Object -> Parser Functions
parseFunctions fObj =
-- fmap FS . for (Map.toList fObj) $ \(n, b) -> parseFunction n b
fmap FS (for (Map.toList fObj) $ uncurry parseFunction)
data Function =
F { functionName :: Text
, functionHandler :: Text
, functionDeployedName :: Maybe Text
, functionDescription :: Maybe Text
, functionRuntime :: Maybe Runtime
, functionMemorySize :: Maybe Int
, functionTimeout :: Maybe Int
, functionEnvironment :: [Environment]
, functionEvents :: [Event]
}
deriving Show
type FunctionName =
Text
parseFunction :: FunctionName -> Value -> Parser Function
parseFunction fName =
withObject "Function" parseFunctionBody
where
parseFunctionBody :: Object -> Parser Function
parseFunctionBody obj =
F <$> return fName
<*> obj .: "handler"
<*> obj .:? "deployedName"
<*> obj .:? "description"
<*> obj .:? "runtime"
<*> obj .:? "memorySize"
<*> obj .:? "timeout"
<*> obj .:? "environment" .!= []
<*> obj .: "events"
type Path =
Text
data Event
= HttpEvent { httpEventPath :: Path
, httpEventMethod :: HttpMethod
, httpEventCors :: Maybe Bool
, httpEventPrivate :: Maybe Bool
}
| S3Event { s3EventBucket :: Text
, s3EventEvent :: Text
, s3EventRules :: [S3EventRule]
}
| ScheduleEvent { scheduleEventRate :: Text
, scheduleEventEnabled :: Bool
, scheduleEventInput :: ScheduleEventInput
, scheduleEventInputPath :: Maybe Text
, scheduleEventName :: Maybe Text
, scheduleEventDescription :: Maybe Text
}
| SnsEvent { snsEventTopicName :: Maybe Text
, snsEventTopicArn :: Maybe Text
, snsEventDisplayName :: Maybe Text
}
| DynamoDBEvent { dynamoDBArn :: Text
}
| KinesisEvent { kinesisArn :: Text
, kinesisBatchSize :: Int
, kinesisStartingPosition :: Text
, kinesisEnabled :: Bool
}
| UnknownEvent Text
deriving Show
data ScheduleEventInput
= SEI { key1 :: Text
, key2 :: Text
, stageParams :: ScheduleEventInputStageParams
}
| EmptySEI
deriving Show
instance FromJSON ScheduleEventInput where
parseJSON (Object o) =
SEI <$> o .: "key1"
<*> o .: "key2"
<*> o .: "stageParams"
parseJSON invalid =
typeMismatch "Schedule Event Input" invalid
data ScheduleEventInputStageParams =
SEISP { stage :: Text }
deriving Show
instance FromJSON ScheduleEventInputStageParams where
parseJSON (String str) =
return SEISP { stage = str }
parseJSON invalid =
typeMismatch "Schedule Event Stage" invalid
data HttpMethod
= Get
| Post
| Put
| Delete
| Patch
deriving Show
data S3EventRule
= Prefix Text
| Suffix Text
deriving Show
type S3EventRuleValue =
Text
type S3EventRuleKey =
Text
mkS3EventRule :: S3EventRuleKey -> S3EventRuleValue -> Either ErrorMsg S3EventRule
mkS3EventRule "suffix" suffix =
Right $ Suffix suffix
mkS3EventRule "prefix" prefix =
Right $ Prefix prefix
mkS3EventRule _ _ =
Left "'prefix' or 'suffix' string"
instance FromJSON S3EventRule where
parseJSON value =
withObject "S3 Event Rule" (unpackRule . Map.toList) value
where
unpackRule :: [(Text, Value)] -> Parser S3EventRule
unpackRule [(k, String v)] =
either (fail . T.unpack) return $ mkS3EventRule k v
unpackRule _ =
typeMismatch "Invalid S3 Event Rule" value
instance FromJSON Event where
parseJSON value =
withObject "Event" (parseEvent . Map.toList) value
where
parseEvent :: [(Text, Value)] -> Parser Event
parseEvent xs =
case xs of
[(eventName, eventConfig)] ->
case eventName of
"http" ->
parseHttpEvent eventConfig
"s3" ->
parseS3Event eventConfig
"schedule" ->
parseScheduleEvent eventConfig
"sns" ->
parseSnsEvent eventConfig
"stream" ->
parseStreamEvent eventConfig
_ ->
return $ UnknownEvent eventName
_ ->
typeMismatch "Event" value
data AwsService
= Sns
| DynamoDB
| Kinesis
deriving (Show, Eq)
type Arn =
Text
validArn :: AwsService -> Arn -> Bool
validArn awsSer arn =
Maybe.isJust $ Regex.matchRegex arnRegex (T.unpack arn)
where
arnRegex =
let
-- see TODO[1]
snsRegex =
Regex.mkRegex "arn:aws:sns:(\\*|[a-z]{2}-[a-z]+-[0-9]+):[0-9]{12}:.+"
dynamoDBRegex =
Regex.mkRegex "arn:aws:dynamodb:(\\*|[a-z]{2}-[a-z]+-[0-9]+):[0-9]{12}:table/.+"
kinesisRegex =
Regex.mkRegex "arn:aws:kinesis:(\\*|[a-z]{2}-[a-z]+-[0-9]+):[0-9]{12}:stream/.+"
in
case awsSer of
-- http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-sns
Sns ->
snsRegex
DynamoDB ->
dynamoDBRegex
Kinesis ->
kinesisRegex
mkDynamoDBEvent :: Arn -> Either Text Event
mkDynamoDBEvent arn
| not . validArn DynamoDB $ arn =
Left $ "'" <> arn <> "' is not a valid " <> T.pack (show DynamoDB) <> " arn"
mkDynamoDBEvent arn =
Right DynamoDBEvent { dynamoDBArn = arn }
mkKinesisEvent :: Arn -> Int -> Text -> Bool -> Either Text Event
mkKinesisEvent arn _ _ _
| not . validArn Kinesis $ arn =
Left $ "'" <> arn <> "' is not a valid " <> T.pack (show Kinesis) <> " arn"
mkKinesisEvent arn batchSize startingPosition enabled =
Right KinesisEvent { kinesisArn = arn
, kinesisBatchSize = batchSize
, kinesisStartingPosition = startingPosition
, kinesisEnabled = enabled
}
parseStreamEvent :: Value -> Parser Event
parseStreamEvent (String arn) =
either (fail . T.unpack) return $ mkDynamoDBEvent arn
parseStreamEvent (Object o) =
do
res <- mkKinesisEvent <$> o .: "arn"
<*> o .: "batchSize"
<*> o .: "startingPosition"
<*> o .: "enabled"
either (fail . T.unpack) return res
parseStreamEvent invalid =
typeMismatch "Stream event" invalid
mkSnsEvent :: Arn -> Maybe Text -> Event
mkSnsEvent arn _ | validArn Sns arn =
SnsEvent { snsEventTopicName = Nothing
, snsEventTopicArn = Just arn
, snsEventDisplayName = Nothing
}
mkSnsEvent topicName Nothing | not . validArn Sns $ topicName =
SnsEvent { snsEventTopicName = Just topicName
, snsEventTopicArn = Nothing
, snsEventDisplayName = Nothing
}
mkSnsEvent topicName displayName =
SnsEvent { snsEventTopicName = Just topicName
, snsEventTopicArn = Nothing
, snsEventDisplayName = displayName
}
parseSnsEvent :: Value -> Parser Event
parseSnsEvent (String arn) =
return $ mkSnsEvent arn Nothing
parseSnsEvent (Object o) =
mkSnsEvent <$> o .: "topicName" <*> o .:? "displayName"
parseSnsEvent invalid =
typeMismatch "Sns Event" invalid
parseScheduleEvent :: Value -> Parser Event
parseScheduleEvent (Object o) =
ScheduleEvent <$> o .: "rate"
<*> o .: "enabled"
<*> o .:? "input" .!= EmptySEI
<*> o .:? "inputPath"
<*> o .:? "name"
<*> o .:? "description"
parseScheduleEvent invalid =
typeMismatch "Schedule Event" invalid
type S3Bucket =
Text
type S3Event =
Text
mkS3Event :: S3Bucket -> S3Event -> [S3EventRule] -> Either ErrorMsg Event
mkS3Event _ event _ | invalidArn =
Left $ "'" <> event <> "' is not a valid s3 event arn"
where
invalidArn =
not . isValidS3EventArn $ event
mkS3Event bucket event rules =
Right S3Event { s3EventBucket = bucket
, s3EventEvent = event
, s3EventRules = rules
}
parseS3Event :: Value -> Parser Event
parseS3Event (Object o) =
do
res <- mkS3Event <$> o .: "bucket" <*> o .: "event" <*> o .:? "rules" .!= []
either (fail . T.unpack) return res
parseS3Event invalid =
typeMismatch "S3 Event" invalid
type S3EventArn =
Text
-- http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html#notification-how-to-event-types-and-destinations
isValidS3EventArn :: S3EventArn -> Bool
isValidS3EventArn event =
Maybe.isJust $ Regex.matchRegex s3EventArnRegex (T.unpack event)
where
-- see TODO[1]
s3EventArnRegex =
let
objCreatedRegex =
"ObjectCreated:(\\*|Put|Post|Copy|CompleteMultipartUpload)"
objRemovedRegex =
"ObjectRemoved:(\\*|Delete|DeleteMarkerCreated)"
regexBuilder =
TLB.toLazyText $ "s3:(" <> objCreatedRegex <> "|" <> objRemovedRegex <> "|ReducedRedundancyLostObject)"
in
Regex.mkRegex . TL.unpack $ regexBuilder
mkHttpEvent :: Path -> HttpMethod -> Maybe Bool -> Maybe Bool -> Event
mkHttpEvent path method cors private =
HttpEvent { httpEventPath = path
, httpEventMethod = method
, httpEventCors = cors
, httpEventPrivate = private
}
type HttpEventConfig =
Text
mkHttpEventFromString :: HttpEventConfig -> Either ErrorMsg Event
mkHttpEventFromString config =
case T.splitOn " " config of
[httpMethodStr, httpEndpoint] ->
case toHttpMethod httpMethodStr of
Right m ->
Right $ mkHttpEvent httpEndpoint m Nothing Nothing
Left err ->
Left $ "Unknown HTTP method: " <> err
_ ->
Left "HTTP string must contain only a HTTP method and a path, i.e. 'http: GET foo'"
parseHttpEvent :: Value -> Parser Event
parseHttpEvent (String config) =
either (fail . T.unpack) return $ mkHttpEventFromString config
parseHttpEvent (Object obj) =
mkHttpEvent <$> obj .: "path" <*> obj .: "method" <*> obj .:? "cors" <*> obj .:? "private"
parseHttpEvent invalid =
typeMismatch "HTTP Event" invalid
toHttpMethod :: Text -> Either ErrorMsg HttpMethod
toHttpMethod httpMethodStr =
case CI.mk httpMethodStr of
"get" ->
Right Get
"patch" ->
Right Patch
"post" ->
Right Post
"put" ->
Right Put
"delete" ->
Right Delete
str ->
Left $ T.pack (show str)
instance FromJSON HttpMethod where
parseJSON (String str) =
case toHttpMethod str of
Right m ->
return m
Left err ->
fail $ T.unpack("Unknown HTTP method: " <> err)
parseJSON invalid =
typeMismatch "HttpMethod" invalid
parse :: FilePath -> IO (Either ParseException Serverless)
parse =
YML.decodeFileEither
main :: IO ()
main =
do
args <- S.getArgs
-- let args = [ "fixtures/serverless.yml"
-- , "fixtures/serverless-bogus.yml"
-- ]
case args of
[] ->
print $ T.pack "Usage: ./serverless-validator /path/to/serverless.yml [/path/to/another/serverless.yml]"
xs ->
forM_ xs checkFile
where
checkFile :: FilePath -> IO ()
checkFile f =
do
res <- parse f
case res of
Left err ->
do
putStrLn $ "'" ++ f ++ "' is not valid"
print err
Right serverless ->
do
print serverless
putStrLn $ "'" ++ f ++ "' is valid"
|
futtetennista/scripts
|
src/ServerlessValidator.hs
|
mit
| 19,164 | 0 | 25 | 5,569 | 4,531 | 2,398 | 2,133 | 509 | 6 |
f x = g
where g :: Int
g = 0
|
Pnom/haskell-ast-pretty
|
Test/examples/IndentedWhere.hs
|
mit
| 39 | 0 | 6 | 21 | 21 | 11 | 10 | 3 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Neuro.Show.Tikz
-- Copyright :
-- License : MIT
--
-- Maintainer : -
-- Stability :
-- Portability :
--
-- |
--
{-# LANGUAGE TypeOperators #-}
module Neuro.Show.Tikz (
NShow(..)
, Tikz(..)
, RenderConfig(..)
, nnet2tikz
, defaultRenderConfig
) where
import Neuro.Show
import Neuro.DSL
import Neuro.DSL.Internal
import Tikz.DSL
import Data.HList
import Data.ByteString.Char8 (ByteString)
-----------------------------------------------------------------------------
newtype Tikz = Tikz ByteString
instance NShow NNDescriptor Tikz where nShow = nnet2tikz defaultRenderConfig
nnet2tikz cfg (NNDescriptor layers) = Tikz . elemRepr 0
$ picture (pictureAttrs cfg)
(pictureStyles cfg)
(pictureDefs cfg)
(renderLayers cfg layers)
data RenderConfig = RenderConfig { pictureAttrs :: PictureAttrs
, pictureStyles :: PictureStyles
, pictureDefs :: PictureDefs
, renderLayers :: [SomeLayer] -> [Expr]
}
nElemId :: NElem -> String
nElemId (NInput i) = "0-" ++ show i
nElemId (Neuron _ l i) = show l ++ "-" ++ show i
-----------------------------------------------------------------------------
defaultRenderConfig = RenderConfig defaultPicAttrs
defaultPicStyles
defaultPicDefs
defaultRenderLayers
defaultPicAttrs = PictureAttrs [ Attr "shorten >=1pt"
, Attr "->"
, Attr "draw=black!50"
]
defaultPicStyles = PictureStyles [ Style "every pin edge" [ Attr "<-"
, Attr "shorten <=1pt"
]
, Style "neuron" [ Attr "circle"
, Attr "fill=black!25"
, Attr "minimum size=17pt"
, Attr "inner sep=0pt"
]
, Style "input neuron" [Attr "neuron", Attr "fill=green!50"]
, Style "output neuron" [Attr "neuron", Attr "fill=red!50"]
, Style "hidden neuron" [Attr "neuron", Attr "fill=blue!50"]
, Style "annot" [ Attr "text width=4em"
, Attr "text centered"
, Attr "node distance=1cm"
]
]
defaultPicDefs = PictureDefs [ Def "layersep" "2.5cm" ]
layerAnnot (e:_) name =
Expr ( Node "input layer"
[Attr "annot", Attr $ "above of=" ++ nElemId e]
Nothing
[Expr $ RawExpr name]
)
defaultRenderLayers :: [SomeLayer] -> [Expr]
defaultRenderLayers = defaultRenderLayers' . zipWith f [0..] . reverse
where f n (SomeLayer l) = (n, vec2list l)
defaultRenderLayers' ((0, l) : ls) = Expr EmptyLine : defaultRenderInputs l'
++ annot : defaultRenderLayers' ls
where annot = layerAnnot l' "Input Layer"
l' = reverse l
defaultRenderLayers' [(n, l)] = Expr EmptyLine : defaultRenderOutputs l
++ [annot]
where annot = layerAnnot l "Output Layer"
defaultRenderLayers' ((n, l) : ls) = Expr EmptyLine : defaultRenderHidden l
++ annot : defaultRenderLayers' ls
where annot = layerAnnot l $ "Hidden Layer \\#" ++ show n
mkNode l i name attrs = Node name attrs (Just $ "\\layersep*" ++ show l ++ ",-" ++ show i) []
defaultRenderInputs (n@(NInput i): ns) = Expr node : defaultRenderInputs ns
where node = mkNode 0 i (nElemId n)
[Attr "input neuron", Attr $ "pin=left:Input " ++ show i]
defaultRenderInputs [] = []
defaultRenderGeneric attrs (n@(Neuron inputs l i) : ns) =
Expr node : synapses ++ defaultRenderGeneric attrs ns
where node = mkNode l i this (attrs i)
synapses = do input <- vec2list inputs
let from = nElemId input
return . Expr $ Path Edge from this
this = nElemId n
defaultRenderGeneric _ [] = []
defaultRenderHidden = defaultRenderGeneric (const [Attr "hidden neuron"])
defaultRenderOutputs =
defaultRenderGeneric (\i -> [ Attr "output neuron"
, Attr $ "pin={[pin edge={->}]right:Output " ++ show i ++ "}"
])
defaultRenderSynopses' = undefined
|
fehu/hneuro
|
src/Neuro/Show/Tikz.hs
|
mit
| 5,057 | 0 | 12 | 2,072 | 1,117 | 583 | 534 | -1 | -1 |
data Term a where
Lit :: Int -> Term Int
Pair :: Term a -> Term b -> Term (a,b)
{- Phantom Types -}
data Expr a = Concat (Expr String) (Expr String) | Add (Expr Int) (Expr Int) | Val a deriving (Show)
eval :: Expr Int -> Int
eval (Val i) = i
eval (Add e1 e2) = (eval e1) + (eval e2)
evalS :: Expr String -> String
evalS (Val s) = s
evalS (Concat e1 e2) = (evalS e1) ++ (evalS e2)
data Lam :: * -> * where
Lift :: a -> Lam a
Tup :: Lam a -> Lam b -> Lam (a, b)
Lam :: (Lam a -> Lam b) -> Lam (a -> b)
App :: Lam (a -> b) -> Lam a -> Lam b
Fix :: Lam (a -> a) -> Lam a
|
nlim/haskell-playground
|
src/Gadts.hs
|
mit
| 635 | 0 | 9 | 211 | 352 | 181 | 171 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
module Oden.Imports
( UnsupportedMessage
, UnsupportedTypesWarning(..)
, PackageImportError(..)
, ForeignImporter
, ImportResolutionEnvironment
, resolveImports
) where
import Oden.Core.Package
import Oden.Core.Untyped
import Oden.Core.Typed
import Oden.Identifier
import Oden.QualifiedName
import Oden.SourceInfo
import Control.Monad.Except
import Control.Arrow (left)
import Data.Map (Map)
import qualified Data.Map as Map
type UnsupportedMessage = (Identifier, String)
data UnsupportedTypesWarning = UnsupportedTypesWarning { pkg :: String
, messages :: [UnsupportedMessage]
} deriving (Show, Eq)
data PackageImportError
= PackageNotFound SourceInfo PackageName
| ForeignPackageImportError String String
| IllegalImportPackageName SourceInfo IdentifierValidationError
| PackageNotInEnvironment ImportReference
deriving (Show, Eq, Ord)
type ImportResolutionEnvironment =
Map
ImportReference
(TypedPackage, [UnsupportedMessage])
type ForeignImporter =
String -> IO (Either PackageImportError (TypedPackage, [UnsupportedMessage]))
importedPackageIdentifier :: SourceInfo
-> PackageName
-> Either PackageImportError Identifier
importedPackageIdentifier si pkgName =
left (IllegalImportPackageName si) legalIdentifier
where
legalIdentifier =
case pkgName of
NativePackageName segments ->
createLegalIdentifier (last segments)
ForeignPackageName name ->
createLegalIdentifier name
findInEnv :: ImportReference
-> ImportResolutionEnvironment
-> Either PackageImportError (TypedPackage, [UnsupportedMessage])
findInEnv ref env =
case Map.lookup ref env of
Just x -> Right x
Nothing -> Left (PackageNotInEnvironment ref)
resolveImports :: ImportResolutionEnvironment
-> UntypedPackage ImportReference
-> Either PackageImportError ( UntypedPackage (ImportedPackage TypedPackage)
, [UnsupportedTypesWarning])
resolveImports env (UntypedPackage pkgDecl imports defs) = do
(importedPackages, warnings) <- foldM resolveImport' ([], []) imports
return (UntypedPackage pkgDecl importedPackages defs, warnings)
where
resolveImport' :: ([ImportedPackage TypedPackage], [UnsupportedTypesWarning])
-> ImportReference
-> Either PackageImportError ( [ImportedPackage TypedPackage]
, [UnsupportedTypesWarning])
resolveImport' (pkgs, warnings) ref = do
(pkg'@(TypedPackage decl _ _), unsupported) <- findInEnv ref env
let pkgName = packageDeclarationName decl
pkgIdentifier <- importedPackageIdentifier (getSourceInfo ref) pkgName
let warnings' =
if null unsupported
then warnings
else UnsupportedTypesWarning (asString pkgIdentifier) unsupported : warnings
return (ImportedPackage ref pkgIdentifier pkg' : pkgs, warnings')
|
oden-lang/oden
|
src/Oden/Imports.hs
|
mit
| 3,193 | 0 | 16 | 831 | 692 | 374 | 318 | 72 | 2 |
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module Language.Clafer.Front.PrintClafer where
-- pretty-printer generated by the BNF converter
import Language.Clafer.Front.AbsClafer
import Data.Char
import Prelude hiding (exp, init)
-- the top-level printing method
printTree :: Print a => a -> String
printTree = render . prt 0
type Doc = [ShowS] -> [ShowS]
doc :: ShowS -> Doc
doc = (:)
render :: Doc -> String
render d = rend 0 (map ($ "") $ d []) "" where
rend i ss = case ss of
"[" :ts -> showChar '[' . rend i ts
"(" :ts -> showChar '(' . rend i ts
"{" :ts -> showChar '{' . new (i+1) . rend (i+1) ts
"}" : ";":ts -> new (i-1) . space "}" . showChar ';' . new (i-1) . rend (i-1) ts
"}" :ts -> new (i-1) . showChar '}' . new (i-1) . rend (i-1) ts
";" :ts -> showChar ';' . new i . rend i ts
t : "," :ts -> showString t . space "," . rend i ts
t : ")" :ts -> showString t . showChar ')' . rend i ts
t : "]" :ts -> showString t . showChar ']' . rend i ts
t :ts -> space t . rend i ts
_ -> id
new i = showChar '\n' . replicateS (2*i) (showChar ' ') . dropWhile isSpace
space t = showString t . (\s -> if null s then "" else (' ':s))
parenth :: Doc -> Doc
parenth ss = doc (showChar '(') . ss . doc (showChar ')')
concatS :: [ShowS] -> ShowS
concatS = foldr (.) id
concatD :: [Doc] -> Doc
concatD = foldr (.) id
replicateS :: Int -> ShowS -> ShowS
replicateS n f = concatS (replicate n f)
-- the printer class does the job
class Print a where
prt :: Int -> a -> Doc
prtList :: Int -> [a] -> Doc
prtList i = concatD . map (prt i)
instance Print a => Print [a] where
prt = prtList
instance Print Char where
prt _ s = doc (showChar '\'' . mkEsc '\'' s . showChar '\'')
prtList _ s = doc (showChar '"' . concatS (map (mkEsc '"') s) . showChar '"')
mkEsc :: Char -> Char -> ShowS
mkEsc q s = case s of
_ | s == q -> showChar '\\' . showChar s
'\\'-> showString "\\\\"
'\n' -> showString "\\n"
'\t' -> showString "\\t"
_ -> showChar s
prPrec :: Int -> Int -> Doc -> Doc
prPrec i j = if j<i then parenth else id
instance Print Integer where
prt _ x = doc (shows x)
instance Print Double where
prt _ x = doc (shows x)
instance Print PosInteger where
prt _ (PosInteger (_,i)) = doc (showString ( i))
instance Print PosDouble where
prt _ (PosDouble (_,i)) = doc (showString ( i))
instance Print PosReal where
prt _ (PosReal (_,i)) = doc (showString ( i))
instance Print PosString where
prt _ (PosString (_,i)) = doc (showString ( i))
instance Print PosIdent where
prt _ (PosIdent (_,i)) = doc (showString ( i))
instance Print PosLineComment where
prt _ (PosLineComment (_,i)) = doc (showString ( i))
instance Print PosBlockComment where
prt _ (PosBlockComment (_,i)) = doc (showString ( i))
instance Print PosAlloy where
prt _ (PosAlloy (_,i)) = doc (showString ( i))
instance Print PosChoco where
prt _ (PosChoco (_,i)) = doc (showString ( i))
instance Print Module where
prt i e = case e of
Module _ declarations -> prPrec i 0 (concatD [prt 0 declarations])
instance Print Declaration where
prt i e = case e of
EnumDecl _ posident enumids -> prPrec i 0 (concatD [doc (showString "enum"), prt 0 posident, doc (showString "="), prt 0 enumids])
ElementDecl _ element -> prPrec i 0 (concatD [prt 0 element])
prtList _ [] = (concatD [])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Clafer where
prt i e = case e of
Clafer _ abstract gcard posident super reference card init elements -> prPrec i 0 (concatD [prt 0 abstract, prt 0 gcard, prt 0 posident, prt 0 super, prt 0 reference, prt 0 card, prt 0 init, prt 0 elements])
instance Print Constraint where
prt i e = case e of
Constraint _ exps -> prPrec i 0 (concatD [doc (showString "["), prt 0 exps, doc (showString "]")])
instance Print Assertion where
prt i e = case e of
Assertion _ exps -> prPrec i 0 (concatD [doc (showString "assert"), doc (showString "["), prt 0 exps, doc (showString "]")])
instance Print Goal where
prt i e = case e of
GoalMinDeprecated _ exps -> prPrec i 0 (concatD [doc (showString "<<"), doc (showString "min"), prt 0 exps, doc (showString ">>")])
GoalMaxDeprecated _ exps -> prPrec i 0 (concatD [doc (showString "<<"), doc (showString "max"), prt 0 exps, doc (showString ">>")])
GoalMinimize _ exps -> prPrec i 0 (concatD [doc (showString "<<"), doc (showString "minimize"), prt 0 exps, doc (showString ">>")])
GoalMaximize _ exps -> prPrec i 0 (concatD [doc (showString "<<"), doc (showString "maximize"), prt 0 exps, doc (showString ">>")])
instance Print Abstract where
prt i e = case e of
AbstractEmpty _ -> prPrec i 0 (concatD [])
Abstract _ -> prPrec i 0 (concatD [doc (showString "abstract")])
instance Print Elements where
prt i e = case e of
ElementsEmpty _ -> prPrec i 0 (concatD [])
ElementsList _ elements -> prPrec i 0 (concatD [doc (showString "{"), prt 0 elements, doc (showString "}")])
instance Print Element where
prt i e = case e of
Subclafer _ clafer -> prPrec i 0 (concatD [prt 0 clafer])
ClaferUse _ name card elements -> prPrec i 0 (concatD [doc (showString "`"), prt 0 name, prt 0 card, prt 0 elements])
Subconstraint _ constraint -> prPrec i 0 (concatD [prt 0 constraint])
Subgoal _ goal -> prPrec i 0 (concatD [prt 0 goal])
SubAssertion _ assertion -> prPrec i 0 (concatD [prt 0 assertion])
prtList _ [] = (concatD [])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Super where
prt i e = case e of
SuperEmpty _ -> prPrec i 0 (concatD [])
SuperSome _ exp -> prPrec i 0 (concatD [doc (showString ":"), prt 18 exp])
instance Print Reference where
prt i e = case e of
ReferenceEmpty _ -> prPrec i 0 (concatD [])
ReferenceSet _ exp -> prPrec i 0 (concatD [doc (showString "->"), prt 15 exp])
ReferenceBag _ exp -> prPrec i 0 (concatD [doc (showString "->>"), prt 15 exp])
instance Print Init where
prt i e = case e of
InitEmpty _ -> prPrec i 0 (concatD [])
InitSome _ inithow exp -> prPrec i 0 (concatD [prt 0 inithow, prt 0 exp])
instance Print InitHow where
prt i e = case e of
InitConstant _ -> prPrec i 0 (concatD [doc (showString "=")])
InitDefault _ -> prPrec i 0 (concatD [doc (showString ":=")])
instance Print GCard where
prt i e = case e of
GCardEmpty _ -> prPrec i 0 (concatD [])
GCardXor _ -> prPrec i 0 (concatD [doc (showString "xor")])
GCardOr _ -> prPrec i 0 (concatD [doc (showString "or")])
GCardMux _ -> prPrec i 0 (concatD [doc (showString "mux")])
GCardOpt _ -> prPrec i 0 (concatD [doc (showString "opt")])
GCardInterval _ ncard -> prPrec i 0 (concatD [prt 0 ncard])
instance Print Card where
prt i e = case e of
CardEmpty _ -> prPrec i 0 (concatD [])
CardLone _ -> prPrec i 0 (concatD [doc (showString "?")])
CardSome _ -> prPrec i 0 (concatD [doc (showString "+")])
CardAny _ -> prPrec i 0 (concatD [doc (showString "*")])
CardNum _ posinteger -> prPrec i 0 (concatD [prt 0 posinteger])
CardInterval _ ncard -> prPrec i 0 (concatD [prt 0 ncard])
instance Print NCard where
prt i e = case e of
NCard _ posinteger exinteger -> prPrec i 0 (concatD [prt 0 posinteger, doc (showString ".."), prt 0 exinteger])
instance Print ExInteger where
prt i e = case e of
ExIntegerAst _ -> prPrec i 0 (concatD [doc (showString "*")])
ExIntegerNum _ posinteger -> prPrec i 0 (concatD [prt 0 posinteger])
instance Print Name where
prt i e = case e of
Path _ modids -> prPrec i 0 (concatD [prt 0 modids])
instance Print Exp where
prt i e = case e of
EDeclAllDisj _ decl exp -> prPrec i 0 (concatD [doc (showString "all"), doc (showString "disj"), prt 0 decl, doc (showString "|"), prt 0 exp])
EDeclAll _ decl exp -> prPrec i 0 (concatD [doc (showString "all"), prt 0 decl, doc (showString "|"), prt 0 exp])
EDeclQuantDisj _ quant decl exp -> prPrec i 0 (concatD [prt 0 quant, doc (showString "disj"), prt 0 decl, doc (showString "|"), prt 0 exp])
EDeclQuant _ quant decl exp -> prPrec i 0 (concatD [prt 0 quant, prt 0 decl, doc (showString "|"), prt 0 exp])
EImpliesElse _ exp1 exp2 exp3 -> prPrec i 0 (concatD [doc (showString "if"), prt 0 exp1, doc (showString "then"), prt 0 exp2, doc (showString "else"), prt 0 exp3])
EIff _ exp1 exp2 -> prPrec i 0 (concatD [prt 0 exp1, doc (showString "<=>"), prt 1 exp2])
EImplies _ exp1 exp2 -> prPrec i 2 (concatD [prt 2 exp1, doc (showString "=>"), prt 3 exp2])
EOr _ exp1 exp2 -> prPrec i 3 (concatD [prt 3 exp1, doc (showString "||"), prt 4 exp2])
EXor _ exp1 exp2 -> prPrec i 4 (concatD [prt 4 exp1, doc (showString "xor"), prt 5 exp2])
EAnd _ exp1 exp2 -> prPrec i 5 (concatD [prt 5 exp1, doc (showString "&&"), prt 6 exp2])
ENeg _ exp -> prPrec i 6 (concatD [doc (showString "!"), prt 7 exp])
ELt _ exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString "<"), prt 8 exp2])
EGt _ exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString ">"), prt 8 exp2])
EEq _ exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString "="), prt 8 exp2])
ELte _ exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString "<="), prt 8 exp2])
EGte _ exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString ">="), prt 8 exp2])
ENeq _ exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString "!="), prt 8 exp2])
EIn _ exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString "in"), prt 8 exp2])
ENin _ exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString "not"), doc (showString "in"), prt 8 exp2])
EQuantExp _ quant exp -> prPrec i 8 (concatD [prt 0 quant, prt 12 exp])
EAdd _ exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString "+"), prt 10 exp2])
ESub _ exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString "-"), prt 10 exp2])
EMul _ exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString "*"), prt 11 exp2])
EDiv _ exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString "/"), prt 11 exp2])
ERem _ exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString "%"), prt 11 exp2])
EGMax _ exp -> prPrec i 11 (concatD [doc (showString "max"), prt 12 exp])
EGMin _ exp -> prPrec i 11 (concatD [doc (showString "min"), prt 12 exp])
ESum _ exp -> prPrec i 12 (concatD [doc (showString "sum"), prt 13 exp])
EProd _ exp -> prPrec i 12 (concatD [doc (showString "product"), prt 13 exp])
ECard _ exp -> prPrec i 12 (concatD [doc (showString "#"), prt 13 exp])
EMinExp _ exp -> prPrec i 12 (concatD [doc (showString "-"), prt 13 exp])
EDomain _ exp1 exp2 -> prPrec i 13 (concatD [prt 13 exp1, doc (showString "<:"), prt 14 exp2])
ERange _ exp1 exp2 -> prPrec i 14 (concatD [prt 14 exp1, doc (showString ":>"), prt 15 exp2])
EUnion _ exp1 exp2 -> prPrec i 15 (concatD [prt 15 exp1, doc (showString "++"), prt 16 exp2])
EUnionCom _ exp1 exp2 -> prPrec i 15 (concatD [prt 15 exp1, doc (showString ","), prt 16 exp2])
EDifference _ exp1 exp2 -> prPrec i 16 (concatD [prt 16 exp1, doc (showString "--"), prt 17 exp2])
EIntersection _ exp1 exp2 -> prPrec i 17 (concatD [prt 17 exp1, doc (showString "**"), prt 18 exp2])
EIntersectionDeprecated _ exp1 exp2 -> prPrec i 17 (concatD [prt 17 exp1, doc (showString "&"), prt 18 exp2])
EJoin _ exp1 exp2 -> prPrec i 18 (concatD [prt 18 exp1, doc (showString "."), prt 19 exp2])
ClaferId _ name -> prPrec i 19 (concatD [prt 0 name])
EInt _ posinteger -> prPrec i 19 (concatD [prt 0 posinteger])
EDouble _ posdouble -> prPrec i 19 (concatD [prt 0 posdouble])
EReal _ posreal -> prPrec i 19 (concatD [prt 0 posreal])
EStr _ posstring -> prPrec i 19 (concatD [prt 0 posstring])
prtList _ [] = (concatD [])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Decl where
prt i e = case e of
Decl _ locids exp -> prPrec i 0 (concatD [prt 0 locids, doc (showString ":"), prt 15 exp])
instance Print Quant where
prt i e = case e of
QuantNo _ -> prPrec i 0 (concatD [doc (showString "no")])
QuantNot _ -> prPrec i 0 (concatD [doc (showString "not")])
QuantLone _ -> prPrec i 0 (concatD [doc (showString "lone")])
QuantOne _ -> prPrec i 0 (concatD [doc (showString "one")])
QuantSome _ -> prPrec i 0 (concatD [doc (showString "some")])
instance Print EnumId where
prt i e = case e of
EnumIdIdent _ posident -> prPrec i 0 (concatD [prt 0 posident])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, doc (showString "|"), prt 0 xs])
instance Print ModId where
prt i e = case e of
ModIdIdent _ posident -> prPrec i 0 (concatD [prt 0 posident])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, doc (showString "\\"), prt 0 xs])
instance Print LocId where
prt i e = case e of
LocIdIdent _ posident -> prPrec i 0 (concatD [prt 0 posident])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ";"), prt 0 xs])
|
juodaspaulius/clafer
|
src/Language/Clafer/Front/PrintClafer.hs
|
mit
| 13,127 | 0 | 16 | 3,048 | 6,824 | 3,329 | 3,495 | 231 | 12 |
{-
DO NOT EDIT: this file is generated/edited by `pet sync`.
-}
module ProjectEuler.AllProblems
( allProblems
) where
import qualified Data.IntMap.Strict as IM
import ProjectEuler.Types
import ProjectEuler.Problem1
import ProjectEuler.Problem2
import ProjectEuler.Problem3
import ProjectEuler.Problem4
import ProjectEuler.Problem5
import ProjectEuler.Problem6
import ProjectEuler.Problem7
import ProjectEuler.Problem8
import ProjectEuler.Problem9
import ProjectEuler.Problem10
import ProjectEuler.Problem11
import ProjectEuler.Problem12
import ProjectEuler.Problem13
import ProjectEuler.Problem14
import ProjectEuler.Problem15
import ProjectEuler.Problem16
import ProjectEuler.Problem17
import ProjectEuler.Problem18
import ProjectEuler.Problem19
import ProjectEuler.Problem20
import ProjectEuler.Problem21
import ProjectEuler.Problem22
import ProjectEuler.Problem23
import ProjectEuler.Problem24
import ProjectEuler.Problem25
import ProjectEuler.Problem26
import ProjectEuler.Problem27
import ProjectEuler.Problem28
import ProjectEuler.Problem29
import ProjectEuler.Problem30
import ProjectEuler.Problem31
import ProjectEuler.Problem32
import ProjectEuler.Problem33
import ProjectEuler.Problem34
import ProjectEuler.Problem35
import ProjectEuler.Problem36
import ProjectEuler.Problem37
import ProjectEuler.Problem38
import ProjectEuler.Problem39
import ProjectEuler.Problem40
import ProjectEuler.Problem41
import ProjectEuler.Problem42
import ProjectEuler.Problem43
import ProjectEuler.Problem44
import ProjectEuler.Problem45
import ProjectEuler.Problem46
import ProjectEuler.Problem47
import ProjectEuler.Problem48
import ProjectEuler.Problem49
import ProjectEuler.Problem50
import ProjectEuler.Problem51
import ProjectEuler.Problem52
import ProjectEuler.Problem53
import ProjectEuler.Problem54
import ProjectEuler.Problem55
import ProjectEuler.Problem56
import ProjectEuler.Problem57
import ProjectEuler.Problem58
import ProjectEuler.Problem59
import ProjectEuler.Problem60
import ProjectEuler.Problem61
import ProjectEuler.Problem62
import ProjectEuler.Problem63
import ProjectEuler.Problem64
import ProjectEuler.Problem65
import ProjectEuler.Problem66
import ProjectEuler.Problem67
import ProjectEuler.Problem68
import ProjectEuler.Problem69
import ProjectEuler.Problem70
import ProjectEuler.Problem71
import ProjectEuler.Problem72
import ProjectEuler.Problem73
import ProjectEuler.Problem74
import ProjectEuler.Problem75
import ProjectEuler.Problem76
import ProjectEuler.Problem77
import ProjectEuler.Problem78
import ProjectEuler.Problem79
import ProjectEuler.Problem80
import ProjectEuler.Problem81
import ProjectEuler.Problem82
import ProjectEuler.Problem83
import ProjectEuler.Problem84
import ProjectEuler.Problem85
import ProjectEuler.Problem86
import ProjectEuler.Problem87
import ProjectEuler.Problem88
import ProjectEuler.Problem89
import ProjectEuler.Problem90
import ProjectEuler.Problem91
import ProjectEuler.Problem92
import ProjectEuler.Problem93
import ProjectEuler.Problem94
import ProjectEuler.Problem95
import ProjectEuler.Problem96
import ProjectEuler.Problem97
import ProjectEuler.Problem98
import ProjectEuler.Problem99
import ProjectEuler.Problem100
import ProjectEuler.Problem101
import ProjectEuler.Problem102
import ProjectEuler.Problem103
import ProjectEuler.Problem104
import ProjectEuler.Problem105
import ProjectEuler.Problem106
import ProjectEuler.Problem107
import ProjectEuler.Problem108
import ProjectEuler.Problem109
import ProjectEuler.Problem110
import ProjectEuler.Problem111
import ProjectEuler.Problem112
import ProjectEuler.Problem113
import ProjectEuler.Problem114
import ProjectEuler.Problem115
import ProjectEuler.Problem116
import ProjectEuler.Problem117
import ProjectEuler.Problem118
import ProjectEuler.Problem119
import ProjectEuler.Problem120
import ProjectEuler.Problem121
import ProjectEuler.Problem122
import ProjectEuler.Problem123
import ProjectEuler.Problem124
import ProjectEuler.Problem125
import ProjectEuler.Problem126
import ProjectEuler.Problem127
import ProjectEuler.Problem128
import ProjectEuler.Problem129
import ProjectEuler.Problem130
import ProjectEuler.Problem131
import ProjectEuler.Problem132
import ProjectEuler.Problem133
import ProjectEuler.Problem134
import ProjectEuler.Problem135
import ProjectEuler.Problem136
import ProjectEuler.Problem137
import ProjectEuler.Problem138
import ProjectEuler.Problem139
import ProjectEuler.Problem140
import ProjectEuler.Problem141
import ProjectEuler.Problem142
import ProjectEuler.Problem143
import ProjectEuler.Problem144
import ProjectEuler.Problem145
import ProjectEuler.Problem146
import ProjectEuler.Problem147
import ProjectEuler.Problem148
import ProjectEuler.Problem149
import ProjectEuler.Problem150
import ProjectEuler.Problem151
import ProjectEuler.Problem206
allProblems :: IM.IntMap Problem
allProblems =
IM.fromList
[ (1, ProjectEuler.Problem1.problem)
, (2, ProjectEuler.Problem2.problem)
, (3, ProjectEuler.Problem3.problem)
, (4, ProjectEuler.Problem4.problem)
, (5, ProjectEuler.Problem5.problem)
, (6, ProjectEuler.Problem6.problem)
, (7, ProjectEuler.Problem7.problem)
, (8, ProjectEuler.Problem8.problem)
, (9, ProjectEuler.Problem9.problem)
, (10, ProjectEuler.Problem10.problem)
, (11, ProjectEuler.Problem11.problem)
, (12, ProjectEuler.Problem12.problem)
, (13, ProjectEuler.Problem13.problem)
, (14, ProjectEuler.Problem14.problem)
, (15, ProjectEuler.Problem15.problem)
, (16, ProjectEuler.Problem16.problem)
, (17, ProjectEuler.Problem17.problem)
, (18, ProjectEuler.Problem18.problem)
, (19, ProjectEuler.Problem19.problem)
, (20, ProjectEuler.Problem20.problem)
, (21, ProjectEuler.Problem21.problem)
, (22, ProjectEuler.Problem22.problem)
, (23, ProjectEuler.Problem23.problem)
, (24, ProjectEuler.Problem24.problem)
, (25, ProjectEuler.Problem25.problem)
, (26, ProjectEuler.Problem26.problem)
, (27, ProjectEuler.Problem27.problem)
, (28, ProjectEuler.Problem28.problem)
, (29, ProjectEuler.Problem29.problem)
, (30, ProjectEuler.Problem30.problem)
, (31, ProjectEuler.Problem31.problem)
, (32, ProjectEuler.Problem32.problem)
, (33, ProjectEuler.Problem33.problem)
, (34, ProjectEuler.Problem34.problem)
, (35, ProjectEuler.Problem35.problem)
, (36, ProjectEuler.Problem36.problem)
, (37, ProjectEuler.Problem37.problem)
, (38, ProjectEuler.Problem38.problem)
, (39, ProjectEuler.Problem39.problem)
, (40, ProjectEuler.Problem40.problem)
, (41, ProjectEuler.Problem41.problem)
, (42, ProjectEuler.Problem42.problem)
, (43, ProjectEuler.Problem43.problem)
, (44, ProjectEuler.Problem44.problem)
, (45, ProjectEuler.Problem45.problem)
, (46, ProjectEuler.Problem46.problem)
, (47, ProjectEuler.Problem47.problem)
, (48, ProjectEuler.Problem48.problem)
, (49, ProjectEuler.Problem49.problem)
, (50, ProjectEuler.Problem50.problem)
, (51, ProjectEuler.Problem51.problem)
, (52, ProjectEuler.Problem52.problem)
, (53, ProjectEuler.Problem53.problem)
, (54, ProjectEuler.Problem54.problem)
, (55, ProjectEuler.Problem55.problem)
, (56, ProjectEuler.Problem56.problem)
, (57, ProjectEuler.Problem57.problem)
, (58, ProjectEuler.Problem58.problem)
, (59, ProjectEuler.Problem59.problem)
, (60, ProjectEuler.Problem60.problem)
, (61, ProjectEuler.Problem61.problem)
, (62, ProjectEuler.Problem62.problem)
, (63, ProjectEuler.Problem63.problem)
, (64, ProjectEuler.Problem64.problem)
, (65, ProjectEuler.Problem65.problem)
, (66, ProjectEuler.Problem66.problem)
, (67, ProjectEuler.Problem67.problem)
, (68, ProjectEuler.Problem68.problem)
, (69, ProjectEuler.Problem69.problem)
, (70, ProjectEuler.Problem70.problem)
, (71, ProjectEuler.Problem71.problem)
, (72, ProjectEuler.Problem72.problem)
, (73, ProjectEuler.Problem73.problem)
, (74, ProjectEuler.Problem74.problem)
, (75, ProjectEuler.Problem75.problem)
, (76, ProjectEuler.Problem76.problem)
, (77, ProjectEuler.Problem77.problem)
, (78, ProjectEuler.Problem78.problem)
, (79, ProjectEuler.Problem79.problem)
, (80, ProjectEuler.Problem80.problem)
, (81, ProjectEuler.Problem81.problem)
, (82, ProjectEuler.Problem82.problem)
, (83, ProjectEuler.Problem83.problem)
, (84, ProjectEuler.Problem84.problem)
, (85, ProjectEuler.Problem85.problem)
, (86, ProjectEuler.Problem86.problem)
, (87, ProjectEuler.Problem87.problem)
, (88, ProjectEuler.Problem88.problem)
, (89, ProjectEuler.Problem89.problem)
, (90, ProjectEuler.Problem90.problem)
, (91, ProjectEuler.Problem91.problem)
, (92, ProjectEuler.Problem92.problem)
, (93, ProjectEuler.Problem93.problem)
, (94, ProjectEuler.Problem94.problem)
, (95, ProjectEuler.Problem95.problem)
, (96, ProjectEuler.Problem96.problem)
, (97, ProjectEuler.Problem97.problem)
, (98, ProjectEuler.Problem98.problem)
, (99, ProjectEuler.Problem99.problem)
, (100, ProjectEuler.Problem100.problem)
, (101, ProjectEuler.Problem101.problem)
, (102, ProjectEuler.Problem102.problem)
, (103, ProjectEuler.Problem103.problem)
, (104, ProjectEuler.Problem104.problem)
, (105, ProjectEuler.Problem105.problem)
, (106, ProjectEuler.Problem106.problem)
, (107, ProjectEuler.Problem107.problem)
, (108, ProjectEuler.Problem108.problem)
, (109, ProjectEuler.Problem109.problem)
, (110, ProjectEuler.Problem110.problem)
, (111, ProjectEuler.Problem111.problem)
, (112, ProjectEuler.Problem112.problem)
, (113, ProjectEuler.Problem113.problem)
, (114, ProjectEuler.Problem114.problem)
, (115, ProjectEuler.Problem115.problem)
, (116, ProjectEuler.Problem116.problem)
, (117, ProjectEuler.Problem117.problem)
, (118, ProjectEuler.Problem118.problem)
, (119, ProjectEuler.Problem119.problem)
, (120, ProjectEuler.Problem120.problem)
, (121, ProjectEuler.Problem121.problem)
, (122, ProjectEuler.Problem122.problem)
, (123, ProjectEuler.Problem123.problem)
, (124, ProjectEuler.Problem124.problem)
, (125, ProjectEuler.Problem125.problem)
, (126, ProjectEuler.Problem126.problem)
, (127, ProjectEuler.Problem127.problem)
, (128, ProjectEuler.Problem128.problem)
, (129, ProjectEuler.Problem129.problem)
, (130, ProjectEuler.Problem130.problem)
, (131, ProjectEuler.Problem131.problem)
, (132, ProjectEuler.Problem132.problem)
, (133, ProjectEuler.Problem133.problem)
, (134, ProjectEuler.Problem134.problem)
, (135, ProjectEuler.Problem135.problem)
, (136, ProjectEuler.Problem136.problem)
, (137, ProjectEuler.Problem137.problem)
, (138, ProjectEuler.Problem138.problem)
, (139, ProjectEuler.Problem139.problem)
, (140, ProjectEuler.Problem140.problem)
, (141, ProjectEuler.Problem141.problem)
, (142, ProjectEuler.Problem142.problem)
, (143, ProjectEuler.Problem143.problem)
, (144, ProjectEuler.Problem144.problem)
, (145, ProjectEuler.Problem145.problem)
, (146, ProjectEuler.Problem146.problem)
, (147, ProjectEuler.Problem147.problem)
, (148, ProjectEuler.Problem148.problem)
, (149, ProjectEuler.Problem149.problem)
, (150, ProjectEuler.Problem150.problem)
, (151, ProjectEuler.Problem151.problem)
, (206, ProjectEuler.Problem206.problem)
]
|
Javran/Project-Euler
|
src/ProjectEuler/AllProblems.hs
|
mit
| 11,492 | 0 | 8 | 1,418 | 2,630 | 1,700 | 930 | 311 | 1 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module ScriptQueries where
import Prelude hiding (Word)
import Control.Lens (over, _1, _2, _Left, toListOf, view, _Just)
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.List as List
import Grammar.IO.QueryStage
import Grammar.Common.List
import qualified Grammar.Common.Prepare as Prepare
import Grammar.Common.Round
import Grammar.Common.Types
import qualified Grammar.Greek.Script.Stage as Stage
import Grammar.Greek.Script.Types
import Grammar.Greek.Script.Word
import qualified Primary
queryElision = pure . view (_2 . _1 . _2)
queryLetterMarks
:: ctx :* ((([Letter :* [Mark]] :* Capitalization) :* Elision) :* HasWordPunctuation)
-> [Letter :* [Mark]]
queryLetterMarks = view (_2 . _1 . _1 . _1)
queryMarks
:: ctx :* ((([Letter :* [Mark]] :* Capitalization) :* Elision) :* HasWordPunctuation)
-> [[Mark]]
queryMarks = over traverse snd . fst . fst . fst . snd
queryLetterSyllabicMark
:: ctx :* ((([Letter :* Maybe ContextualAccent :* Maybe Breathing :* Maybe SyllabicMark] :* Capitalization) :* Elision) :* HasWordPunctuation)
-> [Letter :* Maybe SyllabicMark]
queryLetterSyllabicMark = over traverse (\(l, (_, (_, sm))) -> (l, sm)) . fst . fst . fst . snd
queryVowelMarks
:: ctx
:* ((([ (Vowel :* Maybe ContextualAccent :* Maybe Breathing :* Maybe SyllabicMark) :+ ConsonantRho ]
:* Capitalization) :* Elision) :* HasWordPunctuation)
-> [Vowel :* Maybe ContextualAccent :* Maybe Breathing :* Maybe SyllabicMark]
queryVowelMarks = toListOf (_2 . _1 . _1 . _1 . traverse . _Left)
queryVocalicSyllable
:: ctx
:* ((([ [VocalicSyllable :* Maybe ContextualAccent :* Maybe Breathing] :+ [ConsonantRho] ]
:* DiaeresisConvention :* Capitalization) :* Elision) :* HasWordPunctuation)
-> [[VocalicSyllable]]
queryVocalicSyllable = over (traverse . traverse) (view _1) . toListOf (_2 . _1 . _1 . _1 . traverse . _Left)
queryVowelMarkGroups
:: ctx
:* ((([ [Vowel :* Maybe ContextualAccent :* Maybe Breathing :* Maybe SyllabicMark]
:+ [ConsonantRho]
]
:* Capitalization) :* Elision) :* HasWordPunctuation)
-> [[Vowel :* Maybe ContextualAccent :* Maybe Breathing :* Maybe SyllabicMark]]
queryVowelMarkGroups = toListOf (_2 . _1 . _1 . _1 . traverse . _Left)
queryCrasis
:: ctx :* a :* b :* c :* Crasis :* d
-> [Crasis]
queryCrasis = toListOf (_2 . _2 . _2 . _2 . _1)
queryMarkPreservation
:: ctx :* a :* b :* MarkPreservation :* c
-> [MarkPreservation]
queryMarkPreservation = toListOf (_2 . _2 . _2 . _1)
toAccentReverseIndex :: [Maybe ContextualAccent] -> [(Int, ContextualAccent)]
toAccentReverseIndex = onlyAccents . addReverseIndex
where
onlyAccents :: [(Int, Maybe ContextualAccent)] -> [(Int, ContextualAccent)]
onlyAccents = concatMap go
where
go (i, Just x) = [(i, x)]
go _ = []
queryAccentReverseIndexPunctuation
:: ctx :* ([ ([ConsonantRho] :* VocalicSyllable) :* Maybe ContextualAccent ] :* HasWordPunctuation)
:* [ConsonantRho] :* MarkPreservation :* Crasis :* InitialAspiration :* DiaeresisConvention :* Capitalization :* Elision
-> [[Int :* ContextualAccent] :* HasWordPunctuation]
queryAccentReverseIndexPunctuation = pure . over _1 goAll . getPair
where
goAll = toAccentReverseIndex . getAccents
getPair
:: m :* ([ a :* Maybe ContextualAccent ] :* HasWordPunctuation) :* b
-> [ a :* Maybe ContextualAccent ] :* HasWordPunctuation
getPair x = (view (_2 . _1 . _1) x, view (_2 . _1 . _2) x)
getAccents :: [ a :* Maybe ContextualAccent ] -> [Maybe ContextualAccent]
getAccents = over traverse snd
queryAccentReverseIndex
:: ctx :* ([ ([ConsonantRho] :* VocalicSyllable) :* Maybe ContextualAccent ] :* a) :* b
-> [[Int :* ContextualAccent]]
queryAccentReverseIndex = pure . toAccentReverseIndex . fmap snd . view (_2 . _1 . _1)
queryFinalConsonants
:: ctx :* Word
-> [[ConsonantRho]]
queryFinalConsonants = pure . view (_2 . _wordFinalConsonants)
queryElisionSyllables
:: ctx :* Word
-> [InitialAspiration :* [Syllable] :* [ConsonantRho]]
queryElisionSyllables = result
where
result x = case el x of
IsElided -> [(asp x, (syll x, fin x))]
Aphaeresis -> []
NotElided -> []
asp = view (_2 . _wordInitialAspiration)
syll = view (_2 . _wordSyllables)
fin = view (_2 . _wordFinalConsonants)
el = view (_2 . _wordElision)
queryFinalSyllable
:: ctx :* Word
-> [[Syllable] :* [ConsonantRho]]
queryFinalSyllable = result
where
result x = pure (syll x, fin x)
syll = reverse . List.take 1 . reverse . view (_2 . _wordSyllables)
fin = view (_2 . _wordFinalConsonants)
queryIndependentSyllables :: ctx :* Word -> [Syllable]
queryIndependentSyllables = toListOf (_2 . _wordSyllables . traverse)
getInitialSyllable :: Word -> InitialAspiration :* [Syllable]
getInitialSyllable w = (wordInitialAspiration w, take 1 . wordSyllables $ w)
getFinalSyllable :: Word -> [Syllable] :* [ConsonantRho]
getFinalSyllable w = (take 1 . reverse . wordSyllables $ w, wordFinalConsonants w)
uncurrySyllable :: Syllable -> [ConsonantRho] :* VocalicSyllable
uncurrySyllable (Syllable c v) = (c, v)
getInitialVocalicSyllable :: Word -> [InitialAspiration :* VocalicSyllable]
getInitialVocalicSyllable w = result
where
result = case ss of
(Syllable [] v : _) -> pure (asp, v)
_ -> []
(asp, ss) = getInitialSyllable w
queryElisionNextSyllable
:: (ctx :* Word) :* [ctx :* Word] :* [ctx :* Word]
-> [[[ConsonantRho] :* VocalicSyllable] :* [ConsonantRho] :* [InitialAspiration :* [VocalicSyllable]]]
queryElisionNextSyllable (w, (_, nws)) = ens
where
ens = case view (_2 . _wordElision) w of
IsElided -> pure (fmap uncurrySyllable . snd . getInitialSyllable $ snd w, (fc, mn))
Aphaeresis -> []
NotElided -> []
fc = view (_2 . _wordFinalConsonants) w
mn = case nws of
[] -> []
(nw : _) -> pure (view (_2 . _wordInitialAspiration) nw, fmap (snd . uncurrySyllable) . take 1 . view (_2 . _wordSyllables) $ nw)
queryDeNext
:: (ctx :* Word) :* [ctx :* Word] :* [ctx :* Word]
-> [() :* [InitialAspiration :* VocalicSyllable]]
queryDeNext (w, (_, n)) =
case wordSyllables (snd w) of
[Syllable [CR_δ] (VS_Vowel V_ε)] -> pure ((), concatMap (getInitialVocalicSyllable . snd) . take 1 $ n)
_ -> []
queryStage
:: (Show e1, Ord c, Show c)
=> Round
(MilestoneCtx :* e1)
e2
[MilestoneCtx :* (String :* HasWordPunctuation)]
[b]
-> (b -> [c])
-> QueryOptions
-> [Primary.Group]
-> IO ()
queryStage a f = queryStageContext 0 a (f . fst)
queryStageContext
:: (Show e1, Ord c, Show c)
=> Int
-> Round
(MilestoneCtx :* e1)
e2
[MilestoneCtx :* (String :* HasWordPunctuation)]
[b]
-> (b :* [b] :* [b] -> [c])
-> QueryOptions
-> [Primary.Group]
-> IO ()
queryStageContext contextSize stg itemQuery qo gs = queryStageWithContext contextSize stg itemQuery qo Stage.basicWord Stage.fullWordText Stage.forgetHasWordPunctuation $ Prepare.prepareGroups gs
queryFinalConsonantNoElision
:: ctx :* Word
-> [[ConsonantRho]]
queryFinalConsonantNoElision (_, w) = result
where
result = case (el, fc) of
(NotElided, _ : _) -> pure fc
_ -> []
el = wordElision w
fc = wordFinalConsonants w
queryWordBasicAccent :: ctx :* Word -> [[BasicAccent]]
queryWordBasicAccent (_, w) = [toListOf (_wordAccent . _Just . _accentValue) w]
queryWordExtraAccent :: ctx :* Word -> [[ExtraAccents]]
queryWordExtraAccent (_, w) = [toListOf (_wordAccent . _Just . _accentExtra) w]
queryWordAccentPosition :: ctx :* Word -> [[AccentPosition]]
queryWordAccentPosition (_, w) = [toListOf (_wordAccent . _Just . _accentPosition) w]
queryWordForceAcute :: ctx :* Word -> [ForceAcute]
queryWordForceAcute = toListOf (_2 . _wordAccent . _Just . _accentForce)
queryWordAccentWithPosition :: ctx :* Word -> [Maybe (BasicAccent :* AccentPosition)]
queryWordAccentWithPosition = pure . over _Just (\x -> (accentValue x, accentPosition x)) . view (_2 . _wordAccent)
queryWordInitialAspiration :: ctx :* Word -> [InitialAspiration]
queryWordInitialAspiration (_, w) = toListOf (_wordInitialAspiration) w
queryWordDiaeresisConvention :: ctx :* Word -> [DiaeresisConvention]
queryWordDiaeresisConvention (_, w) = toListOf _wordDiaeresisConvention w
queries :: Map String (QueryOptions -> [Primary.Group] -> IO ())
queries = Map.fromList
[ ("elision", queryStage Stage.toElision queryElision)
, ("letter-marks", queryStage Stage.toMarkGroups queryLetterMarks)
, ("marks", queryStage Stage.toMarkGroups queryMarks)
, ("letter-syllabic-mark", queryStage Stage.toMarkSplit queryLetterSyllabicMark)
, ("vocalic-syllable", queryStage Stage.toVocalicSyllable queryVocalicSyllable)
, ("vowel-marks", queryStage Stage.toConsonantMarks queryVowelMarks)
, ("vowel-mark-groups", queryStage Stage.toGroupVowelConsonants queryVowelMarkGroups)
, ("crasis", queryStage Stage.toBreathing queryCrasis)
, ("mark-preservation", queryStage Stage.toBreathing queryMarkPreservation)
, ("accent-reverse-index", queryStage Stage.toBreathing queryAccentReverseIndex)
, ("accent-reverse-index-punctuation", queryStage Stage.toBreathing queryAccentReverseIndexPunctuation)
, ("final-consonants", queryStage Stage.script queryFinalConsonants)
, ("elision-syllables", queryStage Stage.script queryElisionSyllables)
, ("final-syllable", queryStage Stage.script queryFinalSyllable)
, ("independent-syllables", queryStage Stage.script queryIndependentSyllables)
, ("elision-next-syllable", queryStageContext 1 Stage.script queryElisionNextSyllable)
, ("de-next", queryStageContext 1 Stage.script queryDeNext)
, ("final-consonant-no-elision", queryStage Stage.script queryFinalConsonantNoElision)
, ("word-basic-accent", queryStage Stage.script queryWordBasicAccent)
, ("word-extra-accent", queryStage Stage.script queryWordExtraAccent)
, ("word-accent-position", queryStage Stage.script queryWordAccentPosition)
, ("word-force-acute", queryStage Stage.script queryWordForceAcute)
, ("word-accent-with-position", queryStage Stage.script queryWordAccentWithPosition)
, ("word-initial-aspiration", queryStage Stage.script queryWordInitialAspiration)
, ("word-diaeresis-convention", queryStage Stage.script queryWordDiaeresisConvention)
]
|
ancientlanguage/haskell-analysis
|
greek-script/app/ScriptQueries.hs
|
mit
| 10,267 | 0 | 19 | 1,693 | 3,495 | 1,900 | 1,595 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module FacebookRSS.Facebook (fetchFeed) where
import Data.Maybe
import Data.Aeson
import Data.Facebook.Feed
import Network.HTTP.Client
import Network.HTTP.Client.TLS (tlsManagerSettings)
fetchFeed :: String -> String -> IO (Maybe Feed)
fetchFeed token id =
newManager tlsManagerSettings
>>= httpLbs req
>>= return . decode . responseBody
where
req = fromJust . parseUrl $ fetchFeedUrl token id
fetchFeedUrl :: String -> String -> String
fetchFeedUrl token id =
"https://graph.facebook.com/v2.7/"
++ id
++ "?access_token=" ++ token
++ "&fields=name,about,link,feed{message,id,created_time,permalink_url}"
|
poying/facebook-rss
|
FacebookRSS/Facebook.hs
|
mit
| 671 | 0 | 9 | 105 | 159 | 86 | 73 | 19 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Web.FreeAgent.Util where
import Control.Applicative
import Control.Error.Util
import Control.Monad (liftM, (>=>))
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trans.Either
import Data.Aeson
import Data.Aeson.Types
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Internal as BLI
import qualified Data.Text as T
import Network.Http.Client
import OpenSSL (withOpenSSL)
import System.IO.Streams (InputStream, stdout)
import System.IO.Streams.Attoparsec
import System.IO.Streams.Debug
toStrict :: BLI.ByteString -> C8.ByteString
toStrict = BS.concat . BL.toChunks
fromStrict :: BS.ByteString -> BL.ByteString
fromStrict bs | BS.null bs = BLI.Empty
| otherwise = BLI.Chunk bs BLI.Empty
baseFAHost, baseFAUrl :: BS.ByteString
baseFAHost = "api.irisopenbooks.co.uk"
baseFAUrl = "/v2/"
newtype FAMonad m a = FAMonad { runFA :: EitherT String m a }
deriving (Functor, Monad, MonadIO)
runFreeAgent :: FAMonad m a -> m (Either String a)
runFreeAgent = runEitherT . runFA
faRequest :: Method -> BS.ByteString -> BS.ByteString -> IO Request
faRequest meth path token = buildRequest $ do
http meth $ baseFAUrl `BS.append` path
setHostname baseFAHost 443
setAccept "text/json"
setHeader "Authorization" $ "Bearer " `BS.append` token
noteFA :: (MonadIO m) => String -> Maybe a -> FAMonad m a
noteFA msg = FAMonad . EitherT . liftM (note msg) . return
liftFA :: Monad m => Either String a -> FAMonad m a
liftFA = FAMonad . hoistEither
aesonHandler :: FromJSON a => Response -> InputStream BS.ByteString -> IO (Maybe a)
aesonHandler _ = parseJSONFromStream
debugAesonHandler :: Response -> InputStream BS.ByteString -> IO Value
debugAesonHandler _ = debugInput id "AESON-HANDLER" stdout >=> parseValueFromStream
parseJSONFromStream :: FromJSON a => InputStream C8.ByteString -> IO (Maybe a)
parseJSONFromStream = parseFromStream $ parseMaybe parseJSON <$> json'
parseValueFromStream :: InputStream BS.ByteString -> IO Value
parseValueFromStream = parseFromStream json'
extractVal :: (FromJSON a) => T.Text -> Value -> Parser a
extractVal key = withObject "extract" (.: key)
--apiCall :: Token -> IO (Maybe Object)
apiCall
:: (FromJSON a, MonadIO m) =>
C8.ByteString -> C8.ByteString -> FAMonad m a
apiCall token url = do
resp <- liftIO . withOpenSSL $ do
ctx <- baselineContextSSL
c <- openConnectionSSL ctx baseFAHost 443
r <- faRequest GET url token
sendRequest c r emptyBody
val <- receiveResponse c $ const parseValueFromStream
closeConnection c
return $ parseEither (parseJSON) val
FAMonad $ hoistEither resp
--noteFA ("No object decoded for "++ C8.unpack url) resp -- decode . fromStrict $ resp
extractApiVal :: (MonadIO m, FromJSON a) => T.Text -> Value -> FAMonad m a
extractApiVal key = liftFA . parseEither (extractVal key)
|
perurbis/hfreeagent
|
src/Web/FreeAgent/Util.hs
|
mit
| 3,360 | 0 | 13 | 751 | 918 | 484 | 434 | 69 | 1 |
module Euler.Problem7Spec ( spec ) where
import Helper
import Euler.Problem7
spec :: Spec
spec = do
describe "primeNumber" $ do
it "2nd" $ do
(primeNumber 2 :: Int) `shouldBe` (3 :: Int)
it "3rd" $ do
(primeNumber 3 :: Int) `shouldBe` (5 :: Int)
it "6th" $ do
(primeNumber 6 :: Int) `shouldBe` (13 :: Int)
|
slogsdon/haskell-exercises
|
pe/testsuite/specs/Euler/Problem7Spec.hs
|
mit
| 341 | 0 | 15 | 91 | 141 | 76 | 65 | 12 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-|
Module : PostgREST.Auth
Description : PostgREST authorization functions.
This module provides functions to deal with the JWT authorization (http://jwt.io).
It also can be used to define other authorization functions,
in the future Oauth, LDAP and similar integrations can be coded here.
Authentication should always be implemented in an external service.
In the test suite there is an example of simple login function that can be used for a
very simple authentication system inside the PostgreSQL database.
-}
module PostgREST.Auth (
containsRole
, jwtClaims
, tokenJWT
, JWTAttempt(..)
) where
import Protolude
import Control.Lens
import Data.Aeson (Value (..), parseJSON, toJSON)
import Data.Aeson.Lens
import Data.Aeson.Types (parseMaybe, emptyObject, emptyArray)
import qualified Data.Vector as V
import qualified Data.HashMap.Strict as M
import Data.Maybe (fromJust)
import Data.Time.Clock (NominalDiffTime)
import qualified Web.JWT as JWT
{-|
Possible situations encountered with client JWTs
-}
data JWTAttempt = JWTExpired
| JWTInvalid
| JWTMissingSecret
| JWTClaims (M.HashMap Text Value)
deriving Eq
{-|
Receives the JWT secret (from config) and a JWT and returns a map
of JWT claims.
-}
jwtClaims :: Maybe JWT.Secret -> Text -> NominalDiffTime -> JWTAttempt
jwtClaims _ "" _ = JWTClaims M.empty
jwtClaims secret jwt time =
case secret of
Nothing -> JWTMissingSecret
Just s ->
let mClaims = toJSON . JWT.claims <$> JWT.decodeAndVerifySignature s jwt in
case isExpired <$> mClaims of
Just True -> JWTExpired
Nothing -> JWTInvalid
Just False -> JWTClaims $ value2map $ fromJust mClaims
where
isExpired claims =
let mExp = claims ^? key "exp" . _Integer
in fromMaybe False $ (<= time) . fromInteger <$> mExp
value2map (Object o) = o
value2map _ = M.empty
{-|
Receives the JWT secret (from config) and a JWT and a JSON value
and returns a signed JWT.
-}
tokenJWT :: JWT.Secret -> Value -> Text
tokenJWT secret (Array arr) =
let obj = if V.null arr then emptyObject else V.head arr
jcs = parseMaybe parseJSON obj :: Maybe JWT.JWTClaimsSet in
JWT.encodeSigned JWT.HS256 secret $ fromMaybe JWT.def jcs
tokenJWT secret _ = tokenJWT secret emptyArray
{-|
Whether a response from jwtClaims contains a role claim
-}
containsRole :: JWTAttempt -> Bool
containsRole (JWTClaims claims) = M.member "role" claims
containsRole _ = False
|
Skyfold/postgrest
|
src/PostgREST/Auth.hs
|
mit
| 2,691 | 0 | 14 | 685 | 525 | 283 | 242 | -1 | -1 |
module SudokuHelper where
prettyPrint l a [] = ""
prettyPrint l a (x:xs)
| a == l = "\n"++(show x)++" " ++ (prettyPrint l 1 xs)
| otherwise = (show x)++" "++(prettyPrint l (a+1) xs)
pretty xs = prettyPrint 9 0 xs
sEasy = [3,0,6,5,0,8,4,0,0
,5,2,0,0,0,0,0,0,0
,0,8,7,0,0,0,0,3,1
,0,0,3,0,1,0,0,8,0
,9,0,0,8,6,3,0,0,5
,0,5,0,0,9,0,6,0,0
,1,3,0,0,0,0,2,5,0
,0,0,0,0,0,0,0,7,4
,0,0,5,2,0,6,3,0,0] :: [Int]
sHard=[0,0,0,0,6,0,0,8,0,
0,2,0,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,0,
0,7,0,0,0,0,1,0,2,
5,0,0,0,3,0,0,0,0,
0,0,0,0,0,0,4,0,0,
0,0,4,2,0,1,0,0,0,
3,0,0,7,0,0,6,0,0,
0,0,0,0,0,0,0,5,0] :: [Int]
|
ztuowen/sudoku
|
SudokuHelper.hs
|
mit
| 729 | 0 | 10 | 206 | 638 | 403 | 235 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-canarysetting.html
module Stratosphere.ResourceProperties.ApiGatewayDeploymentCanarySetting where
import Stratosphere.ResourceImports
-- | Full data type definition for ApiGatewayDeploymentCanarySetting. See
-- 'apiGatewayDeploymentCanarySetting' for a more convenient constructor.
data ApiGatewayDeploymentCanarySetting =
ApiGatewayDeploymentCanarySetting
{ _apiGatewayDeploymentCanarySettingPercentTraffic :: Maybe (Val Double)
, _apiGatewayDeploymentCanarySettingStageVariableOverrides :: Maybe Object
, _apiGatewayDeploymentCanarySettingUseStageCache :: Maybe (Val Bool)
} deriving (Show, Eq)
instance ToJSON ApiGatewayDeploymentCanarySetting where
toJSON ApiGatewayDeploymentCanarySetting{..} =
object $
catMaybes
[ fmap (("PercentTraffic",) . toJSON) _apiGatewayDeploymentCanarySettingPercentTraffic
, fmap (("StageVariableOverrides",) . toJSON) _apiGatewayDeploymentCanarySettingStageVariableOverrides
, fmap (("UseStageCache",) . toJSON) _apiGatewayDeploymentCanarySettingUseStageCache
]
-- | Constructor for 'ApiGatewayDeploymentCanarySetting' containing required
-- fields as arguments.
apiGatewayDeploymentCanarySetting
:: ApiGatewayDeploymentCanarySetting
apiGatewayDeploymentCanarySetting =
ApiGatewayDeploymentCanarySetting
{ _apiGatewayDeploymentCanarySettingPercentTraffic = Nothing
, _apiGatewayDeploymentCanarySettingStageVariableOverrides = Nothing
, _apiGatewayDeploymentCanarySettingUseStageCache = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-canarysetting.html#cfn-apigateway-deployment-canarysetting-percenttraffic
agdcsPercentTraffic :: Lens' ApiGatewayDeploymentCanarySetting (Maybe (Val Double))
agdcsPercentTraffic = lens _apiGatewayDeploymentCanarySettingPercentTraffic (\s a -> s { _apiGatewayDeploymentCanarySettingPercentTraffic = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-canarysetting.html#cfn-apigateway-deployment-canarysetting-stagevariableoverrides
agdcsStageVariableOverrides :: Lens' ApiGatewayDeploymentCanarySetting (Maybe Object)
agdcsStageVariableOverrides = lens _apiGatewayDeploymentCanarySettingStageVariableOverrides (\s a -> s { _apiGatewayDeploymentCanarySettingStageVariableOverrides = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-canarysetting.html#cfn-apigateway-deployment-canarysetting-usestagecache
agdcsUseStageCache :: Lens' ApiGatewayDeploymentCanarySetting (Maybe (Val Bool))
agdcsUseStageCache = lens _apiGatewayDeploymentCanarySettingUseStageCache (\s a -> s { _apiGatewayDeploymentCanarySettingUseStageCache = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/ApiGatewayDeploymentCanarySetting.hs
|
mit
| 2,968 | 0 | 12 | 251 | 343 | 196 | 147 | 32 | 1 |
module Main (main) where
import Nauva.Client
import Nauva.Product.Template.App
main :: IO ()
main = runClient app
|
wereHamster/nauva
|
product/template/app/native/Main.hs
|
mit
| 117 | 0 | 6 | 19 | 39 | 23 | 16 | 5 | 1 |
--
-- riot/Riot/UI.hs
--
-- Copyright (c) Tuomo Valkonen 2004-2005.
--
-- 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.
--
-- Module info {{{
module Riot.UI(
Riot.UI.init,
deinit,
new_status,
set_topinfo,
set_entries,
set_callbacks,
change_entry_type,
refresh,
redraw,
snapshot,
-- Low-level drawing
draw_textarea,
draw_topinfo,
draw_midinfo,
draw_botinfo,
draw_entries,
draw_helparea,
draw_botinfo_help,
clear_message,
-- Low-level
message_line,
getCh,
get_key,
get_key_,
get_size,
find_viewlist_pos,
entries_viewlist,
n_entries_viewed,
do_vscroll,
do_hscroll,
max_vscroll,
textarea_height,
entryarea_height,
helparea_height,
do_selectentry,
do_actentry,
do_delentry,
check_everything,
check_entryarea,
mk_snapshot,
do_tag,
do_clear_tags,
do_expand,
do_collapse_p,
selected_entry_loc,
do_move_tagged,
do_delete,
do_vscroll_help,
-- Very low-level
fill_to_eol,
cset_attr,
creset_attr,
waddstr,
-- Misc, to be moved elsewhere
lnth
)where
-- }}}
-- Imports {{{
import qualified Curses.Curses as Curses
import qualified Control.Exception
import Time(CalendarTime)
import IO(stdin)
import Control.Monad(liftM, when)
import Maybe
import Char
import List(find,init,intersperse)
import Control.Monad.Trans(MonadIO, liftIO)
import System.Posix.Signals
import System.Posix.IO (setFdOption, FdOption(..))
import Riot.Style(UIAttr(..), init_uiattr, default_uiattr, StyleSpec)
import Riot.Entry
import Riot.Riot
import qualified Riot.Editor as Editor
import qualified Riot.KeyMap as KeyMap
-- }}}
-- Helper functions {{{
text_n_lines :: String -> Int
text_n_lines text =
length (lines text)
text_n_columns :: String -> Int
text_n_columns text =
foldl max 0 (map length (lines text))
safetail [] = []
safetail (x:xs) = xs
maybehead [] = Nothing
maybehead (x:xs) = Just x
left_align w t =
take w (t ++ repeat ' ')
lnth n l = lookup n $ zip [0..] l
mpass :: (a -> b) -> Maybe a -> Maybe b
mpass f Nothing = Nothing
mpass f (Just x) = Just $ f x
-- }}}
-- Status {{{
undo_count = 100
new_status :: Entry a => KeyMap -> Status a
new_status km = Status {
attr = default_uiattr,
topinfo_text = "--",
textarea_hscroll = 0,
textarea_vscroll = 0,
entryarea_vscroll = 0,
helparea_vscroll = 0,
screen_width = 80,
screen_height = 24,
entries = [],
entries_fname = Nothing,
selected_entry = 0,
active_entry = Nothing,
undo_buffer = [],
redo_buffer = [],
save_callback = save_disabled,
new_callback = new_disabled,
unsaved_changes = False,
mode = DefaultMode,
active_key_map = km,
previous_search = Nothing
}
new_disabled _ _ = error "No handler to create new entries set."
save_disabled _ _ = error "No save handler set."
set_topinfo :: Entry a => Status a -> String -> Status a
set_topinfo s v = s{topinfo_text = v}
set_entries :: Entry a => Status a -> [EntryTree a] -> (Maybe String) -> Status a
set_entries s e fname =
s{
entries = e,
entries_fname = fname,
selected_entry = 0,
active_entry = Nothing,
entryarea_vscroll = 0,
textarea_vscroll = 0,
textarea_hscroll = 0,
unsaved_changes = False,
undo_buffer = [],
redo_buffer = []
}
change_entry_type :: (Entry a, Entry b) => Status a -> Status b
change_entry_type s =
(new_status (active_key_map s)) {
attr = attr s,
topinfo_text = topinfo_text s,
screen_width = screen_width s,
screen_height = screen_height s
}
set_callbacks :: Entry a =>
Status a
-> (String -> [EntryTree a] -> RI a ())
-> (String -> CalendarTime -> RI a a)
-> Status a
set_callbacks s save_cb new_cb =
s{save_callback = save_cb, new_callback = new_cb}
-- }}}
-- Sizes {{{
entryarea_height s = max 1 $ (screen_height s - 3) `div` 2
topinfo_line s = 0
midinfo_line s = (entryarea_height s) + 1
botinfo_line s = (max (screen_height s - 1) (midinfo_line s + 2)) - 1
message_line s = (botinfo_line s) + 1
entryarea_startline s = 1
entryarea_endline s = midinfo_line s - 1
textarea_startline s = midinfo_line s + 1
textarea_endline s = botinfo_line s - 1
textarea_height s = (textarea_endline s) - (textarea_startline s) + 1
helparea_startline s = 1
helparea_endline s = botinfo_line s - 1
helparea_height s = (helparea_endline s) - (helparea_startline s) + 1
-- }}}
-- Viewlist indexing {{{
valid_entry s e = 0<=e && e<n_entries_viewed s
entrytree_viewlist :: Entry a => [EntryTree a] -> [(Loc, EntryTree a)]
entrytree_viewlist et =
entrytree_map f et
where
f e chview loc =
if entrytree_expanded e then
(loc, e):chview
else
[(loc, e)]
entries_viewlist s = entrytree_viewlist (entries s)
entries_viewlist_plain s = snd $ unzip $ entries_viewlist s
entries_viewlist_loc s = fst $ unzip $ entries_viewlist s
viewlist_entry s e = lnth e (entries_viewlist_plain s)
viewlist_entry_loc s e = fromJust $ lnth e (entries_viewlist_loc s)
selected_entry_loc s = viewlist_entry_loc s (selected_entry s)
active_entry_loc s = mpass (viewlist_entry_loc s) (active_entry s)
n_entries_viewed s = length $ entries_viewlist s
find_viewlist_pos et loc =
viewlist_pos 0 et loc
where
viewlist_pos cpos (e:_) (Loc (0:[])) = cpos
viewlist_pos cpos (e:_) (Loc (0:ll)) =
case entrytree_expanded e of
False -> cpos -- Go to parent
True -> viewlist_pos (cpos+1) (entrytree_children e) (Loc ll)
viewlist_pos cpos (e:et) (Loc (l:ll)) =
viewlist_pos (cpos+1+nchv) et $ Loc ((l-1):ll)
where
nchv = case entrytree_expanded e of
False -> 0
True -> length $ entrytree_viewlist $ entrytree_children e
viewlist_pos _ _ _ = error "Invalid location"
-- }}}
-- Initialisation {{{
get_size :: Entry a => Status a -> IO (Status a)
get_size s = do
(h, w) <- Curses.scrSize
return s{screen_width = w, screen_height = h}
init :: Entry a => Status a -> [StyleSpec] -> IO (Status a)
init status styles = do
Curses.initCurses
Curses.resetParams
setFdOption 0 NonBlockingRead False
a <- init_uiattr styles
get_size status{attr = a}
deinit :: IO ()
deinit = do
Curses.endWin
return ()
-- }}}
-- Drawing {{{
waddstr w s = Curses.wAddStr w s >> return ()
cset_attr (a, p) = do
Curses.wAttrSet Curses.stdScr (a, p)
creset_attr = do
cset_attr (Curses.attr0, Curses.Pair 0)
fill_to_eol = do
(h, w) <- Curses.scrSize
(y, x) <- Curses.getYX Curses.stdScr
waddstr Curses.stdScr (replicate (max 0 (w-x)) ' ')
draw_lines s d l_first l_last skip f = do
Curses.wMove Curses.stdScr l_first 0
do_draw_lines s (drop skip d) l_first l_last skip f
where
do_draw_lines s d l l_last nr f
| l>l_last = return ()
| otherwise = do
f s (maybehead d) nr
do_draw_lines s (safetail d) (l+1) l_last (nr+1) f
-- Help area
draw_helparea :: Entry a => Status a -> String -> IO ()
draw_helparea s help_text =
do_draw_text s help_text hs vs sl el
where hs = 0
vs = helparea_vscroll s
sl = helparea_startline s
el = helparea_endline s
-- Text area
textarea_text :: Entry a => Status a -> String
textarea_text s =
case active_entry s of
Nothing -> []
Just e -> maybe "" entry_text $ viewlist_entry s e
next_tab_stop pos = ((pos `div` 8) + 1) * 8
do_tab_stops pos [] = []
do_tab_stops pos ('\t':ss) =
replicate (nxt - pos) ' ' ++ (do_tab_stops nxt ss)
where
nxt = next_tab_stop pos
do_tab_stops pos (s:ss) = s:(do_tab_stops (pos + 1) ss)
do_draw_text s text hs vs sl el = do
cset_attr (attr_text $ attr s)
draw_lines s (map (do_tab_stops 0) $ lines text) sl el vs drawl
creset_attr
where
w = screen_width s
drawl s Nothing _ =
fill_to_eol
drawl s (Just l) _ =
waddstr Curses.stdScr (take w $ drop hs $ l ++ repeat ' ')
do_draw_textarea s text = do
do_draw_text s text hs vs sl el
where
hs = textarea_hscroll s
vs = textarea_vscroll s
sl = textarea_startline s
el = textarea_endline s
draw_textarea :: Entry a => Status a -> IO ()
draw_textarea status =
do_draw_textarea status (textarea_text status)
-- Info lines
botinfo_text :: Entry a => Status a -> String
botinfo_text s =
case active_entry s of
Nothing -> "--"
Just e -> maybe "--" entry_title $ viewlist_entry s e
midinfo_text :: Entry a => Status a -> String
midinfo_text s =
fromMaybe "(no file)" (entries_fname s)
++ if unsaved_changes s then " [modified]" else ""
do_draw_infoline_align status line left right = do
Curses.wMove Curses.stdScr line 0
cset_attr (attr_infoline $ attr status)
waddstr Curses.stdScr ((take n_l left_)++(take n_r right_))
creset_attr
where
left_ = left ++ (repeat ' ')
right_ = ' ':right
w = screen_width status
n_r = min w (length right_)
n_l = max 0 (w-n_r)
do_draw_infoline status line text =
do_draw_infoline_align status line text ""
mk_n_of_m n m =
"("++(show n)++"/"++(show m)++") "
draw_topinfo :: Entry a => Status a -> IO ()
draw_topinfo s =
let help_list = KeyMap.gen_tophelp_text (active_key_map s)
help_text = concat $ intersperse ", " help_list
in do_draw_infoline s (topinfo_line s) ((topinfo_text s) ++ help_text)
draw_topinfo_help s = draw_topinfo s -- FIXME
draw_midinfo :: Entry a => Status a -> IO ()
draw_midinfo s =
do_draw_infoline_align s l t (mk_n_of_m n m)
where
l = midinfo_line s
t = midinfo_text s
m = length (entries_viewlist_plain s)
n = 1 + selected_entry s
draw_botinfo :: Entry a => Status a -> IO ()
draw_botinfo s =
do_draw_infoline_align s l t (mk_n_of_m n m)
where
l = botinfo_line s
t = botinfo_text s
m = text_n_lines (textarea_text s)
n = min m $ (textarea_vscroll s)+(textarea_height s)
draw_botinfo_help :: Entry a => Status a -> String -> IO ()
draw_botinfo_help s help_text =
do_draw_infoline_align s l "Help" (mk_n_of_m n m)
where
l = botinfo_line s
m = text_n_lines help_text
n = min m $ (helparea_vscroll s)+(helparea_height s)
-- Entries
entry_attr s nr =
case (nr == selected_entry s, Just nr == active_entry s) of
(False, False) -> attr_entry $ attr s
(True, False) -> attr_entry_sel $ attr s
(False, True) -> attr_entry_act $ attr s
(True, True) -> attr_entry_act_sel $ attr s
do_draw_entry s Nothing _ = do
cset_attr (attr_entry $ attr s)
fill_to_eol
creset_attr
do_draw_entry s (Just (Loc loc, e)) nr = do
cset_attr (entry_attr s nr)
waddstr Curses.stdScr (left_align w l)
creset_attr
where
w = screen_width s
bullet = case (entrytree_children e) of
[] -> " - " --[' ', Curses.bullet, ' ']
otherwise -> " + "
indent = replicate (3 * (length loc - 1)) ' '
tg = case entrytree_tagged e of
True -> "*"
False -> " "
flags = left_align 4 (entry_flags e)
l = concat [" ", flags, tg, " ", indent, bullet, entry_title e]
draw_entries :: Entry a => Status a -> IO ()
draw_entries s =
draw_lines s (entries_viewlist s) sl el vs do_draw_entry
where
vs = entryarea_vscroll s
sl = entryarea_startline s
el = entryarea_endline s
-- Refresh
redraw :: Entry a => RI a ()
redraw = do
status <- get_status
case mode status of
DefaultMode -> liftIO $ do
--Curses.wclear Curses.stdScr
draw_topinfo status
draw_entries status
draw_midinfo status
draw_textarea status
draw_botinfo status
clear_message status
HelpMode text -> liftIO $ do
draw_topinfo_help status
draw_helparea status text
draw_botinfo_help status text
clear_message status
clear_message :: Entry a => Status a -> IO ()
clear_message s = do
cset_attr (attr_message $ attr s)
Curses.wMove Curses.stdScr (message_line s) 0
fill_to_eol
Curses.refresh
refresh :: Entry a => RI a ()
refresh = do
redraw
liftIO $ Curses.refresh
-- }}}
-- Text scrolling {{{
max_scroll_ :: Int -> Int -> Int
max_scroll_ item_s view_s =
max 0 (item_s - view_s)
text_max_hscroll :: String -> (Int, Int) -> Int
text_max_hscroll text (_, view_w) =
max_scroll_ (text_n_columns text) view_w
text_max_vscroll :: String -> (Int, Int) -> Int
text_max_vscroll text (view_h, _) =
max_scroll_ (text_n_lines text) view_h
textarea_size :: Entry a => Status a -> (Int, Int)
textarea_size s =
(textarea_height s, screen_width s)
helparea_size :: Entry a => Status a -> (Int, Int)
helparea_size s =
(helparea_height s, screen_width s)
calc_scroll s asc csc_fn msc_fn text size =
max 0 (min msc (csc + asc))
where
msc = msc_fn text size
csc = csc_fn s
do_hscroll :: Entry a => Int -> Status a -> Status a
do_hscroll amount s =
s{textarea_hscroll = sc}
where
sc = calc_scroll s amount textarea_hscroll text_max_hscroll
(textarea_text s) (textarea_size s)
do_vscroll :: Entry a => Int -> Status a -> Status a
do_vscroll amount s =
s{textarea_vscroll = sc}
where
sc = calc_scroll s amount textarea_vscroll text_max_vscroll
(textarea_text s) (textarea_size s)
do_vscroll_help :: Entry a => Int -> Status a -> Status a
do_vscroll_help amount s =
s{helparea_vscroll = sc}
where
sc = calc_scroll s amount helparea_vscroll text_max_vscroll
text (helparea_size s)
text = case mode s of
HelpMode t -> t
_ -> ""
max_vscroll :: Entry a => Status a -> Int
max_vscroll s =
text_max_vscroll (textarea_text s) (textarea_height s, screen_width s)
max_hscroll :: Entry a => Status a -> Int
max_hscroll s =
text_max_hscroll (textarea_text s) (textarea_height s, screen_width s)
check_vscroll :: Entry a => Status a -> Status a
check_vscroll s =
case textarea_vscroll s > max_vscroll s of
True -> s{textarea_vscroll = max_vscroll s}
False -> s
check_hscroll :: Entry a => Status a -> Status a
check_hscroll s =
case textarea_hscroll s > max_hscroll s of
True -> s{textarea_hscroll = max_hscroll s}
False -> s
check_textarea :: Entry a => Status a -> Status a
check_textarea = check_vscroll . check_hscroll
-- }}}
-- Entry selection {{{
check_active :: Entry a => Status a -> Status a
check_active s =
case active_entry s of
Just e | e >= n_entries_viewed s -> s{active_entry = Nothing}
otherwise -> s
check_selected :: Entry a => Status a -> Status a
check_selected s =
case selected_entry s >= n_entries_viewed s of
True -> s{selected_entry = max 0 $ (n_entries_viewed s) - 1}
false -> s
check_e_vscroll :: Entry a => Status a -> Status a
check_e_vscroll s =
do_selectentry (selected_entry s) s
check_entryarea :: Entry a => Status a -> Status a
check_entryarea s = check_e_vscroll $ check_selected $ check_active s
check_everything :: Entry a => Status a -> Status a
check_everything = check_textarea . check_entryarea
do_selectentry n s | valid_entry s n =
if n > l_e then
s{selected_entry = n, entryarea_vscroll = n - h + 1}
else if n < f_e then
s{selected_entry = n, entryarea_vscroll = n}
else
s{selected_entry = n}
where
n_entries = length (entries_viewlist s)
h = entryarea_height s
f_e = entryarea_vscroll s
l_e = f_e + h - 1
do_selectentry 0 s | n_entries_viewed s == 0 =
s{selected_entry = 0, entryarea_vscroll = 0}
do_selectentry _ _ = error "Invalid entry"
do_actentry e s | valid_entry s e =
s{active_entry = Just e, textarea_vscroll = 0, textarea_hscroll = 0}
-- }}}
-- Expand/collapse {{{
update_entries s et =
s{entries = et, active_entry = ae, selected_entry = se}
where
ae = mpass (find_viewlist_pos et) (active_entry_loc s)
se = find_viewlist_pos et (selected_entry_loc s)
do_colexp_loc :: Entry a =>
([EntryTree a] -> Loc -> Maybe [EntryTree a]) -> Status a -> Loc
-> Status a
do_colexp_loc fn s loc =
case fn (entries s) loc of
Nothing -> s
Just et -> check_everything $ update_entries s et
do_colexp :: Entry a =>
([EntryTree a] -> Loc -> Maybe [EntryTree a]) -> Status a -> Int
-> Status a
do_colexp fn s e = do_colexp_loc fn s $ viewlist_entry_loc s e
do_expand :: Entry a => Status a -> Int -> Status a
do_expand s e | valid_entry s e =
do_colexp entrytree_expand s e
do_collapse :: Entry a => Status a -> Int -> Status a
do_collapse s e | valid_entry s e =
do_colexp entrytree_collapse s e
do_collapse_p :: Entry a => Status a -> Int -> Status a
do_collapse_p s e | valid_entry s e =
do_colexp entrytree_collapse_p s e
-- }}}
-- Snapshotting {{{
mk_snapshot :: Entry a => Status a -> UndoInfo a
mk_snapshot s =
UndoInfo (selected_entry s) (active_entry s)
(unsaved_changes s) (entries s)
snapshot :: Entry a => Status a -> Status a
snapshot s =
s{undo_buffer = nub, redo_buffer=[], unsaved_changes=True}
where
(rb, ub) = (redo_buffer s, undo_buffer s)
nub = take undo_count $ (mk_snapshot s):(rb ++ reverse rb ++ ub)
-- }}}
-- Entry and entry tree manipulation {{{
rm_new_loc_vl [] rmlocv = Nothing
rm_new_loc_vl ((loc, _):vv) rmlocv =
case loc_rm_effect loc rmlocv of
Nothing -> rm_new_loc_vl vv rmlocv
just_loc -> just_loc
rm_new_loc :: Entry a => Status a -> [Loc] -> Int -> Maybe Loc
rm_new_loc s rmlocv e =
case loc_rm_effect loc rmlocv of
Nothing ->
case rm_new_loc_vl vl_after rmlocv of
Nothing -> rm_new_loc_vl vl_before rmlocv
just_loc -> just_loc
just_loc -> just_loc
where
loc@(Loc loc_) = viewlist_entry_loc s e
vl_after = drop (e+1) $ entries_viewlist s
vl_before = reverse $ take e $ entries_viewlist s
rm_get_new_entry :: Entry a =>
Status a -> [Loc] -> [EntryTree a] -> Int -> Maybe Int
rm_get_new_entry s rmlocv etn e =
mpass (find_viewlist_pos etn) (rm_new_loc s rmlocv e)
do_delete :: Entry a => Status a -> [Loc] -> Status a
do_delete s rmlocv =
check_everything (snapshot s){entries = etn,
selected_entry = nsel,
active_entry = nact}
where
et = entries s
etn = entrytree_remove et rmlocv
gn = rm_get_new_entry s rmlocv etn
nsel = fromMaybe 0 $ gn (selected_entry s)
nact = maybe Nothing gn (active_entry s)
mv_get_new_entry :: Entry a =>
Status a -> InsertWhere -> [Loc] -> [EntryTree a] -> Int -> Maybe Int
mv_get_new_entry s insw mvlocv etn e =
mpass (find_viewlist_pos etn)
$ mpass (\l -> loc_ins_effect l insw (length mvlocv))
(rm_new_loc s mvlocv e)
do_move :: Entry a =>
Status a -> InsertWhere -> [Loc] -> Status a
do_move s insw mvlocv =
check_everything (snapshot s){entries = etn,
selected_entry = nsel,
active_entry = nact}
where
et = entries s
etn = fst $ entrytree_move et insw mvlocv
gn = mv_get_new_entry s insw mvlocv etn
nsel = fromMaybe 0 $ gn (selected_entry s)
nact = maybe Nothing gn (active_entry s)
do_delentry s e =
do_delete s [viewlist_entry_loc s e]
do_move_tagged :: Entry a => Status a -> InsertWhere -> Status a
do_move_tagged s insw =
do_clear_tags $ do_move s insw tagged
where
tagged = entrytree_get_tagged (entries s)
do_tag s act e =
maybe s (\nent_ -> s{entries = nent_}) etn
where
etn = entrytree_tag (entries s) (viewlist_entry_loc s e) act
do_clear_tags s =
maybe s (\nent_ -> s{entries = nent_}) etn
where
etn = entrytree_clear_tags (entries s)
-- }}}
-- getCh {{{
getCh :: IO (Maybe Curses.Key)
getCh = do
v <- Curses.getch
return $ case v of
(-1) -> Nothing
k_ -> Just $ Curses.decodeKey k_
get_key_ :: IO (Maybe Curses.Key)
get_key_ = do
Curses.cBreak True
getCh
get_key :: Entry a => RI a () -> RI a Curses.Key
get_key refresh_fn = do
k <- liftIO $ get_key_
case k of
Nothing -> get_key refresh_fn
Just Curses.KeyResize -> do
mod_status_io get_size
refresh_fn
get_key refresh_fn
Just k -> return k
-- }}}
|
opqdonut/riot
|
Riot/UI.hs
|
gpl-2.0
| 21,294 | 0 | 13 | 5,900 | 7,290 | 3,688 | 3,602 | 552 | 6 |
{-# LANGUAGE OverloadedStrings #-}
module RainbowMode
( rainbowParenMode
) where
import Data.Foldable (asum)
import Data.Maybe
import Yi hiding (super)
import Yi.Mode.Common (fundamentalMode)
import Yi.Modes
import Yi.Lexer.Alex
import Yi.Syntax
import Text.Regex.Applicative
data Paren
= Open !Point
| Close !Point
styleForLevel :: Level -> StyleName
styleForLevel = (colors !!) . (`rem` length colors)
where
colors =
[ importStyle
, stringStyle
, numberStyle
, dataConstructorStyle
]
tokenPoint :: Paren -> Point
tokenPoint (Open p) = p
tokenPoint (Close p) = p
rainbowParenMode :: Mode RainbowStorage
rainbowParenMode = fundamentalMode
{ modeName = "rainbow"
, modeHL = ExtHL rainbowHighlighter
, modeGetStrokes = rainbowGetStrokes
}
type Level = Int
type RainbowStorage = [(Paren, Level)]
rainbowHighlighter :: Highlighter RainbowStorage RainbowStorage
rainbowHighlighter = SynHL
[]
(\scanner _point _oldTokens ->
fromMaybe
[]
(tokenize
(scanRun scanner (scanInit scanner))))
(\tokens _windowRef -> tokens)
(\_refToRegion tokens -> tokens)
rainbowGetStrokes :: RainbowStorage -> Point -> Point -> Point -> [Stroke]
rainbowGetStrokes tokens _point _begin _end =
map
(\(token, level) ->
let pos = tokenPoint token
in Span pos (styleForLevel level) (pos + 1))
tokens
tokenize :: [(Point, Char)] -> Maybe [(Paren, Int)]
tokenize input = fmap assignLevels (input =~ lexTokens)
lexTokens :: RE (Point, Char) [Paren]
lexTokens =
fmap
catMaybes
(many
(asum
[ Just <$> lexToken
, Nothing <$ lexIrrelevant
]))
lexToken :: RE (Point, Char) Paren
lexToken = asum
[ Open . fst <$> psym ((== '(') . snd)
, Close . fst <$> psym ((== ')') . snd)
]
lexIrrelevant :: RE (Point, Char) ()
lexIrrelevant = () <$ many (psym ((`notElem` ['(', ')']) . snd))
assignLevels :: [Paren] -> [(Paren, Int)]
assignLevels = go [] 0
where
go acc _ [] = reverse acc
go acc 0 (Close p : tokens) = go ((Close p, 0) : acc) 0 tokens
go acc level (t@(Open _) : tokens) =
go ((t, level) : acc) (level + 1) tokens
go acc level (t@(Close _) : tokens) =
go ((t, level - 1) : acc) (level - 1) tokens
|
ethercrow/yi-config
|
modules/RainbowMode.hs
|
gpl-2.0
| 2,438 | 0 | 14 | 705 | 850 | 473 | 377 | 76 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module MirakelBot.Handlers where
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Lens
import Control.Monad.Reader
import Control.Monad.Trans.Maybe
import qualified Data.Map as M
import Data.Maybe
import Data.Unique
import MirakelBot.Internal
runHandler :: HandlerInfo -> Handler a -> IO (Maybe a)
runHandler i = flip runReaderT i . runMaybeT . runHandler'
getMessage :: Handler Message
getMessage = Handler $ view handlerMessage
getBotEnv :: Handler BotEnv
getBotEnv = Handler $ view handlerEnv
getOwnId :: Handler HandlerId
getOwnId = Handler $ view handlerId
getUserList :: Channel -> Handler UserList
getUserList channel = Handler $ do
mv <- view (handlerEnv.userlist)
ul <- liftIO $ readMVar mv
return $ fromMaybe M.empty (M.lookup channel ul)
runIrc :: Irc a -> Handler a
runIrc irc = do
env <- getBotEnv
liftIO $ runReaderT irc env
forkHandler :: Handler () -> Handler ThreadId
forkHandler h = Handler $ do
info <- ask
liftIO . forkIO . void $ runHandler info h
modifyUserList :: Channel -> (UserList -> UserList) -> Handler ()
modifyUserList channel f = Handler $ do
ul <- view $ handlerEnv.userlist
liftIO $ modifyMVar_ ul $ return . M.alter modList channel
where
modList Nothing = Just $ f M.empty
modList (Just a) = Just $ f a
addUser :: Channel -> Nick -> UserMode -> Handler ()
addUser channel user mode = modifyUserList channel $ M.insert user mode
delUser :: Channel -> Nick -> Handler ()
delUser channel user = modifyUserList channel $ M.delete user
getUserMode :: Channel -> Nick -> Handler (Maybe UserMode)
getUserMode channel nick = do
ul <- getUserList channel
return $ M.lookup nick ul
userIsOnline :: Channel -> Nick -> Handler Bool
userIsOnline channel nick = isJust <$> getUserMode channel nick
-- | Generates new unique HandelrId
generateHandlerId :: Irc HandlerId
generateHandlerId = HandlerId <$> liftIO newUnique
-- | Add a Handler to the Handler list
registerHandler :: Handler () -> Irc HandlerId
registerHandler h = do
i <- generateHandlerId
mvar <- view handlers
liftIO . modifyMVar_ mvar $ return . ((i,h) :)
return i
-- | Removes a Handler from the Handler List
unregisterHandler :: HandlerId -> Irc ()
unregisterHandler hid = do
mvar <- view handlers
liftIO . modifyMVar_ mvar $ return . filter (\h -> fst h /= hid)
unregisterSelf :: Handler ()
unregisterSelf = do
i <- getOwnId
runIrc $ unregisterHandler i
-- |
handleMessage :: Message -> Irc ()
handleMessage msg = do
env <- ask
hs <- liftIO . readMVar $ env^.handlers
liftIO . forM_ hs $ \(hid, h) -> forkIO . void $ runHandler (HandlerInfo msg env hid) h
|
azapps/mirakelbot
|
src/MirakelBot/Handlers.hs
|
gpl-3.0
| 2,962 | 0 | 12 | 687 | 939 | 462 | 477 | 72 | 2 |
{- $Id$
Rational zeros of a function of three variables.
Solution to http://projecteuler.net/index.php?section=problems&id=180
Copyright 2007 Victor Engmark
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Main( main ) where
import System( getArgs, getProgName )
f1 :: Int -> Int -> Int -> Int -> Int
f1 n x y z = x ** (n + 1) + y ** (n + 1) - z ** (n + 1)
f2 :: Int -> Int -> Int -> Int -> Int
f2 n x y z = (x * y + y * z + z * x) * (x ** (n - 1) + y ** (n - 1) - z ** (n - 1))
f3 :: Int -> Int -> Int -> Int -> Int
f3 n x y z = x * y * z * (x ** (n - 2) + y ** (n - 2) - z ** (n - 2))
fn :: Int -> Int -> Int -> Int -> Int
fn n x y z = f1 n x y z + f2 n x y z + f3 n x y z
goldenTripleOrder :: Int -> Int -> Int -> Int
goldenTripleOrder x y z = 1
s :: Int -> Int -> Int -> Int
s x y z = x + y + z
t :: Int -> Int -> Int
t u v = u / v
sumUVForOrder :: Int -> Int
sumUVForOrder order = 1
usageAndExit :: IO ()
usageAndExit = do
progName <- getProgName
putStrLn $ "Usage: runghc \"" ++ progName ++ "\" [integers]"
putStrLn $ "where [integers] is a space separated list."
main :: IO ()
main = do
args <- getArgs
case args of
[] -> usageAndExit
integers -> putStr . unlines . map (show . sum . read) $ integers
|
l0b0/Project-Euler
|
180 - Golden triple.hs
|
gpl-3.0
| 1,867 | 0 | 15 | 487 | 587 | 304 | 283 | 29 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module JSBoiler.Eval.Property
( getPropertyValue
, setPropertyValue
, makeObject
) where
import Control.Monad (void)
import Control.Monad.IO.Class (liftIO)
import Data.IORef
import Data.Text (Text, append)
import qualified Data.HashMap.Strict as M
import JSBoiler.Type
import JSBoiler.Eval.Function
getProperty :: Text -> Object -> Maybe Property
getProperty name obj = case own of
Nothing -> prototype obj >>= getProperty name
Just _ -> own
where own = M.lookup name $ properties obj
-- |Searches for specified property down the property chain.
-- Calls property getter or returns its value.
getPropertyValue :: Text -> IORef Object -> JSBoiler (Maybe JSType)
getPropertyValue name ref = do
obj <- liftIO $ readIORef ref
let mprop = getProperty name obj
getValue prop = case getter prop of
Nothing -> return $ propertyValue prop
Just func -> callFunction ref func []
maybe (return Nothing) (fmap Just . getValue) mprop
setProperty :: Text -> Property -> Object -> Object
setProperty name prop obj = obj { properties = ps }
where ps = M.insert name prop $ properties obj
setPropertyValue :: Text -> IORef Object -> JSType -> JSBoiler ()
setPropertyValue name ref value = do
obj <- liftIO $ readIORef ref
let props = properties obj
mprop = M.lookup name props
setValue prop val = case setter prop of
Nothing -> if writeable prop
then let obj' = setProperty name (prop { propertyValue = val }) obj
in liftIO $ writeIORef ref obj'
else jsThrow $ JSString $ "Cannot assign to read only property '" `append` name `append` "'"
Just func -> void (callFunction ref func [val])
case mprop of
Nothing -> do
let props' = M.insert name Property
{ propertyValue = value
, writeable = True
, enumerable = True
, configurable = True
, getter = Nothing
, setter = Nothing
} props
obj' = obj { properties = props' }
liftIO $ writeIORef ref obj'
Just prop -> setValue prop value
-- |Makes object with specified properties
makeObject :: [(Text, JSType)] -> IO JSType
makeObject pairs = JSObject <$> newIORef obj
where
toProperty = fmap valuedProperty
props = map toProperty pairs
obj = Object { properties = M.fromList props
, behaviour = Nothing
, prototype = Nothing -- should be Object.prototype
}
|
cuklev/JSBoiler
|
src/JSBoiler/Eval/Property.hs
|
gpl-3.0
| 2,748 | 0 | 21 | 898 | 736 | 383 | 353 | 59 | 4 |
module FQuoter.Templating.Display
( readTree )
where
import Data.Maybe
import Control.Applicative
import Data.Monoid hiding (All)
import Data.Char
import FQuoter.Quote
import FQuoter.Templating.TemplateTypes
type Template = [TokenNode]
-- Given a tree template to display a quote and its context,
-- evaluate this tree with the quote.
readTree :: Template -> Quote -> String
readTree q s = fromMaybe "" $ mapSeveralNodes evalNode q s
-- Evaluate a single node in the display tree.
-- If an Author is detected, an helper function will be called
-- for there are several special cases concerning Authors.
evalNode :: TokenNode -> Quote -> Maybe String
evalNode (One mods (SourceInfo SourceTitle))
= applyMods' mods . Just . title . source
evalNode (One mods (SourceInfo (SourceMetadata t)))
= applyMods' mods . lookupMetadata t . source
evalNode t@(One _ (AuthorInfo _)) = evalAuthor t . mainAuthor
evalNode (SomeAuthors All ts)
= mconcat . mapNodesAndItems evalAuthor ts . author
evalNode (SomeAuthors (Only n) ts)
= mconcat . take n . mapNodesAndItems evalAuthor ts . author
evalNode (One mods (ConstantString s)) = displayConstantString mods s
evalNode (Condition con tn) = handleCondition con tn
evalNode (Or tn tn') = orNode evalNode tn tn'
handleCondition :: TokenContent -> [TokenNode] -> Quote -> Maybe String
handleCondition (SourceInfo (SourceMetadata m)) tn q
| isNothing (lookupMetadata m $ source q) = Nothing
| otherwise = mapSeveralNodes evalNode tn q
handleCondition (AuthorInfo ai) tn q
= handleAuthorCondition ai tn $ mainAuthor q
handleCondition _ _ _
= error "SourceInfo or ConstantString cannot be conditions."
-- Helper function to display constants in templates
displayConstantString :: [TokenModificator] -> String -> a -> Maybe String
displayConstantString mods s _ = applyMods' mods . Just $ s
-- Helper function handling display commands for Authors
evalAuthor :: TokenNode -> Author -> Maybe String
evalAuthor (One mods (AuthorInfo ai)) = applyMods' mods . evalAuthorToken ai
evalAuthor (One mods (ConstantString s)) = displayConstantString mods s
evalAuthor (Or tn tn') = orNode evalAuthor tn tn'
evalAuthor (Condition (AuthorInfo ai) tn) = handleAuthorCondition ai tn
evalAuthor _
= error "One with authorInfo, Or and Conditions only when evaluating this author "
handleAuthorCondition :: TokenAuthorInfo
-> [TokenNode]
-> Author
-> Maybe String
handleAuthorCondition ai tn auth
| isNothing $ evalAuthorToken ai auth = Nothing
| otherwise = mapSeveralNodes evalAuthor tn auth
evalAuthorToken :: TokenAuthorInfo -> Author -> Maybe String
evalAuthorToken (AuthorNickName) = surname
evalAuthorToken (AuthorLastName) = lastName
evalAuthorToken (AuthorFirstName) = firstName
mapNodesAndItems :: (TokenNode -> a -> Maybe String) -> [TokenNode] -> [a] -> [Maybe String]
mapNodesAndItems f ts = map (mapSeveralNodes f ts)
mapSeveralNodes :: (TokenNode -> a -> Maybe String) -> [TokenNode] -> a -> Maybe String
mapSeveralNodes f t a = mconcat . map (`f` a) $ t
orNode :: (TokenNode -> a -> Maybe String) -> [TokenNode] -> [TokenNode] -> a -> Maybe String
orNode f n1 n2 a = mapSeveralNodes f n1 a <|> mapSeveralNodes f n2 a
applyMods' :: [TokenModificator] -> Maybe String -> Maybe String
applyMods' mods = fmap (`applyMods` mods)
applyMods :: String -> [TokenModificator] -> String
applyMods = foldl (flip modify)
modify :: TokenModificator -> String -> String
modify Capital = map toUpper
modify Initial = (:".") . head
modify Italics = prefixSuffixWith "*"
where prefixSuffixWith prsf s = concat [prsf, s, prsf]
|
Raveline/FQuoter
|
lib/FQuoter/Templating/Display.hs
|
gpl-3.0
| 3,692 | 0 | 11 | 694 | 1,148 | 580 | 568 | 67 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- 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.Values.Fancy where
import MyPrelude
import Data.Int
import OpenGL
import OpenAL
import Game.Font
import Game.Data.Color
import Game.Data.View
--------------------------------------------------------------------------------
-- Perspective
valuePerspectiveFOVY :: Float
valuePerspectiveFOVY =
1.047
valuePerspectiveNear :: Float
valuePerspectiveNear =
0.1
valuePerspectiveFar :: Float
valuePerspectiveFar =
512.0
-- | call this value r. let mx my mz be the x, y, z colums of the current
-- modelview matrix. then
-- r : r * abs(mx + my + mz) < projection_far
-- but we assume that modelview(3x3) is orthonormal, so
-- r : r < (projection_far / sqrt 3)
valuePerspectiveRadius :: Float
valuePerspectiveRadius =
valuePerspectiveFar * 0.57735
--------------------------------------------------------------------------------
-- Scene
valueSceneCornerSize :: Float
valueSceneCornerSize =
0.20
--------------------------------------------------------------------------------
-- Grid
valueGridPathRadius :: Float
valueGridPathRadius =
0.3
--------------------------------------------------------------------------------
-- Memory
valueMemoryPathRadius :: Float
valueMemoryPathRadius =
valueGridPathRadius
--------------------------------------------------------------------------------
-- LevelPuzzle
valueLevelPuzzleEatTicks :: Float
valueLevelPuzzleEatTicks = 1.0
valueLevelPuzzleEatTicksInv :: Float
valueLevelPuzzleEatTicksInv = 1.0 / valueLevelPuzzleEatTicks
valueLevelPuzzleDotSlices :: UInt
valueLevelPuzzleDotSlices =
16
valueLevelPuzzleDotStacks :: UInt
valueLevelPuzzleDotStacks =
16
valueLevelPuzzleDotTele0Color :: Color
valueLevelPuzzleDotTele0Color =
Color 1.0 0.45882 0.0 1.0
valueLevelPuzzleDotTele1Color :: Color
valueLevelPuzzleDotTele1Color =
Color 0.0 0.57647 1.0 1.0
valueLevelPuzzleDotBonusColor :: Color
valueLevelPuzzleDotBonusColor =
Color 0.75294 0.09411 0.47843 1.0
valueLevelPuzzleDotFinishColor :: Color
valueLevelPuzzleDotFinishColor =
Color 1.0 1.0 1.0 1.0
valueFadeContentTicks :: Float
valueFadeContentTicks =
4.0
valueFadeContentTicksInv :: Float
valueFadeContentTicksInv =
1.0 / valueFadeContentTicks
valueFadeRoomTicks :: Float
valueFadeRoomTicks =
2.0
valueFadeRoomTicksInv :: Float
valueFadeRoomTicksInv =
1.0 / valueFadeRoomTicks
valueFadeFailureTicks :: Float
valueFadeFailureTicks =
8.0
valueFadeFailureTicksInv :: Float
valueFadeFailureTicksInv =
1.0 / valueFadeRoomTicks
valueLevelPuzzlePathRadius :: Float
valueLevelPuzzlePathRadius =
valueGridPathRadius
--------------------------------------------------------------------------------
-- Run
valueRunCubeFontSize :: Float
valueRunCubeFontSize =
5.2
valueRunCubeFontColor :: FontColor
valueRunCubeFontColor =
FontColor 1.0 1.0 0.2 1.0
valueRunPathColor :: Color
valueRunPathColor =
Color 0.0 0.7 0.8 1.0
valueRunPathRadius :: Float
valueRunPathRadius =
1.0
--------------------------------------------------------------------------------
-- SoundScene. fixme: into module!
valueSoundSceneNoiseNodeRadius :: Int16
valueSoundSceneNoiseNodeRadius = 256
valueSoundSceneNoiseTickMin :: Float
valueSoundSceneNoiseTickMin = 11.0
valueSoundSceneNoiseTickMax :: Float
valueSoundSceneNoiseTickMax = 20.0
valueSoundSceneNoisePitchMin :: Float
valueSoundSceneNoisePitchMin = 0.6
valueSoundSceneNoisePitchMax :: Float
valueSoundSceneNoisePitchMax = 1.8
--------------------------------------------------------------------------------
-- SoundLevelPuzzle. fixme: into module!
valueSoundLevelPuzzleNodeConeInnerAngle :: ALfloat
valueSoundLevelPuzzleNodeConeInnerAngle = 45.0
valueSoundLevelPuzzleNodeConeOuterAngle :: ALfloat
valueSoundLevelPuzzleNodeConeOuterAngle = 360.0
valueSoundLevelPuzzleNodeConeOuterGain :: ALfloat
valueSoundLevelPuzzleNodeConeOuterGain = 0.4
valueSoundLevelPuzzleNodeReferenceDistance :: ALfloat
valueSoundLevelPuzzleNodeReferenceDistance = 8.0
valueSoundLevelPuzzleNodeMaxDistance :: ALfloat
valueSoundLevelPuzzleNodeMaxDistance = 32.0
valueSoundLevelPuzzleNodeRolloffFactor :: ALfloat
valueSoundLevelPuzzleNodeRolloffFactor = 1.0
--------------------------------------------------------------------------------
-- SpaceBox. fixme: into module!!
valueSpaceBoxDefaultColor :: Color
valueSpaceBoxDefaultColor =
Color 0.3 0.9 0.0 1.0
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Text
-- | (relative to Scene hth)
valueTextFontASize :: Float
valueTextFontASize =
0.1
-- | (relative to Scene hth)
valueTextFontAY :: Float
valueTextFontAY =
0.4
valueTextFontAColor :: FontColor
valueTextFontAColor =
FontColor 1.0 0.0 0.0 1.0
-- | (relative to Scene hth)
valueTextFontBSize :: Float
valueTextFontBSize =
0.06
-- | (relative to Scene hth)
valueTextFontBY :: Float
valueTextFontBY =
0.3
valueTextFontBColor :: FontColor
valueTextFontBColor =
FontColor 0.0 1.0 0.0 1.0
-- | (relative to Scene hth)
valueTextFontCSize :: Float
valueTextFontCSize =
0.05
-- | (relative to Scene hth)
valueTextFontCY :: Float
valueTextFontCY =
0.08
valueTextFontCColor :: FontColor
valueTextFontCColor =
FontColor 0.0 0.0 1.0 1.0
|
karamellpelle/grid
|
source/Game/Values/Fancy.hs
|
gpl-3.0
| 6,144 | 0 | 5 | 879 | 668 | 407 | 261 | 136 | 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.Storage.BucketAccessControls.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the ACL entry for the specified entity on the specified bucket.
--
-- /See:/ <https://developers.google.com/storage/docs/json_api/ Cloud Storage JSON API Reference> for @storage.bucketAccessControls.get@.
module Network.Google.Resource.Storage.BucketAccessControls.Get
(
-- * REST Resource
BucketAccessControlsGetResource
-- * Creating a Request
, bucketAccessControlsGet
, BucketAccessControlsGet
-- * Request Lenses
, bacgBucket
, bacgEntity
) where
import Network.Google.Prelude
import Network.Google.Storage.Types
-- | A resource alias for @storage.bucketAccessControls.get@ method which the
-- 'BucketAccessControlsGet' request conforms to.
type BucketAccessControlsGetResource =
"storage" :>
"v1" :>
"b" :>
Capture "bucket" Text :>
"acl" :>
Capture "entity" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] BucketAccessControl
-- | Returns the ACL entry for the specified entity on the specified bucket.
--
-- /See:/ 'bucketAccessControlsGet' smart constructor.
data BucketAccessControlsGet = BucketAccessControlsGet'
{ _bacgBucket :: !Text
, _bacgEntity :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'BucketAccessControlsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bacgBucket'
--
-- * 'bacgEntity'
bucketAccessControlsGet
:: Text -- ^ 'bacgBucket'
-> Text -- ^ 'bacgEntity'
-> BucketAccessControlsGet
bucketAccessControlsGet pBacgBucket_ pBacgEntity_ =
BucketAccessControlsGet'
{ _bacgBucket = pBacgBucket_
, _bacgEntity = pBacgEntity_
}
-- | Name of a bucket.
bacgBucket :: Lens' BucketAccessControlsGet Text
bacgBucket
= lens _bacgBucket (\ s a -> s{_bacgBucket = a})
-- | The entity holding the permission. Can be user-userId,
-- user-emailAddress, group-groupId, group-emailAddress, allUsers, or
-- allAuthenticatedUsers.
bacgEntity :: Lens' BucketAccessControlsGet Text
bacgEntity
= lens _bacgEntity (\ s a -> s{_bacgEntity = a})
instance GoogleRequest BucketAccessControlsGet where
type Rs BucketAccessControlsGet = BucketAccessControl
type Scopes BucketAccessControlsGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/devstorage.full_control"]
requestClient BucketAccessControlsGet'{..}
= go _bacgBucket _bacgEntity (Just AltJSON)
storageService
where go
= buildClient
(Proxy :: Proxy BucketAccessControlsGetResource)
mempty
|
rueshyna/gogol
|
gogol-storage/gen/Network/Google/Resource/Storage/BucketAccessControls/Get.hs
|
mpl-2.0
| 3,551 | 0 | 14 | 785 | 386 | 233 | 153 | 64 | 1 |
module System.IO.Extra where
import Control.Exception.Base
import Data.Functor
import System.IO
import System.IO.Error
tryReadFile :: FilePath -> IO (Either IOError String)
tryReadFile filename = tryIOError $ readFile filename
maybeReadFile :: FilePath -> IO (Maybe String)
maybeReadFile filename = do
r <- tryIOError $ openFile filename ReadMode
case r of
Left _ -> return Nothing
Right h -> Just <$> hGetContents h
|
gelisam/submake
|
src/System/IO/Extra.hs
|
unlicense
| 442 | 0 | 11 | 84 | 141 | 71 | 70 | 13 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Spark.IO.JsonSpec where
import Test.Hspec
import Data.Aeson(encode)
import qualified Data.ByteString.Lazy
-- import System.IO
import Spark.Core.Context
import Spark.Core.Types
import Spark.Core.Row
import Spark.Core.Functions
import Spark.Core.Column
import Spark.IO.Inputs
import Spark.Core.IntegrationUtilities
import Spark.Core.SimpleAddSpec(run)
spec :: Spec
spec = do
describe "Read a json file" $ do
run "simple read" $ do
let xs = [TestStruct7 "x"]
let js = encode xs
_ <- Data.ByteString.Lazy.writeFile "/tmp/x.json" js
let dt = unSQLType (buildType :: SQLType TestStruct7)
let df = json' dt "/tmp/x.json"
let c = collect' (asCol' df)
c1 <- exec1Def' c
c1 `shouldBe` rowArray [rowArray [StringElement "x"]]
c2 <- exec1Def' c
c2 `shouldBe` rowArray [rowArray [StringElement "x"]]
run "simple inference" $ do
let xs = [TestStruct7 "x"]
let js = encode xs
_ <- Data.ByteString.Lazy.writeFile "/tmp/x.json" js
df <- execStateDef $ jsonInfer "/tmp/x.json"
let c = collect' (asCol' df)
c1 <- exec1Def' c
c1 `shouldBe` rowArray [rowArray [StringElement "x"]]
|
krapsh/kraps-haskell
|
test-integration/Spark/IO/JsonSpec.hs
|
apache-2.0
| 1,257 | 0 | 18 | 268 | 398 | 201 | 197 | 36 | 1 |
{- Copyright 2014 David Farrell <[email protected]>
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-}
module Ping where
import IRC.Message (Message(..))
import IRC.Numeric
import IRC.Action
import IRC.Server.Client.Helper
import qualified IRC.Server.Environment as Env
import Config
import Plugin
plugin = defaultPlugin {handlers = [CommandHandler "PING" ping]}
ping :: CommandHSpec
ping env (Message _ _ (server1:_)) = env {Env.actions=a:Env.actions env}
where a = NamedAction "Ping.ping" $ \e -> do
let serverName = getConfigString (Env.config e) "info" "name"
sendClient (Env.client e) $ ":" ++ serverName ++ " PONG " ++ serverName++" :" ++ server1
return e
ping env _ = env {Env.actions=a:Env.actions env}
where a = GenericAction $ \e -> sendNumeric env numERR_NEEDMOREPARAMS ["PING", "Not enough parameters"]
>> return e
|
shockkolate/lambdircd
|
plugins.old/Ping.hs
|
apache-2.0
| 1,386 | 0 | 20 | 264 | 275 | 149 | 126 | 18 | 1 |
-- Copyright 2018-2021 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- | Provides an analog of 'Functor' over arity-1 type constructors.
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Data.Ten.Functor
( Functor10(..), (<$!), (<$>!), void10
) where
import Data.Kind (Type)
import Data.Proxy (Proxy(..))
import GHC.Generics
( Generic1(..)
, (:.:)(..), (:*:)(..), (:+:)(..)
, M1(..), Rec1(..), U1(..), V1, K1(..)
)
import Data.Wrapped (Wrapped1(..))
import Data.Ten.Ap (Ap10(..))
-- | 'Functor' over arity-1 type constructors.
--
-- Whereas 'Functor' maps @a :: Type@ values to @b :: Type@ values, 'Functor10'
-- maps @(m :: k -> Type) a@ values to @m b@ values, parametrically in @a@.
-- That is, the type parameter of 'Functor' has arity 0, and the type
-- parameter of 'Functor10' has arity 1.
class Functor10 (f :: (k -> Type) -> Type) where
-- | Map each @m a@ value in @f m@ parametrically to @n a@ to get @f m@.
fmap10 :: (forall a. m a -> n a) -> f m -> f n
instance (Generic1 f, Functor10 (Rep1 f))
=> Functor10 (Wrapped1 Generic1 f) where
fmap10 f = Wrapped1 . to1 . fmap10 f . from1 . unWrapped1
instance Functor10 (Ap10 a) where
fmap10 f (Ap10 x) = Ap10 (f x)
instance Functor10 (K1 i a) where
fmap10 _ (K1 x) = K1 x
instance Functor10 V1 where
fmap10 _ x = case x of {}
instance Functor10 U1 where
fmap10 _ U1 = U1
deriving instance Functor10 f => Functor10 (Rec1 f)
deriving instance Functor10 f => Functor10 (M1 i c f)
instance (Functor10 f, Functor10 g) => Functor10 (f :+: g) where
fmap10 f (L1 x) = L1 (fmap10 f x)
fmap10 f (R1 x) = R1 (fmap10 f x)
instance (Functor10 f, Functor10 g) => Functor10 (f :*: g) where
fmap10 f (l :*: r) = fmap10 f l :*: fmap10 f r
instance (Functor f, Functor10 g) => Functor10 (f :.: g) where
fmap10 f (Comp1 x) = Comp1 $ fmap (fmap10 f) x
infixl 4 <$!
-- | ('<$') for 'Functor10'.
(<$!) :: Functor10 f => (forall a. n a) -> f m -> f n
x <$! f = fmap10 (const x) f
infixl 4 <$>!
-- | ('<$>') for 'Functor10'.
(<$>!) :: Functor10 f => (forall a. m a -> n a) -> f m -> f n
(<$>!) = fmap10
-- | 'Data.Functor.void' for 'Functor10'.
--
-- This returns @f 'Proxy'@ because @Proxy :: k -> Type@ has the right kind and
-- carries no runtime information. It's isomorphic to @Const ()@ but easier to
-- spell.
void10 :: Functor10 f => f m -> f Proxy
void10 = fmap10 (const Proxy)
|
google/hs-ten
|
ten/src/Data/Ten/Functor.hs
|
apache-2.0
| 3,204 | 0 | 11 | 664 | 846 | 473 | 373 | -1 | -1 |
{-# LANGUAGE TypeFamilies #-}
{-|
Module : Marvin.API.EvaluationMetric
Description : Metrics used for evaluation.
-}
module Marvin.API.EvaluationMetrics (
Accuracy (..)
, MeanSquaredError (..)
, RootMeanSquaredError (..)
, Precision (..)
, Recall (..)
) where
import Marvin.API.Meta.Evaluator
import Marvin.API.Table.Column
import Marvin.API.Fallible
import Marvin.API.Meta.Model
import Marvin.API.Table.DataType
import Data.Vector (Vector)
import qualified Data.Vector.Unboxed as UVec
-- * Accuracy
data Accuracy = Accuracy
accuracy :: PairwiseMetric Binary
accuracy = PM {
prepare = \real predicted -> if (real == predicted) then 1 else 0
, aggregate = average
}
instance Evaluator Accuracy where
type EvalPrediction Accuracy = BinaryColumn
evaluate' Accuracy = evaluatePairwise accuracy
-- * Mean squared error
data MeanSquaredError = MeanSquaredError
meanSqError :: PairwiseMetric Numeric
meanSqError = PM {
prepare = \real predicted -> (real - predicted)^2
, aggregate = average
}
instance Evaluator MeanSquaredError where
type EvalPrediction MeanSquaredError = NumericColumn
evaluate' MeanSquaredError = evaluatePairwise meanSqError
-- * Root mean squared error
data RootMeanSquaredError = RootMeanSquaredError
rootMeanSqError :: PairwiseMetric Numeric
rootMeanSqError = meanSqError {
aggregate = sqrt . (aggregate meanSqError)
}
instance Evaluator RootMeanSquaredError where
type EvalPrediction RootMeanSquaredError = NumericColumn
evaluate' RootMeanSquaredError = evaluatePairwise rootMeanSqError
-- * Precision
data Precision = Precision
precision :: [Bool] -> [Bool] -> Double
precision real pred =
fromIntegral truePos / fromIntegral truePosFalsePos
where
xs = zip real pred
truePosFalsePos = length $ filter snd xs
truePos = length $ filter (\(r, p) -> r && p) xs
instance Evaluator Precision where
type EvalPrediction Precision = BinaryColumn
evaluate' Precision real pred = return $
precision (toList real) (toList pred)
-- * Recall
data Recall = Recall
recall :: [Bool] -> [Bool] -> Double
recall real pred =
fromIntegral truePos / fromIntegral truePosFalseNeg
where
xs = zip real pred
truePosFalseNeg = length $ filter fst xs
truePos = length $ filter (\(r, p) -> r && p) xs
instance Evaluator Recall where
type EvalPrediction Recall = BinaryColumn
evaluate' Recall real pred = return $
recall (toList real) (toList pred)
-- * Pairwise metric
-- | Alias for preparing evaluation element-wise.
type PairwisePrepare a =
ColumnExposed a -- ^ real
-> ColumnExposed a -- ^ predicted
-> Double
-- | Alias for aggregating the prepared elements.
type PairwiseAggregate =
[Double] -> Double
-- | Type for pairwise evaluation.
data PairwiseMetric a = PM {
prepare :: PairwisePrepare a
, aggregate :: PairwiseAggregate
}
-- | Evaluation with a pairwise metric.
evaluatePairwise :: (ColumnDataType a) =>
PairwiseMetric a
-> Column a -- ^ real
-> Column a -- ^ predicted
-> Fallible Double
evaluatePairwise pairwise realCol predCol = return $ aggregate pairwise $
zipWith (prepare pairwise) (exposedVals realCol) (exposedVals predCol)
where
exposedVals col = map (exposure col) $ UVec.toList $ values col
average :: PairwiseAggregate
average xs = sum xs / fromIntegral (length xs)
|
gaborhermann/marvin
|
src/Marvin/API/EvaluationMetrics.hs
|
apache-2.0
| 3,327 | 0 | 11 | 596 | 857 | 474 | 383 | 78 | 2 |
-- | Provides the basic `SGD` pipe type.
module Numeric.SGD.Type
( SGD
) where
import Pipes as P
-- | SGD is a pipe which, given the initial parameter values, consumes training
-- elements of type @e@ and outputs the subsequently calculated parameter sets
-- of type @p@.
type SGD m e p = p -> P.Pipe e p m ()
|
kawu/sgd
|
src/Numeric/SGD/Type.hs
|
bsd-2-clause
| 320 | 0 | 7 | 71 | 47 | 31 | 16 | 4 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
module Guide.Api.Methods
( getCategories
, getCategory
)
where
import Imports
import Servant
import Data.Acid as Acid
import Guide.Types
import Guide.State
import Guide.Utils (Uid)
import Guide.Api.Types (ApiError(..), CategoryInfo, CCategoryDetail, toCategoryInfo, toCCategoryDetail)
getCategories :: DB -> Handler [CategoryInfo]
getCategories db = do
liftIO (Acid.query db GetCategories) <&> \xs ->
map toCategoryInfo xs
getCategory :: DB -> Uid Category -> Handler (Either ApiError CCategoryDetail)
getCategory db catId =
liftIO (Acid.query db (GetCategoryMaybe catId)) <&> \case
Nothing -> Left (ApiError "category not found")
Just cat -> Right $ toCCategoryDetail cat
|
aelve/hslibs
|
src/Guide/Api/Methods.hs
|
bsd-3-clause
| 798 | 0 | 11 | 130 | 224 | 122 | 102 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface, CPP #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.InstancedArrays
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the ARB_instanced_arrays extension, see
-- <http://www.opengl.org/registry/specs/ARB/instanced_arrays.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.InstancedArrays (
-- * Functions
glVertexAttribDivisor,
-- * Tokens
gl_VERTEX_ATTRIB_ARRAY_DIVISOR
) where
import Foreign.C.Types
import Graphics.Rendering.OpenGL.Raw.Core32
import Graphics.Rendering.OpenGL.Raw.Extensions
#include "HsOpenGLRaw.h"
extensionNameString :: String
extensionNameString = "GL_ARB_instanced_arrays"
EXTENSION_ENTRY(dyn_glVertexAttribDivisor,ptr_glVertexAttribDivisor,"glVertexAttribDivisor",glVertexAttribDivisor,GLuint -> GLuint -> IO ())
gl_VERTEX_ATTRIB_ARRAY_DIVISOR :: GLenum
gl_VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88FE
|
mfpi/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/ARB/InstancedArrays.hs
|
bsd-3-clause
| 1,206 | 0 | 11 | 131 | 114 | 77 | 37 | -1 | -1 |
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TemplateHaskell #-}
module Toy.Exp.Data where
import Control.Lens (makeLenses, makePrisms)
import Data.String (IsString (..))
import qualified Data.Vector as V
import Formatting (formatToString, shown, (%))
import qualified Prelude
import Universum
import Toy.Base.Data (BinOp, UnaryOp, Value, Var)
import Toy.Exp.RefEnv (MRef, MRefId)
-- | Expression
data Exp
= ValueE Value
| VarE Var
| UnaryE UnaryOp Exp
| BinE BinOp Exp Exp
| FunE Var [Exp]
| ArrayUninitE Exp -- ^ uninitialized array
| ArrayAccessE Exp Exp -- array & index
deriving (Show)
instance IsString Exp where
fromString = VarE . fromString
instance Num Exp where
(+) = BinE "+"
(-) = BinE "-"
(*) = BinE "*"
abs = error "Num abs: undefined"
signum = error "Num sugnum: undefined"
fromInteger = ValueE . fromInteger
-- | @read@ expression.
readE :: Exp
readE = FunE "read" []
-- | Create value corresponding to char. We store char as int.
charE :: Num i => Char -> i
charE = fromIntegral . fromEnum
-- | Array with some meta info
data ArrayInnards = ArrayInnards
{ _aiRefCounter :: Int
, _aiRefId :: MRefId
, _aiArray :: V.Vector ExpRes
}
instance Show ArrayInnards where
show ArrayInnards {..} =
formatToString
(shown % " (" %shown % ", " %shown % ")")
_aiArray
_aiRefId
_aiRefCounter
-- | Evaluated expression
data ExpRes
= ValueR Value
| ArrayR (MRef (Maybe ArrayInnards))
| NotInitR
instance Show ExpRes where
show (ValueR n) = show n
show (ArrayR _) = "<array>"
show NotInitR = "<undefined>"
makeLenses ''ArrayInnards
makePrisms ''ExpRes
|
Martoon-00/toy-compiler
|
src/Toy/Exp/Data.hs
|
bsd-3-clause
| 1,810 | 0 | 12 | 513 | 467 | 266 | 201 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts, Rank2Types, CPP #-}
#if __GLASGOW_HASKELL__ >= 704
{-# LANGUAGE ConstraintKinds #-}
#else
{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
#endif
{-# OPTIONS_HADDOCK hide #-}
module Data.PhaseChange.Internal where
import Control.Monad
import Control.Monad.ST (ST, runST)
import Control.Monad.ST.Class
import GHC.Exts (RealWorld)
--import Control.Newtype
-- | The @PhaseChange@ class ties together types which provide a mutable and an immutable view
-- on the same data. The mutable type must have a phantom type parameter representing the
-- state thread it is being used in. Many types have this type parameter in the wrong place
-- (not at the end): instances for them can be provided using the @'M1'@ and @'M2'@ newtypes.
class (Thawed imm ~ mut, Frozen mut ~ imm) => PhaseChange (imm :: *) (mut :: * -> *) where
type Thawed imm :: * -> *
type Frozen mut :: *
-- | Should return the same data it got as input, viewed as a mutable type, making no
-- changes.
unsafeThawImpl :: imm -> ST s (Thawed imm s)
-- | Should return the same data it got as input, viewed as an immutable type, making no
-- changes.
unsafeFreezeImpl :: mut s -> ST s (Frozen mut)
-- | Should make a perfect copy of the input argument, leaving nothing shared between
-- the original and the copy, and making no other changes.
copyImpl :: mut s -> ST s (mut s)
-- you might think that unsafeThaw and unsafeFreeze (and for that matter thaw) don't need to
-- be monadic, because after all they're just conceptually wrapping/unwrapping newtypes, and
-- the argument of thaw is immutable so evaluating lazily should be fine.
-- two things get in the way:
-- - GHC's unsafeFreeze/unsafeThaw aren't actually pure, they mutate some bits to let the
-- garbage collector know what's mutable and what's not; and
-- - while it wouldn't break referential transparency directly, it would if you were to use
-- the result of thaw/unsafeThaw in two different calls to runST. so we can't allow that.
#if __GLASGOW_HASKELL__ >= 704
type Mutable mut = PhaseChange (Frozen mut) mut
#else
class PhaseChange (Frozen mut) mut => Mutable mut
instance PhaseChange (Frozen mut) mut => Mutable mut
#endif
-- the type synonyms look nicer in the haddocks, otherwise it doesn't matter which one we use
#if __GLASGOW_HASKELL__ >= 704
type Immutable imm = PhaseChange imm (Thawed imm)
#else
class PhaseChange imm (Thawed imm) => Immutable imm
instance PhaseChange imm (Thawed imm) => Immutable imm
#endif
-- | Returns the input argument viewed as a mutable type. The input argument must not be used
-- afterwards.
unsafeThaw :: (Immutable imm, MonadST mST, s ~ World mST) => imm -> mST (Thawed imm s)
unsafeThaw = liftST . unsafeThawImpl
{-# INLINABLE unsafeThaw #-}
{-# SPECIALIZE unsafeThaw :: (Immutable imm, s ~ World (ST s)) => imm -> ST s (Thawed imm s) #-}
{-# SPECIALIZE unsafeThaw :: Immutable imm => imm -> IO (Thawed imm RealWorld) #-}
-- NOTE this is extremely delicate!
-- With IO it only works if I pre-expand the World type family, with ST it
-- only works if I don't. And if I use World directly in the original signature
-- instead of naming it 's', everything changes again.
-- In general the only way to figure it out seems to be trial and error.
-- Otherwise GHC says things like: "RULE left-hand side too complicated to desugar",
-- or sometimes "match_co baling out".
-- | Returns the input argument viewed as an immutable type. The input argument must not be used
-- afterwards.
unsafeFreeze :: (Mutable mut, MonadST mST, s ~ World mST) => mut s -> mST (Frozen mut)
unsafeFreeze = liftST . unsafeFreezeImpl
{-# INLINABLE unsafeFreeze #-}
{-# SPECIALIZE unsafeFreeze :: (Mutable mut, s ~ World (ST s)) => mut s -> ST s (Frozen mut) #-}
{-# SPECIALIZE unsafeFreeze :: (Mutable mut, s ~ RealWorld) => mut s -> IO (Frozen mut) #-}
-- | Make a copy of mutable data.
copy :: (Mutable mut, MonadST mST, s ~ World mST) => mut s -> mST (mut s)
copy = liftST . copyImpl
{-# INLINABLE copy #-}
{-# SPECIALIZE copy :: (Mutable mut, s ~ World (ST s)) => mut s -> ST s (mut s) #-}
{-# SPECIALIZE copy :: (Mutable mut, s ~ RealWorld) => mut s -> IO (mut s) #-}
-- | Get a copy of immutable data in mutable form.
thaw :: (Immutable imm, MonadST mST, s ~ World mST) => imm -> mST (Thawed imm s)
thaw = thawImpl
{-# INLINE thaw #-}
thawImpl :: (PhaseChange imm mut, MonadST mST) => imm -> mST (mut (World mST))
thawImpl = copy <=< unsafeThaw
{-# INLINABLE thawImpl #-}
{-# SPECIALIZE thawImpl :: PhaseChange imm mut => imm -> ST s (mut (World (ST s))) #-}
{-# SPECIALIZE thawImpl :: PhaseChange imm mut => imm -> IO (mut (World IO)) #-}
-- need to do this ugly thaw/thawImpl thing because I couldn't find any way at all to get
-- the SPECIALIZE to work otherwise
-- (interestingly unsafeThaw has the same exact type signature and didn't have problems...)
-- | Get a copy of mutable data in immutable form.
freeze :: (Mutable mut, MonadST mST, s ~ World mST) => mut s -> mST (Frozen mut)
freeze = unsafeFreeze <=< copy
{-# INLINABLE freeze #-}
{-# SPECIALIZE freeze :: (Mutable mut, s ~ World (ST s)) => mut s -> ST s (Frozen mut) #-}
{-# SPECIALIZE freeze :: (Mutable mut, s ~ RealWorld) => mut s -> IO (Frozen mut) #-}
-- | Produce immutable data from a mutating computation. No copies are made.
frozen :: Mutable mut => (forall s. ST s (mut s)) -> Frozen mut
frozen m = runST $ unsafeFreeze =<< m
{-# NOINLINE [1] frozen #-}
-- {-# INLINABLE frozen #-}
-- I don't see why these should conflict, but GHC says they do
-- | Make an update of immutable data by applying a mutating action. This function allows for
-- copy elision.
--
-- Each chain of 'updateWith's makes only one copy. A chain of 'updateWith's on
-- top of a 'frozen' makes no copies.
updateWith :: Mutable mut => (forall s. mut s -> ST s ()) -> Frozen mut -> Frozen mut
updateWith f a = runST $ do { m <- thaw a; f m; unsafeFreeze m }
{-# NOINLINE [1] updateWith #-}
-- {-# INLINABLE updateWith #-}
-- really wanted to do this the other way around with Immutable and Thawed, but I found
-- absolutely no way to get the RULES to work that way, not even with the thaw/thawImpl trick
type Maker mut = forall s. ST s (mut s)
type Updater mut = forall s. mut s -> ST s ()
{-# RULES
"updateWith/frozen"
forall (stm :: Maker mut) (f :: Updater mut).
updateWith f (frozen stm) = frozen (stm >>= \m -> f m >> return m);
"updateWith/updateWith"
forall (f :: Updater mut) (g :: Updater mut) i.
updateWith f (updateWith g i) = updateWith (\m -> f m >> g m) i
#-}
updateWithResult :: Immutable imm => (forall s. Thawed imm s -> ST s a) -> imm -> (imm, a)
updateWithResult f a = runST $ do { m <- thaw a; r <- f m; i <- unsafeFreeze m; return (i, r) }
{-# INLINABLE updateWithResult #-}
{- RULES
"updateWithResult/frozen"
forall (m :: Mutable mut => (forall s. ST s (mut s))) (f :: Immutable imm => (forall s. Thawed imm s -> ST s a)).
updateWithResult f (frozen m) = frozen (m >>= \m' -> f m' >> return m');
-}
--updateManyWith :: (Immutable imm, Functor f) => (forall s. f (Thawed imm s) -> ST s ()) -> f imm -> f imm
--updateManyWith f a = runST $ do {
--withPlus :: Immutable a => a -> (forall s. Thawed a s -> ST s (Thawed a s, b)) -> (a, b)
{-
let (foo, vec') = updateWithResult asdf vec
(bar, vec'') = updateWithResult bsdf vec'
(baz, vec''') = updateWithResult csdf vec''
-}
-- | Read a value from immutable data with a reading-computation on mutable data.
-- This function is referentially transparent as long as the computation does
-- not mutate its input argument, but there is no way to enforce this.
readWith :: Immutable imm => (forall s. Thawed imm s -> ST s a) -> imm -> a
readWith f i = runST $ do { m <- unsafeThaw i; r <- f m; _ <- unsafeFreeze m; return r }
-- | Newtype for mutable types whose state thread parameter is in the second-to-last position
newtype M1 mut a s = M1 { unM1 :: mut s a }
--instance Newtype (M1 mut a s) (mut s a) where
-- pack = M1
-- unpack = unM1
unsafeThaw1 :: (PhaseChange (imm a) (M1 mut a), MonadST mST, s ~ World mST) => imm a -> mST (mut s a)
unsafeThaw1 = liftM unM1 . unsafeThaw
{-# INLINE unsafeThaw1 #-}
unsafeFreeze1 :: (PhaseChange (imm a) (M1 mut a), MonadST mST, s ~ World mST) => mut s a -> mST (imm a)
unsafeFreeze1 = unsafeFreeze . M1
{-# INLINE unsafeFreeze1 #-}
copy1 :: (PhaseChange (imm a) (M1 mut a), MonadST mST, s ~ World mST) => mut s a -> mST (mut s a)
copy1 = liftM unM1 . copy . M1
{-# INLINE copy1 #-}
thaw1 :: (PhaseChange (imm a) (M1 mut a), MonadST mST, s ~ World mST) => imm a -> mST (mut s a)
thaw1 = liftM unM1 . thaw
{-# INLINE thaw1 #-}
freeze1 :: (PhaseChange (imm a) (M1 mut a), MonadST mST, s ~ World mST) => mut s a -> mST (imm a)
freeze1 = freeze . M1
{-# INLINE freeze1 #-}
frozen1 :: PhaseChange (imm a) (M1 mut a) => (forall s. ST s (mut s a)) -> imm a
frozen1 m = frozen (liftM M1 m)
{-# INLINE frozen1 #-}
updateWith1 :: PhaseChange (imm a) (M1 mut a) => (forall s. mut s a -> ST s ()) -> imm a -> imm a
updateWith1 f = updateWith (f . unM1)
{-# INLINE updateWith1 #-}
readWith1 :: PhaseChange (imm a) (M1 mut a) => (forall s. mut s a -> ST s b) -> imm a -> b
readWith1 f = readWith (f . unM1)
{-# INLINE readWith1 #-}
-- | Newtype for mutable types whose state thread parameter is in the third-to-last position
newtype M2 mut a b s = M2 { unM2 :: mut s a b }
--instance Newtype (M2 mut a b s) (mut s a b) where
-- pack = M2
-- unpack = unM2
unsafeThaw2 :: (PhaseChange (imm a b) (M2 mut a b), MonadST mST, s ~ World mST) => imm a b -> mST (mut s a b)
unsafeThaw2 = liftM unM2 . unsafeThaw
{-# INLINE unsafeThaw2 #-}
unsafeFreeze2 :: (PhaseChange (imm a b) (M2 mut a b), MonadST mST, s ~ World mST) => mut s a b -> mST (imm a b)
unsafeFreeze2 = unsafeFreeze . M2
{-# INLINE unsafeFreeze2 #-}
copy2 :: (PhaseChange (imm a b) (M2 mut a b), MonadST mST, s ~ World mST) => mut s a b -> mST (mut s a b)
copy2 = liftM unM2 . copy . M2
{-# INLINE copy2 #-}
thaw2 :: (PhaseChange (imm a b) (M2 mut a b), MonadST mST, s ~ World mST) => imm a b -> mST (mut s a b)
thaw2 = liftM unM2 . thaw
{-# INLINE thaw2 #-}
freeze2 :: (PhaseChange (imm a b) (M2 mut a b), MonadST mST, s ~ World mST) => mut s a b -> mST (imm a b)
freeze2 = freeze . M2
{-# INLINE freeze2 #-}
frozen2 :: PhaseChange (imm a b) (M2 mut a b) => (forall s. ST s (mut s a b)) -> imm a b
frozen2 m = frozen (liftM M2 m)
{-# INLINE frozen2 #-}
updateWith2 :: PhaseChange (imm a b) (M2 mut a b) => (forall s. mut s a b -> ST s ()) -> imm a b -> imm a b
updateWith2 f = updateWith (f . unM2)
{-# INLINE updateWith2 #-}
readWith2 :: PhaseChange (imm a b) (M2 mut a b) => (forall s. mut s a b -> ST s c) -> imm a b -> c
readWith2 f = readWith (f . unM2)
{-# INLINE readWith2 #-}
|
glaebhoerl/phasechange
|
Data/PhaseChange/Internal.hs
|
bsd-3-clause
| 10,970 | 0 | 11 | 2,363 | 2,407 | 1,273 | 1,134 | -1 | -1 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.Spiral
-- Copyright : (c) Joe Thornber <[email protected]>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Joe Thornber <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- A spiral tiling layout.
--
-----------------------------------------------------------------------------
module XMonad.Layout.Spiral (
-- * Usage
-- $usage
spiral
, spiralWithDir
, Rotation (..)
, Direction (..)
, SpiralWithDir
) where
import Data.Ratio
import XMonad hiding ( Rotation )
import XMonad.StackSet ( integrate )
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Layout.Spiral
--
-- Then edit your @layoutHook@ by adding the Spiral layout:
--
-- > myLayout = spiral (6/7) ||| etc..
-- > main = xmonad defaultConfig { layoutHook = myLayout }
--
-- For more detailed instructions on editing the layoutHook see:
--
-- "XMonad.Doc.Extending#Editing_the_layout_hook"
zipSelf :: (a -> a -> b) -> [a] -> [b]
zipSelf fn xs = zipWith fn xs (tail xs)
fibs :: [Integer]
fibs = 1 : 1 : zipSelf (+) fibs
mkRatios :: [Integer] -> [Rational]
mkRatios = zipSelf (%)
data Rotation = CW | CCW deriving (Read, Show)
data Direction = East | South | West | North deriving (Eq, Enum, Read, Show)
blend :: Rational -> [Rational] -> [Rational]
blend scale ratios = zipWith (+) ratios scaleFactors
where
len = length ratios
step = (scale - (1 % 1)) / (fromIntegral len)
scaleFactors = map (* step) . reverse . take len $ [1..]
-- | A spiral layout. The parameter controls the size ratio between
-- successive windows in the spiral. Sensible values range from 0
-- up to the aspect ratio of your monitor (often 4\/3).
--
-- By default, the spiral is counterclockwise, starting to the east.
-- See also 'spiralWithDir'.
spiral :: Rational -> SpiralWithDir a
spiral = spiralWithDir East CW
-- | Create a spiral layout, specifying the starting cardinal direction,
-- the spiral direction (clockwise or counterclockwise), and the
-- size ratio.
spiralWithDir :: Direction -> Rotation -> Rational -> SpiralWithDir a
spiralWithDir = SpiralWithDir
data SpiralWithDir a = SpiralWithDir Direction Rotation Rational
deriving ( Read, Show )
instance LayoutClass SpiralWithDir a where
pureLayout (SpiralWithDir dir rot scale) sc stack = zip ws rects
where ws = integrate stack
ratios = blend scale . reverse . take (length ws - 1) . mkRatios $ (drop 2 fibs)
rects = divideRects (zip ratios dirs) sc
dirs = dropWhile (/= dir) $ case rot of
CW -> cycle [East .. North]
CCW -> cycle [North, West, South, East]
handleMessage (SpiralWithDir dir rot scale) = return . fmap resize . fromMessage
where resize Expand = spiralWithDir dir rot $ (21 % 20) * scale
resize Shrink = spiralWithDir dir rot $ (20 % 21) * scale
description _ = "Spiral"
-- This will produce one more rectangle than there are splits details
divideRects :: [(Rational, Direction)] -> Rectangle -> [Rectangle]
divideRects [] r = [r]
divideRects ((r,d):xs) rect = case divideRect r d rect of
(r1, r2) -> r1 : (divideRects xs r2)
-- It's much simpler if we work with all Integers and convert to
-- Rectangle at the end.
data Rect = Rect Integer Integer Integer Integer
fromRect :: Rect -> Rectangle
fromRect (Rect x y w h) = Rectangle (fromIntegral x) (fromIntegral y) (fromIntegral w) (fromIntegral h)
toRect :: Rectangle -> Rect
toRect (Rectangle x y w h) = Rect (fromIntegral x) (fromIntegral y) (fromIntegral w) (fromIntegral h)
divideRect :: Rational -> Direction -> Rectangle -> (Rectangle, Rectangle)
divideRect r d rect = let (r1, r2) = divideRect' r d $ toRect rect in
(fromRect r1, fromRect r2)
divideRect' :: Rational -> Direction -> Rect -> (Rect, Rect)
divideRect' ratio dir (Rect x y w h) =
case dir of
East -> let (w1, w2) = chop ratio w in (Rect x y w1 h, Rect (x + w1) y w2 h)
South -> let (h1, h2) = chop ratio h in (Rect x y w h1, Rect x (y + h1) w h2)
West -> let (w1, w2) = chop (1 - ratio) w in (Rect (x + w1) y w2 h, Rect x y w1 h)
North -> let (h1, h2) = chop (1 - ratio) h in (Rect x (y + h1) w h2, Rect x y w h1)
chop :: Rational -> Integer -> (Integer, Integer)
chop rat n = let f = ((fromIntegral n) * (numerator rat)) `div` (denominator rat) in
(f, n - f)
|
jthornber/XMonadContrib
|
XMonad/Layout/Spiral.hs
|
bsd-3-clause
| 4,953 | 0 | 14 | 1,348 | 1,399 | 759 | 640 | 63 | 4 |
{-# LANGUAGE FlexibleContexts #-}
module SandBox.Text.CSS.Parsec.Combinator
( allInAnyOrder
, oneOrMoreInAnyOrder
, countRange
, countMax
, countMin
, manyUpTo
) where
import Text.Parsec ((<|>), Stream, ParsecT, many, try)
allInAnyOrder :: Stream s m t =>
[ParsecT s u m a] -> ParsecT s u m [a]
allInAnyOrder ps = walk ps []
where
walk :: Stream s m t => [ParsecT s u m a] -> [ParsecT s u m a] ->
ParsecT s u m [a]
walk [] [] = return []
walk [p] qs =
p >>= \r -> walk (reverse qs) [] >>= \s -> return (r:s)
walk (p:ps) qs =
(p >>= \r -> walk ((reverse qs)++ps) [] >>= \s -> return (r:s))
<|>
(walk ps (p:qs))
oneOrMoreInAnyOrder :: Stream s m t =>
[ParsecT s u m a] -> ParsecT s u m [a]
oneOrMoreInAnyOrder ps = walk ps [] []
where
walk :: Stream s m t => [ParsecT s u m a] -> [ParsecT s u m a] ->
[a] -> ParsecT s u m [a]
walk [] [] rs = return (reverse rs)
walk [p] qs rs =
p >>= \r -> (walk (reverse qs) [] (r:rs)
<|> return (reverse (r:rs))
)
walk (p:ps) qs rs =
(p >>= \r -> (walk ((reverse qs)++ps) [] (r:rs)
<|> return (reverse (r:rs))
)
)
<|>
(walk ps (p:qs) rs)
countRange :: Stream s m t =>
Int -> Int -> ParsecT s u m a -> ParsecT s u m [a]
countRange min max p
| min <= 0 = countMax max p
| otherwise = try p >>= \x ->
(try (countRange (min-1) (max-1) p) >>= \xs ->
return (x:xs))
countMax :: Stream s m t => Int -> ParsecT s u m a -> ParsecT s u m [a]
countMax max p
| max <= 0 = return []
| otherwise = (try p >>= \x ->
try (countMax (max-1) p) >>= \xs -> return (x:xs)
)
<|> return []
countMin :: Stream s m t => Int -> ParsecT s u m a -> ParsecT s u m [a]
countMin min p
| min <= 0 = many p
| otherwise = try p >>= \x ->
(try (countMin (min-1) p) >>= \xs -> return (x:xs))
manyUpTo :: Stream s m t =>
ParsecT s u m a -> ParsecT s u m a -> ParsecT s u m [a]
manyUpTo p end = scan
where
scan = do{ e <- end; return [e] }
<|> do{ x <- p; xs <- scan; return (x:xs) }
|
hnakamur/haskell-sandbox
|
sandbox-css/SandBox/Text/CSS/Parsec/Combinator.hs
|
bsd-3-clause
| 2,494 | 0 | 17 | 1,038 | 1,205 | 615 | 590 | 58 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (C) 2013-2014 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : provisional
-- Portability : portable
--
-- This module runs HLint on the source tree.
-----------------------------------------------------------------------------
module Main where
import Control.Monad
import Language.Haskell.HLint
import System.Environment
import System.Exit
main :: IO ()
main = do
args <- getArgs
hints <- hlint $ ["source", "--cpp-simple"] ++ args
unless (null hints) exitFailure
|
chaosmasttter/hexploration
|
tests/CodeTest.hs
|
bsd-3-clause
| 688 | 0 | 10 | 114 | 93 | 55 | 38 | 10 | 1 |
module Numeric.Optimisation.Bracket
( isBracket
, findBracket
) where
import Control.Arrow
import Control.Monad
isBracket :: (Num a, Ord a, Ord b) => ((a, b), (a, b), (a, b)) -> Bool
isBracket ((x1, f1), (x2, f2), (x3, f3)) =
((x2 - x1) * (x3 - x2) > 0 && f2 <= f1 && f2 <= f3)
{-# SPECIALIZE isBracket ::
((Double, Double), (Double, Double), (Double, Double)) -> Bool #-}
{-# SPECIALIZE isBracket ::
((Float, Float), (Float, Float), (Float, Float)) -> Bool #-}
findBracket :: (Floating a, Ord a) => (a -> a) -> a -> a
-> ((a, a), (a, a), (a, a))
findBracket f a' b'
| f b' > f a' = golden (b', f b') (a', f a')
| otherwise = golden (a', f a') (b', f b')
where
golden (a, fa) (b, fb) = go (a, fa) (b, fb) . (id &&& f) $
b + (1 + sqrt 5) / 2 * (b - a)
tiny = 1e-20
glimit = 100
go (a, fa) (b, fb) (c, fc)
| isBracket ((a, fa), (b, fb), (c, fc)) = ((a, fa), (b, fb), (c, fc))
| (b - u) * (u - c) > 0 && fu < fc = ((b, fb), (u, fu), (c, fc))
| (b - u) * (u - c) > 0 && fu > fb = ((a, fa), (b, fb), (u, fu))
| any (not . join (<=) . fst) pairs = let x = (id &&& f) (0/0) in (x, x, x)
| (b - u) * (u - c) > 0 = golden (b, fb) (c, fc)
| (c - u) * (u - ulim) > 0 && fu < fc = golden (c, fc) (u, fu)
| (c - u) * (u - ulim) > 0 = go (b, fb) (c, fc) (u, fu)
| (u - ulim) * (ulim - c) >= 0 = go (b, fb) (c, fc) (ulim, f ulim)
| otherwise = golden (b, fb) (c, fc)
where
pairs = [(a, fa), (b, fb), (c, fc), (u, fu)]
r = (b - a) * (fb - fc)
q = (b - c) * (fb - fa)
fu = f u
u = b - ((b - c) * q - (b - a) * r) /
(2 * max (abs (q - r)) tiny * signum (q - r))
ulim = b + glimit * (c - b)
{-- SPECIALIZE findBracket :: (Double -> Double) -> Double -> Double ->
((Double, Double), (Double, Double), (Double, Double)) #-}
{-- SPECIALIZE findBracket :: (Float -> Float) -> Float -> Float ->
((Float, Float), (Float, Float), (Float, Float)) #-}
|
alang9/unsmooth-opt
|
src/Numeric/Optimisation/Bracket.hs
|
bsd-3-clause
| 2,043 | 0 | 17 | 658 | 1,141 | 643 | 498 | 38 | 1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Freeze
-- Copyright : (c) David Himmelstrup 2005
-- Duncan Coutts 2011
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- The cabal freeze command
-----------------------------------------------------------------------------
module Distribution.Client.Freeze (
freeze, getFreezePkgs
) where
import Distribution.Client.Config ( SavedConfig(..) )
import Distribution.Client.Types
import Distribution.Client.Targets
import Distribution.Client.Dependency
import Distribution.Client.Dependency.Types
( ConstraintSource(..), LabeledPackageConstraint(..) )
import Distribution.Client.IndexUtils as IndexUtils
( getSourcePackages, getInstalledPackages )
import Distribution.Client.InstallPlan
( SolverInstallPlan, SolverPlanPackage )
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.PkgConfigDb
( PkgConfigDb, readPkgConfigDb )
import Distribution.Client.Setup
( GlobalFlags(..), FreezeFlags(..), ConfigExFlags(..)
, RepoContext(..) )
import Distribution.Client.Sandbox.PackageEnvironment
( loadUserConfig, pkgEnvSavedConfig, showPackageEnvironment,
userPackageEnvironmentFile )
import Distribution.Client.Sandbox.Types
( SandboxPackageInfo(..) )
import Distribution.Package
( Package, packageId, packageName, packageVersion, installedUnitId )
import Distribution.Simple.Compiler
( Compiler, compilerInfo, PackageDBStack )
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import Distribution.Simple.Program
( ProgramConfiguration )
import Distribution.Simple.Setup
( fromFlag, fromFlagOrDefault, flagToMaybe )
import Distribution.Simple.Utils
( die, notice, debug, writeFileAtomic )
import Distribution.System
( Platform )
import Distribution.Text
( display )
import Distribution.Verbosity
( Verbosity )
import Control.Monad
( when )
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
( mempty )
#endif
import Data.Version
( showVersion )
import Distribution.Version
( thisVersion )
-- ------------------------------------------------------------
-- * The freeze command
-- ------------------------------------------------------------
-- | Freeze all of the dependencies by writing a constraints section
-- constraining each dependency to an exact version.
--
freeze :: Verbosity
-> PackageDBStack
-> RepoContext
-> Compiler
-> Platform
-> ProgramConfiguration
-> Maybe SandboxPackageInfo
-> GlobalFlags
-> FreezeFlags
-> IO ()
freeze verbosity packageDBs repoCtxt comp platform conf mSandboxPkgInfo
globalFlags freezeFlags = do
pkgs <- getFreezePkgs
verbosity packageDBs repoCtxt comp platform conf mSandboxPkgInfo
globalFlags freezeFlags
if null pkgs
then notice verbosity $ "No packages to be frozen. "
++ "As this package has no dependencies."
else if dryRun
then notice verbosity $ unlines $
"The following packages would be frozen:"
: formatPkgs pkgs
else freezePackages verbosity globalFlags pkgs
where
dryRun = fromFlag (freezeDryRun freezeFlags)
-- | Get the list of packages whose versions would be frozen by the @freeze@
-- command.
getFreezePkgs :: Verbosity
-> PackageDBStack
-> RepoContext
-> Compiler
-> Platform
-> ProgramConfiguration
-> Maybe SandboxPackageInfo
-> GlobalFlags
-> FreezeFlags
-> IO [SolverPlanPackage]
getFreezePkgs verbosity packageDBs repoCtxt comp platform conf mSandboxPkgInfo
globalFlags freezeFlags = do
installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf
sourcePkgDb <- getSourcePackages verbosity repoCtxt
pkgConfigDb <- readPkgConfigDb verbosity conf
pkgSpecifiers <- resolveUserTargets verbosity repoCtxt
(fromFlag $ globalWorldFile globalFlags)
(packageIndex sourcePkgDb)
[UserTargetLocalDir "."]
sanityCheck pkgSpecifiers
planPackages
verbosity comp platform mSandboxPkgInfo freezeFlags
installedPkgIndex sourcePkgDb pkgConfigDb pkgSpecifiers
where
sanityCheck pkgSpecifiers = do
when (not . null $ [n | n@(NamedPackage _ _) <- pkgSpecifiers]) $
die $ "internal error: 'resolveUserTargets' returned "
++ "unexpected named package specifiers!"
when (length pkgSpecifiers /= 1) $
die $ "internal error: 'resolveUserTargets' returned "
++ "unexpected source package specifiers!"
planPackages :: Verbosity
-> Compiler
-> Platform
-> Maybe SandboxPackageInfo
-> FreezeFlags
-> InstalledPackageIndex
-> SourcePackageDb
-> PkgConfigDb
-> [PackageSpecifier UnresolvedSourcePackage]
-> IO [SolverPlanPackage]
planPackages verbosity comp platform mSandboxPkgInfo freezeFlags
installedPkgIndex sourcePkgDb pkgConfigDb pkgSpecifiers = do
solver <- chooseSolver verbosity
(fromFlag (freezeSolver freezeFlags)) (compilerInfo comp)
notice verbosity "Resolving dependencies..."
installPlan <- foldProgress logMsg die return $
resolveDependencies
platform (compilerInfo comp) pkgConfigDb
solver
resolverParams
return $ pruneInstallPlan installPlan pkgSpecifiers
where
resolverParams =
setMaxBackjumps (if maxBackjumps < 0 then Nothing
else Just maxBackjumps)
. setIndependentGoals independentGoals
. setReorderGoals reorderGoals
. setShadowPkgs shadowPkgs
. setStrongFlags strongFlags
. addConstraints
[ let pkg = pkgSpecifierTarget pkgSpecifier
pc = PackageConstraintStanzas pkg stanzas
in LabeledPackageConstraint pc ConstraintSourceFreeze
| pkgSpecifier <- pkgSpecifiers ]
. maybe id applySandboxInstallPolicy mSandboxPkgInfo
$ standardInstallPolicy installedPkgIndex sourcePkgDb pkgSpecifiers
logMsg message rest = debug verbosity message >> rest
stanzas = [ TestStanzas | testsEnabled ]
++ [ BenchStanzas | benchmarksEnabled ]
testsEnabled = fromFlagOrDefault False $ freezeTests freezeFlags
benchmarksEnabled = fromFlagOrDefault False $ freezeBenchmarks freezeFlags
reorderGoals = fromFlag (freezeReorderGoals freezeFlags)
independentGoals = fromFlag (freezeIndependentGoals freezeFlags)
shadowPkgs = fromFlag (freezeShadowPkgs freezeFlags)
strongFlags = fromFlag (freezeStrongFlags freezeFlags)
maxBackjumps = fromFlag (freezeMaxBackjumps freezeFlags)
-- | Remove all unneeded packages from an install plan.
--
-- A package is unneeded if it is either
--
-- 1) the package that we are freezing, or
--
-- 2) not a dependency (directly or transitively) of the package we are
-- freezing. This is useful for removing previously installed packages
-- which are no longer required from the install plan.
--
-- Invariant: @pkgSpecifiers@ must refer to packages which are not
-- 'PreExisting' in the 'SolverInstallPlan'.
pruneInstallPlan :: SolverInstallPlan
-> [PackageSpecifier UnresolvedSourcePackage]
-> [SolverPlanPackage]
pruneInstallPlan installPlan pkgSpecifiers =
removeSelf pkgIds $
InstallPlan.dependencyClosure installPlan (map installedUnitId pkgIds)
where
pkgIds = [ PlannedId (packageId pkg)
| SpecificSourcePackage pkg <- pkgSpecifiers ]
removeSelf [thisPkg] = filter (\pp -> packageId pp /= packageId thisPkg)
removeSelf _ = error $ "internal error: 'pruneInstallPlan' given "
++ "unexpected package specifiers!"
freezePackages :: Package pkg => Verbosity -> GlobalFlags -> [pkg] -> IO ()
freezePackages verbosity globalFlags pkgs = do
pkgEnv <- fmap (createPkgEnv . addFrozenConstraints) $
loadUserConfig verbosity "" (flagToMaybe . globalConstraintsFile $ globalFlags)
writeFileAtomic userPackageEnvironmentFile $ showPkgEnv pkgEnv
where
addFrozenConstraints config =
config {
savedConfigureExFlags = (savedConfigureExFlags config) {
configExConstraints = map constraint pkgs
}
}
constraint pkg =
(pkgIdToConstraint $ packageId pkg, ConstraintSourceUserConfig userPackageEnvironmentFile)
where
pkgIdToConstraint pkgId =
UserConstraintVersion (packageName pkgId)
(thisVersion $ packageVersion pkgId)
createPkgEnv config = mempty { pkgEnvSavedConfig = config }
showPkgEnv = BS.Char8.pack . showPackageEnvironment
formatPkgs :: Package pkg => [pkg] -> [String]
formatPkgs = map $ showPkg . packageId
where
showPkg pid = name pid ++ " == " ++ version pid
name = display . packageName
version = showVersion . packageVersion
|
gbaz/cabal
|
cabal-install/Distribution/Client/Freeze.hs
|
bsd-3-clause
| 9,667 | 0 | 20 | 2,490 | 1,716 | 921 | 795 | 181 | 3 |
module UI where
import UI.PlaybackStatus
import Graphics.Vty
import Graphics.Vty.Widgets.All
import Data.Monoid (mempty)
type Choose = IO ()
context :: RenderContext
context = defaultContext
{ focusAttr = white `on` blue
}
-- | The status box consists of a single progress bar widget, whose text
-- contents are the status of the currently playing song.
newStatusBox = do
(play,bar) <- newPlaybackStatus (white `on` blue) (black `on` cyan)
setPlaybackProgress play 50
setPlaybackArtist play "the artist name"
setPlaybackTitle play "the title name"
return bar
playerInterface :: Collection -> IO Choose
playerInterface c = do
fg <- newFocusGroup
statusBox <- newStatusBox
songs <- newStringList mempty ["x", "y", "z"]
addToFocusGroup fg songs
interface <- return statusBox <--> return songs
setBoxChildSizePolicy interface (PerChild (BoxFixed 1) BoxAuto)
songs `onKeyPressed` \ _ k _ -> case k of
KASCII 'k' -> scrollUp songs >> return True
KASCII 'j' -> scrollDown songs >> return True
_ -> return False
fg `onKeyPressed` \ _ k _ -> case k of
KASCII 'q' -> shutdownUi >> return True
KASCII 's' -> focus songs >> return True
_ -> return False
addToCollection c interface fg
|
elliottt/din
|
src/UI.hs
|
bsd-3-clause
| 1,265 | 0 | 13 | 275 | 386 | 192 | 194 | 32 | 5 |
module Sexy.Instances.Applicative.Function () where
import Sexy.Classes (Applicative(..))
import Sexy.Instances.Functor.Function ()
import Sexy.Instances.Pure.Function ()
instance Applicative ((->) a) where
-- (<*>) :: (a -> b -> c) -> (a -> b) -> (a -> c)
f <*> g = \x -> f x (g x)
|
DanBurton/sexy
|
src/Sexy/Instances/Applicative/Function.hs
|
bsd-3-clause
| 290 | 0 | 9 | 51 | 90 | 54 | 36 | 6 | 0 |
module Parser where
import Text.Parsec as P
import Data.List
import Language
parseModuleDecl :: Parsec String () ModuleDecl
parseModuleDecl
= do
string "module"
spaces
name <- many1 letter
spaces
char ';'
return $ Module name
parseImportDirective :: Parsec String () ImportDirective
parseImportDirective
= do
string "import"
spaces
name <- many1 letter
spaces
char ';'
return $ Import name
word :: Parsec String () String
word
= do
lead <- leadChar
rest <- many wordChar
spaces
return $ lead : rest
where
leadChar = letter <|> char '_'
wordChar = leadChar <|> digit
-- TODO: real type parsing
parseArgument :: Parsec String () Argument
parseArgument
= do
spaces
words <- many1 word
P.optional $ char ','
let typeString = concat $ intersperse " " $ init words
let nameString = last words
return $ Argument typeString nameString
parseArgumentList :: Parsec String () [Argument]
parseArgumentList
= do
char '('
arguments <- many parseArgument
char ')'
return arguments
parseBody :: Parsec String () String
parseBody
= do
char '{'
body <- many $ noneOf "}"
char '}'
return body
--parseDelcaration :: Parsec String () (Either Function TypeDefinition)
--parseDelcaration
-- = do
-- words <- many1 word
-- argumentList <- optionMaybe $ parseArgumentList
-- spaces
-- body <- parseBody
-- return $
|
mbelicki/pure-sea
|
src/Parser.hs
|
bsd-3-clause
| 1,640 | 0 | 12 | 557 | 407 | 189 | 218 | 54 | 1 |
{-# LANGUAGE
DeriveDataTypeable
, DeriveGeneric
, TemplateHaskell
#-}
module Observations where
import Evidence
import Data.Set (Set)
import qualified Data.Set as Set
type Observations name p = Set (Evidence name p)
conclude :: (Ord p, Ord name) => [Evidence name p] -> Observations name p
conclude ev = Set.fromList ev
join_observations :: (Ord name, Ord p) => [Observations name p] -> Observations name p
join_observations obs = Set.unions obs
observations_toList :: Observations name p -> [Evidence name p]
observations_toList obs = Set.toList obs
has_fact :: (Ord name, Ord p) => Evidence name p -> Observations name p -> Bool
has_fact e o = Set.member e o
|
jcberentsen/causality
|
src/Observations.hs
|
bsd-3-clause
| 686 | 0 | 8 | 130 | 235 | 123 | 112 | 17 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module : Halytics.Metric
-- Copyright : (c) 2016 Nicolas Mattia
-- License : MIT
-- Maintainer : Nicolas Mattia <[email protected]>
-- Stability : experimental
--
-- ...
module Halytics.Metric where
import Data.List
import Data.List.Split (chunksOf)
import Data.Proxy
import GHC.TypeLits
import Halytics.Monitor.Tuple
-- $setup
-- >>> :set -XDataKinds
-- >>> :set -XTypeOperators
-- >>> :set -XFlexibleContexts
-- >>> :set -XKindSignatures
-- >>> import Safe (maximumMay, minimumMay)
{-|
'All' will simply give back all the entries collected. This should mostly be
used for testing.
>>> let monitor = generate :: Monitor All
>>> result (notifyMany monitor [1.0,2.0,3.0]) :: [Double]
[1.0,2.0,3.0]
The following property should hold:
prop> result (notifyMany (generate :: Monitor All) xs) == xs
-}
data All :: *
instance Collect All where
type S All = [Double]
collect _ = flip (:)
instance Default All where
initial _ = []
instance Resultable All [Double] where
r _ = reverse
instance Resultable All String where
r _ [] = "Collected: (none)"
r _ xs = "Collected: " ++ intercalate ", " (show <$> reverse xs)
{-|
'Max' will result in the largest entry collected so far. If no entry was
collected so far, results in 'Nothing'. If any entry was collected, results
in 'Just' the maximum.
>>> let monitor = generate :: Monitor Max
>>> result (notifyMany monitor [1.0,2.0,3.0]) :: Maybe Double
Just 3.0
>>> result (notifyMany monitor []) :: Maybe Double
Nothing
The following property should hold:
prop> result (notifyMany (generate :: Monitor Max) xs) == maximumMay xs
-}
data Max
instance Collect Max where
type S Max = Maybe Double
collect _ (Just !x) x' = Just $ max x x'
collect _ Nothing x' = Just x'
instance Default Max where
initial _ = Nothing
instance Resultable Max (Maybe Double) where
r _ x = x
instance Resultable Max String where
r _ xs = maybe naught (\x -> "Max: " ++ show x) res
where
naught = "No maximum found"
res = r (Proxy :: Proxy Max) xs :: Maybe Double
{-|
'Min' will result in the smallest entry collected so far. If no entry was
collected so far, results in 'Nothing'. If any entry was collected, results
in 'Just' the minimum.
>>> let monitor = generate :: Monitor Min
>>> result (notifyMany monitor [1.0,2.0,3.0]) :: Maybe Double
Just 1.0
>>> result (notifyMany monitor []) :: Maybe Double
Nothing
The following property should hold:
prop> result (notifyMany (generate :: Monitor Min) xs) == minimumMay xs
-}
data Min
instance Collect Min where
type S Min = Maybe Double
collect _ (Just !x) x' = Just $ min x x'
collect _ Nothing x' = Just x'
instance Default Min where
initial _ = Nothing
instance Resultable Min (Maybe Double) where
r _ x = x
instance Resultable Min String where
r _ xs = maybe naught (\x -> "Min: " ++ show x) res
where
naught = "No minimum found"
res = r (Proxy :: Proxy Min) xs :: Maybe Double
-- Combinators
{-|
'Every' will feed another metric every @n@th element collected. 'Every' will
feed the metric the first, @n+1@ th, @2n+1@ th, ... collected elements.
>>> let monitor = generate :: Monitor (All |^ Every 2)
>>> result (notifyMany monitor [1.0,2.0,3.0,2.0,1.0]) :: [Double]
[1.0,3.0,1.0]
-}
data Every :: Nat -> * -> *
-- TODO: Use pattern guards instead
instance (Collect s, KnownNat n) => Collect (Every n s) where
type S (Every n s) = (Integer, S s)
collect _ (1, s) x = ( natVal (Proxy :: Proxy n)
, collect (Proxy :: Proxy s) s x )
collect _ (n, s) _ = (n-1, s)
instance (KnownNat n, Default s) => Default (Every n s) where
initial _ = (1, initial (Proxy :: Proxy s))
instance (Resultable t r) => Resultable (Every n t) r where
r _ (_, s) = r (Proxy :: Proxy t) s
{-|
'Last' will feed another metric the last @n@ elements collected.
>>> let monitor = generate :: Monitor (All |^ Last 2)
>>> result (notifyMany monitor [1.0,2.0,3.0,2.0,1.0]) :: [Double]
[2.0,1.0]
-}
data Last :: Nat -> * -> *
instance (KnownNat n) => Collect (Last n s) where
type S (Last n s) = [Double]
collect _ xs x = take n (x:xs)
where
n = fromInteger $ natVal (Proxy :: Proxy n) :: Int
instance Default (Last n s) where
initial _ = []
instance (Default t, Collect t, Resultable t r) => Resultable (Last n t) r where
r _ xs = r (Proxy :: Proxy t) s
where
s = foldl' (collect (Proxy :: Proxy t))
(initial (Proxy :: Proxy t))
$ reverse xs
{-|
'PeriodOf' will feed another metric with chunks of @n@ elements. 'result'
returns the list of the results (one for each chunk).
>>> let monitor = generate :: Monitor (All |^ PeriodOf 2)
>>> result (notifyMany monitor [1.0,2.0,3.0,2.0,1.0]) :: [[Double]]
[[1.0,2.0],[3.0,2.0],[1.0]]
-}
data PeriodOf :: Nat -> * -> *
instance Collect (PeriodOf n s) where
type S (PeriodOf n s) = [Double]
collect _ = flip (:)
instance Default (PeriodOf n s) where
initial _ = []
instance (KnownNat n, Resultable t r, Collect t, Default t)
=> Resultable (PeriodOf n t) [r] where
r _ xs = r (Proxy :: Proxy t) <$> ss
where
ss = foldl' f x0 <$> xss
xss = chunksOf n (reverse xs)
n = fromInteger $ natVal (Proxy :: Proxy n) :: Int
f = collect (Proxy :: Proxy t)
x0 = initial (Proxy :: Proxy t)
|
nmattia/halytics
|
src/Halytics/Metric.hs
|
bsd-3-clause
| 5,702 | 0 | 13 | 1,317 | 1,333 | 709 | 624 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RecordWildCards #-}
module CANOpen.Tower.PDO where
import Ivory.Language
import Ivory.Stdlib
import Ivory.Tower
import Ivory.Tower.HAL.Bus.CAN
import Ivory.Tower.HAL.Bus.Interface
import Ivory.Tower.HAL.Bus.CAN.Fragment
import CANOpen.Ivory.Types
import CANOpen.Tower.Utils
import CANOpen.Tower.Types
import CANOpen.Tower.SDO.Types
import Ivory.Serialize.LittleEndian
import CANOpen.Ivory.Types.PdoCommParam
import CANOpen.Ivory.Types.PdoCommMap
--import CANOpen.Ivory.Types.VarArrayPdoCommMap
import CANOpen.Tower.Attr
import CANOpen.Tower.Interface.Base.Dict
pdoBase :: Uint16
pdoBase = 0x180
pdoTower :: ChanOutput ('Struct "can_message")
-> AbortableTransmit ('Struct "can_message") ('Stored IBool)
-> ObjDict
-> BaseAttrs Attr
-> Tower e ()
pdoTower res req ObjDict{..} BaseAttrs{..} = do
monitor "pdo_controller" $ do
-- attrHandler (head $ tpdos attrs) $ callback $ const $ return ()
-- (\x -> attrHandler x $ callback $ const $ return ())
-- (head $ tpdos attrs)
--
tstates <- mapM (\(p, m) -> attrState p) tpdos
mapM_ (\((p, m), s) -> attrHandler p $ callback $ refCopy s)
(zip tpdos tstates)
received <- stateInit "pdo_received" (ival (0 :: Uint32))
handled <- stateInit "pdo_handled" (ival (0 :: Uint32))
--reqe <- emitter (abortableTransmit req) 1
handler res "pdomsg" $ do
callback $ \msg -> do
received += 1
cid <- getStdCANId msg
flip mapM_ tstates $ \s -> do
cidPDO <- s ~>* cob_id
when (cid ==? cidPDO) $ do
handled += 1
|
distrap/ivory-tower-canopen
|
src/CANOpen/Tower/PDO.hs
|
bsd-3-clause
| 1,632 | 0 | 24 | 349 | 443 | 242 | 201 | 40 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
module Streaming.Internal (
-- * The free monad transformer
-- $stream
Stream (..)
-- * Introducing a stream
, unfold
, replicates
, repeats
, repeatsM
, effect
, wrap
, yields
, streamBuild
, cycles
, delays
, never
, untilJust
-- * Eliminating a stream
, intercalates
, concats
, iterT
, iterTM
, destroy
, streamFold
-- * Inspecting a stream wrap by wrap
, inspect
-- * Transforming streams
, maps
, mapsM
, mapsPost
, mapsMPost
, hoistUnexposed
, decompose
, mapsM_
, run
, distribute
, groups
-- , groupInL
-- * Splitting streams
, chunksOf
, splitsAt
, takes
, cutoff
-- , period
-- , periods
-- * Zipping and unzipping streams
, zipsWith
, zipsWith'
, zips
, unzips
, interleaves
, separate
, unseparate
, expand
, expandPost
-- * Assorted Data.Functor.x help
, switch
-- * For use in implementation
, unexposed
, hoistExposed
, hoistExposedPost
, mapsExposed
, mapsMExposed
, destroyExposed
) where
import Control.Applicative
import Control.Concurrent (threadDelay)
import Control.Monad
import Control.Monad.Error.Class
import Control.Monad.Fail as Fail
import Control.Monad.Morph
import Control.Monad.Reader.Class
import Control.Monad.State.Class
import Control.Monad.Trans
import Data.Data (Typeable)
import Data.Function ( on )
import Data.Functor.Classes
import Data.Functor.Compose
import Data.Functor.Sum
import Data.Monoid (Monoid (..))
import Data.Semigroup (Semigroup (..))
-- $setup
-- >>> import Streaming.Prelude as S
{- $stream
The 'Stream' data type is equivalent to @FreeT@ and can represent any effectful
succession of steps, where the form of the steps or 'commands' is
specified by the first (functor) parameter.
> data Stream f m r = Step !(f (Stream f m r)) | Effect (m (Stream f m r)) | Return r
The /producer/ concept uses the simple functor @ (a,_) @ \- or the stricter
@ Of a _ @. Then the news at each step or layer is just: an individual item of type @a@.
Since @Stream (Of a) m r@ is equivalent to @Pipe.Producer a m r@, much of
the @pipes@ @Prelude@ can easily be mirrored in a @streaming@ @Prelude@. Similarly,
a simple @Consumer a m r@ or @Parser a m r@ concept arises when the base functor is
@ (a -> _) @ . @Stream ((->) input) m result@ consumes @input@ until it returns a
@result@.
To avoid breaking reasoning principles, the constructors
should not be used directly. A pattern-match should go by way of 'inspect' \
\- or, in the producer case, 'Streaming.Prelude.next'
The constructors are exported by the 'Internal' module.
-}
data Stream f m r = Step !(f (Stream f m r))
| Effect (m (Stream f m r))
| Return r
#if __GLASGOW_HASKELL__ >= 710
deriving (Typeable)
#endif
-- The most obvious approach would probably be
--
-- s1 == s2 = eqUnexposed (unexposed s1) (unexposed s2)
--
-- but that seems to actually be rather hard (especially if performance
-- matters even a little bit). Using `inspect` instead
-- is nice and simple. The main downside is the rather weird-looking
-- constraint it imposes. We *could* write
--
-- instance (Monad m, Eq r, Eq1 m, Eq1 f) => Eq (Stream f m r)
--
-- but there are an awful lot more Eq instances in the wild than
-- Eq1 instances. Maybe some day soon we'll have implication constraints
-- and everything will be beautiful.
instance (Monad m, Eq (m (Either r (f (Stream f m r)))))
=> Eq (Stream f m r) where
s1 == s2 = inspect s1 == inspect s2
-- See the notes on Eq.
instance (Monad m, Ord (m (Either r (f (Stream f m r)))))
=> Ord (Stream f m r) where
compare = compare `on` inspect
(<) = (<) `on` inspect
(>) = (>) `on` inspect
(<=) = (<=) `on` inspect
(>=) = (>=) `on` inspect
#if MIN_VERSION_base(4,9,0)
-- We could avoid a Show1 constraint for our Show1 instance by sneakily
-- mapping everything to a single known type, but there's really no way
-- to do that for Eq1 or Ord1.
instance (Monad m, Functor f, Eq1 m, Eq1 f) => Eq1 (Stream f m) where
liftEq eq xs ys = liftEqExposed (unexposed xs) (unexposed ys)
where
liftEqExposed (Return x) (Return y) = eq x y
liftEqExposed (Effect m) (Effect n) = liftEq liftEqExposed m n
liftEqExposed (Step f) (Step g) = liftEq liftEqExposed f g
liftEqExposed _ _ = False
instance (Monad m, Functor f, Ord1 m, Ord1 f) => Ord1 (Stream f m) where
liftCompare cmp xs ys = liftCmpExposed (unexposed xs) (unexposed ys)
where
liftCmpExposed (Return x) (Return y) = cmp x y
liftCmpExposed (Effect m) (Effect n) = liftCompare liftCmpExposed m n
liftCmpExposed (Step f) (Step g) = liftCompare liftCmpExposed f g
liftCmpExposed (Return _) _ = LT
liftCmpExposed _ (Return _) = GT
liftCmpExposed _ _ = error "liftCmpExposed: stream was exposed!"
#endif
-- We could get a much less scary implementation using Show1, but
-- Show1 instances aren't nearly as common as Show instances.
--
-- How does this
-- funny-looking instance work?
--
-- We 'inspect' the stream to produce @m (Either r (Stream f m r))@.
-- Then we work under @m@ to produce @m ShowSWrapper@. That's almost
-- like producing @m String@, except that a @ShowSWrapper@ can be
-- shown at any precedence. So the 'Show' instance for @m@ can show
-- the contents at the correct precedence.
instance (Monad m, Show r, Show (m ShowSWrapper), Show (f (Stream f m r)))
=> Show (Stream f m r) where
showsPrec p xs = showParen (p > 10) $
showString "Effect " . (showsPrec 11 $
flip fmap (inspect xs) $ \front ->
SS $ \d -> showParen (d > 10) $
case front of
Left r -> showString "Return " . showsPrec 11 r
Right f -> showString "Step " . showsPrec 11 f)
#if MIN_VERSION_base(4,9,0)
instance (Monad m, Functor f, Show (m ShowSWrapper), Show (f ShowSWrapper))
=> Show1 (Stream f m) where
liftShowsPrec sp sl p xs = showParen (p > 10) $
showString "Effect " . (showsPrec 11 $
flip fmap (inspect xs) $ \front ->
SS $ \d -> showParen (d > 10) $
case front of
Left r -> showString "Return " . sp 11 r
Right f -> showString "Step " .
showsPrec 11 (fmap (SS . (\str i -> liftShowsPrec sp sl i str)) f))
#endif
newtype ShowSWrapper = SS (Int -> ShowS)
instance Show ShowSWrapper where
showsPrec p (SS s) = s p
-- | Operates covariantly on the stream result, not on its elements:
--
-- @
-- Stream (Of a) m r
-- ^ ^
-- | `--- This is what `Functor` and `Applicative` use
-- `--- This is what functions like S.map/S.zipWith use
-- @
instance (Functor f, Monad m) => Functor (Stream f m) where
fmap f = loop where
loop stream = case stream of
Return r -> Return (f r)
Effect m -> Effect (do {stream' <- m; return (loop stream')})
Step g -> Step (fmap loop g)
{-# INLINABLE fmap #-}
a <$ stream0 = loop stream0 where
loop stream = case stream of
Return _ -> Return a
Effect m -> Effect (do {stream' <- m; return (loop stream')})
Step f -> Step (fmap loop f)
{-# INLINABLE (<$) #-}
instance (Functor f, Monad m) => Monad (Stream f m) where
return = pure
{-# INLINE return #-}
(>>) = (*>)
{-# INLINE (>>) #-}
-- (>>=) = _bind
-- {-# INLINE (>>=) #-}
--
stream >>= f =
loop stream where
loop stream0 = case stream0 of
Step fstr -> Step (fmap loop fstr)
Effect m -> Effect (fmap loop m)
Return r -> f r
{-# INLINABLE (>>=) #-}
#if !(MIN_VERSION_base(4,13,0))
fail = lift . Prelude.fail
{-# INLINE fail #-}
#endif
instance (Functor f, MonadFail m) => MonadFail (Stream f m) where
fail = lift . Fail.fail
{-# INLINE fail #-}
-- _bind
-- :: (Functor f, Monad m)
-- => Stream f m r
-- -> (r -> Stream f m s)
-- -> Stream f m s
-- _bind p0 f = go p0 where
-- go p = case p of
-- Step fstr -> Step (fmap go fstr)
-- Effect m -> Effect (m >>= \s -> return (go s))
-- Return r -> f r
-- {-# INLINABLE _bind #-}
--
-- see https://github.com/Gabriel439/Haskell-Pipes-Library/pull/163
-- for a plan to delay inlining and manage interaction with other operations.
-- {-# RULES
-- "_bind (Step fstr) f" forall fstr f .
-- _bind (Step fstr) f = Step (fmap (\p -> _bind p f) fstr);
-- "_bind (Effect m) f" forall m f .
-- _bind (Effect m) f = Effect (m >>= \p -> return (_bind p f));
-- "_bind (Return r) f" forall r f .
-- _bind (Return r) f = f r;
-- #-}
instance (Functor f, Monad m) => Applicative (Stream f m) where
pure = Return
{-# INLINE pure #-}
streamf <*> streamx = do {f <- streamf; x <- streamx; return (f x)}
{-# INLINE (<*>) #-}
stream1 *> stream2 = loop stream1 where
loop stream = case stream of
Return _ -> stream2
Effect m -> Effect (fmap loop m)
Step f -> Step (fmap loop f)
{-# INLINABLE (*>) #-}
{- | The 'Alternative' instance glues streams together stepwise.
> empty = never
> (<|>) = zipsWith (liftA2 (,))
See also 'never', 'untilJust' and 'delays'
-}
instance (Applicative f, Monad m) => Alternative (Stream f m) where
empty = never
{-# INLINE empty #-}
str <|> str' = zipsWith' liftA2 str str'
{-# INLINE (<|>) #-}
instance (Functor f, Monad m, Semigroup w) => Semigroup (Stream f m w) where
a <> b = a >>= \w -> fmap (w <>) b
{-# INLINE (<>) #-}
instance (Functor f, Monad m, Monoid w) => Monoid (Stream f m w) where
mempty = return mempty
{-# INLINE mempty #-}
#if !(MIN_VERSION_base(4,11,0))
mappend a b = a >>= \w -> fmap (w `mappend`) b
{-# INLINE mappend #-}
#endif
instance (Applicative f, Monad m) => MonadPlus (Stream f m) where
mzero = empty
mplus = (<|>)
instance Functor f => MonadTrans (Stream f) where
lift = Effect . fmap Return
{-# INLINE lift #-}
instance Functor f => MFunctor (Stream f) where
hoist trans = loop where
loop stream = case stream of
Return r -> Return r
Effect m -> Effect (trans (fmap loop m))
Step f -> Step (fmap loop f)
{-# INLINABLE hoist #-}
instance Functor f => MMonad (Stream f) where
embed phi = loop where
loop stream = case stream of
Return r -> Return r
Effect m -> phi m >>= loop
Step f -> Step (fmap loop f)
{-# INLINABLE embed #-}
instance (MonadIO m, Functor f) => MonadIO (Stream f m) where
liftIO = Effect . fmap Return . liftIO
{-# INLINE liftIO #-}
instance (Functor f, MonadReader r m) => MonadReader r (Stream f m) where
ask = lift ask
{-# INLINE ask #-}
local f = hoist (local f)
{-# INLINE local #-}
instance (Functor f, MonadState s m) => MonadState s (Stream f m) where
get = lift get
{-# INLINE get #-}
put = lift . put
{-# INLINE put #-}
#if MIN_VERSION_mtl(2,1,1)
state f = lift (state f)
{-# INLINE state #-}
#endif
instance (Functor f, MonadError e m) => MonadError e (Stream f m) where
throwError = lift . throwError
{-# INLINE throwError #-}
str `catchError` f = loop str where
loop x = case x of
Return r -> Return r
Effect m -> Effect $ fmap loop m `catchError` (return . f)
Step g -> Step (fmap loop g)
{-# INLINABLE catchError #-}
{-| Map a stream to its church encoding; compare @Data.List.foldr@.
'destroyExposed' may be more efficient in some cases when
applicable, but it is less safe.
@
destroy s construct eff done
= eff . iterT (return . construct . fmap eff) . fmap done $ s
@
-}
destroy
:: (Functor f, Monad m) =>
Stream f m r -> (f b -> b) -> (m b -> b) -> (r -> b) -> b
destroy stream0 construct theEffect done = theEffect (loop stream0) where
loop stream = case stream of
Return r -> return (done r)
Effect m -> m >>= loop
Step fs -> return (construct (fmap (theEffect . loop) fs))
{-# INLINABLE destroy #-}
{-| 'streamFold' reorders the arguments of 'destroy' to be more akin
to @foldr@ It is more convenient to query in ghci to figure out
what kind of \'algebra\' you need to write.
>>> :t streamFold return join
(Monad m, Functor f) =>
(f (m a) -> m a) -> Stream f m a -> m a -- iterT
>>> :t streamFold return (join . lift)
(Monad m, Monad (t m), Functor f, MonadTrans t) =>
(f (t m a) -> t m a) -> Stream f m a -> t m a -- iterTM
>>> :t streamFold return effect
(Monad m, Functor f, Functor g) =>
(f (Stream g m r) -> Stream g m r) -> Stream f m r -> Stream g m r
>>> :t \f -> streamFold return effect (wrap . f)
(Monad m, Functor f, Functor g) =>
(f (Stream g m a) -> g (Stream g m a))
-> Stream f m a -> Stream g m a -- maps
>>> :t \f -> streamFold return effect (effect . fmap wrap . f)
(Monad m, Functor f, Functor g) =>
(f (Stream g m a) -> m (g (Stream g m a)))
-> Stream f m a -> Stream g m a -- mapped
@
streamFold done eff construct
= eff . iterT (return . construct . fmap eff) . fmap done
@
-}
streamFold
:: (Functor f, Monad m) =>
(r -> b) -> (m b -> b) -> (f b -> b) -> Stream f m r -> b
streamFold done theEffect construct stream = destroy stream construct theEffect done
{-# INLINE streamFold #-}
{- | Reflect a church-encoded stream; cp. @GHC.Exts.build@
> streamFold return_ effect_ step_ (streamBuild psi) = psi return_ effect_ step_
-}
streamBuild
:: (forall b . (r -> b) -> (m b -> b) -> (f b -> b) -> b) -> Stream f m r
streamBuild = \phi -> phi Return Effect Step
{-# INLINE streamBuild #-}
{-| Inspect the first stage of a freely layered sequence.
Compare @Pipes.next@ and the replica @Streaming.Prelude.next@.
This is the 'uncons' for the general 'unfold'.
> unfold inspect = id
> Streaming.Prelude.unfoldr StreamingPrelude.next = id
-}
inspect :: Monad m =>
Stream f m r -> m (Either r (f (Stream f m r)))
inspect = loop where
loop stream = case stream of
Return r -> return (Left r)
Effect m -> m >>= loop
Step fs -> return (Right fs)
{-# INLINABLE inspect #-}
{-| Build a @Stream@ by unfolding steps starting from a seed. See also
the specialized 'Streaming.Prelude.unfoldr' in the prelude.
> unfold inspect = id -- modulo the quotient we work with
> unfold Pipes.next :: Monad m => Producer a m r -> Stream ((,) a) m r
> unfold (curry (:>) . Pipes.next) :: Monad m => Producer a m r -> Stream (Of a) m r
-}
unfold :: (Monad m, Functor f)
=> (s -> m (Either r (f s)))
-> s -> Stream f m r
unfold step = loop where
loop s0 = Effect $ do
e <- step s0
return $ case e of
Left r -> Return r
Right fs -> Step (fmap loop fs)
{-# INLINABLE unfold #-}
{- | Map layers of one functor to another with a transformation. Compare
hoist, which has a similar effect on the 'monadic' parameter.
> maps id = id
> maps f . maps g = maps (f . g)
-}
maps :: (Monad m, Functor f)
=> (forall x . f x -> g x) -> Stream f m r -> Stream g m r
maps phi = loop where
loop stream = case stream of
Return r -> Return r
Effect m -> Effect (fmap loop m)
Step f -> Step (phi (fmap loop f))
{-# INLINABLE maps #-}
{- | Map layers of one functor to another with a transformation involving the base monad.
'maps' is more fundamental than @mapsM@, which is best understood as a convenience
for effecting this frequent composition:
> mapsM phi = decompose . maps (Compose . phi)
The streaming prelude exports the same function under the better name @mapped@,
which overlaps with the lens libraries.
-}
mapsM :: (Monad m, Functor f) => (forall x . f x -> m (g x)) -> Stream f m r -> Stream g m r
mapsM phi = loop where
loop stream = case stream of
Return r -> Return r
Effect m -> Effect (fmap loop m)
Step f -> Effect (fmap Step (phi (fmap loop f)))
{-# INLINABLE mapsM #-}
{- | Map layers of one functor to another with a transformation. Compare
hoist, which has a similar effect on the 'monadic' parameter.
> mapsPost id = id
> mapsPost f . mapsPost g = mapsPost (f . g)
> mapsPost f = maps f
@mapsPost@ is essentially the same as 'maps', but it imposes a 'Functor' constraint on
its target functor rather than its source functor. It should be preferred if 'fmap'
is cheaper for the target functor than for the source functor.
-}
mapsPost :: forall m f g r. (Monad m, Functor g)
=> (forall x. f x -> g x)
-> Stream f m r -> Stream g m r
mapsPost phi = loop where
loop :: Stream f m r -> Stream g m r
loop stream = case stream of
Return r -> Return r
Effect m -> Effect (fmap loop m)
Step f -> Step $ fmap loop $ phi f
{-# INLINABLE mapsPost #-}
{- | Map layers of one functor to another with a transformation involving the base monad.
@mapsMPost@ is essentially the same as 'mapsM', but it imposes a 'Functor' constraint on
its target functor rather than its source functor. It should be preferred if 'fmap'
is cheaper for the target functor than for the source functor.
@mapsPost@ is more fundamental than @mapsMPost@, which is best understood as a convenience
for effecting this frequent composition:
> mapsMPost phi = decompose . mapsPost (Compose . phi)
The streaming prelude exports the same function under the better name @mappedPost@,
which overlaps with the lens libraries.
-}
mapsMPost :: forall m f g r. (Monad m, Functor g)
=> (forall x. f x -> m (g x))
-> Stream f m r -> Stream g m r
mapsMPost phi = loop where
loop :: Stream f m r -> Stream g m r
loop stream = case stream of
Return r -> Return r
Effect m -> Effect (fmap loop m)
Step f -> Effect $ fmap (Step . fmap loop) (phi f)
{-# INLINABLE mapsMPost #-}
{-| Rearrange a succession of layers of the form @Compose m (f x)@.
we could as well define @decompose@ by @mapsM@:
> decompose = mapped getCompose
but @mapped@ is best understood as:
> mapped phi = decompose . maps (Compose . phi)
since @maps@ and @hoist@ are the really fundamental operations that preserve the
shape of the stream:
> maps :: (Monad m, Functor f) => (forall x. f x -> g x) -> Stream f m r -> Stream g m r
> hoist :: (Monad m, Functor f) => (forall a. m a -> n a) -> Stream f m r -> Stream f n r
-}
decompose :: (Monad m, Functor f) => Stream (Compose m f) m r -> Stream f m r
decompose = loop where
loop stream = case stream of
Return r -> Return r
Effect m -> Effect (fmap loop m)
Step (Compose mstr) -> Effect $ do
str <- mstr
return (Step (fmap loop str))
{-| Run the effects in a stream that merely layers effects.
-}
run :: Monad m => Stream m m r -> m r
run = loop where
loop stream = case stream of
Return r -> return r
Effect m -> m >>= loop
Step mrest -> mrest >>= loop
{-# INLINABLE run #-}
{-| Map each layer to an effect, and run them all.
-}
mapsM_ :: (Functor f, Monad m) => (forall x . f x -> m x) -> Stream f m r -> m r
mapsM_ f = run . maps f
{-# INLINE mapsM_ #-}
{-| Interpolate a layer at each segment. This specializes to e.g.
> intercalates :: (Monad m, Functor f) => Stream f m () -> Stream (Stream f m) m r -> Stream f m r
-}
intercalates :: (Monad m, Monad (t m), MonadTrans t) =>
t m x -> Stream (t m) m r -> t m r
intercalates sep = go0
where
go0 f = case f of
Return r -> return r
Effect m -> lift m >>= go0
Step fstr -> do
f' <- fstr
go1 f'
go1 f = case f of
Return r -> return r
Effect m -> lift m >>= go1
Step fstr -> do
_ <- sep
f' <- fstr
go1 f'
{-# INLINABLE intercalates #-}
{-| Specialized fold following the usage of @Control.Monad.Trans.Free@
> iterTM alg = streamFold return (join . lift)
> iterTM alg = iterT alg . hoist lift
-}
iterTM ::
(Functor f, Monad m, MonadTrans t,
Monad (t m)) =>
(f (t m a) -> t m a) -> Stream f m a -> t m a
iterTM out stream = destroyExposed stream out (join . lift) return
{-# INLINE iterTM #-}
{-| Specialized fold following the usage of @Control.Monad.Trans.Free@
> iterT alg = streamFold return join alg
> iterT alg = runIdentityT . iterTM (IdentityT . alg . fmap runIdentityT)
-}
iterT ::
(Functor f, Monad m) => (f (m a) -> m a) -> Stream f m a -> m a
iterT out stream = destroyExposed stream out join return
{-# INLINE iterT #-}
{-| Dissolves the segmentation into layers of @Stream f m@ layers.
-}
concats :: (Monad m, Functor f) => Stream (Stream f m) m r -> Stream f m r
concats = loop where
loop stream = case stream of
Return r -> return r
Effect m -> lift m >>= loop
Step fs -> fs >>= loop
{-# INLINE concats #-}
{-| Split a succession of layers after some number, returning a streaming or
effectful pair.
>>> rest <- S.print $ S.splitAt 1 $ each [1..3]
1
>>> S.print rest
2
3
> splitAt 0 = return
> splitAt n >=> splitAt m = splitAt (m+n)
Thus, e.g.
>>> rest <- S.print $ splitsAt 2 >=> splitsAt 2 $ each [1..5]
1
2
3
4
>>> S.print rest
5
-}
splitsAt :: (Monad m, Functor f) => Int -> Stream f m r -> Stream f m (Stream f m r)
splitsAt = loop where
loop !n stream
| n <= 0 = Return stream
| otherwise = case stream of
Return r -> Return (Return r)
Effect m -> Effect (fmap (loop n) m)
Step fs -> case n of
0 -> Return (Step fs)
_ -> Step (fmap (loop (n-1)) fs)
{-# INLINABLE splitsAt #-}
{- Functor-general take.
@takes 3@ can take three individual values
>>> S.print $ takes 3 $ each [1..]
1
2
3
or three sub-streams
>>> S.print $ mapped S.toList $ takes 3 $ chunksOf 2 $ each [1..]
[1,2]
[3,4]
[5,6]
Or, using 'Data.ByteString.Streaming.Char' (here called @Q@),
three byte streams.
>>> Q.stdout $ Q.unlines $ takes 3 $ Q.lines $ Q.chunk "a\nb\nc\nd\ne\nf"
a
b
c
-}
takes :: (Monad m, Functor f) => Int -> Stream f m r -> Stream f m ()
takes n = void . splitsAt n
{-# INLINE takes #-}
{-| Break a stream into substreams each with n functorial layers.
>>> S.print $ mapped S.sum $ chunksOf 2 $ each [1,1,1,1,1]
2
2
1
-}
chunksOf :: (Monad m, Functor f) => Int -> Stream f m r -> Stream (Stream f m) m r
chunksOf n0 = loop where
loop stream = case stream of
Return r -> Return r
Effect m -> Effect (fmap loop m)
Step fs -> Step (Step (fmap (fmap loop . splitsAt (n0-1)) fs))
{-# INLINABLE chunksOf #-}
{- | Make it possible to \'run\' the underlying transformed monad.
-}
distribute :: (Monad m, Functor f, MonadTrans t, MFunctor t, Monad (t (Stream f m)))
=> Stream f (t m) r -> t (Stream f m) r
distribute = loop where
loop stream = case stream of
Return r -> lift (Return r)
Effect tmstr -> hoist lift tmstr >>= loop
Step fstr -> join (lift (Step (fmap (Return . loop) fstr)))
{-# INLINABLE distribute #-}
-- | Repeat a functorial layer (a \"command\" or \"instruction\") forever.
repeats :: (Monad m, Functor f) => f () -> Stream f m r
repeats f = loop where
loop = Effect (return (Step (loop <$ f)))
-- | Repeat an effect containing a functorial layer, command or instruction forever.
repeatsM :: (Monad m, Functor f) => m (f ()) -> Stream f m r
repeatsM mf = loop where
loop = Effect $ do
f <- mf
return $ Step $ loop <$ f
{- | Repeat a functorial layer, command or instruction a fixed number of times.
> replicates n = takes n . repeats
-}
replicates :: (Monad m, Functor f) => Int -> f () -> Stream f m ()
replicates n f = splitsAt n (repeats f) >> return ()
{-| Construct an infinite stream by cycling a finite one
> cycles = forever
>>>
-}
cycles :: (Monad m, Functor f) => Stream f m () -> Stream f m r
cycles = forever
-- | A less-efficient version of 'hoist' that works properly even when its
-- argument is not a monad morphism.
--
-- > hoistUnexposed = hoist . unexposed
hoistUnexposed :: (Monad m, Functor f)
=> (forall a. m a -> n a)
-> Stream f m r -> Stream f n r
hoistUnexposed trans = loop where
loop = Effect . trans . inspectC (return . Return) (return . Step . fmap loop)
{-# INLINABLE hoistUnexposed #-}
-- A version of 'inspect' that takes explicit continuations.
inspectC :: Monad m => (r -> m a) -> (f (Stream f m r) -> m a) -> Stream f m r -> m a
inspectC f g = loop where
loop (Return r) = f r
loop (Step x) = g x
loop (Effect m) = m >>= loop
{-# INLINE inspectC #-}
-- | The same as 'hoist', but explicitly named to indicate that it
-- is not entirely safe. In particular, its argument must be a monad
-- morphism.
hoistExposed :: (Functor m, Functor f) => (forall b. m b -> n b) -> Stream f m a -> Stream f n a
hoistExposed trans = loop where
loop stream = case stream of
Return r -> Return r
Effect m -> Effect (trans (fmap loop m))
Step f -> Step (fmap loop f)
{-# INLINABLE hoistExposed #-}
-- | The same as 'hoistExposed', but with a 'Functor' constraint on
-- the target rather than the source. This must be used only with
-- a monad morphism.
hoistExposedPost :: (Functor n, Functor f) => (forall b. m b -> n b) -> Stream f m a -> Stream f n a
hoistExposedPost trans = loop where
loop stream = case stream of
Return r -> Return r
Effect m -> Effect (fmap loop (trans m))
Step f -> Step (fmap loop f)
{-# INLINABLE hoistExposedPost #-}
{-# DEPRECATED mapsExposed "Use maps instead." #-}
mapsExposed :: (Monad m, Functor f)
=> (forall x . f x -> g x) -> Stream f m r -> Stream g m r
mapsExposed = maps
{-# INLINABLE mapsExposed #-}
{-# DEPRECATED mapsMExposed "Use mapsM instead." #-}
mapsMExposed :: (Monad m, Functor f)
=> (forall x . f x -> m (g x)) -> Stream f m r -> Stream g m r
mapsMExposed = mapsM
{-# INLINABLE mapsMExposed #-}
{-| Map a stream directly to its church encoding; compare @Data.List.foldr@
It permits distinctions that should be hidden, as can be seen from
e.g.
@isPure stream = destroyExposed (const True) (const False) (const True)@
and similar nonsense. The crucial
constraint is that the @m x -> x@ argument is an /Eilenberg-Moore algebra/.
See Atkey, "Reasoning about Stream Processing with Effects"
When in doubt, use 'destroy' instead.
-}
destroyExposed
:: (Functor f, Monad m) =>
Stream f m r -> (f b -> b) -> (m b -> b) -> (r -> b) -> b
destroyExposed stream0 construct theEffect done = loop stream0 where
loop stream = case stream of
Return r -> done r
Effect m -> theEffect (fmap loop m)
Step fs -> construct (fmap loop fs)
{-# INLINABLE destroyExposed #-}
{-| This is akin to the @observe@ of @Pipes.Internal@ . It reeffects the layering
in instances of @Stream f m r@ so that it replicates that of
@FreeT@.
-}
unexposed :: (Functor f, Monad m) => Stream f m r -> Stream f m r
unexposed = Effect . loop where
loop stream = case stream of
Return r -> return (Return r)
Effect m -> m >>= loop
Step f -> return (Step (fmap (Effect . loop) f))
{-# INLINABLE unexposed #-}
{-| Wrap a new layer of a stream. So, e.g.
> S.cons :: Monad m => a -> Stream (Of a) m r -> Stream (Of a) m r
> S.cons a str = wrap (a :> str)
and, recursively:
> S.each :: (Monad m, Foldable t) => t a -> Stream (Of a) m ()
> S.each = foldr (\a b -> wrap (a :> b)) (return ())
The two operations
> wrap :: (Monad m, Functor f ) => f (Stream f m r) -> Stream f m r
> effect :: (Monad m, Functor f ) => m (Stream f m r) -> Stream f m r
are fundamental. We can define the parallel operations @yields@ and @lift@ in
terms of them
> yields :: (Monad m, Functor f ) => f r -> Stream f m r
> yields = wrap . fmap return
> lift :: (Monad m, Functor f ) => m r -> Stream f m r
> lift = effect . fmap return
-}
wrap :: (Monad m, Functor f ) => f (Stream f m r) -> Stream f m r
wrap = Step
{-# INLINE wrap #-}
{- | Wrap an effect that returns a stream
> effect = join . lift
-}
effect :: (Monad m, Functor f ) => m (Stream f m r) -> Stream f m r
effect = Effect
{-# INLINE effect #-}
{-| @yields@ is like @lift@ for items in the streamed functor.
It makes a singleton or one-layer succession.
> lift :: (Monad m, Functor f) => m r -> Stream f m r
> yields :: (Monad m, Functor f) => f r -> Stream f m r
Viewed in another light, it is like a functor-general version of @yield@:
> S.yield a = yields (a :> ())
-}
yields :: (Monad m, Functor f) => f r -> Stream f m r
yields fr = Step (fmap Return fr)
{-# INLINE yields #-}
{-
Note that if the first stream produces Return, we don't inspect
(and potentially run effects from) the second stream. We used to
do that. Aside from being (arguably) a bit strange, this also runs
into a bit of trouble with MonadPlus laws. Most MonadPlus instances
try to satisfy either left distribution or left catch. Let's first
consider left distribution:
(x <|> y) >>= k = (x >>= k) <|> (y >>= k)
[xy_1, xy_2, xy_3, ..., xy_o | r_xy] >>= k
=
[x_1, x_2, x_3, ..., x_m | r_x] >>= k
<|>
[y_1, y_2, y_3, ..., y_n | r_y] >>= k
x and y may have different lengths, and k may produce an utterly
arbitrary stream from each result, so left distribution seems
quite hopeless.
Now let's consider left catch:
zipsWith' liftA2 (return a) b = return a
To satisfy this, we can't run any effects from the second stream
if the first is finished.
-}
-- | Zip two streams together. The 'zipsWith'' function should generally
-- be preferred for efficiency.
zipsWith :: forall f g h m r. (Monad m, Functor h)
=> (forall x y . f x -> g y -> h (x,y))
-> Stream f m r -> Stream g m r -> Stream h m r
zipsWith phi = zipsWith' $ \xyp fx gy -> (\(x,y) -> xyp x y) <$> phi fx gy
{-# INLINABLE zipsWith #-}
-- Somewhat surprisingly, GHC is *much* more willing to specialize
-- zipsWith if it's defined in terms of zipsWith'. Fortunately, zipsWith'
-- seems like a better function anyway, so I guess that's not a big problem.
-- | Zip two streams together.
zipsWith' :: forall f g h m r. Monad m
=> (forall x y p . (x -> y -> p) -> f x -> g y -> h p)
-> Stream f m r -> Stream g m r -> Stream h m r
zipsWith' phi = loop
where
loop :: Stream f m r -> Stream g m r -> Stream h m r
loop s t = case s of
Return r -> Return r
Step fs -> case t of
Return r -> Return r
Step gs -> Step $ phi loop fs gs
Effect n -> Effect $ fmap (loop s) n
Effect m -> Effect $ fmap (flip loop t) m
{-# INLINABLE zipsWith' #-}
zips :: (Monad m, Functor f, Functor g)
=> Stream f m r -> Stream g m r -> Stream (Compose f g) m r
zips = zipsWith' go where
go p fx gy = Compose (fmap (\x -> fmap (\y -> p x y) gy) fx)
{-# INLINE zips #-}
{-| Interleave functor layers, with the effects of the first preceding
the effects of the second. When the first stream runs out, any remaining
effects in the second are ignored.
> interleaves = zipsWith (liftA2 (,))
>>> let paste = \a b -> interleaves (Q.lines a) (maps (Q.cons' '\t') (Q.lines b))
>>> Q.stdout $ Q.unlines $ paste "hello\nworld\n" "goodbye\nworld\n"
hello goodbye
world world
-}
interleaves
:: (Monad m, Applicative h) =>
Stream h m r -> Stream h m r -> Stream h m r
interleaves = zipsWith' liftA2
{-# INLINE interleaves #-}
{-| Swap the order of functors in a sum of functors.
>>> S.toList $ S.print $ separate $ maps S.switch $ maps (S.distinguish (=='a')) $ S.each "banana"
'a'
'a'
'a'
"bnn" :> ()
>>> S.toList $ S.print $ separate $ maps (S.distinguish (=='a')) $ S.each "banana"
'b'
'n'
'n'
"aaa" :> ()
-}
switch :: Sum f g r -> Sum g f r
switch s = case s of InL a -> InR a; InR a -> InL a
{-# INLINE switch #-}
{-| Given a stream on a sum of functors, make it a stream on the left functor,
with the streaming on the other functor as the governing monad. This is
useful for acting on one or the other functor with a fold, leaving the
other material for another treatment. It generalizes
'Data.Either.partitionEithers', but actually streams properly.
>>> let odd_even = S.maps (S.distinguish even) $ S.each [1..10::Int]
>>> :t separate odd_even
separate odd_even
:: Monad m => Stream (Of Int) (Stream (Of Int) m) ()
Now, for example, it is convenient to fold on the left and right values separately:
>>> S.toList $ S.toList $ separate odd_even
[2,4,6,8,10] :> ([1,3,5,7,9] :> ())
Or we can write them to separate files or whatever:
>>> S.writeFile "even.txt" . S.show $ S.writeFile "odd.txt" . S.show $ S.separate odd_even
>>> :! cat even.txt
2
4
6
8
10
>>> :! cat odd.txt
1
3
5
7
9
Of course, in the special case of @Stream (Of a) m r@, we can achieve the above
effects more simply by using 'Streaming.Prelude.copy'
>>> S.toList . S.filter even $ S.toList . S.filter odd $ S.copy $ each [1..10::Int]
[2,4,6,8,10] :> ([1,3,5,7,9] :> ())
But 'separate' and 'unseparate' are functor-general.
-}
separate :: (Monad m, Functor f, Functor g) => Stream (Sum f g) m r -> Stream f (Stream g m) r
separate str = destroyExposed
str
(\x -> case x of InL fss -> wrap fss; InR gss -> effect (yields gss))
(effect . lift)
return
{-# INLINABLE separate #-}
unseparate :: (Monad m, Functor f, Functor g) => Stream f (Stream g m) r -> Stream (Sum f g) m r
unseparate str = destroyExposed
str
(wrap . InL)
(join . maps InR)
return
{-# INLINABLE unseparate #-}
-- | If 'Of' had a @Comonad@ instance, then we'd have
--
-- @copy = expand extend@
--
-- See 'expandPost' for a version that requires a @Functor g@
-- instance instead.
expand :: (Monad m, Functor f)
=> (forall a b. (g a -> b) -> f a -> h b)
-> Stream f m r -> Stream g (Stream h m) r
expand ext = loop where
loop (Return r) = Return r
loop (Step f) = Effect $ Step $ ext (Return . Step) (fmap loop f)
loop (Effect m) = Effect $ Effect $ fmap (Return . loop) m
{-# INLINABLE expand #-}
-- | If 'Of' had a @Comonad@ instance, then we'd have
--
-- @copy = expandPost extend@
--
-- See 'expand' for a version that requires a @Functor f@ instance
-- instead.
expandPost :: (Monad m, Functor g)
=> (forall a b. (g a -> b) -> f a -> h b)
-> Stream f m r -> Stream g (Stream h m) r
expandPost ext = loop where
loop (Return r) = Return r
loop (Step f) = Effect $ Step $ ext (Return . Step . fmap loop) f
loop (Effect m) = Effect $ Effect $ fmap (Return . loop) m
{-# INLINABLE expandPost #-}
unzips :: (Monad m, Functor f, Functor g) =>
Stream (Compose f g) m r -> Stream f (Stream g m) r
unzips str = destroyExposed
str
(\(Compose fgstr) -> Step (fmap (Effect . yields) fgstr))
(Effect . lift)
return
{-# INLINABLE unzips #-}
{-| Group layers in an alternating stream into adjoining sub-streams
of one type or another.
-}
groups :: (Monad m, Functor f, Functor g)
=> Stream (Sum f g) m r
-> Stream (Sum (Stream f m) (Stream g m)) m r
groups = loop
where
loop str = do
e <- lift $ inspect str
case e of
Left r -> return r
Right ostr -> case ostr of
InR gstr -> wrap $ InR (fmap loop (cleanR (wrap (InR gstr))))
InL fstr -> wrap $ InL (fmap loop (cleanL (wrap (InL fstr))))
cleanL :: (Monad m, Functor f, Functor g) =>
Stream (Sum f g) m r -> Stream f m (Stream (Sum f g) m r)
cleanL = go where
go s = do
e <- lift $ inspect s
case e of
Left r -> return (return r)
Right (InL fstr) -> wrap (fmap go fstr)
Right (InR gstr) -> return (wrap (InR gstr))
cleanR :: (Monad m, Functor f, Functor g) =>
Stream (Sum f g) m r -> Stream g m (Stream (Sum f g) m r)
cleanR = go where
go s = do
e <- lift $ inspect s
case e of
Left r -> return (return r)
Right (InL fstr) -> return (wrap (InL fstr))
Right (InR gstr) -> wrap (fmap go gstr)
{-# INLINABLE groups #-}
-- groupInL :: (Monad m, Functor f, Functor g)
-- => Stream (Sum f g) m r
-- -> Stream (Sum (Stream f m) g) m r
-- groupInL = loop
-- where
-- loop str = do
-- e <- lift $ inspect str
-- case e of
-- Left r -> return r
-- Right ostr -> case ostr of
-- InR gstr -> wrap $ InR (fmap loop gstr)
-- InL fstr -> wrap $ InL (fmap loop (cleanL (wrap (InL fstr))))
-- cleanL :: (Monad m, Functor f, Functor g) =>
-- Stream (Sum f g) m r -> Stream f m (Stream (Sum f g) m r)
-- cleanL = loop where
-- loop s = dos
-- e <- lift $ inspect s
-- case e of
-- Left r -> return (return r)
-- Right (InL fstr) -> wrap (fmap loop fstr)
-- Right (InR gstr) -> return (wrap (InR gstr))
{- | 'never' interleaves the pure applicative action with the return of the monad forever.
It is the 'empty' of the 'Alternative' instance, thus
> never <|> a = a
> a <|> never = a
and so on. If w is a monoid then @never :: Stream (Of w) m r@ is
the infinite sequence of 'mempty', and
@str1 \<|\> str2@ appends the elements monoidally until one of streams ends.
Thus we have, e.g.
>>> S.stdoutLn $ S.take 2 $ S.stdinLn <|> S.repeat " " <|> S.stdinLn <|> S.repeat " " <|> S.stdinLn
1<Enter>
2<Enter>
3<Enter>
1 2 3
4<Enter>
5<Enter>
6<Enter>
4 5 6
This is equivalent to
>>> S.stdoutLn $ S.take 2 $ foldr (<|>) never [S.stdinLn, S.repeat " ", S.stdinLn, S.repeat " ", S.stdinLn ]
Where 'f' is a monad, @(\<|\>)@ sequences the conjoined streams stepwise. See the
definition of @paste@ <https://gist.github.com/michaelt/6c6843e6dd8030e95d58 here>,
where the separate steps are bytestreams corresponding to the lines of a file.
Given, say,
> data Branch r = Branch r r deriving Functor -- add obvious applicative instance
then @never :: Stream Branch Identity r@ is the pure infinite binary tree with
(inaccessible) @r@s in its leaves. Given two binary trees, @tree1 \<|\> tree2@
intersects them, preserving the leaves that came first,
so @tree1 \<|\> never = tree1@
@Stream Identity m r@ is an action in @m@ that is indefinitely delayed. Such an
action can be constructed with e.g. 'untilJust'.
> untilJust :: (Monad m, Applicative f) => m (Maybe r) -> Stream f m r
Given two such items, @\<|\>@ instance races them.
It is thus the iterative monad transformer specially defined in
<https://hackage.haskell.org/package/free-4.12.1/docs/Control-Monad-Trans-Iter.html Control.Monad.Trans.Iter>
So, for example, we might write
>>> let justFour str = if length str == 4 then Just str else Nothing
>>> let four = untilJust (fmap justFour getLine)
>>> run four
one<Enter>
two<Enter>
three<Enter>
four<Enter>
"four"
The 'Alternative' instance in
<https://hackage.haskell.org/package/free-4.12.1/docs/Control-Monad-Trans-Free.html Control.Monad.Trans.Free>
is avowedly wrong, though no explanation is given for this.
-}
never :: (Monad m, Applicative f) => Stream f m r
-- The Monad m constraint should really be an Applicative one,
-- but we still support old versions of base.
never = let loop = Step $ pure (Effect (return loop)) in loop
{-# INLINABLE never #-}
delays :: (MonadIO m, Applicative f) => Double -> Stream f m r
delays seconds = loop where
loop = Effect $ liftIO (threadDelay delay) >> return (Step (pure loop))
delay = fromInteger (truncate (1000000 * seconds))
{-# INLINABLE delays #-}
-- {-| Permit streamed actions to proceed unless the clock has run out.
--
-- -}
-- period :: (MonadIO m, Functor f) => Double -> Stream f m r -> Stream f m (Stream f m r)
-- period seconds str = do
-- utc <- liftIO getCurrentTime
-- let loop s = do
-- utc' <- liftIO getCurrentTime
-- if diffUTCTime utc' utc > (cutoff / 1000000000)
-- then return s
-- else case s of
-- Return r -> Return (Return r)
-- Effect m -> Effect (fmap loop m)
-- Step f -> Step (fmap loop f)
-- loop str
-- where
-- cutoff = fromInteger (truncate (1000000000 * seconds))
-- {-# INLINABLE period #-}
--
--
-- {-| Divide a succession of phases according to a specified time interval. If time runs out
-- while an action is proceeding, it is allowed to run to completion. The clock is only then
-- restarted.
-- -}
-- periods :: (MonadIO m, Functor f) => Double -> Stream f m r -> Stream (Stream f m) m r
-- periods seconds s = do
-- utc <- liftIO getCurrentTime
-- loop (addUTCTime cutoff utc) s
--
-- where
-- cutoff = fromInteger (truncate (1000000000 * seconds)) / 1000000000
-- loop final stream = do
-- utc <- liftIO getCurrentTime
-- if utc > final
-- then loop (addUTCTime cutoff utc) stream
-- else case stream of
-- Return r -> Return r
-- Effect m -> Effect $ fmap (loop final) m
-- Step fstr -> Step $ fmap (periods seconds) (cutoff_ final (Step fstr))
--
-- -- do
-- -- let sloop s = do
-- -- utc' <- liftIO getCurrentTime
-- -- if final < utc'
-- -- then return s
-- -- else case s of
-- -- Return r -> Return (Return r)
-- -- Effect m -> Effect (fmap sloop m)
-- -- Step f -> Step (fmap sloop f)
-- -- Step (Step (fmap (fmap (periods seconds) . sloop) fstr))
-- -- str <- m
-- -- utc' <- liftIO getCurrentTime
-- -- if diffUTCTime utc' utc > (cutoff / 1000000000)
-- -- then return (loop utc' str)
-- -- else return (loop utc str)
-- -- Step fs -> do
-- -- let check str = do
-- -- utc' <- liftIO getCurrentTime
-- -- loop utc' str
-- --
-- {-# INLINABLE periods #-}
--
-- cutoff_ final str = do
-- let loop s = do
-- utc' <- liftIO getCurrentTime
-- if utc' > final
-- then Return s
-- else case s of
-- Return r -> Return (Return r)
-- Effect m -> Effect (fmap loop m)
-- Step f -> Step (fmap loop f)
-- loop str
{- | Repeat a
-}
untilJust :: (Monad m, Applicative f) => m (Maybe r) -> Stream f m r
untilJust act = loop where
loop = Effect $ do
m <- act
return $ case m of
Nothing -> Step $ pure loop
Just a -> Return a
cutoff :: (Monad m, Functor f) => Int -> Stream f m r -> Stream f m (Maybe r)
cutoff = loop where
loop 0 _ = return Nothing
loop n str = do
e <- lift $ inspect str
case e of
Left r -> return (Just r)
Right frest -> Step $ fmap (loop (n-1)) frest
|
haskell-streaming/streaming
|
src/Streaming/Internal.hs
|
bsd-3-clause
| 42,987 | 0 | 24 | 11,370 | 9,388 | 4,834 | 4,554 | -1 | -1 |
-- Copyright (c) 1998-1999 Chris Okasaki.
-- See COPYRIGHT file for terms and conditions.
module RevSeq (
-- generic adaptor for sequences to keep them in the opposite order
Rev, -- Rev s instance of Sequence, Functor, Monad, MonadPlus
-- sequence operations
empty,single,cons,snoc,append,lview,lhead,ltail,rview,rhead,rtail,
null,size,concat,reverse,reverseOnto,fromList,toList,
map,concatMap,foldr,foldl,foldr1,foldl1,reducer,reducel,reduce1,
copy,tabulate,inBounds,lookup,lookupM,lookupWithDefault,update,adjust,
mapWithIndex,foldrWithIndex,foldlWithIndex,
take,drop,splitAt,subseq,filter,partition,takeWhile,dropWhile,splitWhile,
zip,zip3,zipWith,zipWith3,unzip,unzip3,unzipWith,unzipWith3,
-- documentation
moduleName,instanceName,
-- re-export view type from EdisonPrelude for convenience
Maybe2(Just2,Nothing2)
) where
import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1,
filter,takeWhile,dropWhile,lookup,take,drop,splitAt,
zip,zip3,zipWith,zipWith3,unzip,unzip3,null)
import EdisonPrelude(Maybe2(Just2,Nothing2))
import qualified Sequence as S ( Sequence(..) )
import qualified ListSeq as L
import SequenceDefaults -- only used by concatMap
import Monad
-- This module defines a sequence adaptor Rev s.
-- If s is a sequence type constructor, then Rev s
-- is a sequence type constructor that is identical to s,
-- except that it is kept in the opposite order.
-- Also keeps explicit track of the size of the sequence,
-- similar to the Sized adaptor in SizedSeq.hs.
--
-- This module is most useful when s is a sequence type
-- that offers fast access to the front but slow access
-- to the rear, and your application needs the opposite
-- (i.e., fast access to the rear but slow access to the
-- front).
-- signatures for exported functions
moduleName :: String
instanceName :: S.Sequence s => Rev s a -> String
empty :: S.Sequence s => Rev s a
single :: S.Sequence s => a -> Rev s a
cons :: S.Sequence s => a -> Rev s a -> Rev s a
snoc :: S.Sequence s => Rev s a -> a -> Rev s a
append :: S.Sequence s => Rev s a -> Rev s a -> Rev s a
lview :: S.Sequence s => Rev s a -> Maybe2 a (Rev s a)
lhead :: S.Sequence s => Rev s a -> a
ltail :: S.Sequence s => Rev s a -> Rev s a
rview :: S.Sequence s => Rev s a -> Maybe2 (Rev s a) a
rhead :: S.Sequence s => Rev s a -> a
rtail :: S.Sequence s => Rev s a -> Rev s a
null :: S.Sequence s => Rev s a -> Bool
size :: S.Sequence s => Rev s a -> Int
concat :: S.Sequence s => Rev s (Rev s a) -> Rev s a
reverse :: S.Sequence s => Rev s a -> Rev s a
reverseOnto :: S.Sequence s => Rev s a -> Rev s a -> Rev s a
fromList :: S.Sequence s => [a] -> Rev s a
toList :: S.Sequence s => Rev s a -> [a]
map :: S.Sequence s => (a -> b) -> Rev s a -> Rev s b
concatMap :: S.Sequence s => (a -> Rev s b) -> Rev s a -> Rev s b
foldr :: S.Sequence s => (a -> b -> b) -> b -> Rev s a -> b
foldl :: S.Sequence s => (b -> a -> b) -> b -> Rev s a -> b
foldr1 :: S.Sequence s => (a -> a -> a) -> Rev s a -> a
foldl1 :: S.Sequence s => (a -> a -> a) -> Rev s a -> a
reducer :: S.Sequence s => (a -> a -> a) -> a -> Rev s a -> a
reducel :: S.Sequence s => (a -> a -> a) -> a -> Rev s a -> a
reduce1 :: S.Sequence s => (a -> a -> a) -> Rev s a -> a
copy :: S.Sequence s => Int -> a -> Rev s a
tabulate :: S.Sequence s => Int -> (Int -> a) -> Rev s a
inBounds :: S.Sequence s => Rev s a -> Int -> Bool
lookup :: S.Sequence s => Rev s a -> Int -> a
lookupM :: S.Sequence s => Rev s a -> Int -> Maybe a
lookupWithDefault :: S.Sequence s => a -> Rev s a -> Int -> a
update :: S.Sequence s => Int -> a -> Rev s a -> Rev s a
adjust :: S.Sequence s => (a -> a) -> Int -> Rev s a -> Rev s a
mapWithIndex :: S.Sequence s => (Int -> a -> b) -> Rev s a -> Rev s b
foldrWithIndex :: S.Sequence s => (Int -> a -> b -> b) -> b -> Rev s a -> b
foldlWithIndex :: S.Sequence s => (b -> Int -> a -> b) -> b -> Rev s a -> b
take :: S.Sequence s => Int -> Rev s a -> Rev s a
drop :: S.Sequence s => Int -> Rev s a -> Rev s a
splitAt :: S.Sequence s => Int -> Rev s a -> (Rev s a, Rev s a)
subseq :: S.Sequence s => Int -> Int -> Rev s a -> Rev s a
filter :: S.Sequence s => (a -> Bool) -> Rev s a -> Rev s a
partition :: S.Sequence s => (a -> Bool) -> Rev s a -> (Rev s a, Rev s a)
takeWhile :: S.Sequence s => (a -> Bool) -> Rev s a -> Rev s a
dropWhile :: S.Sequence s => (a -> Bool) -> Rev s a -> Rev s a
splitWhile :: S.Sequence s => (a -> Bool) -> Rev s a -> (Rev s a, Rev s a)
zip :: S.Sequence s => Rev s a -> Rev s b -> Rev s (a,b)
zip3 :: S.Sequence s => Rev s a -> Rev s b -> Rev s c -> Rev s (a,b,c)
zipWith :: S.Sequence s => (a -> b -> c) -> Rev s a -> Rev s b -> Rev s c
zipWith3 :: S.Sequence s => (a -> b -> c -> d) -> Rev s a -> Rev s b -> Rev s c -> Rev s d
unzip :: S.Sequence s => Rev s (a,b) -> (Rev s a, Rev s b)
unzip3 :: S.Sequence s => Rev s (a,b,c) -> (Rev s a, Rev s b, Rev s c)
unzipWith :: S.Sequence s => (a -> b) -> (a -> c) -> Rev s a -> (Rev s b, Rev s c)
unzipWith3 :: S.Sequence s => (a -> b) -> (a -> c) -> (a -> d) -> Rev s a -> (Rev s b, Rev s c, Rev s d)
moduleName = "RevSeq"
instanceName (N m s) = "RevSeq(" ++ S.instanceName s ++ ")"
data Rev s a = N !Int (s a)
-- The Int is the size minus one. The "minus one" makes indexing
-- calculations easier.
fromSeq xs = N (S.size xs - 1) xs
toSeq (N m xs) = xs
empty = N (-1) S.empty
single x = N 0 (S.single x)
cons x (N m xs) = N (m+1) (S.snoc xs x)
snoc (N m xs) x = N (m+1) (S.cons x xs)
append (N m xs) (N n ys) = N (m+n+1) (S.append ys xs)
lview (N m xs) = case S.rview xs of
Nothing2 -> Nothing2
Just2 xs x -> Just2 x (N (m-1) xs)
lhead (N m xs) = S.rhead xs
ltail (N (-1) xs) = error "RevSeq.ltail: empty sequence"
ltail (N m xs) = N (m-1) (S.rtail xs)
rview (N m xs) = case S.lview xs of
Nothing2 -> Nothing2
Just2 x xs -> Just2 (N (m-1) xs) x
rhead (N m xs) = S.lhead xs
rtail (N (-1) xs) = error "RevSeq.rtail: empty sequence"
rtail (N m xs) = N (m-1) (S.ltail xs)
null (N m xs) = m == -1
size (N m xs) = m+1
concat (N m xss) = fromSeq (S.concat (S.map toSeq xss))
reverse (N m xs) = N m (S.reverse xs)
reverseOnto (N m xs) (N n ys) = N (m+n+1) (S.append ys (S.reverse xs))
fromList = fromSeq . S.fromList . L.reverse
toList (N m xs) = S.foldl (flip (:)) [] xs
map f (N m xs) = N m (S.map f xs)
concatMap = concatMapUsingFoldr -- only function that uses a default
foldr f e (N m xs) = S.foldl (flip f) e xs
foldl f e (N m xs) = S.foldr (flip f) e xs
foldr1 f (N m xs) = S.foldl1 (flip f) xs
foldl1 f (N m xs) = S.foldr1 (flip f) xs
reducer f e (N m xs) = S.reducel (flip f) e xs
reducel f e (N m xs) = S.reducer (flip f) e xs
reduce1 f (N m xs) = S.reduce1 (flip f) xs
copy n x
| n <= 0 = empty
| otherwise = N (n-1) (S.copy n x)
tabulate n f
| n <= 0 = empty
| otherwise = N m (S.tabulate n (f . (m -)))
where m = n-1
inBounds (N m xs) i = (i >= 0) && (i <= m)
lookup (N m xs) i = S.lookup xs (m-i)
lookupM (N m xs) i = S.lookupM xs (m-i)
lookupWithDefault d (N m xs) i = S.lookupWithDefault d xs (m-i)
update i x (N m xs) = N m (S.update (m-i) x xs)
adjust f i (N m xs) = N m (S.adjust f (m-i) xs)
mapWithIndex f (N m xs) = N m (S.mapWithIndex (f . (m-)) xs)
foldrWithIndex f e (N m xs) = S.foldlWithIndex f' e xs
where f' xs i x = f (m-i) x xs
foldlWithIndex f e (N m xs) = S.foldrWithIndex f' e xs
where f' i x xs = f xs (m-i) x
take i original@(N m xs)
| i <= 0 = empty
| i > m = original
| otherwise = N (i-1) (S.drop (m-i+1) xs)
drop i original@(N m xs)
| i <= 0 = original
| i > m = empty
| otherwise = N (m-i) (S.take (m-i+1) xs)
splitAt i original@(N m xs)
| i <= 0 = (empty, original)
| i > m = (original, empty)
| otherwise = let (ys,zs) = S.splitAt (m-i+1) xs
in (N (i-1) zs, N (m-i) ys)
subseq i len original@(N m xs)
| i <= 0 = take len original
| i > m = empty
| i+len > m = N (m-i) (S.take (m-i+1) xs)
| otherwise = N (len-1) (S.subseq (m-i-len+1) len xs)
filter p = fromSeq . S.filter p . toSeq
partition p (N m xs) = (N (k-1) ys, N (m-k) zs)
where (ys,zs) = S.partition p xs
k = S.size ys
takeWhile p = fromSeq . S.reverse . S.takeWhile p . S.reverse . toSeq
dropWhile p = fromSeq . S.reverse . S.dropWhile p . S.reverse . toSeq
splitWhile p (N m xs) = (N (k-1) (S.reverse ys), N (m-k) (S.reverse zs))
where (ys,zs) = S.splitWhile p (S.reverse xs)
k = S.size ys
zip (N m xs) (N n ys)
| m < n = N m (S.zip xs (S.drop (n-m) ys))
| m > n = N n (S.zip (S.drop (m-n) xs) ys)
| otherwise = N m (S.zip xs ys)
zip3 (N l xs) (N m ys) (N n zs) = N k (S.zip3 xs' ys' zs')
where k = min l (min m n)
xs' = if l == k then xs else S.drop (l-k) xs
ys' = if m == k then ys else S.drop (m-k) ys
zs' = if n == k then zs else S.drop (n-k) zs
zipWith f (N m xs) (N n ys)
| m < n = N m (S.zipWith f xs (S.drop (n-m) ys))
| m > n = N n (S.zipWith f (S.drop (m-n) xs) ys)
| otherwise = N m (S.zipWith f xs ys)
zipWith3 f (N l xs) (N m ys) (N n zs) = N k (S.zipWith3 f xs' ys' zs')
where k = min l (min m n)
xs' = if l == k then xs else S.drop (l-k) xs
ys' = if m == k then ys else S.drop (m-k) ys
zs' = if n == k then zs else S.drop (n-k) zs
unzip (N m xys) = (N m xs, N m ys)
where (xs,ys) = S.unzip xys
unzip3 (N m xyzs) = (N m xs, N m ys, N m zs)
where (xs,ys,zs) = S.unzip3 xyzs
unzipWith f g (N m xys) = (N m xs, N m ys)
where (xs,ys) = S.unzipWith f g xys
unzipWith3 f g h (N m xyzs) = (N m xs, N m ys, N m zs)
where (xs,ys,zs) = S.unzipWith3 f g h xyzs
-- instances
instance S.Sequence s => S.Sequence (Rev s) where
{empty = empty; single = single; cons = cons; snoc = snoc;
append = append; lview = lview; lhead = lhead; ltail = ltail;
rview = rview; rhead = rhead; rtail = rtail; null = null;
size = size; concat = concat; reverse = reverse;
reverseOnto = reverseOnto; fromList = fromList; toList = toList;
map = map; concatMap = concatMap; foldr = foldr; foldl = foldl;
foldr1 = foldr1; foldl1 = foldl1; reducer = reducer;
reducel = reducel; reduce1 = reduce1; copy = copy;
tabulate = tabulate; inBounds = inBounds; lookup = lookup;
lookupM = lookupM; lookupWithDefault = lookupWithDefault;
update = update; adjust = adjust; mapWithIndex = mapWithIndex;
foldrWithIndex = foldrWithIndex; foldlWithIndex = foldlWithIndex;
take = take; drop = drop; splitAt = splitAt; subseq = subseq;
filter = filter; partition = partition; takeWhile = takeWhile;
dropWhile = dropWhile; splitWhile = splitWhile; zip = zip;
zip3 = zip3; zipWith = zipWith; zipWith3 = zipWith3; unzip = unzip;
unzip3 = unzip3; unzipWith = unzipWith; unzipWith3 = unzipWith3;
instanceName = instanceName}
instance S.Sequence s => Functor (Rev s) where
fmap = map
instance S.Sequence s => Monad (Rev s) where
return = single
xs >>= k = concatMap k xs
instance S.Sequence s => MonadPlus (Rev s) where
mplus = append
mzero = empty
-- want to say
-- instance Eq (s a) => Eq (Rev s a) where
-- (N m xs) == (N n ys) = (m == n) && (xs == ys)
-- but can't because can't write Eq (s a) context
instance (S.Sequence s, Eq a) => Eq (Rev s a) where
(N m xs) == (N n ys) = (m == n) && (S.toList xs == S.toList ys)
instance (S.Sequence s, Show a) => Show (Rev s a) where
show xs = show (toList xs)
|
OS2World/DEV-UTIL-HUGS
|
oldlib/RevSeq.hs
|
bsd-3-clause
| 11,860 | 0 | 13 | 3,275 | 6,178 | 3,186 | 2,992 | 220 | 4 |
module C where
import Haskore.Melody
import Haskore.Basic.Duration
import Snippet
main = render_to "c.midi" $ c 1 wn ()
|
nfjinjing/haskore-guide
|
src/c.hs
|
bsd-3-clause
| 121 | 0 | 7 | 19 | 39 | 22 | 17 | 5 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
module OpenBLAS1 where
import qualified Language.C.Inline as C
import qualified Data.Vector.Storable as VS
import Foreign.C.Types
import Data.Monoid ((<>))
C.context (C.baseCtx <> C.vecCtx)
C.include "<math.h>"
C.include "<string.h>"
C.include "atest.h"
C.include "cblas.h"
readAndSumW :: Int -> IO (Int)
readAndSumW n = do
let n' = fromIntegral n
x <- [C.exp| int { readAndSum( $(int n') ) } |]
return $ fromIntegral x
cblas_copyW :: CInt -> VS.Vector CDouble -> CInt -> VS.Vector CDouble -> CInt -> IO ()
cblas_copyW n dx incx dy incy = do
[C.block| void
{
cblas_dcopy(
$(const int n),
$vec-ptr:(const double* dx),
$(const int incx),
$vec-ptr:(double* dy),
$(const int incy)
);
}
|]
cblas_axpyW :: CInt -> CDouble -> VS.Vector CDouble -> CInt -> VS.Vector CDouble -> CInt -> IO ()
cblas_axpyW n da dx incx dy incy = do
[C.block| void
{
cblas_daxpy(
$(const int n),
$(const double da),
$vec-ptr:(const double* dx),
$(const int incx),
$vec-ptr:(double* dy),
$(const int incy)
);
}
|]
cblas_scalW :: CInt -> CDouble -> VS.Vector CDouble -> CInt -> IO ()
cblas_scalW n da dx incx = do
[C.block| void
{
cblas_dscal(
$(const int n),
$(const double da),
$vec-ptr:(double* dx),
$(const int incx)
);
}
|]
cblas_swapW :: CInt -> VS.Vector CDouble -> CInt -> VS.Vector CDouble -> CInt -> IO ()
cblas_swapW n dx incx dy incy = do
[C.block| void
{
cblas_dswap(
$(const int n),
$vec-ptr:(double* dx),
$(const int incx),
$vec-ptr:(double* dy),
$(const int incy)
);
}
|]
-- --
cblas_dotW :: CInt -> VS.Vector CDouble -> CInt -> VS.Vector CDouble -> CInt -> IO (CDouble)
cblas_dotW n dx incx dy incy = do
[C.block| double
{
return cblas_ddot(
$(const int n),
$vec-ptr:(const double* dx),
$(const int incx),
$vec-ptr:(const double* dy),
$(const int incy)
);
}
|]
cblas_nrm2W :: CInt -> VS.Vector CDouble -> CInt -> IO (CDouble)
cblas_nrm2W n dx incx = do
[C.block| double
{
return cblas_dnrm2(
$(const int n),
$vec-ptr:(const double* dx),
$(const int incx)
);
}
|]
cblas_asumW :: CInt -> VS.Vector CDouble -> CInt -> IO (CDouble)
cblas_asumW n dx incx = do
[C.block| double
{
return cblas_dasum(
$(const int n),
$vec-ptr:(const double* dx),
$(const int incx)
);
}
|]
cblas_iamaxW :: CInt -> VS.Vector CDouble -> CInt -> IO (CInt)
cblas_iamaxW n dx incx = do
[C.block| int
{
return cblas_idamax(
$(const int n),
$vec-ptr:(const double* dx),
$(const int incx)
);
}
|]
cblas_rotgW :: VS.Vector CDouble -> IO ()
cblas_rotgW dx = do
[C.block| void
{
double* v = $vec-ptr:(double* dx);
cblas_drotg(&v[0], &v[1], &v[2], &v[3]);
}
|]
|
wyn/blash
|
tests/OpenBLAS1.hs
|
bsd-3-clause
| 3,195 | 0 | 12 | 1,019 | 657 | 344 | 313 | 45 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE TemplateHaskell #-}
module Config where
import Fluid.Type
import Data.Label
import Control.Monad
import Prelude as P
import Data.Array.Accelerate as A
import Data.Array.Accelerate.IO as A
import Data.Array.Accelerate.LLVM.PTX
import System.Console.GetOpt
import System.Environment (getArgs, getProgName)
import System.Exit
import System.IO
data Initial a
= FromFile FilePath
| FromFunction (Int -> Int -> a)
data Source = Camera | Mouse | Leap
deriving (Show,Read)
data SimType = Fluid | GradientLuminance | Gradient | Simple
deriving (Show,Read)
data Coloration = Colorful | Halloween | BlackWhite
deriving (Show,Read)
data Config = Config
{ _windowHeight :: !Int
, _windowWidth :: !Int
, _simType :: !SimType
, _coloration :: !Coloration
, _viscosity :: !Float
, _diffusion :: !Float
, _timestep :: !Float
-- , _inputDensity :: !Float
-- , _inputVelocity :: !Float
, _simulationSteps :: !Int
-- , _displayScale :: !Int
-- , _displayFramerate :: !Int
, _initialDensity :: DensityField
, _initialVelocity :: VelocityField
, _initialPicture :: Pic
, _inputSource :: !Source
, _setupDensity :: Initial DensityField
, _setupVelocity :: Initial VelocityField
}
$(mkLabels [''Config])
defaults :: Config
defaults = Config
{ _viscosity = 0
, _diffusion = 0
, _timestep = 0.1
, _simType = Fluid
-- , _inputDensity = 50
-- , _inputVelocity = 20
, _coloration = Colorful
, _simulationSteps = 40
, _windowWidth = 100
, _windowHeight = 100
, _initialDensity = error "initial density??"
, _initialVelocity = error "initial velocity??"
, _initialPicture = error "initial picture??"
, _inputSource = Camera
, _setupDensity = FromFunction makeField_empty
, _setupVelocity = FromFunction makeField_empty
}
getUsage :: IO String
getUsage =
do
prg <- getProgName
return $ usageInfo prg options
options :: [OptDescr (Config -> IO Config)]
options =
[ Option [] ["height"]
(ReqArg (\arg opt -> return $ parse windowHeight arg opt) "INT")
(describe windowHeight "pixel height")
, Option [] ["width"]
(ReqArg (\arg opt -> return $ parse windowWidth arg opt) "INT")
(describe windowWidth "pixel width")
, Option [] ["simtype"]
(ReqArg (\arg opt -> return $ parse simType arg opt) "Fluid|GradientLuminance|Gradient|Simple")
(describe simType "which type of sim to run")
, Option [] ["source"]
(ReqArg (\arg opt -> return $ parse inputSource arg opt) "Camera|Mouse")
(describe inputSource "input source to fluid only")
, Option [] ["coloration"]
(ReqArg (\arg opt -> return $ parse coloration arg opt) "Colorful|Halloween|BlackWhite")
(describe coloration "coloration method for fluid only")
, Option [] ["viscosity"]
(ReqArg (\arg opt -> return $ parse viscosity arg opt) "FLOAT")
(describe viscosity "viscosity for velocity damping")
, Option [] ["diffusion"]
(ReqArg (\arg opt -> return $ parse diffusion arg opt) "FLOAT")
(describe diffusion "diffusion rate for mass dispersion")
, Option [] ["delta"]
(ReqArg (\arg opt -> return $ parse timestep arg opt) "FLOAT")
(describe timestep "simulation time between each frame")
{-
, Option [] ["density"]
(ReqArg (parse inputDensity) "FLOAT")
(describe inputDensity "magnitude of user input density")
, Option [] ["velocity"]
(ReqArg (parse inputVelocity) "FLOAT")
(describe inputVelocity "magnitude of user input velocity")
-}
, Option [] ["init-checks"]
(NoArg (return . init_checks))
"initial density field with zero velocity field"
, Option [] ["init-man"]
(NoArg (return . init_man))
"initial density field with swirling velocity"
, Option [] ["init-elk"]
(NoArg (return . init_elk))
"initial density field with swirling velocity"
, Option "h" ["help"]
(NoArg
(\_ -> do
usage <- getUsage
hPutStrLn stderr usage
exitWith ExitSuccess))
"Show help"
]
where
parse f x = set f (read x)
describe f msg = msg P.++ " (" P.++ show (get f defaults) P.++ ")"
init_checks = set setupDensity (FromFunction makeDensity_checks)
. set setupVelocity (FromFunction makeField_empty)
init_man = set setupDensity (FromFunction makeDensity_checks)
. set setupVelocity (FromFunction makeVelocity_man)
init_elk = set setupDensity (FromFunction makeDensity_checks)
. set setupVelocity (FromFunction makeVelocity_elk)
parseArgs :: IO Config
parseArgs =
do
args <- getArgs
let (actions,_,_) = getOpt RequireOrder options args
opts <- foldl (>>=) (return defaults) actions
initialiseConfig opts
initialiseConfig :: Config -> IO Config
initialiseConfig conf = do
let
width = get windowWidth conf
height = get windowHeight conf
dens <- case get setupDensity conf of
-- FromFile fn -> loadDensity_bmp fn width height
FromFunction f -> return (f width height)
velo <- case get setupVelocity conf of
-- FromFile fn -> loadVelocity_bmp fn width height
FromFunction f -> return (f width height)
let
pic = A.fromList (Z :. height :. width) $ repeat (0,0,0)
conf' = set initialDensity dens
. set initialVelocity velo
. set initialPicture pic
$ conf
return conf'
makeField_empty :: FieldElt e => Int -> Int -> Field e
makeField_empty width height
= run $ A.fill (constant (Z:.height:.width)) (constant zero)
makeDensity_checks :: Int -> Int -> DensityField
makeDensity_checks width height
= let width' = constant $ P.fromIntegral width
height' = constant $ P.fromIntegral height
yc = constant $ P.fromIntegral (height `div` 2)
xc = constant $ P.fromIntegral (width `div` 2)
checks ix
= let Z :. y :. x = unlift ix
x' = A.fromIntegral x
y' = A.fromIntegral y
tx = 10 * (x' - xc) / width'
ty = 10 * (y' - yc) / height'
xk1 = abs tx A.> 3*pi/2 ? (0 , cos tx)
yk1 = abs ty A.> 3*pi/2 ? (0 , cos ty)
d1 = xk1 * yk1
in
0 `A.max` d1
in
run $ A.generate (constant (Z:.height:.width)) checks
makeVelocity_man :: Int -> Int -> VelocityField
makeVelocity_man width height
= let width' = constant $ P.fromIntegral width
height' = constant $ P.fromIntegral height
yc = constant $ P.fromIntegral (height `div` 2)
xc = constant $ P.fromIntegral (width `div` 2)
man ix
= let Z :. y :. x = unlift ix
x' = A.fromIntegral x
y' = A.fromIntegral y
xk2 = cos (19 * (x' - xc) / width')
yk2 = cos (17 * (y' - yc) / height')
d2 = xk2 * yk2 / 5
in
lift (constant 0, d2)
in
run $ A.generate (constant (Z:.height:.width)) man
makeVelocity_elk :: Int -> Int -> VelocityField
makeVelocity_elk width height
= let width' = constant $ P.fromIntegral width
height' = constant $ P.fromIntegral height
yc = constant $ P.fromIntegral (height `div` 2)
xc = constant $ P.fromIntegral (width `div` 2)
elk ix
= let Z :. y :. x = unlift ix
x' = A.fromIntegral x
y' = A.fromIntegral y
tx = 12 * (x' - xc) / width'
ty = 12 * (y' - yc) / height'
xk2 = cos tx
yk2 = -cos ty
d2 = xk2 * yk2 / 5
in
lift (constant 0, d2)
in
run $ A.generate (constant (Z:.height:.width)) elk
|
cpdurham/accelerate-camera-sandbox
|
app/camera-sandbox/Config.hs
|
bsd-3-clause
| 8,586 | 1 | 18 | 2,955 | 2,379 | 1,251 | 1,128 | 204 | 1 |
{-- snippet assign --}
x = 10
x = 11
{-- /snippet assign --}
|
binesiyu/ifl
|
examples/ch02/Assign.hs
|
mit
| 61 | 0 | 4 | 14 | 13 | 8 | 5 | 2 | 1 |
module Golden.WalletError
( tests
) where
import Universum
import Hedgehog (Property)
import Cardano.Wallet.API.Response (JSONValidationError (..),
UnsupportedMimeTypeError (..))
import Cardano.Wallet.API.V1.Swagger.Example (genExample)
import Cardano.Wallet.API.V1.Types (ErrNotEnoughMoney (..), V1 (..),
WalletError (..), exampleWalletId)
import Test.Pos.Core.ExampleHelpers (exampleAddress)
import Test.Pos.Util.Golden (discoverGolden, goldenTestJSON)
import qualified Hedgehog as H
-----------------------------------------------------------------------
-- Main test export
-----------------------------------------------------------------------
tests :: IO Bool
tests =
H.checkSequential $$discoverGolden
-------------------------------------------------------------------------------
-- WalletError
-------------------------------------------------------------------------------
golden_WalletError_NotEnoughMoneyAvailableBalanceIsInsufficient :: Property
golden_WalletError_NotEnoughMoneyAvailableBalanceIsInsufficient =
goldenTestJSON
(NotEnoughMoney (ErrAvailableBalanceIsInsufficient 14))
"test/unit/Golden/golden/WalletError_NotEnoughMoneyAvailableBalanceIsInsufficient"
golden_WalletError_NotEnoughMoneyCannotCoverFee :: Property
golden_WalletError_NotEnoughMoneyCannotCoverFee =
goldenTestJSON
(NotEnoughMoney ErrCannotCoverFee)
"test/unit/Golden/golden/WalletError_NotEnoughMoneyCannotCoverFee"
golden_WalletError_OutputIsRedeem :: Property
golden_WalletError_OutputIsRedeem =
goldenTestJSON
(OutputIsRedeem $ V1 exampleAddress)
"test/unit/Golden/golden/WalletError_OutputIsRedeem"
golden_WalletError_UnknownError :: Property
golden_WalletError_UnknownError =
goldenTestJSON
(UnknownError "test")
"test/unit/Golden/golden/WalletError_UnknownError"
golden_WalletError_InvalidAddressFormat :: Property
golden_WalletError_InvalidAddressFormat =
goldenTestJSON
(InvalidAddressFormat "test")
"test/unit/Golden/golden/WalletError_InvalidAddressFormat"
golden_WalletError_WalletNotFound :: Property
golden_WalletError_WalletNotFound =
goldenTestJSON
WalletNotFound
"test/unit/Golden/golden/WalletError_WalletNotFound"
golden_WalletError_WalletAlreadyExists :: Property
golden_WalletError_WalletAlreadyExists =
goldenTestJSON
(WalletAlreadyExists exampleWalletId)
"test/unit/Golden/golden/WalletError_WalletAlreadyExists"
golden_WalletError_AddressNotFound :: Property
golden_WalletError_AddressNotFound =
goldenTestJSON
AddressNotFound
"test/unit/Golden/golden/WalletError_AddressNotFound"
golden_WalletError_InvalidPublicKey :: Property
golden_WalletError_InvalidPublicKey =
goldenTestJSON
(InvalidPublicKey "test")
"test/unit/Golden/golden/WalletError_InvalidPublicKey"
golden_WalletError_UnsignedTxCreationError :: Property
golden_WalletError_UnsignedTxCreationError =
goldenTestJSON
UnsignedTxCreationError
"test/unit/Golden/golden/WalletError_UnsignedTxCreationError"
golden_WalletError_SignedTxSubmitError :: Property
golden_WalletError_SignedTxSubmitError =
goldenTestJSON
(SignedTxSubmitError "test")
"test/unit/Golden/golden/WalletError_SignedTxSubmitError"
golden_WalletError_TooBigTransaction :: Property
golden_WalletError_TooBigTransaction =
goldenTestJSON
TooBigTransaction
"test/unit/Golden/golden/WalletError_TooBigTransaction"
golden_WalletError_TxFailedToStabilize :: Property
golden_WalletError_TxFailedToStabilize =
goldenTestJSON
TxFailedToStabilize
"test/unit/Golden/golden/WalletError_TxFailedToStabilize"
golden_WalletError_TxRedemptionDepleted :: Property
golden_WalletError_TxRedemptionDepleted =
goldenTestJSON
TxRedemptionDepleted
"test/unit/Golden/golden/WalletError_TxRedemptionDepleted"
golden_WalletError_TxSafeSignerNotFound :: Property
golden_WalletError_TxSafeSignerNotFound =
goldenTestJSON
(TxSafeSignerNotFound $ V1 exampleAddress)
"test/unit/Golden/golden/WalletError_TxSafeSignerNotFound"
golden_WalletError_MissingRequiredParams :: Property
golden_WalletError_MissingRequiredParams =
goldenTestJSON
(MissingRequiredParams (("test", "test") :| []))
"test/unit/Golden/golden/WalletError_MissingRequiredParams"
golden_WalletError_WalletIsNotReadyToProcessPayments :: Property
golden_WalletError_WalletIsNotReadyToProcessPayments =
goldenTestJSON
(WalletIsNotReadyToProcessPayments genExample)
"test/unit/Golden/golden/WalletError_WalletIsNotReadyToProcessPayments"
golden_WalletError_NodeIsStillSyncing :: Property
golden_WalletError_NodeIsStillSyncing =
goldenTestJSON
(NodeIsStillSyncing genExample)
"test/unit/Golden/golden/WalletError_NodeIsStillSyncing"
golden_WalletError_CannotCreateAddress :: Property
golden_WalletError_CannotCreateAddress =
goldenTestJSON
(CannotCreateAddress "test")
"test/unit/Golden/golden/WalletError_CannotCreateAddress"
-------------------------------------------------------------------------------
-- JSONValidationError
-------------------------------------------------------------------------------
golden_JSONValidationError_JSONValidationFailed :: Property
golden_JSONValidationError_JSONValidationFailed =
goldenTestJSON
(JSONValidationFailed "test")
"test/unit/Golden/golden/JSONValidationError_JSONValidationFailed"
-------------------------------------------------------------------------------
-- UnsupportedMimeTypeError
-------------------------------------------------------------------------------
golden_UnsupportedMimeTypeError_UnsupportedMimeTypePresent :: Property
golden_UnsupportedMimeTypeError_UnsupportedMimeTypePresent =
goldenTestJSON
(UnsupportedMimeTypePresent "test")
"test/unit/Golden/golden/UnsupportedMimeTypeError_UnsupportedMimeTypePresent"
|
input-output-hk/pos-haskell-prototype
|
wallet/test/unit/Golden/WalletError.hs
|
mit
| 6,209 | 0 | 10 | 916 | 591 | 337 | 254 | 120 | 1 |
-- |
-- Module: BDCS.RPM.Utils
-- Copyright: (c) 2016-2017 Red Hat, Inc.
-- License: LGPL
--
-- Maintainer: https://github.com/weldr
-- Stability: alpha
-- Portability: portable
--
-- Utility functions for "BDCS.RPM"
module BDCS.RPM.Utils(splitFilename)
where
import Data.Bifunctor(first)
import qualified Data.Text as T
-- | Turn an RPM filename in form of "NAME-[EPOCH:]VERSION-RELEASE.ARCH[.rpm]
-- into a tuple of (name, epoch, version, release, and arch).
splitFilename :: T.Text -> (T.Text, Maybe T.Text, T.Text, T.Text, T.Text)
splitFilename rpm_ = let
rpm = if ".rpm" `T.isSuffixOf` rpm_ then T.dropEnd 4 rpm_ else rpm_
(front, a) = T.breakOnEnd "." rpm
(front2, r) = T.breakOnEnd "-" $ T.dropWhileEnd (== '.') front
(n, ve) = first (T.dropWhileEnd (== '-')) $ T.breakOnEnd "-" $ T.dropWhileEnd (== '-') front2
(e, v) = first (T.dropWhileEnd (== ':')) $ T.breakOnEnd ":" ve
in
(n, if e == "" then Nothing else Just $ T.dropWhile (== ':') e, v, r, a)
|
atodorov/bdcs
|
src/BDCS/RPM/Utils.hs
|
lgpl-2.1
| 1,008 | 0 | 14 | 198 | 305 | 175 | 130 | 11 | 3 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module HLearn.Models.Classifiers.Bayes
where
import Debug.Trace
import qualified Data.Map as Map
import GHC.TypeLits
import HLearn.Algebra
import HLearn.Models.Distributions
import HLearn.Models.Classifiers.Common
-------------------------------------------------------------------------------
-- data types
data Bayes labelLens dist = Bayes
{ labelDist :: !(Margin labelLens dist)
, attrDist :: !(MarginalizeOut labelLens dist)
}
instance (Show (Margin labelLens dist), Show (MarginalizeOut labelLens dist)) => Show (Bayes labelLens dist)
-- deriving (Read,Show,Eq,Ord)
-------------------------------------------------------------------------------
-- Algebra
-- instance
-- ( {-Monoid (Margin labelLens dist)
-- , Monoid (MarginalizeOut labelLens dist)
-- -}) => Monoid (Bayes labelLens dist)
-- where
-- mempty = undefined -- Bayes undefined undefined -- mempty mempty
-- b1 `mappend` b2 = undefined {-Bayes
-- { labelDist = undefined -- labelDist b1 `mappend` labelDist b2
-- , attrDist = undefined -- attrDist b1 `mappend` attrDist b2
-- }-}
-------------------------------------------------------------------------------
-- Training
-- instance
-- ( {-Datapoint dist ~ Datapoint (MarginalizeOut labelLens dist)
-- , TypeFunction labelLens
-- , Datapoint (Margin labelLens dist) ~ Range labelLens
-- , Datapoint (MarginalizeOut labelLens dist) ~ Domain labelLens
-- , Monoid (MarginalizeOut labelLens dist)
-- , Monoid (Margin labelLens dist)
-- , HomTrainer (MarginalizeOut labelLens dist)
-- , HomTrainer (Margin labelLens dist)
-- -}) => HomTrainer (Bayes labelLens dist)
-- where
-- type Datapoint (Bayes labelLens dist) = Datapoint dist
-- train = undefined
-- train1dp dp = trace "train1dp" $ Bayes
-- { labelDist = undefined -- train1dp $ typefunc (undefined::labelLens) dp
-- , attrDist = undefined -- train1dp dp
-- }
-------------------------------------------------------------------------------
-- Classification
instance Probabilistic (Bayes labelIndex dist) where
type Probability (Bayes labelIndex dist) = Probability dist
instance
( Mean (Margin labelLens dist)
, Margin labelLens dist ~ Categorical label prob
, Ord prob, Fractional prob
, prob ~ Probability (MarginalizeOut labelLens dist)
, Ord (Datapoint (Margin labelLens dist))
-- , PDF dist
-- , Ord (Datapoint (ResultDistribution (Margin labelLens dist)))
, Datapoint dist ~ Datapoint (MarginalizeOut labelLens dist)
, PDF (MarginalizeOut labelLens dist)
) => Classifier (Bayes labelLens dist)
where
type Label (Bayes labelLens dist) = Datapoint (Margin labelLens dist)
type UnlabeledDatapoint (Bayes labelLens dist) = Datapoint dist
type ResultDistribution (Bayes labelLens dist) = Margin labelLens dist
-- probabilityClassify bayes dp = (pdf (labelDist bayes) label)*(pdf (attrDist bayes) dp)
probabilityClassify bayes dp = undefined -- Categorical $ Map.fromList $ map (\k -> (k,prob k)) labelL
where
prob k = pdf (labelDist bayes) k * pdf (attrDist bayes) dp
Categorical labelMap = labelDist bayes
labelL = Map.keys labelMap
-- probabilityClassify bayes dp =
-- Categorical $ Map.mapWithKey (\label dist -> (pdf dist dp)*(pdf (labelDist bayes) label)) $ attrDist bayes
-------------------------------------------------------------------------------
-- Test
data Sex = Male | Female
deriving (Read,Show,Eq,Ord)
data Human = Human
{ _sex :: Sex
, _weight :: Double
, _height :: Double
, _shoesize :: Double
}
makeTypeLenses ''Human
ds =
[ Human Male 6 180 12
, Human Male 5.92 190 11
, Human Male 5.58 170 12
, Human Male 5.92 165 10
, Human Female 5 100 6
, Human Female 5.5 150 8
, Human Female 5.42 130 7
, Human Female 5.75 150 9
]
dp = (6:::130:::8:::HNil)::(HList '[Double,Double,Double])
-- model = train ds :: BC
type BC = Bayes TH_sex
(Multivariate Human
'[ MultiCategorical '[Sex]
, Independent Normal '[Double,Double,Double]
] Double)
instance Monoid (Bayes label dist)
{-dist = train (map snd ds) :: Multivariate (HList '[Double,Double,Double])
'[ Independent Normal '[Double]
, Dependent MultiNormal '[Double,Double]
]
Double-}
|
iamkingmaker/HLearn
|
src/HLearn/Models/Classifiers/BayesNotWorking.hs
|
bsd-3-clause
| 4,952 | 0 | 12 | 1,074 | 781 | 437 | 344 | -1 | -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.CloudWatch.PutMetricData
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch
-- associates the data points with the specified metric. If the specified metric
-- does not exist, Amazon CloudWatch creates the metric. It can take up to
-- fifteen minutes for a new metric to appear in calls to the 'ListMetrics' action.
--
-- The size of a PutMetricData request is limited to 8 KB for HTTP GET
-- requests and 40 KB for HTTP POST requests.
--
-- Although the 'Value' parameter accepts numbers of type 'Double', Amazon
-- CloudWatch truncates values with very large exponents. Values with base-10
-- exponents greater than 126 (1 x 10^126) are truncated. Likewise, values with
-- base-10 exponents less than -130 (1 x 10^-130) are also truncated. Data that
-- is timestamped 24 hours or more in the past may take in excess of 48 hours to
-- become available from submission time using 'GetMetricStatistics'.
--
-- <http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html>
module Network.AWS.CloudWatch.PutMetricData
(
-- * Request
PutMetricData
-- ** Request constructor
, putMetricData
-- ** Request lenses
, pmdMetricData
, pmdNamespace
-- * Response
, PutMetricDataResponse
-- ** Response constructor
, putMetricDataResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.CloudWatch.Types
import qualified GHC.Exts
data PutMetricData = PutMetricData
{ _pmdMetricData :: List "member" MetricDatum
, _pmdNamespace :: Text
} deriving (Eq, Read, Show)
-- | 'PutMetricData' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pmdMetricData' @::@ ['MetricDatum']
--
-- * 'pmdNamespace' @::@ 'Text'
--
putMetricData :: Text -- ^ 'pmdNamespace'
-> PutMetricData
putMetricData p1 = PutMetricData
{ _pmdNamespace = p1
, _pmdMetricData = mempty
}
-- | A list of data describing the metric.
pmdMetricData :: Lens' PutMetricData [MetricDatum]
pmdMetricData = lens _pmdMetricData (\s a -> s { _pmdMetricData = a }) . _List
-- | The namespace for the metric data.
pmdNamespace :: Lens' PutMetricData Text
pmdNamespace = lens _pmdNamespace (\s a -> s { _pmdNamespace = a })
data PutMetricDataResponse = PutMetricDataResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'PutMetricDataResponse' constructor.
putMetricDataResponse :: PutMetricDataResponse
putMetricDataResponse = PutMetricDataResponse
instance ToPath PutMetricData where
toPath = const "/"
instance ToQuery PutMetricData where
toQuery PutMetricData{..} = mconcat
[ "MetricData" =? _pmdMetricData
, "Namespace" =? _pmdNamespace
]
instance ToHeaders PutMetricData
instance AWSRequest PutMetricData where
type Sv PutMetricData = CloudWatch
type Rs PutMetricData = PutMetricDataResponse
request = post "PutMetricData"
response = nullResponse PutMetricDataResponse
|
romanb/amazonka
|
amazonka-cloudwatch/gen/Network/AWS/CloudWatch/PutMetricData.hs
|
mpl-2.0
| 4,007 | 0 | 10 | 839 | 407 | 253 | 154 | 51 | 1 |
module ClassIn1 where
--Any class/instance name declared in this module can be renamed
--Rename class name "Reversable" to "MyReversable"
class MyReversable a where
myreverse :: a -> a
myreverse _ = undefined
instance MyReversable [a] where
myreverse = reverse
data Foo = Boo | Moo
instance Eq Foo where
Boo == Boo = True
Moo == Moo = True
_ == _ = False
main = myreverse [1,2,3]
|
kmate/HaRe
|
old/testing/renaming/ClassIn1_TokOut.hs
|
bsd-3-clause
| 411 | 0 | 7 | 99 | 116 | 62 | 54 | 12 | 1 |
module Test.Haddock.Utils where
import Control.Monad
import Data.Maybe
import System.Directory
import System.FilePath
mlast :: [a] -> Maybe a
mlast = listToMaybe . reverse
partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM _ [] = pure ([], [])
partitionM p (x:xs) = do
(ss, fs) <- partitionM p xs
b <- p x
pure $ if b then (x:ss, fs) else (ss, x:fs)
whenM :: Monad m => m Bool -> m () -> m ()
whenM mb action = mb >>= \b -> when b action
getDirectoryTree :: FilePath -> IO [FilePath]
getDirectoryTree path = do
(dirs, files) <- partitionM isDirectory =<< contents
subfiles <- fmap concat . forM dirs $ \dir ->
map (dir </>) <$> getDirectoryTree (path </> dir)
pure $ files ++ subfiles
where
contents = filter realEntry <$> getDirectoryContents path
isDirectory entry = doesDirectoryExist $ path </> entry
realEntry entry = not $ entry == "." || entry == ".."
createEmptyDirectory :: FilePath -> IO ()
createEmptyDirectory path = do
whenM (doesDirectoryExist path) $ removeDirectoryRecursive path
createDirectory path
-- | Just like 'copyFile' but output directory path is not required to exist.
copyFile' :: FilePath -> FilePath -> IO ()
copyFile' old new = do
createDirectoryIfMissing True $ takeDirectory new
copyFile old new
|
Helkafen/haddock
|
haddock-test/src/Test/Haddock/Utils.hs
|
bsd-2-clause
| 1,328 | 0 | 13 | 292 | 516 | 260 | 256 | 32 | 2 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.HintedTile
-- Copyright : (c) Peter De Wachter <[email protected]>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Peter De Wachter <[email protected]>
-- Andrea Rossato <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- A gapless tiled layout that attempts to obey window size hints,
-- rather than simply ignoring them.
--
-----------------------------------------------------------------------------
module XMonad.Layout.HintedTile (
-- * Usage
-- $usage
HintedTile(..), Orientation(..), Alignment(..)
) where
import XMonad hiding (Tall(..))
import qualified XMonad.StackSet as W
import Control.Monad
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Layout.HintedTile
--
-- Then edit your @layoutHook@ by adding the HintedTile layout:
--
-- > myLayout = hintedTile Tall ||| hintedTile Wide ||| Full ||| etc..
-- > where
-- > hintedTile = HintedTile nmaster delta ratio TopLeft
-- > nmaster = 1
-- > ratio = 1/2
-- > delta = 3/100
-- > main = xmonad defaultConfig { layoutHook = myLayout }
--
-- Because both Xmonad and Xmonad.Layout.HintedTile define Tall,
-- you need to disambiguate Tall. If you are replacing the
-- built-in Tall with HintedTile, change @import Xmonad@ to
-- @import Xmonad hiding (Tall)@.
--
-- For more detailed instructions on editing the layoutHook see:
--
-- "XMonad.Doc.Extending#Editing_the_layout_hook"
data HintedTile a = HintedTile
{ nmaster :: !Int -- ^ number of windows in the master pane
, delta :: !Rational -- ^ how much to change when resizing
, frac :: !Rational -- ^ ratio between master/nonmaster panes
, alignment :: !Alignment -- ^ Where to place windows that are smaller
-- than their preordained rectangles.
, orientation :: !Orientation -- ^ Tall or Wide (mirrored) layout?
} deriving ( Show, Read )
data Orientation
= Wide -- ^ Lay out windows similarly to Mirror tiled.
| Tall -- ^ Lay out windows similarly to tiled.
deriving ( Show, Read, Eq, Ord )
data Alignment = TopLeft | Center | BottomRight
deriving ( Show, Read, Eq, Ord )
instance LayoutClass HintedTile Window where
doLayout (HintedTile { orientation = o, nmaster = nm, frac = f, alignment = al }) r w' = do
bhs <- mapM mkAdjust w
let (masters, slaves) = splitAt nm bhs
return (zip w (tiler masters slaves), Nothing)
where
w = W.integrate w'
tiler masters slaves
| null masters || null slaves = divide al o (masters ++ slaves) r
| otherwise = split o f r (divide al o masters) (divide al o slaves)
pureMessage c m = fmap resize (fromMessage m) `mplus`
fmap incmastern (fromMessage m)
where
resize Shrink = c { frac = max 0 $ frac c - delta c }
resize Expand = c { frac = min 1 $ frac c + delta c }
incmastern (IncMasterN d) = c { nmaster = max 0 $ nmaster c + d }
description l = show (orientation l)
align :: Alignment -> Position -> Dimension -> Dimension -> Position
align TopLeft p _ _ = p
align Center p a b = p + fromIntegral (a - b) `div` 2
align BottomRight p a b = p + fromIntegral (a - b)
-- Divide the screen vertically (horizontally) into n subrectangles
divide :: Alignment -> Orientation -> [D -> D] -> Rectangle -> [Rectangle]
divide _ _ [] _ = []
divide al _ [bh] (Rectangle sx sy sw sh) = [Rectangle (align al sx sw w) (align al sy sh h) w h]
where
(w, h) = bh (sw, sh)
divide al Tall (bh:bhs) (Rectangle sx sy sw sh) = (Rectangle (align al sx sw w) sy w h) :
(divide al Tall bhs (Rectangle sx (sy + fromIntegral h) sw (sh - h)))
where
(w, h) = bh (sw, sh `div` fromIntegral (1 + (length bhs)))
divide al Wide (bh:bhs) (Rectangle sx sy sw sh) = (Rectangle sx (align al sy sh h) w h) :
(divide al Wide bhs (Rectangle (sx + fromIntegral w) sy (sw - w) sh))
where
(w, h) = bh (sw `div` fromIntegral (1 + (length bhs)), sh)
-- Split the screen into two rectangles, using a rational to specify the ratio
split :: Orientation -> Rational -> Rectangle -> (Rectangle -> [Rectangle])
-> (Rectangle -> [Rectangle]) -> [Rectangle]
split Tall f (Rectangle sx sy sw sh) left right = leftRects ++ rightRects
where
leftw = floor $ fromIntegral sw * f
leftRects = left $ Rectangle sx sy leftw sh
rightx = (maximum . map rect_width) leftRects
rightRects = right $ Rectangle (sx + fromIntegral rightx) sy (sw - rightx) sh
split Wide f (Rectangle sx sy sw sh) top bottom = topRects ++ bottomRects
where
toph = floor $ fromIntegral sh * f
topRects = top $ Rectangle sx sy sw toph
bottomy = (maximum . map rect_height) topRects
bottomRects = bottom $ Rectangle sx (sy + fromIntegral bottomy) sw (sh - bottomy)
|
markus1189/xmonad-contrib-710
|
XMonad/Layout/HintedTile.hs
|
bsd-3-clause
| 5,118 | 0 | 14 | 1,249 | 1,405 | 760 | 645 | 70 | 1 |
{-# LANGUAGE DataKinds, TypeFamilies #-}
newtype X = RollX (() -> X)
type family F t :: X where
F t = RollX (t -> ())
|
ezyang/ghc
|
testsuite/tests/typecheck/should_fail/T14055.hs
|
bsd-3-clause
| 124 | 1 | 8 | 32 | 50 | 28 | 22 | 4 | 0 |
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE OverloadedStrings #-}
module IRTS.JavaScript.AST where
import Data.Word
import Data.Char (isDigit)
import qualified Data.Text as T
data JSType = JSIntTy
| JSStringTy
| JSIntegerTy
| JSFloatTy
| JSCharTy
| JSPtrTy
| JSForgotTy
deriving Eq
data JSInteger = JSBigZero
| JSBigOne
| JSBigInt Integer
| JSBigIntExpr JS
deriving Eq
data JSNum = JSInt Int
| JSFloat Double
| JSInteger JSInteger
deriving Eq
data JSWord = JSWord8 Word8
| JSWord16 Word16
| JSWord32 Word32
| JSWord64 Word64
deriving Eq
data JSAnnotation = JSConstructor deriving Eq
instance Show JSAnnotation where
show JSConstructor = "constructor"
data JS = JSRaw String
| JSIdent String
| JSFunction [String] JS
| JSType JSType
| JSSeq [JS]
| JSReturn JS
| JSApp JS [JS]
| JSNew String [JS]
| JSError String
| JSBinOp String JS JS
| JSPreOp String JS
| JSPostOp String JS
| JSProj JS String
| JSNull
| JSUndefined
| JSThis
| JSTrue
| JSFalse
| JSArray [JS]
| JSString String
| JSNum JSNum
| JSWord JSWord
| JSAssign JS JS
| JSAlloc String (Maybe JS)
| JSIndex JS JS
| JSSwitch JS [(JS, JS)] (Maybe JS)
| JSCond [(JS, JS)]
| JSTernary JS JS JS
| JSParens JS
| JSWhile JS JS
| JSFFI String [JS]
| JSAnnotation JSAnnotation JS
| JSDelete JS
| JSNoop
deriving Eq
data FFI = FFICode Char | FFIArg Int | FFIError String
ffi :: String -> [String] -> T.Text
ffi code args = let parsed = ffiParse code in
case ffiError parsed of
Just err -> error err
Nothing -> renderFFI parsed args
where
ffiParse :: String -> [FFI]
ffiParse "" = []
ffiParse ['%'] = [FFIError $ "FFI - Invalid positional argument"]
ffiParse ('%':'%':ss) = FFICode '%' : ffiParse ss
ffiParse ('%':s:ss)
| isDigit s =
FFIArg (
read $ s : takeWhile isDigit ss
) : ffiParse (dropWhile isDigit ss)
| otherwise =
[FFIError "FFI - Invalid positional argument"]
ffiParse (s:ss) = FFICode s : ffiParse ss
ffiError :: [FFI] -> Maybe String
ffiError [] = Nothing
ffiError ((FFIError s):xs) = Just s
ffiError (x:xs) = ffiError xs
renderFFI :: [FFI] -> [String] -> T.Text
renderFFI [] _ = ""
renderFFI (FFICode c : fs) args = c `T.cons` renderFFI fs args
renderFFI (FFIArg i : fs) args
| i < length args && i >= 0 =
T.pack (args !! i)
`T.append` renderFFI fs args
| otherwise = error "FFI - Argument index out of bounds"
compileJS :: JS -> T.Text
compileJS = compileJS' 0
compileJS' :: Int -> JS -> T.Text
compileJS' indent JSNoop = ""
compileJS' indent (JSAnnotation annotation js) =
"/** @"
`T.append` T.pack (show annotation)
`T.append` " */\n"
`T.append` compileJS' indent js
compileJS' indent (JSDelete js) =
"delete " `T.append` compileJS' 0 js
compileJS' indent (JSFFI raw args) =
ffi raw (map (T.unpack . compileJS' indent) args)
compileJS' indent (JSRaw code) =
T.pack code
compileJS' indent (JSIdent ident) =
T.pack ident
compileJS' indent (JSFunction args body) =
T.replicate indent " " `T.append` "function("
`T.append` T.intercalate "," (map T.pack args)
`T.append` "){\n"
`T.append` compileJS' (indent + 2) body
`T.append` "\n}\n"
compileJS' indent (JSType ty)
| JSIntTy <- ty = "i$Int"
| JSStringTy <- ty = "i$String"
| JSIntegerTy <- ty = "i$Integer"
| JSFloatTy <- ty = "i$Float"
| JSCharTy <- ty = "i$Char"
| JSPtrTy <- ty = "i$Ptr"
| JSForgotTy <- ty = "i$Forgot"
compileJS' indent (JSSeq seq) =
T.intercalate ";\n" (
map (
(T.replicate indent " " `T.append`) . (compileJS' indent)
) $ filter (/= JSNoop) seq
) `T.append` ";"
compileJS' indent (JSReturn val) =
"return " `T.append` compileJS' indent val
compileJS' indent (JSApp lhs rhs)
| JSFunction {} <- lhs =
T.concat ["(", compileJS' indent lhs, ")(", args, ")"]
| otherwise =
T.concat [compileJS' indent lhs, "(", args, ")"]
where args :: T.Text
args = T.intercalate "," $ map (compileJS' 0) rhs
compileJS' indent (JSNew name args) =
"new "
`T.append` T.pack name
`T.append` "("
`T.append` T.intercalate "," (map (compileJS' 0) args)
`T.append` ")"
compileJS' indent (JSError exc) =
"(function(){throw new Error(\"" `T.append` T.pack exc `T.append` "\")})()"
compileJS' indent (JSBinOp op lhs rhs) =
compileJS' indent lhs
`T.append` " "
`T.append` T.pack op
`T.append` " "
`T.append` compileJS' indent rhs
compileJS' indent (JSPreOp op val) =
T.pack op `T.append` "(" `T.append` compileJS' indent val `T.append` ")"
compileJS' indent (JSProj obj field)
| JSFunction {} <- obj =
T.concat ["(", compileJS' indent obj, ").", T.pack field]
| JSAssign {} <- obj =
T.concat ["(", compileJS' indent obj, ").", T.pack field]
| otherwise =
compileJS' indent obj `T.append` ('.' `T.cons` T.pack field)
compileJS' indent JSNull =
"null"
compileJS' indent JSUndefined =
"undefined"
compileJS' indent JSThis =
"this"
compileJS' indent JSTrue =
"true"
compileJS' indent JSFalse =
"false"
compileJS' indent (JSArray elems) =
"[" `T.append` T.intercalate "," (map (compileJS' 0) elems) `T.append` "]"
compileJS' indent (JSString str) =
"\"" `T.append` T.pack str `T.append` "\""
compileJS' indent (JSNum num)
| JSInt i <- num = T.pack (show i)
| JSFloat f <- num = T.pack (show f)
| JSInteger JSBigZero <- num = T.pack "i$ZERO"
| JSInteger JSBigOne <- num = T.pack "i$ONE"
| JSInteger (JSBigInt i) <- num = T.pack (show i)
| JSInteger (JSBigIntExpr e) <- num =
"i$bigInt(" `T.append` compileJS' indent e `T.append` ")"
compileJS' indent (JSAssign lhs rhs) =
compileJS' indent lhs `T.append` " = " `T.append` compileJS' indent rhs
compileJS' 0 (JSAlloc name (Just val@(JSNew _ _))) =
"var "
`T.append` T.pack name
`T.append` " = "
`T.append` compileJS' 0 val
`T.append` ";\n"
compileJS' indent (JSAlloc name val) =
"var "
`T.append` T.pack name
`T.append` maybe "" ((" = " `T.append`) . compileJS' indent) val
compileJS' indent (JSIndex lhs rhs) =
compileJS' indent lhs
`T.append` "["
`T.append` compileJS' indent rhs
`T.append` "]"
compileJS' indent (JSCond branches) =
T.intercalate " else " $ map createIfBlock branches
where
createIfBlock (JSNoop, e@(JSSeq _)) =
"{\n"
`T.append` compileJS' (indent + 2) e
`T.append` "\n" `T.append` T.replicate indent " " `T.append` "}"
createIfBlock (JSNoop, e) =
"{\n"
`T.append` compileJS' (indent + 2) e
`T.append` ";\n" `T.append` T.replicate indent " " `T.append` "}"
createIfBlock (cond, e@(JSSeq _)) =
"if (" `T.append` compileJS' indent cond `T.append`") {\n"
`T.append` compileJS' (indent + 2) e
`T.append` "\n" `T.append` T.replicate indent " " `T.append` "}"
createIfBlock (cond, e) =
"if (" `T.append` compileJS' indent cond `T.append`") {\n"
`T.append` T.replicate (indent + 2) " "
`T.append` compileJS' (indent + 2) e
`T.append` ";\n"
`T.append` T.replicate indent " "
`T.append` "}"
compileJS' indent (JSSwitch val [(_,JSSeq seq)] Nothing) =
let (h,t) = splitAt 1 seq in
(T.concat (map (compileJS' indent) h) `T.append` ";\n")
`T.append` (
T.intercalate ";\n" $ map (
(T.replicate indent " " `T.append`) . compileJS' indent
) t
)
compileJS' indent (JSSwitch val branches def) =
"switch(" `T.append` compileJS' indent val `T.append` "){\n"
`T.append` T.concat (map mkBranch branches)
`T.append` mkDefault def
`T.append` T.replicate indent " " `T.append` "}"
where
mkBranch :: (JS, JS) -> T.Text
mkBranch (tag, code) =
T.replicate (indent + 2) " "
`T.append` "case "
`T.append` compileJS' indent tag
`T.append` ":\n"
`T.append` compileJS' (indent + 4) code
`T.append` "\n"
`T.append` (T.replicate (indent + 4) " " `T.append` "break;\n")
mkDefault :: Maybe JS -> T.Text
mkDefault Nothing = ""
mkDefault (Just def) =
T.replicate (indent + 2) " " `T.append` "default:\n"
`T.append` compileJS' (indent + 4)def
`T.append` "\n"
compileJS' indent (JSTernary cond true false) =
let c = compileJS' indent cond
t = compileJS' indent true
f = compileJS' indent false in
"("
`T.append` c
`T.append` ")?("
`T.append` t
`T.append` "):("
`T.append` f
`T.append` ")"
compileJS' indent (JSParens js) =
"(" `T.append` compileJS' indent js `T.append` ")"
compileJS' indent (JSWhile cond body) =
"while (" `T.append` compileJS' indent cond `T.append` ") {\n"
`T.append` compileJS' (indent + 2) body
`T.append` "\n" `T.append` T.replicate indent " " `T.append` "}"
compileJS' indent (JSWord word)
| JSWord8 b <- word =
"new Uint8Array([" `T.append` T.pack (show b) `T.append` "])"
| JSWord16 b <- word =
"new Uint16Array([" `T.append` T.pack (show b) `T.append` "])"
| JSWord32 b <- word =
"new Uint32Array([" `T.append` T.pack (show b) `T.append` "])"
| JSWord64 b <- word =
"i$bigInt(\"" `T.append` T.pack (show b) `T.append` "\")"
jsInstanceOf :: JS -> String -> JS
jsInstanceOf obj cls = JSBinOp "instanceof" obj (JSIdent cls)
jsOr :: JS -> JS -> JS
jsOr lhs rhs = JSBinOp "||" lhs rhs
jsAnd :: JS -> JS -> JS
jsAnd lhs rhs = JSBinOp "&&" lhs rhs
jsMeth :: JS -> String -> [JS] -> JS
jsMeth obj meth args = JSApp (JSProj obj meth) args
jsCall :: String -> [JS] -> JS
jsCall fun args = JSApp (JSIdent fun) args
jsTypeOf :: JS -> JS
jsTypeOf js = JSPreOp "typeof " js
jsEq :: JS -> JS -> JS
jsEq lhs@(JSNum (JSInteger _)) rhs = JSApp (JSProj lhs "equals") [rhs]
jsEq lhs rhs@(JSNum (JSInteger _)) = JSApp (JSProj lhs "equals") [rhs]
jsEq lhs rhs = JSBinOp "==" lhs rhs
jsNotEq :: JS -> JS -> JS
jsNotEq lhs rhs = JSBinOp "!=" lhs rhs
jsIsNumber :: JS -> JS
jsIsNumber js = (jsTypeOf js) `jsEq` (JSString "number")
jsIsNull :: JS -> JS
jsIsNull js = JSBinOp "==" js JSNull
jsBigInt :: JS -> JS
jsBigInt (JSString "0") = JSNum (JSInteger JSBigZero)
jsBigInt (JSString "1") = JSNum (JSInteger JSBigOne)
jsBigInt js = JSNum $ JSInteger $ JSBigIntExpr js
jsUnPackBits :: JS -> JS
jsUnPackBits js = JSIndex js $ JSNum (JSInt 0)
jsPackUBits8 :: JS -> JS
jsPackUBits8 js = JSNew "Uint8Array" [JSArray [js]]
jsPackUBits16 :: JS -> JS
jsPackUBits16 js = JSNew "Uint16Array" [JSArray [js]]
jsPackUBits32 :: JS -> JS
jsPackUBits32 js = JSNew "Uint32Array" [JSArray [js]]
jsPackSBits8 :: JS -> JS
jsPackSBits8 js = JSNew "Int8Array" [JSArray [js]]
jsPackSBits16 :: JS -> JS
jsPackSBits16 js = JSNew "Int16Array" [JSArray [js]]
jsPackSBits32 :: JS -> JS
jsPackSBits32 js = JSNew "Int32Array" [JSArray [js]]
|
mrmonday/Idris-dev
|
src/IRTS/JavaScript/AST.hs
|
bsd-3-clause
| 11,430 | 0 | 15 | 3,124 | 4,398 | 2,320 | 2,078 | 318 | 10 |
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -O #-} -- -O casused a Lint error in the simplifier, so I'm putting that in
-- all the time, so we don't miss it in a fast validate
-- !!! Rank 2 polymorphism
-- Both f and g are rejected by Hugs [April 2001]
module Foo where
data T = T { t1 :: forall a. a -> a , t2 :: forall a b. a->b->b }
-- Test pattern bindings for polymorphic fields
f :: T -> (Int,Char)
f t = let T { t1 = my_t1 } = t
in
(my_t1 3, my_t1 'c')
-- Test record update with polymorphic fields
g :: T -> T
g t = t { t2 = \x y -> y }
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/typecheck/should_compile/tc124.hs
|
bsd-3-clause
| 592 | 0 | 11 | 174 | 144 | 84 | 60 | 9 | 1 |
{-# LANGUAGE TypeFamilies #-}
module T9840 where
import T9840a
type family X :: * -> * where
type family F (a :: * -> *) where
foo :: G (F X) -> G (F X)
foo x = x
|
urbanslug/ghc
|
testsuite/tests/indexed-types/should_compile/T9840.hs
|
bsd-3-clause
| 168 | 0 | 8 | 44 | 73 | 42 | 31 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Routing (handleRequest) where
import Web.Scotty (ScottyM, get,
html, redirect, notFound, text, file, setHeader)
import Views.Home (homeView)
import Views.Contacts (contactsView)
handleRequest :: ScottyM ()
handleRequest = do
get "/" homeView
get "/contacts" contactsView
get "/dl" $ do
setHeader "Content-Type" "application/octet-stream"
setHeader "Content-Disposition" "attachment"
file "src/Main.hs"
get "/google" $ do
redirect "http://www.google.com"
notFound $ do
text "404 not found"
|
av-ast/hello-scotty
|
src/Routing.hs
|
mit
| 582 | 0 | 10 | 113 | 153 | 76 | 77 | 18 | 1 |
module Handler.AdminVerificationUrl where
import Import
import Yesod.Auth.Email (randomKey)
import Model -- UniqueUser
getAdminVerificationUrlR :: Handler Html
getAdminVerificationUrlR = do
app <- getYesod
memail <- runInputGet $ iopt emailField "email"
mpair <-
case memail of
Nothing -> return Nothing
Just email -> $runDB $ do
mident <- selectFirst [IdentLident ==. mkLowerCaseText email] []
key <- liftIO $ randomKey app
uid <- case mident of
Just (Entity _ i) -> do
let uid = identUser i
update uid [UserVerkey =. Just key]
return uid
Nothing -> do
muser <- getBy $ UniqueUser email
case muser of
Nothing -> addUnverifiedDB email key
Just (Entity uid _) -> do
update uid [UserVerkey =. Just key]
return uid
return $ Just (email, VerifyEmailR uid key)
defaultLayout $ do
setTitle "Verification URLs"
[whamlet|
<h1>Verification URLs
<p>
<a href=@{AdminR}>Return to admin page.
$maybe (email, url) <- mpair
<p>
Verification URL for email address #{email} is
<b>@{url}
\.
<p .text-warning>
You should only send this URL to the specified email address.
Otherwise, a user could be verified for an email address he/she does not control.
<form>
Email address:
<input type=email name=email>
<input type=submit value="Get verification URL">
|]
|
fpco/schoolofhaskell.com
|
src/Handler/AdminVerificationUrl.hs
|
mit
| 1,901 | 0 | 28 | 851 | 316 | 148 | 168 | -1 | -1 |
-- | Centrinel C language traversal monad
--
-- The @HGTrav@ monad stack has:
-- 1. a collection of analysis hooks that are triggered by traversals of C ASTs,
-- 2. and a unification state of region unification constraints and a map from C types to region unification variables.
--
--
{-# language GeneralizedNewtypeDeriving, LambdaCase, ViewPatterns #-}
module Centrinel.Trav (
HGTrav
, runHGTrav
, evalHGTrav
, HGAnalysis
, withHGAnalysis
, RegionIdentMap
, frozenRegionUnificationState
) where
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader (ReaderT)
import Control.Monad.Except (ExceptT (..))
import qualified Control.Monad.Trans.Reader as Reader
import Control.Monad.Trans.State.Lazy (StateT)
import qualified Control.Monad.Trans.State.Lazy as State
import Data.Bifunctor (Bifunctor(..))
import qualified Data.Map.Lazy as Map
import Language.C.Data.Ident (SUERef)
import Language.C.Data.Error (CError, fromError)
import Language.C.Analysis.SemRep (DeclEvent)
import qualified Language.C.Analysis.TravMonad as AM
import Language.C.Analysis.TravMonad.Instances ()
import qualified Centrinel.Region.Ident as HGId
import Centrinel.Region.Region (RegionScheme)
import qualified Centrinel.Region.Unification as U
import qualified Centrinel.Region.Unification.Term as U
import Centrinel.Types (CentrinelAnalysisError (..))
import Centrinel.Warning (hgWarn)
type HGAnalysis s = DeclEvent -> HGTrav s ()
type RegionIdentMap = Map.Map HGId.RegionIdent U.RegionUnifyTerm
newtype HGTrav s a = HGTrav { unHGTrav :: ReaderT (HGAnalysis s) (StateT RegionIdentMap (U.UnifyRegT (AM.Trav s))) a}
deriving (Functor, Applicative, Monad)
instance AM.MonadName (HGTrav s) where
genName = HGTrav AM.genName
instance AM.MonadSymtab (HGTrav s) where
getDefTable = HGTrav AM.getDefTable
withDefTable = HGTrav . AM.withDefTable
instance AM.MonadCError (HGTrav s) where
throwTravError = HGTrav . AM.throwTravError
catchTravError (HGTrav c) handler = HGTrav (AM.catchTravError c (unHGTrav . handler))
recordError = HGTrav . AM.recordError
getErrors = HGTrav $ AM.getErrors
instance U.RegionUnification U.RegionVar (HGTrav s) where
newRegion = HGTrav $ lift $ lift U.newRegion
sameRegion v = HGTrav . lift . lift . U.sameRegion v
constantRegion v = HGTrav . lift . lift . U.constantRegion v
regionAddLocation v = HGTrav . lift . lift . U.regionAddLocation v
instance U.ApplyUnificationState (HGTrav s) where
applyUnificationState = HGTrav . lift . lift . U.applyUnificationState
(-:=) :: U.RegionVar -> Maybe U.RegionUnifyTerm -> HGTrav s U.RegionUnifyTerm
v -:= Nothing = return (U.regionUnifyVar v)
v -:= Just r = do
m <- HGTrav $ lift $ lift $ U.unify (U.regionUnifyVar v) r
case m of
Right r' -> return r'
Left _err -> do
AM.recordError (hgWarn "failed to unify regions" Nothing) -- TODO: region info
return (U.regionUnifyVar v)
getRegionIdent :: HGId.RegionIdent -> HGTrav s (Maybe (U.RegionUnifyTerm))
getRegionIdent i = HGTrav $ lift $ State.gets (Map.lookup i)
putRegionIdent :: HGId.RegionIdent -> U.RegionUnifyTerm -> HGTrav s ()
putRegionIdent i m = HGTrav $ lift $ State.modify' (Map.insert i m)
-- | Gets a mapping of the region identifiers that have been noted by
-- unification to their 'RegionScheme' as implied by the constraints available
-- at the time of the call.
frozenRegionUnificationState :: HGTrav s (Map.Map SUERef RegionScheme)
frozenRegionUnificationState = do
sueRegions <- HGTrav $ lift $ State.gets munge
traverse (fmap U.extractRegionScheme . U.applyUnificationState) sueRegions
where
munge :: Map.Map HGId.RegionIdent U.RegionUnifyTerm -> Map.Map SUERef U.RegionUnifyTerm
munge = Map.mapKeysMonotonic onlySUERef . Map.filterWithKey (\k -> const (isStructTag k))
onlySUERef :: HGId.RegionIdent -> SUERef
onlySUERef (HGId.StructTagId sue) = sue
onlySUERef (HGId.TypedefId {}) = error "unexpected TypedefId in onlySUERef"
isStructTag :: HGId.RegionIdent -> Bool
isStructTag (HGId.StructTagId {}) = True
isStructTag (HGId.TypedefId {}) = False
instance HGId.RegionAssignment HGId.RegionIdent U.RegionVar (HGTrav s) where
assignRegion i = do
v <- U.newRegion
r <- getRegionIdent i
r' <- v -:= r
putRegionIdent i r'
return v
instance AM.MonadTrav (HGTrav s) where
handleDecl ev = do
handler <- HGTrav Reader.ask
handler ev
withHGAnalysis :: HGAnalysis s -> HGTrav s a -> HGTrav s a
withHGAnalysis az =
HGTrav . Reader.local (addAnalysis az) . unHGTrav
where
-- new analysis runs last
addAnalysis m = (>> m)
runHGTrav :: Monad m
=> HGTrav () a
-> ExceptT [CentrinelAnalysisError] m ((a, RegionIdentMap), [CentrinelAnalysisError])
runHGTrav = helper State.runStateT
evalHGTrav :: Monad m
=> HGTrav () a
-> ExceptT [CentrinelAnalysisError] m (a, [CentrinelAnalysisError])
evalHGTrav = helper State.evalStateT
helper :: Monad m
=> (StateT RegionIdentMap (U.UnifyRegT (AM.Trav t)) a
-> Map.Map k b
-> U.UnifyRegT (AM.Trav ()) r)
-> HGTrav t a
-> ExceptT [CentrinelAnalysisError] m (r, [CentrinelAnalysisError])
helper destructState (HGTrav comp) =
ExceptT $ return . fixupErrors $ AM.runTrav_ $ U.runUnifyRegT (destructState (Reader.runReaderT comp az) Map.empty)
where
az = const (return ())
-- change errors and warnings from one form to another
fixupFatalNonFatal :: (e1 -> e2) -> (w1 -> w2)
-> Either e1 (a, w1) -> Either e2 (a, w2)
fixupFatalNonFatal fErr fWarn = bimap fErr (fmap fWarn)
-- refine 'CError' errors and warnings to 'CentrinelAnalysisError'
fixupErrors :: Either [CError] (a, [CError])
-> Either [CentrinelAnalysisError] (a, [CentrinelAnalysisError])
fixupErrors = fixupFatalNonFatal (map centrinelAnalysisError) (map centrinelAnalysisError)
-- | Refine an existentially-packed 'CError' into one of the well-known Centrinel
-- analysis errors, or a purely C syntax or semantics error from the "language-c" package.
centrinelAnalysisError :: CError -> CentrinelAnalysisError
centrinelAnalysisError =
\case
e | Just regError <- fromError e -> CARegionMismatchError regError
| Just nakedPtrError <- fromError e -> CANakedPointerError nakedPtrError
| otherwise -> CACError e
|
lambdageek/use-c
|
src/Centrinel/Trav.hs
|
mit
| 6,356 | 0 | 15 | 1,149 | 1,842 | 974 | 868 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Unison.Test.TermParser where
import Control.Applicative
import Control.Monad (join)
import EasyTest
import qualified Text.Megaparsec as P
import Text.RawString.QQ
import Unison.Parser
import qualified Unison.Parsers as Ps
import Unison.PrintError (renderParseErrorAsANSI)
import Unison.Symbol (Symbol)
import qualified Unison.TermParser as TP
import qualified Unison.Test.Common as Common
test1 :: Test ()
test1 = scope "termparser" . tests . map parses $
[ "1"
, "1.0"
, "+1"
, "-1"
, "+1.0"
, "-1.0"
, "1e3"
, "1e+3"
, "1e-3"
, "+1e3"
, "+1e+3"
, "+1e-3"
, "-1e3"
, "-1e+3"
, "-1e-3"
, "1.2e3"
, "1.2e+3"
, "1.2e-3"
, "+1.2e3"
, "+1.2e+3"
, "+1.2e-3"
, "-1.2e3"
, "-1.2e+3"
, "-1.2e-3"
, "-4 th"
, "()"
, "(0)"
, "forty"
, "forty two"
, "\"forty two\""
, "[1,2,3]"
, "\"abc\""
, "?x"
, "?\\n"
, "x + 1"
, "1 + 1"
, "1 Nat.+ 1"
, "( x + 1 )"
, "foo 42"
, "1 Nat.== 1"
, "x Nat.== y"
, "if 1 Nat.== 1 then 1 else 1"
, "if 1 Nat.== x then 1 else 1"
, "if x Nat.== 1 then 1 else 1"
, "if x == 1 then 1 else 1"
, "if x Nat.== x then 1 else 1"
--
-- Block tests
, "let x = 1\n" ++
" x"
, "let\n" ++
" y = 1\n" ++
" x"
, unlines [
"let y = 1 ",
" x = 2 ",
" x + y"]
, "(let \n" ++
" x = 23 + 42\n" ++
" x + 1 )"
--
-- Handlers
, "handle\n" ++
" x = 23 + 42\n" ++
" x + foo 8 102.0 +4\n" ++
"with foo"
, "handle\n" ++
" x = 1\n" ++
" x\n" ++
"with foo"
, "handle x with foo"
, "handle foo with cases\n" ++
" { x } -> x"
-- Patterns
, "match x with x -> x"
, "match x with 0 -> 1"
, "match x with\n" ++
" 0 -> 1"
, "match +0 with\n" ++
" +0 -> -1"
, "match x with\n" ++
" x -> 1\n" ++
" 2 -> 7\n" ++
" _ -> 3\n" ++
" Tuple.Cons x y -> x + y\n" ++
" Tuple.Cons (Tuple.Cons x y) _ -> x + y \n"
, "match x with\n" ++
" 0 ->\n" ++
" z = 0\n" ++
" z"
, "match x with\n" ++
" 0 | 1 == 2 -> 123"
, "match x with\n" ++
" [] -> 0\n" ++
" [1] -> 1\n" ++
" 2 +: _ -> 2\n" ++
" _ :+ 3 -> 3\n" ++
" [4] ++ _ -> 4\n" ++
" _ ++ [5] -> 5\n" ++
" _ -> -1"
, "cases x -> x"
, "cases\n" ++
" [] -> 0\n" ++
" [x] -> 1\n" ++
" _ -> 2"
, "cases\n" ++
" 0 ->\n" ++
" z = 0\n" ++
" z"
-- Conditionals
, "if x then y else z"
, "-- if test 1\n" ++
"if\n" ++
" s = 0\n" ++
" s > 0\n" ++
"then\n" ++
" s = 0\n" ++
" s + 1\n" ++
"else\n" ++
" s = 0\n" ++
" s + 2\n"
, "-- if test 2\n" ++
"if\n" ++
" s = 0\n" ++
" s > 0\n" ++
"then\n" ++
" s: Int\n" ++
" s = (0: Int)\n" ++
" s + 1\n" ++
"else\n" ++
" s = 0\n" ++
" s + 2\n"
, "-- if test 3\n" ++
"if\n" ++
" s = 0\n" ++
" s > 0\n" ++
"then\n" ++
" s: Int\n" ++
" s = (0 : Int)\n" ++
" s + 1\n" ++
"else\n" ++
" s = 0\n" ++
" s + 2\n"
, "x && y"
, "x || y"
, [r|--let r1
let r1 : Nat
r1 = match Optional.Some 3 with
x -> 1
42 |]
, [r|let
increment = (Nat.+) 1
(|>) : forall a . a -> (a -> b) -> b
a |> f = f a
Stream.fromInt -3
|> Stream.take 10
|> Stream.foldLeft 0 increment
|]
]
test2 :: Test ()
test2 = scope "fiddle" . tests $ unitTests
test :: Test ()
test = test1 <|> test2
unitTests :: [Test ()]
unitTests =
[ t w "hi"
, t s "foo.+"
, t (w <|> s) "foo.+"
, t (w *> w) "foo bar"
, t (P.try (w *> w) <|> (w *> s)) "foo +"
, t TP.term "x -> x"
, t (TP.lam TP.term) "x y z -> 1 + 1"
, t (sepBy s w) ""
, t (sepBy s w) "uno"
, t (sepBy s w) "uno + dos"
, t (sepBy s w) "uno + dos * tres"
, t (openBlockWith "(" *> sepBy s w <* closeBlock) "(uno + dos + tres)"
, t TP.term "( 0 )"
]
where
-- type TermP v = P v (AnnotatedTerm v Ann)
t :: P Symbol a -> String -> Test ()
t = parseWith
w = wordyDefinitionName
s = symbolyDefinitionName
parses :: String -> Test ()
parses = parseWith TP.term
parseWith :: P Symbol a -> String -> Test ()
parseWith p s = scope (join . take 1 $ lines s) $
case Ps.parse @ Symbol p s Common.parsingEnv of
Left e -> do
note $ renderParseErrorAsANSI 60 s e
crash $ renderParseErrorAsANSI 60 s e
Right _ -> ok
|
unisonweb/platform
|
parser-typechecker/tests/Unison/Test/TermParser.hs
|
mit
| 4,539 | 0 | 16 | 1,643 | 1,088 | 604 | 484 | -1 | -1 |
module ProjectEuler.Problem99
( problem
) where
import Data.List
import Data.Ord
import qualified Data.Text as T
import ProjectEuler.GetData
problem :: Problem
problem = pureProblemWithData "p099_base_exp.txt" 99 Solved compute
compute :: T.Text -> Int
compute = fst . maximumBy (comparing snd) . getNums
getNums :: T.Text -> [(Int,Double)]
getNums = zipWith go [1..] . lines . T.unpack
where
go lineN rawLine = (lineN, v)
where
(a,b) = read $ "(" ++ rawLine ++ ")" :: (Double,Double)
v = b * log a
|
Javran/Project-Euler
|
src/ProjectEuler/Problem99.hs
|
mit
| 539 | 0 | 11 | 120 | 194 | 109 | 85 | 15 | 1 |
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable, FlexibleContexts, FlexibleInstances, GeneralizedNewtypeDeriving, ImplicitParams, OverloadedStrings, TemplateHaskell, TypeSynonymInstances #-}
module Formura.MPICxx.Language where
import Control.Lens
import Data.Foldable(toList)
import Data.List (intersperse)
import Data.Monoid
import Data.String
import Data.String.ToString
import qualified Data.Text as T
import Prelude hiding (show, Word, length)
import qualified Prelude
import System.FilePath.Lens
import Formura.CommandLineOption
data TargetLanguage = MPICxx | MPIFortran deriving(Eq,Ord,Show,Read)
targetLanguage :: WithCommandLineOption => TargetLanguage
targetLanguage = case ?commandLineOption ^. outputFilename . extension of
('.':'f':_) -> MPIFortran
_ -> MPICxx
data WordF a = Raw T.Text
| Hole a
| PotentialSubroutine (SrcF a)
deriving (Eq, Ord, Show, Read, Functor, Foldable, Traversable)
data TypedHole = Typed { _holeType :: T.Text, _holeExpr :: T.Text}
deriving (Eq, Ord, Show, Read)
type Word = WordF (TypedHole)
newtype SrcF a = Src [WordF a]
deriving (Eq, Ord, Show, Read, Functor, Foldable, Traversable)
type Src = SrcF TypedHole
makeLenses ''TypedHole
-- instance Ord Src where
-- compare = let key :: Src -> ([T.Text], [T.Text], T.Text)
-- key (Src xs) = (xs >>= vals , xs >>= typs, toText (Src xs))
--
-- vals :: Word -> [T.Text]
-- vals (Raw x) = [x]
-- vals (Hole _ x) = []
-- vals (PotentialSubroutine (Src xs)) = xs >>= vals
--
-- typs :: Word -> [T.Text]
-- typs (Raw _) = []
-- typs (Hole t _) = [t]
-- typs (PotentialSubroutine (Src xs)) = xs >>= typs
--
-- in compare `on` key
--
instance Monoid Src where
mempty = Src []
mappend (Src xs) (Src ys) = let -- it
go [] = [] -- let it
go [x] = [x] -- I am one element list
go (Raw x: Raw y: z) = go ((Raw $ x<>y) : z)
go (x:y) = x: go y
_ = error "never bothered me anyway"
in Src $ go $ xs ++ ys
instance IsString Src where
fromString str = Src [Raw $ T.pack str]
instance ToString Word where
toString x = toString $ toText x
instance ToString Src where
toString (Src xs) = concat $ map toString xs
class ToText a where
toText :: a -> T.Text
instance ToText Word where
toText (Raw x) = x
toText (Hole (Typed _ x)) = x
toText (PotentialSubroutine x) = toText x
instance ToText Src where
toText (Src xs) = mconcat $ map toText xs
length :: Src -> Int
length = T.length . toText
raw :: T.Text -> Src
raw t = Src [Raw t]
show :: Show a => a -> Src
show = fromString . Prelude.show
parameter :: Show a => T.Text -> a -> Src
parameter t x = Src [Hole (Typed t (fromString $ Prelude.show x))]
typedHole :: T.Text -> T.Text -> Src
typedHole t x = Src [Hole (Typed t x)]
parens :: Src -> Src
parens x = "(" <> x <> ")"
brackets :: Src -> Src
brackets x = "[" <> x <> "]"
braces :: Src -> Src
braces x = "{" <> x <> "}"
unwords :: [Src] -> Src
unwords = mconcat . intersperse " "
unlines :: [Src] -> Src
unlines = mconcat . map (<> "\n")
intercalate :: Src -> [Src] -> Src
intercalate x ys = mconcat $ intersperse x ys
parensTuple :: Foldable t => t Src -> Src
parensTuple = parens . intercalate ", " . toList
replace :: Src -> Src -> Src -> Src
replace src dest (Src xs) = Src $ map go xs
where
repT = T.replace (toText src) (toText dest)
go (Raw x) = Raw (repT x)
go x@(Hole _) = x
go (PotentialSubroutine s) = PotentialSubroutine $ replace src dest s
-- | Wrap a C source as a potential subroutine
potentialSubroutine :: Src -> Src
potentialSubroutine s = Src [PotentialSubroutine s]
template :: Src -> Src
template (Src xs) = Src $ map go xs
where
go x@(Raw _) = x
go (Hole (Typed t _)) = Hole (Typed t "")
go (PotentialSubroutine s) = PotentialSubroutine $ template s
-- | Does the two code can be made into single subroutine?
isCopipe :: Src -> Src -> Bool
isCopipe x y = template x == template y
pretty :: Src -> T.Text
pretty (Src xs) = T.concat $ map go xs
where
go :: Word -> T.Text
go (Raw x) = x
go (Hole (Typed _ x)) = "<<" <> x <> ">>"
go (PotentialSubroutine s) = pretty s
|
nushio3/formura
|
src/Formura/MPICxx/Language.hs
|
mit
| 4,439 | 0 | 15 | 1,198 | 1,509 | 790 | 719 | -1 | -1 |
module GHCJS.DOM.MallocStatistics (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/MallocStatistics.hs
|
mit
| 46 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Barch.Adaptors where
import Prelude
import Yesod
import Control.Applicative
import Data.Time
import Data.Time.Calendar (fromGregorian)
import qualified Text.BibTeX.Entry as Bib
import qualified Data.Map.Lazy as M
import Data.Text as T
import Text.Parsec
import Yesod.Markdown
import Model
import qualified Barch.QueryParser as Q
-- | Update the update time of a Reference to now
touchReference::MonadIO m=>Reference->m Reference
touchReference ref = do
time <- liftIO getCurrentTime
return $ ref {referenceLastModified = time}
-- | Update the update time of a Maybe Reference to now
touchMaybeReference::MonadIO m=>Maybe Reference->m (Maybe Reference)
touchMaybeReference mref = do
case mref of
Nothing -> return Nothing
Just ref' -> do
ref <- touchReference ref'
return $ Just ref
entry2Reference::[Text]->Markdown->Bib.T->Reference
entry2Reference tags notes entry = (entry2Reference' tags notes entry) $ UTCTime (fromGregorian 0 0 0) (secondsToDiffTime 0)
entry2Reference'::[Text]->Markdown->Bib.T->(UTCTime->Reference)
entry2Reference' tags notes (Bib.Cons typ ident fields) =
Reference (pack typ) (pack ident) fields' (M.keys fields') tags notes
where
fields' = (M.map pack . M.mapKeys (T.toLower . pack)) $ M.fromList fields
reference2Entry::Reference->Bib.T
reference2Entry (Reference typ ident fields _ _ _ _) =
Bib.Cons (unpack typ) (unpack ident) fields'
where
fields' = M.toList $ (M.map unpack . M.mapKeys unpack) fields
text2Tags::Text->[Text]
text2Tags t = Q.unTag <$> (either (\_->[]) id $ parse Q.tags "" t)
-- | Wrap a tag in quotation marks if it contains any spaces
wrapTag::Text->Text
wrapTag x
| T.any (==' ') x = T.snoc ('"' `T.cons` x) '"'
| otherwise = x
tags2Text::[Text]->Text
tags2Text xs = T.intercalate " " (wrapTag <$> xs)
parseBibUrl::(Text, Text)->Either (Text, Text) (Text, Html)
parseBibUrl (key, val) = case (T.toLower key) of
"url" -> Right $ (key, [shamlet|<a href="#{val}">#{val}</a>|])
-- "eprint" -> Right $ (key, [shamlet|<a href="#{val}">#{val}</a>|])
"doi" -> Right $ (key, [shamlet|<a href="https://doi.org/#{val}">#{val}</a>|])
_ -> Left (key, val)
|
klarh/barch
|
Barch/Adaptors.hs
|
mit
| 2,237 | 0 | 13 | 372 | 770 | 411 | 359 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Y2017.M11.D29.Exercise where
{--
So, now that we've added and deleted recommended articles to our recommended
articles list, we need to have our grande poobah user select the ones to be
published, save those off somewhere, and then, well, publish them. That is to
say: return, at a later time, the list of articles to be published alongside
the source article.
Let's do that today.
--}
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
-- below imports available via 1HaskellADay git repository
import Store.SQL.Connection
import Y2017.M11.D21.Exercise -- for Brief-type
import Y2017.M11.D24.Exercise -- for loading Briefs from the database
-- (low-key: anybody else say 'brieves'? 'brèves'?) (the French in me)
-- So we need a publish type that includes the source article id, the
-- recommendation id and a ranking: 1,2,3,4 ...
data Publish = Pub { srcIdx, recIdx, rank :: Integer }
deriving (Eq, Show)
instance ToRow Publish where
toRow pub = undefined
instance FromRow Publish where
fromRow = undefined
-- today, we're just going to upload this publishing info; tomorrow we'll look
-- at extracting article information for articles to be published
insertPubsStmt :: Query
insertPubsStmt =
[sql|INSERT INTO recommendation_publish (source_article_id,recommended_article_id,rank)
VALUES (?,?,?)|]
-- we want to make sure we delete any old crud hanging out in the database:
deleteOldPubsStmt :: Query
deleteOldPubsStmt =
[sql|DELETE FROM recommendation_publish WHERE source_article_id=?|]
insertPub :: Connection -> Integer -> [Integer] -> IO ()
insertPub conn srcId recIds = undefined
-- n.b.: the rank is determined by order, so:
-- recId1 rank is 1, recId2 rank is 2, ...
{-- BONUS -----------------------------------------------------------------
write an app that takes srcId, recIds and saves that info to the database
--}
main' :: [String] -> IO ()
main' artIds = undefined
|
geophf/1HaskellADay
|
exercises/HAD/Y2017/M11/D29/Exercise.hs
|
mit
| 2,133 | 0 | 9 | 338 | 225 | 144 | 81 | 26 | 1 |
-- | Handler for the 'add' command.
module Commands.Add.Handler
( TodoTask
, AddItems
, DayOfWeek
, handleAddCommand
) where
import Types
import Util
import Parsing
import Printing
import TodoLenses
import Commands.Common
import Options.Applicative
import Data.Time hiding (parseTime)
import Data.Time.Calendar.OrdinalDate
import Control.Exception
-- | Handler for the 'add' command.
handleAddCommand :: Command -> IO ()
handleAddCommand (Add task cat pri addItems dowM dateM timeM) = do
items <- if addItems
then putStrLn "Type in the items one by one, then press Enter twice when done:" >> askItems 'a'
else return []
newTask <- constructTask (task, items, cat, dowM, dateM, timeM, pri)
oldList <- parseWith parseTodoList <$> readFile "todo/list.txt"
case oldList of
Right list -> do
newList <- addTask list newTask cat
updateTodoList newList
Left e -> throwIO (ParseException e)
-- Ask for the list of items belonging to the task.
askItems :: Char -> IO [Item]
askItems c = do
item <- prompt (" " ++ [c] ++ ") ")
if item == "" then return []
else do
rest <- askItems (succ c)
return $ Item item False : rest
-- Construct a task from its parameters.
constructTask :: (TodoTask, [Item], Category, Maybe DayOfWeek, Maybe Day, Maybe TimeOfDay, Priority) -> IO Task
constructTask (task, items, cat, dowM, dateM, timeM, pri) = do
deadline <- case dowM of
Just dow -> dayOfWeekToDeadline cat dow timeM -- Day of week is given
Nothing -> case dateM of
Just date -> return $ makeAbsDeadline date timeM -- Date is given
Nothing -> case cat of
RelTime t -> return $ Rel t -- Category is given
_ -> return None
return Task {_desc = task, _items = items, _deadline = deadline, _priority = pri, _done = False}
-- Creates a deadline from the category, day of week, time of day and current date.
dayOfWeekToDeadline :: Category -> DayOfWeek -> Maybe TimeOfDay -> IO Deadline
dayOfWeekToDeadline (Custom _) _ _ = throwIO AmbiguousDay
dayOfWeekToDeadline (RelTime r) dow timeM = do
today <- utctDay <$> getCurrentTime
let dayE = offsetDate r dow today -- Offset the date w.r.t. the day of week.
case dayE of
Right day -> return $ makeAbsDeadline day timeM
Left err -> throwIO err
-- Creates an absoluted deadline from a day and a potential time.
makeAbsDeadline :: Day -> Maybe TimeOfDay -> Deadline
makeAbsDeadline day (Just time) = Abs (Time $ UTCTime day (timeOfDayToTime time))
makeAbsDeadline day Nothing = Abs (Date day)
-- Offset the date based on the relative time, day of week and today's date.
offsetDate :: RelativeTime -> DayOfWeek -> Day -> Either DateTimeException Day
offsetDate Today _ today = Right today
offsetDate Tomorrow _ today = Right (addDays 1 today)
offsetDate ThisMonth dow today = Left AmbiguousDay -- "Tuesday this month" is meaningless
offsetDate NextMonth dow today = Left AmbiguousDay
offsetDate w dow today = case w of
ThisWeek -> if twd < wd -- Need to check whether day of week is later than today
then Right (fromMondayStartWeek thisYear tw wd)
else Left PastDate
NextWeek -> Right $ fromMondayStartWeek thisYear (tw + 1) wd
where (tw, twd) = mondayStartWeek today
wd = fromEnum dow + 1
(thisYear,_,_) = toGregorian today
|
DimaSamoz/thodo
|
src/Commands/Add/Handler.hs
|
mit
| 3,500 | 0 | 18 | 882 | 964 | 493 | 471 | 68 | 4 |
{-# OPTIONS_HADDOCK hide, prune #-}
module Handler.Mooc.Scenario
( getScenarioR
, getScenarioProblemR
, getScenarioId
, getScenarioLink
) where
import Import
import Control.Monad.Trans.Maybe
getScenarioId :: ScenarioProblemId -> Handler (Maybe ScenarioId)
getScenarioId scpId = runMaybeT $ do
userId <- MaybeT maybeAuthId
fmap entityKey . MaybeT . runDB $ selectSource
[ ScenarioAuthorId ==. userId
, ScenarioTaskId ==. scpId
]
[ Desc ScenarioLastUpdate
] $$ await
getScenarioLink :: Handler (Maybe (Route App, Double))
getScenarioLink = runMaybeT $ do
msc_id <- lift $ getsSafeSession userSessionScenarioId
case msc_id of
Just sc_id -> do
scale <- getScScale sc_id
return (ScenarioR sc_id, scale)
Nothing -> do
userId <- MaybeT maybeAuthId
mscp_id <- lift $ getsSafeSession userSessionCustomExerciseId
mScenarioId <- fmap (fmap entityKey) . lift . runDB $ selectSource
(case mscp_id of
Just i -> [ ScenarioAuthorId ==. userId
, ScenarioTaskId ==. i
]
Nothing -> [ScenarioAuthorId ==. userId]
)
[ Desc ScenarioLastUpdate
] $$ await
case mScenarioId of
Just scId -> do
scale <- getScScale scId
return (ScenarioR scId, scale)
Nothing -> do
scp_id <- MaybeT $ return mscp_id
scale <- fmap scenarioProblemScale . MaybeT . runDB $ get scp_id
return (ScenarioProblemR scp_id, scale)
where
getScScale scId = do
sc <- MaybeT . runDB $ get scId
scp <- MaybeT . runDB $ get (scenarioTaskId sc)
return $ scenarioProblemScale scp
getScenarioR :: ScenarioId -> Handler Text
getScenarioR scId = maybe "{}" (decodeUtf8 . scenarioGeometry) <$> runDB (get scId)
getScenarioProblemR :: ScenarioProblemId -> Handler Text
getScenarioProblemR scpId = maybe "{}" (decodeUtf8 . scenarioProblemGeometry) <$> runDB (get scpId)
|
mb21/qua-kit
|
apps/hs/qua-server/src/Handler/Mooc/Scenario.hs
|
mit
| 2,209 | 0 | 22 | 753 | 575 | 278 | 297 | 49 | 4 |
module Test.ReservedWords
( reservedWordsTests,
)
where
import qualified Control.Monad.IO.Class as MIO
import qualified Data.Pool as Pool
import qualified Data.String as String
import qualified Hedgehog as HH
import qualified Orville.PostgreSQL as Orville
import qualified Orville.PostgreSQL.Connection as Conn
import qualified Test.Entities.User as User
import qualified Test.Property as Property
import qualified Test.TestTable as TestTable
reservedWordsTests :: Pool.Pool Conn.Connection -> Property.Group
reservedWordsTests pool =
Property.group "ReservedWords" $
[
( String.fromString "Can insert and select an entity with reserved words in its schema"
, Property.singletonProperty $ do
originalUser <- HH.forAll User.generate
usersFromDB <-
MIO.liftIO $ do
Pool.withResource pool $ \connection ->
TestTable.dropAndRecreateTableDef connection User.table
Orville.runOrville pool $ do
Orville.insertEntity User.table originalUser
Orville.findEntitiesBy User.table mempty
usersFromDB HH.=== [originalUser]
)
]
|
flipstone/orville
|
orville-postgresql-libpq/test/Test/ReservedWords.hs
|
mit
| 1,169 | 0 | 19 | 271 | 242 | 138 | 104 | 26 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Text.Greek.Mounce.NounFirstDeclension where
import Text.Greek.Grammar
import Text.Greek.Mounce.Morphology
import Text.Greek.Mounce.Quote
firstDeclensionNouns :: [Cited NounCategory]
firstDeclensionNouns =
[ mounce §§ ["n-1a"] $
[nounCategory|
Feminine nouns with stems ending in εα, ια, or ρα and a genitive in ας
sg: pl:
nom: α αι
gen: ας ων
dat: ᾳ αις
acc: αν ας
voc: α αι
lemmas:
Ἅννα Εὕα Ἱεροσόλυμα Ἰωάνα Ἰωάννα Μάρθα Νύμφα Ῥεβέκκα στοά
ἀγαθοποιΐα ἀγγελία ἄγκυρα ἁγνεία ἄγνοια
ἀγνωσία ἀγορά ἄγρα ἀγρυπνία ἀγωνία
ἀδιαφθορία ἀδικία ἀηδία ἀθανασία ἀιματεκχυσία
αἰσχρολογία αἰτία αἰχμαλωσία ἀκαθαρσία ἀκαταστασία
ἀκρασία ἀκρίβεια ἀκροβυστία ἀλαζονεία ἀλεκτοροφωνία
ἀλήθεια ἀμαρτία ἀναίδεια ἀναλογία ἀνεγκλησία
ἀνθρακιά Ἅννα ἄνοια ἀνομία ἀντιλογία
ἀντιμισθία Ἀντιόχεια ἀπείθεια ἀπιστία ἀποκαραδοκία
Ἀπολλωνία ἀπολογία ἀπορία ἀποστασία ἀποτομία
ἀπουσία Ἀπφία ἀπώλεια ἀρά Ἀραβία
ἀρεσκεία Ἁριμαθαία ἀσέβεια ἀσέλγεια ἀσθένεια
Ἀσία ἀσιτία ἀσφάλεια ἀσωτία ἀτιμία
Ἀττάλεια αὐτάρκεια ἀφειδία ἀφθαρσία ἀφθονία
ἀφθορία Ἀχαΐα βασιλεία Βέροια Βηθαβαρά
Βηθανία βία Βιθυνία βλασφημία βοήθεια
Γαλατία Γαλιλαία Γαλλία γενεά γενεαλογία
γερουσία Γόμορρα γυμνασία γωνία Δαλματία
δειλία δεισιδαιμονία διακονία διάνοια διασπορά
διαφθορά διγαμία διδασκαλία διερμηνεία διετία
δικαιοκρισία διχοστασία δοκιμασία δουλεία δυσεντερία
δυσφημία δωρεά δωροφορία ἐγκράτεια ἐθελοθρησκία
εἰδέα εἰδωλολατρία εἰλικρίνεια ἐκκλησία ἐκτένεια
ἐλαία ἐλαφρία ἐλευθερία ἐμπορία ἐνέδρα
ἐνέργεια ἔννοια ἐξουσία ἐπαγγελία ἐπαρχεία
ἐπιείκεια ἐπιθυμία ἐπικουρία ἐπιμέλεια ἐπίνοια
ἐπιποθία ἐπιτιμία ἐπιφάνεια ἐπιχορηγία ἐργασία
ἐρημία ἐριθεία ἑρμηνεία ἑσπέρα ἑτοιμασία
Εὕα εὐγλωττία εὐγλωττία εὐδία εὐδοκία
εὐεργεσία εὐκαιρία εὐλάβεια εὐλογία εὔνοια
Εὐοδία εὐοχία εὐποιΐα εὐπορία εὐπρέπεια
εὐσέβεια εὐτραπελία εὐφημία εὐχαριστία εὐωδία
εὐωχία ἐφημερία ἔχθρα ζευκτηρία ζημία
ἡγεμονία ἡλικία ἡμέρα ἡσυχία θεά
θεοσέβεια θεραπεία Θεσσαλία θεωρία θήρα
θρησκεία θύρα θυσία ἰδέα Ἰδουμαία
ἱερατεία Ἱεροσόλυμα ἱκετηρία Ἰουδαία Ἰουλία
Ἰταλία Ἰωάνα Ἰωάννα καθέδρα Καισάρεια
κακία κακοήθεια κακοπάθεια κακοπαθία καλοκαγαθία
Καππαδοκία καραδοκία καρδία καταλαλιά κατάρα
κατηγορία κατήφεια κατοικία Κεγχρεαί κειρία
κενοδοξία κενοφωνία κεραία κιθάρα Κιλικία
Κλαυδία κληρονομία κλισία κοιλία κοινωνία
κολακεία κολυμβήθρα κολωνία κοπρία κουστωδία
κυβεία κυρία λαλιά Λαοδίκεια Λασαία
Λασέα λατρεία λειτουργία Λέκτρα λέπρα
λίτρα λογεία λογομαχία λοιδορία Λυδία
Λυκαονία Λυκία Λύστρα λυχνία μαγεία
μαθήτρια Μακεδονία μακροθυμία μαλακία μανία
Μάρθα Μαρία μαρτυρία ματαιολογία μεθοδεία
μεσημβρία Μεσοποταμία μετάνοια μετοικεσία μήτρα
μισθαποδοσία μνεία μοιχεία Μυσία μωρία
μωρολογία νεομηνία νηστεία νομοθεσία νοσσιά
νουθεσία νουμηνία Νύμφα ξενία ὁδοιπορία
οἰκετεία οἰκία οἰκοδομία οἰκονομία οἰνοφλυγία
ὀλιγοπιστία ὁλοκληρία ὁμιλία ὁμολογία ὀπτασία
ὀπώρα ὀργυιά ὁρκωμοσία ὁροθεσία οὐρά
οὐσία ὀφθαλμοδουλία ὀψία παιδεία παλιγγενεσία
Παμφυλία πανοπλία πανουργία παραγγελία παραμυθία
παρανομία παραφρονία παραχειμασία παρηγορία παρθενία
παροικία παροιμία παρουσία παρρησία πατριά
πεῖρα πενθερά Πέραια περικεφαλαία περισσεία
περιστερά πέτρα πήρα πιθανολογία πικρία
Πισιδία πλατεῖα πλεονεξία πλευρά πληροφορία
ποία πολιτεία πολυλογία πολυπλήθεια πονηρία
πορεία πορία πορνεία πορφύρα πραγματεία
πρασιά πραϋπάθεια πρεσβεία προθεσμία προθυμία
πρόνοια προσδοκία προσφορά προσωπολημψία προσωποληψία
προφητεία πρωΐα πρωτοκαθεδρία πρωτοκλισία πτωχεία
πυρά ῥᾳδιουργία Ῥεβέκκα ῥομφαία ῥυπαρία
Σαμάρεια Σαμαρία Σάρρα σειρά Σελεύκεια
σκηνοπηγία σκιά σκληροκαρδία σκοτία σοφία
Σπανία σπορά στεῖρα στενοχωρία στοά
στρατεία στρατιά συγγένεια συγκυρία συκομορέα
συμποσία συμφωνία συνήθεια συνοδία συνορία
συντέλεια συντυχία συνωμοσία Σύρα Ευρία
σωτηρία ταλαιπωρία τεκνογονία τιμωρία τριετία
τροχιά τρυμαλία ὑδρία υἱοθεσία ὑπερηφανία
ὑπόνοια φαντασία φαρμακεία φθορά Φιλαδέλφεια
φιλαδελφία φιλανθρωπία φιλαργυρία φιλία φιλονεικία
φιλοξενία φιλοσοφία Φρυγία φυτεία χαρά
χήρα χρεία χρηστολογία χώρα ψευδομαρτυρία
ὥρα ὠφέλεια
|]
, mounce §§ ["n-1b"] $
[nounCategory|
Feminine nouns with stems ending in η and a genitive in ης
sg: pl:
nom: η αι
gen: ης ων
dat: ῃ αις
acc: ην ας
voc: η αι
lemmas:
Ἀβιληνή ἀγαθωσύνη ἀγάπη ἀγέλη ἁγιωσύνη
ἀγκάλη ἀγωγή ἀδελφή αἰσχύνη ἀκοήἀλόη
ἀμοιβή ἀναβολή ἀνάγκη ἀναστροφή ἀνατολή
ἀνοχή ἀξίνη ἀπαρχή ἀπάτη ἀπειλή
ἀποβολή ἀπογραφή ἀποδοχή ἀποθήκη ἀποστολή
ἀρετή ἁρπαγή ἀρχή ἀστραπή ἀσχημοσύνη
αὐγή αὐλή ἁφή ἀφορμή ἀφροσύνη
βελόνη Βερνίκη βοή βολή βοτάνη
βουλή βροντή βροχή γαλήνη γενετή
γνώμη γραφή δαπάνη Δέρβη δέσμη
διαθήκη διαπαρατριβή διαστολή διαταγή διατροφή
διδαχή δικαιοσύνη δίκη δοκιμή δούλη
δοχή ραχμή δυσμή ἐγκοπή εἰρήνη
ἐκβολή ἐκδοχή ἐκκοπή ἐκλογή ἐλεημοσύνη
ἐμπαιγμονή ἐμπλοκή ἐντολή ἐντροπή ἐξοχή
ἑορτή ἐπεισαγωγή ἐπιβουλή ἐπιγραφή ἐπιλησμονή
ἐπισκοπή ἐπιστήμη ἐπιστολή ἐπιστροφή ἐπισυναγωγή
ἐπιταγή ἐπιτροπή Εὐνίκη εὐσχημοσύνη εὐφροσύνη
εὐχή ζύμη ζωή ζώνη ἡδονή
θέρμη Θεσσαλονίκη θήκη ἱερωσύνη Ἰόππη
καλάμη Κανδάκη καταβολή καταδίκη καταλλαγή
καταστολή καταστροφή κατατομή κεφαλή Κλαύδη
κλίνη κλοπή κοίτη Κολασσαί Κολοσσαί
κόμη κοπή κραιπάλη κραυγή Κρήτη
κριθή κρύπτη Κυρήνη κώμη λήθη
Λιβύη λίμνη λόγχη λύπη Μαγδαληνή
μάμμη μάχη μεγαλωσύνη μέθη Μελίτη
μετοχή μηλωτή Μιτυλήνη μνήμη μομφή
μονή μορφή νεφέλη νίκη νομή
νύμφη ὀδύνη ὀθόνη οἰκοδομή οἰκουμένη
ὁμίχλη ὀπή ὀργή ὁρμή ὁσμή
ὀφειλή παιδίσκη πάλη παραβολή παραδιατριβή
παραθήκη παρακαταθήκη παρακοή παραλλαγή παρασκευή
παραφροσύνη παρεμβολή πέδη πεισμονή πεντηκοστή
Πέργη περιοχή περιτομή πηγή πλάνη
πληγή πλησμονή πλοκή πνοή ποίμνη
πόρνη προκοπή προσαγωγή προσευχή προσκοπή
πυγμή πύλη ῥέδη ῥιπή Ῥόδη
ῥοπή ῥύμη Ῥώμη σαγήνη Σαλμώνη
Σαλώμη Σαμοθρᾴκη σαργάνη σελήνη σιγή
σκάφη σκευή σκηνή σπουδή σταφυλή
στέγη στιγμή στολή συγγνώμη συναγωγή
συνδρομή συνοχή Συντύχη συστροφή σφαγή
σχολή σωφροσύνη ταβέρναι ταπεινοφροσύνη ταραχή
ταφή τελευτή τέχνη τιμή τροπή
τροφή τρυφή ὕλη ὑπακοή ὑπερβολή
ὑπεροχή ὑπομονή ὑποστολή ὑποταγή φάτνη
φήμη φιάλη φίλη Φοίβη Φοινίκη
φυγή φυλακή φυλή φωνή χλόη
χολή ψυχή ᾠδή
|]
, mounce §§ ["n-1c"] $
[nounCategory|
Feminine nouns with stems ending in α (where the preceding letter is not ε, ι, or ρ) and a genitive in ης
sg: pl:
nom: α αι
gen: ης ων
dat: ῃ αις
acc: αν ας
voc: α αι
lemmas:
Ἀθῆναι ἄκανθα βασίλισσα γάγγραινα Γάζα
γάζα γέεννα γλῶσσα δόξα Δρούσιλλα
ἐπιοῦσα ἔχιδνα θάλασσα Θέκλα θέρμα
θύελλα μάχαιρα μεμβράνα μέριμνα πλήμμυρα
Πρίσκα Πρίσκιλλα πρύμνα πρῷρα πτέρνα
ῥίζα Σάπφιρα Σμύρνα σμύρνα Σουσάννα
σπεῖρα Συράκουσαι Συροφοινίκισσα τράπεζα Τρύφαινα
Τρυφῶσα Φοινίκισσα χάλαζα
|]
, mounce §§ ["n-1d"] $
[nounCategory|
Masculine nouns with stems ending in α(ς) and a genitive in ου
sg: pl:
nom: ας αι
gen: ου ων
dat: ᾳ αις
acc: αν ας
voc: α αι
lemmas:
Ἀδρίας Αἰνέας Ἀμασίας Ἁνανίας Ἀνδρέας
Βαραχίας Ἑζεκίας Ζαχαρίας Ἠλίας Ἠσαΐας
Ἰερεμίας Ἰεχονίας Ἰωνάθας Ἰωσίας Λυσανίας
Λυσίας Μαθθίας Ματθίας Ματταθίας Μεσσίας
μητραλῴας νεανίας Ὀζίας Οὐρίας Οχοζίας
πατραλῴας πατρολῴας Σιμαίας
βορρᾶς
|] -- added βορρᾶς following the footnote on n-1h
, mounce §§ ["n-1e"] $
[nounCategory|
Masculine nouns with stems ending in α(ς) and a genitive in α
sg: pl:
nom: ας *
gen: α *
dat: ᾳ *
acc: αν *
voc: α *
lemmas:
Ἀγρίππας Ἅννας Ἀντιπᾶς Ἁρέτας Ἀρτεμᾶς
Βαραββᾶς Βαριωνᾶς Βαρναβᾶς βαρσαββᾶς βαρσαββᾶς
βορρᾶς Δημᾶς Ἐλύμας Ἐπαφρᾶς Ἑρμᾶς Θευδᾶς
Θωμᾶς Ἰούδας Ἰουνιᾶς Ἰωνᾶς Καϊάφας
Κηφᾶς Κλεοπᾶς Κλωπᾶς κορβανᾶς Λουκᾶς
μαμωνᾶς Νυμφᾶς Ὀλυμπᾶς Παρμενᾶς Πατροβᾶς
Σατανᾶς Σίλας Σκευᾶς Στεφανᾶς χουζᾶς
|]
, mounce §§ ["n-1f"] $
[nounCategory|
Masculine nouns with stems ending in η(ς) and a genitive in ου
sg: pl:
nom: ης αι
gen: ου ων
dat: ῃ αις
acc: ην ας
voc: α αι
lemmas:
ᾅδης ἀδικοκρίτης ἀκροατής ἀνδραποδιστής ἀποστάτης
Ἀρεοπαγίτης ἀρσενοκοίτης ἀρχιλῃστής ἀρχιτελώνης Ἀσιάρχης
αὐλητής αὐτόπτης βαπτιστής βασανιστής βιαστής
βουλευτής Γαλάτης γνώστης γογγυστής δανειστής
δανιστής δεσμώτης δεσπότης διερμηνευτής δικαστής
διώκτης δότης δυνάστης ἐθνάρχης εἰδωλολάτρης
ἑκατοντάρχης Ἐλαμίτης Ἑλληνιστής ἐμπαίκτης ἐξορκιστής
ἐπενδύτης ἐπιθυμητής ἐπιστάτης ἐπόπτης ἐργάτης
ἑρμηνευτής εὐαγγελιστής εὐεργέτης Εὐφράτης ἐφευρετής
ζηλωτής Ἡρῴδης θεριστής Ἰαμβρῆς Ἰάννης
ἰδιώτης Ἱεροσολυμίτης Ἰορδάνης Ἰσκαριώτης Ἰσραηλίτης
Ἰωάννης καθηγητής Κανανίτης καρδιογνώστης καταφρονητής
κερματιστής κλέπτης κοδράντης κολλυβιστής κριτής
κτίστης κυβερνήτης Λευίτης λῃστής λυτρωτής
μαθητής μαργαρίτης μεριστής μεσίτης μετρητής
μιμητής μισθαποδότης ναύτης Νικολαΐτης Νινευίτης
νομοθέτης ξέστης οἰκέτης οἰκοδεσπότης οἰνοπότης
ὀλεθρευτής ὀλοθρευτής ὀφειλέτης παιδευτής παραβάτης
πατριάρχης πλανήτης πλεονέκτης πλήκτης ποιητής
πολιτάρχης πολίτης πρεσβύτης προδότης προσαίτης
προσκυνητής προσωπολήμπτης προσωπολήπτης προφήτης πρωτοστάτης
σαλπιστής Σαμαρίτης Σκύθης στασιαστής στρατιώτης
στρατοπεδάρχης συζητητής συμμαθητής συμμιμητής συμπολίτης
συμφυλέτης συνηλικιώτης συντεχνίτης συστασιαστής τελειωτής
τελώνης τετράρχης τετραάρχης τεχνίτης τιμιότης
τολμητής τραπεζίτης ὑβριστής ὑπηρέτης ὑποκριτής
φαιλόνης φελόνης φρεναπάτης χάρτης χρεοφειλέτης
χρεωφειλέτης ψευδοπροφήτης ψεύστης ψιθυριστής
|]
, mounce §§ ["n-1g"] $
[nounCategory|
Masculine nouns with stems ending in η(ς) and a genitive in η
sg: pl:
nom: ης *
gen: η *
dat: ῃ *
acc: η *
voc: η *
lemmas:
Μανασσῆς Ἰωσῆς
|]
, mounce §§ ["n-1h(a)"] $
[nounCategory|
First declension contract nouns
sg: pl:
nom: α αι
gen: ας ων
dat: ᾳ αις
acc: αν ας
voc: α αι
lemmas:
μνᾶ
|]
, mounce §§ ["n-1h(b)"] $
[nounCategory|
First declension contract nouns
sg: pl:
nom: η αι
gen: ης ων
dat: ῃ αις
acc: ην ας
voc: η αι
lemmas:
συκῆ γῆ
|]
, mounce §§ ["n-1h(c)"] $
[nounCategory|
First declension contract nouns
sg: pl:
nom: ης αι
gen: ου ων
dat: ῃ αις
acc: ην ας
voc: η αι
lemmas:
Απελλῆς Ἑρμῆς
|] -- removed βορρᾶς from here and put in n-1d according to his footnote
]
|
scott-fleischman/greek-grammar
|
haskell/greek-grammar/src/Text/Greek/Mounce/NounFirstDeclension.hs
|
mit
| 19,093 | 0 | 8 | 3,445 | 228 | 153 | 75 | 28 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.