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
-------------------------------------------------------------------------------- -- | -- Module : Language.Pylon.Core.Check -- Copyright : (c) 2014 Lukas Heidemann -- License : BSD -- Maintainer : lukasheidemann@gmail.com -- Stability : experimental -- Portability : ghc -- -- Type checker for Pylon Core. -- -- TODO: check for over-specialization, as in the Idris code: -- > unsafe : (a : Type) -> (x : a) -> a -- > unsafe Bool x = False -- Currently this type checks unsafe code! -------------------------------------------------------------------------------- {-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-} {-# LANGUAGE PatternSynonyms #-} module Language.Pylon.Core.Check ( TypeError , Locals , checkExp , checkBind ) where -------------------------------------------------------------------------------- import Language.Pylon.Util import Language.Pylon.Util.Name import Language.Pylon.Util.Error import Language.Pylon.Core.AST import Language.Pylon.Core.Monad import Language.Pylon.Core.Util import Control.Monad (unless) import Control.Monad.Except (MonadError) import Control.Monad.State.Class (MonadState, get, put) import Control.Monad.Reader.Class (MonadReader, asks, local) import Control.Applicative hiding (Const) import Control.Concurrent.Supply import Data.Foldable (forM_) import Data.Map (Map) import qualified Data.Map as M import Data.Monoid (mempty, (<>)) -------------------------------------------------------------------------------- -- API: Type Checker -------------------------------------------------------------------------------- type TypeError = CtxError Ann String type Locals = Map Ident Type -- | -- Type checks a Pylon Core expression and returns its inferred type, if the -- expression is type correct. checkExp :: Supply -> Program -> Locals -> Exp -> Either TypeError Type checkExp s p l e = runCheck s p l (tcExp e) -- | -- Type checks a Pylon Core binding. checkBind :: Supply -> Program -> Name -> Bind -> Either TypeError () checkBind s p n b = runCheck s p mempty (tcBind n b) -------------------------------------------------------------------------------- -- Monad -------------------------------------------------------------------------------- newtype Check a = Check { fromCheck :: RWSE CheckReader () CheckState CheckError a } deriving ( Functor , Applicative , Monad , MonadState CheckState , MonadReader CheckReader , MonadError CheckError ) type CheckError = TypeError type CheckState = Supply data CheckReader = CheckReader { crFree :: Map Ident Type , crProgram :: Program } instance MonadProgram Check where getProgram = asks crProgram instance MonadSupply Check where getSupply = get putSupply = put runCheck :: Supply -> Program -> Locals -> Check a -> Either CheckError a runCheck s p l go = runRWSE (fromCheck go) (CheckReader l p) s freshIdent :: Check Ident freshIdent = IGen "Check" <$> supplyId ensureEq :: Exp -> Exp -> String -> Check () ensureEq ex ac msg | ex == ac = return () | otherwise = throwError' $ unlines [ msg, "Expected: " ++ show ex, "Actual: " ++ show ac ] -------------------------------------------------------------------------------- -- Locals and Program Context -------------------------------------------------------------------------------- -- | Introduces locals into scope. withFree :: [(Ident, Type)] -> Check a -> Check a withFree vs = local $ \s -> s { crFree = M.fromList vs <> crFree s } -- | Looks up the type of a local. lookupFree :: Ident -> Check Type lookupFree i = asks crFree >>= \vs -> case M.lookup i vs of Just v -> return v Nothing -> throwError' $ "Unknown local variable: " ++ show i -------------------------------------------------------------------------------- -- TC: Bindings and Matches -------------------------------------------------------------------------------- -- | -- Checks a binding by checking its matches. tcBind :: Name -> Bind -> Check () tcBind _ (Bind Nothing _) = return () tcBind n (Bind (Just []) _) = throwError' $ "Binding without any matches: " ++ n tcBind n (Bind (Just ms) _) | arityMismatch ms = throwError' $ "Arity mismatch in binding: " ++ n | otherwise = mapM_ (tcMatch n) ms -- | -- Determines, whether there is an mismatch in arity in the given matches. arityMismatch :: [Match] -> Bool arityMismatch = not . pairwise (==) . fmap matchArity -- | -- Checks if the match is well-formed, then tries to match the types of the -- left- and right-hand side. tcMatch :: Name -> Match -> Check () tcMatch name m@(Match vs lhs rhs) = withFree vs $ do unless (isLhsForm name lhs) $ throwError' $ "Illegal left hand side in match: " ++ show m lhst <- tcExp lhs rhst <- tcExp rhs ensureEq (hnf lhst) (hnf rhst) $ "Type mismatch in match: " ++ show m -- | -- Checks whether the expression can appear on a left hand side. -- todo: this is not complete yet. it accepts too much. isLhsForm :: Name -> Exp -> Bool isLhsForm n (EApp f _) = isLhsForm n f isLhsForm n (EFree m) = ISource n == m isLhsForm _ _ = False -------------------------------------------------------------------------------- -- TC: Expressions -------------------------------------------------------------------------------- -- | -- Type checks an expression by dispatching to the respective functions. tcExp :: Exp -> Check Type tcExp (EConst c ) = tcConst c tcExp (EApp f x ) = tcApp f x tcExp (ELam t e) = tcLam t e tcExp (EPi t e ) = tcPi t e tcExp (ELet t b e) = tcLet t b e tcExp (EFree i) = tcFree i tcExp (EPrim po xs) = tcPrim po xs tcExp (EAnn a x) = tcAnn a x tcExp (ELocal _) = throwError' $ "Unopened local while type checking." tcExp (EHole _) = throwError' $ "Holes can not be type checked." tcExp (EBind _ _) = error "Unmatched binder type." -- | -- Type checks an expression, then converts its type to head normal form. tcExpNF :: Exp -> Check Type tcExpNF = fmap hnf . tcExp -- | -- Logs the annotation for better error messages, then typechecks the expression. tcAnn :: Ann -> Exp -> Check Type tcAnn a e = errorContext a $ tcExp e -- | -- Typechecks constants. tcConst :: Const -> Check Type tcConst (CLit lit ) = return $ litType lit tcConst (CCon name) = conType <$> lookupCon name tcConst CUniv = return $ EConst CUniv tcConst CPrimUniv = return $ EConst CUniv tcConst (CPrim _ ) = return $ EConst CPrimUniv -- | -- Checks if the type of the head is a function (pi) type; then opens the return -- type of the function type with the argument, if the argument type matches. tcApp :: Exp -> Exp -> Check Type tcApp f x = tcExpNF f >>= \ft -> case ft of EPi tx rt -> do xt <- tcExpNF x ensureEq (hnf tx) xt $ "Bad argument type." return $ open x rt _ -> throwError' "Application to non-function." -- | -- Opens the body with a new identifier with the bound type, then constructs -- a pi type from the bound type and the inferred result type. tcLam :: Type -> Exp -> Check Type tcLam t e = do i <- freshIdent rt <- withFree [(i, t)] $ tcExp $ open (EFree i) e return $ EPi t (close i rt) -- | -- Opens the body with a new identifier with the bound type; if it type checks, -- returns Universe. tcPi :: Type -> Exp -> Check Type tcPi t e = do i <- freshIdent _ <- withFree [(i, t)] $ tcExp $ open (EFree i) e return $ EConst CUniv -- | -- Type checks the bound expression and checks if its type matches with the -- given one. If so, open the body with a new identifier of the stated type and -- infer its type. tcLet :: Type -> Exp -> Exp -> Check Type tcLet t b e = do i <- freshIdent bt <- tcExp b ensureEq (hnf t) (hnf bt) $ "Bad typed let binding." withFree [(i, t)] $ tcExp $ open (EFree i) e -- | -- Lookup the type of the free variable in scope. tcFree :: Ident -> Check Type tcFree = lookupFree -------------------------------------------------------------------------------- -- TC: Primitive and Literals -------------------------------------------------------------------------------- -- | Check primitive application. -- todo: add IO tcPrim :: PrimOp -> [Exp] -> Check Type tcPrim p xs = do let (as, r) = primType p unless (length as == length xs) $ throwError' "Under/oversaturated primitive application." forM_ (zip as xs) $ \(a, x) -> do xt <- fmap hnf $ tcExp x ensureEq (EConst $ CPrim a) xt $ "Mismatch in primitive type." return $ EConst $ CPrim r primType :: PrimOp -> ([Prim], Prim) primType op = case op of PPlus p -> binOp p PMult p -> binOp p PDiv p -> binOp p PMinus p -> binOp p PEq p -> binOp p PLt p -> binOp p PLte p -> binOp p PGt p -> binOp p PGte p -> binOp p PForeign _ ps p -> (ps, p) where binOp p = ([p, p], p) litType :: Lit -> Type litType (LInt _) = EConst $ CPrim PInt
zrho/pylon
src/Language/Pylon/Core/Check.hs
bsd-3-clause
8,976
0
15
1,848
2,361
1,221
1,140
151
10
module System.TellMe.Monitor.Clock where import Graphics.UI.Gtk (Widget) import Data.Time.Clock (getCurrentTime) import Data.Time.Format (formatTime) import Data.Time.LocalTime (LocalTime, getCurrentTimeZone, utcToLocalTime) import System.Locale (defaultTimeLocale) import System.TellMe.Monitor tick :: IO LocalTime tick = do tz <- getCurrentTimeZone now <- getCurrentTime return $ utcToLocalTime tz now clockWidget :: String -> IO Widget clockWidget format = periodic_ 1000 tick --> m where m = formatTime defaultTimeLocale format >$< mkText
izuk/tellme
src/System/TellMe/Monitor/Clock.hs
bsd-3-clause
558
0
8
77
158
88
70
15
1
module System.Shana.DSL.Shell where import Prelude hiding ((>), (-), (.)) import System.Shana.Utils import System.Shana import Text.Regex.Posix import System.Directory import Data.List ((\\)) import Control.Applicative ((<$>)) ls :: String -> Shana String String ls x = Shana - const - (\\ [".", ".."]) <$> getDirectoryContents x grep :: String -> Shana String String grep x = Shana - \l -> return - if l =~ x then [l] else []
nfjinjing/shana
src/System/Shana/DSL/Shell.hs
bsd-3-clause
442
0
9
82
174
105
69
15
2
{-# Language MultiParamTypeClasses, FunctionalDependencies, RecordWildCards, FlexibleContexts #-} module Analysis.Types.LambdaCalc where import qualified Analysis.Types.Common as C import Control.Monad.State import qualified Data.Map as M import Control.Monad.Identity import qualified Analysis.Types.Sorts as S import Control.Monad.Except import qualified Analysis.Types.Effect as E import qualified Analysis.Types.Annotation as A import qualified Data.Set as D -- | Type that represents the type-lambda calculus with fixpoints -- described in the paper. data LambdaCalc t = Var Int | VFalse | VTrue | Abs (C.Variable t) (LambdaCalc t) | If (LambdaCalc t) (LambdaCalc t) (LambdaCalc t) | App (LambdaCalc t) (LambdaCalc t) | Fix (LambdaCalc t) deriving (Show,Read,Eq,Ord) -- | Same as the LambdaCalc type, but annotations are -- made explicit by adding an extra field to the constructor. -- This is necessary because fixpoint expressions employ a re-writing -- of the AST such that the annotation information cannot be implicitly -- deduced. data ALambdaCalc t = AVar Int Int | AFalse Int | ATrue Int | AAbs Int (C.Variable t) (ALambdaCalc t) | AIf Int (ALambdaCalc t) (ALambdaCalc t) (ALambdaCalc t) | AApp Int (ALambdaCalc t) (ALambdaCalc t) | AFix Int (ALambdaCalc t) deriving (Show,Read,Eq,Ord) data Algebra t m t' a = Algebra{ fvar :: Int -> Int -> m a, fvfalse :: Int -> m a, fvtrue :: Int -> m a, fabs :: Int -> (C.Variable t) -> a -> m a, fif :: Int -> a -> a -> a -> m a, fapp :: Int -> a -> a -> m a, ffix :: Int -> a -> m a } algebra :: Monad m => Algebra t m (LambdaCalc t) (LambdaCalc t) algebra = Algebra{ fvar = \_ v -> return $ Var v, fvfalse = \_ -> return $ VFalse, fvtrue = \_ -> return $ VTrue, fabs = \_ var s -> return $ Abs var s, fif = \_ cond yes no -> return $ If cond yes no, fapp = \_ t1 t2 -> return $ App t1 t2, ffix = \_ t1 -> return $ Fix t1 } aalgebra :: Monad m => Algebra t m (ALambdaCalc t) (ALambdaCalc t) aalgebra = Algebra{ fvar = \i v -> return $ AVar i v, fvfalse = \i -> return $ AFalse i, fvtrue = \i -> return $ ATrue i, fabs = \i var s -> return $ AAbs i var s, fif = \i cond yes no -> return $ AIf i cond yes no, fapp = \i t1 t2 -> return $ AApp i t1 t2, ffix = \i t1 -> return $ AFix i t1 } instance C.Fold (ALambdaCalc t) (Algebra t) where byId = undefined foldM = foldALambdaCalcM baseAlgebra = aalgebra groupAlgebra = groupAlgebraInit C.void instance C.Fold (LambdaCalc t) (Algebra t) where byId = undefined foldM = foldLambdaCalcM baseAlgebra = algebra groupAlgebra = Algebra{ fvar = \_ _-> return C.void, fvfalse = \_ -> return C.void, fvtrue = \_ -> return C.void, fabs = \_ _ s -> return s, fif = \_ cond yes no -> return $ cond C.<+> yes C.<+> no, fapp = \_ s1 s2 -> return $ s1 C.<+> s2, ffix = \_ s1 -> return s1 } groupAlgebraInit s0 = Algebra{ fvar = \_ _ -> return s0, fvfalse = \_ -> return s0, fvtrue = \_ -> return s0, fabs = \_ _ s -> return s, fif = \_ cond yes no -> return $ cond C.<+> yes C.<+> no, fapp = \_ s1 s2 -> return $ s1 C.<+> s2, ffix = \_ s1 -> return s1 } foldALambdaCalcM Algebra{..} expr = foldLambdaCalcM' undefined expr where foldLambdaCalcM' s l = do case l of AVar i v -> fvar i v AFalse i -> fvfalse i ATrue i -> fvtrue i AAbs i var exp -> foldLambdaCalcM' s exp >>= fabs i var AIf i cond yes no -> do cond' <- foldLambdaCalcM' s cond yes' <- foldLambdaCalcM' s yes no' <- foldLambdaCalcM' s no fif i cond' yes' no' AApp i exp1 exp2 -> do exp1' <- foldLambdaCalcM' s exp1 exp2' <- foldLambdaCalcM' s exp2 fapp i exp1' exp2' AFix i exp -> foldLambdaCalcM' s exp >>= ffix i foldLambdaCalcM Algebra{..} expr = evalStateT (foldLambdaCalcM' undefined expr) 0 where foldLambdaCalcM' s l = do i <- get put (i + 1) case l of Var v -> lift $ fvar i v VFalse -> lift $ fvfalse i VTrue -> lift $ fvtrue i Abs var exp -> foldLambdaCalcM' s exp >>= lift . (fabs i var) If cond yes no -> do cond' <- foldLambdaCalcM' s cond yes' <- foldLambdaCalcM' s yes no' <- foldLambdaCalcM' s no lift $ fif i cond' yes' no' App exp1 exp2 -> do exp1' <- foldLambdaCalcM' s exp1 exp2' <- foldLambdaCalcM' s exp2 lift $ fapp i exp1' exp2' Fix exp -> foldLambdaCalcM' s exp >>= lift . (ffix i) depths = runIdentity . (foldLambdaCalcM alg) where sing i = return $ M.fromList [(i,0 :: Int)] alg = Algebra{ fvar = \i _ -> sing i, fvfalse = sing, fvtrue = sing, fabs = \i _ d -> return $ M.insert i 0 $ M.map (+1) d, fif = \i d1 d2 d3 -> return $ M.insert i 0 $ M.unions [d1,d2,d3], fapp = \i d1 d2 -> return $ M.insert i 0 $ M.union d1 d2, ffix = \i d1 -> return $ M.insert i 0 d1 } -- | Function that converts an implicitly annotated lambda -- calculus into an explicitly annotated variant addLabels = runIdentity . (foldLambdaCalcM alg) where varF i v = return $ AVar i v falseF i = return $ AFalse i trueF i = return $ ATrue i absF i v e = return $ AAbs i v e ifF i cond yes no = return $ AIf i cond yes no appF i a1 a2 = return $ AApp i a1 a2 fixF i a = return $ AFix i a alg = Algebra{ fvar = varF, fvfalse = falseF, fvtrue = trueF, fabs = absF, fif = ifF, fapp = appF, ffix = fixF } shadows v = runIdentity . (foldALambdaCalcM alg) where varF i _ = return $ M.fromList [(i,False)] falseF i = return $ M.fromList [(i,False)] trueF i = return $ M.fromList [(i,False)] absF i v' s = let s' = if C.name v' == v then M.map (const True) s else s in return $ M.insert i False s' ifF i cond yes no = return $ M.insert i False $ cond `M.union` yes `M.union` no appF i a1 a2 = return $ M.insert i False $ M.union a1 a2 fixF i a = return $ M.insert i False a alg = Algebra{ fvar = varF, fvfalse = falseF, fvtrue = trueF, fabs = absF, fif = ifF, fapp = appF, ffix = fixF } -- | Function to replace all ocurrences of the argument -- variable in the second argument (unless shadowed) by -- the third argument replace v e e1 = snd $ runIdentity $ (foldALambdaCalcM alg e) where falseF i = return (AFalse i,AFalse i) trueF i = return (ATrue i,ATrue i) varF i v' | v' == v = return $ (AVar i v',e1) | otherwise = return $ (AVar i v',AVar i v') absF i v' (ex1,ex2) | v == C.name v' = let r = AAbs i v' ex1 in return (r,r) | otherwise = return (AAbs i v' ex1, AAbs i v' ex2) ifF i (cond1,cond2) (yes1,yes2) (no1,no2) = return ( AIf i cond1 yes1 no1, AIf i cond2 yes2 no2) appF i (f1,f2) (a1,a2) = return (AApp i f1 a1,AApp i f2 a2) fixF i (fix1,fix2) = return (AFix i fix1,AFix i fix2) alg = Algebra{ fvfalse = falseF, fvtrue = trueF, fabs = absF, fif = ifF, ffix = fixF, fapp = appF, fvar = varF} -- | Function that reduces an annotated LambdaCalculus. It takes as an -- argument wether or not employ a full reduction or leave the fixpoints -- un-reduced. It is important not to always eagerly reduce the fixpoints -- otherwise it gets into an infinite loop. reduce whnf e = (reduceStep whnf e) >>= go e where go e1 (e2,effs) | e1 == e2 = return (e2,effs) | otherwise = do (e2',effs') <- reduceStep whnf e2 go e2 (e2',D.unions [effs, effs']) -- | Traverse once an entire Annotated Lambda Term and perform all reductions -- | possible. The first argument indicates wether or not reduce the fixpoints reduceStep whnf c = case c of AApp i e1@(AFix _ _) e2 -> if whnf then return (AApp i e1 e2,D.empty) else doApp i e1 e2 AApp i e1 e2 -> doApp i e1 e2 AIf i cond yes no -> do (cond',eff1) <- reduce whnf cond case cond' of ATrue i' -> do (yes',eff2) <- reduce whnf yes return $ (yes',D.unions [eff1, D.singleton (E.Flow (show i) (A.Label (show i'))), eff2]) AFalse i' -> do (no',eff3) <- reduce whnf no return $ (no',D.unions [eff1, D.singleton (E.Flow (show i) (A.Label (show i'))), eff3]) _ -> throwError $ "Cannot reduce: " ++ show c (AFix i e) -> do (e',effs1) <- reduce whnf e case e' of (AAbs i' v ex) -> do (e'',effs2) <- reduce True $ replace (C.name v) ex (AFix i e) return (e'',D.unions [effs1, D.singleton (E.Flow (show i) (A.Label (show i'))), effs2]) _ -> throwError $ "Cannot reduce: " ++ show c e -> return (e,D.empty) where doApp i e1 e2 = do (e1',effs1) <- reduce whnf e1 (e2',effs2) <- reduce whnf e2 case e1' of (AAbs i' v e) -> do (e3,effs3) <- reduce whnf $ replace (C.name v) e e2' return (e3, D.unions [D.singleton (E.Flow (show i) (A.Label (show i'))), effs1, effs2, effs3]) _ -> throwError $ "Cannot reduce: " ++ show c reduceExpr :: (Show t,Eq t) => LambdaCalc t -> Either String (ALambdaCalc t,D.Set E.Effect) reduceExpr = runExcept . reduce False . addLabels
netogallo/polyvariant
src/Analysis/Types/LambdaCalc.hs
bsd-3-clause
9,517
0
25
2,845
3,844
2,001
1,843
228
10
module Fasta ( Pair(..), fastaLines ) where import Data.Foldable ( toList ) import Data.Sequence ( Seq, empty, viewr, ViewR(..), (|>) ) data Pair = Pair { header :: String , sequenceData :: String } deriving (Eq , Show) -- | folds fasta file format into [Pair] fastaLines :: String -> [Pair] fastaLines = toPair . toList . foldLine . lines where foldLine :: [String] -> Seq (String, Seq String) foldLine = foldl mkLine empty toPair :: [(String, Seq String)] -> [Pair] toPair = map (\(h, s) -> Pair h ((concat . toList) s)) -- | folds an individual line mkLine :: Seq (String, Seq String) -> String -> Seq (String, Seq String) mkLine seq entry = let (prevs :> (h, s)) = viewr seq in case (take 1 entry) of [] -> seq ">" -> seq |> (tail entry, empty) -- new header, empty body _ -> prevs |> (h, s |> entry) -- keep header, append body
mitochon/hoosalind
src/Fasta.hs
mit
901
0
14
226
353
199
154
22
3
---------------------------------------------------- -- -- -- HyLoRes.Subsumption.SubsumptionTrie: -- -- Structure to check if new clauses are subsumed -- -- by the set of clauses -- -- -- ---------------------------------------------------- {- Copyright (C) HyLoRes 2002-2007 - See AUTHORS file This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -} module HyLoRes.Subsumption.SubsumptionTrie( SubsumptionTrie, empty, add, subsumes, unit_tests) where import Data.List ( sort, subsequences ) import Test.QuickCheck import HyLo.Test ( UnitTest, runTest ) import HyLoRes.Formula ( HashOrd(..), At, Opaque ) import HyLoRes.Formula.NF ( AtFormulaNF ) import HyLoRes.Clause ( toFormulaList ) import HyLoRes.Clause.FullClause ( FullClause ) data SubsumptionTrie = Nil | Node{val :: HashOrd AtFormulaNF, left :: !SubsumptionTrie, right :: !SubsumptionTrie, next :: !SubsumptionTrie} deriving (Read, Show) empty :: SubsumptionTrie empty = Nil add :: FullClause f -> SubsumptionTrie -> SubsumptionTrie add = addSortedList . asSortedList asSortedList :: FullClause f -> [HashOrd AtFormulaNF] asSortedList = sort . map HashOrd . toFormulaList addSortedList :: [HashOrd AtFormulaNF] -> SubsumptionTrie -> SubsumptionTrie addSortedList [] _ = Nil -- the empty clause subsumes all! -- (possible trie prunning) addSortedList l Nil = foldr (\i st -> Node i Nil Nil st) Nil l addSortedList l@(x:xs) st = case compare x (val st) of EQ -> if isNil (next st) then st -- subsumed by current clause else st{next = addSortedList xs (next st)} LT -> st{left = addSortedList l (left st)} GT -> st{right = addSortedList l (right st)} subsumes :: SubsumptionTrie -> FullClause f -> Bool subsumes st = subsumesSL st . asSortedList subsumesSL :: SubsumptionTrie -> [HashOrd AtFormulaNF] -> Bool subsumesSL Nil _ = False -- the empty set of clauses subsumes nothing subsumesSL _ [] = False subsumesSL st l@(x:xs) = case compare x (val st) of EQ -> isNil (next st) -- end of branch, subsumed! or || subsumesSL (next st) xs -- subsumer contains x or || subsumesSL (right st) xs -- subsumer does not contains x -- LT -> subsumesSL (nodeFor x $ left st) l -- subsumer contains x, or || subsumesSL st xs -- subsumer does not contains x -- GT -> subsumesSL (right st) l -- nothing to do here, moving right isNil :: SubsumptionTrie -> Bool isNil Nil = True isNil _ = False nodeFor :: HashOrd AtFormulaNF -> SubsumptionTrie -> SubsumptionTrie nodeFor _ Nil = Nil nodeFor x st = case compare x (val st) of EQ -> st LT -> nodeFor x (left st) GT -> nodeFor x (right st) clauses :: SubsumptionTrie -> [[HashOrd AtFormulaNF]] clauses Nil = [[]] clauses st = concat [map (val st :) (clauses $ next st), filter (not . null) . clauses $ left st, filter (not . null) . clauses $ right st] contains :: SubsumptionTrie -> [HashOrd AtFormulaNF] -> Bool contains Nil xs = null xs contains _ [] = False contains st (x:xs) = case (nodeFor x st) of Nil -> False st' -> contains (next st') xs ----------------------------------- -- QuickCheck stuff ----------------------------------- instance Arbitrary SubsumptionTrie where arbitrary = f `fmap` arbitrary where f :: [FullClause (At Opaque)] -> SubsumptionTrie f = foldr add Nil -- coarbitrary Nil = variant 0 coarbitrary (Node v l r n) = variant 1 . coarbitrary (fromHashOrd v) . coarbitrary l . coarbitrary r . coarbitrary n prop_nodeForWorks :: SubsumptionTrie -> AtFormulaNF -> Bool prop_nodeForWorks st f = case nodeFor hf st of Nil -> isNil st || (not $ hf `elem` initials) st' -> hf `elem` initials && val st' == hf where initials = map head (clauses st) hf = HashOrd f prop_containedClausesAreSubsumed :: SubsumptionTrie -> Bool prop_containedClausesAreSubsumed st = isNil st || all (subsumesSL st) (clauses st) prop_containedClausesAreContained :: SubsumptionTrie -> Bool prop_containedClausesAreContained st = all (contains st) (clauses st) prop_subsumesIffSubclause :: SubsumptionTrie->FullClause (At Opaque)->Property prop_subsumesIffSubclause st cl = classify isSubsumed "subsumed" $ isSubsumed == subsumes st cl where isSubsumed = or $ map (contains st) (notNullSubseqs $ asSortedList cl) notNullSubseqs = filter (not . null) . subsequences unit_tests :: UnitTest unit_tests = [ ("nodeFor works", runTest prop_nodeForWorks), ("contained clauses are subsumed", runTest prop_containedClausesAreSubsumed), ("contained clauses are contained",runTest prop_containedClausesAreContained), ("subsumes iff subclause", runTest prop_subsumesIffSubclause) ]
nevrenato/HyLoRes_Source
src/HyLoRes/Subsumption/SubsumptionTrie.hs
gpl-2.0
6,668
0
13
2,369
1,437
755
682
101
4
-- | This module has some tools for testing Esqueleto queries from ghci. -- -- It is not intended to be used in any Snowdrift code. Instead, :load it -- from `cabal repl`. module DBTest (dbdev) where import Import import Yesod.Default.Config import qualified Database.Persist import Settings import Control.Monad.Trans.Resource (runResourceT, ResourceT) -- | Query type -- -- Generally, query types will need to be specified. This type is -- a shortcut for writing them down. -- -- It can probably be improved upon. Maybe more specific types for -- different types of queries? type Q a = SqlPersistT (ResourceT IO) a -- | Synonym for Q within this module -- -- Q is a bit too brief for actual code, and shouldn't be confused with TH -- stuff. type Query a = Q a -- | Run an esqueleto query in ghci. -- -- Two examples: -- -- >>> dbdev ((select $ from $ \p -> return (p ^. UserIdent)) :: Q [Value Text]) -- [Value "admin",Value "anonymous"] -- -- >>> fmap (map entityVal) $ dbdev (select $ from $ return :: Q [Entity User]) -- [User {userIdent = "admin", userEmail = ... dbdev :: Show a => Query a -> IO a dbdev = dbtest Development -- | Small generalization of dbdev over the different execution environments. -- -- May be useful later. dbtest :: Show a => DefaultEnv -> Query a -> IO a dbtest env query = do conf <- Yesod.Default.Config.loadConfig (configSettings env) dbconf <- withYamlEnvironment "config/postgresql.yml" (appEnv conf) Database.Persist.loadConfig >>= Database.Persist.applyEnv pool <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf) runResourceT $ Database.Persist.runPool dbconf query pool
chreekat/snowdrift
dev/DBTest.hs
agpl-3.0
1,679
0
11
316
251
146
105
18
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : DiagramSceneType.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:47 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module DiagramScene.DiagramSceneType ( Mode(..), BackgroundType(..), QDiagramScene, DiagramScene(..) ) where import Qtc.ClassTypes.Core import Qtc.ClassTypes.Gui import DiagramScene.DiagramItemType import DiagramScene.ArrowType import Data.IORef data BackgroundType = BlueGrid | WhiteGrid | GrayGrid | NoGrid deriving (Eq, Enum) data Mode = InsertItem | InsertLine | InsertText | MoveItem deriving Enum type QDiagramScene = QGraphicsSceneSc (CQDiagramScene) data CQDiagramScene = CQDiagramScene data DiagramScene = DiagramScene {ds_o :: QDiagramScene, ds_ItemType :: IORef DiagramType, ds_ItemMenu :: QMenu (), ds_mod_io :: IORef Mode, ds_font_io :: IORef (QFont ()), ds_textColor_io :: IORef (QColor ()), ds_itemColor_io :: IORef (QColor ()), ds_lineColor_io :: IORef (QColor ()), ds_items_io :: IORef [DiagramItem], ds_avn_io :: IORef [Int], ds_isn_io :: IORef Int, ds_avs_io :: IORef Int, ds_da :: Arrow, ds_ca_io :: IORef (Bool, Arrow) }
uduki/hsQt
examples/DiagramScene/DiagramSceneType.hs
bsd-2-clause
1,448
0
12
278
303
180
123
28
0
{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving, StandaloneDeriving #-} import Prelude hiding (mapM) import Options.Applicative import Data.Monoid ((<>)) import Control.Monad.Trans.Class import Data.Vector (Vector) import qualified Data.Vector.Generic as V import Statistics.Sample (mean) import Data.Traversable (mapM) import qualified Data.Set as S import Data.Set (Set) import qualified Data.Map as M import ReadData import SerializeText import qualified RunSampler as Sampler import BayesStack.DirMulti import BayesStack.Models.Topic.SharedTaste import BayesStack.UniqueKey import qualified Data.Text as T import qualified Data.Text.IO as TIO import System.FilePath.Posix ((</>)) import Data.Binary import qualified Data.ByteString as BS import Text.Printf import Data.Random import System.Random.MWC data RunOpts = RunOpts { arcsFile :: FilePath , nodesFile :: FilePath , stopwords :: Maybe FilePath , nTopics :: Int , samplerOpts :: Sampler.SamplerOpts , hyperParams :: HyperParams } runOpts = RunOpts <$> strOption ( long "edges" <> short 'e' <> metavar "FILE" <> help "File containing edges" ) <*> strOption ( long "nodes" <> short 'n' <> metavar "FILE" <> help "File containing nodes' items" ) <*> nullOption ( long "stopwords" <> short 's' <> metavar "FILE" <> reader (pure . Just) <> value Nothing <> help "Stop words list" ) <*> option ( long "topics" <> short 't' <> metavar "N" <> value 20 <> help "Number of topics" ) <*> Sampler.samplerOpts <*> hyperOpts hyperOpts = HyperParams <$> option ( long "prior-psi" <> value 1 <> help "Dirichlet parameter for prior on psi" ) <*> option ( long "prior-lambda" <> value 0.1 <> help "Dirichlet parameter for prior on lambda" ) <*> option ( long "prior-phi" <> value 0.01 <> help "Dirichlet parameter for prior on phi" ) <*> option ( long "prior-omega" <> value 0.01 <> help "Dirichlet parameter for prior on omega" ) <*> option ( long "prior-gamma-shared" <> value 0.9 <> help "Beta parameter for prior on gamma (shared)" ) <*> option ( long "prior-gamma-own" <> value 0.1 <> help "Beta parameter for prior on gamma (own)" ) mapMKeys :: (Ord k, Ord k', Monad m, Applicative m) => (a -> m a') -> (k -> m k') -> M.Map k a -> m (M.Map k' a') mapMKeys f g x = M.fromList <$> (mapM (\(k,v)->(,) <$> g k <*> f v) $ M.assocs x) termsToItems :: M.Map NodeName [Term] -> Set (NodeName, NodeName) -> ( (M.Map Node [Item], Set (Node, Node)) , (M.Map Item Term, M.Map Node NodeName)) termsToItems nodes arcs = let ((d', nodeMap), itemMap) = runUniqueKey' [Item i | i <- [0..]] $ runUniqueKeyT' [Node i | i <- [0..]] $ do a <- mapMKeys (mapM (lift . getUniqueKey)) getUniqueKey nodes b <- S.fromList <$> mapM (\(x,y)->(,) <$> getUniqueKey x <*> getUniqueKey y) (S.toList arcs) return (a,b) in (d', (itemMap, nodeMap)) netData :: HyperParams -> M.Map Node [Item] -> Set Edge -> Int -> NetData netData hp nodeItems edges nTopics = NetData { dHypers = hp , dEdges = edges , dItems = S.unions $ map S.fromList $ M.elems nodeItems , dTopics = S.fromList [Topic i | i <- [1..nTopics]] , dNodeItems = M.fromList $ zip [NodeItem i | i <- [0..]] $ do (n,items) <- M.assocs nodeItems item <- items return (n, item) } opts = info runOpts ( fullDesc <> progDesc "Learn shared taste model" <> header "run-st - learn shared taste model" ) instance Sampler.SamplerModel MState where estimateHypers = id -- reestimate -- FIXME modelLikelihood = modelLikelihood summarizeHypers ms = "" -- FIXME main = do args <- execParser opts stopWords <- case stopwords args of Just f -> S.fromList . T.words <$> TIO.readFile f Nothing -> return S.empty printf "Read %d stopwords\n" (S.size stopWords) ((nodeItems, a), (itemMap, nodeMap)) <- termsToItems <$> readNodeItems stopWords (nodesFile args) <*> readEdges (arcsFile args) let edges = S.map Edge a Sampler.createSweeps $ samplerOpts args let sweepsDir = Sampler.sweepsDir $ samplerOpts args encodeFile (sweepsDir </> "item-map") itemMap encodeFile (sweepsDir </> "node-map") nodeMap let termCounts = V.fromListN (M.size nodeItems) $ map length $ M.elems nodeItems :: Vector Int printf "Read %d edges, %d items\n" (S.size edges) (M.size nodeItems) printf "Mean items per node: %1.2f\n" (mean $ V.map realToFrac termCounts) withSystemRandom $ \mwc->do let nd = netData (hyperParams args) nodeItems edges 10 encodeFile (sweepsDir </> "data") nd mInit <- runRVar (randomInitialize nd) mwc let m = model nd mInit Sampler.runSampler (samplerOpts args) m (updateUnits nd) return ()
beni55/bayes-stack
network-topic-models/RunST.hs
bsd-3-clause
6,232
0
19
2,478
1,671
854
817
-1
-1
{-# OPTIONS_HADDOCK prune #-} -- | This package implements Reduced Ordered Binary Decision Diagrams -- (ROBDDs) in pure Haskell. ROBDDs provide canonical representations -- of boolean formulas as directed acyclic graphs and have some very -- convenient properties: -- -- * Tests for formula equality are fast -- -- * The representation is compact for most reasonable formulas -- due to shared structure -- -- The performance of ROBDDs is highly-dependent on the order chosen -- for variables. In the worst case, an ROBDD can be exponential in -- the number of variables. This package does not perform automatic -- variable reordering, though manual reordering through 'replace' is -- simple. -- -- == Performance == -- -- This implementation uses pure Haskell and a simple linked -- representation (as opposed to more-common array-based -- implementations). It performs well on reasonable BDDs of 70 -- variables or so; there is still some performance tuning that is -- possible. I will make it more efficient in the future. It is -- probably not competitive with any of the mainstream BDD -- implementations, but I have not benchmarked it. The implementation -- uses dynamic programming in as many places as possible (except for -- parts of 'replace', which I haven't figured out how to memoize -- yet). -- -- This package makes one significant design decision that sets it -- apart from many others: BDD nodes are only guaranteed to be unique -- within their own BDD. Most other packages that I have seen give -- uniqueness across all BDDs. The primary reason for this choice is -- to allow the RTS garbage collector to collect dead nodes without an -- additional reference counting mechanism (which seemed very -- difficult to implement in pure code). -- -- This means that each BDD is still in canonical form. There is some -- sharing between BDDs, but no guarantees about how much. For -- example, the result of combining two BDDs via 'apply' can share -- nodes from either input BDD. -- -- The downside of this is that equality tests are no longer constant -- time (tests for tautologies and contradictions still are, though). -- That said, they are at worst linear in the number of nodes in the -- BDD (as opposed to exponential for formulas in other formats). -- However, each BDD maintains its own structural hash. If two BDDs -- that are /not/ equal are tested for equality, the test returns -- False in constant time (since the hashes will not match). -- Otherwise, the pessimistic test comparing all nodes proceeds as -- normal. -- -- The upside is that all BDDs are completely indepdenent and do not -- share any (mutable) state, so BDD operations can be run in parallel -- trivially. -- -- == Notes == -- -- This package really needs GHC's @-funbox-strict-fields@ flag (set -- in the cabal file) to have reasonable memory usage. -- -- This API is still unstable and subject to change. In particular, -- some operations could use better names and 'replace' should return -- @Maybe ROBDD@ when a rename fails. -- -- == Examples == -- -- deMorgan's Law !(x[1] OR x[2]) == !x[1] AND !x[2] -- -- >>> let left = neg (makeVar 1 `or` makeVar 2) -- >>> let right = neg (makeVar 1) `and` neg (makeVar 2) -- -- >>> right == left -- > True module Data.ROBDD ( -- * Types ROBDD, Var, -- * Constants makeTrue, makeFalse, makeVar, -- * Operations -- | These functions manipulate BDDs. All of the normal binary -- operators have the same complexity as apply. apply, applyExists, applyForAll, applyUnique, restrict, restrictAll, replace, and, or, xor, impl, biimpl, nand, nor, neg, exist, forAll, unique, -- * Extracting Solutions -- | These functions extract satisfying solutions (or information -- about them) from a BDD. satCount, anySat, allSat, allSat' ) where import Prelude hiding ( and, or ) import Data.Foldable ( toList ) import Data.List ( sort ) import qualified Data.HashMap.Strict as M import qualified Data.HashSet as S import Data.Hashable import qualified Data.Sequence as Seq import Data.Sequence ( Seq, (><) ) import Data.ROBDD.BooleanFunctions import Data.ROBDD.Types type BinBoolFunc = Bool -> Bool -> Bool -- | Make the BDD representing the Tautology (One/True) makeTrue :: ROBDD makeTrue = ROBDD M.empty [0..] One -- | Make the BDD representing the Contradiction (Zero/False) makeFalse :: ROBDD makeFalse = ROBDD M.empty [0..] Zero -- | Make a single BDD variable with the given number. The number is -- used to identify the variable in other functions (like -- quantification). The number must be non-negative; negative numbers -- will cause an error to be raised. -- -- The resulting BDD has a single variable (with the number provided) -- and edges to Zero and One. makeVar :: Var -> ROBDD makeVar v | v >= 0 = ROBDD M.empty [0..] bdd | otherwise = error "Variable numbers must be >= 0" where bdd = BDD Zero v One 0 (hashNode v Zero One) -- | Logical and and :: ROBDD -> ROBDD -> ROBDD and = apply (&&) -- | Logical or or :: ROBDD -> ROBDD -> ROBDD or = apply (||) -- | Logical xor xor :: ROBDD -> ROBDD -> ROBDD xor = apply boolXor -- | Logical implication impl :: ROBDD -> ROBDD -> ROBDD impl = apply boolImpl -- | Logical biimplication biimpl :: ROBDD -> ROBDD -> ROBDD biimpl = apply boolBiimp -- | Logical nand nand :: ROBDD -> ROBDD -> ROBDD nand = apply boolNotAnd -- | Logical nor nor :: ROBDD -> ROBDD -> ROBDD nor = apply boolNotOr -- | Existentially quantify a single variable from a BDD. -- -- > exist b 10 -- -- creates a new BDD based on @b@ where the value of variable 10 is -- valid for an arbitrary assignment. Equivalent to: -- -- > b[10/True] `or` b[10/False] -- -- (where 10/True means that True is substituted in for variable 10). exist :: ROBDD -> Var -> ROBDD exist bdd var = or (restrict bdd var True) (restrict bdd var False) -- | Uniquely quantify a single variable from a BDD. This is similar to -- 'exist', except the decomposed BDDs are combined with ``xor``. unique :: ROBDD -> Var -> ROBDD unique bdd var = xor (restrict bdd var True) (restrict bdd var False) -- | forAll quantify the given variable. This is similar to 'exist', -- except the decomposed BDDs are combined with ``and``. forAll :: ROBDD -> Var -> ROBDD forAll bdd var = and (restrict bdd var True) (restrict bdd var False) -- | Construct a new BDD by applying the provided binary operator -- to the two input BDDs. -- -- O(|v_1||v_2|) apply :: (Bool -> Bool -> Bool) -> ROBDD -> ROBDD -> ROBDD apply op (ROBDD _ _ bdd1) (ROBDD _ _ bdd2) = let (bdd, s) = runBDDContext (applyInner op stdCtxt bdd1 bdd2) emptyBDDState -- FIXME: Remove unused bindings in the revmap to allow the -- runtime to GC unused nodes in ROBDD (bddRevMap s) (bddIdSource s) bdd -- Note: the reverse node maps of each input BDD are ignored because -- we need to build a new one on the fly for the result BDD. -- This is the main implementation of apply, but also re-used for the -- combined apply/quantify operations. applyInner :: BinBoolFunc -> EvaluationContext -> BDD -> BDD -> BDDContext (Int, NodeId, NodeId) BDD BDD applyInner op ctxt bdd1 bdd2 = appBase bdd1 bdd2 where appBase :: BDD -> BDD -> BDDContext (EvaluationContext, NodeId, NodeId) BDD BDD appBase lhs rhs = memoize (ctxt, nodeUID lhs, nodeUID rhs) $ case maybeApply op lhs rhs of Just True -> return One Just False -> return Zero Nothing -> appRec lhs rhs appRec :: BDD -> BDD -> BDDContext (EvaluationContext, NodeId, NodeId) BDD BDD appRec lhs rhs = do (v, l', h') <- genApplySubproblems appBase lhs rhs mk v l' h' maybeApply :: (Bool -> Bool -> Bool) -> BDD -> BDD -> Maybe Bool maybeApply op lhs rhs = do b1 <- toBool lhs b2 <- toBool rhs return $ b1 `op` b2 toBool :: BDD -> Maybe Bool toBool One = Just True toBool Zero = Just False toBool _ = Nothing -- This is the core of apply that determines the subproblems to evaluate -- at this step. The appBase argument is the action that should be -- called recursively for each sub problem. genApplySubproblems :: (Monad m) => (BDD -> BDD -> m BDD) -> BDD -> BDD -> m (Var, BDD, BDD) genApplySubproblems appBase lhs rhs = case lhs `bddCmp` rhs of -- Vars are the same, so use high and low of both lhs and rhs as the -- sub-problem EQ -> do newLowNode <- appBase (lowEdge lhs) (lowEdge rhs) newHighNode <- appBase (highEdge lhs) (highEdge rhs) return (nodeVar lhs, newLowNode, newHighNode) -- Var1 is less than var2, so only take the low/high edges of the -- lhs (pass the RHS through unchanged) LT -> do newLowNode <- appBase (lowEdge lhs) rhs newHighNode <- appBase (highEdge lhs) rhs return (nodeVar lhs, newLowNode, newHighNode) -- Var1 is greater than v2 GT -> do newLowNode <- appBase lhs (lowEdge rhs) newHighNode <- appBase lhs (highEdge rhs) return (nodeVar rhs, newLowNode, newHighNode) -- This is the main implementation of the combined apply/quantify -- operators. They are really all the same except for the -- quantification operator. genericApply :: BinBoolFunc -> BinBoolFunc -> ROBDD -> ROBDD -> [Var] -> ROBDD genericApply quantifier op (ROBDD _ _ bdd1) (ROBDD _ _ bdd2) evars = let (bdd, s) = runBDDContext (appBase bdd1 bdd2) emptyBDDState in ROBDD (bddRevMap s) (bddIdSource s) bdd where varSet = S.fromList evars appBase :: BDD -> BDD -> BDDContext (EvaluationContext, NodeId, NodeId) BDD BDD appBase lhs rhs = memoize (stdCtxt, nodeUID lhs, nodeUID rhs) $ case maybeApply op lhs rhs of Just True -> return One Just False -> return Zero Nothing -> appRec lhs rhs appRec :: BDD -> BDD -> BDDContext (EvaluationContext, NodeId, NodeId) BDD BDD appRec lhs rhs = do (v', l', h') <- genApplySubproblems appBase lhs rhs case v' `S.member` varSet of False -> mk v' l' h' -- Standard case - we are not projecting out this variable -- so just let mk handle creating a new node if necessary True -> applyInner quantifier innerCtxt l' h' -- If this variable is to be quantified out, this magic is -- due to McMillan 92; we quantify it out while we are -- building the tree via a call to or. This re-uses the -- current BDD context and so does not use the top-level -- or, but the underlying machinery -- See http://www.kenmcmil.com/pubs/thesis.pdf -- -- The quantification returns the formula that would -- result if a variable V is declared to be forall, -- unique, or exists; it does this by invoking either and, -- xor, or or on the sub-problems for any step where V is -- the leading variable. -- | A variant of apply that existentially quantifies out the provided -- list of variables on the fly during the bottom-up construction of -- the result. This is much more efficient than performing the -- quantification after the apply. applyExists :: (Bool -> Bool -> Bool) -> ROBDD -> ROBDD -> [Var] -> ROBDD applyExists = genericApply (||) applyUnique :: (Bool -> Bool -> Bool) -> ROBDD -> ROBDD -> [Var] -> ROBDD applyUnique = genericApply boolXor applyForAll :: (Bool -> Bool -> Bool) -> ROBDD -> ROBDD -> [Var] -> ROBDD applyForAll = genericApply (&&) -- | Fix the value of a variable in the formula. -- -- > restrict b 10 True -- -- Creates a new BDD based on @b@ where variable 10 is replaced by -- True. -- -- O(|v|) restrict :: ROBDD -> Var -> Bool -> ROBDD restrict bdd@(ROBDD _ _ Zero) _ _ = bdd restrict bdd@(ROBDD _ _ One) _ _ = bdd restrict (ROBDD revMap idSrc bdd) v b = let (r,s) = runBDDContext (restrict' bdd) emptyBDDState { bddIdSource = idSrc , bddRevMap = revMap } in ROBDD (bddRevMap s) (bddIdSource s) r where restrict' Zero = return Zero restrict' One = return One restrict' o@(BDD low var high uid _) = memoize uid $ case var `compare` v of GT -> return o LT -> do low' <- restrict' low high' <- restrict' high mk var low' high' EQ -> case b of True -> restrict' high False -> restrict' low -- | This is a variant of 'restrict' over a list of variable/value -- assignments. It is more efficient than repeated calls to -- 'restrict'. restrictAll :: ROBDD -> [(Var, Bool)] -> ROBDD restrictAll bdd@(ROBDD _ _ Zero) _ = bdd restrictAll bdd@(ROBDD _ _ One) _ = bdd restrictAll (ROBDD revMap idSrc bdd) vals = let (r, s) = runBDDContext (restrict' bdd) emptyBDDState { bddIdSource = idSrc , bddRevMap = revMap } in ROBDD (bddRevMap s) (bddIdSource s) r where valMap = M.fromList vals restrict' Zero = return Zero restrict' One = return One restrict' (BDD low var high uid _) = memoize uid $ case var `M.lookup` valMap of Just b -> case b of True -> restrict' high False -> restrict' low Nothing -> do low' <- restrict' low high' <- restrict' high mk var low' high' -- | Rename BDD variables according to the @mapping@ provided as an -- alist. This can be a very expensive operation. The renames occur -- simultaneously (I think), so swapping two variables should work -- without intermediate steps. -- -- Note: -- -- This function can throw an exception; this is ugly and I intend to -- convert the return type to Maybe ROBDD once I figure out how to -- determine that a rename will be 'bad'. -- -- I think renames fail when a variable is renamed to a position that -- is already occupied, but I'm not quite sure about that. replace :: ROBDD -> [(Var, Var)] -> ROBDD replace (ROBDD revMap idSrc bdd) mapping = let (r, s) = runBDDContext (replace' bdd) emptyBDDState { bddIdSource = idSrc , bddRevMap = revMap } in ROBDD (bddRevMap s) (bddIdSource s) r where m = M.fromList mapping replace' Zero = return Zero replace' One = return One replace' (BDD low var high uid _) = memoize uid $ do low' <- replace' low high' <- replace' high let level = M.lookupDefault var var m -- ^ The remapped level - default is the current level fixSubgraph level uid low' high' -- innerState <- getBDDState -- let (r, s') = runBDDContext fixup emptyBDDState { bddIdSource = bddIdSource innerState -- , bddRevMap = bddRevMap innerState -- } -- putBDDState emptyBDDState { bddIdSource = bddIdSource s' -- , bddRevMap = bddRevMap s' -- } -- return r -- FIXME: I don't know that uid is the right thing to memoize on -- here... fixSubgraph level uid low high | level `varBddCmp` low == LT && level `varBddCmp` high == LT = {-memoize uid-} mk level low high | level `varBddCmp` low == EQ || level `varBddCmp` high == EQ = error ("Bad replace at " ++ show level ++ "(fixing " ++ show low ++ " and " ++ show high ++ " : " ++ show mapping) | otherwise = {-memoize uid $-} case low `bddCmp` high of EQ -> do l <- fixSubgraph level (nodeUID low) (lowEdge low) (lowEdge high) r <- fixSubgraph level (nodeUID high) (highEdge low) (highEdge high) mk (nodeVar low) l r LT -> do l <- fixSubgraph level (nodeUID low) (lowEdge low) high r <- fixSubgraph level (nodeUID high) (highEdge low) high mk (nodeVar low) l r GT -> do l <- fixSubgraph level (nodeUID low) low (lowEdge high) r <- fixSubgraph level (nodeUID high) low (highEdge high) mk (nodeVar high) l r -- | negate the given BDD. This implementation is somewhat more -- efficient than the naiive translation to @BDD ``impl`` False@. -- Unfortunately, it isn't as much of an improvement as it could be -- via destructive updates. -- -- O(|v|) neg :: ROBDD -> ROBDD neg (ROBDD _ _ bdd) = -- Everything gets re-allocated so don't bother trying to re-use the -- revmap or idsource let (r, s) = runBDDContext (negate' bdd) emptyBDDState in ROBDD (bddRevMap s) (bddIdSource s) r where negate' Zero = return One negate' One = return Zero negate' (BDD low var high uid _) = memoize uid $ do low' <- negate' low high' <- negate' high mk var low' high' -- FIXME: Implement constant-time negation via a flag on the ROBDD -- structure -- | Count the number of satisfying assignments to the BDD. -- -- O(|v|) where @v@ is the number of vertices in the BDD. satCount :: ROBDD -> Int satCount (ROBDD revMap _ bdd) = fst $ runBDDContext (count' bdd) emptyBDDState where varCount = maximum $ map (\(v,_,_) -> v) $ M.keys revMap safeNodeVar n = case n of Zero -> varCount + 1 One -> varCount + 1 _ -> nodeVar n count' Zero = return 0 count' One = return 1 count' (BDD low v high uid _) = memoize uid $ do l <- count' low r <- count' high let lc = 2 ^ (safeNodeVar low - v - 1) hc = 2 ^ (safeNodeVar high - v - 1) return (lc*l + hc*r) -- | Return an arbitrary assignment of values to variables to make the -- formula true. -- -- O(|v|) where @v@ is the number of vertices in the BDD. anySat :: ROBDD -> Maybe [(Var, Bool)] anySat (ROBDD _ _ Zero) = Nothing anySat (ROBDD _ _ One) = Just [] anySat (ROBDD _ _ bdd) = Just $ sat' bdd [] where sat' One acc = acc sat' Zero _ = error "anySat should not hit Zero" sat' (BDD low v high _ _) acc = case low of Zero -> (v, True) : sat' high acc _ -> (v, False) : sat' low acc -- | Extract all satisfying variable assignments to the BDD as a list of -- association lists. -- -- O(2^n) allSat :: ROBDD -> [[(Var, Bool)]] allSat (ROBDD _ _ Zero) = [] allSat (ROBDD _ _ One) = [[]] allSat (ROBDD _ _ bdd) = toList $ fst $ runBDDContext (sat' bdd) emptyBDDState where sat' Zero = return Seq.empty sat' One = return $ Seq.singleton [] sat' (BDD low v high uid _) = memoize uid $ do l <- sat' low r <- sat' high let l' = fmap ((v,False):) l r' = fmap ((v,True):) r return (l' >< r') -- | Extract all satisfying solutions to the BDD, but also ensuring -- that assignments are provided for all of the @activeVars@. A -- normal 'allSat' only provides assignments for variables appearing -- in the BDD (i.e. the variables whose values are not arbitrary). -- Some applications also need assignments for the arbitrary -- variables, but the allSat algorithm cannot know which variables to -- include without the activeVars parameter. -- -- O(2^n) allSat' :: ROBDD -> [Int] -> [[(Var, Bool)]] allSat' (ROBDD _ _ Zero) _ = [] allSat' (ROBDD _ _ One) activeVars = toList $ addArbitrary activeVars (Seq.singleton []) allSat' (ROBDD _ _ bdd) activeVars = toList $ fst $ runBDDContext (sat' bdd vars) emptyBDDState where vars = sort activeVars sat' Zero _ = return Seq.empty sat' One _ = return $ Seq.singleton [] sat' (BDD low v high uid _) vs = memoize uid $ do let (lLocalVars, lLowerVars) = arbitraryVars vs v low (rLocalVars, rLowerVars) = arbitraryVars vs v high -- The localVars are those that can be arbitrary on their -- respective branches. l <- sat' low lLowerVars r <- sat' high rLowerVars -- Computed the satisfying assignments for child trees - add in -- corrections to each branch before adding the assignment for -- this variable let l' = addArbitrary lLocalVars l r' = addArbitrary rLocalVars r l'' = fmap ((v, False):) l' r'' = fmap ((v, True):) r' return (l'' >< r'') arbitraryVars vs v Zero = (filter (/=v) vs, []) arbitraryVars vs v One = (filter (/=v) vs, []) arbitraryVars vs vLocal (BDD _ vNext _ _ _) = let (local, lower) = span (<vNext) vs in (filter (/=vLocal) local, lower) addArbitrary :: [Int] -> Seq [(Int, Bool)] -> Seq [(Int, Bool)] addArbitrary [] subsols = subsols addArbitrary (v:vs) subsols = let s' = addArbitrary vs subsols l = fmap ((v, False):) s' r = fmap ((v, True):) s' -- ^ This value can be arbitrary, so add solutions for both -- possible truth assignments. in l >< r -- TODO: compose -- | The MK operation. Re-use an existing BDD node if possible. -- Otherwise create a new node with the provided NodeId, updating the -- tables. This is not exported and just used internally. It lives -- in the BDDContext monad, which holds the result cache (revLookup -- map) mk :: Var -> BDD -> BDD -> BDDContext a BDD BDD mk v low high = do s <- getBDDState let revMap = bddRevMap s if low == high then return low -- Inputs identical, re-use else case revLookup v low high revMap of -- Return existing node Just node -> return node -- Make a new node Nothing -> revInsert v low high -- | Helpers for mk revLookup :: Var -> BDD -> BDD -> RevMap -> Maybe BDD revLookup v leftTarget rightTarget = M.lookup (v, nodeUID leftTarget, nodeUID rightTarget) -- | Compute the structural hash of a BDD node. The structural hash -- uses the variable number and the hashes of the children. hashNode :: Var -> BDD -> BDD -> Int hashNode v low high = v `hashWithSalt` nodeHash low `hashWithSalt` nodeHash high -- | Create a new node for v with the given high and low edges. -- Insert it into the revMap and return it. revInsert :: Var -> BDD -> BDD -> BDDContext a BDD BDD revInsert v lowTarget highTarget = do s <- getBDDState let revMap = bddRevMap s (nodeId:rest) = bddIdSource s revMap' = M.insert (v, nodeUID lowTarget, nodeUID highTarget) newNode revMap h = hashNode v lowTarget highTarget newNode = BDD lowTarget v highTarget nodeId h putBDDState s { bddRevMap = revMap' , bddIdSource = rest } return newNode -- | Evaluation contexts are tags used in the memoization table to -- differentiate memo entries from different contexts. This is -- important for the genericApply function, which has a set of -- memoized values for its arguments. It recursively calls the normal -- apply driver, which must maintain separate memoized values -- (otherwise you get incorrect results). type EvaluationContext = Int -- | Context for top-level operations stdCtxt :: EvaluationContext stdCtxt = 1 -- | A separate context (used as a key to caches) for inner -- evaluations. This is specifically for the fancy apply operations. innerCtxt :: EvaluationContext innerCtxt = 2
m4lvin/robbed
src/Data/ROBDD.hs
bsd-3-clause
23,084
0
17
5,870
5,108
2,711
2,397
315
6
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} module Copilot.Tools.CBMC ( Params (..) , defaultParams , genCBMC , atomPrefix , sbvPrefix , appendPrefix ) where import Copilot.Core import qualified Copilot.Compile.C99 as C99 import qualified Copilot.Compile.SBV as SBV import qualified System.IO as I import Text.PrettyPrint.HughesPJ -------------------------------------------------------------------------------- data Params = Params { numIterations :: Int } -------------------------------------------------------------------------------- defaultParams :: Params defaultParams = Params { numIterations = 10 } -------------------------------------------------------------------------------- atomPrefix, sbvPrefix :: Maybe String atomPrefix = Just "atm" sbvPrefix = Just "sbv" appendPrefix :: Maybe String -> String -> String appendPrefix (Just pre) name = pre ++ "_" ++ name appendPrefix Nothing name = name -------------------------------------------------------------------------------- genCBMC :: Params -> Spec -> IO () genCBMC params spec = do C99.compile (C99.defaultParams { C99.prefix = atomPrefix }) spec SBV.compile (SBV.defaultParams { SBV.prefix = sbvPrefix }) spec h <- I.openFile "cbmc_driver.c" I.WriteMode I.hPutStrLn h (render (driver params spec)) -------------------------------------------------------------------------------- driver :: Params -> Spec -> Doc driver Params { numIterations = k } spec = vcat [ text "#include <stdbool.h>" , text "#include <stdint.h>" , text "#include <assert.h>" , include atomPrefix C99.c99DirName C99.c99FileRoot , include sbvPrefix SBV.sbvDirName "copilot" , text "" , declNonDets spec , text "" , declExterns spec , text "" , sampleExterns spec , text "" , verifyObservers spec , text "" , text "int main (int argc, char const *argv[])" , text "{" , text " int i;" , text "" , text " for (i = 0; i < " <> int k <> text "; i++)" , text " {" , text " sampleExterns();" , text $ " " ++ appendPrefix atomPrefix "step();" , text $ " " ++ appendPrefix sbvPrefix "step();" , text " verify_observers();" , text " }" , text "" , text " return 0;" , text "}" ] where include prefix dir header = text "#include" <+> doubleQuotes ( text (appendPrefix prefix dir) <> text"/" <> text (appendPrefix prefix (header ++ ".h")) ) -------------------------------------------------------------------------------- declNonDets :: Spec -> Doc declNonDets = vcat . map declNonDet . externVars where declNonDet :: ExtVar -> Doc declNonDet ext@(ExtVar _ t) = typeSpec t <+> nonDetName ext -------------------------------------------------------------------------------- nonDetName :: ExtVar -> Doc nonDetName (ExtVar name t) = text ("nondet_" ++ name ++ "_") <> (typeSpec t) <> text "();" -------------------------------------------------------------------------------- declExterns :: Spec -> Doc declExterns = vcat . map declExtern . externVars where declExtern :: ExtVar -> Doc declExtern (ExtVar name t) = typeSpec t <+> text name <> semi -------------------------------------------------------------------------------- sampleExterns :: Spec -> Doc sampleExterns spec = vcat [ text "void sampleExterns()" , text "{" , text "" , nest 2 (vcat $ map sampleExtern (externVars spec)) , text "}" ] where sampleExtern :: ExtVar -> Doc sampleExtern ext@(ExtVar name _) = text name <+> text "=" <+> nonDetName ext -------------------------------------------------------------------------------- verifyObservers :: Spec -> Doc verifyObservers spec = vcat [ text "void verify_observers()" , text "{" , text "" , nest 2 (vcat $ map verifyObserver (specObservers spec)) , text "}" ] where verifyObserver :: Observer -> Doc verifyObserver (Observer name _ _) = text "assert(" <> text (appendPrefix atomPrefix name) <+> text "==" <+> text (appendPrefix sbvPrefix name) <> text ");" -------------------------------------------------------------------------------- typeSpec :: UType -> Doc typeSpec UType { uTypeType = t } = text $ case t of Bool -> "bool" Int8 -> "int8_t" Int16 -> "int16_t" Int32 -> "int32_t" Int64 -> "int64_t" Word8 -> "uint8_t" Word16 -> "uint16_t" Word32 -> "uint32_t" Word64 -> "uint64_t" Float -> "float" Double -> "double" --------------------------------------------------------------------------------
leepike/copilot-cbmc
src/Copilot/Tools/CBMC.hs
bsd-3-clause
4,768
0
15
872
1,180
613
567
111
11
-- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- | Interface to the essential parts of the Feldspar language. High-level -- libraries have to be imported separately. module Feldspar ( module Feldspar.Prelude , module Feldspar.Core ) where import qualified Prelude -- In order to be able to use the Feldspar module in GHCi without getting name -- clashes. import Feldspar.Prelude import Feldspar.Core
rCEx/feldspar-lang-small
src/Feldspar.hs
bsd-3-clause
1,973
0
5
369
63
52
11
6
0
module Main where import System.Environment import DeepAccelerate import IO main = do args <- getArgs let [inImg,outImg] = args img1 <- readImgAsAccelerateArray inImg newImg <- printTime (run (brightenBy 20 img1)) writeAccelerateImg outImg newImg
robstewart57/small-image-processing-dsl-implementations
haskell/small-image-processing-dsl/app/deep-accelerate/prog1.hs
bsd-3-clause
270
0
12
56
85
42
43
10
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.KMS.Types -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. module Network.AWS.KMS.Types ( -- * Service KMS -- ** Error , JSONError -- * KeyUsageType , KeyUsageType (..) -- * KeyMetadata , KeyMetadata , keyMetadata , kmAWSAccountId , kmArn , kmCreationDate , kmDescription , kmEnabled , kmKeyId , kmKeyUsage -- * DataKeySpec , DataKeySpec (..) -- * GrantConstraints , GrantConstraints , grantConstraints , gcEncryptionContextEquals , gcEncryptionContextSubset -- * AliasListEntry , AliasListEntry , aliasListEntry , aleAliasArn , aleAliasName , aleTargetKeyId -- * GrantListEntry , GrantListEntry , grantListEntry , gleConstraints , gleGrantId , gleGranteePrincipal , gleIssuingAccount , gleOperations , gleRetiringPrincipal -- * GrantOperation , GrantOperation (..) -- * KeyListEntry , KeyListEntry , keyListEntry , kleKeyArn , kleKeyId ) where import Network.AWS.Prelude import Network.AWS.Signing import qualified GHC.Exts -- | Version @2014-11-01@ of the Amazon Key Management Service service. data KMS instance AWSService KMS where type Sg KMS = V4 type Er KMS = JSONError service = service' where service' :: Service KMS service' = Service { _svcAbbrev = "KMS" , _svcPrefix = "kms" , _svcVersion = "2014-11-01" , _svcTargetPrefix = Just "TrentService" , _svcJSONVersion = Just "1.1" , _svcHandle = handle , _svcRetry = retry } handle :: Status -> Maybe (LazyByteString -> ServiceError JSONError) handle = jsonError statusSuccess service' retry :: Retry KMS retry = Exponential { _retryBase = 0.05 , _retryGrowth = 2 , _retryAttempts = 5 , _retryCheck = check } check :: Status -> JSONError -> Bool check (statusCode -> s) (awsErrorCode -> e) | s == 500 = True -- General Server Error | s == 509 = True -- Limit Exceeded | s == 503 = True -- Service Unavailable | otherwise = False data KeyUsageType = EncryptDecrypt -- ^ ENCRYPT_DECRYPT deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable KeyUsageType instance FromText KeyUsageType where parser = takeLowerText >>= \case "encrypt_decrypt" -> pure EncryptDecrypt e -> fail $ "Failure parsing KeyUsageType from " ++ show e instance ToText KeyUsageType where toText EncryptDecrypt = "ENCRYPT_DECRYPT" instance ToByteString KeyUsageType instance ToHeader KeyUsageType instance ToQuery KeyUsageType instance FromJSON KeyUsageType where parseJSON = parseJSONText "KeyUsageType" instance ToJSON KeyUsageType where toJSON = toJSONText data KeyMetadata = KeyMetadata { _kmAWSAccountId :: Maybe Text , _kmArn :: Maybe Text , _kmCreationDate :: Maybe POSIX , _kmDescription :: Maybe Text , _kmEnabled :: Maybe Bool , _kmKeyId :: Text , _kmKeyUsage :: Maybe KeyUsageType } deriving (Eq, Read, Show) -- | 'KeyMetadata' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'kmAWSAccountId' @::@ 'Maybe' 'Text' -- -- * 'kmArn' @::@ 'Maybe' 'Text' -- -- * 'kmCreationDate' @::@ 'Maybe' 'UTCTime' -- -- * 'kmDescription' @::@ 'Maybe' 'Text' -- -- * 'kmEnabled' @::@ 'Maybe' 'Bool' -- -- * 'kmKeyId' @::@ 'Text' -- -- * 'kmKeyUsage' @::@ 'Maybe' 'KeyUsageType' -- keyMetadata :: Text -- ^ 'kmKeyId' -> KeyMetadata keyMetadata p1 = KeyMetadata { _kmKeyId = p1 , _kmAWSAccountId = Nothing , _kmArn = Nothing , _kmCreationDate = Nothing , _kmEnabled = Nothing , _kmDescription = Nothing , _kmKeyUsage = Nothing } -- | Account ID number. kmAWSAccountId :: Lens' KeyMetadata (Maybe Text) kmAWSAccountId = lens _kmAWSAccountId (\s a -> s { _kmAWSAccountId = a }) -- | Key ARN (Amazon Resource Name). kmArn :: Lens' KeyMetadata (Maybe Text) kmArn = lens _kmArn (\s a -> s { _kmArn = a }) -- | Date the key was created. kmCreationDate :: Lens' KeyMetadata (Maybe UTCTime) kmCreationDate = lens _kmCreationDate (\s a -> s { _kmCreationDate = a }) . mapping _Time -- | The description of the key. kmDescription :: Lens' KeyMetadata (Maybe Text) kmDescription = lens _kmDescription (\s a -> s { _kmDescription = a }) -- | Value that specifies whether the key is enabled. kmEnabled :: Lens' KeyMetadata (Maybe Bool) kmEnabled = lens _kmEnabled (\s a -> s { _kmEnabled = a }) -- | Unique identifier for the key. kmKeyId :: Lens' KeyMetadata Text kmKeyId = lens _kmKeyId (\s a -> s { _kmKeyId = a }) -- | A value that specifies what operation(s) the key can perform. kmKeyUsage :: Lens' KeyMetadata (Maybe KeyUsageType) kmKeyUsage = lens _kmKeyUsage (\s a -> s { _kmKeyUsage = a }) instance FromJSON KeyMetadata where parseJSON = withObject "KeyMetadata" $ \o -> KeyMetadata <$> o .:? "AWSAccountId" <*> o .:? "Arn" <*> o .:? "CreationDate" <*> o .:? "Description" <*> o .:? "Enabled" <*> o .: "KeyId" <*> o .:? "KeyUsage" instance ToJSON KeyMetadata where toJSON KeyMetadata{..} = object [ "AWSAccountId" .= _kmAWSAccountId , "KeyId" .= _kmKeyId , "Arn" .= _kmArn , "CreationDate" .= _kmCreationDate , "Enabled" .= _kmEnabled , "Description" .= _kmDescription , "KeyUsage" .= _kmKeyUsage ] data DataKeySpec = AES128 -- ^ AES_128 | AES256 -- ^ AES_256 deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable DataKeySpec instance FromText DataKeySpec where parser = takeLowerText >>= \case "aes_128" -> pure AES128 "aes_256" -> pure AES256 e -> fail $ "Failure parsing DataKeySpec from " ++ show e instance ToText DataKeySpec where toText = \case AES128 -> "AES_128" AES256 -> "AES_256" instance ToByteString DataKeySpec instance ToHeader DataKeySpec instance ToQuery DataKeySpec instance FromJSON DataKeySpec where parseJSON = parseJSONText "DataKeySpec" instance ToJSON DataKeySpec where toJSON = toJSONText data GrantConstraints = GrantConstraints { _gcEncryptionContextEquals :: Map Text Text , _gcEncryptionContextSubset :: Map Text Text } deriving (Eq, Read, Show) -- | 'GrantConstraints' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gcEncryptionContextEquals' @::@ 'HashMap' 'Text' 'Text' -- -- * 'gcEncryptionContextSubset' @::@ 'HashMap' 'Text' 'Text' -- grantConstraints :: GrantConstraints grantConstraints = GrantConstraints { _gcEncryptionContextSubset = mempty , _gcEncryptionContextEquals = mempty } -- | The constraint contains additional key/value pairs that serve to further -- limit the grant. gcEncryptionContextEquals :: Lens' GrantConstraints (HashMap Text Text) gcEncryptionContextEquals = lens _gcEncryptionContextEquals (\s a -> s { _gcEncryptionContextEquals = a }) . _Map -- | The constraint equals the full encryption context. gcEncryptionContextSubset :: Lens' GrantConstraints (HashMap Text Text) gcEncryptionContextSubset = lens _gcEncryptionContextSubset (\s a -> s { _gcEncryptionContextSubset = a }) . _Map instance FromJSON GrantConstraints where parseJSON = withObject "GrantConstraints" $ \o -> GrantConstraints <$> o .:? "EncryptionContextEquals" .!= mempty <*> o .:? "EncryptionContextSubset" .!= mempty instance ToJSON GrantConstraints where toJSON GrantConstraints{..} = object [ "EncryptionContextSubset" .= _gcEncryptionContextSubset , "EncryptionContextEquals" .= _gcEncryptionContextEquals ] data AliasListEntry = AliasListEntry { _aleAliasArn :: Maybe Text , _aleAliasName :: Maybe Text , _aleTargetKeyId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'AliasListEntry' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'aleAliasArn' @::@ 'Maybe' 'Text' -- -- * 'aleAliasName' @::@ 'Maybe' 'Text' -- -- * 'aleTargetKeyId' @::@ 'Maybe' 'Text' -- aliasListEntry :: AliasListEntry aliasListEntry = AliasListEntry { _aleAliasName = Nothing , _aleAliasArn = Nothing , _aleTargetKeyId = Nothing } -- | String that contains the key ARN. aleAliasArn :: Lens' AliasListEntry (Maybe Text) aleAliasArn = lens _aleAliasArn (\s a -> s { _aleAliasArn = a }) -- | String that contains the alias. aleAliasName :: Lens' AliasListEntry (Maybe Text) aleAliasName = lens _aleAliasName (\s a -> s { _aleAliasName = a }) -- | String that contains the key identifier pointed to by the alias. aleTargetKeyId :: Lens' AliasListEntry (Maybe Text) aleTargetKeyId = lens _aleTargetKeyId (\s a -> s { _aleTargetKeyId = a }) instance FromJSON AliasListEntry where parseJSON = withObject "AliasListEntry" $ \o -> AliasListEntry <$> o .:? "AliasArn" <*> o .:? "AliasName" <*> o .:? "TargetKeyId" instance ToJSON AliasListEntry where toJSON AliasListEntry{..} = object [ "AliasName" .= _aleAliasName , "AliasArn" .= _aleAliasArn , "TargetKeyId" .= _aleTargetKeyId ] data GrantListEntry = GrantListEntry { _gleConstraints :: Maybe GrantConstraints , _gleGrantId :: Maybe Text , _gleGranteePrincipal :: Maybe Text , _gleIssuingAccount :: Maybe Text , _gleOperations :: List "Operations" GrantOperation , _gleRetiringPrincipal :: Maybe Text } deriving (Eq, Read, Show) -- | 'GrantListEntry' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gleConstraints' @::@ 'Maybe' 'GrantConstraints' -- -- * 'gleGrantId' @::@ 'Maybe' 'Text' -- -- * 'gleGranteePrincipal' @::@ 'Maybe' 'Text' -- -- * 'gleIssuingAccount' @::@ 'Maybe' 'Text' -- -- * 'gleOperations' @::@ ['GrantOperation'] -- -- * 'gleRetiringPrincipal' @::@ 'Maybe' 'Text' -- grantListEntry :: GrantListEntry grantListEntry = GrantListEntry { _gleGrantId = Nothing , _gleGranteePrincipal = Nothing , _gleRetiringPrincipal = Nothing , _gleIssuingAccount = Nothing , _gleOperations = mempty , _gleConstraints = Nothing } -- | Specifies the conditions under which the actions specified by the 'Operations' -- parameter are allowed. gleConstraints :: Lens' GrantListEntry (Maybe GrantConstraints) gleConstraints = lens _gleConstraints (\s a -> s { _gleConstraints = a }) -- | Unique grant identifier. gleGrantId :: Lens' GrantListEntry (Maybe Text) gleGrantId = lens _gleGrantId (\s a -> s { _gleGrantId = a }) -- | The principal that receives the grant permission. gleGranteePrincipal :: Lens' GrantListEntry (Maybe Text) gleGranteePrincipal = lens _gleGranteePrincipal (\s a -> s { _gleGranteePrincipal = a }) -- | The account under which the grant was issued. gleIssuingAccount :: Lens' GrantListEntry (Maybe Text) gleIssuingAccount = lens _gleIssuingAccount (\s a -> s { _gleIssuingAccount = a }) -- | List of operations permitted by the grant. This can be any combination of one -- or more of the following values: Decrypt Encrypt GenerateDataKey GenerateDataKeyWithoutPlaintext -- ReEncryptFrom ReEncryptTo CreateGrant gleOperations :: Lens' GrantListEntry [GrantOperation] gleOperations = lens _gleOperations (\s a -> s { _gleOperations = a }) . _List -- | The principal that can retire the account. gleRetiringPrincipal :: Lens' GrantListEntry (Maybe Text) gleRetiringPrincipal = lens _gleRetiringPrincipal (\s a -> s { _gleRetiringPrincipal = a }) instance FromJSON GrantListEntry where parseJSON = withObject "GrantListEntry" $ \o -> GrantListEntry <$> o .:? "Constraints" <*> o .:? "GrantId" <*> o .:? "GranteePrincipal" <*> o .:? "IssuingAccount" <*> o .:? "Operations" .!= mempty <*> o .:? "RetiringPrincipal" instance ToJSON GrantListEntry where toJSON GrantListEntry{..} = object [ "GrantId" .= _gleGrantId , "GranteePrincipal" .= _gleGranteePrincipal , "RetiringPrincipal" .= _gleRetiringPrincipal , "IssuingAccount" .= _gleIssuingAccount , "Operations" .= _gleOperations , "Constraints" .= _gleConstraints ] data GrantOperation = GOCreateGrant -- ^ CreateGrant | GODecrypt -- ^ Decrypt | GOEncrypt -- ^ Encrypt | GOGenerateDataKey -- ^ GenerateDataKey | GOGenerateDataKeyWithoutPlaintext -- ^ GenerateDataKeyWithoutPlaintext | GOReEncryptFrom -- ^ ReEncryptFrom | GOReEncryptTo -- ^ ReEncryptTo | GORetireGrant -- ^ RetireGrant deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable GrantOperation instance FromText GrantOperation where parser = takeLowerText >>= \case "creategrant" -> pure GOCreateGrant "decrypt" -> pure GODecrypt "encrypt" -> pure GOEncrypt "generatedatakey" -> pure GOGenerateDataKey "generatedatakeywithoutplaintext" -> pure GOGenerateDataKeyWithoutPlaintext "reencryptfrom" -> pure GOReEncryptFrom "reencryptto" -> pure GOReEncryptTo "retiregrant" -> pure GORetireGrant e -> fail $ "Failure parsing GrantOperation from " ++ show e instance ToText GrantOperation where toText = \case GOCreateGrant -> "CreateGrant" GODecrypt -> "Decrypt" GOEncrypt -> "Encrypt" GOGenerateDataKey -> "GenerateDataKey" GOGenerateDataKeyWithoutPlaintext -> "GenerateDataKeyWithoutPlaintext" GOReEncryptFrom -> "ReEncryptFrom" GOReEncryptTo -> "ReEncryptTo" GORetireGrant -> "RetireGrant" instance ToByteString GrantOperation instance ToHeader GrantOperation instance ToQuery GrantOperation instance FromJSON GrantOperation where parseJSON = parseJSONText "GrantOperation" instance ToJSON GrantOperation where toJSON = toJSONText data KeyListEntry = KeyListEntry { _kleKeyArn :: Maybe Text , _kleKeyId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'KeyListEntry' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'kleKeyArn' @::@ 'Maybe' 'Text' -- -- * 'kleKeyId' @::@ 'Maybe' 'Text' -- keyListEntry :: KeyListEntry keyListEntry = KeyListEntry { _kleKeyId = Nothing , _kleKeyArn = Nothing } -- | ARN of the key. kleKeyArn :: Lens' KeyListEntry (Maybe Text) kleKeyArn = lens _kleKeyArn (\s a -> s { _kleKeyArn = a }) -- | Unique identifier of the key. kleKeyId :: Lens' KeyListEntry (Maybe Text) kleKeyId = lens _kleKeyId (\s a -> s { _kleKeyId = a }) instance FromJSON KeyListEntry where parseJSON = withObject "KeyListEntry" $ \o -> KeyListEntry <$> o .:? "KeyArn" <*> o .:? "KeyId" instance ToJSON KeyListEntry where toJSON KeyListEntry{..} = object [ "KeyId" .= _kleKeyId , "KeyArn" .= _kleKeyArn ]
romanb/amazonka
amazonka-kms/gen/Network/AWS/KMS/Types.hs
mpl-2.0
16,856
0
21
4,572
3,093
1,738
1,355
-1
-1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ms-MY"> <title>Active Scan Rules | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
rnehra01/zap-extensions
src/org/zaproxy/zap/extension/ascanrules/resources/help_ms_MY/helpset_ms_MY.hs
apache-2.0
979
80
66
161
417
211
206
-1
-1
{-# LANGUAGE OverloadedStrings #-} module TeamInfoFor where import qualified Github.Auth as Github import qualified Github.Teams as Github import System.Environment (getArgs) main = do args <- getArgs result <- case args of [team_id, token] -> Github.teamInfoFor' (Just $ Github.GithubOAuth token) (read team_id) [team_id] -> Github.teamInfoFor (read team_id) _ -> error "usage: TeamInfoFor <team_id> [auth token]" case result of Left err -> putStrLn $ "Error: " ++ show err Right team -> putStrLn $ show team
beni55/github
samples/Teams/TeamInfoFor.hs
bsd-3-clause
616
0
15
180
163
85
78
14
4
{- (By Chris Smith) Reimplementation of gloss (minus bitmaps) in terms of Fay. This is a proof of concept that Fay is in a state where it can support use cases like gloss-web on the client. TODO: - Fix the problem with unary negation - Implement support for events and game mode To try it out, skip the boilerplate section at the top; in the final implementation, it will eventually be moved to a different module and imported. Change the definition of go to one of drawIt, animateIt, or simulateIt to try the various modes. -} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE EmptyDataDecls #-} module CodeWorld where import Prelude import FFI data Element getElementById :: String -> Fay Element getElementById = ffi "document['getElementById'](%1)" focusElement :: Element -> Fay () focusElement = ffi "%1.focus()" data Event addEventListener :: String -> Bool -> (Event -> Fay Bool) -> Fay () addEventListener = ffi "window['addEventListener'](%1,%3,%2)" --getEventKeyCode :: Event -> Fay String --getEventKeyCode = ffi "%1['keyCode']" getEventMouseButton :: Event -> Fay Int getEventMouseButton = ffi "%1['button']" data Timer setInterval :: Double -> Fay () -> Fay Timer setInterval = ffi "window['setInterval'](%2,%1)" data Ref a newRef :: a -> Fay (Ref a) newRef = ffi "new Fay$$Ref(%1)" writeRef :: Ref a -> a -> Fay () writeRef = ffi "Fay$$writeRef(%1,%2)" readRef :: Ref a -> Fay a readRef = ffi "Fay$$readRef(%1)" currentTimeMillis :: Fay Double currentTimeMillis = ffi "(Date.now?Date.now():new Date().getTime())" data Context getContext :: Element -> String -> Fay Context getContext = ffi "%1['getContext'](%2)" clearRect :: Context -> Double -> Double -> Double -> Double -> Fay () clearRect = ffi "%1['clearRect'](%2,%3,%4,%5)" save :: Context -> Fay () save = ffi "%1['save']()" restore :: Context -> Fay () restore = ffi "%1['restore']()" canvasTranslate :: Context -> Double -> Double -> Fay () canvasTranslate = ffi "%1['translate'](%2,%3)" canvasScale :: Context -> Double -> Double -> Fay () canvasScale = ffi "%1['scale'](%2,%3)" transform :: Context -> Double -> Double -> Double -> Double -> Double -> Double -> Fay () transform = ffi "%1['transform'](%2,%3,%4,%5,%6,%7)" setTextAlign :: Context -> String -> Fay () setTextAlign = ffi "%1['textAlign']=%2" setTextBaseline :: Context -> String -> Fay () setTextBaseline = ffi "%1['textBaseline']=%2" setLineWidth :: Context -> Double -> Fay () setLineWidth = ffi "%1['lineWidth']=%2" setFont :: Context -> String -> Fay () setFont = ffi "%1['font']=%2" setStrokeStyle :: Context -> String -> Fay () setStrokeStyle = ffi "%1['strokeStyle']=%2" setFillStyle :: Context -> String -> Fay () setFillStyle = ffi "%1['fillStyle']=%2" beginPath :: Context -> Fay () beginPath = ffi "%1['beginPath']()" closePath :: Context -> Fay () closePath = ffi "%1['closePath']()" fill :: Context -> Fay () fill = ffi "%1['fill']()" stroke :: Context -> Fay () stroke = ffi "%1['stroke']()" fillText :: Context ->String -> Double -> Double -> Fay () fillText = ffi "%1['fillText'](%2,%3,%4)" moveTo :: Context -> Double -> Double -> Fay () moveTo = ffi "%1['moveTo'](%2,%3)" lineTo :: Context -> Double -> Double -> Fay () lineTo = ffi "%1['lineTo'](%2,%3)" canvasArc :: Context -> Double -> Double -> Double -> Double -> Double -> Bool -> Fay () canvasArc = ffi "%1['arc'](%2,%3,%4,%5,%6,%7)" -- Special functions defined in codeworld.js getSpecialKey :: Event -> Fay String getSpecialKey = ffi "window.getSpecialKey(%1)" getPressedKey :: Event -> Fay String getPressedKey = ffi "window.getPressedKey(%1)" getReleasedKey :: Event -> Fay String getReleasedKey = ffi "window.getReleasedKey(%1)" stopEvent :: Event -> Fay () stopEvent = ffi "window.stopEvent(%1)" mouseToElementX :: Event -> Fay Double mouseToElementX = ffi "window.mouseToElementX(%1)" mouseToElementY :: Event -> Fay Double mouseToElementY = ffi "window.mouseToElementY(%1)" type Transform = (Double, Double, Double, Double, Double, Double) translateTransform :: Double -> Double -> Transform -> Transform translateTransform x y (a,b,c,d,e,f) = (a, b, c, d, a * x + c * y + e, b * x + d * y + f) scaleTransform :: Double -> Double -> Transform -> Transform scaleTransform x y (a,b,c,d,e,f) = (x*a, x*b, y*c, y*d, e, f) rotateTransform :: Double -> Transform -> Transform rotateTransform r (a,b,c,d,e,f) = let th = r * pi / 180 in (a * cos th + c * sin th, b * cos th + d * sin th, c * cos th - a * sin th, d * cos th - b * sin th, e, f) withTransform :: Context -> Transform -> Fay () -> Fay () withTransform ctx (a,b,c,d,e,f) action = do save ctx transform ctx a b c d e f beginPath ctx action restore ctx data Color = RGBA Double Double Double Double white, black :: Color white = RGBA 1 1 1 1 black = RGBA 0 0 0 1 red, green, blue, cyan, magenta, yellow :: Color red = RGBA 1 0 0 1 green = RGBA 0 1 0 1 blue = RGBA 0 0 1 1 yellow = RGBA 1 1 0 1 cyan = RGBA 0 1 1 1 magenta = RGBA 1 0 1 1 orange, rose, chartreuse, aquamarine, violet, azure :: Color orange = RGBA 1.0 0.5 0.0 1 rose = RGBA 1.0 0.0 0.5 1 chartreuse = RGBA 0.5 1.0 0.0 1 aquamarine = RGBA 0.0 1.0 0.5 1 violet = RGBA 0.5 0.0 1.0 1 azure = RGBA 0.0 0.5 1.0 1 light :: Color -> Color light (RGBA r g b a) = RGBA (min 1 (r + 0.2)) (min 1 (g + 0.2)) (min 1 (b + 0.2)) a dark :: Color -> Color dark (RGBA r g b a) = RGBA (max 0 (r - 0.2)) (max 0 (g - 0.2)) (max 0 (b - 0.2)) a gray, grey :: Double -> Color gray = grey grey k = RGBA k k k 1 type Point = (Double, Double) type Vector = Point data Picture = Polygon [Point] | Line [Point] | ThickArc Double Double Double Double | Text String | Color Color Picture | Translate Double Double Picture | Scale Double Double Picture | Rotate Double Picture | Pictures [Picture] blank :: Picture blank = Pictures [] polygon :: [Point] -> Picture polygon = Polygon line :: [Point] -> Picture line = Line thickArc :: Double -> Double -> Double -> Double -> Picture thickArc = ThickArc arc :: Double -> Double -> Double -> Picture arc b e r = thickArc b e r 0 circle :: Double -> Picture circle = arc 0 360 circleSolid :: Double -> Picture circleSolid r = thickCircle (r/2) r thickCircle :: Double -> Double -> Picture thickCircle = thickArc 0 360 text :: String -> Picture text = Text color :: Color -> Picture -> Picture color = Color translate :: Double -> Double -> Picture -> Picture translate = Translate scale :: Double -> Double -> Picture -> Picture scale = Scale rotate :: Double -> Picture -> Picture rotate = Rotate pictures :: [Picture] -> Picture pictures = Pictures rectangleSolid :: Double -> Double -> Picture rectangleSolid w h = polygon [ (0-w/2, 0-h/2), (w/2, 0-h/2), (w/2, h/2), (0-w/2, h/2) ] rectangleWire :: Double -> Double -> Picture rectangleWire w h = line [ (0-w/2, 0-h/2), (w/2, 0-h/2), (w/2, h/2), (0-w/2, h/2), (0-w/2, 0-h/2) ] pathFromPoints :: Context -> [Point] -> Fay () pathFromPoints _ [] = return () pathFromPoints ctx ((sx,sy):ps) = do moveTo ctx sx sy forM_ ps $ \(x,y) -> lineTo ctx x y drawPicture :: Context -> Transform -> Picture -> Fay () drawPicture ctx t (Polygon ps) = do withTransform ctx t $ pathFromPoints ctx ps fill ctx drawPicture ctx t (Line ps) = do withTransform ctx t $ pathFromPoints ctx ps stroke ctx drawPicture ctx t (ThickArc b e r w) = do save ctx withTransform ctx t $ do when (r > 0) $ canvasArc ctx 0 0 r (b*pi/180) (e*pi/180) False closePath ctx when (w > 0) $ setLineWidth ctx w stroke ctx restore ctx drawPicture ctx t (Text txt) = withTransform ctx t $ do canvasScale ctx 1 (0-1) fillText ctx txt 0 0 drawPicture ctx t (Color (RGBA r g b a) p) = do let str = "rgba(" ++ show (r * 100) ++ "%," ++ show (g * 100) ++ "%," ++ show (b * 100) ++ "%," ++ show a ++ ")" save ctx setStrokeStyle ctx str setFillStyle ctx str drawPicture ctx t p restore ctx drawPicture ctx t (Translate x y p) = drawPicture ctx (translateTransform x y t) p drawPicture ctx t (Scale x y p) = drawPicture ctx (scaleTransform x y t) p drawPicture ctx t (Rotate r p) = drawPicture ctx (rotateTransform r t) p drawPicture ctx t (Pictures ps) = mapM_ (drawPicture ctx t) ps withCanvas :: (Element -> Context -> Fay ()) -> Fay () withCanvas go = addEventListener "load" False $ const $ do canvas <- getElementById "canvas" ctx <- getContext canvas "2d" go canvas ctx return False drawOn :: Context -> Picture -> Fay () drawOn ctx pic = do clearRect ctx 0 0 500 500 save ctx canvasTranslate ctx 250 250 canvasScale ctx 1 (0-1) setTextAlign ctx "left" setTextBaseline ctx "alphabetic" setLineWidth ctx 0 setFont ctx "100px Times Roman" drawPicture ctx (1,0,0,1,0,0) pic restore ctx displayInCanvas :: Picture -> Fay () displayInCanvas pic = withCanvas $ \ canvas ctx -> drawOn ctx pic animateInCanvas :: (Double -> Picture) -> Fay () animateInCanvas anim = withCanvas $ \ canvas ctx -> do startTime <- currentTimeMillis setInterval 30 $ do currentTime <- currentTimeMillis let t = (currentTime - startTime) / 1000 drawOn ctx (anim t) return () data SimState a = SimState a withSimState :: (a -> a) -> Ref (SimState a) -> Fay a withSimState f ref = do SimState val <- readRef ref let newVal = f val writeRef ref (SimState newVal) return newVal -- XXX: This is a hack to pretend to have a decent purely functional -- random number generator. It should be replaced by a correct -- implementation as soon as possible. unsafeRand :: Double -> Double -> Double unsafeRand = ffi "Math.random()*%2+%1" data StdGen = StdGen newStdGen :: Fay StdGen newStdGen = return StdGen splitR :: StdGen -> (StdGen, StdGen) splitR g = (g, g) randomR :: (Double, Double) -> StdGen -> (Double, StdGen) randomR (lo, hi) g = (unsafeRand lo (hi - lo), g) simulateInCanvas :: (StdGen -> a) -> (Double -> a -> a) -> (a -> Picture) -> Fay () simulateInCanvas i s d = withCanvas $ \ canvas ctx -> do startTime <- currentTimeMillis g <- newStdGen valueRef <- newRef (SimState (i g)) timeRef <- newRef startTime setInterval 30 $ do lastTime <- readRef timeRef currentTime <- currentTimeMillis let dt = (currentTime - lastTime) / 1000 val <- withSimState (s dt) valueRef writeRef timeRef currentTime drawOn ctx (d val) return () data GameEvent = KeyPressEvent String | KeyReleaseEvent String | MousePressEvent Int Point | MouseReleaseEvent Int Point | MouseMoveEvent Point deriving Show playInCanvas :: (StdGen -> a) -> (Double -> a -> a) -> (GameEvent -> a -> a) -> (a -> Picture) -> Fay () playInCanvas i s e d = withCanvas $ \ canvas ctx -> do startTime <- currentTimeMillis g <- newStdGen valueRef <- newRef (SimState (i g)) timeRef <- newRef startTime addEventListener "keydown" False $ \ev -> do k <- getSpecialKey ev if k == "None" then return True else do withSimState (e (KeyPressEvent k)) valueRef stopEvent ev return False addEventListener "keypress" False $ \ev -> do k <- getPressedKey ev if k == "None" then return True else do withSimState (e (KeyPressEvent k)) valueRef stopEvent ev return False addEventListener "keyup" False $ \ev -> do k <- getReleasedKey ev if k == "None" then return True else do withSimState (e (KeyReleaseEvent k)) valueRef stopEvent ev return False addEventListener "mousedown" False $ \ev -> do focusElement canvas x <- mouseToElementX ev y <- mouseToElementY ev if abs x > 250 || abs y > 250 then return True else do b <- getEventMouseButton ev withSimState (e (MousePressEvent b (x,y))) valueRef stopEvent ev return False addEventListener "mouseup" False $ \ev -> do x <- mouseToElementX ev y <- mouseToElementY ev if abs x > 250 || abs y > 250 then return True else do b <- getEventMouseButton ev withSimState (e (MouseReleaseEvent b (x,y))) valueRef stopEvent ev return False addEventListener "mousemove" False $ \ev -> do x <- mouseToElementX ev y <- mouseToElementY ev if abs x > 250 || abs y > 250 then return True else do withSimState (e (MouseMoveEvent (x,y))) valueRef stopEvent ev return False setInterval 30 $ do lastTime <- readRef timeRef currentTime <- currentTimeMillis let dt = (currentTime - lastTime) / 1000 val <- withSimState (s dt) valueRef writeRef timeRef currentTime drawOn ctx (d val) return ()
beni55/fay
examples/CodeWorld.hs
bsd-3-clause
13,427
0
21
3,537
4,848
2,427
2,421
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.FetchUtils -- Copyright : (c) David Himmelstrup 2005 -- Duncan Coutts 2011 -- License : BSD-like -- -- Maintainer : cabal-devel@gmail.com -- Stability : provisional -- Portability : portable -- -- Functions for fetching packages ----------------------------------------------------------------------------- module Distribution.Client.FetchUtils ( -- * fetching packages fetchPackage, isFetched, checkFetched, -- ** specifically for repo packages fetchRepoTarball, -- * fetching other things downloadIndex, ) where import Distribution.Client.Types import Distribution.Client.HttpUtils ( downloadURI, isOldHackageURI ) import Distribution.Package ( PackageId, packageName, packageVersion ) import Distribution.Simple.Utils ( notice, info, setupMessage ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity ) import Data.Maybe import System.Directory ( doesFileExist, createDirectoryIfMissing, getTemporaryDirectory ) import System.IO ( openTempFile, hClose ) import System.FilePath ( (</>), (<.>) ) import qualified System.FilePath.Posix as FilePath.Posix ( combine, joinPath ) import Network.URI ( URI(uriPath) ) -- ------------------------------------------------------------ -- * Actually fetch things -- ------------------------------------------------------------ -- | Returns @True@ if the package has already been fetched -- or does not need fetching. -- isFetched :: PackageLocation (Maybe FilePath) -> IO Bool isFetched loc = case loc of LocalUnpackedPackage _dir -> return True LocalTarballPackage _file -> return True RemoteTarballPackage _uri local -> return (isJust local) RepoTarballPackage repo pkgid _ -> doesFileExist (packageFile repo pkgid) checkFetched :: PackageLocation (Maybe FilePath) -> IO (Maybe (PackageLocation FilePath)) checkFetched loc = case loc of LocalUnpackedPackage dir -> return (Just $ LocalUnpackedPackage dir) LocalTarballPackage file -> return (Just $ LocalTarballPackage file) RemoteTarballPackage uri (Just file) -> return (Just $ RemoteTarballPackage uri file) RepoTarballPackage repo pkgid (Just file) -> return (Just $ RepoTarballPackage repo pkgid file) RemoteTarballPackage _uri Nothing -> return Nothing RepoTarballPackage repo pkgid Nothing -> do let file = packageFile repo pkgid exists <- doesFileExist file if exists then return (Just $ RepoTarballPackage repo pkgid file) else return Nothing -- | Fetch a package if we don't have it already. -- fetchPackage :: Verbosity -> PackageLocation (Maybe FilePath) -> IO (PackageLocation FilePath) fetchPackage verbosity loc = case loc of LocalUnpackedPackage dir -> return (LocalUnpackedPackage dir) LocalTarballPackage file -> return (LocalTarballPackage file) RemoteTarballPackage uri (Just file) -> return (RemoteTarballPackage uri file) RepoTarballPackage repo pkgid (Just file) -> return (RepoTarballPackage repo pkgid file) RemoteTarballPackage uri Nothing -> do path <- downloadTarballPackage uri return (RemoteTarballPackage uri path) RepoTarballPackage repo pkgid Nothing -> do local <- fetchRepoTarball verbosity repo pkgid return (RepoTarballPackage repo pkgid local) where downloadTarballPackage uri = do notice verbosity ("Downloading " ++ show uri) tmpdir <- getTemporaryDirectory (path, hnd) <- openTempFile tmpdir "cabal-.tar.gz" hClose hnd downloadURI verbosity uri path return path -- | Fetch a repo package if we don't have it already. -- fetchRepoTarball :: Verbosity -> Repo -> PackageId -> IO FilePath fetchRepoTarball verbosity repo pkgid = do fetched <- doesFileExist (packageFile repo pkgid) if fetched then do info verbosity $ display pkgid ++ " has already been downloaded." return (packageFile repo pkgid) else do setupMessage verbosity "Downloading" pkgid downloadRepoPackage where downloadRepoPackage = case repoKind repo of Right LocalRepo -> return (packageFile repo pkgid) Left remoteRepo -> do let uri = packageURI remoteRepo pkgid dir = packageDir repo pkgid path = packageFile repo pkgid createDirectoryIfMissing True dir downloadURI verbosity uri path return path -- | Downloads an index file to [config-dir/packages/serv-id]. -- downloadIndex :: Verbosity -> RemoteRepo -> FilePath -> IO FilePath downloadIndex verbosity repo cacheDir = do let uri = (remoteRepoURI repo) { uriPath = uriPath (remoteRepoURI repo) `FilePath.Posix.combine` "00-index.tar.gz" } path = cacheDir </> "00-index" <.> "tar.gz" createDirectoryIfMissing True cacheDir downloadURI verbosity uri path return path -- ------------------------------------------------------------ -- * Path utilities -- ------------------------------------------------------------ -- | Generate the full path to the locally cached copy of -- the tarball for a given @PackageIdentifer@. -- packageFile :: Repo -> PackageId -> FilePath packageFile repo pkgid = packageDir repo pkgid </> display pkgid <.> "tar.gz" -- | Generate the full path to the directory where the local cached copy of -- the tarball for a given @PackageIdentifer@ is stored. -- packageDir :: Repo -> PackageId -> FilePath packageDir repo pkgid = repoLocalDir repo </> display (packageName pkgid) </> display (packageVersion pkgid) -- | Generate the URI of the tarball for a given package. -- packageURI :: RemoteRepo -> PackageId -> URI packageURI repo pkgid | isOldHackageURI (remoteRepoURI repo) = (remoteRepoURI repo) { uriPath = FilePath.Posix.joinPath [uriPath (remoteRepoURI repo) ,display (packageName pkgid) ,display (packageVersion pkgid) ,display pkgid <.> "tar.gz"] } packageURI repo pkgid = (remoteRepoURI repo) { uriPath = FilePath.Posix.joinPath [uriPath (remoteRepoURI repo) ,"package" ,display pkgid <.> "tar.gz"] }
IreneKnapp/Faction
faction/Distribution/Client/FetchUtils.hs
bsd-3-clause
6,517
0
15
1,522
1,421
719
702
125
7
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="it-IT"> <title>OAST Support Add-on</title> <maps> <homeID>oast</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/oast/src/main/javahelp/org/zaproxy/addon/oast/resources/help_it_IT/helpset_it_IT.hs
apache-2.0
965
77
67
157
413
209
204
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} module Properties.Swap where import Test.QuickCheck import Instances import Utils import XMonad.StackSet hiding (filter) -- --------------------------------------------------------------------- -- swapUp, swapDown, swapMaster: reordiring windows -- swap is trivially reversible prop_swap_left (x :: T) = (swapUp (swapDown x)) == x prop_swap_right (x :: T) = (swapDown (swapUp x)) == x -- TODO swap is reversible -- swap is reversible, but involves moving focus back the window with -- master on it. easy to do with a mouse... {- prop_promote_reversible x b = (not . null . fromMaybe [] . flip index x . current $ x) ==> (raiseFocus y . promote . raiseFocus z . promote) x == x where _ = x :: T dir = if b then LT else GT (Just y) = peek x (Just (z:_)) = flip index x . current $ x -} -- swap doesn't change focus prop_swap_master_focus (x :: T) = peek x == (peek $ swapMaster x) -- = case peek x of -- Nothing -> True -- Just f -> focus (stack (workspace $ current (swap x))) == f prop_swap_left_focus (x :: T) = peek x == (peek $ swapUp x) prop_swap_right_focus (x :: T) = peek x == (peek $ swapDown x) -- swap is local prop_swap_master_local (x :: T) = hidden_spaces x == hidden_spaces (swapMaster x) prop_swap_left_local (x :: T) = hidden_spaces x == hidden_spaces (swapUp x) prop_swap_right_local (x :: T) = hidden_spaces x == hidden_spaces (swapDown x) -- rotation through the height of a stack gets us back to the start prop_swap_all_l (x :: T) = (foldr (const swapUp) x [1..n]) == x where n = length (index x) prop_swap_all_r (x :: T) = (foldr (const swapDown) x [1..n]) == x where n = length (index x) prop_swap_master_idempotent (x :: T) = swapMaster (swapMaster x) == swapMaster x
atupal/xmonad-mirror
xmonad/tests/Properties/Swap.hs
mit
1,853
0
9
426
436
230
206
19
1
main = do print $ (-7/2) print $ (-7)/2 print $ -f x/y where f n = n * n x = 5 y = 2
k-bx/ghcjs
test/fay/negation.hs
mit
132
1
10
73
78
39
39
6
1
{- This is my xmonad configuration file. There are many like it, but this one is mine. If you want to customize this file, the easiest workflow goes something like this: 1. Make a small change. 2. Hit "super-q", which recompiles and restarts xmonad 3. If there is an error, undo your change and hit "super-q" again to get to a stable place again. 4. Repeat Author: David Brewer Repository: https://github.com/davidbrewer/xmonad-ubuntu-conf -} import XMonad import XMonad.Hooks.SetWMName import XMonad.Layout.Grid import XMonad.Layout.ResizableTile import XMonad.Layout.ThreeColumns import XMonad.Layout.NoBorders import XMonad.Layout.Circle import XMonad.Layout.PerWorkspace (onWorkspace) import XMonad.Layout.Fullscreen import XMonad.Util.EZConfig import XMonad.Util.Run import XMonad.Hooks.DynamicLog import XMonad.Actions.Plane import XMonad.Hooks.ManageDocks import XMonad.Hooks.UrgencyHook import qualified XMonad.StackSet as W import qualified Data.Map as M import Data.Ratio ((%)) {- Xmonad configuration variables. These settings control some of the simpler parts of xmonad's behavior and are straightforward to tweak. -} myModMask = mod4Mask -- changes the mod key to "super" myFocusedBorderColor = "#ff0000" -- color of focused border myNormalBorderColor = "#cccccc" -- color of inactive border myBorderWidth = 1 -- width of border around windows myTerminal = "gnome-terminal" -- which terminal software to use {- Xmobar configuration variables. These settings control the appearance of text which xmonad is sending to xmobar via the DynamicLog hook. -} myTitleColor = "#eeeeee" -- color of window title myTitleLength = 80 -- truncate window title to this length myCurrentWSColor = "#e6744c" -- color of active workspace myVisibleWSColor = "#c185a7" -- color of inactive workspace myUrgentWSColor = "#cc0000" -- color of workspace with 'urgent' window myCurrentWSLeft = "[" -- wrap active workspace with these myCurrentWSRight = "]" myVisibleWSLeft = "(" -- wrap inactive workspace with these myVisibleWSRight = ")" myUrgentWSLeft = "{" -- wrap urgent workspace with these myUrgentWSRight = "}" {- Workspace configuration. Here you can change the names of your workspaces. Note that they are organized in a grid corresponding to the layout of the number pad. I would recommend sticking with relatively brief workspace names because they are displayed in the xmobar status bar, where space can get tight. Also, the workspace labels are referred to elsewhere in the configuration file, so when you change a label you will have to find places which refer to it and make a change there as well. This central organizational concept of this configuration is that the workspaces correspond to keys on the number pad, and that they are organized in a grid which also matches the layout of the number pad. So, I don't recommend changing the number of workspaces unless you are prepared to delve into the workspace navigation keybindings section as well. -} myWorkspaces = [ "7:Chat", "8:Dbg", "9:Pix", "4:Docs", "5:Dev", "6:Web", "1:Term", "2:Hub", "3:Mail", "0:VM", "Extr1", "Extr2" ] startupWorkspace = "5:Dev" -- which workspace do you want to be on after launch? {- Layout configuration. In this section we identify which xmonad layouts we want to use. I have defined a list of default layouts which are applied on every workspace, as well as special layouts which get applied to specific workspaces. Note that all layouts are wrapped within "avoidStruts". What this does is make the layouts avoid the status bar area at the top of the screen. Without this, they would overlap the bar. You can toggle this behavior by hitting "super-b" (bound to ToggleStruts in the keyboard bindings in the next section). -} -- Define group of default layouts used on most screens, in the -- order they will appear. -- "smartBorders" modifier makes it so the borders on windows only -- appear if there is more than one visible window. -- "avoidStruts" modifier makes it so that the layout provides -- space for the status bar at the top of the screen. defaultLayouts = smartBorders(avoidStruts( -- ResizableTall layout has a large master window on the left, -- and remaining windows tile on the right. By default each area -- takes up half the screen, but you can resize using "super-h" and -- "super-l". ResizableTall 1 (3/100) (1/2) [] -- Mirrored variation of ResizableTall. In this layout, the large -- master window is at the top, and remaining windows tile at the -- bottom of the screen. Can be resized as described above. ||| Mirror (ResizableTall 1 (3/100) (1/2) []) -- Full layout makes every window full screen. When you toggle the -- active window, it will bring the active window to the front. ||| noBorders Full -- ThreeColMid layout puts the large master window in the center -- of the screen. As configured below, by default it takes of 3/4 of -- the available space. Remaining windows tile to both the left and -- right of the master window. You can resize using "super-h" and -- "super-l". -- ||| ThreeColMid 1 (3/100) (3/4) -- Circle layout places the master window in the center of the screen. -- Remaining windows appear in a circle around it -- ||| Circle -- Grid layout tries to equally distribute windows in the available -- space, increasing the number of columns and rows as necessary. -- Master window is at top left. ||| Grid)) -- Here we define some layouts which will be assigned to specific -- workspaces based on the functionality of that workspace. -- We are just running Slack on the chat layout. Full screen it. chatLayout = avoidStruts(noBorders Full) -- The GIMP layout uses the ThreeColMid layout. The traditional GIMP -- floating panels approach is a bit of a challenge to handle with xmonad; -- I find the best solution is to make the image you are working on the -- master area, and then use this ThreeColMid layout to make the panels -- tile to the left and right of the image. If you use GIMP 2.8, you -- can use single-window mode and avoid this issue. gimpLayout = smartBorders(avoidStruts(ThreeColMid 1 (3/100) (3/4))) -- Here we combine our default layouts with our specific, workspace-locked -- layouts. myLayouts = onWorkspace "7:Chat" chatLayout $ onWorkspace "9:Pix" gimpLayout $ defaultLayouts {- Custom keybindings. In this section we define a list of relatively straightforward keybindings. This would be the clearest place to add your own keybindings, or change the keys we have defined for certain functions. It can be difficult to find a good list of keycodes for use in xmonad. I have found this page useful -- just look for entries beginning with "xK": http://xmonad.org/xmonad-docs/xmonad/doc-index-X.html Note that in the example below, the last three entries refer to nonstandard keys which do not have names assigned by xmonad. That's because they are the volume and mute keys on my laptop, a Lenovo T430. If you have special keys on your keyboard which you want to bind to specific actions, you can use the "xev" command-line tool to determine the code for a specific key. Launch the command, then type the key in question and watch the output. -} myKeyBindings = [ ((myModMask, xK_b), sendMessage ToggleStruts) , ((myModMask, xK_a), sendMessage MirrorShrink) , ((myModMask, xK_z), sendMessage MirrorExpand) , ((myModMask, xK_p), spawn "synapse") , ((myModMask .|. shiftMask, xK_l), spawn "slock") , ((myModMask .|. mod1Mask, xK_space), spawn "synapse") , ((myModMask, xK_u), focusUrgent) , ((0, 0x1008FF12), spawn "amixer -q set Master toggle") , ((0, 0x1008FF11), spawn "amixer -q set Master 10%-") , ((0, 0x1008FF13), spawn "amixer -q set Master 10%+") ] {- Management hooks. You can use management hooks to enforce certain behaviors when specific programs or windows are launched. This is useful if you want certain windows to not be managed by xmonad, or sent to a specific workspace, or otherwise handled in a special way. Each entry within the list of hooks defines a way to identify a window (before the arrow), and then how that window should be treated (after the arrow). To figure out to identify your window, you will need to use a command-line tool called "xprop". When you run xprop, your cursor will temporarily change to crosshairs; click on the window you want to identify. In the output that is printed in your terminal, look for a couple of things: - WM_CLASS(STRING): values in this list of strings can be compared to "className" to match windows. - WM_NAME(STRING): this value can be compared to "resource" to match windows. The className values tend to be generic, and might match any window or dialog owned by a particular program. The resource values tend to be more specific, and will be different for every dialog. Sometimes you might want to compare both className and resource, to make sure you are matching only a particular window which belongs to a specific program. Once you've pinpointed the window you want to manipulate, here are a few examples of things you might do with that window: - doIgnore: this tells xmonad to completely ignore the window. It will not be tiled or floated. Useful for things like launchers and trays. - doFloat: this tells xmonad to float the window rather than tiling it. Handy for things that pop up, take some input, and then go away, such as dialogs, calculators, and so on. - doF (W.shift "Workspace"): this tells xmonad that when this program is launched it should be sent to a specific workspace. Useful for keeping specific tasks on specific workspaces. In the example below I have specific workspaces for chat, development, and editing images. -} myManagementHooks :: [ManageHook] myManagementHooks = [ resource =? "synapse" --> doIgnore , resource =? "stalonetray" --> doIgnore , className =? "rdesktop" --> doFloat , className =? "Gnome-calculator" --> doFloat , (className =? "Slack") --> doF (W.shift "7:Chat") , (className =? "Gimp-2.8") --> doF (W.shift "9:Pix") ] {- Workspace navigation keybindings. This is probably the part of the configuration I have spent the most time messing with, but understand the least. Be very careful if messing with this section. -} -- We define two lists of keycodes for use in the rest of the -- keyboard configuration. The first is the list of numpad keys, -- in the order they occur on the keyboard (left to right and -- top to bottom). The second is the list of number keys, in an -- order corresponding to the numpad. We will use these to -- make workspace navigation commands work the same whether you -- use the numpad or the top-row number keys. And, we also -- use them to figure out where to go when the user -- uses the arrow keys. numPadKeys = [ xK_KP_Home, xK_KP_Up, xK_KP_Page_Up , xK_KP_Left, xK_KP_Begin,xK_KP_Right , xK_KP_End, xK_KP_Down, xK_KP_Page_Down , xK_KP_Insert, xK_KP_Delete, xK_KP_Enter ] numKeys = [ xK_7, xK_8, xK_9 , xK_4, xK_5, xK_6 , xK_1, xK_2, xK_3 , xK_0, xK_minus, xK_equal ] -- Here, some magic occurs that I once grokked but has since -- fallen out of my head. Essentially what is happening is -- that we are telling xmonad how to navigate workspaces, -- how to send windows to different workspaces, -- and what keys to use to change which monitor is focused. myKeys = myKeyBindings ++ [ ((m .|. myModMask, k), windows $ f i) | (i, k) <- zip myWorkspaces numPadKeys , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)] ] ++ [ ((m .|. myModMask, k), windows $ f i) | (i, k) <- zip myWorkspaces numKeys , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)] ] ++ M.toList (planeKeys myModMask (Lines 4) Finite) ++ [ ((m .|. myModMask, key), screenWorkspace sc >>= flip whenJust (windows . f)) | (key, sc) <- zip [xK_w, xK_e, xK_r] [1,0,2] , (f, m) <- [(W.view, 0), (W.shift, shiftMask)] ] {- Here we actually stitch together all the configuration settings and run xmonad. We also spawn an instance of xmobar and pipe content into it via the logHook. -} main = do xmproc <- spawnPipe "xmobar ~/.xmonad/xmobarrc" xmonad $ withUrgencyHook NoUrgencyHook $ def { focusedBorderColor = myFocusedBorderColor , normalBorderColor = myNormalBorderColor , terminal = myTerminal , borderWidth = myBorderWidth , layoutHook = myLayouts , workspaces = myWorkspaces , modMask = myModMask , handleEventHook = docksEventHook <+> fullscreenEventHook , startupHook = do setWMName "LG3D" windows $ W.greedyView startupWorkspace spawn "~/.xmonad/startup-hook" , manageHook = manageHook def <+> composeAll myManagementHooks <+> manageDocks , logHook = dynamicLogWithPP xmobarPP { ppOutput = hPutStrLn xmproc , ppTitle = xmobarColor myTitleColor "" . shorten myTitleLength , ppCurrent = xmobarColor myCurrentWSColor "" . wrap myCurrentWSLeft myCurrentWSRight , ppVisible = xmobarColor myVisibleWSColor "" . wrap myVisibleWSLeft myVisibleWSRight , ppUrgent = xmobarColor myUrgentWSColor "" . wrap myUrgentWSLeft myUrgentWSRight } } `additionalKeys` myKeys
davidbrewer/xmonad-ubuntu-conf
xmonad.hs
mit
13,617
0
16
2,842
1,416
850
566
129
1
-------------------------------------------------------------------------------- -- -- Prelude Alan Library -- -- (c) Tsitsimpis Ilias, 2011-2012 -- -------------------------------------------------------------------------------- {-# LANGUAGE ScopedTypeVariables #-} module Main (main) where import Data.Word import Data.Int import LLVM.Core prelude :: CodeGenModule () prelude = do -- declare all our functions printf <- newNamedFunction ExternalLinkage "printf" :: TFunction (Ptr Word8 -> VarArgs Word32) scanf <- newNamedFunction ExternalLinkage "scanf" :: TFunction (Ptr Word8 -> VarArgs Word32) getchar <- newNamedFunction ExternalLinkage "getchar" :: TFunction (IO Int32) writeInteger <- newNamedFunction ExternalLinkage "writeInteger" :: TFunction (Int32 -> IO ()) writeByte <- newNamedFunction ExternalLinkage "writeByte" :: TFunction (Word8 -> IO ()) writeChar <- newNamedFunction ExternalLinkage "writeChar" :: TFunction (Word8 -> IO ()) writeString <- newNamedFunction ExternalLinkage "writeString" :: TFunction (Ptr Word8 -> IO ()) readInteger <- newNamedFunction ExternalLinkage "readInteger" :: TFunction (IO Int32) readByte <- newNamedFunction ExternalLinkage "readByte" :: TFunction (IO Word8) readChar <- newNamedFunction ExternalLinkage "readChar" :: TFunction (IO Word8) readString <- newNamedFunction ExternalLinkage "readString" :: TFunction (Int32 -> Ptr Word8 -> IO ()) extend <- newNamedFunction ExternalLinkage "extend" :: TFunction (Word8 -> IO Int32) shrink <- newNamedFunction ExternalLinkage "shrink" :: TFunction (Int32 -> IO Word8) _ <- newNamedFunction ExternalLinkage "strlen" :: TFunction (Ptr Word8 -> IO Int32) _ <- newNamedFunction ExternalLinkage "strcmp" :: TFunction (Ptr Word8 -> Ptr Word8 -> IO Int32) _ <- newNamedFunction ExternalLinkage "strcpy" :: TFunction (Ptr Word8 -> Ptr Word8 -> IO ()) _ <- newNamedFunction ExternalLinkage "strcat" :: TFunction (Ptr Word8 -> Ptr Word8 -> IO ()) -- ----------------------- -- cast printf/scanf let print_d = castVarArgs printf :: Function (Ptr Word8 -> Int32 -> IO Word32) print_b = castVarArgs printf :: Function (Ptr Word8 -> Word8 -> IO Word32) print_s = castVarArgs printf :: Function (Ptr Word8 -> IO Word32) read_d = castVarArgs scanf :: Function (Ptr Word8 -> Ptr Int32 -> IO Word32) read_c = castVarArgs scanf :: Function (Ptr Word8 -> Ptr Word8 -> IO Word32) -- ----------------------- -- writeInteger withStringNul "%d" (\fmt -> defineFunction writeInteger $ \i -> do t1 <- getElementPtr fmt (0::Word32, (0::Word32, ())) _ <- call print_d t1 i ret () ) -- ----------------------- -- writeByte withStringNul "%d" (\fmt -> defineFunction writeByte $ \b -> do t1 <- getElementPtr fmt (0::Word32, (0::Word32, ())) _ <- call print_b t1 b ret () ) -- ----------------------- -- writeChar withStringNul "%c" (\fmt -> defineFunction writeChar $ \c -> do t1 <- getElementPtr fmt (0::Word32, (0::Word32, ())) _ <- call print_b t1 c ret () ) -- ----------------------- -- writeString defineFunction writeString $ \s -> do _ <- call print_s s ret () -- ----------------------- -- readInteger withStringNul "%d" (\fmt -> defineFunction readInteger $ do t1 <- alloca t2 <- getElementPtr fmt (0::Word32, (0::Word32, ())) _ <- call read_d t2 t1 t3 <- load t1 ret t3 ) -- ----------------------- -- readByte defineFunction readByte $ do t1 <- call readInteger (t2 :: Value Word8) <- trunc t1 ret t2 -- ----------------------- -- readChar withStringNul "%c" (\fmt -> defineFunction readChar $ do t1 <- alloca t2 <- getElementPtr fmt (0::Word32, (0::Word32, ())) _ <- call read_c t2 t1 t3 <- load t1 ret t3 ) -- ----------------------- -- readString defineFunction readString $ \n s -> do top <- getCurrentBasicBlock loop <- newBasicBlock body <- newBasicBlock bb1 <- newBasicBlock bb2 <- newBasicBlock exit <- newBasicBlock n' <- sub n (valueOf (1::Int32)) br loop -- loop defineBasicBlock loop i <- phi [(n', top)] -- i starts as (n-1), when entered from top bb p <- phi [(s, top)] -- p starts as s, when entered from top bb t1 <- cmp CmpGT i (valueOf (0::Int32)) condBr t1 body exit -- body defineBasicBlock body t2 <- call getchar t3 <- cmp CmpEQ t2 (valueOf (10::Int32)) condBr t3 exit bb1 -- bb1 defineBasicBlock bb1 t4 <- cmp CmpEQ t2 (valueOf (-1::Int32)) condBr t4 exit bb2 -- bb2 defineBasicBlock bb2 (t5 :: Value Word8) <- trunc t2 store t5 p i' <- sub i (valueOf (1::Int32)) p' <- getElementPtr p (1::Word32, ()) addPhiInputs i [(i', bb2)] addPhiInputs p [(p', bb2)] br loop -- exit defineBasicBlock exit store (valueOf (0::Word8)) p ret () -- ----------------------- -- extend defineFunction extend $ \w -> do (t1 :: Value Int32) <- zext w ret t1 -- ----------------------- -- shrink defineFunction shrink $ \i -> do (t1 :: Value Word8) <- trunc i ret t1 -- ----------------------- -- string functions are -- the same with libc return () main :: IO () main = do mPrelude <- newModule defineModule mPrelude prelude writeBitcodeToFile "prelude.bc" mPrelude
iliastsi/gac
libraries/prelude/Main.hs
mit
6,032
0
18
1,823
1,823
875
948
126
1
-- | Running Hablog {-# LANGUAGE OverloadedStrings #-} module Web.Hablog.Run where import Web.Scotty.Trans import Control.Monad.Reader (runReaderT) import qualified Data.Text.Lazy as TL import Network.URI (parseURI) import Web.Hablog.Router import Web.Hablog.Config -- | Run Hablog on HTTP run :: Config -> IO () run cfg = scottyT (blogPort cfg) (`runReaderT` cfg) (router $! domain) where domain = parseURI (TL.unpack $ blogDomain cfg)
soupi/hablog
src/Web/Hablog/Run.hs
mit
450
0
10
72
128
77
51
12
1
module Monads where import Control.Applicative import Control.Monad hiding (foldM) import Control.Monad.Error import Control.Monad.List import Control.Monad.State hiding (foldM) import Data.List hiding (permutations) --import Data.List import Test.QuickCheck -------------------------------------------------------------------------- -- Introduction: -- -- This module accompanies the second part of the Patterns for Effects -- slides, and contains additional exercises. -- -- (For the first part, just listen.) -------------------------------------------------------------------------- -- Evaluating example expressions: -- -- Try the expressions from the slides: -- -- replicateM 2 [1 .. 3] -- mapM return [1 .. 3] -- sequence [[1, 2], [3, 4], [5, 6]] -- mapM (flip lookup [(1, ’x’), (2, ’y’), (3, ’z’)]) [1 .. 3] -- mapM (flip lookup [(1, ’x’), (2, ’y’), (3, ’z’)]) [1, 4, 3] -- evalState (replicateM_ 5 (modify (+ 2)) > get) 0 -------------------------------------------------------------------------- -- Experimenting with Maybe: -- On the slides, there's this version of the factorial function: -- fac :: Int -> Either String Int -- fac 0 = Right 1 -- fac n | n > 0 = case fac (n - 1) of -- Left e -> Left e -- Right r -> Right (n * r) -- | otherwise = Left "fac: negative argument" fac :: Int -> Either String Int fac 0 = Right 1 fac n | n > 0 = do n' <- fac (n - 1); return (n * n') | otherwise = Left "fac: negative argument" -- Rewrite this version using the Maybe monad. -- Write a version of dfs (from More.hs) that does not rely -- on the graph to be valid, and uses the Maybe monad. -------------------------------------------------------------------------- -- Experimenting with Lists: -- Write a function that given two lists, generates the cartesian product, -- i.e., all combinations of elements of the two lists, using either do -- notation on lists, or a list comprehension (preferably both). cartesian :: [a] -> [b] -> [(a, b)] cartesian x y = do x' <- x y' <- y return (x', y') -- alernatives --cartesian x y = (,) <$> x <*> y --cartesian x y = [ (x', y') | x' <- x, y' <- y ] -- Write a function that generates all permutations of a given list; -- again try using a list comprehension or do notation. permutations :: Eq a => [a] -> [[a]] permutations [] = [[]] permutations xs = [ x:ps | x <- xs , ps <- permutations ( filter (/=x) xs) ] -------------------------------------------------------------------------- -- Experimenting with State: data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Show, Eq) -- The final version of 'labelTree': labelTree :: Tree a -> State Int (Tree (a, Int)) labelTree (Leaf x) = do c <- get put (c + 1) return (Leaf (x, c)) labelTree (Node l r) = Node <$> labelTree l <*> labelTree r labelTreeFrom0 :: Tree a -> Tree (a, Int) labelTreeFrom0 t = evalState (labelTree t) 0 exTree :: Tree Int exTree = Node (Leaf 1) (Node (Leaf 5) (Leaf 3)) -- Exercise: -- -- Run this on one or more examples. -- -- What if you'd instead want to number the tree from right to left? data Rose a = Fork a [Rose a] deriving (Eq, Show) labelRose :: Rose a -> State Int (Rose (a, Int)) labelRose (Fork x cs) = do c <- get put (c + 1) lcs <- mapM labelRose cs return (Fork (x, c) lcs) -- Try to reimplement the sum function on lists using the -- state monad, by applying mapM_ ... -- Try to write a tree-labelling function that labels every -- node with a label from a given supply, discarding the previous -- labels. The function may crash if there are too few labels -- in the supply. labelTree' :: [a] -> Tree b -> Tree a labelTree' = error "TODO: implement labelTree'" -- Now, write a variant of this function that keeps the existing -- label if it is a 'Just', and takes one from the supply if it is -- 'Nothing'. The function may again crash if there are too few -- labels in the supply. completeLabels :: [a] -> Tree (Maybe a) -> Tree a completeLabels = error "TODO: implement completeLabels" -------------------------------------------------------------------------- -- Experimenting with IO: -- One monadic function we have not yet discussed is the monadic -- fold 'foldM': -- -- foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a -- -- Compare this with the type of 'foldl'. -- -- Here is an example: verboseSum :: [Int] -> IO Int verboseSum = foldM (\ acc x -> do putStrLn $ "current total: " ++ show acc return (acc + x)) 0 -- Try it on a couple of lists and see how it works. -- -- Then try to write your own version of 'foldM' that achieves the -- same. -------------------------------------------------------------------------- -- More about QuickCheck generators: -- Let's try to define an arbitrary instance for binary trees. -- -- We are going to make nodes a bit more frequent than leaves, in -- order to get larger trees: instance Arbitrary a => Arbitrary (Tree a) where arbitrary = frequency [ (3, error "TODO: generate a node") , (1, error "TODO: generate a leaf") ] -- Try to fill in the gaps. Note that one way to generate a node here -- would be to generate a pair of subtrees and use fmap: -- -- fmap (\ (l, r) -> Node l r) arbitrary -- -- However, now that we know that Gen is a monad, it seems unnecessary -- to first create a pair only to destruct it immediately after. -- -- Instead, try to achieve the same using either do notation, or the -- applicative notation (using (<$>) and (<*>)). -- Then let's try -- -- sample (arbitrary :: IO Int) -- -- If you've done it right, you'll see trees being printed forever. It -- seems that tree generation does not terminate. Any idea why? -- -- -- The problem we're observing is quite typical for recursive branching -- structures -- we've made nodes quite probable to be generated, and -- each node has two new subtrees, so this quickly explodes. On the other -- hand, if we make leaves really likely, we'll most of the time end up -- with boring, extremely small trees. -- -- Fortunately, QuickCheck generators have a size parameter. This -- parameter is normally hidden state in the 'Gen' monad. However, we -- can access it using the 'sized' function: -- -- sized :: (Int -> Gen a) -> Gen a -- -- We use it as follows: -- -- instance Arbitrary a => Arbitrary (Tree a) where -- arbitrary = sized $ \ s -> ... -- -- Now we have an additional parameter 's' available. We can also -- "resize" an existing generator: -- -- resize :: Int -> Gen a -> Gen a -- -- Now, rewrite arbitrary for binary trees such that: -- -- * if the size is 0, we always generate a leave -- * if the size is non-zero, we generate the old frequency table, -- but we resize the subtrees to one half of the input size. -- -- Sample again in order to check if this works. -- -- Test the following property: -- -- The size of a tree is equal to the length of the flattened tree. -- -- Next, try to write a generator for node-labeled Trees ('BinTree' -- from More.hs), using the same techniques. -- -- As a final challenge, try to write a generator for BSTs (binary -- search trees). When you're done, check whether your generated BSTs -- actually have the BST property.
NickAger/LearningHaskell
well-typed at skills matter/fast-track/exercises/5/Monads.hs
mit
7,330
0
12
1,536
975
569
406
53
1
module MakeCode (codeTable, codes) where import MakeTree (makeTree) import CodeTable (codeTable) import Frequency (frequency) import Types ( Bit (L, R) , HCode , Table , Tree (Leaf, Node) ) codes :: String -> Tree codes = makeTree . frequency
tonyfloatersu/solution-haskell-craft-of-FP
MakeCode.hs
mit
358
0
6
154
83
54
29
10
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.WebGLDrawBuffers ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.WebGLDrawBuffers #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.WebGLDrawBuffers #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/WebGLDrawBuffers.hs
mit
361
0
5
33
33
26
7
4
0
import Control.Monad.Trans.Maybe import Control.Monad import Control.Monad.IO.Class isValid :: String -> Bool isValid v = '!' `elem` v maybeExcite :: MaybeT IO String maybeExcite = do v <- liftIO getLine guard $ isValid v return v doExcite :: IO () doExcite = do putStrLn "say something excite!" excite <- runMaybeT maybeExcite case excite of Nothing -> putStrLn "MOAR EXCITE" Just e -> putStrLn ("Good, was very excite: " ++ e)
mitochon/hexercise
src/haskellbook/ch26/ch26.guard.hs
mit
456
0
12
96
150
74
76
17
2
import Control.Applicative import Control.Monad import System.IO import Data.List data Trie a = EmptyTrie | Root [Trie a] | Node a [Trie a] deriving (Eq, Show) type Counter = Trie (Char, Int) trieRoot :: Counter trieRoot = Root [] partitionTrieList :: Char -> [Counter] -> ([Counter], [Counter]) partitionTrieList val ts = case f of ([], ts) -> ([Node (val, 1) []], ts) ([Node (v, c) innerts], ts) -> ([Node (v, c+1) innerts], ts) where f = partition (\(Node v _) -> (fst v) == val) ts ins :: String -> Counter -> Counter ins [] t = t ins [v] EmptyTrie = Node (v, 1) [] ins (v:vs) EmptyTrie = Node (v, 1) [ins vs EmptyTrie] ins (v:vs) (Root ts) = Root ((ins vs node):others) where (nodes, others) = partitionTrieList v ts node = head nodes ins (v:vs) (Node x ts) = Node x ((ins vs node):others) where (nodes, others) = partitionTrieList v ts node = head nodes filterTrie :: (Trie a -> Bool) -> [Trie a] -> Trie a filterTrie f ts = case (filter f ts) of [] -> EmptyTrie ts' -> head ts' findCount :: String -> Counter -> Int findCount _ EmptyTrie = 0 findCount (x:xs) (Node _ []) = 0 findCount [] (Node v _) = snd v findCount (x:xs) (Node _ ts) = findCount xs $ f ts where f = filterTrie (\(Node v _) -> fst v == x) findCount (x:xs) (Root ts) = findCount xs $ f ts where f = filterTrie (\(Node v _) -> fst v == x) dispatch :: Counter -> String -> String -> IO (Counter) dispatch t "add" d = return $ ins d t dispatch t "find" d = do print $ findCount d t return t process :: Counter -> Int -> IO (Counter) process t i = do op_temp <- getLine let op_t = words op_temp let op = op_t!!0 let contact = op_t!!1 dispatch t op contact main :: IO () main = do n_temp <- getLine let n = read n_temp :: Int foldM_ process trieRoot [1..n]
nbrendler/hackerrank-exercises
tries-contacts/Main.hs
mit
1,809
0
12
427
975
503
472
52
2
{-| Module : Database.Orville.PostgreSQL.Internal.Monad Copyright : Flipstone Technology Partners 2016-2018 License : MIT 'Database.Orville.PostgreSQL.MonadUnliftIO' provides functions and instances for using 'MonadOrville' and 'OrvilleT' for Monad transformer stacks that are using 'MonadUnliftIO'. The most common way to do this is simply to add the following 'MonadOrvilleControl' instance: @ instance MonadOrvilleControl MyMonad where liftWithConnection = liftWithConnectionViaUnliftIO liftFinally = liftFinallyViaUnliftIO @ This module also provides a 'MonadUnliftIO' instance for 'OrvilleT' and 'OrvilleTrigger'. |-} {-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} module Database.Orville.PostgreSQL.MonadUnliftIO ( liftWithConnectionViaUnliftIO , liftFinallyViaUnliftIO ) where import qualified Control.Monad.IO.Unlift as UL import qualified Database.Orville.PostgreSQL as O import qualified Database.Orville.PostgreSQL.Internal.Monad as InternalMonad import qualified Database.Orville.PostgreSQL.Internal.Trigger as InternalTrigger import qualified Database.Orville.PostgreSQL.Trigger as OT {-| liftWithConnectionViaUnliftIO can be use as the implementation of 'liftWithConnection' for 'MonadOrvilleControl' when the 'Monad' implements 'MonadUnliftIO'. |-} liftWithConnectionViaUnliftIO :: UL.MonadUnliftIO m => (forall a. (conn -> IO a) -> IO a) -> (conn -> m b) -> m b liftWithConnectionViaUnliftIO ioWithConn action = UL.withRunInIO $ \runInIO -> ioWithConn (runInIO . action) {-| liftFinallyViaUnliftIO can be use as the implementation of 'liftFinally' for 'MonadOrvilleControl' when the 'Monad' implements 'MonadUnliftIO'. |-} liftFinallyViaUnliftIO :: UL.MonadUnliftIO m => (forall a b. IO a -> IO b -> IO a) -> m c -> m d -> m c liftFinallyViaUnliftIO ioFinally action cleanup = do unlio <- UL.askUnliftIO UL.liftIO $ ioFinally (UL.unliftIO unlio action) (UL.unliftIO unlio cleanup) instance UL.MonadUnliftIO m => UL.MonadUnliftIO (O.OrvilleT conn m) where #if MIN_VERSION_unliftio_core(0,2,0) withRunInIO inner = InternalMonad.OrvilleT $ do UL.withRunInIO $ \run -> inner (run . InternalMonad.unOrvilleT) #else askUnliftIO = InternalMonad.OrvilleT $ do unlio <- UL.askUnliftIO pure $ UL.UnliftIO (UL.unliftIO unlio . InternalMonad.unOrvilleT) #endif instance UL.MonadUnliftIO m => UL.MonadUnliftIO (OT.OrvilleTriggerT trigger conn m) where #if MIN_VERSION_unliftio_core(0,2,0) withRunInIO inner = InternalTrigger.OrvilleTriggerT $ do UL.withRunInIO $ \run -> inner (run . InternalTrigger.unTriggerT) #else askUnliftIO = InternalTrigger.OrvilleTriggerT $ do unlio <- UL.askUnliftIO pure $ UL.UnliftIO (UL.unliftIO unlio . InternalTrigger.unTriggerT) #endif
flipstone/orville
orville-postgresql/src/Database/Orville/PostgreSQL/MonadUnliftIO.hs
mit
2,837
0
14
473
425
233
192
37
1
-- | -- Error codes as per -- <https://www.postgresql.org/docs/9.6/static/errcodes-appendix.html>. module PostgreSQL.ErrorCodes where import qualified Data.ByteString type ErrorCode = Data.ByteString.ByteString -- * Class 00 — Successful Completion ------------------------- -- | Code \"00000\". successful_completion :: ErrorCode = "00000" -- * Class 01 — Warning ------------------------- -- | Code \"01000\". warning :: ErrorCode = "01000" -- | Code \"0100C\". dynamic_result_sets_returned :: ErrorCode = "0100C" -- | Code \"01008\". implicit_zero_bit_padding :: ErrorCode = "01008" -- | Code \"01003\". null_value_eliminated_in_set_function :: ErrorCode = "01003" -- | Code \"01007\". privilege_not_granted :: ErrorCode = "01007" -- | Code \"01006\". privilege_not_revoked :: ErrorCode = "01006" -- | Code \"01004\". string_data_right_truncation :: ErrorCode = "01004" -- | Code \"01P01\". deprecated_feature :: ErrorCode = "01P01" -- * Class 02 — No Data (this is also a warning class per the SQL standard) ------------------------- -- | Code \"02000\". no_data :: ErrorCode = "02000" -- | Code \"02001\". no_additional_dynamic_result_sets_returned :: ErrorCode = "02001" -- * Class 03 — SQL Statement Not Yet Complete ------------------------- -- | Code \"03000\". sql_statement_not_yet_complete :: ErrorCode = "03000" -- * Class 08 — Connection Exception ------------------------- -- | Code \"08000\". connection_exception :: ErrorCode = "08000" -- | Code \"08003\". connection_does_not_exist :: ErrorCode = "08003" -- | Code \"08006\". connection_failure :: ErrorCode = "08006" -- | Code \"08001\". sqlclient_unable_to_establish_sqlconnection :: ErrorCode = "08001" -- | Code \"08004\". sqlserver_rejected_establishment_of_sqlconnection :: ErrorCode = "08004" -- | Code \"08007\". transaction_resolution_unknown :: ErrorCode = "08007" -- | Code \"08P01\". protocol_violation :: ErrorCode = "08P01" -- * Class 09 — Triggered Action Exception ------------------------- -- | Code \"09000\". triggered_action_exception :: ErrorCode = "09000" -- * Class 0A — Feature Not Supported ------------------------- -- | Code \"0A000\". feature_not_supported :: ErrorCode = "0A000" -- * Class 0B — Invalid Transaction Initiation ------------------------- -- | Code \"0B000\". invalid_transaction_initiation :: ErrorCode = "0B000" -- * Class 0F — Locator Exception ------------------------- -- | Code \"0F000\". locator_exception :: ErrorCode = "0F000" -- | Code \"0F001\". invalid_locator_specification :: ErrorCode = "0F001" -- * Class 0L — Invalid Grantor ------------------------- -- | Code \"0L000\". invalid_grantor :: ErrorCode = "0L000" -- | Code \"0LP01\". invalid_grant_operation :: ErrorCode = "0LP01" -- * Class 0P — Invalid Role Specification ------------------------- -- | Code \"0P000\". invalid_role_specification :: ErrorCode = "0P000" -- * Class 0Z — Diagnostics Exception ------------------------- -- | Code \"0Z000\". diagnostics_exception :: ErrorCode = "0Z000" -- | Code \"0Z002\". stacked_diagnostics_accessed_without_active_handler :: ErrorCode = "0Z002" -- * Class 20 — Case Not Found ------------------------- -- | Code \"20000\". case_not_found :: ErrorCode = "20000" -- * Class 21 — Cardinality Violation ------------------------- -- | Code \"21000\". cardinality_violation :: ErrorCode = "21000" -- * Class 22 — Data Exception ------------------------- -- | Code \"22000\". data_exception :: ErrorCode = "22000" -- | Code \"2202E\". array_subscript_error :: ErrorCode = "2202E" -- | Code \"22021\". character_not_in_repertoire :: ErrorCode = "22021" -- | Code \"22008\". datetime_field_overflow :: ErrorCode = "22008" -- | Code \"22012\". division_by_zero :: ErrorCode = "22012" -- | Code \"22005\". error_in_assignment :: ErrorCode = "22005" -- | Code \"2200B\". escape_character_conflict :: ErrorCode = "2200B" -- | Code \"22022\". indicator_overflow :: ErrorCode = "22022" -- | Code \"22015\". interval_field_overflow :: ErrorCode = "22015" -- | Code \"2201E\". invalid_argument_for_logarithm :: ErrorCode = "2201E" -- | Code \"22014\". invalid_argument_for_ntile_function :: ErrorCode = "22014" -- | Code \"22016\". invalid_argument_for_nth_value_function :: ErrorCode = "22016" -- | Code \"2201F\". invalid_argument_for_power_function :: ErrorCode = "2201F" -- | Code \"2201G\". invalid_argument_for_width_bucket_function :: ErrorCode = "2201G" -- | Code \"22018\". invalid_character_value_for_cast :: ErrorCode = "22018" -- | Code \"22007\". invalid_datetime_format :: ErrorCode = "22007" -- | Code \"22019\". invalid_escape_character :: ErrorCode = "22019" -- | Code \"2200D\". invalid_escape_octet :: ErrorCode = "2200D" -- | Code \"22025\". invalid_escape_sequence :: ErrorCode = "22025" -- | Code \"22P06\". nonstandard_use_of_escape_character :: ErrorCode = "22P06" -- | Code \"22010\". invalid_indicator_parameter_value :: ErrorCode = "22010" -- | Code \"22023\". invalid_parameter_value :: ErrorCode = "22023" -- | Code \"2201B\". invalid_regular_expression :: ErrorCode = "2201B" -- | Code \"2201W\". invalid_row_count_in_limit_clause :: ErrorCode = "2201W" -- | Code \"2201X\". invalid_row_count_in_result_offset_clause :: ErrorCode = "2201X" -- | Code \"2202H\". invalid_tablesample_argument :: ErrorCode = "2202H" -- | Code \"2202G\". invalid_tablesample_repeat :: ErrorCode = "2202G" -- | Code \"22009\". invalid_time_zone_displacement_value :: ErrorCode = "22009" -- | Code \"2200C\". invalid_use_of_escape_character :: ErrorCode = "2200C" -- | Code \"2200G\". most_specific_type_mismatch :: ErrorCode = "2200G" -- | Code \"22004\". null_value_not_allowed :: ErrorCode = "22004" -- | Code \"22002\". null_value_no_indicator_parameter :: ErrorCode = "22002" -- | Code \"22003\". numeric_value_out_of_range :: ErrorCode = "22003" -- | Code \"22026\". string_data_length_mismatch :: ErrorCode = "22026" -- | Code \"22001\". string_data_right_truncation' :: ErrorCode = "22001" -- | Code \"22011\". substring_error :: ErrorCode = "22011" -- | Code \"22027\". trim_error :: ErrorCode = "22027" -- | Code \"22024\". unterminated_c_string :: ErrorCode = "22024" -- | Code \"2200F\". zero_length_character_string :: ErrorCode = "2200F" -- | Code \"22P01\". floating_point_exception :: ErrorCode = "22P01" -- | Code \"22P02\". invalid_text_representation :: ErrorCode = "22P02" -- | Code \"22P03\". invalid_binary_representation :: ErrorCode = "22P03" -- | Code \"22P04\". bad_copy_file_format :: ErrorCode = "22P04" -- | Code \"22P05\". untranslatable_character :: ErrorCode = "22P05" -- | Code \"2200L\". not_an_xml_document :: ErrorCode = "2200L" -- | Code \"2200M\". invalid_xml_document :: ErrorCode = "2200M" -- | Code \"2200N\". invalid_xml_content :: ErrorCode = "2200N" -- | Code \"2200S\". invalid_xml_comment :: ErrorCode = "2200S" -- | Code \"2200T\". invalid_xml_processing_instruction :: ErrorCode = "2200T" -- * Class 23 — Integrity Constraint Violation ------------------------- -- | Code \"23000\". integrity_constraint_violation :: ErrorCode = "23000" -- | Code \"23001\". restrict_violation :: ErrorCode = "23001" -- | Code \"23502\". not_null_violation :: ErrorCode = "23502" -- | Code \"23503\". foreign_key_violation :: ErrorCode = "23503" -- | Code \"23505\". unique_violation :: ErrorCode = "23505" -- | Code \"23514\". check_violation :: ErrorCode = "23514" -- | Code \"23P01\". exclusion_violation :: ErrorCode = "23P01" -- * Class 24 — Invalid Cursor State ------------------------- -- | Code \"24000\". invalid_cursor_state :: ErrorCode = "24000" -- * Class 25 — Invalid Transaction State ------------------------- -- | Code \"25000\". invalid_transaction_state :: ErrorCode = "25000" -- | Code \"25001\". active_sql_transaction :: ErrorCode = "25001" -- | Code \"25002\". branch_transaction_already_active :: ErrorCode = "25002" -- | Code \"25008\". held_cursor_requires_same_isolation_level :: ErrorCode = "25008" -- | Code \"25003\". inappropriate_access_mode_for_branch_transaction :: ErrorCode = "25003" -- | Code \"25004\". inappropriate_isolation_level_for_branch_transaction :: ErrorCode = "25004" -- | Code \"25005\". no_active_sql_transaction_for_branch_transaction :: ErrorCode = "25005" -- | Code \"25006\". read_only_sql_transaction :: ErrorCode = "25006" -- | Code \"25007\". schema_and_data_statement_mixing_not_supported :: ErrorCode = "25007" -- | Code \"25P01\". no_active_sql_transaction :: ErrorCode = "25P01" -- | Code \"25P02\". in_failed_sql_transaction :: ErrorCode = "25P02" -- | Code \"25PO3\". idle_in_transaction_session_timeout :: ErrorCode = "25P03" -- * Class 26 — Invalid SQL Statement Name ------------------------- -- | Code \"26000\". invalid_sql_statement_name :: ErrorCode = "26000" -- * Class 27 — Triggered Data Change Violation ------------------------- -- | Code \"27000\". triggered_data_change_violation :: ErrorCode = "27000" -- * Class 28 — Invalid Authorization Specification ------------------------- -- | Code \"28000\". invalid_authorization_specification :: ErrorCode = "28000" -- | Code \"28P01\". invalid_password :: ErrorCode = "28P01" -- * Class 2B — Dependent Privilege Descriptors Still Exist ------------------------- -- | Code \"2B000\". dependent_privilege_descriptors_still_exist :: ErrorCode = "2B000" -- | Code \"2BP01\". dependent_objects_still_exist :: ErrorCode = "2BP01" -- * Class 2D — Invalid Transaction Termination ------------------------- -- | Code \"2D000\". invalid_transaction_termination :: ErrorCode = "2D000" -- * Class 2F — SQL Routine Exception ------------------------- -- | Code \"2F000\". sql_routine_exception :: ErrorCode = "2F000" -- | Code \"2F005\". function_executed_no_return_statement :: ErrorCode = "2F005" -- | Code \"2F002\". modifying_sql_data_not_permitted :: ErrorCode = "2F002" -- | Code \"2F003\". prohibited_sql_statement_attempted :: ErrorCode = "2F003" -- | Code \"2F004\". reading_sql_data_not_permitted :: ErrorCode = "2F004" -- * Class 34 — Invalid Cursor Name ------------------------- -- | Code \"34000\". invalid_cursor_name :: ErrorCode = "34000" -- * Class 38 — External Routine Exception ------------------------- -- | Code \"38000\". external_routine_exception :: ErrorCode = "38000" -- | Code \"38001\". containing_sql_not_permitted :: ErrorCode = "38001" -- | Code \"38002\". modifying_sql_data_not_permitted' :: ErrorCode = "38002" -- | Code \"38003\". prohibited_sql_statement_attempted' :: ErrorCode = "38003" -- | Code \"38004\". reading_sql_data_not_permitted' :: ErrorCode = "38004" -- * Class 39 — External Routine Invocation Exception ------------------------- -- | Code \"39000\". external_routine_invocation_exception :: ErrorCode = "39000" -- | Code \"39001\". invalid_sqlstate_returned :: ErrorCode = "39001" -- | Code \"39004\". null_value_not_allowed' :: ErrorCode = "39004" -- | Code \"39P01\". trigger_protocol_violated :: ErrorCode = "39P01" -- | Code \"39P02\". srf_protocol_violated :: ErrorCode = "39P02" -- | Code \"39PO3\". event_trigger_protocol_violated :: ErrorCode = "39P03" -- * Class 3B — Savepoint Exception ------------------------- -- | Code \"3B000\". savepoint_exception :: ErrorCode = "3B000" -- | Code \"3B001\". invalid_savepoint_specification :: ErrorCode = "3B001" -- * Class 3D — Invalid Catalog Name ------------------------- -- | Code \"3D000\". invalid_catalog_name :: ErrorCode = "3D000" -- * Class 3F — Invalid Schema Name ------------------------- -- | Code \"3F000\". invalid_schema_name :: ErrorCode = "3F000" -- * Class 40 — Transaction Rollback ------------------------- -- | Code \"40000\". transaction_rollback :: ErrorCode = "40000" -- | Code \"40002\". transaction_integrity_constraint_violation :: ErrorCode = "40002" -- | Code \"40001\". serialization_failure :: ErrorCode = "40001" -- | Code \"40003\". statement_completion_unknown :: ErrorCode = "40003" -- | Code \"40P01\". deadlock_detected :: ErrorCode = "40P01" -- * Class 42 — Syntax Error or Access Rule Violation ------------------------- -- | Code \"42000\". syntax_error_or_access_rule_violation :: ErrorCode = "42000" -- | Code \"42601\". syntax_error :: ErrorCode = "42601" -- | Code \"42501\". insufficient_privilege :: ErrorCode = "42501" -- | Code \"42846\". cannot_coerce :: ErrorCode = "42846" -- | Code \"42803\". grouping_error :: ErrorCode = "42803" -- | Code \"42P20\". windowing_error :: ErrorCode = "42P20" -- | Code \"42P19\". invalid_recursion :: ErrorCode = "42P19" -- | Code \"42830\". invalid_foreign_key :: ErrorCode = "42830" -- | Code \"42602\". invalid_name :: ErrorCode = "42602" -- | Code \"42622\". name_too_long :: ErrorCode = "42622" -- | Code \"42939\". reserved_name :: ErrorCode = "42939" -- | Code \"42804\". datatype_mismatch :: ErrorCode = "42804" -- | Code \"42P18\". indeterminate_datatype :: ErrorCode = "42P18" -- | Code \"42P21\". collation_mismatch :: ErrorCode = "42P21" -- | Code \"42P22\". indeterminate_collation :: ErrorCode = "42P22" -- | Code \"42809\". wrong_object_type :: ErrorCode = "42809" -- | Code \"42703\". undefined_column :: ErrorCode = "42703" -- | Code \"42883\". undefined_function :: ErrorCode = "42883" -- | Code \"42P01\". undefined_table :: ErrorCode = "42P01" -- | Code \"42P02\". undefined_parameter :: ErrorCode = "42P02" -- | Code \"42704\". undefined_object :: ErrorCode = "42704" -- | Code \"42701\". duplicate_column :: ErrorCode = "42701" -- | Code \"42P03\". duplicate_cursor :: ErrorCode = "42P03" -- | Code \"42P04\". duplicate_database :: ErrorCode = "42P04" -- | Code \"42723\". duplicate_function :: ErrorCode = "42723" -- | Code \"42P05\". duplicate_prepared_statement :: ErrorCode = "42P05" -- | Code \"42P06\". duplicate_schema :: ErrorCode = "42P06" -- | Code \"42P07\". duplicate_table :: ErrorCode = "42P07" -- | Code \"42712\". duplicate_alias :: ErrorCode = "42712" -- | Code \"42710\". duplicate_object :: ErrorCode = "42710" -- | Code \"42702\". ambiguous_column :: ErrorCode = "42702" -- | Code \"42725\". ambiguous_function :: ErrorCode = "42725" -- | Code \"42P08\". ambiguous_parameter :: ErrorCode = "42P08" -- | Code \"42P09\". ambiguous_alias :: ErrorCode = "42P09" -- | Code \"42P10\". invalid_column_reference :: ErrorCode = "42P10" -- | Code \"42611\". invalid_column_definition :: ErrorCode = "42611" -- | Code \"42P11\". invalid_cursor_definition :: ErrorCode = "42P11" -- | Code \"42P12\". invalid_database_definition :: ErrorCode = "42P12" -- | Code \"42P13\". invalid_function_definition :: ErrorCode = "42P13" -- | Code \"42P14\". invalid_prepared_statement_definition :: ErrorCode = "42P14" -- | Code \"42P15\". invalid_schema_definition :: ErrorCode = "42P15" -- | Code \"42P16\". invalid_table_definition :: ErrorCode = "42P16" -- | Code \"42P17\". invalid_object_definition :: ErrorCode = "42P17" -- * Class 44 — WITH CHECK OPTION Violation ------------------------- -- | Code \"44000\". with_check_option_violation :: ErrorCode = "44000" -- * Class 53 — Insufficient Resources ------------------------- -- | Code \"53000\". insufficient_resources :: ErrorCode = "53000" -- | Code \"53100\". disk_full :: ErrorCode = "53100" -- | Code \"53200\". out_of_memory :: ErrorCode = "53200" -- | Code \"53300\". too_many_connections :: ErrorCode = "53300" -- | Code \"53400\". configuration_limit_exceeded :: ErrorCode = "53400" -- * Class 54 — Program Limit Exceeded ------------------------- -- | Code \"54000\". program_limit_exceeded :: ErrorCode = "54000" -- | Code \"54001\". statement_too_complex :: ErrorCode = "54001" -- | Code \"54011\". too_many_columns :: ErrorCode = "54011" -- | Code \"54023\". too_many_arguments :: ErrorCode = "54023" -- * Class 55 — Object Not In Prerequisite State ------------------------- -- | Code \"55000\". object_not_in_prerequisite_state :: ErrorCode = "55000" -- | Code \"55006\". object_in_use :: ErrorCode = "55006" -- | Code \"55P02\". cant_change_runtime_param :: ErrorCode = "55P02" -- | Code \"55P03\". lock_not_available :: ErrorCode = "55P03" -- * Class 57 — Operator Intervention ------------------------- -- | Code \"57000\". operator_intervention :: ErrorCode = "57000" -- | Code \"57014\". query_canceled :: ErrorCode = "57014" -- | Code \"57P01\". admin_shutdown :: ErrorCode = "57P01" -- | Code \"57P02\". crash_shutdown :: ErrorCode = "57P02" -- | Code \"57P03\". cannot_connect_now :: ErrorCode = "57P03" -- | Code \"57P04\". database_dropped :: ErrorCode = "57P04" -- * Class 58 — System Error (errors external to PostgreSQL itself) ------------------------- -- | Code \"58000\". system_error :: ErrorCode = "58000" -- | Code \"58030\". io_error :: ErrorCode = "58030" -- | Code \"58P01\". undefined_file :: ErrorCode = "58P01" -- | Code \"58P02\". duplicate_file :: ErrorCode = "58P02" -- * Class 72 — Snapshot Failure ------------------------- -- | Code \"72000\". snapshot_too_old :: ErrorCode = "72000" -- * Class F0 — Configuration File Error ------------------------- -- | Code \"F0000\". config_file_error :: ErrorCode = "F0000" -- | Code \"F0001\". lock_file_exists :: ErrorCode = "F0001" -- * Class HV — Foreign Data Wrapper Error (SQL/MED) ------------------------- -- | Code \"HV000\". fdw_error :: ErrorCode = "HV000" -- | Code \"HV005\". fdw_column_name_not_found :: ErrorCode = "HV005" -- | Code \"HV002\". fdw_dynamic_parameter_value_needed :: ErrorCode = "HV002" -- | Code \"HV010\". fdw_function_sequence_error :: ErrorCode = "HV010" -- | Code \"HV021\". fdw_inconsistent_descriptor_information :: ErrorCode = "HV021" -- | Code \"HV024\". fdw_invalid_attribute_value :: ErrorCode = "HV024" -- | Code \"HV007\". fdw_invalid_column_name :: ErrorCode = "HV007" -- | Code \"HV008\". fdw_invalid_column_number :: ErrorCode = "HV008" -- | Code \"HV004\". fdw_invalid_data_type :: ErrorCode = "HV004" -- | Code \"HV006\". fdw_invalid_data_type_descriptors :: ErrorCode = "HV006" -- | Code \"HV091\". fdw_invalid_descriptor_field_identifier :: ErrorCode = "HV091" -- | Code \"HV00B\". fdw_invalid_handle :: ErrorCode = "HV00B" -- | Code \"HV00C\". fdw_invalid_option_index :: ErrorCode = "HV00C" -- | Code \"HV00D\". fdw_invalid_option_name :: ErrorCode = "HV00D" -- | Code \"HV090\". fdw_invalid_string_length_or_buffer_length :: ErrorCode = "HV090" -- | Code \"HV00A\". fdw_invalid_string_format :: ErrorCode = "HV00A" -- | Code \"HV009\". fdw_invalid_use_of_null_pointer :: ErrorCode = "HV009" -- | Code \"HV014\". fdw_too_many_handles :: ErrorCode = "HV014" -- | Code \"HV001\". fdw_out_of_memory :: ErrorCode = "HV001" -- | Code \"HV00P\". fdw_no_schemas :: ErrorCode = "HV00P" -- | Code \"HV00J\". fdw_option_name_not_found :: ErrorCode = "HV00J" -- | Code \"HV00K\". fdw_reply_handle :: ErrorCode = "HV00K" -- | Code \"HV00Q\". fdw_schema_not_found :: ErrorCode = "HV00Q" -- | Code \"HV00R\". fdw_table_not_found :: ErrorCode = "HV00R" -- | Code \"HV00L\". fdw_unable_to_create_execution :: ErrorCode = "HV00L" -- | Code \"HV00M\". fdw_unable_to_create_reply :: ErrorCode = "HV00M" -- | Code \"HV00N\". fdw_unable_to_establish_connection :: ErrorCode = "HV00N" -- * Class P0 — PL/pgSQL Error ------------------------- -- | Code \"P0000\". plpgsql_error :: ErrorCode = "P0000" -- | Code \"P0001\". raise_exception :: ErrorCode = "P0001" -- | Code \"P0002\". no_data_found :: ErrorCode = "P0002" -- | Code \"P0003\". too_many_rows :: ErrorCode = "P0003" -- | Code \"POOO4\". assert_failure :: ErrorCode = "P0004" -- * Class XX — Internal Error ------------------------- -- | Code \"XX000\". internal_error :: ErrorCode = "XX000" -- | Code \"XX001\". data_corrupted :: ErrorCode = "XX001" -- | Code \"XX002\". index_corrupted :: ErrorCode = "XX002"
nikita-volkov/postgresql-error-codes
library/PostgreSQL/ErrorCodes.hs
mit
26,404
0
5
9,366
2,728
1,531
1,197
-1
-1
{-# htermination lcm :: Int -> Int -> Int #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_lcm_1.hs
mit
46
0
2
10
3
2
1
1
0
-- Maintained by yamadapc - mostly inspired by and heavily dependent -- <https://github.com/vicfryzel/xmonad-config> -- (still in development) -- Imports -- -- sys & stuff import System.IO import System.Exit import XMonad import XMonad.Util.Run(spawnPipe) import XMonad.Util.EZConfig(additionalKeys) import qualified XMonad.StackSet as W import qualified Data.Map as M -- hooks import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Hooks.ManageHelpers import XMonad.Hooks.SetWMName -- layouts import XMonad.Layout.Fullscreen import XMonad.Layout.NoBorders import XMonad.Layout.Spiral import XMonad.Layout.Tabbed ------------------------------------------------------------------------ -- Terminal -- The preferred terminal program, which is used in a binding below and by -- certain contrib modules. -- myTerminal = "gnome-terminal" ------------------------------------------------------------------------ -- Workspaces -- The default number of workspaces (virtual screens) and their names. -- myWorkspaces = [ "main" , "hack" , "web" , "media" , "read" , "sys" , "comm" , "8" , "9" ] ------------------------------------------------------------------------ -- Window rules -- Execute arbitrary actions and WindowSet manipulations when managing -- a new window. You can use this to, for example, always float a -- particular program, or have a client always appear on a particular -- workspace. -- -- To find the property name associated with a program, use -- > xprop | grep WM_CLASS -- and click on the client you're interested in. -- -- To match on the WM_NAME, you can use 'title' in the same way that -- 'className' and 'resource' are used below. -- myManageHook = composeAll [ className =? "Google-chrome" --> doShift "3:web" , resource =? "desktop_window" --> doIgnore , className =? "Galculator" --> doFloat , className =? "Steam" --> doFloat , className =? "Gimp" --> doFloat , resource =? "gpicview" --> doFloat , className =? "MPlayer" --> doFloat , isFullscreen --> (doF W.focusDown <+> doFullFloat)] ------------------------------------------------------------------------ -- Layouts -- You can specify and transform your layouts by modifying these values. -- If you change layout bindings be sure to use 'mod-shift-space' after -- restarting (with 'mod-q') to reset your layout state to the new -- defaults, as xmonad preserves your old layout settings by default. -- -- The available layouts. Note that each layout is separated by |||, -- which denotes layout choice. -- myLayout = avoidStruts ( Tall 1 (3/100) (2/3) ||| Mirror (Tall 1 (3/100) (1/2)) ||| tabbed shrinkText tabConfig ||| Full ||| Grid) ------------------------------------------------------------------------ -- Colors and borders -- Currently based on the ir_black theme. -- myNormalBorderColor = "#06060D" myFocusedBorderColor = "#cc0c0c" -- Colors for text and backgrounds of each tab when in "Tabbed" layout. tabConfig = defaultTheme { activeBorderColor = "#7C7C7C", activeTextColor = "#FF5600", activeColor = "#000000", inactiveBorderColor = "#7C7C7C", inactiveTextColor = "#EEEEEE", inactiveColor = "#000000" } -- Color of current window title in xmobar. xmobarTitleColor = "#ADAD89" -- Color of current workspace in xmobar. xmobarCurrentWSColor = "#FFA811" -- Color of hidden workspaces in xmobar xmobarHiddenWSColor = "#949397" xmobarHiddenWSNoWindowsColor = "#949397" -- Color of urgen workspaces in xmobar xmobarUrgentColor = "#cc0c0c" -- Width of the window border in pixels. myBorderWidth = 2 ------------------------------------------------------------------------ -- Key bindings -- -- modMask lets you specify which modkey you want to use. The default -- is mod1Mask ("left alt"). You may also consider using mod3Mask -- ("right alt"), which does not conflict with emacs keybindings. The -- "windows key" is usually mod4Mask. -- myModMask = mod1Mask myKeys conf@(XConfig {XMonad.modMask = modMask}) = M.fromList $ ---------------------------------------------------------------------- -- Custom key bindings -- -- Start a terminal. Terminal to start is specified by myTerminal variable. [ ((modMask .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf) -- Lock the screen using xscreensaver. , ((modMask .|. controlMask, xK_l), spawn "xscreensaver-command -lock") -- Launch dmenu -- Use this to launch programs without a key binding. , ((modMask, xK_p), spawn "exe=`dmenu_run -fn 'Monaco-10' -i -nb '#06060D' -nf 'gray' -sb '#FF2300' -sf 'white'` && eval \"exec $exe\"") -- Take a screenshot in select mode. -- After pressing this key binding, click a window, or draw a rectangle with -- the mouse. , ((modMask .|. shiftMask, xK_p), spawn "select-screenshot") -- Take full screenshot in multi-head mode. -- That is, take a screenshot of everything you see. , ((modMask .|. controlMask .|. shiftMask, xK_p), spawn "screenshot") -- Decrease volume. , ((0, 0xffc6), spawn "amixer -q set Master 10%-") -- Increase volume. , ((0, 0xffc7), spawn "amixer -q set Master 10%+") -- Increase Brightness , ((0, 0xffc4), spawn "xbacklight -inc 10") -- Decrease Brightness , ((0, 0xffc3), spawn "xbacklight -dec 10") -- Audio previous. , ((0, 0x1008FF16), spawn "") -- Play/pause. , ((0, 0x1008FF14), spawn "") -- Audio next. , ((0, 0x1008FF17), spawn "") -- Eject CD tray. , ((0, 0x1008FF2C), spawn "eject -T") -------------------------------------------------------------------- -- "Standard" xmonad key bindings -- -- Close focused window. , ((modMask .|. shiftMask, xK_c), kill) -- Cycle through the available layout algorithms. , ((modMask, xK_space), sendMessage NextLayout) -- Reset the layouts on the current workspace to default. , ((modMask .|. shiftMask, xK_space), setLayout $ XMonad.layoutHook conf) -- Resize viewed windows to the correct size. , ((modMask, xK_n), refresh) -- Move focus to the next window. , ((modMask, xK_Tab), windows W.focusDown) -- Move focus to the next window. , ((modMask, xK_j), windows W.focusDown) -- Move focus to the previous window. , ((modMask, xK_k), windows W.focusUp ) -- Move focus to the master window. , ((modMask, xK_m), windows W.focusMaster ) -- Swap the focused window and the master window. , ((modMask, xK_Return), windows W.swapMaster) -- Swap the focused window with the next window. , ((modMask .|. shiftMask, xK_j), windows W.swapDown ) -- Swap the focused window with the previous window. , ((modMask .|. shiftMask, xK_k), windows W.swapUp ) -- Shrink the master area. , ((modMask, xK_h), sendMessage Shrink) -- Expand the master area. , ((modMask, xK_l), sendMessage Expand) -- Push window back into tiling. , ((modMask, xK_t), withFocused $ windows . W.sink) -- Increment the number of windows in the master area. , ((modMask, xK_comma), sendMessage (IncMasterN 1)) -- Decrement the number of windows in the master area. , ((modMask, xK_period), sendMessage (IncMasterN (-1))) -- Toggle the status bar gap. -- TODO: update this binding with avoidStruts, ((modMask, xK_b), -- Quit xmonad. , ((modMask .|. shiftMask, xK_q), io (exitWith ExitSuccess)) -- Restart xmonad. , ((modMask, xK_q), restart "xmonad" True) ] ++ -- mod-[1..9], Switch to workspace N -- mod-shift-[1..9], Move client to workspace N [((m .|. modMask, k), windows $ f i) | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9] , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] ++ -- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3 -- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3 [((m .|. modMask, key), screenWorkspace sc >>= flip whenJust (windows . f)) | (key, sc) <- zip [xK_w, xK_e, xK_r] [0..] , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]] ------------------------------------------------------------------------ -- Mouse bindings -- -- Focus rules -- True if your focus should follow your mouse cursor. myFocusFollowsMouse :: Bool myFocusFollowsMouse = False myMouseBindings (XConfig {XMonad.modMask = modMask}) = M.fromList $ [ -- mod-button1, Set the window to floating mode and move by dragging ((modMask, button1), (\w -> focus w >> mouseMoveWindow w)) -- mod-button2, Raise the window to the top of the stack , ((modMask, button2), (\w -> focus w >> windows W.swapMaster)) -- mod-button3, Set the window to floating mode and resize by dragging , ((modMask, button3), (\w -> focus w >> mouseResizeWindow w)) -- you may also bind events to the mouse scroll wheel (button4 and button5) ] ------------------------------------------------------------------------ -- Status bars and logging -- Perform an arbitrary action on each internal state change or X event. -- See the 'DynamicLog' extension for examples. -- -- To emulate dwm's status bar -- -- > logHook = dynamicLogDzen -- ------------------------------------------------------------------------ -- Startup hook -- Perform an arbitrary action each time xmonad starts or is restarted -- with mod-q. Used by, e.g., XMonad.Layout.PerWorkspace to initialize -- per-workspace layout choices. -- -- By default, do nothing. myStartupHook = return () ------------------------------------------------------------------------ -- Run xmonad with all the defaults we set up. -- main = do xmproc <- spawnPipe "xmobar" xmonad $ defaults { logHook = dynamicLogWithPP $ xmobarPP { ppOutput = hPutStrLn xmproc , ppTitle = xmobarColor xmobarTitleColor "" . shorten 100 . wrap "(" ")" , ppCurrent = xmobarColor xmobarCurrentWSColor "" . wrap "[" "]" , ppHidden = xmobarColor xmobarHiddenWSColor "" . wrap "" "*" , ppHiddenNoWindows = xmobarColor xmobarHiddenWSNoWindowsColor "" , ppUrgent = xmobarColor xmobarUrgentColor "" . wrap "[" "]" , ppSep = " | " } , manageHook = manageDocks <+> myManageHook , startupHook = setWMName "LG3D" } ------------------------------------------------------------------------ -- Combine it all together -- A structure containing your configuration settings, overriding -- fields in the default config. Any you don't override, will -- use the defaults defined in xmonad/XMonad/Config.hs -- -- No need to modify this. -- defaults = defaultConfig { -- simple stuff terminal = myTerminal, focusFollowsMouse = myFocusFollowsMouse, borderWidth = myBorderWidth, modMask = myModMask, workspaces = myWorkspaces, normalBorderColor = myNormalBorderColor, focusedBorderColor = myFocusedBorderColor, -- key bindings keys = myKeys, mouseBindings = myMouseBindings, -- hooks, layouts layoutHook = smartBorders $ myLayout, manageHook = myManageHook, startupHook = myStartupHook }
yamadapc/dotfiles
linux-spf/xmonad/xmonad.hs
mit
11,370
0
15
2,432
1,845
1,138
707
164
1
import Test.Hspec import qualified ARD.CameraSpec import qualified ARD.ColorSpec import qualified ARD.MatrixSpec import qualified ARD.ParserSpec import qualified ARD.SamplerSpec import qualified ARD.ShapeSpec import qualified ARD.VectorSpec main :: IO () main = hspec $ do ARD.CameraSpec.spec ARD.ColorSpec.spec ARD.MatrixSpec.spec ARD.ParserSpec.spec ARD.SamplerSpec.spec ARD.ShapeSpec.spec ARD.VectorSpec.spec
crazymaik/ard-haskell
test/Spec.hs
mit
429
0
8
56
109
62
47
17
1
module Geometry.Sphere ( sphereVolume, sphereArea ) where sphereVolume :: Float -> Float sphereVolume radius = (4.0 / 3.0) * pi * (radius ^ 3) sphereArea :: Float -> Float sphereArea radius = 4 * pi * (radius ^ 2)
fabriceleal/learn-you-a-haskell
07/Geometry/Sphere.hs
mit
225
2
8
50
87
48
39
7
1
module Main (main) where import qualified Graphics.X11 as X import qualified Graphics.X11.Xlib.Extras as XExtras -- import qualified System.Posix as P -- import qualified Control.Monad as M -- import qualified Data.Bits as B import Data.Bits ((.|.)) main :: IO () main = do d <- X.openDisplay "" backgroundColor <- getColor d "#002b36" foregroundColor <- getColor d "#839496" w <- X.createSimpleWindow d (X.defaultRootWindow d) 0 0 800 600 0 backgroundColor backgroundColor gc <- X.createGC d w X.selectInput d w (X.exposureMask .|. X.keyPressMask) X.storeName d w "phim" X.mapWindow d w X.setForeground d gc foregroundColor font <- X.loadQueryFont d "-*-terminus-medium-*-*-*-20-*-*-*-*-*-*-*" X.setFont d gc (X.fontFromFontStruct font) loop d w gc -- X.drawLine d w gc 10 60 180 20 -- X.flush d -- M.forever $ P.sleep 10 X.freeFont d font X.freeGC d gc X.closeDisplay d return () loop :: X.Display -> X.Window -> X.GC -> IO () loop d w gc = do exit <- X.allocaXEvent (\xev -> do X.nextEvent d xev event <- XExtras.getEvent xev print event X.clearWindow d w case event of XExtras.ExposeEvent{} -> do X.fillRectangle d w gc 20 20 10 10 return False XExtras.KeyEvent{XExtras.ev_keycode = keycode} -> do X.drawString d w gc 50 50 (show keycode) return (keycode == 66) _ -> return False ) case exit of True -> return () False -> loop d w gc getColor :: X.Display -> String -> IO X.Pixel getColor d color = do let colorMap = X.defaultColormap d (X.defaultScreen d) (exact, screen) <- X.allocNamedColor d colorMap color return $ X.color_pixel screen
Ziphilt/phim
phim.hs
gpl-2.0
1,821
0
20
524
610
290
320
46
4
-- Copyright (C) 2003 David Roundy -- -- 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, 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; see the file COPYING. If not, write to -- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. {-# LANGUAGE CPP #-} module Darcs.UI.PrintPatch ( printPatch , contextualPrintPatch , printPatchPager , printFriendly , showFriendly ) where import Storage.Hashed.Monad( virtualTreeIO ) import Storage.Hashed.Tree( Tree ) import Darcs.Util.Printer.Color ( fancyPrinters ) import Darcs.Patch.Apply ( ApplyState ) import Darcs.Patch ( showContextPatch, showPatch, showNicely, description, summary ) import Darcs.Patch.Show ( ShowPatch ) import Darcs.UI.External ( viewDocWith ) --import Darcs.UI.Flags ( DarcsFlag(Summary, Verbose), isUnified ) import Darcs.UI.Options.All ( Verbosity(..), Summary(..), WithContext(..) ) import Darcs.Util.Printer ( Doc, putDocLnWith, RenderMode(..) ) -- | @'printFriendly' opts patch@ prints @patch@ in accordance with the flags -- in opts, ie, whether @--verbose@ or @--summary@ were passed at the -- command-line. printFriendly :: (ShowPatch p, ApplyState p ~ Tree) => Maybe (Tree IO) -> Verbosity -> Summary -> WithContext -> p wX wY -> IO () printFriendly (Just pristine) _ _ YesContext = contextualPrintPatch pristine printFriendly _ v s _ = putDocLnWith fancyPrinters . showFriendly v s -- | @'showFriendly' flags patch@ returns a 'Doc' representing the right -- way to show @patch@ given the list @flags@ of flags darcs was invoked with. showFriendly :: ShowPatch p => Verbosity -> Summary -> p wX wY -> Doc showFriendly Verbose _ = showNicely showFriendly _ YesSummary = summary showFriendly _ NoSummary = description -- | 'printPatch' prints a patch on standard output. printPatch :: ShowPatch p => p wX wY -> IO () printPatch p = putDocLnWith fancyPrinters $ showPatch p -- | 'printPatchPager' runs '$PAGER' and shows a patch in it. printPatchPager :: ShowPatch p => p wX wY -> IO () printPatchPager p = viewDocWith fancyPrinters Standard $ showPatch p -- | 'contextualPrintPatch' prints a patch, together with its context, on -- standard output. contextualPrintPatch :: (ShowPatch p, ApplyState p ~ Tree) => Tree IO -> p wX wY -> IO () contextualPrintPatch s p = do (contextedPatch, _) <- virtualTreeIO (showContextPatch p) s putDocLnWith fancyPrinters contextedPatch
DavidAlphaFox/darcs
src/Darcs/UI/PrintPatch.hs
gpl-2.0
2,997
0
12
566
541
301
240
34
1
{-# LANGUAGE ExistentialQuantification #-} {- | Module : ./OMDoc/Import.hs Description : Transforms an OMDoc file into a development graph Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : Ewaryst.Schulz@dfki.de Stability : provisional Portability : non-portable(Logic) Given an OMDoc file, a Library Environment is constructed from it by following all library links. The import requires the following interface functions to be instantiated for each logic Signature Category: ide, cod Sentences: symmap_of StaticAnalysis: id_to_raw, symbol_to_raw, induced_from_morphism, induced_from_to_morphism , signature_union, empty_signature, add_symb_to_sign Logic: omdoc_metatheory, omdocToSym, omdocToSen These functions have default implementations which are sufficient in many cases: addOMadtToTheory, addOmdocToTheory -} module OMDoc.Import where import Common.Result import Common.ResultT import Common.ExtSign import Common.Id import Common.IRI import Common.LibName import Common.Utils import Common.XmlParser (readXmlFile) import Driver.ReadFn (libNameToFile) import Driver.Options (rmSuffix, HetcatsOpts, putIfVerbose, showDiags) import Logic.Logic ( AnyLogic (Logic) , Logic ( omdoc_metatheory, omdocToSym, omdocToSen, addOMadtToTheory , addOmdocToTheory) , Category (ide, cod) , StaticAnalysis ( induced_from_morphism, induced_from_to_morphism , signature_union, empty_signature, add_symb_to_sign , symbol_to_raw, id_to_raw ) , Sentences (symmap_of) ) import Logic.ExtSign import Logic.Coerce import Logic.Prover import Logic.Grothendieck import Comorphisms.LogicList import Comorphisms.LogicGraph import Static.DevGraph import Static.DgUtils import Static.GTheory import Static.AnalysisStructured import Static.ComputeTheory import OMDoc.DataTypes import OMDoc.XmlInterface (xmlIn) import System.Directory import Data.Graph.Inductive.Graph (LNode, Node) import Data.Maybe import Data.List import qualified Data.Map as Map import Control.Monad import Control.Monad.Trans -- * Import Environment Interface {- | There are three important maps for each theory: 1. OMName -> symbol, the NameSymbolMap stores for each OMDoc name the translated hets symbol 2. OMName -> String, the NameMap stores the notation information of the OMDoc names, identity mappings are NOT stored here! 3. SigMapI symbol, this signature map is just a container to store map 1 and 2 -} type NameSymbolMap = G_mapofsymbol OMName -- | The keys of libMap consist of the filepaths without suffix! data ImpEnv = ImpEnv { libMap :: Map.Map FilePath (LibName, DGraph) , nsymbMap :: Map.Map (LibName, String) NameSymbolMap , hetsOptions :: HetcatsOpts } initialEnv :: HetcatsOpts -> ImpEnv initialEnv opts = ImpEnv { libMap = Map.empty , nsymbMap = Map.empty , hetsOptions = opts } getLibEnv :: ImpEnv -> LibEnv getLibEnv e = computeLibEnvTheories $ Map.fromList $ Map.elems $ libMap e addDGToEnv :: ImpEnv -> LibName -> DGraph -> ImpEnv addDGToEnv e ln dg = e { libMap = Map.insert (libNameToFile ln) (ln, dg) $ libMap e } addNSMapToEnv :: ImpEnv -> LibName -> String -> NameSymbolMap -> ImpEnv addNSMapToEnv e ln nm nsm = e { nsymbMap = Map.insert (ln, nm) nsm $ nsymbMap e } lookupLib :: ImpEnv -> IRI -> Maybe (LibName, DGraph) lookupLib e u = Map.lookup (rmSuffix $ iriPath u) $ libMap e lookupNode :: ImpEnv -> CurrentLib -> IriCD -> Maybe ( LibName -- the origin libname of the theory , LNode DGNodeLab -- the (eventually reference) node ) lookupNode e (ln, dg) ucd = let mn = getModule ucd in if cdInLib ucd ln then case filterLocalNodesByName mn dg of [] -> error $ "lookupNode: Node not found: " ++ mn lnode : _ -> Just (ln, lnode) else case lookupLib e $ fromJust $ getIri ucd of Nothing -> Nothing Just (ln', dg') -> case filterRefNodesByName mn ln' dg of lnode : _ -> Just (ln', lnode) [] -> listToMaybe $ map (\ n -> (ln', n)) $ filterLocalNodesByName mn dg' lookupNSMap :: ImpEnv -> LibName -> Maybe LibName -> String -> NameSymbolMap lookupNSMap e ln mLn nm = let ln' = fromMaybe ln mLn mf = Map.findWithDefault $ error $ concat [ "lookupNSMap: lookup failed for " , show (ln', nm), "\n", show mLn, "\n" , show $ nsymbMap e ] in mf (ln', nm) $ nsymbMap e rPutIfVerbose :: ImpEnv -> Int -> String -> ResultT IO () rPutIfVerbose e n s = lift $ putIfVerbose (hetsOptions e) n s rPut :: ImpEnv -> String -> ResultT IO () rPut e = rPutIfVerbose e 1 rPut2 :: ImpEnv -> String -> ResultT IO () rPut2 e = rPutIfVerbose e 2 -- * IRI Functions readFromURL :: (FilePath -> IO a) -> IRI -> IO a readFromURL f u = if isFileIRI u then f $ iriPath u else error $ "readFromURL: Unsupported IRI-scheme " ++ iriScheme u toIRI :: String -> IRI toIRI s = case parseIRIReference s of Just u -> u _ -> error $ "toIRI: can't parse as iri " ++ s libNameFromURL :: String -> IRI -> LibName libNameFromURL s u = setFilePath (iriPath u) $ emptyLibName s -- | Compute an absolute IRI for a supplied IRI relative to the given filepath. resolveIRI :: IRI -> FilePath -> IRI resolveIRI u fp = fromMaybe (error $ "toIRI: can't resolve iri " ++ show u) $ relativeTo u $ toIRI fp -- | Is the scheme of the iri empty or file? isFileIRI :: IRI -> Bool isFileIRI u = elem (iriScheme u) ["", "file:"] type IriCD = (Maybe IRI, String) showIriCD :: IriCD -> String showIriCD (mIri, s) = case mIri of Just u -> show u ++ "?" ++ s _ -> s getIri :: IriCD -> Maybe IRI getIri = fst getModule :: IriCD -> String getModule = snd -- | Compute an absolute IRI for a supplied CD relative to the given LibName toIriCD :: OMCD -> LibName -> IriCD toIriCD cd ln = let [base, m] = cdToList cd fp = getFilePath ln mU = if null base then Nothing else Just $ resolveIRI (toIRI base) fp in (mU, m) getLogicFromMeta :: Maybe OMCD -> AnyLogic getLogicFromMeta mCD = let p (Logic lid) = case omdoc_metatheory lid of Just cd' -> fromJust mCD == cd' _ -> False in if isNothing mCD then defaultLogic else case find p logicList of Just al -> al _ -> defaultLogic cdInLib :: IriCD -> LibName -> Bool cdInLib ucd ln = case getIri ucd of Nothing -> True Just url -> isFileIRI url && getFilePath ln == iriPath url -- * Main translation functions -- | Translates an OMDoc file to a LibEnv anaOMDocFile :: HetcatsOpts -> FilePath -> IO (Maybe (LibName, LibEnv)) anaOMDocFile opts fp = do dir <- getCurrentDirectory putIfVerbose opts 2 $ "Importing OMDoc file " ++ fp Result ds mEnvLn <- runResultT $ importLib (initialEnv opts) $ resolveIRI (toIRI fp) $ dir ++ "/" showDiags opts ds return $ fmap (\ (env, ln, _) -> (ln, getLibEnv env)) mEnvLn -- * OMDoc traversal {- | If the lib is not already in the environment, the OMDoc file and the closure of its imports is added to the environment. -} importLib :: ImpEnv -- ^ The import environment -> IRI -- ^ The url of the OMDoc file -> ResultT IO (ImpEnv, LibName, DGraph) importLib e u = case lookupLib e u of Just (ln, dg) -> return (e, ln, dg) _ -> readLib e u -- | The OMDoc file and the closure of its imports is added to the environment. readLib :: ImpEnv -- ^ The import environment -> IRI -- ^ The url of the OMDoc file -> ResultT IO (ImpEnv, LibName, DGraph) readLib e u = do rPut e $ "Downloading " ++ show u ++ " ..." xmlString <- lift $ readFromURL readXmlFile u OMDoc n l <- ResultT $ xmlIn xmlString {- the name of the omdoc is used as the libname, no relationship between the libname and the filepath! -} let ln = libNameFromURL n u rPut e $ "Importing library " ++ show ln (e', dg) <- foldM (addTLToDGraph ln) (e, emptyDG) l rPut e $ "... loaded " ++ show u return (addDGToEnv e' ln dg, ln, dg) -- | Adds the Theory in the OMCD and the containing lib to the environment importTheory :: ImpEnv -- ^ The import environment -> CurrentLib -- ^ The current lib -> OMCD -- ^ The cd which points to the Theory -> ResultT IO ( ImpEnv -- the updated environment , LibName -- the origin libname of the theory , DGraph -- the updated devgraph of the current lib , LNode DGNodeLab -- the corresponding node ) importTheory e (ln, dg) cd = do let ucd = toIriCD cd ln rPut2 e $ "Looking up theory " ++ showIriCD ucd ++ " ..." case lookupNode e (ln, dg) ucd of Just (ln', nd) | ln == ln' -> do rPut2 e "... found local node." return (e, ln, dg, nd) | isDGRef $ snd nd -> do rPut2 e "... found already referenced node." return (e, ln', dg, nd) | otherwise -> do rPut2 e "... found node, referencing it ..." let (lnode, dg') = addNodeAsRefToDG nd ln' dg rPut2 e "... done" return (e, ln', dg', lnode) -- if lookupNode finds nothing implies that ln is not the current libname! _ -> do let u = fromJust $ getIri ucd rPut2 e "... node not found, reading lib." (e', ln', refDg) <- readLib e u case filterLocalNodesByName (getModule ucd) refDg of -- don't add the node to the refDG but to the original DG! nd : _ -> let (lnode, dg') = addNodeAsRefToDG nd ln' dg in return (e', ln', dg', lnode) [] -> error $ "importTheory: couldn't find node: " ++ show cd -- | Adds a view or theory to the DG, the ImpEnv may also be modified. addTLToDGraph :: LibName -> (ImpEnv, DGraph) -> TLElement -> ResultT IO (ImpEnv, DGraph) -- adding a theory to the DG addTLToDGraph ln (e, dg) (TLTheory n mCD l) = do rPut e $ "Importing theory " ++ n let clf = classifyTCs l {- I. Lookup all imports (= follow and create them first), and insert DGNodeRefs if neccessary. -} ((e', dg'), iIL) <- followImports ln (e, dg) $ importInfo clf -- II. Compute morphisms and update initial sig and name symbol map stepwise. ((nsmap, gSig), iIWL) <- computeMorphisms e' ln (notations clf) (initialSig $ getLogicFromMeta mCD) iIL -- III. Compute local signature (nsmap', gSig') <- liftR $ localSig clf nsmap gSig -- IV. Add the sentences to the Node. gThy <- liftR $ addSentences clf nsmap' gSig' -- V. Complete the morphisms with final signature iIWL' <- liftR $ completeMorphisms (signOf gThy) iIWL -- VI. Add the Node to the DGraph. let ((nd, _), dg'') = addNodeToDG dg' n gThy -- VII. Create links from the morphisms. dg''' = addLinksToDG nd dg'' iIWL' -- add the new name symbol map to the environment e'' = addNSMapToEnv e' ln n nsmap' return (e'', dg''') addTLToDGraph ln (e, dg) (TLView n from to mMor) = do rPut e $ "Importing view " ++ n {- follow the source and target of the view and insert DGNodeRefs if neccessary. use followTheory for from and to. -} ((e', dg'), [lkNdFrom, lkNdTo]) <- followTheories ln (e, dg) [from, to] lkInf <- computeViewMorphism e' ln $ ImportInfo (lkNdFrom, lkNdTo) n mMor let dg'' = addLinkToDG {- this error should never occur as the linkinfo contains a to-node. The error is used here as a "don't care element" of type Node -} (error "addTLToDGraph: TLView - Default node not available") dg' lkInf return (e', dg'') -- ** Utils to compute DGNodes from OMDoc Theories {- the morphisms are incomplete because the target signature wasn't complete at the time of morphism computation. we complete the morphisms by composing them with signature inclusions to the complete target signature -} completeMorphisms :: G_sign -- ^ the complete target signature -> [LinkInfo] -- ^ the incomplete morphisms -> Result [LinkInfo] completeMorphisms gsig = mapR (fmapLI $ completeMorphism $ ide gsig) completeMorphism :: GMorphism -- ^ the target signature id morphism -> GMorphism -- ^ the incomplete morphism -> Result GMorphism completeMorphism idT gmorph = compInclusion logicGraph gmorph idT computeMorphisms :: ImpEnv -> LibName -> Map.Map OMName String -- ^ Notations -> (NameSymbolMap, G_sign) -> [ImportInfo LinkNode] -> ResultT IO ((NameSymbolMap, G_sign), [LinkInfo]) computeMorphisms e ln nots = mapAccumLM (computeMorphism e ln nots) {- | Computes the morphism for an import link and updates the signature and the name symbol map with the imported symbols -} computeMorphism :: ImpEnv -- ^ The import environment for lookup purposes -> LibName -- ^ Current libname -> Map.Map OMName String -- ^ Notations of target signature -> (NameSymbolMap, G_sign) {- ^ OMDoc symbol to Hets symbol map and target signature -} -> ImportInfo LinkNode -- ^ source label with OMDoc morphism -> ResultT IO ((NameSymbolMap, G_sign), LinkInfo) computeMorphism e ln nots (nsmap, tGSig) (ImportInfo (mLn, (from, lbl)) n morph) = case dgn_theory lbl of G_theory sLid _ (ExtSign sSig _) _ _ _ -> case tGSig of G_sign tLid (ExtSign tSig _) sigId -> do let sourceNSMap = lookupNSMap e ln mLn $ getDGNodeName lbl {- 1. build the morphism compute first the symbol-map -} symMap <- computeSymbolMap (Just nots) sourceNSMap nsmap morph tLid let f = symbol_to_raw tLid g (Left (_, rs)) = rs g (Right s) = symbol_to_raw tLid s rsMap = Map.fromList $ map (\ (x, y) -> (f x, g y) ) symMap -- REMARK: Logic-homogeneous environment assumed sSig' <- coercePlainSign sLid tLid "computeMorphism" sSig mor <- liftR $ induced_from_morphism tLid rsMap sSig' {- 2. build the GMorphism and update the signature and the name symbol map -} newSig <- liftR $ signature_union tLid tSig $ cod mor let gMor = gEmbed $ mkG_morphism tLid mor newGSig = G_sign tLid (makeExtSign tLid newSig) sigId {- function for filtering the raw symbols in the nsmap update -} h (s, Left (n', _)) = Just (s, n') h (_, Right _) = Nothing nsmap' = updateSymbolMap tLid mor nsmap $ mapMaybe h symMap return ( (nsmap', newGSig) , (gMor, globalDef, mkLinkOrigin n, from, Nothing)) -- | Computes the morphism for a view computeViewMorphism :: ImpEnv -- ^ The import environment for lookup purposes -> LibName -- ^ Current libname -> ImportInfo (LinkNode, LinkNode) -- ^ OMDoc morphism with source and target node -> ResultT IO LinkInfo computeViewMorphism e ln (ImportInfo ( (mSLn, (from, lblS)) , (mTLn, (to, lblT))) n morph) = case (dgn_theory lblS, dgn_theory lblT) of (G_theory sLid _ eSSig _ _ _, G_theory tLid _ eTSig _ _ _) -> do let nsmapS = lookupNSMap e ln mSLn $ getDGNodeName lblS nsmapT = lookupNSMap e ln mTLn $ getDGNodeName lblT {- 1. build the morphism compute first the symbol-map -} symMap <- computeSymbolMap Nothing nsmapS nsmapT morph tLid let f = symbol_to_raw tLid {- this can't occur as we do not provide a notation map to computeSymbolMap -} g (Left _) = error "computeViewMorphism: impossible case" g (Right s) = symbol_to_raw tLid s rsMap = Map.fromList $ map (\ (x, y) -> (f x, g y) ) symMap -- REMARK: Logic-homogeneous environment assumed eSSig' <- coerceSign sLid tLid "computeViewMorphism" eSSig mor <- liftR $ induced_from_to_morphism tLid rsMap eSSig' eTSig -- 2. build the GMorphism let gMor = gEmbed $ mkG_morphism tLid mor return (gMor, globalThm, mkLinkOrigin n, from, Just to) mkLinkOrigin :: String -> DGLinkOrigin mkLinkOrigin s = DGLinkMorph $ simpleIdToIRI $ mkSimpleId s {- | For each entry (s, n) in l we enter the mapping (n, m(s)) to the name symbol map -} updateSymbolMap :: forall lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree . Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> morphism -- ^ a signature morphism m -> NameSymbolMap -> [(symbol, OMName)] -- ^ a list l of symbol to OMName mappings -> NameSymbolMap updateSymbolMap lid mor nsmap l = case nsmap of G_mapofsymbol lid' sm -> let f nsm (s, n) = Map.insert n (g s) nsm -- fold function g s = Map.findWithDefault (error $ "updateSymbolMap: symbol not found " ++ show s) s $ symmap_of lid mor sm' = coerceMapofsymbol lid' lid sm in G_mapofsymbol lid $ foldl f sm' l {- | Computes a symbol map for the given TCMorphism. The symbols are looked up in the provided maps. For each symbol not found in the target map we return a OMName, raw symbol pair in order to insert the missing entries in the target name symbol map later. If notations are not present, all lookup failures end up in errors. -} computeSymbolMap :: forall lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree . Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => Maybe (Map.Map OMName String) -- ^ Notations for missing symbols in map -> NameSymbolMap -> NameSymbolMap -> TCMorphism -> lid -> ResultT IO [(symbol, Either (OMName, raw_symbol) symbol)] computeSymbolMap mNots nsmapS nsmapT morph lid = case (nsmapS, nsmapT) of (G_mapofsymbol sLid sm, G_mapofsymbol tLid tm) -> do -- REMARK: Logic-homogeneous environment assumed let sNSMap = coerceMapofsymbol sLid lid sm tNSMap = coerceMapofsymbol tLid lid tm mf msg = Map.findWithDefault $ error $ "computeSymbolMap: lookup failed for " ++ msg -- function for notation lookup g = lookupNotationInMap $ fromMaybe (error "computeSymbolMap: no notations") mNots -- function for map f (omn, omimg) = let tSymName = case omimg of Left s -> mkSimpleName s Right (OMS qn) -> unqualName qn _ -> error $ "computeSymbolMap: Nonsymbol " ++ "element mapped" in ( mf (show omn) omn sNSMap , case Map.lookup tSymName tNSMap of Just ts -> Right ts _ -> Left (tSymName, id_to_raw lid $ nameToId $ g tSymName)) return $ map f morph followImports :: LibName -> (ImpEnv, DGraph) -> [ImportInfo OMCD] -> ResultT IO ((ImpEnv, DGraph), [ImportInfo LinkNode]) followImports ln = mapAccumLCM (curry snd) (followImport ln) {- | Ensures that the theory for the given OMCD is available in the environment. See also 'followTheory' -} followImport :: LibName -> (ImpEnv, DGraph) -> ImportInfo OMCD -> ResultT IO ((ImpEnv, DGraph), ImportInfo LinkNode) followImport ln x iInfo = do (x', linknode) <- followTheory ln x $ iInfoVal iInfo return (x', fmap (const linknode) iInfo) followTheories :: LibName -> (ImpEnv, DGraph) -> [OMCD] -> ResultT IO ((ImpEnv, DGraph), [LinkNode]) followTheories ln = mapAccumLCM (curry snd) (followTheory ln) {- | We lookup the theory referenced by the cd in the environment and add it if neccessary to the environment. -} followTheory :: LibName -> (ImpEnv, DGraph) -> OMCD -> ResultT IO ((ImpEnv, DGraph), LinkNode) followTheory ln (e, dg) cd = do (e', ln', dg', lnode) <- importTheory e (ln, dg) cd let mLn = if ln == ln' then Nothing else Just ln' return ((e', dg'), (mLn, lnode)) -- * Development Graph and LibEnv interface {- | returns a function compatible with mapAccumLM for TCElement processing. Used in localSig. -} sigmapAccumFun :: (Monad m, Show a) => (SigMapI a -> TCElement -> String -> m a) -> SigMapI a -> TCElement -> m (SigMapI a, a) sigmapAccumFun f smi s = do let n = tcName s hetsname = lookupNotation smi n s' <- f smi s hetsname let smi' = smi { sigMapISymbs = Map.insert n s' $ sigMapISymbs smi } return (smi', s') -- | Builds an initial signature and a name map of the given logic. initialSig :: AnyLogic -> (NameSymbolMap, G_sign) initialSig lg = case lg of Logic lid -> ( G_mapofsymbol lid Map.empty , G_sign lid (makeExtSign lid $ empty_signature lid) startSigId) -- | Adds the local signature to the given signature and name symbol map localSig :: TCClassification -> NameSymbolMap -> G_sign -> Result (NameSymbolMap, G_sign) localSig clf nsmap gSig = case (gSig, nsmap) of (G_sign lid _ _, G_mapofsymbol lid' sm) -> do let smi = SigMapI (coerceMapofsymbol lid' lid sm) $ notations clf {- accumulates symbol mappings in the symbMap in SigMapI while creating symbols from OMDoc symbols -} (sm', symbs) <- mapAccumLM (sigmapAccumFun $ omdocToSym lid) smi $ sigElems clf -- adding the symbols to the empty signature sig <- foldM (add_symb_to_sign lid) (empty_signature lid) symbs let locGSig = G_sign lid (makeExtSign lid sig) startSigId -- combining the local and the given signature gSig' <- gsigUnion logicGraph True gSig locGSig return (G_mapofsymbol lid $ sigMapISymbs sm', gSig') -- | Adds sentences and logic dependent signature elements to the given sig addSentences :: TCClassification -> NameSymbolMap -> G_sign -> Result G_theory addSentences clf nsmap gsig = case (nsmap, gsig) of (G_mapofsymbol lidM sm, G_sign lid (ExtSign sig _) ind1) -> do let sigm = SigMapI (coerceMapofsymbol lidM lid sm) $ notations clf -- 1. translate sentences mSens <- mapM (\ tc -> omdocToSen lid sigm tc $ lookupNotation sigm $ tcName tc) $ sentences clf -- 2. translate adts (sig', sens') <- addOMadtToTheory lid sigm (sig, catMaybes mSens) $ adts clf {- 3. translate rest of theory (all the sentences or just those which returned Nothing?) -} (sig'', sens'') <- addOmdocToTheory lid sigm (sig', sens') $ sentences clf return $ G_theory lid Nothing (mkExtSign sig'') ind1 (toThSens sens'') startThId -- | Adds Edges from the LinkInfo list to the development graph. addLinksToDG :: Node -> DGraph -> [LinkInfo] -> DGraph addLinksToDG nd = foldl (addLinkToDG nd) -- | Adds Edge from the LinkInfo to the development graph. addLinkToDG :: Node -> DGraph -> LinkInfo -> DGraph addLinkToDG to dg (gMor, lt, lo, from, mTo) = insLink dg gMor lt lo from $ fromMaybe to mTo -- | Adds a Node from the given 'G_theory' to the development graph. addNodeToDG :: DGraph -> String -> G_theory -> (LNode DGNodeLab, DGraph) addNodeToDG dg n gth = let nd = getNewNodeDG dg ndName = parseNodeName n ndInfo = newNodeInfo DGBasic newNode = (nd, newInfoNodeLab ndName ndInfo gth) in (newNode, insNodeDG newNode dg) addNodeAsRefToDG :: LNode DGNodeLab -> LibName -> DGraph -> (LNode DGNodeLab, DGraph) addNodeAsRefToDG (nd, lbl) ln dg = let info = newRefInfo ln nd refNodeM = lookupInAllRefNodesDG info dg nd' = getNewNodeDG dg lnode = (nd', lbl { nodeInfo = info }) dg1 = insNodeDG lnode dg in case refNodeM of Just refNode -> ((refNode, labDG dg refNode), dg) _ -> (lnode, dg1) -- * Theory-utils type CurrentLib = (LibName, DGraph) type LinkNode = (Maybe LibName, LNode DGNodeLab) type LinkInfo = (GMorphism, DGLinkType, DGLinkOrigin, Node, Maybe Node) data ImportInfo a = ImportInfo a String TCMorphism deriving Show iInfoVal :: ImportInfo a -> a iInfoVal (ImportInfo x _ _) = x instance Functor ImportInfo where fmap f (ImportInfo x y z) = ImportInfo (f x) y z fmapLI :: Monad m => (GMorphism -> m GMorphism) -> LinkInfo -> m LinkInfo fmapLI f (gm, x, y, z, t) = do gm' <- f gm return (gm', x, y, z, t) data TCClassification = TCClf { importInfo :: [ImportInfo OMCD] -- ^ Import-info , sigElems :: [TCElement] -- ^ Signature symbols , sentences :: [TCElement] -- ^ Theory sentences , adts :: [[OmdADT]] -- ^ ADTs , notations :: Map.Map OMName String -- ^ Notations } emptyClassification :: TCClassification emptyClassification = TCClf [] [] [] [] Map.empty classifyTCs :: [TCElement] -> TCClassification classifyTCs = foldr classifyTC emptyClassification classifyTC :: TCElement -> TCClassification -> TCClassification classifyTC tc clf = case tc of TCSymbol _ _ sr _ | elem sr [Obj, Typ] -> clf { sigElems = tc : sigElems clf } | otherwise -> clf { sentences = tc : sentences clf } TCNotation (cd, omn) n (Just "hets") -> if cdIsEmpty cd then clf { notations = Map.insert omn n $ notations clf } else clf TCADT l -> clf { adts = l : adts clf } TCImport n from morph -> clf { importInfo = ImportInfo from n morph : importInfo clf } TCComment _ -> clf TCSmartNotation {} -> error "classifyTC: unexpected SmartNotation" TCFlexibleNotation {} -> error "classifyTC: unexpected FlexibleNotation" -- just for the case TCNotation with a style different from hets _ -> clf
gnn/Hets
OMDoc/Import.hs
gpl-2.0
27,629
0
23
8,485
6,732
3,508
3,224
462
9
{- | Module : $Header$ Description : Abstract syntax of CASL basic specifications Copyright : (c) Klaus Luettich, Christian Maeder, Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable Abstract Syntax of CASL Basic_specs, Symb_items and Symb_map_items. Follows Sect. II:2.2 of the CASL Reference Manual. -} module CASL.AS_Basic_CASL where import Common.Id import Common.AS_Annotation import qualified Data.Set as Set -- DrIFT command {-! global: GetRange !-} data BASIC_SPEC b s f = Basic_spec [Annoted (BASIC_ITEMS b s f)] deriving Show data BASIC_ITEMS b s f = Sig_items (SIG_ITEMS s f) {- the Annotation following the keyword is dropped but preceding the keyword is now an Annotation allowed -} | Free_datatype SortsKind [Annoted DATATYPE_DECL] Range -- pos: free, type, semi colons | Sort_gen [Annoted (SIG_ITEMS s f)] Range -- pos: generated, opt. braces | Var_items [VAR_DECL] Range -- pos: var, semi colons | Local_var_axioms [VAR_DECL] [Annoted (FORMULA f)] Range -- pos: forall, semi colons, dots | Axiom_items [Annoted (FORMULA f)] Range -- pos: dots | Ext_BASIC_ITEMS b deriving Show data SortsKind = NonEmptySorts | PossiblyEmptySorts deriving Show data SIG_ITEMS s f = Sort_items SortsKind [Annoted (SORT_ITEM f)] Range -- pos: sort, semi colons | Op_items [Annoted (OP_ITEM f)] Range -- pos: op, semi colons | Pred_items [Annoted (PRED_ITEM f)] Range -- pos: pred, semi colons | Datatype_items SortsKind [Annoted DATATYPE_DECL] Range -- type, semi colons | Ext_SIG_ITEMS s deriving Show data SORT_ITEM f = Sort_decl [SORT] Range -- pos: commas | Subsort_decl [SORT] SORT Range -- pos: commas, < | Subsort_defn SORT VAR SORT (Annoted (FORMULA f)) Range {- pos: "=", "{", ":", ".", "}" the left anno list stored in Annoted Formula is parsed after the equal sign -} | Iso_decl [SORT] Range -- pos: "="s deriving Show data OP_ITEM f = Op_decl [OP_NAME] OP_TYPE [OP_ATTR f] Range -- pos: commas, colon, OP_ATTR sep. by commas | Op_defn OP_NAME OP_HEAD (Annoted (TERM f)) Range -- pos: "=" deriving Show data OpKind = Total | Partial deriving (Show, Eq, Ord) data OP_TYPE = Op_type OpKind [SORT] SORT Range -- pos: "*"s, "->" ; if null [SORT] then Range = [] or pos: "?" deriving (Show, Eq, Ord) args_OP_TYPE :: OP_TYPE -> [SORT] args_OP_TYPE (Op_type _ args _ _) = args res_OP_TYPE :: OP_TYPE -> SORT res_OP_TYPE (Op_type _ _ res _) = res data OP_HEAD = Op_head OpKind [VAR_DECL] (Maybe SORT) Range -- pos: "(", semicolons, ")", colon deriving (Show, Eq, Ord) data OP_ATTR f = Assoc_op_attr | Comm_op_attr | Idem_op_attr | Unit_op_attr (TERM f) deriving (Show, Eq, Ord) data PRED_ITEM f = Pred_decl [PRED_NAME] PRED_TYPE Range -- pos: commas, colon | Pred_defn PRED_NAME PRED_HEAD (Annoted (FORMULA f)) Range -- pos: "<=>" deriving Show data PRED_TYPE = Pred_type [SORT] Range -- pos: if null [SORT] then "(",")" else "*"s deriving (Show, Eq, Ord) data PRED_HEAD = Pred_head [VAR_DECL] Range -- pos: "(",semi colons , ")" deriving Show data DATATYPE_DECL = Datatype_decl SORT [Annoted ALTERNATIVE] Range -- pos: "::=", "|"s deriving Show data ALTERNATIVE = Alt_construct OpKind OP_NAME [COMPONENTS] Range -- pos: "(", semi colons, ")" optional "?" | Subsorts [SORT] Range -- pos: sort, commas deriving Show data COMPONENTS = Cons_select OpKind [OP_NAME] SORT Range -- pos: commas, colon or ":?" | Sort SORT deriving Show data VAR_DECL = Var_decl [VAR] SORT Range -- pos: commas, colon deriving (Show, Eq, Ord) varDeclRange :: VAR_DECL -> [Pos] varDeclRange (Var_decl vs s _) = case vs of [] -> [] v : _ -> joinRanges [tokenRange v, idRange s] {- Position definition for FORMULA: Information on parens are also encoded in Range. If there are more Pos than necessary there is a pair of Pos enclosing the other Pos informations which encode the brackets of every kind -} data Junctor = Con | Dis deriving (Show, Eq, Ord) data Relation = Implication | RevImpl | Equivalence deriving (Show, Eq, Ord) data Equality = Strong | Existl deriving (Show, Eq, Ord) data FORMULA f = Quantification QUANTIFIER [VAR_DECL] (FORMULA f) Range -- pos: QUANTIFIER, semi colons, dot | Junction Junctor [FORMULA f] Range -- pos: "/\"s or "\/"s | Relation (FORMULA f) Relation (FORMULA f) Range {- pos: "<=>", "=>" or "if" note: the first formula is the premise also for "if"! -} | Negation (FORMULA f) Range -- pos: not | Atom Bool Range -- pos: true or false | Predication PRED_SYMB [TERM f] Range -- pos: opt. "(",commas,")" | Definedness (TERM f) Range -- pos: def | Equation (TERM f) Equality (TERM f) Range -- pos: =e= or = | Membership (TERM f) SORT Range -- pos: in | Mixfix_formula (TERM f) {- Mixfix_ Term/Token/(..)/[..]/{..} a formula left original for mixfix analysis -} | Unparsed_formula String Range -- pos: first Char in String | Sort_gen_ax [Constraint] Bool -- flag: belongs to a free type? | QuantOp OP_NAME OP_TYPE (FORMULA f) -- second order quantifiers | QuantPred PRED_NAME PRED_TYPE (FORMULA f) | ExtFORMULA f -- needed for CASL extensions deriving (Show, Eq, Ord) is_True_atom :: FORMULA f -> Bool is_True_atom f = case f of Atom b _ -> b _ -> False is_False_atom :: FORMULA f -> Bool is_False_atom f = case f of Atom b _ -> not b _ -> False boolForm :: Bool -> FORMULA f boolForm b = Atom b nullRange trueForm :: FORMULA f trueForm = boolForm True falseForm :: FORMULA f falseForm = boolForm False {- In the CASL institution, sort generation constraints have an additional signature morphism component (Sect. III:2.1.3, p.134 of the CASL Reference Manual). The extra signature morphism component is needed because the naive translation of sort generation constraints along signature morphisms may violate the satisfaction condition, namely when sorts are identified by the translation, with the effect that new terms can be formed. We avoid this extra component here and instead use natural numbers to decorate sorts, in this way retaining their identity w.r.t. the original signature. The newSort in a Constraint is implicitly decorated with its index in the list of Constraints. The opSymbs component collects all the operation symbols with newSort (with that index!) as a result sort. The argument sorts of an operation symbol are decorated explicitly via a list [Int] of integers. The origSort in a Constraint is the original sort corresponding to the index. A negative index indicates a sort outside the constraint (i.e. a "parameter sort"). Note that this representation of sort generation constraints is efficiently tailored towards both the use in the proof calculus (Chap. IV:2, p. 282 of the CASL Reference Manual) and the coding into second order logic (p. 429 of Theoret. Comp. Sci. 286). -} data Constraint = Constraint { newSort :: SORT, opSymbs :: [(OP_SYMB, [Int])], origSort :: SORT } deriving (Show, Eq, Ord) -- | no duplicate sorts, i.e. injective sort map? isInjectiveList :: Ord a => [a] -> Bool isInjectiveList l = Set.size (Set.fromList l) == length l {- | from a Sort_gex_ax, recover: a traditional sort generation constraint plus a sort mapping -} recover_Sort_gen_ax :: [Constraint] -> ([SORT], [OP_SYMB], [(SORT, SORT)]) recover_Sort_gen_ax constrs = if isInjectiveList sorts -- we can ignore indices then (sorts, map fst (concatMap opSymbs constrs), []) {- otherwise, we have to introduce new sorts for the indices and afterwards rename them into the sorts they denote -} else (origSorts, indOps, zip origSorts sorts) where sorts = map newSort constrs origSorts = map origSort constrs indSort s i = if i < 0 then s else origSorts !! i indOps = concatMap (\ c -> map (indOp $ origSort c) $ opSymbs c) constrs indOp res (Qual_op_name on (Op_type k args1 _ pos1) pos, args) = Qual_op_name on (Op_type k (zipWith indSort args1 args) res pos1) pos indOp _ _ = error "CASL/AS_Basic_CASL: Internal error: Unqualified OP_SYMB in Sort_gen_ax" {- | from a Sort_gen_ax, recover: the sorts, each paired with the constructors -} recoverSortGen :: [Constraint] -> [(SORT, [OP_SYMB])] recoverSortGen = map $ \ c -> (newSort c, map fst $ opSymbs c) {- | from a free Sort_gen_ax, recover: the sorts, each paired with the constructors fails (i.e. delivers Nothing) if the sort map is not injective -} recover_free_Sort_gen_ax :: [Constraint] -> Maybe [(SORT, [OP_SYMB])] recover_free_Sort_gen_ax constrs = if isInjectiveList $ map newSort constrs then Just $ recoverSortGen constrs else Nothing -- | determine whether a formula is a sort generation constraint isSortGen :: FORMULA f -> Bool isSortGen f = case f of Sort_gen_ax _ _ -> True _ -> False data QUANTIFIER = Universal | Existential | Unique_existential deriving (Show, Eq, Ord) data PRED_SYMB = Pred_name PRED_NAME | Qual_pred_name PRED_NAME PRED_TYPE Range -- pos: "(", pred, colon, ")" deriving (Show, Eq, Ord) predSymbName :: PRED_SYMB -> PRED_NAME predSymbName p = case p of Pred_name n -> n Qual_pred_name n _ _ -> n data TERM f = Qual_var VAR SORT Range -- pos: "(", var, colon, ")" | Application OP_SYMB [TERM f] Range -- pos: parens around TERM f if any and seperating commas | Sorted_term (TERM f) SORT Range -- pos: colon | Cast (TERM f) SORT Range -- pos: "as" | Conditional (TERM f) (FORMULA f) (TERM f) Range -- pos: "when", "else" | Unparsed_term String Range -- SML-CATS -- A new intermediate state | Mixfix_qual_pred PRED_SYMB -- as part of a mixfix formula | Mixfix_term [TERM f] -- not starting with Mixfix_sorted_term/cast | Mixfix_token Token -- NO-BRACKET-TOKEN, LITERAL, PLACE | Mixfix_sorted_term SORT Range -- pos: colon | Mixfix_cast SORT Range -- pos: "as" | Mixfix_parenthesized [TERM f] Range {- non-emtpy term list pos: "(", commas, ")" -} | Mixfix_bracketed [TERM f] Range -- pos: "[", commas, "]" | Mixfix_braced [TERM f] Range {- also for list-notation pos: "{", "}" -} | ExtTERM f deriving (Show, Eq, Ord) -- | state after mixfix- but before overload resolution varOrConst :: Token -> TERM f varOrConst t = Application (Op_name $ simpleIdToId t) [] $ tokPos t data OP_SYMB = Op_name OP_NAME | Qual_op_name OP_NAME OP_TYPE Range -- pos: "(", op, colon, ")" deriving (Show, Eq, Ord) opSymbName :: OP_SYMB -> OP_NAME opSymbName o = case o of Op_name n -> n Qual_op_name n _ _ -> n -- * short cuts for terms and formulas -- | create binding if variables are non-null mkForallRange :: [VAR_DECL] -> FORMULA f -> Range -> FORMULA f mkForallRange vl f ps = if null vl then f else Quantification Universal vl f ps mkForall :: [VAR_DECL] -> FORMULA f -> FORMULA f mkForall vl f = mkForallRange vl f nullRange -- | create an existential binding mkExist :: [VAR_DECL] -> FORMULA f -> FORMULA f mkExist vs f = Quantification Existential vs f nullRange -- | convert a singleton variable declaration into a qualified variable toQualVar :: VAR_DECL -> TERM f toQualVar (Var_decl v s ps) = if isSingle v then Qual_var (head v) s ps else error "toQualVar" mkRel :: Relation -> FORMULA f -> FORMULA f -> FORMULA f mkRel r f f' = Relation f r f' nullRange mkImpl :: FORMULA f -> FORMULA f -> FORMULA f mkImpl = mkRel Implication mkAnyEq :: Equality -> TERM f -> TERM f -> FORMULA f mkAnyEq e f f' = Equation f e f' nullRange mkExEq :: TERM f -> TERM f -> FORMULA f mkExEq = mkAnyEq Existl mkStEq :: TERM f -> TERM f -> FORMULA f mkStEq = mkAnyEq Strong mkEqv :: FORMULA f -> FORMULA f -> FORMULA f mkEqv = mkRel Equivalence mkAppl :: OP_SYMB -> [TERM f] -> TERM f mkAppl op_symb fs = Application op_symb fs nullRange mkPredication :: PRED_SYMB -> [TERM f] -> FORMULA f mkPredication symb fs = Predication symb fs nullRange -- | turn sorted variable into variable delcaration mkVarDecl :: VAR -> SORT -> VAR_DECL mkVarDecl v s = Var_decl [v] s nullRange -- | turn sorted variable into term mkVarTerm :: VAR -> SORT -> TERM f mkVarTerm v = toQualVar . mkVarDecl v -- | optimized conjunction conjunctRange :: [FORMULA f] -> Range -> FORMULA f conjunctRange fs ps = case fs of [] -> Atom True ps [phi] -> phi _ -> Junction Con fs ps conjunct :: [FORMULA f] -> FORMULA f conjunct fs = conjunctRange fs nullRange disjunctRange :: [FORMULA f] -> Range -> FORMULA f disjunctRange fs ps = case fs of [] -> Atom False ps [phi] -> phi _ -> Junction Dis fs ps disjunct :: [FORMULA f] -> FORMULA f disjunct fs = disjunctRange fs nullRange mkQualOp :: OP_NAME -> OP_TYPE -> OP_SYMB mkQualOp f ty = Qual_op_name f ty nullRange mkQualPred :: PRED_NAME -> PRED_TYPE -> PRED_SYMB mkQualPred f ty = Qual_pred_name f ty nullRange negateForm :: FORMULA f -> Range -> FORMULA f negateForm f r = case f of Atom b ps -> Atom (not b) ps Negation nf _ -> nf _ -> Negation f r mkNeg :: FORMULA f -> FORMULA f mkNeg f = negateForm f nullRange mkVarDeclStr :: String -> SORT -> VAR_DECL mkVarDeclStr = mkVarDecl . mkSimpleId -- * type synonyms type CASLFORMULA = FORMULA () type CASLTERM = TERM () type OP_NAME = Id type PRED_NAME = Id type SORT = Id type VAR = Token data SYMB_ITEMS = Symb_items SYMB_KIND [SYMB] Range -- pos: SYMB_KIND, commas deriving (Show, Eq) data SYMB_MAP_ITEMS = Symb_map_items SYMB_KIND [SYMB_OR_MAP] Range -- pos: SYMB_KIND, commas deriving (Show, Eq) data SYMB_KIND = Implicit | Sorts_kind | Ops_kind | Preds_kind deriving (Show, Eq, Ord) data SYMB = Symb_id Id | Qual_id Id TYPE Range -- pos: colon deriving (Show, Eq) data TYPE = O_type OP_TYPE | P_type PRED_TYPE | A_type SORT -- ambiguous pred or (constant total) op deriving (Show, Eq) data SYMB_OR_MAP = Symb SYMB | Symb_map SYMB SYMB Range -- pos: "|->" deriving (Show, Eq)
nevrenato/HetsAlloy
CASL/AS_Basic_CASL.der.hs
gpl-2.0
15,877
0
14
4,742
3,474
1,871
1,603
241
4
{- | Module : ./OWL2/XMLConversion.hs Copyright : (c) Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : f.mance@jacobs-university.de Stability : provisional Portability : portable Conversion from Manchester Syntax to XML Syntax -} module OWL2.XMLConversion where import Common.AS_Annotation (Named, sentence) import Common.GlobalAnnotations as GA (PrefixMap) import Common.IRI hiding (showIRI) import Common.Id import OWL2.AS import OWL2.Sign import OWL2.XMLKeywords import OWL2.Keywords (DatatypeFacet(..)) import Text.XML.Light import Data.Maybe import qualified Data.Set as Set import qualified Data.Map as Map -- | prints the IRI showIRI :: IRI -> String showIRI iri = (if isURN iri then showURN else showIRIFull) iri {hasAngles = False} nullQN :: Text.XML.Light.QName nullQN = QName "" Nothing Nothing nullElem :: Element nullElem = Element nullQN [] [] Nothing makeQN :: String -> Text.XML.Light.QName makeQN s = nullQN {qName = s} -- | sets the content of an element to a list of given elements setContent :: [Element] -> Element -> Element setContent cl e = e {elContent = map Elem cl} -- | sets the content of an element to a given string setText :: String -> Element -> Element setText s e = e {elContent = [Text CData {cdVerbatim = CDataText, cdData = s, cdLine = Nothing}]} setQNPrefix :: String -> Text.XML.Light.QName -> Text.XML.Light.QName setQNPrefix s qn = qn {qPrefix = Just s} {- | sets the name of an element to a given string and the namespace to <http://www.w3.org/2002/07/owl#> -} setName :: String -> Element -> Element setName s e = e {elName = nullQN {qName = s, qURI = Just "http://www.w3.org/2002/07/owl#"} } {- | sets the attribute key to one of IRI, abbreviatedIRI or nodeID and the attribute value to the actual content of the IRI -} setIRI :: IRI -> Element -> Element setIRI iri e = let (ty, fn) | isAbbrev iri = ("abbreviatedIRI", showIRICompact) | isBlankNode iri = (nodeID, showIRI) | otherwise = (iriK, showIRI) in e {elAttribs = [Attr {attrKey = makeQN ty, attrVal = fn $ setReservedPrefix iri}]} mwIRI :: IRI -> Element mwIRI iri = setIRI iri nullElem -- | makes an element with the string as name and the IRI as content mwNameIRI :: String -> IRI -> Element mwNameIRI s iri = setName s $ mwIRI iri -- | makes a new element with the given string as name mwString :: String -> Element mwString s = setName s nullElem -- | makes a new element with the string as name and an element as content makeElementWith1 :: String -> Element -> Element makeElementWith1 s e = setContent [e] $ mwString s {- | makes a new element with the string as name and the list of elements as content -} makeElement :: String -> [Element] -> Element makeElement s el = setContent el $ mwString s mwText :: String -> Element mwText s = setText s nullElem -- | makes a new element with the IRI as the text content mwSimpleIRI :: IRI -> Element mwSimpleIRI s = setName (if hasFullIRI s then iriK else abbreviatedIRI) $ mwText $ showIRI $ setReservedPrefix s {- | generates a list of elements, all with the first string as name, and each with the content in this order: first, the list of elements in the given pair (usually annotations) and second, the result of the application of the function (given as fourth argument) on the second string and the given IRI -} make1 :: Bool -> String -> String -> (String -> IRI -> Element) -> IRI -> [([Element], Element)] -> [Element] make1 rl hdr shdr f iri = map (\ (a, b) -> makeElement hdr $ a ++ (if rl then [f shdr iri, b] else [b, f shdr iri])) -- almost the same, just that the function takes only one argument make2 :: Bool -> String -> (a -> Element) -> a -> [([Element], Element)] -> [Element] make2 rl hdr f expr = map (\ (x, y) -> makeElement hdr $ x ++ (if rl then [f expr, y] else [y, f expr])) -- | sets the cardinality setInt :: Int -> Element -> Element setInt i e = e {elAttribs = [Attr {attrKey = makeQN "cardinality", attrVal = show i}]} -- | the reverse of @properFacet@ in "OWL2.XML" correctFacet :: ConstrainingFacet -> ConstrainingFacet correctFacet c = case getPredefName c of ">" -> facetToIRINoSign MAXEXCLUSIVE "<" -> facetToIRINoSign MINEXCLUSIVE ">=" -> facetToIRINoSign MAXINCLUSIVE "<=" -> facetToIRINoSign MININCLUSIVE _ -> c -- | sets either a literal datatype or a facet setDt :: Bool -> IRI -> Element -> Element setDt b dt e = e {elAttribs = elAttribs e ++ [Attr {attrKey = makeQN (if b then "datatypeIRI" else "facet"), attrVal = showIRI $ if b then setReservedPrefix dt else correctFacet dt}]} setLangTag :: Maybe LanguageTag -> Element -> Element setLangTag ml e = case ml of Nothing -> e Just lt -> e {elAttribs = elAttribs e ++ [Attr {attrKey = setQNPrefix "xml" (makeQN "lang"), attrVal = lt}]} xmlEntity :: Entity -> Element xmlEntity (Entity _ ty ent) = mwNameIRI (case ty of Class -> classK Datatype -> datatypeK ObjectProperty -> objectPropertyK DataProperty -> dataPropertyK AnnotationProperty -> annotationPropertyK NamedIndividual -> namedIndividualK) ent xmlLiteral :: Literal -> Element xmlLiteral l = case l of Literal lf tu -> let part = setName literalK $ mwText lf in case tu of Typed dt -> setDt True dt part Untyped lang -> setLangTag lang $ setDt True plainDatatypeIRI part NumberLit f -> setDt True (nullIRI {iriScheme = "http:", iriPath = stringToId $ "//www.w3.org/2001/XMLSchema#" ++ numberName f}) $ setName literalK $ mwText $ show f xmlIndividual :: IRI -> Element xmlIndividual iri = mwNameIRI (if isAnonymous iri then anonymousIndividualK else namedIndividualK) iri xmlFVPair :: (ConstrainingFacet, RestrictionValue) -> Element xmlFVPair (cf, rv) = setDt False cf $ makeElement facetRestrictionK [xmlLiteral rv] xmlObjProp :: ObjectPropertyExpression -> Element xmlObjProp ope = case ope of ObjectProp op -> mwNameIRI objectPropertyK op ObjectInverseOf i -> makeElement objectInverseOfK [xmlObjProp i] xmlDataRange :: DataRange -> Element xmlDataRange dr = case dr of DataType dt cfl -> let dtelem = mwNameIRI datatypeK dt in if null cfl then dtelem else makeElement datatypeRestrictionK $ dtelem : map xmlFVPair cfl DataJunction jt drl -> makeElement ( case jt of IntersectionOf -> dataIntersectionOfK UnionOf -> dataUnionOfK) $ map xmlDataRange drl DataComplementOf drn -> makeElement dataComplementOfK [xmlDataRange drn] DataOneOf ll -> makeElement dataOneOfK $ map xmlLiteral ll xmlClassExpression :: ClassExpression -> Element xmlClassExpression ce = case ce of Expression c -> mwNameIRI classK c ObjectJunction jt cel -> makeElement ( case jt of IntersectionOf -> objectIntersectionOfK UnionOf -> objectUnionOfK) $ map xmlClassExpression cel ObjectComplementOf cex -> makeElement objectComplementOfK [xmlClassExpression cex] ObjectOneOf il -> makeElement objectOneOfK $ map xmlIndividual il ObjectValuesFrom qt ope cex -> makeElement ( case qt of AllValuesFrom -> objectAllValuesFromK SomeValuesFrom -> objectSomeValuesFromK) [xmlObjProp ope, xmlClassExpression cex] ObjectHasValue ope i -> makeElement objectHasValueK [xmlObjProp ope, xmlIndividual i] ObjectHasSelf ope -> makeElement objectHasSelfK [xmlObjProp ope] ObjectCardinality (Cardinality ct i op mce) -> setInt i $ makeElement ( case ct of MinCardinality -> objectMinCardinalityK MaxCardinality -> objectMaxCardinalityK ExactCardinality -> objectExactCardinalityK) $ xmlObjProp op : case mce of Nothing -> [] Just cexp -> [xmlClassExpression cexp] DataValuesFrom qt dp dr -> makeElement ( case qt of AllValuesFrom -> dataAllValuesFromK SomeValuesFrom -> dataSomeValuesFromK) [mwNameIRI dataPropertyK (head dp), xmlDataRange dr] DataHasValue dp l -> makeElement dataHasValueK [mwNameIRI dataPropertyK dp, xmlLiteral l] DataCardinality (Cardinality ct i dp mdr) -> setInt i $ makeElement ( case ct of MinCardinality -> dataMinCardinalityK MaxCardinality -> dataMaxCardinalityK ExactCardinality -> dataExactCardinalityK) $ mwNameIRI dataPropertyK dp : case mdr of Nothing -> [] Just dr -> [xmlDataRange dr] xmlAnnotation :: Annotation -> Element xmlAnnotation (Annotation al ap av) = makeElement annotationK $ map xmlAnnotation al ++ [mwNameIRI annotationPropertyK ap, case av of AnnValue iri -> xmlSubject iri AnnValLit l -> xmlLiteral l AnnAnInd iri -> xmlSubject iri] xmlSubject :: IRI -> Element xmlSubject iri = if isAnonymous iri then xmlIndividual iri else mwSimpleIRI iri xmlAnnotations :: [Annotation] -> [Element] xmlAnnotations = map xmlAnnotation xmlAssertion :: IRI -> [Annotation] -> [Element] xmlAssertion iri = map (\ (Annotation as ap av) -> makeElement annotationAssertionK $ xmlAnnotations as ++ [mwNameIRI annotationPropertyK ap] ++ [xmlSubject iri, case av of AnnValue avalue -> xmlSubject avalue AnnAnInd ind -> xmlSubject ind AnnValLit l -> xmlLiteral l]) xmlAxioms :: Axiom -> [Element] xmlAxioms axiom = case axiom of Declaration anns entity -> [makeElement declarationK $ xmlAnnotations anns ++ [xmlEntity entity]] ClassAxiom clAxiom -> case clAxiom of SubClassOf anns sub sup -> make2 True subClassOfK xmlClassExpression sub [(xmlAnnotations anns, xmlClassExpression sup)] EquivalentClasses anns ces -> [makeElement equivalentClassesK $ xmlAnnotations anns ++ map xmlClassExpression ces] DisjointClasses anns ces -> [makeElement disjointClassesK $ xmlAnnotations anns ++ map xmlClassExpression ces] DisjointUnion anns clIri ces -> [makeElement disjointUnionK $ xmlAnnotations anns ++ map xmlClassExpression ((Expression clIri) : ces)] ObjectPropertyAxiom opAxiom -> case opAxiom of SubObjectPropertyOf anns sub sup -> case sub of SubObjPropExpr_obj op -> make2 True subObjectPropertyOfK xmlObjProp op [(xmlAnnotations anns, xmlObjProp sup)] SubObjPropExpr_exprchain ops -> let xmlop = map xmlObjProp ops in [makeElement subObjectPropertyOfK $ xmlAnnotations anns ++ [makeElement objectPropertyChainK xmlop , xmlObjProp sup]] EquivalentObjectProperties anns ops -> [makeElement equivalentObjectPropertiesK $ xmlAnnotations anns ++ map xmlObjProp ops] DisjointObjectProperties anns ops -> [makeElement disjointObjectPropertiesK $ xmlAnnotations anns ++ map xmlObjProp ops] InverseObjectProperties anns op1 op2 -> make2 True inverseObjectPropertiesK xmlObjProp op1 [(xmlAnnotations anns, xmlObjProp op2)] ObjectPropertyDomain anns op ce -> make2 True objectPropertyDomainK xmlObjProp op [(xmlAnnotations anns, xmlClassExpression ce)] ObjectPropertyRange anns op ce -> make2 True objectPropertyRangeK xmlObjProp op [(xmlAnnotations anns, xmlClassExpression ce)] FunctionalObjectProperty anns op -> [makeElement functionalObjectPropertyK $ xmlAnnotations anns ++ [xmlObjProp op]] InverseFunctionalObjectProperty anns op -> [makeElement inverseFunctionalObjectPropertyK $ xmlAnnotations anns ++ [xmlObjProp op]] ReflexiveObjectProperty anns op -> [makeElement reflexiveObjectPropertyK $ xmlAnnotations anns ++ [xmlObjProp op]] IrreflexiveObjectProperty anns op -> [makeElement irreflexiveObjectPropertyK $ xmlAnnotations anns ++ [xmlObjProp op]] SymmetricObjectProperty anns op -> [makeElement symmetricObjectPropertyK $ xmlAnnotations anns ++ [xmlObjProp op]] AsymmetricObjectProperty anns op -> [makeElement asymmetricObjectPropertyK $ xmlAnnotations anns ++ [xmlObjProp op]] TransitiveObjectProperty anns op -> [makeElement transitiveObjectPropertyK $ xmlAnnotations anns ++ [xmlObjProp op]] DataPropertyAxiom dpAxiom -> case dpAxiom of SubDataPropertyOf anns sub sup -> make1 True subDataPropertyOfK dataPropertyK mwNameIRI sub [(xmlAnnotations anns, mwNameIRI dataPropertyK sup)] EquivalentDataProperties anns dps -> [makeElement equivalentDataPropertiesK $ xmlAnnotations anns ++ map (mwNameIRI dataPropertyK) dps] DisjointDataProperties anns dps -> [makeElement disjointDataPropertiesK $ xmlAnnotations anns ++ map (mwNameIRI dataPropertyK) dps] DataPropertyDomain anns dpe ce -> make1 True dataPropertyDomainK dataPropertyK mwNameIRI dpe [(xmlAnnotations anns, xmlClassExpression ce)] DataPropertyRange anns dpe dr -> make1 True dataPropertyRangeK dataPropertyK mwNameIRI dpe [(xmlAnnotations anns, xmlDataRange dr)] FunctionalDataProperty anns dpe -> [makeElement functionalDataPropertyK $ xmlAnnotations anns ++ [mwNameIRI dataPropertyK dpe]] DatatypeDefinition anns dt dr -> [makeElement datatypeDefinitionK $ xmlAnnotations anns ++ [mwNameIRI datatypeK dt, xmlDataRange dr]] HasKey anns ce ops dps -> [makeElement hasKeyK $ xmlAnnotations anns ++ [xmlClassExpression ce] ++ map xmlObjProp ops ++ map (mwNameIRI dataPropertyK) dps] Assertion aAxiom -> case aAxiom of SameIndividual anns inds -> [makeElement sameIndividualK $ xmlAnnotations anns ++ map xmlIndividual inds] DifferentIndividuals anns inds -> [makeElement differentIndividualsK $ xmlAnnotations anns ++ map xmlIndividual inds] ClassAssertion anns ce ind -> make2 False classAssertionK xmlIndividual ind [(xmlAnnotations anns, xmlClassExpression ce)] ObjectPropertyAssertion anns op sInd tInd -> [makeElement objectPropertyAssertionK $ xmlAnnotations anns ++ [xmlObjProp op] ++ map xmlIndividual [sInd, tInd]] NegativeObjectPropertyAssertion anns op sInd tInd -> [makeElement negativeObjectPropertyAssertionK $ xmlAnnotations anns ++ [xmlObjProp op] ++ map xmlIndividual [sInd, tInd]] DataPropertyAssertion anns dp sInd tVal -> [makeElement dataPropertyAssertionK $ xmlAnnotations anns ++ [mwNameIRI dataPropertyK dp] ++ [xmlIndividual sInd] ++ [xmlLiteral tVal]] NegativeDataPropertyAssertion anns dp sInd tVal -> [makeElement negativeDataPropertyAssertionK $ xmlAnnotations anns ++ [mwNameIRI dataPropertyK dp] ++ [xmlIndividual sInd] ++ [xmlLiteral tVal]] AnnotationAxiom annAxiom -> case annAxiom of AnnotationAssertion anns prop subj value -> let iri = case subj of AnnSubIri i -> i AnnSubAnInd i -> i in xmlAssertion iri [Annotation anns prop value] SubAnnotationPropertyOf anns sub sup -> make1 True subAnnotationPropertyOfK annotationPropertyK mwNameIRI sub [(xmlAnnotations anns, mwNameIRI annotationPropertyK sup)] AnnotationPropertyDomain anns prop iri -> make1 True annotationPropertyDomainK annotationPropertyK mwNameIRI prop [(xmlAnnotations anns, mwSimpleIRI iri)] AnnotationPropertyRange anns prop iri -> make1 True annotationPropertyRangeK annotationPropertyK mwNameIRI prop [(xmlAnnotations anns, mwSimpleIRI iri)] Rule rule -> case rule of DLSafeRule anns bd hd -> [makeElement dlSafeRuleK $ xmlAnnotations anns ++ [makeElement "Body" $ map xmlAtom bd , makeElement "Head" $ map xmlAtom hd]] DGRule _ _ _ -> error "DG Rules are not supported in XML yet" DGAxiom _ _ _ _ _ -> error "DG Axioms are not supported in XML yet" xmlAtom :: Atom -> Element xmlAtom atom = case atom of ClassAtom ce ia -> makeElement classAtomK [xmlClassExpression ce, xmlIndividualArg ia] DataRangeAtom dr da -> makeElement dataRangeAtomK [xmlDataRange dr, xmlDataArg da] ObjectPropertyAtom oe ia1 ia2 -> makeElement objectPropertyAtomK [xmlObjProp oe, xmlIndividualArg ia1, xmlIndividualArg ia2] DataPropertyAtom dp ia da -> makeElement dataPropertyAtomK [mwNameIRI dataPropertyK dp, xmlIndividualArg ia, xmlDataArg da] BuiltInAtom iri das -> setIRI iri $ makeElement builtInAtomK $ map xmlDataArg das SameIndividualAtom ia1 ia2 -> makeElement sameIndividualAtomK . map xmlIndividualArg $ [ia1, ia2] DifferentIndividualsAtom ia1 ia2 -> makeElement differentIndividualsAtomK . map xmlIndividualArg $ [ia1, ia2] _ -> error "XML Converter: Uknown atom" xmlIndividualArg :: IndividualArg -> Element xmlIndividualArg ia = case ia of IArg i -> mwNameIRI namedIndividualK i IVar i -> mwNameIRI variableK i xmlDataArg :: DataArg -> Element xmlDataArg da = case da of DArg lit -> xmlLiteral lit DVar iri -> mwNameIRI variableK iri xmlUnknownArg :: UnknownArg -> Element xmlUnknownArg ua = case ua of IndividualArg ia -> xmlIndividualArg ia DataArg da -> xmlDataArg da Variable v -> mwNameIRI variableK v mkElemeDecl :: Sign -> String -> (Sign -> Set.Set IRI) -> [Element] mkElemeDecl s k f = map (makeElementWith1 declarationK . mwNameIRI k) $ Set.toList $ f s -- | converts the signature to declarations signToDec :: Sign -> [Element] signToDec s = concatMap (uncurry $ mkElemeDecl s) [ (classK, concepts) , (objectPropertyK, objectProperties) , (dataPropertyK, dataProperties) , (annotationPropertyK, annotationRoles) , (datatypeK, datatypes) , (namedIndividualK, individuals)] xmlImport :: ImportIRI -> Element xmlImport i = setName importK $ mwText $ showIRI i setPref :: String -> Element -> Element setPref s e = e {elAttribs = Attr {attrKey = makeQN "name" , attrVal = s} : elAttribs e} set1Map :: (String, IRI) -> Element set1Map (s, iri) = setPref s $ mwIRI iri xmlPrefixes :: GA.PrefixMap -> [Element] xmlPrefixes pm = let allpm = Map.union pm $ predefPrefixesGA in map (setName prefixK . set1Map) $ Map.toList allpm setOntIRI :: Maybe OntologyIRI -> Element -> Element setOntIRI mIri e = case mIri of Nothing -> e Just iri -> e { elAttribs = Attr { attrKey = makeQN "ontologyIRI" , attrVal = showIRI iri } : elAttribs e } setOntVersionIRI :: Maybe OntologyIRI -> Element -> Element setOntVersionIRI mIri e = case mIri of Nothing -> e Just iri -> e { elAttribs = Attr { attrKey = makeQN "versionIRI" , attrVal = showIRI iri } : elAttribs e } setBase :: String -> Element -> Element setBase s e = e {elAttribs = Attr {attrKey = nullQN {qName = "base", qPrefix = Just "xml"}, attrVal = s} : elAttribs e} setXMLNS :: Element -> Element setXMLNS e = e {elAttribs = Attr {attrKey = makeQN "xmlns", attrVal = "http://www.w3.org/2002/07/owl#"} : elAttribs e} xmlOntologyDoc :: Sign -> OntologyDocument -> Element xmlOntologyDoc s od = let ont = ontology od pd = prefixDeclaration od emptyPref = showIRI $ fromMaybe dummyIRI $ Map.lookup "" pd in setBase emptyPref $ setXMLNS $ setOntIRI (mOntologyIRI ont) $ setOntVersionIRI (mOntologyVersion ont) $ makeElement "Ontology" $ xmlPrefixes pd ++ map xmlImport (importsDocuments ont) ++ concatMap xmlAxioms (axioms ont) -- change xmlFrames ++ concatMap xmlAnnotations [(ontologyAnnotation ont)] ++ signToDec s -- TODO: commented out in 1993 mkODoc :: Sign -> [Named Axiom] -> String mkODoc s = ppTopElement . xmlOntologyDoc s . OntologyDocument (OntologyMetadata AS) (changePrefixMapTypeToGA $ prefixMap s) . Ontology Nothing Nothing [] [] . map sentence
spechub/Hets
OWL2/XMLConversion.hs
gpl-2.0
21,152
0
19
5,670
5,680
2,842
2,838
417
42
{-# LANGUAGE PackageImports #-} import "canx-server" Application (develMain) import Prelude (IO) main :: IO () main = develMain
uros-stegic/canx
server/canx-server/app/devel.hs
gpl-3.0
129
0
6
19
34
20
14
5
1
-- Exercício 08: Encontre o número x entre 1 e 1.000.000 que tem a maior sequência de Collatz. (Project Euler 14) collatz :: Int -> Int collatz x |x `mod` 2 == 0 = x `div` 2 |otherwise = (3 * x)+1 collatzSeq:: Int -> [Int] collatzSeq 1 = [1] collatzSeq x = x:(collatzSeq next) where next = collatz x collatzLen:: Int -> Int collatzLen x = length (collatzSeq x) projectEuler14 :: Int projectEuler14 = maximum [collatzLen x | x <- [1..1000000]] main = do print(projectEuler14)
danielgoncalvesti/BIGDATA2017
Atividade01/Haskell/Activity1/Exercises3/Ex8.hs
gpl-3.0
527
0
9
135
184
96
88
14
1
module Main where import qualified Algebra.Ring as Ring (C) import qualified Haskore.Interface.Braille as Braille import qualified Haskore.Interface.Braille.TextTables as TextTables (Locale(..), braillify, sixDots) import qualified Haskore.Interface.Signal.InstrumentMap as InstrumentMap import qualified Haskore.Interface.Signal.Write as MusicSignal import qualified Haskore.Melody.Standard as StdMelody import qualified Haskore.Music as Music import qualified Haskore.Music.Rhythmic as RhythmicMusic import qualified Haskore.Performance.Context as Context import qualified Haskore.Performance.Fancy as FancyPerformance (map) import qualified Synthesizer.Plain.Filter.Recursive.Comb as Comb (run) import Synthesizer.Plain.Instrument (bell, moogGuitar) import qualified Synthesizer.Plain.Play as Play import qualified Synthesizer.Plain.Signal as Signal import System.Exit (ExitCode(..), exitFailure) import System.Environment (getArgs) data Instrument = Bell | MoogGuitar deriving (Eq, Ord) type Music = RhythmicMusic.T () Instrument context :: Context.T MusicSignal.NonNegTime MusicSignal.Volume (RhythmicMusic.Note () Instrument) context = MusicSignal.contextMetro 40 RhythmicMusic.qn instrMap :: InstrumentMap.InstrumentTable MusicSignal.Time MusicSignal.Volume Instrument instrMap = [(Bell, MusicSignal.amplify (0.2::MusicSignal.Volume) bell ) ,(MoogGuitar, MusicSignal.amplify (0.2::MusicSignal.Volume) moogGuitar ) ] defltSampleRate :: (Num a, Ring.C a) => a defltSampleRate = 11025 -- Volume type arises from Haskore songToSignalMono :: MusicSignal.Time -> Music -> Signal.T MusicSignal.Volume songToSignalMono dif song = MusicSignal.fromRhythmicMusic defltSampleRate (MusicSignal.detuneInstrs dif instrMap) FancyPerformance.map context song songToSignalStereo :: MusicSignal.Time -> Music -> Signal.T (MusicSignal.Volume,MusicSignal.Volume) songToSignalStereo det song = zip (songToSignalMono (1-det) song) (songToSignalMono (1+det) song) melodySignal :: Instrument -> StdMelody.T -> Signal.T (MusicSignal.Volume, MusicSignal.Volume) melodySignal instr mel = let (musr, musl) = unzip (songToSignalStereo 0.001 (RhythmicMusic.fromStdMelody instr mel)) in zip (Comb.run (round (0.11*defltSampleRate :: MusicSignal.Time)) (0.4::MusicSignal.Volume) musl) (Comb.run (round (0.09*defltSampleRate :: MusicSignal.Time)) (0.5::MusicSignal.Volume) musr) braillify :: TextTables.Locale -> String -> String braillify = TextTables.braillify TextTables.sixDots main :: IO ExitCode main = do [braille] <- getArgs either (\e -> print e >> exitFailure) (\mel -> Play.stereoToInt16 defltSampleRate $ melodySignal Bell $ Music.transpose (-24) $ Music.line [mel, Music.qnr, StdMelody.c 2 RhythmicMusic.qn StdMelody.na]) (Braille.toStdMelody 1 $ braillify TextTables.German braille)
mlang/haskore-braille
playbraille.hs
gpl-3.0
2,986
0
14
495
827
472
355
50
1
module Main where import Control.Exception (try) import qualified Sound.Tidal.Context as Tidal import qualified Sound.Tidal.Stream as Tidal import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Network.WebSockets as WS import Data.List import Data.Ratio import Text.JSON import Request import WebDirt import TidalHint type TidalState = (Double -> IO (),[Tidal.ParamPattern -> IO()]) main = do putStrLn "TidalCycles websocket listening on port 9162" WS.runServer "0.0.0.0" 9162 $ (\pending -> do conn <- WS.acceptRequest pending putStrLn "received new connection" WS.forkPingThread conn 30 (cps,getNow) <- Tidal.bpsUtils dss <- mapM (\_ -> Tidal.dirtStream) [0..8] loop (cps,dss) conn ) loop :: TidalState -> WS.Connection -> IO () loop s@(cps,dss) conn = do m <- try (WS.receiveData conn) case m of Right x -> do y <- processResult s (decode (T.unpack x)) case y of Just z -> WS.sendTextData conn (T.pack (encodeStrict z)) Nothing -> return () loop s conn Left WS.ConnectionClosed -> close s "unexpected loss of connection" Left (WS.CloseRequest _ _) -> close s "by request from peer" Left (WS.ParseException e) -> close s ("parse exception: " ++ e) close :: TidalState -> String -> IO () close (cps,dss) msg = do putStrLn ("connection closed: " ++ msg) hush dss hush = mapM_ ($ Tidal.silence) processResult :: TidalState -> Result Request -> IO (Maybe JSValue) processResult _ (Error e) = do putStrLn ("Error: " ++ e) return Nothing processResult state (Ok request) = do putStrLn (show request) processRequest state request processRequest :: TidalState -> Request -> IO (Maybe JSValue) processRequest _ (Info i) = return Nothing processRequest (_,dss) Hush = do hush dss return Nothing processRequest (cps,_) (Cps x) = do cps x return Nothing processRequest (_,dss) (Pattern n p) = do x <- hintParamPattern p case x of (Left error) -> do putStrLn "Error interpreting pattern" return Nothing (Right paramPattern) -> do dss!!(n-1) $ paramPattern return Nothing processRequest _ (Render patt cps cycles) = do x <- hintParamPattern patt case x of (Left error) -> do putStrLn "Error interpreting pattern" return Nothing (Right paramPattern) -> do let r = render paramPattern cps cycles putStrLn (encodeStrict r) return (Just (showJSON r))
yaxu/tidal-websocket
data/old/websocket.hs
gpl-3.0
2,567
0
19
628
953
470
483
73
5
{-# LANGUAGE OverloadedStrings #-} {-| - - This module contains the actions that are run by the CLI dispatcher. - -} module Main.Actions ( printStatus , printFields , printCategories , printProject , printProjects , printIssue , printIssues , printVersion , printVersions , printNextVersion , createNewIssue , closeIssue , newCategory , switchAccount , startTimeTracking , stopTimeTracking , pauseTimeTracking , resumeTimeTracking , abortTimeTracking , watchIssue , unwatchIssue ) where import qualified Data.ByteString.Lazy as LB (ByteString) import qualified Data.List as L import Control.Monad ((>=>), when, unless, join, void) import Control.Monad.Except (runExceptT) import Control.Monad.IO.Class (liftIO) import Data.Aeson ((.=), object, encode) import Data.ConfigFile (emptyCP, readfile, has_section) import Data.Function (on) import Data.Time.Clock (getCurrentTime, utctDay, secondsToDiffTime, DiffTime) import Data.Time.Clock.POSIX (getPOSIXTime) import Data.Maybe (fromJust, isJust, isNothing) import System.Time.Utils (renderSecs) import System.Exit (exitFailure) import System.Directory (getHomeDirectory) import Text.Printf (printf) import Web.HTTP.Redmine import Main.Utils -- Displaying Data -- -- | Print the current account, issue and time, if any. printStatus :: IO () printStatus = do mayAccount <- getAccount tracking <- appFileExists "issue" issue <- if tracking then getTrackedIssue else return 0 started <- appFileExists "start_time" paused <- appFileExists "pause_time" trackedTime <- if tracking then getTrackedTime else return 0 mapM_ putStrLn $ [ "Using account " ++ fromJust mayAccount ++ "." | isJust mayAccount ] ++ [ "Currently tracking time for Issue #" ++ show issue ++ "." | tracking && started && not paused ] ++ [ "Time tracking for Issue #" ++ show issue ++ " is currently paused." | tracking && started && paused ] ++ [ "You have tracked " ++ renderSecs (round trackedTime) ++ " on this Issue so far." | tracking ] ++ [ "Not currenlty tracking an issue or an account." | not tracking && isNothing mayAccount ] -- | Print the available Statuses, Trackers, Priorities and Time Entry -- Activities. printFields :: Redmine () printFields = do statusFork <- redmineMVar getStatuses trackersFork <- redmineMVar getTrackers priorityFork <- redmineMVar getPriorities activityFork <- redmineMVar getActivities redmineTakeMVar statusFork >>= printWithHeader "Issue Statuses" . map statusName >> nl >> redmineTakeMVar trackersFork >>= printWithHeader "Issue Trackers" . map trackerName >> nl >> redmineTakeMVar priorityFork >>= printWithHeader "Issue Priorities" . map priorityName >> nl >> redmineTakeMVar activityFork >>= printWithHeader "Time Entry Activities" . map activityName where nl = liftIO $ putStrLn "" printCategories :: ProjectIdent -> Redmine () printCategories = getProjectFromIdent >=> getCategories . projectId >=> printWithHeader "Issue Categories" . map categoryName -- | Print All Projects printProjects :: Redmine () printProjects = do width <- liftIO getWidth getProjects >>= liftIO . putStrLn . projectsTable width -- | Print A single 'Project'. printProject :: ProjectIdent -> Redmine () printProject pIdent = getProjectFromIdent pIdent >>= liftIO . putStrLn . projectDetail -- | Print Issues filtered by a command line arguments printIssues :: IssueFilter -> Redmine () printIssues f = do width <- liftIO getWidth getIssues f >>= liftIO . putStrLn . issuesTable width -- | Print a single 'Issue'. printIssue :: IssueId -> Redmine () printIssue i = getIssue i >>= liftIO . putStrLn . issueDetail -- | Print A 'Version' and it's Issues. printVersion :: VersionId -> IssueFilter -> Redmine () printVersion v f = do version <- getVersion v issues <- getVersionsIssues version f width <- liftIO getWidth liftIO $ putStrLn (versionDetail version) >> putStrLn "" >> putStrLn "Issues:" >> putStrLn (issuesTable width issues) -- | Print a table showing all 'Versions' of a 'Project'. printVersions :: ProjectIdent -> Redmine () printVersions pIdent = do versions <- getProjectFromIdent pIdent >>= getVersions . projectId let sortedVs = L.sortBy (flip compare `on` versionDueDate) versions width <- liftIO getWidth liftIO . putStrLn . versionTable width $ sortedVs -- | Print the 'Version' that is next due for a 'Project'. printNextVersion :: ProjectIdent -> IssueFilter -> Redmine () printNextVersion pIdent f = do maybeVersion <- getProjectFromIdent pIdent >>= getNextVersionDue . projectId case maybeVersion of Nothing -> redmineLeft "No valid version found." Just v -> printVersion (versionId v) f -- Issue Creation/Updates -- | Create a new Issue and print it's ID. createNewIssue :: LB.ByteString -> Redmine () createNewIssue postData = do issue <- createIssue postData liftIO . putStrLn $ "Created Issue #" ++ show (issueId issue) ++ ": " ++ issueSubject issue -- | Close an Issue, set it's Done Ratio to 100 and if it's Due Date is not -- set, set it to today. closeIssue :: IssueId -> Maybe String -> Redmine () closeIssue i ms = do liftIO . putStrLn $ "Closing Issue #" ++ show i ++ "..." issueFork <- redmineMVar $ getIssue i closedFork <- redmineMVar $ getStatusFromName "Closed" issue <- redmineTakeMVar issueFork closedStatus <- redmineTakeMVar closedFork today <- liftIO $ fmap utctDay getCurrentTime let updateDue = isNothing (issueDueDate issue) || (null . fromJust $ issueDueDate issue) updateStat = isJust closedStatus && issueStatus issue /= "Closed" updateDone = issueDoneRatio issue /= 100 doSomething = updateStat || updateDue || updateDone putData = encode $ object [ "issue" .= object (concat [ [ "status_id" .= statusId (fromJust closedStatus) | updateStat ] , [ "due_date" .= show today | updateDue ] , [ "done_ratio" .= (100 :: Integer) | updateDone ] , [ "notes" .= ("Closing Issue." :: String) | doSomething && isNothing ms ] , [ "notes" .= fromJust ms | doSomething && isJust ms ] ]) ] void $ updateIssue i putData whenPrint updateStat "Issue status changed to Closed." whenPrint updateDue "Issue due date set to today." whenPrint updateDone "Issue done ratio set to 100%." whenPrint (not doSomething) "Found nothing to do." where whenPrint b s = when b (liftIO $ putStrLn s) -- Field Creation -- | Create new Category. newCategory :: ProjectIdent -> String -> Bool -> Redmine () newCategory p n mine = do projectFork <- redmineMVar $ getProjectFromIdent p userFork <- redmineMVar getCurrentUser pID <- projectId <$> redmineTakeMVar projectFork currentUser <- redmineTakeMVar userFork let postData = encode $ object [ "issue_category" .= object ( "name" .= n : [ "assigned_to_id" .= show (userId currentUser) | mine ] ) ] _ <- createCategory pID postData liftIO . putStrLn $ "Successfully created category " ++ n ++ "." -- Account Tracking -- | Switch the current account used. switchAccount :: String -> IO () switchAccount account = do homeDir <- getHomeDirectory let configPath = homeDir ++ "/.hkredminerc" eithAcc <- runExceptT $ do cp <- join $ liftIO $ readfile emptyCP configPath return $ has_section cp account case eithAcc of Right b -> if b then writeAppFile "account" account >> putStrLn ("Successfully switched to " ++ account ++ ".") else exitError "Account not found in config file." Left _ -> exitError "Could not parse config file." where exitError msg = putStrLn msg >> exitFailure -- Issue Tracking -- | Track an Issue by writing it's ID to a File trackIssue :: IssueId -> IO () trackIssue issueID = writeAppFile "issue" $ show issueID -- | Retrieve the currently tracked Issue getTrackedIssue :: IO IssueId getTrackedIssue = read <$> readAppFile "issue" -- Time Tracking -- | Initiate time tracking for an 'Issue' by writing the current POSIX -- time to the `start_time` file. -- -- This includes changing the Status to `In Progress` setting if the -- 'Issue' has the default 'Status' and setting the 'issueStartDate' to the -- current date(if it's not set). startTimeTracking :: IssueId -> Redmine () startTimeTracking i = do alreadyTracking <- liftIO $ appFileExists "start_time" if alreadyTracking then do trackedID <- liftIO getTrackedIssue redmineLeft $ "Can't start, we're already tracking time for " ++ "Issue #" ++ show trackedID ++ "." else liftIO (trackIssue i >> writeTimeFile "start_time" >> putStrLn ("Started tracking time for Issue #" ++ show i ++ ".")) >> markAsInProgressAndSetStartDate i -- | Stop time tracking for an 'Issue' by calculating the time spent, -- prompting for input and submiting the entry. stopTimeTracking :: Maybe String -> Maybe String -> Redmine () stopTimeTracking mayActivity mayComment = do timeSpent <- liftIO getTrackedTime issueID <- liftIO getTrackedIssue issueFork <- redmineMVar $ getIssue issueID activFork <- redmineMVar getActivities issue <- redmineTakeMVar issueFork activities <- redmineTakeMVar activFork let activityNames = map activityName activities activityIds = map (show . activityId) activities validActivity = (`elem` activityNames ++ activityIds) activity <- if isJust mayActivity && validActivity (fromJust mayActivity) then return $ fromJust mayActivity else liftIO $ getUntilValidWithInfo validActivity "Enter a valid activity:" ("\nValid Time Entry Activities:":activityNames) comment <- maybe (liftIO $ putStrLn "\nEnter a short comment: " >> getLine) return mayComment confirmed <- liftIO . confirmWithInfo $ [ "\nCreate the following Time Entry?" , "Issue: \t" ++ "#" ++ show issueID ++ " - " ++ issueSubject issue , "Activity:\t" ++ activity , "Comment: \t" ++ comment , "Hours: \t" ++ printf "%.2f" (diffTimeToHours timeSpent) ] timeActivity <- fromJust <$> getActivityFromName activity if confirmed then addTimeEntry issueID timeSpent timeActivity comment >> liftIO (mapM_ removeAppFile [ "issue", "start_time", "pause_time" ]) >> liftIO (putStrLn "The time entry was successfully created.") else redmineLeft "Time entry submission cancelled." -- | Pause the Time Tracking by writing the current POSIX time to the -- `pause_time` file. pauseTimeTracking :: IO () pauseTimeTracking = do _ <- readFileOrExit "start_time" "Can't pause, not currently tracking time." paused <- appFileExists "pause_time" when paused $ putStrLn "Time tracking is already paused." >> exitFailure _ <- writeTimeFile "pause_time" putStrLn "Paused time tracking." -- | Resume paused time tracking by reading the `start_time` and -- `pause_time` files and then calculating and writing the new -- `start_time`. resumeTimeTracking :: IO () resumeTimeTracking = do startTime <- readFileOrExit "start_time" "No previous time tracking to resume." pauseTime <- readFileOrExit "pause_time" "Time tracking isn't paused." currentTime <- round <$> getPOSIXTime :: IO Integer let newStartTime = currentTime - (read pauseTime - read startTime) removeAppFile "pause_time" writeAppFile "start_time" $ show newStartTime trackedID <- getTrackedIssue putStrLn $ "Resumed tracking time for Issue #" ++ show trackedID ++ "." -- | Abort time tracking by removing the `issue`, `start_time` and -- `pause_time` files if they exist. abortTimeTracking :: IO () abortTimeTracking = mapM_ removeAppFile [ "issue", "start_time", "pause_time" ] >> putStrLn "Aborted time tracking." -- Watching -- | Watch an 'Issue' as the current 'User'. watchIssue :: IssueId -> Redmine () watchIssue i = getCurrentUser >>= addWatcher i >> (liftIO . putStrLn $ "Started watching Issue #" ++ show i ++ ".") -- | Unwatch an 'Issue' as the current 'User'. unwatchIssue :: IssueId -> Redmine () unwatchIssue i = getCurrentUser >>= removeWatcher i >> (liftIO . putStrLn $ "Stopped watching Issue #" ++ show i ++ ".") -- Utils -- | Print a Header and associated Items printWithHeader :: String -> [String] -> Redmine () printWithHeader header items = liftIO $ putStrLn (header ++ ":") >> mapM_ putStrLn items -- | Calculate the current amount of time tracked. getTrackedTime :: IO DiffTime getTrackedTime = do start_time <- read <$> readAppFile "start_time" paused <- appFileExists "pause_time" pause_time <- if paused then read <$> readAppFile "pause_time" else return 0 current_time <- round <$> getPOSIXTime let trackedSecs = if paused then pause_time - start_time else current_time - start_time return $ secondsToDiffTime trackedSecs -- | Write some text then ask for a string until a valid one is given. getUntilValidWithInfo :: (String -> Bool) -> String -> [String] -> IO String getUntilValidWithInfo p prompt info = mapM_ putStrLn info >> untilValid p (putStrLn ("\n" ++ prompt) >> getLine) -- | Write some text then ask for a confirmation. confirmWithInfo :: [String] -> IO Bool confirmWithInfo info = do mapM_ putStrLn info >> putStrLn "\nConfirm(y/n): " response <- getLine return $ response `elem` [ "y", "Y", "yes" , "Yes", "YES" ] -- | Repeat an IO action until the value inside returns True for some -- predicate. untilValid :: (a -> Bool) -> IO a -> IO a untilValid p action = do result <- action if p result then return result else untilValid p action -- | Mark an 'Issue' as "In Progress" if the current 'Status' is the -- default status and set the 'issueStartDate' to today if it is unset. markAsInProgressAndSetStartDate :: IssueId -> Redmine () markAsInProgressAndSetStartDate i = do issue <- getIssue i statusFork <- redmineMVar . fmap fromJust . getStatusFromName . issueStatus $ issue inProgressFork <- redmineMVar $ getStatusFromName "In Progress" status <- redmineTakeMVar statusFork maybeInProgress <- redmineTakeMVar inProgressFork let changeStatus = statusIsDefault status && isJust maybeInProgress setStartDate = isNothing . issueStartDate $ issue notes = if changeStatus || setStartDate then "Starting work on this issue." else "" :: String today <- liftIO $ fmap utctDay getCurrentTime let putData = encode $ object [ "issue" .= object (concat [ ["status_id" .= (statusId . fromJust $ maybeInProgress) | changeStatus] , ["start_date" .= show today | setStartDate] , ["notes" .= notes] ] ) ] unless (isJust maybeInProgress) (liftIO . putStrLn $ "Issue status is unchanged because we couldn't " ++ "find an 'In Progress' status.") when (changeStatus || setStartDate) (updateIssue i putData) when changeStatus (liftIO . putStrLn $ "Changed the Issue Status to " ++ "'In Progress'.") when setStartDate (liftIO . putStrLn $ "Set the Start Date to today.")
prikhi/hkredmine
bin/Main/Actions.hs
gpl-3.0
18,316
0
22
6,284
3,647
1,805
1,842
-1
-1
------------------------------------------------------------------ -- | -- Module : Gom.CodeGen.Constructors -- Copyright : (c) Paul Brauner 2009 -- (c) Emilie Balland 2009 -- (c) INRIA 2009 -- Licence : GPL (see COPYING) -- -- Maintainer : paul.brauner@inria.fr -- Stability : provisional -- Portability : non-portable (requires generalized newtype deriving) -------------------------------------------------------------------- module Gom.CodeGen.Constructors ( compConstructor, compAbstractVariadic ) where import Gom.Sig import Gom.Config import Gom.FileGen import Gom.SymbolTable import Gom.CodeGen.Common import Text.PrettyPrint.Leijen import Control.Monad.Reader hiding (void) import Data.List(intersperse) -- | Given a variadic constructor @VC@, generates an abstract class @VC.java@. compAbstractVariadic :: CtorId -> Gen FileHierarchy compAbstractVariadic vc = do cl <- body return $ Class (show vc) cl where ifP = flip (ifConfM parsers) (return empty) body = do co <- askSt (codomainOf vc) qto <- qualifiedSort co tsb <- compToStringBuilderVariadic vc pa <- ifP $ compParseVariadic vc pat <- ifP $ compParseVariadicTail vc return $ rClass (public <+> abstract) (pretty vc) (Just qto) [] (vcat [tsb,pa,pat]) -- | Given a variadic constructor @List(T*)@, generates -- -- > public void toStringBuilder(java.lang.StringBuilder buf) { -- > buffer.append("List("); -- > if(this instanceof mod.types.codom.ConsList) { -- > mod.types.List cur = this; -- > while(cur instanceof mod.types.codom.ConsList) { -- > mod.types.T elem = cur.getHeadList(); -- > cur = cur.getTailList(); -- > elem.toStringBuilder(buf); -- > if(cur instanceof mod.types.codom.ConsList) { -- > buf.append(","); -- > } -- > } -- > if(!(cur instanceof mod.types.codom.EmptyList)) { -- > buf.append(","); -- > cur.toStringBuilder(buf); -- > } -- > } -- > buf.append(")"); -- > } compToStringBuilderVariadic :: CtorId -> Gen Doc compToStringBuilderVariadic vc = do qcons <- qualifiedCtor cons qnil <- qualifiedCtor nil co <- askSt (codomainOf vc) dom <- askSt (fieldOf vc) qco <- pretty `fmap` qualifiedSort co qdom <- pretty `fmap` qualifiedSort dom let mid = middle qco qcons qnil qdom (isBuiltin dom) return $ rMethodDef public void toSB [jStringBuilder <+> buf] (rBody [pre,mid,post]) where bapp arg = rMethodCall buf (text "append") [arg] cons = prependCons vc nil = prependEmpty vc pre = bapp $ dquotes (pretty vc <> lparen) post = bapp $ dquotes rparen comm = bapp $ dquotes comma cur = text "__cur" elm = text "__elem" getH = text "getHead" <> pretty vc getT = text "getTail" <> pretty vc toSB = text "toStringBuilder" buf = text "__buf" jneg = (text "!" <>) . parens middle qco qc qn dom btin = rIfThen (this <+> instanceof <+> qc) $ rBody [qco <+> cur <+> equals <+> this, rWhile (cur <+> instanceof <+> qc) $ rBody [dom <+> elm <+> equals <+> rMethodCall cur getH [], cur <+> equals <+> rMethodCall cur getT [], if btin then bapp elm else rMethodCall elm toSB [buf], rIfThen (cur <+> instanceof <+> qc) (rBody [comm])], rIfThen (jneg $ cur <+> instanceof <+> qn) $ rBody [comm, rMethodCall cur toSB [buf]]] -- | Given a sort @s@, @parseRecCall arg s@ generates -- -- * @arg.parses()@ if @s@ is a builtin, -- -- * @mod.types.s.parse(arg)@ otherwise parseRecCall :: Doc -> SortId -> Gen Doc parseRecCall arg s = do qs <- qualifiedSort s return $ if isBuiltin s then rMethodCall arg (text "parse" <> pretty s) [] else rMethodCall qs (text "parse") [arg] -- | Given a constructor @C(x1:T1,...,xn:Tn)@, -- of codomain @Co@, generates -- -- > final static mod.types.Co parseArgs(mod.Parser par) { -- > par.parseLpar(); -- > mod.types.T1 x1 = mod.types.T1.parse(par); -- > par.parseComma(); -- > ... -- > par.parseComma(); -- > mod.types.Tn xn = mod.types.Tn.parse(par); -- > par.parseRpar(); -- > return mod.types.Co.C.make(x1,...,xn); -- > } compParseConstructor :: CtorId -> Gen Doc compParseConstructor c = do pr <- packagePrefix co <- askSt (codomainOf c) qco <- qualifiedSort co recs <- iterOverFields call (intersperse pcomm) c post <- postM return $ rMethodDef (final <+> static <+> public) qco (text "parseArgs") [pars pr <+> arg] (rBody (pre:recs++post)) where pars pr = pr <> dot <> text "Parser" arg = text "__par" pcomm = rMethodCall arg (text "parseComma") [] call f s = do qs <- qualifiedSort s rec <- parseRecCall arg s return $ qs <+> _u (pretty f) <+> equals <+> rec pre = rMethodCall arg (text "parseLpar") [] postM = do qc <- qualifiedCtor c fis <- map (_u . pretty . fst) `fmap` askSt (fieldsOf c) return [rMethodCall arg (text "parseRpar") [], jreturn <+> rMethodCall qc (text "make") fis] -- | Given a variadic constructor @VC(T*)@, -- of codomain @Co@, generates -- -- > static public mod.types.Co parseArgs(mod.Parser par) { -- > par.parseLpar(); -- > if (par.isRpar()) { -- > par.parseRpar(); -- > return mod.types.vc.EmptyVC.make(); -- > } else { -- > mod.types.T head = mod.types.T.parse(par) -- > mod.types.Co tail = mod.types.vc.VC.parseTail(par); -- > par.parseRpar(); -- > return mod.types.vc.ConsVC.make(head,tail); -- > } -- > } compParseVariadic :: CtorId -> Gen Doc compParseVariadic vc = do pr <- packagePrefix co <- askSt (codomainOf vc) qco <- qualifiedSort co qvc <- qualifiedCtor vc qcons <- qualifiedCtor (prependCons vc) qnil <- qualifiedCtor (prependEmpty vc) phead <- parseHead return $ rMethodDef (static <+> public) qco (text "parseArgs") [pars pr <+> arg] (vcat [text "__par.parseLpar();", rIfThenElse (text "__par.isRpar()") (rBody [text "__par.parseRpar()", makeNil qnil]) (rBody [phead, parseTail qco qvc, text "__par.parseRpar()", makeCons qcons])]) where pars pr = pr <> dot <> text "Parser" arg = text "__par" parseHead = do dom <- askSt (fieldOf vc) qdom <- qualifiedSort dom rec <- parseRecCall arg dom return $ qdom <+> text "__head" <+> equals <+> rec retMake q as = jreturn <+> rMethodCall q (text "make") as makeCons qc = retMake qc [text "__head", text "__tail"] makeNil qn = retMake qn [] parseTail qco qvc = qco <+> text "__tail" <+> equals <+> rMethodCall qvc (text "parseTail") [arg] -- | Given a variadic constructor @VC(T*)@, -- of codomain @Co@, generates -- -- > static public mod.types.Co parseTail(mod.Parser par) { -- > if (par.isComma()) { -- > par.parseComma(); -- > mod.types.T head = mod.types.T.parse(par) -- > mod.types.Co tail = mod.types.vc.VC.parseTail(par); -- > return mod.types.vc.ConsVC.make(head,tail); -- > } else { -- > return mod.types.vc.EmptyVC.make(); -- > } -- > } compParseVariadicTail :: CtorId -> Gen Doc compParseVariadicTail vc = do pr <- packagePrefix co <- askSt (codomainOf vc) qco <- qualifiedSort co qvc <- qualifiedCtor vc qcons <- qualifiedCtor (prependCons vc) qnil <- qualifiedCtor (prependEmpty vc) phead <- parseHead return $ rMethodDef (static <+> public) qco (text "parseTail") [pars pr <+> arg] (rIfThenElse (text "__par.isComma()") (rBody [text "__par.parseComma()", phead, parseTail qco qvc ,makeCons qcons]) (makeNil qnil <> semi)) where pars pr = pr <> dot <> text "Parser" arg = text "__par" parseHead = do dom <- askSt (fieldOf vc) qdom <- qualifiedSort dom rec <- parseRecCall arg dom return $ qdom <+> text "__head" <+> equals <+> rec retMake q as = jreturn <+> rMethodCall q (text "make") as makeCons qc = retMake qc [text "__head", text "__tail"] makeNil qn = retMake qn [] parseTail qco qvc = qco <+> text "__tail" <+> equals <+> rMethodCall qvc (text "parseTail") [arg] -- | Given a non-variadic constructor @C@, generates a concrete class @C.java@. compConstructor :: CtorId -> Gen FileHierarchy compConstructor c = do mem <- compMembersOfConstructor c smem <- ifSh $ compSharingMembers c ctor <- compCtorOfConstructor c mak <- compMakeOfConstructor c get <- compGettersOfConstructor c set <- compSettersOfConstructor c tos <- ifNG $ compToStringBuilder c toh <- ifConfM haskell (compToHaskellBuilder c) rempty eqs <- ifConfM sharing (compEquiv c) (compEquals c) hac <- ifConf sharing hashCodeMethod empty dup <- ifSh $ compDuplicate c ini <- ifSh $ compInit c inh <- ifSh $ compInitHash c haf <- ifSh $ compHashFun c gcc <- ifV $ compGetChildCount c gca <- ifV $ compGetChildAt c gcs <- ifV $ compGetChildren c sca <- ifV $ compSetChildAt c scs <- ifV $ compSetChildren c par <- ifP $ compParseConstructor c ran <- ifR $ compMakeRandomConstructor c dep <- ifD $ compDepthConstructor c siz <- ifSi $ compSizeConstructor c let isc = compIsX c let syn = compSymbolName c let body = vcat [mem,smem,ctor,mak,syn, get,set,tos,toh,eqs,hac, dup,ini,inh,haf,isc,gcc,gca, gcs,sca,scs,par,ran,dep,siz] cls <- wrap body return $ Class (show c) cls where rempty = return empty ifV = flip (ifConfM visit ) rempty ifSh = flip (ifConfM sharing) rempty ifP = flip (ifConfM parsers) rempty ifR = flip (ifConfM random ) rempty ifD = flip (ifConfM depth ) rempty ifSi = flip (ifConfM size ) rempty -- ifNG == if not generated ifNG a = askSt (isGenerated c) >>= maybe a (const rempty) wrap b = do gen <- askSt (isGenerated c) let rcls d = rClass public (pretty c) (Just d) [] b case gen of Nothing -> do co <- askSt (codomainOf c) qco <- qualifiedSort co return $ rcls qco Just bc -> do qbc <- qualifiedCtor bc return $ rcls qbc -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- generates @m.types.T1 x1; ...; m.types.Tn xn;@ compMembersOfConstructor :: CtorId -> Gen Doc compMembersOfConstructor c = iterOverFields rdr rBody c where rdr f s = do qs <- qualifiedSort s return $ private <+> qs <+> _u (pretty f) -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- generates: -- -- > private int hashCode; -- > private static C proto = new C(); -- > private static int nameHash = -- > shared.HashFunctions.stringHashFunction(mod.types.s.c,n); compSharingMembers :: CtorId -> Gen Doc compSharingMembers c = do qc <- qualifiedCtor c len <- length `fmap` askSt (fieldsOf c) return $ rBody [text "private static int nameHash" <+> equals <+> rMethodCall (text "shared.HashFunctions") (text "stringHashFunction") [dquotes qc, int len], text "private int hashCode", text "private static" <+> pretty c <+> text "__proto = new" <+> pretty c <> text "()"] -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- generates the constructor: -- -- > private C(m.types.T1 x1, ..., m.types.Tn xn) { -- > this.x1 = x1; -- > ... -- > this.xn = xn; -- > } compCtorOfConstructor :: CtorId -> Gen Doc compCtorOfConstructor c = ifConfM sharing ctorShr ctorNoShr where ctorShr = return $ rMethodDef private empty (pretty c) [] empty ctorNoShr = do fis <- askSt (fieldsOf c) a <- mapM rdr1 fis let b = rBody $ map rdr2 fis return $ rMethodDef private empty (pretty c) a b where rdr1 (f,s) = do qs <- qualifiedSort s return $ qs <+> _u (pretty f) rdr2 (f,_) = this <> dot <> _u (pretty f) <+> equals <+> _u (pretty f) -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- generates the make method: -- -- > public static C make(m.types.T1 x1, ..., m.types.Tn xn) { -- > proto.initHashCode(x1,..,xn); -- > return (C) factory.build(proto); -- > } -- -- or the following if @--noSharing@ has been toggled: -- -- > public static C make(m.types.T1 x1, ..., m.types.Tn xn) { -- > return new C(x1, ..., xn); -- > } compMakeOfConstructor :: CtorId -> Gen Doc compMakeOfConstructor c = ifConfM sharing cmakes cmake where -- the sharing case cmakes = do cfs <- cfields let call = rMethodCall proto inith (map (pretty.fst) cfs) let ret = jreturn <+> parens (pretty c) <+> build makeDef $ rBody [call,ret] where proto = text "__proto" inith = text "initHashCode" build = text "factory.build(__proto)" -- the no sharing case cmake = do cfs <- cfields let b = newC (map (pretty . fst) cfs) <> semi makeDef b where newC fs = jreturn <+> rConstructorCall (pretty c) fs -- takes a body bd and returns public static C make(...) { bd } makeDef bd = do cfs <- cfields a <- mapM rdr cfs return $ rMethodDef (public <+> static) (pretty c) (text "make") a bd where rdr (f,s) = do qs <- qualifiedSort s return $ qs <+> (text .show) f -- the fields of c cfields = askSt (fieldsOf c) -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- generates the methods: -- -- > public m.types.T1 getx1() { return x1; } -- > ... -- > public m.types.Tn getxn() { return xn; } compGettersOfConstructor :: CtorId -> Gen Doc compGettersOfConstructor = iterOverFields getter vcat where getter f s = do qs <- qualifiedSort s let fun = text "get" <> pretty f let b = rBody [jreturn <+> _u (pretty f)] return $ rMethodDef public qs fun [] b -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- generates the methods: -- -- > public void setx1(m.types.T1 x1) -- > { this.x1 = x1; } -- > ... -- > public void setxn(m.types.Tn xn) -- > { this.xn = xn; } compSettersOfConstructor :: CtorId -> Gen Doc compSettersOfConstructor = iterOverFields setter vcat where setter f s = do qs <- qualifiedSort s let fun = text "set" <> pretty f let a = [pretty qs <+> _u (pretty f)] let b = rBody [this <> dot <> _u (pretty f) <+> equals <+> _u (pretty f)] return $ rMethodDef public void fun a b -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- generates -- -- > public String toStringBuilder(java.lang.StringBuilder buf) { -- > buffer.append("C("); -- > x1.toStringBuilder(buf); -- > buffer.append(","); -- > ... -- > buffer.append(","); -- > xn.toStringBuilder(buf); -- > buffer.append(")"); -- > } compToStringBuilder :: CtorId -> Gen Doc compToStringBuilder c = do rcalls <- iterOverFields rcall id c return $ rMethodDef public void (text "toStringBuilder") [jStringBuilder <+> text "__buf"] (complete rcalls) where complete b = rBody $ open : intersperse apcomma b ++ [close] bapp arg = text "__buf.append" <> parens arg apcomma = bapp $ dquotes comma open = bapp $ dquotes (pretty c <> lparen) close = bapp $ dquotes rparen rcall x s = return $ if isBuiltin s then renderBuiltin s (_u $ pretty x) (text "__buf") else rMethodCall (this <> dot <> _u (pretty x)) (text "toStringBuilder") [text "__buf"] -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- generates -- -- > public String toHaskellBuilder(java.lang.StringBuilder buf) { -- > buffer.append("(C"); -- > buffer.append(" "); -- > x1.toStringBuilder(buf); -- > buffer.append(" "); -- > ... -- > buffer.append(" "); -- > xn.toStringBuilder(buf); -- > buffer.append(")"); -- > } compToHaskellBuilder :: CtorId -> Gen Doc compToHaskellBuilder c = do rcalls <- iterOverFields rcall id c return $ rMethodDef public void (text "toHaskellBuilder") [jStringBuilder <+> text "__buf"] (complete rcalls) where complete b = rBody $ open : addspaces b ++ [close] bapp arg = text "__buf.append" <> parens arg apspace = bapp $ dquotes space addspaces = foldr (\x r -> apspace:x:r) [] open = bapp $ dquotes (lparen <> pretty c) close = bapp $ dquotes rparen rcall x s = return $ if isBuiltin s then renderBuiltin s (_u $ pretty x) (text "__buf") else rMethodCall (this <> dot <> _u (pretty x)) (text "toHaskellBuilder") [text "__buf"] -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- @compEquiv C@ generates -- -- > public boolean equivalent(shared.SharedObject o) { -- > if (o instanceof C) { -- > C typed_o = (C) o; -- > return true && -- > this.x1 == o.x1 && -- > ... -- > this.xn == o.xn; -- > } else { -- > return false; -- > } -- > } compEquiv :: CtorId -> Gen Doc compEquiv = compEqAux meth comb jShared where meth = text "equivalent" comb lhs rhs = lhs <+> text "==" <+> rhs -- | Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- @compEquals C@ generates -- -- > public boolean equals(java.lang.Object o) { -- > if (o instanceof C) { -- > C typed_o = (C) o; -- > return true && -- > this.x1.equals(o.x1) && -- > ... -- > this.xn.equals(o.xn); -- > } else { -- > return false; -- > } -- > } compEquals :: CtorId -> Gen Doc compEquals = compEqAux meth comb jObject where meth = text "equals" comb lhs rhs = rMethodCall lhs meth [rhs] -- | Given a constructor @C(x1:T1,..,xn:Tn)@, generates -- -- > public shared.SharedObject duplicate() { -- > C clone = new C(); -- > clone.init(this.x1,..,this.xn,hashCode); -- > return clone; -- > } compDuplicate :: CtorId -> Gen Doc compDuplicate c = rdr `fmap` askSt (fieldsOf c) where pc = pretty c cl = text "__clone" th = (text "this." <>) . _u . pretty . fst rdr = rMethodDef public jShared (text "duplicate") [] . body body fis = rBody [pc <+> cl <+> equals <+> rConstructorCall pc [], rMethodCall cl (text "init") (map th fis ++ [text "hashCode"]), jreturn <+> cl] -- | Given a constructor @C(x1:T1,..,xn:Tn)@, generates -- -- > private void init(T1 x1, ..., Tn xn, int hashCode) { -- > this.x1 = x1; -- > ... -- > this.xn = xn; -- > this.hashCode = hashCode; -- > } compInit :: CtorId -> Gen Doc compInit c = do cfs <- askSt $ fieldsOf c tfs <- mapM rdr cfs let args = tfs ++ [text "int __hashCode"] let body = rBody $ map ass cfs ++ [lastLine] return $ rMethodDef private void (text "init") args body where rdr (f,s) = do qs <- qualifiedSort s return $ qs <+> _u (pretty f) ass (f,s) = let pf = _u (pretty f) in this <> dot <> pf <+> equals <+> if isString s then pf <> text ".intern()" else pf lastLine = text "this.hashCode = __hashCode" -- | Given a constructor @C(x1:T1,..,xn:Tn)@, generates -- -- > private void initHashCode(T1 x1, ..., Tn xn) { -- > this.x1 = x1; -- > ... -- > this.xn = xn; -- > this.hashCode = hashFunction(); -- > } compInitHash :: CtorId -> Gen Doc compInitHash c = do cfs <- askSt $ fieldsOf c args <- mapM rdr cfs let body = rBody $ map ass cfs ++ [lastLine] return $ rMethodDef private void (text "initHashCode") args body where rdr (f,s) = do qs <- qualifiedSort s return $ qs <+> _u (pretty f) ass (f,s) = let pf = _u (pretty f) in this <> dot <> pf <+> equals <+> if isString s then pf <> text ".intern()" else pf lastLine = text "this.hashCode = hashFunction()" -- | Auxiliary function for @'compHashFun'@, generates the fields-related part -- of the @hashFunction@ method. hashArgs :: [(FieldId,SortId)] -> Int -> [Doc] hashArgs fis len = zipWith (\i (f,s) -> hashArg i f s) (desc (len -1)) fis where desc n = n:desc (n-1) -- | Auxiliary function for @'hashArgs'@, generates the recursive call -- to the @hashFunction@ method for a non-builin field, ad-hoc magic -- otherwise. hashArg :: Int -> FieldId -> SortId -> Doc hashArg idx fid sid = let res d = char accum <+> text "+=" <+> parens d in if shift == 0 then res go else res $ go <+> text "<<" <+> int shift where go | isILC sid = pfid | isBoolean sid = pfid <> text "?1:0" | isFloat sid = text "(int)" <> toInt pfid <> text "^" <> parens (toInt pfid) <> text ">>>16" | isDouble sid = text "(int)" <> toLong pfid <> text "^" <> parens (toLong pfid) <> text ">>>32" | otherwise = rMethodCall pfid (text "hashCode") [] shift = (idx `mod` 4) * 8 accum = "aaaabbbbcccc" !! (idx `mod` 12) isILC s = any ($ s) [isInt,isLong,isChar] toInt x = text "java.lang.Float.floatToIntBits" <> parens x toLong x = text "java.lang.Double.doubleToLongBits" <> parens x pfid = this <> dot <> _u (pretty fid) -- | Given a constructor @C(x1:T1,..,xn:Tn)@, generates -- -- > protected int hashFunction() { -- > int a, b, c; -- > a = 0x9e3779b9; -- > b = nameHash << 8; -- > c = n; -- > hashArgs [(x1,T1),..,(xn,Tn)] n -- > a -= b; a -= c; a ^= (c >> 13); -- > b -= c; b -= a; b ^= (a << 8); -- > c -= a; c -= b; c ^= (b >> 13); -- > a -= b; a -= c; a ^= (c >> 12); -- > b -= c; b -= a; b ^= (a << 16); -- > c -= a; c -= b; c ^= (b >> 5); -- > a -= b; a -= c; a ^= (c >> 3); -- > b -= c; b -= a; b ^= (a << 10); -- > c -= a; c -= b; c ^= (b >> 15); -- > return c; -- > } compHashFun :: CtorId -> Gen Doc compHashFun c = do fis <- askSt (fieldsOf c) let len = length fis let modif = protected <+> if len == 0 then static else empty return $ rMethodDef modif jint (text "hashFunction") [] (body fis len) where body f l = rBody (prologue ++ mid f l ++ epilogue) prologue = map text ["int a, b, c", "a = 0x9e3779b9", "b = nameHash << 8"] mid f l = (text "c =" <+> int l) : hashArgs f l epilogue = map text ["a -= b; a -= c; a ^= (c >> 13)", "b -= c; b -= a; b ^= (a << 8)" , "c -= a; c -= b; c ^= (b >> 13)", "a -= b; a -= c; a ^= (c >> 12)", "b -= c; b -= a; b ^= (a << 16)", "c -= a; c -= b; c ^= (b >> 5)" , "a -= b; a -= c; a ^= (c >> 3)" , "b -= c; b -= a; b ^= (a << 10)", "c -= a; c -= b; c ^= (b >> 15)", "return c"] -- | Given a constructor @c@ of arity @n@, generates -- -- > public int getChildCount() { -- > return n; -- > } compGetChildCount :: CtorId -> Gen Doc compGetChildCount c = do ar <- length `fmap` askSt (fieldsOf c) return $ wrap ar where wrap n = rMethodDef public jint (text "getChildCount") [] (jreturn <+> int n <> semi) -- | Given a constructor @c@ of fields @x1,..,xn@ generates -- -- > public tom.library.sl.Visitable getChildAt(int n) { -- > switch(n) { -- > case 0: return this.x1; -- > ... -- > case n-1: return this.xn; -- > default: throw new IndexOutOfBoundsException(); -- > } -- > } -- -- Common.Builtins are boxed in @tom.library.sl.VisitableBuiltin@. compGetChildAt :: CtorId -> Gen Doc compGetChildAt c = do fis <- askSt (fieldsOf c) let cs = zip (map int [0..]) (map cook fis) let arg = text "n" return $ rMethodDef public jVisitable (text "getChildAt") [jint <+> arg] (body arg cs) where cook (f,s) = jreturn <+> wrap (this <> dot <> _u (pretty f)) s <> semi body n cs = rSwitch n cs (Just outOfBounds) outOfBounds = text "throw new IndexOutOfBoundsException();" wrap f s | isBuiltin s = rConstructorCall (rWrapBuiltin qs) [f] | otherwise = f where qs = qualifiedBuiltin s -- | Given a constructor @c@ of fields @x1,..,xn@ generates -- -- > public tom.library.sl.Visitable[] getChildren() { -- > return new tom.library.sl.Visitable[] { -- > this.x1, ..., this.xn -- > }; -- > } -- -- Common.Builtins are boxed in @tom.library.sl.VisitableBuiltin@. compGetChildren :: CtorId -> Gen Doc compGetChildren c = do fis <- askSt (fieldsOf c) return $ rMethodDef public jVisitableArray (text "getChildren") [] (body fis) where body fs = let cs = align . sep . punctuate comma $ map child fs in jreturn <+> new <+> jVisitableArray <+> ibraces cs <> semi child (f,s) = if isBuiltin s then rConstructorCall (rWrapBuiltin qs) [df] else df where qs = qualifiedBuiltin s df = this <> dot <> _u (pretty f) -- | Given a constructor @c@ of fields @x1,..,xn@ generates -- -- > public tom.library.sl.Visitable setChildAt(tom.library.sl.Visitable v) { -- > switch(n) { -- > case 0: return c.make((m.foo.T1) x1,this.x2,..,this.xn); -- > ... -- > case n-1: return c.make(this.x1,...,(m.foo.Tn) this.xn); -- > default: throw new IndexOutOfBoundsException(); -- > } -- > } -- -- Common.Builtins are unboxed from @tom.library.sl.VisitableBuiltin@. compSetChildAt :: CtorId -> Gen Doc compSetChildAt c = do fis <- askSt (fieldsOf c) fis' <- mapM set (parts fis) let cs = zip (map int [0..]) fis' return $ rMethodDef public jVisitable (text "setChildAt") [jint <+> text "__n", jVisitable <+> text "__v"] (body cs) where body cs = rSwitch (text "__n") cs (Just outOfBounds) outOfBounds = text "throw new IndexOutOfBoundsException();" set (xs1,(_,t),xs2) = let f (x,_) = this <> dot <> _u (pretty x) dxs1 = map f xs1 dxs2 = map f xs2 in do dx <- cast t let args = dxs1++[dx]++dxs2 let call = rMethodCall (pretty c) (text "make") args return $ jreturn <+> call <> semi parts l = go [] l where go _ [] = [] go xs [x] = [(xs,x,[])] go xs (x:ys) = (xs,x,ys) : go (xs++[x]) ys cast t = if isBuiltin t then let qbt = rWrapBuiltin (qualifiedBuiltin t) cas = parens (parens qbt <+> text "__v") in return $ rMethodCall cas (text "getBuiltin") [] else do qt <- qualifiedSort t return $ parens qt <+> text "__v" -- | Given a constructor @c@ of fields @x1,..,xn@ generates -- -- > public tom.library.sl.Visitable -- > setChildren(tom.library.sl.Visitable[] cs) { -- > if (cs.length == n-1 && -- > cs[0] instanceof T0 && -- > .. -- > cs[n] instanceof Tn) { -- > return c.make(cs[0],..,cs[n]) -- > } else { -- > throw new IndexOutOfBoundsException(); -- > } -- > } -- -- Common.Builtins are unboxed from @tom.library.sl.VisitableBuiltin@. compSetChildren :: CtorId -> Gen Doc compSetChildren c = do cs <- askSt (fieldsOf c) csn <- zipWithM cook [0..] cs let cd = cond csn let bd = body csn let ite = rIfThenElse cd bd er return $ rMethodDef public jVisitable (text "setChildren") [jVisitableArray <+> text "__cs"] ite where cond csn = let cl = checkLen (length csn) ci = map checkInstance csn in align . fillSep $ intersperse (text "&&") (cl:ci) checkLen n = text "__cs.length ==" <+> int n checkInstance (n,t,qt) = nth n <+> instanceof <+> td where td = if isBuiltin t then text "tom.library.sl.VisitableBuiltin" else pretty qt body csn = let call = rMethodCall (pretty c) (text "make") (map r csn) in jreturn <+> call <> semi where r (n,t,qt) | isBuiltin t = rMethodCall cas (text "getBuiltin") [] | otherwise = parens (pretty qt) <+> nth n where wqt = rWrapBuiltin (qualifiedBuiltin t) cas = parens (parens wqt <+> nth n) er = text "throw new IndexOutOfBoundsException();" nth n = text "__cs" <> brackets (int n) cook n (_,t) = do qt <- qualifiedSort t return (n,t,qt) -- | Given a constructor C, generates -- -- > public boolean isC() { return true; } compIsX :: CtorId -> Doc compIsX c = let fun = text "is" <> pretty c b = rBody [jreturn <+> true] in rMethodDef public jboolean fun [] b -- | @compSymbolName c@ renders -- -- > public String symbolName() { -- > return "c"; -- > } compSymbolName :: CtorId -- ^ constructor name -> Doc compSymbolName c = text "public String symbolName()" <+> ibraces (rBody [jreturn <+> dquotes (pretty c)]) -- | Auxiliary function for 'compEquals' and 'compEquiv'. -- Given a non-variadic constructor @C(x1:T1,..,xn:Tn)@, -- a method name @method@, a type name @ty@ and a combinator @comb@, -- @compEqAux method comb ty C@ generates -- -- > public boolean method(ty o) { -- > if (o instanceof C) { -- > C typed_o = (C) o; -- > return true && -- > this.x1 `comb` o.x1 && -- > ... -- > this.xn `comb` o.xn; -- > } else { -- > return false; -- > } -- > } compEqAux :: Doc -> (Doc -> Doc -> Doc) -> Doc -> CtorId -> Gen Doc compEqAux meth comb ty c = do rcalls <- iterOverFields rcall id c return $ rMethodDef (public <+> final) jboolean meth [ty <+> text "__o"] (complete rcalls) where pc = pretty c complete b = rIfThenElse cond (branch1 b) (jreturn <+> false <> semi) cond = text "__o" <+> instanceof <+> pc branch1 b = rBody [l1,l2 (true:b)] l1 = pc <+> text "__typed_o" <+> equals <+> parens pc <+> text "__o" l2 b = jreturn <+> (align . fillSep $ intersperse (text "&&") b) rcall x s = let lhs = this <> dot <> _u (pretty x) rhs = text "__typed_o." <> _u (pretty x) in return $ if isBuiltin s then lhs <+> text "==" <+> rhs else lhs `comb` rhs -- | Given a sort @s@, @randomRecCall s@ generates -- -- * @mod.modAbstractType.randoms(rand)@ if @s@ is a builtin, -- -- * @mod.types.s.makeRandom(rand,depth)@ otherwise randomRecCall :: SortId -> Gen Doc randomRecCall s = do qs <- qualifiedSort s at <- qualifiedAbstractType return $ if isBuiltin s then rMethodCall at (text "random" <> pretty s) [text "__rand"] else rMethodCall qs (text "makeRandom") [text "__rand", text "__depth"] -- | Given a constructor @C(x1:T1,...,xn:Tn)@, -- of codomain @Co@, generates -- -- > final static public -- > mod.types.Co makeRandom(java.util.Random rand, int depth) { -- > return -- > mod.types.co.C.make(mod.types.T1.makeRandom(rand,depth), -- > ..., -- > mod.types.Tn.makeRandom(rand,depth)); -- > } compMakeRandomConstructor :: CtorId -> Gen Doc compMakeRandomConstructor c = do qc <- qualifiedCtor c co <- askSt (codomainOf c) qco <- qualifiedSort co tys <- map snd `fmap` askSt (fieldsOf c) rcalls <- mapM randomRecCall tys return $ rMethodDef (final <+> static <+> public) qco (text "makeRandom") [text "java.util.Random __rand", text "int __depth"] (body qc rcalls) where body qc rc = jreturn <+> rMethodCall qc (text "make") rc <> semi -- | Given a constructor @C(x1:T1,...,xn:Tn)@, generates -- -- > final public static int depth() { -- > int max = 0; -- > int cd = 0; -- > cd = x1.depth(); -- > if (cd > max) max = cd; -- > ... -- > cd = xn.depth(); -- > if (cd > max) max = cd; -- > return max + 1; -- > } compDepthConstructor :: CtorId -> Gen Doc compDepthConstructor c = do fis <- askSt (fieldsOf c) return .wrap $ if null fis then text "return 0;" else pack fis where call (f,s) | isBuiltin s = [] | otherwise = [this <> dot <> _u (pretty f) <> text ".depth();", text "if (__cd > __max) __max = __cd;"] pack l = vcat ([pre] ++ mid ++ [post]) where pre = text "int __max = 0; int __cd = 0;" mid = concatMap call l post = text "return __max + 1;" wrap d = text "final public int depth()" <+> ibraces d -- > final public static int size() { -- > return x1.size() + ... + xn.size(); -- > } compSizeConstructor :: CtorId -> Gen Doc compSizeConstructor c = do fis <- askSt (fieldsOf c) return . pack $ if null fis then one else add (map call fis) where add = align . fillSep . intersperse (text "+") one = text "1" call (f,s) | isBuiltin s = one | otherwise = this <> dot <> _u (pretty f) <> text ".size()" pack d = text "final public int size()" <+> ibraces (jreturn <+> d <> semi)
polux/hgom
src/Gom/CodeGen/Constructors.hs
gpl-3.0
36,449
5
19
12,605
8,928
4,485
4,443
515
4
{-# LANGUAGE UnicodeSyntax, NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module JsonComments ( removeJsonComments ) where import BasePrelude import Prelude.Unicode import qualified Data.ByteString.Lazy.Char8 as BL -- Preserve line numbers removeJsonComments ∷ BL.ByteString → BL.ByteString removeJsonComments = BL.unlines ∘ map removeJsonComment ∘ BL.lines removeJsonComment ∷ BL.ByteString → BL.ByteString removeJsonComment s | isCommentLine s = "" | otherwise = s isCommentLine ∷ BL.ByteString → Bool isCommentLine = BL.isPrefixOf "//" ∘ BL.dropWhile isSpace
39aldo39/klfc
src/JsonComments.hs
gpl-3.0
615
0
8
93
132
72
60
15
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.FusionTables.Column.Patch -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the name or type of an existing column. This method supports -- patch semantics. -- -- /See:/ <https://developers.google.com/fusiontables Fusion Tables API Reference> for @fusiontables.column.patch@. module Network.Google.Resource.FusionTables.Column.Patch ( -- * REST Resource ColumnPatchResource -- * Creating a Request , columnPatch , ColumnPatch -- * Request Lenses , cpPayload , cpTableId , cpColumnId ) where import Network.Google.FusionTables.Types import Network.Google.Prelude -- | A resource alias for @fusiontables.column.patch@ method which the -- 'ColumnPatch' request conforms to. type ColumnPatchResource = "fusiontables" :> "v2" :> "tables" :> Capture "tableId" Text :> "columns" :> Capture "columnId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Column :> Patch '[JSON] Column -- | Updates the name or type of an existing column. This method supports -- patch semantics. -- -- /See:/ 'columnPatch' smart constructor. data ColumnPatch = ColumnPatch' { _cpPayload :: !Column , _cpTableId :: !Text , _cpColumnId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ColumnPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cpPayload' -- -- * 'cpTableId' -- -- * 'cpColumnId' columnPatch :: Column -- ^ 'cpPayload' -> Text -- ^ 'cpTableId' -> Text -- ^ 'cpColumnId' -> ColumnPatch columnPatch pCpPayload_ pCpTableId_ pCpColumnId_ = ColumnPatch' { _cpPayload = pCpPayload_ , _cpTableId = pCpTableId_ , _cpColumnId = pCpColumnId_ } -- | Multipart request metadata. cpPayload :: Lens' ColumnPatch Column cpPayload = lens _cpPayload (\ s a -> s{_cpPayload = a}) -- | Table for which the column is being updated. cpTableId :: Lens' ColumnPatch Text cpTableId = lens _cpTableId (\ s a -> s{_cpTableId = a}) -- | Name or identifier for the column that is being updated. cpColumnId :: Lens' ColumnPatch Text cpColumnId = lens _cpColumnId (\ s a -> s{_cpColumnId = a}) instance GoogleRequest ColumnPatch where type Rs ColumnPatch = Column type Scopes ColumnPatch = '["https://www.googleapis.com/auth/fusiontables"] requestClient ColumnPatch'{..} = go _cpTableId _cpColumnId (Just AltJSON) _cpPayload fusionTablesService where go = buildClient (Proxy :: Proxy ColumnPatchResource) mempty
rueshyna/gogol
gogol-fusiontables/gen/Network/Google/Resource/FusionTables/Column/Patch.hs
mpl-2.0
3,436
0
15
817
463
277
186
71
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} module BookIndexer.IndexerState where import CouchDB.Types.Seq (Seq) import Control.Lens ((^.), makeLensesWith, camelCaseFields) import Data.Aeson (FromJSON(parseJSON), ToJSON(toJSON), (.:), (.=), object, Value(Object)) import Data.Maybe (catMaybes) import Data.Text (Text) indexerStateId :: Text indexerStateId = "indexerState" data IndexerState = IndexerState { indexerStateRev :: Maybe Text , indexerStateLastSeq :: Seq } deriving (Show) makeLensesWith camelCaseFields ''IndexerState instance FromJSON IndexerState where parseJSON (Object v) = IndexerState <$> v .: "_rev" <*> v .: "last_seq" parseJSON _ = error "Invalid IndexerState JSON" instance ToJSON IndexerState where toJSON indexerState = let state = [ Just ("_id" .= indexerStateId) , formatRev <$> (indexerState ^. rev) , Just ("last_seq" .= (indexerState ^. lastSeq)) ] formatRev str = "_rev" .= str in object $ catMaybes state
asvyazin/my-books.purs
server/my-books/BookIndexer/IndexerState.hs
mpl-2.0
1,185
0
15
244
294
169
125
35
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE MultiWayIf #-} import Control.Applicative ((<$>)) import Control.Monad hiding (forM_) import Control.Monad.Reader (ReaderT, ask, liftIO, runReaderT) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C import Data.ByteString.Internal (c2w, w2c) import Data.Char (toLower) import Data.Foldable (forM_) import Data.List.NonEmpty hiding (init, unwords, words) import Data.Monoid (mconcat, (<>)) import Prelude hiding (init, length) import System.Console.CmdArgs hiding (args) import System.Directory import System.Environment import System.IO import System.Process import System.Random.MWC -- Command line interface. type PgAction = ReaderT Sdm IO main :: IO () main = do exists <- doesFileExist "Snowdrift.cabal" unless exists $ error "please run from the project's root directory" sdm <- getProgName >>= cmdArgs . mkSdm run "sudo" ["-K"] -- require a password the first time 'sudo' is run runReaderT handle sdm data Sdm = Sdm { db :: String , action :: String , pgUser :: String , sudoUser :: String } deriving (Typeable, Data, Show) actions, databases :: String actions = "init, clean, reset, export" databases = "dev, test, all (default)" mkSdm :: String -> Sdm mkSdm pname = Sdm { db = "all" -- operate on the dev and test databases &= help "Database to operate on" &= explicit &= name "db" &= typ "DATABASE" , action = def &= argPos 0 &= typ "ACTION" , pgUser = "postgres" &= help "Postgres superuser used to create/modify databases" &= explicit &= name "pgUser" , sudoUser = "postgres" &= help "System user used for peer authentication" &= explicit &= name "sudoUser" } &= summary "Snowdrift database manager 0.1" &= program pname &= details [ "Actions: " <> actions , "Databases: " <> databases ] handle :: PgAction () handle = do Sdm{..} <- ask case action of -- Force evaluation to check that the 'db' argument is valid. "init" -> init $! parse db "clean" -> clean $! parse db "reset" -> reset $! parse db "export" -> export $! parse db _ -> error $ "invalid action; must be one of: " <> actions parse :: String -> NonEmpty DB parse s | s == "dev" = fromList [dev] | s == "test" = fromList [test] | s == "all" = fromList [dev, test] | otherwise = error $ "invalid argument to 'db': " <> "must be one of: " <> databases type Alias = String data DB = Dev Alias DBInfo | Test Alias DBInfo newtype DBFile = DBFile String newtype DBUser = DBUser String newtype DBName = DBName String newtype DBTemp = DBTemp String data DBInfo = DBInfo { dbFile :: DBFile , dbUser :: DBUser , dbName :: DBName , dbTemp :: Maybe DBTemp } class ToString a => DBType a instance DBType DBName instance DBType DBTemp class ToString a where toString :: a -> String instance ToString DBUser where toString (DBUser u) = u instance ToString DBName where toString (DBName n) = n instance ToString DBTemp where toString (DBTemp n) = n dev, test :: DB dev = Dev "dev" DBInfo { dbFile = DBFile "devDB.sql" , dbUser = DBUser "snowdrift_development" , dbName = DBName "snowdrift_development" , dbTemp = Nothing } test = Test "test" DBInfo { dbFile = DBFile "testDB.sql" , dbUser = DBUser "snowdrift_test" , dbName = DBName "snowdrift_test" , dbTemp = Just $ DBTemp "snowdrift_test_template" } -- Shell commands. infixl 2 -|- (-|-) :: CreateProcess -> CreateProcess -> IO String x -|- y = do (_, Just ox, _, _) <- createProcess x { std_out = CreatePipe } (_, Just oy, _, _) <- createProcess y { std_in = UseHandle ox , std_out = CreatePipe } hGetContents oy run :: String -> [String] -> IO () run cmd args = void $ rawSystem cmd args sudoed :: String -> [String] -> CreateProcess sudoed sudoUser args = proc "sudo" $ ["-u", sudoUser] <> args psql :: String -> PgAction () psql cmd = do Sdm{..} <- ask liftIO $ putStr =<< proc "echo" [cmd] -|- sudoed sudoUser ["psql", "-U", pgUser] cat :: String -> CreateProcess cat file = proc "cat" [file] leave :: String -> IO () leave s = do pname <- getProgName putStr $ pname <> ": " <> s leaveLn :: String -> IO () leaveLn s = leave s >> putStr "\n" -- Database interaction. doesDBExist :: DBType a => a -> PgAction Bool doesDBExist dbType = do Sdm{..} <- ask dbs <- liftIO $ sudoed sudoUser ["psql", "-lqt", "-U", pgUser] -|- proc "cut" ["-d|", "-f1"] return $ elem (toString dbType) (words dbs) ifExists :: DBType a => a -> PgAction () -> PgAction () ifExists dbType as = do exists <- doesDBExist dbType if | exists -> as | otherwise -> liftIO $ leaveLn $ mconcat ["'" ,toString dbType ,"' does not exist; doing nothing"] dropDB, createDB :: DBType a => a -> PgAction () dropDB dbType = ifExists dbType (psql $ "DROP DATABASE " <> toString dbType <> ";") createDB dbType = psql $ "CREATE DATABASE " <> toString dbType <> ";" importDB :: DBType a => DBFile -> a -> PgAction () importDB (DBFile f) dbType = do Sdm{..} <- ask liftIO $ putStr =<< cat f -|- sudoed sudoUser ["psql", "-U", pgUser, toString dbType] exportDB :: DBType a => a -> DBFile -> PgAction () exportDB dbType (DBFile f) = do Sdm{..} <- ask liftIO $ loop sudoUser pgUser where loop sudoUser pgUser = do leave $ "overwrite '" <> f <> "'? (yes/No) " -- send the question to 'stdout' immediately hFlush stdout answer <- fmap (fmap toLower) getLine if | answer == "yes" -> do (_, Just o, _, _) <- createProcess (sudoed sudoUser ["pg_dump" ,"-U" ,pgUser ,toString dbType]) { std_out = CreatePipe } dump <- hGetContents o writeFile f dump | answer == "no" || null answer -> leaveLn "doing nothing" | otherwise -> do leaveLn "invalid argument" loop sudoUser pgUser createUser :: DBUser -> [String] -> PgAction () createUser (DBUser u) opts = psql $ mconcat ["CREATE USER " ,u ," " ,unwords opts ,";"] dropRole :: DBUser -> PgAction () dropRole (DBUser u) = psql $ "DROP ROLE " <> u <> ";" alterUser :: DBUser -> String -> PgAction () alterUser (DBUser u) password = psql $ mconcat ["ALTER USER " ,u ," WITH ENCRYPTED PASSWORD '" ,password ,"';"] template :: Bool -> DBTemp -> PgAction () template b dbTemp = ifExists dbTemp . psql $ mconcat $ ["UPDATE pg_database SET datistemplate=" ,show b ," WHERE datname='" ,toString dbTemp ,"';"] setTemplate, unsetTemplate :: DBTemp -> PgAction () setTemplate = template True unsetTemplate = template False -- Actions. config :: String config = "config/postgresql.yml" -- Do not use for important accounts. genPassword :: Int -> String -> IO String genPassword len cs = C.unpack <$> (withSystemRandom . asGenIO $ go len (return B.empty)) where go 0 acc _ = acc go n acc gen = do w <- uniformR (c2w ' ', c2w '~') gen if (w2c w ==) `any` cs then go (pred n) (B.cons w <$> acc) gen else go n acc gen init, clean, reset, export :: NonEmpty DB -> PgAction () init ((Test {}) :| []) = error "cannot initialize only test; try to init dev or all" init dbs = do exists <- liftIO $ doesFileExist config when exists $ error "already initialized; doing nothing" password <- liftIO $ genPassword 42 $ ['a'..'z'] <> ['A'..'Z'] <> ['0'..'9'] -- Setup the databases. liftIO $ run "cp" ["config/postgresql.template", config] forM_ dbs $ \db -> init' db password -- sed -i isn't supported on *BSD liftIO $ run "perl" ["-pi" ,"-e" ,"s/REPLACE WITH YOUR PASSPHRASE/" <> password <> "/" ,config] liftIO $ run "sudo" ["chmod", "400", config] where init' :: DB -> String -> PgAction () init' (Dev _ (DBInfo {..})) password = do createUser dbUser ["NOSUPERUSER", "NOCREATEDB", "NOCREATEROLE"] createDB dbName alterUser dbUser password psql $ mconcat ["GRANT ALL PRIVILEGES ON DATABASE " ,toString dbName ," TO " ,toString dbUser ,";"] importDB dbFile dbName init' (Test _ (DBInfo {..})) password = forM_ dbTemp $ \dbTemp' -> do createUser dbUser ["NOSUPERUSER", "CREATEDB", "NOCREATEROLE"] createDB dbTemp' alterUser dbUser password setTemplate dbTemp' importDB dbFile dbTemp' clean dbs | length dbs == 1 = error "cannot clean a single database; try to reset it or to clean all" | otherwise = do liftIO $ run "rm" ["-f", config] forM_ dbs clean' where dropDBAndRole db role = dropDB db >> dropRole role clean' (Dev _ (DBInfo {..})) = dropDBAndRole dbName dbUser clean' (Test _ (DBInfo {..})) = do forM_ dbTemp $ \dbTemp' -> do unsetTemplate dbTemp' dropDB dbTemp' dropDBAndRole dbName dbUser reset dbs = forM_ dbs reset' where reset' (Dev _ (DBInfo {..})) = do dropDB dbName createDB dbName importDB dbFile dbName reset' (Test _ (DBInfo {..})) = forM_ dbTemp $ \dbTemp' -> do unsetTemplate dbTemp' dropDB dbTemp' createDB dbTemp' setTemplate dbTemp' importDB dbFile dbTemp' export dbs = forM_ dbs export' where export' (Dev _ (DBInfo {..})) = exportDB dbName dbFile export' (Test _ (DBInfo {..})) = forM_ dbTemp $ \dbTemp' -> exportDB dbTemp' dbFile
akegalj/snowdrift
dev/Sdm.hs
agpl-3.0
11,168
0
19
4,010
3,225
1,638
1,587
-1
-1
import Test.HUnit import P9x.Util(expectEqual_, testList) import P9x.P80.P80 import qualified Data.Map.Strict as Map p80 = testList "P80" [ expectEqual_ (Graph [ (Edge 'b' 'c' ()), (Edge 'f' 'c' ()), (Edge 'g' 'h' ()), (Edge 'd' 'd' ()), (Edge 'f' 'b' ()), (Edge 'k' 'f' ()), (Edge 'h' 'g' ()) ]) (graphFromString "[b-c, f-c, g-h, d, f-b, k-f, h-g]"), expectEqual_ (Graph [ (Edge 'b' 'c' 1), (Edge 'f' 'c' 2), (Edge 'g' 'h' 3), (Edge 'd' 'd' 0), (Edge 'f' 'b' 4), (Edge 'k' 'f' 5), (Edge 'h' 'g' 6) ]) (graphFromStringLabel "[b-c/1, f-c/2, g-h/3, d, f-b/4, k-f/5, h-g/6]"), expectEqual_ (Digraph [ (Edge 'b' 'c' ()), (Edge 'f' 'c' ()), (Edge 'g' 'h' ()), (Edge 'd' 'd' ()), (Edge 'f' 'b' ()), (Edge 'k' 'f' ()), (Edge 'h' 'g' ()) ]) (digraphFromString "[b>c, f>c, g>h, d, f>b, k>f, h>g]"), expectEqual_ (Digraph [ (Edge 'b' 'c' 1), (Edge 'f' 'c' 2), (Edge 'g' 'h' 3), (Edge 'd' 'd' 0), (Edge 'f' 'b' 4), (Edge 'k' 'f' 5), (Edge 'h' 'g' 6) ]) (digraphFromStringLabel "[b>c/1, f>c/2, g>h/3, d, f>b/4, k>f/5, h>g/6]"), expectEqual_ ("bcfghdk", [ (Edge 'b' 'c' ()), (Edge 'f' 'c' ()), (Edge 'g' 'h' ()), (Edge 'f' 'b' ()), (Edge 'k' 'f' ()), (Edge 'h' 'g' ()) ]) (graphToTermForm $ graphFromString "[b-c, f-c, g-h, d, f-b, k-f, h-g]"), expectEqual_ [('b', "cf"), ('c',"bf"), ('f',"cbk"), ('g',"h"), ('h',"g"), ('d',""), ('k',"f")] (graphToAdjacentForm $ graphFromString "[b-c, f-c, g-h, d, f-b, k-f, h-g]"), expectEqual_ ("bcfghdk", [ (Edge 'b' 'c' ()), (Edge 'f' 'c' ()), (Edge 'g' 'h' ()), (Edge 'f' 'b' ()), (Edge 'k' 'f' ()), (Edge 'h' 'g' ()) ]) (digraphToTermForm $ digraphFromString "[b>c, f>c, g>h, d, f>b, k>f, h>g]"), expectEqual_ [('b', "cf"), ('c',"bf"), ('f',"cbk"), ('g',"h"), ('h',"g"), ('d',""), ('k',"f")] (digraphToAdjacentForm $ digraphFromString "[b>c, f>c, g>h, d, f>b, k>f, h>g]") ] p81 = testList "P81" [ expectEqual_ ["pq", "pmq"] (graphFindPaths 'p' 'q' $ graphFromStringLabel "[p-q/9, m-q/7, k, p-m/5]"), expectEqual_ ["pq", "pmq"] (digraphFindPaths 'p' 'q' $ digraphFromStringLabel "[p>q/9, m>q/7, k, p>m/5]"), expectEqual_ [] (digraphFindPaths 'p' 'k' $ digraphFromStringLabel "[p>q/9, m>q/7, k, p>m/5]") ] p82 = testList "P82" [ expectEqual_ ["fcbf", "fbcf"] (graphFindCycles 'f' $ graphFromString "[b-c, f-c, g-h, d, f-b, k-f, h-g]"), expectEqual_ ["abca"] (digraphFindCycles 'a' $ digraphFromString "[a>b, b>c, c>a, d]") ] p83 = testList "P83" [ expectEqual_ (graphFromString `map` ["[a-a]"]) (spanningTrees $ graphFromString "[a-a]"), expectEqual_ (graphFromString `map` ["[a-b]"]) (spanningTrees $ graphFromString "[a-b]"), expectEqual_ (graphFromString `map` ["[a-b, b-c, b-d]"]) (spanningTrees $ graphFromString "[a-b, b-c, b-d]"), expectEqual_ (graphFromString `map` ["[a-b, b-c]", "[a-b, a-c]", "[a-c, b-c]"]) (spanningTrees $ graphFromString "[a-b, b-c, a-c]"), expectEqual_ (graphFromString `map` []) (spanningTrees $ graphFromString "[a-b, d]"), expectEqual_ (graphFromString `map` [ "[a-b, a-d, b-c, b-e, d-f, d-g, e-h]", "[a-b, a-d, b-c, b-e, d-f, d-g, g-h]", "[a-b, a-d, b-c, b-e, d-f, e-h, f-g]", "[a-b, a-d, b-c, b-e, d-f, e-h, g-h]", "[a-b, a-d, b-c, b-e, d-f, f-g, g-h]", "[a-b, a-d, b-c, b-e, d-g, e-h, f-g]", "[a-b, a-d, b-c, b-e, d-g, f-g, g-h]", "[a-b, a-d, b-c, b-e, e-h, f-g, g-h]", "[a-b, a-d, b-c, c-e, d-f, d-g, e-h]", "[a-b, a-d, b-c, c-e, d-f, d-g, g-h]", "[a-b, a-d, b-c, c-e, d-f, e-h, f-g]", "[a-b, a-d, b-c, c-e, d-f, e-h, g-h]", "[a-b, a-d, b-c, c-e, d-f, f-g, g-h]", "[a-b, a-d, b-c, c-e, d-g, e-h, f-g]", "[a-b, a-d, b-c, c-e, d-g, f-g, g-h]", "[a-b, a-d, b-c, c-e, e-h, f-g, g-h]", "[a-b, a-d, b-c, d-e, d-f, d-g, e-h]", "[a-b, a-d, b-c, d-e, d-f, d-g, g-h]", "[a-b, a-d, b-c, d-e, d-f, e-h, f-g]", "[a-b, a-d, b-c, d-e, d-f, e-h, g-h]", "[a-b, a-d, b-c, d-e, d-f, f-g, g-h]", "[a-b, a-d, b-c, d-e, d-g, e-h, f-g]", "[a-b, a-d, b-c, d-e, d-g, f-g, g-h]", "[a-b, a-d, b-c, d-e, e-h, f-g, g-h]", "[a-b, a-d, b-c, d-f, d-g, e-h, g-h]", "[a-b, a-d, b-c, d-f, e-h, f-g, g-h]", "[a-b, a-d, b-c, d-g, e-h, f-g, g-h]", "[a-b, a-d, b-e, c-e, d-f, d-g, e-h]", "[a-b, a-d, b-e, c-e, d-f, d-g, g-h]", "[a-b, a-d, b-e, c-e, d-f, e-h, f-g]", "[a-b, a-d, b-e, c-e, d-f, e-h, g-h]", "[a-b, a-d, b-e, c-e, d-f, f-g, g-h]", "[a-b, a-d, b-e, c-e, d-g, e-h, f-g]", "[a-b, a-d, b-e, c-e, d-g, f-g, g-h]", "[a-b, a-d, b-e, c-e, e-h, f-g, g-h]", "[a-b, a-d, c-e, d-e, d-f, d-g, e-h]", "[a-b, a-d, c-e, d-e, d-f, d-g, g-h]", "[a-b, a-d, c-e, d-e, d-f, e-h, f-g]", "[a-b, a-d, c-e, d-e, d-f, e-h, g-h]", "[a-b, a-d, c-e, d-e, d-f, f-g, g-h]", "[a-b, a-d, c-e, d-e, d-g, e-h, f-g]", "[a-b, a-d, c-e, d-e, d-g, f-g, g-h]", "[a-b, a-d, c-e, d-e, e-h, f-g, g-h]", "[a-b, a-d, c-e, d-f, d-g, e-h, g-h]", "[a-b, a-d, c-e, d-f, e-h, f-g, g-h]", "[a-b, a-d, c-e, d-g, e-h, f-g, g-h]", "[a-b, b-c, b-e, d-e, d-f, d-g, e-h]", "[a-b, b-c, b-e, d-e, d-f, d-g, g-h]", "[a-b, b-c, b-e, d-e, d-f, e-h, f-g]", "[a-b, b-c, b-e, d-e, d-f, e-h, g-h]", "[a-b, b-c, b-e, d-e, d-f, f-g, g-h]", "[a-b, b-c, b-e, d-e, d-g, e-h, f-g]", "[a-b, b-c, b-e, d-e, d-g, f-g, g-h]", "[a-b, b-c, b-e, d-e, e-h, f-g, g-h]", "[a-b, b-c, b-e, d-f, d-g, e-h, g-h]", "[a-b, b-c, b-e, d-g, e-h, f-g, g-h]", "[a-b, b-c, b-e, d-f, e-h, f-g, g-h]", "[a-b, b-c, c-e, d-e, d-f, d-g, e-h]", "[a-b, b-c, c-e, d-e, d-f, d-g, g-h]", "[a-b, b-c, c-e, d-e, d-f, e-h, f-g]", "[a-b, b-c, c-e, d-e, d-f, e-h, g-h]", "[a-b, b-c, c-e, d-e, d-f, f-g, g-h]", "[a-b, b-c, c-e, d-e, d-g, e-h, f-g]", "[a-b, b-c, c-e, d-e, d-g, f-g, g-h]", "[a-b, b-c, c-e, d-e, e-h, f-g, g-h]", "[a-b, b-c, c-e, d-f, d-g, e-h, g-h]", "[a-b, b-c, c-e, d-g, e-h, f-g, g-h]", "[a-b, b-c, c-e, d-f, e-h, f-g, g-h]", "[a-b, b-e, c-e, d-e, d-f, d-g, e-h]", "[a-b, b-e, c-e, d-e, d-f, d-g, g-h]", "[a-b, b-e, c-e, d-e, d-f, e-h, f-g]", "[a-b, b-e, c-e, d-e, d-f, e-h, g-h]", "[a-b, b-e, c-e, d-e, d-f, f-g, g-h]", "[a-b, b-e, c-e, d-e, d-g, e-h, f-g]", "[a-b, b-e, c-e, d-e, d-g, f-g, g-h]", "[a-b, b-e, c-e, d-e, e-h, f-g, g-h]", "[a-b, b-e, c-e, d-f, d-g, e-h, g-h]", "[a-b, b-e, c-e, d-g, e-h, f-g, g-h]", "[a-b, b-e, c-e, d-f, e-h, f-g, g-h]", "[a-d, b-c, b-e, d-e, d-f, d-g, e-h]", "[a-d, b-c, b-e, d-e, d-f, d-g, g-h]", "[a-d, b-c, b-e, d-e, d-f, e-h, f-g]", "[a-d, b-c, b-e, d-e, d-f, e-h, g-h]", "[a-d, b-c, b-e, d-e, d-f, f-g, g-h]", "[a-d, b-c, b-e, d-e, d-g, e-h, f-g]", "[a-d, b-c, b-e, d-e, d-g, f-g, g-h]", "[a-d, b-c, b-e, d-e, e-h, f-g, g-h]", "[a-d, b-e, c-e, d-e, d-f, d-g, e-h]", "[a-d, b-e, c-e, d-e, d-f, d-g, g-h]", "[a-d, b-e, c-e, d-e, d-f, e-h, f-g]", "[a-d, b-e, c-e, d-e, d-f, e-h, g-h]", "[a-d, b-e, c-e, d-e, d-f, f-g, g-h]", "[a-d, b-e, c-e, d-e, d-g, e-h, f-g]", "[a-d, b-e, c-e, d-e, d-g, f-g, g-h]", "[a-d, b-e, c-e, d-e, e-h, f-g, g-h]", "[a-d, b-c, c-e, d-e, d-f, d-g, e-h]", "[a-d, b-c, c-e, d-e, d-f, d-g, g-h]", "[a-d, b-c, c-e, d-e, d-f, e-h, f-g]", "[a-d, b-c, c-e, d-e, d-f, e-h, g-h]", "[a-d, b-c, c-e, d-e, d-f, f-g, g-h]", "[a-d, b-c, c-e, d-e, d-g, e-h, f-g]", "[a-d, b-c, c-e, d-e, d-g, f-g, g-h]", "[a-d, b-c, c-e, d-e, e-h, f-g, g-h]", "[a-d, b-c, b-e, d-f, d-g, e-h, g-h]", "[a-d, b-e, c-e, d-f, d-g, e-h, g-h]", "[a-d, b-c, c-e, d-f, d-g, e-h, g-h]", "[a-d, b-c, b-e, d-f, e-h, f-g, g-h]", "[a-d, b-e, c-e, d-f, e-h, f-g, g-h]", "[a-d, b-c, c-e, d-f, e-h, f-g, g-h]", "[a-d, b-c, b-e, d-g, e-h, f-g, g-h]", "[a-d, b-e, c-e, d-g, e-h, f-g, g-h]", "[a-d, b-c, c-e, d-g, e-h, f-g, g-h]" ]) (spanningTrees $ graphFromString "[a-b, a-d, b-c, b-e, c-e, d-e, d-f, d-g, e-h, f-g, g-h]") ] p84 = testList "P84" [ expectEqual_ (graphFromString "[a-a]") (minimalSpanningTree $ graphFromString "[a-a]"), expectEqual_ (graphFromStringLabel "[a-b/1, b-c/2]") (minimalSpanningTree $ graphFromStringLabel "[a-b/1, b-c/2, a-c/3]"), expectEqual_ (graphFromStringLabel "[a-d/3, d-g/3, g-h/1, d-f/4, a-b/5, b-c/2, b-e/4]") (minimalSpanningTree $ graphFromStringLabel "[a-b/5, a-d/3, b-c/2, b-e/4, c-e/6, d-e/7, d-f/4, d-g/3, e-h/5, f-g/4, g-h/1]") ] p85 = testList "P85" [ expectEqual_ (Just(Map.fromList [('a','1')])) (isomorphicMapping (graphFromString "[a-a]") (graphFromString "[1-1]")), expectEqual_ True (areIsomorphic (graphFromString "[a-a]") (graphFromString "[1-1]")), expectEqual_ (Just(Map.fromList [('a','1'), ('b','2')])) (isomorphicMapping (graphFromString "[a-b]") (graphFromString "[1-2]")), expectEqual_ True (areIsomorphic (graphFromString "[a-b]") (graphFromString "[1-2]")), expectEqual_ (Just(Map.fromList [('a','1'), ('b','2'), ('b', '2'), ('c', '3'), ('d', '4')])) (isomorphicMapping (graphFromString "[a-b, b-c, c-a, c-d]") (graphFromString "[1-2, 2-3, 3-1, 3-4]")), expectEqual_ True (areIsomorphic (graphFromString "[a-b, b-c, c-a, c-d]") (graphFromString "[1-2, 2-3, 3-1, 3-4]")) ] p86 = testList "P86" [ expectEqual_ 0 (nodeDegree (graphFromString "[a-a]") 'a'), expectEqual_ 1 (nodeDegree (graphFromString "[a-b]") 'a'), expectEqual_ "a" (nodesByDegree (graphFromString "[a-a]")), expectEqual_ [('a', 1)] (colorNodes (graphFromString "[a-a]")), expectEqual_ 3 (nodeDegree (graphFromString "[a-b, b-c, c-a, a-d]") 'a'), expectEqual_ 2 (nodeDegree (graphFromString "[a-b, b-c, c-a, a-d]") 'b'), expectEqual_ 2 (nodeDegree (graphFromString "[a-b, b-c, c-a, a-d]") 'c'), expectEqual_ 1 (nodeDegree (graphFromString "[a-b, b-c, c-a, a-d]") 'd'), expectEqual_ "acbd" (nodesByDegree (graphFromString "[a-b, b-c, c-a, a-d]")), expectEqual_ [('a', 1), ('d', 2), ('c', 2), ('b', 3)] (colorNodes (graphFromString "[a-b, b-c, c-a, a-d]")) ] p87 = testList "P87" [ expectEqual_ "a" (nodesByDepthFrom 'a' (graphFromString "[a-a]")), expectEqual_ "cba" (nodesByDepthFrom 'a' (graphFromString "[a-b, b-c, a-c]")), expectEqual_ "cab" (nodesByDepthFrom 'b' (graphFromString "[a-b, b-c, a-c]")), expectEqual_ "abc" (nodesByDepthFrom 'c' (graphFromString "[a-b, b-c, a-c]")), expectEqual_ "cbad" (nodesByDepthFrom 'd' (graphFromString "[a-b, b-c, e-e, a-c, a-d]")) ] p88 = testList "P88" [ expectEqual_ [graphFromString "[a-a]"] (splitGraph $ graphFromString "[a-a]"), expectEqual_ [graphFromString "[a-b, b-c]"] (splitGraph $ graphFromString "[a-b, b-c]"), expectEqual_ [graphFromString "[a-b]", graphFromString "[c-c]"] (splitGraph $ graphFromString "[a-b, c-c]") ] p89 = testList "P89" [ expectEqual_ True (isBipartite $ graphFromString "[a-b]"), expectEqual_ True (isBipartite $ graphFromString "[a-b, b-c]"), expectEqual_ True (isBipartite $ graphFromString "[a-b, b-c, d-d]"), expectEqual_ False (isBipartite $ graphFromString "[a-b, b-c, c-a]"), expectEqual_ False (isBipartite $ graphFromString "[a-b, b-c, e-f, f-g, g-e]") ] main :: IO Counts main = runTestTT $ TestList [p80, p81, p82, p83, p84, p85, p86, p87, p88, p89]
dkandalov/katas
haskell/p99/src/p9x/p80/P80_test.hs
unlicense
12,835
0
13
3,882
2,587
1,435
1,152
254
1
-- TODO: Compiler warning about non-exhaustive patterns? -- TODO: Pretty printing! -- -- Once a monad, always a monad. import System.IO import Text.ParserCombinators.Parsec hiding (spaces) import System.Environment import Control.Monad import Control.Monad.Error import Data.Maybe import Data.IORef ----------------------------------------------------------------------------- -- PARSER ----------------------------------------------------------------------------- -- Collect our elementary parsers here. This is also a Monad, -- as evidenced by the whitespaced-set-off Char. symbol :: Parser Char symbol = oneOf "!#$%&|*+-/:<=>?@^_~" -- space and skipMany1 are Parsec monads. spaces :: Parser () spaces = skipMany1 space -- Stuff to store our Lisp values. -- Remember: Constructors and types have different namespaces. So the -- String constructor does not conflict with the String type. -- -- PrimitiveFunc is to store our interpreter-defined functions so they -- can be passed around. User-defined functions use Func, which is a -- record type. -- -- We modify the tutorial to use the type -- (String, [LispVal] -> ThrowsError LispVal) -- so we can also store the name of the function (and we populate it -- with the full entry of primitives). data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Integer | Character Char | String String | Bool Bool | PrimitiveFunc (String, [LispVal] -> ThrowsError LispVal) | Func { params :: [String], vararg :: (Maybe String), body :: [LispVal], closure :: Env } | IOPrimitiveFunc (String, [LispVal] -> IOThrowsError LispVal) | Port Handle -- Patterns can be nested, matching inside -> outside, left -> right. -- We can have multiple matches, but the first text order is used. -- Helper functions for list. This just concatenates strings representing the -- elements of the list, which are obtained by recursing on showVal unwordsList :: [LispVal] -> String unwordsList = unwords . map showVal -- Skipping ahead to the next section showVal :: LispVal -> String -- Base cases. -- TODO: Tabelize the Characters call... (names and chars lists) showVal (String contents) = show contents showVal (Atom name) = name showVal (Number contents) = show contents showVal (Character ' ') = "#\\space" showVal (Character '\n') = "#\\newline" showVal (Character contents) = "#\\" ++ [contents] showVal (Bool True) = "#t" showVal (Bool False) = "#f" -- Recursive cases. showVal (List contents) = "(" ++ unwordsList contents ++ ")" showVal (DottedList head tail) = "(" ++ unwordsList head ++ " . " ++ showVal tail ++ ")" showVal (PrimitiveFunc (name, _)) = "<primitive func " ++ name ++ ">" showVal (Func {params = args, vararg = varargs, body = body, closure = env}) = "(lambda (" ++ unwords (map show args) ++ (case varargs of Nothing -> "" Just arg -> " . " ++ arg) ++ ")" ++ showVal (List body) ++ ")" showVal (IOPrimitiveFunc (name, _)) = "<io primitive func " ++ name ++ ">" showVal (Port _) = "<io port>" -- Make LispVal an instance of class Show instance Show LispVal where show = showVal -- Parsec << is equivalent to a space in BNF, i.e. it parses the elements -- in sequence. -- -- In general, use do when you need to interleave >>= calls. Otherwise, -- you'd have to pass unwieldy lambdas. (The >>= function is reminiscent -- of CPS...) -- -- The last line constructs a LispVal, and then wraps it in a Parser monad. -- TODO: What language feature can do this more efficiently? -- unescape :: String -> Char -- unescape "\\\"" = '"' -- unescape "\\n" = '\n' -- unescape "\\t" = '\t' -- unescape "\\\\" = '\\' -- -- escapeChar :: String -> Parser Char -- escapeChar s = liftM unescape $ try $ string s -- -- nonquoteOrEscape :: Parser Char -- nonquoteOrEscape = escapeChar "\\\"" <|> escapeChar "\\n" <|> escapeChar "\\t" <|> escapeChar "\\\\" <|> noneOf "\"" -- More elegant solution: http://codereview.stackexchange.com/questions/2406/parsing-strings-with-escaped-characters-using-parsec codes = ['b', 'n', 'f', 'r', 't', '\\', '\"', '/'] replacements = ['\b', '\n', '\f', '\r', '\t', '\\', '\"', '/'] escapedChar code replacement = char code >> return replacement escaped = char '\\' >> choice (zipWith escapedChar codes replacements) parseString :: Parser LispVal parseString = do char '"' x <- many (escaped <|> noneOf "\"") char '"' return $ String x -- TODO: Check up documentation for what are valid character literals. -- It seems like standard Scheme is just space and newline. -- http://sicp.ai.mit.edu/Fall-2003/manuals/scheme-7.5.5/doc/scheme_6.html names = ["space", "newline"] chars = [' ', '\n'] namedChar name ch = string name >> return ch parseCharacter = liftM Character (string "\\#" >> charSpec) where charSpec = choice (zipWith namedChar names chars) <|> anyChar -- An atom is a letter or symbol, followed by any number of letters, digits, -- or symbols. -- -- Note that Parser >>= extracts the value of the (successful) parse. parseAtom :: Parser LispVal parseAtom = do first <- letter <|> symbol rest <- many (letter <|> digit <|> symbol) let atom = first:rest return $ case atom of "#t" -> Bool True "#f" -> Bool False _ -> Atom atom -- From Control.Monad -- -- | Promote a function to a monad. -- liftM :: (Monad m) => (a1 -> r) -> m a1 -> m r -- liftM f m1 = do { x1 <- m1; return (f x1) } -- -- The output of (many1 digit) is a Parser String, so we convert it to a -- LispVal. parseNumber :: Parser LispVal parseNumber = do prefix <- optionMaybe (char '-') str <- many1 digit let retnum = return . Number val = read $ str in if isNothing prefix then retnum val else retnum $ -val -- The following is equivalent (I did in fact test this) -- parseNumber = (many1 digit) >>= return . Number . read -- sepBy is a Parsec combinator which parses zero or more occurences of -- parseExpr, separated by spaces. (Which is fine since we can have empty list.) parseList = liftM List $ sepBy parseExpr spaces -- endBy like sepBy, but now we end on a space. parseDottedList = do head <- endBy parseExpr spaces tail <- char '.' >> spaces >> parseExpr return $ DottedList head tail -- the dot recognizer is broken... -- ... ok think about this later... (left-factor the grammar? work out by hand) -- scanToDot = do { char '.'; return ([], True); } -- <|> -- do { x <- parseExpr -- ; spaces -- ; scanret1 <- scanToDot -- ; return ((x:(fst scanret1)), snd scanret1) -- ; } -- <|> -- do { return ([], False); } -- -- parseListOrDottedList = do -- scanret <- scanToDot -- -- if (snd scanret) -- then do { tail <- spaces >> char '.' >> spaces >> parseExpr -- ; return $ DottedList (fst scanret) tail } -- else return $ List (fst scanret) -- -- sugar parseQuoted = do char '\'' x <- parseExpr return $ List [Atom "quote", x] -- string parsers (i.e. not char parsers) seem like they consume input. -- so they need to be wrapped in try. parseExpr :: Parser LispVal parseExpr = parseAtom <|> parseNumber <|> parseString <|> parseCharacter <|> parseQuoted <|> do char '(' x <- try parseList <|> parseDottedList char ')' return x -- throwError takes an Error value and lifts it into the Left constructor -- of either. -- -- parse :: Parser Char -> String -> String -> Either Err String -- the second argument "lisp" is just for errors. -- readOrThrow :: Parser a -> String -> ThrowsError a -- CAREFUL: Bug here when you forgot to replace parseExpr with parser. readOrThrow parser input = case parse parser "lisp" input of Left err -> throwError $ Parser err Right val -> return val readExpr :: String -> ThrowsError LispVal readExpr = readOrThrow parseExpr readExprList :: String -> ThrowsError [LispVal] readExprList = readOrThrow (endBy parseExpr spaces) ----------------------------------------------------------------------------- -- METACIRCULAR EVALUATOR ----------------------------------------------------------------------------- -- Primitive evaluator -- val@(String _) matches against the String constructor but binds val to the -- _whole_ LispVal, not just the string contents. -- String, Number, and Bool are evaluated literally. Lists are interpreted: -- 1. Quoted lists evaluated to the quoted value -- 2. Unquoted lists are interpreted as function calls, which are evaluated. -- Function eval is now a monadic map: -- mapM :: (a -> m b) -> [a] -> m [b] -- -- i.e. it takes a monad-returning function (in this case eval), applies it to -- a list of elements, and wraps it up in a Monad. The arguments are now -- evaluated sequentially, and the result is a Left error Either monad if any -- failed. -- -- Remember that the computation only continues if the Right constructor of -- Either is active. If ever the Left constructor is activated, it is simply -- propagated through the rest of the pipeline. So the rest of the functions -- of the form (a -> m b) don't have to worry about error handling -- if they -- are called, they must be called with the value of the Right part of Either. -- -- We do end up modifying our functions to return ThrowsError LispVal instead -- of LispVal. However, we don't deal with error handling; we just upgrade -- them to throw errors. -- the threaded env seems inelegant. Any points-free style? eval :: Env -> LispVal -> IOThrowsError LispVal -- Easy things. eval env val@(String _) = return val eval env val@(Number _) = return val eval env val@(Bool _) = return val eval env (Atom var) = getVar env var -- Basic special forms. eval env (List [Atom "quote", val]) = return val eval env (List [Atom "if", pred, conseq, alt]) = do result <- eval env pred case result of Bool True -> eval env conseq otherwise -> eval env alt eval env (List (Atom "cond" : clauses)) = evalCond Nothing env clauses eval env (List (Atom "case" : key : clauses)) = eval env key >>= evalCase Nothing env clauses eval env (List [Atom "set!", Atom var, form]) = eval env form >>= setVar env var -- Defines. -- Variable definition (successor to define word is an atom). eval env (List [Atom "define", Atom var, form]) = eval env form >>= defineVar env var -- Function definition (this could be replaced with a macro). eval env (List (Atom "define" : List (Atom var:params) : body)) = makeNormalFunc env params body >>= defineVar env var eval env (List (Atom "define" : DottedList (Atom var:params) varargs : body)) = makeVarArgs varargs env params body >>= defineVar env var eval env (List (Atom "lambda" : List params : body)) = makeNormalFunc env params body eval env (List (Atom "lambda" : DottedList params varargs : body)) = makeVarArgs varargs env params body -- varargs only, no named parameters. Syntax is (lambda varargs <body>). -- This was confusing at first. See R5RS Sec. 4.1.4. eval env (List (Atom "lambda" : varargs@(Atom _) : body)) = makeVarArgs varargs env [] body eval env (List [Atom "load", String filename]) = load filename >>= liftM last . mapM (eval env) -- THE FUNCTION EVALUATOR! -- func is now dynamic, e.g. it may be a lambda, or a name, or whatever LispVal -- that is PrimitiveFunc or Func. -- -- (Well, this non-explicit form makes your compiler harder, but it supports lambda. -- But note that env -> codegen, apply -> function dispatch, so maybe it won't be -- that bad.) eval env (List (func : args)) = do func <- eval env func argVals <- mapM (eval env) args apply func argVals eval env badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm -- There must be some way to factor evalCase and evalCond... everything is the -- same except for the general case. -- Maybe is an early return. evalCond :: (Maybe (IOThrowsError LispVal)) -> Env -> [LispVal] -> IOThrowsError LispVal evalCond (Just ret) _ _ = ret -- Only match the _last_ clause that is an else. evalCond Nothing env ((List (Atom "else" : exprs)):[]) = evalCond (Just $ evalExprs env exprs) env [] evalCond Nothing env ((List (test:exprs)):rest) = do result <- eval env test case result of Bool True -> if null exprs then evalCond (Just $ return result) env [] else evalCond (Just $ evalExprs env exprs) env [] otherwise -> evalCond Nothing env rest -- syntax note: the following are equivalent -- \x -> let (Bool y) = x in return y -- \(Bool y) -> return y eqvpUnwrapped :: LispVal -> LispVal -> IOThrowsError Bool eqvpUnwrapped a b = liftThrowsToIO $ eqvp [a, b] >>= \(Bool y) -> return y evalCase :: (Maybe (IOThrowsError LispVal)) -> Env -> [LispVal] -> LispVal -> IOThrowsError LispVal evalCase (Just ret) _ _ _ = ret -- Only match the _last_ clause that is an else. evalCase Nothing env ((List (Atom "else" : exprs)):[]) key = evalCase (Just $ evalExprs env exprs) env [] key evalCase Nothing env ((List ((List dat):exprs)):rest) key = do matches <- mapM (eqvpUnwrapped key) dat if or matches then evalCase (Just $ evalExprs env exprs) env [] key else evalCase Nothing env rest key evalExprs :: Env -> [LispVal] -> IOThrowsError LispVal evalExprs env [Atom "=>", callback] = throwError $ NotImplemented "lambda callback cond" evalExprs env (last:[]) = eval env last evalExprs env (x:xs) = do _ <- eval env x evalExprs env xs -- Helpers to construct function objects in the environment. -- Note how everything is in terms of LispVal. Even the vararg variable. That is -- just a Lisp symbol after all. makeFunc :: (Maybe String) -> Env -> [LispVal] -> [LispVal] -> IOThrowsError LispVal makeFunc varargs env params body = return $ Func (map showVal params) varargs body env makeNormalFunc = makeFunc Nothing makeVarArgs = makeFunc . Just . showVal -- lookup func primitives returns the value associated with func in the -- association list named primitives. However, its return value is a Maybe. -- The maybe function is defined as -- -- maybe :: b -> (a -> b) -> Maybe a -> b -- maybe n f Nothing = n -- maybe n f (Just x) = f x -- -- Note f is a function, applied to the Just constructor. This is a bit odd -- and asymmetric -- nothing would be lost by returning x. -- -- Nevertheless, f is useful for our purposes. We really want x args, which -- is equivalent to ($ args) x because currying: -- -- $ args = \f -> f args -- -- so ($ args) x = (\f -> f args) x = x args -- The JIT can hook in here to dispatch and call a native function. -- (Primitive functions are already compiled by Haskell, but we may as -- well include a native code library that is linked in.) -- -- Although instead of evaluating LispVal as func, we'd have to have some -- other kind of code object. apply :: LispVal -> [LispVal] -> IOThrowsError LispVal apply (PrimitiveFunc (_, func)) args = liftThrowsToIO $ func args -- Step by step: -- -- 1. e1 = bindVars $ closure $ zip params arg (IO Env) -- 2. e2 = liftIO $ e1 (IOThrowsError Env) -- e2 is now a monad containing the function's _lexical_ context -- it is -- an environment consisting of closure and the bound parameters. -- 3. e3 = bindVarArgs varags (Env -> IOThrowsError Env) -- 4. e4 = e2 >>= e3 (IOThrowsError Env) -- 5. e5 = e4 >>= evalBody (IOThrowsError LispVal) apply (Func params varargs body closure) args = if varargs == Nothing && num params /= num args -- arg length mismatch then throwError $ NumArgs (num params) args else (liftIO $ bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalBody where remainingArgs = drop (length params) args num = toInteger . length evalBody :: Env -> IOThrowsError LispVal evalBody env = liftM last $ mapM (eval env) body -- bind list of remaining args to vararg name bindVarArgs :: (Maybe String) -> Env -> IOThrowsError Env bindVarArgs arg env = case arg of Just argName -> liftIO $ bindVars env [(argName, List $ remainingArgs)] Nothing -> return env -- TO UNDERSTAND: Curried definition? (???) -- you can't curry apply (...) = func; probably because of the destructuring? apply (IOPrimitiveFunc (_, func)) args = func args ----------------------------------------------------------------------------- -- PRIMITIVE FUNCTIONS ----------------------------------------------------------------------------- -- NOTE: radix not supported. -- For now, eqv? and equal? are the same -- equality by value, strong type. -- In the future, may optimize eq? eqv? to check pointers only. -- -- In the tutorial, the only difference in equal? was the weak typing. primitives :: [(String, [LispVal] -> ThrowsError LispVal)] primitives = [("+", numericBinop (+)), ("-", numericBinop (-)), ("*", numericBinop (*)), ("/", numericBinop div), ("modulo", numericBinop mod), ("quotient", numericBinop quot), ("remainder", numericBinop rem), ("eq?", eqvp), ("eqv?", eqvp), ("equal?", eqvp), ("car", car), ("cdr", cdr), ("cons", cons), ("symbol?", unaryOp symbolp), ("string?", unaryOp stringp), ("number?", unaryOp numberp), ("bool?", unaryOp boolp), ("list?", unaryOp listp), ("pair?", unaryOp listp), ("symbol->string", unaryOp symbolToString), ("string->symbol", unaryOp stringToSymbol), ("number->string", numberToString), ("string->number", stringToNumber), ("=", transNumBoolBinop (==)), ("<", transNumBoolBinop (<)), (">", transNumBoolBinop (>)), (">=", transNumBoolBinop (>=)), ("<=", transNumBoolBinop (<=)), ("string=?", transStrBoolBinop (==)), ("string<?", transStrBoolBinop (<)), ("string>?", transStrBoolBinop (>)), ("string<=?", transStrBoolBinop (<=)), ("string>=?", transStrBoolBinop (>=)) ] ioPrimitives :: [(String, [LispVal] -> IOThrowsError LispVal)] ioPrimitives = [("apply", applyProc), ("open-input-file", makePort ReadMode), ("open-output-file", makePort WriteMode), ("close-input-port", closePort), ("close-output-port", closePort), ("read", readProc), ("write", writeProc), ("read-contents", readContents), ("read-all", readAll)] -- Apply a Haskell function to (wrapped) Lisp values. -- Note: foldl1 is basically reduce: -- -- foldl1 f (x:xs) = foldl1 f x xs -- foldl1 _ [] = error "Prelude.foldl1: empty list" -- -- This lets us apply binops to lists, i.e. (+ 1 2 3 4). -- Recall singleVal@[_] captures the pattern to the right of @ (singleton -- list) but returns the entire list in singleVal. -- Unpackers unpackNum :: LispVal -> ThrowsError Integer unpackNum (Number n) = return n unpackNum notNum = throwError $ TypeMismatch "number" notNum unpackStr :: LispVal -> ThrowsError String unpackStr (String s) = return s unpackStr notString = throwError $ TypeMismatch "string" notString unpackBool :: LispVal -> ThrowsError Bool unpackBool (Bool b) = return b unpackBool notBool = throwError $ TypeMismatch "boolean" notBool ----------------------------------------------------------------------------- -- Primitive Func Implementation numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal numericBinop op [] = throwError $ NumArgs 2 [] numericBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op unaryOp :: (LispVal -> LispVal) -> [LispVal] -> ThrowsError LispVal unaryOp f [v] = return $ f v symbolp (Atom _) = Bool True symbolp _ = Bool False numberp (Number _) = Bool True numberp _ = Bool False stringp (String _) = Bool True stringp _ = Bool False boolp (Bool _) = Bool True boolp _ = Bool False listp (List _) = Bool True listp (DottedList _ _) = Bool True listp _ = Bool False symbolToString (Atom x) = String x stringToSymbol (String x) = Atom x -- Support arbitrary number of arguments _in the args list_. Specific -- implementations may have limits. stringToNumber [String s] = let parsed = reads s in if null parsed then throwError $ TypeMismatch "number" $ String s else return $ Number $ fst $ parsed !! 0 stringToNumber ((String s):(Number r):[]) = throwError $ NotImplemented "string->number with radix" stringToNumber args@(a:b:c:xs) = throwError $ NumArgs 2 args stringToNumber bad = throwError $ TypeMismatch "(String, [Number])" $ List bad numberToString [Number n] = return $ String $ show n numberToString ((Number n):(Number r):[]) = throwError $ NotImplemented "number->string with radix" numberToString args@(a:b:c:xs) = throwError $ NumArgs 2 args numberToString bad = throwError $ TypeMismatch "(Number, [Number])" $ List bad -- Make a binary relation transitive. -- TODO: Make Monad (for early return) transBinOp :: (a -> a -> Bool) -> ([a] -> Bool) transBinOp op = g Nothing where g (Just False) _ = False g Nothing [a, b] = a `op` b g Nothing (a:b:xs) = let abval = a `op` b in if abval then abval && g Nothing (b:xs) -- still true; keep recurring else g (Just False) [] -- false; stop early. g _ _ = error "transBinOp: singleton list" -- Now wrap that into LispVals transUnpackedBinOp unpacker op args = mapM unpacker args >>= return . Bool . transBinOp op transNumBoolBinop = transUnpackedBinOp unpackNum transStrBoolBinop = transUnpackedBinOp unpackStr transBoolBoolBinop = transUnpackedBinOp unpackBool -- Helper built-in functions in terms of wrapped variables car :: [LispVal] -> ThrowsError LispVal car [List (x:xs)] = return x -- (car '(a b)) = a ; (car '(a)) = a car [DottedList (x:xs) _] = return x -- (car '(a b . c)) = a car [badArg] = throwError $ TypeMismatch "pair" badArg -- (car 'a) -> error car badArgList = throwError $ NumArgs 1 badArgList -- (car 'a 'b) -> error cdr :: [LispVal] -> ThrowsError LispVal cdr [List (x:xs)] = return $ List xs cdr [DottedList [_] x] = return x -- (cdr '(a . b)) = b (NOT a (dotted) list!) cdr [DottedList (_:xs) x] = return $ DottedList xs x -- (cdr '(a b . c)) = (b . c) cdr [badArg] = throwError $ TypeMismatch "pair" badArg -- (cdr 'a) -> error cdr badArgList = throwError $ NumArgs 1 badArgList -- (cdr 'a 'b) -> error cons :: [LispVal] -> ThrowsError LispVal cons [x1, List []] = return $ List [x1] -- (cons 'a '()) = '(a) cons [x, List xs] = return $ List (x:xs) -- (cons 'a '(b c)) = '(a b c) cons [x, DottedList xs xlast] = return $ DottedList (x:xs) xlast -- (cons 'a '(b . c)) = '(a b . c) cons [x1, x2] = return $ DottedList [x1] x2 -- second arg is not list -> make dotted list. cons badArgList = throwError $ NumArgs 2 badArgList eqvp :: [LispVal] -> ThrowsError LispVal eqvp [(Bool a1), (Bool a2)] = return $ Bool $ a1 == a2 eqvp [(Number a1), (Number a2)] = return $ Bool $ a1 == a2 eqvp [(String a1), (String a2)] = return $ Bool $ a1 == a2 eqvp [(Atom a1), (Atom a2)] = return $ Bool $ a1 == a2 eqvp [(DottedList xs x), (DottedList ys y)] = eqvp [List $ xs ++ [x], List $ ys ++ [y]] eqvp [(List a1), (List a2)] = return $ Bool $ (length a1 == length a2) && (all eqvpPair $ zip a1 a2) where eqvpPair (x1, x2) = case eqvp [x1, x2] of Right (Bool val) -> val Left err -> False eqvp [_, _] = return $ Bool False eqvp badArgList = throwError $ NumArgs 2 badArgList ----------------------------------------------------------------------------- -- IO Primitive Func Implementation applyProc :: [LispVal] -> IOThrowsError LispVal applyProc [func, List args] = apply func args -- 1. openFile ... -> IO Handle -- 2. liftIO ... -> IOThrowsError Handle -- 3. liftM Port ... -> IOThrowsError LispVal makePort :: IOMode -> [LispVal] -> IOThrowsError LispVal makePort mode [String filename] = liftM Port $ liftIO $ openFile filename mode -- According to R5RS, the return type is unspecified. We choose useful ones. -- R5RS says the following (our rational in parentheses) -- 1. No effect if file already closed. (Haskell's hClose has same semantics.) -- 2. Return type is unspecified. (We choose useful values.) closePort :: [LispVal] -> IOThrowsError LispVal closePort [Port port] = liftIO $ hClose port >> (return $ Bool True) closePort _ = return $ Bool False -- Monad comments: -- 1. hGetLine port -> IO String -- 2. liftIO ... -> IOThrowsError String -- 3. readExpr -> ThrowsError LispVal -- 4. liftThrowsToIO ... -> IOThrowsError LispVal readProc :: [LispVal] -> IOThrowsError LispVal readProc [] = readProc [Port stdin] readProc [Port port] = liftIO (hGetLine port) >>= liftThrowsToIO . readExpr -- Monad comments: -- 1. hGetLine port -> IO () -- 2. liftIO ... -> IOThrowsError () writeProc :: [LispVal] -> IOThrowsError LispVal writeProc [obj] = writeProc [obj, Port stdout] writeProc [obj, Port port] = liftIO $ hPrint port obj >> (return $ Bool True) readContents :: [LispVal] -> IOThrowsError LispVal readContents [String filename] = liftM String $ liftIO $ readFile filename -- helper function -- This _only_ loads the statements; it does not execute them. -- Implementing the (load ...) syntax requires a special form, because -- each line of the file can introduce new bindings. load :: String -> IOThrowsError [LispVal] load filename = (liftIO $ readFile filename) >>= liftThrowsToIO . readExprList -- implementation function readAll :: [LispVal] -> IOThrowsError LispVal readAll [String filename] = liftM List $ load filename ----------------------------------------------------------------------------- -- ERROR HANDLER ----------------------------------------------------------------------------- data LispError = NumArgs Integer [LispVal] | TypeMismatch String LispVal | Parser ParseError | BadSpecialForm String LispVal | NotFunction String String | UnboundVar String String | NotImplemented String | Default String preErr = (++) "ERROR: " showError :: LispError -> String showError (UnboundVar message varname) = preErr $ message ++ ": " ++ varname showError (BadSpecialForm message form) = preErr $ message ++ ": " ++ show form showError (NotFunction message func) = preErr $ message ++ ": " ++ show func showError (NumArgs expected found) = preErr $ "Expected " ++ show expected ++ " args, but found values " ++ unwordsList found showError (TypeMismatch expected found) = preErr $ "Invalid type: expected " ++ expected ++ " but found " ++ show found showError (NotImplemented feature) = preErr $ feature ++ " is not yet implemented." showError (Parser parseErr) = preErr $ "Parse error at " ++ show parseErr instance Show LispError where show = showError instance Error LispError where noMsg = Default "An error has occured" strMsg = Default -- Type signature is Either a b However, constructors can be curried just -- like functions, so ThrowsError a = Either LispError a. Right value will -- be the correct (right!) value, if it returns. type ThrowsError = Either LispError ----------------------------------------------------------------------------- -- ENVIRONMENT SUPPORT ----------------------------------------------------------------------------- -- Declare an IORef holding a map from Strings to mutable LispVal. -- Both the environment (binding of names to values) and values themselves -- are mutable in Scheme. type Env = IORef [(String, IORef LispVal)] -- a wrapped empty environment. nullEnv :: IO Env nullEnv = newIORef [] -- Make the startup environment -- flip can be used to curry the first argument instead of the second: -- flip f x y = f y x -- So (flip f x) = \lambda y -> f y x primitiveBindings :: IO Env primitiveBindings = do let wrapFunc ctor (name, func) = (name, ctor (name, func)) wrapped = map (wrapFunc PrimitiveFunc) primitives ioWrapped = map (wrapFunc IOPrimitiveFunc) ioPrimitives e <- nullEnv bindVars e $ wrapped ++ ioWrapped -- STUPID POINTS FREE STYLE! -- -- Points free style seems to be the opposite of legibility. -- (Too elegant to be easy to read.) -- -- primitiveBindings = nullEnv -- >>= (flip bindVars $ (map (wrapFunc PrimitiveFunc) primitives) ++ -- (map (wrapFunc IOPrimitiveFunc) ioPrimitives)) -- where wrapFunc ctor (name, func) = (name, ctor (name, func)) -- ErrorT adds error handling to other monads. Until now, we have essentially -- been running the ThrowsError lambda monads as a subroutine under the IO -- monad. The only interaction to IO monad has been through trapError, which -- switches to showing the error message instead of the value. -- -- We now want to interleave the monads. -- -- From the documentation -- newtype ErrorT e m a = { runErrorT :: m (Either e a) } -- -- where e is the error type, m is the inner monad, and a is an action that -- can throw an error e. (i.e. to wrap ThrowsError String), a = String. -- -- This syntax means (essentially) ErrorT e m a is isomorphic to m (Either e a). type IOThrowsError = ErrorT LispError IO -- We cannot mix actions of different types in the same do-block, so do-blocks -- of IOThrowsError must lift LispError throws. liftThrowsToIO :: ThrowsError a -> IOThrowsError a liftThrowsToIO (Left err) = throwError err liftThrowsToIO (Right val) = return val -- Environment support -- Is a given variable bound (defined) in the environment? -- You should think of env being passed to the RHS, used as the final argument -- in lookup. -- -- Maybe takes a callback, so (const True) simply signals that the maybe call -- returns True if lookup returned a value. -- -- Note: readIORef :: IORef a -> IO a -- liftIO :: IO a -> m a (m must be a MonadIO, e.g. you can't ever leave IO) -- -- In particular, m = IOThrowsError LispVal in this context. This is because -- readIORef returns IO LispVal, but in one do-block we can only have a single -- monad, i.e. IOThrowsError. -- -- TO UNDERSTAND liftIO -- what are restriction isBound :: Env -> String -> IO Bool isBound envRef var = readIORef envRef >>= return . maybe False (const True) . lookup var getVar :: Env -> String -> IOThrowsError LispVal getVar envRef var = do env <- liftIO $ readIORef envRef maybe (throwError $ UnboundVar "Getting unbound variable" var) (liftIO . readIORef) (lookup var env) setVar :: Env -> String -> LispVal -> IOThrowsError LispVal setVar envRef var val = do env <- liftIO $ readIORef envRef maybe (throwError $ UnboundVar "Getting unbound variable" var) (liftIO . (flip writeIORef val)) (lookup var env) return val -- just for convenience defineVar :: Env -> String -> LispVal -> IOThrowsError LispVal defineVar envRef var val = do alreadyDefined <- liftIO $ isBound envRef var if alreadyDefined then setVar envRef var val else liftIO $ do valRef <- newIORef val env <- readIORef envRef writeIORef envRef ((var, valRef):env) return val -- Error-free code! -- -- The whole Monad pipeline is IO Env (as it must be). -- -- newIORef :: a -> IO (IORef a) -- -- The inner function type signatures are -- -- addBinding :: (String, LispVal) -> IORef (String, IORef LispVal) -- (var , val) -- extendEnv :: [(String, LispVal)] -> IORef [(String, IORef LispVal)] -> Env -- bindings env -- -- However, recall Env = IORef [(String, IORef LispVal)] -- -- We need to do the following: -- 1. Convert (String, LispVal) bindings to (String, IORef LispVal) to make -- mutable. -- -- 2. Take the current value of env, and add the new bindings. -- -- mapM :: (a -> m b) -> [a] -> m [b] -- (mapM addBinding bindings) in -- -- in context: a = (String, LispVal), m = IORef, b = (String, IORef LispVal) -- therefore, return is IORef [(String, IORef LispVal)], i.e. Env. -- -- liftM :: (Monad m) => (a1 -> r) -> m a1 -> m r -- liftM (++ env) envRet -- -- in context: a1 -> r = [(String, IORef LispVal)] -> [(String, IORef LispVal)] -- (list concat), so return is Env. -- -- Therefore, extendEnv returns Env -- -- 3. Modify env to point to this value with the new bindings. -- -- (readIORef envRef >>= extendEnv bindings) is an IO Env. -- The final >>= applies newIORef to the naked Env. But its the newIORef -- constructor, so its IO Env once again. -- -- That wasn't so confusing. Just remember that do block = Monad pipeline, and in -- one monad pipeline, you can have only one outer monad. (But the type parameter -- of the monad can change, on >>= calls.) bindVars :: Env -> [(String, LispVal)] -> IO Env bindVars envRef bindings = readIORef envRef >>= extendEnv bindings >>= newIORef where extendEnv bindings env = liftM (++ env) (mapM addBinding bindings) addBinding (var, val) = do ref <- newIORef val return (var, ref) ----------------------------------------------------------------------------- -- REPL ----------------------------------------------------------------------------- -- To show user the prompt flushStr :: String -> IO () flushStr str = putStr str >> hFlush stdout readPrompt :: String -> IO String readPrompt prompt = flushStr prompt >> getLine -- Get rid of error. We are guaranteed only to call this when we have a -- Right branch; see runIOThrows action. -- TODO: More structured form of assertion? extractValue :: ThrowsError a -> a extractValue (Right val) = val extractValue _ = error "I should never have been called!" -- General pontification on monads -- -- Monads are just a computational pattern that obeys an algebraic -- structure, namely the >> and >>=, or threading, functions. The -- threading functions enforce a _sequential_ pipeline of what are -- essentially function compositions of the monad. The monad itself -- (the wrapper) is threaded through each function, while the wrapped -- value is only threaded through the >>= (<-) functions. -- -- The composition of >> and >>= functions (left-associative), or -- equivalently, a do block, must take the type signature m a -> m b. -- That is, no value can escape from a monad in a function that is -- composed from >> and >>=. -- -- But if we know the structure of the monad m, we _can_ write a function -- to escape a value from its monad. After all, a monad is just another -- ADT. This is seen in our extractValue function. Of course, when we -- start working with the concrete representation of a monad, we are now -- responsible for its semantics. In this case, trapError ensures that -- the Right branch is populated. But this is a bit of a hack because -- our overall computation is String -> String, which allows this in-line -- reporting. -- -- In a future version, we could just use Left for the handler and -- write out-of-line exception handling code elsewhere (e.g. write a -- different extractValue, the left case being the equivalently of a -- catch block). -- class Monad m => MonadError e m | m -> e where -- throwError :: e -> m a -- catchError :: m a -> (e -> m a) -> m a -- -- The documentation says "The strategy of combining computations -- that can throw exceptions by bypassing bound functions from the -- point an exception is thrown to the point that it is handled." -- -- Note the (e -> m a) -> m a part of the type signature. This means -- the error handler must return a monad of the same type as the outer -- computation, i.e. error signaling must be done in line. We use -- String for both results and errors, so this is fine. -- -- Actually, this is not true: because the return type is m a, the error -- handler is free just to note the error, e.g. f `catchError` Left, in -- the example. -- -- The point is not to register a mandatory exception handler, but just -- to stop the subsequent computations. Our use case is actually a bit -- of a hack. -- -- In context, e = String, a = String as well (since the overall eval -- pipeline is String -> String; we can ignore the intermediate -- LispVal) from the perspective of this function. All manipulation will -- be threaded into a big monad pipeline, and of course intermediate -- values of the monad pipeline can wrap different types. trapError :: (Show e, MonadError e m) => m String -> m String trapError action = catchError action (return . show) -- "get rid of" the ThrowsError monad. That is, regardless of which execution -- path the monad pipeline takes, return an IO String monad (so in any case -- we get something to display). -- -- runErrorT :: m (Either e a) -- -- Let's analyze: e = LispError, m = IO, a = String. So runErrorT constructs a -- IO (Either LispError String), i.e. IO (ThrowsError String). -- -- From the documentation, "runErrorT removes the ErrorT wrapper" -- think of it -- as a form of _nominal destructuring_. -- -- Let's take this step by step: -- -- action (IOThrowsError String) -- e1 = trapError action (IOThrowsError String) -- Normal path: e1 contains the string result expression. -- Exception path: e1 contains the error message. -- e2 = runErrorT e1 (IO (Either LispError String), i.e. IOThrowsError String, i.e. _deconstructed_ ErrorT String IO String, so we need runErrorT to access) -- e3 = return . extractValue ((Either LispError String) -> IO String, i.e. -- (ThrowsError String) -> IO String) -- e4 = e2 >>= e3 (IO String) -- -- EDIT: Removed dependence on string. runIOThrows :: IOThrowsError String -> IO String runIOThrows action = runErrorT (trapError action) >>= return . extractValue -- showResOrErr :: (Show e, MonadError e m) => m LispVal -> String -- -- Let's take this step by step: -- -- e0 (IOThrowsError e) -- e1 = liftM show e0 (IOThrowsError String) -- e1 = runIOThrows e1 (IO String) showResOrErr :: (Show e) => IOThrowsError e -> IO String showResOrErr = runIOThrows . liftM show -- Let's take this step by step: -- -- expr (String) -- e1 = readExpr expr (ThrowsError LispVal) -- e2 = liftThrowsToIO e1 (IOThrowsError LispVal) -- e3 = e2 >>= eval env (IOThrowsError LispVal, because eval env is LispVal -> IOThrowsError LispVal) -- e4 = showResOrErr e3 (IO String) parseExprString, evalExprString :: Env -> String -> IO String parseExprString _ = showResOrErr . liftThrowsToIO . readExpr evalExprString env expr = showResOrErr $ (liftThrowsToIO $ readExpr expr) >>= eval env evalAndPrint :: Env -> String -> IO () evalAndPrint env expr = do parsed <- parseExprString env expr evaled <- evalExprString env expr putStrLn $ "PARSE: " ++ parsed putStrLn $ "EVAL: " ++ evaled until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m () until_ pred prompt action = do result <- prompt if pred result then return () else action result >> until_ pred prompt action -- You can enter the IO monad, but you can never leave. -- Other monads, you can only leave if allowed to. stdlibFilename = "stdlib.scm" loadLib :: Env -> String -> IOThrowsError LispVal loadLib env filename = eval env (List [Atom "load", String filename]) -- Evaluate a file with given arguments. -- -- Recall: In a do block, we can use an "imperative do" form where we don't -- write _in_. It is equivalent to writing the in and indenting. -- -- Remember, a do-block is essentially CPS, there is a correspondence b/t -- sequece and next continuation. (To clarify. Basically, what you wnt to -- say is that in CPS, you have no expression outside the continuation, e.g. -- the form is (f (g (h ...))) <- a bunch of right). So we may as well -- omit the ), which amounts to the in indentation. -- -- (Wow, that was unclear. Monads hurt your brain.) runOne :: [String] -> IO () runOne args = do let argsGlob = [("args", List $ map String $ tail args)] loadExpr = (List [Atom "load", String (args !! 0)]) -- Append a variable "args" to the environment, which contains the command -- line arguments (as strings). env <- primitiveBindings >>= flip bindVars argsGlob -- Construct (but do not run) a monad representing an errorable evaluation -- of loadExpr in envrionment env. let loadLibEnv = liftM show $ loadLib env stdlibFilename evalAndShow = liftM show $ eval env loadExpr -- BEGIN ERRORABLE PART. -- Note: We should really fine-tune error handling to distinguish between -- error in the library vs. others. -- -- That's just a matter of not using trapError, but just catchError -- directly, with a richer exception hierarchy. But that's just -- engineering; you already know the monad stuff now! -- -- Load the standard library and print the result of evaluating -- loadExpr to stderr. -- -- If an error resulted, an error is printed. -- If no error resulted, the return value of the last statement of the -- program is printed. -- -- stdout only occurs on program output, accomplished via calling (write). runIOThrows (loadLibEnv >> evalAndShow) >>= hPutStrLn stderr -- TODO: Load stdlib, but get more proper exception catching first. runRepl :: IO () runRepl = primitiveBindings >>= until_ (== "quit") (readPrompt "Lisp>>> ") . evalAndPrint main :: IO () main = do args <- getArgs if null args then runRepl else runOne args
kuitang/damon
parser.hs
unlicense
43,205
0
15
10,392
8,065
4,331
3,734
457
5
{-# LANGUAGE DeriveGeneric #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Network.Haskoin.Wallet.Types ( AccountName -- JSON Types , JsonAccount(..) , JsonAddr(..) , JsonCoin(..) , JsonTx(..) -- Request Types , WalletRequest(..) , ListRequest(..) , NewAccount(..) , OfflineTxData(..) , CoinSignData(..) , CreateTx(..) , SignTx(..) , NodeAction(..) , AccountType(..) , AddressType(..) , addrTypeIndex , TxType(..) , TxConfidence(..) , AddressInfo(..) , BalanceInfo(..) -- Response Types , WalletResponse(..) , TxCompleteRes(..) , ListResult(..) , RescanRes(..) , JsonSyncBlock(..) , JsonBlock(..) , Notif(..) , BlockInfo(..) -- Helper Types , WalletException(..) , BTCNode(..) -- *Helpers , splitSelect , splitUpdate , splitDelete , splitInsertMany_ , join2 , limitOffset ) where import Control.DeepSeq (NFData (..)) import Control.Exception (Exception) import Control.Monad import Control.Monad.Trans (MonadIO) import Data.Aeson import Data.Aeson.TH import qualified Data.ByteString as BS import Data.Char (toLower) import Data.Int (Int64) import Data.List.Split (chunksOf) import Data.Maybe (maybeToList) import qualified Data.Serialize as S import Data.String (fromString) import Data.String.Conversions (cs) import Data.Text (Text) import Data.Time (UTCTime) import Data.Typeable (Typeable) import Data.Word (Word32, Word64, Word8) import qualified Database.Esqueleto as E import Database.Esqueleto.Internal.Sql (SqlSelect) import qualified Database.Persist as P import Database.Persist.Class import Database.Persist.Sql import GHC.Generics import Network.Haskoin.Block import Network.Haskoin.Crypto import Network.Haskoin.Network import Network.Haskoin.Script import Network.Haskoin.Transaction import Network.Haskoin.Util import Network.Haskoin.Wallet.Database import Network.Haskoin.Wallet.Types.BlockInfo type AccountName = Text -- TODO: Add NFData instances for all those types {- Request Types -} data TxType = TxIncoming | TxOutgoing | TxSelf deriving (Eq, Show, Read) instance NFData TxType where rnf x = x `seq` () $(deriveJSON (dropSumLabels 2 0 "") ''TxType) data TxConfidence = TxOffline | TxDead | TxPending | TxBuilding deriving (Eq, Show, Read) instance NFData TxConfidence where rnf x = x `seq` () $(deriveJSON (dropSumLabels 2 0 "") ''TxConfidence) data AddressInfo = AddressInfo { addressInfoAddress :: !Address , addressInfoValue :: !(Maybe Word64) , addressInfoIsLocal :: !Bool } deriving (Eq, Show, Read, Generic) instance S.Serialize AddressInfo $(deriveJSON (dropFieldLabel 11) ''AddressInfo) instance NFData AddressInfo where rnf AddressInfo{..} = rnf addressInfoAddress `seq` rnf addressInfoValue `seq` rnf addressInfoIsLocal data BalanceInfo = BalanceInfo { balanceInfoInBalance :: !Word64 , balanceInfoOutBalance :: !Word64 , balanceInfoCoins :: !Int , balanceInfoSpentCoins :: !Int } deriving (Eq, Show, Read) $(deriveJSON (dropFieldLabel 11) ''BalanceInfo) instance NFData BalanceInfo where rnf BalanceInfo{..} = rnf balanceInfoInBalance `seq` rnf balanceInfoOutBalance `seq` rnf balanceInfoCoins `seq` rnf balanceInfoSpentCoins data AccountType = AccountRegular | AccountMultisig { accountTypeRequiredSigs :: !Int , accountTypeTotalKeys :: !Int } deriving (Eq, Show, Read) instance NFData AccountType where rnf t = case t of AccountRegular -> () AccountMultisig m n -> rnf m `seq` rnf n instance ToJSON AccountType where toJSON accType = case accType of AccountRegular -> object [ "type" .= String "regular" ] AccountMultisig m n -> object [ "type" .= String "multisig" , "requiredsigs" .= m , "totalkeys" .= n ] instance FromJSON AccountType where parseJSON = withObject "AccountType" $ \o -> o .: "type" >>= \t -> case (t :: Text) of "regular" -> return AccountRegular "multisig" -> AccountMultisig <$> o .: "requiredsigs" <*> o .: "totalkeys" _ -> mzero data NewAccount = NewAccount { newAccountName :: !AccountName , newAccountType :: !AccountType , newAccountMnemonic :: !(Maybe Text) , newAccountPassword :: !(Maybe Text) , newAccountEntropy :: !(Maybe Word8) , newAccountMaster :: !(Maybe XPrvKey) , newAccountDeriv :: !(Maybe KeyIndex) , newAccountKeys :: ![XPubKey] , newAccountReadOnly :: !Bool } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 10) ''NewAccount) data ListRequest = ListRequest { listOffset :: !Word32 , listLimit :: !Word32 , listReverse :: !Bool } deriving (Eq, Show, Read) $(deriveJSON (dropFieldLabel 4) ''ListRequest) data CoinSignData = CoinSignData { coinSignOutPoint :: !OutPoint , coinSignScriptOutput :: !ScriptOutput , coinSignDeriv :: !SoftPath } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 8) ''CoinSignData) instance S.Serialize CoinSignData where get = do p <- S.get s <- readBS >>= \bs -> case decodeOutputBS bs of Right s -> return s _ -> error "Invalid ScriptOutput in CoinSignData" S.get >>= \dM -> case toSoft (dM :: DerivPath) of Just d -> return $ CoinSignData p s d _ -> error "Invalid derivation in CoinSignData" where readBS = S.get >>= \(VarInt l) -> S.getByteString $ fromIntegral l put (CoinSignData p s d) = do S.put p writeBS $ encodeOutputBS s S.put $ toGeneric d where writeBS bs = do S.put $ VarInt $ fromIntegral $ BS.length bs S.putByteString bs data OfflineTxData = OfflineTxData { offlineTxDataTx :: !Tx , offlineTxDataCoinData :: ![CoinSignData] } $(deriveJSON (dropFieldLabel 13) ''OfflineTxData) instance S.Serialize OfflineTxData where get = OfflineTxData <$> S.get <*> (replicateList =<< S.get) where replicateList (VarInt c) = replicateM (fromIntegral c) S.get put (OfflineTxData t ds) = do S.put t S.put $ VarInt $ fromIntegral $ length ds forM_ ds S.put data CreateTx = CreateTx { createTxRecipients :: ![(Address, Word64)] , createTxFee :: !Word64 , createTxMinConf :: !Word32 , createTxRcptFee :: !Bool , createTxSign :: !Bool , createTxSignKey :: !(Maybe XPrvKey) } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 8) ''CreateTx) data SignTx = SignTx { signTxTxHash :: !TxHash , signTxSignKey :: !(Maybe XPrvKey) } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 6) ''SignTx) data NodeAction = NodeActionRescan { nodeActionTimestamp :: !(Maybe Word32) } | NodeActionStatus deriving (Eq, Show, Read) instance ToJSON NodeAction where toJSON na = case na of NodeActionRescan tM -> object $ ("type" .= String "rescan") : (("timestamp" .=) <$> maybeToList tM) NodeActionStatus -> object [ "type" .= String "status" ] instance FromJSON NodeAction where parseJSON = withObject "NodeAction" $ \o -> do String t <- o .: "type" case t of "rescan" -> NodeActionRescan <$> o .:? "timestamp" "status" -> return NodeActionStatus _ -> mzero data AddressType = AddressInternal | AddressExternal deriving (Eq, Show, Read) $(deriveJSON (dropSumLabels 7 0 "") ''AddressType) instance NFData AddressType where rnf x = x `seq` () addrTypeIndex :: AddressType -> KeyIndex addrTypeIndex AddressExternal = 0 addrTypeIndex AddressInternal = 1 data WalletRequest = AccountReq !AccountName | AccountsReq !ListRequest | NewAccountReq !NewAccount | RenameAccountReq !AccountName !AccountName | AddPubKeysReq !AccountName ![XPubKey] | SetAccountGapReq !AccountName !Word32 | AddrsReq !AccountName !AddressType !Word32 !Bool !ListRequest | UnusedAddrsReq !AccountName !AddressType !ListRequest | AddressReq !AccountName !KeyIndex !AddressType !Word32 !Bool | PubKeyIndexReq !AccountName !PubKeyC !AddressType | SetAddrLabelReq !AccountName !KeyIndex !AddressType !Text | GenerateAddrsReq !AccountName !KeyIndex !AddressType | TxsReq !AccountName !ListRequest | PendingTxsReq !AccountName !ListRequest | DeadTxsReq !AccountName !ListRequest | AddrTxsReq !AccountName !KeyIndex !AddressType !ListRequest | CreateTxReq !AccountName !CreateTx | ImportTxReq !AccountName !Tx | SignTxReq !AccountName !SignTx | TxReq !AccountName !TxHash | DeleteTxReq !TxHash | OfflineTxReq !AccountName !TxHash | SignOfflineTxReq !AccountName !(Maybe XPrvKey) !Tx ![CoinSignData] | BalanceReq !AccountName !Word32 !Bool | NodeActionReq !NodeAction | SyncReq !AccountName !BlockHash !ListRequest | SyncHeightReq !AccountName !BlockHeight !ListRequest | BlockInfoReq ![BlockHash] | StopServerReq deriving (Show, Eq) -- TODO: Set omitEmptyContents on aeson-0.9 $(deriveJSON defaultOptions { constructorTagModifier = map toLower . init , sumEncoding = defaultTaggedObject { tagFieldName = "method" , contentsFieldName = "request" } } ''WalletRequest ) {- JSON Types -} data JsonAccount = JsonAccount { jsonAccountName :: !Text , jsonAccountType :: !AccountType , jsonAccountMaster :: !(Maybe XPrvKey) , jsonAccountMnemonic :: !(Maybe Text) , jsonAccountKeys :: ![XPubKey] , jsonAccountGap :: !Word32 , jsonAccountCreated :: !UTCTime } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 11) ''JsonAccount) data JsonAddr = JsonAddr { jsonAddrAddress :: !Address , jsonAddrIndex :: !KeyIndex , jsonAddrType :: !AddressType , jsonAddrLabel :: !Text , jsonAddrRedeem :: !(Maybe ScriptOutput) , jsonAddrKey :: !(Maybe PubKeyC) , jsonAddrCreated :: !UTCTime -- Optional Balance , jsonAddrBalance :: !(Maybe BalanceInfo) } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 8) ''JsonAddr) data JsonTx = JsonTx { jsonTxHash :: !TxHash , jsonTxNosigHash :: !TxHash , jsonTxType :: !TxType , jsonTxInValue :: !Word64 , jsonTxOutValue :: !Word64 , jsonTxValue :: !Int64 , jsonTxInputs :: ![AddressInfo] , jsonTxOutputs :: ![AddressInfo] , jsonTxChange :: ![AddressInfo] , jsonTxTx :: !Tx , jsonTxIsCoinbase :: !Bool , jsonTxConfidence :: !TxConfidence , jsonTxConfirmedBy :: !(Maybe BlockHash) , jsonTxConfirmedHeight :: !(Maybe Word32) , jsonTxConfirmedDate :: !(Maybe Word32) , jsonTxCreated :: !UTCTime , jsonTxAccount :: !AccountName -- Optional confirmation , jsonTxConfirmations :: !(Maybe Word32) , jsonTxBestBlock :: !(Maybe BlockHash) , jsonTxBestBlockHeight :: !(Maybe BlockHeight) } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 6) ''JsonTx) data JsonCoin = JsonCoin { jsonCoinHash :: !TxHash , jsonCoinPos :: !Word32 , jsonCoinValue :: !Word64 , jsonCoinScript :: !ScriptOutput , jsonCoinCreated :: !UTCTime -- Optional Tx , jsonCoinTx :: !(Maybe JsonTx) -- Optional Address , jsonCoinAddress :: !(Maybe JsonAddr) -- Optional spender , jsonCoinSpendingTx :: !(Maybe JsonTx) } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 8) ''JsonCoin) {- Response Types -} data TxCompleteRes = TxCompleteRes { txCompleteTx :: !Tx , txCompleteComplete :: !Bool } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 10) ''TxCompleteRes) data ListResult a = ListResult { listResultItems :: ![a] , listResultTotal :: !Word32 } $(deriveJSON (dropFieldLabel 10) ''ListResult) data RescanRes = RescanRes { rescanTimestamp :: !Word32 } deriving (Eq, Show, Read) $(deriveJSON (dropFieldLabel 6) ''RescanRes) data WalletResponse a = ResponseError { responseError :: !Text } | ResponseValid { responseResult :: !(Maybe a) } deriving (Eq, Show) $(deriveJSON (dropSumLabels 8 8 "status") ''WalletResponse) data JsonSyncBlock = JsonSyncBlock { jsonSyncBlockHash :: !BlockHash , jsonSyncBlockHeight :: !BlockHeight , jsonSyncBlockPrev :: !BlockHash , jsonSyncBlockTxs :: ![JsonTx] } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 13) ''JsonSyncBlock) data JsonBlock = JsonBlock { jsonBlockHash :: !BlockHash , jsonBlockHeight :: !BlockHeight , jsonBlockPrev :: !BlockHash } deriving (Eq, Show) $(deriveJSON (dropFieldLabel 9) ''JsonBlock) data Notif = NotifBlock !JsonBlock | NotifTx !JsonTx deriving (Eq, Show) $(deriveJSON (dropSumLabels 5 5 "type") ''Notif) {- Helper Types -} data WalletException = WalletException !String deriving (Eq, Read, Show, Typeable) instance Exception WalletException data BTCNode = BTCNode { btcNodeHost :: !String, btcNodePort :: !Int } deriving (Eq, Read, Show) $(deriveJSON (dropFieldLabel 7) ''BTCNode) {- Persistent Instances -} instance PersistField XPrvKey where toPersistValue = PersistText . cs . xPrvExport fromPersistValue (PersistText txt) = maybeToEither "Invalid Persistent XPrvKey" $ xPrvImport $ cs txt fromPersistValue (PersistByteString bs) = maybeToEither "Invalid Persistent XPrvKey" $ xPrvImport bs fromPersistValue _ = Left "Invalid Persistent XPrvKey" instance PersistFieldSql XPrvKey where sqlType _ = SqlString instance PersistField [XPubKey] where toPersistValue = PersistText . cs . encode fromPersistValue (PersistText txt) = maybeToEither "Invalid Persistent XPubKey" $ decodeStrict' $ cs txt fromPersistValue (PersistByteString bs) = maybeToEither "Invalid Persistent XPubKey" $ decodeStrict' bs fromPersistValue _ = Left "Invalid Persistent XPubKey" instance PersistFieldSql [XPubKey] where sqlType _ = SqlString instance PersistField DerivPath where toPersistValue = PersistText . cs . pathToStr fromPersistValue (PersistText txt) = maybeToEither "Invalid Persistent DerivPath" . fmap getParsedPath . parsePath . cs $ txt fromPersistValue (PersistByteString bs) = maybeToEither "Invalid Persistent DerivPath" . fmap getParsedPath . parsePath . cs $ bs fromPersistValue _ = Left "Invalid Persistent DerivPath" instance PersistFieldSql DerivPath where sqlType _ = SqlString instance PersistField HardPath where toPersistValue = PersistText . cs . pathToStr fromPersistValue (PersistText txt) = maybeToEither "Invalid Persistent HardPath" $ parseHard $ cs txt fromPersistValue (PersistByteString bs) = maybeToEither "Invalid Persistent HardPath" $ parseHard $ cs bs fromPersistValue _ = Left "Invalid Persistent HardPath" instance PersistFieldSql HardPath where sqlType _ = SqlString instance PersistField SoftPath where toPersistValue = PersistText . cs . pathToStr fromPersistValue (PersistText txt) = maybeToEither "Invalid Persistent SoftPath" $ parseSoft $ cs txt fromPersistValue (PersistByteString bs) = maybeToEither "Invalid Persistent SoftPath" $ parseSoft $ cs bs fromPersistValue _ = Left "Invalid Persistent SoftPath" instance PersistFieldSql SoftPath where sqlType _ = SqlString instance PersistField AccountType where toPersistValue = PersistText . cs . encode fromPersistValue (PersistText txt) = maybeToEither "Invalid Persistent AccountType" $ decodeStrict' $ cs txt fromPersistValue (PersistByteString bs) = maybeToEither "Invalid Persistent AccountType" $ decodeStrict' bs fromPersistValue _ = Left "Invalid Persistent AccountType" instance PersistFieldSql AccountType where sqlType _ = SqlString instance PersistField AddressType where toPersistValue ts = PersistBool $ case ts of AddressExternal -> True AddressInternal -> False fromPersistValue (PersistBool b) = return $ if b then AddressExternal else AddressInternal fromPersistValue (PersistInt64 i) = return $ case i of 0 -> AddressInternal _ -> AddressExternal fromPersistValue _ = Left "Invalid Persistent AddressType" instance PersistFieldSql AddressType where sqlType _ = SqlBool instance PersistField TxType where toPersistValue ts = PersistText $ case ts of TxIncoming -> "incoming" TxOutgoing -> "outgoing" TxSelf -> "self" fromPersistValue (PersistText txt) = case txt of "incoming" -> return TxIncoming "outgoing" -> return TxOutgoing "self" -> return TxSelf _ -> Left "Invalid Persistent TxType" fromPersistValue (PersistByteString bs) = case bs of "incoming" -> return TxIncoming "outgoing" -> return TxOutgoing "self" -> return TxSelf _ -> Left "Invalid Persistent TxType" fromPersistValue _ = Left "Invalid Persistent TxType" instance PersistFieldSql TxType where sqlType _ = SqlString instance PersistField Address where toPersistValue = PersistText . cs . addrToBase58 fromPersistValue (PersistText a) = maybeToEither "Invalid Persistent Address" $ base58ToAddr $ cs a fromPersistValue (PersistByteString a) = maybeToEither "Invalid Persistent Address" $ base58ToAddr a fromPersistValue _ = Left "Invalid Persistent Address" instance PersistFieldSql Address where sqlType _ = SqlString instance PersistField BloomFilter where toPersistValue = PersistByteString . S.encode fromPersistValue (PersistByteString bs) = case S.decode bs of Right x -> Right x Left e -> Left (fromString e) fromPersistValue _ = Left "Invalid Persistent BloomFilter" instance PersistFieldSql BloomFilter where sqlType _ = SqlBlob instance PersistField BlockHash where toPersistValue = PersistText . cs . blockHashToHex fromPersistValue (PersistText h) = maybeToEither "Could not decode BlockHash" $ hexToBlockHash $ cs h fromPersistValue (PersistByteString h) = maybeToEither "Could not decode BlockHash" $ hexToBlockHash h fromPersistValue _ = Left "Invalid Persistent BlockHash" instance PersistFieldSql BlockHash where sqlType _ = SqlString instance PersistField TxHash where toPersistValue = PersistText . cs . txHashToHex fromPersistValue (PersistText h) = maybeToEither "Invalid Persistent TxHash" $ hexToTxHash $ cs h fromPersistValue (PersistByteString h) = maybeToEither "Invalid Persistent TxHash" $ hexToTxHash h fromPersistValue _ = Left "Invalid Persistent TxHash" instance PersistFieldSql TxHash where sqlType _ = SqlString instance PersistField TxConfidence where toPersistValue tc = PersistText $ case tc of TxOffline -> "offline" TxDead -> "dead" TxPending -> "pending" TxBuilding -> "building" fromPersistValue (PersistText txt) = case txt of "offline" -> return TxOffline "dead" -> return TxDead "pending" -> return TxPending "building" -> return TxBuilding _ -> Left "Invalid Persistent TxConfidence" fromPersistValue (PersistByteString bs) = case bs of "offline" -> return TxOffline "dead" -> return TxDead "pending" -> return TxPending "building" -> return TxBuilding _ -> Left "Invalid Persistent TxConfidence" fromPersistValue _ = Left "Invalid Persistent TxConfidence" instance PersistFieldSql TxConfidence where sqlType _ = SqlString instance PersistField Tx where toPersistValue = PersistByteString . S.encode fromPersistValue (PersistByteString bs) = case S.decode bs of Right x -> Right x Left e -> Left (fromString e) fromPersistValue _ = Left "Invalid Persistent Tx" instance PersistFieldSql Tx where sqlType _ = SqlOther "MEDIUMBLOB" instance PersistField PubKeyC where toPersistValue = PersistText . cs . encodeHex . S.encode fromPersistValue (PersistText txt) = case hex >>= S.decode of Right x -> Right x Left e -> Left (fromString e) where hex = maybeToEither "Could not decode hex" (decodeHex (cs txt)) fromPersistValue (PersistByteString bs) = case hex >>= S.decode of Right x -> Right x Left e -> Left (fromString e) where hex = maybeToEither "Could not decode hex" (decodeHex bs) fromPersistValue _ = Left "Invalid Persistent PubKeyC" instance PersistFieldSql PubKeyC where sqlType _ = SqlString instance PersistField ScriptOutput where toPersistValue = PersistByteString . encodeOutputBS fromPersistValue (PersistByteString bs) = case decodeOutputBS bs of Right x -> Right x Left e -> Left (fromString e) fromPersistValue _ = Left "Invalid Persistent ScriptOutput" instance PersistFieldSql ScriptOutput where sqlType _ = SqlBlob instance PersistField [AddressInfo] where toPersistValue = PersistByteString . S.encode fromPersistValue (PersistByteString bs) = case S.decode bs of Right x -> Right x Left e -> Left (fromString e) fromPersistValue _ = Left "Invalid Persistent AddressInfo" instance PersistFieldSql [AddressInfo] where sqlType _ = SqlOther "MEDIUMBLOB" {- Helpers -} -- Join AND expressions with OR conditions in a binary way join2 :: [E.SqlExpr (E.Value Bool)] -> E.SqlExpr (E.Value Bool) join2 xs = case xs of [] -> E.val False [x] -> x _ -> let (ls,rs) = splitAt (length xs `div` 2) xs in join2 ls E.||. join2 rs splitSelect :: (SqlSelect a r, MonadIO m) => [t] -> ([t] -> E.SqlQuery a) -> E.SqlPersistT m [r] splitSelect ts queryF = fmap concat $ forM vals $ E.select . queryF where vals = chunksOf paramLimit ts splitUpdate :: ( MonadIO m , P.PersistEntity val , P.PersistEntityBackend val ~ E.SqlBackend ) => [t] -> ([t] -> E.SqlExpr (E.Entity val) -> E.SqlQuery ()) -> E.SqlPersistT m () splitUpdate ts updateF = forM_ vals $ E.update . updateF where vals = chunksOf paramLimit ts splitDelete :: MonadIO m => [t] -> ([t] -> E.SqlQuery ()) -> E.SqlPersistT m () splitDelete ts deleteF = forM_ vals $ E.delete . deleteF where vals = chunksOf paramLimit ts splitInsertMany_ :: ( MonadIO m , P.PersistEntity val , P.PersistEntityBackend val ~ E.SqlBackend ) => [val] -> E.SqlPersistT m () splitInsertMany_ = mapM_ P.insertMany_ . chunksOf paramLimit limitOffset :: Word32 -> Word32 -> E.SqlQuery () limitOffset l o = do when (l > 0) $ E.limit $ fromIntegral l when (o > 0) $ E.offset $ fromIntegral o
plaprade/haskoin
haskoin-wallet/src/Network/Haskoin/Wallet/Types.hs
unlicense
24,064
0
16
6,478
6,364
3,277
3,087
-1
-1
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts #-} {-# LANGUAGE GADTs #-} -- ** `Practical' denotational semantics module Tutorial1 where -- Consider a small subset of Haskell -- (or a pure functional subset of other suitable language) -- as an `executable Math' -- How to deal with side-effects, like input? -- Simple sub-language of effectful integer -- expressions, embedded in Haskell -- Define by denotational semantics: giving meaning to each -- expression and how to compose them -- Don't commit to a particular domain yet class ReaderLang d where int :: Int -> d -- Int literals add :: d -> d -> d ask :: d -- Sample expression rlExp = add ask (add ask (int 1)) -- What should be that d? -- EDLS, pp 2 and 6 -- EDLS, p7 -- * Implementing Math data CRead = CRVal Int | Get0 (Int -> CRead) instance ReaderLang CRead where int x = CRVal x ask = Get0 CRVal -- t1 = ask + ask -- p9 add (CRVal x) (CRVal y) = CRVal (x+y) add (Get0 k) y = Get0 (\x -> add (k x) y) add x (Get0 k) = Get0 (\y -> add x (k y)) -- The meaning of rlExp in that domain _ = rlExp :: CRead -- Need authority (admin)! -- p 11 runReader0 :: Int -> CRead -> Int runReader0 e (CRVal x) = x runReader0 e (Get0 k) = runReader0 e $ k e _ = runReader0 2 rlExp -- CRead is too particular semantic domain: nothing but Int value -- (computations) -- Need something more general -- Again, p7 data Comp req a where Val :: a -> Comp req a E :: req x -> (x -> Comp req a) -> Comp req a -- Effect signature data Get x where Get :: Get Int instance ReaderLang (Comp Get Int) where int x = Val x ask = E Get Val add (Val x) (Val y) = Val (x+y) add (E r k) y = E r (\x -> add (k x) y) add x (E r k) = E r (\y -> add x (k y)) -- How to extend to other types of env? runReader :: Int -> Comp Get a -> a runReader e (Val x) = x runReader e (E Get k) = runReader e $ k e _ = runReader 2 rlExp :: Int -- If we need subtraction, should we write the last two clauses -- over again? -- Generalizing even more -- p7, Fig 3 inV :: a -> Comp req a inV = Val bind :: Comp req a -> (a -> Comp req b) -> Comp req b bind (Val x) f = f x bind (E r k) f = E r (\x -> bind (k x) f) -- We can easily write even richer Reader languages, uniformly rlExp2 = bind ask $ \x -> bind ask $ \y -> Val (x + y + 1) -- with multiplication, subtraction, end re-using previous expressions rlExp3 = bind rlExp2 $ \x -> bind ask $ \y -> Val (x * y - 1) _ = runReader 2 rlExp3 :: Int
haroldcarr/learn-haskell-coq-ml-etc
haskell/conference/2017-09-cufp-effects/src/Tutorial1.hs
unlicense
2,605
0
12
686
841
443
398
50
1
-- | Query and update documents {-# LANGUAGE OverloadedStrings, RecordWildCards, NamedFieldPuns, TupleSections, FlexibleContexts, FlexibleInstances, UndecidableInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, StandaloneDeriving, TypeSynonymInstances, TypeFamilies #-} module Database.MongoDB.Query ( -- * Monad Action, access, Failure(..), ErrorCode, AccessMode(..), GetLastError, master, slaveOk, accessMode, MonadDB(..), -- * Database Database, allDatabases, useDb, thisDatabase, -- ** Authentication Username, Password, auth, -- * Collection Collection, allCollections, -- ** Selection Selection(..), Selector, whereJS, Select(select), -- * Write -- ** Insert insert, insert_, insertMany, insertMany_, insertAll, insertAll_, -- ** Update save, replace, repsert, Modifier, modify, -- ** Delete delete, deleteOne, -- * Read -- ** Query Query(..), QueryOption(NoCursorTimeout, TailableCursor, AwaitData, Partial), Projector, Limit, Order, BatchSize, explain, find, findOne, fetch, count, distinct, -- *** Cursor Cursor, nextBatch, next, nextN, rest, closeCursor, isCursorClosed, -- ** Group Group(..), GroupKey(..), group, -- ** MapReduce MapReduce(..), MapFun, ReduceFun, FinalizeFun, MROut(..), MRMerge(..), MRResult, mapReduce, runMR, runMR', -- * Command Command, runCommand, runCommand1, eval, ) where import Prelude as X hiding (lookup) import Data.UString as U (UString, dropWhile, any, tail) import Data.Bson (Document, at, valueAt, lookup, look, Field(..), (=:), (=?), Label, Value(String,Doc), Javascript, genObjectId) import Database.MongoDB.Internal.Protocol (Pipe, Notice(..), Request(GetMore, qOptions, qFullCollection, qSkip, qBatchSize, qSelector, qProjector), Reply(..), QueryOption(..), ResponseFlag(..), InsertOption(..), UpdateOption(..), DeleteOption(..), CursorId, FullCollection, Username, Password, pwKey) import qualified Database.MongoDB.Internal.Protocol as P (send, call, Request(Query)) import Database.MongoDB.Internal.Util (MonadIO', loop, liftIOE, true1, (<.>)) import Control.Monad.MVar import Control.Monad.Error import Control.Monad.Reader import Control.Monad.State (StateT) import Control.Monad.Writer (WriterT, Monoid) import Control.Monad.RWS (RWST) import Control.Monad.Base (MonadBase(liftBase)) import Control.Monad.Trans.Control (ComposeSt, MonadBaseControl(..), MonadTransControl(..), StM, StT, defaultLiftBaseWith, defaultRestoreM) import Control.Applicative (Applicative, (<$>)) import Data.Maybe (listToMaybe, catMaybes) import Data.Int (Int32) import Data.Word (Word32) -- * Monad newtype Action m a = Action {unAction :: ErrorT Failure (ReaderT Context m) a} deriving (Functor, Applicative, Monad, MonadIO, MonadError Failure) -- ^ A monad on top of m (which must be a MonadIO) that may access the database and may fail with a DB 'Failure' instance MonadBase b m => MonadBase b (Action m) where liftBase = Action . liftBase instance (MonadIO m, MonadBaseControl b m) => MonadBaseControl b (Action m) where newtype StM (Action m) a = StMT {unStMT :: ComposeSt Action m a} liftBaseWith = defaultLiftBaseWith StMT restoreM = defaultRestoreM unStMT instance MonadTrans Action where lift = Action . lift . lift instance MonadTransControl Action where newtype StT Action a = StActionT {unStAction :: StT (ReaderT Context) (StT (ErrorT Failure) a)} liftWith f = Action $ liftWith $ \runError -> liftWith $ \runReader -> f (liftM StActionT . runReader . runError . unAction) restoreT = Action . restoreT . restoreT . liftM unStAction access :: (MonadIO m) => Pipe -> AccessMode -> Database -> Action m a -> m (Either Failure a) -- ^ Run action against database on server at other end of pipe. Use access mode for any reads and writes. Return Left on connection failure or read/write failure. access myPipe myAccessMode myDatabase (Action action) = runReaderT (runErrorT action) Context{..} -- | A connection failure, or a read or write exception like cursor expired or inserting a duplicate key. -- Note, unexpected data from the server is not a Failure, rather it is a programming error (you should call 'error' in this case) because the client and server are incompatible and requires a programming change. data Failure = ConnectionFailure IOError -- ^ TCP connection ('Pipeline') failed. May work if you try again on the same Mongo 'Connection' which will create a new Pipe. | CursorNotFoundFailure CursorId -- ^ Cursor expired because it wasn't accessed for over 10 minutes, or this cursor came from a different server that the one you are currently connected to (perhaps a fail over happen between servers in a replica set) | QueryFailure ErrorCode String -- ^ Query failed for some reason as described in the string | WriteFailure ErrorCode String -- ^ Error observed by getLastError after a write, error description is in string | DocNotFound Selection -- ^ 'fetch' found no document matching selection deriving (Show, Eq) type ErrorCode = Int -- ^ Error code from getLastError or query failure instance Error Failure where strMsg = error -- ^ 'fail' is treated the same as a programming 'error'. In other words, don't use it. -- | Type of reads and writes to perform data AccessMode = ReadStaleOk -- ^ Read-only action, reading stale data from a slave is OK. | UnconfirmedWrites -- ^ Read-write action, slave not OK, every write is fire & forget. | ConfirmWrites GetLastError -- ^ Read-write action, slave not OK, every write is confirmed with getLastError. type GetLastError = Document -- ^ Parameters for getLastError command. For example @[\"w\" =: 2]@ tells the server to wait for the write to reach at least two servers in replica set before acknowledging. See <http://www.mongodb.org/display/DOCS/Last+Error+Commands> for more options. master :: AccessMode -- ^ Same as 'ConfirmWrites' [] master = ConfirmWrites [] slaveOk :: AccessMode -- ^ Same as 'ReadStaleOk' slaveOk = ReadStaleOk accessMode :: (Monad m) => AccessMode -> Action m a -> Action m a -- ^ Run action with given 'AccessMode' accessMode mode (Action act) = Action $ local (\ctx -> ctx {myAccessMode = mode}) act readMode :: AccessMode -> ReadMode readMode ReadStaleOk = StaleOk readMode _ = Fresh writeMode :: AccessMode -> WriteMode writeMode ReadStaleOk = Confirm [] writeMode UnconfirmedWrites = NoConfirm writeMode (ConfirmWrites z) = Confirm z -- | Values needed when executing a db operation data Context = Context { myPipe :: Pipe, -- ^ operations read/write to this pipelined TCP connection to a MongoDB server myAccessMode :: AccessMode, -- ^ read/write operation will use this access mode myDatabase :: Database } -- ^ operations query/update this database myReadMode :: Context -> ReadMode myReadMode = readMode . myAccessMode myWriteMode :: Context -> WriteMode myWriteMode = writeMode . myAccessMode send :: (MonadIO m) => [Notice] -> Action m () -- ^ Send notices as a contiguous batch to server with no reply. Throw 'ConnectionFailure' if pipe fails. send ns = Action $ do pipe <- asks myPipe liftIOE ConnectionFailure $ P.send pipe ns call :: (MonadIO m) => [Notice] -> Request -> Action m (ErrorT Failure IO Reply) -- ^ Send notices and request as a contiguous batch to server and return reply promise, which will block when invoked until reply arrives. This call will throw 'ConnectionFailure' if pipe fails on send, and promise will throw 'ConnectionFailure' if pipe fails on receive. call ns r = Action $ do pipe <- asks myPipe promise <- liftIOE ConnectionFailure $ P.call pipe ns r return (liftIOE ConnectionFailure promise) -- | If you stack a monad on top of 'Action' then make it an instance of this class and use 'liftDB' to execute a DB Action within it. Instances already exist for the basic mtl transformers. class (Monad m, MonadBaseControl IO (BaseMonad m), Applicative (BaseMonad m), Functor (BaseMonad m)) => MonadDB m where type BaseMonad m :: * -> * liftDB :: Action (BaseMonad m) a -> m a instance (MonadBaseControl IO m, Applicative m, Functor m) => MonadDB (Action m) where type BaseMonad (Action m) = m liftDB = id instance (MonadDB m, Error e) => MonadDB (ErrorT e m) where type BaseMonad (ErrorT e m) = BaseMonad m liftDB = lift . liftDB instance (MonadDB m) => MonadDB (ReaderT r m) where type BaseMonad (ReaderT r m) = BaseMonad m liftDB = lift . liftDB instance (MonadDB m) => MonadDB (StateT s m) where type BaseMonad (StateT s m) = BaseMonad m liftDB = lift . liftDB instance (MonadDB m, Monoid w) => MonadDB (WriterT w m) where type BaseMonad (WriterT w m) = BaseMonad m liftDB = lift . liftDB instance (MonadDB m, Monoid w) => MonadDB (RWST r w s m) where type BaseMonad (RWST r w s m) = BaseMonad m liftDB = lift . liftDB -- * Database type Database = UString allDatabases :: (MonadIO' m) => Action m [Database] -- ^ List all databases residing on server allDatabases = map (at "name") . at "databases" <$> useDb "admin" (runCommand1 "listDatabases") thisDatabase :: (Monad m) => Action m Database -- ^ Current database in use thisDatabase = Action $ asks myDatabase useDb :: (Monad m) => Database -> Action m a -> Action m a -- ^ Run action against given database useDb db (Action act) = Action $ local (\ctx -> ctx {myDatabase = db}) act -- * Authentication auth :: (MonadIO' m) => Username -> Password -> Action m Bool -- ^ Authenticate with the current database (if server is running in secure mode). Return whether authentication was successful or not. Reauthentication is required for every new pipe. auth usr pss = do n <- at "nonce" <$> runCommand ["getnonce" =: (1 :: Int)] true1 "ok" <$> runCommand ["authenticate" =: (1 :: Int), "user" =: usr, "nonce" =: n, "key" =: pwKey n usr pss] -- * Collection type Collection = UString -- ^ Collection name (not prefixed with database) allCollections :: (MonadIO m, MonadBaseControl IO m, Functor m) => Action m [Collection] -- ^ List all collections in this database allCollections = do db <- thisDatabase docs <- rest =<< find (query [] "system.namespaces") {sort = ["name" =: (1 :: Int)]} return . filter (not . isSpecial db) . map dropDbPrefix $ map (at "name") docs where dropDbPrefix = U.tail . U.dropWhile (/= '.') isSpecial db col = U.any (== '$') col && db <.> col /= "local.oplog.$main" -- * Selection data Selection = Select {selector :: Selector, coll :: Collection} deriving (Show, Eq) -- ^ Selects documents in collection that match selector type Selector = Document -- ^ Filter for a query, analogous to the where clause in SQL. @[]@ matches all documents in collection. @[\"x\" =: a, \"y\" =: b]@ is analogous to @where x = a and y = b@ in SQL. See <http://www.mongodb.org/display/DOCS/Querying> for full selector syntax. whereJS :: Selector -> Javascript -> Selector -- ^ Add Javascript predicate to selector, in which case a document must match both selector and predicate whereJS sel js = ("$where" =: js) : sel class Select aQueryOrSelection where select :: Selector -> Collection -> aQueryOrSelection -- ^ 'Query' or 'Selection' that selects documents in collection that match selector. The choice of type depends on use, for example, in @find (select sel col)@ it is a Query, and in @delete (select sel col)@ it is a Selection. instance Select Selection where select = Select instance Select Query where select = query -- * Write data WriteMode = NoConfirm -- ^ Submit writes without receiving acknowledgments. Fast. Assumes writes succeed even though they may not. | Confirm GetLastError -- ^ Receive an acknowledgment after every write, and raise exception if one says the write failed. This is acomplished by sending the getLastError command, with given 'GetLastError' parameters, after every write. deriving (Show, Eq) write :: (MonadIO m) => Notice -> Action m () -- ^ Send write to server, and if write-mode is 'Safe' then include getLastError request and raise 'WriteFailure' if it reports an error. write notice = Action (asks myWriteMode) >>= \mode -> case mode of NoConfirm -> send [notice] Confirm params -> do let q = query (("getlasterror" =: (1 :: Int)) : params) "$cmd" Batch _ _ [doc] <- fulfill =<< request [notice] =<< queryRequest False q {limit = 1} case lookup "err" doc of Nothing -> return () Just err -> throwError $ WriteFailure (maybe 0 id $ lookup "code" doc) err -- ** Insert insert :: (MonadIO' m) => Collection -> Document -> Action m Value -- ^ Insert document into collection and return its \"_id\" value, which is created automatically if not supplied insert col doc = head <$> insertMany col [doc] insert_ :: (MonadIO' m) => Collection -> Document -> Action m () -- ^ Same as 'insert' except don't return _id insert_ col doc = insert col doc >> return () insertMany :: (MonadIO m) => Collection -> [Document] -> Action m [Value] -- ^ Insert documents into collection and return their \"_id\" values, which are created automatically if not supplied. If a document fails to be inserted (eg. due to duplicate key) then remaining docs are aborted, and LastError is set. insertMany = insert' [] insertMany_ :: (MonadIO m) => Collection -> [Document] -> Action m () -- ^ Same as 'insertMany' except don't return _ids insertMany_ col docs = insertMany col docs >> return () insertAll :: (MonadIO m) => Collection -> [Document] -> Action m [Value] -- ^ Insert documents into collection and return their \"_id\" values, which are created automatically if not supplied. If a document fails to be inserted (eg. due to duplicate key) then remaining docs are still inserted. LastError is set if any doc fails, not just last one. insertAll = insert' [KeepGoing] insertAll_ :: (MonadIO m) => Collection -> [Document] -> Action m () -- ^ Same as 'insertAll' except don't return _ids insertAll_ col docs = insertAll col docs >> return () insert' :: (MonadIO m) => [InsertOption] -> Collection -> [Document] -> Action m [Value] -- ^ Insert documents into collection and return their \"_id\" values, which are created automatically if not supplied insert' opts col docs = do db <- thisDatabase docs' <- liftIO $ mapM assignId docs write (Insert (db <.> col) opts docs') return $ map (valueAt "_id") docs' assignId :: Document -> IO Document -- ^ Assign a unique value to _id field if missing assignId doc = if X.any (("_id" ==) . label) doc then return doc else (\oid -> ("_id" =: oid) : doc) <$> genObjectId -- ** Update save :: (MonadIO' m) => Collection -> Document -> Action m () -- ^ Save document to collection, meaning insert it if its new (has no \"_id\" field) or update it if its not new (has \"_id\" field) save col doc = case look "_id" doc of Nothing -> insert_ col doc Just i -> repsert (Select ["_id" := i] col) doc replace :: (MonadIO m) => Selection -> Document -> Action m () -- ^ Replace first document in selection with given document replace = update [] repsert :: (MonadIO m) => Selection -> Document -> Action m () -- ^ Replace first document in selection with given document, or insert document if selection is empty repsert = update [Upsert] type Modifier = Document -- ^ Update operations on fields in a document. See <http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations> modify :: (MonadIO m) => Selection -> Modifier -> Action m () -- ^ Update all documents in selection using given modifier modify = update [MultiUpdate] update :: (MonadIO m) => [UpdateOption] -> Selection -> Document -> Action m () -- ^ Update first document in selection using updater document, unless 'MultiUpdate' option is supplied then update all documents in selection. If 'Upsert' option is supplied then treat updater as document and insert it if selection is empty. update opts (Select sel col) up = do db <- thisDatabase write (Update (db <.> col) opts sel up) -- ** Delete delete :: (MonadIO m) => Selection -> Action m () -- ^ Delete all documents in selection delete = delete' [] deleteOne :: (MonadIO m) => Selection -> Action m () -- ^ Delete first document in selection deleteOne = delete' [SingleRemove] delete' :: (MonadIO m) => [DeleteOption] -> Selection -> Action m () -- ^ Delete all documents in selection unless 'SingleRemove' option is given then only delete first document in selection delete' opts (Select sel col) = do db <- thisDatabase write (Delete (db <.> col) opts sel) -- * Read data ReadMode = Fresh -- ^ read from master only | StaleOk -- ^ read from slave ok deriving (Show, Eq) readModeOption :: ReadMode -> [QueryOption] readModeOption Fresh = [] readModeOption StaleOk = [SlaveOK] -- ** Query -- | Use 'select' to create a basic query with defaults, then modify if desired. For example, @(select sel col) {limit = 10}@ data Query = Query { options :: [QueryOption], -- ^ Default = [] selection :: Selection, project :: Projector, -- ^ \[\] = all fields. Default = [] skip :: Word32, -- ^ Number of initial matching documents to skip. Default = 0 limit :: Limit, -- ^ Maximum number of documents to return, 0 = no limit. Default = 0 sort :: Order, -- ^ Sort results by this order, [] = no sort. Default = [] snapshot :: Bool, -- ^ If true assures no duplicates are returned, or objects missed, which were present at both the start and end of the query's execution (even if the object were updated). If an object is new during the query, or deleted during the query, it may or may not be returned, even with snapshot mode. Note that short query responses (less than 1MB) are always effectively snapshotted. Default = False batchSize :: BatchSize, -- ^ The number of document to return in each batch response from the server. 0 means use Mongo default. Default = 0 hint :: Order -- ^ Force MongoDB to use this index, [] = no hint. Default = [] } deriving (Show, Eq) type Projector = Document -- ^ Fields to return, analogous to the select clause in SQL. @[]@ means return whole document (analogous to * in SQL). @[\"x\" =: 1, \"y\" =: 1]@ means return only @x@ and @y@ fields of each document. @[\"x\" =: 0]@ means return all fields except @x@. type Limit = Word32 -- ^ Maximum number of documents to return, i.e. cursor will close after iterating over this number of documents. 0 means no limit. type Order = Document -- ^ Fields to sort by. Each one is associated with 1 or -1. Eg. @[\"x\" =: 1, \"y\" =: -1]@ means sort by @x@ ascending then @y@ descending type BatchSize = Word32 -- ^ The number of document to return in each batch response from the server. 0 means use Mongo default. query :: Selector -> Collection -> Query -- ^ Selects documents in collection that match selector. It uses no query options, projects all fields, does not skip any documents, does not limit result size, uses default batch size, does not sort, does not hint, and does not snapshot. query sel col = Query [] (Select sel col) [] 0 0 [] False 0 [] find :: (MonadIO m, MonadBaseControl IO m) => Query -> Action m Cursor -- ^ Fetch documents satisfying query find q@Query{selection, batchSize} = do db <- thisDatabase dBatch <- request [] =<< queryRequest False q newCursor db (coll selection) batchSize dBatch findOne :: (MonadIO m) => Query -> Action m (Maybe Document) -- ^ Fetch first document satisfying query or Nothing if none satisfy it findOne q = do Batch _ _ docs <- fulfill =<< request [] =<< queryRequest False q {limit = 1} return (listToMaybe docs) fetch :: (MonadIO m) => Query -> Action m Document -- ^ Same as 'findOne' except throw 'DocNotFound' if none match fetch q = findOne q >>= maybe (throwError $ DocNotFound $ selection q) return explain :: (MonadIO m) => Query -> Action m Document -- ^ Return performance stats of query execution explain q = do -- same as findOne but with explain set to true Batch _ _ docs <- fulfill =<< request [] =<< queryRequest True q {limit = 1} return $ if null docs then error ("no explain: " ++ show q) else head docs count :: (MonadIO' m) => Query -> Action m Int -- ^ Fetch number of documents satisfying query (including effect of skip and/or limit if present) count Query{selection = Select sel col, skip, limit} = at "n" <$> runCommand (["count" =: col, "query" =: sel, "skip" =: (fromIntegral skip :: Int32)] ++ ("limit" =? if limit == 0 then Nothing else Just (fromIntegral limit :: Int32))) distinct :: (MonadIO' m) => Label -> Selection -> Action m [Value] -- ^ Fetch distinct values of field in selected documents distinct k (Select sel col) = at "values" <$> runCommand ["distinct" =: col, "key" =: k, "query" =: sel] queryRequest :: (Monad m) => Bool -> Query -> Action m (Request, Limit) -- ^ Translate Query to Protocol.Query. If first arg is true then add special $explain attribute. queryRequest isExplain Query{..} = do ctx <- Action ask return $ queryRequest' (myReadMode ctx) (myDatabase ctx) where queryRequest' rm db = (P.Query{..}, remainingLimit) where qOptions = readModeOption rm ++ options qFullCollection = db <.> coll selection qSkip = fromIntegral skip (qBatchSize, remainingLimit) = batchSizeRemainingLimit batchSize limit qProjector = project mOrder = if null sort then Nothing else Just ("$orderby" =: sort) mSnapshot = if snapshot then Just ("$snapshot" =: True) else Nothing mHint = if null hint then Nothing else Just ("$hint" =: hint) mExplain = if isExplain then Just ("$explain" =: True) else Nothing special = catMaybes [mOrder, mSnapshot, mHint, mExplain] qSelector = if null special then s else ("$query" =: s) : special where s = selector selection batchSizeRemainingLimit :: BatchSize -> Limit -> (Int32, Limit) -- ^ Given batchSize and limit return P.qBatchSize and remaining limit batchSizeRemainingLimit batchSize limit = if limit == 0 then (fromIntegral batchSize', 0) -- no limit else if 0 < batchSize' && batchSize' < limit then (fromIntegral batchSize', limit - batchSize') else (- fromIntegral limit, 1) where batchSize' = if batchSize == 1 then 2 else batchSize -- batchSize 1 is broken because server converts 1 to -1 meaning limit 1 type DelayedBatch = ErrorT Failure IO Batch -- ^ A promised batch which may fail data Batch = Batch Limit CursorId [Document] -- ^ CursorId = 0 means cursor is finished. Documents is remaining documents to serve in current batch. Limit is remaining limit for next fetch. request :: (MonadIO m) => [Notice] -> (Request, Limit) -> Action m DelayedBatch -- ^ Send notices and request and return promised batch request ns (req, remainingLimit) = do promise <- call ns req return $ fromReply remainingLimit =<< promise fromReply :: Limit -> Reply -> DelayedBatch -- ^ Convert Reply to Batch or Failure fromReply limit Reply{..} = do mapM_ checkResponseFlag rResponseFlags return (Batch limit rCursorId rDocuments) where -- If response flag indicates failure then throw it, otherwise do nothing checkResponseFlag flag = case flag of AwaitCapable -> return () CursorNotFound -> throwError $ CursorNotFoundFailure rCursorId QueryError -> throwError $ QueryFailure (at "code" $ head rDocuments) (at "$err" $ head rDocuments) fulfill :: (MonadIO m) => DelayedBatch -> Action m Batch -- ^ Demand and wait for result, raise failure if exception fulfill = Action . liftIOE id -- *** Cursor data Cursor = Cursor FullCollection BatchSize (MVar DelayedBatch) -- ^ Iterator over results of a query. Use 'next' to iterate or 'rest' to get all results. A cursor is closed when it is explicitly closed, all results have been read from it, garbage collected, or not used for over 10 minutes (unless 'NoCursorTimeout' option was specified in 'Query'). Reading from a closed cursor raises a 'CursorNotFoundFailure'. Note, a cursor is not closed when the pipe is closed, so you can open another pipe to the same server and continue using the cursor. newCursor :: (MonadIO m, MonadBaseControl IO m) => Database -> Collection -> BatchSize -> DelayedBatch -> Action m Cursor -- ^ Create new cursor. If you don't read all results then close it. Cursor will be closed automatically when all results are read from it or when eventually garbage collected. newCursor db col batchSize dBatch = do var <- newMVar dBatch let cursor = Cursor (db <.> col) batchSize var addMVarFinalizer var (closeCursor cursor) return cursor nextBatch :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m [Document] -- ^ Return next batch of documents in query result, which will be empty if finished. nextBatch (Cursor fcol batchSize var) = modifyMVar var $ \dBatch -> do -- Pre-fetch next batch promise from server and return current batch. Batch limit cid docs <- fulfill dBatch dBatch' <- if cid /= 0 then nextBatch' limit cid else return $ return (Batch 0 0 []) return (dBatch', docs) where nextBatch' limit cid = request [] (GetMore fcol batchSize' cid, remLimit) where (batchSize', remLimit) = batchSizeRemainingLimit batchSize limit next :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m (Maybe Document) -- ^ Return next document in query result, or Nothing if finished. next (Cursor fcol batchSize var) = modifyMVar var nextState where -- Pre-fetch next batch promise from server when last one in current batch is returned. -- nextState:: DelayedBatch -> Action m (DelayedBatch, Maybe Document) nextState dBatch = do Batch limit cid docs <- fulfill dBatch case docs of doc : docs' -> do dBatch' <- if null docs' && cid /= 0 then nextBatch' limit cid else return $ return (Batch limit cid docs') return (dBatch', Just doc) [] -> if cid == 0 then return (return $ Batch 0 0 [], Nothing) -- finished else error $ "server returned empty batch but says more results on server" nextBatch' limit cid = request [] (GetMore fcol batchSize' cid, remLimit) where (batchSize', remLimit) = batchSizeRemainingLimit batchSize limit nextN :: (MonadIO m, MonadBaseControl IO m, Functor m) => Int -> Cursor -> Action m [Document] -- ^ Return next N documents or less if end is reached nextN n c = catMaybes <$> replicateM n (next c) rest :: (MonadIO m, MonadBaseControl IO m, Functor m) => Cursor -> Action m [Document] -- ^ Return remaining documents in query result rest c = loop (next c) closeCursor :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m () closeCursor (Cursor _ _ var) = modifyMVar var $ \dBatch -> do Batch _ cid _ <- fulfill dBatch unless (cid == 0) $ send [KillCursors [cid]] return $ (return $ Batch 0 0 [], ()) isCursorClosed :: (MonadIO m) => Cursor -> Action m Bool isCursorClosed (Cursor _ _ var) = do Batch _ cid docs <- fulfill =<< readMVar var return (cid == 0 && null docs) -- ** Group -- | Groups documents in collection by key then reduces (aggregates) each group data Group = Group { gColl :: Collection, gKey :: GroupKey, -- ^ Fields to group by gReduce :: Javascript, -- ^ @(doc, agg) -> ()@. The reduce function reduces (aggregates) the objects iterated. Typical operations of a reduce function include summing and counting. It takes two arguments, the current document being iterated over and the aggregation value, and updates the aggregate value. gInitial :: Document, -- ^ @agg@. Initial aggregation value supplied to reduce gCond :: Selector, -- ^ Condition that must be true for a row to be considered. [] means always true. gFinalize :: Maybe Javascript -- ^ @agg -> () | result@. An optional function to be run on each item in the result set just before the item is returned. Can either modify the item (e.g., add an average field given a count and a total) or return a replacement object (returning a new object with just _id and average fields). } deriving (Show, Eq) data GroupKey = Key [Label] | KeyF Javascript deriving (Show, Eq) -- ^ Fields to group by, or function (@doc -> key@) returning a "key object" to be used as the grouping key. Use KeyF instead of Key to specify a key that is not an existing member of the object (or, to access embedded members). groupDocument :: Group -> Document -- ^ Translate Group data into expected document form groupDocument Group{..} = ("finalize" =? gFinalize) ++ [ "ns" =: gColl, case gKey of Key k -> "key" =: map (=: True) k; KeyF f -> "$keyf" =: f, "$reduce" =: gReduce, "initial" =: gInitial, "cond" =: gCond ] group :: (MonadIO' m) => Group -> Action m [Document] -- ^ Execute group query and return resulting aggregate value for each distinct key group g = at "retval" <$> runCommand ["group" =: groupDocument g] -- ** MapReduce -- | Maps every document in collection to a list of (key, value) pairs, then for each unique key reduces all its associated values to a single result. There are additional parameters that may be set to tweak this basic operation. -- This implements the latest version of map-reduce that requires MongoDB 1.7.4 or greater. To map-reduce against an older server use runCommand directly as described in http://www.mongodb.org/display/DOCS/MapReduce. data MapReduce = MapReduce { rColl :: Collection, rMap :: MapFun, rReduce :: ReduceFun, rSelect :: Selector, -- ^ Operate on only those documents selected. Default is [] meaning all documents. rSort :: Order, -- ^ Default is [] meaning no sort rLimit :: Limit, -- ^ Default is 0 meaning no limit rOut :: MROut, -- ^ Output to a collection with a certain merge policy. Default is no collection ('Inline'). Note, you don't want this default if your result set is large. rFinalize :: Maybe FinalizeFun, -- ^ Function to apply to all the results when finished. Default is Nothing. rScope :: Document, -- ^ Variables (environment) that can be accessed from map/reduce/finalize. Default is []. rVerbose :: Bool -- ^ Provide statistics on job execution time. Default is False. } deriving (Show, Eq) type MapFun = Javascript -- ^ @() -> void@. The map function references the variable @this@ to inspect the current object under consideration. The function must call @emit(key,value)@ at least once, but may be invoked any number of times, as may be appropriate. type ReduceFun = Javascript -- ^ @(key, [value]) -> value@. The reduce function receives a key and an array of values and returns an aggregate result value. The MapReduce engine may invoke reduce functions iteratively; thus, these functions must be idempotent. That is, the following must hold for your reduce function: @reduce(k, [reduce(k,vs)]) == reduce(k,vs)@. If you need to perform an operation only once, use a finalize function. The output of emit (the 2nd param) and reduce should be the same format to make iterative reduce possible. type FinalizeFun = Javascript -- ^ @(key, value) -> final_value@. A finalize function may be run after reduction. Such a function is optional and is not necessary for many map/reduce cases. The finalize function takes a key and a value, and returns a finalized value. data MROut = Inline -- ^ Return results directly instead of writing them to an output collection. Results must fit within 16MB limit of a single document | Output MRMerge Collection (Maybe Database) -- ^ Write results to given collection, in other database if specified. Follow merge policy when entry already exists deriving (Show, Eq) data MRMerge = Replace -- ^ Clear all old data and replace it with new data | Merge -- ^ Leave old data but overwrite entries with the same key with new data | Reduce -- ^ Leave old data but combine entries with the same key via MR's reduce function deriving (Show, Eq) type MRResult = Document -- ^ Result of running a MapReduce has some stats besides the output. See http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Resultobject mrDocument :: MapReduce -> Document -- ^ Translate MapReduce data into expected document form mrDocument MapReduce{..} = ("mapreduce" =: rColl) : ("out" =: mrOutDoc rOut) : ("finalize" =? rFinalize) ++ [ "map" =: rMap, "reduce" =: rReduce, "query" =: rSelect, "sort" =: rSort, "limit" =: (fromIntegral rLimit :: Int), "scope" =: rScope, "verbose" =: rVerbose ] mrOutDoc :: MROut -> Document -- ^ Translate MROut into expected document form mrOutDoc Inline = ["inline" =: (1 :: Int)] mrOutDoc (Output mrMerge coll mDB) = (mergeName mrMerge =: coll) : mdb mDB where mergeName Replace = "replace" mergeName Merge = "merge" mergeName Reduce = "reduce" mdb Nothing = [] mdb (Just db) = ["db" =: db] mapReduce :: Collection -> MapFun -> ReduceFun -> MapReduce -- ^ MapReduce on collection with given map and reduce functions. Remaining attributes are set to their defaults, which are stated in their comments. mapReduce col map' red = MapReduce col map' red [] [] 0 Inline Nothing [] False runMR :: (MonadIO m, MonadBaseControl IO m, Applicative m) => MapReduce -> Action m Cursor -- ^ Run MapReduce and return cursor of results. Error if map/reduce fails (because of bad Javascript) runMR mr = do res <- runMR' mr case look "result" res of Just (String coll) -> find $ query [] coll Just (Doc doc) -> useDb (at "db" doc) $ find $ query [] (at "collection" doc) Just x -> error $ "unexpected map-reduce result field: " ++ show x Nothing -> newCursor "" "" 0 $ return $ Batch 0 0 (at "results" res) runMR' :: (MonadIO' m) => MapReduce -> Action m MRResult -- ^ Run MapReduce and return a MR result document containing stats and the results if Inlined. Error if the map/reduce failed (because of bad Javascript). runMR' mr = do doc <- runCommand (mrDocument mr) return $ if true1 "ok" doc then doc else error $ "mapReduce error:\n" ++ show doc ++ "\nin:\n" ++ show mr -- * Command type Command = Document -- ^ A command is a special query or action against the database. See <http://www.mongodb.org/display/DOCS/Commands> for details. runCommand :: (MonadIO' m) => Command -> Action m Document -- ^ Run command against the database and return its result runCommand c = maybe err id <$> findOne (query c "$cmd") where err = error $ "Nothing returned for command: " ++ show c runCommand1 :: (MonadIO' m) => UString -> Action m Document -- ^ @runCommand1 foo = runCommand [foo =: 1]@ runCommand1 c = runCommand [c =: (1 :: Int)] eval :: (MonadIO' m) => Javascript -> Action m Document -- ^ Run code on server eval code = at "retval" <$> runCommand ["$eval" =: code] {- Authors: Tony Hannan <tony@10gen.com> Copyright 2011 10gen Inc. 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. -}
mongodb/mongoDB-haskell
Database/MongoDB/Query.hs
apache-2.0
34,762
349
20
6,263
7,875
4,280
3,595
425
6
module Main ( main ) where import Control.Concurrent (forkIO) import qualified GHC.IO.Handle as IO import qualified GHC.IO.Handle.FD as IO import HStatusBar.ModuleParser import qualified System.Environment as IO main :: IO () main = do IO.hSetBuffering IO.stdout IO.LineBuffering args <- (pack <$>) <$> IO.getArgs let modules = case parseModules (unwords args) of Left err -> error err Right mods -> mods commonChan :: Chan (Int, Text) <- newChan forM_ ([0 ..] `zip` modules) $ \(idx, mdl) -> do chan <- newChan void $ forkIO $ mdl chan void $ forkIO $ forever $ do val <- readChan chan writeChan commonChan (idx, val) let loop :: [Text] -> IO () loop vals = do (idx, val) <- readChan commonChan let newVals = editNth vals idx val when (newVals /= vals) $ putStrLn $ concat newVals loop newVals loop $ const "" <$> modules editNth :: [a] -> Int -> a -> [a] editNth xs n x = if 0 <= n && n < length xs then take n xs ++ [x] ++ drop (n + 1) xs else xs
michalrus/hstatusbar
src/Main.hs
apache-2.0
1,134
0
16
361
445
228
217
-1
-1
module Emulator.ROM.ParserSpec where import Emulator.ROM import Emulator.ROM.Parser import Control.Lens import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "readROM" $ do it "should be able to read a ROM from a file" $ do readROM "./res/suite.gba" >>= \case Left err -> fail err Right (rh, _, _) -> do rh ^. magicByte `shouldBe` 0x96
intolerable/GroupProject
test/Emulator/ROM/ParserSpec.hs
bsd-2-clause
407
0
20
105
131
68
63
-1
-1
module QueryTest where import Control.Exception import Opticover import Test.Tasty import Test.Tasty.HUnit case_simpleLiftField :: Assertion case_simpleLiftField = do let a = Portal (Point 0 0) "a" b = Portal (Point 1 1) "b" c = Portal (Point 1 0) "c" links = linksMap [link a c, link c b] now = link a b fields = liftFields now links field <- case fields of [a] -> return a x -> error $ "Unexpected fields list " ++ show x fieldSquare field @?= 0.5 case_doubleLiftField :: Assertion case_doubleLiftField = do let a = Portal (Point 0 0) "a" b = Portal (Point 1 1) "b" c = Portal (Point 1 0) "c" d = Portal (Point 0 1) "d" links = linksMap [link a c, link c b, link a d, link d b] now = link a b fields = liftFields now links (f1, f2) <- case fields of [f1, f2] -> return (f1, f2) x -> error $ "Unexpected fields list " ++ show x fieldSquare f1 @?= 0.5 fieldSquare f2 @?= 0.5 case_doubleMaxField :: Assertion case_doubleMaxField = do let a = Portal (Point 0 0) "a" b = Portal (Point 1 1) "b" c = Portal (Point 1 0) "c" e = Portal (Point 0.75 0.25) "e" d = Portal (Point 0 1) "d" f = Portal (Point 0.25 0.75) "f" links = linksMap [ link a c, link c b, link a d, link d b , link a e, link e b, link a f, link f b ] now = link a b fields = liftFields now links (f1, f2) <- case fields of [f1, f2] -> return (f1, f2) x -> error $ "Unexpected fields list " ++ show x fieldSquare f1 @?= 0.5 fieldSquare f2 @?= 0.5
s9gf4ult/opticover
test/QueryTest.hs
bsd-3-clause
1,563
0
12
449
695
348
347
52
2
module Frenetic.Update where import Frenetic.Common import Nettle.OpenFlow.Match import Frenetic.NetCore.Compiler import Frenetic.NetCore.Types import Frenetic.NetCore.Short explode_all_ports ver m all_ports edge_ports = map (\ p -> (case (p `elem` edge_ports) of True -> Forward (Physical p) (m {modifyDlVlan = Just Nothing}) False -> Forward (Physical p) (m {modifyDlVlan = Just (Just ver)}) )) all_ports version_acts [] version all_ports edge_ports = [] version_acts (Forward (Physical p') m : actions) version all_ports edge_ports = case (p' `elem` edge_ports) of True -> Forward (Physical p') (m {modifyDlVlan = Just Nothing}) : (version_acts actions version all_ports edge_ports) False -> Forward (Physical p') (m {modifyDlVlan = Just (Just version)}) : version_acts actions version all_ports edge_ports version_acts (Forward AllPorts m : actions) version all_ports edge_ports = explode_all_ports version m all_ports edge_ports ++ version_acts actions version all_ports edge_ports version_internal_pol (PoUnion p1 p2) ver sw all_ports ext_ports = (version_internal_pol p1 ver sw all_ports ext_ports) <+> (version_internal_pol p2 ver sw all_ports ext_ports) version_internal_pol (PoBasic pr acts) ver sw all_ports ext_ports = ((Switch sw) <&&> ((DlVlan (Just ver)) <&&> pr)) ==> (version_acts acts ver all_ports ext_ports) version_internal_pol (Restrict p pr) ver sw all_ports ext_ports = (version_internal_pol p ver sw all_ports ext_ports) <%> pr version_full_pol (PoUnion p1 p2) ver sw all_ports ext_ports = (version_full_pol p1 ver sw all_ports ext_ports) <+> (version_full_pol p2 ver sw all_ports ext_ports) version_full_pol (PoBasic pr acts) ver sw all_ports ext_ports = (((Switch sw) <&&> ((DlVlan (Just ver)) <&&> pr)) ==> (version_acts acts ver all_ports ext_ports)) <+> ((((Switch sw) <&&> (DlVlan Nothing)) <&&> pr) ==> (version_acts acts ver all_ports ext_ports)) version_full_pol (Restrict p pr) ver sw all_ports ext_ports = (version_full_pol p ver sw all_ports ext_ports) <%> pr reduce_pol (PoUnion (PoBasic _ []) p) = reduce_pol p reduce_pol (PoUnion p (PoBasic _ [])) = reduce_pol p reduce_pol (PoUnion p1 p2) = let p1' = reduce_pol p1 in let p2' = reduce_pol p2 in case (p1', p2') of (PoBasic _ [], p2') -> p2' (p1', PoBasic _ []) -> p1' _ -> p1' <+> p2' reduce_pol p = p gen_update_pols _ _ [] _ _ = (PoBasic None [], PoBasic None []) gen_update_pols orig ver (sw : switches) allPorts extPorts = let (p1,p2) = (\x -> (reduce_pol $ fst x, reduce_pol $ snd x)) $ gen_update_pols orig ver switches allPorts extPorts in (((reduce_pol (version_internal_pol orig ver sw (allPorts sw) (extPorts sw))) <+> p1), ((reduce_pol (version_full_pol orig ver sw (allPorts sw) (extPorts sw))) <+> p2))
frenetic-lang/netcore-1.0
src/Frenetic/Update.hs
bsd-3-clause
2,900
0
18
584
1,120
576
544
47
3
module Inspection.Config where import Data.List (find) import GHC.Generics (Generic ()) import Data.Aeson.Extra import Data.Yaml (decodeFileEither) import Inspection.Data import Inspection.Data.ReleaseTag (GithubOwner) data Config = Config { superusers :: [GithubOwner] , compilers :: [Compiler] , packages :: [GithubLocation] , releaseFilter :: ReleaseFilter } deriving (Show, Generic) getConfig :: FilePath -> IO Config getConfig fp = either (fail . show) pure =<< decodeFileEither fp packageNames :: Config -> [PackageName] packageNames = map (\(GithubLocation _ n) -> n ) . packages packageLocation :: PackageName -> Config -> Maybe GithubLocation packageLocation name = find (\(GithubLocation _ name') -> name == name') . packages instance FromJSON Config
zudov/purescript-inspection
src/Inspection/Config.hs
bsd-3-clause
831
0
10
171
251
141
110
21
1
module Day08 where import Protolude hiding (try) import Prelude (read) import Text.Megaparsec import Text.Megaparsec.Text import Data.Array.MArray import Data.Array.ST import Data.Array.Unboxed import Data.List.Split (chunksOf) import qualified Data.Text as Text type MutableGrid s = STUArray s Coord Bool type Grid = UArray Coord Bool type Coord = (Int, Int) data Instruction = Rect Int Int | RotateRow Int Int | RotateCol Int Int deriving (Show) measureVoltage :: Grid -> Int measureVoltage = length . filter identity . elems displayGrid :: Grid -> Text displayGrid g = Text.unlines $ map (toS . formatLine) lines where formatLine = intercalate " " . chunksOf 5 lines = transpose $ chunksOf 6 pixels pixels = displayPixel <$> elems g displayPixel = \case True -> '#' False -> '.' runInstructions :: [Instruction] -> Grid runInstructions is = runSTUArray $ do g <- emptyMutableGrid traverse (followInstruction g) is return g emptyMutableGrid :: ST s (MutableGrid s) emptyMutableGrid = newArray ((0, 0), (49, 5)) False followInstruction :: MutableGrid s -> Instruction -> ST s () followInstruction g = \case Rect x y -> do let coords = [(a, b) | a <- [0..x-1], b <- [0..y-1]] traverse_ (\c -> writeArray g c True) coords RotateRow r amount -> do let rowCoords = [(x, r) | x <- [0..49]] row <- traverse (readArray g) rowCoords let rowCoords' = drop amount (cycle rowCoords) let writes = zip rowCoords' row traverse_ (\(i, e) -> writeArray g i e) writes RotateCol c amount -> do let colCoords = [(c, y) | y <- [0..5]] col <- traverse (readArray g) colCoords let colCoords' = drop amount (cycle colCoords) let writes = zip colCoords' col traverse_ (\(i, e) -> writeArray g i e) writes parseDay08 :: Text -> [Instruction] parseDay08 t = is where Right is = parse instructionsP "" t instructionsP :: Parser [Instruction] instructionsP = instructionP `sepBy` eol instructionP = rectP <|> rotateRowP <|> rotateColP rectP = do try $ string "rect " x <- numP char 'x' y <- numP return $ Rect x y rotateRowP = do try $ string "rotate row y=" r <- numP string " by " amount <- numP return $ RotateRow r amount rotateColP = do try $ string "rotate column x=" c <- numP string " by " amount <- numP return $ RotateCol c amount numP = read <$> some digitChar
patrickherrmann/advent2016
src/Day08.hs
bsd-3-clause
2,476
0
17
618
946
482
464
-1
-1
{-# LANGUAGE OverloadedStrings #-} import System.IO import Network.Starling import Network import Data.ByteString.Lazy.Char8() import qualified Data.ByteString.Lazy as BS import Control.Concurrent openUnix :: String -> IO Connection openUnix socket = do h <- connectTo socket $ UnixSocket socket hSetBuffering h NoBuffering open h forkExec :: IO a -> IO (IO a) forkExec k = do result <- newEmptyMVar _ <- forkIO $ k >>= putMVar result return (takeMVar result) updateFn :: Value -> IO (Maybe Value) updateFn val = do threadDelay $ 5 * floor 10e4 -- pause! return Nothing -- return . return $ "updated:" `BS.append` val -- Test that should cause the update to fail, -- as the update function has a thread-delay in it. -- While we're in the middle of the update we change -- the value of the key. testUpdate :: Connection -> IO () testUpdate con = do _ <- delete con "key" putStrLn "Deleted key" set con "key" "value" putStrLn "Set 'key' to 'value'" updateResSus <- forkExec $ update con "key" updateFn putStrLn "forked update of 'key', waiting for a bit..." threadDelay $ floor 10e4 set con "key" "value2" putStrLn "set 'value2'" result <- get con "key" putStr "Get: " print result putStrLn "Waiting for update ..." result <- updateResSus putStr "Update result: " print result result <- get con "key" putStr "Get: " print result
silkapp/starling
Debug.hs
bsd-3-clause
1,411
0
9
305
387
176
211
45
1
-- Copyright : Isaac Jones 2003-2004 {- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} -- | ComponentLocalBuildInfo for Cabal <= 1.16 module CabalVersions.Cabal16 ( ComponentLocalBuildInfo , componentPackageDeps ) where import Distribution.Package (InstalledPackageId, PackageIdentifier) -- From Cabal <= 1.16 data ComponentLocalBuildInfo = ComponentLocalBuildInfo { componentPackageDeps :: [(InstalledPackageId, PackageIdentifier)] } deriving (Read, Show)
imeckler/mote
CabalVersions/Cabal16.hs
bsd-3-clause
1,923
0
10
339
66
42
24
7
0
{-# LANGUAGE OverloadedStrings, PatternGuards #-} -- | Shell expansions. module Language.Bash.Expand ( braceExpand , TildePrefix(..) , tildePrefix , splitWord ) where import Control.Applicative import Control.Monad import Data.Char import Data.Traversable import Text.Parsec.Combinator hiding (optional, manyTill) import Text.Parsec.Prim hiding ((<|>), many, token) import Text.Parsec.String () import Text.PrettyPrint hiding (char) import Language.Bash.Pretty import Language.Bash.Word hiding (prefix) -- | A parser over words. type Parser = Parsec Word () infixl 3 </> -- | Backtracking choice. (</>) :: ParsecT s u m a -> ParsecT s u m a -> ParsecT s u m a p </> q = try p <|> q -- | Run a 'Parser', failing on a parse error. parseUnsafe :: String -> Parser a -> Word -> a parseUnsafe f p w = case parse p (prettyText w) w of Left e -> error $ "Language.Bash.Expand." ++ f ++ ": " ++ show e Right a -> a -- | Parse a general token. token :: (Span -> Maybe a) -> Parser a token = tokenPrim (const "") (\pos _ _ -> pos) -- | Parse an unquoted character satisfying a predicate. satisfy :: (Char -> Bool) -> Parser Span satisfy p = token $ \t -> case t of Char c | p c -> Just t _ -> Nothing -- | Parse an unquoted character satisfying a predicate. satisfy' :: (Char -> Bool) -> Parser Char satisfy' p = token $ \t -> case t of Char c | p c -> Just c _ -> Nothing -- | Parse a span that is not an unquoted character satisfying a predicate. except :: (Char -> Bool) -> Parser Span except p = token $ \t -> case t of Char c | p c -> Nothing _ -> Just t -- | Parse an unquoted character. char :: Char -> Parser Span char c = token $ \t -> case t of Char d | c == d -> Just t _ -> Nothing -- | Parse an unquoted string. string :: String -> Parser Word string = traverse char -- | Parse one of the given characters. oneOf :: [Char] -> Parser Span oneOf cs = satisfy (`elem` cs) -- | Parse anything but a quoted character. noneOf :: [Char] -> Parser Span noneOf cs = except (`elem` cs) -- | Read a number. readNumber :: MonadPlus m => String -> m Int readNumber s = case reads (dropPlus s) of [(n, "")] -> return n _ -> mzero where dropPlus ('+':t) = t dropPlus t = t -- | Read a letter. readAlpha :: MonadPlus m => String -> m Char readAlpha [c] | isAlpha c = return c readAlpha _ = mzero -- | Create a list from a start value, an end value, and an increment. enum :: (Ord a, Enum a) => a -> a -> Maybe Int -> [a] enum x y inc = map toEnum [fromEnum x, fromEnum x + step .. fromEnum y] where step = case inc of Nothing | y > x -> 1 | otherwise -> 1 Just i -> i -- | Brace expand a word. braceExpand :: Word -> [Word] braceExpand = parseUnsafe "braceExpand" start where prefix a bs = map (a ++) bs cross as bs = [a ++ b | a <- as, b <- bs] -- A beginning empty brace is ignored. start = prefix <$> string "{}" <*> expr "" </> expr "" expr delims = foldr ($) [""] <$> many (exprPart delims) exprPart delims = cross <$ char '{' <*> brace delims <* char '}' </> prefix <$> emptyBrace </> prefix . (:[]) <$> noneOf delims brace delims = concat <$> braceParts delims </> sequenceExpand </> map (\s -> "{" ++ s ++ "}") <$> expr ",}" -- The first part of the outermost brace expression is not delimited by -- a close brace. braceParts delims = (:) <$> expr (if ',' `elem` delims then ",}" else ",") <* char ',' <*> expr ",}" `sepBy1` char ',' emptyBrace = do a <- token $ \t -> case t of Char c | c `elem` ws -> Just t Escape c | c `elem` ws -> Just t _ -> Nothing b <- char '{' c <- char '}' <|> oneOf ws return [a, b, c] where ws = " \t\r\n" sequenceExpand = do a <- sequencePart b <- string ".." *> sequencePart c <- optional (string ".." *> sequencePart) inc <- traverse readNumber c map fromString <$> (numExpand a b inc <|> charExpand a b inc) where sequencePart = many1 (satisfy' isAlphaNum) charExpand a b inc = do x <- readAlpha a y <- readAlpha b return . map (:[]) $ enum x y inc numExpand a b inc = do x <- readNumber a y <- readNumber b return . map showPadded $ enum x y inc where width = max (length a) (length b) isPadded ('-':'0':_:_) = True isPadded ('0':_:_) = True isPadded _ = False showPadded = if isPadded a || isPadded b then pad width else show pad w n | n < 0 = '-' : pad (w - 1) (negate n) | otherwise = replicate (w - length s) '0' ++ s where s = show n -- | A tilde prefix. data TildePrefix = Home -- ^ @~/foo@ | UserHome String -- ^ @~fred/foo@ | PWD -- ^ @~+/foo@ | OldPWD -- ^ @~-/foo@ | Dirs Int -- ^ @~N@, @~+N@, @~-N@ deriving (Eq, Read, Show) instance Pretty TildePrefix where pretty Home = "~" pretty (UserHome s) = "~" <> text s pretty PWD = "~+" pretty OldPWD = "~-" pretty (Dirs n) = "~" <> int n -- | Strip the tilde prefix of a word, if any. tildePrefix :: Word -> Maybe (TildePrefix, Word) tildePrefix w = case parseUnsafe "tildePrefix" split w of ('~':s, w') -> Just (readPrefix s, w') _ -> Nothing where split = (,) <$> many (satisfy' (/= '/')) <*> getInput readPrefix s | s == "" = Home | s == "+" = PWD | s == "-" = OldPWD | Just n <- readNumber s = Dirs n | otherwise = UserHome s -- | Split a word on delimiters. splitWord :: [Char] -> Word -> [Word] splitWord ifs = parseUnsafe "splitWord" $ ifsep *> many (word <* ifsep) where ifsep = many (oneOf ifs) word = many1 (noneOf ifs)
jfoutz/language-bash
src/Language/Bash/Expand.hs
bsd-3-clause
6,221
0
18
2,071
2,159
1,096
1,063
140
7
{-# LANGUAGE NegativeLiterals #-} {-# LANGUAGE FlexibleContexts #-} module Filler(Filler, fillerSimulatorInstance, fillerNeuralInstance) where import Brain import Convenience import Minimizer import Simulator import Graphics.Gloss type Updater a = [Vec a] -> Vec a -> [Vec a] data Filler a = Filler [Vec a] (Vec a, a) (Updater a) fillerSimulatorInstance :: RealFloat a => Simulator (Filler a) a fillerSimulatorInstance = Simulator simRender simStep simCost mainState where simRender (Filler (points, goal, _)) = points &> (\p -> circleSolid 8 & vecTranslate p & color white) & (:) (circle () & vecTranslate (computeGoal goal) & color red) & pictures where vecTranslate (Vec (x,y)) = translate (realToFrac x) (realToFrac y) simStep (Filler points goal updater) = Filler (zipWith (+) points vecs) goal updater where vecs = updater points goal simCost (Filler points goal _) = points &> distsq goal & sum mainState = randFillers (100,100) (applyBeforeBox bronx neuralUpdater) 114678 randFillers :: RealFloat a => (a,a) -> Updater a -> a -> Filler a randFillers numFillersRange updater seed = Filler points (randGoal,0) updater where range = (-500,500) randGoal = Vec (pseudoRand range seed, pseudoRand range (seed+1)) numFillers = pseudoRand numFillersRange (seed+2) & floor points = zipWith (curry Vec) (pseudoRands range (seed+3)) (pseudoRands range (seed+4)) & take numFillers myUpdater points goal = points &> (\p -> (goal - p)/(dist goal p & fromScalar)) neuralUpdater :: (Num a) => Brain a 4 2 w -> Weights w a -> Updater a neuralUpdater (Brain feed) weights points goal = points &> (\p -> vecToSized (p,goal) & feed weights & sizedToVec) where vecToSized :: (Vec a,Vec a) -> Sized 4 a vecToSized (Vec (a,b), Vec (c,d)) = Sized [a,b,c,d] sizedToVec :: Num a => Sized 2 a -> Vec a sizedToVec (Sized [a,b]) = Vec (10*a, 10*b) fillerNeuralInstance :: RealFloat a => NeuralSim (Filler a) a _ _ _ _ fillerNeuralInstance = NeuralSim fillerSimulatorInstance currentBox randTrainingState neuralStep where currentBox@(brain,_,_) = bronx neuralStep (Filler (a,b,_)) weights = _simStep fillerSimulatorInstance (Filler a b (neuralUpdater brain weights)) randTrainingState seed weights = randFillers (10,10) (neuralUpdater brain weights) (seed+1)
bmabsout/neural-swarm
src/Filler.hs
bsd-3-clause
2,606
0
15
703
980
513
467
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 This module converts Template Haskell syntax into HsSyn -} {-# LANGUAGE CPP #-} module ETA.HsSyn.Convert( convertToHsExpr, convertToPat, convertToHsDecls, convertToHsType, thRdrNameGuesses ) where import ETA.HsSyn.HsSyn as Hs import ETA.HsSyn.HsTypes ( mkHsForAllTy ) import qualified ETA.Types.Class as Class import ETA.BasicTypes.RdrName import qualified ETA.BasicTypes.Name as Name import ETA.BasicTypes.Module import ETA.Parser.RdrHsSyn import qualified ETA.BasicTypes.OccName as OccName import ETA.BasicTypes.OccName import ETA.BasicTypes.SrcLoc import ETA.Types.Type import qualified ETA.Types.Coercion as Coercion( Role(..) ) import ETA.Prelude.TysWiredIn import ETA.Prelude.TysPrim (eqPrimTyCon) import ETA.BasicTypes.BasicTypes as Hs import ETA.Prelude.ForeignCall import ETA.BasicTypes.Unique import ETA.Main.ErrUtils import ETA.Utils.Bag import ETA.BasicTypes.Lexeme import ETA.Utils.Util import ETA.Utils.FastString import ETA.Utils.Outputable import qualified Data.ByteString as BS import Control.Monad( unless, liftM, ap ) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative (Applicative(..)) #endif import Data.Char ( chr ) import Data.Word ( Word8 ) import Data.Maybe( catMaybes ) import Language.Haskell.TH as TH hiding (sigP) import Language.Haskell.TH.Syntax as TH ------------------------------------------------------------------- -- The external interface convertToHsDecls :: SrcSpan -> [TH.Dec] -> Either MsgDoc [LHsDecl RdrName] convertToHsDecls loc ds = initCvt loc (fmap catMaybes (mapM cvt_dec ds)) where cvt_dec d = wrapMsg "declaration" d (cvtDec d) convertToHsExpr :: SrcSpan -> TH.Exp -> Either MsgDoc (LHsExpr RdrName) convertToHsExpr loc e = initCvt loc $ wrapMsg "expression" e $ cvtl e convertToPat :: SrcSpan -> TH.Pat -> Either MsgDoc (LPat RdrName) convertToPat loc p = initCvt loc $ wrapMsg "pattern" p $ cvtPat p convertToHsType :: SrcSpan -> TH.Type -> Either MsgDoc (LHsType RdrName) convertToHsType loc t = initCvt loc $ wrapMsg "type" t $ cvtType t ------------------------------------------------------------------- newtype CvtM a = CvtM { unCvtM :: SrcSpan -> Either MsgDoc (SrcSpan, a) } -- Push down the source location; -- Can fail, with a single error message -- NB: If the conversion succeeds with (Right x), there should -- be no exception values hiding in x -- Reason: so a (head []) in TH code doesn't subsequently -- make GHC crash when it tries to walk the generated tree -- Use the loc everywhere, for lack of anything better -- In particular, we want it on binding locations, so that variables bound in -- the spliced-in declarations get a location that at least relates to the splice point instance Functor CvtM where fmap = liftM instance Applicative CvtM where pure = return (<*>) = ap instance Monad CvtM where return x = CvtM $ \loc -> Right (loc,x) (CvtM m) >>= k = CvtM $ \loc -> case m loc of Left err -> Left err Right (loc',v) -> unCvtM (k v) loc' initCvt :: SrcSpan -> CvtM a -> Either MsgDoc a initCvt loc (CvtM m) = fmap snd (m loc) force :: a -> CvtM () force a = a `seq` return () failWith :: MsgDoc -> CvtM a failWith m = CvtM (\_ -> Left m) getL :: CvtM SrcSpan getL = CvtM (\loc -> Right (loc,loc)) setL :: SrcSpan -> CvtM () setL loc = CvtM (\_ -> Right (loc, ())) returnL :: a -> CvtM (Located a) returnL x = CvtM (\loc -> Right (loc, L loc x)) returnJustL :: a -> CvtM (Maybe (Located a)) returnJustL = fmap Just . returnL wrapParL :: (Located a -> a) -> a -> CvtM a wrapParL add_par x = CvtM (\loc -> Right (loc, add_par (L loc x))) wrapMsg :: (Show a, TH.Ppr a) => String -> a -> CvtM b -> CvtM b -- E.g wrapMsg "declaration" dec thing wrapMsg what item (CvtM m) = CvtM (\loc -> case m loc of Left err -> Left (err $$ getPprStyle msg) Right v -> Right v) where -- Show the item in pretty syntax normally, -- but with all its constructors if you say -dppr-debug msg sty = hang (ptext (sLit "When splicing a TH") <+> text what <> colon) 2 (if debugStyle sty then text (show item) else text (pprint item)) wrapL :: CvtM a -> CvtM (Located a) wrapL (CvtM m) = CvtM (\loc -> case m loc of Left err -> Left err Right (loc',v) -> Right (loc',L loc v)) ------------------------------------------------------------------- cvtDecs :: [TH.Dec] -> CvtM [LHsDecl RdrName] cvtDecs = fmap catMaybes . mapM cvtDec cvtDec :: TH.Dec -> CvtM (Maybe (LHsDecl RdrName)) cvtDec (TH.ValD pat body ds) | TH.VarP s <- pat = do { s' <- vNameL s ; cl' <- cvtClause (Clause [] body ds) ; returnJustL $ Hs.ValD $ mkFunBind s' [cl'] } | otherwise = do { pat' <- cvtPat pat ; body' <- cvtGuard body ; ds' <- cvtLocalDecs (ptext (sLit "a where clause")) ds ; returnJustL $ Hs.ValD $ PatBind { pat_lhs = pat', pat_rhs = GRHSs body' ds' , pat_rhs_ty = placeHolderType, bind_fvs = placeHolderNames , pat_ticks = ([],[]) } } cvtDec (TH.FunD nm cls) | null cls = failWith (ptext (sLit "Function binding for") <+> quotes (text (TH.pprint nm)) <+> ptext (sLit "has no equations")) | otherwise = do { nm' <- vNameL nm ; cls' <- mapM cvtClause cls ; returnJustL $ Hs.ValD $ mkFunBind nm' cls' } cvtDec (TH.SigD nm typ) = do { nm' <- vNameL nm ; ty' <- cvtType typ ; returnJustL $ Hs.SigD (TypeSig [nm'] ty' PlaceHolder) } cvtDec (TH.InfixD fx nm) -- fixity signatures are allowed for variables, constructors, and types -- the renamer automatically looks for types during renaming, even when -- the RdrName says it's a variable or a constructor. So, just assume -- it's a variable or constructor and proceed. = do { nm' <- vcNameL nm ; returnJustL (Hs.SigD (FixSig (FixitySig [nm'] (cvtFixity fx)))) } cvtDec (PragmaD prag) = cvtPragmaD prag cvtDec (TySynD tc tvs rhs) = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs ; rhs' <- cvtType rhs ; returnJustL $ TyClD $ SynDecl { tcdLName = tc' , tcdTyVars = tvs', tcdFVs = placeHolderNames , tcdRhs = rhs' } } cvtDec (DataD ctxt tc tvs constrs derivs) = do { (ctxt', tc', tvs') <- cvt_tycl_hdr ctxt tc tvs ; cons' <- mapM cvtConstr constrs ; derivs' <- cvtDerivs derivs ; let defn = HsDataDefn { dd_ND = DataType, dd_cType = Nothing , dd_ctxt = ctxt' , dd_kindSig = Nothing , dd_cons = cons', dd_derivs = derivs' } ; returnJustL $ TyClD (DataDecl { tcdLName = tc', tcdTyVars = tvs' , tcdDataDefn = defn , tcdFVs = placeHolderNames }) } cvtDec (NewtypeD ctxt tc tvs constr derivs) = do { (ctxt', tc', tvs') <- cvt_tycl_hdr ctxt tc tvs ; con' <- cvtConstr constr ; derivs' <- cvtDerivs derivs ; let defn = HsDataDefn { dd_ND = NewType, dd_cType = Nothing , dd_ctxt = ctxt' , dd_kindSig = Nothing , dd_cons = [con'] , dd_derivs = derivs' } ; returnJustL $ TyClD (DataDecl { tcdLName = tc', tcdTyVars = tvs' , tcdDataDefn = defn , tcdFVs = placeHolderNames }) } cvtDec (ClassD ctxt cl tvs fds decs) = do { (cxt', tc', tvs') <- cvt_tycl_hdr ctxt cl tvs ; fds' <- mapM cvt_fundep fds ; (binds', sigs', fams', ats', adts') <- cvt_ci_decs (ptext (sLit "a class declaration")) decs ; unless (null adts') (failWith $ (ptext (sLit "Default data instance declarations are not allowed:")) $$ (Outputable.ppr adts')) ; at_defs <- mapM cvt_at_def ats' ; returnJustL $ TyClD $ ClassDecl { tcdCtxt = cxt', tcdLName = tc', tcdTyVars = tvs' , tcdFDs = fds', tcdSigs = sigs', tcdMeths = binds' , tcdATs = fams', tcdATDefs = at_defs, tcdDocs = [] , tcdFVs = placeHolderNames } -- no docs in TH ^^ } where cvt_at_def :: LTyFamInstDecl RdrName -> CvtM (LTyFamDefltEqn RdrName) -- Very similar to what happens in RdrHsSyn.mkClassDecl cvt_at_def decl = case RdrHsSyn.mkATDefault decl of Right def -> return def Left (_, msg) -> failWith msg cvtDec (InstanceD ctxt ty decs) = do { let doc = ptext (sLit "an instance declaration") ; (binds', sigs', fams', ats', adts') <- cvt_ci_decs doc decs ; unless (null fams') (failWith (mkBadDecMsg doc fams')) ; ctxt' <- cvtContext ctxt ; L loc ty' <- cvtType ty ; let inst_ty' = L loc $ mkHsForAllTy Implicit [] ctxt' $ L loc ty' ; returnJustL $ InstD $ ClsInstD $ ClsInstDecl inst_ty' binds' sigs' ats' adts' Nothing } cvtDec (ForeignD ford) = do { ford' <- cvtForD ford ; returnJustL $ ForD ford' } cvtDec (FamilyD flav tc tvs kind) = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs ; kind' <- cvtMaybeKind kind ; returnJustL $ TyClD $ FamDecl $ FamilyDecl (cvtFamFlavour flav) tc' tvs' kind' } where cvtFamFlavour TypeFam = OpenTypeFamily cvtFamFlavour DataFam = DataFamily cvtDec (DataInstD ctxt tc tys constrs derivs) = do { (ctxt', tc', typats') <- cvt_tyinst_hdr ctxt tc tys ; cons' <- mapM cvtConstr constrs ; derivs' <- cvtDerivs derivs ; let defn = HsDataDefn { dd_ND = DataType, dd_cType = Nothing , dd_ctxt = ctxt' , dd_kindSig = Nothing , dd_cons = cons', dd_derivs = derivs' } ; returnJustL $ InstD $ DataFamInstD { dfid_inst = DataFamInstDecl { dfid_tycon = tc', dfid_pats = typats' , dfid_defn = defn , dfid_fvs = placeHolderNames } }} cvtDec (NewtypeInstD ctxt tc tys constr derivs) = do { (ctxt', tc', typats') <- cvt_tyinst_hdr ctxt tc tys ; con' <- cvtConstr constr ; derivs' <- cvtDerivs derivs ; let defn = HsDataDefn { dd_ND = NewType, dd_cType = Nothing , dd_ctxt = ctxt' , dd_kindSig = Nothing , dd_cons = [con'], dd_derivs = derivs' } ; returnJustL $ InstD $ DataFamInstD { dfid_inst = DataFamInstDecl { dfid_tycon = tc', dfid_pats = typats' , dfid_defn = defn , dfid_fvs = placeHolderNames } }} cvtDec (TySynInstD tc eqn) = do { tc' <- tconNameL tc ; eqn' <- cvtTySynEqn tc' eqn ; returnJustL $ InstD $ TyFamInstD { tfid_inst = TyFamInstDecl { tfid_eqn = eqn' , tfid_fvs = placeHolderNames } } } cvtDec (ClosedTypeFamilyD tc tyvars mkind eqns) | not $ null eqns = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tyvars ; mkind' <- cvtMaybeKind mkind ; eqns' <- mapM (cvtTySynEqn tc') eqns ; returnJustL $ TyClD $ FamDecl $ FamilyDecl (ClosedTypeFamily eqns') tc' tvs' mkind' } | otherwise = failWith (ptext (sLit "Illegal empty closed type family")) cvtDec (TH.RoleAnnotD tc roles) = do { tc' <- tconNameL tc ; let roles' = map (noLoc . cvtRole) roles ; returnJustL $ Hs.RoleAnnotD (RoleAnnotDecl tc' roles') } cvtDec (TH.StandaloneDerivD cxt ty) = do { cxt' <- cvtContext cxt ; L loc ty' <- cvtType ty ; let inst_ty' = L loc $ mkHsForAllTy Implicit [] cxt' $ L loc ty' ; returnJustL $ DerivD $ DerivDecl { deriv_type = inst_ty', deriv_overlap_mode = Nothing } } cvtDec (TH.DefaultSigD nm typ) = do { nm' <- vNameL nm ; ty' <- cvtType typ ; returnJustL $ Hs.SigD $ GenericSig [nm'] ty' } ---------------- cvtTySynEqn :: Located RdrName -> TySynEqn -> CvtM (LTyFamInstEqn RdrName) cvtTySynEqn tc (TySynEqn lhs rhs) = do { lhs' <- mapM cvtType lhs ; rhs' <- cvtType rhs ; returnL $ TyFamEqn { tfe_tycon = tc , tfe_pats = mkHsWithBndrs lhs' , tfe_rhs = rhs' } } ---------------- cvt_ci_decs :: MsgDoc -> [TH.Dec] -> CvtM (LHsBinds RdrName, [LSig RdrName], [LFamilyDecl RdrName], [LTyFamInstDecl RdrName], [LDataFamInstDecl RdrName]) -- Convert the declarations inside a class or instance decl -- ie signatures, bindings, and associated types cvt_ci_decs doc decs = do { decs' <- cvtDecs decs ; let (ats', bind_sig_decs') = partitionWith is_tyfam_inst decs' ; let (adts', no_ats') = partitionWith is_datafam_inst bind_sig_decs' ; let (sigs', prob_binds') = partitionWith is_sig no_ats' ; let (binds', prob_fams') = partitionWith is_bind prob_binds' ; let (fams', bads) = partitionWith is_fam_decl prob_fams' ; unless (null bads) (failWith (mkBadDecMsg doc bads)) --We use FromSource as the origin of the bind -- because the TH declaration is user-written ; return (listToBag binds', sigs', fams', ats', adts') } ---------------- cvt_tycl_hdr :: TH.Cxt -> TH.Name -> [TH.TyVarBndr] -> CvtM ( LHsContext RdrName , Located RdrName , LHsTyVarBndrs RdrName) cvt_tycl_hdr cxt tc tvs = do { cxt' <- cvtContext cxt ; tc' <- tconNameL tc ; tvs' <- cvtTvs tvs ; return (cxt', tc', tvs') } cvt_tyinst_hdr :: TH.Cxt -> TH.Name -> [TH.Type] -> CvtM ( LHsContext RdrName , Located RdrName , HsWithBndrs RdrName [LHsType RdrName]) cvt_tyinst_hdr cxt tc tys = do { cxt' <- cvtContext cxt ; tc' <- tconNameL tc ; tys' <- mapM cvtType tys ; return (cxt', tc', mkHsWithBndrs tys') } ------------------------------------------------------------------- -- Partitioning declarations ------------------------------------------------------------------- is_fam_decl :: LHsDecl RdrName -> Either (LFamilyDecl RdrName) (LHsDecl RdrName) is_fam_decl (L loc (TyClD (FamDecl { tcdFam = d }))) = Left (L loc d) is_fam_decl decl = Right decl is_tyfam_inst :: LHsDecl RdrName -> Either (LTyFamInstDecl RdrName) (LHsDecl RdrName) is_tyfam_inst (L loc (Hs.InstD (TyFamInstD { tfid_inst = d }))) = Left (L loc d) is_tyfam_inst decl = Right decl is_datafam_inst :: LHsDecl RdrName -> Either (LDataFamInstDecl RdrName) (LHsDecl RdrName) is_datafam_inst (L loc (Hs.InstD (DataFamInstD { dfid_inst = d }))) = Left (L loc d) is_datafam_inst decl = Right decl is_sig :: LHsDecl RdrName -> Either (LSig RdrName) (LHsDecl RdrName) is_sig (L loc (Hs.SigD sig)) = Left (L loc sig) is_sig decl = Right decl is_bind :: LHsDecl RdrName -> Either (LHsBind RdrName) (LHsDecl RdrName) is_bind (L loc (Hs.ValD bind)) = Left (L loc bind) is_bind decl = Right decl mkBadDecMsg :: Outputable a => MsgDoc -> [a] -> MsgDoc mkBadDecMsg doc bads = sep [ ptext (sLit "Illegal declaration(s) in") <+> doc <> colon , nest 2 (vcat (map Outputable.ppr bads)) ] --------------------------------------------------- -- Data types -- Can't handle GADTs yet --------------------------------------------------- cvtConstr :: TH.Con -> CvtM (LConDecl RdrName) cvtConstr (NormalC c strtys) = do { c' <- cNameL c ; cxt' <- returnL [] ; tys' <- mapM cvt_arg strtys ; returnL $ mkSimpleConDecl c' noExistentials cxt' (PrefixCon tys') } cvtConstr (RecC c varstrtys) = do { c' <- cNameL c ; cxt' <- returnL [] ; args' <- mapM cvt_id_arg varstrtys ; returnL $ mkSimpleConDecl c' noExistentials cxt' (RecCon (noLoc args')) } cvtConstr (InfixC st1 c st2) = do { c' <- cNameL c ; cxt' <- returnL [] ; st1' <- cvt_arg st1 ; st2' <- cvt_arg st2 ; returnL $ mkSimpleConDecl c' noExistentials cxt' (InfixCon st1' st2') } cvtConstr (ForallC tvs ctxt con) = do { tvs' <- cvtTvs tvs ; L loc ctxt' <- cvtContext ctxt ; L _ con' <- cvtConstr con ; returnL $ con' { con_qvars = mkHsQTvs (hsQTvBndrs tvs' ++ hsQTvBndrs (con_qvars con')) , con_cxt = L loc (ctxt' ++ (unLoc $ con_cxt con')) } } cvt_arg :: (TH.Strict, TH.Type) -> CvtM (LHsType RdrName) cvt_arg (NotStrict, ty) = cvtType ty cvt_arg (IsStrict, ty) = do { ty' <- cvtType ty ; returnL $ HsBangTy (HsSrcBang Nothing Nothing True) ty' } cvt_arg (Unpacked, ty) = do { ty' <- cvtType ty ; returnL $ HsBangTy (HsSrcBang Nothing (Just True) True) ty' } cvt_id_arg :: (TH.Name, TH.Strict, TH.Type) -> CvtM (LConDeclField RdrName) cvt_id_arg (i, str, ty) = do { i' <- vNameL i ; ty' <- cvt_arg (str,ty) ; return $ noLoc (ConDeclField { cd_fld_names = [i'] , cd_fld_type = ty' , cd_fld_doc = Nothing}) } cvtDerivs :: [TH.Name] -> CvtM (Maybe (Located [LHsType RdrName])) cvtDerivs [] = return Nothing cvtDerivs cs = do { cs' <- mapM cvt_one cs ; return (Just (noLoc cs')) } where cvt_one c = do { c' <- tconName c ; returnL $ HsTyVar c' } cvt_fundep :: FunDep -> CvtM (Located (Class.FunDep (Located RdrName))) cvt_fundep (FunDep xs ys) = do { xs' <- mapM tName xs ; ys' <- mapM tName ys ; returnL (map noLoc xs', map noLoc ys') } noExistentials :: [LHsTyVarBndr RdrName] noExistentials = [] ------------------------------------------ -- Foreign declarations ------------------------------------------ cvtForD :: Foreign -> CvtM (ForeignDecl RdrName) cvtForD (ImportF callconv safety from nm ty) | callconv == TH.Prim || callconv == TH.JavaScript = mk_imp (CImport (noLoc (cvt_conv callconv)) (noLoc safety') Nothing (CFunction (StaticTarget (mkFastString from) Nothing True)) (noLoc from)) | Just impspec <- parseCImport (noLoc (cvt_conv callconv)) (noLoc safety') (mkFastString (TH.nameBase nm)) from (noLoc from) = mk_imp impspec | otherwise = failWith $ text (show from) <+> ptext (sLit "is not a valid ccall impent") where mk_imp impspec = do { nm' <- vNameL nm ; ty' <- cvtType ty ; return (ForeignImport nm' ty' noForeignImportCoercionYet impspec) } safety' = case safety of Unsafe -> PlayRisky Safe -> PlaySafe Interruptible -> PlayInterruptible cvtForD (ExportF callconv as nm ty) = do { nm' <- vNameL nm ; ty' <- cvtType ty ; let e = CExport (noLoc (CExportStatic (mkFastString as) (cvt_conv callconv))) (noLoc as) ; return $ ForeignExport nm' ty' noForeignExportCoercionYet e } cvt_conv :: TH.Callconv -> CCallConv cvt_conv TH.CCall = CCallConv cvt_conv TH.StdCall = StdCallConv cvt_conv TH.CApi = CApiConv cvt_conv TH.Prim = PrimCallConv cvt_conv TH.JavaScript = JavaScriptCallConv ------------------------------------------ -- Pragmas ------------------------------------------ cvtPragmaD :: Pragma -> CvtM (Maybe (LHsDecl RdrName)) cvtPragmaD (InlineP nm inline rm phases) = do { nm' <- vNameL nm ; let dflt = dfltActivation inline ; let ip = InlinePragma { inl_src = "{-# INLINE" , inl_inline = cvtInline inline , inl_rule = cvtRuleMatch rm , inl_act = cvtPhases phases dflt , inl_sat = Nothing } ; returnJustL $ Hs.SigD $ InlineSig nm' ip } cvtPragmaD (SpecialiseP nm ty inline phases) = do { nm' <- vNameL nm ; ty' <- cvtType ty ; let (inline', dflt) = case inline of Just inline1 -> (cvtInline inline1, dfltActivation inline1) Nothing -> (EmptyInlineSpec, AlwaysActive) ; let ip = InlinePragma { inl_src = "{-# INLINE" , inl_inline = inline' , inl_rule = Hs.FunLike , inl_act = cvtPhases phases dflt , inl_sat = Nothing } ; returnJustL $ Hs.SigD $ SpecSig nm' [ty'] ip } cvtPragmaD (SpecialiseInstP ty) = do { ty' <- cvtType ty ; returnJustL $ Hs.SigD $ SpecInstSig "{-# SPECIALISE" ty' } cvtPragmaD (RuleP nm bndrs lhs rhs phases) = do { let nm' = mkFastString nm ; let act = cvtPhases phases AlwaysActive ; bndrs' <- mapM cvtRuleBndr bndrs ; lhs' <- cvtl lhs ; rhs' <- cvtl rhs ; returnJustL $ Hs.RuleD $ HsRules "{-# RULES" [noLoc $ HsRule (noLoc nm') act bndrs' lhs' placeHolderNames rhs' placeHolderNames] } cvtPragmaD (AnnP target exp) = do { exp' <- cvtl exp ; target' <- case target of ModuleAnnotation -> return ModuleAnnProvenance TypeAnnotation n -> do n' <- tconName n return (TypeAnnProvenance (noLoc n')) ValueAnnotation n -> do n' <- vcName n return (ValueAnnProvenance (noLoc n')) ; returnJustL $ Hs.AnnD $ HsAnnotation "{-# ANN" target' exp' } cvtPragmaD (LineP line file) = do { setL (srcLocSpan (mkSrcLoc (fsLit file) line 1)) ; return Nothing } dfltActivation :: TH.Inline -> Activation dfltActivation TH.NoInline = NeverActive dfltActivation _ = AlwaysActive cvtInline :: TH.Inline -> Hs.InlineSpec cvtInline TH.NoInline = Hs.NoInline cvtInline TH.Inline = Hs.Inline cvtInline TH.Inlinable = Hs.Inlinable cvtRuleMatch :: TH.RuleMatch -> RuleMatchInfo cvtRuleMatch TH.ConLike = Hs.ConLike cvtRuleMatch TH.FunLike = Hs.FunLike cvtPhases :: TH.Phases -> Activation -> Activation cvtPhases AllPhases dflt = dflt cvtPhases (FromPhase i) _ = ActiveAfter i cvtPhases (BeforePhase i) _ = ActiveBefore i cvtRuleBndr :: TH.RuleBndr -> CvtM (Hs.LRuleBndr RdrName) cvtRuleBndr (RuleVar n) = do { n' <- vNameL n ; return $ noLoc $ Hs.RuleBndr n' } cvtRuleBndr (TypedRuleVar n ty) = do { n' <- vNameL n ; ty' <- cvtType ty ; return $ noLoc $ Hs.RuleBndrSig n' $ mkHsWithBndrs ty' } --------------------------------------------------- -- Declarations --------------------------------------------------- cvtLocalDecs :: MsgDoc -> [TH.Dec] -> CvtM (HsLocalBinds RdrName) cvtLocalDecs doc ds | null ds = return EmptyLocalBinds | otherwise = do { ds' <- cvtDecs ds ; let (binds, prob_sigs) = partitionWith is_bind ds' ; let (sigs, bads) = partitionWith is_sig prob_sigs ; unless (null bads) (failWith (mkBadDecMsg doc bads)) ; return (HsValBinds (ValBindsIn (listToBag binds) sigs)) } cvtClause :: TH.Clause -> CvtM (Hs.LMatch RdrName (LHsExpr RdrName)) cvtClause (Clause ps body wheres) = do { ps' <- cvtPats ps ; g' <- cvtGuard body ; ds' <- cvtLocalDecs (ptext (sLit "a where clause")) wheres ; returnL $ Hs.Match Nothing ps' Nothing (GRHSs g' ds') } ------------------------------------------------------------------- -- Expressions ------------------------------------------------------------------- cvtl :: TH.Exp -> CvtM (LHsExpr RdrName) cvtl e = wrapL (cvt e) where cvt (VarE s) = do { s' <- vName s; return $ HsVar s' } cvt (ConE s) = do { s' <- cName s; return $ HsVar s' } cvt (LitE l) | overloadedLit l = do { l' <- cvtOverLit l; return $ HsOverLit l' } | otherwise = do { l' <- cvtLit l; return $ HsLit l' } cvt (AppE x y) = do { x' <- cvtl x; y' <- cvtl y; return $ HsApp x' y' } cvt (LamE ps e) = do { ps' <- cvtPats ps; e' <- cvtl e ; return $ HsLam (mkMatchGroup FromSource [mkSimpleMatch ps' e']) } cvt (LamCaseE ms) = do { ms' <- mapM cvtMatch ms ; return $ HsLamCase placeHolderType (mkMatchGroup FromSource ms') } cvt (TupE [e]) = do { e' <- cvtl e; return $ HsPar e' } -- Note [Dropping constructors] -- Singleton tuples treated like nothing (just parens) cvt (TupE es) = do { es' <- mapM cvtl es ; return $ ExplicitTuple (map (noLoc . Present) es') Boxed } cvt (UnboxedTupE es) = do { es' <- mapM cvtl es ; return $ ExplicitTuple (map (noLoc . Present) es') Unboxed } cvt (CondE x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z; ; return $ HsIf (Just noSyntaxExpr) x' y' z' } cvt (MultiIfE alts) | null alts = failWith (ptext (sLit "Multi-way if-expression with no alternatives")) | otherwise = do { alts' <- mapM cvtpair alts ; return $ HsMultiIf placeHolderType alts' } cvt (LetE ds e) = do { ds' <- cvtLocalDecs (ptext (sLit "a let expression")) ds ; e' <- cvtl e; return $ HsLet ds' e' } cvt (CaseE e ms) = do { e' <- cvtl e; ms' <- mapM cvtMatch ms ; return $ HsCase e' (mkMatchGroup FromSource ms') } cvt (DoE ss) = cvtHsDo DoExpr ss cvt (CompE ss) = cvtHsDo ListComp ss cvt (ArithSeqE dd) = do { dd' <- cvtDD dd; return $ ArithSeq noPostTcExpr Nothing dd' } cvt (ListE xs) | Just s <- allCharLs xs = do { l' <- cvtLit (StringL s); return (HsLit l') } -- Note [Converting strings] | otherwise = do { xs' <- mapM cvtl xs ; return $ ExplicitList placeHolderType Nothing xs' } -- Infix expressions cvt (InfixE (Just x) s (Just y)) = do { x' <- cvtl x; s' <- cvtl s; y' <- cvtl y ; wrapParL HsPar $ OpApp (mkLHsPar x') s' undefined (mkLHsPar y') } -- Parenthesise both arguments and result, -- to ensure this operator application does -- does not get re-associated -- See Note [Operator association] cvt (InfixE Nothing s (Just y)) = do { s' <- cvtl s; y' <- cvtl y ; wrapParL HsPar $ SectionR s' y' } -- See Note [Sections in HsSyn] in HsExpr cvt (InfixE (Just x) s Nothing ) = do { x' <- cvtl x; s' <- cvtl s ; wrapParL HsPar $ SectionL x' s' } cvt (InfixE Nothing s Nothing ) = do { s' <- cvtl s; return $ HsPar s' } -- Can I indicate this is an infix thing? -- Note [Dropping constructors] cvt (UInfixE x s y) = do { x' <- cvtl x ; let x'' = case x' of L _ (OpApp {}) -> x' _ -> mkLHsPar x' ; cvtOpApp x'' s y } -- Note [Converting UInfix] cvt (ParensE e) = do { e' <- cvtl e; return $ HsPar e' } cvt (SigE e t) = do { e' <- cvtl e; t' <- cvtType t ; return $ ExprWithTySig e' t' PlaceHolder } cvt (RecConE c flds) = do { c' <- cNameL c ; flds' <- mapM cvtFld flds ; return $ RecordCon c' noPostTcExpr (HsRecFields flds' Nothing)} cvt (RecUpdE e flds) = do { e' <- cvtl e ; flds' <- mapM cvtFld flds ; return $ RecordUpd e' (HsRecFields flds' Nothing) [] [] [] } cvt (StaticE e) = fmap HsStatic $ cvtl e {- Note [Dropping constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we drop constructors from the input (for instance, when we encounter @TupE [e]@) we must insert parentheses around the argument. Otherwise, @UInfix@ constructors in @e@ could meet @UInfix@ constructors containing the @TupE [e]@. For example: UInfixE x * (TupE [UInfixE y + z]) If we drop the singleton tuple but don't insert parentheses, the @UInfixE@s would meet and the above expression would be reassociated to OpApp (OpApp x * y) + z which we don't want. -} cvtFld :: (TH.Name, TH.Exp) -> CvtM (LHsRecField RdrName (LHsExpr RdrName)) cvtFld (v,e) = do { v' <- vNameL v; e' <- cvtl e ; return (noLoc $ HsRecField { hsRecFieldId = v', hsRecFieldArg = e' , hsRecPun = False}) } cvtDD :: Range -> CvtM (ArithSeqInfo RdrName) cvtDD (FromR x) = do { x' <- cvtl x; return $ From x' } cvtDD (FromThenR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromThen x' y' } cvtDD (FromToR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromTo x' y' } cvtDD (FromThenToR x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z; return $ FromThenTo x' y' z' } {- Note [Operator assocation] We must be quite careful about adding parens: * Infix (UInfix ...) op arg Needs parens round the first arg * Infix (Infix ...) op arg Needs parens round the first arg * UInfix (UInfix ...) op arg No parens for first arg * UInfix (Infix ...) op arg Needs parens round first arg Note [Converting UInfix] ~~~~~~~~~~~~~~~~~~~~~~~~ When converting @UInfixE@ and @UInfixP@ values, we want to readjust the trees to reflect the fixities of the underlying operators: UInfixE x * (UInfixE y + z) ---> (x * y) + z This is done by the renamer (see @mkOppAppRn@ and @mkConOppPatRn@ in RnTypes), which expects that the input will be completely left-biased. So we left-bias the trees of @UInfixP@ and @UInfixE@ that we come across. Sample input: UInfixE (UInfixE x op1 y) op2 (UInfixE z op3 w) Sample output: OpApp (OpApp (OpApp x op1 y) op2 z) op3 w The functions @cvtOpApp@ and @cvtOpAppP@ are responsible for this left-biasing. -} {- | @cvtOpApp x op y@ converts @op@ and @y@ and produces the operator application @x `op` y@. The produced tree of infix expressions will be left-biased, provided @x@ is. We can see that @cvtOpApp@ is correct as follows. The inductive hypothesis is that @cvtOpApp x op y@ is left-biased, provided @x@ is. It is clear that this holds for both branches (of @cvtOpApp@), provided we assume it holds for the recursive calls to @cvtOpApp@. When we call @cvtOpApp@ from @cvtl@, the first argument will always be left-biased since we have already run @cvtl@ on it. -} cvtOpApp :: LHsExpr RdrName -> TH.Exp -> TH.Exp -> CvtM (HsExpr RdrName) cvtOpApp x op1 (UInfixE y op2 z) = do { l <- wrapL $ cvtOpApp x op1 y ; cvtOpApp l op2 z } cvtOpApp x op y = do { op' <- cvtl op ; y' <- cvtl y ; return (OpApp x op' undefined y') } ------------------------------------- -- Do notation and statements ------------------------------------- cvtHsDo :: HsStmtContext Name.Name -> [TH.Stmt] -> CvtM (HsExpr RdrName) cvtHsDo do_or_lc stmts | null stmts = failWith (ptext (sLit "Empty stmt list in do-block")) | otherwise = do { stmts' <- cvtStmts stmts ; let Just (stmts'', last') = snocView stmts' ; last'' <- case last' of L loc (BodyStmt body _ _ _) -> return (L loc (mkLastStmt body)) _ -> failWith (bad_last last') ; return $ HsDo do_or_lc (stmts'' ++ [last'']) placeHolderType } where bad_last stmt = vcat [ ptext (sLit "Illegal last statement of") <+> pprAStmtContext do_or_lc <> colon , nest 2 $ Outputable.ppr stmt , ptext (sLit "(It should be an expression.)") ] cvtStmts :: [TH.Stmt] -> CvtM [Hs.LStmt RdrName (LHsExpr RdrName)] cvtStmts = mapM cvtStmt cvtStmt :: TH.Stmt -> CvtM (Hs.LStmt RdrName (LHsExpr RdrName)) cvtStmt (NoBindS e) = do { e' <- cvtl e; returnL $ mkBodyStmt e' } cvtStmt (TH.BindS p e) = do { p' <- cvtPat p; e' <- cvtl e; returnL $ mkBindStmt p' e' } cvtStmt (TH.LetS ds) = do { ds' <- cvtLocalDecs (ptext (sLit "a let binding")) ds ; returnL $ LetStmt ds' } cvtStmt (TH.ParS dss) = do { dss' <- mapM cvt_one dss; returnL $ ParStmt dss' noSyntaxExpr noSyntaxExpr } where cvt_one ds = do { ds' <- cvtStmts ds; return (ParStmtBlock ds' undefined noSyntaxExpr) } cvtMatch :: TH.Match -> CvtM (Hs.LMatch RdrName (LHsExpr RdrName)) cvtMatch (TH.Match p body decs) = do { p' <- cvtPat p ; g' <- cvtGuard body ; decs' <- cvtLocalDecs (ptext (sLit "a where clause")) decs ; returnL $ Hs.Match Nothing [p'] Nothing (GRHSs g' decs') } cvtGuard :: TH.Body -> CvtM [LGRHS RdrName (LHsExpr RdrName)] cvtGuard (GuardedB pairs) = mapM cvtpair pairs cvtGuard (NormalB e) = do { e' <- cvtl e; g' <- returnL $ GRHS [] e'; return [g'] } cvtpair :: (TH.Guard, TH.Exp) -> CvtM (LGRHS RdrName (LHsExpr RdrName)) cvtpair (NormalG ge,rhs) = do { ge' <- cvtl ge; rhs' <- cvtl rhs ; g' <- returnL $ mkBodyStmt ge' ; returnL $ GRHS [g'] rhs' } cvtpair (PatG gs,rhs) = do { gs' <- cvtStmts gs; rhs' <- cvtl rhs ; returnL $ GRHS gs' rhs' } cvtOverLit :: Lit -> CvtM (HsOverLit RdrName) cvtOverLit (IntegerL i) = do { force i; return $ mkHsIntegral (show i) i placeHolderType} cvtOverLit (RationalL r) = do { force r; return $ mkHsFractional (cvtFractionalLit r) placeHolderType} cvtOverLit (StringL s) = do { let { s' = mkFastString s } ; force s' ; return $ mkHsIsString s s' placeHolderType } cvtOverLit _ = panic "Convert.cvtOverLit: Unexpected overloaded literal" -- An Integer is like an (overloaded) '3' in a Haskell source program -- Similarly 3.5 for fractionals {- Note [Converting strings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we get (ListE [CharL 'x', CharL 'y']) we'd like to convert to a string literal for "xy". Of course, we might hope to get (LitE (StringL "xy")), but not always, and allCharLs fails quickly if it isn't a literal string -} allCharLs :: [TH.Exp] -> Maybe String -- Note [Converting strings] -- NB: only fire up this setup for a non-empty list, else -- there's a danger of returning "" for [] :: [Int]! allCharLs xs = case xs of LitE (CharL c) : ys -> go [c] ys _ -> Nothing where go cs [] = Just (reverse cs) go cs (LitE (CharL c) : ys) = go (c:cs) ys go _ _ = Nothing cvtLit :: Lit -> CvtM HsLit cvtLit (IntPrimL i) = do { force i; return $ HsIntPrim (show i) i } cvtLit (WordPrimL w) = do { force w; return $ HsWordPrim (show w) w } cvtLit (FloatPrimL f) = do { force f; return $ HsFloatPrim (cvtFractionalLit f) } cvtLit (DoublePrimL f) = do { force f; return $ HsDoublePrim (cvtFractionalLit f) } cvtLit (CharL c) = do { force c; return $ HsChar (show c) c } cvtLit (StringL s) = do { let { s' = mkFastString s } ; force s' ; return $ HsString s s' } cvtLit (StringPrimL s) = do { let { s' = BS.pack s } ; force s' ; return $ HsStringPrim (w8ToString s) s' } cvtLit _ = panic "Convert.cvtLit: Unexpected literal" -- cvtLit should not be called on IntegerL, RationalL -- That precondition is established right here in -- Convert.lhs, hence panic w8ToString :: [Word8] -> String w8ToString ws = map (\w -> chr (fromIntegral w)) ws cvtPats :: [TH.Pat] -> CvtM [Hs.LPat RdrName] cvtPats pats = mapM cvtPat pats cvtPat :: TH.Pat -> CvtM (Hs.LPat RdrName) cvtPat pat = wrapL (cvtp pat) cvtp :: TH.Pat -> CvtM (Hs.Pat RdrName) cvtp (TH.LitP l) | overloadedLit l = do { l' <- cvtOverLit l ; return (mkNPat (noLoc l') Nothing) } -- Not right for negative patterns; -- need to think about that! | otherwise = do { l' <- cvtLit l; return $ Hs.LitPat l' } cvtp (TH.VarP s) = do { s' <- vName s; return $ Hs.VarPat s' } cvtp (TupP [p]) = do { p' <- cvtPat p; return $ ParPat p' } -- Note [Dropping constructors] cvtp (TupP ps) = do { ps' <- cvtPats ps; return $ TuplePat ps' Boxed [] } cvtp (UnboxedTupP ps) = do { ps' <- cvtPats ps; return $ TuplePat ps' Unboxed [] } cvtp (ConP s ps) = do { s' <- cNameL s; ps' <- cvtPats ps ; return $ ConPatIn s' (PrefixCon ps') } cvtp (InfixP p1 s p2) = do { s' <- cNameL s; p1' <- cvtPat p1; p2' <- cvtPat p2 ; wrapParL ParPat $ ConPatIn s' (InfixCon (mkParPat p1') (mkParPat p2')) } -- See Note [Operator association] cvtp (UInfixP p1 s p2) = do { p1' <- cvtPat p1; cvtOpAppP p1' s p2 } -- Note [Converting UInfix] cvtp (ParensP p) = do { p' <- cvtPat p; return $ ParPat p' } cvtp (TildeP p) = do { p' <- cvtPat p; return $ LazyPat p' } cvtp (BangP p) = do { p' <- cvtPat p; return $ BangPat p' } cvtp (TH.AsP s p) = do { s' <- vNameL s; p' <- cvtPat p; return $ AsPat s' p' } cvtp TH.WildP = return $ WildPat placeHolderType cvtp (RecP c fs) = do { c' <- cNameL c; fs' <- mapM cvtPatFld fs ; return $ ConPatIn c' $ Hs.RecCon (HsRecFields fs' Nothing) } cvtp (ListP ps) = do { ps' <- cvtPats ps ; return $ ListPat ps' placeHolderType Nothing } cvtp (SigP p t) = do { p' <- cvtPat p; t' <- cvtType t ; return $ SigPatIn p' (mkHsWithBndrs t') } cvtp (ViewP e p) = do { e' <- cvtl e; p' <- cvtPat p ; return $ ViewPat e' p' placeHolderType } cvtPatFld :: (TH.Name, TH.Pat) -> CvtM (LHsRecField RdrName (LPat RdrName)) cvtPatFld (s,p) = do { s' <- vNameL s; p' <- cvtPat p ; return (noLoc $ HsRecField { hsRecFieldId = s', hsRecFieldArg = p' , hsRecPun = False}) } {- | @cvtOpAppP x op y@ converts @op@ and @y@ and produces the operator application @x `op` y@. The produced tree of infix patterns will be left-biased, provided @x@ is. See the @cvtOpApp@ documentation for how this function works. -} cvtOpAppP :: Hs.LPat RdrName -> TH.Name -> TH.Pat -> CvtM (Hs.Pat RdrName) cvtOpAppP x op1 (UInfixP y op2 z) = do { l <- wrapL $ cvtOpAppP x op1 y ; cvtOpAppP l op2 z } cvtOpAppP x op y = do { op' <- cNameL op ; y' <- cvtPat y ; return (ConPatIn op' (InfixCon x y')) } ----------------------------------------------------------- -- Types and type variables cvtTvs :: [TH.TyVarBndr] -> CvtM (LHsTyVarBndrs RdrName) cvtTvs tvs = do { tvs' <- mapM cvt_tv tvs; return (mkHsQTvs tvs') } cvt_tv :: TH.TyVarBndr -> CvtM (LHsTyVarBndr RdrName) cvt_tv (TH.PlainTV nm) = do { nm' <- tName nm ; returnL $ UserTyVar nm' } cvt_tv (TH.KindedTV nm ki) = do { nm' <- tName nm ; ki' <- cvtKind ki ; returnL $ KindedTyVar (noLoc nm') ki' } cvtRole :: TH.Role -> Maybe Coercion.Role cvtRole TH.NominalR = Just Coercion.Nominal cvtRole TH.RepresentationalR = Just Coercion.Representational cvtRole TH.PhantomR = Just Coercion.Phantom cvtRole TH.InferR = Nothing cvtContext :: TH.Cxt -> CvtM (LHsContext RdrName) cvtContext tys = do { preds' <- mapM cvtPred tys; returnL preds' } cvtPred :: TH.Pred -> CvtM (LHsType RdrName) cvtPred = cvtType cvtType :: TH.Type -> CvtM (LHsType RdrName) cvtType = cvtTypeKind "type" cvtTypeKind :: String -> TH.Type -> CvtM (LHsType RdrName) cvtTypeKind ty_str ty = do { (head_ty, tys') <- split_ty_app ty ; case head_ty of TupleT n | length tys' == n -- Saturated -> if n==1 then return (head tys') -- Singleton tuples treated -- like nothing (ie just parens) else returnL (HsTupleTy HsBoxedOrConstraintTuple tys') | n == 1 -> failWith (ptext (sLit ("Illegal 1-tuple " ++ ty_str ++ " constructor"))) | otherwise -> mk_apps (HsTyVar (getRdrName (tupleTyCon BoxedTuple n))) tys' UnboxedTupleT n | length tys' == n -- Saturated -> if n==1 then return (head tys') -- Singleton tuples treated -- like nothing (ie just parens) else returnL (HsTupleTy HsUnboxedTuple tys') | otherwise -> mk_apps (HsTyVar (getRdrName (tupleTyCon UnboxedTuple n))) tys' ArrowT | [x',y'] <- tys' -> returnL (HsFunTy x' y') | otherwise -> mk_apps (HsTyVar (getRdrName funTyCon)) tys' ListT | [x'] <- tys' -> returnL (HsListTy x') | otherwise -> mk_apps (HsTyVar (getRdrName listTyCon)) tys' VarT nm -> do { nm' <- tName nm; mk_apps (HsTyVar nm') tys' } ConT nm -> do { nm' <- tconName nm; mk_apps (HsTyVar nm') tys' } ForallT tvs cxt ty | null tys' -> do { tvs' <- cvtTvs tvs ; cxt' <- cvtContext cxt ; ty' <- cvtType ty ; returnL $ mkExplicitHsForAllTy (hsQTvBndrs tvs') cxt' ty' } SigT ty ki -> do { ty' <- cvtType ty ; ki' <- cvtKind ki ; mk_apps (HsKindSig ty' ki') tys' } LitT lit -> returnL (HsTyLit (cvtTyLit lit)) PromotedT nm -> do { nm' <- cName nm; mk_apps (HsTyVar nm') tys' } -- Promoted data constructor; hence cName PromotedTupleT n | n == 1 -> failWith (ptext (sLit ("Illegal promoted 1-tuple " ++ ty_str))) | m == n -- Saturated -> do { let kis = replicate m placeHolderKind ; returnL (HsExplicitTupleTy kis tys') } where m = length tys' PromotedNilT -> returnL (HsExplicitListTy placeHolderKind []) PromotedConsT -- See Note [Representing concrete syntax in types] -- in Language.Haskell.TH.Syntax | [ty1, L _ (HsExplicitListTy _ tys2)] <- tys' -> returnL (HsExplicitListTy placeHolderKind (ty1:tys2)) | otherwise -> mk_apps (HsTyVar (getRdrName consDataCon)) tys' StarT -> returnL (HsTyVar (getRdrName liftedTypeKindTyCon)) ConstraintT -> returnL (HsTyVar (getRdrName constraintKindTyCon)) EqualityT | [x',y'] <- tys' -> returnL (HsEqTy x' y') | otherwise -> mk_apps (HsTyVar (getRdrName eqPrimTyCon)) tys' _ -> failWith (ptext (sLit ("Malformed " ++ ty_str)) <+> text (show ty)) } mk_apps :: HsType RdrName -> [LHsType RdrName] -> CvtM (LHsType RdrName) mk_apps head_ty [] = returnL head_ty mk_apps head_ty (ty:tys) = do { head_ty' <- returnL head_ty ; mk_apps (HsAppTy head_ty' ty) tys } split_ty_app :: TH.Type -> CvtM (TH.Type, [LHsType RdrName]) split_ty_app ty = go ty [] where go (AppT f a) as' = do { a' <- cvtType a; go f (a':as') } go f as = return (f,as) cvtTyLit :: TH.TyLit -> HsTyLit cvtTyLit (NumTyLit i) = HsNumTy (show i) i cvtTyLit (StrTyLit s) = HsStrTy s (fsLit s) cvtKind :: TH.Kind -> CvtM (LHsKind RdrName) cvtKind = cvtTypeKind "kind" cvtMaybeKind :: Maybe TH.Kind -> CvtM (Maybe (LHsKind RdrName)) cvtMaybeKind Nothing = return Nothing cvtMaybeKind (Just ki) = do { ki' <- cvtKind ki ; return (Just ki') } ----------------------------------------------------------- cvtFixity :: TH.Fixity -> Hs.Fixity cvtFixity (TH.Fixity prec dir) = Hs.Fixity prec (cvt_dir dir) where cvt_dir TH.InfixL = Hs.InfixL cvt_dir TH.InfixR = Hs.InfixR cvt_dir TH.InfixN = Hs.InfixN ----------------------------------------------------------- ----------------------------------------------------------- -- some useful things overloadedLit :: Lit -> Bool -- True for literals that Haskell treats as overloaded overloadedLit (IntegerL _) = True overloadedLit (RationalL _) = True overloadedLit _ = False cvtFractionalLit :: Rational -> FractionalLit cvtFractionalLit r = FL { fl_text = show (fromRational r :: Double), fl_value = r } -------------------------------------------------------------------- -- Turning Name back into RdrName -------------------------------------------------------------------- -- variable names vNameL, cNameL, vcNameL, tconNameL :: TH.Name -> CvtM (Located RdrName) vName, cName, vcName, tName, tconName :: TH.Name -> CvtM RdrName -- Variable names vNameL n = wrapL (vName n) vName n = cvtName OccName.varName n -- Constructor function names; this is Haskell source, hence srcDataName cNameL n = wrapL (cName n) cName n = cvtName OccName.dataName n -- Variable *or* constructor names; check by looking at the first char vcNameL n = wrapL (vcName n) vcName n = if isVarName n then vName n else cName n -- Type variable names tName n = cvtName OccName.tvName n -- Type Constructor names tconNameL n = wrapL (tconName n) tconName n = cvtName OccName.tcClsName n cvtName :: OccName.NameSpace -> TH.Name -> CvtM RdrName cvtName ctxt_ns (TH.Name occ flavour) | not (okOcc ctxt_ns occ_str) = failWith (badOcc ctxt_ns occ_str) | otherwise = do { loc <- getL ; let rdr_name = thRdrName loc ctxt_ns occ_str flavour ; force rdr_name ; return rdr_name } where occ_str = TH.occString occ okOcc :: OccName.NameSpace -> String -> Bool okOcc ns str | OccName.isVarNameSpace ns = okVarOcc str | OccName.isDataConNameSpace ns = okConOcc str | otherwise = okTcOcc str -- Determine the name space of a name in a type -- isVarName :: TH.Name -> Bool isVarName (TH.Name occ _) = case TH.occString occ of "" -> False (c:_) -> startsVarId c || startsVarSym c badOcc :: OccName.NameSpace -> String -> SDoc badOcc ctxt_ns occ = ptext (sLit "Illegal") <+> pprNameSpace ctxt_ns <+> ptext (sLit "name:") <+> quotes (text occ) thRdrName :: SrcSpan -> OccName.NameSpace -> String -> TH.NameFlavour -> RdrName -- This turns a TH Name into a RdrName; used for both binders and occurrences -- See Note [Binders in Template Haskell] -- The passed-in name space tells what the context is expecting; -- use it unless the TH name knows what name-space it comes -- from, in which case use the latter -- -- We pass in a SrcSpan (gotten from the monad) because this function -- is used for *binders* and if we make an Exact Name we want it -- to have a binding site inside it. (cf Trac #5434) -- -- ToDo: we may generate silly RdrNames, by passing a name space -- that doesn't match the string, like VarName ":+", -- which will give confusing error messages later -- -- The strict applications ensure that any buried exceptions get forced thRdrName loc ctxt_ns th_occ th_name = case th_name of TH.NameG th_ns pkg mod -> thOrigRdrName th_occ th_ns pkg mod TH.NameQ mod -> (mkRdrQual $! mk_mod mod) $! occ TH.NameL uniq -> nameRdrName $! (((Name.mkInternalName $! mk_uniq uniq) $! occ) loc) TH.NameU uniq -> nameRdrName $! (((Name.mkSystemNameAt $! mk_uniq uniq) $! occ) loc) TH.NameS | Just name <- isBuiltInOcc_maybe occ -> nameRdrName $! name | otherwise -> mkRdrUnqual $! occ -- We check for built-in syntax here, because the TH -- user might have written a (NameS "(,,)"), for example where occ :: OccName.OccName occ = mk_occ ctxt_ns th_occ thOrigRdrName :: String -> TH.NameSpace -> PkgName -> ModName -> RdrName thOrigRdrName occ th_ns pkg mod = (mkOrig $! (mkModule (mk_pkg pkg) (mk_mod mod))) $! (mk_occ (mk_ghc_ns th_ns) occ) thRdrNameGuesses :: TH.Name -> [RdrName] thRdrNameGuesses (TH.Name occ flavour) -- This special case for NameG ensures that we don't generate duplicates in the output list | TH.NameG th_ns pkg mod <- flavour = [ thOrigRdrName occ_str th_ns pkg mod] | otherwise = [ thRdrName noSrcSpan gns occ_str flavour | gns <- guessed_nss] where -- guessed_ns are the name spaces guessed from looking at the TH name guessed_nss | isLexCon (mkFastString occ_str) = [OccName.tcName, OccName.dataName] | otherwise = [OccName.varName, OccName.tvName] occ_str = TH.occString occ -- The packing and unpacking is rather turgid :-( mk_occ :: OccName.NameSpace -> String -> OccName.OccName mk_occ ns occ = OccName.mkOccName ns occ mk_ghc_ns :: TH.NameSpace -> OccName.NameSpace mk_ghc_ns TH.DataName = OccName.dataName mk_ghc_ns TH.TcClsName = OccName.tcClsName mk_ghc_ns TH.VarName = OccName.varName mk_mod :: TH.ModName -> ModuleName mk_mod mod = mkModuleName (TH.modString mod) mk_pkg :: TH.PkgName -> UnitId mk_pkg pkg = stringToUnitId (TH.pkgString pkg) mk_uniq :: Int -> Unique mk_uniq u = mkUniqueGrimily u {- Note [Binders in Template Haskell] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this TH term construction: do { x1 <- TH.newName "x" -- newName :: String -> Q TH.Name ; x2 <- TH.newName "x" -- Builds a NameU ; x3 <- TH.newName "x" ; let x = mkName "x" -- mkName :: String -> TH.Name -- Builds a NameS ; return (LamE (..pattern [x1,x2]..) $ LamE (VarPat x3) $ ..tuple (x1,x2,x3,x)) } It represents the term \[x1,x2]. \x3. (x1,x2,x3,x) a) We don't want to complain about "x" being bound twice in the pattern [x1,x2] b) We don't want x3 to shadow the x1,x2 c) We *do* want 'x' (dynamically bound with mkName) to bind to the innermost binding of "x", namely x3. d) When pretty printing, we want to print a unique with x1,x2 etc, else they'll all print as "x" which isn't very helpful When we convert all this to HsSyn, the TH.Names are converted with thRdrName. To achieve (b) we want the binders to be Exact RdrNames. Achieving (a) is a bit awkward, because - We must check for duplicate and shadowed names on Names, not RdrNames, *after* renaming. See Note [Collect binders only after renaming] in HsUtils - But to achieve (a) we must distinguish between the Exact RdrNames arising from TH and the Unqual RdrNames that would come from a user writing \[x,x] -> blah So in Convert.thRdrName we translate TH Name RdrName -------------------------------------------------------- NameU (arising from newName) --> Exact (Name{ System }) NameS (arising from mkName) --> Unqual Notice that the NameUs generate *System* Names. Then, when figuring out shadowing and duplicates, we can filter out System Names. This use of System Names fits with other uses of System Names, eg for temporary variables "a". Since there are lots of things called "a" we usually want to print the name with the unique, and that is indeed the way System Names are printed. There's a small complication of course; see Note [Looking up Exact RdrNames] in RnEnv. -}
AlexeyRaga/eta
compiler/ETA/HsSyn/Convert.hs
bsd-3-clause
53,143
1
18
16,614
15,488
7,811
7,677
841
28
{-# language CPP #-} -- | = Name -- -- VK_HUAWEI_invocation_mask - device extension -- -- == VK_HUAWEI_invocation_mask -- -- [__Name String__] -- @VK_HUAWEI_invocation_mask@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 371 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_ray_tracing_pipeline@ -- -- - Requires @VK_KHR_synchronization2@ -- -- [__Contact__] -- -- - Yunpeng Zhu -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_HUAWEI_invocation_mask] @yunxingzhu%0A<<Here describe the issue or question you have about the VK_HUAWEI_invocation_mask extension>> > -- -- [__Extension Proposal__] -- <https://github.com/KhronosGroup/Vulkan-Docs/tree/main/proposals/VK_HUAWEI_invocation_mask.asciidoc VK_HUAWEI_invocation_mask> -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2021-05-27 -- -- [__Interactions and External Dependencies__] -- -- - This extension requires @VK_KHR_ray_tracing_pipeline@, which -- allow to bind an invocation mask image before the ray tracing -- command -- -- - This extension requires @VK_KHR_synchronization2@, which allows -- new pipeline stage for the invocation mask image -- -- [__Contributors__] -- -- - Yunpeng Zhu, HuaWei -- -- == Description -- -- The rays to trace may be sparse in some use cases. For example, the -- scene only have a few regions to reflect. Providing an invocation mask -- image to the ray tracing commands could potentially give the hardware -- the hint to do certain optimization without invoking an additional pass -- to compact the ray buffer. -- -- == New Commands -- -- - 'cmdBindInvocationMaskHUAWEI' -- -- == New Structures -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2', -- 'Vulkan.Core10.Device.DeviceCreateInfo': -- -- - 'PhysicalDeviceInvocationMaskFeaturesHUAWEI' -- -- == New Enum Constants -- -- - 'HUAWEI_INVOCATION_MASK_EXTENSION_NAME' -- -- - 'HUAWEI_INVOCATION_MASK_SPEC_VERSION' -- -- - Extending 'Vulkan.Core13.Enums.AccessFlags2.AccessFlagBits2': -- -- - 'Vulkan.Core13.Enums.AccessFlags2.ACCESS_2_INVOCATION_MASK_READ_BIT_HUAWEI' -- -- - Extending -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.ImageUsageFlagBits': -- -- - 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_INVOCATION_MASK_BIT_HUAWEI' -- -- - Extending -- 'Vulkan.Core13.Enums.PipelineStageFlags2.PipelineStageFlagBits2': -- -- - 'Vulkan.Core13.Enums.PipelineStageFlags2.PIPELINE_STAGE_2_INVOCATION_MASK_BIT_HUAWEI' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_INVOCATION_MASK_FEATURES_HUAWEI' -- -- == Examples -- -- RT mask is updated before each traceRay. -- -- Step 1. Generate InvocationMask. -- -- > //the rt mask image bind as color attachment in the fragment shader -- > Layout(location = 2) out vec4 outRTmask -- > vec4 mask = vec4(x,x,x,x); -- > outRTmask = mask; -- -- Step 2. traceRay with InvocationMask -- -- > vkCmdBindPipeline( -- > commandBuffers[imageIndex], -- > VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, m_rtPipeline); -- > vkCmdBindDescriptorSets(commandBuffers[imageIndex], -- > VK_PIPELINE_BIND_POINT_RAY_TRACING_NV, -- > m_rtPipelineLayout, 0, 1, &m_rtDescriptorSet, -- > 0, nullptr); -- > -- > vkCmdBindInvocationMaskHUAWEI( -- > commandBuffers[imageIndex], -- > InvocationMaskimageView, -- > InvocationMaskimageLayout); -- > vkCmdTraceRaysKHR(commandBuffers[imageIndex], -- > pRaygenShaderBindingTable, -- > pMissShaderBindingTable, -- > swapChainExtent.width, -- > swapChainExtent.height, 1); -- -- == Version History -- -- - Revision 1, 2021-05-27 (Yunpeng Zhu) -- -- - Initial draft. -- -- == See Also -- -- 'PhysicalDeviceInvocationMaskFeaturesHUAWEI', -- 'cmdBindInvocationMaskHUAWEI' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_HUAWEI_invocation_mask Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_HUAWEI_invocation_mask ( cmdBindInvocationMaskHUAWEI , PhysicalDeviceInvocationMaskFeaturesHUAWEI(..) , HUAWEI_INVOCATION_MASK_SPEC_VERSION , pattern HUAWEI_INVOCATION_MASK_SPEC_VERSION , HUAWEI_INVOCATION_MASK_EXTENSION_NAME , pattern HUAWEI_INVOCATION_MASK_EXTENSION_NAME ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Kind (Type) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core10.Handles (CommandBuffer) import Vulkan.Core10.Handles (CommandBuffer(..)) import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer)) import Vulkan.Core10.Handles (CommandBuffer_T) import Vulkan.Dynamic (DeviceCmds(pVkCmdBindInvocationMaskHUAWEI)) import Vulkan.Core10.Enums.ImageLayout (ImageLayout) import Vulkan.Core10.Enums.ImageLayout (ImageLayout(..)) import Vulkan.Core10.Handles (ImageView) import Vulkan.Core10.Handles (ImageView(..)) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_INVOCATION_MASK_FEATURES_HUAWEI)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCmdBindInvocationMaskHUAWEI :: FunPtr (Ptr CommandBuffer_T -> ImageView -> ImageLayout -> IO ()) -> Ptr CommandBuffer_T -> ImageView -> ImageLayout -> IO () -- | vkCmdBindInvocationMaskHUAWEI - Bind an invocation mask image on a -- command buffer -- -- == Valid Usage -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-None-04976# The -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-invocationMask invocation mask image> -- feature /must/ be enabled -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-imageView-04977# If @imageView@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', it /must/ be a -- valid 'Vulkan.Core10.Handles.ImageView' handle of type -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-imageView-04978# If @imageView@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', it /must/ have a -- format of 'Vulkan.Core10.Enums.Format.FORMAT_R8_UINT' -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-imageView-04979# If @imageView@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', it /must/ have been -- created with -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_INVOCATION_MASK_BIT_HUAWEI' -- set -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-imageView-04980# If @imageView@ -- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @imageLayout@ -- /must/ be 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_GENERAL' -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-width-04981# Thread mask image -- resolution must match the @width@ and @height@ in -- 'Vulkan.Extensions.VK_KHR_ray_tracing_pipeline.cmdTraceRaysKHR' -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-None-04982# Each element in the -- invocation mask image /must/ have the value @0@ or @1@. The value 1 -- means the invocation is active -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-width-04983# @width@ in -- 'Vulkan.Extensions.VK_KHR_ray_tracing_pipeline.cmdTraceRaysKHR' -- should be 1 -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-commandBuffer-parameter# -- @commandBuffer@ /must/ be a valid -- 'Vulkan.Core10.Handles.CommandBuffer' handle -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-imageView-parameter# If -- @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- @imageView@ /must/ be a valid 'Vulkan.Core10.Handles.ImageView' -- handle -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-imageLayout-parameter# -- @imageLayout@ /must/ be a valid -- 'Vulkan.Core10.Enums.ImageLayout.ImageLayout' value -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-commandBuffer-recording# -- @commandBuffer@ /must/ be in the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state> -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-commandBuffer-cmdpool# The -- 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was -- allocated from /must/ support compute operations -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-renderpass# This command /must/ -- only be called outside of a render pass instance -- -- - #VUID-vkCmdBindInvocationMaskHUAWEI-commonparent# Both of -- @commandBuffer@, and @imageView@ that are valid handles of -- non-ignored parameters /must/ have been created, allocated, or -- retrieved from the same 'Vulkan.Core10.Handles.Device' -- -- == Host Synchronization -- -- - Host access to @commandBuffer@ /must/ be externally synchronized -- -- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that -- @commandBuffer@ was allocated from /must/ be externally synchronized -- -- == Command Properties -- -- \' -- -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types> | -- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+ -- | Primary | Outside | Compute | -- | Secondary | | | -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_HUAWEI_invocation_mask VK_HUAWEI_invocation_mask>, -- 'Vulkan.Core10.Handles.CommandBuffer', -- 'Vulkan.Core10.Enums.ImageLayout.ImageLayout', -- 'Vulkan.Core10.Handles.ImageView' cmdBindInvocationMaskHUAWEI :: forall io . (MonadIO io) => -- | @commandBuffer@ is the command buffer into which the command will be -- recorded CommandBuffer -> -- | @imageView@ is an image view handle specifying the invocation mask image -- @imageView@ /may/ be set to 'Vulkan.Core10.APIConstants.NULL_HANDLE', -- which is equivalent to specifying a view of an image filled with ones -- value. ImageView -> -- | @imageLayout@ is the layout that the image subresources accessible from -- @imageView@ will be in when the invocation mask image is accessed ImageLayout -> io () cmdBindInvocationMaskHUAWEI commandBuffer imageView imageLayout = liftIO $ do let vkCmdBindInvocationMaskHUAWEIPtr = pVkCmdBindInvocationMaskHUAWEI (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds) unless (vkCmdBindInvocationMaskHUAWEIPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdBindInvocationMaskHUAWEI is null" Nothing Nothing let vkCmdBindInvocationMaskHUAWEI' = mkVkCmdBindInvocationMaskHUAWEI vkCmdBindInvocationMaskHUAWEIPtr traceAroundEvent "vkCmdBindInvocationMaskHUAWEI" (vkCmdBindInvocationMaskHUAWEI' (commandBufferHandle (commandBuffer)) (imageView) (imageLayout)) pure $ () -- | VkPhysicalDeviceInvocationMaskFeaturesHUAWEI - Structure describing -- invocation mask features that can be supported by an implementation -- -- = Members -- -- This structure describes the following features: -- -- = Description -- -- If the 'PhysicalDeviceInvocationMaskFeaturesHUAWEI' structure is -- included in the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2', -- it is filled in to indicate whether each corresponding feature is -- supported. 'PhysicalDeviceInvocationMaskFeaturesHUAWEI' /can/ also be -- used in the @pNext@ chain of 'Vulkan.Core10.Device.DeviceCreateInfo' to -- selectively enable these features. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_HUAWEI_invocation_mask VK_HUAWEI_invocation_mask>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDeviceInvocationMaskFeaturesHUAWEI = PhysicalDeviceInvocationMaskFeaturesHUAWEI { -- | #features-invocationMask# @invocationMask@ indicates that the -- implementation supports the use of an invocation mask image to optimize -- the ray dispatch. invocationMask :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceInvocationMaskFeaturesHUAWEI) #endif deriving instance Show PhysicalDeviceInvocationMaskFeaturesHUAWEI instance ToCStruct PhysicalDeviceInvocationMaskFeaturesHUAWEI where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceInvocationMaskFeaturesHUAWEI{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_INVOCATION_MASK_FEATURES_HUAWEI) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (invocationMask)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_INVOCATION_MASK_FEATURES_HUAWEI) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct PhysicalDeviceInvocationMaskFeaturesHUAWEI where peekCStruct p = do invocationMask <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) pure $ PhysicalDeviceInvocationMaskFeaturesHUAWEI (bool32ToBool invocationMask) instance Storable PhysicalDeviceInvocationMaskFeaturesHUAWEI where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceInvocationMaskFeaturesHUAWEI where zero = PhysicalDeviceInvocationMaskFeaturesHUAWEI zero type HUAWEI_INVOCATION_MASK_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_HUAWEI_INVOCATION_MASK_SPEC_VERSION" pattern HUAWEI_INVOCATION_MASK_SPEC_VERSION :: forall a . Integral a => a pattern HUAWEI_INVOCATION_MASK_SPEC_VERSION = 1 type HUAWEI_INVOCATION_MASK_EXTENSION_NAME = "VK_HUAWEI_invocation_mask" -- No documentation found for TopLevel "VK_HUAWEI_INVOCATION_MASK_EXTENSION_NAME" pattern HUAWEI_INVOCATION_MASK_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern HUAWEI_INVOCATION_MASK_EXTENSION_NAME = "VK_HUAWEI_invocation_mask"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_HUAWEI_invocation_mask.hs
bsd-3-clause
18,207
0
17
3,463
1,580
1,016
564
-1
-1
module Types.Drawable where import Graphics.Gloss.Data.Picture import Graphics.Gloss.Data.Vector import Graphics.Gloss.Data.Point class Drawable a where shape :: a -> Path-- ^ Shape to draw of object pic :: a -> Picture -- ^ Gloss picture to draw
Smurf/dodgem
src/Types/Drawable.hs
bsd-3-clause
271
0
7
59
56
35
21
7
0
{-# LANGUAGE OverloadedStrings #-} module Editor (editor,ide,empty) where import Data.Monoid (mempty) import Text.Blaze.Html import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Network.HTTP.Base (urlEncode) import qualified System.FilePath as FP -- | Display an editor and the compiled result side-by-side. ide :: FilePath -> String -> Html ide fileName code = ideBuilder ("Elm Debugger: " ++ FP.takeBaseName fileName) fileName ("/compile?input=" ++ urlEncode code) -- | Display an editor and the compiled result side-by-side. empty :: Html empty = ideBuilder "Debug Elm" "Empty.elm" "/Try.elm" ideBuilder :: String -> String -> String -> Html ideBuilder title input output = H.docTypeHtml $ do H.head $ do H.title . toHtml $ title preEscapedToMarkup $ concat [ "<frameset cols=\"50%,50%\">\n" , " <frame name=\"input\" src=\"/code/", input, "\" />\n" , " <frame name=\"output\" src=\"", output, "\" />\n" , "</frameset>" ] -- | list of themes to use with CodeMirror themes :: [String] themes = [ "ambiance", "blackboard", "cobalt", "eclipse" , "elegant", "erlang-dark", "lesser-dark", "monokai", "neat", "night" , "rubyblue", "solarized", "twilight", "vibrant-ink", "xq-dark" ] -- | Create an HTML document that allows you to edit and submit Elm code -- for compilation. editor :: FilePath -> String -> Html editor filePath code = H.html $ do H.head $ do H.title . toHtml $ "Elm Editor: " ++ FP.takeBaseName filePath H.link ! A.rel "stylesheet" ! A.href "/codemirror-3.x/lib/codemirror.css" H.script ! A.src "/codemirror-3.x/lib/codemirror.js" $ mempty H.script ! A.src "/codemirror-3.x/mode/elm/elm.js" $ mempty mapM_ (\theme -> H.link ! A.rel "stylesheet" ! A.href (toValue ("/codemirror-3.x/theme/" ++ theme ++ ".css" :: String))) themes H.link ! A.rel "stylesheet" ! A.type_ "text/css" ! A.href "/misc/editor.css" H.script ! A.type_ "text/javascript" ! A.src "/misc/showdown.js" $ mempty H.script ! A.type_ "text/javascript" ! A.src "/misc/editor.js" $ mempty H.body $ do H.form ! A.id "inputForm" ! A.action "/compile" ! A.method "post" ! A.target "output" $ do H.div ! A.id "editor_box" $ H.textarea ! A.name "input" ! A.id "input" $ toHtml ('\n':code) H.div ! A.id "options" $ do bar "documentation" docs bar "editor_options" editorOptions bar "always_on" (buttons >> options) H.script ! A.type_ "text/javascript" $ "initEditor();" bar :: AttributeValue -> Html -> Html bar id' body = H.div ! A.id id' ! A.class_ "option" $ body buttons :: Html buttons = H.div ! A.class_ "valign_kids" ! A.style "float:right; padding-right: 6px;" $ "Auto-update:" >> autoBox >> hotSwapButton >> compileButton where hotSwapButton = H.input ! A.type_ "button" ! A.id "hot_swap_button" ! A.value "Hot Swap" ! A.onclick "hotSwap()" ! A.title "Ctrl-Shift-Enter" compileButton = H.input ! A.type_ "button" ! A.id "compile_button" ! A.value "Compile" ! A.onclick "compile()" ! A.title "Ctrl-Enter: change program behavior but keep the state" autoBox = H.input ! A.type_ "checkbox" ! A.id "auto_hot_swap_checkbox" ! A.onchange "setAutoHotSwap(this.checked)" ! A.style "margin-right:20px;" ! A.title "attempt to hot-swap automatically" options :: Html options = H.div ! A.class_ "valign_kids" ! A.style "float:left; padding-left:6px; padding-top:2px;" ! A.title "Show documentation and types." $ (docs' >> opts) where docs' = do H.span "Hints:" H.input ! A.type_ "checkbox" ! A.id "show_type_checkbox" ! A.onchange "showType(this.checked);" opts = do H.span ! A.style "padding-left: 12px;" $ "Options:" H.input ! A.type_ "checkbox" ! A.id "options_checkbox" ! A.onchange "showOptions(this.checked);" editorOptions :: Html editorOptions = theme >> zoom >> lineNumbers where optionFor :: String -> Html optionFor text = H.option ! A.value (toValue text) $ toHtml text theme = H.select ! A.id "editor_theme" ! A.onchange "setTheme(this.value)" $ mapM_ optionFor themes zoom = H.select ! A.id "editor_zoom" ! A.onchange "setZoom(this.options[this.selectedIndex].innerHTML)" $ mapM_ optionFor ["100%", "80%", "150%", "200%"] lineNumbers = do H.span ! A.style "padding-left: 16px;" $ "Line Numbers:" H.input ! A.type_ "checkbox" ! A.id "editor_lines" ! A.onchange "showLines(this.checked);" docs :: Html docs = tipe >> desc where tipe = H.div ! A.class_ "type" $ message >> more message = H.div ! A.style "position:absolute; left:4px; right:36px; overflow:hidden; text-overflow:ellipsis;" $ "" more = H.a ! A.id "toggle_link" ! A.style "display:none; float:right;" ! A.href "javascript:toggleVerbose();" ! A.title "Ctrl+H" $ "more" desc = H.div ! A.class_ "doc" ! A.style "display:none;" $ ""
elm-lang/debug.elm-lang.org
server/Editor.hs
bsd-3-clause
5,796
0
20
1,820
1,462
726
736
122
1
module Template.Layout where import ClassyPrelude -- import Data.Text (Text) import Lucid -- layout :: HTML -> HTML defaultLayout :: (Monad m) => HtmlT m b -> HtmlT m b defaultLayout content = do doctype_ head_ $ do meta_ [charset_ "utf-8"] meta_ [name_ "viewport",content_ "width=device-width, initial-scale=1"] link_ [href_ "//fonts.googleapis.com/css?family=Open+Sans",rel_ "stylesheet",type_ "text/css"] link_ [href_ "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.0/css/bootstrap.min.css",rel_ "stylesheet",type_ "text/css"] title_ "YSU Closing Status" body_ $ div_ [class_ "container"] content simpleError :: Monad m => Text -> Text -> HtmlT m b -> HtmlT m b simpleError title errMsg ct = div_ [class_ "panel panel-info", style_ "margin-top: 30px;"] $ div_ [class_ "panel-heading"] $ do div_ [class_ "panel-title"] $ toHtml title div_ [class_ "panel-body"] $ do toHtml errMsg div_ ct notice :: Monad m => Text -> HtmlT m () notice msg = div_ [class_ "panel panel-info", style_ "margin-top: 30px;"] $ div_ [class_ "panel-heading"] $ div_ [class_ "panel-body"] (toHtml msg)
rvion/ride
web-playground/src/Template/Layout.hs
bsd-3-clause
1,184
0
12
242
367
171
196
27
1
module Examples where import Grammar import Algo -- | example grammars ex0 = CFG ['S', 'A'] [] [Production 'S' [] ,Production 'S' [Left 'A'] ,Production 'A' [Left 'A']] 'S' -- | simple expressions, left recursive ex1left = CFG ['F', 'T'] ['x', '+'] [Production 'T' [Left 'F'] ,Production 'T' [Left 'T', Right '+', Left 'F'] ,Production 'F' [Right 'x']] 'T' ex1right = CFG ['F', 'T'] ['x', '+'] [Production 'T' [Left 'F'] ,Production 'T' [Left 'F', Right '+', Left 'T'] ,Production 'F' [Right 'x']] 'T' ex2 = CFG ['F'] ['x', 'y'] [Production 'F' [Right 'x'] ,Production 'F' [Right 'y']] 'F' ex3 = CFG ['F'] ['x', 'y'] [Production 'F' [] ,Production 'F' [Right 'y', Left 'F']] 'F' ex4 = CFG ['F'] ['x', 'y'] [Production 'F' [] ,Production 'F' [Left 'F', Right 'y']] 'F' -- | bracketed expressions, left recursive ex5left = CFG ['F', 'T'] ['x', '+', '(', ')'] [Production 'T' [Left 'F'] ,Production 'T' [Left 'T', Right '+', Left 'F'] ,Production 'F' [Right 'x'] ,Production 'F' [Right '(', Left 'T', Right ')']] 'T' ex5right = CFG ['F', 'T'] ['x', '+', '(', ')'] [Production 'T' [Left 'F'] ,Production 'T' [Left 'F', Right '+', Left 'T'] ,Production 'F' [Right 'x'] ,Production 'F' [Right '(', Left 'T', Right ')']] 'T' -- | L = { a^n b^n } ex6left = CFG ['S'] "ab" [Production 'S' [] ,Production 'S' [Right 'a', Left 'S', Right 'b']] 'S' ex6right = CFG ['R'] "ab" [Production 'R' [Right 'a', Left 'R'] ,Production 'R' [Right 'b', Left 'R'] ,Production 'R' []] 'R' -- | L = { a^n b^m | m <= n } ex6leftb = CFG ['S'] "ab" [Production 'S' [] ,Production 'S' [Right 'a', Left 'S'] ,Production 'S' [Right 'a', Left 'S', Right 'b']] 'S' ex6rightb = CFG ['R'] "a" [Production 'R' [Right 'a', Left 'R'] ,Production 'R' []] 'R' -- | L = same number of as and bs ex6leftc = CFG ['S'] "ab" [Production 'S' [] ,Production 'S' [Right 'b', Left 'S', Right 'a'] ,Production 'S' [Right 'a', Left 'S', Right 'b'] ,Production 'S' [Left 'S', Left 'S']] 'S' -- | L = matching parentheses ex7left = CFG ['S'] "<>" [Production 'S' [] ,Production 'S' [Right '<', Left 'S', Right '>'] ,Production 'S' [Left 'S', Left 'S']] 'S' ex7right = CFG ['R'] "<>" [Production 'R' [Right '<', Left 'R'] ,Production 'R' [Right '>', Left 'R'] ,Production 'R' []] 'R'
peterthiemann/cftools
src/Examples.hs
bsd-3-clause
2,885
0
9
1,048
1,097
573
524
106
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Utils.Http (send) where import qualified Control.Exception as E import Control.Monad.Error import qualified Data.ByteString.Char8 as BSC import qualified Data.List as List import Network (withSocketsDo) import Network.HTTP.Client import Network.HTTP.Client.TLS (tlsManagerSettings) import Network.HTTP.Types send :: (MonadIO m, MonadError String m) => String -> (Request -> Manager -> IO a) -> m a send url handler = do result <- liftIO (sendSafe url handler) either throwError return result sendSafe :: String -> (Request -> Manager -> IO a) -> IO (Either String a) sendSafe url handler = sendUnsafe url handler `E.catch` handleHttpError url `E.catch` (handleAnyError url :: E.SomeException -> IO (Either String b)) sendUnsafe :: String -> (Request -> Manager -> IO a) -> IO (Either err a) sendUnsafe url handler = do request <- parseUrl url result <- withSocketsDo $ withManager tlsManagerSettings (handler request) return (Right result) handleHttpError :: String -> HttpException -> IO (Either String b) handleHttpError url exception = case exception of StatusCodeException (Status _code err) headers _ -> let details = case List.lookup "X-Response-Body-Start" headers of Just msg | not (BSC.null msg) -> msg _ -> err in return . Left $ BSC.unpack details _ -> handleAnyError url exception handleAnyError :: (E.Exception e) => String -> e -> IO (Either String b) handleAnyError url exception = return . Left $ "failed with '" ++ show exception ++ "' when sending request to\n" ++ " <" ++ url ++ ">"
rtfeldman/elm-package
src/Utils/Http.hs
bsd-3-clause
1,748
0
21
408
564
289
275
44
3
{-# LANGUAGE TemplateHaskell, RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE BangPatterns #-} module Chapter2Bandit ( Bandit(..) , Policy(..) , mkBandit , loopSteps ) where import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.State import Control.Lens (makeLenses, over, element, (+~), (&), (.~), (%~)) import Data.List(take, repeat) import Data.Random import Data.Random.Distribution import Data.Random.Distribution.Uniform import Data.Random.Shuffle.Weighted import Data.Random.Source.IO import Language.Haskell.TH import Numeric.LinearAlgebra (Vector, Matrix) import qualified Numeric.LinearAlgebra as LA -- project import Utils ------------------------------------------------------------------------------------------ -- | Bandit Problem -- Three methods (Policies): epsilon-greedy, UCB, gradient bandit. -- Policy includes two parts: action selection & state-value estimation update. -- | For action selections (exploit & explore) of above methods: -- 1. epsilon-greedy: randomly do exploration with probability epsilon; -- 2. UCB using: Qt(a) + c sqrt(log t / Nt(a)) to balance exploit and explore -- 3. Gradient using Qt(a) as Preference value, select action by softmax; -- | For Qt(a) (Value Estimate) Update: -- 1. 'epsilon-greedy' & 'UCB' methods using form of: -- newVal = oldVal + stepSize * (curReward - oldVal) -- here, 'stepSize' parameter in configuration file: -- if < 0, use 'sample average', then it is stationary; -- if > 0, use 'exponential, recency-weighted average', -- then it targets non-stationary problem, weight recent reward more. -- 2. Gradient bandit using gradient approximation, estimate value as preference: -- newValue = oldValue + stepSize * (curReward - baselineVal) * ( 1 - softmax) -- for the selected action's state value update -- and newValue = oldValue - stepSize * (curReward - baselineVal) * softmax -- for all other non-selected actions' -- where 'baseline' could be 0, or the average value of all action rewards until the time -- and 'stepSize' is the same as above. ------------------------------------------------------------------------------------------ data Policy = EGreedy (RVar Bool) -- Bernoulli distribution with p = epsilon | UCB Double -- ucb explore parameter 'c' | Gradient Bool -- gradient baseline param, if < 0, use average reward value data Bandit = Bandit { _kArms :: Int ,_bestValueIdx :: Int -- it is pre-known, for OptimalAction statistics ,_qValues :: ![Double] -- estimate value of each action ,_nActions :: ![Int] -- count of each atcion has taken ,_stepSize :: Double ,_totalReward :: !Double ,_curStep :: !Int ,_bestTakes :: ![Double] -- input randoms ,_srcRVars :: ![RVar Double] -- exploit & explore methods ,_policy :: Policy } makeLenses ''Bandit mkBandit :: Int -> Int -> Double -> Double -> [Double] -> Policy -> Bandit mkBandit karm totalStep initValue stepSize trueValues policy = let (maxValueIdx, _) = maxWithIndex (zip [0..] trueValues) in (Bandit karm maxValueIdx (take karm $ repeat initValue) (take karm $ repeat 0) stepSize 0.0 0 [] (map (flip normal 1.0) trueValues) policy ) -------------------------------------------------------------------------------- ---- learning loopSteps :: Int -> StateT Bandit IO [Double] loopSteps times = replicateM times step step :: StateT Bandit IO Double step = selectOneAction >>= takeOneAction selectOneAction :: StateT Bandit IO Int selectOneAction = do bandit <- get actionN <- case _policy bandit of EGreedy epsilonRVar -> do bExplore <- liftIO $ sample epsilonRVar if bExplore then liftIO $ sample (randomElement [0..((_kArms bandit) - 1)]) else pure . fst . maxWithIndex $ (zip [0..] (_qValues bandit)) UCB c -> do let !ucbEstValues = zipWith (calcUCB c (_curStep bandit)) (_nActions bandit) (_qValues bandit) pure $ fst $ maxWithIndex (zip [0..] ucbEstValues) Gradient _ -> do let gradientValues = map exp (_qValues bandit) gradientProbs = map ( / sum gradientValues) gradientValues -- Sampling according to distribution (element probability) -- The following line will produce good result, even 0.4 without baseline. why? -- Is it because we do weighted random extract twice ? weightedRVar = weightedShuffle $ zip gradientProbs [0..] liftIO $ head <$> sample weightedRVar -- pure $ fst $ maxWithIndex (zip [0..] gradientProbs) pure actionN where calcUCB :: Double -> Int -> Int -> Double -> Double calcUCB c total n val = val + c * sqrt ((log $ fromIntegral total) / fromIntegral n) takeOneAction :: Int -> StateT Bandit IO Double takeOneAction actionN = do bandit <- get reward <- liftIO $ sample (_srcRVars bandit !! actionN) let !bestTake = (_bestValueIdx bandit == actionN) ? (1.0, 0.0) !bandit' = bandit & (nActions . element actionN +~ 1) & (totalReward +~ reward) & (curStep +~ 1) & (bestTakes %~ (++ [bestTake])) !bandit'' = stateUpdate bandit' actionN reward put bandit'' pure reward where stateUpdate :: Bandit -> Int -> Double -> Bandit stateUpdate bandit actionN reward = let !actionTakes = (_nActions bandit) !! actionN !ss = (_stepSize bandit < 0) ? (1.0 / fromIntegral actionTakes, _stepSize bandit) !oldEstValue = (_qValues bandit) !! actionN in case _policy bandit of Gradient bBaseline -> let baseline = bBaseline ? (_totalReward bandit / (fromIntegral $ _curStep bandit), 0.0) !gradientValues = map exp (_qValues bandit) !gradientProbs = map ( / sum gradientValues) gradientValues !newEstValues = zipWith3 (updateGradientPreference reward baseline ss) (_qValues bandit) gradientProbs [0..] in bandit & (qValues .~ newEstValues) -- epsilone greedy & ucb use the same updating formular _ -> let !newEstValue = oldEstValue + (reward - oldEstValue) * ss in bandit & (qValues . element actionN .~ newEstValue) updateGradientPreference :: Double -> Double -> Double -> Double -> Double -> Int -> Double updateGradientPreference reward baseline ss oldVal prob actionIdx = (actionN == actionIdx) ? (oldVal + ss * (reward - baseline) * (1 - prob), oldVal - ss * (reward - baseline) * prob) --------------------------------------------------------------------------------
Xingtao/RLHask
src/Chapter2Bandit.hs
bsd-3-clause
7,088
0
22
1,852
1,471
786
685
-1
-1
module DeBruijnSimpleLambdaTyped2 (run, update, removee,emptyContext,emptyVariables, strip, tru,fls,and', twoTrus) where import Data.Maybe data T = Var Int | Varc Char | Abst Type T | App T T | TRUE | FALSE | IF T T T deriving (Eq, Show) --the Other type is for correctness checking data Type = BOOL | Other | Type `ToType` Type deriving (Show, Eq) --Variable as fst, bound term as snd data BoundThing = Bterm T | Btype Type deriving (Show, Eq) type Binding = (T,BoundThing) type Variables = [Binding] type Context = [Binding] emptyContext = [] :: Context --handy notation emptyVariables = [] :: Variables --footy. jk handy notation update :: Binding -> [Binding] -> Either String [Binding] update (x, y) lst | isVariable x = case y of (Bterm term) -> if x == term then Left ("Error: Improper Binding. Direct Circular Referencing: " ++ show x) else Right ((x,y): removee x lst) (Btype typ) -> Right ((x,y): removee x lst) | otherwise = Left ("Error: Improper Binding. Variable expected as fst. Instead found: " ++ show x) increaseVars :: [Binding] -> [Binding] increaseVars = fmap (\(x,y)-> case x of (Var v) -> (Var (v+1),y) _ -> (x,y)) --gets what a variable is bound to. Will have a left value if not found. gett :: T -> [Binding] -> Either String BoundThing gett x lst | isVariable x = performLookup x lst | otherwise = Left ("Error: Non-variable value used as variable in getBinding. Namely: " ++ show x ) removee :: T -> [Binding]->[Binding] removee k = filter (\x -> fst x /= k) --a helper function for gett. performLookup :: T -> [Binding]-> Either String BoundThing performLookup k lst = case lookup k lst of (Just x) -> Right x Nothing -> Left ("Uhoh, Variable '" ++ show k ++ "' not found in context") --does unboxing, gives empty if malformed/left value strip :: Either String [Binding] -> [Binding] strip (Right c) = c strip _ = [] :: [Binding] --checks if the term is a variable term or not isVariable :: T -> Bool isVariable (Varc _ ) = True isVariable (Var _) = True isVariable _ = False --performs a type check and then evaluates if the type checks out run :: Variables -> T -> Either String T run vars term = case getType vars emptyContext term of (Right _) -> Right (eval vars term) (Left l) -> Left l --determines the type of the term for a given context. getType :: Variables ->Context-> T-> Either String Type getType _ _ TRUE = Right BOOL getType _ _ FALSE = Right BOOL getType vars context (IF x y z) = case getType vars context x of (Right BOOL) -> ans where t1 = getType vars context y t2 = getType vars context z ans = if t1 == t2 then t1 else Left "Error: Mismatched return types in IF expression" (Right r) -> Left ("Error: BOOL expected in IF expression. Instead found: " ++ show r) (Left l) -> Left ("Error: Did not resolve to a known type in IF expression conditional. Cause: " ++ show l) {-in the case of an abstraction, we 'return' the type of the body of the abstraction. However, note that first we increase all the variables in our context by 1 (since we have entered an abstraction). Then we update the context to include a Var 0 that has the type the abstraction says it should have. Using this updated context, we check the type of the body. -} getType vars context (Abst tp bod) = getType vars (strip( update (Var 0,Btype tp) (increaseVars context))) bod {-if what we are substituting has the same type as the abstraction, we simply 'return' that type. Otherwise, we give a meaningful error message.-} getType vars context (App (Abst tp bod) v) | abstType == vType = vType | otherwise = case (abstType, vType) of --hindsight says a monad would have been nice here. (Right ra,Right rv) -> Left ("Error: Substitution of wrong type: " ++ show ra ++ " -and- " ++ show rv ++ " caused issue.") (Right ra,Left lv) -> Left ("Error: Substitution variable did not" ++ "resolve to type: " ++ lv) (Left la,Right rv) -> Left ("Error: Substitution failure. Abstraction" ++ "did not resolve to type: " ++ la) (Left la,Left lv) -> Left ("Error: Substitution failure. Abstraction" ++ "did not resolve to type: " ++ la ++ "Error: Substitution variable did not" ++ "resolve to type: " ++ lv) where vType = getType vars context v abstType = getType vars context (Abst tp bod) --if the first part isn't an abstraction, no substitution. Therefore we are only interested in the type of the second part. getType vars context (App _ b) = getType vars context b getType vars context x = case x of (Var v) -> case gett (Var v) context of (Right (Btype t)) -> Right t (Left l) -> Left l (Varc v) -> case gett (Varc v) vars of (Right (Bterm r)) -> getType vars context r (Left l) -> Left l --evaluates a term. NOTE: Assumed types check out when called. eval :: Variables -> T -> T eval vars (App a b) | isReducible a = eval vars (App (eval vars a) b) --E-APP1 Vars shouldn't change so I think okay for now | isReducible b = eval vars (App a (eval vars b)) --E-APP2 | otherwise = case a of --previously I increased the free variables in b in this step. However, I don't think this is --correct since the substitution 'kills' the abstraction. --(Abst _ x) -> eval vars (sub (a, (increaseFrees b))) --E-APPABS (Abst _ x) -> eval vars (sub (a, b)) --E-APPABS (Var x) -> App (Var x) (eval vars b) _ -> App (eval vars a) (eval vars b) eval vars (IF x y z) | x == TRUE = eval vars y | x == FALSE = eval vars z | otherwise = eval vars (IF (eval vars x) y z) eval vars x | isVariable x = case performLookup x vars of (Right (Bterm r)) -> eval vars r _ -> Varc 'Z' --should never get here if argument to eval is first type checked. | otherwise = x isReducible :: T -> Bool isReducible (App Abst{} _) = True isReducible (App a b) = isReducible a || isReducible b isReducible _ = False sub:: (T,T) ->T sub (Abst _ x, y) = subHelper (x,y) 0 sub (x,y) = subHelper (x,y) 0 --should never get here because sub is only called on abstractions. --the integer indicates the 'level' of abstraction at which we are. subHelper :: (T, T) -> Int -> T subHelper (Abst tp x,y) i = Abst tp (subHelper (x,y) (i+1)) subHelper (App a b, y) i = App (subHelper (a,y) i) (subHelper (b,y) i) subHelper (Var x,y) i = if x == i then y else Var x --a (perhaps now) unneeded function increaseFrees :: T -> T increaseFrees (App a b) = App (increaseFrees a) (increaseFrees b) increaseFrees (Abst tp a) = Abst tp (ifHelper a 0) increaseFrees x = x ifHelper :: T -> Int -> T ifHelper (Abst tp x) i = Abst tp (ifHelper x (i +1)) ifHelper (App a b) i = App (ifHelper a i) (ifHelper a i) ifHelper (Var x) i = Var (if x > i then x + 1 else x) --testing helpers tru = Abst t (Abst t (Var 1)) fls = Abst t (Abst t (Var 0)) and' = Abst t (Abst t (App (App (Var 1) (Var 0)) fls)) vars = strip (update (Varc 'y', Bterm (IF TRUE FALSE TRUE)) (strip (update (Varc 'x', Bterm TRUE) []))) twoTrus = App (App and' tru) tru t = BOOL tf = BOOL `ToType` BOOL {-- testing prompt> run emptyContext (App tru (Varc 'x')) Left "Substitution of wrong type caused by: Uhoh, Variable not found in context" prompt> let c = striptoContext (addBinding [] ((Varc 'x'), (Var 88))) prompt> run c (App tru (Varc 'x')) Left "Substitution of wrong type caused by: Uhoh, Variable 'Var 88' not found in context" --}
armoredsoftware/protocol
demos/PaulPractice/deBruijnSimpleLambdaTyped2.hs
bsd-3-clause
9,847
0
15
4,054
2,544
1,307
1,237
128
10
{-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies, FlexibleContexts #-} module Database.Persist.Class.PersistUnique ( PersistUnique (..) , getByValue , insertBy , replaceUnique , checkUnique , onlyUnique ) where import Database.Persist.Types import qualified Prelude import Prelude hiding ((++)) import Control.Exception (throwIO) import Control.Monad (liftM, when) import Control.Monad.IO.Class (liftIO) import Data.List ((\\)) import Control.Monad.Trans.Reader ( ReaderT ) import Control.Monad.IO.Class (MonadIO) import Database.Persist.Class.PersistStore import Database.Persist.Class.PersistEntity import Data.Monoid (mappend) import Data.Text (unpack, Text) -- | Queries against 'Unique' keys (other than the id 'Key'). -- -- Please read the general Persistent documentation to learn how to create -- 'Unique' keys. -- -- Using this with an Entity without a Unique key leads to undefined behavior. -- A few of these functions require a *single* 'Unique', so using an Entity with multiple 'Unique's is also undefined. In these cases persistent's goal is to throw an exception as soon as possible, but persistent is still transitioning to that. -- -- SQL backends automatically create uniqueness constraints, but for MongoDB you must manually place a unique index on a field to have a uniqueness constraint. -- -- Some functions in this module (insertUnique, insertBy, and replaceUnique) first query the unique indexes to check for conflicts. -- You could instead optimistically attempt to perform the operation (e.g. replace instead of replaceUnique). However, -- -- * there is some fragility to trying to catch the correct exception and determing the column of failure. -- -- * an exception will automatically abort the current SQL transaction class PersistStore backend => PersistUnique backend where -- | Get a record by unique key, if available. Returns also the identifier. getBy :: (MonadIO m, backend ~ PersistEntityBackend val, PersistEntity val) => Unique val -> ReaderT backend m (Maybe (Entity val)) -- | Delete a specific record by unique key. Does nothing if no record -- matches. deleteBy :: (MonadIO m, PersistEntityBackend val ~ backend, PersistEntity val) => Unique val -> ReaderT backend m () -- | Like 'insert', but returns 'Nothing' when the record -- couldn't be inserted because of a uniqueness constraint. insertUnique :: (MonadIO m, PersistEntityBackend val ~ backend, PersistEntity val) => val -> ReaderT backend m (Maybe (Key val)) insertUnique datum = do conflict <- checkUnique datum case conflict of Nothing -> Just `liftM` insert datum Just _ -> return Nothing -- | update based on a uniquness constraint or insert -- -- insert the new record if it does not exist -- update the existing record that matches the uniqueness contraint -- -- Throws an exception if there is more than 1 uniqueness contraint upsert :: (MonadIO m, PersistEntityBackend val ~ backend, PersistEntity val) => val -- ^ new record to insert -> [Update val] -- ^ updates to perform if the record already exists. -- leaving this empty is the equivalent of performing a 'repsert' on a unique key. -> ReaderT backend m (Entity val) -- ^ the record in the database after the operation upsert record updates = do uniqueKey <- onlyUnique record mExists <- getBy uniqueKey k <- case mExists of Just (Entity k _) -> do when (null updates) (replace k record) return k Nothing -> insert record Entity k `liftM` updateGet k updates -- | Insert a value, checking for conflicts with any unique constraints. If a -- duplicate exists in the database, it is returned as 'Left'. Otherwise, the -- new 'Key is returned as 'Right'. insertBy :: (MonadIO m, PersistEntity val, PersistUnique backend, PersistEntityBackend val ~ backend) => val -> ReaderT backend m (Either (Entity val) (Key val)) insertBy val = do res <- getByValue val case res of Nothing -> Right `liftM` insert val Just z -> return $ Left z -- | Return the single unique key for a record onlyUnique :: (MonadIO m, PersistEntity val, PersistUnique backend, PersistEntityBackend val ~ backend) => val -> ReaderT backend m (Unique val) onlyUnique record = case onlyUniqueEither record of Right u -> return u Left us -> requireUniques record us >>= liftIO . throwIO . OnlyUniqueException . show . length onlyUniqueEither :: (PersistEntity val) => val -> Either [Unique val] (Unique val) onlyUniqueEither record = case persistUniqueKeys record of (u:[]) -> Right u us -> Left us -- | A modification of 'getBy', which takes the 'PersistEntity' itself instead -- of a 'Unique' record. Returns a record matching /one/ of the unique keys. This -- function makes the most sense on entities with a single 'Unique' -- constructor. getByValue :: (MonadIO m, PersistEntity record, PersistUnique backend, PersistEntityBackend record ~ backend) => record -> ReaderT backend m (Maybe (Entity record)) getByValue record = checkUniques =<< requireUniques record (persistUniqueKeys record) where checkUniques [] = return Nothing checkUniques (x:xs) = do y <- getBy x case y of Nothing -> checkUniques xs Just z -> return $ Just z requireUniques :: (MonadIO m, PersistEntity record) => record -> [Unique record] -> m [Unique record] requireUniques record [] = liftIO $ throwIO $ userError errorMsg where errorMsg = "getByValue: " `mappend` unpack (recordName record) `mappend` " does not have any Unique" requireUniques _ xs = return xs -- TODO: expose this to users recordName :: (PersistEntity record) => record -> Text recordName = unHaskellName . entityHaskell . entityDef . Just -- | Attempt to replace the record of the given key with the given new record. -- First query the unique fields to make sure the replacement maintains uniqueness constraints. -- Return 'Nothing' if the replacement was made. -- If uniqueness is violated, return a 'Just' with the 'Unique' violation -- -- Since 1.2.2.0 replaceUnique :: (MonadIO m, Eq record, Eq (Unique record), PersistEntityBackend record ~ backend, PersistEntity record, PersistUnique backend) => Key record -> record -> ReaderT backend m (Maybe (Unique record)) replaceUnique key datumNew = getJust key >>= replaceOriginal where uniqueKeysNew = persistUniqueKeys datumNew replaceOriginal original = do conflict <- checkUniqueKeys changedKeys case conflict of Nothing -> replace key datumNew >> return Nothing (Just conflictingKey) -> return $ Just conflictingKey where changedKeys = uniqueKeysNew \\ uniqueKeysOriginal uniqueKeysOriginal = persistUniqueKeys original -- | Check whether there are any conflicts for unique keys with this entity and -- existing entities in the database. -- -- Returns 'Nothing' if the entity would be unique, and could thus safely be inserted. -- on a conflict returns the conflicting key checkUnique :: (MonadIO m, PersistEntityBackend record ~ backend, PersistEntity record, PersistUnique backend) => record -> ReaderT backend m (Maybe (Unique record)) checkUnique = checkUniqueKeys . persistUniqueKeys checkUniqueKeys :: (MonadIO m, PersistEntity record, PersistUnique backend, PersistEntityBackend record ~ backend) => [Unique record] -> ReaderT backend m (Maybe (Unique record)) checkUniqueKeys [] = return Nothing checkUniqueKeys (x:xs) = do y <- getBy x case y of Nothing -> checkUniqueKeys xs Just _ -> return (Just x)
junjihashimoto/persistent
persistent/Database/Persist/Class/PersistUnique.hs
mit
7,821
0
17
1,694
1,623
843
780
97
3
{-# OPTIONS_GHC -cpp #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.GHCPackageConfig -- Copyright : (c) The University of Glasgow 2004 -- -- Maintainer : libraries@haskell.org -- Stability : alpha -- Portability : portable -- -- Explanation: Performs registration for GHC. Specific to -- ghc-pkg. Creates a GHC package config file. module Distribution.Simple.GHCPackageConfig ( GHCPackageConfig(..), mkGHCPackageConfig, defaultGHCPackageConfig, showGHCPackageConfig, localPackageConfig, maybeCreateLocalPackageConfig, canWriteLocalPackageConfig, canReadLocalPackageConfig ) where import Distribution.PackageDescription (PackageDescription(..), BuildInfo(..), Library(..)) import Distribution.Package (PackageIdentifier(..), showPackageId) import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..),mkLibDir) import Distribution.Setup (CopyDest(..)) #ifndef __NHC__ import Control.Exception (try) #else import IO (try) #endif import Control.Monad(unless) import Text.PrettyPrint.HughesPJ import System.Directory (doesFileExist, getPermissions, Permissions (..)) import Distribution.Compat.FilePath (joinFileName) import Distribution.Compat.Directory (getHomeDirectory) -- |Where ghc keeps the --user files. -- |return the file, whether it exists, and whether it's readable localPackageConfig :: IO FilePath localPackageConfig = do u <- getHomeDirectory return $ (u `joinFileName` ".ghc-packages") -- |If the package file doesn't exist, we should try to create it. If -- it already exists, do nothing and return true. This does not take -- into account whether it is readable or writeable. maybeCreateLocalPackageConfig :: IO Bool -- ^success? maybeCreateLocalPackageConfig = do f <- localPackageConfig exists <- doesFileExist f unless exists $ (try (writeFile f "[]\n") >> return ()) doesFileExist f -- |Helper function for canReadPackageConfig and canWritePackageConfig checkPermission :: (Permissions -> Bool) -> IO Bool checkPermission perm = do f <- localPackageConfig exists <- doesFileExist f if exists then getPermissions f >>= (return . perm) else return False -- |Check for read permission on the localPackageConfig canReadLocalPackageConfig :: IO Bool canReadLocalPackageConfig = checkPermission readable -- |Check for write permission on the localPackageConfig canWriteLocalPackageConfig :: IO Bool canWriteLocalPackageConfig = checkPermission writable -- ----------------------------------------------------------------------------- -- GHC 6.2 PackageConfig type -- Until GHC supports the InstalledPackageInfo type above, we use its -- existing PackagConfig type. mkGHCPackageConfig :: PackageDescription -> LocalBuildInfo -> GHCPackageConfig mkGHCPackageConfig pkg_descr lbi = defaultGHCPackageConfig { name = pkg_name, auto = True, import_dirs = [mkLibDir pkg_descr lbi NoCopyDest], library_dirs = (mkLibDir pkg_descr lbi NoCopyDest: maybe [] (extraLibDirs . libBuildInfo) (library pkg_descr)), hs_libraries = ["HS"++(showPackageId (package pkg_descr))], extra_libraries = maybe [] (extraLibs . libBuildInfo) (library pkg_descr), include_dirs = maybe [] (includeDirs . libBuildInfo) (library pkg_descr), c_includes = maybe [] (includes . libBuildInfo) (library pkg_descr), package_deps = map pkgName (packageDeps lbi) } where pkg_name = pkgName (package pkg_descr) data GHCPackageConfig = GHCPackage { name :: String, auto :: Bool, import_dirs :: [String], source_dirs :: [String], library_dirs :: [String], hs_libraries :: [String], extra_libraries :: [String], include_dirs :: [String], c_includes :: [String], package_deps :: [String], extra_ghc_opts :: [String], extra_cc_opts :: [String], extra_ld_opts :: [String], framework_dirs :: [String], -- ignored everywhere but on Darwin/MacOS X extra_frameworks:: [String] -- ignored everywhere but on Darwin/MacOS X } defaultGHCPackageConfig :: GHCPackageConfig defaultGHCPackageConfig = GHCPackage { name = error "defaultPackage", auto = False, import_dirs = [], source_dirs = [], library_dirs = [], hs_libraries = [], extra_libraries = [], include_dirs = [], c_includes = [], package_deps = [], extra_ghc_opts = [], extra_cc_opts = [], extra_ld_opts = [], framework_dirs = [], extra_frameworks= [] } -- --------------------------------------------------------------------------- -- Pretty printing package info showGHCPackageConfig :: GHCPackageConfig -> String showGHCPackageConfig pkg = render $ text "Package" $$ nest 3 (braces ( sep (punctuate comma [ text "name = " <> text (show (name pkg)), text "auto = " <> text (show (auto pkg)), dumpField "import_dirs" (import_dirs pkg), dumpField "source_dirs" (source_dirs pkg), dumpField "library_dirs" (library_dirs pkg), dumpField "hs_libraries" (hs_libraries pkg), dumpField "extra_libraries" (extra_libraries pkg), dumpField "include_dirs" (include_dirs pkg), dumpField "c_includes" (c_includes pkg), dumpField "package_deps" (package_deps pkg), dumpField "extra_ghc_opts" (extra_ghc_opts pkg), dumpField "extra_cc_opts" (extra_cc_opts pkg), dumpField "extra_ld_opts" (extra_ld_opts pkg), dumpField "framework_dirs" (framework_dirs pkg), dumpField "extra_frameworks"(extra_frameworks pkg) ]))) dumpField :: String -> [String] -> Doc dumpField name' val = hang (text name' <+> equals) 2 (dumpFieldContents val) dumpFieldContents :: [String] -> Doc dumpFieldContents val = brackets (sep (punctuate comma (map (text . show) val)))
FranklinChen/hugs98-plus-Sep2006
packages/Cabal/Distribution/Simple/GHCPackageConfig.hs
bsd-3-clause
5,966
96
19
1,181
1,411
793
618
110
2
module AnnotationLet (foo) where { import qualified Data.List as DL ; foo = let a 0 = 1 a _ = 2 b = 2 in a b }
bitemyapp/ghc
testsuite/tests/ghc-api/annotations/AnnotationLet.hs
bsd-3-clause
143
0
9
61
55
32
23
7
2
-- | -- Module : Basement.NonEmpty -- License : BSD-style -- Maintainer : Foundation -- Stability : experimental -- Portability : portable -- -- A newtype wrapper around a non-empty Collection. module Basement.NonEmpty ( NonEmpty(..) ) where import Basement.Exception import Basement.Compat.Base -- | NonEmpty property for any Collection newtype NonEmpty a = NonEmpty { getNonEmpty :: a } deriving (Show,Eq) instance IsList c => IsList (NonEmpty c) where type Item (NonEmpty c) = Item c toList = toList . getNonEmpty fromList [] = throw NonEmptyCollectionIsEmpty fromList l = NonEmpty . fromList $ l
vincenthz/hs-foundation
basement/Basement/NonEmpty.hs
bsd-3-clause
670
0
7
163
137
80
57
-1
-1
-- Copyright (c) 2016 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS -- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. {-# OPTIONS_GHC -funbox-strict-fields -Wall -Werror #-} {-# LANGUAGE MultiParamTypeClasses, ScopedTypeVariables #-} -- | A generalized implementation of flow analysis. This algorithm -- operates on a graph, propagating information from each node to its -- outgoing neighbors until the graph reaches a stable fixed point. -- This algorithm is extremely common in compilers and program -- analysis, and many problems can be characterized and solved using -- it. -- -- In order to use this implementation, the node data needs to have a -- 'Monoid' instance, and a 'FlowData' instance needs to be -- provided for the node and edge data. The 'Monoid' instance should -- provide a way to merge information about nodes, producing a new -- node with the combined information of the two arguments. The -- 'propagate' function in the 'FlowData' instance should -- propagate information from a node along a given edge, producing a -- new node type containing the information that was propagated. This -- will then be merged with the neighbor using the 'mappend' function. module Algorithm.Graph.Flow( FlowData(..), flow, ) where import Algorithm.Worklist import Control.Monad.Trans import Data.Graph.Inductive.Graph import Data.Maybe -- | An abstract characterization of the data for a flow analysis -- problem. In flow analysis, we propagate all nodes to all -- neighbors, then combine all the incoming edges for each node -- according to another operation. -- -- We assume here that the 'Monoid' operation on node data represents -- the merge. The 'propagate' operation then propagates each node's -- incoming edges, then merges the results with the existing node -- data. -- -- For the flow analysis to terminate, it must be the case that all -- functions formed out of 'mappend' and 'propagate' converge to a -- fixed point with repeated application. If this property fails, -- then the flow alorithm may not terminate. class Monoid nodety => FlowData nodety edgety where -- | Compute the effects of propagating node data over a given edge. -- This should produce a node data element that will be combined -- with all the others using the monoid instance. propagate :: Monad m => nodety -- ^ The source node data. -> edgety -- ^ The edge over which to propagate. -> m nodety -- ^ The result of propagating the source data over the -- edge, or 'Nothing' if the node doesn't change. -- | Perform flow analysis on the graph. This will propagate each -- node along its outgoing edges as per the 'propagate' function, -- merging with each node by the 'mappend' function from the 'Monoid' -- instance. The process will continue until the graph reaches a -- stable fixed point. flow :: forall nodety edgety gr m. (FlowData nodety edgety, DynGraph gr, MonadIO m, Monoid nodety, Eq nodety) => gr nodety edgety -- ^ The initial graph state. -> [Node] -- ^ The starting nodes. -> m (gr nodety edgety) -- ^ The graph state after doing flow analysis flow initgraph = let -- Work function for a given node. Propagate all inbound -- neighbors over the inbound edges, merge them together with the -- current node state using the monoid operation. workfunc :: gr nodety edgety -> Int -> m (Maybe (gr nodety edgety)) workfunc graph idx = let node :: nodety node = fromMaybe mempty (lab graph idx) mapfun (from, _, edgedata) = case lab graph from of Just fromnode -> propagate fromnode edgedata Nothing -> return mempty inedges = inn graph idx in do mergelist <- mapM mapfun inedges newnode <- return $! mconcat (node : mergelist) if newnode == node then return Nothing else return (Just (insNode (idx, newnode) graph)) in worklistFastIO workfunc initgraph (nodeRange initgraph)
saltlang/compiler-toolbox
src/Algorithm/Graph/Flow.hs
bsd-3-clause
5,541
0
19
1,209
472
280
192
39
3
-- -- Copyright © 2013-2014 Anchor Systems, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of -- the 3-clause BSD licence. -- module Vaultaire.Types.PassThrough ( PassThrough(..) ) where import Control.Applicative import Data.ByteString (ByteString, pack) import Test.QuickCheck import Vaultaire.Classes.WireFormat newtype PassThrough = PassThrough { unPassThrough :: ByteString } deriving (Eq, Show) instance WireFormat PassThrough where toWire = unPassThrough fromWire = Right . PassThrough instance Arbitrary PassThrough where arbitrary = PassThrough . pack <$> arbitrary
anchor/vaultaire-common
lib/Vaultaire/Types/PassThrough.hs
bsd-3-clause
761
0
7
131
120
75
45
14
0
{- Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} module GHC.Read (module M) where import "base" GHC.Read as M
xwysp/codeworld
codeworld-base/src/GHC/Read.hs
apache-2.0
731
0
4
136
23
17
6
4
0
{-# LANGUAGE BangPatterns, CPP, MagicHash, NondecreasingIndentation #-} ------------------------------------------------------------------------------- -- -- | Main API for compiling plain Haskell source code. -- -- This module implements compilation of a Haskell source. It is -- /not/ concerned with preprocessing of source files; this is handled -- in "DriverPipeline". -- -- There are various entry points depending on what mode we're in: -- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and -- "interactive" mode (GHCi). There are also entry points for -- individual passes: parsing, typechecking/renaming, desugaring, and -- simplification. -- -- All the functions here take an 'HscEnv' as a parameter, but none of -- them return a new one: 'HscEnv' is treated as an immutable value -- from here on in (although it has mutable components, for the -- caches). -- -- Warning messages are dealt with consistently throughout this API: -- during compilation warnings are collected, and before any function -- in @HscMain@ returns, the warnings are either printed, or turned -- into a real compialtion error if the @-Werror@ flag is enabled. -- -- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000 -- ------------------------------------------------------------------------------- module HscMain ( -- * Making an HscEnv newHscEnv -- * Compiling complete source files , Messager, batchMsg , HscStatus (..) , hscCompileOneShot , hscCompileCmmFile , hscCompileCore , genericHscCompileGetFrontendResult , genModDetails , hscSimpleIface , hscWriteIface , hscNormalIface , hscGenHardCode , hscInteractive -- * Running passes separately , hscParse , hscTypecheckRename , hscDesugar , makeSimpleIface , makeSimpleDetails , hscSimplify -- ToDo, shouldn't really export this -- * Support for interactive evaluation , hscParseIdentifier , hscTcRcLookupName , hscTcRnGetInfo , hscCheckSafe , hscGetSafe #ifdef GHCI , hscIsGHCiMonad , hscGetModuleInterface , hscRnImportDecls , hscTcRnLookupRdrName , hscStmt, hscStmtWithLocation , hscDecls, hscDeclsWithLocation , hscTcExpr, hscImport, hscKcType , hscCompileCoreExpr -- * Low-level exports for hooks , hscCompileCoreExpr' #endif -- We want to make sure that we export enough to be able to redefine -- hscFileFrontEnd in client code , hscParse', hscSimplify', hscDesugar', tcRnModule' , getHscEnv , hscSimpleIface', hscNormalIface' , oneShotMsg , hscFileFrontEnd, genericHscFrontend, dumpIfaceStats ) where #ifdef GHCI import Id import BasicTypes ( HValue ) import ByteCodeGen ( byteCodeGen, coreExprToBCOs ) import Linker import CoreTidy ( tidyExpr ) import Type ( Type, Kind ) import CoreLint ( lintInteractiveExpr ) import VarEnv ( emptyTidyEnv ) import Panic import ConLike import GHC.Exts #endif import Module import Packages import RdrName import HsSyn import CoreSyn import StringBuffer import Parser import Lexer import SrcLoc import TcRnDriver import TcIface ( typecheckIface ) import TcRnMonad import IfaceEnv ( initNameCache ) import LoadIface ( ifaceStats, initExternalPackageState ) import PrelInfo import MkIface import Desugar import SimplCore import TidyPgm import CorePrep import CoreToStg ( coreToStg ) import qualified StgCmm ( codeGen ) import StgSyn import CostCentre import ProfInit import TyCon import Name import SimplStg ( stg2stg ) import Cmm import CmmParse ( parseCmmFile ) import CmmBuildInfoTables import CmmPipeline import CmmInfo import CodeOutput import NameEnv ( emptyNameEnv ) import NameSet ( emptyNameSet ) import InstEnv import FamInstEnv import Fingerprint ( Fingerprint ) import Hooks import DynFlags import ErrUtils import Outputable import HscStats ( ppSourceStats ) import HscTypes import FastString import UniqSupply import Bag import Exception import qualified Stream import Stream (Stream) import Util import Data.List import Control.Monad import Data.Maybe import Data.IORef import System.FilePath as FilePath import System.Directory import qualified Data.Map as Map #include "HsVersions.h" {- ********************************************************************** %* * Initialisation %* * %********************************************************************* -} newHscEnv :: DynFlags -> IO HscEnv newHscEnv dflags = do eps_var <- newIORef initExternalPackageState us <- mkSplitUniqSupply 'r' nc_var <- newIORef (initNameCache us knownKeyNames) fc_var <- newIORef emptyModuleEnv return HscEnv { hsc_dflags = dflags, hsc_targets = [], hsc_mod_graph = [], hsc_IC = emptyInteractiveContext dflags, hsc_HPT = emptyHomePackageTable, hsc_EPS = eps_var, hsc_NC = nc_var, hsc_FC = fc_var, hsc_type_env_var = Nothing } -- ----------------------------------------------------------------------------- getWarnings :: Hsc WarningMessages getWarnings = Hsc $ \_ w -> return (w, w) clearWarnings :: Hsc () clearWarnings = Hsc $ \_ _ -> return ((), emptyBag) logWarnings :: WarningMessages -> Hsc () logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w) getHscEnv :: Hsc HscEnv getHscEnv = Hsc $ \e w -> return (e, w) handleWarnings :: Hsc () handleWarnings = do dflags <- getDynFlags w <- getWarnings liftIO $ printOrThrowWarnings dflags w clearWarnings -- | log warning in the monad, and if there are errors then -- throw a SourceError exception. logWarningsReportErrors :: Messages -> Hsc () logWarningsReportErrors (warns,errs) = do logWarnings warns when (not $ isEmptyBag errs) $ throwErrors errs -- | Throw some errors. throwErrors :: ErrorMessages -> Hsc a throwErrors = liftIO . throwIO . mkSrcErr -- | Deal with errors and warnings returned by a compilation step -- -- In order to reduce dependencies to other parts of the compiler, functions -- outside the "main" parts of GHC return warnings and errors as a parameter -- and signal success via by wrapping the result in a 'Maybe' type. This -- function logs the returned warnings and propagates errors as exceptions -- (of type 'SourceError'). -- -- This function assumes the following invariants: -- -- 1. If the second result indicates success (is of the form 'Just x'), -- there must be no error messages in the first result. -- -- 2. If there are no error messages, but the second result indicates failure -- there should be warnings in the first result. That is, if the action -- failed, it must have been due to the warnings (i.e., @-Werror@). ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a ioMsgMaybe ioA = do ((warns,errs), mb_r) <- liftIO ioA logWarnings warns case mb_r of Nothing -> throwErrors errs Just r -> ASSERT( isEmptyBag errs ) return r -- | like ioMsgMaybe, except that we ignore error messages and return -- 'Nothing' instead. ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a) ioMsgMaybe' ioA = do ((warns,_errs), mb_r) <- liftIO $ ioA logWarnings warns return mb_r -- ----------------------------------------------------------------------------- -- | Lookup things in the compiler's environment #ifdef GHCI hscTcRnLookupRdrName :: HscEnv -> Located RdrName -> IO [Name] hscTcRnLookupRdrName hsc_env0 rdr_name = runInteractiveHsc hsc_env0 $ do { hsc_env <- getHscEnv ; ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name } #endif hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing) hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe' $ tcRnLookupName hsc_env name -- ignore errors: the only error we're likely to get is -- "name not found", and the Maybe in the return type -- is used to indicate that. hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst], [FamInst])) hscTcRnGetInfo hsc_env0 name = runInteractiveHsc hsc_env0 $ do { hsc_env <- getHscEnv ; ioMsgMaybe' $ tcRnGetInfo hsc_env name } #ifdef GHCI hscIsGHCiMonad :: HscEnv -> String -> IO Name hscIsGHCiMonad hsc_env name = runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env name hscGetModuleInterface :: HscEnv -> Module -> IO ModIface hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe $ getModuleInterface hsc_env mod -- ----------------------------------------------------------------------------- -- | Rename some import declarations hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe $ tcRnImportDecls hsc_env import_decls #endif -- ----------------------------------------------------------------------------- -- | parse a file, returning the abstract syntax hscParse :: HscEnv -> ModSummary -> IO HsParsedModule hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary -- internal version, that doesn't fail due to -Werror hscParse' :: ModSummary -> Hsc HsParsedModule hscParse' mod_summary = do dflags <- getDynFlags let src_filename = ms_hspp_file mod_summary maybe_src_buf = ms_hspp_buf mod_summary -------------------------- Parser ---------------- liftIO $ showPass dflags "Parser" {-# SCC "Parser" #-} do -- sometimes we already have the buffer in memory, perhaps -- because we needed to parse the imports out of it, or get the -- module name. buf <- case maybe_src_buf of Just b -> return b Nothing -> liftIO $ hGetStringBuffer src_filename let loc = mkRealSrcLoc (mkFastString src_filename) 1 1 case unP parseModule (mkPState dflags buf loc) of PFailed span err -> liftIO $ throwOneError (mkPlainErrMsg dflags span err) POk pst rdr_module -> do logWarningsReportErrors (getMessages pst) liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $ ppr rdr_module liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $ ppSourceStats False rdr_module -- To get the list of extra source files, we take the list -- that the parser gave us, -- - eliminate files beginning with '<'. gcc likes to use -- pseudo-filenames like "<built-in>" and "<command-line>" -- - normalise them (elimiante differences between ./f and f) -- - filter out the preprocessed source file -- - filter out anything beginning with tmpdir -- - remove duplicates -- - filter out the .hs/.lhs source filename if we have one -- let n_hspp = FilePath.normalise src_filename srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`)) $ filter (not . (== n_hspp)) $ map FilePath.normalise $ filter (not . (isPrefixOf "<")) $ map unpackFS $ srcfiles pst srcs1 = case ml_hs_file (ms_location mod_summary) of Just f -> filter (/= FilePath.normalise f) srcs0 Nothing -> srcs0 -- sometimes we see source files from earlier -- preprocessing stages that cannot be found, so just -- filter them out: srcs2 <- liftIO $ filterM doesFileExist srcs1 return HsParsedModule { hpm_module = rdr_module, hpm_src_files = srcs2, hpm_annotations = (Map.fromListWith (++) $ annotations pst, Map.fromList $ ((noSrcSpan,comment_q pst) :(annotations_comments pst))) } -- XXX: should this really be a Maybe X? Check under which circumstances this -- can become a Nothing and decide whether this should instead throw an -- exception/signal an error. type RenamedStuff = (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString)) -- | Rename and typecheck a module, additionally returning the renamed syntax hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule -> IO (TcGblEnv, RenamedStuff) hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do tc_result <- tcRnModule' hsc_env mod_summary True rdr_module -- This 'do' is in the Maybe monad! let rn_info = do decl <- tcg_rn_decls tc_result let imports = tcg_rn_imports tc_result exports = tcg_rn_exports tc_result doc_hdr = tcg_doc_hdr tc_result return (decl,imports,exports,doc_hdr) return (tc_result, rn_info) -- wrapper around tcRnModule to handle safe haskell extras tcRnModule' :: HscEnv -> ModSummary -> Bool -> HsParsedModule -> Hsc TcGblEnv tcRnModule' hsc_env sum save_rn_syntax mod = do tcg_res <- {-# SCC "Typecheck-Rename" #-} ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src sum) save_rn_syntax mod -- See Note [Safe Haskell Overlapping Instances Implementation] -- although this is used for more than just that failure case. (tcSafeOK, whyUnsafe) <- liftIO $ readIORef (tcg_safeInfer tcg_res) dflags <- getDynFlags let allSafeOK = safeInferred dflags && tcSafeOK -- end of the safe haskell line, how to respond to user? if not (safeHaskellOn dflags) || (safeInferOn dflags && not allSafeOK) -- if safe Haskell off or safe infer failed, mark unsafe then markUnsafeInfer tcg_res whyUnsafe -- module (could be) safe, throw warning if needed else do tcg_res' <- hscCheckSafeImports tcg_res safe <- liftIO $ fst <$> readIORef (tcg_safeInfer tcg_res') when safe $ do case wopt Opt_WarnSafe dflags of True -> (logWarnings $ unitBag $ mkPlainWarnMsg dflags (warnSafeOnLoc dflags) $ errSafe tcg_res') False | safeHaskell dflags == Sf_Trustworthy && wopt Opt_WarnTrustworthySafe dflags -> (logWarnings $ unitBag $ mkPlainWarnMsg dflags (trustworthyOnLoc dflags) $ errTwthySafe tcg_res') False -> return () return tcg_res' where pprMod t = ppr $ moduleName $ tcg_mod t errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!" errTwthySafe t = quotes (pprMod t) <+> text "is marked as Trustworthy but has been inferred as safe!" -- | Convert a typechecked module to Core hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts hscDesugar hsc_env mod_summary tc_result = runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts hscDesugar' mod_location tc_result = do hsc_env <- getHscEnv r <- ioMsgMaybe $ {-# SCC "deSugar" #-} deSugar hsc_env mod_location tc_result -- always check -Werror after desugaring, this is the last opportunity for -- warnings to arise before the backend. handleWarnings return r -- | Make a 'ModIface' from the results of typechecking. Used when -- not optimising, and the interface doesn't need to contain any -- unfoldings or other cross-module optimisation info. -- ToDo: the old interface is only needed to get the version numbers, -- we should use fingerprint versions instead. makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails -> IO (ModIface,Bool) makeSimpleIface hsc_env maybe_old_iface tc_result details = runHsc hsc_env $ do safe_mode <- hscGetSafeMode tc_result ioMsgMaybe $ do mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) safe_mode details tc_result -- | Make a 'ModDetails' from the results of typechecking. Used when -- typechecking only, as opposed to full compilation. makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result {- ********************************************************************** %* * The main compiler pipeline %* * %********************************************************************* -} {- -------------------------------- The compilation proper -------------------------------- It's the task of the compilation proper to compile Haskell, hs-boot and core files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all (the module is still parsed and type-checked. This feature is mostly used by IDE's and the likes). Compilation can happen in either 'one-shot', 'batch', 'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode targets byte-code. The modes are kept separate because of their different types and meanings: * In 'one-shot' mode, we're only compiling a single file and can therefore discard the new ModIface and ModDetails. This is also the reason it only targets hard-code; compiling to byte-code or nothing doesn't make sense when we discard the result. * 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface and ModDetails. 'Batch' mode doesn't target byte-code since that require us to return the newly compiled byte-code. * 'Nothing' mode has exactly the same type as 'batch' mode but they're still kept separate. This is because compiling to nothing is fairly special: We don't output any interface files, we don't run the simplifier and we don't generate any code. * 'Interactive' mode is similar to 'batch' mode except that we return the compiled byte-code together with the ModIface and ModDetails. Trying to compile a hs-boot file to byte-code will result in a run-time error. This is the only thing that isn't caught by the type-system. -} type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO () genericHscCompileGetFrontendResult :: Bool -- always do basic recompilation check? -> Maybe TcGblEnv -> Maybe Messager -> HscEnv -> ModSummary -> SourceModified -> Maybe ModIface -- Old interface, if available -> (Int,Int) -- (i,n) = module i of n (for msgs) -> IO (Either ModIface (TcGblEnv, Maybe Fingerprint)) genericHscCompileGetFrontendResult always_do_basic_recompilation_check m_tc_result mHscMessage hsc_env mod_summary source_modified mb_old_iface mod_index = do let msg what = case mHscMessage of Just hscMessage -> hscMessage hsc_env mod_index what mod_summary Nothing -> return () skip iface = do msg UpToDate return $ Left iface compile mb_old_hash reason = do msg reason tc_result <- runHsc hsc_env $ genericHscFrontend mod_summary return $ Right (tc_result, mb_old_hash) stable = case source_modified of SourceUnmodifiedAndStable -> True _ -> False case m_tc_result of Just tc_result | not always_do_basic_recompilation_check -> return $ Right (tc_result, Nothing) _ -> do (recomp_reqd, mb_checked_iface) <- {-# SCC "checkOldIface" #-} checkOldIface hsc_env mod_summary source_modified mb_old_iface -- save the interface that comes back from checkOldIface. -- In one-shot mode we don't have the old iface until this -- point, when checkOldIface reads it from the disk. let mb_old_hash = fmap mi_iface_hash mb_checked_iface case mb_checked_iface of Just iface | not (recompileRequired recomp_reqd) -> -- If the module used TH splices when it was last -- compiled, then the recompilation check is not -- accurate enough (#481) and we must ignore -- it. However, if the module is stable (none of -- the modules it depends on, directly or -- indirectly, changed), then we *can* skip -- recompilation. This is why the SourceModified -- type contains SourceUnmodifiedAndStable, and -- it's pretty important: otherwise ghc --make -- would always recompile TH modules, even if -- nothing at all has changed. Stability is just -- the same check that make is doing for us in -- one-shot mode. case m_tc_result of Nothing | mi_used_th iface && not stable -> compile mb_old_hash (RecompBecause "TH") _ -> skip iface _ -> case m_tc_result of Nothing -> compile mb_old_hash recomp_reqd Just tc_result -> return $ Right (tc_result, mb_old_hash) genericHscFrontend :: ModSummary -> Hsc TcGblEnv genericHscFrontend mod_summary = getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary) genericHscFrontend' :: ModSummary -> Hsc TcGblEnv genericHscFrontend' mod_summary = hscFileFrontEnd mod_summary -------------------------------------------------------------- -- Compilers -------------------------------------------------------------- hscCompileOneShot :: HscEnv -> ModSummary -> SourceModified -> IO HscStatus hscCompileOneShot env = lookupHook hscCompileOneShotHook hscCompileOneShot' (hsc_dflags env) env -- Compile Haskell/boot in OneShot mode. hscCompileOneShot' :: HscEnv -> ModSummary -> SourceModified -> IO HscStatus hscCompileOneShot' hsc_env mod_summary src_changed = do -- One-shot mode needs a knot-tying mutable variable for interface -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var. type_env_var <- newIORef emptyNameEnv let mod = ms_mod mod_summary hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) } msg what = oneShotMsg hsc_env' what skip = do msg UpToDate dumpIfaceStats hsc_env' return HscUpToDate compile mb_old_hash reason = runHsc hsc_env' $ do liftIO $ msg reason tc_result <- genericHscFrontend mod_summary guts0 <- hscDesugar' (ms_location mod_summary) tc_result dflags <- getDynFlags case hscTarget dflags of HscNothing -> do when (gopt Opt_WriteInterface dflags) $ liftIO $ do (iface, changed, _details) <- hscSimpleIface hsc_env tc_result mb_old_hash hscWriteIface dflags iface changed mod_summary return HscNotGeneratingCode _ -> case ms_hsc_src mod_summary of t | isHsBootOrSig t -> do (iface, changed, _) <- hscSimpleIface' tc_result mb_old_hash liftIO $ hscWriteIface dflags iface changed mod_summary return (case t of HsBootFile -> HscUpdateBoot HsigFile -> HscUpdateSig HsSrcFile -> panic "hscCompileOneShot Src") _ -> do guts <- hscSimplify' guts0 (iface, changed, _details, cgguts) <- hscNormalIface' guts mb_old_hash liftIO $ hscWriteIface dflags iface changed mod_summary return $ HscRecomp cgguts mod_summary -- XXX This is always False, because in one-shot mode the -- concept of stability does not exist. The driver never -- passes SourceUnmodifiedAndStable in here. stable = case src_changed of SourceUnmodifiedAndStable -> True _ -> False (recomp_reqd, mb_checked_iface) <- {-# SCC "checkOldIface" #-} checkOldIface hsc_env' mod_summary src_changed Nothing -- save the interface that comes back from checkOldIface. -- In one-shot mode we don't have the old iface until this -- point, when checkOldIface reads it from the disk. let mb_old_hash = fmap mi_iface_hash mb_checked_iface case mb_checked_iface of Just iface | not (recompileRequired recomp_reqd) -> -- If the module used TH splices when it was last compiled, -- then the recompilation check is not accurate enough (#481) -- and we must ignore it. However, if the module is stable -- (none of the modules it depends on, directly or indirectly, -- changed), then we *can* skip recompilation. This is why -- the SourceModified type contains SourceUnmodifiedAndStable, -- and it's pretty important: otherwise ghc --make would -- always recompile TH modules, even if nothing at all has -- changed. Stability is just the same check that make is -- doing for us in one-shot mode. if mi_used_th iface && not stable then compile mb_old_hash (RecompBecause "TH") else skip _ -> compile mb_old_hash recomp_reqd -------------------------------------------------------------- -- NoRecomp handlers -------------------------------------------------------------- genModDetails :: HscEnv -> ModIface -> IO ModDetails genModDetails hsc_env old_iface = do new_details <- {-# SCC "tcRnIface" #-} initIfaceCheck hsc_env (typecheckIface old_iface) dumpIfaceStats hsc_env return new_details -------------------------------------------------------------- -- Progress displayers. -------------------------------------------------------------- oneShotMsg :: HscEnv -> RecompileRequired -> IO () oneShotMsg hsc_env recomp = case recomp of UpToDate -> compilationProgressMsg (hsc_dflags hsc_env) $ "compilation IS NOT required" _ -> return () batchMsg :: Messager batchMsg hsc_env mod_index recomp mod_summary = case recomp of MustCompile -> showMsg "Compiling " "" UpToDate | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping " "" | otherwise -> return () RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]") where dflags = hsc_dflags hsc_env showMsg msg reason = compilationProgressMsg dflags $ (showModuleIndex mod_index ++ msg ++ showModMsg dflags (hscTarget dflags) (recompileRequired recomp) mod_summary) ++ reason -------------------------------------------------------------- -- FrontEnds -------------------------------------------------------------- hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv hscFileFrontEnd mod_summary = do hpm <- hscParse' mod_summary hsc_env <- getHscEnv tcg_env <- tcRnModule' hsc_env mod_summary False hpm return tcg_env -------------------------------------------------------------- -- Safe Haskell -------------------------------------------------------------- -- Note [Safe Haskell Trust Check] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Safe Haskell checks that an import is trusted according to the following -- rules for an import of module M that resides in Package P: -- -- * If M is recorded as Safe and all its trust dependencies are OK -- then M is considered safe. -- * If M is recorded as Trustworthy and P is considered trusted and -- all M's trust dependencies are OK then M is considered safe. -- -- By trust dependencies we mean that the check is transitive. So if -- a module M that is Safe relies on a module N that is trustworthy, -- importing module M will first check (according to the second case) -- that N is trusted before checking M is trusted. -- -- This is a minimal description, so please refer to the user guide -- for more details. The user guide is also considered the authoritative -- source in this matter, not the comments or code. -- Note [Safe Haskell Inference] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Safe Haskell does Safe inference on modules that don't have any specific -- safe haskell mode flag. The basic aproach to this is: -- * When deciding if we need to do a Safe language check, treat -- an unmarked module as having -XSafe mode specified. -- * For checks, don't throw errors but return them to the caller. -- * Caller checks if there are errors: -- * For modules explicitly marked -XSafe, we throw the errors. -- * For unmarked modules (inference mode), we drop the errors -- and mark the module as being Unsafe. -- -- It used to be that we only did safe inference on modules that had no Safe -- Haskell flags, but now we perform safe inference on all modules as we want -- to allow users to set the `-fwarn-safe`, `-fwarn-unsafe` and -- `-fwarn-trustworthy-safe` flags on Trustworthy and Unsafe modules so that a -- user can ensure their assumptions are correct and see reasons for why a -- module is safe or unsafe. -- -- This is tricky as we must be careful when we should throw an error compared -- to just warnings. For checking safe imports we manage it as two steps. First -- we check any imports that are required to be safe, then we check all other -- imports to see if we can infer them to be safe. -- | Check that the safe imports of the module being compiled are valid. -- If not we either issue a compilation error if the module is explicitly -- using Safe Haskell, or mark the module as unsafe if we're in safe -- inference mode. hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv hscCheckSafeImports tcg_env = do dflags <- getDynFlags tcg_env' <- checkSafeImports dflags tcg_env checkRULES dflags tcg_env' where checkRULES dflags tcg_env' = do case safeLanguageOn dflags of True -> do -- XSafe: we nuke user written RULES logWarnings $ warns dflags (tcg_rules tcg_env') return tcg_env' { tcg_rules = [] } False -- SafeInferred: user defined RULES, so not safe | safeInferOn dflags && not (null $ tcg_rules tcg_env') -> markUnsafeInfer tcg_env' $ warns dflags (tcg_rules tcg_env') -- Trustworthy OR SafeInferred: with no RULES | otherwise -> return tcg_env' warns dflags rules = listToBag $ map (warnRules dflags) rules warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) = mkPlainWarnMsg dflags loc $ text "Rule \"" <> ftext (unLoc n) <> text "\" ignored" $+$ text "User defined rules are disabled under Safe Haskell" -- | Validate that safe imported modules are actually safe. For modules in the -- HomePackage (the package the module we are compiling in resides) this just -- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules -- that reside in another package we also must check that the external pacakge -- is trusted. See the Note [Safe Haskell Trust Check] above for more -- information. -- -- The code for this is quite tricky as the whole algorithm is done in a few -- distinct phases in different parts of the code base. See -- RnNames.rnImportDecl for where package trust dependencies for a module are -- collected and unioned. Specifically see the Note [RnNames . Tracking Trust -- Transitively] and the Note [RnNames . Trust Own Package]. checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv checkSafeImports dflags tcg_env = do imps <- mapM condense imports' let (safeImps, regImps) = partition (\(_,_,s) -> s) imps -- We want to use the warning state specifically for detecting if safe -- inference has failed, so store and clear any existing warnings. oldErrs <- getWarnings clearWarnings -- Check safe imports are correct safePkgs <- mapM checkSafe safeImps safeErrs <- getWarnings clearWarnings -- Check non-safe imports are correct if inferring safety -- See the Note [Safe Haskell Inference] (infErrs, infPkgs) <- case (safeInferOn dflags) of False -> return (emptyBag, []) True -> do infPkgs <- mapM checkSafe regImps infErrs <- getWarnings clearWarnings return (infErrs, infPkgs) -- restore old errors logWarnings oldErrs case (isEmptyBag safeErrs) of -- Failed safe check False -> liftIO . throwIO . mkSrcErr $ safeErrs -- Passed safe check True -> do let infPassed = isEmptyBag infErrs tcg_env' <- case (not infPassed) of True -> markUnsafeInfer tcg_env infErrs False -> return tcg_env when (packageTrustOn dflags) $ checkPkgTrust dflags pkgReqs let newTrust = pkgTrustReqs safePkgs infPkgs infPassed return tcg_env' { tcg_imports = impInfo `plusImportAvails` newTrust } where impInfo = tcg_imports tcg_env -- ImportAvails imports = imp_mods impInfo -- ImportedMods imports' = moduleEnvToList imports -- (Module, [ImportedModsVal]) pkgReqs = imp_trust_pkgs impInfo -- [PackageKey] condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport) condense (_, []) = panic "HscMain.condense: Pattern match failure!" condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs return (m, l, s) -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport) cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal cond' v1@(m1,_,l1,s1) (_,_,_,s2) | s1 /= s2 = throwErrors $ unitBag $ mkPlainErrMsg dflags l1 (text "Module" <+> ppr m1 <+> (text $ "is imported both as a safe and unsafe import!")) | otherwise = return v1 -- easier interface to work with checkSafe (m, l, _) = fst `fmap` hscCheckSafe' dflags m l -- what pkg's to add to our trust requirements pkgTrustReqs req inf infPassed | safeInferOn dflags && safeHaskell dflags == Sf_None && infPassed = emptyImportAvails { imp_trust_pkgs = catMaybes req ++ catMaybes inf } pkgTrustReqs _ _ _ | safeHaskell dflags == Sf_Unsafe = emptyImportAvails pkgTrustReqs req _ _ = emptyImportAvails { imp_trust_pkgs = catMaybes req } -- | Check that a module is safe to import. -- -- We return True to indicate the import is safe and False otherwise -- although in the False case an exception may be thrown first. hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO Bool hscCheckSafe hsc_env m l = runHsc hsc_env $ do dflags <- getDynFlags pkgs <- snd `fmap` hscCheckSafe' dflags m l when (packageTrustOn dflags) $ checkPkgTrust dflags pkgs errs <- getWarnings return $ isEmptyBag errs -- | Return if a module is trusted and the pkgs it depends on to be trusted. hscGetSafe :: HscEnv -> Module -> SrcSpan -> IO (Bool, [PackageKey]) hscGetSafe hsc_env m l = runHsc hsc_env $ do dflags <- getDynFlags (self, pkgs) <- hscCheckSafe' dflags m l good <- isEmptyBag `fmap` getWarnings clearWarnings -- don't want them printed... let pkgs' | Just p <- self = p:pkgs | otherwise = pkgs return (good, pkgs') -- | Is a module trusted? If not, throw or log errors depending on the type. -- Return (regardless of trusted or not) if the trust type requires the modules -- own package be trusted and a list of other packages required to be trusted -- (these later ones haven't been checked) but the own package trust has been. hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageKey, [PackageKey]) hscCheckSafe' dflags m l = do (tw, pkgs) <- isModSafe m l case tw of False -> return (Nothing, pkgs) True | isHomePkg m -> return (Nothing, pkgs) | otherwise -> return (Just $ modulePackageKey m, pkgs) where isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageKey]) isModSafe m l = do iface <- lookup' m case iface of -- can't load iface to check trust! Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l $ text "Can't load the interface file for" <+> ppr m <> text ", to check that it can be safely imported" -- got iface, check trust Just iface' -> let trust = getSafeMode $ mi_trust iface' trust_own_pkg = mi_trust_pkg iface' -- check module is trusted safeM = trust `elem` [Sf_Safe, Sf_Trustworthy] -- check package is trusted safeP = packageTrusted trust trust_own_pkg m -- pkg trust reqs pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface' -- General errors we throw but Safe errors we log errs = case (safeM, safeP) of (True, True ) -> emptyBag (True, False) -> pkgTrustErr (False, _ ) -> modTrustErr in do logWarnings errs return (trust == Sf_Trustworthy, pkgRs) where pkgTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The package (" <> ppr (modulePackageKey m) <> text ") the module resides in isn't trusted." ] modTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The module itself isn't safe." ] -- | Check the package a module resides in is trusted. Safe compiled -- modules are trusted without requiring that their package is trusted. For -- trustworthy modules, modules in the home package are trusted but -- otherwise we check the package trust flag. packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool packageTrusted Sf_None _ _ = False -- shouldn't hit these cases packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness. packageTrusted _ _ _ | not (packageTrustOn dflags) = True packageTrusted Sf_Safe False _ = True packageTrusted _ _ m | isHomePkg m = True | otherwise = trusted $ getPackageDetails dflags (modulePackageKey m) lookup' :: Module -> Hsc (Maybe ModIface) lookup' m = do hsc_env <- getHscEnv hsc_eps <- liftIO $ hscEPS hsc_env let pkgIfaceT = eps_PIT hsc_eps homePkgT = hsc_HPT hsc_env iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m #ifdef GHCI -- the 'lookupIfaceByModule' method will always fail when calling from GHCi -- as the compiler hasn't filled in the various module tables -- so we need to call 'getModuleInterface' to load from disk iface' <- case iface of Just _ -> return iface Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m) return iface' #else return iface #endif isHomePkg :: Module -> Bool isHomePkg m | thisPackage dflags == modulePackageKey m = True | otherwise = False -- | Check the list of packages are trusted. checkPkgTrust :: DynFlags -> [PackageKey] -> Hsc () checkPkgTrust dflags pkgs = case errors of [] -> return () _ -> (liftIO . throwIO . mkSrcErr . listToBag) errors where errors = catMaybes $ map go pkgs go pkg | trusted $ getPackageDetails dflags pkg = Nothing | otherwise = Just $ mkErrMsg dflags noSrcSpan (pkgQual dflags) $ text "The package (" <> ppr pkg <> text ") is required" <> text " to be trusted but it isn't!" -- | Set module to unsafe and (potentially) wipe trust information. -- -- Make sure to call this method to set a module to inferred unsafe, it should -- be a central and single failure method. We only wipe the trust information -- when we aren't in a specific Safe Haskell mode. -- -- While we only use this for recording that a module was inferred unsafe, we -- may call it on modules using Trustworthy or Unsafe flags so as to allow -- warning flags for safety to function correctly. See Note [Safe Haskell -- Inference]. markUnsafeInfer :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv markUnsafeInfer tcg_env whyUnsafe = do dflags <- getDynFlags when (wopt Opt_WarnUnsafe dflags) (logWarnings $ unitBag $ mkPlainWarnMsg dflags (warnUnsafeOnLoc dflags) (whyUnsafe' dflags)) liftIO $ writeIORef (tcg_safeInfer tcg_env) (False, whyUnsafe) -- NOTE: Only wipe trust when not in an explicity safe haskell mode. Other -- times inference may be on but we are in Trustworthy mode -- so we want -- to record safe-inference failed but not wipe the trust dependencies. case safeHaskell dflags == Sf_None of True -> return $ tcg_env { tcg_imports = wiped_trust } False -> return tcg_env where wiped_trust = (tcg_imports tcg_env) { imp_trust_pkgs = [] } pprMod = ppr $ moduleName $ tcg_mod tcg_env whyUnsafe' df = vcat [ quotes pprMod <+> text "has been inferred as unsafe!" , text "Reason:" , nest 4 $ (vcat $ badFlags df) $+$ (vcat $ pprErrMsgBagWithLoc whyUnsafe) $+$ (vcat $ badInsts $ tcg_insts tcg_env) ] badFlags df = concat $ map (badFlag df) unsafeFlagsForInfer badFlag df (str,loc,on,_) | on df = [mkLocMessage SevOutput (loc df) $ text str <+> text "is not allowed in Safe Haskell"] | otherwise = [] badInsts insts = concat $ map badInst insts checkOverlap (NoOverlap _) = False checkOverlap _ = True badInst ins | checkOverlap (overlapMode (is_flag ins)) = [mkLocMessage SevOutput (nameSrcSpan $ getName $ is_dfun ins) $ ppr (overlapMode $ is_flag ins) <+> text "overlap mode isn't allowed in Safe Haskell"] | otherwise = [] -- | Figure out the final correct safe haskell mode hscGetSafeMode :: TcGblEnv -> Hsc SafeHaskellMode hscGetSafeMode tcg_env = do dflags <- getDynFlags liftIO $ finalSafeMode dflags tcg_env -------------------------------------------------------------- -- Simplifiers -------------------------------------------------------------- hscSimplify :: HscEnv -> ModGuts -> IO ModGuts hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts hscSimplify' :: ModGuts -> Hsc ModGuts hscSimplify' ds_result = do hsc_env <- getHscEnv {-# SCC "Core2Core" #-} liftIO $ core2core hsc_env ds_result -------------------------------------------------------------- -- Interface generators -------------------------------------------------------------- hscSimpleIface :: HscEnv -> TcGblEnv -> Maybe Fingerprint -> IO (ModIface, Bool, ModDetails) hscSimpleIface hsc_env tc_result mb_old_iface = runHsc hsc_env $ hscSimpleIface' tc_result mb_old_iface hscSimpleIface' :: TcGblEnv -> Maybe Fingerprint -> Hsc (ModIface, Bool, ModDetails) hscSimpleIface' tc_result mb_old_iface = do hsc_env <- getHscEnv details <- liftIO $ mkBootModDetailsTc hsc_env tc_result safe_mode <- hscGetSafeMode tc_result (new_iface, no_change) <- {-# SCC "MkFinalIface" #-} ioMsgMaybe $ mkIfaceTc hsc_env mb_old_iface safe_mode details tc_result -- And the answer is ... liftIO $ dumpIfaceStats hsc_env return (new_iface, no_change, details) hscNormalIface :: HscEnv -> ModGuts -> Maybe Fingerprint -> IO (ModIface, Bool, ModDetails, CgGuts) hscNormalIface hsc_env simpl_result mb_old_iface = runHsc hsc_env $ hscNormalIface' simpl_result mb_old_iface hscNormalIface' :: ModGuts -> Maybe Fingerprint -> Hsc (ModIface, Bool, ModDetails, CgGuts) hscNormalIface' simpl_result mb_old_iface = do hsc_env <- getHscEnv (cg_guts, details) <- {-# SCC "CoreTidy" #-} liftIO $ tidyProgram hsc_env simpl_result -- BUILD THE NEW ModIface and ModDetails -- and emit external core if necessary -- This has to happen *after* code gen so that the back-end -- info has been set. Not yet clear if it matters waiting -- until after code output (new_iface, no_change) <- {-# SCC "MkFinalIface" #-} ioMsgMaybe $ mkIface hsc_env mb_old_iface details simpl_result liftIO $ dumpIfaceStats hsc_env -- Return the prepared code. return (new_iface, no_change, details, cg_guts) -------------------------------------------------------------- -- BackEnd combinators -------------------------------------------------------------- hscWriteIface :: DynFlags -> ModIface -> Bool -> ModSummary -> IO () hscWriteIface dflags iface no_change mod_summary = do let ifaceFile = ml_hi_file (ms_location mod_summary) unless no_change $ {-# SCC "writeIface" #-} writeIfaceFile dflags ifaceFile iface whenGeneratingDynamicToo dflags $ do -- TODO: We should do a no_change check for the dynamic -- interface file too -- TODO: Should handle the dynamic hi filename properly let dynIfaceFile = replaceExtension ifaceFile (dynHiSuf dflags) dynIfaceFile' = addBootSuffix_maybe (mi_boot iface) dynIfaceFile dynDflags = dynamicTooMkDynamicDynFlags dflags writeIfaceFile dynDflags dynIfaceFile' iface -- | Compile to hard-code. hscGenHardCode :: HscEnv -> CgGuts -> ModSummary -> FilePath -> IO (FilePath, Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f hscGenHardCode hsc_env cgguts mod_summary output_filename = do let CgGuts{ -- This is the last use of the ModGuts in a compilation. -- From now on, we just use the bits we need. cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_foreign = foreign_stubs0, cg_dep_pkgs = dependencies, cg_hpc_info = hpc_info } = cgguts dflags = hsc_dflags hsc_env location = ms_location mod_summary data_tycons = filter isDataTyCon tycons -- cg_tycons includes newtypes, for the benefit of External Core, -- but we don't generate any code for newtypes ------------------- -- PREPARE FOR CODE GENERATION -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} corePrepPgm hsc_env location core_binds data_tycons ; ----------------- Convert to STG ------------------ (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-} myCoreToStg dflags this_mod prepd_binds let prof_init = profilingInitCode this_mod cost_centre_info foreign_stubs = foreign_stubs0 `appendStubC` prof_init ------------------ Code generation ------------------ -- The back-end is streamed: each top-level function goes -- from Stg all the way to asm before dealing with the next -- top-level function, so showPass isn't very useful here. -- Hence we have one showPass for the whole backend, the -- next showPass after this will be "Assembler". showPass dflags "CodeGen" cmms <- {-# SCC "StgCmm" #-} doCodeGen hsc_env this_mod data_tycons cost_centre_info stg_binds hpc_info ------------------ Code output ----------------------- rawcmms0 <- {-# SCC "cmmToRawCmm" #-} cmmToRawCmm dflags cmms let dump a = do dumpIfSet_dyn dflags Opt_D_dump_cmm_raw "Raw Cmm" (ppr a) return a rawcmms1 = Stream.mapM dump rawcmms0 (output_filename, (_stub_h_exists, stub_c_exists)) <- {-# SCC "codeOutput" #-} codeOutput dflags this_mod output_filename location foreign_stubs dependencies rawcmms1 return (output_filename, stub_c_exists) hscInteractive :: HscEnv -> CgGuts -> ModSummary -> IO (Maybe FilePath, CompiledByteCode, ModBreaks) #ifdef GHCI hscInteractive hsc_env cgguts mod_summary = do let dflags = hsc_dflags hsc_env let CgGuts{ -- This is the last use of the ModGuts in a compilation. -- From now on, we just use the bits we need. cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_foreign = foreign_stubs, cg_modBreaks = mod_breaks } = cgguts location = ms_location mod_summary data_tycons = filter isDataTyCon tycons -- cg_tycons includes newtypes, for the benefit of External Core, -- but we don't generate any code for newtypes ------------------- -- PREPARE FOR CODE GENERATION -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} corePrepPgm hsc_env location core_binds data_tycons ----------------- Generate byte code ------------------ comp_bc <- byteCodeGen dflags this_mod prepd_binds data_tycons mod_breaks ------------------ Create f-x-dynamic C-side stuff --- (_istub_h_exists, istub_c_exists) <- outputForeignStubs dflags this_mod location foreign_stubs return (istub_c_exists, comp_bc, mod_breaks) #else hscInteractive _ _ = panic "GHC not compiled with interpreter" #endif ------------------------------ hscCompileCmmFile :: HscEnv -> FilePath -> FilePath -> IO () hscCompileCmmFile hsc_env filename output_filename = runHsc hsc_env $ do let dflags = hsc_dflags hsc_env cmm <- ioMsgMaybe $ parseCmmFile dflags filename liftIO $ do us <- mkSplitUniqSupply 'S' let initTopSRT = initUs_ us emptySRT dumpIfSet_dyn dflags Opt_D_dump_cmm "Parsed Cmm" (ppr cmm) (_, cmmgroup) <- cmmPipeline hsc_env initTopSRT cmm rawCmms <- cmmToRawCmm dflags (Stream.yield cmmgroup) _ <- codeOutput dflags no_mod output_filename no_loc NoStubs [] rawCmms return () where no_mod = panic "hscCmmFile: no_mod" no_loc = ModLocation{ ml_hs_file = Just filename, ml_hi_file = panic "hscCmmFile: no hi file", ml_obj_file = panic "hscCmmFile: no obj file" } -------------------- Stuff for new code gen --------------------- doCodeGen :: HscEnv -> Module -> [TyCon] -> CollectedCCs -> [StgBinding] -> HpcInfo -> IO (Stream IO CmmGroup ()) -- Note we produce a 'Stream' of CmmGroups, so that the -- backend can be run incrementally. Otherwise it generates all -- the C-- up front, which has a significant space cost. doCodeGen hsc_env this_mod data_tycons cost_centre_info stg_binds hpc_info = do let dflags = hsc_dflags hsc_env let cmm_stream :: Stream IO CmmGroup () cmm_stream = {-# SCC "StgCmm" #-} StgCmm.codeGen dflags this_mod data_tycons cost_centre_info stg_binds hpc_info -- codegen consumes a stream of CmmGroup, and produces a new -- stream of CmmGroup (not necessarily synchronised: one -- CmmGroup on input may produce many CmmGroups on output due -- to proc-point splitting). let dump1 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm "Cmm produced by new codegen" (ppr a) return a ppr_stream1 = Stream.mapM dump1 cmm_stream -- We are building a single SRT for the entire module, so -- we must thread it through all the procedures as we cps-convert them. us <- mkSplitUniqSupply 'S' -- When splitting, we generate one SRT per split chunk, otherwise -- we generate one SRT for the whole module. let pipeline_stream | gopt Opt_SplitObjs dflags = {-# SCC "cmmPipeline" #-} let run_pipeline us cmmgroup = do let (topSRT', us') = initUs us emptySRT (topSRT, cmmgroup) <- cmmPipeline hsc_env topSRT' cmmgroup let srt | isEmptySRT topSRT = [] | otherwise = srtToData topSRT return (us', srt ++ cmmgroup) in do _ <- Stream.mapAccumL run_pipeline us ppr_stream1 return () | otherwise = {-# SCC "cmmPipeline" #-} let initTopSRT = initUs_ us emptySRT run_pipeline = cmmPipeline hsc_env in do topSRT <- Stream.mapAccumL run_pipeline initTopSRT ppr_stream1 Stream.yield (srtToData topSRT) let dump2 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm "Output Cmm" $ ppr a return a ppr_stream2 = Stream.mapM dump2 pipeline_stream return ppr_stream2 myCoreToStg :: DynFlags -> Module -> CoreProgram -> IO ( [StgBinding] -- output program , CollectedCCs) -- cost centre info (declared and used) myCoreToStg dflags this_mod prepd_binds = do stg_binds <- {-# SCC "Core2Stg" #-} coreToStg dflags this_mod prepd_binds (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-} stg2stg dflags this_mod stg_binds return (stg_binds2, cost_centre_info) {- ********************************************************************** %* * \subsection{Compiling a do-statement} %* * %********************************************************************* -} {- When the UnlinkedBCOExpr is linked you get an HValue of type *IO [HValue]* When you run it you get a list of HValues that should be the same length as the list of names; add them to the ClosureEnv. A naked expression returns a singleton Name [it]. The stmt is lifted into the IO monad as explained in Note [Interactively-bound Ids in GHCi] in HscTypes -} #ifdef GHCI -- | Compile a stmt all the way to an HValue, but don't run it -- -- We return Nothing to indicate an empty statement (or comment only), not a -- parse error. hscStmt :: HscEnv -> String -> IO (Maybe ([Id], IO [HValue], FixityEnv)) hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1 -- | Compile a stmt all the way to an HValue, but don't run it -- -- We return Nothing to indicate an empty statement (or comment only), not a -- parse error. hscStmtWithLocation :: HscEnv -> String -- ^ The statement -> String -- ^ The source -> Int -- ^ Starting line -> IO (Maybe ([Id], IO [HValue], FixityEnv)) hscStmtWithLocation hsc_env0 stmt source linenumber = runInteractiveHsc hsc_env0 $ do maybe_stmt <- hscParseStmtWithLocation source linenumber stmt case maybe_stmt of Nothing -> return Nothing Just parsed_stmt -> do -- Rename and typecheck it hsc_env <- getHscEnv (ids, tc_expr, fix_env) <- ioMsgMaybe $ tcRnStmt hsc_env parsed_stmt -- Desugar it ds_expr <- ioMsgMaybe $ deSugarExpr hsc_env tc_expr liftIO (lintInteractiveExpr "desugar expression" hsc_env ds_expr) handleWarnings -- Then code-gen, and link it -- It's important NOT to have package 'interactive' as thisPackageKey -- for linking, else we try to link 'main' and can't find it. -- Whereas the linker already knows to ignore 'interactive' let src_span = srcLocSpan interactiveSrcLoc hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr let hval_io = unsafeCoerce# hval :: IO [HValue] return $ Just (ids, hval_io, fix_env) -- | Compile a decls hscDecls :: HscEnv -> String -- ^ The statement -> IO ([TyThing], InteractiveContext) hscDecls hsc_env str = hscDeclsWithLocation hsc_env str "<interactive>" 1 -- | Compile a decls hscDeclsWithLocation :: HscEnv -> String -- ^ The statement -> String -- ^ The source -> Int -- ^ Starting line -> IO ([TyThing], InteractiveContext) hscDeclsWithLocation hsc_env0 str source linenumber = runInteractiveHsc hsc_env0 $ do L _ (HsModule{ hsmodDecls = decls }) <- hscParseThingWithLocation source linenumber parseModule str {- Rename and typecheck it -} hsc_env <- getHscEnv tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env decls {- Grab the new instances -} -- We grab the whole environment because of the overlapping that may have -- been done. See the notes at the definition of InteractiveContext -- (ic_instances) for more details. let defaults = tcg_default tc_gblenv {- Desugar it -} -- We use a basically null location for iNTERACTIVE let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing, ml_hi_file = panic "hsDeclsWithLocation:ml_hi_file", ml_obj_file = panic "hsDeclsWithLocation:ml_hi_file"} ds_result <- hscDesugar' iNTERACTIVELoc tc_gblenv {- Simplify -} simpl_mg <- liftIO $ hscSimplify hsc_env ds_result {- Tidy -} (tidy_cg, mod_details) <- liftIO $ tidyProgram hsc_env simpl_mg let dflags = hsc_dflags hsc_env !CgGuts{ cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_modBreaks = mod_breaks } = tidy_cg !ModDetails { md_insts = cls_insts , md_fam_insts = fam_insts } = mod_details -- Get the *tidied* cls_insts and fam_insts data_tycons = filter isDataTyCon tycons {- Prepare For Code Generation -} -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} liftIO $ corePrepPgm hsc_env iNTERACTIVELoc core_binds data_tycons {- Generate byte code -} cbc <- liftIO $ byteCodeGen dflags this_mod prepd_binds data_tycons mod_breaks let src_span = srcLocSpan interactiveSrcLoc liftIO $ linkDecls hsc_env src_span cbc let tcs = filterOut isImplicitTyCon (mg_tcs simpl_mg) patsyns = mg_patsyns simpl_mg ext_ids = [ id | id <- bindersOfBinds core_binds , isExternalName (idName id) , not (isDFunId id || isImplicitId id) ] -- We only need to keep around the external bindings -- (as decided by TidyPgm), since those are the only ones -- that might be referenced elsewhere. -- The DFunIds are in 'cls_insts' (see Note [ic_tythings] in HscTypes -- Implicit Ids are implicit in tcs tythings = map AnId ext_ids ++ map ATyCon tcs ++ map (AConLike . PatSynCon) patsyns let icontext = hsc_IC hsc_env ictxt = extendInteractiveContext icontext ext_ids tcs cls_insts fam_insts defaults patsyns return (tythings, ictxt) hscImport :: HscEnv -> String -> IO (ImportDecl RdrName) hscImport hsc_env str = runInteractiveHsc hsc_env $ do (L _ (HsModule{hsmodImports=is})) <- hscParseThing parseModule str case is of [L _ i] -> return i _ -> liftIO $ throwOneError $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan $ ptext (sLit "parse error in import declaration") -- | Typecheck an expression (but don't run it) -- Returns its most general type hscTcExpr :: HscEnv -> String -- ^ The expression -> IO Type hscTcExpr hsc_env0 expr = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv maybe_stmt <- hscParseStmt expr case maybe_stmt of Just (L _ (BodyStmt expr _ _ _)) -> ioMsgMaybe $ tcRnExpr hsc_env expr _ -> throwErrors $ unitBag $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan (text "not an expression:" <+> quotes (text expr)) -- | Find the kind of a type -- Currently this does *not* generalise the kinds of the type hscKcType :: HscEnv -> Bool -- ^ Normalise the type -> String -- ^ The type as a string -> IO (Type, Kind) -- ^ Resulting type (possibly normalised) and kind hscKcType hsc_env0 normalise str = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ty <- hscParseType str ioMsgMaybe $ tcRnType hsc_env normalise ty hscParseStmt :: String -> Hsc (Maybe (GhciLStmt RdrName)) hscParseStmt = hscParseThing parseStmt hscParseStmtWithLocation :: String -> Int -> String -> Hsc (Maybe (GhciLStmt RdrName)) hscParseStmtWithLocation source linenumber stmt = hscParseThingWithLocation source linenumber parseStmt stmt hscParseType :: String -> Hsc (LHsType RdrName) hscParseType = hscParseThing parseType #endif hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName) hscParseIdentifier hsc_env str = runInteractiveHsc hsc_env $ hscParseThing parseIdentifier str hscParseThing :: (Outputable thing) => Lexer.P thing -> String -> Hsc thing hscParseThing = hscParseThingWithLocation "<interactive>" 1 hscParseThingWithLocation :: (Outputable thing) => String -> Int -> Lexer.P thing -> String -> Hsc thing hscParseThingWithLocation source linenumber parser str = {-# SCC "Parser" #-} do dflags <- getDynFlags liftIO $ showPass dflags "Parser" let buf = stringToStringBuffer str loc = mkRealSrcLoc (fsLit source) linenumber 1 case unP parser (mkPState dflags buf loc) of PFailed span err -> do let msg = mkPlainErrMsg dflags span err throwErrors $ unitBag msg POk pst thing -> do logWarningsReportErrors (getMessages pst) liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing) return thing hscCompileCore :: HscEnv -> Bool -> SafeHaskellMode -> ModSummary -> CoreProgram -> FilePath -> IO () hscCompileCore hsc_env simplify safe_mode mod_summary binds output_filename = runHsc hsc_env $ do guts <- maybe_simplify (mkModGuts (ms_mod mod_summary) safe_mode binds) (iface, changed, _details, cgguts) <- hscNormalIface' guts Nothing liftIO $ hscWriteIface (hsc_dflags hsc_env) iface changed mod_summary _ <- liftIO $ hscGenHardCode hsc_env cgguts mod_summary output_filename return () where maybe_simplify mod_guts | simplify = hscSimplify' mod_guts | otherwise = return mod_guts -- Makes a "vanilla" ModGuts. mkModGuts :: Module -> SafeHaskellMode -> CoreProgram -> ModGuts mkModGuts mod safe binds = ModGuts { mg_module = mod, mg_boot = False, mg_exports = [], mg_deps = noDependencies, mg_dir_imps = emptyModuleEnv, mg_used_names = emptyNameSet, mg_used_th = False, mg_rdr_env = emptyGlobalRdrEnv, mg_fix_env = emptyFixityEnv, mg_tcs = [], mg_insts = [], mg_fam_insts = [], mg_patsyns = [], mg_rules = [], mg_vect_decls = [], mg_binds = binds, mg_foreign = NoStubs, mg_warns = NoWarnings, mg_anns = [], mg_hpc_info = emptyHpcInfo False, mg_modBreaks = emptyModBreaks, mg_vect_info = noVectInfo, mg_inst_env = emptyInstEnv, mg_fam_inst_env = emptyFamInstEnv, mg_safe_haskell = safe, mg_trust_pkg = False, mg_dependent_files = [] } {- ********************************************************************** %* * Desugar, simplify, convert to bytecode, and link an expression %* * %********************************************************************* -} #ifdef GHCI hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue hscCompileCoreExpr hsc_env = lookupHook hscCompileCoreExprHook hscCompileCoreExpr' (hsc_dflags hsc_env) hsc_env hscCompileCoreExpr' :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue hscCompileCoreExpr' hsc_env srcspan ds_expr | rtsIsProfiled = throwIO (InstallationError "You can't call hscCompileCoreExpr in a profiled compiler") -- Otherwise you get a seg-fault when you run it | otherwise = do { let dflags = hsc_dflags hsc_env {- Simplify it -} ; simpl_expr <- simplifyExpr dflags ds_expr {- Tidy it (temporary, until coreSat does cloning) -} ; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr {- Prepare for codegen -} ; prepd_expr <- corePrepExpr dflags hsc_env tidy_expr {- Lint if necessary -} ; lintInteractiveExpr "hscCompileExpr" hsc_env prepd_expr {- Convert to BCOs -} ; bcos <- coreExprToBCOs dflags (icInteractiveModule (hsc_IC hsc_env)) prepd_expr {- link it -} ; hval <- linkExpr hsc_env srcspan bcos ; return hval } #endif {- ********************************************************************** %* * Statistics on reading interfaces %* * %********************************************************************* -} dumpIfaceStats :: HscEnv -> IO () dumpIfaceStats hsc_env = do eps <- readIORef (hsc_EPS hsc_env) dumpIfSet dflags (dump_if_trace || dump_rn_stats) "Interface statistics" (ifaceStats eps) where dflags = hsc_dflags hsc_env dump_rn_stats = dopt Opt_D_dump_rn_stats dflags dump_if_trace = dopt Opt_D_dump_if_trace dflags {- ********************************************************************** %* * Progress Messages: Module i of n %* * %********************************************************************* -} showModuleIndex :: (Int, Int) -> String showModuleIndex (i,n) = "[" ++ padded ++ " of " ++ n_str ++ "] " where n_str = show n i_str = show i padded = replicate (length n_str - length i_str) ' ' ++ i_str
fmthoma/ghc
compiler/main/HscMain.hs
bsd-3-clause
69,496
0
27
20,790
11,656
5,953
5,703
829
9
-- Menu from XRC demo module Main where import Graphics.UI.WXCore import Graphics.UI.WX main = start gui gui :: IO () gui = do f <- frameLoadRes "xrcmenu.xrc" "menuTest" [] -- Attach event handlers to the menu items loaded above. menuItemOnCommandRes f "new" (onFileNew f) menuItemOnCommandRes f "open" (onFileOpen f) set f [clientSize := sz 400 300] windowShow f return () onFileNew w = do dlg <- dialog w [text := "File New"] ok <- button dlg [text := "Ok"] _ <- showModal dlg (\onPress -> set ok [on command := onPress Nothing]) return () onFileOpen w = do dlg <- dialog w [text := "File Open"] ok <- button dlg [text := "Ok"] _ <- showModal dlg (\onPress -> set ok [on command := onPress Nothing]) return ()
ekmett/wxHaskell
samples/test/XRCControls/XRCMenu.hs
lgpl-2.1
872
0
14
288
307
146
161
25
1
-- | Useful operator (++) = mappend. module Data.Monoid.Operator where import Data.Monoid (Monoid) import Data.Monoid (mappend) import Prelude() (++) :: Monoid a => a -> a -> a (++) = mappend infixr 5 ++
chrisdone/haskellnews
upstream/snap-app/src/Data/Monoid/Operator.hs
bsd-3-clause
207
0
7
37
68
42
26
7
1
{-# LANGUAGE CPP #-} module UnitTests.Distribution.Client.UserConfig ( tests ) where import Control.Exception (bracket) import Data.List (sort, nub) #if !MIN_VERSION_base(4,8,0) import Data.Monoid #endif import System.Directory (getCurrentDirectory, removeDirectoryRecursive, createDirectoryIfMissing) import System.FilePath (takeDirectory) import Test.Tasty import Test.Tasty.HUnit import Distribution.Compat.Environment (lookupEnv, setEnv) import Distribution.Client.Config import Distribution.Utils.NubList (fromNubList) import Distribution.Client.Setup (GlobalFlags (..), InstallFlags (..)) import Distribution.Simple.Setup (ConfigFlags (..), fromFlag) import Distribution.Verbosity (silent) tests :: [TestTree] tests = [ testCase "nullDiffOnCreate" nullDiffOnCreateTest , testCase "canDetectDifference" canDetectDifference , testCase "canUpdateConfig" canUpdateConfig , testCase "doubleUpdateConfig" doubleUpdateConfig ] nullDiffOnCreateTest :: Assertion nullDiffOnCreateTest = bracketTest . const $ do -- Create a new default config file in our test directory. _ <- loadConfig silent mempty -- Now we read it in and compare it against the default. diff <- userConfigDiff mempty assertBool (unlines $ "Following diff should be empty:" : diff) $ null diff canDetectDifference :: Assertion canDetectDifference = bracketTest . const $ do -- Create a new default config file in our test directory. _ <- loadConfig silent mempty cabalFile <- defaultConfigFile appendFile cabalFile "verbose: 0\n" diff <- userConfigDiff mempty assertBool (unlines $ "Should detect a difference:" : diff) $ diff == [ "- verbose: 1", "+ verbose: 0" ] canUpdateConfig :: Assertion canUpdateConfig = bracketTest . const $ do cabalFile <- defaultConfigFile createDirectoryIfMissing True $ takeDirectory cabalFile -- Write a trivial cabal file. writeFile cabalFile "tests: True\n" -- Update the config file. userConfigUpdate silent mempty -- Load it again. updated <- loadConfig silent mempty assertBool ("Field 'tests' should be True") $ fromFlag (configTests $ savedConfigureFlags updated) doubleUpdateConfig :: Assertion doubleUpdateConfig = bracketTest . const $ do -- Create a new default config file in our test directory. _ <- loadConfig silent mempty -- Update it. userConfigUpdate silent mempty userConfigUpdate silent mempty -- Load it again. updated <- loadConfig silent mempty assertBool ("Field 'remote-repo' doesn't contain duplicates") $ listUnique (map show . fromNubList . globalRemoteRepos $ savedGlobalFlags updated) assertBool ("Field 'extra-prog-path' doesn't contain duplicates") $ listUnique (map show . fromNubList . configProgramPathExtra $ savedConfigureFlags updated) assertBool ("Field 'build-summary' doesn't contain duplicates") $ listUnique (map show . fromNubList . installSummaryFile $ savedInstallFlags updated) listUnique :: Ord a => [a] -> Bool listUnique xs = let sorted = sort xs in nub sorted == xs bracketTest :: ((FilePath, FilePath) -> IO ()) -> Assertion bracketTest = bracket testSetup testTearDown where testSetup :: IO (FilePath, FilePath) testSetup = do Just oldHome <- lookupEnv "HOME" testdir <- fmap (++ "/test-user-config") getCurrentDirectory setEnv "HOME" testdir return (oldHome, testdir) testTearDown :: (FilePath, FilePath) -> IO () testTearDown (oldHome, testdir) = do setEnv "HOME" oldHome removeDirectoryRecursive testdir
rimmington/cabal
cabal-install/tests/UnitTests/Distribution/Client/UserConfig.hs
bsd-3-clause
3,652
0
14
716
830
428
402
72
1
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Control.Monad.ST import Data.Primitive main :: IO () main = do let xs :: [Float] = runST $ do barr <- mutableByteArrayFromList [1..fromIntegral n::Float] peekByteArray n barr print xs where n = 13 mutableByteArrayFromList :: forall s a . (Prim a) => [a] -> ST s (MutableByteArray s) mutableByteArrayFromList xs = do arr <- newByteArray (length xs*sizeOf (undefined :: a)) loop arr 0 xs return arr where loop :: MutableByteArray s -> Int -> [a] -> ST s () loop _ _ [] = return () loop arr i (x : xs) = do writeByteArray arr i x loop arr (i+1) xs peekByteArray :: (Prim a) => Int -> MutableByteArray s -> ST s [a] peekByteArray n arr = loop 0 arr where loop :: (Prim a) => Int -> MutableByteArray s -> ST s [a] loop i _ | i >= n = return [] loop i arr = do x <- readByteArray arr i xs <- loop (i+1) arr return (x : xs)
ezyang/ghc
testsuite/tests/deriving/should_compile/T8138.hs
bsd-3-clause
1,120
0
16
413
444
218
226
-1
-1
{-# LANGUAGE ForeignFunctionInterface #-} module T3807Export where import Foreign.C foo :: IO CInt foo = return (3 + read "123") foreign export ccall foo :: IO CInt
urbanslug/ghc
testsuite/tests/dynlibs/T3807Export.hs
bsd-3-clause
170
0
8
32
49
27
22
6
1
module ConstantPool where import Types import Attribute import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as B import Data.Word import Data.Binary.Get import qualified Data.ByteString.UTF8 as UTF8 import Debug.Trace data Constant = ConstClass NameIx | ConstFieldRef ClassIx NameAndTypeIx | ConstMethodRef ClassIx NameAndTypeIx | ConstInterfaceMethodRef ClassIx NameAndTypeIx | ConstString StringIx | ConstInt IntWord | ConstFloat FloatWord | ConstLong HighIntWord LoIntWord | ConstDouble HighFloatWord LoFloatWord | ConstUtf8 String | ConstNameAndType NameIx DescriptorIx | ConstMethodHandle ReferenceKind ReferenceIx | ConstMethodType DescriptorIx | ConstInvokeDynamic BootstrapMethodAttrIx NameAndTypeIx | ConstUnused deriving Show cCONSTANT_Class = 7 cCONSTANT_Fieldref = 9 cCONSTANT_Methodref = 10 cCONSTANT_InterfaceMethodref = 11 cCONSTANT_String = 8 cCONSTANT_Integer = 3 cCONSTANT_Float = 4 cCONSTANT_Long = 5 cCONSTANT_Double = 6 cCONSTANT_NameAndType = 12 cCONSTANT_Utf8 = 1 cCONSTANT_MethodHandle = 15 cCONSTANT_MethodType = 16 cCONSTANT_InvokeDynamic = 18 getRef :: (Word16 -> Word16 -> Constant) -> Get Constant getRef constructor = do class_index <- getWord16be name_and_type_index <- getWord16be return $ constructor class_index name_and_type_index getShortNum constructor = do bytes <- getWord32be return (constructor bytes) getLargeNum :: (Word32 -> Word32 -> Constant) -> Get Constant getLargeNum constructor = do high_bytes <- getWord32be low_bytes <- getWord32be return (constructor high_bytes low_bytes) getConstantPoolType :: Word16 -> Get Constant getConstantPoolType 7 = do name_index <- getWord16be return (ConstClass name_index) getConstantPoolType 9 = getRef ConstFieldRef getConstantPoolType 10 = getRef $ ConstMethodRef getConstantPoolType 11 = getRef ConstInterfaceMethodRef getConstantPoolType 8 = do string_index <- getWord16be return (ConstString string_index) getConstantPoolType 3 = getShortNum ConstInt getConstantPoolType 4 = getShortNum ConstFloat getConstantPoolType 5 = getLargeNum ConstLong getConstantPoolType 6 = getLargeNum ConstDouble getConstantPoolType 12 = do name_index <- getWord16be descriptor_index <- getWord16be return (ConstNameAndType name_index descriptor_index) getConstantPoolType 1 = do length <- getWord16be bytes <- getByteString (fromIntegral length) return (ConstUtf8 $ UTF8.toString bytes) getConstantPoolType 15 = do reference_kind <- getWord8 reference_index <- getWord16be return $ ConstMethodHandle reference_kind reference_index getConstantPoolType 16 = do descriptor_index <- getWord16be return $ ConstMethodType descriptor_index getConstantPoolType 18 = do bootstrap_method_attr_index <- getWord16be name_and_type_index <- getWord16be return $ ConstInvokeDynamic bootstrap_method_attr_index name_and_type_index remainingPool 5 x = x - 2 remainingPool 6 x = x - 2 remainingPool _ x = x - 1 getConstantPool :: Int -> Get [Constant] getConstantPool 1 = return [] getConstantPool x = do tag <- getWord8 info <- getConstantPoolType (fromIntegral tag) next <- getConstantPool (remainingPool tag x) if (tag == cCONSTANT_Double || tag == cCONSTANT_Long) then return $ info:(ConstUnused:next) else return $ info:next getInterfaces 0 = return [] getInterfaces x = do interfaceIndex <- getWord16be rest <- getInterfaces (x - 1) return $ interfaceIndex:rest
cwgreene/javaclassreader
src/ConstantPool.hs
mit
3,557
0
11
618
907
456
451
99
2
{-| Module: Web.OIDC.Client Maintainer: krdlab@gmail.com Stability: experimental -} module Web.OIDC.Client ( -- * OpenID Connect Discovery module Web.OIDC.Client.Discovery -- * Settings and Tokens , OIDC, newOIDC, setCredentials , module Web.OIDC.Client.Tokens -- * Authorization Code Flow , module Web.OIDC.Client.CodeFlow -- * Types and Exceptions , module Web.OIDC.Client.Types -- * Re-exports , module Jose.Jwt ) where import Web.OIDC.Client.CodeFlow import Web.OIDC.Client.Discovery import Web.OIDC.Client.Settings (OIDC, newOIDC, setCredentials) import Web.OIDC.Client.Tokens import Web.OIDC.Client.Types import Jose.Jwt {-# ANN module "HLint: ignore Use import/export shortcut" #-}
krdlab/haskell-oidc-client
src/Web/OIDC/Client.hs
mit
823
0
5
212
114
82
32
15
0
module TQueue ( TQueue, newTQueue, writeTQueue, readTQueue ) where import Control.Concurrent.STM ( STM, TVar, newTVar, writeTVar, readTVar, atomically, retry) data TQueue a = TQueue (TVar [a]) (TVar [a]) newTQueue :: STM (TQueue a) newTQueue = do read <- newTVar [] write <- newTVar [] return (TQueue read write) writeTQueue :: TQueue a -> a -> STM () writeTQueue (TQueue _read write) a = do listend <- readTVar write writeTVar write (a:listend) readTQueue :: TQueue a -> STM a readTQueue (TQueue read write) = do xs <- readTVar read case xs of (x:xs') -> do writeTVar read xs' return x [] -> do ys <- readTVar write case ys of [] -> retry _ -> do let (z:zs) = reverse ys writeTVar write [] writeTVar read zs return z
Forec/learn
2017.3/Parallel Haskell/ch10/TQueue.hs
mit
945
0
21
355
356
174
182
36
3
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} -- | -- Module : Test.CoCo.TypeInfo -- Copyright : (c) 2017 Michael Walker -- License : MIT -- Maintainer : Michael Walker <mike@barrucadu.co.uk> -- Stability : experimental -- Portability : ScopedTypeVariables, TemplateHaskell -- -- Information about types. module Test.CoCo.TypeInfo where import Control.Monad (forM) import Data.Char (isAlpha, toLower) import Data.Proxy (Proxy(..)) import qualified Data.Typeable as T import Language.Haskell.TH.Syntax (Exp(..), Type(..)) import Test.LeanCheck (Listable, list) import Test.CoCo.Type (Dynamic, fromDyn, unsafeToDyn) import Test.CoCo.Util -- | Information about a type. data TypeInfo = TypeInfo { listValues :: [Dynamic] -- ^ Produce a (possibly infinite) list of values of this type. , dynEq :: Dynamic -> Dynamic -> Bool -- ^ Check two dynamic values of this type are equal. , varName :: Char -- ^ Base name for variables of this type. Conflicting names will be -- made distinct with a numeric suffix. } -- | Produce a base name for a variable from a type. -- -- Returns @'z'@ if the type is not in the list. getVariableBaseName :: [(T.TypeRep, TypeInfo)] -> T.TypeRep -> Char getVariableBaseName typeInfos ty = maybe 'z' varName (lookup ty typeInfos) -- | Get values of a type. -- -- Returns @[]@ if the type is not in the list. getTypeValues :: [(T.TypeRep, TypeInfo)] -> T.TypeRep -> [Dynamic] getTypeValues typeInfos ty = maybe [] listValues (lookup ty typeInfos) -- | 'TypeInfo' for @()@, @Bool@, @Char@, @Double@, @Float@, @Int@, -- @Integer@ and @Ordering@; and @[a]@, @Maybe a@, @Either a b@, -- @(a,b)@, and @(a,b,c)@ where all type variables are concrete in the -- first list. defaultTypeInfos :: [(T.TypeRep, TypeInfo)] defaultTypeInfos = $(do c0s <- map constr <$> sequence [[t|()|], [t|Bool|], [t|Char|], [t|Double|], [t|Float|], [t|Int|], [t|Integer|], [t|Ordering|]] c1s <- map constr <$> sequence [[t|[()]|], [t|Maybe()|]] c2s <- map constr <$> sequence [[t|Either()()|], [t|((),())|]] c3s <- map constr <$> sequence [[t|((),(),())|]] let mkapps = map (foldl1 AppT) . sequence let types = c0s ++ mkapps [c1s, c0s] ++ mkapps [c2s, c0s, c0s] ++ mkapps [c3s, c0s, c0s, c0s] infos <- forM types (\ty -> [|makeTypeInfo (Proxy :: Proxy $(pure ty))|]) pure (ListE infos) ) -- | Make the 'TypeInfo' for a listable type. makeTypeInfo :: (Listable a, Eq a, T.Typeable a) => proxy a -> (T.TypeRep, TypeInfo) makeTypeInfo p = (T.typeRep p, TypeInfo { listValues = dynamicListValues p, dynEq = dynamicEq p, varName = variableName p }) -- | Produce dynamic values from a 'Listable' instance. dynamicListValues :: forall a proxy. (Listable a, T.Typeable a) => proxy a -> [Dynamic] dynamicListValues p = map (unsafeToDyn $ T.typeRep p) (list :: [a]) -- | Like 'dynamicListValues' but takes an actual value, not a proxy. dynamicListValues' :: forall a. (Listable a, T.Typeable a) => a -> [Dynamic] dynamicListValues' _ = dynamicListValues (Proxy :: Proxy a) -- | Produce an equality predicate from a type from an 'Eq' instance. dynamicEq :: forall a proxy. (Eq a, T.Typeable a) => proxy a -> Dynamic -> Dynamic -> Bool dynamicEq _ d1 d2 = case (,) <$> fromDyn d1 <*> fromDyn d2 of Just (a1, a2) -> (a1 :: a) == (a2 :: a) Nothing -> False -- | Like 'dynamicEq' but takes an actual value, not a proxy. dynamicEq' :: forall a. (Eq a, T.Typeable a) => a -> Dynamic -> Dynamic -> Bool dynamicEq' _ = dynamicEq (Proxy :: Proxy a) -- | Produce a variable name from a type. This is mostly just @show@ -- of the 'T.TypeRep', but with some special cases. variableName :: forall a proxy. T.Typeable a => proxy a -> Char variableName p | tyrep `elem` intTypes = 'x' | tyrep `elem` floatTypes = 'd' | otherwise = defname where tyrep = T.typeRep p -- groups of types intTypes = [T.typeOf (undefined::Int), T.typeOf (undefined::Integer)] floatTypes = [T.typeOf (undefined::Double), T.typeOf (undefined::Float)] -- default name is the first alpha character in the @show@ of the -- typerep, or "a" if there are none. defname = case filter isAlpha (show tyrep) of (c:_) -> toLower c [] -> 'a' -- | Like 'variableName' but takes an actual value, not a proxy. variableName' :: forall a. T.Typeable a => a -> Char variableName' _ = variableName (Proxy :: Proxy a)
barrucadu/spec
Test/CoCo/TypeInfo.hs
mit
4,583
0
16
1,012
1,216
702
514
54
2
module Main where import Test.Hspec import Test.QuickCheck import Archie import Archie.Types import Archie.Constants import qualified Data.Text as Text import Demo main :: IO () main = hspec $ describe "Testing Archie" $ do -- HUnit/HSpec tests. describe "CSS generator" $ do it "Can generate empty CSS" $ do let sheet = Stylesheet [] renderCss sheet `shouldBe` "" it "Can generate a single style rule" $ do let selector = Selector "#container" let declaration = Declaration (Property "width") (DimensionVal 960 Px) let ruleset = Ruleset (Just selector) (Declarations [declaration]) let statement = RulesetSt ruleset let sheet = Stylesheet [statement] renderCss sheet `shouldBe` "#container{width: 960px;}" describe "JS generator" $ do it "Can generate empty JS" $ do let sheet = Stylesheet [] renderJs sheet `shouldBe` jsPrefix it "Can generate a single static style rule" $ do let selector = Selector "#container" let declaration = Declaration (Property "width") (DimensionVal 960 Px) let ruleset = Ruleset (Just selector) (Declarations [declaration]) let statement = RulesetSt ruleset let sheet = Stylesheet [statement] renderJs sheet `shouldBe` jsPrefix ++ "rules.push(function(cause) {var $el = $('#container');});" it "Can generate a single dynamic style rule" $ do let selector = Selector "#container" let declaration = DeclarationJS (Property "width") (ValueJS Nothing (Property "width") (Selector "body")) let ruleset = Ruleset (Just selector) (Declarations [declaration]) let statement = RulesetSt ruleset let sheet = Stylesheet [statement] renderJs sheet `shouldBe` jsPrefix ++ "rules.push(function(cause) {var $el = $('#container');" ++ "$el.css('width', $('body').css('width'));});" it "Can generate a single dynamic style rule with a function applied" $ do let selector = Selector "#container" let declaration = DeclarationJS (Property "width") (ValueJS (Just (Function "function(val){return val/2}")) (Property "width") (Selector "body")) let ruleset = Ruleset (Just selector) (Declarations [declaration]) let statement = RulesetSt ruleset let sheet = Stylesheet [statement] renderJs sheet `shouldBe` jsPrefix ++ "rules.push(function(cause) {var $el = $('#container');" ++ "$el.css('width', (function(val){return val/2})" ++ "($('body').css('width')));});" runDemo
osdiab/archie
test/Test.hs
mit
2,732
0
23
755
696
328
368
54
1
fizz :: Integer -> String fizz x | x `mod` 15 == 0 = "Fizzbuzz" | x `mod` 3 == 0 = "Fizz" | x `mod` 5 == 0 = "Buzz" | otherwise = show x main = mapM_ (putStrLn) [fizz x | x <- [1..100]]
maggy96/haskell
smaller snippets/fizz.hs
mit
194
0
9
54
116
59
57
7
1
module Main where import System.Environment import Text.ParserCombinators.Parsec hiding (spaces) main :: IO () main = do args <- getArgs putStrLn (readExpr (args !! 0)) symbol :: Parser Char symbol = oneOf "!$%&|*+-/:<=>?@^_~#" readExpr input = case parse (spaces >> symbol) "lisp" input of Left err -> "No match: " ++ show err Right val -> "Found value" spaces :: Parser () spaces = skipMany1 space
tismith/tlisp
write-yourself-a-scheme/listings/listing3.2.hs
mit
422
0
11
87
147
75
72
13
2
module Y2018.M06.D08.Exercise where import Data.Time {-- Okay, we got this here dater.txt file, and we wish to view these columns of data as rows of data. That is to say: transpose this matrix. But with a twist, see? Because the date-times are internally separated by spaces as well, so we need the date-times as date-time units, not as date in one row and time in another row, because that's all awkward, as real-world dater is wont to be. So you have this here dater: --} dater, exDir :: FilePath dater = "dater1.txt" exDir = "Y2018/M06/D08/" -- read in the dater and transpose it so I can look at without going cross-eyed data Dater = Dater { id :: Integer, fln :: String, received :: Day, record :: Integer} deriving (Eq, Ord, Show) readDater :: FilePath -> IO [Dater] readDater file = undefined {-- BONUS ----------------------------------------------------------------- Dater-analysis. Now SOME of the daters aren't formatted so friendly-like. Read those in, too, even, belike. --} cleanThenReadDater :: FilePath -> IO [Dater] cleanThenReadDater file = undefined -- here are the other daters: otherDaters :: [FilePath] otherDaters = map (("dater" ++) . (++ ".txt")) (words "2 3 4") -- Now that you have read in these daters, are there any records that are the -- same across dater-sets? Are there any fln's that are the same?
geophf/1HaskellADay
exercises/HAD/Y2018/M06/D08/Exercise.hs
mit
1,358
0
8
247
169
102
67
14
1
-- Memcached interface. -- Copyright (C) 2005 Evan Martin <martine@danga.com> module Network.Memcache.Protocol ( Server, connect,disconnect,stats -- server-specific commands ) where -- TODO: -- - use exceptions where appropriate for protocol errors -- - expiration time in store import Network.Memcache import qualified Network import Network.Memcache.Key import Network.Memcache.Serializable import System.IO -- | Gather results from action until condition is true. ioUntil :: (a -> Bool) -> IO a -> IO [a] ioUntil stop io = do val <- io if stop val then return [] else do more <- ioUntil stop io return (val:more) -- | Put out a line with \r\n terminator. hPutNetLn :: Handle -> String -> IO () hPutNetLn h str = hPutStr h (str ++ "\r\n") -- | Get a line, stripping \r\n terminator. hGetNetLn :: Handle -> IO [Char] hGetNetLn h = do str <- ioUntil (== '\r') (hGetChar h) hGetChar h -- read following newline return str -- | Put out a command (words with terminator) and flush. hPutCommand :: Handle -> [String] -> IO () hPutCommand h strs = hPutNetLn h (unwords strs) >> hFlush h newtype Server = Server { sHandle :: Handle } -- connect :: String -> Network.Socket.PortNumber -> IO Server connect :: Network.HostName -> Network.PortNumber -> IO Server connect host port = do handle <- Network.connectTo host (Network.PortNumber port) return (Server handle) disconnect :: Server -> IO () disconnect = hClose . sHandle stats :: Server -> IO [(String, String)] stats (Server handle) = do hPutCommand handle ["stats"] statistics <- ioUntil (== "END") (hGetNetLn handle) return $ map (tupelize . stripSTAT) statistics where stripSTAT ('S':'T':'A':'T':' ':x) = x stripSTAT x = x tupelize line = case words line of (key:rest) -> (key, unwords rest) [] -> (line, "") store :: (Key k, Serializable s) => String -> Server -> k -> s -> IO Bool store action (Server handle) key val = do let flags = (0::Int) let exptime = (0::Int) let valstr = toString val let bytes = length valstr let cmd = unwords [action, toKey key, show flags, show exptime, show bytes] hPutNetLn handle cmd hPutNetLn handle valstr hFlush handle response <- hGetNetLn handle return (response == "STORED") getOneValue :: Handle -> IO (Maybe String) getOneValue handle = do s <- hGetNetLn handle case words s of ["VALUE", _, _, sbytes] -> do let count = read sbytes val <- sequence $ take count (repeat $ hGetChar handle) return $ Just val _ -> return Nothing incDec :: (Key k) => String -> Server -> k -> Int -> IO (Maybe Int) incDec cmd (Server handle) key delta = do hPutCommand handle [cmd, toKey key, show delta] response <- hGetNetLn handle case response of "NOT_FOUND" -> return Nothing x -> return $ Just (read x) instance Memcache Server where set = store "set" add = store "add" replace = store "replace" get (Server handle) key = do hPutCommand handle ["get", toKey key] val <- getOneValue handle case val of Nothing -> return Nothing Just val -> do hGetNetLn handle hGetNetLn handle return $ fromString val delete (Server handle) key delta = do hPutCommand handle [toKey key, show delta] response <- hGetNetLn handle return (response == "DELETED") incr = incDec "incr" decr = incDec "decr" -- vim: set ts=2 sw=2 et :
alsonkemp/haskell-memcached
Network/Memcache/Protocol.hs
mit
3,517
0
17
870
1,219
603
616
87
3
module Grails.Parser.BuildConfig ( parse ) where import Text.ParserCombinators.Parsec hiding (parse) import qualified Text.ParserCombinators.Parsec.Token as T import Text.ParserCombinators.Parsec.Language (javaStyle) import Grails.Parser.Common hiding (symbol, comma) import Grails.Types (EIO, Plugins) parse :: FilePath -> EIO Plugins parse = parseFile onlyPlugins onlyPlugins :: Parser Plugins onlyPlugins = try plugins <|> (anyToken >> onlyPlugins) <|> return [] plugins = do symbol "plugins" dependenciesBlock dependenciesBlock = do dss <- braces (many dependency) return (concat dss) dependency = do lexeme scope optional $ lexeme parenL -- ugly ds <- lexeme (depString <|> (depBlock >> return ("", ""))) `sepBy` comma optional $ lexeme parenR optional comma optional depBlock return (filter (not . null . fst) ds) depBlock = do lexeme braceL manyTill anyChar (try (lexeme braceR)) depString = quoted depSpec depSpec = do optional groupId colon a <- artifactId colon v <- version return (a, v) scope = many1 letter groupId = identifier artifactId = identifier version = identifier identifier = many1 (alphaNum <|> oneOf "_-.$") lexer = T.makeTokenParser javaStyle symbol = T.symbol lexer lexeme = T.lexeme lexer braces = T.braces lexer comma = T.comma lexer
mbezjak/grailsproject
src/Grails/Parser/BuildConfig.hs
mit
1,372
0
15
287
458
234
224
47
1
{-# LANGUAGE BangPatterns #-} -- | Provides utility functions for working with 'SassValues' module Text.Sass.Values.Utils ( combineSassValues , Lib.SassOp (..) ) where import qualified Bindings.Libsass as Lib import System.IO.Unsafe import Text.Sass.Values import Text.Sass.Values.Internal -- | Combines two 'SassValue's using specified operator. -- | -- | Uses 'Lib.sass_value_op'. combineSassValues :: Lib.SassOp -- ^ Operator. -> SassValue -- ^ First value. -> SassValue -- ^ Second value. -> SassValue -- ^ Resulting value. combineSassValues op val1 val2 = unsafePerformIO $ do native1 <- toNativeValue val1 native2 <- toNativeValue val2 combined <- Lib.sass_value_op (fromIntegral $ fromEnum op) native1 native2 !result <- fromNativeValue combined deleteNativeValue native1 deleteNativeValue native2 deleteNativeValue combined return result
jakubfijalkowski/hsass
Text/Sass/Values/Utils.hs
mit
949
0
12
211
174
93
81
22
1
{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE RecordWildCards #-} ----------------------------------------------------------------------------- -- | -- Module : Text.Bibline -- Copyright : (c) 2016 Călin Ardelean -- License : MIT -- -- Maintainer : Călin Ardelean <mmn80cpu@gmail.com> -- Stability : experimental -- Portability : portable -- -- Backend for the bibline console utility. ----------------------------------------------------------------------------- module Text.Bibline ( module Text.Bibline.Parser , Options(..) , SortField(..) , SortOrder(..) , OutputFormat(..) , bibline , match ) where import Control.Monad (unless) import Data.Function (on) import Data.List (sortBy) import Data.Maybe (fromJust) import Data.Text (Text, pack) import qualified Data.Text as T import qualified Data.Text.IO as T import Pipes import Pipes.Parse (runStateT) import qualified Pipes.Prelude as P import qualified Pipes.Text as PT import qualified Pipes.Text.IO as PT import System.IO (hPrint, hPutStrLn, stderr) import System.Process (spawnCommand) import Text.Bibline.Parser import Text.Read (Lexeme (..), lexP, parens, readPrec) data OutputFormat = Compact | BibTeX deriving (Eq) data SortField = Unsorted | SortByTitle | SortByAuthor | SortByYear deriving (Eq) instance Read SortField where readPrec = parens $ do Ident s <- lexP return $ case s of "title" -> SortByTitle "author" -> SortByAuthor "year" -> SortByYear _ -> Unsorted data SortOrder = SortAsc | SortDesc deriving (Eq) instance Read SortOrder where readPrec = parens $ do Ident s <- lexP return $ case s of "asc" -> SortAsc _ -> SortDesc data Options = Options { optType :: Maybe BibEntryType , optKey :: String , optAuthor :: String , optTitle :: String , optYear :: String , optTag :: String , optSortBy :: SortField , optSortOrder :: SortOrder , optFormat :: OutputFormat , optOpen :: Bool , optOpenCmd :: String } bibline :: Options -> IO () bibline opt@Options {..} = do let format = pack . if optFormat == Compact then showEntryCompact else show let noFilter = null optType && all null [optKey, optAuthor, optTitle, optYear, optTag] let fp = biblined PT.stdin >-> P.filter (if noFilter then const True else trickle opt) let runPipe p = runEffect $ for (p >-> (if optOpen then openFilePipe optOpenCmd else cat) >-> P.map format) $ liftIO . T.putStr (r, p) <- if optSortBy == Unsorted then runPipe fp else do (bs, r) <- P.toListM' fp let bs' = sortItems optSortBy optSortOrder bs runPipe $ each bs' return r unless (r == BibParseResultOk) $ do hPrint stderr r (used, p') <- runStateT PT.isEndOfChars p unless used $ do hPutStrLn stderr "Unused input:" runEffect $ for p' (liftIO . T.hPutStr stderr) openFilePipe :: String -> Pipe BibItem BibItem IO r openFilePipe cmd = do b <- await let f = stripParens $ bibFile b lift $ unless (T.null f) $ do _ <- spawnCommand $ cmd ++ " \"" ++ T.unpack f ++ "\"" return () yield b cat sortItems :: SortField -> SortOrder -> [BibItem] -> [BibItem] sortItems sf so = sortBy (cmp `on` fld) where cmp = if so == SortAsc then compare else flip compare fld = case sf of SortByAuthor -> T.intercalate (pack " and ") . map (pack . show) . bibAuthor SortByTitle -> bibTitle _ -> bibYear trickle :: Options -> BibItem -> Bool trickle Options {..} BibEntry {..} = (null optType || fromJust optType == entryType) && (null optKey || match (pack optKey) (stripParens entryKey)) && (null optAuthor || any (match $ pack optAuthor) (pack . show <$> bibAuthor)) && (null optTitle || match (pack optTitle) (stripParens bibTitle)) && (null optYear || match (pack optYear) (stripParens bibYear)) && (null optTag || any (match $ pack optTag) bibKeywords) trickle _ _ = True match :: Text -> Text -> Bool match pat txt = go pats (T.toLower txt) where wildchar c = c == '?' || c == '*' pats = T.groupBy (\c1 c2 -> not $ wildchar c1 || wildchar c2) (T.toLower pat) go ps str = case ps of [] -> True p:ps' -> if | p == T.singleton '*' -> case ps' of [] -> True p':ps'' -> let (_, str2) = T.breakOn p' str in not (T.null str2) && go ps'' (T.drop (T.length p') str2) | p == T.singleton '?' -> case T.uncons str of Nothing -> False Just (_, ss) -> go ps' ss | otherwise -> case T.stripPrefix p str of Nothing -> False Just str' -> go ps' str'
mmn80/bibline
src/Text/Bibline.hs
mit
5,215
0
23
1,701
1,622
851
771
122
7
-- | Module providing various functions popular in quantum calculations, but -- not implemented in "Numeric.LinearAlgebra". module Hoqus.MtxFun where import Numeric.LinearAlgebra.Data import Numeric.LinearAlgebra -- | Trace of a matrix. This function ignores the non-sqare part of the matrix. trace :: Matrix C -> C trace = sum.toList.takeDiag -- | Logarithm of a matrix. Based on 'Numeric.LinearAlgebra.matFunc' function -- from "Numeric.LinearAlgebra" package. logm :: Matrix C -> Matrix C logm = matFunc log
jmiszczak/hoqus
Hoqus/MtxFun.hs
mit
514
0
6
75
66
38
28
7
1