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 QuasiQuotes, BangPatterns, ScopedTypeVariables, TemplateHaskell, OverloadedStrings #-} {- The compactor does link-time optimization. It is much simpler than the Optimizer, no fancy dataflow analysis here. Optimizations: - rewrite all variables starting with h$$ to shorter names, these are internal names - write all function metadata compactly -} module Gen2.Compactor where import DynFlags import Control.Lens import Control.Monad.State.Strict import qualified Data.Binary.Get as DB import qualified Data.Binary.Put as DB import Data.Bits import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as BS import Data.Char (chr, ord) import Data.Function (on) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Data.Int import Data.List import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Compiler.JMacro import Compiler.Settings import Gen2.Base import Gen2.ClosureInfo import Gen2.Utils (buildingProf, buildingDebug) -- | collect global objects (data / CAFs). rename them and add them to the table collectGlobals :: [StaticInfo] -> State CompactorState () collectGlobals = mapM_ (\(StaticInfo i _ _) -> renameObj i) debugShowStat :: (JStat, [ClosureInfo], [StaticInfo]) -> String debugShowStat (_s, cis, sis) = "closures:\n" ++ unlines (map show cis) ++ "\nstatics:" ++ unlines (map show sis) ++ "\n\n" renameInternals :: GhcjsSettings -> DynFlags -> CompactorState -> [(JStat, [ClosureInfo], [StaticInfo])] -> (CompactorState, [JStat], JStat) renameInternals _settings dflags cs0 stats0 = (cs, stats, meta) where ((stats, meta), cs) = runState renamed cs0 renamed :: State CompactorState ([JStat], JStat) renamed | buildingDebug dflags || buildingProf dflags = do cs <- get let renamedStats = map (\(s,_,_) -> s & identsS %~ lookupRenamed cs) stats0 statics = map (renameStaticInfo cs) $ concatMap (\(_,_,x) -> x) stats0 infos = map (renameClosureInfo cs) $ concatMap (\(_,x,_) -> x) stats0 -- render metadata as individual statements meta = mconcat (map staticDeclStat statics) <> mconcat (map (staticInitStat $ buildingProf dflags) statics) <> mconcat (map (closureInfoStat True) infos) return (renamedStats, meta) | otherwise = do -- collect all global objects and entries, add them to the renaming table mapM_ (\(_, cis, sis) -> do mapM_ (renameEntry . TxtI . ciVar) cis mapM_ (renameObj . siVar) sis mapM_ collectLabels sis) stats0 -- sort our entries, store the results -- propagate all renamings throughtout the code cs <- get let renamedStats = map (\(s,_,_) -> s & identsS %~ lookupRenamed cs) stats0 sortedInfo = concatMap (\(_,xs,_) -> map (renameClosureInfo cs) xs) stats0 entryArr = map (TxtI . fst) . sortBy (compare `on` snd) . HM.toList $ cs ^. entries lblArr = map (TxtI . fst) . sortBy (compare `on` snd) . HM.toList $ cs ^. labels ss = concatMap (\(_,_,xs) -> map (renameStaticInfo cs) xs) stats0 infoBlock = encodeStr (concatMap (encodeInfo cs) sortedInfo) staticBlock = encodeStr (concatMap (encodeStatic cs) ss) staticDecls = mconcat (map staticDeclStat ss) meta = staticDecls <> [j| h$scheduleInit(`entryArr`, h$staticDelayed, `lblArr`, `infoBlock`, `staticBlock`); h$staticDelayed = []; |] return (renamedStats, meta) -- | rename a heap object, which means adding it to the -- static init table in addition to the renamer renameObj :: Text -> State CompactorState Text renameObj xs = do (TxtI xs') <- renameVar (TxtI xs) addItem statics statics numStatics numStatics parentStatics xs' return xs' renameEntry :: Ident -> State CompactorState Ident renameEntry i = do i'@(TxtI i'') <- renameVar i addItem entries entries numEntries numEntries parentEntries i'' return i' addItem :: Getting (HashMap Text Int) CompactorState (HashMap Text Int) -> Setting (->) CompactorState CompactorState (HashMap Text Int) (HashMap Text Int) -> Getting Int CompactorState Int -> ASetter' CompactorState Int -> Getting (HashMap Text Int) CompactorState (HashMap Text Int) -> Text -> State CompactorState () addItem items items' numItems numItems' parentItems i = do s <- use items case HM.lookup i s of Just _ -> return () Nothing -> do sp <- use parentItems case HM.lookup i sp of Just _ -> return () Nothing -> do ni <- use numItems items' %= HM.insert i ni numItems' += 1 collectLabels :: StaticInfo -> State CompactorState () collectLabels si = mapM_ (addItem labels labels numLabels numLabels parentLabels) (labelsV . siVal $ si) where labelsV (StaticData _ args) = concatMap labelsA args labelsV (StaticList args _) = concatMap labelsA args labelsV _ = [] labelsA (StaticLitArg l) = labelsL l labelsA _ = [] labelsL (LabelLit _ lbl) = [lbl] labelsL _ = [] lookupRenamed :: CompactorState -> Ident -> Ident lookupRenamed cs i@(TxtI t) = case HM.lookup t (cs ^. nameMap) of Nothing -> i Just i' -> i' renameVar :: Ident -- ^ text identifier to rename -> State CompactorState Ident -- ^ the updated renamer state and the new ident renameVar i@(TxtI t) | "h$$" `T.isPrefixOf` t = do m <- use nameMap case HM.lookup t m of Just r -> return r Nothing -> do y <- newIdent nameMap %= HM.insert t y return y | otherwise = return i newIdent :: State CompactorState Ident newIdent = do (y:ys) <- use identSupply identSupply .= ys return y -- | rename a compactor info entry according to the compactor state (no new renamings are added) renameClosureInfo :: CompactorState -> ClosureInfo -> ClosureInfo renameClosureInfo cs (ClosureInfo v rs n l t s) = (ClosureInfo (renameV v) rs n l t (f s)) where renameV t = maybe t (\(TxtI t') -> t') (HM.lookup t m) m = cs ^. nameMap f (CIStaticRefs rs) = CIStaticRefs (map renameV rs) -- | rename a static info entry according to the compactor state (no new renamings are added) renameStaticInfo :: CompactorState -> StaticInfo -> StaticInfo renameStaticInfo cs si = si & staticIdents %~ renameIdent where renameIdent t = maybe t (\(TxtI t') -> t') (HM.lookup t $ cs ^. nameMap) staticIdents :: Traversal' StaticInfo Text staticIdents f (StaticInfo i v cc) = StaticInfo <$> f i <*> staticIdentsV f v <*> pure cc staticIdentsV :: Traversal' StaticVal Text staticIdentsV f (StaticFun i) = StaticFun <$> f i staticIdentsV f (StaticThunk (Just i)) = StaticThunk . Just <$> f i staticIdentsV f (StaticData con args) = StaticData <$> f con <*> traverse (staticIdentsA f) args staticIdentsV f (StaticList xs t) = StaticList <$> traverse (staticIdentsA f) xs <*> traverse f t staticIdentsV _ x = pure x staticIdentsA :: Traversal' StaticArg Text staticIdentsA f (StaticObjArg t) = StaticObjArg <$> f t staticIdentsA _ x = pure x {- simple encoding of naturals using only printable low char points, rely on gzip to compress repeating sequences, most significant bits first 1 byte: ascii code 32-123 (0-89), \ and " unused 2 byte: 124 a b (90-8189) 3 byte: 125 a b c (8190-737189) -} encodeStr :: [Int] -> String encodeStr = concatMap encodeChr where c :: Int -> Char c i | i > 90 || i < 0 = error ("encodeStr: c " ++ show i) | i >= 59 = chr (34+i) | i >= 2 = chr (33+i) | otherwise = chr (32+i) encodeChr i | i < 0 = error "encodeStr: negative" | i <= 89 = [c i] | i <= 8189 = let (c1, c2) = (i - 90) `divMod` 90 in [chr 124, c c1, c c2] | i <= 737189 = let (c2a, c3) = (i - 8190) `divMod` 90 (c1, c2) = c2a `divMod` 90 in [chr 125, c c1, c c2, c c3] | otherwise = error "encodeStr: overflow" entryIdx :: String -> CompactorState -> Text -> Int entryIdx msg cs i = fromMaybe lookupParent (HM.lookup i' (cs ^. entries)) where (TxtI i') = lookupRenamed cs (TxtI i) lookupParent = maybe err (+ cs ^. numEntries) (HM.lookup i' (cs ^. parentEntries)) err = error (msg ++ ": invalid entry: " ++ T.unpack i') objectIdx :: String -> CompactorState -> Text -> Int objectIdx msg cs i = fromMaybe lookupParent (HM.lookup i' (cs ^. statics)) where (TxtI i') = lookupRenamed cs (TxtI i) lookupParent = maybe err (+ cs ^. numStatics) (HM.lookup i' (cs ^. parentStatics)) err = error (msg ++ ": invalid static: " ++ T.unpack i') labelIdx :: String -> CompactorState -> Text -> Int labelIdx msg cs l = fromMaybe lookupParent (HM.lookup l (cs ^. labels)) where lookupParent = maybe err (+ cs ^. numLabels) (HM.lookup l (cs ^. parentLabels)) err = error (msg ++ ": invalid label: " ++ T.unpack l) encodeInfo :: CompactorState -> ClosureInfo -- ^ information to encode -> [Int] encodeInfo cs (ClosureInfo _var regs name layout typ static) | CIThunk <- typ = [0] ++ ls | (CIFun _arity regs0) <- typ, regs0 /= argSize regs = error ("encodeInfo: inconsistent register metadata for " ++ T.unpack name) | (CIFun arity _regs0) <- typ = [1, arity, encodeRegs regs] ++ ls | (CICon tag) <- typ = [2, tag] ++ ls | CIStackFrame <- typ = [3, encodeRegs regs] ++ ls -- (CIPap ar) <- typ = [4, ar] ++ ls -- these should only appear during runtime | otherwise = error ("encodeInfo, unexpected closure type: " ++ show typ) where ls = encodeLayout layout ++ encodeSrt static encodeLayout CILayoutVariable = [0] encodeLayout (CILayoutUnknown s) = [s+1] encodeLayout (CILayoutFixed s _vs) = [s+1] encodeSrt (CIStaticRefs rs) = length rs : map (objectIdx "encodeInfo" cs) rs encodeRegs CIRegsUnknown = 0 encodeRegs (CIRegs skip regTypes) = let nregs = sum (map varSize regTypes) in encodeRegsTag skip nregs encodeRegsTag skip nregs | skip < 0 || skip > 1 = error "encodeRegsTag: unexpected skip" | otherwise = 1 + (nregs `shiftL` 1) + skip argSize (CIRegs skip regTypes) = sum (map varSize regTypes) - 1 + skip argSize _ = 0 encodeStatic :: CompactorState -> StaticInfo -> [Int] encodeStatic cs (StaticInfo _to sv _) | StaticFun f <- sv = [1, entry f] | StaticThunk (Just t) <- sv = [2, entry t] | StaticThunk Nothing <- sv = [0] | StaticUnboxed (StaticUnboxedBool b) <- sv = [3 + fromEnum b] | StaticUnboxed (StaticUnboxedInt i) <- sv = [5] -- ++ encodeInt i | StaticUnboxed (StaticUnboxedDouble d) <- sv = [6] -- ++ encodeDouble d -- | StaticString t <- sv = [7, T.length t] ++ map encodeChar (T.unpack t) -- | StaticBin bs <- sv = [8, BS.length bs] ++ map fromIntegral (BS.unpack bs) | StaticList [] Nothing <- sv = [8] | StaticList args t <- sv = [9, length args] ++ maybe [0] (\t' -> [1, obj t']) t ++ concatMap encodeArg (reverse args) | StaticData con args <- sv = (if length args <= 6 then [11+length args] else [10,length args]) ++ [entry con] ++ concatMap encodeArg args where obj = objectIdx "encodeStatic" cs entry = entryIdx "encodeStatic" cs lbl = labelIdx "encodeStatic" cs -- | an argument is either a reference to a heap object or a primitive value encodeArg (StaticLitArg (BoolLit b)) = [0 + fromEnum b] encodeArg (StaticLitArg (IntLit 0)) = [2] encodeArg (StaticLitArg (IntLit 1)) = [3] encodeArg (StaticLitArg (IntLit i)) = [4] ++ encodeInt i encodeArg (StaticLitArg NullLit) = [5] encodeArg (StaticLitArg (DoubleLit d)) = [6] ++ encodeDouble d encodeArg (StaticLitArg (StringLit s)) = [7] ++ encodeString s encodeArg (StaticLitArg (BinLit b)) = [8] ++ encodeBinary b encodeArg (StaticLitArg (LabelLit b l)) = [9, fromEnum b, lbl l] encodeArg (StaticConArg con args) = [10, entry con, length args] ++ concatMap encodeArg args encodeArg (StaticObjArg t) = [11 + obj t] -- encodeArg x = error ("encodeArg: unexpected: " ++ show x) encodeChar = ord -- fixme make characters more readable encodeString :: Text -> [Int] encodeString xs = encodeBinary (TE.encodeUtf8 xs) -- ByteString is prefixed with length, then blocks of 4 numbers encoding 3 bytes encodeBinary :: BS.ByteString -> [Int] encodeBinary bs = BS.length bs : go bs where go b | BS.null b = [] | l == 1 = let b0 = b `BS.index` 0 in map fromIntegral [ b0 `shiftR` 2, (b0 .&. 3) `shiftL` 4 ] | l == 2 = let b0 = b `BS.index` 0 b1 = b `BS.index` 1 in map fromIntegral [ b0 `shiftR` 2 , ((b0 .&. 3) `shiftL` 4) .|. (b1 `shiftR` 4) , (b1 .&. 15) `shiftL` 2 ] | otherwise = let b0 = b `BS.index` 0 b1 = b `BS.index` 1 b2 = b `BS.index` 2 in map fromIntegral [ b0 `shiftR` 2 , ((b0 .&. 3) `shiftL` 4) .|. (b1 `shiftR` 4) , ((b1 .&. 15) `shiftL` 2) .|. (b2 `shiftR` 6) , b2 .&. 63 ] ++ go (BS.drop 3 b) where l = BS.length b encodeInt :: Integer -> [Int] encodeInt i | i >= -10 && i < encodeMax - 11 = [fromIntegral i + 12] | i > 2^(31::Int)-1 || i < -2^(31::Int) = error "encodeInt: integer outside 32 bit range" | otherwise = let i' :: Int32 = fromIntegral i in [0, fromIntegral ((i' `shiftR` 16) .&. 0xffff), fromIntegral (i' .&. 0xffff)] -- encode a possibly 53 bit int encodeSignificand :: Integer -> [Int] encodeSignificand i | i >= -10 && i < encodeMax - 11 = [fromIntegral i + 12] | i > 2^(53::Int) || i < -2^(53::Int) = error ("encodeInt: integer outside 53 bit range: " ++ show i) | otherwise = let i' = abs i in [if i < 0 then 0 else 1] ++ map (\r -> fromIntegral ((i' `shiftR` r) .&. 0xffff)) [48,32,16,0] encodeDouble :: SaneDouble -> [Int] encodeDouble (SaneDouble d) | isNegativeZero d = [0] | d == 0 = [1] | isInfinite d && d > 0 = [2] | isInfinite d = [3] | isNaN d = [4] | abs exponent <= 30 = [6 + fromIntegral exponent + 30] ++ encodeSignificand significand | otherwise = [5] ++ encodeInt (fromIntegral exponent) ++ encodeSignificand significand where (significand, exponent) = decodeFloat d encodeMax :: Integer encodeMax = 737189 {- | The Base data structure contains the information we need to do incremental linking against a base bundle. base file format: GHCJSBASE [renamer state] [linkedPackages] [packages] [modules] [symbols] -} renderBase :: Base -- ^ base metadata -> BL.ByteString -- ^ rendered result renderBase = DB.runPut . putBase loadBase :: FilePath -> IO Base loadBase file = DB.runGet (getBase file) <$> BL.readFile file ---------------------------- {-# INLINE identsS #-} identsS :: Traversal' JStat Ident identsS f (DeclStat i) = DeclStat <$> f i identsS f (ReturnStat e) = ReturnStat <$> identsE f e identsS f (IfStat e s1 s2) = IfStat <$> identsE f e <*> identsS f s1 <*> identsS f s2 identsS f (WhileStat b e s) = WhileStat b <$> identsE f e <*> identsS f s identsS f (ForInStat b i e s) = ForInStat b <$> f i <*> identsE f e <*> identsS f s identsS f (SwitchStat e xs s) = SwitchStat <$> identsE f e <*> (traverse . traverseCase) f xs <*> identsS f s where traverseCase g (e,s) = (,) <$> identsE g e <*> identsS g s identsS f (TryStat s1 i s2 s3) = TryStat <$> identsS f s1 <*> f i <*> identsS f s2 <*> identsS f s3 identsS f (BlockStat xs) = BlockStat <$> (traverse . identsS) f xs identsS f (ApplStat e es) = ApplStat <$> identsE f e <*> (traverse . identsE) f es identsS f (UOpStat op e) = UOpStat op <$> identsE f e identsS f (AssignStat e1 e2) = AssignStat <$> identsE f e1 <*> identsE f e2 identsS _ (UnsatBlock{}) = error "identsS: UnsatBlock" identsS _ (AntiStat{}) = error "identsS: AntiStat" identsS f (LabelStat l s) = LabelStat l <$> identsS f s identsS _ b@(BreakStat{}) = pure b identsS _ c@(ContinueStat{}) = pure c {-# INLINE identsE #-} identsE :: Traversal' JExpr Ident identsE f (ValExpr v) = ValExpr <$> identsV f v identsE f (SelExpr e i) = SelExpr <$> identsE f e <*> pure i -- do not rename properties identsE f (IdxExpr e1 e2) = IdxExpr <$> identsE f e1 <*> identsE f e2 identsE f (InfixExpr s e1 e2) = InfixExpr s <$> identsE f e1 <*> identsE f e2 identsE f (UOpExpr o e) = UOpExpr o <$> identsE f e identsE f (IfExpr e1 e2 e3) = IfExpr <$> identsE f e1 <*> identsE f e2 <*> identsE f e3 identsE f (ApplExpr e es) = ApplExpr <$> identsE f e <*> (traverse . identsE) f es identsE _ (UnsatExpr{}) = error "identsE: UnsatExpr" identsE _ (AntiExpr{}) = error "identsE: AntiExpr" {-# INLINE identsV #-} identsV :: Traversal' JVal Ident identsV f (JVar i) = JVar <$> f i identsV f (JList xs) = JList <$> (traverse . identsE) f xs identsV _ d@(JDouble{}) = pure d identsV _ i@(JInt{}) = pure i identsV _ s@(JStr{}) = pure s identsV _ r@(JRegEx{}) = pure r identsV f (JHash m) = JHash <$> (traverse . identsE) f m identsV f (JFunc args s) = JFunc <$> traverse f args <*> identsS f s identsV _ (UnsatVal{}) = error "identsV: UnsatVal" compact :: GhcjsSettings -> DynFlags -> CompactorState -> [(JStat, [ClosureInfo], [StaticInfo])] -> (CompactorState, [JStat], JStat) -- ^ renamer state, statements for each unit, metadata compact settings dflags rs input = renameInternals settings dflags rs input
forked-upstream-packages-for-ghcjs/ghcjs
ghcjs/src/Gen2/Compactor.hs
mit
19,377
0
20
6,009
6,527
3,324
3,203
346
12
module ImpreciseMatch ( ) where import ClassyPrelude data DiaMark = Grave | Acute | Circumflex | Tilde | Macron | Overline | Breve | DotAbove | Diaeresis | HookAbove | RingAbove | DoubleAcute | Caron | VerticalLineAbove | DoubleVerticalLineAbove | DoubleGrave | Candrabindu | InvertedBreve | TurnedCommaAbove | CommaAbove | ReversedCommaAbove -- INCOMPLETE! data CharProp = Uppercase | Lowercase | Superscript | Subscript | Diacritics [DiaMark] decomposeChar ::
aelve/Jane
CharProp.hs
mit
483
1
8
89
105
69
36
-1
-1
module Oden.Identifier ( Identifier(..), IdentifierValidationError, errorMessage, createLegalIdentifier, asString ) where import Data.Char newtype Identifier = Identifier String deriving (Show, Eq, Ord) data IdentifierValidationError = Empty | IllegalStart Char | IllegalCharacters String errorMessage :: IdentifierValidationError -> String errorMessage Empty = "Identifier cannot be empty" errorMessage (IllegalStart c) = "Identifier cannot start with '" ++ [c] ++ "'" errorMessage (IllegalCharacters chars) = "Identifier cannot contain any of '" ++ chars ++ "'" createLegalIdentifier :: String -> Either IdentifierValidationError Identifier createLegalIdentifier [] = Left Empty createLegalIdentifier (first:_) | not (isLetter first) = Left (IllegalStart first) createLegalIdentifier s = case filter (not . legal) s of [] -> Right (Identifier s) chars -> Left (IllegalCharacters chars) where legal c = isLetter c || isNumber c || c `elem` "_-'!?" asString :: Identifier -> String asString (Identifier s) = s
AlbinTheander/oden
src/Oden/Identifier.hs
mit
1,161
0
10
286
311
162
149
29
2
{-# LANGUAGE OverloadedStrings, NoMonomorphismRestriction, FlexibleContexts, MultiParamTypeClasses, ScopedTypeVariables, DeriveDataTypeable, DeriveGeneric #-} module EZCouch.Model.View where import Prelude () import ClassyPrelude import GHC.Generics import EZCouch.Entity import Data.Aeson data View = View { map :: Text, reduce :: Maybe Text } deriving (Show, Eq, Generic) instance ToJSON View where toJSON (View map reduce) = object $ catMaybes [ Just ("map", toJSON map), (,) <$> pure "reduce" <*> toJSON <$> reduce ] instance FromJSON View where parseJSON = withObject "View" $ \o -> View <$> o .: "map" <*> o .:? "reduce"
nikita-volkov/ez-couch
src/EZCouch/Model/View.hs
mit
655
0
12
115
179
98
81
16
0
{-# LANGUAGE CPP #-} module Main ( main -- :: IO () ) where import Criterion.Main import Crypto.Sign.Ed25519 import Data.Maybe (fromJust) import Control.DeepSeq import qualified Data.ByteString as B -------------------------------------------------------------------------------- #if !MIN_VERSION_bytestring(0,10,0) instance NFData B.ByteString #endif instance NFData SecretKey instance NFData PublicKey -------------------------------------------------------------------------------- main :: IO () main = do -- Don't use `createKeypair`, since that will incur a ton of calls -- to the OS to generate randomness. Simply generate a bogus Ed25519 -- seed instead. let seed = B.pack [0..31] keys@(pk,sk) = fromJust (createKeypairFromSeed_ seed) -- Generate a dummy message to sign, and a signature to verify -- against. dummy = B.pack [0..255] msg = sign sk dummy defaultMain [ bench "deterministic key generation" $ nf createKeypairFromSeed_ seed , bench "signing a 256 byte message" $ nf (sign sk) dummy , bench "verifying a signature" $ nf (verify pk) msg , bench "roundtrip 256-byte sign/verify" $ nf (signBench keys) dummy ] signBench :: (PublicKey, SecretKey) -> B.ByteString -> Bool signBench (pk, sk) xs = verify pk (sign sk xs)
thoughtpolice/hs-ed25519
benchmarks/bench.hs
mit
1,370
0
12
306
294
158
136
24
1
{-# LANGUAGE TemplateHaskell #-} module Joebot.Plugins.Steam.Types where import qualified Data.Text as T import qualified Data.Map as M import Control.Lens import Control.Monad.State data User = User { _sid :: T.Text , _pname :: T.Text , _pstate :: Int , _game :: Maybe T.Text } makeLenses ''User type Users = M.Map T.Text T.Text data ServState = ServState { _users :: Users , _skey :: T.Text } makeLenses ''ServState type UserServ = StateT ServState IO
joeschmo/joebot2
src/Joebot/Plugins/Steam/Types.hs
mit
494
0
10
112
145
86
59
18
0
module Example.Data.Student ( Student(..) , StudentId(..) , StudentName(..) ) where import Data.Int (Int32) import Data.Text (Text) import Example.Data.Major (MajorId) data Student key = Student { studentId :: key , studentName :: StudentName , studentMajor :: MajorId } deriving (Show, Eq) newtype StudentId = StudentId { studentIdInt :: Int32 } deriving (Show, Eq, Ord) newtype StudentName = StudentName { studentNameText :: Text } deriving (Show, Eq)
flipstone/orville
orville-postgresql/sample-project/Example/Data/Student.hs
mit
483
0
8
94
152
96
56
18
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} module GenericRLPTest where import Control.Monad (forM_, when) import Data.Either (isRight) import qualified Data.Map as M import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.ByteString as S import qualified Data.ByteString.Base16 as SB16 import qualified Data.ByteString.Char8 as S8 import Test.QuickCheck import Test.QuickCheck.Arbitrary import qualified Test.Tasty as Tasty import Test.Tasty.Hspec import Data.RLP import Data.Proxy import GHC.Generics newtype PositiveInteger = PositiveInteger Integer deriving (Eq, Read, Show, Generic, RLPEncodable) instance Arbitrary PositiveInteger where arbitrary = PositiveInteger . abs <$> arbitrary newtype RLPByteString = RLPByteString S8.ByteString deriving (Eq, Read, Show, Generic, RLPEncodable) instance Arbitrary RLPByteString where arbitrary = do len <- arbitrary RLPByteString . S8.pack <$> vector len data ArglessUnit = ArglessUnit deriving (Show, Eq, Generic) instance RLPEncodable ArglessUnit instance Arbitrary ArglessUnit where arbitrary = return ArglessUnit newtype OneArgUnit a = OneArgUnit PositiveInteger deriving (Show, Eq, Generic) instance (RLPEncodable a) => RLPEncodable (OneArgUnit a) instance (Arbitrary a) => Arbitrary (OneArgUnit a) where arbitrary = OneArgUnit <$> arbitrary data ArglessOneArgSum a = AOALeft | AOARight a deriving (Show, Eq, Generic) instance (RLPEncodable a) => RLPEncodable (ArglessOneArgSum a) instance (Arbitrary a) => Arbitrary (ArglessOneArgSum a) where arbitrary = do lOrR <- arbitrary if lOrR then return AOALeft else AOARight <$> arbitrary data TwoSingleArgSummands a b = TSASLeft PositiveInteger | TSASRight PositiveInteger deriving (Show, Eq, Generic) instance (RLPEncodable a, RLPEncodable b) => RLPEncodable (TwoSingleArgSummands a b) instance (Arbitrary a, Arbitrary b) => Arbitrary (TwoSingleArgSummands a b) where arbitrary = do lOrR <- arbitrary if lOrR then TSASLeft <$> arbitrary else TSASRight <$> arbitrary data TreeLikeStructure a = TLSBranch (TreeLikeStructure a) (TreeLikeStructure a) | TLSLeaf a | TLSTerminal deriving (Show, Eq, Generic) instance (RLPEncodable a) => RLPEncodable (TreeLikeStructure a) instance (Arbitrary a) => Arbitrary (TreeLikeStructure a) where arbitrary = do isTerm <- arbitrary if isTerm then return TLSTerminal else do isBranch <- arbitrary if isBranch then TLSBranch <$> arbitrary <*> arbitrary else TLSLeaf <$> arbitrary data AComplexRecord = AComplexRecord { aComplexString :: RLPByteString , aComplexInt :: PositiveInteger } deriving (Show, Eq, Generic) instance RLPEncodable AComplexRecord instance Arbitrary AComplexRecord where arbitrary = AComplexRecord <$> arbitrary <*> arbitrary data ANestedRecord = ANestedRecord { aNestedString :: RLPByteString , aNestedComplesRecord :: AComplexRecord } deriving (Show, Eq, Generic) instance RLPEncodable ANestedRecord instance Arbitrary ANestedRecord where arbitrary = ANestedRecord <$> arbitrary <*> arbitrary genericSpec :: Spec genericSpec = describe "Generic instances" $ do identityWithQuickcheck (Proxy @ArglessUnit ) "Argless unitary datatype" identityWithQuickcheck (Proxy @(OneArgUnit PositiveInteger) ) "[Int] One-arg unitary datatype" identityWithQuickcheck (Proxy @(ArglessOneArgSum PositiveInteger) ) "[Int] Sum type of argless and one-arg constructors" identityWithQuickcheck (Proxy @(TwoSingleArgSummands PositiveInteger PositiveInteger)) "[Int] Sum type of two one-arg constructors" identityWithQuickcheck (Proxy @(TreeLikeStructure PositiveInteger) ) "[Int] A tree-like structure" identityWithQuickcheck (Proxy @(OneArgUnit RLPByteString) ) "[BS] One-arg unitary datatype" identityWithQuickcheck (Proxy @(ArglessOneArgSum RLPByteString) ) "[BS] Sum type of argless and one-arg constructors" identityWithQuickcheck (Proxy @(TwoSingleArgSummands RLPByteString RLPByteString) ) "[BS/BS] Sum type of two one-arg constructors" identityWithQuickcheck (Proxy @(TreeLikeStructure RLPByteString) ) "[BS] A tree-like structure" identityWithQuickcheck (Proxy @(TwoSingleArgSummands RLPByteString PositiveInteger) ) "[BS/Int] Sum type of two one-arg constructors" identityWithQuickcheck (Proxy @(TwoSingleArgSummands PositiveInteger RLPByteString) ) "[Int/BS] Sum type of two one-arg constructors" identityWithQuickcheck (Proxy @AComplexRecord ) "A record with named fields" identityWithQuickcheck (Proxy @ANestedRecord ) "A record with another record inside of it" maxQuickchecks :: Int maxQuickchecks = 100 identityWithQuickcheck :: forall a proxy. ( Arbitrary a , Eq a , Show a , RLPEncodable a ) => proxy a -> String -> Spec identityWithQuickcheck _ name = describe name . forM_ [1..maxQuickchecks] $ \n -> do describe (show n ++ "/" ++ show maxQuickchecks) $ do theA :: a <- runIO (generate arbitrary) satisfiesIdentity theA satisfiesIdentity :: forall a. ( RLPEncodable a , Eq a , Show a ) => a -> Spec satisfiesIdentity a = do let encoded = rlpEncode a decoded = rlpDecode encoded it "can successfully decode a previously encoded object" $ decoded `shouldSatisfy` isRight let Right asRight = decoded it "maintains identity after encoding and subsequently decoding" $ asRight `shouldBe` a
iostat/relapse
test/GenericRLPTest.hs
mit
6,759
0
15
2,089
1,417
741
676
131
1
module Prepare.Tanach.IndexModel where import Data.Text (Text) import Prepare.Tanach.TeiHeaderModel (TeiHeader) data Chapter = Chapter { chapterNumber :: Integer , chapterVerseCount :: Integer } deriving (Show) data Name = Name { nameName :: Text , nameAbbrev :: Text , nameNumber :: Maybe Text , nameFilename :: Text , nameHebrewname :: Maybe Text } deriving (Show) data Book = Book { bookName :: Name , bookChapters :: [Chapter] , bookChapterCount :: Integer } deriving (Show) data Index = Index { indexHeader :: TeiHeader , indexBooks :: [Book] } deriving (Show)
ancientlanguage/haskell-analysis
prepare/src/Prepare/Tanach/IndexModel.hs
mit
611
0
9
132
176
108
68
23
0
{-# LANGUAGE RecordWildCards #-} module ResourceDiscovery where import SoOSiM import ResourceDiscovery.Types import ResourceDiscovery.Utils resourceDiscovery :: RDState -> ComponentInput -> SimM RDState -- Get a new state, needed for initialization resourceDiscovery _ (ComponentMsg senderId content) | Just (NewState s) <- fromDynamic content = return s -- All nodes behave the same for a discovery request resourceDiscovery rdState (ComponentMsg senderId content) | Just (DiscoveryRequest amount properties) <- fromDynamic content = do let query = generateQuery senderId properties let qmsId = localQms rdState nodes <- invoke Nothing qmsId (toDyn (Upward amount query)) invokeNoWait Nothing senderId nodes return rdState -- All nodes behave the same for a lookup request resourceDiscovery rdState (ComponentMsg senderId content) | Just (Lookup amount query) <- fromDynamic content = do undefined -- Aggregate node receiving an Upward Msg resourceDiscovery rdState@(AggregateState {}) msg@(ComponentMsg senderId content) | Just (Upward amount query) <- fromDynamic content = do case (null $ c1 query, null $ c2 query, null $ c3 query) of -- Type A (False,False,False) -> do forward msg (sqmsInstance rdState) return rdState (False,False,True) -> do if (match (c2 query) (aggregateStamp rdState)) -- Type B then do invokeNoWait Nothing (dhtEntryId rdState) (toDyn (Lookup amount query)) return rdState -- Type C else do let nextId = nextQms [] (sqmsInstance rdState) (probabilityTable rdState) forward msg nextId return rdState -- Type D (False,True,True) -> do invokeNoWait Nothing (dhtEntryId rdState) (toDyn (Lookup amount query)) return rdState -- Aggregate node receiving an Update Msg resourceDiscovery rdState@(AggregateState {}) msg@(ComponentMsg senderId content) | Just (Update amount query nodes) <- fromDynamic content = do let rdState' = rdState {probabilityTable = updateTable (null nodes) senderId (probabilityTable rdState)} if (null nodes) -- Nodes not found then do let nextId = nextQms [] (sqmsInstance rdState) (probabilityTable rdState') forward msg nextId return rdState' -- Nodes are found else do let origin = lookupRouting (queryId query) (routingTable rdState') let rdState'' = rdState' {routingTable = deleteRoute (queryId query) (routingTable rdState')} reply origin (FoundNodes nodes) return rdState'' -- Aggregate node receiving a Downward Msg resourceDiscovery rdState@(AggregateState {}) msg@(ComponentMsg senderId content) | Just (Downward amount query) <- fromDynamic content = do case (null $ c2 query) of False -> do if (match (c2 query) (aggregateStamp rdState)) -- Type A then do invokeNoWait Nothing (dhtEntryId rdState) (toDyn (Lookup amount query)) return rdState -- Type B else do let nextId = nextQms [] (sqmsInstance rdState) (probabilityTable rdState) forward msg nextId return rdState -- Type C True -> do invokeNoWait Nothing (dhtEntryId rdState) (toDyn (Lookup amount query)) return rdState -- Super node receiving an Upward Msg resourceDiscovery rdState@(SuperState {}) msg@(ComponentMsg senderId content) | Just (Upward amount query) <- fromDynamic content = do case (null $ c3 query) of -- Type A False -> do case (match (c3 query) (superStamp rdState), match (c2 query) (aggregateStamp (aggregateState rdState))) of (True,True) -> do invokeNoWait Nothing (dhtEntryId $ aggregateState rdState) (toDyn (Lookup amount query)) return rdState (True,False) -> do let nextId = nextQms [] (sqmsInstance $ aggregateState rdState) (probabilityTable $ aggregateState rdState) invokeNoWait Nothing nextId (toDyn (Downward amount query)) return rdState (False,_) -> do undefined -- Type B True -> do aggregateState' <- resourceDiscovery (aggregateState rdState) msg return $ rdState {aggregateState = aggregateState'} -- Super node receiving an Update Msg resourceDiscovery rdState@(SuperState {}) msg@(ComponentMsg senderId content) | Just (Update amount query nodes) <- fromDynamic content = do if (null nodes) then do undefined else do undefined
christiaanb/SoOSiM
examples/Twente/ResourceDiscovery.hs
mit
4,671
0
24
1,232
1,419
686
733
99
11
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Network.BitFunctor2.Platform.Storage where import Control.Monad.State import Control.Monad.Reader import Control.Monad.Except import qualified Network.BitFunctor.Identifiable as Id import Network.BitFunctor.Crypto.Hash (Hash, Id) import Network.BitFunctor2.Platform.Blockchain.Types (Block) import Network.BitFunctor2.Platform.Storage.Types data BlockchainStorageState = BlockchainStorageState { } deriving (Eq, Show) newtype BlockchainStorageApp a = BlockchainStorageApp { unBlockchainStorageApp :: StateT BlockchainStorageState (ReaderT BlockchainStorageConfig (ExceptT BlockchainStorageError IO)) a } deriving ( Monad , Functor , Applicative , MonadReader BlockchainStorageConfig , MonadState BlockchainStorageState , MonadIO , MonadError BlockchainStorageError ) instance BlockchainStorage BlockchainStorageApp where
BitFunctor/bitfunctor
src/Network/BitFunctor2/Platform/Storage.hs
mit
961
1
11
165
175
107
68
21
0
{-# LANGUAGE RankNTypes #-} module Main where import qualified Data.Conduit.List as CL import qualified Data.Conduit.Binary as CB import Control.Monad.State import Control.Monad.Trans.Resource import Data.ByteString.Char8 (ByteString, empty, pack, unpack) import Data.Conduit import System.IO (stdin) -- Primary references from: -- http://www.stackage.org/snapshot/nightly-2015-03-08/package/conduit-1.2.4 -- http://www.stackage.org/snapshot/nightly-2015-03-08/package/conduit-extra-1.1.7.0 -- Bits and pieces from: -- https://www.fpcomplete.com/user/snoyberg/library-documentation/conduit-overview -- https://www.fpcomplete.com/user/chad/snippets/random-code-snippets/conduit-from-filepath-to-bytestrings main = do let input = "The quick brown fox jumped over the lazy dog" splitWordsExample input wordLengthExample_1 input wordLengthExample_2 input wordLengthExample_3 input userInputExample_1 userInputExample_2 userInputExample_3 filesExample_1 "examples/conduit-101-01/words.txt" filesExample_2 "examples/conduit-101-01/words.txt" "examples/conduit-101-01/output.txt" filesExample_3 "examples/conduit-101-01/words.txt" "examples/conduit-101-01/lengths.txt" splitWordsExample :: String -> IO () splitWordsExample input = do putStrLn "------------------------" putStrLn "EXAMPLE: Splitting words" putStrLn "------------------------" xs <- wordsSource input $$ identitySink mapM_ putStrLn xs putStrLn "" wordLengthExample_1 :: String -> IO () wordLengthExample_1 input = do putStrLn "-----------------------" putStrLn "EXAMPLE: Word lengths 1" putStrLn "-----------------------" xs <- wordsSource input $= numLettersConduit $$ identitySink mapM_ (putStrLn . show) xs putStrLn "" wordLengthExample_2 :: String -> IO () wordLengthExample_2 input = do putStrLn "-----------------------" putStrLn "EXAMPLE: Word lengths 2" putStrLn "-----------------------" xs <- wordsSource input $= numLettersConduit $= showConduit $$ identitySink mapM_ putStrLn xs putStrLn "" wordLengthExample_3 :: String -> IO () wordLengthExample_3 input = do putStrLn "-----------------------" putStrLn "EXAMPLE: Word lengths 3" putStrLn "-----------------------" xs <- wordsSource input $= fusedConduit $$ identitySink mapM_ putStrLn xs putStrLn "" userInputExample_1 :: IO () userInputExample_1 = do putStrLn "-------------------------------" putStrLn "EXAMPLE: Splitting user input 1" putStrLn "-------------------------------" putStrLn "Enter some input." putStrLn "" putStr "> " input <- getLine xs <- wordsSource input $$ identitySink mapM_ putStrLn xs putStrLn "" userInputExample_2 :: IO () userInputExample_2 = do putStrLn "-------------------------------" putStrLn "EXAMPLE: Splitting user input 2" putStrLn "-------------------------------" putStrLn "Enter some input." putStrLn "" putStr "> " _ <- userInputSource $$ identityStdOutSink putStrLn "" userInputExample_3 :: IO () userInputExample_3 = do putStrLn "-------------------------------" putStrLn "EXAMPLE: Splitting user input 3" putStrLn "-------------------------------" putStrLn "Enter some input, multiple times." putStrLn "" putStrLn "Simply hit <ENTER> with no input to quit." _ <- userInputConduitSource $$ identitiesStdOutSink putStrLn "" filesExample_1 :: FilePath -> IO () filesExample_1 file = do putStrLn "-------------------------------" putStrLn "EXAMPLE: Input source from file" putStrLn "-------------------------------" _ <- runResourceT $ fileInputSource file $$ identitiesResStdOutSink putStrLn "" filesExample_2 :: FilePath -> FilePath -> IO () filesExample_2 input output = do putStrLn "----------------------------" putStrLn "EXAMPLE: Output sink to file" putStrLn "----------------------------" putStrLn $ "See output file: " ++ output _ <- runResourceT $ fileInputSource input $= conduitToByteString $$ CB.sinkFile output written <- readFile output putStrLn written filesExample_3 :: FilePath -> FilePath -> IO () filesExample_3 input1 input2 = do putStrLn "-----------------------------" putStrLn "EXAMPLE: Multiple input files" putStrLn "-----------------------------" _ <- runResourceT $ multiFileInputSource [input1, input2] $= conduitFile $$ byteStringStdOutSink putStrLn "" wordsSource :: Monad m => String -> Producer m [String] wordsSource = yield . words identitySink :: Monad m => ConduitM [a] o m [a] identitySink = CL.foldMap id numLettersConduit :: Monad m => Conduit [String] m [Int] numLettersConduit = CL.map (map length) showConduit :: Monad m => Conduit [Int] m [String] showConduit = CL.map (map show) fusedConduit :: Monad m => Conduit [String] m [String] fusedConduit = fuse numLettersConduit showConduit userInputSource :: Producer IO String userInputSource = do let loop acc = do c <- liftIO getChar case c of ' ' -> do yield $ reverse acc loop [] '\n' -> yield $ reverse acc _ -> loop (c : acc) loop [] identityStdOutSink :: Consumer String IO () identityStdOutSink = awaitForever $ liftIO . putStrLn yieldStrings :: ConduitM ByteString [String] IO Bool yieldStrings = do mbs <- await case mbs of Nothing -> return False Just bs -> do let s = takeWhile (\x -> x /= '\r' && x /= '\n') $ unpack bs case s of "" -> return False ss -> do yield $ words ss return True userInputConduitSource :: Source IO [String] userInputConduitSource = do CB.sourceHandle stdin $= CB.lines $= loop where loop = do liftIO $ putStr "> " r <- yieldStrings case r of False -> return () True -> loop identitiesStdOutSink :: Consumer [String] IO () identitiesStdOutSink = awaitForever $ mapM_ (liftIO . putStrLn) fileInputSource :: (Monad m, MonadResource m) => FilePath -> Source m [String] fileInputSource file = do CB.sourceFile file $= loop where loop = do mbs <- await case mbs of Nothing -> return () Just bs -> do yield $ words $ unpack bs loop identitiesResStdOutSink :: (Monad m, MonadResource m) => Consumer [String] m () identitiesResStdOutSink = awaitForever $ mapM_ (liftIO . putStrLn) conduitToByteString :: Monad m => Conduit [String] m ByteString conduitToByteString = do awaitForever $ yield . pack . unlines multiFileInputSource :: MonadResource m => [FilePath] -> Source m FilePath multiFileInputSource files = do mapM_ yield files conduitFile :: MonadResource m => Conduit FilePath m ByteString conduitFile = do awaitForever CB.sourceFile byteStringStdOutSink :: MonadResource m => Consumer ByteString m () byteStringStdOutSink = do awaitForever $ liftIO . putStrLn . unpack
stormont/conduit-examples
examples/conduit-101-01/Main.hs
mit
7,093
0
21
1,541
1,793
830
963
245
3
module Exercise where data Graph = Graph{nodes :: [Node], edges :: [Edge]} type Node = Int type Edge = (Int, Int)
tcoenraad/functioneel-programmeren
2014/opg4a.hs
mit
115
0
9
22
49
32
17
4
0
{-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( getApplicationDev , appMain , develMain , makeFoundation , makeLogWare -- * for DevelMain , getApplicationRepl , shutdownApp -- * for GHCI , handler , db ) where #if MIN_VERSION_base(4,9,0) import Control.Concurrent (forkOSWithUnmask) #else import GHC.IO (unsafeUnmask) #endif import Control.Monad.Logger (liftLoc, runLoggingT) import Database.Persist.MySQL (createMySQLPool, myConnInfo, myPoolSize, runSqlPool) import qualified Database.MySQL.Base as MySQL import Import import Language.Haskell.TH.Syntax (qLocation) import Network.Wai (Middleware) import Network.Wai.Handler.Warp (Settings, defaultSettings, defaultShouldDisplayException, runSettings, setHost, setFork, setOnOpen, setOnClose, setOnException, setPort, getPort) import Network.Wai.Middleware.RequestLogger (Destination (Logger), IPAddrSource (..), OutputFormat (..), destination, mkRequestLogger, outputFormat) import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet, toLogStr) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Common import Handler.Home import Handler.Account import Handler.Quiz import Handler.Summary import Handler.Note import Handler.Generic -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- | This function allocates resources (such as a database connection pool), -- performs initialization and returns a foundation datatype value. This is also -- the place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeFoundation :: AppSettings -> IO App makeFoundation appSettings = do -- Some basic initializations: HTTP connection manager, logger, and static -- subsite. appHttpManager <- newManager appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger appStatic <- (if appMutableStatic appSettings then staticDevel else static) (appStaticDir appSettings) -- See http://www.yesodweb.com/blog/2017/11/use-mysql-safely-in-yesod MySQL.initLibrary -- We need a log function to create a connection pool. We need a connection -- pool to create our foundation. And we need our foundation to get a -- logging function. To get out of this loop, we initially create a -- temporary foundation without a real connection pool, get a log function -- from there, and then create the real foundation. let mkFoundation appConnPool = App {..} -- The App {..} syntax is an example of record wild cards. For more -- information, see: -- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html tempFoundation = mkFoundation $ error "connPool forced in tempFoundation" logFunc = messageLoggerSource tempFoundation appLogger -- Create the database connection pool pool <- flip runLoggingT logFunc $ createMySQLPool (myConnInfo $ appDatabaseConf appSettings) (myPoolSize $ appDatabaseConf appSettings) -- Perform database migration using our application's logging settings. runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc -- Return the foundation return $ mkFoundation pool -- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and -- applying some additional middlewares. makeApplication :: App -> IO Application makeApplication foundation = do logWare <- makeLogWare foundation -- Create the WAI application and apply middlewares appPlain <- toWaiAppPlain foundation return $ logWare $ defaultMiddlewaresNoLogging appPlain makeLogWare :: App -> IO Middleware makeLogWare foundation = mkRequestLogger def { outputFormat = if appDetailedRequestLogging $ appSettings foundation then Detailed True else Apache (if appIpFromHeader $ appSettings foundation then FromFallback else FromSocket) , destination = Logger $ loggerSet $ appLogger foundation } #if ! MIN_VERSION_base(4,9,0) forkOSWithUnmask :: ((forall a . IO a -> IO a) -> IO ()) -> IO ThreadId forkOSWithUnmask io = forkOS (io unsafeUnmask) #endif -- | Warp settings for the given foundation value. -- Use bound threads for thread-safe use of MySQL, and initialise and finalise -- them: see http://www.yesodweb.com/blog/2017/11/use-mysql-safely-in-yesod warpSettings :: App -> Settings warpSettings foundation = setPort (appPort $ appSettings foundation) $ setHost (appHost $ appSettings foundation) $ setOnException (\_req e -> when (defaultShouldDisplayException e) $ messageLoggerSource foundation (appLogger foundation) $(qLocation >>= liftLoc) "yesod" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) $ setFork (\x -> void $ forkOSWithUnmask x) $ setOnOpen (const $ MySQL.initThread >> return True) $ setOnClose (const MySQL.endThread) defaultSettings -- | For yesod devel, return the Warp settings and WAI Application. getApplicationDev :: IO (Settings, Application) getApplicationDev = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app <- makeApplication foundation return (wsettings, app) getAppSettings :: IO AppSettings getAppSettings = loadYamlSettings [configSettingsYml] [] useEnv -- | main function for use by yesod devel develMain :: IO () develMain = develMainHelper getApplicationDev -- | The @main@ function for an executable running this site. appMain :: IO () appMain = do -- Get the settings from all relevant sources settings <- loadYamlSettingsArgs -- fall back to compile-time values, set to [] to require values at runtime [configSettingsYmlValue] -- allow environment variables to override useEnv -- Generate the foundation from the settings foundation <- makeFoundation settings -- Generate a WAI Application from the foundation app <- makeApplication foundation -- Run the application with Warp runSettings (warpSettings foundation) app -------------------------------------------------------------- -- Functions for DevelMain.hs (a way to run the app from GHCi) -------------------------------------------------------------- getApplicationRepl :: IO (Int, App, Application) getApplicationRepl = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app1 <- makeApplication foundation return (getPort wsettings, foundation, app1) shutdownApp :: App -> IO () shutdownApp _ = return () --------------------------------------------- -- Functions for use in development with GHCi --------------------------------------------- -- | Run a handler handler :: Handler a -> IO a handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h -- | Run DB queries db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a db = handler . runDB
quantum-dan/HasKnowledge
Application.hs
mit
7,958
0
16
2,032
1,235
665
570
-1
-1
{-# htermination (readDecMyInt :: (List Char) -> (List (Tup2 MyInt (List Char)))) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Tup2 a b = Tup2 a b ; data Char = Char MyInt ; data Integer = Integer MyInt ; data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ordering = LT | EQ | GT ; fromIntMyInt :: MyInt -> MyInt fromIntMyInt x = x; asAs :: MyBool -> MyBool -> MyBool; asAs MyFalse x = MyFalse; asAs MyTrue x = x; primCmpNat :: Nat -> Nat -> Ordering; primCmpNat Zero Zero = EQ; primCmpNat Zero (Succ y) = LT; primCmpNat (Succ x) Zero = GT; primCmpNat (Succ x) (Succ y) = primCmpNat x y; primCmpInt :: MyInt -> MyInt -> Ordering; primCmpInt (Pos Zero) (Pos Zero) = EQ; primCmpInt (Pos Zero) (Neg Zero) = EQ; primCmpInt (Neg Zero) (Pos Zero) = EQ; primCmpInt (Neg Zero) (Neg Zero) = EQ; primCmpInt (Pos x) (Pos y) = primCmpNat x y; primCmpInt (Pos x) (Neg y) = GT; primCmpInt (Neg x) (Pos y) = LT; primCmpInt (Neg x) (Neg y) = primCmpNat y x; primCmpChar :: Char -> Char -> Ordering; primCmpChar (Char x) (Char y) = primCmpInt x y; compareChar :: Char -> Char -> Ordering compareChar = primCmpChar; esEsOrdering :: Ordering -> Ordering -> MyBool esEsOrdering LT LT = MyTrue; esEsOrdering LT EQ = MyFalse; esEsOrdering LT GT = MyFalse; esEsOrdering EQ LT = MyFalse; esEsOrdering EQ EQ = MyTrue; esEsOrdering EQ GT = MyFalse; esEsOrdering GT LT = MyFalse; esEsOrdering GT EQ = MyFalse; esEsOrdering GT GT = MyTrue; not :: MyBool -> MyBool; not MyTrue = MyFalse; not MyFalse = MyTrue; fsEsOrdering :: Ordering -> Ordering -> MyBool fsEsOrdering x y = not (esEsOrdering x y); gtEsChar :: Char -> Char -> MyBool gtEsChar x y = fsEsOrdering (compareChar x y) LT; ltEsChar :: Char -> Char -> MyBool ltEsChar x y = fsEsOrdering (compareChar x y) GT; isDigit :: Char -> MyBool; isDigit c = asAs (gtEsChar c (Char (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))))))))))))))))))))))))))))))))))))))))))))))) (ltEsChar c (Char (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))); primCharToInt :: Char -> MyInt; primCharToInt (Char x) = x; fromEnumChar :: Char -> MyInt fromEnumChar = primCharToInt; fromEnum_0 :: MyInt; fromEnum_0 = fromEnumChar (Char (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))))))))))))))))))))))))))))))))))))))))); primMinusNat :: Nat -> Nat -> MyInt; primMinusNat Zero Zero = Pos Zero; primMinusNat Zero (Succ y) = Neg (Succ y); primMinusNat (Succ x) Zero = Pos (Succ x); primMinusNat (Succ x) (Succ y) = primMinusNat x y; primPlusNat :: Nat -> Nat -> Nat; primPlusNat Zero Zero = Zero; primPlusNat Zero (Succ y) = Succ y; primPlusNat (Succ x) Zero = Succ x; primPlusNat (Succ x) (Succ y) = Succ (Succ (primPlusNat x y)); primMinusInt :: MyInt -> MyInt -> MyInt; primMinusInt (Pos x) (Neg y) = Pos (primPlusNat x y); primMinusInt (Neg x) (Pos y) = Neg (primPlusNat x y); primMinusInt (Neg x) (Neg y) = primMinusNat y x; primMinusInt (Pos x) (Pos y) = primMinusNat x y; msMyInt :: MyInt -> MyInt -> MyInt msMyInt = primMinusInt; readDec0 d = msMyInt (fromEnumChar d) fromEnum_0; foldr :: (b -> a -> a) -> a -> (List b) -> a; foldr f z Nil = z; foldr f z (Cons x xs) = f x (foldr f z xs); psPs :: (List a) -> (List a) -> (List a); psPs Nil ys = ys; psPs (Cons x xs) ys = Cons x (psPs xs ys); concat :: (List (List a)) -> (List a); concat = foldr psPs Nil; map :: (b -> a) -> (List b) -> (List a); map f Nil = Nil; map f (Cons x xs) = Cons (f x) (map f xs); pt :: (b -> a) -> (c -> b) -> c -> a; pt f g x = f (g x); concatMap :: (a -> (List b)) -> (List a) -> (List b); concatMap f = pt concat (map f); nonnull00 (Tup2 (Cons vy vz) t) = Cons (Tup2 (Cons vy vz) t) Nil; nonnull00 wu = Nil; nonnull0 vu68 = nonnull00 vu68; otherwise :: MyBool; otherwise = MyTrue; span2Span0 xx xy p wv ww MyTrue = Tup2 Nil (Cons wv ww); span2Vu43 xx xy = span xx xy; span2Ys0 xx xy (Tup2 ys wx) = ys; span2Ys xx xy = span2Ys0 xx xy (span2Vu43 xx xy); span2Zs0 xx xy (Tup2 wy zs) = zs; span2Zs xx xy = span2Zs0 xx xy (span2Vu43 xx xy); span2Span1 xx xy p wv ww MyTrue = Tup2 (Cons wv (span2Ys xx xy)) (span2Zs xx xy); span2Span1 xx xy p wv ww MyFalse = span2Span0 xx xy p wv ww otherwise; span2 p (Cons wv ww) = span2Span1 p ww p wv ww (p wv); span3 p Nil = Tup2 Nil Nil; span3 xv xw = span2 xv xw; span :: (a -> MyBool) -> (List a) -> Tup2 (List a) (List a); span p Nil = span3 p Nil; span p (Cons wv ww) = span2 p (Cons wv ww); nonnull :: (Char -> MyBool) -> (List Char) -> (List (Tup2 (List Char) (List Char))); nonnull p s = concatMap nonnull0 (Cons (span p s) Nil); foldl :: (b -> a -> b) -> b -> (List a) -> b; foldl f z Nil = z; foldl f z (Cons x xs) = foldl f (f z x) xs; foldl1 :: (a -> a -> a) -> (List a) -> a; foldl1 f (Cons x xs) = foldl f x xs; fromIntegerMyInt :: Integer -> MyInt fromIntegerMyInt (Integer x) = x; toIntegerMyInt :: MyInt -> Integer toIntegerMyInt x = Integer x; fromIntegral = pt fromIntegerMyInt toIntegerMyInt; primPlusInt :: MyInt -> MyInt -> MyInt; primPlusInt (Pos x) (Neg y) = primMinusNat x y; primPlusInt (Neg x) (Pos y) = primMinusNat y x; primPlusInt (Neg x) (Neg y) = Neg (primPlusNat x y); primPlusInt (Pos x) (Pos y) = Pos (primPlusNat x y); psMyInt :: MyInt -> MyInt -> MyInt psMyInt = primPlusInt; primMulNat :: Nat -> Nat -> Nat; primMulNat Zero Zero = Zero; primMulNat Zero (Succ y) = Zero; primMulNat (Succ x) Zero = Zero; primMulNat (Succ x) (Succ y) = primPlusNat (primMulNat x (Succ y)) (Succ y); primMulInt :: MyInt -> MyInt -> MyInt; primMulInt (Pos x) (Pos y) = Pos (primMulNat x y); primMulInt (Pos x) (Neg y) = Neg (primMulNat x y); primMulInt (Neg x) (Pos y) = Neg (primMulNat x y); primMulInt (Neg x) (Neg y) = Pos (primMulNat x y); srMyInt :: MyInt -> MyInt -> MyInt srMyInt = primMulInt; readInt0 radix n d = psMyInt (srMyInt n radix) d; readInt10 radix digToInt (Tup2 ds r) = Cons (Tup2 (foldl1 (readInt0 radix) (map (pt fromIntegral digToInt) ds)) r) Nil; readInt10 radix digToInt vv = Nil; readInt1 radix digToInt vu77 = readInt10 radix digToInt vu77; readInt radix isDig digToInt s = concatMap (readInt1 radix digToInt) (nonnull isDig s); readDecMyInt :: (List Char) -> (List (Tup2 MyInt (List Char))) readDecMyInt = readInt (fromIntMyInt (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))) isDigit readDec0;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/readDec_1.hs
mit
7,374
0
125
1,563
4,061
2,105
1,956
149
1
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module HgSpec (spec) where import Test.Hspec import Test.HUnit import Data.Time.LocalTime import Data.Time.Calendar import Hg import Str import TestUtil spec :: Spec spec = testUsualCommit testUsualCommit :: Spec testUsualCommit = it "parses usual commits" $ do let source = [strCrT| 2012-12-17 17:24 +0100 auth filtering --->>> _poc/helloplay/app/controllers/Global.scala _poc/helloplay/app/controllers/NeedSecured.scala _poc/helloplay/app/views/login.scala.html _poc/helloplay/conf/routes --->>> |] let expected = Commit { commitDate = LocalTime (fromGregorian 2012 12 17) (TimeOfDay 17 24 0), commitDesc = "auth filtering\n", commitFiles = ["_poc/helloplay/app/controllers/Global.scala", "_poc/helloplay/app/controllers/NeedSecured.scala", "_poc/helloplay/app/views/login.scala.html", "_poc/helloplay/conf/routes"] } testParsecExpectVal source parseCommit expected
emmanueltouzery/cigale-timesheet
tests/HgSpec.hs
mit
1,144
0
15
315
157
91
66
19
1
{- | Module : <File name or $Header$ to be replaced automatically> Description : <optional short text displayed on contents page> Copyright : (c) <Authors or Affiliations> License : <license> Maintainer : <email> Stability : unstable | experimental | provisional | stable | frozen Portability : portable | non-portable (<reason>) <module description starting at first column> -} module Main where -- Standard Library import Control.Applicative ((<$>)) import System.Environment (getEnv) -- Third Party --import Network.Wai.Middleware.RequestLogger (logStdoutDev) import Network.Wai.Middleware.Static (addBase, noDots, staticPolicy, (>->)) import Web.Scotty (middleware, scotty) -- Application import App (app) main :: IO () main = do port <- read <$> getEnv "PORT" scotty port $ do middleware $ staticPolicy (noDots >-> addBase "src/static/images") -- for favicon.ico --middleware logStdoutDev App.app
slogsdon/url
src/Main.hs
mit
1,177
0
14
395
141
82
59
13
1
module Frontend.Alpha (alpha) where import Control.Applicative import Control.Monad.Reader import Data.List import Data.Maybe import Data.Map (Map) import qualified Data.Map as M import Data.Bifunctor import Frontend.AST import Internal -- Alpha Transform alpha :: AlphaEnv -> AnnExpr -> Fresh AnnExpr alpha env = runAlpha env . alphaExpr type AlphaEnv = Map Name Name type Alpha a = ReaderT AlphaEnv Fresh a runAlpha :: AlphaEnv -> Alpha a -> Fresh a runAlpha = flip runReaderT withSubst :: [(Name, Name)] -> Alpha a -> Alpha a withSubst s = local $ flip (foldr $ uncurry M.insert) s replaceName :: Name -> Alpha Name replaceName name = asks $ fromMaybe name . M.lookup name alphaBinder :: (Name, t) -> Alpha (Maybe (Name, Name), (Name, t)) alphaBinder (name, t) = do name' <- flip rename name <$> fresh if name' == name then return $ (Nothing, (name, t)) else return $ (Just (name, name'), (name', t)) alphaExpr :: AnnExpr -> Alpha AnnExpr alphaExpr (AVar name ts) = flip AVar ts <$> replaceName name alphaExpr (AValue val) = return $ AValue val alphaExpr (AIf e1 e2 e3) = AIf <$> alphaExpr e1 <*> alphaExpr e2 <*> alphaExpr e3 alphaExpr (ALet d e) = do (s, d') <- alphaDecl d ALet d' <$> withSubst s (alphaExpr e) alphaExpr (AMatch e alts) = AMatch <$> alphaExpr e <*> mapM alphaAlt alts alphaExpr (AFun b e) = do (s, b') <- first maybeToList <$> alphaBinder b AFun b' <$> withSubst s (alphaExpr e) alphaExpr (AApply e1 e2) = AApply <$> alphaExpr e1 <*> alphaExpr e2 alphaExpr (AOp op es) = AOp op <$> mapM alphaExpr es alphaExpr (ACon con tcon ts es) = ACon con tcon ts <$> mapM alphaExpr es alphaExpr (ATuple es) = ATuple <$> mapM alphaExpr es alphaExpr (AExt s t names) = AExt s t <$> mapM replaceName names alphaDecl :: AnnDecl -> Alpha ([(Name, Name)], AnnDecl) alphaDecl (ARecDecl b e) = do (s, b') <- first maybeToList <$> alphaBinder b (,) s . ARecDecl b' <$> withSubst s (alphaExpr e) alphaDecl (ADecl b e) = do (s, b') <- first maybeToList <$> alphaBinder b (,) s . ADecl b' <$> alphaExpr e alphaDecl (ATupleDecl bs e) = do (s, bs') <- first catMaybes . unzip <$> mapM alphaBinder bs (,) s . ATupleDecl bs' <$> alphaExpr e alphaAlt :: AnnAlt -> Alpha AnnAlt alphaAlt (AConCase con tcon ts bs e) = do (s, bs') <- first catMaybes . unzip <$> mapM alphaBinder bs AConCase con tcon ts bs' <$> withSubst s (alphaExpr e) alphaAlt (ADefaultCase e) = ADefaultCase <$> alphaExpr e
alpicola/mel
src/Frontend/Alpha.hs
mit
2,453
0
11
493
1,097
548
549
66
2
import LList -- 1 : implement your own Eq typeclass class Eq_ a where (===) :: a -> a -> Bool x === y = not $ x /== y (/==) :: a -> a -> Bool x /== y = not $ x === y data BSTree k v = Empty | Node k v (BSTree k v) (BSTree k v) instance (Eq k, Eq v) => Eq_ (BSTree k v) where Empty === Empty = True (Node k1 v1) === (Node k2 v2) = (k1 == k2) -- 2 class Set s where empty :: s a add :: ( Eq a ) => a -> s a -> s a fold :: ( a -> b -> b ) -> b -> s a -> b union :: ( Eq a ) => s a -> s a -> s a remove :: ( Eq a ) => a -> s a -> s a member :: ( Eq a ) => a -> s a -> Bool size :: s a -> Int instance Set [] where empty = [] add x xs = if x `elem` xs then xs else x:xs fold = foldr union s1 s2 = fold add s1 s2 remove x s = fold (\x' s -> if x' /= x then s else x':s) empty s member x s = fold (\x' s -> s || x' == x) False s size = fold (\ _ i -> i + 1) 0 -- C'est mieux de mettre le plus d'implémentation dans le typeclass => cf solution instance Set LList where empty = smartLList [] -- 2 - 2e partie class (Eq a) => Set_ s a | s -> a where empty_ :: s add_ :: a -> s -> s fold_ :: ( a -> b -> b ) -> b -> s -> b union_ :: s -> s -> s remove_ :: a -> s -> s member_ :: a -> s -> Bool size_ :: s -> Int -- 3 data Scalar = Sc Int deriving Show data Vector = Vc Int Int Int deriving Show class Mult a b c | a b -> c where (*-*) :: a -> b -> c instance Mult Scalar Vector Vector where (Sc a) *-* (Vc x1 y1 z1) = Vc x y z where x = a * x1 y = a * y1 z = a * z1 instance Mult Vector Vector Vector where instance Mult Vector Vector Scalar where
t00n/ProjectEuler
TP5.hs
epl-1.0
1,700
0
10
585
839
441
398
-1
-1
-- Implicit CAD. Copyright (C) 2012, Christopher Olah ([email protected]) -- Released under the GNU GPL, see LICENSE module Graphics.Implicit.Export.Render.HandlePolylines (cleanLoopsFromSegs) where import Graphics.Implicit.Definitions cleanLoopsFromSegs :: [Polyline] -> [Polyline] cleanLoopsFromSegs = map reducePolyline . joinSegs . filter polylineNotNull joinSegs :: [Polyline] -> [Polyline] joinSegs [] = [] joinSegs (present:remaining) = let findNext ((p3:ps):segs) = if p3 == last present then (Just (p3:ps), segs) else if last ps == last present then (Just (reverse $ p3:ps), segs) else case findNext segs of (res1,res2) -> (res1,(p3:ps):res2) findNext [] = (Nothing, []) in case findNext remaining of (Nothing, _) -> present:(joinSegs remaining) (Just match, others) -> joinSegs $ (present ++ tail match): others reducePolyline ((x1,y1):(x2,y2):(x3,y3):others) = if (x1,y1) == (x2,y2) then reducePolyline ((x2,y2):(x3,y3):others) else if abs ( (y2-y1)/(x2-x1) - (y3-y1)/(x3-x1) ) < 0.0001 || ( (x2-x1) == 0 && (x3-x1) == 0 && (y2-y1)*(y3-y1) > 0) then reducePolyline ((x1,y1):(x3,y3):others) else (x1,y1) : reducePolyline ((x2,y2):(x3,y3):others) reducePolyline ((x1,y1):(x2,y2):others) = if (x1,y1) == (x2,y2) then reducePolyline ((x2,y2):others) else (x1,y1):(x2,y2):others reducePolyline l = l polylineNotNull (_:l) = not (null l) polylineNotNull [] = False {-cleanLoopsFromSegs = connectPolys -- . joinSegs . filter (not . degeneratePoly) polylinesFromSegsOnGrid = undefined degeneratePoly [] = True degeneratePoly [a,b] = a == b degeneratePoly _ = False data SegOrPoly = Seg (ℝ2) ℝ ℝ2 -- Basis, shift, interval | Poly [ℝ2] isSeg (Seg _ _ _) = True isSeg _ = False toSegOrPoly :: Polyline -> SegOrPoly toSegOrPoly [a, b] = Seg v (a⋅vp) (a⋅v, b⋅v) where v@(va, vb) = normalized (b ^-^ a) vp = (-vb, va) toSegOrPoly ps = Poly ps fromSegOrPoly :: SegOrPoly -> Polyline fromSegOrPoly (Seg v@(va,vb) s (a,b)) = [a*^v ^+^ t, b*^v ^+^ t] where t = s*^(-vb, va) fromSegOrPoly (Poly ps) = ps joinSegs :: [Polyline] -> [Polyline] joinSegs = map fromSegOrPoly . joinSegs' . map toSegOrPoly joinSegs' :: [SegOrPoly] -> [SegOrPoly] joinSegs' segsOrPolys = polys ++ concat (map joinAligned aligned) where polys = filter (not.isSeg) segsOrPolys segs = filter isSeg segsOrPolys aligned = groupWith (\(Seg basis p _) -> (basis,p)) segs joinAligned segs@((Seg b z _):_) = mergeAdjacent orderedSegs where orderedSegs = sortBy (\(Seg _ _ (a1,_)) (Seg _ _ (b1,_)) -> compare a1 b1) segs mergeAdjacent (pres@(Seg _ _ (x1a,x2a)) : next@(Seg _ _ (x1b,x2b)) : others) = if x2a == x1b then mergeAdjacent ((Seg b z (x1a,x2b)): others) else pres : mergeAdjacent (next : others) mergeAdjacent a = a joinAligned [] = [] connectPolys :: [Polyline] -> [Polyline] connectPolys [] = [] connectPolys (present:remaining) = let findNext (ps@(p:_):segs) = if p == last present then (Just ps, segs) else (a, ps:b) where (a,b) = findNext segs findNext [] = (Nothing, []) in case findNext remaining of (Nothing, _) -> present:(connectPolys remaining) (Just match, others) -> connectPolys $ (present ++ tail match): others -}
silky/ImplicitCAD
Graphics/Implicit/Export/Render/HandlePolylines.hs
gpl-2.0
3,454
0
17
806
715
400
315
29
5
module PresentationGen.Render ( htmlSlides, pandocToSlides ) where import Data.List import Data.Maybe import Data.String import Data.Monoid import Control.Monad import Text.Blaze import Text.Blaze.Html5 ( Html, toHtml, (!), toValue ) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Text.Pandoc import System.FilePath ( (</>), (<.>) ) import PresentationGen.Types import PresentationGen.Util htmlSlides :: SlideM Html htmlSlides = do title <- fromJust `fmap` getTitle authors <- getAuthors theme <- getTheme resourceDir <- getResourceDir -- titleSlide <- htmlTitleSlide slideHead <- htmlSlideHead slides <- slidesToHtml 2 return $H.docTypeHtml $ do slideHead H.body $ H.div ! A.class_ (toValue "reveal") $ H.div ! A.class_ (toValue "slides") $ do -- titleSlide slides jsFile $ resourceDir </> "lib/js/head.min.js" jsFile $ resourceDir </> "js/reveal.min.js" jsSource $ intercalate "\n" $ [ "Reveal.initialize({" , "controls: true," , "progress: true," , "history: true," , "center: true," , "theme: '" ++ theme ++ "'," , "transition: Reveal.getQueryHash().transition || 'default'," , "dependencies: [" , "{ src: '" ++ resourceDir </> "lib/js/classList.js', condition: function() { return !document.body.classList; } }," , "{ src: '" ++ resourceDir </> "plugin/markdown/showdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }," --, "{ src: '" ++ resourceDir </> "plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }," , "{ src: '" ++ resourceDir </> "plugin/highlight/highlight.pack.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }," , "{ src: '" ++ resourceDir </> "plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } }," , "{ src: '" ++ resourceDir </> "plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }" , "]" , "});" ] slidesToHtml :: Int -> SlideM Html slidesToHtml initialHeadLevel = do slides <- getSlides mapGenHtml (slideToHtml initialHeadLevel) slides where slideToHtml :: Int -> Slide -> SlideM Html slideToHtml hl (Slide t c subs) = do headContent <- inlinesToHtml t content <- blocksToHtml c subSlides <- mapGenHtml (slideToHtml $ hl + 1) subs return $ H.section $ do (if null subs then id else H.section) $ do H.h2 $ headContent content subSlides htmlSlideHead :: SlideM Html htmlSlideHead = do authors <- (map fst) `fmap` getAuthors title <- fromJust `fmap` getTitle theme <- getTheme resourceDir <- getResourceDir slideDir <- getSlideDir slideName <- getSlideName return $ H.head $ do -- Title H.title $ fromString title -- Charset H.meta ! A.charset (toValue "utf-8") -- Meta information metaTag "description" title metaTag "author" (intercalate ", " authors ) -- Apple specific metaTag "apple-mobile-web-app-capable" "yes" metaTag "apple-mobile-web-app-status-bar-style" "black-translucent" -- Viewport metaTag "viewport" "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" -- Reveal.js styles linkTag "stylesheet" $ resourceDir </> "css/reveal.min.css" linkTag "stylesheet" $ resourceDir </> "css/theme" </> theme <.>"css" -- Syntax highlight linkTag "stylesheet" $ resourceDir </> "lib/css/idea.css" {- Add at some point <!-- If the query includes 'print-pdf', use the PDF print sheet --> <script> document.write( '<link rel="stylesheet" href="css/print/' + ( window.location.search.match( /print-pdf/gi ) ? 'pdf' : 'paper' ) + '.css" type="text/css" media="print">' ); </script> <!--[if lt IE 9]> <script src="lib/js/html5shiv.js"></script> <![endif]--> -} -- Custom CSS linkTag "stylesheet" $ slideDir </> slideName <.> "css" htmlTitleSlide :: SlideM Html htmlTitleSlide = do title <- fromJust `fmap` getTitle authors <- map authorToHtml `fmap` getAuthors organisations <- getOrganisations return $ H.section $ do H.h1 $ fromString title H.p $ H.small $ do case length authors of 0 -> return () 1 -> sequence_ authors n -> do sequence_ (intersperse (fromString ", ") (init authors)) fromString " and " last authors seqMap orgToHtml organisations where authorToHtml :: (String, [Int]) -> Html authorToHtml (auth, []) = fromString auth authorToHtml (auth, assoc) = do fromString auth H.sup $ fromString $ intercalate "," $ map show assoc orgToHtml :: (Int, [String]) -> Html orgToHtml (n, org) = H.p $ H.small $ H.address $ do H.sup $ toHtml n sequence_ $ intersperse H.br $ map fromString org -- ----------------------------------------------------------------------- -- Pandoc to Html Translation -- ----------------------------------------------------------------------- pandocToSlides :: Pandoc -> [Slide] pandocToSlides (Pandoc _ bs) = parseSlides bs isHeader :: Int -> Block -> Bool isHeader n (Header m _ _) | n == m = True isHeader n _ = False parseSlides :: [Block] -> [Slide] parseSlides bs = let (_, headsConts) = groupSplit (isHeader 1) bs in fmap zipFunc headsConts where zipFunc :: (Block, [Block]) -> Slide zipFunc (Header n _ h, c) = let (cont, headsConts) = groupSplit (isHeader (n+1)) c in Slide h cont (fmap zipFunc headsConts) mapGenHtml :: (a -> SlideM Html) -> [a] -> SlideM Html mapGenHtml f l = mapM f l >>= foldM (\a b -> return $ a >> b) (return ()) blocksToHtml :: [Block] -> SlideM Html blocksToHtml = mapGenHtml blockToHtml blockToHtml :: Block -> SlideM Html blockToHtml b = case b of Header n _ t -> do content <- inlinesToHtml t return $ header n $ content Plain t -> inlinesToHtml t Para t -> do content <- inlinesToHtml t return $ H.p $ content BulletList l -> do content <- mapGenHtml listItem l return $ H.ul $ content OrderedList _atts l -> do content <- mapGenHtml listItem l return $ H.ol $ content CodeBlock (_, hClasses, _) c -> do return $ H.pre $ H.code ! A.class_ (toValue $ intercalate " " hClasses) $ toHtml c Null -> return $ return () HorizontalRule -> return $ H.hr RawBlock tag s -> return $ preEscapedToMarkup s Div attr content -> do let (ident, cls, _attrs) = attr innerHtml <- blocksToHtml content return $ H.div ! A.id (toValue ident) ! A.class_ (toValue $ intercalate " " cls) $ innerHtml -- TODO: Handle other cases. _ -> return $ mempty where listItem :: [Block] -> SlideM Html listItem i = do content <- blocksToHtml i return $ H.li $ content inlinesToHtml :: [Inline] -> SlideM Html inlinesToHtml = mapGenHtml inlineToHtml inlineToHtml :: Inline -> SlideM Html inlineToHtml l = case l of Str s -> return $ fromString s Space -> return $ fromString " " LineBreak -> return $ H.br Strong t -> do content <- inlinesToHtml t return $ H.strong $ content --Strikeout t -> do -- content <- inlinesToHtml t -- return $ H.strike $ content Superscript t -> do content <- inlinesToHtml t return $ H.sup $ content Subscript t -> do content <- inlinesToHtml t return $ H.sub $ content Emph t -> do content <- inlinesToHtml t return $ H.em $ content Code _ c -> return $ H.code $ fromString c RawInline _ s -> return $ preEscapedToMarkup s Image alt (url, t) -> do realUrl <- makeImageLink url return $ H.img ! A.alt (toValue $ concatMap inlineToString alt) ! A.src (toValue $ realUrl) ! A.title (toValue t) Link text (url, t) -> do content <- inlinesToHtml text return $ H.a ! A.href (toValue url) ! A.title (toValue t) $ content -- TODO: Handle other cases. _ -> return $ mempty inlineToString :: Inline -> String inlineToString l = case l of Str s -> s Emph t -> concatMap inlineToString t Space -> " " Code _ c -> c Image alt (url, t) -> url -- TODO: Handle other cases. _ -> "" makeImageLink :: String -> SlideM String makeImageLink img = do slideDir <- getSlideDir return $ if isExternalURI img then img else slideDir </> img -- ----------------------------------------------------------------------- -- Html Short-Cuts -- ----------------------------------------------------------------------- metaTag :: String -> String -> Html metaTag name content = H.meta ! A.name (toValue name) ! A.content (toValue content) linkTag :: String -> String -> Html linkTag rel href = H.link ! A.rel (toValue rel) ! A.href (toValue href) jsFile :: FilePath -> Html jsFile file = H.script ! A.type_ (toValue "text/javascript") ! A.src (toValue file) $ return () jsSource :: String -> Html jsSource src = H.script ! A.type_ (toValue "text/javascript") $ fromString src header :: Int -> Html -> Html header 1 = H.h1 header 2 = H.h2 header 3 = H.h3 header 4 = H.h4 header 5 = H.h5 header 6 = H.h6 header n = id
jbracker/presentation-gen
src/PresentationGen/Render.hs
gpl-2.0
9,567
0
22
2,407
2,763
1,360
1,403
222
12
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Flow.Action where import Autolib.TES.Identifier import Autolib.Symbol import Autolib.ToDoc import Autolib.Reader import Autolib.Size import Autolib.Hash -- | used in the alphabet for the automaton data Action = Execute Identifier | Halt deriving ( Eq, Ord ) $(derives [makeToDoc,makeReader] [''Action]) instance Symbol Action -- ? instance Size Action where size = const 1 instance Hash Action where hash a = case a of Execute i -> hash ( 42 :: Int, i ) Halt -> 24
Erdwolf/autotool-bonn
src/Flow/Action.hs
gpl-2.0
565
0
10
120
156
86
70
19
0
{- ********************************************************************** Whitespace - A language with no visible syntax. Copyright (C) 2003 Edwin Brady ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ********************************************************************** -} module Main where import Input import VM import Tokens import System.Environment(getArgs) main :: IO () main = do args <- getArgs if (length args)/=1 then usage else execute (head args) usage :: IO () usage = do putStrLn "wspace 0.4 (c) 2003 Edwin Brady" putStrLn "-------------------------------" putStrLn "Usage: wspace [file]"
haroldl/whitespace-nd
main.hs
gpl-2.0
1,372
2
10
298
111
57
54
16
2
{-# LANGUAGE DeriveDataTypeable, TypeSynonymInstances #-} {- Copyright (C) 2009 John MacFarlane <[email protected]> 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 -} {- | Types for representing a structured formula. -} module Text.TeXMath.Types (Exp(..), TeXSymbolType(..), ArrayLine, FractionType(..), TextType(..), Alignment(..), DisplayType(..), Operator(..), FormType(..), Record(..), Property, Position(..), Env, defaultEnv, InEDelimited) where import Data.Generics data TeXSymbolType = Ord | Op | Bin | Rel | Open | Close | Pun | Accent | Fence | TOver | TUnder | Alpha | BotAccent | Rad deriving (Show, Read, Eq, Data, Typeable) data Alignment = AlignLeft | AlignCenter | AlignRight | AlignDefault deriving (Show, Read, Eq, Data, Typeable) data FractionType = NormalFrac -- ^ Displayed or textual, acc to 'DisplayType' | DisplayFrac -- ^ Force display mode | InlineFrac -- ^ Force inline mode (textual) | NoLineFrac -- ^ No line between top and bottom deriving (Show, Read, Eq, Data, Typeable) type ArrayLine = [[Exp]] data Exp = ENumber String -- ^ A number (@\<mn\>@ in MathML). | EGrouped [Exp] -- ^ A group of expressions that function as a unit -- (e.g. @{...}@) in TeX, @\<mrow\>...\</mrow\>@ in MathML. | EDelimited String String [InEDelimited] -- ^ A group of expressions inside -- paired open and close delimiters (which may in some -- cases be null). | EIdentifier String -- ^ An identifier, e.g. a variable (@\<mi\>...\</mi\>@ -- in MathML. Note that MathML tends to use @\<mi\>@ tags -- for "sin" and other mathematical operators; these -- are represented as 'EMathOperator' in TeXMath. | EMathOperator String -- ^ A spelled-out operator like @lim@ or @sin@. | ESymbol TeXSymbolType String -- ^ A symbol. | ESpace Rational -- ^ A space, with the width specified in em. | ESub Exp Exp -- ^ An expression with a subscript. First argument is base, -- second subscript. | ESuper Exp Exp -- ^ An expresion with a superscript. First argument is base, -- second subscript. | ESubsup Exp Exp Exp -- ^ An expression with both a sub and a superscript. -- First argument is base, second subscript, third -- superscript. | EOver Bool Exp Exp -- ^ An expression with something over it. -- The first argument is True if the formula is -- "convertible:" that is, if the material over the -- formula should appear as a regular superscript in -- inline math. The second argument is the base, -- the third the expression that goes over it. | EUnder Bool Exp Exp -- ^ An expression with something under it. -- The arguments work as in @EOver@. | EUnderover Bool Exp Exp Exp -- ^ An expression with something over and -- something under it. | EPhantom Exp -- ^ A "phantom" operator that takes space but doesn't display. | EBoxed Exp -- ^ A boxed expression. | EFraction FractionType Exp Exp -- ^ A fraction. First argument is -- numerator, second denominator. | ERoot Exp Exp -- ^ An nth root. First argument is index, second is base. | ESqrt Exp -- ^ A square root. | EScaled Rational Exp -- ^ An expression that is scaled to some factor -- of its normal size. | EArray [Alignment] [ArrayLine] -- ^ An array or matrix. The first argument -- specifies the alignments of the columns; the second gives -- the contents of the lines. All of these lists should be -- the same length. | EText TextType String -- ^ Some normal text, possibly styled. | EStyled TextType [Exp] -- ^ A group of styled expressions. deriving (Show, Read, Eq, Data, Typeable) -- | An @EDelimited@ element contains a string of ordinary expressions -- (represented here as @Right@ values) or fences (represented here as -- @Left@, and in LaTeX using @\mid@). type InEDelimited = Either Middle Exp type Middle = String data DisplayType = DisplayBlock -- ^ A displayed formula. | DisplayInline -- ^ A formula rendered inline in text. deriving (Show, Eq) data TextType = TextNormal | TextBold | TextItalic | TextMonospace | TextSansSerif | TextDoubleStruck | TextScript | TextFraktur | TextBoldItalic | TextSansSerifBold | TextSansSerifBoldItalic | TextBoldScript | TextBoldFraktur | TextSansSerifItalic deriving (Show, Ord, Read, Eq, Data, Typeable) data FormType = FPrefix | FPostfix | FInfix deriving (Show, Ord, Eq) type Property = String -- | A record of the MathML dictionary as defined -- <http://www.w3.org/TR/MathML3/appendixc.html in the specification> data Operator = Operator { oper :: String -- ^ Operator , description :: String -- ^ Plain English Description , form :: FormType -- ^ Whether Prefix, Postfix or Infix , priority :: Int -- ^ Default priority for implicit -- nesting , lspace :: Int -- ^ Default Left Spacing , rspace :: Int -- ^ Default Right Spacing , properties :: [Property] -- ^ List of MathML properties } deriving (Show) -- | A record of the Unicode to LaTeX lookup table -- a full descripton can be seen -- <http://milde.users.sourceforge.net/LUCR/Math/data/unimathsymbols.txt -- here> data Record = Record { uchar :: Char -- ^ Unicode Character , commands :: [(String, String)] -- ^ LaTeX commands (package, command) , category :: TeXSymbolType -- ^ TeX math category , comments :: String -- ^ Plain english description } deriving (Show) data Position = Under | Over -- | List of available packages type Env = [String] -- | Contains @amsmath@ and @amssymbol@ defaultEnv :: [String] defaultEnv = ["amsmath", "amssymb"]
beni55/texmath
src/Text/TeXMath/Types.hs
gpl-2.0
7,289
0
10
2,336
821
530
291
83
1
-- grid is a game written in Haskell -- Copyright (C) 2018 [email protected] -- -- This file is part of grid. -- -- grid is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- grid 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 grid. If not, see <http://www.gnu.org/licenses/>. -- module Game.Data.Shape ( Shape (..), shapeOfSize, ) where import MyPrelude data Shape = Shape !Float !Float deriving Eq shapeOfSize :: UInt -> UInt -> Shape shapeOfSize wth hth = let a = 1.0 / fI (max wth hth) in Shape (a * fI wth) (a * fI hth)
karamellpelle/grid
designer/source/Game/Data/Shape.hs
gpl-3.0
1,028
0
12
218
131
78
53
16
1
module Data.Rhythm.FeedBack.Show (toFile, showFile, showValue) where import Data.Rhythm.FeedBack import qualified Data.EventList.Relative.TimeBody as RTB import qualified Data.EventList.Absolute.TimeBody as ATB import Data.Rhythm.Time import Data.Rhythm.Event toFile :: FilePath -> File Ticks Ticks -> IO () toFile fp db = writeFile fp $ showFile db "" showFile :: File Ticks Ticks -> ShowS showFile (File son syn chs) = showSongChunk son . showEventChunk "SyncTrack" syn . compose (map (uncurry showEventChunk) chs) compose :: [a -> a] -> a -> a compose = foldr (.) id startChunk :: String -> ShowS startChunk str onto = "[" ++ str ++ "]\n{\n" ++ onto showLine :: Value -> [Value] -> ShowS showLine lhs rhs onto = concat ["\t", showValue lhs, " = ", unwords (map showValue rhs), "\n", onto] endChunk :: ShowS endChunk onto = "}\n" ++ onto showSongChunk :: [(String, Value)] -> ShowS showSongChunk chunk = startChunk "Song" . compose (map f chunk) . endChunk where f (str, val) = showLine (Ident str) [val] showEventChunk :: String -> RTB.T Ticks (T Ticks) -> ShowS showEventChunk name chunk = startChunk name . middle . endChunk where middle = compose $ map f $ ATB.toPairList $ RTB.toAbsoluteEventList 0 chunk f (Ticks tks, evt) = showLine (Int tks) $ case evt of Length (Ticks len) d -> case d of Note fret -> [Ident "N", Int fret, Int len] Stream strType -> [Ident "S", Int strType, Int len] Point p -> case p of BPM (Beats bps) -> [Ident "B", Int $ floor $ bps * 60000] Anchor (Seconds secs) -> [Ident "A", Int $ floor $ secs * 1000000] TimeSig i -> [Ident "TS", Int i] EventGlobal str -> [Ident "E", Quoted str] EventLocal str -> [Ident "E", Ident str] showValue :: Value -> String showValue (Int i) = show i showValue (Real r) = show (realToFrac r :: Double) showValue (Quoted s) = show s showValue (Ident s) = s
mtolly/rhythm
src/Data/Rhythm/FeedBack/Show.hs
gpl-3.0
1,894
0
17
387
806
415
391
43
7
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE StandaloneDeriving #-} module Config where import Data.Data import Data.Default import System.Log.Logger (Priority(..)) data Config = Config { logPriority :: Priority , movementUpdateFrequency :: Double , regenerationUpdateFrequency :: Double , arenaWidth :: Int , arenaHeight :: Int , serverPort :: Int , wsServerPort :: Int , shipRadius :: Double , shipScanRange :: Double , shipShootRange :: Double , shipSpeed :: Double , shipSpeedWithBoost :: Double , shipDamage :: Int , shipDamageWithShields :: Int , shipStartingEnergy :: Int , shipStartingHealth :: Int , shipMaxEnergy :: Int , shipMaxHealth :: Int , shipEnergyRegen :: Int , shipShieldEnergyCost :: Int , shipBoostEnergyCost :: Int , shipHealthRegen :: Int , scanCost :: Int , turnCost :: Int , shootCost :: Int } deriving (Data, Typeable) deriving instance Data Priority deriving instance Typeable Priority instance Default Config where def = Config { logPriority = INFO , movementUpdateFrequency = 10 , regenerationUpdateFrequency = 10 , arenaWidth = 256 , arenaHeight = 256 , serverPort = 1337 , wsServerPort = 1338 , shipRadius = 8 , shipScanRange = 32 , shipShootRange = 64 , shipSpeed = 32 , shipSpeedWithBoost = 64 , shipDamage = 50 , shipDamageWithShields = 25 , shipStartingEnergy = 25 , shipStartingHealth = 75 , shipMaxEnergy = 100 , shipMaxHealth = 100 , shipEnergyRegen = 1 , shipShieldEnergyCost = 1 , shipBoostEnergyCost = 1 , shipHealthRegen = 2 , scanCost = 5 , turnCost = 5 , shootCost = 20 }
dflemstr/ship
Config.hs
gpl-3.0
1,690
0
8
412
382
248
134
64
0
{-# LANGUAGE OverloadedStrings #-} import SequenceFormats.FreqSum (FreqSumEntry(..), FreqSumHeader(..), readFreqSumStdIn, printFreqSumStdOut) import Control.Error (runScript, tryJust) import Data.List.Split (splitOn) import Data.Monoid ((<>)) import Data.Text (pack) import Data.Version (showVersion) import qualified Options.Applicative as OP import Pipes ((>->), runEffect) import qualified Pipes.Prelude as P import Turtle (format, s, (%)) import Paths_rarecoal_tools (version) data MyOpts = MyOpts [String] main :: IO () main = OP.execParser opts >>= runWithOptions where opts = OP.info (OP.helper <*> parser) (OP.progDesc ("selectInFreqSum version " ++ showVersion version ++ ": a tool to select columns from a freqSum file, read from stdin")) parser :: OP.Parser MyOpts parser = MyOpts <$> OP.option (splitOn "," <$> OP.str) (OP.short 'n' <> OP.long "names" <> OP.metavar "NAME1,NAME2,..." <> OP.help "comma-separated list of names to select") runWithOptions :: MyOpts -> IO () runWithOptions (MyOpts names) = runScript $ do (FreqSumHeader oldNames oldCounts, entries) <- readFreqSumStdIn indices <- mapM (findIndex oldNames) (map pack names) let newEntries = entries >-> P.map (selectColumns indices) -- >-> P.filter ((>0) . sum . catMaybes . fsCounts) newCounts = map (oldCounts!!) indices newHeader = FreqSumHeader (map pack names) newCounts runEffect $ newEntries >-> printFreqSumStdOut newHeader where findIndex xs x = tryJust (format ("could not find name: "%s) x) $ x `lookup` zip xs [0..] selectColumns :: [Int] -> FreqSumEntry -> FreqSumEntry selectColumns indices fs = let newCounts = map ((fsCounts fs) !!) indices in fs {fsCounts = newCounts}
stschiff/rarecoal-tools
src-selectInFreqSum/selectInFreqSum.hs
gpl-3.0
1,774
0
14
339
547
297
250
35
1
module Types ( Note(..) , NoteId , NoteSignature(..) , noteIdToText , ApplicationResult(..) , Verbosity(..) ) where import Data.Aeson import Data.Aeson.Types import Data.Text (Text) import Data.Time.Clock (UTCTime) import Data.Time.Format import Database.SQLite.Simple import Database.SQLite.Simple.FromField import Database.SQLite.Simple.ToField -- * NoteId newtype NoteId = NoteId Text deriving (Eq, Ord, FromField, FromJSON, ToField) noteIdToText :: NoteId -> Text noteIdToText (NoteId t) = t -- * Note data Note = Note { note_id :: NoteId , note_title :: Text , note_text :: Text , note_hash :: Text , note_created :: Text , note_updated :: Text } instance ToRow Note where toRow (Note n_id n_title n_text n_hash n_created n_updated) = toRow (n_id, n_title, n_text, n_hash, n_created, n_updated) instance FromJSON Note where parseJSON (Object o) = Note <$> o .: "id" <*> o .: "title" <*> o .: "text" <*> o .: "hash" <*> o .: "created_at" <*> o .: "updated_at" parseJSON other = typeMismatch "Note" other -- * NoteSignature data NoteSignature = NoteSignature { ns_id :: NoteId , ns_updated :: UTCTime } instance FromJSON NoteSignature where parseJSON (Object o) = NoteSignature <$> o .: "id" <*> (o .: "updated_at" >>= timeFromString) where timeFromString = parseTimeM False defaultTimeLocale "%Y-%m-%d %H:%M:%S" parseJSON other = typeMismatch "NoteSignature" other -- * ApplicationResult -- | Structure describing how many notes were updated, newly added, deleted, and already up to date, -- respectively. data ApplicationResult = ApplicationResult Int Int Int Int -- * Verbosity data Verbosity = Verbose | Standard deriving (Eq)
bdesham/pinboard-notes-backup
src/Types.hs
gpl-3.0
2,162
0
17
767
465
268
197
47
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-| Export the StoneEdge Import XML for an Order. -} import Control.Monad (forM) import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (runNoLoggingT) import Data.Maybe (mapMaybe) import Data.Monoid ((<>)) import Data.Time (utcToLocalTime, getTimeZone) import Database.Persist import Database.Persist.Postgresql ( ConnectionPool, SqlPersistT, createPostgresqlPool, runSqlPool ) import System.Environment (getArgs) import System.Exit (exitFailure) import Text.Read (readMaybe) import Models import Models.Fields import Routes.StoneEdge import StoneEdge import qualified Data.ByteString as BS import qualified Database.Esqueleto as E main :: IO () main = do args <- getArgs case mapMaybe (fmap E.toSqlKey . readMaybe) args of [] -> do putStrLn "Expected at least 1 argument: ORDER_ID [... ORDER_ID]" exitFailure orderIds -> do let idString = show $ map E.fromSqlKey orderIds putStrLn "Connecting to Database" psql <- connectToPostgres putStrLn $ "Fetching Orders Numbers: " <> idString orders <- flip runSqlPool psql $ fetchOrder orderIds putStrLn $ "Writing Order XML to ./order-export.xml" BS.writeFile "order-export.xml" . renderDownloadOrdersResponse $ DownloadOrdersResponse orders putStrLn "Script Completed Successfully!" connectToPostgres :: IO ConnectionPool connectToPostgres = runNoLoggingT $ createPostgresqlPool "dbname=sese-website" 1 -- | Ripped from Routes.StoneEdge.downloadOrdersRoute fetchOrder :: [OrderId] -> SqlPersistT IO [StoneEdgeOrder] fetchOrder orderIds = do orders <- E.select $ E.from $ \(o `E.InnerJoin` c `E.InnerJoin` sa `E.LeftOuterJoin` ba `E.LeftOuterJoin` cp) -> do E.on (o E.^. OrderCouponId E.==. cp E.?. CouponId) E.on (o E.^. OrderBillingAddressId E.==. ba E.?. AddressId) E.on (o E.^. OrderShippingAddressId E.==. sa E.^. AddressId) E.on (o E.^. OrderCustomerId E.==. c E.^. CustomerId) E.where_ $ o E.^. OrderId `E.in_` E.valList orderIds E.orderBy [E.asc $ o E.^. OrderId] return (o, c, sa, ba, cp) orderData <- forM orders $ \(o, c, sa, ba, cp) -> do createdAt <- convertToLocalTime $ orderCreatedAt $ entityVal o adminComments <- forM (orderAdminComments $ entityVal o) $ \comment -> (adminCommentContent comment,) <$> convertToLocalTime (adminCommentTime comment) lineItems <- selectList [OrderLineItemOrderId ==. entityKey o] [] products <- E.select $ E.from $ \(op `E.InnerJoin` v `E.InnerJoin` p) -> do E.on (v E.^. ProductVariantProductId E.==. p E.^. ProductId) E.on (op E.^. OrderProductProductVariantId E.==. v E.^. ProductVariantId) E.where_ $ op E.^. OrderProductOrderId E.==. E.val (entityKey o) return (op, p, v) return (o, createdAt, c, sa, ba, cp, lineItems, products, adminComments) return $ map transformOrder orderData where convertToLocalTime utcTime = do timeZone <- liftIO $ getTimeZone utcTime return $ utcToLocalTime timeZone utcTime
Southern-Exposure-Seed-Exchange/southernexposure.com
server/scripts/ExportStoneEdgeXML.hs
gpl-3.0
3,293
0
21
784
975
506
469
67
2
{-# LANGUAGE ViewPatterns #-} module Utils.Mutation where import Prelude hiding (null) import Data.Maybe import Data.ByteString.Lazy import Control.DeepSeq import Control.Monad import System.Random (randomIO) import Test.QuickCheck.Random (mkQCGen) import Test.QuickCheck.Gen import Test.QuickFuzz.Gen.FormatInfo import Args import Debug import Exception import System.Directory hiding (listDirectory, withCurrentDirectory) import Control.Exception ( bracket ) import Test.QuickCheck.Random (mkQCGen) import Test.QuickCheck.Gen import System.Random (randomIO) sampleGenerator gen n seed = let baseGen = resize n gen baseVal = unGen baseGen (mkQCGen seed) seed in baseVal -- Mutatue a reproductible value, retrying when the generated value fails to -- enconde strictMutate :: (Show base, NFData base) => QFCommand -> FormatInfo base actions -> [base] -> Int -> IO (ByteString, Int) strictMutate cmd fmt values n = do seed <- if usesSeed cmd then return (fromJust (genSeed cmd)) else abs <$> randomIO idx <- return $ (seed `mod` (Prelude.length values)) value <- return (values !! idx) --print value -- Mutate some value. mutated <- return $ sampleGenerator ((mutate fmt) value) n seed if ( show value == show mutated ) then strictMutate cmd fmt values n else ( do bsnf <- forceEvaluation (encode fmt mutated) case bsnf of Nothing -> do debug "Encoding failure" when (usesSeed cmd) (error "given seed raised an encoding error. Aborting") strictMutate cmd fmt values n Just (null -> True) -> do debug "Empty generation" when (usesSeed cmd) (error "given seed raised an encoding error. Aborting") strictMutate cmd fmt values n Just encoded -> do --debug (show val) return (encoded, seed) )
CIFASIS/QuickFuzz
app/Utils/Mutation.hs
gpl-3.0
2,101
0
18
657
541
283
258
49
5
module HEP.Jet.FastJet.Class.ClusterSequenceWithArea where
wavewave/HFastJet
oldsrc/HEP/Jet/FastJet/Class/ClusterSequenceWithArea.hs
lgpl-2.1
60
0
3
4
9
7
2
1
0
{-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} {- Copyright [2014] Tim Dysinger 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. -} import Haste import Haste.Foreign data AmazonWebServices a b where AWS :: a -> b -> AmazonWebServices a b data ElasticComputeCloud a b where EC2 :: a -> b -> ElasticComputeCloud a b data SimpleStorageService a b where S3 :: a -> b -> SimpleStorageService a b class Monad m => AmazonWebServicesAPI a b m where aws :: a -> m (AmazonWebServices a b) class Monad m => ElasticComputeCloudAPI a b m where ec2 :: AmazonWebServices a b -> m (ElasticComputeCloud a b) describeInstances :: ElasticComputeCloud a b -> m () class Monad m => SimpleStorageServiceAPI a b m where s3 :: AmazonWebServices a b -> m (SimpleStorageService a b) listBuckets :: SimpleStorageService a b -> m () ---------------- -- JAVASCRIPT -- ---------------- data JavaScript where JS :: JavaScript type Ptr = Unpacked js :: String -> IO Ptr js f = ffi (toJSString f) >>= return . fromOpaque js1_ :: String -> Ptr -> IO () js1_ f = ffi (toJSString f) . toOpaque js1 :: String -> Ptr -> IO Ptr js1 f j = ffi (toJSString f) (toOpaque j) >>= return . fromOpaque js2_ :: String -> Ptr -> Ptr -> IO () js2_ f j0 j1 = ffi (toJSString f) (toOpaque j0) (toOpaque j1) js2 :: String -> Ptr -> Ptr -> IO Ptr js2 f j0 j1 = ffi (toJSString f) (toOpaque j0) (toOpaque j1) >>= return . fromOpaque instance AmazonWebServicesAPI JavaScript Ptr IO where aws JS = js "(function(){return require('aws-sdk');});" >>= return . AWS JS instance ElasticComputeCloudAPI JavaScript Ptr IO where ec2 (AWS JS j) = js1 "(function(x){return new x.EC2();});" j >>= return . EC2 JS describeInstances (EC2 JS j) = js1_ "(function(x){x.describeInstances().on('success',function(r){console.log(r.data);}).on('error',function(r){console.log('ERR',r.error);}).send();});" j instance SimpleStorageServiceAPI JavaScript Ptr IO where s3 (AWS JS j) = js1 "(function(x){return new x.S3();});" j >>= return . S3 JS listBuckets (S3 JS j) = js1_ "(function(x){x.listBuckets().on('success',function(r){console.log(r.data);}).on('error',function(r){console.log('ERR',r.error);}).send();});" j ---------- -- DEMO -- ---------- main :: IO () main = do amz <- aws JS :: IO (AmazonWebServices JavaScript Ptr) amzEc2 <- ec2 amz :: IO (ElasticComputeCloud JavaScript Ptr) amzS3 <- s3 amz :: IO (SimpleStorageService JavaScript Ptr) describeInstances amzEc2 listBuckets amzS3
dysinger/khartes
Main.hs
apache-2.0
3,062
0
10
570
788
392
396
48
1
{-| Data.Text instances for cereal. Provides instances for Text and lazy Text -} module Data.Serialize.Text () where import qualified Data.Text as T import qualified Data.Text.Lazy as LT import qualified Data.Text.Encoding as TE import qualified Data.Text.Lazy.Encoding as TLE import Data.Serialize import Control.Applicative ((<$>)) instance Serialize T.Text where put = put . TE.encodeUtf8 get = TE.decodeUtf8 <$> get instance Serialize LT.Text where put = put . TLE.encodeUtf8 get = TLE.decodeUtf8 <$> get
ulikoehler/cereal-text
Data/Serialize/Text.hs
apache-2.0
538
0
7
99
128
81
47
13
0
module PowerDivisibility.A254767 (a254767) where import PowerDivisibility.A048798 (a048798) import Data.Maybe (fromJust) import Data.List (find) a254767 :: Integer -> Integer a254767 n = k * fromJust (find (\j -> n < k * j) cubes) where k = a048798 n cubes = map (^3) [1..]
peterokagey/haskellOEIS
src/PowerDivisibility/A254767.hs
apache-2.0
279
0
12
48
116
65
51
8
1
-- | Tiny DSL for finding a path from the current path. {-# LANGUAGE LambdaCase, PackageImports #-} module System.Directory.PathFinder where import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.Maybe import Control.Monad.Trans.State import Data.List import "list-t" ListT (ListT) import System.Directory import System.FilePath import qualified "list-t" ListT type PathFinder = StateT FilePath (MaybeT IO) () type MultiPathFinder = StateT FilePath (ListT IO) () runPathFinder :: PathFinder -> FilePath -> IO (Maybe FilePath) runPathFinder p pwd = runMaybeT (execStateT p pwd) runMultiPathFinder :: MultiPathFinder -> FilePath -> IO [FilePath] runMultiPathFinder p pwd = ListT.toList (execStateT p pwd) filenameIs :: MonadPlus m => String -> StateT FilePath m () filenameIs s = do pwd <- get guard (takeFileName pwd == s) filenameMatches :: MonadPlus m => String -> String -> StateT FilePath m () filenameMatches prefix suffix = do pwd <- get guard (prefix `isPrefixOf` pwd && suffix `isSuffixOf` pwd) hasAncestor :: MonadPlus m => String -> StateT FilePath m () hasAncestor s = do pwd <- get guard (s `elem` splitDirectories pwd) relativePath :: (MonadIO m, MonadPlus m) => FilePath -> StateT FilePath m () relativePath rel = do pwd <- get let pwd' = pwd </> rel exists <- liftIO $ doesDirectoryExist pwd' guard exists pwd'' <- liftIO $ canonicalizePath pwd' put pwd'' someChild :: MultiPathFinder someChild = do pwd <- get childs <- liftIO $ getDirectoryContents pwd child <- lift $ ListT.fromFoldable childs put (pwd </> child)
gelisam/hawk
src/System/Directory/PathFinder.hs
apache-2.0
1,662
0
11
310
544
277
267
44
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGridLayout_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QGridLayout_h where import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QGridLayout ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGridLayout_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QGridLayout_unSetUserMethod" qtc_QGridLayout_unSetUserMethod :: Ptr (TQGridLayout a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QGridLayoutSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGridLayout_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QGridLayout ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGridLayout_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QGridLayoutSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGridLayout_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QGridLayout ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGridLayout_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QGridLayoutSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGridLayout_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QGridLayout ()) (QGridLayout x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QGridLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QGridLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QGridLayout_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setUserMethod" qtc_QGridLayout_setUserMethod :: Ptr (TQGridLayout a) -> CInt -> Ptr (Ptr (TQGridLayout x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QGridLayout :: (Ptr (TQGridLayout x0) -> IO ()) -> IO (FunPtr (Ptr (TQGridLayout x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QGridLayout_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QGridLayoutSc a) (QGridLayout x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QGridLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QGridLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QGridLayout_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QGridLayout ()) (QGridLayout x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QGridLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QGridLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QGridLayout_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setUserMethodVariant" qtc_QGridLayout_setUserMethodVariant :: Ptr (TQGridLayout a) -> CInt -> Ptr (Ptr (TQGridLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QGridLayout :: (Ptr (TQGridLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGridLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QGridLayout_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QGridLayoutSc a) (QGridLayout x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QGridLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QGridLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QGridLayout_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QGridLayout ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QGridLayout_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QGridLayout_unSetHandler" qtc_QGridLayout_unSetHandler :: Ptr (TQGridLayout a) -> CWString -> IO (CBool) instance QunSetHandler (QGridLayoutSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QGridLayout_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler1" qtc_QGridLayout_setHandler1 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout1 :: (Ptr (TQGridLayout x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGridLayout x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qcount_h (QGridLayout ()) (()) where count_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_count cobj_x0 foreign import ccall "qtc_QGridLayout_count" qtc_QGridLayout_count :: Ptr (TQGridLayout a) -> IO CInt instance Qcount_h (QGridLayoutSc a) (()) where count_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_count cobj_x0 instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> IO (Orientations)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (CLong) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler2" qtc_QGridLayout_setHandler2 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> IO (CLong)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout2 :: (Ptr (TQGridLayout x0) -> IO (CLong)) -> IO (FunPtr (Ptr (TQGridLayout x0) -> IO (CLong))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> IO (Orientations)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (CLong) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QexpandingDirections_h (QGridLayout ()) (()) where expandingDirections_h x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_expandingDirections cobj_x0 foreign import ccall "qtc_QGridLayout_expandingDirections" qtc_QGridLayout_expandingDirections :: Ptr (TQGridLayout a) -> IO CLong instance QexpandingDirections_h (QGridLayoutSc a) (()) where expandingDirections_h x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_expandingDirections cobj_x0 instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler3" qtc_QGridLayout_setHandler3 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout3 :: (Ptr (TQGridLayout x0) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGridLayout x0) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QhasHeightForWidth_h (QGridLayout ()) (()) where hasHeightForWidth_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_hasHeightForWidth cobj_x0 foreign import ccall "qtc_QGridLayout_hasHeightForWidth" qtc_QGridLayout_hasHeightForWidth :: Ptr (TQGridLayout a) -> IO CBool instance QhasHeightForWidth_h (QGridLayoutSc a) (()) where hasHeightForWidth_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_hasHeightForWidth cobj_x0 instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler4" qtc_QGridLayout_setHandler4 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout4 :: (Ptr (TQGridLayout x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQGridLayout x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QheightForWidth_h (QGridLayout ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QGridLayout_heightForWidth" qtc_QGridLayout_heightForWidth :: Ptr (TQGridLayout a) -> CInt -> IO CInt instance QheightForWidth_h (QGridLayoutSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_heightForWidth cobj_x0 (toCInt x1) instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler5" qtc_QGridLayout_setHandler5 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout5 :: (Ptr (TQGridLayout x0) -> IO ()) -> IO (FunPtr (Ptr (TQGridLayout x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QGridLayout5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qinvalidate_h (QGridLayout ()) (()) where invalidate_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_invalidate cobj_x0 foreign import ccall "qtc_QGridLayout_invalidate" qtc_QGridLayout_invalidate :: Ptr (TQGridLayout a) -> IO () instance Qinvalidate_h (QGridLayoutSc a) (()) where invalidate_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_invalidate cobj_x0 instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> Int -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler6" qtc_QGridLayout_setHandler6 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout6 :: (Ptr (TQGridLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0))) -> IO (FunPtr (Ptr (TQGridLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0)))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> Int -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QitemAt_h (QGridLayout ()) ((Int)) where itemAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_itemAt cobj_x0 (toCInt x1) foreign import ccall "qtc_QGridLayout_itemAt" qtc_QGridLayout_itemAt :: Ptr (TQGridLayout a) -> CInt -> IO (Ptr (TQLayoutItem ())) instance QitemAt_h (QGridLayoutSc a) ((Int)) where itemAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_itemAt cobj_x0 (toCInt x1) instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler7" qtc_QGridLayout_setHandler7 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout7 :: (Ptr (TQGridLayout x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQGridLayout x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqmaximumSize_h (QGridLayout ()) (()) where qmaximumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_maximumSize cobj_x0 foreign import ccall "qtc_QGridLayout_maximumSize" qtc_QGridLayout_maximumSize :: Ptr (TQGridLayout a) -> IO (Ptr (TQSize ())) instance QqmaximumSize_h (QGridLayoutSc a) (()) where qmaximumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_maximumSize cobj_x0 instance QmaximumSize_h (QGridLayout ()) (()) where maximumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_maximumSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QGridLayout_maximumSize_qth" qtc_QGridLayout_maximumSize_qth :: Ptr (TQGridLayout a) -> Ptr CInt -> Ptr CInt -> IO () instance QmaximumSize_h (QGridLayoutSc a) (()) where maximumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_maximumSize_qth cobj_x0 csize_ret_w csize_ret_h instance QminimumHeightForWidth_h (QGridLayout ()) ((Int)) where minimumHeightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_minimumHeightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QGridLayout_minimumHeightForWidth" qtc_QGridLayout_minimumHeightForWidth :: Ptr (TQGridLayout a) -> CInt -> IO CInt instance QminimumHeightForWidth_h (QGridLayoutSc a) ((Int)) where minimumHeightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_minimumHeightForWidth cobj_x0 (toCInt x1) instance QqminimumSize_h (QGridLayout ()) (()) where qminimumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_minimumSize cobj_x0 foreign import ccall "qtc_QGridLayout_minimumSize" qtc_QGridLayout_minimumSize :: Ptr (TQGridLayout a) -> IO (Ptr (TQSize ())) instance QqminimumSize_h (QGridLayoutSc a) (()) where qminimumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_minimumSize cobj_x0 instance QminimumSize_h (QGridLayout ()) (()) where minimumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_minimumSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QGridLayout_minimumSize_qth" qtc_QGridLayout_minimumSize_qth :: Ptr (TQGridLayout a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSize_h (QGridLayoutSc a) (()) where minimumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_minimumSize_qth cobj_x0 csize_ret_w csize_ret_h instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> QRect t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQRect t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler8" qtc_QGridLayout_setHandler8 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> Ptr (TQRect t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout8 :: (Ptr (TQGridLayout x0) -> Ptr (TQRect t1) -> IO ()) -> IO (FunPtr (Ptr (TQGridLayout x0) -> Ptr (TQRect t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QGridLayout8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> QRect t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQRect t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqsetGeometry_h (QGridLayout ()) ((QRect t1)) where qsetGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGridLayout_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QGridLayout_setGeometry" qtc_QGridLayout_setGeometry :: Ptr (TQGridLayout a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry_h (QGridLayoutSc a) ((QRect t1)) where qsetGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGridLayout_setGeometry cobj_x0 cobj_x1 instance QsetGeometry_h (QGridLayout ()) ((Rect)) where setGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QGridLayout_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QGridLayout_setGeometry_qth" qtc_QGridLayout_setGeometry_qth :: Ptr (TQGridLayout a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry_h (QGridLayoutSc a) ((Rect)) where setGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QGridLayout_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QqsizeHint_h (QGridLayout ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_sizeHint cobj_x0 foreign import ccall "qtc_QGridLayout_sizeHint" qtc_QGridLayout_sizeHint :: Ptr (TQGridLayout a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QGridLayoutSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_sizeHint cobj_x0 instance QsizeHint_h (QGridLayout ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QGridLayout_sizeHint_qth" qtc_QGridLayout_sizeHint_qth :: Ptr (TQGridLayout a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QGridLayoutSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QtakeAt_h (QGridLayout ()) ((Int)) where takeAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_takeAt cobj_x0 (toCInt x1) foreign import ccall "qtc_QGridLayout_takeAt" qtc_QGridLayout_takeAt :: Ptr (TQGridLayout a) -> CInt -> IO (Ptr (TQLayoutItem ())) instance QtakeAt_h (QGridLayoutSc a) ((Int)) where takeAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_takeAt cobj_x0 (toCInt x1) instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> QLayoutItem t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQLayoutItem t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler9" qtc_QGridLayout_setHandler9 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> Ptr (TQLayoutItem t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout9 :: (Ptr (TQGridLayout x0) -> Ptr (TQLayoutItem t1) -> IO ()) -> IO (FunPtr (Ptr (TQGridLayout x0) -> Ptr (TQLayoutItem t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QGridLayout9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> QLayoutItem t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQLayoutItem t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QaddItem_h (QGridLayout ()) ((QLayoutItem t1)) where addItem_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGridLayout_addItem cobj_x0 cobj_x1 foreign import ccall "qtc_QGridLayout_addItem" qtc_QGridLayout_addItem :: Ptr (TQGridLayout a) -> Ptr (TQLayoutItem t1) -> IO () instance QaddItem_h (QGridLayoutSc a) ((QLayoutItem t1)) where addItem_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGridLayout_addItem cobj_x0 cobj_x1 instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> QObject t1 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler10" qtc_QGridLayout_setHandler10 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout10 :: (Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> QObject t1 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QindexOf_h (QGridLayout ()) ((QWidget t1)) where indexOf_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGridLayout_indexOf cobj_x0 cobj_x1 foreign import ccall "qtc_QGridLayout_indexOf" qtc_QGridLayout_indexOf :: Ptr (TQGridLayout a) -> Ptr (TQWidget t1) -> IO CInt instance QindexOf_h (QGridLayoutSc a) ((QWidget t1)) where indexOf_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGridLayout_indexOf cobj_x0 cobj_x1 instance QqisEmpty_h (QGridLayout ()) (()) where qisEmpty_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_isEmpty cobj_x0 foreign import ccall "qtc_QGridLayout_isEmpty" qtc_QGridLayout_isEmpty :: Ptr (TQGridLayout a) -> IO CBool instance QqisEmpty_h (QGridLayoutSc a) (()) where qisEmpty_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_isEmpty cobj_x0 instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler11" qtc_QGridLayout_setHandler11 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> IO (Ptr (TQObject t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout11 :: (Ptr (TQGridLayout x0) -> IO (Ptr (TQObject t0))) -> IO (FunPtr (Ptr (TQGridLayout x0) -> IO (Ptr (TQObject t0)))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qlayout_h (QGridLayout ()) (()) where layout_h x0 () = withQLayoutResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_layout cobj_x0 foreign import ccall "qtc_QGridLayout_layout" qtc_QGridLayout_layout :: Ptr (TQGridLayout a) -> IO (Ptr (TQLayout ())) instance Qlayout_h (QGridLayoutSc a) (()) where layout_h x0 () = withQLayoutResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_layout cobj_x0 instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> IO (QRect t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (Ptr (TQRect t0)) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler12" qtc_QGridLayout_setHandler12 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> IO (Ptr (TQRect t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout12 :: (Ptr (TQGridLayout x0) -> IO (Ptr (TQRect t0))) -> IO (FunPtr (Ptr (TQGridLayout x0) -> IO (Ptr (TQRect t0)))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> IO (QRect t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (Ptr (TQRect t0)) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qqgeometry_h (QGridLayout ()) (()) where qgeometry_h x0 () = withQRectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_geometry cobj_x0 foreign import ccall "qtc_QGridLayout_geometry" qtc_QGridLayout_geometry :: Ptr (TQGridLayout a) -> IO (Ptr (TQRect ())) instance Qqgeometry_h (QGridLayoutSc a) (()) where qgeometry_h x0 () = withQRectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_geometry cobj_x0 instance Qgeometry_h (QGridLayout ()) (()) where geometry_h x0 () = withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_geometry_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h foreign import ccall "qtc_QGridLayout_geometry_qth" qtc_QGridLayout_geometry_qth :: Ptr (TQGridLayout a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO () instance Qgeometry_h (QGridLayoutSc a) (()) where geometry_h x0 () = withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_geometry_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler13" qtc_QGridLayout_setHandler13 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> IO (Ptr (TQLayoutItem t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout13 :: (Ptr (TQGridLayout x0) -> IO (Ptr (TQLayoutItem t0))) -> IO (FunPtr (Ptr (TQGridLayout x0) -> IO (Ptr (TQLayoutItem t0)))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 = do x0obj <- qGridLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QspacerItem_h (QGridLayout ()) (()) where spacerItem_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_spacerItem cobj_x0 foreign import ccall "qtc_QGridLayout_spacerItem" qtc_QGridLayout_spacerItem :: Ptr (TQGridLayout a) -> IO (Ptr (TQSpacerItem ())) instance QspacerItem_h (QGridLayoutSc a) (()) where spacerItem_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_spacerItem cobj_x0 instance Qwidget_h (QGridLayout ()) (()) where widget_h x0 () = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_widget cobj_x0 foreign import ccall "qtc_QGridLayout_widget" qtc_QGridLayout_widget :: Ptr (TQGridLayout a) -> IO (Ptr (TQWidget ())) instance Qwidget_h (QGridLayoutSc a) (()) where widget_h x0 () = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGridLayout_widget cobj_x0 instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler14" qtc_QGridLayout_setHandler14 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout14 :: (Ptr (TQGridLayout x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGridLayout x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QGridLayout ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGridLayout_event cobj_x0 cobj_x1 foreign import ccall "qtc_QGridLayout_event" qtc_QGridLayout_event :: Ptr (TQGridLayout a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QGridLayoutSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGridLayout_event cobj_x0 cobj_x1 instance QsetHandler (QGridLayout ()) (QGridLayout x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout15 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout15_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGridLayout_setHandler15" qtc_QGridLayout_setHandler15 :: Ptr (TQGridLayout a) -> CWString -> Ptr (Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGridLayout15 :: (Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGridLayout15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGridLayoutSc a) (QGridLayout x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGridLayout15 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGridLayout15_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGridLayout_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGridLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qGridLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QGridLayout ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGridLayout_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QGridLayout_eventFilter" qtc_QGridLayout_eventFilter :: Ptr (TQGridLayout a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QGridLayoutSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGridLayout_eventFilter cobj_x0 cobj_x1 cobj_x2
uduki/hsQt
Qtc/Gui/QGridLayout_h.hs
bsd-2-clause
69,572
0
18
15,999
23,029
10,985
12,044
-1
-1
{-# LANGUAGE Haskell2010 #-} module Bug647 where class Bug647 a where f :: a -- ^ doc for arg1 -> a -- ^ doc for arg2 -> a -- ^ doc for arg3
haskell/haddock
html-test/src/Bug647.hs
bsd-2-clause
148
4
8
40
34
20
14
6
0
{-# OPTIONS -fno-warn-orphans -fno-warn-name-shadowing #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} -- | Make the dispatcher. module HL.Dispatch () where import HL.Controller.Community import HL.Controller.Documentation import HL.Controller.Downloads import HL.Controller.Home import HL.Controller.Irc import HL.Controller.MailingLists import HL.Foundation import Yesod.Core.Dispatch mkYesodDispatch "App" resourcesApp
bitemyapp/commercialhaskell.com
src/HL/Dispatch.hs
bsd-3-clause
553
0
5
57
71
47
24
16
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Gelatin.GL.Shader ( -- * Loading shaders loadShaders, loadBezShader, loadGeomShader, loadMaskShader, loadProjectedPolylineShader, loadShader, -- * Shader types ShaderProgram, Shader(..), ShaderDef(..), ProjectedPolylineShader(..), GeomShader(..), BezShader(..), MaskShader(..), SumShader(..), -- * Uniforms Uniform(..), updateUniform, updateUniforms, -- * Attributes -- $layout AttribLoc(..), locToGLuint, -- * Enabling and disabling attribs onlyEnableAttribs, -- * Shader source files vertSourceProjPoly, fragSourceProjPoly, vertSourceGeom, fragSourceGeom, vertSourceBezier, fragSourceBezier, vertSourceMask, fragSourceMask, -- * Shader compilation compileShader, compileProgram, ) where import Prelude hiding (init) import Prelude as P import Graphics.GL.Core33 import Graphics.GL.Types import Gelatin.Picture import Control.Monad import System.Exit import System.Directory import Foreign.Ptr import Foreign.C.String import Foreign.Marshal.Array import Foreign.Marshal.Utils import Foreign.Storable import Data.ByteString.Char8 as B import Data.FileEmbed import Data.Maybe import Linear type ShaderProgram = GLuint data Shader = Shader { shProgram :: ShaderProgram , shUniforms :: [(String, GLint)] } deriving (Show) data ShaderDef = ShaderDefFP { defShaderPaths :: [(String, GLuint)] -- ^ [("path/to/shader.vert", GL_VERTEX_SHADER)] , defUniforms :: [String] , defAttribs :: [AttribLoc] } | ShaderDefBS { defShaderSrcs :: [(ByteString, GLuint)] , defUniforms :: [String] , defAttribs :: [AttribLoc] } deriving (Show, Eq, Ord) newtype ProjectedPolylineShader = PPRS Shader newtype GeomShader = GRS Shader newtype BezShader = BRS Shader newtype MaskShader = MRS Shader data SumShader = SRS { shProjectedPolyline :: ProjectedPolylineShader , shGeometry :: GeomShader , shBezier :: BezShader , shMask :: MaskShader } -------------------------------------------------------------------------------- -- Loading built shaders. -------------------------------------------------------------------------------- -- | Compile all shader programs and return a "sum renderer". loadShaders :: IO SumShader loadShaders = SRS <$> loadProjectedPolylineShader <*> loadGeomShader <*> loadBezShader <*> loadMaskShader -- | Compile a shader program and link attributes for rendering screen space -- projected expanded polylines. loadProjectedPolylineShader :: IO ProjectedPolylineShader loadProjectedPolylineShader = do let nocaps = (LineCapNone,LineCapNone) uniforms = P.map glslUniformIdentifier [UniformProjection 0 ,UniformModelView 0 ,UniformThickness 0 ,UniformFeather 0 ,UniformSumLength 0 ,UniformLineCaps nocaps ,UniformSampler 0 ,UniformHasUV False ] attribs = [PositionLoc,ColorLoc,BezUVLoc,NextLoc,PrevLoc,UVLoc] def = ShaderDefBS[(vertSourceProjPoly, GL_VERTEX_SHADER) ,(fragSourceProjPoly, GL_FRAGMENT_SHADER) ] uniforms attribs PPRS <$> loadShader def -- | Loads a new shader program and attributes for rendering geometry. loadGeomShader :: IO GeomShader loadGeomShader = do let uniforms = P.map glslUniformIdentifier [UniformProjection 0 ,UniformModelView 0 ,UniformSampler 0 ,UniformHasUV False ] attribs = [PositionLoc,ColorLoc,UVLoc] def = ShaderDefBS [(vertSourceGeom, GL_VERTEX_SHADER) ,(fragSourceGeom, GL_FRAGMENT_SHADER) ] uniforms attribs GRS <$> loadShader def -- | Loads a new shader progarm and attributes for rendering beziers. loadBezShader :: IO BezShader loadBezShader = do let uniforms = P.map glslUniformIdentifier [UniformProjection 0 ,UniformModelView 0 ,UniformSampler 0 ,UniformHasUV False ] attribs = [PositionLoc,ColorLoc,UVLoc,BezLoc] def = ShaderDefBS [(vertSourceBezier, GL_VERTEX_SHADER) ,(fragSourceBezier, GL_FRAGMENT_SHADER) ] uniforms attribs BRS <$> loadShader def -- | Loads a new shader program and attributes for masking textures. loadMaskShader :: IO MaskShader loadMaskShader = do let uniforms = P.map glslUniformIdentifier [UniformProjection 0 ,UniformModelView 0 ,UniformMainTex 0 ,UniformMaskTex 0 ] attribs = [PositionLoc,UVLoc] def = ShaderDefBS [(vertSourceMask, GL_VERTEX_SHADER) ,(fragSourceMask, GL_FRAGMENT_SHADER) ] uniforms attribs MRS <$> loadShader def loadShader :: ShaderDef -> IO Shader loadShader (ShaderDefBS ss uniforms attribs) = do shaders <- mapM (uncurry compileShader) ss program <- compileProgram shaders attribs glUseProgram program ulocs <- forM uniforms $ \u -> do loc <- withCString u $ glGetUniformLocation program if loc == (-1) then do P.putStrLn $ "Warning! Could not find the uniform " ++ show u return Nothing else return $ Just (u, loc) return $ Shader program (catMaybes ulocs) loadShader (ShaderDefFP fps uniforms attribs) = do cwd <- getCurrentDirectory srcs <- forM fps $ \(fp, shaderType) -> do src <- B.readFile $ cwd ++ "/" ++ fp return (src, shaderType) loadShader $ ShaderDefBS srcs uniforms attribs -------------------------------------------------------------------------------- -- Updating uniforms -------------------------------------------------------------------------------- data Uniform = UniformProjection (M44 Float) | UniformModelView (M44 Float) | UniformThickness Float | UniformFeather Float | UniformSumLength Float | UniformLineCaps (LineCap,LineCap) | UniformHasUV Bool | UniformSampler Int | UniformMainTex Int | UniformMaskTex Int deriving (Show, Ord, Eq) glslUniformIdentifier :: Uniform -> String glslUniformIdentifier (UniformProjection _) = "projection" glslUniformIdentifier (UniformModelView _) = "modelview" glslUniformIdentifier (UniformThickness _) = "thickness" glslUniformIdentifier (UniformFeather _) = "feather" glslUniformIdentifier (UniformSumLength _) = "sumlength" glslUniformIdentifier (UniformLineCaps _) = "cap" glslUniformIdentifier (UniformHasUV _) = "hasUV" glslUniformIdentifier (UniformSampler _) = "sampler" glslUniformIdentifier (UniformMainTex _) = "mainTex" glslUniformIdentifier (UniformMaskTex _) = "maskTex" updateUniforms :: [Uniform] -> Shader -> IO () updateUniforms us s = mapM_ (`updateUniform` s) us updateUniform :: Uniform -> Shader -> IO () updateUniform u s = withUniform (glslUniformIdentifier u) s $ \p loc -> do glUseProgram p uniformUpdateFunc u loc uniformUpdateFunc :: Uniform -> GLint -> IO () uniformUpdateFunc (UniformProjection m44) u = with m44 $ glUniformMatrix4fv u 1 GL_TRUE . castPtr uniformUpdateFunc (UniformModelView m44) u = with m44 $ glUniformMatrix4fv u 1 GL_TRUE . castPtr uniformUpdateFunc (UniformThickness t) u = glUniform1f u t uniformUpdateFunc (UniformFeather f) u = glUniform1f u f uniformUpdateFunc (UniformSumLength l) u = glUniform1f u l uniformUpdateFunc (UniformLineCaps (capx, capy)) u = let [x,y] = P.map (fromIntegral . fromEnum) [capx,capy] in glUniform2f u x y uniformUpdateFunc (UniformHasUV has) u = glUniform1i u $ if has then 1 else 0 uniformUpdateFunc (UniformSampler s) u = glUniform1i u $ fromIntegral s uniformUpdateFunc (UniformMainTex t) u = glUniform1i u $ fromIntegral t uniformUpdateFunc (UniformMaskTex t) u = glUniform1i u $ fromIntegral t withUniform :: String -> Shader -> (GLuint -> GLint -> IO ()) -> IO () withUniform name (Shader p ls) f = case lookup name ls of Nothing -> do P.putStrLn $ "could not find uniform " ++ name exitFailure Just loc -> f p loc -------------------------------------------------------------------------------- -- $layout -- Attributes layout locations are unique and global. -------------------------------------------------------------------------------- data AttribLoc = PositionLoc | ColorLoc | UVLoc | BezLoc | NextLoc | PrevLoc | BezUVLoc deriving (Show, Eq, Ord, Enum, Bounded) allLocs :: [AttribLoc] allLocs = [minBound..maxBound] glslAttribIdentifier :: AttribLoc -> String glslAttribIdentifier PositionLoc = "position" glslAttribIdentifier ColorLoc = "color" glslAttribIdentifier UVLoc = "uv" glslAttribIdentifier BezLoc = "bez" glslAttribIdentifier NextLoc = "next" glslAttribIdentifier PrevLoc = "previous" glslAttribIdentifier BezUVLoc = "bezuv" locToGLuint :: AttribLoc -> GLuint locToGLuint = fromIntegral . fromEnum -- | Enables the provided attributes and disables all others. onlyEnableAttribs :: [AttribLoc] -> IO () onlyEnableAttribs atts = do mapM_ (glDisableVertexAttribArray . locToGLuint) allLocs mapM_ (glEnableVertexAttribArray . locToGLuint) atts -------------------------------------------------------------------------------- -- Shader compilation -------------------------------------------------------------------------------- compileShader :: ByteString -> GLuint -> IO GLuint compileShader src sh = do shader <- glCreateShader sh when (shader == 0) $ do B.putStrLn "could not create shader" exitFailure withCString (B.unpack src) $ \ptr -> with ptr $ \ptrptr -> glShaderSource shader 1 ptrptr nullPtr glCompileShader shader success <- with (0 :: GLint) $ \ptr -> do glGetShaderiv shader GL_COMPILE_STATUS ptr peek ptr when (success == GL_FALSE) $ do B.putStrLn "could not compile shader:\n" B.putStrLn src infoLog <- with (0 :: GLint) $ \ptr -> do glGetShaderiv shader GL_INFO_LOG_LENGTH ptr logsize <- peek ptr allocaArray (fromIntegral logsize) $ \logptr -> do glGetShaderInfoLog shader logsize nullPtr logptr peekArray (fromIntegral logsize) logptr P.putStrLn $ P.map (toEnum . fromEnum) infoLog exitFailure return shader compileProgram :: [GLuint] -> [AttribLoc] -> IO GLuint compileProgram shaders attribs = do program <- glCreateProgram forM_ shaders (glAttachShader program) forM_ attribs $ \attrib -> withCString (glslAttribIdentifier attrib) (glBindAttribLocation program (locToGLuint attrib)) glLinkProgram program success <- with (0 :: GLint) $ \ptr -> do glGetProgramiv program GL_LINK_STATUS ptr peek ptr when (success == GL_FALSE) $ do B.putStrLn "could not link program" infoLog <- with (0 :: GLint) $ \ptr -> do glGetProgramiv program GL_INFO_LOG_LENGTH ptr logsize <- peek ptr allocaArray (fromIntegral logsize) $ \logptr -> do glGetProgramInfoLog program logsize nullPtr logptr peekArray (fromIntegral logsize) logptr P.putStrLn $ P.map (toEnum . fromEnum) infoLog exitFailure forM_ shaders glDeleteShader return program -------------------------------------------------------------------------------- -- Shader sources -------------------------------------------------------------------------------- vertSourceProjPoly :: ByteString vertSourceProjPoly = $(embedFile "shaders/projected-line.vert") fragSourceProjPoly :: ByteString fragSourceProjPoly = $(embedFile "shaders/projected-line.frag") vertSourceGeom :: ByteString vertSourceGeom = $(embedFile "shaders/2d.vert") fragSourceGeom :: ByteString fragSourceGeom = $(embedFile "shaders/2d.frag") vertSourceBezier :: ByteString vertSourceBezier = $(embedFile "shaders/bezier.vert") fragSourceBezier :: ByteString fragSourceBezier = $(embedFile "shaders/bezier.frag") vertSourceMask :: ByteString vertSourceMask = $(embedFile "shaders/mask.vert") fragSourceMask :: ByteString fragSourceMask = $(embedFile "shaders/mask.frag")
cies/gelatin
gelatin-gl/src/Gelatin/GL/Shader.hs
bsd-3-clause
13,528
0
21
3,885
2,960
1,557
1,403
275
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ExistentialQuantification #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Ivory.Language.Area where import Ivory.Language.Proxy import Ivory.Language.Type import qualified Ivory.Language.Syntax as I import GHC.TypeLits (Nat, Symbol) -- Memory Areas ---------------------------------------------------------------- -- | Type proxies for @Area@s. type AProxy a = Proxy (a :: Area *) -- | The kind of memory-area types. data Area k = Struct Symbol | Array Nat (Area k) | CArray (Area k) | Stored k -- ^ This is lifting for a *-kinded type -- | Guard the inhabitants of the Area type, as not all *s are Ivory *s. class IvoryArea (a :: Area *) where ivoryArea :: Proxy a -> I.Type instance (ANat len, IvoryArea area) => IvoryArea (Array len area) where ivoryArea _ = I.TyArr len area where len = fromInteger (fromTypeNat (aNat :: NatType len)) area = ivoryArea (Proxy :: Proxy area) instance IvoryType a => IvoryArea (Stored a) where ivoryArea _ = ivoryType (Proxy :: Proxy a)
Hodapp87/ivory
ivory/src/Ivory/Language/Area.hs
bsd-3-clause
1,129
0
12
214
270
152
118
25
0
-- !!! Testing IOError (part 2) -- These should both raise the same error - not IOErrors! a1 = ["a" !! 1] a2 = writeFile "foo" (["a"] !! 1)
FranklinChen/Hugs
tests/rts/ioerror2.hs
bsd-3-clause
141
0
8
30
35
20
15
2
1
{-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE OverloadedStrings #-} {-| Module : Relvar.Pretty.BoxesText Description : Text rendering and output to stdout. Copyright : (c) Janthelme, 2016 License : BDS3 Maintainer : [email protected] Stability : experimental Portability : POSIX Set of convenience functions to render relations and output them to stdout. Credit: This module is a modified version of Text.PrettyPrint.Boxes in the boxes package. Original version by Brent Yorgey and David Feuer <https://www.stackage.org/lts-6.13/package/boxes-0.1.4 here> and <https://github.com/treeowl/boxes here>. Modified version by rustydc <https://github.com/treeowl/boxes/pull/1 here>. The original boxes package cannot be used as is, as it does not handle Text type (and therefore does not allow Unicode characters output). The plan is to use the original boxes module when it finally accepts Text types (or represent Unicode characters another way) and discard this one. -} module Relvar.Pretty.BoxesText ( -- * Constructing boxes Box , nullBox , emptyBox , char , text , para , columns -- * Layout of boxes , (<>) , (<+>) , hcat , hsep , (//) , (/+/) , vcat , vsep , punctuateH, punctuateV -- * Alignment , Alignment(..) , left, right , top, bottom , center1, center2 , moveLeft , moveRight , moveUp , moveDown , alignHoriz , alignVert , align -- * Inspecting boxes , rows , cols -- * Rendering boxes , render , printBox ) where import Data.String import qualified Data.Text as T import qualified Data.Text.IO as T (putStr, putStrLn) import Control.Arrow ((***), first) import Data.List (foldl', intersperse) import Data.List.Split import Data.Int (Int64) import Prelude hiding (Word) -- | The basic data type. A box has a specified size and some sort of -- contents. data Box = Box { rows :: Int -- ^ row # , cols :: Int -- ^ col # , content :: Content } deriving (Show) -- | Convenient ability to use bare string literals as boxes. instance IsString Box where fromString = text . T.pack -- | Data type for specifying the alignment of boxes. data Alignment = AlignFirst -- ^ Align at the top/left. | AlignCenter1 -- ^ Centered, biased to the top/left. | AlignCenter2 -- ^ Centered, biased to the bottom/right. | AlignLast -- ^ Align at the bottom/right. deriving (Eq, Read, Show) -- | Align boxes along their tops. top :: Alignment top = AlignFirst -- | Align boxes along their bottoms. bottom :: Alignment bottom = AlignLast -- | Align boxes to the left. left :: Alignment left = AlignFirst -- | Align boxes to the right. right :: Alignment right = AlignLast -- | Align boxes centered, but biased to the left/top in case of -- unequal parities. center1 :: Alignment center1 = AlignCenter1 -- | Align boxes centered, but biased to the right/bottom in case of -- unequal parities. center2 :: Alignment center2 = AlignCenter2 -- | Contents of a box. data Content = Blank -- ^ No content. | Text T.Text -- ^ A raw string. | Row [Box] -- ^ A row of sub-boxes. | Col [Box] -- ^ A column of sub-boxes. | SubBox Alignment Alignment Box -- ^ A sub-box with a specified alignment. deriving (Show) -- | The null box, which has no content and no size. It is quite -- useless. nullBox :: Box nullBox = emptyBox 0 0 -- | @emptyBox r c@ is an empty box with @r@ rows and @c@ columns. -- Useful for effecting more fine-grained positioning of other -- boxes, by inserting empty boxes of the desired size in between -- them. emptyBox :: Int -> Int -> Box emptyBox r c = Box r c Blank -- | A @1x1@ box containing a single character. char :: Char -> Box char c = Box 1 1 (Text (T.singleton c)) -- | A (@1 x len@) box containing a string of length @len@. text :: T.Text -> Box text t = Box 1 (T.length t) (Text t) -- | Paste two boxes together horizontally, using a default (top) -- alignment. (<>) :: Box -> Box -> Box l <> r = hcat top [l,r] -- | Paste two boxes together horizontally with a single intervening -- column of space, using a default (top) alignment. (<+>) :: Box -> Box -> Box l <+> r = hcat top [l, emptyBox 0 1, r] -- | Paste two boxes together vertically, using a default (left) -- alignment. (//) :: Box -> Box -> Box t // b = vcat left [t,b] -- | Paste two boxes together vertically with a single intervening row -- of space, using a default (left) alignment. (/+/) :: Box -> Box -> Box t /+/ b = vcat left [t, emptyBox 1 0, b] -- | Glue a list of boxes together horizontally, with the given alignment. hcat :: Alignment -> [Box] -> Box hcat a bs = Box h w (Row $ map (alignVert a h) bs) where h = maximum . (0:) . map rows $ bs w = sum . map cols $ bs -- | @hsep sep a bs@ lays out @bs@ horizontally with alignment @a@, -- with @sep@ amount of space in between each. hsep :: Int -> Alignment -> [Box] -> Box hsep sep a bs = punctuateH a (emptyBox 0 sep) bs -- | Glue a list of boxes together vertically, with the given alignment. vcat :: Alignment -> [Box] -> Box vcat a bs = Box h w (Col $ map (alignHoriz a w) bs) where h = sum . map rows $ bs w = maximum . (0:) . map cols $ bs -- | @vsep sep a bs@ lays out @bs@ vertically with alignment @a@, -- with @sep@ amount of space in between each. vsep :: Int -> Alignment -> [Box] -> Box vsep sep a bs = punctuateV a (emptyBox sep 0) bs -- | @punctuateH a p bs@ horizontally lays out the boxes @bs@ with a -- copy of @p@ interspersed between each. punctuateH :: Alignment -> Box -> [Box] -> Box punctuateH a p bs = hcat a (intersperse p bs) -- | A vertical version of 'punctuateH'. punctuateV :: Alignment -> Box -> [Box] -> Box punctuateV a p bs = vcat a (intersperse p bs) -------------------------------------------------------------------------------- -- Paragraph flowing --------------------------------------------------------- -------------------------------------------------------------------------------- -- | @para algn w t@ is a box of width @w@, containing text @t@, -- aligned according to @algn@, flowed to fit within the given -- width. para :: Alignment -> Int -> T.Text -> Box para a n t = (\ss -> mkParaBox a (length ss) ss) $ flow n t -- | @columns w h t@ is a list of boxes, each of width @w@ and height -- at most @h@, containing text @t@ flowed into as many columns as -- necessary. columns :: Alignment -> Int -> Int -> T.Text -> [Box] columns a w h t = map (mkParaBox a h) . chunksOf h $ flow w t -- | @mkParaBox a n s@ makes a box of height @n@ with the text @s@ -- aligned according to @a@. mkParaBox :: Alignment -> Int -> [T.Text] -> Box mkParaBox a n = alignVert top n . vcat a . map text -- | Flow the given text into the given width. flow :: Int -> T.Text -> [T.Text] flow n t = map (T.take n) . getLines $ foldl' addWordP (emptyPara n) (map mkWord . T.words $ t) data Para = Para { paraWidth :: Int , paraContent :: ParaContent } data ParaContent = Block { fullLines :: [Line] , lastLine :: Line } emptyPara :: Int -> Para emptyPara pw = Para pw (Block [] (Line 0 [])) getLines :: Para -> [T.Text] getLines (Para _ (Block ls l)) | lLen l == 0 = process ls | otherwise = process (l:ls) where process = map (T.unwords . reverse . map getWord . getWords) . reverse data Line = Line { lLen :: Int, getWords :: [Word] } mkLine :: [Word] -> Line mkLine ws = Line (sum (map wLen ws) + length ws - 1) ws startLine :: Word -> Line startLine = mkLine . (:[]) data Word = Word { wLen :: Int, getWord :: T.Text } mkWord :: T.Text -> Word mkWord w = Word (T.length w) w addWordP :: Para -> Word -> Para addWordP (Para pw (Block fl l)) w | wordFits pw w l = Para pw (Block fl (addWordL w l)) | otherwise = Para pw (Block (l:fl) (startLine w)) addWordL :: Word -> Line -> Line addWordL w (Line len ws) = Line (len + wLen w + 1) (w:ws) wordFits :: Int -> Word -> Line -> Bool wordFits pw w l = lLen l == 0 || lLen l + wLen w + 1 <= pw -------------------------------------------------------------------------------- -- Alignment ----------------------------------------------------------------- -------------------------------------------------------------------------------- -- | @alignHoriz algn n bx@ creates a box of width @n@, with the -- contents and height of @bx@, horizontally aligned according to -- @algn@. alignHoriz :: Alignment -> Int -> Box -> Box alignHoriz a c b = Box (rows b) c $ SubBox a AlignFirst b -- | @alignVert algn n bx@ creates a box of height @n@, with the -- contents and width of @bx@, vertically aligned according to -- @algn@. alignVert :: Alignment -> Int -> Box -> Box alignVert a r b = Box r (cols b) $ SubBox AlignFirst a b -- | @align ah av r c bx@ creates an @r@ x @c@ box with the contents -- of @bx@, aligned horizontally according to @ah@ and vertically -- according to @av@. align :: Alignment -> Alignment -> Int -> Int -> Box -> Box align ah av r c = Box r c . SubBox ah av -- | Move a box \"up\" by putting it in a larger box with extra rows, -- aligned to the top. See the disclaimer for 'moveLeft'. moveUp :: Int -> Box -> Box moveUp n b = alignVert top (rows b + n) b -- | Move a box down by putting it in a larger box with extra rows, -- aligned to the bottom. See the disclaimer for 'moveLeft'. moveDown :: Int -> Box -> Box moveDown n b = alignVert bottom (rows b + n) b -- | Move a box left by putting it in a larger box with extra columns, -- aligned left. Note that the name of this function is -- something of a white lie, as this will only result in the box -- being moved left by the specified amount if it is already in a -- larger right-aligned context. moveLeft :: Int -> Box -> Box moveLeft n b = alignHoriz left (cols b + n) b -- | Move a box right by putting it in a larger box with extra -- columns, aligned right. See the disclaimer for 'moveLeft'. moveRight :: Int -> Box -> Box moveRight n b = alignHoriz right (cols b + n) b -------------------------------------------------------------------------------- -- Implementation ------------------------------------------------------------ -------------------------------------------------------------------------------- -- | Render a 'Box' as a String, suitable for writing to the screen or -- a file. render :: Box -> T.Text render = T.unlines . renderBox -- XXX make QC properties for takeP -- | \"Padded take\": @takeP a n xs@ is the same as @take n xs@, if @n -- <= length xs@; otherwise it is @xs@ followed by enough copies of -- @a@ to make the length equal to @n@. takeP :: a -> Int -> [a] -> [a] takeP _ n _ | n <= 0 = [] takeP b n [] = replicate n b takeP b n (x:xs) = x : takeP b (n-1) xs -- | @takeP' a n t@ is the same as @takeP a n xs@, but on Text. takeP' :: Char -> Int -> T.Text -> T.Text takeP' _ n _ | n <= 0 = T.empty takeP' b n t | T.length t == 0 = T.replicate n (T.singleton b) | otherwise = T.head t `T.cons` takeP' b (n-1) (T.tail t) -- | @takePA @ is like 'takeP', but with alignment. That is, we -- imagine a copy of @xs@ extended infinitely on both sides with -- copies of @a@, and a window of size @n@ placed so that @xs@ has -- the specified alignment within the window; @takePA algn a n xs@ -- returns the contents of this window. takePA :: Alignment -> a -> Int -> [a] -> [a] takePA c b n = glue . (takeP b (numRev c n) *** takeP b (numFwd c n)) . split where split t = first reverse . splitAt (numRev c (length t)) $ t glue = uncurry (++) . first reverse numFwd AlignFirst n = n numFwd AlignLast _ = 0 numFwd AlignCenter1 n = n `div` 2 numFwd AlignCenter2 n = (n+1) `div` 2 numRev AlignFirst _ = 0 numRev AlignLast n = n numRev AlignCenter1 n = (n+1) `div` 2 numRev AlignCenter2 n = n `div` 2 takePA' :: Alignment -> Char -> Int -> T.Text -> T.Text takePA' c b n = glue . (takeP' b (numRev c n) *** takeP' b (numFwd c n)) . split where split t = first T.reverse . T.splitAt (numRev c (T.length t)) $ t glue = uncurry T.append . first T.reverse numFwd AlignFirst n = n numFwd AlignLast _ = 0 numFwd AlignCenter1 n = n `div` 2 numFwd AlignCenter2 n = (n+1) `div` 2 numRev AlignFirst _ = 0 numRev AlignLast n = n numRev AlignCenter1 n = (n+1) `div` 2 numRev AlignCenter2 n = n `div` 2 -- | Generate a string of spaces. blanks :: Int -> T.Text blanks = flip T.replicate (T.singleton ' ') -- | Render a box as a list of lines. renderBox :: Box -> [T.Text] renderBox (Box r c Blank) = resizeBox r c [""] renderBox (Box r c (Text t)) = resizeBox r c [t] renderBox (Box r c (Row bs)) = resizeBox r c . merge . map (renderBoxWithRows r) $ bs where merge = foldr (zipWith T.append) (repeat T.empty) renderBox (Box r c (Col bs)) = resizeBox r c . concatMap (renderBoxWithCols c) $ bs renderBox (Box r c (SubBox ha va b)) = resizeBoxAligned r c ha va . renderBox $ b -- | Render a box as a list of lines, using a given number of rows. renderBoxWithRows :: Int -> Box -> [T.Text] renderBoxWithRows r b = renderBox (b{rows = r}) -- | Render a box as a list of lines, using a given number of columns. renderBoxWithCols :: Int -> Box -> [T.Text] renderBoxWithCols c b = renderBox (b{cols = c}) -- | Resize a rendered list of lines. resizeBox :: Int -> Int -> [T.Text] -> [T.Text] resizeBox r c = takeP (blanks c) r . map (takeP' ' ' c) -- | Resize a rendered list of lines, using given alignments. resizeBoxAligned :: Int -> Int -> Alignment -> Alignment -> [T.Text] -> [T.Text] resizeBoxAligned r c ha va = takePA va (blanks c) r . map (takePA' ha ' ' c) -- | A convenience function for rendering a box to stdout. printBox :: Box -> IO () printBox = T.putStr . render -- side by side - quick hack
JAnthelme/relation-tool
src/Relvar/Pretty/BoxesText.hs
bsd-3-clause
14,586
0
14
3,841
3,612
1,949
1,663
-1
-1
-- This is taken from GHC.List in GHC HEAD, 2014-05-09 {-# LANGUAGE NoImplicitPrelude, ScopedTypeVariables, MagicHash, RankNTypes, CPP #-} module ListImpls.FusingFoldl #include "exports" where import Prelude (Maybe(..), Bool(..), Int(..), (.), otherwise, (&&), (||), String, error, id) import GHC.Exts (Int(..), Int#, (+#), (-#), isTrue#, (>=#), (<=#), (<#)) import Data.Coerce (coerce) build :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a] {-# INLINE [1] build #-} build g = g (:) [] augment :: forall a. (forall b. (a->b->b) -> b -> b) -> [a] -> [a] {-# INLINE [1] augment #-} augment g xs = g (:) xs foldr :: (a -> b -> b) -> b -> [a] -> b -- foldr _ z [] = z -- foldr f z (x:xs) = f x (foldr f z xs) {-# INLINE [0] foldr #-} -- Inline only in the final stage, after the foldr/cons rule has had a chance -- Also note that we inline it when it has *two* parameters, which are the -- ones we are keen about specialising! foldr k z = go where go [] = z go (y:ys) = y `k` go ys {-# RULES "fold/build" forall k z (g::forall b. (a->b->b) -> b -> b) . foldr k z (build g) = g k z "foldr/augment" forall k z xs (g::forall b. (a->b->b) -> b -> b) . foldr k z (augment g xs) = g k (foldr k z xs) "foldr/id" foldr (:) [] = \x -> x "foldr/app" [1] forall ys. foldr (:) ys = \xs -> xs ++ ys -- Only activate this from phase 1, because that's -- when we disable the rule that expands (++) into foldr "foldr/single" forall k z x. foldr k z [x] = k x z "foldr/nil" forall k z. foldr k z [] = z "augment/build" forall (g::forall b. (a->b->b) -> b -> b) (h::forall b. (a->b->b) -> b -> b) . augment g (build h) = build (\c n -> g c (h c n)) "augment/nil" forall (g::forall b. (a->b->b) -> b -> b) . augment g [] = build g #-} map :: (a -> b) -> [a] -> [b] {-# NOINLINE [1] map #-} -- We want the RULE to fire first. -- It's recursive, so won't inline anyway, -- but saying so is more explicit map _ [] = [] map f (x:xs) = f x : map f xs -- Note eta expanded mapFB :: (elt -> lst -> lst) -> (a -> elt) -> a -> lst -> lst {-# INLINE [0] mapFB #-} mapFB c f = \x ys -> c (f x) ys {-# RULES "map" [~1] forall f xs. map f xs = build (\c n -> foldr (mapFB c f) n xs) "mapList" [1] forall f. foldr (mapFB (:) f) [] = map f "mapFB" forall c f g. mapFB (mapFB c f) g = mapFB c (f.g) #-} {-# RULES "map/coerce" [1] map coerce = coerce #-} (++) :: [a] -> [a] -> [a] {-# NOINLINE [1] (++) #-} -- We want the RULE to fire first. -- It's recursive, so won't inline anyway, -- but saying so is more explicit (++) [] ys = ys (++) (x:xs) ys = x : xs ++ ys {-# RULES "++" [~1] forall xs ys. xs ++ ys = augment (\c n -> foldr c n xs) ys #-} head :: [a] -> a head (x:_) = x head [] = badHead {-# NOINLINE [1] head #-} badHead :: a badHead = errorEmptyList "head" {-# RULES "head/build" forall (g::forall b.(a->b->b)->b->b) . head (build g) = g (\x _ -> x) badHead "head/augment" forall xs (g::forall b. (a->b->b) -> b -> b) . head (augment g xs) = g (\x _ -> x) (head xs) #-} uncons :: [a] -> Maybe (a, [a]) uncons [] = Nothing uncons (x:xs) = Just (x, xs) tail :: [a] -> [a] tail (_:xs) = xs tail [] = errorEmptyList "tail" last :: [a] -> a -- use foldl to allow fusion last = foldl (\_ x -> x) (errorEmptyList "last") init :: [a] -> [a] init [] = errorEmptyList "init" init (x:xs) = init' x xs where init' _ [] = [] init' y (z:zs) = y : init' z zs null :: [a] -> Bool null [] = True null (_:_) = False {-# NOINLINE [1] length #-} length :: [a] -> Int length l = lenAcc l 0# lenAcc :: [a] -> Int# -> Int lenAcc [] a# = I# a# lenAcc (_:xs) a# = lenAcc xs (a# +# 1#) incLen :: a -> (Int# -> Int) -> Int# -> Int incLen _ g x = g (x +# 1#) -- These rules make length into a good consumer -- Note that we use a higher-order-style use of foldr, so that -- the accumulating parameter can be evaluated strictly -- See Trac #876 for what goes wrong otherwise {-# RULES "length" [~1] forall xs. length xs = foldr incLen I# xs 0# "lengthList" [1] foldr incLen I# = lenAcc #-} {-# NOINLINE [1] filter #-} filter :: (a -> Bool) -> [a] -> [a] filter _pred [] = [] filter pred (x:xs) | pred x = x : filter pred xs | otherwise = filter pred xs {-# NOINLINE [0] filterFB #-} filterFB :: (a -> b -> b) -> (a -> Bool) -> a -> b -> b filterFB c p x r | p x = x `c` r | otherwise = r {-# RULES "filter" [~1] forall p xs. filter p xs = build (\c n -> foldr (filterFB c p) n xs) "filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p "filterFB" forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x) #-} foldl :: forall a b. (b -> a -> b) -> b -> [a] -> b {-# INLINE foldl #-} foldl k z0 xs = foldr (\(v::a) (fn::b->b) (z::b) -> fn (k z v)) (id :: b -> b) xs z0 -- Implementing foldl via foldr is only a good idea if the compiler can optimize -- the resulting code (eta-expand the recursive "go"), so this needs -fcall-arity! -- Also see #7994 scanl :: (b -> a -> b) -> b -> [a] -> [b] scanl f q ls = q : (case ls of [] -> [] x:xs -> scanl f (f q x) xs) scanl1 :: (a -> a -> a) -> [a] -> [a] scanl1 f (x:xs) = scanl f x xs scanl1 _ [] = [] foldr1 :: (a -> a -> a) -> [a] -> a foldr1 _ [x] = x foldr1 f (x:xs) = f x (foldr1 f xs) foldr1 _ [] = errorEmptyList "foldr1" scanr :: (a -> b -> b) -> b -> [a] -> [b] scanr _ q0 [] = [q0] scanr f q0 (x:xs) = f x q : qs where qs@(q:_) = scanr f q0 xs scanr1 :: (a -> a -> a) -> [a] -> [a] scanr1 _ [] = [] scanr1 _ [x] = [x] scanr1 f (x:xs) = f x q : qs where qs@(q:_) = scanr1 f xs {-# NOINLINE [1] iterate #-} iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) {-# NOINLINE [0] iterateFB #-} iterateFB :: (a -> b -> b) -> (a -> a) -> a -> b iterateFB c f x = x `c` iterateFB c f (f x) {-# RULES "iterate" [~1] forall f x. iterate f x = build (\c _n -> iterateFB c f x) "iterateFB" [1] iterateFB (:) = iterate #-} repeat :: a -> [a] {-# INLINE [0] repeat #-} -- The pragma just gives the rules more chance to fire repeat x = xs where xs = x : xs {-# INLINE [0] repeatFB #-} -- ditto repeatFB :: (a -> b -> b) -> a -> b repeatFB c x = xs where xs = x `c` xs {-# RULES "repeat" [~1] forall x. repeat x = build (\c _n -> repeatFB c x) "repeatFB" [1] repeatFB (:) = repeat #-} {-# INLINE replicate #-} replicate :: Int -> a -> [a] replicate n x = take n (repeat x) cycle :: [a] -> [a] cycle [] = error "Prelude.cycle: empty list" cycle xs = xs' where xs' = xs ++ xs' takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile _ [] = [] takeWhile p (x:xs) | p x = x : takeWhile p xs | otherwise = [] dropWhile :: (a -> Bool) -> [a] -> [a] dropWhile _ [] = [] dropWhile p xs@(x:xs') | p x = dropWhile p xs' | otherwise = xs take :: Int -> [a] -> [a] drop :: Int -> [a] -> [a] splitAt :: Int -> [a] -> ([a],[a]) {-# RULES "take" [~1] forall n xs . take n xs = takeFoldr n xs "takeList" [1] forall n xs . foldr (takeFB (:) []) (takeConst []) xs n = takeUInt n xs #-} {-# INLINE takeFoldr #-} takeFoldr :: Int -> [a] -> [a] takeFoldr (I# n#) xs = build (\c nil -> if isTrue# (n# <=# 0#) then nil else foldr (takeFB c nil) (takeConst nil) xs n#) {-# NOINLINE [0] takeConst #-} -- just a version of const that doesn't get inlined too early, so we -- can spot it in rules. Also we need a type sig due to the unboxed Int#. takeConst :: a -> Int# -> a takeConst x _ = x {-# INLINE [0] takeFB #-} takeFB :: (a -> b -> b) -> b -> a -> (Int# -> b) -> Int# -> b -- The \m accounts for the fact that takeFB is used in a higher-order -- way by takeFoldr, so it's better to inline. A good example is -- take n (repeat x) -- for which we get excellent code... but only if we inline takeFB -- when given four arguments takeFB c n x xs = \ m -> if isTrue# (m <=# 1#) then x `c` n else x `c` xs (m -# 1#) {-# INLINE [0] take #-} take (I# n#) xs = takeUInt n# xs takeUInt :: Int# -> [b] -> [b] takeUInt n xs | isTrue# (n >=# 0#) = take_unsafe_UInt n xs | otherwise = [] take_unsafe_UInt :: Int# -> [b] -> [b] take_unsafe_UInt 0# _ = [] take_unsafe_UInt m ls = case ls of [] -> [] (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs takeUInt_append :: Int# -> [b] -> [b] -> [b] takeUInt_append n xs rs | isTrue# (n >=# 0#) = take_unsafe_UInt_append n xs rs | otherwise = [] take_unsafe_UInt_append :: Int# -> [b] -> [b] -> [b] take_unsafe_UInt_append 0# _ rs = rs take_unsafe_UInt_append m ls rs = case ls of [] -> rs (x:xs) -> x : take_unsafe_UInt_append (m -# 1#) xs rs drop (I# n#) ls | isTrue# (n# <# 0#) = ls | otherwise = drop# n# ls where drop# :: Int# -> [a] -> [a] drop# 0# xs = xs drop# _ xs@[] = xs drop# m# (_:xs) = drop# (m# -# 1#) xs splitAt (I# n#) ls | isTrue# (n# <# 0#) = ([], ls) | otherwise = splitAt# n# ls where splitAt# :: Int# -> [a] -> ([a], [a]) splitAt# 0# xs = ([], xs) splitAt# _ xs@[] = (xs, xs) splitAt# m# (x:xs) = (x:xs', xs'') where (xs', xs'') = splitAt# (m# -# 1#) xs span :: (a -> Bool) -> [a] -> ([a],[a]) span _ xs@[] = (xs, xs) span p xs@(x:xs') | p x = let (ys,zs) = span p xs' in (x:ys,zs) | otherwise = ([],xs) break :: (a -> Bool) -> [a] -> ([a],[a]) -- HBC version (stolen) break _ xs@[] = (xs, xs) break p xs@(x:xs') | p x = ([],xs) | otherwise = let (ys,zs) = break p xs' in (x:ys,zs) reverse :: [a] -> [a] reverse l = rev l [] where rev [] a = a rev (x:xs) a = rev xs (x:a) and :: [Bool] -> Bool or :: [Bool] -> Bool and [] = True and (x:xs) = x && and xs or [] = False or (x:xs) = x || or xs {-# NOINLINE [1] and #-} {-# NOINLINE [1] or #-} {-# RULES "and/build" forall (g::forall b.(Bool->b->b)->b->b) . and (build g) = g (&&) True "or/build" forall (g::forall b.(Bool->b->b)->b->b) . or (build g) = g (||) False #-} -- | Map a function over a list and concatenate the results. concatMap :: (a -> [b]) -> [a] -> [b] concatMap f = foldr ((++) . f) [] -- | Concatenate a list of lists. concat :: [[a]] -> [a] concat = foldr (++) [] {-# NOINLINE [1] concat #-} {-# RULES "concat" forall xs. concat xs = build (\c n -> foldr (\x y -> foldr c y x) n xs) -- We don't bother to turn non-fusible applications of concat back into concat #-} errorEmptyList :: String -> a errorEmptyList fun = error (prel_list_str ++ fun ++ ": empty list") prel_list_str :: String prel_list_str = "Prelude." inits :: [a] -> [[a]] inits xs = [] : case xs of [] -> [] x : xs' -> map (x :) (inits xs')
nomeata/list-fusion-lab
ListImpls/FusingFoldl.hs
bsd-3-clause
12,278
0
12
4,406
3,759
2,047
1,712
257
3
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} module Finance.Exchange.Balance ( Balance ) where -- import Control.Lens import Finance.Exchange.Types import Prelude hiding ((+)) data Balance market = Balance { _balanceMoney :: MonoidalMap (Client market) (Money market) , _balanceInstruments :: MonoidalMap (Client market, InstrumentId market) (Money market) } -- makeLenses ''Balance deriving instance (Show (Money market), Show (InstrumentId market), Show (Amount market), Show (Client market)) => Show (Balance market) deriving instance (Eq (Money market), Eq (InstrumentId market), Eq (Amount market), Eq (Client market)) => Eq (Balance market) {- instance ( AdditiveMapReq (Client market) (Money market) , AdditiveMapReq (Client market, InstrumentId market) (Money market) ) => Additive (Balance market) where l + r = Balance { _balanceMoney = l^.balanceMoney + r^.balanceMoney , _balanceInstruments = l^.balanceInstruments + r^.balanceInstruments } sinnum1p n m = Balance { _balanceMoney = sinnum1p n m^.balanceMoney , _balanceInstruments = sinnum1p n m^.balanceInstruments } instance ( Additive (Money market) , AdditiveMapReq (Client market) (Money market) , AdditiveMapReq (Client market, InstrumentId market) (Money market) , LeftModule Natural (Money market) ) => LeftModule Natural (Balance market) where r .* m = Balance { _balanceMoney = r .* m^.balanceMoney , _balanceInstruments = r .* m^.balanceInstruments } instance ( Additive (Money market) , AdditiveMapReq (Client market) (Money market) , AdditiveMapReq (Client market, InstrumentId market) (Money market) , RightModule Natural (Money market) ) => RightModule Natural (Balance market) where m *. r = Balance { _balanceMoney = m^.balanceMoney *. r , _balanceInstruments = m^.balanceInstruments *. r } instance ( Monoidal (Money market) , AdditiveMapReq (Client market) (Money market) , AdditiveMapReq (Client market, InstrumentId market) (Money market) ) => Monoidal (Balance market) where zero = Balance { _balanceMoney = zero, _balanceInstruments = zero } sinnum n m = Balance { _balanceMoney = sinnum n m^.balanceMoney , _balanceInstruments = sinnum n m^.balanceInstruments } -- toPortfolioReps :: Balance market -> [(Client market, PortfolioRep market)] -- toPortfolioReps ballance = undefined -- toList $ mergeWithKey undefined undefined undefined (ballance^.balanceMoney) (ballance^.balanceInstruments) -}
schernichkin/exchange
src/Finance/Exchange/Balance.hs
bsd-3-clause
2,909
0
11
697
230
128
102
15
0
----------------------------------------------------------------------------- -- | -- Module : Network.HTTP.Stream -- Copyright : (c) Warrick Gray 2002, Bjorn Bringert 2003-2005, 2007 Robin Bate Boerop -- License : BSD -- -- Maintainer : Sigbjorn Finne <[email protected]> -- Stability : experimental -- Portability : non-portable (not tested) -- -- Transmitting HTTP requests and responses holding @String@ in their payload bodies. -- This is one of the implementation modules for the "Network.HTTP" interface, representing -- request and response content as @String@s and transmitting them in non-packed form -- (cf. "Network.HTTP.HandleStream" and its use of @ByteString@s.) over 'Stream' handles. -- It is mostly here for backwards compatibility, representing how requests and responses -- were transmitted up until the 4.x releases of the HTTP package. -- -- For more detailed information about what the individual exports do, please consult -- the documentation for "Network.HTTP". /Notice/ however that the functions here do -- not perform any kind of normalization prior to transmission (or receipt); you are -- responsible for doing any such yourself, or, if you prefer, just switch to using -- "Network.HTTP" function instead. -- ----------------------------------------------------------------------------- module Network.HTTP.Stream ( module Network.Stream , simpleHTTP -- :: Request_String -> IO (Result Response_String) , simpleHTTP_ -- :: Stream s => s -> Request_String -> IO (Result Response_String) , sendHTTP -- :: Stream s => s -> Request_String -> IO (Result Response_String) , sendHTTP_notify -- :: Stream s => s -> Request_String -> IO () -> IO (Result Response_String) , receiveHTTP -- :: Stream s => s -> IO (Result Request_String) , respondHTTP -- :: Stream s => s -> Response_String -> IO () ) where ----------------------------------------------------------------- ------------------ Imports -------------------------------------- ----------------------------------------------------------------- import Network.Stream import Network.StreamDebugger (debugStream) import Network.TCP (openTCPPort) import Network.BufferType ( stringBufferOp ) import Network.HTTP.Base import Network.HTTP.Headers import Network.HTTP.Utils ( trim ) import Data.Char (toLower) import Data.Maybe (fromMaybe) import Control.Monad (when) -- Turn on to enable HTTP traffic logging debug :: Bool debug = False -- File that HTTP traffic logs go to httpLogFile :: String httpLogFile = "http-debug.log" ----------------------------------------------------------------- ------------------ Misc ----------------------------------------- ----------------------------------------------------------------- -- | Simple way to transmit a resource across a non-persistent connection. simpleHTTP :: Request_String -> IO (Result Response_String) simpleHTTP r = do auth <- getAuth r c <- openTCPPort (host auth) (fromMaybe 80 (port auth)) simpleHTTP_ c r -- | Like 'simpleHTTP', but acting on an already opened stream. simpleHTTP_ :: Stream s => s -> Request_String -> IO (Result Response_String) simpleHTTP_ s r | not debug = sendHTTP s r | otherwise = do s' <- debugStream httpLogFile s sendHTTP s' r sendHTTP :: Stream s => s -> Request_String -> IO (Result Response_String) sendHTTP conn rq = sendHTTP_notify conn rq (return ()) sendHTTP_notify :: Stream s => s -> Request_String -> IO () -> IO (Result Response_String) sendHTTP_notify conn rq onSendComplete = do when providedClose $ (closeOnEnd conn True) catchIO (sendMain conn rq onSendComplete) (\e -> do { close conn; ioError e }) where providedClose = findConnClose (rqHeaders rq) -- From RFC 2616, section 8.2.3: -- 'Because of the presence of older implementations, the protocol allows -- ambiguous situations in which a client may send "Expect: 100- -- continue" without receiving either a 417 (Expectation Failed) status -- or a 100 (Continue) status. Therefore, when a client sends this -- header field to an origin server (possibly via a proxy) from which it -- has never seen a 100 (Continue) status, the client SHOULD NOT wait -- for an indefinite period before sending the request body.' -- -- Since we would wait forever, I have disabled use of 100-continue for now. sendMain :: Stream s => s -> Request_String -> IO () -> IO (Result Response_String) sendMain conn rqst onSendComplete = do --let str = if null (rqBody rqst) -- then show rqst -- else show (insertHeader HdrExpect "100-continue" rqst) writeBlock conn (show rqst) -- write body immediately, don't wait for 100 CONTINUE writeBlock conn (rqBody rqst) onSendComplete rsp <- getResponseHead conn switchResponse conn True False rsp rqst -- reads and parses headers getResponseHead :: Stream s => s -> IO (Result ResponseData) getResponseHead conn = do lor <- readTillEmpty1 stringBufferOp (readLine conn) return $ lor >>= parseResponseHead -- Hmmm, this could go bad if we keep getting "100 Continue" -- responses... Except this should never happen according -- to the RFC. switchResponse :: Stream s => s -> Bool {- allow retry? -} -> Bool {- is body sent? -} -> Result ResponseData -> Request_String -> IO (Result Response_String) switchResponse _ _ _ (Left e) _ = return (Left e) -- retry on connreset? -- if we attempt to use the same socket then there is an excellent -- chance that the socket is not in a completely closed state. switchResponse conn allow_retry bdy_sent (Right (cd,rn,hdrs)) rqst = case matchResponse (rqMethod rqst) cd of Continue | not bdy_sent -> {- Time to send the body -} do { val <- writeBlock conn (rqBody rqst) ; case val of Left e -> return (Left e) Right _ -> do { rsp <- getResponseHead conn ; switchResponse conn allow_retry True rsp rqst } } | otherwise -> {- keep waiting -} do { rsp <- getResponseHead conn ; switchResponse conn allow_retry bdy_sent rsp rqst } Retry -> {- Request with "Expect" header failed. Trouble is the request contains Expects other than "100-Continue" -} do { writeBlock conn (show rqst ++ rqBody rqst) ; rsp <- getResponseHead conn ; switchResponse conn False bdy_sent rsp rqst } Done -> do when (findConnClose hdrs) (closeOnEnd conn True) return (Right $ Response cd rn hdrs "") DieHorribly str -> do close conn return $ responseParseError "sendHTTP" ("Invalid response: " ++ str) ExpectEntity -> let tc = lookupHeader HdrTransferEncoding hdrs cl = lookupHeader HdrContentLength hdrs in do { rslt <- case tc of Nothing -> case cl of Just x -> linearTransfer (readBlock conn) (read x :: Int) Nothing -> hopefulTransfer stringBufferOp {-null (++) []-} (readLine conn) [] Just x -> case map toLower (trim x) of "chunked" -> chunkedTransfer stringBufferOp (readLine conn) (readBlock conn) _ -> uglyDeathTransfer "sendHTTP" ; case rslt of Left e -> close conn >> return (Left e) Right (ftrs,bdy) -> do when (findConnClose (hdrs++ftrs)) (closeOnEnd conn True) return (Right (Response cd rn (hdrs++ftrs) bdy)) } -- | Receive and parse a HTTP request from the given Stream. Should be used -- for server side interactions. receiveHTTP :: Stream s => s -> IO (Result Request_String) receiveHTTP conn = getRequestHead >>= processRequest where -- reads and parses headers getRequestHead :: IO (Result RequestData) getRequestHead = do { lor <- readTillEmpty1 stringBufferOp (readLine conn) ; return $ lor >>= parseRequestHead } processRequest (Left e) = return $ Left e processRequest (Right (rm,uri,hdrs)) = do -- FIXME : Also handle 100-continue. let tc = lookupHeader HdrTransferEncoding hdrs cl = lookupHeader HdrContentLength hdrs rslt <- case tc of Nothing -> case cl of Just x -> linearTransfer (readBlock conn) (read x :: Int) Nothing -> return (Right ([], "")) -- hopefulTransfer "" Just x -> case map toLower (trim x) of "chunked" -> chunkedTransfer stringBufferOp (readLine conn) (readBlock conn) _ -> uglyDeathTransfer "receiveHTTP" return $ do (ftrs,bdy) <- rslt return (Request uri rm (hdrs++ftrs) bdy) -- | Very simple function, send a HTTP response over the given stream. This -- could be improved on to use different transfer types. respondHTTP :: Stream s => s -> Response_String -> IO () respondHTTP conn rsp = do writeBlock conn (show rsp) -- write body immediately, don't wait for 100 CONTINUE writeBlock conn (rspBody rsp) return ()
astro/HTTPbis
Network/HTTP/Stream.hs
bsd-3-clause
10,346
22
29
3,359
1,779
909
870
131
10
module Language.Modelica.Parser.Modification where import Language.Modelica.Syntax.Modelica import Language.Modelica.Parser.Parser (Parser) import Language.Modelica.Parser.Lexer import Language.Modelica.Parser.Basic import Language.Modelica.Parser.Expression import Language.Modelica.Parser.Utility (eitherOr, eitherOrOr) import Control.Applicative (liftA, liftA2, liftA3, (*>), (<$>), (<*>)) import Text.ParserCombinators.Parsec ((<|>), optionMaybe) modification :: Parser Modification modification = liftA ModificationAssign (assign *> expression) <|> liftA ModificationColonAssign (colon_assign *> expression) <|> liftA2 Modification class_modification (optionMaybe (assign *> expression)) class_modification :: Parser ClassModification class_modification = liftA ClassModification (parens $ optionMaybe argument_list) argument_list :: Parser ArgumentList argument_list = liftA2 ArgumentList argument (commaList argument) argument :: Parser Argument argument = liftA ArgElementRedeclaration element_redeclaration <|> liftA ArgElementModOrRep element_modification_or_replacable element_modification_or_replacable :: Parser ElementModOrRep element_modification_or_replacable = liftA3 ElementModOrRep (optionMaybe each_) (optionMaybe final_) (element_modification `eitherOr` element_replaceable) element_modification :: Parser ElementModification element_modification = liftA3 ElementModification name (optionMaybe modification) (optionMaybe string_comment) element_redeclaration :: Parser ElementRedeclaration element_redeclaration = liftA3 ElementRedeclaration (redeclare_ *> optionMaybe each_) (optionMaybe final_) (eitherOrOr short_class_definition component_clause1 element_replaceable) element_replaceable :: Parser ElementReplaceableShort element_replaceable = liftA2 ElementReplaceableShort (replaceable_ *> (short_class_definition `eitherOr` component_clause1)) (optionMaybe constraining_clause) short_class_definition :: Parser ShortClassDefinition short_class_definition = liftA3 ShortClassDefinition class_prefixes ident (assign *> (short_class_def_1 <|> short_class_def_2)) short_class_def_1 :: Parser ShortClassDef short_class_def_1 = liftA2 ShortClassDef1 (enumeration_ *> enum_list_or_colon) comment enum_list_or_colon :: Parser (Either Colon (Maybe EnumList)) enum_list_or_colon = parens $ colon `eitherOr` optionMaybe enum_list enum_list :: Parser EnumList enum_list = liftA2 EnumList enumeration_literal (commaList enumeration_literal) enumeration_literal :: Parser EnumerationLiteral enumeration_literal = liftA2 EnumerationLiteral ident comment short_class_def_2 :: Parser ShortClassDef short_class_def_2 = ShortClassDef2 <$> base_prefix <*> name <*> (optionMaybe array_subscripts) <*> (optionMaybe class_modification) <*> comment component_clause1 :: Parser ComponentClause1 component_clause1 = liftA3 ComponentClause1 type_prefix type_specifier component_declaration1 component_declaration1 :: Parser ComponentDeclaration1 component_declaration1 = liftA2 ComponentDeclaration1 declaration comment extends_clause :: Parser ExtendsClause extends_clause = liftA3 ExtendsClause (extends_ *> name) (optionMaybe class_modification) (optionMaybe annotation) constraining_clause :: Parser ConstrainingClause constraining_clause = liftA2 ConstrainingClause (constrainedby_ *> name) (optionMaybe class_modification) declaration :: Parser Declaration declaration = liftA3 Declaration ident (optionMaybe array_subscripts) (optionMaybe modification) annotation :: Parser Annotation annotation = liftA Annotation (annotation_ *> class_modification) comment :: Parser Comment comment = liftA2 Comment (optionMaybe string_comment) (optionMaybe annotation)
xie-dongping/modelicaparser
src/Language/Modelica/Parser/Modification.hs
bsd-3-clause
3,801
0
10
457
824
442
382
92
1
{-# OPTIONS_GHC -cpp -XExistentialQuantification -XDeriveDataTypeable -XOverloadedStrings #-} -------------------------------------------------------------------- -- | -- Module : MediaWiki.API -- Description : A Haskell MediaWiki API binding -- Copyright : (c) Sigbjorn Finne, 2008 -- License : BSD3 -- -- Maintainer: Sigbjorn Finne <[email protected]> -- Stability : provisional -- Portability: portable -- -- A Haskell MediaWiki API binding. -- -------------------------------------------------------------------- module MediaWiki.API ( module MediaWiki.API , URLString ) where import MediaWiki.API.Base import MediaWiki.API.Types import MediaWiki.API.Output import MediaWiki.Util.Fetch as Fetch import Codec.MIME.Type import MediaWiki.API.Query.SiteInfo.Import as SI import MediaWiki.API.Action.Login.Import as Login import Data.Maybe import Data.Text (unpack) import Control.Exception as CE import Data.Typeable import MediaWiki.API.Utils import Text.XML.Light.Types import Control.Monad -- | @webGet url req@ issues a GET to a MediaWiki server, appending -- @api.php?@ followed by the request @req@ to the URL base @url@. webGet :: URLString -> Request -> IO String webGet url req = do let url_q = url ++ "api.php?" ++ showRequest req -- print url_q readContentsURL url_q -- | @webGet mbUser url req@ issues a POST to a MediaWiki server, appending -- @api.php?@ followed by the request @req@ to the URL base @url@. webPost :: Maybe Fetch.AuthUser -> URLString -> String -> Request -> IO ([(String,String)], String) webPost mbUser url act req = do let url_q = url ++ "api.php?action="++act let pload = showRequest req (_cookiesOut, hs, p) <- postContentsURL mbUser url_q [ ("Content-Length", show $ length pload) , ("Content-Type", unpack $ showMIMEType form_mime_ty) ] [{-no cookies..-}] pload return (hs, p) where form_mime_ty = Application "x-www-form-urlencoded" webPostXml :: (String -> Either (String,[String]) a) -> Maybe Fetch.AuthUser -> URLString -> String -> Request -> IO (Maybe a) webPostXml p mbUser url act req = do (_hs,mb) <- webPost mbUser url act req case mb of "" -> return Nothing ls -> do case p ls of Left (x,errs) -> case parseError ls of Right e -> throwMWError e _ -> putStrLn (x ++ ':':' ':unlines errs) >> return Nothing Right x -> return (Just x) webGetXml :: (String -> Either (String,[String]) a) -> URLString -> Request -> IO (Maybe a) webGetXml p url req = do ls <- webGet url req case p ls of Left (x,errs) -> case parseError ls of Right e -> throwMWError e _ -> putStrLn (x ++ ':':' ':unlines errs) >> return Nothing Right x -> return (Just x) queryPage :: PageName -> QueryRequest queryPage pg = emptyQuery{quTitles=[pg]} mkQueryAction :: APIRequest a => QueryRequest -> a -> Action mkQueryAction q qr = case queryKind qr of QProp s -> Query q{quProps=(PropKind s):quProps q} (toReq qr) QList s -> Query q{quLists=(ListKind s):quLists q} (toReq qr) QMeta s -> Query q{quMetas=(MetaKind s):quMetas q} (toReq qr) QGen s -> Query q{quGenerator=(Just (GeneratorKind s))} (toReq qr) -- | @loginWiki u usr pass@ logs in to MediaWiki install at @url@ as -- user @usr@ with password credentials @pass@. Notice that we don't -- presently allow HTTP Auth to happen in conjunction with the Wiki -- login. loginWiki :: URLString -> String -> String -> IO (Maybe LoginResponse) loginWiki url usr pwd = webPostXml Login.stringXml Nothing url "login" req where req = emptyXmlRequest (Login (emptyLogin usr pwd)) queryInfo :: URLString -> PageName -> IO String queryInfo url pgName = webGet url req where req = emptyXmlRequest (mkQueryAction (queryPage pgName) infoRequest) querySiteIWInfo :: URLString -> IO (Maybe SiteInfoResponse) querySiteIWInfo url = webGetXml SI.stringXml url req where req = emptyXmlRequest (mkQueryAction (queryPage "XP") siteInfoRequest{siProp=["interwikimap"]}) queryLangPage :: URLString -> PageName -> Maybe String -> IO String queryLangPage url pgName mb = webGet url req where req = emptyXmlRequest (mkQueryAction (queryPage pgName) langLinksRequest{llContinueFrom=mb}) parseError :: String -> Either (String,[{-Error msg-}String]) MediaWikiError parseError s = parseDoc xmlError s xmlError :: Element -> Maybe MediaWikiError xmlError e = do guard (elName e == nsName "api") let es1 = children e p <- pNode "error" es1 return mwError{ mwErrorCode = fromMaybe "" $ pAttr "code" p , mwErrorInfo = fromMaybe "" $ pAttr "info" p } -- MW exceptions/errors: data MediaWikiError = MediaWikiError { mwErrorCode :: String , mwErrorInfo :: String } deriving ( Typeable ) mwError :: MediaWikiError mwError = MediaWikiError{mwErrorCode="",mwErrorInfo=""} data SomeMWException = forall e . Exception e => SomeMWException e deriving Typeable instance Show SomeMWException where show (SomeMWException e) = show e instance Exception SomeMWException mwToException :: Exception e => e -> SomeException mwToException = toException . SomeMWException mwFromException :: Exception e => SomeException -> Maybe e mwFromException x = do SomeMWException a <- fromException x cast a instance Exception MediaWikiError where toException = mwToException fromException = mwFromException throwMWError :: MediaWikiError -> IO a throwMWError e = throwIO e catchMW :: IO a -> (MediaWikiError -> IO a) -> IO a catchMW f hdlr = CE.catch f (\ e1 -> hdlr e1) handleMW :: (MediaWikiError -> IO a) -> IO a -> IO a handleMW h e = catchMW e h tryMW :: IO a -> IO (Either MediaWikiError a) tryMW f = handleMW (\ x -> return (Left x)) (f >>= return.Right) instance Show MediaWikiError where show x = unlines ( [ "MediaWiki error:" , "" , " Code: " ++ mwErrorCode x , " Info: " ++ mwErrorInfo x ])
DanielG/haskell-mediawiki
MediaWiki/API.hs
bsd-3-clause
6,075
24
23
1,312
1,842
950
892
-1
-1
module Opaleye.TF.Scope where data Scope = Z | S Scope
ocharles/opaleye-tf
src/Opaleye/TF/Scope.hs
bsd-3-clause
56
0
6
11
19
12
7
2
0
{-| Module: Data.Astro.Effects.Nutation Description: Calculation effects of nutation Copyright: Alexander Ignatyev, 2016 Calculation effects of nutation. -} module Data.Astro.Effects.Nutation ( nutationLongitude , nutationObliquity ) where import qualified Data.Astro.Utils as U import Data.Astro.Types (DecimalDegrees(..), toRadians, fromDMS) import Data.Astro.Time.JulianDate (JulianDate, numberOfCenturies) import Data.Astro.Time.Epoch (j1900) -- | Calculates the nutation on the ecliptic longitude at the given JulianDate nutationLongitude :: JulianDate -> DecimalDegrees nutationLongitude jd = let t = numberOfCenturies j1900 jd l = sunMeanLongutude t omega = moonNode t dPsi = -17.2*(sin omega) - 1.3*(sin $ 2*l) in fromDMS 0 0 dPsi -- | Calculates the nutation on the obliquity of the ecliptic at the given JulianDate nutationObliquity :: JulianDate -> DecimalDegrees nutationObliquity jd = let t = numberOfCenturies j1900 jd l = sunMeanLongutude t omega = moonNode t dEps = 9.2*(cos omega) + 0.5*(cos $ 2*l) in fromDMS 0 0 dEps -- | It takes a number of centuries and returns the Sun's mean longitude in radians sunMeanLongutude :: Double -> Double sunMeanLongutude t = let a = 100.002136 * t in U.toRadians $ U.reduceToZeroRange 360 $ 279.6967 + 360 * (a - int a) -- | It takes a number of centuries and returns the Moon's node in radians moonNode :: Double -> Double moonNode t = let b = 5.372617 * t in U.toRadians $ U.reduceToZeroRange 360 $ 259.1833 - 360*(b - int b) -- | 'round' function that returns Double int :: Double -> Double int = fromIntegral . round
Alexander-Ignatyev/astro
src/Data/Astro/Effects/Nutation.hs
bsd-3-clause
1,644
0
13
312
409
221
188
32
1
module GameStage.Player ( Player (..) , player , update , render , hit , gameOver , shoot ) where import Graphics.Rendering.OpenGL (GLfloat) import Data.Complex import GameStage.GameObject import KeyBind import qualified Class.Sprite as SP import Internal.Texture import qualified GameStage.Bullet as B data State = Normal | Invincible Int | Dead Int deriving Eq data Player = Player { object :: GameObject , state :: State , age :: Int , moveSpeed :: Complex GLfloat , shootSpan :: Int , remaining :: Int } deriving (Eq) instance HaveGameObject Player where gameObject (Player {object = object}) = object spawnPoint = 200 :+ 300 update :: Keyset -> Player -> Player update key player@( Player obj@(GameObject { pos = pos }) s a moveSpeed _ _) = player { object = obj {pos = newPos} , state = newS , age = a + 1 } where newPos = case s of Dead _ -> spawnPoint _ -> crop $ pos + dpos dpos = moveSpeed * (normalize . keysetToXY) key crop (x:+y) = (cx x :+ cy y) cx x | x < 100 = 100 | x > 700 = 700 | otherwise = x cy y | y < 100 = 100 | y > 500 = 500 | otherwise = y newS = case s of Dead i | i <= 0 -> Invincible 120 | otherwise -> Dead (i-1) Invincible i | i <= 0 -> Normal | otherwise -> Invincible (i-1) x -> x normalize (x:+y) = case sqrt (x**2 + y**2) of 0 -> 0 n -> (x/n :+ y/n) hit :: Bool -> Player -> Player hit True p@Player { remaining = r } = case state p of Normal -> p { state = Dead (if r == 0 then maxBound else 120) , age = 0 , remaining = r - 1 } _ -> p hit _ p = p gameOver :: Player -> Bool gameOver Player { remaining = r } = r == 0 render :: Player -> IO () render p = do case state p of Dead _ -> return () Normal -> SP.render $ object p Invincible _ | age p `mod` 2 == 0 -> SP.render $ object p | otherwise -> return () shoot :: Bool -> Player -> (Maybe B.BulletType, Player) shoot trig p@Player { shootSpan = span } = (newB, newP) where t = case state p of Dead _ -> False _ -> trig newB = case t of False -> Nothing True | span `mod` 4 == 0 -> Just B.Normal | otherwise -> Nothing newP = p { shootSpan = if t then span+1 else 0 } player = do t <- loadTexture "res/player.png" let ta = TA t (1,1) [(0,0)] return $ Player (defaultGameObject { pos = spawnPoint , radius = 2 , size = 70 :+ 600 , gameTexture = Just ta , offset = 0 :+ (-255) }) Normal 0 4 0 4
c000/PaperPuppet
src/GameStage/Player.hs
bsd-3-clause
3,095
0
15
1,309
1,120
594
526
96
4
-- An abstract data type for performing multiple linear regression, -- using Repa as the backend for matrix operations. module Regression.Repa ( model_features, model_outputs, model_weights, model_predictions, model_rss, feature_mean, create_model, create_features, create_weights, predict, powers, gradient_descent, normalize ) where import Data.Array.Repa as Repa hiding ((++)) import Data.Array.Repa.Algorithms.Matrix (mmultP) import Data.List hiding (transpose) import Data.Maybe (fromJust) import Debug.Trace (trace) import Stat (range, mean, stdev) -- A model is: -- * a feature matrix -- * a feature vector representing the observed output -- * a weight vector containing the calculated vector of optimized weights -- * the predicted outputs using the optimized weights -- * the data Model = MO { model_features :: FeatureMatrix, model_outputs :: FeatureVector, model_weights :: WeightVector, model_predictions :: FeatureVector, model_rss :: Double } deriving (Show) -- A two-dimensional matrix whose columns contain feature values. data FeatureMatrix = FM { fm_name_indexes:: [(String, Int)], fm_values :: (Array U DIM2 Double) } deriving (Show) -- A vector of values for a named feature. data FeatureVector = FV { fv_name :: String, fv_values :: (Array U DIM2 Double) } instance Show FeatureVector where show (FV name values) = name ++ " = " ++ show (toList values) type Feature a = (String, a -> Double) type Output a = (String, a -> Double) type Optimizer = FeatureMatrix -> FeatureVector -> WeightVector -- A vector of weights. Each weight corresponds to a feature in the -- feature matrix used to calculate the weights. data WeightVector = WV { wv_name_indexes :: [(String, Int)], wv_values :: (Array U DIM2 Double) } instance Show WeightVector where show (WV name_indexes values) = concatMap showWeight (zip name_indexes (toList values)) where showWeight ((name, i), value) = name ++ " = " ++ show value ++ "\n" -- Get the mean of a named feature in a feature matrix. feature_mean :: FeatureMatrix -> String -> Double feature_mean (FM name_indexes h) name = let i = fromJust $ Data.List.lookup name name_indexes column = slice h (Any :. (i::Int)) (Z:.j) = extent column [total] = sumAllP column in total/(fromIntegral j) -- Creates a model from a list of records, a list of features, and the output -- accessor function. This computes the weight vector as well. This function -- does not scale the features nor does it add an intercept feature (a feature -- whose values are all 1). create_model :: [a] -> [Feature a] -> Output a -> Optimizer -> Model create_model rows features (output_name, output) optimizer = let fmat = create_features features rows nn = length rows observations = FV output_name (fromListUnboxed (Z:.(nn::Int):.(1::Int)) (Data.List.map output rows)) --weights = gradient_descent fmat observations (create_weights fmat initial_weights) e n weights = optimizer fmat observations predictions = predict fmat weights residuals = rss observations predictions in MO fmat observations weights predictions residuals -- Multiplies a feature matrix by a weights vector to obtain a prediction of -- output. predict :: FeatureMatrix -> WeightVector -> FeatureVector predict (FM _ h) (WV _ w) = let [y'] = h `mmultP` w in FV "" y' -- Generates the feature matrix, usually denoted as H, with N rows and -- D features where D is the length of the feature list. create_features :: [Feature a] -> [a] -> FeatureMatrix create_features hs inputs = let n = length inputs d = length hs names = (Data.List.map fst hs) name_indexes = Prelude.zip names [0..] dat = [h(row) | row <- inputs, (_,h) <- hs] h = fromListUnboxed (Z:.n:.d) dat in FM name_indexes h -- Computes the residual sum of squares from the observed output and -- the predicted output. rss :: (Num a) => FeatureVector -> FeatureVector -> Double rss (FV _ v1) (FV _ v2) = rss' v1 v2 rss' :: Array U DIM2 Double -> Array U DIM2 Double -> Double rss' v1 v2 = let p = Repa.zipWith sq v1 v2 sq a b = (a - b)^2 [result] = foldAllP (+) 0 p in result -- Takes a list of numbers and turns them into a vector of weights. create_weights :: FeatureMatrix -> [Double] -> WeightVector create_weights (FM name_indexes h) weights = let (Z:.i:.j) = extent h in WV name_indexes $ computeS $ fromFunction (Z :. j :. 1) (\(Z:.j:.i) -> weights !! j :: Double) -- Performs gradient descent, updating the weights until the residual -- sum of squares is less than the epsilon value e, at which point the -- weight matrix w is returned. n is the step size. gradient_descent :: Double -> Double -> WeightVector -> Optimizer gradient_descent e n (WV name w) (FM _ f) (FV _ o) = let [ft] = computeP $ transpose f weights = gradient_descent' e n w f ft o in WV name weights gradient_descent' :: Double -> Double -> Array U DIM2 Double -> Array U DIM2 Double -> Array U DIM2 Double -> Array U DIM2 Double -> Array U DIM2 Double gradient_descent' e n w h ht y = let grad = gradient h ht y w -- (-2H^t(y-Hw)) grad_len = magnitude grad -- grad RSS(w) == ||2H^t(y-HW)|| --in if grad_len < e in if (trace ("gradient = " ++ show grad_len) grad_len) < e then w else let delta = Repa.map (*(-n)) grad -- (2nH^t(y-Hw)) [w'] = computeP $ w +^ delta -- in gradient_descent' e n w' h ht y -- Calculates the gradient of the residual sum of squares (-2H^t(y-Hw)). -- This is used to compute the magnitude of the gradient, to see if the -- function is minimized. It is also used to update the weights of the -- features. gradient :: Array U DIM2 Double -> Array U DIM2 Double -> Array U DIM2 Double -> Array U DIM2 Double -> Array U DIM2 Double gradient h ht y w = let [yhat] = h `mmultP` w [err] = computeP $ y -^ yhat [prod] = ht `mmultP` err [grad] = computeP $ Repa.map (*(-2)) prod in grad -- Compute the magnitude of the given vector. magnitude :: Array U DIM2 Double -> Double magnitude vec = let [total] = Repa.sumAllP $ Repa.map (\y -> y^2) vec in sqrt total -- Given a feature, computes polynomial powers of that feature from -- 1 (the original feature) up to and including n. powers :: (String, a -> Double) -> Int -> [(String, a -> Double)] powers (name, f) n = Data.List.map (\i -> (name ++ (show i), (\a -> (f a)^i))) [1..n] -- given a list of values and a feature, return a normalized version of that -- feature where the mean of the feature is subtracted from each feature and -- the result is divided by the standard deviation of the feature. normalize :: [a] -> (a -> Double) -> a -> Double normalize xs f = (/sdxs) . (+(-meanxs)) . f where meanxs = mean (Data.List.map f xs) sdxs = stdev (Data.List.map f xs)
markrgrant/regression
src/Regression/Repa.hs
bsd-3-clause
7,104
0
15
1,681
1,979
1,076
903
121
2
{-# LANGUAGE BangPatterns, CPP, ScopedTypeVariables #-} module Happstack.Server.Internal.Listen(listen, listen',listenOn,listenOnIPv4) where import Happstack.Server.Internal.Types (Conf(..), Request, Response) import Happstack.Server.Internal.Handler (request) import Happstack.Server.Internal.Socket (acceptLite) import Happstack.Server.Internal.TimeoutManager (cancel, initialize, register, forceTimeoutAll) import Happstack.Server.Internal.TimeoutSocket as TS import qualified Control.Concurrent.Thread.Group as TG import Control.Exception.Extensible as E import Control.Concurrent (forkIO, killThread, myThreadId) import Control.Monad import qualified Data.Maybe as Maybe import qualified Network.Socket as Socket import System.IO.Error (isFullError) import Foreign.C (CInt) {- #ifndef mingw32_HOST_OS -} import System.Posix.Signals {- #endif -} import System.Log.Logger (Priority(..), logM) log':: Priority -> String -> IO () log' = logM "Happstack.Server.HTTP.Listen" -- Meant to be TCP in practise. -- See https://www.gnu.org/software/libc/manual/html_node/Creating-a-Socket.html -- which says "zero is usually right". It could theoretically be SCTP, but it -- would be a bizarre system that defaults to SCTP over TCP. proto :: CInt proto = Socket.defaultProtocol {- Network.listenOn binds randomly to IPv4 or IPv6 or both, depending on system and local settings. Lets make it use IPv4 only for now. -} listenOn :: Int -> IO Socket.Socket listenOn portm = do E.bracketOnError (Socket.socket Socket.AF_INET Socket.Stream proto) (Socket.close) (\sock -> do Socket.setSocketOption sock Socket.ReuseAddr 1 Socket.bind sock (Socket.SockAddrInet (fromIntegral portm) iNADDR_ANY) Socket.listen sock (max 1024 Socket.maxListenQueue) return sock ) listenOnIPv4 :: String -- ^ IP address to listen on (must be an IP address not a host name) -> Int -- ^ port number to listen on -> IO Socket.Socket listenOnIPv4 ip portm = do hostAddr <- inet_addr ip E.bracketOnError (Socket.socket Socket.AF_INET Socket.Stream proto) (Socket.close) (\sock -> do Socket.setSocketOption sock Socket.ReuseAddr 1 Socket.bind sock (Socket.SockAddrInet (fromIntegral portm) hostAddr) Socket.listen sock (max 1024 Socket.maxListenQueue) return sock ) inet_addr :: String -> IO Socket.HostAddress inet_addr ip = do addrInfos <- Socket.getAddrInfo (Just Socket.defaultHints) (Just ip) Nothing let getHostAddress addrInfo = case Socket.addrAddress addrInfo of Socket.SockAddrInet _ hostAddress -> Just hostAddress _ -> Nothing maybe (fail "inet_addr: no HostAddress") pure . Maybe.listToMaybe $ Maybe.mapMaybe getHostAddress addrInfos iNADDR_ANY :: Socket.HostAddress iNADDR_ANY = 0 -- | Bind and listen port listen :: Conf -> (Request -> IO Response) -> IO () listen conf hand = do let port' = port conf lsocket <- listenOn port' Socket.setSocketOption lsocket Socket.KeepAlive 1 listen' lsocket conf hand -- | Use a previously bind port and listen listen' :: Socket.Socket -> Conf -> (Request -> IO Response) -> IO () listen' s conf hand = do {- #ifndef mingw32_HOST_OS -} void $ installHandler openEndedPipe Ignore Nothing {- #endif -} let port' = port conf fork = case threadGroup conf of Nothing -> forkIO Just tg -> \m -> fst `liftM` TG.forkIO tg m tm <- initialize ((timeout conf) * (10^(6 :: Int))) -- http:// loop log' NOTICE ("Listening for http:// on port " ++ show port') let eh (x::SomeException) = when ((fromException x) /= Just ThreadKilled) $ log' ERROR ("HTTP request failed with: " ++ show x) work (sock, hn, p) = do tid <- myThreadId thandle <- register tm (killThread tid) let timeoutIO = TS.timeoutSocketIO thandle sock request timeoutIO (logAccess conf) (hn,fromIntegral p) hand `E.catch` eh -- remove thread from timeout table cancel thandle Socket.close sock loop = forever $ do w <- acceptLite s fork $ work w pe e = log' ERROR ("ERROR in http accept thread: " ++ show e) infi :: IO () infi = loop `catchSome` pe >> infi infi `finally` (Socket.close s >> forceTimeoutAll tm) {-- #ifndef mingw32_HOST_OS -} void $ installHandler openEndedPipe Ignore Nothing {- #endif -} where -- why are these handlers needed? catchSome op h = op `E.catches` [ Handler $ \(e :: ArithException) -> h (toException e), Handler $ \(e :: ArrayException) -> h (toException e), Handler $ \(e :: IOException) -> if isFullError e then return () -- h (toException e) -- we could log the exception, but there could be thousands of them else throw e ]
Happstack/happstack-server
src/Happstack/Server/Internal/Listen.hs
bsd-3-clause
5,097
0
16
1,299
1,316
686
630
92
3
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} module Model where import Control.Applicative import Control.Monad (mzero) import qualified Data.Aeson as A import Data.Text import Data.Time.Clock (UTCTime) import Database.Persist import Database.Persist.Sqlite import Database.Persist.TH import GHC.Generics import Model.MatchStatus import Model.NaviStatus import Model.Role import Model.SlotStatus share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persist| User json name Text email Text password Text dept Department role Role Maybe UniqueUser email deriving Show Slot json slotName SlotName dept Department leader UserId Maybe members [UserId] UniqueSlot slotName deriving Show SlotSchedule json slotId SlotId date UTCTime driverId UserId Maybe status SlotStatus surrogate SlotSurrogate UniqueSlotSchedule surrogate deriving Show NavigatorSchedule json naviId UserId date UTCTime available Available Maybe status NaviStatus surrogate NaviSurrogate UniqueNavigatorSchedule surrogate deriving Show Match json date UTCTime slot SlotId driver UserId Maybe navigator UserId Maybe status MatchStatus deriving Show |] data Department = ATCQ | SCHA | DENKI deriving (Show, Read, Eq, Enum) data SlotName = ATCQ1 | ATCQ2 | ATCQ3 | SCHA1 | DENKI1 deriving (Show, Read, Eq, Enum) data Available = OK | NO deriving (Show, Read, Eq, Enum) type SlotSurrogate = (SlotId, UTCTime) type NaviSurrogate = (UserId, UTCTime) derivePersistField "Role" derivePersistField "Department" derivePersistField "SlotName" derivePersistField "SlotStatus" derivePersistField "Available" derivePersistField "NaviStatus" derivePersistField "MatchStatus" derivePersistField "SlotSurrogate" derivePersistField "NaviSurrogate" -- $(deriveJSON id ''Department) instance A.FromJSON Department where parseJSON (A.Object v) = read <$> (v A..: "dept") parseJSON _ = mzero instance A.ToJSON Department where toJSON ATCQ = A.object [ "dept" A..= ("ATCQ" :: String) ] toJSON SCHA = A.object [ "dept" A..= ("SCHA" :: String) ] toJSON DENKI = A.object [ "dept" A..= ("DENKI" :: String) ] instance A.FromJSON SlotName where parseJSON (A.Object v) = read <$> (v A..: "slotName") parseJSON _ = mzero instance A.ToJSON SlotName where toJSON ATCQ1 = A.object [ "slotName" A..= ("ATCQ1" :: String) ] toJSON ATCQ2 = A.object [ "slotName" A..= ("ATCQ2" :: String) ] toJSON ATCQ3 = A.object [ "slotName" A..= ("ATCQ3" :: String) ] toJSON SCHA1 = A.object [ "slotName" A..= ("SCHA1" :: String) ] toJSON DENKI1 = A.object [ "slotName" A..= ("DENKI1" :: String) ] instance A.FromJSON Available where parseJSON (A.Object v) = read <$> (v A..: "available") parseJSON _ = mzero instance A.ToJSON Available where toJSON OK = A.object [ "available" A..= ("OK" :: String) ] toJSON NO = A.object [ "available" A..= ("NO" :: String) ]
takei-shg/Magpie
Model.hs
bsd-3-clause
3,497
0
9
886
747
404
343
66
0
{-# LANGUAGE TupleSections #-} module Data.Tuples where import Control.Applicative import Data.Foldable import Data.Traversable -- 3-tuples fst3 :: (a, b, c) -> a fst3 (x, _, _) = x snd3 :: (a, b, c) -> b snd3 (_, y, _) = y trd3 :: (a, b, c) -> c trd3 (_, _, z) = z instance Functor ((,,) a b) where fmap f (a, b, c) = (a, b, f c) instance Foldable ((,,) a b) where foldMap f = f . trd3 instance Traversable ((,,) a b) where traverse f (a, b, c) = (a, b,) <$> f c
sebastiaanvisser/fixpoints
src/Data/Tuples.hs
bsd-3-clause
479
0
8
114
264
154
110
17
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} module File.Create ( tCreateDevice , tCreateLink ) where import qualified Data.ByteString.Char8 as B import System.Fuse import Data.Maybe (catMaybes) import System.Posix.Types (FileMode, DeviceID) import System.FilePath.Posix (splitExtension, addExtension) import Debug (dbg) import DB.Base import DB.Read (fileEntityNamed, fileEntityFromPath) import DB.Write import File.Util (tagFile) -- move to DB.Write? import File.Version (versionedFileName) import Parse import Stat.Base (dirStat, fileStat) import Types {- | Doesn't actually create a link. Instead, it adds tags to an existing file. -} tCreateLink ∷ DB → FilePath → FilePath → IO Errno tCreateLink db fromPath toPath = do dbg $ "CreateLink: " ++ fromPath ++ ", " ++ toPath -- What we want is for fromPath and toPath to be: -- + alike in name, but -- + different in tags. if pathsDiffer && namesMatch -- Add toTags which file may currently lack. then do maybeFileEntity ← fileEntityFromPath db fromPath case maybeFileEntity of Nothing → return eNOENT Just (FileEntity fileId _) → do tagFile db fileId toTags return eOK else return eINVAL -- eINVAL | ePERM | eACCES -- eACCES - permission denied -- eINVAL - invalid argument -- ePERM - operation not permitted -- http://www.virtsync.com/c-error-codes-include-errno where pathsDiffer = fromPath /= toPath namesMatch = maybeFromName == maybeToName (fromTags, maybeFromName) = parseFilePath fromPath (toTags, maybeToName) = parseFilePath toPath ---------------------------- {- | If asked to create a RegularFile, create an empty one w/ provided mode & return eOK. If some other type of device: eNOENT. TODO: If fileName is already found among existing files, then append suffix to end of filename (before extension). e.g.: foo.txt ⇒ foo(1).txt -} tCreateDevice ∷ DB → FilePath -- FilePath ~ String → EntryType -- FUSE: Unix FS node type (RegularFile | Directory | …) → FileMode -- System.Posix.Types → DeviceID -- System.Posix.Types → IO Errno -- Foreign.C.Error tCreateDevice db filePath entryType mode deviceId = do dbg $ "CreateDevice, path: " ++ filePath ++ ", entryType: " ++ show entryType case entryType of RegularFile → case maybeFileName of Nothing → return eNOENT Just n → do fileId ← createNewFile db n mode tagFile db fileId tagNames return eOK where (tagNames, maybeFileName) = parseFilePath filePath _ → do dbg $ "Failed to create unknown device type with path: " ++ filePath return eNOENT --------------------- createNewFile ∷ DB → FileName → FileMode → IO FileId createNewFile db name mode = do -- TODO: Store stat info w/ file. ctx ← getFuseContext let newStat = (fileStat ctx) { statFileMode = mode } name' ← versionedFileName db name mkFile db (File name' B.empty) newFileIdFromName db name' newFileIdFromName ∷ DB → FileName → IO FileId newFileIdFromName db name = do maybeFileEntity ← fileEntityNamed db name case maybeFileEntity of Nothing → error "We just created the file; should exist." Just (FileEntity fileId (File _ _)) → return fileId
marklar/TagFS
src/File/Create.hs
bsd-3-clause
3,739
0
16
1,104
691
359
332
70
3
----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.MessageFeedback -- Description : An alternative @sendMessage@. -- Copyright : (c) -- Quentin Moser <[email protected]> -- 2018 Yclept Nemo -- License : BSD3 -- -- Maintainer : orphaned -- Stability : unstable -- Portability : unportable -- -- Alternative to 'XMonad.Operations.sendMessage' that provides knowledge -- of whether the message was handled, and utility functions based on -- this facility. ----------------------------------------------------------------------------- module XMonad.Actions.MessageFeedback ( -- * Usage -- $usage -- * Messaging variants -- ** 'SomeMessage' sendSomeMessageB, sendSomeMessage , sendSomeMessageWithNoRefreshB, sendSomeMessageWithNoRefresh , sendSomeMessageWithNoRefreshToCurrentB, sendSomeMessageWithNoRefreshToCurrent -- ** 'Message' , sendMessageB , sendMessageWithNoRefreshB , sendMessageWithNoRefreshToCurrentB, sendMessageWithNoRefreshToCurrent -- * Utility Functions -- ** Send All , sendSomeMessagesB, sendSomeMessages, sendMessagesB, sendMessages -- ** Send Until , tryInOrderB, tryInOrderWithNoRefreshToCurrentB, tryInOrderWithNoRefreshToCurrent , tryMessageB, tryMessageWithNoRefreshToCurrentB, tryMessageWithNoRefreshToCurrent -- ** Aliases , sm -- * Backwards Compatibility -- $backwardsCompatibility , send, sendSM, sendSM_ , tryInOrder, tryInOrder_ , tryMessage, tryMessage_ ) where import XMonad ( Window ) import XMonad.Core ( X(), Message, SomeMessage(..), LayoutClass(..), windowset, catchX, WorkspaceId, Layout, whenJust ) import XMonad.Operations ( updateLayout, windowBracket, modifyWindowSet ) import XMonad.Prelude ( isJust, liftA2, void ) import XMonad.StackSet ( Workspace, current, workspace, layout, tag ) import Control.Monad.State ( gets ) -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Actions.MessageFeedback -- -- You can then use this module's functions wherever an action is expected. All -- feedback variants are supported: -- -- * message to any workspace with no refresh -- * message to current workspace with no refresh -- * message to current workspace with refresh -- -- Except "message to any workspace with refresh" which makes little sense. -- -- Note that most functions in this module have a return type of @X Bool@ -- whereas configuration options will expect a @X ()@ action. For example, the -- key binding: -- -- > -- Shrink the master area of a tiled layout, or move the focused window -- > -- to the left in a WindowArranger-based layout -- > ((modKey, xK_Left), tryMessageWithNoRefreshToCurrentB Shrink (MoveLeft 50)) -- -- is mis-typed. For this reason, this module provides alternatives (not ending -- with an uppercase \"B\", e.g. 'XMonad.Operations.sendMessage' rather than -- 'sendMessageB') that discard their boolean result and return an @X ()@. For -- example, to correct the previous example: -- -- > ((modKey, xK_Left), tryMessageWithNoRefreshToCurrent Shrink (MoveLeft 50)) -- -- This module also provides 'SomeMessage' variants of each 'Message' function -- for when the messages are of differing types (but still instances of -- 'Message'). First box each message using 'SomeMessage' or the convenience -- alias 'sm'. Then, for example, to send each message: -- -- > sendSomeMessages [sm messageOfTypeA, sm messageOfTypeB] -- -- This is /not/ equivalent to the following example, which will not refresh -- the workspace unless the last message is handled: -- -- > sendMessageWithNoRefreshToCurrent messageOfTypeA >> sendMessage messageOfTypeB -- | Variant of 'XMonad.Operations.sendMessage'. Accepts 'SomeMessage'; to use -- 'Message' see 'sendMessageB'. Returns @True@ if the message was handled, -- @False@ otherwise. Instead of using 'sendSomeMessageWithNoRefreshToCurrentB' -- for efficiency this is pretty much an exact copy of the -- 'XMonad.Operations.sendMessage' code - foregoes the O(n) 'updateLayout'. sendSomeMessageB :: SomeMessage -> X Bool sendSomeMessageB m = windowBracket id $ do w <- gets ((workspace . current) . windowset) ml <- handleMessage (layout w) m `catchX` return Nothing whenJust ml $ \l -> modifyWindowSet $ \ws -> ws { current = (current ws) { workspace = (workspace $ current ws) { layout = l }}} return $ isJust ml -- | Variant of 'sendSomeMessageB' that discards the result. sendSomeMessage :: SomeMessage -> X () sendSomeMessage = void . sendSomeMessageB -- | Variant of 'XMonad.Operations.sendMessageWithNoRefresh'. Accepts -- 'SomeMessage'; to use 'Message' see 'sendMessageWithNoRefreshB'. Returns -- @True@ if the message was handled, @False@ otherwise. sendSomeMessageWithNoRefreshB :: SomeMessage -> Workspace WorkspaceId (Layout Window) Window -> X Bool sendSomeMessageWithNoRefreshB m w = handleMessage (layout w) m `catchX` return Nothing >>= liftA2 (>>) (updateLayout $ tag w) (return . isJust) -- | Variant of 'sendSomeMessageWithNoRefreshB' that discards the result. sendSomeMessageWithNoRefresh :: SomeMessage -> Workspace WorkspaceId (Layout Window) Window -> X () sendSomeMessageWithNoRefresh m = void . sendSomeMessageWithNoRefreshB m -- | Variant of 'XMonad.Operations.sendMessageWithNoRefresh' that sends the -- message to the current layout. Accepts 'SomeMessage'; to use 'Message' see -- 'sendMessageWithNoRefreshToCurrentB'. Returns @True@ if the message was -- handled, @False@ otherwise. This function is somewhat of a cross between -- 'XMonad.Operations.sendMessage' (sends to the current layout) and -- 'XMonad.Operations.sendMessageWithNoRefresh' (does not refresh). sendSomeMessageWithNoRefreshToCurrentB :: SomeMessage -> X Bool sendSomeMessageWithNoRefreshToCurrentB m = gets (workspace . current . windowset) >>= sendSomeMessageWithNoRefreshB m -- | Variant of 'sendSomeMessageWithNoRefreshToCurrentB' that discards the -- result. sendSomeMessageWithNoRefreshToCurrent :: SomeMessage -> X () sendSomeMessageWithNoRefreshToCurrent = void . sendSomeMessageWithNoRefreshToCurrentB -- | Variant of 'sendSomeMessageB' which like 'XMonad.Operations.sendMessage' -- accepts 'Message' rather than 'SomeMessage'. Returns @True@ if the message -- was handled, @False@ otherwise. sendMessageB :: Message a => a -> X Bool sendMessageB = sendSomeMessageB . SomeMessage -- | Variant of 'sendSomeMessageWithNoRefreshB' which like -- 'XMonad.Operations.sendMessageWithNoRefresh' accepts 'Message' rather than -- 'SomeMessage'. Returns @True@ if the message was handled, @False@ otherwise. sendMessageWithNoRefreshB :: Message a => a -> Workspace WorkspaceId (Layout Window) Window -> X Bool sendMessageWithNoRefreshB = sendSomeMessageWithNoRefreshB . SomeMessage -- | Variant of 'sendSomeMessageWithNoRefreshToCurrentB' which accepts -- 'Message' rather than 'SomeMessage'. Returns @True@ if the message was -- handled, @False@ otherwise. sendMessageWithNoRefreshToCurrentB :: Message a => a -> X Bool sendMessageWithNoRefreshToCurrentB = sendSomeMessageWithNoRefreshToCurrentB . SomeMessage -- | Variant of 'sendMessageWithNoRefreshToCurrentB' that discards the result. sendMessageWithNoRefreshToCurrent :: Message a => a -> X () sendMessageWithNoRefreshToCurrent = void . sendMessageWithNoRefreshToCurrentB -- | Send each 'SomeMessage' to the current layout without refresh (using -- 'sendSomeMessageWithNoRefreshToCurrentB') and collect the results. If any -- message was handled, refresh. If you want to sequence a series of messages -- that would have otherwise used 'XMonad.Operations.sendMessage' while -- minimizing refreshes, use this. sendSomeMessagesB :: [SomeMessage] -> X [Bool] sendSomeMessagesB = windowBracket or . mapM sendSomeMessageWithNoRefreshToCurrentB -- | Variant of 'sendSomeMessagesB' that discards the results. sendSomeMessages :: [SomeMessage] -> X () sendSomeMessages = void . sendSomeMessagesB -- | Variant of 'sendSomeMessagesB' which accepts 'Message' rather than -- 'SomeMessage'. Use this if all the messages are of the same type. sendMessagesB :: Message a => [a] -> X [Bool] sendMessagesB = sendSomeMessagesB . map SomeMessage -- | Variant of 'sendMessagesB' that discards the results. sendMessages :: Message a => [a] -> X () sendMessages = void . sendMessagesB -- | Apply the dispatch function in order to each message of the list until one -- is handled. Returns @True@ if so, @False@ otherwise. tryInOrderB :: (SomeMessage -> X Bool) -> [SomeMessage] -> X Bool tryInOrderB _ [] = return False tryInOrderB f (m:ms) = do b <- f m if b then return True else tryInOrderB f ms -- | Variant of 'tryInOrderB' that sends messages to the current layout without -- refresh using 'sendSomeMessageWithNoRefreshToCurrentB'. tryInOrderWithNoRefreshToCurrentB :: [SomeMessage] -> X Bool tryInOrderWithNoRefreshToCurrentB = tryInOrderB sendSomeMessageWithNoRefreshToCurrentB -- | Variant of 'tryInOrderWithNoRefreshToCurrent' that discards the results. tryInOrderWithNoRefreshToCurrent :: [SomeMessage] -> X () tryInOrderWithNoRefreshToCurrent = void . tryInOrderWithNoRefreshToCurrentB -- | Apply the dispatch function to the first message, and if it was not -- handled, apply it to the second. Returns @True@ if either message was -- handled, @False@ otherwise. tryMessageB :: (Message a, Message b) => (SomeMessage -> X Bool) -> a -> b -> X Bool tryMessageB f m1 m2 = tryInOrderB f [sm m1,sm m2] -- | Variant of 'tryMessageB' that sends messages to the current layout without -- refresh using 'sendMessageWithNoRefreshToCurrentB'. tryMessageWithNoRefreshToCurrentB :: (Message a, Message b) => a -> b -> X Bool tryMessageWithNoRefreshToCurrentB = tryMessageB sendSomeMessageWithNoRefreshToCurrentB -- | Variant of 'tryMessage' that discards the results. tryMessageWithNoRefreshToCurrent :: (Message a, Message b) => a -> b -> X () tryMessageWithNoRefreshToCurrent m = void . tryMessageWithNoRefreshToCurrentB m -- | Convenience shorthand for 'SomeMessage'. sm :: Message a => a -> SomeMessage sm = SomeMessage -------------------------------------------------------------------------------- -- Backwards Compatibility: -------------------------------------------------------------------------------- {-# DEPRECATED send "Use sendMessageB instead." #-} {-# DEPRECATED sendSM "Use sendSomeMessageB instead." #-} {-# DEPRECATED sendSM_ "Use sendSomeMessage instead." #-} {-# DEPRECATED tryInOrder "Use tryInOrderWithNoRefreshToCurrentB instead." #-} {-# DEPRECATED tryInOrder_ "Use tryInOrderWithNoRefreshToCurrent instead." #-} {-# DEPRECATED tryMessage "Use tryMessageWithNoRefreshToCurrentB instead." #-} {-# DEPRECATED tryMessage_ "Use tryMessageWithNoRefreshToCurrent instead." #-} -- $backwardsCompatibility -- The following functions exist solely for compatibility with pre-0.14 -- releases. -- | See 'sendMessageWithNoRefreshToCurrentB'. send :: Message a => a -> X Bool send = sendMessageWithNoRefreshToCurrentB -- | See 'sendSomeMessageWithNoRefreshToCurrentB'. sendSM :: SomeMessage -> X Bool sendSM = sendSomeMessageWithNoRefreshToCurrentB -- | See 'sendSomeMessageWithNoRefreshToCurrent'. sendSM_ :: SomeMessage -> X () sendSM_ = sendSomeMessageWithNoRefreshToCurrent -- | See 'tryInOrderWithNoRefreshToCurrentB'. tryInOrder :: [SomeMessage] -> X Bool tryInOrder = tryInOrderWithNoRefreshToCurrentB -- | See 'tryInOrderWithNoRefreshToCurrent'. tryInOrder_ :: [SomeMessage] -> X () tryInOrder_ = tryInOrderWithNoRefreshToCurrent -- | See 'tryMessageWithNoRefreshToCurrentB'. tryMessage :: (Message a, Message b) => a -> b -> X Bool tryMessage = tryMessageWithNoRefreshToCurrentB -- | See 'tryMessageWithNoRefreshToCurrent'. tryMessage_ :: (Message a, Message b) => a -> b -> X () tryMessage_ = tryMessageWithNoRefreshToCurrent
xmonad/xmonad-contrib
XMonad/Actions/MessageFeedback.hs
bsd-3-clause
12,093
0
19
1,884
1,478
849
629
99
2
{-| Comment storage in SQLite -} module State.SQLite ( new ) where import Network.URI ( URI, parseRelativeReference ) import Data.Maybe ( listToMaybe, maybeToList ) import Data.List ( intercalate ) import System.IO ( hPutStrLn, stderr ) import qualified Data.Text.Encoding as E import qualified Data.Text as T import Database.SQLite ( openConnection , SQLiteHandle , execParamStatement , execStatement_ , execParamStatement_ , execStatement , defineTableOpt ) import Control.Exception ( onException ) import qualified Database.SQLite as Q import State.Types ( State(..), CommentId, commentId , ChapterId , chapterId, mkCommentId, Comment(..) , SessionId(..), SessionInfo(..) ) import Control.Monad ( forM_, when, (<=<) ) -- |Open a new SQLite comment store new :: FilePath -> IO State new dbName = do hdl <- openConnection dbName checkSchema hdl return $ State { findComments = findComments' hdl , getCounts = getCounts' hdl , addComment = addComment' hdl , addChapter = addChapter' hdl , getLastInfo = getLastInfo' hdl , getChapterComments = getChapterComments' hdl , getChapterURI = getChapterURI' hdl } handleDefault :: b -> String -> Either String a -> (a -> IO b) -> IO b handleDefault d msg (Left err) _ = do hPutStrLn stderr $ "Error " ++ msg ++ ": " ++ err return d handleDefault _ _ (Right x) f = f x getLastInfo' :: SQLiteHandle -> SessionId -> IO (Maybe SessionInfo) getLastInfo' hdl sid = do let sql = "SELECT name, email \ \FROM comments \ \WHERE session_id = :session_id \ \ORDER BY date DESC \ \LIMIT 1" binder = [(":session_id", Q.Blob $ sidBS sid)] res <- execParamStatement hdl sql binder let toInfo [(_, Q.Blob n), (_, ef)] = SessionInfo (E.decodeUtf8 n) `fmap` loadEmail ef toInfo _ = [] handleDefault Nothing "loading info" res $ return . listToMaybe . concatMap toInfo . concat loadEmail :: Q.Value -> [Maybe T.Text] loadEmail Q.Null = return Nothing loadEmail (Q.Blob s) = return $ Just $ E.decodeUtf8 s loadEmail _ = [] -- Load all of the comments for a given comment id findComments' :: SQLiteHandle -> CommentId -> IO [Comment] findComments' hdl cId = do let commentIdBlob = txtBlob $ commentId cId sql = "SELECT name, comment, email, date, session_id \ \FROM comments WHERE comment_id = :comment_id" binder = [(":comment_id", commentIdBlob)] res <- execParamStatement hdl sql binder let toComment [(_, Q.Blob n), (_, Q.Blob c), (_, ef), (_, Q.Double i), (_, Q.Blob sid)] = do e <- loadEmail ef let d = realToFrac i [Comment (E.decodeUtf8 n) (E.decodeUtf8 c) e d (SessionId sid)] toComment _ = [] handleDefault [] "loading comments" res $ return . concatMap toComment . concat -- Load the comment counts for the current chapter, or all counts if -- no chapter is supplied getCounts' :: SQLiteHandle -> Maybe ChapterId -> IO [(CommentId, Int)] getCounts' hdl mChId = do res <- case mChId of Nothing -> let sql = "SELECT comment_id, COUNT(comment_id) \ \FROM comments GROUP BY comment_id" in execStatement hdl sql Just chId -> let sql = "SELECT comments.comment_id, \ \ COUNT(comments.comment_id) \ \FROM comments JOIN chapters \ \ON comments.comment_id == chapters.comment_id \ \WHERE chapters.chapter_id = :chapter_id \ \ AND chapters.chapter_id IS NOT NULL \ \GROUP BY comments.comment_id" chIdBlob = txtBlob $ chapterId chId binder = [(":chapter_id", chIdBlob)] in execParamStatement hdl sql binder let convertRow [(_, Q.Blob cIdBS), (_, Q.Int cnt)] = case mkCommentId $ E.decodeUtf8 cIdBS of Just cId | cnt > 0 -> [(cId, fromIntegral cnt)] _ -> [] convertRow _ = [] handleDefault [] "getting counts" res $ return . concatMap convertRow . concat -- Add the comment, possibly associating it with a chapter addComment' :: SQLiteHandle -> CommentId -> Maybe ChapterId -> Comment -> IO () addComment' hdl cId mChId c = txn hdl $ do case mChId of Nothing -> return () Just chId -> insertChapterComment cId chId hdl insertComment cId c hdl -- Insert a row that adds a comment for the given comment id insertComment :: CommentId -> Comment -> SQLiteHandle -> IO () insertComment cId c hdl = do maybeErr =<< insertRowVal hdl "comments" [ ("comment_id", txtBlob $ commentId cId) , ("name", txtBlob $ cName c) , ("comment", txtBlob $ cComment c) , ("email", maybe Q.Null txtBlob $ cEmail c) , ("date", Q.Double $ realToFrac $ cDate c) , ("session_id", Q.Blob $ sidBS $ cSession c) ] -- Insert a row that maps a comment id with a chapter insertChapterComment :: CommentId -> ChapterId -> SQLiteHandle -> IO () insertChapterComment cId chId hdl = do let sql = "SELECT 1 FROM chapters \ \WHERE chapter_id = :chId AND comment_id = :cId" binder = [ (":chId", txtBlob $ chapterId chId) , (":cId", txtBlob $ commentId cId) ] res <- execParamStatement hdl sql binder case (res :: Either String [[Q.Row ()]]) of Left err -> error err Right rs -> when (null $ concat rs) $ maybeErr =<< insertRowVal hdl "chapters" [ ("chapter_id", txtBlob $ chapterId chId) , ("comment_id", txtBlob $ commentId cId) ] addChapter' :: SQLiteHandle -> ChapterId -> [CommentId] -> Maybe URI -> IO () addChapter' hdl chId cIds mURI = txn hdl $ do forM_ cIds $ \cId -> insertChapterComment cId chId hdl case mURI of Nothing -> return () Just uri -> do let sql = "INSERT OR REPLACE INTO \ \ chapter_info (chapter_id, url) \ \VALUES (:chId, :url)" binder = [ (":chId", txtBlob $ chapterId chId) , (":url", txtBlob $ T.pack $ show uri) ] maybeErr =<< execParamStatement_ hdl sql binder getChapterURI' :: SQLiteHandle -> ChapterId -> IO (Maybe URI) getChapterURI' hdl chId = do let sql = "SELECT url FROM chapter_info WHERE chapter_id = :chId" binder = [(":chId", txtBlob $ chapterId chId)] convertRow [(_, Q.Blob u)] = maybeToList $ parseRelativeReference $ T.unpack $ E.decodeUtf8 u convertRow _ = [] res <- execParamStatement hdl sql binder handleDefault Nothing "getting URI" res $ return . listToMaybe . concatMap convertRow . concat -- If the tables we expect are not there, add them (to deal with the -- case that this is a new database) -- -- This can cause problems if the schema changes, since it does not -- actually check to see that the schema matches what we expect. checkSchema :: SQLiteHandle -> IO () checkSchema hdl = txn hdl $ do mapM_ (maybeErr <=< defineTableOpt hdl True) [ t "comments" [ tCol "comment_id" , tCol "name" , tCol "comment" , tColN "email" [] , Q.Column "date" real [notNull] , tCol "session_id" ] , t "chapters" [ tCol "chapter_id" , tCol "comment_id" ] , t "chapter_info" [ tColN "chapter_id" [ notNull , Q.PrimaryKey False ] , tColN "url" [] ] ] mapM_ (maybeErr <=< execStatement_ hdl) [ "CREATE INDEX IF NOT EXISTS comments_comment_id_idx \ \ON comments(comment_id)" , "CREATE INDEX IF NOT EXISTS chapters_comment_id_idx \ \ON chapters(comment_id)" , "CREATE INDEX IF NOT EXISTS chapters_chapter_id_idx \ \ON chapters(chapter_id)" , "CREATE INDEX IF NOT EXISTS comments_date_idx \ \ON comments(date)" , "CREATE INDEX IF NOT EXISTS comments_session_id \ \ON comments(session_id)" , "CREATE INDEX IF NOT EXISTS chapter_info_chapter_id \ \ON chapters(chapter_id)" ] where real = Q.SQLFloat Nothing Nothing tColN c cs = Q.Column c txt cs notNull = Q.IsNullable False tCol c = tColN c [notNull] t n cs = Q.Table n cs [] txt = Q.SQLBlob $ Q.NormalBlob Nothing getChapterComments' :: SQLiteHandle -> ChapterId -> IO [(CommentId, Comment)] getChapterComments' hdl chId = do let sql = "SELECT comments.comment_id, name, comment, \ \ email, date, session_id \ \FROM comments JOIN chapters \ \ ON comments.comment_id = chapters.comment_id \ \WHERE chapters.chapter_id = :chapter_id \ \ORDER BY comments.date DESC" binder = [(":chapter_id", txtBlob $ chapterId chId)] res <- execParamStatement hdl sql binder let toResult [ (_, Q.Blob cIdB) , (_, Q.Blob n) , (_, Q.Blob c) , (_, ef) , (_, Q.Double i) , (_, Q.Blob sid) ] = do e <- loadEmail ef cId <- maybeToList $ mkCommentId $ E.decodeUtf8 cIdB let d = realToFrac i name = E.decodeUtf8 n commentTxt = E.decodeUtf8 c sId = SessionId sid comment = Comment name commentTxt e d sId [(cId, comment)] toResult _ = [] handleDefault [] "loading comments for chapter" res $ return . concatMap toResult . concat -------------------------------------------------- -- Helpers -- Convert a Data.Text.Text value to a UTF-8-encoded Blob. We use -- Blobs to avoid dealing with database encodings (the application -- does all of the encoding and decoding) txtBlob :: T.Text -> Q.Value txtBlob = Q.Blob . E.encodeUtf8 -- If there is a string in the value, throw an error. Otherwise, do -- nothing. maybeErr :: Maybe String -> IO () maybeErr Nothing = return () maybeErr (Just e) = error e -- Perform the supplied action inside of a database transaction txn :: SQLiteHandle -> IO () -> IO () txn hdl act = do let execSql sql = maybeErr =<< execStatement_ hdl sql execSql "BEGIN" act `onException` (execSql "ROLLBACK" >> return ()) execSql "COMMIT" return () -- Insert a row into a table, using type Value for the values insertRowVal :: SQLiteHandle -> Q.TableName -> Q.Row Q.Value -> IO (Maybe String) insertRowVal hdl tbl r = execParamStatement_ hdl sql row where sql = "INSERT INTO " ++ tbl ++ cols ++ " VALUES " ++ vals tupled l = '(':(intercalate "," l ++ ")") cols = tupled $ map fst r vals = tupled valNames valNames = take (length r) $ map (showString ":val") $ map show [(1::Integer)..] row = zip valNames $ map snd r
j3h/doc-review
src/State/SQLite.hs
bsd-3-clause
11,846
0
20
4,115
2,923
1,497
1,426
206
4
{-# LANGUAGE CPP #-} module Gap ( supportedExtensions , getSrcSpan , getSrcFile , renderMsg , setCtx , fOptions , toStringBuffer , liftIO , extensionToString #if __GLASGOW_HASKELL__ >= 702 #else , module Pretty #endif ) where import Control.Applicative hiding (empty) import Control.Monad import DynFlags import FastString import GHC import GHCChoice import Language.Haskell.Extension import Outputable import StringBuffer #if __GLASGOW_HASKELL__ >= 702 import CoreMonad (liftIO) #else import HscTypes (liftIO) import Pretty #endif {- pretty :: Outputable a => a -> String pretty = showSDocForUser neverQualify . ppr debug :: Outputable a => a -> b -> b debug x v = trace (pretty x) v -} ---------------------------------------------------------------- ---------------------------------------------------------------- supportedExtensions :: [String] #if __GLASGOW_HASKELL__ >= 700 supportedExtensions = supportedLanguagesAndExtensions #else supportedExtensions = supportedLanguages #endif ---------------------------------------------------------------- ---------------------------------------------------------------- getSrcSpan :: SrcSpan -> Maybe (Int,Int,Int,Int) #if __GLASGOW_HASKELL__ >= 702 getSrcSpan (RealSrcSpan spn) #else getSrcSpan spn | isGoodSrcSpan spn #endif = Just (srcSpanStartLine spn , srcSpanStartCol spn , srcSpanEndLine spn , srcSpanEndCol spn) getSrcSpan _ = Nothing getSrcFile :: SrcSpan -> Maybe String #if __GLASGOW_HASKELL__ >= 702 getSrcFile (RealSrcSpan spn) = Just . unpackFS . srcSpanFile $ spn #else getSrcFile spn | isGoodSrcSpan spn = Just . unpackFS . srcSpanFile $ spn #endif getSrcFile _ = Nothing ---------------------------------------------------------------- renderMsg :: SDoc -> PprStyle -> String #if __GLASGOW_HASKELL__ >= 702 renderMsg d stl = renderWithStyle d stl #else renderMsg d stl = Pretty.showDocWith PageMode $ d stl #endif ---------------------------------------------------------------- toStringBuffer :: [String] -> Ghc StringBuffer #if __GLASGOW_HASKELL__ >= 702 toStringBuffer = return . stringToStringBuffer . unlines #else toStringBuffer = liftIO . stringToStringBuffer . unlines #endif ---------------------------------------------------------------- fOptions :: [String] #if __GLASGOW_HASKELL__ >= 704 fOptions = [option | (option,_,_) <- fFlags] ++ [option | (option,_,_) <- fWarningFlags] ++ [option | (option,_,_) <- fLangFlags] #elif __GLASGOW_HASKELL__ == 702 fOptions = [option | (option,_,_,_) <- fFlags] #else fOptions = [option | (option,_,_) <- fFlags] #endif ---------------------------------------------------------------- ---------------------------------------------------------------- setCtx :: [ModSummary] -> Ghc Bool #if __GLASGOW_HASKELL__ >= 704 setCtx ms = do top <- map (IIModule . ms_mod) <$> filterM isTop ms setContext top return (not . null $ top) #else setCtx ms = do top <- map ms_mod <$> filterM isTop ms setContext top [] return (not . null $ top) #endif where isTop mos = lookupMod ||> returnFalse where lookupMod = lookupModule (ms_mod_name mos) Nothing >> return True returnFalse = return False ---------------------------------------------------------------- -- This is Cabal, not GHC API extensionToString :: Extension -> String #if __GLASGOW_HASKELL__ == 704 extensionToString (EnableExtension ext) = show ext extensionToString (DisableExtension ext) = show ext -- FIXME extensionToString (UnknownExtension ext) = ext #else extensionToString = show #endif
johntyree/ghc-mod
Gap.hs
bsd-3-clause
3,646
0
12
611
570
328
242
51
1
module Control.Isomorphism.Partial.Iso ( Iso, unsafeMakeIso, unsafeMakeIso', unsafeMakeNamedIso, unsafeMakeNamedIsoL , unsafeMakeNamedIsoR, unsafeMakeNamedIsoLR, isoRL, isoLR, isoName , isoShowSL, isoShowSR, isoShowL, isoShowR , isoFailedErrorMessageL, isoFailedErrorMessageR ) where data Iso a b = Iso { isoLR :: a -> Maybe b , isoRL :: b -> Maybe a , isoName :: String , isoShowSL :: Maybe (a -> ShowS) , isoShowSR :: Maybe (b -> ShowS) } unsafeMakeIso :: (alpha -> Maybe beta) -> (beta -> Maybe alpha) -> Iso alpha beta unsafeMakeIso f g = Iso { isoLR = f , isoRL = g , isoName = "?" , isoShowSL = Nothing , isoShowSR = Nothing } unsafeMakeIso' :: String -> Maybe (a -> ShowS) -> Maybe (b -> ShowS) -> (a -> Maybe b) -> (b -> Maybe a) -> Iso a b unsafeMakeIso' name showSL showSR f g = Iso { isoLR = f , isoRL = g , isoName = name , isoShowSL = showSL , isoShowSR = showSR } unsafeMakeNamedIso :: String -> (alpha -> Maybe beta) -> (beta -> Maybe alpha) -> Iso alpha beta unsafeMakeNamedIso name f g = Iso { isoLR = f , isoRL = g , isoName = name , isoShowSL = Nothing , isoShowSR = Nothing } unsafeMakeNamedIsoL :: Show alpha => String -> (alpha -> Maybe beta) -> (beta -> Maybe alpha) -> Iso alpha beta unsafeMakeNamedIsoL name f g = Iso { isoLR = f , isoRL = g , isoName = name , isoShowSL = Just shows , isoShowSR = Nothing } unsafeMakeNamedIsoR :: Show beta => String -> (alpha -> Maybe beta) -> (beta -> Maybe alpha) -> Iso alpha beta unsafeMakeNamedIsoR name f g = Iso { isoLR = f , isoRL = g , isoName = name , isoShowSL = Nothing , isoShowSR = Just shows } unsafeMakeNamedIsoLR :: (Show alpha, Show beta) => String -> (alpha -> Maybe beta) -> (beta -> Maybe alpha) -> Iso alpha beta unsafeMakeNamedIsoLR name f g = Iso { isoLR = f , isoRL = g , isoName = name , isoShowSL = Just shows , isoShowSR = Just shows } isoShowL :: Iso a b -> Maybe (a -> String) isoShowL iso = makeShow (isoShowSL iso) isoShowR :: Iso a b -> Maybe (b -> String) isoShowR iso = makeShow (isoShowSR iso) makeShow :: Maybe (a -> ShowS) -> Maybe (a -> String) makeShow Nothing = Nothing makeShow (Just f) = Just (\x -> f x "") isoFailedErrorMessageL :: Iso a b -> a -> String isoFailedErrorMessageL iso = isoFailedErrorMessage (isoName iso) (isoShowSL iso) isoFailedErrorMessageR :: Iso a b -> b -> String isoFailedErrorMessageR iso = isoFailedErrorMessage (isoName iso) (isoShowSR iso) isoFailedErrorMessage :: String -> Maybe (a -> ShowS) -> a -> String isoFailedErrorMessage name mf x = "Isomorphism " ++ name ++ " failed" ++ (case mf of Nothing -> "" Just f -> " on input " ++ f x "")
skogsbaer/roundtrip
src/Control/Isomorphism/Partial/Iso.hs
bsd-3-clause
3,564
0
12
1,475
1,033
558
475
68
2
module Ast where type Prog = [Sent] data IsRec = Rec | NonRec deriving (Show, Eq) data Sent = Def IsRec Idt [Idt] Expr | Sent Expr deriving (Show, Eq) data Expr = Let IsRec Idt [Idt] Expr Expr | Fun Idt Expr | If Expr Expr Expr | LChar Char | LString String | LList [Expr] | LIdt Idt | Pipe Expr Expr | Apply Expr Expr | Number Integer | Call Expr | Next Expr | Nil deriving (Show, Eq) data Idt = Idt String deriving (Show, Eq) alphas :: [Char] alphas = ['0'..'9'] ++ ['a'..'z'] ++ ['A'..'Z'] ++ "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" regchars :: [Char] regchars = "  、。也為如若寧無呼取所也以定「」" {-- <program> = <sentence>+ <sentence> ::= <space>* '定' <space>* '再'? <idt>+ '為' <expr> 。<space>* | <expr> 。<space>* <expr> ::= <pipe> <pipe> ::= <apply> (、 <apply>)+ <apply> ::= <atom> (<expr>)+ <atom> :: = '以' '再'? <idt>+ '為' <pipe> '如' <pipe> | '若' <pipe> '寧' <pipe> '無' <pipe> | '字' <pipe> | ('並' <expr>)+ '空' | 「 <string> 」| <number> | '呼' <atom> | '次' <expr> | <idt> | '所' <expr> '也' <idt> ::= <alpha> <char> (- <char>)* | <idt> 之 <idt> --}
wass80/CoCaml
src/Ast.hs
bsd-3-clause
1,183
0
8
263
244
142
102
27
1
module Data.Git.Index ( ) where import Control.Applicative import Data.Git.Ref {- <INDEX_HEADER> : "DIRC" <INDEX_FILE_VERSION> <INDEX_ENTRY_COUNT> ; -} data IndexHeader = IndexHeader Word32 Word32 deriving (Show,Eq) parseBe32 = be32 <$> A.take 4 parseBe16 = be16 <$> A.take 2 parseRef = fromBinary <$> A.take 20 parseIndexHeader = do magic <- parseBe32 when (magic /= 'DIRC') $ error "wrong magic number for index" ver <- parseBe32 when (ver /= 2) $ error "unsupported packIndex version" entries <- parseBe32 return $ IndexHeader ver entries {- <INDEX_FILE_FORMAT_V2> : <INDEX_HEADER> <EXTENDED_INDEX_CONTENTS> <EXTENDED_CHECKSUM> ; <EXTENDED_CHECKSUM> : _sha-1_digest_( <EXTENDED_INDEX_CONTENTS> ) ; <INDEX_CHECKSUM> : _sha-1_digest_( <INDEX_CONTENTS> ) ; -} parseIndexContents entries = replicateM entries parseIndexEntry {- <EXTENDED_INDEX_CONTENTS> : <INDEX_CONTENTS> <INDEX_CONTENTS_EXTENSIONS> ; -} parseIndexEntry = do -- INDEX_ENTRY_STAT_INFO ctime <- parseTime mtime <- parseTime dev <- parseBe32 inode <- parseBe32 mode <- parseBe32 uid <- parseBe32 gid <- parseBe32 size <- parseBe32 -- entry id, flags, name, zero padding -- how to parse <ENTRY_ID> flags <- parseBe16 -- 16 bit, network byte order, binary integer. -- bits 15-14 Reserved -- bits 13-12 Entry stage -- bits 11-0 Name byte length name <- takeWhileNotNull zeroPadding {- <ENTRY_ZERO_PADDING> # The minimum length 0x00 byte sequence necessary to make the # written of digested byte length of the <INDEX_ENTRY> a # multiple of 8. ; -} parseTime = (,) <$> parseBe32 <*> parseBe32 {- <ENTRY_ID> # Object ID of the of the file system entity contents. ; <ENTRY_NAME> # File system entity name. Path is normalized and relative to # the working directory. ; <INDEX_CONTENTS_EXTENSIONS> : ( <INDEX_EXTENSION> )* ; -} parseIndexExtension = do -- # 4 byte sequence identifying how the <INDEX_EXTENSION_DATA> -- # should be interpreted. If the first byte has a value greater -- # than or equal to the ASCII character 'A' (0x41) and less than -- # or equal to the ASCII character 'Z' (0x5a), the extension is -- # optional and does not affect the interpretation of the other -- # contents in the index file. Any non-optional extensions must -- # be understood by the reading application to correctly -- # interpret the index file contents. name <- A.take 4 dataSize <- parseBe32 data_ <- A.take dataSize return (name,data_)
NicolasDP/hit
Data/Git/Index.hs
bsd-3-clause
2,734
0
10
711
339
174
165
-1
-1
{-# LANGUAGE RebindableSyntax #-} -- Copyright : (C) 2009 Corey O'Connor -- License : BSD-style (see the file LICENSE) -- A fixed deserialization buffer provider can only provided a fixed number of bytes to a -- deserialization action. Requesting more bytes than in the buffer should fail. -- -- This might actually work as a test of laziness as well: The laziness is such that the -- deserialization monad is not executed until the vs value is demanded? import Bind.Marshal.Prelude import Bind.Marshal.Verify import Bind.Marshal.Action import Bind.Marshal.DataModel.Base import Bind.Marshal.DesAction.Base import Bind.Marshal.DesAction.Dynamic import Bind.Marshal.DesAction.Static import Bind.Marshal.DesAction.Verify import Bind.Marshal.StaticProperties import Bind.Marshal.StdLib.Des import Bind.Marshal.StdLib.Dynamic.FixedBuffer import Control.DeepSeq import Control.Exception import "monads-tf" Control.Monad.Trans import Foreign.Storable import Foreign.Marshal.Alloc import Foreign.Ptr import System.IO t_0 i = do rs <- replicateM i $ dyn_action $ do x :: Word32 <- des return x rs `deepseq` return () main = run_test $ do -- allocate enough space for the action, even though the buffer region specified will be -- significantly less. This way if the deserialization fails to fail it doesn't run off into a -- page the program doesn't have mapped. buffer_0 <- liftIO $ mallocBytes (1024 * 4) :: Test ( Ptr Word8 ) verify1 "0 sized buffer" $ liftIOResult $ do let des_buf = BufferRegion buffer_0 0 des_buf_provider <- fixed_buffer des_buf assert_throws "des from 0 sized buffer fails" $ do des_from_buffer_delegate (dyn_action $! t_0 1024) des_buf_provider verify1 "too small buffer" $ liftIOResult $ do let des_buf = BufferRegion buffer_0 (4 * 100) des_buf_provider <- fixed_buffer des_buf assert_throws "des from too small sized buffer fails" $ do des_from_buffer_delegate (dyn_action $! t_0 1024) des_buf_provider returnM () :: Test ()
coreyoconnor/bind-marshal
test/verify_desaction_dynamic_fixed_buffer_fail.hs
bsd-3-clause
2,090
0
17
415
378
201
177
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. module Duckling.Ordinal.IT.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Ordinal.IT.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "IT Tests" [ makeCorpusTest [This Ordinal] corpus ]
rfranek/duckling
tests/Duckling/Ordinal/IT/Tests.hs
bsd-3-clause
600
0
9
96
80
51
29
11
1
{-# LANGUAGE DuplicateRecordFields #-} module Gli.Cli where import qualified Data.Map.Strict as M import Data.Maybe import qualified Data.Text as T import qualified Data.Yaml as Y import Gli.Gitlab import Gli.Setup import Gli.Types import Options.Applicative import Prelude hiding (id) opts :: ParserInfo Commands opts = info (helper <*> versionOption <*> commands) ( fullDesc <> progDesc "Tiny git\"lab/hub\" cli wrapper" <> header "gli - make PR review easy again" ) where versionOption = infoOption "Version 0.0.1-alpha" ( long "Version" <> short 'v' <> help "Show version") commands :: Parser Commands commands = subparser ((command "setup" (info (helper <*> (CmdSetup <$> parseSetupFile)) ( fullDesc <> progDesc "Setup you project" ))) <> (command "prs" (info (pure CmdPrs) ( fullDesc <> progDesc "Get all PR info" )))) parseSetupFile :: Parser Setup parseSetupFile = Setup <$> strOption ( long "file" <> short 'f' <> metavar "FILE" <> help "Accepts input file which has gitlab keys" ) runCli :: Commands -> IO () runCli (CmdSetup cmd) = setupProject $ keyFile cmd runCli CmdPrs = do localCfg <- Y.decodeFile localYmlFile :: IO (Maybe LocalYmlContent) let masterFileKey = masterFileConfig $ fromJust localCfg let filePath = file masterFileKey let fileKey = key (masterFileKey :: MasterFileConfig) let projectID = id (project (fromJust localCfg) :: Project) masterCfg <- Y.decodeFile filePath :: IO (Maybe GliCfg) case masterCfg of Nothing -> error $ mappend "Unable to parse file " (show filePath) Just b -> case M.lookup fileKey (accountMap (accounts b)) of Nothing -> error $ concat[ "Unable to find key" , T.unpack fileKey , " in masterfile " , filePath] Just c -> do mergeRequests (AccountConfig (key (c :: AccountConfig)) gitlabUrl) where gitlabUrl = url c ++ "/projects/" ++ show projectID runParser :: IO () runParser = execParser opts >>= runCli
goromlagche/gli
src/gli/cli.hs
bsd-3-clause
2,503
0
20
929
618
313
305
61
3
-- Caeser cipher example from chapter 5 of Programming in Haskell, -- Graham Hutton, Cambridge University Press, 2016. import Data.Char -- Encoding and decoding let2int :: Char -> Int let2int c = ord c - ord 'a' int2let :: Int -> Char int2let n = chr (ord 'a' + n) shift :: Int -> Char -> Char shift n c | isLower c = int2let ((let2int c + n) `mod` 26) | otherwise = c encode :: Int -> String -> String encode n xs = [shift n x | x <- xs] -- Frequency analysis table :: [Float] table = [8.1, 1.5, 2.8, 4.2, 12.7, 2.2, 2.0, 6.1, 7.0, 0.2, 0.8, 4.0, 2.4, 6.7, 7.5, 1.9, 0.1, 6.0, 6.3, 9.0, 2.8, 1.0, 2.4, 0.2, 2.0, 0.1] lowers :: String -> Int lowers xs = length [x | x <- xs, x >= 'a' && x <= 'z'] count :: Char -> String -> Int count x xs = length [x' | x' <- xs, x == x'] percent :: Int -> Int -> Float percent n m = (fromIntegral n / fromIntegral m) * 100 freqs :: String -> [Float] freqs xs = [percent (count x xs) n | x <- ['a'..'z']] where n = lowers xs chisqr :: [Float] -> [Float] -> Float chisqr os es = sum [((o-e)^2)/e | (o,e) <- zip os es] rotate :: Int -> [a] -> [a] rotate n xs = drop n xs ++ take n xs positions :: Eq a => a -> [a] -> [Int] positions x xs = [i | (x',i) <- zip xs [0..n], x == x'] where n = length xs - 1 crack :: String -> String crack xs = encode (-factor) xs where factor = head (positions (minimum chitab) chitab) chitab = [chisqr (rotate n table') table | n <- [0..25]] table' = freqs xs
thalerjonathan/phd
coding/learning/haskell/grahambook/Code_Solutions/cipher.hs
gpl-3.0
1,548
0
11
435
744
398
346
35
1
{-# LANGUAGE DeriveDataTypeable #-} module Graphics.ImageMagick.MagickCore.Exception ( MagickWandException(..) -- * support for ImageMagick Exceptions , ExceptionCarrier(..) , ExceptionSeverity , ExceptionType ) where import Control.Exception.Base import Data.Typeable import Graphics.ImageMagick.MagickCore.Types data MagickWandException = MagickWandException ExceptionSeverity ExceptionType String deriving (Typeable) instance Show (MagickWandException) where show (MagickWandException _ x s) = concat [show x, ": ", s] instance Exception MagickWandException -- * Exception Carrier can be different objects -- that are used in functions class ExceptionCarrier a where getException :: a -> IO MagickWandException
flowbox-public/imagemagick
Graphics/ImageMagick/MagickCore/Exception.hs
apache-2.0
770
0
8
136
144
84
60
16
0
module Util where import Test.Inspection import Test.HUnit.Base mkHUnitTest :: Result -> Test mkHUnitTest r = TestCase $ case r of Success _s -> return () Failure s -> assertFailure s
kcsongor/generic-lens
generic-optics/test/Util.hs
bsd-3-clause
197
0
10
43
66
34
32
8
2
<?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="ru-RU"> <title>Server-Sent Events | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</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>
0xkasun/security-tools
src/org/zaproxy/zap/extension/sse/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
991
80
67
160
439
221
218
-1
-1
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-2012 Note [Unarisation] ~~~~~~~~~~~~~~~~~~ The idea of this pass is to translate away *all* unboxed-tuple binders. So for example: f (x :: (# Int, Bool #)) = f x + f (# 1, True #) ==> f (x1 :: Int) (x2 :: Bool) = f x1 x2 + f 1 True It is important that we do this at the STG level and NOT at the core level because it would be very hard to make this pass Core-type-preserving. STG fed to the code generators *must* be unarised because the code generators do not support unboxed tuple binders natively. Note [Unarisation and arity] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Because of unarisation, the arity that will be recorded in the generated info table for an Id may be larger than the idArity. Instead we record what we call the RepArity, which is the Arity taking into account any expanded arguments, and corresponds to the number of (possibly-void) *registers* arguments will arrive in. -} {-# LANGUAGE CPP #-} module UnariseStg (unarise) where #include "HsVersions.h" import CoreSyn import StgSyn import VarEnv import UniqSupply import Id import MkId (realWorldPrimId) import Type import TysWiredIn import DataCon import OccName import Name import Util import Outputable import BasicTypes -- | A mapping from unboxed-tuple binders to the Ids they were expanded to. -- -- INVARIANT: Ids in the range don't have unboxed tuple types. -- -- Those in-scope variables without unboxed-tuple types are not present in -- the domain of the mapping at all. type UnariseEnv = VarEnv [Id] ubxTupleId0 :: Id ubxTupleId0 = dataConWorkId (tupleDataCon Unboxed 0) unarise :: UniqSupply -> [StgBinding] -> [StgBinding] unarise us binds = zipWith (\us -> unariseBinding us init_env) (listSplitUniqSupply us) binds where -- See Note [Nullary unboxed tuple] in Type.hs init_env = unitVarEnv ubxTupleId0 [realWorldPrimId] unariseBinding :: UniqSupply -> UnariseEnv -> StgBinding -> StgBinding unariseBinding us rho bind = case bind of StgNonRec x rhs -> StgNonRec x (unariseRhs us rho rhs) StgRec xrhss -> StgRec $ zipWith (\us (x, rhs) -> (x, unariseRhs us rho rhs)) (listSplitUniqSupply us) xrhss unariseRhs :: UniqSupply -> UnariseEnv -> StgRhs -> StgRhs unariseRhs us rho rhs = case rhs of StgRhsClosure ccs b_info fvs update_flag args expr -> StgRhsClosure ccs b_info (unariseIds rho fvs) update_flag args' (unariseExpr us' rho' expr) where (us', rho', args') = unariseIdBinders us rho args StgRhsCon ccs con args -> StgRhsCon ccs con (unariseArgs rho args) ------------------------ unariseExpr :: UniqSupply -> UnariseEnv -> StgExpr -> StgExpr unariseExpr _ rho (StgApp f args) | null args , UbxTupleRep tys <- repType (idType f) = -- Particularly important where (##) is concerned -- See Note [Nullary unboxed tuple] StgConApp (tupleDataCon Unboxed (length tys)) (map StgVarArg (unariseId rho f)) | otherwise = StgApp f (unariseArgs rho args) unariseExpr _ _ (StgLit l) = StgLit l unariseExpr _ rho (StgConApp dc args) | isUnboxedTupleCon dc = StgConApp (tupleDataCon Unboxed (length args')) args' | otherwise = StgConApp dc args' where args' = unariseArgs rho args unariseExpr _ rho (StgOpApp op args ty) = StgOpApp op (unariseArgs rho args) ty unariseExpr us rho (StgLam xs e) = StgLam xs' (unariseExpr us' rho' e) where (us', rho', xs') = unariseIdBinders us rho xs unariseExpr us rho (StgCase e bndr alt_ty alts) = StgCase (unariseExpr us1 rho e) bndr alt_ty alts' where (us1, us2) = splitUniqSupply us alts' = unariseAlts us2 rho alt_ty bndr alts unariseExpr us rho (StgLet bind e) = StgLet (unariseBinding us1 rho bind) (unariseExpr us2 rho e) where (us1, us2) = splitUniqSupply us unariseExpr us rho (StgLetNoEscape bind e) = StgLetNoEscape (unariseBinding us1 rho bind) (unariseExpr us2 rho e) where (us1, us2) = splitUniqSupply us unariseExpr us rho (StgTick tick e) = StgTick tick (unariseExpr us rho e) ------------------------ unariseAlts :: UniqSupply -> UnariseEnv -> AltType -> Id -> [StgAlt] -> [StgAlt] unariseAlts us rho (UbxTupAlt n) bndr [(DEFAULT, [], e)] = [(DataAlt (tupleDataCon Unboxed n), ys, unariseExpr us2' rho' e)] where (us2', rho', ys) = unariseIdBinder us rho bndr unariseAlts us rho (UbxTupAlt n) bndr [(DataAlt _, ys, e)] = [(DataAlt (tupleDataCon Unboxed n), ys', unariseExpr us2' rho'' e)] where (us2', rho', ys') = unariseIdBinders us rho ys rho'' = extendVarEnv rho' bndr ys' unariseAlts _ _ (UbxTupAlt _) _ alts = pprPanic "unariseExpr: strange unboxed tuple alts" (ppr alts) unariseAlts us rho _ _ alts = zipWith (\us alt -> unariseAlt us rho alt) (listSplitUniqSupply us) alts -------------------------- unariseAlt :: UniqSupply -> UnariseEnv -> StgAlt -> StgAlt unariseAlt us rho (con, xs, e) = (con, xs', unariseExpr us' rho' e) where (us', rho', xs') = unariseIdBinders us rho xs ------------------------ unariseArgs :: UnariseEnv -> [StgArg] -> [StgArg] unariseArgs rho = concatMap (unariseArg rho) unariseArg :: UnariseEnv -> StgArg -> [StgArg] unariseArg rho (StgVarArg x) = map StgVarArg (unariseId rho x) unariseArg _ (StgLitArg l) = [StgLitArg l] unariseIds :: UnariseEnv -> [Id] -> [Id] unariseIds rho = concatMap (unariseId rho) unariseId :: UnariseEnv -> Id -> [Id] unariseId rho x | Just ys <- lookupVarEnv rho x = ASSERT2( case repType (idType x) of UbxTupleRep _ -> True; _ -> x == ubxTupleId0 , text "unariseId: not unboxed tuple" <+> ppr x ) ys | otherwise = ASSERT2( case repType (idType x) of UbxTupleRep _ -> False; _ -> True , text "unariseId: was unboxed tuple" <+> ppr x ) [x] unariseIdBinders :: UniqSupply -> UnariseEnv -> [Id] -> (UniqSupply, UnariseEnv, [Id]) unariseIdBinders us rho xs = third3 concat $ mapAccumL2 unariseIdBinder us rho xs unariseIdBinder :: UniqSupply -> UnariseEnv -> Id -> (UniqSupply, UnariseEnv, [Id]) unariseIdBinder us rho x = case repType (idType x) of UnaryRep _ -> (us, rho, [x]) UbxTupleRep tys -> let (us0, us1) = splitUniqSupply us ys = unboxedTupleBindersFrom us0 x tys rho' = extendVarEnv rho x ys in (us1, rho', ys) unboxedTupleBindersFrom :: UniqSupply -> Id -> [UnaryType] -> [Id] unboxedTupleBindersFrom us x tys = zipWith (mkSysLocalOrCoVar fs) (uniqsFromSupply us) tys where fs = occNameFS (getOccName x)
oldmanmike/ghc
compiler/simplStg/UnariseStg.hs
bsd-3-clause
6,552
0
13
1,387
1,921
993
928
111
3
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} import Control.CP.FD.Example main = example_sat_main_single_expr model model :: ExampleModel ModelInt model n = exists $ \col -> do size col @= n loopall (0,(n-1)) $ \i -> do let v0 = col ! i v1 = col ! ((i+1) `mod` n) v2 = col ! ((i+2) `mod` n) 2 * v1 @= 2 * v2 - v0 v0 @: (cte (-10), cte 10) return col
neothemachine/monadiccp
examples/Ring.hs
bsd-3-clause
408
0
20
112
193
102
91
14
1
{-# LANGUAGE RelaxedPolyRec #-} -- needed for inlinesBetween on GHC < 7 {-# LANGUAGE ScopedTypeVariables #-} {- Copyright (C) 2006-2015 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Readers.Markdown Copyright : Copyright (C) 2006-2015 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Conversion of markdown-formatted plain text to 'Pandoc' document. -} module Text.Pandoc.Readers.Markdown ( readMarkdown, readMarkdownWithWarnings ) where import Data.List ( transpose, sortBy, findIndex, intersperse, intercalate ) import qualified Data.Map as M import Data.Scientific (coefficient, base10Exponent) import Data.Ord ( comparing ) import Data.Char ( isSpace, isAlphaNum, toLower ) import Data.Maybe import Text.Pandoc.Definition import qualified Data.Text as T import Data.Text (Text) import qualified Data.Yaml as Yaml import Data.Yaml (ParseException(..), YamlException(..), YamlMark(..)) import qualified Data.HashMap.Strict as H import qualified Text.Pandoc.Builder as B import qualified Text.Pandoc.UTF8 as UTF8 import qualified Data.Vector as V import Text.Pandoc.Builder (Inlines, Blocks, trimInlines, (<>)) import Text.Pandoc.Options import Text.Pandoc.Shared import Text.Pandoc.XML (fromEntities) import Text.Pandoc.Parsing hiding (tableWith) import Text.Pandoc.Readers.LaTeX ( rawLaTeXInline, rawLaTeXBlock ) import Text.Pandoc.Readers.HTML ( htmlTag, htmlInBalanced, isInlineTag, isBlockTag, isTextTag, isCommentTag ) import Data.Monoid (mconcat, mempty) import Control.Applicative ((<$>), (<*), (*>), (<$), (<*>)) import Control.Monad import System.FilePath (takeExtension, addExtension) import Text.HTML.TagSoup import Text.HTML.TagSoup.Match (tagOpen) import qualified Data.Set as Set import Text.Printf (printf) import Debug.Trace (trace) import Text.Pandoc.Error type MarkdownParser = Parser [Char] ParserState -- | Read markdown from an input string and return a Pandoc document. readMarkdown :: ReaderOptions -- ^ Reader options -> String -- ^ String to parse (assuming @'\n'@ line endings) -> Either PandocError Pandoc readMarkdown opts s = (readWith parseMarkdown) def{ stateOptions = opts } (s ++ "\n\n") -- | Read markdown from an input string and return a pair of a Pandoc document -- and a list of warnings. readMarkdownWithWarnings :: ReaderOptions -- ^ Reader options -> String -- ^ String to parse (assuming @'\n'@ line endings) -> Either PandocError (Pandoc, [String]) readMarkdownWithWarnings opts s = (readWithWarnings parseMarkdown) def{ stateOptions = opts } (s ++ "\n\n") trimInlinesF :: F Inlines -> F Inlines trimInlinesF = liftM trimInlines -- -- Constants and data structure definitions -- isBulletListMarker :: Char -> Bool isBulletListMarker '*' = True isBulletListMarker '+' = True isBulletListMarker '-' = True isBulletListMarker _ = False isHruleChar :: Char -> Bool isHruleChar '*' = True isHruleChar '-' = True isHruleChar '_' = True isHruleChar _ = False setextHChars :: String setextHChars = "=-" isBlank :: Char -> Bool isBlank ' ' = True isBlank '\t' = True isBlank '\n' = True isBlank _ = False -- -- auxiliary functions -- -- | Succeeds when we're in list context. inList :: MarkdownParser () inList = do ctx <- stateParserContext <$> getState guard (ctx == ListItemState) isNull :: F Inlines -> Bool isNull ils = B.isNull $ runF ils def spnl :: Parser [Char] st () spnl = try $ do skipSpaces optional newline skipSpaces notFollowedBy (char '\n') indentSpaces :: MarkdownParser String indentSpaces = try $ do tabStop <- getOption readerTabStop count tabStop (char ' ') <|> string "\t" <?> "indentation" nonindentSpaces :: MarkdownParser String nonindentSpaces = do tabStop <- getOption readerTabStop sps <- many (char ' ') if length sps < tabStop then return sps else unexpected "indented line" -- returns number of spaces parsed skipNonindentSpaces :: MarkdownParser Int skipNonindentSpaces = do tabStop <- getOption readerTabStop atMostSpaces (tabStop - 1) <* notFollowedBy (char ' ') atMostSpaces :: Int -> MarkdownParser Int atMostSpaces n | n > 0 = (char ' ' >> (+1) <$> atMostSpaces (n-1)) <|> return 0 | otherwise = return 0 litChar :: MarkdownParser Char litChar = escapedChar' <|> characterReference <|> noneOf "\n" <|> try (newline >> notFollowedBy blankline >> return ' ') -- | Parse a sequence of inline elements between square brackets, -- including inlines between balanced pairs of square brackets. inlinesInBalancedBrackets :: MarkdownParser (F Inlines) inlinesInBalancedBrackets = do char '[' (_, raw) <- withRaw $ charsInBalancedBrackets 1 guard $ not $ null raw parseFromString (trimInlinesF . mconcat <$> many inline) (init raw) charsInBalancedBrackets :: Int -> MarkdownParser () charsInBalancedBrackets 0 = return () charsInBalancedBrackets openBrackets = (char '[' >> charsInBalancedBrackets (openBrackets + 1)) <|> (char ']' >> charsInBalancedBrackets (openBrackets - 1)) <|> (( (() <$ code) <|> (() <$ (escapedChar')) <|> (newline >> notFollowedBy blankline) <|> skipMany1 (noneOf "[]`\n\\") <|> (() <$ count 1 (oneOf "`\\")) ) >> charsInBalancedBrackets openBrackets) -- -- document structure -- titleLine :: MarkdownParser (F Inlines) titleLine = try $ do char '%' skipSpaces res <- many $ (notFollowedBy newline >> inline) <|> try (endline >> whitespace) newline return $ trimInlinesF $ mconcat res authorsLine :: MarkdownParser (F [Inlines]) authorsLine = try $ do char '%' skipSpaces authors <- sepEndBy (many (notFollowedBy (satisfy $ \c -> c == ';' || c == '\n') >> inline)) (char ';' <|> try (newline >> notFollowedBy blankline >> spaceChar)) newline return $ sequence $ filter (not . isNull) $ map (trimInlinesF . mconcat) authors dateLine :: MarkdownParser (F Inlines) dateLine = try $ do char '%' skipSpaces trimInlinesF . mconcat <$> manyTill inline newline titleBlock :: MarkdownParser () titleBlock = pandocTitleBlock <|> mmdTitleBlock pandocTitleBlock :: MarkdownParser () pandocTitleBlock = try $ do guardEnabled Ext_pandoc_title_block lookAhead (char '%') title <- option mempty titleLine author <- option (return []) authorsLine date <- option mempty dateLine optional blanklines let meta' = do title' <- title author' <- author date' <- date return $ (if B.isNull title' then id else B.setMeta "title" title') . (if null author' then id else B.setMeta "author" author') . (if B.isNull date' then id else B.setMeta "date" date') $ nullMeta updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' } yamlMetaBlock :: MarkdownParser (F Blocks) yamlMetaBlock = try $ do guardEnabled Ext_yaml_metadata_block pos <- getPosition string "---" blankline notFollowedBy blankline -- if --- is followed by a blank it's an HRULE rawYamlLines <- manyTill anyLine stopLine -- by including --- and ..., we allow yaml blocks with just comments: let rawYaml = unlines ("---" : (rawYamlLines ++ ["..."])) optional blanklines opts <- stateOptions <$> getState meta' <- case Yaml.decodeEither' $ UTF8.fromString rawYaml of Right (Yaml.Object hashmap) -> return $ return $ H.foldrWithKey (\k v m -> if ignorable k then m else case yamlToMeta opts v of Left _ -> m Right v' -> B.setMeta (T.unpack k) v' m) nullMeta hashmap Right Yaml.Null -> return $ return nullMeta Right _ -> do addWarning (Just pos) "YAML header is not an object" return $ return nullMeta Left err' -> do case err' of InvalidYaml (Just YamlParseException{ yamlProblem = problem , yamlContext = _ctxt , yamlProblemMark = Yaml.YamlMark { yamlLine = yline , yamlColumn = ycol }}) -> addWarning (Just $ setSourceLine (setSourceColumn pos (sourceColumn pos + ycol)) (sourceLine pos + 1 + yline)) $ "Could not parse YAML header: " ++ problem _ -> addWarning (Just pos) $ "Could not parse YAML header: " ++ show err' return $ return nullMeta updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' } return mempty -- ignore fields ending with _ ignorable :: Text -> Bool ignorable t = (T.pack "_") `T.isSuffixOf` t toMetaValue :: ReaderOptions -> Text -> Either PandocError MetaValue toMetaValue opts x = toMeta <$> readMarkdown opts' (T.unpack x) where toMeta p = case p of Pandoc _ [Plain xs] -> MetaInlines xs Pandoc _ [Para xs] | endsWithNewline x -> MetaBlocks [Para xs] | otherwise -> MetaInlines xs Pandoc _ bs -> MetaBlocks bs endsWithNewline t = T.pack "\n" `T.isSuffixOf` t opts' = opts{readerExtensions=readerExtensions opts `Set.difference` meta_exts} meta_exts = Set.fromList [ Ext_pandoc_title_block , Ext_mmd_title_block , Ext_yaml_metadata_block ] yamlToMeta :: ReaderOptions -> Yaml.Value -> Either PandocError MetaValue yamlToMeta opts (Yaml.String t) = toMetaValue opts t yamlToMeta _ (Yaml.Number n) -- avoid decimal points for numbers that don't need them: | base10Exponent n >= 0 = return $ MetaString $ show $ coefficient n * (10 ^ base10Exponent n) | otherwise = return $ MetaString $ show n yamlToMeta _ (Yaml.Bool b) = return $ MetaBool b yamlToMeta opts (Yaml.Array xs) = B.toMetaValue <$> mapM (yamlToMeta opts) (V.toList xs) yamlToMeta opts (Yaml.Object o) = MetaMap <$> H.foldrWithKey (\k v m -> if ignorable k then m else (do v' <- yamlToMeta opts v m' <- m return (M.insert (T.unpack k) v' m'))) (return M.empty) o yamlToMeta _ _ = return $ MetaString "" stopLine :: MarkdownParser () stopLine = try $ (string "---" <|> string "...") >> blankline >> return () mmdTitleBlock :: MarkdownParser () mmdTitleBlock = try $ do guardEnabled Ext_mmd_title_block kvPairs <- many1 kvPair blanklines updateState $ \st -> st{ stateMeta' = stateMeta' st <> return (Meta $ M.fromList kvPairs) } kvPair :: MarkdownParser (String, MetaValue) kvPair = try $ do key <- many1Till (alphaNum <|> oneOf "_- ") (char ':') skipMany1 spaceNoNewline val <- manyTill anyChar (try $ newline >> lookAhead (blankline <|> nonspaceChar)) guard $ not . null . trim $ val let key' = concat $ words $ map toLower key let val' = MetaBlocks $ B.toList $ B.plain $ B.text $ trim val return (key',val') where spaceNoNewline = satisfy (\x -> isSpace x && (x/='\n') && (x/='\r')) parseMarkdown :: MarkdownParser Pandoc parseMarkdown = do -- markdown allows raw HTML updateState $ \state -> state { stateOptions = let oldOpts = stateOptions state in oldOpts{ readerParseRaw = True } } optional titleBlock blocks <- parseBlocks st <- getState let meta = runF (stateMeta' st) st let Pandoc _ bs = B.doc $ runF blocks st return $ Pandoc meta bs referenceKey :: MarkdownParser (F Blocks) referenceKey = try $ do pos <- getPosition skipNonindentSpaces (_,raw) <- reference char ':' skipSpaces >> optional newline >> skipSpaces >> notFollowedBy (char '[') let sourceURL = liftM unwords $ many $ try $ do skipMany spaceChar notFollowedBy' referenceTitle notFollowedBy' (() <$ reference) many1 $ notFollowedBy space >> litChar let betweenAngles = try $ char '<' >> manyTill litChar (char '>') src <- try betweenAngles <|> sourceURL tit <- option "" referenceTitle -- currently we just ignore MMD-style link/image attributes _kvs <- option [] $ guardEnabled Ext_link_attributes >> many (try $ spnl >> keyValAttr) blanklines let target = (escapeURI $ trimr src, tit) st <- getState let oldkeys = stateKeys st let key = toKey raw case M.lookup key oldkeys of Just _ -> addWarning (Just pos) $ "Duplicate link reference `" ++ raw ++ "'" Nothing -> return () updateState $ \s -> s { stateKeys = M.insert key target oldkeys } return $ return mempty referenceTitle :: MarkdownParser String referenceTitle = try $ do skipSpaces >> optional newline >> skipSpaces quotedTitle '"' <|> quotedTitle '\'' <|> charsInBalanced '(' ')' litChar -- A link title in quotes quotedTitle :: Char -> MarkdownParser String quotedTitle c = try $ do char c notFollowedBy spaces let pEnder = try $ char c >> notFollowedBy (satisfy isAlphaNum) let regChunk = many1 (noneOf ['\\','\n','&',c]) <|> count 1 litChar let nestedChunk = (\x -> [c] ++ x ++ [c]) <$> quotedTitle c unwords . words . concat <$> manyTill (nestedChunk <|> regChunk) pEnder -- | PHP Markdown Extra style abbreviation key. Currently -- we just skip them, since Pandoc doesn't have an element for -- an abbreviation. abbrevKey :: MarkdownParser (F Blocks) abbrevKey = do guardEnabled Ext_abbreviations try $ do char '*' reference char ':' skipMany (satisfy (/= '\n')) blanklines return $ return mempty noteMarker :: MarkdownParser String noteMarker = string "[^" >> many1Till (satisfy $ not . isBlank) (char ']') rawLine :: MarkdownParser String rawLine = try $ do notFollowedBy blankline notFollowedBy' $ try $ skipNonindentSpaces >> noteMarker optional indentSpaces anyLine rawLines :: MarkdownParser String rawLines = do first <- anyLine rest <- many rawLine return $ unlines (first:rest) noteBlock :: MarkdownParser (F Blocks) noteBlock = try $ do pos <- getPosition skipNonindentSpaces ref <- noteMarker char ':' optional blankline optional indentSpaces first <- rawLines rest <- many $ try $ blanklines >> indentSpaces >> rawLines let raw = unlines (first:rest) ++ "\n" optional blanklines parsed <- parseFromString parseBlocks raw let newnote = (ref, parsed) oldnotes <- stateNotes' <$> getState case lookup ref oldnotes of Just _ -> addWarning (Just pos) $ "Duplicate note reference `" ++ ref ++ "'" Nothing -> return () updateState $ \s -> s { stateNotes' = newnote : oldnotes } return mempty -- -- parsing blocks -- parseBlocks :: MarkdownParser (F Blocks) parseBlocks = mconcat <$> manyTill block eof block :: MarkdownParser (F Blocks) block = do tr <- getOption readerTrace pos <- getPosition res <- choice [ mempty <$ blanklines , codeBlockFenced , yamlMetaBlock , guardEnabled Ext_latex_macros *> (macro >>= return . return) -- note: bulletList needs to be before header because of -- the possibility of empty list items: - , bulletList , header , lhsCodeBlock , divHtml , htmlBlock , table , codeBlockIndented , rawTeXBlock , lineBlock , blockQuote , hrule , orderedList , definitionList , noteBlock , referenceKey , abbrevKey , para , plain ] <?> "block" when tr $ do st <- getState trace (printf "line %d: %s" (sourceLine pos) (take 60 $ show $ B.toList $ runF res st)) (return ()) return res -- -- header blocks -- header :: MarkdownParser (F Blocks) header = setextHeader <|> atxHeader <?> "header" atxChar :: MarkdownParser Char atxChar = do exts <- getOption readerExtensions return $ if Set.member Ext_literate_haskell exts then '=' else '#' atxHeader :: MarkdownParser (F Blocks) atxHeader = try $ do level <- atxChar >>= many1 . char >>= return . length notFollowedBy $ guardEnabled Ext_fancy_lists >> (char '.' <|> char ')') -- this would be a list skipSpaces (text, raw) <- withRaw $ trimInlinesF . mconcat <$> many (notFollowedBy atxClosing >> inline) attr <- atxClosing attr'@(ident,_,_) <- registerHeader attr (runF text defaultParserState) guardDisabled Ext_implicit_header_references <|> registerImplicitHeader raw ident return $ B.headerWith attr' level <$> text atxClosing :: MarkdownParser Attr atxClosing = try $ do attr' <- option nullAttr (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier) skipMany . char =<< atxChar skipSpaces attr <- option attr' (guardEnabled Ext_header_attributes >> attributes) blanklines return attr setextHeaderEnd :: MarkdownParser Attr setextHeaderEnd = try $ do attr <- option nullAttr $ (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier) <|> (guardEnabled Ext_header_attributes >> attributes) blanklines return attr mmdHeaderIdentifier :: MarkdownParser Attr mmdHeaderIdentifier = do ident <- stripFirstAndLast . snd <$> reference skipSpaces return (ident,[],[]) setextHeader :: MarkdownParser (F Blocks) setextHeader = try $ do -- This lookahead prevents us from wasting time parsing Inlines -- unless necessary -- it gives a significant performance boost. lookAhead $ anyLine >> many1 (oneOf setextHChars) >> blankline skipSpaces (text, raw) <- withRaw $ trimInlinesF . mconcat <$> many1 (notFollowedBy setextHeaderEnd >> inline) attr <- setextHeaderEnd underlineChar <- oneOf setextHChars many (char underlineChar) blanklines let level = (fromMaybe 0 $ findIndex (== underlineChar) setextHChars) + 1 attr'@(ident,_,_) <- registerHeader attr (runF text defaultParserState) guardDisabled Ext_implicit_header_references <|> registerImplicitHeader raw ident return $ B.headerWith attr' level <$> text registerImplicitHeader :: String -> String -> MarkdownParser () registerImplicitHeader raw ident = do let key = toKey $ "[" ++ raw ++ "]" updateState (\s -> s { stateHeaderKeys = M.insert key ('#':ident,"") (stateHeaderKeys s) }) -- -- hrule block -- hrule :: Parser [Char] st (F Blocks) hrule = try $ do skipSpaces start <- satisfy isHruleChar count 2 (skipSpaces >> char start) skipMany (spaceChar <|> char start) newline optional blanklines return $ return B.horizontalRule -- -- code blocks -- indentedLine :: MarkdownParser String indentedLine = indentSpaces >> anyLine >>= return . (++ "\n") blockDelimiter :: (Char -> Bool) -> Maybe Int -> Parser [Char] st Int blockDelimiter f len = try $ do c <- lookAhead (satisfy f) case len of Just l -> count l (char c) >> many (char c) >> return l Nothing -> count 3 (char c) >> many (char c) >>= return . (+ 3) . length attributes :: MarkdownParser Attr attributes = try $ do char '{' spnl attrs <- many (attribute <* spnl) char '}' return $ foldl (\x f -> f x) nullAttr attrs attribute :: MarkdownParser (Attr -> Attr) attribute = identifierAttr <|> classAttr <|> keyValAttr <|> specialAttr identifier :: MarkdownParser String identifier = do first <- letter rest <- many $ alphaNum <|> oneOf "-_:." return (first:rest) identifierAttr :: MarkdownParser (Attr -> Attr) identifierAttr = try $ do char '#' result <- identifier return $ \(_,cs,kvs) -> (result,cs,kvs) classAttr :: MarkdownParser (Attr -> Attr) classAttr = try $ do char '.' result <- identifier return $ \(id',cs,kvs) -> (id',cs ++ [result],kvs) keyValAttr :: MarkdownParser (Attr -> Attr) keyValAttr = try $ do key <- identifier char '=' val <- enclosed (char '"') (char '"') litChar <|> enclosed (char '\'') (char '\'') litChar <|> many (escapedChar' <|> noneOf " \t\n\r}") return $ \(id',cs,kvs) -> case key of "id" -> (val,cs,kvs) "class" -> (id',cs ++ words val,kvs) _ -> (id',cs,kvs ++ [(key,val)]) specialAttr :: MarkdownParser (Attr -> Attr) specialAttr = do char '-' return $ \(id',cs,kvs) -> (id',cs ++ ["unnumbered"],kvs) codeBlockFenced :: MarkdownParser (F Blocks) codeBlockFenced = try $ do c <- try (guardEnabled Ext_fenced_code_blocks >> lookAhead (char '~')) <|> (guardEnabled Ext_backtick_code_blocks >> lookAhead (char '`')) size <- blockDelimiter (== c) Nothing skipMany spaceChar attr <- option ([],[],[]) $ try (guardEnabled Ext_fenced_code_attributes >> attributes) <|> ((\x -> ("",[toLanguageId x],[])) <$> many1 nonspaceChar) blankline contents <- manyTill anyLine (blockDelimiter (== c) (Just size)) blanklines return $ return $ B.codeBlockWith attr $ intercalate "\n" contents -- correctly handle github language identifiers toLanguageId :: String -> String toLanguageId = map toLower . go where go "c++" = "cpp" go "objective-c" = "objectivec" go x = x codeBlockIndented :: MarkdownParser (F Blocks) codeBlockIndented = do contents <- many1 (indentedLine <|> try (do b <- blanklines l <- indentedLine return $ b ++ l)) optional blanklines classes <- getOption readerIndentedCodeClasses return $ return $ B.codeBlockWith ("", classes, []) $ stripTrailingNewlines $ concat contents lhsCodeBlock :: MarkdownParser (F Blocks) lhsCodeBlock = do guardEnabled Ext_literate_haskell (return . B.codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$> (lhsCodeBlockBird <|> lhsCodeBlockLaTeX)) <|> (return . B.codeBlockWith ("",["sourceCode","haskell"],[]) <$> lhsCodeBlockInverseBird) lhsCodeBlockLaTeX :: MarkdownParser String lhsCodeBlockLaTeX = try $ do string "\\begin{code}" manyTill spaceChar newline contents <- many1Till anyChar (try $ string "\\end{code}") blanklines return $ stripTrailingNewlines contents lhsCodeBlockBird :: MarkdownParser String lhsCodeBlockBird = lhsCodeBlockBirdWith '>' lhsCodeBlockInverseBird :: MarkdownParser String lhsCodeBlockInverseBird = lhsCodeBlockBirdWith '<' lhsCodeBlockBirdWith :: Char -> MarkdownParser String lhsCodeBlockBirdWith c = try $ do pos <- getPosition when (sourceColumn pos /= 1) $ fail "Not in first column" lns <- many1 $ birdTrackLine c -- if (as is normal) there is always a space after >, drop it let lns' = if all (\ln -> null ln || take 1 ln == " ") lns then map (drop 1) lns else lns blanklines return $ intercalate "\n" lns' birdTrackLine :: Char -> Parser [Char] st String birdTrackLine c = try $ do char c -- allow html tags on left margin: when (c == '<') $ notFollowedBy letter anyLine -- -- block quotes -- emailBlockQuoteStart :: MarkdownParser Char emailBlockQuoteStart = try $ skipNonindentSpaces >> char '>' <* optional (char ' ') emailBlockQuote :: MarkdownParser [String] emailBlockQuote = try $ do emailBlockQuoteStart let emailLine = many $ nonEndline <|> try (endline >> notFollowedBy emailBlockQuoteStart >> return '\n') let emailSep = try (newline >> emailBlockQuoteStart) first <- emailLine rest <- many $ try $ emailSep >> emailLine let raw = first:rest newline <|> (eof >> return '\n') optional blanklines return raw blockQuote :: MarkdownParser (F Blocks) blockQuote = do raw <- emailBlockQuote -- parse the extracted block, which may contain various block elements: contents <- parseFromString parseBlocks $ (intercalate "\n" raw) ++ "\n\n" return $ B.blockQuote <$> contents -- -- list blocks -- bulletListStart :: MarkdownParser () bulletListStart = try $ do optional newline -- if preceded by a Plain block in a list context startpos <- sourceColumn <$> getPosition skipNonindentSpaces notFollowedBy' (() <$ hrule) -- because hrules start out just like lists satisfy isBulletListMarker endpos <- sourceColumn <$> getPosition tabStop <- getOption readerTabStop lookAhead (newline <|> spaceChar) () <$ atMostSpaces (tabStop - (endpos - startpos)) anyOrderedListStart :: MarkdownParser (Int, ListNumberStyle, ListNumberDelim) anyOrderedListStart = try $ do optional newline -- if preceded by a Plain block in a list context startpos <- sourceColumn <$> getPosition skipNonindentSpaces notFollowedBy $ string "p." >> spaceChar >> digit -- page number res <- do guardDisabled Ext_fancy_lists start <- many1 digit >>= safeRead char '.' return (start, DefaultStyle, DefaultDelim) <|> do (num, style, delim) <- anyOrderedListMarker -- if it could be an abbreviated first name, -- insist on more than one space when (delim == Period && (style == UpperAlpha || (style == UpperRoman && num `elem` [1, 5, 10, 50, 100, 500, 1000]))) $ () <$ spaceChar return (num, style, delim) endpos <- sourceColumn <$> getPosition tabStop <- getOption readerTabStop lookAhead (newline <|> spaceChar) atMostSpaces (tabStop - (endpos - startpos)) return res listStart :: MarkdownParser () listStart = bulletListStart <|> (anyOrderedListStart >> return ()) listLine :: MarkdownParser String listLine = try $ do notFollowedBy' (do indentSpaces many spaceChar listStart) notFollowedByHtmlCloser optional (() <$ indentSpaces) listLineCommon listLineCommon :: MarkdownParser String listLineCommon = concat <$> manyTill ( many1 (satisfy $ \c -> c /= '\n' && c /= '<') <|> liftM snd (htmlTag isCommentTag) <|> count 1 anyChar ) newline -- parse raw text for one list item, excluding start marker and continuations rawListItem :: MarkdownParser a -> MarkdownParser String rawListItem start = try $ do start first <- listLineCommon rest <- many (notFollowedBy listStart >> notFollowedBy blankline >> listLine) blanks <- many blankline return $ unlines (first:rest) ++ blanks -- continuation of a list item - indented and separated by blankline -- or (in compact lists) endline. -- note: nested lists are parsed as continuations listContinuation :: MarkdownParser String listContinuation = try $ do lookAhead indentSpaces result <- many1 listContinuationLine blanks <- many blankline return $ concat result ++ blanks notFollowedByHtmlCloser :: MarkdownParser () notFollowedByHtmlCloser = do inHtmlBlock <- stateInHtmlBlock <$> getState case inHtmlBlock of Just t -> notFollowedBy' $ htmlTag (~== TagClose t) Nothing -> return () listContinuationLine :: MarkdownParser String listContinuationLine = try $ do notFollowedBy blankline notFollowedBy' listStart notFollowedByHtmlCloser optional indentSpaces result <- anyLine return $ result ++ "\n" listItem :: MarkdownParser a -> MarkdownParser (F Blocks) listItem start = try $ do first <- rawListItem start continuations <- many listContinuation -- parsing with ListItemState forces markers at beginning of lines to -- count as list item markers, even if not separated by blank space. -- see definition of "endline" state <- getState let oldContext = stateParserContext state setState $ state {stateParserContext = ListItemState} -- parse the extracted block, which may contain various block elements: let raw = concat (first:continuations) contents <- parseFromString parseBlocks raw updateState (\st -> st {stateParserContext = oldContext}) return contents orderedList :: MarkdownParser (F Blocks) orderedList = try $ do (start, style, delim) <- lookAhead anyOrderedListStart unless (style `elem` [DefaultStyle, Decimal, Example] && delim `elem` [DefaultDelim, Period]) $ guardEnabled Ext_fancy_lists when (style == Example) $ guardEnabled Ext_example_lists items <- fmap sequence $ many1 $ listItem ( try $ do optional newline -- if preceded by Plain block in a list startpos <- sourceColumn <$> getPosition skipNonindentSpaces res <- orderedListMarker style delim endpos <- sourceColumn <$> getPosition tabStop <- getOption readerTabStop lookAhead (newline <|> spaceChar) atMostSpaces (tabStop - (endpos - startpos)) return res ) start' <- option 1 $ guardEnabled Ext_startnum >> return start return $ B.orderedListWith (start', style, delim) <$> fmap compactify' items bulletList :: MarkdownParser (F Blocks) bulletList = do items <- fmap sequence $ many1 $ listItem bulletListStart return $ B.bulletList <$> fmap compactify' items -- definition lists defListMarker :: MarkdownParser () defListMarker = do sps <- nonindentSpaces char ':' <|> char '~' tabStop <- getOption readerTabStop let remaining = tabStop - (length sps + 1) if remaining > 0 then try (count remaining (char ' ')) <|> string "\t" <|> many1 spaceChar else mzero return () definitionListItem :: Bool -> MarkdownParser (F (Inlines, [Blocks])) definitionListItem compact = try $ do rawLine' <- anyLine raw <- many1 $ defRawBlock compact term <- parseFromString (trimInlinesF . mconcat <$> many inline) rawLine' contents <- mapM (parseFromString parseBlocks . (++"\n")) raw optional blanklines return $ liftM2 (,) term (sequence contents) defRawBlock :: Bool -> MarkdownParser String defRawBlock compact = try $ do hasBlank <- option False $ blankline >> return True defListMarker firstline <- anyLine let dline = try ( do notFollowedBy blankline notFollowedByHtmlCloser if compact -- laziness not compatible with compact then () <$ indentSpaces else (() <$ indentSpaces) <|> notFollowedBy defListMarker anyLine ) rawlines <- many dline cont <- liftM concat $ many $ try $ do trailing <- option "" blanklines ln <- indentSpaces >> notFollowedBy blankline >> anyLine lns <- many dline return $ trailing ++ unlines (ln:lns) return $ trimr (firstline ++ "\n" ++ unlines rawlines ++ cont) ++ if hasBlank || not (null cont) then "\n\n" else "" definitionList :: MarkdownParser (F Blocks) definitionList = try $ do lookAhead (anyLine >> optional (blankline >> notFollowedBy (table >> return ())) >> -- don't capture table caption as def list! defListMarker) compactDefinitionList <|> normalDefinitionList compactDefinitionList :: MarkdownParser (F Blocks) compactDefinitionList = do guardEnabled Ext_compact_definition_lists items <- fmap sequence $ many1 $ definitionListItem True return $ B.definitionList <$> fmap compactify'DL items normalDefinitionList :: MarkdownParser (F Blocks) normalDefinitionList = do guardEnabled Ext_definition_lists items <- fmap sequence $ many1 $ definitionListItem False return $ B.definitionList <$> items -- -- paragraph block -- para :: MarkdownParser (F Blocks) para = try $ do exts <- getOption readerExtensions result <- trimInlinesF . mconcat <$> many1 inline option (B.plain <$> result) $ try $ do newline (blanklines >> return mempty) <|> (guardDisabled Ext_blank_before_blockquote >> () <$ lookAhead blockQuote) <|> (guardEnabled Ext_backtick_code_blocks >> () <$ lookAhead codeBlockFenced) <|> (guardDisabled Ext_blank_before_header >> () <$ lookAhead header) <|> (guardEnabled Ext_lists_without_preceding_blankline >> -- Avoid creating a paragraph in a nested list. notFollowedBy' inList >> () <$ lookAhead listStart) <|> do guardEnabled Ext_native_divs inHtmlBlock <- stateInHtmlBlock <$> getState case inHtmlBlock of Just "div" -> () <$ lookAhead (htmlTag (~== TagClose "div")) _ -> mzero return $ do result' <- result case B.toList result' of [Image alt (src,tit)] | Ext_implicit_figures `Set.member` exts -> -- the fig: at beginning of title indicates a figure return $ B.para $ B.singleton $ Image alt (src,'f':'i':'g':':':tit) _ -> return $ B.para result' plain :: MarkdownParser (F Blocks) plain = fmap B.plain . trimInlinesF . mconcat <$> many1 inline -- -- raw html -- htmlElement :: MarkdownParser String htmlElement = rawVerbatimBlock <|> strictHtmlBlock <|> liftM snd (htmlTag isBlockTag) htmlBlock :: MarkdownParser (F Blocks) htmlBlock = do guardEnabled Ext_raw_html try (do (TagOpen t attrs) <- lookAhead $ fst <$> htmlTag isBlockTag (guard (t `elem` ["pre","style","script"]) >> (return . B.rawBlock "html") <$> rawVerbatimBlock) <|> (do guardEnabled Ext_markdown_attribute oldMarkdownAttribute <- stateMarkdownAttribute <$> getState markdownAttribute <- case lookup "markdown" attrs of Just "0" -> False <$ updateState (\st -> st{ stateMarkdownAttribute = False }) Just _ -> True <$ updateState (\st -> st{ stateMarkdownAttribute = True }) Nothing -> return oldMarkdownAttribute res <- if markdownAttribute then rawHtmlBlocks else htmlBlock' updateState $ \st -> st{ stateMarkdownAttribute = oldMarkdownAttribute } return res) <|> (guardEnabled Ext_markdown_in_html_blocks >> rawHtmlBlocks)) <|> htmlBlock' htmlBlock' :: MarkdownParser (F Blocks) htmlBlock' = try $ do first <- htmlElement skipMany spaceChar optional blanklines return $ return $ B.rawBlock "html" first strictHtmlBlock :: MarkdownParser String strictHtmlBlock = htmlInBalanced (not . isInlineTag) rawVerbatimBlock :: MarkdownParser String rawVerbatimBlock = try $ do (TagOpen tag _, open) <- htmlTag (tagOpen (flip elem ["pre", "style", "script"]) (const True)) contents <- manyTill anyChar (htmlTag (~== TagClose tag)) return $ open ++ contents ++ renderTags' [TagClose tag] rawTeXBlock :: MarkdownParser (F Blocks) rawTeXBlock = do guardEnabled Ext_raw_tex result <- (B.rawBlock "latex" . concat <$> rawLaTeXBlock `sepEndBy1` blankline) <|> (B.rawBlock "context" . concat <$> rawConTeXtEnvironment `sepEndBy1` blankline) spaces return $ return result rawHtmlBlocks :: MarkdownParser (F Blocks) rawHtmlBlocks = do (TagOpen tagtype _, raw) <- htmlTag isBlockTag -- try to find closing tag -- we set stateInHtmlBlock so that closing tags that can be either block or -- inline will not be parsed as inline tags oldInHtmlBlock <- stateInHtmlBlock <$> getState updateState $ \st -> st{ stateInHtmlBlock = Just tagtype } let closer = htmlTag (\x -> x ~== TagClose tagtype) contents <- mconcat <$> many (notFollowedBy' closer >> block) result <- (closer >>= \(_, rawcloser) -> return ( return (B.rawBlock "html" $ stripMarkdownAttribute raw) <> contents <> return (B.rawBlock "html" rawcloser))) <|> return (return (B.rawBlock "html" raw) <> contents) updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock } return result -- remove markdown="1" attribute stripMarkdownAttribute :: String -> String stripMarkdownAttribute s = renderTags' $ map filterAttrib $ parseTags s where filterAttrib (TagOpen t as) = TagOpen t [(k,v) | (k,v) <- as, k /= "markdown"] filterAttrib x = x -- -- line block -- lineBlock :: MarkdownParser (F Blocks) lineBlock = try $ do guardEnabled Ext_line_blocks lines' <- lineBlockLines >>= mapM (parseFromString (trimInlinesF . mconcat <$> many inline)) return $ B.para <$> (mconcat $ intersperse (return B.linebreak) lines') -- -- Tables -- -- Parse a dashed line with optional trailing spaces; return its length -- and the length including trailing space. dashedLine :: Char -> Parser [Char] st (Int, Int) dashedLine ch = do dashes <- many1 (char ch) sp <- many spaceChar let lengthDashes = length dashes lengthSp = length sp return (lengthDashes, lengthDashes + lengthSp) -- Parse a table header with dashed lines of '-' preceded by -- one (or zero) line of text. simpleTableHeader :: Bool -- ^ Headerless table -> MarkdownParser (F [Blocks], [Alignment], [Int]) simpleTableHeader headless = try $ do rawContent <- if headless then return "" else anyLine initSp <- nonindentSpaces dashes <- many1 (dashedLine '-') newline let (lengths, lines') = unzip dashes let indices = scanl (+) (length initSp) lines' -- If no header, calculate alignment on basis of first row of text rawHeads <- liftM (tail . splitStringByIndices (init indices)) $ if headless then lookAhead anyLine else return rawContent let aligns = zipWith alignType (map (\a -> [a]) rawHeads) lengths let rawHeads' = if headless then replicate (length dashes) "" else rawHeads heads <- fmap sequence $ mapM (parseFromString (mconcat <$> many plain)) $ map trim rawHeads' return (heads, aligns, indices) -- Returns an alignment type for a table, based on a list of strings -- (the rows of the column header) and a number (the length of the -- dashed line under the rows. alignType :: [String] -> Int -> Alignment alignType [] _ = AlignDefault alignType strLst len = let nonempties = filter (not . null) $ map trimr strLst (leftSpace, rightSpace) = case sortBy (comparing length) nonempties of (x:_) -> (head x `elem` " \t", length x < len) [] -> (False, False) in case (leftSpace, rightSpace) of (True, False) -> AlignRight (False, True) -> AlignLeft (True, True) -> AlignCenter (False, False) -> AlignDefault -- Parse a table footer - dashed lines followed by blank line. tableFooter :: MarkdownParser String tableFooter = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> blanklines -- Parse a table separator - dashed line. tableSep :: MarkdownParser Char tableSep = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> char '\n' -- Parse a raw line and split it into chunks by indices. rawTableLine :: [Int] -> MarkdownParser [String] rawTableLine indices = do notFollowedBy' (blanklines <|> tableFooter) line <- many1Till anyChar newline return $ map trim $ tail $ splitStringByIndices (init indices) line -- Parse a table line and return a list of lists of blocks (columns). tableLine :: [Int] -> MarkdownParser (F [Blocks]) tableLine indices = rawTableLine indices >>= fmap sequence . mapM (parseFromString (mconcat <$> many plain)) -- Parse a multiline table row and return a list of blocks (columns). multilineRow :: [Int] -> MarkdownParser (F [Blocks]) multilineRow indices = do colLines <- many1 (rawTableLine indices) let cols = map unlines $ transpose colLines fmap sequence $ mapM (parseFromString (mconcat <$> many plain)) cols -- Parses a table caption: inlines beginning with 'Table:' -- and followed by blank lines. tableCaption :: MarkdownParser (F Inlines) tableCaption = try $ do guardEnabled Ext_table_captions skipNonindentSpaces string ":" <|> string "Table:" trimInlinesF . mconcat <$> many1 inline <* blanklines -- Parse a simple table with '---' header and one line per row. simpleTable :: Bool -- ^ Headerless table -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) simpleTable headless = do (aligns, _widths, heads', lines') <- tableWith (simpleTableHeader headless) tableLine (return ()) (if headless then tableFooter else tableFooter <|> blanklines) -- Simple tables get 0s for relative column widths (i.e., use default) return (aligns, replicate (length aligns) 0, heads', lines') -- Parse a multiline table: starts with row of '-' on top, then header -- (which may be multiline), then the rows, -- which may be multiline, separated by blank lines, and -- ending with a footer (dashed line followed by blank line). multilineTable :: Bool -- ^ Headerless table -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) multilineTable headless = tableWith (multilineTableHeader headless) multilineRow blanklines tableFooter multilineTableHeader :: Bool -- ^ Headerless table -> MarkdownParser (F [Blocks], [Alignment], [Int]) multilineTableHeader headless = try $ do unless headless $ tableSep >> notFollowedBy blankline rawContent <- if headless then return $ repeat "" else many1 $ notFollowedBy tableSep >> anyLine initSp <- nonindentSpaces dashes <- many1 (dashedLine '-') newline let (lengths, lines') = unzip dashes let indices = scanl (+) (length initSp) lines' rawHeadsList <- if headless then liftM (map (:[]) . tail . splitStringByIndices (init indices)) $ lookAhead anyLine else return $ transpose $ map (tail . splitStringByIndices (init indices)) rawContent let aligns = zipWith alignType rawHeadsList lengths let rawHeads = if headless then replicate (length dashes) "" else map (unlines . map trim) rawHeadsList heads <- fmap sequence $ mapM (parseFromString (mconcat <$> many plain)) $ map trim rawHeads return (heads, aligns, indices) -- Parse a grid table: starts with row of '-' on top, then header -- (which may be grid), then the rows, -- which may be grid, separated by blank lines, and -- ending with a footer (dashed line followed by blank line). gridTable :: Bool -- ^ Headerless table -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) gridTable headless = tableWith (gridTableHeader headless) gridTableRow (gridTableSep '-') gridTableFooter gridTableSplitLine :: [Int] -> String -> [String] gridTableSplitLine indices line = map removeFinalBar $ tail $ splitStringByIndices (init indices) $ trimr line gridPart :: Char -> Parser [Char] st (Int, Int) gridPart ch = do dashes <- many1 (char ch) char '+' let lengthDashes = length dashes return (lengthDashes, lengthDashes + 1) gridDashedLines :: Char -> Parser [Char] st [(Int,Int)] gridDashedLines ch = try $ char '+' >> many1 (gridPart ch) <* blankline removeFinalBar :: String -> String removeFinalBar = reverse . dropWhile (`elem` " \t") . dropWhile (=='|') . reverse -- | Separator between rows of grid table. gridTableSep :: Char -> MarkdownParser Char gridTableSep ch = try $ gridDashedLines ch >> return '\n' -- | Parse header for a grid table. gridTableHeader :: Bool -- ^ Headerless table -> MarkdownParser (F [Blocks], [Alignment], [Int]) gridTableHeader headless = try $ do optional blanklines dashes <- gridDashedLines '-' rawContent <- if headless then return $ repeat "" else many1 (notFollowedBy (gridTableSep '=') >> char '|' >> many1Till anyChar newline) if headless then return () else gridTableSep '=' >> return () let lines' = map snd dashes let indices = scanl (+) 0 lines' let aligns = replicate (length lines') AlignDefault -- RST does not have a notion of alignments let rawHeads = if headless then replicate (length dashes) "" else map (unlines . map trim) $ transpose $ map (gridTableSplitLine indices) rawContent heads <- fmap sequence $ mapM (parseFromString parseBlocks . trim) rawHeads return (heads, aligns, indices) gridTableRawLine :: [Int] -> MarkdownParser [String] gridTableRawLine indices = do char '|' line <- many1Till anyChar newline return (gridTableSplitLine indices line) -- | Parse row of grid table. gridTableRow :: [Int] -> MarkdownParser (F [Blocks]) gridTableRow indices = do colLines <- many1 (gridTableRawLine indices) let cols = map ((++ "\n") . unlines . removeOneLeadingSpace) $ transpose colLines fmap compactify' <$> fmap sequence (mapM (parseFromString parseBlocks) cols) removeOneLeadingSpace :: [String] -> [String] removeOneLeadingSpace xs = if all startsWithSpace xs then map (drop 1) xs else xs where startsWithSpace "" = True startsWithSpace (y:_) = y == ' ' -- | Parse footer for a grid table. gridTableFooter :: MarkdownParser [Char] gridTableFooter = blanklines pipeBreak :: MarkdownParser [Alignment] pipeBreak = try $ do nonindentSpaces openPipe <- (True <$ char '|') <|> return False first <- pipeTableHeaderPart rest <- many $ sepPipe *> pipeTableHeaderPart -- surrounding pipes needed for a one-column table: guard $ not (null rest && not openPipe) optional (char '|') blankline return (first:rest) pipeTable :: MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) pipeTable = try $ do nonindentSpaces lookAhead nonspaceChar (heads,aligns) <- (,) <$> pipeTableRow <*> pipeBreak lines' <- sequence <$> many pipeTableRow let widths = replicate (length aligns) 0.0 return $ (aligns, widths, heads, lines') sepPipe :: MarkdownParser () sepPipe = try $ do char '|' <|> char '+' notFollowedBy blankline -- parse a row, also returning probable alignments for org-table cells pipeTableRow :: MarkdownParser (F [Blocks]) pipeTableRow = do skipMany spaceChar openPipe <- (True <$ char '|') <|> return False let cell = mconcat <$> many (notFollowedBy (blankline <|> char '|') >> inline) first <- cell rest <- many $ sepPipe *> cell -- surrounding pipes needed for a one-column table: guard $ not (null rest && not openPipe) optional (char '|') blankline let cells = sequence (first:rest) return $ do cells' <- cells return $ map (\ils -> case trimInlines ils of ils' | B.isNull ils' -> mempty | otherwise -> B.plain $ ils') cells' pipeTableHeaderPart :: Parser [Char] st Alignment pipeTableHeaderPart = try $ do skipMany spaceChar left <- optionMaybe (char ':') many1 (char '-') right <- optionMaybe (char ':') skipMany spaceChar return $ case (left,right) of (Nothing,Nothing) -> AlignDefault (Just _,Nothing) -> AlignLeft (Nothing,Just _) -> AlignRight (Just _,Just _) -> AlignCenter -- Succeed only if current line contains a pipe. scanForPipe :: Parser [Char] st () scanForPipe = do inp <- getInput case break (\c -> c == '\n' || c == '|') inp of (_,'|':_) -> return () _ -> mzero -- | Parse a table using 'headerParser', 'rowParser', -- 'lineParser', and 'footerParser'. Variant of the version in -- Text.Pandoc.Parsing. tableWith :: MarkdownParser (F [Blocks], [Alignment], [Int]) -> ([Int] -> MarkdownParser (F [Blocks])) -> MarkdownParser sep -> MarkdownParser end -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) tableWith headerParser rowParser lineParser footerParser = try $ do (heads, aligns, indices) <- headerParser lines' <- fmap sequence $ rowParser indices `sepEndBy1` lineParser footerParser numColumns <- getOption readerColumns let widths = if (indices == []) then replicate (length aligns) 0.0 else widthsFromIndices numColumns indices return $ (aligns, widths, heads, lines') table :: MarkdownParser (F Blocks) table = try $ do frontCaption <- option Nothing (Just <$> tableCaption) (aligns, widths, heads, lns) <- try (guardEnabled Ext_pipe_tables >> scanForPipe >> pipeTable) <|> try (guardEnabled Ext_multiline_tables >> multilineTable False) <|> try (guardEnabled Ext_simple_tables >> (simpleTable True <|> simpleTable False)) <|> try (guardEnabled Ext_multiline_tables >> multilineTable True) <|> try (guardEnabled Ext_grid_tables >> (gridTable False <|> gridTable True)) <?> "table" optional blanklines caption <- case frontCaption of Nothing -> option (return mempty) tableCaption Just c -> return c return $ do caption' <- caption heads' <- heads lns' <- lns return $ B.table caption' (zip aligns widths) heads' lns' -- -- inline -- inline :: MarkdownParser (F Inlines) inline = choice [ whitespace , bareURL , str , endline , code , strongOrEmph , note , cite , link , image , math , strikeout , subscript , superscript , inlineNote -- after superscript because of ^[link](/foo)^ , autoLink , spanHtml , rawHtmlInline , escapedChar , rawLaTeXInline' , exampleRef , smart , return . B.singleton <$> charRef , symbol , ltSign ] <?> "inline" escapedChar' :: MarkdownParser Char escapedChar' = try $ do char '\\' (guardEnabled Ext_all_symbols_escapable >> satisfy (not . isAlphaNum)) <|> oneOf "\\`*_{}[]()>#+-.!~\"" escapedChar :: MarkdownParser (F Inlines) escapedChar = do result <- escapedChar' case result of ' ' -> return $ return $ B.str "\160" -- "\ " is a nonbreaking space '\n' -> guardEnabled Ext_escaped_line_breaks >> return (return B.linebreak) -- "\[newline]" is a linebreak _ -> return $ return $ B.str [result] ltSign :: MarkdownParser (F Inlines) ltSign = do guardDisabled Ext_raw_html <|> (notFollowedByHtmlCloser >> notFollowedBy' (htmlTag isBlockTag)) char '<' return $ return $ B.str "<" exampleRef :: MarkdownParser (F Inlines) exampleRef = try $ do guardEnabled Ext_example_lists char '@' lab <- many1 (alphaNum <|> oneOf "-_") return $ do st <- askF return $ case M.lookup lab (stateExamples st) of Just n -> B.str (show n) Nothing -> B.str ('@':lab) symbol :: MarkdownParser (F Inlines) symbol = do result <- noneOf "<\\\n\t " <|> try (do lookAhead $ char '\\' notFollowedBy' (() <$ rawTeXBlock) char '\\') return $ return $ B.str [result] -- parses inline code, between n `s and n `s code :: MarkdownParser (F Inlines) code = try $ do starts <- many1 (char '`') skipSpaces result <- many1Till (many1 (noneOf "`\n") <|> many1 (char '`') <|> (char '\n' >> notFollowedBy' blankline >> return " ")) (try (skipSpaces >> count (length starts) (char '`') >> notFollowedBy (char '`'))) attr <- option ([],[],[]) (try $ guardEnabled Ext_inline_code_attributes >> optional whitespace >> attributes) return $ return $ B.codeWith attr $ trim $ concat result math :: MarkdownParser (F Inlines) math = (return . B.displayMath <$> (mathDisplay >>= applyMacros')) <|> (return . B.math <$> (mathInline >>= applyMacros')) <+?> ((getOption readerSmart >>= guard) *> (return <$> apostrophe) <* notFollowedBy space) -- Parses material enclosed in *s, **s, _s, or __s. -- Designed to avoid backtracking. enclosure :: Char -> MarkdownParser (F Inlines) enclosure c = do -- we can't start an enclosure with _ if after a string and -- the intraword_underscores extension is enabled: guardDisabled Ext_intraword_underscores <|> guard (c == '*') <|> (guard =<< notAfterString) cs <- many1 (char c) (return (B.str cs) <>) <$> whitespace <|> do case length cs of 3 -> three c 2 -> two c mempty 1 -> one c mempty _ -> return (return $ B.str cs) ender :: Char -> Int -> MarkdownParser () ender c n = try $ do count n (char c) guard (c == '*') <|> guardDisabled Ext_intraword_underscores <|> notFollowedBy alphaNum -- Parse inlines til you hit one c or a sequence of two cs. -- If one c, emit emph and then parse two. -- If two cs, emit strong and then parse one. -- Otherwise, emit ccc then the results. three :: Char -> MarkdownParser (F Inlines) three c = do contents <- mconcat <$> many (notFollowedBy (ender c 1) >> inline) (ender c 3 >> return ((B.strong . B.emph) <$> contents)) <|> (ender c 2 >> one c (B.strong <$> contents)) <|> (ender c 1 >> two c (B.emph <$> contents)) <|> return (return (B.str [c,c,c]) <> contents) -- Parse inlines til you hit two c's, and emit strong. -- If you never do hit two cs, emit ** plus inlines parsed. two :: Char -> F Inlines -> MarkdownParser (F Inlines) two c prefix' = do contents <- mconcat <$> many (try $ notFollowedBy (ender c 2) >> inline) (ender c 2 >> return (B.strong <$> (prefix' <> contents))) <|> return (return (B.str [c,c]) <> (prefix' <> contents)) -- Parse inlines til you hit a c, and emit emph. -- If you never hit a c, emit * plus inlines parsed. one :: Char -> F Inlines -> MarkdownParser (F Inlines) one c prefix' = do contents <- mconcat <$> many ( (notFollowedBy (ender c 1) >> inline) <|> try (string [c,c] >> notFollowedBy (ender c 1) >> two c mempty) ) (ender c 1 >> return (B.emph <$> (prefix' <> contents))) <|> return (return (B.str [c]) <> (prefix' <> contents)) strongOrEmph :: MarkdownParser (F Inlines) strongOrEmph = enclosure '*' <|> enclosure '_' -- | Parses a list of inlines between start and end delimiters. inlinesBetween :: (Show b) => MarkdownParser a -> MarkdownParser b -> MarkdownParser (F Inlines) inlinesBetween start end = (trimInlinesF . mconcat) <$> try (start >> many1Till inner end) where inner = innerSpace <|> (notFollowedBy' (() <$ whitespace) >> inline) innerSpace = try $ whitespace <* notFollowedBy' end strikeout :: MarkdownParser (F Inlines) strikeout = fmap B.strikeout <$> (guardEnabled Ext_strikeout >> inlinesBetween strikeStart strikeEnd) where strikeStart = string "~~" >> lookAhead nonspaceChar >> notFollowedBy (char '~') strikeEnd = try $ string "~~" superscript :: MarkdownParser (F Inlines) superscript = fmap B.superscript <$> try (do guardEnabled Ext_superscript char '^' mconcat <$> many1Till (notFollowedBy spaceChar >> inline) (char '^')) subscript :: MarkdownParser (F Inlines) subscript = fmap B.subscript <$> try (do guardEnabled Ext_subscript char '~' mconcat <$> many1Till (notFollowedBy spaceChar >> inline) (char '~')) whitespace :: MarkdownParser (F Inlines) whitespace = spaceChar >> return <$> (lb <|> regsp) <?> "whitespace" where lb = spaceChar >> skipMany spaceChar >> option B.space (endline >> return B.linebreak) regsp = skipMany spaceChar >> return B.space nonEndline :: Parser [Char] st Char nonEndline = satisfy (/='\n') str :: MarkdownParser (F Inlines) str = do result <- many1 alphaNum updateLastStrPos let spacesToNbr = map (\c -> if c == ' ' then '\160' else c) isSmart <- getOption readerSmart if isSmart then case likelyAbbrev result of [] -> return $ return $ B.str result xs -> choice (map (\x -> try (string x >> oneOf " \n" >> lookAhead alphaNum >> return (return $ B.str $ result ++ spacesToNbr x ++ "\160"))) xs) <|> (return $ return $ B.str result) else return $ return $ B.str result -- | if the string matches the beginning of an abbreviation (before -- the first period, return strings that would finish the abbreviation. likelyAbbrev :: String -> [String] likelyAbbrev x = let abbrevs = [ "Mr.", "Mrs.", "Ms.", "Capt.", "Dr.", "Prof.", "Gen.", "Gov.", "e.g.", "i.e.", "Sgt.", "St.", "vol.", "vs.", "Sen.", "Rep.", "Pres.", "Hon.", "Rev.", "Ph.D.", "M.D.", "M.A.", "p.", "pp.", "ch.", "sec.", "cf.", "cp."] abbrPairs = map (break (=='.')) abbrevs in map snd $ filter (\(y,_) -> y == x) abbrPairs -- an endline character that can be treated as a space, not a structural break endline :: MarkdownParser (F Inlines) endline = try $ do newline notFollowedBy blankline -- parse potential list-starts differently if in a list: notFollowedBy (inList >> listStart) guardDisabled Ext_lists_without_preceding_blankline <|> notFollowedBy listStart guardEnabled Ext_blank_before_blockquote <|> notFollowedBy emailBlockQuoteStart guardEnabled Ext_blank_before_header <|> (notFollowedBy . char =<< atxChar) -- atx header guardDisabled Ext_backtick_code_blocks <|> notFollowedBy (() <$ (lookAhead (char '`') >> codeBlockFenced)) notFollowedByHtmlCloser (eof >> return mempty) <|> (guardEnabled Ext_hard_line_breaks >> return (return B.linebreak)) <|> (guardEnabled Ext_ignore_line_breaks >> return mempty) <|> (return $ return B.space) -- -- links -- -- a reference label for a link reference :: MarkdownParser (F Inlines, String) reference = do notFollowedBy' (string "[^") -- footnote reference withRaw $ trimInlinesF <$> inlinesInBalancedBrackets parenthesizedChars :: MarkdownParser [Char] parenthesizedChars = do result <- charsInBalanced '(' ')' litChar return $ '(' : result ++ ")" -- source for a link, with optional title source :: MarkdownParser (String, String) source = do char '(' skipSpaces let urlChunk = try parenthesizedChars <|> (notFollowedBy (oneOf " )") >> (count 1 litChar)) <|> try (many1 spaceChar <* notFollowedBy (oneOf "\"')")) let sourceURL = (unwords . words . concat) <$> many urlChunk let betweenAngles = try $ char '<' >> manyTill litChar (char '>') src <- try betweenAngles <|> sourceURL tit <- option "" $ try $ spnl >> linkTitle skipSpaces char ')' return (escapeURI $ trimr src, tit) linkTitle :: MarkdownParser String linkTitle = quotedTitle '"' <|> quotedTitle '\'' link :: MarkdownParser (F Inlines) link = try $ do st <- getState guard $ stateAllowLinks st setState $ st{ stateAllowLinks = False } (lab,raw) <- reference setState $ st{ stateAllowLinks = True } regLink B.link lab <|> referenceLink B.link (lab,raw) regLink :: (String -> String -> Inlines -> Inlines) -> F Inlines -> MarkdownParser (F Inlines) regLink constructor lab = try $ do (src, tit) <- source return $ constructor src tit <$> lab -- a link like [this][ref] or [this][] or [this] referenceLink :: (String -> String -> Inlines -> Inlines) -> (F Inlines, String) -> MarkdownParser (F Inlines) referenceLink constructor (lab, raw) = do sp <- (True <$ lookAhead (char ' ')) <|> return False (_,raw') <- option (mempty, "") $ lookAhead (try (spnl >> normalCite >> return (mempty, ""))) <|> try (spnl >> reference) when (raw' == "") $ guardEnabled Ext_shortcut_reference_links let labIsRef = raw' == "" || raw' == "[]" let key = toKey $ if labIsRef then raw else raw' parsedRaw <- parseFromString (mconcat <$> many inline) raw' fallback <- parseFromString (mconcat <$> many inline) $ dropBrackets raw implicitHeaderRefs <- option False $ True <$ guardEnabled Ext_implicit_header_references let makeFallback = do parsedRaw' <- parsedRaw fallback' <- fallback return $ B.str "[" <> fallback' <> B.str "]" <> (if sp && not (null raw) then B.space else mempty) <> parsedRaw' return $ do keys <- asksF stateKeys case M.lookup key keys of Nothing -> if implicitHeaderRefs then do headerKeys <- asksF stateHeaderKeys case M.lookup key headerKeys of Just (src, tit) -> constructor src tit <$> lab Nothing -> makeFallback else makeFallback Just (src,tit) -> constructor src tit <$> lab dropBrackets :: String -> String dropBrackets = reverse . dropRB . reverse . dropLB where dropRB (']':xs) = xs dropRB xs = xs dropLB ('[':xs) = xs dropLB xs = xs bareURL :: MarkdownParser (F Inlines) bareURL = try $ do guardEnabled Ext_autolink_bare_uris getState >>= guard . stateAllowLinks (orig, src) <- uri <|> emailAddress notFollowedBy $ try $ spaces >> htmlTag (~== TagClose "a") return $ return $ B.link src "" (B.str orig) autoLink :: MarkdownParser (F Inlines) autoLink = try $ do getState >>= guard . stateAllowLinks char '<' (orig, src) <- uri <|> emailAddress -- in rare cases, something may remain after the uri parser -- is finished, because the uri parser tries to avoid parsing -- final punctuation. for example: in `<http://hi---there>`, -- the URI parser will stop before the dashes. extra <- fromEntities <$> manyTill nonspaceChar (char '>') return $ return $ B.link (src ++ escapeURI extra) "" (B.str $ orig ++ extra) image :: MarkdownParser (F Inlines) image = try $ do char '!' (lab,raw) <- reference defaultExt <- getOption readerDefaultImageExtension let constructor src = case takeExtension src of "" -> B.image (addExtension src defaultExt) _ -> B.image src regLink constructor lab <|> referenceLink constructor (lab,raw) note :: MarkdownParser (F Inlines) note = try $ do guardEnabled Ext_footnotes ref <- noteMarker return $ do notes <- asksF stateNotes' case lookup ref notes of Nothing -> return $ B.str $ "[^" ++ ref ++ "]" Just contents -> do st <- askF -- process the note in a context that doesn't resolve -- notes, to avoid infinite looping with notes inside -- notes: let contents' = runF contents st{ stateNotes' = [] } return $ B.note contents' inlineNote :: MarkdownParser (F Inlines) inlineNote = try $ do guardEnabled Ext_inline_notes char '^' contents <- inlinesInBalancedBrackets return $ B.note . B.para <$> contents rawLaTeXInline' :: MarkdownParser (F Inlines) rawLaTeXInline' = try $ do guardEnabled Ext_raw_tex lookAhead $ char '\\' >> notFollowedBy' (string "start") -- context env RawInline _ s <- rawLaTeXInline return $ return $ B.rawInline "tex" s -- "tex" because it might be context or latex rawConTeXtEnvironment :: Parser [Char] st String rawConTeXtEnvironment = try $ do string "\\start" completion <- inBrackets (letter <|> digit <|> spaceChar) <|> (many1 letter) contents <- manyTill (rawConTeXtEnvironment <|> (count 1 anyChar)) (try $ string "\\stop" >> string completion) return $ "\\start" ++ completion ++ concat contents ++ "\\stop" ++ completion inBrackets :: (Parser [Char] st Char) -> Parser [Char] st String inBrackets parser = do char '[' contents <- many parser char ']' return $ "[" ++ contents ++ "]" spanHtml :: MarkdownParser (F Inlines) spanHtml = try $ do guardEnabled Ext_native_spans (TagOpen _ attrs, _) <- htmlTag (~== TagOpen "span" []) contents <- mconcat <$> manyTill inline (htmlTag (~== TagClose "span")) let ident = fromMaybe "" $ lookup "id" attrs let classes = maybe [] words $ lookup "class" attrs let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"] case lookup "style" keyvals of Just s | null ident && null classes && map toLower (filter (`notElem` " \t;") s) == "font-variant:small-caps" -> return $ B.smallcaps <$> contents _ -> return $ B.spanWith (ident, classes, keyvals) <$> contents divHtml :: MarkdownParser (F Blocks) divHtml = try $ do guardEnabled Ext_native_divs (TagOpen _ attrs, rawtag) <- htmlTag (~== TagOpen "div" []) -- we set stateInHtmlBlock so that closing tags that can be either block or -- inline will not be parsed as inline tags oldInHtmlBlock <- stateInHtmlBlock <$> getState updateState $ \st -> st{ stateInHtmlBlock = Just "div" } bls <- option "" (blankline >> option "" blanklines) contents <- mconcat <$> many (notFollowedBy' (htmlTag (~== TagClose "div")) >> block) closed <- option False (True <$ htmlTag (~== TagClose "div")) if closed then do updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock } let ident = fromMaybe "" $ lookup "id" attrs let classes = maybe [] words $ lookup "class" attrs let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"] return $ B.divWith (ident, classes, keyvals) <$> contents else -- avoid backtracing return $ return (B.rawBlock "html" (rawtag <> bls)) <> contents rawHtmlInline :: MarkdownParser (F Inlines) rawHtmlInline = do guardEnabled Ext_raw_html inHtmlBlock <- stateInHtmlBlock <$> getState let isCloseBlockTag t = case inHtmlBlock of Just t' -> t ~== TagClose t' Nothing -> False mdInHtml <- option False $ ( guardEnabled Ext_markdown_in_html_blocks <|> guardEnabled Ext_markdown_attribute ) >> return True (_,result) <- htmlTag $ if mdInHtml then (\x -> isInlineTag x && not (isCloseBlockTag x)) else not . isTextTag return $ return $ B.rawInline "html" result -- Citations cite :: MarkdownParser (F Inlines) cite = do guardEnabled Ext_citations citations <- textualCite <|> do (cs, raw) <- withRaw normalCite return $ (flip B.cite (B.text raw)) <$> cs return citations textualCite :: MarkdownParser (F Inlines) textualCite = try $ do (_, key) <- citeKey let first = Citation{ citationId = key , citationPrefix = [] , citationSuffix = [] , citationMode = AuthorInText , citationNoteNum = 0 , citationHash = 0 } mbrest <- option Nothing $ try $ spnl >> Just <$> withRaw normalCite case mbrest of Just (rest, raw) -> return $ (flip B.cite (B.text $ '@':key ++ " " ++ raw) . (first:)) <$> rest Nothing -> (do (cs, raw) <- withRaw $ bareloc first let (spaces',raw') = span isSpace raw spc | null spaces' = mempty | otherwise = B.space lab <- parseFromString (mconcat <$> many inline) $ dropBrackets raw' fallback <- referenceLink B.link (lab,raw') return $ do fallback' <- fallback cs' <- cs return $ case B.toList fallback' of Link{}:_ -> B.cite [first] (B.str $ '@':key) <> spc <> fallback' _ -> B.cite cs' (B.text $ '@':key ++ " " ++ raw)) <|> return (do st <- askF return $ case M.lookup key (stateExamples st) of Just n -> B.str (show n) _ -> B.cite [first] $ B.str $ '@':key) bareloc :: Citation -> MarkdownParser (F [Citation]) bareloc c = try $ do spnl char '[' notFollowedBy $ char '^' suff <- suffix rest <- option (return []) $ try $ char ';' >> citeList spnl char ']' notFollowedBy $ oneOf "[(" return $ do suff' <- suff rest' <- rest return $ c{ citationSuffix = B.toList suff' } : rest' normalCite :: MarkdownParser (F [Citation]) normalCite = try $ do char '[' spnl citations <- citeList spnl char ']' return citations suffix :: MarkdownParser (F Inlines) suffix = try $ do hasSpace <- option False (notFollowedBy nonspaceChar >> return True) spnl rest <- trimInlinesF . mconcat <$> many (notFollowedBy (oneOf ";]") >> inline) return $ if hasSpace then (B.space <>) <$> rest else rest prefix :: MarkdownParser (F Inlines) prefix = trimInlinesF . mconcat <$> manyTill inline (char ']' <|> liftM (const ']') (lookAhead citeKey)) citeList :: MarkdownParser (F [Citation]) citeList = fmap sequence $ sepBy1 citation (try $ char ';' >> spnl) citation :: MarkdownParser (F Citation) citation = try $ do pref <- prefix (suppress_author, key) <- citeKey suff <- suffix return $ do x <- pref y <- suff return $ Citation{ citationId = key , citationPrefix = B.toList x , citationSuffix = B.toList y , citationMode = if suppress_author then SuppressAuthor else NormalCitation , citationNoteNum = 0 , citationHash = 0 } smart :: MarkdownParser (F Inlines) smart = do getOption readerSmart >>= guard doubleQuoted <|> singleQuoted <|> choice (map (return <$>) [apostrophe, dash, ellipses]) singleQuoted :: MarkdownParser (F Inlines) singleQuoted = try $ do singleQuoteStart withQuoteContext InSingleQuote $ fmap B.singleQuoted . trimInlinesF . mconcat <$> many1Till inline singleQuoteEnd -- doubleQuoted will handle regular double-quoted sections, as well -- as dialogues with an open double-quote without a close double-quote -- in the same paragraph. doubleQuoted :: MarkdownParser (F Inlines) doubleQuoted = try $ do doubleQuoteStart contents <- mconcat <$> many (try $ notFollowedBy doubleQuoteEnd >> inline) (withQuoteContext InDoubleQuote $ doubleQuoteEnd >> return (fmap B.doubleQuoted . trimInlinesF $ contents)) <|> (return $ return (B.str "\8220") <> contents)
poxu/pandoc
src/Text/Pandoc/Readers/Markdown.hs
gpl-2.0
73,665
0
28
20,522
21,691
10,721
10,970
1,625
7
{-# LANGUAGE StandaloneKindSignatures #-} {-# LANGUAGE PolyKinds, RankNTypes #-} module SAKS_016 where import Data.Kind (Type) type T :: forall k. k -> forall j. j -> Type data T (x :: hk) (y :: hj)
sdiehl/ghc
testsuite/tests/saks/should_compile/saks016.hs
bsd-3-clause
202
0
8
38
57
37
20
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ms-MY"> <title>Revisit | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/revisit/src/main/javahelp/org/zaproxy/zap/extension/revisit/resources/help_ms_MY/helpset_ms_MY.hs
apache-2.0
968
78
66
158
411
208
203
-1
-1
-- | This is designed to be used as -- -- > qualified import Yesod.Core.Unsafe as Unsafe -- -- This serves as a reminder that the functions are unsafe to use in many situations. module Yesod.Core.Unsafe (runFakeHandler, fakeHandlerGetLogger) where import Yesod.Core.Internal.Run (runFakeHandler) import Yesod.Core.Types import Yesod.Core.Class.Yesod import Data.Monoid (mempty, mappend) import Control.Monad.IO.Class (MonadIO) -- | designed to be used as -- -- > unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger fakeHandlerGetLogger :: (Yesod site, MonadIO m) => (site -> Logger) -> site -> HandlerT site IO a -> m a fakeHandlerGetLogger getLogger app f = runFakeHandler mempty getLogger app f >>= either (error . ("runFakeHandler issue: " `mappend`) . show) return
ygale/yesod
yesod-core/Yesod/Core/Unsafe.hs
mit
824
0
10
161
169
101
68
12
1
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} module T12133 where import GHC.Classes (IP(..)) import Data.Kind (Constraint, Type) -- | From "Data.Constraint": data Dict :: Constraint -> Type where Dict :: a => Dict a newtype a :- b = Sub (a => Dict b) infixl 1 \\ -- required comment (\\) :: a => (b => r) -> (a :- b) -> r r \\ Sub Dict = r -- | GHC 7.10.2 type checks this function but GHC 8.0.1 does not unless -- you modify this example in one of the following ways: -- -- * uncomments the type signature for 'Sub' -- -- * flatten the nested pairs of constraints into a triple of constraints -- -- * replace 'IP sym ty' with 'c9', where 'c9' is a new constraint variable. -- -- The error message is listed below. foo :: forall c1 c2 c3 sym ty . (c1, c2) :- c3 -> (c1, (IP sym ty, c2)) :- (IP sym ty, c3) foo sp = ( Sub -- :: ((c1, (IP sym ty, c2)) => Dict (IP sym ty, c3)) -- -> (c1, ((IP sym ty), c2)) :- (IP sym ty, c3) ) ( (Dict \\ sp) :: Dict (IP sym ty, c3) ) {- Compiler error message: GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help [1 of 1] Compiling T ( t.hs, interpreted ) t.hs:44:13: error: • Could not deduce: IP sym ty arising from a use of ‘Dict’ from the context: (c1, (IP sym ty, c2)) bound by a type expected by the context: (c1, (IP sym ty, c2)) => Dict (IP sym ty, c3) at t.hs:(40,10)-(44,49) or from: c3 bound by a type expected by the context: c3 => Dict (IP sym ty, c3) at t.hs:44:13-22 • In the first argument of ‘(\\)’, namely ‘Dict’ In the first argument of ‘Sub’, namely ‘((Dict \\ sp) :: Dict (IP sym ty, c3))’ In the expression: (Sub) ((Dict \\ sp) :: Dict (IP sym ty, c3)) • Relevant bindings include foo :: (c1, c2) :- c3 -> (c1, (IP sym ty, c2)) :- (IP sym ty, c3) (bound at t.hs:40:1) Failed, modules loaded: none. -}
sdiehl/ghc
testsuite/tests/typecheck/should_compile/T12133.hs
bsd-3-clause
2,244
0
10
621
256
155
101
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} module Idris.TypeSearch ( searchByType, searchPred, defaultScoreFunction ) where import Control.Applicative (Applicative (..), (<$>), (<*>), (<|>)) import Control.Arrow (first, second, (&&&), (***)) import Control.Monad (when, guard) import Data.List (find, partition, (\\)) import Data.Map (Map) import qualified Data.Map as M import Data.Maybe (catMaybes, fromMaybe, isJust, maybeToList, mapMaybe) import Data.Monoid (Monoid (mempty, mappend)) import Data.Ord (comparing) import qualified Data.PriorityQueue.FingerTree as Q import Data.Set (Set) import qualified Data.Set as S import qualified Data.Text as T (pack, isPrefixOf) import Data.Traversable (traverse) import Idris.AbsSyntax (addUsingConstraints, addImpl, getIState, putIState, implicit, logLvl) import Idris.AbsSyntaxTree (class_instances, ClassInfo, defaultSyntax, eqTy, Idris, IState (idris_classes, idris_docstrings, tt_ctxt, idris_outputmode), implicitAllowed, OutputMode(..), PTerm, toplevel) import Idris.Core.Evaluate (Context (definitions), Def (Function, TyDecl, CaseOp), normaliseC) import Idris.Core.TT hiding (score) import Idris.Core.Unify (match_unify) import Idris.Delaborate (delabTy) import Idris.Docstrings (noDocs, overview) import Idris.Elab.Type (elabType) import Idris.Output (iputStrLn, iRenderOutput, iPrintResult, iRenderError, iRenderResult, prettyDocumentedIst) import Idris.IBC import Prelude hiding (pred) import Util.Pretty (text, char, vsep, (<>), Doc, annotate) searchByType :: [String] -> PTerm -> Idris () searchByType pkgs pterm = do i <- getIState -- save original when (not (null pkgs)) $ iputStrLn $ "Searching packages: " ++ showSep ", " pkgs mapM_ loadPkgIndex pkgs pterm' <- addUsingConstraints syn emptyFC pterm pterm'' <- implicit toplevel syn name pterm' let pterm''' = addImpl [] i pterm'' ty <- elabType toplevel syn (fst noDocs) (snd noDocs) emptyFC [] name NoFC pterm' let names = searchUsing searchPred i ty let names' = take numLimit names let docs = [ let docInfo = (n, delabTy i n, fmap (overview . fst) (lookupCtxtExact n (idris_docstrings i))) in displayScore theScore <> char ' ' <> prettyDocumentedIst i docInfo | (n, theScore) <- names'] if (not (null docs)) then case idris_outputmode i of RawOutput _ -> do mapM_ iRenderOutput docs iPrintResult "" IdeMode _ _ -> iRenderResult (vsep docs) else iRenderError $ text "No results found" putIState i -- don't actually make any changes where numLimit = 50 syn = defaultSyntax { implicitAllowed = True } -- syntax name = sMN 0 "searchType" -- name -- | Conduct a type-directed search using a given match predicate searchUsing :: (IState -> Type -> [(Name, Type)] -> [(Name, a)]) -> IState -> Type -> [(Name, a)] searchUsing pred istate ty = pred istate nty . concat . M.elems $ M.mapWithKey (\key -> M.toAscList . M.mapMaybe (f key)) (definitions ctxt) where nty = normaliseC ctxt [] ty ctxt = tt_ctxt istate f k x = do guard $ not (special k) type2 <- typeFromDef x return $ normaliseC ctxt [] type2 special :: Name -> Bool special (NS n _) = special n special (SN _) = True special (UN n) = T.pack "default#" `T.isPrefixOf` n || n `elem` map T.pack ["believe_me", "really_believe_me"] special _ = False -- | Our default search predicate. searchPred :: IState -> Type -> [(Name, Type)] -> [(Name, Score)] searchPred istate ty1 = matcher where maxScore = 100 matcher = matchTypesBulk istate maxScore ty1 typeFromDef :: (Def, b, c, d) -> Maybe Type typeFromDef (def, _, _, _) = get def where get :: Def -> Maybe Type get (Function ty _) = Just ty get (TyDecl _ ty) = Just ty -- get (Operator ty _ _) = Just ty get (CaseOp _ ty _ _ _ _) = Just ty get _ = Nothing -- Replace all occurences of `Lazy' s t` with `t` in a type unLazy :: Type -> Type unLazy typ = case typ of App _ (App _ (P _ lazy _) _) ty | lazy == sUN "Lazy'" -> unLazy ty Bind name binder ty -> Bind name (fmap unLazy binder) (unLazy ty) App s t1 t2 -> App s (unLazy t1) (unLazy t2) Proj ty i -> Proj (unLazy ty) i _ -> typ -- | reverse the edges for a directed acyclic graph reverseDag :: Ord k => [((k, a), Set k)] -> [((k, a), Set k)] reverseDag xs = map f xs where f ((k, v), _) = ((k, v), S.fromList . map (fst . fst) $ filter (S.member k . snd) xs) -- run vToP first! -- | Compute a directed acyclic graph corresponding to the -- arguments of a function. -- returns [(the name and type of the bound variable -- the names in the type of the bound variable)] computeDagP :: Ord n => (TT n -> Bool) -- ^ filter to remove some arguments -> TT n -> ([((n, TT n), Set n)], [(n, TT n)], TT n) computeDagP removePred t = (reverse (map f arguments), reverse theRemovedArgs , retTy) where f (n, ty) = ((n, ty), M.keysSet (usedVars ty)) (arguments, theRemovedArgs, retTy) = go [] [] t -- NOTE : args are in reverse order go args removedArgs (Bind n (Pi _ ty _) sc) = let arg = (n, ty) in if removePred ty then go args (arg : removedArgs) sc else go (arg : args) removedArgs sc go args removedArgs sc = (args, removedArgs, sc) -- | Collect the names and types of all the free variables -- The Boolean indicates those variables which are determined due to injectivity -- I have not given nearly enough thought to know whether this is correct usedVars :: Ord n => TT n -> Map n (TT n, Bool) usedVars = f True where f b (P Bound n t) = M.singleton n (t, b) `M.union` f b t f b (Bind n binder t2) = (M.delete n (f b t2) `M.union`) $ case binder of Let t v -> f b t `M.union` f b v Guess t v -> f b t `M.union` f b v bind -> f b (binderTy bind) f b (App _ t1 t2) = f b t1 `M.union` f (b && isInjective t1) t2 f b (Proj t _) = f b t f _ (V _) = error "unexpected! run vToP first" f _ _ = M.empty -- | Remove a node from a directed acyclic graph deleteFromDag :: Ord n => n -> [((n, TT n), (a, Set n))] -> [((n, TT n), (a, Set n))] deleteFromDag name [] = [] deleteFromDag name (((name2, ty), (ix, set)) : xs) = (if name == name2 then id else (((name2, ty) , (ix, S.delete name set)) :) ) (deleteFromDag name xs) deleteFromArgList :: Ord n => n -> [(n, TT n)] -> [(n, TT n)] deleteFromArgList n = filter ((/= n) . fst) -- | Asymmetric modifications to keep track of data AsymMods = Mods { argApp :: !Int , typeClassApp :: !Int , typeClassIntro :: !Int } deriving (Eq, Show) -- | Homogenous tuples data Sided a = Sided { left :: !a , right :: !a } deriving (Eq, Show) sided :: (a -> a -> b) -> Sided a -> b sided f (Sided l r) = f l r -- | Could be a functor instance, but let's avoid name overloading both :: (a -> b) -> Sided a -> Sided b both f (Sided l r) = Sided (f l) (f r) -- | Keeps a record of the modifications made to match one type -- signature with another data Score = Score { transposition :: !Int -- ^ transposition of arguments , equalityFlips :: !Int -- ^ application of symmetry of equality , asymMods :: !(Sided AsymMods) -- ^ "directional" modifications } deriving (Eq, Show) displayScore :: Score -> Doc OutputAnnotation displayScore score = case both noMods (asymMods score) of Sided True True -> annotated EQ "=" -- types are isomorphic Sided True False -> annotated LT "<" -- found type is more general than searched type Sided False True -> annotated GT ">" -- searched type is more general than found type Sided False False -> text "_" where annotated ordr = annotate (AnnSearchResult ordr) . text noMods (Mods app tcApp tcIntro) = app + tcApp + tcIntro == 0 -- | This allows the search to stop expanding on a certain state if its -- score is already too high. Returns 'True' if the algorithm should keep -- exploring from this state, and 'False' otherwise. scoreCriterion :: Score -> Bool scoreCriterion (Score _ _ amods) = not ( sided (&&) (both ((> 0) . argApp) amods) || sided (+) (both argApp amods) > 4 || sided (||) (both (\(Mods _ tcApp tcIntro) -> tcApp > 3 || tcIntro > 3) amods) ) -- | Convert a 'Score' to an 'Int' to provide an order for search results. -- Lower scores are better. defaultScoreFunction :: Score -> Int defaultScoreFunction (Score trans eqFlip amods) = trans + eqFlip + linearPenalty + upAndDowncastPenalty where -- prefer finding a more general type to a less general type linearPenalty = (\(Sided l r) -> 3 * l + r) (both (\(Mods app tcApp tcIntro) -> 3 * app + 4 * tcApp + 2 * tcIntro) amods) -- it's very bad to have *both* upcasting and downcasting upAndDowncastPenalty = 100 * sided (*) (both (\(Mods app tcApp tcIntro) -> 2 * app + tcApp + tcIntro) amods) instance Ord Score where compare = comparing defaultScoreFunction instance Monoid a => Monoid (Sided a) where mempty = Sided mempty mempty (Sided l1 r1) `mappend` (Sided l2 r2) = Sided (l1 `mappend` l2) (r1 `mappend` r2) instance Monoid AsymMods where mempty = Mods 0 0 0 (Mods a b c) `mappend` (Mods a' b' c') = Mods (a + a') (b + b') (c + c') instance Monoid Score where mempty = Score 0 0 mempty (Score t e mods) `mappend` (Score t' e' mods') = Score (t + t') (e + e') (mods `mappend` mods') -- | A directed acyclic graph representing the arguments to a function -- The 'Int' represents the position of the argument (1st argument, 2nd, etc.) type ArgsDAG = [((Name, Type), (Int, Set Name))] -- | A list of typeclass constraints type Classes = [(Name, Type)] -- | The state corresponding to an attempted match of two types. data State = State { holes :: ![(Name, Type)] -- ^ names which have yet to be resolved , argsAndClasses :: !(Sided (ArgsDAG, Classes)) -- ^ arguments and typeclass constraints for each type which have yet to be resolved , score :: !Score -- ^ the score so far , usedNames :: ![Name] -- ^ all names that have been used } deriving Show modifyTypes :: (Type -> Type) -> (ArgsDAG, Classes) -> (ArgsDAG, Classes) modifyTypes f = modifyDag *** modifyList where modifyDag = map (first (second f)) modifyList = map (second f) findNameInArgsDAG :: Name -> ArgsDAG -> Maybe (Type, Maybe Int) findNameInArgsDAG name = fmap ((snd . fst) &&& (Just . fst . snd)) . find ((name ==) . fst . fst) findName :: Name -> (ArgsDAG, Classes) -> Maybe (Type, Maybe Int) findName n (args, classes) = findNameInArgsDAG n args <|> ((,) <$> lookup n classes <*> Nothing) deleteName :: Name -> (ArgsDAG, Classes) -> (ArgsDAG, Classes) deleteName n (args, classes) = (deleteFromDag n args, filter ((/= n) . fst) classes) tcToMaybe :: TC a -> Maybe a tcToMaybe (OK x) = Just x tcToMaybe (Error _) = Nothing inArgTys :: (Type -> Type) -> ArgsDAG -> ArgsDAG inArgTys = map . first . second typeclassUnify :: Ctxt ClassInfo -> Context -> Type -> Type -> Maybe [(Name, Type)] typeclassUnify classInfo ctxt ty tyTry = do res <- tcToMaybe $ match_unify ctxt [] (ty, Nothing) (retTy, Nothing) [] theHoles [] guard $ null (theHoles \\ map fst res) let argTys' = map (second $ foldr (.) id [ subst n t | (n, t) <- res ]) tcArgs return argTys' where tyTry' = vToP tyTry theHoles = map fst nonTcArgs retTy = getRetTy tyTry' (tcArgs, nonTcArgs) = partition (isTypeClassArg classInfo . snd) $ getArgTys tyTry' isTypeClassArg :: Ctxt ClassInfo -> Type -> Bool isTypeClassArg classInfo ty = not (null (getClassName clss >>= flip lookupCtxt classInfo)) where (clss, args) = unApply ty getClassName (P (TCon _ _) className _) = [className] getClassName _ = [] -- | Compute the power set subsets :: [a] -> [[a]] subsets [] = [[]] subsets (x : xs) = let ss = subsets xs in map (x :) ss ++ ss -- not recursive (i.e., doesn't flip iterated identities) at the moment -- recalls the number of flips that have been made flipEqualities :: Type -> [(Int, Type)] flipEqualities t = case t of eq1@(App _ (App _ (App _ (App _ eq@(P _ eqty _) tyL) tyR) valL) valR) | eqty == eqTy -> [(0, eq1), (1, app (app (app (app eq tyR) tyL) valR) valL)] Bind n binder sc -> (\bind' (j, sc') -> (fst (binderTy bind') + j, Bind n (fmap snd bind') sc')) <$> traverse flipEqualities binder <*> flipEqualities sc App _ f x -> (\(i, f') (j, x') -> (i + j, app f' x')) <$> flipEqualities f <*> flipEqualities x t' -> [(0, t')] where app = App Complete --DONT run vToP first! -- | Try to match two types together in a unification-like procedure. -- Returns a list of types and their minimum scores, sorted in order -- of increasing score. matchTypesBulk :: forall info. IState -> Int -> Type -> [(info, Type)] -> [(info, Score)] matchTypesBulk istate maxScore type1 types = getAllResults startQueueOfQueues where getStartQueues :: (info, Type) -> Maybe (Score, (info, Q.PQueue Score State)) getStartQueues nty@(info, type2) = case mapMaybe startStates ty2s of [] -> Nothing xs -> Just (minimum (map fst xs), (info, Q.fromList xs)) where ty2s = (\(i, dag) (j, retTy) -> (i + j, dag, retTy)) <$> flipEqualitiesDag dag2 <*> flipEqualities retTy2 flipEqualitiesDag dag = case dag of [] -> [(0, [])] ((n, ty), (pos, deps)) : xs -> (\(i, ty') (j, xs') -> (i + j , ((n, ty'), (pos, deps)) : xs')) <$> flipEqualities ty <*> flipEqualitiesDag xs startStates (numEqFlips, sndDag, sndRetTy) = do state <- unifyQueue (State startingHoles (Sided (dag1, typeClassArgs1) (sndDag, typeClassArgs2)) (mempty { equalityFlips = numEqFlips }) usedns) [(retTy1, sndRetTy)] return (score state, state) (dag2, typeClassArgs2, retTy2) = makeDag (uniqueBinders (map fst argNames1) type2) argNames2 = map fst dag2 usedns = map fst startingHoles startingHoles = argNames1 ++ argNames2 startingTypes = [(retTy1, retTy2)] startQueueOfQueues :: Q.PQueue Score (info, Q.PQueue Score State) startQueueOfQueues = Q.fromList $ mapMaybe getStartQueues types getAllResults :: Q.PQueue Score (info, Q.PQueue Score State) -> [(info, Score)] getAllResults q = case Q.minViewWithKey q of Nothing -> [] Just ((nextScore, (info, stateQ)), q') -> if defaultScoreFunction nextScore <= maxScore then case nextStepsQueue stateQ of Nothing -> getAllResults q' Just (Left stateQ') -> case Q.minViewWithKey stateQ' of Nothing -> getAllResults q' Just ((newQscore,_), _) -> getAllResults (Q.add newQscore (info, stateQ') q') Just (Right theScore) -> (info, theScore) : getAllResults q' else [] ctxt = tt_ctxt istate classInfo = idris_classes istate (dag1, typeClassArgs1, retTy1) = makeDag type1 argNames1 = map fst dag1 makeDag :: Type -> (ArgsDAG, Classes, Type) makeDag = first3 (zipWith (\i (ty, deps) -> (ty, (i, deps))) [0..] . reverseDag) . computeDagP (isTypeClassArg classInfo) . vToP . unLazy first3 f (a,b,c) = (f a, b, c) -- update our state with the unification resolutions resolveUnis :: [(Name, Type)] -> State -> Maybe (State, [(Type, Type)]) resolveUnis [] state = Just (state, []) resolveUnis ((name, term@(P Bound name2 _)) : xs) state | isJust findArgs = do ((ty1, ix1), (ty2, ix2)) <- findArgs (state'', queue) <- resolveUnis xs state' let transScore = fromMaybe 0 (abs <$> ((-) <$> ix1 <*> ix2)) return (inScore (\s -> s { transposition = transposition s + transScore }) state'', (ty1, ty2) : queue) where unresolved = argsAndClasses state inScore f stat = stat { score = f (score stat) } findArgs = ((,) <$> findName name (left unresolved) <*> findName name2 (right unresolved)) <|> ((,) <$> findName name2 (left unresolved) <*> findName name (right unresolved)) matchnames = [name, name2] deleteArgs = deleteName name . deleteName name2 state' = state { holes = filter (not . (`elem` matchnames) . fst) (holes state) , argsAndClasses = both (modifyTypes (subst name term) . deleteArgs) unresolved} resolveUnis ((name, term) : xs) state@(State hs unresolved _ _) = case both (findName name) unresolved of Sided Nothing Nothing -> Nothing Sided (Just _) (Just _) -> error "Idris internal error: TypeSearch.resolveUnis" oneOfEach -> first (addScore (both scoreFor oneOfEach)) <$> nextStep where scoreFor (Just _) = mempty { argApp = 1 } scoreFor Nothing = mempty { argApp = otherApplied } -- find variables which are determined uniquely by the type -- due to injectivity matchedVarMap = usedVars term bothT f (x, y) = (f x, f y) (injUsedVars, notInjUsedVars) = bothT M.keys . M.partition id . M.filterWithKey (\k _-> k `elem` map fst hs) $ M.map snd matchedVarMap varsInTy = injUsedVars ++ notInjUsedVars toDelete = name : varsInTy deleteMany = foldr (.) id (map deleteName toDelete) otherApplied = length notInjUsedVars addScore additions theState = theState { score = let s = score theState in s { asymMods = asymMods s `mappend` additions } } state' = state { holes = filter (not . (`elem` toDelete) . fst) hs , argsAndClasses = both (modifyTypes (subst name term) . deleteMany) (argsAndClasses state) } nextStep = resolveUnis xs state' -- | resolve a queue of unification constraints unifyQueue :: State -> [(Type, Type)] -> Maybe State unifyQueue state [] = return state unifyQueue state ((ty1, ty2) : queue) = do --trace ("go: \n" ++ show state) True `seq` return () res <- tcToMaybe $ match_unify ctxt [ (n, Pi Nothing ty (TType (UVar 0))) | (n, ty) <- holes state] (ty1, Nothing) (ty2, Nothing) [] (map fst $ holes state) [] (state', queueAdditions) <- resolveUnis res state guard $ scoreCriterion (score state') unifyQueue state' (queue ++ queueAdditions) possClassInstances :: [Name] -> Type -> [Type] possClassInstances usedns ty = do className <- getClassName clss classDef <- lookupCtxt className classInfo n <- class_instances classDef def <- lookupCtxt (fst n) (definitions ctxt) nty <- normaliseC ctxt [] <$> (case typeFromDef def of Just x -> [x]; Nothing -> []) let ty' = vToP (uniqueBinders usedns nty) return ty' where (clss, _) = unApply ty getClassName (P (TCon _ _) className _) = [className] getClassName _ = [] -- 'Just' if the computation hasn't totally failed yet, 'Nothing' if it has -- 'Left' if we haven't found a terminal state, 'Right' if we have nextStepsQueue :: Q.PQueue Score State -> Maybe (Either (Q.PQueue Score State) Score) nextStepsQueue queue = do ((nextScore, next), rest) <- Q.minViewWithKey queue Just $ if isFinal next then Right nextScore else let additions = if scoreCriterion nextScore then Q.fromList [ (score state, state) | state <- nextSteps next ] else Q.empty in Left (Q.union rest additions) where isFinal (State [] (Sided ([], []) ([], [])) _ _) = True isFinal _ = False -- | Find all possible matches starting from a given state. -- We go in stages rather than concatenating all three results in hopes of narrowing -- the search tree. Once we advance in a phase, there should be no going back. nextSteps :: State -> [State] -- Stage 3 - match typeclasses nextSteps (State [] unresolved@(Sided ([], c1) ([], c2)) scoreAcc usedns) = if null results3 then results4 else results3 where -- try to match a typeclass argument from the left with a typeclass argument from the right results3 = catMaybes [ unifyQueue (State [] (Sided ([], deleteFromArgList n1 c1) ([], map (second subst2for1) (deleteFromArgList n2 c2))) scoreAcc usedns) [(ty1, ty2)] | (n1, ty1) <- c1, (n2, ty2) <- c2, let subst2for1 = psubst n2 (P Bound n1 ty1)] -- try to hunt match a typeclass constraint by replacing it with an instance results4 = [ State [] (both (\(cs, _, _) -> ([], cs)) sds) (scoreAcc `mappend` Score 0 0 (both (\(_, amods, _) -> amods) sds)) (usedns ++ sided (++) (both (\(_, _, hs) -> hs) sds)) | sds <- allMods ] where allMods = parallel defMod mods mods :: Sided [( Classes, AsymMods, [Name] )] mods = both (instanceMods . snd) unresolved defMod :: Sided (Classes, AsymMods, [Name]) defMod = both (\(_, cs) -> (cs, mempty , [])) unresolved parallel :: Sided a -> Sided [a] -> [Sided a] parallel (Sided l r) (Sided ls rs) = map (flip Sided r) ls ++ map (Sided l) rs instanceMods :: Classes -> [( Classes , AsymMods, [Name] )] instanceMods classes = [ ( newClassArgs, mempty { typeClassApp = 1 }, newHoles ) | (_, ty) <- classes , inst <- possClassInstances usedns ty , newClassArgs <- maybeToList $ typeclassUnify classInfo ctxt ty inst , let newHoles = map fst newClassArgs ] -- Stage 1 - match arguments nextSteps (State hs (Sided (dagL, c1) (dagR, c2)) scoreAcc usedns) = results where results = concatMap takeSomeClasses results1 -- we only try to match arguments whose names don't appear in the types -- of any other arguments canBeFirst :: ArgsDAG -> [(Name, Type)] canBeFirst = map fst . filter (S.null . snd . snd) -- try to match an argument from the left with an argument from the right results1 = catMaybes [ unifyQueue (State (filter (not . (`elem` [n1,n2]) . fst) hs) (Sided (deleteFromDag n1 dagL, c1) (inArgTys subst2for1 $ deleteFromDag n2 dagR, map (second subst2for1) c2)) scoreAcc usedns) [(ty1, ty2)] | (n1, ty1) <- canBeFirst dagL, (n2, ty2) <- canBeFirst dagR , let subst2for1 = psubst n2 (P Bound n1 ty1)] -- Stage 2 - simply introduce a subset of the typeclasses -- we've finished, so take some classes takeSomeClasses (State [] unresolved@(Sided ([], _) ([], _)) scoreAcc usedns) = map statesFromMods . prod $ both (classMods . snd) unresolved where swap (Sided l r) = Sided r l statesFromMods :: Sided (Classes, AsymMods) -> State statesFromMods sides = let classes = both (\(c, _) -> ([], c)) sides mods = swap (both snd sides) in State [] classes (scoreAcc `mappend` (mempty { asymMods = mods })) usedns classMods :: Classes -> [(Classes, AsymMods)] classMods cs = let lcs = length cs in [ (cs', mempty { typeClassIntro = lcs - length cs' }) | cs' <- subsets cs ] prod :: Sided [a] -> [Sided a] prod (Sided ls rs) = [Sided l r | l <- ls, r <- rs] -- still have arguments to match, so just be the identity takeSomeClasses s = [s]
mrmonday/Idris-dev
src/Idris/TypeSearch.hs
bsd-3-clause
22,922
0
20
5,429
8,529
4,582
3,947
409
22
module ShouldSucceed where type H = (Int,Bool)
siddhanathan/ghc
testsuite/tests/typecheck/should_compile/tc028.hs
bsd-3-clause
48
0
5
8
16
11
5
2
0
-- !!! Newtypes -- This one made ghc 5.01 (after newtype squashing) fall over -- by generating Core code that contained a pattern match on -- the InPE data constructor (which doesn't exist) module Main where data Expr e = One e | Many [e] newtype PExpr a = InPE (Expr (PExpr a), Int) one :: Int -> PExpr e -> PExpr e one l x = InPE (One (plus1 x), l) plus1 :: PExpr a -> PExpr a plus1 x@(InPE (_, loc)) = InPE (Many [plus1 x], loc) get :: PExpr e -> Int get (InPE (_,l)) = l main = print (get (plus1 (InPE (Many [], 0))))
urbanslug/ghc
testsuite/tests/typecheck/should_run/tcrun014.hs
bsd-3-clause
531
0
14
118
222
120
102
10
1
module Verba.Formatting where label :: String -> String label str = "\o33[2;49;37m" ++ str ++ "\o33[0m" success :: String -> String success str = "\o33[0;32m" ++ str ++ "\o33[0m" warning :: String -> String warning str = "\o33[0;33m" ++ str ++ "\o33[0m"
Jefffrey/Verba
src/Verba/Formatting.hs
mit
257
0
6
45
81
43
38
7
1
import qualified Data.ByteString.Lazy.Char8 as BS main :: IO () main = do contents <- BS.getContents -- all IO in one go BS.putStr contents
feliposz/spoj-solutions
haskell/bstest.hs
mit
146
0
8
29
44
24
20
5
1
{-# LANGUAGE OverloadedStrings #-} module BenchNames where import qualified Data.ByteString.Lazy as BS import Data.Aeson import Control.Applicative import Control.Monad import qualified Data.Map as M import qualified Data.Text as T import Data.List import Paths import JsonUtils import ReportTypes import qualified BenchmarkSettings as S benchNamesMain :: [S.BenchName] -> IO () benchNamesMain benchNames = do settings <- S.readSettings "gipeda.yaml" let groups = sortOn (liftA2 (,) groupName groupMembers) $ map (\(name, (s, bns)) -> BenchGroup { groupName = name , groupMembers = bns , groupUnitFull = S.unitFull s }) $ M.toList $ M.map (fmap sort) $ M.fromListWith (\(s, bns) (_, bns') -> (s, bns ++ bns')) [ (S.group s, (s, [bn])) | bn <- benchNames , let s = S.benchSettings settings bn ] let doc = emptyGlobalReport { benchGroups = Just groups } BS.putStr (encode doc)
nomeata/gipeda
src/BenchNames.hs
mit
1,077
0
20
333
327
185
142
31
1
module Ethereum.RLP(module X) where import Ethereum.RLP.Item as X import Ethereum.RLP.Convert as X
bkirwi/ethereum-haskell
src/Ethereum/RLP.hs
mit
100
0
4
13
28
20
8
3
0
module Latro.ILGen where import Control.Monad.Writer import Data.Char (toLower) import Latro.Ast import Latro.Compiler import Latro.Semant ilGenClause :: Show a => CaseClause a UniqId -> ILWriter ILCase a ilGenClause (CaseClause p patE bodyE) = do bodyE' <- ilGen bodyE return $ ILCase p (ilGenPat patE) bodyE' ilGenPat :: PatExp a UniqId -> ILPat a ilGenPat patE = case patE of PatExpNumLiteral p s -> ILPatInt p $ read s PatExpBoolLiteral p b -> ILPatBool p b PatExpStringLiteral p s -> ILPatStr p s PatExpCharLiteral p s -> ILPatChar p s PatExpTuple p patEs -> ILPatTuple p $ map ilGenPat patEs PatExpAdt p (Id _ uid) patEs -> ILPatAdt p uid $ map ilGenPat patEs PatExpList p patEs -> ILPatList p $ map ilGenPat patEs PatExpListCons p patHd patTl -> ILPatCons p (ilGenPat patHd) (ilGenPat patTl) PatExpId p id -> ILPatId p id PatExpWildcard p -> ILPatWildcard p ilGenFieldInit :: Show a => FieldInit a UniqId -> ILWriter ILFieldInit a ilGenFieldInit (FieldInit p e) = do e' <- ilGen e return $ ILFieldInit p e' ilGenPrim :: UniqId -> Prim ilGenPrim (UserId id) = case map toLower id of "println" -> PrimPrintln "readln" -> PrimReadln "chareq" -> PrimCharEq "chartoint" -> PrimCharToInt "intadd" -> PrimIntAdd "intsub" -> PrimIntSub "intdiv" -> PrimIntDiv "intmul" -> PrimIntMul "intmod" -> PrimIntMod "inteq" -> PrimIntEq "intlt" -> PrimIntLt "intleq" -> PrimIntLeq "intgt" -> PrimIntGt "intgeq" -> PrimIntGeq _ -> PrimUnknown id ilGenTy :: Show a => SynTy a UniqId -> SynTy a UniqId ilGenTy (SynTyPrim p id@(UserId tyId)) = case tyId of "int" -> SynTyInt p "bool" -> SynTyBool p "char" -> SynTyChar p "unit" -> SynTyUnit p _ -> SynTyUnknown p id ilGenTy (SynTyArrow p paramTys retTy) = SynTyArrow p (map ilGenTy paramTys) $ ilGenTy retTy ilGenTy (SynTyStruct p fields) = SynTyStruct p $ map (\(fid, fty) -> (fid, ilGenTy fty)) fields ilGenTy (SynTyAdt p id alts) = SynTyAdt p id $ map (\(AdtAlternative ap aid ai tys) -> AdtAlternative ap aid ai (map ilGenTy tys)) alts ilGenTy (SynTyList p sty) = SynTyList p $ ilGenTy sty ilGenTy (SynTyTuple p tys) = SynTyTuple p $ map ilGenTy tys ilGenTy sty = sty ilGen :: Show a => Exp a UniqId -> ILWriter IL a ilGen (ExpTypeDec p tyDec) = do tell [tyDec'] return $ ILBegin p [] where tyDec' = mapTyDecTys tyDec ilGenTy ilGen (ExpCons p l r) = do hd <- ilGen l tl <- ilGen r return $ ILCons p hd tl ilGen (ExpInParens _ e) = ilGen e ilGen (ExpMemberAccess p e id) = do e' <- ilGen e return $ ILApp p (ILRef p id) [e'] ilGen (ExpApp p rator rands) = do rator' <- ilGen rator rands' <- mapM ilGen rands return $ ILApp p rator' rands' ilGen (ExpPrim p ratorId) = return $ ILPrim p $ ilGenPrim ratorId ilGen (ExpAssign p patE e) = do e' <- ilGen e return $ ILAssign p (ilGenPat patE) e' ilGen (ExpTopLevelAssign p patE e) = do e' <- ilGen e return $ ILAssign p (ilGenPat patE) e' ilGen (ExpProtoDec p protoId tyId straints tyAnns) = return $ ILProtoDec p protoId tyId straints tyAnns ilGen (ExpProtoImp p synTy protoId straints bodyEs) = do bodyEs' <- mapM ilGen bodyEs return $ ILProtoImp p synTy protoId straints bodyEs' ilGen (ExpWithAnn (TyAnn p id tyParamIds ty straints) e) = do e' <- ilGen e let ty' = ilGenTy ty return $ ILWithAnn p (TyAnn p id tyParamIds ty' straints) e' ilGen (ExpFunDef (FunDefFun p fid@(UniqId _ fName) argPatEs bodyE)) = do bodyE' <- ilGen bodyE return $ if fName == "main" then ILMain p argIds bodyE' else ILFunDef p fid argIds bodyE' where argIds = map assumeIdPat argPatEs ilGen (ExpStruct p (Id _ uid) fieldInits) = do fieldInits' <- mapM ilGenFieldInit fieldInits return $ ILStruct p uid fieldInits' ilGen (ExpIfElse p e thenE elseE) = do e' <- ilGen e thenE' <- ilGen thenE elseE' <- ilGen elseE return $ ILSwitch p e' [ ILCase p (ILPatBool p True) thenE' , ILCase p (ILPatBool p False) elseE' ] ilGen (ExpMakeAdt p id i argEs) = do argEs' <- mapM ilGen argEs return $ ILMakeAdt p id i argEs' ilGen (ExpGetAdtField p e i) = do e' <- ilGen e return $ ILGetAdtField p e' i ilGen (ExpTuple p argEs) = do argEs' <- mapM ilGen argEs return $ ILTuple p argEs' ilGen (ExpSwitch p e clauses) = do e' <- ilGen e clauses' <- mapM ilGenClause clauses return $ ILSwitch p e' clauses' ilGen (ExpList p argEs) = do argEs' <- mapM ilGen argEs return $ ILList p argEs' ilGen (ExpFun p argPatEs bodyE) = do bodyE' <- ilGen bodyE return $ ILFun p argIds bodyE' where argIds = map assumeIdPat argPatEs ilGen (ExpNum p s) = return $ ILInt p $ read s ilGen (ExpBool p b) = return $ ILBool p b ilGen (ExpString p s) = return $ ILStr p s ilGen (ExpChar p s) = return $ ILChar p s ilGen (ExpRef p id) = return $ ILRef p id ilGen (ExpUnit p) = return $ ILUnit p ilGen (ExpBegin p es) = do es' <- mapM ilGen es return $ ILBegin p es' ilGen (ExpFail p msg) = return $ ILFail p msg ilGen e = error ("Could not generate IL for expression: " ++ show e) ilGenEs :: Show a => [Exp a UniqId] -> Writer [TypeDec a UniqId] [IL a] ilGenEs es = mapM ilGen es type ILWriter t a = Writer [TypeDec a UniqId] (t a) type ILGenM a = CompilerPass CompilerEnv a runILGen :: UniqAst CompUnit -> ILGenM (Untyped ILCompUnit) runILGen (CompUnit p es) = let (il, tyDecs) = runWriter $ ilGenEs es in return $ ILCompUnit p tyDecs il
Zoetermeer/latro
src/Latro/ILGen.hs
mit
5,618
0
12
1,411
2,340
1,103
1,237
159
15
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.RTCTrackEvent (newRTCTrackEvent, getReceiver, getTrack, getStreams, getTransceiver, RTCTrackEvent(..), gTypeRTCTrackEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCTrackEvent Mozilla RTCTrackEvent documentation> newRTCTrackEvent :: (MonadDOM m, ToJSString type') => type' -> RTCTrackEventInit -> m RTCTrackEvent newRTCTrackEvent type' eventInitDict = liftDOM (RTCTrackEvent <$> new (jsg "RTCTrackEvent") [toJSVal type', toJSVal eventInitDict]) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCTrackEvent.receiver Mozilla RTCTrackEvent.receiver documentation> getReceiver :: (MonadDOM m) => RTCTrackEvent -> m RTCRtpReceiver getReceiver self = liftDOM ((self ^. js "receiver") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCTrackEvent.track Mozilla RTCTrackEvent.track documentation> getTrack :: (MonadDOM m) => RTCTrackEvent -> m MediaStreamTrack getTrack self = liftDOM ((self ^. js "track") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCTrackEvent.streams Mozilla RTCTrackEvent.streams documentation> getStreams :: (MonadDOM m) => RTCTrackEvent -> m [MediaStream] getStreams self = liftDOM ((self ^. js "streams") >>= fromJSArrayUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCTrackEvent.transceiver Mozilla RTCTrackEvent.transceiver documentation> getTransceiver :: (MonadDOM m) => RTCTrackEvent -> m RTCRtpTransceiver getTransceiver self = liftDOM ((self ^. js "transceiver") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/RTCTrackEvent.hs
mit
2,573
0
10
347
585
350
235
39
1
module Numeric.Limp.Solvers.Cbc ( Error(..) , solve ) where import qualified Numeric.Limp.Canon as C import Numeric.Limp.Program import Numeric.Limp.Rep import qualified Numeric.Limp.Solvers.Cbc.Solve as S import Numeric.Limp.Solvers.Cbc.Error solve :: (Ord z, Ord r) => Program z r IntDouble -> Either Error (Assignment z r IntDouble) solve p = let pc = C.program p in S.solve pc
amosr/limp-cbc
src/Numeric/Limp/Solvers/Cbc.hs
mit
401
0
10
73
135
80
55
12
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} import Data.Aeson import Control.Applicative import qualified Data.ByteString.Lazy as B import GHC.Generics data Person = Person { name :: String , email :: String , created_at :: String , is_deleted :: Maybe Int } deriving Generic instance FromJSON Person main :: IO () main = do input <- B.readFile "data/input.json" let mm = decode input :: Maybe Person case mm of Nothing -> print "error parsing JSON" Just m -> (putStrLn . printPerson) m printPerson m = (show.name) m ++" has a email: "++ (show.email) m
slon1024/haskell_read_data
Json.hs
mit
688
0
12
206
185
98
87
20
2
{-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} module Elm.Decoder ( toElmDecoderRef , toElmDecoderRefWith , toElmDecoderSource , toElmDecoderSourceWith ) where import Control.Monad.Reader import Data.Semigroup import Data.Text hiding (map) import Elm.Common import Elm.Type import Formatting class HasDecoder a where render :: a -> Reader Options Text class HasDecoderRef a where renderRef :: a -> Reader Options Text instance HasDecoder ElmDatatype where render d@(ElmDatatype name mc@(MultipleConstructors _)) = do fnName <- renderRef d let fnBody = " in \"" <> toLower name <> "\" := string `andThen` stringTo" <> name catch = " _ -> fail <| \"unexpected " <> name <> " -- \" ++ s" localFn = " let stringTo" <> name <> " s =" caseHead = " case s of" bot = sformat (cr % stext % cr % stext) catch fnBody top = sformat (stext % " : Decoder " % stext % cr % stext % " =" % cr % stext % cr % stext % stext) fnName name fnName localFn caseHead <$> render mc (flip mappend bot) <$> top render d@(ElmDatatype name constructor) = do fnName <- renderRef d sformat (stext % " : Decoder " % stext % cr % stext % " =" % cr % stext) fnName name fnName <$> render constructor render (ElmPrimitive primitive) = renderRef primitive instance HasDecoderRef ElmDatatype where renderRef (ElmDatatype name _) = pure $ sformat ("decode" % stext) name renderRef (ElmPrimitive primitive) = renderRef primitive instance HasDecoder ElmConstructor where render (NamedConstructor name value) = sformat (" decode " % stext % cr % stext) name <$> render value render (RecordConstructor name value) = sformat (" decode " % stext % cr % stext) name <$> render value render (MultipleConstructors xs) = let renderLine t (NamedConstructor name value) = sformat (stext % cr % " " % "\"" % stext % "\" -> succeed " % stext % stext) t (toLower name) name <$> render value renderLine t (RecordConstructor name value) = sformat (stext % cr % stext % " record " % stext % stext) t (toLower name) name <$> render value renderLine t (MultipleConstructors ys) = foldM renderLine t ys in foldM renderLine mempty xs instance HasDecoder ElmValue where render (ElmRef name) = pure (sformat ("decode" % stext) name) render (ElmPrimitiveRef primitive) = renderRef primitive render (Values x y) = sformat (stext % cr % stext) <$> render x <*> render y render (ElmField name value) = do fieldModifier <- asks fieldLabelModifier sformat (" |> required \"" % stext % "\" " % stext) (fieldModifier name) <$> render value render ElmEmpty = pure mempty instance HasDecoderRef ElmPrimitive where renderRef (EList (ElmPrimitive EChar)) = pure "string" renderRef (EList datatype) = sformat ("(list " % stext % ")") <$> renderRef datatype renderRef (EDict key value) = sformat ("(map Dict.fromList " % stext % ")") <$> renderRef (EList (ElmPrimitive (ETuple2 (ElmPrimitive key) value))) renderRef (EMaybe datatype) = sformat ("(maybe " % stext % ")") <$> renderRef datatype renderRef (ETuple2 x y) = sformat ("(tuple2 (,) " % stext % " " % stext % ")") <$> renderRef x <*> renderRef y renderRef EUnit = pure "(succeed ())" renderRef EDate = pure "(customDecoder string Date.fromString)" renderRef EInt = pure "int" renderRef EBool = pure "bool" renderRef EChar = pure "char" renderRef EFloat = pure "float" renderRef EString = pure "string" renderRef EUuid = pure "(customDecoder string (Result.FromMaybe \"Error decoding Uuid\" << Uuid.fromString))" toElmDecoderRefWith :: ElmType a => Options -> a -> Text toElmDecoderRefWith options x = runReader (renderRef (toElmType x)) options toElmDecoderRef :: ElmType a => a -> Text toElmDecoderRef = toElmDecoderRefWith defaultOptions toElmDecoderSourceWith :: ElmType a => Options -> a -> Text toElmDecoderSourceWith options x = runReader (render (toElmType x)) options toElmDecoderSource :: ElmType a => a -> Text toElmDecoderSource = toElmDecoderSourceWith defaultOptions
InfernalKnight/elm-export
src/Elm/Decoder.hs
epl-1.0
4,727
0
23
1,380
1,368
675
693
108
1
{-# LANGUAGE TemplateHaskell #-} module Control.Semester.Typ where import Control.Types import Autolib.Reader import Autolib.ToDoc import Data.Typeable -- | das sollte exactly das sein, was auch in DB-tabelle steht data Semester = Semester { enr :: ENr , unr :: UNr -- jedes Semester ist einer Schule zugeordnet , name :: Name , von :: Time , bis :: Time -- | nicht in DB, aber bei Zugriff ausgerechnet , status :: TimeStatus } deriving ( Eq, Ord, Typeable ) $(derives [makeReader, makeToDoc] [''Semester]) -- local variables: -- mode: haskell -- end
florianpilz/autotool
src/Control/Semester/Typ.hs
gpl-2.0
616
4
9
155
121
75
46
15
0
module Tema_7_Spec (main, spec) where import Tema_7 import Test.Hspec import Prelude hiding (id, foldr, foldl, (.)) import Test.QuickCheck import Data.Char main :: IO () main = hspec spec spec :: Spec spec = do describe "dosVeces" $ do it "e1" $ dosVeces (*3) 2 `shouldBe` 18 it "e2" $ dosVeces reverse [2,5,7] `shouldBe` [2,5,7] describe "map" $ do it "e1" $ map (*2) [3,4,7] `shouldBe` [6,8,14] it "e2" $ map (1/) [1,2,4] `shouldBe` [1.0,0.5,0.25] it "e3" $ map even [1..5] `shouldBe` [False,True,False,True,False] describe "prop_sum_map" $ it "e1" $ property prop_sum_map describe "filter" $ do it "e1" $ filter even [1,3,5,4,2,6,1] `shouldBe` [4,2,6] it "e2" $ filter (>3) [1,3,5,4,2,6,1] `shouldBe` [5,4,6] describe "sumaCuadradosPares" $ it "e1" $ sumaCuadradosPares [1..5] `shouldBe` 20 describe "longitud" $ it "e1" $ longitud [4,2,5] `shouldBe` 3 describe "inversa" $ it "e1" $ inversa [4,2,5] `shouldBe` [5,2,4] describe "conc" $ it "e1" $ conc [4,2,5] [7,9] `shouldBe` [4,2,5,7,9] describe "suma" $ it "e1" $ suma [2,3,7] `shouldBe` 12 describe "composicionLista" $ do it "e1" $ composicionLista [(*2),(^2)] 3 `shouldBe` 18 it "e2" $ composicionLista [(^2),(*2)] 3 `shouldBe` 36 it "e3" $ composicionLista [(/9),(^2),(*2)] 3 `shouldBe` 4.0 describe "bin2int" $ it "e1" $ bin2int [1,0,1,1] `shouldBe` 13 describe "bin2intR" $ it "e1" $ bin2intR [1,0,1,1] `shouldBe` 13 describe "bin2intC" $ it "e1" $ bin2intC [1,0,1,1] `shouldBe` 13 describe "int2bin" $ it "e1" $ int2bin 13 `shouldBe` [1,0,1,1] describe "prop_int_bin" $ it "e1" $ property prop_int_bin describe "creaOcteto" $ do it "e1" $ creaOcteto [1,0,1,1,0,0,1,1,1,0,0,0] `shouldBe` [1,0,1,1,0,0,1,1] it "e2" $ creaOcteto [1,0,1,1] `shouldBe` [1,0,1,1,0,0,0,0] describe "creaOcteto'" $ do it "e1" $ creaOcteto' [1,0,1,1,0,0,1,1,1,0,0,0] `shouldBe` [1,0,1,1,0,0,1,1] it "e2" $ creaOcteto' [1,0,1,1] `shouldBe` [1,0,1,1,0,0,0,0] describe "prop_transmite" $ it "e1" $ property prop_transmite
jaalonso/I1M-Cod-Temas
test/Tema_7_Spec.hs
gpl-2.0
2,355
0
14
680
1,230
684
546
80
1
{-# LANGUAGE DeriveDataTypeable #-} module Syntax.Syntax where import Data.Generics (Data, Typeable) data Graph = Chain Graph Graph | Fork Graph Graph | Loop Graph | Terminal String | Symbol String | Empty deriving (Eq, Data, Typeable) type Language = [(String, Graph)] -- The first entry is assumed to be the start symbol
Erdwolf/autotool-bonn
src/Syntax/Syntax.hs
gpl-2.0
402
0
6
131
87
53
34
11
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} -- | This module provides an interface for writing session typed programs module Control.SessionTypes.MonadSession ( -- * Primitives MonadSession (..), -- * Combinators empty, empty0, selN, selN1, selN2, selN3, selN4, Select(sel), (<&), (<&>), offer, recurseFix, recurse0, weaken0, var0, eps0 ) where import Control.SessionTypes.Indexed as I import Control.SessionTypes.Types import Data.Function (fix) import Data.Typeable (Proxy(..)) -- | The `MonadSession` type class exposes a set of functions that composed together form a session typed program -- -- A type that is an instance of `MonadSession` must therefore also be an instance of `IxMonad`. -- -- The functions themselves are generally defined as wrappers over corresponding `STTerm` constructors. class IxMonad m => MonadSession m where send :: a -> m ('Cap ctx (a :!> r)) ('Cap ctx r) () recv :: m ('Cap ctx (a :?> r)) ('Cap ctx r) a sel1 :: m ('Cap ctx (Sel (s ': xs))) ('Cap ctx s) () sel2 :: m ('Cap ctx (Sel (s ': t ': xs))) ('Cap ctx (Sel (t ': xs))) () offZ :: m ('Cap ctx s) r a -> m ('Cap ctx (Off '[s])) r a offS :: m ('Cap ctx s) r a -> m ('Cap ctx (Off (t ': xs))) r a -> m ('Cap ctx (Off (s ': t ': xs))) r a recurse :: m ('Cap (s ': ctx) s) r a -> m ('Cap ctx (R s)) r a weaken :: m ('Cap ctx s) r a -> m ('Cap (t ': ctx) (Wk s)) r a var :: m ('Cap (s ': ctx) s) r a -> m ('Cap (s ': ctx) V) r a eps :: a -> m ('Cap ctx Eps) ('Cap ctx Eps) a -- | A session typed program that is polymorphic in its context can often not be used by interpreters. -- -- We can apply `empty` to the session typed program before passing it to an interpreter to instantiate that the context is empty. empty :: MonadSession m => m ('Cap '[] s) r a -> m ('Cap '[] s) r a empty = id -- | Monadic composable definition of `empty` -- -- Prefix a session typed program with (empty >>) to instantiate the context to be empty. empty0 :: MonadSession m => m ('Cap '[] r) ('Cap '[] r) () empty0 = I.return () -- | Allows indexing of selections. -- -- The given `Ref` type can be used as an indexed to select a branch. This circumvents the need to sequence a bunch of `sel1` and `sel2` to select a branch. -- -- @ -- prog :: MonadSession m => m ('Cap ctx (Sel '[a,b,c,d])) ('Cap ctx Eps) () -- -- MonadSession m => m ('Cap ctx b) ('Cap ctx Eps) () -- prog2 = prog >> selN (RefS RefZ) -- @ -- selN :: MonadSession m => Ref s xs -> m ('Cap ctx (Sel xs)) ('Cap ctx s) () selN RefZ = sel1 selN (RefS r) = sel2 I.>> selN r -- | Select the first branch of a selection. selN1 :: MonadSession m => m ('Cap ctx (Sel (s ': xs))) ('Cap ctx s) () selN1 = sel1 -- | Select the second branch of a selection. selN2 :: MonadSession m => m ('Cap ctx (Sel (s ': t ': xs))) ('Cap ctx t) () selN2 = sel2 I.>> sel1 -- | Select the third branch of a selection. selN3 :: MonadSession m => m ('Cap ctx (Sel (s ': t ': k ': xs))) ('Cap ctx k) () selN3 = sel2 I.>> sel2 I.>> sel1 -- | Select the fourth branch of a selection. selN4 :: MonadSession m => m ('Cap ctx (Sel (s ': t ': k ': r ': xs))) ('Cap ctx r) () selN4 = sel2 I.>> sel2 I.>> sel2 I.>> sel1 -- | Type class for selecting a branch through injection. -- -- Selects the first branch that matches the given session type. -- -- @ -- prog :: MonadSession m => m ('Cap ctx (Sel '[Eps, String :!> Eps, Int :!> Eps])) ('Cap ctx Eps) () -- prog = sel >> send "c" >>= eps -- @ -- -- It should be obvious that you cannot select a branch using `sel` if that branch has the same session type as a previous branch. class Select xs s where sel :: MonadSession m => m ('Cap ctx (Sel xs)) ('Cap ctx s) () instance (tl ~ TypeEqList xs s, Select' xs s tl) => Select xs s where sel = sel' (Proxy :: Proxy tl) class Select' xs s (tl :: k) | xs tl -> s where sel' :: MonadSession m => Proxy tl -> m ('Cap ctx (Sel xs)) ('Cap ctx s) () instance Select' (s ': xs) s ('True ': tl) where sel' _ = sel1 instance Select' (r ': xs) t tl => Select' (s ': r ': xs) t ('False ': tl) where sel' _ = sel2 I.>> sel' (Proxy :: Proxy tl) -- | Takes two session typed programs and constructs an offering consisting of two branches offer :: MonadSession m => m ('Cap ctx s) r a -> m ('Cap ctx t) r a -> m ('Cap ctx (Off '[s, t])) r a offer s r = offS s (offZ r) -- | Infix synonym for `offS` infixr 1 <& (<&) :: MonadSession m => m ('Cap ctx s) r a -> m ('Cap ctx (Off (t ': xs))) r a -> m ('Cap ctx (Off (s ': t ': xs))) r a (<&) = offS -- | Infix synonym for `offer` -- -- Using both `<&` and `<&>` we can now construct an offering as follows: -- -- @ -- branch1 -- \<& branch2 -- \<& branch3 -- \<&\> branch4 -- @ -- -- This will be parsed as -- -- @ -- (branch1 -- \<& (branch2 -- \<& (branch3 -- \<&\> branch4))) -- @ infix 2 <&> (<&>) :: MonadSession m => m ('Cap ctx s) r a -> m ('Cap ctx t) r a -> m ('Cap ctx (Off '[s, t])) r a s <&> r = offS s (offZ r) -- | A fixpoint combinator for recursion -- -- The argument function must take a recursion variable as an argument that can be used to denote the point of recursion. -- -- For example: -- -- @ -- prog = recurseFix \\f -> do -- send 5 -- f -- @ -- -- This program will send the number 5 an infinite amount of times. recurseFix :: MonadSession m => (m ('Cap (s ': ctx) V) r a -> m ('Cap (s ': ctx) s) r a) -> m ('Cap ctx (R s)) r a recurseFix s = recurse $ fix (\f -> s $ var f) -- | Monadic composable definition of `recurse` recurse0 :: MonadSession m => m ('Cap ctx (R s)) ('Cap (s ': ctx) s) () recurse0 = recurse $ I.return () -- | Monadic composable definition of `weaken` weaken0 :: MonadSession m => m ('Cap (t ': ctx) (Wk s)) ('Cap ctx s) () weaken0 = weaken $ I.return () -- | Monadic composable definition of `var` var0 :: MonadSession m => m ('Cap (s ': ctx) V) ('Cap (s ': ctx) s) () var0 = var $ I.return () -- | Monadic composable definition of `eps` eps0 :: MonadSession m => m ('Cap ctx Eps) ('Cap ctx Eps) () eps0 = eps ()
Ferdinand-vW/sessiontypes
src/Control/SessionTypes/MonadSession.hs
gpl-3.0
6,438
0
16
1,518
2,365
1,252
1,113
90
1
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings #-} module LiName.Config ( getConf, loadConfigFile ) where import LiName.Options import LiName.Types import Control.Applicative ((<$>)) import Control.Exception import Control.Lens import Data.Default (def) import Data.Text (pack, Text) import qualified Data.Yaml as Y import Data.Yaml (FromJSON, (.:), (.:?), (.!=)) import Data.Yaml.Config (loadYamlSettings, ignoreEnv) import Prelude hiding (lookup) import System.Directory (getHomeDirectory) import System.FilePath (combine) import System.Posix.Files (getFdStatus, isNamedPipe) import System.Posix.IO (stdInput) data LiNameYamlConfig = LiNameYamlConfig { _yEditorCommand :: LiNameCommand , _yTrashCommand :: LiNameCommand , _yOptoins :: [String]} instance FromJSON LiNameCommand where parseJSON (Y.Object v) = LiNameCommand <$> v .: "command" <*> v .: "options" <*> v .: "place_holder" instance FromJSON LiNameYamlConfig where parseJSON (Y.Object v) = LiNameYamlConfig <$> v .:? "editor" .!= editorCommandDefault <*> v .:? "trash" .!= trashCommandDefault <*> v .:? "options" .!= [] parseJSON _ = fail "Expected Object for Config value" fromYConfig :: LiNameYamlConfig -> IO LiNameConfig fromYConfig (LiNameYamlConfig e t o) = do let cmded = def { _editorCommand = e, _trashCommand = t } parsed <- parseOptions True cmded o case parsed of (Right (conf, _)) -> return conf (Left e) -> putStrLn e >> return cmded getConf :: Bool -> [String] -> IO (Either String (LiNameConfig, [String])) getConf allowEmpty as = do fileConf <- loadConfigFile fd <- getFdStatus stdInput pas <- if isNamedPipe fd then lines <$> getContents else return [] parseOptions allowEmpty fileConf $ as ++ pas loadConfigFile :: IO LiNameConfig loadConfigFile = do home <- getHomeDirectory let y = combine home ".liname.yaml" loadYamlSettings [y] [] ignoreEnv >>= fromYConfig `catch` catchAndReturnDefault def withDefault :: a -> IO a -> IO a withDefault d a = a `catch` catchAndReturnDefault d catchAndReturnDefault :: a -> SomeException -> IO a catchAndReturnDefault d _ = return d
anekos/liname-hs
src/LiName/Config.hs
gpl-3.0
2,275
0
14
500
674
363
311
59
2
module Functions.InfixOpParser (infixParser ) where import Functions.InfixOperations import Functions.FunctionMaps --Infix Operation Block Check infFMKeyList :: [String] infFMKeyList = getFMKeys infixFunctionMap infFMValList :: [ (Double->Double->Double) ] infFMValList = getFMVals infixFunctionMap --Parentheses are used for making in-process rpn blocks infixParser :: String -> String -> Int -> String infixParser a b fmIndex | infCCheck a b = show $ (infFMValList !! fmIndex) aNum bNum | infVCheck a b = unwords $ a:b:(infFMKeyList !! fmIndex):[] where aNum = read a bNum = read b -- | error "Incorrect Input\n"
LeoMingo/RPNMathParser
Functions/InfixOpParser.hs
gpl-3.0
776
0
9
247
180
95
85
14
1
module Tests.TemplateHaskell where import QFeldspar.MyPrelude import Language.Haskell.TH.Syntax add :: Word32 -> Word32 -> Word32 add = (+) dbl :: Q (TExp (Word32 -> Word32)) dbl = [||\ x -> add x x ||] compose :: Q (TExp ((tb -> tc) -> (ta -> tb) -> ta -> tc)) compose = [|| \ x2 -> \ x1 -> \ x0 -> x2 (x1 x0) ||] four :: Q (TExp Word32) four = [|| ($$compose $$dbl $$dbl) 1 ||]
shayan-najd/QFeldspar
Tests/TemplateHaskell.hs
gpl-3.0
399
6
14
96
201
112
89
-1
-1
{-| Module : Alpaca.MaMa.Machine Description : Alpaca Machine Maintainer : [email protected] Stability : stable Portability : portable Copyright : (c) Sascha Rechenberger, 2014 License : GPL-3 This file is part of Alpaca. Alpaca is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Alpaca 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 Alpaca. If not, see <http://www.gnu.org/licenses/>. -} module Alpaca.MaMa.Machine ( -- * Simple Types Pointer, Program, -- * Monad MaMa, stmt, haul, runProgram, -- * error runtimeError ) where import Prelude hiding (lookup) import Alpaca.MaMa.Types (Basic (..), HeapObject (..)) import Control.Monad.Trans.Either (EitherT, runEitherT, left) import Control.Monad.State.Lazy (State, runState, get, put, execState, evalState) import Control.Applicative ((<$>), (<*>), (*>), (<*), pure) import Data.Map (Map, insert, lookup, member, adjust, empty, (!), size, fromList) import Data.List (intercalate) import Debug.Trace (trace) import Text.Parsec (parse, try, many1, char, string, lower, (<|>), lookAhead, spaces, unexpected, oneOf, many1, anyChar, digit, sepBy1) import Text.Parsec.String (Parser) type Pointer = Int type Heap = (Pointer, Map Pointer HeapObject) type Stack = Map Pointer Basic type Program = Map Pointer (MaMa ()) data MaMaState = MaMaState {pc :: Pointer, sp :: Pointer, fp :: Pointer, gp :: Pointer, st :: Stack, hp :: Heap} deriving(Show) data Result = Success Basic | Failure String deriving (Show) type MaMa = EitherT Result (State MaMaState) data Address = PC | SP | FP | GP | ST Address | HP Address Selector | Const Pointer | New Tag [Address] | Unary (Pointer -> Pointer) Address | Binary (Pointer -> Pointer -> Pointer) Address Address deriving () instance Show Address where show PC = "$pc" show SP = "$sp" show FP = "$fp" show GP = "$gp" show (ST a) = "$st[" ++ show a ++ "]" show (HP a s) = "$hp[" ++ show a ++ "]." ++ show s show (Const x) = show x show (New t as) = "new " ++ show t ++ " (" ++ intercalate ", " (map show as) ++ ")" show (Unary f a) = case f 1 of -1 -> "(-" ++ show a ++ ")" _ -> "f(" ++ show a ++ ")" show (Binary f a b) = case f (-2) (-2) of -4 -> "(" ++ show a ++ " + " ++ show b ++ ")" 0 -> "(" ++ show a ++ " - " ++ show b ++ ")" 4 -> "(" ++ show a ++ " * " ++ show b ++ ")" 1 -> "(" ++ show a ++ " / " ++ show b ++ ")" _ -> "f(" ++ show a ++ ", " ++ show b ++ ")" data Tag = BASIC | CLOSURE | FUNVAL | VECTOR deriving (Eq, Show) data Selector = V | A Int | CP | GLOB | AP | N deriving (Eq) instance Show Selector where show V = "b" show (A i) = "v[" ++ show i ++ "]" show CP = "cp" show GLOB = "gp" show AP = "ap" show N = "n" data Assign = Address := Address deriving (Show) runtimeError :: String -> MaMa a runtimeError s = left . Failure $ "RUNTIME ERROR " ++ s ++ "." getLabel :: Address -> MaMa Pointer getLabel (Const ptr) = return ptr getLabel (Unary f a) = f <$> getLabel a getLabel (Binary f a b) = f <$> getLabel a <*> getLabel b getLabel a = do ptr <- rightHandSide a case ptr of Label p -> return p _ -> runtimeError $ show ptr ++ " is no label" getPointer :: Address -> MaMa Pointer getPointer (Const ptr) = return ptr getPointer (Unary f a) = f <$> getPointer a getPointer (Binary f a b) = f <$> getPointer a <*> getPointer b getPointer a = do ptr <- rightHandSide a case ptr of Pointer p -> return p _ -> runtimeError $ show ptr ++ " is no pointer" rightHandSide :: Address -> MaMa Basic rightHandSide a = case a of PC -> get >>= return . Label . pc SP -> get >>= return . Pointer . sp FP -> get >>= return . Pointer . fp GP -> get >>= return . Pointer . gp New tag args -> case tag of BASIC -> if length args /= 1 then runtimeError $ "BASIC object needing 1 argument misdistributed with " ++ show (length args) else return args >>= rightHandSide . head >>= new . Basic CLOSURE -> if length args /= 2 then runtimeError $ "CLOSURE object needing 2 arguments misdistributed with " ++ show (length args) else do cp <- getLabel (args !! 0) gp <- getPointer (args !! 1) new $ Closure cp gp FUNVAL -> if length args /= 3 then runtimeError $ "FUNVAL object needing 3 arguments misdistributed with " ++ show (length args) else do cp <- getLabel (args !! 0) ap <- getPointer (args !! 1) gp <- getPointer (args !! 2) new $ FunVal cp ap gp VECTOR -> if length args /= 1 then runtimeError $ "VECTOR object needing 1 argument misdistributed with " ++ show (length args) else pure args >>= getPointer . head >>= new . flip Vector empty ST p -> getPointer p >>= \p -> get >>= \mama -> case lookup p (st mama) of Nothing -> runtimeError $ "cannot read ST[" ++ show p ++ "]; null pointer" Just elem -> return elem HP p sel -> getPointer p >>= \p -> get >>= \mama -> case lookup p (snd . hp $ mama) of Nothing -> runtimeError $ "cannot read HP[" ++ show p ++ "]; null pointer" Just elem -> case elem of Basic b -> case sel of V -> return b _ -> runtimeError $ "cannot get " ++ show sel ++ " of a basic" Closure lbl glob -> case sel of CP -> return . Label $ lbl GLOB -> return . Pointer $ glob _ -> runtimeError $ "cannot get " ++ show sel ++ " of a closure" FunVal lbl fap glob -> case sel of CP -> return . Label $ lbl AP -> return . Pointer $ fap GLOB -> return . Pointer $ glob _ -> runtimeError $ "cannot get " ++ show sel ++ " of a function" Vector n vals -> case sel of A ix -> if ix >= size vals then runtimeError $ show ix ++ " violates vector bounds" else return . Pointer $ vals ! ix N -> return . Pointer $ n _ -> runtimeError $ "cannot get " ++ show sel ++ " of a vector" Cons _ n vals -> case sel of A ix -> if ix >= size vals then runtimeError $ show ix ++ " violates constructor bounds" else return . Pointer $ vals ! ix _ -> runtimeError $ "cannot get " ++ show sel ++ " of a constructor" err -> runtimeError $ show err ++ " is no legal right hand side" {-} Unary f a -> (Pointer . f) <$> getPointer a Binary f a b -> Pointer <$> (f <$> getPointer a <*> getPointer b) Const x -> return . Pointer $ x -} assign :: Assign -> MaMa () assign (lhs := rhs) = do case lhs of PC -> getLabel rhs >>= \lbl -> get >>= \mama -> put mama {pc = lbl} SP -> getPointer rhs >>= \ptr -> get >>= \mama -> put mama {pc = ptr} FP -> getPointer rhs >>= \ptr -> get >>= \mama -> put mama {pc = ptr} GP -> getPointer rhs >>= \ptr -> get >>= \mama -> put mama {pc = ptr} ST a -> rightHandSide rhs >>= \datum -> getPointer a >>= \ptr -> get >>= \mama -> if ptr `member` st mama then put mama {st = adjust (const datum) ptr (st mama)} else put mama {st = insert ptr datum (st mama)} HP p sel -> getPointer p >>= \ptr -> get >>= \mama -> case lookup ptr (snd . hp $ mama) of Nothing -> runtimeError $ "cannot update HP[" ++ show p ++ "]; null pointer" Just elem -> case elem of Basic _ -> rightHandSide rhs >>= \datum -> case sel of V -> put mama {hp = (fst . hp $ mama, adjust (const . Basic $ datum) ptr . snd . hp $ mama)} e -> runtimeError $ "cannot write " ++ show e ++ " field of a BASIC object" Closure c v -> case sel of CP -> getLabel rhs >>= \lbl -> get >>= \mama -> put mama {hp = (fst . hp $ mama, adjust (const (Closure lbl v)) ptr . snd . hp $ mama)} GLOB -> rightHandSide rhs >>= \datum -> case datum of Pointer x -> put mama {hp = (fst . hp $ mama, adjust (const (Closure c x)) ptr . snd . hp $ mama)} err -> runtimeError $ "cannot write " ++ show err ++ " into the gp field of a closure" e -> runtimeError $ "cannot write " ++ show e ++ " field of a CLOSURE object" FunVal c a v -> case sel of CP -> rightHandSide rhs >>= \datum -> case datum of Label x -> put mama {hp = (fst . hp $ mama, adjust (const (FunVal x a v)) ptr . snd . hp $ mama)} err -> runtimeError $ "cannot write " ++ show err ++ " into the cp field of a funval" AP -> rightHandSide rhs >>= \datum -> case datum of Pointer x -> put mama {hp = (fst . hp $ mama, adjust (const (FunVal c x v)) ptr . snd . hp $ mama)} err -> runtimeError $ "cannot write " ++ show err ++ " into the ap field of a funval" GLOB -> rightHandSide rhs >>= \datum -> case datum of Pointer x -> put mama {hp = (fst . hp $ mama, adjust (const (FunVal c a x)) ptr . snd . hp $ mama)} err -> runtimeError $ "cannot write " ++ show err ++ " into the gp field of a funval" e -> runtimeError $ "cannot write " ++ show e ++ " field of a FUNVAL object" Vector n ptrs -> case sel of A ix -> rightHandSide rhs >>= \datum -> case datum of Pointer x -> put mama {hp = (fst . hp $ mama, adjust (const (Vector n (adjust (const x) ix ptrs))) ptr . snd . hp $ mama)} err -> runtimeError $ "cannot write " ++ show err ++ " into the a field of a vector" N -> rightHandSide rhs >>= \datum -> case datum of Pointer x -> put mama {hp = (fst . hp $ mama, adjust (const (Vector x ptrs)) ptr . snd . hp $ mama)} err -> runtimeError $ "cannot write " ++ show err ++ " into the a field of a vector" e -> runtimeError $ "cannot write " ++ show e ++ " field of a VECTOR object" _ -> runtimeError $ "no memory cell is chosen" new :: HeapObject -> MaMa Basic new obj = do mama <- get let next = fst . hp $ mama let heap = snd . hp $ mama put mama {hp = (next + 1, insert next obj heap)} return . Pointer $ next assignment :: Map String Basic -> Parser Assign assignment env = (:=) <$> location env <*> (spaces *> string ":=" *> spaces *> location env) location :: Map String Basic -> Parser Address location env = try memory <|> try new <|> try param where memory, param, new :: Parser Address memory = do reg <- char '$' *> many1 lower case reg of "sp" -> return SP "pc" -> return PC "gp" -> return GP "fp" -> return FP "st" -> ST <$> (char '[' *> param <* char ']') "hp" -> HP <$> (char '[' *> param <* char ']') <*> (char '.' *> selector) s -> unexpected $ "$" ++ s ++ " is no memory" new = do string "new" spaces x <- oneOf "BCFV" spaces char '(' params <- param `sepBy1` (do spaces; char ','; spaces) char ')' case x of 'B' -> return $ New BASIC params 'C' -> return $ New CLOSURE params 'F' -> return $ New FUNVAL params 'V' -> return $ New VECTOR params selector :: Parser Selector selector = do s <- many1 lower case s of "b" -> return V "v" -> A <$> (char '[' *> (try var <|> try const) <* char ']') "gp" -> return GLOB "cp" -> return CP "ap" -> return AP "n" -> return N where var, const :: Parser Int var = do x <- many1 lower case lookup x env of Nothing -> unexpected $ x ++ " was never bound" Just (Pointer x) -> return x Just (Label x) -> return x Just err -> unexpected $ show err ++ " is no pointer" const = read <$> many1 digit param = try (char '(' *> unary <* char ')') <|> try (char '(' *> binary <* char ')') <|> try const <|> try memory <|> try var where unary, binary, const, var :: Parser Address unary = char '-' *> (Unary negate <$> memory) const = Const . read <$> many1 digit var = do v <- many1 lower case lookup v env of Nothing -> unexpected $ v ++ " was never bound" Just (Pointer x) -> return . Const $ x Just (Label x) -> return . Const $ x Just err -> unexpected $ show err ++ " is no pointer" binary = do a <- try param spaces o <- op spaces b <- try param return (Binary o a b) where op :: Parser (Pointer -> Pointer -> Pointer) op = do o <- oneOf "+-*/" case o of '+' -> return (+) '-' -> return (-) '*' -> return (*) '/' -> return div err -> unexpected $ err:" is no binary operator" stmt :: [(String, Basic)] -> String -> MaMa () stmt env input = case parse (assignment (fromList env)) "" input of Right a -> assign a Left s -> runtimeError $ "CODE ERROR " ++ intercalate " " (words . show $ s) haul :: [(String, Basic)] -> String -> MaMa Basic haul env input = case parse (location (fromList env)) "" input of Right a -> rightHandSide a Left s -> runtimeError $ "CODE ERROR " ++ intercalate " " (words . show $ s) -- runProgram :: Map Pointer (MaMa ()) -> Result mainLoop prg = do pc <- haul [] "$pc" case pc of Label lbl -> do stmt [] "$pc := $pc + 1" case lookup lbl prg of Nothing -> runtimeError $ "line " ++ show lbl ++ " does no exist" Just a -> a _ -> runtimeError $ show pc ++ " is no label" mainLoop prg runProgram :: Program -> Either Result () runProgram prg = flip evalState (MaMaState 0 0 0 0 empty (0, empty)) . runEitherT $ mainLoop prg test = flip runState (MaMaState 0 0 0 0 empty (0, empty)) . runEitherT $ do stmt [("k", Pointer 10), ("g", Pointer 5)] "$pc := 1 + g"
SRechenberger/Alpaca
src/Alpaca/MaMa/Machine.hs
gpl-3.0
17,316
0
43
7,378
5,265
2,639
2,626
279
32
module Main where import Mudblood.Screen.Vty import Mudblood import MGExperimental import System.Environment main :: IO () main = do args <- getArgs userpath <- initUserPath [] profpath <- case args of [profile] -> initUserPath ["mg", profile] _ -> initUserPath ["mg"] execScreen mkMBConfig (mkMBState NoTrigger mkMGState) (boot userpath profpath >> screen )
talanis85/mudblood
main/Main-MG-Experimental-Vty.hs
gpl-3.0
401
0
12
92
126
65
61
13
2
{- | Module : Main Description : The Tank game Copyright : (c) Frédéric BISSON, 2015 License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : POSIX The Tank game is a simple game where 2 tanks fight each other on a playfield. They can fire missiles, drop mines in order to destroy the opponent. -} module Main where import qualified Data.ByteString.Char8 as BIO import qualified Data.Text.IO as TIO import Control.Monad.State.Lazy (runState) import System.IO (hPrint, hPutStrLn, stderr) import ParseActions (parseActions) import Tank.Units (Coords (XY), makeDeg) import Tank.Game (TankID (TankA, TankB), playActionS) import Tank.SVG (svgShow, svgRender, makeSvg) import Tank.Defaults {-| Initialize the game and run some actions on it. -} main :: IO () main = do actionsATxt <- TIO.readFile "test/actionsA.txt" actionsBTxt <- TIO.readFile "test/actionsB.txt" let tankA = makeTank (XY 500.0 30.0) (makeDeg 90) ("#c5c1ec", "#7262e1") tankB = makeTank (XY 500.0 970.0) (makeDeg (-90)) ("#c1ecce", "#62e186") playfield = makePlayfield tankA tankB actionsA = parseActions TankA actionsATxt actionsB = parseActions TankB actionsBTxt case (actionsA, actionsB) of (Left msg, _) -> hPrint stderr msg (_, Left msg) -> hPrint stderr msg (Right a, Right b) -> do let actions = zip a b (winner, playfield') = runState (playActionS actions) playfield pfsvg = makeSvg (svgShow playfield') BIO.putStrLn $ svgRender pfsvg hPutStrLn stderr $ show winner
Zigazou/Tank
src/Main.hs
gpl-3.0
1,733
0
17
480
406
221
185
32
3
module Relations.RelationHelper where import Domains.Domain import Domains.DomainHelper import Domains.Dimensionable import Domains.DomainElement import FuzzySets.FuzzySet import FuzzySets.CalculatedFuzzySet import Relations.Relation import Utility isUTimesURelation :: Relation -> Bool isUTimesURelation r = let d = domain r components = getAllComponents d in case components of [c1, c2] -> c1 == c2 _ -> False isSymmetric :: Relation -> Bool isSymmetric r = let pairs = extractDomainPairs r in isUTimesURelation r && all (\ (e1, e2) -> f (joinElements e1 e2) == f (joinElements e2 e1)) pairs where f = valueAt r isReflexive :: Relation -> Bool isReflexive r = let d = domain r dim = cardinality $ getComponent d 0 is = diagonalIndices dim elements = map (elementAtIndex d) is in isUTimesURelation r && all (== 1) (map (valueAt r) elements) isMaxMinTransitive :: Relation -> Bool isMaxMinTransitive r = let it = domainIterator r pairs = extractDomainPairs r maxMin x y = maximum $ map (\ z -> min (f (joinElements x z)) (f (joinElements z y))) it f = valueAt r in isUTimesURelation r && all (\ (x, y) -> f (joinElements x y) >= maxMin x y) pairs compositionOfBinaryRelations :: Relation -> Relation -> Relation compositionOfBinaryRelations r1 r2 = let [d1, d2] = map domain [r1, r2] [c11, c12] = map (getComponent d1) [0, 1] [c21, c22] = map (getComponent d2) [0, 1] d = ADomain $ combine [c11, c22] mu i = let [x, y] = map (domainElement . (:[])) $ extractDomainElement $ elementAtIndex d i in maximum $ map (\ z -> min (valueAt r1 (joinElements x z)) (valueAt r2 (joinElements z y))) (iterator c12) in if | all isBinaryRelation [r1, r2] && c12 == c21 -> relation $ calculatedFuzzySet mu d | otherwise -> error "Only binary relations with equal inner domains may be composed." isFuzzyEquivalence :: Relation -> Bool isFuzzyEquivalence r = all ($ r) [isSymmetric, isReflexive, isMaxMinTransitive] isBinaryRelation :: AFuzzySet -> Bool isBinaryRelation r = dimension (domain r) == 2 domainIterator :: Relation -> [DomainElement] domainIterator r = let d = domain r c = getComponent d 0 in iterator c extractDomainPairs :: Relation -> [(DomainElement, DomainElement)] extractDomainPairs r = let it = domainIterator r in [(p1, p2) | p1 <- it, p2 <- it]
mrlovre/super-memory
Pro2/src/Relations/RelationHelper.hs
gpl-3.0
2,508
0
19
625
923
474
449
-1
-1
module Lambda.Eval ( evalTree ) where import Lambda.Symbols import Lambda.Ast import Lambda.Reducer import Text.Parsec data Action = Action Int LambdaTerm Reduction instance Show Action where show (Action n l r) = show n ++ ": " ++ show l ++ " " ++ show r ++ "\n" tupleToAction :: (LambdaTerm, Reduction) -> Action tupleToAction (l,r) = Action 0 l r lambdaTermFromAction :: Action -> LambdaTerm lambdaTermFromAction (Action _ l _) = l reductionFromAction :: Action -> Reduction reductionFromAction (Action _ _ r) = r evalLambdaTerm' :: Int -> LambdaTerm -> [Action] evalLambdaTerm' step m = let result = (tupleToAction . reduceLambdaTerm $ m) in Action step m (reductionFromAction result): -- Break if the result is equal after the reduction and is not an Alpha reduction if m == lambdaTermFromAction result && reductionFromAction result /= Alpha then [Action (step + 1) m None] else evalLambdaTerm (step + 1) $ lambdaTermFromAction result evalLambdaTerm :: Int -> LambdaTerm -> [Action] evalLambdaTerm step m | canEtaReduce m = evalLambdaTerm' step m | normalFormP m = [Action step m None] | otherwise = evalLambdaTerm' step m joinActions :: [Action] -> IO String joinActions a = return $ foldr ((++) . show) "" a -- return $ (foldr (++) "") . (map show) $ a evalTree :: Either ParseError ParseTree -> IO String evalTree (Left parseError) = return $ show parseError evalTree (Right tree) = convertTree tree >>= (joinActions . evalLambdaTerm 1) convertTree :: ParseTree -> IO LambdaTerm convertTree tree = return $ cstToAst tree
KuroAku/lambda
src/Lambda/Eval.hs
gpl-3.0
1,605
0
12
325
531
269
262
38
2