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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
import Test.Tasty
import ReaderTests
import EvalTests
tests :: TestTree
tests = testGroup "Tests" [readerTests, evalTests]
main :: IO ()
main = defaultMain tests
|
lkitching/PScheme
|
test/Spec.hs
|
bsd-3-clause
| 165
| 0
| 6
| 26
| 51
| 28
| 23
| 7
| 1
|
module TypeClass04
(
)
where
newtype Poly a = P [a]
-- Exercise 1 -----------------------------------------
x :: Num a => Poly a
x = P [0,1]
-- Exercise 2 ----------------------------------------
instance (Num a, Eq a) => Eq (Poly a) where
P [] == P [] = True
P [] == P y = P y == P []
P (x':xs) == P [] = x' == 0 && P xs == P []
P (x':xs) == P (y:ys) = x' == y && P xs == P ys
-- Exercise 3 -----------------------------------------
joinList :: String -> [String] -> String
joinList _ [] = []
joinList _ (y:[]) = y
joinList xs (y:ys) = y ++ xs ++ joinList xs ys
instance (Num a, Eq a, Show a) => Show (Poly a) where
show (P xs) = joinList " + " .
reverse .
filter (not.null) .
map display
$ zip [0..] xs
where display (_,0) = ""
display (0,c) = show c
display (d,c) = showC c ++ showD d
showC 1 = ""
showC (-1) = "-"
showC c = show c
showD 1 = "x"
showD d = "x^" ++ show d
-- Exercise 4 -----------------------------------------
plusList :: Num t => [t] -> [t] -> [t]
plusList xs' [] = xs'
plusList [] ys' = ys'
plusList (x':xs') (y':ys') = (x'+y'):plusList xs' ys'
plus :: Num a => Poly a -> Poly a -> Poly a
plus (P xs) (P ys) = P (plusList xs ys)
-- Exercise 5 -----------------------------------------
times :: Num a => Poly a -> Poly a -> Poly a
times (P a) (P b) = P (foldl plusList ([]) $ timesList a b)
where timesList a' b' = map (plusC a') $ zip numList b'
plusC l (d,c) = fill0 d $ map (*c) l
fill0 0 l = l
fill0 n l = fill0 (n-1) (0:l)
numList = (0::Integer) : map (+1) numList
-- Exercise 6 -----------------------------------------
instance Num a => Num (Poly a) where
(+) = plus
(*) = times
-- since -1 is actual (negate 1) , if (* (-1)) will cause infinite loop
-- negate = (* P[-1])
negate (P a) = P $ (map negate a)
fromInteger i = P [fromInteger i]
-- No meaningful definitions exist
abs = undefined
signum = undefined
-- Exercise 7 -----------------------------------------
applyP :: Num a => Poly a -> a -> a
applyP (P l) a = sum $ map (apply a) (zip [0..] l)
where apply a (d,c) = (a^d)*c
-- Exercise 8 -----------------------------------------
class Num a => Differentiable a where
deriv :: a -> a
nderiv :: Int -> a -> a
nderiv 0 y = y
nderiv n f = nderiv (n-1) (deriv f)
-- Exercise 9 -----------------------------------------
instance Num a => Differentiable (Poly a) where
deriv (P []) = P []
deriv (P l) = P (zipWith (*) numList (tail l))
where numList = 1 : map (+1) numList
|
Enzo-Liu/cis194
|
src/TypeClass04.hs
|
bsd-3-clause
| 2,712
| 0
| 11
| 797
| 1,225
| 623
| 602
| 60
| 2
|
-- | List type that supports O(1) amortized 'cons', 'snoc', 'uncons' and 'isEmpty'.
module General.Bilist(
Bilist, cons, snoc, uncons, toList, isEmpty
) where
import Data.Semigroup
import Prelude
data Bilist a = Bilist [a] [a]
toList :: Bilist a -> [a]
toList (Bilist as bs) = as ++ reverse bs
isEmpty :: Bilist a -> Bool
isEmpty (Bilist as bs) = null as && null bs
instance Eq a => Eq (Bilist a) where
a == b = toList a == toList b
instance Semigroup (Bilist a) where
a <> b = Bilist (toList a ++ toList b) []
instance Monoid (Bilist a) where
mempty = Bilist [] []
mappend = (<>)
cons :: a -> Bilist a -> Bilist a
cons x (Bilist as bs) = Bilist (x:as) bs
snoc :: Bilist a -> a -> Bilist a
snoc (Bilist as bs) x = Bilist as (x:bs)
uncons :: Bilist a -> Maybe (a, Bilist a)
uncons (Bilist [] []) = Nothing
uncons (Bilist (a:as) bs) = Just (a, Bilist as bs)
uncons (Bilist [] bs) = uncons $ Bilist (reverse bs) []
|
ndmitchell/shake
|
src/General/Bilist.hs
|
bsd-3-clause
| 948
| 0
| 9
| 218
| 465
| 236
| 229
| 24
| 1
|
f x | x > 1 = if x > 2
then 2
else 1
| otherwise = 0
|
itchyny/vim-haskell-indent
|
test/if/guard.in.hs
|
mit
| 53
| 1
| 8
| 19
| 39
| 19
| 20
| -1
| -1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE Rank2Types #-}
module Data.Concurrent.HashMap
( HashMap
, new
, new'
, null
, insert
, delete
, lookup
, update
, fromList
, toList
, hashString
, hashBS
, hashInt
, nextHighestPowerOf2 ) where
------------------------------------------------------------------------------
import Control.Concurrent.MVar
import Control.Monad
import Data.Bits
import qualified Data.ByteString as B
import qualified Data.Digest.Murmur32 as Murmur
import qualified Data.Digest.Murmur64 as Murmur
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
import Data.Maybe
import qualified Data.Vector as V
import Data.Vector (Vector)
import GHC.Conc (numCapabilities)
import Prelude hiding (lookup, null)
import qualified Prelude
#if __GLASGOW_HASKELL__ >= 503
import GHC.Exts ( Word(..), Int(..), shiftRL# )
#else
import Data.Word
#endif
hashString :: String -> Word
hashString = if bitSize (undefined :: Word) == 32
then fromIntegral . Murmur.asWord32 . Murmur.hash32
else fromIntegral . Murmur.asWord64 . Murmur.hash64
{-# INLINE hashString #-}
hashInt :: Int -> Word
hashInt = if bitSize (undefined :: Word) == 32
then fromIntegral . Murmur.asWord32 . Murmur.hash32
else fromIntegral . Murmur.asWord64 . Murmur.hash64
{-# INLINE hashInt #-}
hashBS :: B.ByteString -> Word
hashBS = if bitSize (undefined :: Word) == 32 then h32 else h64
where
h32 s = fromIntegral $ Murmur.asWord32 $
B.foldl' (\h c -> h `seq` c `seq`
Murmur.hash32AddInt (fromEnum c) h)
(Murmur.hash32 ([] :: [Int]))
s
h64 s = fromIntegral $ Murmur.asWord64 $
B.foldl' (\h c -> h `seq` c `seq`
Murmur.hash64AddInt (fromEnum c) h)
(Murmur.hash64 ([] :: [Int]))
s
{-# INLINE hashBS #-}
data HashMap k v = HM {
_hash :: !(k -> Word)
, _hashToBucket :: !(Word -> Word)
, _maps :: !(Vector (MVar (Submap k v)))
}
null :: HashMap k v -> IO Bool
null ht = liftM V.and $ V.mapM f $ _maps ht
where
f mv = withMVar mv (return . IM.null)
new' :: Eq k =>
Int -- ^ number of locks to use
-> (k -> Word) -- ^ hash function
-> IO (HashMap k v)
new' numLocks hashFunc = do
vector <- V.replicateM (fromEnum n) (newMVar IM.empty)
return $! HM hf bh vector
where
hf !x = hashFunc x
bh !x = x .&. (n-1)
!n = nextHighestPowerOf2 $ toEnum numLocks
new :: Eq k =>
(k -> Word) -- ^ hash function
-> IO (HashMap k v)
new = new' defaultNumberOfLocks
insert :: k -> v -> HashMap k v -> IO ()
insert key value ht =
modifyMVar_ submap $ \m ->
return $! insSubmap hashcode key value m
where
hashcode = _hash ht key
bucket = _hashToBucket ht hashcode
submap = V.unsafeIndex (_maps ht) (fromEnum bucket)
delete :: (Eq k) => k -> HashMap k v -> IO ()
delete key ht =
modifyMVar_ submap $ \m ->
return $! delSubmap hashcode key m
where
hashcode = _hash ht key
bucket = _hashToBucket ht hashcode
submap = V.unsafeIndex (_maps ht) (fromEnum bucket)
lookup :: (Eq k) => k -> HashMap k v -> IO (Maybe v)
lookup key ht =
withMVar submap $ \m ->
return $! lookupSubmap hashcode key m
where
hashcode = _hash ht key
bucket = _hashToBucket ht hashcode
submap = V.unsafeIndex (_maps ht) (fromEnum bucket)
update :: (Eq k) => k -> v -> HashMap k v -> IO Bool
update key value ht =
modifyMVar submap $ \m ->
return $! updateSubmap hashcode key value m
where
hashcode = _hash ht key
bucket = _hashToBucket ht hashcode
submap = V.unsafeIndex (_maps ht) (fromEnum bucket)
toList :: HashMap k v -> IO [(k,v)]
toList ht = liftM (concat . V.toList) $ V.mapM f $ _maps ht
where
f m = withMVar m $ \sm -> return $ concat $ IM.elems sm
fromList :: (Eq k) => (k -> Word) -> [(k,v)] -> IO (HashMap k v)
fromList hf xs = do
ht <- new hf
mapM_ (\(k,v) -> insert k v ht) xs
return $! ht
------------------------------------------------------------------------------
-- helper functions
------------------------------------------------------------------------------
-- nicked this technique from Data.IntMap
shiftRL :: Word -> Int -> Word
#if __GLASGOW_HASKELL__
{--------------------------------------------------------------------
GHC: use unboxing to get @shiftRL@ inlined.
--------------------------------------------------------------------}
shiftRL (W# x) (I# i)
= W# (shiftRL# x i)
#else
shiftRL x i = shiftR x i
#endif
type Submap k v = IntMap [(k,v)]
nextHighestPowerOf2 :: Word -> Word
nextHighestPowerOf2 w = highestBitMask (w-1) + 1
highestBitMask :: Word -> Word
highestBitMask !x0 = case (x0 .|. shiftRL x0 1) of
x1 -> case (x1 .|. shiftRL x1 2) of
x2 -> case (x2 .|. shiftRL x2 4) of
x3 -> case (x3 .|. shiftRL x3 8) of
x4 -> case (x4 .|. shiftRL x4 16) of
x5 -> x5 .|. shiftRL x5 32
insSubmap :: Word -> k -> v -> Submap k v -> Submap k v
insSubmap hashcode key value m = let !x = f m in x
where
f = IM.insertWith (++) (fromIntegral hashcode) [(key,value)]
delSubmap :: (Eq k) => Word -> k -> Submap k v -> Submap k v
delSubmap hashcode key m =
let !z = IM.update f (fromIntegral hashcode) m in z
where
f l = let l' = del l in if Prelude.null l' then Nothing else Just l'
del = filter ((/= key) . fst)
lookupSubmap :: (Eq k) => Word -> k -> Submap k v -> Maybe v
lookupSubmap hashcode key m = maybe Nothing (Prelude.lookup key) mbBucket
where
mbBucket = IM.lookup (fromIntegral hashcode) m
updateSubmap :: (Eq k) => Word -> k -> v -> Submap k v -> (Submap k v, Bool)
updateSubmap hashcode key value m = (m'', b)
where
oldV = lookupSubmap hashcode key m
m' = maybe m (const $ delSubmap hashcode key m) oldV
m'' = insSubmap hashcode key value m'
b = isJust oldV
defaultNumberOfLocks :: Int
defaultNumberOfLocks = 8 * numCapabilities
|
beni55/snap-server
|
src/Data/Concurrent/HashMap.hs
|
bsd-3-clause
| 6,351
| 0
| 21
| 1,776
| 2,182
| 1,149
| 1,033
| 151
| 2
|
module Robots3.Examples where
-- -- $Id$
import Robots3.Data
import Robots3.Config
import Autolib.ToDoc
-- | Aufgabe von Alexander Krabbes
alex :: Config
alex = make
[ Robot { name = "A", position = Position { x = 4, y = 5} }
, Robot { name = "B", position = Position { x = -4,y = 5} }
, Robot { name = "C", position = Position { x = 3, y = 4} }
, Robot { name = "D", position = Position { x = -3,y = 4} }
, Robot { name = "E", position = Position { x = 0, y = 5} }
, Robot { name = "F", position = Position { x = 4,y = -4} }
, Robot { name = "G", position = Position { x = -4,y = -4} }
]
[ Position {x = 0, y = 0} ]
-- | die beispielkarte nr. 40 aus dem original-spiel
-- von binaryarts.com
fourty :: Config
fourty = make
[ Robot { name = "A", position = Position { x = -2, y = 2} }
, Robot { name = "B", position = Position { x = 0,y = 2} }
, Robot { name = "C", position = Position { x = 2, y = 2} }
, Robot { name = "D", position = Position { x = 2,y = -1} }
, Robot { name = "E", position = Position { x = -1,y = -2} }
]
[ Position { x = 0, y = 0} ]
|
florianpilz/autotool
|
src/Robots3/Examples.hs
|
gpl-2.0
| 1,097
| 0
| 11
| 302
| 479
| 304
| 175
| 22
| 1
|
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.PkgConfigDb
-- Copyright : (c) Iñaki García Etxebarria 2016
-- License : BSD-like
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- Read the list of packages available to pkg-config.
-----------------------------------------------------------------------------
module Distribution.Client.PkgConfigDb
( PkgConfigDb
, readPkgConfigDb
, pkgConfigDbFromList
, pkgConfigPkgIsPresent
, getPkgConfigDbDirs
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>), (<*>))
#endif
import Control.Exception (IOException, handle)
import Data.Char (isSpace)
import qualified Data.Map as M
import Data.Version (parseVersion)
import Text.ParserCombinators.ReadP (readP_to_S)
import System.FilePath (splitSearchPath)
import Distribution.Package
( PackageName(..) )
import Distribution.Verbosity
( Verbosity )
import Distribution.Version
( Version, VersionRange, withinRange )
import Distribution.Compat.Environment
( lookupEnv )
import Distribution.Simple.Program
( ProgramConfiguration, pkgConfigProgram, getProgramOutput,
requireProgram )
import Distribution.Simple.Utils
( info )
-- | The list of packages installed in the system visible to
-- @pkg-config@. This is an opaque datatype, to be constructed with
-- `readPkgConfigDb` and queried with `pkgConfigPkgPresent`.
data PkgConfigDb = PkgConfigDb (M.Map PackageName (Maybe Version))
-- ^ If an entry is `Nothing`, this means that the
-- package seems to be present, but we don't know the
-- exact version (because parsing of the version
-- number failed).
| NoPkgConfigDb
-- ^ For when we could not run pkg-config successfully.
deriving (Show)
-- | Query pkg-config for the list of installed packages, together
-- with their versions. Return a `PkgConfigDb` encapsulating this
-- information.
readPkgConfigDb :: Verbosity -> ProgramConfiguration -> IO PkgConfigDb
readPkgConfigDb verbosity conf = handle ioErrorHandler $ do
(pkgConfig, _) <- requireProgram verbosity pkgConfigProgram conf
pkgList <- lines <$> getProgramOutput verbosity pkgConfig ["--list-all"]
-- The output of @pkg-config --list-all@ also includes a description
-- for each package, which we do not need.
let pkgNames = map (takeWhile (not . isSpace)) pkgList
pkgVersions <- lines <$> getProgramOutput verbosity pkgConfig
("--modversion" : pkgNames)
(return . pkgConfigDbFromList . zip pkgNames) pkgVersions
where
-- For when pkg-config invocation fails (possibly because of a
-- too long command line).
ioErrorHandler :: IOException -> IO PkgConfigDb
ioErrorHandler e = do
info verbosity ("Failed to query pkg-config, Cabal will continue"
++ " without solving for pkg-config constraints: "
++ show e)
return NoPkgConfigDb
-- | Create a `PkgConfigDb` from a list of @(packageName, version)@ pairs.
pkgConfigDbFromList :: [(String, String)] -> PkgConfigDb
pkgConfigDbFromList pairs = (PkgConfigDb . M.fromList . map convert) pairs
where
convert :: (String, String) -> (PackageName, Maybe Version)
convert (n,vs) = (PackageName n,
case (reverse . readP_to_S parseVersion) vs of
(v, "") : _ -> Just v
_ -> Nothing -- Version not (fully)
-- understood.
)
-- | Check whether a given package range is satisfiable in the given
-- @pkg-config@ database.
pkgConfigPkgIsPresent :: PkgConfigDb -> PackageName -> VersionRange -> Bool
pkgConfigPkgIsPresent (PkgConfigDb db) pn vr =
case M.lookup pn db of
Nothing -> False -- Package not present in the DB.
Just Nothing -> True -- Package present, but version unknown.
Just (Just v) -> withinRange v vr
-- If we could not read the pkg-config database successfully we allow
-- the check to succeed. The plan found by the solver may fail to be
-- executed later on, but we have no grounds for rejecting the plan at
-- this stage.
pkgConfigPkgIsPresent NoPkgConfigDb _ _ = True
-- | Query pkg-config for the locations of pkg-config's package files. Use this
-- to monitor for changes in the pkg-config DB.
--
getPkgConfigDbDirs :: Verbosity -> ProgramConfiguration -> IO [FilePath]
getPkgConfigDbDirs verbosity conf =
(++) <$> getEnvPath <*> getDefPath
where
-- According to @man pkg-config@:
--
-- PKG_CONFIG_PATH
-- A colon-separated (on Windows, semicolon-separated) list of directories
-- to search for .pc files. The default directory will always be searched
-- after searching the path
--
getEnvPath = maybe [] parseSearchPath
<$> lookupEnv "PKG_CONFIG_PATH"
-- Again according to @man pkg-config@:
--
-- pkg-config can be used to query itself for the default search path,
-- version number and other information, for instance using:
--
-- > pkg-config --variable pc_path pkg-config
--
getDefPath = handle ioErrorHandler $ do
(pkgConfig, _) <- requireProgram verbosity pkgConfigProgram conf
parseSearchPath <$>
getProgramOutput verbosity pkgConfig
["--variable", "pc_path", "pkg-config"]
parseSearchPath str =
case lines str of
[p] | not (null p) -> splitSearchPath p
_ -> []
ioErrorHandler :: IOException -> IO [FilePath]
ioErrorHandler _e = return []
|
tolysz/prepare-ghcjs
|
spec-lts8/cabal/cabal-install/Distribution/Client/PkgConfigDb.hs
|
bsd-3-clause
| 5,816
| 0
| 15
| 1,438
| 895
| 502
| 393
| 74
| 3
|
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2013
--
-----------------------------------------------------------------------------
{-# LANGUAGE GADTs #-}
module SPARC.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import SPARC.Base
import SPARC.CodeGen.Sanity
import SPARC.CodeGen.Amode
import SPARC.CodeGen.CondCode
import SPARC.CodeGen.Gen64
import SPARC.CodeGen.Gen32
import SPARC.CodeGen.Base
import SPARC.Ppr ()
import SPARC.Instr
import SPARC.Imm
import SPARC.AddrMode
import SPARC.Regs
import SPARC.Stack
import Instruction
import Size
import NCGMonad
-- Our intermediate code:
import BlockId
import Cmm
import CmmUtils
import CmmSwitch
import Hoopl
import PIC
import Reg
import CLabel
import CPrim
-- The rest:
import BasicTypes
import DynFlags
import FastString
import OrdList
import Outputable
import Platform
import Unique
import Control.Monad ( mapAndUnzipM )
-- | Top level code generation
cmmTopCodeGen :: RawCmmDecl
-> NatM [NatCmmDecl CmmStatics Instr]
cmmTopCodeGen (CmmProc info lab live graph)
= do let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
let tops = proc : concat statics
return tops
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec dat] -- no translation, we just use CmmStatic
-- | Do code generation on a single block of CMM code.
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
basicBlockCodeGen :: CmmBlock
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl CmmStatics Instr])
basicBlockCodeGen block = do
let (_, nodes, tail) = blockSplit block
id = entryLabel block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
let
(top,other_blocks,statics)
= foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
-- do intra-block sanity checking
blocksChecked
= map (checkBlock block)
$ BasicBlock id top : other_blocks
return (blocksChecked, statics)
-- | Convert some Cmm statements to SPARC instructions.
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmTick {} -> return nilOL
CmmUnwind {} -> return nilOL
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode size reg src
| isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode size reg src
where ty = cmmRegType dflags reg
size = cmmTypeSize ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode size addr src
| isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode size addr src
where ty = cmmExprType dflags src
size = cmmTypeSize ty
CmmUnsafeForeignCall target result_regs args
-> genCCall target result_regs args
CmmBranch id -> genBranch id
CmmCondBranch arg true false -> do b1 <- genCondJump true arg
b2 <- genBranch false
return (b1 `appOL` b2)
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg } -> genJump arg
_
-> panic "stmtToInstrs: statement should have been cps'd away"
{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = mkAsmTempLabel (getUnique blockid)
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_IntCode pk addr src = do
(srcReg, code) <- getSomeReg src
Amode dstAddr addr_code <- getAmode addr
return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
assignReg_IntCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_IntCode _ reg src = do
dflags <- getDynFlags
r <- getRegister src
let dst = getRegisterReg (targetPlatform dflags) reg
return $ case r of
Any _ code -> code dst
Fixed _ freg fcode -> fcode `snocOL` OR False g0 (RIReg freg) dst
-- Floating point assignment to memory
assignMem_FltCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_FltCode pk addr src = do
dflags <- getDynFlags
Amode dst__2 code1 <- getAmode addr
(src__2, code2) <- getSomeReg src
tmp1 <- getNewRegNat pk
let
pk__2 = cmmExprType dflags src
code__2 = code1 `appOL` code2 `appOL`
if sizeToWidth pk == typeWidth pk__2
then unitOL (ST pk src__2 dst__2)
else toOL [ FxTOy (cmmTypeSize pk__2) pk src__2 tmp1
, ST pk tmp1 dst__2]
return code__2
-- Floating point assignment to a register/temporary
assignReg_FltCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_FltCode pk dstCmmReg srcCmmExpr = do
dflags <- getDynFlags
let platform = targetPlatform dflags
srcRegister <- getRegister srcCmmExpr
let dstReg = getRegisterReg platform dstCmmReg
return $ case srcRegister of
Any _ code -> code dstReg
Fixed _ srcFixedReg srcCode -> srcCode `snocOL` FMOV pk srcFixedReg dstReg
genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
genJump (CmmLit (CmmLabel lbl))
= return (toOL [CALL (Left target) 0 True, NOP])
where
target = ImmCLbl lbl
genJump tree
= do
(target, code) <- getSomeReg tree
return (code `snocOL` JMP (AddrRegReg target g0) `snocOL` NOP)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
SPARC: First, we have to ensure that the condition codes are set
according to the supplied comparison operation. We generate slightly
different code for floating point comparisons, because a floating
point operation cannot directly precede a @BF@. We assume the worst
and fill that slot with a @NOP@.
SPARC: Do not fill the delay slots here; you will confuse the register
allocator.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump bid bool = do
CondCode is_float cond code <- getCondCode bool
return (
code `appOL`
toOL (
if is_float
then [NOP, BF cond False bid, NOP]
else [BI cond False bid, NOP]
)
)
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock
genSwitch dflags expr targets
| gopt Opt_PIC dflags
= error "MachCodeGen: sparc genSwitch PIC not finished\n"
| otherwise
= do (e_reg, e_code) <- getSomeReg (cmmOffset dflags expr offset)
base_reg <- getNewRegNat II32
offset_reg <- getNewRegNat II32
dst <- getNewRegNat II32
label <- getNewLabelNat
return $ e_code `appOL`
toOL
[ -- load base of jump table
SETHI (HI (ImmCLbl label)) base_reg
, OR False base_reg (RIImm $ LO $ ImmCLbl label) base_reg
-- the addrs in the table are 32 bits wide..
, SLL e_reg (RIImm $ ImmInt 2) offset_reg
-- load and jump to the destination
, LD II32 (AddrRegReg base_reg offset_reg) dst
, JMP_TBL (AddrRegImm dst (ImmInt 0)) ids label
, NOP ]
where (offset, ids) = switchTargetsToTable targets
generateJumpTableForInstr :: DynFlags -> Instr
-> Maybe (NatCmmDecl CmmStatics Instr)
generateJumpTableForInstr dflags (JMP_TBL _ ids label) =
let jumpTable = map (jumpTableEntry dflags) ids
in Just (CmmData ReadOnlyData (Statics label jumpTable))
generateJumpTableForInstr _ _ = Nothing
-- -----------------------------------------------------------------------------
-- Generating C calls
{-
Now the biggest nightmare---calls. Most of the nastiness is buried in
@get_arg@, which moves the arguments to the correct registers/stack
locations. Apart from that, the code is easy.
The SPARC calling convention is an absolute
nightmare. The first 6x32 bits of arguments are mapped into
%o0 through %o5, and the remaining arguments are dumped to the
stack, beginning at [%sp+92]. (Note that %o6 == %sp.)
If we have to put args on the stack, move %o6==%sp down by
the number of words to go on the stack, to ensure there's enough space.
According to Fraser and Hanson's lcc book, page 478, fig 17.2,
16 words above the stack pointer is a word for the address of
a structure return value. I use this as a temporary location
for moving values from float to int regs. Certainly it isn't
safe to put anything in the 16 words starting at %sp, since
this area can get trashed at any time due to window overflows
caused by signal handlers.
A final complication (if the above isn't enough) is that
we can't blithely calculate the arguments one by one into
%o0 .. %o5. Consider the following nested calls:
fff a (fff b c)
Naive code moves a into %o0, and (fff b c) into %o1. Unfortunately
the inner call will itself use %o0, which trashes the value put there
in preparation for the outer call. Upshot: we need to calculate the
args into temporary regs, and move those to arg regs or onto the
stack only immediately prior to the call proper. Sigh.
-}
genCCall
:: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
-- On SPARC under TSO (Total Store Ordering), writes earlier in the instruction stream
-- are guaranteed to take place before writes afterwards (unlike on PowerPC).
-- Ref: Section 8.4 of the SPARC V9 Architecture manual.
--
-- In the SPARC case we don't need a barrier.
--
genCCall (PrimTarget MO_WriteBarrier) _ _
= return $ nilOL
genCCall (PrimTarget (MO_Prefetch_Data _)) _ _
= return $ nilOL
genCCall target dest_regs args0
= do
-- need to remove alignment information
let args | PrimTarget mop <- target,
(mop == MO_Memcpy ||
mop == MO_Memset ||
mop == MO_Memmove)
= init args0
| otherwise
= args0
-- work out the arguments, and assign them to integer regs
argcode_and_vregs <- mapM arg_to_int_vregs args
let (argcodes, vregss) = unzip argcode_and_vregs
let vregs = concat vregss
let n_argRegs = length allArgRegs
let n_argRegs_used = min (length vregs) n_argRegs
-- deal with static vs dynamic call targets
callinsns <- case target of
ForeignTarget (CmmLit (CmmLabel lbl)) _ ->
return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
ForeignTarget expr _
-> do (dyn_c, [dyn_r]) <- arg_to_int_vregs expr
return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
PrimTarget mop
-> do res <- outOfLineMachOp mop
lblOrMopExpr <- case res of
Left lbl -> do
return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
Right mopExpr -> do
(dyn_c, [dyn_r]) <- arg_to_int_vregs mopExpr
return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
return lblOrMopExpr
let argcode = concatOL argcodes
let (move_sp_down, move_sp_up)
= let diff = length vregs - n_argRegs
nn = if odd diff then diff + 1 else diff -- keep 8-byte alignment
in if nn <= 0
then (nilOL, nilOL)
else (unitOL (moveSp (-1*nn)), unitOL (moveSp (1*nn)))
let transfer_code
= toOL (move_final vregs allArgRegs extraStackArgsHere)
dflags <- getDynFlags
return
$ argcode `appOL`
move_sp_down `appOL`
transfer_code `appOL`
callinsns `appOL`
unitOL NOP `appOL`
move_sp_up `appOL`
assign_code (targetPlatform dflags) dest_regs
-- | Generate code to calculate an argument, and move it into one
-- or two integer vregs.
arg_to_int_vregs :: CmmExpr -> NatM (OrdList Instr, [Reg])
arg_to_int_vregs arg = do dflags <- getDynFlags
arg_to_int_vregs' dflags arg
arg_to_int_vregs' :: DynFlags -> CmmExpr -> NatM (OrdList Instr, [Reg])
arg_to_int_vregs' dflags arg
-- If the expr produces a 64 bit int, then we can just use iselExpr64
| isWord64 (cmmExprType dflags arg)
= do (ChildCode64 code r_lo) <- iselExpr64 arg
let r_hi = getHiVRegFromLo r_lo
return (code, [r_hi, r_lo])
| otherwise
= do (src, code) <- getSomeReg arg
let pk = cmmExprType dflags arg
case cmmTypeSize pk of
-- Load a 64 bit float return value into two integer regs.
FF64 -> do
v1 <- getNewRegNat II32
v2 <- getNewRegNat II32
let code2 =
code `snocOL`
FMOV FF64 src f0 `snocOL`
ST FF32 f0 (spRel 16) `snocOL`
LD II32 (spRel 16) v1 `snocOL`
ST FF32 f1 (spRel 16) `snocOL`
LD II32 (spRel 16) v2
return (code2, [v1,v2])
-- Load a 32 bit float return value into an integer reg
FF32 -> do
v1 <- getNewRegNat II32
let code2 =
code `snocOL`
ST FF32 src (spRel 16) `snocOL`
LD II32 (spRel 16) v1
return (code2, [v1])
-- Move an integer return value into its destination reg.
_ -> do
v1 <- getNewRegNat II32
let code2 =
code `snocOL`
OR False g0 (RIReg src) v1
return (code2, [v1])
-- | Move args from the integer vregs into which they have been
-- marshalled, into %o0 .. %o5, and the rest onto the stack.
--
move_final :: [Reg] -> [Reg] -> Int -> [Instr]
-- all args done
move_final [] _ _
= []
-- out of aregs; move to stack
move_final (v:vs) [] offset
= ST II32 v (spRel offset)
: move_final vs [] (offset+1)
-- move into an arg (%o[0..5]) reg
move_final (v:vs) (a:az) offset
= OR False g0 (RIReg v) a
: move_final vs az offset
-- | Assign results returned from the call into their
-- destination regs.
--
assign_code :: Platform -> [LocalReg] -> OrdList Instr
assign_code _ [] = nilOL
assign_code platform [dest]
= let rep = localRegType dest
width = typeWidth rep
r_dest = getRegisterReg platform (CmmLocal dest)
result
| isFloatType rep
, W32 <- width
= unitOL $ FMOV FF32 (regSingle $ fReg 0) r_dest
| isFloatType rep
, W64 <- width
= unitOL $ FMOV FF64 (regSingle $ fReg 0) r_dest
| not $ isFloatType rep
, W32 <- width
= unitOL $ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest
| not $ isFloatType rep
, W64 <- width
, r_dest_hi <- getHiVRegFromLo r_dest
= toOL [ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest_hi
, mkRegRegMoveInstr platform (regSingle $ oReg 1) r_dest]
| otherwise
= panic "SPARC.CodeGen.GenCCall: no match"
in result
assign_code _ _
= panic "SPARC.CodeGen.GenCCall: no match"
-- | Generate a call to implement an out-of-line floating point operation
outOfLineMachOp
:: CallishMachOp
-> NatM (Either CLabel CmmExpr)
outOfLineMachOp mop
= do let functionName
= outOfLineMachOp_table mop
dflags <- getDynFlags
mopExpr <- cmmMakeDynamicReference dflags CallReference
$ mkForeignLabel functionName Nothing ForeignLabelInExternalPackage IsFunction
let mopLabelOrExpr
= case mopExpr of
CmmLit (CmmLabel lbl) -> Left lbl
_ -> Right mopExpr
return mopLabelOrExpr
-- | Decide what C function to use to implement a CallishMachOp
--
outOfLineMachOp_table
:: CallishMachOp
-> FastString
outOfLineMachOp_table mop
= case mop of
MO_F32_Exp -> fsLit "expf"
MO_F32_Log -> fsLit "logf"
MO_F32_Sqrt -> fsLit "sqrtf"
MO_F32_Pwr -> fsLit "powf"
MO_F32_Sin -> fsLit "sinf"
MO_F32_Cos -> fsLit "cosf"
MO_F32_Tan -> fsLit "tanf"
MO_F32_Asin -> fsLit "asinf"
MO_F32_Acos -> fsLit "acosf"
MO_F32_Atan -> fsLit "atanf"
MO_F32_Sinh -> fsLit "sinhf"
MO_F32_Cosh -> fsLit "coshf"
MO_F32_Tanh -> fsLit "tanhf"
MO_F64_Exp -> fsLit "exp"
MO_F64_Log -> fsLit "log"
MO_F64_Sqrt -> fsLit "sqrt"
MO_F64_Pwr -> fsLit "pow"
MO_F64_Sin -> fsLit "sin"
MO_F64_Cos -> fsLit "cos"
MO_F64_Tan -> fsLit "tan"
MO_F64_Asin -> fsLit "asin"
MO_F64_Acos -> fsLit "acos"
MO_F64_Atan -> fsLit "atan"
MO_F64_Sinh -> fsLit "sinh"
MO_F64_Cosh -> fsLit "cosh"
MO_F64_Tanh -> fsLit "tanh"
MO_UF_Conv w -> fsLit $ word2FloatLabel w
MO_Memcpy -> fsLit "memcpy"
MO_Memset -> fsLit "memset"
MO_Memmove -> fsLit "memmove"
MO_BSwap w -> fsLit $ bSwapLabel w
MO_PopCnt w -> fsLit $ popCntLabel w
MO_Clz w -> fsLit $ clzLabel w
MO_Ctz w -> fsLit $ ctzLabel w
MO_AtomicRMW w amop -> fsLit $ atomicRMWLabel w amop
MO_Cmpxchg w -> fsLit $ cmpxchgLabel w
MO_AtomicRead w -> fsLit $ atomicReadLabel w
MO_AtomicWrite w -> fsLit $ atomicWriteLabel w
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _) -> unsupported
where unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported here")
|
fmthoma/ghc
|
compiler/nativeGen/SPARC/CodeGen.hs
|
bsd-3-clause
| 22,875
| 0
| 29
| 7,602
| 4,673
| 2,320
| 2,353
| 391
| 48
|
module Settings.Builders.HsCpp (hsCppBuilderArgs) where
import Packages
import Settings.Builders.Common
hsCppBuilderArgs :: Args
hsCppBuilderArgs = builder HsCpp ? do
stage <- getStage
root <- getBuildRoot
ghcPath <- expr $ buildPath (vanillaContext stage compiler)
mconcat [ getSettingList HsCppArgs
, arg "-P"
, arg "-Iincludes"
, arg $ "-I" ++ root -/- generatedDir
, arg $ "-I" ++ ghcPath
, arg "-x", arg "c"
, arg =<< getInput ]
|
snowleopard/shaking-up-ghc
|
src/Settings/Builders/HsCpp.hs
|
bsd-3-clause
| 529
| 0
| 12
| 160
| 143
| 74
| 69
| 15
| 1
|
#if __GLASGOW_HASKELL__ < 706
module GHC.IP where
#else
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# OPTIONS_GHC -XNoImplicitPrelude #-}
module GHC.IP (IP(..)) where
import GHC.TypeLits
-- | The syntax @?x :: a@ is desugared into @IP "x" a@
class IP (x :: Symbol) a | x -> a where
ip :: a
#endif
|
beni55/haste-compiler
|
libraries/ghc-7.8/base/GHC/IP.hs
|
bsd-3-clause
| 398
| 1
| 4
| 67
| 10
| 7
| 3
| 1
| 0
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- ----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2006
--
-- Fingerprints for recompilation checking and ABI versioning, and
-- implementing fast comparison of Typeable.
--
-- ----------------------------------------------------------------------------
module GHC.Fingerprint.Type (Fingerprint(..)) where
import GHC.Base
import GHC.List (length, replicate)
import GHC.Num
import GHC.Show
import GHC.Word
import Numeric (showHex)
-- Using 128-bit MD5 fingerprints for now.
data Fingerprint = Fingerprint {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64
deriving (Eq, Ord)
-- | @since 4.7.0.0
instance Show Fingerprint where
show (Fingerprint w1 w2) = hex16 w1 ++ hex16 w2
where
-- | Formats a 64 bit number as 16 digits hex.
hex16 :: Word64 -> String
hex16 i = let hex = showHex i ""
in replicate (16 - length hex) '0' ++ hex
|
olsner/ghc
|
libraries/base/GHC/Fingerprint/Type.hs
|
bsd-3-clause
| 1,002
| 0
| 14
| 181
| 184
| 105
| 79
| 16
| 0
|
-- | A description of the register set of the X86.
--
-- This isn't used directly in GHC proper.
--
-- See RegArchBase.hs for the reference.
-- See MachRegs.hs for the actual trivColorable function used in GHC.
--
module RegAlloc.Graph.ArchX86 (
classOfReg,
regsOfClass,
regName,
regAlias,
worst,
squeese,
) where
import RegAlloc.Graph.ArchBase (Reg(..), RegSub(..), RegClass(..))
import UniqSet
-- | Determine the class of a register
classOfReg :: Reg -> RegClass
classOfReg reg
= case reg of
Reg c _ -> c
RegSub SubL16 _ -> ClassG16
RegSub SubL8 _ -> ClassG8
RegSub SubL8H _ -> ClassG8
-- | Determine all the regs that make up a certain class.
regsOfClass :: RegClass -> UniqSet Reg
regsOfClass c
= case c of
ClassG32
-> mkUniqSet [ Reg ClassG32 i
| i <- [0..7] ]
ClassG16
-> mkUniqSet [ RegSub SubL16 (Reg ClassG32 i)
| i <- [0..7] ]
ClassG8
-> unionUniqSets
(mkUniqSet [ RegSub SubL8 (Reg ClassG32 i) | i <- [0..3] ])
(mkUniqSet [ RegSub SubL8H (Reg ClassG32 i) | i <- [0..3] ])
ClassF64
-> mkUniqSet [ Reg ClassF64 i
| i <- [0..5] ]
-- | Determine the common name of a reg
-- returns Nothing if this reg is not part of the machine.
regName :: Reg -> Maybe String
regName reg
= case reg of
Reg ClassG32 i
| i <= 7-> Just $ [ "eax", "ebx", "ecx", "edx"
, "ebp", "esi", "edi", "esp" ] !! i
RegSub SubL16 (Reg ClassG32 i)
| i <= 7 -> Just $ [ "ax", "bx", "cx", "dx"
, "bp", "si", "di", "sp"] !! i
RegSub SubL8 (Reg ClassG32 i)
| i <= 3 -> Just $ [ "al", "bl", "cl", "dl"] !! i
RegSub SubL8H (Reg ClassG32 i)
| i <= 3 -> Just $ [ "ah", "bh", "ch", "dh"] !! i
_ -> Nothing
-- | Which regs alias what other regs.
regAlias :: Reg -> UniqSet Reg
regAlias reg
= case reg of
-- 32 bit regs alias all of the subregs
Reg ClassG32 i
-- for eax, ebx, ecx, eds
| i <= 3
-> mkUniqSet
$ [ Reg ClassG32 i, RegSub SubL16 reg
, RegSub SubL8 reg, RegSub SubL8H reg ]
-- for esi, edi, esp, ebp
| 4 <= i && i <= 7
-> mkUniqSet
$ [ Reg ClassG32 i, RegSub SubL16 reg ]
-- 16 bit subregs alias the whole reg
RegSub SubL16 r@(Reg ClassG32 _)
-> regAlias r
-- 8 bit subregs alias the 32 and 16, but not the other 8 bit subreg
RegSub SubL8 r@(Reg ClassG32 _)
-> mkUniqSet $ [ r, RegSub SubL16 r, RegSub SubL8 r ]
RegSub SubL8H r@(Reg ClassG32 _)
-> mkUniqSet $ [ r, RegSub SubL16 r, RegSub SubL8H r ]
-- fp
Reg ClassF64 _
-> unitUniqSet reg
_ -> error "regAlias: invalid register"
-- | Optimised versions of RegColorBase.{worst, squeese} specific to x86
worst :: Int -> RegClass -> RegClass -> Int
worst n classN classC
= case classN of
ClassG32
-> case classC of
ClassG32 -> min n 8
ClassG16 -> min n 8
ClassG8 -> min n 4
ClassF64 -> 0
ClassG16
-> case classC of
ClassG32 -> min n 8
ClassG16 -> min n 8
ClassG8 -> min n 4
ClassF64 -> 0
ClassG8
-> case classC of
ClassG32 -> min (n*2) 8
ClassG16 -> min (n*2) 8
ClassG8 -> min n 8
ClassF64 -> 0
ClassF64
-> case classC of
ClassF64 -> min n 6
_ -> 0
squeese :: RegClass -> [(Int, RegClass)] -> Int
squeese classN countCs
= sum (map (\(i, classC) -> worst i classN classC) countCs)
|
sgillespie/ghc
|
compiler/nativeGen/RegAlloc/Graph/ArchX86.hs
|
bsd-3-clause
| 4,080
| 0
| 14
| 1,676
| 1,134
| 589
| 545
| 94
| 14
|
{-# LANGUAGE TemplateHaskell #-}
module T11797 where
import Language.Haskell.TH
import System.IO
$(do dec <- [d| class Foo a where
meth :: a -> b -> a |]
runIO $ do putStrLn $ pprint dec
hFlush stdout
return [] )
-- the key bit is the forall b. in the type of the method
|
olsner/ghc
|
testsuite/tests/th/T11797.hs
|
bsd-3-clause
| 319
| 0
| 13
| 101
| 66
| 34
| 32
| 9
| 0
|
module Main where
import GHC
import Packages
import GhcMonad
import Outputable
import System.Environment
import DynFlags
import Module
main =
do [libdir] <- getArgs
_ <- runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
setSessionDynFlags dflags
dflags <- getSessionDynFlags
liftIO $ print (mkModuleName "Outputable" `elem` listVisibleModuleNames dflags)
_ <- runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
setSessionDynFlags (dflags {
packageFlags = [ExposePackage "-package ghc"
(PackageArg "ghc")
(ModRenaming True [])]
})
dflags <- getSessionDynFlags
liftIO $ print (mkModuleName "Outputable" `elem` listVisibleModuleNames dflags)
return ()
|
GaloisInc/halvm-ghc
|
testsuite/tests/ghc-api/T9595.hs
|
bsd-3-clause
| 945
| 0
| 19
| 370
| 217
| 107
| 110
| 24
| 1
|
-- Test for bug #1047
import Control.Concurrent
import Control.Exception
-- This loop spends most of its time printing stuff, and very occasionally
-- executes 'unblock (return ())'. This test ensures that a thread waiting
-- to throwTo this thread is not blocked indefinitely.
loop restore = do restore (return ()); print "alive"; loop restore
main = do tid <- forkIO (mask $ \restore -> loop restore)
yield
killThread tid
|
ryantm/ghc
|
testsuite/tests/concurrent/should_run/conc066.hs
|
bsd-3-clause
| 448
| 0
| 12
| 93
| 90
| 44
| 46
| 6
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Writer.Formats.Unbeast
-- License : MIT (see the LICENSE file)
-- Maintainer : Felix Klein (klein@react.uni-saarland.de)
--
-- Transforms a specification to the Unbeast format.
--
-----------------------------------------------------------------------------
module Writer.Formats.Unbeast where
-----------------------------------------------------------------------------
import Config
import Simplify
import Data.LTL
import Data.Error
import Data.Specification
import Writer.Eval
import Control.Exception
-----------------------------------------------------------------------------
-- | Unbeast format writer.
writeFormat
:: Configuration -> Specification -> Either Error String
writeFormat c s = do
(es,ss,rs,as,is,gs) <- eval c s
us <- mapM (simplify' (c { noRelease = True, noWeak = True })) $
case ss of
[] -> filter (/= FFalse) $ es ++ map fGlobally rs ++ as
_ -> filter (/= FFalse) $ es ++
map (\f -> fOr [fNot $ fAnd ss, f])
(map fGlobally rs ++ as)
vs <- mapM (simplify' (c { noRelease = True, noWeak = True })) $
filter (/= TTrue) $ ss ++ [fGlobally $ fAnd is] ++ gs
(si,so) <- signals c s
return $ main si so us vs
where
main si so as vs =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>"
++ "\n" ++ "<!DOCTYPE SynthesisProblem SYSTEM \""
++ specfile ++ "\">"
++ "\n"
++ "\n" ++ "<!--"
++ "\n" ++ "This specification was automatically created "
++ "from a TLSF specification,"
++ "\n" ++ "using the SyFCo tool."
++ "\n"
++ "\n" ++ "Please consider that default values for the .dtd file "
++ "and the LTL compiler"
++ "\n" ++ "have been used. To change them, you can use the "
++ "'updatePathsInXML.py' script,"
++ "\n" ++ "that is shipped with the Unbeast tool."
++ "\n" ++ "-->"
++ "\n"
++ "\n" ++ "<SynthesisProblem>"
++ "\n" ++ " <Title>" ++ title s ++ "</Title>"
++ "\n" ++ " <Description>"
++ "\n" ++ fixedIndent (description s)
++ "\n" ++ " </Description>"
++ "\n" ++ " <PathToLTLCompiler>" ++ compiler
++ "</PathToLTLCompiler>"
++ "\n" ++ " <GlobalInputs>"
++ concatMap printSignal si
++ "\n" ++ " </GlobalInputs>"
++ "\n" ++ " <GlobalOutputs>"
++ concatMap printSignal so
++ "\n" ++ " </GlobalOutputs>"
++ (if null as then ""
else "\n" ++ " <Assumptions>" ++
concatMap (\x -> "\n <LTL>\n" ++ printFormula 6 x
++ " </LTL>\n") as ++
" </Assumptions>")
++ "\n" ++ " <Specification>"
++ concatMap (\x -> "\n <LTL>\n" ++ printFormula 6 x
++ " </LTL>\n") vs
++ " </Specification>"
++ "\n" ++ "</SynthesisProblem>"
++ "\n"
specfile = "SynSpec.dtd"
compiler = "ltl2ba -f"
fixedIndent str = case str of
[] -> []
(' ':xr) -> fixedIndent xr
('\t':xr) -> fixedIndent xr
('\n':xr) -> fixedIndent xr
_ -> " " ++
concatMap ident (rmLeadingSpace [] False str)
ident chr = case chr of
'\n' -> "\n "
_ -> [chr]
rmLeadingSpace a b str = case str of
[] -> reverse a
('\n':xr) -> rmLeadingSpace ('\n':a) True xr
('\t':xr) ->
if b
then rmLeadingSpace a b xr
else rmLeadingSpace (' ':a) b xr
(' ':xr) ->
if b
then rmLeadingSpace a b xr
else rmLeadingSpace (' ':a) b xr
(x:xr) -> rmLeadingSpace (x:a) False xr
printSignal sig =
"\n <Bit>" ++ sig ++ "</Bit>"
printFormula n f = replicate n ' ' ++ printFormula' (n + 2) f
printFormula' n f = case f of
TTrue -> "<True></True>\n"
FFalse -> "<False></False>\n"
Atomic x -> "<Var>" ++ show x ++ "</Var>\n"
Not x -> "<Not>\n" ++ printFormula n x ++ replicate (n - 2) ' ' ++ "</Not>\n"
Next x -> "<X>\n" ++ printFormula n x ++ replicate (n - 2) ' ' ++ "</X>\n"
Globally x -> "<G>\n" ++ printFormula n x ++ replicate (n - 2) ' ' ++ "</G>\n"
Finally x -> "<F>\n" ++ printFormula n x ++ replicate (n - 2) ' ' ++ "</F>\n"
Or xs -> "<Or>\n" ++ concatMap (printFormula n) xs ++ replicate (n - 2) ' ' ++ "</Or>\n"
And xs -> "<And>\n" ++ concatMap (printFormula n) xs ++ replicate (n - 2) ' ' ++ "</And>\n"
Equiv x y -> "<Iff>\n" ++ printFormula n x ++ printFormula n y ++ replicate (n - 2) ' ' ++ "</Iff>\n"
Until x y -> "<U>\n" ++ printFormula n x ++ printFormula n y ++ replicate (n - 2) ' ' ++ "</U>\n"
_ -> assert False undefined
noImpl fml = case fml of
Implies x y -> Or [Not $ noImpl x, noImpl y]
_ -> applySub noImpl fml
simplify' cc f = do
f' <- simplify cc $ noImpl f
if f' == f then return f else simplify' cc f'
-----------------------------------------------------------------------------
|
reactive-systems/syfco
|
src/lib/Writer/Formats/Unbeast.hs
|
mit
| 5,206
| 0
| 64
| 1,617
| 1,536
| 773
| 763
| 109
| 27
|
module Env (
GlDef(..),
GlEnv(..),
emptyGlEnv,
Env
) where
import Control.Monad.State
import qualified Data.Map as M
import Kinds
import Types
import Expr
{----------------------------------------------------------------------}
{-- Global Environment -}
{----------------------------------------------------------------------}
data GlDef a b = GlDef {
glDef :: a,
glAnn :: b
} deriving Show
{-
The global enviornment contains a list of all definitions and their
inferred types.
-}
data GlEnv = MkGlEnv {
kindEnv :: M.Map String Kind,
typeEnv :: M.Map String (GlDef Type Kind),
valEnv :: M.Map Variable (GlDef Expr Type)
} deriving Show
emptyGlEnv :: GlEnv
emptyGlEnv = MkGlEnv M.empty M.empty M.empty
{-
We use the global environment as state parameter for an instance of the
state monad transformer on top of IO.
-}
type Env = StateT GlEnv IO
|
mbg/system-f-with-kind-polymorphism
|
Env.hs
|
mit
| 968
| 0
| 11
| 247
| 181
| 110
| 71
| 22
| 1
|
module Server(
runServer
) where
runServer = undefined
|
5outh/icy
|
src/Server.hs
|
mit
| 56
| 2
| 5
| 9
| 17
| 10
| 7
| 3
| 1
|
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative ((<$>))
import Control.Arrow (second)
import Control.Monad (forM)
import Control.Monad.IO.Class (liftIO)
import Data.Text (pack, Text, concat)
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Data.Char (toLower)
import Data.Monoid ((<>))
import Graphics.ImageMagick.MagickWand
import Prelude hiding (concat)
import System.Random (randomRIO)
import System.Environment (getArgs)
------------------------------------------------------------------------------------------------
-- | Takes a random element from list
pick :: [a] -> IO a
pick xs = (xs!!) <$> randomRIO (0, length xs - 1)
------------------------------------------------------------------------------------------------
colors = ["black","blue","brown","cyan","gray","green","magenta","orange","pink","red","violet","white","yellow"]
chars = filter (`notElem`("Il"::String)) $ ['a'..'x']++['A'..'X']++['1'..'9']
makeCaptcha :: String -> -- ^ Path to captcha
IO (Text, Text) -- ^ captcha value and hint
makeCaptcha path = withMagickWandGenesis $ localGenesis $ do
(_, w) <- magickWand
(_,dw) <- drawingWand
pw <- pixelWand
let len = 5
space = 12.0 :: Double -- space between characters in px
height = 30 -- image height
fSize = 25 -- font size
newImage w (truncate space*(len+2)) height pw
dw `setFontSize` fSize
w `addNoiseImage` randomNoise
blurImage w 0 1
text <- forM [1..len] $ \i -> do
x <- liftIO (randomRIO (-1.0,1.0) :: IO Double)
y <- liftIO (randomRIO (-2.0,2.0) :: IO Double)
char <- liftIO $ pick chars
color <- liftIO $ pick colors
pw `setColor` color
dw `setStrokeColor` pw
drawAnnotation dw (x+space*(fromIntegral i)) ((fSize :: Double)+y) (pack $ char:[])
return (decodeUtf8 $ color, pack $ (:[]) $ toLower $ char)
drawImage w dw
trimImage w 0
writeImage w $ Just $ pack path
color <- liftIO $ fst <$> pick text
let filteredText = concat $ map snd $ filter ((==color).fst) text
return (filteredText, "<div style='width:50px; height: 30px; display:inline-block; background-color:"<>color<>";'></div>")
------------------------------------------------------------------------------------------------
main = do
putStrLn . show =<< makeCaptcha . head =<< getArgs
|
ahushh/Monaba
|
monaba/captcha/Yoba/Main.hs
|
mit
| 2,673
| 0
| 19
| 742
| 779
| 424
| 355
| 48
| 1
|
module Loop where
import Control.Monad
import Data.STRef
import Control.Monad.ST
forLoop :: i -> (i -> Bool) -> (i -> i) -> (i -> s -> s) -> s -> s
forLoop i0 pred next update s0 = runST $ do
refI <- newSTRef i0
refS <- newSTRef s0
iter refI refS
readSTRef refS
where iter refI refS = do
i <- readSTRef refI
s <- readSTRef refS
when (pred i) $ do
writeSTRef refI $ next i
writeSTRef refS $ update i s
iter refI refS
|
mortum5/programming
|
haskell/usefull/Loop.hs
|
mit
| 499
| 0
| 13
| 169
| 208
| 98
| 110
| -1
| -1
|
{-# LANGUAGE InstanceSigs #-}
module Ch26.ReaderT where
newtype ReaderT r m a = ReaderT {
runReaderT :: r -> m a
}
instance Functor m => Functor (ReaderT r m) where
fmap f (ReaderT rma) = ReaderT $ (fmap . fmap) f rma
instance Applicative m => Applicative (ReaderT r m) where
pure a = ReaderT $ (pure . pure) a
(<*>) (ReaderT f) (ReaderT rma) = ReaderT $ (<*>) <$> f <*> rma
instance Monad m => Monad (ReaderT r m) where
return = pure
(>>=) :: ReaderT r m a -> (a -> ReaderT r m b) -> ReaderT r m b
(>>=) (ReaderT rma) f = ReaderT $ \r -> do
a <- rma r
runReaderT (f a) r
|
andrewMacmurray/haskell-book-solutions
|
src/ch26/ReaderT.hs
|
mit
| 600
| 0
| 12
| 150
| 290
| 151
| 139
| 15
| 0
|
--------------------------------------------------------------------------------
-- Triangular, pentagonal, and hexagonal
-- Problem 45
-- Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
-- Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
-- Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
-- Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
-- It can be verified that T285 = P165 = H143 = 40755.
-- Find the next triangle number that is also pentagonal and hexagonal.
--------------------------------------------------------------------------------
import Math.NumberTheory.Powers.Squares
hex :: Integer -> Integer
hex n = n * (2*n -1)
tri :: Integer -> Integer
tri n = n * (n+1) `div` 2
is_pent :: Integer -> Bool
is_pent x = (isSquare p) && ((mod q 6) == 5)
where
p = (24*x) + 1
q = integerSquareRoot p
solve n
| is_pent $ hex n = (n,hex n,m,tri m)
| True = solve (n+1)
where
m = 2*n -1
main = do
print $ map hex [1..5]
print $ map tri [1..5]
print $ map is_pent [1,5,12,22,35,40755]
print $ solve 2
print $ solve 144
{-
Every hexagonal number is also a triangular number, and of the three
hexagonals increase the fastest. So generate hexagonal number, test if it
is pentagonal, and adjust the subscript to get triangular number.
We will not know the subscript of the pentagonal number, but that is not
required.
-}
|
bertdouglas/euler-haskell
|
001-050/45a.hs
|
mit
| 1,408
| 0
| 9
| 287
| 315
| 168
| 147
| 19
| 1
|
{-# htermination ord :: Char -> Int #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_ord_1.hs
|
mit
| 40
| 0
| 2
| 8
| 3
| 2
| 1
| 1
| 0
|
{-# LANGUAGE RecordWildCards #-}
import Data.Binary
import qualified Data.ByteString as BS
data Unitit = Unitit { unitit :: [Unit]} deriving (Show)
instance Binary Unitit where
put Unitit{..} = do
put unitit
get = do
unitit <- get
return Unitit{..}
data Unit = Unit { name :: String
, ap :: Int
, pp :: Float
, traits :: [Trait]
, team :: Int
, animFrame :: Int
} deriving (Show)
instance Binary Unit where
put Unit{..} = do
put name
put ap
put pp
put traits
put team
put animFrame
get = do
name <- get
ap <- get
pp <- get
traits <- get
team <- get
animFrame <- get
return Unit{..}
data Trait = Trait { traitAp :: Int
, traitPp :: Int
, duration :: Int } deriving (Show)
instance Binary Trait where
put Trait{..} = do
put traitAp
put traitPp
put duration
get = do
traitAp <- get
traitPp <- get
duration <- get
return Trait{..}
data Testi = Testi {nimi :: String, toinenNimi :: String, koko :: Integer} deriving (Show)
instance Binary Testi where
put Testi{..} = do
put nimi
put toinenNimi
put koko
get = do
nimi <- get
toinenNimi <- return "Default"
koko <- get
return Testi{..}
main :: IO ()
main = do
let testi = Testi {nimi="Testi jou jou", toinenNimi = "Jep", koko=500+2^100*5}
let enkoodaus = encode testi
print enkoodaus
let dekoodaus = decode enkoodaus
print (dekoodaus:: Testi)
let traitti1 = Trait{traitAp = 10, traitPp = 10, duration = 5}
let traitti2 = Trait{traitAp = 5, traitPp = 12, duration = 6}
let unitti1 = Unit{name ="Pekka", ap=5, pp=9,traits =[traitti1,traitti2], team = 1,animFrame=0}
let unitti2 = Unit{name ="Matti", ap=5, pp=9,traits =[traitti1,traitti2], team = 1,animFrame=0}
let unitteja = Unitit{unitit = [unitti1, unitti2]}
let unittejenEnkoodaus = encode unitteja
print unittejenEnkoodaus
-- let pituus = length unittejenEnkoodaus
-- print pituus
let unittejenDekoodaus = decode unittejenEnkoodaus
print (unittejenDekoodaus :: Unitit)
|
maqqr/psycho-bongo-fight
|
serialTesti.hs
|
mit
| 2,357
| 0
| 14
| 806
| 816
| 426
| 390
| 73
| 1
|
{-|
Module : Fatorial
Description : example of recursive functions
Copyright : (c) Fabrício Olivetti, 2017
License : GPL-3
Maintainer : fabricio.olivetti@gmail.com
Calculates the fatorial recursively.
-}
module Main where
-- |'fatorial' calculates the fatorial
fatorial :: Integer -> Integer
fatorial 0 = 1
fatorial 1 = 1
fatorial n = n * fatorial (n-1)
-- |'fatorialT' uses tail recursion
fatorialT :: Integer -> Integer
fatorialT 0 = 1
fatorialT 1 = 1
fatorialT n = fatorial' n 1
where
fatorial' 1 r = r
fatorial' n r = fatorial' (n-1) (n*r)
-- |'main' executa programa principal
main :: IO ()
main = do
print (fatorial 10)
print (fatorialT 10)
|
folivetti/BIGDATA
|
02 - Básico/Fatorial.hs
|
mit
| 690
| 2
| 9
| 145
| 172
| 89
| 83
| 15
| 2
|
-- @Author: Zeyuan Shang
-- @Date: 2016-06-01 19:22:05
-- @Last Modified by: Zeyuan Shang
-- @Last Modified time: 2016-06-01 19:54:44
data Tree a = Node a [Tree a]
deriving (Eq, Show)
bottom_up :: Tree a -> [a]
bottom_up (Node x ts) = concatMap bottom_up ts ++ [x]
tree1 = Node 'a' []
tree2 = Node 'a' [Node 'b' []]
tree3 = Node 'a' [Node 'b' [Node 'c' []]]
tree4 = Node 'b' [Node 'd' [], Node 'e' []]
tree5 = Node 'a' [
Node 'f' [Node 'g' []],
Node 'c' [],
Node 'b' [Node 'd' [], Node 'e' []]
]
main = do
let value = bottom_up tree5
print value
|
zeyuanxy/haskell-playground
|
ninety-nine-haskell-problems/vol8/72.hs
|
mit
| 631
| 0
| 10
| 195
| 256
| 130
| 126
| 15
| 1
|
--makeList (a:as) (b:bs) = a^b : (makeList [a] b:bs) ++ (makeList a:as [b]) ++ (makeList as bs)
import Data.List
as = [2..100]
bs = [2..100]
combos = [ (a,b) | a<-as, b<-bs ]
l = map (\(a,b) -> a^b) combos
-- counts unique elements of an ordered list (not counting duplicates)
countUnique [] _ = 0
countUnique (x:xs) prev =
if (x == prev) then countUnique xs prev
else 1 + countUnique xs x
answer = countUnique (sort l) 0
|
gumgl/project-euler
|
29/29.hs
|
mit
| 428
| 4
| 8
| 86
| 164
| 90
| 74
| 10
| 2
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts,
TypeSynonymInstances, FlexibleInstances,
OverloadedStrings, GeneralizedNewtypeDeriving #-}
module Control.Monad.DefinedIdents (
) where
|
antalsz/hs-to-coq
|
src/lib/Control/Monad/DefinedIdents.hs
|
mit
| 220
| 0
| 3
| 44
| 11
| 8
| 3
| 4
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad ( replicateM )
import Network.Transport
import Network.Transport.AMQP
import Network.AMQP
import Test.Tasty
import Test.Tasty.HUnit
import Control.Concurrent
main :: IO ()
main = defaultMain $
testGroup "API tests"
[ testCase "simple" test_simple
--, testCase "connection break" test_connectionBreak
-- , testCase "test multicast" test_multicast
-- , testCase "connect to non existent host" test_nonexists
]
newTransport :: IO Transport
newTransport = do
conn <- openConnection "localhost" "/" "guest" "guest"
let amqpTransport = AMQPParameters conn "simple-multicast" Nothing
createTransport amqpTransport
test_simple :: IO ()
test_simple = do
transport <- newTransport
Right ep1 <- newEndPoint transport
Right ep2 <- newEndPoint transport
Right c1 <- connect ep1 (address ep2) ReliableOrdered defaultConnectHints
Right c2 <- connect ep2 (address ep1) ReliableOrdered defaultConnectHints
Right _ <- send c1 ["123"]
Right _ <- send c2 ["321"]
close c1
close c2
[ConnectionOpened _ ReliableOrdered _, Received _ ["321"], ConnectionClosed _] <- replicateM 3 $ receive ep1
[ConnectionOpened _ ReliableOrdered _, Received _ ["123"], ConnectionClosed _] <- replicateM 3 $ receive ep2
closeTransport transport
test_connectionBreak :: IO ()
test_connectionBreak = do
conn <- openConnection "localhost" "/" "guest" "guest"
let amqpTransport = AMQPParameters conn "simple-multicast" Nothing
(amqp, transport) <- createTransportExposeInternals amqpTransport
Right ep1 <- newEndPoint transport
Right ep2 <- newEndPoint transport
Right ep3 <- newEndPoint transport
Right c21 <- connect ep1 (address ep2) ReliableOrdered defaultConnectHints
Right c22 <- connect ep2 (address ep1) ReliableOrdered defaultConnectHints
Right c23 <- connect ep3 (address ep1) ReliableOrdered defaultConnectHints
ConnectionOpened 1 ReliableOrdered _ <- receive ep2
ConnectionOpened 1 ReliableOrdered _ <- receive ep1
ConnectionOpened 2 ReliableOrdered _ <- receive ep1
breakConnection amqp (address ep1) (address ep2)
ErrorEvent (TransportError (EventConnectionLost _ ) _) <- receive $ ep1
ErrorEvent (TransportError (EventConnectionLost _ ) _) <- receive $ ep2
Left (TransportError SendFailed _) <- send c21 ["test"]
Left (TransportError SendFailed _) <- send c22 ["test"]
p <- send c23 ["test"]
print p
--Left (TransportError SendFailed _) <- send c23 ["test"]
ErrorEvent (TransportError (EventConnectionLost _) _ ) <- receive ep1
Right c24 <- connect ep3 (address ep1) ReliableOrdered defaultConnectHints
Right () <- send c24 ["final"]
ConnectionOpened 3 ReliableOrdered _ <- receive ep1
Received 3 ["final"] <- receive ep1
closeTransport transport
test_multicast :: IO ()
test_multicast = do
conn <- openConnection "localhost" "/" "guest" "guest"
let amqpTransport = AMQPParameters conn "simple-multicast" Nothing
transport <- createTransport amqpTransport
Right ep1 <- newEndPoint transport
Right ep2 <- newEndPoint transport
Right g1 <- newMulticastGroup ep1
multicastSubscribe g1
threadDelay 1000000
multicastSend g1 ["test"]
ReceivedMulticast _ ["test"] <- receive ep1
Right g2 <- resolveMulticastGroup ep2 (multicastAddress g1)
multicastSubscribe g2
threadDelay 100000
multicastSend g2 ["test-2"]
ReceivedMulticast _ ["test-2"] <- receive ep2
ReceivedMulticast _ ["test-2"] <- receive ep1
return ()
test_nonexists :: IO ()
test_nonexists = do
conn <- openConnection "localhost" "/" "guest" "guest"
let amqpTransport = AMQPParameters conn "simple-multicast" Nothing
tr <- createTransport amqpTransport
Right ep <- newEndPoint tr
Left (TransportError ConnectFailed _) <- connect ep (EndPointAddress "tcp://129.0.0.1:7684") ReliableOrdered defaultConnectHints
closeTransport tr
|
iconnect/network-transport-amqp
|
tests/TestAPI.hs
|
mit
| 3,931
| 0
| 12
| 686
| 1,200
| 540
| 660
| 86
| 1
|
module Main where
import Data.List
import Data.Map hiding (map, foldl)
--import Data.Vector
import Data.Char
import Data.Maybe
import Text.Printf
import System.IO
import Control.Monad
-- http://hayoo.fh-wedel.de/?query=replicate
-- create a type Matrix which is just a list of characters
type Matrix = [[Char]]
-- Create a list of 10 characters, which are 10 dots
base_matrix :: Matrix
base_matrix = replicate 10 . replicate 10 $ '.'
-- display the matrix
showMatrix :: Matrix -> String
showMatrix m = unlines . map showRow $ m
where
showRow r = r
printMatrix :: Matrix -> IO ()
printMatrix x = putStrLn (showMatrix x)
{-
[1, 2, 3, 4, 5]
[1,2] [3,4,5]
[1,2] ++ [6] ++ [4,5]
-}
-- input: a list of elements, a single element, an int
-- output: a list of elements
-- xs = list of elements
-- e = element
-- i = int
replaceNth :: [a] -> a -> Int -> [a]
replaceNth xs e i = left ++ [e] ++ (tail right)
where
(left, right) = splitAt i xs
-- input: int tuples, matrix
-- output: new matrix
--
replace :: (Int, Int) -> Matrix -> Matrix
replace (x,y) m = replaceNth m newRow y
where
origRow = m !! y
newRow = replaceNth origRow '0' x
--replace2 :: (Int, Int) -> [Int] -> [Int]
--replace2 (x,y) m = replaceNth (y * 10 + x) '0' m
-- Read the file name and get its contents
read_file :: IO ()
read_file = do
putStrLn "please enter a file name"
fileName <- getLine
fileContents <- readFile fileName
let file_lines = lines fileContents
putStrLn fileContents
let tuples = (read . head $ file_lines :: [(Int, Int)])
{-
let replacedMatrix = flip execState base_matrix $ do
mapM_ (\t -> modify $ replace t) tuples
-}
-- foldl :: (b -> a -> b) -> b -> [a] -> b
-- sum xs = fold (+) 0 xs
-- foldl :: (Matrix -> (Int,Int) -> Matrix) -> Matrix -> [(Int, Int)] -> Matrix
let replacedMatrix = foldl (flip replace) base_matrix tuples
printMatrix replacedMatrix
print "Done."
-- Print out the contents of the file
main :: IO()
main = do
read_file
--let initialMatrix = foldl (flip replace) base_matrix tuples
--printMatrix initialMatrix
|
nadyac/haskell-gol
|
src/gol.hs
|
mit
| 2,207
| 0
| 12
| 562
| 453
| 246
| 207
| 37
| 1
|
module AST where
import System.Exit
import Text.Regex.Posix
import Data.ByteString.Char8 as C
type S = ByteString
-- Keeps both basic and extended here, then selects variant on execution. Just
-- to avoid threading dialects all the way into the parser. (though maybe
-- Trifecta does allow some parser state we can hook into...)
-- Still feels wrong. Maybe this should just be the string, the IR can contain
-- Regex and the IR translation can also have a flag in its monad state for
-- which dialect to compile into.
data RE = RE S Regex Regex
type Label = S
instance Show RE where
show (RE s _ _) = show s
instance Eq RE where
RE s _ _ == RE t _ _ = s == t
instance Ord RE where
compare (RE s _ _) (RE t _ _) = compare s t
re :: S -> Maybe RE
re s | C.null s = Nothing
| otherwise = Just (RE s bre ere)
where bre = makeRegexOpts blankCompOpt defaultExecOpt s
ere = makeRegexOpts compExtended defaultExecOpt s
data Subst = Literal S | BackReference Int | WholeMatch deriving (Ord,Eq,Show)
type Replacement = [Subst]
data SubstType
= SubstFirst
| SubstNth Int
| SubstAll
-- TODO More flags
deriving (Show, Ord, Eq)
data SubstAction
= SActionNone
| SActionPrint Int
| SActionWriteFile S
| SActionExec
deriving (Show, Ord, Eq)
data Address = Line Int | Match (Maybe RE) | EOF | IRQ
deriving (Show, Ord, Eq)
data MaybeAddress
-- Perhaps the "Always" case should not be here since that allows e.g. (NotAddr Always)
= Always
| At Address
| Between Address Address
| NotAddr MaybeAddress
deriving (Show, Ord, Eq)
data Sed = Sed MaybeAddress Cmd deriving (Show, Ord, Eq)
data Cmd
= Block [Sed]
| Fork Sed
| Label Label
| Branch (Maybe Label)
| Test (Maybe Label)
| TestNot (Maybe Label)
| Next Int
| NextA Int
| Print Int
| PrintFirstLine Int
| PrintLiteral Int
| PrintLineNumber Int
-- fork flags are parsed separately to an event address with fork
| Listen Int (Maybe S) Int
| Accept Int Int
| Redirect Int (Maybe Int)
-- s///
| Subst (Maybe RE) Replacement SubstType SubstAction
-- y///
| Trans S S
-- a: append text after this cycle finishes (TODO for this: needs more state)
| Append S
-- i: insert text, outputing it immediately
| Insert S
-- c: replace text in matching address range with new text, restarts cycle
-- every time since we'll clear the pattern space whenever it matches.
| Change S
-- d - clear pattern space and start new cycle
| Delete
-- D - clear until the first newline, then start new cycle
| DeleteFirstLine
-- hH/gG
| Hold (Maybe S)
| HoldA (Maybe S)
| Get (Maybe S)
| GetA (Maybe S)
| Exchange (Maybe S)
| ReadFile S
| WriteFile S
| Message (Maybe S)
-- qQ (print before exit) (exit code)
| Quit Bool ExitCode
-- z
| Clear
deriving (Show, Ord, Eq)
|
olsner/sedition
|
AST.hs
|
mit
| 2,845
| 0
| 9
| 678
| 734
| 410
| 324
| 74
| 1
|
{-# LANGUAGE BangPatterns #-}
import Graphics.Gloss
import Graphics.Gloss.Data.Vector
import System.Random
import Control.Monad
data MassPoint = MassPoint
{ pointPosition, pointVelocity :: {-# UNPACK #-} !Vector
, pointMass :: {-# UNPACK #-} !Float
} deriving (Show, Eq)
data Box = Box
{ boxXMin, boxXMax, boxYMin, boxYMax:: {-# UNPACK #-} !Float }
deriving (Show, Eq)
data Tree
= Tree
{ treeSubs :: [Tree]
, width, height :: {-# UNPACK #-} !Float
, massCenter :: {-# UNPACK #-} !Vector
, totalMass :: {-# UNPACK #-} !Float
, treeBox :: {-# UNPACK #-} !Box
}
deriving (Show, Eq)
main :: IO ()
main = do
world <- randomPoints
simulate (InWindow "BH" (windowSize, windowSize) (0, 0))
white 20 (emptyTree, State [] world True) draw
(\_ _ (_, state) ->
let tree = head $ buildTree (boxForPoints $ points state) (points state) in
(tree, step tree state))
where emptyTree = Tree [] 0 0 (0, 0) 0 (Box 0 0 0 0)
windowSize :: Int
windowSize = 800
data State = State { lastAccel :: [Vector]
, points :: [MassPoint]
, isFirstStep :: Bool
} deriving (Show, Eq)
step :: Tree -> State -> State
step tree !state = State newAccel movedPoints False -- HACK
where newAccel = map (flip accelOf tree) (points state)
lastAccel' = if isFirstStep state then newAccel else lastAccel state
movedPoints = zipWith move (points state) $ zip lastAccel' newAccel
-- | leapfrog integration
{-# INLINE move #-}
move :: MassPoint -> (Vector, Vector) -> MassPoint
move !mp (lastAccel, newAccel) = mp
{ pointPosition = pointPosition mp + mulSV dt (pointVelocity mp) + mulSV (0.5 * dt^2) lastAccel
, pointVelocity = pointVelocity mp + mulSV (0.5 * dt) (lastAccel + newAccel)
}
dt :: Float
dt = 1.0
accelOf :: MassPoint -> Tree -> Vector
accelOf !mp tree
| null (treeSubs tree) =
let !r = sqrt (dotV between between)
!between = massCenter tree - pointPosition mp -- checked
in if r <= radius then (0,0) else mulSV (graviConst * totalMass tree / (eps + r)^2) $ normalizeV between
| isFarAway tree mp = accelOf mp tree { treeSubs = [] }
| otherwise = foldr ((+) . accelOf mp) (0, 0) (treeSubs tree)
graviConst :: Float
graviConst = 1e-2 -- fake
mass :: Float
mass = 100
radius :: Float
radius = 0.1
eps :: Float
eps = 1.0
{-# INLINE isFarAway #-}
isFarAway :: Tree -> MassPoint -> Bool
isFarAway tree !mp = d/r < 1
where
!d = max (width tree) (height tree)
!r = norm (pointPosition mp - massCenter tree)
buildTree :: Box -> [MassPoint] -> [Tree]
buildTree _ [] = []
buildTree box [p] = [Tree [] w h (pointPosition p) (pointMass p) box]
where
!h = boxYMax box - boxYMin box
!w = boxXMin box - boxXMax box
buildTree box ps = [Tree subs w h mc tm box]
where
!h = boxYMax box - boxYMin box
!w = boxXMin box - boxXMax box
subs = concat $ zipWith buildTree subBoxes pss
!pss = foldr (insertPoint subBoxes) (replicate 4 []) ps
insertPoint :: [Box] -> MassPoint -> [[MassPoint]] -> [[MassPoint]]
insertPoint (box':subBoxes') point (pointBox:pointBoxes)
| inBox box' (pointPosition point) = (point:pointBox):pointBoxes
| otherwise = pointBox : insertPoint subBoxes' point pointBoxes
insertPoint [] _ _ = error "bug in box finding"
!subBoxes = splitBox box
!mc = mulSV (1 / tm) $ sum $ map (\pm -> pointMass pm `mulSV` pointPosition pm) ps
!tm = sum $ map pointMass ps
{-# INLINE boxForPoints #-}
boxForPoints :: [MassPoint] -> Box
boxForPoints !ps = Box
(minimum (map (fst . pointPosition) ps))
(maximum (map (fst . pointPosition) ps))
(minimum (map (snd . pointPosition) ps))
(maximum (map (snd . pointPosition) ps))
{-# INLINE inBox #-}
inBox :: Box -> Vector -> Bool
inBox !box !(x, y) =
x >= boxXMin box && x <= boxXMax box &&
y >= boxYMin box && y <= boxYMax box
{-# INLINE splitBox #-}
splitBox :: Box -> [Box]
splitBox !box =
[ Box (boxXMin box) centerX centerY (boxYMax box) -- left top
, Box centerX (boxXMax box) centerY (boxYMax box) -- right top
, Box (boxXMin box) centerX (boxYMin box) centerY -- left botton
, Box centerX (boxXMax box) (boxXMin box) centerY -- right botton
]
where
!w = boxXMax box - boxXMin box
!h = boxYMax box - boxYMin box
!w' = w / 2
!h' = h / 2
!centerX = boxXMin box + w'
!centerY = boxYMin box + h'
randomPoints :: IO [MassPoint]
randomPoints = replicateM 300 $ do
angle <- randomRIO (0, 2*pi)
dist <- randomRIO (0, fromIntegral $ windowSize `div` 2)
let pos = (sin angle * dist, cos angle * dist)
let vel = (0, 0) -- normalizeV (snd pos, -fst pos)
return $ MassPoint pos vel mass
draw :: (Tree, State) -> Picture
draw (tree, state) = Pictures $ drawTree tree : map drawPoint (points state)
drawPoint :: MassPoint -> Picture
drawPoint p = uncurry Translate (pointPosition p) $ Color red $ Circle (4 * fromIntegral windowSize / 800)
drawTree :: Tree -> Picture
drawTree tree =
Pictures $ drawBox (treeBox tree) : map drawTree (treeSubs tree)
drawBox :: Box -> Picture
drawBox !box = Line
[(boxXMin box, boxYMin box), (boxXMax box, boxYMin box),
(boxXMax box, boxYMax box), (boxXMin box, boxYMax box),
(boxXMin box, boxYMin box)]
norm :: Vector -> Float
norm v = sqrt (dotV v v)
|
orion-42/barnes-hut
|
BH.hs
|
mit
| 5,555
| 0
| 18
| 1,477
| 2,165
| 1,113
| 1,052
| 132
| 2
|
{-# LANGUAGE RankNTypes #-}
{-
Copyright (C) 2012-2017 Kacper Bak, Jimmy Liang, Michal Antkiewicz, Paulius Juodisius <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
{- | Transforms an Abstract Syntax Tree (AST) from "Language.Clafer.Front.AbsClafer"
into Intermediate representation (IR) from "Language.Clafer.Intermediate.Intclafer" of a Clafer model.
-}
module Language.Clafer.Intermediate.Desugarer where
import Language.Clafer.Common
import Data.Maybe (fromMaybe)
import Language.Clafer.Front.AbsClafer
import Language.Clafer.Intermediate.Intclafer
-- | Transform the AST into the intermediate representation (IR)
desugarModule :: Maybe String -> Module -> IModule
desugarModule mURL (Module _ declarations) = IModule
(fromMaybe "" mURL)
(declarations >>= desugarEnums >>= desugarDeclaration)
sugarModule :: IModule -> Module
sugarModule x = Module noSpan $ map sugarDeclaration $ _mDecls x -- (fragments x >>= mDecls)
-- | desugars enumeration to abstract and global singleton features
desugarEnums :: Declaration -> [Declaration]
desugarEnums (EnumDecl (Span p1 p2) id' enumids) = absEnum : map mkEnum enumids
where
p2' = case enumids of
-- the abstract enum clafer should end before the first literal begins
((EnumIdIdent (Span (Pos y' x') _) _):_) -> Pos y' (x'-3) -- cutting the ' = '
[] -> p2 -- should never happen - cannot have enum without any literals. Return the original end pos.
oneToOne pos' = (CardInterval noSpan $
NCard noSpan (PosInteger (pos', "1")) (ExIntegerNum noSpan $ PosInteger (pos', "1")))
absEnum = let
s1 = Span p1 p2'
in
ElementDecl s1 $
Subclafer s1 $
Clafer s1 (Abstract s1) (GCardEmpty s1) id' (SuperEmpty s1) (ReferenceEmpty s1) (CardEmpty s1) (InitEmpty s1) (ElementsList s1 [])
mkEnum (EnumIdIdent s2 eId) = -- each concrete clafer must fit within the original span of the literal
ElementDecl s2 $
Subclafer s2 $
Clafer s2 (AbstractEmpty s2) (GCardEmpty s2) eId ((SuperSome s2) (ClaferId s2 $ Path s2 [ModIdIdent s2 id'])) (ReferenceEmpty s2) (oneToOne (0, 0)) (InitEmpty s2) (ElementsList s2 [])
desugarEnums x = [x]
desugarDeclaration :: Declaration -> [IElement]
desugarDeclaration (ElementDecl _ element) = desugarElement element
desugarDeclaration _ = error "Desugarer.desugarDeclaration: enum declarations should have already been converted to clafers. BUG."
sugarDeclaration :: IElement -> Declaration
sugarDeclaration (IEClafer clafer) = ElementDecl (_cinPos clafer) $ Subclafer (_cinPos clafer) $ sugarClafer clafer
sugarDeclaration (IEConstraint True constraint) =
ElementDecl (_inPos constraint) $ Subconstraint (_inPos constraint) $ sugarConstraint constraint
sugarDeclaration (IEConstraint False assertion) =
ElementDecl (_inPos assertion) $ SubAssertion (_inPos assertion) $ sugarAssertion assertion
sugarDeclaration (IEGoal isMaximize' goal) = ElementDecl (_inPos goal) $ Subgoal (_inPos goal) $ sugarGoal goal isMaximize'
desugarClafer :: Clafer -> [IElement]
desugarClafer claf@(Clafer s abstract gcrd' id' super' reference' crd' init' elements') =
case (super', reference') of
(SuperSome ss setExp, ReferenceEmpty _) -> if isPrimitive $ getPExpClaferIdent setExp
then desugarClafer (Clafer s abstract gcrd' id' (SuperEmpty s) (ReferenceSet ss setExp) crd' init' elements')
else desugarClafer' claf
(SuperSome _ setExp, ReferenceSet _ _) -> if isPrimitive $ getPExpClaferIdent setExp
then error "Desugarer: cannot rewrite : with primitive type into -> because a reference is also present. Using : with primitive types is discouraged."
else desugarClafer' claf
(SuperSome _ setExp, ReferenceBag _ _) -> if isPrimitive $ getPExpClaferIdent setExp
then error "Desugarer: cannot rewrite : with primitive type into -> because a reference is also present. Using : with primitive types is discouraged."
else desugarClafer' claf
_ -> desugarClafer' claf
where
desugarClafer' (Clafer s'' abstract'' gcrd'' id'' super'' reference'' crd'' init'' elements'') =
(IEClafer $ IClafer s'' (desugarAbstract abstract'') (desugarGCard gcrd'') (transIdent id'')
"" "" (desugarSuper super'') (desugarReference reference'') (desugarCard crd'') (0, -1)
(desugarElements elements'')) : (desugarInit id'' init'')
getPExpClaferIdent :: Exp -> String
getPExpClaferIdent (ClaferId _ (Path _ [ (ModIdIdent _ pident') ] )) = transIdent pident'
getPExpClaferIdent (EJoin _ _ e2) = getPExpClaferIdent e2
getPExpClaferIdent _ = error "Desugarer:getPExpClaferIdent not given a ClaferId PExp"
sugarClafer :: IClafer -> Clafer
sugarClafer (IClafer s abstract gcard' _ uid' _ super' reference' crd' _ elements') =
Clafer s (sugarAbstract abstract) (sugarGCard gcard') (mkIdent uid')
(sugarSuper super') (sugarReference reference') (sugarCard crd') (InitEmpty s) (sugarElements elements')
desugarSuper :: Super -> Maybe PExp
desugarSuper (SuperEmpty _) = Nothing
desugarSuper (SuperSome _ (ClaferId _ (Path _ [ (ModIdIdent _ (PosIdent (_, "clafer"))) ] ))) = Nothing
desugarSuper (SuperSome _ setexp) = Just $ desugarExp setexp
desugarReference :: Reference -> Maybe IReference
desugarReference (ReferenceEmpty _) = Nothing
desugarReference (ReferenceSet _ setexp) = Just $ IReference True $ desugarExp setexp
desugarReference (ReferenceBag _ setexp) = Just $ IReference False $ desugarExp setexp
desugarInit :: PosIdent -> Init -> [IElement]
desugarInit _ (InitEmpty _) = []
desugarInit id' (InitSome s inithow exp') = [ IEConstraint (desugarInitHow inithow) (pExpDefPid s implIExp) ]
where
cId :: PExp
cId = mkPLClaferId (getSpan id') (snd $ getIdent id') False Nothing
-- <id> = <exp'>
assignIExp :: IExp
assignIExp = (IFunExp "=" [cId, desugarExp exp'])
-- some <id> => <assignIExp>
implIExp :: IExp
implIExp = (IFunExp "=>" [ pExpDefPid s $ IDeclPExp ISome [] cId, pExpDefPid s assignIExp ])
getIdent (PosIdent y) = y
desugarInitHow :: InitHow -> Bool
desugarInitHow (InitConstant _) = True
desugarInitHow (InitDefault _ )= False
desugarName :: Name -> IExp
desugarName (Path _ path) =
IClaferId (concatMap ((++ modSep).desugarModId) (init path))
(desugarModId $ last path) True Nothing
desugarModId :: ModId -> Result
desugarModId (ModIdIdent _ id') = transIdent id'
sugarModId :: String -> ModId
sugarModId modid = ModIdIdent noSpan $ mkIdent modid
sugarSuper :: Maybe PExp -> Super
sugarSuper Nothing = SuperEmpty noSpan
sugarSuper (Just pexp') = SuperSome noSpan (sugarExp pexp')
sugarReference :: Maybe IReference -> Reference
sugarReference Nothing = ReferenceEmpty noSpan
sugarReference (Just (IReference True pexp')) = ReferenceSet noSpan (sugarExp pexp')
sugarReference (Just (IReference False pexp')) = ReferenceBag noSpan (sugarExp pexp')
sugarInitHow :: Bool -> InitHow
sugarInitHow True = InitConstant noSpan
sugarInitHow False = InitDefault noSpan
desugarConstraint :: Constraint -> PExp
desugarConstraint (Constraint _ exps') = desugarPath $ desugarExp $
(if length exps' > 1 then foldl1 (EAnd noSpan) else head) exps'
desugarAssertion :: Assertion -> PExp
desugarAssertion (Assertion _ exps') = desugarPath $ desugarExp $
(if length exps' > 1 then foldl1 (EAnd noSpan) else head) exps'
desugarGoal :: Goal -> IElement
desugarGoal (GoalMinimize s [exp']) = mkMinimizeMaximizePExp False s exp'
desugarGoal (GoalMinDeprecated s [exp']) = mkMinimizeMaximizePExp False s exp'
desugarGoal (GoalMaximize s [exp']) = mkMinimizeMaximizePExp True s exp'
desugarGoal (GoalMaxDeprecated s [exp']) = mkMinimizeMaximizePExp True s exp'
desugarGoal goal = error $ "Desugarer.desugarGoal: malformed objective:\n" ++ show goal
mkMinimizeMaximizePExp :: Bool -> Span -> Exp -> IElement
mkMinimizeMaximizePExp isMaximize' s exp' =
IEGoal isMaximize' $ desugarPath $ PExp Nothing "" s $ IFunExp (if isMaximize' then iMaximize else iMinimize) [desugarExp exp']
sugarConstraint :: PExp -> Constraint
sugarConstraint pexp = Constraint (_inPos pexp) $ map sugarExp [pexp]
sugarAssertion :: PExp -> Assertion
sugarAssertion pexp = Assertion (_inPos pexp) $ map sugarExp [pexp]
sugarGoal :: PExp -> Bool -> Goal
sugarGoal PExp{_exp=IFunExp _ [pexp]} True = GoalMaximize (_inPos pexp) $ map sugarExp [pexp]
sugarGoal PExp{_exp=IFunExp _ [pexp]} False = GoalMinimize (_inPos pexp) $ map sugarExp [pexp]
sugarGoal goal _ = error $ "Desugarer.sugarGoal: malformed objective:\n" ++ show goal
desugarAbstract :: Abstract -> Bool
desugarAbstract (AbstractEmpty _) = False
desugarAbstract (Abstract _) = True
sugarAbstract :: Bool -> Abstract
sugarAbstract False = AbstractEmpty noSpan
sugarAbstract True = Abstract noSpan
desugarElements :: Elements -> [IElement]
desugarElements (ElementsEmpty _) = []
desugarElements (ElementsList _ es) = es >>= desugarElement
sugarElements :: [IElement] -> Elements
sugarElements x = ElementsList noSpan $ map sugarElement x
desugarElement :: Element -> [IElement]
desugarElement x = case x of
Subclafer _ claf -> (desugarClafer claf)
ClaferUse s name crd es -> desugarClafer $ Clafer s
(AbstractEmpty s) (GCardEmpty s) (mkIdent $ _sident $ desugarName name)
(SuperSome s (ClaferId s name)) (ReferenceEmpty s) crd (InitEmpty s) es
Subconstraint _ constraint ->
[IEConstraint True $ desugarConstraint constraint]
SubAssertion _ assertion ->
[IEConstraint False $ desugarAssertion assertion]
Subgoal _ goal -> [desugarGoal goal]
sugarElement :: IElement -> Element
sugarElement x = case x of
IEClafer claf -> Subclafer noSpan $ sugarClafer claf
IEConstraint True constraint -> Subconstraint noSpan $ sugarConstraint constraint
IEConstraint False assertion -> SubAssertion noSpan $ sugarAssertion assertion
IEGoal isMaximize' goal -> Subgoal noSpan $ sugarGoal goal isMaximize'
desugarGCard :: GCard -> Maybe IGCard
desugarGCard x = case x of
GCardEmpty _ -> Nothing
GCardXor _ -> Just $ IGCard True (1, 1)
GCardOr _ -> Just $ IGCard True (1, -1)
GCardMux _ -> Just $ IGCard True (0, 1)
GCardOpt _ -> Just $ IGCard True (0, -1)
GCardInterval _ ncard ->
Just $ IGCard (isOptionalDef ncard) $ desugarNCard ncard
isOptionalDef :: NCard -> Bool
isOptionalDef (NCard _ m n) = ((0::Integer) == mkInteger m) && (not $ isExIntegerAst n)
isExIntegerAst :: ExInteger -> Bool
isExIntegerAst (ExIntegerAst _) = True
isExIntegerAst _ = False
sugarGCard :: Maybe IGCard -> GCard
sugarGCard x = case x of
Nothing -> GCardEmpty noSpan
Just (IGCard _ (i, ex)) -> GCardInterval noSpan $ NCard noSpan (PosInteger ((0, 0), show i)) (sugarExInteger ex)
desugarCard :: Card -> Maybe Interval
desugarCard x = case x of
CardEmpty _ -> Nothing
CardLone _ -> Just (0, 1)
CardSome _ -> Just (1, -1)
CardAny _ -> Just (0, -1)
CardNum _ n -> Just (mkInteger n, mkInteger n)
CardInterval _ ncard -> Just $ desugarNCard ncard
desugarNCard :: NCard -> (Integer, Integer)
desugarNCard (NCard _ i ex) = (mkInteger i, desugarExInteger ex)
desugarExInteger :: ExInteger -> Integer
desugarExInteger (ExIntegerAst _) = -1
desugarExInteger (ExIntegerNum _ n) = mkInteger n
sugarCard :: Maybe Interval -> Card
sugarCard x = case x of
Nothing -> CardEmpty noSpan
Just (i, ex) ->
CardInterval noSpan $ NCard noSpan (PosInteger ((0, 0), show i)) (sugarExInteger ex)
sugarExInteger :: Integer -> ExInteger
sugarExInteger n = if n == -1 then ExIntegerAst noSpan else (ExIntegerNum noSpan $ PosInteger ((0, 0), show n))
desugarExp :: Exp -> PExp
desugarExp x = pExpDefPid (getSpan x) $ desugarExp' x
desugarExp' :: Exp -> IExp
desugarExp' x = case x of
EDeclAllDisj _ decl exp' ->
IDeclPExp IAll [desugarDecl True decl] (dpe exp')
EDeclAll _ decl exp' -> IDeclPExp IAll [desugarDecl False decl] (dpe exp')
EDeclQuantDisj _ quant' decl exp' ->
IDeclPExp (desugarQuant quant') [desugarDecl True decl] (dpe exp')
EDeclQuant _ quant' decl exp' ->
IDeclPExp (desugarQuant quant') [desugarDecl False decl] (dpe exp')
EIff _ exp0 exp' -> dop iIff [exp0, exp']
EImplies _ exp0 exp' -> dop iImpl [exp0, exp']
EImpliesElse _ exp0 exp1 exp' -> dop iIfThenElse [exp0, exp1, exp']
EOr _ exp0 exp' -> dop iOr [exp0, exp']
EXor _ exp0 exp' -> dop iXor [exp0, exp']
EAnd _ exp0 exp' -> dop iAnd [exp0, exp']
ENeg _ exp' -> dop iNot [exp']
EQuantExp _ quant' exp' ->
IDeclPExp (desugarQuant quant') [] (desugarExp exp')
ELt _ exp0 exp' -> dop iLt [exp0, exp']
EGt _ exp0 exp' -> dop iGt [exp0, exp']
EEq _ exp0 exp' -> dop iEq [exp0, exp']
ELte _ exp0 exp' -> dop iLte [exp0, exp']
EGte _ exp0 exp' -> dop iGte [exp0, exp']
ENeq _ exp0 exp' -> dop iNeq [exp0, exp']
EIn _ exp0 exp' -> dop iIn [exp0, exp']
ENin _ exp0 exp' -> dop iNin [exp0, exp']
EAdd _ exp0 exp' -> dop iPlus [exp0, exp']
ESub _ exp0 exp' -> dop iSub [exp0, exp']
EMul _ exp0 exp' -> dop iMul [exp0, exp']
EDiv _ exp0 exp' -> dop iDiv [exp0, exp']
ERem _ exp0 exp' -> dop iRem [exp0, exp']
ECard _ exp' -> dop iCSet [exp']
ESum _ exp' -> dop iSumSet [exp']
EProd _ exp' -> dop iProdSet [exp']
EMinExp _ exp' -> dop iMin [exp']
EGMax _ exp' -> dop iMaximum [exp']
EGMin _ exp' -> dop iMinimum [exp']
EInt _ n -> IInt $ mkInteger n
EDouble _ (PosDouble n) -> IDouble $ read $ snd n
EReal _ (PosReal n) -> IReal $ read $ snd n
EStr _ (PosString str) -> IStr $ snd str
EUnion _ exp0 exp' -> dop iUnion [exp0, exp']
EUnionCom _ exp0 exp' -> dop iUnion [exp0, exp']
EDifference _ exp0 exp' -> dop iDifference [exp0, exp']
EIntersection _ exp0 exp' -> dop iIntersection [exp0, exp']
EIntersectionDeprecated _ exp0 exp' -> dop iIntersection [exp0, exp']
EDomain _ exp0 exp' -> dop iDomain [exp0, exp']
ERange _ exp0 exp' -> dop iRange [exp0, exp']
EJoin _ exp0 exp' -> dop iJoin [exp0, exp']
ClaferId _ name -> desugarName name
where
dop = desugarOp desugarExp
dpe = desugarPath.desugarExp
desugarOp :: (a -> PExp) -> String -> [a] -> IExp
desugarOp f op' exps' =
if (op' == iIfThenElse)
then IFunExp op' $ (desugarPath $ head mappedList) : (map reducePExp $ tail mappedList)
else IFunExp op' $ map (trans.f) exps'
where
mappedList = map f exps'
trans = if op' `elem` ([iNot, iIfThenElse] ++ logBinOps)
then desugarPath else id
sugarExp :: PExp -> Exp
sugarExp x = sugarExp' $ _exp x
sugarExp' :: IExp -> Exp
sugarExp' x = case x of
IDeclPExp quant' [] pexp -> EQuantExp noSpan (sugarQuant quant') (sugarExp pexp)
IDeclPExp IAll (decl@(IDecl True _ _):[]) pexp ->
EDeclAllDisj noSpan (sugarDecl decl) (sugarExp pexp)
IDeclPExp IAll (decl@(IDecl False _ _):[]) pexp ->
EDeclAll noSpan (sugarDecl decl) (sugarExp pexp)
IDeclPExp quant' (decl@(IDecl True _ _):[]) pexp ->
EDeclQuantDisj noSpan (sugarQuant quant') (sugarDecl decl) (sugarExp pexp)
IDeclPExp quant' (decl@(IDecl False _ _):[]) pexp ->
EDeclQuant noSpan (sugarQuant quant') (sugarDecl decl) (sugarExp pexp)
IClaferId "" id' _ _ -> ClaferId noSpan $ Path noSpan [ModIdIdent noSpan $ mkIdent id']
IClaferId modName' id' _ _ -> ClaferId noSpan $ Path noSpan $ (sugarModId modName') : [sugarModId id']
IInt n -> EInt noSpan $ PosInteger ((0, 0), show n)
IDouble n -> EDouble noSpan $ PosDouble ((0, 0), show n)
IReal n -> EReal noSpan $ PosReal ((0, 0), show n)
IStr str -> EStr noSpan $ PosString ((0, 0), str)
IFunExp op' exps' ->
if op' `elem` unOps then (sugarUnOp op') (exps''!!0)
else if op' `elem` binOps then (sugarOp op') (exps''!!0) (exps''!!1)
else (sugarTerOp op') (exps''!!0) (exps''!!1) (exps''!!2)
where
exps'' = map sugarExp exps'
x' -> error $ "Desugarer.sugarExp': invalid argument: " ++ show x' -- This should never happen
where
sugarUnOp op''
| op'' == iNot = ENeg noSpan
| op'' == iCSet = ECard noSpan
| op'' == iMin = EMinExp noSpan
| op'' == iMaximum = EGMax noSpan
| op'' == iMinimum = EGMin noSpan
| op'' == iSumSet = ESum noSpan
| op'' == iProdSet = EProd noSpan
| otherwise = error $ show op'' ++ "is not an op"
sugarOp op''
| op'' == iIff = EIff noSpan
| op'' == iImpl = EImplies noSpan
| op'' == iOr = EOr noSpan
| op'' == iXor = EXor noSpan
| op'' == iAnd = EAnd noSpan
| op'' == iLt = ELt noSpan
| op'' == iGt = EGt noSpan
| op'' == iEq = EEq noSpan
| op'' == iLte = ELte noSpan
| op'' == iGte = EGte noSpan
| op'' == iNeq = ENeq noSpan
| op'' == iIn = EIn noSpan
| op'' == iNin = ENin noSpan
| op'' == iPlus = EAdd noSpan
| op'' == iSub = ESub noSpan
| op'' == iMul = EMul noSpan
| op'' == iDiv = EDiv noSpan
| op'' == iRem = ERem noSpan
| op'' == iUnion = EUnion noSpan
| op'' == iDifference = EDifference noSpan
| op'' == iIntersection = EIntersection noSpan
| op'' == iDomain = EDomain noSpan
| op'' == iRange = ERange noSpan
| op'' == iJoin = EJoin noSpan
| otherwise = error $ show op'' ++ "is not an op"
sugarTerOp op''
| op'' == iIfThenElse = EImpliesElse noSpan
| otherwise = error $ show op'' ++ "is not an op"
desugarPath :: PExp -> PExp
desugarPath (PExp iType' pid' pos' x) = reducePExp $ PExp iType' pid' pos' result
where
result
| isSetExp x = IDeclPExp ISome [] (pExpDefPid pos' x)
| isNegSome x = IDeclPExp INo [] $ _bpexp $ _exp $ head $ _exps x
| otherwise = x
isNegSome (IFunExp op' [PExp _ _ _ (IDeclPExp ISome [] _)]) = op' == iNot
isNegSome _ = False
isSetExp :: IExp -> Bool
isSetExp (IClaferId _ _ _ _) = True
isSetExp (IFunExp op' _) = op' `elem` setBinOps
isSetExp _ = False
-- reduce parent
reducePExp :: PExp -> PExp
reducePExp (PExp t pid' pos' x) = PExp t pid' pos' $ reduceIExp x
reduceIExp :: IExp -> IExp
reduceIExp (IDeclPExp quant' decls' pexp) = IDeclPExp quant' decls' $ reducePExp pexp
reduceIExp (IFunExp op' exps') = redNav $ IFunExp op' $ map redExps exps'
where
(redNav, redExps) = if op' == iJoin then (reduceNav, id) else (id, reducePExp)
reduceIExp x = x
reduceNav :: IExp -> IExp
reduceNav x@(IFunExp op' exps'@((PExp _ _ _ iexp@(IFunExp _ (pexp0:pexp:_))):pPexp:_)) =
if op' == iJoin && isParent pPexp && isClaferName pexp
then reduceNav $ _exp pexp0
else x{_exps = (head exps'){_exp = reduceIExp iexp} :
tail exps'}
reduceNav x = x
desugarDecl :: Bool -> Decl -> IDecl
desugarDecl isDisj' (Decl _ locids exp') =
IDecl isDisj' (map desugarLocId locids) (desugarExp exp')
sugarDecl :: IDecl -> Decl
sugarDecl (IDecl _ locids exp') =
Decl noSpan (map sugarLocId locids) (sugarExp exp')
desugarLocId :: LocId -> String
desugarLocId (LocIdIdent _ id') = transIdent id'
sugarLocId :: String -> LocId
sugarLocId x = LocIdIdent noSpan $ mkIdent x
desugarQuant :: Quant -> IQuant
desugarQuant (QuantNo _) = INo
desugarQuant (QuantNot _) = INo
desugarQuant (QuantLone _) = ILone
desugarQuant (QuantOne _) = IOne
desugarQuant (QuantSome _) = ISome
sugarQuant :: IQuant -> Quant
sugarQuant INo = QuantNo noSpan -- will never sugar to QuantNOT
sugarQuant ILone = QuantLone noSpan
sugarQuant IOne = QuantOne noSpan
sugarQuant ISome = QuantSome noSpan
sugarQuant IAll = error "sugarQaunt was called on IAll, this is not allowed!" --Should never happen
|
juodaspaulius/clafer
|
src/Language/Clafer/Intermediate/Desugarer.hs
|
mit
| 20,870
| 0
| 19
| 4,530
| 7,164
| 3,547
| 3,617
| 365
| 44
|
-- -*- mode: haskell -*-
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Control.Stud_Aufg.Typ where
import Control.Types
import Autolib.Reader
import Autolib.ToDoc
import Data.Typeable
-- | das sollte exactly das sein, was auch in DB-tabelle steht
data Stud_Aufg =
Stud_Aufg { snr :: SNr
, anr :: ANr
, ok :: Oks
, no :: Nos
-- ignored: size, scoretime
, instant :: Maybe File
, result :: Maybe Wert
, input :: Maybe File
, report :: Maybe File
}
deriving ( Eq, Ord, Typeable )
$(derives [makeReader, makeToDoc] [''Stud_Aufg])
|
Erdwolf/autotool-bonn
|
src/Control/Stud_Aufg/Typ.hs
|
gpl-2.0
| 638
| 3
| 10
| 186
| 132
| 83
| 49
| 17
| 0
|
{-# LANGUAGE Haskell2010 #-}
module Simplex.Parser (
lex, parse,
Token(..), Block(..), Document (Document),
Table, Cell(..), CellType(..), RowType(..),
Items(..), ItemType(..), TableOpt(..),
loadIncludes, loadHashbangs, newTableOpt
) where
import Simplex.Util
import Data.List (intersperse, elemIndex)
import Data.Char (isAlpha, isDigit, isLower, isUpper)
import Data.Maybe
import Control.Exception
import Prelude hiding (lex)
data Block =
BAny String String
| BParagraph String
| BSection String
| BSubsection String
| BSubsubsection String
| BChapter String
| BPart String
| BDefine String String
| BRemark String String
| BVerbatim String String
| BImport String String
| BAdvise [String]
| BItems Items
| BDescription [(String, String)]
| BDescribeItems [(String, String)]
| BLine
| BTable Table
| BCommand String [String]
deriving (Eq, Show)
data TableOpt = TableOpt {
tableDef :: String,
tableX :: Bool,
tableCaptionTop :: Maybe String,
tableCaptionBottom :: Maybe String
} deriving (Eq, Show)
newTableOpt = TableOpt {
tableDef = "",
tableX = False,
tableCaptionTop = Nothing,
tableCaptionBottom = Nothing
}
type Table = (TableOpt, [(RowType, [(Cell, String)])])
data ItemType = Enumerate | Itemize
deriving (Eq, Show)
data Items = Item String | Items ItemType [Items]
deriving (Eq, Show)
data Cell = Cell (Maybe String) (Maybe Char) Int Int Bool Bool CellType
deriving (Eq, Show)
data CellType = Default | Math | Verb | Head
deriving (Eq, Show)
data RowType = NoBorder | SingleBorder | DoubleBorder
deriving (Eq, Show)
data Document = Document [Block] [(String, String)]
deriving (Eq, Show)
data Token = TControl String | TBlock String | TCommand String [String]
deriving (Eq, Show)
data State = SStart | SNewline | SControl | SControlAfter | SSymbol | SSpace | SCommand
deriving (Eq, Show)
isBlock (TBlock _) = True
isBlock _ = False
parse :: [Token] -> Document
parse = parse' $ Document [] []
parse' :: Document -> [Token] -> Document
parse' (Document blocks prop) s@(TControl ('@':cs) : TBlock b : xs)
= parse' (Document blocks ((cs, b):prop)) xs
parse' doc s@(TCommand cmd args : xs)
= upd doc xs $ BCommand cmd args
parse' doc s@(TControl ('.':cs@(_:_)) : xs)
= let (b, bs) = break (not.isBlock) xs
concat' = concat . intersperse "\n\n"
in upd doc bs $ BVerbatim cs $ concat' $ map (\(TBlock x) -> x) b
parse' doc s@(TControl c@('>':_) : xs)
= let (t, r) = parseTable s in upd doc r $ BTable t
parse' doc s@(TControl c : TBlock b : xs)
= case c of
"." -> upd doc xs $ BParagraph b
"=" -> upd doc xs $ BSection b
"==" -> upd doc xs $ BSubsection b
"===" -> upd doc xs $ BSubsubsection b
"!!" -> upd doc xs $ BChapter b
"!!!" -> upd doc xs $ BPart b
":=" -> upd doc xs $ mkDefine b
":-" -> upd doc xs $ mkRemark b
"*" -> let (l, r) = parseItems s in upd doc r $ BItems l
"+" -> let (l, r) = parseItems s in upd doc r $ BItems l
"-" -> let (l, r) = parseItems s in upd doc r $ BItems l
":" -> let (l, r) = parseDescription s in upd doc r $ BDescription l
"::" -> let (l, r) = parseDescribeItems s in upd doc r $ BDescribeItems l
"->" -> let (l, r) = parseAdvise s in upd doc r $ BAdvise l
_ -> upd doc xs $ BAny c b
parse' doc (TBlock b : xs)
= upd doc xs $ BParagraph b
parse' (Document blocks prop) []
= Document (reverse blocks) prop
mkDefine :: String -> Block
mkDefine xs
= let (w, rs) = splitHead xs
in BDefine w rs
mkRemark :: String -> Block
mkRemark xs
= let (w, rs) = splitHead xs
in BRemark w rs
splitHead [] = ("", "")
splitHead (':':xs) = ("", xs)
splitHead ('\\':':':xs) = (':':x', xs')
where (x', xs') = splitHead xs
splitHead (x:xs) = (x:x', xs')
where (x', xs') = splitHead xs
upd :: Document -> [Token] -> Block -> Document
upd (Document blocks prop) xs block = parse' (Document (block:blocks) prop) xs
parseAdvise :: [Token] -> ([String], [Token])
parseAdvise (TControl "->" : TBlock b : xs)
= let (l, r) = parseAdvise xs
in (b:l, r)
parseAdvise xs = ([], xs)
parseDescription :: [Token] -> ([(String, String)], [Token])
parseDescription (TControl ":" : TBlock b : xs)
= let (l, r) = parseDescription xs
in ((parseItem b):l, r)
parseDescription xs = ([], xs)
parseDescribeItems :: [Token] -> ([(String, String)], [Token])
parseDescribeItems (TControl "::" : TBlock b : xs)
= let (l, r) = parseDescribeItems xs
in ((parseItem b):l, r)
parseDescribeItems xs = ([], xs)
parseItems :: [Token] -> (Items, [Token])
parseItems (TControl "*" : TBlock b : xs) = parseIt [Items Itemize [Item b]] xs
parseItems (TControl "+" : TBlock b : xs) = parseIt [Items Enumerate [Item b]] xs
parseIt [Items t it, Items Itemize is] s@(TControl "*" : TBlock b : xs)
= parseIt [Items Itemize $ Item b:Items t (reverse it):is] xs
parseIt [Items Itemize is] s@(TControl "*" : TBlock b : xs)
= parseIt [Items Itemize $ Item b:is] xs
parseIt [ix] s@(TControl "**" : TBlock b : xs)
= parseIt [Items Itemize [Item b], ix] xs
parseIt (Items Itemize is : ix) s@(TControl "**" : TBlock b : xs)
= parseIt (Items Itemize (Item b:is) : ix) xs
parseIt [Items t it, Items Enumerate is] s@(TControl [x] : TBlock b : xs)
| elem x "+-" = parseIt [Items Enumerate $ Item b:Items t (reverse it):is] xs
parseIt [Items Enumerate is] s@(TControl [x] : TBlock b : xs)
| elem x "+-" = parseIt [Items Enumerate $ Item b:is] xs
parseIt [ix] s@(TControl "++" : TBlock b : xs)
= parseIt [Items Enumerate [Item b], ix] xs
parseIt (Items Enumerate is : ix) s@(TControl "++" : TBlock b : xs)
= parseIt (Items Enumerate (Item b:is) : ix) xs
parseIt ix@(Items t is:xs) s = (reduce ix, s)
where
reduce (Items t1 i1:Items t2 i2:ix) = reduce (Items t2 (Items t1 (reverse i1) : i2):ix)
reduce [Items t is] = Items t $ reverse is
parseIt _ s = (Items Itemize [], s)
parseItem i
| r == "" = ("", w)
| otherwise = (w, r)
where (w, r) = splitHead i
parseTable :: [Token] -> (Table, [Token])
-- ^ parses Tokens as a Table, returns the Table and the remaining Tokens.
parseTable = parseTable' (newTableOpt, [(NoBorder, [])])
parseTable' :: Table -> [Token] -> (Table, [Token])
parseTable' (opt, rows) (TControl ">@" : TBlock b : xs)
= parseTable' (opt { tableDef = b }, rows) xs
parseTable' (opt, rows) (TControl ">X" : TBlock b : xs)
= parseTable' (opt { tableDef = b, tableX = True }, rows) xs
parseTable' (opt, rows) (TControl ">^" : TBlock b : xs)
= parseTable' (opt { tableCaptionTop = Just b }, rows) xs
parseTable' (opt, rows) (TControl ">_" : TBlock b : xs)
= parseTable' (opt { tableCaptionBottom = Just b }, rows) xs
parseTable' (opt, rows@((t,r):rs)) (TControl ">-" : TBlock b : xs)
= parseTable' (opt, ((NoBorder, []) : (SingleBorder, r) : rs)) xs
parseTable' (opt, rows@((t,r):rs)) (TControl ">=" : TBlock b : xs)
= parseTable' (opt, ((NoBorder, []) : (DoubleBorder, r) : rs)) xs
parseTable' (opt, rows@((t,r):rs)) (TControl ">+" : TBlock b : xs)
= parseTable' (opt, ((NoBorder, []) : (NoBorder, r) : rs)) xs
parseTable' (opt, rows@((t,r):rs)) (TControl ('>':c) : TBlock b : xs)
= parseTable' (opt, ((t, (parseCell c, b):r):rs)) xs
parseTable' (opt, rows) xs
= ((opt, map (\(t,r) -> (t, reverse r)) $ reverse rows), xs)
parseCell c
= let
digits = filter isDigit c
upper = filter isUpper c
lower = filter isLower c
comma = elemIndex ',' c
split = splitAt (fromJust comma) c
left = filter isDigit $ fst split
right = filter isDigit $ snd split
pos x
| x < 1 = 1
| otherwise = x
colSpan
| isJust comma && left /= [] = pos $ read left
| isNothing comma && digits /= [] = pos $ read digits
| otherwise = 1
rowSpan
| isJust comma && right /= [] = read right
| otherwise = 1
color = case lower of
"red" -> Just "red"
"yellow" -> Just "yellow"
"blue" -> Just "blue"
"green" -> Just "green"
"gray" -> Just "gray"
_ -> Nothing
align = case upper of
"L" -> Just 'l'
"R" -> Just 'r'
"C" -> Just 'c'
_ -> Nothing
typ
| '$' `elem` c = Math
| '#' `elem` c = Verb
| '!' `elem` c = Head
| otherwise = Default
in Cell color align colSpan rowSpan (head c == '|') (last c == '|') typ
lex :: String -> [Token]
-- ^ Lexes a String into Tokens.
lex xs = lex' 1 0 [] SStart (xs ++ "\n\n")
lex' :: Int -> Int -> String -> State -> String -> [Token]
lex' _ _ _ _ [] = []
lex' l c m SStart s@(x:xs)
| x == ' ' = lex' l (c+1) [] SSpace xs
| x == '\n' = lex' (l+1) 0 [] SStart xs
| x == '\t' = lex' l (c+1) [] SSymbol xs
| isAlpha x = lex' l (c+1) [x] SCommand xs
| x == '\\' && xs ^= "begin{code}"
= let (haskell, simplex) = split xs'
xs' = drop 12 xs
split ('\n':'\\':xs)
| xs ^= "end{code}" = ("", drop 9 xs)
split (x:xs) = let (r, rs) = split xs in (x:r, rs)
in TControl ".haskell" : TBlock haskell : TControl "." : lex' (l+1) 11 "" SSpace simplex
| otherwise = lex' l (c+1) [x] SControl xs
lex' l c m SNewline s@(x:xs)
| x == '\n' = mkBlock m : lex' (l+1) 0 m SStart xs
| x == ' ' = lex' l (c+1) m SSpace xs
| x == '\t' = lex' l (c+1) ('\n':m) SSymbol xs
| isAlpha x = mkBlock m : lex' l (c+1) [x] SCommand xs
| otherwise = mkBlock m : lex' l (c+1) [x] SControl xs
lex' l c m SCommand s@(x:xs)
| x == '\n' = TCommand (reverse m) [] : lex' (l+1) 0 [] SStart xs
| x == ' ' = lexCommand l (c+1) (reverse m) "" [] xs
| x == '\t' = lexCommand l (c+1) (reverse m) "" [] xs
| otherwise = lex' l (c+1) (x:m) SCommand xs
lex' l c m SControl s@(x:xs)
| x == ' ' && c < 4 = TControl (reverse m) : lex' l (c+1) [] SControlAfter xs
| x == ' ' = TControl (reverse m) : lex' l (c+1) [] SSymbol xs
| x == '\t' = TControl (reverse m) : lex' l (c+1) [] SSymbol xs
| x == '\n' = TControl (reverse m) : lex' (l+1) 0 [] SNewline xs
| otherwise = lex' l (c+1) (x:m) SControl xs
lex' l c m SControlAfter s@(x:xs)
| x == '\n' = lex' (l+1) 0 [] SNewline xs
| x == ' ' && c < 4 = lex' l (c+1) [] SControlAfter xs
| otherwise = lex' l (c+1) [x] SSymbol xs
lex' l c m SSymbol s@(x:xs)
| x == '\n' = lex' (l+1) 0 m SNewline xs
| otherwise = lex' l (c+1) (x:m) SSymbol xs
lex' l c m SSpace s@(x:xs)
| x == '\n' = mkBlock m : lex' (l+1) 0 m SStart xs
| x == ' ' && c < 4 = lex' l (c+1) m SSpace xs
| x == '\t' = lex' l (c+1) ('\n':m) SSymbol xs
| otherwise = lex' l (c+1) (x:'\n':m) SSymbol xs
lexCommand l c cmd b a s@(x:xs)
| x == ' ' = lexCommand l (c+1) cmd "" (reverse b : a) xs
| x == '\t' = lexCommand l (c+1) cmd "" (reverse b : a) xs
| x == '\n' = TCommand cmd (reverse $ filter (/= "") (reverse b : a)) : lex' (l+1) 0 [] SStart xs
| otherwise = lexCommand l (c+1) cmd (x:b) a xs
mkBlock = TBlock . dropWhile (== '\n') . reverse
loadHashbangs :: [Token] -> IO [Token]
-- ^ Loads includes (those lines starting with a hashbang)
loadHashbangs (TControl ('#':c@(_:_)) : TBlock b : xs) = do
(c', block) <- loadHashbang c b
rest <- loadHashbangs xs
return $ TControl ('.':c') : TBlock block : rest
loadHashbangs (x:xs) = loadHashbangs xs >>= return . (x :)
loadHashbangs _ = return []
loadHashbang :: String -> String -> IO (String, String)
-- ^ Loads a single hashbang reference
loadHashbang c b = do
let f = reverse . dropWhile (`elem` " \t\n\r\"<>")
trim = f . f
file = trim b
try (readFile file) >>= return . either
(\e -> ("error", show (e :: IOException)))
(\d -> (c, d))
loadIncludes :: Bool -> [Token] -> IO [Token]
-- ^ load other simplex files included via `#include`
loadIncludes inc (TControl "#include" : TBlock b : xs) = do
let f = reverse . dropWhile (`elem` " \t\n\r\"<>")
trim = f . f
file = trim b
tok <- try (readFile file) >>= either
(\e -> return [TControl ".error", TBlock $ show (e :: IOException)])
(loadIncludes False . lex)
rest <- loadIncludes inc xs
return $ tok ++ rest
loadIncludes inc (TControl "#image" : TBlock b : xs) = do
let f = reverse . dropWhile (`elem` " \t\n\r\"<>")
trim = f . f
file = trim b
rest <- loadIncludes inc xs
return (TCommand "image" [file] : rest)
loadIncludes inc (TCommand "ignore" _ : xs) = do
let f (TCommand "endignore" _) = False
f _ = True
loadIncludes inc $ tail' $ dropWhile f xs
loadIncludes False (TCommand "noinclude" _ : xs) = do
let f (TCommand "endnoinclude" _) = False
f _ = True
loadIncludes False $ tail' $ dropWhile f xs
loadIncludes inc (x:xs) = loadIncludes inc xs >>= return . (x :)
loadIncludes _ _ = return []
|
scravy/simplex
|
src/Simplex/Parser.hs
|
gpl-3.0
| 13,667
| 0
| 16
| 4,071
| 6,562
| 3,376
| 3,186
| 309
| 15
|
-- | A pass on the sugared AST to decide where to put parenthesis
{-# LANGUAGE TypeApplications, TypeFamilies, DefaultSignatures, ScopedTypeVariables #-}
module Lamdu.Sugar.Parens
( MinOpPrec
, addToWorkArea, addToTopLevel
) where
import qualified Control.Lens as Lens
import Hyper
import Hyper.Recurse (Recursive(..), proxyArgument)
import qualified Lamdu.Calc.Term as V
import Lamdu.Precedence (Prec, Precedence(..), HasPrecedence(..), before, after)
import qualified Lamdu.Sugar.Lens as SugarLens
import Lamdu.Sugar.Types
import Lamdu.Prelude
-- | Do we need parenthesis (OR any other visual disambiguation?)
type NeedsParens = Bool
type MinOpPrec = Prec
addToWorkArea ::
HasPrecedence name =>
WorkArea v name i o a ->
WorkArea v name i o (ParenInfo, a)
addToWorkArea w =
w
{ _waRepl = w ^. waRepl & replExpr %~ addToTopLevel 0
, _waPanes = w ^. waPanes <&> SugarLens.paneBinder %~ addToTopLevel 0
}
unambiguousChild :: h # expr -> (Const (MinOpPrec, Precedence Prec) :*: h) # expr
unambiguousChild = (Const (0, Precedence 0 0) :*:)
unambiguousBody :: HFunctor expr => (expr # h) -> expr # (Const (MinOpPrec, Precedence Prec) :*: h)
unambiguousBody = hmap (const unambiguousChild)
class GetPrec h where
getPrec :: HasPrecedence name => h # Const (BinderVarRef name o) -> Prec
instance GetPrec (Ann a) where
getPrec = precedence . (^. hVal . Lens._Wrapped . bvNameRef . nrName)
class HFunctor expr => AddParens expr where
parenInfo ::
GetPrec h =>
Precedence Prec -> expr # h ->
(NeedsParens, expr # (Const (MinOpPrec, Precedence Prec) :*: h))
parenInfo _ = (,) False . unambiguousBody
addParensRecursive :: Proxy expr -> Dict (HNodesConstraint expr AddParens)
default addParensRecursive ::
HNodesConstraint expr AddParens =>
Proxy expr -> Dict (HNodesConstraint expr AddParens)
addParensRecursive _ = Dict
instance Recursive AddParens where
recurse = addParensRecursive . proxyArgument
addToTopLevel :: AddParens expr => MinOpPrec -> Annotated a # expr -> Annotated (ParenInfo, a) # expr
addToTopLevel = (`addToNode` Precedence 0 0)
addToNode ::
forall expr a.
AddParens expr =>
MinOpPrec -> Precedence Prec -> Annotated a # expr -> Annotated (ParenInfo, a) # expr
addToNode minOpPrec parentPrec (Ann (Const pl) b0) =
withDict (recurse (Proxy @(AddParens expr))) $
hmap (Proxy @AddParens #> \(Const (opPrec, prec) :*: x) -> addToNode opPrec prec x) b1
& Ann (Const (ParenInfo minOpPrec r, pl))
where
(r, b1) = parenInfo parentPrec b0
instance AddParens (Const a)
instance HasPrecedence name => AddParens (Else v name i o)
instance HasPrecedence name => AddParens (PostfixFunc v name i o)
instance HasPrecedence name => AddParens (Assignment v name i o) where
parenInfo parentPrec (BodyPlain x) = apBody (parenInfo parentPrec) x & _2 %~ BodyPlain
parenInfo _ (BodyFunction x) = (False, unambiguousBody x & BodyFunction)
instance HasPrecedence name => AddParens (Binder v name i o) where
parenInfo parentPrec (BinderTerm x) = parenInfo parentPrec x & _2 %~ BinderTerm
parenInfo _ (BinderLet x) = (False, unambiguousBody x & BinderLet)
instance HasPrecedence name => AddParens (Term v name i o) where
parenInfo parentPrec =
\case
BodyRecord x -> (False, unambiguousBody x & BodyRecord)
BodyPostfixFunc x -> (parentPrec ^. before >= 12, unambiguousBody x & BodyPostfixFunc)
BodyLam x -> (parentPrec ^. after > 0, unambiguousBody x & BodyLam)
BodyToNom x -> (parentPrec ^. after > 0, unambiguousBody x & BodyToNom)
BodySimpleApply x -> simpleApply x
BodyLabeledApply x -> labeledApply x
BodyPostfixApply x -> postfixApply x
BodyIfElse x ->
( parentPrec ^. after > 1
, BodyIfElse IfElse
{ _iIf = Const (precedence ':' + 1, Precedence 0 0) :*: x ^. iIf
, _iThen = Const (0, Precedence 0 0) :*: x ^. iThen
, _iElse = Const (0, Precedence 0 0) :*: x ^. iElse
}
)
BodyFragment x -> (True, x & fExpr %~ (Const (13, pure 1) :*:) & BodyFragment)
BodyNullaryInject x -> (False, unambiguousBody x & BodyNullaryInject)
BodyLeaf x ->
-- A quite hacky rule for inject
(Lens.has _LeafInject x && parentPrec ^. after /= 13, BodyLeaf x)
where
simpleApply (V.App f a) =
( needParens
, BodySimpleApply V.App
{ V._appFunc = Const (0, p & after .~ 13) :*: f
, V._appArg = Const (13, p & before .~ 13) :*: a
}
)
where
needParens = parentPrec ^. before > 13 || parentPrec ^. after >= 13
p = newParentPrec needParens
newParentPrec needParens
| needParens = pure 0
| otherwise = parentPrec
labeledApply x =
( needParens
, maybe (BodyLabeledApply (unambiguousBody x)) (simpleInfix needParens) (x ^? bareInfix)
)
where
prec = getPrec (x ^. aFunc)
needParens = parentPrec ^. before >= prec || parentPrec ^. after > prec
simpleInfix needParens (func, OperatorArgs l r s) =
bareInfix #
( unambiguousChild func
, OperatorArgs
(Const (0, p & after .~ prec) :*: l)
(Const (prec+1, p & before .~ prec) :*: r)
s
) & BodyLabeledApply
where
prec = getPrec func
p = newParentPrec needParens
postfixApply (PostfixApply a f) =
( needParens
, BodyPostfixApply PostfixApply
{ _pArg = Const (0, p & after .~ 12) :*: a
, _pFunc = Const (13, Precedence 0 0) :*: f
}
)
where
needParens = parentPrec ^. before >= 13 || parentPrec ^. after > 12
p = newParentPrec needParens
bareInfix ::
Lens.Prism' (LabeledApply v name i o # h)
( h # Const (BinderVarRef name o)
, OperatorArgs v name i o # h
)
bareInfix =
Lens.prism' toLabeledApply fromLabeledApply
where
toLabeledApply (f, a) = LabeledApply f (Just a) [] []
fromLabeledApply (LabeledApply f (Just a) [] []) = Just (f, a)
fromLabeledApply _ = Nothing
|
Peaker/lamdu
|
src/Lamdu/Sugar/Parens.hs
|
gpl-3.0
| 6,712
| 0
| 18
| 2,142
| 2,114
| 1,095
| 1,019
| -1
| -1
|
module ExampleObject(DT, ExampleObject(..), newShip, shipR) where
import Zoepis
import Control.Monad
type DT = Float
data ExampleObject = Object {
objUpdate :: DT -> ExampleObject
, objScene :: [ZSceneObject]
}
data Orientation = Orient {
oRotation :: Quaternion Float
, oCofR :: Point3D Float -- point about which to rotate
, oOffset :: Vector3D Float -- oCofR o + oOffset is the position
} deriving Show
oUp o = rotateVector (oRotation o) yAxis
oForward o = rotateVector (oRotation o) zAxis
oRight o = rotateVector (oRotation o) (-xAxis)
rotateO :: Quaternion Float -> Orientation -> Orientation
rotateO r o = o {
oRotation = r `mulq` (oRotation o)
, oOffset = rot (oOffset o)
}
where rot v = rotateVector r v
offsetO :: Vector3D Float -> Orientation -> Orientation
offsetO v o = o { oOffset = (oOffset o) + v }
transO :: Vector3D Float -> Orientation -> Orientation
transO v o = o { oCofR = (oCofR o) + v }
oPos o = oCofR o + oOffset o
newOrient :: Point3D Float -> Quaternion Float -> Orientation
newOrient pos rot = Orient { oCofR = pos
, oOffset = vector3D (0,0,0)
, oRotation = rot
}
where up = rotateVector rot yAxis
forward = rotateVector rot zAxis
-- Ship specific, an example of an object --
data Ship = Ship {
sOrient :: Orientation
, sSpeed :: Float
, sEngineL :: ([ZParticle], Orientation)
, sEngineR :: ([ZParticle], Orientation)
, sRand :: ZRandGen
}
shipVel :: Ship -> Vector3D Float
shipVel s = scale (sSpeed s) (oForward . sOrient $ s)
shipDir :: Ship -> Vector3D Float
shipDir = oForward . sOrient
moveShip :: Ship -> Vector3D Float -> Ship
moveShip s v = s { sOrient = transO v (sOrient s)
, sEngineL = moveEngine (sEngineL s)
, sEngineR = moveEngine (sEngineR s)
}
where moveEngine (pe, o) = (pe, transO v o)
rotateShip :: Ship -> Quaternion Float -> Ship
rotateShip s r = s { sOrient = rotateO r (sOrient s)
, sEngineL = rotEngine (sEngineL s)
, sEngineR = rotEngine (sEngineR s)
}
where rotEngine (pe, o) = (pe, rotateO r o)
shipR = do zLoadObject 0 "resources/GhoulOBJ.obj" True
zLoadTexture 0 "resources/Part.jpg"
newShip pos rot speed seed = mkShip $ Ship {
sOrient = shipO
, sSpeed = speed
, sEngineL = eL
, sEngineR = eR
, sRand = zRandGen seed
}
where shipO = newOrient pos rot
eOff = scale 0.02 (oUp shipO)
eRight = scale 0.35 (oRight shipO)
eBack = scale (-0.80) (oForward shipO)
eL = (newEngine 25, offsetO (eOff - eRight + eBack) shipO)
eR = (newEngine 25, offsetO (eOff + eRight + eBack) shipO)
mkShip :: Ship -> ExampleObject
mkShip s = Object update render
where
transShip dt ship = moveShip ship (scale dt (shipVel ship))
(rot, rng) = zRunRand (randomRot 0.8 (sOrient s)) (sRand s)
stepShip sh dt = stepEngines $ transShip dt s -- $ rotateShip s rot
update dt = mkShip $ (stepShip s dt) { sRand = rng }
render = renderShip s
stepEngines :: Ship -> Ship
stepEngines ship = ship { sEngineL = stepEngine $ sEngineL ship
, sEngineR = stepEngine $ sEngineR ship
}
where stepEngine (ps, o) = (updateAndSpawn o ps, o)
updateAndSpawn o (ZDeadParticle:ps) =
(engineParticle 1.0 o):(map justUpdate ps)
updateAndSpawn o (p:ps) = (justUpdate p):(updateAndSpawn o ps)
updateAndSpawn _ [] = []
justUpdate ZDeadParticle = ZDeadParticle
justUpdate p = if pLife p < 0
then ZDeadParticle
else p { pLife = pLife p - 0.06 }
newEngine n = replicate n $ ZDeadParticle
engineParticle l o = zParticle l (1.0, 0.6, 0.1) (oPos o) (oForward o) 0
randomRot :: Float -> Orientation -> ZRandom (Quaternion (Float))
randomRot threshold orientation = do
{
; p <- zGetRandomR (0, 1.0::Float)
; if p <= threshold
then do
theta <- zGetRandomR (-0.02, 0.02)
let rot = rotation theta (oRight orientation + oUp orientation)
return rot
else return $ rotation 0 (vector3D (0,0,0))
}
renderShip :: Ship -> [ZSceneObject]
renderShip s =
[ZModel zNoScale (zRot $ rotate `mulq` reOrient) (zTrans pos) 0
,ZParticles 50 0 peR
,ZParticles 50 0 peL
]
where up = oUp $ sOrient s
pos = oPos $ sOrient s
peL = fst . sEngineL $ s
peR = fst . sEngineR $ s
reOrient = rotation (3*pi/2) yAxis `mulq` rotation (3*pi/2) xAxis
rotate = oRotation $ sOrient s
|
abakst/Zoepis
|
ExampleObject.hs
|
gpl-3.0
| 5,228
| 1
| 16
| 1,919
| 1,692
| 898
| 794
| 106
| 5
|
--------------------------------------------------------------------------------
-- This file is part of diplomarbeit ("Diplomarbeit Johannes Weiß"). --
-- --
-- diplomarbeit 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. --
-- --
-- diplomarbeit 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 diplomarbeit. If not, see <http://www.gnu.org/licenses/>. --
-- --
-- Copyright 2012, Johannes Weiß --
--------------------------------------------------------------------------------
module Main (main) where
import Codec.LBS ( InputValues, lbsFromExpr, renderLBSProgram, runLBS
, LBSProgram, LBSStmt(..), Register(..), OffsetDirection(..)
, ScaleFactor(..), lbsProgramLength
)
import Data.ExpressionTypes (Expr(..))
import Data.Monoid (mappend, mconcat)
import Data.Text.Lazy (Text())
import Data.Text.Lazy.Builder (Builder(), fromString, toLazyText)
import qualified Data.DList as DL
import qualified Data.Map as M
import qualified Data.Text.Lazy.IO as TIO
_VARS_ :: InputValues
_VARS_ = M.fromList [("x", 17), ("y", 34)]
_X_ :: Expr Integer
_X_ = Var "x"
_Y_ :: Expr Integer
_Y_ = Var "y"
--test :: Expr Integer
--test = (4 * _X_ * _X_ + 2 * (_X_ + _Y_ * _Y_) * _X_ * _Y_ + 7) * _X_
--big_sum :: Expr Integer
--big_sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + _X_ + _Y_
--
--test :: Expr Integer
--test = big_sum * big_sum * big_sum * big_sum * big_sum +
-- big_sum * big_sum * big_sum * big_sum * big_sum +
-- big_sum * big_sum * big_sum * big_sum * big_sum
--
--test :: Expr Integer
--test = 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19
--test :: Expr Integer
--test = 3 * _X_ + 4 * _Y_
--pow :: Num a => a -> Integer -> a
--pow a p = a ^ p
t :: Expr Integer
t = ((1 * 2) * (3 * 4)) * ((5 * 6) * (7 * 8)) *
((1 * 2) * (3 * 4)) * ((5 * 6) * (7 * 8))
test :: Expr Integer -- size 255
test = ((t * t) * (t * t)) * ((t * t) * (t * t))
fromShow :: Show a => a -> Builder
fromShow = fromString . show
maxRegister :: LBSStmt -> Integer
maxRegister (Offset (Reg o) _ (Reg i) _) = max i o
maximaMatrixFromLBSStmt :: Integer -> (LBSStmt, Integer) -> Builder
maximaMatrixFromLBSStmt matrixSize (Offset (Reg o) dir (Reg i) sf, lineNo) =
fromString "M" `mappend`
fromShow lineNo `mappend`
fromString " : ident(" `mappend`
fromShow matrixSize `mappend`
fromString ");\nM" `mappend`
fromShow lineNo `mappend`
fromString "[" `mappend`
fromShow (o+1) `mappend`
fromString ", " `mappend`
fromShow (i+1) `mappend`
fromString "] : " `mappend`
fromString dirString `mappend`
fromString sfString `mappend`
fromString ";"
where dirString =
case dir of
OffsetPlus -> "+"
OffsetMinus -> "-"
sfString =
case sf of
ScaleFactorConstant c -> show c
ScaleFactorInput input -> input
maximaMatrixFromLBSProgram :: LBSProgram -> Text
maximaMatrixFromLBSProgram lbs =
toLazyText $
foldr joinStmts (fromString "") numberedStmts `mappend`
(mconcat $ map (\i -> (fromString "M") `mappend` (fromShow i) `mappend`
(fromString " . "))
(reverse stmtNums))
where
numberedStmts :: [(LBSStmt, Integer)]
numberedStmts = zip (DL.unDL lbs []) [1..]
stmtNums :: [Integer]
stmtNums = map snd numberedStmts
stmts :: [LBSStmt]
stmts = map fst numberedStmts
maxReg :: Integer
maxReg = 1 + (maximum $ map maxRegister stmts)
joinStmts :: (LBSStmt, Integer) -> Builder -> Builder
joinStmts l s = (maximaMatrixFromLBSStmt maxReg l) `mappend`
(fromString "\n") `mappend`
s
doLBS :: Expr Integer -> IO ()
doLBS e = do
putStrLn "Expression:"
print e
putStrLn "LBSStmt:"
TIO.putStrLn $ renderLBSProgram $ lbsFromExpr e
putStrLn "EXEC:"
print $ runLBS _VARS_ (lbsFromExpr e)
putStrLn "LBSStmt:"
TIO.putStrLn $ maximaMatrixFromLBSProgram $ lbsFromExpr e
main :: IO ()
main = do
doLBS 1
print $ lbsProgramLength $ lbsFromExpr test
loop 1 14 1
where loop :: Int -> Int -> Expr Integer -> IO ()
loop i end frag =
if i < end
then let lbs = lbsFromExpr e'
e' = frag * frag
in do
putStr $ show i ++ ", "
print $ lbsProgramLength lbs
print $ runLBS _VARS_ lbs
loop (i+1) end e'
else do
return ()
|
weissi/diplomarbeit
|
programs/ExprToMRM.hs
|
gpl-3.0
| 5,572
| 0
| 18
| 1,928
| 1,271
| 700
| 571
| 96
| 3
|
module Verification where
import Control.Concurrent
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Maybe
import qualified Data.SBV as SBV
import Data.SBV(modelExists)
import Collect
import Transformer
import GCL
import Prover
import Control.Monad
import PrettyPrint
import Examples
verify :: Stmt -> IO ()
verify stmt = do
let (Vars xs stmts, vars) = transform stmt
Pre pre = head stmts
mvar <- newEmptyMVar
t <- forkIO (readInput mvar)
putStrLn ""
putStrLn "Press space to start verification step-by-step or press N to skip to result\n"
(invs,w) <- foldWlp mvar vars True_ (tail stmts)
unless (null invs) $ do
putStrLn "------------------------------"
putStrLn "Invariants are not valid:"
mapM_ (\x -> do
putStrLn $ pp x
putStrLn "\n\n") invs
putStrLn "\n\n\n-----------------------------"
putStrLn "RESULT: "
putStrLn "Given precondition: "
putStrLn $ pp pre
putStrLn "Calculated precondition: "
putStrLn $ pp w
putStrLn ""
putStrLn "Now proving implication: "
proveImpl vars pre w >>= putStrLn . show
killThread t
foldWlp :: MVar Char -> [Var] -> Expr -> [Stmt] -> IO ([Expr],Expr)
foldWlp mvar vars e s = foldr (\x y -> do
(xs,expr) <- y
(ys,expr') <- wlp mvar vars x expr
return (xs ++ ys, expr')) (return ([],e)) s
--The wlp function will calculate the WLP.
--We do by pattern matching over the statements.
--Most of the cases pretty straightforward, so we will not explain all cases.
wlp :: MVar Char -> [Var] -> Stmt -> Expr -> IO ([Expr],Expr)
wlp mvar vars Skip q = do
doStep mvar
stepPrint q Skip q
return ([],q)
wlp mvar vars (Vars vars' s) q = foldWlp mvar vars q s
--The assignQ function goes over the q and tries to find the reference and substitute the old value with e2.
--The reference is a tuple. The left element of this tuple is the reference Expr and the right element is used as an option for an array with an index..
wlp mvar vars (Assign (Name s) e2) q = do
doStep mvar
let assign = assignQ q (s, Nothing) e2
stepPrint q (Assign (Name s) e2) assign
return ([],assign)
wlp mvar vars (Assign (Repby (Name s) i) e2) q = do
doStep mvar
let assign = assignQ q (s,Just i) e2
stepPrint q (Assign (Repby (Name s) i) e2) assign
return ([],assign)
wlp mvar vars (Post e) q = do
doStep mvar
stepPrint q (Post e) (e .&& q)
return ([],e .&& q)
wlp mvar vars (Pre e) q = do
doStep mvar
stepPrint q (Pre e) (e .==> q)
return ([],e .==> q)
wlp mvar vars (If g s1 s2) q = do
(xs,e1) <- foldWlp mvar vars q s1
(ys,e2) <- foldWlp mvar vars q s2
stepPrint q (If g s1 s2) ((g .&& e1) .|| (neg g .&& e2))
return (xs ++ ys, (g .&& e1) .|| (neg g .&& e2))
-- In order to calculate the WLP of the while we first have to proof the correctness of an invariant.
-- First we calculate the wlp s i
-- Second, we proof the (i && not g) => q
-- Third, we proof (i && g) => wlp s i
-- If the invariant is not correct, we still continue calculating the WLP. However, it will be reported that the while is not correct.
wlp mvar vars (Inv i (While g s)) q = do
impl1Val <- implIsValid vars (i .&& neg g) q
(xs,wlpOfS) <- foldWlp mvar vars i s
impl2Val <- implIsValid vars (i .&& g) wlpOfS
let implInv1 = if impl1Val then [] else [i .&& neg g .==> q]
implInv2 = if impl2Val then xs else (i .&& g .==> wlpOfS) : xs
invs = implInv1 ++ implInv2
if impl1Val && impl2Val
then do
stepPrint q (Inv i (While g [])) i
return (invs,i)
else do
stepPrint q (Inv i (While g [])) (neg g .&& q)
return (i : xs,neg g .&& q)
wlp mvar vars (While g s) q = do
putStrLn "Loop reduction"
putStrLn ("Q: " ++ show q)
fixpoint <- loopReduction 10 (neg g .==> q) g s q mvar vars
putStrLn "End loop reduction"
return ([],fixpoint)
wlp mvar vars Prog{} q = return ([],q)
wlp mvar _ _ _ = error "Not supported by our wlp function"
--In loopReducation we try to calculate the fixpoint.
--The first parameter is an int, which determines the amount of iterations. We will stop iterating when k is 0.
--The second parameters is the previous calculated post condition
--The g is the condition of the while
--the s is the body of the while
--To verify an fixpoint, we try to imply the post condition with the previous post condition
--However, when we do not find an fixpoint we return (neg g .&& q)
loopReduction :: Int -> Expr -> Expr -> [Stmt] -> Expr -> MVar Char -> [Var] -> IO Expr
loopReduction 0 e1 g s q mvar vars = do
(_,w) <- foldWlp mvar vars e1 s
let fixpoint = (g .&& w) .|| (neg g .&& q)
impl1Val <- implIsValid vars e1 fixpoint
if impl1Val
then return fixpoint
else do
putStrLn "No fixpoint"
return (neg g .&& q)
loopReduction k e1 g s q mvar vars = do
(_,w) <- foldWlp mvar vars e1 s
let fixpoint = (g .&& w) .|| (neg g .&& q)
print k
impl1Val <- implIsValid vars e1 fixpoint
if impl1Val
then return fixpoint
else loopReduction (k-1) fixpoint g s q mvar vars
-- The AssignQ function is used to subsitute an Expr with an other Expr.
-- First we try to find the corresponding reference in q.
-- We do this by pattern matching over all the Expression in q.
-- When the corresponding reference is found we will subsitute the corresponding reference for expr.
assignQ :: Expr -> (String, Maybe Expr) -> Expr -> Expr
assignQ (Lit i) ref expr = Lit i
assignQ (Name s) ref expr
| s == fst ref = expr
| otherwise = Name s
assignQ (ForAll s e) ref expr = ForAll s $ assignQ e ref expr
assignQ (Minus e1 e2) ref expr = Minus (assignQ e1 ref expr) (assignQ e2 ref expr)
assignQ (Plus e1 e2) ref expr = Plus (assignQ e1 ref expr) (assignQ e2 ref expr)
assignQ e@(Equal e1 e2) ref expr = permExpr e ref expr
assignQ e@(Lower e1 e2) ref expr = permExpr e ref expr
assignQ e@(LowerE e1 e2) ref expr = permExpr e ref expr
assignQ (And e1 e2) ref expr = And (assignQ e1 ref expr) (assignQ e2 ref expr)
assignQ (Or e1 e2) ref expr = Or (assignQ e1 ref expr) (assignQ e2 ref expr)
assignQ (Impl e1 e2) ref expr = Impl (assignQ e1 ref expr) (assignQ e2 ref expr)
assignQ (Not e1) ref expr = Not (assignQ e1 ref expr)
assignQ True_ ref expr = True_
assignQ (Repby (Name s) index) ref expr | isJust (snd ref) && index == fromJust (snd ref) && s == fst ref = expr
| isNothing (snd ref) && s == fst ref = Repby expr (assignQ index ref expr)
| otherwise = Repby (Name s) (assignQ index ref expr)
assignQ expr _ _ = error $ show expr
--If we are assigning to an array that is indexed, then we will have to compare the index of that array
--with the indexes that are used in the current wlp. We make permutations of these comparisons and for each
--permutation we do the relevant substitution.
permExpr :: Expr -> (String, Maybe Expr) -> Expr -> Expr
permExpr (Lower e1 e2) ref@(s, Nothing) args = Lower (assignQ e1 ref args) (assignQ e2 ref args)
permExpr (LowerE e1 e2) ref@(s, Nothing) args = LowerE (assignQ e1 ref args) (assignQ e2 ref args)
permExpr (Equal e1 e2) ref@(s, Nothing) args = Equal (assignQ e1 ref args) (assignQ e2 ref args)
permExpr expr (s, Just i) args =
let xs = permArrays s $ findArrays expr
perms = permutations xs
permExprs = map (\ys -> permutation expr xs ys i .==> replaceArray ys s args expr) perms
in case length xs > 0 of --In the case that we could not find any indexed arrays in the wlp
True -> foldr1 (.&&) permExprs
False -> expr
--Generates a single permutation
permutation :: Expr -> [Expr] -> [Expr] -> Expr -> Expr
permutation e all pExprs index =
let negs = all L.\\ pExprs
eqExprs = foldr1 (.&&) (map (.== index) pExprs)
in case length (negs ++ pExprs) <= 0 of
False -> foldr1 (.&&) (map (.== index) pExprs ++ map (neg . (.==) index) negs)
True -> error $ pp e
--Substitution
replaceArray :: [Expr] -> String -> Expr -> Expr -> Expr
replaceArray xs ref expr (Lower e1 e2) = Lower (replaceArray xs ref expr e1) (replaceArray xs ref expr e2)
replaceArray xs ref expr (LowerE e1 e2) = LowerE (replaceArray xs ref expr e1) (replaceArray xs ref expr e2)
replaceArray xs ref expr (Equal e1 e2) = Equal (replaceArray xs ref expr e1) (replaceArray xs ref expr e2)
replaceArray xs ref expr (Minus e1 e2) = Minus (replaceArray xs ref expr e1) (replaceArray xs ref expr e2)
replaceArray xs ref expr (Plus e1 e2) = Plus (replaceArray xs ref expr e1) (replaceArray xs ref expr e2)
replaceArray xs ref expr (Repby (Name s) index)
| s == ref && index `elem` xs = expr
| otherwise = Repby (Name s) index
replaceArray _ _ expr e = e
--Find all possible permutations
permutations :: Eq a => [a] -> [[a]]
permutations [] = [[]]
permutations xs = xs : L.nub [ zs | (x,ys) <- selections xs, zs <- permutations ys ]
--General selection function
selections :: [a] -> [(a,[a])]
selections [] = []
selections (x:xs) = (x,xs) : [ (y,x:ys) | (y,ys) <- selections xs ]
--We can only substitute arrays that have the correct name
permArrays :: String -> [Expr] -> [Expr]
permArrays s xs = map (\(Repby _ i) -> i) $ filter (\(Repby (Name s1) index) -> s1 == s) xs
--Find all indexed arrays
findArrays :: Expr -> [Expr]
findArrays (Lower e1 e2) = findArrays e1 ++ findArrays e2
findArrays (LowerE e1 e2) = findArrays e1 ++ findArrays e2
findArrays (Equal e1 e2) = findArrays e1 ++ findArrays e2
findArrays (Minus e1 e2) = findArrays e1 ++ findArrays e2
findArrays (Plus e1 e2) = findArrays e1 ++ findArrays e2
findArrays (Repby s i) = [Repby s i]
findArrays (Name s) = []
findArrays (Lit i) = []
--Connects to the prover to determine whether the implication is valid
implIsValid :: [Var] -> Expr -> Expr -> IO Bool
implIsValid vars e1 e2 = do
validity <- proveImpl vars e1 e2
return $ not $ modelExists validity
--Some interactivity functions
readInput :: MVar Char -> IO ()
readInput mvar = do
c <- getChar
putMVar mvar c
readInput mvar
doStep :: MVar Char -> IO ()
doStep mvar = do
c <- readMVar mvar
case c of
'n' -> return ()
' ' -> do
takeMVar mvar
return ()
implPrint :: String -> Expr -> Expr -> IO ()
implPrint s e1 e2 = do
let str = "\n--------------------------\n" ++
s ++ "\n" ++
pp e1 ++ "\n" ++
".==>\n" ++
pp e2 ++ "\n" ++
"-----------------------\n"
appendFile "Output.txt" str
stepPrint :: Expr -> Stmt -> Expr -> IO ()
stepPrint q stmt p = do
let str = "\nPre: " ++ pp p ++ "\n" ++
"Stmt: " ++ pp stmt ++ "\n" ++
"Post: " ++ pp q ++ "\n" ++
"---------------------------------\n"
appendFile "Output.txt" str
putStrLn $ "Pre: " ++ pp p
putStrLn $ "Stmt: " ++ pp stmt
putStrLn $ "Post: " ++ pp q
putStrLn ""
putStrLn "-----------------------------\n"
|
Ferdinand-vW/Wlp-verification-engine
|
src/Verification.hs
|
gpl-3.0
| 11,092
| 0
| 19
| 2,772
| 4,188
| 2,072
| 2,116
| 217
| 4
|
{-# OPTIONS -Wall #-}
{-# LANGUAGE TupleSections #-}
module Graphics.UI.GLFW.Events(GLFWEvent(..), KeyEvent(..), IsPress(..), eventLoop) where
import Control.Concurrent(threadDelay, forkIO)
import Control.Concurrent.MVar
import Control.Monad(forever, (<=<))
import Data.IORef
import Data.Time.Clock (UTCTime, getCurrentTime, diffUTCTime)
import Graphics.UI.GLFW.ModState(ModState, isModifierKey, asModkey, modStateFromModkeySet)
import qualified Data.Set as Set
import qualified Graphics.UI.GLFW as GLFW
data IsPress = Press | Release
deriving (Show, Read, Eq, Ord)
isPressFromBool :: Bool -> IsPress
isPressFromBool True = Press
isPressFromBool False = Release
-- this is the reification of the callback information:
data GLFWRawEvent = RawCharEvent IsPress Char
| RawKeyEvent IsPress GLFW.Key
| RawWindowRefresh
| RawWindowClose
deriving (Show, Eq)
data KeyEvent = KeyEvent {
keyPress :: IsPress,
keyEventModState :: ModState,
keyEventChar :: Maybe Char,
keyEventKey :: GLFW.Key }
deriving (Show, Eq)
-- This is the final representation we expose of events:
data GLFWEvent = GLFWKeyEvent KeyEvent
| GLFWWindowClose
| GLFWWindowRefresh
deriving (Show, Eq)
translate :: [(ModState, GLFWRawEvent)] -> [GLFWEvent]
translate [] = []
translate ((_, RawWindowClose) : xs) = GLFWWindowClose : translate xs
translate ((_, RawWindowRefresh) : xs) = GLFWWindowRefresh : translate xs
translate ((modState1, rk@(RawKeyEvent isPress1 key)) :
(modState2, rc@(RawCharEvent isPress2 char)) : xs)
| isModifierKey key =
-- This happens when you press shift while a key is pressed,
-- ignore
GLFWKeyEvent (KeyEvent isPress1 modState1 Nothing key) : translate xs
| isPress1 == isPress2 =
GLFWKeyEvent (KeyEvent isPress2 modState2 (Just char) key) : translate xs
| otherwise =
error $
"RawCharEvent " ++ show rc ++
" mismatches the RawKeyEvent: " ++ show rk
translate ((modState, RawKeyEvent isPress key) : xs) =
GLFWKeyEvent (KeyEvent isPress modState Nothing key) : translate xs
-- This happens when you press shift while a key is pressed, ignore
translate ((_, RawCharEvent _ _) : xs) = translate xs
atomicModifyIORef_ :: IORef a -> (a -> a) -> IO ()
atomicModifyIORef_ var f = atomicModifyIORef var ((, ()) . f)
rawEventLoop :: ([GLFWRawEvent] -> IO ()) -> IO a
rawEventLoop eventsHandler = do
eventsVar <- newIORef []
let
addEvent event = atomicModifyIORef_ eventsVar (event:)
addKeyEvent key isPress = addEvent $ RawKeyEvent (isPressFromBool isPress) key
charEventHandler char isPress
| '\57344' <= char && char <= '\63743' = return () -- Range for "key" characters (keys for left key, right key, etc.)
| otherwise = addEvent $ RawCharEvent (isPressFromBool isPress) char
GLFW.setCharCallback charEventHandler
GLFW.setKeyCallback addKeyEvent
GLFW.setWindowRefreshCallback $ addEvent RawWindowRefresh
GLFW.setWindowSizeCallback . const . const $ addEvent RawWindowRefresh
GLFW.setWindowCloseCallback $ addEvent RawWindowClose >> return True
forever $ do
GLFW.pollEvents
let handleReversedEvents rEvents = ([], reverse rEvents)
events <- atomicModifyIORef eventsVar handleReversedEvents
eventsHandler events
GLFW.swapBuffers
data TypematicState =
NoKey |
TypematicRepeat {
_tsEvent :: KeyEvent,
_tsCount :: Int,
_tsStartTime :: UTCTime
}
pureModifyMVar :: MVar a -> (a -> a) -> IO ()
pureModifyMVar mvar f = modifyMVar_ mvar (return . f)
-- Calls handler from multiple threads!
typematicKeyHandlerWrap ::
([GLFWEvent] -> IO ()) -> IO ([GLFWEvent] -> IO ())
typematicKeyHandlerWrap handler = do
stateVar <- newMVar NoKey
accumulatedVar <- newMVar []
let
addEvent = pureModifyMVar accumulatedVar . (:)
typematicIteration state@(TypematicRepeat keyEvent count startTime) = do
now <- getCurrentTime
let timeDiff = diffUTCTime now startTime
if timeDiff >= timeFunc count
then do
addEvent $ GLFWKeyEvent keyEvent
return (TypematicRepeat keyEvent (count + 1) startTime,
timeFunc (count + 1) - timeDiff)
else
return (state, timeFunc count - timeDiff)
typematicIteration state@NoKey = return (state, timeFunc 0)
handleEvent event@(GLFWKeyEvent keyEvent@KeyEvent { keyPress=isPress }) = do
newValue <-
case isPress of
Press -> fmap (TypematicRepeat keyEvent 0) getCurrentTime
Release -> return NoKey
_ <- swapMVar stateVar newValue
addEvent event
handleEvent event = addEvent event
_ <- forkIO . forever $ do
sleepTime <- modifyMVar stateVar typematicIteration
threadDelay . max 0 $ round (1000000 * sleepTime)
return $ \events -> do
mapM_ handleEvent events
accumulated <- swapMVar accumulatedVar []
handler $ reverse accumulated
where
timeFunc = (0.5 +) . (0.025 *) . fromIntegral
modKeyHandlerWrap ::
([(ModState, GLFWRawEvent)] -> IO ()) ->
IO ([GLFWRawEvent] -> IO ())
modKeyHandlerWrap handler = do
keySetVar <- newIORef Set.empty
let
modState r = do
keySet <- readIORef keySetVar
return (modStateFromModkeySet keySet, r)
handleEvent e@(RawKeyEvent Press key) = do
maybe (return ()) (modifyIORef keySetVar . Set.insert) $
asModkey key
modState e
handleEvent e@(RawKeyEvent Release key) = do
result <- modState e
maybe (return ()) (modifyIORef keySetVar . Set.delete) $
asModkey key
return result
handleEvent e = modState e
return $ handler <=< mapM handleEvent
eventLoop :: ([GLFWEvent] -> IO ()) -> IO a
eventLoop handler = do
tHandler <- typematicKeyHandlerWrap handler
mRawHandler <- modKeyHandlerWrap (tHandler . translate)
rawEventLoop mRawHandler
|
nimia/bottle
|
bottlelib/Graphics/UI/GLFW/Events.hs
|
gpl-3.0
| 5,865
| 0
| 20
| 1,267
| 1,818
| 924
| 894
| 136
| 5
|
module Config where
import TagFS (TagSet, Tag, File(..))
import qualified TagSet as T
import qualified Data.Map as M
import Control.Monad
import Data.Functor
import Control.Exception
import System.IO
data Config = Config
{ tagSet :: TagSet
, mapping :: M.Map File FilePath
}
deriving (Eq, Show, Read)
emptyConfig :: Config
emptyConfig = Config T.emptyTagSet M.empty
readConfig :: FilePath -> IO (Maybe Config)
readConfig f = either foo Just
<$> try (withFile f ReadMode $ hGetContents >=> bar)
where
foo :: SomeException -> Maybe Config -- resolves ambiguities of Exception
foo _ = Nothing
bar :: String -> IO Config
bar s = do
_ <- evaluate (length s)
return (read s)
writeConfig :: FilePath -> Config -> IO ()
writeConfig f c = writeFile f $ show c
addFile :: (FilePath, FilePath) -> Config -> Config
addFile (n,p) c = Config (T.addFile f $ tagSet c) (M.insert f p $ mapping c)
where f = File [n]
removeFile :: FilePath -> Config -> Config
removeFile n c = Config (T.removeFile f $ tagSet c) (M.delete f $ mapping c)
where f = File [n]
tagFile :: Tag -> FilePath -> Config -> Config
tagFile t f c = Config (T.addTag t (File [f]) $ tagSet c) (mapping c)
|
ffwng/tagfs
|
Config.hs
|
gpl-3.0
| 1,186
| 63
| 11
| 237
| 502
| 272
| 230
| 33
| 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.Games.Pushtokens.Update
-- 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)
--
-- Registers a push token for the current user and application.
--
-- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.pushtokens.update@.
module Network.Google.Resource.Games.Pushtokens.Update
(
-- * REST Resource
PushtokensUpdateResource
-- * Creating a Request
, pushtokensUpdate
, PushtokensUpdate
-- * Request Lenses
, puPayload
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.pushtokens.update@ method which the
-- 'PushtokensUpdate' request conforms to.
type PushtokensUpdateResource =
"games" :>
"v1" :>
"pushtokens" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] PushToken :> Put '[JSON] ()
-- | Registers a push token for the current user and application.
--
-- /See:/ 'pushtokensUpdate' smart constructor.
newtype PushtokensUpdate =
PushtokensUpdate'
{ _puPayload :: PushToken
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PushtokensUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'puPayload'
pushtokensUpdate
:: PushToken -- ^ 'puPayload'
-> PushtokensUpdate
pushtokensUpdate pPuPayload_ = PushtokensUpdate' {_puPayload = pPuPayload_}
-- | Multipart request metadata.
puPayload :: Lens' PushtokensUpdate PushToken
puPayload
= lens _puPayload (\ s a -> s{_puPayload = a})
instance GoogleRequest PushtokensUpdate where
type Rs PushtokensUpdate = ()
type Scopes PushtokensUpdate =
'["https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.me"]
requestClient PushtokensUpdate'{..}
= go (Just AltJSON) _puPayload gamesService
where go
= buildClient
(Proxy :: Proxy PushtokensUpdateResource)
mempty
|
brendanhay/gogol
|
gogol-games/gen/Network/Google/Resource/Games/Pushtokens/Update.hs
|
mpl-2.0
| 2,799
| 0
| 12
| 632
| 311
| 191
| 120
| 48
| 1
|
module Foundation where
import Import.NoFoundation
import Database.Persist.Sql (ConnectionPool, runSqlPool)
import Text.Hamlet (hamletFile)
import Text.Jasmine (minifym)
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Core.Types (Logger)
import qualified Yesod.Core.Unsafe as Unsafe
-- | The foundation datatype for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have access
-- to the data present here.
data App =
App {appSettings :: AppSettings
,appStatic :: Static -- ^ Settings for static file serving.
,appConnPool :: ConnectionPool -- ^ Database connection pool.
,appHttpManager :: Manager
,appLogger :: Logger}
instance HasHttpManager App where
getHttpManager = appHttpManager
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/routing-and-handlers
--
-- Note that this is really half the story; in Application.hs, mkYesodDispatch
-- generates the rest of the code. Please see the linked documentation for an
-- explanation for this split.
--
-- This function also generates the following type synonyms:
-- type Handler = HandlerT App IO
-- type Widget = WidgetT App IO ()
mkYesodData "App" $(parseRoutesFile "config/routes")
-- | A convenient synonym for creating forms.
type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
-- Controls the base of generated URLs. For more information on modifying,
-- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot
approot = ApprootMaster $ appRoot . appSettings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ =
Just <$> defaultClientSessionBackend 120 "config/client_session_key.aes"
defaultLayout widget =
do master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
let links = $(hamletFile "templates/links.hamlet")
dropdownHtml =
[hamlet|
<li .dropdown>
<a href="#" .dropdown-toggle data-toggle=dropdown role=button
aria-expanded=false>
Other links
<span .caret>
<ul .dropdown-menu role=menu>
^{links}
|]
pc <-
widgetToPageContent $
do addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- The page to be redirected to when authentication is required.
authRoute _ = Nothing
-- Routes not requiring authentication.
isAuthorized FaviconR _ = return Authorized
isAuthorized RobotsR _ = return Authorized
-- Default to Authorized for now.
isAuthorized _ _ = return Authorized
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent ext mime content =
do master <- getYesod
let staticDir = appStaticDir $ appSettings master
addStaticContentExternal minifym
genFileName
staticDir
(StaticR . flip StaticRoute [])
ext
mime
content
where
-- Generate a unique filename based on the content itself
genFileName lbs = "autogen-" ++ base64md5 lbs
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog app _source level =
appShouldLogAll (appSettings app) ||
level == LevelWarn || level == LevelError
makeLogger = return . appLogger
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlBackend
runDB action = do
master <- getYesod
runSqlPool action $ appConnPool master
instance YesodPersistRunner App where
getDBRunner = defaultGetDBRunner appConnPool
-- instance YesodAuth App where
-- type AuthId App = UserId
-- -- Where to send a user after successful login
-- loginDest _ = RootR
-- -- Where to send a user after logout
-- logoutDest _ = RootR
-- -- Override the above two destinations when a Referer: header is present
-- redirectToReferer _ = True
-- authenticate creds =
-- runDB $
-- do x <- getBy $ UniqueUser $ credsIdent creds
-- fail "I hate you yesod"
-- -- return $ case x of
-- -- Just (Entity uid _) -> Authenticated uid
-- -- Nothing -> UserError InvalidLogin
-- -- You can add other plugins like BrowserID, email or OAuth here
-- authPlugins _ = []
-- authHttpManager = getHttpManager
-- instance YesodAuthPersist App
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
unsafeHandler :: App -> Handler a -> IO a
unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
-- Note: Some functionality previously present in the scaffolding has been
-- moved to documentation in the Wiki. Following are some hopefully helpful
-- links:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
-- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain
-- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding
|
learnyou/learnyou
|
Foundation.hs
|
agpl-3.0
| 6,297
| 0
| 14
| 1,490
| 658
| 370
| 288
| -1
| -1
|
-- To compile: ghc --make RunShaders .
-- {-# LANGUAGE #-}
{-# OPTIONS_GHC -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : Shady
-- Copyright : (c) Conal Elliott 2009
-- License : GPL-3
--
-- Maintainer : conal@conal.net
-- Stability : experimental
--
-- Run saved shaders
----------------------------------------------------------------------
module Main where
import System.Environment (getArgs)
import Graphics.Shady.RunSurface (glsl,runShader)
load :: FilePath -> IO ()
load path =
do (v,f) <- read `fmap` readFile path
runShader (glsl v f)
main :: IO ()
main =
do args <- getArgs
if length args /= 1 then
putStrLn "I'd like to have an argument, please (file path)"
else
load (head args)
|
conal/shady-examples
|
src/RunShaders.hs
|
agpl-3.0
| 803
| 0
| 10
| 168
| 152
| 86
| 66
| 14
| 2
|
module TableDifferences.A339010Spec (main, spec) where
import Test.Hspec
import TableDifferences.A339010 (a339010)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A339010" $
it "correctly computes the first 20 elements" $
take 20 (map a339010 [1..]) `shouldBe` expectedValue where
expectedValue = [0,0,1,1,1,2,1,2,3,2,1,5,1,2,5,3,1,6,1,5]
|
peterokagey/haskellOEIS
|
test/TableDifferences/A339010Spec.hs
|
apache-2.0
| 367
| 0
| 10
| 59
| 160
| 95
| 65
| 10
| 1
|
fibs = scanl (+) 0 (1:fibs)
countDigits num = length (show num)
main = do
let limit = 1000
let fibsWithIdx = zip [0..] fibs :: [(Integer, Integer)]
let filteredFibs = map fst $ filter ((>= limit) . countDigits . snd) $ fibsWithIdx
print $ head $ filteredFibs
|
ulikoehler/ProjectEuler
|
Euler25.hs
|
apache-2.0
| 276
| 0
| 16
| 65
| 131
| 67
| 64
| 7
| 1
|
{-# LANGUAGE MultiParamTypeClasses, ScopedTypeVariables, FlexibleInstances, GADTs, RecordWildCards #-}
module Llvm.Hir.Cast where
import Llvm.Hir.Data.Inst
import Llvm.Hir.Data.Type
import Llvm.Hir.Data.Module
import Data.Int
import Llvm.ErrorLoc
{-
This module contains the functions to cast one Ir data type to
another. Only compatable data types should be involved in casting.
In some cases, casting is statically safe, which is normally known as
up casting (or denoted as Ucast). In some cases, casting can only be
decided at runtime, which is normally known as down casting (or
denoted as Dcast). Dcast might throw out irrefutable fatal errors if
incompatible types are involved. In such a situation, your code should
filter out incompatible types before feeding them to Dcast.
-}
{- up casting -}
class Ucast l1 l2 where
ucast :: l1 -> l2
{- down casting -}
class Dcast l1 l2 where
dcast :: FileLoc -> l1 -> l2
instance Ucast l l where
ucast = id
instance Dcast l l where
dcast _ = id
{- A datum that can be casted to a constant -}
class Cvalue x where
toConst :: x -> Const
instance Cvalue Int32 where
toConst = C_s32
instance Cvalue Int64 where
toConst = C_s64
instance Cvalue Word32 where
toConst = C_u32
instance Cvalue Word64 where
toConst = C_u64
{- A data that can be casted to a value -}
class Rvalue x where
toRvalue :: x -> Value
instance Rvalue LocalId where
toRvalue = Val_ssa
instance Rvalue GlobalId where
toRvalue = Val_const . C_globalAddr
instance Rvalue Const where
toRvalue = Val_const
instance Rvalue Int32 where
toRvalue = Val_const . C_s32
instance Rvalue Word32 where
toRvalue = Val_const . C_u32
instance Rvalue Word64 where
toRvalue = Val_const . C_u64
{- Typed Integer Constant, Typed Integer Constants are often used in
indexing memory elements.
-}
class TC x where
toTC :: x -> T (Type ScalarB I) Const
instance TC Word32 where
toTC x = T (TpI 32) (toConst x)
instance TC Word64 where
toTC x = T (TpI 64) (toConst x)
instance TC Int32 where
toTC x = T (TpI 32) (toConst x)
{- Typed Integer Value. -}
class TV x where
toTV :: x -> T (Type ScalarB I) Value
instance TV Word32 where
toTV x = T (TpI 32) (toRvalue x)
instance TV Int32 where
toTV x = T (TpI 32) (toRvalue x)
toTVs :: TV x => [x] -> [T (Type ScalarB I) Value]
toTVs l = fmap toTV l
toTCs :: TC x => [x] -> [T (Type ScalarB I) Const]
toTCs l = fmap toTC l
i32sToTvs :: [Int32] -> [T (Type ScalarB I) Value]
i32sToTvs = toTVs
i32sToTcs :: [Int32] -> [T (Type ScalarB I) Const]
i32sToTcs = toTCs
u32sToTvs :: [Word32] -> [T (Type ScalarB I) Value]
u32sToTvs = toTVs
u32sToTcs :: [Word32] -> [T (Type ScalarB I) Const]
u32sToTcs = toTCs
i32ToTv :: Int32 -> T (Type ScalarB I) Value
i32ToTv = toTV
u32ToTv :: Word32 -> T (Type ScalarB I) Value
u32ToTv = toTV
instance Ucast Const Value where
ucast = Val_const
instance Dcast Value Const where
dcast lc x = case x of
Val_const v -> v
_ -> dcastError lc "Const" x
instance (Ucast t s, Ucast u v) => Ucast (T t u) (T s v) where
ucast (T t u) = T (ucast t) (ucast u)
instance (Dcast s t, Dcast v u) => Dcast (T s v) (T t u) where
dcast lc (T s v) = T (dcast lc s) (dcast lc v)
{- Type s r, which represents all types, ucast to Utype -}
instance Ucast (Type s r) Utype where
ucast x = case x of
TpI _ -> UtypeScalarI x
TpF _ -> UtypeScalarF x
TpV _ -> UtypeScalarI x
Tvoid -> UtypeVoidU x
TpHalf -> UtypeScalarF x
TpFloat -> UtypeScalarF x
TpDouble -> UtypeScalarF x
TpFp128 -> UtypeScalarF x
TpX86Fp80 -> UtypeScalarF x
TpPpcFp128 -> UtypeScalarF x
TpX86Mmx -> UtypeScalarI x
TpNull -> UtypeScalarI x
TpLabel -> UtypeLabelX x
Topaque -> UtypeOpaqueD x
TvectorI _ _ -> UtypeVectorI x
TvectorF _ _ -> UtypeVectorF x
TvectorP _ _ -> UtypeVectorP x
Tfirst_class_array _ _ -> UtypeFirstClassD x
Tfirst_class_struct _ _ -> UtypeFirstClassD x
Tfirst_class_name _ -> UtypeFirstClassD x
Tfirst_class_quoteName _ -> UtypeFirstClassD x
Tfirst_class_no _ -> UtypeFirstClassD x
Tarray _ _ -> UtypeRecordD x
Tstruct _ _ -> UtypeRecordD x
Topaque_struct _ _ -> UtypeOpaqueD x
Topaque_array _ _ -> UtypeOpaqueD x
Tpointer _ _ -> UtypeScalarP x
Tfunction _ _ _ -> UtypeFunX x
{- Scalar -}
TnameScalarI _ -> UtypeScalarI x
TquoteNameScalarI _ -> UtypeScalarI x
TnoScalarI _ -> UtypeScalarI x
TnameScalarF _ -> UtypeScalarF x
TquoteNameScalarF _ -> UtypeScalarF x
TnoScalarF _ -> UtypeScalarF x
TnameScalarP _ -> UtypeScalarP x
TquoteNameScalarP _ -> UtypeScalarP x
TnoScalarP _ -> UtypeScalarP x
{- Vector -}
TnameVectorI _ -> UtypeVectorI x
TquoteNameVectorI _ -> UtypeVectorI x
TnoVectorI _ -> UtypeVectorI x
TnameVectorF _ -> UtypeVectorF x
TquoteNameVectorF _ -> UtypeVectorF x
TnoVectorF _ -> UtypeVectorF x
TnameVectorP _ -> UtypeVectorP x
TquoteNameVectorP _ -> UtypeVectorP x
TnoVectorP _ -> UtypeVectorP x
{- Large -}
TnameRecordD _ -> UtypeRecordD x
TquoteNameRecordD _ -> UtypeRecordD x
TnoRecordD _ -> UtypeRecordD x
{- Code -}
TnameCodeFunX _ -> UtypeFunX x
TquoteNameCodeFunX _ -> UtypeFunX x
TnoCodeFunX _ -> UtypeFunX x
{- Opaque -}
TnameOpaqueD _ -> UtypeOpaqueD x
TquoteNameOpaqueD _ -> UtypeOpaqueD x
TnoOpaqueD _ -> UtypeOpaqueD x
instance Dcast Utype (Type ScalarB I) where
dcast lc e = case e of
UtypeScalarI x -> x
_ -> dcastError lc "Type ScalarB I" e
instance Dcast Utype (Type ScalarB F) where
dcast lc e = case e of
UtypeScalarF x -> x
_ -> dcastError lc "Type ScalarB F" e
instance Dcast Utype (Type ScalarB P) where
dcast lc e = case e of
UtypeScalarP x -> x
_ -> dcastError lc "Type ScalarB P" e
instance Dcast Utype (Type VectorB I) where
dcast lc e = case e of
UtypeVectorI x -> x
_ -> dcastError lc "Type VectorB I" e
instance Dcast Utype (Type VectorB F) where
dcast lc e = case e of
UtypeVectorF x -> x
_ -> dcastError lc "Type VectorB F" e
instance Dcast Utype (Type VectorB P) where
dcast lc e = case e of
UtypeVectorP x -> x
_ -> dcastError lc "Type VectorB P" e
instance Dcast Utype (Type FirstClassB D) where
dcast lc e = case e of
UtypeFirstClassD x -> x
_ -> dcastError lc "Type FirstClassB D" e
instance Dcast Utype (Type RecordB D) where
dcast lc e = case e of
UtypeRecordD x -> x
_ -> dcastError lc "Type RecordB D" e
instance Dcast Utype (Type CodeFunB X) where
dcast lc e = case e of
UtypeFunX x -> x
_ -> dcastError lc "Type CodeFunB X" e
instance Dcast Utype (Type CodeLabelB X) where
dcast lc e = case e of
UtypeLabelX x -> x
_ -> dcastError lc "Type CodeLabelB X" e
instance Dcast Utype (Type OpaqueB D) where
dcast lc e = case e of
UtypeOpaqueD x -> x
_ -> dcastError lc "Type OpaqueB D" e
{- Etype's dcast, ucast, dcast -}
instance Dcast Utype Etype where
dcast lc x = case x of
UtypeScalarI e -> EtypeScalarI e
UtypeScalarF e -> EtypeScalarF e
UtypeScalarP e -> EtypeScalarP e
UtypeVectorI e -> EtypeVectorI e
UtypeVectorF e -> EtypeVectorF e
UtypeVectorP e -> EtypeVectorP e
UtypeFirstClassD e -> EtypeFirstClassD e
UtypeRecordD e -> EtypeRecordD e
UtypeOpaqueD e -> EtypeOpaqueD e
UtypeFunX e -> EtypeFunX e
_ -> dcastError lc "Etype" x
instance Ucast Etype Utype where
ucast x = case x of
EtypeScalarI e -> UtypeScalarI e
EtypeScalarF e -> UtypeScalarF e
EtypeScalarP e -> UtypeScalarP e
EtypeVectorI e -> UtypeVectorI e
EtypeVectorF e -> UtypeVectorF e
EtypeVectorP e -> UtypeVectorP e
EtypeFirstClassD e -> UtypeFirstClassD e
EtypeRecordD e -> UtypeRecordD e
EtypeOpaqueD e -> UtypeOpaqueD e
EtypeFunX e -> UtypeFunX e
instance Dcast Etype Dtype where
dcast lc x = case x of
EtypeScalarI e -> DtypeScalarI e
EtypeScalarF e -> DtypeScalarF e
EtypeScalarP e -> DtypeScalarP e
EtypeVectorI e -> DtypeVectorI e
EtypeVectorF e -> DtypeVectorF e
EtypeVectorP e -> DtypeVectorP e
EtypeFirstClassD e -> DtypeFirstClassD e
EtypeRecordD e -> DtypeRecordD e
_ -> dcastError lc "Dtype" x
instance Dcast (Type s r) Etype where
dcast lc x = let (x1::Utype) = ucast x
in dcast lc x1
instance Ucast (Type x I) Etype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x F) Etype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x P) Etype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type FirstClassB x) Etype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type RecordB D) Etype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type CodeFunB X) Etype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
{- Rtype's dcast, ucast, dcast -}
instance Dcast Utype Rtype where
dcast lc x = case x of
UtypeScalarI e -> RtypeScalarI e
UtypeScalarF e -> RtypeScalarF e
UtypeScalarP e -> RtypeScalarP e
UtypeVectorI e -> RtypeVectorI e
UtypeVectorF e -> RtypeVectorF e
UtypeVectorP e -> RtypeVectorP e
UtypeRecordD e -> RtypeRecordD e
UtypeVoidU e -> RtypeVoidU e
_ -> dcastError lc "Rtype" x
instance Ucast Rtype Utype where
ucast x = case x of
RtypeScalarI e -> UtypeScalarI e
RtypeScalarF e -> UtypeScalarF e
RtypeScalarP e -> UtypeScalarP e
RtypeVectorI e -> UtypeVectorI e
RtypeVectorF e -> UtypeVectorF e
RtypeVectorP e -> UtypeVectorP e
RtypeRecordD e -> UtypeRecordD e
RtypeFirstClassD e -> UtypeFirstClassD e
RtypeVoidU e -> UtypeVoidU e
instance Dcast Rtype Dtype where
dcast lc x = case x of
RtypeScalarI e -> DtypeScalarI e
RtypeScalarF e -> DtypeScalarF e
RtypeScalarP e -> DtypeScalarP e
RtypeVectorI e -> DtypeVectorI e
RtypeVectorF e -> DtypeVectorF e
RtypeVectorP e -> DtypeVectorP e
RtypeRecordD e -> DtypeRecordD e
_ -> dcastError lc "Rtype" x
instance Dcast (Type s r) Rtype where
dcast lc x = let (x1::Utype) = ucast x
in dcast lc x1
instance Ucast (Type x I) Rtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x F) Rtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x P) Rtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type FirstClassB D) Rtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type RecordB D) Rtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type NoB U) Rtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
{- Dtype's dcast, ucast, dcast -}
instance Dcast Utype Dtype where
dcast lc x = case x of
UtypeScalarI e -> DtypeScalarI e
UtypeScalarF e -> DtypeScalarF e
UtypeScalarP e -> DtypeScalarP e
UtypeVectorI e -> DtypeVectorI e
UtypeVectorF e -> DtypeVectorF e
UtypeVectorP e -> DtypeVectorP e
UtypeFirstClassD e -> DtypeFirstClassD e
UtypeRecordD e -> DtypeRecordD e
_ -> dcastError lc "Dtype" x
instance Ucast Dtype Utype where
ucast x = case x of
DtypeScalarI e -> UtypeScalarI e
DtypeScalarF e -> UtypeScalarF e
DtypeScalarP e -> UtypeScalarP e
DtypeVectorI e -> UtypeVectorI e
DtypeVectorF e -> UtypeVectorF e
DtypeVectorP e -> UtypeVectorP e
DtypeFirstClassD e -> UtypeFirstClassD e
DtypeRecordD e -> UtypeRecordD e
instance Ucast Dtype Etype where
ucast x = case x of
DtypeScalarI e -> EtypeScalarI e
DtypeScalarF e -> EtypeScalarF e
DtypeScalarP e -> EtypeScalarP e
DtypeVectorI e -> EtypeVectorI e
DtypeVectorF e -> EtypeVectorF e
DtypeVectorP e -> EtypeVectorP e
DtypeFirstClassD e -> EtypeFirstClassD e
DtypeRecordD e -> EtypeRecordD e
instance Ucast Dtype Rtype where
ucast x = case x of
DtypeScalarI e -> RtypeScalarI e
DtypeScalarF e -> RtypeScalarF e
DtypeScalarP e -> RtypeScalarP e
DtypeVectorI e -> RtypeVectorI e
DtypeVectorF e -> RtypeVectorF e
DtypeVectorP e -> RtypeVectorP e
DtypeFirstClassD e -> RtypeFirstClassD e
DtypeRecordD e -> RtypeRecordD e
instance Dcast (Type s r) Dtype where
dcast lc x = let (x1::Utype) = ucast x
in dcast lc x1
instance Ucast (Type x I) Dtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x F) Dtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x P) Dtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type RecordB D) Dtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type FirstClassB D) Dtype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Dcast Dtype (Type ScalarB P) where
dcast lc x = case x of
DtypeScalarP e -> e
_ -> dcastError lc "Type ScalarB P" x
instance Dcast Dtype (Type ScalarB I) where
dcast lc x = case x of
DtypeScalarI e -> e
_ -> dcastError lc "Type ScalarB I" x
instance Dcast Dtype (Type RecordB D) where
dcast lc x = case x of
DtypeRecordD e -> e
_ -> dcastError lc "Type RecordB D" x
{- Ftype's dcast, ucast, dcast -}
instance Dcast Utype Ftype where
dcast lc x = case x of
UtypeScalarI e -> FtypeScalarI e
UtypeScalarF e -> FtypeScalarF e
UtypeScalarP e -> FtypeScalarP e
UtypeVectorI e -> FtypeVectorI e
UtypeVectorF e -> FtypeVectorF e
UtypeVectorP e -> FtypeVectorP e
UtypeFirstClassD e -> FtypeFirstClassD e
_ -> dcastError lc "Ftype" x
instance Ucast Ftype Utype where
ucast x = case x of
FtypeScalarI e -> UtypeScalarI e
FtypeScalarF e -> UtypeScalarF e
FtypeScalarP e -> UtypeScalarP e
FtypeVectorI e -> UtypeVectorI e
FtypeVectorF e -> UtypeVectorF e
FtypeVectorP e -> UtypeVectorP e
FtypeFirstClassD e -> UtypeFirstClassD e
instance Ucast Ftype Dtype where
ucast x = case x of
FtypeScalarI e -> DtypeScalarI e
FtypeScalarF e -> DtypeScalarF e
FtypeScalarP e -> DtypeScalarP e
FtypeVectorI e -> DtypeVectorI e
FtypeVectorF e -> DtypeVectorF e
FtypeVectorP e -> DtypeVectorP e
FtypeFirstClassD e -> DtypeFirstClassD e
instance Dcast (Type s r) Ftype where
dcast lc x = let (x1::Utype) = ucast x
in dcast lc x1
instance Ucast (Type x I) Ftype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x F) Ftype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x P) Ftype where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
{- ScalarType's dcast, ucast, dcast -}
instance Dcast Utype ScalarType where
dcast lc x = case x of
UtypeScalarI e -> ScalarTypeI e
UtypeScalarF e -> ScalarTypeF e
UtypeScalarP e -> ScalarTypeP e
_ -> dcastError lc "ScalarType" x
instance Ucast ScalarType Utype where
ucast x = case x of
ScalarTypeI e -> UtypeScalarI e
ScalarTypeF e -> UtypeScalarF e
ScalarTypeP e -> UtypeScalarP e
instance Dcast Dtype ScalarType where
dcast lc x = case x of
DtypeScalarI e -> ScalarTypeI e
DtypeScalarF e -> ScalarTypeF e
DtypeScalarP e -> ScalarTypeP e
_ -> dcastError lc "ScalarType" x
instance Ucast ScalarType Dtype where
ucast x = case x of
ScalarTypeI e -> DtypeScalarI e
ScalarTypeF e -> DtypeScalarF e
ScalarTypeP e -> DtypeScalarP e
instance Dcast (Type s r) ScalarType where
dcast lc x = let (x1::Utype) = ucast x
in dcast lc x1
instance Ucast (Type x I) ScalarType where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x F) ScalarType where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type x P) ScalarType where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
{- IntOrPtrType's dcast, ucast, dcast -}
instance Dcast Utype (IntOrPtrType ScalarB) where
dcast lc x = case x of
UtypeScalarI e -> IntOrPtrTypeI e
UtypeScalarP e -> IntOrPtrTypeP e
_ -> dcastError lc "IntOrPtrType ScalarB" x
instance Dcast Utype (IntOrPtrType VectorB) where
dcast lc x = case x of
UtypeVectorI e -> IntOrPtrTypeI e
UtypeVectorP e -> IntOrPtrTypeP e
_ -> dcastError lc "IntOrPtrType VectorB" x
instance Ucast (IntOrPtrType ScalarB) Utype where
ucast x = case x of
IntOrPtrTypeI e -> UtypeScalarI e
IntOrPtrTypeP e -> UtypeScalarP e
instance Ucast (IntOrPtrType VectorB) Utype where
ucast x = case x of
IntOrPtrTypeI e -> UtypeVectorI e
IntOrPtrTypeP e -> UtypeVectorP e
instance Dcast (Type s r) (IntOrPtrType ScalarB) where
dcast lc x = let (x1::Utype) = ucast x
in dcast lc x1
instance Dcast (Type s r) (IntOrPtrType VectorB) where
dcast lc x = let (x1::Utype) = ucast x
in dcast lc x1
instance Ucast (Type ScalarB I) (IntOrPtrType ScalarB) where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type ScalarB P) (IntOrPtrType ScalarB) where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type VectorB I) (IntOrPtrType VectorB) where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
instance Ucast (Type VectorB P) (IntOrPtrType VectorB) where
ucast x = let (x1::Utype) = ucast x
in dcast (FileLoc "irrefutable") x1
squeeze :: FileLoc -> Type RecordB D -> Type FirstClassB D
squeeze loc x = case x of
Tstruct pk dl -> Tfirst_class_struct pk (fmap (dcast loc) dl)
Tarray n el -> Tfirst_class_array n (dcast loc el)
TnameRecordD e -> Tfirst_class_name e
TquoteNameRecordD e -> Tfirst_class_quoteName e
TnoRecordD e -> Tfirst_class_no e
uc :: Ucast a b => a -> b
uc x = ucast x
dc :: Dcast a b => FileLoc -> String -> a -> b
dc lc s x = dcast lc x
|
sanjoy/hLLVM
|
src/Llvm/Hir/Cast.hs
|
bsd-3-clause
| 18,850
| 0
| 12
| 4,800
| 6,835
| 3,192
| 3,643
| 482
| 5
|
{-# LANGUAGE UndecidableInstances #-}
-- | A value-level category with a type of objects and a type of
-- 'loose' morphisms. An `Arrow` is a `LooseMorphism` together with
-- its domain and codomain.
module Math.ValueCategory where
class (Semigroup (Arrow ob)) => ValueCategory ob where
type LooseMorphism ob = (mor :: *) | mor -> ob
looseid :: ob -> LooseMorphism ob
-- domain :: Morphism ob -> ob
-- codomain :: Morphism ob -> ob
data Arrow a = Arrow {domain :: a, mor :: LooseMorphism a, codomain :: a}
deriving instance (Show a, Show (LooseMorphism a)) => Show (Arrow a)
data CompArrows a = CompArrows a (LooseMorphism a) a (LooseMorphism a) a
vid :: ValueCategory ob => ob -> Arrow ob
vid a = Arrow a (looseid a) a
data Square a = Square
{ squareTop :: LooseMorphism a,
squareBottom :: LooseMorphism a
}
instance (Semigroup (LooseMorphism a)) => Semigroup (Square a) where
(Square t b) <> (Square t' b') = Square (t <> t') (b <> b')
instance (ValueCategory ob) => ValueCategory (Arrow ob) where
type LooseMorphism (Arrow ob) = Square ob
looseid (Arrow d f c) = Square (looseid d) (looseid c)
-- domain = Arrow . squareDomain
-- codomain = Arrow . squareCodomain
instance (Semigroup (Arrow ob)) => Semigroup (Arrow (Arrow ob)) where
(Arrow _ (Square tf bf) c@(Arrow cd _ cc)) <> (Arrow d@(Arrow dd _ dc) (Square tg bg) (Arrow md _ mc)) =
Arrow d (Square tfg bfg) c
where
Arrow _ tfg _ = Arrow md tf cd <> Arrow dd tg md
Arrow _ bfg _ = Arrow mc bf cc <> Arrow dc bg mc
|
mvr/at
|
src/Math/ValueCategory.hs
|
bsd-3-clause
| 1,536
| 1
| 11
| 339
| 576
| 299
| 277
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
module Main
(main
, go
) where
import BasicPrelude
import Control.Concurrent.MVar
import Data.Map (Map)
import qualified Data.Map as M
import Filesystem
import Filesystem.Path.CurrentOS
import System.INotify
import System.Linux.Cgroups
main = getArgs >>= go
go (path:_) = do
let upath = unsafeCgroup $ fromText path
tasks = tasksFile upath
m <- newEmptyMVar
withINotify $ \notify ->
bracket (addWatch notify [AllEvents] (encodeString tasks)
(\e -> do t <- getTasks' upath
print t
when (length t < 50) (putMVar m ())))
(removeWatch)
(const $ takeMVar m)
|
qnikst/cgroups-hs
|
example/cgroup_watchdog.hs
|
bsd-3-clause
| 709
| 0
| 19
| 207
| 220
| 118
| 102
| 24
| 1
|
{-# LANGUAGE PackageImports, PatternGuards #-}
module Data.ICalendar.RRule ( RRule(..)
, RFreq(..)
, parseRRule
, recurrences
) where
import Data.Char (isDigit)
import Control.Monad (ap, (>=>), liftM)
import "mtl" Control.Monad.Writer (Writer, writer, tell, execWriter)
import Data.Maybe (listToMaybe, isJust, isNothing)
import Control.Arrow
import Data.List.Split (splitOn)
import Data.Time.LocalTime
import Data.Time.Clock (UTCTime)
import Data.Time.Recurrence
import Data.Time.CalendarTime
import Data.ICalendar.Parse
import Data.ICalendar.Types
data RFreq = Yearly | Monthly | Weekly | Daily | Hourly | Minutely | Secondly
deriving (Show, Eq)
data RRule = RRule { rFreq :: RFreq
, rInterval :: Integer
, rDateStart :: CalendarTime
, rCount :: Maybe Int
, rUntil :: Maybe CalendarTime
, rBySecond :: Maybe [Int]
, rByMinute :: Maybe [Int]
, rByHour :: Maybe [Int]
, rByWeekDay :: Maybe [(WeekDay, Maybe Int)]
, rByMonthDay :: Maybe [Int]
, rByYearDay :: Maybe [Int]
, rByWeekNo :: Maybe [Int]
, rByMonth :: Maybe [Month]
, rBySetPos :: Maybe [Int]
, rWeekStart :: WeekDay }
deriving (Show, Eq)
findDay :: String -> WeekDay
findDay "MO" = Monday
findDay "TU" = Tuesday
findDay "WE" = Wednesday
findDay "TH" = Thursday
findDay "FR" = Friday
findDay "SA" = Saturday
findDay "SU" = Sunday
findDay _ = error "Unknown day"
findFreq :: String -> RFreq
findFreq "YEARLY" = Yearly
findFreq "MONTHLY" = Monthly
findFreq "WEEKLY" = Weekly
findFreq "HOURLY" = Hourly
findFreq "MINUTELY" = Minutely
findFreq "SECONDLY" = Secondly
parseRRule :: TimeZone -> ICalObject -> IO (Maybe RRule)
parseRRule localTz obj =
let dtstart = maybe (error "No DTSTART found") id $ lookupProp obj "DTSTART"
dtend = return parseDateTimeProp `ap` lookupProp obj "DTEND"
rrule = lookupPropValue obj "RRULE"
in do dtstart' <- parseDateTimeProp dtstart
case (rrule, dtstart') of
(Nothing, _) -> return Nothing
(Just rrule, Nothing) -> error "Failed to parse DTSTART"
(Just rrule, Just d) -> return $ Just $ parseRRule' localTz d rrule
-- | Parse an ICal formatted RRULE with the given STARTDT
parseRRule' :: TimeZone -> CalendarTime -> String -> RRule
parseRRule' localTz dtstart rrule
= let terms = map (break (=='=') >>> second (arr $ drop 1)) $ splitOn ";" rrule
splitList = splitOn ","
parseList :: Read a => String -> [a]
parseList = map read . splitList
parseDate :: String -> CalendarTime
parseDate = maybe (error "DTSTART parse error") id . readDateTime localTz
parseByDay :: String -> (WeekDay, Maybe Int)
parseByDay a = let (n,day) = span isDigit a
n' = case n of "" -> Nothing
a -> Just $ read a
in (findDay day, n')
in RRule { rFreq = maybe (error "No recurrence frequency given") findFreq $ lookup "FREQ" terms
, rInterval = maybe 1 read $ lookup "INTERVAL" terms
, rDateStart = maybe dtstart parseDate $ lookup "DTSTART" terms
, rCount = return read `ap` lookup "COUNT" terms
, rUntil = return parseDate `ap` lookup "UNTIL" terms
, rBySecond = return parseList `ap` lookup "BYSECOND" terms
, rByMinute = return parseList `ap` lookup "BYMINUTE" terms
, rByHour = return parseList `ap` lookup "BYHOUR" terms
, rByWeekDay = return (map parseByDay . splitList) `ap` lookup "BYDAY" terms
, rByMonthDay = return parseList `ap` lookup "BYMONTHDAY" terms
, rByYearDay = return parseList `ap` lookup "BYYEARDAY" terms
, rByWeekNo = return parseList `ap` lookup "BYWEEKNO" terms
, rByMonth = return (map toEnum . parseList) `ap` lookup "BYMONTH" terms
, rBySetPos = return parseList `ap` lookup "BYSETPOS" terms
, rWeekStart = maybe Monday findDay $ lookup "WKST" terms }
validateRRule :: RRule -> Maybe String
validateRRule = listToMaybe . execWriter . validateRRule'
validateRRule' :: RRule -> Writer [String] ()
validateRRule' rr =
do testMaybe (rBySecond rr) (and . map (\v->v >= 0 && v <= 60)) "Invalid BYSECOND value"
testMaybe (rByMinute rr) (and . map (\v->v >= 0 && v <= 60)) "Invalid BYMINUTE value"
testMaybe (rByHour rr) (and . map (\v->v >= 0 && v <= 23)) "Invalid BYHOUR value"
testMaybe (rByMonthDay rr) (and . map (\v->v >= 1 && v <= 31)) "Invalid BYMONTHDAY value"
testMaybe (rByMonthDay rr) (and . map (\v->v <= -1 && v >= -31)) "Invalid BYMONTHDAY value"
testMaybe (rByYearDay rr) (and . map (\v->v >= 1 && v <= 366)) "Invalid BYYEARDAY value"
testMaybe (rByYearDay rr) (and . map (\v->v <= -1 && v >= -366)) "Invalid BYYEARDAY value"
testMaybe (rByWeekNo rr) (and . map (\v->v >= 1 && v <= 53)) "Invalid BYWEEKNO value"
testMaybe (rByWeekNo rr) (and . map (\v->v <= -1 && v >= -53)) "Invalid BYWEEKNO value"
test (isNothing $ rBySetPos rr) "BYSETPOS not implemented"
testMaybe (rByWeekDay rr) (and . map (\(_,v)->isNothing v)) "Numberic BYDAY not implemented"
where test :: Bool -> String -> Writer [String] ()
test True _ = return ()
test False msg = tell [msg]
testMaybe :: Maybe a -> (a -> Bool) -> String -> Writer [String] ()
testMaybe (Just a) condf b = test (condf a) b
testMaybe Nothing _ _ = return ()
buildSched :: (CalendarTimeConvertible a, Moment a) => RRule -> [a] -> Schedule a
buildSched rr
| Yearly <- rFreq rr =
f enumMonths (rByMonth rr)
-- >=> f enumWeekNumbers (rByWeekNo rr) -- TODO
>=> f enumYearDays (rByYearDay rr)
>=> f enumDays (rByMonthDay rr)
>=> f enumWeekDaysInMonth (liftM (map fst) $ rByWeekDay rr)
>=> f enumHours (rByHour rr)
>=> f enumMinutes (rByMinute rr)
>=> f enumSeconds (rBySecond rr)
| Monthly <- rFreq rr =
f filterMonths (rByMonth rr)
>=> f enumDays (rByMonthDay rr)
>=> f enumWeekDaysInMonth (liftM (map fst) $ rByWeekDay rr)
>=> f enumHours (rByHour rr)
>=> f enumMinutes (rByMinute rr)
>=> f enumSeconds (rBySecond rr)
| Weekly <- rFreq rr =
f filterMonths (rByMonth rr)
>=> f enumWeekDaysInMonth (liftM (map fst) $ rByWeekDay rr)
>=> f enumHours (rByHour rr)
>=> f enumMinutes (rByMinute rr)
>=> f enumSeconds (rBySecond rr)
| Daily <- rFreq rr =
f filterMonths (rByMonth rr)
>=> f filterDays (rByMonthDay rr)
>=> f filterWeekDays (liftM (map fst) $ rByWeekDay rr)
>=> f enumHours (rByHour rr)
>=> f enumMinutes (rByMinute rr)
>=> f enumSeconds (rBySecond rr)
| Hourly <- rFreq rr =
f filterMonths (rByMonth rr)
>=> f filterYearDays (rByYearDay rr)
>=> f filterDays (rByMonthDay rr)
>=> f filterWeekDays (liftM (map fst) $ rByWeekDay rr)
>=> f filterHours (rByHour rr)
>=> f enumMinutes (rByMinute rr)
>=> f enumSeconds (rBySecond rr)
| Minutely <- rFreq rr =
f filterMonths (rByMonth rr)
>=> f filterYearDays (rByYearDay rr)
>=> f filterDays (rByMonthDay rr)
>=> f filterWeekDays (liftM (map fst) $ rByWeekDay rr)
>=> f filterHours (rByHour rr)
>=> f filterMinutes (rByMinute rr)
>=> f enumSeconds (rBySecond rr)
| Secondly <- rFreq rr =
f filterMonths (rByMonth rr)
>=> f filterYearDays (rByYearDay rr)
>=> f filterDays (rByMonthDay rr)
>=> f filterWeekDays (liftM (map fst) $ rByWeekDay rr)
>=> f filterHours (rByHour rr)
>=> f filterMinutes (rByMinute rr)
>=> f filterSeconds (rBySecond rr)
where f :: (b -> [a] -> Schedule a) -> Maybe b -> ([a] -> Schedule a)
f g (Just a) = g a
f _ Nothing = return
recurrences :: RRule -> [UTCTime]
recurrences rr = recurrencesStarting rr (rDateStart rr)
recurrencesStarting :: RRule -> CalendarTime -> [UTCTime]
recurrencesStarting rr from = filterUntil $ filterCount $ r
where period = case rFreq rr of
Yearly -> yearly
Monthly -> monthly
Weekly -> weekly
Daily -> daily
Hourly -> hourly
Minutely -> minutely
Secondly -> secondly
start = maybe (error "Failed to convert start time") id $ fromCalendarTime from
r = recur period `withStartOfWeek` rWeekStart rr
`by` rInterval rr
`starting` start
$ buildSched rr
filterUntil, filterCount :: [UTCTime] -> [UTCTime]
filterUntil = case rUntil rr of
Just d -> takeWhile (<= ( maybe (error "Failed to convert until time") id
$ fromCalendarTime d))
Nothing -> id
filterCount = case rCount rr of
Just c -> take c
Nothing -> id
|
bgamari/icalendar
|
Data/ICalendar/RRule.hs
|
bsd-3-clause
| 10,346
| 0
| 17
| 3,868
| 3,176
| 1,615
| 1,561
| 192
| 9
|
{-# LANGUAGE OverloadedStrings #-}
module Milter.Switch (milter) where
import Control.Applicative
import Control.Exception
import Control.Monad (unless)
import Data.ByteString.Char8 (ByteString)
import Data.IORef
import MailSpec
import Milter.Base
import Milter.Env
import Milter.Log
import Milter.Types
import Network.DomainAuth
import RPF
import System.IO
----------------------------------------------------------------
milter :: Env -> Handle -> IORef State -> IO ()
milter env hdl ref = withValidHandleDo $
handle errorHandle $ do
rpkt <- getPacket hdl
switch env hdl ref rpkt
milter env hdl ref
where
errorHandle (SomeException e) = logDebug env ref $ show e
withValidHandleDo blk = do
closed <- hIsClosed hdl
eof <- hIsEOF hdl
unless (eof || closed) blk
switch :: Env -> Handle -> IORef State -> Packet -> IO ()
switch env hdl ref (Packet 'O' bs) = open env hdl ref bs
switch env hdl ref (Packet 'C' bs) = conn env hdl ref bs
switch env hdl ref (Packet 'H' bs) = helo env hdl ref bs
switch env hdl ref (Packet 'M' bs) = mfro env hdl ref bs
switch _ hdl _ (Packet 'R' _ ) = continue hdl
switch _ hdl _ (Packet 'A' _ ) = continue hdl -- xxx
switch env hdl ref (Packet 'L' bs) = hedr env hdl ref bs
switch env hdl ref (Packet 'N' bs) = eohd env hdl ref bs
switch env hdl ref (Packet 'B' bs) = body env hdl ref bs
switch env hdl ref (Packet 'E' bs) = eoms env hdl ref bs
switch _ _ _ (Packet 'D' _) = return ()
switch _ _ _ (Packet 'Q' _) = return ()
switch env _ ref (Packet x _) = logError env ref $ "Switch: " ++ [x]
----------------------------------------------------------------
mfilter :: Env -> Handle -> IORef State -> MailSpec -> BlockName -> IO ()
mfilter env hdl ref ms bn =
let ply = policy env
in case evalRPF ms ply bn of
(l,A_Accept) -> doit accept "Accepted" l
(l,A_Discard) -> doit discard "Discarded" l
(l,A_Hold) -> doit hold "Held" l
(l,A_Reject) -> doit reject "Rejected" l
(_,A_Continue) -> if bn == B_Body
then logResult env ref "Accepted by default" >> continue hdl
else logMonitor env ref "continue" >> continue hdl
where
doit act m l = do
logResult env ref $ m ++ " in line " ++ show l
if logonly env
then accept hdl
else act hdl
----------------------------------------------------------------
type Filter = Env -> Handle -> IORef State -> ByteString -> IO ()
----------------------------------------------------------------
open :: Filter
open env hdl ref _ = do
logMonitor env ref "Milter opened"
negotiate hdl
----------------------------------------------------------------
conn :: Filter
conn env hdl ref bs = do
st <- readIORef ref
let ip = getIP bs
ms = (mailspec st) { msPeerIP = ip }
writeIORef ref st { mailspec = ms }
-- after IP set for logging
logResult env ref "SMTP connected"
logDebug env ref $ '\t' : show ms
mfilter env hdl ref ms B_Connect
----------------------------------------------------------------
helo :: Filter
helo env hdl ref _ = do
logMonitor env ref "HELO"
continue hdl
----------------------------------------------------------------
mfro :: Filter
mfro env hdl ref bs = do
logMonitor env ref "MAIL FROM"
let jmailfrom = extractDomain bs
case jmailfrom of
Nothing -> continue hdl -- xxx
Just dom -> do
st <- readIORef ref
xspf <- getSPF dom st
let ms = (mailspec st) { msSPFResult = xspf, msMailFrom = jmailfrom }
writeIORef ref st { mailspec = ms }
logDebug env ref $ '\t' : show ms
mfilter env hdl ref ms B_MailFrom
where
getSPF dom st = do
let ip = msPeerIP (mailspec st)
spf env dom ip
----------------------------------------------------------------
hedr :: Filter
hedr env hdl ref bs = do
logMonitor env ref "DATA HEADER FIELD"
st <- readIORef ref
let (key,val) = getKeyVal bs
ckey = canonicalizeKey key
xm = pushField key val (xmail st)
prd = pushPRD key val (prdspec st)
(pv,ms) = checkField ckey val (parsedv st) (mailspec st)
writeIORef ref $ st { xmail = xm, mailspec = ms, prdspec = prd, parsedv = pv}
logDebug env ref $ "\t" ++ show xm ++ "\n\t" ++ show ms ++ "\n\t" ++ show prd
continue hdl
where
checkField ckey val pv ms
| ckey == dkFieldKey = case parseDK val of
Nothing -> (pv, ms)
x@(Just pdk) -> (pv { mpdk = x},
ms { msSigDK = True
, msDKFrom = Just (dkDomain pdk) })
| ckey == dkimFieldKey = case parseDKIM val of
Nothing -> (pv, ms)
x@(Just pdkim) -> (pv { mpdkim = x},
ms { msSigDKIM = True
, msDKIMFrom = Just (dkimDomain pdkim) })
| otherwise = (pv, ms)
----------------------------------------------------------------
eohd :: Filter
eohd env hdl ref _ = do
logMonitor env ref "DATA HEADER END"
st <- readIORef ref
let jfrom = getFrom st
jprd = decidePRD (prdspec st)
sid <- getSenderID jprd
let ms = (mailspec st) { msSenderIDResult = sid, msFrom = jfrom, msPRA = jprd }
writeIORef ref st { mailspec = ms }
mfilter env hdl ref ms B_Header
where
getFrom = decideFrom . prdspec
getSenderID jprd =
case jprd of
Nothing -> return DAPermError
Just dom -> do
ms <- mailspec <$> readIORef ref
if jprd == msMailFrom ms
then return $ msSPFResult ms
else let ip = msPeerIP ms
in spf env dom ip
----------------------------------------------------------------
body :: Filter
body env hdl ref bs = do
logMonitor env ref "DATA BODY"
st <- readIORef ref
let bc = getBody bs
xm = pushBody bc (xmail st)
writeIORef ref st { xmail = xm }
continue hdl
----------------------------------------------------------------
eoms :: Filter
eoms env hdl ref _ = do
logMonitor env ref "DATA BODY END"
st <- readIORef ref
let mail = finalizeMail (xmail st)
mdk = mpdk (parsedv st)
mdkim = mpdkim (parsedv st)
xdk <- maybe (return DANone) (dk env mail) mdk
xdkim <- maybe (return DANone) (dkim env mail) mdkim
let ms = (mailspec st) { msDKResult = xdk, msDKIMResult = xdkim }
mfilter env hdl ref ms B_Body
|
kazu-yamamoto/rpf
|
Milter/Switch.hs
|
bsd-3-clause
| 6,556
| 0
| 17
| 1,878
| 2,280
| 1,119
| 1,161
| 153
| 7
|
#!/usr/bin/env runghc
import System.Log.Logger hiding (addHandler)
import Network.XMPP
import Data.Maybe
compDomain = "my-component.example.com"
compPort = 8888
compPasswd = "secret"
xmppAddr = "127.0.0.1"
main = do
updateGlobalLogger "XMPP" $ setLevel DEBUG
updateGlobalLogger "XMPP.Monad" $ setLevel WARNING
c <- openComponent xmppAddr compPort compDomain compPasswd
runXMPP c $ do
addHandler (const True) hndlr True
addHandler isIQReq handlePing True
hndlr e = do
liftIO $ putStrLn $ "Received unknown : "++show e
isIQReq :: XMLElem -> Bool
isIQReq x = isIq x && getAttr "type" x == Just "get"
handlePing :: XMLElem -> XMPP ()
handlePing x = do
sendIqResp x "result" [XML "query" [] []]
return ()
where
from = fromMaybe (error "missing from!") $ getAttr "from" x
sendIqResp inResponseTo iqtype payload =
sendStanza $ XML "iq"
[("to", from),
("from", to),
("type", iqtype),
("id", id)]
payload
where
from = fromMaybe (error "missing from!") $ getAttr "from" inResponseTo
to = fromMaybe (error "missing to!") $ getAttr "to" inResponseTo
id = fromMaybe (error "missing id!") $ getAttr "id" inResponseTo
|
drpowell/XMPP
|
examples/xmpp-component.hs
|
bsd-3-clause
| 1,272
| 2
| 12
| 333
| 400
| 197
| 203
| 33
| 1
|
-- generated by derive.hs
module Prose.Internal.Hebrew_Letter where
hebrew_letter = [
['\x05D0'..'\x05EA'],
['\x05F0'..'\x05F2'],
['\xFB1D'],
['\xFB1F'..'\xFB28'],
['\xFB2A'..'\xFB36'],
['\xFB38'..'\xFB3C'],
['\xFB3E'],
['\xFB40'..'\xFB41'],
['\xFB43'..'\xFB44'],
['\xFB46'..'\xFB4F'] ]
|
llelf/prose
|
Prose/Internal/Hebrew_Letter.hs
|
bsd-3-clause
| 327
| 0
| 6
| 61
| 73
| 49
| 24
| 12
| 1
|
-- |
-- Module: Instruments.Derivatives.Derivatives
-- Copyright: (c) Johan Astborg, Andreas Bock
-- License: BSD-3
-- Maintainer: Andreas Bock <bock@andreasbock.dk>
-- Stability: experimental
-- Portability: portable
--
-- Types and functions for working with interest rates
module Instruments.Derivatives.Derivatives where
import Instruments.Instrument
-- The following class is purely proof of concept
class Instrument d => Derivative d where
data Underlying :: *
underlying :: d -> Underlying
|
HIPERFIT/HQL
|
src/Instruments/Derivatives/Derivatives.hs
|
bsd-3-clause
| 517
| 0
| 7
| 86
| 53
| 34
| 19
| -1
| -1
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.VertexType10f11f11fRev
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.VertexType10f11f11fRev (
-- * Extension Support
glGetARBVertexType10f11f11fRev,
gl_ARB_vertex_type_10f_11f_11f_rev,
-- * Enums
pattern GL_UNSIGNED_INT_10F_11F_11F_REV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/VertexType10f11f11fRev.hs
|
bsd-3-clause
| 702
| 0
| 5
| 91
| 47
| 36
| 11
| 7
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Examples.Intercom.Programs
( fetchConversation
, fetchUser
, fetchAdmin
, fetchAllAdmins
, fetchAllConversations
, firstConversation
) where
import Data.Text (Text)
import qualified Drive as D
import qualified Drive.Intercom as I
type IntercomP a = D.Free I.IntercomF a
fetchConversation :: Text -> IntercomP I.Conversation
fetchConversation c
= I.getConversation (I.ConversationID c)
fetchUser :: Text -> IntercomP I.User
fetchUser c
= I.getUser (I.UserID c)
fetchAdmin :: Text -> IntercomP Text
fetchAdmin c
= I.adminName <$> I.getAdmin (I.AdminID c)
fetchAllAdmins :: IntercomP [Text]
fetchAllAdmins
= (fmap . fmap) I.adminName I.listAdmins
fetchAllConversations :: IntercomP [I.ConversationID]
fetchAllConversations
= I.listConversations
firstConversation :: IntercomP (Either Text I.Conversation)
firstConversation = do
cs <- I.listConversations
case cs of
[] -> pure $ Left "did not get any conversations"
x:_ -> Right <$> I.getConversation x
|
palf/free-driver
|
apps/src/Examples/Intercom/Programs.hs
|
bsd-3-clause
| 1,068
| 0
| 12
| 204
| 302
| 161
| 141
| 33
| 2
|
{-# LANGUAGE DeriveGeneric, GeneralizedNewtypeDeriving, BangPatterns #-}
{-# OPTIONS_GHC -Wall #-}
module Main where
import Control.Applicative
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
import Data.Hashable
import Data.Hashable.Generic
import Data.Word
import GHC.Generics
main :: IO ()
main = defaultMain tests
tests :: [Test]
tests = [ testGroup "Documentation"
[ testProperty "Simple Record" simpleRecord
, testProperty "Recursive Type" recursiveType
, testProperty "Parametric and Recursive Type" paraRecursive
, testProperty "Different values => different hash. This can fail rarely, but not usually."
$ \x y -> x /= y ==> not (haveSameHash x y)
]
]
-- | A value with bit pattern (01)* (or 5* in hexa), for any size of Int.
-- It is used as data constructor distinguisher. GHC computes its value during
-- compilation.
distinguisher :: Int
distinguisher = fromIntegral $ (maxBound :: Word) `quot` 3
{-# INLINE distinguisher #-}
data FooA = FooA AccountId Name Address
deriving (Generic, Show)
instance Arbitrary FooA where
arbitrary = FooA <$> arbitrary
<*> arbitrary
<*> arbitrary
data FooB = FooB AccountId Name Address
type Address = [String]
type Name = String
newtype AccountId = AccountId Int
deriving (Hashable, Show)
instance Arbitrary AccountId where
arbitrary = AccountId <$> arbitrary
instance Hashable FooA where
hashWithSalt s x = gHashWithSalt s x
{-# INLINEABLE hashWithSalt #-}
instance Hashable FooB where
hashWithSalt salt (FooB ac n ad) = hashWithSalt
(hashWithSalt
(hashWithSalt salt ac)
n)
ad
aToB :: FooA -> FooB
aToB (FooA ac n ad) = FooB ac n ad
simpleRecord :: FooA -> Bool
simpleRecord a = let b = aToB a
in hash a == hash b
data NA = ZA | SA NA
deriving (Generic, Show)
data NB = ZB | SB NB
instance Hashable NA where
hashWithSalt s x = gHashWithSalt s x
{-# INLINEABLE hashWithSalt #-}
instance Hashable NB where
hashWithSalt !salt ZB = combine salt 0
hashWithSalt !salt (SB xs) = hashWithSalt (salt `combine` distinguisher) xs
instance Arbitrary NA where
arbitrary = lst2A <$> arbitrary
lst2A :: [()] -> NA
lst2A [] = ZA
lst2A (_:xs) = SA $ lst2A xs
na2nb :: NA -> NB
na2nb ZA = ZB
na2nb (SA x) = SB $ na2nb x
recursiveType :: NA -> Bool
recursiveType a = let b = na2nb a
in hash a == hash b
data BarA a = BarA0 | BarA1 a | BarA2 (BarA a)
deriving (Generic, Show, Eq)
data BarB a = BarB0 | BarB1 a | BarB2 (BarB a)
instance Arbitrary a => Arbitrary (BarA a) where
arbitrary = oneof [ return BarA0
, BarA1 <$> arbitrary
, BarA2 <$> arbitrary
]
instance Hashable a => Hashable (BarA a) where
hashWithSalt s x = gHashWithSalt s x
{-# INLINEABLE hashWithSalt #-}
instance Hashable a => Hashable (BarB a) where
hashWithSalt !salt BarB0 = salt `combine` 0
hashWithSalt !salt (BarB1 x) = hashWithSalt (salt `combine` distinguisher `combine` 0) x
hashWithSalt !salt (BarB2 x) = hashWithSalt (salt `combine` distinguisher `combine` distinguisher) x
barA2B :: BarA a -> BarB a
barA2B BarA0 = BarB0
barA2B (BarA1 x) = BarB1 x
barA2B (BarA2 x) = BarB2 $ barA2B x
paraRecursive :: BarA Int -> Bool
paraRecursive a = let b = barA2B a
in hash a == hash b
haveSameHash :: BarA Int -> BarA Int -> Bool
haveSameHash x y = hash x == hash y
|
cgaebel/hashable-generics
|
test/Suite.hs
|
bsd-3-clause
| 3,735
| 0
| 13
| 1,079
| 1,100
| 573
| 527
| 90
| 1
|
-- | Main module to run all tests.
--
module TestSuite where
import Test.Framework (defaultMain, testGroup)
import qualified Text.Blaze.Tests
import qualified Text.Blaze.Tests.Cases
import qualified Util.Tests
main :: IO ()
main = defaultMain
[ testGroup "Text.Blaze.Tests" Text.Blaze.Tests.tests
, testGroup "Text.Blaze.Tests.Cases" Text.Blaze.Tests.Cases.tests
, testGroup "Util.Tests" Util.Tests.tests
]
|
jgm/blaze-html
|
tests/TestSuite.hs
|
bsd-3-clause
| 444
| 0
| 8
| 82
| 94
| 58
| 36
| 10
| 1
|
module Gtk.Samples.Internal
(
) where
|
nishihs/gtk-samples
|
src/Gtk/Samples/Internal.hs
|
bsd-3-clause
| 46
| 0
| 3
| 13
| 10
| 7
| 3
| 2
| 0
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
module Data.Type.Remove.Util where
import Data.Kind
import Data.Proxy
import Data.Type.Length
import Data.Type.Remove
import Type.Family.List
data RemPart :: [k] -> k -> [k] -> Type where
RP :: !(Length cs)
-> !(Proxy a)
-> !(Length ds)
-> RemPart (cs ++ '[a] ++ ds) a (cs ++ ds)
remPart :: Length as -> Remove as a bs -> RemPart as a bs
remPart = \case
LZ -> \case
LS l -> \case
RZ -> RP LZ Proxy l
RS s -> case remPart l s of
RP lC pA lD -> RP (LS lC) pA lD
|
mstksg/tensor-ops
|
src/Data/Type/Remove/Util.hs
|
bsd-3-clause
| 840
| 0
| 16
| 282
| 249
| 134
| 115
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Provers.Z3
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- The connection to the Z3 SMT solver
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
module Data.SBV.Provers.Z3(z3) where
import qualified Control.Exception as C
import Data.Char (toLower)
import Data.Function (on)
import Data.List (sortBy, intercalate, isPrefixOf, groupBy)
import System.Environment (getEnv)
import qualified System.Info as S(os)
import Data.SBV.BitVectors.AlgReals
import Data.SBV.BitVectors.Data
import Data.SBV.BitVectors.PrettyNum
import Data.SBV.SMT.SMT
import Data.SBV.SMT.SMTLib
import Data.SBV.Utils.Lib (splitArgs)
-- Choose the correct prefix character for passing options
-- TBD: Is there a more foolproof way of determining this?
optionPrefix :: Char
optionPrefix
| map toLower S.os `elem` ["linux", "darwin"] = '-'
| True = '/' -- windows
-- | The description of the Z3 SMT solver
-- The default executable is @\"z3\"@, which must be in your path. You can use the @SBV_Z3@ environment variable to point to the executable on your system.
-- The default options are @\"-in -smt2\"@, which is valid for Z3 4.1. You can use the @SBV_Z3_OPTIONS@ environment variable to override the options.
z3 :: SMTSolver
z3 = SMTSolver {
name = Z3
, executable = "z3"
, options = map (optionPrefix:) ["in", "smt2"]
, engine = \cfg isSat qinps modelMap skolemMap pgm -> do
execName <- getEnv "SBV_Z3" `C.catch` (\(_ :: C.SomeException) -> return (executable (solver cfg)))
execOpts <- (splitArgs `fmap` getEnv "SBV_Z3_OPTIONS") `C.catch` (\(_ :: C.SomeException) -> return (options (solver cfg)))
let cfg' = cfg { solver = (solver cfg) {executable = execName, options = addTimeOut (timeOut cfg) execOpts} }
tweaks = case solverTweaks cfg' of
[] -> ""
ts -> unlines $ "; --- user given solver tweaks ---" : ts ++ ["; --- end of user given tweaks ---"]
dlim = printRealPrec cfg'
ppDecLim = "(set-option :pp.decimal_precision " ++ show dlim ++ ")\n"
script = SMTScript {scriptBody = tweaks ++ ppDecLim ++ pgm, scriptModel = Just (cont (roundingMode cfg) skolemMap)}
if dlim < 1
then error $ "SBV.Z3: printRealPrec value should be at least 1, invalid value received: " ++ show dlim
else standardSolver cfg' script cleanErrs (ProofError cfg') (interpretSolverOutput cfg' (extractMap isSat qinps modelMap))
, xformExitCode = id
, capabilities = SolverCapabilities {
capSolverName = "Z3"
, mbDefaultLogic = Nothing
, supportsMacros = True
, supportsProduceModels = True
, supportsQuantifiers = True
, supportsUninterpretedSorts = True
, supportsUnboundedInts = True
, supportsReals = True
, supportsFloats = True
, supportsDoubles = True
}
}
where cleanErrs = intercalate "\n" . filter (not . junk) . lines
junk = ("WARNING:" `isPrefixOf`)
cont rm skolemMap = intercalate "\n" $ concatMap extract skolemMap
where -- In the skolemMap:
-- * Left's are universals: i.e., the model should be true for
-- any of these. So, we simply "echo 0" for these values.
-- * Right's are existentials. If there are no dependencies (empty list), then we can
-- simply use get-value to extract it's value. Otherwise, we have to apply it to
-- an appropriate number of 0's to get the final value.
extract (Left s) = ["(echo \"((" ++ show s ++ " " ++ mkSkolemZero rm (kindOf s) ++ "))\")"]
extract (Right (s, [])) = let g = "(get-value (" ++ show s ++ "))" in getVal (kindOf s) g
extract (Right (s, ss)) = let g = "(get-value ((" ++ show s ++ concat [' ' : mkSkolemZero rm (kindOf a) | a <- ss] ++ ")))" in getVal (kindOf s) g
getVal KReal g = ["(set-option :pp.decimal false) " ++ g, "(set-option :pp.decimal true) " ++ g]
getVal _ g = [g]
addTimeOut Nothing o = o
addTimeOut (Just i) o
| i < 0 = error $ "Z3: Timeout value must be non-negative, received: " ++ show i
| True = o ++ [optionPrefix : "T:" ++ show i]
extractMap :: Bool -> [(Quantifier, NamedSymVar)] -> [(String, UnintKind)] -> [String] -> SMTModel
extractMap isSat qinps _modelMap solverLines =
SMTModel { modelAssocs = map snd $ squashReals $ sortByNodeId $ concatMap (interpretSolverModelLine inps) solverLines
, modelUninterps = []
, modelArrays = []
}
where sortByNodeId :: [(Int, a)] -> [(Int, a)]
sortByNodeId = sortBy (compare `on` fst)
inps -- for "sat", display the prefix existentials. For completeness, we will drop
-- only the trailing foralls. Exception: Don't drop anything if it's all a sequence of foralls
| isSat = map snd $ if all (== ALL) (map fst qinps)
then qinps
else reverse $ dropWhile ((== ALL) . fst) $ reverse qinps
-- for "proof", just display the prefix universals
| True = map snd $ takeWhile ((== ALL) . fst) qinps
squashReals :: [(Int, (String, CW))] -> [(Int, (String, CW))]
squashReals = concatMap squash . groupBy ((==) `on` fst)
where squash [(i, (n, cw1)), (_, (_, cw2))] = [(i, (n, mergeReals n cw1 cw2))]
squash xs = xs
mergeReals :: String -> CW -> CW -> CW
mergeReals n (CW KReal (CWAlgReal a)) (CW KReal (CWAlgReal b)) = CW KReal (CWAlgReal (mergeAlgReals (bad n a b) a b))
mergeReals n a b = bad n a b
bad n a b = error $ "SBV.Z3: Cannot merge reals for variable: " ++ n ++ " received: " ++ show (a, b)
|
Copilot-Language/sbv-for-copilot
|
Data/SBV/Provers/Z3.hs
|
bsd-3-clause
| 6,990
| 0
| 20
| 2,559
| 1,560
| 868
| 692
| 80
| 7
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main
( main -- :: IO ()
) where
import Data.ByteString.Char8 as S
import Control.Monad (liftM)
import System.Posix.User (getEffectiveUserID)
import Database.LevelDB
import System.Exit
import Data.Maybe (fromJust)
import Control.Monad.Trans.Resource
import Control.Monad.IO.Class
import Control.Exception.Lifted as Lifted
import Control.Exception
main :: IO ()
main = do
dbname <- (("/tmp/leveldb_hs_test-"++) . show) `liftM` getEffectiveUserID
say $ "creating db " ++ dbname
let opts = def {dbCreateIfMissing = True, dbErrorIfExists = True}
destroy dbname opts
withDB dbname opts $ \db -> do
say "stats"
s <- property db DBStats
say_ s
say "put"
putBS db def "foo" "hello"
putBS db def "box" "c"
say "get"
x <- getBS db def "foo"
say_ (show x)
x <- getBS db def "box"
say_ (show x)
say "snapshot"
withSnapshot db $ \snap -> do
deleteBS db def "foo"
x <- getBS db def{readSnapshot = Just snap} "foo"
say_ (show x)
x <- getBS db def "foo"
say_ (show x)
return ()
say "compacting"
compactAll db
say_ "ok"
say "repair"
repair dbname def
say "stats"
withDB dbname def $ \db -> do
say_ "number of files at levels:"
Lifted.catch (do property db (NumFilesAtLevel 0) >>= say_
property db (NumFilesAtLevel 1) >>= say_
property db (NumFilesAtLevel 2) >>= say_
property db (NumFilesAtLevel 3) >>= say_
property db (NumFilesAtLevel 4) >>= say_
property db (NumFilesAtLevel 5) >>= say_
property db (NumFilesAtLevel 6) >>= say_
-- This will throw an exception to be caught
property db (NumFilesAtLevel 7) >>= say_
) (\(_::SomeException) -> return ())
putBS db def "hi" "omg"
putBS db def "lol" "omg"
getBS db def "lol" >>= say_ . show
say_ "database stats:"
property db DBStats >>= say_
say_ "sstable stats:"
property db SSTables >>= say_
say "end"
say_ :: MonadIO m => String -> m ()
say_ = liftIO . Prelude.putStrLn
say :: MonadIO m => String -> m ()
say x = say_ $ "===== " ++ x ++ " ====="
|
thoughtpolice/hs-leveldb
|
examples/hl_test.hs
|
bsd-3-clause
| 2,325
| 0
| 19
| 690
| 796
| 374
| 422
| 69
| 1
|
module Network.MoHWS.Part.DynHS.CGI where
import Network.MoHWS.Part.CGI (mkCGIEnv, mkCGIResponse, )
import qualified Network.MoHWS.HTTP.Response as Response
import qualified Network.MoHWS.HTTP.Request as Request
import qualified Network.MoHWS.Server.Request as ServerRequest
import qualified Network.MoHWS.Server.Context as ServerContext
import ServerRequest (clientRequest, )
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.Map as Map
import Data.Maybe (isJust)
import Network.CGI.Monad (CGI, runCGIT, )
import Network.CGI.Protocol
hwsRunCGI :: ServerContext.T ext -> ServerRequest.T -> CGI CGIResult -> IO (Response.T String)
hwsRunCGI st sreq cgi =
do let path_info = "" -- FIXME: do the path walk
env <- mkCGIEnv st sreq path_info
let input = BS.pack $ Request.body $ clientRequest sreq
(hs,body) <- runCGI_ env input (runCGIT cgi)
mkCGIResponse hs (BS.unpack body)
-- | Run a CGI action. This is what runCGIEnvFPS really should look like.
runCGI_ :: Monad m =>
[(String,String)] -- ^ CGI environment variables.
-> ByteString -- ^ Request body.
-> (CGIRequest -> m (Header.Group, CGIResult)) -- ^ CGI action.
-> m (Header.Group, ByteString) -- ^ (Response.T String) (headers and content).
runCGI_ vars inp f
= do (hs,outp) <- f $ CGIRequest {
cgiVars = Map.fromList vars,
cgiInputs = decodeInput vars inp,
cgiRequestBody = inp
}
return $ case outp of
CGIOutput c -> (hs',c)
where hs' = if isJust (lookup ct hs)
then hs else hs ++ [(ct,defaultContentType)]
ct = HeaderName "Content-type"
CGINothing -> (hs, BS.empty)
defaultContentType :: String
defaultContentType = "text/html; charset=ISO-8859-1"
|
xpika/mohws
|
src/Network/MoHWS/Part/DynHS/CGI.hs
|
bsd-3-clause
| 1,991
| 0
| 16
| 543
| 498
| 288
| 210
| 38
| 3
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import Control.Arrow((&&&))
import Control.Applicative
import Data.Function(on)
import Data.List(sortBy)
import Data.Maybe(fromMaybe)
import Data.Monoid
import Data.String(IsString(..))
import Data.Time.Calendar(fromGregorian, diffDays)
import Data.Time.LocalTime
import Data.Text.Lazy(Text)
import Data.Text.Format
import Text.StringTemplate
import qualified Data.Time.Calendar as C
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as IO
--------------------------------------------------------------------------------
-- | Settings
users = [ Person "staals" "Frank Staals" Male $ fromDate 2015 08 31
, Person "bash" "Bas de Haas" Female $ fromDate 2012 08 31
, Person "newguy" "New Guy" Male $ fromDate 2020 01 01
]
templateDir = "templates/"
htmlTemplateExt = ".html"
messageTemplateExt = ".st"
outputFile = "html/generated.html"
--------------------------------------------------------------------------------
newtype Date = Date { unDay :: C.Day }
deriving (Eq,Ord,Show)
type Year = Integer
type Month = Int
type Day = Int
type TotalDays = Integer
fromDate :: Year -> Month -> Day -> Date
fromDate yyyy mm dd = Date $ fromGregorian yyyy mm dd
today :: IO Date
today = Date . localDay . zonedTimeToLocalTime <$> getZonedTime
daysUntil :: Integral a => Date -> Date -> a
(Date a) `daysUntil` (Date b) = fromInteger $ b `diffDays` a
timeUntil :: Date -> Date -> ((Year, Month, Day), TotalDays)
a `timeUntil` b = collectTime &&& id $ a `daysUntil` b
where
collectTime t = let years = t `div` 365
t' = fromInteger $ t `mod` 365
months = t' `div` 31
days = t' `mod` 31
in (years,months,days)
-- TODO: We can make this more precise (e.g. taking care of leap-years etc.) by
-- adding durations/days starting at a, and running until we hit b.
instance Read Date where
readsPrec = undefined -- TODO
--------------------------------------------------------------------------------
newtype UserId = UserId { unUI :: Text }
deriving (Read,Show,Eq,IsString)
data Gender = Male | Female
deriving (Read,Show,Eq)
newtype Name = Name { unN :: Text }
deriving (Show,Eq,Ord,Read,IsString)
data Person = Person { userId :: UserId
, name :: Name
, gender :: Gender
, dueDate :: Date
}
deriving (Read,Show,Eq)
timeLeft :: Person -> IO ((Year,Month,Day),TotalDays)
timeLeft p = (`timeUntil` dueDate p) <$> today
homepage :: Person -> Text
homepage p = let us = unUI . userId $ p in
format "http://www.cs.uu.nl/staff/{}.html" $ Only us
--------------------------------------------------------------------------------
-- | Buisness logic
data RenderData = RenderData { person :: Person
, height :: Height
, progress :: ProgressState
, message :: Message
}
deriving (Show,Eq)
newtype Height = Height { unH :: Int }
deriving (Read,Show,Eq,Ord, Num, Integral, Real, Enum)
instance Bounded Height where
minBound = Height 0
maxBound = Height 300
data ProgressState = MayStill | HasTo | HasStill | HasOnly | IsLate
deriving (Read,Show,Eq,Ord)
toCssClass :: ProgressState -> Text
toCssClass = T.toLower . showT
progressState :: Year -> ProgressState
progressState y | y < 0 = IsLate
progressState 0 = HasOnly
progressState 1 = HasStill
progressState 2 = HasTo
progressState _ = MayStill
newtype Message = Message { unM :: Text }
deriving (Show,Eq,Ord,Read,IsString)
mkMessage :: ProgressState -> (Year,Month,Day) -> Message
mkMessage s t = Message $ message'' NL Male s t
data Language = NL | EN
deriving (Show,Read,Eq)
day, days, month, months, year, years :: Language -> Text
day NL = "dag"
day EN = "day"
days NL = "dagen"
days EN = "days"
month NL = "maand"
month EN = "month"
months NL = "maanden"
months EN = "months"
year NL = "jaar"
year EN = "year"
years NL = "jaar"
years EN = "years"
mkDays :: Language -> Year -> Month -> Day -> Text
mkDays l 0 0 d = mkDays' l d
mkDays NL _ _ d = "en " <> mkDays' NL d
mkDays EN _ _ d = "and " <> mkDays' EN d
mkDays' :: Language -> Day -> Text
mkDays' _ 0 = ""
mkDays' l 1 = format "1 {}" $ Only (day l)
mkDays' l d = format "{} {}" (d, (days l))
mkMonths :: Language -> Month -> Text
mkMonths _ 0 = ""
mkMonths l 1 = format "1 {}" $ Only (month l)
mkMonths l m = format "{} {}" (m,months l)
mkYears :: Language -> Year -> Text
mkYears _ 0 = ""
mkYears l 1 = format "1 {}" $ Only (year l)
mkYears l y = format "{} {}" (y,year l)
hisHer :: Language -> Gender -> Text
hisHer NL Male = "zijn"
hisHer NL Female = "haar"
hisHer EN Male = "his"
hisHer EN Female = "her"
isLate, hasOnly, hasStill, mayStill :: Language -> Format
isLate NL = "wordt verondersteld {} proefschrift te hebben afgerond."
isLate EN = "is supposed to be done with {} thesis."
hasOnly NL = "heeft nog maar {} {} {}"
hasOnly EN = ""
hasStill NL = "heeft nog {} {} {}"
hasTo NL = "moet nog {} {} {}"
mayStill NL = "mag nog {} {} {}"
message'' :: Language -> Gender -> ProgressState -> (Year,Month,Day) -> Text
message'' l g IsLate _ = format (isLate l) (Only $ hisHer l g)
message'' l _ HasOnly (y,m,d) = format (hasOnly l) (mkYears l y, mkMonths l m, mkDays l y m d)
message'' l _ HasStill (y,m,d) = format (hasStill l) (mkYears l y, mkMonths l m, mkDays l y m d)
message'' l _ HasTo (y,m,d) = format (hasTo l) (mkYears l y, mkMonths l m, mkDays l y m d)
message'' l _ MayStill (y,m,d) = format (mayStill l) (mkYears l y, mkMonths l m, mkDays l y m d)
renderData :: Person -> IO RenderData
renderData p = renderData' <$> timeLeft p
where
renderData' (tl@(y,_,_),td) = let s = progressState y in
RenderData p (calcHeight td) s (mkMessage s tl)
calcHeight :: Integer -> Height
calcHeight td = Height $ min' + floor (frac * len)
where
max' = unH (maxBound :: Height)
min' = unH (minBound :: Height)
len = fromIntegral $ max' - min'
maxDays = 4*365 -- Default duration of a Phd = 4 years
frac :: Double
frac = max 0.0 . min 1.0 $ (fromInteger td) / maxDays
-- Fraction of the (maximum) time remaining
--------------------------------------------------------------------------------
-- | Html templates
loadTemplates :: IO (STGroup Text)
loadTemplates = mergeSTGroups <$> directoryGroupExt htmlTemplateExt templateDir
<*> directoryGroupExt messageTemplateExt templateDir
itemAttrs :: RenderData -> [(String,Text)]
itemAttrs (RenderData p@(Person u n g d) h s m) = [ ("progressState", toCssClass s)
, ("height", showT . unH $ h)
, ("picture", unUI u)
, ("homepage", homepage p)
, ("name", unN n)
, ("message", unM m)
]
--------------------------------------------------------------------------------
-- | The main program
main = do mHtml <- mkHtml <$> mapM renderData (sortOn dueDate users)
<*> loadTemplates
IO.writeFile outputFile $ fromMaybe mempty mHtml
mkHtml :: [RenderData] -> STGroup Text -> Maybe Text
mkHtml userData templates = render' <$> getStringTemplate "item" templates
<*> getStringTemplate "damokles" templates
where
render' itemT = let itemsHtml = [ render $ setManyAttrib (itemAttrs ud) itemT
| ud <- userData
]
in render . setManyAttrib [("items", itemsHtml)]
--------------------------------------------------------------------------------
-- | Generic utility functions
showT :: Show a => a -> Text
showT = T.pack . show
sortOn :: Ord b => (a -> b) -> [a] -> [a]
sortOn k = sortBy (compare `on` k)
|
noinia/damokles
|
src/Main.hs
|
bsd-3-clause
| 8,749
| 0
| 15
| 2,683
| 2,622
| 1,425
| 1,197
| 172
| 1
|
module LinePt2_Test (
linePt2Tests
) where
import Control.Monad
import Data.List
import Data.Monoid
import Graphics.Rendering.OpenGL
import Test.HUnit
import Rand
import LinePt2
import TestUtils
linesCrossedTests = TestLabel "linesCrossed"
$ TestList testCases'
where label' (a,b,e) = "linesCrossed " ++ show a
++ " with " ++ show b ++ " = " ++ show e
testCase' c@(a,b,e) = TestCase $ assertEqual (label' c)
(linesCrossed a b)
e
testCases' = fmap testCase' testCaseList
testCaseList = [ (linePt2 0 0 1 1.5, linePt2 1.5 0 0 1, True)
, (linePt2 0 0 1 1.5, linePt2 1 0 1 1.0, False) ]
lineCrossPt2Tests = TestLabel "lineCrossPt2"
$ TestList testCases'
where label' (a,b,e) = "lineCrossPt2 " ++ show a
++ " with " ++ show b ++ " = " ++ show e
testCase' c@(a,b,e) = TestCase $ assertEqual (label' c)
(lineCrossPt2 a b)
e
testCases' = fmap testCase' testCaseList
testCaseList = [ (linePt2 0 0 1 1, linePt2 1 0 0 1, pt2 0.5 0.5 )
, (linePt2 0 0 1 3, linePt2 1 0 0 1, pt2 0.25 0.75 ) ]
pairsA = [ linePt2 1 1 1 2
, linePt2 2 1 2 2
, linePt2 3 1 4 2 ]
pairsB = [ linePt2 0 1 7 3
, linePt2 7 0 0 2 ]
testPairs = sort $ crossedLinePairs pairsA pairsB
testPairs' = sort $ crossedLinePairsBrute pairsA pairsB
crossedLinePairsTests = TestLabel "crossedLinePairsTests" testCase'
where label' = "crossedLinePairsTests pairsA pairsB"
testCase' = TestCase $ assertEqual label' testPairs testPairs'
rightTestCase t@(p, line, n) = TestLabel label' $ TestCase $ assertEqual label' n' n
where label' = show t
n' = pt2LineRightCrossingNumber p line
rightTestCases = TestLabel "rightCrossingNumber" $ TestList $ fmap rightTestCase rightCrossSamples
rightCrossSamples = -- through point
[ (pt2 1 1, linePt2 1 1 1 2, 0)
-- degenerate line (point)
, (pt2 1 1, linePt2 2 1 2 1, 0)
-- entirely above
, (pt2 1 1, linePt2 2 3 2 2, 0)
, (pt2 1 1, linePt2 2 2 2 3, 0)
-- entirely below
, (pt2 1 1, linePt2 2 0 2 (-1), 0)
, (pt2 1 1, linePt2 2 (-1) 2 0, 0)
-- touching and up
, (pt2 1 1, linePt2 2 1 1 2, -1)
, (pt2 1 1, linePt2 2 1 2 2, -1)
, (pt2 1 1, linePt2 2 1 3 2, -1)
-- crosses and up
, (pt2 1 1, linePt2 2 0 1 2, -1)
, (pt2 1 1, linePt2 2 0 2 2, -1)
, (pt2 1 1, linePt2 2 0 3 2, -1)
-- crosses and down
, (pt2 1 1, linePt2 2 2 1 0, 1)
, (pt2 1 1, linePt2 2 2 2 0, 1)
, (pt2 1 1, linePt2 2 2 3 0, 1)
-- touching and up
, (pt2 1 1, linePt2 3 2 2 1, 1)
, (pt2 1 1, linePt2 2 2 2 1, 1)
, (pt2 1 1, linePt2 1 2 2 1, 1)
-- touching and down
, (pt2 1 1, linePt2 2 1 1 0, 0)
, (pt2 1 1, linePt2 2 1 2 0, 0)
, (pt2 1 1, linePt2 2 1 3 0, 0)
-- entirely left
, (pt2 1 4, linePt2 1 1 1 2, 0)
, (pt2 1 4, linePt2 2 1 2 1, 0)
, (pt2 1 4, linePt2 2 2 2 3, 0)
, (pt2 1 4, linePt2 2 3 2 2, 0)
, (pt2 1 4, linePt2 2 0 2 (-1), 0)
, (pt2 1 4, linePt2 2 (-1) 2 0, 0)
, (pt2 1 4, linePt2 2 1 1 2, 0)
, (pt2 1 4, linePt2 2 1 2 2, 0)
, (pt2 1 4, linePt2 2 1 3 2, 0)
, (pt2 1 4, linePt2 2 0 1 2, 0)
, (pt2 1 4, linePt2 2 0 2 2, 0)
, (pt2 1 4, linePt2 2 0 3 2, 0)
, (pt2 1 4, linePt2 2 2 1 0, 0)
, (pt2 1 4, linePt2 2 2 2 0, 0)
, (pt2 1 4, linePt2 2 2 3 0, 0)
, (pt2 1 4, linePt2 3 2 2 1, 0)
, (pt2 1 4, linePt2 2 2 2 1, 0)
, (pt2 1 4, linePt2 2 1 3 1, 0)
, (pt2 1 4, linePt2 2 1 1 0, 0)
, (pt2 1 4, linePt2 2 1 2 0, 0)
, (pt2 1 4, linePt2 2 1 3 0, 0) ]
linePt2Tests = TestList [ linesCrossedTests
, lineCrossPt2Tests
, crossedLinePairsTests
, rightTestCases ]
|
trenttobler/hs-asteroids
|
test/LinePt2_Test.hs
|
bsd-3-clause
| 4,992
| 0
| 12
| 2,432
| 1,789
| 960
| 829
| 91
| 1
|
import Execs
main :: IO ()
main = potyogosTreeWithHeu
|
AndrasKovacs/elte-cbsd
|
TestExecs/Components/PotyogosTreeWithHeu.hs
|
bsd-3-clause
| 55
| 0
| 6
| 10
| 19
| 10
| 9
| 3
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Tests.Readers.Markdown (tests) where
import Text.Pandoc.Definition
import Test.Framework
import Tests.Helpers
import Tests.Arbitrary()
import Text.Pandoc.Builder
import qualified Data.Set as Set
-- import Text.Pandoc.Shared ( normalize )
import Text.Pandoc
import Text.Pandoc.Error
markdown :: String -> Pandoc
markdown = handleError . readMarkdown def
markdownSmart :: String -> Pandoc
markdownSmart = handleError . readMarkdown def { readerSmart = True }
markdownCDL :: String -> Pandoc
markdownCDL = handleError . readMarkdown def { readerExtensions = Set.insert
Ext_compact_definition_lists $ readerExtensions def }
markdownGH :: String -> Pandoc
markdownGH = handleError . readMarkdown def { readerExtensions = githubMarkdownExtensions }
infix 4 =:
(=:) :: ToString c
=> String -> (String, c) -> Test
(=:) = test markdown
testBareLink :: (String, Inlines) -> Test
testBareLink (inp, ils) =
test (handleError . readMarkdown def{ readerExtensions =
Set.fromList [Ext_autolink_bare_uris, Ext_raw_html] })
inp (inp, doc $ para ils)
autolink :: String -> Inlines
autolink s = link s "" (str s)
bareLinkTests :: [(String, Inlines)]
bareLinkTests =
[ ("http://google.com is a search engine.",
autolink "http://google.com" <> " is a search engine.")
, ("<a href=\"http://foo.bar.baz\">http://foo.bar.baz</a>",
rawInline "html" "<a href=\"http://foo.bar.baz\">" <>
"http://foo.bar.baz" <> rawInline "html" "</a>")
, ("Try this query: http://google.com?search=fish&time=hour.",
"Try this query: " <> autolink "http://google.com?search=fish&time=hour" <> ".")
, ("HTTPS://GOOGLE.COM,",
autolink "HTTPS://GOOGLE.COM" <> ",")
, ("http://el.wikipedia.org/wiki/Τεχνολογία,",
autolink "http://el.wikipedia.org/wiki/Τεχνολογία" <> ",")
, ("doi:10.1000/182,",
autolink "doi:10.1000/182" <> ",")
, ("git://github.com/foo/bar.git,",
autolink "git://github.com/foo/bar.git" <> ",")
, ("file:///Users/joe/joe.txt, and",
autolink "file:///Users/joe/joe.txt" <> ", and")
, ("mailto:someone@somedomain.com.",
autolink "mailto:someone@somedomain.com" <> ".")
, ("Use http: this is not a link!",
"Use http: this is not a link!")
, ("(http://google.com).",
"(" <> autolink "http://google.com" <> ").")
, ("http://en.wikipedia.org/wiki/Sprite_(computer_graphics)",
autolink "http://en.wikipedia.org/wiki/Sprite_(computer_graphics)")
, ("http://en.wikipedia.org/wiki/Sprite_[computer_graphics]",
link "http://en.wikipedia.org/wiki/Sprite_%5Bcomputer_graphics%5D" ""
(str "http://en.wikipedia.org/wiki/Sprite_[computer_graphics]"))
, ("http://en.wikipedia.org/wiki/Sprite_{computer_graphics}",
link "http://en.wikipedia.org/wiki/Sprite_%7Bcomputer_graphics%7D" ""
(str "http://en.wikipedia.org/wiki/Sprite_{computer_graphics}"))
, ("http://example.com/Notification_Center-GitHub-20101108-140050.jpg",
autolink "http://example.com/Notification_Center-GitHub-20101108-140050.jpg")
, ("https://github.com/github/hubot/blob/master/scripts/cream.js#L20-20",
autolink "https://github.com/github/hubot/blob/master/scripts/cream.js#L20-20")
, ("http://www.rubyonrails.com",
autolink "http://www.rubyonrails.com")
, ("http://www.rubyonrails.com:80",
autolink "http://www.rubyonrails.com:80")
, ("http://www.rubyonrails.com/~minam",
autolink "http://www.rubyonrails.com/~minam")
, ("https://www.rubyonrails.com/~minam",
autolink "https://www.rubyonrails.com/~minam")
, ("http://www.rubyonrails.com/~minam/url%20with%20spaces",
autolink "http://www.rubyonrails.com/~minam/url%20with%20spaces")
, ("http://www.rubyonrails.com/foo.cgi?something=here",
autolink "http://www.rubyonrails.com/foo.cgi?something=here")
, ("http://www.rubyonrails.com/foo.cgi?something=here&and=here",
autolink "http://www.rubyonrails.com/foo.cgi?something=here&and=here")
, ("http://www.rubyonrails.com/contact;new",
autolink "http://www.rubyonrails.com/contact;new")
, ("http://www.rubyonrails.com/contact;new%20with%20spaces",
autolink "http://www.rubyonrails.com/contact;new%20with%20spaces")
, ("http://www.rubyonrails.com/contact;new?with=query&string=params",
autolink "http://www.rubyonrails.com/contact;new?with=query&string=params")
, ("http://www.rubyonrails.com/~minam/contact;new?with=query&string=params",
autolink "http://www.rubyonrails.com/~minam/contact;new?with=query&string=params")
, ("http://en.wikipedia.org/wiki/Wikipedia:Today%27s_featured_picture_%28animation%29/January_20%2C_2007",
autolink "http://en.wikipedia.org/wiki/Wikipedia:Today%27s_featured_picture_%28animation%29/January_20%2C_2007")
, ("http://www.mail-archive.com/rails@lists.rubyonrails.org/",
autolink "http://www.mail-archive.com/rails@lists.rubyonrails.org/")
, ("http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1",
autolink "http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1")
, ("http://en.wikipedia.org/wiki/Texas_hold%27em",
autolink "http://en.wikipedia.org/wiki/Texas_hold%27em")
, ("https://www.google.com/doku.php?id=gps:resource:scs:start",
autolink "https://www.google.com/doku.php?id=gps:resource:scs:start")
, ("http://www.rubyonrails.com",
autolink "http://www.rubyonrails.com")
, ("http://manuals.ruby-on-rails.com/read/chapter.need_a-period/103#page281",
autolink "http://manuals.ruby-on-rails.com/read/chapter.need_a-period/103#page281")
, ("http://foo.example.com/controller/action?parm=value&p2=v2#anchor123",
autolink "http://foo.example.com/controller/action?parm=value&p2=v2#anchor123")
, ("http://foo.example.com:3000/controller/action",
autolink "http://foo.example.com:3000/controller/action")
, ("http://foo.example.com:3000/controller/action+pack",
autolink "http://foo.example.com:3000/controller/action+pack")
, ("http://business.timesonline.co.uk/article/0,,9065-2473189,00.html",
autolink "http://business.timesonline.co.uk/article/0,,9065-2473189,00.html")
, ("http://www.mail-archive.com/ruby-talk@ruby-lang.org/",
autolink "http://www.mail-archive.com/ruby-talk@ruby-lang.org/")
, ("https://example.org/?anchor=lala-",
autolink "https://example.org/?anchor=lala-")
, ("https://example.org/?anchor=-lala",
autolink "https://example.org/?anchor=-lala")
]
{-
p_markdown_round_trip :: Block -> Bool
p_markdown_round_trip b = matches d' d''
where d' = normalize $ Pandoc (Meta [] [] []) [b]
d'' = normalize
$ readMarkdown def { readerSmart = True }
$ writeMarkdown def d'
matches (Pandoc _ [Plain []]) (Pandoc _ []) = True
matches (Pandoc _ [Para []]) (Pandoc _ []) = True
matches (Pandoc _ [Plain xs]) (Pandoc _ [Para xs']) = xs == xs'
matches x y = x == y
-}
tests :: [Test]
tests = [ testGroup "inline code"
[ "with attribute" =:
"`document.write(\"Hello\");`{.javascript}"
=?> para
(codeWith ("",["javascript"],[]) "document.write(\"Hello\");")
, "with attribute space" =:
"`*` {.haskell .special x=\"7\"}"
=?> para (codeWith ("",["haskell","special"],[("x","7")]) "*")
]
, testGroup "emph and strong"
[ "two strongs in emph" =:
"***a**b **c**d*" =?> para (emph (strong (str "a") <> str "b" <> space
<> strong (str "c") <> str "d"))
, "emph and strong emph alternating" =:
"*xxx* ***xxx*** xxx\n*xxx* ***xxx*** xxx"
=?> para (emph "xxx" <> space <> strong (emph "xxx") <>
space <> "xxx" <> space <>
emph "xxx" <> space <> strong (emph "xxx") <>
space <> "xxx")
, "emph with spaced strong" =:
"*x **xx** x*"
=?> para (emph ("x" <> space <> strong "xx" <> space <> "x"))
, "intraword underscore with opening underscore (#1121)" =:
"_foot_ball_" =?> para (emph (text "foot_ball"))
]
, testGroup "raw LaTeX"
[ "in URL" =:
"\\begin\n" =?> para (text "\\begin")
]
, testGroup "raw HTML"
[ "nesting (issue #1330)" =:
"<del>test</del>" =?>
rawBlock "html" "<del>" <> plain (str "test") <>
rawBlock "html" "</del>"
, "invalid tag (issue #1820" =:
"</ div></.div>" =?>
para (text "</ div></.div>")
, "technically invalid comment" =:
"<!-- pandoc --help -->" =?>
rawBlock "html" "<!-- pandoc --help -->"
, test markdownGH "issue 2469" $
"<\n\na>" =?>
para (text "<") <> para (text "a>")
]
, testGroup "emoji"
[ test markdownGH "emoji symbols" $
":smile: and :+1:" =?> para (text "😄 and 👍")
]
, "unbalanced brackets" =:
"[[[[[[[[[[[[[[[hi" =?> para (text "[[[[[[[[[[[[[[[hi")
, testGroup "backslash escapes"
[ "in URL" =:
"[hi](/there\\))"
=?> para (link "/there)" "" "hi")
, "in title" =:
"[hi](/there \"a\\\"a\")"
=?> para (link "/there" "a\"a" "hi")
, "in reference link title" =:
"[hi]\n\n[hi]: /there (a\\)a)"
=?> para (link "/there" "a)a" "hi")
, "in reference link URL" =:
"[hi]\n\n[hi]: /there\\.0"
=?> para (link "/there.0" "" "hi")
]
, testGroup "bare URIs"
(map testBareLink bareLinkTests)
, testGroup "autolinks"
[ "with unicode dash following" =:
"<http://foo.bar>\8212" =?> para (autolink "http://foo.bar" <>
str "\8212")
, "a partial URL (#2277)" =:
"<www.boe.es/buscar/act.php?id=BOE-A-1996-8930#a66>" =?>
para (text "<www.boe.es/buscar/act.php?id=BOE-A-1996-8930#a66>")
]
, testGroup "links"
[ "no autolink inside link" =:
"[<https://example.org>](url)" =?>
para (link "url" "" (text "<https://example.org>"))
, "no inline link inside link" =:
"[[a](url2)](url)" =?>
para (link "url" "" (text "[a](url2)"))
, "no bare URI inside link" =:
"[https://example.org(](url)" =?>
para (link "url" "" (text "https://example.org("))
]
, testGroup "Headers"
[ "blank line before header" =:
"\n# Header\n"
=?> headerWith ("header",[],[]) 1 "Header"
, "bracketed text (#2062)" =:
"# [hi]\n"
=?> headerWith ("hi",[],[]) 1 "[hi]"
, "ATX header without trailing #s" =:
"# Foo bar\n\n" =?>
headerWith ("foo-bar",[],[]) 1 "Foo bar"
, "ATX header without trailing #s" =:
"# Foo bar with # #" =?>
headerWith ("foo-bar-with",[],[]) 1 "Foo bar with #"
, "setext header" =:
"Foo bar\n=\n\n Foo bar 2 \n=" =?>
headerWith ("foo-bar",[],[]) 1 "Foo bar"
<> headerWith ("foo-bar-2",[],[]) 1 "Foo bar 2"
]
, testGroup "Implicit header references"
[ "ATX header without trailing #s" =:
"# Header\n[header]\n\n[header ]\n\n[ header]" =?>
headerWith ("header",[],[]) 1 "Header"
<> para (link "#header" "" (text "header"))
<> para (link "#header" "" (text "header"))
<> para (link "#header" "" (text "header"))
, "ATX header with trailing #s" =:
"# Foo bar #\n[foo bar]\n\n[foo bar ]\n\n[ foo bar]" =?>
headerWith ("foo-bar",[],[]) 1 "Foo bar"
<> para (link "#foo-bar" "" (text "foo bar"))
<> para (link "#foo-bar" "" (text "foo bar"))
<> para (link "#foo-bar" "" (text "foo bar"))
, "setext header" =:
" Header \n=\n\n[header]\n\n[header ]\n\n[ header]" =?>
headerWith ("header",[],[]) 1 "Header"
<> para (link "#header" "" (text "header"))
<> para (link "#header" "" (text "header"))
<> para (link "#header" "" (text "header"))
]
, testGroup "smart punctuation"
[ test markdownSmart "quote before ellipses"
("'...hi'"
=?> para (singleQuoted "…hi"))
, test markdownSmart "apostrophe before emph"
("D'oh! A l'*aide*!"
=?> para ("D’oh! A l’" <> emph "aide" <> "!"))
, test markdownSmart "apostrophe in French"
("À l'arrivée de la guerre, le thème de l'«impossibilité du socialisme»"
=?> para "À l’arrivée de la guerre, le thème de l’«impossibilité du socialisme»")
, test markdownSmart "apostrophe after math" $ -- issue #1909
"The value of the $x$'s and the systems' condition." =?>
para (text "The value of the " <> math "x" <> text "\8217s and the systems\8217 condition.")
]
, testGroup "footnotes"
[ "indent followed by newline and flush-left text" =:
"[^1]\n\n[^1]: my note\n\n \nnot in note\n"
=?> para (note (para "my note")) <> para "not in note"
, "indent followed by newline and indented text" =:
"[^1]\n\n[^1]: my note\n \n in note\n"
=?> para (note (para "my note" <> para "in note"))
, "recursive note" =:
"[^1]\n\n[^1]: See [^1]\n"
=?> para (note (para "See [^1]"))
]
, testGroup "lhs"
[ test (handleError . readMarkdown def{ readerExtensions = Set.insert
Ext_literate_haskell $ readerExtensions def })
"inverse bird tracks and html" $
"> a\n\n< b\n\n<div>\n"
=?> codeBlockWith ("",["sourceCode","literate","haskell"],[]) "a"
<>
codeBlockWith ("",["sourceCode","haskell"],[]) "b"
<>
rawBlock "html" "<div>\n\n"
]
-- the round-trip properties frequently fail
-- , testGroup "round trip"
-- [ property "p_markdown_round_trip" p_markdown_round_trip
-- ]
, testGroup "definition lists"
[ "no blank space" =:
"foo1\n : bar\n\nfoo2\n : bar2\n : bar3\n" =?>
definitionList [ (text "foo1", [plain (text "bar")])
, (text "foo2", [plain (text "bar2"),
plain (text "bar3")])
]
, "blank space before first def" =:
"foo1\n\n : bar\n\nfoo2\n\n : bar2\n : bar3\n" =?>
definitionList [ (text "foo1", [para (text "bar")])
, (text "foo2", [para (text "bar2"),
plain (text "bar3")])
]
, "blank space before second def" =:
"foo1\n : bar\n\nfoo2\n : bar2\n\n : bar3\n" =?>
definitionList [ (text "foo1", [plain (text "bar")])
, (text "foo2", [plain (text "bar2"),
para (text "bar3")])
]
, "laziness" =:
"foo1\n : bar\nbaz\n : bar2\n" =?>
definitionList [ (text "foo1", [plain (text "bar baz"),
plain (text "bar2")])
]
, "no blank space before first of two paragraphs" =:
"foo1\n : bar\n\n baz\n" =?>
definitionList [ (text "foo1", [para (text "bar") <>
para (text "baz")])
]
, "first line not indented" =:
"foo\n: bar\n" =?>
definitionList [ (text "foo", [plain (text "bar")]) ]
, "list in definition" =:
"foo\n: - bar\n" =?>
definitionList [ (text "foo", [bulletList [plain (text "bar")]]) ]
, "in div" =:
"<div>foo\n: - bar\n</div>" =?>
divWith nullAttr (definitionList
[ (text "foo", [bulletList [plain (text "bar")]]) ])
]
, testGroup "+compact_definition_lists"
[ test markdownCDL "basic compact list" $
"foo1\n: bar\n baz\nfoo2\n: bar2\n" =?>
definitionList [ (text "foo1", [plain (text "bar baz")])
, (text "foo2", [plain (text "bar2")])
]
]
, testGroup "lists"
[ "issue #1154" =:
" - <div>\n first div breaks\n </div>\n\n <button>if this button exists</button>\n\n <div>\n with this div too.\n </div>\n"
=?> bulletList [divWith nullAttr (para $ text "first div breaks") <>
rawBlock "html" "<button>" <>
plain (text "if this button exists") <>
rawBlock "html" "</button>" <>
divWith nullAttr (para $ text "with this div too.")]
, test markdownGH "issue #1636" $
unlines [ "* a"
, "* b"
, "* c"
, " * d" ]
=?>
bulletList [ plain "a"
, plain "b"
, plain "c" <> bulletList [plain "d"] ]
]
, testGroup "citations"
[ "simple" =:
"@item1" =?> para (cite [
Citation{ citationId = "item1"
, citationPrefix = []
, citationSuffix = []
, citationMode = AuthorInText
, citationNoteNum = 0
, citationHash = 0
}
] "@item1")
, "key starts with digit" =:
"@1657:huyghens" =?> para (cite [
Citation{ citationId = "1657:huyghens"
, citationPrefix = []
, citationSuffix = []
, citationMode = AuthorInText
, citationNoteNum = 0
, citationHash = 0
}
] "@1657:huyghens")
]
, let citation = cite [Citation "cita" [] [] AuthorInText 0 0] (str "@cita")
in testGroup "footnote/link following citation" -- issue #2083
[ "footnote" =:
unlines [ "@cita[^note]"
, ""
, "[^note]: note" ] =?>
para (
citation <> note (para $ str "note")
)
, "normal link" =:
"@cita [link](http://www.com)" =?>
para (
citation <> space <> link "http://www.com" "" (str "link")
)
, "reference link" =:
unlines [ "@cita [link][link]"
, ""
, "[link]: http://www.com" ] =?>
para (
citation <> space <> link "http://www.com" "" (str "link")
)
, "short reference link" =:
unlines [ "@cita [link]"
, ""
, "[link]: http://www.com" ] =?>
para (
citation <> space <> link "http://www.com" "" (str "link")
)
, "implicit header link" =:
unlines [ "# Header"
, "@cita [Header]" ] =?>
headerWith ("header",[],[]) 1 (str "Header") <> para (
citation <> space <> link "#header" "" (str "Header")
)
, "regular citation" =:
"@cita [foo]" =?>
para (
cite [Citation "cita" [] [Str "foo"] AuthorInText 0 0]
(str "@cita" <> space <> str "[foo]")
)
]
]
|
michaelbeaumont/pandoc
|
tests/Tests/Readers/Markdown.hs
|
gpl-2.0
| 20,400
| 0
| 22
| 6,573
| 3,772
| 1,993
| 1,779
| 373
| 1
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | @SPECIALIZE@ pragma declarations for RGB images.
module Vision.Image.RGB.Specialize () where
import Data.Int
import Vision.Histogram (Histogram, histogram, histogram2D)
import Vision.Image.RGB.Type (RGB)
import Vision.Image.Transform (
InterpolMethod, crop, resize, horizontalFlip, verticalFlip
)
import Vision.Primitive (DIM3, DIM5, Rect, Size)
{-# SPECIALIZE histogram :: Maybe DIM3 -> RGB -> Histogram DIM3 Int32
, Maybe DIM3 -> RGB -> Histogram DIM3 Double
, Maybe DIM3 -> RGB -> Histogram DIM3 Float #-}
{-# SPECIALIZE histogram2D :: DIM5 -> RGB -> Histogram DIM5 Int32
, DIM5 -> RGB -> Histogram DIM5 Double
, DIM5 -> RGB -> Histogram DIM5 Float #-}
{-# SPECIALIZE crop :: Rect -> RGB -> RGB #-}
{-# SPECIALIZE resize :: InterpolMethod -> Size -> RGB -> RGB #-}
{-# SPECIALIZE horizontalFlip :: RGB -> RGB #-}
{-# SPECIALIZE verticalFlip :: RGB -> RGB #-}
|
TomMD/friday
|
src/Vision/Image/RGB/Specialize.hs
|
lgpl-3.0
| 1,057
| 0
| 5
| 290
| 94
| 64
| 30
| 18
| 0
|
{-|
Arbitrary types for Network.Haskoin.Crypto
-}
module Network.Haskoin.Test.Crypto where
import Crypto.Secp256k1 ()
import Data.Bits (clearBit)
import Data.Either (fromRight)
import Data.List (foldl')
import Data.Serialize (decode)
import Data.Word (Word32)
import Network.Haskoin.Crypto.Base58
import Network.Haskoin.Crypto.ECDSA
import Network.Haskoin.Crypto.ExtendedKeys
import Network.Haskoin.Crypto.Hash
import Network.Haskoin.Crypto.Keys
import Network.Haskoin.Test.Util
import Test.QuickCheck
arbitraryHash160 :: Gen Hash160
arbitraryHash160 =
(fromRight (error "Could not decode Hash160") . decode) <$> arbitraryBSn 20
arbitraryHash256 :: Gen Hash256
arbitraryHash256 =
(fromRight (error "Could not decode Hash256") . decode) <$> arbitraryBSn 32
arbitraryHash512 :: Gen Hash512
arbitraryHash512 =
(fromRight (error "Could not decode Hash512") . decode) <$> arbitraryBSn 64
arbitraryCheckSum32 :: Gen CheckSum32
arbitraryCheckSum32 =
(fromRight (error "Could not decode CheckSum32") . decode) <$>
arbitraryBSn 4
arbitraryPrvKey :: Gen PrvKey
arbitraryPrvKey = oneof [ toPrvKeyG <$> arbitraryPrvKeyC
, toPrvKeyG <$> arbitraryPrvKeyU
]
-- | Arbitrary compressed private key
arbitraryPrvKeyC :: Gen PrvKeyC
arbitraryPrvKeyC = makePrvKeyC <$> arbitrary
-- | Arbitrary uncompressed private key
arbitraryPrvKeyU :: Gen PrvKeyU
arbitraryPrvKeyU = makePrvKeyU <$> arbitrary
-- | Arbitrary public key (can be both compressed or uncompressed) with its
-- corresponding private key.
arbitraryPubKey :: Gen (PrvKey, PubKey)
arbitraryPubKey =
oneof [ f <$> arbitraryPubKeyC
, f <$> arbitraryPubKeyU
]
where
f (k, p) = (toPrvKeyG k, toPubKeyG p)
-- | Arbitrary compressed public key with its corresponding private key.
arbitraryPubKeyC :: Gen (PrvKeyC, PubKeyC)
arbitraryPubKeyC = (\k -> (k, derivePubKey k)) <$> arbitraryPrvKeyC
-- | Arbitrary uncompressed public key with its corresponding private key.
arbitraryPubKeyU :: Gen (PrvKeyU, PubKeyU)
arbitraryPubKeyU = (\k -> (k, derivePubKey k)) <$> arbitraryPrvKeyU
-- | Arbitrary address (can be a pubkey or script hash address)
arbitraryAddress :: Gen Address
arbitraryAddress = oneof [ arbitraryPubKeyAddress
, arbitraryScriptAddress
]
-- | Arbitrary public key hash address
arbitraryPubKeyAddress :: Gen Address
arbitraryPubKeyAddress = PubKeyAddress <$> arbitraryHash160
-- | Arbitrary script hash address
arbitraryScriptAddress :: Gen Address
arbitraryScriptAddress = ScriptAddress <$> arbitraryHash160
-- | Arbitrary message hash, private key, nonce and corresponding signature.
-- The signature is generated with a random message, random private key and a
-- random nonce.
arbitrarySignature :: Gen (Hash256, PrvKey, Signature)
arbitrarySignature = do
msg <- arbitraryHash256
key <- arbitraryPrvKey
let sig = signMsg msg key
return (msg, key, sig)
-- | Arbitrary extended private key.
arbitraryXPrvKey :: Gen XPrvKey
arbitraryXPrvKey = XPrvKey <$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitraryHash256
<*> arbitraryPrvKeyC
-- | Arbitrary extended public key with its corresponding private key.
arbitraryXPubKey :: Gen (XPrvKey, XPubKey)
arbitraryXPubKey = (\k -> (k, deriveXPubKey k)) <$> arbitraryXPrvKey
{- Custom derivations -}
genIndex :: Gen Word32
genIndex = (`clearBit` 31) <$> arbitrary
arbitraryBip32PathIndex :: Gen Bip32PathIndex
arbitraryBip32PathIndex =
oneof [ Bip32SoftIndex <$> genIndex
, Bip32HardIndex <$> genIndex
]
arbitraryHardPath :: Gen HardPath
arbitraryHardPath = foldl' (:|) Deriv <$> listOf genIndex
arbitrarySoftPath :: Gen SoftPath
arbitrarySoftPath = foldl' (:/) Deriv <$> listOf genIndex
arbitraryDerivPath :: Gen DerivPath
arbitraryDerivPath = concatBip32Segments <$> listOf arbitraryBip32PathIndex
arbitraryParsedPath :: Gen ParsedPath
arbitraryParsedPath =
oneof [ ParsedPrv <$> arbitraryDerivPath
, ParsedPub <$> arbitraryDerivPath
, ParsedEmpty <$> arbitraryDerivPath
]
|
xenog/haskoin
|
src/Network/Haskoin/Test/Crypto.hs
|
unlicense
| 4,494
| 0
| 10
| 1,118
| 839
| 468
| 371
| 81
| 1
|
{- portable environment variables
-
- Copyright 2013 Joey Hess <joey@kitenet.net>
-
- License: BSD-2-clause
-}
{-# LANGUAGE CPP #-}
module Utility.Env where
#ifdef mingw32_HOST_OS
import Utility.Exception
import Control.Applicative
import Data.Maybe
import qualified System.Environment as E
#else
import qualified System.Posix.Env as PE
#endif
getEnv :: String -> IO (Maybe String)
#ifndef mingw32_HOST_OS
getEnv = PE.getEnv
#else
getEnv = catchMaybeIO . E.getEnv
#endif
getEnvDefault :: String -> String -> IO String
#ifndef mingw32_HOST_OS
getEnvDefault = PE.getEnvDefault
#else
getEnvDefault var fallback = fromMaybe fallback <$> getEnv var
#endif
getEnvironment :: IO [(String, String)]
#ifndef mingw32_HOST_OS
getEnvironment = PE.getEnvironment
#else
getEnvironment = E.getEnvironment
#endif
{- Returns True if it could successfully set the environment variable.
-
- There is, apparently, no way to do this in Windows. Instead,
- environment varuables must be provided when running a new process. -}
setEnv :: String -> String -> Bool -> IO Bool
#ifndef mingw32_HOST_OS
setEnv var val overwrite = do
PE.setEnv var val overwrite
return True
#else
setEnv _ _ _ = return False
#endif
{- Returns True if it could successfully unset the environment variable. -}
unsetEnv :: String -> IO Bool
#ifndef mingw32_HOST_OS
unsetEnv var = do
PE.unsetEnv var
return True
#else
unsetEnv _ = return False
#endif
{- Adds the environment variable to the input environment. If already
- present in the list, removes the old value.
-
- This does not really belong here, but Data.AssocList is for some reason
- buried inside hxt.
-}
addEntry :: Eq k => k -> v -> [(k, v)] -> [(k, v)]
addEntry k v l = ( (k,v) : ) $! delEntry k l
addEntries :: Eq k => [(k, v)] -> [(k, v)] -> [(k, v)]
addEntries = foldr (.) id . map (uncurry addEntry) . reverse
delEntry :: Eq k => k -> [(k, v)] -> [(k, v)]
delEntry _ [] = []
delEntry k (x@(k1,_) : rest)
| k == k1 = rest
| otherwise = ( x : ) $! delEntry k rest
|
abailly/propellor-test2
|
src/Utility/Env.hs
|
bsd-2-clause
| 2,013
| 0
| 10
| 366
| 467
| 262
| 205
| 26
| 1
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PolyKinds #-}
-----------------------------------------------------------------------------
-- |
-- Module : Generics.Instant.Functions.Enum
-- Copyright : (c) 2010, Universiteit Utrecht
-- License : BSD3
--
-- Maintainer : generics@haskell.org
-- Stability : experimental
-- Portability : non-portable
--
-- Generically enumerate values
--
-----------------------------------------------------------------------------
module Generics.Instant.Functions.Enum (
GEnum(..), genum
) where
import Generics.Instant.Base
import Generics.Instant.Instances ()
-- Generic enum (worker)
class GEnum a where
genum' :: [a]
instance GEnum U where
genum' = [U]
instance (GEnum a) => GEnum (Rec a) where
genum' = map Rec genum'
instance (GEnum a) => GEnum (Var a) where
genum' = map Var genum'
instance (GEnum a) => GEnum (CEq c p p a) where genum' = map C genum'
instance GEnum (CEq c p q a) where genum' = []
instance (GEnum f, GEnum g) => GEnum (f :+: g) where
genum' = map L genum' ||| map R genum'
instance (GEnum f, GEnum g) => GEnum (f :*: g) where
genum' = diag (map (\x -> map (\y -> x :*: y) genum') genum')
instance GEnum Int where
genum' = [0..9]
-- Dispatcher
genum :: (Representable a, GEnum (Rep a)) => [a]
genum = map to genum'
-- Utilities
infixr 5 |||
(|||) :: [a] -> [a] -> [a]
[] ||| ys = ys
(x:xs) ||| ys = x : ys ||| xs
diag :: [[a]] -> [a]
diag = concat . foldr skew [] . map (map (\x -> [x]))
skew :: [[a]] -> [[a]] -> [[a]]
skew [] ys = ys
skew (x:xs) ys = x : combine (++) xs ys
combine :: (a -> a -> a) -> [a] -> [a] -> [a]
combine _ xs [] = xs
combine _ [] ys = ys
combine f (x:xs) (y:ys) = f x y : combine f xs ys
|
dreixel/instant-generics
|
src/Generics/Instant/Functions/Enum.hs
|
bsd-3-clause
| 2,088
| 0
| 14
| 508
| 708
| 395
| 313
| 44
| 1
|
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "Data/Aeson/Encoding/Internal.hs" #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Data.Aeson.Encoding.Internal
(
-- * Encoding
Encoding' (..)
, Encoding
, encodingToLazyByteString
, unsafeToEncoding
, retagEncoding
, Series (..)
, pairs
, pair
, pairStr
, pair'
-- * Predicates
, nullEncoding
-- * Encoding constructors
, emptyArray_
, emptyObject_
, wrapObject
, wrapArray
, null_
, bool
, text
, lazyText
, string
, list
, dict
, tuple
, (>*<)
, InArray
, empty
, (><)
, econcat
-- ** Decimal numbers
, int8, int16, int32, int64, int
, word8, word16, word32, word64, word
, integer, float, double, scientific
-- ** Decimal numbers as Text
, int8Text, int16Text, int32Text, int64Text, intText
, word8Text, word16Text, word32Text, word64Text, wordText
, integerText, floatText, doubleText, scientificText
-- ** Time
, day
, localTime
, utcTime
, timeOfDay
, zonedTime
-- ** value
, value
-- ** JSON tokens
, comma, colon, openBracket, closeBracket, openCurly, closeCurly
) where
import Prelude ()
import Prelude.Compat
import Data.Aeson.Types.Internal (Value)
import Data.ByteString.Builder (Builder, char7, toLazyByteString)
import Data.Int
import Data.Scientific (Scientific)
import Data.Semigroup (Semigroup ((<>)))
import Data.Text (Text)
import Data.Time (Day, LocalTime, TimeOfDay, UTCTime, ZonedTime)
import Data.Typeable (Typeable)
import Data.Word
import qualified Data.Aeson.Encoding.Builder as EB
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Text.Lazy as LT
-- | An encoding of a JSON value.
--
-- @tag@ represents which kind of JSON the Encoding is encoding to,
-- we reuse 'Text' and 'Value' as tags here.
newtype Encoding' tag = Encoding {
fromEncoding :: Builder
-- ^ Acquire the underlying bytestring builder.
} deriving (Typeable)
-- | Often used synonnym for 'Encoding''.
type Encoding = Encoding' Value
-- | Make Encoding from Builder.
--
-- Use with care! You have to make sure that the passed Builder
-- is a valid JSON Encoding!
unsafeToEncoding :: Builder -> Encoding' a
unsafeToEncoding = Encoding
encodingToLazyByteString :: Encoding' a -> BSL.ByteString
encodingToLazyByteString = toLazyByteString . fromEncoding
{-# INLINE encodingToLazyByteString #-}
retagEncoding :: Encoding' a -> Encoding' b
retagEncoding = Encoding . fromEncoding
-------------------------------------------------------------------------------
-- Encoding instances
-------------------------------------------------------------------------------
instance Show (Encoding' a) where
show (Encoding e) = show (toLazyByteString e)
instance Eq (Encoding' a) where
Encoding a == Encoding b = toLazyByteString a == toLazyByteString b
instance Ord (Encoding' a) where
compare (Encoding a) (Encoding b) =
compare (toLazyByteString a) (toLazyByteString b)
-- | A series of values that, when encoded, should be separated by
-- commas. Since 0.11.0.0, the '.=' operator is overloaded to create
-- either @(Text, Value)@ or 'Series'. You can use Series when
-- encoding directly to a bytestring builder as in the following
-- example:
--
-- > toEncoding (Person name age) = pairs ("name" .= name <> "age" .= age)
data Series = Empty
| Value (Encoding' Series)
deriving (Typeable)
pair :: Text -> Encoding -> Series
pair name val = pair' (text name) val
{-# INLINE pair #-}
pairStr :: String -> Encoding -> Series
pairStr name val = pair' (string name) val
{-# INLINE pairStr #-}
pair' :: Encoding' Text -> Encoding -> Series
pair' name val = Value $ retagEncoding $ retagEncoding name >< colon >< val
instance Semigroup Series where
Empty <> a = a
a <> Empty = a
Value a <> Value b = Value (a >< comma >< b)
instance Monoid Series where
mempty = Empty
mappend = (<>)
nullEncoding :: Encoding' a -> Bool
nullEncoding = BSL.null . toLazyByteString . fromEncoding
emptyArray_ :: Encoding
emptyArray_ = Encoding EB.emptyArray_
emptyObject_ :: Encoding
emptyObject_ = Encoding EB.emptyObject_
wrapArray :: Encoding' a -> Encoding
wrapArray e = retagEncoding $ openBracket >< e >< closeBracket
wrapObject :: Encoding' a -> Encoding
wrapObject e = retagEncoding $ openCurly >< e >< closeCurly
null_ :: Encoding
null_ = Encoding EB.null_
bool :: Bool -> Encoding
bool True = Encoding "true"
bool False = Encoding "false"
-- | Encode a series of key/value pairs, separated by commas.
pairs :: Series -> Encoding
pairs (Value v) = openCurly >< retagEncoding v >< closeCurly
pairs Empty = emptyObject_
{-# INLINE pairs #-}
list :: (a -> Encoding) -> [a] -> Encoding
list _ [] = emptyArray_
list to' (x:xs) = openBracket >< to' x >< commas xs >< closeBracket
where
commas = foldr (\v vs -> comma >< to' v >< vs) empty
{-# INLINE list #-}
-- | Encode as JSON object
dict
:: (k -> Encoding' Text) -- ^ key encoding
-> (v -> Encoding) -- ^ value encoding
-> (forall a. (k -> v -> a -> a) -> a -> m -> a) -- ^ @foldrWithKey@ - indexed fold
-> m -- ^ container
-> Encoding
dict encodeKey encodeVal foldrWithKey = pairs . foldrWithKey go mempty
where
go k v c = Value (encodeKV k v) <> c
encodeKV k v = retagEncoding (encodeKey k) >< colon >< retagEncoding (encodeVal v)
{-# INLINE dict #-}
-- | Type tag for tuples contents, see 'tuple'.
data InArray
infixr 6 >*<
-- | See 'tuple'.
(>*<) :: Encoding' a -> Encoding' b -> Encoding' InArray
a >*< b = retagEncoding a >< comma >< retagEncoding b
{-# INLINE (>*<) #-}
empty :: Encoding' a
empty = Encoding mempty
econcat :: [Encoding' a] -> Encoding' a
econcat = foldr (><) empty
infixr 6 ><
(><) :: Encoding' a -> Encoding' a -> Encoding' a
Encoding a >< Encoding b = Encoding (a <> b)
{-# INLINE (><) #-}
-- | Encode as a tuple.
--
-- @
-- toEncoding (X a b c) = tuple $
-- toEncoding a >*<
-- toEncoding b >*<
-- toEncoding c
tuple :: Encoding' InArray -> Encoding
tuple b = retagEncoding $ openBracket >< b >< closeBracket
{-# INLINE tuple #-}
text :: Text -> Encoding' a
text = Encoding . EB.text
lazyText :: LT.Text -> Encoding' a
lazyText t = Encoding $
B.char7 '"' <>
LT.foldrChunks (\x xs -> EB.unquoted x <> xs) (B.char7 '"') t
string :: String -> Encoding' a
string = Encoding . EB.string
-------------------------------------------------------------------------------
-- chars
-------------------------------------------------------------------------------
comma, colon, openBracket, closeBracket, openCurly, closeCurly :: Encoding' a
comma = Encoding $ char7 ','
colon = Encoding $ char7 ':'
openBracket = Encoding $ char7 '['
closeBracket = Encoding $ char7 ']'
openCurly = Encoding $ char7 '{'
closeCurly = Encoding $ char7 '}'
-------------------------------------------------------------------------------
-- Decimal numbers
-------------------------------------------------------------------------------
int8 :: Int8 -> Encoding
int8 = Encoding . B.int8Dec
int16 :: Int16 -> Encoding
int16 = Encoding . B.int16Dec
int32 :: Int32 -> Encoding
int32 = Encoding . B.int32Dec
int64 :: Int64 -> Encoding
int64 = Encoding . B.int64Dec
int :: Int -> Encoding
int = Encoding . B.intDec
word8 :: Word8 -> Encoding
word8 = Encoding . B.word8Dec
word16 :: Word16 -> Encoding
word16 = Encoding . B.word16Dec
word32 :: Word32 -> Encoding
word32 = Encoding . B.word32Dec
word64 :: Word64 -> Encoding
word64 = Encoding . B.word64Dec
word :: Word -> Encoding
word = Encoding . B.wordDec
integer :: Integer -> Encoding
integer = Encoding . B.integerDec
float :: Float -> Encoding
float = realFloatToEncoding $ Encoding . B.floatDec
double :: Double -> Encoding
double = realFloatToEncoding $ Encoding . B.doubleDec
scientific :: Scientific -> Encoding
scientific = Encoding . EB.scientific
realFloatToEncoding :: RealFloat a => (a -> Encoding) -> a -> Encoding
realFloatToEncoding e d
| isNaN d || isInfinite d = null_
| otherwise = e d
{-# INLINE realFloatToEncoding #-}
-------------------------------------------------------------------------------
-- Decimal numbers as Text
-------------------------------------------------------------------------------
int8Text :: Int8 -> Encoding' a
int8Text = Encoding . EB.quote . B.int8Dec
int16Text :: Int16 -> Encoding' a
int16Text = Encoding . EB.quote . B.int16Dec
int32Text :: Int32 -> Encoding' a
int32Text = Encoding . EB.quote . B.int32Dec
int64Text :: Int64 -> Encoding' a
int64Text = Encoding . EB.quote . B.int64Dec
intText :: Int -> Encoding' a
intText = Encoding . EB.quote . B.intDec
word8Text :: Word8 -> Encoding' a
word8Text = Encoding . EB.quote . B.word8Dec
word16Text :: Word16 -> Encoding' a
word16Text = Encoding . EB.quote . B.word16Dec
word32Text :: Word32 -> Encoding' a
word32Text = Encoding . EB.quote . B.word32Dec
word64Text :: Word64 -> Encoding' a
word64Text = Encoding . EB.quote . B.word64Dec
wordText :: Word -> Encoding' a
wordText = Encoding . EB.quote . B.wordDec
integerText :: Integer -> Encoding' a
integerText = Encoding . EB.quote . B.integerDec
floatText :: Float -> Encoding' a
floatText = Encoding . EB.quote . B.floatDec
doubleText :: Double -> Encoding' a
doubleText = Encoding . EB.quote . B.doubleDec
scientificText :: Scientific -> Encoding' a
scientificText = Encoding . EB.quote . EB.scientific
-------------------------------------------------------------------------------
-- time
-------------------------------------------------------------------------------
day :: Day -> Encoding' a
day = Encoding . EB.quote . EB.day
localTime :: LocalTime -> Encoding' a
localTime = Encoding . EB.quote . EB.localTime
utcTime :: UTCTime -> Encoding' a
utcTime = Encoding . EB.quote . EB.utcTime
timeOfDay :: TimeOfDay -> Encoding' a
timeOfDay = Encoding . EB.quote . EB.timeOfDay
zonedTime :: ZonedTime -> Encoding' a
zonedTime = Encoding . EB.quote . EB.zonedTime
-------------------------------------------------------------------------------
-- Value
-------------------------------------------------------------------------------
value :: Value -> Encoding
value = Encoding . EB.encodeToBuilder
|
phischu/fragnix
|
tests/packages/scotty/Data.Aeson.Encoding.Internal.hs
|
bsd-3-clause
| 10,584
| 0
| 14
| 2,091
| 2,692
| 1,482
| 1,210
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
module Main (main) where
import Control.Monad
import Control.Monad.Trans
import Data.Version (showVersion)
import Language.Haskell.Interpreter hiding (get)
import Options.Declarative
import System.IO
import Evaluator
import Paths_hoe (version)
imports :: [String]
imports =
[ "Prelude"
-- from base
, "Control.Applicative"
, "Control.Arrow"
, "Control.Monad"
, "Data.Bits"
, "Data.Char"
, "Data.Complex"
, "Data.Either"
, "Data.Function"
, "Data.List"
, "Data.Maybe"
, "Data.Monoid"
, "Data.Ord"
, "Data.Ratio"
, "Numeric"
, "System.IO"
, "System.IO.Unsafe"
, "System.Info"
, "System.Random"
, "Text.Printf"
-- other common modules
, "Data.List.Split" -- from split
, "Data.Time" -- from time
, "Text.Regex.Posix" -- from regex-posix
]
hoe :: Flag "i" '["inplace"] "EXT" "Edit files in-place (make backup if EXT is not null)" (Maybe String)
-> Arg "SCRIPT" String
-> Arg "[FILES]" [String]
-> Flag "m" '["mod"] "MODULES" "Import modules before running the script" (Def "" String)
-> Cmd "hoe: Haskell One-liner Evaluator" ()
hoe inplace script files modules = do
compiled <- liftIO $ runInterpreter $ do
reset
setImportsQ $
[ (m, Nothing) | m <- imports ] ++
[ (m, Nothing) | m <- words $ get modules ]
set [ installedModulesInScope := True ]
compile $ get script
case compiled of
Left (WontCompile errs) ->
liftIO $ hPutStr stderr $ "compile error: " ++ unlines (map errMsg errs)
Left (UnknownError msg) ->
liftIO $ hPutStrLn stderr msg
Left err ->
liftIO $ hPrint stderr err
Right (ty, descr, f) -> do
logStr 1 $ "Interpret as: " ++ ty ++ " :: " ++ descr
liftIO $ exec (get files) (get inplace) f
exec :: [String] -> Maybe String -> Script -> IO ()
exec [] _ f = putStr =<< f =<< getContents
exec files mbext f =
forM_ files $ \file -> do
s <- readFile file
case mbext of
Nothing -> putStr =<< f s
Just ext -> do
when (ext /= "") $ writeFile (file ++ "." ++ ext) s
length s `seq ` writeFile file =<< f s
main :: IO ()
main = run "hoe" (Just $ showVersion version) hoe
|
steshaw/hoe
|
src/HOE.hs
|
bsd-3-clause
| 2,487
| 0
| 18
| 828
| 701
| 365
| 336
| 70
| 4
|
{-# OPTIONS_HADDOCK hide #-}
{- |
This module contains the FunGEn objects procedures
-}
{-
FunGEN - Functional Game Engine
http://www.cin.ufpe.br/~haskell/fungen
Copyright (C) 2002 Andre Furtado <awbf@cin.ufpe.br>
This code 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.
-}
module Graphics.UI.Fungen.Objects (
ObjectManager,
GameObject,
ObjectPicture(..), Primitive(..),
FillMode (..),
-- ** creating
object,
-- ** object attributes
getGameObjectId, getGameObjectName, getGameObjectManagerName, getGameObjectAsleep,
getGameObjectPosition, getGameObjectSize, getGameObjectSpeed, getGameObjectAttribute,
-- ** updating
updateObject, updateObjectAsleep, updateObjectSize, updateObjectPosition,
updateObjectSpeed, updateObjectAttribute, updateObjectPicture,
-- ** drawing
drawGameObjects, drawGameObject,
-- ** moving
moveGameObjects,
-- ** destroying
destroyGameObject,
-- ** groups of objects
objectGroup, addObjectsToManager,
getObjectManagerName, getObjectManagerCounter , getObjectManagerObjects,
-- ** searching
findObjectFromId, searchObjectManager, searchGameObject,
) where
import Graphics.UI.Fungen.Types
import Graphics.UI.Fungen.Util
import Graphics.Rendering.OpenGL hiding (Primitive)
data GameObject t = GO {
objId :: Integer,
objName :: String,
objManagerName :: String,
objPicture :: GameObjectPicture,
objAsleep :: Bool,
objSize :: Point2D,
objPosition :: Point2D,
objSpeed :: Point2D,
objAttribute :: t
}
data ObjectManager t = OM {
mngName :: String, -- name of the manager
mngCounter :: Integer, -- next current avaible index for a new object
mngObjects :: [(GameObject t)] -- the SET of objects
}
data GamePrimitive
= P [Vertex3 GLdouble] (Color4 GLfloat) FillMode
| C GLdouble (Color4 GLfloat) FillMode
data GameObjectPicture
= Tx Int
| B GamePrimitive
-- | A [TextureObject] Int -- miliseconds between frames
data Primitive
= Polyg [Point2D] GLfloat GLfloat GLfloat FillMode -- the points (must be in CCW order!), color, fill mode
| Circle GLdouble GLfloat GLfloat GLfloat FillMode -- color, radius, fill mode
data ObjectPicture
= Tex (GLdouble,GLdouble) Int -- size, current texture
| Basic Primitive
-- | Animation [(FilePath,InvList)] Int -- (path to file, invisible colors), miliseconds between frames
data FillMode
= Filled
| Unfilled
deriving Eq
-------------------------------------------
-- get & updating routines for GameObjects
-------------------------------------------
getGameObjectId :: GameObject t -> Integer
getGameObjectId = objId
getGameObjectName :: GameObject t -> String
getGameObjectName = objName
getGameObjectManagerName :: GameObject t -> String
getGameObjectManagerName = objManagerName
-- internal use only!
getGameObjectPicture :: GameObject t -> GameObjectPicture
getGameObjectPicture = objPicture
getGameObjectAsleep :: GameObject t -> Bool
getGameObjectAsleep = objAsleep
getGameObjectSize :: GameObject t -> (GLdouble,GLdouble)
getGameObjectSize o = (realToFrac sX,realToFrac sY)
where (sX,sY) = objSize o
getGameObjectPosition :: GameObject t -> (GLdouble,GLdouble)
getGameObjectPosition o = (realToFrac pX,realToFrac pY)
where (pX,pY) = objPosition o
getGameObjectSpeed :: GameObject t -> (GLdouble,GLdouble)
getGameObjectSpeed o = (realToFrac sX,realToFrac sY)
where (sX,sY) = objSpeed o
getGameObjectAttribute :: GameObject t -> t
getGameObjectAttribute = objAttribute
updateObjectPicture :: Int -> Int -> GameObject t -> GameObject t
updateObjectPicture newIndex maxIndex obj =
case (getGameObjectPicture obj) of
Tx _ -> if (newIndex <= maxIndex)
then (obj {objPicture = Tx newIndex})
else (error ("Objects.updateObjectPicture error: picture index out of range for object " ++
(getGameObjectName obj) ++ " of group " ++ (getGameObjectManagerName obj)))
_ -> error ("Objects.updateObjectPicture error: object " ++ (getGameObjectName obj) ++
" of group " ++ (getGameObjectManagerName obj) ++ " is not a textured object!")
updateObjectAsleep :: Bool -> GameObject t -> GameObject t
updateObjectAsleep asleep o = o {objAsleep = asleep}
updateObjectSize :: (GLdouble,GLdouble) -> GameObject t -> GameObject t
updateObjectSize (sX,sY) o = o {objSize = (realToFrac sX, realToFrac sY)}
updateObjectPosition :: (GLdouble,GLdouble) -> GameObject t -> GameObject t
updateObjectPosition (pX,pY) o = o {objPosition = (realToFrac pX, realToFrac pY)}
updateObjectSpeed :: (GLdouble,GLdouble) -> GameObject t -> GameObject t
updateObjectSpeed (sX,sY) o = o {objSpeed = (realToFrac sX, realToFrac sY)}
updateObjectAttribute :: t -> GameObject t -> GameObject t
updateObjectAttribute oAttrib o = o {objAttribute = oAttrib}
----------------------------------------------
-- get & updating routines for ObjectManagers
----------------------------------------------
getObjectManagerName :: ObjectManager t -> String
getObjectManagerName = mngName
getObjectManagerCounter :: ObjectManager t -> Integer
getObjectManagerCounter = mngCounter
getObjectManagerObjects :: ObjectManager t -> [(GameObject t)]
getObjectManagerObjects = mngObjects
updateObjectManagerObjects :: [(GameObject t)] -> ObjectManager t -> ObjectManager t
updateObjectManagerObjects objs mng = mng {mngObjects = objs}
----------------------------------------
-- initialization of GameObjects
----------------------------------------
object :: String -> ObjectPicture -> Bool -> (GLdouble,GLdouble) -> (GLdouble,GLdouble) -> t -> GameObject t
object name pic asleep pos speed oAttrib = let (picture, size) = createPicture pic in
GO {
objId = 0,
objName = name,
objManagerName = "object not grouped yet!",
objPicture = picture,
objAsleep = asleep,
objSize = size,
objPosition = pos,
objSpeed = speed,
objAttribute = oAttrib
}
createPicture :: ObjectPicture -> (GameObjectPicture,Point2D)
createPicture (Basic (Polyg points r g b fillMode)) = (B (P (point2DtoVertex3 points) (Color4 r g b 1.0) fillMode),findSize points)
createPicture (Basic (Circle radius r g b fillMode)) = (B (C radius (Color4 r g b 1.0) fillMode),(2 * radius,2 * radius))
createPicture (Tex size picIndex) = (Tx picIndex,size)
-- given a point list, finds the height and width
findSize :: [Point2D] -> Point2D
findSize l = ((x2 - x1),(y2 - y1))
where (xList,yList) = unzip l
(x2,y2) = (maximum xList,maximum yList)
(x1,y1) = (minimum xList,minimum yList)
----------------------------------------------
-- grouping GameObjects and creating managers
----------------------------------------------
objectGroup :: String -> [(GameObject t)] -> (ObjectManager t)
objectGroup name objs = OM {mngName = name, mngCounter = toEnum (length objs), mngObjects = objectGroupAux objs name 0}
objectGroupAux :: [(GameObject t)] -> String -> Integer -> [(GameObject t)]
objectGroupAux [] _ _ = []
objectGroupAux (o:os) managerName oId = (o {objId = oId, objManagerName = managerName}):(objectGroupAux os managerName (oId + 1))
addObjectsToManager :: [(GameObject t)] -> String -> [(ObjectManager t)] -> [(ObjectManager t)]
addObjectsToManager _ managerName [] = error ("Objects.addObjectsToManager error: object manager " ++ managerName ++ " does not exists!")
addObjectsToManager objs managerName (m:ms) | (getObjectManagerName m == managerName) = (addObjectsToManagerAux objs m):ms
| otherwise = m:(addObjectsToManager objs managerName ms)
addObjectsToManagerAux :: [(GameObject t)] -> ObjectManager t -> ObjectManager t
addObjectsToManagerAux objs mng = let counter = getObjectManagerCounter mng
newObjects = adjustNewObjects objs (getObjectManagerCounter mng) (getObjectManagerName mng)
in mng {mngObjects = newObjects ++ (getObjectManagerObjects mng), mngCounter = counter + (toEnum (length objs))}
adjustNewObjects :: [(GameObject t)] -> Integer -> String -> [(GameObject t)]
adjustNewObjects [] _ _ = []
adjustNewObjects (o:os) oId managerName = (o {objId = oId, objManagerName = managerName}):(adjustNewObjects os (oId + 1) managerName)
------------------------------------------
-- draw routines
------------------------------------------
drawGameObjects :: [(ObjectManager t)] -> QuadricPrimitive -> [TextureObject] -> IO ()
drawGameObjects [] _ _ = return ()
drawGameObjects (m:ms) qobj picList = drawGameObjectList (getObjectManagerObjects m) qobj picList >> drawGameObjects ms qobj picList
drawGameObjectList :: [(GameObject t)] -> QuadricPrimitive -> [TextureObject] -> IO ()
drawGameObjectList [] _ _ = return ()
drawGameObjectList (o:os) qobj picList | (getGameObjectAsleep o) = drawGameObjectList os qobj picList
| otherwise = drawGameObject o qobj picList >> drawGameObjectList os qobj picList
drawGameObject :: GameObject t -> QuadricPrimitive -> [TextureObject] -> IO ()
drawGameObject o _qobj picList = do
loadIdentity
let (pX,pY) = getGameObjectPosition o
picture = getGameObjectPicture o
translate (Vector3 pX pY (0 :: GLdouble) )
case picture of
(B (P points c fillMode)) -> do
color c
if (fillMode == Filled)
then (renderPrimitive Polygon $ mapM_ vertex points)
else (renderPrimitive LineLoop $ mapM_ vertex points)
(B (C r c fillMode)) -> do
color c
renderQuadric style $ Disk 0 r 20 3
where style = QuadricStyle Nothing NoTextureCoordinates Outside fillStyle
fillStyle = if (fillMode == Filled) then FillStyle else SilhouetteStyle
(Tx picIndex) -> do
texture Texture2D $= Enabled
bindTexture Texture2D (picList !! picIndex)
color (Color4 1.0 1.0 1.0 (1.0 :: GLfloat))
renderPrimitive Quads $ do
texCoord2 0.0 0.0; vertex3 (-x) (-y) 0.0
texCoord2 1.0 0.0; vertex3 x (-y) 0.0
texCoord2 1.0 1.0; vertex3 x y 0.0
texCoord2 0.0 1.0; vertex3 (-x) y 0.0
texture Texture2D $= Disabled
where (sX,sY) = getGameObjectSize o
x = sX/2
y = sY/2
------------------------------------------
-- search routines
------------------------------------------
findObjectFromId :: GameObject t -> [(ObjectManager t)] -> GameObject t
findObjectFromId o mngs = findObjectFromIdAux (getGameObjectId o) (getGameObjectManagerName o) mngs
findObjectFromIdAux :: Integer -> String -> [(ObjectManager t)] -> GameObject t
findObjectFromIdAux _ managerName [] = error ("Objects.findObjectFromIdAux error: object group " ++ managerName ++ " not found!")
findObjectFromIdAux objectId managerName (m:ms) | (managerName == getObjectManagerName m) = searchFromId objectId (getObjectManagerObjects m)
| otherwise = findObjectFromIdAux objectId managerName ms
searchFromId :: Integer -> [(GameObject t)] -> GameObject t
searchFromId _ [] = error ("Objects.searchFromId error: object not found!")
searchFromId objectId (o:os) | (objectId == getGameObjectId o) = o
| otherwise = searchFromId objectId os
searchObjectManager :: String -> [(ObjectManager t)] -> ObjectManager t
searchObjectManager managerName [] = error ("Objects.searchObjectManager error: object group " ++ managerName ++ " not found!")
searchObjectManager managerName (m:ms) | (getObjectManagerName m == managerName) = m
| otherwise = searchObjectManager managerName ms
searchGameObject :: String -> ObjectManager t -> GameObject t
searchGameObject objectName m = searchGameObjectAux objectName (getObjectManagerObjects m)
searchGameObjectAux :: String -> [(GameObject t)] -> GameObject t
searchGameObjectAux objectName [] = error ("Objects.searchGameObjectAux error: object " ++ objectName ++ " not found!")
searchGameObjectAux objectName (a:as) | (getGameObjectName a == objectName) = a
| otherwise = searchGameObjectAux objectName as
------------------------------------------
-- update routines
------------------------------------------
-- substitutes an old object by a new one, given the function to be applied to the old object (whose id is given),
-- the name of its manager and the group of game managers.
updateObject :: (GameObject t -> GameObject t) -> Integer -> String -> [(ObjectManager t)] -> [(ObjectManager t)]
updateObject _ _ managerName [] = error ("Objects.updateObject error: object manager: " ++ managerName ++ " not found!")
updateObject f objectId managerName (m:ms) | (getObjectManagerName m == managerName) = (updateObjectManagerObjects newObjects m):ms
| otherwise = m:(updateObject f objectId managerName ms)
where newObjects = updateObjectAux f objectId (getObjectManagerObjects m)
updateObjectAux :: (GameObject t -> GameObject t) -> Integer -> [(GameObject t)] -> [(GameObject t)]
updateObjectAux _ _ [] = error ("Objects.updateObjectAux error: object not found!")
updateObjectAux f objectId (o:os) | (getGameObjectId o == objectId) = (f o):os
| otherwise = o:(updateObjectAux f objectId os)
------------------------------------------
-- moving routines
------------------------------------------
-- modifies all objects position according to their speed
moveGameObjects :: [(ObjectManager t)] -> [(ObjectManager t)]
moveGameObjects [] = []
moveGameObjects (m:ms) = (updateObjectManagerObjects (map moveSingleObject (getObjectManagerObjects m)) m):(moveGameObjects ms)
moveSingleObject :: GameObject t -> GameObject t
moveSingleObject o = if (getGameObjectAsleep o)
then o
else let (vX,vY) = getGameObjectSpeed o
(pX,pY) = getGameObjectPosition o
in updateObjectPosition (pX + vX, pY + vY) o
------------------------------------------
-- destroy routines
------------------------------------------
destroyGameObject :: String -> String -> [(ObjectManager t)] -> [(ObjectManager t)]
destroyGameObject _ managerName [] = error ("Objects.destroyGameObject error: object manager: " ++ managerName ++ " not found!")
destroyGameObject objectName managerName (m:ms) | (getObjectManagerName m == managerName) = (updateObjectManagerObjects newObjects m):ms
| otherwise = m:(destroyGameObject objectName managerName ms)
where newObjects = destroyGameObjectAux objectName (getObjectManagerObjects m)
destroyGameObjectAux :: String -> [(GameObject t)] -> [(GameObject t)]
destroyGameObjectAux objectName [] = error ("Objects.destroyGameObjectAux error: object: " ++ objectName ++ " not found!")
destroyGameObjectAux objectName (o:os) | (getGameObjectName o == objectName) = os
| otherwise = o:(destroyGameObjectAux objectName os)
|
simonmichael/fungen
|
Graphics/UI/Fungen/Objects.hs
|
bsd-3-clause
| 16,284
| 0
| 17
| 4,086
| 4,119
| 2,176
| 1,943
| 219
| 5
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Control.CP.FD.Interface (
FDSolver,
FDInstance,
(@+),(@-),(@*),(@/),(@%),(!),(@!!),(@..),(@++),size,xfold,xsum,xhead,xtail,list,slice,xmap,cte,
(Control.CP.FD.Interface.@||),
(Control.CP.FD.Interface.@&&),
Control.CP.FD.Interface.inv,
(Control.CP.FD.Interface.@=),
(Control.CP.FD.Interface.@/=),
(Control.CP.FD.Interface.@<),
(Control.CP.FD.Interface.@>),
(Control.CP.FD.Interface.@<=),
(Control.CP.FD.Interface.@>=),
(Control.CP.FD.Interface.@:),
(Control.CP.FD.Interface.@?),
(Control.CP.FD.Interface.@??),
Control.CP.FD.Interface.channel,
val,
-- Control.CP.FD.Interface.newInt, Control.CP.FD.Interface.newBool, Control.CP.FD.Interface.newCol,
Control.CP.FD.Interface.sorted,
Control.CP.FD.Interface.sSorted,
Control.CP.FD.Interface.forall,
Control.CP.FD.Interface.forany,
Control.CP.FD.Interface.loopall,
Control.CP.FD.Interface.allDiff,
Control.CP.FD.Interface.allDiffD,
Control.CP.FD.Interface.loopany,
allin,
asExpr, asCol, Control.CP.FD.Interface.asBool,
colList, labelCol,
ModelInt, ModelCol, ModelBool,
exists, true, false,
-- Modelable,
) where
import Control.CP.FD.FD (FDSolver, FDInstance, FDIntTerm, getColItems)
import qualified Control.CP.FD.Model as Model
import Control.CP.FD.Model (Model, ModelBool, ModelCol, ModelInt, ToModelBool, asBool, asExpr, asCol, cte, newModelTerm, ModelIntArg, ModelBoolArg, ModelColArg)
import qualified Data.Expr.Sugar as Sugar
import Data.Expr.Util
import Data.Expr.Data
import Data.Expr.Sugar ((@+),(@-),(@*),(@/),(@%),(!),(@!!),(@..),(@++),size,xfold,xhead,xtail,slice,xmap,xsum,list)
import Control.CP.Solver
import Control.CP.SearchTree
import Control.CP.EnumTerm
newtype DummySolver a = DummySolver ()
instance Monad DummySolver where
return _ = DummySolver ()
_ >>= _ = DummySolver ()
data EQHelp b where
EQHelp :: Model.ModelTermType b => ((b -> Model) -> Model) -> EQHelp b
instance Model.ModelTermType t => Term DummySolver t where
type Help DummySolver t = EQHelp t
help _ _ = EQHelp newModelTerm
newvar = DummySolver ()
instance Solver DummySolver where
type Constraint DummySolver = Either Model ()
type Label DummySolver = ()
add _ = DummySolver ()
run _ = error "Attempt to run dummy solver"
mark = DummySolver ()
goto _ = DummySolver ()
newtype Model.ModelTermType t => DummyTerm t = DummyTerm t
-- class (Solver s, Term s ModelBool, Term s ModelInt, Term s ModelCol) => Modelable s where
-- instance Modelable DummySolver where
-- instance FDSolver s => Modelable (FDInstance s) where
treeToModel :: Tree DummySolver () -> Model
treeToModel (Return _) = BoolConst True
treeToModel (Try a b) = (Sugar.@||) (treeToModel a) (treeToModel b)
treeToModel (Add (Left c) m) = (Sugar.@&&) c (treeToModel m)
treeToModel Fail = BoolConst False
treeToModel (Label _) = error "Cannot turn labelled trees into expressions"
treeToModel (NewVar (f :: t -> Tree DummySolver ())) = case (help ((error "treeToModel undefined 1") :: DummySolver ()) ((error "treeToModel undefined 2") :: t)) of EQHelp ff -> ff (\x -> treeToModel $ f (x :: t))
addM :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => Model -> m ()
addM m = addC $ Left m
infixr 2 @||
(@||) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => Tree DummySolver () -> Tree DummySolver () -> m ()
(@||) a b = addM $ treeToModel $ a \/ b
infixr 3 @&&
(@&&) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => Tree DummySolver () -> Tree DummySolver () -> m ()
(@&&) a b = addM $ treeToModel $ a /\ b
channel :: Tree DummySolver () -> ModelInt
channel a = Sugar.channel $ treeToModel a
inv :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => Tree DummySolver () -> m ()
inv a = addM $ Sugar.inv $ treeToModel a
infix 4 @=, @/=, @<, @>, @<=, @>=
class ModelExprClass a where
(@=) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => a -> a -> m ()
(@/=) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => a -> a -> m ()
instance ModelExprClass ModelInt where
a @= b = addM $ (Sugar.@=) a b
a @/= b = addM $ (Sugar.@/=) a b
instance ModelExprClass ModelCol where
a @= b = addM $ (Sugar.@=) a b
a @/= b = addM $ (Sugar.@/=) a b
instance ModelExprClass ModelBool where
a @= b = addM $ (Sugar.@=) a b
a @/= b = addM $ (Sugar.@/=) a b
instance ModelExprClass (Tree DummySolver ()) where
a @= b = addM $ (Sugar.@=) (treeToModel a) (treeToModel b)
a @/= b = addM $ (Sugar.@/=) (treeToModel a) (treeToModel b)
(@<) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelInt -> ModelInt -> m ()
(@<) a b = addM $ (Sugar.@<) a b
(@>) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelInt -> ModelInt -> m ()
(@>) a b = addM $ (Sugar.@>) a b
(@>=) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelInt -> ModelInt -> m ()
(@>=) a b = addM $ (Sugar.@>=) a b
(@<=) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelInt -> ModelInt -> m ()
(@<=) a b = addM $ (Sugar.@<=) a b
val :: Tree DummySolver () -> ModelInt
val = Sugar.toExpr . treeToModel
{- newBool :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelBool -> Tree DummySolver a) -> m a
newBool = exists
newInt :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelInt -> m a) -> m a
newInt = exists
newCol :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelCol -> m a) -> m a
newCol = exists
-}
asBool :: (FDSolver s, MonadTree m, TreeSolver m ~ FDInstance s, ToModelBool t) => t -> m ()
asBool = addM . Control.CP.FD.Model.asBool
sorted :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> m ()
sorted = addM . Sugar.sorted
sSorted :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> m ()
sSorted = addM . Sugar.sSorted
allDiff :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> m ()
allDiff = addM . Sugar.allDiff
allDiffD :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> m ()
allDiffD = addM . Sugar.allDiffD
mm (nv@(Term tv)) m x =
let tf t = if (t==tv) then x else Term t
tb t = if (Term t==x) then nv else Term t
in boolTransformEx (tf,ColTerm,BoolTerm,tb,ColTerm,BoolTerm) m
forall :: (Term s ModelInt, Term s ModelBool, Term s ModelCol, Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> (ModelInt -> Tree DummySolver ()) -> m ()
-- forall col f = exists $ \nv -> addM $ Sugar.forall col $ mm nv $ treeToModel $ f nv
forall col f = addM $ Sugar.forall col (treeToModel . f)
forany :: (Term s ModelInt, Term s ModelBool, Term s ModelCol, Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> (ModelInt -> Tree DummySolver ()) -> m ()
-- forany col f = exists $ \nv -> addM $ Sugar.forany col $ mm nv $ treeToModel $ f nv
forany col f = addM $ Sugar.forany col (treeToModel . f)
loopall :: (Term s ModelInt, Term s ModelBool, Term s ModelCol, Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelInt,ModelInt) -> (ModelInt -> Tree DummySolver ()) -> m ()
-- loopall r f = exists $ \nv -> addM $ Sugar.loopall r $ mm nv $ treeToModel $ f nv
loopall r f = addM $ Sugar.loopall r (treeToModel . f)
loopany :: (Term s ModelInt, Term s ModelBool, Term s ModelCol, Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => (ModelInt,ModelInt) -> (ModelInt -> Tree DummySolver ()) -> m ()
-- loopany r f = exists $ \nv -> addM $ Sugar.loopany r $ mm nv $ treeToModel $ f nv
loopany r f = addM $ Sugar.loopany r (treeToModel . f)
colList :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s) => ModelCol -> Int -> m [ModelInt]
colList col len = do
addM $ (Sugar.@=) (size col) (asExpr len)
return $ map (\i -> col!cte i) [0..len-1]
labelCol :: (FDSolver s, MonadTree m, TreeSolver m ~ FDInstance s, EnumTerm s (FDIntTerm s)) => ModelCol -> m [TermBaseType s (FDIntTerm s)]
labelCol col = label $ do
lst <- getColItems col maxBound
return $ do
lsti <- colList col $ length lst
enumerate lsti
assignments lsti
infix 5 @:
(@:) :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s, Sugar.ExprRange ModelIntArg ModelColArg ModelBoolArg r, Term s ModelInt, Term s ModelBool, Term s ModelCol) => ModelInt -> r -> m ()
a @: b = addM $ (Sugar.@:) a b
infix 4 @?
infix 4 @??
a @? (t,f) = (Sugar.@?) (treeToModel a) (t,f)
a @?? (t,f) = addM $ (Sugar.@??) (treeToModel a) (treeToModel t, treeToModel f)
allin :: (Constraint s ~ Either Model q, MonadTree m, TreeSolver m ~ s, Sugar.ExprRange ModelIntArg ModelColArg ModelBoolArg r, Term s ModelInt, Term s ModelBool, Term s ModelCol) => ModelCol -> r -> m ()
allin c b = Control.CP.FD.Interface.forall c $ \x -> addM $ (Sugar.@:) x b
|
FranklinChen/monadiccp
|
Control/CP/FD/Interface.hs
|
bsd-3-clause
| 9,176
| 0
| 13
| 1,695
| 3,661
| 1,972
| 1,689
| -1
| -1
|
{-# LANGUAGE CPP #-}
module Aws.S3.Commands.PutObject
where
import Aws.Core
import Aws.S3.Core
import Control.Applicative
import Control.Arrow (second)
import Crypto.Hash
import Data.ByteString.Char8 ({- IsString -})
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import qualified Data.CaseInsensitive as CI
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.HTTP.Conduit as HTTP
data PutObject = PutObject {
poObjectName :: T.Text,
poBucket :: Bucket,
poContentType :: Maybe B.ByteString,
poCacheControl :: Maybe T.Text,
poContentDisposition :: Maybe T.Text,
poContentEncoding :: Maybe T.Text,
poContentMD5 :: Maybe (Digest MD5),
poExpires :: Maybe Int,
poAcl :: Maybe CannedAcl,
poStorageClass :: Maybe StorageClass,
poWebsiteRedirectLocation :: Maybe T.Text,
poServerSideEncryption :: Maybe ServerSideEncryption,
#if MIN_VERSION_http_conduit(2, 0, 0)
poRequestBody :: HTTP.RequestBody,
#else
poRequestBody :: HTTP.RequestBody (C.ResourceT IO),
#endif
poMetadata :: [(T.Text,T.Text)],
poAutoMakeBucket :: Bool -- ^ Internet Archive S3 nonstandard extension
}
#if MIN_VERSION_http_conduit(2, 0, 0)
putObject :: Bucket -> T.Text -> HTTP.RequestBody -> PutObject
#else
putObject :: Bucket -> T.Text -> HTTP.RequestBody (C.ResourceT IO) -> PutObject
#endif
putObject bucket obj body = PutObject obj bucket Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing body [] False
data PutObjectResponse
= PutObjectResponse {
porVersionId :: Maybe T.Text
}
deriving (Show)
-- | ServiceConfiguration: 'S3Configuration'
instance SignQuery PutObject where
type ServiceConfiguration PutObject = S3Configuration
signQuery PutObject {..} = s3SignQuery S3Query {
s3QMethod = Put
, s3QBucket = Just $ T.encodeUtf8 poBucket
, s3QSubresources = []
, s3QQuery = []
, s3QContentType = poContentType
, s3QContentMd5 = poContentMD5
, s3QAmzHeaders = map (second T.encodeUtf8) $ catMaybes [
("x-amz-acl",) <$> writeCannedAcl <$> poAcl
, ("x-amz-storage-class",) <$> writeStorageClass <$> poStorageClass
, ("x-amz-website-redirect-location",) <$> poWebsiteRedirectLocation
, ("x-amz-server-side-encryption",) <$> writeServerSideEncryption <$> poServerSideEncryption
, if poAutoMakeBucket then Just ("x-amz-auto-make-bucket", "1") else Nothing
] ++ map( \x -> (CI.mk . T.encodeUtf8 $ T.concat ["x-amz-meta-", fst x], snd x)) poMetadata
, s3QOtherHeaders = map (second T.encodeUtf8) $ catMaybes [
("Expires",) . T.pack . show <$> poExpires
, ("Cache-Control",) <$> poCacheControl
, ("Content-Disposition",) <$> poContentDisposition
, ("Content-Encoding",) <$> poContentEncoding
]
, s3QRequestBody = Just poRequestBody
, s3QObject = Just $ T.encodeUtf8 poObjectName
}
instance ResponseConsumer PutObject PutObjectResponse where
type ResponseMetadata PutObjectResponse = S3Metadata
responseConsumer _ = s3ResponseConsumer $ \resp -> do
let vid = T.decodeUtf8 `fmap` lookup "x-amz-version-id" (HTTP.responseHeaders resp)
return $ PutObjectResponse vid
instance Transaction PutObject PutObjectResponse
instance AsMemoryResponse PutObjectResponse where
type MemoryResponse PutObjectResponse = PutObjectResponse
loadToMemory = return
|
fpco/aws
|
Aws/S3/Commands/PutObject.hs
|
bsd-3-clause
| 4,173
| 0
| 17
| 1,363
| 807
| 463
| 344
| -1
| -1
|
module C (bar) where bar = do putStrLn "Hello C"
|
codeboardio/mantra
|
test/test_resources/haskell/hs_error_several_files/Root/C.hs
|
mit
| 48
| 0
| 7
| 9
| 20
| 11
| 9
| 1
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudSearch.DescribeDomains
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Gets information about the search domains owned by this account. Can be
-- limited to specific domains. Shows all domains by default. To get the number
-- of searchable documents in a domain, use the console or submit a 'matchall'
-- request to your domain's search endpoint: 'q=matchall&q.parser=structured&size=0'. For more information, see Getting Information about a Search Domain in the /Amazon CloudSearch Developer Guide/.
--
-- <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/API_DescribeDomains.html>
module Network.AWS.CloudSearch.DescribeDomains
(
-- * Request
DescribeDomains
-- ** Request constructor
, describeDomains
-- ** Request lenses
, ddDomainNames
-- * Response
, DescribeDomainsResponse
-- ** Response constructor
, describeDomainsResponse
-- ** Response lenses
, ddrDomainStatusList
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.CloudSearch.Types
import qualified GHC.Exts
newtype DescribeDomains = DescribeDomains
{ _ddDomainNames :: List "member" Text
} deriving (Eq, Ord, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeDomains where
type Item DescribeDomains = Text
fromList = DescribeDomains . GHC.Exts.fromList
toList = GHC.Exts.toList . _ddDomainNames
-- | 'DescribeDomains' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ddDomainNames' @::@ ['Text']
--
describeDomains :: DescribeDomains
describeDomains = DescribeDomains
{ _ddDomainNames = mempty
}
-- | The names of the domains you want to include in the response.
ddDomainNames :: Lens' DescribeDomains [Text]
ddDomainNames = lens _ddDomainNames (\s a -> s { _ddDomainNames = a }) . _List
newtype DescribeDomainsResponse = DescribeDomainsResponse
{ _ddrDomainStatusList :: List "member" DomainStatus
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeDomainsResponse where
type Item DescribeDomainsResponse = DomainStatus
fromList = DescribeDomainsResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _ddrDomainStatusList
-- | 'DescribeDomainsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ddrDomainStatusList' @::@ ['DomainStatus']
--
describeDomainsResponse :: DescribeDomainsResponse
describeDomainsResponse = DescribeDomainsResponse
{ _ddrDomainStatusList = mempty
}
ddrDomainStatusList :: Lens' DescribeDomainsResponse [DomainStatus]
ddrDomainStatusList =
lens _ddrDomainStatusList (\s a -> s { _ddrDomainStatusList = a })
. _List
instance ToPath DescribeDomains where
toPath = const "/"
instance ToQuery DescribeDomains where
toQuery DescribeDomains{..} = mconcat
[ "DomainNames" =? _ddDomainNames
]
instance ToHeaders DescribeDomains
instance AWSRequest DescribeDomains where
type Sv DescribeDomains = CloudSearch
type Rs DescribeDomains = DescribeDomainsResponse
request = post "DescribeDomains"
response = xmlResponse
instance FromXML DescribeDomainsResponse where
parseXML = withElement "DescribeDomainsResult" $ \x -> DescribeDomainsResponse
<$> x .@? "DomainStatusList" .!@ mempty
|
romanb/amazonka
|
amazonka-cloudsearch/gen/Network/AWS/CloudSearch/DescribeDomains.hs
|
mpl-2.0
| 4,318
| 0
| 10
| 855
| 531
| 320
| 211
| 62
| 1
|
module Dotnet.System.Web.Mail.MailAttachment where
import Dotnet
import qualified Dotnet.System.Object
import qualified Dotnet.System.Web.Mail.MailEncoding
data MailAttachment_ a
type MailAttachment a = Dotnet.System.Object.Object (MailAttachment_ a)
foreign import dotnet
"method System.Web.Mail.MailAttachment.get_Filename"
get_Filename :: MailAttachment obj -> IO (String)
foreign import dotnet
"method System.Web.Mail.MailAttachment.get_Encoding"
get_Encoding :: MailAttachment obj -> IO (Dotnet.System.Web.Mail.MailEncoding.MailEncoding a0)
|
alekar/hugs
|
dotnet/lib/Dotnet/System/Web/Mail/MailAttachment.hs
|
bsd-3-clause
| 560
| 0
| 10
| 60
| 111
| 68
| 43
| -1
| -1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
-- | Parsing command line targets
--
-- There are two relevant data sources for performing this parsing:
-- the project configuration, and command line arguments. Project
-- configurations includes the resolver (defining a LoadedSnapshot of
-- global and snapshot packages), local dependencies, and project
-- packages. It also defines local flag overrides.
--
-- The command line arguments specify both additional local flag
-- overrides and targets in their raw form.
--
-- Flags are simple: we just combine CLI flags with config flags and
-- make one big map of flags, preferring CLI flags when present.
--
-- Raw targets can be a package name, a package name with component,
-- just a component, or a package name and version number. We first
-- must resolve these raw targets into both simple targets and
-- additional dependencies. This works as follows:
--
-- * If a component is specified, find a unique project package which
-- defines that component, and convert it into a name+component
-- target.
--
-- * Ensure that all name+component values refer to valid components
-- in the given project package.
--
-- * For names, check if the name is present in the snapshot, local
-- deps, or project packages. If it is not, then look up the most
-- recent version in the package index and convert to a
-- name+version.
--
-- * For name+version, first ensure that the name is not used by a
-- project package. Next, if that name+version is present in the
-- snapshot or local deps _and_ its location is PLIndex, we have the
-- package. Otherwise, add to local deps with the appropriate
-- PLIndex.
--
-- If in either of the last two bullets we added a package to local
-- deps, print a warning to the user recommending modifying the
-- extra-deps.
--
-- Combine the various 'ResolveResults's together into 'Target'
-- values, by combining various components for a single package and
-- ensuring that no conflicting statements were made about targets.
--
-- At this point, we now have a Map from package name to SimpleTarget,
-- and an updated Map of local dependencies. We still have the
-- aggregated flags, and the snapshot and project packages.
--
-- Finally, we upgrade the snapshot by using
-- calculatePackagePromotion.
module Stack.Build.Target
( -- * Types
Target (..)
, NeedTargets (..)
, PackageType (..)
, parseTargets
-- * Convenience helpers
, gpdVersion
-- * Test suite exports
, parseRawTarget
, RawTarget (..)
, UnresolvedComponent (..)
) where
import Stack.Prelude
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import Distribution.PackageDescription (GenericPackageDescription, package, packageDescription)
import Path
import Path.Extra (rejectMissingDir)
import Path.IO
import Stack.Config (getLocalPackages)
import Stack.PackageIndex
import Stack.PackageLocation
import Stack.Snapshot (calculatePackagePromotion)
import Stack.Types.Config
import Stack.Types.NamedComponent
import Stack.Types.PackageIdentifier
import Stack.Types.PackageName
import Stack.Types.Version
import Stack.Types.Build
import Stack.Types.BuildPlan
import Stack.Types.GhcPkgId
-- | Do we need any targets? For example, `stack build` will fail if
-- no targets are provided.
data NeedTargets = NeedTargets | AllowNoTargets
---------------------------------------------------------------------------------
-- Get the RawInput
---------------------------------------------------------------------------------
-- | Raw target information passed on the command line.
newtype RawInput = RawInput { unRawInput :: Text }
getRawInput :: BuildOptsCLI -> Map PackageName LocalPackageView -> ([Text], [RawInput])
getRawInput boptscli locals =
let textTargets' = boptsCLITargets boptscli
textTargets =
-- Handle the no targets case, which means we pass in the names of all project packages
if null textTargets'
then map packageNameText (Map.keys locals)
else textTargets'
in (textTargets', map RawInput textTargets)
---------------------------------------------------------------------------------
-- Turn RawInput into RawTarget
---------------------------------------------------------------------------------
-- | The name of a component, which applies to executables, test
-- suites, and benchmarks
type ComponentName = Text
-- | Either a fully resolved component, or a component name that could be
-- either an executable, test, or benchmark
data UnresolvedComponent
= ResolvedComponent !NamedComponent
| UnresolvedComponent !ComponentName
deriving (Show, Eq, Ord)
-- | Raw command line input, without checking against any databases or list of
-- locals. Does not deal with directories
data RawTarget
= RTPackageComponent !PackageName !UnresolvedComponent
| RTComponent !ComponentName
| RTPackage !PackageName
-- Explicitly _not_ supporting revisions on the command line. If
-- you want that, you should be modifying your stack.yaml! (In
-- fact, you should probably do that anyway, we're just letting
-- people be lazy, since we're Haskeletors.)
| RTPackageIdentifier !PackageIdentifier
deriving (Show, Eq)
-- | Same as @parseRawTarget@, but also takes directories into account.
parseRawTargetDirs :: MonadIO m
=> Path Abs Dir -- ^ current directory
-> Map PackageName LocalPackageView
-> RawInput -- ^ raw target information from the commandline
-> m (Either Text [(RawInput, RawTarget)])
parseRawTargetDirs root locals ri =
case parseRawTarget t of
Just rt -> return $ Right [(ri, rt)]
Nothing -> do
mdir <- liftIO $ forgivingAbsence (resolveDir root (T.unpack t))
>>= rejectMissingDir
case mdir of
Nothing -> return $ Left $ "Directory not found: " `T.append` t
Just dir ->
case mapMaybe (childOf dir) $ Map.toList locals of
[] -> return $ Left $
"No local directories found as children of " `T.append`
t
names -> return $ Right $ map ((ri, ) . RTPackage) names
where
childOf dir (name, lpv) =
if dir == lpvRoot lpv || isProperPrefixOf dir (lpvRoot lpv)
then Just name
else Nothing
RawInput t = ri
-- | If this function returns @Nothing@, the input should be treated as a
-- directory.
parseRawTarget :: Text -> Maybe RawTarget
parseRawTarget t =
(RTPackageIdentifier <$> parsePackageIdentifier t)
<|> (RTPackage <$> parsePackageNameFromString s)
<|> (RTComponent <$> T.stripPrefix ":" t)
<|> parsePackageComponent
where
s = T.unpack t
parsePackageComponent =
case T.splitOn ":" t of
[pname, "lib"]
| Just pname' <- parsePackageNameFromString (T.unpack pname) ->
Just $ RTPackageComponent pname' $ ResolvedComponent CLib
[pname, cname]
| Just pname' <- parsePackageNameFromString (T.unpack pname) ->
Just $ RTPackageComponent pname' $ UnresolvedComponent cname
[pname, typ, cname]
| Just pname' <- parsePackageNameFromString (T.unpack pname)
, Just wrapper <- parseCompType typ ->
Just $ RTPackageComponent pname' $ ResolvedComponent $ wrapper cname
_ -> Nothing
parseCompType t' =
case t' of
"exe" -> Just CExe
"test" -> Just CTest
"bench" -> Just CBench
_ -> Nothing
---------------------------------------------------------------------------------
-- Resolve the raw targets
---------------------------------------------------------------------------------
data ResolveResult = ResolveResult
{ rrName :: !PackageName
, rrRaw :: !RawInput
, rrComponent :: !(Maybe NamedComponent)
-- ^ Was a concrete component specified?
, rrAddedDep :: !(Maybe Version)
-- ^ Only if we're adding this as a dependency
, rrPackageType :: !PackageType
}
-- | Convert a 'RawTarget' into a 'ResolveResult' (see description on
-- the module).
resolveRawTarget
:: forall env. HasConfig env
=> Map PackageName (LoadedPackageInfo GhcPkgId) -- ^ globals
-> Map PackageName (LoadedPackageInfo (PackageLocationIndex FilePath)) -- ^ snapshot
-> Map PackageName (GenericPackageDescription, PackageLocationIndex FilePath) -- ^ local deps
-> Map PackageName LocalPackageView -- ^ project packages
-> (RawInput, RawTarget)
-> RIO env (Either Text ResolveResult)
resolveRawTarget globals snap deps locals (ri, rt) =
go rt
where
-- Helper function: check if a 'NamedComponent' matches the given 'ComponentName'
isCompNamed :: ComponentName -> NamedComponent -> Bool
isCompNamed _ CLib = False
isCompNamed t1 (CExe t2) = t1 == t2
isCompNamed t1 (CTest t2) = t1 == t2
isCompNamed t1 (CBench t2) = t1 == t2
go (RTComponent cname) = return $
-- Associated list from component name to package that defines
-- it. We use an assoc list and not a Map so we can detect
-- duplicates.
let allPairs = concatMap
(\(name, lpv) -> map (name,) $ Set.toList $ lpvComponents lpv)
(Map.toList locals)
in case filter (isCompNamed cname . snd) allPairs of
[] -> Left $ cname `T.append` " doesn't seem to be a local target. Run 'stack ide targets' for a list of available targets"
[(name, comp)] -> Right ResolveResult
{ rrName = name
, rrRaw = ri
, rrComponent = Just comp
, rrAddedDep = Nothing
, rrPackageType = ProjectPackage
}
matches -> Left $ T.concat
[ "Ambiugous component name "
, cname
, ", matches: "
, T.pack $ show matches
]
go (RTPackageComponent name ucomp) = return $
case Map.lookup name locals of
Nothing -> Left $ T.pack $ "Unknown local package: " ++ packageNameString name
Just lpv ->
case ucomp of
ResolvedComponent comp
| comp `Set.member` lpvComponents lpv -> Right ResolveResult
{ rrName = name
, rrRaw = ri
, rrComponent = Just comp
, rrAddedDep = Nothing
, rrPackageType = ProjectPackage
}
| otherwise -> Left $ T.pack $ concat
[ "Component "
, show comp
, " does not exist in package "
, packageNameString name
]
UnresolvedComponent comp ->
case filter (isCompNamed comp) $ Set.toList $ lpvComponents lpv of
[] -> Left $ T.concat
[ "Component "
, comp
, " does not exist in package "
, T.pack $ packageNameString name
]
[x] -> Right ResolveResult
{ rrName = name
, rrRaw = ri
, rrComponent = Just x
, rrAddedDep = Nothing
, rrPackageType = ProjectPackage
}
matches -> Left $ T.concat
[ "Ambiguous component name "
, comp
, " for package "
, T.pack $ packageNameString name
, ": "
, T.pack $ show matches
]
go (RTPackage name)
| Map.member name locals = return $ Right ResolveResult
{ rrName = name
, rrRaw = ri
, rrComponent = Nothing
, rrAddedDep = Nothing
, rrPackageType = ProjectPackage
}
| Map.member name deps ||
Map.member name snap ||
Map.member name globals = return $ Right ResolveResult
{ rrName = name
, rrRaw = ri
, rrComponent = Nothing
, rrAddedDep = Nothing
, rrPackageType = Dependency
}
| otherwise = do
mversion <- getLatestVersion name
return $ case mversion of
-- This is actually an error case. We _could_ return a
-- Left value here, but it turns out to be better to defer
-- this until the ConstructPlan phase, and let it complain
-- about the missing package so that we get more errors
-- together, plus the fancy colored output from that
-- module.
Nothing -> Right ResolveResult
{ rrName = name
, rrRaw = ri
, rrComponent = Nothing
, rrAddedDep = Nothing
, rrPackageType = Dependency
}
Just version -> Right ResolveResult
{ rrName = name
, rrRaw = ri
, rrComponent = Nothing
, rrAddedDep = Just version
, rrPackageType = Dependency
}
where
getLatestVersion pn =
fmap fst . Set.maxView <$> getPackageVersions pn
go (RTPackageIdentifier ident@(PackageIdentifier name version))
| Map.member name locals = return $ Left $ T.concat
[ packageNameText name
, " target has a specific version number, but it is a local package."
, "\nTo avoid confusion, we will not install the specified version or build the local one."
, "\nTo build the local package, specify the target without an explicit version."
]
| otherwise = return $
case Map.lookup name allLocs of
-- Installing it from the package index, so we're cool
-- with overriding it if necessary
Just (PLIndex (PackageIdentifierRevision (PackageIdentifier _name versionLoc) _mcfi)) -> Right ResolveResult
{ rrName = name
, rrRaw = ri
, rrComponent = Nothing
, rrAddedDep =
if version == versionLoc
-- But no need to override anyway, this is already the
-- version we have
then Nothing
-- OK, we'll override it
else Just version
, rrPackageType = Dependency
}
-- The package was coming from something besides the
-- index, so refuse to do the override
Just (PLOther loc') -> Left $ T.concat
[ "Package with identifier was targeted on the command line: "
, packageIdentifierText ident
, ", but it was specified from a non-index location: "
, T.pack $ show loc'
, ".\nRecommendation: add the correctly desired version to extra-deps."
]
-- Not present at all, so add it
Nothing -> Right ResolveResult
{ rrName = name
, rrRaw = ri
, rrComponent = Nothing
, rrAddedDep = Just version
, rrPackageType = Dependency
}
where
allLocs :: Map PackageName (PackageLocationIndex FilePath)
allLocs = Map.unions
[ Map.mapWithKey
(\name' lpi -> PLIndex $ PackageIdentifierRevision
(PackageIdentifier name' (lpiVersion lpi))
CFILatest)
globals
, Map.map lpiLocation snap
, Map.map snd deps
]
---------------------------------------------------------------------------------
-- Combine the ResolveResults
---------------------------------------------------------------------------------
-- | How a package is intended to be built
data Target
= TargetAll !PackageType
-- ^ Build all of the default components.
| TargetComps !(Set NamedComponent)
-- ^ Only build specific components
data PackageType = ProjectPackage | Dependency
deriving (Eq, Show)
combineResolveResults
:: forall env. HasLogFunc env
=> [ResolveResult]
-> RIO env ([Text], Map PackageName Target, Map PackageName (PackageLocationIndex FilePath))
combineResolveResults results = do
addedDeps <- fmap Map.unions $ forM results $ \result ->
case rrAddedDep result of
Nothing -> return Map.empty
Just version -> do
let ident = PackageIdentifier (rrName result) version
return $ Map.singleton (rrName result) $ PLIndex $ PackageIdentifierRevision ident CFILatest
let m0 = Map.unionsWith (++) $ map (\rr -> Map.singleton (rrName rr) [rr]) results
(errs, ms) = partitionEithers $ flip map (Map.toList m0) $ \(name, rrs) ->
let mcomps = map rrComponent rrs in
-- Confirm that there is either exactly 1 with no component, or
-- that all rrs are components
case rrs of
[] -> assert False $ Left "Somehow got no rrComponent values, that can't happen"
[rr] | isNothing (rrComponent rr) -> Right $ Map.singleton name $ TargetAll $ rrPackageType rr
_
| all isJust mcomps -> Right $ Map.singleton name $ TargetComps $ Set.fromList $ catMaybes mcomps
| otherwise -> Left $ T.concat
[ "The package "
, packageNameText name
, " was specified in multiple, incompatible ways: "
, T.unwords $ map (unRawInput . rrRaw) rrs
]
return (errs, Map.unions ms, addedDeps)
---------------------------------------------------------------------------------
-- OK, let's do it!
---------------------------------------------------------------------------------
parseTargets
:: HasEnvConfig env
=> NeedTargets
-> BuildOptsCLI
-> RIO env
( LoadedSnapshot -- upgraded snapshot, with some packages possibly moved to local
, Map PackageName (LoadedPackageInfo (PackageLocationIndex FilePath)) -- all local deps
, Map PackageName Target
)
parseTargets needTargets boptscli = do
logDebug "Parsing the targets"
bconfig <- view buildConfigL
ls0 <- view loadedSnapshotL
workingDir <- getCurrentDir
lp <- getLocalPackages
let locals = lpProject lp
deps = lpDependencies lp
globals = lsGlobals ls0
snap = lsPackages ls0
(textTargets', rawInput) = getRawInput boptscli locals
(errs1, concat -> rawTargets) <- fmap partitionEithers $ forM rawInput $
parseRawTargetDirs workingDir (lpProject lp)
(errs2, resolveResults) <- fmap partitionEithers $ forM rawTargets $
resolveRawTarget globals snap deps locals
(errs3, targets, addedDeps) <- combineResolveResults resolveResults
case concat [errs1, errs2, errs3] of
[] -> return ()
errs -> throwIO $ TargetParseException errs
case (Map.null targets, needTargets) of
(False, _) -> return ()
(True, AllowNoTargets) -> return ()
(True, NeedTargets)
| null textTargets' && bcImplicitGlobal bconfig -> throwIO $ TargetParseException
["The specified targets matched no packages.\nPerhaps you need to run 'stack init'?"]
| null textTargets' && Map.null locals -> throwIO $ TargetParseException
["The project contains no local packages (packages not marked with 'extra-dep')"]
| otherwise -> throwIO $ TargetParseException
["The specified targets matched no packages"]
root <- view projectRootL
let dropMaybeKey (Nothing, _) = Map.empty
dropMaybeKey (Just key, value) = Map.singleton key value
flags = Map.unionWith Map.union
(Map.unions (map dropMaybeKey (Map.toList (boptsCLIFlags boptscli))))
(bcFlags bconfig)
hides = Map.empty -- not supported to add hidden packages
-- We promote packages to the local database if the GHC options
-- are added to them by name. See:
-- https://github.com/commercialhaskell/stack/issues/849#issuecomment-320892095.
--
-- GHC options applied to all packages are handled by getGhcOptions.
options = configGhcOptionsByName (bcConfig bconfig)
drops = Set.empty -- not supported to add drops
(globals', snapshots, locals') <- do
addedDeps' <- fmap Map.fromList $ forM (Map.toList addedDeps) $ \(name, loc) -> do
gpd <- parseSingleCabalFileIndex root loc
return (name, (gpd, loc, Nothing))
-- Calculate a list of all of the locals, based on the project
-- packages, local dependencies, and added deps found from the
-- command line
let allLocals :: Map PackageName (GenericPackageDescription, PackageLocationIndex FilePath, Maybe LocalPackageView)
allLocals = Map.unions
[ -- project packages
Map.map
(\lpv -> (lpvGPD lpv, PLOther $ lpvLoc lpv, Just lpv))
(lpProject lp)
, -- added deps take precendence over local deps
addedDeps'
, -- added deps take precendence over local deps
Map.map
(\(gpd, loc) -> (gpd, loc, Nothing))
(lpDependencies lp)
]
calculatePackagePromotion
root ls0 (Map.elems allLocals)
flags hides options drops
let ls = LoadedSnapshot
{ lsCompilerVersion = lsCompilerVersion ls0
, lsGlobals = globals'
, lsPackages = snapshots
}
localDeps = Map.fromList $ flip mapMaybe (Map.toList locals') $ \(name, lpi) ->
-- We want to ignore any project packages, but grab the local
-- deps and upgraded snapshot deps
case lpiLocation lpi of
(_, Just (Just _localPackageView)) -> Nothing -- project package
(loc, _) -> Just (name, lpi { lpiLocation = loc }) -- upgraded or local dep
return (ls, localDeps, targets)
gpdVersion :: GenericPackageDescription -> Version
gpdVersion gpd =
version
where
PackageIdentifier _ version = fromCabalPackageIdentifier $ package $ packageDescription gpd
|
anton-dessiatov/stack
|
src/Stack/Build/Target.hs
|
bsd-3-clause
| 23,182
| 0
| 24
| 7,390
| 4,128
| 2,202
| 1,926
| 387
| 17
|
-- (c) Simon Marlow 2011, see the file LICENSE for copying terms.
-- Simple wrapper around HTTP, allowing proxy use
module GetURL (getURL) where
import Network.HTTP
import Network.Browser
import Network.URI
import Data.ByteString (ByteString)
getURL :: String -> IO ByteString
getURL url = do
Network.Browser.browse $ do
setCheckForProxy True
setDebugLog Nothing
setOutHandler (const (return ()))
(_, rsp) <- request (getRequest' (escapeURIString isUnescapedInURI url))
return (rspBody rsp)
where
getRequest' :: String -> Request ByteString
getRequest' urlString =
case parseURI urlString of
Nothing -> error ("getRequest: Not a valid URL - " ++ urlString)
Just u -> mkRequest GET u
|
prt2121/haskell-practice
|
parconc/GetURL.hs
|
apache-2.0
| 734
| 0
| 15
| 148
| 199
| 99
| 100
| 18
| 2
|
module HAD.Y2014.M03.D07.Solution where
import Control.Applicative ((<*>))
import Data.List (intercalate)
-- | trueIndexes produce an infinite list where only the index given in the list
-- in parameter are true.
-- The parameter list is supposed to be sorted and nubbed
--
-- Point-free: Probably hard to find!
-- Level: HARD
--
-- Examples:
-- >>> take 2 $ trueIndexes [1]
-- [False,True]
--
-- >>> take 6 $ trueIndexes [0,2..]
-- [True,False,True,False,True,False]
--
-- >>> take 3 $ trueIndexes []
-- [False,False,False]
--
trueIndexes :: [Int] -> [Bool]
trueIndexes =
intercalate [True]
. (++ [repeat False])
. (zipWith ((flip replicate False .) . subtract . (+1)) <*> tail)
. (-1:)
|
1HaskellADay/1HAD
|
exercises/HAD/Y2014/M03/D07/Solution.hs
|
mit
| 706
| 0
| 14
| 128
| 136
| 88
| 48
| 9
| 1
|
{-# LANGUAGE DataKinds #-}
-- GSoC 2015 - Haskell bindings for OpenCog.
-- | This Module offers useful functions for working on an AtomSpace.
module OpenCog.AtomSpace.Utils (
showAtom
, printAtom
, atomMap
, atomMapM
, atomFold
, atomElem
, nodeName
, atomType
, atomGetAllNodes
) where
import OpenCog.AtomSpace.Types (Atom(..),TruthVal(..))
import OpenCog.AtomSpace.Internal (fromTVRaw,toTVRaw)
import OpenCog.AtomSpace.Api (get,insert)
import OpenCog.AtomSpace.Types
import OpenCog.AtomSpace.Env (AtomSpace)
import Data.Functor ((<$>))
import Data.Typeable (Typeable)
-- | 'showTV' shows a truth value in opencog notation.
showTV :: TruthVal -> String
showTV (SimpleTV a b ) = "(stv "++show a++" "++show b++")"
showTV (CountTV a b c ) = "(ctv "++show a++" "++show b++" "++show c++")"
showTV (IndefTV a b c d e) = "(itv "++show a++" "++show b++" "
++show c++" "++show d++" "
++show e++")"
showTV (FuzzyTV a b ) = "(ftv "++show a++" "++show b++")"
showTV (ProbTV a b c ) = "(ptv "++show a++" "++show b++" "++show c++")"
showTV' :: Maybe TruthVal -> String
showTV' (Just tv) = showTV tv
showTV' Nothing = ""
-- | 'showAtom' shows an atom in opencog notation (indented notation).
showAtom :: Atom -> String
showAtom at = concatWNewline $ list 0 at
where
list :: Int -> Atom -> [String]
list lv at = case at of
Link atype lraw tv -> let showtv = showTV tv
in [tab lv $ concatWSpaces [atype,showtv]]
++ concat (map (list (lv+1)) lraw)
Node atype aname tv -> let showtv = showTV tv
in [tab lv $ concatWSpaces [atype,showtv
,"\""++aname++"\""]]
concatWNewline :: [String] -> String
concatWNewline [] = []
concatWNewline (x:xs) = foldr1 (\a b -> a++"\n"++b) (x:xs)
concatWSpaces :: [String] -> String
concatWSpaces [] = []
concatWSpaces (x:xs) = foldr1 (\a b -> if a /= ""
then a++" "++b
else b) (x:xs)
tab :: Int -> String -> String
tab 0 s = s
tab lv s = " "++ tab (lv-1) s
-- | 'printAtom' prints the given atom on stdout.
printAtom :: Atom -> IO ()
printAtom at = putStrLn $ showAtom at
-- Atoms can build a tree structure
-- the following functions make it easier to
-- apply functions to all Atoms in such a tree
atomMap :: (Atom -> Atom) -> Atom -> Atom
atomMap f (Link t ls tv) = f $ Link t (map (atomMap f) ls) tv
atomMap f n@(Node _ _ _) = f n
atomMapM :: Monad m => (Atom -> m Atom) -> Atom -> m Atom
atomMapM f (Link t ls tv) = do
nls <- (mapM (atomMapM f) ls)
f $ Link t nls tv
atomMapM f n@(Node _ _ _) = f n
atomFold :: (a -> Atom -> a) -> a -> Atom -> a
atomFold f v a@(Link t ls tv) = f (foldl (atomFold f) v ls) a
atomFold f v a@(Node _ _ _) = f v a
atomElem :: Atom -> Atom -> Bool
atomElem n@(Node _ _ _) a@(Node _ _ _) = n == a
atomElem n@(Node _ _ _) a@(Link _ _ _) =
atomFold (\b a -> a == n || b) False a
atomElem n@(Link _ _ _) a@(Node _ _ _) = False
atomElem n@(Link _ _ _) a@(Link _ _ _) =
atomFold (\ b a -> a == n || b) False a
atomGetAllNodes :: Atom -> [Atom]
atomGetAllNodes n@(Node _ _ _) = [n]
atomGetAllNodes (Link _ ls _) = concatMap atomGetAllNodes ls
nodeName :: Atom -> String
nodeName (Node _ n _) = n
nodeName (Link _ _ _) = error "nodeName expects a Node."
atomType :: Atom -> String
atomType (Node t _ _) = t
atomType (Link t _ _) = t
|
inflector/atomspace
|
opencog/haskell/OpenCog/AtomSpace/Utils.hs
|
agpl-3.0
| 3,706
| 0
| 19
| 1,146
| 1,524
| 791
| 733
| 79
| 6
|
{-# LANGUAGE TemplateHaskell, RankNTypes, TypeOperators, DataKinds,
PolyKinds, TypeFamilies, GADTs, StarIsType #-}
module RAE_T32a where
import Data.Kind
data family Sing (k :: *) :: k -> *
data TyArr' (a :: *) (b :: *) :: *
type TyArr (a :: *) (b :: *) = TyArr' a b -> *
type family (a :: TyArr k1 k2) @@ (b :: k1) :: k2
data TyPi' (a :: *) (b :: TyArr a *) :: *
type TyPi (a :: *) (b :: TyArr a *) = TyPi' a b -> *
type family (a :: TyPi k1 k2) @@@ (b :: k1) :: k2 @@ b
$(return [])
data MkStar (p :: *) (x :: TyArr' p *)
type instance MkStar p @@ x = *
$(return [])
type instance (MkStar p) @@ x = *
$(return [])
foo :: forall p x . MkStar p @@ x
foo = undefined
data Sigma (p :: *) (r :: TyPi p (MkStar p)) :: * where
Sigma ::
forall (p :: *) (r :: TyPi p (MkStar p)) (a :: p) (b :: r @@@ a).
Sing * p -> Sing (TyPi p (MkStar p)) r -> Sing p a -> Sing (r @@@ a) b
-> Sigma p r
$(return [])
data instance Sing Sigma (Sigma p r) x where
SSigma ::
forall (p :: *) (r :: TyPi p (MkStar p)) (a :: p) (b :: r @@@ a)
(sp :: Sing * p) (sr :: Sing (TyPi p (MkStar p)) r) (sa :: Sing p a)
(sb :: Sing (r @@@ a) b).
Sing (Sing (r @@@ a) b) sb ->
Sing (Sigma p r) ('Sigma sp sr sa sb)
-- I (RAE) believe this last definition is ill-typed.
|
sdiehl/ghc
|
testsuite/tests/printer/Ppr040.hs
|
bsd-3-clause
| 1,296
| 2
| 13
| 356
| 663
| 379
| 284
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.Hpc
-- Copyright : Thomas Tuegel 2011
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This module provides an library interface to the @hpc@ program.
module Distribution.Simple.Program.Hpc
( markup
, union
) where
import Distribution.ModuleName
import Distribution.Simple.Program.Run
import Distribution.Simple.Program.Types
import Distribution.Text
import Distribution.Simple.Utils
import Distribution.Verbosity
import Distribution.Version
-- | Invoke hpc with the given parameters.
--
-- Prior to HPC version 0.7 (packaged with GHC 7.8), hpc did not handle
-- multiple .mix paths correctly, so we print a warning, and only pass it the
-- first path in the list. This means that e.g. test suites that import their
-- library as a dependency can still work, but those that include the library
-- modules directly (in other-modules) don't.
markup :: ConfiguredProgram
-> Version
-> Verbosity
-> FilePath -- ^ Path to .tix file
-> [FilePath] -- ^ Paths to .mix file directories
-> FilePath -- ^ Path where html output should be located
-> [ModuleName] -- ^ List of modules to exclude from report
-> IO ()
markup hpc hpcVer verbosity tixFile hpcDirs destDir excluded = do
hpcDirs' <- if withinRange hpcVer (orLaterVersion version07)
then return hpcDirs
else do
warn verbosity $ "Your version of HPC (" ++ display hpcVer
++ ") does not properly handle multiple search paths. "
++ "Coverage report generation may fail unexpectedly. These "
++ "issues are addressed in version 0.7 or later (GHC 7.8 or "
++ "later)."
++ if null droppedDirs
then ""
else " The following search paths have been abandoned: "
++ show droppedDirs
return passedDirs
runProgramInvocation verbosity
(markupInvocation hpc tixFile hpcDirs' destDir excluded)
where
version07 = Version [0, 7] []
(passedDirs, droppedDirs) = splitAt 1 hpcDirs
markupInvocation :: ConfiguredProgram
-> FilePath -- ^ Path to .tix file
-> [FilePath] -- ^ Paths to .mix file directories
-> FilePath -- ^ Path where html output should be
-- located
-> [ModuleName] -- ^ List of modules to exclude from
-- report
-> ProgramInvocation
markupInvocation hpc tixFile hpcDirs destDir excluded =
let args = [ "markup", tixFile
, "--destdir=" ++ destDir
]
++ map ("--hpcdir=" ++) hpcDirs
++ ["--exclude=" ++ display moduleName
| moduleName <- excluded ]
in programInvocation hpc args
union :: ConfiguredProgram
-> Verbosity
-> [FilePath] -- ^ Paths to .tix files
-> FilePath -- ^ Path to resultant .tix file
-> [ModuleName] -- ^ List of modules to exclude from union
-> IO ()
union hpc verbosity tixFiles outFile excluded =
runProgramInvocation verbosity
(unionInvocation hpc tixFiles outFile excluded)
unionInvocation :: ConfiguredProgram
-> [FilePath] -- ^ Paths to .tix files
-> FilePath -- ^ Path to resultant .tix file
-> [ModuleName] -- ^ List of modules to exclude from union
-> ProgramInvocation
unionInvocation hpc tixFiles outFile excluded =
programInvocation hpc $ concat
[ ["sum", "--union"]
, tixFiles
, ["--output=" ++ outFile]
, ["--exclude=" ++ display moduleName
| moduleName <- excluded ]
]
|
tolysz/prepare-ghcjs
|
spec-lts8/cabal/Cabal/Distribution/Simple/Program/Hpc.hs
|
bsd-3-clause
| 3,999
| 0
| 18
| 1,289
| 575
| 318
| 257
| 70
| 3
|
-- Kind error message
module ShouldFail where
data T k = T (k Int)
g :: T Int
g x = x
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_fail/tcfail160.hs
|
bsd-3-clause
| 89
| 0
| 8
| 25
| 37
| 21
| 16
| 4
| 1
|
module LightSpherical where
import qualified Color3
import qualified Position3
import qualified Spaces
data T = LS {
color :: Color3.T,
intensity :: Float,
origin :: Position3.T Spaces.Eye,
radius :: Float,
falloff :: Float
} deriving (Eq, Ord, Show)
|
io7m/r2
|
com.io7m.r2.documentation/src/main/resources/com/io7m/r2/documentation/haskell/LightSpherical.hs
|
isc
| 275
| 0
| 10
| 62
| 79
| 49
| 30
| 11
| 0
|
module Language.EBNF.FormatText where
import Language.EBNF.Types
import Data.List
fmtGrammar :: Grammar -> String
fmtGrammar g = desc ++ intercalate "\n" (map (fmtVar "") (gVars g))
where desc = if null s then "" else comment s
where s = gDesc g
comment = ("\n\n" ++ ) . unlines . map (++"-- ") . lines
fmtVar :: String -> Var -> String
fmtVar ind v = desc_str ++ ind ++ v_str ++ eq_str ++ " " ++ expr_str ++ where_str
where desc_str
| null desc = ""
| otherwise = unlines (map ((ind ++ "-- ")++) (lines desc))
where desc = vDesc v
v_str = vName v
eq_str = " ="
expr_str =
case vExpr v of
(ExprAlts _ [(e,c)])
-- foo = bar baz qux
| length short_expr < cols_left -> short_expr
where short_expr = fmtExpr e ++ comment c
e@(ExprAlts _ as)
-- >> [ind]foo = bar baz | qux? biz+ | doz
| all (null . snd) as &&
length short_expr < cols_left -> short_expr
where short_expr = fmtExpr e
e@(ExprAlts _ as)
-- Have comments on some of these or they are too long;
-- expand alts on to lines
--
-- >> [ind]foo =
-- >> [ind] bar baz -- comment
-- >> [ind] | ...
| otherwise -> "\n" ++
ind ++ " " ++ fmtExpr e0 ++ comment c0 ++ "\n" ++
intercalate "\n" (map fmtAlt (tail as))
where (e0,c0) = head as
fmtAlt (e,c) = ind ++ " | " ++ fmtExpr e ++ comment c
e -> fmtExpr e
cols_left :: Int
cols_left = 80 - (length ind + length v_str + 1 + length eq_str + 1) -- "var = "
where_str
-- [ind]foo =
-- [ind] bar baz -- comment
-- [ind] | ...
-- >> [ind] where ...
-- >> [ind]
| null (vWhere v) = ""
| otherwise =
"\n" ++ ind ++ " " ++ "where\n" ++
intercalate "\n" (map (fmtVar (ind ++ " ")) (vWhere v))
comment "" = ""
comment s = " -- " ++ s
fmtExpr :: Expr -> String
fmtExpr (ExprAlts _ as) = intercalate (" | ") (map (fmtExpr . fst) as)
fmtExpr (ExprSeq _ es) = intercalate " " (map fmtExpr es)
fmtExpr (ExprOpt _ e) = fmtExpr e ++ "?"
fmtExpr (ExprMany _ e) = fmtExpr e ++ "*"
fmtExpr (ExprPos _ e) = fmtExpr e ++ "+"
fmtExpr (ExprAs _ t e) = "[" ++ t ++ "]" ++ fmtExpr e
fmtExpr (ExprGrp _ e) = "(" ++ fmtExpr e ++ ")"
fmtExpr (ExprVar _ v) = v
fmtExpr (ExprLit _ l) = "'" ++ l ++ "'"
fmtExpr (ExprPatt _ l) = "@" ++ escP l ++ "@"
where escP [] = []
escP ('@':cs) = "\\@" ++ escP cs
escP (c:cs) = c:escP cs
fmtExpr (ExprDots _) = "..."
|
trbauer/ebnf
|
Language/EBNF/FormatText.hs
|
mit
| 2,843
| 0
| 17
| 1,096
| 995
| 503
| 492
| 56
| 5
|
module Name where
import Text.PrettyPrint.ANSI.Leijen
type Name = String
newtype ModName = ModName { getModName :: Name }
instance Pretty ModName where
pretty = blue . text . getModName
|
pxqr/algorithm-wm
|
src/Name.hs
|
mit
| 192
| 0
| 7
| 35
| 51
| 32
| 19
| 6
| 0
|
--------------------------------------------------------------------
-- |
-- Module : Network.Curl.Debug
-- Copyright : (c) Galois, Inc. 2008-2009
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <sof@galois.com>
-- Stability : provisional
-- Portability:
--
-- Debug hooks
module Network.Shpider.Curl.Debug (debug) where
import System.IO
debugging :: Bool
debugging = False
debug :: String -> IO ()
debug msg
| debugging = putStrLn ("DEBUG: " ++ msg) >> hFlush stdout
| otherwise = return ()
|
elginer/shpider
|
Network/Shpider/Curl/Debug.hs
|
mit
| 518
| 0
| 9
| 93
| 98
| 56
| 42
| 8
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Y2015.Bench where
import Criterion (Benchmark, bench, bgroup, nf, whnf)
import Criterion.Main (env)
import Control.Monad
import Data.ByteString (pack)
import Data.ByteString.Char8 (unpack)
import Data.Word (Word8)
import System.Random.MWC
import Y2015
entropy :: IO String
entropy = do
rand <- withSystemRandom . asGenIO $ \ gen ->
replicateM 1000 $ uniformR (c '(', c ')') gen
return $ unpack $ pack rand
where c :: Char -> Word8
c = fromIntegral . fromEnum
benchmarks :: Benchmark
benchmarks =
env entropy $ \levels ->
bgroup "Y2015"
[ bgroup "Day 1"
[ bench "simple" $ nf level "()((()(())))(((((((())))))))(()))))))"
, bench "large" $ nf level (Prelude.take 100 levels)
, bench "huge" $ nf level levels
]
, bgroup "Day 22"
[ bench "simple" $ whnf (testSpellBattle False)
(unlines ["Hit Points: 13", "Damage: 8"])
, bench "alternate" $ whnf (testSpellBattle False)
(unlines ["Hit Points: 14", "Damage: 8"])
]
, bgroup "Day 24"
[ bgroup "idealEntanglement"
[ bench "small" $ whnf (idealEntanglement 3)
(unlines $ map show [1, 3, 2, 2, 4])
, bench "large" $ whnf (idealEntanglement 3)
(unlines $ map show $ [1..5] ++ [7..11])
]
, bgroup "idealEntanglementOptimized"
[ bench "small" $ whnf (idealEntanglementOptimized 3)
(unlines $ map show [1, 3, 2, 2, 4])
, bench "large" $ whnf (idealEntanglementOptimized 3)
(unlines $ map show $ [1..5] ++ [7..11])
]
]
]
|
tylerjl/adventofcode
|
benchmark/Y2015/Bench.hs
|
mit
| 1,916
| 0
| 19
| 736
| 555
| 293
| 262
| 41
| 1
|
module Vals where
import Control.Monad.Error
import Text.ParserCombinators.Parsec hiding (spaces)
import Text.ParseErrorEq ()
import Data.IORef
import System.IO
data LispVal = Atom Char | List [LispVal] | DottedList [LispVal] LispVal |
Number Integer | String String | Bool Bool |
PrimitiveFunc Char |
Func { params :: [Char], vararg :: (Maybe Char),
body :: [LispVal], closure :: Env } |
IOFunc Char |
Port Handle deriving Eq
unwordsList :: [LispVal] -> String
unwordsList = unwords . map showVal
valToChar :: LispVal -> Char
valToChar (Atom name) = name
valsToChars :: [LispVal] -> [Char]
valsToChars vals = map valToChar vals
showVal :: LispVal -> String
showVal (String str) = "\"" ++ str ++ "\""
showVal (Atom name) = show name
showVal (Number i) = show i
showVal (Bool True) = "#"
showVal (Bool False) = "~"
showVal (List contents) = "(" ++ unwordsList contents ++ ")"
showVal (DottedList hd tl) = "(" ++ unwordsList hd ++ " . " ++ showVal tl ++ ")"
showVal (PrimitiveFunc name) = "<primitive" ++ show name ++ ">"
showVal (Func {params = args, vararg = varargs, body = _, closure = _}) =
"(\\ (" ++ unwords (map show args) ++
(case varargs of
Nothing -> ""
Just arg -> " . " ++ show arg) ++ ") ...)"
showVal (Port h) = "<IO port" ++ show h ++ ">"
showVal (IOFunc name) = "<IO primitive" ++ show name ++ ">"
instance Show LispVal where show = showVal
data LispError = NumArgs Integer [LispVal]
| TypeMismatch String LispVal
| Parser ParseError
| BadSpecialForm String LispVal
| NotFunction String String
| UnboundVar String String
| Default String deriving Eq
showError :: LispError -> String
showError (UnboundVar message varname) = message ++ ": " ++ varname
showError (BadSpecialForm message form) = message ++ ": " ++ show form
showError (NotFunction message func) = message ++ ": " ++ show func
showError (NumArgs expected found) = "Expected " ++ show expected
++ " args; found values " ++ unwordsList found
showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected
++ ", found " ++ show found
showError (Parser parseErr) = "Parse error at " ++ show parseErr
instance Show LispError where show = showError
instance Error LispError where
noMsg = Default "An error has occurred"
strMsg = Default
type ThrowsError = Either LispError
trapError :: (Show e, MonadError e m) => m String -> m String
trapError action = catchError action (return . show)
extractValue :: ThrowsError a -> a
extractValue (Right val) = val
type Env = IORef [(Char, IORef LispVal)]
type IOThrowsError = ErrorT LispError IO
liftThrows :: ThrowsError a -> IOThrowsError a
liftThrows (Left err) = throwError err
liftThrows (Right val) = return val
runIOThrows :: IOThrowsError String -> IO String
runIOThrows action = runErrorT (trapError action) >>= return . extractValue
isBound :: Env -> Char -> IO Bool
isBound envRef var = readIORef envRef >>= return . maybe False (const True) . lookup var
getVar :: Env -> Char -> IOThrowsError LispVal
getVar envRef var = do
env <- liftIO $ readIORef envRef
maybe (throwError $ UnboundVar "Unbound variable" $ show var)
(liftIO . readIORef)
(lookup var env)
setVar :: Env -> Char -> LispVal -> IOThrowsError LispVal
setVar envRef var value = do env <- liftIO $ readIORef envRef
maybe (throwError $ UnboundVar "Setting an unbound variable" $ show var)
(liftIO . (flip writeIORef value))
(lookup var env)
return value
defineVar :: Env -> Char -> LispVal -> IOThrowsError LispVal
defineVar envRef var value = do
alreadyDefined <- liftIO $ isBound envRef var
if alreadyDefined
then setVar envRef var value >> return value
else liftIO $ do
valueRef <- newIORef value
env <- readIORef envRef
writeIORef envRef ((var, valueRef) : env)
return value
bindVars :: Env -> [(Char, LispVal)] -> IO Env
bindVars envRef bindings = readIORef envRef >>= extendEnv bindings >>= newIORef
where extendEnv bs env = liftM (++ env) (mapM addBinding bs)
addBinding (var, value) = do ref <- newIORef value
return (var, ref)
|
eligottlieb/chaitin
|
src/Vals.hs
|
mit
| 4,552
| 12
| 14
| 1,277
| 1,509
| 768
| 741
| 97
| 2
|
import System.Console.ANSI
data RelationType = Enemy | Friend | Unknown | Neutral | Player deriving(Show)
data EntityType = EntityType{entitySym::Char
,relation::RelationType
,hp::Int
,mp::Int
,dmg::Int} deriving(Show)
data WallType = WallType {wallSym::Char
,breackable :: Bool
} deriving(Show)
data RoadType = RoadType {roadSym::Char
, walkable :: Bool
} deriving(Show)
data DoorType = DoorType {doorSym::Char
, opened :: Bool
} deriving(Show)
data PlantType = PlantType {plantSym::Char
, destroyable :: Bool
} deriving(Show)
data Slot = Entity EntityType | Wall WallType | Road RoadType | Door DoorType | Plant PlantType deriving(Show)
cDefault,cBlack,cRed,cGreen,cYellow,cBlue,cMagenta,cCyan,cWhite,cPrefix,cSuffix :: String
cDefault = "0"
cBlack = "30"
cRed = "31"
cGreen = "32"
cYellow = "33"
cBlue = "34"
cMagenta = "35"
cCyan = "36"
cWhite = "37"
cPrefix = "\x1b["
cSuffix = "m"
colorProduct :: String -> String
colorProduct c = cPrefix ++ c ++ cSuffix
snake,goblin,rat,bat,player :: EntityType
snake = EntityType 'S' Enemy 10 10 1
goblin = EntityType 'g' Enemy 5 0 5
rat = EntityType 'r' Enemy 3 0 1
bat = EntityType 'b' Enemy 7 0 2
player = EntityType '@' Player 10 10 2
type Table = [[Slot]]
getSym :: Slot -> Char
getSym slot = case slot of
Entity e -> entitySym e
Wall w -> wallSym w
Road r -> roadSym r
Door d -> doorSym d
Plant p -> plantSym p
produceTableFrom :: [String] -> Table
produceTableFrom = map produceFromStr
where produceFromStr = map sym
where sym s' = case s' of
'#' -> Wall (WallType s' False)
'W' -> Wall (WallType s' True)
'.' -> Road (RoadType s' True)
',' -> Road (RoadType s' False)
'g' -> Entity goblin
'S' -> Entity snake
'r' -> Entity rat
'b' -> Entity bat
'@' -> Entity player
'Y' -> Plant $ PlantType s' False
_ -> Wall $ WallType s' False
colorizeSlot :: Slot -> String
colorizeSlot (Entity e) = case relation e of
Friend -> colorProduct cGreen
Player -> colorProduct cMagenta
Enemy -> colorProduct cRed
Unknown -> colorProduct cYellow
Neutral -> colorProduct cBlue
colorizeSlot (Wall w) = colorProduct cDefault
colorizeSlot (Road r) = colorProduct cDefault
colorizeSlot (Door d) = colorProduct cDefault
colorizeSlot (Plant p) = colorProduct cGreen
reduceTable2Strs :: Table -> [String]
reduceTable2Strs = map $ foldr ((++) . (\ y -> colorizeSlot y ++ [getSym y])) (colorProduct cDefault)
reduceStrs :: [String] -> String
reduceStrs = foldr (\ x y -> x ++ ('\n' : y)) "\n"
visibleRadius :: Int
visibleRadius = 5
getViewedChunk :: Table -> Int -> Int -> Table
getViewedChunk table x y = map (cut y) (cut x table)
where cut w z = take (2 * visibleRadius + 1) (drop (w - visibleRadius - 1) z)
main :: IO()
main = do
putStrLn $ reduceStrs $ reduceTable2Strs (getViewedChunk (produceTableFrom (map (\x ->map (\_->if x `mod` 2 == 0 then '.' else 'Y') (show x)) ([10000000000000000..10000000000001000]::[Integer]))) 13 11)
print player
|
grachyov/Rogue-like-game-experiments
|
main.hs
|
mit
| 3,491
| 0
| 22
| 1,091
| 1,176
| 633
| 543
| 87
| 11
|
{-# LANGUAGE RankNTypes #-}
-- | the prelude for the whole system: generally useful stuff
--
-- all the included and reexported modules and
-- the functions declared in this module are
-- used within the whole system
module PPL2.Prelude
( module PPL2.Prelude
, module Control.Lens
, module Control.Monad
, module Control.Monad.Except
, module Data.Bifunctor
, module Data.Either
, module Data.Maybe
, module Data.Monoid
, module Data.Word
)
where
import Control.Lens
import Control.Monad
import Control.Monad.Except
import Data.Bifunctor
import Data.Maybe hiding (fromJust)
import Data.Either
import Data.Monoid
import Data.Word (Word)
-- ----------------------------------------
--
-- construct pais with an infix op to avoid (,)
infixr 1 .->
(.->) :: a -> b -> (a, b)
x .-> y = (x, y)
-- ----------------------------------------
--
-- collect all element, which occur
-- more than once in a list
-- the result doesn't contain duplicates
dup :: Eq a => [a] -> [a]
dup = reverse . dup' []
where
dup' acc [] = acc
dup' acc (x : xs)
| x `elem` xs
&&
x `notElem` acc = dup' (x : acc) xs
| otherwise = dup' acc xs
-- ----------------------------------------
|
UweSchmidt/ppl2
|
src/PPL2/Prelude.hs
|
mit
| 1,294
| 0
| 12
| 327
| 288
| 173
| 115
| 30
| 2
|
module Language.Astview.Languages.Python (python) where
import Prelude hiding (span)
import Language.Astview.Language
import Language.Astview.DataTree (dataToAstIgnoreByExample)
import Language.Python.Version3.Parser(parseModule)
import qualified Language.Python.Common.SrcLocation as Py
import Data.Generics (Data,extQ)
import Data.Generics.Zipper(toZipper,down,query)
python :: Language
python = Language "Python" "Python" [".py"] parsePy
parsePy :: String -> Either Error Ast
parsePy s = case parseModule s [] of
Right (m,_) -> Right $ dataToAstIgnoreByExample getSrcLoc
(undefined::Py.SrcSpan)
m
Left e -> Left $ ErrMessage (show e)
getSrcLoc :: Data t => t -> Maybe SrcSpan
getSrcLoc t = down (toZipper t) >>= query (def `extQ` atSpan) where
def :: a -> Maybe SrcSpan
def _ = Nothing
atSpan :: Py.SrcSpan -> Maybe SrcSpan
atSpan (Py.SpanPoint _ r c) = Just $ position r c
atSpan (Py.SpanCoLinear _ r sc ec) = Just $ linear r sc ec
atSpan (Py.SpanMultiLine _ sr sc er ec) = Just $ span sr sc er ec
atSpan (Py.SpanEmpty) = Nothing
|
jokusi/Astview
|
src/core/Language/Astview/Languages/Python.hs
|
mit
| 1,199
| 0
| 11
| 312
| 402
| 216
| 186
| 25
| 4
|
module GiveYouAHead.Clean
(
clean
) where
import System.Process(createProcess,shell,waitForProcess)
import Macro.MacroIO(getMacroFromFile)
import Macro.MacroReplace(splitMacroDef,toText)
clean :: IO()
clean = do
t <- getMacroFromFile "clean"
(_,_,_,hp) <- createProcess $ shell $ concatMap show $ toText $ splitMacroDef t
_ <- waitForProcess hp
putStrLn "Cleaned!"
|
Qinka/GiveYouAHead
|
lib/GiveYouAHead/Clean.hs
|
mit
| 448
| 0
| 11
| 124
| 132
| 70
| 62
| 12
| 1
|
-- Adapted from ANUPlot version by Clem Baker-Finch
module Main where
import World
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Simulate
import System.Random
-- varying prng sequence
main
= do gen <- getStdGen
simulate (InWindow "Lifespan" (800, 600) (10, 10))
(greyN 0.1) -- background color
2 -- number of steps per second
(genesis' gen) -- initial world
render -- function to convert world to a Picture
evolve -- function to step the world one iteration
|
gscalzo/HaskellTheHardWay
|
gloss-try/gloss-master/gloss-examples/picture/Lifespan/Main.hs
|
mit
| 530
| 10
| 8
| 129
| 103
| 61
| 42
| 13
| 1
|
import Data.Digits
--import Data.List
--import qualified Data.Map as Map
import Control.Monad.State.Strict
import qualified Data.IntMap.Strict as IntMap
import Data.IORef
import Debug.Trace
-- highest step possible
cacheSize = 7 * 9^2
step :: Int -> Int
step n = do {-trace ("[n=" ++ show n ++ "]")-} (sum $ map (^2) (digits 10 n))
endsWith89 :: IORef (IntMap.IntMap Bool) -> Int -> IO Bool
endsWith89 _ 1 = pure False
endsWith89 _ 89 = pure True
endsWith89 ref n = do
m <- readIORef ref
case IntMap.lookup n m of
(Just v) -> pure v
Nothing -> do
v <- endsWith89 ref (step n)
writeIORef ref (IntMap.insert n v m)
pure v
--a chain starting at n
chain n =
if (n == 89 || n == 1)
then [n]
else n : chain (step n)
--answerI = length $ filter (\i -> (last (chain i)) == 89) [1..10^7-1]
--answerE = length $ filter memoized_endOfChain [1..10^7-1]
main :: IO ()
main = do
ref <- newIORef (IntMap.empty)-- :: IntMap.IntMap Bool)
answer <- length <$> filterM (endsWith89 ref) [1..9999999]
print answer
--readIORef ref >>= print
|
gumgl/project-euler
|
92/92.hs
|
mit
| 1,114
| 0
| 15
| 277
| 360
| 184
| 176
| 28
| 2
|
module Unison.Test.Util.Bytes where
import EasyTest
import Control.Monad
import Data.List (foldl')
import qualified Unison.Util.Bytes as Bytes
import qualified Data.ByteString as BS
test :: Test ()
test = scope "util.bytes" . tests $ [
scope "empty ==" . expect $ Bytes.empty == Bytes.empty,
scope "empty `compare`" . expect $ Bytes.empty `compare` Bytes.empty == EQ,
scope "==" . expect $
Bytes.fromWord8s [0,1,2,3,4,5] <> Bytes.fromWord8s [6,7,8,9]
==
Bytes.fromWord8s [0,1,2,3,4,5,6,7,8,9],
scope "at" $ do
expect' (Bytes.at 0 (Bytes.fromWord8s [77,13,12]) == Just 77)
expect' (Bytes.at 0 (Bytes.fromWord8s []) == Nothing)
ok,
scope "at.cornerCases" $ do
let b = Bytes.drop 3 $ Bytes.fromWord8s [77,13,12] <> Bytes.fromWord8s [9,10,11]
expect' (Bytes.at 0 b == Just 9)
expect' (Bytes.at 0 (mempty <> Bytes.fromWord8s [1,2,3]) == Just 1)
ok,
scope "consistency with ByteString" $ do
forM_ [(1::Int)..100] $ \_ -> do
n <- int' 0 50
m <- int' 0 50
k <- int' 0 (n + m)
o <- int' 0 50
b1 <- BS.pack <$> replicateM n word8
b2 <- BS.pack <$> replicateM m word8
b3 <- BS.pack <$> replicateM o word8
let [b1s, b2s, b3s] = Bytes.fromArray <$> [b1, b2, b3]
scope "associtivity" . expect' $
b1s <> (b2s <> b3s) == (b1s <> b2s) <> b3s
scope "<>" . expect' $
Bytes.toArray (b1s <> b2s <> b3s) == b1 <> b2 <> b3
scope "Ord" . expect' $
(b1 <> b2 <> b3) `compare` b3 ==
(b1s <> b2s <> b3s) `compare` b3s
scope "take" . expect' $
Bytes.toArray (Bytes.take k (b1s <> b2s)) == BS.take k (b1 <> b2)
scope "drop" . expect' $
Bytes.toArray (Bytes.drop k (b1s <> b2s)) == BS.drop k (b1 <> b2)
scope "at" $
let bs = b1s <> b2s <> b3s
b = b1 <> b2 <> b3
in forM_ [0 .. (BS.length b - 1)] $ \ind ->
expect' $ Just (BS.index b ind) == Bytes.at ind bs
ok,
scope "lots of chunks" $ do
forM_ [(0::Int)..100] $ \i -> do
n <- int' 0 50
k <- int' 0 i
chunks <- replicateM n (replicateM k word8)
let b1 = foldMap Bytes.fromWord8s chunks
b2 = foldr (<>) mempty (Bytes.fromWord8s <$> chunks)
b3 = foldl' (<>) mempty (Bytes.fromWord8s <$> chunks)
b = BS.concat (BS.pack <$> chunks)
expect' $ b1 == b2 && b2 == b3
expect' $ Bytes.toArray b1 == b
expect' $ Bytes.toArray b2 == b
expect' $ Bytes.toArray b3 == b
ok
]
|
unisonweb/platform
|
parser-typechecker/tests/Unison/Test/Util/Bytes.hs
|
mit
| 2,513
| 0
| 24
| 729
| 1,184
| 598
| 586
| 64
| 1
|
{-# LANGUAGE FlexibleContexts #-}
module Oden.Backend.Go (
GoBackend(..),
prelude,
genPackage
) where
import Control.Monad.Except
import Control.Monad.Reader
import Data.List (sortOn, find, intercalate)
import Data.Maybe (maybeToList)
import qualified Data.Set as Set
import Text.PrettyPrint.Leijen (renderPretty, displayS, pretty)
import System.FilePath
import qualified Oden.Go.AST as AST
import qualified Oden.Go.Identifier as GI
import qualified Oden.Go.Type as GT
import Oden.Go.Pretty ()
import Oden.Backend
import Oden.Compiler.Monomorphization
import Oden.Core
import Oden.Core.Operator
import Oden.Identifier
import Oden.Metadata
import Oden.QualifiedName (QualifiedName(..))
import Oden.SourceInfo hiding (fileName)
import qualified Oden.Type.Monomorphic as Mono
type Codegen = ReaderT MonomorphedPackage (Except CodegenError)
newtype GoBackend = GoBackend FilePath
isUniverseTypeConstructor :: String -> Mono.Type -> Bool
isUniverseTypeConstructor expected (Mono.TCon _ (FQN [] (Identifier actual))) =
actual == expected
isUniverseTypeConstructor _ _ = False
replaceIdentifierPart :: Char -> String
replaceIdentifierPart c = case c of
'-' -> "_DASH_"
'\'' -> "_PRIM_"
'!' -> "_BANG_"
'$' -> "_DLLR_"
'&' -> "_AMPR_"
'*' -> "_STAR_"
'+' -> "_PLUS_"
'<' -> "_LT_"
'=' -> "_EQ_"
'>' -> "_GT_"
'?' -> "_QST_"
'^' -> "_CRCM_"
'|' -> "_PIPE_"
'~' -> "_TLDE_"
_ -> [c]
safeName :: String -> GI.Identifier
safeName = GI.Identifier . concatMap replaceIdentifierPart
genIdentifier :: Identifier -> Codegen GI.Identifier
genIdentifier (Identifier s) = return $ safeName s
genType :: Mono.Type -> Codegen GT.Type
genType t@Mono.TCon{}
| isUniverseTypeConstructor "unit" t = return $ GT.Struct []
| isUniverseTypeConstructor "int" t = return $ GT.Basic (GI.Identifier "int") False
| isUniverseTypeConstructor "bool" t = return $ GT.Basic (GI.Identifier "bool") False
| isUniverseTypeConstructor "string" t = return $ GT.Basic (GI.Identifier "string") False
| otherwise = throwError (UnexpectedError $ "Unsupported type constructor: " ++ show t)
genType (Mono.TTuple _ f s r) =
GT.Struct <$> zipWithM genTupleField [0..] (f:s:r)
where
genTupleField :: Int -> Mono.Type -> Codegen GT.StructField
genTupleField n t = GT.StructField (GI.Identifier ("_" ++ show n)) <$> genType t
genType (Mono.TNoArgFn _ f) = do
fc <- genType f
return (GT.Signature Nothing (GT.Parameters [] False) (GT.Returns [fc]))
genType (Mono.TFn _ d r) = do
dc <- genType d
rc <- genType r
return (GT.Signature Nothing (GT.Parameters [dc] False) (GT.Returns [rc]))
genType (Mono.TSlice _ t) =
GT.Slice <$> genType t
genType (Mono.TForeignFn _ isVariadic ps rs) = do
ps' <- mapM genType ps
rs' <- mapM genType rs
return (GT.Signature Nothing (GT.Parameters ps' isVariadic) (GT.Returns rs'))
genType (Mono.TRecord _ row) = genType row
genType (Mono.TNamed _ _ t) = genType t
genType Mono.REmpty{} = return $ GT.Struct []
genType row@Mono.RExtension{} = do
let fields = sortOn fst (Mono.rowToList row)
GT.Struct <$> mapM genField fields
where genField (Identifier name, t) = GT.StructField (safeName name) <$> genType t
genBinaryOperator :: BinaryOperator -> AST.BinaryOperator
genBinaryOperator op = case op of
Add -> AST.Sum
Subtract -> AST.Difference
Multiply -> AST.Product
Divide -> AST.Quotient
Equals -> AST.EQ
Concat -> AST.Sum
LessThan -> AST.LT
GreaterThan -> AST.GT
LessThanEqual -> AST.LTE
GreaterThanEqual -> AST.GTE
And -> AST.And
Or -> AST.Or
genUnaryOperator :: UnaryOperator -> AST.UnaryOperator
genUnaryOperator Negative = AST.UnaryNegation
genUnaryOperator Positive = AST.UnaryPlus
genUnaryOperator Not = AST.Not
genRange :: Range Mono.Type -> Codegen AST.SliceExpression
genRange (Range e1 e2) = AST.ClosedSlice <$> genExpr e1 <*> genExpr e2
genRange (RangeFrom e) = AST.LowerBoundSlice <$> genExpr e
genRange (RangeTo e) = AST.UpperBoundSlice <$> genExpr e
-- | Generates a call to an foreign function.
genRawForeignFnApplication :: Expr Mono.Type -> [Expr Mono.Type] -> Codegen AST.PrimaryExpression
genRawForeignFnApplication f args =
case typeOf f of
Mono.TForeignFn _ True _ _ -> do
let nonVariadicArgs = init args
slice = last args
fc <- genPrimaryExpression f
args' <- map AST.Argument <$> mapM genExpr nonVariadicArgs
variadicArg <- AST.VariadicSliceArgument <$> genExpr slice
return (AST.Application fc (args' ++ [variadicArg]))
_ -> AST.Application <$> genPrimaryExpression f
<*> (map AST.Argument <$> mapM genExpr args)
operandName :: GI.Identifier -> AST.Expression
operandName = AST.Expression . AST.Operand . AST.OperandName
literalExpr :: AST.Literal -> AST.Expression
literalExpr = AST.Expression . AST.Operand . AST.Literal
-- | Generates an anonymous function that will take parameters of the specified
-- types and return a tuple containing those values.
genTupleWrapper :: (Mono.Type, Mono.Type, [Mono.Type]) -> Codegen AST.PrimaryExpression
genTupleWrapper (fstType, sndType, restTypes) = do
let types = fstType : sndType : restTypes
names = take (length types) (map (GI.Identifier . ("_" ++) . show) [(0 :: Int)..])
paramTypes <- mapM genType types
-- TODO: Create this type out of 'names' and AST constructors directly, don't
-- genType to get it.
tupleType <- genType (Mono.TTuple (Metadata Missing) fstType sndType restTypes)
let params = zipWith AST.FunctionParameter names paramTypes
tupleLiteral = AST.Expression
(AST.Operand
(AST.Literal
(AST.CompositeLiteral
tupleType
(AST.LiteralValueElements
(map (AST.UnkeyedElement . operandName) names)))))
return (AST.Operand
(AST.Literal
(AST.FunctionLiteral
(AST.FunctionSignature params [tupleType])
(AST.Block [AST.ReturnStmt [tupleLiteral]]))))
-- | Generates a call to a foreign function with multiple return values,
-- returning a tuple.
genTupleWrappedForeignFnApplication :: Expr Mono.Type -- the function expr
-> [Expr Mono.Type] -- function application arguments
-> (Mono.Type, Mono.Type, [Mono.Type]) -- tuple types
-> Codegen AST.Expression
genTupleWrappedForeignFnApplication f args returnTypes = do
fnCall <- genRawForeignFnApplication f args
wrapperFn <- genTupleWrapper returnTypes
return (AST.Expression
(AST.Application
wrapperFn
[AST.Argument (AST.Expression fnCall)]))
emptyStructLiteral :: AST.Expression
emptyStructLiteral =
literalExpr
(AST.CompositeLiteral
(GT.Struct [])
(AST.LiteralValueElements []))
-- | Wraps the provided code in a function that returns unit
voidToUnitWrapper :: AST.Expression -> AST.Expression
voidToUnitWrapper expr =
AST.Expression
(AST.Application
(AST.Operand
(AST.Literal
(AST.FunctionLiteral
(AST.FunctionSignature [] [GT.Struct []])
(AST.Block [AST.SimpleStmt (AST.ExpressionStmt expr),
AST.ReturnStmt [emptyStructLiteral]]))))
[])
asPrimaryExpression :: AST.Expression -> AST.PrimaryExpression
asPrimaryExpression (AST.Expression primaryExpr) = primaryExpr
asPrimaryExpression nonPrimary = AST.Operand (AST.GroupedExpression nonPrimary)
genPrimaryExpression :: Expr Mono.Type -> Codegen AST.PrimaryExpression
genPrimaryExpression expr = asPrimaryExpression <$> genExpr expr
returnSingle :: AST.Expression -> AST.Stmt
returnSingle expr = AST.ReturnStmt [expr]
genExpr :: Expr Mono.Type -> Codegen AST.Expression
genExpr expr = case expr of
Symbol _ i _ -> (AST.Expression . AST.Operand . AST.OperandName) <$> genIdentifier i
Subscript _ s i _ ->
AST.Expression <$> (AST.Index <$> genPrimaryExpression s <*> genExpr i)
Subslice _ s r _ ->
AST.Expression <$> (AST.Slice <$> genPrimaryExpression s <*> genRange r)
UnaryOp _ o e _ ->
AST.UnaryOp (genUnaryOperator o) <$> genPrimaryExpression e
BinaryOp _ o lhs rhs _ ->
AST.BinaryOp (genBinaryOperator o) <$> genExpr lhs <*> genExpr rhs
Application _ f arg _ ->
AST.Expression <$> (AST.Application <$> genPrimaryExpression f
<*> (((:[]) . AST.Argument) <$> genExpr arg))
ForeignFnApplication _ f args _ ->
case typeOf f of
-- Go functions that return unit are (almost always) void functions
-- we wrap them to make the call to them return unit
Mono.TForeignFn _ _ _ [t] | isUniverseTypeConstructor "unit" t -> do
fnCall <- genRawForeignFnApplication f args
return $ voidToUnitWrapper (AST.Expression fnCall)
Mono.TForeignFn _ _ _ (t1:t2:tr) ->
genTupleWrappedForeignFnApplication f args (t1, t2, tr)
-- Otherwise, just generate the call
_ -> AST.Expression <$> genRawForeignFnApplication f args
NoArgApplication _ f _->
AST.Expression <$> (AST.Application <$> genPrimaryExpression f <*> return [])
Fn _ (NameBinding _ paramName) body (Mono.TFn _ d r) -> do
param <- AST.FunctionParameter <$> genIdentifier paramName <*> genType d
returnType <- genType r
returnStmt <- returnSingle <$> genExpr body
return (literalExpr (AST.FunctionLiteral (AST.FunctionSignature [param] [returnType]) (AST.Block [returnStmt])))
Fn _ _ _ t ->
throwError $ UnexpectedError $ "Invalid fn type: " ++ show t
NoArgFn _ body (Mono.TNoArgFn _ r) -> do
returnType <- genType r
returnStmt <- returnSingle <$> genExpr body
return (literalExpr (AST.FunctionLiteral (AST.FunctionSignature [] [returnType]) (AST.Block [returnStmt])))
NoArgFn _ _ t ->
throwError $ UnexpectedError $ "Invalid no-arg fn type: " ++ show t
Let _ (NameBinding _ name) bindingExpr body letType -> do
varDecl <- (AST.DeclarationStmt . AST.VarDecl)
<$> (AST.VarDeclInitializer
<$> genIdentifier name
<*> genType (typeOf bindingExpr)
<*> genExpr bindingExpr)
returnStmt <- returnSingle <$> genExpr body
letType' <- genType letType
let func = AST.Operand (AST.Literal (AST.FunctionLiteral (AST.FunctionSignature [] [letType']) (AST.Block [varDecl, returnStmt])))
return (AST.Expression (AST.Application func []))
Literal _ lit _ -> case lit of
Int n -> return $ literalExpr $ AST.BasicLiteral $ AST.IntLiteral n
Bool True -> return $ operandName (GI.Identifier "true")
Bool False -> return $ operandName (GI.Identifier "false")
String s -> return $ literalExpr $ AST.BasicLiteral $ AST.StringLiteral $ AST.InterpretedStringLiteral s
Unit{} -> return emptyStructLiteral
Tuple _ f s r t ->
literalExpr <$> (AST.CompositeLiteral
<$> genType t
<*> (AST.LiteralValueElements . map AST.UnkeyedElement <$> mapM genExpr (f:s:r)))
If _ condExpr thenExpr elseExpr exprType -> do
condExpr' <- genExpr condExpr
thenBranch <- (AST.Block . (:[]) . returnSingle) <$> genExpr thenExpr
elseBranch <- (AST.ElseBlock . AST.Block . (:[]) . returnSingle) <$> genExpr elseExpr
exprType' <- genType exprType
let ifStmt = AST.IfStmt (AST.IfElse condExpr' thenBranch elseBranch)
let func = AST.Operand (AST.Literal (AST.FunctionLiteral (AST.FunctionSignature [] [exprType']) (AST.Block [ifStmt])))
return (AST.Expression (AST.Application func []))
Slice _ exprs t -> do
sliceType <- genType t
elements <- AST.LiteralValueElements . map AST.UnkeyedElement <$> mapM genExpr exprs
return (literalExpr (AST.CompositeLiteral sliceType elements))
(Block _ [] _) -> return emptyStructLiteral
(Block _ exprs t) -> do
blockType <- genType t
initStmts <- map (AST.SimpleStmt . AST.ExpressionStmt) <$> mapM genExpr (init exprs)
returnStmt <- returnSingle <$> genExpr (last exprs)
let func = AST.Operand (AST.Literal (AST.FunctionLiteral (AST.FunctionSignature [] [blockType]) (AST.Block $ initStmts ++ [returnStmt])))
return (AST.Expression (AST.Application func []))
RecordInitializer _ recordType values-> do
elements <- AST.LiteralValueElements <$> mapM genField values
structType <- genType recordType
return (literalExpr (AST.CompositeLiteral structType elements))
where
genField (FieldInitializer _ label initializerExpr) =
AST.KeyedElement <$> (AST.LiteralKeyName <$> genIdentifier label)
<*> genExpr initializerExpr
RecordFieldAccess _ recordExpr name _ -> do
primaryExpr <- genPrimaryExpression recordExpr
AST.Expression . AST.Selector primaryExpr <$> genIdentifier name
PackageMemberAccess _ pkgAlias name _ ->
(AST.Expression . AST.Operand) <$> (AST.QualifiedOperandName <$> genIdentifier pkgAlias
<*> genIdentifier name)
genBlock :: Expr Mono.Type -> Codegen AST.Block
genBlock expr = (AST.Block . (:[]) . AST.ReturnStmt . (:[])) <$> genExpr expr
genTopLevel :: Identifier -> Mono.Type -> Expr Mono.Type -> Codegen AST.TopLevelDeclaration
genTopLevel (Identifier "main") (Mono.TNoArgFn _ t) (NoArgFn _ body _) | isUniverseTypeConstructor "unit" t = do
block <- case body of
Block _ [] _ -> return (AST.Block [])
_ -> AST.Block . (:[]) . AST.SimpleStmt . AST.ExpressionStmt <$> genExpr body
return (AST.FunctionDecl (GI.Identifier "main") (AST.FunctionSignature [] []) block)
genTopLevel name _ (NoArgFn _ body (Mono.TNoArgFn _ returnType)) = do
name' <- genIdentifier name
returnType' <- genType returnType
AST.FunctionDecl name' (AST.FunctionSignature [] [returnType']) <$> genBlock body
genTopLevel name (Mono.TFn _ paramType returnType) (Fn _ (NameBinding _ paramName) body _) = do
name' <- genIdentifier name
paramName' <- genIdentifier paramName
paramType' <- genType paramType
returnType' <- genType returnType
AST.FunctionDecl name' (AST.FunctionSignature [AST.FunctionParameter paramName' paramType'] [returnType']) <$> genBlock body
genTopLevel name type' expr = do
var <- AST.VarDeclInitializer <$> genIdentifier name
<*> genType type'
<*> genExpr expr
return (AST.Decl (AST.VarDecl var))
genInstance :: InstantiatedDefinition -> Codegen AST.TopLevelDeclaration
genInstance (InstantiatedDefinition (Identifier _defName) _si name expr) =
-- let comment = text "/*"
-- $+$ text "Name:" <+> text defName
-- $+$ text "Defined at:" <+> text (show $ getSourceInfo expr)
-- $+$ text "Instantiated with type:" <+> pp (typeOf expr)
-- $+$ text "Instantiated at:" <+> text (show $ unwrap si)
-- $+$ text "*/"
genTopLevel name (typeOf expr) expr
genMonomorphed :: MonomorphedDefinition -> Codegen AST.TopLevelDeclaration
genMonomorphed (MonomorphedDefinition _ name mt expr) =
genTopLevel name mt expr
genImport :: ImportedPackage -> Codegen AST.ImportDecl
genImport (ImportedPackage _ identifier (Package (PackageDeclaration _ pkgName) _ _)) =
AST.ImportDecl <$> genIdentifier identifier
<*> return (AST.InterpretedStringLiteral (intercalate "/" pkgName))
-- | Return the import alias name for the fmt package and possibly the code for
-- importing fmt (if not imported by the user).
getFmtImport :: [ImportedPackage] -> (GI.Identifier, Maybe AST.ImportDecl)
getFmtImport pkgs =
case find isFmtPackage pkgs of
Just (ImportedPackage _ (Identifier alias) _) -> (GI.Identifier alias, Nothing)
Nothing ->
let fmt = GI.Identifier "fmt"
in (fmt, Just (AST.ImportDecl fmt (AST.InterpretedStringLiteral "fmt")))
where
isFmtPackage (ImportedPackage _ _ (Package (PackageDeclaration _ ["fmt"]) _ _)) = True
isFmtPackage _ = False
prelude :: GI.Identifier -> [AST.TopLevelDeclaration]
prelude fmtAlias =
let printSignature = AST.FunctionSignature [AST.FunctionParameter (GI.Identifier "x") (GT.Interface [])] []
xOperand = AST.Expression (AST.Operand (AST.OperandName (GI.Identifier "x")))
fmtApplication name = AST.Expression (AST.Application (AST.Operand (AST.QualifiedOperandName fmtAlias name)) (map AST.Argument [xOperand]))
in [
AST.FunctionDecl (GI.Identifier "print") printSignature (AST.Block [
AST.SimpleStmt (AST.ExpressionStmt (fmtApplication (GI.Identifier "Print")))]),
AST.FunctionDecl (GI.Identifier "println") printSignature (AST.Block [
AST.SimpleStmt (AST.ExpressionStmt (fmtApplication (GI.Identifier "Println")))])
]
genPackage :: MonomorphedPackage -> Codegen AST.SourceFile
genPackage (MonomorphedPackage (PackageDeclaration _ name) imports is ms) = do
imports' <- mapM genImport imports
let (fmtAlias, fmtImport) = getFmtImport imports
allImports = imports' ++ maybeToList fmtImport
is' <- mapM genInstance (Set.toList is)
ms' <- mapM genMonomorphed (Set.toList ms)
let allTopLevel = prelude fmtAlias ++ is' ++ ms'
return (AST.SourceFile (AST.PackageClause (safeName (last name))) allImports allTopLevel)
toFilePath :: GoBackend -> PackageName -> Codegen FilePath
toFilePath _ [] = throwError (UnexpectedError "Package name cannot be empty")
toFilePath (GoBackend goPath) parts =
let isMain = last parts == "main"
dirParts = "src" : if isMain then init parts else parts
dir = foldl (</>) goPath dirParts
fileName = if isMain then "main.go" else last parts ++ ".go"
in return (dir </> fileName)
instance Backend GoBackend where
codegen backend pkg@(MonomorphedPackage (PackageDeclaration _ name) _ _ _) =
runExcept (runReaderT action pkg)
where action = do path <- toFilePath backend name
code <- genPackage pkg
return [CompiledFile path (displayS (renderPretty 0.4 120 (pretty code)) "")]
|
AlbinTheander/oden
|
src/Oden/Backend/Go.hs
|
mit
| 18,245
| 0
| 23
| 3,990
| 5,847
| 2,881
| 2,966
| 339
| 28
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.