code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Network.Orchid.Format.Pdf (fPdf) where
import Control.Monad (liftM)
import Data.ByteString.Lazy hiding (writeFile)
import Data.FileStore (FileStore)
import Network.Orchid.Core.Format
import Prelude hiding (readFile)
import System.Process (waitForProcess, runProcess)
import Text.Document.Document
fPdf :: WikiFormat
fPdf = WikiFormat "pdf" "application/pdf" pdf
-- TODO: write to _cache dir, not /tmp
pdf :: FileStore -> FilePath -> FilePath -> String -> IO Output
pdf _ _ _ src = do
writeFile "/tmp/tex-to-pdf.tex"
$ either show toLaTeX
$ fromWiki src
_ <- runProcess "pdflatex" ["-interaction=batchmode", "/tmp/tex-to-pdf.tex"]
(Just "/tmp") Nothing Nothing Nothing Nothing
>>= waitForProcess
liftM BinaryOutput $ readFile "/tmp/tex-to-pdf.pdf"
{- runProcess "latexmk" [
"-pdf", "-silent", "-f", "-g"
] (Just "/tmp") Nothing Nothing Nothing Nothing
>>= waitForProcess-}
| sebastiaanvisser/orchid | src/Network/Orchid/Format/Pdf.hs | bsd-3-clause | 920 | 0 | 11 | 148 | 210 | 115 | 95 | 19 | 1 |
module HMQ.Query where
-- Copyright (c) 2008 Stephen C. Harris.
-- See COPYING file at the root of this distribution for copyright information.
import Data.Maybe
import HMQ.Metadata.TableMetadata
import HMQ.Utils.Strings
data Query =
Query
{
selectFields :: [(String, Maybe String)],
fromClause :: String,
whereConditions :: [String]
}
deriving (Show)
selectFieldExprs :: Query -> [String]
selectFieldExprs = map fst . selectFields
selectFieldNames :: Query -> [Maybe String]
selectFieldNames = map snd . selectFields
toSqlString :: Query -> String
toSqlString (Query selFlds fromClause restrs) =
let
selectFieldString (expr,maybeAlias) = expr ++ maybe "" (\alias -> " AS \"" ++ alias ++ "\"") maybeAlias
in
"SELECT " ++ listAsString selectFieldString "," selFlds ++ "\n" ++
"FROM " ++ fromClause ++ "\n" ++
if null restrs then ""
else "WHERE\n" ++
foldl (\accumRestrs r -> (if accumRestrs == "" then " " else accumRestrs ++ "\n AND ") ++ "(" ++ r ++ ")")
""
restrs
data QueryTable =
QueryTable
{
tableIdentifier :: TableIdentifier,
tableAlias :: TableAlias
}
deriving(Show)
type TableAlias = String
| scharris/hmq | Query.hs | bsd-3-clause | 1,275 | 6 | 18 | 343 | 333 | 185 | 148 | 31 | 3 |
module Snippet where
import Haskore.Music.GeneralMIDI as MidiMusic
import Haskore.Interface.MIDI.Render as Render
-- c_major
render_to f m = Render.fileFromGeneralMIDIMusic f song where
song = MidiMusic.fromMelodyNullAttr MidiMusic.AcousticGrandPiano m
-- bach's prelude
export_to f v = render_to $ concat ["midi/", f, "/", f, "_", show v, ".midi"]
in_group_of n [] = []
in_group_of n xs = h : in_group_of n t where (h, t) = splitAt n xs
-- wow_1
play_with = MidiMusic.fromMelodyNullAttr
render_to' f = Render.fileFromGeneralMIDIMusic f
export_to' f v = render_to' $ concat ["midi/", f, "/", f, "_", show v, ".midi"]
| nfjinjing/haskore-guide | src/Snippet.hs | bsd-3-clause | 645 | 0 | 8 | 118 | 211 | 117 | 94 | 11 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Futhark.Representation.Kernels.Simplify
( simplifyKernels
, simplifyFun
)
where
import Control.Applicative
import Control.Monad
import Data.Either
import Data.List hiding (any, all)
import Data.Maybe
import Data.Monoid
import qualified Data.HashMap.Lazy as HM
import qualified Data.HashSet as HS
import Prelude hiding (any, all)
import Futhark.Representation.Kernels
import Futhark.Representation.AST.Attributes.Aliases
import qualified Futhark.Optimise.Simplifier.Engine as Engine
import qualified Futhark.Optimise.Simplifier as Simplifier
import Futhark.Optimise.Simplifier.Rules
import Futhark.MonadFreshNames
import Futhark.Tools
import Futhark.Optimise.Simplifier (simplifyProgWithRules, noExtraHoistBlockers)
import Futhark.Optimise.Simplifier.Simple
import Futhark.Optimise.Simplifier.RuleM
import Futhark.Optimise.Simplifier.Rule
import qualified Futhark.Analysis.SymbolTable as ST
import qualified Futhark.Analysis.UsageTable as UT
simplifyKernels :: MonadFreshNames m => Prog -> m Prog
simplifyKernels =
simplifyProgWithRules bindableSimpleOps kernelRules noExtraHoistBlockers
simplifyFun :: MonadFreshNames m => FunDef -> m FunDef
simplifyFun =
Simplifier.simplifyFunWithRules bindableSimpleOps kernelRules Engine.noExtraHoistBlockers
instance (Attributes lore, Engine.SimplifiableOp lore (Op lore)) =>
Engine.SimplifiableOp lore (Kernel lore) where
simplifyOp (MapKernel cs w index ispace inps returns body) = do
cs' <- Engine.simplify cs
w' <- Engine.simplify w
ispace' <- forM ispace $ \(i, bound) -> do
bound' <- Engine.simplify bound
return (i, bound')
returns' <- forM returns $ \(t, perm) -> do
t' <- Engine.simplify t
return (t', perm)
par_blocker <- Engine.asksEngineEnv $ Engine.blockHoistPar . Engine.envHoistBlockers
Engine.enterLoop $ Engine.bindLoopVars ((index,w) : ispace) $ do
inps' <- mapM simplifyKernelInput inps
body' <- Engine.bindLParams (map kernelInputParam inps') $
Engine.blockIf (Engine.hasFree bound_here `Engine.orIf`
Engine.isConsumed `Engine.orIf`
par_blocker) $
Engine.simplifyBody (map (const Observe) returns) body
return $ MapKernel cs' w' index ispace' inps' returns' body'
where bound_here = HS.fromList $ index : map kernelInputName inps ++ map fst ispace
simplifyOp (ReduceKernel cs w kernel_size comm parlam seqlam arrs) = do
cs' <- Engine.simplify cs
w' <- Engine.simplify w
kernel_size' <- Engine.simplify kernel_size
arrs' <- mapM Engine.simplify arrs
parlam' <- Engine.simplifyLambda parlam Nothing $ map (const Nothing) arrs
seqlam' <- Engine.simplifyLambda seqlam Nothing $ map Just arrs
let consumed_in_seq = consumedInBody $ lambdaBody seqlam'
arr_params = drop 1 $ lambdaParams seqlam'
forM_ (zip arr_params arrs) $ \(p,arr) ->
when (paramName p `HS.member` consumed_in_seq) $
Engine.consumedName arr
return $ ReduceKernel cs' w' kernel_size' comm parlam' seqlam' arrs'
simplifyOp (ScanKernel cs w kernel_size order lam input) = do
arrs' <- mapM Engine.simplify arrs
ScanKernel <$> Engine.simplify cs <*> Engine.simplify w <*>
Engine.simplify kernel_size <*> pure order <*>
Engine.simplifyLambda lam (Just nes) (map Just arrs') <*>
(zip <$> mapM Engine.simplify nes <*> pure arrs')
where (nes, arrs) = unzip input
simplifyOp (ChunkedMapKernel cs w kernel_size o lam arrs) = do
arrs' <- mapM Engine.simplify arrs
ChunkedMapKernel <$> Engine.simplify cs <*> Engine.simplify w <*>
Engine.simplify kernel_size <*> pure o <*>
Engine.simplifyLambda lam Nothing (map Just arrs') <*>
pure arrs'
simplifyOp (WriteKernel cs ts i vs as) = do
cs' <- Engine.simplify cs
ts' <- mapM Engine.simplify ts
i' <- Engine.simplify i
vs' <- mapM Engine.simplify vs
as' <- mapM Engine.simplify as
return $ WriteKernel cs' ts' i' vs' as'
simplifyOp NumGroups = return NumGroups
simplifyOp GroupSize = return GroupSize
simplifyKernelInput :: Engine.MonadEngine m =>
KernelInput (Engine.InnerLore m) -> m (KernelInput (Lore m))
simplifyKernelInput (KernelInput param arr is) = do
param' <- Engine.simplifyParam Engine.simplify param
arr' <- Engine.simplify arr
is' <- mapM Engine.simplify is
return $ KernelInput param' arr' is'
instance Engine.Simplifiable KernelSize where
simplify (KernelSize num_groups group_size thread_chunk
num_elements offset_multiple num_threads) = do
num_groups' <- Engine.simplify num_groups
group_size' <- Engine.simplify group_size
thread_chunk' <- Engine.simplify thread_chunk
num_elements' <- Engine.simplify num_elements
offset_multiple' <- Engine.simplify offset_multiple
num_threads' <- Engine.simplify num_threads
return $ KernelSize num_groups' group_size' thread_chunk' num_elements' offset_multiple' num_threads'
kernelRules :: (MonadBinder m,
LocalScope (Lore m) m,
Op (Lore m) ~ Kernel (Lore m),
Aliased (Lore m)) => RuleBook m
kernelRules = (std_td_rules <> topDownRules,
std_bu_rules <> bottomUpRules)
where (std_td_rules, std_bu_rules) = standardRules
topDownRules :: (MonadBinder m,
LocalScope (Lore m) m,
Op (Lore m) ~ Kernel (Lore m),
Aliased (Lore m)) => TopDownRules m
topDownRules = [removeUnusedKernelInputs
, simplifyKernelInputs
, removeInvariantKernelOutputs
, fuseReduceIota
, fuseChunkedMapIota
]
bottomUpRules :: (MonadBinder m,
LocalScope (Lore m) m,
Op (Lore m) ~ Kernel (Lore m)) => BottomUpRules m
bottomUpRules = [ removeDeadKernelOutputs
]
-- | Remove inputs that are not used inside the @kernel@.
removeUnusedKernelInputs :: (MonadBinder m, Op (Lore m) ~ Kernel (Lore m)) =>
TopDownRule m
removeUnusedKernelInputs _ (Let pat _ (Op (MapKernel cs w index ispace inps returns body)))
| (used,unused) <- partition usedInput inps,
not (null unused) =
letBind_ pat $ Op $ MapKernel cs w index ispace used returns body
where used_in_body = freeInBody body
usedInput inp = kernelInputName inp `HS.member` used_in_body
removeUnusedKernelInputs _ _ = cannotSimplify
-- | Kernel inputs are indexes into arrays. Based on how those arrays
-- are defined, we may be able to simplify the input.
simplifyKernelInputs :: (MonadBinder m,
LocalScope (Lore m) m,
Op (Lore m) ~ Kernel (Lore m), Aliased (Lore m)) =>
TopDownRule m
simplifyKernelInputs vtable (Let pat _ (Op (MapKernel cs w index ispace inps returns body)))
| (inps', extra_cs, extra_bnds) <- unzip3 $ map simplifyInput inps,
inps /= catMaybes inps' = do
body' <- localScope index_env $ insertBindingsM $ do
forM_ (catMaybes extra_bnds) $ \(name, se) ->
letBindNames'_ [name] $ PrimOp $ SubExp se
return body
letBind_ pat $ Op $
MapKernel (cs++concat extra_cs) w index ispace
(catMaybes inps') returns body'
where defOf = (`ST.lookupExp` vtable)
seType (Var v) = ST.lookupType v vtable
seType (Constant v) = Just $ Prim $ primValueType v
index_env = HM.fromList $ zip (map fst ispace) $ repeat IndexInfo
consumed_in_body = consumedInBody body
simplifyInput inp@(KernelInput param arr is) =
case simplifyIndexing defOf seType arr is consumed of
Just (IndexResult inp_cs arr' is') ->
(Just $ KernelInput param arr' is', inp_cs, Nothing)
Just (SubExpResult se) ->
(Nothing, [], Just (paramName param, se))
_ ->
(Just inp, [], Nothing)
where consumed = paramName param `HS.member` consumed_in_body
simplifyKernelInputs _ _ = cannotSimplify
removeInvariantKernelOutputs :: (MonadBinder m, Op (Lore m) ~ Kernel (Lore m)) =>
TopDownRule m
removeInvariantKernelOutputs vtable (Let pat _ (Op (MapKernel cs w index ispace inps returns body)))
| (invariant, variant) <-
partitionEithers $ zipWith3 isInvariant
(patternValueElements pat) returns $ bodyResult body,
not $ null invariant = do
let (variant_pat_elems, variant_returns, variant_result) =
unzip3 variant
pat' = Pattern [] variant_pat_elems
forM_ invariant $ \(pat_elem, (t, perm), se) ->
if perm /= sort perm
then cannotSimplify
else do
flat <- letExp "kernel_invariant_flat" $ PrimOp $ Replicate w se
let shape = map DimNew $ map snd ispace ++ arrayDims t
letBind_ (Pattern [] [pat_elem]) $ PrimOp $ Reshape cs shape flat
letBind_ pat' $ Op $
MapKernel cs w index ispace inps variant_returns
body { bodyResult = variant_result }
where isInvariant pat_elem ret (Var v)
| Just _ <- ST.lookupType v vtable = Left (pat_elem, ret, Var v)
isInvariant pat_elem ret (Constant v) = Left (pat_elem, ret, Constant v)
isInvariant pat_elem ret se = Right (pat_elem, ret, se)
removeInvariantKernelOutputs _ _ = cannotSimplify
removeDeadKernelOutputs :: (MonadBinder m, Op (Lore m) ~ Kernel (Lore m)) => BottomUpRule m
removeDeadKernelOutputs (_, used) (Let pat _ (Op (MapKernel cs w index ispace inps returns body)))
| (used_pat_elems, used_returns, used_result) <-
unzip3 $ filter usedOutput pats_rets_and_ses,
used_returns /= returns = do
let pat' = pat { patternValueElements = used_pat_elems }
letBind_ pat' $ Op $
MapKernel cs w index ispace inps used_returns
body { bodyResult = used_result }
where pats_rets_and_ses = zip3 (patternValueElements pat) returns $ bodyResult body
usedOutput (pat_elem, _, _) = patElemName pat_elem `UT.used` used
removeDeadKernelOutputs _ _ = cannotSimplify
fuseReduceIota :: (LocalScope (Lore m) m,
MonadBinder m, Op (Lore m) ~ Kernel (Lore m)) =>
TopDownRule m
fuseReduceIota vtable (Let pat _ (Op (ReduceKernel cs w size comm redlam foldlam arrs)))
| Just f <- fuseIota vtable size comm foldlam arrs = do
(foldlam', arrs') <- f
letBind_ pat $ Op $ ReduceKernel cs w size comm redlam foldlam' arrs'
fuseReduceIota _ _ = cannotSimplify
fuseChunkedMapIota :: (LocalScope (Lore m) m,
MonadBinder m, Op (Lore m) ~ Kernel (Lore m)) =>
TopDownRule m
fuseChunkedMapIota vtable (Let pat _ (Op (ChunkedMapKernel cs w size o lam arrs)))
| Just f <- fuseIota vtable size comm lam arrs = do
(lam', arrs') <- f
letBind_ pat $ Op $ ChunkedMapKernel cs w size o lam' arrs'
where comm = case o of Disorder -> Commutative
InOrder -> Noncommutative
fuseChunkedMapIota _ _ = cannotSimplify
fuseIota :: (LocalScope (Lore m) m, MonadBinder m) =>
ST.SymbolTable (Lore m)
-> KernelSize
-> Commutativity
-> LambdaT (Lore m)
-> [VName]
-> Maybe (m (LambdaT (Lore m), [VName]))
fuseIota vtable size comm lam arrs
| null iota_params = Nothing
| otherwise = Just $ do
fold_body <- (uncurry (flip mkBodyM) =<<) $ collectBindings $ inScopeOf lam $ do
case comm of
Noncommutative -> do
start_offset <- letSubExp "iota_start_offset" $
PrimOp $ BinOp (Mul Int32) (Var thread_index) elems_per_thread
forM_ iota_params $ \(p, x) -> do
start <- letSubExp "iota_start" $
PrimOp $ BinOp (Add Int32) start_offset x
letBindNames'_ [p] $
PrimOp $ Iota (Var $ paramName chunk_param) start $
constant (1::Int32)
Commutative ->
forM_ iota_params $ \(p, x) -> do
start <- letSubExp "iota_start" $
PrimOp $ BinOp (Add Int32) (Var thread_index) x
letBindNames'_ [p] $
PrimOp $ Iota (Var $ paramName chunk_param) start
num_threads
mapM_ addBinding $ bodyBindings $ lambdaBody lam
return $ bodyResult $ lambdaBody lam
let (arr_params', arrs') = unzip params_and_arrs
lam' = lam { lambdaBody = fold_body
, lambdaParams = Param thread_index (paramAttr chunk_param) :
chunk_param :
arr_params'
}
return (lam', arrs')
where elems_per_thread = kernelElementsPerThread size
num_threads = kernelNumThreads size
(thread_index, chunk_param, params_and_arrs, iota_params) =
iotaParams vtable lam arrs
iotaParams :: ST.SymbolTable lore
-> LambdaT lore
-> [VName]
-> (VName,
Param (LParamAttr lore),
[(ParamT (LParamAttr lore), VName)],
[(VName, SubExp)])
iotaParams vtable lam arrs = (thread_index, chunk_param, params_and_arrs, iota_params)
where (thread_index, chunk_param, arr_params) =
partitionChunkedKernelLambdaParameters $ lambdaParams lam
(params_and_arrs, iota_params) =
partitionEithers $ zipWith isIota arr_params arrs
isIota p v
| Just (Iota _ x (Constant (IntValue (Int32Value 1)))) <- asPrimOp =<< ST.lookupExp v vtable =
Right (paramName p, x)
| otherwise =
Left (p, v)
| CulpaBS/wbBach | src/Futhark/Representation/Kernels/Simplify.hs | bsd-3-clause | 13,870 | 0 | 27 | 3,644 | 4,346 | 2,165 | 2,181 | 280 | 4 |
{-|
Module : Data.Tree.Utils
Description : Several utilities for manipulating `Tree`s
Copyright : (c) Michael Klein, 2016
License : BSD3
Maintainer : lambdamichael(at)gmail.com
`TextShow` instances for `Tree`s.
Several general and specialized filters for `Tree`s.
`Tree` and `Forest` union(by).
-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Data.Tree.Utils ( forestBranches
, forestFilter
, forestLeaves
, forestSort
, forestSortBy
, forestUnion
, forestUnionBy
, treeBranches
, treeFilter
, treeLeaves
, treeSort
, treeSortBy
, treeUnion
, treeUnionBy
) where
import Data.List ( sortBy
)
import Data.List.Utils ( keepPartition
)
import Data.Tree ( Forest
, Tree(..)
)
-- | @forestFilter p forest@ returns a list of all the subtrees in @forest@
-- that satisfy @p@
forestFilter :: (Tree a -> Bool) -> Forest a -> [Tree a]
forestFilter _ [] = []
forestFilter p x = keep ++ forestFilter p (bs >>= subForest)
where
~(keep, _, bs) = keepPartition p (null . subForest) x
-- | `forestFilter` for `Tree`s
treeFilter :: (Tree a -> Bool) -> Tree a -> [Tree a]
treeFilter p x = forestFilter p [x]
-- | A binding function to allow using @forestFilter@/@treeFilter@ to
-- select either branches or leaves
nodeFilter :: (Bool -> c) -> ((Tree a1 -> c) -> a -> [Tree b]) -> a -> [b]
nodeFilter p f = map rootLabel . f (p . null . subForest)
-- | Given a tree/forest filter and a tree/forest, return all leaves
leaves :: ((Tree a1 -> Bool) -> a -> [Tree b]) -> a -> [b]
leaves = nodeFilter not
-- | Given a tree/forest filter and a tree/forest, return all branches
branches :: ((Tree a1 -> Bool) -> a -> [Tree b]) -> a -> [b]
branches = nodeFilter id
-- | Return a list of the `rootLabel`s of all leaves in a forest
forestLeaves :: Forest a -> [a]
forestLeaves = leaves forestFilter
-- | Return a list of the `rootLabel`s of all branches in a forest
forestBranches :: Forest a -> [a]
forestBranches = branches forestFilter
-- | Return a list of the `rootLabel`s of all leaves in a tree
treeLeaves :: Tree a -> [a]
treeLeaves = leaves treeFilter
-- | Return a list of the `rootLabel`s of all branches in a tree
treeBranches :: Tree a -> [a]
treeBranches = branches treeFilter
-- | Note that all these sorts can be tested by the following:
-- sort . sort == sort,
-- sort . reverse == id,
-- length . sort == length
treeSort :: Ord a => Tree a -> Tree a
treeSort = treeSortBy compare
-- | This is `treeSort`, except it uses a user-supplied comparison function
-- instead of the overloaded `compare` function.
treeSortBy :: (a -> a -> Ordering) -> Tree a -> Tree a
treeSortBy cmp (Node x xs) = Node x $ forestSortBy cmp xs
-- | See `treeSort`
forestSort :: Ord a => Forest a -> Forest a
forestSort = forestSortBy compare
-- | This is `forestSort`, except it uses a user-supplied comparison function
-- instead of the overloaded `compare` function.
forestSortBy :: (a -> a -> Ordering) -> Forest a -> Forest a
forestSortBy cmp = map (treeSortBy cmp) . sortBy cmp'
where
cmp' x y = cmp (rootLabel x) (rootLabel y)
-- | Why require `Ord` for `treeUnion` and related functions?
-- It allows roughly @O(n)@ time operations.
--
-- >>> treeUnion x x
-- [x]
--
-- If @x /= y@, then
--
-- >>> treeUnion (Node x a) (Node y b)
-- [Node x a, Node y a]
--
-- >>> treeUnion (Node 1 [Node 2 []]) (Node 1 [Node 2 [], Node 3 [])
-- [Node 1 [Node 2 [], Node 3 []]]
--
treeUnion :: Ord a => Tree a -> Tree a -> Forest a
treeUnion = treeUnionBy compare
-- | This is `treeUnion`, except it uses a user-supplied comparison function
-- instead of the overloaded `compare` function.
treeUnionBy :: (a -> a -> Ordering) -> Tree a -> Tree a -> Forest a
treeUnionBy cmp x y = forestUnionBy cmp [x] [y]
-- | This effectively applies `treeUnion` to all pairs of `Tree`s in the
-- given forests, until there is no further change
forestUnion :: Ord a => Forest a -> Forest a -> Forest a
forestUnion = forestUnionBy compare
-- | This is `forestUnion`, except it uses a user-supplied comparison function
-- instead of the overloaded `compare` function.
forestUnionBy :: (a -> a -> Ordering) -> Forest a -> Forest a -> Forest a
forestUnionBy cmp xs ys = forestUnionBy' cmp xs' ys'
where
xs' = forestSortBy cmp xs
ys' = forestSortBy cmp ys
-- | This function requires that its arguments are sorted, otherwise it is
-- equivalent to `forestUnionBy`
forestUnionBy' :: (a -> a -> Ordering) -> Forest a -> Forest a -> Forest a
forestUnionBy' _ xs [] = xs
forestUnionBy' _ [] ys = ys
forestUnionBy' c s t = case c (rootLabel x) (rootLabel y) of
LT -> x : forestUnionBy' c xs t
GT -> y : forestUnionBy' c s ys
EQ -> u : forestUnionBy' c xs ys
where
~(x:xs) = s
~(y:ys) = t
~[u] = treeUnionBy c x y
| michaeljklein/git-details | src/Data/Tree/Utils.hs | bsd-3-clause | 5,407 | 0 | 11 | 1,598 | 1,180 | 622 | 558 | 69 | 3 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.VI.Corpus
( corpus
, negativeCorpus
) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Types hiding (examples)
import Duckling.Time.Corpus
import Duckling.Time.Types hiding (Month, refTime)
import Duckling.TimeGrain.Types hiding (add)
negativeCorpus :: NegativeCorpus
negativeCorpus = (context, testOptions, examples)
where
examples =
[ "có ngày chính xác"
]
corpus :: Corpus
corpus = (context, testOptions, allExamples)
context :: Context
context = testContext
{ locale = makeLocale VI Nothing
, referenceTime = refTime (2017, 2, 2, 3, 55, 0) (-2)
}
allExamples :: [Example]
allExamples = concat
[ examples (datetime (2017, 2, 2, 3, 55, 0) Second)
[ "bây giờ"
, "ngay bây giờ"
, "ngay lúc này"
]
, examples (datetime (2017, 2, 2, 0, 0, 0) Day)
[ "hôm nay"
, "ngày hôm nay"
, "bữa nay"
]
, examples (datetime (2017, 2, 1, 0, 0, 0) Day)
[ "hôm qua"
, "ngày hôm qua"
]
, examples (datetime (2017, 2, 3, 0, 0, 0) Day)
[ "ngày mai"
]
, examples (datetime (2017, 1, 31, 0, 0, 0) Day)
[ "hôm kia"
, "ngày hôm kia"
]
, examples (datetime (2017, 2, 6, 0, 0, 0) Day)
[ "thứ 2"
, "thứ hai"
]
, examples (datetime (2017, 2, 6, 0, 0, 0) Day)
[ "thứ 2 ngày 6 tháng 2"
, "thứ 2 mồng 6 tháng 2"
, "thứ hai ngày 6 tháng 2"
]
, examples (datetime (2017, 2, 7, 0, 0, 0) Day)
[ "thứ 3"
, "thứ ba"
]
, examples (datetime (2017, 2, 5, 0, 0, 0) Day)
[ "chủ nhật"
, "chúa nhật"
]
, examples (datetime (2017, 6, 1, 0, 0, 0) Month)
[ "tháng 6"
, "tháng sáu"
]
, examples (datetime (2017, 3, 1, 0, 0, 0) Day)
[ "ngày đầu tiên của tháng ba"
, "ngày đầu tiên của tháng 3"
]
, examples (datetime (2017, 3, 3, 0, 0, 0) Day)
[ "mồng 3 tháng ba"
, "mồng 3 tháng 3"
]
, examples (datetime (2017, 3, 3, 0, 0, 0) Day)
[ "ngày mồng 3 tháng 3 năm 2017"
, "ngày 3 tháng 3 năm 2017"
, "3/3/2017"
, "3/3/17"
, "03/03/2017"
]
, examples (datetime (2017, 3, 7, 0, 0, 0) Day)
[ "ngày mồng 7 tháng 3"
, "ngày 7 tháng ba"
, "7/3"
, "07/03"
]
, examples (datetime (2017, 10, 1, 0, 0, 0) Month)
[ "tháng 10 năm 2017"
, "tháng mười năm 2017"
]
, examples (datetime (1991, 9, 3, 0, 0, 0) Day)
[ "03/09/1991"
, "3/9/91"
, "3/9/1991"
]
, examples (datetime (2017, 10, 12, 0, 0, 0) Day)
[ "12 tháng 10 năm 2017"
, "ngày 12 tháng 10 năm 2017"
]
, examples (datetime (2017, 2, 9, 0, 0, 0) Day)
[ "thứ năm tuần tới"
, "thứ 5 tuần sau"
]
, examples (datetime (2017, 3, 1, 0, 0, 0) Month)
[ "tháng 3 tới"
]
, examples (datetime (2017, 4, 9, 0, 0, 0) Day)
[ "chủ nhật ngày mồng 9 tháng 4"
, "chủ nhật ngày 9 tháng 4"
, "chúa nhật ngày 9 tháng 4"
]
, examples (datetime (2017, 2, 6, 0, 0, 0) Day)
[ "thứ 2 ngày 6 tháng 2"
, "thứ 2 ngày mồng 6 tháng 2"
, "thứ hai ngày mồng 6 tháng 2"
]
, examples (datetime (2018, 4, 3, 0, 0, 0) Day)
[ "thứ 3 ngày 3 tháng 4 năm 2018"
]
, examples (datetime (2017, 1, 30, 0, 0, 0) Week)
[ "tuần này"
]
, examples (datetime (2017, 1, 23, 0, 0, 0) Week)
[ "tuần trước"
]
, examples (datetime (2017, 2, 6, 0, 0, 0) Week)
[ "tuần sau"
]
, examples (datetime (2017, 1, 1, 0, 0, 0) Month)
[ "tháng trước"
]
, examples (datetime (2017, 3, 1, 0, 0, 0) Month)
[ "tháng sau"
]
, examples (datetime (2017, 1, 1, 0, 0, 0) Quarter)
[ "quý này"
]
, examples (datetime (2017, 4, 1, 0, 0, 0) Quarter)
[ "quý sau"
]
, examples (datetime (2017, 7, 1, 0, 0, 0) Quarter)
[ "quý 3"
, "quý ba"
]
, examples (datetime (2018, 10, 1, 0, 0, 0) Quarter)
[ "quý 4 năm 2018"
]
, examples (datetime (2016, 1, 1, 0, 0, 0) Year)
[ "năm trước"
, "năm ngoái"
]
, examples (datetime (2017, 1, 1, 0, 0, 0) Year)
[ "năm nay"
]
, examples (datetime (2018, 1, 1, 0, 0, 0) Year)
[ "năm sau"
]
, examples (datetime (2017, 1, 1, 0, 0, 0) Quarter)
[ "quý này"
, "quý nay"
, "quý hiện tại"
]
, examples (datetime (2017, 4, 1, 0, 0, 0) Quarter)
[ "quý tới"
, "quý tiếp"
]
, examples (datetime (2017, 7, 1, 0, 0, 0) Quarter)
[ "quý ba"
, "quý 3"
]
, examples (datetime (2018, 10, 1, 0, 0, 0) Quarter)
[ "quý 4 của năm 2018"
]
, examples (datetime (2016, 1, 1, 0, 0, 0) Year)
[ "năm ngoái"
, "năm trước"
]
, examples (datetime (2017, 1, 1, 0, 0, 0) Year)
[ "năm nay"
]
, examples (datetime (2018, 1, 1, 0, 0, 0) Year)
[ "năm tiếp theo"
, "năm kế tiếp"
, "năm tới"
]
, examples (datetime (2017, 1, 31, 0, 0, 0) Day)
[ "thứ ba vừa rồi"
]
, examples (datetime (2017, 2, 7, 0, 0, 0) Day)
[ "thứ ba tới"
]
, examples (datetime (2017, 2, 3, 0, 0, 0) Day)
[ "thứ sáu tới"
]
, examples (datetime (2017, 2, 8, 0, 0, 0) Day)
[ "thứ tư tuần tới"
, "thứ tư của tuần tới"
]
, examples (datetime (2017, 2, 3, 0, 0, 0) Day)
[ "thứ sáu tuần này"
, "thứ 6 tuần này"
, "thứ 6 của tuần này"
]
, examples (datetime (2017, 2, 2, 0, 0, 0) Day)
[ "thứ năm tuần này"
, "thứ 5 của tuần này"
]
, examples (datetime (2017, 9, 4, 0, 0, 0) Week)
[ "tuần đầu tiên của tháng 9 năm 2017"
]
, examples (datetime (2017, 2, 3, 2, 0, 0) Hour)
[ "vào lúc 2 giờ sáng"
, "lúc 2 giờ sáng"
]
, examples (datetime (2017, 2, 3, 1, 18, 0) Minute)
[ "1:18 sáng"
]
, examples (datetime (2017, 2, 2, 15, 0, 0) Hour)
[ "lúc 3 giờ tối"
, "vào lúc 3 giờ chiều"
, "vào đúng 3 giờ chiều"
]
, examples (datetime (2017, 2, 2, 15, 0, 0) Hour)
[ "vào khoảng 3 giờ chiều"
, "khoảng 3 giờ chiều"
]
, examples (datetime (2017, 2, 2, 15, 30, 0) Minute)
[ "3 giờ rưỡi chiều"
, "3:30 chiều"
, "ba giờ rưỡi chiều"
]
, examples (datetime (2017, 2, 2, 14, 30, 0) Minute)
[ "2:30"
, "hai giờ rưỡi"
]
, examples (datetime (2017, 2, 2, 15, 23, 24) Second)
[ "15:23:24"
]
, examples (datetime (2017, 2, 2, 10, 45, 0) Minute)
[ "11 giờ kém 15"
, "10 giờ 45 phút"
, "10:45"
, "10 giờ 45"
, "10h45"
, "10g45"
]
, examples (datetime (2017, 2, 2, 20, 0, 0) Hour)
[ "8 giờ tối nay"
]
, examples (datetime (2017, 4, 20, 19, 30, 0) Minute)
[ "vào lúc 7:30 chiều ngày 20 tháng 4 năm 2017"
, "7:30 chiều ngày 20/4/2017"
]
, examples (datetimeInterval ((2017, 6, 21, 0, 0, 0), (2017, 9, 24, 0, 0, 0)) Day)
[ "mùa hè này"
, "mùa hè năm nay"
]
, examples (datetimeInterval ((2016, 12, 21, 0, 0, 0), (2017, 3, 21, 0, 0, 0)) Day)
[ "mùa đông này"
]
, examples (datetimeInterval ((2017, 2, 2, 18, 0, 0), (2017, 2, 3, 0, 0, 0)) Hour)
[ "tối nay"
, "tối hôm nay"
]
, examples (datetimeInterval ((2017, 2, 3, 18, 0, 0), (2017, 2, 4, 0, 0, 0)) Hour)
[ "tối mai"
, "tối ngày mai"
]
, examples (datetimeInterval ((2017, 2, 3, 12, 0, 0), (2017, 2, 3, 14, 0, 0)) Hour)
[ "trưa mai"
, "trưa ngày mai"
]
, examples (datetimeInterval ((2017, 2, 1, 18, 0, 0), (2017, 2, 2, 0, 0, 0)) Hour)
[ "tối qua"
, "tối hôm qua"
]
, examples (datetimeInterval ((2017, 2, 5, 4, 0, 0), (2017, 2, 5, 12, 0, 0)) Hour)
[ "sáng chủ nhật"
, "sáng chúa nhật"
]
, examples (datetimeInterval ((2017, 2, 2, 3, 54, 58), (2017, 2, 2, 3, 55, 0)) Second)
[ "2 giây vừa rồi"
]
, examples (datetimeInterval ((2017, 2, 2, 3, 55, 1), (2017, 2, 2, 3, 55, 4)) Second)
[ "3 giây tới"
, "3 giây tiếp theo"
, "3 s tiếp theo"
]
, examples (datetimeInterval ((2017, 2, 2, 3, 53, 0), (2017, 2, 2, 3, 55, 0)) Minute)
[ "2 phút vừa rồi"
]
, examples (datetimeInterval ((2017, 2, 2, 3, 56, 0), (2017, 2, 2, 3, 59, 0)) Minute)
[ "3 phút tới"
, "3 phút tiếp theo"
]
, examples (datetimeInterval ((2017, 2, 2, 2, 0, 0), (2017, 2, 2, 3, 0, 0)) Hour)
[ "một tiếng vừa rồi"
, "1 giờ vừa qua"
]
, examples (datetimeInterval ((2017, 2, 2, 4, 0, 0), (2017, 2, 2, 7, 0, 0)) Hour)
[ "3 tiếng tiếp theo"
, "3 giờ tới"
]
, examples (datetimeInterval ((2017, 1, 31, 0, 0, 0), (2017, 2, 2, 0, 0, 0)) Day)
[ "2 ngày vừa rồi"
, "2 ngày vừa qua"
]
, examples (datetimeInterval ((2017, 2, 3, 0, 0, 0), (2017, 2, 6, 0, 0, 0)) Day)
[ "3 ngày tới"
, "3 ngày tiếp theo"
]
, examples (datetimeInterval ((2016, 12, 1, 0, 0, 0), (2017, 2, 1, 0, 0, 0)) Month)
[ "2 tháng vừa rồi"
, "2 tháng qua"
]
, examples (datetimeInterval ((2017, 3, 1, 0, 0, 0), (2017, 6, 1, 0, 0, 0)) Month)
[ "3 tháng tới"
, "ba tháng tiếp theo"
]
, examples (datetimeInterval ((2015, 1, 1, 0, 0, 0), (2017, 1, 1, 0, 0, 0)) Year)
[ "2 năm vừa rồi"
]
, examples (datetimeInterval ((2018, 1, 1, 0, 0, 0), (2021, 1, 1, 0, 0, 0)) Year)
[ "3 năm tới"
, "3 năm tiếp theo"
]
, examples (datetime (2017, 2, 2, 13, 0, 0) Minute)
[ "4pm CET"
]
, examples (datetime (2017, 2, 2, 14, 0, 0) Hour)
[ "hôm nay lúc 2 giờ chiều"
, "lúc 2 giờ chiều"
]
, examples (datetime (2017, 4, 23, 16, 0, 0) Minute)
[ "lúc 4:00 chiều ngày 23/4"
]
, examples (datetime (2017, 10, 12, 0, 0, 0) Day)
[ "ngày 12/10"
]
, examples (datetime (2017, 4, 23, 16, 0, 0) Hour)
[ "lúc 4 giờ chiều ngày 23 tháng 4"
]
, examples (datetime (2017, 2, 3, 15, 0, 0) Hour)
[ "3 giờ chiều ngày mai"
]
, examples (datetime (2017, 2, 2, 13, 30, 0) Minute)
[ "lúc 1:30 chiều"
, "lúc 1 giờ 30 chiều"
]
, examples (datetimeInterval ((2017, 2, 2, 13, 0, 0), (2017, 2, 2, 17, 0, 0)) Hour)
[ "sau bữa trưa"
]
, examples (datetime (2017, 2, 2, 10, 30, 0) Minute)
[ "10:30"
]
, examples (datetimeInterval ((2017, 2, 2, 4, 0, 0), (2017, 2, 2, 12, 0, 0)) Hour)
[ "buổi sáng nay"
]
, examples (datetime (2017, 2, 6, 0, 0, 0) Day)
[ "thứ hai tới"
, "thứ 2 tới"
]
, examples (datetime (2017, 4, 1, 0, 0, 0) Month)
[ "tháng 4"
, "tháng tư"
]
, examples (datetime (2017, 12, 25, 0, 0, 0) Day)
[ "giáng sinh"
, "ngày giáng sinh"
]
]
| facebookincubator/duckling | Duckling/Time/VI/Corpus.hs | bsd-3-clause | 13,439 | 0 | 11 | 5,531 | 4,271 | 2,601 | 1,670 | 281 | 1 |
{-# LANGUAGE MultiParamTypeClasses,TypeFamilies #-}
module Examples.Applyable.TestQQ where
import QuickWeave.Runtime.Applyable as QRApp
import QuickWeave.QuasiQuoter
data Exp = Var String
| App Exp Exp
deriving Show
instance Applyable Exp Exp where
type Result Exp Exp = Exp
fromApp = App
qq = qweaveQQWith ["OverridableApplications"]
-- ghci> :set -XQuasiQuotes
-- ghci> [qq| (Var "f") (Var "x")|]
-- App (Var "f") (Var "x")
| shayan-najd/QuickWeave | Examples/Applyable/ApplyQQ.hs | bsd-3-clause | 462 | 0 | 6 | 95 | 80 | 49 | 31 | 11 | 1 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
-------------------------------------------------------------------------------------
-- | SSA Monad ----------------------------------------------------------------------
-------------------------------------------------------------------------------------
module Language.Nano.SSA.SSAMonad (
-- * SSA Information
SsaInfo (..)
-- * SSA Monad
, SSAM
, ssaError
, execute
-- * SSA Environment
, SsaEnv
, setSsaEnv
, getSsaEnv
, updSsaEnv
, extSsaEnv
, findSsaEnv
-- * Access Annotations
, addAnn
, getAnns
-- * Immutable Variables
, isImmutable
, getImmutables
, setImmutables
, addImmutables
) where
import Control.Applicative ((<$>))
import Control.Monad
import Control.Monad.State
import Control.Monad.Error
import qualified Data.HashMap.Strict as M
import Language.Nano.Errors
import Language.Nano.Env
import Language.Nano.Types (dummySpan)
import Language.Nano.Typecheck.Types
import Language.ECMAScript3.Syntax
import Language.ECMAScript3.Parser (SourceSpan (..))
import Language.Fixpoint.Misc
import Text.Printf (printf)
import Text.Parsec.Pos
type SSAM = ErrorT String (State SsaState)
data SsaState = SsaST { immutables :: Env () -- ^ globals
, names :: SsaEnv -- ^ current SSA names
, count :: !Int -- ^ fresh index
, anns :: !AnnInfo -- ^ built up map of annots
}
type SsaEnv = Env SsaInfo
newtype SsaInfo = SI (Id SourceSpan) deriving (Eq)
-------------------------------------------------------------------------------------
extSsaEnv :: [Id SourceSpan] -> SsaEnv -> SsaEnv
-------------------------------------------------------------------------------------
extSsaEnv xs = envAdds [(x, SI x) | x <- xs]
-------------------------------------------------------------------------------------
getSsaEnv :: SSAM SsaEnv
-------------------------------------------------------------------------------------
getSsaEnv = names <$> get
-------------------------------------------------------------------------------------
addImmutables :: Env () -> SSAM ()
-------------------------------------------------------------------------------------
addImmutables z = modify $ \st -> st { immutables = envExt z (immutables st) }
where
envExt x y = envFromList (envToList x ++ envToList y)
-------------------------------------------------------------------------------------
setImmutables :: Env () -> SSAM ()
-------------------------------------------------------------------------------------
setImmutables z = modify $ \st -> st { immutables = z }
-------------------------------------------------------------------------------------
getImmutables :: SSAM (Env ())
-------------------------------------------------------------------------------------
getImmutables = immutables <$> get
-------------------------------------------------------------------------------------
setSsaEnv :: SsaEnv -> SSAM ()
-------------------------------------------------------------------------------------
setSsaEnv θ = modify $ \st -> st { names = θ }
-------------------------------------------------------------------------------------
updSsaEnv :: SourceSpan -> Id SourceSpan -> SSAM (Id SourceSpan)
-------------------------------------------------------------------------------------
updSsaEnv l x
= do imm <- isImmutable x
when imm $ ssaError l $ errorWriteImmutable x
n <- count <$> get
let x' = newId l x n
modify $ \st -> st {names = envAdds [(x, SI x')] (names st)} {count = 1 + n}
return x'
---------------------------------------------------------------------------------
isImmutable :: Id SourceSpan -> SSAM Bool
---------------------------------------------------------------------------------
isImmutable x = envMem x . immutables <$> get
newId :: SourceSpan -> Id SourceSpan -> Int -> Id SourceSpan
newId l (Id _ x) n = Id l (x ++ "_SSA_" ++ show n)
-------------------------------------------------------------------------------
findSsaEnv :: Id SourceSpan -> SSAM (Maybe (Id SourceSpan))
-------------------------------------------------------------------------------
findSsaEnv x
= do θ <- names <$> get
case envFindTy x θ of
Just (SI i) -> return $ Just i
Nothing -> return Nothing
-- allNames = do xs <- map fst . envToList . names <$> get
-- ys <- map fst . envToList . immutables <$> get
-- return $ xs ++ ys
-------------------------------------------------------------------------------
addAnn :: SourceSpan -> Fact -> SSAM ()
-------------------------------------------------------------------------------
addAnn l f = modify $ \st -> st { anns = inserts l f (anns st) }
-------------------------------------------------------------------------------
getAnns :: SSAM AnnInfo
-------------------------------------------------------------------------------
getAnns = anns <$> get
-------------------------------------------------------------------------------
ssaError :: SourceSpan -> String -> SSAM a
-------------------------------------------------------------------------------
ssaError l msg = throwError $ printf "ERROR at %s : %s" (ppshow l) msg
-- inserts l xs m = M.insert l (xs ++ M.lookupDefault [] l m) m
-------------------------------------------------------------------------------
execute :: SSAM a -> Either (SourceSpan, String) a
-------------------------------------------------------------------------------
execute act
= case runState (runErrorT act) initState of
(Left err, _) -> Left (dummySpan, err)
(Right x, _) -> Right x
initState :: SsaState
initState = SsaST envEmpty envEmpty 0 M.empty
| UCSD-PL/nano-js | Language/Nano/SSA/SSAMonad.hs | bsd-3-clause | 6,215 | 0 | 15 | 1,298 | 1,127 | 618 | 509 | 88 | 2 |
module Main where
import Control.Applicative
import Control.Concurrent
import Control.Exception
import Control.Monad
import qualified Data.ByteString as BS
import Data.Either
import Data.Maybe
import Data.Text (pack)
import Data.Text.Encoding (encodeUtf8)
import Network (listenOn, PortID(..), PortNumber)
import Network.HTTP
import Network.Socket
import Network.Stream
import System.Timeout
main = withSocketsDo $ do
http_socket <- listenOn $ PortNumber 9090
dispatch_on_accept http_socket $ either handle_failed_request handle_valid_request
sClose http_socket
handle_failed_request failure = do
let response = Response (4,0,0) "Bad Request" [mkHeader HdrConnection "close"]
(encodeUtf8 $ pack $ show failure)
return (response, True)
handle_valid_request request = do
let request_body = rqBody request
let done = Just "close" == findHeader HdrConnection request
response = Response (2,0,0) "OK" [] (encodeUtf8 $ pack $ show request_body)
response' = if done then insertHeader HdrConnection "close" response else response
return (response', done)
dispatch_on_accept http_socket handler = forever $ accept http_socket >>= forkIO . httpHandler . fst
where
httpHandler client_socket = bracket (socketConnection "client" 0 client_socket)
Network.HTTP.close
client_interact
client_interact :: HandleStream BS.ByteString -> IO ()
client_interact byte_stream = loop
where loop = do
mbrequest <- timeout (15 * 1000000) $ receiveHTTP byte_stream
case mbrequest of
Nothing -> return ()
Just request -> do
(response, done) <- handler request
respondHTTP byte_stream response
unless done loop
| coreyoconnor/tiny-http-hp | TinyHttp.hs | bsd-3-clause | 1,966 | 0 | 17 | 581 | 502 | 257 | 245 | 43 | 2 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PolyKinds #-}
module Control.LnMonad.Reader where
import Data.LnFunctor
import Data.LnFunctor.Apply
import Data.LnFunctor.Bind
import Control.LnApplicative
import Type.Families
newtype Reader
(r :: k -> *)
(i :: k)
(j :: k)
(a :: *) = Reader
{ unReader :: r i -> a
}
class Forget (r :: k -> *) (i :: k) (j :: k) where
forget :: r j -> r i
instance IxFunctor (Reader r) where
imap f (Reader mi) = Reader $ f . mi
instance LnFunctor (Reader r) where
type L (Reader r) i k = Forget r i k
type R (Reader r) j l = ()
weaken (Reader (m :: r i -> a)) =
Reader $ m . forget
strengthen (Reader m) = Reader m
lmap f = imap f . stretch
instance LnInitial (Reader r) where
type Init (Reader r) i j = ()
instance LnApply (Reader r) where
type Link (Reader r) i j k l h m =
(Forget r i h, Forget r k h)
lap (Reader (fi :: r i -> a -> b)) (Reader (ak :: r k -> a))
= Reader $ \rh -> fi (forget rh) $ ak (forget rh)
instance LnApplicative (Reader r) where
lpure = Reader . const
instance LnBind (Reader r) where
lbind (Reader (ai :: r i -> a)) (fk :: a -> Reader r k l b)
= Reader $ \rh -> unReader (fk $ ai $ forget rh) $ forget rh
ask :: Reader r i i (r i)
ask = Reader id
local :: (r i -> r k) -> Reader r k l a -> Reader r i l a
local f (Reader ak) = Reader $ ak . f
reader :: (r i -> a) -> Reader r i j a
reader = Reader
| kylcarte/lnfunctors | src/Control/LnMonad/Reader.hs | bsd-3-clause | 1,716 | 0 | 12 | 405 | 744 | 392 | 352 | 52 | 1 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Data.Kicad.SExpr.Parse
( parse
, parseWithFilename
)
where
import Text.ParserCombinators.Parsec hiding (spaces, parse)
import qualified Text.ParserCombinators.Parsec as Parsec (parse)
import Text.Parsec.Char (endOfLine)
import Text.Parsec (getPosition)
import Data.Kicad.SExpr.SExpr
{-| Parse a 'String' as a 'SExpr' or return an error. -}
parse :: String -> Either String SExpr
parse = parseWithFilename ""
{-| Parse a 'String' as a 'SExpr' giving a filename to use in the source code location -}
parseWithFilename :: String -> String -> Either String SExpr
parseWithFilename filename input =
case Parsec.parse parseListOrComment filename input of
Left err -> Left $ "Parse Error: " ++ show err
Right val -> Right val
parseListOrComment :: Parser SExpr
parseListOrComment = do
spaces
skipMany parseComment
s <- parseList
return s
parseComment :: Parser String
parseComment = do
char '#'
s <- many (noneOf "\r\n")
endOfLine
spaces
return s
parseList :: Parser SExpr
parseList = do
pos <- getPosition
char '('
spaces
list <- try parseExpr `sepEndBy` spaces
char ')'
spaces
return $ List pos list
parseExpr :: Parser SExpr
parseExpr = try parseString
<|> try parseListOrComment
<?> "a double, string or s-expression"
parseString :: Parser SExpr
parseString =
do pos <- getPosition
str <- parseQuotedString <|> parseUnquotedString <?> "string"
return $ Atom pos str
where
parseQuotedString = do
char '"'
x <- many (noneOf "\\\"" <|> (char '\\' >> anyChar))
char '"'
return x
parseUnquotedString = many1 (noneOf " ()\r\n")
spaces = skipMany spaceChar
spaceChar = oneOf "\r\n\t "
| kasbah/haskell-kicad-data | Data/Kicad/SExpr/Parse.hs | mit | 1,937 | 0 | 15 | 506 | 479 | 236 | 243 | 56 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{- |
Module : Network.MPD.Applicative.Status
Copyright : (c) Joachim Fasting 2012
License : MIT
Maintainer : [email protected]
Stability : stable
Portability : unportable
Querying MPD's status.
-}
module Network.MPD.Applicative.Status
( clearError
, currentSong
, idle
, noidle
, status
, stats
) where
import Control.Monad
import Control.Arrow ((***))
import Network.MPD.Util
import Network.MPD.Applicative.Internal
import Network.MPD.Commands.Arg hiding (Command)
import Network.MPD.Commands.Parse
import Network.MPD.Commands.Types
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.UTF8 as UTF8
-- | Clear current error message in status.
clearError :: Command ()
clearError = Command emptyResponse ["clearerror"]
-- | Song metadata for currently playing song, if any.
currentSong :: Command (Maybe Song)
currentSong = Command (liftParser parseMaybeSong) ["currentsong"]
takeSubsystems :: [ByteString] -> Either String [Subsystem]
takeSubsystems = mapM f . toAssocList
where
f :: (ByteString, ByteString) -> Either String Subsystem
f ("changed", system) =
case system of
"database" -> Right DatabaseS
"update" -> Right UpdateS
"stored_playlist" -> Right StoredPlaylistS
"playlist" -> Right PlaylistS
"player" -> Right PlayerS
"mixer" -> Right MixerS
"output" -> Right OutputS
"options" -> Right OptionsS
k -> Left ("Unknown subsystem: " ++ UTF8.toString k)
f x = Left ("idle: Unexpected " ++ show x)
-- | Wait until there is noteworthy change in one or more of MPD's
-- subsystems.
-- When active, only 'noidle' commands are allowed.
idle :: [Subsystem] -> Command [Subsystem]
idle ss = Command (liftParser takeSubsystems) c
where
c = ["idle" <@> foldr (<++>) (Args []) ss]
-- | Cancel an 'idle' request.
noidle :: Command ()
noidle = Command emptyResponse ["noidle"]
-- | Get database statistics.
stats :: Command Stats
stats = Command (liftParser parseStats) ["stats"]
-- | Get the current status of the player.
status :: Command Status
status = Command (liftParser parseStatus) ["status"]
where
-- Builds a 'Status' instance from an assoc. list.
parseStatus :: [ByteString] -> Either String Status
parseStatus = foldM go def . toAssocList
where
go a p@(k, v) = case k of
"volume" -> num $ \x -> a { stVolume = x }
"repeat" -> bool $ \x -> a { stRepeat = x }
"random" -> bool $ \x -> a { stRandom = x }
"single" -> bool $ \x -> a { stSingle = x }
"consume" -> bool $ \x -> a { stConsume = x }
"playlist" -> num $ \x -> a { stPlaylistVersion = x }
"playlistlength" -> num $ \x -> a { stPlaylistLength = x }
"state" -> state $ \x -> a { stState = x}
"song" -> num $ \x -> a { stSongPos = Just x }
"songid" -> num $ \x -> a { stSongID = Just $ Id x }
"nextsong" -> num $ \x -> a { stNextSongPos = Just x }
"nextsongid" -> num $ \x -> a { stNextSongID = Just $ Id x }
"time" -> time $ \x -> a { stTime = x }
"elapsed" -> frac $ \x -> a { stTime = (x, snd $ stTime a) }
"bitrate" -> num $ \x -> a { stBitrate = x }
"xfade" -> num $ \x -> a { stXFadeWidth = x }
"mixrampdb" -> frac $ \x -> a { stMixRampdB = x }
"mixrampdelay" -> frac $ \x -> a { stMixRampDelay = x }
"audio" -> audio $ \x -> a { stAudio = x }
"updating_db" -> num $ \x -> a { stUpdatingDb = Just x }
"error" -> Right a { stError = Just (UTF8.toString v) }
_ -> unexpectedPair
where
unexpectedPair = Left ("unexpected key-value pair: " ++ show p)
num f = maybe unexpectedPair (Right . f) (parseNum v)
bool f = maybe unexpectedPair (Right . f) (parseBool v)
frac f = maybe unexpectedPair (Right . f) (parseFrac v)
-- This is sometimes "audio: 0:?:0", so we ignore any parse
-- errors.
audio f = Right $ maybe a f (parseTriple ':' parseNum v)
time f = case parseFrac *** parseNum $ breakChar ':' v of
(Just a_, Just b) -> (Right . f) (a_, b)
_ -> unexpectedPair
state f = case v of
"play" -> (Right . f) Playing
"pause" -> (Right . f) Paused
"stop" -> (Right . f) Stopped
_ -> unexpectedPair
| sol/libmpd-haskell | src/Network/MPD/Applicative/Status.hs | mit | 5,472 | 0 | 18 | 2,252 | 1,357 | 737 | 620 | 83 | 26 |
import Text.Printf
main = do
putStrLn ("Joining " ++ "strings.")
putStrLn "First line\nSecond line"
let value = 3
printf "The value %s is interpolated" (show value)
| Bigsby/langs | src/hs/strings.hs | apache-2.0 | 183 | 0 | 9 | 44 | 53 | 24 | 29 | 6 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS -fno-warn-orphans #-}
module Optical.Bit
(
-- * Bits
Bit(..)
, pattern On
, pattern Off
, _Bit
-- * Bit Vectors with rank
, BitVector(..)
, _BitVector
, rank
, size
, singleton
-- * Vectors of Bits
, UM.MVector(MV_Bit)
, U.Vector(V_Bit)
) where
import Control.Lens as L
import Control.Monad
import Data.Bits
import Data.Data
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as GM
import Data.Vector.Internal.Check as Ck
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import Data.Word
import Prelude hiding (null)
#define BOUNDS_CHECK(f) (Ck.f __FILE__ __LINE__ Ck.Bounds)
-- | A simple newtype around a 'Bool'
--
-- The principal use of this is that a 'U.Vector' 'Bit' is densely
-- packed into individual bits rather than stored as one entry per 'Word8'.
newtype Bit = Bit { getBit :: Bool }
deriving (Eq,Ord,Enum,Bounded,Data,Typeable)
instance Show Bit where
show On = "On"
show _ = "Off"
pattern On :: Bit
pattern On = Bit True
pattern Off :: Bit
pattern Off = Bit False
instance Rewrapped Bit Bit
instance Wrapped Bit where
type Unwrapped Bit = Bool
_Wrapped' = _Bit
{-# INLINE _Wrapped' #-}
-- | 'Bit' and 'Bool' are isomorphic.
_Bit :: Iso' Bit Bool
_Bit = iso getBit Bit
{-# INLINE _Bit #-}
instance UM.Unbox Bit
data instance UM.MVector s Bit = MV_Bit {-# UNPACK #-} !Int {-# UNPACK #-} !(UM.MVector s Word64)
instance GM.MVector U.MVector Bit where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
{-# INLINE basicUnsafeReplicate #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_Bit n _) = n
basicUnsafeSlice i n (MV_Bit _ u) = MV_Bit n $ GM.basicUnsafeSlice i (wds n) u
basicOverlaps (MV_Bit _ v1) (MV_Bit _ v2) = GM.basicOverlaps v1 v2
basicUnsafeNew n = do
v <- GM.basicUnsafeNew (wds n)
return $ MV_Bit n v
basicUnsafeReplicate n (Bit b) = do
v <- GM.basicUnsafeReplicate (wds n) (if b then -1 else 0)
return $ MV_Bit n v
basicUnsafeRead (MV_Bit _ u) i = do
w <- GM.basicUnsafeRead u (wd i)
return $ Bit $ testBit w (bt i)
basicUnsafeWrite (MV_Bit _ u) i (Bit b) = do
let wn = wd i
w <- GM.basicUnsafeRead u wn
GM.basicUnsafeWrite u wn $ if b then setBit w (bt i) else clearBit w (bt i)
basicClear (MV_Bit _ u) = GM.basicClear u
basicSet (MV_Bit _ u) (Bit b) = GM.basicSet u $ if b then -1 else 0
basicUnsafeCopy (MV_Bit _ u1) (MV_Bit _ u2) = GM.basicUnsafeCopy u1 u2
basicUnsafeMove (MV_Bit _ u1) (MV_Bit _ u2) = GM.basicUnsafeMove u1 u2
basicUnsafeGrow (MV_Bit _ u) n = liftM (MV_Bit n) (GM.basicUnsafeGrow u (wds n))
basicInitialize (MV_Bit _ u) = GM.basicInitialize u
data instance U.Vector Bit = V_Bit {-# UNPACK #-} !Int {-# UNPACK #-} !(U.Vector Word64)
instance G.Vector U.Vector Bit where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicLength (V_Bit n _) = n
basicUnsafeFreeze (MV_Bit n u) = liftM (V_Bit n) (G.basicUnsafeFreeze u)
basicUnsafeThaw (V_Bit n u) = liftM (MV_Bit n) (G.basicUnsafeThaw u)
basicUnsafeSlice i n (V_Bit _ u) = V_Bit n (G.basicUnsafeSlice i (wds n) u)
basicUnsafeIndexM (V_Bit _ u) i = do
w <- G.basicUnsafeIndexM u (wd i)
return $ Bit $ testBit w (bt i)
basicUnsafeCopy (MV_Bit _ mu) (V_Bit _ u) = G.basicUnsafeCopy mu u
elemseq _ b z = b `seq` z
#define BOUNDS_CHECK(f) (Ck.f __FILE__ __LINE__ Ck.Bounds)
-- | A BitVector support for naïve /O(1)/ 'rank'.
data BitVector = BitVector !(U.Vector Bit) {-# UNPACK #-} !(U.Vector Int)
deriving (Eq,Ord,Show)
-- | /O(n) embedding/ A 'BitVector' is isomorphic to a vector of bits. It just carries extra information.
_BitVector :: Iso' BitVector (U.Vector Bit)
_BitVector = iso (\(BitVector v _) -> v) $ \v@(V_Bit _ ws) -> BitVector v $ G.scanl (\a b -> a + popCount b) 0 ws
{-# INLINE _BitVector #-}
-- | /O(1)/. @'rank' i v@ counts the number of 'True' bits up through and including the position @i@
rank :: BitVector -> Int -> Int
rank (BitVector (V_Bit n ws) ps) i
= BOUNDS_CHECK(checkIndex) "rank" i n
$ (ps U.! w) + popCount ((ws U.! w) .&. (bit (bt i + 1) - 1))
where w = wd i
{-# INLINE rank #-}
instance AsEmpty BitVector where
_Empty = nearly (_BitVector # G.empty) ((== 0) . size)
-- | /O(1)/. Return the size of the 'BitVector'.
size :: BitVector -> Int
size (BitVector (V_Bit n _) _) = n
{-# INLINE size #-}
type instance Index BitVector = Int
type instance IxValue BitVector = Bool
-- instance Ixed BitVector where
-- ix f (BitVector (V_Bit n v) r) =
{-
instance (Functor f, Contravariant f) => Contains f BitVector where
contains i f (BitVector n as _) = coerce $ L.indexed f i (0 <= i && i < n && getBit (as U.! i))
-}
-- | Construct a 'BitVector' with a single element.
singleton :: Bool -> BitVector
singleton b = _BitVector # U.singleton (Bit b)
{-# INLINE singleton #-}
wds :: Int -> Int
wds x = unsafeShiftR (x + 63) 6
{-# INLINE wds #-}
wd :: Int -> Int
wd x = unsafeShiftR x 6
{-# INLINE wd #-}
bt :: Int -> Int
bt x = x .&. 63
{-# INLINE bt #-}
-- Maybe instance ------------------------------------------------------
instance UM.Unbox a => UM.Unbox (Maybe a)
data instance UM.MVector s (Maybe a) = MV_Maybe !(UM.MVector s Bit) !(UM.MVector s a)
instance U.Unbox a => GM.MVector U.MVector (Maybe a) where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
{-# INLINE basicUnsafeReplicate #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_Maybe b _) = GM.basicLength b
basicUnsafeSlice i n (MV_Maybe b v) = MV_Maybe (GM.basicUnsafeSlice i n b) (GM.basicUnsafeSlice i n v)
basicOverlaps (MV_Maybe b1 v1) (MV_Maybe b2 v2) = GM.basicOverlaps b1 b2 && GM.basicOverlaps v1 v2
basicUnsafeNew n = do
b <- GM.basicUnsafeNew n
v <- GM.basicUnsafeNew n
return $! MV_Maybe b v
basicUnsafeReplicate n Nothing = do
b <- GM.basicUnsafeReplicate n Off
v <- GM.basicUnsafeNew n
return $! MV_Maybe b v
basicUnsafeReplicate n (Just a) = do
b <- GM.basicUnsafeReplicate n On
v <- GM.basicUnsafeReplicate n a
return $! MV_Maybe b v
basicUnsafeRead (MV_Maybe b v) i = do
Bit e <- GM.basicUnsafeRead b i
if e then Just `liftM` GM.basicUnsafeRead v i else return Nothing
basicUnsafeWrite (MV_Maybe b _) i Nothing =
GM.basicUnsafeWrite b i Off
basicUnsafeWrite (MV_Maybe b v) i (Just a) = do
GM.basicUnsafeWrite b i On
GM.basicUnsafeWrite v i a
basicClear (MV_Maybe b u) = GM.basicClear b >> GM.basicClear u
basicSet (MV_Maybe b _) Nothing = GM.basicSet b Off
basicSet (MV_Maybe b v) (Just a) = do
GM.basicSet b On
GM.basicSet v a
basicUnsafeCopy (MV_Maybe b1 v1) (MV_Maybe b2 v2) = do
GM.basicUnsafeCopy b1 b2
GM.basicUnsafeCopy v1 v2
basicUnsafeMove (MV_Maybe b1 v1) (MV_Maybe b2 v2) = do
GM.basicUnsafeMove b1 b2
GM.basicUnsafeMove v1 v2
basicUnsafeGrow (MV_Maybe b v) n = do
b' <- GM.basicUnsafeGrow b n
v' <- GM.basicUnsafeGrow v n
return $! MV_Maybe b' v'
basicInitialize (MV_Maybe b v) = GM.basicInitialize b >> GM.basicInitialize v
data instance U.Vector (Maybe a) = V_Maybe !(U.Vector Bit) !(U.Vector a)
instance U.Unbox a => G.Vector U.Vector (Maybe a) where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicLength (V_Maybe b _) = G.basicLength b
basicUnsafeFreeze (MV_Maybe mb mv) = do
b <- G.basicUnsafeFreeze mb
v <- G.basicUnsafeFreeze mv
return $! V_Maybe b v
basicUnsafeThaw (V_Maybe b v) = do
mb <- G.basicUnsafeThaw b
mv <- G.basicUnsafeThaw v
return $! MV_Maybe mb mv
basicUnsafeSlice i n (V_Maybe b v) = V_Maybe (G.basicUnsafeSlice i n b) (G.basicUnsafeSlice i n v)
basicUnsafeIndexM (V_Maybe b v) i = do
Bit e <- G.basicUnsafeIndexM b i
if e then Just `liftM` G.basicUnsafeIndexM v i else return Nothing
basicUnsafeCopy (MV_Maybe mb mv) (V_Maybe b v) = do
G.basicUnsafeCopy mb b
G.basicUnsafeCopy mv v
elemseq _ Nothing z = z
elemseq _ (Just a) z = a `seq` z
| cchalmers/optical | src/Optical/Bit.hs | bsd-3-clause | 9,343 | 0 | 14 | 2,144 | 2,880 | 1,465 | 1,415 | 230 | 1 |
{-# language CPP #-}
#ifndef ENABLE_INTERNAL_DOCUMENTATION
{-# OPTIONS_HADDOCK hide #-}
#endif
module OpenCV.Internal.C.PlacementNew ( PlacementNew(..) ) where
import "base" Foreign.Ptr ( Ptr )
--------------------------------------------------------------------------------
-- | Copy source to destination using C++'s placement new feature
class PlacementNew a where
-- | Copy source to destination using C++'s placement new feature
--
-- This method is intended for types that are proxies for actual
-- types in C++.
--
-- > new(dst) CType(*src)
--
-- The copy should be performed by constructing a new object in
-- the memory pointed to by @dst@. The new object is initialised
-- using the value of @src@. This design allow underlying
-- structures to be shared depending on the implementation of
-- @CType@.
placementNew
:: Ptr a -- ^ Source
-> Ptr a -- ^ Destination
-> IO ()
placementDelete
:: Ptr a
-> IO ()
| lukexi/haskell-opencv | src/OpenCV/Internal/C/PlacementNew.hs | bsd-3-clause | 1,017 | 0 | 10 | 244 | 98 | 62 | 36 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module T14174a where
import Data.Kind
data TyFun :: * -> * -> *
type a ~> b = TyFun a b -> *
infixr 0 ~>
type family Apply (f :: k1 ~> k2) (x :: k1) :: k2
type a @@ b = Apply a b
infixl 9 @@
data FunArrow = (:->) | (:~>)
class FunType (arr :: FunArrow) where
type Fun (k1 :: Type) arr (k2 :: Type) :: Type
class FunType arr => AppType (arr :: FunArrow) where
type App k1 arr k2 (f :: Fun k1 arr k2) (x :: k1) :: k2
type FunApp arr = (FunType arr, AppType arr)
instance FunType (:->) where
type Fun k1 (:->) k2 = k1 -> k2
instance AppType (:->) where
type App k1 (:->) k2 (f :: k1 -> k2) x = f x
instance FunType (:~>) where
type Fun k1 (:~>) k2 = k1 ~> k2
instance AppType (:~>) where
type App k1 (:~>) k2 (f :: k1 ~> k2) x = f @@ x
infixr 0 -?>
type (-?>) (k1 :: Type) (k2 :: Type) (arr :: FunArrow) = Fun k1 arr k2
type family ElimBool (p :: Bool -> Type)
(z :: Bool)
(pFalse :: p False)
(pTrue :: p True)
:: p z where
-- Commenting out the line below makes the panic go away
ElimBool p z pFalse pTrue = ElimBoolPoly (:->) p z pFalse pTrue
type family ElimBoolPoly (arr :: FunArrow)
(p :: (Bool -?> Type) arr)
(z :: Bool)
(pFalse :: App Bool arr Type p False)
(pTrue :: App Bool arr Type p True)
:: App Bool arr Type p z
| shlevy/ghc | testsuite/tests/polykinds/T14174a.hs | bsd-3-clause | 1,602 | 13 | 13 | 511 | 587 | 337 | 250 | -1 | -1 |
{-
Author: George Karachalias <[email protected]>
Pattern Matching Coverage Checking.
-}
{-# LANGUAGE CPP, GADTs, DataKinds, KindSignatures #-}
module Check (
-- Checking and printing
checkSingle, checkMatches, isAnyPmCheckEnabled,
-- See Note [Type and Term Equality Propagation]
genCaseTmCs1, genCaseTmCs2
) where
#include "HsVersions.h"
import TmOracle
import DynFlags
import HsSyn
import TcHsSyn
import Id
import ConLike
import DataCon
import Name
import FamInstEnv
import TysWiredIn
import TyCon
import SrcLoc
import Util
import Outputable
import FastString
import DsMonad -- DsM, initTcDsForSolver, getDictsDs
import TcSimplify -- tcCheckSatisfiability
import TcType -- toTcType, toTcTypeBag
import Bag
import ErrUtils
import MonadUtils -- MonadIO
import Var -- EvVar
import Type
import UniqSupply
import DsGRHSs -- isTrueLHsExpr
import Data.List -- find
import Data.Maybe -- isNothing, isJust, fromJust
import Control.Monad -- liftM3, forM
import Coercion
import TcEvidence
import IOEnv
{-
This module checks pattern matches for:
\begin{enumerate}
\item Equations that are redundant
\item Equations with inaccessible right-hand-side
\item Exhaustiveness
\end{enumerate}
The algorithm is based on the paper:
"GADTs Meet Their Match:
Pattern-matching Warnings That Account for GADTs, Guards, and Laziness"
http://people.cs.kuleuven.be/~george.karachalias/papers/p424-karachalias.pdf
%************************************************************************
%* *
Pattern Match Check Types
%* *
%************************************************************************
-}
type PmM a = DsM a
data PatTy = PAT | VA -- Used only as a kind, to index PmPat
-- The *arity* of a PatVec [p1,..,pn] is
-- the number of p1..pn that are not Guards
data PmPat :: PatTy -> * where
PmCon :: { pm_con_con :: DataCon
, pm_con_arg_tys :: [Type]
, pm_con_tvs :: [TyVar]
, pm_con_dicts :: [EvVar]
, pm_con_args :: [PmPat t] } -> PmPat t
-- For PmCon arguments' meaning see @ConPatOut@ in hsSyn/HsPat.hs
PmVar :: { pm_var_id :: Id } -> PmPat t
PmLit :: { pm_lit_lit :: PmLit } -> PmPat t -- See Note [Literals in PmPat]
PmNLit :: { pm_lit_id :: Id
, pm_lit_not :: [PmLit] } -> PmPat 'VA
PmGrd :: { pm_grd_pv :: PatVec
, pm_grd_expr :: PmExpr } -> PmPat 'PAT
-- data T a where
-- MkT :: forall p q. (Eq p, Ord q) => p -> q -> T [p]
-- or MkT :: forall p q r. (Eq p, Ord q, [p] ~ r) => p -> q -> T r
type Pattern = PmPat 'PAT -- ^ Patterns
type ValAbs = PmPat 'VA -- ^ Value Abstractions
type PatVec = [Pattern] -- ^ Pattern Vectors
data ValVec = ValVec [ValAbs] Delta -- ^ Value Vector Abstractions
-- | Term and type constraints to accompany each value vector abstraction.
-- For efficiency, we store the term oracle state instead of the term
-- constraints. TODO: Do the same for the type constraints?
data Delta = MkDelta { delta_ty_cs :: Bag EvVar
, delta_tm_cs :: TmState }
type ValSetAbs = [ValVec] -- ^ Value Set Abstractions
type Uncovered = ValSetAbs
-- Instead of keeping the whole sets in memory, we keep a boolean for both the
-- covered and the divergent set (we store the uncovered set though, since we
-- want to print it). For both the covered and the divergent we have:
--
-- True <=> The set is non-empty
--
-- hence:
-- C = True ==> Useful clause (no warning)
-- C = False, D = True ==> Clause with inaccessible RHS
-- C = False, D = False ==> Redundant clause
type Triple = (Bool, Uncovered, Bool)
-- | Pattern check result
--
-- * Redundant clauses
-- * Not-covered clauses
-- * Clauses with inaccessible RHS
type PmResult = ([Located [LPat Id]], Uncovered, [Located [LPat Id]])
{-
%************************************************************************
%* *
Entry points to the checker: checkSingle and checkMatches
%* *
%************************************************************************
-}
-- | Check a single pattern binding (let)
checkSingle :: DynFlags -> DsMatchContext -> Id -> Pat Id -> DsM ()
checkSingle dflags ctxt@(DsMatchContext _ locn) var p = do
mb_pm_res <- tryM (checkSingle' locn var p)
case mb_pm_res of
Left _ -> warnPmIters dflags ctxt
Right res -> dsPmWarn dflags ctxt res
-- | Check a single pattern binding (let)
checkSingle' :: SrcSpan -> Id -> Pat Id -> DsM PmResult
checkSingle' locn var p = do
resetPmIterDs -- set the iter-no to zero
fam_insts <- dsGetFamInstEnvs
clause <- translatePat fam_insts p
missing <- mkInitialUncovered [var]
(cs,us,ds) <- runMany (pmcheckI clause []) missing -- no guards
return $ case (cs,ds) of
(True, _ ) -> ([], us, []) -- useful
(False, False) -> ( m, us, []) -- redundant
(False, True ) -> ([], us, m) -- inaccessible rhs
where m = [L locn [L locn p]]
-- | Check a matchgroup (case, functions, etc.)
checkMatches :: DynFlags -> DsMatchContext
-> [Id] -> [LMatch Id (LHsExpr Id)] -> DsM ()
checkMatches dflags ctxt vars matches = do
mb_pm_res <- tryM (checkMatches' vars matches)
case mb_pm_res of
Left _ -> warnPmIters dflags ctxt
Right res -> dsPmWarn dflags ctxt res
-- | Check a matchgroup (case, functions, etc.)
checkMatches' :: [Id] -> [LMatch Id (LHsExpr Id)] -> DsM PmResult
checkMatches' vars matches
| null matches = return ([], [], [])
| otherwise = do
resetPmIterDs -- set the iter-no to zero
missing <- mkInitialUncovered vars
(rs,us,ds) <- go matches missing
return (map hsLMatchToLPats rs, us, map hsLMatchToLPats ds)
where
go [] missing = return ([], missing, [])
go (m:ms) missing = do
fam_insts <- dsGetFamInstEnvs
(clause, guards) <- translateMatch fam_insts m
(cs, missing', ds) <- runMany (pmcheckI clause guards) missing
(rs, final_u, is) <- go ms missing'
return $ case (cs, ds) of
(True, _ ) -> ( rs, final_u, is) -- useful
(False, False) -> (m:rs, final_u, is) -- redundant
(False, True ) -> ( rs, final_u, m:is) -- inaccessible
hsLMatchToLPats :: LMatch id body -> Located [LPat id]
hsLMatchToLPats (L l (Match _ pats _ _)) = L l pats
{-
%************************************************************************
%* *
Transform source syntax to *our* syntax
%* *
%************************************************************************
-}
-- -----------------------------------------------------------------------
-- * Utilities
nullaryConPattern :: DataCon -> Pattern
-- Nullary data constructor and nullary type constructor
nullaryConPattern con =
PmCon { pm_con_con = con, pm_con_arg_tys = []
, pm_con_tvs = [], pm_con_dicts = [], pm_con_args = [] }
{-# INLINE nullaryConPattern #-}
truePattern :: Pattern
truePattern = nullaryConPattern trueDataCon
{-# INLINE truePattern #-}
-- | A fake guard pattern (True <- _) used to represent cases we cannot handle
fake_pat :: Pattern
fake_pat = PmGrd { pm_grd_pv = [truePattern]
, pm_grd_expr = PmExprOther EWildPat }
{-# INLINE fake_pat #-}
-- | Check whether a guard pattern is generated by the checker (unhandled)
isFakeGuard :: [Pattern] -> PmExpr -> Bool
isFakeGuard [PmCon { pm_con_con = c }] (PmExprOther EWildPat)
| c == trueDataCon = True
| otherwise = False
isFakeGuard _pats _e = False
-- | Generate a `canFail` pattern vector of a specific type
mkCanFailPmPat :: Type -> PmM PatVec
mkCanFailPmPat ty = do
var <- mkPmVar ty
return [var, fake_pat]
vanillaConPattern :: DataCon -> [Type] -> PatVec -> Pattern
-- ADT constructor pattern => no existentials, no local constraints
vanillaConPattern con arg_tys args =
PmCon { pm_con_con = con, pm_con_arg_tys = arg_tys
, pm_con_tvs = [], pm_con_dicts = [], pm_con_args = args }
{-# INLINE vanillaConPattern #-}
-- | Create an empty list pattern of a given type
nilPattern :: Type -> Pattern
nilPattern ty =
PmCon { pm_con_con = nilDataCon, pm_con_arg_tys = [ty]
, pm_con_tvs = [], pm_con_dicts = []
, pm_con_args = [] }
{-# INLINE nilPattern #-}
mkListPatVec :: Type -> PatVec -> PatVec -> PatVec
mkListPatVec ty xs ys = [PmCon { pm_con_con = consDataCon
, pm_con_arg_tys = [ty]
, pm_con_tvs = [], pm_con_dicts = []
, pm_con_args = xs++ys }]
{-# INLINE mkListPatVec #-}
-- | Create a (non-overloaded) literal pattern
mkLitPattern :: HsLit -> Pattern
mkLitPattern lit = PmLit { pm_lit_lit = PmSLit lit }
{-# INLINE mkLitPattern #-}
-- -----------------------------------------------------------------------
-- * Transform (Pat Id) into of (PmPat Id)
translatePat :: FamInstEnvs -> Pat Id -> PmM PatVec
translatePat fam_insts pat = case pat of
WildPat ty -> mkPmVars [ty]
VarPat id -> return [PmVar (unLoc id)]
ParPat p -> translatePat fam_insts (unLoc p)
LazyPat _ -> mkPmVars [hsPatType pat] -- like a variable
-- ignore strictness annotations for now
BangPat p -> translatePat fam_insts (unLoc p)
AsPat lid p -> do
-- Note [Translating As Patterns]
ps <- translatePat fam_insts (unLoc p)
let [e] = map vaToPmExpr (coercePatVec ps)
g = PmGrd [PmVar (unLoc lid)] e
return (ps ++ [g])
SigPatOut p _ty -> translatePat fam_insts (unLoc p)
-- See Note [Translate CoPats]
CoPat wrapper p ty
| isIdHsWrapper wrapper -> translatePat fam_insts p
| WpCast co <- wrapper, isReflexiveCo co -> translatePat fam_insts p
| otherwise -> do
ps <- translatePat fam_insts p
(xp,xe) <- mkPmId2Forms ty
let g = mkGuard ps (HsWrap wrapper (unLoc xe))
return [xp,g]
-- (n + k) ===> x (True <- x >= k) (n <- x-k)
NPlusKPat (L _ _n) _k1 _k2 _ge _minus ty -> mkCanFailPmPat ty
-- (fun -> pat) ===> x (pat <- fun x)
ViewPat lexpr lpat arg_ty -> do
ps <- translatePat fam_insts (unLoc lpat)
-- See Note [Guards and Approximation]
case all cantFailPattern ps of
True -> do
(xp,xe) <- mkPmId2Forms arg_ty
let g = mkGuard ps (HsApp lexpr xe)
return [xp,g]
False -> mkCanFailPmPat arg_ty
-- list
ListPat ps ty Nothing -> do
foldr (mkListPatVec ty) [nilPattern ty]
<$> translatePatVec fam_insts (map unLoc ps)
-- overloaded list
ListPat lpats elem_ty (Just (pat_ty, _to_list))
| Just e_ty <- splitListTyConApp_maybe pat_ty
, (_, norm_elem_ty) <- normaliseType fam_insts Nominal elem_ty
-- elem_ty is frequently something like
-- `Item [Int]`, but we prefer `Int`
, norm_elem_ty `eqType` e_ty ->
-- We have to ensure that the element types are exactly the same.
-- Otherwise, one may give an instance IsList [Int] (more specific than
-- the default IsList [a]) with a different implementation for `toList'
translatePat fam_insts (ListPat lpats e_ty Nothing)
-- See Note [Guards and Approximation]
| otherwise -> mkCanFailPmPat pat_ty
ConPatOut { pat_con = L _ (PatSynCon _) } ->
-- Pattern synonyms have a "matcher"
-- (see Note [Pattern synonym representation] in PatSyn.hs
-- We should be able to transform (P x y)
-- to v (Just (x, y) <- matchP v (\x y -> Just (x,y)) Nothing
-- That is, a combination of a variable pattern and a guard
-- But there are complications with GADTs etc, and this isn't done yet
mkCanFailPmPat (hsPatType pat)
ConPatOut { pat_con = L _ (RealDataCon con)
, pat_arg_tys = arg_tys
, pat_tvs = ex_tvs
, pat_dicts = dicts
, pat_args = ps } -> do
args <- translateConPatVec fam_insts arg_tys ex_tvs con ps
return [PmCon { pm_con_con = con
, pm_con_arg_tys = arg_tys
, pm_con_tvs = ex_tvs
, pm_con_dicts = dicts
, pm_con_args = args }]
NPat (L _ ol) mb_neg _eq ty -> translateNPat fam_insts ol mb_neg ty
LitPat lit
-- If it is a string then convert it to a list of characters
| HsString src s <- lit ->
foldr (mkListPatVec charTy) [nilPattern charTy] <$>
translatePatVec fam_insts (map (LitPat . HsChar src) (unpackFS s))
| otherwise -> return [mkLitPattern lit]
PArrPat ps ty -> do
tidy_ps <- translatePatVec fam_insts (map unLoc ps)
let fake_con = parrFakeCon (length ps)
return [vanillaConPattern fake_con [ty] (concat tidy_ps)]
TuplePat ps boxity tys -> do
tidy_ps <- translatePatVec fam_insts (map unLoc ps)
let tuple_con = tupleDataCon boxity (length ps)
return [vanillaConPattern tuple_con tys (concat tidy_ps)]
-- --------------------------------------------------------------------------
-- Not supposed to happen
ConPatIn {} -> panic "Check.translatePat: ConPatIn"
SplicePat {} -> panic "Check.translatePat: SplicePat"
SigPatIn {} -> panic "Check.translatePat: SigPatIn"
-- | Translate an overloaded literal (see `tidyNPat' in deSugar/MatchLit.hs)
translateNPat :: FamInstEnvs
-> HsOverLit Id -> Maybe (SyntaxExpr Id) -> Type -> PmM PatVec
translateNPat fam_insts (OverLit val False _ ty) mb_neg outer_ty
| not type_change, isStringTy ty, HsIsString src s <- val, Nothing <- mb_neg
= translatePat fam_insts (LitPat (HsString src s))
| not type_change, isIntTy ty, HsIntegral src i <- val
= translatePat fam_insts (mk_num_lit HsInt src i)
| not type_change, isWordTy ty, HsIntegral src i <- val
= translatePat fam_insts (mk_num_lit HsWordPrim src i)
where
type_change = not (outer_ty `eqType` ty)
mk_num_lit c src i = LitPat $ case mb_neg of
Nothing -> c src i
Just _ -> c src (-i)
translateNPat _ ol mb_neg _
= return [PmLit { pm_lit_lit = PmOLit (isJust mb_neg) ol }]
-- | Translate a list of patterns (Note: each pattern is translated
-- to a pattern vector but we do not concatenate the results).
translatePatVec :: FamInstEnvs -> [Pat Id] -> PmM [PatVec]
translatePatVec fam_insts pats = mapM (translatePat fam_insts) pats
-- | Translate a constructor pattern
translateConPatVec :: FamInstEnvs -> [Type] -> [TyVar]
-> DataCon -> HsConPatDetails Id -> PmM PatVec
translateConPatVec fam_insts _univ_tys _ex_tvs _ (PrefixCon ps)
= concat <$> translatePatVec fam_insts (map unLoc ps)
translateConPatVec fam_insts _univ_tys _ex_tvs _ (InfixCon p1 p2)
= concat <$> translatePatVec fam_insts (map unLoc [p1,p2])
translateConPatVec fam_insts univ_tys ex_tvs c (RecCon (HsRecFields fs _))
-- Nothing matched. Make up some fresh term variables
| null fs = mkPmVars arg_tys
-- The data constructor was not defined using record syntax. For the
-- pattern to be in record syntax it should be empty (e.g. Just {}).
-- So just like the previous case.
| null orig_lbls = ASSERT(null matched_lbls) mkPmVars arg_tys
-- Some of the fields appear, in the original order (there may be holes).
-- Generate a simple constructor pattern and make up fresh variables for
-- the rest of the fields
| matched_lbls `subsetOf` orig_lbls
= ASSERT(length orig_lbls == length arg_tys)
let translateOne (lbl, ty) = case lookup lbl matched_pats of
Just p -> translatePat fam_insts p
Nothing -> mkPmVars [ty]
in concatMapM translateOne (zip orig_lbls arg_tys)
-- The fields that appear are not in the correct order. Make up fresh
-- variables for all fields and add guards after matching, to force the
-- evaluation in the correct order.
| otherwise = do
arg_var_pats <- mkPmVars arg_tys
translated_pats <- forM matched_pats $ \(x,pat) -> do
pvec <- translatePat fam_insts pat
return (x, pvec)
let zipped = zip orig_lbls [ x | PmVar x <- arg_var_pats ]
guards = map (\(name,pvec) -> case lookup name zipped of
Just x -> PmGrd pvec (PmExprVar (idName x))
Nothing -> panic "translateConPatVec: lookup")
translated_pats
return (arg_var_pats ++ guards)
where
-- The actual argument types (instantiated)
arg_tys = dataConInstOrigArgTys c (univ_tys ++ mkTyVarTys ex_tvs)
-- Some label information
orig_lbls = map flSelector $ dataConFieldLabels c
matched_pats = [ (getName (unLoc (hsRecFieldId x)), unLoc (hsRecFieldArg x))
| L _ x <- fs]
matched_lbls = [ name | (name, _pat) <- matched_pats ]
subsetOf :: Eq a => [a] -> [a] -> Bool
subsetOf [] _ = True
subsetOf (_:_) [] = False
subsetOf (x:xs) (y:ys)
| x == y = subsetOf xs ys
| otherwise = subsetOf (x:xs) ys
-- Translate a single match
translateMatch :: FamInstEnvs -> LMatch Id (LHsExpr Id) -> PmM (PatVec,[PatVec])
translateMatch fam_insts (L _ (Match _ lpats _ grhss)) = do
pats' <- concat <$> translatePatVec fam_insts pats
guards' <- mapM (translateGuards fam_insts) guards
return (pats', guards')
where
extractGuards :: LGRHS Id (LHsExpr Id) -> [GuardStmt Id]
extractGuards (L _ (GRHS gs _)) = map unLoc gs
pats = map unLoc lpats
guards = map extractGuards (grhssGRHSs grhss)
-- -----------------------------------------------------------------------
-- * Transform source guards (GuardStmt Id) to PmPats (Pattern)
-- | Translate a list of guard statements to a pattern vector
translateGuards :: FamInstEnvs -> [GuardStmt Id] -> PmM PatVec
translateGuards fam_insts guards = do
all_guards <- concat <$> mapM (translateGuard fam_insts) guards
return (replace_unhandled all_guards)
-- It should have been (return all_guards) but it is too expressive.
-- Since the term oracle does not handle all constraints we generate,
-- we (hackily) replace all constraints the oracle cannot handle with a
-- single one (we need to know if there is a possibility of falure).
-- See Note [Guards and Approximation] for all guard-related approximations
-- we implement.
where
replace_unhandled :: PatVec -> PatVec
replace_unhandled gv
| any_unhandled gv = fake_pat : [ p | p <- gv, shouldKeep p ]
| otherwise = gv
any_unhandled :: PatVec -> Bool
any_unhandled gv = any (not . shouldKeep) gv
shouldKeep :: Pattern -> Bool
shouldKeep p
| PmVar {} <- p = True
| PmCon {} <- p = length (allConstructors (pm_con_con p)) == 1
&& all shouldKeep (pm_con_args p)
shouldKeep (PmGrd pv e)
| all shouldKeep pv = True
| isNotPmExprOther e = True -- expensive but we want it
shouldKeep _other_pat = False -- let the rest..
-- | Check whether a pattern can fail to match
cantFailPattern :: Pattern -> Bool
cantFailPattern p
| PmVar {} <- p = True
| PmCon {} <- p = length (allConstructors (pm_con_con p)) == 1
&& all cantFailPattern (pm_con_args p)
cantFailPattern (PmGrd pv _e)
= all cantFailPattern pv
cantFailPattern _ = False
-- | Translate a guard statement to Pattern
translateGuard :: FamInstEnvs -> GuardStmt Id -> PmM PatVec
translateGuard fam_insts guard = case guard of
BodyStmt e _ _ _ -> translateBoolGuard e
LetStmt binds -> translateLet (unLoc binds)
BindStmt p e _ _ _ -> translateBind fam_insts p e
LastStmt {} -> panic "translateGuard LastStmt"
ParStmt {} -> panic "translateGuard ParStmt"
TransStmt {} -> panic "translateGuard TransStmt"
RecStmt {} -> panic "translateGuard RecStmt"
ApplicativeStmt {} -> panic "translateGuard ApplicativeLastStmt"
-- | Translate let-bindings
translateLet :: HsLocalBinds Id -> PmM PatVec
translateLet _binds = return []
-- | Translate a pattern guard
translateBind :: FamInstEnvs -> LPat Id -> LHsExpr Id -> PmM PatVec
translateBind fam_insts (L _ p) e = do
ps <- translatePat fam_insts p
return [mkGuard ps (unLoc e)]
-- | Translate a boolean guard
translateBoolGuard :: LHsExpr Id -> PmM PatVec
translateBoolGuard e
| isJust (isTrueLHsExpr e) = return []
-- The formal thing to do would be to generate (True <- True)
-- but it is trivial to solve so instead we give back an empty
-- PatVec for efficiency
| otherwise = return [mkGuard [truePattern] (unLoc e)]
{- Note [Guards and Approximation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Even if the algorithm is really expressive, the term oracle we use is not.
Hence, several features are not translated *properly* but we approximate.
The list includes:
1. View Patterns
----------------
A view pattern @(f -> p)@ should be translated to @x (p <- f x)@. The term
oracle does not handle function applications so we know that the generated
constraints will not be handled at the end. Hence, we distinguish between two
cases:
a) Pattern @p@ cannot fail. Then this is just a binding and we do the *right
thing*.
b) Pattern @p@ can fail. This means that when checking the guard, we will
generate several cases, with no useful information. E.g.:
h (f -> [a,b]) = ...
h x ([a,b] <- f x) = ...
uncovered set = { [x |> { False ~ (f x ~ []) }]
, [x |> { False ~ (f x ~ (t1:[])) }]
, [x |> { False ~ (f x ~ (t1:t2:t3:t4)) }] }
So we have two problems:
1) Since we do not print the constraints in the general case (they may
be too many), the warning will look like this:
Pattern match(es) are non-exhaustive
In an equation for `h':
Patterns not matched:
_
_
_
Which is not short and not more useful than a single underscore.
2) The size of the uncovered set increases a lot, without gaining more
expressivity in our warnings.
Hence, in this case, we replace the guard @([a,b] <- f x)@ with a *dummy*
@fake_pat@: @True <- _@. That is, we record that there is a possibility
of failure but we minimize it to a True/False. This generates a single
warning and much smaller uncovered sets.
2. Overloaded Lists
-------------------
An overloaded list @[...]@ should be translated to @x ([...] <- toList x)@. The
problem is exactly like above, as its solution. For future reference, the code
below is the *right thing to do*:
ListPat lpats elem_ty (Just (pat_ty, to_list))
otherwise -> do
(xp, xe) <- mkPmId2Forms pat_ty
ps <- translatePatVec (map unLoc lpats)
let pats = foldr (mkListPatVec elem_ty) [nilPattern elem_ty] ps
g = mkGuard pats (HsApp (noLoc to_list) xe)
return [xp,g]
3. Overloaded Literals
----------------------
The case with literals is a bit different. a literal @l@ should be translated
to @x (True <- x == from l)@. Since we want to have better warnings for
overloaded literals as it is a very common feature, we treat them differently.
They are mainly covered in Note [Undecidable Equality on Overloaded Literals]
in PmExpr.
4. N+K Patterns & Pattern Synonyms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An n+k pattern (n+k) should be translated to @x (True <- x >= k) (n <- x-k)@.
Since the only pattern of the three that causes failure is guard @(n <- x-k)@,
and has two possible outcomes. Hence, there is no benefit in using a dummy and
we implement the proper thing. Pattern synonyms are simply not implemented yet.
Hence, to be conservative, we generate a dummy pattern, assuming that the
pattern can fail.
5. Actual Guards
----------------
During translation, boolean guards and pattern guards are translated properly.
Let bindings though are omitted by function @translateLet@. Since they are lazy
bindings, we do not actually want to generate a (strict) equality (like we do
in the pattern bind case). Hence, we safely drop them.
Additionally, top-level guard translation (performed by @translateGuards@)
replaces guards that cannot be reasoned about (like the ones we described in
1-4) with a single @fake_pat@ to record the possibility of failure to match.
Note [Translate CoPats]
~~~~~~~~~~~~~~~~~~~~~~~
The pattern match checker did not know how to handle coerced patterns `CoPat`
efficiently, which gave rise to #11276. The original approach translated
`CoPat`s:
pat |> co ===> x (pat <- (e |> co))
Instead, we now check whether the coercion is a hole or if it is just refl, in
which case we can drop it. Unfortunately, data families generate useful
coercions so guards are still generated in these cases and checking data
families is not really efficient.
%************************************************************************
%* *
Utilities for Pattern Match Checking
%* *
%************************************************************************
-}
-- ----------------------------------------------------------------------------
-- * Basic utilities
-- | Get the type out of a PmPat. For guard patterns (ps <- e) we use the type
-- of the first (or the single -WHEREVER IT IS- valid to use?) pattern
pmPatType :: PmPat p -> Type
pmPatType (PmCon { pm_con_con = con, pm_con_arg_tys = tys })
= mkTyConApp (dataConTyCon con) tys
pmPatType (PmVar { pm_var_id = x }) = idType x
pmPatType (PmLit { pm_lit_lit = l }) = pmLitType l
pmPatType (PmNLit { pm_lit_id = x }) = idType x
pmPatType (PmGrd { pm_grd_pv = pv })
= ASSERT(patVecArity pv == 1) (pmPatType p)
where Just p = find ((==1) . patternArity) pv
-- | Generate a value abstraction for a given constructor (generate
-- fresh variables of the appropriate type for arguments)
mkOneConFull :: Id -> DataCon -> PmM (ValAbs, ComplexEq, Bag EvVar)
-- * x :: T tys, where T is an algebraic data type
-- NB: in the case of a data familiy, T is the *representation* TyCon
-- e.g. data instance T (a,b) = T1 a b
-- leads to
-- data TPair a b = T1 a b -- The "representation" type
-- It is TPair, not T, that is given to mkOneConFull
--
-- * 'con' K is a constructor of data type T
--
-- After instantiating the universal tyvars of K we get
-- K tys :: forall bs. Q => s1 .. sn -> T tys
--
-- Results: ValAbs: K (y1::s1) .. (yn::sn)
-- ComplexEq: x ~ K y1..yn
-- [EvVar]: Q
mkOneConFull x con = do
let -- res_ty == TyConApp (dataConTyCon cabs_con) cabs_arg_tys
res_ty = idType x
(univ_tvs, ex_tvs, eq_spec, thetas, arg_tys, _) = dataConFullSig con
data_tc = dataConTyCon con -- The representation TyCon
tc_args = case splitTyConApp_maybe res_ty of
Just (tc, tys) -> ASSERT( tc == data_tc ) tys
Nothing -> pprPanic "mkOneConFull: Not TyConApp:" (ppr res_ty)
subst1 = zipTvSubst univ_tvs tc_args
(subst, ex_tvs') <- cloneTyVarBndrs subst1 ex_tvs <$> getUniqueSupplyM
-- Fresh term variables (VAs) as arguments to the constructor
arguments <- mapM mkPmVar (substTys subst arg_tys)
-- All constraints bound by the constructor (alpha-renamed)
let theta_cs = substTheta subst (eqSpecPreds eq_spec ++ thetas)
evvars <- mapM (nameType "pm") theta_cs
let con_abs = PmCon { pm_con_con = con
, pm_con_arg_tys = tc_args
, pm_con_tvs = ex_tvs'
, pm_con_dicts = evvars
, pm_con_args = arguments }
return (con_abs, (PmExprVar (idName x), vaToPmExpr con_abs), listToBag evvars)
-- ----------------------------------------------------------------------------
-- * More smart constructors and fresh variable generation
-- | Create a guard pattern
mkGuard :: PatVec -> HsExpr Id -> Pattern
mkGuard pv e
| all cantFailPattern pv = PmGrd pv expr
| PmExprOther {} <- expr = fake_pat
| otherwise = PmGrd pv expr
where
expr = hsExprToPmExpr e
-- | Create a term equality of the form: `(False ~ (x ~ lit))`
mkNegEq :: Id -> PmLit -> ComplexEq
mkNegEq x l = (falsePmExpr, PmExprVar (idName x) `PmExprEq` PmExprLit l)
{-# INLINE mkNegEq #-}
-- | Create a term equality of the form: `(x ~ lit)`
mkPosEq :: Id -> PmLit -> ComplexEq
mkPosEq x l = (PmExprVar (idName x), PmExprLit l)
{-# INLINE mkPosEq #-}
-- | Generate a variable pattern of a given type
mkPmVar :: Type -> PmM (PmPat p)
mkPmVar ty = PmVar <$> mkPmId ty
{-# INLINE mkPmVar #-}
-- | Generate many variable patterns, given a list of types
mkPmVars :: [Type] -> PmM PatVec
mkPmVars tys = mapM mkPmVar tys
{-# INLINE mkPmVars #-}
-- | Generate a fresh `Id` of a given type
mkPmId :: Type -> PmM Id
mkPmId ty = getUniqueM >>= \unique ->
let occname = mkVarOccFS (fsLit (show unique))
name = mkInternalName unique occname noSrcSpan
in return (mkLocalId name ty)
-- | Generate a fresh term variable of a given and return it in two forms:
-- * A variable pattern
-- * A variable expression
mkPmId2Forms :: Type -> PmM (Pattern, LHsExpr Id)
mkPmId2Forms ty = do
x <- mkPmId ty
return (PmVar x, noLoc (HsVar (noLoc x)))
-- ----------------------------------------------------------------------------
-- * Converting between Value Abstractions, Patterns and PmExpr
-- | Convert a value abstraction an expression
vaToPmExpr :: ValAbs -> PmExpr
vaToPmExpr (PmCon { pm_con_con = c, pm_con_args = ps })
= PmExprCon c (map vaToPmExpr ps)
vaToPmExpr (PmVar { pm_var_id = x }) = PmExprVar (idName x)
vaToPmExpr (PmLit { pm_lit_lit = l }) = PmExprLit l
vaToPmExpr (PmNLit { pm_lit_id = x }) = PmExprVar (idName x)
-- | Convert a pattern vector to a list of value abstractions by dropping the
-- guards (See Note [Translating As Patterns])
coercePatVec :: PatVec -> [ValAbs]
coercePatVec pv = concatMap coercePmPat pv
-- | Convert a pattern to a list of value abstractions (will be either an empty
-- list if the pattern is a guard pattern, or a singleton list in all other
-- cases) by dropping the guards (See Note [Translating As Patterns])
coercePmPat :: Pattern -> [ValAbs]
coercePmPat (PmVar { pm_var_id = x }) = [PmVar { pm_var_id = x }]
coercePmPat (PmLit { pm_lit_lit = l }) = [PmLit { pm_lit_lit = l }]
coercePmPat (PmCon { pm_con_con = con, pm_con_arg_tys = arg_tys
, pm_con_tvs = tvs, pm_con_dicts = dicts
, pm_con_args = args })
= [PmCon { pm_con_con = con, pm_con_arg_tys = arg_tys
, pm_con_tvs = tvs, pm_con_dicts = dicts
, pm_con_args = coercePatVec args }]
coercePmPat (PmGrd {}) = [] -- drop the guards
-- | Get all constructors in the family (including given)
allConstructors :: DataCon -> [DataCon]
allConstructors = tyConDataCons . dataConTyCon
-- -----------------------------------------------------------------------
-- * Types and constraints
newEvVar :: Name -> Type -> EvVar
newEvVar name ty = mkLocalId name (toTcType ty)
nameType :: String -> Type -> PmM EvVar
nameType name ty = do
unique <- getUniqueM
let occname = mkVarOccFS (fsLit (name++"_"++show unique))
idname = mkInternalName unique occname noSrcSpan
return (newEvVar idname ty)
{-
%************************************************************************
%* *
The type oracle
%* *
%************************************************************************
-}
-- | Check whether a set of type constraints is satisfiable.
tyOracle :: Bag EvVar -> PmM Bool
tyOracle evs
= do { ((_warns, errs), res) <- initTcDsForSolver $ tcCheckSatisfiability evs
; case res of
Just sat -> return sat
Nothing -> pprPanic "tyOracle" (vcat $ pprErrMsgBagWithLoc errs) }
{-
%************************************************************************
%* *
Sanity Checks
%* *
%************************************************************************
-}
-- | The arity of a pattern/pattern vector is the
-- number of top-level patterns that are not guards
type PmArity = Int
-- | Compute the arity of a pattern vector
patVecArity :: PatVec -> PmArity
patVecArity = sum . map patternArity
-- | Compute the arity of a pattern
patternArity :: Pattern -> PmArity
patternArity (PmGrd {}) = 0
patternArity _other_pat = 1
{-
%************************************************************************
%* *
Heart of the algorithm: Function pmcheck
%* *
%************************************************************************
Main functions are:
* mkInitialUncovered :: [Id] -> PmM Uncovered
Generates the initial uncovered set. Term and type constraints in scope
are checked, if they are inconsistent, the set is empty, otherwise, the
set contains only a vector of variables with the constraints in scope.
* pmcheck :: PatVec -> [PatVec] -> ValVec -> PmM Triple
Checks redundancy, coverage and inaccessibility, using auxilary functions
`pmcheckGuards` and `pmcheckHd`. Mainly handles the guard case which is
common in all three checks (see paper) and calls `pmcheckGuards` when the
whole clause is checked, or `pmcheckHd` when the pattern vector does not
start with a guard.
* pmcheckGuards :: [PatVec] -> ValVec -> PmM Triple
Processes the guards.
* pmcheckHd :: Pattern -> PatVec -> [PatVec]
-> ValAbs -> ValVec -> PmM Triple
Worker: This function implements functions `covered`, `uncovered` and
`divergent` from the paper at once. Slightly different from the paper because
it does not even produce the covered and uncovered sets. Since we only care
about whether a clause covers SOMETHING or if it may forces ANY argument, we
only store a boolean in both cases, for efficiency.
-}
-- | Lift a pattern matching action from a single value vector abstration to a
-- value set abstraction, but calling it on every vector and the combining the
-- results.
runMany :: (ValVec -> PmM Triple) -> (Uncovered -> PmM Triple)
runMany pm us = mapAndUnzip3M pm us >>= \(css, uss, dss) ->
return (or css, concat uss, or dss)
{-# INLINE runMany #-}
-- | Generate the initial uncovered set. It initializes the
-- delta with all term and type constraints in scope.
mkInitialUncovered :: [Id] -> PmM Uncovered
mkInitialUncovered vars = do
ty_cs <- getDictsDs
tm_cs <- map toComplex . bagToList <$> getTmCsDs
sat_ty <- tyOracle ty_cs
return $ case (sat_ty, tmOracle initialTmState tm_cs) of
(True, Just tm_state) -> [ValVec patterns (MkDelta ty_cs tm_state)]
-- If any of the term/type constraints are non
-- satisfiable, the initial uncovered set is empty
_non_satisfiable -> []
where
patterns = map PmVar vars
-- | Increase the counter for elapsed algorithm iterations, check that the
-- limit is not exceeded and call `pmcheck`
pmcheckI :: PatVec -> [PatVec] -> ValVec -> PmM Triple
pmcheckI ps guards vva = incrCheckPmIterDs >> pmcheck ps guards vva
{-# INLINE pmcheckI #-}
-- | Increase the counter for elapsed algorithm iterations, check that the
-- limit is not exceeded and call `pmcheckGuards`
pmcheckGuardsI :: [PatVec] -> ValVec -> PmM Triple
pmcheckGuardsI gvs vva = incrCheckPmIterDs >> pmcheckGuards gvs vva
{-# INLINE pmcheckGuardsI #-}
-- | Increase the counter for elapsed algorithm iterations, check that the
-- limit is not exceeded and call `pmcheckHd`
pmcheckHdI :: Pattern -> PatVec -> [PatVec] -> ValAbs -> ValVec -> PmM Triple
pmcheckHdI p ps guards va vva = incrCheckPmIterDs >>
pmcheckHd p ps guards va vva
{-# INLINE pmcheckHdI #-}
-- | Matching function: Check simultaneously a clause (takes separately the
-- patterns and the list of guards) for exhaustiveness, redundancy and
-- inaccessibility.
pmcheck :: PatVec -> [PatVec] -> ValVec -> PmM Triple
pmcheck [] guards vva@(ValVec [] _)
| null guards = return (True, [], False)
| otherwise = pmcheckGuardsI guards vva
-- Guard
pmcheck (p@(PmGrd pv e) : ps) guards vva@(ValVec vas delta)
-- short-circuit if the guard pattern is useless.
-- we just have two possible outcomes: fail here or match and recurse
-- none of the two contains any useful information about the failure
-- though. So just have these two cases but do not do all the boilerplate
| isFakeGuard pv e = forces . mkCons vva <$> pmcheckI ps guards vva
| otherwise = do
y <- mkPmId (pmPatType p)
let tm_state = extendSubst y e (delta_tm_cs delta)
delta' = delta { delta_tm_cs = tm_state }
utail <$> pmcheckI (pv ++ ps) guards (ValVec (PmVar y : vas) delta')
pmcheck [] _ (ValVec (_:_) _) = panic "pmcheck: nil-cons"
pmcheck (_:_) _ (ValVec [] _) = panic "pmcheck: cons-nil"
pmcheck (p:ps) guards (ValVec (va:vva) delta)
= pmcheckHdI p ps guards va (ValVec vva delta)
-- | Check the list of guards
pmcheckGuards :: [PatVec] -> ValVec -> PmM Triple
pmcheckGuards [] vva = return (False, [vva], False)
pmcheckGuards (gv:gvs) vva = do
(cs, vsa, ds ) <- pmcheckI gv [] vva
(css, vsas, dss) <- runMany (pmcheckGuardsI gvs) vsa
return (cs || css, vsas, ds || dss)
-- | Worker function: Implements all cases described in the paper for all three
-- functions (`covered`, `uncovered` and `divergent`) apart from the `Guard`
-- cases which are handled by `pmcheck`
pmcheckHd :: Pattern -> PatVec -> [PatVec] -> ValAbs -> ValVec -> PmM Triple
-- Var
pmcheckHd (PmVar x) ps guards va (ValVec vva delta)
| Just tm_state <- solveOneEq (delta_tm_cs delta)
(PmExprVar (idName x), vaToPmExpr va)
= ucon va <$> pmcheckI ps guards (ValVec vva (delta {delta_tm_cs = tm_state}))
| otherwise = return (False, [], False)
-- ConCon
pmcheckHd ( p@(PmCon {pm_con_con = c1, pm_con_args = args1})) ps guards
(va@(PmCon {pm_con_con = c2, pm_con_args = args2})) (ValVec vva delta)
| c1 /= c2 = return (False, [ValVec (va:vva) delta], False)
| otherwise = kcon c1 (pm_con_arg_tys p) (pm_con_tvs p) (pm_con_dicts p)
<$> pmcheckI (args1 ++ ps) guards (ValVec (args2 ++ vva) delta)
-- LitLit
pmcheckHd (PmLit l1) ps guards (va@(PmLit l2)) vva = case eqPmLit l1 l2 of
True -> ucon va <$> pmcheckI ps guards vva
False -> return $ ucon va (False, [vva], False)
-- ConVar
pmcheckHd (p@(PmCon { pm_con_con = con })) ps guards
(PmVar x) (ValVec vva delta) = do
cons_cs <- mapM (mkOneConFull x) (allConstructors con)
inst_vsa <- flip concatMapM cons_cs $ \(va, tm_ct, ty_cs) -> do
let ty_state = ty_cs `unionBags` delta_ty_cs delta -- not actually a state
sat_ty <- if isEmptyBag ty_cs then return True
else tyOracle ty_state
return $ case (sat_ty, solveOneEq (delta_tm_cs delta) tm_ct) of
(True, Just tm_state) -> [ValVec (va:vva) (MkDelta ty_state tm_state)]
_ty_or_tm_failed -> []
force_if (canDiverge (idName x) (delta_tm_cs delta)) <$>
runMany (pmcheckI (p:ps) guards) inst_vsa
-- LitVar
pmcheckHd (p@(PmLit l)) ps guards (PmVar x) (ValVec vva delta)
= force_if (canDiverge (idName x) (delta_tm_cs delta)) <$>
mkUnion non_matched <$>
case solveOneEq (delta_tm_cs delta) (mkPosEq x l) of
Just tm_state -> pmcheckHdI p ps guards (PmLit l) $
ValVec vva (delta {delta_tm_cs = tm_state})
Nothing -> return (False, [], False)
where
us | Just tm_state <- solveOneEq (delta_tm_cs delta) (mkNegEq x l)
= [ValVec (PmNLit x [l] : vva) (delta { delta_tm_cs = tm_state })]
| otherwise = []
non_matched = (False, us, False)
-- LitNLit
pmcheckHd (p@(PmLit l)) ps guards
(PmNLit { pm_lit_id = x, pm_lit_not = lits }) (ValVec vva delta)
| all (not . eqPmLit l) lits
, Just tm_state <- solveOneEq (delta_tm_cs delta) (mkPosEq x l)
-- Both guards check the same so it would be sufficient to have only
-- the second one. Nevertheless, it is much cheaper to check whether
-- the literal is in the list so we check it first, to avoid calling
-- the term oracle (`solveOneEq`) if possible
= mkUnion non_matched <$>
pmcheckHdI p ps guards (PmLit l)
(ValVec vva (delta { delta_tm_cs = tm_state }))
| otherwise = return non_matched
where
us | Just tm_state <- solveOneEq (delta_tm_cs delta) (mkNegEq x l)
= [ValVec (PmNLit x (l:lits) : vva) (delta { delta_tm_cs = tm_state })]
| otherwise = []
non_matched = (False, us, False)
-- ----------------------------------------------------------------------------
-- The following three can happen only in cases like #322 where constructors
-- and overloaded literals appear in the same match. The general strategy is
-- to replace the literal (positive/negative) by a variable and recurse. The
-- fact that the variable is equal to the literal is recorded in `delta` so
-- no information is lost
-- LitCon
pmcheckHd (PmLit l) ps guards (va@(PmCon {})) (ValVec vva delta)
= do y <- mkPmId (pmPatType va)
let tm_state = extendSubst y (PmExprLit l) (delta_tm_cs delta)
delta' = delta { delta_tm_cs = tm_state }
pmcheckHdI (PmVar y) ps guards va (ValVec vva delta')
-- ConLit
pmcheckHd (p@(PmCon {})) ps guards (PmLit l) (ValVec vva delta)
= do y <- mkPmId (pmPatType p)
let tm_state = extendSubst y (PmExprLit l) (delta_tm_cs delta)
delta' = delta { delta_tm_cs = tm_state }
pmcheckHdI p ps guards (PmVar y) (ValVec vva delta')
-- ConNLit
pmcheckHd (p@(PmCon {})) ps guards (PmNLit { pm_lit_id = x }) vva
= pmcheckHdI p ps guards (PmVar x) vva
-- Impossible: handled by pmcheck
pmcheckHd (PmGrd {}) _ _ _ _ = panic "pmcheckHd: Guard"
-- ----------------------------------------------------------------------------
-- * Utilities for main checking
-- | Take the tail of all value vector abstractions in the uncovered set
utail :: Triple -> Triple
utail (cs, vsa, ds) = (cs, vsa', ds)
where vsa' = [ ValVec vva delta | ValVec (_:vva) delta <- vsa ]
-- | Prepend a value abstraction to all value vector abstractions in the
-- uncovered set
ucon :: ValAbs -> Triple -> Triple
ucon va (cs, vsa, ds) = (cs, vsa', ds)
where vsa' = [ ValVec (va:vva) delta | ValVec vva delta <- vsa ]
-- | Given a data constructor of arity `a` and an uncovered set containing
-- value vector abstractions of length `(a+n)`, pass the first `n` value
-- abstractions to the constructor (Hence, the resulting value vector
-- abstractions will have length `n+1`)
kcon :: DataCon -> [Type] -> [TyVar] -> [EvVar] -> Triple -> Triple
kcon con arg_tys ex_tvs dicts (cs, vsa, ds)
= (cs, [ ValVec (va:vva) delta
| ValVec vva' delta <- vsa
, let (args, vva) = splitAt n vva'
, let va = PmCon { pm_con_con = con
, pm_con_arg_tys = arg_tys
, pm_con_tvs = ex_tvs
, pm_con_dicts = dicts
, pm_con_args = args } ]
, ds)
where n = dataConSourceArity con
-- | Get the union of two covered, uncovered and divergent value set
-- abstractions. Since the covered and divergent sets are represented by a
-- boolean, union means computing the logical or (at least one of the two is
-- non-empty).
mkUnion :: Triple -> Triple -> Triple
mkUnion (cs1, vsa1, ds1) (cs2, vsa2, ds2)
= (cs1 || cs2, vsa1 ++ vsa2, ds1 || ds2)
-- | Add a value vector abstraction to a value set abstraction (uncovered).
mkCons :: ValVec -> Triple -> Triple
mkCons vva (cs, vsa, ds) = (cs, vva:vsa, ds)
-- | Set the divergent set to not empty
forces :: Triple -> Triple
forces (cs, us, _) = (cs, us, True)
-- | Set the divergent set to non-empty if the flag is `True`
force_if :: Bool -> Triple -> Triple
force_if True (cs,us,_) = (cs,us,True)
force_if False triple = triple
-- ----------------------------------------------------------------------------
-- * Propagation of term constraints inwards when checking nested matches
{- Note [Type and Term Equality Propagation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When checking a match it would be great to have all type and term information
available so we can get more precise results. For this reason we have functions
`addDictsDs' and `addTmCsDs' in DsMonad that store in the environment type and
term constraints (respectively) as we go deeper.
The type constraints we propagate inwards are collected by `collectEvVarsPats'
in HsPat.hs. This handles bug #4139 ( see example
https://ghc.haskell.org/trac/ghc/attachment/ticket/4139/GADTbug.hs )
where this is needed.
For term equalities we do less, we just generate equalities for HsCase. For
example we accurately give 2 redundancy warnings for the marked cases:
f :: [a] -> Bool
f x = case x of
[] -> case x of -- brings (x ~ []) in scope
[] -> True
(_:_) -> False -- can't happen
(_:_) -> case x of -- brings (x ~ (_:_)) in scope
(_:_) -> True
[] -> False -- can't happen
Functions `genCaseTmCs1' and `genCaseTmCs2' are responsible for generating
these constraints.
-}
-- | Generate equalities when checking a case expression:
-- case x of { p1 -> e1; ... pn -> en }
-- When we go deeper to check e.g. e1 we record two equalities:
-- (x ~ y), where y is the initial uncovered when checking (p1; .. ; pn)
-- and (x ~ p1).
genCaseTmCs2 :: Maybe (LHsExpr Id) -- Scrutinee
-> [Pat Id] -- LHS (should have length 1)
-> [Id] -- MatchVars (should have length 1)
-> DsM (Bag SimpleEq)
genCaseTmCs2 Nothing _ _ = return emptyBag
genCaseTmCs2 (Just scr) [p] [var] = do
fam_insts <- dsGetFamInstEnvs
[e] <- map vaToPmExpr . coercePatVec <$> translatePat fam_insts p
let scr_e = lhsExprToPmExpr scr
return $ listToBag [(var, e), (var, scr_e)]
genCaseTmCs2 _ _ _ = panic "genCaseTmCs2: HsCase"
-- | Generate a simple equality when checking a case expression:
-- case x of { matches }
-- When checking matches we record that (x ~ y) where y is the initial
-- uncovered. All matches will have to satisfy this equality.
genCaseTmCs1 :: Maybe (LHsExpr Id) -> [Id] -> Bag SimpleEq
genCaseTmCs1 Nothing _ = emptyBag
genCaseTmCs1 (Just scr) [var] = unitBag (var, lhsExprToPmExpr scr)
genCaseTmCs1 _ _ = panic "genCaseTmCs1: HsCase"
{- Note [Literals in PmPat]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Instead of translating a literal to a variable accompanied with a guard, we
treat them like constructor patterns. The following example from
"./libraries/base/GHC/IO/Encoding.hs" shows why:
mkTextEncoding' :: CodingFailureMode -> String -> IO TextEncoding
mkTextEncoding' cfm enc = case [toUpper c | c <- enc, c /= '-'] of
"UTF8" -> return $ UTF8.mkUTF8 cfm
"UTF16" -> return $ UTF16.mkUTF16 cfm
"UTF16LE" -> return $ UTF16.mkUTF16le cfm
...
Each clause gets translated to a list of variables with an equal number of
guards. For every guard we generate two cases (equals True/equals False) which
means that we generate 2^n cases to feed the oracle with, where n is the sum of
the length of all strings that appear in the patterns. For this particular
example this means over 2^40 cases. Instead, by representing them like with
constructor we get the following:
1. We exploit the common prefix with our representation of VSAs
2. We prune immediately non-reachable cases
(e.g. False == (x == "U"), True == (x == "U"))
Note [Translating As Patterns]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Instead of translating x@p as: x (p <- x)
we instead translate it as: p (x <- coercePattern p)
for performance reasons. For example:
f x@True = 1
f y@False = 2
Gives the following with the first translation:
x |> {x == False, x == y, y == True}
If we use the second translation we get an empty set, independently of the
oracle. Since the pattern `p' may contain guard patterns though, it cannot be
used as an expression. That's why we call `coercePatVec' to drop the guard and
`vaToPmExpr' to transform the value abstraction to an expression in the
guard pattern (value abstractions are a subset of expressions). We keep the
guards in the first pattern `p' though.
%************************************************************************
%* *
Pretty printing of exhaustiveness/redundancy check warnings
%* *
%************************************************************************
-}
-- | Check whether any part of pattern match checking is enabled (does not
-- matter whether it is the redundancy check or the exhaustiveness check).
isAnyPmCheckEnabled :: DynFlags -> DsMatchContext -> Bool
isAnyPmCheckEnabled dflags (DsMatchContext kind _loc)
= wopt Opt_WarnOverlappingPatterns dflags || exhaustive dflags kind
instance Outputable ValVec where
ppr (ValVec vva delta)
= let (residual_eqs, subst) = wrapUpTmState (delta_tm_cs delta)
vector = substInValAbs subst vva
in ppr_uncovered (vector, residual_eqs)
-- | Apply a term substitution to a value vector abstraction. All VAs are
-- transformed to PmExpr (used only before pretty printing).
substInValAbs :: PmVarEnv -> [ValAbs] -> [PmExpr]
substInValAbs subst = map (exprDeepLookup subst . vaToPmExpr)
-- | Wrap up the term oracle's state once solving is complete. Drop any
-- information about unhandled constraints (involving HsExprs) and flatten
-- (height 1) the substitution.
wrapUpTmState :: TmState -> ([ComplexEq], PmVarEnv)
wrapUpTmState (residual, (_, subst)) = (residual, flattenPmVarEnv subst)
-- | Issue all the warnings (coverage, exhaustiveness, inaccessibility)
dsPmWarn :: DynFlags -> DsMatchContext -> PmResult -> DsM ()
dsPmWarn dflags ctx@(DsMatchContext kind loc) pm_result
= when (flag_i || flag_u) $ do
let exists_r = flag_i && notNull redundant
exists_i = flag_i && notNull inaccessible
exists_u = flag_u && notNull uncovered
when exists_r $ forM_ redundant $ \(L l q) -> do
putSrcSpanDs l (warnDs (Reason Opt_WarnOverlappingPatterns)
(pprEqn q "is redundant"))
when exists_i $ forM_ inaccessible $ \(L l q) -> do
putSrcSpanDs l (warnDs (Reason Opt_WarnOverlappingPatterns)
(pprEqn q "has inaccessible right hand side"))
when exists_u $
putSrcSpanDs loc (warnDs flag_u_reason (pprEqns uncovered))
where
(redundant, uncovered, inaccessible) = pm_result
flag_i = wopt Opt_WarnOverlappingPatterns dflags
flag_u = exhaustive dflags kind
flag_u_reason = maybe NoReason Reason (exhaustiveWarningFlag kind)
maxPatterns = maxUncoveredPatterns dflags
-- Print a single clause (for redundant/with-inaccessible-rhs)
pprEqn q txt = pp_context True ctx (text txt) $ \f -> ppr_eqn f kind q
-- Print several clauses (for uncovered clauses)
pprEqns qs = pp_context False ctx (text "are non-exhaustive") $ \_ ->
case qs of -- See #11245
[ValVec [] _]
-> text "Guards do not cover entire pattern space"
_missing -> let us = map ppr qs
in hang (text "Patterns not matched:") 4
(vcat (take maxPatterns us)
$$ dots maxPatterns us)
-- | Issue a warning when the predefined number of iterations is exceeded
-- for the pattern match checker
warnPmIters :: DynFlags -> DsMatchContext -> PmM ()
warnPmIters dflags (DsMatchContext kind loc)
= when (flag_i || flag_u) $ do
iters <- maxPmCheckIterations <$> getDynFlags
putSrcSpanDs loc (warnDs NoReason (msg iters))
where
ctxt = pprMatchContext kind
msg is = fsep [ text "Pattern match checker exceeded"
, parens (ppr is), text "iterations in", ctxt <> dot
, text "(Use -fmax-pmcheck-iterations=n"
, text "to set the maximun number of iterations to n)" ]
flag_i = wopt Opt_WarnOverlappingPatterns dflags
flag_u = exhaustive dflags kind
dots :: Int -> [a] -> SDoc
dots maxPatterns qs
| qs `lengthExceeds` maxPatterns = text "..."
| otherwise = empty
-- | Check whether the exhaustiveness checker should run (exhaustiveness only)
exhaustive :: DynFlags -> HsMatchContext id -> Bool
exhaustive dflags = maybe False (`wopt` dflags) . exhaustiveWarningFlag
-- | Denotes whether an exhaustiveness check is supported, and if so,
-- via which 'WarningFlag' it's controlled.
-- Returns 'Nothing' if check is not supported.
exhaustiveWarningFlag :: HsMatchContext id -> Maybe WarningFlag
exhaustiveWarningFlag (FunRhs {}) = Just Opt_WarnIncompletePatterns
exhaustiveWarningFlag CaseAlt = Just Opt_WarnIncompletePatterns
exhaustiveWarningFlag IfAlt = Nothing
exhaustiveWarningFlag LambdaExpr = Just Opt_WarnIncompleteUniPatterns
exhaustiveWarningFlag PatBindRhs = Just Opt_WarnIncompleteUniPatterns
exhaustiveWarningFlag ProcExpr = Just Opt_WarnIncompleteUniPatterns
exhaustiveWarningFlag RecUpd = Just Opt_WarnIncompletePatternsRecUpd
exhaustiveWarningFlag ThPatSplice = Nothing
exhaustiveWarningFlag PatSyn = Nothing
exhaustiveWarningFlag ThPatQuote = Nothing
exhaustiveWarningFlag (StmtCtxt {}) = Nothing -- Don't warn about incomplete patterns
-- in list comprehensions, pattern guards
-- etc. They are often *supposed* to be
-- incomplete
-- True <==> singular
pp_context :: Bool -> DsMatchContext -> SDoc -> ((SDoc -> SDoc) -> SDoc) -> SDoc
pp_context singular (DsMatchContext kind _loc) msg rest_of_msg_fun
= vcat [text txt <+> msg,
sep [ text "In" <+> ppr_match <> char ':'
, nest 4 (rest_of_msg_fun pref)]]
where
txt | singular = "Pattern match"
| otherwise = "Pattern match(es)"
(ppr_match, pref)
= case kind of
FunRhs fun -> (pprMatchContext kind, \ pp -> ppr fun <+> pp)
_ -> (pprMatchContext kind, \ pp -> pp)
ppr_pats :: HsMatchContext Name -> [Pat Id] -> SDoc
ppr_pats kind pats
= sep [sep (map ppr pats), matchSeparator kind, text "..."]
ppr_eqn :: (SDoc -> SDoc) -> HsMatchContext Name -> [LPat Id] -> SDoc
ppr_eqn prefixF kind eqn = prefixF (ppr_pats kind (map unLoc eqn))
ppr_constraint :: (SDoc,[PmLit]) -> SDoc
ppr_constraint (var, lits) = var <+> text "is not one of"
<+> braces (pprWithCommas ppr lits)
ppr_uncovered :: ([PmExpr], [ComplexEq]) -> SDoc
ppr_uncovered (expr_vec, complex)
| null cs = fsep vec -- there are no literal constraints
| otherwise = hang (fsep vec) 4 $
text "where" <+> vcat (map ppr_constraint cs)
where
sdoc_vec = mapM pprPmExprWithParens expr_vec
(vec,cs) = runPmPprM sdoc_vec (filterComplex complex)
{- Note [Representation of Term Equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the paper, term constraints always take the form (x ~ e). Of course, a more
general constraint of the form (e1 ~ e1) can always be transformed to an
equivalent set of the former constraints, by introducing a fresh, intermediate
variable: { y ~ e1, y ~ e1 }. Yet, implementing this representation gave rise
to #11160 (incredibly bad performance for literal pattern matching). Two are
the main sources of this problem (the actual problem is how these two interact
with each other):
1. Pattern matching on literals generates twice as many constraints as needed.
Consider the following (tests/ghci/should_run/ghcirun004):
foo :: Int -> Int
foo 1 = 0
...
foo 5000 = 4999
The covered and uncovered set *should* look like:
U0 = { x |> {} }
C1 = { 1 |> { x ~ 1 } }
U1 = { x |> { False ~ (x ~ 1) } }
...
C10 = { 10 |> { False ~ (x ~ 1), .., False ~ (x ~ 9), x ~ 10 } }
U10 = { x |> { False ~ (x ~ 1), .., False ~ (x ~ 9), False ~ (x ~ 10) } }
...
If we replace { False ~ (x ~ 1) } with { y ~ False, y ~ (x ~ 1) }
we get twice as many constraints. Also note that half of them are just the
substitution [x |-> False].
2. The term oracle (`tmOracle` in deSugar/TmOracle) uses equalities of the form
(x ~ e) as substitutions [x |-> e]. More specifically, function
`extendSubstAndSolve` applies such substitutions in the residual constraints
and partitions them in the affected and non-affected ones, which are the new
worklist. Essentially, this gives quadradic behaviour on the number of the
residual constraints. (This would not be the case if the term oracle used
mutable variables but, since we use it to handle disjunctions on value set
abstractions (`Union` case), we chose a pure, incremental interface).
Now the problem becomes apparent (e.g. for clause 300):
* Set U300 contains 300 substituting constraints [y_i |-> False] and 300
constraints that we know that will not reduce (stay in the worklist).
* To check for consistency, we apply the substituting constraints ONE BY ONE
(since `tmOracle` is called incrementally, it does not have all of them
available at once). Hence, we go through the (non-progressing) constraints
over and over, achieving over-quadradic behaviour.
If instead we allow constraints of the form (e ~ e),
* All uncovered sets Ui contain no substituting constraints and i
non-progressing constraints of the form (False ~ (x ~ lit)) so the oracle
behaves linearly.
* All covered sets Ci contain exactly (i-1) non-progressing constraints and
a single substituting constraint. So the term oracle goes through the
constraints only once.
The performance improvement becomes even more important when more arguments are
involved.
-}
| tjakway/ghcjvm | compiler/deSugar/Check.hs | bsd-3-clause | 58,895 | 1 | 22 | 14,583 | 11,370 | 5,926 | 5,444 | -1 | -1 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Network/Wai/Handler/Warp/HTTP2/Types.hs" #-}
{-# LANGUAGE OverloadedStrings, CPP #-}
{-# LANGUAGE NamedFieldPuns, RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
module Network.Wai.Handler.Warp.HTTP2.Types where
import Data.ByteString.Builder (Builder)
import Control.Concurrent (forkIO)
import Control.Concurrent.STM
import Control.Exception (SomeException, bracket)
import Control.Monad (void, forM_)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.IntMap.Strict (IntMap, IntMap)
import qualified Data.IntMap.Strict as M
import qualified Network.HTTP.Types as H
import Network.Wai (Request, FilePart)
import Network.Wai.Handler.Warp.HTTP2.Manager
import Network.Wai.Handler.Warp.IORef
import Network.Wai.Handler.Warp.Types
import Network.HTTP2
import Network.HTTP2.Priority
import Network.HPACK hiding (Buffer)
----------------------------------------------------------------
http2ver :: H.HttpVersion
http2ver = H.HttpVersion 2 0
isHTTP2 :: Transport -> Bool
isHTTP2 TCP = False
isHTTP2 tls = useHTTP2
where
useHTTP2 = case tlsNegotiatedProtocol tls of
Nothing -> False
Just proto -> "h2-" `BS.isPrefixOf` proto
----------------------------------------------------------------
data Input = Input Stream Request ValueTable InternalInfo
----------------------------------------------------------------
type DynaNext = Buffer -> BufSize -> WindowSize -> IO Next
type BytesFilled = Int
data Next = Next !BytesFilled (Maybe DynaNext)
data Rspn = RspnNobody H.Status (TokenHeaderList, ValueTable)
| RspnStreaming H.Status (TokenHeaderList, ValueTable) (TBQueue Sequence)
| RspnBuilder H.Status (TokenHeaderList, ValueTable) Builder
| RspnFile H.Status (TokenHeaderList, ValueTable) FilePath (Maybe FilePart)
rspnStatus :: Rspn -> H.Status
rspnStatus (RspnNobody s _) = s
rspnStatus (RspnStreaming s _ _) = s
rspnStatus (RspnBuilder s _ _) = s
rspnStatus (RspnFile s _ _ _ ) = s
rspnHeaders :: Rspn -> (TokenHeaderList, ValueTable)
rspnHeaders (RspnNobody _ t) = t
rspnHeaders (RspnStreaming _ t _) = t
rspnHeaders (RspnBuilder _ t _) = t
rspnHeaders (RspnFile _ t _ _ ) = t
data Output = Output {
outputStream :: !Stream
, outputRspn :: !Rspn
, outputII :: !InternalInfo
, outputHook :: IO () -- OPush: wait for done, O*: telling done
, outputH2Data :: IO (Maybe HTTP2Data)
, outputType :: !OutputType
}
data OutputType = ORspn
| OWait
| OPush !TokenHeaderList !StreamId -- associated stream id from client
| ONext !DynaNext
outputMaybeTBQueue :: Output -> Maybe (TBQueue Sequence)
outputMaybeTBQueue (Output _ (RspnStreaming _ _ tbq) _ _ _ _) = Just tbq
outputMaybeTBQueue _ = Nothing
data Control = CFinish
| CGoaway !ByteString
| CFrame !ByteString
| CSettings !ByteString !SettingsList
| CSettings0 !ByteString !ByteString !SettingsList
----------------------------------------------------------------
data Sequence = SFinish
| SFlush
| SBuilder Builder
----------------------------------------------------------------
-- | The context for HTTP/2 connection.
data Context = Context {
-- HTTP/2 settings received from a browser
http2settings :: !(IORef Settings)
, firstSettings :: !(IORef Bool)
, streamTable :: !StreamTable
, concurrency :: !(IORef Int)
, priorityTreeSize :: !(IORef Int)
-- | RFC 7540 says "Other frames (from any stream) MUST NOT
-- occur between the HEADERS frame and any CONTINUATION
-- frames that might follow". This field is used to implement
-- this requirement.
, continued :: !(IORef (Maybe StreamId))
, clientStreamId :: !(IORef StreamId)
, serverStreamId :: !(IORef StreamId)
, inputQ :: !(TQueue Input)
, outputQ :: !(PriorityTree Output)
, controlQ :: !(TQueue Control)
, encodeDynamicTable :: !DynamicTable
, decodeDynamicTable :: !DynamicTable
-- the connection window for data from a server to a browser.
, connectionWindow :: !(TVar WindowSize)
}
----------------------------------------------------------------
newContext :: IO Context
newContext = Context <$> newIORef defaultSettings
<*> newIORef False
<*> newStreamTable
<*> newIORef 0
<*> newIORef 0
<*> newIORef Nothing
<*> newIORef 0
<*> newIORef 0
<*> newTQueueIO
<*> newPriorityTree
<*> newTQueueIO
<*> newDynamicTableForEncoding defaultDynamicTableSize
<*> newDynamicTableForDecoding defaultDynamicTableSize 4096
<*> newTVarIO defaultInitialWindowSize
clearContext :: Context -> IO ()
clearContext _ctx = return ()
----------------------------------------------------------------
data OpenState =
JustOpened
| Continued [HeaderBlockFragment]
!Int -- Total size
!Int -- The number of continuation frames
!Bool -- End of stream
!Priority
| NoBody (TokenHeaderList,ValueTable) !Priority
| HasBody (TokenHeaderList,ValueTable) !Priority
| Body !(TQueue ByteString)
!(Maybe Int) -- received Content-Length
-- compared the body length for error checking
!(IORef Int) -- actual body length
data ClosedCode = Finished
| Killed
| Reset !ErrorCodeId
| ResetByMe SomeException
deriving Show
data StreamState =
Idle
| Open !OpenState
| HalfClosed
| Closed !ClosedCode
| Reserved
isIdle :: StreamState -> Bool
isIdle Idle = True
isIdle _ = False
isOpen :: StreamState -> Bool
isOpen Open{} = True
isOpen _ = False
isHalfClosed :: StreamState -> Bool
isHalfClosed HalfClosed = True
isHalfClosed _ = False
isClosed :: StreamState -> Bool
isClosed Closed{} = True
isClosed _ = False
instance Show StreamState where
show Idle = "Idle"
show Open{} = "Open"
show HalfClosed = "HalfClosed"
show (Closed e) = "Closed: " ++ show e
show Reserved = "Reserved"
----------------------------------------------------------------
data Stream = Stream {
streamNumber :: !StreamId
, streamState :: !(IORef StreamState)
, streamWindow :: !(TVar WindowSize)
, streamPrecedence :: !(IORef Precedence)
}
instance Show Stream where
show s = show (streamNumber s)
newStream :: StreamId -> WindowSize -> IO Stream
newStream sid win = Stream sid <$> newIORef Idle
<*> newTVarIO win
<*> newIORef defaultPrecedence
newPushStream :: Context -> WindowSize -> Precedence -> IO Stream
newPushStream Context{serverStreamId} win pre = do
sid <- atomicModifyIORef' serverStreamId inc2
Stream sid <$> newIORef Reserved
<*> newTVarIO win
<*> newIORef pre
where
inc2 x = let !x' = x + 2 in (x', x')
----------------------------------------------------------------
opened :: Context -> Stream -> IO ()
opened Context{concurrency} Stream{streamState} = do
atomicModifyIORef' concurrency (\x -> (x+1,()))
writeIORef streamState (Open JustOpened)
closed :: Context -> Stream -> ClosedCode -> IO ()
closed Context{concurrency,streamTable} Stream{streamState,streamNumber} cc = do
remove streamTable streamNumber
atomicModifyIORef' concurrency (\x -> (x-1,()))
writeIORef streamState (Closed cc) -- anyway
----------------------------------------------------------------
newtype StreamTable = StreamTable (IORef (IntMap Stream))
newStreamTable :: IO StreamTable
newStreamTable = StreamTable <$> newIORef M.empty
insert :: StreamTable -> M.Key -> Stream -> IO ()
insert (StreamTable ref) k v = atomicModifyIORef' ref $ \m ->
let !m' = M.insert k v m
in (m', ())
remove :: StreamTable -> M.Key -> IO ()
remove (StreamTable ref) k = atomicModifyIORef' ref $ \m ->
let !m' = M.delete k m
in (m', ())
search :: StreamTable -> M.Key -> IO (Maybe Stream)
search (StreamTable ref) k = M.lookup k <$> readIORef ref
updateAllStreamWindow :: (WindowSize -> WindowSize) -> StreamTable -> IO ()
updateAllStreamWindow adst (StreamTable ref) = do
strms <- M.elems <$> readIORef ref
forM_ strms $ \strm -> atomically $ modifyTVar (streamWindow strm) adst
{-# INLINE forkAndEnqueueWhenReady #-}
forkAndEnqueueWhenReady :: IO () -> PriorityTree Output -> Output -> Manager -> IO ()
forkAndEnqueueWhenReady wait outQ out mgr = bracket setup teardown $ \_ ->
void . forkIO $ do
wait
enqueueOutput outQ out
where
setup = addMyId mgr
teardown _ = deleteMyId mgr
{-# INLINE enqueueOutput #-}
enqueueOutput :: PriorityTree Output -> Output -> IO ()
enqueueOutput outQ out = do
let Stream{..} = outputStream out
pre <- readIORef streamPrecedence
enqueue outQ streamNumber pre out
{-# INLINE enqueueControl #-}
enqueueControl :: TQueue Control -> Control -> IO ()
enqueueControl ctlQ ctl = atomically $ writeTQueue ctlQ ctl
----------------------------------------------------------------
-- | HTTP/2 specific data.
--
-- Since: 3.2.7
data HTTP2Data = HTTP2Data {
-- | Accessor for 'PushPromise' in 'HTTP2Data'.
--
-- Since: 3.2.7
http2dataPushPromise :: [PushPromise]
-- Since: 3.2.8
, http2dataTrailers :: H.ResponseHeaders
} deriving (Eq,Show)
-- | Default HTTP/2 specific data.
--
-- Since: 3.2.7
defaultHTTP2Data :: HTTP2Data
defaultHTTP2Data = HTTP2Data [] []
-- | HTTP/2 push promise or sever push.
--
-- Since: 3.2.7
data PushPromise = PushPromise {
-- | Accessor for a URL path in 'PushPromise'.
-- E.g. \"\/style\/default.css\".
--
-- Since: 3.2.7
promisedPath :: ByteString
-- | Accessor for 'FilePath' in 'PushPromise'.
-- E.g. \"FILE_PATH/default.css\".
--
-- Since: 3.2.7
, promisedFile :: FilePath
-- | Accessor for 'H.ResponseHeaders' in 'PushPromise'
-- \"content-type\" must be specified.
-- Default value: [].
--
--
-- Since: 3.2.7
, promisedResponseHeaders :: H.ResponseHeaders
-- | Accessor for 'Weight' in 'PushPromise'.
-- Default value: 16.
--
-- Since: 3.2.7
, promisedWeight :: Weight
} deriving (Eq,Ord,Show)
-- | Default push promise.
--
-- Since: 3.2.7
defaultPushPromise :: PushPromise
defaultPushPromise = PushPromise "" "" [] 16
| phischu/fragnix | tests/packages/scotty/Network.Wai.Handler.Warp.HTTP2.Types.hs | bsd-3-clause | 10,994 | 0 | 19 | 2,823 | 2,563 | 1,364 | 1,199 | 309 | 2 |
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module GHC.Fingerprint.Type (module M) where
import "base" GHC.Fingerprint.Type as M
| Ye-Yong-Chi/codeworld | codeworld-base/src/GHC/Fingerprint/Type.hs | apache-2.0 | 755 | 0 | 4 | 136 | 25 | 19 | 6 | 4 | 0 |
{-
types:
A__dummy :: (*, data)
values:
p :: A__dummy -> Bool
A__dummy :: A__dummy
scope:
Prelude.A__dummy |-> Prelude.A__dummy, Type [A__dummy] []
Prelude.A__dummy |-> Prelude.A__dummy, con of A__dummy
Prelude.p |-> Prelude.p, Value
A__dummy |-> Prelude.A__dummy, Type [A__dummy] []
A__dummy |-> Prelude.A__dummy, con of A__dummy
p |-> Prelude.p, Value
-}
module Dummy where
data A__dummy = A__dummy
p :: A__dummy -> Bool
p x = True
p x = False
p x = (\ (a, b, c) -> if b then a else c)
(p x,
uncurry{-Bool Bool Bool-} (||)
(flip{-Bool Bool Bool-} seq{-Bool Bool-} True (p x),
False),
p x)
| mariefarrell/Hets | ToHaskell/test/Builtin.hascasl.hs | gpl-2.0 | 669 | 0 | 11 | 178 | 117 | 67 | 50 | 11 | 2 |
module A1 where
fib n
| n <= 1 = 1
| otherwise = n1 + n2 + 1
where
n1 = fib (n-1)
n2 = fib (n-2)
n1_2 = "bob"
| RefactoringTools/HaRe | old/testing/evalMonad/A1.hs | bsd-3-clause | 142 | 0 | 9 | 63 | 76 | 39 | 37 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Vim.Ex.Commands.Cabal
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
module Yi.Keymap.Vim.Ex.Commands.Cabal (parse) where
import Control.Applicative (Alternative ((<|>)))
import Control.Monad (void)
import qualified Data.Attoparsec.Text as P (string, try)
import qualified Data.Text as T (pack)
import Yi.Command (cabalBuildE)
import Yi.Keymap (Action (YiA))
import Yi.Keymap.Vim.Common (EventString)
import qualified Yi.Keymap.Vim.Ex.Commands.Common as Common (commandArgs, impureExCommand, parse)
import Yi.Keymap.Vim.Ex.Types (ExCommand (cmdAction, cmdShow))
import Yi.MiniBuffer (CommandArguments (CommandArguments))
-- TODO: Either hack Text into these parsec parsers or use Attoparsec.
-- Attoparsec is faster anyway and backtracks by default so we may
-- want to use that anyway.
parse :: EventString -> Maybe ExCommand
parse = Common.parse $ do
void $ P.try (P.string "cabal build") <|> P.try (P.string "cabal")
args <- Common.commandArgs
return $ Common.impureExCommand {
cmdShow = T.pack "cabal build"
, cmdAction = YiA $ cabalBuildE $ CommandArguments args
}
| siddhanathan/yi | yi-keymap-vim/src/Yi/Keymap/Vim/Ex/Commands/Cabal.hs | gpl-2.0 | 1,517 | 0 | 13 | 431 | 282 | 176 | 106 | 20 | 1 |
module HAD.Y2014.M03.D26.Exercise
( Board
, board
, getList
, Direction (..)
, viewFrom
) where
import Data.List (groupBy)
import Control.Applicative ((<*>))
import Control.Monad (liftM, replicateM)
import Test.QuickCheck
-- Preamble
-- $setup
-- >>> import Control.Applicative ((<$>), (<*>))
-- >>> import Data.List (sort)
-- >>> :{
-- let checkReverse d1 d2 =
-- (==) <$>
-- sort . map sort . getList . viewFrom d1 <*>
-- sort . map (sort . reverse) . getList . viewFrom d2
-- :}
newtype Board a = Board {getList :: [[a]]}
deriving (Eq, Show)
data Direction = North | South | East | West
deriving (Eq, Read, Show)
-- Exercise
-- | viewFrom given a direction, produce an involution such that the
-- inner lists elements are ordered as if they were seen from that direction.
--
--
-- Examples:
--
-- Defaut view is from West
-- prop> xs == viewFrom West xs
--
-- The function is an involution
-- prop> \(d,xxs) -> (==) <*> (viewFrom d . viewFrom d) $ (xxs :: Board Int)
--
-- Ordering properties from opposite side views (for inner lists elements
-- prop> checkReverse West East (xxs :: Board Int)
-- prop> checkReverse East West (xxs :: Board Int)
-- prop> checkReverse North South (xxs :: Board Int)
-- prop> checkReverse South North (xxs :: Board Int)
--
viewFrom :: Direction -> Board a -> Board a
viewFrom = undefined
-- Constructor
-- | board Yesterday's squareOf, build a square board with initial values
board :: Int -> a -> [a] -> [[a]]
board n x = take n . map (take n) . iterate (drop n) . (++ repeat x)
-- Arbitrary instances
instance Arbitrary a => Arbitrary (Board a) where
arbitrary = liftM Board (arbitrary >>= replicateM <*> vector)
instance Arbitrary Direction where
arbitrary = elements [North, South , East , West]
| 1HaskellADay/1HAD | exercises/HAD/Y2014/M03/D26/Exercise.hs | mit | 1,798 | 0 | 10 | 371 | 334 | 204 | 130 | 22 | 1 |
import Sound.Tidal.Tempo (Tempo, logicalTime, clocked, clockedTick, bps)
import Sound.OSC.FD
import Sound.OSC.Datum
--import Sound.OpenSoundControl
--import Sound.OSC.FD
import System.IO
import Control.Concurrent
mykip = "192.168.178.135";
mykport = 57120
main :: IO ()
main = do myk <- openUDP mykip mykport
clockedTick 2 $ onTick myk
wave n = drop i s ++ take i s
where s = "¸.·´¯`·.´¯`·.¸¸.·´¯`·.¸<º)))><"
i = n `mod` (length s)
onTick :: UDP -> Tempo -> Int -> IO ()
onTick myk current ticks =
do putStr $ "tickmyk " ++ (show ticks) ++ " " ++ (wave ticks) ++ "\r"
hFlush stdout
let m = Message "/sync" [int32 ticks, float ((bps current) * 60)]
forkIO $ do threadDelay $ floor $ 0.075 * 1000000
sendOSC myk m
return ()
| kindohm/Tidal | sync/Canute.hs | gpl-3.0 | 803 | 1 | 16 | 187 | 300 | 151 | 149 | 21 | 1 |
module StablePtr (module Foreign.StablePtr) where
import Foreign.StablePtr
| FranklinChen/hugs98-plus-Sep2006 | packages/haskell98/StablePtr.hs | bsd-3-clause | 75 | 0 | 5 | 7 | 17 | 11 | 6 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- This module contains logic pertaining to camliType "email"
module Shed.Blob.Email where
import Control.Arrow ((***))
import Control.Logging (log')
import Control.Monad (when)
import Data.Aeson
import Data.Aeson.Encode.Pretty (encodePretty)
import Data.Aeson.Types
import Data.Binary.Builder (Builder)
import qualified Data.Binary.Builder as Builder
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.Char (toLower)
import Data.Maybe (fromMaybe, listToMaybe)
import Data.MBox (body, fromLine, headers, parseMBox)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import Network.Wai (Response)
import System.FilePath (takeExtension)
import Web.Fn (File (..))
import qualified Web.Larceny as L
import qualified Shed.Blob.File as File
import qualified Shed.Blob.Permanode as Permanode
import Shed.BlobServer
import Shed.IndexServer
import Shed.Types
import Shed.Util
data Header = Header Text Text deriving Show
instance FromJSON Header where
parseJSON (Object v) = Header <$> v .: "name"
<*> v .: "value"
parseJSON invalid = typeMismatch "Header" invalid
instance ToJSON Header where
toJSON (Header name value) = object ["name" .= name
,"value" .= value]
getHeader :: [Header] -> Text -> Maybe Text
getHeader hs k = (\(Header _ v) -> v) <$> listToMaybe (filter (\(Header k' _) -> k == k') hs)
data EmailBlob = EmailBlob Text [Header] [File.Part]
instance FromJSON EmailBlob where
parseJSON (Object v) = (do t <- v .: "camliType"
if t == ("email" :: Text) then
EmailBlob <$> v .: "from"
<*> v .: "headers"
<*> v .: "body"
else fail "Not an email")
parseJSON invalid = typeMismatch "Blob" invalid
instance ToJSON EmailBlob where
toJSON (EmailBlob from headers body) =
object ["camliVersion" .= (1 :: Int)
,"camliType" .= ("email" :: Text)
,"from" .= from
,"headers" .= headers
,"body" .= body]
indexBlob :: SomeBlobServer -> SomeIndexServer -> SHA1 -> EmailBlob -> IO ()
indexBlob store serv sha (EmailBlob from headers body) = do
exists <- permanodeHasContent serv sha
when exists $ do
setPermanodeShowInUI serv sha
setSearchHigh serv sha $
T.concat [fromMaybe "" $ getHeader headers "From", "\n"
,fromMaybe "" $ getHeader headers "Subject", "\n"]
b <- File.readFileBytes store body
let body' = T.decodeUtf8 $ BL.toStrict $ Builder.toLazyByteString b
setSearchLow serv sha body'
let preview = (maybe "" (<> "\n") (getHeader headers "Subject"))
<> (maybe "" (\x -> "From: " <> x <> "\n") (getHeader headers "From"))
<> (maybe "" (\x -> "Date: " <> x <> "\n") (getHeader headers "Date"))
setPermanodePreview serv sha preview
recognizeBlob :: SomeBlobServer -> SomeIndexServer -> Key -> File -> (File -> IO ()) -> IO ()
recognizeBlob store serv key file recognize =
case map toLower $ takeExtension (T.unpack $ fileName file) of
".mbox" -> emailextract store serv key file
ext -> return ()
emailextract :: SomeBlobServer -> SomeIndexServer -> Key -> File -> IO ()
emailextract store serv key f = do
let messages = parseMBox (TL.decodeUtf8 (fileContent f))
mapM_ (\m -> do log' $ "Adding email '" <> TL.toStrict (fromLine m) <> "'."
brefs <- File.addChunks store (BL.toStrict $ TL.encodeUtf8 $ body m)
let email = EmailBlob (TL.toStrict $ fromLine m)
(map (uncurry Header . (TL.toStrict *** TL.toStrict)) (headers m))
(map (uncurry File.Part) brefs)
let emailblob = BL.toStrict $ encodePretty email
exists <- statBlob store emailblob
if exists then return () else do
(SHA1 eref) <- writeBlob store emailblob
(pref, permablob) <- Permanode.addPermanode store key
(cref, claimblob) <- Permanode.setAttribute store key pref "camliContent" eref
Permanode.indexBlob store serv pref permablob
Permanode.indexBlob store serv cref claimblob
indexBlob store serv (SHA1 eref) email
) messages
toHtml :: SomeBlobServer -> SomeIndexServer -> (L.Substitutions () -> Text -> IO (Maybe Response)) -> SHA1 -> BL.ByteString -> IO (Maybe Response)
toHtml store serv renderWith sha bs = do
case decode bs of
Just (EmailBlob from headers body) -> do
b <- File.readFileBytes store body
let body = T.decodeUtf8 $ BL.toStrict $ Builder.toLazyByteString b
renderWith (L.subs
[("from", L.textFill $ getHeader headers "From")
,("subject", L.textFill $ getHeader headers "Subject")
,("message-id", L.textFill $ getHeader headers "Message-ID")
,("date", L.textFill $ getHeader headers "Date")
,("body-content", L.textFill body)])
"email"
_ -> return Nothing
where getHeader hs h = let (Header _ v) = fromMaybe (Header "" "") $ listToMaybe $ filter (\(Header n v) -> n == h) hs in v
| dbp/shed | src/Shed/Blob/Email.hs | isc | 6,011 | 0 | 22 | 1,977 | 1,799 | 940 | 859 | 111 | 2 |
-- Part 1: State monad as a functor
module Session5.State (test) where
import Prelude
data State s a = State (s -> (a, s))
instance Functor (State s) where
fmap g (State f) = State (\st -> let (a, st') = f st
b = g a
in (b, st'))
(>=>) :: (a -> [b]) -> (b -> [c]) -> a -> [c]
f >=> g = \a -> let bs = f a
css = fmap g bs
in concat css
test :: IO ()
test = do
let f0 :: Int -> [String]
f0 _ = []
f1 :: String -> [Double]
f1 _ = []
g = f0 >=> f1
print $ g 0
return ()
| seahug/pcph-scratch | src/Session5/State.hs | mit | 634 | 0 | 13 | 287 | 290 | 154 | 136 | 20 | 1 |
module Graphics.Cogh.Image
( newTextureFromImage
) where
import Foreign.C
import Foreign.Ptr
import Graphics.Cogh.Render
import Graphics.Cogh.Window.Internal
type ImagePtr = Ptr ()
newTextureFromImage :: Window -> FilePath -> IO Texture
newTextureFromImage w file = do
cTexture <- withCString file $ \cString -> cNewTextureFromImage w cString
newTexture cTexture
foreign import ccall unsafe "newTextureFromImage"
cNewTextureFromImage :: Window -> CString -> IO ImagePtr
| ivokosir/cogh | src/Graphics/Cogh/Image.hs | mit | 497 | 0 | 10 | 84 | 127 | 68 | 59 | 13 | 1 |
{-# LANGUAGE MultiParamTypeClasses
, RankNTypes
, TemplateHaskell
#-}
-- in comments, [q| xxx |] is intended to mean 'like [| xxx |], but outside
-- of the Q monad
{- |
Description : embedded 'option types' for use in OptDesc descriptor strings
Copyright : (c) Martyn J. Pearce 2014, 2015
License : BSD
Maintainer : [email protected]
embedded 'option types' for use in OptDesc descriptor strings
-}
module Console.Getopt.OTypes
( pclvType, pclvTypename, parser, setter, enactor, startIsDefault
, typeDefault, typeStart, optionTypename, optionType )
where
-- to make a thing use maybe:
-- -) add "Maybe " ++ to pclvTypename
-- -) list the field in dfGetter'
-- -) adjust the setter to use the maybeized setter
-- -) compose Just onto the front of the parser
-- -) compose Just onto the front of the defaults
-- base --------------------------------
import Data.Char ( isUpper )
-- template-haskell --------------------
import Language.Haskell.TH ( Exp ( AppE, ConE, LitE, SigE, VarE )
, Lit ( IntegerL, StringL )
, Type( AppT, ArrowT, ConT )
, ExpQ, Name
, mkName
)
-- fluffy ------------------------------
import Fluffy.Data.List ( splitOn2 )
import Fluffy.Language.TH ( composeApE, composeE, mAppE, stringE )
import Fluffy.Language.TH.Type ( readType, strToT )
-- this package --------------------------------------------
import Console.Getopt ( setval, setvaltM
, setvalcM, setvalc'M
, setvalsM, setvals'M
)
import Console.Getopt.CmdlineParseable ( FileRO, enactOpt )
import Console.Getopt.ParseOpt ( parseAs )
--------------------------------------------------------------------------------
-- | return type for oType function; info about how we handle option-target
-- pseudo-types (e.g., incr, or ?Int)
-- so we take a command-line string, parse it with parser_, set it
-- with setter_ , into the PCLV record. And we use
-- enactor to take the PCLV field or the uber-default, and set that into the
-- OV record.
data OptType = OptType { {- | the type used for the PCLV container field.
Note that this will be prefixed with "Maybe" by
the `pclvTypename` fn, since we need to handle
option defaults
-}
pclvTypename_ :: String -- e.g., "Maybe FilePath"
-- | the type used for the OV container field
, optionTypename_ :: String -- e.g., "Handle"
{- | how to take a value that has been parsed by
parser_, and store it into the PCLV record.
Thus, no IO. This one will need setval or
similar to set the value in the record. We pass
in a start value to initialize the lens when it
is called (but not beforehand, so we may
determine an uncalled opt)
-}
, setter_ :: Exp -- e.g., [q| setval return |]
{- | how to parse a String to generate a value; as an
Exp (:: String -> optionType). This also
includes parsing a default value given in the
string to mkopts.
-}
, parser_ :: Exp -- e.g., readParser "<type>"
{- | how to take a value, perform IO on it to provide
a user value. This must be capable of handling
default values, too (so that, say, a default
filero of "/etc/motd" doesn't do its IO unless
the default is actually used)
-}
, enactor_ :: Exp -- e.g., [q| openFileRO |]
{- | The value to use as the default for an option,
if no default is provided to mkopts (in <...>).
If Nothing, then it is an error to fail to
provide a default to mkopts.
-}
, default_ :: Maybe Exp -- e.g., Just [q| 0 |]
{- | The value to use as the start value for an
option, if none is provided to mkopts (in a
second(?) pair of <...>).
If Nothing, then there is no start value for
this type; it starts with Nothing or empty list
or empty map.
-}
, start_ :: Maybe Exp -- e.g., Just [q| 0 |]
{- | If true, there are no distinct start & default;
the start value is the default value. E.g., for
incr, it makes no sense to have different start
& default values.
-}
, startIsDefault_ :: Bool
}
deriving Show
--------------------------------------------------------------------------------
-- | \ t -> [q| readType t :: String -> t |]
readParser :: String -> Exp
readParser t = SigE (AppE (VarE 'readType) (LitE (StringL t)))
(AppT (AppT ArrowT (ConT ''String)) (strToT t))
readInt :: Exp
readInt = readParser "Int"
-- | open a file in read-only mode
openFileRO :: FilePath -> IO FileRO
openFileRO = enactOpt
-- | call setval on a thing parsed to type t
setval_as :: String -> Exp
setval_as t = -- [q| const $ setval (parseAs t) |]
composeApE (VarE 'const)
(AppE (VarE 'setval)
(AppE (VarE 'parseAs) (stringE t)))
-- | like setval_as, but prefixes the result with Just to use in a '?' type
setval_as_maybe :: String -> Exp
setval_as_maybe t = -- [q| const $ setval ((fmap Just) . (parseAs t)) |]
composeApE (VarE 'const)
(AppE (VarE 'setval)
(composeE (AppE (VarE 'fmap) (ConE 'Just))
(AppE (VarE 'parseAs)
(stringE t))))
------------------------------------------------------------
nothingE :: Exp
nothingE = ConE 'Nothing
falseE :: Exp
falseE = ConE 'False
emptyE :: Exp
emptyE = ConE '[]
-- oType for a list type, i.e., "[<type>]", e.g., "[String]"
oType_Listish :: String -> Exp -> OptType
oType_Listish t f =
OptType { pclvTypename_ = t
, optionTypename_ = t
, setter_ = -- [q| f (parseAs tt) |]
AppE f
(AppE (VarE 'parseAs) (stringE t))
, parser_ = readParser t
, enactor_ = VarE 'return
, default_ = Just emptyE
, start_ = Just emptyE
, startIsDefault_ = False
}
oType_List :: String -> OptType
oType_List t = oType_Listish t (VarE 'setvalsM)
oType_ListSplit :: String -> String -> OptType
oType_ListSplit delim t =
oType_Listish ("[" ++ t ++ "]") (AppE (VarE 'setvals'M) (stringE delim))
------------------------------------------------------------
-- oType for incr/decr
zeroE :: Exp
zeroE = LitE $ IntegerL 0
justZeroE :: Exp
justZeroE = AppE (ConE 'Just) zeroE
oType_Counter :: Name -> OptType
oType_Counter f =
OptType { pclvTypename_ = "Int"
, optionTypename_ = "Int"
, setter_ = VarE f
-- we need a parser to parse a potential default value
, parser_ = readInt
, enactor_ = VarE 'return
, default_ = Just zeroE
, start_ = Just justZeroE
, startIsDefault_ = True
}
----------------------------------------
oType_FileRO :: OptType
oType_FileRO =
OptType { pclvTypename_ = "FilePath"
, optionTypename_ = "FileRO"
, setter_ = -- [q| const $ setval return |]
composeApE (VarE 'const)
(AppE (VarE 'setval) (VarE 'return))
, parser_ = VarE 'id
, enactor_ = VarE 'openFileRO
, default_ = Just nothingE
, start_ = Just nothingE
, startIsDefault_ = True
}
----------------------------------------
oType_Maybe :: String -> OptType
oType_Maybe t =
OptType { pclvTypename_ = "Maybe " ++ t
, optionTypename_ = '?' : t
, setter_ = setval_as_maybe t
, parser_ = readParser t
, enactor_ = VarE 'return
, default_ = Just nothingE
, start_ = Just nothingE
, startIsDefault_ = False
}
----------------------------------------
oType_MaybeIO :: String -> OptType
oType_MaybeIO t =
OptType { pclvTypename_ = "Maybe String"
, optionTypename_ = '?' : t
, setter_ = setval_as_maybe t
, parser_ = VarE 'id
, enactor_ =
-- [q| maybe (return Nothing) ((fmap Just) . enactOpt) |]
mAppE [ VarE 'maybe
, AppE (VarE 'return) nothingE
, composeE (AppE (VarE 'fmap) (ConE 'Just)) (VarE 'enactOpt)
]
, default_ = Just nothingE
, start_ = Just nothingE
, startIsDefault_ = False
}
----------------------------------------
oType_IO :: String -> OptType
oType_IO t =
OptType { pclvTypename_ = "String"
, optionTypename_ = t
, setter_ = setval_as t
, parser_ = VarE 'id
, enactor_ = VarE 'enactOpt
, default_ = Nothing
, start_ = Just nothingE
, startIsDefault_ = False
}
----------------------------------------
oType_Simple :: String -> OptType
oType_Simple t =
OptType { pclvTypename_ = t
, optionTypename_ = t
, setter_ = setval_as t
, parser_ = readParser t
, enactor_ = VarE 'return
, default_ =
case t of
"String" -> Just . LitE $ StringL ""
"Int" -> Just . LitE $ IntegerL 0
_ -> Nothing
-- since values are set rather than updated, it makes
-- no sense to have a start /= default
, start_ = Just nothingE
, startIsDefault_ = True
}
----------------------------------------
oType_Bool :: OptType
oType_Bool =
OptType { pclvTypename_ = "Bool"
, optionTypename_ = "Bool"
, setter_ = VarE 'setvaltM
, parser_ = readParser "Bool"
, enactor_ = VarE 'return
, default_ = Just falseE
-- since values are set rather than updated, it makes
-- no sense to have a start /= default
, start_ = Just falseE
, startIsDefault_ = True
}
------------------------------------------------------------
oType :: String -> OptType
oType "incr" = oType_Counter 'setvalcM -- incr
oType "decr" = oType_Counter 'setvalc'M -- decr
oType "filero" = oType_FileRO -- filero
oType ('?' : '*' : t@(h :_)) -- ?*TYPE -- (maybe IO)
| isUpper h = oType_MaybeIO t
| otherwise = error $ "no such option type: '?*" ++ t ++ "'"
oType ('?':t) = oType_Maybe t -- ?TYPE -- (maybe)
oType ('[':',':t) -- [,TYPE] -- (list, split on ,)
| last t == ']'
= oType ("[<,>" ++ t)
oType tt@('[':'<':s) -- [<X>TYPE] -- (list, split on X)
| '>' `elem` s && last s == ']'
= let (d,t') = splitOn2 ">" s
t = init t'
in oType_ListSplit d t
| otherwise = error $ "no such option type: '" ++ tt ++ "'"
oType tt@('[':t) -- [TYPE] -- (list)
| and [ not (null t), (isUpper (head t) || '[' == head t) , last t == ']' ]
= oType_List tt
oType ('*' : t@(h : _)) -- '*TYPE' -- (IO)
| isUpper h = oType_IO t
| otherwise = error $ "no such option type: '*" ++ t ++ "'"
oType [] = oType_Bool -- simple boolean
oType t@(h:_) -- TYPE -- simple type
| isUpper h = oType_Simple t
| otherwise = error $ "no such option type: '" ++ t ++ "'"
--Y oType tt@('[' : '*' : t@(h :_))
--Y | isUpper h && last t == ']' =
--Y def { pclvTypename_ = '[' : t
--Y , optionTypename_ = '[' : t
--Y , setter_ = VarE 'setvals
--Y , enactor_ = VarE 'enactOpt
--Y , parser_ = VarE 'id
--Y , default_ = Just $ ConE '[]
--Y , start_ = Just $ ConE '[]
--Y }
--Y
--Y | otherwise = error $ "no such option type: '" ++ tt ++ "'"
-- typeDefault -----------------------------------------------------------------
-- | uber-default value for named type
typeDefault :: String -> Maybe ExpQ
typeDefault = fmap return . default_ . oType
-- typeStart -------------------------------------------------------------------
-- | uber-default start value for named type
typeStart :: String -> Maybe ExpQ
typeStart = fmap return . start_ . oType
-- pclvTypename -------------------------------------------------------------------
-- | type to use within the PCLV record for a requested option type
-- (so Int becomes Maybe Int (to allow for default != start) for example)
pclvTypename :: String -> String
pclvTypename = ("Maybe " ++) . pclvTypename_ . oType
-- pclvType --------------------------------------------------------------------
-- | type to use within the PCLV record for a requested option type
-- (so Int becomes Maybe Int (to allow for default != start) for example)
pclvType :: String -> Type
pclvType = ConT . mkName . pclvTypename
-- optionTypename -----------------------------------------------------------------
-- | type to represent to the getopt developer for a requested option type (so
-- incr becomes Int, for example)
optionTypename :: String -> String
optionTypename = optionTypename_ . oType
-- optionType ------------------------------------------------------------------
-- | type to represent to the getopt developer for a requested option type (so
-- incr becomes Int, for example)
optionType :: String -> Type
optionType = ConT . mkName . optionTypename
-- setter ----------------------------------------------------------------------
{- | how to take a value that has been parsed by parser_, and store it into the
PCLV record. Thus, no IO. This one will need setval or similar to set the
value in the record. It expects a start value as its first argument.
-}
setter :: String -> Exp
setter = setter_ . oType
-- parser ----------------------------------------------------------------------
{- | how to parse a String to generate a value; as an
Exp (:: String -> optionType). This also includes parsing a default value
given in the string to mkopts
-}
parser :: String -> Exp
parser = parser_ . oType
-- enactor ---------------------------------------------------------------------
{- | how to take a value, perform IO on it to provide a user value. This must
be capable of handling default values, too (so that, say, a default filero
of "/etc/motd" doesn't do its IO unless the default is actually used)
-}
enactor :: String -> Exp
enactor = enactor_ . oType
-- enactor _ = VarE 'enactOpt
-- startIsDefault --------------------------------------------------------------
{- | If true, there are no distinct start & default; the start value is the
default value. E.g., for incr, it makes no sense to have different start &
default values.
-}
startIsDefault :: String -> Bool
startIsDefault = startIsDefault_ . oType
| sixears/getopt | src/Console/Getopt/OTypes.hs | mit | 16,768 | 1 | 15 | 6,214 | 2,312 | 1,328 | 984 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables, FlexibleInstances #-} -- allows "forall t. NetworkDescription t"
module Main where
import Control.Monad (when)
import Data.Maybe (isJust, fromJust)
import Data.List (nub)
import System.Random
import System.IO
import Debug.Trace
import Data.IORef
import Reactive.Banana as R
import Reactive.Banana.Frameworks as R
import AsteroidTexts
import AsteroidData
main :: IO ()
main = do
displayHelpMessage
source <- makeSource
network <- compile $ setupNetwork source
actuate network
eventLoop source
makeSource = newAddHandler
eventLoop :: EventSource () -> IO ()
eventLoop roll = loop
where
loop = do
putStr">> "
hFlush stdout
s <- getLine
case s of
"v" -> fire roll ()
"q" -> return ()
_ -> putStrLn $ s ++ " - unknown"
when (s /= "q") loop
type EventSource a = (AddHandler a, a -> IO ())
addHandler :: EventSource a -> AddHandler a
addHandler = fst
fire :: EventSource a -> a -> IO ()
fire = snd
setupNetwork :: forall t. Frameworks t =>
EventSource () -> Moment t ()
setupNetwork esroll = do
initialStdGen <- liftIO $ newStdGen
eroll <- fromAddHandler $ addHandler esroll
let
-- Behavior and event for the random number generator.
bStdGen :: Behavior t StdGen
eNewRand :: Event t Int
(eNewRand, bStdGen) = mapAccum initialStdGen (rand <$> eDoesRoll)
rand :: () -> StdGen -> (Int, StdGen)
rand () gen0 = (x, gen1)
where
random = randomR(1,6)
(x, gen1) = random gen0
-- Behavior and event for the GameState
bGameState :: Behavior t GameState
eGameState :: Event t GameState
(eGameState, bGameState) = mapAccum initialGameState . fmap (\x y -> (x y, x y)) $ updateGameState <$> eNewRand
eDoesRoll :: Event t ()
eDoesRoll = filterApply ((\x _ -> isAlive x) <$> bGameState) eroll
eAsteroid :: Event t Int
eAsteroid = filterE (>= 1) $ asteroidFromGS <$> eGameState
eWin :: Event t ()
eWin = () <$ filterE (\x -> getShipPos x == 6) eGameState
eDie :: Event t ()
eDie = () <$ filterE isDead eGameState
--reactimate $ displayShipState <$> eShipState
reactimate $ putStrLn . showRoll <$> eNewRand
reactimate $ displayAsteroidMessage <$> eAsteroid
reactimate $ displayWinMessage <$ eWin
reactimate $ displayDieMessage <$ eDie
reactimate $ displayShipStatus . getShip <$> eGameState
showRoll y = "You rolled: " ++ show y
| KatsCyl/AsteroidRoulette | app/AsteroidGame.hs | mit | 2,546 | 0 | 17 | 671 | 800 | 410 | 390 | 67 | 3 |
module Main where
import Party
main :: IO ()
main = do
raw <- readFile "company.txt"
let guestList = maxFun $ read raw
putStrLn $ (listHeader guestList) ++ "\n" ++ (guestNames guestList)
| bachase/cis194 | hw8/Main.hs | mit | 200 | 0 | 11 | 45 | 75 | 37 | 38 | 7 | 1 |
--
-- xmonad example config file.
--
-- A template showing all available configuration hooks,
-- and how to override the defaults in your own xmonad.hs conf file.
--
-- Normally, you'd only override those defaults you care about.
--
import XMonad
import System.Exit
import XMonad.Config.Gnome
import XMonad.Config.Desktop
import XMonad.Hooks.ManageDocks
import XMonad.Actions.SpawnOn
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageHelpers
import XMonad.Util.Run(spawnPipe)
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.EwmhDesktops
import XMonad.Layout.Cross
import XMonad.Layout.Circle
import XMonad.Layout.Accordion
import XMonad.Layout.NoBorders
import Graphics.X11.ExtraTypes.XF86
import XMonad.Actions.SwapWorkspaces
import System.IO
import qualified XMonad.StackSet as W
import qualified Data.Map as M
-- The preferred terminal program, which is used in a binding below and by
-- certain contrib modules.
--
myTerminal = "gnome-terminal"
-- Width of the window border in pixels.
--
myBorderWidth = 1
-- modMask lets you specify which modkey you want to use. The default
-- is mod1Mask ("left alt"). You may also consider using mod3Mask
-- ("right alt"), which does not conflict with emacs keybindings. The
-- "windows key" is usually mod4Mask.
--
myModMask = mod4Mask
-- The mask for the numlock key. Numlock status is "masked" from the
-- current modifier status, so the keybindings will work with numlock on or
-- off. You may need to change this on some systems.
--
-- You can find the numlock modifier by running "xmodmap" and looking for a
-- modifier with Num_Lock bound to it:
--
-- > $ xmodmap | grep Num
-- > mod2 Num_Lock (0x4d)
--
-- Set numlockMask = 0 if you don't have a numlock key, or want to treat
-- numlock status separately.
--
--myNumlockMask = mod2Mask
-- The default number of workspaces (virtual screens) and their names.
-- By default we use numeric strings, but any string may be used as a
-- workspace name. The number of workspaces is determined by the length
-- of this list.
--
-- A tagging example:
--
-- > workspaces = ["web", "irc", "code" ] ++ map show [4..9]
--
myWorkspaces = ["web", "2","3","4","5","6","7","8","9","0", "-", "=", "ctl"] -- ctl is ~
-- Border colors for unfocused and focused windows, respectively.
--
selected = "'#fad184'"
background = "'#efebe7'"
foreground = "'#000000'"
myNormalBorderColor = "#dddddd"
myFocusedBorderColor = "#ff8822"
-- height matches Ubuntu top Gnome panel
barHeight = "24"
-- font intended to match Ubuntu default application font
appFontXft = "'xft\
\:Sans\
\:pixelsize=14\
\:weight=regular\
\:width=semicondensed\
\:dpi=96\
\:hinting=true\
\:hintstyle=hintslight\
\:antialias=true\
\:rgba=rgb\
\:lcdfilter=lcdlight\
\'"
-- currently dzen2 compiled locally to get xft support
-- (-e prevents loss of title if naive user clicks on dzen2)
myDzenTitleBar =
"dzen2\
\ -ta l\
\ -x 400 -w 900 -y 0\
\ -e 'entertitle=uncollapse'\
\ -h " ++ barHeight ++ "\
\ -bg " ++ background ++ "\
\ -fg " ++ foreground ++ "\
\ -fn " ++ appFontXft
-- dmenu patched and compiled locally to add xft support
myDmenuTitleBar =
"exec `dmenu_run \
\ -i\
\ -bh " ++ barHeight ++ "\
\ -nb " ++ background ++ "\
\ -nf " ++ foreground ++ "\
\ -sb " ++ selected ++ "\
\ -fn " ++ appFontXft ++ "\
\`"
--"
------------------------------------------------------------------------
-- Key bindings. Add, modify or remove key bindings here.
--
myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $
-- launch a terminal
[ ((modm , xK_Return), spawn $ XMonad.terminal conf)
, ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf)
-- launch dmenu
--, ((modm , xK_p ), spawn "exe=`dmenu_path | dmenu` && eval \"exec $exe\"")
, ((modm , xK_p ), spawn "dmenu_run")
-- launch gnome-do
--, ((modm , xK_p ), spawn "gnome-do")
-- close focused window
, ((modm .|. shiftMask, xK_c ), kill)
-- Musicazoo
, ((shiftMask, xF86XK_AudioRaiseVolume ), spawn "mz vol up > /dev/null")
, ((shiftMask, xF86XK_AudioLowerVolume ), spawn "mz vol down > /dev/null")
, ((shiftMask, xF86XK_AudioMute ), spawn "mz skip > /dev/null")
-- Rotate through the available layout algorithms
, ((modm, xK_space ), sendMessage NextLayout)
-- Reset the layouts on the current workspace to default
, ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf)
-- Resize viewed windows to the correct size
, ((modm, xK_n ), refresh)
-- Move focus to the next window
, ((modm, xK_Tab ), windows W.focusDown)
-- Move focus to the next window
, ((modm, xK_j ), windows W.focusDown)
-- Move focus to the previous window
, ((modm, xK_k ), windows W.focusUp )
-- Move focus to the master window
, ((modm, xK_m ), windows W.focusMaster )
-- Swap the focused window and the master window
--, ((modm, xK_Return), windows W.swapMaster)
-- Swap the focused window with the next window
, ((modm .|. shiftMask, xK_j ), windows W.swapDown )
-- Swap the focused window with the previous window
, ((modm .|. shiftMask, xK_k ), windows W.swapUp )
-- Shrink the master area
, ((modm, xK_h ), sendMessage Shrink)
-- Expand the master area
, ((modm, xK_l ), sendMessage Expand)
-- Push window back into tiling
, ((modm, xK_t ), withFocused $ windows . W.sink)
-- Increment the number of windows in the master area
, ((modm , xK_comma ), sendMessage (IncMasterN 1))
-- Deincrement the number of windows in the master area
, ((modm , xK_period), sendMessage (IncMasterN (-1)))
-- Lock screen
, ((modm .|. shiftMask, xK_l ), spawn "gnome-screensaver-command -l")
-- Suspend
, ((modm .|. shiftMask, xK_s ), spawn "sudo pm-suspend")
-- Hibernate
, ((modm .|. shiftMask, xK_h ), spawn "sudo pm-hibernate")
--, ((modm, xK_z ), spawn "export DISPLAY=:0; /home/zbanks/autoclick ")
-- toggle the status bar gap (used with avoidStruts from Hooks.ManageDocks)
-- , ((modm , xK_b ), sendMessage ToggleStruts)
, ((modm .|. shiftMask, xK_o ), spawn myDmenuTitleBar)
-- Quit xmonad
--, ((modm .|. shiftMask, xK_q ), io (exitWith ExitSuccess))
-- Weird shortcuts
, ((modm .|. shiftMask, xK_q ), spawn "gnome-terminal -x sh -c 'vim ~/.xmonad/xmonad.hs'")
, ((modm .|. shiftMask, xK_g ), spawn "sleep 0.3; gnome-screenshot --area")
-- Restart xmonad
, ((modm , xK_q ), restart "xmonad" True)
]
++
--
-- mod-[1..9], Switch to workspace N
-- mod-shift-[1..9], Move client to workspace N
--
[((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) ([xK_1 .. xK_9]++[xK_0, xK_minus, xK_equal, xK_grave])
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
++
--
-- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3
-- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3
--
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
++
[((modm .|. controlMask, k), windows $ swapWithCurrent i)
| (i, k) <- zip (XMonad.workspaces conf) [xK_1 ..]]
------------------------------------------------------------------------
-- Mouse bindings: default actions bound to mouse events
--
myMouseBindings (XConfig {XMonad.modMask = modMask}) = M.fromList $
-- mod-button1, Set the window to floating mode and move by dragging
[ ((modMask .|. shiftMask, button1), (\w -> focus w >> mouseMoveWindow w))
-- mod-button2, Raise the window to the top of the stack
, ((modMask .|. shiftMask, button2), (\w -> focus w >> windows W.swapMaster))
-- mod-button3, Set the window to floating mode and resize by dragging
, ((modMask .|. shiftMask, button3), (\w -> focus w >> mouseResizeWindow w))
-- you may also bind events to the mouse scroll wheel (button4 and button5)
]
------------------------------------------------------------------------
-- Layouts:
-- You can specify and transform your layouts by modifying these values.
-- If you change layout bindings be sure to use 'mod-shift-space' after
-- restarting (with 'mod-q') to reset your layout state to the new
-- defaults, as xmonad preserves your old layout settings by default.
--
-- The available layouts. Note that each layout is separated by |||,
-- which denotes layout choice.
--
myLayout = avoidStruts ( smartBorders tiled ||| Mirror tiled ||| noBorders Full ||| radiance)
where
radiance = Mirror $ Tall 1 0 (782/1080)
-- default tiling algorithm partitions the screen into two panes
tiled = Tall nmaster delta ratio
-- The default number of windows in the master pane
nmaster = 1
-- Default proportion of screen occupied by master pane
ratio = 1/2
-- Percent of screen to increment by when resizing panes
delta = 3/100
------------------------------------------------------------------------
-- Window rules:
-- Execute arbitrary actions and WindowSet manipulations when managing
-- a new window. You can use this to, for example, always float a
-- particular program, or have a client always appear on a particular
-- workspace.
--
-- To find the property name associated with a program, use
-- > xprop | grep WM_CLASS
-- and click on the client you're interested in.
--
-- To match on the WM_NAME, you can use 'title' in the same way that
-- 'className' and 'resource' are used below.
--
-- | Move the window to a given workspace
doSink = ask >>= \w -> doF (W.sink w)
--doSwapMaster = ask >>= \w -> doF (W.swapMaster w)
myManageHook = composeAll
[ manageHook gnomeConfig
, className =? "MPlayer" --> doFloat
, className =? "Gimp" --> doFloat
, className =? "Do" --> doIgnore
, className =? "radiance" --> doSink
, className =? "radiance" --> doF W.swapMaster
, resource =? "desktop_window" --> doIgnore
, resource =? "kdesktop" --> doIgnore
, isFullscreen --> doFullFloat ] <+> manageDocks
-- Whether focus follows the mouse pointer.
myFocusFollowsMouse :: Bool
myFocusFollowsMouse = True
------------------------------------------------------------------------
-- Status bars and logging
-- Perform an arbitrary action on each internal state change or X event.
-- See the 'DynamicLog' extension for examples.
--
-- To emulate dwm's status bar
--
-- > logHook = dynamicLogDzen
--
-----------------------------
myLogHookWithPP :: PP -> X ()
myLogHookWithPP pp = do
ewmhDesktopsLogHook
dynamicLogWithPP pp
-------------------------------------------
-- Startup hook
-- Perform an arbitrary action each time xmonad starts or is restarted
-- with mod-q. Used by, e.g., XMonad.Layout.PerWorkspace to initialize
-- per-workspace layout choices.
--
-- By default, do nothing.
myStartupHook = do
-- spawnOnce "google-chrome"
spawn "xmodmap -e 'remove Lock = Caps_Lock'"
spawn "xmodmap -e 'keysym Caps_Lock = Escape'"
spawn "setxkbmap -option caps:escape"
--spawn "xmobar"
spawnOn "ctl" "gnome-terminal --class=CtlTerm -e 'alsamixer -c1'"
spawnOn "ctl" "gnome-terminal --class=CtlTerm -e 'watch -n10 acpi -V'"
spawnOn "ctl" "gnome-terminal --class=CtlTerm -e nmtui"
gnomeRegister
startupHook desktopConfig
------------------------------------------------------------------------
-- Now run xmonad with all the defaults we set up.
-- Run xmonad with the settings you specify. No need to modify this.
--
main = do
xmonad $ gnomeConfig {
-- simple stuff
terminal = myTerminal,
focusFollowsMouse = myFocusFollowsMouse,
borderWidth = myBorderWidth,
modMask = myModMask,
--numlockMask = myNumlockMask,
workspaces = myWorkspaces,
normalBorderColor = myNormalBorderColor,
focusedBorderColor = myFocusedBorderColor,
-- key bindings
keys = myKeys,
mouseBindings = myMouseBindings,
-- hooks, layouts
layoutHook = myLayout,
manageHook = myManageHook,
startupHook = myStartupHook
}
-- A structure containing your configuration settings, overriding
-- fields in the default config. Any you don't override, will
-- use the defaults defined in xmonad/XMonad/Config.hs
--
-- No need to modify this.
--
--defaults = gnomeConfig {
---- simple stuff
--terminal = myTerminal,
--focusFollowsMouse = myFocusFollowsMouse,
--borderWidth = myBorderWidth,
--modMask = myModMask,
--numlockMask = myNumlockMask,
--workspaces = myWorkspaces,
--normalBorderColor = myNormalBorderColor,
--focusedBorderColor = myFocusedBorderColor,
--
---- key bindings
--keys = myKeys,
--mouseBindings = myMouseBindings,
--
---- hooks, layouts
--layoutHook = myLayout,
--manageHook = myManageHook,
--logHook = myLogHook,
--startupHook = myStartupHook
--}
| zbanks/dotfiles | xmonad.hs | mit | 13,879 | 0 | 15 | 3,526 | 1,949 | 1,201 | 748 | 134 | 1 |
{-# htermination delFromFM :: Ord a => FiniteMap (Maybe a) b -> (Maybe a) -> FiniteMap (Maybe a) b #-}
import FiniteMap
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/FiniteMap_delFromFM_9.hs | mit | 122 | 0 | 3 | 24 | 5 | 3 | 2 | 1 | 0 |
{-| Module to take historical data copied from e.g.
http://www.investing.com/currencies/eur-gbp-historical-data
and stored in a text file, and convert it to haskell structures
for further processing
-}
module InvestingDotComConverter where
import Data.Char (ord)
import Data.Csv
import qualified Data.ByteString.Lazy as BS
import qualified Data.Vector as DV
import Control.Applicative
import Data.Time
data HistoricalFx = HistoricalFx {
date :: String,
last :: Double,
open :: Double,
high :: Double,
low :: Double,
change :: String
} deriving (Show)
instance FromRecord HistoricalFx where
parseRecord v
| DV.length v == 6 = HistoricalFx <$>
v .! 0 <*>
v .! 1 <*>
v .! 2 <*>
v .! 3 <*>
v .! 4 <*>
v .! 5
| otherwise = fail "Unable to parse data as HistoricalFx"
decodeOptions = defaultDecodeOptions {
decDelimiter = fromIntegral $ ord '\t'
}
decodeTabDelimited :: FromRecord a => BS.ByteString -> Maybe [a]
decodeTabDelimited s = case Data.Csv.decodeWith decodeOptions HasHeader s of
Left _ -> Nothing
Right decoded -> Just $ DV.toList decoded
decodeHistoricalFx :: FilePath -> IO (Maybe [HistoricalFx])
-- decodeHistoricalFx f = do
-- encoded <- BS.readFile f
-- return $ parseDates <$> decodeTabDelimited encoded
decodeHistoricalFx f = BS.readFile f >>= process
where process encoded = return $ parseDates <$> decodeTabDelimited encoded
parseDates :: [HistoricalFx] -> [HistoricalFx]
parseDates = map updateDates
where updateDates fx = fx { date = doParse $ date fx }
doParse = showGregorian . parseTimeOrError True defaultTimeLocale "%b %d, %Y"
| lhoghu/yahoo-portfolio-manager | src/Data/YahooPortfolioManager/InvestingDotComConverter.hs | mit | 1,901 | 0 | 18 | 587 | 409 | 220 | 189 | 38 | 2 |
module TestStateMonad where
type Stack = [Int]
newtype State s a = State { runState :: s -> (a, s) }
instance Monad (State s) where
return x = State $ \s -> (x, s)
(State h) >>= f = State $ \s -> let (a, newState) = h s
(State g) = f a
in g newState
pop :: State Stack Int
pop = State $ \(x:xs) -> (x, xs)
push :: Int -> State Stack ()
push a = State $ \xs -> ((), a:xs)
stackManip :: State Stack Int
stackManip = do
push 3
a <- pop
pop
stackyStack :: State Stack ()
stackyStack = do
stackNow <- get
if stackNow == [1,2,3]
then put [8,3,1]
else put [9,2,1]
| rockdragon/julia-programming | code/haskell/TestStateMonad.hs | mit | 662 | 0 | 13 | 227 | 325 | 176 | 149 | 23 | 2 |
module LogicProblem.Solver.Def (
RApply(..)
, REntry
, RApplyResult(..)
, isSuccess
, isFailure
, isUndetermined
, getResultEntries
, RuleResult(..)
) where
import LogicProblem.Solver.Env
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
type ApplyRule1 e = e -> RApplyResult (Value e)
data RApply e = RApply1 (ApplyRule1 e)
| RApply2 (e -> ApplyRule1 e)
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
type REntry v = (Id, [v])
data RApplyResult v = RImplies { what :: [REntry v]
, reason :: [REntry v]
}
| RBroken [REntry v]
| RConfirm [REntry v]
| RPossible [REntry v]
deriving Show
isSuccess :: RApplyResult v -> Bool
isFailure :: RApplyResult v -> Bool
isUndetermined :: RApplyResult v -> Bool
getResultEntries :: RApplyResult v -> [REntry v]
isSuccess (RImplies _ _) = True
isSuccess (RConfirm _) = True
isSuccess _ = False
isFailure (RBroken _) = True
isFailure _ = False
isUndetermined (RPossible _) = True
isUndetermined _ = False
getResultEntries RImplies {what = w} = w
getResultEntries (RBroken es) = es
getResultEntries (RConfirm es) = es
getResultEntries (RPossible es) = es
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
data RuleResult r e = RuleContradicts r [RApplyResult (Value e)]
| RuleApplies r (RApplyResult (Value e))
| RuleMultiple r [RApplyResult (Value e)]
| RuleUnmatched r [RApplyResult (Value e)]
deriving Show
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
| fehu/h-logic-einstein | src/LogicProblem/Solver/Def.hs | mit | 1,931 | 0 | 10 | 669 | 472 | 262 | 210 | 40 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
-- | This executable generated .golden tests for importify.
module Main where
import Universum
import Path (fromRelFile, parseRelFile, (-<.>))
import Path.IO (removeFile)
import Test.Tasty.Golden (findByExtension, writeBinaryFile)
import Importify.Main (importifyFileContent)
import Importify.Path (testDataDir)
main :: IO ()
main = do
arguments <- getArgs
case arguments of
["--clean"] -> cleanGoldenExamples
["--force"] -> generateGoldenTestsPrompt True
[] -> generateGoldenTestsPrompt False
_ -> putText "Incorrect arguments!"
cleanGoldenExamples :: IO ()
cleanGoldenExamples = do
goldenExamples <- findByExtension [".golden"] testDataDir
mapM_ (parseRelFile >=> removeFile) goldenExamples
generateGoldenTestsPrompt :: Bool -> IO ()
generateGoldenTestsPrompt True = generateGoldenTests
generateGoldenTestsPrompt False = do
putText "> Are you sure want to generate new golden examples? [y/N]"
getLine >>= \case
"y" -> generateGoldenTests
_ -> putText "Aborting generation"
generateGoldenTests :: IO ()
generateGoldenTests = do
testCaseFiles <- findByExtension [".hs"] testDataDir
forM_ testCaseFiles $ \testCaseFile -> do
testCasePath <- parseRelFile testCaseFile
Right modifiedSrc <- importifyFileContent testCasePath
goldenPath <- testCasePath -<.> "golden"
writeBinaryFile (fromRelFile goldenPath) (toString modifiedSrc)
| kristoff3r/importify | test/GGenerator.hs | mit | 1,671 | 0 | 13 | 411 | 345 | 176 | 169 | 37 | 4 |
module Javelin.Lib.ByteCode.ConstantPool
( getConstants
) where
import qualified Data.Binary.Get as Get
import qualified Data.Map.Lazy as Map
import qualified Data.Word as Word
import qualified Unsafe.Coerce as Unsafe
import qualified Javelin.Lib.ByteCode.Data as ByteCode
import qualified Data.ByteString.UTF8 as BS
getConstants 1 = return []
getConstants len = do
constant <- getConstant
let double = ([constant, constant] ++) <$> getConstants (len - 2)
single = (constant :) <$> getConstants (len - 1)
case constant of
ByteCode.LongInfo _ -> double
ByteCode.DoubleInfo _ -> double
_ -> single
getConstant :: Get.Get ByteCode.Constant
getConstant = do
tag <- Get.getWord8
Map.findWithDefault (failingConstParser tag) tag constantTypeParser
failingConstParser :: Word.Word8 -> Get.Get ByteCode.Constant
failingConstParser x = fail $ "Undefined constant with index " ++ show x ++ "\n"
constantTypeParser :: Map.Map Word.Word8 (Get.Get ByteCode.Constant)
constantTypeParser =
Map.fromList
[ (1, utf8InfoParser)
, (3, integerInfoParser)
, (4, floatInfoParser)
, (5, longInfoParser)
, (6, doubleInfoParser)
, (7, classInfoParser)
, (8, stringInfoParser)
, (9, fieldrefParser)
, (10, methodrefParser)
, (11, interfaceMethodrefParser)
, (12, nameAndTypeInfoParser)
, (15, methodHandleInfoParser)
, (16, methodTypeInfoParser)
, (18, invokeDynamicInfoParser)
]
utf8InfoParser :: Get.Get ByteCode.Constant
utf8InfoParser = do
byteStringLen <- Get.getWord16be
byteString <- Get.getByteString $ fromIntegral byteStringLen
return $ ByteCode.Utf8Info $ BS.toString byteString
twoTwoBytesInfoParser :: (Word.Word16 -> Word.Word16 -> ByteCode.Constant) -> Get.Get ByteCode.Constant
twoTwoBytesInfoParser constConstr = constConstr <$> Get.getWord16be <*> Get.getWord16be
twoFourBytesInfoParser :: (Word.Word32 -> Word.Word32 -> ByteCode.Constant) -> Get.Get ByteCode.Constant
twoFourBytesInfoParser constConstr = constConstr <$> Get.getWord32be <*> Get.getWord32be
twoBytesInfoParser :: (Word.Word16 -> ByteCode.Constant) -> Get.Get ByteCode.Constant
twoBytesInfoParser constConstr = constConstr <$> Get.getWord16be
fourBytesInfoParser :: (Word.Word32 -> ByteCode.Constant) -> Get.Get ByteCode.Constant
fourBytesInfoParser constConstr = constConstr <$> Get.getWord32be
fieldrefParser = twoTwoBytesInfoParser ByteCode.Fieldref
methodrefParser = ByteCode.Methodref <$> Get.getWord16be <*> Get.getWord16be
interfaceMethodrefParser :: Get.Get ByteCode.Constant
interfaceMethodrefParser = twoTwoBytesInfoParser ByteCode.InterfaceMethodref
nameAndTypeInfoParser :: Get.Get ByteCode.Constant
nameAndTypeInfoParser = twoTwoBytesInfoParser ByteCode.NameAndTypeInfo
classInfoParser = twoBytesInfoParser ByteCode.ClassInfo
stringInfoParser = twoBytesInfoParser ByteCode.StringInfo
integerInfoParser = ByteCode.IntegerInfo <$> Unsafe.unsafeCoerce <$> Get.getWord32be
floatInfoParser = ByteCode.FloatInfo <$> Unsafe.unsafeCoerce <$> Get.getWord32be
longInfoParser = ByteCode.LongInfo <$> Unsafe.unsafeCoerce <$> Get.getWord64be
doubleInfoParser = ByteCode.DoubleInfo <$> Unsafe.unsafeCoerce <$> Get.getWord64be
methodHandleInfoParser = ByteCode.MethodHandleInfo <$> Get.getWord8 <*> Get.getWord16be
methodTypeInfoParser = ByteCode.MethodTypeInfo <$> Get.getWord16be
invokeDynamicInfoParser = twoTwoBytesInfoParser ByteCode.InvokeDynamicInfo
| antonlogvinenko/javelin | src/Javelin/Lib/ByteCode/ConstantPool.hs | mit | 3,437 | 23 | 13 | 459 | 950 | 485 | 465 | 68 | 3 |
{-# LANGUAGE TypeSynonymInstances #-}
module Graphics.DrawGL.Fold where
import Data.List
import Graphics.DrawGL.Internal
import Graphics.DrawGL.Types
class ShapeFold a where
foldShape :: (b -> a -> b) -> b -> Shape -> b
defaultColor = Color (1,1,1,1)
instance ShapeFold Vertex where
foldShape f a (Shape _ vs) = foldVertices f a vs
foldShape f a (ShapeSum s1 s2) = foldShape f a' s2 where
a' = foldShape f a s1
foldShape f a (ShapeList ss) = foldl' (foldShape f) a ss
foldShape f a (Transformed g s) = foldShape f' a s where
f' a = f a . snd . g . (,) defaultColor
instance ShapeFold ColoredVertex where
foldShape f a (Shape _ vs) = foldVertices f' a vs where
f' a = f a . (,) defaultColor
foldShape f a (ShapeSum s1 s2) = foldShape f a' s2 where
a' = foldShape f a s1
foldShape f a (ShapeList ss) = foldl' (foldShape f) a ss
foldShape f a (Transformed g s) = foldShape f' a s where
f' a = f a . g
foldVertices :: (b -> Vertex -> b) -> b -> Vertices -> b
foldVertices f a v = case v of
VertexList vs -> foldl' f a vs
VertexSum v1 v2 -> let a' = foldVertices f a v1 in foldVertices f a' v2
| shangaslammi/hdrawgl | src/Graphics/DrawGL/Fold.hs | mit | 1,200 | 6 | 18 | 329 | 516 | 258 | 258 | 27 | 2 |
module StupidBot.Goal where
import Vindinium.Types
import Utils
import Data.Maybe (fromJust, isNothing)
import qualified Data.Set as S
import Debug.Trace
data Mine = OwnedMine HeroId | AnyMine deriving (Show) -- any excludes mines that we own
data Goal = Capture Mine | Kill HeroId | Heal | Survive deriving (Show)
type GPS = State -> Goal
whereToGo :: GPS
whereToGo s
| heroLife (stateHero s) < 20 = Heal -- very advanced heuristic ©
| isTavernNearby s && heroLife (stateHero s) < 90 = Heal
| amWinning s = Survive
| otherwise = Capture AnyMine
amWinning :: State -> Bool
amWinning s =
let enemies = getEnemies s
me = stateHero s
in 2 * (heroMineCount me) > (maximum $ map heroMineCount enemies)
isGoal :: Goal -> State -> Pos -> Bool
isGoal goal s pos =
let board = gameBoard $ stateGame s
heroid = heroId $ stateHero s
tile = tileAt board pos
--in trace ("Goal: " ++ show goal) $
in
if isNothing tile then False
else case goal of
Capture _ -> canCaptureMine (fromJust tile) heroid
Kill hero -> heroid == hero
Heal -> isTavern $ fromJust tile
Survive -> isSafe s pos
canCaptureMine :: Tile -> HeroId -> Bool
canCaptureMine (MineTile owner) hero =
case owner of
Nothing -> True
Just he -> he /= hero
canCaptureMine _ _ = False
isTavern :: Tile -> Bool
isTavern TavernTile = True
isTavern _ = False
isSafe :: State -> Pos -> Bool
isSafe s pos = 0 == dangerLevelWithin 3 s (heroPos $ stateHero s) pos
dangerLevelWithin :: Int -> State -> Pos -> Pos -> Int
dangerLevelWithin 0 _ _ _ = 0
dangerLevelWithin steps s from pos =
let next = S.delete from $ adjacentTiles (gameBoard $ stateGame s) pos
heroes = heroesNearby s pos
in if null heroes then sum $ map (dangerLevelWithin (steps-1) s pos) (S.toList next)
else sum $ map (\_ -> calcCost steps) heroes
calcCost :: Int -> Int
calcCost steps = round $ (1 / (toRational steps)) * 8
heroesNearby :: State -> Pos -> [Hero]
heroesNearby s pos =
foldl (\es e ->
if pos `S.member` (adjacentTiles (gameBoard $ stateGame s) (heroPos e))
then e:es else es) [] (getEnemies s)
| flyrry/phonypony | src/StupidBot/Goal.hs | mit | 2,153 | 0 | 14 | 509 | 815 | 417 | 398 | 56 | 5 |
import System.Random
import qualified Data.Map as Map
import Data.List (sortBy)
import Data.Ord (comparing)
ns = [7,6..1]
chunks n xs
| n <= length xs = fst (splitAt n xs) : chunks n (tail xs)
| otherwise = []
rootmap str =
Map.fromListWith (Map.unionWith (+)) t
where
t = [(init s, Map.singleton (last s) 1) | s <- chks str]
chks str = concat [chunks x str | x <- ns]
mapAccumFsum = Map.mapAccum fsum 0
where
fsum a b = (a + b, (a+1,a+b))
rands :: IO [Double]
rands = do
g <- getStdGen
let rs = randomRs (0.0,1.0) g
return rs
floorLogBase = floor . logBase 0.5
truncBetween a b x = a `max` x `min` b
filterMe (d,m) c = Map.filter (\(a,b) -> a<=c && c<=b) m
randLengths rands = map (truncBetween 0 6) r1s
where
r1s = map floorLogBase rands
randAccum rmap (x,out) = findAccum rmap (drop out x)
findAccum rmap x = lookAccum rmap (Map.lookup x rmap) x
lookAccum rmap (Just x) str = (str,x)
lookAccum rmap Nothing str = lookAccum rmap (Map.lookup next rmap) next
where
next = drop 1 str
accumTest content randTrlens accum = map (\(a,b) -> (a, fst (mapAccumFsum b))) l1
where
l1 = map (randAccum rmap) (zip tests randTrlens)
tests = take 10 (repeat accum)
rmap = rootmap example
example = take 10000 content
main = do
rs <- rands
content <- readFile "matkustus-maan-keskipisteeseen.txt"
--content <- readFile "journey-to-centre-of-earth.txt"
let
accum = take 6 content
rtls = randLengths rs
traccums = accumTest content rtls accum
traccumsSorted = sortBy (comparing (\(x,y) -> length x)) traccums
mapM_ (putStrLn . show) (reverse traccumsSorted)
| jsavatgy/dit-doo | code/accum-start-01.hs | gpl-2.0 | 1,649 | 0 | 15 | 376 | 755 | 388 | 367 | 43 | 1 |
-- 类型参数
data Rect = Rect Int Int
area :: Rect -> Int
area (Rect w h) = w * h
perim :: Rect -> Int
perim (Rect w h) = 2 * w + 2 * h
main = do
let r = Rect 10 5
putStrLn $ "area: " ++ show (area r)
putStrLn $ "perim: " ++ show (perim r)
| solvery/lang-features | haskell/type_5.hs | gpl-2.0 | 259 | 0 | 10 | 79 | 138 | 68 | 70 | 9 | 1 |
-- | This defines a bunch of generic commands that can be used in a
-- variety of X actions.
module XMonad.Config.Fizzixnerd.Commands where
browser = "firefox"
explorer = "nautilus"
systemMonitor = "gnome-system-monitor"
music = "rhythmbox"
video = "vlc"
myTerminal = "gnome-terminal"
compton = "killall compton; sleep 0.5; compton -f -I 0.10 -O 0.10 --backend glx --vsync opengl"
dock = "killall docky; sleep 0.5; docky"
gnomeDo = "gnome-do"
volumeUp = "amixer -D pulse sset Master 5%+"
volumeDown = "amixer -D pulse sset Master 5%-"
toggleMute = "amixer -D pulse set Master 1+ toggle"
time = "date"
| Fizzixnerd/xmonad-config | site-haskell/src/XMonad/Config/Fizzixnerd/Commands.hs | gpl-3.0 | 606 | 0 | 4 | 100 | 75 | 47 | 28 | 14 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
-- FIXME: better types in checkLevel
{-# LANGUAGE FlexibleContexts #-}
-- |
-- Copyright : (c) 2010-2012 Simon Meier & Benedikt Schmidt
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Portability : GHC only
--
-- Types to represent proofs.
module Theory.Proof (
-- * Utilities
LTree(..)
, mergeMapsWith
-- * Types
, ProofStep(..)
, DiffProofStep(..)
, Proof
, DiffProof
-- ** Paths inside proofs
, ProofPath
, atPath
, atPathDiff
, insertPaths
, insertPathsDiff
-- ** Folding/modifying proofs
, mapProofInfo
, mapDiffProofInfo
, foldProof
, foldDiffProof
, annotateProof
, annotateDiffProof
, ProofStatus(..)
, proofStepStatus
, diffProofStepStatus
-- ** Unfinished proofs
, sorry
, unproven
, diffSorry
, diffUnproven
-- ** Incremental proof construction
, IncrementalProof
, IncrementalDiffProof
, Prover
, DiffProver
, runProver
, runDiffProver
, mapProverProof
, mapDiffProverDiffProof
, orelse
, tryProver
, sorryProver
, sorryDiffProver
, oneStepProver
, oneStepDiffProver
, focus
, focusDiff
, checkAndExtendProver
, checkAndExtendDiffProver
, replaceSorryProver
, replaceDiffSorryProver
, contradictionProver
, contradictionDiffProver
-- ** Explicit representation of a fully automatic prover
, SolutionExtractor(..)
, AutoProver(..)
, runAutoProver
, runAutoDiffProver
-- ** Pretty Printing
, prettyProof
, prettyDiffProof
, prettyProofWith
, prettyDiffProofWith
, showProofStatus
, showDiffProofStatus
-- ** Parallel Strategy for exploring a proof
, parLTreeDFS
-- ** Small-step interface to the constraint solver
, module Theory.Constraint.Solver
) where
import Data.Binary
import Data.DeriveTH
-- import Data.Foldable (Foldable, foldMap)
import Data.List
import qualified Data.Label as L
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
-- import Data.Traversable
import Debug.Trace
import Control.Basics
import Control.DeepSeq
import qualified Control.Monad.State as S
import Control.Parallel.Strategies
import Theory.Constraint.Solver
import Theory.Model
import Theory.Text.Pretty
------------------------------------------------------------------------------
-- Utility: Trees with uniquely labelled edges.
------------------------------------------------------------------------------
-- | Trees with uniquely labelled edges.
data LTree l a = LNode
{ root :: a
, children :: M.Map l (LTree l a)
}
deriving( Eq, Ord, Show )
instance Functor (LTree l) where
fmap f (LNode r cs) = LNode (f r) (M.map (fmap f) cs)
instance Foldable (LTree l) where
foldMap f (LNode x cs) = f x `mappend` foldMap (foldMap f) cs
instance Traversable (LTree l) where
traverse f (LNode x cs) = LNode <$> f x <*> traverse (traverse f) cs
-- | A parallel evaluation strategy well-suited for DFS traversal: As soon as
-- a node is forced it sparks off the computation of the number of case-maps
-- of all its children. This way most of the data is already evaulated, when
-- the actual DFS traversal visits it.
--
-- NOT used for now. It sometimes required too much memory.
parLTreeDFS :: Strategy (LTree l a)
parLTreeDFS (LNode x0 cs0) = do
cs0' <- (`parTraversable` cs0) $ \(LNode x cs) -> LNode x <$> rseq cs
return $ LNode x0 (M.map (runEval . parLTreeDFS) cs0')
------------------------------------------------------------------------------
-- Utility: Merging maps
------------------------------------------------------------------------------
-- | /O(n+m)/. A generalized union operator for maps with differing types.
mergeMapsWith :: Ord k
=> (a -> c) -> (b -> c) -> (a -> b -> c)
-> M.Map k a -> M.Map k b -> M.Map k c
mergeMapsWith leftOnly rightOnly combine l r =
M.map extract $ M.unionWith combine' l' r'
where
l' = M.map (Left . Left) l
r' = M.map (Left . Right) r
combine' (Left (Left a)) (Left (Right b)) = Right $ combine a b
combine' _ _ = error "mergeMapsWith: impossible"
extract (Left (Left a)) = leftOnly a
extract (Left (Right b)) = rightOnly b
extract (Right c) = c
------------------------------------------------------------------------------
-- Proof Steps
------------------------------------------------------------------------------
-- | A proof steps is a proof method together with additional context-dependent
-- information.
data ProofStep a = ProofStep
{ psMethod :: ProofMethod
, psInfo :: a
}
deriving( Eq, Ord, Show )
instance Functor ProofStep where
fmap f (ProofStep m i) = ProofStep m (f i)
instance Foldable ProofStep where
foldMap f = f . psInfo
instance Traversable ProofStep where
traverse f (ProofStep m i) = ProofStep m <$> f i
instance HasFrees a => HasFrees (ProofStep a) where
foldFrees f (ProofStep m i) = foldFrees f m `mappend` foldFrees f i
foldFreesOcc _ _ = const mempty
mapFrees f (ProofStep m i) = ProofStep <$> mapFrees f m <*> mapFrees f i
-- | A diff proof steps is a proof method together with additional context-dependent
-- information.
data DiffProofStep a = DiffProofStep
{ dpsMethod :: DiffProofMethod
, dpsInfo :: a
}
deriving( Eq, Ord, Show )
instance Functor DiffProofStep where
fmap f (DiffProofStep m i) = DiffProofStep m (f i)
instance Foldable DiffProofStep where
foldMap f = f . dpsInfo
instance Traversable DiffProofStep where
traverse f (DiffProofStep m i) = DiffProofStep m <$> f i
instance HasFrees a => HasFrees (DiffProofStep a) where
foldFrees f (DiffProofStep m i) = foldFrees f m `mappend` foldFrees f i
foldFreesOcc _ _ = const mempty
mapFrees f (DiffProofStep m i) = DiffProofStep <$> mapFrees f m <*> mapFrees f i
------------------------------------------------------------------------------
-- Proof Trees
------------------------------------------------------------------------------
-- | A path to a subproof.
type ProofPath = [CaseName]
-- | A proof is a tree of proof steps whose edges are labelled with case names.
type Proof a = LTree CaseName (ProofStep a)
-- | A diff proof is a tree of proof steps whose edges are labelled with case names.
type DiffProof a = LTree CaseName (DiffProofStep a)
-- Unfinished proofs
--------------------
-- | A proof using the 'sorry' proof method.
sorry :: Maybe String -> a -> Proof a
sorry reason ann = LNode (ProofStep (Sorry reason) ann) M.empty
-- | A proof using the 'sorry' proof method.
diffSorry :: Maybe String -> a -> DiffProof a
diffSorry reason ann = LNode (DiffProofStep (DiffSorry reason) ann) M.empty
-- | A proof denoting an unproven part of the proof.
unproven :: a -> Proof a
unproven = sorry Nothing
-- | A proof denoting an unproven part of the proof.
diffUnproven :: a -> DiffProof a
diffUnproven = diffSorry Nothing
-- Paths in proofs
------------------
-- | @prf `atPath` path@ returns the subproof at the @path@ in @prf@.
atPath :: Proof a -> ProofPath -> Maybe (Proof a)
atPath = foldM (flip M.lookup . children)
-- | @prf `atPath` path@ returns the subproof at the @path@ in @prf@.
atPathDiff :: DiffProof a -> ProofPath -> Maybe (DiffProof a)
atPathDiff = foldM (flip M.lookup . children)
-- | @modifyAtPath f path prf@ applies @f@ to the subproof at @path@,
-- if there is one.
modifyAtPath :: (Proof a -> Maybe (Proof a)) -> ProofPath
-> Proof a -> Maybe (Proof a)
modifyAtPath f =
go
where
go [] prf = f prf
go (l:ls) prf = do
let cs = children prf
prf' <- go ls =<< M.lookup l cs
return (prf { children = M.insert l prf' cs })
-- | @modifyAtPath f path prf@ applies @f@ to the subproof at @path@,
-- if there is one.
modifyAtPathDiff :: (DiffProof a -> Maybe (DiffProof a)) -> ProofPath
-> DiffProof a -> Maybe (DiffProof a)
modifyAtPathDiff f =
go
where
go [] prf = f prf
go (l:ls) prf = do
let cs = children prf
prf' <- go ls =<< M.lookup l cs
return (prf { children = M.insert l prf' cs })
-- | @insertPaths prf@ inserts the path to every proof node.
insertPaths :: Proof a -> Proof (a, ProofPath)
insertPaths =
insertPath []
where
insertPath path (LNode ps cs) =
LNode (fmap (,reverse path) ps)
(M.mapWithKey (\n prf -> insertPath (n:path) prf) cs)
-- | @insertPaths prf@ inserts the path to every diff proof node.
insertPathsDiff :: DiffProof a -> DiffProof (a, ProofPath)
insertPathsDiff =
insertPath []
where
insertPath path (LNode ps cs) =
LNode (fmap (,reverse path) ps)
(M.mapWithKey (\n prf -> insertPath (n:path) prf) cs)
-- Utilities for dealing with proofs
------------------------------------
-- | Apply a function to the information of every proof step.
mapProofInfo :: (a -> b) -> Proof a -> Proof b
mapProofInfo = fmap . fmap
-- | Apply a function to the information of every proof step.
mapDiffProofInfo :: (a -> b) -> DiffProof a -> DiffProof b
mapDiffProofInfo = fmap . fmap
-- | @boundProofDepth bound prf@ bounds the depth of the proof @prf@ using
-- 'Sorry' steps to replace the cut sub-proofs.
boundProofDepth :: Int -> Proof a -> Proof a
boundProofDepth bound =
go bound
where
go n (LNode ps@(ProofStep _ info) cs)
| 0 < n = LNode ps $ M.map (go (pred n)) cs
| otherwise = sorry (Just $ "bound " ++ show bound ++ " hit") info
-- | @boundProofDepth bound prf@ bounds the depth of the proof @prf@ using
-- 'Sorry' steps to replace the cut sub-proofs.
boundDiffProofDepth :: Int -> DiffProof a -> DiffProof a
boundDiffProofDepth bound =
go bound
where
go n (LNode ps@(DiffProofStep _ info) cs)
| 0 < n = LNode ps $ M.map (go (pred n)) cs
| otherwise = diffSorry (Just $ "bound " ++ show bound ++ " hit") info
-- | Fold a proof.
foldProof :: Monoid m => (ProofStep a -> m) -> Proof a -> m
foldProof f =
go
where
go (LNode step cs) = f step `mappend` foldMap go (M.elems cs)
-- | Fold a proof.
foldDiffProof :: Monoid m => (DiffProofStep a -> m) -> DiffProof a -> m
foldDiffProof f =
go
where
go (LNode step cs) = f step `mappend` foldMap go (M.elems cs)
-- | Annotate a proof in a bottom-up fashion.
annotateProof :: (ProofStep a -> [b] -> b) -> Proof a -> Proof b
annotateProof f =
go
where
go (LNode step@(ProofStep method _) cs) =
LNode (ProofStep method info') cs'
where
cs' = M.map go cs
info' = f step (map (psInfo . root . snd) (M.toList cs'))
-- | Annotate a proof in a bottom-up fashion.
annotateDiffProof :: (DiffProofStep a -> [b] -> b) -> DiffProof a -> DiffProof b
annotateDiffProof f =
go
where
go (LNode step@(DiffProofStep method _) cs) =
LNode (DiffProofStep method info') cs'
where
cs' = M.map go cs
info' = f step (map (dpsInfo . root . snd) (M.toList cs'))
-- Proof cutting
----------------
-- | The status of a 'Proof'.
data ProofStatus =
UndeterminedProof -- ^ All steps are unannotated
| CompleteProof -- ^ The proof is complete: no annotated sorry,
-- no annotated solved step
| IncompleteProof -- ^ There is a annotated sorry,
-- but no annotatd solved step.
| TraceFound -- ^ There is an annotated solved step
deriving (Show)
instance Monoid ProofStatus where
mempty = CompleteProof
mappend TraceFound _ = TraceFound
mappend _ TraceFound = TraceFound
mappend IncompleteProof _ = IncompleteProof
mappend _ IncompleteProof = IncompleteProof
mappend _ CompleteProof = CompleteProof
mappend CompleteProof _ = CompleteProof
mappend UndeterminedProof UndeterminedProof = UndeterminedProof
-- | The status of a 'ProofStep'.
proofStepStatus :: ProofStep (Maybe a) -> ProofStatus
proofStepStatus (ProofStep _ Nothing ) = UndeterminedProof
proofStepStatus (ProofStep Solved (Just _)) = TraceFound
proofStepStatus (ProofStep (Sorry _) (Just _)) = IncompleteProof
proofStepStatus (ProofStep _ (Just _)) = CompleteProof
-- | The status of a 'DiffProofStep'.
diffProofStepStatus :: DiffProofStep (Maybe a) -> ProofStatus
diffProofStepStatus (DiffProofStep _ Nothing ) = UndeterminedProof
diffProofStepStatus (DiffProofStep DiffAttack (Just _)) = TraceFound
diffProofStepStatus (DiffProofStep (DiffSorry _) (Just _)) = IncompleteProof
diffProofStepStatus (DiffProofStep _ (Just _)) = CompleteProof
{- TODO: Test and probably improve
-- | @proveSystem rules se@ tries to construct a proof that @se@ is valid.
-- This proof may contain 'Sorry' steps, if the prover is stuck. It can also be
-- of infinite depth, if the proof strategy loops.
proveSystemIterDeep :: ProofContext -> System -> Proof System
proveSystemIterDeep rules se0 =
fromJust $ asum $ map (prove se0 . round) $ iterate (*1.5) (3::Double)
where
prove :: System -> Int -> Maybe (Proof System)
prove se bound
| bound < 0 = Nothing
| otherwise =
case next of
[] -> pure $ sorry "prover stuck => possible attack found" se
xs -> asum $ map mkProof xs
where
next = do m <- possibleProofMethods se
(m,) <$> maybe mzero return (execProofMethod rules m se)
mkProof (method, cases) =
LNode (ProofStep method se) <$> traverse (`prove` (bound - 1)) cases
-}
-- | @checkProof rules se prf@ replays the proof @prf@ against the start
-- sequent @se@. A failure to apply a proof method is denoted by a resulting
-- proof step without an annotated sequent. An unhandled case is denoted using
-- the 'Sorry' proof method.
checkProof :: ProofContext
-> (Int -> System -> Proof (Maybe System)) -- prover for new cases in depth
-> Int -- ^ Original depth
-> System
-> Proof a
-> Proof (Maybe a, Maybe System)
checkProof ctxt prover d sys prf@(LNode (ProofStep method info) cs) =
case (method, execProofMethod ctxt method sys) of
(Sorry reason, _ ) -> sorryNode reason cs
(_ , Just cases) -> node method $ checkChildren cases
(_ , Nothing ) ->
sorryNode (Just "invalid proof step encountered")
(M.singleton "" prf)
where
node m = LNode (ProofStep m (Just info, Just sys))
sorryNode reason cases = node (Sorry reason) (M.map noSystemPrf cases)
noSystemPrf = mapProofInfo (\i -> (Just i, Nothing))
checkChildren cases = mergeMapsWith
unhandledCase noSystemPrf (checkProof ctxt prover (d + 1)) cases cs
where
unhandledCase = mapProofInfo ((,) Nothing) . prover d
-- | @checkDiffProof rules se prf@ replays the proof @prf@ against the start
-- sequent @se@. A failure to apply a proof method is denoted by a resulting
-- proof step without an annotated sequent. An unhandled case is denoted using
-- the 'Sorry' proof method.
checkDiffProof :: DiffProofContext
-> (Int -> DiffSystem -> DiffProof (Maybe DiffSystem)) -- prover for new cases in depth
-> Int -- ^ Original depth
-> DiffSystem
-> DiffProof a
-> DiffProof (Maybe a, Maybe DiffSystem)
checkDiffProof ctxt prover d sys prf@(LNode (DiffProofStep method info) cs) =
case (method, execDiffProofMethod ctxt method sys) of
(DiffSorry reason, _ ) -> sorryNode reason cs
(_ , Just cases) -> node method $ checkChildren cases
(_ , Nothing ) ->
sorryNode (Just "invalid proof step encountered")
(M.singleton "" prf)
where
node m = LNode (DiffProofStep m (Just info, Just sys))
sorryNode reason cases = node (DiffSorry reason) (M.map noSystemPrf cases)
noSystemPrf = mapDiffProofInfo (\i -> (Just i, Nothing))
checkChildren cases = mergeMapsWith
unhandledCase noSystemPrf (checkDiffProof ctxt prover (d + 1)) cases cs
where
unhandledCase = mapDiffProofInfo ((,) Nothing) . prover d
-- | Annotate a proof with the constraint systems of all intermediate steps
-- under the assumption that all proof steps are valid. If some proof steps
-- might be invalid, then you must use 'checkProof', which handles them
-- gracefully.
annotateWithSystems :: ProofContext -> System -> Proof () -> Proof System
annotateWithSystems ctxt =
go
where
-- Here we are careful to construct the result such that an inspection of
-- the proof does not force the recomputed constraint systems.
go sysOrig (LNode (ProofStep method _) csOrig) =
LNode (ProofStep method sysOrig) $ M.fromList $ do
(name, prf) <- M.toList csOrig
let sysAnn = extract ("case '" ++ name ++ "' non-existent") $
M.lookup name csAnn
return (name, go sysAnn prf)
where
extract msg = fromMaybe (error $ "annotateWithSystems: " ++ msg)
csAnn = extract "proof method execution failed" $
execProofMethod ctxt method sysOrig
-- | Annotate a proof with the constraint systems of all intermediate steps
-- under the assumption that all proof steps are valid. If some proof steps
-- might be invalid, then you must use 'checkProof', which handles them
-- gracefully.
annotateWithDiffSystems :: DiffProofContext -> DiffSystem -> DiffProof () -> DiffProof DiffSystem
annotateWithDiffSystems ctxt =
go
where
-- Here we are careful to construct the result such that an inspection of
-- the proof does not force the recomputed constraint systems.
go sysOrig (LNode (DiffProofStep method _) csOrig) =
LNode (DiffProofStep method sysOrig) $ M.fromList $ do
(name, prf) <- M.toList csOrig
let sysAnn = extract ("case '" ++ name ++ "' non-existent") $
M.lookup name csAnn
return (name, go sysAnn prf)
where
extract msg = fromMaybe (error $ "annotateWithSystems: " ++ msg)
csAnn = extract "diff proof method execution failed" $
execDiffProofMethod ctxt method sysOrig
------------------------------------------------------------------------------
-- Provers: the interface to the outside world.
------------------------------------------------------------------------------
-- | Incremental proofs are used to represent intermediate results of proof
-- checking/construction.
type IncrementalProof = Proof (Maybe System)
-- | Incremental diff proofs are used to represent intermediate results of proof
-- checking/construction.
-- FIXME: not clear if/how we need the system
type IncrementalDiffProof = DiffProof (Maybe DiffSystem)
-- | Provers whose sequencing is handled via the 'Monoid' instance.
--
-- > p1 `mappend` p2
--
-- Is a prover that first runs p1 and then p2 on the resulting proof.
newtype Prover = Prover
{ runProver
:: ProofContext -- proof rules to use
-> Int -- proof depth
-> System -- original sequent to start with
-> IncrementalProof -- original proof
-> Maybe IncrementalProof -- resulting proof
}
instance Monoid Prover where
mempty = Prover $ \_ _ _ -> Just
p1 `mappend` p2 = Prover $ \ctxt d se ->
runProver p1 ctxt d se >=> runProver p2 ctxt d se
-- | Provers whose sequencing is handled via the 'Monoid' instance.
--
-- > p1 `mappend` p2
--
-- Is a prover that first runs p1 and then p2 on the resulting proof.
newtype DiffProver = DiffProver
{ runDiffProver
:: DiffProofContext -- proof rules to use
-> Int -- proof depth
-> DiffSystem -- original sequent to start with
-> IncrementalDiffProof -- original proof
-> Maybe IncrementalDiffProof -- resulting proof
}
instance Monoid DiffProver where
mempty = DiffProver $ \_ _ _ -> Just
p1 `mappend` p2 = DiffProver $ \ctxt d se ->
runDiffProver p1 ctxt d se >=> runDiffProver p2 ctxt d se
-- | Map the proof generated by the prover.
mapProverProof :: (IncrementalProof -> IncrementalProof) -> Prover -> Prover
mapProverProof f p = Prover $ \ ctxt d se prf -> f <$> runProver p ctxt d se prf
-- | Map the proof generated by the prover.
mapDiffProverDiffProof :: (IncrementalDiffProof -> IncrementalDiffProof) -> DiffProver -> DiffProver
mapDiffProverDiffProof f p = DiffProver $ \ctxt d se prf -> f <$> runDiffProver p ctxt d se prf
-- | Prover that always fails.
failProver :: Prover
failProver = Prover (\ _ _ _ _ -> Nothing)
-- | Prover that always fails.
failDiffProver :: DiffProver
failDiffProver = DiffProver (\_ _ _ _ -> Nothing)
-- | Resorts to the second prover, if the first one is not successful.
orelse :: Prover -> Prover -> Prover
orelse p1 p2 = Prover $ \ctxt d se prf ->
runProver p1 ctxt d se prf `mplus` runProver p2 ctxt d se prf
-- | Resorts to the second prover, if the first one is not successful.
orelseDiff :: DiffProver -> DiffProver -> DiffProver
orelseDiff p1 p2 = DiffProver $ \ctxt d se prf ->
runDiffProver p1 ctxt d se prf `mplus` runDiffProver p2 ctxt d se prf
-- | Try to apply a prover. If it fails, just return the original proof.
tryProver :: Prover -> Prover
tryProver = (`orelse` mempty)
-- | Try to execute one proof step using the given proof method.
oneStepProver :: ProofMethod -> Prover
oneStepProver method = Prover $ \ctxt _ se _ -> do
cases <- execProofMethod ctxt method se
return $ LNode (ProofStep method (Just se)) (M.map (unproven . Just) cases)
-- | Try to execute one proof step using the given proof method.
oneStepDiffProver :: DiffProofMethod -> DiffProver
oneStepDiffProver method = DiffProver $ \ctxt _ se _ -> do
cases <- execDiffProofMethod ctxt method se
-- error $ show $ LNode (DiffProofStep method (Just se)) (M.map (diffUnproven . Just) cases) -- (show cases ++ " " ++ show se)
return $ LNode (DiffProofStep method (Just se)) (M.map (diffUnproven . Just) cases)
-- | Replace the current proof with a sorry step and the given reason.
sorryProver :: Maybe String -> Prover
sorryProver reason = Prover $ \_ _ se _ -> return $ sorry reason (Just se)
-- | Replace the current proof with a sorry step and the given reason.
sorryDiffProver :: Maybe String -> DiffProver
sorryDiffProver reason = DiffProver $ \_ _ se _ -> return $ diffSorry reason (Just se)
-- | Apply a prover only to a sub-proof, fails if the subproof doesn't exist.
focus :: ProofPath -> Prover -> Prover
focus [] prover = prover
focus path prover =
Prover $ \ctxt d _ prf ->
modifyAtPath (prover' ctxt (d + length path)) path prf
where
prover' ctxt d prf = do
se <- psInfo (root prf)
runProver prover ctxt d se prf
-- | Apply a diff prover only to a sub-proof, fails if the subproof doesn't exist.
focusDiff :: ProofPath -> DiffProver -> DiffProver
focusDiff [] prover = prover
focusDiff path prover =
DiffProver $ \ctxt d _ prf ->
modifyAtPathDiff (prover' ctxt (d + length path)) path prf
where
prover' ctxt d prf = do
se <- dpsInfo (root prf)
runDiffProver prover ctxt d se prf
-- | Check the proof and handle new cases using the given prover.
checkAndExtendProver :: Prover -> Prover
checkAndExtendProver prover0 = Prover $ \ctxt d se prf ->
return $ mapProofInfo snd $ checkProof ctxt (prover ctxt) d se prf
where
unhandledCase = sorry (Just "unhandled case") Nothing
prover ctxt d se =
fromMaybe unhandledCase $ runProver prover0 ctxt d se unhandledCase
-- | Check the proof and handle new cases using the given prover.
checkAndExtendDiffProver :: DiffProver -> DiffProver
checkAndExtendDiffProver prover0 = DiffProver $ \ctxt d se prf ->
return $ mapDiffProofInfo snd $ checkDiffProof ctxt (prover ctxt) d se prf
where
unhandledCase = diffSorry (Just "unhandled case") Nothing
prover ctxt d se =
fromMaybe unhandledCase $ runDiffProver prover0 ctxt d se unhandledCase
-- | Replace all annotated sorry steps using the given prover.
replaceSorryProver :: Prover -> Prover
replaceSorryProver prover0 = Prover prover
where
prover ctxt d _ = return . replace
where
replace prf@(LNode (ProofStep (Sorry _) (Just se)) _) =
fromMaybe prf $ runProver prover0 ctxt d se prf
replace (LNode ps cases) =
LNode ps $ M.map replace cases
-- | Replace all annotated sorry steps using the given prover.
replaceDiffSorryProver :: DiffProver -> DiffProver
replaceDiffSorryProver prover0 = DiffProver prover
where
prover ctxt d _ = return . replace
where
replace prf@(LNode (DiffProofStep (DiffSorry _) (Just se)) _) =
fromMaybe prf $ runDiffProver prover0 ctxt d se prf
replace (LNode ps cases) =
LNode ps $ M.map replace cases
-- | Use the first prover that works.
firstProver :: [Prover] -> Prover
firstProver = foldr orelse failProver
-- | Prover that does one contradiction step.
contradictionProver :: Prover
contradictionProver = Prover $ \ctxt d sys prf ->
runProver
(firstProver $ map oneStepProver $
(Contradiction . Just <$> contradictions ctxt sys))
ctxt d sys prf
-- | Use the first diff prover that works.
firstDiffProver :: [DiffProver] -> DiffProver
firstDiffProver = foldr orelseDiff failDiffProver
-- | Diff Prover that does one contradiction step if possible.
contradictionDiffProver :: DiffProver
contradictionDiffProver = DiffProver $ \ctxt d sys prf ->
case (L.get dsCurrentRule sys, L.get dsSide sys, L.get dsSystem sys) of
(Just _, Just s, Just sys') -> runDiffProver
(firstDiffProver $ map oneStepDiffProver $
(DiffBackwardSearchStep . Contradiction . Just <$> contradictions (eitherProofContext ctxt s) sys'))
ctxt d sys prf
(_ , _ , _ ) -> Nothing
------------------------------------------------------------------------------
-- Automatic Prover's
------------------------------------------------------------------------------
data SolutionExtractor = CutDFS | CutBFS | CutNothing
deriving( Eq, Ord, Show, Read )
data AutoProver = AutoProver
{ apHeuristic :: Heuristic
, apBound :: Maybe Int
, apCut :: SolutionExtractor
}
runAutoProver :: AutoProver -> Prover
runAutoProver (AutoProver heuristic bound cut) =
mapProverProof cutSolved $ maybe id boundProver bound autoProver
where
cutSolved = case cut of
CutDFS -> cutOnSolvedDFS
CutBFS -> cutOnSolvedBFS
CutNothing -> id
-- | The standard automatic prover that ignores the existing proof and
-- tries to find one by itself.
autoProver :: Prover
autoProver = Prover $ \ctxt depth sys _ ->
return $ fmap (fmap Just)
$ annotateWithSystems ctxt sys
$ proveSystemDFS heuristic ctxt depth sys
-- | Bound the depth of proofs generated by the given prover.
boundProver :: Int -> Prover -> Prover
boundProver b p = Prover $ \ctxt d se prf ->
boundProofDepth b <$> runProver p ctxt d se prf
runAutoDiffProver :: AutoProver -> DiffProver
runAutoDiffProver (AutoProver heuristic bound cut) =
mapDiffProverDiffProof cutSolved $ maybe id boundProver bound autoProver
where
cutSolved = case cut of
CutDFS -> cutOnSolvedDFSDiff
CutBFS -> cutOnSolvedBFSDiff
CutNothing -> id
-- | The standard automatic prover that ignores the existing proof and
-- tries to find one by itself.
autoProver :: DiffProver
autoProver = DiffProver $ \ctxt depth sys _ ->
return $ fmap (fmap Just)
$ annotateWithDiffSystems ctxt sys
$ proveDiffSystemDFS heuristic ctxt depth sys
-- | Bound the depth of proofs generated by the given prover.
boundProver :: Int -> DiffProver -> DiffProver
boundProver b p = DiffProver $ \ctxt d se prf ->
boundDiffProofDepth b <$> runDiffProver p ctxt d se prf
-- | The result of one pass of iterative deepening.
data IterDeepRes = NoSolution | MaybeNoSolution | Solution ProofPath
instance Monoid IterDeepRes where
mempty = NoSolution
x@(Solution _) `mappend` _ = x
_ `mappend` y@(Solution _) = y
MaybeNoSolution `mappend` _ = MaybeNoSolution
_ `mappend` MaybeNoSolution = MaybeNoSolution
NoSolution `mappend` NoSolution = NoSolution
-- | @cutOnSolvedDFS prf@ removes all other cases if an attack is found. The
-- attack search is performed using a parallel DFS traversal with iterative
-- deepening.
--
-- FIXME: Note that this function may use a lot of space, as it holds onto the
-- whole proof tree.
cutOnSolvedDFS :: Proof (Maybe a) -> Proof (Maybe a)
cutOnSolvedDFS prf0 =
go (4 :: Integer) $ insertPaths prf0
where
go dMax prf = case findSolved 0 prf of
NoSolution -> prf0
MaybeNoSolution -> go (2 * dMax) prf
Solution path -> extractSolved path prf0
where
findSolved d node
| d >= dMax = MaybeNoSolution
| otherwise = case node of
-- do not search in nodes that are not annotated
LNode (ProofStep _ (Nothing, _ )) _ -> NoSolution
LNode (ProofStep Solved (Just _ , path)) _ -> Solution path
LNode (ProofStep _ (Just _ , _ )) cs ->
foldMap (findSolved (succ d))
(cs `using` parTraversable nfProofMethod)
nfProofMethod node = do
void $ rseq (psMethod $ root node)
void $ rseq (psInfo $ root node)
void $ rseq (children node)
return node
extractSolved [] p = p
extractSolved (label:ps) (LNode pstep m) = case M.lookup label m of
Just subprf ->
LNode pstep (M.fromList [(label, extractSolved ps subprf)])
Nothing ->
error "Theory.Constraint.cutOnSolvedDFS: impossible, extractSolved failed, invalid path"
-- | @cutOnSolvedDFS prf@ removes all other cases if an attack is found. The
-- attack search is performed using a parallel DFS traversal with iterative
-- deepening.
--
-- FIXME: Note that this function may use a lot of space, as it holds onto the
-- whole proof tree.
cutOnSolvedDFSDiff :: DiffProof (Maybe a) -> DiffProof (Maybe a)
cutOnSolvedDFSDiff prf0 =
go (4 :: Integer) $ insertPathsDiff prf0
where
go dMax prf = case findSolved 0 prf of
NoSolution -> prf0
MaybeNoSolution -> go (2 * dMax) prf
Solution path -> extractSolved path prf0
where
findSolved d node
| d >= dMax = MaybeNoSolution
| otherwise = case node of
-- do not search in nodes that are not annotated
LNode (DiffProofStep _ (Nothing, _ )) _ -> NoSolution
LNode (DiffProofStep DiffAttack (Just _ , path)) _ -> Solution path
LNode (DiffProofStep _ (Just _ , _ )) cs ->
foldMap (findSolved (succ d))
(cs `using` parTraversable nfProofMethod)
nfProofMethod node = do
void $ rseq (dpsMethod $ root node)
void $ rseq (dpsInfo $ root node)
void $ rseq (children node)
return node
extractSolved [] p = p
extractSolved (label:ps) (LNode pstep m) = case M.lookup label m of
Just subprf ->
LNode pstep (M.fromList [(label, extractSolved ps subprf)])
Nothing ->
error "Theory.Constraint.cutOnSolvedDFSDiff: impossible, extractSolved failed, invalid path"
-- | Search for attacks in a BFS manner.
cutOnSolvedBFS :: Proof (Maybe a) -> Proof (Maybe a)
cutOnSolvedBFS =
go (1::Int)
where
go l prf =
-- FIXME: See if that poor man's logging could be done better.
trace ("searching for attacks at depth: " ++ show l) $
case S.runState (checkLevel l prf) CompleteProof of
(_, UndeterminedProof) -> error "cutOnSolvedBFS: impossible"
(_, CompleteProof) -> prf
(_, IncompleteProof) -> go (l+1) prf
(prf', TraceFound) ->
trace ("attack found at depth: " ++ show l) prf'
checkLevel 0 (LNode step@(ProofStep Solved (Just _)) _) =
S.put TraceFound >> return (LNode step M.empty)
checkLevel 0 prf@(LNode (ProofStep _ x) cs)
| M.null cs = return prf
| otherwise = do
st <- S.get
msg <- case st of
TraceFound -> return $ "ignored (attack exists)"
_ -> S.put IncompleteProof >> return "bound reached"
return $ LNode (ProofStep (Sorry (Just msg)) x) M.empty
checkLevel l prf@(LNode step cs)
| isNothing (psInfo step) = return prf
| otherwise = LNode step <$> traverse (checkLevel (l-1)) cs
-- | Search for attacks in a BFS manner.
cutOnSolvedBFSDiff :: DiffProof (Maybe a) -> DiffProof (Maybe a)
cutOnSolvedBFSDiff =
go (1::Int)
where
go l prf =
-- FIXME: See if that poor man's logging could be done better.
trace ("searching for attacks at depth: " ++ show l) $
case S.runState (checkLevel l prf) CompleteProof of
(_, UndeterminedProof) -> error "cutOnSolvedBFS: impossible"
(_, CompleteProof) -> prf
(_, IncompleteProof) -> go (l+1) prf
(prf', TraceFound) ->
trace ("attack found at depth: " ++ show l) prf'
checkLevel 0 (LNode step@(DiffProofStep DiffAttack (Just _)) _) =
S.put TraceFound >> return (LNode step M.empty)
checkLevel 0 prf@(LNode (DiffProofStep _ x) cs)
| M.null cs = return prf
| otherwise = do
st <- S.get
msg <- case st of
TraceFound -> return $ "ignored (attack exists)"
_ -> S.put IncompleteProof >> return "bound reached"
return $ LNode (DiffProofStep (DiffSorry (Just msg)) x) M.empty
checkLevel l prf@(LNode step cs)
| isNothing (dpsInfo step) = return prf
| otherwise = LNode step <$> traverse (checkLevel (l-1)) cs
-- | @proveSystemDFS rules se@ explores all solutions of the initial
-- constraint system using a depth-first-search strategy to resolve the
-- non-determinism wrt. what goal to solve next. This proof can be of
-- infinite depth, if the proof strategy loops.
--
-- Use 'annotateWithSystems' to annotate the proof tree with the constraint
-- systems.
proveSystemDFS :: Heuristic -> ProofContext -> Int -> System -> Proof ()
proveSystemDFS heuristic ctxt d0 sys0 =
prove d0 sys0
where
prove !depth sys =
case rankProofMethods (useHeuristic heuristic depth) ctxt sys of
[] -> node Solved M.empty
(method, (cases, _expl)):_ -> node method cases
where
node method cases =
LNode (ProofStep method ()) (M.map (prove (succ depth)) cases)
-- | @proveSystemDFS rules se@ explores all solutions of the initial
-- constraint system using a depth-first-search strategy to resolve the
-- non-determinism wrt. what goal to solve next. This proof can be of
-- infinite depth, if the proof strategy loops.
--
-- Use 'annotateWithSystems' to annotate the proof tree with the constraint
-- systems.
proveDiffSystemDFS :: Heuristic -> DiffProofContext -> Int -> DiffSystem -> DiffProof ()
proveDiffSystemDFS heuristic ctxt d0 sys0 =
prove d0 sys0
where
prove !depth sys =
case rankDiffProofMethods (useHeuristic heuristic depth) ctxt sys of
[] -> node DiffMirrored M.empty
(method, (cases, _expl)):_ -> node method cases
where
node method cases =
LNode (DiffProofStep method ()) (M.map (prove (succ depth)) cases)
------------------------------------------------------------------------------
-- Pretty printing
------------------------------------------------------------------------------
prettyProof :: HighlightDocument d => Proof a -> d
prettyProof = prettyProofWith (prettyProofMethod . psMethod) (const id)
prettyProofWith :: HighlightDocument d
=> (ProofStep a -> d) -- ^ Make proof step pretty
-> (ProofStep a -> d -> d) -- ^ Make whole case pretty
-> Proof a -- ^ The proof to prettify
-> d
prettyProofWith prettyStep prettyCase =
ppPrf
where
ppPrf (LNode ps cs) = ppCases ps (M.toList cs)
ppCases ps@(ProofStep Solved _) [] = prettyStep ps
ppCases ps [] = prettyCase ps (kwBy <> text " ")
<> prettyStep ps
ppCases ps [("", prf)] = prettyStep ps $-$ ppPrf prf
ppCases ps cases =
prettyStep ps $-$
(vcat $ intersperse (prettyCase ps kwNext) $ map ppCase cases) $-$
prettyCase ps kwQED
ppCase (name, prf) = nest 2 $
(prettyCase (root prf) $ kwCase <-> text name) $-$
ppPrf prf
prettyDiffProof :: HighlightDocument d => DiffProof a -> d
prettyDiffProof = prettyDiffProofWith (prettyDiffProofMethod . dpsMethod) (const id)
prettyDiffProofWith :: HighlightDocument d
=> (DiffProofStep a -> d) -- ^ Make proof step pretty
-> (DiffProofStep a -> d -> d) -- ^ Make whole case pretty
-> DiffProof a -- ^ The proof to prettify
-> d
prettyDiffProofWith prettyStep prettyCase =
ppPrf
where
ppPrf (LNode ps cs) = ppCases ps (M.toList cs)
ppCases ps@(DiffProofStep DiffMirrored _) [] = prettyStep ps
ppCases ps [] = prettyCase ps (kwBy <> text " ")
<> prettyStep ps
ppCases ps [("", prf)] = prettyStep ps $-$ ppPrf prf
ppCases ps cases =
prettyStep ps $-$
(vcat $ intersperse (prettyCase ps kwNext) $ map ppCase cases) $-$
prettyCase ps kwQED
ppCase (name, prf) = nest 2 $
(prettyCase (root prf) $ kwCase <-> text name) $-$
ppPrf prf
-- | Convert a proof status to a redable string.
showProofStatus :: SystemTraceQuantifier -> ProofStatus -> String
showProofStatus ExistsNoTrace TraceFound = "falsified - found trace"
showProofStatus ExistsNoTrace CompleteProof = "verified"
showProofStatus ExistsSomeTrace CompleteProof = "falsified - no trace found"
showProofStatus ExistsSomeTrace TraceFound = "verified"
showProofStatus _ IncompleteProof = "analysis incomplete"
showProofStatus _ UndeterminedProof = "analysis undetermined"
-- | Convert a proof status to a redable string.
showDiffProofStatus :: ProofStatus -> String
showDiffProofStatus TraceFound = "falsified - found trace"
showDiffProofStatus CompleteProof = "verified"
showDiffProofStatus IncompleteProof = "analysis incomplete"
showDiffProofStatus UndeterminedProof = "analysis undetermined"
-- Derived instances
--------------------
$( derive makeBinary ''ProofStep)
$( derive makeBinary ''DiffProofStep)
$( derive makeBinary ''ProofStatus)
$( derive makeBinary ''SolutionExtractor)
$( derive makeBinary ''AutoProver)
$( derive makeNFData ''ProofStep)
$( derive makeNFData ''DiffProofStep)
$( derive makeNFData ''ProofStatus)
$( derive makeNFData ''SolutionExtractor)
$( derive makeNFData ''AutoProver)
instance (Ord l, NFData l, NFData a) => NFData (LTree l a) where
rnf (LNode r m) = rnf r `seq` rnf m
instance (Ord l, Binary l, Binary a) => Binary (LTree l a) where
put (LNode r m) = put r >> put m
get = LNode <$> get <*> get
| samscott89/tamarin-prover | lib/theory/src/Theory/Proof.hs | gpl-3.0 | 40,665 | 0 | 17 | 10,896 | 9,964 | 5,114 | 4,850 | 645 | 7 |
module FourChan.Helpers
( module FourChan.Helpers.Download
, module FourChan.Helpers.Html
) where
import FourChan.Helpers.Download
import FourChan.Helpers.Html
| xcv-/4chan.hs | lib/FourChan/Helpers.hs | gpl-3.0 | 173 | 0 | 5 | 27 | 34 | 23 | 11 | 5 | 0 |
-- module with tools for prime numbers
module Maths.NumberTheory.Primes
( primes,
factorize
) where
-- list of prime numbers generated by the Sieve of Eratosthenes
primes :: [Int]
primes = sieve $ 2:[3,5..]
where sieve (p:ns) = p : sieve [n | n <- ns, n `mod` p /= 0]
-- factorize integer
-- return list of prime factors (with multiplicities)
factorize :: Int -> [Int]
factorize n = factorize' n primes
where factorize' n (d:ds)
| n == 1 = []
| n `mod` d /= 0 = factorize' n ds
| otherwise = d : factorize' (n `div` d) (d:ds)
| mathemage/htools | Maths/NumberTheory/Primes.hs | apache-2.0 | 632 | 0 | 12 | 208 | 209 | 114 | 95 | 12 | 1 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Applicative hiding (many)
import Control.Monad (forM_, void)
import Control.Monad.Trans.Resource
import Data.Conduit (($$))
import qualified Data.HashMap.Strict as M
import qualified Data.List as L
import Data.Maybe (maybe)
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Time
import Database.Persist.Postgresql
import Database.Persist.Store
import Model
import Shelly
import System.Environment
import Text.XML.Stream.Parse
import qualified Text.XML.Stream.Parse as XP
import Yesod.Default.Config (DefaultEnv(..), withYamlEnvironment)
default (LT.Text)
data Post = Post
{ id :: Int
, parentId :: Maybe Int
, postTypeId :: Int
, acceptedAnswerId :: Maybe Int
, creationDate :: T.Text -- UTCTime
, score :: Int
, viewCount :: Int
, postBody :: T.Text
, ownerUserId :: Maybe Int
, lastEditorUserId :: Maybe Int
, lastEditorDisplayName :: Maybe T.Text
, lastEditDate :: Maybe T.Text -- UTCTime
, lastActivityDate :: T.Text -- UTCTime
, communityOwnedDate :: Maybe T.Text
, closedDate :: Maybe T.Text
, postTitle :: Maybe T.Text
, postTags :: Maybe T.Text
, answerCount :: Maybe Int
, commentCount :: Maybe Int
, favoriteCount :: Maybe Int
}
deriving (Show)
parsePosts = tagNoAttr "posts" $ many parseRow
parseRow = tagName "row" attrs return
where
attrs :: AttrParser Post
attrs = Post <$> (read' <$> requireAttr "Id")
<*> (fread' <$> optionalAttr "ParentId")
<*> (read' <$> requireAttr "PostTypeId")
<*> (fread' <$> optionalAttr "AcceptedAnswerId")
<*> (requireAttr "CreationDate")
<*> (read' <$> requireAttr "Score")
<*> (read' <$> requireAttr "ViewCount")
<*> (requireAttr "Body")
<*> (fread' <$> optionalAttr "OwnerUserId")
<*> (fread' <$> optionalAttr "LastEditorUserId")
<*> (optionalAttr "LastEditorDisplayName")
<*> (optionalAttr "LastEditDate")
<*> (requireAttr "LastActivityDate")
<*> (optionalAttr "CommunityOwnedDate")
<*> (optionalAttr "ClosedDate")
<*> (optionalAttr "Title")
<*> (optionalAttr "Tags")
<*> (fread' <$> optionalAttr "AnswerCount")
<*> (fread' <$> optionalAttr "CommentCount")
<*> (fread' <$> optionalAttr "FavoriteCount")
read' = read . T.unpack
fread' = fmap read'
postToDocument :: Shelly.FilePath -> UserId -> Post -> IO Document
postToDocument source userId post = do
let body = postBody post
now <- getCurrentTime
return $ Document (maybe "<untitled>" Prelude.id $ postTitle post)
(Just . LT.toStrict $ toTextIgnore source)
userId
now
(makeHash body)
body
getUserId dbconf username =
withPostgresqlConn (pgConnStr dbconf) $ runSqlConn $ do
muser <- getBy (UniqueUser username)
return $ case muser of
Just (Entity userId _) -> Just userId
Nothing -> Nothing
readPosts inputFile =
runResourceT $ XP.parseFile def inputFile
$$ force "rows required" parsePosts
loadData dbconf userId inputFiles = forM_ inputFiles $ \inputFile -> do
start <- liftIO getCurrentTime
echo (toTextIgnore inputFile)
rows <- liftIO $ readPosts inputFile
docs <- liftIO . mapM (postToDocument inputFile userId) $ take 1000 rows
let docSet = M.elems $ L.foldl' (\m d -> M.insert (documentHash d) d m)
M.empty docs
inspect ("row count:", length rows)
inspect ("unqiue count:", length docSet)
liftIO $ withPostgresqlConn (pgConnStr dbconf) $ runSqlConn $ do
forM_ docSet $ \d -> do
-- liftIO . putStrLn . (">>> " ++) $ show d
_ <- insert d
return ()
end <- liftIO getCurrentTime
inspect ("done", end `diffUTCTime` start)
main :: IO ()
main = do
args <- getArgs
case args of
(configFile:userName:inputFiles) -> do
dbconf <- withYamlEnvironment configFile Development loadConfig
mUserId <- getUserId dbconf $ T.pack userName
case mUserId of
Just userId -> shelly $ verbosely $
loadData dbconf userId $ map (fromText . LT.pack) inputFiles
Nothing -> putStrLn "Invalid user name."
_ -> putStrLn "usage: loadData DB_CONFIG_FILE USER_NAME INPUT_FILE [INPUT_FILE...]"
| erochest/whatisdh | data/loadData.hs | bsd-2-clause | 5,196 | 0 | 29 | 1,840 | 1,287 | 670 | 617 | 115 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Text.Megaparsec.ByteSpec (spec) where
import Control.Monad
import Data.ByteString (ByteString)
import Data.Char
import Data.Maybe (fromMaybe)
import Data.Proxy
import Data.Semigroup ((<>))
import Data.Void
import Data.Word (Word8)
import Test.Hspec
import Test.Hspec.Megaparsec
import Test.Hspec.Megaparsec.AdHoc (nes)
import Test.QuickCheck
import Text.Megaparsec
import Text.Megaparsec.Byte
import qualified Data.ByteString as B
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
type Parser = Parsec Void ByteString
spec :: Spec
spec = do
describe "newline" $
checkStrLit "newline" "\n" (tokenToChunk bproxy <$> newline)
describe "csrf" $
checkStrLit "crlf newline" "\r\n" crlf
describe "eol" $ do
context "when stream begins with a newline" $
it "succeeds returning the newline" $
property $ \s -> do
let s' = "\n" <> s
prs eol s' `shouldParse` "\n"
prs' eol s' `succeedsLeaving` s
context "when stream begins with CRLF sequence" $
it "parses the CRLF sequence" $
property $ \s -> do
let s' = "\r\n" <> s
prs eol s' `shouldParse` "\r\n"
prs' eol s' `succeedsLeaving` s
context "when stream begins with '\\r', but it's not followed by '\\n'" $
it "signals correct parse error" $
property $ \ch -> ch /= 10 ==> do
let s = "\r" <> B.singleton ch
prs eol s `shouldFailWith`
err posI (utoks (B.unpack s) <> elabel "end of line")
context "when input stream is '\\r'" $
it "signals correct parse error" $
prs eol "\r" `shouldFailWith` err posI
(utok 13 <> elabel "end of line")
context "when stream does not begin with newline or CRLF sequence" $
it "signals correct parse error" $
property $ \ch s -> (ch /= 13 && ch /= 10) ==> do
let s' = B.singleton ch <> s
prs eol s' `shouldFailWith` err posI
(utoks (B.unpack $ B.take 2 s') <> elabel "end of line")
context "when stream is empty" $
it "signals correct parse error" $
prs eol "" `shouldFailWith` err posI
(ueof <> elabel "end of line")
describe "tab" $
checkStrLit "tab" "\t" (tokenToChunk bproxy <$> tab)
describe "space" $
it "consumes space up to first non-space character" $
property $ \s' -> do
let (s0,s1) = B.partition isSpace' s'
s = s0 <> s1
prs space s `shouldParse` ()
prs' space s `succeedsLeaving` s1
describe "space1" $ do
context "when stream does not start with a space character" $
it "signals correct parse error" $
property $ \ch s' -> not (isSpace' ch) ==> do
let (s0,s1) = B.partition isSpace' s'
s = B.singleton ch <> s0 <> s1
prs space1 s `shouldFailWith` err posI (utok ch <> elabel "white space")
prs' space1 s `failsLeaving` s
context "when stream starts with a space character" $
it "consumes space up to first non-space character" $
property $ \s' -> do
let (s0,s1) = B.partition isSpace' s'
s = " " <> s0 <> s1
prs space1 s `shouldParse` ()
prs' space1 s `succeedsLeaving` s1
context "when stream is empty" $
it "signals correct parse error" $
prs space1 "" `shouldFailWith` err posI (ueof <> elabel "white space")
describe "controlChar" $
checkCharPred "control character" (isControl . toChar) controlChar
describe "spaceChar" $
checkCharRange "white space" [9,10,11,12,13,32,160] spaceChar
-- describe "upperChar" $
-- checkCharPred "uppercase letter" (isUpper . toChar) upperChar
-- describe "lowerChar" $
-- checkCharPred "lowercase letter" (isLower . toChar) lowerChar
-- describe "letterChar" $
-- checkCharPred "letter" (isAlpha . toChar) letterChar
describe "alphaNumChar" $
checkCharPred "alphanumeric character" (isAlphaNum . toChar) alphaNumChar
describe "printChar" $
checkCharPred "printable character" (isPrint . toChar) printChar
describe "digitChar" $
checkCharRange "digit" [48..57] digitChar
describe "octDigitChar" $
checkCharRange "octal digit" [48..55] octDigitChar
describe "hexDigitChar" $
checkCharRange "hexadecimal digit" ([48..57] ++ [97..102] ++ [65..70]) hexDigitChar
-- describe "asciiChar" $
-- checkCharPred "ASCII character" (isAscii . toChar) asciiChar
describe "char'" $ do
context "when stream begins with the character specified as argument" $
it "parses the character" $
property $ \ch s -> do
let sl = B.cons (liftChar toLower ch) s
su = B.cons (liftChar toUpper ch) s
prs (char' ch) sl `shouldParse` liftChar toLower ch
prs (char' ch) su `shouldParse` liftChar toUpper ch
prs' (char' ch) sl `succeedsLeaving` s
prs' (char' ch) su `succeedsLeaving` s
context "when stream does not begin with the character specified as argument" $
it "signals correct parse error" $
property $ \ch ch' s -> liftChar toLower ch /= liftChar toLower ch' ==> do
let s' = B.cons ch' s
ms = utok ch' <> etok (liftChar toLower ch) <> etok (liftChar toUpper ch)
prs (char' ch) s' `shouldFailWith` err posI ms
prs' (char' ch) s' `failsLeaving` s'
context "when stream is empty" $
it "signals correct parse error" $
property $ \ch -> do
let ms = ueof <> etok (liftChar toLower ch) <> etok (liftChar toUpper ch)
prs (char' ch) "" `shouldFailWith` err posI ms
----------------------------------------------------------------------------
-- Helpers
checkStrLit :: String -> ByteString -> Parser ByteString -> SpecWith ()
checkStrLit name ts p = do
context ("when stream begins with " ++ name) $
it ("parses the " ++ name) $
property $ \s -> do
let s' = ts <> s
prs p s' `shouldParse` ts
prs' p s' `succeedsLeaving` s
context ("when stream does not begin with " ++ name) $
it "signals correct parse error" $
property $ \ch s -> ch /= B.head ts ==> do
let s' = B.cons ch s
us = B.unpack $ B.take (B.length ts) s'
ps = B.unpack ts
prs p s' `shouldFailWith` err posI (utoks us <> etoks ps)
prs' p s' `failsLeaving` s'
context "when stream is empty" $
it "signals correct parse error" $
prs p "" `shouldFailWith` err posI (ueof <> etoks (B.unpack ts))
checkCharPred :: String -> (Word8 -> Bool) -> Parser Word8 -> SpecWith ()
checkCharPred name f p = do
context ("when stream begins with " ++ name) $
it ("parses the " ++ name) $
property $ \ch s -> f ch ==> do
let s' = B.singleton ch <> s
prs p s' `shouldParse` ch
prs' p s' `succeedsLeaving` s
context ("when stream does not begin with " ++ name) $
it "signals correct parse error" $
property $ \ch s -> not (f ch) ==> do
let s' = B.singleton ch <> s
prs p s' `shouldFailWith` err posI (utok ch <> elabel name)
prs' p s' `failsLeaving` s'
context "when stream is empty" $
it "signals correct parse error" $
prs p "" `shouldFailWith` err posI (ueof <> elabel name)
checkCharRange :: String -> [Word8] -> Parser Word8 -> SpecWith ()
checkCharRange name tchs p = do
forM_ tchs $ \tch ->
context ("when stream begins with " ++ showTokens (nes tch)) $
it ("parses the " ++ showTokens (nes tch)) $
property $ \s -> do
let s' = B.singleton tch <> s
prs p s' `shouldParse` tch
prs' p s' `succeedsLeaving` s
context "when stream is empty" $
it "signals correct parse error" $
prs p "" `shouldFailWith` err posI (ueof <> elabel name)
prs
:: Parser a -- ^ Parser to run
-> ByteString -- ^ Input for the parser
-> Either (ParseError Word8 Void) a -- ^ Result of parsing
prs p = parse p ""
prs'
:: Parser a -- ^ Parser to run
-> ByteString -- ^ Input for the parser
-> (State ByteString, Either (ParseError Word8 Void) a) -- ^ Result of parsing
prs' p s = runParser' p (initialState s)
bproxy :: Proxy ByteString
bproxy = Proxy
-- | 'Word8'-specialized version of 'isSpace'.
isSpace' :: Word8 -> Bool
isSpace' x
| x >= 9 && x <= 13 = True
| x == 32 = True
| x == 160 = True
| otherwise = False
-- | Convert a byte to char.
toChar :: Word8 -> Char
toChar = chr . fromIntegral
-- | Covert a char to byte.
fromChar :: Char -> Maybe Word8
fromChar x = let p = ord x in
if p > 0xff
then Nothing
else Just (fromIntegral p)
-- | Lift char transformation to byte transformation.
liftChar :: (Char -> Char) -> Word8 -> Word8
liftChar f x = (fromMaybe x . fromChar . f . toChar) x
| recursion-ninja/megaparsec | tests/Text/Megaparsec/ByteSpec.hs | bsd-2-clause | 8,920 | 0 | 23 | 2,489 | 2,763 | 1,356 | 1,407 | 197 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTableWidget_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTableWidget_h where
import Qtc.Enums.Base
import Qtc.Enums.Gui.QItemSelectionModel
import Qtc.Enums.Gui.QAbstractItemView
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QAbstractItemDelegate
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QTableWidget ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTableWidget_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QTableWidget_unSetUserMethod" qtc_QTableWidget_unSetUserMethod :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QTableWidgetSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTableWidget_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QTableWidget ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTableWidget_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QTableWidgetSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTableWidget_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QTableWidget ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTableWidget_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QTableWidgetSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTableWidget_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QTableWidget ()) (QTableWidget x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTableWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTableWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTableWidget_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setUserMethod" qtc_QTableWidget_setUserMethod :: Ptr (TQTableWidget a) -> CInt -> Ptr (Ptr (TQTableWidget x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QTableWidget :: (Ptr (TQTableWidget x0) -> IO ()) -> IO (FunPtr (Ptr (TQTableWidget x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QTableWidget_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTableWidgetSc a) (QTableWidget x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTableWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTableWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTableWidget_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QTableWidget ()) (QTableWidget x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTableWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTableWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTableWidget_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setUserMethodVariant" qtc_QTableWidget_setUserMethodVariant :: Ptr (TQTableWidget a) -> CInt -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTableWidget :: (Ptr (TQTableWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTableWidget_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTableWidgetSc a) (QTableWidget x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTableWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTableWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTableWidget_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QTableWidget ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTableWidget_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QTableWidget_unSetHandler" qtc_QTableWidget_unSetHandler :: Ptr (TQTableWidget a) -> CWString -> IO (CBool)
instance QunSetHandler (QTableWidgetSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTableWidget_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler1" qtc_QTableWidget_setHandler1 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget1 :: (Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdropEvent_h (QTableWidget ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_dropEvent" qtc_QTableWidget_dropEvent :: Ptr (TQTableWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QTableWidgetSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dropEvent cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler2" qtc_QTableWidget_setHandler2 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget2 :: (Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QTableWidget ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_event cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_event" qtc_QTableWidget_event :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QTableWidgetSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_event cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> QPoint t1 -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler3" qtc_QTableWidget_setHandler3 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget3 :: (Ptr (TQTableWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> QPoint t1 -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QindexAt_h (QTableWidget ()) ((Point)) where
indexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTableWidget_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QTableWidget_indexAt_qth" qtc_QTableWidget_indexAt_qth :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ()))
instance QindexAt_h (QTableWidgetSc a) ((Point)) where
indexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTableWidget_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance QqindexAt_h (QTableWidget ()) ((QPoint t1)) where
qindexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_indexAt cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_indexAt" qtc_QTableWidget_indexAt :: Ptr (TQTableWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex ()))
instance QqindexAt_h (QTableWidgetSc a) ((QPoint t1)) where
qindexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_indexAt cobj_x0 cobj_x1
instance QpaintEvent_h (QTableWidget ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_paintEvent" qtc_QTableWidget_paintEvent :: Ptr (TQTableWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QTableWidgetSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_paintEvent cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTableWidgetFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler4" qtc_QTableWidget_setHandler4 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> CInt -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget4 :: (Ptr (TQTableWidget x0) -> CInt -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQTableWidget x0) -> CInt -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTableWidgetFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QscrollContentsBy_h (QTableWidget ()) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_scrollContentsBy" qtc_QTableWidget_scrollContentsBy :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance QscrollContentsBy_h (QTableWidgetSc a) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> QModelIndex t1 -> ScrollHint -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2enum
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler5" qtc_QTableWidget_setHandler5 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget5 :: (Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> QModelIndex t1 -> ScrollHint -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2enum
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QscrollTo_h (QTableWidget ()) ((QModelIndex t1, ScrollHint)) where
scrollTo_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_scrollTo cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTableWidget_scrollTo" qtc_QTableWidget_scrollTo :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
instance QscrollTo_h (QTableWidgetSc a) ((QModelIndex t1, ScrollHint)) where
scrollTo_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_scrollTo cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler6" qtc_QTableWidget_setHandler6 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget6 :: (Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> IO ()) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetModel_h (QTableWidget ()) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setModel cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setModel" qtc_QTableWidget_setModel :: Ptr (TQTableWidget a) -> Ptr (TQAbstractItemModel t1) -> IO ()
instance QsetModel_h (QTableWidgetSc a) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setModel cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler7" qtc_QTableWidget_setHandler7 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget7 :: (Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO ()) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetRootIndex_h (QTableWidget ()) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setRootIndex cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setRootIndex" qtc_QTableWidget_setRootIndex :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> IO ()
instance QsetRootIndex_h (QTableWidgetSc a) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setRootIndex cobj_x0 cobj_x1
instance QsetSelectionModel_h (QTableWidget ()) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setSelectionModel cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setSelectionModel" qtc_QTableWidget_setSelectionModel :: Ptr (TQTableWidget a) -> Ptr (TQItemSelectionModel t1) -> IO ()
instance QsetSelectionModel_h (QTableWidgetSc a) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setSelectionModel cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> QModelIndex t1 -> IO (QRect t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler8" qtc_QTableWidget_setHandler8 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget8 :: (Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> QModelIndex t1 -> IO (QRect t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqvisualRect_h (QTableWidget ()) ((QModelIndex t1)) where
qvisualRect_h x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_visualRect cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_visualRect" qtc_QTableWidget_visualRect :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect ()))
instance QqvisualRect_h (QTableWidgetSc a) ((QModelIndex t1)) where
qvisualRect_h x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_visualRect cobj_x0 cobj_x1
instance QvisualRect_h (QTableWidget ()) ((QModelIndex t1)) where
visualRect_h x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QTableWidget_visualRect_qth" qtc_QTableWidget_visualRect_qth :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QvisualRect_h (QTableWidgetSc a) ((QModelIndex t1)) where
visualRect_h x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qTableWidgetFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler9" qtc_QTableWidget_setHandler9 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget9 :: (Ptr (TQTableWidget x0) -> IO ()) -> IO (FunPtr (Ptr (TQTableWidget x0) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qTableWidgetFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdoItemsLayout_h (QTableWidget ()) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_doItemsLayout cobj_x0
foreign import ccall "qtc_QTableWidget_doItemsLayout" qtc_QTableWidget_doItemsLayout :: Ptr (TQTableWidget a) -> IO ()
instance QdoItemsLayout_h (QTableWidgetSc a) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_doItemsLayout cobj_x0
instance QdragEnterEvent_h (QTableWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_dragEnterEvent" qtc_QTableWidget_dragEnterEvent :: Ptr (TQTableWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QTableWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QTableWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_dragLeaveEvent" qtc_QTableWidget_dragLeaveEvent :: Ptr (TQTableWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QTableWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QTableWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_dragMoveEvent" qtc_QTableWidget_dragMoveEvent :: Ptr (TQTableWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QTableWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragMoveEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QTableWidget ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_focusInEvent" qtc_QTableWidget_focusInEvent :: Ptr (TQTableWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QTableWidgetSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QTableWidget ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_focusOutEvent" qtc_QTableWidget_focusOutEvent :: Ptr (TQTableWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QTableWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler10" qtc_QTableWidget_setHandler10 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget10 :: (Ptr (TQTableWidget x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQTableWidget x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QTableWidget ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QTableWidget_inputMethodQuery" qtc_QTableWidget_inputMethodQuery :: Ptr (TQTableWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QTableWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent_h (QTableWidget ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_keyPressEvent" qtc_QTableWidget_keyPressEvent :: Ptr (TQTableWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QTableWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_keyPressEvent cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1str <- stringFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1str
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler11" qtc_QTableWidget_setHandler11 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQString ()) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget11 :: (Ptr (TQTableWidget x0) -> Ptr (TQString ()) -> IO ()) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQString ()) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
x1str <- stringFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1str
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QkeyboardSearch_h (QTableWidget ()) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_keyboardSearch cobj_x0 cstr_x1
foreign import ccall "qtc_QTableWidget_keyboardSearch" qtc_QTableWidget_keyboardSearch :: Ptr (TQTableWidget a) -> CWString -> IO ()
instance QkeyboardSearch_h (QTableWidgetSc a) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_keyboardSearch cobj_x0 cstr_x1
instance QmouseDoubleClickEvent_h (QTableWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_mouseDoubleClickEvent" qtc_QTableWidget_mouseDoubleClickEvent :: Ptr (TQTableWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QTableWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QTableWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_mouseMoveEvent" qtc_QTableWidget_mouseMoveEvent :: Ptr (TQTableWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QTableWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QTableWidget ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_mousePressEvent" qtc_QTableWidget_mousePressEvent :: Ptr (TQTableWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QTableWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QTableWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_mouseReleaseEvent" qtc_QTableWidget_mouseReleaseEvent :: Ptr (TQTableWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QTableWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseReleaseEvent cobj_x0 cobj_x1
instance Qreset_h (QTableWidget ()) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_reset cobj_x0
foreign import ccall "qtc_QTableWidget_reset" qtc_QTableWidget_reset :: Ptr (TQTableWidget a) -> IO ()
instance Qreset_h (QTableWidgetSc a) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_reset cobj_x0
instance QresizeEvent_h (QTableWidget ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_resizeEvent" qtc_QTableWidget_resizeEvent :: Ptr (TQTableWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QTableWidgetSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_resizeEvent cobj_x0 cobj_x1
instance QselectAll_h (QTableWidget ()) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_selectAll cobj_x0
foreign import ccall "qtc_QTableWidget_selectAll" qtc_QTableWidget_selectAll :: Ptr (TQTableWidget a) -> IO ()
instance QselectAll_h (QTableWidgetSc a) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_selectAll cobj_x0
instance QviewportEvent_h (QTableWidget ()) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_viewportEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_viewportEvent" qtc_QTableWidget_viewportEvent :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance QviewportEvent_h (QTableWidgetSc a) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_viewportEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QTableWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_contextMenuEvent" qtc_QTableWidget_contextMenuEvent :: Ptr (TQTableWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QTableWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qTableWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler12" qtc_QTableWidget_setHandler12 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget12 :: (Ptr (TQTableWidget x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQTableWidget x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qTableWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QTableWidget ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_minimumSizeHint cobj_x0
foreign import ccall "qtc_QTableWidget_minimumSizeHint" qtc_QTableWidget_minimumSizeHint :: Ptr (TQTableWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QTableWidgetSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QTableWidget ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTableWidget_minimumSizeHint_qth" qtc_QTableWidget_minimumSizeHint_qth :: Ptr (TQTableWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QTableWidgetSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QqsizeHint_h (QTableWidget ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHint cobj_x0
foreign import ccall "qtc_QTableWidget_sizeHint" qtc_QTableWidget_sizeHint :: Ptr (TQTableWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QTableWidgetSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHint cobj_x0
instance QsizeHint_h (QTableWidget ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTableWidget_sizeHint_qth" qtc_QTableWidget_sizeHint_qth :: Ptr (TQTableWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QTableWidgetSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QwheelEvent_h (QTableWidget ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_wheelEvent" qtc_QTableWidget_wheelEvent :: Ptr (TQTableWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QTableWidgetSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_wheelEvent cobj_x0 cobj_x1
instance QchangeEvent_h (QTableWidget ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_changeEvent" qtc_QTableWidget_changeEvent :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QTableWidgetSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_changeEvent cobj_x0 cobj_x1
instance QactionEvent_h (QTableWidget ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_actionEvent" qtc_QTableWidget_actionEvent :: Ptr (TQTableWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QTableWidgetSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_actionEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QTableWidget ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_closeEvent" qtc_QTableWidget_closeEvent :: Ptr (TQTableWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QTableWidgetSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_closeEvent cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qTableWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler13" qtc_QTableWidget_setHandler13 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget13 :: (Ptr (TQTableWidget x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQTableWidget x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qTableWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdevType_h (QTableWidget ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_devType cobj_x0
foreign import ccall "qtc_QTableWidget_devType" qtc_QTableWidget_devType :: Ptr (TQTableWidget a) -> IO CInt
instance QdevType_h (QTableWidgetSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_devType cobj_x0
instance QenterEvent_h (QTableWidget ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_enterEvent" qtc_QTableWidget_enterEvent :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QTableWidgetSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_enterEvent cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler14" qtc_QTableWidget_setHandler14 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget14 :: (Ptr (TQTableWidget x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQTableWidget x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QheightForWidth_h (QTableWidget ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_heightForWidth" qtc_QTableWidget_heightForWidth :: Ptr (TQTableWidget a) -> CInt -> IO CInt
instance QheightForWidth_h (QTableWidgetSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QTableWidget ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_hideEvent" qtc_QTableWidget_hideEvent :: Ptr (TQTableWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QTableWidgetSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_hideEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QTableWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_keyReleaseEvent" qtc_QTableWidget_keyReleaseEvent :: Ptr (TQTableWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QTableWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QTableWidget ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_leaveEvent" qtc_QTableWidget_leaveEvent :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QTableWidgetSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_leaveEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QTableWidget ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_moveEvent" qtc_QTableWidget_moveEvent :: Ptr (TQTableWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QTableWidgetSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qTableWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler15" qtc_QTableWidget_setHandler15 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget15 :: (Ptr (TQTableWidget x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQTableWidget x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qTableWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QTableWidget ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_paintEngine cobj_x0
foreign import ccall "qtc_QTableWidget_paintEngine" qtc_QTableWidget_paintEngine :: Ptr (TQTableWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QTableWidgetSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_paintEngine cobj_x0
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler16" qtc_QTableWidget_setHandler16 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget16 :: (Ptr (TQTableWidget x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQTableWidget x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTableWidgetFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QTableWidget ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTableWidget_setVisible" qtc_QTableWidget_setVisible :: Ptr (TQTableWidget a) -> CBool -> IO ()
instance QsetVisible_h (QTableWidgetSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QTableWidget ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_showEvent" qtc_QTableWidget_showEvent :: Ptr (TQTableWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QTableWidgetSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_showEvent cobj_x0 cobj_x1
instance QtabletEvent_h (QTableWidget ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_tabletEvent" qtc_QTableWidget_tabletEvent :: Ptr (TQTableWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QTableWidgetSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_tabletEvent cobj_x0 cobj_x1
instance QsetHandler (QTableWidget ()) (QTableWidget x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTableWidget_setHandler17" qtc_QTableWidget_setHandler17 :: Ptr (TQTableWidget a) -> CWString -> Ptr (Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTableWidget17 :: (Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTableWidget17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTableWidgetSc a) (QTableWidget x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTableWidget17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTableWidget17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTableWidget_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTableWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTableWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QTableWidget ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTableWidget_eventFilter" qtc_QTableWidget_eventFilter :: Ptr (TQTableWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QTableWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_eventFilter cobj_x0 cobj_x1 cobj_x2
| uduki/hsQt | Qtc/Gui/QTableWidget_h.hs | bsd-2-clause | 91,523 | 0 | 18 | 19,657 | 30,066 | 14,441 | 15,625 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Display
( initWindow
, destroy
, present
) where
import Control.Monad.Reader (ask, liftIO)
import Data.Types (scrnW, scrnH)
import Linear.V2
import Render.Engine
import qualified SDL
( PixelFormat (BGR888)
, Surface
, Window
, InitFlag (InitVideo)
, windowInitialSize
, defaultWindow
, createWindow
, initialize
, createRGBSurfaceFrom
, surfaceBlit
, freeSurface
, quit
, destroyWindow
, updateWindowSurface
)
initWindow :: IO SDL.Window
initWindow = do
SDL.initialize [SDL.InitVideo]
SDL.createWindow "Hobo" SDL.defaultWindow
{SDL.windowInitialSize = V2 scrnW scrnH}
destroy :: SDL.Window -> SDL.Surface -> Engine ()
destroy wind screen = liftIO $ do
SDL.destroyWindow wind
SDL.freeSurface screen
SDL.quit
present :: SDL.Window -> SDL.Surface -> Engine ()
present wind screen = do
EngineState {..} <- ask
surf <- SDL.createRGBSurfaceFrom
bBuff
(V2 scrnW scrnH)
(scrnW * 4)
SDL.BGR888
SDL.surfaceBlit surf Nothing screen Nothing
SDL.updateWindowSurface wind
| Lucsanszky/soft-engine | src/Display.hs | bsd-3-clause | 1,224 | 0 | 10 | 327 | 324 | 174 | 150 | 45 | 1 |
module Part1.Problem2 where
--
-- Even Fibonacci numbers
--
-- Each new term in the Fibonacci sequence is generated by adding the previous
-- two terms. By starting with 1 and 2, the first 10 terms will be:
--
-- 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
--
-- By considering the terms in the Fibonacci sequence whose values do not exceed
-- four million, find the sum of the even-valued terms.
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
problem2 :: Integer
problem2 = sum $ filter even $ takeWhile (<= 4000000) fibs
| c0deaddict/project-euler | src/Part1/Problem2.hs | bsd-3-clause | 536 | 0 | 8 | 107 | 82 | 50 | 32 | 5 | 1 |
module PredictionExts(extensions, Extensions, restHr, maxHr,
predictionExts, karvonen,
karvonenInv, fromPower) where
import Ultra
import Text.Printf
data Extensions = Extensions { restHr::Double, maxHr::Double, weight::Double } deriving Show
-- The famous Karvonen formula and its inverse. Any source does not
-- bother to mention a true source. Correspondence to VO2max is rather
-- good, and the biggest source of the error is the heat, and its
-- increased blood circulation. The predictions are usually on the
-- lowest possible HR average on given distance.
-- In Mongolian S2S I had very high average HR, which might
-- have been due to the high altitude of the course.
karvonen :: Extensions -> Double -> Double
karvonen hr rate
| rate > restHr hr = (rate - restHr hr) / (maxHr hr - restHr hr)
| otherwise = 0.0
karvonenInv :: Extensions -> Double -> Double
karvonenInv hr power =
power * (maxHr hr - restHr hr) + restHr hr
predictionExts :: Predictor -> Extensions -> Double -> [(String, String)]
predictionExts predictor exts time =
predExts predictor exts time
relativePower :: Predictor -> Double -> Double
relativePower p t =
(distanceByTime p t) / t / (vo2maxspeed p)
fromPower :: Double -> String
fromPower power
| power > 0.0 = printf "%02d %%" ((round (100*power))::Int)
| otherwise = ""
extensions :: Double -> Double -> Double -> Extensions
extensions r m w
-- Oh, well. After two beers. Consider refactoring.
| m > r && r > 0 && w <= 0 = Extensions r m 0
| m > r && r > 0 && w > 0 = Extensions r m w
| w > 0 = Extensions 0 0 w
| otherwise = Extensions 0 0 0
fromExtensions :: Double -> String
fromExtensions rate
| rate > 0 = printf "%d" ((round rate)::Int)
| otherwise = ""
-- Typical variation of O2 consumption is around 190-210ml/kg/km
-- for the recreational athletes and 180 - 220 ml/kg/km covers already
-- most elites and runners without any skill.
-- kcalkgkm == 1 correspond approximately 200. Did not bother to check
-- though.
kcal :: Double -> Double -> String
kcal w d
| w > 0 = printf "%d" ((round (kcalkgkm * (d/1000) * w))::Int)
| otherwise = ""
where kcalkgkm = 1
-- Also known as respiratory exchange ratio.
-- Assuming linear relationship, so that 50% power corresponds 100% fat and
-- And 85% (anaerobic threshold) corresponds 100% from carbs. Using 0.7 and 1.0
-- as ratios on these ends, and the linear between.
-- The relation is not really linear, and the biggest error is in the
-- low power regime.
co2o2ratio rp
| rp >= 0.85 = 1.0
| rp < 0.5 = 0.7
| otherwise = 0.7 + 0.3/0.35*(rp-0.5)
-- Sources for the error are the running economy (litersperminutperkg) and
-- RER (co2o2ratio). The magnitude is correct, but +/- 10% error is probably
-- true.
co2 :: Double -> Double -> Double -> String
co2 rp d w
| rp > 0 && w > 0 = printf "%dg" ((round (w * (d/1000) *
litersperminuteperkg
/ lpmol * co2molweight *
(co2o2ratio rp)))::Int)
| otherwise = ""
where litersperminuteperkg = 0.2 -- oxygen consumption
lpmol = 22.04 -- L/mol
co2molweight = 44.01 -- molar mass g/mol
predExts :: Predictor -> Extensions -> Double -> [(String, String)]
predExts predictor exts time =
[ ("power", fromPower rp)
, ("hr" , fromExtensions (karvonenInv exts rp))
, ("kcal" , kcal w d)
, ("co2" , co2 rp d w)
]
where rp = relativePower predictor time
d = distanceByTime predictor time
w = weight exts
| jrosti/ultra | src/PredictionExts.hs | bsd-3-clause | 3,748 | 0 | 17 | 1,020 | 948 | 499 | 449 | 61 | 1 |
{-# LANGUAGE NamedFieldPuns #-}
module Text.Scalar.CLI where
import System.IO (hPutStr, hPutStrLn, hPrint, stderr)
import Control.Monad (when)
import Text.Scalar
import Text.Pandoc.Options
import Text.Pandoc.Readers.Scalar
import Text.Pandoc (Pandoc, writeJSON)
import qualified Data.Text as T
import Options.Applicative
data CliArgs = CliArgs
{ maybePath :: Maybe String
, warnings :: Bool
, inputFile :: String
}
cliArgs :: Parser CliArgs
cliArgs = CliArgs
<$> (optional $ strOption ( short 'p'
<> metavar "PATH"
<> help "The Scalar page with the path to follow (defaults to index)"))
<*> switch ( short 'v'
<> long "verbose"
<> help "display additional processing information")
<*> argument str (metavar "INPUT")
run :: CliArgs -> IO ()
run CliArgs {inputFile, maybePath, warnings} = do
let orderBy = case maybePath of
Just path -> Path $ T.pack path
Nothing -> IndexPath
scalarOpts = def {orderPagesBy = orderBy}
(pandoc, log') <- fmap runScalarM $ case inputFile of
"-" -> parseStdin scalarOpts
_ -> readAndParseScalarFile inputFile scalarOpts
when (not (null log') && warnings) $ do
hPutStr stderr $ "Warnings:\n" ++ log'
hPutStrLn stderr ""
case pandoc of
Left err -> hPutStr stderr "Error: " >> case err of
ScalarError strErr -> hPutStrLn stderr strErr
_ -> hPrint stderr err
Right doc -> putStrLn $ writeJSON def doc
parseStdin :: ScalarOptions -> IO (ScalarM Pandoc)
parseStdin opts = fmap (readScalar def opts) getContents
main :: IO ()
main = execParser opts >>= run
where
opts = info (helper <*> cliArgs)
( fullDesc
<> progDesc "Reads INPUT and outputs pandoc's native format to stdout"
<> header "scalar-convert - export ANVC Scalar RDF/XML with pandoc" )
| corajr/scalar-convert | src/Text/Scalar/CLI.hs | bsd-3-clause | 1,861 | 0 | 15 | 450 | 545 | 278 | 267 | 48 | 5 |
-- Author: Lee Ehudin
-- Contains all event handling and UI updating code
module Controller.EventHandler (handleEvents) where
import Model.Buffer (MBuffer, ModifyMBuffer, left, right, upLine, downLine,
insert, delete, insertNewline, getScreen, getCursorPos,
writeBufferToFile)
import View.Curses (updateText)
import Control.Monad (unless)
import UI.HSCurses.Curses (Key(..), getCh)
-- Character codes for actions on certain computers
backspace, enter, escape, save, close :: Char
backspace = '\DEL'
enter = '\r'
escape = '\ESC'
save = '\DC3' -- ctrl + s
close = '\EOT' -- ctrl + d
-- Maps keys to actions that modify the buffer
handleKey :: Key -> ModifyMBuffer
handleKey (KeyChar c)
| c == backspace = delete
| c == enter = insertNewline
| c == save = writeBufferToFile
| otherwise = insert c
handleKey KeyDown = downLine
handleKey KeyUp = upLine
handleKey KeyLeft = left
handleKey KeyRight = right
handleKey KeyBackspace = delete
handleKey _ = const $ return ()
-- Loop to get a key as input, then modify the buffer and refresh the screen
-- until either the escape key is pressed or ctrl + d
handleEvents :: (Int, Int) -> MBuffer -> IO ()
handleEvents screenSize buffer = do
key <- getCh
unless (key == KeyChar escape || key == KeyChar close) $ do
handleKey key buffer
cursorPos <- getCursorPos buffer
getScreen screenSize buffer >>= updateText cursorPos screenSize
handleEvents screenSize buffer
| percivalgambit/hasked | src/Controller/EventHandler.hs | bsd-3-clause | 1,574 | 0 | 13 | 394 | 381 | 206 | 175 | 33 | 1 |
-- | Compose functions with higher arity.
--
-- Ever tried something like this:
--
-- > (length . (++)) stringA stringB
--
-- Only to find out that you can't? The second function takes two parameters,
-- and as such the simple function composition does not work.
--
-- A well known solution to this problem is this fun operator:
--
-- > (.).(.) :: (c -> d) -> (a -> b -> c) -> (a -> b -> d)
--
-- And this is quite general:
--
-- > ((.).(.).(.)) :: (d -> e) -> (a -> b -> c -> d) -> (a -> b -> c -> e)
--
-- See the following link to gain a intuition for how this works:
-- <https://stackoverflow.com/questions/17585649/composing-function-composition-how-does-work>
--
-- However, in real use these suffer from some problems, namely:
--
-- * They cannot be used infix, even with ticks (at least in ghci).
--
-- * They are quite verbose.
--
-- Then, someone thought about using a new symbol instead:
--
-- > (.:) :: (c -> d) -> (a -> b -> c) -> (a -> b -> d)
--
-- And for each new parameter, you would add a dot
--
-- > (.:.) :: (d -> e) -> (a -> b -> c -> d) -> (a -> b -> c -> e)
--
-- And so on, to @.::@, @.::.@, etc. This is the approach taken by
-- the "composition" package, which inspired this one. It can be found at:
--
-- <http://hackage.haskell.org/package/composition>
--
-- This package is included in (and re-exported from) this AltComposition.
--
-- So, why define a new package?
--
-- It does not scale well for other combinations. Let say I want @(+) . (*)@,
-- a function that takes three parameters, uses the first two in the multiplication,
-- and then adds the third parameter with the result.
-- And what if I want to feed to the first binary function as the second parameter of
-- the second function?
--
-- The scheme proposed here is a little more verbose than the one from the
-- "composition" package, but it allows for a precise indication of where the
-- result of the first function is applied on the second function using the
-- @%@ symbol (remember printf @%@). So, the following operator:
--
-- > *%*.**
--
-- Takes a binary function, and composes it with a ternary function,
-- aplying its result as the middle parameter.
--
-- Its all a matter of opinion, and I strongly recomend that you use standard
-- haskell syntax instead of these, for more portable code.
--
-- Also, many of these verbose operators have simpler counterparts.
-- This is either noted as Deprecation, or a single note.
--
-- However, I still find myself writing the @*%.***@ operators myself, and I trust
-- the deprecations to warn me about the simpler alternatives.
--
-- If you need even higher arity, first check your code, then refactor your code,
-- and if you still need it, please send a pull request!
--
module Data.AltComposition (
module Data.Composition
, (%.**)
, (%.***)
, (%.****)
, (%*.*)
, (%*.**)
, (%*.***)
{-, (%*.****)-}
, (*%.*)
, (*%.**)
, (*%.***)
{-, (*%.****)-}
, (%**.*)
, (%**.**)
, (%**.***)
{-, (%**.****)-}
, (*%*.*)
, (*%*.**)
, (*%*.***)
{-, (*%*.****)-}
, (**%.*)
, (**%.**)
, (**%.***)
{-, (**%.****)-}
, (%***.*)
, (%***.**)
, (?.)
, (.$)
, (§)
, (&&\)
, (||\)
, for
, with
) where
import Data.Composition
import qualified Control.Category as Cat
-- | Compose a binary function with a unitary function
--
-- /Note/: you should use idiomatic haskell instead
--
-- > (.).(.) :: (c -> d) -> (a -> b -> c) -> (a -> b -> d)
--
-- > (f %.** g) x y = f (g x y)
--
-- > (f .: g) x y = f (g x y)
(%.**) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(f %.** g) x y = f (g x y)
infixr 9 %.**
-- | Compose a ternary function with a unitary function
--
-- /Note/: you should use idiomatic haskell instead
--
-- > (.).(.).(.) :: (d -> e) -> (a -> b -> c -> d) -> (a -> b -> c -> e)
--
-- > (f %.*** g) x y z = f (g x y z)
--
-- > (f .:. g) x y z = f (g x y z)
(%.***) :: (d -> e) -> (a -> b -> c -> d) -> a -> b -> c -> e
(f %.*** g) x y z = f (g x y z)
infixr 9 %.***
-- | Compose a quaternary function with a unitary function
--
-- /Note/: you should use idiomatic haskell instead
--
-- > (.).(.).(.).(.) :: (e -> f) -> (a -> b -> c -> d -> e) -> (a -> b -> c -> d -> f)
--
-- > (f %.**** g) w x y z = f (g w x y z)
--
-- > (f .:: g) w x y z = f (g w x y z)
(%.****) :: (e -> f) -> (a -> b -> c -> d -> e) -> a -> b -> c -> d -> f
(f %.**** g) w x y z = f (g w x y z)
infixr 9 %.****
-- | Compose a unary function with a binary function,
-- applying the result of the unary function as the
-- first parameter of the binary function.
--
-- /Note/: DO NOT USE. Equivalent to @.@.
--
-- > (f %*.* g) x y = f (g x) y <=> f . g
(%*.*) :: (b -> c -> d) -> (a -> b) -> a -> c -> d
(f %*.* g) x y = f (g x) y
infixr 9 %*.*
{-# DEPRECATED (%*.*) "This is the same as just (.)" #-}
-- | Compose a unary function with a binary function,
-- applying the result of the unary function as the
-- second parameter of the binary function.
--
-- /Note/: DO NOT USE. Equivalent to @flip f . g@.
--
-- > (f *%.* g) x y = f y (g x)
(*%.*) :: (b -> c -> d) -> (a -> c) -> a -> b -> d
(f *%.* g) x y = f y (g x)
infixr 9 *%.*
-- | Compose a unary function with a ternary function,
-- applying the result of the unary function as the
-- first parameter of the ternary function.
--
-- /Note/: DO NOT USE. Equivalent to @.@.
--
-- > (f %**.* g) x y z = f (g x) y z
(%**.*) :: (b -> c -> d -> e) -> (a -> b) -> a -> c -> d -> e
(f %**.* g) x y z = f (g x) y z
infix 9 %**.*
{-# DEPRECATED (%**.*) "This is the same as just (.)" #-}
-- | Compose a unary function with a ternary function,
-- applying the result of the unary function as the
-- second parameter of the ternary function.
--
-- > (f *%*.* g) x y z = f y (g x) z
(*%*.*) :: (b -> c -> d -> e) -> (a -> c) -> a -> b -> d -> e
(f *%*.* g) x y z = f y (g x) z
infix 9 *%*.*
-- | Compose a unary function with a ternary function,
-- applying the result of the unary function as the
-- third parameter of the ternary function.
--
-- > (f **%.* g) x y z = f y z (g x)
(**%.*) :: (b -> c -> d -> e) -> (a -> d) -> a -> b -> c -> e
(f **%.* g) x y z = f y z (g x)
infix 9 **%.*
-- | Compose a binary function with another binary function,
-- applying the result of the first binary function as the
-- first parameter of the second binary function.
--
-- /Note/: DO NOT USE. Equivalent to @flip f . g@.
--
-- > (f %*.** g) x y z = f (g x y) z
(%*.**) :: (c -> d -> e) -> (a -> b -> c) -> a -> b -> d -> e
(f %*.** g) x y z = f (g x y) z
infixr 9 %*.**
{-# DEPRECATED (%*.**) "Use f %.** g or .: instead" #-}
-- | Compose a binary function with another binary function,
-- applying the result of the first binary function as the
-- second parameter of the second binary function.
--
-- /Note/: DO NOT USE. Equivalent to @flip f .: g@ or @flip f %.** g@.
--
-- > (f *%.** g) x y z = f z (g x y)
(*%.**) :: (c -> d -> e) -> (a -> b -> d) -> a -> b -> c -> e
(f *%.** g) x y z = f z (g x y)
infixr 9 *%.**
-- | Compose a ternary function with a binary function,
-- applying the result of the ternary function as the
-- first parameter of the binary function.
--
-- > (f %*.*** g) x y w z = f (g x y w) z
(%*.***) :: (d -> e -> f) -> (a -> b -> c -> d) -> a -> b -> c -> e -> f
(f %*.*** g) x y w z = f (g x y w) z
infix 9 %*.***
{-# DEPRECATED (%*.***) "Use f %.*** g or f .:. instead" #-}
-- | Compose a ternary function with a binary function,
-- applying the result of the ternary function as the
-- second parameter of the binary function.
--
-- /Note/: DO NOT USE. Equivalent to @flip f .:. g@ or @flip f %.*** g@.
--
-- > (f *%.*** g) x y w z = f z (g x y w)
(*%.***) :: (d -> e -> f) -> (a -> b -> c -> e) -> a -> b -> c -> d -> f
(f *%.*** g) x y w z = f z (g x y w)
infix 9 *%.***
-- | Compose a binary function with a ternary function,
-- applying the result of the binary function as the
-- first parameter of the ternary function.
--
-- > (f %**.** g) x y w z = f (g x y) w z
(%**.**) :: (c -> d -> e -> f) -> (a -> b -> c) -> a -> b -> d -> e -> f
(f %**.** g) x y w z = f (g x y) w z
infix 9 %**.**
{-# DEPRECATED (%**.**) "Use f %.** g or f .: instead" #-}
-- | Compose a binary function with a ternary function,
-- applying the result of the binary function as the
-- second parameter of the ternary function.
--
-- /Note/: DO NOT USE. Equivalent to @flip f .: g@ or @flip f %.** g@.
--
-- > (f *%*.** g) x y w z = f w (g x y) z
(*%*.**) :: (c -> d -> e -> f) -> (a -> b -> d) -> a -> b -> c -> e -> f
(f *%*.** g) x y w z = f w (g x y) z
infix 9 *%*.**
{-# DEPRECATED (*%*.**) "Use f *%.** g instead" #-}
-- | Compose a binary function with a ternary function,
-- applying the result of the binary function as the
-- third parameter of the ternary function.
--
-- > (f **%.** g) x y w z = f w z (g x y)
(**%.**) :: (c -> d -> e -> f) -> (a -> b -> e) -> a -> b -> c -> d -> f
(f **%.** g) x y w z = f w z (g x y)
infix 9 **%.**
-- | Compose a ternary function with another ternary function,
-- applying the result of the first ternary function as the
-- first parameter of the last ternary function.
--
-- > (f %**.*** g) v w x y z = f (g v w x) y z
(%**.***) :: (f -> d -> e -> g) -> (a -> b -> c -> f) -> a -> b -> c -> d -> e -> g
(f %**.*** g) v w x y z = f (g v w x) y z
infix 9 %**.***
{-# DEPRECATED (%**.***) "Use f %.*** g or f .:. instead" #-}
-- | Compose a ternary function with another ternary function,
-- applying the result of the first ternary function as the
-- second parameter of the last ternary function.
--
-- /Note/: DO NOT USE. Equivalent to @flip f .:. g@ or @flip f %.*** g@.
--
-- > (f *%*.*** g) v w x y z = f y (g v w x) z
(*%*.***) :: (d -> f -> e -> g) -> (a -> b -> c -> f) -> a -> b -> c -> d -> e -> g
(f *%*.*** g) v w x y z = f y (g v w x) z
infix 9 *%*.***
{-# DEPRECATED (*%*.***) "Use f *%.*** g instead" #-}
-- | Compose a ternary function with another ternary function,
-- applying the result of the first ternary function as the
-- third parameter of the last ternary function.
--
-- > (f **%.*** g) v w x y z = f y z (g v w x)
(**%.***) :: (d -> e -> f -> g) -> (a -> b -> c -> f) -> a -> b -> c -> d -> e -> g
(f **%.*** g) v w x y z = f y z (g v w x)
infix 9 **%.***
-- | Compose a unary function with a quaternary function,
-- applying the result of the first unary function as the
-- first parameter of the quaternary function.
--
-- > (f %***.* g) w x y z = f (g w) x y z
(%***.*) :: (f -> b -> c -> d -> g) -> (a -> f) -> a -> b -> c -> d -> g
(f %***.* g) w x y z = f (g w) x y z
infix 9 %***.*
{-# DEPRECATED (%***.*) "This is the same as just (.)" #-}
-- | Compose a binary function with a quaternary function,
-- applying the result of the first binary function as the
-- first parameter of the quaternary function.
--
-- > (f %***.** g) v w x y z = f (g v w) x y z
(%***.**) :: (f -> c -> d -> e -> g) -> (a -> b -> f) -> a -> b -> c -> d -> e -> g
(f %***.** g) v w x y z = f (g v w) x y z
infix 9 %***.**
{-# DEPRECATED (%***.**) "This is the same as just %.** or .:" #-}
-- | Conditional composition. Borrowed (and modified) from
-- <http://hackage.haskell.org/package/cond-0.4.0.2>
-- If the predicate is False, 'id' is returned
-- instead of the second argument. This function, for example, can be used to
-- conditionally add functions to a composition chain.
(?.) :: (Cat.Category cat) => Bool -> cat a a -> cat a a
p ?. c = if p then c else Cat.id
{-# INLINE (?.) #-}
-- | Slightly Lower fixity function composition for use with @'?.'@.
(.$) :: (b -> c) -> (a -> b) -> (a -> c)
(.$) = (Prelude..)
infixl 8 .$
-- | Just like (@'$'@), but with higher precedence than (@'<>'@), but still lower
-- than (@'.'@). Similar to "Diagrams.Util" @'#'@, but without flipped arguments.
{-# INLINE (§) #-}
(§) :: (a -> b) -> a -> b
f § x = f x
infixr 8 §
-- | Group conditions with @'&&'@. Useful for filter.
--
-- /Note/: an easy mnemonic to remember is that operators ending in \\ (lambda)
-- imply that their parameters are functions instead of values (in this particular
-- case, boolean tests)
--
-- > (f &&\ g) x = f x && g x
(&&\) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(f &&\ g) x = f x && g x
infixr 3 &&\{- This comment tells CPP to behave -}
-- | Group conditions with @'||'@ Useful for filter.
--
-- /Note/: an easy mnemonic to remember is that operators ending in \\ (lambda)
-- imply that their parameters are functions instead of values (in this particular
-- case, boolean tests)
--
-- > (f ||\ g) x = f x || g x
(||\) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(f ||\ g) x = f x || g x
infixr 2 ||\{- This comment tells CPP to behave -}
-- | fmap with its arguments reversed.
--
-- <http://www.reddit.com/r/haskell/comments/qy990/suggestion_for_flip_map/>
--
-- > for = flip fmap
-- > with = flip fmap
for,with :: (Functor f) => f a -> (a -> b) -> f b
for = flip fmap
with= flip fmap
| jcristovao/altcomposition | Data/AltComposition.hs | bsd-3-clause | 12,837 | 0 | 15 | 3,057 | 2,647 | 1,544 | 1,103 | 120 | 2 |
module Hashids where
encode :: [Int] -> String
encode nums = show nums
decode :: String -> [Int]
decode hashid = read hashid
| newhoggy/hashids-haskell | src/Hashids.hs | bsd-3-clause | 128 | 0 | 6 | 26 | 50 | 27 | 23 | 5 | 1 |
{-# LANGUAGE GADTs, RankNTypes, TupleSections #-}
module QnA5
where
type Input = String
type Prompt = String
type Color = String
type Size = Int
type Weight = Int
type Height = Int
data Question a = Question {
prompt :: Prompt,
answer :: Input -> a
}
doYouKnowYourSizeQ :: Question Bool
doYouKnowYourSizeQ = Question "Do you know your size?" read
whatIsYourSizeQ :: Question Size
whatIsYourSizeQ = Question "What is your size?" read
whatIsYourWeightQ :: Question Weight
whatIsYourWeightQ = Question "What is your weight?" read
whatIsYourHeightQ :: Question Height
whatIsYourHeightQ = Question "What is your height?" read
whatIsYourFavColorQ :: Question Color
whatIsYourFavColorQ = Question "What is your fav color?" id
data EdgeId = E1 | E2 | E3 | E4 | Ef deriving (Read, Show)
data Node s a s' = Node {
question :: Question a,
process :: s -> a -> s'
}
data Edge s sf where
Edge :: EdgeId -> Node s a s' -> (s' -> a -> Edge s' sf) -> Edge s sf
Final :: EdgeId -> Node s a s' -> (s' -> a -> sf) -> Edge s sf
n1 :: Node () Bool Bool
n1 = Node doYouKnowYourSizeQ (const id)
n2 :: Node Bool Size (Bool, Size)
n2 = Node whatIsYourSizeQ (,)
n3 :: Node Bool Weight (Bool, Weight)
n3 = Node whatIsYourWeightQ (,)
n4 :: Node (Bool, Weight) Height (Bool, Size)
n4 = Node whatIsYourHeightQ (\ (b, w) h -> (b, w * h))
n5 :: Node (Bool, Size) Color (Bool, Size, Color)
n5 = Node whatIsYourFavColorQ (\ (b, i) c -> (b, i, c))
-- These Edges are type checked
e1 = Edge E1 n1 (const $ \ b -> if b then e2 else e3)
e2 = Edge E2 n2 (const $ const ef)
e3 = Edge E3 n3 (const $ const e4)
e4 = Edge E4 n4 (const $ const ef)
ef = Final Ef n5 const
ask :: Edge s sf -> Prompt
ask (Edge _ n _) = prompt $ question n
ask (Final _ n _) = prompt $ question n
respond :: s -> Input -> Edge s sf -> Either sf (s', Edge s' sf)
respond s i (Edge _ n f) =
let a = (answer $ question n) i
s' = process n s a
n' = f s' a
in Right undefined --TODO n'
respond s i (Final _ n f) =
let a = (answer $ question n) i
s' = process n s a
in Left undefined --TODO s'
-- User Interaction:
saveState :: (Show s) => (s, Edge s sf) -> String
saveState (s, Edge eid n _) = show (s, eid)
getEdge :: EdgeId -> Edge s sf
getEdge = undefined --TODO
main' :: String -> Input -> Either sf (s', Edge s' sf)
main' state input =
let (s, eid) = read state :: ((), EdgeId) --TODO
edge = getEdge eid
in respond s input edge
| homam/fsm-conversational-ui | src/QnA5.hs | bsd-3-clause | 2,443 | 0 | 12 | 572 | 1,041 | 558 | 483 | 65 | 2 |
{-# LANGUAGE ImplicitParams, TupleSections, RecordWildCards, ScopedTypeVariables #-}
-- Convert flattened spec to internal representation
module Frontend.SpecInline (specSimplify, spec2Internal, specXducers2Internal) where
import Data.List
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Monad.State hiding (guard)
import qualified Data.Graph.Inductive.Graph as G
import TSLUtil
import Util hiding (name, trace)
import Frontend.Spec
import qualified Internal.ISpec as I
import qualified Internal.TranSpec as I
import qualified Internal.IExpr as I
import qualified Internal.CFA as I
import qualified Internal.IType as I
import qualified Internal.IVar as I
import qualified Internal.ITransducer as I
import Internal.PID
import Pos
import Name
import Frontend.NS
import Frontend.Statement
import Frontend.StatementInline
import Frontend.Expr
import Frontend.ExprInline
import Frontend.Template
import Frontend.TemplateOps
import Frontend.TemplateFlatten
import Frontend.RelationInline
import Frontend.TVar
import Frontend.TVarOps
import Frontend.Method
import Frontend.MethodOps
import Frontend.Process
import Frontend.Type
import Frontend.Inline
import Frontend.Transducer
-- Main function
-- The input spec must be simplified using specSimplify
spec2Internal :: Spec -> I.Spec
spec2Internal s =
let -- preprocessing
?spec = s in
let cfas = I.specAllCFAs spec
pids = map fst $ I.specAllProcs spec
-- PC variables and associated enums
(pcvars, pcenums) = unzip
$ map (\(EPIDProc pid,cfa) -> let enum = I.Enumeration (mkPCEnumName pid) $ map (mkPCEnum pid) $ I.cfaDelayLocs cfa
var = I.Var False I.VarState (mkPCVarName pid) (I.Enum Nothing $ I.enumName enum)
in (var, enum))
$ filter ((/=1) . length . I.cfaDelayLocs . snd)
$ filter ((/= EPIDCont) . fst) cfas
-- built-in enums used in translating choice{} statements
nctasks = length $ filter ((== Task Controllable) . methCat) $ tmMethod tmMain
choiceenum = map mkChoiceEnumDecl [0..(max 31 nctasks)]
senum = mapMaybe (\d -> case tspec d of
EnumSpec _ es -> Just $ I.Enumeration (sname d) (map sname es)
_ -> Nothing) (specType ?spec)
(pidlvar, pidenum) = mkPIDLVarDecl pids
vars = mkVars
(tvar, tenum) = mkTagVarDecl
fairreg = mkFair spec'
((specWire, specPrefix, inittran, goals), (_, extratmvars)) =
runState (do wire <- mkWires
prefix <- mkPrefix
inittr <- mkInit
usergoals <- mapM mkGoal $ tmGoal tmMain
maggoal <- mkMagicGoal
return (wire, prefix, inittr, maggoal:usergoals))
(0,[])
extraivars = let ?scope = ScopeTemplate tmMain in map (\v -> mkVarDecl (varMem v) (NSID Nothing Nothing) v (varType v)) extratmvars
(specProc, tmppvs) = unzip $ (map procToCProc $ tmProcess tmMain)
specRels = map relToIRel $ tmRelation tmMain
specEnum = choiceenum ++ (tenum : pidenum : (senum ++ pcenums))
specVar = cvars ++ [tvar, pidlvar] ++ pcvars ++ vars ++ concat tmppvs ++ extraivars
specCAct = ctran
specTran = error "specTran undefined"
specUpds = M.empty -- mkUpds spec'
specApply = map applyToIApply $ tmApply tmMain
specXducers = map xducerToIXducer $ specTransducer s
spec0 = I.Spec {..}
spec = I.specMapCFA (\cfa -> I.cfaMapExpr cfa $ exprExpandLabels spec0) spec0
spec' = I.specMapCFA (\cfa -> I.cfaMapStat cfa $ statAddNullTypes spec) spec
-- Controllable transitions
(ctran, cvars) = mkCTran
-- Uncontrollable transitions
utran = concatMap (\(epid, cfa) -> cfaToITransitions epid cfa)
$ filter ((/= EPIDCont) . fst)
$ I.specAllCFAs spec'
-- initialise PC variables.
pcinit = map (\(EPIDProc pid, cfa) -> mkPCEq cfa pid (mkPC pid I.cfaInitLoc))
$ filter ((/= EPIDCont) . fst)
$ I.specAllCFAs spec'
-- initialise $en vars to false
peninit = concatMap (mapPTreeFProc (\pid _ -> mkEnVar pid Nothing I.=== I.false)) $ tmProcess tmMain
maginit = mkMagicVar I.=== I.false
errinit = mkErrVar I.=== I.false
res =
spec' {I.specTran = I.TranSpec { I.tsCTran = cfaToITransitions EPIDCont $ I.specCAct spec'
, I.tsUTran = utran
, I.tsInit = (inittran, I.conj $ (pcinit ++ peninit ++ [errinit, maginit]))
, I.tsGoal = map (\g -> g{I.goalCond = (I.goalCond g){I.tranCFA = I.cfaMapExpr (I.tranCFA $ I.goalCond g) $ exprExpandLabels spec'}}) goals
, I.tsFair = map (\f -> f{I.fairCond = exprExpandLabels spec' (I.fairCond f)}) fairreg
}} in
{-I.cfaTraceFiles (zip (map (("tr" ++) . show) [0..]) $ map I.tranCFA $ (I.tsUTran $ I.specTran res) ++ (I.tsCTran $ I.specTran res)) $-} res
------------------------------------------------------------------------------
-- Preprocess all statements and expressions before inlining.
-- In the preprocessed spec:
-- * Method calls can only appear in top-level expressions
-- * No method calls in return statements
-- * Local variables are declared and initialised separately
------------------------------------------------------------------------------
specSimplify :: Spec -> Spec
specSimplify s = let ?spec = s
in s{specTemplate = [tmSimplify (head $ specTemplate s)]}
tmSimplify :: (?spec::Spec) => Template -> Template
tmSimplify tm = tm { tmProcess = map (procSimplify tm) (tmProcess tm)
, tmMethod = map (methSimplify tm) (tmMethod tm)}
procSimplify :: (?spec::Spec) => Template -> Process -> Process
procSimplify tm p = let ?scope = ScopeProcess tm p
in p { procStatement = evalState (statSimplify $ procStatement p) (0,[])}
methSimplify :: (?spec::Spec) => Template -> Method -> Method
methSimplify tm m = let ?scope = ScopeMethod tm m
in m { methBody = Right $ evalState (statSimplify $ fromRight $ methBody m) (0,[])}
----------------------------------------------------------------------
-- Wires
----------------------------------------------------------------------
-- Generate transition that assigns all wire variables. It will be
-- implicitly prepended to all "regular" transitions.
mkWires :: (?spec::Spec) => NameGen (Maybe I.CFA)
mkWires | (null $ tmWire tmMain) = return Nothing
| otherwise = do
let wires = orderWires
-- Generate assignment statement for each wire
stat <- let ?scope = ScopeTemplate tmMain
in statSimplify $ SSeq nopos Nothing $ map (\w -> SAssign (pos w) Nothing (ETerm nopos [name w]) (fromJust $ wireRHS w)) wires
let ctx = CFACtx { ctxEPID = Nothing
, ctxStack = [(ScopeTemplate tmMain, error "return from a wire assignment", Nothing, M.empty)]
, ctxCFA = I.newCFA (ScopeTemplate tmMain) stat I.true
, ctxBrkLocs = [error "break outside a loop"]
, ctxGNMap = globalNMap
, ctxLastVar = 0
, ctxVar = []
, ctxLabels = []}
ctx' = let ?procs =[]
?nestedmb = False
?xducer = False
in execState (procStatToCFA stat I.cfaInitLoc) ctx
return $ Just $ {-I.cfaTraceFile (ctxCFA ctx') "wires_cfa" $-} ctxCFA ctx'
-- Build total order of wires so that for each wire, all wires that
-- it depends on occur eaerlier in the ordering.
-- Recursively prune nodes without dependencies from the wire dependency graph.
-- (assumes that the graph is acyclic)
orderWires :: (?spec::Spec) => [Wire]
orderWires = map (\n -> getWire s $ fromJust $ G.lab g n) $ orderWires' g
where s = ScopeTemplate tmMain
g = wireGraph
orderWires' :: (?spec::Spec) => WireGraph -> [G.Node]
orderWires' g | G.noNodes g == 0 = []
| otherwise = ord ++ orderWires' g'
where (g',ord) = foldl' (\(g0,ord0) n -> if null $ G.suc g0 n then (G.delNode n g0, ord0++[n]) else (g0,ord0))
(g,[]) (G.nodes g)
----------------------------------------------------------------------
-- Prefix-block
----------------------------------------------------------------------
-- Generate transition that performs all prefix actions. It will be
-- implicitly prepended to all "regular" transitions.
mkPrefix :: (?spec::Spec) => NameGen (Maybe I.CFA)
mkPrefix | (null $ tmPrefix tmMain) = return Nothing
| otherwise = do
stat <- let ?scope = ScopeTemplate tmMain
in statSimplify $ SSeq nopos Nothing $ map prefBody $ tmPrefix tmMain
let ctx = CFACtx { ctxEPID = Nothing
, ctxStack = [(ScopeTemplate tmMain, error "return from an prefix-block", Nothing, M.empty)]
, ctxCFA = I.newCFA (ScopeTemplate tmMain) stat I.true
, ctxBrkLocs = [error "break outside a loop"]
, ctxGNMap = globalNMap
, ctxLastVar = 0
, ctxVar = []
, ctxLabels = []}
ctx' = let ?procs = []
?nestedmb = False
?xducer = False
in execState (procStatToCFA stat I.cfaInitLoc) ctx
return $ Just $ {- I.cfaTraceFile (ctxCFA ctx') "prefix_cfa" $-} ctxCFA ctx'
----------------------------------------------------------------------
-- Fair sets
----------------------------------------------------------------------
--mkFair :: (?spec::Spec) => I.Spec -> ([I.Var], [I.Expr], I.FairRegion)
--mkFair ispec = (mkFairRegVarDecls ispec
-- , map (I.=== I.false) $ mkFairRegVars ispec
-- , I.FairRegion "fair" $ I.neg $ I.conj $ mkFairRegVars ispec)
mkFair :: (?spec::Spec) => I.Spec -> [I.FairRegion]
mkFair ispec = mkFairSched : (map mkFairProc $ I.specAllProcs ispec)
where
-- Fair scheduling: GF (not ($magic==true && $cont == false))
mkFairSched = I.FairRegion "fair_scheduler" $ (mkMagicVar I.=== I.true) `I.land` (mkContLVar I.=== I.false)
-- For each uncontrollable process:
-- GF (not ((\/i . pc=si && condi) && lastpid /= pid))
-- where si and condi are process pause locations and matching conditions
-- i.e, the process eventually either becomes disabled or makes a transition.
mkFairProc :: (PrID, I.Process) -> I.FairRegion
mkFairProc (pid,p) = I.FairRegion ("fair_" ++ show pid)
$ mkFairCFA (I.procCFA p) pid
mkFairCFA :: I.CFA -> PrID -> I.Expr
mkFairCFA cfa pid =
((mkPIDLVar I./== mkPIDEnum pid) `I.lor` (mkContLVar I.=== I.true)) `I.land`
(I.disj $ map (\loc -> mkPCEq cfa pid (mkPC pid loc) `I.land` (I.cfaLocWaitCond cfa loc))
$ filter (not . I.isDeadendLoc cfa)
$ I.cfaDelayLocs cfa)
----------------------------------------------------------------------
-- Explicit update functions
----------------------------------------------------------------------
--mkUpds :: I.Spec -> M.Map String [(I.Expr, I.Expr)]
--mkUpds spec = M.fromList $ []
--contUpd :: [(I.Expr, I.Expr)]
--contUpd = [ ( (I.neg mkContVar) `I.land` mkMagicVar , mkContLVar)
-- , ( I.neg ((I.neg mkContVar) `I.land` mkMagicVar), I.false)]
--epidUpd :: [(I.Expr, I.Expr)]
--epidUpd = [ (mkContLVar , I.EConst $ I.EnumVal $ mkEPIDEnumeratorName EPIDCont)
-- , (I.neg mkContLVar, mkEPIDLVar)]
----------------------------------------------------------------------
-- Init and goal conditions
----------------------------------------------------------------------
mkInit :: (?spec::Spec) => NameGen I.Transition
mkInit = do
-- conjunction of initial variable assignments
let ass = SSeq nopos Nothing
$ mapMaybe (\v -> case varInit $ gvarVar v of
Nothing -> Nothing
Just e -> Just $ SAssume (pos v) Nothing $ EBinOp (pos v) Eq (ETerm nopos $ [name v]) e) (tmVar tmMain)
-- add init blocks
cond = SAssume nopos Nothing $ eAnd nopos $ map initBody (tmInit tmMain)
mkCond "$init" (SSeq nopos Nothing [ass, cond]) []
-- $err == false
noerror :: I.Expr
noerror = I.EUnOp Not mkErrVar
mkGoal :: (?spec::Spec) => Goal -> NameGen I.Goal
mkGoal g = -- Add $err==false to the goal condition
(liftM $ I.Goal (sname g)) $ mkCond (sname g) (SAssume nopos Nothing $ goalCond g) [{-I.EUnOp Not mkMagicVar, noerror-}]
-- In addition to regular goals, we are required to be outside a magic block
-- infinitely often
mkMagicGoal :: (?spec::Spec) => NameGen I.Goal
mkMagicGoal = (liftM $ I.Goal "$magic_goal") $ mkCond "$magic_goal" (SAssume nopos Nothing $ EBool nopos True) [I.EUnOp Not mkMagicVar, noerror]
mkCond :: (?spec::Spec) => String -> Statement -> [I.Expr] -> NameGen I.Transition
mkCond descr s extra = do
-- simplify and convert into a statement
stat <- let ?scope = ScopeTemplate tmMain
in statSimplify s
let ctx = CFACtx { ctxEPID = Nothing
, ctxStack = [(ScopeTemplate tmMain, error $ "return from " ++ descr, Nothing, M.empty)]
, ctxCFA = I.newCFA (ScopeTemplate tmMain) stat I.true
, ctxBrkLocs = error "break outside a loop"
, ctxGNMap = globalNMap
, ctxLastVar = 0
, ctxVar = []
, ctxLabels = []}
ctx' = let ?procs = []
?nestedmb = False
?xducer = False
in execState (do aft <- procStatToCFA stat I.cfaInitLoc
ctxPause aft I.true I.ActNone) ctx
trans = map snd $ I.cfaLocTrans (ctxCFA ctx') I.cfaInitLoc
-- precondition
return $ case trans of
[t] -> let res = foldl' tranAppend (I.Transition (head $ I.cfaSource t) (head $ I.cfaSink t) t) (map I.SAssume extra)
in {-I.cfaTraceFile (I.tranCFA res) descr $-} res
_ -> error $ "mkCond " ++ show s ++ ": Invalid condition"
----------------------------------------------------------------------
-- Controllable transitions
----------------------------------------------------------------------
-- only allow controllable transitions in a controllable state
--contGuard = I.SAssume $ I.conj [mkContVar I.=== I.true]
--contGuard = I.SAssume $ I.conj $ [mkMagicVar I.=== I.true, mkContVar I.===
--I.true]
-- generate CFA that represents all possible controllable transitions
mkCTran :: (?spec::Spec) => (I.CFA, [I.Var])
mkCTran = I.cfaTraceFile (ctxCFA ctx' ) "cont_cfa" $ (ctxCFA ctx', ctxVar ctx')
where sc = ScopeTemplate tmMain
ctasks = filter ((== Task Controllable) . methCat) $ tmMethod tmMain
stats = SMagExit nopos Nothing :
SDoNothing nopos Nothing :
(map (\m -> SInvoke nopos Nothing (MethodRef nopos [name m])
$ map (\a -> if' (argDir a == ArgIn) (Just $ ENonDet nopos (Just $ Ident nopos $ mkArgTmpVarName m a)) Nothing) (methArg m))
ctasks)
stats' = map (\stat -> let ?scope = sc in evalState (statSimplify stat) (0,[])) stats
ctx = CFACtx { ctxEPID = Just EPIDCont
, ctxStack = [(sc, error "return from controllable transition", Nothing, M.empty)]
, ctxCFA = I.newCFA sc (SSeq nopos Nothing []) I.true
, ctxBrkLocs = []
, ctxGNMap = globalNMap
, ctxLastVar = 0
, ctxVar = []
, ctxLabels = []}
ctx' = let ?procs = []
?nestedmb = False
?xducer = False
in execState (mapM (\(t,s) -> do afttag <- ctxInsTrans' I.cfaInitLoc $ I.TranStat $ I.SAssume $ mkTagVar I.=== (I.EConst $ I.EnumVal t)
aftcont <- ctxInsTrans' afttag $ I.TranStat $ I.SAssume $ mkContLVar I.=== I.true
aftmag <- ctxInsTrans' aftcont $ I.TranStat $ I.SAssume $ mkMagicVar I.=== I.true
aftcall <- procStatToCFA s aftmag
ctxFinal aftcall)
$ zip mkTagList stats') ctx
----------------------------------------------------------------------
-- Variables
----------------------------------------------------------------------
mkVars :: (?spec::Spec) => [I.Var]
mkVars = mkErrVarDecl : mkContLVarDecl : mkMagicVarDecl : (wires ++ gvars ++ fvars ++ ivars ++ fpvars ++ pvars)
where
-- global variables
gvars = let ?scope = ScopeTemplate tmMain
in map (\v -> mkVarDecl (varMem $ gvarVar v) (NSID Nothing Nothing) (gvarVar v) (varType $ gvarVar v)) $ tmVar tmMain
-- wires
wires = let ?scope = ScopeTemplate tmMain
in map (\w -> mkVarDecl False (NSID Nothing Nothing) w (wireType w)) $ tmWire tmMain
-- functions, procedures, and controllable tasks
fvars = concatMap (methVars Nothing False)
$ filter ((flip elem) [Function, Procedure, Task Controllable] . methCat)
$ tmMethod tmMain
-- inlined uncontrollable and invisible tasks:
ivars = concatMap (concat . mapPTreeInlinedTask (\pid m -> methVars (Just pid) False m))
$ tmProcess tmMain
-- For each root process:
-- * local variables
pvars = concatMap (\p -> map (\v -> let ?scope = ScopeProcess tmMain p
in mkVarDecl (varMem v) (NSID (Just $ PrID (sname p) []) Nothing) v (varType v)) (procVar p))
$ tmProcess tmMain
-- For each forked process:
-- * enabling variable
fpvars = concatMap (mapPTreeFProc (\pid _ -> mkEnVarDecl pid Nothing))
$ tmProcess tmMain
methVars :: Maybe PrID -> Bool -> Method -> [I.Var]
methVars mpid ret m =
(let ?scope = ScopeMethod tmMain m in map (\v -> mkVarDecl (varMem v) (NSID mpid (Just m)) v (varType v)) (methVar m)) ++
(let ?scope = ScopeMethod tmMain m in map (\a -> mkVarDecl False (NSID mpid (Just m)) a (argType a)) (methArg m)) ++
(if ret then maybeToList (mkRetVarDecl mpid m) else [])
----------------------------------------------------------------------
-- Transducers
----------------------------------------------------------------------
specXducers2Internal :: Spec -> I.Spec
specXducers2Internal s =
let -- preprocessing
?spec = s in
let specEnum = mapMaybe (\d -> case tspec d of
EnumSpec _ es -> Just $ I.Enumeration (sname d) (map sname es)
_ -> Nothing) (specType ?spec)
specXducers = map xducerToIXducer $ specTransducer s
in I.Spec {..}
xducerToIXducer :: (?spec::Spec) => Transducer -> I.Transducer
xducerToIXducer x@(Transducer _ n is os b) = I.Transducer (sname n) is' os' b'
where is' = map (\i -> (mkType $ Type ScopeTop $ tpType i, sname i)) is
os' = map (\o -> (mkType $ Type ScopeTop $ tpType o, sname o)) os
sc = ScopeTransducer x
ctx stat = CFACtx { ctxEPID = Nothing
, ctxStack = [(sc, error "return from a transducer", Nothing, xducerLMap x)]
, ctxCFA = I.newCFA sc stat I.true
, ctxBrkLocs = error "break outside a loop"
, ctxGNMap = globalConstNMap
, ctxLastVar = 0
, ctxVar = []
, ctxLabels = []}
reftoiref :: TxPortRef -> I.TxPortRef
reftoiref (TxInputRef p) = I.TxInputRef $ sname p
reftoiref (TxLocalRef i p) = I.TxLocalRef (sname i) (sname p)
b' = case b of
Left (refs, insts) -> Left ( map reftoiref refs
, map (\i -> I.TxInstance (sname $ tiTxName i) (sname $ tiInstName i) (map (fmap reftoiref) $ tiInputs i)) insts)
Right st -> let ?procs = []
?nestedmb = False
?xducer = True in
let stvars = map (\v -> I.Var False I.VarState (sname v) (mkType $ Type sc $ tspec v)) $ stmtVar st
st' = let ?scope = sc in evalState (statSimplify st) (0,[])
cfa = ctxCFA $ execState (do aft <- procStatToCFA st' I.cfaInitLoc
ctxFinal aft) (ctx st')
in Right (cfa, stvars)
----------------------------------------------------------------------
-- CFA transformation
----------------------------------------------------------------------
-- Convert normal or forked process to CFA
procToCFA :: (?spec::Spec, ?procs::[I.Process]) => PrID -> NameMap -> Scope -> Statement -> (I.CFA, [I.Var])
procToCFA pid@(PrID _ ps) lmap parscope stat = {-I.cfaTraceFile (ctxCFA ctx') (show pid)-} (ctxCFA ctx', ctxVar ctx')
where -- top-level processes are not guarded
guarded = not $ null ps
guard = if guarded
then mkEnVar pid Nothing I.=== I.true
else I.true
-- Add process-local variables to nmap
ctx = CFACtx { ctxEPID = Just $ EPIDProc pid
, ctxStack = [(parscope, error "return from a process", Nothing, lmap)]
, ctxCFA = I.newCFA parscope stat guard
, ctxBrkLocs = error "break outside a loop"
, ctxGNMap = globalNMap
, ctxLastVar = 0
, ctxVar = []
, ctxLabels = []}
ctx' = execState (do aftguard <- if guarded
then ctxInsTrans' I.cfaInitLoc $ I.TranStat $ I.SAssume guard
else return I.cfaInitLoc
aft <- let ?nestedmb = False
?xducer = False in
procStatToCFA stat aftguard
_ <- ctxFinal aft
modify $ \c -> c {ctxCFA = cfaShortcut $ ctxCFA c}
ctxUContInsertSuffixes
ctxPruneUnreachable) ctx
-- Shortcut initial transition of the CFA if it does not do anything
cfaShortcut :: I.CFA -> I.CFA
cfaShortcut cfa = cfaShortcut' cfa I.cfaInitLoc
cfaShortcut' :: I.CFA -> I.Loc -> I.CFA
cfaShortcut' cfa l | (I.isDelayLabel $ fromJust $ G.lab cfa l) && (l /= I.cfaInitLoc) = graphUpdNode I.cfaInitLoc (\lab -> lab {I.locStack = I.stackSetLoc (I.locStack lab) I.cfaInitLoc})
$ graphChangeNodeID l I.cfaInitLoc
$ G.delNode I.cfaInitLoc cfa
| (length $ G.lsuc cfa l) /= 1 = cfa
| (snd $ head $ G.lsuc cfa l) /= I.TranNop = cfa
| otherwise = cfaShortcut' cfa $ head $ G.suc cfa l
-- Recursively construct CFA's for the process and its children
procToCProc :: (?spec::Spec) => Process -> (I.Process, [I.Var])
procToCProc p = fprocToCProc Nothing ((ScopeProcess tmMain p), (sname p, (procStatement p)))
fprocToCProc :: (?spec::Spec) => Maybe PrID -> (Scope, (String, Statement)) -> (I.Process, [I.Var])
fprocToCProc mparpid (sc, (n,stat)) = (I.Process{..}, pvs ++ concat cvs)
where lmap = scopeLMap mparpid sc
pid = maybe (PrID n []) (\parpid -> childPID parpid n) mparpid
procName = n
(procChildren, cvs) = unzip $ map (fprocToCProc $ Just pid) $ forkedProcsRec sc stat
(procCFA,pvs) = let ?procs = procChildren in procToCFA pid lmap sc stat
-- Map a function over all inlined invisible and uncontrollable tasks called by the process
mapPTreeInlinedTask :: (?spec::Spec) => (PrID -> Method -> a) -> Process -> [a]
mapPTreeInlinedTask f p = mapPTreeInlinedTask' f (PrID (sname p) []) (ScopeProcess tmMain p) (procStatement p)
mapPTreeInlinedTask' :: (?spec::Spec) => (PrID -> Method -> a) -> PrID -> Scope -> Statement -> [a]
mapPTreeInlinedTask' f pid sc stat =
(map (f pid)
$ filter (\m -> elem (methCat m) [Task Invisible, Task Uncontrollable])
$ procCallees sc stat)
++
(concatMap (\(sc',(n,st)) -> mapPTreeInlinedTask' f (childPID pid n) sc' st) $ forkedProcsRec sc stat)
-- Map a function over forked processes
mapPTreeFProc :: (?spec::Spec) => (PrID -> Statement -> a) -> Process -> [a]
mapPTreeFProc f p = mapPTreeFProc' f (PrID (sname p) []) (ScopeProcess tmMain p) (procStatement p)
mapPTreeFProc' :: (?spec::Spec) => (PrID -> Statement -> a) -> PrID -> Scope -> Statement -> [a]
mapPTreeFProc' f pid s stat =
case pid of
PrID _ [] -> []
_ -> [f pid stat]
++
(concatMap (\(s',(n,st)) -> mapPTreeFProc' f (childPID pid n) s' st) $ forkedProcsRec s stat)
-- Find all methods invoked by the statement in the context of the current process,
-- i.e., not inside fork blocks
procCallees :: (?spec::Spec) => Scope -> Statement -> [Method]
procCallees s stat =
map (\n -> snd $ getMethod s (MethodRef nopos [n]))
$ S.toList $ S.fromList $ map (name . snd . getMethod s) $ procCalleesRec s stat
procCallees' :: (?spec::Spec) => Scope -> Statement -> [MethodRef]
procCallees' s (SSeq _ _ ss) = concatMap (procCallees' s) ss
procCallees' s (SForever _ _ b) = procCallees' s b
procCallees' s (SDo _ _ b _) = procCallees' s b
procCallees' s (SWhile _ _ _ b) = procCallees' s b
procCallees' s (SFor _ _ (i,_,u) b) = (fromMaybe [] $ fmap (procCallees' s) i) ++ procCallees' s u ++ procCallees' s b
procCallees' s (SChoice _ _ ss) = concatMap (procCallees' s) ss
procCallees' _ (SInvoke _ _ mref _) = [mref]
procCallees' _ (SAssign _ _ _ (EApply _ mref _)) = [mref]
procCallees' s (SITE _ _ _ t me) = procCallees' s t ++ (fromMaybe [] $ fmap (procCallees' s) me)
procCallees' s (SCase _ _ _ cs md) = concatMap (\(_,st) -> procCallees' s st) cs ++
(fromMaybe [] $ fmap (procCallees' s) md)
procCallees' _ _ = []
procCalleesRec :: (?spec::Spec) => Scope -> Statement -> [MethodRef]
procCalleesRec s stat = ms1 ++ ms2
where ms1 = procCallees' s stat
ms2 = concatMap (procCalleesRec s . fromRight . methBody . snd . getMethod s) ms1
-- Find processes forked by the statement
forkedProcs :: (?spec::Spec) => Statement -> [(String, Statement)]
forkedProcs (SSeq _ _ ss) = concatMap forkedProcs ss
forkedProcs (SPar _ _ ps) = map (\st -> (sname $ fromJust $ stLab st, st)) ps
forkedProcs (SForever _ _ b) = forkedProcs b
forkedProcs (SDo _ _ b _) = forkedProcs b
forkedProcs (SWhile _ _ _ b) = forkedProcs b
forkedProcs (SFor _ _ (minit, _, i) b) = fromMaybe [] (fmap forkedProcs minit) ++ forkedProcs i ++ forkedProcs b
forkedProcs (SChoice _ _ ss) = concatMap forkedProcs ss
forkedProcs (SITE _ _ _ t me) = forkedProcs t ++ fromMaybe [] (fmap forkedProcs me)
forkedProcs (SCase _ _ _ cs mdef) = concatMap (forkedProcs . snd) cs ++
fromMaybe [] (fmap forkedProcs mdef)
forkedProcs _ = []
-- Recurse over task invocations
forkedProcsRec :: (?spec::Spec) => Scope -> Statement -> [(Scope, (String, Statement))]
forkedProcsRec s stat =
(map (s,) $ forkedProcs stat) ++
(concatMap (\m -> map (ScopeMethod tmMain m,) $ forkedProcs $ fromRight $ methBody m) (procCallees s stat))
---------------------------------------------------------------
-- CFA to LTS transformation
---------------------------------------------------------------
--cfaToITransition :: I.CFA -> String -> I.Transition
--cfaToITransition cfa fname = case trans of
-- [t] -> {-I.cfaTraceFile (I.tranCFA t) fname $-} t
-- _ -> error $ "cfaToITransition: Invalid CFA:\n" ++ (intercalate "\n\n" $ map show trans)
-- where trans = locTrans cfa I.cfaInitLoc
-- Convert CFA to a list of transitions.
-- Assume that unreachable states have already been pruned.
cfaToITransitions :: EPID -> I.CFA -> [I.Transition]
cfaToITransitions epid cfa = {-I.cfaTraceFileMany (map I.tranCFA trans') ("tran_" ++ show epid)-} trans'
where
-- compute a set of transitions for each location labelled with pause or final
states = I.cfaDelayLocs cfa
trans = concatMap (I.cfaLocTrans cfa) states
trans' = map (extractTransition epid cfa . snd) trans
-- Extract transition into a separate CFA
extractTransition :: EPID -> I.CFA -> I.CFA -> I.Transition
extractTransition epid cfa tcfa =
let from = head $ I.cfaSource tcfa
to = head $ I.cfaSink tcfa
in case epid of
EPIDCont -> I.Transition from to tcfa
EPIDProc pid -> -- check PC value before the transition
let (cfa2, befpc) = I.cfaInsLoc (I.LInst I.ActNone) tcfa
cfa3 = I.cfaInsTrans befpc from (I.TranStat $ I.SAssume $ mkPCEq cfa pid (mkPC pid from)) cfa2
in I.Transition befpc to cfa3
tranAppend :: I.Transition -> I.Statement -> I.Transition
tranAppend (I.Transition from to cfa) s = I.Transition from to' cfa'
where (cfa', to') = I.cfaInsTrans' to (I.TranStat s) cfa
| termite2/tsl | Frontend/SpecInline.hs | bsd-3-clause | 31,321 | 0 | 27 | 10,156 | 8,575 | 4,526 | 4,049 | 403 | 3 |
{-# LANGUAGE KindSignatures, PolyKinds, MultiParamTypeClasses, FunctionalDependencies, ConstraintKinds, NoImplicitPrelude, TypeFamilies, TypeOperators, FlexibleContexts, FlexibleInstances, UndecidableInstances, UndecidableSuperClasses, RankNTypes, GADTs, ScopedTypeVariables, DataKinds, AllowAmbiguousTypes, LambdaCase, DefaultSignatures, EmptyCase #-}
module Hask.Tensor
(
-- * Tensors
Semitensor(..), I, Tensor'(..), Tensor, semitensorClosed
-- * Monoids
, Semigroup(..), Monoid'(..), Monoid
-- * Comonoids (Opmonoids)
, Cosemigroup(..), Comonoid'(..), Comonoid
) where
import Hask.Category
import Hask.Iso
import Data.Void
--------------------------------------------------------------------------------
-- * Monoidal Tensors and Monoids
--------------------------------------------------------------------------------
class (Bifunctor p, Dom p ~ Dom2 p, Dom p ~ Cod2 p) => Semitensor p where
associate :: (Ob (Dom p) a, Ob (Dom p) b, Ob (Dom p) c, Ob (Dom p) a', Ob (Dom p) b', Ob (Dom p) c')
=> Iso (Dom p) (Dom p) (->)
(p (p a b) c) (p (p a' b') c')
(p a (p b c)) (p a' (p b' c'))
semitensorClosed :: forall c t x y. (Semitensor t, Category c, Dom t ~ c, Ob c x, Ob c y) => Dict (Ob c (t x y))
semitensorClosed = case ob :: Ob c x :- FunctorOf c c (t x) of
Sub Dict -> case ob :: Ob c y :- Ob c (t x y) of
Sub Dict -> Dict
type family I (p :: i -> i -> i) :: i
class Semitensor p => Tensor' p where
lambda :: (Ob (Dom p) a, Ob (Dom p) a') => Iso (Dom p) (Dom p) (->) (p (I p) a) (p (I p) a') a a'
rho :: (Ob (Dom p) a, Ob (Dom p) a') => Iso (Dom p) (Dom p) (->) (p a (I p)) (p a' (I p)) a a'
class (Monoid' p (I p), Tensor' p) => Tensor p
instance (Monoid' p (I p), Tensor' p) => Tensor p
class Semitensor p => Semigroup p m where
mu :: Dom p (p m m) m
class (Semigroup p m, Tensor' p) => Monoid' p m where
eta :: NatId p -> Dom p (I p) m
class (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Monoid' p m) => Monoid p m
instance (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Monoid' p m) => Monoid p m
class Semitensor p => Cosemigroup p w where
delta :: Dom p w (p w w)
class (Cosemigroup p w, Tensor' p) => Comonoid' p w where
epsilon :: NatId p -> Dom p w (I p)
class (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Comonoid' p w) => Comonoid p w
instance (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Comonoid' p w) => Comonoid p w
--------------------------------------------------------------------------------
-- * (&)
--------------------------------------------------------------------------------
class (p, q) => p & q
instance (p, q) => p & q
instance Functor (&) where
type Dom (&) = (:-)
type Cod (&) = Nat (:-) (:-)
fmap f = Nat $ Sub $ Dict \\ f
instance Functor ((&) a) where
type Dom ((&) a) = (:-)
type Cod ((&) a) = (:-)
fmap f = Sub $ Dict \\ f
instance Semitensor (&) where
associate = dimap (Sub Dict) (Sub Dict)
type instance I (&) = (() :: Constraint)
instance Tensor' (&) where
lambda = dimap (Sub Dict) (Sub Dict)
rho = dimap (Sub Dict) (Sub Dict)
instance Semigroup (&) a where
mu = Sub Dict
instance Monoid' (&) (() :: Constraint) where
eta _ = Sub Dict
instance Cosemigroup (&) a where
delta = Sub Dict
instance Comonoid' (&) a where
epsilon _ = Sub Dict
--------------------------------------------------------------------------------
-- * (,) and ()
--------------------------------------------------------------------------------
instance Semitensor (,) where
associate = dimap (\((a,b),c) -> (a,(b,c))) (\(a,(b,c)) -> ((a,b),c))
type instance I (,) = ()
instance Tensor' (,) where
lambda = dimap (\ ~(_,a) -> a) ((,)())
rho = dimap (\ ~(a,_) -> a) (\a -> (a,()))
instance Semigroup (,) () where
mu ((),()) = ()
instance Monoid' (,) () where
eta _ = id
instance Cosemigroup (,) a where
delta a = (a,a)
instance Comonoid' (,) a where
epsilon _ _ = ()
--------------------------------------------------------------------------------
-- * Either and Void
--------------------------------------------------------------------------------
instance Semitensor Either where
associate = dimap hither yon where
hither (Left (Left a)) = Left a
hither (Left (Right b)) = Right (Left b)
hither (Right c) = Right (Right c)
yon (Left a) = Left (Left a)
yon (Right (Left b)) = Left (Right b)
yon (Right (Right c)) = Right c
type instance I Either = Void
instance Tensor' Either where
lambda = dimap (\(Right a) -> a) Right
rho = dimap (\(Left a) -> a) Left
instance Semigroup (,) Void where
mu (a,_) = a
instance Semigroup Either Void where
mu (Left a) = a
mu (Right b) = b
instance Monoid' Either Void where
eta _ = absurd
instance Cosemigroup Either Void where
delta = absurd
instance Comonoid' Either Void where
epsilon _ = id
| ekmett/hask | src/Hask/Tensor.hs | bsd-3-clause | 4,904 | 2 | 12 | 1,054 | 2,195 | 1,163 | 1,032 | -1 | -1 |
module Handler.Home where
--import Import
--import Yesod.Form.Bootstrap3 (BootstrapFormLayout (..), renderBootstrap3,
-- withSmallInput)
-- This is a handler function for the GET request method on the HomeR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
--getHomeR :: Handler Html
--getHomeR = do
-- (formWidget, formEnctype) <- generateFormPost sampleForm
-- let submission = Nothing :: Maybe (FileInfo, Text)
-- handlerName = "getHomeR" :: Text
-- defaultLayout $ do
-- aDomId <- newIdent
-- setTitle "Welcome To Yesod!"
-- $(widgetFile "homepage")
-- $(fayFile "Home")
--
--postHomeR :: Handler Html
--postHomeR = do
-- ((result, formWidget), formEnctype) <- runFormPost sampleForm
-- let handlerName = "postHomeR" :: Text
-- submission = case result of
-- FormSuccess res -> Just res
-- _ -> Nothing
--
-- defaultLayout $ do
-- aDomId <- newIdent
-- setTitle "Welcome To Yesod!"
-- $(widgetFile "homepage")
--
--sampleForm :: Form (FileInfo, Text)
--sampleForm = renderBootstrap3 BootstrapBasicForm $ (,)
-- <$> fileAFormReq "Choose a file"
-- <*> areq textField (withSmallInput "What's on the file?") Nothing
| lubomir/dot-race | Handler/Home.hs | bsd-3-clause | 1,487 | 0 | 3 | 346 | 44 | 42 | 2 | 1 | 0 |
module Diffbot.FrontPage where
import Data.Maybe
import Diffbot.Types
-- | Takes in a multifaceted \"homepage\" and returns individual page
-- elements.
data FrontPage = FrontPage
{ frontPageAll :: Bool
-- ^ Returns all content from page, including navigation and
-- similar links that the Diffbot visual processing engine
-- considers less important/non-core.
, frontPageContent :: Maybe Content
, frontPageTimeout :: Maybe Int
-- ^ Specify a value in milliseconds to override the default API
-- timeout of 5000ms.
}
instance Post FrontPage where
content = frontPageContent
setContent c f = f { frontPageContent = c }
instance Timeout FrontPage where
timeout = frontPageTimeout
setTimeout t f = f { frontPageTimeout = t }
instance Request FrontPage where
toReq r = Req { reqApi = "http://www.diffbot.com/api/frontpage"
, reqContent = content r
, reqQuery = mkFrontPageQuery r
}
mkFrontPageQuery :: FrontPage -> [(String, Maybe String)]
mkFrontPageQuery f = catMaybes [ mkQueryBool "all" (frontPageAll f)
, mkQuery "format" (Just "json")
, timeoutQuery f
]
defFrontPage :: FrontPage
defFrontPage = FrontPage { frontPageAll = False
, frontPageContent = Nothing
, frontPageTimeout = Nothing
}
| tymmym/diffbot | src/Diffbot/FrontPage.hs | bsd-3-clause | 1,516 | 0 | 9 | 504 | 256 | 146 | 110 | 25 | 1 |
module EveTypes (
module EveTypes.Blueprints
) where
import EveTypes.Blueprints
| Frefreak/Gideon | src/EveTypes.hs | bsd-3-clause | 89 | 0 | 5 | 18 | 17 | 11 | 6 | 3 | 0 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2014 Edward Kmett and Gabríel Arthúr Pétursson
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : portable
--
----------------------------------------------------------------------------
module Graphics.GL.Types (
-- * Types
-- ** Function Types
GLDEBUGPROC
, GLDEBUGPROCAMD
, GLDEBUGPROCARB
, GLDEBUGPROCKHR
, mkGLDEBUGPROC
, mkGLDEBUGPROCAMD
, mkGLDEBUGPROCARB
, mkGLDEBUGPROCKHR
-- ** Common Types
, GLbitfield
, GLboolean
, GLbyte
, GLchar
, GLcharARB
, GLclampd
, GLclampf
, GLclampx
, GLdouble
, GLeglImageOES
, GLenum
, GLfixed
, GLfloat
, GLhalf
, GLhalfARB
, GLhalfNV
, GLhandleARB
, GLint
, GLint64
, GLint64EXT
, GLintptr
, GLintptrARB
, GLshort
, GLsizei
, GLsizeiptr
, GLsizeiptrARB
, GLsync
, GLubyte
, GLuint
, GLuint64
, GLuint64EXT
, GLushort
, GLvdpauSurfaceNV
) where
import Data.Int
import Data.Word
import Foreign.C.Types
import Foreign.Ptr
import Numeric.Fixed
import Numeric.Half
type GLDEBUGPROC =
FunPtr (GLenum
-> GLenum
-> GLuint
-> GLenum
-> GLsizei
-> Ptr GLchar
-> Ptr ()
-> IO ())
type GLDEBUGPROCAMD =
FunPtr (GLuint
-> GLenum
-> GLenum
-> GLsizei
-> Ptr GLchar
-> Ptr ()
-> IO ())
type GLDEBUGPROCARB =
FunPtr (GLenum
-> GLenum
-> GLuint
-> GLenum
-> GLsizei
-> Ptr GLchar
-> Ptr ()
-> IO ())
type GLDEBUGPROCKHR =
FunPtr (GLenum
-> GLenum
-> GLuint
-> GLenum
-> GLsizei
-> Ptr GLchar
-> Ptr ()
-> IO ())
-- | The storage associated with the resulting 'FunPtr' has to be released with
-- 'freeHaskellFunPtr' when it is no longer required.
foreign import CALLCONV "wrapper"
mkGLDEBUGPROC :: (GLenum -> GLenum -> GLuint -> GLenum -> GLsizei -> Ptr GLchar -> Ptr () -> IO ()) -> IO GLDEBUGPROC
-- | The storage associated with the resulting 'FunPtr' has to be released with
-- 'freeHaskellFunPtr' when it is no longer required.
foreign import CALLCONV "wrapper"
mkGLDEBUGPROCAMD :: (GLuint -> GLenum -> GLenum -> GLsizei -> Ptr GLchar -> Ptr () -> IO ()) -> IO GLDEBUGPROCAMD
-- | The storage associated with the resulting 'FunPtr' has to be released with
-- 'freeHaskellFunPtr' when it is no longer required.
foreign import CALLCONV "wrapper"
mkGLDEBUGPROCARB :: (GLenum -> GLenum -> GLuint -> GLenum -> GLsizei -> Ptr GLchar -> Ptr () -> IO ()) -> IO GLDEBUGPROCARB
-- | The storage associated with the resulting 'FunPtr' has to be released with
-- 'freeHaskellFunPtr' when it is no longer required.
foreign import CALLCONV "wrapper"
mkGLDEBUGPROCKHR :: (GLenum -> GLenum -> GLuint -> GLenum -> GLsizei -> Ptr GLchar -> Ptr () -> IO ()) -> IO GLDEBUGPROCKHR
type GLbitfield = Word32
type GLboolean = Word8
type GLbyte = Int8
type GLchar = CChar
type GLcharARB = CChar
type GLclampd = Double
type GLclampf = Float
type GLclampx = Int32
type GLdouble = Double
type GLeglImageOES = Ptr ()
type GLenum = Word32
type GLfixed = Fixed
type GLfloat = Float
type GLhalf = Half
type GLhalfARB = Half
type GLhalfNV = Half
type GLint = Int32
type GLint64 = Int64
type GLint64EXT = Int64
type GLintptr = CPtrdiff
type GLintptrARB = CPtrdiff
type GLshort = Int16
type GLsizei = Int32
type GLsizeiptr = CPtrdiff
type GLsizeiptrARB = CPtrdiff
type GLsync = Ptr ()
type GLubyte = Word8
type GLuint = Word32
type GLuint64 = Word64
type GLuint64EXT = Word64
type GLushort = Word16
type GLvdpauSurfaceNV = CPtrdiff
#if __APPLE__
type GLhandleARB = Ptr ()
#else
type GLhandleARB = Word32
#endif
| phaazon/gl | src/Graphics/GL/Types.hs | bsd-3-clause | 4,086 | 42 | 16 | 1,140 | 923 | 493 | 430 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
module Sync.Local.Hashing where
import Control.Monad.Trans
import qualified Data.ByteString.Lazy as BL
import Data.Maybe
import System.IO
import Text.ProtocolBuffers
import Sync.Hashing
import Sync.Internal.Types
import Sync.Internal.IO
import Sync.Internal.Protocol
import Sync.Protocol
-- | Get weak (\"rolling\") hashes for each block and send them over the stream
sendRollingHashes
:: MonadResourceBase m
=> FileTransferInfo
-> NetApp m ()
sendRollingHashes fi = do
bs <- liftIO $ BL.readFile fp
sendList $ toRollingBlocks s bs
where
fp = toString $ ft_filename fi
s = fromIntegral $ ft_blocksize fi
-- | Compare local file with incoming hashes, send out unmatched file
-- locations and return matched file locations as lookup list
getMatchingMD5s
:: MonadResourceBase m
=> FileTransferInfo
-> NetApp m [HashingMatch MD5]
getMatchingMD5s fi = do
h <- withBinaryFile' fp ReadMode
md5s <- receiveList $ toMsg'
matches <- mapM (compareMD5 h) md5s
return $ catMaybes matches
where
fp = toString $ ft_filename fi
| mcmaniac/sync | src/Sync/Local/Hashing.hs | bsd-3-clause | 1,194 | 0 | 10 | 296 | 254 | 133 | 121 | 31 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
module Main where
import Control.Concurrent (threadDelay)
import Control.Monad (when, forever)
import Data.ByteString (unpack)
import Data.ByteString.Base32 (decode)
import Data.ByteString.Char8 (pack)
import Data.Monoid
import Data.OTP
import Data.Time
import Options.Applicative
data Opts = Opts
{ optsIsAsci :: Bool
, optsLength :: Int
, optsInterval :: Int
, optsLoop :: Bool
, optsSecret :: String
}
parseOpts :: Parser Opts
parseOpts =
Opts <$>
flag
False
True
(long "ascii" <> showDefault <>
help
"treat the secret key as plain text, rather than base32-encoded string (default: false)") <*>
option
auto
(long "length" <> showDefault <> metavar "length" <>
help "the length of password/token to generate" <>
value 6) <*>
option
auto
(long "interval" <> showDefault <> metavar "interval" <>
help "refresh interval" <>
value 30) <*>
flag False True (long "loop" <> showDefault <> help "") <*>
strOption
(long "secret" <> showDefault <> metavar "secret" <> help "secret key")
main :: IO ()
main = do
opts <- execParser (info (helper <*> parseOpts) (fullDesc <> mempty))
generatePassword opts
generatePassword :: Opts -> IO ()
generatePassword opts = do
let secret = pack $ optsSecret opts
let decoder =
if optsIsAsci opts
then Right
else decode
case decoder secret of
Right s -> do
let bytes = unpack s
time <- getCurrentTime
putStrLn . padZeros (optsLength opts) $
totp bytes time (optsLength opts) (optsInterval opts)
when (optsLoop opts) $ do
threadDelay (optsInterval opts * 1000000)
generatePassword opts
return ()
Left e -> do
print e
return ()
padZeros :: Int -> Int -> String
padZeros len num =
let s = show num
in replicate (len - length s) '0' ++ s
| pbogdan/otp-auth | src/Main.hs | bsd-3-clause | 1,933 | 0 | 18 | 487 | 615 | 303 | 312 | 68 | 3 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- TODO:
-- XXX on error in thread, kill everything.
-- XXX prove each assertion only once?
-- Dependence on timeout. Not clear how to remove it, since Haskell doesn't
-- have a good mechanism to guarantee killing an external process.
-- | Parses the (standard) output CBMC and prints to standard out for each
-- function: It's location, did it succeed or fail. Filepaths must be relative
-- to the curent directory.
module Main
where
import ParseXML
import CmdLine
import ParseSrcs
import Prelude hiding (init)
import System.Exit
import System.Process
import System.Environment
import System.FilePath
import System.Directory
import Data.List hiding (sort, init)
import Data.Maybe
import Control.Monad
import Data.Monoid hiding (All)
import Control.Concurrent
import Control.Concurrent.MSem
import qualified Spreadsheet as S
import qualified Spreadsheet.Renderer as S
import qualified Spreadsheet.Sorting as S
import qualified MonadLib as M
--import Text.Show.Pretty
--import Debug.Trace
--------------------------------------------------------------------------------
-- Environment/execution
-- How we want to use CBMC.
data Output = ReachableClaims -- Shows just reachable claims from the entry point.
| ShowClaims -- Shows every claim in the all the sources.
| Run -- Run the model-checker.
deriving (Eq, Show, Read)
instance PShow Output where
pshow ReachableClaims = "--cover-assertions"
pshow ShowClaims = "--show-claims"
pshow Run = "analyzing claims"
-- Error messages and entry functions causing errors.
newtype Error = Error { errMsgs :: [String] }
deriving (Show, Read, Eq)
instance Monoid Error where
mempty = Error []
-- Errors probably shouln't get too big, so concatentation is efficient
-- enough.
(Error a) `mappend` (Error b) = Error (a ++ b)
--------------------------------------------------------------------------------
-- CBMC Monad and functions.
newtype CBMC a = CBMC { unCBMC :: M.WriterT Error IO a }
deriving Monad
insertErr :: String -> CBMC ()
insertErr err = CBMC (M.put $ Error [err])
maybeInsertErr :: Maybe Error -> CBMC ()
maybeInsertErr = maybe (return ()) (CBMC . M.put)
liftIO :: IO a -> CBMC a
liftIO io = CBMC $ M.inBase io
putStrLnM :: String -> CBMC ()
putStrLnM = liftIO . putStrLn
--------------------------------------------------------------------------------
-- Misc type synonyms
-- Error, the function, and the output.
type ChanData = (Maybe Error, Func, String)
type FuncsCoverage = (Func, [ClaimName])
--------------------------------------------------------------------------------
main :: IO ()
main = do
args <- getArgs
case parseArgs args of
Left errs -> ioError (userError $ unlines $ errs ++ [myUsageInfo])
Right opts
| help opts -> putStrLn myUsageInfo
| otherwise -> do
sources <- mapM makeRelativeToCurrentDirectory (srcs opts)
let headers = map ("-I"++) (incls opts)
functions <- case function opts of
[] -> extractSrcs sources headers
fs -> return fs
let opts' = opts { cbmcOpts = cbmcOpts opts ++ headers ++ sources
, function = functions
}
(claims, Error errs) <- M.runWriterT (unCBMC $ run opts')
putStrLn " Generating spreadsheet ..."
let spreadsheet | format opts' == ASCII
= S.renderSpreadsheet (spreadSheetize opts' claims)
| otherwise -- format opts' == Markdown
= S.renderSmd (spreadSheetize opts' claims)
maybe ( putStrLn $ allOut spreadsheet claims errs )
( \f -> putStrLn ("Attempting to write to " ++ show f ++ " ...")
>> createDirectoryIfMissing True (takeDirectory f)
>> writeFile f (allOut spreadsheet claims errs)
>> putStrLn "Done!"
)
( outfile opts' )
where
allOut ss clms errs = unlines
$ "Claims Table"
: "------------"
: ["", ss]
++ ["", totals (cnt clms), ""]
++ if null errs then [] else [outErrs errs]
cnt = partition id . map claimVal
totals (true,false) =
"Analyzed " ++ show (length true) ++ " true " ++ claimStr true
++ " and " ++ show (length false) ++ " false "
++ claimStr false ++ "."
where claimStr xs = if length xs == 1 then "claim" else "claims"
outErrs :: [String] -> String
outErrs errs = unlines $ "************"
: "Warnings"
: "--------"
: map ("\n * "++) errs
-- Main driver function.
run :: Opts -> CBMC [Claim]
run opts@Opts {cbmc, function} = do
cbmc' <- liftIO $ do f <- doesFileExist cbmc
ex <- getExec "cbmc"
return $ if f then cbmc else ex
timeout <- liftIO $ getExec "timeout"
let opts' = opts {cbmc = cbmc', toExec = timeout}
-- Find the functions that get all reachable claims. XXX This algorithm just
-- iterates over functions and does not not compute a maximum vertex cycle
-- cover.
putStrLnM " Getting all reachable claims ..."
-- Minimal number of functions to cover all claims.
entriesAndClaims <-
spawnCBMC opts' ReachableClaims allReaches function []
let minEntriesAndClaims =
case coverage opts' of
All -> entriesAndClaims -- We prove starting from each function here.
Min -> minCoverageSet entriesAndClaims
-- The only reason we need to run ShowClaims for analysis is because in the
-- --xml-ui output of CBMC, for --cover-assertions, the line/file/function
-- info isn't given, even though it's given in the non --xml-ui output. We
-- don't have to run this from a particular entry point, but CBMC requires
-- *some* existing entry point (note the entry point doesn't even have to be
-- analyzable (i.e., while(1) loop is fine). *However*, we do use the results
-- of this to provide the user with warnings about missed claims in the source
-- files.
allClaims <-
spawnCBMC opts' ShowClaims collectClaims (take 1 function) []
reachableClaims <- keepReachableClaims allClaims minEntriesAndClaims
-- Should contain no duplicates by default.
let funcsMin = map fst minEntriesAndClaims
putStrLnM " Analyzing claims ..."
results <- spawnCBMC opts' Run collectResults funcsMin reachableClaims
return $ nubResults results
where
-- Remove duplicated claims (from different starting functions), prioritizing
-- false claims over true.
nubResults reses = go [] reses
where
go clms [] = clms
go clms rst@( Claim{ claimFile = cf0, claimFunc = cc0
, claimLine = cl0 }
: _
)
= go (getMaybeFalse : clms) nos
where
-- yeses can't be empty, by construction.
(yes,nos) = partition (\Claim{ claimFile = cf1, claimFunc = cc1
, claimLine = cl1 } ->
cf0 == cf1 && cc0 == cc1 && cl0 == cl1
) rst
getMaybeFalse :: Claim
getMaybeFalse = fromMaybe (head yes) (find (not . claimVal) yes)
--------------------------------------------------------------------------------
spawnCBMC :: Opts
-> Output
-> (MSem Integer -> Chan ChanData -> [a] -> Int -> CBMC [a])
-> [Func]
-> [a]
-> CBMC [a]
spawnCBMC opts outFormat folder funcs init = do
chan <- liftIO newChan
sem <- liftIO $ new (threads opts)
forM_ funcs (spawnThread sem chan)
foldM (folder sem chan) init [1..length funcs]
where
spawnThread :: MSem Integer -> Chan ChanData -> Func -> CBMC ThreadId
spawnThread sem chan func = do
putStrLnM $ " Spawning thread: "
++ pshow outFormat ++ " from function "
++ func ++ " ... "
liftIO $ forkIO $ runCBMC sem chan outFormat opts func
--------------------------------------------------------------------------------
-- Initalized with all possible claims.
collectResults :: MSem Integer
-> Chan ChanData
-> [Claim]
-> Int
-> CBMC [Claim]
collectResults sem chan claims _ = do
(merr, func, output) <- liftIO (readChan chan)
liftIO $ signal sem
maybeInsertErr merr
let parsedRes = parseResXML output
reses <- errNoParse [(func, parsedRes)]
return $ map (markFailure func reses) claims
markFailure :: Func -> [Result Failure] -> Claim -> Claim
markFailure entry reses c@Claim{claimFile, claimFunc, claimLine, claimEntry} =
maybe c (const c {claimVal = False}) (find go reses)
where
go :: Result Failure -> Bool
go res =
case res of
Succeeded -> False
Failed Failure {failFile , failFunc , failLine} ->
claimEntry == entry
&& claimFile == failFile
&& claimFunc == failFunc
&& claimLine == failLine
--------------------------------------------------------------------------------
-- | Get location info for all reachable claims.
collectClaims :: MSem Integer -> Chan ChanData -> [Claim] -> Int -> CBMC [Claim]
collectClaims sem chan claims _ = do
(merr, func, output) <- liftIO (readChan chan)
liftIO $ signal sem
maybeInsertErr merr
let parsedClaims = parseClaimsXML output
let claimsWithFunc = zip (repeat func) parsedClaims
assert <- errNoParse claimsWithFunc
return $ assert ++ claims
--------------------------------------------------------------------------------
allReaches :: MSem Integer
-> Chan ChanData
-> [FuncsCoverage]
-> Int
-> CBMC [FuncsCoverage]
allReaches sem chan claims _ = do
(merr, func, output) <- liftIO (readChan chan)
liftIO $ signal sem
asserts <- errNoParse $ zip (repeat func) (parseReachableXML output)
-- Don't insert the function if we got an error processing it.
return $ if isJust merr then claims else (func, asserts) : claims
--------------------------------------------------------------------------------
-- Running CBMC.
-- Entry point to call CBMC.
runCBMC :: MSem Integer -> Chan ChanData -> Output -> Opts -> Func -> IO ()
runCBMC sem chan outputType opts func = do
wait sem
(merr, output) <- getCBMCOutPut opts func outputType
writeChan chan (merr, func, output)
-- Actually call out to CBMC.
getCBMCOutPut :: Opts -> Func -> Output -> IO (Maybe Error, String)
getCBMCOutPut opts@Opts {cbmc} func outputType = do
-- No stderr output is given with XML mode.
(exitCode,stdout,_) <- runIt allArgs
processOut exitCode stdout
where
args = "--function":func:out
allArgs = "--xml-ui" : args ++ cbmcOpts opts
errArgs = args ++ cbmcOpts opts
-- Timeout processes as necessary using timeout (GNU tool).
duration = show (timeout opts) ++ "s"
timeoutArgs args' = ("--kill-after=" ++ duration) : duration : cbmc : args'
-- Actually call CBMC.
runIt args' = readProcessWithExitCode (toExec opts) (timeoutArgs args') ""
processOut exitCode stdout
-- Timeout killed the process.
| exitCode == ExitFailure 124 -- 124 is the timeout exit code.
|| exitCode == ExitFailure 9 -- Hard kill.
= return ( Just $ Error ["timeout: cbmc with args: " ++ unwords args]
, stdout
)
-- Were there processing errors?
| parseErrMsgsXML stdout
-- Run the command again to get the error message, and throw a fatal error.
= do putStrLn "*** Fatal CBMC error encountered!"
putStrLn "*** (Rebuilding error ...)\n"
(_,_,errout) <- runIt errArgs
putStrLn $ " Error: " ++ errout
error "\n*** Ending run."
| otherwise
= return (Nothing, stdout)
out = case outputType of
ShowClaims -> [pshow ShowClaims]
ReachableClaims -> [pshow ReachableClaims]
Run -> []
--------------------------------------------------------------------------------
-- Helpers
errNoParse :: [(Func, Maybe a)]-> CBMC [a]
errNoParse = foldM go []
where
go acc (func,result)
| Just res <- result = return (res:acc)
| otherwise = do insertErr $ "Can't parse output from func: "
++ func
return acc
getExec :: FilePath -> IO FilePath
getExec exec = do
mfp <- findExecutable exec
return $ fromMaybe (error $ "executable \""
++ exec ++ "\" does not exist!")
mfp
--------------------------------------------------------------------------------
-- Analyzing claims
-- | Greedy algorithm implementing the minimum coverage set
-- <http://en.wikipedia.org/wiki/Set_cover_problem>. Returns the minimal number
-- of entry-point functions covering all reachable claims.
minCoverageSet :: [FuncsCoverage] -> [FuncsCoverage]
minCoverageSet = minCoverageSet' []
where
minCoverageSet' :: [FuncsCoverage] -> [FuncsCoverage] -> [FuncsCoverage]
minCoverageSet' minSet ls =
case ls of
[] -> minSet
_ -> let minClms = nub $ concatMap snd minSet in
let m = findMaxUncovered minClms ls in
let go fc = minCoverageSet' (fc:minSet) (delete fc ls) in
-- if m is Nothing, we've covered the set.
maybe minSet go m
-- return the max uncovered.
findMaxUncovered :: [ClaimName] -> [FuncsCoverage] -> Maybe FuncsCoverage
findMaxUncovered minSet candidates =
case zipped of
[] -> Nothing
_ -> let (diff, cand) = maximumBy go zipped in
if diff <= 0 then Nothing else Just cand
where
go a b = compare (fst a) (fst b)
diffs = map (diffCoveredClaim . snd) candidates
zipped = zip diffs candidates
-- How many elements in ls that aren't in minSet.
diffCoveredClaim :: [ClaimName] -> Int
diffCoveredClaim candidate = length $ candidate \\ minSet
eqClaim :: Claim -> Claim -> Bool
eqClaim c0 c1 = claimName c0 == claimName c1
eqClaimFailure :: Failure -> Claim -> Bool
eqClaimFailure
Failure { failFile, failFunc, failLine }
Claim { claimFile, claimFunc, claimLine }
= claimFile == failFile && claimFunc == failFunc && claimLine == failLine
-- Get the meta data for reachable claims from the all-claims pass as well as
-- insert errors if there is an unreachable claim. Also, put the entry function
-- inside the claim data.
keepReachableClaims :: [Claim] -> [FuncsCoverage] -> CBMC [Claim]
keepReachableClaims allClaims reachables = foldM go [] allClaims
where
reachableWEntries :: [(Func, ClaimName)]
reachableWEntries = concatMap (\(f, cns) -> zip (repeat f) cns) reachables
go :: [Claim] -> Claim -> CBMC [Claim]
go reachableClaims allClaim =
case withEntry of
[] -> withErr
_ -> insertClms withEntry
where
reses :: [(Func, ClaimName)]
reses = filter (\(_,cn) -> claimName allClaim == cn)
reachableWEntries
-- Make a new claim for each possibly entry.
withEntry :: [Claim]
withEntry = map (\(f,_) -> allClaim {claimEntry = f}) reses
insertClms we = return $ we ++ reachableClaims
withErr = do insertErr $ "Did not cover claim "
++ " in file " ++ claimFile allClaim
++ " in function " ++ claimFunc allClaim
++ " at line " ++ show (claimLine allClaim)
return reachableClaims
--------------------------------------------------------------------------------
-- | Prettyprint report
spreadSheetize :: Opts -> [Claim] -> S.Spreadsheet
spreadSheetize Opts {sort, asserts} claims
= S.sortSpreadsheet $ S.Spreadsheet columns (transpose cellValues)
where
so = Just S.Ascending
fileCol = S.Column "File" S.StringT so
funcCol = S.Column "Function" S.StringT so
lineCol = S.Column "Line" (S.NumberT Nothing) so
resCol = S.Column "Result" S.StringT so
entCol = S.Column "Entry" S.StringT so
astCol = S.Column "Expr" S.StringT so
initCol = case sort of
File -> (fileCol, fileVals)
Func -> (funcCol, funcVals)
Line -> (lineCol, lineVals)
Result -> (resCol , resVals)
Entry -> (entCol , entVals)
cols = [fileCol, funcCol, lineCol, resCol, entCol]
vals = [fileVals, funcVals, lineVals, resVals, entVals]
(columns, cellValues) =
unzip $ nub (initCol : zip cols vals)
++ if asserts then [(astCol, astVals)] else []
fileVals = map (S.StringV . claimFile) claims
funcVals = map (S.StringV . claimFunc) claims
lineVals = map (S.NumberV . fromIntegral . claimLine) claims
resVals = map (S.StringV . show . claimVal) claims
entVals = map (S.StringV . claimEntry) claims
astVals = map (S.StringV . claimExpr) claims
--------------------------------------------------------------------------------
| VCTLabs/cbmc-reporter | src/Report.hs | bsd-3-clause | 17,278 | 0 | 23 | 4,655 | 4,278 | 2,216 | 2,062 | 305 | 6 |
{-# LANGUAGE ScopedTypeVariables #-}
module Astro.Coords.TNRSpec where
import Test.Hspec
import Test.QuickCheck
import Data.AEq
import TestUtil
import TestInstances
import Astrodynamics (greenwichRA)
import Astro.Coords
import Astro.Coords.ECR
import Astro.Coords.TNR
import Astro.Coords.PosVel
import Astro.Time -- (UT1, E, addTime)
import Astro.Time.At
import Astro.Util (perfectGEO, perfectGEO')
import Numeric.Units.Dimensional.Prelude
import Numeric.Units.Dimensional.LinearAlgebra
import Numeric.Units.Dimensional.LinearAlgebra.PosVel (Car)
import qualified Prelude
main = hspec spec
spec = do
spec_trivialSV
spec_trivialRetroSV
spec_eciToECR
spec_ecrToECIPV
spec_eciToECRPV
-- ----------------------------------------------------------
spec_trivialSV = describe "A trivial state vector" $ do
it "gives a correct orbital (TNR) frame" $
orbitalFrame pv == _Y |: _Z |:. _X
it "gives a correct attiude (RPY) frame" $
attitudeCoordSys pv ~== _Y |: negateVec _Z |:. negateVec _X
where
r = scaleVec ((1::Double) *~ meter) _X :: Car DLength Double
v = scaleVec (1 *~ (meter / second)) _Y
pv = C' r v
spec_trivialRetroSV = describe "A trivial retrograde state vector" $ do
it "gives a correct orbital (TNR) frame" $
orbitalFrame pv == negateVec _Y |: negateVec _Z |:. _X
it "gives a correct attiude (RPY) frame" $
attitudeCoordSys pv ~== negateVec _Y |: _Z |:. negateVec _X
where
r = scaleVec ((1::Double) *~ meter) _X
v = scaleVec (1 *~ (meter / second)) _Y
pv = C' r (negateVec v)
-- ----------------------------------------------------------
spec_eciToECR = describe "eciToECR" $ do
it "is the inverse of ecrToECI"
(property $ \(p::Coord ECI D) t ->
(ecrToECI t . eciToECR t) p ~== p)
-- ----------------------------------------------------------
spec_ecrToECIPV = describe "ecrToECIPV" $ do
it "is identical to ecrToECI for the position"
(property $ \(pv::PosVel ECR D) t ->
--Comparison of cartesian coords fails due to numerics.
(s . pos . ecrToECIPV t) pv ~== (s . ecrToECI t . pos) pv)
it "is the inverse of eciToECRPV"
(property $ \(pv::PosVel ECR D) t ->
(eciToECRPV t . ecrToECIPV t) pv ~== pv)
-- ----------------------------------------------------------
spec_eciToECRPV = describe "eciToECRPV" $ do
it "is identical to eciToECR for the position"
(property $ \(pv::PosVel ECI D) t ->
--Comparison of cartesian coords fails due to numerics.
(s . pos . eciToECRPV t) pv ~== (s . eciToECR t . pos) pv)
it "is the inverse of ecrToECIPV"
(property $ \(pv::PosVel ECI D) t ->
(ecrToECIPV t . eciToECRPV t) pv ~== pv)
-- {-
p = (-0.5653349232735853::D) *~ meter <: (-5.133004275272132) *~meter <:. (-7.22445929855348) *~ meter
t = clock' 1858 11 24 20 10 15.151878680541
pv = C' p (_0 <: _0 <:. _0)
-- -}
| bjornbm/astro | test/Astro/Coords/TNRSpec.hs | bsd-3-clause | 2,869 | 0 | 17 | 559 | 850 | 440 | 410 | 63 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Forml.Optimize.Inline (inline_apply, Inlines, Inline, Inlineable(..)) where
import System.IO.Unsafe ()
import Prelude hiding (curry)
import GHC.Generics
import qualified Data.Map as M
import Data.Serialize
import Language.Javascript.JMacro
import Forml.Parser.Utils
import Forml.Types.Axiom
import Forml.Types.Definition
import Forml.Types.Expression
import Forml.Types.Namespace hiding (Module)
import Forml.Types.Pattern
import Forml.Types.Symbol
data Inlineable = InlineSymbol Symbol | InlineRecord (Expression Definition) deriving (Eq, Generic, Show)
type Inlines = [((Namespace, Inlineable), (Match (Expression Definition), Expression Definition))]
type Inline = [(Inlineable, (Match (Expression Definition), Expression Definition))]
instance Serialize Inlineable
afmap ::
[(String, Expression Definition)] ->
(Symbol -> Expression Definition) ->
Axiom (Expression Definition) ->
Axiom (Expression Definition)
afmap d f (EqualityAxiom (Match pss cond) expr) =
EqualityAxiom (Match pss (fmap (replace_expr d f) cond)) (fmap (replace_expr d f) expr)
afmap _ _ t = t
dfmap d f (Definition a b c as) =
Definition a b c (fmap (afmap d f) as)
replace_expr d f (ApplyExpression a b) =
ApplyExpression (replace_expr d f a) (replace_expr d f `map` b)
replace_expr d f (IfExpression a b Nothing) =
IfExpression (replace_expr d f a) (replace_expr d f b) Nothing
replace_expr d f (IfExpression a b (Just c)) =
IfExpression (replace_expr d f a) (replace_expr d f b) (Just (replace_expr d f c))
replace_expr d f (LiteralExpression x) =
LiteralExpression x
replace_expr d f (JSExpression j) =
JSExpression (replace_jexpr d j)
replace_expr d f (LazyExpression a b) =
LazyExpression (fmap (replace_expr d f) a) b
replace_expr d f (FunctionExpression as) =
FunctionExpression (map (afmap d f) as)
replace_expr d f (RecordExpression vs) =
RecordExpression (fmap (replace_expr d f) vs)
replace_expr d f (LetExpression ds e) =
LetExpression (dfmap d f `map` ds) (replace_expr d f e)
replace_expr d f (ListExpression xs) =
ListExpression (map (replace_expr d f) xs)
replace_expr d f (AccessorExpression a ss) =
AccessorExpression (fmap (replace_expr d f) a) ss
replace_expr d f (SymbolExpression (Symbol s)) = f (Symbol s)
replace_expr d f (SymbolExpression s) = SymbolExpression s
replace_expr _ _ s = s
replace_stat dict (ReturnStat x) = ReturnStat (replace_jexpr dict x)
replace_stat dict (IfStat a b c) = IfStat (replace_jexpr dict a) (replace_stat dict b) (replace_stat dict c)
replace_stat dict (WhileStat a b c) = WhileStat a (replace_jexpr dict b) (replace_stat dict c)
replace_stat dict (ForInStat a b c d) = ForInStat a b (replace_jexpr dict c) (replace_stat dict d)
replace_stat dict (SwitchStat a b c) = SwitchStat (replace_jexpr dict a) b (replace_stat dict c)
replace_stat dict (TryStat a b c d) = TryStat (replace_stat dict a) b (replace_stat dict c) (replace_stat dict d)
replace_stat dict (BlockStat xs) = BlockStat (replace_stat dict `map` xs)
replace_stat dict (ApplStat a b) = ApplStat (replace_jexpr dict a) (replace_jexpr dict `map` b)
replace_stat dict (PPostStat a b c) = PPostStat a b (replace_jexpr dict c)
replace_stat dict (AssignStat a b) = AssignStat (replace_jexpr dict a) (replace_jexpr dict b)
replace_stat dict (UnsatBlock a) = UnsatBlock (replace_stat dict `fmap` a)
replace_stat dict (DeclStat v t) = DeclStat v t
replace_stat dict (UnsatBlock ident_supply) = UnsatBlock (replace_stat dict `fmap` ident_supply)
replace_stat dict (AntiStat s) = AntiStat s
replace_stat dict (ForeignStat s t) = ForeignStat s t
replace_stat dict (BreakStat s) = (BreakStat s)
replace_jval dict (JList xs) = JList (replace_jexpr dict `map` xs)
replace_jval dict (JHash m) = JHash (M.map (replace_jexpr dict) m)
replace_jval dict (JFunc xs x) = JFunc xs (replace_stat dict x)
replace_jval dict (UnsatVal x) = UnsatVal (replace_jval dict `fmap` x)
replace_jval dict x@(JDouble _) = x
replace_jval dict x@(JInt _) = x
replace_jval dict x@(JStr _) = x
replace_jval dict x@(JRegEx _) = x
replace_jval dict (JVar (StrI y)) =
case y `lookup` dict of
Just y' -> JVar . StrI . show . jsToDoc . toJExpr $ y'
Nothing -> JVar (StrI y)
replace_jval _ (JVar x) = JVar x
replace_jexpr dict (SelExpr e (StrI i)) = IdxExpr (replace_jexpr dict e) (ValExpr (JStr i)) -- Closure fix - advanced mode nukes these
replace_jexpr dict (IdxExpr a b) = IdxExpr (replace_jexpr dict a) (replace_jexpr dict b)
replace_jexpr dict (InfixExpr a b c) = InfixExpr a (replace_jexpr dict b) (replace_jexpr dict c)
replace_jexpr dict (PPostExpr a b c) = PPostExpr a b (replace_jexpr dict c)
replace_jexpr dict (IfExpr a b c) = IfExpr (replace_jexpr dict a) (replace_jexpr dict b) (replace_jexpr dict c)
replace_jexpr dict (NewExpr a) = NewExpr (replace_jexpr dict a)
replace_jexpr dict (ApplExpr a b) = ApplExpr (replace_jexpr dict a) (replace_jexpr dict `map` b)
replace_jexpr dict (TypeExpr a b c) = TypeExpr a (replace_jexpr dict b) c
replace_jexpr dict (ValExpr a) = ValExpr (replace_jval dict a)
replace_jexpr dict (UnsatExpr a) = UnsatExpr (replace_jexpr dict `fmap` a)
inline_apply ::
[Pattern t] -> -- Function being inlined's patterns
[Expression Definition] -> -- Arguments to this function
[Expression Definition] -> -- Optimized arguments to this functions
Expression Definition -> -- Expression of the funciton being inline
Expression Definition -- Resulting inlined expression
inline_apply pss args opt_args ex = do
replace_expr (concat $ zipWith gen_expr pss opt_args) (gen_exprs args pss) ex
where
gen_exprs args' pats (Symbol s) =
case s `lookup` (concat $ zipWith gen_expr pats args') of
Just ex -> ex
Nothing -> (SymbolExpression (Symbol s))
gen_exprs _ _ s = SymbolExpression s
gen_expr (VarPattern x) y =
[(x, y)]
gen_expr (RecordPattern xs _) y =
concat $ zipWith gen_expr (M.elems xs) (map (to_accessor y) $ M.keys xs)
gen_expr (ListPattern xs) y =
concat $ zipWith gen_expr xs (map (to_array y) [0..])
gen_expr (AliasPattern xs) y =
concatMap (flip gen_expr y) xs
gen_expr _ _ =
[]
to_array expr idx =
JSExpression [jmacroE| `(expr)`[idx] |]
to_accessor expr sym =
AccessorExpression (Addr undefined undefined expr) [sym] | texodus/forml | src/hs/lib/Forml/Optimize/Inline.hs | bsd-3-clause | 7,358 | 0 | 13 | 1,714 | 2,600 | 1,327 | 1,273 | 134 | 7 |
{-|
Unit tests module for the longest path algorithm. Checks that the
following properties hold true for randomly generated DAGs:
* The only DAG in in which the longest path is empty is the DAG
of order 0.
* If the longest path is not empty, then the first vertex has
no predecessors and the last no successors in the graph.
-}
module Test.LongestPath (testLongestPath) where
import Test.ArbitraryInstances
import LongestPath
import GraphUtils
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
-- | Test group aggregating all tests in this module.
testLongestPath :: Test
testLongestPath = testGroup "LongestPath.longestPath"
[testProperty
"The longest path is only empty when given an empty DAG"
pEmptyPath,
testProperty
"The first and last vertex of the longest path are a source and sink respectively"
pFirstLastSourceSink]
-- | Checks that the algorithm returns an empty path iff the graph
-- is of order 0 (ie it has no vertices and no edges).
pEmptyPath :: DAG -> Bool
pEmptyPath (DAG graph) =
let
actualLongestPath = longestPath graph
isGraphEmpty = order graph == 0
isLongestPathEmpty = actualLongestPath == [] in
(if isGraphEmpty then isLongestPathEmpty else True) &&
(if isLongestPathEmpty then isGraphEmpty else True)
-- | Checks that the first vertex in the longest path is
-- a source vertex (it has no incoming edges) and that the
-- last vertex in the longest path is a sink vertex (it has
-- no outgoing edges).
pFirstLastSourceSink :: DAG -> Bool
pFirstLastSourceSink (DAG graph) =
let actualLongestPath = longestPath graph in
if null actualLongestPath
then True
else
isSource graph (head actualLongestPath)
&& isSink graph (last actualLongestPath)
-- | A vertex is a source iff it has no predecessors.
isSource :: Graph -> Vertex -> Bool
isSource graph vertex =
null $ predecessors graph vertex
-- | A vertex is a sink iff it has no successors
isSink :: Graph -> Vertex -> Bool
isSink graph vertex =
null $ successors graph vertex
| alexisVallet/ag44-graph-algorithms | Test/LongestPath.hs | bsd-3-clause | 2,059 | 0 | 11 | 388 | 304 | 165 | 139 | 36 | 3 |
module Graphics.UI.SDL
( module Init
, module Exception
, module Types
, module Audio
, module Timer
, module Events
, module Video
, module Version
) where
import Graphics.UI.SDL.Init as Init
import Graphics.UI.SDL.Exception as Exception
import Graphics.UI.SDL.Types as Types
import Graphics.UI.SDL.Audio as Audio
import Graphics.UI.SDL.Timer as Timer
import Graphics.UI.SDL.Events as Events
import Graphics.UI.SDL.Video as Video
import Graphics.UI.SDL.Version as Version
| abbradar/MySDL | src/Graphics/UI/SDL.hs | bsd-3-clause | 537 | 0 | 4 | 124 | 113 | 86 | 27 | 17 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE FlexibleContexts #-}
-- | Symbolic links
module Haskus.System.Linux.FileSystem.SymLink
( sysSymlink
, ReadSymLinkErrors
, readSymbolicLink
)
where
import Haskus.System.Linux.Error
import Haskus.System.Linux.ErrorCode
import Haskus.System.Linux.Handle
import Haskus.System.Linux.Syscalls
import Haskus.Format.String
import Haskus.Format.Binary.Storable
import Haskus.Utils.Flow
type ReadSymLinkErrors
= '[ NotAllowed
, NotSymbolicLink
, FileSystemIOError
, SymbolicLinkLoop
, TooLongPathName
, FileNotFound
, OutOfKernelMemory
, InvalidPathComponent
]
-- | Read the path in a symbolic link
readSymbolicLink :: MonadInIO m => Maybe Handle -> FilePath -> FlowT ReadSymLinkErrors m String
readSymbolicLink hdl path = do
sysReadLinkAt hdl path
`catchLiftLeft` \case
EACCES -> throwE NotAllowed
EINVAL -> throwE NotSymbolicLink
EIO -> throwE FileSystemIOError
ELOOP -> throwE SymbolicLinkLoop
ENAMETOOLONG -> throwE TooLongPathName
ENOENT -> throwE FileNotFound
ENOMEM -> throwE OutOfKernelMemory
ENOTDIR -> throwE InvalidPathComponent
EBADF -> error "readSymbolicLink: invalid handle"
-- EFAULT: shouldn't happen (or is a haskus-system bug)
e -> unhdlErr "readSymbolicLink" e
-- | Wrapper for readlinkat syscall
sysReadLinkAt :: MonadInIO m => Maybe Handle -> FilePath -> FlowT '[ErrorCode] m String
sysReadLinkAt hdl path = tryReadLinkAt 2048
where
-- if no handle is passed, we assume the path is absolute and we give a
-- (-1) file descriptor which should be ignored. If the path is relative,
-- hopefully we will get a EBADF error
fd = case hdl of
Just (Handle x) -> x
Nothing -> maxBound
-- allocate a buffer and try to readlinkat.
tryReadLinkAt size = do
mv <- allocaBytes size $ \ptr ->
withCString path $ \path' -> do
n <- checkErrorCode =<< liftIO (syscall_readlinkat fd path' ptr (fromIntegral size))
if fromIntegral n == size
then return Nothing
else Just <$> peekCStringLen (fromIntegral n) ptr
case mv of
Nothing -> tryReadLinkAt (2*size) -- retry with double buffer size
Just v -> return v
-- | Create a symbolic link
sysSymlink :: MonadInIO m => FilePath -> FilePath -> FlowT '[ErrorCode] m ()
sysSymlink src dest =
withCString src $ \src' ->
withCString dest $ \dest' ->
checkErrorCode_ =<< liftIO (syscall_symlink src' dest')
| hsyl20/ViperVM | haskus-system/src/lib/Haskus/System/Linux/FileSystem/SymLink.hs | bsd-3-clause | 2,883 | 0 | 22 | 824 | 568 | 299 | 269 | 60 | 10 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
module Stanag.EoIrLaserOperatingState where
import Ivory.Language
import Stanag.Packing
import Util.Logger
eoIrLaserOperatingStateInstance :: MemArea (Stored Uint32)
eoIrLaserOperatingStateInstance = area "eoIrLaserOperatingStateInstance" (Just (ival 0))
[ivoryFile|Stanag/EoIrLaserOperatingState.ivory|]
| GaloisInc/loi | Stanag/EoIrLaserOperatingState.hs | bsd-3-clause | 465 | 0 | 9 | 46 | 69 | 41 | 28 | 12 | 1 |
module Homework8.Employee where
import Data.Tree
-- Employee names are represented by Strings.
type Name = String
-- The amount of fun an employee would have at the party, represented
-- by an Integer
type Fun = Integer
-- An Employee consists of a name and a fun score.
data Employee = Emp { empName :: Name, empFun :: Fun }
deriving (Show, Read, Eq)
-- A small company hierarchy to use for testing purposes.
testCompany :: Tree Employee
testCompany
= Node (Emp "Stan" 9)
[ Node (Emp "Bob" 2)
[ Node (Emp "Joe" 5)
[ Node (Emp "John" 1) []
, Node (Emp "Sue" 5) []
]
, Node (Emp "Fred" 3) []
]
, Node (Emp "Sarah" 17)
[ Node (Emp "Sam" 4) []
]
]
testCompany2 :: Tree Employee
testCompany2
= Node (Emp "Stan" 9)
[ Node (Emp "Bob" 3) -- (8, 8)
[ Node (Emp "Joe" 5) -- (5, 6)
[ Node (Emp "John" 1) [] -- (1, 0)
, Node (Emp "Sue" 5) [] -- (5, 0)
]
, Node (Emp "Fred" 3) [] -- (3, 0)
]
, Node (Emp "Sarah" 17) -- (17, 4)
[ Node (Emp "Sam" 4) [] -- (4, 0)
]
]
-- A type to store a list of guests and their total fun score.
data GuestList = GL [Employee] Fun
deriving (Eq)
instance Ord GuestList where
compare (GL _ f1) (GL _ f2) = compare f1 f2
instance Show GuestList where
show (GL xs f) = "Total fun: " ++ show f ++ "\n" ++ (concat $ map ((++"\n") .empName) xs)
| gabluc/CIS194-Solutions | src/Homework8/Employee.hs | bsd-3-clause | 1,411 | 1 | 13 | 415 | 487 | 258 | 229 | 32 | 1 |
{-# -fglasgow-exts #-}
module DNS.Type (question, rquestion,
putLine, enc, Bufi, Data,
Question(Q), MayIO,
RR(RR), RClass, RType,
Name, satisfies, Zone(..), MayIOSt,
Packet(..), converge, WState, PSt,
errorPacket, emptyPacket, hashQuestion
) where
import Data.Char
import Data.Int (Int32)
import Data.Bits(shiftR)
import Data.Word
import Foreign.Ptr
import Control.Monad.Error
import Control.Monad.State
import Data.Array.Unboxed
type MayIO = ErrorT String IO
type MayIOSt s = StateT s MayIO
type WState = ((), Bufi, Ptr Word8)
type PSt = StateT (Ptr Word8) IO
putLine :: String -> MayIO ()
putLine s = liftIO $ putStrLn s
-- Questions
type Data = UArray Int Word8
data Question = Q !Name !QType !QClass
instance Eq Question where
(==) (Q an at ac) (Q bn bt _) = an == bn && at `teq` bt && ac `teq` bt
teq :: Word16 -> Word16 -> Bool
teq 255 _ = True
teq _ 255 = True
teq x y = x == y
satisfies :: Question -> RR -> Bool
satisfies (Q n t c) (RR rn rt rc _ _) = n == rn && (rt == 5 || t == 255 || t == rt) && c `teq` rc
type QType = Word16
type QClass= Word16
type QId = Word16
type Bufi = (Ptr Word8, Int)
question :: String -> QType -> QClass -> Question
question a b c = Q (enc a) b c
rquestion a b c = Q a b c
hashQuestion :: Question -> Int32
hashQuestion (Q n t _) = fromIntegral $ fromEnum t + foldl fun 0 lst
where lst = take 10 $ drop 4 $ elems n
fun a e = fromEnum e + (a `shiftR` 7)
instance Show Question where
show (Q qs qt qc) = "Question: '"++qd qs++"' type="++show qt++" class="++show qc
-- FIXME add safety checks for chunk < 64 and total < 256
enc :: String -> UArray Int Word8
enc s = let lst = enc' s in listArray (0,length lst - 1) lst
enc' s = concatMap (\p -> fromIntegral (length p) : map (fromIntegral . ord) p) $ reverse splitted
where ein ("",a) '.' = ("",a)
ein (c,a) '.' = ("",reverse c : a)
ein (c,a) ch = (ch:c,a)
norm l@("":_) = l
norm lst = "":lst
splitted = let (t,r) = foldl ein ("",[]) s in norm $ reverse t : r
qd = qd' . elems
qd' :: [Word8] -> String
qd' [] = ""
qd' (n:ns) = let h = map (chr . fromEnum) $ take (fromEnum n) ns
t = drop (fromEnum n) ns
in if length t <= 1 then h else h ++ '.':qd' t
-- RRs
type RType = Word16
type RClass= Word16
data RR = RR Name RType RClass Word32 Data
instance Show RR where
show (RR n t c ts d) = unwords ["RR",qd n,show t,show c,show ts,show d]
-- Zones
data Zone = Zone Name [RR] deriving(Show)
type Name = UArray Int Word8
-- Packets
data Packet = Packet { idPQ :: !Word16,
hePQ :: !Word16,
qsPQ :: ![Question],
rsPQ :: ![RR],
nsPQ :: ![RR],
asPQ :: ![RR]
} deriving(Show)
emptyPacket = Packet 0 0 [] [] [] []
errorPacket = emptyPacket { hePQ = 33155 }
related :: Question -> RR -> RR -> Bool
related (Q _ qt qc) (RR _ 5 _ _ ca) (RR rn rt rc _ _) = elems ca == elems rn && qt `teq` rt && qc `teq` rc
related _ _ _ = False
converge :: Word16 -> Question -> Packet -> Packet
converge id q p = let rrs = rsPQ p ++ asPQ p
sat = filter (satisfies q) rrs
-- rel = filter (\rr -> any (\i -> related q i rr) sat) rrs
in Packet id (hePQ p) [q] rrs [] []
| creswick/hsntp | DNS/Type.hs | bsd-3-clause | 3,243 | 42 | 14 | 847 | 1,560 | 836 | 724 | 104 | 4 |
module CreateEnv
( createEnv
) where
import Fragnix.Environment (
persistEnvironment)
import Fragnix.Paths (
builtinEnvironmentPath,cbitsPath,includePath)
import Language.Haskell.Exts (
Module,parseFileContentsWithMode,defaultParseMode,ParseMode(..),baseFixities,
ParseResult(ParseOk,ParseFailed),
SrcSpan,srcInfoSpan,SrcLoc(SrcLoc),
Extension(EnableExtension),KnownExtension(..),
ModuleName(ModuleName), Name(Ident))
import Language.Haskell.Names (
resolve, Environment, Symbol(Value, symbolModule, Data, Constructor))
import qualified Data.Map as Map (
empty, adjust)
import Data.List (isSuffixOf)
import System.Directory (
listDirectory, doesFileExist, copyFile, createDirectoryIfMissing)
import System.FilePath ((</>), takeFileName)
import Control.Monad (
forM, forM_, filterM)
createEnv :: IO ()
createEnv = do
createCbits
createInclude
createPackageEnv
-- | Return a list of all files of a given directory
getDirFiles :: FilePath -> IO [FilePath]
getDirFiles fp = do
filesAndDirs <- map (fp </>) <$> listDirectory fp
filterM doesFileExist filesAndDirs
-- Include the correct cbits in the fragnix folder
-- | Return a list of all the files ending in "*.c" in builtins/cbits/
getCFiles :: IO [FilePath]
getCFiles = do
files <- getDirFiles ("builtins" </> "cbits")
return $ takeFileName <$> (filter (isSuffixOf ".c") files)
createCbits :: IO ()
createCbits = do
putStrLn "Initializing .fragnix/cbits ..."
cfiles <- getCFiles
createDirectoryIfMissing True cbitsPath
forM_ cfiles $ \file -> do
putStrLn $ " Copying " ++ file ++ "..."
copyFile ("builtins" </> "cbits" </> file) (cbitsPath </> file)
return ()
-- Include the correct includes in the fragnix folder
-- | Return a list of all the files ending in "*.h" in builtins/include/
getHFiles :: IO [FilePath]
getHFiles = do
files <- getDirFiles ("builtins" </> "include")
return $ takeFileName <$> (filter (isSuffixOf ".h") files)
createInclude :: IO ()
createInclude = do
putStrLn "Initializing .fragnix/include ..."
hfiles <- getHFiles
createDirectoryIfMissing True includePath
forM_ hfiles $ \file -> do
putStrLn $ " Copying " ++ file ++ "..."
copyFile ("builtins" </> "include" </> file) (includePath </> file)
return ()
-- Include the correct Builtin environment
createPackageEnv :: IO ()
createPackageEnv = do
putStrLn "Initializing builtin environment ..."
baseFiles <- listDirectory "builtins/base/" >>= return . Prelude.map ("builtins/base/" ++)
ghcPrimFiles <- listDirectory "builtins/ghc-prim/" >>= return . Prelude.map ("builtins/ghc-prim/" ++)
integerGmpFiles <- listDirectory "builtins/integer-gmp/" >>= return . Prelude.map ("builtins/integer-gmp/" ++)
baseModules <- forM baseFiles parse
ghcPrimModules <- forM ghcPrimFiles parse
integerGmpModules <- forM integerGmpFiles parse
let builtinEnvironment = resolve (baseModules ++ ghcPrimModules ++ integerGmpModules) Map.empty
patchedBuiltinEnvironment = patchBuiltinEnvironment builtinEnvironment
persistEnvironment builtinEnvironmentPath patchedBuiltinEnvironment
parse :: FilePath -> IO (Module SrcSpan)
parse path = do
fileContents <- readFile path
let parseMode = defaultParseMode {
parseFilename = path,
extensions = globalExtensions,
fixities = Just baseFixities}
parseresult = parseFileContentsWithMode parseMode fileContents
case parseresult of
ParseOk ast -> return (fmap srcInfoSpan ast)
ParseFailed (SrcLoc filename line column) message -> error (unlines [
"failed to parse module.",
"filename: " ++ filename,
"line: " ++ show line,
"column: " ++ show column,
"error: " ++ message])
globalExtensions :: [Extension]
globalExtensions = [
EnableExtension MultiParamTypeClasses,
EnableExtension NondecreasingIndentation,
EnableExtension ExplicitForAll,
EnableExtension PatternGuards,
EnableExtension ExplicitNamespaces,
EnableExtension FlexibleContexts,
EnableExtension DataKinds,
EnableExtension KindSignatures,
EnableExtension PolyKinds]
-- | The environment we get needs two changes:
-- 1. We have to add 'realWorld#' to "GHC.Base"
-- 2. We have to rewrite the origin of names exported in several modules
-- The reason is that the origin is hidden
patchBuiltinEnvironment :: Environment -> Environment
patchBuiltinEnvironment =
rewriteFloat .
rewriteDataTypeable .
rewriteLazyST .
rewriteForeignPtr .
rewriteGHCIntegerType .
rewriteInteger .
rewriteBigNat .
rewriteDataList .
addRealWorld
addRealWorld :: Environment -> Environment
addRealWorld = Map.adjust (++ [realWorldSymbol]) ghcBaseModuleName where
ghcBaseModuleName = ModuleName () "GHC.Base"
realWorldSymbol = Value ghcBaseModuleName (Ident () "realWorld#")
rewriteSymbolModuleInModules :: String -> String -> [String] -> Environment -> Environment
rewriteSymbolModuleInModules fromModuleName toModuleName inModules =
foldr (.) id (map (Map.adjust (map rewriteSymbol) . ModuleName ()) inModules) where
rewriteSymbol symbol = if symbolModule symbol == ModuleName () fromModuleName
then symbol { symbolModule = ModuleName () toModuleName }
else symbol
rewriteDataList :: Environment -> Environment
rewriteDataList = rewriteSymbolModuleInModules "Data.OldList" "Data.List" ["Data.List","Prelude","Data.String"]
rewriteGHCIntegerType :: Environment -> Environment
rewriteGHCIntegerType = rewriteSymbolModuleInModules "GHC.Integer.Type" "GHC.Integer" ["Prelude", "GHC.Num", "GHC.Integer"]
rewriteForeignPtr :: Environment -> Environment
rewriteForeignPtr = rewriteSymbolModuleInModules "Foreign.ForeignPtr.Imp" "Foreign.ForeignPtr" ["Foreign", "Foreign.ForeignPtr", "Foreign.Safe", "Foreign.ForeignPtr.Safe"]
rewriteLazyST :: Environment -> Environment
rewriteLazyST = rewriteSymbolModuleInModules "Control.Monad.ST.Lazy.Imp" "Control.Monad.ST.Lazy" ["Control.Monad.ST.Lazy", "Control.Monad.ST.Lazy.Safe", "Control.Monad.ST.Lazy.Unsafe"]
rewriteDataTypeable :: Environment -> Environment
rewriteDataTypeable = rewriteSymbolModuleInModules "Data.Typeable.Internal" "Data.Typeable" ["Data.Typeable", "Data.Dynamic", "Data.Data"]
rewriteSymbolInModules :: Symbol -> Symbol -> [String] -> Environment -> Environment
rewriteSymbolInModules fromSymbol toSymbol inModules =
foldr (.) id (map (Map.adjust (map rewriteSymbol) . ModuleName ()) inModules) where
rewriteSymbol symbol = if symbol == fromSymbol
then toSymbol
else symbol
rewriteFloat :: Environment -> Environment
rewriteFloat = foldr (.) id [
rewriteSymbolInModules
(Data (ModuleName () "GHC.Types") (Ident () "Double"))
(Data (ModuleName () "GHC.Float") (Ident () "Double"))
["Prelude", "GHC.Exts"],
rewriteSymbolInModules
(Constructor (ModuleName () "GHC.Types") (Ident () "D#") (Ident () "Double"))
(Constructor (ModuleName () "GHC.Float") (Ident () "D#") (Ident () "Double"))
["Prelude", "GHC.Exts"],
rewriteSymbolInModules
(Data (ModuleName () "GHC.Types") (Ident () "Float"))
(Data (ModuleName () "GHC.Float") (Ident () "Float"))
["Prelude", "GHC.Exts"],
rewriteSymbolInModules
(Constructor (ModuleName () "GHC.Types") (Ident () "F#") (Ident () "Float"))
(Constructor (ModuleName () "GHC.Float") (Ident () "F#") (Ident () "Float"))
["Prelude", "GHC.Exts"]]
-- | It is important that this comes before 'rewriteGHCIntegerType'
rewriteBigNat :: Environment -> Environment
rewriteBigNat = foldr (.) id [
rewriteSymbolInModules
(Data (ModuleName () "GHC.Integer.Type") (Ident () "BigNat"))
(Data (ModuleName () "GHC.Integer.GMP.Internals") (Ident () "BigNat"))
["GHC.Integer.GMP.Internals"],
rewriteSymbolInModules
(Constructor (ModuleName () "GHC.Integer.Type") (Ident () "BN#") (Ident () "BigNat"))
(Constructor (ModuleName () "GHC.Integer.GMP.Internals") (Ident () "BN#") (Ident () "BigNat"))
["GHC.Natural", "GHC.Integer.GMP.Internals"]]
-- | It is important that this comes before 'rewriteGHCIntegerType'
rewriteInteger :: Environment -> Environment
rewriteInteger = foldr (.) id [
rewriteSymbolInModules
(Data (ModuleName () "GHC.Integer.Type") (Ident () "Integer"))
(Data (ModuleName () "GHC.Integer.GMP.Internals") (Ident () "Integer"))
["Prelude", "GHC.Num", "GHC.Integer", "GHC.Integer.GMP.Internals"],
rewriteSymbolInModules
(Constructor (ModuleName () "GHC.Integer.Type") (Ident () "S#") (Ident () "Integer"))
(Constructor (ModuleName () "GHC.Integer.GMP.Internals") (Ident () "S#") (Ident () "Integer"))
["Prelude", "GHC.Num", "GHC.Integer", "GHC.Integer.GMP.Internals"],
rewriteSymbolInModules
(Constructor (ModuleName () "GHC.Integer.Type") (Ident () "Jp#") (Ident () "Integer"))
(Constructor (ModuleName () "GHC.Integer.GMP.Internals") (Ident () "Jp#") (Ident () "Integer"))
["Prelude", "GHC.Num", "GHC.Integer", "GHC.Integer.GMP.Internals"],
rewriteSymbolInModules
(Constructor (ModuleName () "GHC.Integer.Type") (Ident () "Jn#") (Ident () "Integer"))
(Constructor (ModuleName () "GHC.Integer.GMP.Internals") (Ident () "Jn#") (Ident () "Integer"))
["Prelude", "GHC.Num", "GHC.Integer", "GHC.Integer.GMP.Internals"]]
| phischu/fragnix | app/CreateEnv.hs | bsd-3-clause | 9,308 | 5 | 16 | 1,504 | 2,475 | 1,298 | 1,177 | 179 | 2 |
import Control.Monad
import Data.Maybe
import Data.Functor
import Text.XkbCommon
import Common
xor :: Bool -> Bool -> Bool
xor x y = (x || y) && not (x && y)
testFile :: Context -> String -> Bool -> IO ()
testFile ctx path shouldwork = do
str <- readFile (datadir++path)
let keymap = newKeymapFromString ctx str
assert (shouldwork `xor` isNothing keymap) "file load failure"
main = do
ctx <- getTestContext
mapM_ (\ path -> testFile ctx path True) [
"keymaps/basic.xkb",
"keymaps/comprehensive-plus-geom.xkb",
"keymaps/no-types.xkb"]
mapM_ (\ path -> testFile ctx path False) [
"keymaps/divide-by-zero.xkb",
"keymaps/bad.xkb"]
| tulcod/haskell-xkbcommon | tests/filecomp.hs | mit | 665 | 10 | 10 | 130 | 236 | 121 | 115 | 21 | 1 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
module System.HFind.Combinators where
import Prelude hiding (filter)
import Data.Bifunctor
import qualified Data.Text as T
import Pipes
import qualified Pipes.Prelude as P
import System.HFind.Path
import System.HFind.Types
import System.IO (hPutStrLn, stderr)
bimapM :: Monad m
=> (fp -> m fp')
-> (dp -> m dp')
-> Walk m fp dp
-> m (Walk m fp' dp')
bimapM mffp _ (FileP fp) = FileP <$> mffp fp
bimapM mffp mfdp (DirP dp mbs) = do
dp' <- mfdp dp
return $ DirP dp' (mbs >-> P.mapM (bimapM mffp mfdp))
bimapM_ :: Monad m
=> (fp -> m ())
-> (dp -> m ())
-> Walk m fp dp
-> m (Walk m fp dp)
bimapM_ mffp _ n@(FileP fp) = n <$ mffp fp
bimapM_ mffp mfdp (DirP dp mbs) = do
mfdp dp
return $ DirP dp (mbs >-> P.mapM (bimapM_ mffp mfdp))
hoistWalk :: (Monad m, Monad n)
=> (forall a. m a -> n a) -> Walk m fp dp -> Walk n fp dp
hoistWalk _ (FileP fp) = FileP fp
hoistWalk f (DirP dp p) = DirP dp (hoist f p >-> P.map (hoistWalk f))
type Transform fp dp m = Pipe (Walk m fp dp) (Walk m fp dp) m ()
type TransformP m = Pipe (WalkP m) (WalkP m) m ()
type TransformN m s = Pipe (WalkN m s) (WalkN m s) m ()
type TransformL m = Pipe (WalkL m) (WalkL m) m ()
type TransformN' m = Pipe (WalkN' m) (WalkN' m) m ()
type TransformR m = Pipe (WalkR m) (WalkR m) m ()
type EntryTransformN m s = Pipe (NodeListEntry s) (NodeListEntry s) m ()
type EntryTransformR m = EntryTransformN m 'Resolved
type EntryConsumerN m s = Consumer (NodeListEntry s) m ()
type EntryConsumerR m = EntryConsumerN m 'Resolved
mapChildren :: Monad m
=> (Producer' (Walk m fp dp) m () -> Producer' (Walk m fp dp) m ())
-> Transform fp dp m
mapChildren f = P.map $ \case
DirP dp mbs -> DirP dp (f mbs)
file -> file
fixP :: forall m a b. Monad m
=> ((Producer' a m () -> Producer' b m ()) -> Pipe a b m ())
-> Pipe a b m ()
fixP f = f_go
where
go :: Producer' a m () -> Producer' b m ()
go as = as >-> f_go
f_go :: Pipe a b m ()
f_go = f go
recurse :: Monad m
=> Pipe (Walk m fp dp) (Walk m fp dp) m ()
-> Pipe (Walk m fp dp) (Walk m fp dp) m ()
recurse f = fixP (\go -> f >-> mapChildren go)
censor :: Monad m => (Walk m fp dp -> Bool) -> Transform fp dp m
censor p = recurse (P.filter p)
censorM :: Monad m => (Walk m fp dp -> m Bool) -> Transform fp dp m
censorM p = recurse (P.filterM p)
censorF2 :: Monad m => (fp -> Bool) -> (dp -> Bool) -> Transform fp dp m
censorF2 p q = censor p'
where
p' (FileP fp) = p fp
p' (DirP dp _) = q dp
censorF2M :: Monad m => (fp -> m Bool) -> (dp -> m Bool) -> Transform fp dp m
censorF2M p q = censorM p'
where
p' (FileP fp) = p fp
p' (DirP dp _) = q dp
censorP :: Monad m => (forall t. IsPathType t => Path Abs t -> Bool) -> TransformP m
censorP p = censorF2 p p
censorPM :: Monad m => (forall t. IsPathType t => Path Abs t -> m Bool) -> TransformP m
censorPM p = censorF2M p p
censorN :: Monad m => (forall t. IsPathType t => FSNode t s -> Bool) -> TransformN m s
censorN p = censorF2 p p
censorNM :: Monad m => (forall t. IsPathType t => FSNode t s -> m Bool) -> TransformN m s
censorNM p = censorF2M p p
skip :: Monad m => (Walk m fp dp -> Bool) -> Transform fp dp m
skip p = censor (not . p)
skipM :: Monad m => (Walk m fp dp -> m Bool) -> Transform fp dp m
skipM p = censorM (fmap not . p)
skipF2 :: Monad m => (fp -> Bool) -> (dp -> Bool) -> Transform fp dp m
skipF2 p q = censorF2 (not . p) (not . q)
skipF2M :: Monad m => (fp -> m Bool) -> (dp -> m Bool) -> Transform fp dp m
skipF2M p q = censorF2M (fmap not . p) (fmap not . q)
skipP :: Monad m => (forall t. IsPathType t => Path Abs t -> Bool) -> TransformP m
skipP p = skipF2 p p
skipPM :: Monad m => (forall t. IsPathType t => Path Abs t -> m Bool) -> TransformP m
skipPM p = skipF2M p p
skipN :: Monad m => (forall t. IsPathType t => FSNode t s -> Bool) -> TransformN m s
skipN p = skipF2 p p
skipNM :: Monad m => (forall t. IsPathType t => FSNode t s -> m Bool) -> TransformN m s
skipNM p = skipF2M p p
pruneDirs :: Monad m => (dp -> Bool) -> Transform fp dp m
pruneDirs = skipF2 (const False)
pruneDirsM :: Monad m => (dp -> m Bool) -> Transform fp dp m
pruneDirsM = skipF2M (const $ return False)
follow :: forall s s' t. (HasErrors s ~ HasErrors s') => FSNode t s -> FSNode t s'
follow (FileNode stat p) = FileNode stat p
follow (DirNode stat p) = DirNode stat p
follow (Symlink _ l n) =
case follow n :: FSNode t s' of
FileNode stat _ -> FileNode stat (asFilePath (getLinkPath l))
DirNode stat _ -> DirNode stat (asDirPath (getLinkPath l))
Missing p -> Missing p
FSCycle p -> FSCycle p
_ -> error "System.Posix.Find.Combinators.follow: the impossible happened!"
follow (Missing p) = Missing p
follow (FSCycle l) = FSCycle l
follow (PermissionDenied p) = PermissionDenied p
followLinks :: Monad m => Pipe (WalkL m) (WalkN' m) m ()
followLinks = P.map (bimap follow follow)
type NodeFilter m s s' = forall t. FSNode t s -> Producer' (FSNode t s') m ()
report :: (MonadIO m, HasLinks s ~ HasLinks s') => NodeFilter m s s'
report = \case
FileNode stat p -> yield (FileNode stat p)
DirNode stat p -> yield (DirNode stat p)
Symlink stat l p -> for (report p) (yield . Symlink stat l)
Missing p -> liftIO $ hPutStrLn stderr ("*** File not found " ++ show p)
FSCycle l -> liftIO $ hPutStrLn stderr ("*** File system cycle at " ++ show l)
PermissionDenied p -> liftIO $ hPutStrLn stderr ("*** Permission denied: " ++ show p)
silence :: (Monad m, HasLinks s ~ HasLinks s') => NodeFilter m s s'
silence = \case
FileNode stat p -> yield (FileNode stat p)
DirNode stat p -> yield (DirNode stat p)
Symlink stat l p -> for (silence p) (yield . Symlink stat l)
Missing _ -> return ()
FSCycle _ -> return ()
PermissionDenied _ -> return ()
onError :: (Monad m, HasLinks s ~ HasLinks s')
=> NodeFilter m s s' -> Pipe (WalkN m s) (WalkN m s') m ()
onError erase = fixP $ \go ->
for cat $ \case
FileP fp -> erase fp >-> P.map FileP
DirP dp mbs -> erase dp >-> P.map (\dp' -> DirP dp' (go mbs))
clean :: MonadIO m => Pipe (WalkL m) (WalkR m) m ()
clean = followLinks >-> onError report
flatten :: Monad m => Pipe (Walk m fp dp) (ListEntry fp dp) m ()
flatten =
for cat $ \case
FileP fp -> yield (FileEntry fp)
DirP dp mbs -> yield (DirEntry dp) >> (mbs >-> flatten)
asPaths :: Monad m => Pipe NodeListEntryR PathListEntry m ()
asPaths = P.map (bimap nodePath nodePath)
asFiles :: Monad m => Pipe PathListEntry (Path Abs File) m ()
asFiles = P.map (\case DirEntry p -> asFilePath p
FileEntry p -> asFilePath p)
plainText :: Monad m => Pipe (Path Abs File) T.Text m ()
plainText = P.map toText
stringPaths :: Monad m => Pipe (Path Abs File) String m ()
stringPaths = P.map toString
-- disambiguation
is :: Pipe a a m () -> Pipe a a m ()
is = id
raw :: Monad m => Pipe (WalkN m 'Raw) (WalkN m 'Raw) m ()
raw = cat
withLinks :: Monad m => Pipe (WalkN m 'WithLinks) (WalkN m 'WithLinks) m ()
withLinks = cat
withoutLinks :: Monad m => Pipe (WalkN m 'WithoutLinks) (WalkN m 'WithoutLinks) m ()
withoutLinks = cat
resolved :: Monad m => Pipe (WalkN m 'Resolved) (WalkN m 'Resolved) m ()
resolved = cat
| xcv-/hfind | src/System/HFind/Combinators.hs | mit | 7,832 | 0 | 17 | 2,143 | 3,733 | 1,839 | 1,894 | 171 | 6 |
{-# LANGUAGE FlexibleContexts #-}
{- |
Module : ./CSL/GenericInterpreter.hs
Description : Generic ASState functionality for AssignmentStores
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
Generic functionality for 'AssignmentStore's based on the 'ASState'
datastructure. Handles all the translation stuff between the EnCL specification
and the terms on the CAS side
(see the 'BMap' structure in the Interpreter module)
-}
module CSL.GenericInterpreter where
import CSL.AS_BASIC_CSL
import CSL.ASUtils
import CSL.Interpreter
import Control.Monad.State.Class
import Control.Monad.Reader
{- ----------------------------------------------------------------------
Generic Translation Interface
---------------------------------------------------------------------- -}
getBooleanFromExpr :: EXPRESSION -> Either String Bool
getBooleanFromExpr (Op (OpId OP_true) _ _ _) = Right True
getBooleanFromExpr (Op (OpId OP_false) _ _ _) = Right False
getBooleanFromExpr (Op (OpId OP_failure) _ _ _) = Left "AssignmentStore FAILURE"
getBooleanFromExpr e = Left $ "Cannot translate expression to boolean: "
++ show e
transConstant :: MonadState (ASState s) as => ConstantName -> as String
transConstant s = do
r <- get
let bm = getBMap r
(bm', s') = lookupOrInsert bm s
put r { getBMap = bm' }
return s'
lookupConstant :: MonadState (ASState s) as => ConstantName -> as (Maybe String)
lookupConstant s = do
r <- get
let bm = getBMap r
return $ rolookup bm s
transExpr :: MonadState (ASState s) as => EXPRESSION -> as EXPRESSION
transExpr e = do
r <- get
let bm = getBMap r
(bm', e') = translateExpr bm e
put r { getBMap = bm' }
return e'
transExprWithVars :: MonadState (ASState s) as =>
[String] -> EXPRESSION -> as ([String], EXPRESSION)
transExprWithVars vl e = do
r <- get
let bm = getBMap r
args = translateArgVars bm vl
(bm', e') = translateExprWithVars vl bm e
put r { getBMap = bm' }
return (args, e')
transDef :: MonadState (ASState s) as => AssDefinition -> as AssDefinition
transDef (FunDef l e) = liftM (uncurry FunDef) $ transExprWithVars l e
transDef (ConstDef e) = liftM ConstDef $ transExpr e
transAssignment :: (MonadState (ASState s) as) =>
(ConstantName, AssDefinition) -> as (String, AssDefinition)
transAssignment (c, a) = do
n' <- transConstant c
def' <- transDef a
return (n', def')
revtransDefExpr :: MonadState (ASState s) as => AssDefinition -> EXPRESSION
-> as EXPRESSION
revtransDefExpr def = revtransExpr $ getArguments def
revtransExpr :: MonadState (ASState s) as => [String] -> EXPRESSION
-> as EXPRESSION
revtransExpr args e = do
r <- get
let bm = getBMap r
return $ if null args then revtranslateExpr bm e
else revtranslateExprWithVars args bm e
{- ----------------------------------------------------------------------
Generic AssignmentStore Methods
---------------------------------------------------------------------- -}
genAssign :: ( MonadState (ASState s) as) =>
(String -> AssDefinition -> as EXPRESSION)
-> ConstantName -> AssDefinition -> as EXPRESSION
genAssign ef n def =
transAssignment (n, def) >>= uncurry ef >>= revtransDefExpr def
genAssigns :: (MonadState (ASState s) as) =>
([(String, AssDefinition)] -> as a)
-> [(ConstantName, AssDefinition)] -> as a
genAssigns ef l = mapM transAssignment l >>= ef
genLookup :: (MonadState (ASState s) as) =>
(String -> as EXPRESSION)
-> ConstantName -> as (Maybe EXPRESSION)
genLookup ef n = do
mN <- lookupConstant n
case mN of
Just n' ->
ef n' >>= liftM Just . revtransExpr []
_ -> return Nothing
genEval :: (MonadState (ASState s) as) =>
(EXPRESSION -> as EXPRESSION)
-> EXPRESSION -> as EXPRESSION
genEval ef e = transExpr e >>= ef >>= revtransExpr []
genCheck :: (MonadState (ASState s) as) =>
(EXPRESSION -> as EXPRESSION)
-> EXPRESSION -> as (Either String Bool)
genCheck ef e = transExpr e >>= liftM getBooleanFromExpr . ef
| spechub/Hets | CSL/GenericInterpreter.hs | gpl-2.0 | 4,294 | 0 | 12 | 945 | 1,273 | 628 | 645 | 86 | 2 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples, RankNTypes #-}
{-# OPTIONS_HADDOCK not-home #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.ST
-- Copyright : (c) The University of Glasgow, 1992-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The 'ST' Monad.
--
-----------------------------------------------------------------------------
module GHC.ST (
ST(..), STret(..), STRep,
runST,
-- * Unsafe functions
liftST, unsafeInterleaveST, unsafeDupableInterleaveST
) where
import GHC.Base
import GHC.Show
import qualified Control.Monad.Fail as Fail
default ()
-- The 'ST' monad proper. By default the monad is strict;
-- too many people got bitten by space leaks when it was lazy.
-- | The strict 'ST' monad.
-- The 'ST' monad allows for destructive updates, but is escapable (unlike IO).
-- A computation of type @'ST' s a@ returns a value of type @a@, and
-- execute in "thread" @s@. The @s@ parameter is either
--
-- * an uninstantiated type variable (inside invocations of 'runST'), or
--
-- * 'RealWorld' (inside invocations of 'Control.Monad.ST.stToIO').
--
-- It serves to keep the internal states of different invocations
-- of 'runST' separate from each other and from invocations of
-- 'Control.Monad.ST.stToIO'.
--
-- The '>>=' and '>>' operations are strict in the state (though not in
-- values stored in the state). For example,
--
-- @'runST' (writeSTRef _|_ v >>= f) = _|_@
newtype ST s a = ST (STRep s a)
type STRep s a = State# s -> (# State# s, a #)
-- | @since 2.01
instance Functor (ST s) where
fmap f (ST m) = ST $ \ s ->
case (m s) of { (# new_s, r #) ->
(# new_s, f r #) }
-- | @since 4.4.0.0
instance Applicative (ST s) where
{-# INLINE pure #-}
{-# INLINE (*>) #-}
pure x = ST (\ s -> (# s, x #))
m *> k = m >>= \ _ -> k
(<*>) = ap
liftA2 = liftM2
-- | @since 2.01
instance Monad (ST s) where
{-# INLINE (>>=) #-}
(>>) = (*>)
(ST m) >>= k
= ST (\ s ->
case (m s) of { (# new_s, r #) ->
case (k r) of { ST k2 ->
(k2 new_s) }})
-- | @since 4.11.0.0
instance Fail.MonadFail (ST s) where
fail s = errorWithoutStackTrace s
-- | @since 4.11.0.0
instance Semigroup a => Semigroup (ST s a) where
(<>) = liftA2 (<>)
-- | @since 4.11.0.0
instance Monoid a => Monoid (ST s a) where
mempty = pure mempty
data STret s a = STret (State# s) a
-- liftST is useful when we want a lifted result from an ST computation.
liftST :: ST s a -> State# s -> STret s a
liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
noDuplicateST :: ST s ()
noDuplicateST = ST $ \s -> (# noDuplicate# s, () #)
-- | 'unsafeInterleaveST' allows an 'ST' computation to be deferred
-- lazily. When passed a value of type @ST a@, the 'ST' computation will
-- only be performed when the value of the @a@ is demanded.
{-# INLINE unsafeInterleaveST #-}
unsafeInterleaveST :: ST s a -> ST s a
unsafeInterleaveST m = unsafeDupableInterleaveST (noDuplicateST >> m)
-- | 'unsafeDupableInterleaveST' allows an 'ST' computation to be deferred
-- lazily. When passed a value of type @ST a@, the 'ST' computation will
-- only be performed when the value of the @a@ is demanded.
--
-- The computation may be performed multiple times by different threads,
-- possibly at the same time. To prevent this, use 'unsafeInterleaveST' instead.
--
-- @since 4.11
{-# NOINLINE unsafeDupableInterleaveST #-}
-- See Note [unsafeDupableInterleaveIO should not be inlined]
-- in GHC.IO.Unsafe
unsafeDupableInterleaveST :: ST s a -> ST s a
unsafeDupableInterleaveST (ST m) = ST ( \ s ->
let
r = case m s of (# _, res #) -> res
in
(# s, r #)
)
-- | @since 2.01
instance Show (ST s a) where
showsPrec _ _ = showString "<<ST action>>"
showList = showList__ (showsPrec 0)
{-# INLINE runST #-}
-- | Return the value computed by a state thread.
-- The @forall@ ensures that the internal state used by the 'ST'
-- computation is inaccessible to the rest of the program.
runST :: (forall s. ST s a) -> a
runST (ST st_rep) = case runRW# st_rep of (# _, a #) -> a
-- See Note [Definition of runRW#] in GHC.Magic
| sdiehl/ghc | libraries/base/GHC/ST.hs | bsd-3-clause | 4,383 | 0 | 16 | 972 | 837 | 478 | 359 | 58 | 1 |
module Distribution.Client.Dependency.Modular.Index where
import Data.List as L
import Data.Map as M
import Prelude hiding (pi)
import Distribution.Client.Dependency.Modular.Dependency
import Distribution.Client.Dependency.Modular.Flag
import Distribution.Client.Dependency.Modular.Package
-- | An index contains information about package instances. This is a nested
-- dictionary. Package names are mapped to instances, which in turn is mapped
-- to info.
type Index = Map PN (Map I PInfo)
-- | Info associated with a package instance.
-- Currently, dependencies, flags and encapsulations.
data PInfo = PInfo (FlaggedDeps PN) FlagDefaults Encaps
deriving (Show)
-- | Encapsulations. A list of package names.
type Encaps = [PN]
mkIndex :: [(PN, I, PInfo)] -> Index
mkIndex xs = M.map M.fromList (groupMap (L.map (\ (pn, i, pi) -> (pn, (i, pi))) xs))
groupMap :: Ord a => [(a, b)] -> Map a [b]
groupMap xs = M.fromListWith (++) (L.map (\ (x, y) -> (x, [y])) xs)
| IreneKnapp/Faction | faction/Distribution/Client/Dependency/Modular/Index.hs | bsd-3-clause | 970 | 0 | 13 | 150 | 282 | 172 | 110 | 15 | 1 |
module IRTS.CodegenC (codegenC) where
import Idris.AbsSyntax
import IRTS.Bytecode
import IRTS.Lang
import IRTS.Simplified
import IRTS.Defunctionalise
import IRTS.System
import IRTS.CodegenCommon
import Idris.Core.TT
import Util.System
import Numeric
import Data.Char
import Data.Bits
import Data.List (intercalate)
import System.Process
import System.Exit
import System.IO
import System.Directory
import System.FilePath ((</>), (<.>))
import Control.Monad
import Debug.Trace
codegenC :: CodeGenerator
codegenC ci = do codegenC' (simpleDecls ci)
(outputFile ci)
(outputType ci)
(includes ci)
(compileObjs ci)
(map mkLib (compileLibs ci) ++
map incdir (importDirs ci))
(compilerFlags ci)
(exportDecls ci)
(interfaces ci)
(debugLevel ci)
when (interfaces ci) $
codegenH (exportDecls ci)
where mkLib l = "-l" ++ l
incdir i = "-I" ++ i
codegenC' :: [(Name, SDecl)] ->
String -> -- output file name
OutputType -> -- generate executable if True, only .o if False
[FilePath] -> -- include files
[String] -> -- extra object files
[String] -> -- extra compiler flags (libraries)
[String] -> -- extra compiler flags (anything)
[ExportIFace] ->
Bool -> -- interfaces too (so make a .o instead)
DbgLevel ->
IO ()
codegenC' defs out exec incs objs libs flags exports iface dbg
= do -- print defs
let bc = map toBC defs
let h = concatMap toDecl (map fst bc)
let cc = concatMap (uncurry toC) bc
let hi = concatMap ifaceC (concatMap getExp exports)
d <- getDataDir
mprog <- readFile (d </> "rts" </> "idris_main" <.> "c")
let cout = headers incs ++ debug dbg ++ h ++ cc ++
(if (exec == Executable) then mprog else hi)
case exec of
MavenProject -> putStrLn ("FAILURE: output type not supported")
Raw -> writeSource out cout
_ -> do
(tmpn, tmph) <- tempfile ".c"
hPutStr tmph cout
hFlush tmph
hClose tmph
comp <- getCC
libFlags <- getLibFlags
incFlags <- getIncFlags
envFlags <- getEnvFlags
let args = [gccDbg dbg] ++
gccFlags iface ++
-- # Any flags defined here which alter the RTS API must also be added to config.mk
["-DHAS_PTHREAD", "-DIDRIS_ENABLE_STATS",
"-I."] ++ objs ++ envFlags ++
(if (exec == Executable) then [] else ["-c"]) ++
[tmpn] ++
(if not iface then concatMap words libFlags else []) ++
concatMap words incFlags ++
(if not iface then concatMap words libs else []) ++
concatMap words flags ++
["-o", out]
-- putStrLn (show args)
exit <- rawSystem comp args
when (exit /= ExitSuccess) $
putStrLn ("FAILURE: " ++ show comp ++ " " ++ show args)
where
getExp (Export _ _ exp) = exp
headers xs =
concatMap
(\h -> "#include \"" ++ h ++ "\"\n")
(xs ++ ["idris_rts.h", "idris_bitstring.h", "idris_stdfgn.h"])
debug TRACE = "#define IDRIS_TRACE\n\n"
debug _ = ""
-- We're using signed integers now. Make sure we get consistent semantics
-- out of them from gcc. See e.g. http://thiemonagel.de/2010/01/signed-integer-overflow/
gccFlags i = if i then ["-fwrapv"]
else ["-fwrapv", "-fno-strict-overflow"]
gccDbg DEBUG = "-g"
gccDbg TRACE = "-O2"
gccDbg _ = "-O2"
cname :: Name -> String
cname n = "_idris_" ++ concatMap cchar (showCG n)
where cchar x | isAlpha x || isDigit x = [x]
| otherwise = "_" ++ show (fromEnum x) ++ "_"
indent :: Int -> String
indent n = replicate (n*4) ' '
creg RVal = "RVAL"
creg (L i) = "LOC(" ++ show i ++ ")"
creg (T i) = "TOP(" ++ show i ++ ")"
creg Tmp = "REG1"
toDecl :: Name -> String
toDecl f = "void " ++ cname f ++ "(VM*, VAL*);\n"
toC :: Name -> [BC] -> String
toC f code
= -- "/* " ++ show code ++ "*/\n\n" ++
"void " ++ cname f ++ "(VM* vm, VAL* oldbase) {\n" ++
indent 1 ++ "INITFRAME;\n" ++
concatMap (bcc 1) code ++ "}\n\n"
showCStr :: String -> String
showCStr s = '"' : foldr ((++) . showChar) "\"" s
where
showChar :: Char -> String
showChar '"' = "\\\""
showChar '\\' = "\\\\"
showChar c
-- Note: we need the double quotes around the codes because otherwise
-- "\n3" would get encoded as "\x0a3", which is incorrect.
-- Instead, we opt for "\x0a""3" and let the C compiler deal with it.
| ord c < 0x10 = "\"\"\\x0" ++ showHex (ord c) "\"\""
| ord c < 0x20 = "\"\"\\x" ++ showHex (ord c) "\"\""
| ord c < 0x7f = [c] -- 0x7f = \DEL
| otherwise = showHexes (utf8bytes (ord c))
utf8bytes :: Int -> [Int]
utf8bytes x = let (h : bytes) = split [] x in
headHex h (length bytes) : map toHex bytes
where
split acc 0 = acc
split acc x = let xbits = x .&. 0x3f
xrest = shiftR x 6 in
split (xbits : acc) xrest
headHex h 1 = h + 0xc0
headHex h 2 = h + 0xe0
headHex h 3 = h + 0xf0
headHex h n = error "Can't happen: Invalid UTF8 character"
toHex i = i + 0x80
showHexes = foldr ((++) . showUTF8) ""
showUTF8 c = "\"\"\\x" ++ showHex c "\"\""
bcc :: Int -> BC -> String
bcc i (ASSIGN l r) = indent i ++ creg l ++ " = " ++ creg r ++ ";\n"
bcc i (ASSIGNCONST l c)
= indent i ++ creg l ++ " = " ++ mkConst c ++ ";\n"
where
mkConst (I i) = "MKINT(" ++ show i ++ ")"
mkConst (BI i) | i < (2^30) = "MKINT(" ++ show i ++ ")"
| otherwise = "MKBIGC(vm,\"" ++ show i ++ "\")"
mkConst (Fl f) = "MKFLOAT(vm, " ++ show f ++ ")"
mkConst (Ch c) = "MKINT(" ++ show (fromEnum c) ++ ")"
mkConst (Str s) = "MKSTR(vm, " ++ showCStr s ++ ")"
mkConst (B8 x) = "idris_b8const(vm, " ++ show x ++ "U)"
mkConst (B16 x) = "idris_b16const(vm, " ++ show x ++ "U)"
mkConst (B32 x) = "idris_b32const(vm, " ++ show x ++ "UL)"
mkConst (B64 x) = "idris_b64const(vm, " ++ show x ++ "ULL)"
-- if it's a type constant, we won't use it, but equally it shouldn't
-- report an error. These might creep into generated for various reasons
-- (especially if erasure is disabled).
mkConst c | isTypeConst c = "MKINT(42424242)"
mkConst c = error $ "mkConst of (" ++ show c ++ ") not implemented"
bcc i (UPDATE l r) = indent i ++ creg l ++ " = " ++ creg r ++ ";\n"
bcc i (MKCON l loc tag []) | tag < 256
= indent i ++ creg l ++ " = NULL_CON(" ++ show tag ++ ");\n"
bcc i (MKCON l loc tag args)
= indent i ++ alloc loc tag ++
indent i ++ setArgs 0 args ++ "\n" ++
indent i ++ creg l ++ " = " ++ creg Tmp ++ ";\n"
-- "MKCON(vm, " ++ creg l ++ ", " ++ show tag ++ ", " ++
-- show (length args) ++ concatMap showArg args ++ ");\n"
where showArg r = ", " ++ creg r
setArgs i [] = ""
setArgs i (x : xs) = "SETARG(" ++ creg Tmp ++ ", " ++ show i ++ ", " ++ creg x ++
"); " ++ setArgs (i + 1) xs
alloc Nothing tag
= "allocCon(" ++ creg Tmp ++ ", vm, " ++ show tag ++ ", " ++
show (length args) ++ ", 0);\n"
alloc (Just old) tag
= "updateCon(" ++ creg Tmp ++ ", " ++ creg old ++ ", " ++ show tag ++ ", " ++
show (length args) ++ ");\n"
bcc i (PROJECT l loc a) = indent i ++ "PROJECT(vm, " ++ creg l ++ ", " ++ show loc ++
", " ++ show a ++ ");\n"
bcc i (PROJECTINTO r t idx)
= indent i ++ creg r ++ " = GETARG(" ++ creg t ++ ", " ++ show idx ++ ");\n"
bcc i (CASE True r code def)
| length code < 4 = showCase i def code
where
showCode :: Int -> [BC] -> String
showCode i bc = "{\n" ++ concatMap (bcc (i + 1)) bc ++
indent i ++ "}\n"
showCase :: Int -> Maybe [BC] -> [(Int, [BC])] -> String
showCase i Nothing [(t, c)] = indent i ++ showCode i c
showCase i (Just def) [] = indent i ++ showCode i def
showCase i def ((t, c) : cs)
= indent i ++ "if (CTAG(" ++ creg r ++ ") == " ++ show t ++ ") " ++ showCode i c
++ indent i ++ "else\n" ++ showCase i def cs
bcc i (CASE safe r code def)
= indent i ++ "switch(" ++ ctag safe ++ "(" ++ creg r ++ ")) {\n" ++
concatMap (showCase i) code ++
showDef i def ++
indent i ++ "}\n"
where
ctag True = "CTAG"
ctag False = "TAG"
showCase i (t, bc) = indent i ++ "case " ++ show t ++ ":\n"
++ concatMap (bcc (i+1)) bc ++ indent (i + 1) ++ "break;\n"
showDef i Nothing = ""
showDef i (Just c) = indent i ++ "default:\n"
++ concatMap (bcc (i+1)) c ++ indent (i + 1) ++ "break;\n"
bcc i (CONSTCASE r code def)
| intConsts code
-- = indent i ++ "switch(GETINT(" ++ creg r ++ ")) {\n" ++
-- concatMap (showCase i) code ++
-- showDef i def ++
-- indent i ++ "}\n"
= concatMap (iCase (creg r)) code ++
indent i ++ "{\n" ++ showDefS i def ++ indent i ++ "}\n"
| strConsts code
= concatMap (strCase ("GETSTR(" ++ creg r ++ ")")) code ++
indent i ++ "{\n" ++ showDefS i def ++ indent i ++ "}\n"
| bigintConsts code
= concatMap (biCase (creg r)) code ++
indent i ++ "{\n" ++ showDefS i def ++ indent i ++ "}\n"
| otherwise = error $ "Can't happen: Can't compile const case " ++ show code
where
intConsts ((I _, _ ) : _) = True
intConsts ((Ch _, _ ) : _) = True
intConsts ((B8 _, _ ) : _) = True
intConsts ((B16 _, _ ) : _) = True
intConsts ((B32 _, _ ) : _) = True
intConsts ((B64 _, _ ) : _) = True
intConsts _ = False
bigintConsts ((BI _, _ ) : _) = True
bigintConsts _ = False
strConsts ((Str _, _ ) : _) = True
strConsts _ = False
strCase sv (s, bc) =
indent i ++ "if (strcmp(" ++ sv ++ ", " ++ show s ++ ") == 0) {\n" ++
concatMap (bcc (i+1)) bc ++ indent i ++ "} else\n"
biCase bv (BI b, bc) =
indent i ++ "if (bigEqConst(" ++ bv ++ ", " ++ show b ++ ")) {\n"
++ concatMap (bcc (i+1)) bc ++ indent i ++ "} else\n"
iCase v (I b, bc) =
indent i ++ "if (GETINT(" ++ v ++ ") == " ++ show b ++ ") {\n"
++ concatMap (bcc (i+1)) bc ++ indent i ++ "} else\n"
iCase v (Ch b, bc) =
indent i ++ "if (GETINT(" ++ v ++ ") == " ++ show (fromEnum b) ++ ") {\n"
++ concatMap (bcc (i+1)) bc ++ indent i ++ "} else\n"
iCase v (B8 w, bc) =
indent i ++ "if (GETBITS8(" ++ v ++ ") == " ++ show (fromEnum w) ++ ") {\n"
++ concatMap (bcc (i+1)) bc ++ indent i ++ "} else\n"
iCase v (B16 w, bc) =
indent i ++ "if (GETBITS16(" ++ v ++ ") == " ++ show (fromEnum w) ++ ") {\n"
++ concatMap (bcc (i+1)) bc ++ indent i ++ "} else\n"
iCase v (B32 w, bc) =
indent i ++ "if (GETBITS32(" ++ v ++ ") == " ++ show (fromEnum w) ++ ") {\n"
++ concatMap (bcc (i+1)) bc ++ indent i ++ "} else\n"
iCase v (B64 w, bc) =
indent i ++ "if (GETBITS64(" ++ v ++ ") == " ++ show (fromEnum w) ++ ") {\n"
++ concatMap (bcc (i+1)) bc ++ indent i ++ "} else\n"
showCase i (t, bc) = indent i ++ "case " ++ show t ++ ":\n"
++ concatMap (bcc (i+1)) bc ++
indent (i + 1) ++ "break;\n"
showDef i Nothing = ""
showDef i (Just c) = indent i ++ "default:\n"
++ concatMap (bcc (i+1)) c ++
indent (i + 1) ++ "break;\n"
showDefS i Nothing = ""
showDefS i (Just c) = concatMap (bcc (i+1)) c
bcc i (CALL n) = indent i ++ "CALL(" ++ cname n ++ ");\n"
bcc i (TAILCALL n) = indent i ++ "TAILCALL(" ++ cname n ++ ");\n"
bcc i (SLIDE n) = indent i ++ "SLIDE(vm, " ++ show n ++ ");\n"
bcc i REBASE = indent i ++ "REBASE;\n"
bcc i (RESERVE 0) = ""
bcc i (RESERVE n) = indent i ++ "RESERVE(" ++ show n ++ ");\n"
bcc i (ADDTOP 0) = ""
bcc i (ADDTOP n) = indent i ++ "ADDTOP(" ++ show n ++ ");\n"
bcc i (TOPBASE n) = indent i ++ "TOPBASE(" ++ show n ++ ");\n"
bcc i (BASETOP n) = indent i ++ "BASETOP(" ++ show n ++ ");\n"
bcc i STOREOLD = indent i ++ "STOREOLD;\n"
bcc i (OP l fn args) = indent i ++ doOp (creg l ++ " = ") fn args ++ ";\n"
bcc i (FOREIGNCALL l rty (FStr fn) args)
= indent i ++
c_irts (toFType rty) (creg l ++ " = ")
(fn ++ "(" ++ showSep "," (map fcall args) ++ ")") ++ ";\n"
where fcall (t, arg) = irts_c (toFType t) (creg arg)
bcc i (NULL r) = indent i ++ creg r ++ " = NULL;\n" -- clear, so it'll be GCed
bcc i (ERROR str) = indent i ++ "fprintf(stderr, " ++ show str ++ "); fprintf(stderr, \"\\n\"); exit(-1);\n"
-- bcc i c = error (show c) -- indent i ++ "// not done yet\n"
-- Deconstruct the Foreign type in the defunctionalised expression and build
-- a foreign type description for c_irts and irts_c
toAType (FCon i)
| i == sUN "C_IntChar" = ATInt ITChar
| i == sUN "C_IntNative" = ATInt ITNative
| i == sUN "C_IntBits8" = ATInt (ITFixed IT8)
| i == sUN "C_IntBits16" = ATInt (ITFixed IT16)
| i == sUN "C_IntBits32" = ATInt (ITFixed IT32)
| i == sUN "C_IntBits64" = ATInt (ITFixed IT64)
toAType t = error (show t ++ " not defined in toAType")
toFType (FCon c)
| c == sUN "C_Str" = FString
| c == sUN "C_Float" = FArith ATFloat
| c == sUN "C_Ptr" = FPtr
| c == sUN "C_MPtr" = FManagedPtr
| c == sUN "C_Unit" = FUnit
toFType (FApp c [_,ity])
| c == sUN "C_IntT" = FArith (toAType ity)
toFType (FApp c [_])
| c == sUN "C_Any" = FAny
toFType t = FAny
c_irts (FArith (ATInt ITNative)) l x = l ++ "MKINT((i_int)(" ++ x ++ "))"
c_irts (FArith (ATInt ITChar)) l x = c_irts (FArith (ATInt ITNative)) l x
c_irts (FArith (ATInt (ITFixed ity))) l x
= l ++ "idris_b" ++ show (nativeTyWidth ity) ++ "const(vm, " ++ x ++ ")"
c_irts FString l x = l ++ "MKSTR(vm, " ++ x ++ ")"
c_irts FUnit l x = x
c_irts FPtr l x = l ++ "MKPTR(vm, " ++ x ++ ")"
c_irts FManagedPtr l x = l ++ "MKMPTR(vm, " ++ x ++ ")"
c_irts (FArith ATFloat) l x = l ++ "MKFLOAT(vm, " ++ x ++ ")"
c_irts FAny l x = l ++ x
irts_c (FArith (ATInt ITNative)) x = "GETINT(" ++ x ++ ")"
irts_c (FArith (ATInt ITChar)) x = irts_c (FArith (ATInt ITNative)) x
irts_c (FArith (ATInt (ITFixed ity))) x
= "(" ++ x ++ "->info.bits" ++ show (nativeTyWidth ity) ++ ")"
irts_c FString x = "GETSTR(" ++ x ++ ")"
irts_c FUnit x = x
irts_c FPtr x = "GETPTR(" ++ x ++ ")"
irts_c FManagedPtr x = "GETMPTR(" ++ x ++ ")"
irts_c (FArith ATFloat) x = "GETFLOAT(" ++ x ++ ")"
irts_c FAny x = x
bitOp v op ty args = v ++ "idris_b" ++ show (nativeTyWidth ty) ++ op ++ "(vm, " ++ intercalate ", " (map creg args) ++ ")"
bitCoerce v op input output arg
= v ++ "idris_b" ++ show (nativeTyWidth input) ++ op ++ show (nativeTyWidth output) ++ "(vm, " ++ creg arg ++ ")"
signedTy :: NativeTy -> String
signedTy t = "int" ++ show (nativeTyWidth t) ++ "_t"
doOp v (LPlus (ATInt ITNative)) [l, r] = v ++ "ADD(" ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LMinus (ATInt ITNative)) [l, r] = v ++ "INTOP(-," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LTimes (ATInt ITNative)) [l, r] = v ++ "MULT(" ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LUDiv ITNative) [l, r] = v ++ "UINTOP(/," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSDiv (ATInt ITNative)) [l, r] = v ++ "INTOP(/," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LURem ITNative) [l, r] = v ++ "UINTOP(%," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSRem (ATInt ITNative)) [l, r] = v ++ "INTOP(%," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LAnd ITNative) [l, r] = v ++ "INTOP(&," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LOr ITNative) [l, r] = v ++ "INTOP(|," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LXOr ITNative) [l, r] = v ++ "INTOP(^," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSHL ITNative) [l, r] = v ++ "INTOP(<<," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LLSHR ITNative) [l, r] = v ++ "UINTOP(>>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LASHR ITNative) [l, r] = v ++ "INTOP(>>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LCompl ITNative) [x] = v ++ "INTOP(~," ++ creg x ++ ")"
doOp v (LEq (ATInt ITNative)) [l, r] = v ++ "INTOP(==," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLt (ATInt ITNative)) [l, r] = v ++ "INTOP(<," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLe (ATInt ITNative)) [l, r] = v ++ "INTOP(<=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGt (ATInt ITNative)) [l, r] = v ++ "INTOP(>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGe (ATInt ITNative)) [l, r] = v ++ "INTOP(>=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LLt ITNative) [l, r] = v ++ "UINTOP(<," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LLe ITNative) [l, r] = v ++ "UINTOP(<=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LGt ITNative) [l, r] = v ++ "UINTOP(>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LGe ITNative) [l, r] = v ++ "UINTOP(>=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LPlus (ATInt ITChar)) [l, r] = doOp v (LPlus (ATInt ITNative)) [l, r]
doOp v (LMinus (ATInt ITChar)) [l, r] = doOp v (LMinus (ATInt ITNative)) [l, r]
doOp v (LTimes (ATInt ITChar)) [l, r] = doOp v (LTimes (ATInt ITNative)) [l, r]
doOp v (LUDiv ITChar) [l, r] = doOp v (LUDiv ITNative) [l, r]
doOp v (LSDiv (ATInt ITChar)) [l, r] = doOp v (LSDiv (ATInt ITNative)) [l, r]
doOp v (LURem ITChar) [l, r] = doOp v (LURem ITNative) [l, r]
doOp v (LSRem (ATInt ITChar)) [l, r] = doOp v (LSRem (ATInt ITNative)) [l, r]
doOp v (LAnd ITChar) [l, r] = doOp v (LAnd ITNative) [l, r]
doOp v (LOr ITChar) [l, r] = doOp v (LOr ITNative) [l, r]
doOp v (LXOr ITChar) [l, r] = doOp v (LXOr ITNative) [l, r]
doOp v (LSHL ITChar) [l, r] = doOp v (LSHL ITNative) [l, r]
doOp v (LLSHR ITChar) [l, r] = doOp v (LLSHR ITNative) [l, r]
doOp v (LASHR ITChar) [l, r] = doOp v (LASHR ITNative) [l, r]
doOp v (LCompl ITChar) [x] = doOp v (LCompl ITNative) [x]
doOp v (LEq (ATInt ITChar)) [l, r] = doOp v (LEq (ATInt ITNative)) [l, r]
doOp v (LSLt (ATInt ITChar)) [l, r] = doOp v (LSLt (ATInt ITNative)) [l, r]
doOp v (LSLe (ATInt ITChar)) [l, r] = doOp v (LSLe (ATInt ITNative)) [l, r]
doOp v (LSGt (ATInt ITChar)) [l, r] = doOp v (LSGt (ATInt ITNative)) [l, r]
doOp v (LSGe (ATInt ITChar)) [l, r] = doOp v (LSGe (ATInt ITNative)) [l, r]
doOp v (LLt ITChar) [l, r] = doOp v (LLt ITNative) [l, r]
doOp v (LLe ITChar) [l, r] = doOp v (LLe ITNative) [l, r]
doOp v (LGt ITChar) [l, r] = doOp v (LGt ITNative) [l, r]
doOp v (LGe ITChar) [l, r] = doOp v (LGe ITNative) [l, r]
doOp v (LPlus ATFloat) [l, r] = v ++ "FLOATOP(+," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LMinus ATFloat) [l, r] = v ++ "FLOATOP(-," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LTimes ATFloat) [l, r] = v ++ "FLOATOP(*," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSDiv ATFloat) [l, r] = v ++ "FLOATOP(/," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LEq ATFloat) [l, r] = v ++ "FLOATBOP(==," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLt ATFloat) [l, r] = v ++ "FLOATBOP(<," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLe ATFloat) [l, r] = v ++ "FLOATBOP(<=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGt ATFloat) [l, r] = v ++ "FLOATBOP(>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGe ATFloat) [l, r] = v ++ "FLOATBOP(>=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LIntFloat ITBig) [x] = v ++ "idris_castBigFloat(vm, " ++ creg x ++ ")"
doOp v (LFloatInt ITBig) [x] = v ++ "idris_castFloatBig(vm, " ++ creg x ++ ")"
doOp v (LPlus (ATInt ITBig)) [l, r] = v ++ "idris_bigPlus(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LMinus (ATInt ITBig)) [l, r] = v ++ "idris_bigMinus(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LTimes (ATInt ITBig)) [l, r] = v ++ "idris_bigTimes(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSDiv (ATInt ITBig)) [l, r] = v ++ "idris_bigDivide(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSRem (ATInt ITBig)) [l, r] = v ++ "idris_bigMod(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LAnd ITBig) [l, r] = v ++ "idris_bigAnd(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LOr ITBig) [l, r] = v ++ "idris_bigOr(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSHL ITBig) [l, r] = v ++ "idris_bigShiftLeft(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LLSHR ITBig) [l, r] = v ++ "idris_bigLShiftRight(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LASHR ITBig) [l, r] = v ++ "idris_bigAShiftRight(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LEq (ATInt ITBig)) [l, r] = v ++ "idris_bigEq(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLt (ATInt ITBig)) [l, r] = v ++ "idris_bigLt(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLe (ATInt ITBig)) [l, r] = v ++ "idris_bigLe(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGt (ATInt ITBig)) [l, r] = v ++ "idris_bigGt(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGe (ATInt ITBig)) [l, r] = v ++ "idris_bigGe(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LIntFloat ITNative) [x] = v ++ "idris_castIntFloat(" ++ creg x ++ ")"
doOp v (LFloatInt ITNative) [x] = v ++ "idris_castFloatInt(" ++ creg x ++ ")"
doOp v (LSExt ITNative ITBig) [x] = v ++ "idris_castIntBig(vm, " ++ creg x ++ ")"
doOp v (LTrunc ITBig ITNative) [x] = v ++ "idris_castBigInt(vm, " ++ creg x ++ ")"
doOp v (LStrInt ITBig) [x] = v ++ "idris_castStrBig(vm, " ++ creg x ++ ")"
doOp v (LIntStr ITBig) [x] = v ++ "idris_castBigStr(vm, " ++ creg x ++ ")"
doOp v (LIntStr ITNative) [x] = v ++ "idris_castIntStr(vm, " ++ creg x ++ ")"
doOp v (LStrInt ITNative) [x] = v ++ "idris_castStrInt(vm, " ++ creg x ++ ")"
doOp v (LIntStr (ITFixed _)) [x] = v ++ "idris_castBitsStr(vm, " ++ creg x ++ ")"
doOp v LFloatStr [x] = v ++ "idris_castFloatStr(vm, " ++ creg x ++ ")"
doOp v LStrFloat [x] = v ++ "idris_castStrFloat(vm, " ++ creg x ++ ")"
doOp v (LSLt (ATInt (ITFixed ty))) [x, y] = bitOp v "SLt" ty [x, y]
doOp v (LSLe (ATInt (ITFixed ty))) [x, y] = bitOp v "SLte" ty [x, y]
doOp v (LEq (ATInt (ITFixed ty))) [x, y] = bitOp v "Eq" ty [x, y]
doOp v (LSGe (ATInt (ITFixed ty))) [x, y] = bitOp v "SGte" ty [x, y]
doOp v (LSGt (ATInt (ITFixed ty))) [x, y] = bitOp v "SGt" ty [x, y]
doOp v (LLt (ITFixed ty)) [x, y] = bitOp v "Lt" ty [x, y]
doOp v (LLe (ITFixed ty)) [x, y] = bitOp v "Lte" ty [x, y]
doOp v (LGe (ITFixed ty)) [x, y] = bitOp v "Gte" ty [x, y]
doOp v (LGt (ITFixed ty)) [x, y] = bitOp v "Gt" ty [x, y]
doOp v (LSHL (ITFixed ty)) [x, y] = bitOp v "Shl" ty [x, y]
doOp v (LLSHR (ITFixed ty)) [x, y] = bitOp v "LShr" ty [x, y]
doOp v (LASHR (ITFixed ty)) [x, y] = bitOp v "AShr" ty [x, y]
doOp v (LAnd (ITFixed ty)) [x, y] = bitOp v "And" ty [x, y]
doOp v (LOr (ITFixed ty)) [x, y] = bitOp v "Or" ty [x, y]
doOp v (LXOr (ITFixed ty)) [x, y] = bitOp v "Xor" ty [x, y]
doOp v (LCompl (ITFixed ty)) [x] = bitOp v "Compl" ty [x]
doOp v (LPlus (ATInt (ITFixed ty))) [x, y] = bitOp v "Plus" ty [x, y]
doOp v (LMinus (ATInt (ITFixed ty))) [x, y] = bitOp v "Minus" ty [x, y]
doOp v (LTimes (ATInt (ITFixed ty))) [x, y] = bitOp v "Times" ty [x, y]
doOp v (LUDiv (ITFixed ty)) [x, y] = bitOp v "UDiv" ty [x, y]
doOp v (LSDiv (ATInt (ITFixed ty))) [x, y] = bitOp v "SDiv" ty [x, y]
doOp v (LURem (ITFixed ty)) [x, y] = bitOp v "URem" ty [x, y]
doOp v (LSRem (ATInt (ITFixed ty))) [x, y] = bitOp v "SRem" ty [x, y]
doOp v (LSExt (ITFixed from) ITBig) [x]
= v ++ "MKBIGSI(vm, (" ++ signedTy from ++ ")" ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ ")"
doOp v (LSExt ITNative (ITFixed to)) [x]
= v ++ "idris_b" ++ show (nativeTyWidth to) ++ "const(vm, GETINT(" ++ creg x ++ "))"
doOp v (LSExt ITChar (ITFixed to)) [x]
= doOp v (LSExt ITNative (ITFixed to)) [x]
doOp v (LSExt (ITFixed from) ITNative) [x]
= v ++ "MKINT((i_int)((" ++ signedTy from ++ ")" ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ "))"
doOp v (LSExt (ITFixed from) ITChar) [x]
= doOp v (LSExt (ITFixed from) ITNative) [x]
doOp v (LSExt (ITFixed from) (ITFixed to)) [x]
| nativeTyWidth from < nativeTyWidth to = bitCoerce v "S" from to x
doOp v (LZExt ITNative (ITFixed to)) [x]
= v ++ "idris_b" ++ show (nativeTyWidth to) ++ "const(vm, (uintptr_t)GETINT(" ++ creg x ++ "))"
doOp v (LZExt ITChar (ITFixed to)) [x]
= doOp v (LZExt ITNative (ITFixed to)) [x]
doOp v (LZExt (ITFixed from) ITNative) [x]
= v ++ "MKINT((i_int)" ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ ")"
doOp v (LZExt (ITFixed from) ITChar) [x]
= doOp v (LZExt (ITFixed from) ITNative) [x]
doOp v (LZExt (ITFixed from) ITBig) [x]
= v ++ "MKBIGUI(vm, " ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ ")"
doOp v (LZExt ITNative ITBig) [x]
= v ++ "MKBIGUI(vm, (uintptr_t)GETINT(" ++ creg x ++ "))"
doOp v (LZExt (ITFixed from) (ITFixed to)) [x]
| nativeTyWidth from < nativeTyWidth to = bitCoerce v "Z" from to x
doOp v (LTrunc ITNative (ITFixed to)) [x]
= v ++ "idris_b" ++ show (nativeTyWidth to) ++ "const(vm, GETINT(" ++ creg x ++ "))"
doOp v (LTrunc ITChar (ITFixed to)) [x]
= doOp v (LTrunc ITNative (ITFixed to)) [x]
doOp v (LTrunc (ITFixed from) ITNative) [x]
= v ++ "MKINT((i_int)" ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ ")"
doOp v (LTrunc (ITFixed from) ITChar) [x]
= doOp v (LTrunc (ITFixed from) ITNative) [x]
doOp v (LTrunc ITBig (ITFixed to)) [x]
= v ++ "idris_b" ++ show (nativeTyWidth to) ++ "const(vm, ISINT(" ++ creg x ++ ") ? GETINT(" ++ creg x ++ ") : mpz_get_ui(GETMPZ(" ++ creg x ++ ")))"
doOp v (LTrunc (ITFixed from) (ITFixed to)) [x]
| nativeTyWidth from > nativeTyWidth to = bitCoerce v "T" from to x
doOp v LFExp [x] = v ++ flUnOp "exp" (creg x)
doOp v LFLog [x] = v ++ flUnOp "log" (creg x)
doOp v LFSin [x] = v ++ flUnOp "sin" (creg x)
doOp v LFCos [x] = v ++ flUnOp "cos" (creg x)
doOp v LFTan [x] = v ++ flUnOp "tan" (creg x)
doOp v LFASin [x] = v ++ flUnOp "asin" (creg x)
doOp v LFACos [x] = v ++ flUnOp "acos" (creg x)
doOp v LFATan [x] = v ++ flUnOp "atan" (creg x)
doOp v LFSqrt [x] = v ++ flUnOp "sqrt" (creg x)
doOp v LFFloor [x] = v ++ flUnOp "floor" (creg x)
doOp v LFCeil [x] = v ++ flUnOp "ceil" (creg x)
doOp v LFNegate [x] = v ++ "MKFLOAT(vm, -GETFLOAT(" ++ (creg x) ++ "))"
-- String functions which don't need to know we're UTF8
doOp v LStrConcat [l,r] = v ++ "idris_concat(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v LStrLt [l,r] = v ++ "idris_strlt(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v LStrEq [l,r] = v ++ "idris_streq(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v LReadStr [_] = v ++ "idris_readStr(vm, stdin)"
doOp v LWriteStr [_,s]
= v ++ "MKINT((i_int)(idris_writeStr(stdout"
++ ",GETSTR("
++ creg s ++ "))))"
-- String functions which need to know we're UTF8
doOp v LStrHead [x] = v ++ "idris_strHead(vm, " ++ creg x ++ ")"
doOp v LStrTail [x] = v ++ "idris_strTail(vm, " ++ creg x ++ ")"
doOp v LStrCons [x, y] = v ++ "idris_strCons(vm, " ++ creg x ++ "," ++ creg y ++ ")"
doOp v LStrIndex [x, y] = v ++ "idris_strIndex(vm, " ++ creg x ++ "," ++ creg y ++ ")"
doOp v LStrRev [x] = v ++ "idris_strRev(vm, " ++ creg x ++ ")"
doOp v LStrLen [x] = v ++ "idris_strlen(vm, " ++ creg x ++ ")"
doOp v LStrSubstr [x,y,z] = v ++ "idris_substr(vm, " ++ creg x ++ "," ++ creg y ++ "," ++ creg z ++ ")"
doOp v LFork [x] = v ++ "MKPTR(vm, vmThread(vm, " ++ cname (sMN 0 "EVAL") ++ ", " ++ creg x ++ "))"
doOp v LPar [x] = v ++ creg x -- "MKPTR(vm, vmThread(vm, " ++ cname (MN 0 "EVAL") ++ ", " ++ creg x ++ "))"
doOp v (LChInt ITNative) args = v ++ creg (last args)
doOp v (LChInt ITChar) args = doOp v (LChInt ITNative) args
doOp v (LIntCh ITNative) args = v ++ creg (last args)
doOp v (LIntCh ITChar) args = doOp v (LIntCh ITNative) args
doOp v LSystemInfo [x] = v ++ "idris_systemInfo(vm, " ++ creg x ++ ")"
doOp v LNoOp args = v ++ creg (last args)
-- Pointer primitives (declared as %extern in Builtins.idr)
doOp v (LExternal rf) [_,x]
| rf == sUN "prim__readFile"
= v ++ "idris_readStr(vm, GETPTR(" ++ creg x ++ "))"
doOp v (LExternal wf) [_,x,s]
| wf == sUN "prim__writeFile"
= v ++ "MKINT((i_int)(idris_writeStr(GETPTR(" ++ creg x
++ "),GETSTR("
++ creg s ++ "))))"
doOp v (LExternal vm) [] | vm == sUN "prim__vm" = v ++ "MKPTR(vm, vm)"
doOp v (LExternal si) [] | si == sUN "prim__stdin" = v ++ "MKPTR(vm, stdin)"
doOp v (LExternal so) [] | so == sUN "prim__stdout" = v ++ "MKPTR(vm, stdout)"
doOp v (LExternal se) [] | se == sUN "prim__stderr" = v ++ "MKPTR(vm, stderr)"
doOp v (LExternal nul) [] | nul == sUN "prim__null" = v ++ "MKPTR(vm, NULL)"
doOp v (LExternal eqp) [x, y] | eqp == sUN "prim__eqPtr"
= v ++ "MKINT((i_int)(GETPTR(" ++ creg x ++ ") == GETPTR(" ++ creg y ++ ")))"
doOp v (LExternal eqp) [x, y] | eqp == sUN "prim__eqManagedPtr"
= v ++ "MKINT((i_int)(GETMPTR(" ++ creg x ++ ") == GETMPTR(" ++ creg y ++ ")))"
doOp v (LExternal rp) [p, i] | rp == sUN "prim__registerPtr"
= v ++ "MKMPTR(vm, GETPTR(" ++ creg p ++ "), GETINT(" ++ creg i ++ "))"
doOp _ op args = error $ "doOp not implemented (" ++ show (op, args) ++ ")"
flUnOp :: String -> String -> String
flUnOp name val = "MKFLOAT(vm, " ++ name ++ "(GETFLOAT(" ++ val ++ ")))"
-------------------- Interface file generation
-- First, the wrappers in the C file
ifaceC :: Export -> String
ifaceC (ExportData n) = "typedef VAL " ++ cdesc n ++ ";\n"
ifaceC (ExportFun n cn ret args)
= ctype ret ++ " " ++ cdesc cn ++
"(VM* vm" ++ showArgs (zip argNames args) ++ ") {\n"
++ mkBody n (zip argNames args) ret ++ "}\n\n"
where showArgs [] = ""
showArgs ((n, t) : ts) = ", " ++ ctype t ++ " " ++ n ++
showArgs ts
argNames = zipWith (++) (repeat "arg") (map show [0..])
mkBody n as t = indent 1 ++ "INITFRAME;\n" ++
indent 1 ++ "RESERVE(" ++ show (max (length as) 3) ++ ");\n" ++
push 0 as ++ call n ++ retval t
where push i [] = ""
push i ((n, t) : ts) = indent 1 ++ c_irts (toFType t)
("TOP(" ++ show i ++ ") = ") n
++ ";\n" ++ push (i + 1) ts
call _ = indent 1 ++ "STOREOLD;\n" ++
indent 1 ++ "BASETOP(0);\n" ++
indent 1 ++ "ADDTOP(" ++ show (length as) ++ ");\n" ++
indent 1 ++ "CALL(" ++ cname n ++ ");\n"
retval (FIO t)
= indent 1 ++ "TOP(0) = NULL;\n" ++
indent 1 ++ "TOP(1) = NULL;\n" ++
indent 1 ++ "TOP(2) = RVAL;\n" ++
indent 1 ++ "STOREOLD;\n" ++
indent 1 ++ "BASETOP(0);\n" ++
indent 1 ++ "ADDTOP(3);\n" ++
indent 1 ++ "CALL(" ++ cname (sUN "call__IO") ++ ");\n" ++
retval t
retval t = indent 1 ++ "return " ++ irts_c (toFType t) "RVAL" ++ ";\n"
ctype (FCon c)
| c == sUN "C_Str" = "char*"
| c == sUN "C_Float" = "float"
| c == sUN "C_Ptr" = "void*"
| c == sUN "C_MPtr" = "void*"
| c == sUN "C_Unit" = "void"
ctype (FApp c [_,ity])
| c == sUN "C_IntT" = carith ity
ctype (FApp c [_])
| c == sUN "C_Any" = "VAL"
ctype (FStr s) = s
ctype FUnknown = "void*"
ctype (FIO t) = ctype t
ctype t = error "Can't happen: Not a valid interface type " ++ show t
carith (FCon i)
| i == sUN "C_IntChar" = "char"
| i == sUN "C_IntNative" = "int"
carith t = error "Can't happen: Not an exportable arithmetic type"
cdesc (FStr s) = s
cdesc s = error "Can't happen: Not a valid C name"
-- Then, the header files
codegenH :: [ExportIFace] -> IO ()
codegenH es = mapM_ writeIFace es
writeIFace :: ExportIFace -> IO ()
writeIFace (Export ffic hdr exps)
| ffic == sNS (sUN "FFI_C") ["FFI_C"]
= do let hfile = "#ifndef " ++ hdr_guard hdr ++ "\n" ++
"#define " ++ hdr_guard hdr ++ "\n\n" ++
"#include <idris_rts.h>\n\n" ++
concatMap hdr_export exps ++ "\n" ++
"#endif\n\n"
writeFile hdr hfile
| otherwise = return ()
hdr_guard x = "__" ++ map hchar x
where hchar x | isAlphaNum x = toUpper x
hchar _ = '_'
hdr_export :: Export -> String
hdr_export (ExportData n) = "typedef VAL " ++ cdesc n ++ ";\n"
hdr_export (ExportFun n cn ret args)
= ctype ret ++ " " ++ cdesc cn ++
"(VM* vm" ++ showArgs (zip argNames args) ++ ");\n"
where showArgs [] = ""
showArgs ((n, t) : ts) = ", " ++ ctype t ++ " " ++ n ++
showArgs ts
argNames = zipWith (++) (repeat "arg") (map show [0..])
| aaronc/Idris-dev | src/IRTS/CodegenC.hs | bsd-3-clause | 33,130 | 0 | 27 | 9,489 | 15,144 | 7,533 | 7,611 | 592 | 32 |
{-
(c) The University of Glasgow 2006-2012
(c) The GRASP Project, Glasgow University, 1992-2002
Various types used during typechecking, please see TcRnMonad as well for
operations on these types. You probably want to import it, instead of this
module.
All the monads exported here are built on top of the same IOEnv monad. The
monad functions like a Reader monad in the way it passes the environment
around. This is done to allow the environment to be manipulated in a stack
like fashion when entering expressions... ect.
For state that is global and should be returned at the end (e.g not part
of the stack mechanism), you should use an TcRef (= IORef) to store them.
-}
{-# LANGUAGE CPP, ExistentialQuantification, GeneralizedNewtypeDeriving #-}
module TcRnTypes(
TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
TcRef,
-- The environment types
Env(..),
TcGblEnv(..), TcLclEnv(..),
IfGblEnv(..), IfLclEnv(..),
-- Renamer types
ErrCtxt, RecFieldEnv(..),
ImportAvails(..), emptyImportAvails, plusImportAvails,
WhereFrom(..), mkModDeps,
-- Typechecker types
TcTypeEnv, TcIdBinderStack, TcIdBinder(..),
TcTyThing(..), PromotionErr(..),
pprTcTyThingCategory, pprPECategory,
-- Desugaring types
DsM, DsLclEnv(..), DsGblEnv(..), PArrBuiltin(..),
DsMetaEnv, DsMetaVal(..),
-- Template Haskell
ThStage(..), PendingStuff(..), topStage, topAnnStage, topSpliceStage,
ThLevel, impLevel, outerLevel, thLevel,
-- Arrows
ArrowCtxt(..),
-- Canonical constraints
Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, pprCts,
singleCt, listToCts, ctsElts, consCts, snocCts, extendCtsList,
isEmptyCts, isCTyEqCan, isCFunEqCan,
isCDictCan_Maybe, isCFunEqCan_maybe,
isCIrredEvCan, isCNonCanonical, isWantedCt, isDerivedCt,
isGivenCt, isHoleCt, isExprHoleCt, isTypeHoleCt,
ctEvidence, ctLoc, ctPred, ctFlavour, ctEqRel,
mkNonCanonical, mkNonCanonicalCt,
ctEvPred, ctEvLoc, ctEvEqRel,
ctEvTerm, ctEvCoercion, ctEvId,
WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
andWC, unionsWC, addSimples, addImplics, mkSimpleWC, addInsols,
dropDerivedWC, dropDerivedSimples, dropDerivedInsols,
insolubleImplic, trulyInsoluble,
Implication(..), ImplicStatus(..), isInsolubleStatus,
SubGoalDepth, initialSubGoalDepth,
bumpSubGoalDepth, subGoalDepthExceeded,
CtLoc(..), ctLocSpan, ctLocEnv, ctLocLevel, ctLocOrigin,
ctLocDepth, bumpCtLocDepth,
setCtLocOrigin, setCtLocEnv, setCtLocSpan,
CtOrigin(..), pprCtOrigin,
pushErrCtxt, pushErrCtxtSameOrigin,
SkolemInfo(..),
CtEvidence(..),
mkGivenLoc,
isWanted, isGiven, isDerived,
ctEvRole,
-- Constraint solver plugins
TcPlugin(..), TcPluginResult(..), TcPluginSolver,
TcPluginM, runTcPluginM, unsafeTcPluginTcM,
CtFlavour(..), ctEvFlavour,
-- Pretty printing
pprEvVarTheta,
pprEvVars, pprEvVarWithType,
pprArising, pprArisingAt,
-- Misc other types
TcId, TcIdSet, HoleSort(..)
) where
#include "HsVersions.h"
import HsSyn
import CoreSyn
import HscTypes
import TcEvidence
import Type
import CoAxiom ( Role )
import Class ( Class )
import TyCon ( TyCon )
import ConLike ( ConLike(..) )
import DataCon ( DataCon, dataConUserType, dataConOrigArgTys )
import PatSyn ( PatSyn, patSynType )
import TcType
import Annotations
import InstEnv
import FamInstEnv
import IOEnv
import RdrName
import Name
import NameEnv
import NameSet
import Avail
import Var
import VarEnv
import Module
import SrcLoc
import VarSet
import ErrUtils
import UniqFM
import UniqSupply
import BasicTypes
import Bag
import DynFlags
import Outputable
import ListSetOps
import FastString
import GHC.Fingerprint
import Data.Set (Set)
import Control.Monad (ap, liftM)
#ifdef GHCI
import Data.Map ( Map )
import Data.Dynamic ( Dynamic )
import Data.Typeable ( TypeRep )
import qualified Language.Haskell.TH as TH
#endif
{-
************************************************************************
* *
Standard monad definition for TcRn
All the combinators for the monad can be found in TcRnMonad
* *
************************************************************************
The monad itself has to be defined here, because it is mentioned by ErrCtxt
-}
type TcRnIf a b = IOEnv (Env a b)
type TcRn = TcRnIf TcGblEnv TcLclEnv -- Type inference
type IfM lcl = TcRnIf IfGblEnv lcl -- Iface stuff
type IfG = IfM () -- Top level
type IfL = IfM IfLclEnv -- Nested
type DsM = TcRnIf DsGblEnv DsLclEnv -- Desugaring
-- TcRn is the type-checking and renaming monad: the main monad that
-- most type-checking takes place in. The global environment is
-- 'TcGblEnv', which tracks all of the top-level type-checking
-- information we've accumulated while checking a module, while the
-- local environment is 'TcLclEnv', which tracks local information as
-- we move inside expressions.
-- | Historical "renaming monad" (now it's just 'TcRn').
type RnM = TcRn
-- | Historical "type-checking monad" (now it's just 'TcRn').
type TcM = TcRn
-- We 'stack' these envs through the Reader like monad infastructure
-- as we move into an expression (although the change is focused in
-- the lcl type).
data Env gbl lcl
= Env {
env_top :: HscEnv, -- Top-level stuff that never changes
-- Includes all info about imported things
env_us :: {-# UNPACK #-} !(IORef UniqSupply),
-- Unique supply for local varibles
env_gbl :: gbl, -- Info about things defined at the top level
-- of the module being compiled
env_lcl :: lcl -- Nested stuff; changes as we go into
}
instance ContainsDynFlags (Env gbl lcl) where
extractDynFlags env = hsc_dflags (env_top env)
replaceDynFlags env dflags
= env {env_top = replaceDynFlags (env_top env) dflags}
instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
extractModule env = extractModule (env_gbl env)
{-
************************************************************************
* *
The interface environments
Used when dealing with IfaceDecls
* *
************************************************************************
-}
data IfGblEnv
= IfGblEnv {
-- The type environment for the module being compiled,
-- in case the interface refers back to it via a reference that
-- was originally a hi-boot file.
-- We need the module name so we can test when it's appropriate
-- to look in this env.
if_rec_types :: Maybe (Module, IfG TypeEnv)
-- Allows a read effect, so it can be in a mutable
-- variable; c.f. handling the external package type env
-- Nothing => interactive stuff, no loops possible
}
data IfLclEnv
= IfLclEnv {
-- The module for the current IfaceDecl
-- So if we see f = \x -> x
-- it means M.f = \x -> x, where M is the if_mod
if_mod :: Module,
-- The field is used only for error reporting
-- if (say) there's a Lint error in it
if_loc :: SDoc,
-- Where the interface came from:
-- .hi file, or GHCi state, or ext core
-- plus which bit is currently being examined
if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
-- (and coercions)
if_id_env :: UniqFM Id -- Nested id binding
}
{-
************************************************************************
* *
Desugarer monad
* *
************************************************************************
Now the mondo monad magic (yes, @DsM@ is a silly name)---carry around
a @UniqueSupply@ and some annotations, which
presumably include source-file location information:
-}
-- If '-XParallelArrays' is given, the desugarer populates this table with the corresponding
-- variables found in 'Data.Array.Parallel'.
--
data PArrBuiltin
= PArrBuiltin
{ lengthPVar :: Var -- ^ lengthP
, replicatePVar :: Var -- ^ replicateP
, singletonPVar :: Var -- ^ singletonP
, mapPVar :: Var -- ^ mapP
, filterPVar :: Var -- ^ filterP
, zipPVar :: Var -- ^ zipP
, crossMapPVar :: Var -- ^ crossMapP
, indexPVar :: Var -- ^ (!:)
, emptyPVar :: Var -- ^ emptyP
, appPVar :: Var -- ^ (+:+)
, enumFromToPVar :: Var -- ^ enumFromToP
, enumFromThenToPVar :: Var -- ^ enumFromThenToP
}
data DsGblEnv
= DsGblEnv
{ ds_mod :: Module -- For SCC profiling
, ds_fam_inst_env :: FamInstEnv -- Like tcg_fam_inst_env
, ds_unqual :: PrintUnqualified
, ds_msgs :: IORef Messages -- Warning messages
, ds_if_env :: (IfGblEnv, IfLclEnv) -- Used for looking up global,
-- possibly-imported things
, ds_dph_env :: GlobalRdrEnv -- exported entities of 'Data.Array.Parallel.Prim'
-- iff '-fvectorise' flag was given as well as
-- exported entities of 'Data.Array.Parallel' iff
-- '-XParallelArrays' was given; otherwise, empty
, ds_parr_bi :: PArrBuiltin -- desugarar names for '-XParallelArrays'
, ds_static_binds :: IORef [(Fingerprint, (Id,CoreExpr))]
-- ^ Bindings resulted from floating static forms
}
instance ContainsModule DsGblEnv where
extractModule = ds_mod
data DsLclEnv = DsLclEnv {
dsl_meta :: DsMetaEnv, -- Template Haskell bindings
dsl_loc :: SrcSpan -- to put in pattern-matching error msgs
}
-- Inside [| |] brackets, the desugarer looks
-- up variables in the DsMetaEnv
type DsMetaEnv = NameEnv DsMetaVal
data DsMetaVal
= DsBound Id -- Bound by a pattern inside the [| |].
-- Will be dynamically alpha renamed.
-- The Id has type THSyntax.Var
| DsSplice (HsExpr Id) -- These bindings are introduced by
-- the PendingSplices on a HsBracketOut
{-
************************************************************************
* *
Global typechecker environment
* *
************************************************************************
-}
-- | 'TcGblEnv' describes the top-level of the module at the
-- point at which the typechecker is finished work.
-- It is this structure that is handed on to the desugarer
-- For state that needs to be updated during the typechecking
-- phase and returned at end, use a 'TcRef' (= 'IORef').
data TcGblEnv
= TcGblEnv {
tcg_mod :: Module, -- ^ Module being compiled
tcg_src :: HscSource,
-- ^ What kind of module (regular Haskell, hs-boot, ext-core)
tcg_sig_of :: Maybe Module,
-- ^ Are we being compiled as a signature of an implementation?
tcg_mod_name :: Maybe (Located ModuleName),
-- ^ @Nothing@: \"module X where\" is omitted
tcg_impl_rdr_env :: Maybe GlobalRdrEnv,
-- ^ Environment used only during -sig-of for resolving top level
-- bindings. See Note [Signature parameters in TcGblEnv and DynFlags]
tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
tcg_default :: Maybe [Type],
-- ^ Types used for defaulting. @Nothing@ => no @default@ decl
tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
-- See Note [The interactive package] in HscTypes
tcg_type_env :: TypeEnv,
-- ^ Global type env for the module we are compiling now. All
-- TyCons and Classes (for this module) end up in here right away,
-- along with their derived constructors, selectors.
--
-- (Ids defined in this module start in the local envt, though they
-- move to the global envt during zonking)
--
-- NB: for what "things in this module" means, see
-- Note [The interactive package] in HscTypes
tcg_type_env_var :: TcRef TypeEnv,
-- Used only to initialise the interface-file
-- typechecker in initIfaceTcRn, so that it can see stuff
-- bound in this module when dealing with hi-boot recursions
-- Updated at intervals (e.g. after dealing with types and classes)
tcg_inst_env :: InstEnv,
-- ^ Instance envt for all /home-package/ modules;
-- Includes the dfuns in tcg_insts
tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
tcg_ann_env :: AnnEnv, -- ^ And for annotations
tcg_visible_orphan_mods :: ModuleSet,
-- ^ The set of orphan modules which transitively reachable from
-- direct imports. We use this to figure out if an orphan instance
-- in the global InstEnv should be considered visible.
-- See Note [Instance lookup and orphan instances] in InstEnv
-- Now a bunch of things about this module that are simply
-- accumulated, but never consulted until the end.
-- Nevertheless, it's convenient to accumulate them along
-- with the rest of the info from this module.
tcg_exports :: [AvailInfo], -- ^ What is exported
tcg_imports :: ImportAvails,
-- ^ Information about what was imported from where, including
-- things bound in this module. Also store Safe Haskell info
-- here about transative trusted packaage requirements.
tcg_dus :: DefUses, -- ^ What is defined in this module and what is used.
tcg_used_rdrnames :: TcRef (Set RdrName),
-- See Note [Tracking unused binding and imports]
tcg_keep :: TcRef NameSet,
-- ^ Locally-defined top-level names to keep alive.
--
-- "Keep alive" means give them an Exported flag, so that the
-- simplifier does not discard them as dead code, and so that they
-- are exposed in the interface file (but not to export to the
-- user).
--
-- Some things, like dict-fun Ids and default-method Ids are "born"
-- with the Exported flag on, for exactly the above reason, but some
-- we only discover as we go. Specifically:
--
-- * The to/from functions for generic data types
--
-- * Top-level variables appearing free in the RHS of an orphan
-- rule
--
-- * Top-level variables appearing free in a TH bracket
tcg_th_used :: TcRef Bool,
-- ^ @True@ <=> Template Haskell syntax used.
--
-- We need this so that we can generate a dependency on the
-- Template Haskell package, because the desugarer is going
-- to emit loads of references to TH symbols. The reference
-- is implicit rather than explicit, so we have to zap a
-- mutable variable.
tcg_th_splice_used :: TcRef Bool,
-- ^ @True@ <=> A Template Haskell splice was used.
--
-- Splices disable recompilation avoidance (see #481)
tcg_dfun_n :: TcRef OccSet,
-- ^ Allows us to choose unique DFun names.
-- The next fields accumulate the payload of the module
-- The binds, rules and foreign-decl fields are collected
-- initially in un-zonked form and are finally zonked in tcRnSrcDecls
tcg_rn_exports :: Maybe [Located (IE Name)],
-- Nothing <=> no explicit export list
tcg_rn_imports :: [LImportDecl Name],
-- Keep the renamed imports regardless. They are not
-- voluminous and are needed if you want to report unused imports
tcg_rn_decls :: Maybe (HsGroup Name),
-- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
-- decls.
tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
#ifdef GHCI
tcg_th_topdecls :: TcRef [LHsDecl RdrName],
-- ^ Top-level declarations from addTopDecls
tcg_th_topnames :: TcRef NameSet,
-- ^ Exact names bound in top-level declarations in tcg_th_topdecls
tcg_th_modfinalizers :: TcRef [TH.Q ()],
-- ^ Template Haskell module finalizers
tcg_th_state :: TcRef (Map TypeRep Dynamic),
-- ^ Template Haskell state
#endif /* GHCI */
tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
-- Things defined in this module, or (in GHCi)
-- in the declarations for a single GHCi command.
-- For the latter, see Note [The interactive package] in HscTypes
tcg_binds :: LHsBinds Id, -- Value bindings in this module
tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
tcg_warns :: Warnings, -- ...Warnings and deprecations
tcg_anns :: [Annotation], -- ...Annotations
tcg_tcs :: [TyCon], -- ...TyCons and Classes
tcg_insts :: [ClsInst], -- ...Instances
tcg_fam_insts :: [FamInst], -- ...Family instances
tcg_rules :: [LRuleDecl Id], -- ...Rules
tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
tcg_vects :: [LVectDecl Id], -- ...Vectorisation declarations
tcg_patsyns :: [PatSyn], -- ...Pattern synonyms
tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
tcg_hpc :: AnyHpcUsage, -- ^ @True@ if any part of the
-- prog uses hpc instrumentation.
tcg_main :: Maybe Name, -- ^ The Name of the main
-- function, if this module is
-- the main module.
tcg_safeInfer :: TcRef (Bool, WarningMessages),
-- ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)
-- See Note [Safe Haskell Overlapping Instances Implementation],
-- although this is used for more than just that failure case.
tcg_tc_plugins :: [TcPluginSolver],
-- ^ A list of user-defined plugins for the constraint solver.
tcg_static_wc :: TcRef WantedConstraints
-- ^ Wanted constraints of static forms.
}
-- Note [Signature parameters in TcGblEnv and DynFlags]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- When compiling signature files, we need to know which implementation
-- we've actually linked against the signature. There are three seemingly
-- redundant places where this information is stored: in DynFlags, there
-- is sigOf, and in TcGblEnv, there is tcg_sig_of and tcg_impl_rdr_env.
-- Here's the difference between each of them:
--
-- * DynFlags.sigOf is global per invocation of GHC. If we are compiling
-- with --make, there may be multiple signature files being compiled; in
-- which case this parameter is a map from local module name to implementing
-- Module.
--
-- * HscEnv.tcg_sig_of is global per the compilation of a single file, so
-- it is simply the result of looking up tcg_mod in the DynFlags.sigOf
-- parameter. It's setup in TcRnMonad.initTc. This prevents us
-- from having to repeatedly do a lookup in DynFlags.sigOf.
--
-- * HscEnv.tcg_impl_rdr_env is a RdrEnv that lets us look up names
-- according to the sig-of module. It's setup in TcRnDriver.tcRnSignature.
-- Here is an example showing why we need this map:
--
-- module A where
-- a = True
--
-- module ASig where
-- import B
-- a :: Bool
--
-- module B where
-- b = False
--
-- When we compile ASig --sig-of main:A, the default
-- global RdrEnv (tcg_rdr_env) has an entry for b, but not for a
-- (we never imported A). So we have to look in a different environment
-- to actually get the original name.
--
-- By the way, why do we need to do the lookup; can't we just use A:a
-- as the name directly? Well, if A is reexporting the entity from another
-- module, then the original name needs to be the real original name:
--
-- module C where
-- a = True
--
-- module A(a) where
-- import C
instance ContainsModule TcGblEnv where
extractModule env = tcg_mod env
data RecFieldEnv
= RecFields (NameEnv [Name]) -- Maps a constructor name *in this module*
-- to the fields for that constructor
NameSet -- Set of all fields declared *in this module*;
-- used to suppress name-shadowing complaints
-- when using record wild cards
-- E.g. let fld = e in C {..}
-- This is used when dealing with ".." notation in record
-- construction and pattern matching.
-- The FieldEnv deals *only* with constructors defined in *this*
-- module. For imported modules, we get the same info from the
-- TypeEnv
{-
Note [Tracking unused binding and imports]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We gather two sorts of usage information
* tcg_dus (defs/uses)
Records *defined* Names (local, top-level)
and *used* Names (local or imported)
Used (a) to report "defined but not used"
(see RnNames.reportUnusedNames)
(b) to generate version-tracking usage info in interface
files (see MkIface.mkUsedNames)
This usage info is mainly gathered by the renamer's
gathering of free-variables
* tcg_used_rdrnames
Records used *imported* (not locally-defined) RdrNames
Used only to report unused import declarations
Notice that they are RdrNames, not Names, so we can
tell whether the reference was qualified or unqualified, which
is esssential in deciding whether a particular import decl
is unnecessary. This info isn't present in Names.
************************************************************************
* *
The local typechecker environment
* *
************************************************************************
Note [The Global-Env/Local-Env story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During type checking, we keep in the tcg_type_env
* All types and classes
* All Ids derived from types and classes (constructors, selectors)
At the end of type checking, we zonk the local bindings,
and as we do so we add to the tcg_type_env
* Locally defined top-level Ids
Why? Because they are now Ids not TcIds. This final GlobalEnv is
a) fed back (via the knot) to typechecking the
unfoldings of interface signatures
b) used in the ModDetails of this module
-}
data TcLclEnv -- Changes as we move inside an expression
-- Discarded after typecheck/rename; not passed on to desugarer
= TcLclEnv {
tcl_loc :: RealSrcSpan, -- Source span
tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
tcl_tclvl :: TcLevel, -- Birthplace for new unification variables
tcl_th_ctxt :: ThStage, -- Template Haskell context
tcl_th_bndrs :: ThBindEnv, -- Binding level of in-scope Names
-- defined in this module (not imported)
tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
tcl_rdr :: LocalRdrEnv, -- Local name envt
-- Maintained during renaming, of course, but also during
-- type checking, solely so that when renaming a Template-Haskell
-- splice we have the right environment for the renamer.
--
-- Does *not* include global name envt; may shadow it
-- Includes both ordinary variables and type variables;
-- they are kept distinct because tyvar have a different
-- occurrence contructor (Name.TvOcc)
-- We still need the unsullied global name env so that
-- we can look up record field names
tcl_env :: TcTypeEnv, -- The local type environment:
-- Ids and TyVars defined in this module
tcl_bndrs :: TcIdBinderStack, -- Used for reporting relevant bindings
tcl_tidy :: TidyEnv, -- Used for tidying types; contains all
-- in-scope type variables (but not term variables)
tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
-- Namely, the in-scope TyVars bound in tcl_env,
-- plus the tyvars mentioned in the types of Ids bound
-- in tcl_lenv.
-- Why mutable? see notes with tcGetGlobalTyVars
tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
tcl_errs :: TcRef Messages -- Place to accumulate errors
}
type TcTypeEnv = NameEnv TcTyThing
type ThBindEnv = NameEnv (TopLevelFlag, ThLevel)
-- Domain = all Ids bound in this module (ie not imported)
-- The TopLevelFlag tells if the binding is syntactically top level.
-- We need to know this, because the cross-stage persistence story allows
-- cross-stage at arbitrary types if the Id is bound at top level.
--
-- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being
-- bound at top level! See Note [Template Haskell levels] in TcSplice
{- Note [Given Insts]
~~~~~~~~~~~~~~~~~~
Because of GADTs, we have to pass inwards the Insts provided by type signatures
and existential contexts. Consider
data T a where { T1 :: b -> b -> T [b] }
f :: Eq a => T a -> Bool
f (T1 x y) = [x]==[y]
The constructor T1 binds an existential variable 'b', and we need Eq [b].
Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
pass it inwards.
-}
-- | Type alias for 'IORef'; the convention is we'll use this for mutable
-- bits of data in 'TcGblEnv' which are updated during typechecking and
-- returned at the end.
type TcRef a = IORef a
-- ToDo: when should I refer to it as a 'TcId' instead of an 'Id'?
type TcId = Id
type TcIdSet = IdSet
---------------------------
-- The TcIdBinderStack
---------------------------
type TcIdBinderStack = [TcIdBinder]
-- This is a stack of locally-bound ids, innermost on top
-- Used ony in error reporting (relevantBindings in TcError)
data TcIdBinder
= TcIdBndr
TcId
TopLevelFlag -- Tells whether the bindind is syntactically top-level
-- (The monomorphic Ids for a recursive group count
-- as not-top-level for this purpose.)
instance Outputable TcIdBinder where
ppr (TcIdBndr id top_lvl) = ppr id <> brackets (ppr top_lvl)
---------------------------
-- Template Haskell stages and levels
---------------------------
data ThStage -- See Note [Template Haskell state diagram] in TcSplice
= Splice -- Inside a top-level splice splice
-- This code will be run *at compile time*;
-- the result replaces the splice
-- Binding level = 0
Bool -- True if in a typed splice, False otherwise
| Comp -- Ordinary Haskell code
-- Binding level = 1
| Brack -- Inside brackets
ThStage -- Enclosing stage
PendingStuff
data PendingStuff
= RnPendingUntyped -- Renaming the inside of an *untyped* bracket
(TcRef [PendingRnSplice]) -- Pending splices in here
| RnPendingTyped -- Renaming the inside of a *typed* bracket
| TcPending -- Typechecking the inside of a typed bracket
(TcRef [PendingTcSplice]) -- Accumulate pending splices here
(TcRef WantedConstraints) -- and type constraints here
topStage, topAnnStage, topSpliceStage :: ThStage
topStage = Comp
topAnnStage = Splice False
topSpliceStage = Splice False
instance Outputable ThStage where
ppr (Splice _) = text "Splice"
ppr Comp = text "Comp"
ppr (Brack s _) = text "Brack" <> parens (ppr s)
type ThLevel = Int
-- NB: see Note [Template Haskell levels] in TcSplice
-- Incremented when going inside a bracket,
-- decremented when going inside a splice
-- NB: ThLevel is one greater than the 'n' in Fig 2 of the
-- original "Template meta-programming for Haskell" paper
impLevel, outerLevel :: ThLevel
impLevel = 0 -- Imported things; they can be used inside a top level splice
outerLevel = 1 -- Things defined outside brackets
thLevel :: ThStage -> ThLevel
thLevel (Splice _) = 0
thLevel Comp = 1
thLevel (Brack s _) = thLevel s + 1
---------------------------
-- Arrow-notation context
---------------------------
{- Note [Escaping the arrow scope]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In arrow notation, a variable bound by a proc (or enclosed let/kappa)
is not in scope to the left of an arrow tail (-<) or the head of (|..|).
For example
proc x -> (e1 -< e2)
Here, x is not in scope in e1, but it is in scope in e2. This can get
a bit complicated:
let x = 3 in
proc y -> (proc z -> e1) -< e2
Here, x and z are in scope in e1, but y is not.
We implement this by
recording the environment when passing a proc (using newArrowScope),
and returning to that (using escapeArrowScope) on the left of -< and the
head of (|..|).
All this can be dealt with by the *renamer*. But the type checker needs
to be involved too. Example (arrowfail001)
class Foo a where foo :: a -> ()
data Bar = forall a. Foo a => Bar a
get :: Bar -> ()
get = proc x -> case x of Bar a -> foo -< a
Here the call of 'foo' gives rise to a (Foo a) constraint that should not
be captured by the pattern match on 'Bar'. Rather it should join the
constraints from further out. So we must capture the constraint bag
from further out in the ArrowCtxt that we push inwards.
-}
data ArrowCtxt -- Note [Escaping the arrow scope]
= NoArrowCtxt
| ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)
---------------------------
-- TcTyThing
---------------------------
-- | A typecheckable thing available in a local context. Could be
-- 'AGlobal' 'TyThing', but also lexically scoped variables, etc.
-- See 'TcEnv' for how to retrieve a 'TyThing' given a 'Name'.
data TcTyThing
= AGlobal TyThing -- Used only in the return type of a lookup
| ATcId { -- Ids defined in this module; may not be fully zonked
tct_id :: TcId,
tct_closed :: TopLevelFlag } -- See Note [Bindings with closed types]
| ATyVar Name TcTyVar -- The type variable to which the lexically scoped type
-- variable is bound. We only need the Name
-- for error-message purposes; it is the corresponding
-- Name in the domain of the envt
| AThing TcKind -- Used temporarily, during kind checking, for the
-- tycons and clases in this recursive group
-- Can be a mono-kind or a poly-kind; in TcTyClsDcls see
-- Note [Type checking recursive type and class declarations]
| APromotionErr PromotionErr
data PromotionErr
= TyConPE -- TyCon used in a kind before we are ready
-- data T :: T -> * where ...
| ClassPE -- Ditto Class
| FamDataConPE -- Data constructor for a data family
-- See Note [AFamDataCon: not promoting data family constructors] in TcRnDriver
| RecDataConPE -- Data constructor in a recursive loop
-- See Note [ARecDataCon: recusion and promoting data constructors] in TcTyClsDecls
| NoDataKinds -- -XDataKinds not enabled
instance Outputable TcTyThing where -- Debugging only
ppr (AGlobal g) = pprTyThing g
ppr elt@(ATcId {}) = text "Identifier" <>
brackets (ppr (tct_id elt) <> dcolon
<> ppr (varType (tct_id elt)) <> comma
<+> ppr (tct_closed elt))
ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
ppr (AThing k) = text "AThing" <+> ppr k
ppr (APromotionErr err) = text "APromotionErr" <+> ppr err
instance Outputable PromotionErr where
ppr ClassPE = text "ClassPE"
ppr TyConPE = text "TyConPE"
ppr FamDataConPE = text "FamDataConPE"
ppr RecDataConPE = text "RecDataConPE"
ppr NoDataKinds = text "NoDataKinds"
pprTcTyThingCategory :: TcTyThing -> SDoc
pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe
pprPECategory :: PromotionErr -> SDoc
pprPECategory ClassPE = ptext (sLit "Class")
pprPECategory TyConPE = ptext (sLit "Type constructor")
pprPECategory FamDataConPE = ptext (sLit "Data constructor")
pprPECategory RecDataConPE = ptext (sLit "Data constructor")
pprPECategory NoDataKinds = ptext (sLit "Data constructor")
{- Note [Bindings with closed types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f x = let g ys = map not ys
in ...
Can we generalise 'g' under the OutsideIn algorithm? Yes,
because all g's free variables are top-level; that is they themselves
have no free type variables, and it is the type variables in the
environment that makes things tricky for OutsideIn generalisation.
Definition:
A variable is "closed", and has tct_closed set to TopLevel,
iff
a) all its free variables are imported, or are let-bound with closed types
b) generalisation is not restricted by the monomorphism restriction
Under OutsideIn we are free to generalise a closed let-binding.
This is an extension compared to the JFP paper on OutsideIn, which
used "top-level" as a proxy for "closed". (It's not a good proxy
anyway -- the MR can make a top-level binding with a free type
variable.)
Note that:
* A top-level binding may not be closed, if it suffers from the MR
* A nested binding may be closed (eg 'g' in the example we started with)
Indeed, that's the point; whether a function is defined at top level
or nested is orthogonal to the question of whether or not it is closed
* A binding may be non-closed because it mentions a lexically scoped
*type variable* Eg
f :: forall a. blah
f x = let g y = ...(y::a)...
-}
type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, MsgDoc))
-- Monadic so that we have a chance
-- to deal with bound type variables just before error
-- message construction
-- Bool: True <=> this is a landmark context; do not
-- discard it when trimming for display
{-
************************************************************************
* *
Operations over ImportAvails
* *
************************************************************************
-}
-- | 'ImportAvails' summarises what was imported from where, irrespective of
-- whether the imported things are actually used or not. It is used:
--
-- * when processing the export list,
--
-- * when constructing usage info for the interface file,
--
-- * to identify the list of directly imported modules for initialisation
-- purposes and for optimised overlap checking of family instances,
--
-- * when figuring out what things are really unused
--
data ImportAvails
= ImportAvails {
imp_mods :: ImportedMods,
-- = ModuleEnv [(ModuleName, Bool, SrcSpan, Bool)],
-- ^ Domain is all directly-imported modules
-- The 'ModuleName' is what the module was imported as, e.g. in
-- @
-- import Foo as Bar
-- @
-- it is @Bar@.
--
-- The 'Bool' means:
--
-- - @True@ => import was @import Foo ()@
--
-- - @False@ => import was some other form
--
-- Used
--
-- (a) to help construct the usage information in the interface
-- file; if we import something we need to recompile if the
-- export version changes
--
-- (b) to specify what child modules to initialise
--
-- We need a full ModuleEnv rather than a ModuleNameEnv here,
-- because we might be importing modules of the same name from
-- different packages. (currently not the case, but might be in the
-- future).
imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
-- ^ Home-package modules needed by the module being compiled
--
-- It doesn't matter whether any of these dependencies
-- are actually /used/ when compiling the module; they
-- are listed if they are below it at all. For
-- example, suppose M imports A which imports X. Then
-- compiling M might not need to consult X.hi, but X
-- is still listed in M's dependencies.
imp_dep_pkgs :: [PackageKey],
-- ^ Packages needed by the module being compiled, whether directly,
-- or via other modules in this package, or via modules imported
-- from other packages.
imp_trust_pkgs :: [PackageKey],
-- ^ This is strictly a subset of imp_dep_pkgs and records the
-- packages the current module needs to trust for Safe Haskell
-- compilation to succeed. A package is required to be trusted if
-- we are dependent on a trustworthy module in that package.
-- While perhaps making imp_dep_pkgs a tuple of (PackageKey, Bool)
-- where True for the bool indicates the package is required to be
-- trusted is the more logical design, doing so complicates a lot
-- of code not concerned with Safe Haskell.
-- See Note [RnNames . Tracking Trust Transitively]
imp_trust_own_pkg :: Bool,
-- ^ Do we require that our own package is trusted?
-- This is to handle efficiently the case where a Safe module imports
-- a Trustworthy module that resides in the same package as it.
-- See Note [RnNames . Trust Own Package]
imp_orphs :: [Module],
-- ^ Orphan modules below us in the import tree (and maybe including
-- us for imported modules)
imp_finsts :: [Module]
-- ^ Family instance modules below us in the import tree (and maybe
-- including us for imported modules)
}
mkModDeps :: [(ModuleName, IsBootInterface)]
-> ModuleNameEnv (ModuleName, IsBootInterface)
mkModDeps deps = foldl add emptyUFM deps
where
add env elt@(m,_) = addToUFM env m elt
emptyImportAvails :: ImportAvails
emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
imp_dep_mods = emptyUFM,
imp_dep_pkgs = [],
imp_trust_pkgs = [],
imp_trust_own_pkg = False,
imp_orphs = [],
imp_finsts = [] }
-- | Union two ImportAvails
--
-- This function is a key part of Import handling, basically
-- for each import we create a separate ImportAvails structure
-- and then union them all together with this function.
plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
plusImportAvails
(ImportAvails { imp_mods = mods1,
imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
imp_orphs = orphs1, imp_finsts = finsts1 })
(ImportAvails { imp_mods = mods2,
imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
imp_orphs = orphs2, imp_finsts = finsts2 })
= ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
imp_trust_pkgs = tpkgs1 `unionLists` tpkgs2,
imp_trust_own_pkg = tself1 || tself2,
imp_orphs = orphs1 `unionLists` orphs2,
imp_finsts = finsts1 `unionLists` finsts2 }
where
plus_mod_dep (m1, boot1) (m2, boot2)
= WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
-- Check mod-names match
(m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
{-
************************************************************************
* *
\subsection{Where from}
* *
************************************************************************
The @WhereFrom@ type controls where the renamer looks for an interface file
-}
data WhereFrom
= ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
| ImportBySystem -- Non user import.
| ImportByPlugin -- Importing a plugin;
-- See Note [Care with plugin imports] in LoadIface
instance Outputable WhereFrom where
ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
| otherwise = empty
ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
ppr ImportByPlugin = ptext (sLit "{- PLUGIN -}")
{-
************************************************************************
* *
* Canonical constraints *
* *
* These are the constraints the low-level simplifier works with *
* *
************************************************************************
-}
-- The syntax of xi types:
-- xi ::= a | T xis | xis -> xis | ... | forall a. tau
-- Two important notes:
-- (i) No type families, unless we are under a ForAll
-- (ii) Note that xi types can contain unexpanded type synonyms;
-- however, the (transitive) expansions of those type synonyms
-- will not contain any type functions, unless we are under a ForAll.
-- We enforce the structure of Xi types when we flatten (TcCanonical)
type Xi = Type -- In many comments, "xi" ranges over Xi
type Cts = Bag Ct
data Ct
-- Atomic canonical constraints
= CDictCan { -- e.g. Num xi
cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
cc_class :: Class,
cc_tyargs :: [Xi] -- cc_tyargs are function-free, hence Xi
}
| CIrredEvCan { -- These stand for yet-unusable predicates
cc_ev :: CtEvidence -- See Note [Ct/evidence invariant]
-- The ctev_pred of the evidence is
-- of form (tv xi1 xi2 ... xin)
-- or (tv1 ~ ty2) where the CTyEqCan kind invariant fails
-- or (F tys ~ ty) where the CFunEqCan kind invariant fails
-- See Note [CIrredEvCan constraints]
}
| CTyEqCan { -- tv ~ rhs
-- Invariants:
-- * See Note [Applying the inert substitution] in TcFlatten
-- * tv not in tvs(rhs) (occurs check)
-- * If tv is a TauTv, then rhs has no foralls
-- (this avoids substituting a forall for the tyvar in other types)
-- * typeKind ty `subKind` typeKind tv
-- See Note [Kind orientation for CTyEqCan]
-- * rhs is not necessarily function-free,
-- but it has no top-level function.
-- E.g. a ~ [F b] is fine
-- but a ~ F b is not
-- * If the equality is representational, rhs has no top-level newtype
-- See Note [No top-level newtypes on RHS of representational
-- equalities] in TcCanonical
-- * If rhs is also a tv, then it is oriented to give best chance of
-- unification happening; eg if rhs is touchable then lhs is too
cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
cc_tyvar :: TcTyVar,
cc_rhs :: TcType, -- Not necessarily function-free (hence not Xi)
-- See invariants above
cc_eq_rel :: EqRel
}
| CFunEqCan { -- F xis ~ fsk
-- Invariants:
-- * isTypeFamilyTyCon cc_fun
-- * typeKind (F xis) = tyVarKind fsk
-- * always Nominal role
-- * always Given or Wanted, never Derived
cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
cc_fun :: TyCon, -- A type function
cc_tyargs :: [Xi], -- cc_tyargs are function-free (hence Xi)
-- Either under-saturated or exactly saturated
-- *never* over-saturated (because if so
-- we should have decomposed)
cc_fsk :: TcTyVar -- [Given] always a FlatSkol skolem
-- [Wanted] always a FlatMetaTv unification variable
-- See Note [The flattening story] in TcFlatten
}
| CNonCanonical { -- See Note [NonCanonical Semantics]
cc_ev :: CtEvidence
}
| CHoleCan { -- See Note [Hole constraints]
-- Treated as an "insoluble" constraint
-- See Note [Insoluble constraints]
cc_ev :: CtEvidence,
cc_occ :: OccName, -- The name of this hole
cc_hole :: HoleSort -- The sort of this hole (expr, type, ...)
}
-- | Used to indicate which sort of hole we have.
data HoleSort = ExprHole -- ^ A hole in an expression (TypedHoles)
| TypeHole -- ^ A hole in a type (PartialTypeSignatures)
{-
Note [Hole constraints]
~~~~~~~~~~~~~~~~~~~~~~~
CHoleCan constraints are used for two kinds of holes,
distinguished by cc_hole:
* For holes in expressions
e.g. f x = g _ x
* For holes in type signatures
e.g. f :: _ -> _
f x = [x,True]
Note [Kind orientation for CTyEqCan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given an equality (t:* ~ s:Open), we can't solve it by updating t:=s,
ragardless of how touchable 't' is, because the kinds don't work.
Instead we absolutely must re-orient it. Reason: if that gets into the
inert set we'll start replacing t's by s's, and that might make a
kind-correct type into a kind error. After re-orienting,
we may be able to solve by updating s:=t.
Hence in a CTyEqCan, (t:k1 ~ xi:k2) we require that k2 is a subkind of k1.
If the two have incompatible kinds, we just don't use a CTyEqCan at all.
See Note [Equalities with incompatible kinds] in TcCanonical
We can't require *equal* kinds, because
* wanted constraints don't necessarily have identical kinds
eg alpha::? ~ Int
* a solved wanted constraint becomes a given
Note [Kind orientation for CFunEqCan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For (F xis ~ rhs) we require that kind(lhs) is a subkind of kind(rhs).
This really only maters when rhs is an Open type variable (since only type
variables have Open kinds):
F ty ~ (a:Open)
which can happen, say, from
f :: F a b
f = undefined -- The a:Open comes from instantiating 'undefined'
Note that the kind invariant is maintained by rewriting.
Eg wanted1 rewrites wanted2; if both were compatible kinds before,
wanted2 will be afterwards. Similarly givens.
Caveat:
- Givens from higher-rank, such as:
type family T b :: * -> * -> *
type instance T Bool = (->)
f :: forall a. ((T a ~ (->)) => ...) -> a -> ...
flop = f (...) True
Whereas we would be able to apply the type instance, we would not be able to
use the given (T Bool ~ (->)) in the body of 'flop'
Note [CIrredEvCan constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CIrredEvCan constraints are used for constraints that are "stuck"
- we can't solve them (yet)
- we can't use them to solve other constraints
- but they may become soluble if we substitute for some
of the type variables in the constraint
Example 1: (c Int), where c :: * -> Constraint. We can't do anything
with this yet, but if later c := Num, *then* we can solve it
Example 2: a ~ b, where a :: *, b :: k, where k is a kind variable
We don't want to use this to substitute 'b' for 'a', in case
'k' is subequently unifed with (say) *->*, because then
we'd have ill-kinded types floating about. Rather we want
to defer using the equality altogether until 'k' get resolved.
Note [Ct/evidence invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If ct :: Ct, then extra fields of 'ct' cache precisely the ctev_pred field
of (cc_ev ct), and is fully rewritten wrt the substitution. Eg for CDictCan,
ctev_pred (cc_ev ct) = (cc_class ct) (cc_tyargs ct)
This holds by construction; look at the unique place where CDictCan is
built (in TcCanonical).
In contrast, the type of the evidence *term* (ccev_evtm or ctev_evar) in
the evidence may *not* be fully zonked; we are careful not to look at it
during constraint solving. See Note [Evidence field of CtEvidence]
-}
mkNonCanonical :: CtEvidence -> Ct
mkNonCanonical ev = CNonCanonical { cc_ev = ev }
mkNonCanonicalCt :: Ct -> Ct
mkNonCanonicalCt ct = CNonCanonical { cc_ev = cc_ev ct }
ctEvidence :: Ct -> CtEvidence
ctEvidence = cc_ev
ctLoc :: Ct -> CtLoc
ctLoc = ctEvLoc . ctEvidence
ctPred :: Ct -> PredType
-- See Note [Ct/evidence invariant]
ctPred ct = ctEvPred (cc_ev ct)
-- | Get the flavour of the given 'Ct'
ctFlavour :: Ct -> CtFlavour
ctFlavour = ctEvFlavour . ctEvidence
-- | Get the equality relation for the given 'Ct'
ctEqRel :: Ct -> EqRel
ctEqRel = ctEvEqRel . ctEvidence
dropDerivedWC :: WantedConstraints -> WantedConstraints
-- See Note [Dropping derived constraints]
dropDerivedWC wc@(WC { wc_simple = simples, wc_insol = insols })
= wc { wc_simple = dropDerivedSimples simples
, wc_insol = dropDerivedInsols insols }
-- The wc_impl implications are already (recursively) filtered
dropDerivedSimples :: Cts -> Cts
dropDerivedSimples simples = filterBag isWantedCt simples
-- simples are all Wanted or Derived
dropDerivedInsols :: Cts -> Cts
-- See Note [Dropping derived constraints]
dropDerivedInsols insols = filterBag keep insols
where -- insols can include Given
keep ct
| isDerivedCt ct = keep_orig (ctLocOrigin (ctLoc ct))
| otherwise = True
keep_orig :: CtOrigin -> Bool
keep_orig (KindEqOrigin {}) = True
keep_orig (GivenOrigin {}) = True
keep_orig (FunDepOrigin1 {}) = True
keep_orig (FunDepOrigin2 {}) = True
-- keep_orig (FunDepOrigin1 _ loc _ _) = keep_orig (ctLocOrigin loc)
-- keep_orig (FunDepOrigin2 _ orig _ _) = keep_orig orig
keep_orig _ = False
{- Note [Dropping derived constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In general we discard derived constraints at the end of constraint solving;
see dropDerivedWC. For example
* If we have an unsolved [W] (Ord a), we don't want to complain about
an unsolved [D] (Eq a) as well.
* If we have [W] a ~ Int, [W] a ~ Bool, improvement will generate
[D] Int ~ Bool, and we don't want to report that because it's incomprehensible.
That is why we don't rewrite wanteds with wanteds!
But (tiresomely) we do keep *some* Derived insolubles:
* Insoluble kind equalities (e.g. [D] * ~ (* -> *)) may arise from
a type equality a ~ Int#, say. In future they'll be Wanted, not Derived,
but at the moment they are Derived.
* Insoluble derived equalities (e.g. [D] Int ~ Bool) may arise from
functional dependency interactions, either between Givens or
Wanteds. It seems sensible to retain these:
- For Givens they reflect unreachable code
- For Wanteds it is arguably better to get a fundep error than
a no-instance error (Trac #9612)
To distinguish these cases we use the CtOrigin.
************************************************************************
* *
CtEvidence
The "flavor" of a canonical constraint
* *
************************************************************************
-}
isWantedCt :: Ct -> Bool
isWantedCt = isWanted . cc_ev
isGivenCt :: Ct -> Bool
isGivenCt = isGiven . cc_ev
isDerivedCt :: Ct -> Bool
isDerivedCt = isDerived . cc_ev
isCTyEqCan :: Ct -> Bool
isCTyEqCan (CTyEqCan {}) = True
isCTyEqCan (CFunEqCan {}) = False
isCTyEqCan _ = False
isCDictCan_Maybe :: Ct -> Maybe Class
isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
isCDictCan_Maybe _ = Nothing
isCIrredEvCan :: Ct -> Bool
isCIrredEvCan (CIrredEvCan {}) = True
isCIrredEvCan _ = False
isCFunEqCan_maybe :: Ct -> Maybe (TyCon, [Type])
isCFunEqCan_maybe (CFunEqCan { cc_fun = tc, cc_tyargs = xis }) = Just (tc, xis)
isCFunEqCan_maybe _ = Nothing
isCFunEqCan :: Ct -> Bool
isCFunEqCan (CFunEqCan {}) = True
isCFunEqCan _ = False
isCNonCanonical :: Ct -> Bool
isCNonCanonical (CNonCanonical {}) = True
isCNonCanonical _ = False
isHoleCt:: Ct -> Bool
isHoleCt (CHoleCan {}) = True
isHoleCt _ = False
isExprHoleCt :: Ct -> Bool
isExprHoleCt (CHoleCan { cc_hole = ExprHole }) = True
isExprHoleCt _ = False
isTypeHoleCt :: Ct -> Bool
isTypeHoleCt (CHoleCan { cc_hole = TypeHole }) = True
isTypeHoleCt _ = False
instance Outputable Ct where
ppr ct = ppr (cc_ev ct) <+> parens (text ct_sort)
where ct_sort = case ct of
CTyEqCan {} -> "CTyEqCan"
CFunEqCan {} -> "CFunEqCan"
CNonCanonical {} -> "CNonCanonical"
CDictCan {} -> "CDictCan"
CIrredEvCan {} -> "CIrredEvCan"
CHoleCan {} -> "CHoleCan"
singleCt :: Ct -> Cts
singleCt = unitBag
andCts :: Cts -> Cts -> Cts
andCts = unionBags
listToCts :: [Ct] -> Cts
listToCts = listToBag
ctsElts :: Cts -> [Ct]
ctsElts = bagToList
consCts :: Ct -> Cts -> Cts
consCts = consBag
snocCts :: Cts -> Ct -> Cts
snocCts = snocBag
extendCtsList :: Cts -> [Ct] -> Cts
extendCtsList cts xs | null xs = cts
| otherwise = cts `unionBags` listToBag xs
andManyCts :: [Cts] -> Cts
andManyCts = unionManyBags
emptyCts :: Cts
emptyCts = emptyBag
isEmptyCts :: Cts -> Bool
isEmptyCts = isEmptyBag
pprCts :: Cts -> SDoc
pprCts cts = vcat (map ppr (bagToList cts))
{-
************************************************************************
* *
Wanted constraints
These are forced to be in TcRnTypes because
TcLclEnv mentions WantedConstraints
WantedConstraint mentions CtLoc
CtLoc mentions ErrCtxt
ErrCtxt mentions TcM
* *
v%************************************************************************
-}
data WantedConstraints
= WC { wc_simple :: Cts -- Unsolved constraints, all wanted
, wc_impl :: Bag Implication
, wc_insol :: Cts -- Insoluble constraints, can be
-- wanted, given, or derived
-- See Note [Insoluble constraints]
}
emptyWC :: WantedConstraints
emptyWC = WC { wc_simple = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
mkSimpleWC :: [CtEvidence] -> WantedConstraints
mkSimpleWC cts
= WC { wc_simple = listToBag (map mkNonCanonical cts)
, wc_impl = emptyBag
, wc_insol = emptyBag }
isEmptyWC :: WantedConstraints -> Bool
isEmptyWC (WC { wc_simple = f, wc_impl = i, wc_insol = n })
= isEmptyBag f && isEmptyBag i && isEmptyBag n
andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
andWC (WC { wc_simple = f1, wc_impl = i1, wc_insol = n1 })
(WC { wc_simple = f2, wc_impl = i2, wc_insol = n2 })
= WC { wc_simple = f1 `unionBags` f2
, wc_impl = i1 `unionBags` i2
, wc_insol = n1 `unionBags` n2 }
unionsWC :: [WantedConstraints] -> WantedConstraints
unionsWC = foldr andWC emptyWC
addSimples :: WantedConstraints -> Bag Ct -> WantedConstraints
addSimples wc cts
= wc { wc_simple = wc_simple wc `unionBags` cts }
-- Consider: Put the new constraints at the front, so they get solved first
addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
addInsols :: WantedConstraints -> Bag Ct -> WantedConstraints
addInsols wc cts
= wc { wc_insol = wc_insol wc `unionBags` cts }
isInsolubleStatus :: ImplicStatus -> Bool
isInsolubleStatus IC_Insoluble = True
isInsolubleStatus _ = False
insolubleImplic :: Implication -> Bool
insolubleImplic ic = isInsolubleStatus (ic_status ic)
insolubleWC :: WantedConstraints -> Bool
insolubleWC (WC { wc_impl = implics, wc_insol = insols })
= anyBag trulyInsoluble insols
|| anyBag insolubleImplic implics
trulyInsoluble :: Ct -> Bool
-- The constraint is in the wc_insol set,
-- but we do not treat as truly isoluble
-- a) type-holes, arising from PartialTypeSignatures,
-- b) superclass constraints, arising from the emitInsoluble
-- in TcInstDcls.tcSuperClasses. In fact only equalities
-- are truly-insoluble.
-- Yuk!
trulyInsoluble insol
= isEqPred (ctPred insol)
&& not (isTypeHoleCt insol)
instance Outputable WantedConstraints where
ppr (WC {wc_simple = s, wc_impl = i, wc_insol = n})
= ptext (sLit "WC") <+> braces (vcat
[ ppr_bag (ptext (sLit "wc_simple")) s
, ppr_bag (ptext (sLit "wc_insol")) n
, ppr_bag (ptext (sLit "wc_impl")) i ])
ppr_bag :: Outputable a => SDoc -> Bag a -> SDoc
ppr_bag doc bag
| isEmptyBag bag = empty
| otherwise = hang (doc <+> equals)
2 (foldrBag (($$) . ppr) empty bag)
{-
************************************************************************
* *
Implication constraints
* *
************************************************************************
-}
data Implication
= Implic {
ic_tclvl :: TcLevel, -- TcLevel: unification variables
-- free in the environment
ic_skols :: [TcTyVar], -- Introduced skolems
ic_info :: SkolemInfo, -- See Note [Skolems in an implication]
-- See Note [Shadowing in a constraint]
ic_given :: [EvVar], -- Given evidence variables
-- (order does not matter)
-- See Invariant (GivenInv) in TcType
ic_no_eqs :: Bool, -- True <=> ic_givens have no equalities, for sure
-- False <=> ic_givens might have equalities
ic_env :: TcLclEnv, -- Gives the source location and error context
-- for the implication, and hence for all the
-- given evidence variables
ic_wanted :: WantedConstraints, -- The wanted
ic_binds :: EvBindsVar, -- Points to the place to fill in the
-- abstraction and bindings
ic_status :: ImplicStatus
}
data ImplicStatus
= IC_Solved -- All wanteds in the tree are solved, all the way down
{ ics_need :: VarSet -- Evidence variables needed by this implication
, ics_dead :: [EvVar] } -- Subset of ic_given that are not needed
-- See Note [Tracking redundant constraints] in TcSimplify
| IC_Insoluble -- At least one insoluble constraint in the tree
| IC_Unsolved -- Neither of the above; might go either way
instance Outputable Implication where
ppr (Implic { ic_tclvl = tclvl, ic_skols = skols
, ic_given = given, ic_no_eqs = no_eqs
, ic_wanted = wanted, ic_status = status
, ic_binds = binds, ic_info = info })
= hang (ptext (sLit "Implic") <+> lbrace)
2 (sep [ ptext (sLit "TcLevel =") <+> ppr tclvl
, ptext (sLit "Skolems =") <+> pprTvBndrs skols
, ptext (sLit "No-eqs =") <+> ppr no_eqs
, ptext (sLit "Status =") <+> ppr status
, hang (ptext (sLit "Given =")) 2 (pprEvVars given)
, hang (ptext (sLit "Wanted =")) 2 (ppr wanted)
, ptext (sLit "Binds =") <+> ppr binds
, pprSkolInfo info ] <+> rbrace)
instance Outputable ImplicStatus where
ppr IC_Insoluble = ptext (sLit "Insoluble")
ppr IC_Unsolved = ptext (sLit "Unsolved")
ppr (IC_Solved { ics_need = vs, ics_dead = dead })
= ptext (sLit "Solved")
<+> (braces $ vcat [ ptext (sLit "Dead givens =") <+> ppr dead
, ptext (sLit "Needed =") <+> ppr vs ])
{-
Note [Needed evidence variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Th ic_need_evs field holds the free vars of ic_binds, and all the
ic_binds in nested implications.
* Main purpose: if one of the ic_givens is not mentioned in here, it
is redundant.
* solveImplication may drop an implication altogether if it has no
remaining 'wanteds'. But we still track the free vars of its
evidence binds, even though it has now disappeared.
Note [Shadowing in a constraint]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We assume NO SHADOWING in a constraint. Specifically
* The unification variables are all implicitly quantified at top
level, and are all unique
* The skolem varibles bound in ic_skols are all freah when the
implication is created.
So we can safely substitute. For example, if we have
forall a. a~Int => ...(forall b. ...a...)...
we can push the (a~Int) constraint inwards in the "givens" without
worrying that 'b' might clash.
Note [Skolems in an implication]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The skolems in an implication are not there to perform a skolem escape
check. That happens because all the environment variables are in the
untouchables, and therefore cannot be unified with anything at all,
let alone the skolems.
Instead, ic_skols is used only when considering floating a constraint
outside the implication in TcSimplify.floatEqualities or
TcSimplify.approximateImplications
Note [Insoluble constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some of the errors that we get during canonicalization are best
reported when all constraints have been simplified as much as
possible. For instance, assume that during simplification the
following constraints arise:
[Wanted] F alpha ~ uf1
[Wanted] beta ~ uf1 beta
When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
we will simply see a message:
'Can't construct the infinite type beta ~ uf1 beta'
and the user has no idea what the uf1 variable is.
Instead our plan is that we will NOT fail immediately, but:
(1) Record the "frozen" error in the ic_insols field
(2) Isolate the offending constraint from the rest of the inerts
(3) Keep on simplifying/canonicalizing
At the end, we will hopefully have substituted uf1 := F alpha, and we
will be able to report a more informative error:
'Can't construct the infinite type beta ~ F alpha beta'
Insoluble constraints *do* include Derived constraints. For example,
a functional dependency might give rise to [D] Int ~ Bool, and we must
report that. If insolubles did not contain Deriveds, reportErrors would
never see it.
************************************************************************
* *
Pretty printing
* *
************************************************************************
-}
pprEvVars :: [EvVar] -> SDoc -- Print with their types
pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
pprEvVarTheta :: [EvVar] -> SDoc
pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
pprEvVarWithType :: EvVar -> SDoc
pprEvVarWithType v = ppr v <+> dcolon <+> pprType (evVarPred v)
{-
************************************************************************
* *
CtEvidence
* *
************************************************************************
Note [Evidence field of CtEvidence]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During constraint solving we never look at the type of ctev_evar;
instead we look at the cte_pred field. The evtm/evar field
may be un-zonked.
Note [Bind new Givens immediately]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For Givens we make new EvVars and bind them immediately. Two main reasons:
* Gain sharing. E.g. suppose we start with g :: C a b, where
class D a => C a b
class (E a, F a) => D a
If we generate all g's superclasses as separate EvTerms we might
get selD1 (selC1 g) :: E a
selD2 (selC1 g) :: F a
selC1 g :: D a
which we could do more economically as:
g1 :: D a = selC1 g
g2 :: E a = selD1 g1
g3 :: F a = selD2 g1
* For *coercion* evidence we *must* bind each given:
class (a~b) => C a b where ....
f :: C a b => ....
Then in f's Givens we have g:(C a b) and the superclass sc(g,0):a~b.
But that superclass selector can't (yet) appear in a coercion
(see evTermCoercion), so the easy thing is to bind it to an Id.
So a Given has EvVar inside it rather that (as previously) an EvTerm.
-}
data CtEvidence
= CtGiven { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
, ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
, ctev_loc :: CtLoc }
-- Truly given, not depending on subgoals
-- NB: Spontaneous unifications belong here
| CtWanted { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
, ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
, ctev_loc :: CtLoc }
-- Wanted goal
| CtDerived { ctev_pred :: TcPredType
, ctev_loc :: CtLoc }
-- A goal that we don't really have to solve and can't immediately
-- rewrite anything other than a derived (there's no evidence!)
-- but if we do manage to solve it may help in solving other goals.
ctEvPred :: CtEvidence -> TcPredType
-- The predicate of a flavor
ctEvPred = ctev_pred
ctEvLoc :: CtEvidence -> CtLoc
ctEvLoc = ctev_loc
-- | Get the equality relation relevant for a 'CtEvidence'
ctEvEqRel :: CtEvidence -> EqRel
ctEvEqRel = predTypeEqRel . ctEvPred
-- | Get the role relevant for a 'CtEvidence'
ctEvRole :: CtEvidence -> Role
ctEvRole = eqRelRole . ctEvEqRel
ctEvTerm :: CtEvidence -> EvTerm
ctEvTerm ev = EvId (ctEvId ev)
ctEvCoercion :: CtEvidence -> TcCoercion
ctEvCoercion ev = mkTcCoVarCo (ctEvId ev)
ctEvId :: CtEvidence -> TcId
ctEvId (CtWanted { ctev_evar = ev }) = ev
ctEvId (CtGiven { ctev_evar = ev }) = ev
ctEvId ctev = pprPanic "ctEvId:" (ppr ctev)
instance Outputable CtEvidence where
ppr fl = case fl of
CtGiven {} -> ptext (sLit "[G]") <+> ppr (ctev_evar fl) <+> ppr_pty
CtWanted {} -> ptext (sLit "[W]") <+> ppr (ctev_evar fl) <+> ppr_pty
CtDerived {} -> ptext (sLit "[D]") <+> text "_" <+> ppr_pty
where ppr_pty = dcolon <+> ppr (ctEvPred fl)
isWanted :: CtEvidence -> Bool
isWanted (CtWanted {}) = True
isWanted _ = False
isGiven :: CtEvidence -> Bool
isGiven (CtGiven {}) = True
isGiven _ = False
isDerived :: CtEvidence -> Bool
isDerived (CtDerived {}) = True
isDerived _ = False
{-
%************************************************************************
%* *
CtFlavour
%* *
%************************************************************************
Just an enum type that tracks whether a constraint is wanted, derived,
or given, when we need to separate that info from the constraint itself.
-}
data CtFlavour = Given | Wanted | Derived
deriving Eq
instance Outputable CtFlavour where
ppr Given = text "[G]"
ppr Wanted = text "[W]"
ppr Derived = text "[D]"
ctEvFlavour :: CtEvidence -> CtFlavour
ctEvFlavour (CtWanted {}) = Wanted
ctEvFlavour (CtGiven {}) = Given
ctEvFlavour (CtDerived {}) = Derived
{-
************************************************************************
* *
SubGoalDepth
* *
************************************************************************
Note [SubGoalDepth]
~~~~~~~~~~~~~~~~~~~
The 'SubGoalDepth' takes care of stopping the constraint solver from looping.
The counter starts at zero and increases. It includes dictionary constraints,
equality simplification, and type family reduction. (Why combine these? Because
it's actually quite easy to mistake one for another, in sufficiently involved
scenarios, like ConstraintKinds.)
The flag -fcontext-stack=n (not very well named!) fixes the maximium
level.
* The counter includes the depth of type class instance declarations. Example:
[W] d{7} : Eq [Int]
That is d's dictionary-constraint depth is 7. If we use the instance
$dfEqList :: Eq a => Eq [a]
to simplify it, we get
d{7} = $dfEqList d'{8}
where d'{8} : Eq Int, and d' has depth 8.
For civilised (decidable) instance declarations, each increase of
depth removes a type constructor from the type, so the depth never
gets big; i.e. is bounded by the structural depth of the type.
* The counter also increments when resolving
equalities involving type functions. Example:
Assume we have a wanted at depth 7:
[W] d{7} : F () ~ a
If thre is an type function equation "F () = Int", this would be rewritten to
[W] d{8} : Int ~ a
and remembered as having depth 8.
Again, without UndecidableInstances, this counter is bounded, but without it
can resolve things ad infinitum. Hence there is a maximum level.
* Lastly, every time an equality is rewritten, the counter increases. Again,
rewriting an equality constraint normally makes progress, but it's possible
the "progress" is just the reduction of an infinitely-reducing type family.
Hence we need to track the rewrites.
When compiling a program requires a greater depth, then GHC recommends turning
off this check entirely by setting -freduction-depth=0. This is because the
exact number that works is highly variable, and is likely to change even between
minor releases. Because this check is solely to prevent infinite compilation
times, it seems safe to disable it when a user has ascertained that their program
doesn't loop at the type level.
-}
-- | See Note [SubGoalDepth]
newtype SubGoalDepth = SubGoalDepth Int
deriving (Eq, Ord, Outputable)
initialSubGoalDepth :: SubGoalDepth
initialSubGoalDepth = SubGoalDepth 0
bumpSubGoalDepth :: SubGoalDepth -> SubGoalDepth
bumpSubGoalDepth (SubGoalDepth n) = SubGoalDepth (n + 1)
subGoalDepthExceeded :: DynFlags -> SubGoalDepth -> Bool
subGoalDepthExceeded dflags (SubGoalDepth d)
= mkIntWithInf d > reductionDepth dflags
{-
************************************************************************
* *
CtLoc
* *
************************************************************************
The 'CtLoc' gives information about where a constraint came from.
This is important for decent error message reporting because
dictionaries don't appear in the original source code.
type will evolve...
-}
data CtLoc = CtLoc { ctl_origin :: CtOrigin
, ctl_env :: TcLclEnv
, ctl_depth :: !SubGoalDepth }
-- The TcLclEnv includes particularly
-- source location: tcl_loc :: RealSrcSpan
-- context: tcl_ctxt :: [ErrCtxt]
-- binder stack: tcl_bndrs :: TcIdBinderStack
-- level: tcl_tclvl :: TcLevel
mkGivenLoc :: TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
mkGivenLoc tclvl skol_info env
= CtLoc { ctl_origin = GivenOrigin skol_info
, ctl_env = env { tcl_tclvl = tclvl }
, ctl_depth = initialSubGoalDepth }
ctLocEnv :: CtLoc -> TcLclEnv
ctLocEnv = ctl_env
ctLocLevel :: CtLoc -> TcLevel
ctLocLevel loc = tcl_tclvl (ctLocEnv loc)
ctLocDepth :: CtLoc -> SubGoalDepth
ctLocDepth = ctl_depth
ctLocOrigin :: CtLoc -> CtOrigin
ctLocOrigin = ctl_origin
ctLocSpan :: CtLoc -> RealSrcSpan
ctLocSpan (CtLoc { ctl_env = lcl}) = tcl_loc lcl
setCtLocSpan :: CtLoc -> RealSrcSpan -> CtLoc
setCtLocSpan ctl@(CtLoc { ctl_env = lcl }) loc = setCtLocEnv ctl (lcl { tcl_loc = loc })
bumpCtLocDepth :: CtLoc -> CtLoc
bumpCtLocDepth loc@(CtLoc { ctl_depth = d }) = loc { ctl_depth = bumpSubGoalDepth d }
setCtLocOrigin :: CtLoc -> CtOrigin -> CtLoc
setCtLocOrigin ctl orig = ctl { ctl_origin = orig }
setCtLocEnv :: CtLoc -> TcLclEnv -> CtLoc
setCtLocEnv ctl env = ctl { ctl_env = env }
pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
= loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
-- Just add information w/o updating the origin!
pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
= loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
pprArising :: CtOrigin -> SDoc
-- Used for the main, top-level error message
-- We've done special processing for TypeEq and FunDep origins
pprArising (TypeEqOrigin {}) = empty
pprArising orig = pprCtOrigin orig
pprArisingAt :: CtLoc -> SDoc
pprArisingAt (CtLoc { ctl_origin = o, ctl_env = lcl})
= sep [ pprCtOrigin o
, text "at" <+> ppr (tcl_loc lcl)]
{-
************************************************************************
* *
SkolemInfo
* *
************************************************************************
-}
-- SkolemInfo gives the origin of *given* constraints
-- a) type variables are skolemised
-- b) an implication constraint is generated
data SkolemInfo
= SigSkol UserTypeCtxt -- A skolem that is created by instantiating
Type -- a programmer-supplied type signature
-- Location of the binding site is on the TyVar
-- The rest are for non-scoped skolems
| ClsSkol Class -- Bound at a class decl
| InstSkol -- Bound at an instance decl
| DataSkol -- Bound at a data type declaration
| FamInstSkol -- Bound at a family instance decl
| PatSkol -- An existential type variable bound by a pattern for
ConLike -- a data constructor with an existential type.
(HsMatchContext Name)
-- e.g. data T = forall a. Eq a => MkT a
-- f (MkT x) = ...
-- The pattern MkT x will allocate an existential type
-- variable for 'a'.
| ArrowSkol -- An arrow form (see TcArrows)
| IPSkol [HsIPName] -- Binding site of an implicit parameter
| RuleSkol RuleName -- The LHS of a RULE
| InferSkol [(Name,TcType)]
-- We have inferred a type for these (mutually-recursivive)
-- polymorphic Ids, and are now checking that their RHS
-- constraints are satisfied.
| BracketSkol -- Template Haskell bracket
| UnifyForAllSkol -- We are unifying two for-all types
[TcTyVar] -- The instantiated skolem variables
TcType -- The instantiated type *inside* the forall
| UnkSkol -- Unhelpful info (until I improve it)
instance Outputable SkolemInfo where
ppr = pprSkolInfo
pprSkolInfo :: SkolemInfo -> SDoc
-- Complete the sentence "is a rigid type variable bound by..."
pprSkolInfo (SigSkol ctxt ty) = pprSigSkolInfo ctxt ty
pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter binding") <> plural ips <+> ptext (sLit "for")
<+> pprWithCommas ppr ips
pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
pprSkolInfo DataSkol = ptext (sLit "a data type declaration")
pprSkolInfo FamInstSkol = ptext (sLit "a family instance declaration")
pprSkolInfo BracketSkol = ptext (sLit "a Template Haskell bracket")
pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
pprSkolInfo ArrowSkol = ptext (sLit "an arrow form")
pprSkolInfo (PatSkol cl mc) = sep [ pprPatSkolInfo cl
, ptext (sLit "in") <+> pprMatchContext mc ]
pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
, vcat [ ppr name <+> dcolon <+> ppr ty
| (name,ty) <- ids ]]
pprSkolInfo (UnifyForAllSkol tvs ty) = ptext (sLit "the type") <+> ppr (mkForAllTys tvs ty)
-- UnkSkol
-- For type variables the others are dealt with by pprSkolTvBinding.
-- For Insts, these cases should not happen
pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
pprSigSkolInfo :: UserTypeCtxt -> Type -> SDoc
pprSigSkolInfo ctxt ty
= case ctxt of
FunSigCtxt f _ -> pp_sig f
_ -> hang (pprUserTypeCtxt ctxt <> colon)
2 (ppr ty)
where
pp_sig f = sep [ ptext (sLit "the type signature for:")
, pprPrefixOcc f <+> dcolon <+> ppr ty ]
pprPatSkolInfo :: ConLike -> SDoc
pprPatSkolInfo (RealDataCon dc)
= sep [ ptext (sLit "a pattern with constructor:")
, nest 2 $ ppr dc <+> dcolon
<+> pprType (dataConUserType dc) <> comma ]
-- pprType prints forall's regardless of -fprint-explict-foralls
-- which is what we want here, since we might be saying
-- type variable 't' is bound by ...
pprPatSkolInfo (PatSynCon ps)
= sep [ ptext (sLit "a pattern with pattern synonym:")
, nest 2 $ ppr ps <+> dcolon
<+> pprType (patSynType ps) <> comma ]
{-
************************************************************************
* *
CtOrigin
* *
************************************************************************
-}
data CtOrigin
= GivenOrigin SkolemInfo
-- All the others are for *wanted* constraints
| OccurrenceOf Name -- Occurrence of an overloaded identifier
| AppOrigin -- An application of some kind
| SpecPragOrigin UserTypeCtxt -- Specialisation pragma for
-- function or instance
| TypeEqOrigin { uo_actual :: TcType
, uo_expected :: TcType }
| KindEqOrigin
TcType TcType -- A kind equality arising from unifying these two types
CtOrigin -- originally arising from this
| CoercibleOrigin TcType TcType -- a Coercible constraint
| IPOccOrigin HsIPName -- Occurrence of an implicit parameter
| LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
| NegateOrigin -- Occurrence of syntactic negation
| ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
| PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
| SectionOrigin
| TupleOrigin -- (..,..)
| ExprSigOrigin -- e :: ty
| PatSigOrigin -- p :: ty
| PatOrigin -- Instantiating a polytyped pattern at a constructor
| RecordUpdOrigin
| ViewPatOrigin
| ScOrigin -- Typechecking superclasses of an instance declaration
| DerivOrigin -- Typechecking deriving
| DerivOriginDC DataCon Int
-- Checking constraints arising from this data con and field index
| DerivOriginCoerce Id Type Type
-- DerivOriginCoerce id ty1 ty2: Trying to coerce class method `id` from
-- `ty1` to `ty2`.
| StandAloneDerivOrigin -- Typechecking stand-alone deriving
| DefaultOrigin -- Typechecking a default decl
| DoOrigin -- Arising from a do expression
| MCompOrigin -- Arising from a monad comprehension
| IfOrigin -- Arising from an if statement
| ProcOrigin -- Arising from a proc expression
| AnnOrigin -- An annotation
| FunDepOrigin1 -- A functional dependency from combining
PredType CtLoc -- This constraint arising from ...
PredType CtLoc -- and this constraint arising from ...
| FunDepOrigin2 -- A functional dependency from combining
PredType CtOrigin -- This constraint arising from ...
PredType SrcSpan -- and this instance
-- We only need a CtOrigin on the first, because the location
-- is pinned on the entire error message
| HoleOrigin
| UnboundOccurrenceOf RdrName
| ListOrigin -- An overloaded list
| StaticOrigin -- A static form
ctoHerald :: SDoc
ctoHerald = ptext (sLit "arising from")
pprCtOrigin :: CtOrigin -> SDoc
pprCtOrigin (GivenOrigin sk) = ctoHerald <+> ppr sk
pprCtOrigin (SpecPragOrigin ctxt)
= case ctxt of
FunSigCtxt n _ -> ptext (sLit "a SPECIALISE pragma for") <+> quotes (ppr n)
SpecInstCtxt -> ptext (sLit "a SPECIALISE INSTANCE pragma")
_ -> ptext (sLit "a SPECIALISE pragma") -- Never happens I think
pprCtOrigin (FunDepOrigin1 pred1 loc1 pred2 loc2)
= hang (ctoHerald <+> ptext (sLit "a functional dependency between constraints:"))
2 (vcat [ hang (quotes (ppr pred1)) 2 (pprArisingAt loc1)
, hang (quotes (ppr pred2)) 2 (pprArisingAt loc2) ])
pprCtOrigin (FunDepOrigin2 pred1 orig1 pred2 loc2)
= hang (ctoHerald <+> ptext (sLit "a functional dependency between:"))
2 (vcat [ hang (ptext (sLit "constraint") <+> quotes (ppr pred1))
2 (pprArising orig1 )
, hang (ptext (sLit "instance") <+> quotes (ppr pred2))
2 (ptext (sLit "at") <+> ppr loc2) ])
pprCtOrigin (KindEqOrigin t1 t2 _)
= hang (ctoHerald <+> ptext (sLit "a kind equality arising from"))
2 (sep [ppr t1, char '~', ppr t2])
pprCtOrigin (UnboundOccurrenceOf name)
= ctoHerald <+> ptext (sLit "an undeclared identifier") <+> quotes (ppr name)
pprCtOrigin (DerivOriginDC dc n)
= hang (ctoHerald <+> ptext (sLit "the") <+> speakNth n
<+> ptext (sLit "field of") <+> quotes (ppr dc))
2 (parens (ptext (sLit "type") <+> quotes (ppr ty)))
where
ty = dataConOrigArgTys dc !! (n-1)
pprCtOrigin (DerivOriginCoerce meth ty1 ty2)
= hang (ctoHerald <+> ptext (sLit "the coercion of the method") <+> quotes (ppr meth))
2 (sep [ text "from type" <+> quotes (ppr ty1)
, nest 2 $ text "to type" <+> quotes (ppr ty2) ])
pprCtOrigin (CoercibleOrigin ty1 ty2)
= hang (ctoHerald <+> text "trying to show that the representations of")
2 (quotes (ppr ty1) <+> text "and" $$
quotes (ppr ty2) <+> text "are the same")
pprCtOrigin simple_origin
= ctoHerald <+> pprCtO simple_origin
----------------
pprCtO :: CtOrigin -> SDoc -- Ones that are short one-liners
pprCtO (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
pprCtO AppOrigin = ptext (sLit "an application")
pprCtO (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
pprCtO RecordUpdOrigin = ptext (sLit "a record update")
pprCtO ExprSigOrigin = ptext (sLit "an expression type signature")
pprCtO PatSigOrigin = ptext (sLit "a pattern type signature")
pprCtO PatOrigin = ptext (sLit "a pattern")
pprCtO ViewPatOrigin = ptext (sLit "a view pattern")
pprCtO IfOrigin = ptext (sLit "an if statement")
pprCtO (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
pprCtO (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
pprCtO (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
pprCtO SectionOrigin = ptext (sLit "an operator section")
pprCtO TupleOrigin = ptext (sLit "a tuple")
pprCtO NegateOrigin = ptext (sLit "a use of syntactic negation")
pprCtO ScOrigin = ptext (sLit "the superclasses of an instance declaration")
pprCtO DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
pprCtO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
pprCtO DefaultOrigin = ptext (sLit "a 'default' declaration")
pprCtO DoOrigin = ptext (sLit "a do statement")
pprCtO MCompOrigin = ptext (sLit "a statement in a monad comprehension")
pprCtO ProcOrigin = ptext (sLit "a proc expression")
pprCtO (TypeEqOrigin t1 t2) = ptext (sLit "a type equality") <+> sep [ppr t1, char '~', ppr t2]
pprCtO AnnOrigin = ptext (sLit "an annotation")
pprCtO HoleOrigin = ptext (sLit "a use of") <+> quotes (ptext $ sLit "_")
pprCtO ListOrigin = ptext (sLit "an overloaded list")
pprCtO StaticOrigin = ptext (sLit "a static form")
pprCtO _ = panic "pprCtOrigin"
{-
Constraint Solver Plugins
-------------------------
-}
type TcPluginSolver = [Ct] -- given
-> [Ct] -- derived
-> [Ct] -- wanted
-> TcPluginM TcPluginResult
newtype TcPluginM a = TcPluginM (TcM a)
instance Functor TcPluginM where
fmap = liftM
instance Applicative TcPluginM where
pure = return
(<*>) = ap
instance Monad TcPluginM where
return x = TcPluginM (return x)
fail x = TcPluginM (fail x)
TcPluginM m >>= k =
TcPluginM (do a <- m
let TcPluginM m1 = k a
m1)
runTcPluginM :: TcPluginM a -> TcM a
runTcPluginM (TcPluginM m) = m
-- | This function provides an escape for direct access to
-- the 'TcM` monad. It should not be used lightly, and
-- the provided 'TcPluginM' API should be favoured instead.
unsafeTcPluginTcM :: TcM a -> TcPluginM a
unsafeTcPluginTcM = TcPluginM
data TcPlugin = forall s. TcPlugin
{ tcPluginInit :: TcPluginM s
-- ^ Initialize plugin, when entering type-checker.
, tcPluginSolve :: s -> TcPluginSolver
-- ^ Solve some constraints.
-- TODO: WRITE MORE DETAILS ON HOW THIS WORKS.
, tcPluginStop :: s -> TcPluginM ()
-- ^ Clean up after the plugin, when exiting the type-checker.
}
data TcPluginResult
= TcPluginContradiction [Ct]
-- ^ The plugin found a contradiction.
-- The returned constraints are removed from the inert set,
-- and recorded as insoluable.
| TcPluginOk [(EvTerm,Ct)] [Ct]
-- ^ The first field is for constraints that were solved.
-- These are removed from the inert set,
-- and the evidence for them is recorded.
-- The second field contains new work, that should be processed by
-- the constraint solver.
| fmthoma/ghc | compiler/typecheck/TcRnTypes.hs | bsd-3-clause | 90,836 | 0 | 16 | 27,061 | 10,760 | 6,186 | 4,574 | 875 | 5 |
{-# LANGUAGE OverloadedStrings, Rank2Types, LiberalTypeSynonyms #-}
module Circles (circlesClass) where
import Control.Applicative
import Control.Monad
import Data.String (fromString)
import Data.Void
import Lens.Family2
import React
-- model
data Circ = C1 | C2 | C3 | C4 deriving (Eq, Show)
data CircState = CircState Circ [Circ]
data AnimState = AnimState Color Color Color Color (Double, Double)
data Transition = SingleFlash Circ | RepeatingFlash
coord :: Circ -> (Double, Double)
coord C1 = (-1, -1)
coord C2 = (1, -1)
coord C3 = (1, 1)
coord C4 = (-1, 1)
circOrder :: [Circ]
circOrder = cycle [C1, C3, C2, C4]
initialState :: CircState
initialState = CircState C1 (tail circOrder)
initialAnimationState :: AnimState
initialAnimationState =
AnimState animZero animZero animZero animZero (0, 0)
colorL :: Circ -> Lens' AnimState Color
colorL C1 f (AnimState c1 c2 c3 c4 pt) =
(\x -> AnimState x c2 c3 c4 pt) <$> f c1
colorL C2 f (AnimState c1 c2 c3 c4 pt) =
(\x -> AnimState c1 x c3 c4 pt) <$> f c2
colorL C3 f (AnimState c1 c2 c3 c4 pt) =
(\x -> AnimState c1 c2 x c4 pt) <$> f c3
colorL C4 f (AnimState c1 c2 c3 c4 pt) =
(\x -> AnimState c1 c2 c3 x pt) <$> f c4
ptL :: Lens' AnimState (Double, Double)
ptL f (AnimState c1 c2 c3 c4 pt) = AnimState c1 c2 c3 c4 <$> f pt
-- update
transitionFn :: Transition
-> CircState
-> (CircState, [AnimConfig Transition AnimState])
transitionFn flash (CircState c' cs) =
let colorTrans = fillorange `animSub` fillblue
(newLoc, cs', newSignal) = case flash of
RepeatingFlash -> (head cs, tail cs, Just RepeatingFlash)
SingleFlash c'' -> (c'', cs, Nothing)
coordTrans = coord newLoc `animSub` coord c'
in ( CircState newLoc cs'
, [ AnimConfig
800
(colorTrans, animZero)
(colorL newLoc)
EaseInQuad
(const newSignal)
, AnimConfig
2000
(coordTrans, animZero)
ptL
EaseInOutQuad
(const Nothing)
]
)
-- view
fillblue, fillorange :: Color
fillblue = Color 85 161 220
fillorange = Color 245 175 51
fill_' = fill_ . fromString . show
circ :: Circ -> Color -> ReactNode CircState
circ c = circ' True (const (Just (SingleFlash c))) (coord c)
circ' :: Bool
-> (MouseEvent -> Maybe Transition)
-> (Double, Double)
-> Color
-> ReactNode CircState
circ' clickable handler (x, y) color =
let lst = [ cx_ x
, cy_ y
, r_ 0.15
, fill_' color
]
lst' = [ class_ "hover-circ"
, onClick handler
]
++ lst
in circle_ (if clickable then lst' else lst)
circlesClass :: [AttrOrHandler Void] -> () -> ReactNode Void
circlesClass = classLeaf $ smartClass
{ name = "Circles"
, transition = transitionFn
, initialState = initialState
, renderFn = \_ (CircState c _) -> div_ [] $ do
-- AnimState c1 c2 c3 c4 trans <- getAnimationState
svg_ [ width_ 600
, height_ 600
, viewBox_ "-1.5 -1.5 3 3"
] $ do
circ C1 (fillblue `animAdd` c1)
circ C2 (fillblue `animAdd` c2)
circ C3 (fillblue `animAdd` c3)
circ C4 (fillblue `animAdd` c4)
circ' False (const Nothing) (coord c `animSub` trans) fillblue
}
| adarqui/react-haskell | example/animation/Circles.hs | mit | 3,505 | 0 | 18 | 1,110 | 1,203 | 643 | 560 | 92 | 2 |
-- |
-- Module : Criterion.Monad
-- Copyright : (c) 2009 Neil Brown
--
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- The environment in which most criterion code executes.
module Criterion.Monad
(
Criterion
, withConfig
, getGen
, getOverhead
) where
import Control.Monad.Reader (asks, runReaderT)
import Control.Monad.Trans (liftIO)
import Control.Monad (when)
import Criterion.Measurement (measure, runBenchmark, secs)
import Criterion.Monad.Internal (Criterion(..), Crit(..))
import Criterion.Types hiding (measure)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Statistics.Regression (olsRegress)
import System.Random.MWC (GenIO, createSystemRandom)
import qualified Data.Vector.Generic as G
-- | Run a 'Criterion' action with the given 'Config'.
withConfig :: Config -> Criterion a -> IO a
withConfig cfg (Criterion act) = do
g <- newIORef Nothing
o <- newIORef Nothing
runReaderT act (Crit cfg g o)
-- | Return a random number generator, creating one if necessary.
--
-- This is not currently thread-safe, but in a harmless way (we might
-- call 'createSystemRandom' more than once if multiple threads race).
getGen :: Criterion GenIO
getGen = memoise gen createSystemRandom
-- | Return an estimate of the measurement overhead.
getOverhead :: Criterion Double
getOverhead = do
verbose <- asks ((== Verbose) . verbosity)
memoise overhead $ do
(meas,_) <- runBenchmark (whnfIO $ measure (whnfIO $ return ()) 1) 1
let metric get = G.convert . G.map get $ meas
let o = G.head . fst $
olsRegress [metric (fromIntegral . measIters)] (metric measTime)
when verbose . liftIO $
putStrLn $ "measurement overhead " ++ secs o
return o
-- | Memoise the result of an 'IO' action.
--
-- This is not currently thread-safe, but hopefully in a harmless way.
-- We might call the given action more than once if multiple threads
-- race, so our caller's job is to write actions that can be run
-- multiple times safely.
memoise :: (Crit -> IORef (Maybe a)) -> IO a -> Criterion a
memoise ref generate = do
r <- Criterion $ asks ref
liftIO $ do
mv <- readIORef r
case mv of
Just rv -> return rv
Nothing -> do
rv <- generate
writeIORef r (Just rv)
return rv
| paulolieuthier/criterion | Criterion/Monad.hs | bsd-2-clause | 2,369 | 10 | 28 | 499 | 581 | 311 | 270 | 45 | 2 |
{- $Id: testAFRPMain.hs,v 1.9 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* A F R P *
* *
* Module: testAFRPMain *
* Purpose: Main driver routine for running tests. *
* Authors: Henrik Nilsson and Antony Courtney *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module Main where
import AFRPTests
import System.IO
import System.Environment (getArgs, getProgName)
-- main = runTests
-- main = runSpaceTests
data TestFlags = TestFlags { tReg :: Bool -- run regression tests
, tSpace :: Bool -- run space tests
, tHelp :: Bool -- print usage and exit
}
defFlags = TestFlags { tReg = False, tSpace = False, tHelp = False}
allFlags = TestFlags { tReg = True, tSpace = True, tHelp = False}
parseArgs :: TestFlags -> [String] -> Either TestFlags String
parseArgs flags [] = Left flags
parseArgs flags (arg:args) =
case arg of
"-r" -> parseArgs (flags {tReg = True}) args
"-s" -> parseArgs (flags {tSpace = True}) args
"-h" -> parseArgs (flags {tHelp = True}) args
_ -> Right ("invalid argument: " ++ arg)
usage :: String -> Maybe String -> IO ()
usage pname mbEmsg = do
case mbEmsg of
(Just emsg) -> hPutStrLn stderr (pname ++ ": " ++ emsg)
_ -> return ()
hPutStrLn stderr ("usage: " ++ pname ++ " [-r] [-s] [-h]")
hPutStrLn stderr "\t-s run space tests"
hPutStrLn stderr "\t-r run regression tests"
hPutStrLn stderr "\t-h print this help message"
hPutStrLn stderr "(no arguments runs all tests.)"
main :: IO ()
main = do
pname <- getProgName
args <- getArgs
let eFlags = if (length args) < 1
then (Left allFlags)
else parseArgs defFlags args
case eFlags of
(Left tFlags) ->
if (tHelp tFlags)
then usage pname Nothing
else do
if (tReg tFlags)
then runRegTests
else return ()
if (tSpace tFlags)
then runSpaceTests
else return ()
(Right emsg) -> usage pname (Just emsg)
| ony/Yampa-core | tests/testAFRPMain.hs | bsd-3-clause | 2,541 | 2 | 15 | 945 | 549 | 288 | 261 | 46 | 6 |
{-| General purpose utilities
The names in this module clash heavily with the Haskell Prelude, so I
recommend the following import scheme:
> import Pipes
> import qualified Pipes.Prelude as P -- or use any other qualifier you prefer
Note that 'String'-based 'IO' is inefficient. The 'String'-based utilities
in this module exist only for simple demonstrations without incurring a
dependency on the @text@ package.
Also, 'stdinLn' and 'stdoutLn' remove and add newlines, respectively. This
behavior is intended to simplify examples. The corresponding @stdin@ and
@stdout@ utilities from @pipes-bytestring@ and @pipes-text@ preserve
newlines.
-}
{-# LANGUAGE RankNTypes, Trustworthy #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Pipes.Prelude (
-- * Producers
-- $producers
stdinLn
, readLn
, fromHandle
, repeatM
, replicateM
-- * Consumers
-- $consumers
, stdoutLn
, print
, toHandle
, drain
-- * Pipes
-- $pipes
, map
, mapM
, sequence
, mapFoldable
, filter
, filterM
, take
, takeWhile
, drop
, dropWhile
, concat
, elemIndices
, findIndices
, scan
, scanM
, chain
, read
, show
-- * Folds
-- $folds
, fold
, fold'
, foldM
, foldM'
, all
, any
, and
, or
, elem
, notElem
, find
, findIndex
, head
, index
, last
, length
, maximum
, minimum
, null
, sum
, product
, toList
, toListM
-- * Zips
, zip
, zipWith
-- * Utilities
, tee
, generalize
) where
import Control.Exception (throwIO, try)
import Control.Monad (liftM, replicateM_, when, unless)
import Control.Monad.Trans.State.Strict (get, put)
import Data.Functor.Identity (Identity, runIdentity)
import Foreign.C.Error (Errno(Errno), ePIPE)
import Pipes
import Pipes.Core
import Pipes.Internal
import Pipes.Lift (evalStateP)
import qualified GHC.IO.Exception as G
import qualified System.IO as IO
import qualified Prelude
import Prelude hiding (
all
, and
, any
, concat
, drop
, dropWhile
, elem
, filter
, head
, last
, length
, map
, mapM
, maximum
, minimum
, notElem
, null
, or
, print
, product
, read
, readLn
, sequence
, show
, sum
, take
, takeWhile
, zip
, zipWith
)
{- $producers
Use 'for' loops to iterate over 'Producer's whenever you want to perform the
same action for every element:
> -- Echo all lines from standard input to standard output
> runEffect $ for P.stdinLn $ \str -> do
> lift $ putStrLn str
... or more concisely:
>>> runEffect $ for P.stdinLn (lift . putStrLn)
Test<Enter>
Test
ABC<Enter>
ABC
...
-}
{-| Read 'String's from 'IO.stdin' using 'getLine'
Terminates on end of input
-}
stdinLn :: MonadIO m => Producer' String m ()
stdinLn = fromHandle IO.stdin
{-# INLINABLE stdinLn #-}
-- | 'read' values from 'IO.stdin', ignoring failed parses
readLn :: (MonadIO m, Read a) => Producer' a m ()
readLn = stdinLn >-> read
{-# INLINABLE readLn #-}
{-| Read 'String's from a 'IO.Handle' using 'IO.hGetLine'
Terminates on end of input
-}
fromHandle :: MonadIO m => IO.Handle -> Producer' String m ()
fromHandle h = go
where
go = do
eof <- liftIO $ IO.hIsEOF h
unless eof $ do
str <- liftIO $ IO.hGetLine h
yield str
go
{-# INLINABLE fromHandle #-}
-- | Repeat a monadic action indefinitely, 'yield'ing each result
repeatM :: Monad m => m a -> Producer' a m r
repeatM m = lift m >~ cat
{-# INLINABLE repeatM #-}
{-# RULES
"repeatM m >-> p" forall m p . repeatM m >-> p = lift m >~ p
#-}
{-| Repeat a monadic action a fixed number of times, 'yield'ing each result
> replicateM 0 x = return ()
>
> replicateM (m + n) x = replicateM m x >> replicateM n x -- 0 <= {m,n}
-}
replicateM :: Monad m => Int -> m a -> Producer' a m ()
replicateM n m = lift m >~ take n
{-# INLINABLE replicateM #-}
{- $consumers
Feed a 'Consumer' the same value repeatedly using ('>~'):
>>> runEffect $ lift getLine >~ P.stdoutLn
Test<Enter>
Test
ABC<Enter>
ABC
...
-}
{-| Write 'String's to 'IO.stdout' using 'putStrLn'
Unlike 'toHandle', 'stdoutLn' gracefully terminates on a broken output pipe
-}
stdoutLn :: MonadIO m => Consumer' String m ()
stdoutLn = go
where
go = do
str <- await
x <- liftIO $ try (putStrLn str)
case x of
Left (G.IOError { G.ioe_type = G.ResourceVanished
, G.ioe_errno = Just ioe })
| Errno ioe == ePIPE
-> return ()
Left e -> liftIO (throwIO e)
Right () -> go
{-# INLINABLE stdoutLn #-}
-- | 'print' values to 'IO.stdout'
print :: (MonadIO m, Show a) => Consumer' a m r
print = for cat (\a -> liftIO (Prelude.print a))
{-# INLINABLE print #-}
{-# RULES
"p >-> print" forall p .
p >-> print = for p (\a -> liftIO (Prelude.print a))
#-}
-- | Write 'String's to a 'IO.Handle' using 'IO.hPutStrLn'
toHandle :: MonadIO m => IO.Handle -> Consumer' String m r
toHandle handle = for cat (\str -> liftIO (IO.hPutStrLn handle str))
{-# INLINABLE toHandle #-}
{-# RULES
"p >-> toHandle handle" forall p handle .
p >-> toHandle handle = for p (\str -> liftIO (IO.hPutStrLn handle str))
#-}
-- | 'discard' all incoming values
drain :: Monad m => Consumer' a m r
drain = for cat discard
{-# INLINABLE drain #-}
{-# RULES
"p >-> drain" forall p .
p >-> drain = for p discard
#-}
{- $pipes
Use ('>->') to connect 'Producer's, 'Pipe's, and 'Consumer's:
>>> runEffect $ P.stdinLn >-> P.takeWhile (/= "quit") >-> P.stdoutLn
Test<Enter>
Test
ABC<Enter>
ABC
quit<Enter>
>>>
-}
{-| Apply a function to all values flowing downstream
> map id = cat
>
> map (g . f) = map f >-> map g
-}
map :: Monad m => (a -> b) -> Pipe a b m r
map f = for cat (\a -> yield (f a))
{-# INLINABLE map #-}
{-# RULES
"p >-> map f" forall p f . p >-> map f = for p (\a -> yield (f a))
; "map f >-> p" forall p f . map f >-> p = (do
a <- await
return (f a) ) >~ p
#-}
{-| Apply a monadic function to all values flowing downstream
> mapM return = cat
>
> mapM (f >=> g) = mapM f >-> mapM g
-}
mapM :: Monad m => (a -> m b) -> Pipe a b m r
mapM f = for cat $ \a -> do
b <- lift (f a)
yield b
{-# INLINABLE mapM #-}
{-# RULES
"p >-> mapM f" forall p f . p >-> mapM f = for p (\a -> do
b <- lift (f a)
yield b )
; "mapM f >-> p" forall p f . mapM f >-> p = (do
a <- await
b <- lift (f a)
return b ) >~ p
#-}
-- | Convert a stream of actions to a stream of values
sequence :: Monad m => Pipe (m a) a m r
sequence = mapM id
{-# INLINABLE sequence #-}
{- | Apply a function to all values flowing downstream, and
forward each element of the result.
-}
mapFoldable :: (Monad m, Foldable t) => (a -> t b) -> Pipe a b m r
mapFoldable f = for cat (\a -> each (f a))
{-# INLINABLE mapFoldable #-}
{-# RULES
"p >-> mapFoldable f" forall p f .
p >-> mapFoldable f = for p (\a -> each (f a))
#-}
{-| @(filter predicate)@ only forwards values that satisfy the predicate.
> filter (pure True) = cat
>
> filter (liftA2 (&&) p1 p2) = filter p1 >-> filter p2
-}
filter :: Monad m => (a -> Bool) -> Pipe a a m r
filter predicate = for cat $ \a -> when (predicate a) (yield a)
{-# INLINABLE filter #-}
{-# RULES
"p >-> filter predicate" forall p predicate.
p >-> filter predicate = for p (\a -> when (predicate a) (yield a))
#-}
{-| @(filterM predicate)@ only forwards values that satisfy the monadic
predicate
> filterM (pure (pure True)) = cat
>
> filterM (liftA2 (liftA2 (&&)) p1 p2) = filterM p1 >-> filterM p2
-}
filterM :: Monad m => (a -> m Bool) -> Pipe a a m r
filterM predicate = for cat $ \a -> do
b <- lift (predicate a)
when b (yield a)
{-# INLINABLE filterM #-}
{-# RULES
"p >-> filterM predicate" forall p predicate .
p >-> filterM predicate = for p (\a -> do
b <- lift (predicate a)
when b (yield a) )
#-}
{-| @(take n)@ only allows @n@ values to pass through
> take 0 = return ()
>
> take (m + n) = take m >> take n
> take <infinity> = cat
>
> take (min m n) = take m >-> take n
-}
take :: Monad m => Int -> Pipe a a m ()
take n = replicateM_ n $ do
a <- await
yield a
{-# INLINABLE take #-}
{-| @(takeWhile p)@ allows values to pass downstream so long as they satisfy
the predicate @p@.
> takeWhile (pure True) = cat
>
> takeWhile (liftA2 (&&) p1 p2) = takeWhile p1 >-> takeWhile p2
-}
takeWhile :: Monad m => (a -> Bool) -> Pipe a a m ()
takeWhile predicate = go
where
go = do
a <- await
if (predicate a)
then do
yield a
go
else return ()
{-# INLINABLE takeWhile #-}
{-| @(drop n)@ discards @n@ values going downstream
> drop 0 = cat
>
> drop (m + n) = drop m >-> drop n
-}
drop :: Monad m => Int -> Pipe a a m r
drop n = do
replicateM_ n await
cat
{-# INLINABLE drop #-}
{-| @(dropWhile p)@ discards values going downstream until one violates the
predicate @p@.
> dropWhile (pure False) = cat
>
> dropWhile (liftA2 (||) p1 p2) = dropWhile p1 >-> dropWhile p2
-}
dropWhile :: Monad m => (a -> Bool) -> Pipe a a m r
dropWhile predicate = go
where
go = do
a <- await
if (predicate a)
then go
else do
yield a
cat
{-# INLINABLE dropWhile #-}
-- | Flatten all 'Foldable' elements flowing downstream
concat :: (Monad m, Foldable f) => Pipe (f a) a m r
concat = for cat each
{-# INLINABLE concat #-}
{-# RULES
"p >-> concat" forall p . p >-> concat = for p each
#-}
-- | Outputs the indices of all elements that match the given element
elemIndices :: (Monad m, Eq a) => a -> Pipe a Int m r
elemIndices a = findIndices (a ==)
{-# INLINABLE elemIndices #-}
-- | Outputs the indices of all elements that satisfied the predicate
findIndices :: Monad m => (a -> Bool) -> Pipe a Int m r
findIndices predicate = loop 0
where
loop n = do
a <- await
when (predicate a) (yield n)
loop $! n + 1
{-# INLINABLE findIndices #-}
{-| Strict left scan
> Control.Foldl.purely scan :: Monad m => Fold a b -> Pipe a b m r
-}
scan :: Monad m => (x -> a -> x) -> x -> (x -> b) -> Pipe a b m r
scan step begin done = loop begin
where
loop x = do
yield (done x)
a <- await
let x' = step x a
loop $! x'
{-# INLINABLE scan #-}
{-| Strict, monadic left scan
> Control.Foldl.impurely scan :: Monad m => FoldM a m b -> Pipe a b m r
-}
scanM :: Monad m => (x -> a -> m x) -> m x -> (x -> m b) -> Pipe a b m r
scanM step begin done = do
x <- lift begin
loop x
where
loop x = do
b <- lift (done x)
yield b
a <- await
x' <- lift (step x a)
loop $! x'
{-# INLINABLE scanM #-}
{-| Apply an action to all values flowing downstream
> chain (pure (return ())) = cat
>
> chain (liftA2 (>>) m1 m2) = chain m1 >-> chain m2
-}
chain :: Monad m => (a -> m ()) -> Pipe a a m r
chain f = for cat $ \a -> do
lift (f a)
yield a
{-# INLINABLE chain #-}
{-# RULES
"p >-> chain f" forall p f .
p >-> chain f = for p (\a -> do
lift (f a)
yield a )
; "chain f >-> p" forall p f .
chain f >-> p = (do
a <- await
lift (f a)
return a ) >~ p
#-}
-- | Parse 'Read'able values, only forwarding the value if the parse succeeds
read :: (Monad m, Read a) => Pipe String a m r
read = for cat $ \str -> case (reads str) of
[(a, "")] -> yield a
_ -> return ()
{-# INLINABLE read #-}
{-# RULES
"p >-> read" forall p .
p >-> read = for p (\str -> case (reads str) of
[(a, "")] -> yield a
_ -> return () )
#-}
-- | Convert 'Show'able values to 'String's
show :: (Monad m, Show a) => Pipe a String m r
show = map Prelude.show
{-# INLINABLE show #-}
{- $folds
Use these to fold the output of a 'Producer'. Many of these folds will stop
drawing elements if they can compute their result early, like 'any':
>>> P.any null P.stdinLn
Test<Enter>
ABC<Enter>
<Enter>
True
>>>
-}
{-| Strict fold of the elements of a 'Producer'
> Control.Foldl.purely fold :: Monad m => Fold a b -> Producer a m () -> m b
-}
fold :: Monad m => (x -> a -> x) -> x -> (x -> b) -> Producer a m () -> m b
fold step begin done p0 = loop p0 begin
where
loop p x = case p of
Request v _ -> closed v
Respond a fu -> loop (fu ()) $! step x a
M m -> m >>= \p' -> loop p' x
Pure _ -> return (done x)
{-# INLINABLE fold #-}
{-| Strict fold of the elements of a 'Producer' that preserves the return value
> Control.Foldl.purely fold' :: Monad m => Fold a b -> Producer a m r -> m (b, r)
-}
fold' :: Monad m => (x -> a -> x) -> x -> (x -> b) -> Producer a m r -> m (b, r)
fold' step begin done p0 = loop p0 begin
where
loop p x = case p of
Request v _ -> closed v
Respond a fu -> loop (fu ()) $! step x a
M m -> m >>= \p' -> loop p' x
Pure r -> return (done x, r)
{-# INLINABLE fold' #-}
{-| Strict, monadic fold of the elements of a 'Producer'
> Control.Foldl.impurely foldM :: Monad m => FoldM a b -> Producer a m () -> m b
-}
foldM
:: Monad m
=> (x -> a -> m x) -> m x -> (x -> m b) -> Producer a m () -> m b
foldM step begin done p0 = do
x0 <- begin
loop p0 x0
where
loop p x = case p of
Request v _ -> closed v
Respond a fu -> do
x' <- step x a
loop (fu ()) $! x'
M m -> m >>= \p' -> loop p' x
Pure _ -> done x
{-# INLINABLE foldM #-}
{-| Strict, monadic fold of the elements of a 'Producer'
> Control.Foldl.impurely foldM' :: Monad m => FoldM a b -> Producer a m r -> m (b, r)
-}
foldM'
:: Monad m
=> (x -> a -> m x) -> m x -> (x -> m b) -> Producer a m r -> m (b, r)
foldM' step begin done p0 = do
x0 <- begin
loop p0 x0
where
loop p x = case p of
Request v _ -> closed v
Respond a fu -> do
x' <- step x a
loop (fu ()) $! x'
M m -> m >>= \p' -> loop p' x
Pure r -> do
b <- done x
return (b, r)
{-# INLINABLE foldM' #-}
{-| @(all predicate p)@ determines whether all the elements of @p@ satisfy the
predicate.
-}
all :: Monad m => (a -> Bool) -> Producer a m () -> m Bool
all predicate p = null $ p >-> filter (\a -> not (predicate a))
{-# INLINABLE all #-}
{-| @(any predicate p)@ determines whether any element of @p@ satisfies the
predicate.
-}
any :: Monad m => (a -> Bool) -> Producer a m () -> m Bool
any predicate p = liftM not $ null (p >-> filter predicate)
{-# INLINABLE any #-}
-- | Determines whether all elements are 'True'
and :: Monad m => Producer Bool m () -> m Bool
and = all id
{-# INLINABLE and #-}
-- | Determines whether any element is 'True'
or :: Monad m => Producer Bool m () -> m Bool
or = any id
{-# INLINABLE or #-}
{-| @(elem a p)@ returns 'True' if @p@ has an element equal to @a@, 'False'
otherwise
-}
elem :: (Monad m, Eq a) => a -> Producer a m () -> m Bool
elem a = any (a ==)
{-# INLINABLE elem #-}
{-| @(notElem a)@ returns 'False' if @p@ has an element equal to @a@, 'True'
otherwise
-}
notElem :: (Monad m, Eq a) => a -> Producer a m () -> m Bool
notElem a = all (a /=)
{-# INLINABLE notElem #-}
-- | Find the first element of a 'Producer' that satisfies the predicate
find :: Monad m => (a -> Bool) -> Producer a m () -> m (Maybe a)
find predicate p = head (p >-> filter predicate)
{-# INLINABLE find #-}
{-| Find the index of the first element of a 'Producer' that satisfies the
predicate
-}
findIndex :: Monad m => (a -> Bool) -> Producer a m () -> m (Maybe Int)
findIndex predicate p = head (p >-> findIndices predicate)
{-# INLINABLE findIndex #-}
-- | Retrieve the first element from a 'Producer'
head :: Monad m => Producer a m () -> m (Maybe a)
head p = do
x <- next p
return $ case x of
Left _ -> Nothing
Right (a, _) -> Just a
{-# INLINABLE head #-}
-- | Index into a 'Producer'
index :: Monad m => Int -> Producer a m () -> m (Maybe a)
index n p = head (p >-> drop n)
{-# INLINABLE index #-}
-- | Retrieve the last element from a 'Producer'
last :: Monad m => Producer a m () -> m (Maybe a)
last p0 = do
x <- next p0
case x of
Left _ -> return Nothing
Right (a, p') -> loop a p'
where
loop a p = do
x <- next p
case x of
Left _ -> return (Just a)
Right (a', p') -> loop a' p'
{-# INLINABLE last #-}
-- | Count the number of elements in a 'Producer'
length :: Monad m => Producer a m () -> m Int
length = fold (\n _ -> n + 1) 0 id
{-# INLINABLE length #-}
-- | Find the maximum element of a 'Producer'
maximum :: (Monad m, Ord a) => Producer a m () -> m (Maybe a)
maximum = fold step Nothing id
where
step x a = Just $ case x of
Nothing -> a
Just a' -> max a a'
{-# INLINABLE maximum #-}
-- | Find the minimum element of a 'Producer'
minimum :: (Monad m, Ord a) => Producer a m () -> m (Maybe a)
minimum = fold step Nothing id
where
step x a = Just $ case x of
Nothing -> a
Just a' -> min a a'
{-# INLINABLE minimum #-}
-- | Determine if a 'Producer' is empty
null :: Monad m => Producer a m () -> m Bool
null p = do
x <- next p
return $ case x of
Left _ -> True
Right _ -> False
{-# INLINABLE null #-}
-- | Compute the sum of the elements of a 'Producer'
sum :: (Monad m, Num a) => Producer a m () -> m a
sum = fold (+) 0 id
{-# INLINABLE sum #-}
-- | Compute the product of the elements of a 'Producer'
product :: (Monad m, Num a) => Producer a m () -> m a
product = fold (*) 1 id
{-# INLINABLE product #-}
-- | Convert a pure 'Producer' into a list
toList :: Producer a Identity () -> [a]
toList = loop
where
loop p = case p of
Request v _ -> closed v
Respond a fu -> a:loop (fu ())
M m -> loop (runIdentity m)
Pure _ -> []
{-# INLINABLE toList #-}
{-| Convert an effectful 'Producer' into a list
Note: 'toListM' is not an idiomatic use of @pipes@, but I provide it for
simple testing purposes. Idiomatic @pipes@ style consumes the elements
immediately as they are generated instead of loading all elements into
memory.
-}
toListM :: Monad m => Producer a m () -> m [a]
toListM = loop
where
loop p = case p of
Request v _ -> closed v
Respond a fu -> do
as <- loop (fu ())
return (a:as)
M m -> m >>= loop
Pure _ -> return []
{-# INLINABLE toListM #-}
-- | Zip two 'Producer's
zip :: Monad m
=> (Producer a m r)
-> (Producer b m r)
-> (Producer' (a, b) m r)
zip = zipWith (,)
{-# INLINABLE zip #-}
-- | Zip two 'Producer's using the provided combining function
zipWith :: Monad m
=> (a -> b -> c)
-> (Producer a m r)
-> (Producer b m r)
-> (Producer' c m r)
zipWith f = go
where
go p1 p2 = do
e1 <- lift $ next p1
case e1 of
Left r -> return r
Right (a, p1') -> do
e2 <- lift $ next p2
case e2 of
Left r -> return r
Right (b, p2') -> do
yield (f a b)
go p1' p2'
{-# INLINABLE zipWith #-}
{-| Transform a 'Consumer' to a 'Pipe' that reforwards all values further
downstream
-}
tee :: Monad m => Consumer a m r -> Pipe a a m r
tee p = evalStateP Nothing $ do
r <- up >\\ (hoist lift p //> dn)
ma <- lift get
case ma of
Nothing -> return ()
Just a -> yield a
return r
where
up () = do
ma <- lift get
case ma of
Nothing -> return ()
Just a -> yield a
a <- await
lift $ put (Just a)
return a
dn v = closed v
{-# INLINABLE tee #-}
{-| Transform a unidirectional 'Pipe' to a bidirectional 'Proxy'
> generalize (f >-> g) = generalize f >+> generalize g
>
> generalize cat = pull
-}
generalize :: Monad m => Pipe a b m r -> x -> Proxy x a x b m r
generalize p x0 = evalStateP x0 $ up >\\ hoist lift p //> dn
where
up () = do
x <- lift get
request x
dn a = do
x <- respond a
lift $ put x
{-# INLINABLE generalize #-}
| michaelt/series | notes/pipeprelude.hs | bsd-3-clause | 20,812 | 0 | 21 | 6,461 | 5,223 | 2,637 | 2,586 | -1 | -1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-
Module: Projectile
This module provides utility functions to gather various paths of a project
-}
module Projectile (getProjectRootDir) where
import Protolude hiding (catch, (<>))
import Control.Exception.Safe (MonadCatch, MonadThrow, catch, throwM)
import Data.Monoid ((<>))
import Data.Vector (Vector)
import Path (Abs, Dir, Path, Rel, parent, parseRelFile, (</>))
import Path.IO (isLocationOccupied)
import qualified Data.Vector as V
--------------------------------------------------------------------------------
data ProjectileException
-- | Error thrown when calling project function from
-- a path that does not not belong to any project
= ProjectRootNotFound
deriving (Generic, NFData, Show, Eq)
instance Exception ProjectileException
data WalkAction
= WalkFinish
| WalkContinue
| WalkInvalid
deriving (Generic, NFData, Show, Eq)
--------------------------------------------------------------------------------
isRoot :: Path Abs Dir -> Bool
isRoot path =
parent path == path
-- | A list of files considered to mark the root of a project. The top-most
-- match has precedence.
projectRootTopLangMarkFiles :: Vector FilePath
projectRootTopLangMarkFiles =
V.fromList
[
"rebar.config" -- Rebar project file
, "project.clj" -- Leiningen project file
, "build.boot" -- Boot-clj project file
, "SConstruct" -- Scons project file
, "pom.xml" -- Maven project file
, "build.sbt" -- SBT project file
, "gradlew" -- Gradle wrapper script
, "build.gradle" -- Gradle project file
, ".ensime" -- Ensime configuration file
, "Gemfile" -- Bundler file
, "requirements.txt" -- Pip file
, "setup.py" -- Setuptools file
, "tox.ini" -- Tox file
, "composer.json" -- Composer project file
, "Cargo.toml" -- Cargo project file
, "mix.exs" -- Elixir mix project file
, "stack.yaml" -- Haskell's stack tool based project
, "stack.yml" -- Haskell's stack tool based project
, "info.rkt" -- Racket package description file
, "DESCRIPTION" -- R package description file
, "TAGS" -- etags/ctags are usually in the root of project
, "GTAGS" -- GNU Global tags
]
-- | A list of files considered to mark the root of a project. The top-most
-- match has precedence.
projectRootTopMarkFiles :: Vector FilePath
projectRootTopMarkFiles =
V.fromList
[
".projectile" -- projectile project marker
, ".git" -- Git VCS root dir
, ".hg" -- Mercurial VCS root dir
, ".fslckout" -- Fossil VCS root dir
, "_FOSSIL_" -- Fossil VCS root DB on Windows
, ".bzr" -- Bazaar VCS root dir
, "_darcs" -- Darcs VCS root dir
]
-- | A list of files considered to mark the root of a project. This
-- file must be in all sub-directories of a project.
projectRecurringMarkFiles :: Vector FilePath
projectRecurringMarkFiles =
V.fromList
[
".svn" -- Svn VCS root dir
, "CVS" -- Csv VCS root dir
, "Makefile"
]
-- | Iterate from the current path to parent paths until the match function
-- returns a value for finishing the traversal
locateDominatingFile
:: (MonadIO m, MonadThrow m)
=> Path Abs Dir -- ^ Directory to start from
-> (Path Abs Dir -> m WalkAction) -- ^ Match function that will return what to do next on the iteration
-> m (Path Abs Dir) -- ^ The path where the match function returns @WalkFinish@
locateDominatingFile dir continueP
| isRoot dir =
throwM ProjectRootNotFound
| otherwise = do
walkNext <- continueP dir
case walkNext of
WalkInvalid ->
throwM ProjectRootNotFound
WalkFinish ->
return dir
WalkContinue ->
locateDominatingFile (parent dir) continueP
-- | Returns a @WalkAction@ that indicates a finish of iteration when any of the
-- given relative paths is contained on the given directory
doesContainAny
:: MonadIO m
=> Vector (Path Rel t) -- ^ Relative path that should be contained in directory input
-> Path b Dir -- ^ Directory path that should contain any of the relative paths
-> m WalkAction
doesContainAny files dir = do
matchesAnyFile <-
(not . V.null . V.dropWhile not)
<$> V.mapM (\file -> isLocationOccupied (dir </> file)) files
if matchesAnyFile then
return WalkFinish
else
return WalkContinue
getDirWithRootProjectFile
:: (MonadIO m, MonadThrow m)
=> Path Abs Dir
-> m (Path Abs Dir)
getDirWithRootProjectFile currentDir = do
files <-
mapM parseRelFile (projectRootTopMarkFiles
<> projectRootTopLangMarkFiles)
locateDominatingFile currentDir (doesContainAny files)
getDirWithRecurringProjectFile
:: (MonadIO m, MonadThrow m)
=> Path Abs Dir
-> m (Path Abs Dir)
getDirWithRecurringProjectFile currentDir =
let
parentDoesNotContainOneOf files dir = do
fileLocated <- doesContainAny files dir
if fileLocated == WalkFinish then do
-- return check of parent directory not containing one of the
-- recurring project files
parentContains <- doesContainAny files (parent dir)
if parentContains == WalkFinish then
return WalkContinue
else
return WalkFinish
-- if the path doesn't contain the recurring marking file, then
-- this is not a project that can be recognizable
else
return WalkInvalid
in do
files <- mapM parseRelFile projectRecurringMarkFiles
locateDominatingFile currentDir (parentDoesNotContainOneOf files)
-- | Retrieves the root of the current project if available.
-- A @ProjectRootNotFound@ error is returned otherwise.
--
getProjectRootDir
:: (MonadCatch m, MonadIO m)
=> Path Abs Dir -- ^ Directory from where to look the root of the project
-> m (Path Abs Dir) -- ^ Root of the project directory
getProjectRootDir dir =
catch (getDirWithRecurringProjectFile dir)
(\(_ :: ProjectileException) -> getDirWithRootProjectFile dir)
| roman/Haskell-projectile | src/Projectile.hs | isc | 6,420 | 0 | 17 | 1,646 | 999 | 554 | 445 | 131 | 3 |
-- |Quake VM builtin functions reader.
module Builtin (BuiltinDefs, getBuiltins) where
import Control.Arrow ((>>>))
import Data.List (isPrefixOf)
import Data.Map (Map, fromList, toList)
import Language.C
import Language.C.Analysis
import Language.C.System.GCC (newGCC)
-- |Alias to a map of functions declarations.
type BuiltinDefs = Map Int FunDef
-- |Checks if the declaration is a Quake VM builtin.
isBuiltin :: FilePath -> DeclEvent -> Bool
isBuiltin input (DeclEvent (FunctionDef f)) =
Just input == fileOfNode f && prefixed
where prefixed = ("vm_b_" `isPrefixOf`) . identToString . declIdent $ f
isBuiltin _ _ =
False
-- |Returns a map of builtins from a source file.
getBuiltins :: [String] -> FilePath -> IO BuiltinDefs
getBuiltins cflags source = do
ast <- parseCFile (newGCC "gcc") Nothing cflags source >>= step "parse"
(globals, _warnings) <- (runTrav_ >>> step "analyse") $ analyseAST ast
return $ getBuiltins globals
where
-- |Raise an error or continue.
step :: (Show a) => String -> (Either a b) -> IO b
step label = either (error . (concat ["[", label, "] "] ++) . show) return
-- |Get builtins map from globals.
getBuiltins :: GlobalDecls -> BuiltinDefs
getBuiltins = remap . funDefs . gObjs . filterGlobalDecls (isBuiltin source)
funDefs objs =
let (_, (_, _, funDefMap)) = splitIdentDecls False objs in
funDefMap
remap :: Map Ident FunDef -> BuiltinDefs
remap =
fromList . map (\(_ident, funDef) -> (posRow . posOf $ funDef, funDef)) . toList
| ftrvxmtrx/qvmgen | Builtin.hs | mit | 1,538 | 0 | 14 | 306 | 480 | 261 | 219 | 29 | 1 |
-- | All these methods work as follows:
-- |
-- | Given a feasible (or near feasible trajectory), an HJB style cost metric, ControlledSystem System, will attempt to improve that trajectory to a better one.
-- | Uses Optimize.NonLinear as a backend in all cases.
import qualified RapidlyExploringRandomTree as RRT
-- | Represents a Trajectory.
data Trajectory = Trajectory [(StatePoint,ControlInput)] Float
data StateTrajectory = StateTrajectory [StatePoint] Float
data ControlTrajectory = ControlTrajectory [ControlInput] Float
-- TODO: Converters.
-- | This function should be effectivly idempotent, i.e. once a trajectory is optimized, it cannot be optimized further.
optimize_trajectory :: ControlledSystem -> TrajectoryCostMetric -> Trajectory -> Trajectory
optimize_trajectory system cost_metric trajectory = colocation system cost_metric trajectory []
-- | Will return an optimized trajectory.
-- | TODO Probably needs to take in a default dt
create_trajectory :: ControlledSystem -> TrajectoryCostMetric -> StatePoint -> StatePoint -> Trajectory
create_trajectory system cost_metric start goal
= let rough_trajectory = RRT.create_trajectory system start goal
trajectory = optimize_trajectory system cost_metric rough_trajectory
-- | Three implemented methods.
shooting_method -- | Optimize over u and dt only, with a constraint that we end where we want too.
direct_transcription -- | Optimize over both x, u, add dynamics contraints x_(n+1) = x_n + dt
colocation -- | Like direct transcription, but force the dynamics to work at the so called "knot points" -- midpoints of the associated cubic spline in x.
| Zomega/thesis | Wurm/Trajectory/Optimize.hs | mit | 1,640 | 1 | 8 | 255 | 174 | 100 | 74 | -1 | -1 |
{-# htermination (pr :: MyInt -> MyInt -> MyInt) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data Dummy = Nil
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data Ordering = LT | EQ | GT ;
stop :: MyBool -> a;
stop MyFalse = stop MyFalse;
error :: a;
error = stop MyTrue;
pr0 wy wz = error;
fromIntMyInt :: MyInt -> MyInt
fromIntMyInt x = x;
primCmpNat :: Nat -> Nat -> Ordering;
primCmpNat Zero Zero = EQ;
primCmpNat Zero (Succ y) = LT;
primCmpNat (Succ x) Zero = GT;
primCmpNat (Succ x) (Succ y) = primCmpNat x y;
primCmpInt :: MyInt -> MyInt -> Ordering;
primCmpInt (Pos Zero) (Pos Zero) = EQ;
primCmpInt (Pos Zero) (Neg Zero) = EQ;
primCmpInt (Neg Zero) (Pos Zero) = EQ;
primCmpInt (Neg Zero) (Neg Zero) = EQ;
primCmpInt (Pos x) (Pos y) = primCmpNat x y;
primCmpInt (Pos x) (Neg y) = GT;
primCmpInt (Neg x) (Pos y) = LT;
primCmpInt (Neg x) (Neg y) = primCmpNat y x;
compareMyInt :: MyInt -> MyInt -> Ordering
compareMyInt = primCmpInt;
esEsOrdering :: Ordering -> Ordering -> MyBool
esEsOrdering LT LT = MyTrue;
esEsOrdering LT EQ = MyFalse;
esEsOrdering LT GT = MyFalse;
esEsOrdering EQ LT = MyFalse;
esEsOrdering EQ EQ = MyTrue;
esEsOrdering EQ GT = MyFalse;
esEsOrdering GT LT = MyFalse;
esEsOrdering GT EQ = MyFalse;
esEsOrdering GT GT = MyTrue;
gtMyInt :: MyInt -> MyInt -> MyBool
gtMyInt x y = esEsOrdering (compareMyInt x y) GT;
primMinusNat :: Nat -> Nat -> MyInt;
primMinusNat Zero Zero = Pos Zero;
primMinusNat Zero (Succ y) = Neg (Succ y);
primMinusNat (Succ x) Zero = Pos (Succ x);
primMinusNat (Succ x) (Succ y) = primMinusNat x y;
primPlusNat :: Nat -> Nat -> Nat;
primPlusNat Zero Zero = Zero;
primPlusNat Zero (Succ y) = Succ y;
primPlusNat (Succ x) Zero = Succ x;
primPlusNat (Succ x) (Succ y) = Succ (Succ (primPlusNat x y));
primMinusInt :: MyInt -> MyInt -> MyInt;
primMinusInt (Pos x) (Neg y) = Pos (primPlusNat x y);
primMinusInt (Neg x) (Pos y) = Neg (primPlusNat x y);
primMinusInt (Neg x) (Neg y) = primMinusNat y x;
primMinusInt (Pos x) (Pos y) = primMinusNat x y;
msMyInt :: MyInt -> MyInt -> MyInt
msMyInt = primMinusInt;
primEvenNat :: Nat -> MyBool;
primEvenNat Zero = MyTrue;
primEvenNat (Succ Zero) = MyFalse;
primEvenNat (Succ (Succ x)) = primEvenNat x;
primEvenInt :: MyInt -> MyBool;
primEvenInt (Pos x) = primEvenNat x;
primEvenInt (Neg x) = primEvenNat x;
evenMyInt :: MyInt -> MyBool
evenMyInt = primEvenInt;
otherwise :: MyBool;
otherwise = MyTrue;
primMulNat :: Nat -> Nat -> Nat;
primMulNat Zero Zero = Zero;
primMulNat Zero (Succ y) = Zero;
primMulNat (Succ x) Zero = Zero;
primMulNat (Succ x) (Succ y) = primPlusNat (primMulNat x (Succ y)) (Succ y);
primMulInt :: MyInt -> MyInt -> MyInt;
primMulInt (Pos x) (Pos y) = Pos (primMulNat x y);
primMulInt (Pos x) (Neg y) = Neg (primMulNat x y);
primMulInt (Neg x) (Pos y) = Neg (primMulNat x y);
primMulInt (Neg x) (Neg y) = Pos (primMulNat x y);
srMyInt :: MyInt -> MyInt -> MyInt
srMyInt = primMulInt;
pr2F0G0 vxy x n MyTrue = pr2F x (msMyInt n (fromIntMyInt (Pos (Succ Zero)))) (srMyInt x vxy);
primMinusNatS :: Nat -> Nat -> Nat;
primMinusNatS (Succ x) (Succ y) = primMinusNatS x y;
primMinusNatS Zero (Succ y) = Zero;
primMinusNatS x Zero = x;
primDivNatS0 x y MyTrue = Succ (primDivNatS (primMinusNatS x y) (Succ y));
primDivNatS0 x y MyFalse = Zero;
primGEqNatS :: Nat -> Nat -> MyBool;
primGEqNatS (Succ x) Zero = MyTrue;
primGEqNatS (Succ x) (Succ y) = primGEqNatS x y;
primGEqNatS Zero (Succ x) = MyFalse;
primGEqNatS Zero Zero = MyTrue;
primDivNatS :: Nat -> Nat -> Nat;
primDivNatS Zero Zero = error;
primDivNatS (Succ x) Zero = error;
primDivNatS (Succ x) (Succ y) = primDivNatS0 x y (primGEqNatS x y);
primDivNatS Zero (Succ x) = Zero;
primQuotInt :: MyInt -> MyInt -> MyInt;
primQuotInt (Pos x) (Pos (Succ y)) = Pos (primDivNatS x (Succ y));
primQuotInt (Pos x) (Neg (Succ y)) = Neg (primDivNatS x (Succ y));
primQuotInt (Neg x) (Pos (Succ y)) = Neg (primDivNatS x (Succ y));
primQuotInt (Neg x) (Neg (Succ y)) = Pos (primDivNatS x (Succ y));
primQuotInt xw xx = error;
quotMyInt :: MyInt -> MyInt -> MyInt
quotMyInt = primQuotInt;
pr2F0G1 vxy x n MyTrue = pr2F0G vxy (srMyInt x x) (quotMyInt n (fromIntMyInt (Pos (Succ (Succ Zero)))));
pr2F0G1 vxy x n MyFalse = pr2F0G0 vxy x n otherwise;
pr2F0G2 vxy x n = pr2F0G1 vxy x n (evenMyInt n);
pr2F0G vxy x n = pr2F0G2 vxy x n;
pr2F0 x n y = pr2F0G y x n;
primEqNat :: Nat -> Nat -> MyBool;
primEqNat Zero Zero = MyTrue;
primEqNat Zero (Succ y) = MyFalse;
primEqNat (Succ x) Zero = MyFalse;
primEqNat (Succ x) (Succ y) = primEqNat x y;
primEqInt :: MyInt -> MyInt -> MyBool;
primEqInt (Pos (Succ x)) (Pos (Succ y)) = primEqNat x y;
primEqInt (Neg (Succ x)) (Neg (Succ y)) = primEqNat x y;
primEqInt (Pos Zero) (Neg Zero) = MyTrue;
primEqInt (Neg Zero) (Pos Zero) = MyTrue;
primEqInt (Neg Zero) (Neg Zero) = MyTrue;
primEqInt (Pos Zero) (Pos Zero) = MyTrue;
primEqInt xy xz = MyFalse;
esEsMyInt :: MyInt -> MyInt -> MyBool
esEsMyInt = primEqInt;
pr2F3 MyTrue wx vuy y = y;
pr2F3 vuz vvu vvv vvw = pr2F0 vvu vvv vvw;
pr2F4 wx vuy y = pr2F3 (esEsMyInt vuy (fromIntMyInt (Pos Zero))) wx vuy y;
pr2F4 vvx vvy vvz = pr2F0 vvx vvy vvz;
pr2F wx vuy y = pr2F4 wx vuy y;
pr2F x n y = pr2F0 x n y;
pr2Pr1 x n MyTrue = pr2F x (msMyInt n (fromIntMyInt (Pos (Succ Zero)))) x;
pr2Pr1 x n MyFalse = pr0 x n;
pr2 x n = pr2Pr1 x n (gtMyInt n (fromIntMyInt (Pos Zero)));
pr2 vwu vwv = pr0 vwu vwv;
pr3 MyTrue x vww = fromIntMyInt (Pos (Succ Zero));
pr3 vwx vwy vwz = pr2 vwy vwz;
pr4 x vww = pr3 (esEsMyInt vww (fromIntMyInt (Pos Zero))) x vww;
pr4 vxu vxv = pr2 vxu vxv;
pr x vww = pr4 x vww;
pr x n = pr2 x n;
pr wy wz = pr0 wy wz;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/CARET_2.hs | mit | 5,745 | 20 | 15 | 1,201 | 2,957 | 1,480 | 1,477 | 143 | 1 |
module Main (main) where
import System.Environment
import System.Console.GetOpt
import Prelude hiding (Left, Right)
import XBattBar.Types
import XBattBar.Core (start)
defaultOptions :: Options
defaultOptions = Options {
onTop = False,
thickness = 2,
interval = 5,
chargeColorAC = "green",
dischargeColorAC = "olive drab",
chargeColorBat = "blue",
dischargeColorBat = "red",
position = Bottom
}
options :: [ OptDescr (Options -> Options) ]
options =
[ Option "a" [] (NoArg (\opts -> opts { onTop = True }))
"Always on top",
Option "t" [] (ReqArg (\x s -> s { thickness = read x }) "PX")
"Thickness",
Option "p" [] (ReqArg (\x s -> s { interval = read x }) "PX")
"Polling interval",
Option "I" [] (ReqArg (\x s -> s { chargeColorAC = x }) "PX")
"Charge color when on AC",
Option "O" [] (ReqArg (\x s -> s { dischargeColorAC = x }) "PX")
"Discharge color when on AC",
Option "o" [] (ReqArg (\x s -> s { dischargeColorBat = x }) "PX")
"Charge color when on battery",
Option "i" [] (ReqArg (\x s -> s { chargeColorBat = x }) "PX")
"Discharge color when on battery",
Option "h" [] (NoArg (usage))
"Print help message"
]
nonoptions :: Options -> [String] -> Options
nonoptions opts [] = opts
nonoptions opts ["top"] = opts { position = Top }
nonoptions opts ["bottom"] = opts { position = Bottom }
nonoptions opts ["left"] = opts { position = Left }
nonoptions opts ["right"] = opts { position = Right }
nonoptions _ _ = usage
usage = error $ "usage: xbattbar [-a] [-h|v] [-p sec] [-t thickness] " ++
"[-I color] [-O color] [-i color] [-o color] " ++
"[ top | bottom | left | right ]"
main = do
args <- getArgs
let (actions, nonOptions, errors) = getOpt RequireOrder options args
let opts = foldl (flip id) defaultOptions actions
start $ nonoptions opts nonOptions
| polachok/xbattbar | src/Main.hs | mit | 2,167 | 0 | 13 | 722 | 646 | 359 | 287 | 49 | 1 |
module Symmath
(
module Symmath.Eval,
module Symmath.Terms,
module Symmath.Functiontable,
module Symmath.Constants,
module Symmath.Derivate,
module Symmath.Simplify,
module Symmath.Util,
module Symmath.Parse,
module Symmath.RPNParse,
module Symmath.TermToTex,
module Symmath.NumericIntegration
)
where
import Symmath.Eval
import Symmath.Terms
import Symmath.Functiontable
import Symmath.Constants
import Symmath.Derivate
import Symmath.Simplify
import Symmath.Util
import Symmath.Parse
import Symmath.RPNParse
import Symmath.TermToTex
import Symmath.NumericIntegration
| Spheniscida/symmath | Symmath.hs | mit | 617 | 0 | 5 | 97 | 127 | 81 | 46 | 24 | 0 |
--------------------------------------------------------------------
-- |
-- Copyright : © Oleg Grenrus 2014
-- License : MIT
-- Maintainer: Oleg Grenrus <[email protected]>
-- Stability : experimental
-- Portability: non-portable
--
-- This module re-exports 'Set'-based implementation.
--------------------------------------------------------------------
module Data.Algebra.Boolean.CNF (
module Data.Algebra.Boolean.CNF.Set
) where
import Data.Algebra.Boolean.CNF.Set
| phadej/boolean-normal-forms | src/Data/Algebra/Boolean/CNF.hs | mit | 483 | 0 | 5 | 52 | 37 | 30 | 7 | 3 | 0 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternSynonyms #-}
module GLUtils where
import Language.Haskell.TH.Ppr (bytesToString)
import qualified Graphics.GL.Core32 as GL
import qualified Graphics.GL.Types as GL
import qualified Foreign as F
import qualified Foreign.C.String as F
import qualified Foreign.C.Types as F()
printGLError :: IO ()
printGLError = GL.glGetError >>= \case
GL.GL_NO_ERROR -> putStrLn "GL_NO_ERROR"
GL.GL_INVALID_ENUM -> putStrLn "GL_INVALID_ENUM"
GL.GL_INVALID_VALUE -> putStrLn "GL_INVALID_VALUE"
GL.GL_INVALID_OPERATION -> putStrLn "GL_INVALID_OPERATION"
GL.GL_INVALID_FRAMEBUFFER_OPERATION -> putStrLn "GL_INVALID_FRAME_OPERATION"
GL.GL_OUT_OF_MEMORY -> putStrLn "GL_OUT_OF_MEMORY"
_ -> putStrLn "I don't know"
printGLVersion :: IO ()
printGLVersion = GL.glGetString GL.GL_VERSION >>= F.peekArray0 0 >>= putStrLn . bytesToString
printShaderInfoLog :: GL.GLuint -> IO ()
printShaderInfoLog shader = F.allocaArray0 511 (\arr -> GL.glGetShaderInfoLog shader 512 F.nullPtr arr >> F.peekArray 512 arr >>= putStrLn . fmap F.castCCharToChar)
| soupi/haskell-sdl2gl | src/MySDL/GLUtils.hs | mit | 1,087 | 0 | 12 | 144 | 276 | 150 | 126 | 22 | 7 |
module Data.Mole.Builder where
import Data.Mole.Types
import Data.Mole.Builder.Html
import Data.Mole.Builder.Binary
import Data.Mole.Builder.JavaScript
import Data.Mole.Builder.Image
import Data.Mole.Builder.Stylesheet
import System.FilePath
builderForFile :: FilePath -> String -> Handle -> AssetId -> IO Builder
builderForFile basePath x = case takeExtension x of
".css" -> stylesheetBuilder x
".html" -> htmlBuilder (drop (length basePath) x) x
".js" -> javascriptBuilder x
".png" -> imageBuilder x "image/png"
".jpeg" -> imageBuilder x "image/jpeg"
".jpg" -> imageBuilder x "image/jpeg"
_ -> binaryBuilder x "application/octet-stream"
| wereHamster/mole | src/Data/Mole/Builder.hs | mit | 754 | 0 | 12 | 188 | 181 | 97 | 84 | 17 | 7 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE InstanceSigs #-}
module Foundation where
import Import.NoFoundation
import Database.Persist.Sql (ConnectionPool, runSqlPool)
import Text.Hamlet (hamletFile)
import Text.Jasmine (minifym)
import Yesod.Auth.HashDB (authHashDBWithForm)
import Yesod.Auth.Message
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Core.Types (Logger)
import qualified Yesod.Core.Unsafe as Unsafe
import Control.Monad.Logger (LogSource)
-- Used only in Foundation.hs
import qualified Data.Text as T
import qualified Data.Map as Map
import qualified Network.Wai as WAI (Request(..))
import Network.HTTP.Types (mkStatus)
import Network.HTTP.Client.Conduit (Manager, HasHttpManager (getHttpManager))
import GHC.Word (Word64)
import System.FilePath ((</>))
maxFileSize :: Word64
maxFileSize = 25 -- in MB
-- | 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
, appSSEClients :: TVar (Map.Map Text UTCTime)
, appSSEChan :: TChan (Text, Text)
}
instance HasHttpManager App where
getHttpManager = appHttpManager
-- Data types appear in routes
data ManageBoardAction = NewBoard | AllBoards | UpdateBoard
deriving (Show, Read, Eq)
data Censorship = SFW | R15 | R18 | R18G
deriving (Show, Read, Eq, Enum, Bounded, Ord)
-- i18n helpers
i18nFoundPostsRus :: Int -> String
i18nFoundPostsRus n
| n == 1 = "Найден "++show n++" пост"
| n `elem` [2..4] = "Найдено "++show n++" поста"
| n `elem` [5..19] = "Найдено "++show n++" постов"
| lastN == 0 = "Найдено "++show n++" постов"
| lastN == 1 = "Найден "++show n++" пост"
| lastN `elem` [2..4] = "Найдено "++show n++" поста"
| lastN `elem` [5..9] = "Найдено "++show n++" постов"
| otherwise = "Найдено "++show n++" постов"
where lastN = (head $ ((++)[0]) $ map (`mod`10) $ takeWhile (>0) $ iterate (`div`10) n)
omittedRus :: Int -> String
omittedRus n
| n == 1 = "пост пропущен"
| n `elem` [2..4] = "поста пропущено"
| n `elem` [5..19] = "постов пропущено"
| lastN == 0 = "постов пропущено"
| lastN == 1 = "пост пропущен"
| lastN `elem` [2..4] = "поста пропущено"
| lastN `elem` [5..9] = "постов пропущено"
| otherwise = "постов пропущено"
where lastN = (head $ ((++)[0]) $ map (`mod`10) $ takeWhile (>0) $ iterate (`div`10) n)
timesRus :: Int -> String
timesRus n
| n `elem` [11..14] = "раз"
| lastN `elem` [2,3,4] = "раза"
| otherwise = "раз"
where lastN = (head $ ((++)[0]) $ map (`mod`10) $ takeWhile (>0) $ iterate (`div`10) n)
plural :: Int -> String -> String -> String
plural 1 x _ = x
plural _ _ y = y
unlimitedBump :: Int -> String -> String
unlimitedBump 0 s = s
unlimitedBump n _ = show n
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
-- 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.
mkYesodData "App" $(parseRoutesFile "config/routes")
-- | A convenient synonym for creating forms.
type Form x = Html -> MForm (HandlerFor App) (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
maximumContentLength _ _ = Just $ maxFileSize * (1024^(2 :: Word64))
-- Controls the base of generated URLs. For more information on modifying,
-- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot
-- Controls the base of generated URLs. For more information on modifying,
-- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot
approot = ApprootRequest $ \app req ->
case appRoot $ appSettings app of
Nothing -> getApprootText guessApproot app req
Just root -> root
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = Just <$> defaultClientSessionBackend
(60 * 60 * 24 * 7) -- timeout in minutes, 7 days
"config/client_session_key.aes"
defaultLayout widget = do
muser <- maybeAuth
master <- getYesod
mmsg <- getMessage
msgrender <- getMessageRender
boards <- runDB $ selectList ([]::[Filter Board]) []
permissions <- (maybe [] (groupPermissions . entityVal)) <$> runDB (getBy $ GroupUniqName $ maybe "" (userGroup . entityVal) muser)
categories <- (maybe [] (configBoardCategories . entityVal)) <$> runDB (selectFirst ([]::[Filter Config]) [])
stylesheet <- flip mplus (Just $ appStylesheet $ appSettings master) <$> lookupSession "stylesheet"
let stylesheetPath s = "/" </> appStaticDir (appSettings master) </> "stylesheets" </> (unpack s ++ ".css")
uGroup = (userGroup . entityVal) <$> muser
settings = appSettings master
-- 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.
pc <- widgetToPageContent $ do
$(widgetFile "default-layout")
withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
isAuthorized x _ = case x of
AdminR{} -> isAuthorized' [ManagePanelP]
NewPasswordR{} -> isAuthorized' [ManagePanelP]
AccountR{} -> isAuthorized' [ManagePanelP]
StickR{} -> isAuthorized' [ManageThreadP]
LockR{} -> isAuthorized' [ManageThreadP]
AutoSageR{} -> isAuthorized' [ManageThreadP]
MoveThreadR{} -> isAuthorized' [ManageThreadP]
ChangeThreadR{} -> isAuthorized' [ManageThreadP]
BanByIpR{} -> isAuthorized' [ManageBanP]
BanByIpAndDeleteR{} -> isAuthorized' [ManageBanP, DeletePostsP]
BanDeleteR{} -> isAuthorized' [ManageBanP]
ManageBoardsR{} -> isAuthorized' [ManageBoardP]
NewBoardsR{} -> isAuthorized' [ManageBoardP]
UpdateBoardsR{} -> isAuthorized' [ManageBoardP]
AllBoardsR{} -> isAuthorized' [ManageBoardP]
DeleteBoardR{} -> isAuthorized' [ManageBoardP]
CleanBoardR{} -> isAuthorized' [ManageBoardP]
RebuildPostsMessagesOnBoardR{} -> isAuthorized' [ManageBoardP]
HellBanNoPageR{} -> isAuthorized' [HellBanP]
HellBanR{} -> isAuthorized' [HellBanP]
HellBanActionR{} -> isAuthorized' [HellBanP]
HellBanGetFormR{} -> isAuthorized' [HellBanP]
AdminSearchHBUIDR{} -> isAuthorized' [ViewIPAndIDP, HellBanP]
AdminSearchHBUIDNoPageR{} -> isAuthorized' [ViewIPAndIDP, HellBanP]
AdminSearchHBUsersR{} -> isAuthorized' [ViewIPAndIDP, HellBanP]
AdminSearchHBUsersNoPageR{} -> isAuthorized' [ViewIPAndIDP, HellBanP]
UsersR{} -> isAuthorized' [ManageUsersP]
ManageGroupsR{} -> isAuthorized' [ManageUsersP]
DeleteGroupsR{} -> isAuthorized' [ManageUsersP]
UsersDeleteR{} -> isAuthorized' [ManageUsersP]
ModlogR{} -> isAuthorized' [ViewModlogP]
AdminSearchIPR{} -> isAuthorized' [ViewIPAndIDP]
AdminSearchIPNoPageR{} -> isAuthorized' [ViewIPAndIDP]
AdminSearchUIDR{} -> isAuthorized' [ViewIPAndIDP]
AdminSearchUIDNoPageR{} -> isAuthorized' [ViewIPAndIDP]
ManageCensorshipR{} -> isAuthorized' [ChangeFileRatingP]
AdminDeletedR{} -> isAuthorized' [DeletePostsP]
AdminDeletedFilteredR{} -> isAuthorized' [DeletePostsP]
AdminRecoverDeletedR{} -> isAuthorized' [DeletePostsP]
DeletePostsByIPR{} -> isAuthorized' [DeletePostsP]
AdminLockEditingR{} -> isAuthorized' [EditPostsP]
ConfigR{} -> isAuthorized' [ManageConfigP]
AdminGitPullR{} -> isAuthorized' [AppControlP]
AdminRestartR{} -> isAuthorized' [AppControlP]
AdminWordfilterR{} -> isAuthorized' [WordfilterP]
AdminWordfilterDeleteR{} -> isAuthorized' [WordfilterP]
AdminReportsR{} -> isAuthorized' [ReportsP]
AdminReportsDelR{} -> isAuthorized' [ReportsP]
_ -> 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.
shouldLogIO :: App -> LogSource -> LogLevel -> IO Bool
shouldLogIO app _source level =
return $
appShouldLogAll (appSettings app)
|| level == LevelWarn
|| level == LevelError
makeLogger = return . appLogger
errorHandler errorResponse = do
$(logWarn) (T.append "Error Response: " $ pack (show errorResponse))
req <- waiRequest
let reqwith = lookup "X-Requested-With" $ WAI.requestHeaders req
errorText NotFound = (404, "Not Found", "Sorry, not found")
errorText (InternalError msg) = (400, "Bad Request", msg)
errorText (InvalidArgs m) = (400, "Bad Request", T.unwords m)
errorText (PermissionDenied msg) = (403, "Forbidden", msg)
errorText (BadMethod _) = (405, "Method Not Allowed", "Method not supported")
errorText NotAuthenticated = (401, "Not authenticated", "You don't have permission to do this")
when (maybe False (== "XMLHttpRequest") reqwith) $ do
let (code, brief, full) = errorText errorResponse
sendResponseStatus
(mkStatus code brief)
$ RepPlain $ toContent $ T.append "Error: " full
defaultErrorHandler errorResponse
isAuthorized' :: [Permission] -> Handler AuthResult
isAuthorized' permissions = do
mauth <- maybeAuth
case mauth of
Nothing -> return AuthenticationRequired
Just (Entity _ user) -> do
mGroup <- runDB $ getBy $ GroupUniqName (userGroup user)
case mGroup of
Nothing -> return AuthenticationRequired
Just group -> do
if all (`elem` groupPermissions (entityVal group)) permissions
then return Authorized
else return $ Unauthorized "Not permitted"
-- Path pieces
instance PathPiece IP where
toPathPiece = pack . show
fromPathPiece s =
case reads $ unpack s of
(i,""):_ -> Just i
_ -> Nothing
instance PathPiece Censorship where
toPathPiece = pack . show
fromPathPiece s =
case reads $ unpack s of
(i,""):_ -> Just i
_ -> Nothing
instance PathPiece ManageBoardAction where
toPathPiece = pack . show
fromPathPiece s =
case reads $ unpack s of
(i,""):_ -> Just i
_ -> Nothing
-- 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
authForm :: Route App -> Widget
authForm action = $(whamletFile "templates/loginform.hamlet")
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = HomeR
-- Where to send a user after logout
logoutDest _ = HomeR
-- Override the above two destinations when a Referer: header is present
redirectToReferer _ = True
-- You can add other plugins like BrowserID, email or OAuth here
authPlugins _ = [ authHashDBWithForm authForm (Just . UserUniqName) ]
authenticate creds = liftHandler $ runDB $ do
x <- getBy $ UserUniqName $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Authenticated uid
Nothing -> Authenticated <$> insert User
{ userName = credsIdent creds
, userPassword = Nothing
, userGroup = ""
}
-- authHttpManager = liftHandler getHttpManager
onLogin = liftHandler (setMessageI NowLoggedIn >> redirect ModlogLoginR)
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
| ahushh/Monaba | monaba/src/Foundation.hs | mit | 14,760 | 0 | 22 | 3,630 | 3,534 | 1,851 | 1,683 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
-- |
-- Module : Data.Sorted
-- Copyright : (c) Joseph Abrahamson 2013
-- License : MIT
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable
--
-- Operations on lazily sorted lists. Use 'Sorted' to indicate a list
-- with a sorted constraint. Intended to be imported qualified.
module Data.Sorted (
-- * The base type
-- /Abstract/
Sorted, toList, sort,
-- * Iterative creation
build, insert, singleton,
-- * Higher-order operations
pair, map
) where
import qualified Data.Foldable as F
import qualified Data.List as L
import Data.Monoid
import Prelude hiding (elem, map, null)
import Prelude as P
newtype Sorted a = Sorted { toList :: [a] }
deriving ( Show, Eq, Ord )
sort :: (Ord a, F.Foldable f) => f a -> Sorted a
sort = Sorted . L.sort . F.toList
build :: Ord a => (forall m . Monoid m => (a -> m) -> m) -> Sorted a
build f = f singleton
fromList :: Ord a => [a] -> Sorted a
fromList xs = build (`F.foldMap` xs)
-- | Inserts a new element, "from the front".
--
-- prop> elem x . insert x == const True
insert :: Ord a => a -> Sorted a -> Sorted a
insert x = Sorted . go . toList where
go [] = [x]
go (y:ys) | x <= y = x : y : ys
| x > y = y : go ys
singleton :: a -> Sorted a
singleton = Sorted . return
instance Ord a => Monoid (Sorted a) where
mempty = Sorted mempty
-- lazy stable sorted merge
mappend (Sorted as) (Sorted bs) = Sorted (go as bs) where
go :: Ord a => [a] -> [a] -> [a]
go [] xs = xs
go xs [] = xs
go (x:xs) (y:ys) | x == y = x : y : go xs ys
| x < y = x : go xs (y:ys)
| x > y = y : go (x:xs) ys
null :: Sorted a -> Bool
null = P.null . toList
-- | Determines whether an element is in a 'Sorted' set. This function
-- takes advantage of 'Sorted' structure to be more efficient than
-- @elem . toList@.
elem :: Ord a => a -> Sorted a -> Bool
elem a = go . toList where
go [] = False
go (x:xs) | a < x = go xs
| a == x = True
| a > x = False
-- | Produces the product of two sorted sets, resulting in a
-- lexicographically sorted set. Along with singleton forms an
-- \"'Applicative'-like\" interface to 'Sorted'.
pair :: Sorted a -> Sorted b -> Sorted (a, b)
pair (Sorted as) (Sorted bs) = Sorted [(a, b) | a <- as, b <- bs ]
-- | 'Sorted' is a category functor, but cannot instantiate 'Functor'
-- because it constrains its domain category.
map :: Ord b => (a -> b) -> Sorted a -> Sorted b
map f = sort . P.map f . toList
-- monotonicMap
| tel/sorted | src/Data/Sorted.hs | mit | 2,684 | 0 | 12 | 776 | 889 | 474 | 415 | 46 | 2 |
module Main where
import Prelude
import Criterion
import Criterion.Main
import qualified PostgreSQL.Binary.Encoding as E
main =
defaultMain
[
value "bool" E.bool True
,
value "int2" E.int2_int16 1000
,
value "int4" E.int4_int32 1000
,
value "int8" E.int8_int64 1000
,
value "float4" E.float4 12.65468468
,
value "float8" E.float8 12.65468468
,
value "numeric" E.numeric (read "20.213290183")
,
value "char_utf8" E.char_utf8 'Я'
,
value "text" E.text_strict "alsdjflskjдывлоаы оады"
,
value "bytea" E.bytea_strict "alskdfj;dasjfl;dasjflksdj"
,
value "date" E.date (read "2000-01-19")
,
value "time" E.time_int (read "10:41:06")
,
value "timetz" E.timetz_int (read "(10:41:06, +0300)")
,
value "timestamp" E.timestamp_int (read "2000-01-19 10:41:06")
,
value "timestamptz" E.timestamptz_int (read "2000-01-19 10:41:06")
,
value "interval" E.interval_int (secondsToDiffTime 23472391128374)
,
value "uuid" E.uuid (read "550e8400-e29b-41d4-a716-446655440000")
,
let
encoder =
E.array 23 . E.dimensionArray foldl' (E.encodingArray . E.int4_int32)
in
value "array" encoder [1,2,3,4]
]
where
value name encoder value =
bench name $ nf (E.encodingBytes . encoder) value
| nikita-volkov/postgresql-binary | encoding/Main.hs | mit | 1,445 | 0 | 15 | 418 | 379 | 195 | 184 | 31 | 1 |
-- Growth of a Population
-- http://www.codewars.com/kata/563b662a59afc2b5120000c6/train/haskell
module Codewars.G964.Arge where
nbYear :: Int -> Double -> Int -> Int -> Int
nbYear p0 percent aug p | p <= p0 = 0
| otherwise = 1 + nbYear px percent aug p
where px = p0 + aug + round (0.01 * percent * fromIntegral p0)
| gafiatulin/codewars | src/7 kyu/Arge.hs | mit | 367 | 0 | 11 | 106 | 108 | 55 | 53 | 5 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
-- | This module provides an abstraction over 'STM', which can be used
-- with 'MonadConc'.
module Control.Monad.STM.Class where
import Control.Concurrent.STM (STM)
import Control.Concurrent.STM.TVar (TVar, newTVar, readTVar, writeTVar)
import Control.Exception (Exception)
import Control.Monad (unless)
import Control.Monad.Catch (MonadCatch, MonadThrow, throwM, catch)
import Control.Monad.Reader (ReaderT(..), runReaderT)
import Control.Monad.Trans (lift)
import qualified Control.Monad.RWS.Lazy as RL
import qualified Control.Monad.RWS.Strict as RS
import qualified Control.Monad.STM as S
import qualified Control.Monad.State.Lazy as SL
import qualified Control.Monad.State.Strict as SS
import qualified Control.Monad.Writer.Lazy as WL
import qualified Control.Monad.Writer.Strict as WS
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative)
import Data.Monoid (Monoid)
#endif
-- | @MonadSTM@ is an abstraction over 'STM'.
--
-- This class does not provide any way to run transactions, rather
-- each 'MonadConc' has an associated @MonadSTM@ from which it can
-- atomically run a transaction.
--
-- A minimal implementation consists of 'retry', 'orElse', 'newCTVar',
-- 'readCTVar', and 'writeCTVar'.
class (Applicative m, Monad m, MonadCatch m, MonadThrow m) => MonadSTM m where
-- | The mutable reference type. These behave like 'TVar's, in that
-- they always contain a value and updates are non-blocking and
-- synchronised.
type CTVar m :: * -> *
-- | Retry execution of this transaction because it has seen values
-- in @CTVar@s that it shouldn't have. This will result in the
-- thread running the transaction being blocked until any @CTVar@s
-- referenced in it have been mutated.
retry :: m a
-- | Run the first transaction and, if it @retry@s, run the second
-- instead. If the monad is an instance of
-- 'Alternative'/'MonadPlus', 'orElse' should be the '(<|>)'/'mplus'
-- function.
orElse :: m a -> m a -> m a
-- | Check whether a condition is true and, if not, call @retry@.
--
-- > check b = unless b retry
check :: Bool -> m ()
check b = unless b retry
-- | Create a new @CTVar@ containing the given value.
newCTVar :: a -> m (CTVar m a)
-- | Return the current value stored in a @CTVar@.
readCTVar :: CTVar m a -> m a
-- | Write the supplied value into the @CTVar@.
writeCTVar :: CTVar m a -> a -> m ()
-- | Throw an exception. This aborts the transaction and propagates
-- the exception.
--
-- > throwSTM = Control.Monad.Catch.throwM
throwSTM :: Exception e => e -> m a
throwSTM = throwM
-- | Handling exceptions from 'throwSTM'.
--
-- > catchSTM = Control.Monad.Catch.catch
catchSTM :: Exception e => m a -> (e -> m a) -> m a
catchSTM = Control.Monad.Catch.catch
instance MonadSTM STM where
type CTVar STM = TVar
retry = S.retry
orElse = S.orElse
newCTVar = newTVar
readCTVar = readTVar
writeCTVar = writeTVar
-------------------------------------------------------------------------------
-- Transformer instances
instance MonadSTM m => MonadSTM (ReaderT r m) where
type CTVar (ReaderT r m) = CTVar m
retry = lift retry
orElse ma mb = ReaderT $ \r -> orElse (runReaderT ma r) (runReaderT mb r)
check = lift . check
newCTVar = lift . newCTVar
readCTVar = lift . readCTVar
writeCTVar v = lift . writeCTVar v
instance (MonadSTM m, Monoid w) => MonadSTM (WL.WriterT w m) where
type CTVar (WL.WriterT w m) = CTVar m
retry = lift retry
orElse ma mb = WL.WriterT $ orElse (WL.runWriterT ma) (WL.runWriterT mb)
check = lift . check
newCTVar = lift . newCTVar
readCTVar = lift . readCTVar
writeCTVar v = lift . writeCTVar v
instance (MonadSTM m, Monoid w) => MonadSTM (WS.WriterT w m) where
type CTVar (WS.WriterT w m) = CTVar m
retry = lift retry
orElse ma mb = WS.WriterT $ orElse (WS.runWriterT ma) (WS.runWriterT mb)
check = lift . check
newCTVar = lift . newCTVar
readCTVar = lift . readCTVar
writeCTVar v = lift . writeCTVar v
instance MonadSTM m => MonadSTM (SL.StateT s m) where
type CTVar (SL.StateT s m) = CTVar m
retry = lift retry
orElse ma mb = SL.StateT $ \s -> orElse (SL.runStateT ma s) (SL.runStateT mb s)
check = lift . check
newCTVar = lift . newCTVar
readCTVar = lift . readCTVar
writeCTVar v = lift . writeCTVar v
instance MonadSTM m => MonadSTM (SS.StateT s m) where
type CTVar (SS.StateT s m) = CTVar m
retry = lift retry
orElse ma mb = SS.StateT $ \s -> orElse (SS.runStateT ma s) (SS.runStateT mb s)
check = lift . check
newCTVar = lift . newCTVar
readCTVar = lift . readCTVar
writeCTVar v = lift . writeCTVar v
instance (MonadSTM m, Monoid w) => MonadSTM (RL.RWST r w s m) where
type CTVar (RL.RWST r w s m) = CTVar m
retry = lift retry
orElse ma mb = RL.RWST $ \r s -> orElse (RL.runRWST ma r s) (RL.runRWST mb r s)
check = lift . check
newCTVar = lift . newCTVar
readCTVar = lift . readCTVar
writeCTVar v = lift . writeCTVar v
instance (MonadSTM m, Monoid w) => MonadSTM (RS.RWST r w s m) where
type CTVar (RS.RWST r w s m) = CTVar m
retry = lift retry
orElse ma mb = RS.RWST $ \r s -> orElse (RS.runRWST ma r s) (RS.runRWST mb r s)
check = lift . check
newCTVar = lift . newCTVar
readCTVar = lift . readCTVar
writeCTVar v = lift . writeCTVar v
| bitemyapp/dejafu | Control/Monad/STM/Class.hs | mit | 5,534 | 0 | 12 | 1,262 | 1,550 | 843 | 707 | 95 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.