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 : Graphics.X11
-- Copyright : (c) Alastair Reid, 1999-2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- A Haskell binding for the X11 libraries.
--
-----------------------------------------------------------------------------
module Graphics.X11
( module Graphics.X11.Xlib
) where
import Graphics.X11.Xlib
----------------------------------------------------------------
-- End
----------------------------------------------------------------
| mgsloan/X11 | Graphics/X11.hs | bsd-3-clause | 694 | 0 | 5 | 101 | 37 | 30 | 7 | 3 | 0 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>Requester</title>
<maps>
<homeID>requester</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/requester/src/main/javahelp/help_tr_TR/helpset_tr_TR.hs | apache-2.0 | 960 | 77 | 66 | 155 | 404 | 205 | 199 | -1 | -1 |
{-# OPTIONS_JHC -fno-prelude #-}
module Jhc.Inst.Show() where
import Jhc.Basics
import Jhc.Class.Num
import Jhc.Class.Ord
import Jhc.Class.Real
import Jhc.Show
import Jhc.Type.C
-- we convert them to Word or WordMax so the showIntAtBase specialization can occur.
fromIntegral :: (Integral a, Num b) => a -> b
fromIntegral x = fromInteger (toInteger x)
instance Show Word where
showsPrec _ x = showWord x
instance Show Word8 where
showsPrec _ x = showWord (fromIntegral x :: Word)
instance Show Word16 where
showsPrec _ x = showWord (fromIntegral x :: Word)
instance Show Word32 where
showsPrec _ x = showWord (fromIntegral x :: Word)
instance Show Word64 where
showsPrec _ x = showWordMax (fromIntegral x :: WordMax)
instance Show WordPtr where
showsPrec _ x = showWordMax (fromIntegral x :: WordMax)
instance Show WordMax where
showsPrec _ x = showWordMax x
instance Show Int where
showsPrec p x
| p `seq` x `seq` False = undefined
| x < 0 = showParen (p > 6) (showChar '-' . showWord (fromIntegral $ negate x :: Word))
| True = showWord (fromIntegral x :: Word)
instance Show Integer where
showsPrec p x
| p `seq` x `seq` False = undefined
| x < 0 = showParen (p > 6) (showChar '-' . showWordMax (fromIntegral $ negate x :: WordMax))
| True = showWordMax (fromIntegral x :: WordMax)
instance Show Int8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Show Int16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Show Int32 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Show Int64 where
showsPrec p x = showsPrec p (fromIntegral x :: Integer)
instance Show IntPtr where
showsPrec p x = showsPrec p (fromIntegral x :: Integer)
instance Show IntMax where
showsPrec p x = showsPrec p (fromIntegral x :: Integer)
instance Show CSize where
showsPrec p x = showsPrec p (fromIntegral x :: Integer)
instance Show CInt where
showsPrec p x = showsPrec p (fromIntegral x :: Integer)
instance Show CLong where
showsPrec p x = showsPrec p (fromIntegral x :: Integer)
instance Show CChar where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Show CSChar where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Show CUChar where
showsPrec _ x = showWord (fromIntegral x :: Word)
instance Show CUInt where
showsPrec _ x = showWord (fromIntegral x :: Word)
instance Show CULong where
showsPrec _ x = showWordMax (fromIntegral x :: WordMax)
instance Show CWchar where
showsPrec _ x = showWord (fromIntegral x :: Word)
-- specialized base 10 only versions of show
showWord :: Word -> String -> String
showWord w rest = w `seq` case quotRem w 10 of
(n',d) -> n' `seq` d `seq` rest' `seq` if n' == 0 then rest' else showWord n' rest'
where rest' = chr (fromIntegral d + ord '0') : rest
showWordMax :: WordMax -> String -> String
showWordMax w rest = w `seq` case quotRem w 10 of
(n',d) -> n' `seq` d `seq` rest' `seq` if n' == 0 then rest' else showWordMax n' rest'
where rest' = chr (fromIntegral d + ord '0') : rest
| hvr/jhc | lib/jhc/Jhc/Inst/Show.hs | mit | 3,166 | 0 | 15 | 714 | 1,192 | 614 | 578 | 72 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -Wall #-}
module Bug where
import Language.Haskell.TH
-- Warnings should be preserved through recover
main :: IO ()
main = putStrLn $(recover (stringE "splice failed")
[| let x = "a" in let x = "b" in x |])
| sdiehl/ghc | testsuite/tests/th/TH_recover_warns.hs | bsd-3-clause | 284 | 0 | 10 | 72 | 49 | 29 | 20 | 7 | 1 |
{-# LANGUAGE PatternGuards, DeriveFunctor #-}
module IRTS.Lang where
import Control.Monad.State hiding (lift)
import Control.Applicative hiding (Const)
import Idris.Core.TT
import Idris.Core.CaseTree
import Data.List
import Debug.Trace
data Endianness = Native | BE | LE deriving (Show, Eq)
data LVar = Loc Int | Glob Name
deriving (Show, Eq)
-- ASSUMPTION: All variable bindings have unique names here
data LExp = LV LVar
| LApp Bool LExp [LExp] -- True = tail call
| LLazyApp Name [LExp] -- True = tail call
| LLazyExp LExp
| LForce LExp -- make sure Exp is evaluted
| LLet Name LExp LExp -- name just for pretty printing
| LLam [Name] LExp -- lambda, lifted out before compiling
| LProj LExp Int -- projection
| LCon (Maybe LVar) -- Location to reallocate, if available
Int Name [LExp]
| LCase CaseType LExp [LAlt]
| LConst Const
| LForeign FDesc -- Function descriptor (usually name as string)
FDesc -- Return type descriptor
[(FDesc, LExp)] -- first LExp is the FFI type description
| LOp PrimFn [LExp]
| LNothing
| LError String
deriving Eq
data FDesc = FCon Name
| FStr String
| FUnknown
| FIO FDesc
| FApp Name [FDesc]
deriving (Show, Eq)
data Export = ExportData FDesc -- Exported data descriptor (usually string)
| ExportFun Name -- Idris name
FDesc -- Exported function descriptor
FDesc -- Return type descriptor
[FDesc] -- Argument types
deriving (Show, Eq)
data ExportIFace = Export Name -- FFI descriptor
String -- interface file
[Export]
deriving (Show, Eq)
-- Primitive operators. Backends are not *required* to implement all
-- of these, but should report an error if they are unable
data PrimFn = LPlus ArithTy | LMinus ArithTy | LTimes ArithTy
| LUDiv IntTy | LSDiv ArithTy | LURem IntTy | LSRem ArithTy
| LAnd IntTy | LOr IntTy | LXOr IntTy | LCompl IntTy
| LSHL IntTy | LLSHR IntTy | LASHR IntTy
| LEq ArithTy | LLt IntTy | LLe IntTy | LGt IntTy | LGe IntTy
| LSLt ArithTy | LSLe ArithTy | LSGt ArithTy | LSGe ArithTy
| LSExt IntTy IntTy | LZExt IntTy IntTy | LTrunc IntTy IntTy
| LStrConcat | LStrLt | LStrEq | LStrLen
| LIntFloat IntTy | LFloatInt IntTy | LIntStr IntTy | LStrInt IntTy
| LFloatStr | LStrFloat | LChInt IntTy | LIntCh IntTy
| LBitCast ArithTy ArithTy -- Only for values of equal width
| LFExp | LFLog | LFSin | LFCos | LFTan | LFASin | LFACos | LFATan
| LFSqrt | LFFloor | LFCeil | LFNegate
| LStrHead | LStrTail | LStrCons | LStrIndex | LStrRev
| LReadStr | LWriteStr
-- system info
| LSystemInfo
| LFork
| LPar -- evaluate argument anywhere, possibly on another
-- core or another machine. 'id' is a valid implementation
| LExternal Name
| LNoOp
deriving (Show, Eq)
-- Supported target languages for foreign calls
data FCallType = FStatic | FObject | FConstructor
deriving (Show, Eq)
data FType = FArith ArithTy
| FFunction
| FFunctionIO
| FString
| FUnit
| FPtr
| FManagedPtr
| FAny
deriving (Show, Eq)
-- FIXME: Why not use this for all the IRs now?
data LAlt' e = LConCase Int Name [Name] e
| LConstCase Const e
| LDefaultCase e
deriving (Show, Eq, Functor)
type LAlt = LAlt' LExp
data LDecl = LFun [LOpt] Name [Name] LExp -- options, name, arg names, def
| LConstructor Name Int Int -- constructor name, tag, arity
deriving (Show, Eq)
type LDefs = Ctxt LDecl
data LOpt = Inline | NoInline
deriving (Show, Eq)
addTags :: Int -> [(Name, LDecl)] -> (Int, [(Name, LDecl)])
addTags i ds = tag i ds []
where tag i ((n, LConstructor n' (-1) a) : as) acc
= tag (i + 1) as ((n, LConstructor n' i a) : acc)
tag i ((n, LConstructor n' t a) : as) acc
= tag i as ((n, LConstructor n' t a) : acc)
tag i (x : as) acc = tag i as (x : acc)
tag i [] acc = (i, reverse acc)
data LiftState = LS Name Int [(Name, LDecl)]
lname (NS n x) i = NS (lname n i) x
lname (UN n) i = MN i n
lname x i = sMN i (show x ++ "_lam")
liftAll :: [(Name, LDecl)] -> [(Name, LDecl)]
liftAll xs = concatMap (\ (x, d) -> lambdaLift x d) xs
lambdaLift :: Name -> LDecl -> [(Name, LDecl)]
lambdaLift n (LFun opts _ args e)
= let (e', (LS _ _ decls)) = runState (lift args e) (LS n 0 []) in
(n, LFun opts n args e') : decls
lambdaLift n x = [(n, x)]
getNextName :: State LiftState Name
getNextName = do LS n i ds <- get
put (LS n (i + 1) ds)
return (lname n i)
addFn :: Name -> LDecl -> State LiftState ()
addFn fn d = do LS n i ds <- get
put (LS n i ((fn, d) : ds))
lift :: [Name] -> LExp -> State LiftState LExp
lift env (LV v) = return (LV v) -- Lifting happens before these can exist...
lift env (LApp tc (LV (Glob n)) args) = do args' <- mapM (lift env) args
return (LApp tc (LV (Glob n)) args')
lift env (LApp tc f args) = do f' <- lift env f
fn <- getNextName
addFn fn (LFun [Inline] fn env f')
args' <- mapM (lift env) args
return (LApp tc (LV (Glob fn)) (map (LV . Glob) env ++ args'))
lift env (LLazyApp n args) = do args' <- mapM (lift env) args
return (LLazyApp n args')
lift env (LLazyExp (LConst c)) = return (LConst c)
-- lift env (LLazyExp (LApp tc (LV (Glob f)) args))
-- = lift env (LLazyApp f args)
lift env (LLazyExp e) = do e' <- lift env e
let usedArgs = nub $ usedIn env e'
fn <- getNextName
addFn fn (LFun [NoInline] fn usedArgs e')
return (LLazyApp fn (map (LV . Glob) usedArgs))
lift env (LForce e) = do e' <- lift env e
return (LForce e')
lift env (LLet n v e) = do v' <- lift env v
e' <- lift (env ++ [n]) e
return (LLet n v' e')
lift env (LLam args e) = do e' <- lift (env ++ args) e
let usedArgs = nub $ usedIn env e'
fn <- getNextName
addFn fn (LFun [Inline] fn (usedArgs ++ args) e')
return (LApp False (LV (Glob fn)) (map (LV . Glob) usedArgs))
lift env (LProj t i) = do t' <- lift env t
return (LProj t' i)
lift env (LCon loc i n args) = do args' <- mapM (lift env) args
return (LCon loc i n args')
lift env (LCase up e alts) = do alts' <- mapM liftA alts
e' <- lift env e
return (LCase up e' alts')
where
liftA (LConCase i n args e) = do e' <- lift (env ++ args) e
return (LConCase i n args e')
liftA (LConstCase c e) = do e' <- lift env e
return (LConstCase c e')
liftA (LDefaultCase e) = do e' <- lift env e
return (LDefaultCase e')
lift env (LConst c) = return (LConst c)
lift env (LForeign t s args) = do args' <- mapM (liftF env) args
return (LForeign t s args')
where
liftF env (t, e) = do e' <- lift env e
return (t, e')
lift env (LOp f args) = do args' <- mapM (lift env) args
return (LOp f args')
lift env (LError str) = return $ LError str
lift env LNothing = return $ LNothing
allocUnique :: LDefs -> (Name, LDecl) -> (Name, LDecl)
allocUnique defs p@(n, LConstructor _ _ _) = p
allocUnique defs (n, LFun opts fn args e)
= let e' = evalState (findUp e) [] in
(n, LFun opts fn args e')
where
-- Keep track of 'updatable' names in the state, i.e. names whose heap
-- entry may be reused, along with the arity which was there
findUp :: LExp -> State [(Name, Int)] LExp
findUp (LApp t (LV (Glob n)) as)
| Just (LConstructor _ i ar) <- lookupCtxtExact n defs,
ar == length as
= findUp (LCon Nothing i n as)
findUp (LV (Glob n))
| Just (LConstructor _ i 0) <- lookupCtxtExact n defs
= return $ LCon Nothing i n [] -- nullary cons are global, no need to update
findUp (LApp t f as) = LApp t <$> findUp f <*> mapM findUp as
findUp (LLazyApp n as) = LLazyApp n <$> mapM findUp as
findUp (LLazyExp e) = LLazyExp <$> findUp e
findUp (LForce e) = LForce <$> findUp e
-- use assumption that names are unique!
findUp (LLet n val sc) = LLet n <$> findUp val <*> findUp sc
findUp (LLam ns sc) = LLam ns <$> findUp sc
findUp (LProj e i) = LProj <$> findUp e <*> return i
findUp (LCon (Just l) i n es) = LCon (Just l) i n <$> mapM findUp es
findUp (LCon Nothing i n es)
= do avail <- get
v <- findVar [] avail (length es)
LCon v i n <$> mapM findUp es
findUp (LForeign t s es)
= LForeign t s <$> mapM (\ (t, e) -> do e' <- findUp e
return (t, e')) es
findUp (LOp o es) = LOp o <$> mapM findUp es
findUp (LCase Updatable e@(LV (Glob n)) as)
= LCase Updatable e <$> mapM (doUpAlt n) as
findUp (LCase t e as)
= LCase t <$> findUp e <*> mapM findUpAlt as
findUp t = return t
findUpAlt (LConCase i t args rhs) = do avail <- get
rhs' <- findUp rhs
put avail
return $ LConCase i t args rhs'
findUpAlt (LConstCase i rhs) = LConstCase i <$> findUp rhs
findUpAlt (LDefaultCase rhs) = LDefaultCase <$> findUp rhs
doUpAlt n (LConCase i t args rhs)
= do avail <- get
put ((n, length args) : avail)
rhs' <- findUp rhs
put avail
return $ LConCase i t args rhs'
doUpAlt n (LConstCase i rhs) = LConstCase i <$> findUp rhs
doUpAlt n (LDefaultCase rhs) = LDefaultCase <$> findUp rhs
findVar _ [] i = return Nothing
findVar acc ((n, l) : ns) i | l == i = do put (reverse acc ++ ns)
return (Just (Glob n))
findVar acc (n : ns) i = findVar (n : acc) ns i
-- Return variables in list which are used in the expression
usedArg env n | n `elem` env = [n]
| otherwise = []
usedIn :: [Name] -> LExp -> [Name]
usedIn env (LV (Glob n)) = usedArg env n
usedIn env (LApp _ e args) = usedIn env e ++ concatMap (usedIn env) args
usedIn env (LLazyApp n args) = concatMap (usedIn env) args ++ usedArg env n
usedIn env (LLazyExp e) = usedIn env e
usedIn env (LForce e) = usedIn env e
usedIn env (LLet n v e) = usedIn env v ++ usedIn (env \\ [n]) e
usedIn env (LLam ns e) = usedIn (env \\ ns) e
usedIn env (LCon v i n args) = let rest = concatMap (usedIn env) args in
case v of
Nothing -> rest
Just (Glob n) -> usedArg env n ++ rest
usedIn env (LProj t i) = usedIn env t
usedIn env (LCase up e alts) = usedIn env e ++ concatMap (usedInA env) alts
where usedInA env (LConCase i n ns e) = usedIn env e
usedInA env (LConstCase c e) = usedIn env e
usedInA env (LDefaultCase e) = usedIn env e
usedIn env (LForeign _ _ args) = concatMap (usedIn env) (map snd args)
usedIn env (LOp f args) = concatMap (usedIn env) args
usedIn env _ = []
instance Show LExp where
show e = show' [] "" e where
show' env ind (LV (Loc i)) = env!!i
show' env ind (LV (Glob n)) = show n
show' env ind (LLazyApp e args)
= show e ++ "|(" ++ showSep ", " (map (show' env ind) args) ++")"
show' env ind (LApp _ e args)
= show' env ind e ++ "(" ++ showSep ", " (map (show' env ind) args) ++")"
show' env ind (LLazyExp e) = "lazy{ " ++ show' env ind e ++ " }"
show' env ind (LForce e) = "force{ " ++ show' env ind e ++ " }"
show' env ind (LLet n v e)
= "let " ++ show n ++ " = " ++ show' env ind v
++ " in " ++ show' (env ++ [show n]) ind e
show' env ind (LLam args e)
= "\\ " ++ showSep "," (map show args)
++ " => " ++ show' (env ++ (map show args)) ind e
show' env ind (LProj t i) = show t ++ "!" ++ show i
show' env ind (LCon loc i n args)
= atloc loc ++ show n ++ "(" ++ showSep ", " (map (show' env ind) args) ++ ")"
where atloc Nothing = ""
atloc (Just l) = "@" ++ show (LV l) ++ ":"
show' env ind (LCase up e alts)
= "case" ++ update ++ show' env ind e ++ " of \n" ++ fmt alts
where
update = case up of
Shared -> " "
Updatable -> "! "
fmt [] = ""
fmt [alt]
= "\t" ++ ind ++ "| " ++ showAlt env (ind ++ " ") alt
fmt (alt:as)
= "\t" ++ ind ++ "| " ++ showAlt env (ind ++ ". ") alt
++ "\n" ++ fmt as
show' env ind (LConst c) = show c
show' env ind (LForeign ty n args) = concat
[ "foreign{ "
, show n ++ "("
, showSep ", " (map (\(ty,x) -> show' env ind x ++ " : " ++ show ty) args)
, ") : "
, show ty
, " }"
]
show' env ind (LOp f args)
= show f ++ "(" ++ showSep ", " (map (show' env ind) args) ++ ")"
show' env ind (LError str) = "error " ++ show str
show' env ind LNothing = "____"
showAlt env ind (LConCase _ n args e)
= show n ++ "(" ++ showSep ", " (map show args) ++ ") => "
++ show' env ind e
showAlt env ind (LConstCase c e) = show c ++ " => " ++ show' env ind e
showAlt env ind (LDefaultCase e) = "_ => " ++ show' env ind e
| osa1/Idris-dev | src/IRTS/Lang.hs | bsd-3-clause | 14,464 | 0 | 17 | 5,378 | 5,508 | 2,783 | 2,725 | 287 | 22 |
<?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="hi-IN">
<title>Getting started Guide</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> | ccgreen13/zap-extensions | src/org/zaproxy/zap/extension/gettingStarted/resources/help_hi_IN/helpset_hi_IN.hs | apache-2.0 | 967 | 79 | 66 | 158 | 411 | 208 | 203 | -1 | -1 |
-- Test we don't get a cycle for "phantom" superclasses
{-# LANGUAGE ConstraintKinds, MultiParamTypeClasses, FlexibleContexts #-}
module TcOK where
class A cls c where
meth :: cls c => c -> c
class A B c => B c where
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/typecheck/should_compile/tc259.hs | bsd-3-clause | 223 | 0 | 8 | 46 | 51 | 26 | 25 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
module Network.HTTP.Download.VerifiedSpec where
import Crypto.Hash
import Control.Monad (unless)
import Control.Monad.Trans.Reader
import Control.Retry (limitRetries)
import Data.Maybe
import Network.HTTP.Client.Conduit
import Network.HTTP.Download.Verified
import Path
import System.Directory
import System.IO.Temp
import Test.Hspec hiding (shouldNotBe, shouldNotReturn)
-- TODO: share across test files
withTempDir :: (Path Abs Dir -> IO a) -> IO a
withTempDir f = withSystemTempDirectory "NHD_VerifiedSpec" $ \dirFp -> do
dir <- parseAbsDir dirFp
f dir
-- | An example path to download the exampleReq.
getExamplePath :: Path Abs Dir -> IO (Path Abs File)
getExamplePath dir = do
file <- parseRelFile "cabal-install-1.22.4.0.tar.gz"
return (dir </> file)
-- | An example DownloadRequest that uses a SHA1
exampleReq :: DownloadRequest
exampleReq = fromMaybe (error "exampleReq") $ do
req <- parseUrl "http://download.fpcomplete.com/stackage-cli/linux64/cabal-install-1.22.4.0.tar.gz"
return DownloadRequest
{ drRequest = req
, drHashChecks = [exampleHashCheck]
, drLengthCheck = Just exampleLengthCheck
, drRetryPolicy = limitRetries 1
}
exampleHashCheck :: HashCheck
exampleHashCheck = HashCheck
{ hashCheckAlgorithm = SHA1
, hashCheckHexDigest = CheckHexDigestString "b98eea96d321cdeed83a201c192dac116e786ec2"
}
exampleLengthCheck :: LengthCheck
exampleLengthCheck = 302513
-- | The wrong ContentLength for exampleReq
exampleWrongContentLength :: Int
exampleWrongContentLength = 302512
-- | The wrong SHA1 digest for exampleReq
exampleWrongDigest :: CheckHexDigest
exampleWrongDigest = CheckHexDigestString "b98eea96d321cdeed83a201c192dac116e786ec3"
exampleWrongContent :: String
exampleWrongContent = "example wrong content"
isWrongContentLength :: VerifiedDownloadException -> Bool
isWrongContentLength WrongContentLength{} = True
isWrongContentLength _ = False
isWrongDigest :: VerifiedDownloadException -> Bool
isWrongDigest WrongDigest{} = True
isWrongDigest _ = False
data T = T
{ manager :: Manager
}
runWith :: Manager -> ReaderT Manager m r -> m r
runWith = flip runReaderT
setup :: IO T
setup = do
manager <- newManager
return T{..}
teardown :: T -> IO ()
teardown _ = return ()
shouldNotBe :: (Show a, Eq a) => a -> a -> Expectation
actual `shouldNotBe` expected =
unless (actual /= expected) (expectationFailure msg)
where
msg = "Value was exactly what it shouldn't be: " ++ show expected
shouldNotReturn :: (Show a, Eq a) => IO a -> a -> Expectation
action `shouldNotReturn` unexpected = action >>= (`shouldNotBe` unexpected)
spec :: Spec
spec = beforeAll setup $ afterAll teardown $ do
let exampleProgressHook _ = return ()
describe "verifiedDownload" $ do
-- Preconditions:
-- * the exampleReq server is running
-- * the test runner has working internet access to it
it "downloads the file correctly" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
doesFileExist exampleFilePath `shouldReturn` False
let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook
go `shouldReturn` True
doesFileExist exampleFilePath `shouldReturn` True
it "is idempotent, and doesn't redownload unnecessarily" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
doesFileExist exampleFilePath `shouldReturn` False
let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook
go `shouldReturn` True
doesFileExist exampleFilePath `shouldReturn` True
go `shouldReturn` False
doesFileExist exampleFilePath `shouldReturn` True
-- https://github.com/commercialhaskell/stack/issues/372
it "does redownload when the destination file is wrong" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
writeFile exampleFilePath exampleWrongContent
doesFileExist exampleFilePath `shouldReturn` True
readFile exampleFilePath `shouldReturn` exampleWrongContent
let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook
go `shouldReturn` True
doesFileExist exampleFilePath `shouldReturn` True
readFile exampleFilePath `shouldNotReturn` exampleWrongContent
it "rejects incorrect content length" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
let wrongContentLengthReq = exampleReq
{ drLengthCheck = Just exampleWrongContentLength
}
let go = runWith manager $ verifiedDownload wrongContentLengthReq examplePath exampleProgressHook
go `shouldThrow` isWrongContentLength
doesFileExist exampleFilePath `shouldReturn` False
it "rejects incorrect digest" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
let wrongHashCheck = exampleHashCheck { hashCheckHexDigest = exampleWrongDigest }
let wrongDigestReq = exampleReq { drHashChecks = [wrongHashCheck] }
let go = runWith manager $ verifiedDownload wrongDigestReq examplePath exampleProgressHook
go `shouldThrow` isWrongDigest
doesFileExist exampleFilePath `shouldReturn` False
-- https://github.com/commercialhaskell/stack/issues/240
it "can download hackage tarballs" $ \T{..} -> withTempDir $ \dir -> do
dest <- fmap (dir </>) $ parseRelFile "acme-missiles-0.3.tar.gz"
let destFp = toFilePath dest
req <- parseUrl "http://hackage.haskell.org/package/acme-missiles-0.3/acme-missiles-0.3.tar.gz"
let dReq = DownloadRequest
{ drRequest = req
, drHashChecks = []
, drLengthCheck = Nothing
, drRetryPolicy = limitRetries 1
}
let go = runWith manager $ verifiedDownload dReq dest exampleProgressHook
doesFileExist destFp `shouldReturn` False
go `shouldReturn` True
doesFileExist destFp `shouldReturn` True
| akhileshs/stack | src/test/Network/HTTP/Download/VerifiedSpec.hs | bsd-3-clause | 6,282 | 0 | 22 | 1,218 | 1,496 | 759 | 737 | 122 | 1 |
module Main(main) where
import System.Random
tstRnd rng = checkRange rng (genRnd 50 rng)
genRnd n rng = take n (randomRs rng (mkStdGen 2))
checkRange (lo,hi) = all pred
where
pred
| lo <= hi = \ x -> x >= lo && x <= hi
| otherwise = \ x -> x >= hi && x <= lo
main :: IO ()
main = do
print (tstRnd (1,5::Double))
print (tstRnd (1,5::Int))
print (tstRnd (10,54::Integer))
print (tstRnd ((-6),2::Int))
print (tstRnd (2,(-6)::Int))
| danse/ghcjs | test/pkg/base/rand001.hs | mit | 460 | 0 | 12 | 112 | 271 | 141 | 130 | 15 | 1 |
module CodeModel.Core where
import CodeModel.Function
import CodeModel.Signature
data Core = Core String [Function]
instance Show Core where
show (Core name funs) = "core " ++ name ++ "\n" ++ unlines (map show funs)
getFunction :: Core -> String -> Maybe Function
getFunction (Core _ fs) s = (\filtered -> if null filtered then Nothing else Just $ head filtered) (filter (\(Function (Signature n _) _) -> n == s) fs)
| MarcusVoelker/Recolang | CodeModel/Core.hs | mit | 423 | 0 | 13 | 76 | 176 | 92 | 84 | 8 | 2 |
module Y2018.M05.D08.Exercise where
{--
Okay, now that we have the new articles downloaded from the REST endpoint and
the ArticleMetaData context from the database, let's do some triage!
So, just like with the ArticleMetaData, we have to generalize the Article-
TriageInformation type from the specific Package and (Dated)Article types to
types that allow us to switch from Pilot(-specific) articles to WPJ, or, in the
future, articles of any type, ... or so we hope.
Whilst still being useful for solving this problem, too.
So, without further ado:
--}
import Data.Aeson (Value)
import Data.Map (Map)
import Database.PostgreSQL.Simple
-- below imports available via 1HaskellADay git repository
import Store.SQL.Connection
import Store.SQL.Util.Indexed
-- import Y2018.M01.D30.Exercise -- template for our ArticleTriageInformation
import Y2018.M04.D02.Exercise -- for Article type
import Y2018.M04.D13.Exercise -- for Packet type
import Y2018.M05.D04.Exercise -- for articles from the rest endpoint
import Y2018.M05.D07.Exercise -- for article context from the database
data Triage = NEW | UPDATED | REDUNDANT
deriving (Eq, Ord, Show)
instance Monoid Triage where
mempty = REDUNDANT
mappend = undefined
-- Triage is the dual of a Semigroupoid: we only care about its unit value
-- in logic analyses.
data ArticleTriageInformation package block article idx =
ATI { pack :: package,
art :: (block, article),
amd :: Maybe (IxValue (ArticleMetaData idx)) }
deriving Show
{--
The output from our analysis of the article context from the database (the
ArticleMetadata set) and the articles downloaded from the REST endpoint (the
ParsedPackage values) is the triaged article set
--}
type WPJATI = ArticleTriageInformation (Packet Value) Value Article Int
type MapTri = Map Triage WPJATI
triageArticles :: [IxValue (ArticleMetaData Int)] -> [ParsedPacket] -> MapTri
triageArticles amd packets = undefined
{--
So, with the above.
1. download the last week's articles from the REST endpoint
2. get the article metadata context from the database
3. triage the downloaded articles.
1. How many new articles are there?
2. How many updated articles are there?
3. How many redundant articles are there?
Since the World Policy Journal doesn't publish many articles each day, and a
packet has 100 articles, there 'may' be a lot of redundant articles. Do your
results bear this out?
--}
| geophf/1HaskellADay | exercises/HAD/Y2018/M05/D08/Exercise.hs | mit | 2,432 | 0 | 13 | 419 | 257 | 159 | 98 | 24 | 1 |
import Test.Hspec.Attoparsec
import Test.Tasty
import Test.Tasty.Hspec
import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString.Char8 as C8
import Data.STEP.Parsers
main :: IO ()
main = do
specs <- createSpecs
let tests = testGroup "Tests" [specs]
defaultMain tests
createSpecs = testSpec "Parsing" $ parallel $
describe "success cases" $ do
it "should parse case1" $
(C8.pack "( 1.45 , 666. ,2. ,6.022E23)") ~> parseStep
`shouldParse` (Vector [1.45, 666.0, 2.0, 6.022e23])
it "should parse case2" $
(C8.pack "(1.0,2.0,3.0,4.0)") ~> parseStep
`shouldParse` (Vector [1.0, 2.0, 3.0, 4.0])
| Newlifer/libstep | test/test.hs | mit | 659 | 0 | 13 | 136 | 200 | 109 | 91 | 19 | 1 |
import Test.Tasty
import Test.Tasty.QuickCheck
import Coreutils
import Data.List (intersperse)
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Unit tests" [libTests]
libTests :: TestTree
libTests = testGroup "coreutils" [splitTests]
splitTests :: TestTree
splitTests = testGroup "split"
[ testProperty "removes a" $
\as -> length (as :: String) > 10 ==>
notElem ',' . concat . split ',' . intersperse ',' $ as
, testProperty "has +1 results from element count" $
\as -> length (as :: String) > 10 ==>
let commafied = intersperse ',' as
count = length . filter (== ',') $ commafied
len = length $ split ',' commafied
in len == count + 1
]
| mrak/coreutils.hs | tests/unit/Main.hs | mit | 768 | 0 | 17 | 216 | 241 | 126 | 115 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
import Data.Foldable (traverse_)
input :: ByteString
input = "10001001100000001"
bitFlip :: Char -> Char
bitFlip '0' = '1'
bitFlip _ = '0'
dragon :: ByteString -> ByteString
dragon β = β `BC.append` ('0' `BC.cons` BC.reverse (BC.map bitFlip β))
dragonTest :: Bool
dragonTest = all
(\(α, β) -> dragon α == β)
[ ("1" , "100")
, ("0" , "001")
, ("11111" , "11111000000")
, ("111100001010", "1111000010100101011110000")
]
checkStep :: ByteString -> ByteString
checkStep β = go β ""
where
{-# INLINABLE go #-}
go :: ByteString -> ByteString -> ByteString
go α ω | BC.null α = ω
| otherwise = go α' ω'
where
γ = α `BC.index` 0
δ = α `BC.index` 1
ϵ = if γ == δ then '1' else '0'
α' = BC.drop 2 α
ω' = ω `BC.snoc` ϵ
checkStepTest :: Bool
checkStepTest = all (\(α, β) -> checkStep α == β)
[("110010110100", "110101"), ("110101", "100")]
shrink :: ByteString -> ByteString
shrink β | odd $ BC.length β = β
| otherwise = shrink $ checkStep β
expand :: Int -> ByteString -> ByteString
expand λ β | BC.length β >= λ = β
| otherwise = expand λ $ dragon β
checkSum :: Int -> ByteString -> ByteString
checkSum λ = shrink . BC.take λ . expand λ
main :: IO ()
main = do
traverse_ print [dragonTest, checkStepTest]
traverse_ (BC.putStrLn . (`checkSum` input)) [272, 35651584]
| genos/online_problems | advent_of_code_2016/day16/hask/src/Main.hs | mit | 1,652 | 0 | 11 | 464 | 589 | 320 | 269 | 44 | 2 |
-----------------------------------------------------------------------------
--
-- Module : Language.PureScript.CoreFn.Ann
-- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
-- License : MIT
--
-- Maintainer : Phil Freeman <paf31@cantab.net>, Gary Burgess <gary.burgess@gmail.com>
-- Stability : experimental
-- Portability :
--
-- | Type alias for basic annotations
--
-----------------------------------------------------------------------------
module Language.PureScript.CoreFn.Ann where
import Language.PureScript.AST.SourcePos
import Language.PureScript.CoreFn.Meta
import Language.PureScript.Types
import Language.PureScript.Comments
-- |
-- Type alias for basic annotations
--
type Ann = (Maybe SourceSpan, [Comment], Maybe Type, Maybe Meta)
-- |
-- Initial annotation with no metadata
--
nullAnn :: Ann
nullAnn = (Nothing, [], Nothing, Nothing)
-- |
-- Remove the comments from an annotation
--
removeComments :: Ann -> Ann
removeComments (ss, _, ty, meta) = (ss, [], ty, meta)
| michaelficarra/purescript | src/Language/PureScript/CoreFn/Ann.hs | mit | 1,048 | 0 | 6 | 148 | 153 | 104 | 49 | 10 | 1 |
import Data.List
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [ [] ]
combinations n xs = [ y:ys | y:xs' <- tails xs
, ys <- combinations (n-1) xs']
| curiousily/haskell-99problems | 26.hs | mit | 187 | 0 | 10 | 62 | 95 | 50 | 45 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
module Codec.Xlsx.Types.Internal.CommentTable where
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Lazy.Char8 as LBC8
import Data.List.Extra (nubOrd)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import Data.Text.Lazy (toStrict)
import qualified Data.Text.Lazy.Builder as B
import qualified Data.Text.Lazy.Builder.Int as B
import GHC.Generics (Generic)
import Safe
import Text.XML
import Text.XML.Cursor
import Codec.Xlsx.Parser.Internal
import Codec.Xlsx.Types.Comment
import Codec.Xlsx.Types.Common
import Codec.Xlsx.Writer.Internal
newtype CommentTable = CommentTable
{ _commentsTable :: Map CellRef Comment }
deriving (Eq, Show, Generic)
fromList :: [(CellRef, Comment)] -> CommentTable
fromList = CommentTable . M.fromList
toList :: CommentTable -> [(CellRef, Comment)]
toList = M.toList . _commentsTable
lookupComment :: CellRef -> CommentTable -> Maybe Comment
lookupComment ref = M.lookup ref . _commentsTable
instance ToDocument CommentTable where
toDocument = documentFromElement "Sheet comments generated by xlsx"
. toElement "comments"
instance ToElement CommentTable where
toElement nm (CommentTable m) = Element
{ elementName = nm
, elementAttributes = M.empty
, elementNodes = [ NodeElement $ elementListSimple "authors" authorNodes
, NodeElement . elementListSimple "commentList" $ map commentToEl (M.toList m) ]
}
where
commentToEl (ref, Comment{..}) = Element
{ elementName = "comment"
, elementAttributes = M.fromList [ ("ref" .= ref)
, ("authorId" .= lookupAuthor _commentAuthor)]
, elementNodes = [NodeElement $ toElement "text" _commentText]
}
lookupAuthor a = fromJustNote "author lookup" $ M.lookup a authorIds
authorNames = nubOrd . map _commentAuthor $ M.elems m
decimalToText :: Integer -> Text
decimalToText = toStrict . B.toLazyText . B.decimal
authorIds = M.fromList $ zip authorNames (map decimalToText [0..])
authorNodes = map (elementContent "author") authorNames
instance FromCursor CommentTable where
fromCursor cur = do
let authorNames = cur $/ element (n_ "authors") &/ element (n_ "author") >=> contentOrEmpty
authors = M.fromList $ zip [0..] authorNames
items = cur $/ element (n_ "commentList") &/ element (n_ "comment") >=> parseComment authors
return . CommentTable $ M.fromList items
parseComment :: Map Int Text -> Cursor -> [(CellRef, Comment)]
parseComment authors cur = do
ref <- fromAttribute "ref" cur
txt <- cur $/ element (n_ "text") >=> fromCursor
authorId <- cur $| attribute "authorId" >=> decimal
let author = fromJustNote "authorId" $ M.lookup authorId authors
return (ref, Comment txt author True)
-- | helper to render comment baloons vml file,
-- currently uses fixed shape
renderShapes :: CommentTable -> ByteString
renderShapes (CommentTable m) = LB.concat
[ "<xml xmlns:v=\"urn:schemas-microsoft-com:vml\" "
, "xmlns:o=\"urn:schemas-microsoft-com:office:office\" "
, "xmlns:x=\"urn:schemas-microsoft-com:office:excel\">"
, commentShapeType
, LB.concat commentShapes
, "</xml>"
]
where
commentShapeType = LB.concat
[ "<v:shapetype id=\"baloon\" coordsize=\"21600,21600\" o:spt=\"202\" "
, "path=\"m,l,21600r21600,l21600,xe\">"
, "<v:stroke joinstyle=\"miter\"></v:stroke>"
, "<v:path gradientshapeok=\"t\" o:connecttype=\"rect\"></v:path>"
, "</v:shapetype>"
]
fromRef = fromJustNote "Invalid comment ref" . fromSingleCellRef
commentShapes = [ commentShape (fromRef ref) (_commentVisible cmnt)
| (ref, cmnt) <- M.toList m ]
commentShape (r, c) v = LB.concat
[ "<v:shape type=\"#baloon\" "
, "style=\"position:absolute;width:auto" -- ;width:108pt;height:59.25pt"
, if v then "" else ";visibility:hidden"
, "\" fillcolor=\"#ffffe1\" o:insetmode=\"auto\">"
, "<v:fill color2=\"#ffffe1\"></v:fill><v:shadow color=\"black\" obscured=\"t\"></v:shadow>"
, "<v:path o:connecttype=\"none\"></v:path><v:textbox style=\"mso-direction-alt:auto\">"
, "<div style=\"text-align:left\"></div></v:textbox>"
, "<x:ClientData ObjectType=\"Note\">"
, "<x:MoveWithCells></x:MoveWithCells><x:SizeWithCells></x:SizeWithCells>"
, "<x:Anchor>4, 15, 0, 7, 6, 31, 5, 1</x:Anchor><x:AutoFill>False</x:AutoFill>"
, "<x:Row>"
, LBC8.pack $ show (r - 1)
, "</x:Row>"
, "<x:Column>"
, LBC8.pack $ show (c - 1)
, "</x:Column>"
, "</x:ClientData>"
, "</v:shape>"
]
| qrilka/xlsx | src/Codec/Xlsx/Types/Internal/CommentTable.hs | mit | 4,940 | 0 | 16 | 1,068 | 1,104 | 611 | 493 | 100 | 2 |
-- | Biegunka - configuration development library
module Control.Biegunka
( -- * Interpreters control
biegunka, Settings, defaultSettings, runRoot, biegunkaRoot
, Templates(..), templates
-- * Interpreters
, Interpreter
, pause, confirm, changes, run, check
-- * Types
, Script, Scope(..)
-- * Actions layer primitives
, link, register, copy, unE, substitute, raw
-- * Script environment
, sourceRoot
-- * Modifiers
, namespace
, sudo, User(..), username, uid, retries, reacting, React(..), prerequisiteOf, (<~>)
-- * Auxiliary
, into
-- * Commandline options parser autogeneration
, runner_, runnerOf, Environments(..), Generic
-- * Quasiquoters
, multiline, sh, shell
-- * Settings
-- ** Mode
, mode, Mode(..)
-- * Little helpers
, (~>)
, pass
) where
import GHC.Generics (Generic)
import System.Directory.Layout (username, uid)
import Control.Biegunka.Biegunka (biegunka)
import Control.Biegunka.Settings
( Settings, defaultSettings, biegunkaRoot
, Templates(..), templates
, mode, Mode(..)
)
import Control.Biegunka.Execute (run)
import Control.Biegunka.Interpreter (Interpreter, pause, confirm, changes)
import Control.Biegunka.Language (Scope(..))
import Control.Biegunka.Primitive
import Control.Biegunka.Script (runRoot, sourceRoot, Script, User(..), React(..), into)
import Control.Biegunka.QQ (multiline, sh, shell)
import Control.Biegunka.Options (Environments(..), runnerOf, runner_)
import Control.Biegunka.Check (check)
infix 4 ~>
-- | An alias for '(,)' for better looking pairing
(~>) :: a -> b -> (a, b)
(~>) = (,)
-- | Do nothing.
pass :: Applicative m => m ()
pass = pure ()
| biegunka/biegunka | src/Control/Biegunka.hs | mit | 1,687 | 0 | 7 | 304 | 453 | 302 | 151 | 37 | 1 |
import Data.Char
import Data.List (sort)
{- Chapter 7 :: Higher-order functions -}
twice :: (a -> a) -> a -> a
twice f x = f (f x)
map' :: (a -> b) -> [a] -> [b]
map' f xs = [f x | x <- xs]
-- map defined by recursion
map'' :: (a -> b) -> [a] -> [b]
map'' f [] = []
map'' f (x:xs) = f x : map'' f xs
filter' :: (a -> Bool) -> [a] -> [a]
filter' p xs = [x | x <- xs, p x]
-- filter defined by recursion
filter'' :: (a -> Bool) -> [a] -> [a]
filter'' p [] = []
filter'' p (x:xs) | p x = x : filter'' p xs
| otherwise = filter'' p xs
sumsqreven :: [Int] -> Int
sumsqreven ns = sum (map (^2) (filter even ns))
-- foldr function
sum' :: Num a => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum' xs
sum'' :: Num a => [a] -> a
sum'' = foldr (+) 0
{-
(foldr (+) 0) [1,2,3]
= 1 : (2 : (3 : []))
= 1 + (2 + (3 + 0))
Takeaway: foldr can be thought of replacing each cons
operator in a list by the function f and the empty list
at the end by the value v.
-}
product' :: Num a => [a] -> a
product' [] = 1
product' (x:xs) = x * product xs
product'' :: Num a => [a] -> a
product'' = foldr (*) 1
or' :: [Bool] -> Bool
or' [] = False
or' (x:xs) = x || or' xs
or'' :: [Bool] -> Bool
or'' = foldr (||) False
and' :: [Bool] -> Bool
and' [] = True
and' (x:xs) = x && and' xs
and'' :: [Bool] -> Bool
and'' = foldr (&&) True
foldr' :: (a -> b -> b) -> b -> [a] -> b
foldr' f v [] = v
foldr' f v (x:xs) = f x (foldr' f v xs)
length' :: [a] -> Int
length' = foldr (\_ n -> 1+n) 0
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
snoc :: a -> [a] -> [a]
snoc x xs = xs ++ [x]
reverse'' :: [a] -> [a]
reverse'' = foldr snoc []
{-
reverse [1,2,3]
= 1 : (2 : (3 : []))
= 1 snoc (2 snoc (3 snoc []))
= (2 snoc (3 snoc [])) ++ [1]
= ((3 snoc []) ++ [2]) ++ [1]
= (([] ++ [3]) ++ [2]) ++ [1]
-}
-- foldl function
sum''' :: Num a => [a] -> a
sum''' = sum' 0
where
sum' v [] = v
sum' v (x:xs) = sum' (v+x) xs
{-
sum [1,2,3]
= sum' 0 [1,2,3]
= sum' (0+1) [2,3]
= sum' ((0+1)+2) [3]
= sum' (((0+1)+2)+3) []
= sum' ((0+1)+2)+3
= 6
-}
length'' :: [a] -> Int
length'' = foldl (\n _ -> n+1) 0
-- length'' [1,2,3] = ((0 + 1) + 1) + 1 = 3
reverse''' :: [a] -> [a]
reverse''' = foldl (\xs x -> x:xs) []
{-
swap_cons = (\xs x -> x:xs)
swap_cons [2,3] 1 == [1,2,3]
reverse''' [1,2,3]
= ((([] swap_cons 1) swap_cons 2) swap_cons 3)
= (([1] swap_cons 2) swap_cons 3)
= ([2,1] swap_cons 3)
= [3,2,1]
-}
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' f v [] = v
foldl' f v (x:xs) = foldl' f (f v x) xs
-- composition operator
(.*) :: (b -> c) -> (a -> b) -> (a -> c)
f .* g = \x -> f (g x)
{-
not . even $ 10 == False
not . not . even $ 10 == True
-}
compose :: [a -> a] -> (a -> a)
compose = foldr (.) id
{-
compose [\x -> x^2, \y -> y*5] 4 == 400
-}
-- bit conversion
type Bit = Int
{-
iterate produces an infinite list by applying
a function on a value - i.e.:
iterate (*10) 1 = [1, 10, 100..]
take 5 $ iterate (*2) 1 == [1,2,4,8,16]
-}
bin2int :: [Bit] -> Int
bin2int bits = sum [w*b | (w,b) <- zip weights bits]
where weights = iterate (*2) 1
bin2int' :: [Bit] -> Int
bin2int' = foldr (\x y -> x + 2*y) 0
int2bin :: Int -> [Bit]
int2bin 0 = []
int2bin n = n `mod` 2 : int2bin (n `div` 2)
make8 :: [Bit] -> [Bit]
make8 bits = take 8 (bits ++ repeat 0)
{-
bin2int' [1,0,1,1] == 13
int2bin 13 == [1,0,1,1]
make8 [1,1,0,1] == [1,1,0,1,0,0,0,0]
-}
-- convert each letter to bit representation and
-- concatenate the output lists into one list.
encode' :: String -> [Bit]
encode' = concat . map (make8 . int2bin . ord)
chop8 :: [Bit] -> [[Bit]]
chop8 [] = []
chop8 bits = take 8 bits : chop8 (drop 8 bits)
decode :: [Bit] -> String
decode = map (chr . bin2int') . chop8
{-
encode' "abc"
= [1,0,0,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,1,0]
chop8 [1,0,0,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,1,0]
= [[1,0,0,0,0,1,1,0],[0,1,0,0,0,1,1,0],[1,1,0,0,0,1,1,0]]
decode [1,0,0,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,1,0]
= "abc"
-}
transmit :: String -> String
transmit = decode . channel . encode'
channel :: [Bit] -> [Bit]
channel = id
{-
transmit "higher-order functions are easy"
= "higher-order functions are easy
-}
-- voting algorithms
votes :: [String]
votes = ["Red", "Blue", "Green", "Blue", "Blue", "Red"]
count :: Eq a => a -> [a] -> Int
count x = length . filter (== x)
{-
count "Red" votes == 2
-}
rmdupes :: Eq a => [a] -> [a]
rmdupes [] = []
rmdupes (x:xs) = x : rmdupes (filter (/= x) xs)
{-
Incorrect definition of rmdups, check Errata on
http://www.cs.nott.ac.uk/~pszgmh/pih-errata.html
rmdupes :: Eq a => [a] -> [a]
rmdupes [] = []
rmdupes (x:xs) = x : filter (/= x) (rmdupes xs)
rmdupes [1,3,1,3,2]
= 1 : rmdupes (/= 1) [3,1,3,2]
= 1 : filter (/= 1) (rmdupes [3,1,3,2])
= 1 : filter (/= 1) (3 : filter (/= 3) (rmdupes [1,3,2]))
= 1 : filter (/= 1) (3 : filter (/= 3) (1 : filter (/= 1) (rmdupes [3,2])))
= 1 : filter (/= 1) (3 : filter (/= 3) (1 : filter (/= 1) (3 : filter (/= 3) (rmdupes [2]))))
= 1 : filter (/= 1) (3 : filter (/= 3) (1 : filter (/= 1) (3 : filter (/= 3) (2 : filter (/= 2) (rmdupes [])))))
= 1 : filter (/= 1) (3 : filter (/= 3) (1 : filter (/= 1) (3 : filter (/= 3) (2 : filter (/= 2) []))))
= 1 : filter (/= 1) (3 : filter (/= 3) (1 : filter (/= 1) [3,2]))
= 1 : filter (/= 1) (3 : filter (/= 3) [1,3,2])
= 1 : filter (/= 1) (3 : [1,2])
= 1 : filter (/= 1) [3,1,2]
= 1 : [3,2]
= [1,3,2]
rmdupes votes
= ["Red","Blue","Green"]
-}
result :: Ord a => [a] -> [(Int,a)]
result vs = sort [(count v vs, v) | v <- rmdupes vs]
winner :: Ord a => [a] -> a
winner = snd . last . result
{-
result votes
= [(1,"Green"),(2,"Red"),(3,"Blue")]
winner votes
= "Blue"
-}
ballots :: [[String]]
ballots = [["Red", "Green"],
["Green"],
["Blue"],
["Green","Red","Blue"],
["Blue","Green","Red"],
["Green"]]
rmempty :: Eq a => [[a]] -> [[a]]
rmempty = filter (/= [])
elim :: Eq a => a -> [[a]] -> [[a]]
elim x = map (filter (/= x))
rank :: Ord a => [[a]] -> [a]
rank = map snd . result . map head
-- case mechanism allows for pattern matching in the
-- body of a definition.
winner' :: Ord a => [[a]] -> a
winner' bs = case rank (rmempty bs) of
[c] -> c
(c:cs) -> winner' (elim c bs)
{-
rank ballots
= ["Red", "Blue", "Green"]
winner' ballots
= "Green"
-}
| rad1al/hutton_exercises | notes_ch07.hs | gpl-2.0 | 6,499 | 0 | 10 | 1,692 | 2,125 | 1,160 | 965 | 114 | 2 |
module Physics.ImplicitEMC () where
| firegurafiku/ImplicitEMC | src/Physics/ImplicitEMC.hs | gpl-2.0 | 37 | 0 | 3 | 5 | 9 | 6 | 3 | 1 | 0 |
{- This module was generated from data in the Kate syntax
highlighting file vhdl.xml, version 1.12, by Rocky Scaletta (rocky@purdue.edu), Stefan Endrullis (stefan@endrullis.de), Florent Ouchet (outchy@users.sourceforge.net), Chris Higgs (chiggs.99@gmail.com), Jan Michel (jan@mueschelsoft.de) -}
module Text.Highlighting.Kate.Syntax.Vhdl
(highlight, parseExpression, syntaxName, syntaxExtensions)
where
import Text.Highlighting.Kate.Types
import Text.Highlighting.Kate.Common
import Text.ParserCombinators.Parsec hiding (State)
import Control.Monad.State
import Data.Char (isSpace)
import qualified Data.Set as Set
-- | Full name of language.
syntaxName :: String
syntaxName = "VHDL"
-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.vhdl;*.vhd"
-- | Highlight source code using this syntax definition.
highlight :: String -> [SourceLine]
highlight input = evalState (mapM parseSourceLine $ lines input) startingState
parseSourceLine :: String -> State SyntaxState SourceLine
parseSourceLine = mkParseSourceLine (parseExpression Nothing)
-- | Parse an expression using appropriate local context.
parseExpression :: Maybe (String,String)
-> KateParser Token
parseExpression mbcontext = do
(lang,cont) <- maybe currentContext return mbcontext
result <- parseRules (lang,cont)
optional $ do eof
updateState $ \st -> st{ synStPrevChar = '\n' }
pEndLine
return result
startingState = SyntaxState {synStContexts = [("VHDL","start")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = False, synStCaptures = []}
pEndLine = do
updateState $ \st -> st{ synStPrevNonspace = False }
context <- currentContext
contexts <- synStContexts `fmap` getState
st <- getState
if length contexts >= 2
then case context of
_ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False }
("VHDL","start") -> return ()
("VHDL","package") -> return ()
("VHDL","packagemain") -> return ()
("VHDL","packagefunction") -> return ()
("VHDL","packagebody") -> return ()
("VHDL","packagebodymain") -> return ()
("VHDL","packagebodyfunc1") -> return ()
("VHDL","packagebodyfunc2") -> return ()
("VHDL","architecture_main") -> return ()
("VHDL","arch_start") -> return ()
("VHDL","arch_decl") -> return ()
("VHDL","detect_arch_parts") -> return ()
("VHDL","generate1") -> return ()
("VHDL","generate2") -> return ()
("VHDL","process1") -> return ()
("VHDL","proc_rules") -> return ()
("VHDL","instance") -> return ()
("VHDL","instanceMap") -> return ()
("VHDL","instanceInnerPar") -> return ()
("VHDL","forwhile1") -> return ()
("VHDL","forwhile2") -> return ()
("VHDL","if_start") -> return ()
("VHDL","if") -> return ()
("VHDL","case1") -> return ()
("VHDL","case2") -> return ()
("VHDL","caseWhen") -> return ()
("VHDL","caseWhen2") -> return ()
("VHDL","entity") -> return ()
("VHDL","entity_main") -> return ()
("VHDL","configuration") -> return ()
("VHDL","conf_start") -> return ()
("VHDL","conf_decl") -> return ()
("VHDL","conf_for") -> return ()
("VHDL","preDetection") -> return ()
("VHDL","generalDetection") -> return ()
("VHDL","comment") -> (popContext) >> pEndLine
("VHDL","string") -> return ()
("VHDL","attribute") -> (popContext) >> pEndLine
("VHDL","quot in att") -> return ()
("VHDL","signal") -> return ()
_ -> return ()
else return ()
withAttribute attr txt = do
when (null txt) $ fail "Parser matched no text"
updateState $ \st -> st { synStPrevChar = last txt
, synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) }
return (attr, txt)
list_keywordsToplevel = Set.fromList $ words $ "file library use"
list_keywords = Set.fromList $ words $ "access after alias all array assert assume assume_guarantee attribute begin block body bus component constant context cover default disconnect downto end exit fairness falling_edge file for force function generate generic group guarded impure inertial is label linkage literal map new next null of on open others parameter port postponed procedure process property protected pure range record register reject release report return rising_edge select sequence severity signal shared strong subtype to transport type unaffected units until variable vmode vprop vunit wait when with note warning error failure in inout out buffer and abs or xor xnor not mod nand nor rem rol ror sla sra sll srl"
list_if = Set.fromList $ words $ "if else elsif then"
list_forOrWhile = Set.fromList $ words $ "loop"
list_directions = Set.fromList $ words $ "in inout out buffer linkage"
list_signals = Set.fromList $ words $ "signal variable constant type attribute"
list_range = Set.fromList $ words $ "to downto others"
list_case = Set.fromList $ words $ "case when"
list_timeunits = Set.fromList $ words $ "fs ps ns us ms sec min hr"
list_types = Set.fromList $ words $ "bit bit_vector character boolean boolean_vector integer integer_vector real real_vector time time_vector delay_length string severity_level positive natural file_open_kind file_open_status signed unsigned unresolved_unsigned unresolved_signed line text side width std_logic std_logic_vector std_ulogic std_ulogic_vector x01 x01z ux01 ux01z qsim_state qsim_state_vector qsim_12state qsim_12state_vector qsim_strength mux_bit mux_vector reg_bit reg_vector wor_bit wor_vector"
regex_'28'5cb'29package'5cb = compileRegex True "(\\b)package\\b"
regex_'28'5cb'29is'5cb = compileRegex True "(\\b)is\\b"
regex_'28'5cb'29end'5cb = compileRegex True "(\\b)end\\b"
regex_'28'5cb'29function'5cb = compileRegex True "(\\b)function\\b"
regex_'28'5cb'29'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'5cb = compileRegex True "(\\b)\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b\\b"
regex_'28'5cb'29end'5cs'2bpackage'5cb = compileRegex True "(\\b)end\\s+package\\b"
regex_'28'5cb'29begin'5cb = compileRegex True "(\\b)begin\\b"
regex_'28'5cb'29'28generate'7cloop'29'5cb = compileRegex True "(\\b)(generate|loop)\\b"
regex_'28'5cb'29'28for'7cif'7cwhile'29'5cb = compileRegex True "(\\b)(for|if|while)\\b"
regex_'28'5cb'29end'5cs'2b'28generate'7cloop'29'28'5cs'2b'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f = compileRegex True "(\\b)end\\s+(generate|loop)(\\s+\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)?"
regex_'28'5cb'29process'5cb = compileRegex True "(\\b)process\\b"
regex_'28'5cb'29'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'28'3f'3d'5cs'2a'3a'28'3f'21'3d'29'29 = compileRegex True "(\\b)\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b(?=\\s*:(?!=))"
regex_'28'5cb'29if'5cb = compileRegex True "(\\b)if\\b"
regex_'28'5cb'29case'5cb = compileRegex True "(\\b)case\\b"
regex_'28'5cb'29'28port'7cgeneric'29'5cs'2bmap'5cs'2a'5c'28 = compileRegex True "(\\b)(port|generic)\\s+map\\s*\\("
regex_'28'5cb'29loop'5cb = compileRegex True "(\\b)loop\\b"
regex_'28'5cb'29'28for'7cwhile'29'5cb = compileRegex True "(\\b)(for|while)\\b"
regex_'28'5cb'29end'5cs'2bloop'28'5cs'2b'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f = compileRegex True "(\\b)end\\s+loop(\\s+\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)?"
regex_'28'5cb'29then'5cb = compileRegex True "(\\b)then\\b"
regex_'28'5cb'29end'5cs'2bif'28'5cs'2b'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f'5cs'2a'3b = compileRegex True "(\\b)end\\s+if(\\s+\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)?\\s*;"
regex_'28'5cb'29end'5cs'2bcase'28'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f'5cs'2a'3b = compileRegex True "(\\b)end\\s+case(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)?\\s*;"
regex_'28'5cb'29when'5cb = compileRegex True "(\\b)when\\b"
regex_'5cs'2awhen'5cb = compileRegex True "\\s*when\\b"
regex_'5cs'2aend'5cs'2bcase'5cb = compileRegex True "\\s*end\\s+case\\b"
regex_'28'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29 = compileRegex True "(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)"
regex_generic = compileRegex True "generic"
regex_port = compileRegex True "port"
regex_end'28'5cs'2b'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f = compileRegex True "end(\\s+\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)?"
parseRules ("VHDL","start") =
(((parseRules ("VHDL","preDetection")))
<|>
((lookAhead (pRegExprDynamic "(\\b)architecture\\s+(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\b") >> pushContext ("VHDL","architecture_main") >> currentContext >>= parseRules))
<|>
((pString False "entity" >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","entity"))
<|>
((lookAhead (pRegExprDynamic "(\\b)package\\s+(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s+is\\b") >> pushContext ("VHDL","package") >> currentContext >>= parseRules))
<|>
((lookAhead (pRegExprDynamic "(\\b)package\\s+body\\s+(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s+is\\b") >> pushContext ("VHDL","packagebody") >> currentContext >>= parseRules))
<|>
((lookAhead (pRegExprDynamic "(\\b)configuration\\s+(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\b") >> pushContext ("VHDL","configuration") >> currentContext >>= parseRules))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywordsToplevel >>= withAttribute KeywordTok))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","start")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","package") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29package'5cb >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'28'5cb'29is'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","packagemain"))
<|>
((pRegExprDynamic "(\\b)%2\\b" >>= withAttribute KeywordTok))
<|>
((pRegExprDynamic "(\\b)end(\\s+package)?(\\s+%2)?\\s*;" >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","package")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","packagemain") =
(((parseRules ("VHDL","preDetection")))
<|>
((lookAhead (pRegExpr regex_'28'5cb'29end'5cb) >> (popContext) >> currentContext >>= parseRules))
<|>
((pRegExpr regex_'28'5cb'29function'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","packagefunction"))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","packagemain")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","packagefunction") =
(((pRegExpr regex_'28'5cb'29'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'5cb >>= withAttribute KeywordTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","packagefunction")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","packagebody") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29package'5cb >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'28'5cb'29is'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","packagebodymain"))
<|>
((pRegExprDynamic "(\\b)%2\\b" >>= withAttribute KeywordTok))
<|>
((pRegExprDynamic "(\\b)end(\\s+package)?(\\s+%2)?\\s*;" >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","packagebody")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","packagebodymain") =
(((parseRules ("VHDL","preDetection")))
<|>
((lookAhead (pRegExpr regex_'28'5cb'29end'5cs'2bpackage'5cb) >> (popContext) >> currentContext >>= parseRules))
<|>
((lookAhead (pRegExprDynamic "(\\b)function\\s+(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\b") >> pushContext ("VHDL","packagebodyfunc1") >> currentContext >>= parseRules))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","packagebodymain")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","packagebodyfunc1") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29begin'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","packagebodyfunc2"))
<|>
((pRegExprDynamic "(\\b)end(\\s+function)?(\\s+%2)?\\b" >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((pRegExprDynamic "(\\b)%2\\b" >>= withAttribute KeywordTok))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","packagebodyfunc1")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","packagebodyfunc2") =
(((parseRules ("VHDL","preDetection")))
<|>
((lookAhead (pRegExprDynamic "(\\b)end(\\s+function)?\\b") >> (popContext) >> currentContext >>= parseRules))
<|>
((pRegExpr regex_'28'5cb'29begin'5cb >>= withAttribute KeywordTok))
<|>
((parseRules ("VHDL","proc_rules")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","packagebodyfunc2")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","architecture_main") =
(((parseRules ("VHDL","preDetection")))
<|>
((lookAhead (pRegExprDynamic "(\\b)architecture\\s+(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s+of\\s+(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s+is") >> pushContext ("VHDL","arch_start") >> currentContext >>= parseRules))
<|>
((pRegExprDynamic "(\\b)end(\\s+architecture)?(\\s+%2)?\\s*;" >>= withAttribute KeywordTok) >>~ (popContext >> popContext))
<|>
((pRegExprDynamic "(\\b)end(\\s+architecture)?(\\s+\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s*;" >>= withAttribute ErrorTok) >>~ (popContext >> popContext))
<|>
((parseRules ("VHDL","detect_arch_parts")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","architecture_main")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","arch_start") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29is'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","arch_decl"))
<|>
((pRegExprDynamic "(\\b)%2\\b" >>= withAttribute KeywordTok))
<|>
((pRegExprDynamic "(\\b)%4\\b" >>= withAttribute FunctionTok))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","arch_start")) >> pDefault >>= withAttribute KeywordTok))
parseRules ("VHDL","arch_decl") =
(((parseRules ("VHDL","preDetection")))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_signals >>= withAttribute OtherTok) >>~ pushContext ("VHDL","signal"))
<|>
((pString False "component" >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","entity"))
<|>
((pString False "begin" >>= withAttribute KeywordTok) >>~ (popContext >> popContext))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","arch_decl")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","detect_arch_parts") =
(((lookAhead (pRegExprDynamic "(\\b)(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b\\s*:\\s*)(if|for).*\\s+generate\\b") >> pushContext ("VHDL","generate1") >> currentContext >>= parseRules))
<|>
((lookAhead (pRegExprDynamic "(\\b)(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b\\s*:\\s*)?process\\b") >> pushContext ("VHDL","process1") >> currentContext >>= parseRules))
<|>
((lookAhead (pRegExprDynamic "(\\b)(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s*:\\s*((entity\\s+)?(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)(\\.\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)?)") >> pushContext ("VHDL","instance") >> currentContext >>= parseRules))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","detect_arch_parts")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","generate1") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29'28generate'7cloop'29'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","generate2"))
<|>
((pRegExprDynamic "(\\b)%3\\b" >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'28'5cb'29'28for'7cif'7cwhile'29'5cb >>= withAttribute KeywordTok))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","generate1")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","generate2") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29begin'5cb >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'28'5cb'29end'5cs'2b'28generate'7cloop'29'28'5cs'2b'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f >>= withAttribute KeywordTok) >>~ (popContext >> popContext))
<|>
((parseRules ("VHDL","detect_arch_parts")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","generate2")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","process1") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExprDynamic "(\\b)end\\s+process(\\s+%3)?" >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((pRegExprDynamic "(\\b)end\\s+process(\\s+\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)?" >>= withAttribute ErrorTok) >>~ (popContext))
<|>
((pRegExpr regex_'28'5cb'29process'5cb >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'28'5cb'29begin'5cb >>= withAttribute KeywordTok))
<|>
((parseRules ("VHDL","proc_rules")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","process1")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","proc_rules") =
(((pRegExpr regex_'28'5cb'29'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'28'3f'3d'5cs'2a'3a'28'3f'21'3d'29'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'28'5cb'29if'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","if_start"))
<|>
((lookAhead (pRegExpr regex_'28'5cb'29case'5cb) >> pushContext ("VHDL","case1") >> currentContext >>= parseRules))
<|>
((lookAhead (pRegExprDynamic "(\\b)((\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s*:\\s*)?((for|while)\\s+.+\\s+)loop\\b") >> pushContext ("VHDL","forwhile1") >> currentContext >>= parseRules))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","proc_rules")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","instance") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExprDynamic "(\\b)%4\\b" >>= withAttribute FunctionTok))
<|>
((pRegExprDynamic "(\\b)%3\\b" >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'28'5cb'29'28port'7cgeneric'29'5cs'2bmap'5cs'2a'5c'28 >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","instanceMap"))
<|>
((pDetectChar False ';' >>= withAttribute NormalTok) >>~ (popContext))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","instance")) >> pDefault >>= withAttribute ErrorTok))
parseRules ("VHDL","instanceMap") =
(((pAnyChar "<;:" >>= withAttribute ErrorTok))
<|>
((pDetectChar False ':' >>= withAttribute ErrorTok))
<|>
((parseRules ("VHDL","preDetection")))
<|>
((pDetectChar False ')' >>= withAttribute NormalTok) >>~ (popContext))
<|>
((pDetectChar False '(' >>= withAttribute NormalTok) >>~ pushContext ("VHDL","instanceInnerPar"))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","instanceMap")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","instanceInnerPar") =
(((parseRules ("VHDL","preDetection")))
<|>
((pDetectChar False ')' >>= withAttribute NormalTok) >>~ (popContext))
<|>
((pDetectChar False '(' >>= withAttribute NormalTok) >>~ pushContext ("VHDL","instanceInnerPar"))
<|>
((pDetectChar False ';' >>= withAttribute ErrorTok))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","instanceInnerPar")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","forwhile1") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29loop'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","forwhile2"))
<|>
((pRegExprDynamic "(\\b)%3\\b" >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'28'5cb'29'28for'7cwhile'29'5cb >>= withAttribute KeywordTok))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","forwhile1")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","forwhile2") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29begin'5cb >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'28'5cb'29end'5cs'2bloop'28'5cs'2b'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f >>= withAttribute KeywordTok) >>~ (popContext >> popContext))
<|>
((parseRules ("VHDL","proc_rules")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","forwhile2")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","if_start") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29then'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","if"))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","if_start")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","if") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29end'5cs'2bif'28'5cs'2b'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f'5cs'2a'3b >>= withAttribute KeywordTok) >>~ (popContext >> popContext))
<|>
((parseRules ("VHDL","proc_rules")))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_if >>= withAttribute KeywordTok))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","if")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","case1") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29is'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","case2"))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_case >>= withAttribute KeywordTok))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","case1")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","case2") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29end'5cs'2bcase'28'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f'5cs'2a'3b >>= withAttribute KeywordTok) >>~ (popContext >> popContext))
<|>
((lookAhead (pRegExprDynamic "(\\b)when(\\s+\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)?\\b") >> pushContext ("VHDL","caseWhen") >> currentContext >>= parseRules))
<|>
((parseRules ("VHDL","proc_rules")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","case2")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","caseWhen") =
(((pDetect2Chars False '=' '>' >>= withAttribute OtherTok) >>~ pushContext ("VHDL","caseWhen2"))
<|>
((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29when'5cb >>= withAttribute KeywordTok))
<|>
((pRegExprDynamic "(\\b)%2\\b" >>= withAttribute KeywordTok))
<|>
((parseRules ("VHDL","proc_rules")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","caseWhen")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","caseWhen2") =
(((parseRules ("VHDL","preDetection")))
<|>
((pColumn 0 >> lookAhead (pRegExpr regex_'5cs'2awhen'5cb) >> (popContext >> popContext) >> currentContext >>= parseRules))
<|>
((pColumn 0 >> lookAhead (pRegExpr regex_'5cs'2aend'5cs'2bcase'5cb) >> (popContext >> popContext) >> currentContext >>= parseRules))
<|>
((parseRules ("VHDL","proc_rules")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","caseWhen2")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","entity") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29 >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","entity_main"))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","entity")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","entity_main") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExprDynamic "(\\b)end(\\s+(entity|component))?(\\s+%1)?\\s*;" >>= withAttribute KeywordTok) >>~ (popContext >> popContext))
<|>
((pRegExprDynamic "(\\b)end(\\s+(entity|component))?(\\s+\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)?\\s*;" >>= withAttribute ErrorTok) >>~ (popContext >> popContext))
<|>
((pRegExpr regex_generic >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_port >>= withAttribute KeywordTok))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","entity_main")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","configuration") =
(((parseRules ("VHDL","preDetection")))
<|>
((lookAhead (pRegExprDynamic "(\\b)configuration\\s+(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s+of\\s+(\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s+is") >> pushContext ("VHDL","conf_start") >> currentContext >>= parseRules))
<|>
((pRegExprDynamic "(\\b)end(\\s+configuration)?(\\s+%2)?\\s*;" >>= withAttribute KeywordTok) >>~ (popContext >> popContext))
<|>
((pRegExprDynamic "(\\b)end(\\s+configuration)?(\\s+\\b(?!(?:process|constant|signal|variable))([A-Za-z_][A-Za-z0-9_]*)\\b)\\s*;" >>= withAttribute ErrorTok) >>~ (popContext >> popContext))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","configuration")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","conf_start") =
(((parseRules ("VHDL","preDetection")))
<|>
((pRegExpr regex_'28'5cb'29is'5cb >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","conf_decl"))
<|>
((pRegExprDynamic "(\\b)%2\\b" >>= withAttribute KeywordTok))
<|>
((pRegExprDynamic "(\\b)%4\\b" >>= withAttribute FunctionTok))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","conf_start")) >> pDefault >>= withAttribute KeywordTok))
parseRules ("VHDL","conf_decl") =
(((parseRules ("VHDL","preDetection")))
<|>
((pString False "for" >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","conf_for"))
<|>
((lookAhead (pString False "end") >> (popContext >> popContext) >> currentContext >>= parseRules))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","conf_decl")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","conf_for") =
(((parseRules ("VHDL","preDetection")))
<|>
((pString False "for" >>= withAttribute KeywordTok) >>~ pushContext ("VHDL","conf_for"))
<|>
((pRegExpr regex_end'28'5cs'2b'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'29'3f >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","conf_for")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","preDetection") =
(((pDetect2Chars False '-' '-' >>= withAttribute CommentTok) >>~ pushContext ("VHDL","comment"))
<|>
((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("VHDL","string"))
<|>
((pAnyChar "[&><=:+\\-*\\/|].," >>= withAttribute OtherTok))
<|>
((pDetectChar False '\'' >>= withAttribute BaseNTok) >>~ pushContext ("VHDL","attribute"))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","preDetection")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","generalDetection") =
(((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_types >>= withAttribute DataTypeTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_timeunits >>= withAttribute DataTypeTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_signals >>= withAttribute OtherTok) >>~ pushContext ("VHDL","signal"))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_range >>= withAttribute OtherTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywords >>= withAttribute KeywordTok))
<|>
((pInt >>= withAttribute DecValTok))
<|>
((pHlCChar >>= withAttribute CharTok))
<|>
((pDetectSpaces >>= withAttribute NormalTok))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","generalDetection")) >> pDefault >>= withAttribute NormalTok))
parseRules ("VHDL","comment") =
(currentContext >>= \x -> guard (x == ("VHDL","comment")) >> pDefault >>= withAttribute CommentTok)
parseRules ("VHDL","string") =
(((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","string")) >> pDefault >>= withAttribute StringTok))
parseRules ("VHDL","attribute") =
(((pDetectChar False '"' >>= withAttribute BaseNTok) >>~ pushContext ("VHDL","quot in att"))
<|>
((pDetectChar False '"' >>= withAttribute BaseNTok) >>~ pushContext ("VHDL","quot in att"))
<|>
((pDetectChar False ' ' >>= withAttribute NormalTok) >>~ (popContext))
<|>
((pDetectChar False '\'' >>= withAttribute BaseNTok) >>~ (popContext))
<|>
((pAnyChar ")=<>" >>= withAttribute BaseNTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","attribute")) >> pDefault >>= withAttribute BaseNTok))
parseRules ("VHDL","quot in att") =
(((pDetectChar False '"' >>= withAttribute BaseNTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","quot in att")) >> pDefault >>= withAttribute BaseNTok))
parseRules ("VHDL","signal") =
(((parseRules ("VHDL","preDetection")))
<|>
((lookAhead (pDetectChar False ';') >> (popContext) >> currentContext >>= parseRules))
<|>
((parseRules ("VHDL","generalDetection")))
<|>
(currentContext >>= \x -> guard (x == ("VHDL","signal")) >> pDefault >>= withAttribute NormalTok))
parseRules x = parseRules ("VHDL","start") <|> fail ("Unknown context" ++ show x)
| ambiata/highlighting-kate | Text/Highlighting/Kate/Syntax/Vhdl.hs | gpl-2.0 | 32,109 | 0 | 20 | 4,197 | 8,369 | 4,497 | 3,872 | 548 | 43 |
module Data.FNLP
(
module Data.Convertible
, module Data.Convertible.Auto
) where
import Data.Convertible
import Data.Convertible.Auto
| RoboNickBot/fnlp | src/Data/FNLP.hs | gpl-3.0 | 154 | 0 | 5 | 33 | 32 | 21 | 11 | 6 | 0 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Board where
import Piece
import qualified Data.Sequence as S
import qualified Data.List as L
import qualified Data.Foldable as F
type Row = S.Seq Piece
instance Pretty Row where
pretty o r = "│ " ++ L.intercalate " │ " prettyPieces ++ " │"
where prettyPieces = map (pretty o) . F.toList $ F.toList r
instance Pretty Board where
pretty o b = bTop
++ lkLnSep bSep (S.take 3 b) ++ bSep
++ pretty o (S.index b 3) ++ bLakTop
++ pLakeLn (S.index b 4) ++ bLakMid
++ pLakeLn (S.index b 5) ++ bLakBot
++ (lkLnSep bSep . S.take 3 $ S.drop 6 b) ++ bSep
++ pretty o (S.index b 9) ++ bBot
where bTop = "┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐\n"
bSep = "\n├───┼───┼───┼───┼───┼───┼───┼───┼───┼───┤\n"
bLakTop = "\n├───┼───┼───┴───┼───┼───┼───┴───┼───┼───┤\n"
bLakMid = "\n├───┼───┤ ├───┼───┤ ├───┼───┤\n"
bLakBot = "\n├───┼───┼───┬───┼───┼───┼───┬───┼───┼───┤\n"
bBot = "\n└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘"
lkLnSep s = L.intercalate s . F.toList . fmap (pretty o)
pLakeLn r = "│ " ++ L.intercalate " │ "
[ lkLnSep " │ " $ S.take 2 r
, lkLnSep " " . S.take 2 $ S.drop 2 r
, lkLnSep " │ " . S.take 2 $ S.drop 4 r
, lkLnSep " " . S.take 2 $ S.drop 6 r
, lkLnSep " │ " $ S.drop 8 r
] ++ " │"
type Board = S.Seq Row
type Pos = (Int, Int) -- (Row, Column)
(!) :: Board -> Pos -> Piece
s ! (r,c) = S.index (S.index s c) r
takeWhile' _ [] = []
takeWhile' p (x:xs)
| p x = x : takeWhile' p xs
| otherwise = [x]
posInRange:: Pos -> Board -> [Pos]
posInRange p@(r,c) b
| outOfBounds p = []
| range piece <= 0 = []
| otherwise = filter (canCollide piece . (b!)) targets
where outOfBounds (x,y) = x < 0 || x > 9 || y < 0 || y > 9
piece = b ! p
posInDir = concat [ [(r, y)| y <- map (+ c) ranges]
, [(x, c)| x <- map (+ r) ranges]
] where ranges = ps ++ ns
ps = [1..9]
ns = [-1, -2 .. -9]
isBlank pos = b ! pos == Piece None Empty True
targets = filter (not . outOfBounds)
$ case rank piece of
Scout -> takeWhile' isBlank posInDir
otherwise -> [ (r, c - 1), (r, c + 1)
, (r - 1, c), (r + 1, c)
]
placePiece :: Piece -> Pos -> Board -> Board
placePiece p (r,c) b = S.update c (S.update r p $ S.index b c) b
movablePieces :: Player -> Board -> [Pos]
movablePieces p b = filter (canMove p) pieces
where pieces = [(x,y)| x <- [0..9], y <- [0..9]]
canMove pl pc = (length $ posInRange pc b) > 0
&& owner (b!pc) == pl
movePiece :: Pos -> Pos -> Board -> Board
movePiece p@(r,c) p'@(r',c') b
| invalidMove = b
| otherwise = placePiece blank p $ placePiece winner p' b
where invalidMove = notElem p' $ posInRange p b
attacker = b ! p
defender = b ! p'
blank = Piece None Empty True
winner = collide attacker defender
gameOver :: Board -> Player
gameOver b | hasLost Blue = Red
| hasLost Red = Blue
| otherwise = None
where hasLost p = hasNoMove p || hasNoFlag p
hasNoMove p = length (movablePieces p b) == 0
hasNoFlag p = notElem (Piece p Flag False) pieces
pieces = [b!(x,y)| x <- [0..9], y <- [0..9]]
blankBoard :: Board
blankBoard = S.fromList
[ bln, bln, bln, bln, lln, lln, bln, bln, bln, bln
] where blank = Piece None Empty True
lake = Piece None Lake True
bln = S.replicate 10 blank
lln = S.fromList
[ blank, blank
, lake , lake
, blank, blank
, lake , lake
, blank, blank
]
| HalosGhost/stratagem | src/Board.hs | gpl-3.0 | 5,425 | 0 | 21 | 2,350 | 1,579 | 824 | 755 | 95 | 2 |
{-# LANGUAGE RecordWildCards, OverloadedStrings, TemplateHaskell, DeriveGeneric #-}
module Lamdu.GUI.ExpressionEdit.HoleEdit.State
( HoleState(..), hsSearchTerm
, emptyState, setHoleStateAndJump, assocStateRef
) where
import qualified Control.Lens as Lens
import Control.MonadA (MonadA)
import Data.Binary (Binary)
import Data.Store.Guid (Guid)
import qualified Data.Store.Transaction as Transaction
import GHC.Generics (Generic)
import qualified Graphics.UI.Bottle.Widget as Widget
import Lamdu.GUI.ExpressionEdit.HoleEdit.WidgetIds (WidgetIds(..))
import qualified Lamdu.GUI.ExpressionEdit.HoleEdit.WidgetIds as WidgetIds
import qualified Lamdu.Sugar.Types as Sugar
type T = Transaction.Transaction
newtype HoleState = HoleState
{ _hsSearchTerm :: String
} deriving (Eq, Generic)
Lens.makeLenses ''HoleState
instance Binary HoleState
emptyState :: HoleState
emptyState =
HoleState
{ _hsSearchTerm = ""
}
setHoleStateAndJump :: MonadA m => Guid -> HoleState -> Sugar.EntityId -> T m Widget.Id
setHoleStateAndJump guid state entityId = do
Transaction.setP (assocStateRef guid) state
let WidgetIds{..} = WidgetIds.make entityId
return hidOpenSearchTerm
assocStateRef :: MonadA m => Guid -> Transaction.MkProperty m HoleState
assocStateRef = Transaction.assocDataRefDef emptyState "searchTerm"
| rvion/lamdu | Lamdu/GUI/ExpressionEdit/HoleEdit/State.hs | gpl-3.0 | 1,392 | 0 | 11 | 236 | 326 | 191 | 135 | 31 | 1 |
{- -----------------------------------------------------------------------------
PTrader is a Personal Stock Trader Toolbox.
Copyright (C) 2012 Luis Cabellos
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------------------------------------------- -}
import PTrader.Report(
Report, runReport, newScreen, newLine, stocksState, indexState )
import Control.Monad( forever )
import System.Exit( exitSuccess )
import System.Posix.Unistd( sleep )
import System.Posix.Signals( Handler(..), installHandler, sigINT )
-- -----------------------------------------------------------------------------
stocks :: [String]
stocks = ["ENG.MC","SAN.MC","TEF.MC","OHL.MC","FER.MC"]
indexes :: [String]
indexes = ["^IBEX"]
myReport :: Report ()
myReport = do
-- clear console screen
newScreen
-- print the state of indexes
indexState indexes
newLine
-- print the state of selected stocks
stocksState stocks
-- -----------------------------------------------------------------------------
main :: IO ()
main = do
_ <- installHandler sigINT (CatchOnce exitSuccess) Nothing
forever $ do
-- print myReport using colors
runReport myReport True
-- wait 1 minute
sleep 60
-- -----------------------------------------------------------------------------
| zhensydow/ptrader | examples/example01.hs | gpl-3.0 | 1,870 | 0 | 10 | 268 | 220 | 125 | 95 | 22 | 1 |
module Main where
import Control.Applicative
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Monad
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.Function (on)
import Data.List (foldl')
import Data.Map.KDMap
import Data.Monoid
import Data.Time (UTCTime, getCurrentTime, diffUTCTime)
import Data.Vector ((!))
import Debug.Trace
import Graphics.Gloss
import qualified Graphics.Gloss.Data.Color as Color
import Graphics.Gloss.Interface.IO.Game
import Pipes
import Pipes.RealTime
import qualified Pipes.Prelude as PP
import System.Environment
import System.Directory
import Data.Ephys.Spike
import Data.Ephys.OldMWL.Parse
import Data.Ephys.OldMWL.ParseSpike
drawPoint :: Int -> Int -> Double -> (Point4, SpikeTime) -> Picture
drawPoint xInd yInd tNow (p, tSpike) =
translate (realToFrac $ pointD p (Depth xInd)) (realToFrac $ pointD p (Depth yInd)) $
Pictures [ color (pointColor tNow tSpike) $
circleSolid (1e-6 + log (realToFrac $ pointW p) / 3000000)
, circle (1e-6 + log (realToFrac $ pointW p) / 3000000)
]
pointColor :: Double -> SpikeTime -> Color.Color
pointColor tNow (SpikeTime tSpike) = Color.makeColor r g b 1
where e tau = exp (-1 * (max dt 0) / tau)
dt = (realToFrac tNow) - (realToFrac tSpike)
r = e 0.2
g = e 1
b = e 20
newtype SpikeTime = SpikeTime { unSpikeTime :: Double }
deriving (Eq)
instance Monoid SpikeTime where
mempty = SpikeTime (-1e6)
mappend a b = SpikeTime $ (max `on` unSpikeTime) a b
data World = World { mainMap :: KDMap Point4 SpikeTime
, selection :: Maybe (Point4, SpikeTime)
, time :: Double
, spikeChan :: TChan TrodeSpike
, chanX :: Int
, chanY :: Int
}
world0 :: TChan TrodeSpike -> World
world0 c = World KDEmpty Nothing 4492 c 0 1
drawTree :: Int -> Int -> Double -> KDMap Point4 SpikeTime -> Picture
drawTree xInd yInd tNow = Pictures . map (drawPoint xInd yInd tNow) . toList
drawSelection :: Int -> Int -> Double -> Maybe (Point4,SpikeTime) -> [Picture]
drawSelection _ _ _ Nothing = []
drawSelection xInd yInd tNow (Just (p,i)) = [drawPoint xInd yInd tNow (p,i)]
drawWorld :: World -> IO Picture
drawWorld w = do
return $ translate (-200) (-200) $ scale 2000000 2000000 $
Pictures (drawTree x y t (mainMap w) : drawSelection x y t (selection w))
where t = time w
x = chanX w
y = chanY w
flushChan :: TChan a -> STM [a]
flushChan c = go []
where go acc = do
emp <- isEmptyTChan c
if emp
then return $ reverse acc
else do
e <- readTChan c
go (e:acc)
fTime :: UTCTime -> Float -> World -> IO World
fTime t0 _ w = do
tNext <- getExperimentTime t0 4492 -- (old way) time w + realToFrac t
let c = spikeChan w
spikes <- atomically $ flushChan c
let spikeCoords s = (spikeAmplitudes s ! 1, spikeAmplitudes s ! 2)
toPoint s = Point4
(realToFrac $ spikeAmplitudes s ! 0)
(realToFrac $ spikeAmplitudes s ! 1)
(realToFrac $ spikeAmplitudes s ! 2)
(realToFrac $ spikeAmplitudes s ! 3)
1.0
points = map toPoint spikes
times = map (SpikeTime . spikeTime) spikes
newMap = foldl' (\m (p,t) -> add m 0.000016 p t) (mainMap w) (zip points times)
return w { mainMap = newMap,
time = tNext
}
------------------------------------------------------------------------------
fInputs :: Event -> World -> IO World
fInputs (EventKey (MouseButton b) Up _ (x,y)) w
-- | b == LeftButton =
-- let newMap = add (mainMap w) 20.0 (Point4 (realToFrac x) (realToFrac y) 3.0) (SpikeTime 0)
-- in return w { mainMap = newMap }
| b == LeftButton =
return $ w { chanX = (chanX w + 1) `mod` 4}
| b == RightButton =
return $ w { chanY = (chanY w + 1) `mod` 4}
| otherwise = return w
fInputs _ w = return w
------------------------------------------------------------------------------
main :: IO ()
main = do
(f:_) <- getArgs
--let fn = "/home/greghale/Data/caillou/112812clip2/" ++
-- f ++ "/" ++ f ++ ".tt"
let fn = f
fileExist <-doesFileExist fn
when (not fileExist) $ error "File does not exist"
c <- newTChanIO
t0 <- getCurrentTime
_ <- async . runEffect $ produceTrodeSpikesFromFile fn 16
>-> relativeTimeCat (\s -> spikeTime s - 4492)
>-> (forever $ await >>= lift . atomically . writeTChan c)
playIO (InWindow "KDMap" (500,500) (100,100))
white 30 (world0 c) drawWorld fInputs (fTime t0)
getExperimentTime :: UTCTime -> Double -> IO Double
getExperimentTime t0 et0 =
(et0 +) . realToFrac . flip diffUTCTime t0 <$> getCurrentTime
| imalsogreg/tetrode-ephys | utils/drawKD.hs | gpl-3.0 | 4,889 | 0 | 16 | 1,294 | 1,681 | 882 | 799 | 113 | 2 |
module Objects where
import Geometry3
import Types
printObj :: Object -> String
printObj (Sphere c r _) = "Sphere " ++ show c ++ " " ++ show r
printObj (Triangle a b c _ _) = "Triangle " ++ show a ++ " " ++
show b ++ " " ++ show c
calcNormal :: Vec3 -> Vec3 -> Vec3 -> Vec3
calcNormal a b c = normalize $ cross (subt b a) (subt c a)
{- Smart Constructor for Object that computes triangle normal -}
makeTriangle :: Vec3 -> Vec3 -> Vec3 -> Material -> Object
makeTriangle a b c = Triangle a b c (calcNormal a b c)
okObject :: Object -> Bool
okObject Sphere{} = True
okObject (Triangle a b c n _) = a /= b && b /= c && a /= c && okVec3 n
makeParallelPiped :: Vec3 -- corner point
-> Vec3 -- width vector (must be positive)
-> Vec3 -- height vector (must be positive)
-> Vec3 -- depth vector (must be positive)
-> Material
-> [Object] -- list of triangles that make cuboid
makeParallelPiped p0 wd0 ht0 dp0 m = ts
where
(wd,ht,dp) = mapT3 (vecM id) (wd0,ht0,dp0)
p1 = add p0 wd
p2 = add p0 ht
p3 = add p1 ht
p4 = add p0 dp
p5 = add p1 dp
p6 = add p2 dp
p7 = add p3 dp
t0 = makeTriangle p0 p2 p1 m --back face
t1 = makeTriangle p1 p2 p3 m
t2 = makeTriangle p0 p1 p5 m --bottom face
t3 = makeTriangle p0 p5 p4 m
t4 = makeTriangle p0 p4 p2 m --left side face
t5 = makeTriangle p2 p4 p6 m
t6 = makeTriangle p2 p6 p3 m --top face
t7 = makeTriangle p3 p6 p7 m
t8 = makeTriangle p3 p7 p5 m --right face
t9 = makeTriangle p3 p5 p1 m
t10 = makeTriangle p4 p5 p6 m --front face
t11 = makeTriangle p5 p7 p6 m
ts = [t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11]
mapT3 :: (a -> b) -> (a,a,a) -> (b,b,b)
mapT3 f (a,b,c) = (f a, f b, f c)
| jrraymond/ray-tracer | src/Objects.hs | gpl-3.0 | 1,849 | 0 | 10 | 589 | 729 | 386 | 343 | 44 | 1 |
module Util where
import Ast
import Char
import Data.Bits
import Text.ParserCombinators.Parsec.Pos
hex d v = hex_ d (fromInteger v)
hex_ 0 v = ""
hex_ d v = (hex_ (d-1) (v `div` 16)) ++ [(hx (v `mod` 16))]
bv n b = if (testBit b n) then "1" else "0"
bz 0 v = ""
bz n v = (bv (n-1) v) ++ (bz (n-1) v)
bz_ n v = bz n (toInteger v)
hx v | v>9 = chr $ ord 'A' + (v-10)
hx v = chr $ ord '0' + v
islabel l (p,i,(Label s)) = s == l
islabel _ _ = False
haslabel ast l = or $ map (islabel l) ast
scanlM_ f v p [] = return []
scanlM_ f v p ((l,i,x):xs) = let v'=(f v p (l,i,x))
in do v'' <- v'
l' <- scanlM_ f v' ((l,v'',x):p) xs
return $ (v):l'
scanlM f v l = scanlM_ f v [] l
labtargets ast = foldl (++) [] (map lt_ ast)
where lt_ (p,i,Store x y z) = lt__ p i z
lt_ (p,i,Load x y z) = lt__ p i z
lt_ (p,i,Branch x y) = lt__ p i y
lt_ (p,i,Jump x) = lt__ p i x
lt_ (p,i,Data x y) = (lt__ p i x) ++ (lt__ p i y)
lt_ (p,i,Align x y z) = (lt__ p i x) ++ (lt__ p i y) ++ (lt__ p i z)
lt_ (p,i,Origin x) = lt__ p i x
lt_ x = []
lt__ p i (Lab s) = [(p,i,s)]
lt__ p i (EMul x y) = (lt__ p i x) ++ (lt__ p i y)
lt__ p i (EDiv x y) = (lt__ p i x) ++ (lt__ p i y)
lt__ p i (EAdd x y) = (lt__ p i x) ++ (lt__ p i y)
lt__ p i (ESub x y) = (lt__ p i x) ++ (lt__ p i y)
lt__ p i x = []
labelloc [] l = 0
labelloc (((Label b),n):as) l = if b == l then n else (labelloc as l)
labelloc (a:as) l = labelloc as l
loc n s = n ++ " " ++ (show name) ++ "(" ++ (show line) ++ "," ++ (show coln) ++ ")"
where name = sourceName s
line = sourceLine s
coln = sourceColumn s
| luebbers/reconos | tools/fsmLanguage/kurm/assembler/Util.hs | gpl-3.0 | 2,160 | 0 | 13 | 1,016 | 1,163 | 602 | 561 | 45 | 13 |
module MLSB.Eval where
import qualified Data.Map as Map
import Data.Functor.Foldable (Fix(..), Recursive(..), Corecursive(..))
import Data.Monoid((<>))
import Data.Map (Map, (!))
import MLSB.Types
data Val =
ValC Const
| ValFn (Val -> Val)
printVal :: Val -> String
printVal val =
case val of
ValC c -> "ValC "<>show c
ValFn _ -> "ValFn <func>"
eqVal :: Rational -> Val -> Val -> Bool
eqVal tol a b =
case (a,b) of
(ValC c1, ValC c2) -> eqConst tol c1 c2
_ -> error $ "eqVal: can't compare non-constant values: " <> printVal a <> ", " <> printVal b
type Env = Map String Val
evalExpr :: Env -> Expr -> Val
evalExpr env expr =
case expr of
Const c -> ValC c
Ident i ->
case Map.lookup i env of
Just val -> val
Nothing -> error $ "Invalid identifier '"<>i<>"'"
Lam (Pat p) elam -> ValFn $ \v -> evalExpr (Map.insert p v env) elam
Let (Pat p) elet ein -> evalExpr (Map.insert p (evalExpr env elet) env) ein
App elam earg ->
case evalExpr env elam of
ValFn f -> f (evalExpr env earg)
val -> error "Unable to apply to non-lambda"
Slice _ _ -> error "Slicing is not implemented"
evalExpr1 :: Env -> Expr1 -> Val
evalExpr1 env = evalExpr env . cata embed
emptyEnv :: Env
emptyEnv = Map.empty
initEnv :: Env
initEnv = Map.fromList $
let
arithm nm op =
ValFn $ \a -> ValFn $ \b ->
case (a,b) of
(ValC (ConstR af), ValC (ConstR bf)) -> ValC $ ConstR $ af`op`bf
_ -> error $ "Invalid operands for ("<>nm<>")"
in [
("+", arithm "+" (+))
, ("-", arithm "-" (-))
, ("*", arithm "*" (*))
, ("/", arithm "/" (/))
, ("<>",
ValFn $ \a -> ValFn $ \b ->
case (a,b) of
(ValC (ConstS as), ValC (ConstS bs)) -> ValC $ ConstS $ as<>bs
_ -> error $ "Invalid operands for ("<>"<>"<>")"
)
]
| grwlf/ml-df | src/MLSB/Eval.hs | gpl-3.0 | 1,867 | 0 | 20 | 527 | 807 | 426 | 381 | 57 | 8 |
module Types where
-- Name representa el nombre de una lista de peliculas.
type Name = String
-------------------------
-- AST
data Comm = Seq Comm Comm -- secuencia de comandos
| Def Name FList -- define una lista
| Add Name FList -- operador <<
| Rem Name FList -- operador >>
deriving Show
-- Formato de la lista antes de ser evaluada.
data FList = New Params
| And FList FList
| Var Name
deriving Show
-- Parametros a partir de los cuales pueden formarse las listas.
-- Los parametros no especificados tomaran el valor por defecto de
-- la API.
data Params = P { rate :: Maybe Integer,
limit :: Maybe Integer,
genre :: Maybe String,
query :: Maybe String,
sorted :: Maybe String,
order :: Maybe String
} deriving Show
-- El objetivo de AuxParams es simplemente hacer el parseo más fácil.
-- La representación de los parámetros a partir de la cual se hará el
-- request es el record de arriba de tipo Params
-- Ver en Parser.hs
data AuxParams = Rating Integer
| Limit Integer
| Genre String
| Query String
| Sort String
| Order String
deriving Show
-------------------------
-- Lista de listas de peliculas
type Env = [(Name, [Film])]
-- Posibles errores durante la evaluación
data Error = BadParams -- ninguna película satisface los parámetros
| Undef Name -- lista no definida
| IQuit -- salir del interprete
-- Estado que llevara el interprete.
data State = State { d_dir :: String, -- directorio donde guardar las descargas
lfile :: String, -- ultimo archivo cargado
list :: Env, -- lista con todas las listas de peliculas
dlist :: [String] -- pids de los procesos que están descargando
} -- los represento como String para no tener que importar el modulo System.Process
-- también me sirve para facilitar la función stopDownload (ver en Download.hs)
-- Representacion de una pelicula luego de ser evaluada.
data Film = Film { film_id :: Int,
imdb_code :: String,
title :: String,
year :: Int,
rating :: Float,
runtime :: Int,
genres :: [String],
synopsis :: String,
language :: String,
background_image :: String,
cover_image :: String,
torrents :: [Torrent]
} deriving (Show, Eq, Ord)
-- Representacion de un archivo torrent luego de que la película correspondiente sea evaluada.
data Torrent = Torrent { hash :: String,
url :: String,
quality :: String,
seeds :: Int,
peers :: Int,
size :: String
} deriving (Show, Eq, Ord)
| g-deluca/yts-dl | app/Types.hs | gpl-3.0 | 3,686 | 0 | 9 | 1,749 | 433 | 276 | 157 | 53 | 0 |
module View.Project
( editProjectForm
, projectContactForm
, inviteForm
, projectBlogForm
, projectConfirmSharesForm
, renderBlogPost
, renderProject
, viewForm
) where
import Import
import Data.Filter
import Data.Order
import Model.Currency
import Model.Markdown
import Model.Project
import Model.Shares
import Model.Role
import Widgets.Markdown
import qualified Data.Text as T
import Data.Time.Clock
import Yesod.Markdown
renderProject :: Maybe ProjectId -> Project -> [Int64] -> Maybe (Entity Pledge) -> WidgetT App IO ()
renderProject maybe_project_id project pledges pledge = do
let share_value = projectShareValue project
users = fromIntegral $ length pledges
shares = sum pledges
project_value = share_value $* fromIntegral shares
description = markdownWidgetWith (fixLinks $ projectHandle project) $ projectDescription project
maybe_shares = pledgeShares . entityVal <$> pledge
now <- liftIO getCurrentTime
amounts <- case projectLastPayday project of
Nothing -> return Nothing
Just last_payday -> handlerToWidget $ runDB $ do
-- This assumes there were transactions associated with the last payday
[Value (Just last) :: Value (Maybe Rational)] <-
select $
from $ \ transaction -> do
where_ $
transaction ^. TransactionPayday ==. val (Just last_payday) &&.
transaction ^. TransactionCredit ==. val (Just $ projectAccount project)
return $ sum_ $ transaction ^. TransactionAmount
[Value (Just year) :: Value (Maybe Rational)] <-
select $
from $ \ (transaction `InnerJoin` payday) -> do
where_ $
payday ^. PaydayDate >. val (addUTCTime (-365 * 24 * 60 * 60) now) &&.
transaction ^. TransactionCredit ==. val (Just $ projectAccount project)
on_ $ transaction ^. TransactionPayday ==. just (payday ^. PaydayId)
return $ sum_ $ transaction ^. TransactionAmount
[Value (Just total) :: Value (Maybe Rational)] <-
select $
from $ \ transaction -> do
where_ $ transaction ^. TransactionCredit ==. val (Just $ projectAccount project)
return $ sum_ $ transaction ^. TransactionAmount
return $ Just (Milray $ round last, Milray $ round year, Milray $ round total)
((_, update_shares), _) <- handlerToWidget $ generateFormGet $ maybe previewPledgeForm pledgeForm maybe_project_id
$(widgetFile "project")
renderBlogPost :: Text -> ProjectBlog -> WidgetT App IO ()
renderBlogPost project_handle blog_post = do
let (Markdown top_content) = projectBlogTopContent blog_post
(Markdown bottom_content) = maybe (Markdown "") ("***\n" <>) $ projectBlogBottomContent blog_post
title = projectBlogTitle blog_post
content = markdownWidgetWith (fixLinks project_handle) $ Markdown $ T.snoc top_content '\n' <> bottom_content
$(widgetFile "blog_post")
editProjectForm :: Maybe (Project, [Text]) -> Form UpdateProject
editProjectForm project =
renderBootstrap3 $ UpdateProject
<$> areq' textField "Project Name" (projectName . fst <$> project)
<*> areq' snowdriftMarkdownField "Description" (projectDescription . fst <$> project)
<*> (maybe [] (map T.strip . T.splitOn ",") <$> aopt' textField "Tags" (Just . T.intercalate ", " . snd <$> project))
<*> aopt' textField "Github Repository" (projectGithubRepo . fst <$> project)
projectBlogForm :: Maybe (Text, Text, Markdown) -> Form (UTCTime -> UserId -> ProjectId -> DiscussionId -> ProjectBlog)
projectBlogForm defaults = renderBootstrap3 $
let getTitle (title, _, _) = title
getHandle (_, handle, _) = handle
getContent (_, _, content) = content
in mkBlog
<$> areq' textField "Post Title" (getTitle <$> defaults)
<*> areq' textField "Post Handle" (getHandle <$> defaults)
<*> areq' snowdriftMarkdownField "Content" (getContent <$> defaults)
where
mkBlog :: Text -> Text -> Markdown -> (UTCTime -> UserId -> ProjectId -> DiscussionId -> ProjectBlog)
mkBlog title handle (Markdown content) now user_id project_id discussion_id =
let (top_content, bottom_content) = break (== "***") $ T.lines content
in ProjectBlog now title handle user_id project_id
discussion_id (Markdown $ T.unlines top_content)
(if null bottom_content then Nothing else Just $ Markdown $ T.unlines bottom_content)
projectContactForm :: Form Markdown
projectContactForm = renderBootstrap3 $ areq' snowdriftMarkdownField "" Nothing
inviteForm :: Form (Text, Role)
inviteForm = renderBootstrap3 $ (,)
<$> areq' textField "About this invitation:" Nothing
<*> areq roleField "Type of Invite:" (Just TeamMember)
viewForm :: Form (Filterable -> Bool, Orderable -> [Double])
viewForm = renderBootstrap3 $ (,)
<$> (either (const defaultFilter) id . parseFilterExpression . fromMaybe "" <$> aopt' textField "filter" Nothing)
<*> (either (const defaultOrder) id . parseOrderExpression . fromMaybe "" <$> aopt' textField "sort" Nothing)
projectConfirmSharesForm :: Maybe Int64 -> Form SharesPurchaseOrder
projectConfirmSharesForm = renderBootstrap3 . fmap SharesPurchaseOrder . areq' hiddenField ""
| Happy0/snowdrift | View/Project.hs | agpl-3.0 | 5,569 | 0 | 30 | 1,429 | 1,580 | 796 | 784 | -1 | -1 |
import System.Plugins
import API
src = "../Plugin.hs"
wrap = "../Wrapper.hs"
apipath = "../api"
main = do status <- make src ["-i"++apipath]
case status of
MakeSuccess _ _ -> f
MakeFailure e-> mapM_ putStrLn e
where f = do v <- load "../Plugin.o" ["../api"] [] "resource"
-- (i,_) <- exec "ghc" ["--numeric-version"]
-- mapM_ putStrLn i
putStrLn "done."
| Changaco/haskell-plugins | testsuite/pdynload/null/prog/Main.hs | lgpl-2.1 | 465 | 0 | 11 | 168 | 116 | 58 | 58 | 11 | 2 |
{-
Copyright (C) 2009 Andrejs Sisojevs <andrejs.sisojevs@nextmail.ru>
All rights reserved.
For license and copyright information, see the file COPYRIGHT
-}
--------------------------------------------------------------------------
--------------------------------------------------------------------------
{-# LANGUAGE DeriveDataTypeable #-}
-- 1) HelloWorld program that doesn't use PCLT and PCLT-DB packages is to be found in PCLT packages examples directory.
-- 2) HelloWorld program that uses only PCLT (but no PCLT-DB) package is to be found in PCLT packages examples directory. All the explanations about using PCLT are also there, but here are omited.
-- 3)< HelloWorld program that uses both PCLT and PCLT-DB packages is the one you are currently looking at.
-- It's best to understand (1) and (2) before trying to understand what's going on in this listing here.
-- Before running this exaple user must run HelloWorld.sql
module HelloWorld where
-----------------------------------------------------
-- Modules necessary for our PCLTCatalog
import Control.Concurrent
import Database.HDBC
import Database.HDBC.PostgreSQL
import qualified Data.ByteString.Lazy.UTF8.Unified as Lazy (ByteString)
import qualified Data.ByteString.Lazy.UTF8.Unified as B hiding (ByteString)
import Data.List
import qualified Data.Map as M
import Data.Map (Map, (!))
import Data.Typeable
import qualified Text.ConstraintedLBS as CB
import Database.PCLT -- this module exports most required PCLT-DB modules
import Text.PCLT
import Prelude hiding (putStrLn, readLn)
import System.IO hiding (putStrLn, readLn, hPutStr)
import System.IO.UTF8 -- putStrLn from here will be used to correctly output russian letters
-----------------------------------------------------
-----------------------------------------------------
-- Application specific modules
import Control.Exception
import HelloWorld_Data -- Application specific ADTs and type synonyms
import HelloWorld__ -- instances for ShowAsPCSI and HasStaticRawPCLTs
-----------------------------------------------------
-----------------------------------------------------
-- Functional part of app
type SayHelloWorld_Mode = Int
sayHelloWorld :: SayHelloWorld_Mode -> Either HelloWorldError HelloWorld
sayHelloWorld mode =
case mode of
0 -> Right HelloWorld
1 -> Left NoWorld_HWE
2 -> Left $ AmbiguousChoiceOfWorlds_HWE ("RealWorld", 1) ("VirtualWorld", 2) [("OtherWorld1", 3), ("OtherWorld2", 4), ("OtherWorld3", 5)]
3 -> Left $ SomeVeryStrangeError_HWE 5789 "Noise..." True (Just True) Nothing (SomeException DivideByZero)
4 -> Left $ FailedDueToErrorInSubsystem_HWE ErrorType1_EIS
5 -> Left $ FailedDueToErrorInSubsystem_HWE ErrorType2_EIS
6 -> Left $ FailedDueToErrorInSubsystem_HWE $ FailedDueToErrorInSub_sub_system_EIS ErrorType1_EISS
7 -> Left $ FailedDueToErrorInSubsystem_HWE $ FailedDueToErrorInSub_sub_system_EIS ErrorType2_EISS
-------------------------------------
--some constants required by catalogizing system
__db_name = "pcltcatalogs"
__dbms_user = "user_pcltcatalogs_data_reader"
__dbms_user_password = "data_reader_password"
__connection_string_delimiter = " "
__connectionString = "dbname=" ++ __db_name ++ __connection_string_delimiter
__connectionString' = __connectionString ++ "user=" ++ __dbms_user ++ __connection_string_delimiter
__connectionString'' = __connectionString' ++ "password=" ++ __dbms_user_password ++ __connection_string_delimiter
__update_frequency_sec = 8
__my_lng = "rus" -- possible values: "eng", "rus", "hs_"
__my_sdl = InfinitelyBig_SDL -- possible values: Zero_SDL < One_SDL < SDL Int < InfinitelyBig_SDL
__my_stderr_clbs_size = 50000
__my_stdout_clbs_size = 50000
__catalog_id = 50
type Microseconds = Int
data CatalogControl = -- MVar of this will be in between HelloWorld mainmodule and thread that will regularly update catalog from DB
CatalogControl {
catcCatalogMV :: MVar PCLT_Catalog
, catcUpdateFrequency :: MVar Microseconds
, catcUpdatorLoopHolder :: MVar Bool -- initialized as True; whenever we putthis to False, the next iteration on of update cycle begins with service termination
, catcUpdatorTaskTriggerChan :: Chan Bool -- between iterations service awaits on this channel; we regularly send thereit gets catcUpdatorLoopHolder value; if False is sent, updator finishes
, catcUpdatorTaskTriggerThreadID :: ThreadId
, catcUpdatorThreadID :: ThreadId
} deriving (Typeable)
acquireCatalog :: StdErr_CLBS -> (ShowDetalizationLevel, LanguageName) -> IO (CatalogControl, MVar StdErr_CLBS)
acquireCatalog stderr_clbs (stderr_sdl, stderr_lng) = do
let catalog_config =
defaultPCLTInnerConfig {
pcsStrictOrient_ofParamsAndCmpsts_onDfltLngTplsSets =
(pcsStrictOrient_ofParamsAndCmpsts_onDfltLngTplsSets defaultPCLTInnerConfig) {
soExcludingCompParameters = soExcludingCompParameters (pcsStrictOrient_ofParamsAndCmpsts_onDfltLngTplsSets defaultPCLTInnerConfig)
++ [("E_HWE_AMBWRLDCH_OW", "__row_idx")] -- this is described in a HelloWorld that uses only PCLT (but no PCLT-DB)
}
}
updateFrequency_mv <- newMVar (__update_frequency_sec * 1000000)
updatorLoopHolder_mv <- newMVar True
let taskEnablerCycle :: Chan Bool -> IO ()
taskEnablerCycle ch = do
freq <- readMVar updateFrequency_mv
threadDelay freq
enabled_isit <- readMVar updatorLoopHolder_mv
putStrLn "#catalog updated...#"
writeChan ch enabled_isit
case enabled_isit of
True -> taskEnablerCycle ch
False -> return ()
let taskEnablerThread :: IO (Chan Bool, ThreadId) -- this thread will regularly stimulate iterations of catalog updator
taskEnablerThread = do
ch <- newChan
tm_TID <- forkIO $ taskEnablerCycle ch
return (ch, tm_TID)
(aliveChan, tm_TID) <- taskEnablerThread -- thread started
stderr_clbs_mv <- newMVar stderr_clbs
let errorsReporter :: PCLT_Catalog -> CatalogUpdateFromDBErrors -> IO () -- ths is how the catalog updator service must react on catalog read failure (due to error); if catalog isn't read, the previous version of catalog is used here
errorsReporter cat cue = modifyMVar_
stderr_clbs_mv
(\ _errs_clbs -> return $ pcsi2text_plus_errs_1 _errs_clbs (showAsPCSI cue) (__my_sdl, __my_lng) cat )
serviceStart :: IO CatalogControl
serviceStart = do
db_conn <- connectPostgreSQL __connectionString''
serv_db_conn <- clone db_conn -- good practice for cases, when have multiple same connections - make a prototype and clone it as many times as needed
(cat_mv, us_TID) <- runCatalogUpdatorService
(__catalog_id, catalog_config, PCLTRawCatalog__HelloWorld) -- With this catalog updator will start it's service. This way we ensure, that even if DB connection fails, we still have a catalog available.
(serv_db_conn, True) -- True says, that server must disconnect assigned to it DB connection, when it finishes
errorsReporter
aliveChan
disconnect db_conn -- prototype isn't needed anymore
return CatalogControl {
catcCatalogMV = cat_mv
, catcUpdateFrequency = updateFrequency_mv
, catcUpdatorLoopHolder = updatorLoopHolder_mv
, catcUpdatorTaskTriggerChan = aliveChan
, catcUpdatorTaskTriggerThreadID = tm_TID
, catcUpdatorThreadID = us_TID
}
cc <- serviceStart
return (cc, stderr_clbs_mv)
showHelloWorld :: SayHelloWorld_Mode -> (StdOut_CLBS, StdErr_CLBS) -> (ShowDetalizationLevel, LanguageName, PCLT_Catalog) -> (StdOut_CLBS, StdErr_CLBS)
showHelloWorld mode (stdout_clbs, stderr_clbs) (sdl, lng, catalog) = -- showHelloWorld here doesn't differ the HelloWorld, that uses only PCLT (but no PCLT-DB) - it is described there
let err_or_HelloWorld = sayHelloWorld mode
(new_stdout_clbs, new_stderr_clbs) =
pcsi2text_plus_errs_2
(stdout_clbs, stderr_clbs)
(showAsPCSI err_or_HelloWorld)
(sdl, lng)
catalog
in (new_stdout_clbs, new_stderr_clbs)
main = run_test __my_lng __my_sdl
run_test _lng _sdl =
let stderr_clbs0 = newCLBS __my_stderr_clbs_size
stdout_clbs0 = newCLBS __my_stdout_clbs_size
in do (catalog_control, stderr_clbs_mv) <- acquireCatalog stderr_clbs0 (__my_sdl, __my_lng)
putStrLn ("Language, SDL (detailization level), update frequency (sec): " ++ show (_lng, _sdl, __update_frequency_sec))
putStrLn "----Init-errors:-----------------"
stderr_clbs1 <- modifyMVar stderr_clbs_mv (\ stderr_clbs1 -> return (stderr_clbs0, stderr_clbs1))
putStrLn $ show stderr_clbs1
dump stderr_clbs1
putStrLn "----Cycle-start:-----------------"
let iterate_ = do
putStrLn "----New-iteration:---------------"
putStrLn "Input sayHelloWorld mode (0-7; '-1' to exit): "
mode <- readLn
case mode >= 0 && mode <= 7 of
True -> do (stdout_clbs1, stderr_clbs1) <- -- stderr_clbs1 accumulates all errors from work of catalog udator servece, and independently also accumulates errors from interaction with user
withMVar
(catcCatalogMV catalog_control)
(\ catalog ->
modifyMVar
stderr_clbs_mv
(\ _stderr_clbs ->
return ( stderr_clbs0 -- in each iteration of interaction with user, stderr gets shown and emptyed
, showHelloWorld
mode
(stdout_clbs0, _stderr_clbs)
(__my_sdl, __my_lng, catalog)
)
)
)
putStrLn "----Errors:----------------------"
putStrLn_paged 12 $ show stderr_clbs1
putStrLn "----Output:----------------------"
putStrLn $ show stdout_clbs1
iterate_
False -> case mode == (-1) of
True -> modifyMVar_ (catcUpdatorLoopHolder catalog_control) (\ _ -> return False) -- tell updator services to finish
False -> iterate_
iterate_
putStrLn_paged :: Int -> String -> IO ()
putStrLn_paged page_size s = f $ lines s
where
f lines_list =
let (to_print, to_next_itera) = splitAt page_size lines_list
in do putStrLn (concat $ intersperse "\n" to_print)
case null to_next_itera of
True -> return ()
False -> f to_next_itera << hGetChar stdin << putStrLn "\n-------Press any key to continue...-------"
dump :: Show a => a -> IO ()
dump a = do
h <- openFile "./dump.out" WriteMode -- WriteMode -- AppendMode
hPutStr h $ show a
hClose h
infixr 1 <<
(<<) :: Monad m => m b -> m a -> m b
f << x = x >> f
-----------------------------------------------------
-----------------------------------------------------
-- Representations
-- moved to file HelloWorld__.hs
{-
-------------------------------------------------------------------------
-- CONCLUSION
It is a lot of work to play multilinguality, using PCLT-DB. The ShowAsPCSI instaniations, HasStaticRawPCLTs instaniations, templates management... however PCLT-DB was built with an aim, that once catalog is setup, tested and put to work, it's management cost is minimal possible. When using PCLT only (no DB) the following management points are there:
a) Choose catalog configuration in haskell code.
b) Adjust (together with (c)) templates in an electronic table (f.e. using OpenOffice Calc).
c) Adjust (together with (b)) templates "calls" in ShowAsPCSI instances.
d) From (b) fill in HasStaticRawPCLTs instances
e) Use HasStaticRawPCLTs instances to unite into module-wide and package-wide raw template sets.
When using PCLT-DB the following management points there are:
f) Choose catalog configuration and store it in DB.
g) Adjust (together with (c)) templates in DB.
j) Use collections in DB in order to unite module-wide and package-wide template sets.
i) If needed, manage configure and representation policies in DB - a way to set different schemes of detalization requirements "with one key press".
Possible economies:
(f) makes unnecessary (a)
(g) makes unnecessary (b)
(j) makes unnecessary (d) and (e)
(f,g,j) is considered to require less code and management cost than (a,b,d,e)
One might get confused: why then Database.PCLT.runCatalogUpdatorService input still requires a some PCLT_InnerConfig and an instance of HasStaticRawPCLTs, if all this is now kept in DB?
The answer:
0) If DB for some reasons is unawailable, catalog will be formed from the data hardcoded in HasStaticRawPCLTs instances, and using some hardcoded config.
1) Despite (a,b,d,e) becomes unnecessary, one may still choose to use them. (a,b,d,e) and (f,g,j) may work together - if DB is off, hardcoded version (a,b,d,e) of catalog is always available! Double cost for double reliability, why not, if resources allow.
2) But even if programmer doesn't want to manage (a,b,d,e), it is asummed, that at least templates used by PCLT/-DB itselt are nice to have operatively available. In this case on input to
Database.PCLT.runCatalogUpdatorService programmer puts
Database.PCLT.PCLTRawCatalog__Database_PCLT_UpdatableCatalog
(or Text.PCLT.PCLTRawCatalog__Text_PCLT_InitialDefaultCatalog)
and Text.PCLT.Config.defaultPCLTInnerConfig.
Best regards, Belka
-} | Andrey-Sisoyev/PCLT-DB | examples/HelloWorld/HelloWorld.hs | lgpl-2.1 | 16,119 | 0 | 29 | 5,323 | 1,814 | 963 | 851 | -1 | -1 |
module FreePalace.Handlers.Incoming where
import Control.Concurrent
import Control.Exception
import qualified System.Log.Logger as Log
import qualified FreePalace.Domain.Chat as Chat
import qualified FreePalace.Domain.GUI as GUI
import qualified FreePalace.Domain.State as State
import qualified FreePalace.Domain.User as User
import qualified FreePalace.Media.Loader as MediaLoader
import qualified FreePalace.Messages.Inbound as InboundMessages
import qualified FreePalace.Messages.PalaceProtocol.InboundReader as PalaceInbound
import qualified FreePalace.Net.PalaceProtocol.Connect as Connect
-- TODO Time out if this takes too long, don't keep listening, tell the main thread.
-- TODO Make sure exceptions are caught so as not to block the main thread waiting on the MVar
initializeMessageDispatcher :: MVar State.Connected -> State.Connected -> IO ()
initializeMessageDispatcher conveyorOfStateBackToMainThread clientState =
do
Log.debugM "Incoming.Message.Await" $ "Awaiting initial handshake with state: " ++ (show clientState)
header <- readHeader clientState
Log.debugM "Incoming.Message.Header" (show header)
message <- readMessage clientState header
newState <- case message of
InboundMessages.HandshakeMessage _ -> handleInboundEvent clientState message
_ -> throwIO $ userError "Connection failed. No handshake."
Log.debugM "Incoming.Message.Processed" $ "Message processed. New state: " ++ (show newState)
putMVar conveyorOfStateBackToMainThread newState
dispatchIncomingMessages newState
-- TODO Handle connection loss
dispatchIncomingMessages :: State.Connected -> IO ()
dispatchIncomingMessages clientState =
do
Log.debugM "Incoming.Message.Await" $ "Awaiting messages with state: " ++ (show clientState)
header <- readHeader clientState
Log.debugM "Incoming.Message.Header" (show header)
message <- readMessage clientState header
newState <- handleInboundEvent clientState message
Log.debugM "Incoming.Message.Processed" $ "Message processed. New state: " ++ (show newState)
dispatchIncomingMessages newState
readHeader :: State.Connected -> IO InboundMessages.Header
readHeader clientState =
case State.protocolState clientState of
State.PalaceProtocolState connection messageConverters -> PalaceInbound.readHeader connection messageConverters
readMessage :: State.Connected -> InboundMessages.Header -> IO InboundMessages.InboundMessage
readMessage clientState header =
case State.protocolState clientState of
State.PalaceProtocolState connection messageConverters -> PalaceInbound.readMessage connection messageConverters header
-- TODO Right now these need to be in IO because of logging and GUI changes. Separate those out.
handleInboundEvent :: State.Connected -> InboundMessages.InboundMessage -> IO State.Connected
handleInboundEvent clientState (InboundMessages.HandshakeMessage handshakeData) = handleHandshake clientState handshakeData
handleInboundEvent clientState (InboundMessages.LogonReplyMessage logonReply) = handleLogonReply clientState logonReply
handleInboundEvent clientState (InboundMessages.ServerVersionMessage serverVersion) = handleServerVersion clientState serverVersion
handleInboundEvent clientState (InboundMessages.ServerInfoMessage serverInfo) = handleServerInfo clientState serverInfo
handleInboundEvent clientState (InboundMessages.UserStatusMessage userStatus) = handleUserStatus clientState userStatus
handleInboundEvent clientState (InboundMessages.UserLogonMessage userLogonNotification) = handleUserLogonNotification clientState userLogonNotification
handleInboundEvent clientState (InboundMessages.MediaServerMessage mediaServerInfo) = handleMediaServerInfo clientState mediaServerInfo
handleInboundEvent clientState (InboundMessages.RoomDescriptionMessage roomDescription) = handleRoomDescription clientState roomDescription
handleInboundEvent clientState (InboundMessages.UserListMessage userListing) = handleUserList clientState userListing
handleInboundEvent clientState (InboundMessages.UserEnteredRoomMessage userEnteredRoom) = handleUserEnteredRoom clientState userEnteredRoom
handleInboundEvent clientState (InboundMessages.UserExitedRoomMessage userExitedRoom) = handleUserExitedRoom clientState userExitedRoom
handleInboundEvent clientState (InboundMessages.UserDisconnectedMessage userDisconnected) = handleUserDisconnected clientState userDisconnected
handleInboundEvent clientState (InboundMessages.ChatMessage chat) = handleChat clientState chat
handleInboundEvent clientState (InboundMessages.MovementMessage movementNotification) = handleMovement clientState movementNotification
handleInboundEvent clientState (InboundMessages.NoOpMessage noOp) = handleNoOp clientState noOp
handleHandshake :: State.Connected -> InboundMessages.Handshake -> IO State.Connected
handleHandshake clientState handshake =
do
Log.debugM "Incoming.Handshake" (show handshake)
let newState = handleProtocolUpdate clientState (InboundMessages.protocolInfo handshake)
userRefId = InboundMessages.userRefId handshake
return $ State.withUserRefId newState userRefId
-- This is separate because it depends on the specific protocol
handleProtocolUpdate :: State.Connected -> InboundMessages.ProtocolInfo -> State.Connected
handleProtocolUpdate clientState (InboundMessages.PalaceProtocol connection endianness) =
State.withProtocol clientState (State.PalaceProtocolState connection newMessageConverters)
where newMessageConverters = Connect.messageConvertersFor endianness
{- Re AlternateLogonReply: OpenPalace comments say:
This is only sent when the server is running in "guests-are-members" mode.
This is pointless... it's basically echoing back the logon packet that we sent to the server.
The only reason we support this is so that certain silly servers can change our puid and ask
us to reconnect "for security reasons."
-}
handleLogonReply :: State.Connected -> InboundMessages.LogonReply -> IO State.Connected
handleLogonReply clientState logonReply =
do
Log.debugM "Incoming.Message.LogonReply" (show logonReply)
return clientState -- TODO return puidCrc and puidCounter when we need it
handleServerVersion :: State.Connected -> InboundMessages.ServerVersion -> IO State.Connected
handleServerVersion clientState serverVersion =
do
Log.debugM "Incoming.Message.ServerVersion" $ "Server version: " ++ (show serverVersion)
return clientState -- TODO Add server version to host state
handleServerInfo :: State.Connected -> InboundMessages.ServerInfoNotification -> IO State.Connected
handleServerInfo clientState serverInfo =
do
Log.debugM "Incoming.Message.ServerInfo" $ "Server info: " ++ (show serverInfo)
return clientState
handleUserStatus :: State.Connected -> InboundMessages.UserStatusNotification -> IO State.Connected
handleUserStatus clientState userStatus =
do
Log.debugM "Incoming.Message.UserStatus" $ "User status -- User flags: " ++ (show userStatus)
return clientState
-- A user connects to this host
handleUserLogonNotification :: State.Connected -> InboundMessages.UserLogonNotification -> IO State.Connected
handleUserLogonNotification clientState logonNotification =
do
Log.debugM "Incoming.Message.UserLogonNotification" $ (show logonNotification)
return clientState
{- OpenPalace does:
Adds the user ID to recentLogonUserIds; sets a timer to remove it in 15 seconds.
This is for the Ping sound managed by the NewUserNotification.
-}
handleMediaServerInfo :: State.Connected -> InboundMessages.MediaServerInfo -> IO State.Connected
handleMediaServerInfo clientState serverInfo =
do
Log.debugM "Incoming.Message.MediaServerInfo" $ show serverInfo
let newState = State.withMediaServerInfo clientState serverInfo
_ <- loadRoomBackgroundImage newState
Log.debugM "Incoming.Message.MediaServerInfo.Processed" $ "New state: " ++ (show newState)
return newState
-- room name, background image, overlay images, props, hotspots, draw commands
handleRoomDescription :: State.Connected -> InboundMessages.RoomDescription -> IO State.Connected
handleRoomDescription clientState roomDescription =
do
Log.debugM "Incoming.Message.RoomDescription" $ show roomDescription
let newState = State.withRoomDescription clientState roomDescription
_ <- loadRoomBackgroundImage newState
Log.debugM "Incoming.Message.RoomDescription.Processed" $ "New state: " ++ (show newState)
return newState
{- OpenPalace also does this when receiving these messages:
clearStatusMessage currentRoom
clearAlarms
midiStop
and after parsing the information:
Dim room 100
Room.showAvatars = true -- scripting can hide all avatars
Dispatch room change event for scripting
-}
-- List of users in the current room
handleUserList :: State.Connected -> InboundMessages.UserListing -> IO State.Connected
handleUserList clientState userList =
do
Log.debugM "Incoming.Message.UserList" $ show userList
let newState = State.withRoomUsers clientState userList
return newState
{- OpenPalace - after creating each user:
user.loadProps()
-}
handleUserEnteredRoom :: State.Connected -> InboundMessages.UserEnteredRoom -> IO State.Connected
handleUserEnteredRoom clientState userNotification =
do
let newState = State.withRoomUsers clientState $ InboundMessages.UserListing [userNotification]
gui = State.guiState clientState
userWhoArrived = InboundMessages.userId userNotification
message = (User.userName $ State.userIdFor newState userWhoArrived) ++ " entered the room."
Log.debugM "Incoming.Message.NewUser" $ show userNotification
GUI.appendMessage (GUI.logWindow gui) $ Chat.makeRoomAnnouncement message
return newState
{- OpenPalace does:
Looks for this user in recentLogonIds (set in UserLogonNotification) - to see if the user has entered the palace within the last 15 sec.
If so, remove it from the recentLogonIds and play the connection Ping:
PalaceSoundPlayer.getInstance().playConnectionPing();
If someone else entered and they were selected in the user list, they are selected (for whisper) in the room too.
And if one's self entered:
if (needToRunSignonHandlers) { -- This flag is set to true when you first log on
requestRoomList();
requestUserList();
palaceController.triggerHotspotEvents(IptEventHandler.TYPE_SIGNON);
needToRunSignonHandlers = false; }
palaceController.triggerHotspotEvents(IptEventHandler.TYPE_ENTER);
-}
handleUserExitedRoom :: State.Connected -> InboundMessages.UserExitedRoom -> IO State.Connected
handleUserExitedRoom clientState exitNotification@(InboundMessages.UserExitedRoom userWhoLeft) =
do
let
message = (User.userName $ State.userIdFor clientState userWhoLeft) ++ " left the room."
gui = State.guiState clientState
newState = State.withUserLeavingRoom clientState userWhoLeft
Log.debugM "Incoming.Message.NewUser" $ show exitNotification
GUI.appendMessage (GUI.logWindow gui) $ Chat.makeRoomAnnouncement message
return newState
handleUserDisconnected :: State.Connected -> InboundMessages.UserDisconnected -> IO State.Connected
handleUserDisconnected clientState disconnectedNotification@(InboundMessages.UserDisconnected userWhoLeft population) =
do
let newState = State.withUserDisconnecting clientState userWhoLeft population
Log.debugM "Incoming.Message.NewUser" $ show disconnectedNotification
return newState
{- OpenPalace does:
If user is in the room, PalaceSoundPlayer.getInstance().playConnectionPing()
If that user was the selected user for whisper (in the room or not), unset the selected user
-}
handleChat :: State.Connected -> InboundMessages.Chat -> IO State.Connected
handleChat clientState chatData =
do
let gui = State.guiState clientState
communication = State.communicationFromChatData clientState chatData
Log.debugM "Incoming.Message.Chat" $ show communication
GUI.appendMessage (GUI.logWindow gui) communication
-- TODO send talk and user (and message type) to chat balloon in GUI
-- TODO send talk to script event handler when there is scripting
-- TODO new state with chat log and fix below
let newState = clientState
return newState
handleMovement :: State.Connected -> InboundMessages.MovementNotification -> IO State.Connected
handleMovement clientState movementData =
do
Log.debugM "Incoming.Message.Movement" $ show movementData
let (_, newState) = State.withMovementData clientState movementData
-- TODO tell the GUI to move the user (in Handler.hs)
-- TODO send action to script event handler when there is scripting?
return newState
handleNoOp :: State.Connected -> InboundMessages.NoOp -> IO State.Connected
handleNoOp clientState noOp =
do
Log.debugM "Incoming.Message.NoOp" $ show noOp
return clientState
-- TODO Do we want to reload this every time a new room description gets sent? How often does that happen?
-- TODO This should happen on a separate thread.
loadRoomBackgroundImage :: State.Connected -> IO State.Connected
loadRoomBackgroundImage state =
do
let possibleMediaServer = State.mediaServer $ State.hostState state
possibleImageName = State.roomBackgroundImageName . State.currentRoomState . State.hostState $ state
roomCanvas = GUI.roomCanvas $ State.guiState state
Log.debugM "Load.BackgroundImage" $ "Media server url: " ++ (show possibleMediaServer)
Log.debugM "Load.BackgroundImage" $ "Background image: " ++ (show possibleImageName)
case (possibleMediaServer, possibleImageName) of
(Just mediaServerUrl, Just imageName) ->
do
let host = State.hostname $ State.hostState state
port = State.portId $ State.hostState state
Log.debugM "Load.BackgroundImage" $ "Fetching background image " ++ imageName ++ " from " ++ (show mediaServerUrl)
possibleImagePath <- MediaLoader.fetchCachedBackgroundImagePath host port mediaServerUrl imageName
case possibleImagePath of
Just imagePath -> GUI.displayBackground roomCanvas imagePath
Nothing -> return ()
return state
(_, _) -> return state
| psfblair/freepalace | src/FreePalace/Handlers/Incoming.hs | apache-2.0 | 14,645 | 0 | 17 | 2,460 | 2,529 | 1,218 | 1,311 | 183 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module FreezePredicateParserSpec where
import Bio.Motions.Types
import Bio.Motions.Representation.Common
import Bio.Motions.Utils.FreezePredicateParser
import GHC.Exts
import Data.Either
import Text.Parsec
import Test.Hspec
import Test.Hspec.SmallCheck
run :: String -> Either ParseError FreezePredicate
run = parse freezePredicateParser "<test>"
makeBeadSignature :: Int -> Int -> BeadSignature
makeBeadSignature chain indexOnChain = BeadSignature
{ _beadEV = fromList []
, _beadAtomIndex = -1
, _beadChain = chain
, _beadIndexOnChain = indexOnChain
}
prop :: String -> String -> (Int -> Int -> Bool) -> Spec
prop description (run -> Right parsed) predicate =
it description . property $ \(chain, index) ->
parsed (makeBeadSignature chain index) == predicate chain index
{-# ANN correctSpec "HLint: ignore Use ||" #-}
correctSpec :: Spec
correctSpec = do
context "when parsing an empty file" $
prop "freezes nothing" "" $ \_ _ ->
False
context "when parsing a single chain" $
prop "freezes only this chain" "4" $ \chain _ ->
chain == 4
context "when parsing a chain range" $
prop "freezes only those chains" "4-8" $ \chain _ ->
chain `elem` [4..8]
context "when parsing a bead range on a single chain" $
prop "freezes only those beads" "1:2-10" $ \chain index ->
chain == 1 && index `elem` [2..10]
context "when parsing a bead range on multiple chains" $
prop "freezes only those beads" "1-2:3-8" $ \chain index ->
chain `elem` [1..2] && index `elem` [3..8]
context "when parsing a wildcard range" $
prop "freezes only those beads" "*:2-9" $ \_ index ->
index `elem` [2..9]
context "when parsing a negation of a chain" $
prop "freezes everything except for this chain" "!3" $ \chain _ ->
chain /= 3
context "when parsing an alternative of chains" $
prop "freezes only those chains" "1,3,9" $ \chain _ ->
chain `elem` [1, 3, 9]
context "when parsing a nested expression" $
prop "freezes only those chains" "!(1,7)" $ \chain _ ->
chain `notElem` [1, 7]
context "when parsing a complex alternative" $
prop "freezes only those chains" "1,2,3-5:4,9:6-8" $ \chain index ->
or [ chain `elem` [1, 2]
, chain `elem` [3..5] && index == 4
, chain == 9 && index `elem` [6..8]
]
incorrectSpec :: Spec
incorrectSpec = do
context "when parsing a non-integer" $
it "fails" $ isLeft (run "helloworld") `shouldBe` True
context "when parsing an unterminated range" $
it "fails" $ isLeft (run "1-") `shouldBe` True
spec :: Spec
spec = describe "the FreezePredicate parser" $ do
context "when parsing correct ranges"
correctSpec
context "when parsing incorrect ranges"
incorrectSpec
| Motions/motions | test/FreezePredicateParserSpec.hs | apache-2.0 | 3,060 | 0 | 14 | 804 | 767 | 405 | 362 | 71 | 1 |
-- "Treealize" expression terms
module OperationExtension2 where
import Data.Tree
import DataBase
import DataExtension
class ToTree x
where
toTree :: x -> Tree String
instance ToTree Lit
where
toTree (Lit i) = Node "Lit" []
instance (Exp x, Exp y, ToTree x, ToTree y) => ToTree (Add x y)
where
toTree (Add x y) = Node "Add" [toTree x, toTree y]
instance (Exp x, ToTree x) => ToTree (Neg x)
where
toTree (Neg x) = Node "Neg" [toTree x]
| egaburov/funstuff | Haskell/tytag/xproblem_src/samples/expressions/Haskell/OpenDatatype1/OperationExtension2.hs | apache-2.0 | 454 | 0 | 8 | 97 | 196 | 100 | 96 | 12 | 0 |
------------------------------------------------------------------------------
-- Copyright 2012 Microsoft Corporation.
--
-- This is free software; you can redistribute it and/or modify it under the
-- terms of the Apache License, Version 2.0. A copy of the License can be
-- found in the file "license.txt" at the root of this distribution.
-----------------------------------------------------------------------------
{-
Map constructor names to constructor info.
-}
-----------------------------------------------------------------------------
module Kind.Constructors( -- * Constructors
Constructors, ConInfo(..)
, constructorsEmpty
, constructorsExtend, constructorsLookup, constructorsFind
, constructorsIsEmpty
, constructorsFindScheme
, constructorsSet
, constructorsCompose, constructorsFromList
, extractConstructors
-- * Pretty
, ppConstructors
) where
import qualified Data.List as L
import qualified Common.NameMap as M
import qualified Common.NameSet as S
import Lib.PPrint
import Common.Failure( failure )
import Common.Name
import Common.Syntax ( Visibility(..))
import Kind.Pretty ( kindColon )
import Type.Type
import Type.Pretty
import qualified Core.Core as Core
{--------------------------------------------------------------------------
Newtype map
--------------------------------------------------------------------------}
-- | Constructors: a map from newtype names to newtype information
newtype Constructors = Constructors (M.NameMap ConInfo)
constructorsEmpty :: Constructors
constructorsEmpty
= Constructors M.empty
constructorsIsEmpty :: Constructors -> Bool
constructorsIsEmpty (Constructors m)
= M.null m
constructorsExtend :: Name -> ConInfo -> Constructors -> Constructors
constructorsExtend name conInfo (Constructors m)
= Constructors (M.insert name conInfo m)
constructorsFromList :: [ConInfo] -> Constructors
constructorsFromList conInfos
= Constructors (M.fromList [(conInfoName info, info) | info <- conInfos])
constructorsCompose :: Constructors -> Constructors -> Constructors
constructorsCompose (Constructors cons1) (Constructors cons2)
= Constructors (M.union cons2 cons1) -- ASSUME: left-biased union
constructorsLookup :: Name -> Constructors -> Maybe ConInfo
constructorsLookup name (Constructors m)
= M.lookup name m
constructorsFind :: Name -> Constructors -> ConInfo
constructorsFind name syn
= case constructorsLookup name syn of
Nothing -> failure ("Kind.Constructors.constructorsFind: unknown constructor: " ++ show name)
Just x -> x
constructorsFindScheme :: Name -> Constructors -> Scheme
constructorsFindScheme conname cons
= conInfoType (constructorsFind conname cons)
constructorsSet :: Constructors -> S.NameSet
constructorsSet (Constructors m)
= S.fromList (M.keys m)
{--------------------------------------------------------------------------
Pretty printing
--------------------------------------------------------------------------}
instance Show Constructors where
show = show . pretty
instance Pretty Constructors where
pretty syns
= ppConstructors Type.Pretty.defaultEnv syns
ppConstructors showOptions (Constructors m)
= vcat [fill 8 (pretty name) <> kindColon (colors showOptions) <+>
ppType showOptions (conInfoType conInfo)
| (name,conInfo) <- L.sortBy (\(n1,_) (n2,_) -> compare (show n1) (show n2)) $ M.toList m]
-- | Extract constructor environment from core
extractConstructors :: Bool -> Core.Core -> Constructors
extractConstructors publicOnly core
= Constructors (M.unions (L.map (extractTypeDefGroup isVisible) (Core.coreProgTypeDefs core)))
where
isVisible Public = True
isVisible _ = not publicOnly
extractTypeDefGroup isVisible (Core.TypeDefGroup tdefs)
= M.unions (L.map (extractTypeDef isVisible) tdefs)
extractTypeDef :: (Visibility -> Bool) -> Core.TypeDef -> M.NameMap ConInfo
extractTypeDef isVisible tdef
= case tdef of
Core.Data dataInfo vis conViss | isVisible vis
-> let conInfos = dataInfoConstrs dataInfo
in M.fromList [(conInfoName conInfo,conInfo) | (conInfo,vis) <- zip conInfos conViss, isVisible vis]
_ -> M.empty
| lpeterse/koka | src/Kind/Constructors.hs | apache-2.0 | 4,461 | 0 | 15 | 894 | 951 | 506 | 445 | 74 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Database.HXournal.Store.Config where
import Data.Configurator as C
import Data.Configurator.Types
import Control.Applicative
import Control.Concurrent
import Control.Monad
import System.Environment
import System.Directory
import System.FilePath
data HXournalStoreConfiguration =
HXournalStoreConfiguration { hxournalstore_base :: FilePath }
deriving (Show)
emptyConfigString :: String
emptyConfigString = "# hxournal-store configuration\n# base = \"blah\"\n"
loadConfigFile :: IO Config
loadConfigFile = do
homepath <- getEnv "HOME"
let dothxournalstore = homepath </> ".hxournal-store"
doesFileExist dothxournalstore >>= \b -> when (not b) $ do
writeFile dothxournalstore emptyConfigString
threadDelay 1000000
config <- load [Required "$(HOME)/.hxournal-store"]
return config
getHXournalStoreConfiguration :: Config -> IO (Maybe HXournalStoreConfiguration)
getHXournalStoreConfiguration c = do
mbase <- C.lookup c "base"
return (HXournalStoreConfiguration <$> mbase )
| wavewave/hxournal-store | lib/Database/HXournal/Store/Config.hs | bsd-2-clause | 1,079 | 0 | 12 | 175 | 237 | 122 | 115 | 28 | 1 |
{-# LANGUAGE PackageImports #-}
import Control.Applicative hiding (many)
import qualified Data.Attoparsec as P
import Data.Attoparsec.Char8 -- as P8
import qualified Data.ByteString.Char8 as B hiding (map)
import HEP.Parser.LHEParser
import Debug.Trace
import qualified Data.Iteratee as Iter
import qualified Data.ListLike as LL
iter_parseoneevent :: Iter.Iteratee B.ByteString IO (Maybe LHEvent)
iter_parseoneevent = Iter.Iteratee step
where step = undefined
-------------------------------
hline = putStrLn "---------------------------------"
main = do
hline
putStrLn "This is a test of attoparsec parser."
hline
putStrLn " I am reading test.lhe "
bytestr <- B.readFile "test.lhe"
let r = parse lheheader bytestr
s = case r of
Partial _ -> onlyremain (feed r B.empty)
Done _ _ -> onlyremain r
Fail _ _ _ -> trace "Test failed" $ onlyremain r
putStrLn $ show $ B.take 100 s
let r' = parse eachevent s
s' = case r' of
Partial _ -> onlyresult (feed r' B.empty)
Done _ _ -> onlyresult r'
Fail _ _ _ -> trace "Test failed" $ onlyresult r'
putStrLn $ show s'
onlyresult (Done _ r) = r
onlyremain (Done s _) = s
somestring (Fail a _ message ) = (Prelude.take 100 $ show $ B.take 100 a ) ++ " : " ++ message
somestring (Done a b ) = (Prelude.take 100 $ show $ B.take 100 a ) ++ " : " ++ (Prelude.take 100 (show b))
| wavewave/LHEParser | test/test.hs | bsd-2-clause | 1,490 | 0 | 16 | 403 | 489 | 245 | 244 | 35 | 5 |
import Data.List (nub)
main = print $ length $ nub [ a^b | a <- [2 .. 100], b <- [2 .. 100] ]
| foreverbell/project-euler-solutions | src/29.hs | bsd-3-clause | 95 | 0 | 10 | 25 | 62 | 34 | 28 | 2 | 1 |
{-# LANGUAGE TypeFamilies, CPP #-}
-- | Simple interface for shell scripting-like tasks.
module Control.Shell
( -- * Running Shell programs
Shell, ExitReason (..)
, shell, shell_, exitString
-- * Error handling and control flow
, (|>), capture, captureStdErr, capture2, capture3, stream, lift
, try, orElse, exit
, Guard (..), guard, when, unless
-- * Environment handling
, withEnv, withoutEnv, lookupEnv, getEnv, cmdline
-- * Running external commands
, MonadIO (..), Env (..)
, run, sudo
, unsafeLiftIO
, absPath, shellEnv, getShellEnv, joinResult, runSh
-- * Working with directories
, cpdir, pwd, ls, mkdir, rmdir, inDirectory, isDirectory
, withHomeDirectory, inHomeDirectory, withAppDirectory, inAppDirectory
, forEachFile, forEachFile_, forEachDirectory, forEachDirectory_
-- * Working with files
, isFile, rm, mv, cp, input, output
, withFile, withBinaryFile, openFile, openBinaryFile
-- * Working with temporary files and directories
, FileMode (..)
, withTempFile, withCustomTempFile
, withTempDirectory, withCustomTempDirectory
, inTempDirectory, inCustomTempDirectory
-- * Working with handles
, Handle, IOMode (..), BufferMode (..)
, hFlush, hClose, hReady
, hGetBuffering, hSetBuffering
, getStdIn, getStdOut, getStdErr
-- * Text I/O
, hPutStr, hPutStrLn, echo, echo_, ask, stdin
, hGetLine, hGetContents
-- * Terminal text formatting
, module Control.Shell.Color
-- * ByteString I/O
, hGetBytes, hPutBytes, hGetByteLine, hGetByteContents
-- * Convenient re-exports
, module System.FilePath
, module Control.Monad
) where
import qualified System.Environment as Env
import System.IO.Unsafe
import Control.Shell.Base hiding (getEnv, takeEnvLock, releaseEnvLock, setShellEnv)
import qualified Control.Shell.Base as CSB
import Control.Shell.Handle
import Control.Shell.File
import Control.Shell.Directory
import Control.Shell.Temp
import Control.Shell.Control
import Control.Shell.Color
import Control.Monad hiding (guard, when, unless)
import System.FilePath
-- | Convert an 'ExitReason' into a 'String'. Successful termination yields
-- the empty string, while abnormal termination yields the termination
-- error message. If the program terminaged abnormally but without an error
-- message - i.e. the error message is empty string - the error message will
-- be shown as @"abnormal termination"@.
exitString :: ExitReason -> String
exitString Success = ""
exitString (Failure "") = "abnormal termination"
exitString (Failure s) = s
-- | Get the complete environment for the current computation.
getShellEnv :: Shell Env
getShellEnv = CSB.getEnv
insert :: Eq k => k -> v -> [(k, v)] -> [(k, v)]
insert k' v' (kv@(k, _) : kvs)
| k == k' = (k', v') : kvs
| otherwise = kv : insert k' v' kvs
insert k v _ = [(k, v)]
delete :: Eq k => k -> [(k, v)] -> [(k, v)]
delete k' (kv@(k, _) : kvs)
| k == k' = kvs
| otherwise = kv : delete k' kvs
delete _ _ = []
-- | The executable's command line arguments.
cmdline :: [String]
cmdline = unsafePerformIO Env.getArgs
-- | Run a computation with the given environment variable set.
withEnv :: String -> String -> Shell a -> Shell a
withEnv k v m = do
e <- CSB.getEnv
inEnv (e {envEnvVars = insert k v (envEnvVars e)}) m
-- | Run a computation with the given environment variable unset.
withoutEnv :: String -> Shell a -> Shell a
withoutEnv k m = do
e <- CSB.getEnv
inEnv (e {envEnvVars = delete k (envEnvVars e)}) m
-- | Get the value of an environment variable. Returns Nothing if the variable
-- doesn't exist.
lookupEnv :: String -> Shell (Maybe String)
lookupEnv k = lookup k . envEnvVars <$> CSB.getEnv
-- | Get the value of an environment variable. Returns the empty string if
-- the variable doesn't exist.
getEnv :: String -> Shell String
getEnv key = maybe "" id `fmap` lookupEnv key
-- | Run a command with elevated privileges.
sudo :: FilePath -> [String] -> Shell ()
sudo cmd as = run "sudo" (cmd:"--":as)
-- | Performs a command inside a temporary directory. The directory will be
-- cleaned up after the command finishes.
inTempDirectory :: Shell a -> Shell a
inTempDirectory = withTempDirectory . flip inDirectory
-- | Performs a command inside a temporary directory. The directory will be
-- cleaned up after the command finishes.
inCustomTempDirectory :: FilePath -> Shell a -> Shell a
inCustomTempDirectory dir m = withCustomTempDirectory dir $ flip inDirectory m
-- | Get the standard input, output and error handle respectively.
getStdIn, getStdOut, getStdErr :: Shell Handle
getStdIn = envStdIn <$> CSB.getEnv
getStdOut = envStdOut <$> CSB.getEnv
getStdErr = envStdErr <$> CSB.getEnv
| valderman/shellmate | shellmate/Control/Shell.hs | bsd-3-clause | 4,736 | 0 | 13 | 889 | 1,149 | 676 | 473 | 84 | 1 |
module Network.Kontiki.SerializationSpec where
import Data.Binary (Binary, decode, encode)
import Network.Kontiki.Raft
import Test.Hspec
import Test.QuickCheck
serializationSpec :: Spec
serializationSpec = do
describe "Messages" $ do
it "Message Int" $ property (prop_serialization :: Message Int -> Bool)
it "RequestVote" $ property (prop_serialization :: RequestVote -> Bool)
it "RequestVoteResponse" $ property (prop_serialization :: RequestVoteResponse -> Bool)
it "AppendEntries Int" $ property (prop_serialization :: AppendEntries Int -> Bool)
it "AppendEntriesResponse" $ property (prop_serialization :: AppendEntriesResponse -> Bool)
describe "State" $ do
it "SomeState" $ property (prop_serialization :: SomeState -> Bool)
it "Follower" $ property (prop_serialization :: Follower -> Bool)
it "Candidate" $ property (prop_serialization :: Candidate -> Bool)
it "Leader" $ property (prop_serialization :: Leader -> Bool)
describe "Entry Int" $ do
it "Entry Int" $ property (prop_serialization :: Entry Int -> Bool)
prop_serialization :: (Eq a, Binary a) => a -> Bool
prop_serialization a = decode (encode a) == a
| abailly/kontiki | test/Network/Kontiki/SerializationSpec.hs | bsd-3-clause | 1,225 | 0 | 14 | 252 | 363 | 179 | 184 | 22 | 1 |
module Language.GhcHaskell.Parser
where
import Control.Monad
import qualified Language.Haskell.Exts.Parser as P
import Language.Haskell.AST.HSE
import Language.GhcHaskell.AST
parsePat :: String -> ParseResult (Parsed Pat)
parsePat = P.parse >=> fromHsePat
parseExp :: String -> ParseResult (Parsed Exp)
parseExp = P.parse >=> fromHseExp
parseType :: String -> ParseResult (Parsed Type)
parseType = P.parse >=> fromHseType
parseDecl :: String -> ParseResult (Parsed Decl)
parseDecl = P.parse >=> fromHseDecl
parseModule :: String -> ParseResult (Parsed Module)
parseModule = P.parse >=> fromHseModule
| jcpetruzza/haskell-ast | src/Language/GhcHaskell/Parser.hs | bsd-3-clause | 609 | 0 | 8 | 83 | 180 | 100 | 80 | 15 | 1 |
{-# LANGUAGE Haskell2010 #-}
module Maybe1 where
instance Functor Maybe' where
fmap f m = m >>= pure . f
instance Applicative Maybe' where
pure = Just'
f1 <*> f2 = f1 >>= \v1 -> f2 >>= (pure . v1)
data Maybe' a = Nothing' | Just' a
instance Monad Maybe' where
return = pure
Nothing' >>= _ = Nothing'
Just' x >>= f = f x
fail _ = Nothing'
| hvr/Hs2010To201x | testcases/H2010/Maybe1.expected.hs | bsd-3-clause | 373 | 0 | 10 | 106 | 137 | 71 | 66 | 13 | 0 |
module Main where
import ImageFlatten
import Data.Maybe
import Data.Char
import Options.Applicative
import System.IO
import System.Environment
import System.FilePath
data Options = Options
{ input :: String,
output :: String,
combine :: Bool,
remove :: Bool,
avg :: Bool,
thresh :: Maybe Float,
quality :: Maybe Int } deriving (Show)
main :: IO ()
main = do
opt <- execParser $ info (helper <*> optParser) description
let validated = validateOptions opt
case validated of
Left e -> hPutStrLn stderr e
Right (op, inp, out) -> flatten op inp out
description :: InfoMod Options
description = fullDesc
<> progDesc "Flatten DIRECTORY into OUTPUT"
<> header "image-flatten - flatten multiple images into a single image, combining or hiding differences"
optParser :: Parser Options
optParser = Options
<$> strOption (long "input" <> short 'i' <> metavar "DIRECTORY" <> help "A directory containing images to flatten")
<*> strOption (long "output" <> short 'o' <> metavar "OUTPUT" <> help "File path to save result image to")
<*> switch (long "combine" <> short 'c' <> help "Specifies that differences in images should be combined")
<*> switch (long "remove" <> short 'r' <> help "Specifies that differences in images should be removed")
<*> switch (long "average" <> short 'a' <> help "Specifies that images should be averaged")
<*> optional (option auto (long "threshold" <> short 't' <> help "Adjust the sensitivity for detecting features. A low number is required to detect subtle differences eg a green jumper on grass. A high number will suffice for white stars against a black sky. Default is 10."))
<*> optional (option auto (long "quality" <> short 'q' <> help "If output is a JPEG, this specifies the quality to use when saving"))
validateOptions :: Options -> Either String (Operation, InputSource, OutputDestination)
validateOptions (Options i o c r a t q)
| q' < 0 || q' > 100 = Left "Jpeg quality must be between 0 and 100 inclusive"
| not (isPng || isJpg) = Left "Output file must be a .png or .jpg"
| length (filter id [c,r,a]) > 1 = Left "Only one of remove (-r), combine (-c) and average (-a) can be specified"
| otherwise = Right (
case (c,r,a) of
(True,_,_) -> CombineDifferences t'
(_,_,True) -> Average
_ -> HideDifferences,
Directory i,
output) where
isPng = extension == ".png"
isJpg = extension == ".jpg" || extension == ".jpeg"
output = if isJpg then JpgFile o q' else PngFile o
q' = fromMaybe 100 q
extension = map toLower $ takeExtension o
t' = fromMaybe 10 t
| iansullivan88/image-flatten | app/Main.hs | bsd-3-clause | 3,056 | 0 | 17 | 993 | 744 | 374 | 370 | 54 | 4 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
DeriveDataTypeable, TypeSynonymInstances, PatternGuards #-}
module Idris.AbsSyntaxTree where
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Typecheck
import Idris.Docstrings
import IRTS.Lang
import IRTS.CodegenCommon
import Util.Pretty
import Util.DynamicLinker
import Idris.Colours
import System.Console.Haskeline
import System.IO
import Prelude hiding ((<$>))
import Control.Applicative ((<|>))
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Except
import qualified Control.Monad.Trans.Class as Trans (lift)
import Data.Data (Data)
import Data.Function (on)
import Data.Generics.Uniplate.Data (universe, children)
import Data.List hiding (group)
import Data.Char
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import Data.Either
import qualified Data.Set as S
import Data.Word (Word)
import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
import Data.Traversable (Traversable)
import Data.Typeable
import Data.Foldable (Foldable)
import Debug.Trace
import Text.PrettyPrint.Annotated.Leijen
data ElabWhat = ETypes | EDefns | EAll
deriving (Show, Eq)
-- Data to pass to recursively called elaborators; e.g. for where blocks,
-- paramaterised declarations, etc.
-- rec_elabDecl is used to pass the top level elaborator into other elaborators,
-- so that we can have mutually recursive elaborators in separate modules without
-- having to muck about with cyclic modules.
data ElabInfo = EInfo { params :: [(Name, PTerm)],
inblock :: Ctxt [Name], -- names in the block, and their params
liftname :: Name -> Name,
namespace :: Maybe [String],
elabFC :: Maybe FC,
rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl ->
Idris () }
toplevel :: ElabInfo
toplevel = EInfo [] emptyContext id Nothing Nothing (\_ _ _ -> fail "Not implemented")
eInfoNames :: ElabInfo -> [Name]
eInfoNames info = map fst (params info) ++ M.keys (inblock info)
data IOption = IOption { opt_logLevel :: Int,
opt_typecase :: Bool,
opt_typeintype :: Bool,
opt_coverage :: Bool,
opt_showimp :: Bool, -- ^^ show implicits
opt_errContext :: Bool,
opt_repl :: Bool,
opt_verbose :: Bool,
opt_nobanner :: Bool,
opt_quiet :: Bool,
opt_codegen :: Codegen,
opt_outputTy :: OutputType,
opt_ibcsubdir :: FilePath,
opt_importdirs :: [FilePath],
opt_triple :: String,
opt_cpu :: String,
opt_cmdline :: [Opt], -- remember whole command line
opt_origerr :: Bool,
opt_autoSolve :: Bool, -- ^ automatically apply "solve" tactic in prover
opt_autoImport :: [FilePath], -- ^ e.g. Builtins+Prelude
opt_optimise :: [Optimisation],
opt_printdepth :: Maybe Int,
opt_evaltypes :: Bool, -- ^ normalise types in :t
opt_desugarnats :: Bool
}
deriving (Show, Eq)
defaultOpts = IOption { opt_logLevel = 0
, opt_typecase = False
, opt_typeintype = False
, opt_coverage = True
, opt_showimp = False
, opt_errContext = False
, opt_repl = True
, opt_verbose = True
, opt_nobanner = False
, opt_quiet = False
, opt_codegen = Via "c"
, opt_outputTy = Executable
, opt_ibcsubdir = ""
, opt_importdirs = []
, opt_triple = ""
, opt_cpu = ""
, opt_cmdline = []
, opt_origerr = False
, opt_autoSolve = True
, opt_autoImport = []
, opt_optimise = defaultOptimise
, opt_printdepth = Just 5000
, opt_evaltypes = True
, opt_desugarnats = False
}
data PPOption = PPOption {
ppopt_impl :: Bool -- ^^ whether to show implicits
, ppopt_desugarnats :: Bool
, ppopt_pinames :: Bool -- ^^ whether to show names in pi bindings
, ppopt_depth :: Maybe Int
} deriving (Show)
data Optimisation = PETransform -- partial eval and associated transforms
deriving (Show, Eq)
defaultOptimise = [PETransform]
-- | Pretty printing options with default verbosity.
defaultPPOption :: PPOption
defaultPPOption = PPOption { ppopt_impl = False,
ppopt_desugarnats = False,
ppopt_pinames = False,
ppopt_depth = Just 200 }
-- | Pretty printing options with the most verbosity.
verbosePPOption :: PPOption
verbosePPOption = PPOption { ppopt_impl = True,
ppopt_desugarnats = True,
ppopt_pinames = True,
ppopt_depth = Just 200 }
-- | Get pretty printing options from the big options record.
ppOption :: IOption -> PPOption
ppOption opt = PPOption {
ppopt_impl = opt_showimp opt,
ppopt_pinames = False,
ppopt_depth = opt_printdepth opt,
ppopt_desugarnats = opt_desugarnats opt
}
-- | Get pretty printing options from an idris state record.
ppOptionIst :: IState -> PPOption
ppOptionIst = ppOption . idris_options
data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
-- | The output mode in use
data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle
| IdeMode Integer Handle -- ^ Send IDE output for some request ID to the handle
deriving Show
-- | How wide is the console?
data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
| ColsWide Int -- ^ Manually specified - must be positive
| AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
deriving (Show, Eq)
-- | The global state used in the Idris monad
data IState = IState {
tt_ctxt :: Context, -- ^ All the currently defined names and their terms
idris_constraints :: S.Set ConstraintFC,
-- ^ A list of universe constraints and their corresponding source locations
idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
idris_implicits :: Ctxt [PArg],
idris_statics :: Ctxt [Bool],
idris_classes :: Ctxt ClassInfo,
idris_records :: Ctxt RecordInfo,
idris_dsls :: Ctxt DSL,
idris_optimisation :: Ctxt OptInfo,
idris_datatypes :: Ctxt TypeInfo,
idris_namehints :: Ctxt [Name],
idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
-- ^ list of lhs/rhs, and a list of missing clauses
idris_flags :: Ctxt [FnOpt],
idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
idris_calledgraph :: Ctxt [Name],
idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]),
idris_moduledocs :: Ctxt (Docstring DocTerm),
-- ^ module documentation is saved in a special MN so the context
-- mechanism can be used for disambiguation
idris_tyinfodata :: Ctxt TIData,
idris_fninfo :: Ctxt FnInfo,
idris_transforms :: Ctxt [(Term, Term)],
idris_autohints :: Ctxt [Name],
idris_totcheck :: [(FC, Name)], -- names to check totality on
idris_defertotcheck :: [(FC, Name)], -- names to check at the end
idris_totcheckfail :: [(FC, String)],
idris_options :: IOption,
idris_name :: Int,
idris_lineapps :: [((FilePath, Int), PTerm)],
-- ^ Full application LHS on source line
idris_metavars :: [(Name, (Maybe Name, Int, [Name], Bool))],
-- ^ The currently defined but not proven metavariables. The Int
-- is the number of vars to display as a context, the Maybe Name
-- is its top-level function, the [Name] is the list of local variables
-- available for proof search and the Bool is whether :p is
-- allowed
idris_coercions :: [Name],
idris_errRev :: [(Term, Term)],
syntax_rules :: SyntaxRules,
syntax_keywords :: [String],
imported :: [FilePath], -- ^ The imported modules
idris_scprims :: [(Name, (Int, PrimFn))],
idris_objs :: [(Codegen, FilePath)],
idris_libs :: [(Codegen, String)],
idris_cgflags :: [(Codegen, String)],
idris_hdrs :: [(Codegen, String)],
idris_imported :: [(FilePath, Bool)], -- ^ Imported ibc file names, whether public
proof_list :: [(Name, (Bool, [String]))],
errSpan :: Maybe FC,
parserWarnings :: [(FC, Err)],
lastParse :: Maybe Name,
indent_stack :: [Int],
brace_stack :: [Maybe Int],
lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
idris_parsedSpan :: Maybe FC,
hide_list :: [(Name, Maybe Accessibility)],
default_access :: Accessibility,
default_total :: Bool,
ibc_write :: [IBCWrite],
compiled_so :: Maybe String,
idris_dynamic_libs :: [DynamicLib],
idris_language_extensions :: [LanguageExt],
idris_outputmode :: OutputMode,
idris_colourRepl :: Bool,
idris_colourTheme :: ColourTheme,
idris_errorhandlers :: [Name], -- ^ Global error handlers
idris_nameIdx :: (Int, Ctxt (Int, Name)),
idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
module_aliases :: M.Map [T.Text] [T.Text],
idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
idris_postulates :: S.Set Name,
idris_externs :: S.Set (Name, Int),
idris_erasureUsed :: [(Name, Int)], -- ^ Function/constructor name, argument position is used
idris_whocalls :: Maybe (M.Map Name [Name]),
idris_callswho :: Maybe (M.Map Name [Name]),
idris_repl_defs :: [Name], -- ^ List of names that were defined in the repl, and can be re-/un-defined
elab_stack :: [(Name, Bool)], -- ^ Stack of names currently being elaborated, Bool set if it's an instance
-- (instances appear twice; also as a funtion name)
idris_symbols :: M.Map Name Name, -- ^ Symbol table (preserves sharing of names)
idris_exports :: [Name], -- ^ Functions with ExportList
idris_highlightedRegions :: [(FC, OutputAnnotation)], -- ^ Highlighting information to output
idris_parserHighlights :: [(FC, OutputAnnotation)] -- ^ Highlighting information from the parser
}
-- Required for parsers library, and therefore trifecta
instance Show IState where
show = const "{internal state}"
data SizeChange = Smaller | Same | Bigger | Unknown
deriving (Show, Eq)
{-!
deriving instance Binary SizeChange
deriving instance NFData SizeChange
!-}
type SCGEntry = (Name, [Maybe (Int, SizeChange)])
type UsageReason = (Name, Int) -- fn_name, its_arg_number
data CGInfo = CGInfo { argsdef :: [Name],
calls :: [(Name, [[Name]])],
scg :: [SCGEntry],
argsused :: [Name],
usedpos :: [(Int, [UsageReason])] }
deriving Show
{-!
deriving instance Binary CGInfo
deriving instance NFData CGInfo
!-}
primDefs = [sUN "unsafePerformPrimIO",
sUN "mkLazyForeignPrim",
sUN "mkForeignPrim",
sUN "void"]
-- information that needs writing for the current module's .ibc file
data IBCWrite = IBCFix FixDecl
| IBCImp Name
| IBCStatic Name
| IBCClass Name
| IBCRecord Name
| IBCInstance Bool Bool Name Name
| IBCDSL Name
| IBCData Name
| IBCOpt Name
| IBCMetavar Name
| IBCSyntax Syntax
| IBCKeyword String
| IBCImport (Bool, FilePath) -- True = import public
| IBCImportDir FilePath
| IBCObj Codegen FilePath
| IBCLib Codegen String
| IBCCGFlag Codegen String
| IBCDyLib String
| IBCHeader Codegen String
| IBCAccess Name Accessibility
| IBCMetaInformation Name MetaInformation
| IBCTotal Name Totality
| IBCFlags Name [FnOpt]
| IBCFnInfo Name FnInfo
| IBCTrans Name (Term, Term)
| IBCErrRev (Term, Term)
| IBCCG Name
| IBCDoc Name
| IBCCoercion Name
| IBCDef Name -- i.e. main context
| IBCNameHint (Name, Name)
| IBCLineApp FilePath Int PTerm
| IBCErrorHandler Name
| IBCFunctionErrorHandler Name Name Name
| IBCPostulate Name
| IBCExtern (Name, Int)
| IBCTotCheckErr FC String
| IBCParsedRegion FC
| IBCModDocs Name -- ^ The name is the special name used to track module docs
| IBCUsage (Name, Int)
| IBCExport Name
| IBCAutoHint Name Name
deriving Show
-- | The initial state for the compiler
idrisInit :: IState
idrisInit = IState initContext S.empty []
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext
[] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] []
[] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] []
(RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty
AutomaticWidth S.empty S.empty [] Nothing Nothing [] [] M.empty [] [] []
-- | The monad for the main REPL - reading and processing files and updating
-- global state (hence the IO inner monad).
--type Idris = WriterT [Either String (IO ())] (State IState a))
type Idris = StateT IState (ExceptT Err IO)
catchError :: Idris a -> (Err -> Idris a) -> Idris a
catchError = liftCatch catchE
throwError :: Err -> Idris a
throwError = Trans.lift . throwE
-- Commands in the REPL
data Codegen = Via String
-- | ViaC
-- | ViaJava
-- | ViaNode
-- | ViaJavaScript
-- | ViaLLVM
| Bytecode
deriving (Show, Eq)
{-!
deriving instance NFData Codegen
!-}
data HowMuchDocs = FullDocs | OverviewDocs
-- | REPL commands
data Command = Quit
| Help
| Eval PTerm
| NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
| Undefine [Name]
| Check PTerm
| Core PTerm
| DocStr (Either Name Const) HowMuchDocs
| TotCheck Name
| Reload
| Load FilePath (Maybe Int) -- up to maximum line number
| ChangeDirectory FilePath
| ModImport String
| Edit
| Compile Codegen String
| Execute PTerm
| ExecVal PTerm
| Metavars
| Prove Bool Name -- ^ If false, use prover, if true, use elab shell
| AddProof (Maybe Name)
| RmProof Name
| ShowProof Name
| Proofs
| Universes
| LogLvl Int
| Spec PTerm
| WHNF PTerm
| TestInline PTerm
| Defn Name
| Missing Name
| DynamicLink FilePath
| ListDynamic
| Pattelab PTerm
| Search [String] PTerm
| CaseSplitAt Bool Int Name
| AddClauseFrom Bool Int Name
| AddProofClauseFrom Bool Int Name
| AddMissing Bool Int Name
| MakeWith Bool Int Name
| MakeCase Bool Int Name
| MakeLemma Bool Int Name
| DoProofSearch Bool -- update file
Bool -- recursive search
Int -- depth
Name -- top level name
[Name] -- hints
| SetOpt Opt
| UnsetOpt Opt
| NOP
| SetColour ColourType IdrisColour
| ColourOn
| ColourOff
| ListErrorHandlers
| SetConsoleWidth ConsoleWidth
| SetPrinterDepth (Maybe Int)
| Apropos [String] String
| WhoCalls Name
| CallsWho Name
| Browse [String]
| MakeDoc String -- IdrisDoc
| Warranty
| PrintDef Name
| PPrint OutputFmt Int PTerm
| TransformInfo Name
-- Debugging commands
| DebugInfo Name
| DebugUnify PTerm PTerm
data OutputFmt = HTMLOutput | LaTeXOutput
data Opt = Filename String
| Quiet
| NoBanner
| ColourREPL Bool
| Idemode
| IdemodeSocket
| ShowLibs
| ShowLibdir
| ShowIncs
| ShowPkgs
| NoBasePkgs
| NoPrelude
| NoBuiltins -- only for the really primitive stuff!
| NoREPL
| OLogging Int
| Output String
| Interface
| TypeCase
| TypeInType
| DefaultTotal
| DefaultPartial
| WarnPartial
| WarnReach
| EvalTypes
| NoCoverage
| ErrContext
| ShowImpl
| Verbose
| Port String -- REPL TCP port
| IBCSubDir String
| ImportDir String
| PkgBuild String
| PkgInstall String
| PkgClean String
| PkgCheck String
| PkgREPL String
| PkgMkDoc String -- IdrisDoc
| PkgTest String
| PkgIndex FilePath
| WarnOnly
| Pkg String
| BCAsm String
| DumpDefun String
| DumpCases String
| UseCodegen Codegen
| CodegenArgs String
| OutputTy OutputType
| Extension LanguageExt
| InterpretScript String
| EvalExpr String
| TargetTriple String
| TargetCPU String
| OptLevel Int
| AddOpt Optimisation
| RemoveOpt Optimisation
| Client String
| ShowOrigErr
| AutoWidth -- ^ Automatically adjust terminal width
| AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
| UseConsoleWidth ConsoleWidth
| DumpHighlights
| DesugarNats
deriving (Show, Eq)
data ElabShellCmd = EQED | EAbandon | EUndo | EProofState | EProofTerm
| EEval PTerm | ECheck PTerm | ESearch PTerm
| EDocStr (Either Name Const)
deriving (Show, Eq)
-- Parsed declarations
data Fixity = Infixl { prec :: Int }
| Infixr { prec :: Int }
| InfixN { prec :: Int }
| PrefixN { prec :: Int }
deriving Eq
{-!
deriving instance Binary Fixity
deriving instance NFData Fixity
!-}
instance Show Fixity where
show (Infixl i) = "infixl " ++ show i
show (Infixr i) = "infixr " ++ show i
show (InfixN i) = "infix " ++ show i
show (PrefixN i) = "prefix " ++ show i
data FixDecl = Fix Fixity String
deriving Eq
instance Show FixDecl where
show (Fix f s) = show f ++ " " ++ s
{-!
deriving instance Binary FixDecl
deriving instance NFData FixDecl
!-}
instance Ord FixDecl where
compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
data Static = Static | Dynamic
deriving (Show, Eq, Data, Typeable)
{-!
deriving instance Binary Static
deriving instance NFData Static
!-}
-- Mark bindings with their explicitness, and laziness
data Plicity = Imp { pargopts :: [ArgOpt],
pstatic :: Static,
pparam :: Bool,
pscoped :: Maybe ImplicitInfo -- Nothing, if top level
}
| Exp { pargopts :: [ArgOpt],
pstatic :: Static,
pparam :: Bool } -- this is a param (rather than index)
| Constraint { pargopts :: [ArgOpt],
pstatic :: Static }
| TacImp { pargopts :: [ArgOpt],
pstatic :: Static,
pscript :: PTerm }
deriving (Show, Eq, Data, Typeable)
{-!
deriving instance Binary Plicity
deriving instance NFData Plicity
!-}
is_scoped :: Plicity -> Maybe ImplicitInfo
is_scoped (Imp _ _ _ s) = s
is_scoped _ = Nothing
impl = Imp [] Dynamic False Nothing
forall_imp = Imp [] Dynamic False (Just (Impl False))
forall_constraint = Imp [] Dynamic False (Just (Impl True))
expl = Exp [] Dynamic False
expl_param = Exp [] Dynamic True
constraint = Constraint [] Static
tacimpl t = TacImp [] Dynamic t
data FnOpt = Inlinable -- always evaluate when simplifying
| TotalFn | PartialFn | CoveringFn
| Coinductive | AssertTotal
| Dictionary -- type class dictionary, eval only when
-- a function argument, and further evaluation resutls
| Implicit -- implicit coercion
| NoImplicit -- do not apply implicit coercions
| CExport String -- export, with a C name
| ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
| ErrorReverse -- ^^ attempt to reverse normalise before showing in error
| Reflection -- a reflecting function, compile-time only
| Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
| Constructor -- Data constructor type
| AutoHint -- use in auto implicit search
| PEGenerated -- generated by partial evaluator
deriving (Show, Eq)
{-!
deriving instance Binary FnOpt
deriving instance NFData FnOpt
!-}
type FnOpts = [FnOpt]
inlinable :: FnOpts -> Bool
inlinable = elem Inlinable
dictionary :: FnOpts -> Bool
dictionary = elem Dictionary
-- | Type provider - what to provide
data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
| ProvPostulate t -- ^ goal type must be Type, so only term
deriving (Show, Eq, Functor)
type ProvideWhat = ProvideWhat' PTerm
-- | Top-level declarations such as compiler directives, definitions,
-- datatypes and typeclasses.
data PDecl' t
= PFix FC Fixity [String] -- ^ Fixity declaration
| PTy (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC FnOpts Name FC t -- ^ Type declaration (last FC is precise name location)
| PPostulate Bool -- external def if true
(Docstring (Either Err t)) SyntaxInfo FC FC FnOpts Name t -- ^ Postulate, second FC is precise name location
| PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
| PCAF FC Name t -- ^ Top level constant
| PData (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
| PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
| PNamespace String FC [PDecl' t]
-- ^ New namespace, where FC is accurate location of the
-- namespace in the file
| PRecord (Docstring (Either Err t)) SyntaxInfo FC DataOpts
Name -- Record name
FC -- Record name precise location
[(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span
[(Name, Docstring (Either Err t))] -- Param Docs
[((Maybe (Name, FC)), Plicity, t, Maybe (Docstring (Either Err t)))] -- Fields
(Maybe (Name, FC)) -- Optional constructor name and location
(Docstring (Either Err t)) -- Constructor doc
SyntaxInfo -- Constructor SyntaxInfo
-- ^ Record declaration
| PClass (Docstring (Either Err t)) SyntaxInfo FC
[(Name, t)] -- constraints
Name -- class name
FC -- accurate location of class name
[(Name, FC, t)] -- parameters and precise locations
[(Name, Docstring (Either Err t))] -- parameter docstrings
[(Name, FC)] -- determining parameters and precise locations
[PDecl' t] -- declarations
(Maybe (Name, FC)) -- instance constructor name and location
(Docstring (Either Err t)) -- instance constructor docs
-- ^ Type class: arguments are documentation, syntax info, source location, constraints,
-- class name, class name location, parameters, method declarations, optional constructor name
| PInstance
(Docstring (Either Err t)) -- Instance docs
[(Name, Docstring (Either Err t))] -- Parameter docs
SyntaxInfo
FC [(Name, t)] -- constraints
Name -- class
FC -- precise location of class
[t] -- parameters
t -- full instance type
(Maybe Name) -- explicit name
[PDecl' t]
-- ^ Instance declaration: arguments are documentation, syntax info, source
-- location, constraints, class name, parameters, full instance
-- type, optional explicit name, and definitions
| PDSL Name (DSL' t) -- ^ DSL declaration
| PSyntax FC Syntax -- ^ Syntax definition
| PMutual FC [PDecl' t] -- ^ Mutual block
| PDirective Directive -- ^ Compiler directive.
| PProvider (Docstring (Either Err t)) SyntaxInfo FC FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term. The second FC is precise highlighting location.
| PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
-- bool is True, lhs and rhs must be convertible
| PRunElabDecl FC t [String] -- ^ FC is decl-level, for errors, and
-- Strings represent the namespace
deriving Functor
{-!
deriving instance Binary PDecl'
deriving instance NFData PDecl'
!-}
-- | The set of source directives
data Directive = DLib Codegen String |
DLink Codegen String |
DFlag Codegen String |
DInclude Codegen String |
DHide Name |
DFreeze Name |
DAccess Accessibility |
DDefault Bool |
DLogging Integer |
DDynamicLibs [String] |
DNameHint Name FC [(Name, FC)] |
DErrorHandlers Name FC Name FC [(Name, FC)] |
DLanguage LanguageExt |
DUsed FC Name Name
-- | A set of instructions for things that need to happen in IState
-- after a term elaboration when there's been reflected elaboration.
data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type
| RClausesInstrs Name [([Name], Term, Term)]
| RAddInstance Name Name
-- | For elaborator state
data EState = EState {
case_decls :: [(Name, PDecl)],
delayed_elab :: [(Int, Elab' EState ())],
new_tyDecls :: [RDeclInstructions],
highlighting :: [(FC, OutputAnnotation)]
}
initEState :: EState
initEState = EState [] [] [] []
type ElabD a = Elab' EState a
highlightSource :: FC -> OutputAnnotation -> ElabD ()
highlightSource fc annot =
updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux })
-- | One clause of a top-level definition. Term arguments to constructors are:
--
-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
--
-- 2. The list of extra 'with' patterns
--
-- 3. The right-hand side
--
-- 4. The where block (PDecl' t)
data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
| PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t]
| PClauseR FC [t] t [PDecl' t]
| PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t]
deriving Functor
{-!
deriving instance Binary PClause'
deriving instance NFData PClause'
!-}
-- | Data declaration
data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
d_name_fc :: FC, -- ^ The precise location of the type constructor name
d_tcon :: t, -- ^ Type constructor
d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors
}
-- ^ Data declaration
| PLaterdecl { d_name :: Name, d_name_fc :: FC, d_tcon :: t }
-- ^ "Placeholder" for data whose constructors are defined later
deriving Functor
-- | Transform the FCs in a PData and its associated terms. The first
-- function transforms the general-purpose FCs, and the second transforms
-- those that are used for semantic source highlighting, so they can be
-- treated specially.
mapPDataFC :: (FC -> FC) -> (FC -> FC) -> PData -> PData
mapPDataFC f g (PDatadecl n nfc tycon ctors) =
PDatadecl n (g nfc) (mapPTermFC f g tycon) (map ctorFC ctors)
where ctorFC (doc, argDocs, n, nfc, ty, fc, ns) =
(doc, argDocs, n, g nfc, mapPTermFC f g ty, f fc, ns)
mapPDataFC f g (PLaterdecl n nfc tycon) =
PLaterdecl n (g nfc) (mapPTermFC f g tycon)
{-!
deriving instance Binary PData'
deriving instance NFData PData'
!-}
-- Handy to get a free function for applying PTerm -> PTerm functions
-- across a program, by deriving Functor
type PDecl = PDecl' PTerm
type PData = PData' PTerm
type PClause = PClause' PTerm
-- | Transform the FCs in a PTerm. The first function transforms the
-- general-purpose FCs, and the second transforms those that are used
-- for semantic source highlighting, so they can be treated specially.
mapPDeclFC :: (FC -> FC) -> (FC -> FC) -> PDecl -> PDecl
mapPDeclFC f g (PFix fc fixity ops) =
PFix (f fc) fixity ops
mapPDeclFC f g (PTy doc argdocs syn fc opts n nfc ty) =
PTy doc argdocs syn (f fc) opts n (g nfc) (mapPTermFC f g ty)
mapPDeclFC f g (PPostulate ext doc syn fc nfc opts n ty) =
PPostulate ext doc syn (f fc) (g nfc) opts n (mapPTermFC f g ty)
mapPDeclFC f g (PClauses fc opts n clauses) =
PClauses (f fc) opts n (map (fmap (mapPTermFC f g)) clauses)
mapPDeclFC f g (PCAF fc n tm) = PCAF (f fc) n (mapPTermFC f g tm)
mapPDeclFC f g (PData doc argdocs syn fc opts dat) =
PData doc argdocs syn (f fc) opts (mapPDataFC f g dat)
mapPDeclFC f g (PParams fc params decls) =
PParams (f fc)
(map (\(n, ty) -> (n, mapPTermFC f g ty)) params)
(map (mapPDeclFC f g) decls)
mapPDeclFC f g (PNamespace ns fc decls) =
PNamespace ns (f fc) (map (mapPDeclFC f g) decls)
mapPDeclFC f g (PRecord doc syn fc opts n nfc params paramdocs fields ctor ctorDoc syn') =
PRecord doc syn (f fc) opts n (g nfc)
(map (\(pn, pnfc, plic, ty) -> (pn, g pnfc, plic, mapPTermFC f g ty)) params)
paramdocs
(map (\(fn, plic, ty, fdoc) -> (fmap (\(fn', fnfc) -> (fn', g fnfc)) fn,
plic, mapPTermFC f g ty, fdoc))
fields)
(fmap (\(ctorN, ctorNFC) -> (ctorN, g ctorNFC)) ctor)
ctorDoc
syn'
mapPDeclFC f g (PClass doc syn fc constrs n nfc params paramDocs det body ctor ctorDoc) =
PClass doc syn (f fc)
(map (\(constrn, constr) -> (constrn, mapPTermFC f g constr)) constrs)
n (g nfc) (map (\(n, nfc, pty) -> (n, g nfc, mapPTermFC f g pty)) params)
paramDocs (map (\(dn, dnfc) -> (dn, g dnfc)) det)
(map (mapPDeclFC f g) body)
(fmap (\(n, nfc) -> (n, g nfc)) ctor)
ctorDoc
mapPDeclFC f g (PInstance doc paramDocs syn fc constrs cn cnfc params instTy instN body) =
PInstance doc paramDocs syn (f fc)
(map (\(constrN, constrT) -> (constrN, mapPTermFC f g constrT)) constrs)
cn (g cnfc) (map (mapPTermFC f g) params)
(mapPTermFC f g instTy)
instN
(map (mapPDeclFC f g) body)
mapPDeclFC f g (PDSL n dsl) = PDSL n (fmap (mapPTermFC f g) dsl)
mapPDeclFC f g (PSyntax fc syn) = PSyntax (f fc) $
case syn of
Rule syms tm ctxt -> Rule syms (mapPTermFC f g tm) ctxt
DeclRule syms decls -> DeclRule syms (map (mapPDeclFC f g) decls)
mapPDeclFC f g (PMutual fc decls) =
PMutual (f fc) (map (mapPDeclFC f g) decls)
mapPDeclFC f g (PDirective d) =
PDirective $
case d of
DNameHint n nfc ns ->
DNameHint n (g nfc) (map (\(hn, hnfc) -> (hn, g hnfc)) ns)
DErrorHandlers n nfc n' nfc' ns ->
DErrorHandlers n (g nfc) n' (g nfc') $
map (\(an, anfc) -> (an, g anfc)) ns
mapPDeclFC f g (PProvider doc syn fc nfc what n) =
PProvider doc syn (f fc) (g nfc) (fmap (mapPTermFC f g) what) n
mapPDeclFC f g (PTransform fc safe l r) =
PTransform (f fc) safe (mapPTermFC f g l) (mapPTermFC f g r)
mapPDeclFC f g (PRunElabDecl fc script ns) =
PRunElabDecl (f fc) (mapPTermFC f g script) ns
-- | Get all the names declared in a declaration
declared :: PDecl -> [Name]
declared (PFix _ _ _) = []
declared (PTy _ _ _ _ _ n fc t) = [n]
declared (PPostulate _ _ _ _ _ _ n t) = [n]
declared (PClauses _ _ n _) = [] -- not a declaration
declared (PCAF _ n _) = [n]
declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
where fstt (_, _, a, _, _, _, _) = a
declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n]
declared (PParams _ _ ds) = concatMap declared ds
declared (PNamespace _ _ ds) = concatMap declared ds
declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms)
declared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
declared (PDSL n _) = [n]
declared (PSyntax _ _) = []
declared (PMutual _ ds) = concatMap declared ds
declared (PDirective _) = []
declared _ = []
-- get the names declared, not counting nested parameter blocks
tldeclared :: PDecl -> [Name]
tldeclared (PFix _ _ _) = []
tldeclared (PTy _ _ _ _ _ n _ t) = [n]
tldeclared (PPostulate _ _ _ _ _ _ n t) = [n]
tldeclared (PClauses _ _ n _) = [] -- not a declaration
tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
where fstt (_, _, a, _, _, _, _) = a
tldeclared (PParams _ _ ds) = []
tldeclared (PMutual _ ds) = concatMap tldeclared ds
tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds
tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms)
tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
tldeclared _ = []
defined :: PDecl -> [Name]
defined (PFix _ _ _) = []
defined (PTy _ _ _ _ _ n _ t) = []
defined (PPostulate _ _ _ _ _ _ n t) = []
defined (PClauses _ _ n _) = [n] -- not a declaration
defined (PCAF _ n _) = [n]
defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
where fstt (_, _, a, _, _, _, _) = a
defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = []
defined (PParams _ _ ds) = concatMap defined ds
defined (PNamespace _ _ ds) = concatMap defined ds
defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms)
defined (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
defined (PDSL n _) = [n]
defined (PSyntax _ _) = []
defined (PMutual _ ds) = concatMap defined ds
defined (PDirective _) = []
defined _ = []
updateN :: [(Name, Name)] -> Name -> Name
updateN ns n | Just n' <- lookup n ns = n'
updateN _ n = n
updateNs :: [(Name, Name)] -> PTerm -> PTerm
updateNs [] t = t
updateNs ns t = mapPT updateRef t
where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f)
updateRef t = t
-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
-- updateDNs [] t = t
-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
-- where updateCNs ns (PClause n l ts r ds)
-- = PClause (updateN ns n) (fmap (updateNs ns) l)
-- (map (fmap (updateNs ns)) ts)
-- (fmap (updateNs ns) r)
-- (map (updateDNs ns) ds)
-- updateDNs ns c = c
data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show, Data, Typeable)
-- | High level language terms
data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language
| PRef FC [FC] Name -- ^ A reference to a variable. The FC is its precise source location for highlighting. The list of FCs is a collection of additional highlighting locations.
| PInferRef FC [FC] Name -- ^ A name to be defined later
| PPatvar FC Name -- ^ A pattern variable
| PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span.
| PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable
| PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location)
| PTyped PTerm PTerm -- ^ Term with explicit type
| PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
| PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only)
| PAppBind FC PTerm [PArg] -- ^ implicitly bound application
| PMatchApp FC Name -- ^ Make an application by type matching
| PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse
| PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs
| PTrue FC PunInfo -- ^ Unit type..?
| PResolveTC FC -- ^ Solve this dictionary by type class resolution
| PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type
| PPair FC [FC] PunInfo PTerm PTerm -- ^ A pair (a, b) and whether it's a product type or a pair (solved by elaboration). The list of FCs is its punctuation.
| PDPair FC [FC] PunInfo PTerm PTerm PTerm -- ^ A dependent pair (tm : a ** b) and whether it's a sigma type or a pair that inhabits one (solved by elaboration). The [FC] is its punctuation.
| PAs FC Name PTerm -- ^ @-pattern, valid LHS only
| PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames.
| PHidden PTerm -- ^ Irrelevant or hidden pattern
| PType FC -- ^ 'Type' type
| PUniverse Universe -- ^ Some universe
| PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions
| PConstant FC Const -- ^ Builtin types
| Placeholder -- ^ Underscore
| PDoBlock [PDo] -- ^ Do notation
| PIdiom FC PTerm -- ^ Idiom brackets
| PReturn FC
| PMetavar FC Name -- ^ A metavariable, ?name, and its precise location
| PProof [PTactic] -- ^ Proof script
| PTactics [PTactic] -- ^ As PProof, but no auto solving
| PElabError Err -- ^ Error to report on elaboration
| PImpossible -- ^ Special case for declaring when an LHS can't typecheck
| PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
| PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
| PUnifyLog PTerm -- ^ dump a trace of unifications when building term
| PNoImplicits PTerm -- ^ never run implicit converions on the term
| PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
| PUnquote PTerm -- ^ ~Term
| PQuoteName Name Bool FC -- ^ `{n} where the FC is the precise highlighting for the name in particular. If the Bool is False, then it's `{{n}} and the name won't be resolved.
| PRunElab FC PTerm [String] -- ^ %runElab tm - New-style proof script. Args are location, script, enclosing namespace.
| PConstSugar FC PTerm -- ^ A desugared constant. The FC is a precise source location that will be used to highlight it later.
deriving (Eq, Data, Typeable)
data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed
| FirstSuccess
| TryImplicit
deriving (Eq, Data, Typeable)
-- | Transform the FCs in a PTerm. The first function transforms the
-- general-purpose FCs, and the second transforms those that are used
-- for semantic source highlighting, so they can be treated specially.
mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm
mapPTermFC f g (PQuote q) = PQuote q
mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n
mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n
mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n
mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PLet fc n fc' t1 t2 t3) = PLet (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls
mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n
mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
mapPTermFC f g (PCase fc t cases) = PCase (f fc) (mapPTermFC f g t) (map (\(l,r) -> (mapPTermFC f g l, mapPTermFC f g r)) cases)
mapPTermFC f g (PTrue fc info) = PTrue (f fc) info
mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc)
mapPTermFC f g (PRewrite fc t1 t2 t3) = PRewrite (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3)
mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PDPair fc hls info t1 t2 t3) = PDPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t)
mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts)
mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t)
mapPTermFC f g (PType fc) = PType (f fc)
mapPTermFC f g (PUniverse u) = PUniverse u
mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2)
mapPTermFC f g (PConstant fc c) = PConstant (f fc) c
mapPTermFC f g Placeholder = Placeholder
mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos)
where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t)
mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t)
mapPDoFC (DoBindP fc t1 t2 alts) =
DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts)
mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t)
mapPTermFC f g (PReturn fc) = PReturn (f fc)
mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n
mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs)
mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs)
mapPTermFC f g (PElabError err) = PElabError err
mapPTermFC f g PImpossible = PImpossible
mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t)
mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t)
mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t)
mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t)
mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2)
mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t)
mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns
mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm)
mapPTermFC f g (PQuoteName n x fc) = PQuoteName n x (g fc)
{-!
dg instance Binary PTerm
deriving instance NFData PTerm
!-}
mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
mapPT f t = f (mpt t) where
mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s)
mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s)
mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)
mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
(fmap (mapPT f) g)
mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e)
mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r)
mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r)
mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as)
mpt (PHidden t) = PHidden (mapPT f t)
mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
mpt x = x
data PTactic' t = Intro [Name] | Intros | Focus Name
| Refine Name [Bool] | Rewrite t | DoUnify
| Induction t
| CaseTac t
| Equiv t
| Claim Name t
| Unfocus
| MatchRefine Name
| LetTac Name t | LetTacTy Name t t
| Exact t | Compute | Trivial | TCInstance
| ProofSearch Bool Bool Int (Maybe Name)
[Name] -- allowed local names
[Name] -- hints
-- ^ the bool is whether to search recursively
| Solve
| Attack
| ProofState | ProofTerm | Undo
| Try (PTactic' t) (PTactic' t)
| TSeq (PTactic' t) (PTactic' t)
| ApplyTactic t -- see Language.Reflection module
| ByReflection t
| Reflect t
| Fill t
| GoalType String (PTactic' t)
| TCheck t
| TEval t
| TDocStr (Either Name Const)
| TSearch t
| Skip
| TFail [ErrorReportPart]
| Qed | Abandon
| SourceFC
deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable)
{-!
deriving instance Binary PTactic'
deriving instance NFData PTactic'
!-}
instance Sized a => Sized (PTactic' a) where
size (Intro nms) = 1 + size nms
size Intros = 1
size (Focus nm) = 1 + size nm
size (Refine nm bs) = 1 + size nm + length bs
size (Rewrite t) = 1 + size t
size (Induction t) = 1 + size t
size (LetTac nm t) = 1 + size nm + size t
size (Exact t) = 1 + size t
size Compute = 1
size Trivial = 1
size Solve = 1
size Attack = 1
size ProofState = 1
size ProofTerm = 1
size Undo = 1
size (Try l r) = 1 + size l + size r
size (TSeq l r) = 1 + size l + size r
size (ApplyTactic t) = 1 + size t
size (Reflect t) = 1 + size t
size (Fill t) = 1 + size t
size Qed = 1
size Abandon = 1
size Skip = 1
size (TFail ts) = 1 + size ts
size SourceFC = 1
size DoUnify = 1
size (CaseTac x) = 1 + size x
size (Equiv t) = 1 + size t
size (Claim x y) = 1 + size x + size y
size Unfocus = 1
size (MatchRefine x) = 1 + size x
size (LetTacTy x y z) = 1 + size x + size y + size z
size TCInstance = 1
type PTactic = PTactic' PTerm
data PDo' t = DoExp FC t
| DoBind FC Name FC t -- ^ second FC is precise name location
| DoBindP FC t t [(t,t)]
| DoLet FC Name FC t t -- ^ second FC is precise name location
| DoLetP FC t t
deriving (Eq, Functor, Data, Typeable)
{-!
deriving instance Binary PDo'
deriving instance NFData PDo'
!-}
instance Sized a => Sized (PDo' a) where
size (DoExp fc t) = 1 + size fc + size t
size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t
size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r
size (DoLetP fc l r) = 1 + size fc + size l + size r
type PDo = PDo' PTerm
-- The priority gives a hint as to elaboration order. Best to elaborate
-- things early which will help give a more concrete type to other
-- variables, e.g. a before (interpTy a).
data PArg' t = PImp { priority :: Int,
machine_inf :: Bool, -- true if the machine inferred it
argopts :: [ArgOpt],
pname :: Name,
getTm :: t }
| PExp { priority :: Int,
argopts :: [ArgOpt],
pname :: Name,
getTm :: t }
| PConstraint { priority :: Int,
argopts :: [ArgOpt],
pname :: Name,
getTm :: t }
| PTacImplicit { priority :: Int,
argopts :: [ArgOpt],
pname :: Name,
getScript :: t,
getTm :: t }
deriving (Show, Eq, Functor, Data, Typeable)
data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg | UnknownImp
deriving (Show, Eq, Data, Typeable)
instance Sized a => Sized (PArg' a) where
size (PImp p _ l nm trm) = 1 + size nm + size trm
size (PExp p l nm trm) = 1 + size nm + size trm
size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
{-!
deriving instance Binary PArg'
deriving instance NFData PArg'
!-}
pimp n t mach = PImp 1 mach [] n t
pexp t = PExp 1 [] (sMN 0 "arg") t
pconst t = PConstraint 1 [] (sMN 0 "carg") t
ptacimp n s t = PTacImplicit 2 [] n s t
type PArg = PArg' PTerm
-- | Get the highest FC in a term, if one exists
highestFC :: PTerm -> Maybe FC
highestFC (PQuote _) = Nothing
highestFC (PRef fc _ _) = Just fc
highestFC (PInferRef fc _ _) = Just fc
highestFC (PPatvar fc _) = Just fc
highestFC (PLam fc _ _ _ _) = Just fc
highestFC (PPi _ _ _ _ _) = Nothing
highestFC (PLet fc _ _ _ _ _) = Just fc
highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty
highestFC (PApp fc _ _) = Just fc
highestFC (PAppBind fc _ _) = Just fc
highestFC (PMatchApp fc _) = Just fc
highestFC (PCase fc _ _) = Just fc
highestFC (PIfThenElse fc _ _ _) = Just fc
highestFC (PTrue fc _) = Just fc
highestFC (PResolveTC fc) = Just fc
highestFC (PRewrite fc _ _ _) = Just fc
highestFC (PPair fc _ _ _ _) = Just fc
highestFC (PDPair fc _ _ _ _ _) = Just fc
highestFC (PAs fc _ _) = Just fc
highestFC (PAlternative _ _ args) =
case mapMaybe highestFC args of
[] -> Nothing
(fc:_) -> Just fc
highestFC (PHidden _) = Nothing
highestFC (PType fc) = Just fc
highestFC (PUniverse _) = Nothing
highestFC (PGoal fc _ _ _) = Just fc
highestFC (PConstant fc _) = Just fc
highestFC Placeholder = Nothing
highestFC (PDoBlock lines) =
case map getDoFC lines of
[] -> Nothing
(fc:_) -> Just fc
where
getDoFC (DoExp fc t) = fc
getDoFC (DoBind fc nm nfc t) = fc
getDoFC (DoBindP fc l r alts) = fc
getDoFC (DoLet fc nm nfc l r) = fc
getDoFC (DoLetP fc l r) = fc
highestFC (PIdiom fc _) = Just fc
highestFC (PReturn fc) = Just fc
highestFC (PMetavar fc _) = Just fc
highestFC (PProof _) = Nothing
highestFC (PTactics _) = Nothing
highestFC (PElabError _) = Nothing
highestFC PImpossible = Nothing
highestFC (PCoerced tm) = highestFC tm
highestFC (PDisamb _ opts) = highestFC opts
highestFC (PUnifyLog tm) = highestFC tm
highestFC (PNoImplicits tm) = highestFC tm
highestFC (PQuasiquote _ _) = Nothing
highestFC (PUnquote tm) = highestFC tm
highestFC (PQuoteName _ _ fc) = Just fc
highestFC (PRunElab fc _ _) = Just fc
highestFC (PConstSugar fc _) = Just fc
highestFC (PAppImpl t _) = highestFC t
-- Type class data
data ClassInfo = CI { instanceCtorName :: Name,
class_methods :: [(Name, (FnOpts, PTerm))],
class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
class_default_superclasses :: [PDecl],
class_params :: [Name],
class_instances :: [(Name, Bool)], -- the Bool is whether to include in instance search, so named instances are excluded
class_determiners :: [Int] }
deriving Show
{-!
deriving instance Binary ClassInfo
deriving instance NFData ClassInfo
!-}
-- Record data
data RecordInfo = RI { record_parameters :: [(Name,PTerm)],
record_constructor :: Name,
record_projections :: [Name] }
deriving Show
-- Type inference data
data TIData = TIPartial -- ^ a function with a partially defined type
| TISolution [Term] -- ^ possible solutions to a metavariable in a type
deriving Show
-- | Miscellaneous information about functions
data FnInfo = FnInfo { fn_params :: [Int] }
deriving Show
{-!
deriving instance Binary FnInfo
deriving instance NFData FnInfo
!-}
data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
detaggable :: Bool }
deriving Show
{-!
deriving instance Binary OptInfo
deriving instance NFData OptInfo
!-}
-- | Syntactic sugar info
data DSL' t = DSL { dsl_bind :: t,
dsl_return :: t,
dsl_apply :: t,
dsl_pure :: t,
dsl_var :: Maybe t,
index_first :: Maybe t,
index_next :: Maybe t,
dsl_lambda :: Maybe t,
dsl_let :: Maybe t,
dsl_pi :: Maybe t
}
deriving (Show, Functor)
{-!
deriving instance Binary DSL'
deriving instance NFData DSL'
!-}
type DSL = DSL' PTerm
data SynContext = PatternSyntax | TermSyntax | AnySyntax
deriving Show
{-!
deriving instance Binary SynContext
deriving instance NFData SynContext
!-}
data Syntax = Rule [SSymbol] PTerm SynContext
| DeclRule [SSymbol] [PDecl]
deriving Show
syntaxNames :: Syntax -> [Name]
syntaxNames (Rule syms _ _) = mapMaybe ename syms
where ename (Keyword n) = Just n
ename _ = Nothing
syntaxNames (DeclRule syms _) = mapMaybe ename syms
where ename (Keyword n) = Just n
ename _ = Nothing
syntaxSymbols :: Syntax -> [SSymbol]
syntaxSymbols (Rule ss _ _) = ss
syntaxSymbols (DeclRule ss _) = ss
{-!
deriving instance Binary Syntax
deriving instance NFData Syntax
!-}
data SSymbol = Keyword Name
| Symbol String
| Binding Name
| Expr Name
| SimpleExpr Name
deriving (Show, Eq)
{-!
deriving instance Binary SSymbol
deriving instance NFData SSymbol
!-}
newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] }
emptySyntaxRules :: SyntaxRules
emptySyntaxRules = SyntaxRules []
updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules
updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules
where
newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr)
ruleSort [] [] = EQ
ruleSort [] _ = LT
ruleSort _ [] = GT
ruleSort (s1:ss1) (s2:ss2) =
case symCompare s1 s2 of
EQ -> ruleSort ss1 ss2
r -> r
-- Better than creating Ord instance for SSymbol since
-- in general this ordering does not really make sense.
symCompare (Keyword n1) (Keyword n2) = compare n1 n2
symCompare (Keyword _) _ = LT
symCompare (Symbol _) (Keyword _) = GT
symCompare (Symbol s1) (Symbol s2) = compare s1 s2
symCompare (Symbol _) _ = LT
symCompare (Binding _) (Keyword _) = GT
symCompare (Binding _) (Symbol _) = GT
symCompare (Binding b1) (Binding b2) = compare b1 b2
symCompare (Binding _) _ = LT
symCompare (Expr _) (Keyword _) = GT
symCompare (Expr _) (Symbol _) = GT
symCompare (Expr _) (Binding _) = GT
symCompare (Expr e1) (Expr e2) = compare e1 e2
symCompare (Expr _) _ = LT
symCompare (SimpleExpr _) (Keyword _) = GT
symCompare (SimpleExpr _) (Symbol _) = GT
symCompare (SimpleExpr _) (Binding _) = GT
symCompare (SimpleExpr _) (Expr _) = GT
symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2
initDSL = DSL (PRef f [] (sUN ">>="))
(PRef f [] (sUN "return"))
(PRef f [] (sUN "<*>"))
(PRef f [] (sUN "pure"))
Nothing
Nothing
Nothing
Nothing
Nothing
Nothing
where f = fileFC "(builtin)"
data Using = UImplicit Name PTerm
| UConstraint Name [Name]
deriving (Show, Eq, Data, Typeable)
{-!
deriving instance Binary Using
deriving instance NFData Using
!-}
data SyntaxInfo = Syn { using :: [Using],
syn_params :: [(Name, PTerm)],
syn_namespace :: [String],
no_imp :: [Name],
imp_methods :: [Name], -- class methods. When expanding
-- implicits, these should be expanded even under
-- binders
decoration :: Name -> Name,
inPattern :: Bool,
implicitAllowed :: Bool,
maxline :: Maybe Int,
mut_nesting :: Int,
dsl_info :: DSL,
syn_in_quasiquote :: Int }
deriving Show
{-!
deriving instance NFData SyntaxInfo
deriving instance Binary SyntaxInfo
!-}
defaultSyntax = Syn [] [] [] [] [] id False False Nothing 0 initDSL 0
expandNS :: SyntaxInfo -> Name -> Name
expandNS syn n@(NS _ _) = n
expandNS syn n = case syn_namespace syn of
[] -> n
xs -> sNS n xs
-- For inferring types of things
bi = fileFC "builtin"
inferTy = sMN 0 "__Infer"
inferCon = sMN 0 "__infer"
inferDecl = PDatadecl inferTy NoFC
(PType bi)
[(emptyDocstring, [], inferCon, NoFC, PPi impl (sMN 0 "iType") NoFC (PType bi) (
PPi expl (sMN 0 "ival") NoFC (PRef bi [] (sMN 0 "iType"))
(PRef bi [] inferTy)), bi, [])]
inferOpts = []
infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
infP = P (TCon 6 0) inferTy (TType (UVal 0))
getInferTerm, getInferType :: Term -> Term
getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
getInferTerm (App _ (App _ _ _) tm) = tm
getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
where toTy (Lam t) = Pi Nothing t (TType (UVar 0))
toTy (PVar t) = PVTy t
toTy b = b
getInferType (App _ (App _ _ ty) _) = ty
-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
primNames = [inferTy, inferCon]
unitTy = sUN "Unit"
unitCon = sUN "MkUnit"
falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $
"The empty type, also known as the trivially false proposition." ++
"\n\n" ++
"Use `void` or `absurd` to prove anything if you have a variable " ++
"of type `Void` in scope."
falseTy = sUN "Void"
pairTy = sNS (sUN "Pair") ["Builtins"]
pairCon = sNS (sUN "MkPair") ["Builtins"]
upairTy = sNS (sUN "UPair") ["Builtins"]
upairCon = sNS (sUN "MkUPair") ["Builtins"]
eqTy = sUN "="
eqCon = sUN "Refl"
eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $
"The propositional equality type. A proof that `x` = `y`." ++
"\n\n" ++
"To use such a proof, pattern-match on it, and the two equal things will " ++
"then need to be the _same_ pattern." ++
"\n\n" ++
"**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++
"is possible to state equalities between values of potentially different " ++
"types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++
"\n\n" ++
"You may need to use `(~=~)` to explicitly request heterogeneous equality."
eqDecl = PDatadecl eqTy NoFC (piBindp impl [(n "A", PType bi), (n "B", PType bi)]
(piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))]
(PType bi)))
[(reflDoc, reflParamDoc,
eqCon, NoFC, PPi impl (n "A") NoFC (PType bi) (
PPi impl (n "x") NoFC (PRef bi [] (n "A"))
(PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False,
pimp (n "B") Placeholder False,
pexp (PRef bi [] (n "x")),
pexp (PRef bi [] (n "x"))])), bi, [])]
where n a = sUN a
reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $
"A proof that `x` in fact equals `x`. To construct this, you must have already " ++
"shown that both sides are in fact equal."
reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"),
(n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")]
eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"),
(n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality")
]
where n a = sUN a
eqOpts = []
-- | The special name to be used in the module documentation context -
-- not for use in the main definition context. The namespace around it
-- will determine the module to which the docs adhere.
modDocName :: Name
modDocName = sMN 0 "ModuleDocs"
-- Defined in builtins.idr
sigmaTy = sNS (sUN "Sigma") ["Builtins"]
sigmaCon = sNS (sUN "MkSigma") ["Builtins"]
piBind :: [(Name, PTerm)] -> PTerm -> PTerm
piBind = piBindp expl
piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
piBindp p [] t = t
piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t)
-- Pretty-printing declarations and terms
-- These "show" instances render to an absurdly wide screen because inserted line breaks
-- could interfere with interactive editing, which calls "show".
instance Show PTerm where
showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
instance Show PDecl where
showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d
instance Show PClause where
showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
instance Show PData where
showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
instance Pretty PTerm OutputAnnotation where
pretty = prettyImp defaultPPOption
-- | Colourise annotations according to an Idris state. It ignores the names
-- in the annotation, as there's no good way to show extended information on a
-- terminal.
annotationColour :: IState -> OutputAnnotation -> Maybe IdrisColour
annotationColour ist _ | not (idris_colourRepl ist) = Nothing
annotationColour ist (AnnConst c) =
let theme = idris_colourTheme ist
in Just $ if constIsType c
then typeColour theme
else dataColour theme
annotationColour ist (AnnData _ _) = Just $ dataColour (idris_colourTheme ist)
annotationColour ist (AnnType _ _) = Just $ typeColour (idris_colourTheme ist)
annotationColour ist (AnnBoundName _ True) = Just $ implicitColour (idris_colourTheme ist)
annotationColour ist (AnnBoundName _ False) = Just $ boundVarColour (idris_colourTheme ist)
annotationColour ist AnnKeyword = Just $ keywordColour (idris_colourTheme ist)
annotationColour ist (AnnName n _ _ _) =
let ctxt = tt_ctxt ist
theme = idris_colourTheme ist
in case () of
_ | isDConName n ctxt -> Just $ dataColour theme
_ | isFnName n ctxt -> Just $ functionColour theme
_ | isTConName n ctxt -> Just $ typeColour theme
_ | isPostulateName n ist -> Just $ postulateColour theme
_ | otherwise -> Nothing -- don't colourise unknown names
annotationColour ist (AnnTextFmt fmt) = Just (colour fmt)
where colour BoldText = IdrisColour Nothing True False True False
colour UnderlineText = IdrisColour Nothing True True False False
colour ItalicText = IdrisColour Nothing True False False True
annotationColour ist _ = Nothing
-- | Colourise annotations according to an Idris state. It ignores the names
-- in the annotation, as there's no good way to show extended
-- information on a terminal. Note that strings produced this way will
-- not be coloured on Windows, so the use of the colour rendering
-- functions in Idris.Output is to be preferred.
consoleDecorate :: IState -> OutputAnnotation -> String -> String
consoleDecorate ist ann = maybe id colourise (annotationColour ist ann)
isPostulateName :: Name -> IState -> Bool
isPostulateName n ist = S.member n (idris_postulates ist)
-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
prettyImp :: PPOption -- ^^ pretty printing options
-> PTerm -- ^^ the term to pretty-print
-> Doc OutputAnnotation
prettyImp impl = pprintPTerm impl [] [] []
-- | Serialise something to base64 using its Binary instance.
-- | Do the right thing for rendering a term in an IState
prettyIst :: IState -> PTerm -> Doc OutputAnnotation
prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
-- | Pretty-print a high-level Idris term in some bindings context with infix info
pprintPTerm :: PPOption -- ^^ pretty printing options
-> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
-> [Name] -- ^^ names to always show in pi, even if not used
-> [FixDecl] -- ^^ Fixity declarations
-> PTerm -- ^^ the term to pretty-print
-> Doc OutputAnnotation
pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
where
startPrec = 0
funcAppPrec = 10
prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
prettySe d p bnd (PQuote r) =
text "![" <> pretty r <> text "]"
prettySe d p bnd (PPatvar fc n) = pretty n
prettySe d p bnd e
| Just str <- slist d p bnd e = depth d $ str
| Just n <- snat ppo d p e = depth d $ annotate (AnnData "Nat" "") (text (show n))
prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n
prettySe d p bnd (PLam fc n nfc ty sc) =
depth d . bracket p startPrec . group . align . hang 2 $
text "\\" <> prettyBindingOf n False <+> text "=>" <$>
prettySe (decD d) startPrec ((n, False):bnd) sc
prettySe d p bnd (PLet fc n nfc ty v sc) =
depth d . bracket p startPrec . group . align $
kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>
kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)
prettySe d p bnd (PPi (Exp l s _) n _ ty sc)
| n `elem` allNamesIn sc || ppopt_impl ppo && uname n || n `elem` docArgs
|| ppopt_pinames ppo && uname n =
depth d . bracket p startPrec . group $
enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
| otherwise =
depth d . bracket p startPrec . group $
group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$>
group (prettySe (decD d) startPrec ((n, False):bnd) sc)
where
uname (UN n) = case str n of
('_':_) -> False
_ -> True
uname _ = False
st =
case s of
Static -> text "[static]" <> space
_ -> empty
prettySe d p bnd (PPi (Imp l s _ fa) n _ ty sc)
| ppopt_impl ppo =
depth d . bracket p startPrec $
lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
| otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc
where
st =
case s of
Static -> text "[static]" <> space
_ -> empty
prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) =
depth d . bracket p startPrec $
prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc
prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch _ _ _ _ _ _])) n _ ty sc) =
lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) =
depth d . bracket p startPrec $
lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
-- This case preserves the behavior of the former constructor PEq.
-- It should be removed if feasible when the pretty-printing of infix
-- operators in general is improved.
prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r])
| n == eqTy, ppopt_impl ppo =
depth d . bracket p eqPrec $
enclose lparen rparen eq <+>
align (group (vsep (map (prettyArgS (decD d) bnd)
[lt, rt, l, r])))
| n == eqTy =
depth d . bracket p eqPrec . align . group $
prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r))
where eq = annName eqTy (text "=")
eqPrec = startPrec
prettyTerm = prettySe (decD d) (eqPrec + 1) bnd
prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args
| UN nm <- basename f
, not (ppopt_impl ppo) && null (getShowArgs args) =
prettyName True (ppopt_impl ppo) bnd f
prettySe d p bnd (PAppBind _ (PRef _ _ f) [])
| not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f
prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators
| UN nm <- basename op
, not (tnull nm) &&
(not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
case getShowArgs args of
[] -> opName True
[x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x)))
[l,r] -> let precedence = maybe (startPrec - 1) prec f
in depth d . bracket p precedence $ inFix (getTm l) (getTm r)
(l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) ->
depth d . bracket p funcAppPrec $
enclose lparen rparen (inFix (getTm l) (getTm r)) <+>
align (group (vsep (map (prettyArgS d bnd) rest)))
as -> opName True <+> align (vsep (map (prettyArgS d bnd) as))
where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op
f = getFixity (opStr op)
left = case f of
Nothing -> funcAppPrec + 1
Just (Infixl p') -> p'
Just f' -> prec f' + 1
right = case f of
Nothing -> funcAppPrec + 1
Just (Infixr p') -> p'
Just f' -> prec f' + 1
inFix l r = align . group $
(prettySe (decD d) left bnd l <+> opName False) <$>
group (prettySe (decD d) right bnd r)
prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo
| PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm,
f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str))
prettySe d p bnd (PApp _ f as) = -- Normal prefix applications
let args = getShowArgs as
fp = prettySe (decD d) (startPrec + 1) bnd f
shownArgs = if ppopt_impl ppo then as else args
in
depth d . bracket p funcAppPrec . group $
if null shownArgs
then fp
else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs))
prettySe d p bnd (PCase _ scr cases) =
align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$>
depth d (indent 2 (vsep (map ppcase cases)))
where
ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec
([(n, False) | n <- vars l] ++ bnd)
in nest nestingSize $
prettyCase l <+> text "=>" <+> prettyCase r
-- Warning: this is a bit of a hack. At this stage, we don't have the
-- global context, so we can't determine which names are constructors,
-- which are types, and which are pattern variables on the LHS of the
-- case pattern. We use the heuristic that names without a namespace
-- are patvars, because right now case blocks in PTerms are always
-- delaborated from TT before being sent to the pretty-printer. If they
-- start getting printed directly, THIS WILL BREAK.
-- Potential solution: add a list of known patvars to the cases in
-- PCase, and have the delaborator fill it out, kind of like the pun
-- disambiguation on PDPair.
vars tm = filter noNS (allNamesIn tm)
noNS (NS _ _) = False
noNS _ = True
prettySe d p bnd (PIfThenElse _ c t f) =
depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $
[ kwd "if" <+> prettySe (decD d) startPrec bnd c
, kwd "then" <+> prettySe (decD d) startPrec bnd t
, kwd "else" <+> prettySe (decD d) startPrec bnd f
]
prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
prettySe d p bnd (PResolveTC _) = kwd "%instance"
prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
prettySe d p bnd (PRewrite _ l r _) =
depth d . bracket p startPrec $
text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l <+> text "in" <+> prettySe (decD d) startPrec bnd r
prettySe d p bnd (PTyped l r) =
lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen
prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser
| Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) .
align . group . vsep . punctuate (ann comma) $
map (prettySe (decD d) startPrec bnd) elts
where ann = case pun of
TypeOrTerm -> id
IsType -> annName pairTy
IsTerm -> annName pairCon
prettySe d p bnd (PDPair _ _ pun l t r) =
depth d $
annotated lparen <>
left <+>
annotated (text "**") <+>
prettySe (decD d) startPrec (addBinding bnd) r <>
annotated rparen
where annotated = case pun of
IsType -> annName sigmaTy
IsTerm -> annName sigmaCon
TypeOrTerm -> id
(left, addBinding) = case (l, pun) of
(PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :))
_ -> (prettySe (decD d) startPrec bnd l, id)
prettySe d p bnd (PAlternative ns a as) =
lparen <> text "|" <> prettyAs <> text "|" <> rparen
where
prettyAs =
foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (depth d . prettySe (decD d) startPrec bnd) as
prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type"
prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u)
prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c))
-- XXX: add pretty for tactics
prettySe d p bnd (PProof ts) =
kwd "proof" <+> lbrace <> ellipsis <> rbrace
prettySe d p bnd (PTactics ts) =
kwd "tactics" <+> lbrace <> ellipsis <> rbrace
prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n
prettySe d p bnd (PReturn f) = kwd "return"
prettySe d p bnd PImpossible = kwd "impossible"
prettySe d p bnd Placeholder = text "_"
prettySe d p bnd (PDoBlock dos) =
bracket p startPrec $
kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos)))
where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos
ppdo bnd (DoBind _ bn _ tm : dos) =
(prettyBindingOf bn False <+> text "<-" <+>
group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) :
ppdo ((bn, False):bnd) dos
ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab
text "no pretty printer for pattern-matching do binding" :
ppdo bnd dos
ppdo bnd (DoLet _ ln _ ty v : dos) =
(kwd "let" <+> prettyBindingOf ln False <+>
(if ty /= Placeholder
then colon <+> prettySe (decD d) startPrec bnd ty <+> text "="
else text "=") <+>
group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) :
ppdo ((ln, False):bnd) dos
ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab
text "no pretty printer for pattern-matching do binding" :
ppdo bnd dos
ppdo _ [] = []
prettySe d p bnd (PCoerced t) = prettySe d p bnd t
prettySe d p bnd (PElabError s) = pretty s
-- Quasiquote pprinting ignores bound vars
prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")"
prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")"
prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t
prettySe d p bnd (PQuoteName n res _) = text start <> prettyName True (ppopt_impl ppo) bnd n <> text end
where start = if res then "`{" else "`{{"
end = if res then "}" else "}}"
prettySe d p bnd (PRunElab _ tm _) =
bracket p funcAppPrec . group . align . hang 2 $
text "%runElab" <$>
prettySe (decD d) funcAppPrec bnd tm
prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
prettySe d p bnd _ = text "missing pretty-printer for term"
prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation
prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n))
where display (UN n) = T.unpack n
display (MN _ n) = T.unpack n
-- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings
display (NS n ns) = (concat . intersperse "." . map T.unpack . reverse) ns ++ "." ++ display n
display n = show n
prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm)
prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm
prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm
prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm)
prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg
prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace
prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
annName n = annotate (AnnName n Nothing Nothing Nothing)
opStr :: Name -> String
opStr (NS n _) = opStr n
opStr (UN n) = T.unpack n
slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation]
slist' (Just d) _ _ _ | d <= 0 = Nothing
slist' d _ _ e
| containsHole e = Nothing
slist' d p bnd (PApp _ (PRef _ _ nil) _)
| not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
slist' d p bnd (PRef _ _ nil)
| not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
slist' d p bnd (PApp _ (PRef _ _ cons) args)
| nsroot cons == sUN "::",
(PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
all isImp imps,
Just tl' <- slist' (decD d) p bnd tl
= Just (prettySe d startPrec bnd hd : tl')
where
isImp (PImp {}) = True
isImp _ = False
slist' _ _ _ tm = Nothing
slist d p bnd e | Just es <- slist' d p bnd e = Just $
case es of
[] -> annotate (AnnData "" "") $ text "[]"
[x] -> enclose left right . group $ x
xs -> enclose left right .
align . group . vsep .
punctuate comma $ xs
where left = (annotate (AnnData "" "") (text "["))
right = (annotate (AnnData "" "") (text "]"))
comma = (annotate (AnnData "" "") (text ","))
slist _ _ _ _ = Nothing
pairElts :: PTerm -> Maybe [PTerm]
pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts)
| otherwise = Just [x, y]
pairElts _ = Nothing
natns = "Prelude.Nat."
snat :: PPOption -> Maybe Int -> Int -> PTerm -> Maybe Integer
snat ppo d p e
| ppopt_desugarnats ppo = Nothing
| otherwise = snat' d p e
where
snat' :: Maybe Int -> Int -> PTerm -> Maybe Integer
snat' (Just x) _ _ | x <= 0 = Nothing
snat' d p (PRef _ _ z)
| show z == (natns++"Z") || show z == "Z" = Just 0
snat' d p (PApp _ s [PExp {getTm=n}])
| show s == (natns++"S") || show s == "S",
Just n' <- snat' (decD d) p n
= Just $ 1 + n'
snat' _ _ _ = Nothing
bracket outer inner doc
| outer > inner = lparen <> doc <> rparen
| otherwise = doc
ellipsis = text "..."
depth Nothing = id
depth (Just d) = if d <= 0 then const (ellipsis) else id
decD = fmap (\x -> x - 1)
kwd = annotate AnnKeyword . text
fixities :: M.Map String Fixity
fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
getFixity :: String -> Maybe Fixity
getFixity = flip M.lookup fixities
-- | Strip away namespace information
basename :: Name -> Name
basename (NS n _) = basename n
basename n = n
-- | Determine whether a name was the one inserted for a hole or
-- guess by the delaborator
isHoleName :: Name -> Bool
isHoleName (UN n) = n == T.pack "[__]"
isHoleName _ = False
-- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess
containsHole :: PTerm -> Bool
containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm]
-- | Pretty-printer helper for names that attaches the correct annotations
prettyName
:: Bool -- ^^ whether the name should be parenthesised if it is an infix operator
-> Bool -- ^^ whether to show namespaces
-> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
-> Name -- ^^ the name to pprint
-> Doc OutputAnnotation
prettyName infixParen showNS bnd n
| (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_"
| (UN n') <- n, T.unpack n' == "_" = text "_"
| Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName
| otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName
where fullName = text nameSpace <> parenthesise (text (baseName n))
baseName (UN n) = T.unpack n
baseName (NS n ns) = baseName n
baseName (MN i s) = T.unpack s
baseName other = show other
nameSpace = case n of
(NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else ""
_ -> ""
isInfix = case baseName n of
"" -> False
(c : _) -> not (isAlpha c)
parenthesise = if isInfix && infixParen then enclose lparen rparen else id
showCImp :: PPOption -> PClause -> Doc OutputAnnotation
showCImp ppo (PClause _ n l ws r w)
= prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
<+> text "where" <+> text (show w)
where
showWs [] = empty
showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
showCImp ppo (PWith _ n l ws r pn w)
= prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
<+> braces (text (show w))
where
showWs [] = empty
showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
showDImp :: PPOption -> PData -> Doc OutputAnnotation
showDImp ppo (PDatadecl n nfc ty cons)
= text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
(indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons))
showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
showDecls o ds = vsep (map (showDeclImp o) ds)
showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
indent 2 (vsep (map (showCImp o) cs))
showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _)
= text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
showDeclImp o (PInstance _ _ _ _ cs n _ _ t _ ds)
= text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
showDeclImp _ _ = text "..."
-- showDeclImp (PImport o) = "import " ++ o
getImps :: [PArg] -> [(Name, PTerm)]
getImps [] = []
getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
getImps (_ : xs) = getImps xs
getExps :: [PArg] -> [PTerm]
getExps [] = []
getExps (PExp _ _ _ tm : xs) = tm : getExps xs
getExps (_ : xs) = getExps xs
getShowArgs :: [PArg] -> [PArg]
getShowArgs [] = []
getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs
getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs
| PImp _ _ _ _ tm <- e
, containsHole tm = e : getShowArgs xs
getShowArgs (_ : xs) = getShowArgs xs
getConsts :: [PArg] -> [PTerm]
getConsts [] = []
getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
getConsts (_ : xs) = getConsts xs
getAll :: [PArg] -> [PTerm]
getAll = map getTm
-- | Show Idris name
showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
-> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
-> PPOption -- ^^ pretty printing options
-> Bool -- ^^ whether to colourise
-> Name -- ^^ the term to show
-> String
showName ist bnd ppo colour n = case ist of
Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
Nothing -> showbasic n
where name = if ppopt_impl ppo then show n else showbasic n
showbasic n@(UN _) = showCG n
showbasic (MN i s) = str s
showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
showbasic (SN s) = show s
fst3 (x, _, _) = x
colourise n t = let ctxt' = fmap tt_ctxt ist in
case ctxt' of
Nothing -> name
Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
else colouriseBound t name
| isDConName n ctxt -> colouriseData t name
| isFnName n ctxt -> colouriseFun t name
| isTConName n ctxt -> colouriseType t name
-- The assumption is that if a name is not bound and does not exist in the
-- global context, then we're somewhere in which implicit info has been lost
-- (like error messages). Thus, unknown vars are colourised as implicits.
| otherwise -> colouriseImplicit t name
showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
-> PTerm -- ^^ the term to show
-> String
showTm ist = displayDecorated (consoleDecorate ist) .
renderPretty 0.8 100000 .
prettyImp (ppOptionIst ist)
-- | Show a term with implicits, no colours
showTmImpls :: PTerm -> String
showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
-- | Show a term with specific options
showTmOpts :: PPOption -> PTerm -> String
showTmOpts opt = flip (displayS . renderPretty 1.0 10000000 . prettyImp opt) ""
instance Sized PTerm where
size (PQuote rawTerm) = size rawTerm
size (PRef fc _ name) = size name
size (PLam fc name _ ty bdy) = 1 + size ty + size bdy
size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy
size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy
size (PTyped trm ty) = 1 + size trm + size ty
size (PApp fc name args) = 1 + size args
size (PAppBind fc name args) = 1 + size args
size (PCase fc trm bdy) = 1 + size trm + size bdy
size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f])
size (PTrue fc _) = 1
size (PResolveTC fc) = 1
size (PRewrite fc left right _) = 1 + size left + size right
size (PPair fc _ _ left right) = 1 + size left + size right
size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right
size (PAlternative _ a alts) = 1 + size alts
size (PHidden hidden) = size hidden
size (PUnifyLog tm) = size tm
size (PDisamb _ tm) = size tm
size (PNoImplicits tm) = size tm
size (PType _) = 1
size (PUniverse _) = 1
size (PConstant fc const) = 1 + size fc + size const
size Placeholder = 1
size (PDoBlock dos) = 1 + size dos
size (PIdiom fc term) = 1 + size term
size (PReturn fc) = 1
size (PMetavar _ name) = 1
size (PProof tactics) = size tactics
size (PElabError err) = size err
size PImpossible = 1
size _ = 0
getPArity :: PTerm -> Int
getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc
getPArity _ = 0
-- Return all names, free or globally bound, in the given term.
allNamesIn :: PTerm -> [Name]
allNamesIn tm = nub $ ni 0 [] tm
where -- TODO THINK added niTacImp, but is it right?
ni 0 env (PRef _ _ n)
| not (n `elem` env) = [n]
ni 0 env (PPatvar _ n) = [n]
ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os)
ni 0 env (PIfThenElse _ c t f) = ni 0 env c ++ ni 0 env t ++ ni 0 env f
ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
ni 0 env (PLet _ n _ ty val sc) = ni 0 env ty ++ ni 0 env val ++ ni 0 (n:env) sc
ni 0 env (PHidden tm) = ni 0 env tm
ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
ni 0 env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : ni 0 env r
ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
ni 0 env (PAlternative ns a ls) = concatMap (ni 0 env) ls
ni 0 env (PUnifyLog tm) = ni 0 env tm
ni 0 env (PDisamb _ tm) = ni 0 env tm
ni 0 env (PNoImplicits tm) = ni 0 env tm
ni i env (PQuasiquote tm ty) = ni (i+1) env tm ++ maybe [] (ni i env) ty
ni i env (PUnquote tm) = ni (i - 1) env tm
ni i env tm = concatMap (ni i env) (children tm)
niTacImp i env (TacImp _ _ scr) = ni i env scr
niTacImp _ _ _ = []
-- Return all names defined in binders in the given term
boundNamesIn :: PTerm -> [Name]
boundNamesIn tm = S.toList (ni 0 S.empty tm)
where -- TODO THINK Added niTacImp, but is it right?
ni :: Int -> S.Set Name -> PTerm -> S.Set Name
ni 0 set (PApp _ f as) = niTms 0 (ni 0 set f) (map getTm as)
ni 0 set (PAppBind _ f as) = niTms 0 (ni 0 set f) (map getTm as)
ni 0 set (PCase _ c os) = niTms 0 (ni 0 set c) (map snd os)
ni 0 set (PIfThenElse _ c t f) = niTms 0 set [c, t, f]
ni 0 set (PLam fc n _ ty sc) = S.insert n $ ni 0 (ni 0 set ty) sc
ni 0 set (PLet fc n nfc ty val sc) = S.insert n $ ni 0 (ni 0 (ni 0 set ty) val) sc
ni 0 set (PPi p n _ ty sc) = niTacImp 0 (S.insert n $ ni 0 (ni 0 set ty) sc) p
ni 0 set (PRewrite _ l r _) = ni 0 (ni 0 set l) r
ni 0 set (PTyped l r) = ni 0 (ni 0 set l) r
ni 0 set (PPair _ _ _ l r) = ni 0 (ni 0 set l) r
ni 0 set (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 (ni 0 set t) r
ni 0 set (PDPair _ _ _ l t r) = ni 0 (ni 0 (ni 0 set l) t) r
ni 0 set (PAlternative ns a as) = niTms 0 set as
ni 0 set (PHidden tm) = ni 0 set tm
ni 0 set (PUnifyLog tm) = ni 0 set tm
ni 0 set (PDisamb _ tm) = ni 0 set tm
ni 0 set (PNoImplicits tm) = ni 0 set tm
ni i set (PQuasiquote tm ty) = ni (i + 1) set tm `S.union` maybe S.empty (ni i set) ty
ni i set (PUnquote tm) = ni (i - 1) set tm
ni i set tm = foldr S.union set (map (ni i set) (children tm))
niTms :: Int -> S.Set Name -> [PTerm] -> S.Set Name
niTms i set [] = set
niTms i set (x : xs) = niTms i (ni i set x) xs
niTacImp i set (TacImp _ _ scr) = ni i set scr
niTacImp i set _ = set
-- Return names which are valid implicits in the given term (type).
implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
implicitNamesIn uvars ist tm = nub $ ni 0 [] tm
where
ni 0 env (PRef _ _ n)
| not (n `elem` env)
= case lookupTy n (tt_ctxt ist) of
[] -> [n]
_ -> if n `elem` uvars then [n] else []
ni 0 env (PApp _ f@(PRef _ _ n) as)
| n `elem` uvars = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
| otherwise = concatMap (ni 0 env) (map getTm as)
ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
ni 0 env (PCase _ c os) = ni 0 env c ++
-- names in 'os', not counting the names bound in the cases
(nub (concatMap (ni 0 env) (map snd os))
\\ nub (concatMap (ni 0 env) (map fst os)))
ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
ni 0 env (PPi p n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
ni 0 env (PHidden tm) = ni 0 env tm
ni 0 env (PUnifyLog tm) = ni 0 env tm
ni 0 env (PDisamb _ tm) = ni 0 env tm
ni 0 env (PNoImplicits tm) = ni 0 env tm
ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++
maybe [] (ni i env) ty
ni i env (PUnquote tm) = ni (i - 1) env tm
ni i env tm = concatMap (ni i env) (children tm)
-- Return names which are free in the given term.
namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
namesIn uvars ist tm = nub $ ni 0 [] tm
where
ni 0 env (PRef _ _ n)
| not (n `elem` env)
= case lookupTy n (tt_ctxt ist) of
[] -> [n]
_ -> if n `elem` (map fst uvars) then [n] else []
ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
ni 0 env (PCase _ c os) = ni 0 env c ++
-- names in 'os', not counting the names bound in the cases
(nub (concatMap (ni 0 env) (map snd os))
\\ nub (concatMap (ni 0 env) (map fst os)))
ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
ni 0 env (PLam fc n nfc ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
ni 0 env (PHidden tm) = ni 0 env tm
ni 0 env (PUnifyLog tm) = ni 0 env tm
ni 0 env (PDisamb _ tm) = ni 0 env tm
ni 0 env (PNoImplicits tm) = ni 0 env tm
ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
ni i env (PUnquote tm) = ni (i - 1) env tm
ni i env tm = concatMap (ni i env) (children tm)
niTacImp i env (TacImp _ _ scr) = ni i env scr
niTacImp _ _ _ = []
-- Return which of the given names are used in the given term.
usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
usedNamesIn vars ist tm = nub $ ni 0 [] tm
where -- TODO THINK added niTacImp, but is it right?
ni 0 env (PRef _ _ n)
| n `elem` vars && not (n `elem` env)
= case lookupDefExact n (tt_ctxt ist) of
Nothing -> [n]
_ -> []
ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os)
ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
ni 0 env (PHidden tm) = ni 0 env tm
ni 0 env (PUnifyLog tm) = ni 0 env tm
ni 0 env (PDisamb _ tm) = ni 0 env tm
ni 0 env (PNoImplicits tm) = ni 0 env tm
ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
ni i env (PUnquote tm) = ni (i - 1) env tm
ni i env tm = concatMap (ni i env) (children tm)
niTacImp i env (TacImp _ _ scr) = ni i env scr
niTacImp _ _ _ = []
-- Return the list of inaccessible (= dotted) positions for a name.
getErasureInfo :: IState -> Name -> [Int]
getErasureInfo ist n =
case lookupCtxtExact n (idris_optimisation ist) of
Just (Optimise inacc detagg) -> map fst inacc
Nothing -> []
| MetaMemoryT/Idris-dev | src/Idris/AbsSyntaxTree.hs | bsd-3-clause | 103,703 | 0 | 22 | 33,350 | 35,399 | 18,304 | 17,095 | 1,835 | 98 |
module Yesod.Helpers.Yaml (
module Yesod.Helpers.Yaml
, DefaultEnv(..)
) where
import Prelude
import Data.Yaml
import Yesod
import Data.Text (Text)
import Data.Aeson (withObject)
import qualified Data.Text as T
import Data.Maybe (isJust)
import Data.List (find)
import Yesod.Default.Config (DefaultEnv(..))
import Yesod.Helpers.Aeson
-- | check whether a string is in the list identified by a key string
-- some special strings:
-- __any__ will match any string
--
-- example yaml like this
-- Develpment:
-- dangerous-op: foo bar
-- simple-op:
-- - foo
-- - bar
-- safe-op: __any__
checkInListYaml ::
(Show config, MonadIO m, MonadLogger m) =>
FilePath
-> config -- ^ config section: Develpment/Production/...
-> Text -- ^ the key
-> Text -- ^ the name looking for
-> m Bool
checkInListYaml fp c key name = do
checkInListYaml' fp c key (== name)
checkInListYaml' ::
(Show config, MonadIO m, MonadLogger m) =>
FilePath
-> config -- ^ config section: Develpment/Production/...
-> Text -- ^ the key
-> (Text -> Bool) -- ^ the name looking for
-> m Bool
checkInListYaml' fp c key chk_name = do
result <- liftIO $ decodeFileEither fp
case result of
Left ex -> do
$(logError) $ T.pack $
"failed to parse YAML file " ++ show fp ++ ": " ++ show ex
return False
Right v -> do
case parseEither look_for_names v of
Left err -> do
$(logError) $ T.pack $
"YAML " ++ show fp
++ " contains invalid content: "
++ show err
return False
Right names -> return $ isJust $ find match names
where
look_for_names = withObject "section-mapping" $ \obj -> do
obj .:? (T.pack $ show c)
>>= maybe (return [])
(\section -> do
section .:? key >>=
maybe (return []) (parseWordList' "words")
)
match x = if x == "__any__"
then True
else chk_name x
| yoo-e/yesod-helpers | Yesod/Helpers/Yaml.hs | bsd-3-clause | 2,512 | 0 | 23 | 1,090 | 541 | 286 | 255 | -1 | -1 |
module QueryArrow.Control.Monad.Logger.HSLogger where
import Control.Monad.Logger
import System.Log.FastLogger
import System.Log.Logger
import qualified Data.Text as T
import Data.Text.Encoding
instance MonadLogger IO where
monadLoggerLog loc logsource loglevel msg = do
let priority = case loglevel of
LevelDebug -> DEBUG
LevelInfo -> INFO
LevelWarn -> WARNING
LevelError -> ERROR
LevelOther _ -> NOTICE
logM (show logsource) priority (T.unpack (decodeUtf8 (fromLogStr (toLogStr msg))))
instance MonadLoggerIO IO where
askLoggerIO = return monadLoggerLog
| xu-hao/QueryArrow | log-adapter/src/QueryArrow/Control/Monad/Logger/HSLogger.hs | bsd-3-clause | 706 | 0 | 16 | 216 | 167 | 90 | 77 | 17 | 0 |
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- | Wiki page view.
module HL.V.Wiki where
import HL.V
import HL.V.Code
import HL.V.Template
import Data.List (isPrefixOf)
import Data.Text (unpack,pack)
import Language.Haskell.HsColour.CSS (hscolour)
import Prelude hiding (readFile)
import Text.Pandoc.Definition
import Text.Pandoc.Options
import Text.Pandoc.Walk
import Text.Pandoc.Writers.HTML
-- | Wiki view.
wikiV :: (Route App -> Text) -> Either Text (Text,Pandoc) -> FromSenza App
wikiV urlr result =
template
([WikiHomeR] ++
[WikiR n | Right (n,_) <- [result]])
(case result of
Left{} -> "Wiki error!"
Right (t,_) -> t)
(\_ ->
container
(row
(span12
[]
(case result of
Left err ->
do h1 [] "Wiki page retrieval problem!"
p [] (toHtml err)
Right (t,pan) ->
do h1 [] (toHtml t)
writeHtml writeOptions (cleanup urlr pan)))))
where cleanup url = highlightBlock . highlightInline . relativize url
writeOptions = def { writerTableOfContents = True }
-- | Make all wiki links use the wiki route.
relativize :: (Route App -> Text) -> Pandoc -> Pandoc
relativize url = walk links
where links asis@(Link is (ref,t))
| isPrefixOf "http://" ref || isPrefixOf "https://" ref = asis
| otherwise = Link is (unpack (url (WikiR (pack ref))),t)
links x = x
-- | Highlight code blocks and inline code samples with a decent
-- Haskell syntax highlighter.
highlightBlock :: Pandoc -> Pandoc
highlightBlock = walk codes
where codes (CodeBlock ("",["haskell"],[]) text) =
RawBlock "html" (hscolour False text)
codes x = x
-- | Highlight code blocks and inline code samples with a decent
-- Haskell syntax highlighter.
highlightInline :: Pandoc -> Pandoc
highlightInline = walk codes
where codes (Code ("",["haskell"],[]) text) =
RawInline "html" (preToCode (hscolour False text))
codes x = x
| yogsototh/hl | src/HL/V/Wiki.hs | bsd-3-clause | 2,130 | 0 | 21 | 579 | 651 | 349 | 302 | 53 | 3 |
module Yesod.Helpers.Auth where
import Prelude
import Yesod
import Yesod.Auth
import Control.Monad.Catch (MonadThrow)
import Control.Monad
import qualified Data.Text as T
yesodAuthIdDo :: (YesodAuth master, MonadIO m, MonadThrow m, MonadBaseControl IO m) =>
(AuthId master -> HandlerT master m a)
-> HandlerT master m a
yesodAuthIdDo f = do
liftHandlerT maybeAuthId
>>= maybe (permissionDeniedI $ (T.pack "Login Required")) return
>>= f
yesodAuthIdDoSub :: (YesodAuth master, MonadIO m, MonadThrow m, MonadBaseControl IO m) =>
(AuthId master -> HandlerT site (HandlerT master m) a)
-> HandlerT site (HandlerT master m) a
yesodAuthIdDoSub f = do
(lift $ liftHandlerT maybeAuthId)
>>= maybe (permissionDeniedI $ (T.pack "Login Required")) return
>>= f
yesodAuthEntityDo :: (YesodAuthPersist master, MonadIO m, MonadThrow m, MonadBaseControl IO m) =>
((AuthId master, AuthEntity master) -> HandlerT master m a)
-> HandlerT master m a
yesodAuthEntityDo f = do
user_id <- liftHandlerT maybeAuthId
>>= maybe (permissionDeniedI $ (T.pack "Login Required")) return
let get_user =
#if MIN_VERSION_yesod_core(1, 4, 0)
getAuthEntity
#else
runDB . get
#endif
user <- liftHandlerT (get_user user_id)
>>= maybe (permissionDeniedI $ (T.pack "AuthEntity not found")) return
f (user_id, user)
yesodAuthEntityDoSub :: (YesodAuthPersist master, MonadIO m, MonadThrow m, MonadBaseControl IO m) =>
((AuthId master, AuthEntity master) -> HandlerT site (HandlerT master m) a)
-> HandlerT site (HandlerT master m) a
yesodAuthEntityDoSub f = do
let get_user =
#if MIN_VERSION_yesod_core(1, 4, 0)
getAuthEntity
#else
runDB . get
#endif
user_id <- lift (liftHandlerT maybeAuthId)
>>= maybe (permissionDeniedI $ (T.pack "Login Required")) return
user <- lift (liftHandlerT $ get_user user_id)
>>= maybe (permissionDeniedI $ (T.pack "AuthEntity not found")) return
f (user_id, user)
-- | 用于实现一种简单的身份认证手段:使用 google email 作为用户标识
newtype GoogleEmail = GoogleEmail { unGoogleEmail :: T.Text }
deriving (Show, Eq, PathPiece)
-- | used to implement 'authenticate' method of 'YesodAuth' class
authenticateGeImpl :: (MonadHandler m, AuthId master ~ GoogleEmail)
=> Creds master
-> m (AuthenticationResult master)
authenticateGeImpl creds = do
setSession "authed_gmail" raw_email
return $ Authenticated $ GoogleEmail raw_email
where
raw_email = credsIdent creds
-- | used to implement 'manybeAuthId' method of 'YesodAuth' class
maybeAuthIdGeImpl :: MonadHandler m => m (Maybe GoogleEmail)
maybeAuthIdGeImpl = do
liftM (fmap GoogleEmail) $ lookupSession "authed_gmail"
eitherGetLoggedInUserId :: YesodAuth master
=> HandlerT master IO (Either AuthResult (AuthId master))
eitherGetLoggedInUserId = do
m_uid <- maybeAuthId
case m_uid of
Nothing -> return $ Left AuthenticationRequired
Just uid -> return $ Right uid
| yoo-e/yesod-helpers | Yesod/Helpers/Auth.hs | bsd-3-clause | 3,357 | 0 | 14 | 913 | 893 | 449 | 444 | -1 | -1 |
module Main where
import Language.ECMAScript3.Syntax
import Language.ECMAScript3.Syntax.Annotations
import Language.ECMAScript3.Parser
import Language.ECMAScript3.PrettyPrint
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Data (Data)
--import System.IO
import Data.Generics.Uniplate.Data
import Data.List
main :: IO ()
main = getContents >>= parseJavaScript >>=
(print . apiAnalysis)
parseJavaScript :: String -> IO (JavaScript SourcePos)
parseJavaScript source = case parse parseScript "stdin" source of
Left perr -> fail $ show perr
Right js -> return js
data APIAnalysisResults = APIAnalysisResults {apiElements :: Set APIElement
,warnings :: [Warning]}
instance Show APIAnalysisResults where
show r = "The following API methods and fields are used: " ++
intercalate ", " (map show $ Set.toList $ apiElements r) ++
".\n" ++ if null $ warnings r then "No warnings to report"
else "Warning, the analysis results might not be sound: " ++
intercalate "\n" (map show $ warnings r)
data APIElement = APIElement [String]
deriving (Eq, Ord)
data Warning = Warning SourcePos String
instance Show APIElement where
show (APIElement elems) = intercalate "." elems
instance Show Warning where
show (Warning pos msg) = show pos ++ ": " ++ msg
topLevelAPIVars = ["window", "document", "XMLHttpRequest", "Object"
,"Function", "Array", "String", "Boolean", "Number", "Date"
,"RegExp", "Error", "EvalError", "RangeError"
,"ReferenceError", "SyntaxError", "TypeError", "URIError"
,"Math", "JSON"]
-- | The API analysis function. Returns a 'Set' of API
-- functions/fields and a list of warnings
apiAnalysis :: JavaScript SourcePos -> APIAnalysisResults
apiAnalysis script = APIAnalysisResults (Set.fromList $ genApiElements script)
(genWarnings script)
genApiElements :: JavaScript SourcePos -> [APIElement]
genApiElements = map toAPIElement . filter isAnAPIAccessor . universeBi
where isAnAPIAccessor :: Expression SourcePos -> Bool
isAnAPIAccessor e = case e of
DotRef _ o _ -> isAnAPIAccessor o
BracketRef _ o _ -> isAnAPIAccessor o
VarRef _ (Id _ v) -> v `elem` topLevelAPIVars
_ -> False
toAPIElement e = case e of
DotRef _ o (Id _ fld) -> toAPIElement o `addElement` fld
BracketRef _ o (StringLit _ s) -> toAPIElement o `addElement` s
VarRef _ (Id _ vn) -> APIElement [vn]
_ -> APIElement []
addElement :: APIElement -> String -> APIElement
addElement (APIElement elems) elem = APIElement (elems ++ [elem])
genWarnings :: JavaScript SourcePos -> [Warning]
genWarnings script = concatMap warnAliased topLevelAPIVars
++warnEvalUsed
where warnAliased varName =
[Warning (getAnnotation e) $ varName ++ " is aliased (in " ++
renderExpression e ++ ")"
|e@(AssignExpr _ _ _ (VarRef _ (Id _ vn))) <- universeBi script,
vn == varName]++
[Warning (getAnnotation vd) $ varName ++ " is aliased (in " ++
show vd ++ ")"
|vd@(VarDecl _ _ (Just (VarRef _ (Id _ vn)))) <- universeBi script,
vn == varName]
warnEvalUsed = [Warning (getAnnotation e) "Eval used"
|e@(CallExpr _ f _) <- universeBi script,
isEvalRef f]
isEvalRef e = case e of
VarRef _ (Id _ "eval") -> True
DotRef _ (VarRef _ (Id _ "window")) (Id _ "eval") -> True
_ -> False
-- | returns true if inside the expression there is a reference to the
-- variable
usesVariable :: (Data a) => String -> Expression a -> Bool
usesVariable v e = and [v' == v | VarRef _ (Id _ v') <- universe e]
| achudnov/jsapia | Main.hs | bsd-3-clause | 4,038 | 0 | 19 | 1,208 | 1,167 | 604 | 563 | 76 | 7 |
module Main where
import MenuIO
main :: IO ()
main = menu []
| arthurmgo/regex-ftc | app/Main.hs | bsd-3-clause | 63 | 0 | 6 | 15 | 27 | 15 | 12 | 4 | 1 |
module OutputDirectory
(outdir) where
outdir = "_data"
| pnlbwh/test-tensormasking | config-output-paths/OutputDirectory.hs | bsd-3-clause | 58 | 0 | 4 | 10 | 14 | 9 | 5 | 3 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module WFF where
import qualified Data.Map as M
import Test.QuickCheck hiding ((.||.), (==>), (.&&.))
import qualified Data.Set as S
import Data.Data
import Data.Generics.Uniplate.Data
import Data.List hiding (lookup, union)
import Prelude hiding (lookup)
import Control.Applicative hiding (empty)
data WFF = Var String
| And WFF WFF
| Or WFF WFF
| Not WFF
| Impl WFF WFF
| Eqv WFF WFF deriving (Data)
instance Show WFF where
show (Var s) = s
show (And x y) = "("++(show x) ++ " && "++(show y)++")"
show (Or x y) ="("++(show x) ++ " || "++(show y)++")"
show (Not x) = "~"++(show x)
show (Impl x y) = "("++(show x) ++ "=>" ++ (show y)++")"
show (Eqv x y) = "("++(show x) ++ "=" ++ (show y) ++ ")"
instance Arbitrary WFF where
arbitrary = sized myArbitrary
where
myArbitrary 0 = do
s <- oneof (map (return . show) [1..30])
return (Var s)
myArbitrary n = oneof [ binary n And,
binary n Or,
binary n Impl,
binary n Eqv,
fmap Not (myArbitrary (n-1)),
var
]
where
var = do
s <- oneof (map (return . show) [1..30])
return (Var s)
binary n f = do
s <- myArbitrary (div n 2)
t <- myArbitrary (div n 2)
return (f s t)
t `xor` t' = (t .|| t') .&& (n (t .&& t'))
t .&& t' = And t t'
t .|| t' = Or t t'
t ==> t' = Impl t t'
t <=> t' = Eqv t t'
n t = Not t
v s = Var s
variables wff = [v | Var v <- universe wff]
fromJust (Just x) = x
fromJust _ = undefined
eval :: M.Map String Bool -> WFF -> Bool
eval m (Var s) = fromJust $ M.lookup s m
eval m (And x y) = (&&) (eval m x) (eval m y)
eval m (Or x y) = (||) (eval m x) (eval m y)
eval m (Not y) = not (eval m y)
eval m (Impl x y) = (not (eval m x)) || (eval m y)
eval m (Eqv x y) = (==) (eval m x) (eval m y)
| patrikja/GRACeFUL | ConstraintModelling/WFF.hs | bsd-3-clause | 2,457 | 0 | 17 | 1,138 | 1,016 | 522 | 494 | 58 | 1 |
#!/usr/bin/env runhaskell
{-# LANGUAGE BangPatterns
#-}
{-| The Sphere Online Judge is a collection of problems. One problem, problem
450, came up on the mailing list as a sensible benchmark for fast integer
parsing.
-}
{- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
https://www.spoj.pl/problems/INTEST/
Slow IO?
http://www.nabble.com/Slow-IO--td25210251.html
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}
import Data.List
import Prelude hiding (drop, take)
import System.IO (stdin, stdout, stderr, Handle, putStrLn)
import Control.Monad
import Data.ByteString hiding (putStrLn, foldl')
import Data.ByteString.Nums.Careless
main = do
(n, k) <- breakByte 0x20 `fmap` hGetLine stdin
count <- show `fmap` obvious (int n) (int k)
putStrLn count
obvious n k = sum `fmap` sequence (numbers n stdin)
where
sum = foldl' (check k) 0
numbers :: Int -> Handle -> [IO Int]
numbers n h = const (int `fmap` hGetLine h) `fmap` [1..n]
check :: Int -> Int -> Int -> Int
check k acc n
| n `mod` k == 0 = acc + 1
| otherwise = acc
| solidsnack/bytestring-nums | SPOJObvious.hs | bsd-3-clause | 1,328 | 0 | 11 | 476 | 294 | 161 | 133 | 19 | 1 |
squareM = #x -> `(,x * ,x) -- `#` indicates macro-lambda
unittest "squareM" [
(squareM 3, 9),
(let a = 3 in squareM a, 9),
]
a = "a"
unittest "macro_expand" [
(macro_expand {squareM 3}, (*) 3 3),
(macro_expand {(squareM 3) + 1}, (+) ((*) 3 3) 1),
(macro_expand {squareM a}, (*) a a),
(macro_expand {let a = 1 in squareM a}, (\a.(*) a a) 1),
(macro_expand {let a = 1 in squareM (a+1)}, (\a.(*) ((+) a 1) ((+) a 1)) 1),
]
evalN 0 ((squareM 3) + 1)
evalN 1 ((squareM 3) + 1)
evalN 2 ((squareM 3) + 1)
evalN 3 ((squareM 3) + 1)
evalN 4 ((squareM 3) + 1)
-- (+) ((*) 3 3) 1
-- (+) ((3 *) 3) 1
-- (+) 9 1
-- (9 +) 1
-- 10
lazyevalN 0 ((squareM 3) + 1)
lazyevalN 1 ((squareM 3) + 1)
lazyevalN 2 ((squareM 3) + 1)
lazyevalN 3 ((squareM 3) + 1)
lazyevalN 4 ((squareM 3) + 1)
-- (+) ((*) 3 3) 1
-- (+) ((*) 3 3) 1
-- (+) 9 1
-- (9 +) 1
-- 10
| ocean0yohsuke/Simply-Typed-Lambda | Start/UnitTest/Macro.hs | bsd-3-clause | 926 | 24 | 11 | 281 | 470 | 270 | 200 | -1 | -1 |
import Control.Arrow ((***))
import Control.Monad (join)
{-- snippet adler32 --}
import Data.Char (ord)
import Data.Bits (shiftL, (.&.), (.|.))
base = 65521
adler32 xs = helper 1 0 xs
where helper a b (x:xs) = let a' = (a + (ord x .&. 0xff)) `mod` base
b' = (a' + b) `mod` base
in helper a' b' xs
helper a b _ = (b `shiftL` 16) .|. a
{-- /snippet adler32 --}
{-- snippet adler32_try2 --}
adler32_try2 xs = helper (1,0) xs
where helper (a,b) (x:xs) =
let a' = (a + (ord x .&. 0xff)) `mod` base
b' = (a' + b) `mod` base
in helper (a',b') xs
helper (a,b) _ = (b `shiftL` 16) .|. a
{-- /snippet adler32_try2 --}
{-- snippet adler32_foldl --}
adler32_foldl xs = let (a, b) = foldl step (1, 0) xs
in (b `shiftL` 16) .|. a
where step (a, b) x = let a' = a + (ord x .&. 0xff)
in (a' `mod` base, (a' + b) `mod` base)
{-- /snippet adler32_foldl --}
adler32_golf = uncurry (flip ((.|.) . (`shiftL` 16))) . foldl f (1,0)
where f (a,b) x = join (***) ((`mod` base) . (a + (ord x .&. 0xff) +)) (0,b)
| binesiyu/ifl | examples/ch04/Adler32.hs | mit | 1,188 | 0 | 16 | 403 | 548 | 313 | 235 | 22 | 2 |
{-@ LIQUID "--no-termination" @-}
module Lec02 where
import Text.Printf (printf)
import Debug.Trace (trace)
incr :: Int -> Int
incr x = x + 1
zincr :: Int -> Int
zincr = \x -> x + 1
eleven = incr (10 + 2)
-- sumList xs = case xs of
-- [] -> 0
-- (x:xs) -> x + sumList xs
sumList :: [Int] -> Int
sumList [] = 0
sumList (x:xs) = x + sumList xs
isOdd x = x `mod` 2 == 1
oddsBelow100 = myfilter isOdd [0..100]
myfilter f [] = []
myfilter f (x:xs') = if f x then x : rest else rest
where
rest = myfilter f xs'
neg :: (a -> Bool) -> (a -> Bool)
neg f = \x -> not (f x)
isEven = neg isOdd
partition p xs = (myfilter p xs, myfilter (neg p) xs)
sort [] = []
sort (x:xs) = sort ls ++ [x] ++ sort rs
where
ls = [ y | y <- xs, y < x ]
rs = [ z | z <- xs, x <= z ]
quiz = [x * 10 | x <- xs, x > 3]
where
xs = [0..5]
data Expr
= Number Double
| Plus Expr Expr
| Minus Expr Expr
| Times Expr Expr
deriving (Eq, Ord, Show)
eval :: Expr -> Double
eval e = case e of
Number n -> n
Plus e1 e2 -> eval e1 + eval e2
Minus e1 e2 -> eval e1 - eval e2
Times e1 e2 -> eval e1 * eval e2
ex0 :: Expr
ex0 = Number 5
ex1 :: Expr
ex1 = Plus ex0 (Number 7)
ex2 :: Expr
ex2 = Minus (Number 4) (Number 2)
ex3 :: Expr
ex3 = Times ex1 ex2
fact :: Int -> Int
fact n = trace msg res
where
msg = printf "Fact n = %d res = %d\n" n res
res = if n <= 0 then 0 else n * fact (n-1)
{-
-- fact :: Int -> Int
let rec fact n =
let res = if n <= 0 then 0 else n * fact (n-1) in
let _ = Printf.printf "Fact n = %d res = %d\n" n res in
res
-}
----
| ucsd-progsys/131-web | static/hs/lec-1-17-2018.hs | mit | 1,707 | 0 | 11 | 586 | 724 | 381 | 343 | 50 | 4 |
module Main where
comb :: [([Char], [Char])]
color = ["blue", "red", "green"]
comb = [(x, y) | x <- color, y <- color, x < y] | momo9/seven-lang | haskell/src/combination.hs | mit | 125 | 0 | 7 | 25 | 76 | 46 | 30 | 4 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{- |
Module : Network.MPD.Applicative.Internal
Copyright : (c) Simon Hengel 2012
License : MIT
Maintainer : joachifm@fastmail.fm
Stability : stable
Portability : unportable
Applicative MPD command interface.
This allows us to combine commands into command lists, as in
> (,,) <$> currentSong <*> stats <*> status
where the requests are automatically combined into a command list and
the result of each command passed to the consumer.
-}
module Network.MPD.Applicative.Internal
( Parser(..)
, liftParser
, getResponse
, emptyResponse
, unexpected
, Command(..)
, runCommand
) where
import Control.Monad
import Data.ByteString.Char8 (ByteString)
import Network.MPD.Core hiding (getResponse)
import qualified Network.MPD.Core as Core
import Control.Monad.Except
import qualified Control.Monad.Fail as Fail
-- | A line-oriented parser that returns a value along with any remaining input.
newtype Parser a
= Parser { runParser :: [ByteString] -> Either String (a, [ByteString]) }
deriving Functor
instance Monad Parser where
return a = Parser $ \input -> Right (a, input)
p1 >>= p2 = Parser $ \input -> runParser p1 input >>= uncurry (runParser . p2)
instance Fail.MonadFail Parser where
fail = Prelude.fail
instance Applicative Parser where
pure = return
(<*>) = ap
-- | Convert a regular parser.
liftParser :: ([ByteString] -> Either String a) -> Parser a
liftParser p = Parser $ \input -> case break (== "list_OK") input of
(xs, ys) -> fmap (, drop 1 ys) (p xs)
-- | Return everything until the next "list_OK".
getResponse :: Parser [ByteString]
getResponse = Parser $ \input -> case break (== "list_OK") input of
(xs, ys) -> Right (xs, drop 1 ys)
-- | For commands returning an empty response.
emptyResponse :: Parser ()
emptyResponse = do
r <- getResponse
unless (null r) $
unexpected r
-- | Fail with unexpected response.
unexpected :: [ByteString] -> Parser a
unexpected = fail . ("unexpected Response: " ++) . show
-- | A compound command, comprising a parser for the responses and a
-- combined request of an arbitrary number of commands.
data Command a = Command {
commandParser :: Parser a
, commandRequest :: [String]
} deriving Functor
instance Applicative Command where
pure a = Command (pure a) []
(Command p1 c1) <*> (Command p2 c2) = Command (p1 <*> p2) (c1 ++ c2)
-- | Execute a 'Command'.
runCommand :: MonadMPD m => Command a -> m a
runCommand (Command p c) = do
r <- Core.getResponse command
case runParser p r of
Left err -> throwError (Unexpected err)
Right (a, []) -> return a
Right (_, xs) -> throwError (Unexpected $ "superfluous input: " ++ show xs)
where
command = case c of
[x] -> x
xs -> unlines ("command_list_ok_begin" : xs)
++ "command_list_end"
| bens/libmpd-haskell | src/Network/MPD/Applicative/Internal.hs | lgpl-2.1 | 3,046 | 0 | 13 | 725 | 755 | 415 | 340 | 59 | 4 |
{-# LANGUAGE CPP, ScopedTypeVariables #-}
--
-- (c) The University of Glasgow 2002
--
-- Binary I/O library, with special tweaks for GHC
--
-- Based on the nhc98 Binary library, which is copyright
-- (c) Malcolm Wallace and Colin Runciman, University of York, 1998.
-- Under the terms of the license for that software, we must tell you
-- where you can obtain the original version of the Binary library, namely
-- http://www.cs.york.ac.uk/fp/nhc98/
module Binary
( {-type-} Bin,
{-class-} Binary(..),
{-type-} BinHandle,
openBinIO, openBinIO_,
openBinMem,
-- closeBin,
seekBin,
tellBin,
castBin,
writeBinMem,
readBinMem,
isEOFBin,
-- for writing instances:
putByte,
getByte,
putSharedString,
getSharedString,
-- lazy Bin I/O
lazyGet,
lazyPut,
#if __GLASGOW_HASKELL__<610
-- GHC only:
ByteArray(..),
getByteArray,
putByteArray,
#endif
getBinFileWithDict, -- :: Binary a => FilePath -> IO a
putBinFileWithDict, -- :: Binary a => FilePath -> ModuleName -> a -> IO ()
) where
#if __GLASGOW_HASKELL__>=604
#include "ghcconfig.h"
#else
#include "config.h"
#endif
import FastMutInt
import Map (Map)
import qualified Map as Map
#if __GLASGOW_HASKELL__>=602
# if __GLASGOW_HASKELL__>=707
import Data.HashTable.Class as HashTable
(HashTable)
import Data.HashTable.IO as HashTable
(BasicHashTable, toList, new, insert, lookup)
# else
import Data.HashTable as HashTable
# endif
#endif
import Data.Array.IO
import Data.Array
import Data.Bits
import Data.Int
import Data.Word
import Data.IORef
import Data.Char ( ord, chr )
import Data.Array.Base ( unsafeRead, unsafeWrite )
import Control.Monad ( when, liftM )
import System.IO as IO
import System.IO.Unsafe ( unsafeInterleaveIO )
import System.IO.Error ( mkIOError, eofErrorType )
import GHC.Real ( Ratio(..) )
import GHC.Exts
# if __GLASGOW_HASKELL__>=612
import GHC.IO (IO(IO))
#else
import GHC.IOBase (IO(IO))
#endif
import GHC.Word ( Word8(..) )
# if __GLASGOW_HASKELL__<602
import GHC.Handle ( hSetBinaryMode )
# endif
-- for debug
import System.CPUTime (getCPUTime)
import Numeric (showFFloat)
#define SIZEOF_HSINT SIZEOF_VOID_P
type BinArray = IOUArray Int Word8
---------------------------------------------------------------
-- BinHandle
---------------------------------------------------------------
data BinHandle
= BinMem { -- binary data stored in an unboxed array
bh_usr :: UserData, -- sigh, need parameterized modules :-)
off_r :: !FastMutInt, -- the current offset
sz_r :: !FastMutInt, -- size of the array (cached)
arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1))
}
-- XXX: should really store a "high water mark" for dumping out
-- the binary data to a file.
| BinIO { -- binary data stored in a file
bh_usr :: UserData,
off_r :: !FastMutInt, -- the current offset (cached)
hdl :: !IO.Handle -- the file handle (must be seekable)
}
-- cache the file ptr in BinIO; using hTell is too expensive
-- to call repeatedly. If anyone else is modifying this Handle
-- at the same time, we'll be screwed.
getUserData :: BinHandle -> UserData
getUserData bh = bh_usr bh
setUserData :: BinHandle -> UserData -> BinHandle
setUserData bh us = bh { bh_usr = us }
---------------------------------------------------------------
-- Bin
---------------------------------------------------------------
newtype Bin a = BinPtr Int
deriving (Eq, Ord, Show, Bounded)
castBin :: Bin a -> Bin b
castBin (BinPtr i) = BinPtr i
---------------------------------------------------------------
-- class Binary
---------------------------------------------------------------
class Binary a where
put_ :: BinHandle -> a -> IO ()
put :: BinHandle -> a -> IO (Bin a)
get :: BinHandle -> IO a
-- define one of put_, put. Use of put_ is recommended because it
-- is more likely that tail-calls can kick in, and we rarely need the
-- position return value.
put_ bh a = do put bh a; return ()
put bh a = do p <- tellBin bh; put_ bh a; return p
putAt :: Binary a => BinHandle -> Bin a -> a -> IO ()
putAt bh p x = do seekBin bh p; put bh x; return ()
getAt :: Binary a => BinHandle -> Bin a -> IO a
getAt bh p = do seekBin bh p; get bh
openBinIO_ :: IO.Handle -> IO BinHandle
openBinIO_ h = openBinIO h
openBinIO :: IO.Handle -> IO BinHandle
openBinIO h = do
r <- newFastMutInt
writeFastMutInt r 0
return (BinIO noUserData r h)
openBinMem :: Int -> IO BinHandle
openBinMem size
| size <= 0 = error "Data.Binary.openBinMem: size must be >= 0"
| otherwise = do
arr <- newArray_ (0,size-1)
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r size
return (BinMem noUserData ix_r sz_r arr_r)
tellBin :: BinHandle -> IO (Bin a)
tellBin (BinIO _ r _) = do ix <- readFastMutInt r; return (BinPtr ix)
tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix)
seekBin :: BinHandle -> Bin a -> IO ()
seekBin (BinIO _ ix_r h) (BinPtr p) = do
writeFastMutInt ix_r p
hSeek h AbsoluteSeek (fromIntegral p)
seekBin h@(BinMem _ ix_r sz_r a) (BinPtr p) = do
sz <- readFastMutInt sz_r
if (p >= sz)
then do expandBin h p; writeFastMutInt ix_r p
else writeFastMutInt ix_r p
isEOFBin :: BinHandle -> IO Bool
isEOFBin (BinMem _ ix_r sz_r a) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
return (ix >= sz)
isEOFBin (BinIO _ ix_r h) = hIsEOF h
writeBinMem :: BinHandle -> FilePath -> IO ()
writeBinMem (BinIO _ _ _) _ = error "Data.Binary.writeBinMem: not a memory handle"
writeBinMem (BinMem _ ix_r sz_r arr_r) fn = do
h <- openFile fn WriteMode
hSetBinaryMode h True
arr <- readIORef arr_r
ix <- readFastMutInt ix_r
hPutArray h arr ix
hClose h
readBinMem :: FilePath -> IO BinHandle
-- Return a BinHandle with a totally undefined State
readBinMem filename = do
h <- openFile filename ReadMode
hSetBinaryMode h True
filesize' <- hFileSize h
let filesize = fromIntegral filesize'
arr <- newArray_ (0,filesize-1)
count <- hGetArray h arr filesize
when (count /= filesize)
(error ("Binary.readBinMem: only read " ++ show count ++ " bytes"))
hClose h
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r filesize
return (BinMem noUserData ix_r sz_r arr_r)
-- expand the size of the array to include a specified offset
expandBin :: BinHandle -> Int -> IO ()
expandBin (BinMem _ ix_r sz_r arr_r) off = do
sz <- readFastMutInt sz_r
let sz' = head (dropWhile (<= off) (iterate (* 2) sz))
arr <- readIORef arr_r
arr' <- newArray_ (0,sz'-1)
sequence_ [ unsafeRead arr i >>= unsafeWrite arr' i
| i <- [ 0 .. sz-1 ] ]
writeFastMutInt sz_r sz'
writeIORef arr_r arr'
#ifdef DEBUG
hPutStrLn stderr ("Binary: expanding to size: " ++ show sz')
#endif
return ()
expandBin (BinIO _ _ _) _ = return ()
-- no need to expand a file, we'll assume they expand by themselves.
-- -----------------------------------------------------------------------------
-- Low-level reading/writing of bytes
putWord8 :: BinHandle -> Word8 -> IO ()
putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
-- double the size of the array if it overflows
if (ix >= sz)
then do expandBin h ix
putWord8 h w
else do arr <- readIORef arr_r
unsafeWrite arr ix w
writeFastMutInt ix_r (ix+1)
return ()
putWord8 (BinIO _ ix_r h) w = do
ix <- readFastMutInt ix_r
hPutChar h (chr (fromIntegral w)) -- XXX not really correct
writeFastMutInt ix_r (ix+1)
return ()
getWord8 :: BinHandle -> IO Word8
getWord8 (BinMem _ ix_r sz_r arr_r) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
when (ix >= sz) $
ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing)
arr <- readIORef arr_r
w <- unsafeRead arr ix
writeFastMutInt ix_r (ix+1)
return w
getWord8 (BinIO _ ix_r h) = do
ix <- readFastMutInt ix_r
c <- hGetChar h
writeFastMutInt ix_r (ix+1)
return $! (fromIntegral (ord c)) -- XXX not really correct
putByte :: BinHandle -> Word8 -> IO ()
putByte bh w = put_ bh w
getByte :: BinHandle -> IO Word8
getByte = getWord8
-- -----------------------------------------------------------------------------
-- Primitve Word writes
instance Binary Word8 where
put_ = putWord8
get = getWord8
instance Binary Word16 where
put_ h w = do -- XXX too slow.. inline putWord8?
putByte h (fromIntegral (w `shiftR` 8))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2)
instance Binary Word32 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 24))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 24) .|.
(fromIntegral w2 `shiftL` 16) .|.
(fromIntegral w3 `shiftL` 8) .|.
(fromIntegral w4))
instance Binary Word64 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 56))
putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
w5 <- getWord8 h
w6 <- getWord8 h
w7 <- getWord8 h
w8 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 56) .|.
(fromIntegral w2 `shiftL` 48) .|.
(fromIntegral w3 `shiftL` 40) .|.
(fromIntegral w4 `shiftL` 32) .|.
(fromIntegral w5 `shiftL` 24) .|.
(fromIntegral w6 `shiftL` 16) .|.
(fromIntegral w7 `shiftL` 8) .|.
(fromIntegral w8))
-- -----------------------------------------------------------------------------
-- Primitve Int writes
instance Binary Int8 where
put_ h w = put_ h (fromIntegral w :: Word8)
get h = do w <- get h; return $! (fromIntegral (w::Word8))
instance Binary Int16 where
put_ h w = put_ h (fromIntegral w :: Word16)
get h = do w <- get h; return $! (fromIntegral (w::Word16))
instance Binary Int32 where
put_ h w = put_ h (fromIntegral w :: Word32)
get h = do w <- get h; return $! (fromIntegral (w::Word32))
instance Binary Int64 where
put_ h w = put_ h (fromIntegral w :: Word64)
get h = do w <- get h; return $! (fromIntegral (w::Word64))
-- -----------------------------------------------------------------------------
-- Instances for standard types
instance Binary () where
put_ bh () = return ()
get _ = return ()
-- getF bh p = case getBitsF bh 0 p of (_,b) -> ((),b)
instance Binary Bool where
put_ bh b = putByte bh (fromIntegral (fromEnum b))
get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x))
-- getF bh p = case getBitsF bh 1 p of (x,b) -> (toEnum x,b)
instance Binary Char where
put_ bh c = put_ bh (fromIntegral (ord c) :: Word8)
get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word8)))
-- getF bh p = case getBitsF bh 8 p of (x,b) -> (toEnum x,b)
instance Binary Int where
#if SIZEOF_HSINT == 4
put_ bh i = put_ bh (fromIntegral i :: Int32)
get bh = do
x <- get bh
return $! (fromIntegral (x :: Int32))
#elif SIZEOF_HSINT == 8
put_ bh i = put_ bh (fromIntegral i :: Int64)
get bh = do
x <- get bh
return $! (fromIntegral (x :: Int64))
#else
#error "unsupported sizeof(HsInt)"
#endif
-- getF bh = getBitsF bh 32
instance Binary a => Binary [a] where
put_ bh list = do put_ bh (length list)
mapM_ (put_ bh) list
get bh = do len <- get bh
let getMany :: Int -> IO [a]
getMany 0 = return []
getMany n = do x <- get bh
xs <- getMany (n-1)
return (x:xs)
getMany len
instance (Binary a, Binary b) => Binary (a,b) where
put_ bh (a,b) = do put_ bh a; put_ bh b
get bh = do a <- get bh
b <- get bh
return (a,b)
instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where
put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c
get bh = do a <- get bh
b <- get bh
c <- get bh
return (a,b,c)
instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where
put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (a,b,c,d)
instance Binary a => Binary (Maybe a) where
put_ bh Nothing = putByte bh 0
put_ bh (Just a) = do putByte bh 1; put_ bh a
get bh = do h <- getWord8 bh
case h of
0 -> return Nothing
_ -> do x <- get bh; return (Just x)
instance (Binary a, Binary b) => Binary (Either a b) where
put_ bh (Left a) = do putByte bh 0; put_ bh a
put_ bh (Right b) = do putByte bh 1; put_ bh b
get bh = do h <- getWord8 bh
case h of
0 -> do a <- get bh ; return (Left a)
_ -> do b <- get bh ; return (Right b)
instance (Binary a, Binary i, Ix i) => Binary (Array i a) where
put_ bh arr = do put_ bh (Data.Array.bounds arr)
put_ bh (Data.Array.elems arr)
get bh = do bounds <- get bh
elems <- get bh
return $ listArray bounds elems
instance (Binary key, Ord key, Binary elem) => Binary (Map key elem) where
-- put_ bh fm = put_ bh (Map.toList fm)
-- get bh = do list <- get bh
-- return (Map.fromList list)
put_ bh fm = do let list = Map.toList fm
put_ bh (length list)
mapM_ (\(key, val) -> do put_ bh key
lazyPut bh val) list
get bh = do len <- get bh
let getMany :: Int -> IO [(key,elem)]
getMany 0 = return []
getMany n = do key <- get bh
val <- lazyGet bh
xs <- getMany (n-1)
return ((key,val):xs)
-- printElapsedTime "before get Map"
list <- getMany len
-- printElapsedTime "after get Map"
return (Map.fromList list)
#ifdef __GLASGOW_HASKELL__
#if __GLASGOW_HASKELL__<610
instance Binary Integer where
put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#)
put_ bh (J# s# a#) = do
p <- putByte bh 1;
put_ bh (I# s#)
let sz# = sizeofByteArray# a# -- in *bytes*
put_ bh (I# sz#) -- in *bytes*
putByteArray bh a# sz#
get bh = do
b <- getByte bh
case b of
0 -> do (I# i#) <- get bh
return (S# i#)
_ -> do (I# s#) <- get bh
sz <- get bh
(BA a#) <- getByteArray bh sz
return (J# s# a#)
putByteArray :: BinHandle -> ByteArray# -> Int# -> IO ()
putByteArray bh a s# = loop 0#
where loop n#
| n# ==# s# = return ()
| otherwise = do
putByte bh (indexByteArray a n#)
loop (n# +# 1#)
getByteArray :: BinHandle -> Int -> IO ByteArray
getByteArray bh (I# sz) = do
(MBA arr) <- newByteArray sz
let loop n
| n ==# sz = return ()
| otherwise = do
w <- getByte bh
writeByteArray arr n w
loop (n +# 1#)
loop 0#
freezeByteArray arr
data ByteArray = BA ByteArray#
data MBA = MBA (MutableByteArray# RealWorld)
newByteArray :: Int# -> IO MBA
newByteArray sz = IO $ \s ->
case newByteArray# sz s of { (# s, arr #) ->
(# s, MBA arr #) }
freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray
freezeByteArray arr = IO $ \s ->
case unsafeFreezeByteArray# arr s of { (# s, arr #) ->
(# s, BA arr #) }
writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO ()
#if __GLASGOW_HASKELL__ < 503
writeByteArray arr i w8 = IO $ \s ->
case word8ToWord w8 of { W# w# ->
case writeCharArray# arr i (chr# (word2Int# w#)) s of { s ->
(# s , () #) }}
#else
writeByteArray arr i (W8# w) = IO $ \s ->
case writeWord8Array# arr i w s of { s ->
(# s, () #) }
#endif
#if __GLASGOW_HASKELL__ < 503
indexByteArray a# n# = fromIntegral (I# (ord# (indexCharArray# a# n#)))
#else
indexByteArray a# n# = W8# (indexWord8Array# a# n#)
#endif
instance (Integral a, Binary a) => Binary (Ratio a) where
put_ bh (a :% b) = do put_ bh a; put_ bh b
get bh = do a <- get bh; b <- get bh; return (a :% b)
#else
instance Binary Integer where
put_ h n = do
put h ((fromIntegral $ signum n) :: Int8)
when (n /= 0) $ do
let n' = abs n
nBytes = byteSize n'
put h (fromIntegral nBytes :: Word64)
mapM_ (putByte h) [ fromIntegral ((n' `shiftR` (b * 8)) .&. 0xff)
| b <- [ nBytes-1, nBytes-2 .. 0 ] ]
where byteSize n =
let f b = if (1 `shiftL` (b * 8)) > n
then b
else f (b + 1)
in f 0
get h = do
sign :: Int8 <- get h
if sign == 0
then return 0
else do
nBytes :: Word64 <- get h
n <- accumBytes nBytes 0
return $ fromIntegral sign * n
where accumBytes nBytes acc | nBytes == 0 = return acc
| otherwise = do
b <- getByte h
accumBytes (nBytes - 1) ((acc `shiftL` 8) .|. fromIntegral b)
#endif
#endif
instance Binary (Bin a) where
put_ bh (BinPtr i) = put_ bh i
get bh = do i <- get bh; return (BinPtr i)
-- -----------------------------------------------------------------------------
-- Lazy reading/writing
lazyPut :: Binary a => BinHandle -> a -> IO ()
lazyPut bh a = do
-- output the obj with a ptr to skip over it:
pre_a <- tellBin bh
put_ bh pre_a -- save a slot for the ptr
put_ bh a -- dump the object
q <- tellBin bh -- q = ptr to after object
putAt bh pre_a q -- fill in slot before a with ptr to q
seekBin bh q -- finally carry on writing at q
lazyGet :: Binary a => BinHandle -> IO a
lazyGet bh = do
p <- get bh -- a BinPtr
p_a <- tellBin bh
a <- unsafeInterleaveIO (getAt bh p_a)
seekBin bh p -- skip over the object for now
return a
-- --------------------------------------------------------------
-- Main wrappers: getBinFileWithDict, putBinFileWithDict
--
-- This layer is built on top of the stuff above,
-- and should not know anything about BinHandles
-- --------------------------------------------------------------
initBinMemSize = (1024*1024) :: Int
binaryInterfaceMagic = 0x1face :: Word32
getBinFileWithDict :: Binary a => FilePath -> IO a
getBinFileWithDict file_path = do
bh <- Binary.readBinMem file_path
-- Read the magic number to check that this really is a GHC .hi file
-- (This magic number does not change when we change
-- GHC interface file format)
magic <- get bh
when (magic /= binaryInterfaceMagic) $
error "magic number mismatch: old/corrupt interface file?"
-- Read the dictionary
-- The next word in the file is a pointer to where the dictionary is
-- (probably at the end of the file)
dict_p <- Binary.get bh -- Get the dictionary ptr
data_p <- tellBin bh -- Remember where we are now
seekBin bh dict_p
dict <- getDictionary bh
seekBin bh data_p -- Back to where we were before
-- Initialise the user-data field of bh
let bh' = setUserData bh (initReadState dict)
-- At last, get the thing
get bh'
putBinFileWithDict :: Binary a => FilePath -> a -> IO ()
putBinFileWithDict file_path the_thing = do
-- hnd <- openBinaryFile file_path WriteMode
-- bh <- openBinIO hnd
bh <- openBinMem initBinMemSize
put_ bh binaryInterfaceMagic
-- Remember where the dictionary pointer will go
dict_p_p <- tellBin bh
put_ bh dict_p_p -- Placeholder for ptr to dictionary
-- Make some intial state
usr_state <- newWriteState
-- Put the main thing,
put_ (setUserData bh usr_state) the_thing
-- Get the final-state
j <- readIORef (ud_next usr_state)
#if __GLASGOW_HASKELL__>=602
fm <- HashTable.toList (ud_map usr_state)
#else
fm <- liftM Map.toList $ readIORef (ud_map usr_state)
#endif
dict_p <- tellBin bh -- This is where the dictionary will start
-- Write the dictionary pointer at the fornt of the file
putAt bh dict_p_p dict_p -- Fill in the placeholder
seekBin bh dict_p -- Seek back to the end of the file
-- Write the dictionary itself
putDictionary bh j (constructDictionary j fm)
-- And send the result to the file
writeBinMem bh file_path
-- hClose hnd
-- -----------------------------------------------------------------------------
-- UserData
-- -----------------------------------------------------------------------------
data UserData =
UserData { -- This field is used only when reading
ud_dict :: Dictionary,
-- The next two fields are only used when writing
ud_next :: IORef Int, -- The next index to use
#if __GLASGOW_HASKELL__>=602
# if __GLASGOW_HASKELL__>=707
ud_map :: BasicHashTable String Int -- The index of each string
# else
ud_map :: HashTable String Int -- The index of each string
# endif
#else
ud_map :: IORef (Map String Int)
#endif
}
noUserData = error "Binary.UserData: no user data"
initReadState :: Dictionary -> UserData
initReadState dict = UserData{ ud_dict = dict,
ud_next = undef "next",
ud_map = undef "map" }
newWriteState :: IO UserData
newWriteState = do
j_r <- newIORef 0
#if __GLASGOW_HASKELL__>=602
# if __GLASGOW_HASKELL__>=707
out_r <- HashTable.new
# else
out_r <- HashTable.new (==) HashTable.hashString
# endif
#else
out_r <- newIORef Map.empty
#endif
return (UserData { ud_dict = error "dict",
ud_next = j_r,
ud_map = out_r })
undef s = error ("Binary.UserData: no " ++ s)
---------------------------------------------------------
-- The Dictionary
---------------------------------------------------------
type Dictionary = Array Int String -- The dictionary
-- Should be 0-indexed
putDictionary :: BinHandle -> Int -> Dictionary -> IO ()
putDictionary bh sz dict = do
put_ bh sz
mapM_ (put_ bh) (elems dict)
getDictionary :: BinHandle -> IO Dictionary
getDictionary bh = do
sz <- get bh
elems <- sequence (take sz (repeat (get bh)))
return (listArray (0,sz-1) elems)
constructDictionary :: Int -> [(String,Int)] -> Dictionary
constructDictionary j fm = array (0,j-1) (map (\(x,y) -> (y,x)) fm)
---------------------------------------------------------
-- Reading and writing memoised Strings
---------------------------------------------------------
putSharedString :: BinHandle -> String -> IO ()
putSharedString bh str =
case getUserData bh of
UserData { ud_next = j_r, ud_map = out_r, ud_dict = dict} -> do
#if __GLASGOW_HASKELL__>=602
entry <- HashTable.lookup out_r str
#else
fm <- readIORef out_r
let entry = Map.lookup str fm
#endif
case entry of
Just j -> put_ bh j
Nothing -> do
j <- readIORef j_r
put_ bh j
writeIORef j_r (j+1)
#if __GLASGOW_HASKELL__>=602
HashTable.insert out_r str j
#else
modifyIORef out_r (\fm -> Map.insert str j fm)
#endif
getSharedString :: BinHandle -> IO String
getSharedString bh = do
j <- get bh
return $! (ud_dict (getUserData bh) ! j)
{-
---------------------------------------------------------
-- Reading and writing FastStrings
---------------------------------------------------------
putFS bh (FastString id l ba) = do
put_ bh (I# l)
putByteArray bh ba l
putFS bh s = error ("Binary.put_(FastString): " ++ unpackFS s)
-- Note: the length of the FastString is *not* the same as
-- the size of the ByteArray: the latter is rounded up to a
-- multiple of the word size.
{- -- possible faster version, not quite there yet:
getFS bh@BinMem{} = do
(I# l) <- get bh
arr <- readIORef (arr_r bh)
off <- readFastMutInt (off_r bh)
return $! (mkFastSubStringBA# arr off l)
-}
getFS bh = do
(I# l) <- get bh
(BA ba) <- getByteArray bh (I# l)
return $! (mkFastSubStringBA# ba 0# l)
instance Binary FastString where
put_ bh f@(FastString id l ba) =
case getUserData bh of {
UserData { ud_next = j_r, ud_map = out_r, ud_dict = dict} -> do
out <- readIORef out_r
let uniq = getUnique f
case lookupUFM out uniq of
Just (j,f) -> put_ bh j
Nothing -> do
j <- readIORef j_r
put_ bh j
writeIORef j_r (j+1)
writeIORef out_r (addToUFM out uniq (j,f))
}
put_ bh s = error ("Binary.put_(FastString): " ++ show (unpackFS s))
get bh = do
j <- get bh
return $! (ud_dict (getUserData bh) ! j)
-}
printElapsedTime :: String -> IO ()
printElapsedTime msg = do
time <- getCPUTime
hPutStr stderr $ "elapsed time: " ++ Numeric.showFFloat (Just 2) ((fromIntegral time) / 10^12) " (" ++ msg ++ ")\n"
| k0001/gtk2hs | tools/c2hs/base/general/Binary.hs | gpl-3.0 | 27,010 | 2 | 19 | 8,071 | 7,275 | 3,626 | 3,649 | -1 | -1 |
{-# LANGUAGE DataKinds, PolyKinds, TypeOperators, TypeFamilies
, TypeApplications #-}
module DumpTypecheckedAst where
import Data.Kind
data Peano = Zero | Succ Peano
type family Length (as :: [k]) :: Peano where
Length (a : as) = Succ (Length as)
Length '[] = Zero
data T f (a :: k) = MkT (f a)
type family F (a :: k) (f :: k -> Type) :: Type where
F @Peano a f = T @Peano f a
main = putStrLn "hello"
| sdiehl/ghc | testsuite/tests/parser/should_compile/DumpTypecheckedAst.hs | bsd-3-clause | 431 | 2 | 8 | 109 | 158 | 92 | 66 | -1 | -1 |
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import Prelude
import Text.Shakespeare.Text (st)
import Language.Haskell.TH.Syntax
import Database.Persist.Sqlite (SqliteConf)
import Yesod.Default.Config
import Yesod.Default.Util
import Data.Text (Text)
import Data.Yaml
import Control.Applicative
import Settings.Development
import Data.Default (def)
import Text.Hamlet
-- | Which Persistent backend this site is using.
type PersistConf = SqliteConf
-- Static setting below. Changing these requires a recompile
-- | The location of static files on your system. This is a file system
-- path. The default value works properly with your scaffolded site.
staticDir :: FilePath
staticDir = "static"
-- | The base URL for your static files. As you can see by the default
-- value, this can simply be "static" appended to your application root.
-- A powerful optimization can be serving static files from a separate
-- domain name. This allows you to use a web server optimized for static
-- files, more easily set expires and cache values, and avoid possibly
-- costly transference of cookies on static files. For more information,
-- please see:
-- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
--
-- If you change the resource pattern for StaticR in Foundation.hs, you will
-- have to make a corresponding change here.
--
-- To see how this value is used, see urlRenderOverride in Foundation.hs
staticRoot :: AppConfig DefaultEnv x -> Text
staticRoot conf = [st|#{appRoot conf}/lab/nom/static|]
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
{ wfsHamletSettings = defaultHamletSettings
{ hamletNewlines = AlwaysNewlines
}
}
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if development then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
data Extra = Extra
{ extraCopyright :: Text
, extraAnalytics :: Maybe Text -- ^ Google Analytics
} deriving Show
parseExtra :: DefaultEnv -> Object -> Parser Extra
parseExtra _ o = Extra
<$> o .: "copyright"
<*> o .:? "analytics"
| SuetakeY/nomnichi_yesod | Settings.hs | bsd-2-clause | 2,742 | 0 | 9 | 483 | 287 | 182 | 105 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude
, RecordWildCards
, BangPatterns
, NondecreasingIndentation
, RankNTypes
#-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Handle.Internals
-- Copyright : (c) The University of Glasgow, 1994-2001
-- License : see libraries/base/LICENSE
--
-- Maintainer : libraries@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- This module defines the basic operations on I\/O \"handles\". All
-- of the operations defined here are independent of the underlying
-- device.
--
-----------------------------------------------------------------------------
module GHC.IO.Handle.Internals (
withHandle, withHandle', withHandle_,
withHandle__', withHandle_', withAllHandles__,
wantWritableHandle, wantReadableHandle, wantReadableHandle_,
wantSeekableHandle,
mkHandle, mkFileHandle, mkDuplexHandle,
openTextEncoding, closeTextCodecs, initBufferState,
dEFAULT_CHAR_BUFFER_SIZE,
flushBuffer, flushWriteBuffer, flushCharReadBuffer,
flushCharBuffer, flushByteReadBuffer, flushByteWriteBuffer,
readTextDevice, writeCharBuffer, readTextDeviceNonBlocking,
decodeByteBuf,
augmentIOError,
ioe_closedHandle, ioe_EOF, ioe_notReadable, ioe_notWritable,
ioe_finalizedHandle, ioe_bufsiz,
hClose_help, hLookAhead_,
HandleFinalizer, handleFinalizer,
debugIO,
) where
import GHC.IO
import GHC.IO.IOMode
import GHC.IO.Encoding as Encoding
import GHC.IO.Encoding.Types (CodeBuffer)
import GHC.IO.Handle.Types
import GHC.IO.Buffer
import GHC.IO.BufferedIO (BufferedIO)
import GHC.IO.Exception
import GHC.IO.Device (IODevice, SeekMode(..))
import qualified GHC.IO.Device as IODevice
import qualified GHC.IO.BufferedIO as Buffered
import GHC.Conc.Sync
import GHC.Real
import GHC.Base
import GHC.Exception
import GHC.Num ( Num(..) )
import GHC.Show
import GHC.IORef
import GHC.MVar
import Data.Typeable
import Control.Monad
import Data.Maybe
import Foreign.Safe
import System.Posix.Internals hiding (FD)
import Foreign.C
c_DEBUG_DUMP :: Bool
c_DEBUG_DUMP = False
-- ---------------------------------------------------------------------------
-- Creating a new handle
type HandleFinalizer = FilePath -> MVar Handle__ -> IO ()
newFileHandle :: FilePath -> Maybe HandleFinalizer -> Handle__ -> IO Handle
newFileHandle filepath mb_finalizer hc = do
m <- newMVar hc
case mb_finalizer of
Just finalizer -> addMVarFinalizer m (finalizer filepath m)
Nothing -> return ()
return (FileHandle filepath m)
-- ---------------------------------------------------------------------------
-- Working with Handles
{-
In the concurrent world, handles are locked during use. This is done
by wrapping an MVar around the handle which acts as a mutex over
operations on the handle.
To avoid races, we use the following bracketing operations. The idea
is to obtain the lock, do some operation and replace the lock again,
whether the operation succeeded or failed. We also want to handle the
case where the thread receives an exception while processing the IO
operation: in these cases we also want to relinquish the lock.
There are three versions of @withHandle@: corresponding to the three
possible combinations of:
- the operation may side-effect the handle
- the operation may return a result
If the operation generates an error or an exception is raised, the
original handle is always replaced.
-}
{-# INLINE withHandle #-}
withHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a
withHandle fun h@(FileHandle _ m) act = withHandle' fun h m act
withHandle fun h@(DuplexHandle _ m _) act = withHandle' fun h m act
withHandle' :: String -> Handle -> MVar Handle__
-> (Handle__ -> IO (Handle__,a)) -> IO a
withHandle' fun h m act =
mask_ $ do
(h',v) <- do_operation fun h act m
checkHandleInvariants h'
putMVar m h'
return v
{-# INLINE withHandle_ #-}
withHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a
withHandle_ fun h@(FileHandle _ m) act = withHandle_' fun h m act
withHandle_ fun h@(DuplexHandle _ m _) act = withHandle_' fun h m act
withHandle_' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a
withHandle_' fun h m act = withHandle' fun h m $ \h_ -> do
a <- act h_
return (h_,a)
withAllHandles__ :: String -> Handle -> (Handle__ -> IO Handle__) -> IO ()
withAllHandles__ fun h@(FileHandle _ m) act = withHandle__' fun h m act
withAllHandles__ fun h@(DuplexHandle _ r w) act = do
withHandle__' fun h r act
withHandle__' fun h w act
withHandle__' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO Handle__)
-> IO ()
withHandle__' fun h m act =
mask_ $ do
h' <- do_operation fun h act m
checkHandleInvariants h'
putMVar m h'
return ()
do_operation :: String -> Handle -> (Handle__ -> IO a) -> MVar Handle__ -> IO a
do_operation fun h act m = do
h_ <- takeMVar m
checkHandleInvariants h_
act h_ `catchException` handler h_
where
handler h_ e = do
putMVar m h_
case () of
_ | Just ioe <- fromException e ->
ioError (augmentIOError ioe fun h)
_ | Just async_ex <- fromException e -> do -- see Note [async]
let _ = async_ex :: SomeAsyncException
t <- myThreadId
throwTo t e
do_operation fun h act m
_otherwise ->
throwIO e
-- Note [async]
--
-- If an asynchronous exception is raised during an I/O operation,
-- normally it is fine to just re-throw the exception synchronously.
-- However, if we are inside an unsafePerformIO or an
-- unsafeInterleaveIO, this would replace the enclosing thunk with the
-- exception raised, which is wrong (#3997). We have to release the
-- lock on the Handle, but what do we replace the thunk with? What
-- should happen when the thunk is subsequently demanded again?
--
-- The only sensible choice we have is to re-do the IO operation on
-- resumption, but then we have to be careful in the IO library that
-- this is always safe to do. In particular we should
--
-- never perform any side-effects before an interruptible operation
--
-- because the interruptible operation may raise an asynchronous
-- exception, which may cause the operation and its side effects to be
-- subsequently performed again.
--
-- Re-doing the IO operation is achieved by:
-- - using throwTo to re-throw the asynchronous exception asynchronously
-- in the current thread
-- - on resumption, it will be as if throwTo returns. In that case, we
-- recursively invoke the original operation (see do_operation above).
--
-- Interruptible operations in the I/O library are:
-- - threadWaitRead/threadWaitWrite
-- - fillReadBuffer/flushWriteBuffer
-- - readTextDevice/writeTextDevice
augmentIOError :: IOException -> String -> Handle -> IOException
augmentIOError ioe@IOError{ ioe_filename = fp } fun h
= ioe { ioe_handle = Just h, ioe_location = fun, ioe_filename = filepath }
where filepath
| Just _ <- fp = fp
| otherwise = case h of
FileHandle path _ -> Just path
DuplexHandle path _ _ -> Just path
-- ---------------------------------------------------------------------------
-- Wrapper for write operations.
wantWritableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
wantWritableHandle fun h@(FileHandle _ m) act
= wantWritableHandle' fun h m act
wantWritableHandle fun h@(DuplexHandle _ _ m) act
= wantWritableHandle' fun h m act
-- we know it's not a ReadHandle or ReadWriteHandle, but we have to
-- check for ClosedHandle/SemiClosedHandle. (#4808)
wantWritableHandle'
:: String -> Handle -> MVar Handle__
-> (Handle__ -> IO a) -> IO a
wantWritableHandle' fun h m act
= withHandle_' fun h m (checkWritableHandle act)
checkWritableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a
checkWritableHandle act h_@Handle__{..}
= case haType of
ClosedHandle -> ioe_closedHandle
SemiClosedHandle -> ioe_closedHandle
ReadHandle -> ioe_notWritable
ReadWriteHandle -> do
buf <- readIORef haCharBuffer
when (not (isWriteBuffer buf)) $ do
flushCharReadBuffer h_
flushByteReadBuffer h_
buf <- readIORef haCharBuffer
writeIORef haCharBuffer buf{ bufState = WriteBuffer }
buf <- readIORef haByteBuffer
buf' <- Buffered.emptyWriteBuffer haDevice buf
writeIORef haByteBuffer buf'
act h_
_other -> act h_
-- ---------------------------------------------------------------------------
-- Wrapper for read operations.
wantReadableHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a
wantReadableHandle fun h act = withHandle fun h (checkReadableHandle act)
wantReadableHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a
wantReadableHandle_ fun h@(FileHandle _ m) act
= wantReadableHandle' fun h m act
wantReadableHandle_ fun h@(DuplexHandle _ m _) act
= wantReadableHandle' fun h m act
-- we know it's not a WriteHandle or ReadWriteHandle, but we have to
-- check for ClosedHandle/SemiClosedHandle. (#4808)
wantReadableHandle'
:: String -> Handle -> MVar Handle__
-> (Handle__ -> IO a) -> IO a
wantReadableHandle' fun h m act
= withHandle_' fun h m (checkReadableHandle act)
checkReadableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a
checkReadableHandle act h_@Handle__{..} =
case haType of
ClosedHandle -> ioe_closedHandle
SemiClosedHandle -> ioe_closedHandle
AppendHandle -> ioe_notReadable
WriteHandle -> ioe_notReadable
ReadWriteHandle -> do
-- a read/write handle and we want to read from it. We must
-- flush all buffered write data first.
bbuf <- readIORef haByteBuffer
when (isWriteBuffer bbuf) $ do
when (not (isEmptyBuffer bbuf)) $ flushByteWriteBuffer h_
cbuf' <- readIORef haCharBuffer
writeIORef haCharBuffer cbuf'{ bufState = ReadBuffer }
bbuf <- readIORef haByteBuffer
writeIORef haByteBuffer bbuf{ bufState = ReadBuffer }
act h_
_other -> act h_
-- ---------------------------------------------------------------------------
-- Wrapper for seek operations.
wantSeekableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
wantSeekableHandle fun h@(DuplexHandle _ _ _) _act =
ioException (IOError (Just h) IllegalOperation fun
"handle is not seekable" Nothing Nothing)
wantSeekableHandle fun h@(FileHandle _ m) act =
withHandle_' fun h m (checkSeekableHandle act)
checkSeekableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a
checkSeekableHandle act handle_@Handle__{haDevice=dev} =
case haType handle_ of
ClosedHandle -> ioe_closedHandle
SemiClosedHandle -> ioe_closedHandle
AppendHandle -> ioe_notSeekable
_ -> do b <- IODevice.isSeekable dev
if b then act handle_
else ioe_notSeekable
-- -----------------------------------------------------------------------------
-- Handy IOErrors
ioe_closedHandle, ioe_EOF,
ioe_notReadable, ioe_notWritable, ioe_cannotFlushNotSeekable,
ioe_notSeekable :: IO a
ioe_closedHandle = ioException
(IOError Nothing IllegalOperation ""
"handle is closed" Nothing Nothing)
ioe_EOF = ioException
(IOError Nothing EOF "" "" Nothing Nothing)
ioe_notReadable = ioException
(IOError Nothing IllegalOperation ""
"handle is not open for reading" Nothing Nothing)
ioe_notWritable = ioException
(IOError Nothing IllegalOperation ""
"handle is not open for writing" Nothing Nothing)
ioe_notSeekable = ioException
(IOError Nothing IllegalOperation ""
"handle is not seekable" Nothing Nothing)
ioe_cannotFlushNotSeekable = ioException
(IOError Nothing IllegalOperation ""
"cannot flush the read buffer: underlying device is not seekable"
Nothing Nothing)
ioe_finalizedHandle :: FilePath -> Handle__
ioe_finalizedHandle fp = throw
(IOError Nothing IllegalOperation ""
"handle is finalized" Nothing (Just fp))
ioe_bufsiz :: Int -> IO a
ioe_bufsiz n = ioException
(IOError Nothing InvalidArgument "hSetBuffering"
("illegal buffer size " ++ showsPrec 9 n []) Nothing Nothing)
-- 9 => should be parens'ified.
-- ---------------------------------------------------------------------------
-- Wrapper for Handle encoding/decoding.
-- The interface for TextEncoding changed so that a TextEncoding doesn't raise
-- an exception if it encounters an invalid sequnce. Furthermore, encoding
-- returns a reason as to why encoding stopped, letting us know if it was due
-- to input/output underflow or an invalid sequence.
--
-- This code adapts this elaborated interface back to the original TextEncoding
-- interface.
--
-- FIXME: it is possible that Handle code using the haDecoder/haEncoder fields
-- could be made clearer by using the 'encode' interface directly. I have not
-- looked into this.
streamEncode :: BufferCodec from to state
-> Buffer from -> Buffer to
-> IO (Buffer from, Buffer to)
streamEncode codec from to = fmap (\(_, from', to') -> (from', to')) $ recoveringEncode codec from to
-- | Just like 'encode', but interleaves calls to 'encode' with calls to 'recover' in order to make as much progress as possible
recoveringEncode :: BufferCodec from to state -> CodeBuffer from to
recoveringEncode codec from to = go from to
where
go from to = do
(why, from', to') <- encode codec from to
-- When we are dealing with Handles, we don't care about input/output
-- underflow particularly, and we want to delay errors about invalid
-- sequences as far as possible.
case why of
InvalidSequence | bufL from == bufL from' -> do
-- NB: it is OK to call recover here. Because we saw InvalidSequence, by the invariants
-- on "encode" it must be the case that there is at least one elements available in the output
-- buffer. Furthermore, clearly there is at least one element in the input buffer since we found
-- something invalid there!
(from', to') <- recover codec from' to'
go from' to'
_ -> return (why, from', to')
-- -----------------------------------------------------------------------------
-- Handle Finalizers
-- For a duplex handle, we arrange that the read side points to the write side
-- (and hence keeps it alive if the read side is alive). This is done by
-- having the haOtherSide field of the read side point to the read side.
-- The finalizer is then placed on the write side, and the handle only gets
-- finalized once, when both sides are no longer required.
-- NOTE about finalized handles: It's possible that a handle can be
-- finalized and then we try to use it later, for example if the
-- handle is referenced from another finalizer, or from a thread that
-- has become unreferenced and then resurrected (arguably in the
-- latter case we shouldn't finalize the Handle...). Anyway,
-- we try to emit a helpful message which is better than nothing.
--
-- [later; 8/2010] However, a program like this can yield a strange
-- error message:
--
-- main = writeFile "out" loop
-- loop = let x = x in x
--
-- because the main thread and the Handle are both unreachable at the
-- same time, the Handle may get finalized before the main thread
-- receives the NonTermination exception, and the exception handler
-- will then report an error. We'd rather this was not an error and
-- the program just prints "<<loop>>".
handleFinalizer :: FilePath -> MVar Handle__ -> IO ()
handleFinalizer fp m = do
handle_ <- takeMVar m
(handle_', _) <- hClose_help handle_
putMVar m handle_'
return ()
-- ---------------------------------------------------------------------------
-- Allocating buffers
-- using an 8k char buffer instead of 32k improved performance for a
-- basic "cat" program by ~30% for me. --SDM
dEFAULT_CHAR_BUFFER_SIZE :: Int
dEFAULT_CHAR_BUFFER_SIZE = 2048 -- 8k/sizeof(HsChar)
getCharBuffer :: IODevice dev => dev -> BufferState
-> IO (IORef CharBuffer, BufferMode)
getCharBuffer dev state = do
buffer <- newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state
ioref <- newIORef buffer
is_tty <- IODevice.isTerminal dev
let buffer_mode
| is_tty = LineBuffering
| otherwise = BlockBuffering Nothing
return (ioref, buffer_mode)
mkUnBuffer :: BufferState -> IO (IORef CharBuffer, BufferMode)
mkUnBuffer state = do
buffer <- newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state
-- See [note Buffer Sizing], GHC.IO.Handle.Types
ref <- newIORef buffer
return (ref, NoBuffering)
-- -----------------------------------------------------------------------------
-- Flushing buffers
-- | syncs the file with the buffer, including moving the
-- file pointer backwards in the case of a read buffer. This can fail
-- on a non-seekable read Handle.
flushBuffer :: Handle__ -> IO ()
flushBuffer h_@Handle__{..} = do
buf <- readIORef haCharBuffer
case bufState buf of
ReadBuffer -> do
flushCharReadBuffer h_
flushByteReadBuffer h_
WriteBuffer -> do
flushByteWriteBuffer h_
-- | flushes the Char buffer only. Works on all Handles.
flushCharBuffer :: Handle__ -> IO ()
flushCharBuffer h_@Handle__{..} = do
cbuf <- readIORef haCharBuffer
case bufState cbuf of
ReadBuffer -> do
flushCharReadBuffer h_
WriteBuffer ->
when (not (isEmptyBuffer cbuf)) $
error "internal IO library error: Char buffer non-empty"
-- -----------------------------------------------------------------------------
-- Writing data (flushing write buffers)
-- flushWriteBuffer flushes the buffer iff it contains pending write
-- data. Flushes both the Char and the byte buffer, leaving both
-- empty.
flushWriteBuffer :: Handle__ -> IO ()
flushWriteBuffer h_@Handle__{..} = do
buf <- readIORef haByteBuffer
when (isWriteBuffer buf) $ flushByteWriteBuffer h_
flushByteWriteBuffer :: Handle__ -> IO ()
flushByteWriteBuffer h_@Handle__{..} = do
bbuf <- readIORef haByteBuffer
when (not (isEmptyBuffer bbuf)) $ do
bbuf' <- Buffered.flushWriteBuffer haDevice bbuf
writeIORef haByteBuffer bbuf'
-- write the contents of the CharBuffer to the Handle__.
-- The data will be encoded and pushed to the byte buffer,
-- flushing if the buffer becomes full.
writeCharBuffer :: Handle__ -> CharBuffer -> IO ()
writeCharBuffer h_@Handle__{..} !cbuf = do
--
bbuf <- readIORef haByteBuffer
debugIO ("writeCharBuffer: cbuf=" ++ summaryBuffer cbuf ++
" bbuf=" ++ summaryBuffer bbuf)
(cbuf',bbuf') <- case haEncoder of
Nothing -> latin1_encode cbuf bbuf
Just encoder -> (streamEncode encoder) cbuf bbuf
debugIO ("writeCharBuffer after encoding: cbuf=" ++ summaryBuffer cbuf' ++
" bbuf=" ++ summaryBuffer bbuf')
-- flush if the write buffer is full
if isFullBuffer bbuf'
-- or we made no progress
|| not (isEmptyBuffer cbuf') && bufL cbuf' == bufL cbuf
-- or the byte buffer has more elements than the user wanted buffered
|| (case haBufferMode of
BlockBuffering (Just s) -> bufferElems bbuf' >= s
NoBuffering -> True
_other -> False)
then do
bbuf'' <- Buffered.flushWriteBuffer haDevice bbuf'
writeIORef haByteBuffer bbuf''
else
writeIORef haByteBuffer bbuf'
if not (isEmptyBuffer cbuf')
then writeCharBuffer h_ cbuf'
else return ()
-- -----------------------------------------------------------------------------
-- Flushing read buffers
-- It is always possible to flush the Char buffer back to the byte buffer.
flushCharReadBuffer :: Handle__ -> IO ()
flushCharReadBuffer Handle__{..} = do
cbuf <- readIORef haCharBuffer
if isWriteBuffer cbuf || isEmptyBuffer cbuf then return () else do
-- haLastDecode is the byte buffer just before we did our last batch of
-- decoding. We're going to re-decode the bytes up to the current char,
-- to find out where we should revert the byte buffer to.
(codec_state, bbuf0) <- readIORef haLastDecode
cbuf0 <- readIORef haCharBuffer
writeIORef haCharBuffer cbuf0{ bufL=0, bufR=0 }
-- if we haven't used any characters from the char buffer, then just
-- re-install the old byte buffer.
if bufL cbuf0 == 0
then do writeIORef haByteBuffer bbuf0
return ()
else do
case haDecoder of
Nothing -> do
writeIORef haByteBuffer bbuf0 { bufL = bufL bbuf0 + bufL cbuf0 }
-- no decoder: the number of bytes to decode is the same as the
-- number of chars we have used up.
Just decoder -> do
debugIO ("flushCharReadBuffer re-decode, bbuf=" ++ summaryBuffer bbuf0 ++
" cbuf=" ++ summaryBuffer cbuf0)
-- restore the codec state
setState decoder codec_state
(bbuf1,cbuf1) <- (streamEncode decoder) bbuf0
cbuf0{ bufL=0, bufR=0, bufSize = bufL cbuf0 }
debugIO ("finished, bbuf=" ++ summaryBuffer bbuf1 ++
" cbuf=" ++ summaryBuffer cbuf1)
writeIORef haByteBuffer bbuf1
-- When flushing the byte read buffer, we seek backwards by the number
-- of characters in the buffer. The file descriptor must therefore be
-- seekable: attempting to flush the read buffer on an unseekable
-- handle is not allowed.
flushByteReadBuffer :: Handle__ -> IO ()
flushByteReadBuffer h_@Handle__{..} = do
bbuf <- readIORef haByteBuffer
if isEmptyBuffer bbuf then return () else do
seekable <- IODevice.isSeekable haDevice
when (not seekable) $ ioe_cannotFlushNotSeekable
let seek = negate (bufR bbuf - bufL bbuf)
debugIO ("flushByteReadBuffer: new file offset = " ++ show seek)
IODevice.seek haDevice RelativeSeek (fromIntegral seek)
writeIORef haByteBuffer bbuf{ bufL=0, bufR=0 }
-- ----------------------------------------------------------------------------
-- Making Handles
mkHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev
-> FilePath
-> HandleType
-> Bool -- buffered?
-> Maybe TextEncoding
-> NewlineMode
-> Maybe HandleFinalizer
-> Maybe (MVar Handle__)
-> IO Handle
mkHandle dev filepath ha_type buffered mb_codec nl finalizer other_side = do
openTextEncoding mb_codec ha_type $ \ mb_encoder mb_decoder -> do
let buf_state = initBufferState ha_type
bbuf <- Buffered.newBuffer dev buf_state
bbufref <- newIORef bbuf
last_decode <- newIORef (error "codec_state", bbuf)
(cbufref,bmode) <-
if buffered then getCharBuffer dev buf_state
else mkUnBuffer buf_state
spares <- newIORef BufferListNil
newFileHandle filepath finalizer
(Handle__ { haDevice = dev,
haType = ha_type,
haBufferMode = bmode,
haByteBuffer = bbufref,
haLastDecode = last_decode,
haCharBuffer = cbufref,
haBuffers = spares,
haEncoder = mb_encoder,
haDecoder = mb_decoder,
haCodec = mb_codec,
haInputNL = inputNL nl,
haOutputNL = outputNL nl,
haOtherSide = other_side
})
-- | makes a new 'Handle'
mkFileHandle :: (IODevice dev, BufferedIO dev, Typeable dev)
=> dev -- ^ the underlying IO device, which must support
-- 'IODevice', 'BufferedIO' and 'Typeable'
-> FilePath
-- ^ a string describing the 'Handle', e.g. the file
-- path for a file. Used in error messages.
-> IOMode
-- The mode in which the 'Handle' is to be used
-> Maybe TextEncoding
-- Create the 'Handle' with no text encoding?
-> NewlineMode
-- Translate newlines?
-> IO Handle
mkFileHandle dev filepath iomode mb_codec tr_newlines = do
mkHandle dev filepath (ioModeToHandleType iomode) True{-buffered-} mb_codec
tr_newlines
(Just handleFinalizer) Nothing{-other_side-}
-- | like 'mkFileHandle', except that a 'Handle' is created with two
-- independent buffers, one for reading and one for writing. Used for
-- full-duplex streams, such as network sockets.
mkDuplexHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev
-> FilePath -> Maybe TextEncoding -> NewlineMode -> IO Handle
mkDuplexHandle dev filepath mb_codec tr_newlines = do
write_side@(FileHandle _ write_m) <-
mkHandle dev filepath WriteHandle True mb_codec
tr_newlines
(Just handleFinalizer)
Nothing -- no othersie
read_side@(FileHandle _ read_m) <-
mkHandle dev filepath ReadHandle True mb_codec
tr_newlines
Nothing -- no finalizer
(Just write_m)
return (DuplexHandle filepath read_m write_m)
ioModeToHandleType :: IOMode -> HandleType
ioModeToHandleType ReadMode = ReadHandle
ioModeToHandleType WriteMode = WriteHandle
ioModeToHandleType ReadWriteMode = ReadWriteHandle
ioModeToHandleType AppendMode = AppendHandle
initBufferState :: HandleType -> BufferState
initBufferState ReadHandle = ReadBuffer
initBufferState _ = WriteBuffer
openTextEncoding
:: Maybe TextEncoding
-> HandleType
-> (forall es ds . Maybe (TextEncoder es) -> Maybe (TextDecoder ds) -> IO a)
-> IO a
openTextEncoding Nothing ha_type cont = cont Nothing Nothing
openTextEncoding (Just TextEncoding{..}) ha_type cont = do
mb_decoder <- if isReadableHandleType ha_type then do
decoder <- mkTextDecoder
return (Just decoder)
else
return Nothing
mb_encoder <- if isWritableHandleType ha_type then do
encoder <- mkTextEncoder
return (Just encoder)
else
return Nothing
cont mb_encoder mb_decoder
closeTextCodecs :: Handle__ -> IO ()
closeTextCodecs Handle__{..} = do
case haDecoder of Nothing -> return (); Just d -> Encoding.close d
case haEncoder of Nothing -> return (); Just d -> Encoding.close d
-- ---------------------------------------------------------------------------
-- closing Handles
-- hClose_help is also called by lazyRead (in GHC.IO.Handle.Text) when
-- EOF is read or an IO error occurs on a lazy stream. The
-- semi-closed Handle is then closed immediately. We have to be
-- careful with DuplexHandles though: we have to leave the closing to
-- the finalizer in that case, because the write side may still be in
-- use.
hClose_help :: Handle__ -> IO (Handle__, Maybe SomeException)
hClose_help handle_ =
case haType handle_ of
ClosedHandle -> return (handle_,Nothing)
_ -> do mb_exc1 <- trymaybe $ flushWriteBuffer handle_ -- interruptible
-- it is important that hClose doesn't fail and
-- leave the Handle open (#3128), so we catch
-- exceptions when flushing the buffer.
(h_, mb_exc2) <- hClose_handle_ handle_
return (h_, if isJust mb_exc1 then mb_exc1 else mb_exc2)
trymaybe :: IO () -> IO (Maybe SomeException)
trymaybe io = (do io; return Nothing) `catchException` \e -> return (Just e)
hClose_handle_ :: Handle__ -> IO (Handle__, Maybe SomeException)
hClose_handle_ h_@Handle__{..} = do
-- close the file descriptor, but not when this is the read
-- side of a duplex handle.
-- If an exception is raised by the close(), we want to continue
-- to close the handle and release the lock if it has one, then
-- we return the exception to the caller of hClose_help which can
-- raise it if necessary.
maybe_exception <-
case haOtherSide of
Nothing -> trymaybe $ IODevice.close haDevice
Just _ -> return Nothing
-- free the spare buffers
writeIORef haBuffers BufferListNil
writeIORef haCharBuffer noCharBuffer
writeIORef haByteBuffer noByteBuffer
-- release our encoder/decoder
closeTextCodecs h_
-- we must set the fd to -1, because the finalizer is going
-- to run eventually and try to close/unlock it.
-- ToDo: necessary? the handle will be marked ClosedHandle
-- XXX GHC won't let us use record update here, hence wildcards
return (Handle__{ haType = ClosedHandle, .. }, maybe_exception)
{-# NOINLINE noCharBuffer #-}
noCharBuffer :: CharBuffer
noCharBuffer = unsafePerformIO $ newCharBuffer 1 ReadBuffer
{-# NOINLINE noByteBuffer #-}
noByteBuffer :: Buffer Word8
noByteBuffer = unsafePerformIO $ newByteBuffer 1 ReadBuffer
-- ---------------------------------------------------------------------------
-- Looking ahead
hLookAhead_ :: Handle__ -> IO Char
hLookAhead_ handle_@Handle__{..} = do
buf <- readIORef haCharBuffer
-- fill up the read buffer if necessary
new_buf <- if isEmptyBuffer buf
then readTextDevice handle_ buf
else return buf
writeIORef haCharBuffer new_buf
peekCharBuf (bufRaw buf) (bufL buf)
-- ---------------------------------------------------------------------------
-- debugging
debugIO :: String -> IO ()
debugIO s
| c_DEBUG_DUMP
= do _ <- withCStringLen (s ++ "\n") $
\(p, len) -> c_write 1 (castPtr p) (fromIntegral len)
return ()
| otherwise = return ()
-- ----------------------------------------------------------------------------
-- Text input/output
-- Read characters into the provided buffer. Return when any
-- characters are available; raise an exception if the end of
-- file is reached.
--
-- In uses of readTextDevice within base, the input buffer is either:
-- * empty
-- * or contains a single \r (when doing newline translation)
--
-- The input character buffer must have a capacity at least 1 greater
-- than the number of elements it currently contains.
--
-- Users of this function expect that the buffer returned contains
-- at least 1 more character than the input buffer.
readTextDevice :: Handle__ -> CharBuffer -> IO CharBuffer
readTextDevice h_@Handle__{..} cbuf = do
--
bbuf0 <- readIORef haByteBuffer
debugIO ("readTextDevice: cbuf=" ++ summaryBuffer cbuf ++
" bbuf=" ++ summaryBuffer bbuf0)
bbuf1 <- if not (isEmptyBuffer bbuf0)
then return bbuf0
else do
(r,bbuf1) <- Buffered.fillReadBuffer haDevice bbuf0
if r == 0 then ioe_EOF else do -- raise EOF
return bbuf1
debugIO ("readTextDevice after reading: bbuf=" ++ summaryBuffer bbuf1)
(bbuf2,cbuf') <-
case haDecoder of
Nothing -> do
writeIORef haLastDecode (error "codec_state", bbuf1)
latin1_decode bbuf1 cbuf
Just decoder -> do
state <- getState decoder
writeIORef haLastDecode (state, bbuf1)
(streamEncode decoder) bbuf1 cbuf
debugIO ("readTextDevice after decoding: cbuf=" ++ summaryBuffer cbuf' ++
" bbuf=" ++ summaryBuffer bbuf2)
-- We can't return from readTextDevice without reading at least a single extra character,
-- so check that we have managed to achieve that
writeIORef haByteBuffer bbuf2
if bufR cbuf' == bufR cbuf
-- we need more bytes to make a Char. NB: bbuf2 may be empty (even though bbuf1 wasn't) when we
-- are using an encoding that can skip bytes without outputting characters, such as UTF8//IGNORE
then readTextDevice' h_ bbuf2 cbuf
else return cbuf'
-- we have an incomplete byte sequence at the end of the buffer: try to
-- read more bytes.
readTextDevice' :: Handle__ -> Buffer Word8 -> CharBuffer -> IO CharBuffer
readTextDevice' h_@Handle__{..} bbuf0 cbuf0 = do
--
-- copy the partial sequence to the beginning of the buffer, so we have
-- room to read more bytes.
bbuf1 <- slideContents bbuf0
-- readTextDevice only calls us if we got some bytes but not some characters.
-- This can't occur if haDecoder is Nothing because latin1_decode accepts all bytes.
let Just decoder = haDecoder
(r,bbuf2) <- Buffered.fillReadBuffer haDevice bbuf1
if r == 0
then do
-- bbuf2 can be empty here when we encounter an invalid byte sequence at the end of the input
-- with a //IGNORE codec which consumes bytes without outputting characters
if isEmptyBuffer bbuf2 then ioe_EOF else do
(bbuf3, cbuf1) <- recover decoder bbuf2 cbuf0
debugIO ("readTextDevice' after recovery: bbuf=" ++ summaryBuffer bbuf3 ++ ", cbuf=" ++ summaryBuffer cbuf1)
writeIORef haByteBuffer bbuf3
-- We should recursively invoke readTextDevice after recovery,
-- if recovery did not add at least one new character to the buffer:
-- 1. If we were using IgnoreCodingFailure it might be the case that
-- cbuf1 is the same length as cbuf0 and we need to raise ioe_EOF
-- 2. If we were using TransliterateCodingFailure we might have *mutated*
-- the byte buffer without changing the pointers into either buffer.
-- We need to try and decode it again - it might just go through this time.
if bufR cbuf1 == bufR cbuf0
then readTextDevice h_ cbuf1
else return cbuf1
else do
debugIO ("readTextDevice' after reading: bbuf=" ++ summaryBuffer bbuf2)
(bbuf3,cbuf1) <- do
state <- getState decoder
writeIORef haLastDecode (state, bbuf2)
(streamEncode decoder) bbuf2 cbuf0
debugIO ("readTextDevice' after decoding: cbuf=" ++ summaryBuffer cbuf1 ++
" bbuf=" ++ summaryBuffer bbuf3)
writeIORef haByteBuffer bbuf3
if bufR cbuf0 == bufR cbuf1
then readTextDevice' h_ bbuf3 cbuf1
else return cbuf1
-- Read characters into the provided buffer. Do not block;
-- return zero characters instead. Raises an exception on end-of-file.
readTextDeviceNonBlocking :: Handle__ -> CharBuffer -> IO CharBuffer
readTextDeviceNonBlocking h_@Handle__{..} cbuf = do
--
bbuf0 <- readIORef haByteBuffer
when (isEmptyBuffer bbuf0) $ do
(r,bbuf1) <- Buffered.fillReadBuffer0 haDevice bbuf0
if isNothing r then ioe_EOF else do -- raise EOF
writeIORef haByteBuffer bbuf1
decodeByteBuf h_ cbuf
-- Decode bytes from the byte buffer into the supplied CharBuffer.
decodeByteBuf :: Handle__ -> CharBuffer -> IO CharBuffer
decodeByteBuf h_@Handle__{..} cbuf = do
--
bbuf0 <- readIORef haByteBuffer
(bbuf2,cbuf') <-
case haDecoder of
Nothing -> do
writeIORef haLastDecode (error "codec_state", bbuf0)
latin1_decode bbuf0 cbuf
Just decoder -> do
state <- getState decoder
writeIORef haLastDecode (state, bbuf0)
(streamEncode decoder) bbuf0 cbuf
writeIORef haByteBuffer bbuf2
return cbuf'
| frantisekfarka/ghc-dsi | libraries/base/GHC/IO/Handle/Internals.hs | bsd-3-clause | 35,776 | 0 | 23 | 8,646 | 6,855 | 3,469 | 3,386 | 543 | 6 |
{-# LANGUAGE TypeOperators #-}
module Language.LSP.Server
( module Language.LSP.Server.Control
, VFSData(..)
, ServerDefinition(..)
-- * Handlers
, Handlers(..)
, Handler
, transmuteHandlers
, mapHandlers
, notificationHandler
, requestHandler
, ClientMessageHandler(..)
, Options(..)
, defaultOptions
-- * LspT and LspM
, LspT(..)
, LspM
, MonadLsp(..)
, runLspT
, LanguageContextEnv(..)
, type (<~>)(..)
, getClientCapabilities
, getConfig
, getRootPath
, getWorkspaceFolders
, sendRequest
, sendNotification
-- * VFS
, getVirtualFile
, getVirtualFiles
, persistVirtualFile
, getVersionedTextDoc
, reverseFileMap
, snapshotVirtualFiles
-- * Diagnostics
, publishDiagnostics
, flushDiagnosticsBySource
-- * Progress
, withProgress
, withIndefiniteProgress
, ProgressAmount(..)
, ProgressCancellable(..)
, ProgressCancelledException
-- * Dynamic registration
, registerCapability
, unregisterCapability
, RegistrationToken
, setupLogger
, reverseSortEdit
) where
import Language.LSP.Server.Control
import Language.LSP.Server.Core
| wz1000/haskell-lsp | lsp/src/Language/LSP/Server.hs | mit | 1,139 | 0 | 5 | 228 | 209 | 147 | 62 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module Data.Modable.Tests where
import Data.Maybe (isNothing)
import Data.Modable
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
testModable :: forall a b.
( Eq a, Show a, Arbitrary a
, Eq (Relative a), Show (Relative a), Arbitrary (Relative a)
, Relative a ~ Maybe b
, Modable a
) => a -> Test
testModable _ = testGroup "maybe math"
[ testProperty "plus→minus" (\(a::a) (b::Relative a) ->
minus (plus a b) b == a)
, testProperty "minus→plus" (\(a::a) (b::Relative a) ->
plus (minus a b) b == a)
, testProperty "clobber" (\(a::a) (b::Relative a) ->
if isNothing b
then clobber a b == a
else clobber a b `like` b)
, testProperty "absify relify" (\(a::a) -> absify (relify a) == Just a)
, testProperty "like" (\(a::a) -> a `like` relify a)
]
| Soares/Dater.hs | test/Data/Modable/Tests.hs | mit | 980 | 0 | 13 | 233 | 388 | 208 | 180 | 26 | 2 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module HttpApp.BotKey.Api.Types where
import Data.Aeson (FromJSON, ToJSON)
import GHC.Generics (Generic)
import HttpApp.BotKey.Types (BotKey, Label, Secret)
data BKNewResp = BKNewResp
{ _nrespBotKey :: BotKey
} deriving (Generic, ToJSON)
data BKAllResp = BKAllResp
{ _arespBotKeys :: [BotKey]
} deriving (Generic, ToJSON)
data BKSetLabelRq = BKSetLabelRq
{ _slrqSecret :: Secret
, _slrqLabel :: Label
} deriving (Generic, FromJSON)
data BKSetLabelResp = BKSetLabelResp
{ _slrespLabel :: Label
} deriving (Generic, ToJSON)
data BKDeleteRq = BKDeleteRq
{ _drqSecret :: Secret
} deriving (Generic, FromJSON)
| rubenmoor/skull | skull-server/src/HttpApp/BotKey/Api/Types.hs | mit | 749 | 0 | 9 | 168 | 189 | 114 | 75 | 22 | 0 |
module Main.DB
(
session,
oneRow,
unit,
integerDatetimes,
serverVersion,
)
where
import Main.Prelude hiding (unit)
import Control.Monad.Trans.Reader
import Control.Monad.IO.Class
import qualified Database.PostgreSQL.LibPQ as LibPQ
import qualified Data.ByteString as ByteString; import Data.ByteString (ByteString)
type Session =
ExceptT ByteString (ReaderT LibPQ.Connection IO)
session :: Session a -> IO (Either ByteString a)
session m =
do
c <- connect
initConnection c
r <- runReaderT (runExceptT m) c
LibPQ.finish c
return r
oneRow :: ByteString -> [Maybe (LibPQ.Oid, ByteString, LibPQ.Format)] -> LibPQ.Format -> Session ByteString
oneRow statement params outFormat =
do
Just result <- result statement params outFormat
Just result <- liftIO $ LibPQ.getvalue result 0 0
return result
unit :: ByteString -> [Maybe (LibPQ.Oid, ByteString, LibPQ.Format)] -> Session ()
unit statement params =
void $ result statement params LibPQ.Binary
result :: ByteString -> [Maybe (LibPQ.Oid, ByteString, LibPQ.Format)] -> LibPQ.Format -> Session (Maybe LibPQ.Result)
result statement params outFormat =
do
result <- ExceptT $ ReaderT $ \connection -> fmap Right $ LibPQ.execParams connection statement params outFormat
checkResult result
return result
checkResult :: Maybe LibPQ.Result -> Session ()
checkResult result =
ExceptT $ ReaderT $ \connection -> do
case result of
Just result -> do
LibPQ.resultErrorField result LibPQ.DiagMessagePrimary >>= maybe (return (Right ())) (return . Left)
Nothing -> do
m <- LibPQ.errorMessage connection
return $ Left $ maybe "Fatal PQ error" (\m -> "Fatal PQ error: " <> m) m
integerDatetimes :: Session Bool
integerDatetimes =
lift (ReaderT getIntegerDatetimes)
serverVersion :: Session Int
serverVersion =
lift (ReaderT LibPQ.serverVersion)
-- *
-------------------------
connect :: IO LibPQ.Connection
connect =
LibPQ.connectdb bs
where
bs =
ByteString.intercalate " " components
where
components =
[
"host=" <> host,
"port=" <> (fromString . show) port,
"user=" <> user,
"password=" <> password,
"dbname=" <> db
]
where
host = "localhost"
port = 5432
user = "postgres"
password = ""
db = "postgres"
initConnection :: LibPQ.Connection -> IO ()
initConnection c =
void $ LibPQ.exec c $ mconcat $ map (<> ";") $
[
"SET client_min_messages TO WARNING",
"SET client_encoding = 'UTF8'",
"SET intervalstyle = 'postgres'"
]
getIntegerDatetimes :: LibPQ.Connection -> IO Bool
getIntegerDatetimes c =
fmap parseResult $ LibPQ.parameterStatus c "integer_datetimes"
where
parseResult =
\case
Just "on" -> True
_ -> False
| nikita-volkov/postgresql-binary | tasty/Main/DB.hs | mit | 2,908 | 0 | 20 | 724 | 872 | 447 | 425 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Entry point to the Post Correspondence Programming Language
module Language.PCPL
( module Language.PCPL.Syntax
, module Language.PCPL.Pretty
, module Language.PCPL.CompileTM
-- * Execute PCPL programs
, runProgram
-- * Utility
, topString
-- * Examples
, unaryAdder
, parensMatcher
) where
import qualified Data.Map as Map
import Language.UTM.Syntax
import Language.PCPL.Syntax
import Language.PCPL.Pretty
import Language.PCPL.Solver
import Language.PCPL.CompileTM
-- | Run a PCPL program on the given input, producing a PCP match.
runProgram :: Program -> Input -> [Domino]
runProgram pgm w = map (dss !!) indices
where
dss@(d : ds) = (startDomino pgm w) : dominos pgm
Just initialConfig = updateConf (Top []) d
indices = reverse $ search (zip [1..] ds) [Node [0] initialConfig]
-- | Return the string across the top of a list of Dominos.
-- Useful after finding a match.
topString :: [Domino] -> String
topString ds = concat [ s | Domino xs _ <- ds, Symbol s <- xs]
-- | Turing machine that adds unary numbers.
-- For example: @1+11@ becomes @111@.
unaryAdder :: TuringMachine
unaryAdder = TuringMachine
{ startState = "x"
, acceptState = "a"
, rejectState = "reject"
, blankSymbol = "_"
, inputAlphabet = ["1", "+"]
, transitionFunction = Map.fromList
[ (("x", "1"), ("x", "1", R))
, (("x", "+"), ("y", "1", R))
, (("y", "1"), ("y", "1", R))
, (("y", "_"), ("z", "_", L))
, (("z", "1"), ("a", "_", R))
, (("z", "+"), ("a", "_", R))
]
}
-- | Turing machine that accepts strings of balanced parentheses.
-- Note: due to the restrictions described in 'compileTM', the input must
-- start with a @$@ symbol. For example: the input @$(())()@ is accepted.
-- This Turing machine is based on:
-- <http://www2.lns.mit.edu/~dsw/turing/examples/paren.tm>.
parensMatcher :: TuringMachine
parensMatcher = TuringMachine
{ startState = "S"
, acceptState = "Y"
, rejectState = "N"
, blankSymbol = "_"
, inputAlphabet = syms "$()A"
, transitionFunction = Map.fromList
[ (("S", "$"), ("0", "$", R))
, (("0", "("), ("0", "(", R))
, (("0", ")"), ("1", "A", L))
, (("0", "A"), ("0", "A", R))
, (("0", "_"), ("2", "_", L))
, (("1", "("), ("0", "A", R))
, (("1", "A"), ("1", "A", L))
, (("2", "A"), ("2", "A", L))
, (("2", "$"), ("Y", "$", R))
]
}
| davidlazar/PCPL | src/Language/PCPL.hs | mit | 2,530 | 0 | 11 | 634 | 745 | 470 | 275 | 53 | 1 |
module Ch2 where
import Test.QuickCheck
import Test.Hspec
ch2 :: IO ()
ch2 = hspec $ do
describe "_______________________Chapter 2 tests_______________________" $ do
it "should have tests" $ do
True
| Kiandr/CrackingCodingInterview | Haskell/src/chapter-2/Ch2.hs | mit | 214 | 0 | 13 | 44 | 56 | 28 | 28 | 8 | 1 |
{-# OPTIONS_HADDOCK show-extensions #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-|
Module : Data.Nat.Peano
Description : Peano natural numbers
Copyright : (c) Lars Brünjes, 2016
License : MIT
Maintainer : brunjlar@gmail.com
Stability : experimental
Portability : portable
Defines Peano natural numbers, i.e. natural numbers with unary representation.
They are far less efficient than binary natural numbers, but much easier to reason about.
-}
module Data.Nat.Peano
( Peano(..)
) where
import Data.Constraint
import Data.Logic
import Data.Ordered
-- | Peano natural numbers: @Z = 0@, @S Z = 1@, @S S Z = 2@ and so on.
data Peano =
Z -- ^ zero
| S !Peano -- ^ successor
deriving (Show, Read, Eq)
infix 4 ???
type family (m :: Peano) ??? (n :: Peano) :: Ordering where
'Z ??? 'Z = 'EQ
'Z ??? _ = 'LT
'S _ ??? 'Z = 'GT
'S m ??? 'S n = m ??? n
instance Ordered Peano where
type m ?? n = m ??? n
data Sing Peano n where
SZ :: Sing Peano 'Z
SS :: Sing Peano n -> Sing Peano ('S n)
dec SZ SZ = DecEQ Dict
dec SZ (SS _) = DecLT Dict
dec (SS _) SZ = DecGT Dict
dec (SS m) (SS n) = case dec m n of
DecLT Dict -> DecLT Dict
DecEQ Dict -> DecEQ Dict
DecGT Dict -> DecGT Dict
{-# INLINE dec #-}
symm SZ SZ = Dict
symm SZ (SS _) = Dict
symm (SS _) SZ = Dict
symm (SS m) (SS n) = using (symm m n) Dict
{-# INLINE symm #-}
eqSame SZ SZ = Dict
eqSame (SS m) (SS n) = using (eqSame m n) Dict
{-# INLINE eqSame #-}
instance Nat Peano where
type Zero Peano = 'Z
type Succ Peano n = 'S n
zero = SZ
{-# INLINE zero #-}
succ' = SS
{-# INLINE succ' #-}
toSING 0 = SING SZ
toSING n = case toSING (pred n) of
SING n' -> SING (SS n')
{-# INLINE toSING #-}
toNatural SZ = 0
toNatural (SS n) = succ $ toNatural n
{-# INLINE toNatural #-}
| brunjlar/heap | src/Data/Nat/Peano.hs | mit | 2,067 | 32 | 10 | 650 | 603 | 315 | 288 | 57 | 0 |
{-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances #-}
{-| This library provides a collection of monad transformers that
can be combined to produce various monads.
-}
module MonadLibMorph (
-- * Types
-- $Types
Id, Lift, ReaderT, WriterT, StateT, ExceptionT, ContT,
-- * Lifting
-- $Lifting
MonadT(..), BaseM(..),
-- * Effect Classes
-- $Effects
ReaderM(..), WriterM(..), StateM(..), ExceptionM(..), ContM(..),
Label, labelCC, jump,
-- * Execution
-- ** Eliminating Effects
-- $Execution
runId, runLift, runReaderT, runWriterT, runStateT, runExceptionT, runContT,
-- ** Nested Execution
-- $Nested_Exec
RunReaderM(..), RunWriterM(..), RunStateM(..), RunExceptionM(..),
-- * Miscellaneous
version,
module Control.Monad
) where
import Control.Monad
import Control.Monad.Fix
import Data.Monoid
-- | The current version of the library.
version :: (Int,Int,Int)
version = (3,1,0)
-- $Types
--
-- The following types define the representations of the
-- computation types supported by the library.
-- Each type adds support for a different effect.
-- | Computations with no effects.
newtype Id a = I a
-- | Computation with no effects (stritc).
data Lift a = L a
-- | Add support for propagating a context.
newtype ReaderT i m a = R (i -> m a)
-- | Add support for collecting values.
newtype WriterT i m a = W (m (a,i))
-- | Add support for threading state.
newtype StateT i m a = S (i -> m (a,i))
-- | Add support for exceptions.
newtype ExceptionT i m a = X (m (Either i a))
-- | Add support for jumps.
newtype ContT i m a = C ((a -> m i) -> m i)
-- $Execution
--
-- The following functions eliminate the outermost effect
-- of a computation by translating a computation into an
-- equivalent computation in the underlying monad.
-- (The exception is 'Id' which is not a monad transformer
-- but an ordinary monad, and so, its run operation simply
-- eliminates the monad.)
-- | Get the result of a pure computation.
runId :: Id a -> a
runId (I a) = a
-- | Get the result of a pure strict computation.
runLift :: Lift a -> a
runLift (L a) = a
-- | Execute a reader computation in the given context.
runReaderT :: i -> ReaderT i m a -> m a
runReaderT i (R m) = m i
-- | Execute a writer computation.
-- Returns the result and the collected output.
runWriterT :: WriterT i m a -> m (a,i)
runWriterT (W m) = m
-- | Execute a stateful computation in the given initial state.
-- The second component of the result is the final state.
runStateT :: i -> StateT i m a -> m (a,i)
runStateT i (S m) = m i
-- | Execute a computation with exceptions.
-- Successful results are tagged with 'Right',
-- exceptional results are tagged with 'Left'.
runExceptionT :: ExceptionT i m a -> m (Either i a)
runExceptionT (X m) = m
-- | Execute a computation with the given continuation.
runContT :: (a -> m i) -> ContT i m a -> m i
runContT i (C m) = m i
-- $Lifting
--
-- The following operations allow us to promote computations
-- in the underlying monad to computations that support an extra
-- effect. Computations defined in this way do not make use of
-- the new effect but can be combined with other operations that
-- utilize the effect.
class MonadT t where
-- | Promote a computation from the underlying monad.
lift :: (Monad m) => m a -> t m a
-- It is interesting to note that these use something the resembles
-- the non-transformer 'return's.
instance MonadT (ReaderT i) where lift m = R (\_ -> m)
instance MonadT (StateT i) where lift m = S (\s -> liftM (\a -> (a,s)) m)
instance (Monoid i) =>
MonadT (WriterT i) where lift m = W (liftM (\a -> (a,mempty)) m)
instance MonadT (ExceptionT i) where lift m = X (liftM Right m)
instance MonadT (ContT i) where lift m = C (m >>=)
class (Monad m, Monad n) => BaseM m n | m -> n where
-- | Promote a computation from the base monad.
inBase :: n a -> m a
instance BaseM IO IO where inBase = id
instance BaseM Maybe Maybe where inBase = id
instance BaseM [] [] where inBase = id
instance BaseM Id Id where inBase = id
instance BaseM Lift Lift where inBase = id
instance (BaseM m n) => BaseM (ReaderT i m) n where inBase = lift . inBase
instance (BaseM m n) => BaseM (StateT i m) n where inBase = lift . inBase
instance (BaseM m n,Monoid i) => BaseM (WriterT i m) n where inBase = lift . inBase
instance (BaseM m n) => BaseM (ExceptionT i m) n where inBase = lift . inBase
instance (BaseM m n) => BaseM (ContT i m) n where inBase = lift . inBase
instance Monad Id where
return x = I x
fail x = error x
m >>= k = k (runId m)
instance Monad Lift where
return x = L x
fail x = error x
L x >>= k = k x
-- For the monad transformers, the definition of 'return'
-- is completely determined by the 'lift' operations.
-- None of the transformers make essential use of the 'fail' method.
-- Instead they delegate its behavior to the underlying monad.
instance (Monad m) => Monad (ReaderT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = R $ \r -> runReaderT r m >>= \a ->
runReaderT r (k a)
instance (Monad m) => Monad (StateT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = S $ \s -> runStateT s m >>= \ ~(a,s') ->
runStateT s' (k a)
instance (Monad m,Monoid i) => Monad (WriterT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = W $ runWriterT m >>= \ ~(a,w1) ->
runWriterT (k a) >>= \ ~(b,w2) ->
return (b,mappend w1 w2)
instance (Monad m) => Monad (ExceptionT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = X $ runExceptionT m >>= \a ->
case a of
Left x -> return (Left x)
Right a -> runExceptionT (k a)
instance (Monad m) => Monad (ContT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = C $ \c -> runContT (\a -> runContT c (k a)) m
instance Functor Id where fmap = liftM
instance Functor Lift where fmap = liftM
instance (Monad m) => Functor (ReaderT i m) where fmap = liftM
instance (Monad m) => Functor (StateT i m) where fmap = liftM
instance (Monad m,Monoid i) => Functor (WriterT i m) where fmap = liftM
instance (Monad m) => Functor (ExceptionT i m) where fmap = liftM
instance (Monad m) => Functor (ContT i m) where fmap = liftM
-- $Monadic_Value_Recursion
--
-- Recursion that does not duplicate side-effects.
-- For details see Levent Erkok's dissertation.
--
-- Monadic types built with 'ContT' do not support
-- monadic value recursion.
instance MonadFix Id where
mfix f = let m = f (runId m) in m
instance MonadFix Lift where
mfix f = let m = f (runLift m) in m
instance (MonadFix m) => MonadFix (ReaderT i m) where
mfix f = R $ \r -> mfix (runReaderT r . f)
instance (MonadFix m) => MonadFix (StateT i m) where
mfix f = S $ \s -> mfix (runStateT s . f . fst)
instance (MonadFix m,Monoid i) => MonadFix (WriterT i m) where
mfix f = W $ mfix (runWriterT . f . fst)
instance (MonadFix m) => MonadFix (ExceptionT i m) where
mfix f = X $ mfix (runExceptionT . f . fromRight)
where fromRight (Right a) = a
fromRight _ = error "ExceptionT: mfix looped."
instance (MonadPlus m) => MonadPlus (ReaderT i m) where
mzero = lift mzero
mplus (R m) (R n) = R (\r -> mplus (m r) (n r))
instance (MonadPlus m) => MonadPlus (StateT i m) where
mzero = lift mzero
mplus (S m) (S n) = S (\s -> mplus (m s) (n s))
instance (MonadPlus m,Monoid i) => MonadPlus (WriterT i m) where
mzero = lift mzero
mplus (W m) (W n) = W (mplus m n)
instance (MonadPlus m) => MonadPlus (ExceptionT i m) where
mzero = lift mzero
mplus (X m) (X n) = X (mplus m n)
-- $Effects
--
-- The following classes define overloaded operations
-- that can be used to define effectful computations.
-- | Classifies monads that provide access to a context of type @i@.
class (Monad m) => ReaderM m i | m -> i where
-- | Get the context.
ask :: m i
instance (Monad m) => ReaderM (ReaderT i m) i where
ask = R return
instance (ReaderM m j,Monoid i)
=> ReaderM (WriterT i m) j where ask = lift ask
instance (ReaderM m j) => ReaderM (StateT i m) j where ask = lift ask
instance (ReaderM m j) => ReaderM (ExceptionT i m) j where ask = lift ask
instance (ReaderM m j) => ReaderM (ContT i m) j where ask = lift ask
-- | Classifies monads that can collect values of type @i@.
class (Monad m) => WriterM m i | m -> i where
-- | Add a value to the collection.
put :: i -> m ()
instance (Monad m,Monoid i) => WriterM (WriterT i m) i where
put x = W (return ((),x))
instance (WriterM m j) => WriterM (ReaderT i m) j where put = lift . put
instance (WriterM m j) => WriterM (StateT i m) j where put = lift . put
instance (WriterM m j) => WriterM (ExceptionT i m) j where put = lift . put
instance (WriterM m j) => WriterM (ContT i m) j where put = lift . put
-- | Classifies monads that propagate a state component of type @i@.
class (Monad m) => StateM m i | m -> i where
-- | Get the state.
get :: m i
-- | Set the state.
set :: i -> m ()
instance (Monad m) => StateM (StateT i m) i where
get = S (\s -> return (s,s))
set s = S (\_ -> return ((),s))
instance (StateM m j) => StateM (ReaderT i m) j where
get = lift get
set = lift . set
instance (StateM m j,Monoid i) => StateM (WriterT i m) j where
get = lift get
set = lift . set
instance (StateM m j) => StateM (ExceptionT i m) j where
get = lift get
set = lift . set
instance (StateM m j) => StateM (ContT i m) j where
get = lift get
set = lift . set
-- | Classifies monads that support raising exceptions of type @i@.
class (Monad m) => ExceptionM m i | m -> i where
-- | Raise an exception.
raise :: i -> m a
instance (Monad m) => ExceptionM (ExceptionT i m) i where
raise x = X (return (Left x))
instance (ExceptionM m j) => ExceptionM (ReaderT i m) j where
raise = lift . raise
instance (ExceptionM m j,Monoid i) => ExceptionM (WriterT i m) j where
raise = lift . raise
instance (ExceptionM m j) => ExceptionM (StateT i m) j where
raise = lift . raise
instance (ExceptionM m j) => ExceptionM (ContT i m) j where
raise = lift . raise
-- The following instances differ from the others because the
-- liftings are not as uniform (although they certainly follow a pattern).
-- | Classifies monads that provide access to a computation's continuation.
class Monad m => ContM m where
-- | Capture the current continuation.
callCC :: ((a -> m b) -> m a) -> m a
instance (ContM m) => ContM (ReaderT i m) where
callCC f = R $ \r -> callCC $ \k -> runReaderT r $ f $ \a -> lift $ k a
instance (ContM m) => ContM (StateT i m) where
callCC f = S $ \s -> callCC $ \k -> runStateT s $ f $ \a -> lift $ k (a,s)
instance (ContM m,Monoid i) => ContM (WriterT i m) where
callCC f = W $ callCC $ \k -> runWriterT $ f $ \a -> lift $ k (a,mempty)
instance (ContM m) => ContM (ExceptionT i m) where
callCC f = X $ callCC $ \k -> runExceptionT $ f $ \a -> lift $ k $ Right a
instance (Monad m) => ContM (ContT i m) where
callCC f = C $ \k -> runContT k $ f $ \a -> C $ \_ -> k a
-- $Nested_Exec
--
-- The following classes define operations that are overloaded
-- versions of the @run@ operations. Unlike the @run@ operations,
-- functions do not change the type of the computation (i.e, they
-- do not remove a layer). However, they do not perform any
-- side-effects in the corresponding layer. Instead, they execute
-- a computation in a ``separate thread'' with respect to the
-- corresponding effect.
-- | Classifies monads that support changing the context for a
-- sub-computation.
class (ReaderM m i) => RunReaderM m i | m -> i where
-- | Change the context for the duration of a computation.
local :: i -> m a -> m a
instance (Monad m) => RunReaderM (ReaderT i m) i where
local i m = lift (runReaderT i m)
instance (RunReaderM m j,Monoid i) => RunReaderM (WriterT i m) j where
local i (W m) = W (local i m)
instance (RunReaderM m j) => RunReaderM (StateT i m) j where
local i (S m) = S (local i . m)
instance (RunReaderM m j) => RunReaderM (ExceptionT i m) j where
local i (X m) = X (local i m)
-- | Classifies monads that support collecting the output of
-- a sub-computation.
class WriterM m i => RunWriterM m i | m -> i where
-- | Collect the output from a computation.
collect :: m a -> m (a,i)
instance (RunWriterM m j) => RunWriterM (ReaderT i m) j where
collect (R m) = R (collect . m)
instance (Monad m,Monoid i) => RunWriterM (WriterT i m) i where
collect (W m) = lift m
instance (RunWriterM m j) => RunWriterM (StateT i m) j where
collect (S m) = S (liftM swap . collect . m)
where swap (~(a,s),w) = ((a,w),s)
instance (RunWriterM m j) => RunWriterM (ExceptionT i m) j where
collect (X m) = X (liftM swap (collect m))
where swap (Right a,w) = Right (a,w)
swap (Left x,_) = Left x
-- NOTE: If the local computation fails, then the output
-- is discarded because the result type cannot accommodate it.
-- | Classifies monads that support separate state threads.
class (StateM m i) => RunStateM m i | m -> i where
-- | Modify the state for the duration of a computation.
-- Returns the final state.
runS :: i -> m a -> m (a,i)
instance (RunStateM m j) => RunStateM (ReaderT i m) j where
runS s (R m) = R (runS s . m)
instance (RunStateM m j,Monoid i) => RunStateM (WriterT i m) j where
runS s (W m) = W (liftM swap (runS s m))
where swap (~(a,s),w) = ((a,w),s)
instance (Monad m) => RunStateM (StateT i m) i where
runS s m = lift (runStateT s m)
instance (RunStateM m j) => RunStateM (ExceptionT i m) j where
runS s (X m) = X (liftM swap (runS s m))
where swap (Left e,_) = Left e
swap (Right a,s) = Right (a,s)
-- NOTE: If the local computation fails, then the modifications
-- are discarded because the result type cannot accommodate it.
-- | Classifies monads that support handling of exceptions.
class ExceptionM m i => RunExceptionM m i | m -> i where
-- | Exceptions are explicit in the result.
try :: m a -> m (Either i a)
instance (RunExceptionM m i) => RunExceptionM (ReaderT j m) i where
try (R m) = R (try . m)
instance (RunExceptionM m i,Monoid j) => RunExceptionM (WriterT j m) i where
try (W m) = W (liftM swap (try m))
where swap (Right ~(a,w)) = (Right a,w)
swap (Left e) = (Left e, mempty)
instance (RunExceptionM m i) => RunExceptionM (StateT j m) i where
try (S m) = S (\s -> liftM (swap s) (try (m s)))
where swap _ (Right ~(a,s)) = (Right a,s)
swap s (Left e) = (Left e, s)
instance (Monad m) => RunExceptionM (ExceptionT i m) i where
try m = lift (runExceptionT m)
-- Some convenient functions for working with continuations.
-- | An explicit representation for continuations that store a value.
newtype Label m a = Lab ((a, Label m a) -> m ())
-- | Capture the current continuation.
-- This function is like 'return', except that it also captures
-- the current continuation. Later we can use 'jump' to go back to
-- the continuation with a possibly different value.
labelCC :: (ContM m) => a -> m (a, Label m a)
labelCC x = callCC (\k -> return (x, Lab k))
-- | Change the value passed to a previously captured continuation.
jump :: (ContM m) => a -> Label m a -> m b
jump x (Lab k) = k (x, Lab k) >> return unreachable
where unreachable = error "(bug) jump: unreachable"
newtype Morph m n = M (forall a. m a -> n a)
-- indexed monad on the category of monads
class (MonadT (t i), MonadT (t j), MonadT (t k))
=> TMon t i j k | t i j -> k where
bindT :: (Monad m) => Morph m (t i m) -> t j m a -> t k m a
instance TMon ReaderT i j (i,j) where
bindT (M f) m = do ~(i,j) <- ask
lift (runReaderT i (f (runReaderT j m)))
instance TMon StateT i j (i,j) where
bindT (M f) m = do ~(i,j) <- get
~(~(a,i'),j') <- lift (runStateT i (f (runStateT j m)))
set (i,j)
return a
instance (Monoid i, Monoid j) => TMon WriterT i j (i,j) where
bindT (M f) m = do ~(~(a,j),i) <- lift (runWriterT (f (runWriterT m)))
put (i,j)
return a
instance TMon ExceptionT i j (Either i j) where
bindT (M f) m = do x <- lift (runExceptionT (f (runExceptionT m)))
case x of
Left i -> raise (Left i)
Right (Left j) -> raise (Right j)
Right (Right a) -> return a
{- Continuation are tricky:
C i (C j m) a
=
(a -> C j m i) -> C j m i
=
(a -> (i -> m j) -> m j) -> (i -> m j) -> m j
= (uncurry)
(a -> (i -> m j) -> m j, i -> m j) -> m j
= (uncurry)
((a,i -> m j) -> m j, i -> m j) -> m j
= (sum)
(Either (a,i -> m j) i -> m j) -> m j
= C j m (Either (a,i -> m j) i)
-}
| yav/monadlib | experimental/MonadLibMorph.hs | mit | 17,481 | 0 | 15 | 4,745 | 6,379 | 3,353 | 3,026 | -1 | -1 |
import Data.Char (digitToInt)
main = print problem40Value
problem40Value :: Int
problem40Value = d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000
where d1 = digitToInt $ list !! 0
d10 = digitToInt $ list !! 9
d100 = digitToInt $ list !! 99
d1000 = digitToInt $ list !! 999
d10000 = digitToInt $ list !! 9999
d100000 = digitToInt $ list !! 99999
d1000000 = digitToInt $ list !! 999999
list = concat $ map show [1..]
| jchitel/ProjectEuler.hs | Problems/Problem0040.hs | mit | 496 | 8 | 19 | 158 | 181 | 87 | 94 | 12 | 1 |
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
module Arith where
import Control.Exception
import Data.Int
import Data.Text as T
type T = Int64
zero :: T
zero = 0
neg :: T -> T
neg x | x == minBound = throw Overflow
| otherwise = -x
add :: T -> T -> T
add x y =
if | p x && p y && n sum -> throw Overflow
| n x && n y && p sum -> throw Underflow
| otherwise -> sum
where sum = x + y
p x = x > 0
n x = x < 0
sub x y = add x (neg y)
fromText :: Int -> Text -> T
fromText scale txt =
case splitOn "." txt of
[i] -> read . unpack $ T.concat [i, padding scale]
[i, d] ->
if T.any (/= '0') post then throw LossOfPrecision
else read . unpack $
T.concat [i, pre, padding $ scale - T.length pre]
where (pre, post) = T.splitAt scale d
_ -> error "no parse"
where padding n = T.replicate n "0"
-- TODO: can we simplify this? Sounds very complex
toText :: Int -> T -> Text
toText 0 x = pack $ show x
toText scale x =
if | x == 0 -> "0"
| x > 0 -> toTextPos x
| otherwise -> T.concat ["-", toTextPos $ neg x]
where
toTextPos x =
case T.splitAt (T.length textPadded - scale) textPadded of
("", d) -> T.concat ["0.", d]
(i, d) -> T.concat [i, ".", d]
where text = pack $ show x
textPadded = T.concat [padding $ scale - T.length text, text]
padding n = T.replicate n "0"
| gip/cinq-cloches-ledger | src/Arith.hs | mit | 1,475 | 0 | 14 | 486 | 642 | 325 | 317 | 45 | 4 |
module TestLib (mkTestSuite, run, (<$>)) where
import Test.HUnit
import AsciiMath hiding (run)
import Prelude hiding ((<$>))
import Control.Applicative ((<$>))
unComment :: [String] -> [String]
unComment [] = []
unComment ("":ss) = "" : unComment ss
unComment (('#':_):ss) = unComment ss
unComment (s:ss) = s : unComment ss
readSrc :: String -> IO [String]
readSrc = (unComment . lines <$>) . readFile . ("tests/spec/"++)
mkTest :: String -> String -> Test
mkTest inp out = case compile inp of
Right s -> TestCase $ assertEqual ("for " ++ inp ++ ",") out s
Left err ->
TestCase $ assertFailure $ "Error while compiling \"" ++ inp ++ "\":\n" ++ renderError err ++ ".\n"
mkTestSuite :: String -> String -> IO Test
mkTestSuite name filename = do {
inp <- readSrc $ filename ++ ".txt";
out <- readSrc $ filename ++ ".latex";
return $ TestLabel name . TestList $ zipWith mkTest inp out
}
run :: Test -> IO ()
run t = do {
c <- runTestTT t;
if errors c == 0 && failures c == 0
then return ()
else error "fail";
}
| Kerl13/AsciiMath | tests/TestLib.hs | mit | 1,037 | 0 | 13 | 214 | 445 | 235 | 210 | 28 | 2 |
module Language.Egison.Typing where
import Data.Set (Set)
import qualified Data.Set as S
import Data.Map (Map)
import qualified Data.Map as M
import Language.Egison.Types
-- I will deprecate this synonym
type EgisonType = EgisonTypeExpr
type TypeVar = String
type ConsName = String
data TypeCons = TCons ConsName -- Name
Int -- Arity
type ClassName = String
type TypeContext = [(ClassName, TypeVar)]
type TypeVarEnv = Set TypeVar
type TypeConsEnv = Map TypeCons Int
type | tokiwoousaka/egison4 | hs-src/Language/Egison/Typing.hs | mit | 504 | 1 | 7 | 103 | 124 | 80 | 44 | -1 | -1 |
-- | Utility functions for dealing with the conversion of Output to Xml
module Util.Xml.Output (
outputToXmlString,
stringToXmlString,
xmlStringToOutput,
outputToXOutput
) where
import qualified Util.Xml.OutputDTD as X
import qualified Autolib.Output as O
import Util.Xml.Representation
-- import Text.PrettyPrint.HughesPJ hiding (style)
import qualified Autolib.Multilingual as M
import qualified Autolib.Multilingual.Html as H
-- import qualified Text.Blaze.Html.Renderer.String
-- import qualified Text.Blaze.Html.Renderer.Utf8
import qualified Autolib.Multilingual.Doc as D
import Data.String ( fromString )
-- import qualified Codec.Binary.Base64 as C
import qualified Data.ByteString.Base64 as BB
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import System.FilePath
import Control.Applicative
import Data.Maybe
import Data.Text (unpack)
import Util.Png
outputToXOutput :: M.Language -> O.Output -> IO X.Output
outputToXOutput lang o = case o of
O.Empty ->
return $ X.OBeside $ X.Beside []
O.Doc doc ->
outputToXOutput lang $ O.Pre doc
O.Pre doc ->
return $ X.OPre $ X.Pre $ D.render_for lang doc
O.String txt ->
return $ X.OText $ X.Text txt
O.Text txt ->
return $ X.OText $ X.Text $ Data.Text.unpack txt
O.Image file (O.Hidden contents) -> do
let ext = drop 1 $ snd $ splitExtension file
contents' <- contents
let (w, h) = case ext of
"png" -> (pngSize contents')
_ -> (0, 0)
img = BC.unpack $ BB.encode contents'
return $ X.OImage $
X.Image (X.Image_Attrs { X.imageType = ext,
X.imageAlt = "<image>",
X.imageUnit = "px",
X.imageWidth = show w,
X.imageHeight = show h })
img
O.Link uri ->
outputToXOutput lang (O.Named_Link uri uri)
O.Named_Link txt uri ->
return $ X.OLink $ X.Link (X.Link_Attrs { X.linkHref = uri }) txt
O.HRef uri o1 -> do
-- FIXME
-- outputToXOutput $ O.Above ( O.Link uri ) o1
outputToXOutput lang o1
O.Above o1 o2 ->
X.OAbove . X.Above <$> mapM (outputToXOutput lang) (aboves o1 ++ aboves o2)
O.Beside o1 o2 ->
X.OBeside . X.Beside <$> mapM (outputToXOutput lang) (besides o1 ++ besides o2)
O.Itemize os ->
X.OItemize . X.Itemize <$> mapM (outputToXOutput lang) os
O.Nest o' ->
X.OBeside . X.Beside <$> sequence [return nestSpacing, outputToXOutput lang o']
O.Figure a b ->
X.OFigure <$> (X.Figure <$> outputToXOutput lang a <*> outputToXOutput lang b)
xoutputToOutput :: X.Output -> O.Output
xoutputToOutput o = case o of
X.OPre (X.Pre txt) -> O.Pre (D.text txt)
X.OText (X.Text txt) -> O.String txt
X.OImage (X.Image _ img) ->
O.Image (mkData img) (O.Hidden $ return $ BB.decodeLenient $ fromString img)
X.OLink (X.Link (X.Link_Attrs { X.linkHref = uri }) txt) ->
O.Named_Link txt uri
X.OAbove (X.Above []) -> O.Empty
X.OAbove (X.Above xs) -> foldl1 O.Above $ map xoutputToOutput xs
X.OBeside (X.Beside []) -> O.Empty
-- handle special shape that is produce by outputToXOutput (Nest this)
X.OBeside (X.Beside [ X.OSpace{}, this ]) -> O.Nest $ xoutputToOutput this
X.OBeside (X.Beside xs) -> foldl1 O.Beside $ map xoutputToOutput xs
X.OItemize (X.Itemize xs) -> O.Itemize $ map xoutputToOutput xs
X.OSpace _ -> O.Empty -- FIXME
X.OFigure (X.Figure a b) -> O.Figure (xoutputToOutput a) (xoutputToOutput b)
mkData = ("data:image/png;base64," ++)
wrapXOutput :: X.Output -> Document ()
wrapXOutput o = let [CElem e _] = toContents o in
Document (Prolog (Just (XMLDecl "1.0" Nothing Nothing)) [] Nothing [])
emptyST e []
-- FIXME: this should go to Bytestring or Text instead
xmlToString :: Document () -> String
xmlToString = renderDocument_via_Doc
outputToXmlString :: M.Language -> O.Output -> IO String
outputToXmlString lang = fmap (xmlToString . wrapXOutput) . outputToXOutput lang
xmlStringToOutput :: String -> O.Output
xmlStringToOutput = xoutputToOutput . either error id . readXml
stringToXmlString :: String -> String
stringToXmlString = xmlToString . wrapXOutput . X.OText . X.Text
-- helpers for outputToXOutput
nestSpacing :: X.Output
nestSpacing = X.OSpace $ X.Space {
X.spaceWidth = "4",
X.spaceHeight = "0",
X.spaceUnit = "em" }
besides :: O.Output -> [O.Output]
besides (O.Beside a b) = besides a ++ besides b
besides a = [a]
aboves :: O.Output -> [O.Output]
aboves (O.Above a b) = aboves a ++ aboves b
aboves a = [a]
| marcellussiegburg/autotool | server-interface/src/Util/Xml/Output.hs | gpl-2.0 | 4,780 | 0 | 17 | 1,211 | 1,608 | 823 | 785 | 102 | 15 |
-- |
-- Module : Setup
-- Copyright : (C) 2007-2008 Bryan O'Sullivan
-- (C) 2012-2014 Jens Petersen
--
-- Maintainer : Jens Petersen <petersen@fedoraproject.org>
-- Stability : alpha
-- Portability : portable
--
-- Explanation: Command line option processing for building RPM
-- packages.
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
module Setup (
RpmFlags(..)
, parseArgs
, quiet
) where
import Control.Monad (unless, when)
import Data.Char (toLower)
import Data.Maybe (listToMaybe, fromMaybe)
import Data.Version (showVersion)
import Distribution.Compiler (CompilerId)
import Distribution.Text (simpleParse)
import Distribution.PackageDescription (FlagName (..))
import Distribution.ReadE (readEOrFail)
import Distribution.Verbosity (Verbosity, flagToVerbosity, normal,
silent)
import System.Console.GetOpt (ArgDescr (..), ArgOrder (..), OptDescr (..),
getOpt', usageInfo)
import System.Environment (getProgName)
import System.Exit (ExitCode (..), exitSuccess, exitWith)
import System.IO (Handle, hPutStrLn, stderr, stdout)
import Distro (Distro(..), readDistroName)
import Paths_cabal_rpm (version)
import SysCmd ((+-+))
data RpmFlags = RpmFlags
{ rpmConfigurationsFlags :: [(FlagName, Bool)]
, rpmForce :: Bool
, rpmHelp :: Bool
, rpmBinary :: Bool
, rpmStrict :: Bool
, rpmRelease :: Maybe String
, rpmCompilerId :: Maybe CompilerId
, rpmDistribution :: Maybe Distro
, rpmVerbosity :: Verbosity
, rpmVersion :: Bool
}
deriving (Eq, Show)
emptyRpmFlags :: RpmFlags
emptyRpmFlags = RpmFlags
{ rpmConfigurationsFlags = []
, rpmForce = False
, rpmHelp = False
, rpmBinary = False
, rpmStrict = False
, rpmRelease = Nothing
, rpmCompilerId = Nothing
, rpmDistribution = Nothing
, rpmVerbosity = normal
, rpmVersion = False
}
quiet :: RpmFlags
quiet = emptyRpmFlags {rpmVerbosity = silent}
options :: [OptDescr (RpmFlags -> RpmFlags)]
options =
[
Option "h?" ["help"] (NoArg (\x -> x { rpmHelp = True }))
"Show this help text",
Option "b" ["binary"] (NoArg (\x -> x { rpmBinary = True }))
"Force Haskell package name to be base package name",
Option "f" ["flags"] (ReqArg (\flags x -> x { rpmConfigurationsFlags = rpmConfigurationsFlags x ++ flagList flags }) "FLAGS")
"Set given flags in Cabal conditionals",
Option "" ["force"] (NoArg (\x -> x { rpmForce = True }))
"Overwrite existing spec file.",
Option "" ["strict"] (NoArg (\x -> x { rpmStrict = True }))
"Fail rather than produce an incomplete spec file.",
Option "" ["release"] (ReqArg (\rel x -> x { rpmRelease = Just rel }) "RELEASE")
"Override the default package release",
Option "" ["compiler"] (ReqArg (\cid x -> x { rpmCompilerId = Just (parseCompilerId cid) }) "COMPILER-ID")
"Finalize Cabal files targetting the given compiler version",
Option "" ["distro"] (ReqArg (\did x -> x { rpmDistribution = Just (readDistroName did) }) "DISTRO")
"Choose the distribution generated spec files will target",
Option "v" ["verbose"] (ReqArg (\verb x -> x { rpmVerbosity = readEOrFail flagToVerbosity verb }) "n")
"Change build verbosity",
Option "V" ["version"] (NoArg (\x -> x { rpmVersion = True }))
"Show version number"
]
-- Lifted from Distribution.Simple.Setup, since it's not exported.
flagList :: String -> [(FlagName, Bool)]
flagList = map tagWithValue . words
where tagWithValue ('-':name) = (FlagName (map toLower name), False)
tagWithValue name = (FlagName (map toLower name), True)
printHelp :: Handle -> IO ()
printHelp h = do
progName <- getProgName
let info = "Usage: " ++ progName ++ " [OPTION]... COMMAND [PATH|PKG|PKG-VERSION]\n"
++ "\n"
++ "PATH can be a .spec file, .cabal file, or pkg dir.\n"
++ "\n"
++ "Commands:\n"
++ " spec\t\t- generate a spec file\n"
++ " srpm\t\t- generate a src rpm file\n"
++ " prep\t\t- unpack source\n"
++ " local\t\t- build rpm package locally\n"
++ " builddep\t- install dependencies\n"
++ " install\t- install packages recursively\n"
++ " depends\t- list Cabal depends\n"
++ " requires\t- list package buildrequires\n"
++ " missingdeps\t- list missing buildrequires\n"
++ " diff\t\t- diff current spec file\n"
++ " update\t- update spec file package to latest version\n"
-- ++ " mock\t\t- mock build package\n"
++ "\n"
++ "Options:"
hPutStrLn h (usageInfo info options)
parseCompilerId :: String -> CompilerId
parseCompilerId x = fromMaybe err (simpleParse x)
where err = error (show x ++ " is not a valid compiler id")
parseArgs :: [String] -> IO (RpmFlags, String, Maybe String)
parseArgs args = do
let (os, args', unknown, errs) = getOpt' Permute options args
opts = foldl (flip ($)) emptyRpmFlags os
when (rpmHelp opts) $ do
printHelp stdout
exitSuccess
when (rpmVersion opts) $ do
putStrLn $ showVersion version
exitSuccess
unless (null errs) $
error $ unlines errs
unless (null unknown) $
error $ "Unrecognised options:" +-+ unwords unknown
when (null args') $ do
printHelp stderr
exitWith (ExitFailure 1)
when (head args' `notElem` ["builddep", "depends", "diff", "install", "missingdeps", "prep", "requires", "spec", "srpm", "build", "local", "rpm", "update", "refresh"]) $ do
hPutStrLn stderr $ "Unknown command:" +-+ head args'
printHelp stderr
exitWith (ExitFailure 1)
when (length args' > 2) $
error $ "Too many arguments:" +-+ unwords args'
return (opts, head args', listToMaybe $ tail args')
| opensuse-haskell/cabal-rpm | src/Setup.hs | gpl-3.0 | 6,406 | 0 | 28 | 1,797 | 1,545 | 858 | 687 | 124 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# OPTIONS -Wall -fno-warn-unused-binds #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Fixed
-- Copyright : (c) Ashley Yakeley 2005, 2006, 2009
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : Ashley Yakeley <ashley@semantic.org>
-- Stability : experimental
-- Portability : portable
--
-- This module defines a \"Fixed\" type for fixed-precision arithmetic.
-- The parameter to Fixed is any type that's an instance of HasResolution.
-- HasResolution has a single method that gives the resolution of the Fixed type.
--
-- This module also contains generalisations of div, mod, and divmod to work
-- with any Real instance.
--
-----------------------------------------------------------------------------
module Data.Fixed
(
div',mod',divMod',
Fixed(..), HasResolution(..),
showFixed,
E0,Uni,
E1,Deci,
E2,Centi,
E3,Milli,
E6,Micro,
E9,Nano,
E12,Pico
) where
import Prelude -- necessary to get dependencies right
import Data.Typeable
import Data.Data
import GHC.Read
import Text.ParserCombinators.ReadPrec
import Text.Read.Lex
default () -- avoid any defaulting shenanigans
-- | generalisation of 'div' to any instance of Real
div' :: (Real a,Integral b) => a -> a -> b
div' n d = floor ((toRational n) / (toRational d))
-- | generalisation of 'divMod' to any instance of Real
divMod' :: (Real a,Integral b) => a -> a -> (b,a)
divMod' n d = (f,n - (fromIntegral f) * d) where
f = div' n d
-- | generalisation of 'mod' to any instance of Real
mod' :: (Real a) => a -> a -> a
mod' n d = n - (fromInteger f) * d where
f = div' n d
-- | The type parameter should be an instance of 'HasResolution'.
newtype Fixed a = MkFixed Integer -- ^ /Since: 4.7.0.0/
deriving (Eq,Ord,Typeable)
-- We do this because the automatically derived Data instance requires (Data a) context.
-- Our manual instance has the more general (Typeable a) context.
tyFixed :: DataType
tyFixed = mkDataType "Data.Fixed.Fixed" [conMkFixed]
conMkFixed :: Constr
conMkFixed = mkConstr tyFixed "MkFixed" [] Prefix
instance (Typeable a) => Data (Fixed a) where
gfoldl k z (MkFixed a) = k (z MkFixed) a
gunfold k z _ = k (z MkFixed)
dataTypeOf _ = tyFixed
toConstr _ = conMkFixed
class HasResolution a where
resolution :: p a -> Integer
withType :: (p a -> f a) -> f a
withType foo = foo undefined
withResolution :: (HasResolution a) => (Integer -> f a) -> f a
withResolution foo = withType (foo . resolution)
instance Enum (Fixed a) where
succ (MkFixed a) = MkFixed (succ a)
pred (MkFixed a) = MkFixed (pred a)
toEnum = MkFixed . toEnum
fromEnum (MkFixed a) = fromEnum a
enumFrom (MkFixed a) = fmap MkFixed (enumFrom a)
enumFromThen (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromThen a b)
enumFromTo (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromTo a b)
enumFromThenTo (MkFixed a) (MkFixed b) (MkFixed c) = fmap MkFixed (enumFromThenTo a b c)
instance (HasResolution a) => Num (Fixed a) where
(MkFixed a) + (MkFixed b) = MkFixed (a + b)
(MkFixed a) - (MkFixed b) = MkFixed (a - b)
fa@(MkFixed a) * (MkFixed b) = MkFixed (div (a * b) (resolution fa))
negate (MkFixed a) = MkFixed (negate a)
abs (MkFixed a) = MkFixed (abs a)
signum (MkFixed a) = fromInteger (signum a)
fromInteger i = withResolution (\res -> MkFixed (i * res))
instance (HasResolution a) => Real (Fixed a) where
toRational fa@(MkFixed a) = (toRational a) / (toRational (resolution fa))
instance (HasResolution a) => Fractional (Fixed a) where
fa@(MkFixed a) / (MkFixed b) = MkFixed (div (a * (resolution fa)) b)
recip fa@(MkFixed a) = MkFixed (div (res * res) a) where
res = resolution fa
fromRational r = withResolution (\res -> MkFixed (floor (r * (toRational res))))
instance (HasResolution a) => RealFrac (Fixed a) where
properFraction a = (i,a - (fromIntegral i)) where
i = truncate a
truncate f = truncate (toRational f)
round f = round (toRational f)
ceiling f = ceiling (toRational f)
floor f = floor (toRational f)
chopZeros :: Integer -> String
chopZeros 0 = ""
chopZeros a | mod a 10 == 0 = chopZeros (div a 10)
chopZeros a = show a
-- only works for positive a
showIntegerZeros :: Bool -> Int -> Integer -> String
showIntegerZeros True _ 0 = ""
showIntegerZeros chopTrailingZeros digits a = replicate (digits - length s) '0' ++ s' where
s = show a
s' = if chopTrailingZeros then chopZeros a else s
withDot :: String -> String
withDot "" = ""
withDot s = '.':s
-- | First arg is whether to chop off trailing zeros
showFixed :: (HasResolution a) => Bool -> Fixed a -> String
showFixed chopTrailingZeros fa@(MkFixed a) | a < 0 = "-" ++ (showFixed chopTrailingZeros (asTypeOf (MkFixed (negate a)) fa))
showFixed chopTrailingZeros fa@(MkFixed a) = (show i) ++ (withDot (showIntegerZeros chopTrailingZeros digits fracNum)) where
res = resolution fa
(i,d) = divMod a res
-- enough digits to be unambiguous
digits = ceiling (logBase 10 (fromInteger res) :: Double)
maxnum = 10 ^ digits
fracNum = div (d * maxnum) res
instance (HasResolution a) => Show (Fixed a) where
show = showFixed False
instance (HasResolution a) => Read (Fixed a) where
readPrec = readNumber convertFixed
readListPrec = readListPrecDefault
readList = readListDefault
convertFixed :: forall a . HasResolution a => Lexeme -> ReadPrec (Fixed a)
convertFixed (Number n)
| Just (i, f) <- numberToFixed e n =
return (fromInteger i + (fromInteger f / (10 ^ e)))
where r = resolution (undefined :: Fixed a)
-- round 'e' up to help make the 'read . show == id' property
-- possible also for cases where 'resolution' is not a
-- power-of-10, such as e.g. when 'resolution = 128'
e = ceiling (logBase 10 (fromInteger r) :: Double)
convertFixed _ = pfail
data E0 = E0
deriving (Typeable)
instance HasResolution E0 where
resolution _ = 1
-- | resolution of 1, this works the same as Integer
type Uni = Fixed E0
data E1 = E1
deriving (Typeable)
instance HasResolution E1 where
resolution _ = 10
-- | resolution of 10^-1 = .1
type Deci = Fixed E1
data E2 = E2
deriving (Typeable)
instance HasResolution E2 where
resolution _ = 100
-- | resolution of 10^-2 = .01, useful for many monetary currencies
type Centi = Fixed E2
data E3 = E3
deriving (Typeable)
instance HasResolution E3 where
resolution _ = 1000
-- | resolution of 10^-3 = .001
type Milli = Fixed E3
data E6 = E6
deriving (Typeable)
instance HasResolution E6 where
resolution _ = 1000000
-- | resolution of 10^-6 = .000001
type Micro = Fixed E6
data E9 = E9
deriving (Typeable)
instance HasResolution E9 where
resolution _ = 1000000000
-- | resolution of 10^-9 = .000000001
type Nano = Fixed E9
data E12 = E12
deriving (Typeable)
instance HasResolution E12 where
resolution _ = 1000000000000
-- | resolution of 10^-12 = .000000000001
type Pico = Fixed E12
| jwiegley/ghc-release | libraries/base/Data/Fixed.hs | gpl-3.0 | 7,207 | 0 | 15 | 1,558 | 2,296 | 1,207 | 1,089 | 147 | 2 |
{-# LANGUAGE MultiParamTypeClasses, KindSignatures, TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Numerical.Petsc.Internal.Mutable
-- Copyright : (c) Marco Zocca 2015
-- License : LGPL3
-- Maintainer : zocca . marco . gmail . com
-- Stability : experimental
--
-- | Mutable containers in the IO monad
--
-----------------------------------------------------------------------------
module Numerical.PETSc.Internal.Mutable where
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Control.Monad
import Control.Monad.ST (runST, ST)
import Foreign.Storable
import qualified Control.Monad.Primitive as P
type family MutContainer (mc :: * -> *) :: * -> * -> *
class MContainer c a where
type MCSize c
type MCIdx c
basicSize :: c s a -> MCSize c
basicUnsafeSlice :: MCIdx c -> MCIdx c -> c s a -> c s a
-- basicUnsafeThaw :: P.PrimMonad m => c s a -> m (MutContainer c (P.PrimState m) a)
basicInitialize :: P.PrimMonad m => c (P.PrimState m) a -> m ()
-- | Yield the element at the given position. This method should not be
-- called directly, use 'unsafeRead' instead.
basicUnsafeRead :: P.PrimMonad m => c (P.PrimState m) a -> MCIdx c -> m a
-- | Replace the element at the given position. This method should not be
-- called directly, use 'unsafeWrite' instead.
basicUnsafeWrite :: P.PrimMonad m => c (P.PrimState m) a -> MCIdx c -> a -> m ()
-- instance G.Vector Vector a where
-- basicUnsafeFreeze (MVector i n marr)
-- = Vector i n `liftM` unsafeFreezeArray marr
-- basicUnsafeThaw (Vector i n arr)
-- = MVector i n `liftM` unsafeThawArray arr
-- basicLength (Vector _ n _) = n
-- basicUnsafeSlice j n (Vector i _ arr) = Vector (i+j) n arr
-- basicUnsafeIndexM (Vector i _ arr) j = indexArrayM arr (i+j)
-- basicUnsafeCopy (MVector i n dst) (Vector j _ src)
-- = copyArray dst i src j n
-- class Mutable v where
-- newVar :: a -> IO (v a)
-- readVar :: v a -> IO a
-- writeVar :: v a -> a -> IO ()
-- modifyVar :: v a -> (a -> a) -> IO ()
-- modifyVar' :: v a -> (a -> (a, b)) -> IO b
-- instance Mutable MVar where
-- newVar = newMVar
-- readVar = takeMVar
-- writeVar = putMVar
-- modifyVar v f = modifyMVar_ v (return . f)
-- modifyVar' v f = modifyMVar v (return . f)
-- instance Mutable TVar where
-- newVar = newTVarIO
-- readVar = readTVarIO
-- writeVar v x = atomically $ writeTVar v x
-- modifyVar v f = atomically $ do x <- readTVar v
-- writeTVar v (f x)
-- modifyVar' v f = atomically $ do x <- readTVar v
-- let (x', y) = f x
-- writeTVar v x'
-- return y
| ocramz/petsc-hs | src/Numerical/PETSc/Internal/Mutable.hs | gpl-3.0 | 2,823 | 0 | 12 | 732 | 322 | 193 | 129 | 17 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.SecurityPolicies.GetRule
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets a rule at the specified priority.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.securityPolicies.getRule@.
module Network.Google.Resource.Compute.SecurityPolicies.GetRule
(
-- * REST Resource
SecurityPoliciesGetRuleResource
-- * Creating a Request
, securityPoliciesGetRule
, SecurityPoliciesGetRule
-- * Request Lenses
, spgrPriority
, spgrProject
, spgrSecurityPolicy
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.securityPolicies.getRule@ method which the
-- 'SecurityPoliciesGetRule' request conforms to.
type SecurityPoliciesGetRuleResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"securityPolicies" :>
Capture "securityPolicy" Text :>
"getRule" :>
QueryParam "priority" (Textual Int32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] SecurityPolicyRule
-- | Gets a rule at the specified priority.
--
-- /See:/ 'securityPoliciesGetRule' smart constructor.
data SecurityPoliciesGetRule =
SecurityPoliciesGetRule'
{ _spgrPriority :: !(Maybe (Textual Int32))
, _spgrProject :: !Text
, _spgrSecurityPolicy :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SecurityPoliciesGetRule' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'spgrPriority'
--
-- * 'spgrProject'
--
-- * 'spgrSecurityPolicy'
securityPoliciesGetRule
:: Text -- ^ 'spgrProject'
-> Text -- ^ 'spgrSecurityPolicy'
-> SecurityPoliciesGetRule
securityPoliciesGetRule pSpgrProject_ pSpgrSecurityPolicy_ =
SecurityPoliciesGetRule'
{ _spgrPriority = Nothing
, _spgrProject = pSpgrProject_
, _spgrSecurityPolicy = pSpgrSecurityPolicy_
}
-- | The priority of the rule to get from the security policy.
spgrPriority :: Lens' SecurityPoliciesGetRule (Maybe Int32)
spgrPriority
= lens _spgrPriority (\ s a -> s{_spgrPriority = a})
. mapping _Coerce
-- | Project ID for this request.
spgrProject :: Lens' SecurityPoliciesGetRule Text
spgrProject
= lens _spgrProject (\ s a -> s{_spgrProject = a})
-- | Name of the security policy to which the queried rule belongs.
spgrSecurityPolicy :: Lens' SecurityPoliciesGetRule Text
spgrSecurityPolicy
= lens _spgrSecurityPolicy
(\ s a -> s{_spgrSecurityPolicy = a})
instance GoogleRequest SecurityPoliciesGetRule where
type Rs SecurityPoliciesGetRule = SecurityPolicyRule
type Scopes SecurityPoliciesGetRule =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient SecurityPoliciesGetRule'{..}
= go _spgrProject _spgrSecurityPolicy _spgrPriority
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy SecurityPoliciesGetRuleResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/SecurityPolicies/GetRule.hs | mpl-2.0 | 4,091 | 0 | 17 | 943 | 494 | 291 | 203 | 80 | 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.BigQuery.Models.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)
--
-- Patch specific fields in the specified model.
--
-- /See:/ <https://cloud.google.com/bigquery/ BigQuery API Reference> for @bigquery.models.patch@.
module Network.Google.Resource.BigQuery.Models.Patch
(
-- * REST Resource
ModelsPatchResource
-- * Creating a Request
, modelsPatch
, ModelsPatch
-- * Request Lenses
, mpModelId
, mpPayload
, mpDataSetId
, mpProjectId
) where
import Network.Google.BigQuery.Types
import Network.Google.Prelude
-- | A resource alias for @bigquery.models.patch@ method which the
-- 'ModelsPatch' request conforms to.
type ModelsPatchResource =
"bigquery" :>
"v2" :>
"projects" :>
Capture "projectId" Text :>
"datasets" :>
Capture "datasetId" Text :>
"models" :>
Capture "modelId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Model :> Patch '[JSON] Model
-- | Patch specific fields in the specified model.
--
-- /See:/ 'modelsPatch' smart constructor.
data ModelsPatch =
ModelsPatch'
{ _mpModelId :: !Text
, _mpPayload :: !Model
, _mpDataSetId :: !Text
, _mpProjectId :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ModelsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mpModelId'
--
-- * 'mpPayload'
--
-- * 'mpDataSetId'
--
-- * 'mpProjectId'
modelsPatch
:: Text -- ^ 'mpModelId'
-> Model -- ^ 'mpPayload'
-> Text -- ^ 'mpDataSetId'
-> Text -- ^ 'mpProjectId'
-> ModelsPatch
modelsPatch pMpModelId_ pMpPayload_ pMpDataSetId_ pMpProjectId_ =
ModelsPatch'
{ _mpModelId = pMpModelId_
, _mpPayload = pMpPayload_
, _mpDataSetId = pMpDataSetId_
, _mpProjectId = pMpProjectId_
}
-- | Required. Model ID of the model to patch.
mpModelId :: Lens' ModelsPatch Text
mpModelId
= lens _mpModelId (\ s a -> s{_mpModelId = a})
-- | Multipart request metadata.
mpPayload :: Lens' ModelsPatch Model
mpPayload
= lens _mpPayload (\ s a -> s{_mpPayload = a})
-- | Required. Dataset ID of the model to patch.
mpDataSetId :: Lens' ModelsPatch Text
mpDataSetId
= lens _mpDataSetId (\ s a -> s{_mpDataSetId = a})
-- | Required. Project ID of the model to patch.
mpProjectId :: Lens' ModelsPatch Text
mpProjectId
= lens _mpProjectId (\ s a -> s{_mpProjectId = a})
instance GoogleRequest ModelsPatch where
type Rs ModelsPatch = Model
type Scopes ModelsPatch =
'["https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient ModelsPatch'{..}
= go _mpProjectId _mpDataSetId _mpModelId
(Just AltJSON)
_mpPayload
bigQueryService
where go
= buildClient (Proxy :: Proxy ModelsPatchResource)
mempty
| brendanhay/gogol | gogol-bigquery/gen/Network/Google/Resource/BigQuery/Models/Patch.hs | mpl-2.0 | 3,776 | 0 | 17 | 944 | 543 | 322 | 221 | 86 | 1 |
{-# LANGUAGE RecordWildCards #-}
-- | 'Ktx' is the only format can handle all sorts of textures available
-- among OpenGL [ES] implementations. This library holds any Texture as 'Ktx'
-- internally.
module Graphics.TextureContainer.KTX where
import Control.Applicative
import Control.Exception
import Control.Monad
import qualified Data.ByteString as B
import Data.Packer
import Data.Word
-- | Khronos Texture Container Format
--
-- Spec: <http://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/>
data Ktx = Ktx
{ ktxName :: FilePath -- ^ Debug purpose
, ktxContent :: B.ByteString -- ^ Holding the original ForeignPtr.
, ktxGlType :: Word32
, ktxGlTypeSize :: Word32
, ktxGlFormat :: Word32
, ktxGlInternalFormat :: Word32
, ktxGlBaseInternalFormat :: Word32
, ktxPixelWidth :: Word32
, ktxPixelHeight :: Word32
, ktxPixelDepth :: Word32
, ktxNumElems :: Word32
, ktxNumFaces :: Word32
, ktxNumMipLevels :: Word32
, ktxMap :: [(B.ByteString, B.ByteString)] -- ^ \[(utf8 string, any)]
-- Note that if the value is utf8, it includes NULL terminator.
, ktxImage :: [[B.ByteString]]
} deriving Show
-- | 'Unpacking' instance.
unpackKtx :: FilePath -> B.ByteString -> Unpacking Ktx
unpackKtx name orig = do
let w = getWord32
-- '«', 'K', 'T', 'X', ' ', '1', '1', '»', '\r', '\n', '\x1A', '\n'
(0x58544BAB, 0xBB313120, 0x0A1A0A0D) <- (,,) <$> w <*> w <*> w
-- Endianness
-- Assuming Big-endian is a loser of history, just ignore it.
-- Note: All modern platforms (Android, iOS, Windows, ...)
-- runs Little-endian nevertheless the processor is bi-endian.
0x04030201 <- getWord32
ktx <- Ktx name orig <$> w <*> w <*> w <*> w <*> w <*> w
<*> w <*> w <*> w <*> w <*> w
bytesOfKeyValueData <- getWord32
let getKVP 0 = return []
getKVP i = do
keyAndValueByteSize <- getWord32
x <- getBytes (fromIntegral keyAndValueByteSize)
let padding = 3 - (keyAndValueByteSize + 3) `mod` 4
unpackSkip (fromIntegral padding)
xs <- getKVP (i - keyAndValueByteSize - padding)
return (x:xs)
kvp <- map (B.breakByte 0) <$> getKVP bytesOfKeyValueData
let Ktx{..} = ktx kvp []
imgs <- forM [1..max 1 ktxNumMipLevels] $ \_ -> do
imageSize <- getWord32
forM [1..max 1 ktxNumFaces] $ \_ -> do
img <- getBytes (fromIntegral imageSize)
unpackSkip $ fromIntegral (3 - (imageSize + 3) `mod` 4)
return img
return $ ktx kvp imgs
-- | Build 'Ktx' from given path.
ktxFromFile :: FilePath -> IO Ktx
ktxFromFile path = B.readFile path >>= return . readKtx path
-- | Build 'Ktx' with arbitrary resource name and actual data.
readKtx :: FilePath -> B.ByteString -> Ktx
readKtx path bs = runUnpacking (unpackKtx path bs) bs
-- | Same as 'readKtx' except error handling is explicit.
tryKtx :: FilePath -> B.ByteString -> Either SomeException Ktx
tryKtx path bs = tryUnpacking (unpackKtx path bs) bs
{-
type MipmapData = [Face or ArrayElements]
type ArrayElements = B.ByteString
type Face = B.ByteString
KTX Spec
---------
Byte[12] identifier
UInt32 endianness
UInt32 glType
UInt32 glTypeSize
UInt32 glFormat
Uint32 glInternalFormat
Uint32 glBaseInternalFormat
UInt32 pixelWidth
UInt32 pixelHeight
UInt32 pixelDepth
UInt32 numberOfArrayElements
UInt32 numberOfFaces
UInt32 numberOfMipmapLevels
UInt32 bytesOfKeyValueData
for each keyValuePair that fits in bytesOfKeyValueData
UInt32 keyAndValueByteSize
Byte keyAndValue[keyAndValueByteSize]
Byte valuePadding[3 - ((keyAndValueByteSize + 3) % 4)]
end
for each mipmap_level in numberOfMipmapLevels*
UInt32 imageSize;
for each array_element in numberOfArrayElements*
for each face in numberOfFaces
for each z_slice in pixelDepth*
for each row or row_of_blocks in pixelHeight*
for each pixel or block_of_pixels in pixelWidth
Byte data[format-specific-number-of-bytes]**
end
end
end
Byte cubePadding[0-3]
end
end
Byte mipPadding[3 - ((imageSize + 3) % 4)]
end
* Replace with 1 if this field is 0.
** Uncompressed texture data matches a GL_UNPACK_ALIGNMENT of 4.
-} | capsjac/opengles | src/Graphics/TextureContainer/KTX.hs | lgpl-3.0 | 4,142 | 7 | 22 | 848 | 742 | 394 | 348 | 56 | 2 |
-- | To represent a "package-name.cabal" file.
-- We only care about the dependencies, but we also need to preserve
-- everything else (including the whitespace!) because we will write the file
-- back to disk and we don't want to obliterate the user's indentation style.
module CabalFile.Types where
import Data.Either
import Distribution.Package
import Distribution.Version
-- The Cabal library already has the type Distribution.PackageDescription, and
-- it already has a parser and a pretty-printer. However, we cannot use that
-- representation because we need to keep the whitespace information intact.
type Cabal = [Either String Dependency]
dependencies :: Cabal -> [Dependency]
dependencies = rights
packages :: Cabal -> [PackageName]
packages = map package . dependencies
where
package :: Dependency -> PackageName
package (Dependency p _) = p
-- Replace the given dependencies
(//) :: Cabal -> [(PackageName, VersionRange)] -> Cabal
[] // _ = []
(Left s:xs) // ds = Left s : (xs // ds)
(Right (Dependency p v):xs) // ds = case lookup p ds of
Nothing -> Right (Dependency p v) : (xs // ds)
Just v' -> Right (Dependency p v') : (xs // ds)
| gelisam/cabal-rangefinder | src/CabalFile/Types.hs | unlicense | 1,179 | 0 | 11 | 220 | 282 | 152 | 130 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Spark.Core.GroupsSpec where
import Test.Hspec
import Data.Text(Text)
import Spark.Core.Context
import Spark.Core.Functions
import Spark.Core.ColumnFunctions
import Spark.Core.Column
import Spark.Core.IntegrationUtilities
import Spark.Core.CollectSpec(run)
import Spark.Core.Internal.Groups
sumGroup :: [MyPair] -> [(Text, Int)] -> IO ()
sumGroup l lexp = do
let ds = dataset l
let keys = ds // myKey'
let values = ds // myVal'
let g = groupByKey keys values
let ds2 = g `aggKey` sumCol
l2 <- exec1Def $ collect (asCol ds2)
l2 `shouldBe` lexp
spec :: Spec
spec = do
describe "Integration test - groups on (text, int)" $ do
run "empty" $
sumGroup [] []
run "one" $
sumGroup [MyPair "x" 1] [("x", 1)]
run "two" $
sumGroup [MyPair "x" 1, MyPair "x" 2, MyPair "y" 1] [("x", 3), ("y", 1)]
| krapsh/kraps-haskell | test-integration/Spark/Core/GroupsSpec.hs | apache-2.0 | 915 | 0 | 13 | 181 | 336 | 179 | 157 | 30 | 1 |
sequence' :: Monad m => [m a] -> m [a]
sequence' [] = return []
sequence' (m:ms) = m >>= \ a -> do as <- sequence' ms
return (a: as)
sequence'' ms = foldr func (return []) ms
where
func :: (Monad m) => m a -> m [a] -> m [a]
func m acc = do x <- m
xs <- acc
return (x: xs)
sequence''' [] = return []
sequence''' (m : ms) = do a <- m
as <- sequence''' ms
return (a:as)
{--
sequence'''' [] = return []
sequence'''' (m : ms) = m >>= \ a -> do as <- sequence'''' ms
return (a : as)
--}
mapM' :: Monad m => (a -> m b) -> [a] -> m [b]
mapM' f as = sequence' (map f as)
mapM'' f [] = return []
mapM'' f (a : as) = f a >>= \ b -> mapM'' f as >>= \ bs -> return (b : bs)
sequence_' :: Monad m => [m a] -> m ()
sequence_' [] = return ()
sequence_' (m : ms) = m >> sequence_' ms
--mapM''' :: Monad m => (a -> m b) -> [a] -> m [b]
--mapM''' f as = sequence_' (map f as)
mapMM f [] = return []
mapMM f (a : as) = do b <- f a
bs <- mapMM f as
return (b : bs)
mapMM' f [] = return []
mapMM' f (a : as) = f a >>= \ b ->
do bs <- mapMM' f as
return (b : bs)
mapMM'' f [] = return []
mapMM'' f (a : as) = f a >>= \ b ->
do bs <- mapMM'' f as
return (bs ++ [b])
filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a]
filterM' _ [] = return []
filterM' p (x : xs) = do flag <- p x
ys <- filterM' p xs
if flag then return (x: ys) else return ys
foldLeftM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
foldLeftM f a [] = return a
foldLeftM f a (x: xs) = do z <- f a x
foldLeftM f z xs
foldRightM :: Monad m => (a -> b -> m b) -> b -> [a] -> m b
foldRightM f a [] = return a
foldRightM f a as = do z <- f (last as) a
foldRightM f z $ init as
liftM :: Monad m => (a -> b) -> m a -> m b
liftM f m = do a <- m
return (f a)
liftM' :: Monad m => (a -> b) -> m a -> m b
liftM' f m = m >>= \ a -> return (f a)
liftM'' :: Monad m => (a -> b) -> m a -> m b
liftM'' f m = m >>= \ a -> m >>= \ b -> return (f a)
liftM''' :: Monad m => (a -> b) -> m a -> m b
liftM''' f m = m >>= \ a -> m >>= \ b -> return (f b)
--liftMM f m = mapM f [m]
| dongarerahul/edx-haskell | chapter-8-hw.hs | apache-2.0 | 2,479 | 4 | 12 | 1,016 | 1,251 | 608 | 643 | 54 | 2 |
import Controller (withOR)
import System.IO (hPutStrLn, stderr)
import Network.Wai.Middleware.Debug (debug)
import Network.Wai.Handler.Warp (run)
main :: IO ()
main = do
let port = 3000
hPutStrLn stderr $ "Application launched, listening on port " ++ show port
withOR $ run port . debug
| snoyberg/orangeroster | test.hs | bsd-2-clause | 300 | 0 | 9 | 55 | 101 | 54 | 47 | 9 | 1 |
-- |Interactions with the user.
module Ovid.Interactions
( tell
, options
) where
import Ovid.Prelude
import qualified System.Console.Editline.Readline as R
-- |Prompt the user.
tell s = liftIO (putStrLn s)
-- |Asks the user to pick an item from a list.
options :: (MonadIO m, Show a) => [a] -> m a
options xs = do
let numOptions = length xs
let showOption (n,x) = tell $ show n ++ " - " ++ show x
mapM_ showOption (zip [1..] xs)
tell $ "Select one (1 .. " ++ show numOptions ++ ") >"
let makeSelection = do
ch <- liftIO $ R.readKey
case tryInt "ch" of
Nothing -> do
tell $ "Enter a number between 1 and " ++ show numOptions
makeSelection
Just n ->
if n >= 1 && n <= numOptions
then return (xs !! (n-1))
else do
tell $ "Enter a number between 1 and " ++ show numOptions
makeSelection
makeSelection
| brownplt/ovid | src/Ovid/Interactions.hs | bsd-2-clause | 972 | 0 | 20 | 329 | 293 | 146 | 147 | 25 | 3 |
-- | Helper functions for dealing with text values
module Language.Terraform.Util.Text(
template,
show
) where
import Prelude hiding(show)
import qualified Prelude(show)
import qualified Data.Text as T
show :: (Show a) => a -> T.Text
show = T.pack . Prelude.show
-- | `template src substs` will replace all occurences the string $i
-- in src with `substs !! i`
template :: T.Text -> [T.Text] -> T.Text
template t substs = foldr replace t (zip [1,2..] substs)
where
replace (i,s) t = T.replace (T.pack ('$':Prelude.show i)) s t
| timbod7/terraform-hs | src/Language/Terraform/Util/Text.hs | bsd-3-clause | 547 | 0 | 13 | 106 | 178 | 102 | 76 | 11 | 1 |
module Validations.Types
( module Validations.Types.Checker
) where
import Validations.Types.Checker
| mavenraven/validations | src/Validations/Types.hs | bsd-3-clause | 106 | 0 | 5 | 14 | 21 | 14 | 7 | 3 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Futhark.Compiler
(
runPipelineOnProgram
, runCompilerOnProgram
, runPipelineOnSource
, interpretAction'
, FutharkConfig (..)
, newFutharkConfig
, dumpError
)
where
import Data.Monoid
import Control.Monad
import Control.Monad.IO.Class
import Data.Maybe
import System.Exit (exitWith, ExitCode(..))
import System.IO
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Prelude
import Language.Futhark.Parser
import Futhark.Internalise
import Futhark.Pipeline
import Futhark.Actions
import qualified Language.Futhark as E
import qualified Language.Futhark.TypeChecker as E
import Futhark.MonadFreshNames
import Futhark.Representation.AST
import qualified Futhark.Representation.SOACS as I
import qualified Futhark.TypeCheck as I
data FutharkConfig = FutharkConfig {
futharkVerbose :: Maybe (Maybe FilePath)
}
newFutharkConfig :: FutharkConfig
newFutharkConfig = FutharkConfig { futharkVerbose = Nothing }
dumpError :: FutharkConfig -> CompileError -> IO ()
dumpError config err = do
T.hPutStrLn stderr $ errorDesc err
case (errorData err, futharkVerbose config) of
(s, Just outfile) ->
maybe (T.hPutStr stderr) T.writeFile outfile $ s <> "\n"
_ -> return ()
runCompilerOnProgram :: FutharkConfig
-> Pipeline I.SOACS lore
-> Action lore
-> FilePath
-> IO ()
runCompilerOnProgram config pipeline action file = do
res <- runFutharkM compile $ isJust $ futharkVerbose config
case res of
Left err -> liftIO $ do
dumpError config err
exitWith $ ExitFailure 2
Right () ->
return ()
where compile = do
source <- liftIO $ T.readFile file
prog <- runPipelineOnSource config pipeline file source
when (isJust $ futharkVerbose config) $
liftIO $ hPutStrLn stderr $ "Running action " ++ actionName action
actionProcedure action prog
runPipelineOnProgram :: FutharkConfig
-> Pipeline I.SOACS tolore
-> FilePath
-> FutharkM (Prog tolore)
runPipelineOnProgram config pipeline file = do
source <- liftIO $ T.readFile file
runPipelineOnSource config pipeline file source
runPipelineOnSource :: FutharkConfig
-> Pipeline I.SOACS tolore
-> FilePath
-> T.Text
-> FutharkM (Prog tolore)
runPipelineOnSource config pipeline filename srccode = do
parsed_prog <- parseSourceProgram filename srccode
(tagged_ext_prog, namesrc) <- typeCheckSourceProgram parsed_prog
putNameSource namesrc
res <- internaliseProg tagged_ext_prog
case res of
Left err ->
compileErrorS "During internalisation:" err
Right int_prog -> do
typeCheckInternalProgram int_prog
runPasses pipeline pipeline_config int_prog
where pipeline_config =
PipelineConfig { pipelineVerbose = isJust $ futharkVerbose config
, pipelineValidate = True
}
parseSourceProgram :: FilePath -> T.Text
-> FutharkM E.UncheckedProg
parseSourceProgram filename file_contents = do
parsed <- liftIO $ parseFuthark filename file_contents
case parsed of
Left err -> compileError (T.pack $ show err) ()
Right prog -> return prog
typeCheckSourceProgram :: E.UncheckedProg
-> FutharkM (E.Prog, VNameSource)
typeCheckSourceProgram prog =
case E.checkProg prog of
Left err -> compileError (T.pack $ show err) ()
Right prog' -> return prog'
typeCheckInternalProgram :: I.Prog -> FutharkM ()
typeCheckInternalProgram prog =
case I.checkProg prog of
Left err -> compileError (T.pack $ "After internalisation:\n" ++ show err) prog
Right () -> return ()
interpretAction' :: Action I.SOACS
interpretAction' =
interpretAction parseValues'
where parseValues' :: FilePath -> T.Text -> Either ParseError [I.Value]
parseValues' path s =
fmap concat $ mapM internalise =<< parseValues path s
internalise v =
maybe (Left $ ParseError $ "Invalid input value: " ++ I.pretty v) Right $
internaliseValue v
| mrakgr/futhark | src/Futhark/Compiler.hs | bsd-3-clause | 4,305 | 0 | 16 | 1,127 | 1,138 | 571 | 567 | 112 | 2 |
{-# LANGUAGE OverloadedStrings,GADTs,DeriveDataTypeable,DeriveFunctor,GeneralizedNewtypeDeriving,MultiParamTypeClasses,QuasiQuotes,TemplateHaskell,TypeFamilies,PackageImports,NamedFieldPuns,RecordWildCards,TypeSynonymInstances,FlexibleContexts #-}
module Main where
import Data.Crawler
import Data.CrawlerParameters
import Misc
import WWW.SimpleTable
import Control.Applicative
import Control.Concurrent
import qualified Control.Exception as Ex
import Control.Monad
import Control.Monad.Catch
import Control.Monad.Error
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Writer.Lazy
import Data.Attoparsec.Text (Parser)
import qualified Data.Attoparsec.Text as AP
import Data.ByteString (ByteString,empty,writeFile)
import qualified Data.ByteString as B (empty,writeFile)
import Data.Char
import Data.List
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import Data.Time
import Data.Word
import Database.Persist
import qualified Database.Persist.MongoDB as Mongo
import Database.Persist.TH
import Language.Haskell.TH.Syntax (Type(ConT))
import Network (PortID (PortNumber))
import Network.Curl
import Network.Socket (PortNumber(..))
import "network" Network.URI
import System.Console.CmdArgs.Implicit
import System.Exit (ExitCode(..),exitWith)
import System.FilePath.Posix
import Text.HTML.TagSoup
import qualified Text.Pandoc as P
import Text.Poppler
main :: IO ()
main = do
(mongoP,crawlP) <- processParams
docs <- crawlBisBcbsPublications (courtesyPeriod crawlP)
(publishedFrom crawlP) (publishedUntil crawlP)
Ex.catch
(do
Mongo.withMongoDBConn (db mongoP) (host mongoP) (port mongoP) (auth mongoP) (dt mongoP) $ \pool -> do
Mongo.runMongoDBPool Mongo.master (writeDocs (courtesyPeriod crawlP)
docs (pdfPath crawlP)) pool)
gobalExceptionHandler
gobalExceptionHandler :: Ex.SomeException -> IO ()
gobalExceptionHandler e = do
putStrLn $ "gobalExceptionHandler: Got an exception --> " ++ show e
writeDocs :: Int -> [BisDoc] -> FilePath -> Mongo.Action IO ()
writeDocs ct docs pdfPath = do
liftIO $ putStrLn "Insert publications..."
forM_ docs (\d -> writeOneDoc d ct pdfPath)
writeDocsHandler :: Ex.SomeException -> IO (Either (Int, String) Text)
writeDocsHandler e = do
putStrLn $ "writeDocsHandler: Got an exception --> " ++ show e
return $ Left (-1,show e)
writeOneDoc :: BisDoc -> Int -> FilePath -> Mongo.Action IO ()
writeOneDoc d ct pdfPath = do
let title = T.unpack $ bisDocTitle d
liftIO $ putStrLn $ "Download and process '"++title++"'"
case bisDocDetails d of
Just det -> case bisDocumentDetailsFullTextLink det of
Just url -> do
mFullPdf <- liftIO $ getFile ct url
case mFullPdf of
Just fullPdf -> do
fullHtml <- liftIO $ Ex.handle writeDocsHandler $ do
let fname = snd (splitFileName (uriPath (fromJust (parseURI url))))
B.writeFile (pdfPath++fname) fullPdf
fullHtml <- pdfToHtmlTextOnly [] fullPdf
return fullHtml
case fullHtml of
Right html -> do
let fullMd = htmlToMarkdown html
let det' = det{bisDocumentDetailsFullTextMarkdown=Just fullMd}
Mongo.insert_ (d {bisDocDetails=Just det'})
Left (e,stderr) -> do
liftIO $ putStrLn $ "Error: "++show e
liftIO $ putStrLn stderr
Mongo.insert_ d
Nothing -> do
liftIO $ putStrLn $ "Error: Could not load pdf file."
Mongo.insert_ d
Nothing -> do
liftIO $ putStrLn $ "No file to download for '"++title++"'"
Mongo.insert_ d
Nothing -> do
liftIO $ putStrLn $ "No details for '"++title++"'"
Mongo.insert_ d
type TTag = Tag Text
getFile :: Int -> URLString -> IO (Maybe ByteString)
getFile ct url = Ex.catch
(do
resp <- curlGetResponse_ url [] :: IO (CurlResponse_ [(String,String)] ByteString)
threadDelay ct
return $ Just $ respBody resp)
handler
where handler :: Ex.SomeException -> IO (Maybe ByteString)
handler e = do
putStrLn $ "getFile: Got an exception --> " ++ show e
return Nothing
openUrlUtf8 :: Int -> URLString -> IO Text
openUrlUtf8 ct url =
Ex.catch (do
resp <- curlGetResponse_ url []
:: IO (CurlResponse_ [(String,String)] ByteString)
threadDelay ct
return (T.decodeUtf8 (respBody resp)))
handler
where handler :: Ex.SomeException -> IO Text
handler e = do
putStrLn $ "openUrlUtf8: Got an exception --> " ++ show e
return ""
collectWhile :: Monad m => Maybe t -> (t -> m [a]) -> (t -> m (Maybe t)) -> [a] -> m [a]
collectWhile (Just jx) process next bag = do
x1 <- next jx
new <- process jx
collectWhile x1 process next (bag++new)
collectWhile Nothing _ _ bag = return bag
ppTags tags = putStrLns (map showT tags)
bisSite :: URLString
bisSite = "http://www.bis.org"
crawlBisBcbsPublications :: Int -> Maybe Day -> Maybe Day -> IO [BisDoc]
crawlBisBcbsPublications ct t0 t1 = withCurlDo $ do
putStrLn $ "Start with page "++startingPoint
src <- openUrlUtf8 ct startingPoint
if src==""
then do
T.putStrLn "Cannot get page."
return []
else do
let tags = parseTags src
collectWhile (Just tags) (processBISDocPage ct t0 t1) (getNextBISDocPage ct) []
where startingPoint = bisSite++"/bcbs/publications.htm"
processBISDocPage :: Int -> Maybe Day -> Maybe Day -> [TTag] -> IO [BisDoc]
processBISDocPage ct t0 t1 tags = do
let ts = simpleTables tags
if null ts
then do
T.putStrLn "No table found on page."
return []
else do
let ts1 = head ts
docs <- catMaybes <$> mapM (processDoc ct t0 t1) (rows ts1)
T.putStrLn "Found: "
T.putStrLn $ T.intercalate "\n" (map (\ d -> "-- " `T.append` (bisDocTitle d)) docs)
return docs
processDoc :: Int -> Maybe Day -> Maybe Day -> TableRow -> IO (Maybe BisDoc)
processDoc ct t0 t1 row = do
let es = elements row
dt = getDateFromRow es
typ = getTypeFromRow es
lnk = getLinkFromRow es
ttl = getTitleFromRow es
if not (between dt t0 t1)
then return Nothing
else do
details <- case lnk of
Nothing -> return Nothing
Just l ->
if "pdf" `isSuffixOf` l
then do
resp <- curlGetResponse_ l [] :: IO (CurlResponse_ [(String,String)] ByteString)
threadDelay ct
return $ Just BisDocumentDetails {
bisDocumentDetailsDocumentTitle=ttl,
bisDocumentDetailsSummary = "",
bisDocumentDetailsFullTextLink = Just l,
bisDocumentDetailsFullTextMarkdown = Nothing,
bisDocumentDetailsLocalFile = Just $ filenameFromUrl l,
bisDocumentDetailsOtherLinks = []}
else analyzeBisSingleDocPage ct l
return $ Just $ BisDoc dt typ lnk ttl details
getDateFromRow tags = let ds = deleteAll ["\n","\t","\r"] $ fromTagText (head (head tags))
in case AP.parseOnly parseDate ds of
Left m -> error $ "Parse error while processing a date: "++m
Right d -> d
getTypeFromRow tags = let tag = (tags!!1)!!3
in if isTagOpen tag
then let attr = fromAttrib "title" tag
in if attr=="" then Nothing else Just attr
else Nothing
getLinkFromRow :: [[TTag]] -> Maybe URLString
getLinkFromRow tags = let tag = (tags!!2)!!3
in if isTagOpen tag
then Just $ bisSite++(T.unpack $ fromAttrib "href" tag)
else Nothing
getTitleFromRow tags = let tag = (tags!!2)!!4
in if isTagText tag
then deleteAll ["\t","\r","\n"] $ fromTagText tag
else ""
getNextBISDocPage :: Int -> [TTag] -> IO (Maybe [TTag])
getNextBISDocPage ct tags = do
let nextLink = getNextDocLink tags
case nextLink of
Just lnk -> do
putStrLn $ "Follow link: "++lnk
src <- openUrlUtf8 ct lnk
let tags1 = parseTags src
return (Just tags1)
Nothing -> return Nothing
getNextDocLink :: [TTag] -> Maybe URLString
getNextDocLink tags =
let s = sections (~== (TagOpen ("a"::Text) [("class","next")])) tags
in if null s
then Nothing
else let t = head (head s)
in let href = fromAttrib "href" t
in if href==""
then Nothing
else Just (if T.head href=='/'
then bisSite++(T.unpack href)
else T.unpack href)
analyzeBisSingleDocPage :: Int -> URLString -> IO (Maybe BisDocumentDetails)
analyzeBisSingleDocPage ct url = do
putStrLn $ "Analyse "++url
allTags <- return . partitionIt =<< (return . parseTags) =<< openUrlUtf8 ct url
if not (null allTags)
then if length allTags==3
then do
let contentTags = allTags!!0
annotationTags = allTags!!1
docTitle = fromTagText (contentTags!!1)
docSummary = let divSections = sections (~== (TagClose ("div"::Text))) contentTags
summaryHtml = if length divSections>=2
then purgeHtmlText $ tail (divSections!!1)
else error "Cannot parse page because structure has changed."
in T.pack $
P.writeMarkdown P.def $
P.readHtml P.def $
T.unpack $
renderTags summaryHtml
fullTextLink = let fBox = sections (~==divFullText) annotationTags
in if not (null fBox)
then let aTag = sections (~==aLinkTag) (head fBox)
link = T.unpack $ fromAttrib "href" (head $ head aTag)
in if "/" `isPrefixOf` link
then Just $ bisSite++link
else Just link
else Nothing
let otherBoxes = partitions (~== otherBox) annotationTags
let others = map processOtherBox otherBoxes
return $ Just $ BisDocumentDetails docTitle docSummary fullTextLink Nothing
(fmap filenameFromUrl fullTextLink) others
else do
putStrLn $ "Cannot parse page because structure has changed. "
++"Content:\n"
++show allTags
return Nothing
else do
putStrLn "No input. Probably You are not connected to the internet."
return Nothing
where tagContent = TagOpen "h1" [] :: TTag
tagAnnotations = TagOpen "div" [("id","right"),
("class","column"),
("role","complementary")] :: TTag
tagFooter = TagOpen "div" [("id","footer"),("role","contentinfo")] :: TTag
partitionIt = partitions (\tag -> tag~==tagContent
|| tag~==tagAnnotations
|| tag~==tagFooter)
divFullText = TagOpen "div" [("class","list_box full_text")] :: TTag
otherBox = TagOpen "div" [("class","list_box")] :: TTag
processOtherBox :: [Tag Text] -> DocumentLink
processOtherBox tags = let t1 = sections (~== (TagOpen "h4" [] :: TTag)) tags
typ = fromTagText ((head t1)!!1)
t2 = partitions (~==aLinkTag) tags
link tags = if null tags
then ""
else let lnk' = T.unpack $ fromAttrib "href" (head tags)
lnk = if lnk'==""
then ""
else if "/" `isPrefixOf` lnk'
then bisSite++lnk'
else lnk'
in lnk
links = map link t2
in (DocumentLink typ links)
| tkemps/bcbs-crawler | src/BcbsCrawler-old.hs | bsd-3-clause | 13,475 | 0 | 35 | 5,011 | 3,673 | 1,866 | 1,807 | 287 | 6 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
import System.Remote.Monitoring
import Web.Auth.OAuth2
import Web.Auth.Service
import Web.Orion
import Web.Scotty.Trans
import Web.Template
import Web.Template.Renderer
import Web.Session
import Database
import Text.Blaze.Html
import Text.Blaze.Html5 hiding (param, object, map, b)
import qualified Data.Text.Lazy as LT
import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.Map as Map
main :: IO ()
main = do
_ <- forkServer "localhost" 9989
orion $ do
createUserDatabaseIfNeeded
get "/" $ (blaze $ authdWrapper "Home" "Home")
`ifAuthorizedOr`
(blaze $ wrapper "Home" "Home")
get "/authCheck" $ do
mU <- readUserCookie
blaze $ wrapper "Auth Check" $ do
h3 "Auth Check"
pre $ toHtml $ show mU
get "/user" $ withAuthUser $ \u -> blaze $ authdWrapper "User" $ userTable u
get "/error/:err" $ do
err <- fmap errorMessage $ param "err"
blaze $ wrapper "Error" err
get "/login" $ do
dest <- defaultParam "redirect" ""
(blaze $ authdWrapper "Login" $ loginOptions $ Just dest)
`ifAuthorizedOr`
(blaze $ wrapper "Login" $ loginOptions $ Just dest)
get "/logout" $ do
expireUserCookie
blaze $ wrapper "Logout" $ p "You have been logged out."
get "/login/:service" $ do
service <- param "service"
let Just key = oauth2serviceKey service
url <- prepareServiceLogin service key
redirect url
get "/login/:service/complete" $ do
dest <- popRedirectDestination
eUser <- oauthenticate
case eUser of
Left err -> blaze $ wrapper "OAuth Error" $ do
h3 "Authentication Error"
p $ toHtml $ LB.unpack err
Right u -> do c <- futureCookieForUser u
writeUserCookie c
redirect dest
--get "/link/:service" $ withAuthUser $ \u -> do
-- service <- param "service"
-- if service `elem` linkedServices u
-- then blaze $ wrapper "Link Service" $ do
-- h3 "Blarg"
-- p "You've already linked that service."
-- else do let key = serviceKey service
-- baseUrl <- readCfg getCfgBaseUrl
-- let call = concat [ baseUrl
-- , "/link/"
-- , serviceToString service
-- , "/complete"
-- ]
-- call' = B.pack call
-- key' = key{oauthCallback= Just call'}
-- url <- prepareServiceLogin service key'
-- redirect url
--get "/link/:service/complete" $ withAuthUser $ \OrionUser{..} -> do
-- dest <- popRedirectDestination
-- service <- param "service"
-- eUdat <- fetchRemoteUserData
-- case eUdat of
-- Left err -> blaze $ authdWrapper "Link Error" $ do
-- h3 $ toHtml $ "Error linking " ++ serviceToString service
-- p $ toHtml $ LB.unpack err
-- Right udat -> do mUser <- addAccountToUser service _ouId udat
-- case mUser of
-- Nothing -> blaze $ authdWrapper "Link Error" $ do
-- h3 $ toHtml $ "Error linking " ++ serviceToString service
-- p $ "Failed to add account."
-- Just _ -> redirect dest
popRedirectDestination :: ActionOM LT.Text
popRedirectDestination = do
state <- param "state"
states <- readAuthStates
modifyAuthStates $ Map.delete state
case Map.lookup state states of
Nothing -> redirect "error/stateMismatch"
Just dest -> return dest
| schell/orion | src/Main.hs | bsd-3-clause | 4,457 | 0 | 21 | 1,883 | 680 | 341 | 339 | 66 | 2 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveFunctor #-}
module Data.Queue (
Queue
, empty, singleton, fromList
, toList, enqueue, dequeue, enqueueAll
) where
import Control.DeepSeq (NFData)
import GHC.Generics (Generic)
data Queue a = Q [a] [a]
deriving (Show, Eq, Functor, NFData, Generic)
empty ∷ Queue a
empty = Q [] []
singleton ∷ a → Queue a
singleton a = Q [a] []
fromList ∷ [a] → Queue a
fromList as = Q as []
toList ∷ Queue a → [a]
toList (Q h t) = h ++ reverse t
enqueue ∷ Queue a → a → Queue a
enqueue (Q h t) a = Q (a:h) t
enqueueAll ∷ Queue a → [a] → Queue a
enqueueAll (Q h t) as = Q (as ++ h) t
dequeue ∷ Queue a → Maybe (Queue a, a)
dequeue (Q [] []) = Nothing
dequeue (Q h []) = let (h':t) = reverse h
in Just (Q [] t, h')
dequeue (Q h (h':t)) = Just (Q h t, h')
| stefan-hoeck/labeled-graph | Data/Queue.hs | bsd-3-clause | 898 | 0 | 10 | 224 | 454 | 237 | 217 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 800
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
#endif
module Text.RE.PCRE.ByteString
(
-- * Tutorial
-- $tutorial
-- * The Match Operators
(*=~)
, (?=~)
, (=~)
, (=~~)
-- * The Toolkit
-- $toolkit
, module Text.RE
-- * The 'RE' Type
-- $re
, module Text.RE.PCRE.RE
) where
import Prelude.Compat
import qualified Data.ByteString as B
import Data.Typeable
import Text.Regex.Base
import Text.RE
import Text.RE.Internal.AddCaptureNames
import Text.RE.PCRE.RE
import qualified Text.Regex.PCRE as PCRE
-- | find all matches in text
(*=~) :: B.ByteString
-> RE
-> Matches B.ByteString
(*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ match (reRegex rex) bs
-- | find first match in text
(?=~) :: B.ByteString
-> RE
-> Match B.ByteString
(?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ match (reRegex rex) bs
-- | the regex-base polymorphic match operator
(=~) :: ( Typeable a
, RegexContext PCRE.Regex B.ByteString a
, RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption String
)
=> B.ByteString
-> RE
-> a
(=~) bs rex = addCaptureNames (reCaptureNames rex) $ match (reRegex rex) bs
-- | the regex-base monadic, polymorphic match operator
(=~~) :: ( Monad m
, Functor m
, Typeable a
, RegexContext PCRE.Regex B.ByteString a
, RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption String
)
=> B.ByteString
-> RE
-> m a
(=~~) bs rex = addCaptureNames (reCaptureNames rex) <$> matchM (reRegex rex) bs
instance IsRegex RE B.ByteString where
matchOnce = flip (?=~)
matchMany = flip (*=~)
regexSource = reSource
-- $tutorial
-- We have a regex tutorial at <http://tutorial.regex.uk>. These API
-- docs are mainly for reference.
-- $toolkit
--
-- Beyond the above match operators and the regular expression type
-- below, "Text.RE" contains the toolkit for replacing captures,
-- specifying options, etc.
-- $re
--
-- "Text.RE.PCRE.RE" contains the toolkit specific to the 'RE' type,
-- the type generated by the gegex compiler.
| cdornan/idiot | Text/RE/PCRE/ByteString.hs | bsd-3-clause | 2,516 | 0 | 8 | 658 | 484 | 287 | 197 | 50 | 1 |
module SlaeGauss where
import Data.Bifunctor
import qualified Data.Matrix as Mx
import qualified Data.Vector as Vec
import Library
compute :: Matrix -> Either ComputeError Vector
compute = fmap backtrackPermuted . triangulate
where
backtrackPermuted (mx, permutations) =
Vec.map (backtrack mx Vec.!) permutations
triangulate :: Matrix -> Either ComputeError (Matrix, Permutations)
triangulate mx = first Mx.fromRows <$> go 0 permutations rows
where
rows = Mx.toRows mx
permutations = Vec.fromList [0..(length rows - 1)]
go :: Int -> Permutations -> [Vector]
-> Either ComputeError ([Vector], Permutations)
go _ ps [] = Right ([], ps)
go j ps m@(as:ass)
| isLastCol = Right (m, ps)
| isZeroPivot = Left SingularMatrix
| otherwise = first (as':) <$> go (j + 1) ps' (map updRow ass')
where
isLastCol = j + 2 >= Vec.length as
isZeroPivot = nearZero as'j
as'j = as' Vec.! j
(as':ass', ps') = permuteToMax j ps m
updRow bs = Vec.zipWith op as' bs
where
k = bs Vec.! j / as'j
op a b = b - a * k
permuteToMax :: Int -> Permutations -> [Vector] -> ([Vector], Permutations)
permuteToMax col ps m =
( Mx.toRows $ permuteRows 0 i $ permuteCols col j $ Mx.fromRows m
, swapComponents col j ps
)
where
(i, j, _) = foldr imax (0, 0, 0) $ zip [0..] m
imax :: (Int, Vec.Vector Double) -> (Int, Int, Double) -> (Int, Int, Double)
imax (i, v) oldMax@(_, _, max)
| rowMax > max = (i, j + col, rowMax)
| otherwise = oldMax
where (j, rowMax) = Vec.ifoldl vimax (0, 0) (Vec.drop col $ Vec.init v)
vimax :: (Int, Double) -> Int -> Double -> (Int, Double)
vimax (i, max) k a
| a > max = (k, a)
| otherwise = (i, max)
permuteRows :: Int -> Int -> Matrix -> Matrix
permuteRows i k = Mx.fromColumns . map (swapComponents i k) . Mx.toColumns
permuteCols :: Int -> Int -> Matrix -> Matrix
permuteCols i k = Mx.fromRows . map (swapComponents i k) . Mx.toRows
swapComponents :: Int -> Int -> Vec.Vector a -> Vec.Vector a
swapComponents i k v = Vec.imap cmpSelector v
where cmpSelector j el
| j == i = v Vec.! k
| j == k = v Vec.! i
| otherwise = el
backtrack :: Matrix -> Vector
backtrack = foldr eqSolver Vec.empty . Mx.toRows
eqSolver :: Vector -> Vector -> Vector
eqSolver as xs = Vec.cons ((Vec.last as' - Vec.sum (resolveKnown as' xs)) / Vec.head as') xs
where as' = Vec.dropWhile nearZero as
resolveKnown :: Vector -> Vector -> Vector
resolveKnown as xs = Vec.zipWith (*) xs (Vec.tail $ Vec.init as)
| hrsrashid/nummet | lib/SlaeGauss.hs | bsd-3-clause | 2,689 | 0 | 13 | 749 | 1,141 | 595 | 546 | 58 | 2 |
module Paths_variants (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/jo/.cabal/bin"
libdir = "/Users/jo/.cabal/lib/x86_64-osx-ghc-7.10.2/varia_5wCMPNeYlGhAk0qTYbHvsm"
datadir = "/Users/jo/.cabal/share/x86_64-osx-ghc-7.10.2/variants-0.1.0.0"
libexecdir = "/Users/jo/.cabal/libexec"
sysconfdir = "/Users/jo/.cabal/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "variants_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "variants_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "variants_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "variants_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "variants_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| josephDunne/variants | dist/build/autogen/Paths_variants.hs | bsd-3-clause | 1,313 | 0 | 10 | 177 | 362 | 206 | 156 | 28 | 1 |
{-# LANGUAGE PatternSignatures #-}
module Main where
import GHC.Conc
import Control.Exception
import Foreign.StablePtr
import System.IO
import GHC.Conc.Sync (atomicallyWithIO)
inittvar :: STM (TVar String)
inittvar = newTVar "Hello world"
deadlock0 :: STM String
deadlock0 = retry
deadlock1 :: TVar String -> STM String
deadlock1 v1 = do s1 <- readTVar v1
retry
atomically_ x = atomicallyWithIO x (\x -> putStrLn "IO" >> return x)
-- Basic single-threaded operations with retry
main = do newStablePtr stdout
putStr "Before\n"
t1 <- atomically ( newTVar 0 )
-- Atomic block that contains a retry but does not perform it
r <- atomically_ ( do r1 <- readTVar t1
if (r1 /= 0) then retry else return ()
return r1 )
putStr ("Survived unused retry\n")
-- Atomic block that retries after reading 0 TVars
s1 <- Control.Exception.catch (atomically_ retry )
(\(e::SomeException) -> return ("Caught: " ++ (show e) ++ "\n"))
putStr s1
-- Atomic block that retries after reading 1 TVar
t1 <- atomically ( inittvar )
s1 <- Control.Exception.catch (atomically_ ( deadlock1 t1 ))
(\(e::SomeException) -> return ("Caught: " ++ (show e) ++ "\n"))
putStr s1
return ()
| mcschroeder/ghc | libraries/base/tests/Concurrent/stmio047.hs | bsd-3-clause | 1,402 | 0 | 17 | 438 | 386 | 192 | 194 | 30 | 2 |
{-# LANGUAGE RecordWildCards #-}
module Main (main) where
import GeoLabel (toString, fromString')
import GeoLabel.Strings (format, parse)
import GeoLabel.Strings.Wordlist (wordlist)
import GeoLabel.Geometry.QuadTree (Subface(A,B,C,D))
import GeoLabel.Geometry.Point (lengthOf, (<->))
import GeoLabel.Geometry.Conversion (cartesian)
import GeoLabel.Geometry.Polar (Polar(..))
import GeoLabel.Geodesic.Earth (earthRadius)
import GeoLabel.Unit.Location (Location(..), idOf, fromId)
import Numeric.Units.Dimensional ((*~), one)
import Numeric.Units.Dimensional.SIUnits (meter)
import System.Exit (exitFailure)
import Test.QuickCheck (quickCheckResult, Result(..), forAll, vector, vectorOf, elements, choose)
import Data.Maybe (fromJust)
import GeoLabel.Real (R)
import Data.Number.BigFloat (BigFloat, Prec50, Epsilon)
import System.Random (Random, randomR, random)
instance Epsilon e => Random (BigFloat e) where
randomR (a,b) g = (c,g')
where
(d,g') = randomR (realToFrac a :: Double, realToFrac b) g
c = realToFrac d
random g = (realToFrac (d :: Double), g')
where (d,g') = random g
main :: IO ()
main = do
print "testing location -> bits -> location"
try $ quickCheckResult idTest
print "testing location -> String -> location"
try $ quickCheckResult locTest
print "testing coordinate -> String -> coordinate"
try $ quickCheckResult coordTest
try :: (IO Result) -> IO ()
try test = do
result <- test
case result of
Failure{..} -> exitFailure
_ -> return ()
idTest = forAll (choose (0,19)) $ \face ->
forAll (vectorOf 25 (elements [A,B,C,D])) $ \subfaces ->
let loc = Location face subfaces in
loc == (fromJust . fromId . idOf $ loc)
locTest = forAll (choose (0,19)) $ \face ->
forAll (vectorOf 25 (elements [A,B,C,D])) $ \subfaces ->
let loc = Location face subfaces in
loc == (fromJust . parse . format $ loc)
coordTest = forAll (choose (0.0, pi)) $ \lat ->
forAll (choose (0.0, pi)) $ \lon ->
acceptableError (lat, lon) (fromString' . toString $ (lat, lon))
acceptableError :: (R, R) -> (R, R) -> Bool
acceptableError (a1, b1) (a2, b2) = difference <= 0.2 *~ meter
where
point1 = cartesian (Polar earthRadius (a1 *~ one) (b1 *~ one))
point2 = cartesian (Polar earthRadius (a2 *~ one) (b2 *~ one))
difference = lengthOf (point1 <-> point2)
-- Infinite loop?
-- 1.1477102348032477
-- 2.5287052457281303
-- toString (1.1477102348032477, 2.5287052457281303)
-- It's resulting in a lot of kicks
-- It's landing really far away
-- V3 -1615695.0421316223 m 3918971.9410642236 m 582344.6221676043 m
--0.5342809894312989
--2.434338807577105
-- V3 2089283.5979154985 m 1236191.1378369904 m -2840087.204665418 m | wyager/GeoLabel | src/GeoLabel/Test.hs | bsd-3-clause | 2,776 | 0 | 15 | 535 | 947 | 535 | 412 | 55 | 2 |
{-|
Module : Reactive.DOM.Children.MonotoneList
Description : Definition of the MonotoneList children container.
Copyright : (c) Alexander Vieth, 2016
Licence : BSD3
Maintainer : aovieth@gmail.com
Stability : experimental
Portability : non-portable (GHC only)
-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
module Reactive.DOM.Children.MonotoneList where
import Data.Semigroup
import Data.Functor.Compose
import Reactive.DOM.Internal.ChildrenContainer
import Reactive.DOM.Internal.Mutation
newtype MonotoneList t inp out f = MonotoneList {
runMonotoneList :: [f t]
}
deriving instance Semigroup (MonotoneList t inp out f)
deriving instance Monoid (MonotoneList t inp out f)
instance FunctorTransformer (MonotoneList inp out t) where
functorTrans trans (MonotoneList fts) = MonotoneList (trans <$> fts)
functorCommute (MonotoneList fts) = MonotoneList <$> sequenceA (getCompose <$> fts)
instance ChildrenContainer (MonotoneList inp out t) where
type Change (MonotoneList t inp out) = MonotoneList t inp out
getChange get (MonotoneList news) (MonotoneList olds) =
let nextList = MonotoneList (olds <> news)
mutations = AppendChild . get <$> news
in (nextList, mutations)
childrenContainerList get (MonotoneList ts) = get <$> ts
| avieth/reactive-dom | Reactive/DOM/Children/MonotoneList.hs | bsd-3-clause | 1,438 | 0 | 12 | 250 | 302 | 166 | 136 | 24 | 0 |