code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Tree.Lens -- Copyright : (C) 2012-14 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : MTPCs -- ---------------------------------------------------------------------------- module Data.Tree.Lens ( root , branches ) where import Control.Lens import Data.Functor import Data.Tree -- | A 'Lens' that focuses on the root of a 'Tree'. -- -- >>> view root $ Node 42 [] -- 42 root :: Lens' (Tree a) a root f (Node a as) = (`Node` as) <$> f a {-# INLINE root #-} -- | A 'Lens' returning the direct descendants of the root of a 'Tree' -- -- @'view' 'branches' ≡ 'subForest'@ branches :: Lens' (Tree a) [Tree a] branches f (Node a as) = Node a <$> f as {-# INLINE branches #-}
hvr/lens
src/Data/Tree/Lens.hs
bsd-3-clause
934
0
7
172
147
88
59
13
1
{- Author: Wishnu Prasetya Copyright 2011 Utrecht University The use of this sofware is free under the Modified BSD License. -} {- | This module provides a type representing serialized objects which are to be read from a log, and: * a parser to read from semi compressed raw log. * XML formater. -} module Eu.Fittest.Logging.XML.Value( Value_(..), FieldSentence_(..), Field_(..), parseValue, parseSingleParValTy, buildXREFmap, getAllField_, getField_, getField__, getDeepAllField, getDeepField, getValType, getXID, maxXID, renumberXID, isNull, isUndefined, isUnserializable, isArray, isCollection, isDictionary, getArrayElems, getArrayElemsTypes, getCollectionElems, getCollectionElemsTypes, getDictionaryElems, getDictionaryKeysTypes, getDictionaryValsTypes, fieldName --isSing ) where import Debug.Trace import Text.ParserCombinators.ReadP import Data.Maybe import Data.IntMap import Data.List import Text.XML.Light import Eu.Fittest.Logging.XML.Base import Eu.Fittest.Logging.Compression.RawlogParser import Eu.Fittest.Logging.Compression.Compress -- | Type representing a serialized value or object in the log. data Value_ = SingleVal_ { vVal::String, vTy:: String } -- single line value | Obj_ { ocname :: String, ofields::[Field_] } -- class name, fields deriving (Show,Eq) {- ============================================================== The parser part. It parses from semi-compressed log. ============================================================== -} -- | To parse a Value_ from a semi-compressed raw log. parseValue :: CompressedLogParser Value_ parseValue = parseSingleParValTy <<| parseObj -- | To parse a single paragraph Value_ from compressed log. parseSingleParValTy :: CompressedLogParser Value_ parseSingleParValTy = do { dict <- getDict_ ; p <- satisfy_ isParagraph `elseError` "Parsing a sigle-par value. Expecting a paragraph"; case readVal dict p of Just rv -> return rv _ -> fail "Parsing a single-par value. Fail on its sentence" `withEvidence` [p] } where readVal dict (Par (Par_ [s])) = -- maybe monad do { (x,ty) <- splitValSentence s ; return (SingleVal_ { vVal=x, vTy=ty }) } readVal dict (Par (Par_ _)) = Nothing readVal dict (Par (XPar_ i)) = -- maybe monad do { sentences <- Data.IntMap.lookup i dict ; case sentences of [s] -> do { (x,ty) <- splitValSentence s ; return (SingleVal_ { vVal=x, vTy=ty }) } _ -> fail "" } -- | to split a sentence of the form val:ty splitValSentence s = if couldNotSerialize then Just ("??", drop 3 s) -- case ?? else if isString then Just (splitOnClosingQuote s) -- case string else if not(Prelude.null ty_) then Just (v, tail ty_) -- other cases else Nothing where couldNotSerialize = take 2 s == "??" isString = take 1 s == "\"" (v,ty_) = break (== ':') s splitOnClosingQuote t = ('\"' : reverse b, tail(reverse a)) where (a,b) = break (== '\"') (reverse (tail t)) -- | To parse an object from compressed log. parseObj :: CompressedLogParser Value_ parseObj = do { dict <- getDict_ ; s@(Section _ tag_ elems) <- satisfy_ isSection `elseError` "Parsing an object. Expecting a section" ; case getTag dict tag_ of Nothing -> fail "Parsing an object. Tag cannot be found in dict" `withEvidence` [s] Just tag -> if isObjectTag tag then -- parse the elements of the section case runCLparser parseFields dict elems of Right (fields,[]) -> return (Obj_ { ocname = getType tag, ofields = fields } ) _ -> fail "Parsing an object. Failing on subobjects" `withEvidence` [s] else fail "Parsing an object. Failing on the syntax of the tag" `withEvidence` [s] } where getTag dict (Tag_ t) = Just t getTag dict (XTag_ i) = do { t <- Data.IntMap.lookup i dict ; if isSing t then return (head t) else fail "" } isObjectTag tag = take 2 tag == "O:" getType tag = drop 2 tag isSing [x] = True isSing _ = False -- intermediate type to represent a field data FieldSentence_ = FnValTy_ String String String -- name=3:int | FnXref_ String Int -- name=^1 | FnNextObj_ String -- name=> deriving Show isFnNextObj_ (FnNextObj_ _) = True isFnNextObj_ _ = False -- another intermediate type to represent a field data Field_ = FieldValTy_ String String String -- name,value,type | FieldXref_ String Int -- name,ref | FieldObj_ String Value_ -- name,obj deriving (Show,Eq) -- | to split a setence of the form field=something splitFieldSentence s = if Prelude.null s2 then Nothing else if separator == "=^" then return (FnXref_ fn (read . drop 2 $ s2)) -- case =^ else if separator == "=>" then return (FnNextObj_ fn) -- case => else -- maybe monad -- case = do { (v,ty) <- splitValSentence (tail s2) ; return (FnValTy_ fn v ty) } where (fn,s2) = break (== '=') s separator = take 2 s2 -- to parser a paragraph containing (possibly multiple) fields parseFieldsPar dict (Par (XPar_ i)) = -- on maybe monad do { sentences <- Data.IntMap.lookup i dict ; sequence (Prelude.map splitFieldSentence sentences) } parseFieldsPar dict (Par (Par_ sentences)) = sequence (Prelude.map splitFieldSentence sentences) -- To parse a list of section fragments to a list fo fields. -- This includes handling the =^ type of field. parseFields = eof_ [] <<| do { dict <- getDict_ ; par <- satisfy_ isParagraph `elseError` "Parsing a field-group. Expecting a paragraph" ; case parseFieldsPar dict par of Nothing -> fail "Parsing a field-group. Failing on a paragrah" `withEvidence` [par] Just fields_ -> do { (rest,lastf) <- return (splitAtLast fields_) ; if isSing lastf && isFnNextObj_ (head lastf) then do { --special case, when last field is =^ fields <- return (Prelude.map convert rest) ; FnNextObj_ fn <- return (head lastf) ; obj <- parseObj ; -- getting the next object morefields <- parseFields ; -- recursion return (fields ++ [FieldObj_ fn obj] ++ morefields) } else do { --normal case, when last field is not =^ fields <- return (Prelude.map convert fields_) ; morefields <- parseFields ; -- recursion return (fields ++ morefields) } } } where convert (FnValTy_ fn v ty) = FieldValTy_ fn v ty convert (FnXref_ fn i) = FieldXref_ fn i splitAtLast s = splitAt (length s - 1) s {- ============================================================== The XML formater part ============================================================== -} instance ConvertibleToXML Value_ where toXML (SingleVal_ { vVal=val, vTy=ty }) = mkElem "V" attrs [] where attrs = attribs [("v",val),("ty",ty)] toXML (Obj_ {ocname=cname, ofields=fields }) = mkElem "O" [attrib1 "ty" cname] (Prelude.map toXML fields) instance ConvertibleToXML Field_ where toXML (FieldValTy_ name val ty) = mkElem "fd" [attrib1 "n" name] [toXML (SingleVal_ {vVal=val, vTy=ty})] toXML (FieldXref_ name ref) = mkElem "fd" [attrib1 "n" name] [mkElem "X" [attrib1 "to" (show ref)] []] toXML (FieldObj_ name obj) = mkElem "fd" [attrib1 "n" name] [toXML obj] {- ============================================================== Some utilities to navigate through a value ============================================================== -} -- | This will build the mapping of subobjects and their IDs. -- buildXREFmap :: Value_ -> [(Int,Value_)] buildXREFmap (SingleVal_ _ _) = [] buildXREFmap obj = case id_ of Just (FieldValTy_ _ id _) -> (read id, obj) : map_ _ -> map_ where fields = ofields obj id_ = find isXID fields subObjs = Data.List.map getVal . Data.List.filter isObj $ fields map_ = concat (Data.List.map buildXREFmap subObjs) isObj (FieldObj_ _ _) = True isObj _ = False getVal (FieldObj_ _ val) = val isXID (FieldValTy_ "I" _ "ID") = True isXID _ = False -- | Return the integer ID of an object. -- getXID :: Value_ -> Maybe Int getXID (Obj_ {ocname = _ , ofields=fields }) = case id_ of Just (FieldValTy_ _ id _) -> Just (read id) _ -> Nothing where id_ = find isXID fields -- | Return the greatest ID used in an object. maxXID val = maximum (0 : Data.List.map fst (buildXREFmap val)) -- | Renumber the IDs in an object by increasing them with k -- renumberXID k v@(SingleVal_ _ _) = v renumberXID k v@(Obj_ {ocname = cn , ofields=fields }) = (Obj_ {ocname = cn , ofields=fields2 }) where id_ = getXID v fields2 = case id_ of Nothing -> [renumberXID_ k f | f <- fields] Just i -> let new_id = FieldValTy_ "I" (show (i+k)) "ID" fields3 = [ f | f <- fields, not . isXID $ f ] in new_id : [renumberXID_ k f | f <- fields3] renumberXID_ k field = case field of FieldXref_ n i -> FieldXref_ n (i+k) FieldObj_ n o -> FieldObj_ n (renumberXID k o) _ -> field -- | Return the list of values associated to the field fn of the given -- object. A FITTEST object may have multiple values associated to -- the same field. -- getAllField_ :: [(Int,Value_)] -> String -> Value_ -> [Value_] getAllField_ xREFmap fn (SingleVal_ _ _) = [] getAllField_ xREFmap fn (Obj_ {ocname = _ , ofields=fields }) = concat [ fieldVal xREFmap f | f<-fields, fieldName f == fn ] fieldName (FieldValTy_ n _ _) = n fieldName (FieldXref_ n _) = n fieldName (FieldObj_ n _) = n fieldVal xREFmap field = case field of FieldValTy_ _ val ty -> [SingleVal_ val ty] FieldXref_ _ id -> case find ((== id) . fst) xREFmap of Just (_,o) -> [o] _ -> [] FieldObj_ _ o -> [o] -- | Return just a single value associated to a field in a given value. getField_ :: [(Int,Value_)] -> String -> Value_ -> Maybe Value_ getField_ xREFmap fn val = case getAllField_ xREFmap fn val of [] -> Nothing (o:_) -> Just o -- | Same as getField_ , but it assumes that the field exists. getField__ :: [(Int,Value_)] -> String -> Value_ -> Value_ getField__ xREFmap fn val = fromJust . getField_ xREFmap fn $ val -- | Same as getAllField, but can get to a field that is deeper -- in an object. Such a field is specified by a path. getDeepAllField :: [(Int,Value_)] -> [String] -> Value_ -> [Value_] getDeepAllField xREFmap path val = worker path val where worker [] _ = [] worker [fn] val = getAllField_ xREFmap fn val worker (fn:therest) val = concat [ worker therest o | o <- subObjs ] where subObjs = getAllField_ xREFmap fn val -- | Same as getField_, but can get to a field that is deeper -- in an object. Such a field is specified by a path. getDeepField :: [(Int,Value_)] -> [String] -> Value_ -> Maybe Value_ getDeepField xREFmap path val = case getDeepAllField xREFmap path val of [] -> Nothing (o:_) -> Just o getValType (SingleVal_ {vVal=_ , vTy=ty}) = ty getValType (Obj_ {ocname=c, ofields=_}) = c isNull (SingleVal_ {vVal=_ , vTy=ty}) = ty == "Null" isNull _ = False isUndefined (SingleVal_ {vVal=_, vTy=ty}) = ty == "void" isUndefined _ = False isUnserializable (SingleVal_ {vVal=val, vTy=_}) = val == "??" isArray v = getValType v == "Array" isCollection v = getValType v == "Collection" isDictionary v = getValType v == "Dictionary" getArrayElems xREFmap a = getAllField_ xREFmap "elem" a getArrayElemsTypes xREFmap a = [getValType v | v <- getArrayElems xREFmap a] getCollectionElems xREFmap c = getAllField_ xREFmap "elem" c getCollectionElemsTypes xREFmap c = [getValType v | v <- getCollectionElems xREFmap c] getDictionaryElems xREFmap d = zip keys vals where keys = getAllField_ xREFmap "key" d vals = getAllField_ xREFmap "val" d getDictionaryKeysTypes xREFmap d = [ getValType k | (k,_)<-getDictionaryElems xREFmap d] getDictionaryValsTypes xREFmap d = [ getValType v | (_,v)<-getDictionaryElems xREFmap d] {- ============================================================== Examples for test use e.g. uncurry (topRunCLparser parser) exPar1 to test parsers putStr . ppElement . toXML . uncurry (topRunCLparser parser) $ exPar1 to test XML converter ============================================================== -} exPar0 = (dic,log2) where (dic,log1) = strCompress "%<P %>" log2 = decompressTimeStamp log1 exPar1 = (dic,log2) where (dic,log1) = strCompress "%<P %<{ 3:int }%> %>" log2 = decompressTimeStamp log1 exPar2 = (dic,log2) where (dic,log1) = strCompress "%<P %<{ \"hello\":String }%> %>" log2 = decompressTimeStamp log1 exPar3 = (dic, tail log2) where (dic,log1) = strCompress "%<P %<{ 3:int }%> %> %<P %<{ 3:int }%> %>" log2 = decompressTimeStamp log1 exPar4 = (dic,log2) where (dic,log1) = strCompress "%<P %<{ 3:int }%> %<{ 4:int }%> %>" log2 = decompressTimeStamp log1 exPar5 = (dic,log2) where (dic,log1) = strCompress "%<P %<{ }%> %>" log2 = decompressTimeStamp log1 exObj1 = (dic,log2) where (dic,log1) = strCompress "%<S 0:0 \"O:package::class\" %<P %<{ x=100:int}%>%>%>" log2 = decompressTimeStamp log1 exObj2 = (dic,log2) where (dic,log1) = strCompress "%<S 0:0 \"O:packageA.B.C::class\" %<P %<{ x=100:int}%> %<{ y=??:pck.A.B::class }%> %>%>" log2 = decompressTimeStamp log1 exObj3 = (dic,log2) where (dic,log1) = strCompress "%<S 0:0 \"O:packageA.B.C::class\" %<P %<{ x=100:int}%>%> %<P%<{ y=^1 }%> %>%>" log2 = decompressTimeStamp log1 exObj4 = (dic,log2) where (dic,log1) = strCompress "%<S 0:0 \"O:packageA.B.C::class\" %<P %<{ next=> }%>%> %<S 0:1 \"O:packageA.B.C::class\" %<P %<{ next=null:Null }%>%>%> %<P %<{ x=100:int}%>%> %>" log2 = decompressTimeStamp log1
aelyasov/Haslog
src/Eu/Fittest/Logging/XML/Value.hs
bsd-3-clause
16,933
218
23
6,144
3,802
2,091
1,711
281
6
{-# LANGUAGE TemplateHaskell #-} module Reify where import Language.Haskell.TH import Control.Applicative testReify :: Q [Con] testReify = do DataConI _ (ConT n) _ _ <- reify 'True TyConI (DataD _ _ _ c _) <- reify n return c noOthers :: Pat -> Q Bool noOthers (LitP _) = return True noOthers (VarP _) = return True noOthers (TupP pats) = and <$> mapM noOthers pats noOthers (UnboxedTupP pats) = and <$> mapM noOthers pats -- noOthers noOthers WildP = return True
YoshikuniJujo/papillon
test/templateHaskell/Reify.hs
bsd-3-clause
471
0
10
89
195
96
99
15
1
{-# LANGUAGE OverloadedStrings #-} module MultisetExample where import qualified Data.MultiSet as MultiSet import qualified Data.Text.Lazy as LazyText import qualified Data.Text.Lazy.Builder as LazyBuilder import Data.Text.Lazy.Builder.Int (decimal) import Data.Ord (Down(..)) import qualified Data.Char as Char import qualified Data.List as List import Control.Arrow ((>>>)) import Data.Monoid ((<>)) -- | Break up text into "words" separated by spaces, while treating -- non-letters as spaces, count them, output a report line for each -- word and its count in descending order of count but ascending order -- of word. wordCount :: LazyText.Text -> LazyText.Text wordCount = LazyText.map replaceNonLetterWithSpace >>> LazyText.words >>> MultiSet.fromList >>> MultiSet.toOccurList >>> List.sortOn (snd >>> Down) >>> map summarizeWordCount >>> mconcat >>> LazyBuilder.toLazyText -- | Same thing, using traditional right-to-left composition. wordCountTraditional :: LazyText.Text -> LazyText.Text wordCountTraditional = LazyBuilder.toLazyText . mconcat . map summarizeWordCount . List.sortOn (Down . snd) . MultiSet.toOccurList . MultiSet.fromList . LazyText.words . LazyText.map replaceNonLetterWithSpace replaceNonLetterWithSpace :: Char -> Char replaceNonLetterWithSpace c | Char.isLetter c = c | otherwise = ' ' summarizeWordCount :: (LazyText.Text, MultiSet.Occur) -> LazyBuilder.Builder summarizeWordCount (word, count) = LazyBuilder.fromLazyText word <> " " <> decimal count <> "\n"
FranklinChen/twenty-four-days2015-of-hackage
src/MultisetExample.hs
bsd-3-clause
1,533
0
13
227
344
196
148
38
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} import GHC.Conc (numCapabilities) import System.FilePath.Posix ((</>)) import System.Directory (getDirectoryContents) import System.IO (hPutStrLn, stderr) import qualified System.Console.CmdArgs as A import System.Console.CmdArgs ((&=)) import Search.Common import qualified Search.Dictionary as D import qualified Search.Collection as C import qualified Search.SearchIndex as SI import Search.Processing (extractWords) import Control.Monad (liftM, replicateM) import Control.Concurrent.ThreadPool (concurrentMapN) import Control.DeepSeq import qualified Data.List as L import qualified Data.Vector.Generic as VG import qualified Data.Vector as V import qualified Data.Vector.Unboxed as VU import qualified Data.IntMap.Strict as I import System.Random (randomRIO) import Data.Maybe (mapMaybe) import qualified Data.Text as T import qualified Data.Text.IO as TIO import Data.Binary isSearchIndexFile :: String -> Bool isSearchIndexFile str | "searchindex_" `L.isPrefixOf` str = True | otherwise = False type SearchIndexSizes = I.IntMap Int data PostingsLengths = PostingsLengths { totalLength1 :: !Int , totalLength2 :: !Int , lengths1s :: !(VU.Vector Int) , lengths2s :: !(VU.Vector Int) } postingsLengths :: V.Vector (SearchIndexSizes) -> Token -> Token -> PostingsLengths postingsLengths sizes t1 t2 = PostingsLengths { totalLength1 = VU.sum $ l1s , totalLength2 = VU.sum $ l2s , lengths1s = l1s , lengths2s = l2s } where lens (Token t) = I.findWithDefault 0 (fromIntegral t) l1s = V.convert $ V.map (lens t1) sizes l2s = V.convert $ V.map (lens t2) sizes type ComplexityFunc = Int -> Int -> Double minFunc :: ComplexityFunc minFunc x y = fromIntegral $ min x y cacheFunc :: ComplexityFunc cacheFunc x y = if minV == 0 then 0 else (fromIntegral minV) * (-350*(fromIntegral minV/ fromIntegral maxV) + 400) where minV = min x y maxV = max x y logFunc :: ComplexityFunc logFunc x y = if minV == 0 then 0 else (fromIntegral minV) * log (fromIntegral minV/ fromIntegral maxV) where minV = min x y maxV = max x y sum' :: Num a => [a] -> a sum' = L.foldl' (+) 0 printSpeedups :: [PostingsLengths] -> IO () printSpeedups pls = do putStrLn $ "Average speedup: " ++ (show $ sum' speedups / fromIntegral (length speedups)) let totalComp = sum' $ map complexityTotal pls let clusterComp = sum' $ map (complexityCluster True) pls let clusterComp' = sum' $ map (complexityCluster False) pls putStrLn $ "Total speedup: " ++ show (speedup totalComp clusterComp) ++ "(" ++ show totalComp ++ "/" ++ show clusterComp ++ ")" putStrLn $ "Total speedup (only list intersection)" ++ show (speedup totalComp clusterComp') let clusterContainments = map (VU.length . nonEmpty) pls putStrLn $ "Average cluster containment: " ++ show ((fromIntegral $ sum' clusterContainments) / (fromIntegral $ length pls)) where complexity = minFunc complexityTotal pl = complexity (totalLength1 pl) (totalLength2 pl) zippedLengths pl = VU.zip (lengths1s pl) (lengths2s pl) nonEmpty pl = VU.filter (\(a,b) -> a /= 0 && b /= 0) $ zippedLengths pl complexityCluster merge pl = let c1 = VU.sum $ VU.map (uncurry complexity) (nonEmpty pl) c2 = complexity (VU.length $ zippedLengths pl) (VU.length $ nonEmpty pl) in c1 + (if merge then c2 else 0) speedup x y = if y == 0 then 1 else x/y speedups = map (\pl -> speedup (complexityTotal pl) (complexityCluster True pl)) pls printRatios :: [PostingsLengths] -> IO () printRatios pls = mapM_ printRatio pls where printRatio pl = do let op = ratioOp pl putStr $ show $ op (totalLength1 pl) (totalLength2 pl) putStr " " let zipped = VU.zip (lengths1s pl) (lengths2s pl) let printSingle (l1,l2) = do putStr $ (show $ op l1 l2) ++ " " VU.mapM_ printSingle zipped putStrLn "" safeDiv x y = if y == 0 then 0 else (fromIntegral x) / (fromIntegral y) ratioOp :: PostingsLengths -> Int -> Int -> Double ratioOp pl = if (totalLength1 pl > totalLength2 pl) then flip safeDiv else safeDiv printSizes :: [PostingsLengths] -> IO () printSizes pls = mapM_ printSize pls where printSize pl = do putStrLn $ showSizes (totalLength1 pl) (totalLength2 pl) let zipped = V.convert $ VU.zip (lengths1s pl) (lengths2s pl) putStrLn $ show $ V.map (uncurry showSizes) zipped where showSizes a b = show a ++ "/" ++ show b pickV :: VG.Vector v a => v a -> IO a pickV v | VG.length v == 0 = error "empty vector" | otherwise = liftM (v VG.!) $ randomRIO (0, VG.length v - 1) readLine :: D.WordMap -> T.Text -> Maybe (Token, Token) readLine dict line = let terms = extractWords line tokens = L.nub $ mapMaybe (D.lookupWord dict) terms in if length tokens /= 2 then Nothing else Just $ (head tokens, tokens !! 1) pickRandomQuery :: C.DocCollection a -> IO (Token, Token) pickRandomQuery coll = do did <- liftM (DocId . fromIntegral) $ randomRIO (0, C.collectionSize coll - 1) doc <- C.loadTokenDoc coll did let docV = vectorFromDoc $ tokenDoc doc if VU.length docV == 0 then pickRandomQuery coll else do t1 <- pickV docV t2 <- pickV docV return (t1,t2) data StatsMode = SMSpeedup | SMClusterRatios | SMClusterSizes deriving (Eq, Show, A.Data, A.Typeable) data LArgs = LArgs { indexDir :: FilePath , collectionDir :: FilePath , randomQueries :: Maybe Int , statsMode :: StatsMode } deriving (Eq, Show, A.Data, A.Typeable) lArgs :: LArgs lArgs = LArgs { indexDir = A.def &= A.typ "SEARCH_INDEX_DIR" &= A.argPos 0 , collectionDir = A.def &= A.typ "COLLECTION" &= A.argPos 1 , randomQueries = Nothing &= A.typ "NUM" &= A.help "use n randomly generated queries" , statsMode = A.enum [ SMSpeedup &= A.explicit &= A.name "speedup" &= A.help "show speedup stats" , SMClusterRatios &= A.explicit &= A.name "ratio" &= A.help "show ratios of list length" , SMClusterSizes &= A.explicit &= A.name "sizes" &= A.help "show list sizes" ] } loadSearchIndexSizes :: FilePath -> IO SearchIndexSizes loadSearchIndexSizes path = do putInfo $ "Loading index file " ++ show path si <- decodeFile path let !sizesMap = VU.foldl' add I.empty $ VU.indexed $ SI.numDocsPerTerm si return sizesMap where add m (i,v) | v == 0 = m | otherwise = I.insert i v m putInfo :: String -> IO () putInfo = hPutStrLn stderr main :: IO () main = do args <- A.cmdArgs lArgs let baseDir = indexDir args putInfo $ "Loading Document collection" !coll <- C.loadDocCollection (collectionDir args) putInfo $ "Loading queries" !queries <- case (randomQueries args) of Just num -> do replicateM num (pickRandomQuery coll) Nothing -> do !dict <- liftM D.buildWordMap $ C.loadTokenMap coll ls <- liftM T.lines TIO.getContents return $!! mapMaybe (readLine dict) ls putInfo $ "Loading indexes" files <- getDirectoryContents baseDir let indexFiles = map (baseDir </>) $ filter isSearchIndexFile files putInfo $ "Number of clusters: " ++ (show $ length indexFiles) !ci <- liftM V.fromList $ concurrentMapN numCapabilities loadSearchIndexSizes indexFiles let lens = map (uncurry $ postingsLengths ci) queries case (statsMode args) of SMSpeedup -> printSpeedups lens SMClusterRatios -> printRatios lens SMClusterSizes -> printSizes lens
jdimond/diplomarbeit
tools/LookupComplexity.hs
bsd-3-clause
8,221
70
19
2,323
2,730
1,383
1,347
185
4
{-# LANGUAGE NoMonomorphismRestriction #-} module Main ( main ) where import qualified Data.Vector.Unboxed as V import Data.Random.Source.PureMT import Data.Random import Control.Monad.State import System.Environment(getArgs) import Data.Colour.Names import Data.Colour import Control.Lens import Data.Default.Class import Data.Time.LocalTime import Graphics.Rendering.Chart import Graphics.Rendering.Chart.Backend.Cairo nSamples :: Int nSamples = 10000 beta :: Double beta = 2.0 testXs :: Int -> V.Vector Double testXs m = V.fromList $ evalState (replicateM m (sample StdUniform)) (pureMT 2) testEpsilons :: Int -> V.Vector Double testEpsilons m = V.fromList $ evalState (replicateM m (sample StdNormal)) (pureMT 2) testYs m = V.zipWith (\x e -> beta * x + e) (testXs m) (testEpsilons m) prices' :: [(Double,Double)] prices' = V.toList $ V.zip (testXs nSamples) (testYs nSamples) chart = toRenderable layout where price1 = plot_points_style . point_color .~ opaque red $ plot_points_values .~ prices' $ plot_points_title .~ "price 1" $ def layout = layoutlr_title .~"Price History" $ layoutlr_left_axis . laxis_override .~ axisGridHide $ layoutlr_right_axis . laxis_override .~ axisGridHide $ layoutlr_x_axis . laxis_override .~ axisGridHide $ layoutlr_plots .~ [Left (toPlot price1), Right (toPlot price1)] $ layoutlr_grid_last .~ False $ def main = renderableToFile def chart "example2_big.png"
idontgetoutmuch/StochVol
LinRegSingle.hs
bsd-3-clause
1,583
0
21
366
453
246
207
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} ----------------------------------------------------------------------------- -- | -- Module : Text.CSL.Input.Bibtex -- Copyright : (c) John MacFarlane -- License : BSD-style (see LICENSE) -- -- Maintainer : John MacFarlane <fiddlosopher@gmail.com> -- Stability : unstable-- Portability : unportable -- ----------------------------------------------------------------------------- module Text.CSL.Input.Bibtex ( readBibtex , readBibtexString , Lang(..) , langToLocale , getLangFromEnv ) where import Prelude import Control.Applicative import qualified Control.Exception as E import Control.Monad import Control.Monad.RWS hiding ((<>)) import qualified Data.ByteString as B import Data.Char (isAlphaNum, isDigit, isUpper, toLower, toUpper) import Data.List (foldl', intercalate) import Data.List.Split (splitOn, splitWhen, wordsBy) import qualified Data.Map as Map import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import System.Environment (getEnvironment) import Text.CSL.Compat.Pandoc (readLaTeX) import Text.CSL.Exception (CiteprocException (ErrorReadingBib, ErrorReadingBibFile)) import Text.CSL.Parser (parseLocale) import Text.CSL.Reference import Text.CSL.Style (Agent (..), emptyAgent, CslTerm (..), Formatted (..), Locale (..)) import Text.CSL.Util (onBlocks, protectCase, safeRead, splitWhen, splitStrWhen, trim, unTitlecase, addSpaceAfterPeriod) import Text.Pandoc.Definition import qualified Text.Pandoc.Walk as Walk import Text.Parsec hiding (State, many, (<|>)) blocksToFormatted :: [Block] -> Bib Formatted blocksToFormatted bs = case bs of [Plain xs] -> inlinesToFormatted xs [Para xs] -> inlinesToFormatted xs _ -> inlinesToFormatted $ Walk.query (:[]) bs adjustSpans :: Lang -> Inline -> [Inline] adjustSpans _ (Span ("",[],[]) xs) = xs adjustSpans lang (RawInline (Format "latex") s) | s == "\\hyphen" || s == "\\hyphen " = [Str "-"] | otherwise = Walk.walk (concatMap (adjustSpans lang)) $ parseRawLaTeX lang s adjustSpans _ x = [x] parseRawLaTeX :: Lang -> Text -> [Inline] parseRawLaTeX lang (T.stripPrefix "\\" -> Just xs) = case latex' contents of [Para ys] -> f command ys [Plain ys] -> f command ys _ -> [] where (command', contents') = T.break (=='{') xs command = trim command' contents = T.drop 1 $ T.dropEnd 1 contents' f "mkbibquote" ils = [Quoted DoubleQuote ils] f "mkbibemph" ils = [Emph ils] f "mkbibitalic" ils = [Emph ils] -- TODO: italic/=emph f "mkbibbold" ils = [Strong ils] f "mkbibparens" ils = [Str "("] ++ ils ++ [Str ")"] -- TODO: ... f "mkbibbrackets" ils = [Str "["] ++ ils ++ [Str "]"] -- TODO: ... -- ... both should be nestable & should work in year fields f "autocap" ils = ils -- TODO: should work in year fields f "textnormal" ils = [Span ("",["nodecor"],[]) ils] f "bibstring" [Str s] = [Str $ resolveKey' lang s] f _ ils = [Span nullAttr ils] parseRawLaTeX _ _ = [] inlinesToFormatted :: [Inline] -> Bib Formatted inlinesToFormatted ils = do lang <- gets localeLanguage return $ Formatted $ Walk.walk (concatMap (adjustSpans lang)) ils data Item = Item{ identifier :: Text , entryType :: Text , fields :: Map.Map Text Text } -- | Get 'Lang' from the environment variable LANG, defaulting to en-US. getLangFromEnv :: IO Lang getLangFromEnv = do env <- getEnvironment return $ case lookup "LANG" env of Just x -> case Text.CSL.Util.splitWhen (\c -> c == '_' || c == '-') (T.takeWhile (/='.') (T.pack x)) of (w:z:_) -> Lang w z [w] | not (T.null w) -> Lang w mempty _ -> Lang "en" "US" Nothing -> Lang "en" "US" -- | Parse a BibTeX or BibLaTeX file into a list of 'Reference's. -- The first parameter is a predicate to filter identifiers. -- If the second parameter is true, the file will be treated as -- BibTeX; otherwise as BibLaTeX. If the third parameter is -- true, an "untitlecase" transformation will be performed. readBibtex :: (Text -> Bool) -> Bool -> Bool -> FilePath -> IO [Reference] readBibtex idpred isBibtex caseTransform f = do contents <- decodeUtf8 <$> B.readFile f E.catch (readBibtexString idpred isBibtex caseTransform contents) (\e -> case e of ErrorReadingBib es -> E.throwIO $ ErrorReadingBibFile f es _ -> E.throwIO e) -- | Like 'readBibtex' but operates on Text rather than a file. readBibtexString :: (Text -> Bool) -> Bool -> Bool -> Text -> IO [Reference] readBibtexString idpred isBibtex caseTransform contents = do lang <- getLangFromEnv locale <- parseLocale (langToLocale lang) case runParser (bibEntries <* eof) Map.empty "stdin" contents of -- drop 8 to remove "stdin" + space Left err -> E.throwIO $ ErrorReadingBib $ drop 8 $ show err Right xs -> return $ mapMaybe (itemToReference lang locale isBibtex caseTransform) (filter (idpred . identifier) (resolveCrossRefs isBibtex xs)) type BibParser = Parsec Text (Map.Map Text Text) bibEntries :: BibParser [Item] bibEntries = do skipMany nonEntry many (bibItem <* skipMany nonEntry) where nonEntry = bibSkip <|> try (char '@' >> (bibComment <|> bibPreamble <|> bibString)) bibSkip :: BibParser () bibSkip = skipMany1 (satisfy (/='@')) bibComment :: BibParser () bibComment = do cistring "comment" spaces void inBraces <|> bibSkip <|> return () bibPreamble :: BibParser () bibPreamble = do cistring "preamble" spaces void inBraces bibString :: BibParser () bibString = do cistring "string" spaces char '{' spaces (k,v) <- entField char '}' updateState (Map.insert k v) return () inBraces :: BibParser Text inBraces = try $ do char '{' res <- manyTill ( (T.pack <$> many1 (noneOf "{}\\")) <|> (char '\\' >> ( (char '{' >> return "\\{") <|> (char '}' >> return "\\}") <|> return "\\")) <|> (braced <$> inBraces) ) (char '}') return $ T.concat res braced :: Text -> Text braced = T.cons '{' . flip T.snoc '}' inQuotes :: BibParser Text inQuotes = do char '"' T.concat <$> manyTill ( (T.pack <$> many1 (noneOf "\"\\{")) <|> (char '\\' >> T.cons '\\' . T.singleton <$> anyChar) <|> braced <$> inBraces ) (char '"') fieldName :: BibParser Text fieldName = resolveAlias . T.toLower . T.pack <$> many1 (letter <|> digit <|> oneOf "-_:+") isBibtexKeyChar :: Char -> Bool isBibtexKeyChar c = isAlphaNum c || c `elem` (".:;?!`'()/*@_+=-[]*&" :: String) bibItem :: BibParser Item bibItem = do char '@' enttype <- map toLower <$> many1 letter spaces char '{' spaces entid <- many1 (satisfy isBibtexKeyChar) spaces char ',' spaces entfields <- entField `sepEndBy` (char ',' >> spaces) spaces char '}' return $ Item (T.pack entid) (T.pack enttype) (Map.fromList entfields) entField :: BibParser (Text, Text) entField = do k <- fieldName spaces char '=' spaces vs <- (expandString <|> inQuotes <|> inBraces <|> rawWord) `sepBy` try (spaces >> char '#' >> spaces) spaces return (k, T.concat vs) resolveAlias :: Text -> Text resolveAlias "archiveprefix" = "eprinttype" resolveAlias "primaryclass" = "eprintclass" resolveAlias s = s rawWord :: BibParser Text rawWord = T.pack <$> many1 alphaNum expandString :: BibParser Text expandString = do k <- fieldName strs <- getState case Map.lookup k strs of Just v -> return v Nothing -> return k -- return raw key if not found cistring :: Text -> BibParser Text cistring s = try (go s) where go t = case T.uncons t of Nothing -> return "" Just (c,cs) -> do x <- char (toLower c) <|> char (toUpper c) xs <- go cs return (T.cons x xs) resolveCrossRefs :: Bool -> [Item] -> [Item] resolveCrossRefs isBibtex entries = map (resolveCrossRef isBibtex entries) entries splitKeys :: Text -> [Text] splitKeys = filter (not . T.null) . T.split (\c -> c == ' ' || c == ',') getXrefFields :: Bool -> Item -> [Item] -> Text -> [(Text, Text)] getXrefFields isBibtex baseEntry entries keys = do let keys' = splitKeys keys xrefEntry <- [e | e <- entries, identifier e `elem` keys'] (k, v) <- Map.toList $ fields xrefEntry if k == "crossref" || k == "xdata" then do xs <- mapM (getXrefFields isBibtex baseEntry entries) (splitKeys v) (x, y) <- xs guard $ isNothing $ Map.lookup x $ fields xrefEntry return (x, y) else do k' <- if isBibtex then return k else transformKey (entryType xrefEntry) (entryType baseEntry) k guard $ isNothing $ Map.lookup k' $ fields baseEntry return (k',v) resolveCrossRef :: Bool -> [Item] -> Item -> Item resolveCrossRef isBibtex entries entry = Map.foldrWithKey go entry (fields entry) where go key val entry' = if key == "crossref" || key == "xdata" then entry'{ fields = fields entry' <> Map.fromList (getXrefFields isBibtex entry entries val) } else entry' -- transformKey source target key -- derived from Appendix C of bibtex manual transformKey :: Text -> Text -> Text -> [Text] transformKey _ _ "ids" = [] transformKey _ _ "crossref" = [] transformKey _ _ "xref" = [] transformKey _ _ "entryset" = [] transformKey _ _ "entrysubtype" = [] transformKey _ _ "execute" = [] transformKey _ _ "label" = [] transformKey _ _ "options" = [] transformKey _ _ "presort" = [] transformKey _ _ "related" = [] transformKey _ _ "relatedoptions" = [] transformKey _ _ "relatedstring" = [] transformKey _ _ "relatedtype" = [] transformKey _ _ "shorthand" = [] transformKey _ _ "shorthandintro" = [] transformKey _ _ "sortkey" = [] transformKey x y "author" | x `elem` ["mvbook", "book"] && y `elem` ["inbook", "bookinbook", "suppbook"] = ["bookauthor", "author"] -- note: this next clause is not in the biblatex manual, but it makes -- sense in the context of CSL conversion: transformKey x y "author" | x == "mvbook" && y == "book" = ["bookauthor", "author"] transformKey "mvbook" y z | y `elem` ["book", "inbook", "bookinbook", "suppbook"] = standardTrans z transformKey x y z | x `elem` ["mvcollection", "mvreference"] && y `elem` ["collection", "reference", "incollection", "inreference", "suppcollection"] = standardTrans z transformKey "mvproceedings" y z | y `elem` ["proceedings", "inproceedings"] = standardTrans z transformKey "book" y z | y `elem` ["inbook", "bookinbook", "suppbook"] = bookTrans z transformKey x y z | x `elem` ["collection", "reference"] && y `elem` ["incollection", "inreference", "suppcollection"] = bookTrans z transformKey "proceedings" "inproceedings" z = bookTrans z transformKey "periodical" y z | y `elem` ["article", "suppperiodical"] = case z of "title" -> ["journaltitle"] "subtitle" -> ["journalsubtitle"] "shorttitle" -> [] "sorttitle" -> [] "indextitle" -> [] "indexsorttitle" -> [] _ -> [z] transformKey _ _ x = [x] standardTrans :: Text -> [Text] standardTrans z = case z of "title" -> ["maintitle"] "subtitle" -> ["mainsubtitle"] "titleaddon" -> ["maintitleaddon"] "shorttitle" -> [] "sorttitle" -> [] "indextitle" -> [] "indexsorttitle" -> [] _ -> [z] bookTrans :: Text -> [Text] bookTrans z = case z of "title" -> ["booktitle"] "subtitle" -> ["booksubtitle"] "titleaddon" -> ["booktitleaddon"] "shorttitle" -> [] "sorttitle" -> [] "indextitle" -> [] "indexsorttitle" -> [] _ -> [z] -- | A representation of a language and localization. data Lang = Lang Text Text -- e.g. "en" "US" -- | Prints a 'Lang' in BCP 47 format. langToLocale :: Lang -> Text langToLocale (Lang x y) = x <> (if T.null y then "" else T.cons '-' y) -- Biblatex Localization Keys (see Biblatex manual) -- Currently we only map a subset likely to be used in Biblatex *databases* -- (in fields such as `type`, and via `\bibstring{}` commands). resolveKey :: Lang -> Formatted -> Formatted resolveKey lang (Formatted ils) = Formatted (Walk.walk go ils) where go (Str s) = Str $ resolveKey' lang s go x = x -- biblatex localization keys, from files at -- http://github.com/plk/biblatex/tree/master/tex/latex/biblatex/lbx -- Some keys missing in these were added from csl locale files at -- http://github.com/citation-style-language/locales -- labeled "csl" resolveKey' :: Lang -> Text -> Text resolveKey' (Lang "ca" "AD") k = case T.toLower k of "inpreparation" -> "en preparació" "submitted" -> "enviat" "forthcoming" -> "disponible en breu" "inpress" -> "a impremta" "prepublished" -> "pre-publicat" "mathesis" -> "tesi de màster" "phdthesis" -> "tesi doctoral" "candthesis" -> "tesi de candidatura" "techreport" -> "informe tècnic" "resreport" -> "informe de recerca" "software" -> "programari" "datacd" -> "CD de dades" "audiocd" -> "CD d’àudio" "patent" -> "patent" "patentde" -> "patent alemana" "patenteu" -> "patent europea" "patentfr" -> "patent francesa" "patentuk" -> "patent britànica" "patentus" -> "patent estatunidenca" "patreq" -> "soŀlicitud de patent" "patreqde" -> "soŀlicitud de patent alemana" "patreqeu" -> "soŀlicitud de patent europea" "patreqfr" -> "soŀlicitud de patent francesa" "patrequk" -> "soŀlicitud de patent britànica" "patrequs" -> "soŀlicitud de patent estatunidenca" "countryde" -> "Alemanya" "countryeu" -> "Unió Europea" "countryep" -> "Unió Europea" "countryfr" -> "França" "countryuk" -> "Regne Unit" "countryus" -> "Estats Units d’Amèrica" "newseries" -> "sèrie nova" "oldseries" -> "sèrie antiga" _ -> k resolveKey' (Lang "da" "DK") k = case T.toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "kommende" -- csl "inpress" -> "i tryk" -- csl -- "prepublished" -> "" -- missing "mathesis" -> "speciale" "phdthesis" -> "ph.d.-afhandling" "candthesis" -> "kandidatafhandling" "techreport" -> "teknisk rapport" "resreport" -> "forskningsrapport" "software" -> "software" "datacd" -> "data-cd" "audiocd" -> "lyd-cd" "patent" -> "patent" "patentde" -> "tysk patent" "patenteu" -> "europæisk patent" "patentfr" -> "fransk patent" "patentuk" -> "britisk patent" "patentus" -> "amerikansk patent" "patreq" -> "ansøgning om patent" "patreqde" -> "ansøgning om tysk patent" "patreqeu" -> "ansøgning om europæisk patent" "patreqfr" -> "ansøgning om fransk patent" "patrequk" -> "ansøgning om britisk patent" "patrequs" -> "ansøgning om amerikansk patent" "countryde" -> "Tyskland" "countryeu" -> "Europæiske Union" "countryep" -> "Europæiske Union" "countryfr" -> "Frankrig" "countryuk" -> "Storbritanien" "countryus" -> "USA" "newseries" -> "ny serie" "oldseries" -> "gammel serie" _ -> k resolveKey' (Lang "de" "DE") k = case T.toLower k of "inpreparation" -> "in Vorbereitung" "submitted" -> "eingereicht" "forthcoming" -> "im Erscheinen" "inpress" -> "im Druck" "prepublished" -> "Vorveröffentlichung" "mathesis" -> "Magisterarbeit" "phdthesis" -> "Dissertation" -- "candthesis" -> "" -- missing "techreport" -> "Technischer Bericht" "resreport" -> "Forschungsbericht" "software" -> "Computer-Software" "datacd" -> "CD-ROM" "audiocd" -> "Audio-CD" "patent" -> "Patent" "patentde" -> "deutsches Patent" "patenteu" -> "europäisches Patent" "patentfr" -> "französisches Patent" "patentuk" -> "britisches Patent" "patentus" -> "US-Patent" "patreq" -> "Patentanmeldung" "patreqde" -> "deutsche Patentanmeldung" "patreqeu" -> "europäische Patentanmeldung" "patreqfr" -> "französische Patentanmeldung" "patrequk" -> "britische Patentanmeldung" "patrequs" -> "US-Patentanmeldung" "countryde" -> "Deutschland" "countryeu" -> "Europäische Union" "countryep" -> "Europäische Union" "countryfr" -> "Frankreich" "countryuk" -> "Großbritannien" "countryus" -> "USA" "newseries" -> "neue Folge" "oldseries" -> "alte Folge" _ -> k resolveKey' (Lang "en" "US") k = case T.toLower k of "audiocd" -> "audio CD" "by" -> "by" "candthesis" -> "Candidate thesis" "countryde" -> "Germany" "countryep" -> "European Union" "countryeu" -> "European Union" "countryfr" -> "France" "countryuk" -> "United Kingdom" "countryus" -> "United States of America" "datacd" -> "data CD" "edition" -> "ed." "forthcoming" -> "forthcoming" "inpreparation" -> "in preparation" "inpress" -> "in press" "introduction" -> "introduction" "jourser" -> "ser." "mathesis" -> "Master’s thesis" "newseries" -> "new series" "nodate" -> "n. d." "number" -> "no." "numbers" -> "nos." "oldseries" -> "old series" "patent" -> "patent" "patentde" -> "German patent" "patenteu" -> "European patent" "patentfr" -> "French patent" "patentuk" -> "British patent" "patentus" -> "U.S. patent" "patreq" -> "patent request" "patreqde" -> "German patent request" "patreqeu" -> "European patent request" "patreqfr" -> "French patent request" "patrequk" -> "British patent request" "patrequs" -> "U.S. patent request" "phdthesis" -> "PhD thesis" "prepublished" -> "pre-published" "pseudonym" -> "pseud." "recorded" -> "recorded" "resreport" -> "research report" "reviewof" -> "Review of" "revisededition" -> "rev. ed." "software" -> "computer software" "submitted" -> "submitted" "techreport" -> "technical report" "volume" -> "vol." _ -> k resolveKey' (Lang "es" "ES") k = case T.toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "previsto" -- csl "inpress" -> "en imprenta" -- csl -- "prepublished" -> "" -- missing "mathesis" -> "Tesis de licenciatura" "phdthesis" -> "Tesis doctoral" -- "candthesis" -> "" -- missing "techreport" -> "informe técnico" -- "resreport" -> "" -- missing -- "software" -> "" -- missing -- "datacd" -> "" -- missing -- "audiocd" -> "" -- missing "patent" -> "patente" "patentde" -> "patente alemana" "patenteu" -> "patente europea" "patentfr" -> "patente francesa" "patentuk" -> "patente británica" "patentus" -> "patente americana" "patreq" -> "solicitud de patente" "patreqde" -> "solicitud de patente alemana" "patreqeu" -> "solicitud de patente europea" "patreqfr" -> "solicitud de patente francesa" "patrequk" -> "solicitud de patente británica" "patrequs" -> "solicitud de patente americana" "countryde" -> "Alemania" "countryeu" -> "Unión Europea" "countryep" -> "Unión Europea" "countryfr" -> "Francia" "countryuk" -> "Reino Unido" "countryus" -> "Estados Unidos de América" "newseries" -> "nueva época" "oldseries" -> "antigua época" _ -> k resolveKey' (Lang "fi" "FI") k = case T.toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "tulossa" -- csl "inpress" -> "painossa" -- csl -- "prepublished" -> "" -- missing "mathesis" -> "tutkielma" "phdthesis" -> "tohtorinväitöskirja" "candthesis" -> "kandidat" "techreport" -> "tekninen raportti" "resreport" -> "tutkimusraportti" "software" -> "ohjelmisto" "datacd" -> "data-CD" "audiocd" -> "ääni-CD" "patent" -> "patentti" "patentde" -> "saksalainen patentti" "patenteu" -> "Euroopan Unionin patentti" "patentfr" -> "ranskalainen patentti" "patentuk" -> "englantilainen patentti" "patentus" -> "yhdysvaltalainen patentti" "patreq" -> "patenttihakemus" "patreqde" -> "saksalainen patenttihakemus" "patreqeu" -> "Euroopan Unionin patenttihakemus" "patreqfr" -> "ranskalainen patenttihakemus" "patrequk" -> "englantilainen patenttihakemus" "patrequs" -> "yhdysvaltalainen patenttihakemus" "countryde" -> "Saksa" "countryeu" -> "Euroopan Unioni" "countryep" -> "Euroopan Unioni" "countryfr" -> "Ranska" "countryuk" -> "Iso-Britannia" "countryus" -> "Yhdysvallat" "newseries" -> "uusi sarja" "oldseries" -> "vanha sarja" _ -> k resolveKey' (Lang "fr" "FR") k = case T.toLower k of "inpreparation" -> "en préparation" "submitted" -> "soumis" "forthcoming" -> "à paraître" "inpress" -> "sous presse" "prepublished" -> "prépublié" "mathesis" -> "mémoire de master" "phdthesis" -> "thèse de doctorat" "candthesis" -> "thèse de candidature" "techreport" -> "rapport technique" "resreport" -> "rapport scientifique" "software" -> "logiciel" "datacd" -> "cédérom" "audiocd" -> "disque compact audio" "patent" -> "brevet" "patentde" -> "brevet allemand" "patenteu" -> "brevet européen" "patentfr" -> "brevet français" "patentuk" -> "brevet britannique" "patentus" -> "brevet américain" "patreq" -> "demande de brevet" "patreqde" -> "demande de brevet allemand" "patreqeu" -> "demande de brevet européen" "patreqfr" -> "demande de brevet français" "patrequk" -> "demande de brevet britannique" "patrequs" -> "demande de brevet américain" "countryde" -> "Allemagne" "countryeu" -> "Union européenne" "countryep" -> "Union européenne" "countryfr" -> "France" "countryuk" -> "Royaume-Uni" "countryus" -> "États-Unis" "newseries" -> "nouvelle série" "oldseries" -> "ancienne série" _ -> k resolveKey' (Lang "it" "IT") k = case T.toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "futuro" -- csl "inpress" -> "in stampa" -- "prepublished" -> "" -- missing "mathesis" -> "tesi di laurea magistrale" "phdthesis" -> "tesi di dottorato" -- "candthesis" -> "" -- missing "techreport" -> "rapporto tecnico" "resreport" -> "rapporto di ricerca" -- "software" -> "" -- missing -- "datacd" -> "" -- missing -- "audiocd" -> "" -- missing "patent" -> "brevetto" "patentde" -> "brevetto tedesco" "patenteu" -> "brevetto europeo" "patentfr" -> "brevetto francese" "patentuk" -> "brevetto britannico" "patentus" -> "brevetto americano" "patreq" -> "brevetto richiesto" "patreqde" -> "brevetto tedesco richiesto" "patreqeu" -> "brevetto europeo richiesto" "patreqfr" -> "brevetto francese richiesto" "patrequk" -> "brevetto britannico richiesto" "patrequs" -> "brevetto U.S.A. richiesto" "countryde" -> "Germania" "countryeu" -> "Unione Europea" "countryep" -> "Unione Europea" "countryfr" -> "Francia" "countryuk" -> "Regno Unito" "countryus" -> "Stati Uniti d’America" "newseries" -> "nuova serie" "oldseries" -> "vecchia serie" _ -> k resolveKey' (Lang "nl" "NL") k = case T.toLower k of "inpreparation" -> "in voorbereiding" "submitted" -> "ingediend" "forthcoming" -> "onderweg" "inpress" -> "in druk" "prepublished" -> "voorpublicatie" "mathesis" -> "masterscriptie" "phdthesis" -> "proefschrift" -- "candthesis" -> "" -- missing "techreport" -> "technisch rapport" "resreport" -> "onderzoeksrapport" "software" -> "computersoftware" "datacd" -> "cd-rom" "audiocd" -> "audio-cd" "patent" -> "patent" "patentde" -> "Duits patent" "patenteu" -> "Europees patent" "patentfr" -> "Frans patent" "patentuk" -> "Brits patent" "patentus" -> "Amerikaans patent" "patreq" -> "patentaanvraag" "patreqde" -> "Duitse patentaanvraag" "patreqeu" -> "Europese patentaanvraag" "patreqfr" -> "Franse patentaanvraag" "patrequk" -> "Britse patentaanvraag" "patrequs" -> "Amerikaanse patentaanvraag" "countryde" -> "Duitsland" "countryeu" -> "Europese Unie" "countryep" -> "Europese Unie" "countryfr" -> "Frankrijk" "countryuk" -> "Verenigd Koninkrijk" "countryus" -> "Verenigde Staten van Amerika" "newseries" -> "nieuwe reeks" "oldseries" -> "oude reeks" _ -> k resolveKey' (Lang "pl" "PL") k = case T.toLower k of "inpreparation" -> "przygotowanie" "submitted" -> "prezentacja" "forthcoming" -> "przygotowanie" "inpress" -> "wydrukowane" "prepublished" -> "przedwydanie" "mathesis" -> "praca magisterska" "phdthesis" -> "praca doktorska" "techreport" -> "sprawozdanie techniczne" "resreport" -> "sprawozdanie naukowe" "software" -> "oprogramowanie" "datacd" -> "CD-ROM" "audiocd" -> "audio CD" "patent" -> "patent" "patentde" -> "patent Niemiec" "patenteu" -> "patent Europy" "patentfr" -> "patent Francji" "patentuk" -> "patent Wielkiej Brytanji" "patentus" -> "patent USA" "patreq" -> "podanie na patent" "patreqeu" -> "podanie na patent Europy" "patrequs" -> "podanie na patent USA" "countryde" -> "Niemcy" "countryeu" -> "Unia Europejska" "countryep" -> "Unia Europejska" "countryfr" -> "Francja" "countryuk" -> "Wielka Brytania" "countryus" -> "Stany Zjednoczone Ameryki" "newseries" -> "nowa serja" "oldseries" -> "stara serja" _ -> k resolveKey' (Lang "pt" "PT") k = case T.toLower k of -- "candthesis" -> "" -- missing "techreport" -> "relatório técnico" "resreport" -> "relatório de pesquisa" "software" -> "software" "datacd" -> "CD-ROM" "patent" -> "patente" "patentde" -> "patente alemã" "patenteu" -> "patente européia" "patentfr" -> "patente francesa" "patentuk" -> "patente britânica" "patentus" -> "patente americana" "patreq" -> "pedido de patente" "patreqde" -> "pedido de patente alemã" "patreqeu" -> "pedido de patente européia" "patreqfr" -> "pedido de patente francesa" "patrequk" -> "pedido de patente britânica" "patrequs" -> "pedido de patente americana" "countryde" -> "Alemanha" "countryeu" -> "União Europeia" "countryep" -> "União Europeia" "countryfr" -> "França" "countryuk" -> "Reino Unido" "countryus" -> "Estados Unidos da América" "newseries" -> "nova série" "oldseries" -> "série antiga" -- "inpreparation" -> "" -- missing "forthcoming" -> "a publicar" -- csl "inpress" -> "na imprensa" -- "prepublished" -> "" -- missing "mathesis" -> "tese de mestrado" "phdthesis" -> "tese de doutoramento" "audiocd" -> "CD áudio" _ -> k resolveKey' (Lang "pt" "BR") k = case T.toLower k of -- "candthesis" -> "" -- missing "techreport" -> "relatório técnico" "resreport" -> "relatório de pesquisa" "software" -> "software" "datacd" -> "CD-ROM" "patent" -> "patente" "patentde" -> "patente alemã" "patenteu" -> "patente européia" "patentfr" -> "patente francesa" "patentuk" -> "patente britânica" "patentus" -> "patente americana" "patreq" -> "pedido de patente" "patreqde" -> "pedido de patente alemã" "patreqeu" -> "pedido de patente européia" "patreqfr" -> "pedido de patente francesa" "patrequk" -> "pedido de patente britânica" "patrequs" -> "pedido de patente americana" "countryde" -> "Alemanha" "countryeu" -> "União Europeia" "countryep" -> "União Europeia" "countryfr" -> "França" "countryuk" -> "Reino Unido" "countryus" -> "Estados Unidos da América" "newseries" -> "nova série" "oldseries" -> "série antiga" "inpreparation" -> "em preparação" "forthcoming" -> "aceito para publicação" "inpress" -> "no prelo" "prepublished" -> "pré-publicado" "mathesis" -> "dissertação de mestrado" "phdthesis" -> "tese de doutorado" "audiocd" -> "CD de áudio" _ -> k resolveKey' (Lang "sv" "SE") k = case T.toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "kommande" -- csl "inpress" -> "i tryck" -- csl -- "prepublished" -> "" -- missing "mathesis" -> "examensarbete" "phdthesis" -> "doktorsavhandling" "candthesis" -> "kandidatavhandling" "techreport" -> "teknisk rapport" "resreport" -> "forskningsrapport" "software" -> "datorprogram" "datacd" -> "data-cd" "audiocd" -> "ljud-cd" "patent" -> "patent" "patentde" -> "tyskt patent" "patenteu" -> "europeiskt patent" "patentfr" -> "franskt patent" "patentuk" -> "brittiskt patent" "patentus" -> "amerikanskt patent" "patreq" -> "patentansökan" "patreqde" -> "ansökan om tyskt patent" "patreqeu" -> "ansökan om europeiskt patent" "patreqfr" -> "ansökan om franskt patent" "patrequk" -> "ansökan om brittiskt patent" "patrequs" -> "ansökan om amerikanskt patent" "countryde" -> "Tyskland" "countryeu" -> "Europeiska unionen" "countryep" -> "Europeiska unionen" "countryfr" -> "Frankrike" "countryuk" -> "Storbritannien" "countryus" -> "USA" "newseries" -> "ny följd" "oldseries" -> "gammal följd" _ -> k resolveKey' _ k = resolveKey' (Lang "en" "US") k parseMonth :: Text -> Maybe Int parseMonth s = case T.toLower s of "jan" -> Just 1 "feb" -> Just 2 "mar" -> Just 3 "apr" -> Just 4 "may" -> Just 5 "jun" -> Just 6 "jul" -> Just 7 "aug" -> Just 8 "sep" -> Just 9 "oct" -> Just 10 "nov" -> Just 11 "dec" -> Just 12 _ -> safeRead s data BibState = BibState{ untitlecase :: Bool , localeLanguage :: Lang } type Bib = RWST Item () BibState Maybe notFound :: Text -> Bib a notFound f = Prelude.fail $ T.unpack f ++ " not found" getField :: Text -> Bib Formatted getField f = do fs <- asks fields case Map.lookup f fs of Just x -> latex x Nothing -> notFound f getPeriodicalTitle :: Text -> Bib Formatted getPeriodicalTitle f = do fs <- asks fields case Map.lookup f fs of Just x -> blocksToFormatted $ onBlocks protectCase $ latex' $ trim x Nothing -> notFound f getTitle :: Text -> Bib Formatted getTitle f = do fs <- asks fields case Map.lookup f fs of Just x -> latexTitle x Nothing -> notFound f getShortTitle :: Bool -> Text -> Bib Formatted getShortTitle requireColon f = do fs <- asks fields utc <- gets untitlecase let processTitle = if utc then onBlocks unTitlecase else id case Map.lookup f fs of Just x -> case processTitle $ latex' x of bs | not requireColon || containsColon bs -> blocksToFormatted $ upToColon bs | otherwise -> return mempty Nothing -> notFound f containsColon :: [Block] -> Bool containsColon [Para xs] = Str ":" `elem` xs containsColon [Plain xs] = containsColon [Para xs] containsColon _ = False upToColon :: [Block] -> [Block] upToColon [Para xs] = [Para $ takeWhile (/= Str ":") xs] upToColon [Plain xs] = upToColon [Para xs] upToColon bs = bs getDates :: Text -> Bib [RefDate] getDates f = parseEDTFDate <$> getRawField f isNumber :: Text -> Bool isNumber t = case T.uncons t of Just ('-', ds) -> T.all isDigit ds Just _ -> T.all isDigit t Nothing -> False -- A negative (BC) year might be written with -- or --- in bibtex: fixLeadingDash :: Text -> Text fixLeadingDash t = case T.uncons t of Just (c, ds) | (c == '–' || c == '—') && firstIsDigit ds -> T.cons '–' ds _ -> t where firstIsDigit = maybe False (isDigit . fst) . T.uncons getOldDates :: Text -> Bib [RefDate] getOldDates prefix = do year' <- fixLeadingDash <$> getRawField (prefix <> "year") <|> return "" month' <- (parseMonth <$> getRawField (prefix <> "month")) <|> return Nothing day' <- (safeRead <$> getRawField (prefix <> "day")) <|> return Nothing endyear' <- (fixLeadingDash <$> getRawField (prefix <> "endyear")) <|> return "" endmonth' <- (parseMonth <$> getRawField (prefix <> "endmonth")) <|> return Nothing endday' <- (safeRead <$> getRawField (prefix <> "endday")) <|> return Nothing let start' = RefDate { year = safeRead year' , month = month' , season = Nothing , day = day' , other = Literal $ if isNumber year' then "" else year' , circa = False } let end' = RefDate { year = safeRead endyear' , month = endmonth' , day = endday' , season = Nothing , other = Literal $ if isNumber endyear' then "" else endyear' , circa = False } let hasyear r = isJust (year r) return $ filter hasyear [start', end'] getRawField :: Text -> Bib Text getRawField f = do fs <- asks fields case Map.lookup f fs of Just x -> return x Nothing -> notFound f getAuthorList :: Options -> Text -> Bib [Agent] getAuthorList opts f = do fs <- asks fields case Map.lookup f fs of Just x -> latexAuthors opts x Nothing -> notFound f getLiteralList :: Text -> Bib [Formatted] getLiteralList f = do fs <- asks fields case Map.lookup f fs of Just x -> toLiteralList $ latex' x Nothing -> notFound f -- separates items with semicolons getLiteralList' :: Text -> Bib Formatted getLiteralList' f = Formatted . intercalate [Str ";", Space] . map unFormatted <$> getLiteralList f splitByAnd :: [Inline] -> [[Inline]] splitByAnd = splitOn [Space, Str "and", Space] toLiteralList :: [Block] -> Bib [Formatted] toLiteralList [Para xs] = mapM inlinesToFormatted $ splitByAnd xs toLiteralList [Plain xs] = toLiteralList [Para xs] toLiteralList _ = mzero toAuthorList :: Options -> [Block] -> Bib [Agent] toAuthorList opts [Para xs] = filter (/= emptyAgent) <$> mapM (toAuthor opts . addSpaceAfterPeriod) (splitByAnd xs) toAuthorList opts [Plain xs] = toAuthorList opts [Para xs] toAuthorList _ _ = mzero toAuthor :: Options -> [Inline] -> Bib Agent toAuthor _ [Str "others"] = return Agent { givenName = [] , droppingPart = mempty , nonDroppingPart = mempty , familyName = mempty , nameSuffix = mempty , literal = Formatted [Str "others"] , commaSuffix = False , parseNames = False } toAuthor _ [Span ("",[],[]) ils] = return -- corporate author Agent { givenName = [] , droppingPart = mempty , nonDroppingPart = mempty , familyName = mempty , nameSuffix = mempty , literal = Formatted ils , commaSuffix = False , parseNames = False } -- extended BibLaTeX name format - see #266 toAuthor _ ils@(Str ys:_) | T.any (== '=') ys = do let commaParts = Data.List.Split.splitWhen (== Str ",") . splitStrWhen (\c -> c == ',' || c == '=' || c == '\160') $ ils let addPart ag (Str "given" : Str "=" : xs) = ag{ givenName = givenName ag ++ [Formatted xs] } addPart ag (Str "family" : Str "=" : xs) = ag{ familyName = Formatted xs } addPart ag (Str "prefix" : Str "=" : xs) = ag{ droppingPart = Formatted xs } addPart ag (Str "useprefix" : Str "=" : Str "true" : _) = ag{ nonDroppingPart = droppingPart ag, droppingPart = mempty } addPart ag (Str "suffix" : Str "=" : xs) = ag{ nameSuffix = Formatted xs } addPart ag (Space : xs) = addPart ag xs addPart ag _ = ag return $ foldl' addPart emptyAgent commaParts -- First von Last -- von Last, First -- von Last, Jr ,First -- NOTE: biblatex and bibtex differ on: -- Drummond de Andrade, Carlos -- bibtex takes "Drummond de" as the von; -- biblatex takes the whole as a last name. -- See https://github.com/plk/biblatex/issues/236 -- Here we implement the more sensible biblatex behavior. toAuthor opts ils = do let useprefix = optionSet "useprefix" opts let usecomma = optionSet "juniorcomma" opts let bibtex = optionSet "bibtex" opts let words' = wordsBy (\x -> x == Space || x == Str "\160") let commaParts = map words' $ Data.List.Split.splitWhen (== Str ",") $ splitStrWhen (\c -> c == ',' || c == '\160') ils let (first, vonlast, jr) = case commaParts of --- First is the longest sequence of white-space separated -- words starting with an uppercase and that is not the -- whole string. von is the longest sequence of whitespace -- separated words whose last word starts with lower case -- and that is not the whole string. [fvl] -> let (caps', rest') = span isCapitalized fvl in if null rest' && not (null caps') then (init caps', [last caps'], []) else (caps', rest', []) [vl,f] -> (f, vl, []) (vl:j:f:_) -> (f, vl, j ) [] -> ([], [], []) let (von, lastname) = if bibtex then case span isCapitalized $ reverse vonlast of ([],w:ws) -> (reverse ws, [w]) (vs, ws) -> (reverse ws, reverse vs) else case break isCapitalized vonlast of (vs@(_:_), []) -> (init vs, [last vs]) (vs, ws) -> (vs, ws) let prefix = Formatted $ intercalate [Space] von let family = Formatted $ intercalate [Space] lastname let suffix = Formatted $ intercalate [Space] jr let givens = map Formatted first return Agent { givenName = givens , droppingPart = if useprefix then mempty else prefix , nonDroppingPart = if useprefix then prefix else mempty , familyName = family , nameSuffix = suffix , literal = mempty , commaSuffix = usecomma , parseNames = False } isCapitalized :: [Inline] -> Bool isCapitalized (Str (T.uncons -> Just (c,cs)) : rest) | isUpper c = True | isDigit c = isCapitalized (Str cs : rest) | otherwise = False isCapitalized (_:rest) = isCapitalized rest isCapitalized [] = True optionSet :: Text -> Options -> Bool optionSet key opts = case lookup key opts of Just "true" -> True Just s -> s == mempty _ -> False latex' :: Text -> [Block] latex' s = Walk.walk removeSoftBreak bs where Pandoc _ bs = readLaTeX s removeSoftBreak :: Inline -> Inline removeSoftBreak SoftBreak = Space removeSoftBreak x = x latex :: Text -> Bib Formatted latex s = blocksToFormatted $ latex' $ trim s latexTitle :: Text -> Bib Formatted latexTitle s = do utc <- gets untitlecase let processTitle = if utc then onBlocks unTitlecase else id blocksToFormatted $ processTitle $ latex' s latexAuthors :: Options -> Text -> Bib [Agent] latexAuthors opts = toAuthorList opts . latex' . trim bib :: Bib Reference -> Item -> Maybe Reference bib m entry = fst Control.Applicative.<$> evalRWST m entry (BibState True (Lang "en" "US")) toLocale :: Text -> Text toLocale "english" = "en-US" -- "en-EN" unavailable in CSL toLocale "usenglish" = "en-US" toLocale "american" = "en-US" toLocale "british" = "en-GB" toLocale "ukenglish" = "en-GB" toLocale "canadian" = "en-US" -- "en-CA" unavailable in CSL toLocale "australian" = "en-GB" -- "en-AU" unavailable in CSL toLocale "newzealand" = "en-GB" -- "en-NZ" unavailable in CSL toLocale "afrikaans" = "af-ZA" toLocale "arabic" = "ar" toLocale "basque" = "eu" toLocale "bulgarian" = "bg-BG" toLocale "catalan" = "ca-AD" toLocale "croatian" = "hr-HR" toLocale "czech" = "cs-CZ" toLocale "danish" = "da-DK" toLocale "dutch" = "nl-NL" toLocale "estonian" = "et-EE" toLocale "finnish" = "fi-FI" toLocale "canadien" = "fr-CA" toLocale "acadian" = "fr-CA" toLocale "french" = "fr-FR" toLocale "francais" = "fr-FR" toLocale "austrian" = "de-AT" toLocale "naustrian" = "de-AT" toLocale "german" = "de-DE" toLocale "germanb" = "de-DE" toLocale "ngerman" = "de-DE" toLocale "greek" = "el-GR" toLocale "polutonikogreek" = "el-GR" toLocale "hebrew" = "he-IL" toLocale "hungarian" = "hu-HU" toLocale "icelandic" = "is-IS" toLocale "italian" = "it-IT" toLocale "japanese" = "ja-JP" toLocale "latvian" = "lv-LV" toLocale "lithuanian" = "lt-LT" toLocale "magyar" = "hu-HU" toLocale "mongolian" = "mn-MN" toLocale "norsk" = "nb-NO" toLocale "nynorsk" = "nn-NO" toLocale "farsi" = "fa-IR" toLocale "polish" = "pl-PL" toLocale "brazil" = "pt-BR" toLocale "brazilian" = "pt-BR" toLocale "portugues" = "pt-PT" toLocale "portuguese" = "pt-PT" toLocale "romanian" = "ro-RO" toLocale "russian" = "ru-RU" toLocale "serbian" = "sr-RS" toLocale "serbianc" = "sr-RS" toLocale "slovak" = "sk-SK" toLocale "slovene" = "sl-SL" toLocale "spanish" = "es-ES" toLocale "swedish" = "sv-SE" toLocale "thai" = "th-TH" toLocale "turkish" = "tr-TR" toLocale "ukrainian" = "uk-UA" toLocale "vietnamese" = "vi-VN" toLocale "latin" = "la" toLocale x = x concatWith :: Char -> [Formatted] -> Formatted concatWith sep = Formatted . foldl' go mempty . map unFormatted where go :: [Inline] -> [Inline] -> [Inline] go accum [] = accum go accum s = case reverse accum of [] -> s (Str x:_) | not (T.null x) && T.last x `elem` ("!?.,:;" :: String) -> accum ++ (Space : s) _ -> accum ++ (Str (T.singleton sep) : Space : s) type Options = [(Text, Text)] parseOptions :: Text -> Options parseOptions = map breakOpt . T.splitOn "," where breakOpt x = case T.break (=='=') x of (w,v) -> (T.toLower $ trim w, T.toLower $ trim $ T.drop 1 v) ordinalize :: Locale -> Text -> Text ordinalize locale n = case [termSingular c | c <- terms, cslTerm c == ("ordinal-" <> pad0 n)] ++ [termSingular c | c <- terms, cslTerm c == "ordinal"] of (suff:_) -> n <> suff [] -> n where pad0 s = case T.uncons s of Just (c,"") -> T.pack ['0', c] _ -> s terms = localeTerms locale itemToReference :: Lang -> Locale -> Bool -> Bool -> Item -> Maybe Reference itemToReference lang locale bibtex caseTransform = bib $ do modify $ \st -> st{ localeLanguage = lang, untitlecase = case lang of Lang "en" _ -> caseTransform _ -> False } id' <- asks identifier otherIds <- (map trim . T.splitOn "," <$> getRawField "ids") <|> return [] et <- asks entryType guard $ et /= "xdata" opts <- (parseOptions <$> getRawField "options") <|> return [] let getAuthorList' = getAuthorList (("bibtex", T.toLower . T.pack $ show bibtex):opts) st <- getRawField "entrysubtype" <|> return mempty isEvent <- (True <$ (getRawField "eventdate" <|> getRawField "eventtitle" <|> getRawField "venue")) <|> return False reftype' <- resolveKey lang <$> getField "type" <|> return mempty let (reftype, refgenre) = case et of "article" | st == "magazine" -> (ArticleMagazine,mempty) | st == "newspaper" -> (ArticleNewspaper,mempty) | otherwise -> (ArticleJournal,mempty) "book" -> (Book,mempty) "booklet" -> (Pamphlet,mempty) "bookinbook" -> (Chapter,mempty) "collection" -> (Book,mempty) "dataset" -> (Dataset,mempty) "electronic" -> (Webpage,mempty) "inbook" -> (Chapter,mempty) "incollection" -> (Chapter,mempty) "inreference" -> (EntryEncyclopedia,mempty) "inproceedings" -> (PaperConference,mempty) "manual" -> (Book,mempty) "mastersthesis" -> (Thesis, if reftype' == mempty then Formatted [Str $ resolveKey' lang "mathesis"] else reftype') "misc" -> (NoType,mempty) "mvbook" -> (Book,mempty) "mvcollection" -> (Book,mempty) "mvproceedings" -> (Book,mempty) "mvreference" -> (Book,mempty) "online" -> (Webpage,mempty) "patent" -> (Patent,mempty) "periodical" | st == "magazine" -> (ArticleMagazine,mempty) | st == "newspaper" -> (ArticleNewspaper,mempty) | otherwise -> (ArticleJournal,mempty) "phdthesis" -> (Thesis, if reftype' == mempty then Formatted [Str $ resolveKey' lang "phdthesis"] else reftype') "proceedings" -> (Book,mempty) "reference" -> (Book,mempty) "report" -> (Report,mempty) "software" -> (Book,mempty) -- no "software" type in CSL "suppbook" -> (Chapter,mempty) "suppcollection" -> (Chapter,mempty) "suppperiodical" | st == "magazine" -> (ArticleMagazine,mempty) | st == "newspaper" -> (ArticleNewspaper,mempty) | otherwise -> (ArticleJournal,mempty) "techreport" -> (Report,mempty) "thesis" -> (Thesis,mempty) "unpublished" -> (if isEvent then Speech else Manuscript,mempty) "www" -> (Webpage,mempty) -- biblatex, "unsupported" "artwork" -> (Graphic,mempty) "audio" -> (Song,mempty) -- for audio *recordings* "commentary" -> (Book,mempty) "image" -> (Graphic,mempty) -- or "figure" ? "jurisdiction" -> (LegalCase,mempty) "legislation" -> (Legislation,mempty) -- or "bill" ? "legal" -> (Treaty,mempty) "letter" -> (PersonalCommunication,mempty) "movie" -> (MotionPicture,mempty) "music" -> (Song,mempty) -- for musical *recordings* "performance" -> (Speech,mempty) "review" -> (Review,mempty) -- or "review-book" ? "standard" -> (Legislation,mempty) "video" -> (MotionPicture,mempty) -- biblatex-apa: "data" -> (Dataset,mempty) "letters" -> (PersonalCommunication,mempty) "newsarticle" -> (ArticleNewspaper,mempty) _ -> (NoType,mempty) -- hyphenation: let defaultHyphenation = case lang of Lang x y -> x <> "-" <> y let getLangId = do langid <- trim . T.toLower <$> getRawField "langid" idopts <- trim . T.toLower <$> getRawField "langidopts" <|> return "" case (langid, idopts) of ("english","variant=british") -> return "british" ("english","variant=american") -> return "american" ("english","variant=us") -> return "american" ("english","variant=usmax") -> return "american" ("english","variant=uk") -> return "british" ("english","variant=australian") -> return "australian" ("english","variant=newzealand") -> return "newzealand" (x,_) -> return x hyphenation <- (toLocale . T.toLower <$> (getLangId <|> getRawField "hyphenation")) <|> return mempty -- authors: author' <- getAuthorList' "author" <|> return [] containerAuthor' <- getAuthorList' "bookauthor" <|> return [] translator' <- getAuthorList' "translator" <|> return [] editortype <- getRawField "editortype" <|> return mempty editor'' <- getAuthorList' "editor" <|> return [] director'' <- getAuthorList' "director" <|> return [] let (editor', director') = case editortype of "director" -> ([], editor'') _ -> (editor'', director'') -- FIXME: add same for editora, editorb, editorc -- titles let isArticle = et `elem` ["article", "periodical", "suppperiodical", "review"] let isPeriodical = et == "periodical" let isChapterlike = et `elem` ["inbook","incollection","inproceedings","inreference","bookinbook"] hasMaintitle <- (True <$ getRawField "maintitle") <|> return False let hyphenation' = if T.null hyphenation then defaultHyphenation else hyphenation let la = case T.splitOn "-" hyphenation' of (x:_) -> x [] -> mempty modify $ \s -> s{ untitlecase = caseTransform && la == "en" } title' <- (guard isPeriodical >> getTitle "issuetitle") <|> (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "maintitle") <|> getTitle "title" <|> return mempty subtitle' <- (guard isPeriodical >> getTitle "issuesubtitle") <|> (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "mainsubtitle") <|> getTitle "subtitle" <|> return mempty titleaddon' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "maintitleaddon") <|> getTitle "titleaddon" <|> return mempty volumeTitle' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "title") <|> (guard hasMaintitle >> guard isChapterlike >> getTitle "booktitle") <|> return mempty volumeSubtitle' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "subtitle") <|> (guard hasMaintitle >> guard isChapterlike >> getTitle "booksubtitle") <|> return mempty volumeTitleAddon' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "titleaddon") <|> (guard hasMaintitle >> guard isChapterlike >> getTitle "booktitleaddon") <|> return mempty containerTitle' <- (guard isPeriodical >> getPeriodicalTitle "title") <|> (guard isChapterlike >> getTitle "maintitle") <|> (guard isChapterlike >> getTitle "booktitle") <|> getPeriodicalTitle "journaltitle" <|> getPeriodicalTitle "journal" <|> return mempty containerSubtitle' <- (guard isPeriodical >> getPeriodicalTitle "subtitle") <|> (guard isChapterlike >> getTitle "mainsubtitle") <|> (guard isChapterlike >> getTitle "booksubtitle") <|> getPeriodicalTitle "journalsubtitle" <|> return mempty containerTitleAddon' <- (guard isPeriodical >> getPeriodicalTitle "titleaddon") <|> (guard isChapterlike >> getTitle "maintitleaddon") <|> (guard isChapterlike >> getTitle "booktitleaddon") <|> return mempty containerTitleShort' <- (guard isPeriodical >> guard (not hasMaintitle) >> getField "shorttitle") <|> getPeriodicalTitle "shortjournal" <|> return mempty -- change numerical series title to e.g. 'series 3' let fixSeriesTitle (Formatted [Str xs]) | T.all isDigit xs = Formatted [Str (ordinalize locale xs), Space, Str (resolveKey' lang "ser.")] fixSeriesTitle x = x seriesTitle' <- fixSeriesTitle . resolveKey lang <$> getTitle "series" <|> return mempty shortTitle' <- (guard (not hasMaintitle || isChapterlike) >> getTitle "shorttitle") <|> if (subtitle' /= mempty || titleaddon' /= mempty) && not hasMaintitle then getShortTitle False "title" else getShortTitle True "title" <|> return mempty eventTitle' <- getTitle "eventtitle" <|> return mempty origTitle' <- getTitle "origtitle" <|> return mempty -- publisher pubfields <- mapM (\f -> Just `fmap` (if bibtex || f == "howpublished" then getField f else getLiteralList' f) <|> return Nothing) ["school","institution","organization", "howpublished","publisher"] let publisher' = concatWith ';' $ catMaybes pubfields origpublisher' <- getField "origpublisher" <|> return mempty -- places venue' <- getField "venue" <|> return mempty address' <- (if bibtex then getField "address" else getLiteralList' "address" <|> (guard (et /= "patent") >> getLiteralList' "location")) <|> return mempty origLocation' <- (if bibtex then getField "origlocation" else getLiteralList' "origlocation") <|> return mempty jurisdiction' <- if et == "patent" then (concatWith ';' . map (resolveKey lang) <$> getLiteralList "location") <|> return mempty else return mempty -- locators pages' <- getField "pages" <|> return mempty volume' <- getField "volume" <|> return mempty part' <- getField "part" <|> return mempty volumes' <- getField "volumes" <|> return mempty pagetotal' <- getField "pagetotal" <|> return mempty chapter' <- getField "chapter" <|> return mempty edition' <- getField "edition" <|> return mempty version' <- getField "version" <|> return mempty (number', collectionNumber', issue') <- (getField "number" <|> return mempty) >>= \x -> if et `elem` ["book","collection","proceedings","reference", "mvbook","mvcollection","mvproceedings", "mvreference", "bookinbook","inbook", "incollection","inproceedings", "inreference", "suppbook","suppcollection"] then return (mempty,x,mempty) else if isArticle then (getField "issue" >>= \y -> return (mempty,mempty,concatWith ',' [x,y])) <|> return (mempty,mempty,x) else return (x,mempty,mempty) -- dates issued' <- getDates "date" <|> getOldDates mempty <|> return [] eventDate' <- getDates "eventdate" <|> getOldDates "event" <|> return [] origDate' <- getDates "origdate" <|> getOldDates "orig" <|> return [] accessed' <- getDates "urldate" <|> getOldDates "url" <|> return [] -- url, doi, isbn, etc.: -- note that with eprinttype = arxiv, we take eprint to be a partial url -- archivePrefix is an alias for eprinttype url' <- (guard (et == "online" || lookup "url" opts /= Just "false") >> getRawField "url") <|> (do etype <- getRawField "eprinttype" eprint <- getRawField "eprint" let baseUrl = case T.toLower etype of "arxiv" -> "http://arxiv.org/abs/" "jstor" -> "http://www.jstor.org/stable/" "pubmed" -> "http://www.ncbi.nlm.nih.gov/pubmed/" "googlebooks" -> "http://books.google.com?id=" _ -> "" if T.null baseUrl then mzero else return $ baseUrl <> eprint) <|> return mempty doi' <- (guard (lookup "doi" opts /= Just "false") >> getRawField "doi") <|> return mempty isbn' <- getRawField "isbn" <|> return mempty issn' <- getRawField "issn" <|> return mempty pmid' <- getRawField "pmid" <|> return mempty pmcid' <- getRawField "pmcid" <|> return mempty callNumber' <- getRawField "library" <|> return mempty -- notes annotation' <- getField "annotation" <|> getField "annote" <|> return mempty abstract' <- getField "abstract" <|> return mempty keywords' <- getField "keywords" <|> return mempty note' <- if et == "periodical" then return mempty else getField "note" <|> return mempty addendum' <- if bibtex then return mempty else getField "addendum" <|> return mempty pubstate' <- resolveKey lang `fmap` ( getField "pubstate" <|> case issued' of (x:_) | other x == Literal "forthcoming" -> return (Formatted [Str "forthcoming"]) _ -> return mempty ) let convertEnDash (Str s) = Str (T.map (\c -> if c == '–' then '-' else c) s) convertEnDash x = x let takeDigits (Str xs : _) = case T.takeWhile isDigit xs of "" -> [] ds -> [Str ds] takeDigits x = x return $ emptyReference { refId = Literal id' , refOtherIds = map Literal otherIds , refType = reftype , author = author' , editor = editor' , translator = translator' -- , recipient = undefined -- :: [Agent] -- , interviewer = undefined -- :: [Agent] -- , composer = undefined -- :: [Agent] , director = director' -- , illustrator = undefined -- :: [Agent] -- , originalAuthor = undefined -- :: [Agent] , containerAuthor = containerAuthor' -- , collectionEditor = undefined -- :: [Agent] -- , editorialDirector = undefined -- :: [Agent] -- , reviewedAuthor = undefined -- :: [Agent] , issued = issued' , eventDate = eventDate' , accessed = accessed' -- , container = undefined -- :: [RefDate] , originalDate = origDate' -- , submitted = undefined -- :: [RefDate] , title = concatWith '.' [ concatWith ':' [title', subtitle'] , titleaddon' ] , titleShort = shortTitle' -- , reviewedTitle = undefined -- :: String , containerTitle = concatWith '.' [ concatWith ':' [ containerTitle' , containerSubtitle'] , containerTitleAddon' ] , collectionTitle = seriesTitle' , volumeTitle = concatWith '.' [ concatWith ':' [ volumeTitle' , volumeSubtitle'] , volumeTitleAddon' ] , containerTitleShort = containerTitleShort' , collectionNumber = collectionNumber' , originalTitle = origTitle' , publisher = publisher' , originalPublisher = origpublisher' , publisherPlace = address' , originalPublisherPlace = origLocation' , jurisdiction = jurisdiction' , event = eventTitle' , eventPlace = venue' , page = Formatted $ Walk.walk convertEnDash $ unFormatted pages' , pageFirst = Formatted $ takeDigits $ unFormatted pages' , numberOfPages = pagetotal' , version = version' , volume = Formatted $ intercalate [Str "."] $ filter (not . null) [unFormatted volume', unFormatted part'] , numberOfVolumes = volumes' , issue = issue' , chapterNumber = chapter' -- , medium = undefined -- :: String , status = pubstate' , edition = edition' -- , section = undefined -- :: String -- , source = undefined -- :: String , genre = if refgenre == mempty then reftype' else refgenre , note = concatWith '.' [note', addendum'] , annote = annotation' , abstract = abstract' , keyword = keywords' , number = number' , url = Literal url' , doi = Literal doi' , isbn = Literal isbn' , issn = Literal issn' , pmcid = Literal pmcid' , pmid = Literal pmid' , language = Literal hyphenation , callNumber = Literal callNumber' }
jgm/pandoc-citeproc
src/Text/CSL/Input/Bibtex.hs
bsd-3-clause
67,033
20
21
23,000
15,903
8,097
7,806
1,426
406
{-# LANGUAGE TupleSections #-} module Language.DemonL.Script where import Control.Applicative import Control.Monad import Data.List import qualified Data.Map as M import Math.SMT.Yices.Syntax import Language.DemonL.AST import Language.DemonL.Goal import Language.DemonL.TypeCheck (ProcedureT) generateScript goal dom goalExprs = let actionMap = foldr inspectTag M.empty goalExprs argumentMap = foldr (inspectArg actionMap dom) M.empty goalExprs equivs = objEquivalence goal goalExprs in reconstrFromMaps dom actionMap argumentMap equivs reconstrFromMaps dom actMap argMap equivs = let f idx proc = proc ++ " (" ++ reconstrArgs (numArgs dom proc) idx equivs argMap ++ ")" scriptMap = M.mapWithKey f actMap in unlines $ map snd $ M.toAscList scriptMap objEquivalence :: SerialGoal -> [ExpY] -> M.Map Integer String objEquivalence goal goalExprs = let f ((VarE v) := (LitI i)) m | isGoalVar v goal = M.insert i v m f ((LitI i) := (VarE v)) m | isGoalVar v goal = M.insert i v m f _ m = m in foldr f M.empty goalExprs numArgs dom name = case findProc dom name of Just p -> length (prcdArgs p) Nothing -> error $ "no proc " ++ name ++ " found" isGoalVar v goal = v `elem` map declName (vars goal) -- | Reconstruct the comma separated argument string. reconstrArgs :: Int -> Integer -> M.Map Integer String -> M.Map Integer (M.Map Integer ExpY) -> String reconstrArgs n idx equivs = let exprEquiv (LitI i) = maybe (show i) id (M.lookup i equivs) exprEquiv e = show e in intercalate "," . take n . map (exprEquiv . snd) . M.toAscList . (M.! idx) inspectArg actionMap dom (e1 := e2) argsMap = let argTuple = argM actionMap dom e1 <|> argM actionMap dom e2 val = valM actionMap dom e1 <|> valM actionMap dom e2 insertArg (name, timeIndex, argNum) v = M.insertWith M.union timeIndex (M.singleton argNum v) argsMap argsMapM = insertArg <$> argTuple <*> val in maybe argsMap id argsMapM valM actionMap dom e = case argM actionMap dom e of Just _ -> Nothing _ -> Just e argStr = "_arg" -- | Given an action map, a domain and a Yices expression, -- build a type argument number and index argM actionMap dom (APP (VarE str) [LitI timeIndex, LitI argNum]) = let proc = findProcUnsafe dom (actionMap M.! timeIndex) args = prcdArgs proc argDecl = args !! fromIntegral argNum argTypeName = show $ declType argDecl in if fromIntegral argNum < length args && argTypeName `isPrefixOf` str then Just (argTypeName, timeIndex, argNum) else Nothing argM _ _ _ = Nothing inspectTag (e1 := e2) tagMap = let tagNum = tagNumM e1 <|> tagNumM e2 tag = tagM e1 <|> tagM e2 tagMapM = M.insert <$> tagNum <*> tag <*> pure tagMap in maybe tagMap id tagMapM tagStr = "_tag" stripSuffix suffix str = reverse <$> stripPrefix (reverse suffix) (reverse str) tagM (VarE str) = stripSuffix tagStr str tagM _ = Nothing tagNumM (APP (VarE "tag_array") [LitI i]) = Just i tagNumM _ = Nothing
scottgw/demonL
Language/DemonL/Script.hs
bsd-3-clause
3,179
0
13
816
1,125
560
565
73
3
module Problem36 where import Data.Digits isPalindrome :: [Int] -> Bool isPalindrome [_] = True isPalindrome xs = isPalindrome' xs [] where isPalindrome' xs@(h:t) rxs | length xs > length rxs = isPalindrome' t (h:rxs) | length xs < length rxs = isPalindrome' xs (tail rxs) | otherwise = xs == rxs isDoubleBasePalindrome :: Int -> Bool isDoubleBasePalindrome n = isPalindrome (digits 10 n) && isPalindrome (digits 2 n) main :: IO () main = print $ sum $ filter isDoubleBasePalindrome [1..1000000]
noraesae/euler
src/Problem36.hs
bsd-3-clause
537
0
11
122
216
107
109
13
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} module Data.Vector.Fixed.Linear where import Data.Vector.Fixed hiding ((!)) import qualified Data.Vector.Fixed as Fixed import Data.Vector.Fixed.Size import Data.Vector.Fixed.Indexed import Control.DeepSeq import Data.Foldable hiding (sum) import Data.Traversable import Control.Applicative import Data.Monoid import Data.Proxy import Data.Distributive import Prelude hiding (sum, maximum) newtype Matrix (r :: Size) (c :: Size) a = Matrix{flattenMatrix :: Vector (r * c) a} deriving(Show, Eq, Ord, Functor, Foldable, Traversable, NFData, Applicative) instance (Known r, Known c) => Distributive (Matrix r c) where distribute = Matrix . distribute . fmap flattenMatrix instance (Known r, Known c) => Indexable (Matrix r c) where type Index (Matrix r c) = (Int, Int) indices = Matrix . generate $ \ix -> quotRem ix (getInt (Proxy :: Proxy c)) m !? (rix,cix) = if 0 <= rix && rix < getInt (Proxy :: Proxy r) && 0 <= cix && cix < getInt (Proxy :: Proxy r) then Just (m ! (rix,cix)) else Nothing sum :: (Foldable f, Num a) => f a -> a sum = foldl' (+) 0 (!) :: forall c. Known c => forall r a. Matrix r c a -> (Int, Int) -> a (!) = let c = getInt (Proxy :: Proxy c) in (\(Matrix v) (rix,cix) -> (Fixed.!) v (c*rix + cix)) ixMatrix :: forall r c.(Known c, Known (r*c)) => Matrix r c (Int, Int) ixMatrix = let c = getInt (Proxy :: Proxy c) in Matrix $ generate (\ix -> ix `quotRem` c) onRows :: (Known r, Known c) => (Vector c a -> b) -> Matrix r c a -> Vector r b onRows f = fmap f . separate . flattenMatrix zero :: (Known n, Num a) => Vector n a zero = pure 0 sub :: (Known n, Num a) => Vector n a -> Vector n a -> Vector n a sub = liftA2 (-) add :: (Known n, Num a) => Vector n a -> Vector n a -> Vector n a add = liftA2 (+) dot :: (Known n, Num a) => Vector n a -> Vector n a -> a dot a = sum . liftA2 (*) a cossim :: (Known n, Floating a) => Vector n a -> Vector n a -> a cossim a b = sum $ (*) <$> normalize2 a <*> normalize2 b outer :: (Known n, Known m, Num a) => Vector n a -> Vector m a -> Matrix n m a outer v = Matrix . flatten . traverse (\x -> (*x) <$> v) mXv :: (Known r, Known c, Num a) => Matrix r c a -> Vector c a -> Vector r a mXv (Matrix m) v = dot v <$> separate m vXm :: (Known r, Known c, Num a) => Vector r a-> Matrix r c a -> Vector c a vXm v (Matrix m) = foldl' add zero $ (\x -> fmap (x*)) <$> v <*> separate m transpose :: forall r c a. (Known r, Known c) => Matrix r c a -> Matrix c r a transpose (Matrix m) = Matrix $ flatten (sequenceA . separate $ m :: Vector c (Vector r a)) norm2Square :: (Known n, Num a) => Vector n a -> a norm2Square = getSum . foldMap (\x -> Sum (x * x)) dist2Square :: (Known n, Num a) => Vector n a -> Vector n a -> a dist2Square a = norm2Square . sub a norm2 :: (Known n, Floating a) => Vector n a -> a norm2 = sqrt . norm2Square dist2 :: (Known n, Floating a) => Vector n a -> Vector n a -> a dist2 a = sqrt . dist2Square a normalize2 :: (Known n, Floating a) => Vector n a -> Vector n a normalize2 v = (/ norm2 v) <$> v norm1 :: (Known n, Num a) => Vector n a -> a norm1 = getSum . foldMap (Sum . abs) dist1 :: (Known n, Num a) => Vector n a -> Vector n a -> a dist1 a = norm1 . sub a normalize1 :: (Known n, Fractional a) => Vector n a -> Vector n a normalize1 v = (/ norm1 v) <$> v normInf :: (Known n, Num a, Ord a) => Vector n a -> a normInf = maximum . fmap abs distInf :: (Known n, Num a, Ord a) => Vector n a -> Vector n a -> a distInf a = normInf . sub a normalizeInf :: (Known n, Fractional a, Ord a) => Vector n a -> Vector n a normalizeInf v = (/ normInf v) <$> v
Apsod/fixed
Data/Vector/Fixed/Linear.hs
bsd-3-clause
4,138
0
14
1,102
1,936
1,020
916
85
1
import Bayesian.CheckedError import Bayesian.Factor import Bayesian.Variable import Bayesian.Inference.VariableElimination import Data.Either import Data.List main :: IO () main = do print vePr1Test1 print vePr1Test2 print vePr1Test3 print vePr1Test4 variableA :: Variable variableA = createVariable "A" ["0", "1"] variableB :: Variable variableB = createVariable "B" ["0", "1"] variableC :: Variable variableC = createVariable "C" ["0", "1"] factorA :: Checked Factor factorA = buildFactor "A" vars factorValues where vars = [variableA] factorValues = do buildFactorValueFromInstantiation ["1"] 0.6 buildFactorValueFromInstantiation ["0"] 0.4 factorB :: Checked Factor factorB = buildFactor "B" vars factorValues where vars = [variableA, variableB] factorValues = do buildFactorValueFromInstantiation ["1", "1"] 0.9 buildFactorValueFromInstantiation ["1", "0"] 0.1 buildFactorValueFromInstantiation ["0", "1"] 0.2 buildFactorValueFromInstantiation ["0", "0"] 0.8 factorC :: Checked Factor factorC = buildFactor "C" vars factorValues where vars = [variableB, variableC] factorValues = do buildFactorValueFromInstantiation ["1", "1"] 0.3 buildFactorValueFromInstantiation ["1", "0"] 0.7 buildFactorValueFromInstantiation ["0", "1"] 0.5 buildFactorValueFromInstantiation ["0", "0"] 0.5 vePr1Test1 = vePr1 [variableB, variableA] $ rights [factorA, factorB, factorC] vePr1Test2 = vePr1 [variableA, variableB] $ rights [factorA, factorB, factorC] vePr1Test3 = vePr1 [variableC, variableB] $ rights [factorA, factorB, factorC] vePr1Test4 = vePr1 [variableA, variableC] $ rights [factorA, factorB, factorC]
sebassimoes/haskell-bayesian
test/VariableEliminationTestSuite.hs
bsd-3-clause
1,746
0
10
331
499
266
233
44
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} module Main where import System.Environment (getArgs) import System.Directory (doesFileExist, doesDirectoryExist) import Data.List (isSuffixOf) import Control.Monad (liftM2, void) import Control.Monad.Trans import Control.Monad.Trans.Maybe import Text.Pandoc (def, readMarkdown, writeHtmlString) import qualified Data.Text as T -- | The monad of landrover newtype LandroverM a = LandroverM { unwrapL :: MaybeT IO a } deriving (Functor, Applicative, MonadIO) instance Monad LandroverM where a >>= f = LandroverM (unwrapL a >>= unwrapL . f) fail err = do liftIO . putStrLn $ err LandroverM . fail $ err -- | Run a LandroverM runLandroverM :: LandroverM a -> IO (Maybe a) runLandroverM = runMaybeT . unwrapL -- | Retrieve and validate the paths supplied via arguments getPaths :: LandroverM (FilePath, FilePath) getPaths = do args <- liftIO getArgs case args of [markdown, presentation] -> liftM2 (,) (validateMarkdownPath markdown) (validatePresentationPath presentation) _ -> fail "Usage: landrover [markdown] [presentation]" -- | Validate the path to the markdown file by assuring it exists validateMarkdownPath :: FilePath -> LandroverM FilePath validateMarkdownPath path = do exists <- liftIO . doesFileExist $ path if exists then return path else fail $ "Can't find markdown at " ++ path -- | Validate the path to the presentation folder, checking wether it and -- the template file exist validatePresentationPath :: FilePath -> LandroverM FilePath validatePresentationPath path = do -- Make sure the path ends with a '/' let fixedPath = if "/" `isSuffixOf` path then path else path ++ "/" presentationExists <- liftIO . doesDirectoryExist $ fixedPath if presentationExists then do templateExists <- liftIO . doesFileExist $ fixedPath ++ "template.html" if templateExists then return fixedPath else fail $ "Can't find template at " ++ fixedPath ++ "template.html" else fail $ "Can't find presentation in " ++ path -- | Try converting the markdown to html convertMarkdown :: FilePath -> LandroverM String convertMarkdown path = do markdown <- liftIO . readFile $ path case readMarkdown def markdown of Right pandoc -> return . writeHtmlString def $ pandoc Left err -> fail $ "Error reading markdown: " ++ show err -- | Convert the html code into reveal.js slides slidifyHtml :: String -> T.Text slidifyHtml html = foldr1 T.append sections where sections = map surround . T.splitOn "<hr />" $ packed packed = T.pack html surround text = "<section>" `T.append` text `T.append` "</section>" -- | Insert the slides into the template and save it as index.html insertIntoTemplate :: FilePath -> T.Text -> LandroverM () insertIntoTemplate presentationPath insert = do content <- liftIO . readFile $ presentationPath ++ "template.html" let template = T.pack content output = T.replace token insert template liftIO . writeFile (presentationPath ++ "index.html") . T.unpack $ output where token = "<!-- SLIDES -->" main = void . runLandroverM $ do (markdown, presentation) <- getPaths html <- convertMarkdown markdown let slides = slidifyHtml html insertIntoTemplate presentation slides
froozen/landrover
Main.hs
bsd-3-clause
3,504
0
13
816
828
429
399
73
4
module X ( foo, bar, baz ) where foo = 10
itchyny/vim-haskell-indent
test/module/export_lines_paren_where.out.hs
mit
66
0
4
35
20
13
7
4
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="tr-TR"> <title>Hızlı Başlat | ZAP uzantısı</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>İçindekiler</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>İçerik</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Arama</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favoriler</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/diff/src/main/javahelp/org/zaproxy/zap/extension/diff/resources/help_tr_TR/helpset_tr_TR.hs
apache-2.0
985
80
66
160
431
217
214
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Snap.Internal.Util.FileUploads ( -- * Functions handleFormUploads , foldMultipart , PartFold , FormParam , FormFile (..) , storeAsLazyByteString , withTemporaryStore -- ** Backwards compatible API , handleFileUploads , handleMultipart , PartProcessor -- * Uploaded parts , PartInfo(..) , PartDisposition(..) , toPartDisposition -- ** Policy -- *** General upload policy , UploadPolicy(..) , defaultUploadPolicy , doProcessFormInputs , setProcessFormInputs , getMaximumFormInputSize , setMaximumFormInputSize , getMaximumNumberOfFormInputs , setMaximumNumberOfFormInputs , getMinimumUploadRate , setMinimumUploadRate , getMinimumUploadSeconds , setMinimumUploadSeconds , getUploadTimeout , setUploadTimeout -- *** File upload policy , FileUploadPolicy(..) , defaultFileUploadPolicy , setMaximumFileSize , setMaximumNumberOfFiles , setSkipFilesWithoutNames , setMaximumSkippedFileSize -- *** Per-file upload policy , PartUploadPolicy(..) , disallow , allowWithMaximumSize -- * Exceptions , FileUploadException(..) , fileUploadExceptionReason , BadPartException(..) , PolicyViolationException(..) ) where ------------------------------------------------------------------------------ import Control.Applicative (Alternative ((<|>)), Applicative (pure, (*>), (<*))) import Control.Arrow (Arrow (first)) import Control.Exception.Lifted (Exception, SomeException (..), bracket, catch, finally, fromException, mask, throwIO, toException) import qualified Control.Exception.Lifted as E (try) import Control.Monad (Functor (fmap), Monad (return, (>>=)), MonadPlus (mzero), forM_, guard, liftM, sequence, unless, void, when, (>=>)) import Control.Monad.IO.Class (liftIO) import Data.Attoparsec.ByteString.Char8 (Parser, isEndOfLine, string, takeWhile) import qualified Data.Attoparsec.ByteString.Char8 as Atto (try) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as S import Data.ByteString.Internal (c2w) import qualified Data.ByteString.Lazy.Internal as LB (ByteString (Empty), chunk) import qualified Data.CaseInsensitive as CI (mk) import Data.Int (Int, Int64) import qualified Data.IORef as IORef import Data.List (find, map, (++)) import qualified Data.Map as Map (insertWith) import Data.Maybe (Maybe (..), fromMaybe, isJust, maybe) import Data.Text (Text) import qualified Data.Text as T (concat, pack, unpack) import qualified Data.Text.Encoding as TE (decodeUtf8) import Data.Typeable (Typeable, cast) import Prelude (Bool (..), Double, Either (..), Eq (..), FilePath, IO, Ord (..), Show (..), String, const, either, foldr, fst, id, max, not, otherwise, seq, snd, succ, ($), ($!), (.), (^), (||)) import Snap.Core (HasHeaders (headers), Headers, MonadSnap, Request (rqParams, rqPostParams), getHeader, getRequest, getTimeoutModifier, putRequest, runRequestBody) import Snap.Internal.Parsing (crlf, fullyParse, pContentTypeWithParameters, pHeaders, pValueWithParameters') import qualified Snap.Types.Headers as H (fromList) import System.Directory (removeFile) import System.FilePath ((</>)) import System.IO (BufferMode (NoBuffering), Handle, hClose, hSetBuffering, openBinaryTempFile) import System.IO.Error (isDoesNotExistError) import System.IO.Streams (InputStream, MatchInfo (..), TooManyBytesReadException, search) import qualified System.IO.Streams as Streams import System.IO.Streams.Attoparsec (parseFromStream) import System.PosixCompat.Temp (mkstemp) ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Reads uploaded files into a temporary directory and calls a user handler -- to process them. -- -- Note: /THE REQUEST MUST BE CORRECTLY ENCODED/. If the request's -- @Content-type@ is not \"@multipart/formdata@\", this function skips -- processing using 'pass'. -- -- Given a temporary directory, global and file-specific upload policies, and a -- user handler, this function consumes a request body uploaded with -- @Content-type: multipart/form-data@. Each file is read into the temporary -- directory, and is then passed to the user handler. After the user handler -- runs (but before the 'Response' body is streamed to the client), the files -- are deleted from disk; so if you want to retain or use the uploaded files in -- the generated response, you need to move or otherwise process them. -- -- The argument passed to the user handler is a tuple: -- -- > (PartInfo, Either PolicyViolationException FilePath) -- -- The first half of this tuple is a 'PartInfo', which contains the -- information the client browser sent about the given upload part (like -- filename, content-type, etc). The second half of this tuple is an 'Either' -- stipulating that either: -- -- 1. the file was rejected on a policy basis because of the provided -- 'PartUploadPolicy' handler -- -- 2. the file was accepted and exists at the given path. -- -- /Exceptions/ -- -- If the client's upload rate passes below the configured minimum (see -- 'setMinimumUploadRate' and 'setMinimumUploadSeconds'), this function -- terminates the connection. This setting is there to protect the server -- against slowloris-style denial of service attacks. -- -- If the given 'UploadPolicy' stipulates that you wish form inputs to be -- placed in the 'rqParams' parameter map (using 'setProcessFormInputs'), and -- a form input exceeds the maximum allowable size, this function will throw a -- 'PolicyViolationException'. -- -- If an uploaded part contains MIME headers longer than a fixed internal -- threshold (currently 32KB), this function will throw a 'BadPartException'. handleFileUploads :: (MonadSnap m) => FilePath -- ^ temporary directory -> UploadPolicy -- ^ general upload policy -> (PartInfo -> PartUploadPolicy) -- ^ per-part upload policy -> (PartInfo -> Either PolicyViolationException FilePath -> IO a) -- ^ user handler (see function -- description) -> m [a] handleFileUploads tmpdir uploadPolicy partPolicy partHandler = handleMultipart uploadPolicy go where go partInfo stream = maybe disallowed takeIt mbFs where ctText = partContentType partInfo fnText = fromMaybe "" $ partFileName partInfo ct = TE.decodeUtf8 ctText fn = TE.decodeUtf8 fnText (PartUploadPolicy mbFs) = partPolicy partInfo takeIt maxSize = do str' <- Streams.throwIfProducesMoreThan maxSize stream fileReader tmpdir partHandler partInfo str' `catch` tooMany maxSize tooMany maxSize (_ :: TooManyBytesReadException) = partHandler partInfo (Left $ PolicyViolationException $ T.concat [ "File \"" , fn , "\" exceeded maximum allowable size " , T.pack $ show maxSize ]) disallowed = partHandler partInfo (Left $ PolicyViolationException $ T.concat [ "Policy disallowed upload of file \"" , fn , "\" with content-type \"" , ct , "\"" ] ) ------------------------------------------------------------------------------ -- | Contents of form field of type @file@ data FormFile a = FormFile { formFileName :: !ByteString -- ^ Name of a field , formFileValue :: a -- ^ Result of storing file } deriving (Eq, Ord, Show) data UploadState a = UploadState { numUploadedFiles :: !Int , uploadedFiles :: !([FormFile a] -> [FormFile a]) } -- | Processes form data and calls provided storage function on -- file parts. -- -- You can use this together with 'withTemporaryStore', 'storeAsLazyByteString' -- or provide your own callback to store uploaded files. -- -- If you need to process uploaded file mime type or file name, do it in the -- store callback function. -- -- See also 'foldMultipart'. -- -- Example using with small files which can safely be stored in memory. -- -- @ -- -- import qualified Data.ByteString.Lazy as Lazy -- -- handleSmallFiles :: MonadSnap m => [(ByteString, ByteString, Lazy.ByteString)] -- handleSmallFiles = handleFormUploads uploadPolicy filePolicy store -- -- where -- uploadPolicy = defaultUploadPolicy -- filePolicy = setMaximumFileSize (64*1024) -- $ setMaximumNumberOfFiles 5 -- defaultUploadPolicy -- store partInfo stream = do -- content <- storeAsLazyByteString partInfo stream -- let -- fileName = partFileName partInfo -- fileMime = partContentType partInfo -- in (fileName, fileMime, content) -- @ -- handleFormUploads :: (MonadSnap m) => UploadPolicy -- ^ general upload policy -> FileUploadPolicy -- ^ Upload policy for files -> (PartInfo -> InputStream ByteString -> IO a) -- ^ A file storage function -> m ([FormParam], [FormFile a]) handleFormUploads uploadPolicy filePolicy partHandler = do (params, !st) <- foldMultipart uploadPolicy go (UploadState 0 id) return (params, uploadedFiles st []) where go !partInfo stream !st = do when (numUploads >= maxFiles) throwTooManyFiles case partFileName partInfo of Nothing -> onEmptyName Just _ -> takeIt where numUploads = numUploadedFiles st files = uploadedFiles st maxFiles = maxNumberOfFiles filePolicy maxFileSize = maxFileUploadSize filePolicy fnText = fromMaybe "" $ partFileName partInfo fn = TE.decodeUtf8 fnText takeIt = do str' <- Streams.throwIfProducesMoreThan maxFileSize stream r <- partHandler partInfo str' `catch` tooMany maxFileSize let f = FormFile (partFieldName partInfo) r return $! UploadState (succ numUploads) (files . ([f] ++) ) skipIt maxSize = do str' <- Streams.throwIfProducesMoreThan maxSize stream !_ <- Streams.skipToEof str' `catch` tooMany maxSize return $! UploadState (succ numUploads) files onEmptyName = if skipEmptyFileName filePolicy then skipIt (maxEmptyFileNameSize filePolicy) else takeIt throwTooManyFiles = throwIO . PolicyViolationException $ T.concat ["number of files exceeded the maximum of " ,T.pack (show maxFiles) ] tooMany maxSize (_ :: TooManyBytesReadException) = throwIO . PolicyViolationException $ T.concat [ "File \"" , fn , "\" exceeded maximum allowable size " , T.pack $ show maxSize ] ------------------------------------------------------------------------------ -- | A type alias for a function that will process one of the parts of a -- @multipart/form-data@ HTTP request body with accumulator. type PartFold a = PartInfo -> InputStream ByteString -> a -> IO a ------------------------------------------------------------------------------ -- | Given an upload policy and a function to consume uploaded \"parts\", -- consume a request body uploaded with @Content-type: multipart/form-data@. -- -- If 'setProcessFormInputs' is 'True', then parts with disposition @form-data@ -- (a form parameter) will be processed and returned as first element of -- resulting pair. Parts with other disposition will be fed to 'PartFold' -- handler. -- -- If 'setProcessFormInputs' is 'False', then parts with any disposition will -- be fed to 'PartFold' handler and first element of returned pair will be -- empty. In this case it is important that you limit number of form inputs -- and sizes of inputs in your 'PartFold' handler to avoid common DOS attacks. -- -- Note: /THE REQUEST MUST BE CORRECTLY ENCODED/. If the request's -- @Content-type@ is not \"@multipart/formdata@\", this function skips -- processing using 'pass'. -- -- Most users will opt for the higher-level 'handleFileUploads', which writes -- to temporary files, rather than 'handleMultipart'. This function should be -- chosen, however, if you need to stream uploaded files directly to your own -- processing function: e.g. to a database or a remote service via RPC. -- -- If the client's upload rate passes below the configured minimum (see -- 'setMinimumUploadRate' and 'setMinimumUploadSeconds'), this function -- terminates the connection. This setting is there to protect the server -- against slowloris-style denial of service attacks. -- -- /Exceptions/ -- -- If the given 'UploadPolicy' stipulates that you wish form inputs to be -- processed (using 'setProcessFormInputs'), and a form input exceeds the -- maximum allowable size or the form exceeds maximum number of inputs, this -- function will throw a 'PolicyViolationException'. -- -- If an uploaded part contains MIME headers longer than a fixed internal -- threshold (currently 32KB), this function will throw a 'BadPartException'. -- -- /Since: 1.0.3.0/ foldMultipart :: (MonadSnap m) => UploadPolicy -- ^ global upload policy -> PartFold a -- ^ part processor -> a -- ^ seed accumulator -> m ([FormParam], a) foldMultipart uploadPolicy origPartHandler zero = do hdrs <- liftM headers getRequest let (ct, mbBoundary) = getContentType hdrs tickleTimeout <- liftM (. max) getTimeoutModifier let bumpTimeout = tickleTimeout $ uploadTimeout uploadPolicy let partHandler = if doProcessFormInputs uploadPolicy then captureVariableOrReadFile (getMaximumFormInputSize uploadPolicy) origPartHandler else \x y acc -> liftM File $ origPartHandler x y acc -- not well-formed multipart? bomb out. guard (ct == "multipart/form-data") boundary <- maybe (throwIO $ BadPartException "got multipart/form-data without boundary") return mbBoundary -- RateTooSlowException will be caught and properly dealt with by -- runRequestBody runRequestBody (proc bumpTimeout boundary partHandler) where -------------------------------------------------------------------------- uploadRate = minimumUploadRate uploadPolicy uploadSecs = minimumUploadSeconds uploadPolicy maxFormVars = maximumNumberOfFormInputs uploadPolicy -------------------------------------------------------------------------- proc bumpTimeout boundary partHandler = Streams.throwIfTooSlow bumpTimeout uploadRate uploadSecs >=> internalFoldMultipart maxFormVars boundary partHandler zero ------------------------------------------------------------------------------ -- | A type alias for a function that will process one of the parts of a -- @multipart/form-data@ HTTP request body without usinc accumulator. type PartProcessor a = PartInfo -> InputStream ByteString -> IO a ------------------------------------------------------------------------------ -- | A variant of 'foldMultipart' accumulating results into a list. -- Also puts captured 'FormParam's into rqPostParams and rqParams maps. -- handleMultipart :: (MonadSnap m) => UploadPolicy -- ^ global upload policy -> PartProcessor a -- ^ part processor -> m [a] handleMultipart uploadPolicy origPartHandler = do (captures, files) <- foldMultipart uploadPolicy partFold id procCaptures captures return $! files [] where partFold info input acc = do x <- origPartHandler info input return $ acc . ([x]++) -------------------------------------------------------------------------- procCaptures [] = pure () procCaptures params = do rq <- getRequest putRequest $ modifyParams (\m -> foldr ins m params) rq -------------------------------------------------------------------------- ins (!k, !v) = Map.insertWith (\_ ex -> (v:ex)) k [v] -- prepend value if key exists, since we are folding from right -------------------------------------------------------------------------- modifyParams f r = r { rqPostParams = f $ rqPostParams r , rqParams = f $ rqParams r } ------------------------------------------------------------------------------ -- | Represents the disposition type specified via the @Content-Disposition@ -- header field. See <https://www.ietf.org/rfc/rfc1806.txt RFC 1806>. data PartDisposition = DispositionAttachment -- ^ @Content-Disposition: attachment@. | DispositionFile -- ^ @Content-Disposition: file@. | DispositionFormData -- ^ @Content-Disposition: form-data@. | DispositionOther ByteString -- ^ Any other value. deriving (Eq, Show) ------------------------------------------------------------------------------ -- | 'PartInfo' contains information about a \"part\" in a request uploaded -- with @Content-type: multipart/form-data@. data PartInfo = PartInfo { partFieldName :: !ByteString -- ^ Field name associated with this part (i.e., the name specified with -- @\<input name=\"partFieldName\" ...@). , partFileName :: !(Maybe ByteString) -- ^ Name of the uploaded file. , partContentType :: !ByteString -- ^ Content type of this part. , partDisposition :: !PartDisposition -- ^ Disposition type of this part. See 'PartDisposition'. , partHeaders :: !Headers -- ^ Remaining headers associated with this part. } deriving (Show) ------------------------------------------------------------------------------ toPartDisposition :: ByteString -> PartDisposition toPartDisposition s | s == "attachment" = DispositionAttachment | s == "file" = DispositionFile | s == "form-data" = DispositionFormData | otherwise = DispositionOther s ------------------------------------------------------------------------------ -- | All of the exceptions defined in this package inherit from -- 'FileUploadException', so if you write -- -- > foo `catch` \(e :: FileUploadException) -> ... -- -- you can catch a 'BadPartException', a 'PolicyViolationException', etc. data FileUploadException = forall e . (ExceptionWithReason e, Show e) => WrappedFileUploadException e deriving (Typeable) ------------------------------------------------------------------------------ class Exception e => ExceptionWithReason e where exceptionReason :: e -> Text ------------------------------------------------------------------------------ instance Show FileUploadException where show (WrappedFileUploadException e) = show e ------------------------------------------------------------------------------ instance Exception FileUploadException ------------------------------------------------------------------------------ -- | Human-readable error message corresponding to the 'FileUploadException'. fileUploadExceptionReason :: FileUploadException -> Text fileUploadExceptionReason (WrappedFileUploadException e) = exceptionReason e ------------------------------------------------------------------------------ uploadExceptionToException :: ExceptionWithReason e => e -> SomeException uploadExceptionToException = toException . WrappedFileUploadException ------------------------------------------------------------------------------ uploadExceptionFromException :: ExceptionWithReason e => SomeException -> Maybe e uploadExceptionFromException x = do WrappedFileUploadException e <- fromException x cast e ------------------------------------------------------------------------------ -- | Thrown when a part is invalid in some way (e.g. the headers are too large). data BadPartException = BadPartException { -- | Human-readable error message corresponding to the 'BadPartException'. badPartExceptionReason :: Text } deriving (Typeable) instance Exception BadPartException where toException = uploadExceptionToException fromException = uploadExceptionFromException instance ExceptionWithReason BadPartException where exceptionReason (BadPartException e) = T.concat ["Bad part: ", e] instance Show BadPartException where show = T.unpack . exceptionReason ------------------------------------------------------------------------------ -- | Thrown when an 'UploadPolicy' or 'PartUploadPolicy' is violated. data PolicyViolationException = PolicyViolationException { -- | Human-readable error message corresponding to the -- 'PolicyViolationException'. policyViolationExceptionReason :: Text } deriving (Typeable) instance Exception PolicyViolationException where toException e@(PolicyViolationException _) = uploadExceptionToException e fromException = uploadExceptionFromException instance ExceptionWithReason PolicyViolationException where exceptionReason (PolicyViolationException r) = T.concat ["File upload policy violation: ", r] instance Show PolicyViolationException where show (PolicyViolationException s) = "File upload policy violation: " ++ T.unpack s ------------------------------------------------------------------------------ -- | 'UploadPolicy' controls overall policy decisions relating to -- @multipart/form-data@ uploads, specifically: -- -- * whether to treat parts without filenames as form input (reading them into -- the 'rqParams' map) -- -- * because form input is read into memory, the maximum size of a form input -- read in this manner, and the maximum number of form inputs -- -- * the minimum upload rate a client must maintain before we kill the -- connection; if very low-bitrate uploads were allowed then a Snap server -- would be vulnerable to a trivial denial-of-service using a -- \"slowloris\"-type attack -- -- * the minimum number of seconds which must elapse before we start killing -- uploads for having too low an upload rate. -- -- * the amount of time we should wait before timing out the connection -- whenever we receive input from the client. data UploadPolicy = UploadPolicy { processFormInputs :: Bool , maximumFormInputSize :: Int64 , maximumNumberOfFormInputs :: Int , minimumUploadRate :: Double , minimumUploadSeconds :: Int , uploadTimeout :: Int } ------------------------------------------------------------------------------ -- | A reasonable set of defaults for upload policy. The default policy is: -- -- [@maximum form input size@] 128kB -- -- [@maximum number of form inputs@] 10 -- -- [@minimum upload rate@] 1kB/s -- -- [@seconds before rate limiting kicks in@] 10 -- -- [@inactivity timeout@] 20 seconds -- defaultUploadPolicy :: UploadPolicy defaultUploadPolicy = UploadPolicy True maxSize maxNum minRate minSeconds tout where maxSize = 2^(17::Int) maxNum = 10 minRate = 1000 minSeconds = 10 tout = 20 ------------------------------------------------------------------------------ -- | Does this upload policy stipulate that we want to treat parts without -- filenames as form input? doProcessFormInputs :: UploadPolicy -> Bool doProcessFormInputs = processFormInputs ------------------------------------------------------------------------------ -- | Set the upload policy for treating parts without filenames as form input. setProcessFormInputs :: Bool -> UploadPolicy -> UploadPolicy setProcessFormInputs b u = u { processFormInputs = b } ------------------------------------------------------------------------------ -- | Get the maximum size of a form input which will be read into our -- 'rqParams' map. getMaximumFormInputSize :: UploadPolicy -> Int64 getMaximumFormInputSize = maximumFormInputSize ------------------------------------------------------------------------------ -- | Set the maximum size of a form input which will be read into our -- 'rqParams' map. setMaximumFormInputSize :: Int64 -> UploadPolicy -> UploadPolicy setMaximumFormInputSize s u = u { maximumFormInputSize = s } ------------------------------------------------------------------------------ -- | Get the maximum size of a form input which will be read into our -- 'rqParams' map. getMaximumNumberOfFormInputs :: UploadPolicy -> Int getMaximumNumberOfFormInputs = maximumNumberOfFormInputs ------------------------------------------------------------------------------ -- | Set the maximum size of a form input which will be read into our -- 'rqParams' map. setMaximumNumberOfFormInputs :: Int -> UploadPolicy -> UploadPolicy setMaximumNumberOfFormInputs s u = u { maximumNumberOfFormInputs = s } ------------------------------------------------------------------------------ -- | Get the minimum rate (in /bytes\/second/) a client must maintain before -- we kill the connection. getMinimumUploadRate :: UploadPolicy -> Double getMinimumUploadRate = minimumUploadRate ------------------------------------------------------------------------------ -- | Set the minimum rate (in /bytes\/second/) a client must maintain before -- we kill the connection. setMinimumUploadRate :: Double -> UploadPolicy -> UploadPolicy setMinimumUploadRate s u = u { minimumUploadRate = s } ------------------------------------------------------------------------------ -- | Get the amount of time which must elapse before we begin enforcing the -- upload rate minimum getMinimumUploadSeconds :: UploadPolicy -> Int getMinimumUploadSeconds = minimumUploadSeconds ------------------------------------------------------------------------------ -- | Set the amount of time which must elapse before we begin enforcing the -- upload rate minimum setMinimumUploadSeconds :: Int -> UploadPolicy -> UploadPolicy setMinimumUploadSeconds s u = u { minimumUploadSeconds = s } ------------------------------------------------------------------------------ -- | Get the \"upload timeout\". Whenever input is received from the client, -- the connection timeout is set this many seconds in the future. getUploadTimeout :: UploadPolicy -> Int getUploadTimeout = uploadTimeout ------------------------------------------------------------------------------ -- | Set the upload timeout. setUploadTimeout :: Int -> UploadPolicy -> UploadPolicy setUploadTimeout s u = u { uploadTimeout = s } ------------------------------------------------------------------------------ -- | File upload policy, if any policy is violated then -- 'PolicyViolationException' is thrown data FileUploadPolicy = FileUploadPolicy { maxFileUploadSize :: !Int64 , maxNumberOfFiles :: !Int , skipEmptyFileName :: !Bool , maxEmptyFileNameSize :: !Int64 } -- | A default 'FileUploadPolicy' -- -- [@maximum file size@] 1MB -- -- [@maximum number of files@] 10 -- -- [@skip files without name@] yes -- -- [@maximum size of skipped file@] 0 -- -- defaultFileUploadPolicy :: FileUploadPolicy defaultFileUploadPolicy = FileUploadPolicy maxFileSize maxFiles skipEmptyName maxEmptySize where maxFileSize = 1048576 -- 1MB maxFiles = 10 skipEmptyName = True maxEmptySize = 0 -- | Maximum size of single uploaded file. setMaximumFileSize :: Int64 -> FileUploadPolicy -> FileUploadPolicy setMaximumFileSize maxSize s = s { maxFileUploadSize = maxSize } -- | Maximum number of uploaded files. setMaximumNumberOfFiles :: Int -> FileUploadPolicy -> FileUploadPolicy setMaximumNumberOfFiles maxFiles s = s { maxNumberOfFiles = maxFiles } -- | Skip files with empty file names. -- -- If set, parts without filenames will not be fed to storage function. -- -- HTML5 form data encoding standard states that form input fields of type -- file, without value set, are encoded same way as if file with empty body, -- empty file name, and type @application/octet-stream@ was set as value. -- -- You most likely want to use this with zero bytes allowed to avoid storing -- such fields (see 'setMaximumSkippedFileSize'). -- -- By default files without names are skipped. -- -- /Since: 1.0.3.0/ setSkipFilesWithoutNames :: Bool -> FileUploadPolicy -> FileUploadPolicy setSkipFilesWithoutNames shouldSkip s = s { skipEmptyFileName = shouldSkip } -- | Maximum size of file without name which can be skipped. -- -- Ignored if 'setSkipFilesWithoutNames' is @False@. -- -- If skipped file is larger than this setting then 'FileUploadException' -- is thrown. -- -- By default maximum file size is 0. -- -- /Since: 1.0.3.0/ setMaximumSkippedFileSize :: Int64 -> FileUploadPolicy -> FileUploadPolicy setMaximumSkippedFileSize maxSize s = s { maxEmptyFileNameSize = maxSize } ------------------------------------------------------------------------------ -- | Upload policy can be set on an \"general\" basis (using 'UploadPolicy'), -- but handlers can also make policy decisions on individual files\/parts -- uploaded. For each part uploaded, handlers can decide: -- -- * whether to allow the file upload at all -- -- * the maximum size of uploaded files, if allowed data PartUploadPolicy = PartUploadPolicy (Maybe Int64) ------------------------------------------------------------------------------ -- | Disallows the file to be uploaded. disallow :: PartUploadPolicy disallow = PartUploadPolicy Nothing ------------------------------------------------------------------------------ -- | Allows the file to be uploaded, with maximum size /n/ in bytes. allowWithMaximumSize :: Int64 -> PartUploadPolicy allowWithMaximumSize = PartUploadPolicy . Just ------------------------------------------------------------------------------ -- | Stores file body in memory as Lazy ByteString. storeAsLazyByteString :: InputStream ByteString -> IO LB.ByteString storeAsLazyByteString !str = do f <- Streams.fold (\f c -> f . LB.chunk c) id str return $! f LB.Empty ------------------------------------------------------------------------------ -- | Store files in a temporary directory, and clean up on function exit. -- -- Files are safe to move until function exists. -- -- If asynchronous exception is thrown during cleanup, temporary files may -- remain. -- -- @ -- uploadsHandler = withTemporaryStore "/var/tmp" "upload-" $ \store -> do -- (inputs, files) <- handleFormUploads defaultUploadpolicy -- defaultFileUploadPolicy -- (const store) -- saveFiles files -- -- @ -- withTemporaryStore :: MonadSnap m => FilePath -- ^ temporary directory -> String -- ^ file name pattern -> ((InputStream ByteString -> IO FilePath) -> m a) -- ^ Action taking store function -> m a withTemporaryStore tempdir pat act = do ioref <- liftIO $ IORef.newIORef [] let modifyIORef' ref f = do -- ghc 7.4 does not have modifyIORef' x <- IORef.readIORef ref let x' = f x x' `seq` IORef.writeIORef ref x' go input = do (fn, h) <- openBinaryTempFile tempdir pat modifyIORef' ioref (fn:) hSetBuffering h NoBuffering output <- Streams.handleToOutputStream h Streams.connect input output hClose h pure fn cleanup = liftIO $ do files <- IORef.readIORef ioref forM_ files $ \fn -> removeFile fn `catch` handleExists handleExists e = unless (isDoesNotExistError e) $ throwIO e act go `finally` cleanup ------------------------------------------------------------------------------ -- private exports follow. FIXME: organize ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ captureVariableOrReadFile :: Int64 -- ^ maximum size of form input -> PartFold a -- ^ file reading code -> PartInfo -> InputStream ByteString -> a -> IO (Capture a) captureVariableOrReadFile maxSize fileHandler partInfo stream acc = if isFile then liftM File $ fileHandler partInfo stream acc else variable `catch` handler where isFile = isJust (partFileName partInfo) || partDisposition partInfo == DispositionFile variable = do !x <- liftM S.concat $ Streams.throwIfProducesMoreThan maxSize stream >>= Streams.toList return $! Capture fieldName x fieldName = partFieldName partInfo handler (_ :: TooManyBytesReadException) = throwIO $ PolicyViolationException $ T.concat [ "form input '" , TE.decodeUtf8 fieldName , "' exceeded maximum permissible size (" , T.pack $ show maxSize , " bytes)" ] ------------------------------------------------------------------------------ data Capture a = Capture !ByteString !ByteString | File a ------------------------------------------------------------------------------ fileReader :: FilePath -> (PartInfo -> Either PolicyViolationException FilePath -> IO a) -> PartProcessor a fileReader tmpdir partProc partInfo input = withTempFile tmpdir "snap-upload-" $ \(fn, h) -> do hSetBuffering h NoBuffering output <- Streams.handleToOutputStream h Streams.connect input output hClose h partProc partInfo $ Right fn ------------------------------------------------------------------------------ data MultipartState a = MultipartState { numFormVars :: {-# UNPACK #-} !Int , numFormFiles :: {-# UNPACK #-} !Int , capturedFields :: !([FormParam] -> [FormParam]) , accumulator :: !a } ------------------------------------------------------------------------------ -- | A form parameter name-value pair type FormParam = (ByteString, ByteString) ------------------------------------------------------------------------------ addCapture :: ByteString -> ByteString -> MultipartState a -> MultipartState a addCapture !k !v !ms = let !kv = (k,v) f = capturedFields ms . ([kv]++) !ms' = ms { capturedFields = f , numFormVars = succ (numFormVars ms) } in ms' ------------------------------------------------------------------------------ internalFoldMultipart :: Int -- ^ max num fields -> ByteString -- ^ boundary value -> (PartInfo -> InputStream ByteString -> a -> IO (Capture a)) -- ^ part processor -> a -> InputStream ByteString -> IO ([FormParam], a) internalFoldMultipart !maxFormVars !boundary clientHandler !zeroAcc !stream = go where -------------------------------------------------------------------------- initialState = MultipartState 0 0 id zeroAcc -------------------------------------------------------------------------- go = do -- swallow the first boundary _ <- parseFromStream (parseFirstBoundary boundary) stream bmstream <- search (fullBoundary boundary) stream ms <- foldParts goPart bmstream initialState return $ (capturedFields ms [], accumulator ms) -------------------------------------------------------------------------- pBoundary !b = Atto.try $ do _ <- string "--" string b -------------------------------------------------------------------------- fullBoundary !b = S.concat ["\r\n", "--", b] pLine = takeWhile (not . isEndOfLine . c2w) <* eol parseFirstBoundary !b = pBoundary b <|> (pLine *> parseFirstBoundary b) -------------------------------------------------------------------------- takeHeaders !str = hdrs `catch` handler where hdrs = do str' <- Streams.throwIfProducesMoreThan mAX_HDRS_SIZE str liftM toHeaders $ parseFromStream pHeadersWithSeparator str' handler (_ :: TooManyBytesReadException) = throwIO $ BadPartException "headers exceeded maximum size" -------------------------------------------------------------------------- goPart !str !state = do hdrs <- takeHeaders str -- are we using mixed? let (contentType, mboundary) = getContentType hdrs let (fieldName, fileName, disposition) = getFieldHeaderInfo hdrs if contentType == "multipart/mixed" then maybe (throwIO $ BadPartException $ "got multipart/mixed without boundary") (processMixed fieldName str state) mboundary else do let info = PartInfo fieldName fileName contentType disposition hdrs handlePart info str state -------------------------------------------------------------------------- handlePart !info !str !ms = do r <- clientHandler info str (accumulator ms) case r of Capture !k !v -> do when (maxFormVars <= numFormVars ms) throwTooMuchVars return $! addCapture k v ms File !newAcc -> return $! ms { accumulator = newAcc , numFormFiles = succ (numFormFiles ms) } throwTooMuchVars = throwIO . PolicyViolationException $ T.concat [ "number of form inputs exceeded maximum of " , T.pack $ show maxFormVars ] -------------------------------------------------------------------------- processMixed !fieldName !str !state !mixedBoundary = do -- swallow the first boundary _ <- parseFromStream (parseFirstBoundary mixedBoundary) str bm <- search (fullBoundary mixedBoundary) str foldParts (mixedStream fieldName) bm state -------------------------------------------------------------------------- mixedStream !fieldName !str !acc = do hdrs <- takeHeaders str let (contentType, _) = getContentType hdrs let (_, fileName, disposition) = getFieldHeaderInfo hdrs let info = PartInfo fieldName fileName contentType disposition hdrs handlePart info str acc ------------------------------------------------------------------------------ getContentType :: Headers -> (ByteString, Maybe ByteString) getContentType hdrs = (contentType, boundary) where contentTypeValue = fromMaybe "text/plain" $ getHeader "content-type" hdrs eCT = fullyParse contentTypeValue pContentTypeWithParameters (!contentType, !params) = either (const ("text/plain", [])) id eCT boundary = findParam "boundary" params ------------------------------------------------------------------------------ getFieldHeaderInfo :: Headers -> (ByteString, Maybe ByteString, PartDisposition) getFieldHeaderInfo hdrs = (fieldName, fileName, disposition) where contentDispositionValue = fromMaybe "unknown" $ getHeader "content-disposition" hdrs eDisposition = fullyParse contentDispositionValue $ pValueWithParameters' (const True) (!dispositionType, dispositionParameters) = either (const ("unknown", [])) id eDisposition disposition = toPartDisposition dispositionType fieldName = fromMaybe "" $ findParam "name" dispositionParameters fileName = findParam "filename" dispositionParameters ------------------------------------------------------------------------------ findParam :: (Eq a) => a -> [(a, b)] -> Maybe b findParam p = fmap snd . find ((== p) . fst) ------------------------------------------------------------------------------ partStream :: InputStream MatchInfo -> IO (InputStream ByteString) partStream st = Streams.makeInputStream go where go = do s <- Streams.read st return $! s >>= f f (NoMatch s) = return s f _ = mzero ------------------------------------------------------------------------------ -- | Assuming we've already identified the boundary value and split the input -- up into parts which match and parts which don't, run the given 'ByteString' -- InputStream over each part and grab a list of the resulting values. -- -- TODO/FIXME: fix description foldParts :: (InputStream ByteString -> MultipartState a -> IO (MultipartState a)) -> InputStream MatchInfo -> (MultipartState a) -> IO (MultipartState a) foldParts partFunc stream = go where part acc pStream = do isLast <- parseFromStream pBoundaryEnd pStream if isLast then return Nothing else do !x <- partFunc pStream acc Streams.skipToEof pStream return $! Just x go !acc = do cap <- partStream stream >>= part acc maybe (return acc) go cap pBoundaryEnd = (eol *> pure False) <|> (string "--" *> pure True) ------------------------------------------------------------------------------ eol :: Parser ByteString eol = (string "\n") <|> (string "\r\n") ------------------------------------------------------------------------------ pHeadersWithSeparator :: Parser [(ByteString,ByteString)] pHeadersWithSeparator = pHeaders <* crlf ------------------------------------------------------------------------------ toHeaders :: [(ByteString,ByteString)] -> Headers toHeaders kvps = H.fromList kvps' where kvps' = map (first CI.mk) kvps ------------------------------------------------------------------------------ mAX_HDRS_SIZE :: Int64 mAX_HDRS_SIZE = 32768 ------------------------------------------------------------------------------ withTempFile :: FilePath -> String -> ((FilePath, Handle) -> IO a) -> IO a withTempFile tmpl temp handler = mask $ \restore -> bracket make cleanup (restore . handler) where make = mkstemp $ tmpl </> (temp ++ "XXXXXXX") cleanup (fp,h) = sequence $ map gobble [hClose h, removeFile fp] t :: IO z -> IO (Either SomeException z) t = E.try gobble = void . t
snapframework/snap-core
src/Snap/Internal/Util/FileUploads.hs
bsd-3-clause
43,905
0
17
10,219
6,535
3,634
2,901
576
3
{-# OPTIONS_GHC -cpp #-} -- #hide module Distribution.Compat.RawSystem (rawSystem) where #if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 602 import Data.List (intersperse) import System.Cmd (system) import System.Exit (ExitCode) #else import System.Cmd (rawSystem) #endif #if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 602 rawSystem :: String -> [String] -> IO ExitCode rawSystem p args = system $ concat $ intersperse " " (p : map esc args) where esc arg = "'" ++ arg ++ "'" -- this is hideously broken, actually #endif
alekar/hugs
packages/Cabal/Distribution/Compat/RawSystem.hs
bsd-3-clause
528
0
9
80
122
70
52
3
0
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN" "http://java.sun.com/products/javahelp/helpset_1_0.dtd"> <helpset version="1.0"> <title>PetClinic Help</title> <maps> <mapref location="map.jhm"/> <homeID>PetClinic-ID</homeID> </maps> <view> <name>toc</name> <label>Table of Contents</label> <type>javax.help.TOCView</type> <data>toc.xml</data> </view> <view> <name>index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> </helpset>
springrichclient/springrcp
spring-richclient-samples/spring-richclient-samples-petclinic/petclinic-gui/src/main/resources/help/helpset.hs
apache-2.0
728
53
44
206
277
141
136
-1
-1
{-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details -- | A description of the register set of the X86. -- This isn't used directly in GHC proper. -- -- See RegArchBase.hs for the reference. -- See MachRegs.hs for the actual trivColorable function used in GHC. -- module RegAlloc.Graph.ArchX86 ( classOfReg, regsOfClass, regName, regAlias, worst, squeese, ) where import RegAlloc.Graph.ArchBase (Reg(..), RegSub(..), RegClass(..)) import UniqSet -- | Determine the class of a register classOfReg :: Reg -> RegClass classOfReg reg = case reg of Reg c _ -> c RegSub SubL16 _ -> ClassG16 RegSub SubL8 _ -> ClassG8 RegSub SubL8H _ -> ClassG8 -- | Determine all the regs that make up a certain class. regsOfClass :: RegClass -> UniqSet Reg regsOfClass c = case c of ClassG32 -> mkUniqSet [ Reg ClassG32 i | i <- [0..7] ] ClassG16 -> mkUniqSet [ RegSub SubL16 (Reg ClassG32 i) | i <- [0..7] ] ClassG8 -> unionUniqSets (mkUniqSet [ RegSub SubL8 (Reg ClassG32 i) | i <- [0..3] ]) (mkUniqSet [ RegSub SubL8H (Reg ClassG32 i) | i <- [0..3] ]) ClassF64 -> mkUniqSet [ Reg ClassF64 i | i <- [0..5] ] -- | Determine the common name of a reg -- returns Nothing if this reg is not part of the machine. regName :: Reg -> Maybe String regName reg = case reg of Reg ClassG32 i | i <= 7 -> Just ([ "eax", "ebx", "ecx", "edx", "ebp", "esi", "edi", "esp" ] !! i) RegSub SubL16 (Reg ClassG32 i) | i <= 7 -> Just ([ "ax", "bx", "cx", "dx", "bp", "si", "di", "sp"] !! i) RegSub SubL8 (Reg ClassG32 i) | i <= 3 -> Just ([ "al", "bl", "cl", "dl"] !! i) RegSub SubL8H (Reg ClassG32 i) | i <= 3 -> Just ([ "ah", "bh", "ch", "dh"] !! i) _ -> Nothing -- | Which regs alias what other regs regAlias :: Reg -> UniqSet Reg regAlias reg = case reg of -- 32 bit regs alias all of the subregs Reg ClassG32 i -- for eax, ebx, ecx, eds | i <= 3 -> mkUniqSet $ [ Reg ClassG32 i, RegSub SubL16 reg, RegSub SubL8 reg, RegSub SubL8H reg ] -- for esi, edi, esp, ebp | 4 <= i && i <= 7 -> mkUniqSet $ [ Reg ClassG32 i, RegSub SubL16 reg ] -- 16 bit subregs alias the whole reg RegSub SubL16 r@(Reg ClassG32 _) -> regAlias r -- 8 bit subregs alias the 32 and 16, but not the other 8 bit subreg RegSub SubL8 r@(Reg ClassG32 _) -> mkUniqSet $ [ r, RegSub SubL16 r, RegSub SubL8 r ] RegSub SubL8H r@(Reg ClassG32 _) -> mkUniqSet $ [ r, RegSub SubL16 r, RegSub SubL8H r ] -- fp Reg ClassF64 _ -> unitUniqSet reg _ -> error "regAlias: invalid register" -- | Optimised versions of RegColorBase.{worst, squeese} specific to x86 worst :: Int -> RegClass -> RegClass -> Int worst n classN classC = case classN of ClassG32 -> case classC of ClassG32 -> min n 8 ClassG16 -> min n 8 ClassG8 -> min n 4 ClassF64 -> 0 ClassG16 -> case classC of ClassG32 -> min n 8 ClassG16 -> min n 8 ClassG8 -> min n 4 ClassF64 -> 0 ClassG8 -> case classC of ClassG32 -> min (n*2) 8 ClassG16 -> min (n*2) 8 ClassG8 -> min n 8 ClassF64 -> 0 ClassF64 -> case classC of ClassF64 -> min n 6 _ -> 0 squeese :: RegClass -> [(Int, RegClass)] -> Int squeese classN countCs = sum (map (\(i, classC) -> worst i classN classC) countCs)
nomeata/ghc
compiler/nativeGen/RegAlloc/Graph/ArchX86.hs
bsd-3-clause
3,557
216
15
873
1,219
690
529
87
14
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Stack.UploadSpec (spec) where import RIO import RIO.Directory import RIO.FilePath ((</>)) import Stack.Upload import Test.Hspec import System.Permissions (osIsWindows) import System.PosixCompat.Files (getFileStatus, fileMode) import Data.Bits ((.&.)) spec :: Spec spec = do it "writeFilePrivate" $ example $ withSystemTempDirectory "writeFilePrivate" $ \dir -> replicateM_ 2 $ do let fp = dir </> "filename" contents :: IsString s => s contents = "These are the contents" writeFilePrivate fp contents actual <- readFileBinary fp actual `shouldBe` contents perms <- getPermissions fp perms `shouldBe` setOwnerWritable True (setOwnerReadable True emptyPermissions) unless osIsWindows $ do status <- getFileStatus fp (fileMode status .&. 0o777) `shouldBe` 0o600
juhp/stack
src/test/Stack/UploadSpec.hs
bsd-3-clause
897
0
18
167
250
132
118
25
1
----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology, 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- Classes for monad transformers. -- -- A monad transformer makes new monad out of an existing monad, such -- that computations of the old monad may be embedded in the new one. -- To construct a monad with a desired set of features, one typically -- starts with a base monad, such as @Identity@, @[]@ or 'IO', and -- applies a sequence of monad transformers. -- -- Most monad transformer modules include the special case of applying the -- transformer to @Identity@. For example, @State s@ is an abbreviation -- for @StateT s Identity@. -- -- Each monad transformer also comes with an operation @run@/XXX/ to -- unwrap the transformer, exposing a computation of the inner monad. ----------------------------------------------------------------------------- module Control.Monad.Trans ( module Control.Monad.Trans.Class, module Control.Monad.IO.Class ) where import Control.Monad.IO.Class import Control.Monad.Trans.Class
johanneshilden/principle
public/mtl-2.2.1/Control/Monad/Trans.hs
bsd-3-clause
1,329
0
5
226
65
54
11
5
0
module SDL.Raw.Power ( -- * Power Management Status getPowerInfo ) where import Control.Monad.IO.Class import Foreign.C.Types import Foreign.Ptr import SDL.Raw.Enum foreign import ccall "SDL.h SDL_GetPowerInfo" getPowerInfoFFI :: Ptr CInt -> Ptr CInt -> IO PowerState getPowerInfo :: MonadIO m => Ptr CInt -> Ptr CInt -> m PowerState getPowerInfo v1 v2 = liftIO $ getPowerInfoFFI v1 v2 {-# INLINE getPowerInfo #-}
Velro/sdl2
src/SDL/Raw/Power.hs
bsd-3-clause
421
0
8
67
115
62
53
10
1
import Test.Cabal.Prelude main = setupAndCabalTest $ do skipUnless =<< ghcVersionIs (>= mkVersion [7,9]) withDirectory "p" $ do r <- fails $ setup' "configure" ["--cabal-file", "p.cabal.fail-missing"] assertOutputContains "Missing" r
mydaum/cabal
cabal-testsuite/PackageTests/ReexportedModules/setup-fail-missing.test.hs
bsd-3-clause
258
0
14
52
79
39
40
6
1
{-# OPTIONS_GHC -Wall #-} module Completesig11 where data A = A | B {-# COMPLETE A, B #-} foo :: A -> () foo A = () foo B = () foo A = ()
ezyang/ghc
testsuite/tests/pmcheck/complete_sigs/completesig14.hs
bsd-3-clause
142
0
6
38
57
32
25
8
1
{-# LANGUAGE MagicHash #-} module LiteralsTest2 where x,y :: Int x = 0003 y = 0x04 s :: String s = "\x20" c :: Char c = '\x20' d :: Double d = 0.00 blah = x where charH = '\x41'# intH = 0004# wordH = 005## floatH = 3.20# doubleH = 04.16## -- int64H = 00456L# -- word64H = 00456L## x = 1
olsner/ghc
testsuite/tests/printer/Ppr038.hs
bsd-3-clause
326
0
6
103
91
57
34
18
1
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.Home where import Import getHomeR :: Handler Html getHomeR = do defaultLayout $ do setTitleI MsgHomeTitle $(widgetFile "homepage")
lulf/wishsys
Handler/Home.hs
mit
218
0
12
46
46
23
23
8
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE OverloadedStrings #-} module RenderHtml where import Data.String import Data.List (intersperse) import Control.Monad import Text.Blaze.Html5 (Html, (!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import qualified Data.Set as S import LinearProof import Syntax metaKindSpan :: String -> Html metaKindSpan = (H.span ! A.class_ "metakind") . fromString metaQuantifierSpan :: String -> Html metaQuantifierSpan = (H.span ! A.class_ "metaquantifier") . fromString varSpan :: String -> Html varSpan = (H.span ! A.class_ "var") . fromString termIntroSpan :: String -> Html termIntroSpan = (H.span ! A.class_ "termIntro") . fromString parSpan :: String -> Html parSpan = (H.span ! A.class_ "par") . fromString opSpan :: String -> Html opSpan = (H.span ! A.class_ "op") . fromString predSpan :: String -> Html predSpan = (H.span ! A.class_ "pred") . fromString holeSpan :: Html -> Html holeSpan = H.span ! A.class_ "hole" cdots :: Html cdots = H.span ! A.class_ "cdots" $ fromString "⋯" render :: OpenLineProof -> Html render l@(OpenLineProof hyps frags) = do let pclosed = H.p ! A.style "float: right;" if isClosedProof l then pclosed ! A.class_ "closed-indicator" $ "Proof is closed!" else pclosed ! A.class_ "open-indicator" $ "Proof contains holes and/or higher-order objects." let implicits = S.fromList [ x | b <- hyps, bindImplicit b, Just x <- [bindVar b] ] renderFrags implicits frags H.h2 $ fromString "Premise(s) and assumptions(s)" renderProofHypotheses hyps parens :: Html -> Html parens h = parSpan "(" >> h >> parSpan ")" renderFrags :: S.Set VarName -> [ProofFragment] -> Html renderFrags implicits frags = H.table ! A.class_ "boxproof" $ mapM_ (renderFrag 0 S.empty S.empty) frags where nboxcols = depth frags renderFrag d open close frag = let ocClass l = if S.member l open then "open" else if S.member l close then "close" else "" boxcols emptyLine rev l inner = forM_ ((if rev then reverse else id) [1 .. nboxcols]) $ \i -> let classes = unwords $ ["box"] ++ ["active" | or [i <= d && not (emptyLine && S.member l close) ,i < d] ] ++ [ocClass l | or [i >= d && not (emptyLine || rev) ,i > d && not emptyLine]] in H.td ! A.class_ (fromString classes) $ if i == d then inner else "" line l lineLabel varLabel concLabel refLabel = do H.tr $ do H.td ! A.class_ "line" $ fromString lineLabel boxcols False False l $ fromString varLabel H.td ! A.class_ (fromString $ unwords ["conc", ocClass l]) $ concLabel H.td ! A.class_ (fromString $ unwords ["rule", ocClass l]) $ refLabel boxcols False True l "" H.tr ! A.class_ "empty" $ do H.td ! A.class_ "line" $ " " boxcols True False l " " H.td ! A.class_ (fromString $ unwords ["conc"]) $ " " H.td ! A.class_ (fromString $ unwords ["rule"]) $ " " boxcols True True l " " in case frag of VarIntroduction l x -> line l (show l) x "" (renderReference implicits "var" []) Line l sq rule refs -> line l (show l) "" (renderSequent sq) (renderReference implicits rule refs) HoleLine l (ProofType bt) h _args | S.member h implicits -> line l (show l) "" (holeSpan $ renderSequent bt) (holeSpan $ fromString h) | otherwise -> line l (show l) "" (renderSequent bt) (fromString h) Box l1 l2 frags' -> let open' = S.insert l1 open close' = S.insert l2 close in mapM_ (renderFrag (d+1) open' close') frags' renderReference :: S.Set VarName -> String -> [LineRef] -> Html renderReference implicits rule refs = do let ruleTable = (map (\(x,y) -> (x, fromString y)) [ ("top_i", "⊤i"), ("con_i", "∧i"), ("con_e1", "∧e₁"), ("con_e2", "∧e₂") , ("dis_i1", "∨i₁"), ("dis_i2", "∨i₂"), ("dis_e","∨e"), ("imp_i","→i") , ("imp_e","→e"), ("neg_i","¬i"), ("neg_e","¬e"), ("bot_e","⊥e") , ("all_i","∀i"), ("all_e","∀e"), ("exi_i","∃i"), ("exi_e","∃e") , ("eq_i","=i"), ("eq_e","=e"), ("lem", "LEM"), ("nne", "¬¬e") , ("mt", "MT"), ("nni", "¬¬i"), ("pbc", "PBC") ]) ++ [("var", termIntroSpan "variable")] let renderLineRef r = case r of LineRefSingle l' -> fromString $ show l' LineRefMulti l1 l2 -> fromString $ concat [show l1, "-", show l2] LineRefHole h | S.member h implicits -> holeSpan $ fromString $ concat ["(",h,")"] | otherwise -> fromString $ concat ["(",h,")"] _ <- (maybe (fromString rule) id (lookup rule ruleTable)) _ <- fromString " " sequence_ (intersperse (fromString ", ") $ map renderLineRef refs) flag_renderAllHypotheses :: Bool flag_renderAllHypotheses = False -- Render a tabular representation of the full proof context, including implicit -- hypotheses. renderProofHypotheses :: [HypBinding] -> Html renderProofHypotheses hyps = H.table ! A.class_ "hypotheses" $ mapM_ renderHyp $ filter isVisible hyps where isVisible (HypBinding _ implicit typ) = or [flag_renderAllHypotheses ,implicit ,isJudgment typ ] renderHyp (HypBinding mx implicit typ) = H.tr $ do H.td $ (if implicit then holeSpan else id) $ fromString $ maybe "" id mx H.td $ maybe "" (const " : ") mx H.td $ renderObjType typ renderObjType :: ObjType -> Html renderObjType (TermTy c@(Open hyps' TermConst)) | all (isClosedTermTy . bindTy) hyps' = let arity = length hyps' in if arity == 0 then metaKindSpan "Constant" else metaKindSpan "Term" >> parens (fromString $ show arity) | otherwise = renderContextual (const (metaKindSpan "Term")) c renderObjType (PropTy c@(Open hyps' PropConst)) | all (isClosedTermTy . bindTy) hyps' = let arity = length hyps' in if arity == 0 then metaKindSpan "Proposition" else metaKindSpan "Predicate" >> parens (fromString $ show arity) | otherwise = renderContextual (const (metaKindSpan "Proposition")) c renderObjType (RefTy c) = renderContextual (\(RefType bt) -> {-metaKindSpan "Ref to " >>-} (renderSequent bt)) c renderObjType (SequentTy c) = renderContextual (const (metaKindSpan "Sequent")) c renderObjType (ProofTy c) = flip renderContextual c $ \(ProofType bt) -> metaKindSpan "Proof of " >> (renderSequent bt) renderContextual :: (a -> Html) -> Open a -> Html renderContextual f (Open [] a) = f a renderContextual f (Open bindings a) = do f a H.div ! A.class_ "context-separator" $ "with premise(s) and assumption(s)" H.div ! A.class_ "context" $ renderProofHypotheses bindings type Precedence = Int data Fixity = FixPrefix | FixInfix Assoc | FixPostfix deriving (Eq) data Assoc = AssocLeft | AssocRight | AssocNone deriving (Show, Eq) data Position = PosLeft | PosRight deriving (Show, Eq) type OpSpec = (Precedence, Fixity) type CtxHtml = (OpSpec, Html) par :: OpSpec -> Position -> CtxHtml -> Html par (pprec, pfix) cpos ((cprec, cfix), s) = if not isUnambiguous then parens s else s where isUnambiguous = (cprec > pprec) || and [cprec == pprec, cfix == pfix, posCompatible] posCompatible = case cfix of FixInfix AssocLeft -> cpos == PosLeft FixInfix AssocRight -> cpos == PosRight FixInfix AssocNone -> False _ -> True showInfixOp :: OpSpec -> Html -> CtxHtml -> CtxHtml -> CtxHtml showInfixOp spec op t1 t2 = (spec, par spec PosLeft t1 >> op >> par spec PosRight t2) showPrefixOp :: OpSpec -> Html -> CtxHtml -> CtxHtml showPrefixOp spec op t1 = (spec, op >> par spec PosRight t1) showConst :: Html -> CtxHtml showConst cnst = ((maxBound, FixPrefix), cnst) renderFormula :: Formula -> Html renderFormula phi = let (_, s) = go phi in s where go p = case p of Top -> showConst "⊤" Bot -> showConst "⊥" Conj p1 p2 -> showInfixOp (3, FixInfix AssocNone) (opSpan " ∧ ") (go p1) (go p2) Disj p1 p2 -> showInfixOp (3, FixInfix AssocNone) (opSpan " ∨ ") (go p1) (go p2) Imp p1 p2 -> showInfixOp (1, FixInfix AssocRight) (opSpan " → ") (go p1) (go p2) Neg p' -> showPrefixOp (5, FixPrefix) (opSpan "¬") (go p') Pred q ts -> showConst $ predSpan q >> objsListHtml ts Eq t1 t2 -> showConst $ renderTerm t1 >> predSpan " = " >> renderTerm t2 All x phi' -> showPrefixOp (4, FixPrefix) (opSpan "∀" >> varSpan x >> fromString " ") (go phi') Exi x phi' -> showPrefixOp (4, FixPrefix) (opSpan "∃" >> varSpan x >> fromString " ") (go phi') objsListHtml :: [Obj] -> Html objsListHtml ts = appList (map renderObj ts) -- Given a list [h1, ..., hn], renders nothing if n = 0 and otherwise renders -- the sequence enclosed in parameters and separated by commas. appList :: [Html] -> Html appList [] = return () appList hs = parSpan "(" >> sequence_ (intersperse (fromString ", ") hs) >> parSpan ")" renderObj :: Obj -> Html renderObj o = case o of ObjTerm (Open bs t) -> lam bs >> renderTerm t ObjProp (Open bs phi) -> lam bs >> renderFormula phi ObjRef (Open bs ref) -> lam bs >> renderRef ref ObjSequent (Open bs sq) -> lam bs >> renderSequent sq ObjProof (Open bs _pt) -> lam bs >> fromString "<proof term>" where lam [] = (return () :: Html) lam bs = do _ <- fromString "λ" let hs = map (fromString . maybe "_" id . bindVar) bs sequence_ $ intersperse (fromString ", ") hs fromString ". " renderRef :: Ref -> Html renderRef (RefApp x []) = varSpan x renderRef (RefApp x args) = varSpan x >> objsListHtml args renderTerm :: Term -> Html renderTerm (Var x) = varSpan x renderTerm (App f ts) = varSpan f >> objsListHtml ts renderSequent :: Sequent -> Html renderSequent (Sequent [] (Left (x, ys))) = varSpan x >> appList (map varSpan ys) renderSequent (Sequent [] (Right phi)) = renderFormula phi renderSequent (Sequent as c) = sequence_ (intersperse (fromString ", ") (map aux as)) >> case c of Left (x,ys) -> fromString "|" >> varSpan x >> appList (map varSpan ys) Right phi -> fromString " ⊢ " >> renderFormula phi where aux (Left x) = varSpan x >> fromString ":" >> metaKindSpan "Term" aux (Right phi) = renderFormula phi ---- Render a compact representation of an open object, excluding implicit ---- hypotheses. renderOpen :: (a -> Html) -> Open a -> Html renderOpen f (Open hyps a) = quantification >> derivations >> rest where explicitHyps = filter (not . bindImplicit) hyps (subjects, hyps') = span (\h -> isSubject (bindTy h)) explicitHyps (judgments, hyps'') = span (\h -> isJudgment (bindTy h)) hyps' quantification | null subjects || null judgments = return () | otherwise = do metaQuantifierSpan "for all " mapM_ subj subjects fromString ", " derivations | null judgments = return () | otherwise = do --metaQuantifierSpan "using " mapM_ judg judgments cdots rest | null hyps'' = f a | otherwise = renderOpen f (Open hyps'' a) subj (HypBinding Nothing _ _) = return () subj (HypBinding (Just x) _ ty) = case ty of TermTy (Open hs TermConst) -> do varSpan x H.sup . fromString $ concat ["(",show $ length hs,")"] fromString " " PropTy (Open hs PropConst) -> do varSpan x when (not . null $ hs) $ H.sup . fromString $ concat ["(",show $ length hs,")"] fromString " " -- We don't really know how to render explicit quantification of sequents. -- Use cases are also quite limited. SequentTy (Open _hs SequentConst) -> return () -- Remaining cases shouldn't happen _ -> return () judg (HypBinding _ _ ty) = case ty of ProofTy (Open hs (ProofType sq)) -> parens (renderOpen renderSequent (Open hs sq)) >> fromString " " RefTy (Open hs (RefType sq)) -> parens (renderOpen renderSequent (Open hs sq)) >> fromString " " -- Remaining cases should not happen _ -> return () isSubject :: ObjType -> Bool isSubject (PropTy _) = True isSubject (TermTy _) = True isSubject (SequentTy _) = True isSubject (RefTy _) = False isSubject (ProofTy _) = False isJudgment :: ObjType -> Bool isJudgment = not . isSubject
ulrikrasmussen/BoxProver
src/RenderHtml.hs
mit
13,283
0
28
3,873
4,790
2,401
2,389
274
10
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} import Data.OpenUnion type MyUnion = Union '[Char, Int, [()]] showMyUnion :: MyUnion -> String showMyUnion = (\(c :: Char) -> "char: " ++ show c) @> (\(i :: Int) -> "int: " ++ show i) @> (\(l :: [()]) -> "list length: " ++ show (length l)) @> (\(s :: String) -> "string: " ++ s) -- MyUnion doesn't contain String. That's fine. @> typesExhausted main :: IO () main = do putStrLn $ showMyUnion $ liftUnion (4 :: Int) putStrLn $ showMyUnion $ liftUnion 'a' putStrLn $ showMyUnion $ liftUnion [(), ()]
rimmington/open-union
example.hs
mit
598
0
13
137
233
126
107
16
1
{-# LANGUAGE ScopedTypeVariables #-} import System.IO (stderr, hPrint, hPutStrLn) import qualified Vision.Image as I import Vision.Image.Storage.DevIL (Autodetect (..), load, save) import Options.Applicative (header, progDesc, Parser, argument, option, str, metavar, long, eitherReader, value, short, help, showDefaultWith, (<>), execParser, info, helper, fullDesc) description = progDesc "Removes all but one colors" header' = header "KeepOneColor" yellow = I.RGBPixel 255 255 0 black = I.RGBPixel 0 0 0 white = I.RGBPixel 255 255 255 data Param = Param { fileIn :: String, fileOut :: String, colorToKeep :: I.RGBPixel, bgColor :: I.RGBPixel, replaceColor :: I.RGBPixel } readRGB :: String -> Either String I.RGBPixel readRGB s = case tripple of [((a, b, c), "")] | valid [a, b, c] -> Right (I.RGBPixel (f a) (f b) (f c)) | otherwise -> Left "all numbers between 0 and 255" _ -> Left "e.g. (2, 4, 5)" where valid = all (\a -> 0 <= a && a <= 255) tripple = reads s :: [((Int, Int, Int), String)] f = fromIntegral showRGB :: I.RGBPixel -> String showRGB a = "(" ++ show (I.rgbRed a) ++ ", " ++ show (I.rgbGreen a) ++ ", " ++ show (I.rgbBlue a) ++ ")" argparser :: Parser Param argparser = Param <$> argument str (metavar "INPUT") <*> argument str (metavar "OUTPUT") <*> option (eitherReader readRGB) (long "keep" <> short 'k' <> help "rgb of a color to keep" <> metavar "(R, G, B)" <> value yellow <> showDefaultWith showRGB) <*> option (eitherReader readRGB) (long "background" <> short 'b' <> help "rgb of the background color" <> metavar "(R, G, B)" <> value white <> showDefaultWith showRGB) <*> option (eitherReader readRGB) (long "replace" <> short 'r' <> help "rgb of a replacement color" <> metavar "(R, G, B)" <> value black <> showDefaultWith showRGB) main :: IO () main = execParser opts >>= runWithOptions where opts = info (helper <*> argparser) (fullDesc <> description <> header') runWithOptions :: Param -> IO () runWithOptions opts = do io <- load Autodetect (fileIn opts) case io of Left err -> do hPutStrLn stderr "Unable to load image:" hPrint stderr err Right (rgb :: I.RGB) -> do mErr <- save Autodetect (fileOut opts) (I.map (processPixels opts) rgb :: I.RGB) case mErr of Nothing -> return () Just err -> do hPutStrLn stderr "Unable to save the image:" hPrint stderr err processPixels :: Param -> I.RGBPixel -> I.RGBPixel processPixels opts p = if p == colorToKeep opts then replaceColor opts else bgColor opts
afiodorov/keepOneColor
Main.hs
mit
2,944
0
17
917
963
494
469
71
3
module GitHub.Git.References where import GitHub.Internal refs o r = ownerRepo o r <> "/git/refs" ref o r r' = refs o r <> "/" <> r' --| GET /repos/:owner/:repo/git/refs/:ref getReference :: OwnerName -> RepoName -> Ref -> GitHub ReferenceData getReference o r r' = get [] $ ref o r r' --| GET /repos/:owner/:repo/git/refs getAllReferences :: OwnerName -> RepoName -> GitHub ReferencesData getAllReferences o r = get [] $ refs o r --| POST /repos/:owner/:repo/git/refs createReference :: OwnerName -> RepoName -> NewRef -> GitHub ReferenceData createReference o r = post [] $ refs o r --| PATCH /repos/:owner/:repo/git/refs/:ref updateReference :: OwnerName -> RepoName -> RefPatch -> GitHub ReferenceData updateReference o r r' = patch [] $ ref o r r' --| DELETE /repos/:owner/:repo/git/refs/:ref deleteReference :: OwnerName -> RepoName -> Ref -> GitHub () deleteReference o r r' = delete [] $ ref o r r'
SaneApp/github-api
src/GitHub/Git/References.hs
mit
933
38
12
171
481
234
247
-1
-1
import Trace (traceJS) import System.Environment (getArgs) main :: IO () main = getArgs >>= readFile . head >>= putStrLn . traceJS
heyLu/tracing-js
Main.hs
mit
132
0
8
22
50
27
23
4
1
-- ghc interactive_script.hs -o i -- echo "10 10 10" | ./i main :: IO () main = interact ( (\finalOutput -> finalOutput ++ "\n") . show . sum . map read . words)
raventid/coursera_learning
haskell/interactive_script.hs
mit
163
0
13
35
55
29
26
2
1
module Main where import Monad import System.Environment import Text.ParserCombinators.Parsec hiding (spaces) main :: IO () main = do args <- getArgs putStrLn (readExpr (args !! 0)) symbol :: Parser Char symbol = oneOf "!$%&|*+-/:<=>?@^_~#" readExpr input = case parse parseExpr "lisp" input of Left err -> "No match: " ++ show err Right val -> "Found value" spaces :: Parser () spaces = skipMany1 space data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Integer | String String | Bool Bool parseString :: Parser LispVal parseString = do char '"' x <- many (noneOf "\"") char '"' return $ String x parseAtom :: Parser LispVal parseAtom = do first <- letter <|> symbol rest <- many (letter <|> digit <|> symbol) let atom = [first] ++ rest return $ case atom of "#t" -> Bool True "#f" -> Bool False otherwise -> Atom atom parseNumber :: Parser LispVal parseNumber = liftM (Number . read) $ many1 digit parseExpr :: Parser LispVal parseExpr = parseAtom <|> parseString <|> parseNumber
tismith/tlisp
write-yourself-a-scheme/listings/listing3.3.hs
mit
1,299
0
11
457
386
193
193
39
3
{-# LANGUAGE OverloadedStrings #-} import BT.Global import BT.Mining import BT.User import qualified Data.ByteString.Char8 as BC import System.Environment (getArgs) import Control.Monad (liftM) import Control.Exception (catch) import BT.Util (elogCatch) main :: IO () main = do conn <- makeCons username <- liftM (BC.pack . head) getArgs BC.putStrLn username _ <- catch (do share <- getCurrentMiningShare conn username _ <- incrementUserBalance conn username 1.0 _ <- incrementUnconfirmedBalance conn username 1.0 _ <- incrementSharePayout conn share 1.0 return Nothing) elogCatch return ()
c00w/BitToll
haskell/MineUserTest.hs
mit
656
0
13
143
200
100
100
21
1
-- Problem 6 -- (*) Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x). -- -- > isPalindrome "madamimadam" -- True isPalindrome :: Eq a => [a] -> Bool isPalindrome [] = True isPalindrome [x] = True isPalindrome xs = (head xs == last xs) && isPalindrome (tail $ init xs)
usami-k/H-99-Ninety-Nine-Haskell-Problems
01-10/06.hs
mit
326
0
9
67
84
44
40
4
1
module Main where import Game (Game, Position, Coordinate, move, isFinished, start, bounds, marks) import Opponent (randomMove) import Control.Monad (join) import Data.Maybe (fromJust, isJust) import System.IO (hFlush, stdout) import Text.Read (readMaybe) main :: IO () main = putDoubleLine >> getTurns >>= \turns -> putDoubleLine >> untilM2 isFinished turns start >>= print >> pure () type Turn = Game -> IO Game data PlayerType = H | C deriving Read getTurns :: IO (Turn, Turn) getTurns = putStrLn "(H)uman or\n(C)omputer?" >> (,) <$> getTurn (fst marks) <*> getTurn (snd marks) getTurn :: String -> IO Turn getTurn m = getInput (turn . fromJust) isJust ("Player " ++ m) turn :: PlayerType -> Turn turn H = takeTurn turn C = randomTurn takeTurn :: Turn takeTurn game = untilM (/= game) tryTurn game tryTurn :: Turn tryTurn game = print game >> getPosition >>= \pos -> putDoubleLine >> pure (game >>= move pos) randomTurn :: Turn randomTurn game = print game >> putDoubleLine >> either (pure . Left) randomMove game getPosition :: IO Position getPosition = (,) <$> getCoord "ROW" <*> getCoord "COLUMN" getCoord :: String -> IO Coordinate getCoord = getInput fromJust isCoord isCoord :: Maybe Coordinate -> Bool isCoord (Just c) = c `elem` bounds isCoord _ = False getInput :: Read a => (Maybe a -> b) -> (Maybe a -> Bool) -> String -> IO b getInput t c p = t <$> untilM c (const $ promptLine p) Nothing promptLine :: Read a => String -> IO (Maybe a) promptLine p = prompt p >> fmap readMaybe getLine prompt :: String -> IO () prompt p = putStr (padRight 8 (p ++ ": ")) >> hFlush stdout padRight :: Int -> String -> String padRight n s = s ++ replicate (n - length s) ' ' putDoubleLine :: IO () putDoubleLine = putStrLn "\n" untilM2 :: Monad m => (a -> Bool) -> (a -> m a, a -> m a) -> a -> m a untilM2 p (k, l) x | p x = pure x | otherwise = k x >>= untilM2 p (l, k) untilM :: Monad m => (a -> Bool) -> (a -> m a) -> a -> m a untilM p = untilM2 p . join (,)
amar47shah/NICTA-TicTacToe
app/Main.hs
mit
2,077
0
11
494
894
459
435
62
1
module Object ( Object(..), Value(..), call, genObject, genNilObject, genIntObject, genStringObject, genBoolObject, genFunctionObject ) where import AST import qualified Data.Map as Map type Env = Map.Map String Object data Value = IntValue Integer | StringValue String | BoolValue Bool | ArrayValue [Object] | ASTValue [String] AST | EmptyValue deriving (Show) -- Object -- data Object = Object {klass :: String, value :: Value, methods :: Map.Map String (Object -> [Object] -> Object)} | Return Object instance Show Object where show obj = string where stringObj = call obj "to_s" [] StringValue string = value stringObj genObject = Object {klass = "Object", value = EmptyValue, methods = objMethod} where objMethod = Map.fromList [ ("to_s", toSObject), ("true?", toBObject) ] call :: Object -> String -> [Object] -> Object call callie caller args = case looked of Just method -> method callie args Nothing -> error $ "can not find method " ++ caller where looked = Map.lookup caller $ methods callie toSObject :: Object -> [Object] -> Object toSObject self _ = genStringObject $ "#<" ++ (klass self) ++ ">" toBObject :: Object -> [Object] -> Object toBObject _ _ = genBoolObject True -- nil -- genNilObject = Object {klass = "nil", value = EmptyValue, methods = nilMethod} where obj = genObject overrides = Map.fromList [ ("to_s", toSNil), ("true?", toBNil) ] nilMethod = Map.union overrides $ methods obj toSNil :: Object -> [Object] -> Object toSNil _ _ = genStringObject "nil" toBNil :: Object -> [Object] -> Object toBNil _ _ = genBoolObject False -- Int -- genIntObject :: Integer -> Object genIntObject n = Object {klass = "Int", value = IntValue n, methods = intMethod} where obj = genObject overrides = Map.fromList [ ("to_s", toSInt), ("==", eqInt), ("+", addInt), ("-", subInt), ("*", mulInt), ("/", divInt), (">", gtInt), ("<", ltInt), (">=", agtInt), ("<=", altInt), ("true?", toBInt) ] intMethod = Map.union overrides $ methods obj toSInt :: Object -> [Object] -> Object toSInt self _ = genStringObject $ show n where IntValue n = value self eqInt :: Object -> [Object] -> Object eqInt self [right] = genBoolObject b where b = intBoolOp (==) (value self) (value right) addInt :: Object -> [Object] -> Object addInt self [right] = genIntObject n where n = intBinOp (+) (value self) (value right) subInt :: Object -> [Object] -> Object subInt self [right] = genIntObject n where n = intBinOp (-) (value self) (value right) mulInt :: Object -> [Object] -> Object mulInt self [right] = genIntObject n where n = intBinOp (*) (value self) (value right) divInt :: Object -> [Object] -> Object divInt self [right] = genIntObject n where n = intBinOp (div) (value self) (value right) gtInt :: Object -> [Object] -> Object gtInt self [right] = genBoolObject b where b = intBoolOp (>) (value self) (value right) ltInt :: Object -> [Object] -> Object ltInt self [right] = genBoolObject b where b = intBoolOp (<) (value self) (value right) agtInt :: Object -> [Object] -> Object agtInt self [right] = genBoolObject b where b = intBoolOp (>=) (value self) (value right) altInt :: Object -> [Object] -> Object altInt self [right] = genBoolObject b where b = intBoolOp (<=) (value self) (value right) intBinOp f (IntValue x) (IntValue y) = f x y intBinOp _ _ _ = error "can not add" intBoolOp f (IntValue x) (IntValue y) = f x y intBoolOp _ _ _ = error "can not add" toBInt :: Object -> [Object] -> Object toBInt self _ = genBoolObject $ n /= 0 where IntValue n = value self -- String -- genStringObject :: String -> Object genStringObject s = Object {klass = "String", value = StringValue s, methods = stringMethod} where obj = genObject overrides = Map.fromList [ ("to_s", toSString), ("true?", toBString) ] stringMethod = Map.union overrides $ methods obj toSString :: Object -> [Object] -> Object toSString self _ = self toBString :: Object -> [Object] -> Object toBString self _ = genBoolObject $ s /= "" where StringValue s = value self -- Bool -- genBoolObject :: Bool -> Object genBoolObject b = Object {klass = "Bool", value = BoolValue b, methods = boolMethod} where obj = genObject overrides = Map.fromList [ ("to_s", toSBool), ("true?", toBBool) ] boolMethod = Map.union overrides $ methods obj toSBool :: Object -> [Object] -> Object toSBool self _ = if val then trueString else falseString where BoolValue val = value self trueString = genStringObject "true" falseString = genStringObject "false" toBBool :: Object -> [Object] -> Object toBBool self _ = self -- Function -- genFunctionObject :: [String] -> AST -> Object genFunctionObject args ast = Object {klass = "Function", value = ASTValue args ast, methods = functionMethod} where obj = genObject overrides = Map.fromList [ ("to_s", toSFunction), ("call", callFunction), ("true?", toBFunction) ] functionMethod = Map.union overrides $ methods obj toSFunction :: Object -> [Object] -> Object toSFunction self _ = genStringObject $ klass self callFunction :: Object -> [Object] -> Object callFunction self args = self toBFunction :: Object -> [Object] -> Object toBFunction _ _ = genBoolObject True
NKMR6194/carrot
src/Object.hs
mit
5,675
0
13
1,447
2,006
1,099
907
142
2
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude, GeneralizedNewtypeDeriving, DeriveGeneric #-} {-# LANGUAGE RecordWildCards, TypeFamilies,DeriveDataTypeable,ScopedTypeVariables #-} {-# LANGUAGE ConstraintKinds #-} {-| This module defines the types used in the Template haskell routine in order to automate the creation of a higher level set of access functions to the Atomic Data in SimpleStore State. Most notably, it allows datatypes that look like Keyed vectors to make changes without write locking above the Key Level This is very important when writing to Time Series Data. |-} module SimpleStore.Cell.Types (StoreCellError(..) , CellKey (..) , CellKeyStore (..) , SimpleCell (..) , CellCore (..) , FileKey (..) , SimpleCellState (..) , Cell (..) , CellStateConstraint , CellConstraint ) where -- System import Filesystem.Path.CurrentOS hiding (root) -- Controls import CorePrelude hiding (try,catch, finally,FilePath) import Control.Concurrent.STM -- Typeclasses import GHC.Generics -- Component Libraries import DirectedKeys.Types -- Containers -- import qualified Data.Map.Strict as M import qualified STMContainers.Map as M import qualified Data.Set as S -- Strings /Monomorphs import SimpleStore import Data.Aeson import Data.Aeson.Serialize import Data.Serialize -- | 'CellKey' declares two functions, -- 'getKey' which is supposed to take a SimpleStore Value and return a 'DirectedKeyRaw' -- 'makeFilename' which takes a directed key and returns text. -- you could use 'parseFilename' which escapes all the characters with valid unix ones -- or you can write your own, but it is very important that they are invertable! -- so be careful -- | 'CellKey' enforces no guarantees on your filenames, this is done because -- we want to keep the libraries light and portable but it means you need to add these -- guarantees on your functions data CellKey k src dst tm st = CellKey { getKey :: st -> (DirectedKeyRaw k src dst tm) , codeCellKeyFilename :: (DirectedKeyRaw k src dst tm) -> Text , decodeCellKeyFilename :: Text -> Either Text (DirectedKeyRaw k src dst tm) } -- | the codeCellKeyFilename actually will be used to make these file keys but -- I figure why not just make it where you can pass a Text generator. newtype FileKey = FileKey { getFileKey :: Text} deriving (Show,Generic,Ord,Eq) instance ToJSON FileKey where instance FromJSON FileKey where instance Serialize FileKey where get = getFromJSON put = putToJSON -- |'CellCoreLive' and 'CellCoreDormant' both define maps to acid states -- Live means currently loaded into memory -- Dormant means currently not loaded data CellCore k src dst tm tvlive stdormant = CellCore { ccLive :: ((M.Map (DirectedKeyRaw k src dst tm) tvlive )) ,ccDormant :: stdormant } newtype CellKeyStore = CellKeyStore { getCellKeyStore :: (S.Set FileKey)} deriving (Show,Generic) instance ToJSON CellKeyStore where instance FromJSON CellKeyStore where instance Serialize CellKeyStore where get = getFromJSON put = putToJSON -- | Transactional Cell Core -- Transactional Cell Core is where both the map to live acidstates are stored and the map for -- dormant filenames type TCellCore k src dst tm stlive stdormant = (CellCore k src dst tm stlive stdormant) data SimpleCell k src dst tm stlive stdormant = SimpleCell { cellCore :: !(TCellCore k src dst tm (SimpleStore stlive) stdormant ) , cellKey :: !(CellKey k src dst tm stlive) , cellParentFP :: !FilePath -- /root/otherstuff/parentofopenlocalstatefromdir , cellRootFP :: !FilePath -- /root/otherstuff/parentofopenlocalstatefromdir/openLocalStateFromdir } deriving (Typeable,Generic) data StoreCellError = InsertFail !Text | DeleteFail !Text | StateNotFound !Text -- | To create an instance of SimpleCellState one must provide a CellKey class SimpleCellState st where type SimpleCellKey st type SimpleCellSrc st type SimpleCellDst st type SimpleCellDateTime st simpleCellKey :: CellKey (SimpleCellKey st) (SimpleCellSrc st) (SimpleCellDst st) (SimpleCellDateTime st) st type CellStateConstraint k src dst tm st = (Ord k , Hashable k , Ord src, Hashable src, Ord dst, Hashable dst, Ord tm , Hashable tm , SimpleCellState st, k ~ SimpleCellKey st, src ~ SimpleCellSrc st, dst ~ SimpleCellDst st, tm ~ SimpleCellDateTime st, Serialize st) -- | Interface to a Cell class Cell c where type CellLiveStateType c type CellDormantStateType c insertStore :: (CellLiveStateType c ~ st, CellStateConstraint k src dst tm st) => c -> st -> IO (Either StoreError (SimpleStore st)) getStore :: (CellLiveStateType c ~ st, CellStateConstraint k src dst tm st) => c -> st -> IO (Maybe (SimpleStore st)) updateStore :: (CellLiveStateType c ~ st, CellStateConstraint k src dst tm st) => c -> SimpleStore st -> st -> IO () deleteStore :: (CellLiveStateType c ~ st, CellStateConstraint k src dst tm st) => c -> st -> IO () type CellConstraint k src dst tm st c = (Cell c, CellLiveStateType c ~ st, CellStateConstraint k src dst tm st)
plow-technologies/simple-cell-types
src/SimpleStore/Cell/Types.hs
mit
5,847
0
14
1,681
1,041
606
435
101
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-tags.html module Stratosphere.ResourceProperties.AutoScalingAutoScalingGroupTagProperty where import Stratosphere.ResourceImports -- | Full data type definition for AutoScalingAutoScalingGroupTagProperty. See -- 'autoScalingAutoScalingGroupTagProperty' for a more convenient -- constructor. data AutoScalingAutoScalingGroupTagProperty = AutoScalingAutoScalingGroupTagProperty { _autoScalingAutoScalingGroupTagPropertyKey :: Val Text , _autoScalingAutoScalingGroupTagPropertyPropagateAtLaunch :: Val Bool , _autoScalingAutoScalingGroupTagPropertyValue :: Val Text } deriving (Show, Eq) instance ToJSON AutoScalingAutoScalingGroupTagProperty where toJSON AutoScalingAutoScalingGroupTagProperty{..} = object $ catMaybes [ (Just . ("Key",) . toJSON) _autoScalingAutoScalingGroupTagPropertyKey , (Just . ("PropagateAtLaunch",) . toJSON) _autoScalingAutoScalingGroupTagPropertyPropagateAtLaunch , (Just . ("Value",) . toJSON) _autoScalingAutoScalingGroupTagPropertyValue ] -- | Constructor for 'AutoScalingAutoScalingGroupTagProperty' containing -- required fields as arguments. autoScalingAutoScalingGroupTagProperty :: Val Text -- ^ 'asasgtpKey' -> Val Bool -- ^ 'asasgtpPropagateAtLaunch' -> Val Text -- ^ 'asasgtpValue' -> AutoScalingAutoScalingGroupTagProperty autoScalingAutoScalingGroupTagProperty keyarg propagateAtLauncharg valuearg = AutoScalingAutoScalingGroupTagProperty { _autoScalingAutoScalingGroupTagPropertyKey = keyarg , _autoScalingAutoScalingGroupTagPropertyPropagateAtLaunch = propagateAtLauncharg , _autoScalingAutoScalingGroupTagPropertyValue = valuearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-tags.html#cfn-as-tags-Key asasgtpKey :: Lens' AutoScalingAutoScalingGroupTagProperty (Val Text) asasgtpKey = lens _autoScalingAutoScalingGroupTagPropertyKey (\s a -> s { _autoScalingAutoScalingGroupTagPropertyKey = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-tags.html#cfn-as-tags-PropagateAtLaunch asasgtpPropagateAtLaunch :: Lens' AutoScalingAutoScalingGroupTagProperty (Val Bool) asasgtpPropagateAtLaunch = lens _autoScalingAutoScalingGroupTagPropertyPropagateAtLaunch (\s a -> s { _autoScalingAutoScalingGroupTagPropertyPropagateAtLaunch = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-tags.html#cfn-as-tags-Value asasgtpValue :: Lens' AutoScalingAutoScalingGroupTagProperty (Val Text) asasgtpValue = lens _autoScalingAutoScalingGroupTagPropertyValue (\s a -> s { _autoScalingAutoScalingGroupTagPropertyValue = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/AutoScalingAutoScalingGroupTagProperty.hs
mit
2,844
0
13
277
357
203
154
35
1
{- Copyright (C) 2012 John MacFarlane <jgm@berkeley.edu> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Functions for writing a parsed formula as OMML. -} module Text.TeXMath.Writers.OMML (writeOMML) where import Text.XML.Light import Text.TeXMath.Types import Data.Generics (everywhere, mkT) -- | Transforms an expression tree to an OMML XML Tree writeOMML :: DisplayType -> [Exp] -> Element writeOMML dt = container . concatMap (showExp (setProps TextNormal)) . everywhere (mkT $ handleDownup dt) where container = case dt of DisplayBlock -> \x -> mnode "oMathPara" [ mnode "oMathParaPr" $ mnodeA "jc" "center" () , mnode "oMath" x ] DisplayInline -> mnode "oMath" mnode :: Node t => String -> t -> Element mnode s = node (QName s Nothing (Just "m")) mnodeA :: Node t => String -> String -> t -> Element mnodeA s v = add_attr (Attr (QName "val" Nothing (Just "m")) v) . mnode s str :: [Element] -> String -> Element str props s = mnode "r" [ mnode "rPr" props , mnode "t" s ] showFraction :: [Element] -> FractionType -> Exp -> Exp -> Element showFraction props ft x y = case ft of NormalFrac -> mnode "f" [ mnode "fPr" $ mnodeA "type" "bar" () , mnode "num" x' , mnode "den" y'] DisplayFrac -> showFraction props NormalFrac x y InlineFrac -> mnode "f" [ mnode "fPr" $ mnodeA "type" "lin" () , mnode "num" x' , mnode "den" y'] NoLineFrac -> mnode "f" [ mnode "fPr" $ mnodeA "type" "noBar" () , mnode "num" x' , mnode "den" y' ] where x' = showExp props x y' = showExp props y makeArray :: [Element] -> [Alignment] -> [ArrayLine] -> Element makeArray props as rs = mnode "m" $ mProps : map toMr rs where mProps = mnode "mPr" [ mnodeA "baseJc" "center" () , mnodeA "plcHide" "on" () , mnode "mcs" $ map toMc as' ] as' = take (length rs) $ as ++ cycle [AlignDefault] toMr r = mnode "mr" $ map (mnode "e" . concatMap (showExp props)) r toMc a = mnode "mc" $ mnode "mcPr" $ mnodeA "mcJc" (toAlign a) () toAlign AlignLeft = "left" toAlign AlignRight = "right" toAlign AlignCenter = "center" toAlign AlignDefault = "left" makeText :: TextType -> String -> Element makeText a s = str (setProps a) s setProps :: TextType -> [Element] setProps tt = case tt of TextNormal -> [sty "p"] TextBold -> [sty "b"] TextItalic -> [sty "i"] TextMonospace -> [sty "p", scr "monospace"] TextSansSerif -> [sty "p", scr "sans-serif"] TextDoubleStruck -> [sty "p", scr "double-struck"] TextScript -> [sty "p", scr "script"] TextFraktur -> [sty "p", scr "fraktur"] TextBoldItalic -> [sty "i"] TextSansSerifBold -> [sty "b", scr "sans-serif"] TextBoldScript -> [sty "b", scr "script"] TextBoldFraktur -> [sty "b", scr "fraktur"] TextSansSerifItalic -> [sty "i", scr "sans-serif"] TextSansSerifBoldItalic -> [sty "bi", scr "sans-serif"] where sty x = mnodeA "sty" x () scr x = mnodeA "scr" x () handleDownup :: DisplayType -> [Exp] -> [Exp] handleDownup dt (exp' : xs) = case exp' of EOver convertible x y | isNary x -> EGrouped [EUnderover convertible x y emptyGroup, next] : rest | convertible && dt == DisplayInline -> ESuper x y : xs EUnder convertible x y | isNary x -> EGrouped [EUnderover convertible x emptyGroup y, next] : rest | convertible && dt == DisplayInline -> ESub x y : xs EUnderover convertible x y z | isNary x -> EGrouped [EUnderover convertible x y z, next] : rest | convertible && dt == DisplayInline -> ESubsup x y z : xs ESub x y | isNary x -> EGrouped [ESubsup x y emptyGroup, next] : rest ESuper x y | isNary x -> EGrouped [ESubsup x emptyGroup y, next] : rest ESubsup x y z | isNary x -> EGrouped [ESubsup x y z, next] : rest _ -> exp' : next : rest where (next, rest) = case xs of (t:ts) -> (t,ts) [] -> (emptyGroup, []) emptyGroup = EGrouped [] handleDownup _ [] = [] showExp :: [Element] -> Exp -> [Element] showExp props e = case e of ENumber x -> [str props x] EGrouped [EUnderover _ (ESymbol Op s) y z, w] -> [makeNary props "undOvr" s y z w] EGrouped [ESubsup (ESymbol Op s) y z, w] -> [makeNary props "subSup" s y z w] EGrouped xs -> concatMap (showExp props) xs EDelimited start end xs -> [mnode "d" [ mnode "dPr" [ mnodeA "begChr" start () , mnodeA "endChr" end () , mnode "grow" () ] , mnode "e" $ concatMap (either ((:[]) . str props) (showExp props)) xs ] ] EIdentifier x -> [str props x] EMathOperator x -> [makeText TextNormal x] -- TODO revisit, use props? ESymbol _ x -> [str props x] ESpace n | n > 0 && n <= 0.17 -> [str props "\x2009"] | n > 0.17 && n <= 0.23 -> [str props "\x2005"] | n > 0.23 && n <= 0.28 -> [str props "\x2004"] | n > 0.28 && n <= 0.5 -> [str props "\x2004"] | n > 0.5 && n <= 1.8 -> [str props "\x2001"] | n > 1.8 -> [str props "\x2001\x2001"] | otherwise -> [] -- this is how the xslt sheet handles all spaces EUnder _ x (ESymbol Accent [c]) | isBarChar c -> [mnode "bar" [ mnode "barPr" $ mnodeA "pos" "bot" () , mnode "e" $ showExp props x ]] EOver _ x (ESymbol Accent [c]) | isBarChar c -> [mnode "bar" [ mnode "barPr" $ mnodeA "pos" "top" () , mnode "e" $ showExp props x ]] EOver _ x (ESymbol Accent y) -> [mnode "acc" [ mnode "accPr" $ mnodeA "chr" y () , mnode "e" $ showExp props x ]] ESub x y -> [mnode "sSub" [ mnode "e" $ showExp props x , mnode "sub" $ showExp props y]] ESuper x y -> [mnode "sSup" [ mnode "e" $ showExp props x , mnode "sup" $ showExp props y]] ESubsup x y z -> [mnode "sSubSup" [ mnode "e" $ showExp props x , mnode "sub" $ showExp props y , mnode "sup" $ showExp props z]] EUnder _ x y -> [mnode "limLow" [ mnode "e" $ showExp props x , mnode "lim" $ showExp props y]] EOver _ x y -> [mnode "limUpp" [ mnode "e" $ showExp props x , mnode "lim" $ showExp props y]] EUnderover c x y z -> showExp props (EUnder c x (EOver c y z)) ESqrt x -> [mnode "rad" [ mnode "radPr" $ mnodeA "degHide" "on" () , mnode "deg" () , mnode "e" $ showExp props x]] ERoot i x -> [mnode "rad" [ mnode "radPr" $ mnodeA "degHide" "on" () , mnode "deg" $ showExp props i , mnode "e" $ showExp props x]] EFraction ft x y -> [showFraction props ft x y] EPhantom x -> [mnode "phant" [ mnode "phantPr" [ mnodeA "show" "0" () ] , mnode "e" $ showExp props x]] EBoxed x -> [mnode "borderBox" [ mnode "e" $ showExp props x]] EScaled _ x -> showExp props x -- no support for scaler? EArray as ls -> [makeArray props as ls] EText a s -> [makeText a s] EStyled a es -> concatMap (showExp (setProps a)) es isBarChar :: Char -> Bool isBarChar c = c == '\x203E' || c == '\x00AF' isNary :: Exp -> Bool isNary (ESymbol Op _) = True isNary _ = False makeNary :: [Element] -> String -> String -> Exp -> Exp -> Exp -> Element makeNary props t s y z w = mnode "nary" [ mnode "naryPr" [ mnodeA "chr" s () , mnodeA "limLoc" t () , mnodeA "supHide" (if y == EGrouped [] then "on" else "off") () , mnodeA "supHide" (if y == EGrouped [] then "on" else "off") () ] , mnode "e" $ showExp props w , mnode "sub" $ showExp props y , mnode "sup" $ showExp props z ]
timtylin/scholdoc-texmath
src/Text/TeXMath/Writers/OMML.hs
gpl-2.0
10,068
0
18
4,084
3,183
1,556
1,627
184
27
-- Check that the agent's observation is intuitively correct. module T where import Tests.KBPBasis kbpt = kTest ("kbp" `knows_hat` "bit") kbp = agent "kbp" kbpt c = proc () -> do boot <- delayAC falseA trueA -< () bit <- nondetBitA -< () obs <- andA -< (boot, bit) probeA "bit" -< bit probeA "out" <<< kbp -< obs -- Synthesis using the clock semantics Just (_kautos_clk, mclk, _) = clockSynth MinNone c ctlM_clk = mkCTLModel mclk -- Synthesis using the SPR semantics Just (_kautos_spr, mspr, _) = singleSPRSynth MinNone c ctlM_spr = mkCTLModel mspr -- In branching time, the bit could always go either way. test_clock_bit_alternates = isOK (mc ctlM_clk (ag (ex (probe "bit") /\ ex (neg (probe "bit"))))) test_spr_bit_alternates = isOK (mc ctlM_spr (ag (ex (probe "bit") /\ ex (neg (probe "bit"))))) -- Initially the agent does not the bit. test_clock_knows_init = isOK (mc ctlM_clk (neg (probe "out"))) test_spr_knows_init = isOK (mc ctlM_spr (neg (probe "out"))) -- Later it does. test_clock_oblivious_later = isOK (mc ctlM_clk (ax (ag (probe "out")))) test_spr_oblivious_later = isOK (mc ctlM_spr (ax (ag (probe "out"))))
peteg/ADHOC
Tests/10_Knowledge/024_agent_obs_rev_boot.hs
gpl-2.0
1,175
1
16
231
420
213
207
-1
-1
module Main where -- This program is provided to convert an XML file containing a DTD -- into a Haskell module containing data/newtype definitions which -- mirror the DTD. Once you have used this program to generate your type -- definitions, you should import Xml2Haskell wherever you intend -- to read and write XML files with your Haskell programs. import System import IO import List (nub,takeWhile,dropWhile) import Text.XML.HaXml.Wrappers (fix2Args) import Text.XML.HaXml.Types (DocTypeDecl(..)) import Text.XML.HaXml.Parse (dtdParse) import Text.XML.HaXml.DtdToHaskell.TypeDef (TypeDef,ppTypeDef,mangle) import Text.XML.HaXml.DtdToHaskell.Convert (dtd2TypeDef) import Text.XML.HaXml.DtdToHaskell.Instance (mkInstance) import Text.PrettyPrint.HughesPJ (render,vcat) main = fix2Args >>= \(inf,outf)-> ( if inf=="-" then getContents else readFile inf ) >>= \content-> ( if outf=="-" then return stdout else openFile outf WriteMode ) >>= \o-> let (DTD name _ markup) = (getDtd . dtdParse inf) content decls = (nub . dtd2TypeDef) markup realname = if outf/="-" then mangle (trim outf) else if null name then mangle (trim inf) else mangle name in do hPutStrLn o ("module "++realname ++" where\n\nimport Text.XML.HaXml.Xml2Haskell" ++"\nimport Text.XML.HaXml.OneOfN") hPutStrLn o "\n\n{-Type decls-}\n" (hPutStrLn o . render . vcat . map ppTypeDef) decls hPutStrLn o "\n\n{-Instance decls-}\n" (hPutStrLn o . render . vcat . map mkInstance) decls hPutStrLn o "\n\n{-Done-}" getDtd (Just dtd) = dtd getDtd (Nothing) = error "No DTD in this document" trim name | '/' `elem` name = (trim . tail . dropWhile (/='/')) name | '.' `elem` name = takeWhile (/='.') name | otherwise = name
jgoerzen/dtmconv
HaXml-1.12/src/tools/DtdToHaskell.hs
gpl-2.0
1,869
0
20
424
509
277
232
35
5
{-# LANGUAGE OverloadedStrings #-} module Web.Crew.Templates.Renderer ( blaze, blazePretty ) where import Web.Scotty import Text.Blaze.Html (Html) import qualified Text.Blaze.Html.Renderer.Utf8 as Utf8 import qualified Text.Blaze.Html.Renderer.Pretty as Pretty import qualified Data.ByteString.Lazy.Char8 as B -- | Render some Blaze Html -- blaze :: Html -> ActionM () blaze h = do setHeader "Content-Type" "text/html" raw $ Utf8.renderHtml h blazePretty :: Html -> ActionM () blazePretty h = do setHeader "Content-Type" "text/html" raw $ B.pack $ Pretty.renderHtml h
schell/scottys-crew
Web/Crew/Templates/Renderer.hs
gpl-3.0
607
0
9
113
157
91
66
17
1
{-# OPTIONS_GHC -F -pgmF tasty-discover -optF --tree-display #-}
Kyarigwo/ki-component-store
test/Spec.hs
gpl-3.0
67
0
2
10
3
2
1
1
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Fitness.Users.Sessions.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates or insert a given session. -- -- /See:/ <https://developers.google.com/fit/rest/ Fitness Reference> for @fitness.users.sessions.update@. module Network.Google.Resource.Fitness.Users.Sessions.Update ( -- * REST Resource UsersSessionsUpdateResource -- * Creating a Request , usersSessionsUpdate , UsersSessionsUpdate -- * Request Lenses , usuPayload , usuUserId , usuCurrentTimeMillis , usuSessionId ) where import Network.Google.Fitness.Types import Network.Google.Prelude -- | A resource alias for @fitness.users.sessions.update@ method which the -- 'UsersSessionsUpdate' request conforms to. type UsersSessionsUpdateResource = "fitness" :> "v1" :> "users" :> Capture "userId" Text :> "sessions" :> Capture "sessionId" Text :> QueryParam "currentTimeMillis" (Textual Int64) :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Session :> Put '[JSON] Session -- | Updates or insert a given session. -- -- /See:/ 'usersSessionsUpdate' smart constructor. data UsersSessionsUpdate = UsersSessionsUpdate' { _usuPayload :: !Session , _usuUserId :: !Text , _usuCurrentTimeMillis :: !(Maybe (Textual Int64)) , _usuSessionId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UsersSessionsUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'usuPayload' -- -- * 'usuUserId' -- -- * 'usuCurrentTimeMillis' -- -- * 'usuSessionId' usersSessionsUpdate :: Session -- ^ 'usuPayload' -> Text -- ^ 'usuUserId' -> Text -- ^ 'usuSessionId' -> UsersSessionsUpdate usersSessionsUpdate pUsuPayload_ pUsuUserId_ pUsuSessionId_ = UsersSessionsUpdate' { _usuPayload = pUsuPayload_ , _usuUserId = pUsuUserId_ , _usuCurrentTimeMillis = Nothing , _usuSessionId = pUsuSessionId_ } -- | Multipart request metadata. usuPayload :: Lens' UsersSessionsUpdate Session usuPayload = lens _usuPayload (\ s a -> s{_usuPayload = a}) -- | Create sessions for the person identified. Use me to indicate the -- authenticated user. Only me is supported at this time. usuUserId :: Lens' UsersSessionsUpdate Text usuUserId = lens _usuUserId (\ s a -> s{_usuUserId = a}) -- | The client\'s current time in milliseconds since epoch. usuCurrentTimeMillis :: Lens' UsersSessionsUpdate (Maybe Int64) usuCurrentTimeMillis = lens _usuCurrentTimeMillis (\ s a -> s{_usuCurrentTimeMillis = a}) . mapping _Coerce -- | The ID of the session to be created. usuSessionId :: Lens' UsersSessionsUpdate Text usuSessionId = lens _usuSessionId (\ s a -> s{_usuSessionId = a}) instance GoogleRequest UsersSessionsUpdate where type Rs UsersSessionsUpdate = Session type Scopes UsersSessionsUpdate = '["https://www.googleapis.com/auth/fitness.activity.write"] requestClient UsersSessionsUpdate'{..} = go _usuUserId _usuSessionId _usuCurrentTimeMillis (Just AltJSON) _usuPayload fitnessService where go = buildClient (Proxy :: Proxy UsersSessionsUpdateResource) mempty
rueshyna/gogol
gogol-fitness/gen/Network/Google/Resource/Fitness/Users/Sessions/Update.hs
mpl-2.0
4,163
0
16
985
562
331
231
85
1
-- comment { id x = x; const x y = x }
metaborg/jsglr
org.spoofax.jsglr/tests-offside/terms/doaitse/explicit1.hs
apache-2.0
38
2
5
12
25
13
12
1
1
module Step_1_7 where -- Time to write your our first function input :: String input = "`Twas brillig, and the slithy toves\n" ++ "Did gyre and gimble in the wabe;\n" ++ "All mimsy were the borogoves,\n" ++ "And the mome raths outgrabe.\n" output :: String output = output1 oneNumber :: Int -> String -> String oneNumber n s = show n ++ ": " ++ s output1 :: String output1 = oneNumber 3 "All mimsy..." lineNumbers :: Int -> [String] -> [String] lineNumbers n xs = if xs == [] then [] else [oneNumber n (head xs)] ++ lineNumbers (n+1) (tail xs) output2 :: String output2 = unlines $ lineNumbers 1 $ lines input
mzero/barley
seed/Chapter1/Step_1_7.hs
apache-2.0
644
0
10
148
191
102
89
19
2
-- Copyright (c) 2013-2014 PivotCloud, Inc. -- -- Aws.Lambda.Commands.ListFunctions -- -- Please feel free to contact us at licensing@pivotmail.com with any -- contributions, additions, or other feedback; we would love to hear from -- you. -- -- 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 FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UnicodeSyntax #-} module Aws.Lambda.Commands.ListFunctions ( -- * Request ListFunctions(..) , listFunctions -- ** Lenses , lfMarker , lfMaxItems -- * Response , ListFunctionsResponse -- ** Lenses , lfrNextMarker , lfrFunctions ) where import Aws.Lambda.Core import Aws.Lambda.Types import Control.Applicative import Control.Applicative.Unicode import Control.Lens import Data.Aeson import qualified Data.Text as T import Network.HTTP.Types import Prelude.Unicode -- | Returns a list of your Lambda functions. For each function, the response -- includes the function configuration information. You must use @GetFunction@ to -- retrieve the code for your function. -- -- This operation requires permission for the @lambda:ListFunctions@ action. -- data ListFunctions = ListFunctions { _lfMarker ∷ !(Maybe PaginationToken) -- ^ An opaque pagination token returned from a previous 'ListFunctions' -- operation. If present, indicates where to continue the listing. , _lfMaxItems ∷ !(Maybe Int) -- ^ Specifies the maximum number of AWS Lambda functions to return in -- response. This parameter value must be greater than @0@ and less than -- @10000@. } deriving (Eq, Show) makeLenses ''ListFunctions -- | A minimal 'ListFunctions' request. -- listFunctions ∷ ListFunctions listFunctions = ListFunctions { _lfMarker = Nothing , _lfMaxItems = Nothing } data ListFunctionsResponse = ListFunctionsResponse { _lfrFunctions ∷ ![FunctionConfiguration] -- ^ A list of Lambda functions. , _lfrNextMarker ∷ !(Maybe PaginationToken) -- ^ A token whose presence indicates that more functions are available. } deriving (Eq, Show) makeLenses ''ListFunctionsResponse instance FromJSON ListFunctionsResponse where parseJSON = withObject "ListFunctionsResponse" $ \o → pure ListFunctionsResponse ⊛ o .:? "Functions" .!= [] ⊛ o .:? "NextMarker" instance LambdaTransaction ListFunctions () ListFunctionsResponse where buildQuery lf = lambdaQuery GET ["functions"] & lqParams %~ (at "Marker" .~ lf ^? lfMarker ∘ _Just ∘ ptText) ∘ (at "MaxItems" .~ lf ^? lfMaxItems ∘ _Just ∘ to (T.pack ∘ show)) instance PagedLambdaTransaction ListFunctions () ListFunctionsResponse PaginationToken [FunctionConfiguration] where requestCursor = lfMarker responseCursor = lfrNextMarker responseAccum = lfrFunctions
alephcloud/hs-aws-lambda
src/Aws/Lambda/Commands/ListFunctions.hs
apache-2.0
3,367
0
13
570
441
263
178
63
1
-- 137846528820 import Euler(nChooseK) nn = 20 -- two choices at each node, 2n nodes to traverse latticePaths n = nChooseK (n*2) n main = putStrLn $ show $ latticePaths nn
higgsd/euler
hs/15.hs
bsd-2-clause
175
0
7
34
52
28
24
4
1
-- | Benchmarks simple file reading -- -- Tested in this benchmark: -- -- * Reading a file from the disk -- module Benchmarks.FileRead ( benchmark ) where import Control.Applicative ((<$>)) import Criterion (Benchmark, bgroup, bench, whnfIO) import qualified Data.ByteString as SB import qualified Data.ByteString.Lazy as LB import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy as LT import qualified Data.Text.Lazy.Encoding as LT import qualified Data.Text.Lazy.IO as LT benchmark :: FilePath -> Benchmark benchmark p = bgroup "FileRead" [ bench "String" $ whnfIO $ length <$> readFile p , bench "ByteString" $ whnfIO $ SB.length <$> SB.readFile p , bench "LazyByteString" $ whnfIO $ LB.length <$> LB.readFile p , bench "Text" $ whnfIO $ T.length <$> T.readFile p , bench "LazyText" $ whnfIO $ LT.length <$> LT.readFile p , bench "TextByteString" $ whnfIO $ (T.length . T.decodeUtf8) <$> SB.readFile p , bench "LazyTextByteString" $ whnfIO $ (LT.length . LT.decodeUtf8) <$> LB.readFile p ]
bgamari/text
benchmarks/haskell/Benchmarks/FileRead.hs
bsd-2-clause
1,136
0
11
220
329
191
138
23
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGraphicsLineItem.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:26 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QGraphicsLineItem ( QqqGraphicsLineItem(..), QqGraphicsLineItem(..) ,QqqGraphicsLineItem_nf(..), QqGraphicsLineItem_nf(..) ,qline, qqline ,QsetLine(..), qsetLine ,qGraphicsLineItem_delete, qGraphicsLineItem_delete1 ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QGraphicsItem import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QGraphicsLineItem ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QGraphicsLineItem_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QGraphicsLineItem_userMethod" qtc_QGraphicsLineItem_userMethod :: Ptr (TQGraphicsLineItem a) -> CInt -> IO () instance QuserMethod (QGraphicsLineItemSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QGraphicsLineItem_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QGraphicsLineItem ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QGraphicsLineItem_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QGraphicsLineItem_userMethodVariant" qtc_QGraphicsLineItem_userMethodVariant :: Ptr (TQGraphicsLineItem a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QGraphicsLineItemSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QGraphicsLineItem_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqqGraphicsLineItem x1 where qqGraphicsLineItem :: x1 -> IO (QGraphicsLineItem ()) class QqGraphicsLineItem x1 where qGraphicsLineItem :: x1 -> IO (QGraphicsLineItem ()) instance QqGraphicsLineItem (()) where qGraphicsLineItem () = withQGraphicsLineItemResult $ qtc_QGraphicsLineItem foreign import ccall "qtc_QGraphicsLineItem" qtc_QGraphicsLineItem :: IO (Ptr (TQGraphicsLineItem ())) instance QqqGraphicsLineItem ((QLineF t1)) where qqGraphicsLineItem (x1) = withQGraphicsLineItemResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem1 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem1" qtc_QGraphicsLineItem1 :: Ptr (TQLineF t1) -> IO (Ptr (TQGraphicsLineItem ())) instance QqGraphicsLineItem ((LineF)) where qGraphicsLineItem (x1) = withQGraphicsLineItemResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> qtc_QGraphicsLineItem2 clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 foreign import ccall "qtc_QGraphicsLineItem2" qtc_QGraphicsLineItem2 :: CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQGraphicsLineItem ())) instance QqGraphicsLineItem ((QGraphicsItem t1)) where qGraphicsLineItem (x1) = withQGraphicsLineItemResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem3 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem3" qtc_QGraphicsLineItem3 :: Ptr (TQGraphicsItem t1) -> IO (Ptr (TQGraphicsLineItem ())) instance QqGraphicsLineItem ((QGraphicsTextItem t1)) where qGraphicsLineItem (x1) = withQGraphicsLineItemResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem3_graphicstextitem cobj_x1 foreign import ccall "qtc_QGraphicsLineItem3_graphicstextitem" qtc_QGraphicsLineItem3_graphicstextitem :: Ptr (TQGraphicsTextItem t1) -> IO (Ptr (TQGraphicsLineItem ())) instance QqqGraphicsLineItem ((QLineF t1, QGraphicsItem t2)) where qqGraphicsLineItem (x1, x2) = withQGraphicsLineItemResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem4 cobj_x1 cobj_x2 foreign import ccall "qtc_QGraphicsLineItem4" qtc_QGraphicsLineItem4 :: Ptr (TQLineF t1) -> Ptr (TQGraphicsItem t2) -> IO (Ptr (TQGraphicsLineItem ())) instance QqqGraphicsLineItem ((QLineF t1, QGraphicsTextItem t2)) where qqGraphicsLineItem (x1, x2) = withQGraphicsLineItemResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem4_graphicstextitem cobj_x1 cobj_x2 foreign import ccall "qtc_QGraphicsLineItem4_graphicstextitem" qtc_QGraphicsLineItem4_graphicstextitem :: Ptr (TQLineF t1) -> Ptr (TQGraphicsTextItem t2) -> IO (Ptr (TQGraphicsLineItem ())) instance QqGraphicsLineItem ((LineF, QGraphicsItem t2)) where qGraphicsLineItem (x1, x2) = withQGraphicsLineItemResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem5 clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 cobj_x2 foreign import ccall "qtc_QGraphicsLineItem5" qtc_QGraphicsLineItem5 :: CDouble -> CDouble -> CDouble -> CDouble -> Ptr (TQGraphicsItem t2) -> IO (Ptr (TQGraphicsLineItem ())) instance QqGraphicsLineItem ((LineF, QGraphicsTextItem t2)) where qGraphicsLineItem (x1, x2) = withQGraphicsLineItemResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem5_qth clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 cobj_x2 foreign import ccall "qtc_QGraphicsLineItem5_qth" qtc_QGraphicsLineItem5_qth :: CDouble -> CDouble -> CDouble -> CDouble -> Ptr (TQGraphicsTextItem t2) -> IO (Ptr (TQGraphicsLineItem ())) instance QqGraphicsLineItem ((QGraphicsItem t1, QGraphicsScene t2)) where qGraphicsLineItem (x1, x2) = withQGraphicsLineItemResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem6 cobj_x1 cobj_x2 foreign import ccall "qtc_QGraphicsLineItem6" qtc_QGraphicsLineItem6 :: Ptr (TQGraphicsItem t1) -> Ptr (TQGraphicsScene t2) -> IO (Ptr (TQGraphicsLineItem ())) instance QqGraphicsLineItem ((QGraphicsTextItem t1, QGraphicsScene t2)) where qGraphicsLineItem (x1, x2) = withQGraphicsLineItemResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem6_graphicstextitem cobj_x1 cobj_x2 foreign import ccall "qtc_QGraphicsLineItem6_graphicstextitem" qtc_QGraphicsLineItem6_graphicstextitem :: Ptr (TQGraphicsTextItem t1) -> Ptr (TQGraphicsScene t2) -> IO (Ptr (TQGraphicsLineItem ())) instance QqqGraphicsLineItem ((QLineF t1, QGraphicsItem t2, QGraphicsScene t3)) where qqGraphicsLineItem (x1, x2, x3) = withQGraphicsLineItemResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem7 cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QGraphicsLineItem7" qtc_QGraphicsLineItem7 :: Ptr (TQLineF t1) -> Ptr (TQGraphicsItem t2) -> Ptr (TQGraphicsScene t3) -> IO (Ptr (TQGraphicsLineItem ())) instance QqqGraphicsLineItem ((QLineF t1, QGraphicsTextItem t2, QGraphicsScene t3)) where qqGraphicsLineItem (x1, x2, x3) = withQGraphicsLineItemResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem7_graphicstextitem cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QGraphicsLineItem7_graphicstextitem" qtc_QGraphicsLineItem7_graphicstextitem :: Ptr (TQLineF t1) -> Ptr (TQGraphicsTextItem t2) -> Ptr (TQGraphicsScene t3) -> IO (Ptr (TQGraphicsLineItem ())) instance QqGraphicsLineItem ((LineF, QGraphicsItem t2, QGraphicsScene t3)) where qGraphicsLineItem (x1, x2, x3) = withQGraphicsLineItemResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem8 clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 cobj_x2 cobj_x3 foreign import ccall "qtc_QGraphicsLineItem8" qtc_QGraphicsLineItem8 :: CDouble -> CDouble -> CDouble -> CDouble -> Ptr (TQGraphicsItem t2) -> Ptr (TQGraphicsScene t3) -> IO (Ptr (TQGraphicsLineItem ())) instance QqGraphicsLineItem ((LineF, QGraphicsTextItem t2, QGraphicsScene t3)) where qGraphicsLineItem (x1, x2, x3) = withQGraphicsLineItemResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem8_qth clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 cobj_x2 cobj_x3 foreign import ccall "qtc_QGraphicsLineItem8_qth" qtc_QGraphicsLineItem8_qth :: CDouble -> CDouble -> CDouble -> CDouble -> Ptr (TQGraphicsTextItem t2) -> Ptr (TQGraphicsScene t3) -> IO (Ptr (TQGraphicsLineItem ())) class QqqGraphicsLineItem_nf x1 where qqGraphicsLineItem_nf :: x1 -> IO (QGraphicsLineItem ()) class QqGraphicsLineItem_nf x1 where qGraphicsLineItem_nf :: x1 -> IO (QGraphicsLineItem ()) instance QqGraphicsLineItem_nf (()) where qGraphicsLineItem_nf () = withObjectRefResult $ qtc_QGraphicsLineItem instance QqqGraphicsLineItem_nf ((QLineF t1)) where qqGraphicsLineItem_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem1 cobj_x1 instance QqGraphicsLineItem_nf ((LineF)) where qGraphicsLineItem_nf (x1) = withObjectRefResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> qtc_QGraphicsLineItem2 clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 instance QqGraphicsLineItem_nf ((QGraphicsItem t1)) where qGraphicsLineItem_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem3 cobj_x1 instance QqGraphicsLineItem_nf ((QGraphicsTextItem t1)) where qGraphicsLineItem_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem3_graphicstextitem cobj_x1 instance QqqGraphicsLineItem_nf ((QLineF t1, QGraphicsItem t2)) where qqGraphicsLineItem_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem4 cobj_x1 cobj_x2 instance QqqGraphicsLineItem_nf ((QLineF t1, QGraphicsTextItem t2)) where qqGraphicsLineItem_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem4_graphicstextitem cobj_x1 cobj_x2 instance QqGraphicsLineItem_nf ((LineF, QGraphicsItem t2)) where qGraphicsLineItem_nf (x1, x2) = withObjectRefResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem5 clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 cobj_x2 instance QqGraphicsLineItem_nf ((LineF, QGraphicsTextItem t2)) where qGraphicsLineItem_nf (x1, x2) = withObjectRefResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem5_qth clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 cobj_x2 instance QqGraphicsLineItem_nf ((QGraphicsItem t1, QGraphicsScene t2)) where qGraphicsLineItem_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem6 cobj_x1 cobj_x2 instance QqGraphicsLineItem_nf ((QGraphicsTextItem t1, QGraphicsScene t2)) where qGraphicsLineItem_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem6_graphicstextitem cobj_x1 cobj_x2 instance QqqGraphicsLineItem_nf ((QLineF t1, QGraphicsItem t2, QGraphicsScene t3)) where qqGraphicsLineItem_nf (x1, x2, x3) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem7 cobj_x1 cobj_x2 cobj_x3 instance QqqGraphicsLineItem_nf ((QLineF t1, QGraphicsTextItem t2, QGraphicsScene t3)) where qqGraphicsLineItem_nf (x1, x2, x3) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem7_graphicstextitem cobj_x1 cobj_x2 cobj_x3 instance QqGraphicsLineItem_nf ((LineF, QGraphicsItem t2, QGraphicsScene t3)) where qGraphicsLineItem_nf (x1, x2, x3) = withObjectRefResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem8 clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 cobj_x2 cobj_x3 instance QqGraphicsLineItem_nf ((LineF, QGraphicsTextItem t2, QGraphicsScene t3)) where qGraphicsLineItem_nf (x1, x2, x3) = withObjectRefResult $ withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem8_qth clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 cobj_x2 cobj_x3 instance QqqboundingRect (QGraphicsLineItem ()) (()) (IO (QRectF ())) where qqboundingRect x0 () = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_boundingRect_h cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_boundingRect_h" qtc_QGraphicsLineItem_boundingRect_h :: Ptr (TQGraphicsLineItem a) -> IO (Ptr (TQRectF ())) instance QqqboundingRect (QGraphicsLineItemSc a) (()) (IO (QRectF ())) where qqboundingRect x0 () = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_boundingRect_h cobj_x0 instance QqboundingRect (QGraphicsLineItem ()) (()) (IO (RectF)) where qboundingRect x0 () = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_boundingRect_qth_h cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h foreign import ccall "qtc_QGraphicsLineItem_boundingRect_qth_h" qtc_QGraphicsLineItem_boundingRect_qth_h :: Ptr (TQGraphicsLineItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO () instance QqboundingRect (QGraphicsLineItemSc a) (()) (IO (RectF)) where qboundingRect x0 () = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_boundingRect_qth_h cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h instance Qqcontains (QGraphicsLineItem ()) ((PointF)) where qcontains x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QGraphicsLineItem_contains_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y foreign import ccall "qtc_QGraphicsLineItem_contains_qth_h" qtc_QGraphicsLineItem_contains_qth_h :: Ptr (TQGraphicsLineItem a) -> CDouble -> CDouble -> IO CBool instance Qqcontains (QGraphicsLineItemSc a) ((PointF)) where qcontains x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QGraphicsLineItem_contains_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y instance Qqqcontains (QGraphicsLineItem ()) ((QPointF t1)) where qqcontains x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_contains_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_contains_h" qtc_QGraphicsLineItem_contains_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQPointF t1) -> IO CBool instance Qqqcontains (QGraphicsLineItemSc a) ((QPointF t1)) where qqcontains x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_contains_h cobj_x0 cobj_x1 instance Qextension (QGraphicsLineItem ()) ((QVariant t1)) (IO (QVariant ())) where extension x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_extension cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_extension" qtc_QGraphicsLineItem_extension :: Ptr (TQGraphicsLineItem a) -> Ptr (TQVariant t1) -> IO (Ptr (TQVariant ())) instance Qextension (QGraphicsLineItemSc a) ((QVariant t1)) (IO (QVariant ())) where extension x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_extension cobj_x0 cobj_x1 instance QisObscuredBy (QGraphicsLineItem ()) ((QGraphicsItem t1)) where isObscuredBy x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_isObscuredBy_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_isObscuredBy_h" qtc_QGraphicsLineItem_isObscuredBy_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool instance QisObscuredBy (QGraphicsLineItemSc a) ((QGraphicsItem t1)) where isObscuredBy x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_isObscuredBy_h cobj_x0 cobj_x1 instance QisObscuredBy (QGraphicsLineItem ()) ((QGraphicsTextItem t1)) where isObscuredBy x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_isObscuredBy_graphicstextitem_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_isObscuredBy_graphicstextitem_h" qtc_QGraphicsLineItem_isObscuredBy_graphicstextitem_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool instance QisObscuredBy (QGraphicsLineItemSc a) ((QGraphicsTextItem t1)) where isObscuredBy x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_isObscuredBy_graphicstextitem_h cobj_x0 cobj_x1 qline :: QGraphicsLineItem a -> (()) -> IO (LineF) qline x0 () = withLineFResult $ \clinef_ret_x1 clinef_ret_y1 clinef_ret_x2 clinef_ret_y2 -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_line_qth cobj_x0 clinef_ret_x1 clinef_ret_y1 clinef_ret_x2 clinef_ret_y2 foreign import ccall "qtc_QGraphicsLineItem_line_qth" qtc_QGraphicsLineItem_line_qth :: Ptr (TQGraphicsLineItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO () qqline :: QGraphicsLineItem a -> (()) -> IO (QLineF ()) qqline x0 () = withQLineFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_line cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_line" qtc_QGraphicsLineItem_line :: Ptr (TQGraphicsLineItem a) -> IO (Ptr (TQLineF ())) instance QopaqueArea (QGraphicsLineItem ()) (()) where opaqueArea x0 () = withQPainterPathResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_opaqueArea_h cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_opaqueArea_h" qtc_QGraphicsLineItem_opaqueArea_h :: Ptr (TQGraphicsLineItem a) -> IO (Ptr (TQPainterPath ())) instance QopaqueArea (QGraphicsLineItemSc a) (()) where opaqueArea x0 () = withQPainterPathResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_opaqueArea_h cobj_x0 instance Qpaint (QGraphicsLineItem a) ((QPainter t1, QStyleOptionGraphicsItem t2)) where paint x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem_paint cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QGraphicsLineItem_paint" qtc_QGraphicsLineItem_paint :: Ptr (TQGraphicsLineItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> IO () instance Qpaint (QGraphicsLineItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where paint x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem_paint1_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QGraphicsLineItem_paint1_h" qtc_QGraphicsLineItem_paint1_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO () instance Qpaint (QGraphicsLineItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where paint x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsLineItem_paint1_h cobj_x0 cobj_x1 cobj_x2 cobj_x3 instance Qpen (QGraphicsLineItem a) (()) where pen x0 () = withQPenResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_pen cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_pen" qtc_QGraphicsLineItem_pen :: Ptr (TQGraphicsLineItem a) -> IO (Ptr (TQPen ())) instance QsetExtension (QGraphicsLineItem ()) ((QGraphicsItemExtension, QVariant t2)) where setExtension x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem_setExtension cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2 foreign import ccall "qtc_QGraphicsLineItem_setExtension" qtc_QGraphicsLineItem_setExtension :: Ptr (TQGraphicsLineItem a) -> CLong -> Ptr (TQVariant t2) -> IO () instance QsetExtension (QGraphicsLineItemSc a) ((QGraphicsItemExtension, QVariant t2)) where setExtension x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem_setExtension cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2 class QsetLine x1 where setLine :: QGraphicsLineItem a -> x1 -> IO () instance QsetLine ((Double, Double, Double, Double)) where setLine x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_setLine1 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4) foreign import ccall "qtc_QGraphicsLineItem_setLine1" qtc_QGraphicsLineItem_setLine1 :: Ptr (TQGraphicsLineItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO () instance QsetLine ((LineF)) where setLine x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCLineF x1 $ \clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 -> qtc_QGraphicsLineItem_setLine_qth cobj_x0 clinef_x1_x1 clinef_x1_y1 clinef_x1_x2 clinef_x1_y2 foreign import ccall "qtc_QGraphicsLineItem_setLine_qth" qtc_QGraphicsLineItem_setLine_qth :: Ptr (TQGraphicsLineItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO () qsetLine :: QGraphicsLineItem a -> ((QLineF t1)) -> IO () qsetLine x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_setLine cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_setLine" qtc_QGraphicsLineItem_setLine :: Ptr (TQGraphicsLineItem a) -> Ptr (TQLineF t1) -> IO () instance QsetPen (QGraphicsLineItem a) ((QPen t1)) where setPen x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_setPen cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_setPen" qtc_QGraphicsLineItem_setPen :: Ptr (TQGraphicsLineItem a) -> Ptr (TQPen t1) -> IO () instance Qshape (QGraphicsLineItem ()) (()) (IO (QPainterPath ())) where shape x0 () = withQPainterPathResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_shape_h cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_shape_h" qtc_QGraphicsLineItem_shape_h :: Ptr (TQGraphicsLineItem a) -> IO (Ptr (TQPainterPath ())) instance Qshape (QGraphicsLineItemSc a) (()) (IO (QPainterPath ())) where shape x0 () = withQPainterPathResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_shape_h cobj_x0 instance QsupportsExtension (QGraphicsLineItem ()) ((QGraphicsItemExtension)) where supportsExtension x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_supportsExtension cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QGraphicsLineItem_supportsExtension" qtc_QGraphicsLineItem_supportsExtension :: Ptr (TQGraphicsLineItem a) -> CLong -> IO CBool instance QsupportsExtension (QGraphicsLineItemSc a) ((QGraphicsItemExtension)) where supportsExtension x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_supportsExtension cobj_x0 (toCLong $ qEnum_toInt x1) instance Qqtype (QGraphicsLineItem ()) (()) (IO (Int)) where qtype x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_type_h cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_type_h" qtc_QGraphicsLineItem_type_h :: Ptr (TQGraphicsLineItem a) -> IO CInt instance Qqtype (QGraphicsLineItemSc a) (()) (IO (Int)) where qtype x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_type_h cobj_x0 qGraphicsLineItem_delete :: QGraphicsLineItem a -> IO () qGraphicsLineItem_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_delete cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_delete" qtc_QGraphicsLineItem_delete :: Ptr (TQGraphicsLineItem a) -> IO () qGraphicsLineItem_delete1 :: QGraphicsLineItem a -> IO () qGraphicsLineItem_delete1 x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_delete1 cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_delete1" qtc_QGraphicsLineItem_delete1 :: Ptr (TQGraphicsLineItem a) -> IO () instance QaddToIndex (QGraphicsLineItem ()) (()) where addToIndex x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_addToIndex cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_addToIndex" qtc_QGraphicsLineItem_addToIndex :: Ptr (TQGraphicsLineItem a) -> IO () instance QaddToIndex (QGraphicsLineItemSc a) (()) where addToIndex x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_addToIndex cobj_x0 instance Qadvance (QGraphicsLineItem ()) ((Int)) where advance x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_advance_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QGraphicsLineItem_advance_h" qtc_QGraphicsLineItem_advance_h :: Ptr (TQGraphicsLineItem a) -> CInt -> IO () instance Qadvance (QGraphicsLineItemSc a) ((Int)) where advance x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_advance_h cobj_x0 (toCInt x1) instance QcollidesWithItem (QGraphicsLineItem ()) ((QGraphicsItem t1)) where collidesWithItem x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithItem_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_collidesWithItem_h" qtc_QGraphicsLineItem_collidesWithItem_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool instance QcollidesWithItem (QGraphicsLineItemSc a) ((QGraphicsItem t1)) where collidesWithItem x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithItem_h cobj_x0 cobj_x1 instance QcollidesWithItem (QGraphicsLineItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where collidesWithItem x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithItem1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QGraphicsLineItem_collidesWithItem1_h" qtc_QGraphicsLineItem_collidesWithItem1_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool instance QcollidesWithItem (QGraphicsLineItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where collidesWithItem x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithItem1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QcollidesWithItem (QGraphicsLineItem ()) ((QGraphicsTextItem t1)) where collidesWithItem x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithItem_graphicstextitem_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_collidesWithItem_graphicstextitem_h" qtc_QGraphicsLineItem_collidesWithItem_graphicstextitem_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool instance QcollidesWithItem (QGraphicsLineItemSc a) ((QGraphicsTextItem t1)) where collidesWithItem x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithItem_graphicstextitem_h cobj_x0 cobj_x1 instance QcollidesWithItem (QGraphicsLineItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where collidesWithItem x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithItem1_graphicstextitem_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QGraphicsLineItem_collidesWithItem1_graphicstextitem_h" qtc_QGraphicsLineItem_collidesWithItem1_graphicstextitem_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool instance QcollidesWithItem (QGraphicsLineItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where collidesWithItem x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithItem1_graphicstextitem_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QcollidesWithPath (QGraphicsLineItem ()) ((QPainterPath t1)) where collidesWithPath x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithPath_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_collidesWithPath_h" qtc_QGraphicsLineItem_collidesWithPath_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQPainterPath t1) -> IO CBool instance QcollidesWithPath (QGraphicsLineItemSc a) ((QPainterPath t1)) where collidesWithPath x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithPath_h cobj_x0 cobj_x1 instance QcollidesWithPath (QGraphicsLineItem ()) ((QPainterPath t1, ItemSelectionMode)) where collidesWithPath x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithPath1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QGraphicsLineItem_collidesWithPath1_h" qtc_QGraphicsLineItem_collidesWithPath1_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool instance QcollidesWithPath (QGraphicsLineItemSc a) ((QPainterPath t1, ItemSelectionMode)) where collidesWithPath x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_collidesWithPath1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QcontextMenuEvent (QGraphicsLineItem ()) ((QGraphicsSceneContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_contextMenuEvent_h" qtc_QGraphicsLineItem_contextMenuEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QGraphicsLineItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_contextMenuEvent_h cobj_x0 cobj_x1 instance QdragEnterEvent (QGraphicsLineItem ()) ((QGraphicsSceneDragDropEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_dragEnterEvent_h" qtc_QGraphicsLineItem_dragEnterEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO () instance QdragEnterEvent (QGraphicsLineItemSc a) ((QGraphicsSceneDragDropEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QGraphicsLineItem ()) ((QGraphicsSceneDragDropEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_dragLeaveEvent_h" qtc_QGraphicsLineItem_dragLeaveEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO () instance QdragLeaveEvent (QGraphicsLineItemSc a) ((QGraphicsSceneDragDropEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QGraphicsLineItem ()) ((QGraphicsSceneDragDropEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_dragMoveEvent_h" qtc_QGraphicsLineItem_dragMoveEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO () instance QdragMoveEvent (QGraphicsLineItemSc a) ((QGraphicsSceneDragDropEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QGraphicsLineItem ()) ((QGraphicsSceneDragDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_dropEvent_h" qtc_QGraphicsLineItem_dropEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO () instance QdropEvent (QGraphicsLineItemSc a) ((QGraphicsSceneDragDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_dropEvent_h cobj_x0 cobj_x1 instance QfocusInEvent (QGraphicsLineItem ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_focusInEvent_h" qtc_QGraphicsLineItem_focusInEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QGraphicsLineItemSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_focusInEvent_h cobj_x0 cobj_x1 instance QfocusOutEvent (QGraphicsLineItem ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_focusOutEvent_h" qtc_QGraphicsLineItem_focusOutEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QGraphicsLineItemSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_focusOutEvent_h cobj_x0 cobj_x1 instance QhoverEnterEvent (QGraphicsLineItem ()) ((QGraphicsSceneHoverEvent t1)) where hoverEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_hoverEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_hoverEnterEvent_h" qtc_QGraphicsLineItem_hoverEnterEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO () instance QhoverEnterEvent (QGraphicsLineItemSc a) ((QGraphicsSceneHoverEvent t1)) where hoverEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_hoverEnterEvent_h cobj_x0 cobj_x1 instance QhoverLeaveEvent (QGraphicsLineItem ()) ((QGraphicsSceneHoverEvent t1)) where hoverLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_hoverLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_hoverLeaveEvent_h" qtc_QGraphicsLineItem_hoverLeaveEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO () instance QhoverLeaveEvent (QGraphicsLineItemSc a) ((QGraphicsSceneHoverEvent t1)) where hoverLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_hoverLeaveEvent_h cobj_x0 cobj_x1 instance QhoverMoveEvent (QGraphicsLineItem ()) ((QGraphicsSceneHoverEvent t1)) where hoverMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_hoverMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_hoverMoveEvent_h" qtc_QGraphicsLineItem_hoverMoveEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO () instance QhoverMoveEvent (QGraphicsLineItemSc a) ((QGraphicsSceneHoverEvent t1)) where hoverMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_hoverMoveEvent_h cobj_x0 cobj_x1 instance QinputMethodEvent (QGraphicsLineItem ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_inputMethodEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_inputMethodEvent_h" qtc_QGraphicsLineItem_inputMethodEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QGraphicsLineItemSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_inputMethodEvent_h cobj_x0 cobj_x1 instance QinputMethodQuery (QGraphicsLineItem ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QGraphicsLineItem_inputMethodQuery_h" qtc_QGraphicsLineItem_inputMethodQuery_h :: Ptr (TQGraphicsLineItem a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QGraphicsLineItemSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) instance QitemChange (QGraphicsLineItem ()) ((GraphicsItemChange, QVariant t2)) where itemChange x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem_itemChange_h cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2 foreign import ccall "qtc_QGraphicsLineItem_itemChange_h" qtc_QGraphicsLineItem_itemChange_h :: Ptr (TQGraphicsLineItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ())) instance QitemChange (QGraphicsLineItemSc a) ((GraphicsItemChange, QVariant t2)) where itemChange x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem_itemChange_h cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2 instance QkeyPressEvent (QGraphicsLineItem ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_keyPressEvent_h" qtc_QGraphicsLineItem_keyPressEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QGraphicsLineItemSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_keyPressEvent_h cobj_x0 cobj_x1 instance QkeyReleaseEvent (QGraphicsLineItem ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_keyReleaseEvent_h" qtc_QGraphicsLineItem_keyReleaseEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QGraphicsLineItemSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_keyReleaseEvent_h cobj_x0 cobj_x1 instance QmouseDoubleClickEvent (QGraphicsLineItem ()) ((QGraphicsSceneMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_mouseDoubleClickEvent_h" qtc_QGraphicsLineItem_mouseDoubleClickEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QGraphicsLineItemSc a) ((QGraphicsSceneMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance QmouseMoveEvent (QGraphicsLineItem ()) ((QGraphicsSceneMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_mouseMoveEvent_h" qtc_QGraphicsLineItem_mouseMoveEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO () instance QmouseMoveEvent (QGraphicsLineItemSc a) ((QGraphicsSceneMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_mouseMoveEvent_h cobj_x0 cobj_x1 instance QmousePressEvent (QGraphicsLineItem ()) ((QGraphicsSceneMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_mousePressEvent_h" qtc_QGraphicsLineItem_mousePressEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO () instance QmousePressEvent (QGraphicsLineItemSc a) ((QGraphicsSceneMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QGraphicsLineItem ()) ((QGraphicsSceneMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_mouseReleaseEvent_h" qtc_QGraphicsLineItem_mouseReleaseEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO () instance QmouseReleaseEvent (QGraphicsLineItemSc a) ((QGraphicsSceneMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_mouseReleaseEvent_h cobj_x0 cobj_x1 instance QprepareGeometryChange (QGraphicsLineItem ()) (()) where prepareGeometryChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_prepareGeometryChange cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_prepareGeometryChange" qtc_QGraphicsLineItem_prepareGeometryChange :: Ptr (TQGraphicsLineItem a) -> IO () instance QprepareGeometryChange (QGraphicsLineItemSc a) (()) where prepareGeometryChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_prepareGeometryChange cobj_x0 instance QremoveFromIndex (QGraphicsLineItem ()) (()) where removeFromIndex x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_removeFromIndex cobj_x0 foreign import ccall "qtc_QGraphicsLineItem_removeFromIndex" qtc_QGraphicsLineItem_removeFromIndex :: Ptr (TQGraphicsLineItem a) -> IO () instance QremoveFromIndex (QGraphicsLineItemSc a) (()) where removeFromIndex x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsLineItem_removeFromIndex cobj_x0 instance QsceneEvent (QGraphicsLineItem ()) ((QEvent t1)) where sceneEvent x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_sceneEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_sceneEvent_h" qtc_QGraphicsLineItem_sceneEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQEvent t1) -> IO CBool instance QsceneEvent (QGraphicsLineItemSc a) ((QEvent t1)) where sceneEvent x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_sceneEvent_h cobj_x0 cobj_x1 instance QsceneEventFilter (QGraphicsLineItem ()) ((QGraphicsItem t1, QEvent t2)) where sceneEventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem_sceneEventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QGraphicsLineItem_sceneEventFilter_h" qtc_QGraphicsLineItem_sceneEventFilter_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool instance QsceneEventFilter (QGraphicsLineItemSc a) ((QGraphicsItem t1, QEvent t2)) where sceneEventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem_sceneEventFilter_h cobj_x0 cobj_x1 cobj_x2 instance QsceneEventFilter (QGraphicsLineItem ()) ((QGraphicsTextItem t1, QEvent t2)) where sceneEventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem_sceneEventFilter_graphicstextitem_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QGraphicsLineItem_sceneEventFilter_graphicstextitem_h" qtc_QGraphicsLineItem_sceneEventFilter_graphicstextitem_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool instance QsceneEventFilter (QGraphicsLineItemSc a) ((QGraphicsTextItem t1, QEvent t2)) where sceneEventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsLineItem_sceneEventFilter_graphicstextitem_h cobj_x0 cobj_x1 cobj_x2 instance QwheelEvent (QGraphicsLineItem ()) ((QGraphicsSceneWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsLineItem_wheelEvent_h" qtc_QGraphicsLineItem_wheelEvent_h :: Ptr (TQGraphicsLineItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO () instance QwheelEvent (QGraphicsLineItemSc a) ((QGraphicsSceneWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsLineItem_wheelEvent_h cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QGraphicsLineItem.hs
bsd-2-clause
47,577
0
17
6,879
13,337
6,759
6,578
-1
-1
{-# LANGUAGE PackageImports #-} module Numeric.Histogram ( module Histogram ) where import qualified "Chart" Numeric.Histogram as Histogram
bgamari/chart-histogram
Numeric/Histogram.hs
bsd-3-clause
142
0
4
19
22
16
6
3
0
module Matching where import Syntax import Pretty import Text.PrettyPrint import Control.Monad.State.Lazy import Control.Monad.Except import Data.List import qualified Data.Set as S import Debug.Trace -- As we have second-order matching, the state will be a list of -- all possible success substitutions -- list of success pattern, [] indicates failure, (Subst []) indicates identity sub -- convert a type expression that contains Imply to App (Const "->") convert :: Exp -> Exp -- convert (Pos _ e) = convert e convert (Imply x y) = App (App (Const "->" dummyPos) (convert x)) (convert y) convert Star = Star convert a@(Var _ _) = a convert a@(Const _ _) = a convert (App x y) = App (convert x) (convert y) convert (Forall x e) = Forall x (convert e) convert (Lambda x e) = Lambda x (convert e) convert e = error $ show e ++ "from convert" -- inversion of convert invert Star = Star invert a@(Var _ _) = a invert a@(Const _ _) = a invert (Forall x e) = Forall x (invert e) invert (Lambda x e) = Lambda x (invert e) invert (App (App (Const "->" _) x) y) = Imply (invert x) (invert y) invert (App x y) = App (invert x) (invert y) -- runMatch run the matching function, and postprocess the results by removing -- unused substitutions and duplicatations runMatch e1 e2 = let states = match ([(convert e1, convert e2)], [], Subst [], 0) fvs = freeVar e1 `S.union` freeVar e2 subs = [sub | ([], vars, sub, _) <- states, apart sub, agree sub, apartEV sub vars ] subs' = [ Subst s' | Subst s <- subs, let s' = [(x, invert e) | (x, e) <- s, x `S.member` fvs]] -- subs'' = nub $ map S.fromList subs' -- subs''' = map (Subst . S.toList) subs'' in subs' apartEV :: Subst -> [Name] -> Bool apartEV (Subst sub) vars = let codom = concat $ map (eigenVar . snd) sub in null $ codom `intersect` vars apart :: Subst -> Bool apart (Subst sub) = let dom = map fst sub codom = concat $ map (freeVars . snd) sub in null $ dom `intersect` codom agree :: Subst -> Bool agree (Subst s) = let xs = [(x, e) | (x, e) <- s, let a = filter (\ (y, e') -> y == x) s, all (\ (x', e'') -> e `alphaEq` e'') a] in length s == length xs type MatchState = ([(Exp, Exp)], [Name], Subst, Int) match :: MatchState -> [MatchState] -- match (eqs, vars, sub, i) | trace ("match " ++show (disp eqs) ++"\n") False = undefined match ((Star, Star):xs, vars, sub, i) = match (xs, vars, sub, i) match ((Var a p, Var b p'):xs, vars, sub, i) | b == a = match (xs, vars, sub, i) match ((Var a p, e):xs, vars, sub, i) | a `elem` freeVars e = [] | otherwise = let newSub = Subst [(a, e)] in match (map (\ (a1, a2) -> (apply newSub a1, apply newSub a2)) xs, vars, extend newSub sub, i) match ((e, Var a p):xs, vars, sub, i) = match ((Var a p, e):xs, vars, sub, i) match ((Forall x e, (Forall y e')):xs, vars, sub, i) = let fresh = "u"++ show i ++ "#" e1 = apply (Subst [(x, Const fresh dummyPos)]) e e2 = apply (Subst [(y, Const fresh dummyPos)]) e' in match ((e1, e2):xs, fresh:vars, sub, i+1) match ((e1, e2):res, vars, sub, i) | (Const x _):xs <- flatten e1, (Const y _):ys <- flatten e2, x == y, length xs == length ys = match (zip xs ys ++ res, vars, sub, i) match ((e1, e2):res, vars, sub, i) | (Const x _):xs <- flatten e1, (Var z _):ys <- flatten e2 = match ((e2, e1):res, vars, sub, i) match ((e1, e2):res, vars, sub, i) | (Var x p1):xs <- flatten e1, (Const y p2):ys <- flatten e2 = let argL = length xs argL' = length ys prjs = genProj argL (imi, j) = genImitation i (Const y p2) argL argL' iminew = normalize $ apply (Subst [(x, imi)]) e1 newsubs = Subst [(x, imi)] : map (\ p -> Subst [(x, p)]) prjs neweqs = (iminew, e2) : map (\ x -> (x, e2)) xs in concat [match (eq:res, vars, extend sub' sub, j) | (sub', eq) <- zip newsubs neweqs] match ((e1, e2):res, vars, sub, i) = [] match ([], vars, sub, i) = [([], vars, sub, i)] genProj :: Int -> [Exp] genProj l = if l == 0 then [] else let vars = map (\ y -> "x"++ show y ++ "#") $ take l [1..] ts = map (\ z -> foldr (\ x y -> Lambda (Var x dummyPos) y) (Var z dummyPos) vars) vars in ts genImitation :: Int -> Exp -> Int -> Int -> (Exp, Int) genImitation n head arity arity' = let l = take arity' [n..] lb = take arity [1..] n' = n + arity' hash = getName head fvars = map (\ x -> "h" ++ show x ++ hash ++ "#") l bvars = map (\ x -> "m" ++ show x ++ "#") lb bvars' = map (\ x -> Var x dummyPos) bvars args = map (\ c -> (foldl' (\ z x -> App z x) (Var c dummyPos) bvars')) fvars body = foldl' (\ z x -> App z x) head args res = foldr (\ x y -> Lambda (Var x dummyPos) y) body bvars in (res, n')
Fermat/higher-rank
src/Matching.hs
bsd-3-clause
5,017
0
18
1,446
2,453
1,311
1,142
103
2
{-# LANGUAGE ImplicitParams, RecordWildCards #-} module Frontend.Inline where import Data.List import Data.List.Split import Data.Maybe import Data.Tuple.Select import Control.Monad.State import Text.PrettyPrint import qualified Data.Map as M import qualified Data.Graph.Inductive as G import Util hiding (name) import PP 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.ISpec as I import Internal.PID import Name import Frontend.NS import Frontend.Method import Frontend.Spec import Frontend.Template import Frontend.Process import Frontend.Type import Frontend.TypeOps import Frontend.ExprOps import Frontend.Transducer import Frontend.Statement import Ops import Frontend.Const import Frontend.Val -- Extract template from flattened spec (that only has one template) tmMain :: (?spec::Spec) => Template tmMain = head $ specTemplate ?spec ---------------------------------------------------------------------- -- Names ---------------------------------------------------------------------- mkVarName :: (WithName a) => NSID -> a -> String mkVarName nsid x = mkVarNameS nsid (sname x) mkVarNameS :: NSID -> String -> String mkVarNameS (NSID mpid mmeth) s = intercalate "/" names where -- don't prefix function, procedure, and controllable task variables with PID mpid' = case mmeth of Nothing -> mpid Just m -> case methCat m of Function -> Nothing Procedure -> Nothing Task Controllable -> Nothing _ -> mpid names = maybe [] (return . show) mpid' ++ maybe [] (return . (++ "()") . sname) mmeth ++ [s] mkVar :: (WithName a) => NSID -> a -> I.Expr mkVar nsid x = I.EVar $ mkVarName nsid x mkVarS :: NSID -> String -> I.Expr mkVarS nsid s = I.EVar $ mkVarNameS nsid s mkVarDecl :: (?spec::Spec, WithName a) => Bool -> NSID -> a -> Type -> I.Var mkVarDecl mem nsid n t = I.Var mem I.VarState (mkVarName nsid n) (mkType t) parseVarName :: String -> (Maybe PrID, Maybe String, String) parseVarName n = (mpid, mmeth, vname) where toks = splitOn "/" n vname = last toks (mpid,mmeth) = case init toks of [] -> (Nothing, Nothing) toks' -> (mp, mm) where mm = if (take 2 $ reverse $ last toks') == ")(" then Just $ init $ init $ last toks' else Nothing mp = case init toks' of [] -> Nothing (p:ps) -> Just $ PrID p ps -- Variable that stores return value of a task mkRetVar :: Maybe PrID -> Method -> Maybe I.Expr mkRetVar mpid meth = case methRettyp meth of Nothing -> Nothing Just _ -> Just $ mkVarS (NSID mpid (Just meth)) "$ret" mkRetVarDecl :: (?spec::Spec) => Maybe PrID -> Method -> Maybe I.Var mkRetVarDecl mpid meth = case methRettyp meth of Nothing -> Nothing Just t -> Just $ I.Var False I.VarState (mkVarNameS (NSID mpid (Just meth)) "$ret") (mkType $ Type (ScopeTemplate tmMain) t) mkEnVarName :: PrID -> Maybe Method -> String mkEnVarName pid mmeth = mkVarNameS (NSID (Just pid) mmeth) "$en" mkEnVar :: PrID -> Maybe Method -> I.Expr mkEnVar pid mmeth = I.EVar $ mkEnVarName pid mmeth mkEnVarDecl :: PrID -> Maybe Method -> I.Var mkEnVarDecl pid mmeth = I.Var False I.VarState (mkEnVarName pid mmeth) (I.Bool Nothing) mkWaitForTask :: PrID -> Method -> I.Expr mkWaitForTask pid meth = envar I.=== I.false where envar = mkEnVar pid (Just meth) isWaitForTask :: I.Expr -> Maybe String isWaitForTask (I.EBinOp Eq (I.EVar n) e2) | e2 == I.false = case parseVarName n of (_, ms, "$en") -> ms _ -> Nothing isWaitForTask _ = Nothing isWaitForMagic :: I.Expr -> Bool isWaitForMagic (I.EBinOp Eq (I.EVar n) e2) | (e2 == I.false) && (n == mkMagicVarName) = True | otherwise = False isWaitForMagic _ = False mkPCVarName :: PrID -> String mkPCVarName pid = mkVarNameS (NSID (Just pid) Nothing) "$pc" mkPCEnumName :: PrID -> String mkPCEnumName pid = mkVarNameS (NSID (Just pid) Nothing) "$pcenum" --mkPCVar :: PrID -> I.Expr --mkPCVar pid = I.EVar $ mkPCVarName pid mkPCEnum :: PrID -> I.Loc -> String mkPCEnum pid loc = mkVarNameS (NSID (Just pid) Nothing) $ "$pc" ++ show loc mkPC :: PrID -> I.Loc -> I.Expr mkPC pid loc = I.EConst $ I.EnumVal $ mkPCEnum pid loc mkPCEq :: I.CFA -> PrID -> I.Expr -> I.Expr mkPCEq cfa pid e | (length $ I.cfaDelayLocs cfa) <= 1 = I.true | otherwise = (I.EVar $ mkPCVarName pid) I.=== e mkPCAsn :: I.CFA -> PrID -> I.Expr -> I.TranLabel mkPCAsn cfa pid e | (length $ I.cfaDelayLocs cfa) <= 1 = I.TranNop | otherwise = I.TranStat $ (I.EVar $ mkPCVarName pid) I.=: e pcEnumToLoc :: String -> I.Loc pcEnumToLoc str = read $ drop (length "$pc") $ fromJust $ find (isPrefixOf "$pc") $ reverse $ tails str -- Variables that encode fairness mkFairSchedVarName :: String mkFairSchedVarName = "$fair_sched" mkFairSchedVarDecl :: I.Var mkFairSchedVarDecl = I.Var False I.VarState mkFairSchedVarName (I.Bool Nothing) mkFairSchedVar :: I.Expr mkFairSchedVar = I.EVar mkFairSchedVarName mkFairProcVarName :: PrID -> String mkFairProcVarName pid = "$pfair_" ++ show pid fairProcVarPID :: String -> Maybe PrID fairProcVarPID s | isPrefixOf "$pfair_" s = Just $ parsePID $ drop (length "$pfair_") s | otherwise = Nothing isFairVarName :: String -> Bool isFairVarName n = (isJust $ fairProcVarPID n) || n == mkFairSchedVarName mkFairProcVarDecl :: PrID -> I.Var mkFairProcVarDecl pid = I.Var False I.VarState (mkFairProcVarName pid) (I.Bool Nothing) mkFairProcVar :: PrID -> I.Expr mkFairProcVar pid = I.EVar $ mkFairProcVarName pid mkFairRegVarDecls :: I.Spec -> [I.Var] mkFairRegVarDecls spec = mkFairSchedVarDecl : (map (mkFairProcVarDecl . fst) $ I.specAllProcs spec) mkFairRegVars :: I.Spec -> [I.Expr] mkFairRegVars spec = mkFairSchedVar : (map (mkFairProcVar . fst) $ I.specAllProcs spec) -- PID of the process making a transition mkPIDLVarName :: String mkPIDLVarName = "$lpid" mkPIDLVar :: I.Expr mkPIDLVar = I.EVar mkPIDLVarName mkPIDEnumeratorName :: PrID -> String mkPIDEnumeratorName pid = "$" ++ show pid parsePIDEnumerator :: String -> PrID parsePIDEnumerator n = parsePID $ tail n mkPIDEnum :: PrID -> I.Expr mkPIDEnum = I.EConst . I.EnumVal . mkPIDEnumeratorName mkPIDEnumName :: String mkPIDEnumName = "$pidenum" --mkEPIDNone :: String --mkEPIDNone = "$epidnone" mkPIDLVarDecl :: [PrID] -> (I.Var, I.Enumeration) mkPIDLVarDecl pids = (I.Var False I.VarTmp mkPIDLVarName (I.Enum Nothing mkPIDEnumName), enum) where enum = I.Enumeration mkPIDEnumName $ map mkPIDEnumeratorName pids --mkContVarName :: String --mkContVarName = "$cont" -- --mkContVar :: I.Expr --mkContVar = I.EVar mkContVarName -- --mkContVarDecl :: (?spec::Spec) => I.Var --mkContVarDecl = I.Var False I.VarState mkContVarName I.Bool mkContLVarName :: String mkContLVarName = "$lcont" mkContLVar :: I.Expr mkContLVar = I.EVar mkContLVarName mkContLVarDecl :: (?spec::Spec) => I.Var mkContLVarDecl = I.Var False I.VarTmp mkContLVarName (I.Bool Nothing) mkMagicVarName :: String mkMagicVarName = "$magic" mkMagicVar :: I.Expr mkMagicVar = I.EVar mkMagicVarName mkMagicVarDecl :: I.Var mkMagicVarDecl = I.Var False I.VarState mkMagicVarName (I.Bool Nothing) mkMagicDoneCond :: I.Expr mkMagicDoneCond = mkMagicVar I.=== I.false mkErrVarName :: String mkErrVarName = I.cfaErrVarName mkErrVar :: I.Expr mkErrVar = I.EVar mkErrVarName mkErrVarDecl :: I.Var mkErrVarDecl = I.Var False I.VarState mkErrVarName (I.Bool Nothing) mkTagVarName :: String mkTagVarName = "$tag" mkTagVar :: I.Expr mkTagVar = I.EVar mkTagVarName mkTagExit = "$tagexit" -- exit magic block mkTagDoNothing = "$tagnop" -- idle loop transition -- mkTagNone = "$tagnone" mkTagVarDecl :: (?spec::Spec) => (I.Var, I.Enumeration) mkTagVarDecl = (I.Var False I.VarTmp mkTagVarName (I.Enum Nothing "$tags"), I.Enumeration "$tags" mkTagList) mkTagList :: (?spec::Spec) => [String] mkTagList = mkTagExit : mkTagDoNothing : (map sname $ filter ((== Task Controllable) . methCat) $ tmMethod tmMain) mkArgTmpVarName :: Method -> Arg -> String mkArgTmpVarName m a = "$$" ++ sname m ++ "." ++ sname a mkChoiceTypeName :: Int -> String mkChoiceTypeName n = "$choice" ++ show n mkChoiceType :: Int -> I.Type mkChoiceType n = I.Enum Nothing $ mkChoiceTypeName n mkChoiceValName :: String -> Int -> String mkChoiceValName tname i = tname ++ "_" ++ show i mkChoice :: I.Var -> Int -> I.Expr mkChoice v i = I.EConst $ I.EnumVal $ mkChoiceValName tname i where I.Enum _ tname = I.varType v mkChoiceEnumDecl :: Int -> I.Enumeration mkChoiceEnumDecl i = I.Enumeration {..} where enumName = mkChoiceTypeName i enumEnums = map (mkChoiceValName enumName) [0..i-1] type NameMap = M.Map Ident I.Expr methodLMap :: Maybe PrID -> Method -> NameMap methodLMap mpid meth = M.fromList $ map (\v -> (name v, mkVar (NSID mpid (Just meth)) v)) (methVar meth) ++ map (\a -> (name a, mkVar (NSID mpid (Just meth)) a)) (methArg meth) procLMap :: Process -> NameMap procLMap p = M.fromList $ map (\v -> (name v, mkVar (NSID (Just $ PrID (sname p) []) Nothing) v)) (procVar p) xducerLMap :: Transducer -> NameMap xducerLMap x@Transducer{..} = M.fromList $ inputs ++ outputs ++ locals where inputs = map (\i -> (name i, I.EVar $ sname i)) txInput outputs = map (\o -> (name o, I.EVar $ sname o)) txOutput locals = case txBody of Left _ -> [] Right st -> map (\v -> (name v, I.EVar $ sname v)) $ stmtVar st scopeLMap :: Maybe PrID -> Scope -> NameMap scopeLMap mpid sc = case sc of ScopeMethod _ meth -> methodLMap mpid meth ScopeProcess _ proc -> procLMap proc ScopeTransducer tx -> xducerLMap tx ScopeTemplate _ -> M.empty globalNMap :: (?spec::Spec) => NameMap globalNMap = M.union (M.fromList $ gvars ++ wires) globalConstNMap where -- global variables gvars = map (\v -> (name v, mkVar (NSID Nothing Nothing) v)) $ tmVar tmMain -- wires wires = map (\w -> (name w, mkVar (NSID Nothing Nothing) w)) $ tmWire tmMain globalConstNMap :: (?spec::Spec) => NameMap globalConstNMap = M.fromList $ enums ++ consts where enums = concatMap (\d -> case tspec d of EnumSpec _ es -> map (\e -> (name e, I.EConst $ I.EnumVal $ sname e)) es _ -> []) $ specType ?spec consts = let ?scope = ScopeTop in mapMaybe (\c -> case eval $ constVal c of TVal _ (StructVal _) -> Nothing v -> Just (name c, I.EConst $ valToIVal v)) $ specConst ?spec ---------------------------------------------------------------------- -- Types ---------------------------------------------------------------------- valToIVal :: (?spec::Spec) => TVal -> I.Val valToIVal (TVal _ (BoolVal True)) = I.BoolVal True valToIVal (TVal _ (BoolVal False)) = I.BoolVal False valToIVal (TVal t (IntVal i)) = case tspec $ typ' t of SIntSpec _ w -> I.SIntVal w i UIntSpec _ w -> I.UIntVal w i valToIVal (TVal _ (EnumVal n)) = I.EnumVal $ sname n mkType :: (?spec::Spec) => Type -> I.Type mkType t = case typ' t of Type _ (BoolSpec _) -> I.Bool alias Type _ (SIntSpec _ w) -> I.SInt alias w Type _ (UIntSpec _ w) -> I.UInt alias w Type s (StructSpec _ fs) -> I.Struct alias $ map (\(Field _ t' n) -> I.Field (sname n) (mkType (Type s t'))) fs Type _ (EnumSpec _ es) -> I.Enum alias $ getEnumName $ name $ head es Type s (PtrSpec _ t') -> I.Ptr alias $ mkType $ Type s t' Type s (ArraySpec _ t' l) -> let ?scope = s in I.Array alias (mkType $ Type s t') (fromInteger $ evalInt l) Type s (VarArraySpec _ t') -> let ?scope = s in I.VarArray alias (mkType $ Type s t') Type s (SeqSpec _ t') -> let ?scope = s in I.Seq alias (mkType $ Type s t') Type _ t' -> error $ "mkType: " ++ show t' where alias = case tspec t of UserTypeSpec _ a -> Just $ render $ pp a _ -> Nothing getEnumName :: (?spec::Spec) => Ident -> String getEnumName n = sname $ fromJustMsg ("getEnumName: enumerator " ++ sname n ++ " not found") $ find (\d -> case tspec d of EnumSpec _ es -> isJust $ find ((==n) . name) es _ -> False) $ specType ?spec ----------------------------------------------------------- -- State maintained during CFA construction ----------------------------------------------------------- data CFACtx = CFACtx { ctxEPID :: Maybe EPID -- ID of the CFA being constructed or Nothing if the CFA is not part of the final spec , ctxStack :: [(Scope, I.Loc, Maybe I.Expr, NameMap)] -- stack of syntactic scopes: (scope, return location, LHS, local namemap) , ctxCFA :: I.CFA -- CFA constructed so far , ctxBrkLocs :: [I.Loc] -- stack break location , ctxGNMap :: NameMap -- global variables visible in current scope , ctxLastVar :: Int -- counter used to generate unique variable names , ctxVar :: [I.Var] -- temporary vars , ctxLabels :: [String] -- statement label stack } ctxScope :: CFACtx -> Scope ctxScope = sel1 . head . ctxStack ctxRetLoc :: CFACtx -> I.Loc ctxRetLoc = sel2 . head . ctxStack ctxLHS :: CFACtx -> Maybe I.Expr ctxLHS = sel3 . head . ctxStack ctxLNMap :: CFACtx -> NameMap ctxLNMap = sel4 . head . ctxStack ctxPushScope :: Scope -> I.Loc -> Maybe I.Expr -> NameMap -> State CFACtx () ctxPushScope sc retloc lhs nmap = modify (\ctx -> ctx {ctxStack = (sc, retloc, lhs, nmap) : (ctxStack ctx)}) ctxPopScope :: State CFACtx () ctxPopScope = modify (\ctx -> ctx {ctxStack = tail $ ctxStack ctx}) ctxBrkLoc :: CFACtx -> I.Loc ctxBrkLoc = head . ctxBrkLocs ctxPushBrkLoc :: I.Loc -> State CFACtx () ctxPushBrkLoc loc = modify (\ctx -> ctx {ctxBrkLocs = loc : (ctxBrkLocs ctx)}) ctxPopBrkLoc :: State CFACtx () ctxPopBrkLoc = modify (\ctx -> ctx {ctxBrkLocs = tail $ ctxBrkLocs ctx}) ctxPushLabel :: String -> State CFACtx () ctxPushLabel lab = modify (\ctx -> ctx {ctxLabels = lab : ctxLabels ctx}) ctxPopLabel :: State CFACtx () ctxPopLabel = modify (\ctx -> ctx {ctxLabels = tail $ ctxLabels ctx}) ctxInsLoc :: State CFACtx I.Loc ctxInsLoc = ctxInsLocLab (I.LInst I.ActNone) ctxInsLocLab :: I.LocLabel -> State CFACtx I.Loc ctxInsLocLab lab = do ctx <- get let (cfa', loc) = I.cfaInsLoc lab $ ctxCFA ctx put $ ctx {ctxCFA = cfa'} return loc ctxLocSetAct :: I.Loc -> I.LocAction -> State CFACtx () ctxLocSetAct loc act = modify (\ctx -> ctx {ctxCFA = I.cfaLocSetAct loc act $ ctxCFA ctx}) ctxLocSetStack :: I.Loc -> I.Stack -> State CFACtx () ctxLocSetStack loc stack = modify (\ctx -> ctx {ctxCFA = I.cfaLocSetStack loc stack $ ctxCFA ctx}) ctxInsTrans :: I.Loc -> I.Loc -> I.TranLabel -> State CFACtx () ctxInsTrans from to t = modify (\ctx -> ctx {ctxCFA = I.cfaInsTrans from to t $ ctxCFA ctx}) ctxInsTransMany :: I.Loc -> I.Loc -> [I.TranLabel] -> State CFACtx () ctxInsTransMany from to ts = modify $ (\ctx -> ctx {ctxCFA = I.cfaInsTransMany from to ts $ ctxCFA ctx}) ctxInsTrans' :: I.Loc -> I.TranLabel -> State CFACtx I.Loc ctxInsTrans' from t = do to <- ctxInsLoc ctxInsTrans from to t return to ctxInsTransMany' :: I.Loc -> [I.TranLabel] -> State CFACtx I.Loc ctxInsTransMany' from ts = do to <- ctxInsLoc ctxInsTransMany from to ts return to ctxInsTmpVar :: Maybe Ident -> I.Type -> State CFACtx I.Var ctxInsTmpVar mn t = do lst <- gets ctxLastVar mepid <- gets ctxEPID sc <- gets ctxScope let nsid = maybe (NSID Nothing Nothing) (\epid -> epid2nsid epid sc) mepid vname = mkVarNameS nsid $ maybe ("$tmp" ++ show (lst + 1)) sname mn v = I.Var False I.VarTmp vname t modify $ (\ctx -> ctx { ctxLastVar = lst + 1 , ctxVar = v:(ctxVar ctx)}) return v ctxFrames :: I.Loc -> State CFACtx I.Stack ctxFrames loc = do cfastack <- gets ctxStack -- CFACtx stack stores return locations in stack frames, but the Stack -- type stores current locations in frames. Shift ret locations by one -- and append current location in the end. let scopes = map sel1 cfastack locs = loc: (init $ map sel2 cfastack) return $ map (uncurry I.Frame) $ zip scopes locs ctxPause :: I.Loc -> I.Expr -> I.LocAction -> State CFACtx I.Loc ctxPause loc cond act = do labs <- gets ctxLabels after <- ctxInsLocLab (I.LPause act [] labs cond) stack <- ctxFrames after ctxLocSetStack after stack ctxInsTrans loc after $ I.TranNop -- ctxSuffix loc after after ctxInsTrans' after (I.TranStat $ I.SAssume cond) ctxIn :: I.Loc -> I.Expr -> I.Expr -> I.LocAction -> State CFACtx I.Loc ctxIn loc elhs erhs act = do after <- ctxInsLocLab (I.LIn act elhs erhs) ctxInsTrans loc after $ I.TranNop return after ctxFinal :: I.Loc -> State CFACtx I.Loc ctxFinal loc = do labs <- gets ctxLabels after <- ctxInsLocLab (I.LFinal I.ActNone [] labs) stack <- ctxFrames after ctxLocSetStack after stack ctxInsTrans loc after $ I.TranNop -- ctxSuffix loc after after return after ctxUContInsertSuffixes :: State CFACtx () ctxUContInsertSuffixes = do Just (EPIDProc pid) <- gets ctxEPID cfa0 <- gets ctxCFA modify $ \ctx -> ctx {ctxCFA = foldl' (insertSuffix pid) cfa0 (I.cfaDelayLocs cfa0)} cfa1 <- gets ctxCFA modify $ \ctx -> ctx {ctxCFA = foldl' (insertPrefix pid) cfa1 (I.cfaDelayLocs cfa1)} insertPrefix :: PrID -> I.CFA -> I.Loc -> I.CFA insertPrefix pid cfa loc | (null $ G.lsuc cfa loc) = cfa | otherwise = I.cfaInsTrans loc loc' (I.TranStat $ I.SAssume $ lepid `I.land` ucont) cfa1 where (Just (pre, _, lab, suc), cfa0) = G.match loc cfa loc' = (snd $ G.nodeRange cfa) + 1 cfa1 = (pre, loc, lab, []) G.& (([], loc', I.LInst I.ActNone, suc) G.& cfa0) lepid = mkPIDLVar I.=== (mkPIDEnum pid) ucont = mkContLVar I.=== I.false insertSuffix :: PrID -> I.CFA -> I.Loc -> I.CFA insertSuffix pid cfa loc | (null $ G.pre cfa loc) = cfa | otherwise = cfa1 where (loc', cfa0) = I.cfaSplitLoc loc cfa -- pc cfa1 = I.cfaInsTrans loc' loc (mkPCAsn cfa pid (mkPC pid loc)) cfa0 -- cont --cfa2 = I.cfaInsTrans aftpc loc (I.TranStat $ mkContVar I.=: mkContLVar) cfa1 ctxErrTrans :: I.Loc -> I.Loc -> State CFACtx () ctxErrTrans from to = do modify $ \ctx -> ctx {ctxCFA = I.cfaErrTrans from to $ ctxCFA ctx} -- Add error transitions for all potential null-pointer dereferences ctxAddNullPtrTrans :: State CFACtx () ctxAddNullPtrTrans = do ctx <- get _ <- mapM addNullPtrTrans1 (G.labEdges $ ctxCFA ctx) return () addNullPtrTrans1 :: (I.Loc,I.Loc,I.TranLabel) -> State CFACtx () addNullPtrTrans1 (from , to, l@(I.TranStat (I.SAssign e1 e2))) = do let cond = -- We don't have access to ?spec here, hence cannot determine type of -- NullVal. Keep it undefined until a separate pass. I.disj $ map (\e -> e I.=== (I.EConst $ I.NullVal $ error "NullVal type undefined")) $ I.exprPtrSubexpr e1 ++ I.exprPtrSubexpr e2 case cond of I.EConst (I.BoolVal False) -> return () _ -> do modify $ \ctx -> ctx {ctxCFA = G.delLEdge (from, to, l) $ ctxCFA ctx} from' <- ctxInsTrans' from (I.TranStat $ I.SAssume $ I.neg cond) fromerr <- ctxInsTrans' from (I.TranStat $ I.SAssume cond) ctxInsTrans from' to l ctxErrTrans fromerr from' addNullPtrTrans1 (_ , _, _) = return () ctxPruneUnreachable :: State CFACtx () ctxPruneUnreachable = modify (\ctx -> ctx {ctxCFA = I.cfaPruneUnreachable (ctxCFA ctx) [I.cfaInitLoc]})
termite2/tsl
Frontend/Inline.hs
bsd-3-clause
21,817
0
20
6,402
7,228
3,698
3,530
406
11
{-# LANGUAGE CPP , UnicodeSyntax , NoImplicitPrelude , FlexibleContexts , ScopedTypeVariables #-} -------------------------------------------------------------------------------- -- | -- Module : System.USB.Safe.Iteratee -- Copyright : (c) 2011 Bas van Dijk -- License : BSD3 (see the file LICENSE) -- Maintainer : Bas van Dijk <v.dijk.bas@gmail.com> -- -- Iteratee enumerators for endpoints. -- -------------------------------------------------------------------------------- module System.USB.Safe.Iteratee ( enumReadBulk , enumReadInterrupt #ifdef HAS_EVENT_MANAGER , enumReadIsochronous #endif ) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- -- from base: import Prelude ( fromIntegral ) import Data.Function ( ($) ) import Data.Word ( Word8 ) import Data.Maybe ( Maybe(Nothing, Just) ) import Control.Monad ( (>>=), return ) import Foreign.Storable ( peek ) import Foreign.Ptr ( castPtr ) import Foreign.Marshal.Alloc ( alloca, allocaBytes ) import Control.Exception ( toException ) #if __GLASGOW_HASKELL__ < 700 import Prelude ( fromInteger ) import Control.Monad ( fail ) #endif -- from base-unicode-symbols: import Data.Eq.Unicode ( (≡), (≢) ) import Data.Bool.Unicode ( (∧) ) import Data.Function.Unicode ( (∘) ) -- from bindings-libusb: import Bindings.Libusb ( c'libusb_bulk_transfer , c'libusb_interrupt_transfer , c'LIBUSB_SUCCESS , c'LIBUSB_ERROR_TIMEOUT ) -- from usb: import System.USB.DeviceHandling ( DeviceHandle ) import System.USB.Descriptors ( EndpointAddress ) import System.USB.IO ( Timeout, Size ) import System.USB.Internal ( C'TransferFunc , withDevHndlPtr , marshalEndpointAddress , convertUSBException ) #ifdef __HADDOCK__ import System.USB.Descriptors ( maxPacketSize, endpointMaxPacketSize , TransferDirection(In) , TransferType(Bulk, Interrupt) ) #endif -- from iteratee: import Data.Iteratee.Base ( Stream(EOF, Chunk), runIter, idoneM ) import Data.Iteratee.Iteratee ( Enumerator, throwErr ) import Data.Iteratee.Base.ReadableChunk ( ReadableChunk(readFromPtr) ) import Data.NullPoint ( NullPoint(empty) ) -- from regions: import Control.Monad.Trans.Region ( RegionControlIO ) import Control.Monad.Trans.Region.Unsafe ( unsafeControlIO ) #ifdef HAS_EVENT_MANAGER -------------------------------------------------------------------------------- -- from base: import Data.Bool ( otherwise, not ) import Data.Int ( Int ) import Data.Function ( id ) import Data.List ( (++), map ) import Foreign.Ptr ( Ptr, nullPtr, plusPtr ) import Foreign.Storable ( poke ) import System.IO ( IO ) import Text.Show ( show ) import Prelude ( (*), error, String ) import Control.Exception ( SomeException, onException, mask, uninterruptibleMask_ ) import #if MIN_VERSION_base(4,4,0) GHC.Event #else System.Event #endif ( registerTimeout, unregisterTimeout ) -- from iteratee: import Data.Iteratee.Base ( Iteratee ) -- from bindings-libusb: import Bindings.Libusb ( c'LIBUSB_TRANSFER_TYPE_BULK , c'LIBUSB_TRANSFER_TYPE_INTERRUPT , c'LIBUSB_TRANSFER_TYPE_ISOCHRONOUS , c'LIBUSB_TRANSFER_COMPLETED , c'LIBUSB_TRANSFER_TIMED_OUT , c'LIBUSB_TRANSFER_ERROR , c'LIBUSB_TRANSFER_NO_DEVICE , c'LIBUSB_TRANSFER_OVERFLOW , c'LIBUSB_TRANSFER_STALL , c'LIBUSB_TRANSFER_CANCELLED , C'libusb_iso_packet_descriptor(..) , C'libusb_transfer(..) , c'libusb_submit_transfer , c'libusb_cancel_transfer , p'libusb_transfer'status , p'libusb_transfer'actual_length ) -- from usb: import System.USB.DeviceHandling ( getDevice ) import System.USB.Exceptions ( USBException(..), ioException ) #ifdef __HADDOCK__ import System.USB.Descriptors ( TransferType(Isochronous), maxIsoPacketSize ) #endif import System.USB.IO ( noTimeout ) import System.USB.Internal ( threaded , C'TransferType , allocaTransfer, withCallback , newLock, acquire, release , SumLength(..), sumLength , peekIsoPacketDescs , initIsoPacketDesc , getCtx, getEventManager ) #endif -------------------------------------------------------------------------------- -- Enumerators -------------------------------------------------------------------------------- -- | Iteratee enumerator for reading /bulk/ endpoints. enumReadBulk ∷ (ReadableChunk s Word8, NullPoint s, RegionControlIO m) ⇒ DeviceHandle -- ^ A handle for the device to communicate with. → EndpointAddress -- ^ The address of a valid 'In' and 'Bulk' -- endpoint to communicate with. Make sure the -- endpoint belongs to the current alternate -- setting of a claimed interface which belongs -- to the device. → Size -- ^ Chunk size. A good value for this would be -- the @'maxPacketSize' . 'endpointMaxPacketSize'@. → Timeout -- ^ Timeout (in milliseconds) that this function -- should wait for each chunk before giving up -- due to no response being received. → Enumerator s m α enumReadBulk #ifdef HAS_EVENT_MANAGER | threaded = enumReadAsync c'LIBUSB_TRANSFER_TYPE_BULK #endif | otherwise = enumReadSync c'libusb_bulk_transfer -- | Iteratee enumerator for reading /interrupt/ endpoints. enumReadInterrupt ∷ (ReadableChunk s Word8, NullPoint s, RegionControlIO m) ⇒ DeviceHandle -- ^ A handle for the device to communicate -- with. → EndpointAddress -- ^ The address of a valid 'In' and -- 'Interrupt' endpoint to communicate -- with. Make sure the endpoint belongs to -- the current alternate setting of a -- claimed interface which belongs to the -- device. → Size -- ^ Chunk size. A good value for this would -- be the @'maxPacketSize' . 'endpointMaxPacketSize'@. → Timeout -- ^ Timeout (in milliseconds) that this -- function should wait for each chunk -- before giving up due to no response -- being received. → Enumerator s m α enumReadInterrupt #ifdef HAS_EVENT_MANAGER | threaded = enumReadAsync c'LIBUSB_TRANSFER_TYPE_INTERRUPT #endif | otherwise = enumReadSync c'libusb_interrupt_transfer type Run s m α = Stream s → IO (Restore s m α) type Restore s m α = m (Iteratee s m α) #ifdef HAS_EVENT_MANAGER -------------------------------------------------------------------------------- -- Asynchronous -------------------------------------------------------------------------------- enumReadAsync ∷ ∀ s m α . (ReadableChunk s Word8, NullPoint s, RegionControlIO m) ⇒ C'TransferType → DeviceHandle → EndpointAddress → Size → Timeout → Enumerator s m α enumReadAsync transType = \devHndl endpointAddr chunkSize timeout → enum transType 0 [] devHndl endpointAddr timeout chunkSize withResult withResult where withResult ∷ WithResult s m α withResult transPtr bufferPtr cont stop = do n ← peek $ p'libusb_transfer'actual_length transPtr if n ≡ 0 then stop $ Chunk empty else readFromPtr bufferPtr (fromIntegral n) >>= cont ∘ Chunk type WithResult s m α = Ptr C'libusb_transfer → Ptr Word8 → Run s m α -- To continue → Run s m α -- To stop → IO (Restore s m α) enum ∷ ∀ m s α . RegionControlIO m ⇒ C'TransferType → Int → [C'libusb_iso_packet_descriptor] → DeviceHandle → EndpointAddress → Timeout → Size → WithResult s m α → WithResult s m α → Enumerator s m α enum transType nrOfIsoPackets isoPackageDescs devHndl endpointAddr timeout chunkSize onCompletion onTimeout = \iter → unsafeControlIO $ \runInIO → withDevHndlPtr devHndl $ \devHndlPtr → allocaBytes chunkSize $ \bufferPtr → allocaTransfer nrOfIsoPackets $ \transPtr → do lock ← newLock let Just (evtMgr, mbHandleEvents) = getEventManager $ getCtx $ getDevice devHndl waitForTermination = case mbHandleEvents of Just handleEvents | timeout ≢ noTimeout → do tk ← registerTimeout evtMgr (timeout * 1000) handleEvents acquire lock `onException` (uninterruptibleMask_ $ do unregisterTimeout evtMgr tk _err ← c'libusb_cancel_transfer transPtr acquire lock) _ → acquire lock `onException` (uninterruptibleMask_ $ do _err ← c'libusb_cancel_transfer transPtr acquire lock) withCallback (\_ → release lock) $ \cbPtr → do poke transPtr $ C'libusb_transfer { c'libusb_transfer'dev_handle = devHndlPtr , c'libusb_transfer'flags = 0 -- unused , c'libusb_transfer'endpoint = marshalEndpointAddress endpointAddr , c'libusb_transfer'type = transType , c'libusb_transfer'timeout = fromIntegral timeout , c'libusb_transfer'status = 0 -- output , c'libusb_transfer'length = fromIntegral chunkSize , c'libusb_transfer'actual_length = 0 -- output , c'libusb_transfer'callback = cbPtr , c'libusb_transfer'user_data = nullPtr -- unused , c'libusb_transfer'buffer = castPtr bufferPtr , c'libusb_transfer'num_iso_packets = fromIntegral nrOfIsoPackets , c'libusb_transfer'iso_packet_desc = isoPackageDescs } let go ∷ Enumerator s m α go i = runIter i idoneM on_cont on_cont ∷ (Stream s → Iteratee s m α) → Maybe SomeException → m (Iteratee s m α) on_cont _ (Just e) = return $ throwErr e on_cont k Nothing = unsafeControlIO $ \runInIO' → mask $ \restore → do let stop, cont ∷ Run s m α stop = return ∘ return ∘ k cont = runInIO' ∘ go ∘ k ex ∷ USBException → IO (Restore s m α) ex = stop ∘ EOF ∘ Just ∘ toException err ← c'libusb_submit_transfer transPtr if err ≢ c'LIBUSB_SUCCESS then ex $ convertUSBException err else do waitForTermination restore $ do status ← peek $ p'libusb_transfer'status transPtr let run withResult = withResult transPtr bufferPtr cont stop case status of ts | ts ≡ c'LIBUSB_TRANSFER_COMPLETED → run onCompletion | ts ≡ c'LIBUSB_TRANSFER_TIMED_OUT → run onTimeout | ts ≡ c'LIBUSB_TRANSFER_ERROR → ex ioException | ts ≡ c'LIBUSB_TRANSFER_NO_DEVICE → ex NoDeviceException | ts ≡ c'LIBUSB_TRANSFER_OVERFLOW → ex OverflowException | ts ≡ c'LIBUSB_TRANSFER_STALL → ex PipeException | ts ≡ c'LIBUSB_TRANSFER_CANCELLED → moduleError "transfer status can't be Cancelled!" | otherwise → moduleError $ "Unknown transfer status: " ++ show ts ++ "!" runInIO $ go iter moduleError ∷ String → error moduleError msg = error $ thisModule ++ ": " ++ msg thisModule ∷ String thisModule = "System.USB.IO.Iteratee" needThreadedRTSError ∷ String → error needThreadedRTSError msg = moduleError $ msg ++ " is only supported when using the threaded runtime. " ++ "Please build your program with -threaded." -------------------------------------------------------------------------------- -- Isochronous -------------------------------------------------------------------------------- -- | Iteratee enumerator for reading /isochronous/ endpoints. -- -- /WARNING:/ You need to enable the threaded runtime (@-threaded@) for this -- function to work correctly. It throws a runtime error otherwise! enumReadIsochronous ∷ ∀ s m α . (ReadableChunk s Word8, RegionControlIO m) ⇒ DeviceHandle -- ^ A handle for the device to communicate with. → EndpointAddress -- ^ The address of a valid 'In' and 'Isochronous' -- endpoint to communicate with. Make sure the -- endpoint belongs to the current alternate -- setting of a claimed interface which belongs -- to the device. → [Size] -- ^ Sizes of isochronous packets. A good -- value for these would be the -- 'maxIsoPacketSize' → Timeout -- ^ Timeout (in milliseconds) that this -- function should wait for each chunk -- before giving up due to no response -- being received. → Enumerator [s] m α enumReadIsochronous devHndl endpointAddr sizes timeout | not threaded = needThreadedRTSError "enumReadIsochronous" | otherwise = enum c'LIBUSB_TRANSFER_TYPE_ISOCHRONOUS nrOfIsoPackets (map initIsoPacketDesc sizes) devHndl endpointAddr timeout totalSize onCompletion onTimeout where SumLength totalSize nrOfIsoPackets = sumLength sizes onCompletion, onTimeout ∷ WithResult [s] m α onCompletion transPtr bufferPtr cont _ = peekIsoPacketDescs nrOfIsoPackets transPtr >>= go bufferPtr id where go _ ss [] = cont $ Chunk $ ss [] go ptr ss (C'libusb_iso_packet_descriptor l a _ : ds) = do s ← readFromPtr ptr (fromIntegral a) go (ptr `plusPtr` fromIntegral l) (ss ∘ (s:)) ds onTimeout _ _ _ stop = stop ∘ EOF ∘ Just ∘ toException $ TimeoutException #endif -------------------------------------------------------------------------------- -- Synchronous -------------------------------------------------------------------------------- enumReadSync ∷ ∀ s m α . (ReadableChunk s Word8, NullPoint s, RegionControlIO m) ⇒ C'TransferFunc → ( DeviceHandle → EndpointAddress → Size → Timeout → Enumerator s m α ) enumReadSync c'transfer = \devHndl endpoint chunkSize timeout → \iter → unsafeControlIO $ \runInIO → withDevHndlPtr devHndl $ \devHndlPtr → alloca $ \transferredPtr → allocaBytes chunkSize $ \dataPtr → let go ∷ Enumerator s m α go i = runIter i idoneM on_cont on_cont ∷ (Stream s → Iteratee s m α) → Maybe SomeException → m (Iteratee s m α) on_cont _ (Just e) = return $ throwErr e on_cont k Nothing = unsafeControlIO $ \runInIO' → do let stop, cont ∷ Run s m α stop = return ∘ return ∘ k cont = runInIO' ∘ go ∘ k err ← c'transfer devHndlPtr (marshalEndpointAddress endpoint) (castPtr dataPtr) (fromIntegral chunkSize) transferredPtr (fromIntegral timeout) if err ≢ c'LIBUSB_SUCCESS ∧ err ≢ c'LIBUSB_ERROR_TIMEOUT then stop ∘ EOF ∘ Just ∘ toException $ convertUSBException err else do t ← peek transferredPtr if t ≡ 0 then stop $ Chunk empty else readFromPtr dataPtr (fromIntegral t) >>= cont ∘ Chunk in runInIO $ go iter
basvandijk/usb-safe
System/USB/Safe/Iteratee.hs
bsd-3-clause
19,490
2
49
7,889
2,983
1,645
1,338
96
4
{-| Module : Database.Relational.NotNull Description : Definition of NOT_NULL. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : aovieth@gmail.com Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} module Database.Relational.NotNull ( NOT_NULL(..) ) where data NOT_NULL = NOT_NULL
avieth/Relational
Database/Relational/NotNull.hs
bsd-3-clause
377
0
5
73
25
17
8
4
0
{-# LANGUAGE NoImplicitPrelude #-} -- | -- Module: $HEADER$ -- Description: TODO -- Copyright: (c) 2014, 2015 Peter Trsko -- License: BSD3 -- -- Maintainer: peter.trsko@gmail.com -- Stability: experimental -- Portability: NoImplicitPrelude -- -- TODO module Main.Type.OptionsConfig ( OptionsConfig(..) , variableDefines , templateSearchQuery , outputFile ) where import Data.Maybe (Maybe(Nothing)) import System.IO (FilePath) import Text.Show (Show) import Control.Lens (Lens', lens) import Data.Default.Class (Default(def)) import Skeletos.Type.Define (Define) import Skeletos.Type.Query (QueryAtom) data OptionsConfig = OptionsConfig { _variableDefines :: [Define] , _outputFile :: Maybe FilePath -- ^ Is either 'Data.Maybe.Nothing' or 'Data.Maybe.Just' non-empty string. -- Invariant of non-empty string is preserved by 'filePath' parser. , _templateSearchQuery :: [QueryAtom] } deriving (Show) instance Default OptionsConfig where def = OptionsConfig { _variableDefines = [] , _outputFile = Nothing , _templateSearchQuery = [] } variableDefines :: Lens' OptionsConfig [Define] variableDefines = _variableDefines `lens` \s b -> s{_variableDefines = b} outputFile :: Lens' OptionsConfig (Maybe FilePath) outputFile = _outputFile `lens` \s b -> s{_outputFile = b} templateSearchQuery :: Lens' OptionsConfig [QueryAtom] templateSearchQuery = _templateSearchQuery `lens` \s b -> s{_templateSearchQuery = b}
trskop/skeletos
src/Main/Type/OptionsConfig.hs
bsd-3-clause
1,537
0
9
305
323
202
121
30
1
{-| Module : Tree Description : Tests for Network.Kademlia.Tree Tests specific to Network.Kademlia.Tree. -} module Tree where import Test.QuickCheck import qualified Network.Kademlia.Tree as T import Network.Kademlia.Types import Control.Monad (liftM) import Data.List (sortBy) import Data.Maybe (isJust) import TestTypes -- | Helper method for lookup checking lookupCheck :: (Serialize i, Eq i) => T.NodeTree i -> Node i -> Bool lookupCheck tree node = T.lookup tree (nodeId node) == Just node -- | Check wether an inserted Node is retrievable insertCheck :: IdType -> Node IdType -> Bool insertCheck id node = lookupCheck tree node where tree = T.insert (T.create id) node -- | Make sure a deleted Node can't be retrieved anymore deleteCheck :: IdType -> Node IdType -> Bool deleteCheck id node = not . lookupCheck tree $ node where tree = T.delete origin . nodeId $ node origin = T.insert (T.create id) node withTree :: (T.NodeTree IdType -> [Node IdType] -> a) -> NodeBunch IdType -> IdType -> a withTree f bunch id = f tree $ nodes bunch where tree = foldr (flip T.insert) (T.create id) $ nodes bunch splitCheck :: NodeBunch IdType -> IdType -> Property splitCheck = withTree f where f tree nodes = conjoin . foldr (foldingFunc tree) [] $ nodes tree `contains` node = node `elem` T.toList tree foldingFunc tree node props = prop : props where prop = counterexample ("Failed to find " ++ show node) $ -- There is the possibiliy that nodes weren't inserted -- because of full buckets. lookupCheck tree node || not (tree `contains` node) -- | Make sure the bucket sizes end up correct bucketSizeCheck :: NodeBunch IdType -> IdType -> Bool bucketSizeCheck = withTree $ \tree _ -> T.fold foldingFunc True tree where foldingFunc _ False = False foldingFunc b _ = length b <= 7 -- | Make sure refreshed Nodes are actually refreshed refreshCheck :: NodeBunch IdType -> IdType -> Bool refreshCheck = withTree f where f tree nodes = T.fold foldingFunc True refreshed where refreshed = T.insert tree node node = last nodes foldingFunc _ False = False foldingFunc b _ = node `notElem` b || head b == node -- | Make sure findClosest returns the Node with the closest Ids of all nodes -- in the tree. findClosestCheck :: IdType -> NodeBunch IdType -> IdType -> Property findClosestCheck id = withTree f where f tree nodes = conjoin . foldr g [] $ manualClosest where g node props = counterexample (text node) (prop node):props where prop node = node `elem` treeClosest text node = "Failed to find: " ++ show node treeClosest = T.findClosest tree id 7 contained = filter contains nodes contains node = isJust . T.lookup tree . nodeId $ node manualClosest = map fst . take 7 . sort $ packed packed = zip contained $ map distanceF contained distanceF = distance id . nodeId sort = sortBy $ \(_, a) (_, b) -> compare a b
froozen/kademlia
test/Tree.hs
bsd-3-clause
3,290
0
14
970
934
478
456
54
2
{-# LANGUAGE TypeOperators #-} -- For :+: in signatures {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} import Data.Char import Data.Machine import qualified Data.Map as Map {- Simplest possible machine ------------------------- To do something useful, you need to call run, run :: MachineT Identity k b -> [b] The constructor for a MachineT is MachineT runMachineT :: m (Step k o (MachineT m k o)) In this simplest case m is Identity, so MachineT runMachineT :: Identity (Step k o (MachineT Identity k o)) The `Step k o r` functor is the base functor for a Machine or MachineT, and is normally generated via a `Plan`. This wants a Machine generating b, and will result in a list of b, with monadic effect A Machine gets built from a Plan. A Plan can be considered to be built up from one of the following primitives data Plan k o a = Done a | Yield o (Plan k o a) | forall z. Await (z -> Plan k o a) (k z) (Plan k o a) | Fail This Plan is a specification for a pure Machine, that reads inputs selected by k with types based on i, writes values of type o, and has intermediate results of type a. (What is `i`?) The simplest possible plan is simply yield b -} plana :: PlanT k Char m () plana = yield 'a' {- We make a Machine from the Plan. The type context must be properly defined or the construction will fail construct :: Monad m => PlanT k o m a -> MachineT m k o -} machinea :: Monad m => MachineT m k Char machinea = construct plana -- |simplest machine, using Identity Monad for pure results simplest :: [Char] simplest = run machinea {- *Main> simplest "a" *Main> Slightly more complex one, repeated data ---------------------------------------- type Source b = Monad m => MachineT m k b -} schar :: Source Char schar = source "abcde" {- Note: *Main> :t schar schar :: Monad m => MachineT m k Char *Main> run schar "abcde" A process that does not let the character b through -} nob :: Process Char Char nob = filtered (/='b') {- *Main> :t schar ~> nob schar ~> nob :: Monad m => MachineT m k Char *Main> run $ schar ~> nob "acde" *Main> Terminology (hand waving) Plan : is used to compose Machines Machine : is run to generate useful output. Generalisation of Source and Process Source : Machine generating output only. Effectively anchors one side of the processing chain with input Process : Machine that takes input of one type, transforms it, and generates output of a possible different type Automaton : for later investigation More pieces ----------- cap attaches a process to a source, generating a new source *Main> :t cap cap :: Monad m => Process a b -> Source a -> MachineT m k b *Main> :t cap nob schar cap nob schar :: Monad m => MachineT m k Char *Main> run $ cap nob schar "acde" *Main> How do we make a plan? ---------------------- From the slides stop :: Plan k o a The next primitives are used to sequence processing inside the Machine generated from the plan Generate output yield :: o -> Plan k o () Wait for input await :: Category k => Plan (k i) o i So k must have identity and composition awaits :: k i -> Plan k o i Think of it as 'await specific' Converting a plan into a Machine -------------------------------- construct :: Monad m => PlanT k o m a -> MachineT m k o Compile a machine to a model. repeatedly :: Monad m => PlanT k o m a -> MachineT m k o Generates a model that runs a machine until it stops, then start it up again. before :: Monad m => MachineT m k o -> PlanT k o m a -> MachineT m k o Evaluate a machine until it stops, and then yield answers according to the supplied model. Also to connect different machines fit :: Monad m => (forall a. k a -> k' a) -> MachineT m k o -> MachineT m k' o connect different kinds of machines, swapping one k function for another fitM :: (Monad m, Monad m') => (forall a. m a -> m' a) -> MachineT m k o -> MachineT m' k o connect different kinds of machines, swapping one monad for another pass :: k o -> Machine k o Given a handle, ignore all other inputs and just stream input from that handle The k functions define the sources, and how they are connected. There are two types, a Tee and a Wye. What is a Tee? ------------- A 'Machine' that can read from two input stream in a deterministic manner. type Tee a b c = Machine (T a b) c type TeeT m a b c = MachineT m (T a b) c Monadic version of Tee The `T` data type defines the input as follows data T a b c where Constructors L :: T a b a R :: T a b b This defines a type which can either have an L value or an R one, and takes a function (or Monad) generating the expected output type 'a' depending on which kind of input is presented. -} {- So lets try interleaving input from two sources -} streama,streamb :: Machine m Char streama = source "abcde" streamb = source "vwxyz" {- :t tee streama streamb tee streama streamb :: Monad m => TeeT m Char Char c -> TeeT m a b c I think the following is defined to read from two streams of Char, and generate output of Char -} -- myInterleave :: Tee Char Char Char -> Machine (((->) Char) :+: ((->) Char)) Char myInterleave :: Monad m => TeeT m Char Char c -> TeeT m a b c myInterleave = tee streama streamb myTee :: Tee Char Char Char myTee = repeatedly $ do x <- awaits L yield x y <- awaits R yield y -- myInterleave' :: Machine ((a -> Char) :+: (b -> Char)) Char myInterleave' :: Monad m => TeeT m a b Char myInterleave' = tee streama streamb myTee {- *Main> run myInterleave' "avbwcxdyez" *Main> -} -- --------------------------------------------------------------------- {- Exploring the Wye ----------------- type Wye a b c = Machine (Y a b) c A Machine that can read from two input stream in a non-deterministic manner. type WyeT m a b c = MachineT m (Y a b) c A Machine that can read from two input stream in a non-deterministic manner with monadic side-effects. The input descriptor for a Wye or WyeT data Y a b c where Constructors X :: Y a b a Y :: Y a b b Z :: Y a b (Either a b) So effectively a Wye is a heterogenous Tee, in that the two sources can feed different data types in. This could probably be emulated by appropriate choice of data type in a Tee The `wye` function is used to precompose two processes onto a Wye wye : Monad m => ProcessT m a a' -> ProcessT m b b' -> WyeT m a' b' c -> WyeT m a b c -} streamn :: Machine m Int streamn = source [1,2,3,4,5] -- |round robin input from the Wye myWye :: (Monad m) => MachineT m (Y Char Int) String myWye = repeatedly $ do x <- awaits X yield [x] y <- awaits Y yield (show y) wm :: Monad m => WyeT m Char Int String wm = wye streama streamn myWye {- *Main> run wm ["a","1","b","2","c","3","d","4","e","5"] *Main> -} -- | left-biased input from the Y, as per the implementation of `wye` myWye2 :: (Monad m) => MachineT m (Y Char Int) String myWye2 = repeatedly $ do x <- awaits Z case x of Left c -> yield [c] Right i -> yield (show i) wm2 :: Monad m => WyeT m Char Int String wm2 = wye streama streamn myWye2 {- Note: prioritises the one source over the other. This is a feature of 'wye' *Main> run wm2 ["a","b","c","d","e","1","2","3","4","5"] *Main> -} main = putStrLn "done" {- Experimenting with state machines ---------------------------------- Moore Machine : output values are determined solely by its current state. data Moore a b Constructors Moore b (a -> Moore a b) Mealy Machine : output values are determined both by its current state and the current inputs. newtype Mealy a b Constructors Mealy runMealy :: a -> (b, Mealy a b) Construct a Moore machine from a state valuation and transition function unfoldMoore :: (s -> (b, a -> s)) -> s -> Moore a b -} {- Construct a simple Moore machine -------------------------------- This will have two states, and every time there is an input it changes state. -} data M1State = M1A | M1B deriving (Eq,Show,Ord) -- We will arbitrarily choose a Char type for input -- |Transition function from state M1A m1TransitionFmA :: Char -> Moore Char M1State m1TransitionFmA _ = Moore M1B m1TransitionFmB -- |Transition function from state M1B m1TransitionFmB :: Char -> Moore Char M1State m1TransitionFmB _ = Moore M1A m1TransitionFmA -- |Starting state and transitions for the machine m1 :: Moore Char M1State m1 = Moore M1A m1TransitionFmA -- Turn the Moore state machine into a process m1a :: Monad m => MachineT m (Is Char) M1State m1a = auto m1 m1m :: Monad m => MachineT m k M1State m1m = (source "abcde") ~> m1a {- *Main> run m1m [M1A,M1B,M1A,M1B,M1A,M1B] *Main> -} {- Construct a simple Mealy machine -------------------------------- This will have two states, and every time there is an input it changes state, and outputs the char used to transition. data Moore a b Constructors Moore b (a -> Moore a b) newtype Mealy a b Constructors Mealy runMealy :: a -> (b, Mealy a b) -} m2Mealy :: Char -> (M1State, Mealy Char M1State) m2Mealy = m2TransitionFmA m2TransitionFmA :: Char -> (M1State, Mealy Char M1State) m2TransitionFmA _ = (M1B,Mealy m2TransitionFmB) m2TransitionFmB :: Char -> (M1State, Mealy Char M1State) m2TransitionFmB _ = (M1A,Mealy m2TransitionFmA) m2 :: Mealy Char M1State m2 = Mealy m2TransitionFmA -- Turn the Mealy state machine into a process m2a :: Monad m => MachineT m (Is Char) M1State m2a = auto m2 m2m :: Monad m => MachineT m k M1State m2m = (source "abcde") ~> m2a {- *Main> run m2m [M1B,M1A,M1B,M1A,M1B] *Main> -} -- How is this different from the Moore machine? -- Moore b (a -> Moore a b) -- Mealy (a -> (b, Mealy a b)) -- Moore gives a state, and a function mapping from input to next state -- Mealy gives a function mapping from input to next (state,transition) -- When they run we only see the state as output. {- A Moore machine can be defined as a 6-tuple ( S, S0, Σ, Λ, T, G ) consisting of the following: a finite set of states ( S ) a start state (also called initial state) S0 which is an element of (S) a finite set called the input alphabet ( Σ ) a finite set called the output alphabet ( Λ ) a transition function (T : S × Σ → S) mapping a state and the input alphabet to the next state an output function (G : S → Λ) mapping each state to the output alphabet A Moore machine can be regarded as a restricted type of finite state transducer. A Mealy machine is a 6-tuple, (S, S0, Σ, Λ, T, G), consisting of the following: a finite set of states (S) a start state (also called initial state) S0 which is an element of (S) a finite set called the input alphabet (Σ) a finite set called the output alphabet (Λ) a transition function (T : S × Σ → S) mapping pairs of a state and an input symbol to the corresponding next state. an output function (G : S × Σ → Λ) mapping pairs of a state and an input symbol to the corresponding output symbol. In some formulations, the transition and output functions are coalesced into a single function (T : S × Σ → S × Λ). It seems that in this formulation the states and output alphabet have been coalesced -} {- Mealy XOR example from https://en.wikipedia.org/wiki/Mealy_machine [Note, seems to be an error in the diagram, two states labelled S1] S = { S0,S1,Si} S0 = Si Σ = {0,1} Λ = {0,1} T : S × Σ → S × Λ = Si 0 -> (S0,0) Si 1 -> (S1,0) S0 0 -> (S0,0) S0 1 -> (S1,1) S1 0 -> (S0,1) S1 1 -> (S1,0) -} data XIn = I0 | I1 deriving (Eq,Show,Ord) data XOut = O0 | O1 deriving (Eq,Show) data XState = S0 XOut | S1 XOut | Si XOut deriving (Eq,Show) m3Mealy :: XIn -> (XState, Mealy XIn XState) m3Mealy = m3TransitionFmSi m3TransitionFmSi :: XIn -> (XState, Mealy XIn XState) m3TransitionFmSi I0 = (S0 O0,Mealy m3TransitionFmS0) m3TransitionFmSi I1 = (S1 O0,Mealy m3TransitionFmS1) m3TransitionFmS0 :: XIn -> (XState, Mealy XIn XState) m3TransitionFmS0 I0 = (S0 O0,Mealy m3TransitionFmS0) m3TransitionFmS0 I1 = (S1 O1,Mealy m3TransitionFmS1) m3TransitionFmS1 :: XIn -> (XState, Mealy XIn XState) m3TransitionFmS1 I0 = (S0 O1,Mealy m3TransitionFmS0) m3TransitionFmS1 I1 = (S1 O0,Mealy m3TransitionFmS1) m3 :: Mealy XIn XState m3 = Mealy m3TransitionFmSi -- Turn the Mealy state machine into a process m3a :: Monad m => MachineT m (Is XIn) XState m3a = auto m3 m3m :: Monad m => MachineT m k XState m3m = (source [I0,I0,I0,I1,I1,I1,I0,I0]) ~> m3a {- *Main> run m3m [S0 O0,S0 O0,S0 O0,S1 O1,S1 O0,S1 O0,S0 O1,S0 O0] *Main> -} -- --------------------------------------------------------------------- -- |Transition function from state M4A m4TransitionFmSi :: XIn -> Moore XIn XState m4TransitionFmSi I0 = Moore (S0 O0) m4TransitionFmS0 m4TransitionFmSi I1 = Moore (S1 O0) m4TransitionFmS1 m4TransitionFmS0 I0 = Moore (S0 O0) m4TransitionFmS0 m4TransitionFmS0 I1 = Moore (S1 O1) m4TransitionFmS1 m4TransitionFmS1 I0 = Moore (S0 O1) m4TransitionFmS0 m4TransitionFmS1 I1 = Moore (S1 O0) m4TransitionFmS1 -- |Starting state and transitions for the machine m4 :: Moore XIn XState m4 = Moore (Si O0) m4TransitionFmSi -- Turn the Moore state machine into a process m4a :: Monad m => MachineT m (Is XIn) XState m4a = auto m4 m4m :: Monad m => MachineT m k XState m4m = (source [I0,I0,I0,I1,I1,I1,I0,I0]) ~> m4a {- *Main> run m4m [Si O0,S0 O0,S0 O0,S0 O0,S1 O1,S1 O0,S1 O0,S0 O1,S0 O0] *Main> -} {- [Si O0 ,S0 O0 ,S0 O0 ,S0 O0 ,S1 O1 ,S1 O0 ,S1 O0 ,S0 O1 ,S0 O0] -} -- Meally [Si O0,S0 O0,S0 O0,S0 O0,S1 O1,S1 O0,S1 O0,S0 O1,S0 O0] -- Moore [S0 O0,S0 O0,S0 O0,S1 O1,S1 O0,S1 O0,S0 O1,S0 O0] -- ----------------------------------------------- -- understanding unfoldMoore -- ------------------------- -- [copied here for inspection] -- | Construct a Moore machine from a state valuation and transition function unfoldMoore1 :: (s -> (b, a -> s)) -> s -> Moore a b unfoldMoore1 f = go where go s = case f s of (b, g) -> Moore b (go . g) {-# INLINE unfoldMoore1 #-} {- First call uses s to generate (b, a -> s) -- current state, function from input seen to next state Redoing the first two state example, using XIn: -} m6Fm1A :: XIn -> M1State m6Fm1A _ = M1B m6Fm1B :: XIn -> M1State m6Fm1B _ = M1A fMoore :: M1State -> (M1State, XIn -> M1State) fMoore M1A = (M1A,m6Fm1A) fMoore M1B = (M1B,m6Fm1B) m6 :: Moore XIn M1State m6 = unfoldMoore fMoore M1A m6m :: Monad m => MachineT m k M1State m6m = (source [I0,I1,I1,I1,I0]) ~> auto m6 {- *Main> run m6m [M1A,M1B,M1A,M1B,M1A,M1B] *Main> -} -- --------------------------------------------------------------------- -- newtype Mealy a b -- Constructors -- Mealy runMealy :: a -> (b, Mealy a b) -- unfoldMealy :: (s -> a -> (b, s)) -> s -> Mealy a b -- Here a is XIn, -- b is XState initial :: [s] initial = [] fMealy :: [s] -> XIn -> (XState,[s]) fMealy [] = error "empty list" -- fMealy (x:xs) m5 :: Mealy XIn XState m5 = unfoldMealy fMealy initial -- | A 'Mealy' machine modeled with explicit state. unfoldMealy1 :: (s -> a -> (b, s)) -> s -> Mealy a b unfoldMealy1 f = go where go s = Mealy $ \a -> case f s a of (b, t) -> (b, go t) {-# INLINE unfoldMealy1 #-}
bitemyapp/machines-play
Main.hs
bsd-3-clause
15,431
0
13
3,436
2,012
1,070
942
132
2
{-# LANGUAGE LambdaCase, TupleSections, RecordWildCards, OverloadedStrings #-} module Transformations.Optimising.Inlining where import Debug.Trace import Text.Printf import Data.Set (Set) import qualified Data.Set as Set import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Functor.Foldable as Foldable import qualified Data.Foldable import Grin.Grin import Grin.TypeEnv import Transformations.Util import Transformations.Names import Data.Bifunctor (first) -- analysis data Stat = Stat { bindCount :: !Int , functionCallCount :: !(Map Name Int) } instance Semigroup Stat where (Stat i1 m1) <> (Stat i2 m2) = Stat (i1 + i2) (Map.unionWith (+) m1 m2) instance Monoid Stat where mempty = Stat 0 mempty selectInlineSet :: Program -> Set Name selectInlineSet prog@(Program exts defs) = inlineSet where (bindList, callTrees) = unzip [ (Map.singleton name bindCount, (name, functionCallCount)) | def@(Def name _ _) <- defs , let Stat{..} = cata folder def ] bindSequenceLimit = 100 -- TODO: limit inline overhead using CALL COUNT * SIZE < LIMIT callSet = Map.keysSet . Map.filter (== 1) . Map.unionsWith (+) $ map snd callTrees bindSet = Map.keysSet . Map.filter (< bindSequenceLimit) $ mconcat bindList candidateSet = mconcat [bindSet `Set.intersection` leafSet, callSet] defCallTree = Map.fromList callTrees leafSet = Set.fromList [name | (name, callMap) <- callTrees, Map.null callMap] -- keep only the leaves of the candidate call tree inlineSet = Set.delete "grinMain" $ Data.Foldable.foldr stripCallers candidateSet candidateSet -- remove intermediate nodes from the call tree stripCallers name set = set Set.\\ (Map.keysSet $ Map.findWithDefault mempty name defCallTree) folder :: ExpF Stat -> Stat folder = \case EBindF left _ right -> mconcat [left, right, Stat 1 mempty] SAppF name _ | not (isExternalName exts name) -> Stat 0 $ Map.singleton name 1 exp -> Data.Foldable.fold exp -- transformation -- TODO: add the cloned variables to the type env -- QUESTION: apo OR ana ??? inlining :: Set Name -> TypeEnv -> Program -> (Program, ExpChanges) inlining functionsToInline typeEnv prog@(Program exts defs) = evalNameM prog $ apoM builder prog where defMap :: Map Name Def defMap = Map.fromList [(name, def) | def@(Def name _ _) <- defs] builder :: Exp -> NameM (ExpF (Either Exp Exp)) builder = \case -- HINT: do not touch functions marked to inline Def name args body | Set.member name functionsToInline -> pure . DefF name args $ Left body -- HINT: bind argument values to function's new arguments and append the body with the fresh names -- with this solution the name refreshing is just a name mapping and does not require a substitution map SApp name argVals | Set.member name functionsToInline , Just def <- Map.lookup name defMap -> do freshDef <- refreshNames mempty def let (Def _ argNames funBody, nameMap) = freshDef let bind (n,v) e = EBind (SReturn v) (Var n) e pure . SBlockF . Left $ foldr bind funBody (zip argNames argVals) exp -> pure (Right <$> project exp) {- - maintain type env - test inlining - test inline selection - test inline: autoselection + inlining -} lateInlining :: TypeEnv -> Exp -> (Exp, ExpChanges) lateInlining typeEnv prog = first (cleanup nameSet typeEnv) $ inlining nameSet typeEnv prog where nameSet = selectInlineSet prog inlineEval :: TypeEnv -> Exp -> (Exp, ExpChanges) inlineEval te = first (cleanup nameSet te) . inlining nameSet te where nameSet = Set.fromList ["eval", "idr_{EVAL_0}"] inlineApply :: TypeEnv -> Exp -> (Exp, ExpChanges) inlineApply te = first (cleanup nameSet te) . inlining nameSet te where nameSet = Set.fromList ["apply", "idr_{APPLY_0}"] inlineBuiltins :: TypeEnv -> Exp -> (Exp, ExpChanges) inlineBuiltins te = first (cleanup nameSet te) . inlining nameSet te where nameSet = Set.fromList ["_rts_int_gt", "_rts_int_add", "_rts_int_print"] -- TODO: use proper selection cleanup :: Set Name -> TypeEnv -> Program -> Program cleanup nameSet typeEnv (Program exts defs) = Program exts [def | def@(Def name _ _) <- defs, Set.notMember name nameSet]
andorp/grin
grin/src/Transformations/Optimising/Inlining.hs
bsd-3-clause
4,299
0
18
876
1,328
692
636
78
3
{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving #-} {- | Module : $Header$ Description : Validation of M4 type statements Copyright : (c) Galois, Inc. Validation of M4 type statements -} module SCD.M4.CheckTypeStmt(checkInterface) where import SCD.M4.Syntax(Interface(..), InterfaceElement(..), InterfaceType(..), Stmt(..), M4Id) -- | Return a list of interface names paired with type-declaration -- statements, found in interface bodies that declare new types. checkInterface :: Interface -> [(M4Id, Stmt)] checkInterface (InterfaceModule _ ies) = concatMap checkInterfaceElement ies checkInterfaceElement :: InterfaceElement -> [(M4Id, Stmt)] checkInterfaceElement (InterfaceElement InterfaceType _ i ss) = [(i,e) | e <- checkStmts ss] checkInterfaceElement (InterfaceElement TemplateType _ _ _) = [] checkStmts :: [Stmt] -> [Stmt] checkStmts = concatMap checkStmt checkStmt :: Stmt -> [Stmt] checkStmt (Tunable _ s1 s2) = checkStmts s1 ++ checkStmts s2 checkStmt (Optional s1 s2) = checkStmts s1 ++ checkStmts s2 checkStmt (Ifdef _ s1 s2) = checkStmts s1 ++ checkStmts s2 checkStmt (Ifndef _ s1) = checkStmts s1 checkStmt (RefPolicyWarn _) = [] checkStmt (Call _ _) = [] checkStmt (Role _ _) = [] checkStmt (RoleTransition _ _ _) = [] checkStmt (RoleAllow _ _) = [] checkStmt (Attribute _) = [] checkStmt s@(Type _ _ _) = [s] checkStmt (TypeAlias _ _) = [] checkStmt (TypeAttribute _ _) = [] checkStmt (RangeTransition _ _ _ _) = [] checkStmt (TeNeverAllow _ _) = [] checkStmt (Transition _ _ _) = [] checkStmt (TeAvTab _ _ _) = [] checkStmt (CondStmt _ s1 s2) = checkStmts s1 ++ checkStmts s2 checkStmt (XMLDocStmt _) = [] checkStmt (SidStmt _) = [] checkStmt (FileSystemUseStmt _) = [] checkStmt (GenFileSystemStmt _) = [] checkStmt (PortStmt _) = [] checkStmt (NetInterfaceStmt _) = [] checkStmt (NodeStmt _) = [] checkStmt (Define _) = [] checkStmt (Require _) = [] checkStmt (GenBoolean _ _ _) = []
GaloisInc/sk-dev-platform
libs/SCD/src/SCD/M4/CheckTypeStmt.hs
bsd-3-clause
2,201
0
8
580
748
389
359
41
1
{-# LANGUAGE FlexibleInstances #-} module System.Armory.Types ( Platform(..) , Version , Architecture(..) , Name , InstructionsMap , Program(..) , Config(..) , makeDefaultConfig ) where import Control.Applicative ((<$>), (<*>), empty, pure) import Data.Version (showVersion) import System.Info (os) import Data.Aeson ( (.:) , (.=) , FromJSON(..) , ToJSON(..) , Value(..) , object ) import Data.HashMap.Strict (foldrWithKey) import qualified Data.Map as M (Map, empty, foldrWithKey, insert, singleton) import Data.Text (Text, pack, unpack) import Data.Vector (toList) import System.Directory (doesFileExist) import Paths_armory (version) data Platform = Debian | Windows | Unknown Text deriving (Eq, Ord) instance Read Platform where readsPrec _ "debian" = [(Debian, "")] readsPrec _ "windows" = [(Windows, "")] readsPrec _ u = [(Unknown $ pack u, "")] instance Show Platform where show Debian = "debian" show Windows = "windows" show (Unknown u) = unpack u instance FromJSON Platform where parseJSON (String s) = pure $ read $ unpack s parseJSON _ = empty instance ToJSON Platform where toJSON = String . pack . show type Version = Text data Architecture = Architecture Platform Version | All deriving (Eq, Ord) instance Read Architecture where readsPrec _ "all" = [(All, "")] readsPrec _ arch = let (platform, version') = span (/= '@') arch in [(Architecture (read platform) (pack version'), "")] instance Show Architecture where show (Architecture platform version') = show platform ++ unpack version' show All = "all" instance FromJSON Architecture where parseJSON (String s) = pure $ read $ unpack s parseJSON _ = empty instance ToJSON Architecture where toJSON = String . pack . show type Name = Text type InstructionsMap = M.Map Architecture [Text] instance (ToJSON v) => ToJSON (M.Map Architecture v) where toJSON = object . M.foldrWithKey folder [] where -- where clause indentation is a little weird here folder arch value pairs = pairs ++ [pack (show arch) .= value] data Program = Program Name InstructionsMap deriving (Eq, Ord, Read, Show) parseInstructionsMap :: Value -> InstructionsMap parseInstructionsMap (Object o) = foldrWithKey parseInstructions M.empty o where stringUnwrapper :: Value -> Text stringUnwrapper (String s) = s stringUnwrapper v = error $ "Expected an instruction as a String, instead received: " ++ show v parseInstructions :: Text -> Value -> InstructionsMap -> InstructionsMap parseInstructions arch (Array a) = M.insert (read $ unpack arch) (map stringUnwrapper $ toList a) parseInstructions arch v = error $ "Expected an array of instructions for " ++ show arch ++ ", instead received: " ++ show v parseInstructionsMap v = error $ "Expected a mapping of architectures to instructions, instead received: " ++ show v instance FromJSON Program where parseJSON (Object o) = Program <$> o .: "name" <*> (parseInstructionsMap <$> o .: "install") parseJSON _ = empty instance ToJSON Program where toJSON (Program name instructionsMap) = object [ "name" .= name , "install" .= instructionsMap ] data Config = Config { architecture :: Architecture , installer :: Text , uninstaller :: Text , programs :: [Program] } deriving (Eq, Ord, Read, Show) -- Can't use data-default due to overlapping instance of `Data.Default a => Data.Default (IO a)` and `IO Config` here. makeDefaultConfig :: IO Config makeDefaultConfig = do archGuess <- do debian <- doesFileExist "/etc/debian_version" if debian then return Debian else if os == "mingw32" then return Windows else return $ Unknown $ pack os (installer', uninstaller') <- case archGuess of Debian -> return ("apt-get install -y", "apt-get remove -y --purge") Windows -> return ("choco install -y", "choco uninstall -y") Unknown _ -> do putStrLn "Unrecognized operating system." putStr "What command do you install programs with? (e.g. `apt-get install -y` on Debian) " installer'' <- pack <$> getLine putStr "What command do you remove programs with? (e.g. `apt-get remove -y --purge` on Debian) " uninstaller'' <- pack <$> getLine return (installer'', uninstaller'') let arch = Architecture archGuess "" return $ Config arch installer' uninstaller' [ Program (pack $ "armory@" ++ showVersion version) (M.singleton arch ["armory install armory"]) ] instance FromJSON Config where parseJSON (Object o) = Config <$> o .: "architecture" <*> o .: "installer" <*> o .: "uninstaller" <*> o .: "programs" parseJSON _ = empty instance ToJSON Config where toJSON (Config a i u p) = object [ "architecture" .= a , "installer" .= i , "uninstaller" .= u , "programs" .= p ]
chrisdotcode/armory
System/Armory/Types.hs
bsd-3-clause
5,390
0
14
1,553
1,476
789
687
135
5
{-# LANGUAGE TypeFamilies #-} module EFA.Flow.Storage.Quantity where import qualified EFA.Flow.Storage.Variable as StorageVar import qualified EFA.Flow.Storage.Index as StorageIdx import qualified EFA.Flow.Storage as Storage import qualified EFA.Flow.Topology.Quantity as FlowTopo import qualified EFA.Flow.Part.Index as PartIdx import qualified EFA.Flow.Part.Map as PartMap import qualified EFA.Flow.SequenceState.Variable as Var import qualified EFA.Flow.SequenceState.Index as Idx import EFA.Equation.Unknown (Unknown(unknown)) import qualified Data.Traversable as Trav import qualified Data.Map as Map ; import Data.Map (Map) import Control.Applicative (Applicative, pure, liftA2, (<*>), (<$>)) import Data.Foldable (Foldable) import Data.Monoid (Monoid) type Graph carry a = Storage.Graph (CarryPart carry) a (carry a) class (Applicative f, Foldable f) => Carry f where carryEnergy, carryXOut, carryXIn :: f a -> a foldEnergy :: (Monoid m) => (a -> m) -> f a -> m type CarryPart f :: * carryVars :: (CarryPart f ~ part) => f (StorageIdx.Edge part -> StorageVar.Scalar part) mapGraphWithVar :: (Carry carry, CarryPart carry ~ part, PartIdx.Format part, Show part) => (Idx.PartNode part node -> Maybe (FlowTopo.Sums v)) -> (Var.Scalar part node -> a0 -> a1) -> node -> Graph carry a0 -> Graph carry a1 mapGraphWithVar lookupSums f node (Storage.Graph partMap edges) = Storage.Graph (PartMap.mapWithVar (maybe (error "mapStoragesWithVar: missing corresponding sum") FlowTopo.dirFromSums . lookupSums) f node partMap) (Map.mapWithKey (mapCarryWithVar f node) edges) mapCarryWithVar :: (Carry carry, CarryPart carry ~ part) => (Var.Scalar part node -> a0 -> a1) -> node -> StorageIdx.Edge part -> carry a0 -> carry a1 mapCarryWithVar f node edge = liftA2 f (Idx.ForStorage <$> (carryVars <*> pure edge) <*> pure node) mapGraph :: (Functor carry, CarryPart carry ~ part, Ord part) => (a0 -> a1) -> Graph carry a0 -> Graph carry a1 mapGraph f = Storage.mapNode f . Storage.mapEdge (fmap f) traverseGraph :: (Applicative f, Trav.Traversable carry, CarryPart carry ~ part, Ord part) => (a0 -> f a1) -> Graph carry a0 -> f (Graph carry a1) traverseGraph f = Storage.traverse f (Trav.traverse f) forwardEdgesFromSums :: (Ord part) => Map part (FlowTopo.Sums v) -> [StorageIdx.Edge part] forwardEdgesFromSums stores = do let ins = Map.mapMaybe FlowTopo.sumIn stores let outs = Map.mapMaybe FlowTopo.sumOut stores secin <- Idx.Init : map Idx.NoInit (Map.keys ins) secout <- (++[Idx.Exit]) $ map Idx.NoExit $ Map.keys $ case secin of Idx.Init -> outs Idx.NoInit s -> snd $ Map.split s outs return $ StorageIdx.Edge secin secout allEdgesFromSums :: (Ord part) => Map part (FlowTopo.Sums a) -> [StorageIdx.Edge part] allEdgesFromSums stores = liftA2 StorageIdx.Edge (Idx.Init : map Idx.NoInit (Map.keys (Map.mapMaybe FlowTopo.sumIn stores))) (Idx.Exit : map Idx.NoExit (Map.keys (Map.mapMaybe FlowTopo.sumOut stores))) graphFromList :: (Carry carry, CarryPart carry ~ part, Ord part, Unknown a) => [part] -> [StorageIdx.Edge part] -> Graph carry a graphFromList sts edges = Storage.Graph (PartMap.constant unknown sts) (Map.fromListWith (error "duplicate storage edge") $ map (flip (,) (pure unknown)) edges) lookupEnergy :: (Carry carry, CarryPart carry ~ part, Ord part) => StorageIdx.Energy part -> Graph carry a -> Maybe a lookupEnergy (StorageIdx.Energy se) sgr = fmap carryEnergy $ Storage.lookupEdge se sgr lookupX :: (Carry carry, CarryPart carry ~ part, Ord part) => StorageIdx.X part -> Graph carry a -> Maybe a lookupX (StorageIdx.X se) sgr = StorageIdx.withEdgeFromPosition (fmap carryXIn . flip Storage.lookupEdge sgr) (fmap carryXOut . flip Storage.lookupEdge sgr) se {- | It is an unchecked error if you lookup StInSum where is only an StOutSum. -} lookupInSum :: (Carry carry, CarryPart carry ~ part, Ord part) => StorageIdx.InSum part -> Graph carry a -> Maybe a lookupInSum (StorageIdx.InSum aug) (Storage.Graph partMap _) = case aug of Idx.Exit -> return $ PartMap.exit partMap Idx.NoExit sec -> Map.lookup sec $ PartMap.parts partMap {- | It is an unchecked error if you lookup StOutSum where is only an StInSum. -} lookupOutSum :: (Carry carry, CarryPart carry ~ part, Ord part) => StorageIdx.OutSum part -> Graph carry a -> Maybe a lookupOutSum (StorageIdx.OutSum aug) (Storage.Graph partMap _) = case aug of Idx.Init -> return $ PartMap.init partMap Idx.NoInit sec -> Map.lookup sec $ PartMap.parts partMap class (StorageVar.Index idx) => Lookup idx where lookup :: (Carry carry, CarryPart carry ~ StorageVar.Part idx) => idx -> Graph carry a -> Maybe a instance (PartIdx.Format sec, Ord sec) => Lookup (StorageIdx.Energy sec) where lookup = lookupEnergy instance (PartIdx.Format sec, Ord sec) => Lookup (StorageIdx.X sec) where lookup = lookupX instance (PartIdx.Format sec, Ord sec) => Lookup (StorageIdx.InSum sec) where lookup = lookupInSum instance (PartIdx.Format sec, Ord sec) => Lookup (StorageIdx.OutSum sec) where lookup = lookupOutSum
energyflowanalysis/efa-2.1
src/EFA/Flow/Storage/Quantity.hs
bsd-3-clause
5,354
0
14
1,111
1,926
994
932
127
2
{-# LANGUAGE QuasiQuotes #-} module Main where import QuadrapleTH import TuringMachine zeroOneDouble :: SimpleMachine zeroOneDouble = [tm| -- 0: initial state; seeking '0' -- 1: seeking first '1' -- 2: seeking second '2' -- 3: return to the last 'X' -- 4: ensuring every '1' replaced by 'Y' -- 5: accepted. -- a-: rejected. 00X1 -- read '0' and started to seek '1' 1XR1 -- skip 'X' while seeking '1' 10R1 -- skip '0' 1YR1 -- skip '1's already read, namely'Y' 11Y2 -- first '1' found; rewrite as 'Y' then seeking another '1' 2YR2 -- go to next 21Y3 -- second '1' found; rewrite as 'Y' then return to the 'X' 2BBa -- too few '1'! error! 3YL3 -- skip 'Y's until 'X' found 30L3 -- skip '0's until 'X' found 3XR0 -- if 'X' was found, then searching '0' 0YR4 -- if all the '1' have been found, let's ensure no '1' left there 4YR4 -- skip 'Y' 4BB5 -- blank. every '1' was replaced. Let's greet 5BR6 6BO6 6OR7 7BK7 7KR8 8B!8 8!R9 411a -- failed. there are '1' still left! a1Ra aYRa aXRa a0Ra aBRb bBEb bERc cBrc crRd dBrd drRe eB!e e!Rf |] ops :: Tape Char ops = [tape|1111 11 111 111|] markOPTH :: SimpleMachine markOPTH = [tm| 01L4 4BH1 1HR1 11R1 1BR2 21R1 2BL3 3BT3 |] zeroOneEqual :: SimpleMachine zeroOneEqual = [tm| 00X1 0YR5 1XR2 20R2 2YR2 21Y3 2BBa 3YL4 4YL4 40L4 4XR0 511a 5YR5 5BR6 6BO6 6OR7 7BK7 7KR8 8B!8 8!R9 a1Ra aBRb bBEb bERc cBrc crRd dBrd drRe eB!e e!Rf |] headTailMarker :: TuringMachine Int Char headTailMarker = makeTM [(0, Just '1', GoLeft, 0) ,(0, Nothing , Write 'H', 1) ,(1, Just 'H', GoRight, 1) ,(1, Just '1', GoRight, 1) ,(1, Nothing, Write 'T', 2) ] main :: IO () main = do putStrLn "mark H at Head and T at Tail on \"11111\", started from the third" mapM_ print $ execTM headTailMarker 0 (right $ right [tape|11111|]) putStrLn "==========\n" putStrLn "parses 0^{n}1^{n}" print $ runTM zeroOneEqual 0 [tape|0011|] putStrLn "==========\n" putStrLn "parses 0^{n}1^{2n}; but fail." mapM_ print $ execTM zeroOneDouble 0 [tape|00111|] putStrLn "==========\n" putStrLn "parses 0^{n}1^{2n}; but fail again." mapM_ print $ execTM zeroOneDouble 0 [tape|0111|] putStrLn "==========\n" putStrLn "parses 0^{n}1^{2n}; success!." mapM_ print $ execTM zeroOneDouble 0 [tape|001111|]
konn/turing-machine
example.hs
bsd-3-clause
2,481
0
11
671
359
198
161
34
1
-- (c) The University of Glasgow 2006 -- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -- -- The @Class@ datatype {-# LANGUAGE CPP, DeriveDataTypeable #-} module Class ( Class, ClassOpItem, DefMeth (..), ClassATItem(..), ClassMinimalDef, defMethSpecOfDefMeth, FunDep, pprFundeps, pprFunDep, mkClass, classTyVars, classArity, classKey, className, classATs, classATItems, classTyCon, classMethods, classOpItems, classBigSig, classExtraBigSig, classTvsFds, classSCTheta, classAllSelIds, classSCSelId, classMinimalDef ) where #include "HsVersions.h" import {-# SOURCE #-} TyCon ( TyCon, tyConName, tyConUnique ) import {-# SOURCE #-} TypeRep ( Type, PredType ) import Var import Name import BasicTypes import Unique import Util import Outputable import FastString import BooleanFormula (BooleanFormula) import Data.Typeable (Typeable) import qualified Data.Data as Data {- ************************************************************************ * * \subsection[Class-basic]{@Class@: basic definition} * * ************************************************************************ A @Class@ corresponds to a Greek kappa in the static semantics: -} data Class = Class { classTyCon :: TyCon, -- The data type constructor for -- dictionaries of this class -- See Note [ATyCon for classes] in TypeRep className :: Name, -- Just the cached name of the TyCon classKey :: Unique, -- Cached unique of TyCon classTyVars :: [TyVar], -- The class kind and type variables; -- identical to those of the TyCon classFunDeps :: [FunDep TyVar], -- The functional dependencies -- Superclasses: eg: (F a ~ b, F b ~ G a, Eq a, Show b) -- We need value-level selectors for both the dictionary -- superclasses and the equality superclasses classSCTheta :: [PredType], -- Immediate superclasses, classSCSels :: [Id], -- Selector functions to extract the -- superclasses from a -- dictionary of this class -- Associated types classATStuff :: [ClassATItem], -- Associated type families -- Class operations (methods, not superclasses) classOpStuff :: [ClassOpItem], -- Ordered by tag -- Minimal complete definition classMinimalDef :: ClassMinimalDef } deriving Typeable -- | e.g. -- -- > class C a b c | a b -> c, a c -> b where... -- -- Here fun-deps are [([a,b],[c]), ([a,c],[b])] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'', type FunDep a = ([a],[a]) type ClassOpItem = (Id, DefMeth) -- Selector function; contains unfolding -- Default-method info data DefMeth = NoDefMeth -- No default method | DefMeth Name -- A polymorphic default method | GenDefMeth Name -- A generic default method deriving Eq data ClassATItem = ATI TyCon -- See Note [Associated type tyvar names] (Maybe Type) -- Default associated type (if any) from this template -- Note [Associated type defaults] type ClassMinimalDef = BooleanFormula Name -- Required methods -- | Convert a `DefMethSpec` to a `DefMeth`, which discards the name field in -- the `DefMeth` constructor of the `DefMeth`. defMethSpecOfDefMeth :: DefMeth -> DefMethSpec defMethSpecOfDefMeth meth = case meth of NoDefMeth -> NoDM DefMeth _ -> VanillaDM GenDefMeth _ -> GenericDM {- Note [Associated type defaults] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following is an example of associated type defaults: class C a where data D a r type F x a b :: * type F p q r = (p,q)->r -- Default Note that * The TyCons for the associated types *share type variables* with the class, so that we can tell which argument positions should be instantiated in an instance decl. (The first for 'D', the second for 'F'.) * We can have default definitions only for *type* families, not data families * In the default decl, the "patterns" should all be type variables, but (in the source language) they don't need to be the same as in the 'type' decl signature or the class. It's more like a free-standing 'type instance' declaration. * HOWEVER, in the internal ClassATItem we rename the RHS to match the tyConTyVars of the family TyCon. So in the example above we'd get a ClassATItem of ATI F ((x,a) -> b) So the tyConTyVars of the family TyCon bind the free vars of the default Type rhs The @mkClass@ function fills in the indirect superclasses. -} mkClass :: [TyVar] -> [([TyVar], [TyVar])] -> [PredType] -> [Id] -> [ClassATItem] -> [ClassOpItem] -> ClassMinimalDef -> TyCon -> Class mkClass tyvars fds super_classes superdict_sels at_stuff op_stuff mindef tycon = Class { classKey = tyConUnique tycon, className = tyConName tycon, classTyVars = tyvars, classFunDeps = fds, classSCTheta = super_classes, classSCSels = superdict_sels, classATStuff = at_stuff, classOpStuff = op_stuff, classMinimalDef = mindef, classTyCon = tycon } {- Note [Associated type tyvar names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The TyCon of an associated type should use the same variable names as its parent class. Thus class C a b where type F b x a :: * We make F use the same Name for 'a' as C does, and similary 'b'. The reason for this is when checking instances it's easier to match them up, to ensure they match. Eg instance C Int [d] where type F [d] x Int = .... we should make sure that the first and third args match the instance header. Having the same variables for class and tycon is also used in checkValidRoles (in TcTyClsDecls) when checking a class's roles. ************************************************************************ * * \subsection[Class-selectors]{@Class@: simple selectors} * * ************************************************************************ The rest of these functions are just simple selectors. -} classArity :: Class -> Arity classArity clas = length (classTyVars clas) -- Could memoise this classAllSelIds :: Class -> [Id] -- Both superclass-dictionary and method selectors classAllSelIds c@(Class {classSCSels = sc_sels}) = sc_sels ++ classMethods c classSCSelId :: Class -> Int -> Id -- Get the n'th superclass selector Id -- where n is 0-indexed, and counts -- *all* superclasses including equalities classSCSelId (Class { classSCSels = sc_sels }) n = ASSERT( n >= 0 && n < length sc_sels ) sc_sels !! n classMethods :: Class -> [Id] classMethods (Class {classOpStuff = op_stuff}) = [op_sel | (op_sel, _) <- op_stuff] classOpItems :: Class -> [ClassOpItem] classOpItems = classOpStuff classATs :: Class -> [TyCon] classATs (Class { classATStuff = at_stuff }) = [tc | ATI tc _ <- at_stuff] classATItems :: Class -> [ClassATItem] classATItems = classATStuff classTvsFds :: Class -> ([TyVar], [FunDep TyVar]) classTvsFds c = (classTyVars c, classFunDeps c) classBigSig :: Class -> ([TyVar], [PredType], [Id], [ClassOpItem]) classBigSig (Class {classTyVars = tyvars, classSCTheta = sc_theta, classSCSels = sc_sels, classOpStuff = op_stuff}) = (tyvars, sc_theta, sc_sels, op_stuff) classExtraBigSig :: Class -> ([TyVar], [FunDep TyVar], [PredType], [Id], [ClassATItem], [ClassOpItem]) classExtraBigSig (Class {classTyVars = tyvars, classFunDeps = fundeps, classSCTheta = sc_theta, classSCSels = sc_sels, classATStuff = ats, classOpStuff = op_stuff}) = (tyvars, fundeps, sc_theta, sc_sels, ats, op_stuff) {- ************************************************************************ * * \subsection[Class-instances]{Instance declarations for @Class@} * * ************************************************************************ We compare @Classes@ by their keys (which include @Uniques@). -} instance Eq Class where c1 == c2 = classKey c1 == classKey c2 c1 /= c2 = classKey c1 /= classKey c2 instance Ord Class where c1 <= c2 = classKey c1 <= classKey c2 c1 < c2 = classKey c1 < classKey c2 c1 >= c2 = classKey c1 >= classKey c2 c1 > c2 = classKey c1 > classKey c2 compare c1 c2 = classKey c1 `compare` classKey c2 instance Uniquable Class where getUnique c = classKey c instance NamedThing Class where getName clas = className clas instance Outputable Class where ppr c = ppr (getName c) instance Outputable DefMeth where ppr (DefMeth n) = ptext (sLit "Default method") <+> ppr n ppr (GenDefMeth n) = ptext (sLit "Generic default method") <+> ppr n ppr NoDefMeth = empty -- No default method pprFundeps :: Outputable a => [FunDep a] -> SDoc pprFundeps [] = empty pprFundeps fds = hsep (ptext (sLit "|") : punctuate comma (map pprFunDep fds)) pprFunDep :: Outputable a => FunDep a -> SDoc pprFunDep (us, vs) = hsep [interppSP us, ptext (sLit "->"), interppSP vs] instance Data.Data Class where -- don't traverse? toConstr _ = abstractConstr "Class" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "Class"
green-haskell/ghc
compiler/types/Class.hs
bsd-3-clause
10,039
0
12
2,853
1,577
904
673
132
3
{-# LANGUAGE CPP , NoImplicitPrelude , PackageImports , TypeFamilies , UnicodeSyntax #-} module Text.Numeral.Exp.Reified ( Exp(..), showExp, Side(L, R) ) where ------------------------------------------------------------------------------- -- Imports ------------------------------------------------------------------------------- import "base" Data.Bool ( Bool(False, True) ) import "base" Data.Eq ( Eq ) import "base" Data.List ( (++) ) import "base" Prelude ( String ) import "base" Text.Show ( Show, show ) import "base-unicode-symbols" Prelude.Unicode ( ℤ ) import qualified "this" Text.Numeral.Exp as E ------------------------------------------------------------------------------- -- Reified expression type ------------------------------------------------------------------------------- -- | An expression that represents the structure of a numeral. data Exp i -- | An unknown value. = Unknown -- | A literal value. | Lit ℤ -- | Negation of an expression. | Neg (Exp i) -- | Addition of two expressions. | Add (Exp i) (Exp i) -- | Multiplication of two expressions. | Mul (Exp i) (Exp i) -- | One expression subtracted from another expression. | Sub (Exp i) (Exp i) -- | A fraction. | Frac (Exp i) (Exp i) -- | A step in a scale of large values. | Scale ℤ ℤ (Exp i) -- | A dual form of an expression. | Dual (Exp i) -- | A plural form of an expression. | Plural (Exp i) -- | A change of inflection. | Inflection (i → i) (Exp i) infixl 6 `Add` infixl 6 `Sub` infixl 7 `Mul` showExp ∷ Exp i → String showExp Unknown = "Unknown" showExp (Lit n) = "Lit " ++ show n showExp (Neg x) = "Neg (" ++ showExp x ++ ")" showExp (Add x y) = "Add (" ++ showExp x ++ ") (" ++ showExp y ++ ")" showExp (Mul x y) = "Mul (" ++ showExp x ++ ") (" ++ showExp y ++ ")" showExp (Sub x y) = "Sub (" ++ showExp x ++ ") (" ++ showExp y ++ ")" showExp (Frac x y) = "Frac (" ++ showExp x ++ ") (" ++ showExp y ++ ")" showExp (Scale b o r) = "Scale " ++ show b ++ " " ++ show o ++ " (" ++ showExp r ++ ")" showExp (Dual x) = "Dual (" ++ showExp x ++ ")" showExp (Plural x) = "Plural (" ++ showExp x ++ ")" showExp (Inflection _ x) = "Inflection <func> (" ++ showExp x ++ ")" -- | Precisely the 'Unknown' constructor. instance E.Unknown (Exp i) where unknown = Unknown isUnknown Unknown = True isUnknown _ = False -- | Precisely the 'Lit' constructor. instance E.Lit (Exp i) where lit = Lit -- | Precisely the 'Neg' constructor. instance E.Neg (Exp i) where neg = Neg -- | Precisely the 'Add' constructor. instance E.Add (Exp i) where add = Add -- | Precisely the 'Mul' constructor. instance E.Mul (Exp i) where mul = Mul -- | Precisely the 'Sub' constructor. instance E.Sub (Exp i) where sub = Sub -- | Precisely the 'Frac' constructor. instance E.Frac (Exp i) where frac = Frac -- | Precisely the 'Scale' constructor. instance E.Scale (Exp i) where scale = Scale -- | Precisely the 'Dual' constructor. instance E.Dual (Exp i) where dual = Dual -- | Precisely the 'Plural' constructor. instance E.Plural (Exp i) where plural = Plural -- | Precisely the 'Inflection' constructor. instance E.Inflection (Exp i) where #if __GLASGOW_HASKELL__ < 704 type E.Inf (Exp i) = i #else type Inf (Exp i) = i #endif inflection = Inflection ------------------------------------------------------------------------------- -- Side ------------------------------------------------------------------------------- -- | A side or direction, either 'L'eft or 'R'ight. data Side = L -- ^ Left. | R -- ^ Right. deriving (Eq, Show)
roelvandijk/numerals-base
src/Text/Numeral/Exp/Reified.hs
bsd-3-clause
3,845
0
11
939
959
533
426
62
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} -- | -- Module: $HEADER$ -- Description: TODO -- Copyright: (c) 2015 Jan Šipr, Matej Kollár, Peter Trško -- License: BSD3 -- -- Stability: experimental -- Portability: GHC specific language extensions. -- -- TODO module Data.DHT.Type.NodeId where import Prelude (Bounded) import Data.Data (Data, Typeable) import Data.Eq (Eq) import Data.Ord (Ord) import Data.Word (Word64) import GHC.Generics (Generic) import Text.Printf (printf) import Text.Show (Show(showsPrec), showString) newtype NodeId = NodeId Word64 deriving (Bounded, Data, Eq, Generic, Ord, Typeable) instance Show NodeId where showsPrec _ (NodeId n) = showString (printf "%016x" n)
FPBrno/dht-api
src/Data/DHT/Type/NodeId.hs
bsd-3-clause
782
0
8
132
179
109
70
16
0
-- !!! Irrefutable patterns + guards module Read003 where import Data.OldList; import Prelude hiding (null) ~(a,b,c) | nullity b = a | nullity c = a | otherwise = a where nullity = null
jstolarek/ghc
testsuite/tests/parser/should_fail/readFail003.hs
bsd-3-clause
197
6
8
45
79
42
37
6
1
{-# LANGUAGE ScopedTypeVariables #-} module Graphics.ChalkBoard.Shader ( gslBoard , UniformArgument(..) , Argument(..) , TextureSize(..) , board , buffer , uniform ) where import Graphics.ChalkBoard.Internals --import Graphics.ChalkBoard.Types import Graphics.ChalkBoard.O.Internals import Graphics.ChalkBoard.O -- We may need (smart) constructors for the UA's below, so that we can transmit this over the wire to the server. -- | gslBoard is mid-level API into the the GSL shader langauge. gslBoard :: forall a . (Obs a) => String -> [(String,TextureSize,UniformTexture)] -> [(String,UniformArgument)] -> Board a gslBoard fn as1 as2 = Board (typeO (o (error "gslBoard" :: a))) (BoardGSI fn as1 as2)
andygill/chalkboard2
Graphics/ChalkBoard/Shader.hs
bsd-3-clause
715
6
11
111
174
105
69
14
1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} ----------------------------------------------------------------------------- -- -- Stg to C-- code generation: expressions -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module StgCmmExpr ( cgExpr ) where #include "HsVersions.h" import {-# SOURCE #-} StgCmmBind ( cgBind ) import StgCmmMonad import StgCmmHeap import StgCmmEnv import StgCmmCon import StgCmmProf (saveCurrentCostCentre, restoreCurrentCostCentre, emitSetCCC) import StgCmmLayout import StgCmmPrim import StgCmmHpc import StgCmmTicky import StgCmmUtils import StgCmmClosure import StgSyn import MkGraph import BlockId import Cmm import CmmInfo import CoreSyn import DataCon import ForeignCall import Id import PrimOp import TyCon import Type import RepType ( isVoidTy, countConRepArgs ) import CostCentre ( CostCentreStack, currentCCS ) import Maybes import Util import FastString import Outputable import Control.Monad (unless,void) import Control.Arrow (first) import Prelude hiding ((<*>)) ------------------------------------------------------------------------ -- cgExpr: the main function ------------------------------------------------------------------------ cgExpr :: StgExpr -> FCode ReturnKind cgExpr (StgApp fun args) = cgIdApp fun args {- seq# a s ==> a -} cgExpr (StgOpApp (StgPrimOp SeqOp) [StgVarArg a, _] _res_ty) = cgIdApp a [] cgExpr (StgOpApp op args ty) = cgOpApp op args ty cgExpr (StgConApp con args _)= cgConApp con args cgExpr (StgTick t e) = cgTick t >> cgExpr e cgExpr (StgLit lit) = do cmm_lit <- cgLit lit emitReturn [CmmLit cmm_lit] cgExpr (StgLet binds expr) = do { cgBind binds; cgExpr expr } cgExpr (StgLetNoEscape binds expr) = do { u <- newUnique ; let join_id = mkBlockId u ; cgLneBinds join_id binds ; r <- cgExpr expr ; emitLabel join_id ; return r } cgExpr (StgCase expr bndr alt_type alts) = cgCase expr bndr alt_type alts cgExpr (StgLam {}) = panic "cgExpr: StgLam" ------------------------------------------------------------------------ -- Let no escape ------------------------------------------------------------------------ {- Generating code for a let-no-escape binding, aka join point is very very similar to what we do for a case expression. The duality is between let-no-escape x = b in e and case e of ... -> b That is, the RHS of 'x' (ie 'b') will execute *later*, just like the alternative of the case; it needs to be compiled in an environment in which all volatile bindings are forgotten, and the free vars are bound only to stable things like stack locations.. The 'e' part will execute *next*, just like the scrutinee of a case. -} ------------------------- cgLneBinds :: BlockId -> StgBinding -> FCode () cgLneBinds join_id (StgNonRec bndr rhs) = do { local_cc <- saveCurrentCostCentre -- See Note [Saving the current cost centre] ; (info, fcode) <- cgLetNoEscapeRhs join_id local_cc bndr rhs ; fcode ; addBindC info } cgLneBinds join_id (StgRec pairs) = do { local_cc <- saveCurrentCostCentre ; r <- sequence $ unzipWith (cgLetNoEscapeRhs join_id local_cc) pairs ; let (infos, fcodes) = unzip r ; addBindsC infos ; sequence_ fcodes } ------------------------- cgLetNoEscapeRhs :: BlockId -- join point for successor of let-no-escape -> Maybe LocalReg -- Saved cost centre -> Id -> StgRhs -> FCode (CgIdInfo, FCode ()) cgLetNoEscapeRhs join_id local_cc bndr rhs = do { (info, rhs_code) <- cgLetNoEscapeRhsBody local_cc bndr rhs ; let (bid, _) = expectJust "cgLetNoEscapeRhs" $ maybeLetNoEscape info ; let code = do { (_, body) <- getCodeScoped rhs_code ; emitOutOfLine bid (first (<*> mkBranch join_id) body) } ; return (info, code) } cgLetNoEscapeRhsBody :: Maybe LocalReg -- Saved cost centre -> Id -> StgRhs -> FCode (CgIdInfo, FCode ()) cgLetNoEscapeRhsBody local_cc bndr (StgRhsClosure cc _bi _ _upd args body) = cgLetNoEscapeClosure bndr local_cc cc (nonVoidIds args) body cgLetNoEscapeRhsBody local_cc bndr (StgRhsCon cc con args) = cgLetNoEscapeClosure bndr local_cc cc [] (StgConApp con args (pprPanic "cgLetNoEscapeRhsBody" $ text "StgRhsCon doesn't have type args")) -- For a constructor RHS we want to generate a single chunk of -- code which can be jumped to from many places, which will -- return the constructor. It's easy; just behave as if it -- was an StgRhsClosure with a ConApp inside! ------------------------- cgLetNoEscapeClosure :: Id -- binder -> Maybe LocalReg -- Slot for saved current cost centre -> CostCentreStack -- XXX: *** NOT USED *** why not? -> [NonVoid Id] -- Args (as in \ args -> body) -> StgExpr -- Body (as in above) -> FCode (CgIdInfo, FCode ()) cgLetNoEscapeClosure bndr cc_slot _unused_cc args body = do dflags <- getDynFlags return ( lneIdInfo dflags bndr args , code ) where code = forkLneBody $ do { ; withNewTickyCounterLNE (idName bndr) args $ do ; restoreCurrentCostCentre cc_slot ; arg_regs <- bindArgsToRegs args ; void $ noEscapeHeapCheck arg_regs (tickyEnterLNE >> cgExpr body) } ------------------------------------------------------------------------ -- Case expressions ------------------------------------------------------------------------ {- Note [Compiling case expressions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is quite interesting to decide whether to put a heap-check at the start of each alternative. Of course we certainly have to do so if the case forces an evaluation, or if there is a primitive op which can trigger GC. A more interesting situation is this (a Plan-B situation) !P!; ...P... case x# of 0# -> !Q!; ...Q... default -> !R!; ...R... where !x! indicates a possible heap-check point. The heap checks in the alternatives *can* be omitted, in which case the topmost heapcheck will take their worst case into account. In favour of omitting !Q!, !R!: - *May* save a heap overflow test, if ...P... allocates anything. - We can use relative addressing from a single Hp to get at all the closures so allocated. - No need to save volatile vars etc across heap checks in !Q!, !R! Against omitting !Q!, !R! - May put a heap-check into the inner loop. Suppose the main loop is P -> R -> P -> R... Q is the loop exit, and only it does allocation. This only hurts us if P does no allocation. If P allocates, then there is a heap check in the inner loop anyway. - May do more allocation than reqd. This sometimes bites us badly. For example, nfib (ha!) allocates about 30\% more space if the worst-casing is done, because many many calls to nfib are leaf calls which don't need to allocate anything. We can un-allocate, but that costs an instruction Neither problem hurts us if there is only one alternative. Suppose the inner loop is P->R->P->R etc. Then here is how many heap checks we get in the *inner loop* under various conditions Alloc Heap check in branches (!Q!, !R!)? P Q R yes no (absorb to !P!) -------------------------------------- n n n 0 0 n y n 0 1 n . y 1 1 y . y 2 1 y . n 1 1 Best choices: absorb heap checks from Q and R into !P! iff a) P itself does some allocation or b) P does allocation, or there is exactly one alternative We adopt (b) because that is more likely to put the heap check at the entry to a function, when not many things are live. After a bunch of single-branch cases, we may have lots of things live Hence: two basic plans for case e of r { alts } ------ Plan A: the general case --------- ...save current cost centre... ...code for e, with sequel (SetLocals r) ...restore current cost centre... ...code for alts... ...alts do their own heap checks ------ Plan B: special case when --------- (i) e does not allocate or call GC (ii) either upstream code performs allocation or there is just one alternative Then heap allocation in the (single) case branch is absorbed by the upstream check. Very common example: primops on unboxed values ...code for e, with sequel (SetLocals r)... ...code for alts... ...no heap check... -} ------------------------------------- data GcPlan = GcInAlts -- Put a GC check at the start the case alternatives, [LocalReg] -- which binds these registers | NoGcInAlts -- The scrutinee is a primitive value, or a call to a -- primitive op which does no GC. Absorb the allocation -- of the case alternative(s) into the upstream check ------------------------------------- cgCase :: StgExpr -> Id -> AltType -> [StgAlt] -> FCode ReturnKind cgCase (StgOpApp (StgPrimOp op) args _) bndr (AlgAlt tycon) alts | isEnumerationTyCon tycon -- Note [case on bool] = do { tag_expr <- do_enum_primop op args -- If the binder is not dead, convert the tag to a constructor -- and assign it. ; unless (isDeadBinder bndr) $ do { dflags <- getDynFlags ; tmp_reg <- bindArgToReg (NonVoid bndr) ; emitAssign (CmmLocal tmp_reg) (tagToClosure dflags tycon tag_expr) } ; (mb_deflt, branches) <- cgAlgAltRhss (NoGcInAlts,AssignedDirectly) (NonVoid bndr) alts ; emitSwitch tag_expr branches mb_deflt 0 (tyConFamilySize tycon - 1) ; return AssignedDirectly } where do_enum_primop :: PrimOp -> [StgArg] -> FCode CmmExpr do_enum_primop TagToEnumOp [arg] -- No code! = getArgAmode (NonVoid arg) do_enum_primop primop args = do dflags <- getDynFlags tmp <- newTemp (bWord dflags) cgPrimOp [tmp] primop args return (CmmReg (CmmLocal tmp)) {- Note [case on bool] ~~~~~~~~~~~~~~~~~~~ This special case handles code like case a <# b of True -> False -> --> case tagToEnum# (a <$# b) of True -> .. ; False -> ... --> case (a <$# b) of r -> case tagToEnum# r of True -> .. ; False -> ... If we let the ordinary case code handle it, we'll get something like tmp1 = a < b tmp2 = Bool_closure_tbl[tmp1] if (tmp2 & 7 != 0) then ... // normal tagged case but this junk won't optimise away. What we really want is just an inline comparison: if (a < b) then ... So we add a special case to generate tmp1 = a < b if (tmp1 == 0) then ... and later optimisations will further improve this. Now that #6135 has been resolved it should be possible to remove that special case. The idea behind this special case and pre-6135 implementation of Bool-returning primops was that tagToEnum# was added implicitly in the codegen and then optimized away. Now the call to tagToEnum# is explicit in the source code, which allows to optimize it away at the earlier stages of compilation (i.e. at the Core level). Note [Scrutinising VoidRep] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have this STG code: f = \[s : State# RealWorld] -> case s of _ -> blah This is very odd. Why are we scrutinising a state token? But it can arise with bizarre NOINLINE pragmas (Trac #9964) crash :: IO () crash = IO (\s -> let {-# NOINLINE s' #-} s' = s in (# s', () #)) Now the trouble is that 's' has VoidRep, and we do not bind void arguments in the environment; they don't live anywhere. See the calls to nonVoidIds in various places. So we must not look up 's' in the environment. Instead, just evaluate the RHS! Simple. -} cgCase (StgApp v []) _ (PrimAlt _) alts | isVoidRep (idPrimRep v) -- See Note [Scrutinising VoidRep] , [(DEFAULT, _, rhs)] <- alts = cgExpr rhs {- Note [Dodgy unsafeCoerce 1] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider case (x :: HValue) |> co of (y :: MutVar# Int) DEFAULT -> ... We want to gnerate an assignment y := x We want to allow this assignment to be generated in the case when the types are compatible, because this allows some slightly-dodgy but occasionally-useful casts to be used, such as in RtClosureInspect where we cast an HValue to a MutVar# so we can print out the contents of the MutVar#. If instead we generate code that enters the HValue, then we'll get a runtime panic, because the HValue really is a MutVar#. The types are compatible though, so we can just generate an assignment. -} cgCase (StgApp v []) bndr alt_type@(PrimAlt _) alts | isUnliftedType (idType v) -- Note [Dodgy unsafeCoerce 1] || reps_compatible = -- assignment suffices for unlifted types do { dflags <- getDynFlags ; unless reps_compatible $ panic "cgCase: reps do not match, perhaps a dodgy unsafeCoerce?" ; v_info <- getCgIdInfo v ; emitAssign (CmmLocal (idToReg dflags (NonVoid bndr))) (idInfoToAmode v_info) ; bindArgToReg (NonVoid bndr) ; cgAlts (NoGcInAlts,AssignedDirectly) (NonVoid bndr) alt_type alts } where reps_compatible = idPrimRep v == idPrimRep bndr {- Note [Dodgy unsafeCoerce 2, #3132] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In all other cases of a lifted Id being cast to an unlifted type, the Id should be bound to bottom, otherwise this is an unsafe use of unsafeCoerce. We can generate code to enter the Id and assume that it will never return. Hence, we emit the usual enter/return code, and because bottom must be untagged, it will be entered. The Sequel is a type-correct assignment, albeit bogus. The (dead) continuation loops; it would be better to invoke some kind of panic function here. -} cgCase scrut@(StgApp v []) _ (PrimAlt _) _ = do { dflags <- getDynFlags ; mb_cc <- maybeSaveCostCentre True ; withSequel (AssignTo [idToReg dflags (NonVoid v)] False) (cgExpr scrut) ; restoreCurrentCostCentre mb_cc ; emitComment $ mkFastString "should be unreachable code" ; l <- newLabelC ; emitLabel l ; emit (mkBranch l) -- an infinite loop ; return AssignedDirectly } {- Note [Handle seq#] ~~~~~~~~~~~~~~~~~~~~~ case seq# a s of v (# s', a' #) -> e ==> case a of v (# s', a' #) -> e (taking advantage of the fact that the return convention for (# State#, a #) is the same as the return convention for just 'a') -} cgCase (StgOpApp (StgPrimOp SeqOp) [StgVarArg a, _] _) bndr alt_type alts = -- Note [Handle seq#] -- Use the same return convention as vanilla 'a'. cgCase (StgApp a []) bndr alt_type alts cgCase scrut bndr alt_type alts = -- the general case do { dflags <- getDynFlags ; up_hp_usg <- getVirtHp -- Upstream heap usage ; let ret_bndrs = chooseReturnBndrs bndr alt_type alts alt_regs = map (idToReg dflags) ret_bndrs ; simple_scrut <- isSimpleScrut scrut alt_type ; let do_gc | not simple_scrut = True | isSingleton alts = False | up_hp_usg > 0 = False | otherwise = True -- cf Note [Compiling case expressions] gc_plan = if do_gc then GcInAlts alt_regs else NoGcInAlts ; mb_cc <- maybeSaveCostCentre simple_scrut ; let sequel = AssignTo alt_regs do_gc{- Note [scrut sequel] -} ; ret_kind <- withSequel sequel (cgExpr scrut) ; restoreCurrentCostCentre mb_cc ; _ <- bindArgsToRegs ret_bndrs ; cgAlts (gc_plan,ret_kind) (NonVoid bndr) alt_type alts } {- Note [scrut sequel] The job of the scrutinee is to assign its value(s) to alt_regs. Additionally, if we plan to do a heap-check in the alternatives (see Note [Compiling case expressions]), then we *must* retreat Hp to recover any unused heap before passing control to the sequel. If we don't do this, then any unused heap will become slop because the heap check will reset the heap usage. Slop in the heap breaks LDV profiling (+RTS -hb) which needs to do a linear sweep through the nursery. Note [Inlining out-of-line primops and heap checks] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If shouldInlinePrimOp returns True when called from StgCmmExpr for the purpose of heap check placement, we *must* inline the primop later in StgCmmPrim. If we don't things will go wrong. -} ----------------- maybeSaveCostCentre :: Bool -> FCode (Maybe LocalReg) maybeSaveCostCentre simple_scrut | simple_scrut = return Nothing | otherwise = saveCurrentCostCentre ----------------- isSimpleScrut :: StgExpr -> AltType -> FCode Bool -- Simple scrutinee, does not block or allocate; hence safe to amalgamate -- heap usage from alternatives into the stuff before the case -- NB: if you get this wrong, and claim that the expression doesn't allocate -- when it does, you'll deeply mess up allocation isSimpleScrut (StgOpApp op args _) _ = isSimpleOp op args isSimpleScrut (StgLit _) _ = return True -- case 1# of { 0# -> ..; ... } isSimpleScrut (StgApp _ []) (PrimAlt _) = return True -- case x# of { 0# -> ..; ... } isSimpleScrut _ _ = return False isSimpleOp :: StgOp -> [StgArg] -> FCode Bool -- True iff the op cannot block or allocate isSimpleOp (StgFCallOp (CCall (CCallSpec _ _ safe)) _) _ = return $! not (playSafe safe) isSimpleOp (StgPrimOp op) stg_args = do arg_exprs <- getNonVoidArgAmodes stg_args dflags <- getDynFlags -- See Note [Inlining out-of-line primops and heap checks] return $! isJust $ shouldInlinePrimOp dflags op arg_exprs isSimpleOp (StgPrimCallOp _) _ = return False ----------------- chooseReturnBndrs :: Id -> AltType -> [StgAlt] -> [NonVoid Id] -- These are the binders of a case that are assigned by the evaluation of the -- scrutinee. -- They're non-void, see Note [Post-unarisation invariants] in UnariseStg. chooseReturnBndrs bndr (PrimAlt _) _alts = assertNonVoidIds [bndr] chooseReturnBndrs _bndr (MultiValAlt n) [(_, ids, _)] = ASSERT2(n == length ids, ppr n $$ ppr ids $$ ppr _bndr) assertNonVoidIds ids -- 'bndr' is not assigned! chooseReturnBndrs bndr (AlgAlt _) _alts = assertNonVoidIds [bndr] -- Only 'bndr' is assigned chooseReturnBndrs bndr PolyAlt _alts = assertNonVoidIds [bndr] -- Only 'bndr' is assigned chooseReturnBndrs _ _ _ = panic "chooseReturnBndrs" -- MultiValAlt has only one alternative ------------------------------------- cgAlts :: (GcPlan,ReturnKind) -> NonVoid Id -> AltType -> [StgAlt] -> FCode ReturnKind -- At this point the result of the case are in the binders cgAlts gc_plan _bndr PolyAlt [(_, _, rhs)] = maybeAltHeapCheck gc_plan (cgExpr rhs) cgAlts gc_plan _bndr (MultiValAlt _) [(_, _, rhs)] = maybeAltHeapCheck gc_plan (cgExpr rhs) -- Here bndrs are *already* in scope, so don't rebind them cgAlts gc_plan bndr (PrimAlt _) alts = do { dflags <- getDynFlags ; tagged_cmms <- cgAltRhss gc_plan bndr alts ; let bndr_reg = CmmLocal (idToReg dflags bndr) (DEFAULT,deflt) = head tagged_cmms -- PrimAlts always have a DEFAULT case -- and it always comes first tagged_cmms' = [(lit,code) | (LitAlt lit, code) <- tagged_cmms] ; emitCmmLitSwitch (CmmReg bndr_reg) tagged_cmms' deflt ; return AssignedDirectly } cgAlts gc_plan bndr (AlgAlt tycon) alts = do { dflags <- getDynFlags ; (mb_deflt, branches) <- cgAlgAltRhss gc_plan bndr alts ; let fam_sz = tyConFamilySize tycon bndr_reg = CmmLocal (idToReg dflags bndr) -- Is the constructor tag in the node reg? ; if isSmallFamily dflags fam_sz then do let -- Yes, bndr_reg has constr. tag in ls bits tag_expr = cmmConstrTag1 dflags (CmmReg bndr_reg) branches' = [(tag+1,branch) | (tag,branch) <- branches] emitSwitch tag_expr branches' mb_deflt 1 fam_sz else -- No, get tag from info table do dflags <- getDynFlags let -- Note that ptr _always_ has tag 1 -- when the family size is big enough untagged_ptr = cmmRegOffB bndr_reg (-1) tag_expr = getConstrTag dflags (untagged_ptr) emitSwitch tag_expr branches mb_deflt 0 (fam_sz - 1) ; return AssignedDirectly } cgAlts _ _ _ _ = panic "cgAlts" -- UbxTupAlt and PolyAlt have only one alternative -- Note [alg-alt heap check] -- -- In an algebraic case with more than one alternative, we will have -- code like -- -- L0: -- x = R1 -- goto L1 -- L1: -- if (x & 7 >= 2) then goto L2 else goto L3 -- L2: -- Hp = Hp + 16 -- if (Hp > HpLim) then goto L4 -- ... -- L4: -- call gc() returns to L5 -- L5: -- x = R1 -- goto L1 ------------------- cgAlgAltRhss :: (GcPlan,ReturnKind) -> NonVoid Id -> [StgAlt] -> FCode ( Maybe CmmAGraphScoped , [(ConTagZ, CmmAGraphScoped)] ) cgAlgAltRhss gc_plan bndr alts = do { tagged_cmms <- cgAltRhss gc_plan bndr alts ; let { mb_deflt = case tagged_cmms of ((DEFAULT,rhs) : _) -> Just rhs _other -> Nothing -- DEFAULT is always first, if present ; branches = [ (dataConTagZ con, cmm) | (DataAlt con, cmm) <- tagged_cmms ] } ; return (mb_deflt, branches) } ------------------- cgAltRhss :: (GcPlan,ReturnKind) -> NonVoid Id -> [StgAlt] -> FCode [(AltCon, CmmAGraphScoped)] cgAltRhss gc_plan bndr alts = do dflags <- getDynFlags let base_reg = idToReg dflags bndr cg_alt :: StgAlt -> FCode (AltCon, CmmAGraphScoped) cg_alt (con, bndrs, rhs) = getCodeScoped $ maybeAltHeapCheck gc_plan $ do { _ <- bindConArgs con base_reg (assertNonVoidIds bndrs) -- alt binders are always non-void, -- see Note [Post-unarisation invariants] in UnariseStg ; _ <- cgExpr rhs ; return con } forkAlts (map cg_alt alts) maybeAltHeapCheck :: (GcPlan,ReturnKind) -> FCode a -> FCode a maybeAltHeapCheck (NoGcInAlts,_) code = code maybeAltHeapCheck (GcInAlts regs, AssignedDirectly) code = altHeapCheck regs code maybeAltHeapCheck (GcInAlts regs, ReturnedTo lret off) code = altHeapCheckReturnsTo regs lret off code ----------------------------------------------------------------------------- -- Tail calls ----------------------------------------------------------------------------- cgConApp :: DataCon -> [StgArg] -> FCode ReturnKind cgConApp con stg_args | isUnboxedTupleCon con -- Unboxed tuple: assign and return = do { arg_exprs <- getNonVoidArgAmodes stg_args ; tickyUnboxedTupleReturn (length arg_exprs) ; emitReturn arg_exprs } | otherwise -- Boxed constructors; allocate and return = ASSERT2( stg_args `lengthIs` countConRepArgs con, ppr con <> parens (ppr (countConRepArgs con)) <+> ppr stg_args ) do { (idinfo, fcode_init) <- buildDynCon (dataConWorkId con) False currentCCS con (assertNonVoidStgArgs stg_args) -- con args are always non-void, -- see Note [Post-unarisation invariants] in UnariseStg -- The first "con" says that the name bound to this -- closure is is "con", which is a bit of a fudge, but -- it only affects profiling (hence the False) ; emit =<< fcode_init ; tickyReturnNewCon (length stg_args) ; emitReturn [idInfoToAmode idinfo] } cgIdApp :: Id -> [StgArg] -> FCode ReturnKind cgIdApp fun_id [] | isVoidTy (idType fun_id) = emitReturn [] cgIdApp fun_id args = do dflags <- getDynFlags fun_info <- getCgIdInfo fun_id self_loop_info <- getSelfLoop let cg_fun_id = cg_id fun_info -- NB: use (cg_id fun_info) instead of fun_id, because -- the former may be externalised for -split-objs. -- See Note [Externalise when splitting] in StgCmmMonad fun_arg = StgVarArg cg_fun_id fun_name = idName cg_fun_id fun = idInfoToAmode fun_info lf_info = cg_lf fun_info n_args = length args v_args = length $ filter (isVoidTy . stgArgType) args node_points dflags = nodeMustPointToIt dflags lf_info case getCallMethod dflags fun_name cg_fun_id lf_info n_args v_args (cg_loc fun_info) self_loop_info of -- A value in WHNF, so we can just return it. ReturnIt -> emitReturn [fun] -- ToDo: does ReturnIt guarantee tagged? EnterIt -> ASSERT( null args ) -- Discarding arguments emitEnter fun SlowCall -> do -- A slow function call via the RTS apply routines { tickySlowCall lf_info args ; emitComment $ mkFastString "slowCall" ; slowCall fun args } -- A direct function call (possibly with some left-over arguments) DirectEntry lbl arity -> do { tickyDirectCall arity args ; if node_points dflags then directCall NativeNodeCall lbl arity (fun_arg:args) else directCall NativeDirectCall lbl arity args } -- Let-no-escape call or self-recursive tail-call JumpToIt blk_id lne_regs -> do { adjustHpBackwards -- always do this before a tail-call ; cmm_args <- getNonVoidArgAmodes args ; emitMultiAssign lne_regs cmm_args ; emit (mkBranch blk_id) ; return AssignedDirectly } -- Note [Self-recursive tail calls] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- Self-recursive tail calls can be optimized into a local jump in the same -- way as let-no-escape bindings (see Note [What is a non-escaping let] in -- stgSyn/CoreToStg.hs). Consider this: -- -- foo.info: -- a = R1 // calling convention -- b = R2 -- goto L1 -- L1: ... -- ... -- ... -- L2: R1 = x -- R2 = y -- call foo(R1,R2) -- -- Instead of putting x and y into registers (or other locations required by the -- calling convention) and performing a call we can put them into local -- variables a and b and perform jump to L1: -- -- foo.info: -- a = R1 -- b = R2 -- goto L1 -- L1: ... -- ... -- ... -- L2: a = x -- b = y -- goto L1 -- -- This can be done only when function is calling itself in a tail position -- and only if the call passes number of parameters equal to function's arity. -- Note that this cannot be performed if a function calls itself with a -- continuation. -- -- This in fact implements optimization known as "loopification". It was -- described in "Low-level code optimizations in the Glasgow Haskell Compiler" -- by Krzysztof Woś, though we use different approach. Krzysztof performed his -- optimization at the Cmm level, whereas we perform ours during code generation -- (Stg-to-Cmm pass) essentially making sure that optimized Cmm code is -- generated in the first place. -- -- Implementation is spread across a couple of places in the code: -- -- * FCode monad stores additional information in its reader environment -- (cgd_self_loop field). This information tells us which function can -- tail call itself in an optimized way (it is the function currently -- being compiled), what is the label of a loop header (L1 in example above) -- and information about local registers in which we should arguments -- before making a call (this would be a and b in example above). -- -- * Whenever we are compiling a function, we set that information to reflect -- the fact that function currently being compiled can be jumped to, instead -- of called. This is done in closureCodyBody in StgCmmBind. -- -- * We also have to emit a label to which we will be jumping. We make sure -- that the label is placed after a stack check but before the heap -- check. The reason is that making a recursive tail-call does not increase -- the stack so we only need to check once. But it may grow the heap, so we -- have to repeat the heap check in every self-call. This is done in -- do_checks in StgCmmHeap. -- -- * When we begin compilation of another closure we remove the additional -- information from the environment. This is done by forkClosureBody -- in StgCmmMonad. Other functions that duplicate the environment - -- forkLneBody, forkAlts, codeOnly - duplicate that information. In other -- words, we only need to clean the environment of the self-loop information -- when compiling right hand side of a closure (binding). -- -- * When compiling a call (cgIdApp) we use getCallMethod to decide what kind -- of call will be generated. getCallMethod decides to generate a self -- recursive tail call when (a) environment stores information about -- possible self tail-call; (b) that tail call is to a function currently -- being compiled; (c) number of passed non-void arguments is equal to -- function's arity. (d) loopification is turned on via -floopification -- command-line option. -- -- * Command line option to turn loopification on and off is implemented in -- DynFlags. -- -- -- Note [Void arguments in self-recursive tail calls] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- State# tokens can get in the way of the loopification optimization as seen in -- #11372. Consider this: -- -- foo :: [a] -- -> (a -> State# s -> (# State s, Bool #)) -- -> State# s -- -> (# State# s, Maybe a #) -- foo [] f s = (# s, Nothing #) -- foo (x:xs) f s = case f x s of -- (# s', b #) -> case b of -- True -> (# s', Just x #) -- False -> foo xs f s' -- -- We would like to compile the call to foo as a local jump instead of a call -- (see Note [Self-recursive tail calls]). However, the generated function has -- an arity of 2 while we apply it to 3 arguments, one of them being of void -- type. Thus, we mustn't count arguments of void type when checking whether -- we can turn a call into a self-recursive jump. -- emitEnter :: CmmExpr -> FCode ReturnKind emitEnter fun = do { dflags <- getDynFlags ; adjustHpBackwards ; sequel <- getSequel ; updfr_off <- getUpdFrameOff ; case sequel of -- For a return, we have the option of generating a tag-test or -- not. If the value is tagged, we can return directly, which -- is quicker than entering the value. This is a code -- size/speed trade-off: when optimising for speed rather than -- size we could generate the tag test. -- -- Right now, we do what the old codegen did, and omit the tag -- test, just generating an enter. Return -> do { let entry = entryCode dflags $ closureInfoPtr dflags $ CmmReg nodeReg ; emit $ mkJump dflags NativeNodeCall entry [cmmUntag dflags fun] updfr_off ; return AssignedDirectly } -- The result will be scrutinised in the sequel. This is where -- we generate a tag-test to avoid entering the closure if -- possible. -- -- The generated code will be something like this: -- -- R1 = fun -- copyout -- if (fun & 7 != 0) goto Lcall else goto Lret -- Lcall: -- call [fun] returns to Lret -- Lret: -- fun' = R1 -- copyin -- ... -- -- Note in particular that the label Lret is used as a -- destination by both the tag-test and the call. This is -- because Lret will necessarily be a proc-point, and we want to -- ensure that we generate only one proc-point for this -- sequence. -- -- Furthermore, we tell the caller that we generated a native -- return continuation by returning (ReturnedTo Lret off), so -- that the continuation can be reused by the heap-check failure -- code in the enclosing case expression. -- AssignTo res_regs _ -> do { lret <- newLabelC ; let (off, _, copyin) = copyInOflow dflags NativeReturn (Young lret) res_regs [] ; lcall <- newLabelC ; updfr_off <- getUpdFrameOff ; let area = Young lret ; let (outArgs, regs, copyout) = copyOutOflow dflags NativeNodeCall Call area [fun] updfr_off [] -- refer to fun via nodeReg after the copyout, to avoid having -- both live simultaneously; this sometimes enables fun to be -- inlined in the RHS of the R1 assignment. ; let entry = entryCode dflags (closureInfoPtr dflags (CmmReg nodeReg)) the_call = toCall entry (Just lret) updfr_off off outArgs regs ; tscope <- getTickScope ; emit $ copyout <*> mkCbranch (cmmIsTagged dflags (CmmReg nodeReg)) lret lcall Nothing <*> outOfLine lcall (the_call,tscope) <*> mkLabel lret tscope <*> copyin ; return (ReturnedTo lret off) } } ------------------------------------------------------------------------ -- Ticks ------------------------------------------------------------------------ -- | Generate Cmm code for a tick. Depending on the type of Tickish, -- this will either generate actual Cmm instrumentation code, or -- simply pass on the annotation as a @CmmTickish@. cgTick :: Tickish Id -> FCode () cgTick tick = do { dflags <- getDynFlags ; case tick of ProfNote cc t p -> emitSetCCC cc t p HpcTick m n -> emit (mkTickBox dflags m n) SourceNote s n -> emitTick $ SourceNote s n _other -> return () -- ignore }
snoyberg/ghc
compiler/codeGen/StgCmmExpr.hs
bsd-3-clause
34,704
3
20
9,333
4,926
2,600
2,326
-1
-1
-- A non-copying cp based on mmap. import System.IO.Posix.MMap import Control.Monad import System.Mem import qualified Data.ByteString as S import Text.Printf import Control.Exception import System.CPUTime main = do --should run in constant space, and be faster: time $ forM_ [0..1000] $ \_ -> do unsafeMMapFile "/usr/share/dict/words" putStrLn "\nShould be faster than:\n" --should run in constant space: time $ forM_ [0..1000] $ \_ -> do S.readFile "/usr/share/dict/words" time :: IO t -> IO t time a = do start <- getCPUTime v <- a v `seq` return () end <- getCPUTime let diff = (fromIntegral (end - start)) / (10^12) printf "Computation time: %0.3f sec\n" (diff :: Double) return v
michaelt/pipes-bytestring-mmap
tests/pressure.hs
bsd-3-clause
759
0
14
181
228
116
112
22
1
{-# LANGUAGE CPP #-} module Test.QuickCheck ( -- * Running tests quickCheck , Args(..), Result(..) , stdArgs , quickCheckWith , quickCheckWithResult , quickCheckResult -- ** Running tests verbosely , verboseCheck , verboseCheckWith , verboseCheckWithResult , verboseCheckResult , verbose -- * Random generation , Gen -- ** Generator combinators , sized , resize , choose , promote , suchThat , suchThatMaybe , oneof , frequency , elements , growingElements , listOf , listOf1 , vectorOf -- ** Generators which use Arbitrary , vector , orderedList -- ** Generator debugging , sample , sample' -- * Arbitrary and CoArbitrary classes , Arbitrary(..) , CoArbitrary(..) -- ** Helper functions for implementing arbitrary , arbitrarySizedIntegral , arbitrarySizedFractional , arbitrarySizedBoundedIntegral , arbitraryBoundedIntegral , arbitraryBoundedRandom , arbitraryBoundedEnum , coarbitraryEnum -- ** Helper functions for implementing shrink , shrinkNothing , shrinkIntegral , shrinkRealFrac -- ** Helper functions for implementing coarbitrary , variant , (><) , coarbitraryIntegral , coarbitraryReal , coarbitraryShow -- ** Type-level modifiers for changing generator behavior , Blind(..) , Fixed(..) , OrderedList(..) , NonEmptyList(..) , Positive(..) , NonZero(..) , NonNegative(..) , Smart(..) , Shrink2(..) #ifndef NO_MULTI_PARAM_TYPE_CLASSES , Shrinking(..) #endif , ShrinkState(..) -- * Properties , Property, Prop, Testable(..) -- ** Property combinators , mapSize , shrinking , (==>) , discard , forAll , forAllShrink -- *** Experimental combinators for conjunction and disjunction , (.&.) , (.&&.) , conjoin , (.||.) , disjoin -- *** Handling failure , whenFail , printTestCase , whenFail' , expectFailure , within -- *** Test distribution , label , collect , classify , cover , once -- * Text formatting , Str(..) , ranges ) where -------------------------------------------------------------------------- -- imports import Test.QuickCheck.Gen import Test.QuickCheck.Arbitrary import Test.QuickCheck.Modifiers import Test.QuickCheck.Property hiding ( Result(..) ) import Test.QuickCheck.Test import Test.QuickCheck.Text import Test.QuickCheck.Exception -------------------------------------------------------------------------- -- the end.
nh2/quickcheck
Test/QuickCheck.hs
bsd-3-clause
2,494
0
6
536
414
293
121
91
0
{-# LANGUAGE GADTs, ScopedTypeVariables #-} module Desysad where import Control.Monad.State.Strict import Control.Monad.Error import System.IO import System.Directory import System.Process import System.Exit import Control.Concurrent import Control.Exception as E --- ONE APPROACH data Cmd a where Return :: a -> Cmd a Bind :: Cmd a -> (a -> Cmd b) -> Cmd b Run :: String -> Cmd String Fail :: String -> Cmd a Mplus :: Cmd a -> Cmd a -> Cmd a instance Functor Cmd where fmap f cmd = cmd `Bind` (Return . f) instance Monad Cmd where return = Return (>>=) = Bind fail = Fail instance MonadPlus Cmd where mzero = Fail "mzero" mplus x y = Mplus x y data DS = DS { pkgList1 :: [String], runTests1 :: Bool } type Sys a = StateT DS Cmd a runCmd :: Cmd a -> IO a runCmd (Return x) = return x runCmd (Fail s) = fail s runCmd (Bind cmdx f) = runCmd cmdx >>= runCmd . f runCmd (Run s) = do res <- sh s case res of Left s -> fail s Right s -> return s runCmd (Mplus (Fail s) cy) = runCmd cy runCmd (Mplus cx cy) = do runCmd cx `E.catch` (\(e::SomeException)-> runCmd cy) runSys :: Sys a -> IO a runSys stcmda = do let s = DS [] False runCmd $ evalStateT stcmda s run :: String -> Sys () run s = lift (Run s) >> return () ensure_pkg_list :: Sys () ensure_pkg_list = do pkgs <- fmap pkgList1 get when (null pkgs) $ do return () has_apt :: String -> Sys () has_apt pkg = do run ("dpkg -l $1 >/dev/null 2>/dev/null") `mplus` run ("apt-get install -y -q $i") --- ANOTHER ATTEMPT data DS1= DS1 { handles :: (Handle, Handle, Handle, ProcessHandle), pkgList :: [String], runTests :: Bool } type Sys1 a = StateT DS1 (ErrorT String IO) a io m = lift $ lift m sh :: String -> IO (Either String String) sh cmd = do (hin, hout, herr, ph) <- runInteractiveCommand cmd excode <- waitForProcess ph sout <- hGetContents hout serr <- hGetContents herr case excode of ExitSuccess -> return $ Right sout ExitFailure n -> return $ Left $ concat ["process error ", show n, " :", serr ] main2 = runLocal $ do pwd <- cmd "pwd" console pwd cmd :: String -> Sys1 String cmd s = do (inp, o , e, p) <- fmap handles get io $ hPutStr inp $ s++"\n" io $ hGetLine o console :: String -> Sys1 () console s = lift $ lift $ putStrLn s --pwd :: Sys String --pwd = runLocal :: Sys1 () -> IO () runLocal esio = do -- hSetBuffering stdin NoBuffering h@(inp,o,e,pid) <- runInteractiveCommand "bash" threadDelay $ 100*1000 myForkIO $ do let s = DS1 h [] False let errio = evalStateT esio s r <- runErrorT errio case r of Right x -> return x Left s -> error s hClose o hClose e hClose inp terminateProcess pid waitForProcess pid -- bufmode <- hGetBuffering stdin -- when (bufmode /= LineBuffering) $ hSetBuffering stdin LineBuffering return () myForkIO :: IO () -> IO () myForkIO io = do mvar <- newEmptyMVar forkIO (io `finally` putMVar mvar ()) takeMVar mvar
glutamate/tnutils
Desysad.hs
bsd-3-clause
3,526
0
14
1,262
1,250
621
629
102
2
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim.StateUtils -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable module Yi.Keymap.Vim.StateUtils ( switchMode , switchModeE , resetCount , resetCountE , setCountE , modifyStateE , getMaybeCountE , getCountE , accumulateEventE , accumulateBindingEventE , accumulateTextObjectEventE , flushAccumulatorE , dropAccumulatorE , dropBindingAccumulatorE , dropTextObjectAccumulatorE , setRegisterE , getRegisterE , normalizeCountE , maybeMult , updateModeIndicatorE , saveInsertEventStringE , resetActiveRegisterE ) where import Control.Monad (when) import qualified Data.HashMap.Strict as HM (insert, lookup) import Data.Maybe (fromMaybe, isJust) import Data.Monoid ((<>)) import qualified Data.Text as T (null) import Yi.Buffer.Normal (RegionStyle (Block, LineWise)) import Yi.Editor (EditorM, getEditorDyn, putEditorDyn, setStatus) import Yi.Event (Event) import Yi.Keymap.Vim.Common import Yi.Keymap.Vim.EventUtils import Yi.Rope (YiString) import Yi.String (showT) import Yi.Style (defaultStyle) switchMode :: VimMode -> VimState -> VimState switchMode mode state = state { vsMode = mode } switchModeE :: VimMode -> EditorM () switchModeE mode = modifyStateE $ switchMode mode modifyStateE :: (VimState -> VimState) -> EditorM () modifyStateE f = do currentState <- getEditorDyn putEditorDyn $ f currentState resetCount :: VimState -> VimState resetCount s = s { vsCount = Nothing } resetCountE :: EditorM () resetCountE = modifyStateE resetCount getMaybeCountE :: EditorM (Maybe Int) getMaybeCountE = fmap vsCount getEditorDyn getCountE :: EditorM Int getCountE = do currentState <- getEditorDyn return $! fromMaybe 1 (vsCount currentState) setCountE :: Int -> EditorM () setCountE n = modifyStateE $ \s -> s { vsCount = Just n } accumulateBindingEventE :: Event -> EditorM () accumulateBindingEventE e = modifyStateE $ \s -> s { vsBindingAccumulator = vsBindingAccumulator s <> eventToEventString e } accumulateEventE :: Event -> EditorM () accumulateEventE e = modifyStateE $ \s -> s { vsAccumulator = vsAccumulator s <> eventToEventString e } accumulateTextObjectEventE :: EventString -> EditorM () accumulateTextObjectEventE evs = modifyStateE $ \s -> s { vsTextObjectAccumulator = vsTextObjectAccumulator s <> evs } flushAccumulatorE :: EditorM () flushAccumulatorE = do accum <- vsAccumulator <$> getEditorDyn let repeatableAction = stringToRepeatableAction accum accum `seq` modifyStateE $ \s -> s { vsRepeatableAction = Just repeatableAction , vsAccumulator = mempty , vsCurrentMacroRecording = fmap (fmap (<> accum)) (vsCurrentMacroRecording s) } dropAccumulatorE :: EditorM () dropAccumulatorE = modifyStateE $ \s -> let accum = vsAccumulator s in s { vsAccumulator = mempty , vsCurrentMacroRecording = fmap (fmap (<> accum)) (vsCurrentMacroRecording s) } dropBindingAccumulatorE :: EditorM () dropBindingAccumulatorE = modifyStateE $ \s -> s { vsBindingAccumulator = mempty } dropTextObjectAccumulatorE :: EditorM () dropTextObjectAccumulatorE = modifyStateE $ \s -> s { vsTextObjectAccumulator = mempty } getRegisterE :: RegisterName -> EditorM (Maybe Register) getRegisterE name = fmap (HM.lookup name . vsRegisterMap) getEditorDyn setRegisterE :: RegisterName -> RegionStyle -> YiString -> EditorM () setRegisterE name style rope = do rmap <- fmap vsRegisterMap getEditorDyn let rmap' = HM.insert name (Register style rope) rmap modifyStateE $ \state -> state { vsRegisterMap = rmap' } normalizeCountE :: Maybe Int -> EditorM () normalizeCountE n = do mcount <- getMaybeCountE modifyStateE $ \s -> s { vsCount = maybeMult mcount n , vsAccumulator = Ev (showT . fromMaybe 1 $ maybeMult mcount n) <> snd (splitCountedCommand . normalizeCount $ vsAccumulator s) } maybeMult :: Num a => Maybe a -> Maybe a -> Maybe a maybeMult (Just a) (Just b) = Just (a * b) maybeMult Nothing Nothing = Nothing maybeMult a Nothing = a maybeMult Nothing b = b updateModeIndicatorE :: VimState -> EditorM () updateModeIndicatorE prevState = do currentState <- getEditorDyn let mode = vsMode currentState prevMode = vsMode prevState paste = vsPaste currentState isRecording = isJust . vsCurrentMacroRecording $ currentState prevRecording = isJust . vsCurrentMacroRecording $ prevState when (mode /= prevMode || isRecording /= prevRecording) $ do let modeName = case mode of Insert _ -> "INSERT" <> if paste then " (paste) " else "" InsertNormal -> "(insert)" InsertVisual -> "(insert) VISUAL" Replace -> "REPLACE" Visual Block -> "VISUAL BLOCK" Visual LineWise -> "VISUAL LINE" Visual _ -> "VISUAL" _ -> "" decoratedModeName' = if T.null modeName then mempty else "-- " <> modeName <> " --" decoratedModeName = if isRecording then decoratedModeName' <> "recording" else decoratedModeName' setStatus ([decoratedModeName], defaultStyle) saveInsertEventStringE :: EventString -> EditorM () saveInsertEventStringE evs = modifyStateE $ \s -> s { vsOngoingInsertEvents = vsOngoingInsertEvents s <> evs } resetActiveRegisterE :: EditorM () resetActiveRegisterE = modifyStateE $ \s -> s { vsActiveRegister = '\0' }
Fuuzetsu/yi
yi-keymap-vim/src/Yi/Keymap/Vim/StateUtils.hs
gpl-2.0
6,122
0
17
1,679
1,534
820
714
138
11
main = (1.0e10, 3.0e-4, 4.5e+2, 1E-4, 2E4, 3.0E+4, 4E-20)
roberth/uu-helium
test/parser/Exponent.hs
gpl-3.0
58
0
5
9
27
17
10
1
1
{- | == Convenience header for basic GObject-Introspection modules See the documentation for each individual module for a description and usage help. -} module Data.GI.Base ( module Data.GI.Base.Attributes , module Data.GI.Base.BasicConversions , module Data.GI.Base.BasicTypes , module Data.GI.Base.Closure , module Data.GI.Base.Constructible , module Data.GI.Base.GError , module Data.GI.Base.GHashTable , module Data.GI.Base.GObject , module Data.GI.Base.GValue , module Data.GI.Base.GVariant , module Data.GI.Base.ManagedPtr , module Data.GI.Base.Signals ) where import Data.GI.Base.Attributes (get, set, AttrOp(..)) import Data.GI.Base.BasicConversions import Data.GI.Base.BasicTypes import Data.GI.Base.Closure import Data.GI.Base.Constructible (new) import Data.GI.Base.GError import Data.GI.Base.GHashTable import Data.GI.Base.GObject (new') import Data.GI.Base.GValue (GValue(..), IsGValue(..)) import Data.GI.Base.GVariant import Data.GI.Base.ManagedPtr import Data.GI.Base.Signals (on, after, SignalProxy(PropertyNotify))
hamishmack/haskell-gi-base
src/Data/GI/Base.hs
lgpl-2.1
1,090
0
6
154
246
176
70
25
0
{-# LANGUAGE DeriveGeneric #-} {- | Module: Network.SoundCloud.MiniUser Copyright: (c) 2012 Sebastián Ramírez Magrí <sebasmagri@gmail.com> License: BSD3 Maintainer: Sebastián Ramírez Magrí <sebasmagri@gmail.com> Stability: experimental Minimal representation of an user used when embedding users information on other resources information -} module Network.SoundCloud.MiniUser where import Data.Aeson (FromJSON, ToJSON, decode) import qualified Data.ByteString.Lazy.Char8 as BSL import GHC.Generics (Generic) -- | Represents mini user JSON as a record data JSON = JSON { id :: Int , username :: String , uri :: String , permalink_url :: String , avatar_url :: Maybe String } deriving (Show, Generic) instance FromJSON JSON instance ToJSON JSON -- | Decode a 'JSON' record from a valid miniuser -- JSON string decodeJSON :: String -> Maybe JSON decodeJSON dat = decode (BSL.pack dat) :: Maybe JSON
sebasmagri/HScD
src/Network/SoundCloud/MiniUser.hs
bsd-3-clause
1,076
0
9
300
152
90
62
15
1
-------------------------------------------------------------------------------- -- | -- Module : HEP.Data.LHEF.PipesUtil -- Copyright : (c) 2017 Chan Beom Park -- License : BSD-style -- Maintainer : Chan Beom Park <cbpark@gmail.com> -- Stability : experimental -- Portability : GHC -- -- Helper functions for analyses of LHEF data files using pipes. -- -------------------------------------------------------------------------------- module HEP.Data.LHEF.PipesUtil ( getLHEFEvent , initialStates , finalStates , groupByMother ) where import HEP.Data.LHEF.Parser (lhefEvent) import HEP.Data.LHEF.Type import HEP.Data.ParserUtil (parseEvent) import Data.ByteString (ByteString) import qualified Data.IntMap as M import Pipes import qualified Pipes.Prelude as P import Control.Monad (forever) import Data.Function (on) import Data.List (groupBy) -- | Parsing LHEF event, 'Event' -- -- Example usage: -- -- > import HEP.Data.LHEF (getLHEFEvent) -- > import Pipes (runEffect, (>->)) -- > import Pipes.ByteString (fromHandle) -- > import qualified Pipes.Prelude as P -- > import System.Environment (getArgs) -- > import System.IO (IOMode (..), withFile) -- > -- > main :: IO () -- > main = do -- > infile <- head <$> getArgs -- > withFile infile ReadMode $ \hin -> -- > runEffect $ getLHEFEvent fromHandle hin >-> P.take 3 >-> P.print -- > putStrLn "-- Done parsing." getLHEFEvent :: Monad m => (a -> Producer ByteString m ()) -> a -> Producer Event m () getLHEFEvent produce = parseEvent lhefEvent . produce getParticles :: Monad m => (Particle -> Bool) -> Pipe EventEntry [Particle] m () getParticles f = forever $ particles >-> getSome where particles = P.map M.elems getSome = void $ await >>= yield . filter f initialStates :: Monad m => Pipe EventEntry [Particle] m () initialStates = getParticles ((==1) . fst . mothup) finalStates :: Monad m => Pipe EventEntry [Particle] m () finalStates = getParticles ((==1) . istup) groupByMother :: Monad m => Pipe [Particle] [[Particle]] m () groupByMother = P.map (groupBy ((==) `on` mothup))
cbpark/hep-kinematics
src/HEP/Data/LHEF/PipesUtil.hs
bsd-3-clause
2,385
0
10
646
440
258
182
31
1
module Data.Yaml.Union ( decodeBytestrings , decodeBytestringsEither , decodeFiles , decodeFilesEither ) where import Data.ByteString (ByteString) import Data.Foldable import qualified Data.HashMap.Strict as M import Data.Yaml hiding (decodeFile, decodeFileEither) import Data.Yaml.Include import Data.Maybe (mapMaybe, fromJust ) import Data.Vector (Vector) import qualified Data.Vector as Vec -- | Decode multiple YAML strings and override fields recursively decodeBytestrings :: FromJSON a => [ByteString] -> Maybe a decodeBytestrings = parseMaybe parseJSON . Object . unions . mapMaybe decode -- | Decode multiple YAML strings and override fields recursively decodeBytestringsEither :: FromJSON a => [ByteString] -> Either String a decodeBytestringsEither = parseEither parseJSON . Object . unions . mapMaybe decode -- | Decode multiple YAML-files and override fields recursively decodeFiles :: FromJSON a => [FilePath] -> IO (Maybe a) decodeFiles fs = do s <- mapM (\f -> do s <- decodeFile f return $ fromJust s) fs return $ parseMaybe parseJSON . Object . unions $ s -- | Decode multiple YAML-files and override fields recursively decodeFilesEither :: FromJSON a => [FilePath] -> IO (Either String a) decodeFilesEither fs = do s <- mapM (\f -> do s <- decodeFileEither f case s of Left err -> error (show err) Right x -> return x) fs return $ parseEither parseJSON . Object . unions $ s unions :: [Object] -> Object unions = foldl' union M.empty union :: Object -> Object -> Object union = M.unionWith dispatch dispatch :: Value -> Value -> Value dispatch (Object v1) (Object v2) = Object (v1 `union` v2) dispatch (Array v1) (Array v2) = Array $ vecUnion v1 v2 dispatch _ x = x vecUnion :: Eq a => Vector a -> Vector a -> Vector a vecUnion = vecUnionBy (==) vecUnionBy :: (a -> a -> Bool) -> Vector a -> Vector a -> Vector a vecUnionBy eq xs ys = (Vec.++) xs (foldl (flip (vecDeleteBy eq)) (vecNubBy eq ys) xs) vecDeleteBy :: (a -> a -> Bool) -> a -> Vector a -> Vector a vecDeleteBy eq x ys | Vec.length ys == 0 = ys | otherwise = if x `eq` Vec.head ys then Vec.tail ys else Vec.head ys `Vec.cons` vecDeleteBy eq x (Vec.tail ys) vecNubBy :: (a -> a -> Bool) -> Vector a -> Vector a vecNubBy eq vec | Vec.length vec == 0 = vec | otherwise = Vec.head vec `Vec.cons` vecNubBy eq (Vec.filter (not . eq (Vec.head vec)) (Vec.tail vec))
michelk/yaml-overrides.hs
src/Data/Yaml/Union.hs
bsd-3-clause
2,570
0
18
630
919
467
452
70
2
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} -- | Some next-gen helper functions for the scaffolding's configuration system. module Yesod.Default.Config2 ( -- * Locally defined configSettingsYml , getDevSettings , develMainHelper , makeYesodLogger -- * Re-exports from Data.Yaml.Config , applyCurrentEnv , getCurrentEnv , applyEnvValue , loadYamlSettings , loadYamlSettingsArgs , EnvUsage , ignoreEnv , useEnv , requireEnv , useCustomEnv , requireCustomEnv -- * For backwards compatibility , MergedValue (..) , loadAppSettings , loadAppSettingsArgs ) where import Data.Yaml.Config import Data.Semigroup import Data.Aeson import qualified Data.HashMap.Strict as H import System.Environment (getEnvironment) import Network.Wai (Application) import Network.Wai.Handler.Warp import Text.Read (readMaybe) import Data.Maybe (fromMaybe) import Control.Concurrent (forkIO, threadDelay) import System.Exit (exitSuccess) import System.Directory (doesFileExist) import Network.Wai.Logger (clockDateCacher) import Yesod.Core.Types (Logger (Logger)) import System.Log.FastLogger (LoggerSet) #ifndef mingw32_HOST_OS import System.Posix.Signals (installHandler, sigINT, Handler(Catch)) #endif newtype MergedValue = MergedValue { getMergedValue :: Value } instance Semigroup MergedValue where MergedValue x <> MergedValue y = MergedValue $ mergeValues x y -- | Left biased mergeValues :: Value -> Value -> Value mergeValues (Object x) (Object y) = Object $ H.unionWith mergeValues x y mergeValues x _ = x -- | Load the settings from the following three sources: -- -- * Run time config files -- -- * Run time environment variables -- -- * The default compile time config file loadAppSettings :: FromJSON settings => [FilePath] -- ^ run time config files to use, earlier files have precedence -> [Value] -- ^ any other values to use, usually from compile time config. overridden by files -> EnvUsage -> IO settings loadAppSettings = loadYamlSettings {-# DEPRECATED loadAppSettings "Use loadYamlSettings" #-} -- | Same as @loadAppSettings@, but get the list of runtime config files from -- the command line arguments. loadAppSettingsArgs :: FromJSON settings => [Value] -- ^ any other values to use, usually from compile time config. overridden by files -> EnvUsage -- ^ use environment variables -> IO settings loadAppSettingsArgs = loadYamlSettingsArgs {-# DEPRECATED loadAppSettingsArgs "Use loadYamlSettingsArgs" #-} -- | Location of the default config file. configSettingsYml :: FilePath configSettingsYml = "config/settings.yml" -- | Helper for getApplicationDev in the scaffolding. Looks up PORT and -- DISPLAY_PORT and prints appropriate messages. getDevSettings :: Settings -> IO Settings getDevSettings settings = do env <- getEnvironment let p = fromMaybe (getPort settings) $ lookup "PORT" env >>= readMaybe pdisplay = fromMaybe p $ lookup "DISPLAY_PORT" env >>= readMaybe putStrLn $ "Devel application launched: http://localhost:" ++ show pdisplay return $ setPort p settings -- | Helper for develMain in the scaffolding. develMainHelper :: IO (Settings, Application) -> IO () develMainHelper getSettingsApp = do #ifndef mingw32_HOST_OS _ <- installHandler sigINT (Catch $ return ()) Nothing #endif putStrLn "Starting devel application" (settings, app) <- getSettingsApp _ <- forkIO $ runSettings settings app loop where loop :: IO () loop = do threadDelay 100000 e <- doesFileExist "yesod-devel/devel-terminate" if e then terminateDevel else loop terminateDevel :: IO () terminateDevel = exitSuccess -- | Create a 'Logger' value (from yesod-core) out of a 'LoggerSet' (from -- fast-logger). makeYesodLogger :: LoggerSet -> IO Logger makeYesodLogger loggerSet' = do (getter, _) <- clockDateCacher return $! Yesod.Core.Types.Logger loggerSet' getter
s9gf4ult/yesod
yesod/Yesod/Default/Config2.hs
mit
3,998
0
14
753
754
423
331
86
2
module Main (main) where import Graphics.UI.Gtk {- widgets that go into making a menubar and submenus: * menu item (what the user wants to select) * menu (acts as a container for the menu items) * menubar (container for each of the individual menus) menuitem widgets are used for two different things: * they are packed into the menu * they are packed into the menubar, which, when selected, activates the menu Functions: * menuBarNew creates a new menubar, which can be packed into a container like a window or a box * menuNew creates a new menu, which is never actually shown; it is just a container for the menu items * menuItemNew, menuItemNewWithLabel, menuItemMenuWithMnemonic create the menu items that are to be displayed; they are actually buttons with associated actions Once a menu item has been created, it should be put into a menu with the menuShellAppend function. In order to capture when the item is selected by the user, the activate signal need to be connected in the usual way. -} createMenuBar descr = do bar <- menuBarNew mapM_ (createMenu bar) descr return bar where createMenu bar (name,items) = do menu <- menuNew item <- menuItemNewWithLabelOrMnemonic name menuItemSetSubmenu item menu menuShellAppend bar item mapM_ (createMenuItem menu) items createMenuItem menu (name,action) = do item <- menuItemNewWithLabelOrMnemonic name menuShellAppend menu item case action of Just act -> onActivateLeaf item act Nothing -> onActivateLeaf item (return ()) menuItemNewWithLabelOrMnemonic name | elem '_' name = menuItemNewWithMnemonic name | otherwise = menuItemNewWithLabel name menuBarDescr = [ ("_File", [ ("Open", Nothing) , ("Save", Nothing) , ("_Quit", Just mainQuit) ] ) , ("Help", [ ("_Help", Nothing) ] ) ] main = do initGUI window <- windowNew menuBar <- createMenuBar menuBarDescr set window [ windowTitle := "Demo" , containerChild := menuBar ] onDestroy window mainQuit widgetShowAll window mainGUI
phischu/gtk2hs
gtk/demo/menu/MenuDemo.hs
lgpl-3.0
2,395
0
15
769
350
171
179
35
2
{- ****************************************************************************** * H M T C * * * * Module: TAMCode * * Purpose: Triangle Abstract Machine (TAM) Code * * Authors: Henrik Nilsson * * * * Copyright (c) Henrik Nilsson, 2006 - 2013 * * * ****************************************************************************** -} -- | Triangle Abstract Machine (TAM) Code. module TAMCode ( MTInt, -- TAM integer type Addr(..), -- Address TAMInst(..) ) where -- HMTC module imports import Name import Type (MTInt) -- | TAM stack addresses data Addr = SB MTInt -- ^ SB (Stack base) + displacement: [SB + d] | LB MTInt -- ^ LB (Local Base) + displacement: [LB + d] | ST MTInt -- ^ ST (Stack Top) + displacement: [ST + d] deriving (Eq, Show) -- | TAM instruction type. data TAMInst -- Label = Label Name -- ^ Symbolic location (pseudo instruction) -- Load and store | LOADL MTInt -- ^ Push literal integer onto stack | LOADCA Name -- ^ Push code address onto stack | LOAD Addr -- ^ Push contents at addres onto stack | LOADA Addr -- ^ Push address onto stack | LOADI MTInt -- ^ Load indirectly; addr = top elem.+displ. | STORE Addr -- ^ Pop elem. from stack and store at address | STOREI MTInt -- ^ Store indirectly; addr = top elem.+displ. -- Block operations | LOADLB MTInt MTInt -- ^ Push block of literal integer onto stack | LOADIB MTInt -- ^ Load block indirectly; addr = top elem. | STOREIB MTInt -- ^ Store block indirectly; addr = top elem. | POP MTInt MTInt -- ^ POP m n: pop n elements below top m elems. -- Aritmetic operations | ADD -- ^ [b, a, ...] => [a + b, ...] | SUB -- ^ [b, a, ...] => [a - b, ...] | MUL -- ^ [b, a, ...] => [a * b, ...] | DIV -- ^ [b, a, ...] => [a / b, ...] | NEG -- ^ [a, ...] => [-a, ...] -- Comparison & logical ops: false = 0, true = 1 (as arg., anything /= 0) | LSS -- ^ [b, a, ...] => [a < b, ...] | EQL -- ^ [b, a, ...] => [a == b, ...] | GTR -- ^ [b, a, ...] => [a > b, ...] | AND -- ^ [b, a, ...] => [a && b, ...] | OR -- ^ [b, a, ...] => [a || b, ...] | NOT -- ^ [a, ...] => [!a, ...] -- Control transfer | JUMP Name -- ^ Jump unconditionally | JUMPIFZ Name -- ^ Pop top value, jump if zero (false) | JUMPIFNZ Name -- ^ Pop top value, jump if not zero (true) | CALL Name -- ^ Call global subroutine | CALLI -- ^ Call indirectly; addr & static lnk on stk | RETURN MTInt MTInt -- ^ RETURN m n: result size m, args size n. -- I/O | PUTINT -- ^ Pop and print top element to terminal | PUTCHR -- ^ Pop and print top element interp. as char. | GETINT -- ^ Read an integer and push onto stack | GETCHR -- ^ Read a character and push onto stack -- TAM Control | HALT -- ^ Stop TAM deriving (Eq, Show)
jbracker/supermonad-plugin
examples/monad/hmtc/original/TAMCode.hs
bsd-3-clause
3,981
0
6
1,890
273
188
85
47
0
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for the @/proc/diskstats@ parser -} {- Copyright (C) 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Test.Ganeti.Storage.Diskstats.Parser (testBlock_Diskstats_Parser) where import Test.QuickCheck as QuickCheck hiding (Result) import Test.HUnit import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Control.Applicative ((<*>), (<$>)) import qualified Data.Attoparsec.Text as A import Data.Text (pack) import Text.Printf import Ganeti.Storage.Diskstats.Parser (diskstatsParser) import Ganeti.Storage.Diskstats.Types {-# ANN module "HLint: ignore Use camelCase" #-} -- | Test a diskstats. case_diskstats :: Assertion case_diskstats = testParser diskstatsParser "proc_diskstats.txt" [ Diskstats 1 0 "ram0" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 1 "ram1" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 2 "ram2" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 3 "ram3" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 4 "ram4" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 5 "ram5" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 6 "ram6" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 7 "ram7" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 8 "ram8" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 9 "ram9" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 10 "ram10" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 11 "ram11" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 12 "ram12" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 13 "ram13" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 14 "ram14" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 1 15 "ram15" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 7 0 "loop0" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 7 1 "loop1" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 7 2 "loop2" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 7 3 "loop3" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 7 4 "loop4" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 7 5 "loop5" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 7 6 "loop6" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 7 7 "loop7" 0 0 0 0 0 0 0 0 0 0 0 , Diskstats 8 0 "sda" 89502 4833 4433387 89244 519115 62738 16059726 465120 0 149148 554564 , Diskstats 8 1 "sda1" 505 2431 8526 132 478 174 124358 8500 0 340 8632 , Diskstats 8 2 "sda2" 2 0 4 4 0 0 0 0 0 4 4 , Diskstats 8 5 "sda5" 88802 2269 4422249 89032 453703 62564 15935368 396244 0 90064 485500 , Diskstats 252 0 "dm-0" 90978 0 4420002 158632 582226 0 15935368 5592012 0 167688 5750652 , Diskstats 252 1 "dm-1" 88775 0 4402378 157204 469594 0 15136008 4910424 0 164556 5067640 , Diskstats 252 2 "dm-2" 1956 0 15648 1052 99920 0 799360 682492 0 4516 683552 , Diskstats 8 16 "sdb" 0 0 0 0 0 0 0 0 0 0 0 ] -- | The instance for generating arbitrary Diskstats instance Arbitrary Diskstats where arbitrary = Diskstats <$> genNonNegative <*> genNonNegative <*> genName <*> genNonNegative <*> genNonNegative <*> genNonNegative <*> genNonNegative <*> genNonNegative <*> genNonNegative <*> genNonNegative <*> genNonNegative <*> genNonNegative <*> genNonNegative <*> genNonNegative -- | Serialize a list of Diskstats in a parsable way serializeDiskstatsList :: [Diskstats] -> String serializeDiskstatsList = concatMap serializeDiskstats -- | Serialize a Diskstats in a parsable way serializeDiskstats :: Diskstats -> String serializeDiskstats ds = printf "\t%d\t%d %s %d %d %d %d %d %d %d %d %d %d %d\n" (dsMajor ds) (dsMinor ds) (dsName ds) (dsReadsNum ds) (dsMergedReads ds) (dsSecRead ds) (dsTimeRead ds) (dsWrites ds) (dsMergedWrites ds) (dsSecWritten ds) (dsTimeWrite ds) (dsIos ds) (dsTimeIO ds) (dsWIOmillis ds) -- | Test whether an arbitrary Diskstats is parsed correctly prop_diskstats :: [Diskstats] -> Property prop_diskstats dsList = case A.parseOnly diskstatsParser $ pack (serializeDiskstatsList dsList) of Left msg -> failTest $ "Parsing failed: " ++ msg Right obtained -> dsList ==? obtained testSuite "Block/Diskstats/Parser" [ 'case_diskstats, 'prop_diskstats ]
vladimir-ipatov/ganeti
test/hs/Test/Ganeti/Storage/Diskstats/Parser.hs
gpl-2.0
4,633
0
19
1,097
1,464
758
706
75
2
{-| Module : IRTS.Lang Description : Internal representation of Idris' constructs. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE DeriveFunctor, DeriveGeneric, PatternGuards #-} module IRTS.Lang where import Idris.Core.CaseTree import Idris.Core.TT import Control.Applicative hiding (Const) import Control.Monad.State hiding (lift) import Data.List import Debug.Trace import GHC.Generics (Generic) data Endianness = Native | BE | LE deriving (Show, Eq) data LVar = Loc Int | Glob Name deriving (Show, Eq) -- ASSUMPTION: All variable bindings have unique names here -- Constructors commented as lifted are not present in the LIR provided to the different backends. data LExp = LV LVar | LApp Bool LExp [LExp] -- True = tail call | LLazyApp Name [LExp] -- True = tail call | LLazyExp LExp -- lifted out before compiling | LForce LExp -- make sure Exp is evaluted | LLet Name LExp LExp -- name just for pretty printing | LLam [Name] LExp -- lambda, lifted out before compiling | LProj LExp Int -- projection | LCon (Maybe LVar) -- Location to reallocate, if available Int Name [LExp] | LCase CaseType LExp [LAlt] | LConst Const | LForeign FDesc -- Function descriptor (usually name as string) FDesc -- Return type descriptor [(FDesc, LExp)] -- first LExp is the FFI type description | LOp PrimFn [LExp] | LNothing | LError String deriving Eq data FDesc = FCon Name | FStr String | FUnknown | FIO FDesc | FApp Name [FDesc] deriving (Show, Eq) data Export = ExportData FDesc -- Exported data descriptor (usually string) | ExportFun Name -- Idris name FDesc -- Exported function descriptor FDesc -- Return type descriptor [FDesc] -- Argument types deriving (Show, Eq) data ExportIFace = Export Name -- FFI descriptor String -- interface file [Export] deriving (Show, Eq) -- Primitive operators. Backends are not *required* to implement all -- of these, but should report an error if they are unable data PrimFn = LPlus ArithTy | LMinus ArithTy | LTimes ArithTy | LUDiv IntTy | LSDiv ArithTy | LURem IntTy | LSRem ArithTy | LAnd IntTy | LOr IntTy | LXOr IntTy | LCompl IntTy | LSHL IntTy | LLSHR IntTy | LASHR IntTy | LEq ArithTy | LLt IntTy | LLe IntTy | LGt IntTy | LGe IntTy | LSLt ArithTy | LSLe ArithTy | LSGt ArithTy | LSGe ArithTy | LSExt IntTy IntTy | LZExt IntTy IntTy | LTrunc IntTy IntTy | LStrConcat | LStrLt | LStrEq | LStrLen | LIntFloat IntTy | LFloatInt IntTy | LIntStr IntTy | LStrInt IntTy | LFloatStr | LStrFloat | LChInt IntTy | LIntCh IntTy | LBitCast ArithTy ArithTy -- Only for values of equal width | LFExp | LFLog | LFSin | LFCos | LFTan | LFASin | LFACos | LFATan | LFSqrt | LFFloor | LFCeil | LFNegate | LStrHead | LStrTail | LStrCons | LStrIndex | LStrRev | LStrSubstr | LReadStr | LWriteStr -- system info | LSystemInfo | LFork | LPar -- evaluate argument anywhere, possibly on another -- core or another machine. 'id' is a valid implementation | LExternal Name | LCrash | LNoOp deriving (Show, Eq, Generic) -- Supported target languages for foreign calls data FCallType = FStatic | FObject | FConstructor deriving (Show, Eq) data FType = FArith ArithTy | FFunction | FFunctionIO | FString | FUnit | FPtr | FManagedPtr | FCData | FAny deriving (Show, Eq) -- FIXME: Why not use this for all the IRs now? data LAlt' e = LConCase Int Name [Name] e | LConstCase Const e | LDefaultCase e deriving (Show, Eq, Functor) type LAlt = LAlt' LExp data LDecl = LFun [LOpt] Name [Name] LExp -- options, name, arg names, def | LConstructor Name Int Int -- constructor name, tag, arity deriving (Show, Eq) type LDefs = Ctxt LDecl data LOpt = Inline | NoInline deriving (Show, Eq) addTags :: Int -> [(Name, LDecl)] -> (Int, [(Name, LDecl)]) addTags i ds = tag i ds [] where tag i ((n, LConstructor n' (-1) a) : as) acc = tag (i + 1) as ((n, LConstructor n' i a) : acc) tag i ((n, LConstructor n' t a) : as) acc = tag i as ((n, LConstructor n' t a) : acc) tag i (x : as) acc = tag i as (x : acc) tag i [] acc = (i, reverse acc) data LiftState = LS Name Int [(Name, LDecl)] lname (NS n x) i = NS (lname n i) x lname (UN n) i = MN i n lname x i = sMN i (showCG x ++ "_lam") liftAll :: [(Name, LDecl)] -> [(Name, LDecl)] liftAll xs = concatMap (\ (x, d) -> lambdaLift x d) xs lambdaLift :: Name -> LDecl -> [(Name, LDecl)] lambdaLift n (LFun opts _ args e) = let (e', (LS _ _ decls)) = runState (lift args e) (LS n 0 []) in (n, LFun opts n args e') : decls lambdaLift n x = [(n, x)] getNextName :: State LiftState Name getNextName = do LS n i ds <- get put (LS n (i + 1) ds) return (lname n i) addFn :: Name -> LDecl -> State LiftState () addFn fn d = do LS n i ds <- get put (LS n i ((fn, d) : ds)) lift :: [Name] -> LExp -> State LiftState LExp lift env (LV v) = return (LV v) -- Lifting happens before these can exist... lift env (LApp tc (LV (Glob n)) args) = do args' <- mapM (lift env) args return (LApp tc (LV (Glob n)) args') lift env (LApp tc f args) = do f' <- lift env f fn <- getNextName addFn fn (LFun [Inline] fn env f') args' <- mapM (lift env) args return (LApp tc (LV (Glob fn)) (map (LV . Glob) env ++ args')) lift env (LLazyApp n args) = do args' <- mapM (lift env) args return (LLazyApp n args') lift env (LLazyExp (LConst c)) = return (LConst c) -- lift env (LLazyExp (LApp tc (LV (Glob f)) args)) -- = lift env (LLazyApp f args) lift env (LLazyExp e) = do e' <- lift env e let usedArgs = nub $ usedIn env e' fn <- getNextName addFn fn (LFun [NoInline] fn usedArgs e') return (LLazyApp fn (map (LV . Glob) usedArgs)) lift env (LForce e) = do e' <- lift env e return (LForce e') lift env (LLet n v e) = do v' <- lift env v e' <- lift (env ++ [n]) e return (LLet n v' e') lift env (LLam args e) = do e' <- lift (env ++ args) e let usedArgs = nub $ usedIn env e' fn <- getNextName addFn fn (LFun [Inline] fn (usedArgs ++ args) e') return (LApp False (LV (Glob fn)) (map (LV . Glob) usedArgs)) lift env (LProj t i) = do t' <- lift env t return (LProj t' i) lift env (LCon loc i n args) = do args' <- mapM (lift env) args return (LCon loc i n args') lift env (LCase up e alts) = do alts' <- mapM liftA alts e' <- lift env e return (LCase up e' alts') where liftA (LConCase i n args e) = do e' <- lift (env ++ args) e return (LConCase i n args e') liftA (LConstCase c e) = do e' <- lift env e return (LConstCase c e') liftA (LDefaultCase e) = do e' <- lift env e return (LDefaultCase e') lift env (LConst c) = return (LConst c) lift env (LForeign t s args) = do args' <- mapM (liftF env) args return (LForeign t s args') where liftF env (t, e) = do e' <- lift env e return (t, e') lift env (LOp f args) = do args' <- mapM (lift env) args return (LOp f args') lift env (LError str) = return $ LError str lift env LNothing = return LNothing allocUnique :: LDefs -> (Name, LDecl) -> (Name, LDecl) allocUnique defs p@(n, LConstructor _ _ _) = p allocUnique defs (n, LFun opts fn args e) = let e' = evalState (findUp e) [] in (n, LFun opts fn args e') where -- Keep track of 'updatable' names in the state, i.e. names whose heap -- entry may be reused, along with the arity which was there findUp :: LExp -> State [(Name, Int)] LExp findUp (LApp t (LV (Glob n)) as) | Just (LConstructor _ i ar) <- lookupCtxtExact n defs, ar == length as = findUp (LCon Nothing i n as) findUp (LV (Glob n)) | Just (LConstructor _ i 0) <- lookupCtxtExact n defs = return $ LCon Nothing i n [] -- nullary cons are global, no need to update findUp (LApp t f as) = LApp t <$> findUp f <*> mapM findUp as findUp (LLazyApp n as) = LLazyApp n <$> mapM findUp as findUp (LLazyExp e) = LLazyExp <$> findUp e findUp (LForce e) = LForce <$> findUp e -- use assumption that names are unique! findUp (LLet n val sc) = LLet n <$> findUp val <*> findUp sc findUp (LLam ns sc) = LLam ns <$> findUp sc findUp (LProj e i) = LProj <$> findUp e <*> return i findUp (LCon (Just l) i n es) = LCon (Just l) i n <$> mapM findUp es findUp (LCon Nothing i n es) = do avail <- get v <- findVar [] avail (length es) LCon v i n <$> mapM findUp es findUp (LForeign t s es) = LForeign t s <$> mapM (\ (t, e) -> do e' <- findUp e return (t, e')) es findUp (LOp o es) = LOp o <$> mapM findUp es findUp (LCase Updatable e@(LV (Glob n)) as) = LCase Updatable e <$> mapM (doUpAlt n) as findUp (LCase t e as) = LCase t <$> findUp e <*> mapM findUpAlt as findUp t = return t findUpAlt (LConCase i t args rhs) = do avail <- get rhs' <- findUp rhs put avail return $ LConCase i t args rhs' findUpAlt (LConstCase i rhs) = LConstCase i <$> findUp rhs findUpAlt (LDefaultCase rhs) = LDefaultCase <$> findUp rhs doUpAlt n (LConCase i t args rhs) = do avail <- get put ((n, length args) : avail) rhs' <- findUp rhs put avail return $ LConCase i t args rhs' doUpAlt n (LConstCase i rhs) = LConstCase i <$> findUp rhs doUpAlt n (LDefaultCase rhs) = LDefaultCase <$> findUp rhs findVar _ [] i = return Nothing findVar acc ((n, l) : ns) i | l == i = do put (reverse acc ++ ns) return (Just (Glob n)) findVar acc (n : ns) i = findVar (n : acc) ns i -- Return variables in list which are used in the expression usedArg env n | n `elem` env = [n] | otherwise = [] usedIn :: [Name] -> LExp -> [Name] usedIn env (LV (Glob n)) = usedArg env n usedIn env (LApp _ e args) = usedIn env e ++ concatMap (usedIn env) args usedIn env (LLazyApp n args) = concatMap (usedIn env) args ++ usedArg env n usedIn env (LLazyExp e) = usedIn env e usedIn env (LForce e) = usedIn env e usedIn env (LLet n v e) = usedIn env v ++ usedIn (env \\ [n]) e usedIn env (LLam ns e) = usedIn (env \\ ns) e usedIn env (LCon v i n args) = let rest = concatMap (usedIn env) args in case v of Nothing -> rest Just (Glob n) -> usedArg env n ++ rest usedIn env (LProj t i) = usedIn env t usedIn env (LCase up e alts) = usedIn env e ++ concatMap (usedInA env) alts where usedInA env (LConCase i n ns e) = usedIn env e usedInA env (LConstCase c e) = usedIn env e usedInA env (LDefaultCase e) = usedIn env e usedIn env (LForeign _ _ args) = concatMap (usedIn env) (map snd args) usedIn env (LOp f args) = concatMap (usedIn env) args usedIn env _ = [] lsubst :: Name -> LExp -> LExp -> LExp lsubst n new (LV (Glob x)) | n == x = new lsubst n new (LApp t e args) = let e' = lsubst n new e args' = map (lsubst n new) args in LApp t e' args' lsubst n new (LLazyApp fn args) = let args' = map (lsubst n new) args in LLazyApp fn args' lsubst n new (LLazyExp e) = LLazyExp (lsubst n new e) lsubst n new (LForce e) = LForce (lsubst n new e) lsubst n new (LLet v val sc) = LLet v (lsubst n new val) (lsubst n new sc) lsubst n new (LLam ns sc) = LLam ns (lsubst n new sc) lsubst n new (LProj e i) = LProj (lsubst n new e) i lsubst n new (LCon lv t cn args) = let args' = map (lsubst n new) args in LCon lv t cn args' lsubst n new (LOp op args) = let args' = map (lsubst n new) args in LOp op args' lsubst n new (LForeign fd rd args) = let args' = map (\(d, a) -> (d, lsubst n new a)) args in LForeign fd rd args' lsubst n new (LCase t e alts) = let e' = lsubst n new e alts' = map (fmap (lsubst n new)) alts in LCase t e' alts' lsubst n new tm = tm instance Show LExp where show e = show' [] "" e where show' env ind (LV (Loc i)) = env!!i show' env ind (LV (Glob n)) = show n show' env ind (LLazyApp e args) = show e ++ "|(" ++ showSep ", " (map (show' env ind) args) ++")" show' env ind (LApp _ e args) = show' env ind e ++ "(" ++ showSep ", " (map (show' env ind) args) ++")" show' env ind (LLazyExp e) = "lazy{ " ++ show' env ind e ++ " }" show' env ind (LForce e) = "force{ " ++ show' env ind e ++ " }" show' env ind (LLet n v e) = "let " ++ show n ++ " = " ++ show' env ind v ++ " in " ++ show' (env ++ [show n]) ind e show' env ind (LLam args e) = "\\ " ++ showSep "," (map show args) ++ " => " ++ show' (env ++ (map show args)) ind e show' env ind (LProj t i) = show t ++ "!" ++ show i show' env ind (LCon loc i n args) = atloc loc ++ show n ++ "(" ++ showSep ", " (map (show' env ind) args) ++ ")" where atloc Nothing = "" atloc (Just l) = "@" ++ show (LV l) ++ ":" show' env ind (LCase up e alts) = "case" ++ update ++ show' env ind e ++ " of \n" ++ fmt alts where update = case up of Shared -> " " Updatable -> "! " fmt [] = "" fmt [alt] = "\t" ++ ind ++ "| " ++ showAlt env (ind ++ " ") alt fmt (alt:as) = "\t" ++ ind ++ "| " ++ showAlt env (ind ++ ". ") alt ++ "\n" ++ fmt as show' env ind (LConst c) = show c show' env ind (LForeign ty n args) = concat [ "foreign{ " , show n ++ "(" , showSep ", " (map (\(ty,x) -> show' env ind x ++ " : " ++ show ty) args) , ") : " , show ty , " }" ] show' env ind (LOp f args) = show f ++ "(" ++ showSep ", " (map (show' env ind) args) ++ ")" show' env ind (LError str) = "error " ++ show str show' env ind LNothing = "____" showAlt env ind (LConCase _ n args e) = show n ++ "(" ++ showSep ", " (map show args) ++ ") => " ++ show' env ind e showAlt env ind (LConstCase c e) = show c ++ " => " ++ show' env ind e showAlt env ind (LDefaultCase e) = "_ => " ++ show' env ind e
bravit/Idris-dev
src/IRTS/Lang.hs
bsd-3-clause
16,194
0
17
6,046
6,140
3,093
3,047
313
22
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sr-CS"> <title>AMF Support</title> <maps> <homeID>amf</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/amf/src/main/javahelp/help_sr_CS/helpset_sr_CS.hs
apache-2.0
956
77
66
156
407
206
201
-1
-1
module LambdaIn1 where f z = \y@(j:js) -> j
SAdams601/HaRe
old/testing/simplifyExpr/LambdaIn1_TokOut.hs
bsd-3-clause
49
0
8
14
27
16
11
2
1
module T13644B where data FuncId = FuncId { name :: () }
ezyang/ghc
testsuite/tests/rename/should_fail/T13644B.hs
bsd-3-clause
75
0
9
30
21
13
8
2
0
{-# LANGUAGE MultiParamTypeClasses #-} -- | This module caused a duplicate instance in the documentation for the Foo -- type. module Bug7 where -- | The Foo datatype data Foo = Foo -- | The Bar class class Bar x y -- | Just one instance instance Bar Foo Foo
DavidAlphaFox/ghc
utils/haddock/html-test/src/Bug7.hs
bsd-3-clause
262
0
5
54
35
21
14
-1
-1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.Marshal.Utils -- Copyright : (c) The FFI task force 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : ffi@haskell.org -- Stability : provisional -- Portability : portable -- -- Utilities for primitive marshaling -- ----------------------------------------------------------------------------- module Foreign.Marshal.Utils ( -- * General marshalling utilities -- ** Combined allocation and marshalling -- with, new, -- ** Marshalling of Boolean values (non-zero corresponds to 'True') -- fromBool, toBool, -- ** Marshalling of Maybe values -- maybeNew, maybeWith, maybePeek, -- ** Marshalling lists of storable objects -- withMany, -- ** Haskellish interface to memcpy and memmove -- | (argument order: destination, source) -- copyBytes, moveBytes, -- ** Filling up memory area with required values -- fillBytes, ) where import Data.Maybe import Foreign.Ptr ( Ptr, nullPtr ) import Foreign.Storable ( Storable(poke) ) import Foreign.C.Types ( CSize(..), CInt(..) ) import Foreign.Marshal.Alloc ( malloc, alloca ) import Data.Word ( Word8 ) import GHC.Real ( fromIntegral ) import GHC.Num import GHC.Base -- combined allocation and marshalling -- ----------------------------------- -- |Allocate a block of memory and marshal a value into it -- (the combination of 'malloc' and 'poke'). -- The size of the area allocated is determined by the 'Foreign.Storable.sizeOf' -- method from the instance of 'Storable' for the appropriate type. -- -- The memory may be deallocated using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree' when no longer required. -- new :: Storable a => a -> IO (Ptr a) new val = do ptr <- malloc poke ptr val return ptr -- |@'with' val f@ executes the computation @f@, passing as argument -- a pointer to a temporarily allocated block of memory into which -- @val@ has been marshalled (the combination of 'alloca' and 'poke'). -- -- The memory is freed when @f@ terminates (either normally or via an -- exception), so the pointer passed to @f@ must /not/ be used after this. -- with :: Storable a => a -> (Ptr a -> IO b) -> IO b with val f = alloca $ \ptr -> do poke ptr val res <- f ptr return res -- marshalling of Boolean values (non-zero corresponds to 'True') -- ----------------------------- -- |Convert a Haskell 'Bool' to its numeric representation -- fromBool :: Num a => Bool -> a fromBool False = 0 fromBool True = 1 -- |Convert a Boolean in numeric representation to a Haskell value -- toBool :: (Eq a, Num a) => a -> Bool toBool = (/= 0) -- marshalling of Maybe values -- --------------------------- -- |Allocate storage and marshal a storable value wrapped into a 'Maybe' -- -- * the 'nullPtr' is used to represent 'Nothing' -- maybeNew :: ( a -> IO (Ptr b)) -> (Maybe a -> IO (Ptr b)) maybeNew = maybe (return nullPtr) -- |Converts a @withXXX@ combinator into one marshalling a value wrapped -- into a 'Maybe', using 'nullPtr' to represent 'Nothing'. -- maybeWith :: ( a -> (Ptr b -> IO c) -> IO c) -> (Maybe a -> (Ptr b -> IO c) -> IO c) maybeWith = maybe ($ nullPtr) -- |Convert a peek combinator into a one returning 'Nothing' if applied to a -- 'nullPtr' -- maybePeek :: (Ptr a -> IO b) -> Ptr a -> IO (Maybe b) maybePeek peek ptr | ptr == nullPtr = return Nothing | otherwise = do a <- peek ptr; return (Just a) -- marshalling lists of storable objects -- ------------------------------------- -- |Replicates a @withXXX@ combinator over a list of objects, yielding a list of -- marshalled objects -- withMany :: (a -> (b -> res) -> res) -- withXXX combinator for one object -> [a] -- storable objects -> ([b] -> res) -- action on list of marshalled obj.s -> res withMany _ [] f = f [] withMany withFoo (x:xs) f = withFoo x $ \x' -> withMany withFoo xs (\xs' -> f (x':xs')) -- Haskellish interface to memcpy and memmove -- ------------------------------------------ -- |Copies the given number of bytes from the second area (source) into the -- first (destination); the copied areas may /not/ overlap -- copyBytes :: Ptr a -> Ptr a -> Int -> IO () copyBytes dest src size = do _ <- memcpy dest src (fromIntegral size) return () -- |Copies the given number of bytes from the second area (source) into the -- first (destination); the copied areas /may/ overlap -- moveBytes :: Ptr a -> Ptr a -> Int -> IO () moveBytes dest src size = do _ <- memmove dest src (fromIntegral size) return () -- Filling up memory area with required values -- ------------------------------------------- -- |Fill a given number of bytes in memory area with a byte value. -- -- @since 4.8.0.0 fillBytes :: Ptr a -> Word8 -> Int -> IO () fillBytes dest char size = do _ <- memset dest (fromIntegral char) (fromIntegral size) return () -- auxilliary routines -- ------------------- -- |Basic C routines needed for memory copying -- foreign import ccall unsafe "string.h" memcpy :: Ptr a -> Ptr a -> CSize -> IO (Ptr a) foreign import ccall unsafe "string.h" memmove :: Ptr a -> Ptr a -> CSize -> IO (Ptr a) foreign import ccall unsafe "string.h" memset :: Ptr a -> CInt -> CSize -> IO (Ptr a)
tolysz/prepare-ghcjs
spec-lts8/base/Foreign/Marshal/Utils.hs
bsd-3-clause
5,752
0
12
1,405
1,107
604
503
69
1
{-# LANGUAGE KindSignatures #-} module Foo where data Foo (a :: *) = Foo a
urbanslug/ghc
testsuite/tests/parser/should_compile/read051.hs
bsd-3-clause
79
0
6
19
21
14
7
3
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ConstraintKinds #-} -- | Find all Alloc statements and associate their memory blocks with the -- allocation size. module Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizes ( memBlockSizesFunDef, memBlockSizesParamsBodyNonRec , Sizes ) where import qualified Data.Map.Strict as M import Control.Monad.Writer import Futhark.Representation.AST import Futhark.Representation.ExplicitMemory (ExplicitMemorish, ExplicitMemory, InKernel) import qualified Futhark.Representation.ExplicitMemory as ExpMem import Futhark.Representation.Kernels.Kernel import Futhark.Optimise.MemoryBlockMerging.Types import Futhark.Optimise.MemoryBlockMerging.Miscellaneous -- | maps memory blocks to its size and space/type type Sizes = M.Map MName (SubExp, Space) -- Also Space information newtype FindM lore a = FindM { unFindM :: Writer Sizes a } deriving (Monad, Functor, Applicative, MonadWriter Sizes) type LoreConstraints lore = (ExplicitMemorish lore, AllocSizeUtils lore, FullWalk lore) coerce :: (ExplicitMemorish flore, ExplicitMemorish tlore) => FindM flore a -> FindM tlore a coerce = FindM . unFindM recordMapping :: VName -> (SubExp, Space) -> FindM lore () recordMapping var (size, space) = tell $ M.singleton var (size, space) memBlockSizesFunDef :: LoreConstraints lore => FunDef lore -> Sizes memBlockSizesFunDef fundef = let m = unFindM $ do mapM_ lookInFParam $ funDefParams fundef lookInBody $ funDefBody fundef mem_sizes = execWriter m in mem_sizes memBlockSizesParamsBodyNonRec :: LoreConstraints lore => [FParam lore] -> Body lore -> Sizes memBlockSizesParamsBodyNonRec params body = let m = unFindM $ do mapM_ lookInFParam params mapM_ lookInStm $ bodyStms body mem_sizes = execWriter m in mem_sizes lookInFParam :: LoreConstraints lore => FParam lore -> FindM lore () lookInFParam (Param mem (ExpMem.MemMem size space)) = recordMapping mem (size, space) lookInFParam _ = return () lookInLParam :: LoreConstraints lore => LParam lore -> FindM lore () lookInLParam (Param mem (ExpMem.MemMem size space)) = recordMapping mem (size, space) lookInLParam _ = return () lookInBody :: LoreConstraints lore => Body lore -> FindM lore () lookInBody (Body _ bnds _res) = mapM_ lookInStmRec bnds lookInKernelBody :: LoreConstraints lore => KernelBody lore -> FindM lore () lookInKernelBody (KernelBody _ bnds _res) = mapM_ lookInStmRec bnds lookInStm :: LoreConstraints lore => Stm lore -> FindM lore () lookInStm (Let (Pattern patctxelems patvalelems) _ e) = do case patvalelems of [PatElem mem _ _] -> case lookForAllocSize e of Just (size, space) -> recordMapping mem (size, space) Nothing -> return () _ -> return () mapM_ lookInPatCtxElem patctxelems lookInStmRec :: LoreConstraints lore => Stm lore -> FindM lore () lookInStmRec stm@(Let _ _ e) = do lookInStm stm fullWalkExpM walker walker_kernel e where walker = identityWalker { walkOnBody = lookInBody , walkOnFParam = lookInFParam , walkOnLParam = lookInLParam } walker_kernel = identityKernelWalker { walkOnKernelBody = coerce . lookInBody , walkOnKernelKernelBody = coerce . lookInKernelBody , walkOnKernelLambda = coerce . lookInLambda , walkOnKernelLParam = lookInLParam } lookInPatCtxElem :: LoreConstraints lore => PatElem lore -> FindM lore () lookInPatCtxElem (PatElem mem _bindage (ExpMem.MemMem size space)) = recordMapping mem (size, space) lookInPatCtxElem _ = return () lookInLambda :: LoreConstraints lore => Lambda lore -> FindM lore () lookInLambda (Lambda params body _) = do forM_ params lookInLParam lookInBody body class AllocSizeUtils lore where lookForAllocSize :: Exp lore -> Maybe (SubExp, Space) instance AllocSizeUtils ExplicitMemory where lookForAllocSize (Op (ExpMem.Alloc size space)) = Just (size, space) lookForAllocSize _ = Nothing instance AllocSizeUtils InKernel where -- There can be no allocations inside kernels. lookForAllocSize _ = Nothing
ihc/futhark
src/Futhark/Optimise/MemoryBlockMerging/Reuse/AllocationSizes.hs
isc
4,478
0
14
1,054
1,192
615
577
104
3
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -F -pgmF htfpp #-} module Mock.Connection ( FakeConnection, newFakeConnection, prepareMsgToRead, getSentMsg, FakeConnections, sendBuffer, recvBuffer, resetSendBuffer ) where import App.ConnectionMgnt import ClassyPrelude import Control.Monad.Extra (whenJust) import Network.Protocol import Test.Framework data FakeConnection = FakeConnection { sendBuffer :: TVar (Maybe MessageForClient) , recvBuffer :: TVar (Maybe MessageForServer) } type FakeConnections = ClientConnections FakeConnection newFakeConnection :: IO FakeConnection newFakeConnection = do sb <- newTVarIO Nothing rb <- newTVarIO Nothing return $ FakeConnection sb rb prepareMsgToRead :: FakeConnection -> MessageForServer -> IO () prepareMsgToRead conn = atomically . writeTVar (recvBuffer conn) . Just getSentMsg :: FakeConnection -> IO (Maybe MessageForClient) getSentMsg = readTVarIO . sendBuffer resetSendBuffer :: FakeConnection -> IO () resetSendBuffer FakeConnection{sendBuffer} = atomically $ writeTVar sendBuffer Nothing instance IsConnection FakeConnection where type Pending FakeConnection = Maybe MessageForServer sendMsg conn = atomically . writeTVar (sendBuffer conn) . Just recvMsg (FakeConnection _ rb) = atomically $ swapTVar rb Nothing acceptRequest msgForServer = do conn <- newFakeConnection whenJust msgForServer (prepareMsgToRead conn) return conn
Haskell-Praxis/core-catcher
test/Mock/Connection.hs
mit
1,689
0
11
381
371
192
179
46
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} module Xml.GroupSpec (spec) where import Lastfm import Lastfm.Group import Test.Hspec import Text.Xml.Lens import SpecHelper spec :: Spec spec = do it "getHype" $ publicly (getHype <*> groupname) `shouldHaveXml` root.node "weeklyartistchart".node "artist".node "mbid".text it "getMembers" $ publicly (getMembers <*> groupname <* limit 10) `shouldHaveXml` root.node "members".node "user".node "name".text it "getWeeklyAlbumChart" $ publicly (getWeeklyAlbumChart <*> groupname) `shouldHaveXml` root.node "weeklyalbumchart".node "album".node "playcount".text it "getWeeklyArtistChart" $ publicly (getWeeklyArtistChart <*> groupname) `shouldHaveXml` root.node "weeklyartistchart".node "artist".node "name".text it "getWeeklyChartList" $ publicly (getWeeklyChartList <*> groupname) `shouldHaveXml` root.node "weeklychartlist".node "chart".attr "from" it "getWeeklyTrackChart" $ publicly (getWeeklyTrackChart <*> groupname) `shouldHaveXml` root.node "weeklytrackchart".node "track".node "url".text groupname :: Request f Group groupname = group "People with no social lives that listen to more music than is healthy who are slightly scared of spiders and can never seem to find a pen"
supki/liblastfm
test/api/Xml/GroupSpec.hs
mit
1,331
0
12
228
314
160
154
-1
-1
{-# LANGUAGE FlexibleInstances #-} module Import ( module Import ) where import Foundation as Import import Import.NoFoundation as Import import Import.Utils as Import import Import.File as Import import Control.Arrow as Import (first, second, (&&&), (***)) import Database.Persist.Sql as Import (toSqlKey, fromSqlKey) import Control.Applicative (liftA2, (<|>)) import Data.String import Data.Char (toLower, isPrint) import Data.Digest.OpenSSL.MD5 (md5sum) import Data.Geolocation.GeoIP import Data.Text.Encoding (decodeUtf8, encodeUtf8) import Data.Time (addUTCTime, secondsToDiffTime) import Data.Time.Format (formatTime) import Network.Wai import System.FilePath ((</>)) import Data.Time.Format (defaultTimeLocale) import System.Random (randomIO, randomRIO) import Text.HTML.TagSoup (parseTagsOptions, parseOptionsFast, Tag(TagText)) import qualified Data.ByteString.UTF8 as B import qualified Data.Map.Strict as MapS import qualified Data.Text as T (concat, toLower, append, take) ------------------------------------------------------------------------------------------------------------------- -- | If ajax request, redirects to page that makes JSON from message and status string. -- If regular request, redirects to given URL. trickyRedirect :: (MonadHandler m, RenderMessage (HandlerSite m) msg, RedirectUrl (HandlerSite m) url, RedirectUrl (HandlerSite m) (Route App)) => Text -> Either msg Text -> url -> m b trickyRedirect status msg url = do let th t = preEscapedToHtml t th :: Text -> Html either setMessageI (setMessage . th) msg t <- isAjaxRequest if t then redirect (JsonFromMsgR status) else redirect url ------------------------------------------------------------------------------------------------------------------- showWordfilterAction :: WordfilterAction -> AppMessage showWordfilterAction a = let m' = lookup a xs in case m' of Just m -> m Nothing -> error "case-of failed at showWordfilterAction" where xs = [(WordfilterBan , MsgWordfilterBan ) ,(WordfilterHB , MsgWordfilterHB ) ,(WordfilterHBHide, MsgWordfilterHBHide ) ,(WordfilterDeny , MsgWordfilterDeny ) ,(WordfilterReplace, MsgWordfilterReplace ) ] showWordfilterType :: WordfilterDataType -> AppMessage showWordfilterType t = let m' = lookup t xs in case m' of Just m -> m Nothing -> error "case-of failed at showWordfilterType" where xs = [(WordfilterWords , MsgWordfilterWords) ,(WordfilterExactMatch, MsgWordfilterExactMatch) ,(WordfilterRegex , MsgWordfilterRegex) ] showPermission :: Permission -> AppMessage showPermission p = let m' = lookup p xs in case m' of Just m -> m Nothing -> error "case-of failed at showPermission" where xs = [(ManageThreadP , MsgManageThread ) ,(ManageBoardP , MsgManageBoard ) ,(ManageUsersP , MsgManageUsers ) ,(ManageConfigP , MsgManageConfig ) ,(DeletePostsP , MsgDeletePosts ) ,(ManagePanelP , MsgManagePanel ) ,(ManageBanP , MsgManageBan ) ,(EditPostsP , MsgEditPosts ) ,(ShadowEditP , MsgShadowEdit ) ,(AdditionalMarkupP, MsgAdditionalMarkup) ,(ViewModlogP , MsgViewModlog ) ,(ViewIPAndIDP , MsgViewIPAndID ) ,(HellBanP , MsgHellbanning ) ,(ChangeFileRatingP, MsgChangeFileRating) ,(AppControlP , MsgAppControl) ,(WordfilterP , MsgWordfilter) ,(ReportsP , MsgReports) ] data GroupConfigurationForm = GroupConfigurationForm Text -- ^ Group name Bool -- ^ Permission to manage threads Bool -- ^ ... boards Bool -- ^ ... users Bool -- ^ ... config Bool -- ^ to delete posts Bool -- ^ to view admin panel Bool -- ^ to manage bans Bool -- ^ to edit any post Bool -- ^ Permission to edit any post without saving history Bool -- ^ to use additional markup Bool -- ^ to view moderation log Bool -- ^ to view ip and uid Bool -- ^ to use hellbanning Bool -- ^ to change censorship rating Bool -- ^ to control application Bool -- ^ to configure wordfilter Bool -- ^ to use reports data BoardConfigurationForm = BoardConfigurationForm (Maybe Text) -- ^ Name (Maybe Text) -- ^ Board title (Maybe Int) -- ^ Bump limit (Maybe Int) -- ^ Number of files (Maybe Text) -- ^ Allowed file types (Maybe Text) -- ^ Default name (Maybe Int ) -- ^ The maximum message length (Maybe Int ) -- ^ Thumbnail size (Maybe Int ) -- ^ Threads per page (Maybe Int ) -- ^ Previews post per thread (Maybe Int ) -- ^ Thread limit (Maybe Text) -- ^ OP file (Maybe Text) -- ^ Reply file (Maybe Text) -- ^ Is hidden (Enable,Disable,DoNotChange) (Maybe Text) -- ^ Enable captcha (Enable,Disable,DoNotChange) (Maybe Text) -- ^ Category (Maybe [Text]) -- ^ View access (Maybe [Text]) -- ^ Reply access (Maybe [Text]) -- ^ Thread access (Maybe Text ) -- ^ Allow OP moderate his/her thread (Maybe Textarea) -- ^ Extra rules (Maybe Text ) -- ^ Enable geo IP (Maybe Text ) -- ^ Enable OP editing (Maybe Text ) -- ^ Enable post editing (Maybe Text ) -- ^ Show or not editing history (Maybe Text ) -- ^ Show or not post date (Maybe Text ) -- ^ Summary (Maybe Text ) -- ^ Enable forced anonymity (no name input) (Maybe Text ) -- ^ Required thread title (Maybe Int ) -- ^ Index (Maybe Text ) -- ^ Enable private messages (Maybe Text ) -- ^ Onion access only ------------------------------------------------------------------------------------------------------------------- -- Search ------------------------------------------------------------------------------------------------------------------- data SearchResult = SearchResult { searchResultPostId :: PostId , searchResultPost :: Post , searchResultExcerpt :: Html } searchForm :: Maybe Text -> Html -> MForm Handler (FormResult (Text, Maybe Text), Widget) searchForm board = renderDivs $ (,) <$> areq (searchField False) "" Nothing <*> aopt hiddenField "" (Just board) ------------------------------------------------------------------------------------------------------------------- -- Handful functions ------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------- -- Files ------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------- -- Handler helpers ------------------------------------------------------------------------------------------------------------------- incPostCount :: Handler () incPostCount = do pc <- lookupSession "post-count" case pc of Just n -> setSession "post-count" $ tshow $ plus 1 $ tread n Nothing -> setSession "post-count" "1" where plus :: Integer -> Integer -> Integer plus = (+) listPages :: Int -> Int -> [Int] listPages elemsPerPage numberOfElems = [0..pagesFix $ floor $ (fromIntegral numberOfElems :: Double) / (fromIntegral elemsPerPage :: Double)] where pagesFix x | numberOfElems > 0 && numberOfElems `mod` elemsPerPage == 0 = x - 1 | otherwise = x getIgnoredBoard :: Maybe Text -> Entity Board -> Maybe Text getIgnoredBoard group board@(Entity _ b) = if isBoardHidden group board then Just $ boardName b else Nothing getIgnoredBoard' :: Maybe Text -> Entity Board -> Maybe Text getIgnoredBoard' group board@(Entity _ b) = if isBoardHidden' group board then Just $ boardName b else Nothing isBoardHidden :: Maybe Text -> Entity Board -> Bool isBoardHidden group x@(Entity _ b) = boardHidden b || isBoardHidden' group x isBoardHidden' :: Maybe Text -> Entity Board -> Bool isBoardHidden' group (Entity _ b) = (isJust (boardViewAccess b) && isNothing group) || (isJust (boardViewAccess b) && notElem (fromJust group) (fromJust $ boardViewAccess b)) -- | Remove all HTML tags stripTags :: Text -> Text stripTags = foldr (T.append . textOnly) "" . parseTagsOptions parseOptionsFast where textOnly (TagText t) = t textOnly _ = "" -- | Check if request has X-Requested-With header isAjaxRequest :: forall (m :: * -> *). MonadHandler m => m Bool isAjaxRequest = do maybeHeader <- lookup "X-Requested-With" . requestHeaders <$> waiRequest return $ maybe False (=="XMLHttpRequest") maybeHeader ------------------------------------------------------------------------------------------------------------------- -- Template helpers ------------------------------------------------------------------------------------------------------------------- inc :: Int -> Int inc = (+1) makeFileInfo :: Attachedfile -> String makeFileInfo file = extractFileExt (attachedfileName file) ++", "++ attachedfileSize file ++i where i = if length (attachedfileInfo file) > 0 then ", "++ attachedfileInfo file else "" checkAbbr :: Int -> -- ^ Message length Bool -> -- ^ Show full message Bool checkAbbr len t = len > postAbbrLength && not t -- | The maximum length of an abbreviated message postAbbrLength :: Int postAbbrLength = 1500 enumerate :: forall b. [b] -> [(Int, b)] enumerate = zip [0..] ifelse :: Bool -> Text -> Text -> Text ifelse x y z = if x then y else z ifelseall :: forall a. Bool -> a -> a -> a ifelseall x y z = if x then y else z myFormatTime :: Int -> -- ^ Time offset in seconds UTCTime -> -- ^ UTCTime String myFormatTime offset t = formatTime defaultTimeLocale "%d %B %Y (%a) %H:%M:%S" $ addUTCTime' offset t -- | Truncate file name if it's length greater than specified truncateFileName :: Int -> String -> String truncateFileName maxLen s = if len > maxLen then result else s where len = length s excess = len - maxLen halfLen = round $ fromIntegral len / (2 :: Double) halfExc = round $ fromIntegral excess / (2 :: Double) splitted = splitAt halfLen s left = reverse $ drop (halfExc + 2) $ reverse $ fst splitted right = drop (halfExc + 2) $ snd splitted result = left ++ "[..]" ++ right defaultTitleMsg title = do AppSettings{..} <- appSettings <$> getYesod msgrender <- getMessageRender setTitle $ toHtml $ T.concat [appSiteName, appTitleDelimiter, msgrender title] defaultTitle title = do AppSettings{..} <- appSettings <$> getYesod setTitle $ toHtml $ T.concat [appSiteName, appTitleDelimiter, title] defaultTitleReverse title = do AppSettings{..} <- appSettings <$> getYesod setTitle $ toHtml $ T.concat $ reverse [appSiteName, appTitleDelimiter, title] ------------------------------------------------------------------------------------------------------------------- -- Widgets ------------------------------------------------------------------------------------------------------------------- catalogPostWidget :: Entity Post -> [Entity Attachedfile] -> Int -> Widget catalogPostWidget ePost files replies = do let post = entityVal ePost mFile = if length files > 0 then Just (head files) else Nothing msgLength = 35 rating <- handlerToWidget getCensorshipRating AppSettings{..} <- handlerToWidget $ appSettings <$> getYesod $(widgetFile "catalog-post") postWidget :: Entity Post -> [Entity Attachedfile] -> Bool -> -- ^ Are we in a thread Bool -> -- ^ Have access to post Bool -> -- ^ Show parent board/thread in the upper right corner Bool -> -- ^ If geo ip enabled Bool -> -- ^ Show post date [Permission] -> -- ^ List of the all permissions Int -> -- ^ Index number Bool -> -- ^ Enable PM Widget postWidget ePost eFiles inThread canPost showParent geoIp showPostDate permissions number enablePM = let postVal = entityVal ePost sPostLocalId = show $ postLocalId $ entityVal ePost postLocalId' = postLocalId $ entityVal ePost sPostId = show $ fromSqlKey $ entityKey ePost postId = fromSqlKey $ entityKey ePost sThreadLocalId = show $ postParent $ entityVal ePost threadLocalId = postParent $ entityVal ePost board = postBoard $ entityVal ePost isThread = sThreadLocalId == "0" pClass' = (if isThread then "op" else "reply") <> (if elem HellBanP permissions && postHellbanned postVal then " hellbanned" else "") :: Text itsforMe uid = maybe True (==uid) (postDestUID $ entityVal ePost) || uid == (postPosterId $ entityVal ePost) destUID = postDestUID $ entityVal ePost in do timeZone <- handlerToWidget getTimeZone rating <- handlerToWidget getCensorshipRating posterId <- handlerToWidget getPosterId AppSettings{..} <- handlerToWidget $ appSettings <$> getYesod inBookmarks <- handlerToWidget $ do bm <- getBookmarks return $ isJust $ lookup (fromIntegral postId) bm req <- handlerToWidget $ waiRequest app <- handlerToWidget $ getYesod let pClass = pClass' <> if posterId == postPosterId postVal then " my" else "" let approot' = case appRoot of Nothing -> getApprootText guessApproot app req Just root -> root $(widgetFile "post") paginationWidget page pages route = $(widgetFile "pagination") deleteWidget :: [Permission] -> Widget deleteWidget permissions = $(widgetFile "delete") adminNavbarWidget :: Widget adminNavbarWidget = do permissions <- handlerToWidget $ ((fmap getPermissions) . getMaybeGroup) =<< maybeAuth reports <- handlerToWidget $ runDB $ count ([]::[Filter Report]) $(widgetFile "admin/navbar") ------------------------------------------------------------------------------------------------------------------- bareLayout :: Yesod site => WidgetT site IO () -> HandlerT site IO Html bareLayout widget = do pc <- widgetToPageContent widget withUrlRenderer [hamlet| ^{pageBody pc} |] ------------------------------------------------------------------------------------------------------------------- -- Access checkers ------------------------------------------------------------------------------------------------------------------- checkHellbanned :: Post -> [Permission] -> Text -> Bool checkHellbanned post permissions posterId = not (postHellbanned post) || elem HellBanP permissions || (postPosterId post) == posterId checkAccessToReply :: Maybe (Entity Group) -> Board -> Bool checkAccessToReply mgroup boardVal = let group = (groupName . entityVal) <$> mgroup access = boardReplyAccess boardVal in isNothing access || (isJust group && elem (fromJust group) (fromJust access)) checkAccessToNewThread :: Maybe (Entity Group) -> Board -> Bool checkAccessToNewThread mgroup boardVal = let group = (groupName . entityVal) <$> mgroup access = boardThreadAccess boardVal in isNothing access || (isJust group && elem (fromJust group) (fromJust access)) checkViewAccess' :: forall (m :: * -> *). MonadHandler m => Maybe (Entity Group) -> Board -> m Bool checkViewAccess' mgroup boardVal = do let group = (groupName . entityVal) <$> mgroup access = boardViewAccess boardVal ip <- pack <$> getIp return $ not ( (isJust access && isNothing group) || (isJust access && notElem (fromJust group) (fromJust access)) || (boardOnion boardVal && not (isOnion ip)) ) checkViewAccess :: forall (m :: * -> *). MonadHandler m => Maybe (Entity Group) -> Board -> m () checkViewAccess mgroup boardVal = do let group = (groupName . entityVal) <$> mgroup access = boardViewAccess boardVal ip <- pack <$> getIp when ( (isJust access && isNothing group) || (isJust access && notElem (fromJust group) (fromJust access)) || (boardOnion boardVal && not (isOnion ip)) ) notFound isOnion :: forall a. (Eq a, Data.String.IsString a) => a -> Bool isOnion = (=="172.19.0.4") getPermissions :: Maybe (Entity Group) -> [Permission] getPermissions = maybe [] (groupPermissions . entityVal) ------------------------------------------------------------------------------------------------------------------- -- Some getters ------------------------------------------------------------------------------------------------------------------- getMaybeGroup :: Maybe (Entity User) -> Handler (Maybe (Entity Group)) getMaybeGroup muser = case muser of Just (Entity _ u) -> runDB $ getBy $ GroupUniqName $ userGroup u _ -> return Nothing getBoardVal404 :: Text -> Handler Board getBoardVal404 board = runDB (getBy $ BoardUniqName board) >>= maybe notFound (return . entityVal) getTimeZone :: Handler Int getTimeZone = do defaultZone <- appTimezone . appSettings <$> getYesod timezone <- lookupSession "timezone" return $ maybe defaultZone tread timezone getCensorshipRating :: Handler Censorship getCensorshipRating = do mRating <- lookupSession "censorship-rating" case mRating of Just rating -> return $ tread rating Nothing -> setSession "censorship-rating" "SFW" >> return SFW getPosterId :: Handler Text getPosterId = do maybePosterId <- lookupSession "posterId" case maybePosterId of Just posterId -> return posterId Nothing -> do posterId <- liftIO $ pack . md5sum . B.fromString <$> liftA2 (++) (show <$> (randomIO :: IO Int)) (show <$> getCurrentTime) setSession "posterId" posterId return posterId getConfig :: forall b. (Config -> b) -> Handler b getConfig f = f . entityVal . fromJust <$> runDB (selectFirst ([]::[Filter Config]) []) getConfigEntity :: Handler Config getConfigEntity = entityVal . fromJust <$> runDB (selectFirst ([]::[Filter Config]) []) getFeedBoards :: Handler [Text] getFeedBoards = do bs <- lookupSession "feed-ignore-boards" case bs of Just xs -> return $ tread xs Nothing -> setSession "feed-ignore-boards" "[]" >> return [] getHiddenThreads :: Text -> Handler [(Int,Int)] getHiddenThreads board = do ht <- lookupSession "hidden-threads" case ht of Just xs -> return $ fromMaybe [] $ lookup board (read (unpack xs) :: [(Text, [(Int,Int)])]) Nothing -> setSession "hidden-threads" "[]" >> return [] getAllHiddenThreads :: Handler [(Text, [(Int,Int)])] getAllHiddenThreads = do ht <- lookupSession "hidden-threads" case ht of Just xs -> return $ read $ unpack xs Nothing -> setSession "hidden-threads" "[]" >> return [] getBookmarks :: Handler [(Int, Int)] getBookmarks = do bm <- lookupSession "bookmarks" case bm of Just xs -> return $ read $ unpack xs Nothing -> setSession "bookmarks" "[]" >> return [] getAllHiddenPostsIds :: [Text] -> Handler [Key Post] getAllHiddenPostsIds boards = do threadsIds <- concat <$> forM boards (\b -> map (toSqlKey . fromIntegral . snd) <$> getHiddenThreads b) threads <- runDB $ selectList [PostId <-. threadsIds] [] replies <- runDB $ forM threads $ \(Entity _ t) -> selectList [PostBoard ==. postBoard t, PostParent ==. postLocalId t] [] return $ map f threads ++ map f (concat replies) where f (Entity k _) = k ------------------------------------------------------------------------------------------------------------------- -- IP getter ------------------------------------------------------------------------------------------------------------------- -- | Gets IP from X-Real-IP/CF-Connecting-I or remote-host header getIp = do realIp <- fmap B.toString <$> getIpReal cfIp <- fmap B.toString <$> getIpCF hostIp <- getIpFromHost let resultIp = fromJust (cfIp <|> realIp <|> Just hostIp) return resultIp where getIpReal = lookup "X-Real-IP" . requestHeaders <$> waiRequest getIpCF = lookup "CF-Connecting-IP" . requestHeaders <$> waiRequest getIpFromHost = takeWhile (not . (`elem` (":"::String))) . show . remoteHost . reqWaiRequest <$> getRequest ------------------------------------------------------------------------------------------------------------------- -- Geo IP ------------------------------------------------------------------------------------------------------------------- getCountry :: Text -> -- ^ IP adress Handler (Maybe (Text,Text)) -- ^ (country code, country name) getCountry ip = do dbPath <- unpack . appGeoIPCityPath . appSettings <$> getYesod geoIpRes <- liftIO $ openGeoDB memory_cache dbPath >>= flip geoLocateByIPAddress (encodeUtf8 ip) return $ ((decodeUtf8 . geoCountryCode) &&& (decodeUtf8 . geoCountryName)) <$> geoIpRes ------------------------------------------------------------------------------------------------------------------- -- Board stats ------------------------------------------------------------------------------------------------------------------- getBoardStats :: Handler [(Text,Int,Int)] getBoardStats = do mgroup <- (fmap $ userGroup . entityVal) <$> maybeAuth maybeStats <- lookupSession "board-stats" case maybeStats of Just s -> return $ tread s Nothing -> do posterId <- getPosterId boards <- map (boardName . entityVal) . filter (not . isBoardHidden mgroup) <$> runDB (selectList ([]::[Filter Board]) []) hiddenThreads <- getAllHiddenThreads stats <- runDB $ forM boards $ \b -> do lastPost <- selectFirst [PostBoard ==. b, PostDeleted ==. False, PostPosterId !=. posterId, PostHellbanned ==. False ,PostParent /<-. concatMap (map fst . snd) (filter ((==b).fst) hiddenThreads)] [Desc PostLocalId] return (b, maybe 0 (postLocalId . entityVal) lastPost, 0) saveBoardStats stats return stats saveBoardStats :: [(Text,Int,Int)] -> Handler () saveBoardStats stats = do deleteSession "board-stats" setSession "board-stats" $ tshow stats cleanAllBoardsStats :: Handler () cleanAllBoardsStats = do mgroup <- (fmap $ userGroup . entityVal) <$> maybeAuth boards <- map (boardName . entityVal) . filter (not . isBoardHidden mgroup) <$> runDB (selectList ([]::[Filter Board]) []) forM_ boards cleanBoardStats cleanBoardStats :: Text -> Handler () cleanBoardStats board = do hiddenThreads <- getAllHiddenThreads oldStats <- getBoardStats newStats <- forM oldStats $ \s@(b,_,_) -> if b == board then do lastPost <- runDB $ selectFirst [PostBoard ==. b, PostDeleted ==. False, PostHellbanned ==. False ,PostParent /<-. concatMap (map fst . snd) (filter ((==b).fst) hiddenThreads)] [Desc PostLocalId] return (b, maybe 0 (postLocalId . entityVal) lastPost, 0) else return s saveBoardStats newStats ------------------------------------------------------------------------------------------------------------------- -- JSON instances ------------------------------------------------------------------------------------------------------------------- data PostAndFiles = PostAndFiles (Entity Post, [Entity Attachedfile]) type OpPostAndFiles = PostAndFiles data ThreadsAndPreviews = ThreadsAndPreviews [( OpPostAndFiles , [PostAndFiles] , Int )] appUploadDir' :: String appUploadDir' = "upload" appStaticDir' :: String appStaticDir' = "static" instance ToJSON Attachedfile where toJSON Attachedfile {..} = object [ "hashsum" .= attachedfileHashsum , "name" .= attachedfileName , "extension" .= attachedfileExtension , "thumbSize" .= attachedfileThumbSize , "thumbWidth" .= attachedfileThumbWidth , "thumbHeight" .= attachedfileThumbHeight , "size" .= attachedfileSize , "info" .= attachedfileInfo , "path" .= attachedfilePath , "rating" .= attachedfileRating , "thumb_path" .= thumbUrlPath appUploadDir' appStaticDir' attachedfileThumbSize attachedfileFiletype attachedfileExtension attachedfileHashsum attachedfileOnion ] instance ToJSON Post where toJSON Post {..} = object [ "board" .= postBoard , "id" .= postLocalId , "parent" .= postParent , "date" .= postDate , "bumped" .= postBumped , "sticked" .= postSticked , "locked" .= postLocked , "autosage" .= postAutosage , "message" .= postMessage , "rawMessage" .= postRawMessage , "title" .= postTitle , "name" .= postName , "deletedByOp" .= postDeletedByOp ] instance ToJSON (Entity Attachedfile) where toJSON (Entity k v) = toJSON v instance ToJSON (Entity Post) where toJSON (Entity k v) = toJSON v instance ToJSON PostAndFiles where toJSON (PostAndFiles (post, files)) = object [ "post" .= post, "files" .= files ] instance ToJSON ThreadsAndPreviews where toJSON (ThreadsAndPreviews threads) = array $ map (\(op, replies, omitted) -> object [ "op" .= op , "replies" .= replies , "omitted" .= omitted ]) threads
ahushh/Monaba
monaba/src/Import.hs
mit
28,251
0
26
8,215
6,600
3,448
3,152
-1
-1
module Grains where square :: Integer -> Integer square 1 = 1 square i = 2 * square (i-1) total :: Integer total = sum $ map square [1..64]
tonyfischetti/exercism
haskell/grains/Grains.hs
mit
143
0
8
32
67
36
31
6
1
module Compiler where import Codec.Compression.GZip (bestCompression, compressLevel, compressWith, decompress, defaultCompressParams) import Data.Aeson (eitherDecode) import Data.Aeson.Encode.Pretty (encodePretty) import Data.Binary (decodeOrFail, encode, encodeFile) import Data.ByteString.Lazy.Char8 (unpack) import qualified Data.ByteString.Lazy.Char8 as BS import Data.List (find, isPrefixOf, stripPrefix) import System.Directory (getCurrentDirectory, getHomeDirectory) import System.FilePath (normalise, takeDirectory, (</>)) import qualified Parser as P import Types import Utils compileRef :: [Card] -> Maybe CardNameReference -> Sparker [Deployment] compileRef cs mcnr = do firstCard <- case mcnr of Nothing -> if null cs then throwError $ CompileError "No cards found for compilation." else return $ head cs Just (CardNameReference name) -> do case find (\c -> card_name c == name) cs of Nothing -> throwError $ CompileError $ unwords ["Card", name, "not found for compilation."] Just card -> return card compile firstCard cs compile :: Card -> [Card] -> Sparker [Deployment] compile card allCards = do initial <- initialState card allCards ((_,_),dps) <- runSparkCompiler initial compileDeployments return dps outputCompiled :: [Deployment] -> Sparker () outputCompiled deps = do form <- asks conf_compile_format out <- asks conf_compile_output case form of FormatBinary -> do case out of Nothing -> liftIO $ BS.putStrLn $ compressWith compressionParams $ encode deps Just fp -> liftIO $ BS.writeFile fp $ compressWith compressionParams $ encode deps FormatText -> do let str = unlines $ map show deps case out of Nothing -> liftIO $ putStrLn str Just fp -> liftIO $ writeFile fp str FormatJson -> do let bs = encodePretty deps case out of Nothing -> liftIO $ BS.putStrLn bs Just fp -> liftIO $ BS.writeFile fp bs FormatStandalone -> notImplementedYet where compressionParams = defaultCompressParams {compressLevel = bestCompression} inputCompiled :: FilePath -> Sparker [Deployment] inputCompiled fp = do form <- asks conf_compile_format case form of FormatBinary -> do content <- liftIO $ BS.readFile fp case decodeOrFail $ decompress content of Left (_,_,err) -> throwError $ CompileError $ "Something went wrong while deserialising binary data: " ++ err Right (_,_,deps) -> return deps FormatText -> do str <- liftIO $ readFile fp return $ map read $ lines str FormatJson -> do bs <- liftIO $ BS.readFile fp case eitherDecode bs of Left err -> throwError $ CompileError $ "Something went wrong while deserialising json data: " ++ err Right ds -> return ds FormatStandalone -> throwError $ CompileError "You're not supposed to use standalone compiled deployments in any other way than by executing it." initialState :: Card -> [Card] -> Sparker CompilerState initialState c@(Card _ fp (Block ds)) cds = do currentDir <- liftIO getCurrentDirectory override <- asks conf_compile_kind return $ CompilerState { state_current_card = c , state_current_directory = currentDir </> takeDirectory fp , state_all_cards = cds , state_declarations_left = ds , state_deployment_kind_override = override , state_into = "" , state_outof_prefix = [] } -- Compiler pop :: SparkCompiler Declaration pop = do dec <- gets state_declarations_left modify (\s -> s {state_declarations_left = tail dec}) return $ head dec done :: SparkCompiler Bool done = fmap null $ gets state_declarations_left compileDeployments :: SparkCompiler () compileDeployments = do d <- done if d then return () else processDeclaration >> compileDeployments add :: Deployment -> SparkCompiler () add dep = tell [dep] addAll :: [Deployment] -> SparkCompiler () addAll = tell resolvePrefix :: CompilerPrefix -> [FilePath] resolvePrefix [] = [] resolvePrefix [Literal s] = [s] resolvePrefix [Alts ds] = ds resolvePrefix ((Literal s):ps) = do rest <- resolvePrefix ps return $ s </> rest resolvePrefix ((Alts as):ps) = do a <- as rest <- resolvePrefix ps return $ a </> rest sources :: FilePath -> PrefixPart sources fp@('.':f) = Alts [fp, f] sources fp = Literal fp stripHome :: FilePath -> SparkCompiler FilePath stripHome fp = do home <- liftIO $ getHomeDirectory return $ case home `stripPrefix` fp of Nothing -> fp Just stripped -> "~" ++ stripped processDeclaration :: SparkCompiler () processDeclaration = do dec <- pop case dec of Deploy src dst kind -> do override <- gets state_deployment_kind_override superOverride <- asks conf_compile_override let resultKind = case (superOverride, override, kind) of (Nothing, Nothing, Nothing) -> LinkDeployment (Nothing, Nothing, Just k ) -> k (Nothing, Just o , _ ) -> o (Just o , _ , _ ) -> o dir <- gets state_current_directory outof <- gets state_outof_prefix into <- gets state_into let alts = map normalise . resolvePrefix $ [Literal dir] ++ outof ++ [sources src] let dest = normalise $ into </> dst alternates <- mapM stripHome alts destination <- stripHome dest add $ Put alternates destination resultKind SparkOff st -> do case st of CardRepo _ -> lift $ lift notImplementedYet CardFile (CardFileReference file mn) -> do dir <- gets state_current_directory newCards <- liftSparker $ P.parseFile $ dir </> file oldCards <- gets state_all_cards let allCards = oldCards ++ newCards nextCard <- case mn of Nothing -> return $ head newCards Just (CardNameReference name) -> case find (\c -> card_name c == name) allCards of Nothing -> throwError $ CompileError "card not found" -- FIXME this is unsafe. Just c -> return c newDeclarations <- liftSparker $ compile nextCard newCards modify (\s -> s {state_all_cards = allCards}) addAll newDeclarations CardName (CardNameReference name) -> do allCards <- gets state_all_cards case find (\c -> card_name c == name) allCards of Nothing -> throwError $ CompileError "card not found" -- FIXME this is unsafe. Just c@(Card _ _ (Block dcs)) -> do before <- get modify (\s -> s {state_declarations_left = dcs ,state_current_card = c}) compileDeployments put before IntoDir dir -> do ip <- gets state_into if null ip then modify (\s -> s {state_into = dir} ) else modify (\s -> s {state_into = ip </> dir} ) OutofDir dir -> do op <- gets state_outof_prefix modify (\s -> s {state_outof_prefix = op ++ [Literal dir]}) DeployKindOverride kind -> modify (\s -> s {state_deployment_kind_override = Just kind }) Block ds -> do before <- get modify (\s -> s {state_declarations_left = ds}) compileDeployments put before Alternatives ds -> do op <- gets state_outof_prefix modify (\s -> s {state_outof_prefix = op ++ [Alts ds]}) liftSparker :: Sparker a -> SparkCompiler a liftSparker = lift . lift
plietar/super-user-spark
src/Compiler.hs
mit
8,701
0
26
3,157
2,384
1,184
1,200
186
16
module Model.Object (module Model.Movement ,Object(..) ,Color(..) ,moveObject ,objectHas ,objectCollidingWith ,mergeObjectWith ,increaseObject ) where import Model.Movement {- Naming convention for this module. * Record field names. Each name is prefixed by abbreviation of record: data Record = Record { rcdField :: Int } where rcd ~ record * Record function names. ** Compute value functions. Each name is prefixed by record's name in lower case: data Record = Record { rcdA :: Int, rcdB :: Int } recordSum :: Record -> Int recordSum (Record a b) = a + b ** Update record functions. Each name is combined from verd which prefixes a record name: data Record = Record { rcdA :: Int, rcdB :: Int } scaleRecord :: Int -> Record -> Record scaleRecord n (Record a b) = Record (n * a) (n * b) -} {- Abbreviations. * obj ~ object * ccl ~ circle * rct ~ rectangle * ctr ~ center * dst ~ distance -} {- Object data type. Object is movable item which has a radius and color. -} data Object a = Object { objCtr :: Pnt a , objVel :: Vel a , objAcc :: Acc a , objRadius :: a , objColor :: Color } {- Show instance for Object. Show instance isn't derived because it would make Object unable to read when printed. Most of the time, Object will be in a container. So it is better to make Show instance to look good in container. -} prettyShow :: Show a => Object a -> String prettyShow (Object p v a s c) = "\n" ++ "Object {" ++ "\n center: " ++ (show p) ++ "\n velocity: " ++ (show v) ++ "\n acceleration: " ++ (show a) ++ "\n radius: " ++ (show s) ++ "\n color: " ++ (show c) ++ "\n}\n" instance Show a => Show (Object a) where show = indent . prettyShow where indent = unlines. map (spc++) . lines where spc = " " {- Note about naming enumerations. Enumerated types like data EnumType = Val1 | Val2 | ... | ValN could be defined like data EnumType = EnumTypeVal1 | EnumTypeVal2 | ... | EnumTypeValN It makes names a little bit ugly, but more readable. I don't think here will be a problem with readability. So, names stay nice. -} -- Type of color. data Color = Red | Orange | Yellow | Green | Azure | Blue | Purple deriving (Bounded, Enum, Show) {- Object's interface -} -- Returns new state of object after some period of time. moveObject :: Floating a => a -> Object a -> Object a moveObject dt (Object p v a r c) = -- Update point using velocity; -- update velocity using acceleration; -- update accelration using some hidden formula: let p' = pntDrv dt v v' = velDrv dt a a' = updateAcc in Object p' v' a' r c where -- Acceleration changing formula. updateAcc = -- Acceleration changes depending from radius: let accInc = acc 0 $ r / 4 in a ^+^ accInc -- Checks whether object has supplied point. objectHas :: (Floating a, Ord a) => Pnt a -> Object a -> Bool objectHas p obj = pntDst p (objCtr obj) < objRadius obj {- Checks whether two objects are colliding. Two objects are collading if distance between their centers is less then the minimal distance from center of one of them to it's boarders. NOTE: This criteria holds for circles. For other figures it might fail. -} objectCollidingWith :: (Floating a, Ord a) => Object a -> Object a -> Bool objectCollidingWith objA objB = let -- Distance between centers. ctrDst = objCtr objA `pntDst` objCtr objB -- Minimal distance from center of A to it's boarder. minDstA = objRadius objA -- Minimal distance from center of B to it's boarder. minDstB = objRadius objB in ctrDst < minDstA || ctrDst < minDstB -- Merges two objects into one. mergeObjectWith :: (Floating a, Ord a) => Object a -> Object a -> Object a mergeObjectWith (Object pA vA aA rA cA) (Object pB vB aB rB cB) = let -- New point is a middle between two. p' = pntMid pA pB -- New velocity is a half of sum of two. v' = (vA ^+^ vB) ^/ 2 -- New acceleration is a quoter of sum of two. a' = (aA ^+^ aB) ^/ 4 -- New radius is a result of half of sum of two. r' = (rA + rB) / 2 -- New color is those whose object's square is bigger. sA = pi * rA^2 sB = pi * rB^2 c' = if sA > sB then cA else cB in Object p' v' a' r' c' -- Increases object's radius. increaseObject :: Fractional a => Object a -> Object a increaseObject (Object p v a r c) = Object p v a (r + inc) c where -- formula of radius increment: inc = r / 6 {- Abstract interface of object. NOTE: this is scratch. Should it wide enough to allow adding a new objects into existing world? -} class Object' t where -- Returns object's state after supplied time value. move :: a -> t a -> t a {- Returns object's center. Having a two objects of different types it is still possible to find a distance between them using coordinates of their centers. -} center :: t a -> Pnt a -- Whether object has a point inside. hasPnt :: Pnt a -> t a -> Bool {- Square of object. Should it be here? -} square :: t a -> a
wowofbob/circles
src/Model/Object.hs
mit
6,291
0
16
2,471
968
514
454
74
2
{-# LANGUAGE GADTs #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveFunctor #-} module Vegito where import Control.Applicative (liftA2) data Step s o r where Yield :: s -> o -> Step s o r Skip :: s -> Step s o r Done :: r -> Step s o r deriving Functor data Stream o m r where Stream :: (s -> m (Step s o r)) -> s -> Stream o m r instance Functor m => Functor (Stream o m) where fmap f (Stream step s) = Stream (fmap (fmap f) . step) s instance Applicative m => Applicative (Stream o m) where pure r = Stream (\() -> pure (Done r)) () Stream f1 s1orig <*> Stream f2 s2orig = Stream go (First s1orig s2orig) where go (First s1 s2) = fmap goStep (f1 s1) where goStep (Yield s1' o) = Yield (First s1' s2) o goStep (Skip s1') = Skip (First s1' s2) goStep (Done r) = Skip (Second r s2) go (Second r1 s2) = fmap goStep (f2 s2) where goStep (Yield s2' o) = Yield (Second r1 s2') o goStep (Skip s2') = Skip (Second r1 s2') goStep (Done r2) = Done (r1 r2) data ApplicativeHelper x y r = First x y | Second r y instance Applicative m => Monad (Stream o m) where return = pure (>>) = (*>) Stream f1 s1orig >>= right = Stream go (Left s1orig) where go (Left s1) = fmap goStep (f1 s1) where goStep (Yield s1' o) = Yield (Left s1') o goStep (Skip s1') = Skip (Left s1') goStep (Done r) = Skip (Right (right r)) go (Right (Stream f2 s2)) = fmap goStep (f2 s2) where goStep (Yield s2' o) = Yield (Right (Stream f2 s2')) o goStep (Skip s2') = Skip (Right (Stream f2 s2')) goStep (Done r) = Done r instance (Applicative m, Monoid r) => Monoid (Stream o m r) where mempty = pure mempty mappend = liftA2 mappend enumFromToS :: (Ord o, Applicative m, Num o) => o -> o -> Stream o m () enumFromToS low high = Stream go low where go x | x <= high = pure (Yield (x + 1) x) | otherwise = pure (Done ()) {-# INLINE enumFromToS #-} foldlS :: (Monad m) => (r -> i -> r) -> r -> Stream i m () -> m r foldlS g accum0 (Stream f sorig) = let loop accum s = do step <- f s case step of Done () -> pure accum Skip s' -> loop accum s' Yield s' i -> let accum' = g accum i in accum' `seq` loop accum' s' in loop accum0 sorig {-# INLINE foldlS #-} sumS :: (Num i, Monad m) => Stream i m () -> m i sumS = foldlS (+) 0 {-# INLINE sumS #-} mapS :: Functor m => (i -> o) -> Stream i m r -> Stream o m r mapS f (Stream src sorig) = let go s = fmap goStep (src s) goStep (Yield s i) = Yield s (f i) goStep (Skip s) = Skip s goStep (Done r) = Done r in Stream go sorig {-# INLINE mapS #-}
snoyberg/vegito
src/Vegito.hs
mit
3,023
1
18
1,077
1,348
666
682
78
3
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, ScopedTypeVariables #-} module Main (main) where import RAExpr.Row import RAExpr.RASet import RAExpr.Value import RAExpr.Condition import RAExpr.Expression import Parser import Class.Pretty import System.Environment import System.IO (hFlush, stdout) import Text.Parsec (parse) import qualified System.REPL as REPL import qualified System.REPL.Command as Command import Data.Text.Lazy import System.IO expressionAsker :: REPL.Asker IO REPL.Verbatim expressionAsker = REPL.typeAsker (pack "> ") (pack "ERROR!") main = do input <- REPL.ask' expressionAsker let expression = (unpack (REPL.fromVerbatim input)) run $ parseExpression expression main run (Right expression) = putStrLn (pretty result) where (Just result) = eval expression run (Left error) = putStrLn (show error)
cameronbwhite/RelationalAlgebra
src/Main.hs
mit
864
0
14
117
253
137
116
26
1
{-# language OverloadedStrings #-} module Internal where import Control.Concurrent.Async (async, wait) import Control.Exception (bracket, throwIO, try) import Control.Monad (when) import Data.Maybe (fromJust) import Data.String (IsString) import Data.ByteString (ByteString) import System.Posix.Files.ByteString (removeLink, fileExist) import Test.Tasty import Test.Tasty.HUnit import System.Socket import System.Socket.Type.Stream import System.Socket.Type.Datagram import System.Socket.Protocol.Default import System.Socket.Family.Unix groupUnixPathname :: TestTree groupUnixPathname = testGroup "Unix path name" [ testCase "connect to non-existing path name" $ bracket unixSocketStream close (\s -> do r <- try $ connect s addr case r of Left e | e == eNoEntry -> return () | otherwise -> throwIO e Right () -> assertFailure "connection should have failed" ) , testCase "server\\client stream" $ bracket ( (,) <$> unixSocketStream <*> unixSocketStream) closeSockets (testServerClientStream addr) , testCase "server\\client datagram" $ bracket ((,) <$> unixSocketDatagram <*> unixSocketDatagram) closeSockets (testServerClientDatagram addr cAddr) ] where addr = fromJust $ socketAddressUnixPath unixPath cAddr = fromJust $ socketAddressUnixPath clientUnixPath closeSockets (server, client) = do close server close client unlink unixPath unlink clientUnixPath -- Sockets with real pathname should be unlinked after closing unlink path = fileExist path >>= flip when (removeLink path) clientMessage :: ByteString clientMessage = "client message" serverMessage :: ByteString serverMessage = "server message" unixPath :: ByteString unixPath = "Woum5ag3oohuaLee.socket" clientUnixPath :: ByteString clientUnixPath = "Io4meo0epoquashi.socket" abstractPath :: ByteString abstractPath = "/tmp/uth4Aechiereejae.socket" clientAbstractPath :: ByteString clientAbstractPath = "/tmp/FieNg4shamo4Thie.socket" unixSocketStream :: IO (Socket Unix Stream Default) unixSocketStream = socket unixSocketDatagram :: IO (Socket Unix Datagram Default) unixSocketDatagram = socket testServerClientStream :: SocketAddress Unix -> (Socket Unix Stream Default, Socket Unix Stream Default) -> IO () testServerClientStream addr (server, client) = do bind server addr listen server 5 serverRecv <- async $ do (peerSock, peerAddr) <- accept server r <- receive peerSock 4096 mempty send peerSock serverMessage mempty pure r connect client addr send client clientMessage mempty clientMessageReceived <- wait serverRecv serverMessageReceived <- receive client 4096 mempty clientMessageReceived @?= clientMessage serverMessageReceived @?= serverMessage testServerClientDatagram :: SocketAddress Unix -> SocketAddress Unix -> (Socket Unix Datagram Default, Socket Unix Datagram Default) -> IO () testServerClientDatagram sAddr cAddr (server, client) = do bind server sAddr bind client cAddr serverRecv <- async $ do (r, peerAddr) <- receiveFrom server 4096 mempty sendTo server serverMessage mempty peerAddr pure r sendTo client clientMessage mempty sAddr clientMessageReceived <- wait serverRecv serverMessageReceived <- receive client 4096 mempty clientMessageReceived @?= clientMessage serverMessageReceived @?= serverMessage
VyacheslavHashov/haskell-socket-unix
test/Internal.hs
mit
3,599
0
19
785
887
445
442
94
2
module Rebase.Data.Hashable ( module Data.Hashable ) where import Data.Hashable
nikita-volkov/rebase
library/Rebase/Data/Hashable.hs
mit
83
0
5
12
20
13
7
4
0