code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{- -} module ProgParser where import HOCHC.Tokeniser import HOCHC.Parser import Text.Parsec.Prim import Text.Parsec.Combinator import Data.Char import Data.Maybe import Data.List(sortBy,union) import Data.Ord(comparing) import HOCHC.DataTypes import Control.Applicative((<**>)) lineParser :: MyParser Definition lineParser = do do optionMaybe$ tok "let" optionMaybe$ tok "rec" (fn:args) <- many1 identifier oneOf [":=","="] body <- formula return (fn,args,body) file :: MyParser [Definition] file = do res <- chainr ((:[])<$>lineParser) (tok "\n" >> return (++)) [] eof return res parseFile :: String -> String -> Either String [Definition] parseFile fname contents = fromParse (do ts <- tokeniseFromFile (["assert"] ++symbols ++ map fst cannonicals) fname contents let body = map cannonise ts runParser file () fname body) fromParse (Left x) = Left $ show x fromParse (Right x) = Right x --for testing qp = (>>= (runParser formula () "" . map cannonise)) . tokeniseFromOps (symbols ++ map fst cannonicals)
penteract/HigherOrderHornRefinement
HOCHC/Translate/ProgParser.hs
bsd-3-clause
1,088
0
14
221
417
215
202
32
1
{-# LANGUAGE TypeFamilies, EmptyDataDecls, ScopedTypeVariables #-} import Data.Monoid type family Force a :: * data Forced (a :: *) type instance Force (Forced a) = a newtype VarF var term value = AVar { unVar :: String } data TermF var term value = Var (Force var) | App (Force term) (Force var) | Value (Force value) | Add (Force term) (Force term) data ValueF var term value = Literal Int | Lambda String (Force term) data SyntaxAlgebra var term value = SyntaxAlgebra { varAlgebra :: VarF var term value -> Force var, termAlgebra :: TermF var term value -> Force term, valueAlgebra :: ValueF var term value -> Force value } type Fix3_1 f g h = f (FixTag3_1 f g h) (FixTag3_2 f g h) (FixTag3_3 f g h) type Fix3_2 f g h = g (FixTag3_1 f g h) (FixTag3_2 f g h) (FixTag3_3 f g h) type Fix3_3 f g h = h (FixTag3_1 f g h) (FixTag3_2 f g h) (FixTag3_3 f g h) data FixTag3_1 f g h data FixTag3_2 f g h data FixTag3_3 f g h type instance Force (FixTag3_1 f g h) = Fix3_1 f g h type instance Force (FixTag3_2 f g h) = Fix3_2 f g h type instance Force (FixTag3_3 f g h) = Fix3_3 f g h type Var = Fix3_1 VarF TermF ValueF type Term = Fix3_2 VarF TermF ValueF type Value = Fix3_3 VarF TermF ValueF -- TODO: try doing this as a functor category? fmap3VarF :: (Force var -> Force var') -> (Force term -> Force term') -> (Force value -> Force value') -> VarF var term value -> VarF var' term' value' fmap3VarF _var _term _value x = case x of AVar x -> AVar x fmap3TermF :: (Force var -> Force var') -> (Force term -> Force term') -> (Force value -> Force value') -> TermF var term value -> TermF var' term' value' fmap3TermF var term value e = case e of Var x -> Var (var x) App e x -> App (term e) (var x) Value v -> Value (value v) Add e1 e2 -> Add (term e1) (term e2) fmap3ValueF :: (Force var -> Force var') -> (Force term -> Force term') -> (Force value -> Force value') -> ValueF var term value -> ValueF var' term' value' fmap3ValueF _var term _value v = case v of Literal l -> Literal l Lambda x e -> Lambda x (term e) foldMap3VarF :: Monoid m => (Force var -> m) -> (Force term -> m) -> (Force value -> m) -> VarF var term value -> m foldMap3VarF _var _term _value x = case x of AVar _ -> mempty foldMap3TermF :: Monoid m => (Force var -> m) -> (Force term -> m) -> (Force value -> m) -> TermF var term value -> m foldMap3TermF var term value e = case e of Var x -> var x App e x -> term e `mappend` var x Value v -> value v Add e1 e2 -> term e1 `mappend` term e2 foldMap3ValueF :: Monoid m => (Force var -> m) -> (Force term -> m) -> (Force value -> m) -> ValueF var term value -> m foldMap3ValueF _var term _value v = case v of Literal _ -> mempty Lambda _ e -> term e example :: Value example = Lambda "x" $ Add (Value (Literal 1)) (Var (AVar "x")) `App` AVar "x" -- fixAlgebra :: SyntaxAlgebra var term value -> SyntaxAlgebra (Fix3_1 var term value) (Fix3_2 var term value) (Fix3_3 var term value) -- fixAlgebra alg = undefined applyAlgebra :: forall var term value. SyntaxAlgebra var term value -> Term -> Force term -- -> SyntaxAlgebra (FixTag3_1 VarF TermF ValueF) (FixTag3_2 VarF TermF ValueF) (FixTag3_3 VarF TermF ValueF) applyAlgebra alg = {- SyntaxAlgebra var term value -- -} term where var :: Var -> Force var var = varAlgebra alg . fmap3VarF var term value term :: Term -> Force term term = termAlgebra alg . fmap3TermF var term value value :: Value -> Force value value = valueAlgebra alg . fmap3ValueF var term value instance Monoid Int where mempty = 0 mappend = (+) main = print result where result = applyAlgebra alg (Value example) alg :: SyntaxAlgebra (Forced Int) (Forced Int) (Forced Int) alg = SyntaxAlgebra var term value var x = 1 + foldMap3VarF id id id x term e = 1 + foldMap3TermF id id id e value v = 1 + foldMap3ValueF id id id v
batterseapower/haskell-kata
Generics1.hs
bsd-3-clause
4,368
0
11
1,366
1,607
819
788
-1
-1
{-# LANGUAGE OverloadedStrings #-} import Text.Templating.Muttonchops import qualified Data.Text.IO as T main = mapM_ T.putStrLn $ take 1000 $ cycle [render "How are you {{foo}}" [("foo", "gentlemen")], render "All your base are belong to {{whom}}" [("whom", "us")], render "You have no chance to survive make your {{what}}" [("what", "time")]]
ThoughtLeadr/muttonchops
Tests/Main.hs
bsd-3-clause
361
0
10
65
92
53
39
7
1
{-# LANGUAGE QuasiQuotes #-} module VirtualMethodsInStructs (testVirtualMethodsInStructs) where import Pygmalion.Test import Pygmalion.Test.TH testVirtualMethodsInStructs = runPygmalionTest "virtual-in-structs.cpp" $ [pygTest| #include "virtual.h" struct ABDE_struct { ABDE var; }; struct ABDE_ptr_struct { ABDE* ptr; }; struct ABDE_ref_struct { ABDE& ref; }; int main(int argc, char** argv) { ABDE ABDE_instance; ABDE* ABDE_ptr = &ABDE_instance; // Structs containing instance values. ABDE_struct ABDE_struct_instance; ABDE_struct_instance.var.@A_pure_method(); ~[Def "ABDE::A_pure_method() [CXXMethod]"]~ ABDE_struct_instance.var.@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ ABDE_struct_instance.var.AB::@AB_method(0); ~[Def "AB::AB_method(int) [CXXMethod]"]~ ABDE_struct_instance.var.ABDE::@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ ABDE_struct* ABDE_struct_ptr = &ABDE_struct_instance; ABDE_struct_ptr->var.@A_pure_method(); ~[Def "ABDE::A_pure_method() [CXXMethod]"]~ ABDE_struct_ptr->var.@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ ABDE_struct_ptr->var.AB::@AB_method(0); ~[Def "AB::AB_method(int) [CXXMethod]"]~ ABDE_struct_ptr->var.ABDE::@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ ABDE_struct& ABDE_struct_ref = ABDE_struct_instance; ABDE_struct_ref.var.@A_pure_method(); ~[Def "ABDE::A_pure_method() [CXXMethod]"]~ ABDE_struct_ref.var.@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ ABDE_struct_ref.var.AB::@AB_method(0); ~[Def "AB::AB_method(int) [CXXMethod]"]~ ABDE_struct_ref.var.ABDE::@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ // Structs containing pointers to instances. ABDE_ptr_struct ABDE_ptr_struct_instance { ABDE_ptr }; ABDE_ptr_struct_instance.ptr->@A_pure_method(); ~~ ~[Defs ["ABDE::A_pure_method() [CXXMethod]", "ABDEF::A_pure_method() [CXXMethod]"]]~ ABDE_ptr_struct_instance.ptr->@AB_method(0); ~~ ~[Defs ["ABDE::AB_method(int) [CXXMethod]", "ABDEF::AB_method(int) [CXXMethod]"]]~ ABDE_ptr_struct_instance.ptr->AB::@AB_method(0); ~[Def "AB::AB_method(int) [CXXMethod]"]~ ABDE_ptr_struct_instance.ptr->ABDE::@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ ABDE_ptr_struct* ABDE_ptr_struct_ptr = &ABDE_ptr_struct_instance; ABDE_ptr_struct_ptr->ptr->@A_pure_method(); ~~ ~[Defs ["ABDE::A_pure_method() [CXXMethod]", "ABDEF::A_pure_method() [CXXMethod]"]]~ ABDE_ptr_struct_ptr->ptr->@AB_method(0); ~~ ~[Defs ["ABDE::AB_method(int) [CXXMethod]", "ABDEF::AB_method(int) [CXXMethod]"]]~ ABDE_ptr_struct_ptr->ptr->AB::@AB_method(0); ~[Def "AB::AB_method(int) [CXXMethod]"]~ ABDE_ptr_struct_ptr->ptr->ABDE::@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ ABDE_ptr_struct& ABDE_ptr_struct_ref = ABDE_ptr_struct_instance; ABDE_ptr_struct_ref.ptr->@A_pure_method(); ~~ ~[Defs ["ABDE::A_pure_method() [CXXMethod]", "ABDEF::A_pure_method() [CXXMethod]"]]~ ABDE_ptr_struct_ref.ptr->@AB_method(0); ~~ ~[Defs ["ABDE::AB_method(int) [CXXMethod]", "ABDEF::AB_method(int) [CXXMethod]"]]~ ABDE_ptr_struct_ref.ptr->AB::@AB_method(0); ~[Def "AB::AB_method(int) [CXXMethod]"]~ ABDE_ptr_struct_ref.ptr->ABDE::@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ // Structs containing references to instances. ABDE_ref_struct ABDE_ref_struct_instance { ABDE_instance }; ABDE_ref_struct_instance.ref.@A_pure_method(); ~~ ~[Defs ["ABDE::A_pure_method() [CXXMethod]", "ABDEF::A_pure_method() [CXXMethod]"]]~ ABDE_ref_struct_instance.ref.@AB_method(0); ~~ ~[Defs ["ABDE::AB_method(int) [CXXMethod]", "ABDEF::AB_method(int) [CXXMethod]"]]~ ABDE_ref_struct_instance.ref.AB::@AB_method(0); ~[Def "AB::AB_method(int) [CXXMethod]"]~ ABDE_ref_struct_instance.ref.ABDE::@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ ABDE_ref_struct* ABDE_ref_struct_ptr = &ABDE_ref_struct_instance; ABDE_ref_struct_ptr->ref.@A_pure_method(); ~~ ~[Defs ["ABDE::A_pure_method() [CXXMethod]", "ABDEF::A_pure_method() [CXXMethod]"]]~ ABDE_ref_struct_ptr->ref.@AB_method(0); ~~ ~[Defs ["ABDE::AB_method(int) [CXXMethod]", "ABDEF::AB_method(int) [CXXMethod]"]]~ ABDE_ref_struct_ptr->ref.AB::@AB_method(0); ~[Def "AB::AB_method(int) [CXXMethod]"]~ ABDE_ref_struct_ptr->ref.ABDE::@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ ABDE_ref_struct& ABDE_ref_struct_ref = ABDE_ref_struct_instance; ABDE_ref_struct_ref.ref.@A_pure_method(); ~~ ~[Defs ["ABDE::A_pure_method() [CXXMethod]", "ABDEF::A_pure_method() [CXXMethod]"]]~ ABDE_ref_struct_ref.ref.@AB_method(0); ~~ ~[Defs ["ABDE::AB_method(int) [CXXMethod]", "ABDEF::AB_method(int) [CXXMethod]"]]~ ABDE_ref_struct_ref.ref.AB::@AB_method(0); ~[Def "AB::AB_method(int) [CXXMethod]"]~ ABDE_ref_struct_ref.ref.ABDE::@AB_method(0); ~[Def "ABDE::AB_method(int) [CXXMethod]"]~ return 0; } |]
sethfowler/pygmalion
tests/VirtualMethodsInStructs.hs
bsd-3-clause
5,416
0
6
974
37
24
13
5
1
-- |Hardware.HHDL -- Convenient top-level module that exports everything HHDL-related. {-# LANGUAGE NoImplicitPrelude #-} module Hardware.HHDL( module Hardware.HHDL.HHDL ) where import Hardware.HHDL.HHDL
thesz/hhdl
src/Hardware/HHDL.hs
bsd-3-clause
219
4
5
37
28
19
9
4
0
module Language.Modelica.Parser.Parser where import Language.Modelica.Parser.Option import qualified Text.Parsec.Prim as Prim type Parser = Prim.Parsec String OptionSet
xie-dongping/modelicaparser
src/Language/Modelica/Parser/Parser.hs
bsd-3-clause
174
0
6
21
37
25
12
4
0
{-# LANGUAGE RankNTypes, TypeOperators, DefaultSignatures #-} -- | Compare to indexed.Data.Functor.Indexed (IxFunctor) module MHask.Indexed.Functor where import MHask.Arrow import qualified MHask.Functor as MHask -- | The indexed version of "MHask.Functor". -- IxFunctor is its own dual. class IxFunctor t where -- | Flipping the arrows on imap's type signature -- is just the same type signature in disguise. -- -- > (m <~ n) -> (t i j m <~ t i j n) -- -- Any implementation of @imap@ must obey Functor laws. -- -- > imap identityArrow ≡ identityArrow -- > imap (f ~>~ g) ≡ imap f ~>~ imap g imap :: (Monad m, Monad n) => (m ~> n) -> (t i j m ~> t i j n) default imap :: (Monad m, Monad n, MHask.Functor (t i j)) => (m ~> n) -> (t i j m ~> t i j n) imap = MHask.fmap
DanBurton/MHask
MHask/Indexed/Functor.hs
bsd-3-clause
835
0
12
213
171
98
73
11
0
module Data.Map.Extensions ( introduce , fromList' , (|->) , (\/) , (/\) ) where import Data.Map (Map, insert, member, empty, union, intersection) import Data.List (foldl') infixr 1 |-> --infix n \/ /\ fromList' :: (Ord k) => [(k,v)] -> Map k v fromList' = foldl' intro empty where intro m (k,v) = introduce k v m introduce :: (Ord k) => k -> v -> Map k v -> Map k v introduce k v m | k `member` m = error $ "keys multiple defined" | otherwise = insert k v m (|->) :: a -> b -> (a,b) (|->) = (,) (\/) :: (Ord k) => Map k v -> Map k v -> Map k v (\/) = union (/\) :: (Ord k) => Map k v -> Map k v -> Map k v (/\) = intersection extend :: (Ord k) => Map k v -> [(k,v)] -> Map k v extend = foldl' ins where ins m (k,v) = insert k v m
timjs/spl-compiler
Old/Extensions.hs
bsd-3-clause
763
0
9
200
415
232
183
25
1
-- TODO: check that every occurrence of "die" should really be a death, and not just a "fix-it-up-and-warn" -- boilerplate {{{ {-# LANGUAGE NoMonomorphismRestriction, FlexibleContexts #-} module Data.SGF.Parse ( collection, clipDate, PropertyType(..), properties, extraProperties, Property(..), Warning(..), ErrorType(..), Error(..) ) where import Control.Applicative import Control.Arrow import Control.Monad import Control.Monad.Reader import Control.Monad.State import Control.Monad.Writer import Data.Bits import Data.Char import Data.Encoding import Data.Function import Data.List import Data.List.Split import Data.Maybe import Data.Ord import Data.Time.Calendar import Data.Tree import Data.Word import Prelude hiding (round) import Text.Parsec hiding (newline) import Text.Parsec.Pos (newPos) import qualified Data.Map as Map import qualified Data.Set as Set import Data.SGF.Parse.Encodings import Data.SGF.Parse.Raw hiding (collection) import Data.SGF.Types hiding (Game(..), GameInfo(..), GameNode(..), Setup(..), Move(..)) import Data.SGF.Types (Game(Game), GameNode(GameNode)) import Data.SGF.Parse.Util import qualified Data.SGF.Parse.Raw as Raw import qualified Data.SGF.Types as T -- }}} -- top level/testing {{{ translate trans state = case runStateT (runWriterT trans) state of Left (UnknownError Nothing ) -> fail "" Left (UnknownError (Just e)) -> fail e Left e -> setPosition (errorPosition e) >> fail (show e) Right ((a, warnings), _) -> return (a, warnings) -- TODO: delete "test" test = runParser collection () "<interactive>" . map enum -- | -- Parse a 'Word8' stream into an SGF collection. A collection is a list of -- games; the documentation for 'Game' has more details. There are generally -- two kinds of errors in SGF files: recoverable ones (which will be -- accumulated in the ['Warning'] return) and unrecoverable ones (which will -- result in parse errors). collection :: Stream s m Word8 => ParsecT s u m (Collection, [Warning]) collection = second concat . unzip <$> (mapM (translate gameTree) =<< Raw.collection) gameTree = do hea <- parseHeader app <- application hea gam <- gameType var <- variationType siz <- size gam fmap (Game app var siz) (parse hea gam siz False) where parse h g s = case g of Go -> fmap TreeGo . nodeGo h s Backgammon -> fmap TreeBackgammon . nodeBackgammon h LinesOfAction -> fmap TreeLinesOfAction . nodeLinesOfAction h Hex -> gameHex h Octi -> fmap TreeOcti . nodeOcti h other -> fmap (TreeOther other) . nodeOther h -- }}} warnAll w ps = mapM_ (\p -> maybe (return ()) (tell . (:[]) . w) =<< consume p) ps dieEarliest e ps = dieWith e . head . sortBy (comparing position) . catMaybes =<< mapM consume ps -- game header information {{{ getFormat = do prop <- consumeSingle "FF" ff <- maybe (return 1) number prop when (ff /= 4) (dieWithPos FormatUnsupported (maybe (newPos "FF_missing" 1 1) position prop)) return ff getEncoding = do ws <- consumeSingle "CA" case maybe [encodingFromString "latin1"] (guessEncoding . head . values) ws of [encoding] -> return encoding [] -> dieWithJust UnknownEncoding ws _ -> dieWithJust AmbiguousEncoding ws -- pretty much guaranteed not to happen parseHeader = liftM2 Header getFormat getEncoding application = flip transMap "AP" . join compose . simple gameType = do property <- consumeSingle "GM" gameType <- maybe (return 1) number property if enum (minBound :: GameType) <= gameType && gameType <= enum (maxBound :: GameType) then return (enum gameType) else dieWithJust OutOfBounds property variationType = transMap (\p -> number p >>= variationType' p) "ST" where variationType' property 0 = return (T.Children, True ) variationType' property 1 = return (T.Siblings, True ) variationType' property 2 = return (T.Children, False) variationType' property 3 = return (T.Siblings, False) variationType' property _ = dieWith OutOfBounds property size gameType = do property <- consumeSingle "SZ" case property of Nothing -> return $ lookup gameType defaultSize Just p -> if enum ':' `elem` head (values p) then do (m, n) <- join compose number p when (m == n) . tell . return . SquareSizeSpecifiedAsRectangle . position $ p checkValidity gameType m n property else do m <- number p checkValidity gameType m m property where invalid t m n = or [t == Go && (m > 52 || n > 52), m < 1, n < 1] checkValidity t m n p = when (invalid t m n) (dieWithJust OutOfBounds p) >> return (Just (m, n)) -- }}} -- game-info properties {{{ gameInfo header = consumeFreeformGameInfo header >>= consumeUpdateGameInfo rank (\g v -> g { T.rankBlack = v }) "BR" header >>= consumeUpdateGameInfo rank (\g v -> g { T.rankWhite = v }) "WR" header >>= consumeUpdateGameInfo round (\g v -> g { T.round = v }) "RO" header >>= consumeUpdateGameInfoMaybe result (\g v -> g { T.result = v }) "RE" header >>= consumeUpdateGameInfoMaybe date dateUpdate "DT" header >>= warnClipDate >>= timeLimit freeformGameInfo = [ ("AN", T.Annotator ), ("BT", T.TeamName Black ), ("CP", T.Copyright ), ("EV", T.Event ), ("GN", T.GameName ), ("GC", T.Context ), ("ON", T.Opening ), ("OT", T.Overtime ), ("PB", T.PlayerName Black), ("PC", T.Location ), ("PW", T.PlayerName White), ("SO", T.Source ), ("US", T.User ), ("WT", T.TeamName White ) ] consumeFreeformGameInfo header = fmap gameInfo tagValues where (tags, types) = unzip freeformGameInfo tagValues = mapM (transMap (simple header)) tags gameInfo vals = (\m -> emptyGameInfo { T.freeform = m }) . Map.fromList . catMaybes $ zipWith (fmap . (,)) types vals consumeUpdateGameInfo = consumeUpdateGameInfoMaybe . (return .) consumeUpdateGameInfoMaybe fromString update property header gameInfo = do maybeProp <- consumeSingle property maybeString <- transMap' (simple header) maybeProp case (maybeProp, maybeString >>= fromString) of (Nothing, _) -> return gameInfo (_, Nothing) -> dieWithJust BadlyFormattedValue maybeProp (_, v) -> return (update gameInfo v) abbreviateList xs = xs >>= \(n, v) -> [(n, v), (take 1 n, v)] -- TODO: can we unify this with the other implementation of reading a rational? readRational s = liftM3 (\s n d -> s * (fromInteger n + d)) maybeSign maybeNum maybeDen where (sign, rest) = span (`elem` "+-") s (numerator, rest') = span isDigit rest denominator' = drop 1 rest' ++ "0" denominator = fromInteger (read denominator') / 10 ^ length denominator' maybeSign = lookup sign [("", 1), ("+", 1), ("-", -1)] maybeNum = listToMaybe numerator >> return (read numerator) maybeDen = guard (take 1 rest' `isPrefixOf` "." && all isDigit denominator') >> return denominator rank s = fromMaybe (OtherRank s) maybeRanked where (rank, rest) = span isDigit s (scale, certainty) = span isAlpha rest maybeRank = listToMaybe rank >> return (read rank) maybeScale = lookup (map toLower scale) scales maybeCertainty = lookup certainty certainties maybeRanked = liftM3 Ranked maybeRank maybeScale maybeCertainty certainties = [("", Nothing), ("?", Just Uncertain), ("*", Just Certain)] scales = abbreviateList [("kyu", Kyu), ("dan", Dan), ("pro", Pro)] result (c:'+':score) = liftM2 Win maybeColor maybeWinType where maybeColor = lookup (toLower c) [('b', Black), ('w', White)] maybeWinType = lookup (map toLower score) winTypes `mplus` fmap Score (readRational score) winTypes = abbreviateList [("", OtherWinType), ("forfeit", Forfeit), ("time", Time), ("resign", Resign)] result s = lookup (map toLower s) [("0", Draw), ("draw", Draw), ("void", Void), ("?", Unknown)] timeLimit gameInfo = fmap (\v -> gameInfo { T.timeLimit = v }) (transMap real "TM") date = expect [] . splitWhen (== ',') where expect parsers [] = return [] expect parsers (pd:pds) = do parsed <- msum . sequence ([parseYMD, parseYM, parseY] ++ parsers) . splitWhen (== '-') $ pd liftM (parsed:) . ($ pds) $ case parsed of Year {} -> expect [] Month { year = y } -> expect [parseMD y, parseM y] Day { year = y, month = m } -> expect [parseMD y, parseD y m] ensure p x = guard (p x) >> return x hasLength n xs = n >= 0 && hasLength' n xs where hasLength' n [] = n == 0 hasLength' 0 (x:xs) = False hasLength' n (x:xs) = hasLength' (n-1) xs ensureLength = ensure . hasLength parseYMD ss = ensureLength 3 ss >>= \[y, m, d] -> liftM3 Day (checkY y) (checkMD m) (checkMD d) parseYM ss = ensureLength 2 ss >>= \[y, m ] -> liftM2 Month (checkY y) (checkMD m) parseY ss = ensureLength 1 ss >>= \[y ] -> liftM Year (checkY y) parseMD y ss = ensureLength 2 ss >>= \[ m, d] -> liftM2 (Day y) (checkMD m) (checkMD d) parseM y ss = ensureLength 1 ss >>= \[ m ] -> liftM (Month y) (checkMD m) parseD y m ss = ensureLength 1 ss >>= \[ d] -> liftM (Day y m) (checkMD d) checkY y = ensureLength 4 y >>= readM checkMD md = ensureLength 2 md >>= readM readM = listToMaybe . map fst . filter (null . snd) . reads -- | -- Clip to a valid, representable date. Years are clipped to the 0000-9999 -- range; months are clipped to the 1-12 range, and days are clipped to the -- 1-\<number of days in the given month\> range (accounting for leap years in -- the case of February). -- -- If a parsed date is changed by this function, a warning is emitted. clipDate :: PartialDate -> PartialDate clipDate (y@Year {}) = Year . min 9999 . max 0 . year $ y clipDate (Month { year = y, month = m }) = Month { year = year . clipDate . Year $ y, month = min 12 . max 1 $ m } clipDate (Day { year = y, month = m, day = d }) = let m' = clipDate (Month y m) in Day { year = year m', month = month m', day = max 1 . min (fromIntegral (gregorianMonthLength (year m') (fromIntegral (month m')))) $ d } warnClipDate gameInfo@(T.GameInfo { T.date = d }) = let d' = Set.map clipDate d in do when (d /= d') (tell [InvalidDatesClipped d]) return gameInfo { T.date = d' } dateUpdate g v = g { T.date = maybe Set.empty Set.fromList v } round s = case words s of [roundNumber@(_:_)] | all isDigit roundNumber -> SimpleRound (read roundNumber) [roundNumber@(_:_), '(':roundType] | all isDigit roundNumber && last roundType == ')' -> FormattedRound (read roundNumber) (init roundType) _ -> OtherRound s -- }}} -- move properties {{{ move move = do color_ <- mapM has ["B", "W"] [number_, overtimeMovesBlack_, overtimeMovesWhite_] <- mapM (transMap number) ["MN", "OB", "OW"] [timeBlack_, timeWhite_] <- mapM (transMap real ) ["BL", "WL"] let partialMove = emptyMove { T.number = number_, T.timeBlack = timeBlack_, T.timeWhite = timeWhite_, T.overtimeMovesBlack = overtimeMovesBlack_, T.overtimeMovesWhite = overtimeMovesWhite_ } case color_ of [False, False] -> warnAll MovelessAnnotationOmitted ["KO", "BM", "DO", "IT", "TE"] >> return partialMove [True , True ] -> dieEarliest ConcurrentBlackAndWhiteMove ["B", "W"] [black, white] -> let color = if black then Black else White in do Just move <- fmap msum . mapM (transMap move) $ ["B", "W"] illegal <- fmap (maybe Possibly (const Definitely)) (transMap none "KO") annotations <- mapM has ["BM", "DO", "IT", "TE"] quality <- case annotations of [False, False, False, False] -> return Nothing [True , False, False, False] -> fmap (fmap Bad ) (transMap double "BM") [False, False, False, True ] -> fmap (fmap Good) (transMap double "TE") [False, True , False, False] -> transMap none "DO" >> return (Just Doubtful ) [False, False, True , False] -> transMap none "IT" >> return (Just Interesting) _ -> dieEarliest ConcurrentAnnotations ["BM", "DO", "IT", "TE"] return partialMove { T.move = Just (color, move), T.illegal = illegal, T.quality = quality } -- }}} -- setup properties {{{ setupPoint point = do points <- mapM (transMapList (listOfPoint point)) ["AB", "AW", "AE"] let [addBlack, addWhite, remove] = map Set.fromList points allPoints = addBlack `Set.union` addWhite `Set.union` remove duplicates = concat points \\ Set.elems allPoints addWhite' = addWhite Set.\\ addBlack remove' = remove Set.\\ (addBlack `Set.union` addWhite') unless (null duplicates) (tell [DuplicateSetupOperationsOmitted duplicates]) setupFinish addBlack addWhite' remove' -- note: does not (cannot, in general) check the constraint that addBlack, -- addWhite, and remove specify disjoint sets of points -- TODO: what, really, cannot? even if we allow ourselves a class constraint or something? setupPointStone point stone = do addBlack <- transMapList (listOf stone) "AB" addWhite <- transMapList (listOf stone) "AW" remove <- transMapList (listOfPoint point) "AE" setupFinish (Set.fromList addBlack) (Set.fromList addWhite) (Set.fromList remove) setupFinish addBlack addWhite remove = liftM (T.Setup addBlack addWhite remove) (transMap color "PL") -- }}} -- none properties {{{ annotation header = do comment <- transMap (text header) "C" name <- transMap (simple header) "N" hotspot <- transMap double "HO" value <- transMap real "V" judgments' <- mapM (transMap double) ["GW", "GB", "DM", "UC"] let judgments = [(j, e) | (j, Just e) <- zip [GoodForWhite ..] judgments'] tell . map ExtraPositionalJudgmentOmitted . drop 1 $ judgments return emptyAnnotation { T.comment = comment, T.name = name, T.hotspot = hotspot, T.value = value, T.judgment = listToMaybe judgments } addMarks marks (mark, points) = tell warning >> return result where (ignored, inserted) = partition (`Map.member` marks) points warning = map (DuplicateMarkupOmitted . (,) mark) ignored result = marks `Map.union` Map.fromList [(i, mark) | i <- inserted] markup header point = do markedPoints <- mapM (transMapList (listOfPoint point)) ["CR", "MA", "SL", "SQ", "TR"] marks <- foldM addMarks Map.empty . zip [Circle ..] $ markedPoints labels <- transMapList (listOf (compose point (simple header))) "LB" arrows <- consumePointPairs "AR" lines <- consumePointPairs "LN" dim <- transMapMulti ( listOfPoint point) "DD" visible <- transMapMulti (elistOfPoint point) "VW" numbering <- transMap number "PM" figure <- transMap (figurePTranslator header) "FG" tell . map DuplicateLabelOmitted $ labels \\ nubBy (on (==) fst) labels tell [UnknownNumberingIgnored n | Just n <- [numbering], n < 0 || n > 2] -- TODO: some kind of warning when omitting arrows and lines return Markup { T.marks = marks, T.labels = Map.fromList labels, T.arrows = prune arrows, T.lines = prune . map canonicalize $ lines, T.dim = fmap Set.fromList dim, T.visible = fmap Set.fromList visible, T.numbering = numbering >>= flip lookup (zip [0..] [Unnumbered ..]), T.figure = figure } where consumePointPairs = transMapList (listOf (join compose point)) prune = Set.fromList . filter (uncurry (/=)) canonicalize (x, y) = (min x y, max x y) figurePTranslator header (Property { values = [[]] }) = return DefaultFigure figurePTranslator header p = do (flags, name) <- compose number (simple header) p return $ if testBit flags 16 then NamedDefaultFigure name else NamedFigure name (not . testBit flags . fromEnum) -- }}} -- known properties list {{{ -- | -- Types of properties, as given in the SGF specification. data PropertyType = Move | Setup | Root | GameInfo | Inherit -- ^ -- Technically, these properties have type \"none\" and -- /attribute/ \"inherit\", but the property index lists them as -- properties of type \"inherit\" with no attributes, so we -- follow that lead. | None deriving (Eq, Ord, Show, Read, Enum, Bounded) -- | -- All properties of each type listed in the SGF specification. properties :: GameType -> PropertyType -> [String] properties = liftM2 (++) properties' . extraProperties where properties' Move = ["B", "KO", "MN", "W", "BM", "DO", "IT", "TE", "BL", "OB", "OW", "WL"] properties' Setup = ["AB", "AE", "AW", "PL"] properties' Root = ["AP", "CA", "FF", "GM", "ST", "SZ"] properties' GameInfo = ["AN", "BR", "BT", "CP", "DT", "EV", "GN", "GC", "ON", "OT", "PB", "PC", "PW", "RE", "RO", "RU", "SO", "TM", "US", "WR", "WT"] properties' Inherit = ["DD", "PM", "VW"] properties' None = ["C", "DM", "GB", "GW", "HO", "N", "UC", "V", "AR", "CR", "LB", "LN", "MA", "SL", "SQ", "TR", "FG"] -- }}} -- game-specific stuff {{{ defaultSize = [ (Go , (19, 19)), (Chess , ( 8, 8)), (LinesOfAction , ( 8, 8)), (Hex , (11, 11)), (Amazons , (10, 10)), (Gess , (20, 20)) ] ruleSetLookup rs = flip lookup rs . map toLower ruleSetGo = ruleSetLookup [ ("aga" , AGA), ("goe" , GOE), ("chinese" , Chinese), ("japanese" , Japanese), ("nz" , NewZealand) ] ruleSetBackgammon = ruleSetLookup [ ("crawford" , Crawford), ("crawford:crawfordgame" , CrawfordGame), ("jacoby" , Jacoby) ] ruleSetOcti s = case break (== ':') s of (major, ':':minors) -> liftM (flip OctiRuleSet (minorVariations minors )) (majorVariation major ) (majorOrMinors, "") -> liftM (flip OctiRuleSet (Set.empty )) (majorVariation majorOrMinors) `mplus` return (OctiRuleSet Full (minorVariations majorOrMinors)) where majorVariation = ruleSetLookup [("full", Full), ("fast", Fast), ("kids", Kids)] minorVariation s = fromMaybe (OtherMinorVariation s) . ruleSetLookup [("edgeless", Edgeless), ("superprong", Superprong)] $ s minorVariations = Set.fromList . map minorVariation . splitWhen (== ',') ruleSet read maybeDefault header = do maybeRulesetString <- transMap (simple header) "RU" return $ case (maybeRulesetString, maybeRulesetString >>= read) of (Nothing, _ ) -> fmap Known maybeDefault (Just s , Nothing) -> Just (OtherRuleSet s) (_ , Just rs) -> Just (Known rs) ruleSetDefault = ruleSet (const Nothing) Nothing -- | -- Just the properties associated with specific games. extraProperties :: GameType -> PropertyType -> [String] extraProperties Go GameInfo = ["HA", "KM"] extraProperties Go None = ["TB", "TW"] extraProperties Backgammon Setup = ["CO", "CV", "DI"] extraProperties Backgammon GameInfo = ["MI", "RE", "RU"] extraProperties LinesOfAction GameInfo = ["IP", "IY", "SU"] extraProperties LinesOfAction None = ["AS", "SE"] extraProperties Hex Root = ["IS"] extraProperties Hex GameInfo = ["IP"] extraProperties Amazons Setup = ["AA"] extraProperties Octi Setup = ["RP"] extraProperties Octi GameInfo = ["BO", "WO", "NP", "NR", "NS"] extraProperties Octi None = ["AS", "CS", "MS", "SS", "TS"] extraProperties _ _ = [] gameInfoGo = liftM2 GameInfoGo (transMap number "HA") (transMap real "KM") pointGo (Property { values = [[x, y]] }) | valid x && valid y = return (translate x, translate y) where valid x = (enum 'a' <= x && x <= enum 'z') || (enum 'A' <= x && x <= enum 'Z') translate x = enum x - enum (if x < enum 'a' then 'A' else 'a') pointGo p = dieWith BadlyFormattedValue p moveGo _ (Property { values = [[]] }) = return Pass moveGo (Just (w, h)) p = pointGo p >>= \v@(x, y) -> return $ if x >= w || y >= h then Pass else Play v moveGo _ p = fmap Play (pointGo p) annotationGo = do territories <- mapM (transMap (elistOfPoint pointGo)) ["TB", "TW"] return . Map.fromList $ [(c, Set.fromList t) | (c, Just t) <- zip [Black, White] territories] gameHex header seenGameInfo = fmap (TreeHex []) (nodeHex header seenGameInfo) nodeGo header size seenGameInfo = do [hasGameInfo, hasRoot, hasSetup, hasMove] <- mapM (hasAny . properties Go) [GameInfo, Root, Setup, Move] let setGameInfo = hasGameInfo && not seenGameInfo duplicateGameInfo = hasGameInfo && seenGameInfo when (hasSetup && hasMove) dieSetupAndMove when duplicateGameInfo warnGameInfo when hasRoot warnRoot mGameInfo <- liftM (\x -> guard setGameInfo >> Just x) (gameInfo header) otherGameInfo <- gameInfoGo ruleSet_ <- ruleSet ruleSetGo Nothing header action_ <- if hasMove then liftM Right $ move (moveGo size) else liftM Left $ setupPoint pointGo annotation_ <- annotation header otherAnnotation <- annotationGo markup_ <- markup header pointGo unknown_ <- unknownProperties children <- gets subForest >>= mapM (\s -> put s >> nodeGo header size (seenGameInfo || hasGameInfo)) return (Node (GameNode (fmap (\gi -> gi { T.ruleSet = ruleSet_, T.otherGameInfo = otherGameInfo }) mGameInfo) action_ annotation_ { T.otherAnnotation = otherAnnotation } markup_ unknown_) children) where dieSetupAndMove = dieEarliest ConcurrentMoveAndSetup (properties Go =<< [Setup, Move]) warnGameInfo = warnAll ExtraGameInfoOmitted (properties Go GameInfo) warnRoot = warnAll NestedRootPropertyOmitted (properties Go Root) nodeBackgammon = nodeOther -- TODO nodeLinesOfAction = nodeOther -- TODO nodeHex = nodeOther -- TODO nodeOcti = nodeOther -- TODO nodeOther header seenGameInfo = return (Node emptyGameNode []) -- TODO -- }}}
tonicebrian/sgf
Data/SGF/Parse.hs
bsd-3-clause
23,300
0
21
6,389
7,831
4,168
3,663
394
9
-- Copyright : (C) 2009 Corey O'Connor -- License : BSD-style (see the file LICENSE) module Bind.Marshal ( module Bind.Marshal , module Bind.Marshal.Action , module Bind.Marshal.DesAction , module Bind.Marshal.SerAction , module Bind.Marshal.StaticProperties , module Bind.Marshal.StdLib ) where import Bind.Marshal.Action import Bind.Marshal.DesAction import Bind.Marshal.SerAction import Bind.Marshal.StaticProperties import Bind.Marshal.StdLib
coreyoconnor/bind-marshal
src/Bind/Marshal.hs
bsd-3-clause
578
0
5
178
81
56
25
11
0
module Day1 where import Control.Applicative import Data.Maybe (fromMaybe) import System.IO (readFile) import Text.Megaparsec hiding (Pos, between) import Text.Megaparsec.Lexer import Text.Megaparsec.String data Turn = L | R deriving (Eq, Show) data Step = Step Turn Int deriving (Eq, Show) data Orientation = N | E | S | W deriving (Eq, Show) type Pos = (Int, Int) data Placement = Placement Orientation Pos deriving (Eq, Show) distance :: Pos -> Pos -> Int distance (p1, p2) (q1, q2) = abs (p1 - q1) + abs (p2 - q2) stepsP :: Parser [Step] stepsP = stepP `sepBy1` string ", " where stepP = Step <$> (l <|> r) <*> n l = char 'L' *> pure L r = char 'R' *> pure R n = fromIntegral <$> integer turn :: Turn -> Orientation -> Orientation turn R N = E turn R E = S turn R S = W turn R W = N turn L N = W turn L W = S turn L S = E turn L E = N move :: Orientation -> Int -> Pos -> Pos move N n (x, y) = (x, y - n) move E n (x, y) = (x + n, y) move S n (x, y) = (x, y + n) move W n (x, y) = (x - n, y) step :: Placement -> Step -> Placement step (Placement o pos) (Step t n) = let o' = turn t o pos' = move o' n pos in Placement o' pos' between :: Pos -> Pos -> [Pos] between (sx, sy) (ex, ey) | sx == ex = [ (sx, y) | y <- if sy < ey then [sy .. ey - 1] else reverse [ey + 1 .. sy] ] | sy == ey = [ (x, sy) | x <- if sx < ex then [sx .. ex - 1] else reverse [ex + 1 .. sx] ] | otherwise = [] stepAll :: Placement -> Step -> [Placement] stepAll (Placement o pos) (Step t n) = let o' = turn t o allPos = [ move o' i pos | i <- [1 .. n] ] in Placement o' <$> allPos part1 :: [Step] -> Int part1 steps = let start@(Placement _ startPos) = Placement N (0, 0) (Placement _ endPos) = foldl step start steps in distance startPos endPos firstDuplicate :: Eq a => [a] -> Maybe a firstDuplicate [] = Nothing firstDuplicate (a:as) | a `elem` as = Just a | otherwise = firstDuplicate as part2 :: [Step] -> Int part2 steps = let start@(Placement _ startPos) = Placement N (0, 0) interpolated [] = [] interpolated (a:b:rest) = between a b ++ interpolated (b : rest) interpolated [a] = [a] positions = interpolated $ (\(Placement _ pos) -> pos) <$> scanl step start steps endPos = fromMaybe startPos (firstDuplicate positions) in distance startPos endPos main :: IO () main = do let inputFile = "input/day1.txt" input <- readFile inputFile let (Right steps) = parse stepsP inputFile input print $ part1 steps print $ part2 steps
liff/adventofcode-2016
app/Day1.hs
bsd-3-clause
2,771
0
14
878
1,274
672
602
104
3
module Sexy.Instances.OrderingC.Ordering () where import Sexy.Classes (OrderingC(..)) import Sexy.Data (Ordering(..), ordering') instance OrderingC Ordering where lt = LT eq = EQ gt = GT ordering = ordering'
DanBurton/sexy
src/Sexy/Instances/OrderingC/Ordering.hs
bsd-3-clause
218
0
6
37
70
44
26
8
0
module YOLP.Weather (getRain, getRainWithPast) where import Data.Text (Text) import YOLP.Base (Requestable, toRequest) import YOLP.Weather.Query import YOLP.Weather.Result import Network.HTTP.Simple (httpLBS) import Network.HTTP.Conduit (responseBody, Request) import Data.Aeson (decode) -- -- TODO : consider Either report :: Requestable r => r -> IO (Maybe [Weather]) report req = do response <- httpLBS . toRequest $ req return . sh $ getWeathers <$> (decode . responseBody $ response) where sh Nothing = Nothing sh (Just []) = Nothing sh (Just (h:_)) = Just h getRain :: (Double, Double) -> IO (Maybe [Weather]) getRain l = report $ baseQuery `withCoords` l getRainWithPast :: (Double, Double) -> IO (Maybe [Weather]) getRainWithPast l = report $ baseQuery `withCoords` l `withPast` TwoHours
lesguillemets/rainfall-vim-hs
src/YOLP/Weather.hs
bsd-3-clause
831
0
11
149
309
172
137
19
3
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Main -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Main (main) where import Test.Tasty import Test.AWS.S3 import Test.AWS.S3.Internal main :: IO () main = defaultMain $ testGroup "S3" [ testGroup "tests" tests , testGroup "fixtures" fixtures ]
fmapfmapfmap/amazonka
amazonka-s3/test/Main.hs
mpl-2.0
519
0
8
103
76
47
29
9
1
-- | -- Module: SwiftNav.SBP.Settings -- Copyright: Copyright (C) 2015 Swift Navigation, Inc. -- License: LGPL-3 -- Maintainer: Mark Fine <[email protected]> -- Stability: experimental -- Portability: portable -- -- Messages for reading and writing the device's device settings. These are in -- the implementation-defined range (0x0000-0x00FF). Note that some of these -- messages share the same message type ID for both the host request and the -- device response. See the accompanying document for descriptions of settings -- configurations and examples: https://github.com/swift- -- nav/piksi\_firmware/blob/master/docs/settings.pdf module SwiftNav.SBP.Settings where import BasicPrelude import Control.Monad import Control.Monad.Loops import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier) import Data.Binary import Data.Binary.Get import Data.Binary.IEEE754 import Data.Binary.Put import Data.ByteString import Data.ByteString.Lazy hiding ( ByteString ) import Data.Int import Data.Word import SwiftNav.SBP.Encoding msgSettingsSave :: Word16 msgSettingsSave = 0x00A1 -- | SBP class for message MSG_SETTINGS_SAVE (0x00A1). -- -- The save settings message persists the device's current settings -- configuration to its onboard flash memory file system. data MsgSettingsSave = MsgSettingsSave deriving ( Show, Read, Eq ) instance Binary MsgSettingsSave where get = return MsgSettingsSave put MsgSettingsSave = return () msgSettingsWrite :: Word16 msgSettingsWrite = 0x00A0 -- | SBP class for message MSG_SETTINGS_WRITE (0x00A0). -- -- The setting message writes the device's configuration. data MsgSettingsWrite = MsgSettingsWrite { msgSettingsWrite_setting :: ByteString -- ^ A NULL-terminated and delimited string with contents [SECTION_SETTING, -- SETTING, VALUE]. } deriving ( Show, Read, Eq ) instance Binary MsgSettingsWrite where get = do msgSettingsWrite_setting <- liftM toStrict getRemainingLazyByteString return MsgSettingsWrite {..} put MsgSettingsWrite {..} = do putByteString msgSettingsWrite_setting $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "msgSettingsWrite_" . stripPrefix "msgSettingsWrite_"} ''MsgSettingsWrite) msgSettingsReadReq :: Word16 msgSettingsReadReq = 0x00A4 -- | SBP class for message MSG_SETTINGS_READ_REQ (0x00A4). -- -- The setting message reads the device's configuration. data MsgSettingsReadReq = MsgSettingsReadReq { msgSettingsReadReq_setting :: ByteString -- ^ A NULL-terminated and delimited string with contents [SECTION_SETTING, -- SETTING]. } deriving ( Show, Read, Eq ) instance Binary MsgSettingsReadReq where get = do msgSettingsReadReq_setting <- liftM toStrict getRemainingLazyByteString return MsgSettingsReadReq {..} put MsgSettingsReadReq {..} = do putByteString msgSettingsReadReq_setting $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "msgSettingsReadReq_" . stripPrefix "msgSettingsReadReq_"} ''MsgSettingsReadReq) msgSettingsReadResp :: Word16 msgSettingsReadResp = 0x00A5 -- | SBP class for message MSG_SETTINGS_READ_RESP (0x00A5). -- -- The setting message reads the device's configuration. data MsgSettingsReadResp = MsgSettingsReadResp { msgSettingsReadResp_setting :: ByteString -- ^ A NULL-terminated and delimited string with contents [SECTION_SETTING, -- SETTING, VALUE]. } deriving ( Show, Read, Eq ) instance Binary MsgSettingsReadResp where get = do msgSettingsReadResp_setting <- liftM toStrict getRemainingLazyByteString return MsgSettingsReadResp {..} put MsgSettingsReadResp {..} = do putByteString msgSettingsReadResp_setting $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "msgSettingsReadResp_" . stripPrefix "msgSettingsReadResp_"} ''MsgSettingsReadResp) msgSettingsReadByIndexReq :: Word16 msgSettingsReadByIndexReq = 0x00A2 -- | SBP class for message MSG_SETTINGS_READ_BY_INDEX_REQ (0x00A2). -- -- The settings message for iterating through the settings values. It will read -- the setting at an index, returning a NULL-terminated and delimited string -- with contents [SECTION_SETTING, SETTING, VALUE]. data MsgSettingsReadByIndexReq = MsgSettingsReadByIndexReq { msgSettingsReadByIndexReq_index :: Word16 -- ^ An index into the device settings, with values ranging from 0 to -- length(settings) } deriving ( Show, Read, Eq ) instance Binary MsgSettingsReadByIndexReq where get = do msgSettingsReadByIndexReq_index <- getWord16le return MsgSettingsReadByIndexReq {..} put MsgSettingsReadByIndexReq {..} = do putWord16le msgSettingsReadByIndexReq_index $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "msgSettingsReadByIndexReq_" . stripPrefix "msgSettingsReadByIndexReq_"} ''MsgSettingsReadByIndexReq) msgSettingsReadByIndexResp :: Word16 msgSettingsReadByIndexResp = 0x00A7 -- | SBP class for message MSG_SETTINGS_READ_BY_INDEX_RESP (0x00A7). -- -- The settings message for iterating through the settings values. It will read -- the setting at an index, returning a NULL-terminated and delimited string -- with contents [SECTION_SETTING, SETTING, VALUE]. data MsgSettingsReadByIndexResp = MsgSettingsReadByIndexResp { msgSettingsReadByIndexResp_index :: Word16 -- ^ An index into the device settings, with values ranging from 0 to -- length(settings) , msgSettingsReadByIndexResp_setting :: ByteString -- ^ A NULL-terminated and delimited string with contents [SECTION_SETTING, -- SETTING, VALUE]. } deriving ( Show, Read, Eq ) instance Binary MsgSettingsReadByIndexResp where get = do msgSettingsReadByIndexResp_index <- getWord16le msgSettingsReadByIndexResp_setting <- liftM toStrict getRemainingLazyByteString return MsgSettingsReadByIndexResp {..} put MsgSettingsReadByIndexResp {..} = do putWord16le msgSettingsReadByIndexResp_index putByteString msgSettingsReadByIndexResp_setting $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "msgSettingsReadByIndexResp_" . stripPrefix "msgSettingsReadByIndexResp_"} ''MsgSettingsReadByIndexResp) msgSettingsReadByIndexDone :: Word16 msgSettingsReadByIndexDone = 0x00A6 -- | SBP class for message MSG_SETTINGS_READ_BY_INDEX_DONE (0x00A6). -- -- The settings message for indicating end of the settings values. data MsgSettingsReadByIndexDone = MsgSettingsReadByIndexDone deriving ( Show, Read, Eq ) instance Binary MsgSettingsReadByIndexDone where get = return MsgSettingsReadByIndexDone put MsgSettingsReadByIndexDone = return ()
paparazzi/libsbp
haskell/src/SwiftNav/SBP/Settings.hs
lgpl-3.0
6,638
0
11
1,014
922
504
418
-1
-1
-- | Recursive topological sort. module Ivory.Compile.ACL2.RecTopoSort ( recTopoSort , allDependencies ) where import Data.Function (on) import Data.List (nub, sort, sortBy) -- | Topological sort of recursive functions. recTopoSort :: (Eq a, Ord a) => (a -> [a]) -> [a] -> [[a]] recTopoSort callees = filter (not . null) . f [] . sortBy (compare `on` length) . map (allDependencies callees) where f sofar a = case a of [] -> [] a : b -> [ a | a <- a, not $ elem a sofar ] : f (nub $ a ++ sofar) b -- | All the dependencies for a given functions, including that function. allDependencies :: (Eq a, Ord a) => (a -> [a]) -> a -> [a] allDependencies callees a = f [a] where f sofar | sofar == next = sofar | otherwise = f next where next = sort $ nub $ sofar ++ concatMap callees sofar
GaloisInc/ivory-backend-acl2
src/Ivory/Compile/ACL2/RecTopoSort.hs
bsd-3-clause
828
0
14
200
341
182
159
16
2
------------------------------------------------------------------------ -- | -- Module : Kask.Text -- Copyright : (c) 2016 Konrad Grzanek -- License : BSD-style (see the file LICENSE) -- Created : 2016-08-29 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Misc. functionalities related to Text; constructors, validators, etc. ------------------------------------------------------------------------ module Kask.Text ( NonBlank , Stripped , StrippedNonBlank , ShowText , strip , stripNonBlank , showText ) where import qualified Data.Text as T import qualified Kask.Constr as C import RIO class ShowText a where showText :: a -> T.Text -- | Stripped text newtype Stripped = Stripped T.Text deriving (Eq, Generic) instance Hashable Stripped instance NFData Stripped instance Show Stripped where show (Stripped txt) = show txt {-# INLINE show #-} instance ShowText Stripped where showText (Stripped txt) = txt {-# INLINE showText #-} class Strip a where strip :: a -> Stripped instance Strip T.Text where strip = Stripped . T.strip {-# INLINE strip #-} instance Strip String where strip = strip . T.pack {-# INLINE strip #-} -- | NonNull constraint for Stripped instance C.IsNull Stripped where isNull (Stripped txt) = C.isNull txt {-# INLINE isNull #-} -- | Non-blank textual content type NonBlank = C.Constr C.NonNull T.Text type StrippedNonBlank = C.Constr C.NonNull Stripped stripNonBlank :: Strip a => a -> Maybe StrippedNonBlank stripNonBlank = C.constr C.NonNull . strip {-# INLINE stripNonBlank #-}
kongra/kask-base
src/Kask/Text.hs
bsd-3-clause
1,684
0
8
358
325
183
142
38
1
module WriteSpec ( writeSpec ) where import TestInit import Prelude hiding (FilePath) import Data.Text (Text) default (Text) createsFile :: FilePath -> (FilePath -> IO ()) -> IO () createsFile f action = do exists <- shelly $ test_e f when exists $ error "cleanup after yourself!" action f shelly $ rm f return () writeSpec :: Spec writeSpec = do describe "writefile" $ it "creates and overwrites a file" $ createsFile "foo" $ \f -> do assert . (== "a") =<< (shelly $ writefile f "a" >> readfile f) assert . (== "b") =<< (shelly $ writefile f "b" >> readfile f) describe "writeBinary" $ it "creates and overwrites a file" $ createsFile "foo" $ \f -> do assert . (== "a") =<< (shelly $ writeBinary f "a" >> readBinary f) assert . (== "b") =<< (shelly $ writeBinary f "b" >> readBinary f) describe "appendfile" $ it "creates and appends a file" $ createsFile "foo" $ \f -> do assert . (== "a") =<< (shelly $ appendfile f "a" >> readfile f) assert . (== "ab") =<< (shelly $ appendfile f "b" >> readfile f) describe "touchfile" $ it "creates and updates a file" $ createsFile "foo" $ \f -> do assert . (== "") =<< (shelly $ touchfile f >> readfile f) assert . (== "") =<< (shelly $ touchfile f >> readfile f) assert . (== "a") =<< (shelly $ writefile f "a" >> touchfile f >> readfile f)
adinapoli/Shelly.hs
test/src/WriteSpec.hs
bsd-3-clause
1,389
0
16
348
563
276
287
32
1
{- ** ********************************************************************* * * * (c) Kathleen Fisher <[email protected]> * * John Launchbury <[email protected]> * * * ************************************************************************ -} module Language.Pads.LazyList where import qualified Data.ByteString as B import qualified Language.Pads.Source as S import qualified Data.List as List -- Lazy append-lists type FList = B.ByteString -> B.ByteString (+++) :: FList -> FList -> FList p +++ q = \ws -> p (q ws) nil :: FList nil = \ws -> ws concatFL :: [FList] -> FList concatFL (f:fs) = f +++ (concatFL fs) concatFL [] = nil printNothing :: FList printNothing ws = ws addBString :: B.ByteString -> FList addBString bs = \ws -> B.append bs ws addString :: String -> FList addString s = \ws -> B.append (S.strToByteString s) ws fshow :: Show a => a -> FList fshow x = \ws -> B.append (S.strToByteString (show x)) ws printEOR :: FList printEOR = addString ['\n'] printEOF :: FList printEOF = addString [] endRecord :: FList -> FList endRecord fst = fst +++ printEOR printF :: FList -> IO () printF q = Prelude.print (B.unpack (q B.empty)) -------------------------------------------------- printList :: ((r,m) -> FList) -> FList -> FList -> ([r], (b,[m])) -> FList printList printItem printSep printTerm (reps, (_,mds)) = (concatFL (List.intersperse printSep (map printItem (zip reps mds))) ) +++ printTerm
GaloisInc/pads-haskell
Language/Pads/LazyList.hs
bsd-3-clause
1,659
0
13
442
491
270
221
32
1
{-# Language UndecidableInstances, DataKinds, TypeOperators, KindSignatures, PolyKinds, TypeInType, TypeFamilies, GADTs, LambdaCase, ScopedTypeVariables #-} module T14554 where import Data.Kind import Data.Proxy type a ~> b = (a, b) -> Type data IdSym0 :: (Type,Type) -> Type data KIND = X | FNARR KIND KIND data TY :: KIND -> Type where ID :: TY (FNARR X X) FNAPP :: TY (FNARR k k') -> TY k -> TY k' data TyRep (kind::KIND) :: TY kind -> Type where TID :: TyRep (FNARR X X) ID TFnApp :: TyRep (FNARR k k') f -> TyRep k a -> TyRep k' (FNAPP f a) type family IK (kind::KIND) :: Type where IK X = Type IK (FNARR k k') = IK k ~> IK k' type family IT (ty::TY kind) :: IK kind zero :: TyRep X a -> IT a zero x = case x of TFnApp TID a -> undefined
shlevy/ghc
testsuite/tests/indexed-types/should_compile/T14554.hs
bsd-3-clause
860
0
10
266
315
170
145
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.SQS.SendMessage -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Delivers a message to the specified queue. With Amazon SQS, you now have the -- ability to send large payload messages that are up to 256KB (262,144 bytes) -- in size. To send large payloads, you must use an AWS SDK that supports SigV4 -- signing. To verify whether SigV4 is supported for an AWS SDK, check the SDK -- release notes. -- -- The following list shows the characters (in Unicode) allowed in your -- message, according to the W3C XML specification. For more information, go to <http://www.w3.org/TR/REC-xml/#charsets http://www.w3.org/TR/REC-xml/#charsets> If you send any characters not included in the list, your request will be -- rejected. -- -- #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] | [#x10000 to -- #x10FFFF] -- -- -- -- <http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html> module Network.AWS.SQS.SendMessage ( -- * Request SendMessage -- ** Request constructor , sendMessage -- ** Request lenses , smDelaySeconds , smMessageAttributes , smMessageBody , smQueueUrl -- * Response , SendMessageResponse -- ** Response constructor , sendMessageResponse -- ** Response lenses , smrMD5OfMessageAttributes , smrMD5OfMessageBody , smrMessageId ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.SQS.Types import qualified GHC.Exts data SendMessage = SendMessage { _smDelaySeconds :: Maybe Int , _smMessageAttributes :: EMap "entry" "Name" "Value" Text MessageAttributeValue , _smMessageBody :: Text , _smQueueUrl :: Text } deriving (Eq, Read, Show) -- | 'SendMessage' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'smDelaySeconds' @::@ 'Maybe' 'Int' -- -- * 'smMessageAttributes' @::@ 'HashMap' 'Text' 'MessageAttributeValue' -- -- * 'smMessageBody' @::@ 'Text' -- -- * 'smQueueUrl' @::@ 'Text' -- sendMessage :: Text -- ^ 'smQueueUrl' -> Text -- ^ 'smMessageBody' -> SendMessage sendMessage p1 p2 = SendMessage { _smQueueUrl = p1 , _smMessageBody = p2 , _smDelaySeconds = Nothing , _smMessageAttributes = mempty } -- | The number of seconds (0 to 900 - 15 minutes) to delay a specific message. -- Messages with a positive 'DelaySeconds' value become available for processing -- after the delay time is finished. If you don't specify a value, the default -- value for the queue applies. smDelaySeconds :: Lens' SendMessage (Maybe Int) smDelaySeconds = lens _smDelaySeconds (\s a -> s { _smDelaySeconds = a }) -- | Each message attribute consists of a Name, Type, and Value. For more -- information, see <http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSMessageAttributes.html#SQSMessageAttributesNTV Message Attribute Items>. smMessageAttributes :: Lens' SendMessage (HashMap Text MessageAttributeValue) smMessageAttributes = lens _smMessageAttributes (\s a -> s { _smMessageAttributes = a }) . _EMap -- | The message to send. String maximum 256 KB in size. For a list of allowed -- characters, see the preceding important note. smMessageBody :: Lens' SendMessage Text smMessageBody = lens _smMessageBody (\s a -> s { _smMessageBody = a }) -- | The URL of the Amazon SQS queue to take action on. smQueueUrl :: Lens' SendMessage Text smQueueUrl = lens _smQueueUrl (\s a -> s { _smQueueUrl = a }) data SendMessageResponse = SendMessageResponse { _smrMD5OfMessageAttributes :: Maybe Text , _smrMD5OfMessageBody :: Maybe Text , _smrMessageId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'SendMessageResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'smrMD5OfMessageAttributes' @::@ 'Maybe' 'Text' -- -- * 'smrMD5OfMessageBody' @::@ 'Maybe' 'Text' -- -- * 'smrMessageId' @::@ 'Maybe' 'Text' -- sendMessageResponse :: SendMessageResponse sendMessageResponse = SendMessageResponse { _smrMD5OfMessageBody = Nothing , _smrMD5OfMessageAttributes = Nothing , _smrMessageId = Nothing } -- | An MD5 digest of the non-URL-encoded message attribute string. This can be -- used to verify that Amazon SQS received the message correctly. Amazon SQS -- first URL decodes the message before creating the MD5 digest. For information -- about MD5, go to <http://www.faqs.org/rfcs/rfc1321.html http://www.faqs.org/rfcs/rfc1321.html>. smrMD5OfMessageAttributes :: Lens' SendMessageResponse (Maybe Text) smrMD5OfMessageAttributes = lens _smrMD5OfMessageAttributes (\s a -> s { _smrMD5OfMessageAttributes = a }) -- | An MD5 digest of the non-URL-encoded message body string. This can be used to -- verify that Amazon SQS received the message correctly. Amazon SQS first URL -- decodes the message before creating the MD5 digest. For information about -- MD5, go to <http://www.faqs.org/rfcs/rfc1321.html http://www.faqs.org/rfcs/rfc1321.html>. smrMD5OfMessageBody :: Lens' SendMessageResponse (Maybe Text) smrMD5OfMessageBody = lens _smrMD5OfMessageBody (\s a -> s { _smrMD5OfMessageBody = a }) -- | An element containing the message ID of the message sent to the queue. For -- more information, see <http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ImportantIdentifiers.html Queue and Message Identifiers> in the /Amazon SQSDeveloper Guide/. smrMessageId :: Lens' SendMessageResponse (Maybe Text) smrMessageId = lens _smrMessageId (\s a -> s { _smrMessageId = a }) instance ToPath SendMessage where toPath = const "/" instance ToQuery SendMessage where toQuery SendMessage{..} = mconcat [ "DelaySeconds" =? _smDelaySeconds , toQuery _smMessageAttributes , "MessageBody" =? _smMessageBody , "QueueUrl" =? _smQueueUrl ] instance ToHeaders SendMessage instance AWSRequest SendMessage where type Sv SendMessage = SQS type Rs SendMessage = SendMessageResponse request = post "SendMessage" response = xmlResponse instance FromXML SendMessageResponse where parseXML = withElement "SendMessageResult" $ \x -> SendMessageResponse <$> x .@? "MD5OfMessageAttributes" <*> x .@? "MD5OfMessageBody" <*> x .@? "MessageId"
romanb/amazonka
amazonka-sqs/gen/Network/AWS/SQS/SendMessage.hs
mpl-2.0
7,377
0
13
1,526
816
495
321
89
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.AutoScaling.DeleteAutoScalingGroup -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Deletes the specified Auto Scaling group. -- -- The group must have no instances and no scaling activities in progress. -- -- To remove all instances before calling 'DeleteAutoScalingGroup', you can call 'UpdateAutoScalingGroup' to set the minimum and maximum size of the AutoScalingGroup to zero. -- -- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DeleteAutoScalingGroup.html> module Network.AWS.AutoScaling.DeleteAutoScalingGroup ( -- * Request DeleteAutoScalingGroup -- ** Request constructor , deleteAutoScalingGroup -- ** Request lenses , dasgAutoScalingGroupName , dasgForceDelete -- * Response , DeleteAutoScalingGroupResponse -- ** Response constructor , deleteAutoScalingGroupResponse ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.AutoScaling.Types import qualified GHC.Exts data DeleteAutoScalingGroup = DeleteAutoScalingGroup { _dasgAutoScalingGroupName :: Text , _dasgForceDelete :: Maybe Bool } deriving (Eq, Ord, Read, Show) -- | 'DeleteAutoScalingGroup' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dasgAutoScalingGroupName' @::@ 'Text' -- -- * 'dasgForceDelete' @::@ 'Maybe' 'Bool' -- deleteAutoScalingGroup :: Text -- ^ 'dasgAutoScalingGroupName' -> DeleteAutoScalingGroup deleteAutoScalingGroup p1 = DeleteAutoScalingGroup { _dasgAutoScalingGroupName = p1 , _dasgForceDelete = Nothing } -- | The name of the group to delete. dasgAutoScalingGroupName :: Lens' DeleteAutoScalingGroup Text dasgAutoScalingGroupName = lens _dasgAutoScalingGroupName (\s a -> s { _dasgAutoScalingGroupName = a }) -- | Specifies that the group will be deleted along with all instances associated -- with the group, without waiting for all instances to be terminated. This -- parameter also deletes any lifecycle actions associated with the group. dasgForceDelete :: Lens' DeleteAutoScalingGroup (Maybe Bool) dasgForceDelete = lens _dasgForceDelete (\s a -> s { _dasgForceDelete = a }) data DeleteAutoScalingGroupResponse = DeleteAutoScalingGroupResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'DeleteAutoScalingGroupResponse' constructor. deleteAutoScalingGroupResponse :: DeleteAutoScalingGroupResponse deleteAutoScalingGroupResponse = DeleteAutoScalingGroupResponse instance ToPath DeleteAutoScalingGroup where toPath = const "/" instance ToQuery DeleteAutoScalingGroup where toQuery DeleteAutoScalingGroup{..} = mconcat [ "AutoScalingGroupName" =? _dasgAutoScalingGroupName , "ForceDelete" =? _dasgForceDelete ] instance ToHeaders DeleteAutoScalingGroup instance AWSRequest DeleteAutoScalingGroup where type Sv DeleteAutoScalingGroup = AutoScaling type Rs DeleteAutoScalingGroup = DeleteAutoScalingGroupResponse request = post "DeleteAutoScalingGroup" response = nullResponse DeleteAutoScalingGroupResponse
romanb/amazonka
amazonka-autoscaling/gen/Network/AWS/AutoScaling/DeleteAutoScalingGroup.hs
mpl-2.0
4,068
0
9
806
401
246
155
53
1
-------------------------------------------------------------------- -- | -- Module : Text.Atom.Feed.Link -- Copyright : (c) Galois, Inc. 2008, -- (c) Sigbjorn Finne 2009- -- License : BSD3 -- -- Maintainer: Sigbjorn Finne <[email protected]> -- Stability : provisional -- Portability: portable -- -------------------------------------------------------------------- module Text.Atom.Feed.Link ( LinkRelation(..) , showLinkRelation , showLinkAttr ) where -- | Atom feeds uses typed IRI links to represent -- information \/ metadata that is of interest to the -- consumers (software, in the main) of feeds. For instance, -- the edit link relation attached to an atom:entry element -- points to the IRI to use to update\/edit it. -- -- The Atom standard encourages that such typed links to -- be registered with IANA if they have wider applicability, -- and the 'LinkRelation' data type encodes the currently -- registered link types (derived from: -- http:\/\/www.iana.org\/assignments\/link-relations.html -- on 2007-10-28] -- data LinkRelation -- relevant RFC: = LinkAlternate -- http://www.rfc-editor.org/rfc/rfc4287.txt | LinkCurrent -- http://www.rfc-editor.org/rfc/rfc5005.txt | LinkEnclosure -- http://www.rfc-editor.org/rfc/rfc4287.txt | LinkEdit -- http://www.rfc-editor.org/rfc/rfc5023.txt | LinkEditMedia -- http://www.rfc-editor.org/rfc/rfc5023.txt | LinkFirst -- http://www.iana.org/assignments/link-relations/first | LinkLast -- http://www.iana.org/assignments/link-relations/last | LinkLicense -- http://www.rfc-editor.org/rfc/rfc4946.txt | LinkNext -- http://www.rfc-editor.org/rfc/rfc5005.txt | LinkNextArchive -- http://www.rfc-editor.org/rfc/rfc5005.txt | LinkPayment -- http://www.iana.org/assignments/link-relations/payment | LinkPrevArchive -- http://www.rfc-editor.org/rfc/rfc5005.txt | LinkPrevious -- http://www.rfc-editor.org/rfc/rfc5005.txt | LinkRelated -- http://www.rfc-editor.org/rfc/rfc4287.txt | LinkReplies -- http://www.rfc-editor.org/rfc/rfc4685.txt | LinkSelf -- http://www.rfc-editor.org/rfc/rfc4287.txt | LinkVia -- http://www.rfc-editor.org/rfc/rfc4287.txt | LinkOther String deriving (Eq, Show) showLinkRelation :: LinkRelation -> String showLinkRelation lr = case lr of LinkAlternate -> "alternate" LinkCurrent -> "current" LinkEnclosure -> "enclosure" LinkEdit -> "edit" LinkEditMedia -> "edit-media" LinkFirst -> "first" LinkLast -> "last" LinkLicense -> "license" LinkNext -> "next" LinkNextArchive -> "next-archive" LinkPayment -> "payment" LinkPrevArchive -> "prev-archive" LinkPrevious -> "previous" LinkRelated -> "related" LinkReplies -> "replies" LinkSelf -> "self" LinkVia -> "via" LinkOther s -> s showLinkAttr :: LinkRelation -> String{-URI-} -> String showLinkAttr lr s = showLinkRelation lr ++ '=':'"':concatMap escQ s ++ "\"" where escQ '"' = "&dquot;" escQ x = [x]
danfran/feed
src/Text/Atom/Feed/Link.hs
bsd-3-clause
3,337
0
9
831
338
205
133
49
18
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} -- | Abstract syntax of global declarations. -- -- Definitions for: @SynDecl@ and @ConDecl@, @ClassDecl@, -- @InstDecl@, @DefaultDecl@ and @ForeignDecl@. module HsDecls ( -- * Toplevel declarations HsDecl(..), LHsDecl, HsDataDefn(..), -- ** Class or type declarations TyClDecl(..), LTyClDecl, TyClGroup(..), tyClGroupConcat, mkTyClGroup, isClassDecl, isDataDecl, isSynDecl, tcdName, isFamilyDecl, isTypeFamilyDecl, isDataFamilyDecl, isOpenTypeFamilyInfo, isClosedTypeFamilyInfo, tyFamInstDeclName, tyFamInstDeclLName, countTyClDecls, pprTyClDeclFlavour, tyClDeclLName, tyClDeclTyVars, hsDeclHasCusk, famDeclHasCusk, FamilyDecl(..), LFamilyDecl, -- ** Instance declarations InstDecl(..), LInstDecl, NewOrData(..), FamilyInfo(..), TyFamInstDecl(..), LTyFamInstDecl, instDeclDataFamInsts, DataFamInstDecl(..), LDataFamInstDecl, pprDataFamInstFlavour, TyFamEqn(..), TyFamInstEqn, LTyFamInstEqn, TyFamDefltEqn, LTyFamDefltEqn, HsTyPats, LClsInstDecl, ClsInstDecl(..), -- ** Standalone deriving declarations DerivDecl(..), LDerivDecl, -- ** @RULE@ declarations LRuleDecls,RuleDecls(..),RuleDecl(..), LRuleDecl, RuleBndr(..),LRuleBndr, collectRuleBndrSigTys, flattenRuleDecls, -- ** @VECTORISE@ declarations VectDecl(..), LVectDecl, lvectDeclName, lvectInstDecl, -- ** @default@ declarations DefaultDecl(..), LDefaultDecl, -- ** Template haskell declaration splice SpliceExplicitFlag(..), SpliceDecl(..), LSpliceDecl, -- ** Foreign function interface declarations ForeignDecl(..), LForeignDecl, ForeignImport(..), ForeignExport(..), noForeignImportCoercionYet, noForeignExportCoercionYet, CImportSpec(..), -- ** Data-constructor declarations ConDecl(..), LConDecl, ResType(..), HsConDeclDetails, hsConDeclArgTys, -- ** Document comments DocDecl(..), LDocDecl, docDeclDoc, -- ** Deprecations WarnDecl(..), LWarnDecl, WarnDecls(..), LWarnDecls, -- ** Annotations AnnDecl(..), LAnnDecl, AnnProvenance(..), annProvenanceName_maybe, -- ** Role annotations RoleAnnotDecl(..), LRoleAnnotDecl, roleAnnotDeclName, -- ** Injective type families FamilyResultSig(..), LFamilyResultSig, InjectivityAnn(..), LInjectivityAnn, resultVariableName, -- * Grouping HsGroup(..), emptyRdrGroup, emptyRnGroup, appendGroups ) where -- friends: import {-# SOURCE #-} HsExpr( LHsExpr, HsExpr, HsSplice, pprExpr, pprSplice ) -- Because Expr imports Decls via HsBracket import HsBinds import HsPat import HsTypes import HsDoc import TyCon import Name import BasicTypes import Coercion import ForeignCall import PlaceHolder ( PostTc,PostRn,PlaceHolder(..),DataId ) import NameSet -- others: import InstEnv import Class import Outputable import Util import SrcLoc import FastString import Bag import Data.Data hiding (TyCon,Fixity) #if __GLASGOW_HASKELL__ < 709 import Data.Foldable ( Foldable ) import Data.Traversable ( Traversable ) #endif {- ************************************************************************ * * \subsection[HsDecl]{Declarations} * * ************************************************************************ -} type LHsDecl id = Located (HsDecl id) -- ^ When in a list this may have -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' -- -- For details on above see note [Api annotations] in ApiAnnotation -- | A Haskell Declaration data HsDecl id = TyClD (TyClDecl id) -- ^ A type or class declaration. | InstD (InstDecl id) -- ^ An instance declaration. | DerivD (DerivDecl id) | ValD (HsBind id) | SigD (Sig id) | DefD (DefaultDecl id) | ForD (ForeignDecl id) | WarningD (WarnDecls id) | AnnD (AnnDecl id) | RuleD (RuleDecls id) | VectD (VectDecl id) | SpliceD (SpliceDecl id) -- Includes quasi-quotes | DocD (DocDecl) | RoleAnnotD (RoleAnnotDecl id) deriving (Typeable) deriving instance (DataId id) => Data (HsDecl id) -- NB: all top-level fixity decls are contained EITHER -- EITHER SigDs -- OR in the ClassDecls in TyClDs -- -- The former covers -- a) data constructors -- b) class methods (but they can be also done in the -- signatures of class decls) -- c) imported functions (that have an IfacSig) -- d) top level decls -- -- The latter is for class methods only -- | A 'HsDecl' is categorised into a 'HsGroup' before being -- fed to the renamer. data HsGroup id = HsGroup { hs_valds :: HsValBinds id, hs_splcds :: [LSpliceDecl id], hs_tyclds :: [TyClGroup id], -- A list of mutually-recursive groups -- No family-instances here; they are in hs_instds -- Parser generates a singleton list; -- renamer does dependency analysis hs_instds :: [LInstDecl id], -- Both class and family instance declarations in here hs_derivds :: [LDerivDecl id], hs_fixds :: [LFixitySig id], -- Snaffled out of both top-level fixity signatures, -- and those in class declarations hs_defds :: [LDefaultDecl id], hs_fords :: [LForeignDecl id], hs_warnds :: [LWarnDecls id], hs_annds :: [LAnnDecl id], hs_ruleds :: [LRuleDecls id], hs_vects :: [LVectDecl id], hs_docs :: [LDocDecl] } deriving (Typeable) deriving instance (DataId id) => Data (HsGroup id) emptyGroup, emptyRdrGroup, emptyRnGroup :: HsGroup a emptyRdrGroup = emptyGroup { hs_valds = emptyValBindsIn } emptyRnGroup = emptyGroup { hs_valds = emptyValBindsOut } emptyGroup = HsGroup { hs_tyclds = [], hs_instds = [], hs_derivds = [], hs_fixds = [], hs_defds = [], hs_annds = [], hs_fords = [], hs_warnds = [], hs_ruleds = [], hs_vects = [], hs_valds = error "emptyGroup hs_valds: Can't happen", hs_splcds = [], hs_docs = [] } appendGroups :: HsGroup a -> HsGroup a -> HsGroup a appendGroups HsGroup { hs_valds = val_groups1, hs_splcds = spliceds1, hs_tyclds = tyclds1, hs_instds = instds1, hs_derivds = derivds1, hs_fixds = fixds1, hs_defds = defds1, hs_annds = annds1, hs_fords = fords1, hs_warnds = warnds1, hs_ruleds = rulds1, hs_vects = vects1, hs_docs = docs1 } HsGroup { hs_valds = val_groups2, hs_splcds = spliceds2, hs_tyclds = tyclds2, hs_instds = instds2, hs_derivds = derivds2, hs_fixds = fixds2, hs_defds = defds2, hs_annds = annds2, hs_fords = fords2, hs_warnds = warnds2, hs_ruleds = rulds2, hs_vects = vects2, hs_docs = docs2 } = HsGroup { hs_valds = val_groups1 `plusHsValBinds` val_groups2, hs_splcds = spliceds1 ++ spliceds2, hs_tyclds = tyclds1 ++ tyclds2, hs_instds = instds1 ++ instds2, hs_derivds = derivds1 ++ derivds2, hs_fixds = fixds1 ++ fixds2, hs_annds = annds1 ++ annds2, hs_defds = defds1 ++ defds2, hs_fords = fords1 ++ fords2, hs_warnds = warnds1 ++ warnds2, hs_ruleds = rulds1 ++ rulds2, hs_vects = vects1 ++ vects2, hs_docs = docs1 ++ docs2 } instance OutputableBndr name => Outputable (HsDecl name) where ppr (TyClD dcl) = ppr dcl ppr (ValD binds) = ppr binds ppr (DefD def) = ppr def ppr (InstD inst) = ppr inst ppr (DerivD deriv) = ppr deriv ppr (ForD fd) = ppr fd ppr (SigD sd) = ppr sd ppr (RuleD rd) = ppr rd ppr (VectD vect) = ppr vect ppr (WarningD wd) = ppr wd ppr (AnnD ad) = ppr ad ppr (SpliceD dd) = ppr dd ppr (DocD doc) = ppr doc ppr (RoleAnnotD ra) = ppr ra instance OutputableBndr name => Outputable (HsGroup name) where ppr (HsGroup { hs_valds = val_decls, hs_tyclds = tycl_decls, hs_instds = inst_decls, hs_derivds = deriv_decls, hs_fixds = fix_decls, hs_warnds = deprec_decls, hs_annds = ann_decls, hs_fords = foreign_decls, hs_defds = default_decls, hs_ruleds = rule_decls, hs_vects = vect_decls }) = vcat_mb empty [ppr_ds fix_decls, ppr_ds default_decls, ppr_ds deprec_decls, ppr_ds ann_decls, ppr_ds rule_decls, ppr_ds vect_decls, if isEmptyValBinds val_decls then Nothing else Just (ppr val_decls), ppr_ds (tyClGroupConcat tycl_decls), ppr_ds inst_decls, ppr_ds deriv_decls, ppr_ds foreign_decls] where ppr_ds :: Outputable a => [a] -> Maybe SDoc ppr_ds [] = Nothing ppr_ds ds = Just (vcat (map ppr ds)) vcat_mb :: SDoc -> [Maybe SDoc] -> SDoc -- Concatenate vertically with white-space between non-blanks vcat_mb _ [] = empty vcat_mb gap (Nothing : ds) = vcat_mb gap ds vcat_mb gap (Just d : ds) = gap $$ d $$ vcat_mb blankLine ds data SpliceExplicitFlag = ExplicitSplice | -- <=> $(f x y) ImplicitSplice -- <=> f x y, i.e. a naked top level expression deriving (Data, Typeable) type LSpliceDecl name = Located (SpliceDecl name) data SpliceDecl id = SpliceDecl -- Top level splice (Located (HsSplice id)) SpliceExplicitFlag deriving (Typeable) deriving instance (DataId id) => Data (SpliceDecl id) instance OutputableBndr name => Outputable (SpliceDecl name) where ppr (SpliceDecl (L _ e) _) = pprSplice e {- ************************************************************************ * * \subsection[SynDecl]{@data@, @newtype@ or @type@ (synonym) type declaration} * * ************************************************************************ -------------------------------- THE NAMING STORY -------------------------------- Here is the story about the implicit names that go with type, class, and instance decls. It's a bit tricky, so pay attention! "Implicit" (or "system") binders ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Each data type decl defines a worker name for each constructor to-T and from-T convertors Each class decl defines a tycon for the class a data constructor for that tycon the worker for that constructor a selector for each superclass All have occurrence names that are derived uniquely from their parent declaration. None of these get separate definitions in an interface file; they are fully defined by the data or class decl. But they may *occur* in interface files, of course. Any such occurrence must haul in the relevant type or class decl. Plan of attack: - Ensure they "point to" the parent data/class decl when loading that decl from an interface file (See RnHiFiles.getSysBinders) - When typechecking the decl, we build the implicit TyCons and Ids. When doing so we look them up in the name cache (RnEnv.lookupSysName), to ensure correct module and provenance is set These are the two places that we have to conjure up the magic derived names. (The actual magic is in OccName.mkWorkerOcc, etc.) Default methods ~~~~~~~~~~~~~~~ - Occurrence name is derived uniquely from the method name E.g. $dmmax - If there is a default method name at all, it's recorded in the ClassOpSig (in HsBinds), in the DefMeth field. (DefMeth is defined in Class.hs) Source-code class decls and interface-code class decls are treated subtly differently, which has given me a great deal of confusion over the years. Here's the deal. (We distinguish the two cases because source-code decls have (Just binds) in the tcdMeths field, whereas interface decls have Nothing. In *source-code* class declarations: - When parsing, every ClassOpSig gets a DefMeth with a suitable RdrName This is done by RdrHsSyn.mkClassOpSigDM - The renamer renames it to a Name - During typechecking, we generate a binding for each $dm for which there's a programmer-supplied default method: class Foo a where op1 :: <type> op2 :: <type> op1 = ... We generate a binding for $dmop1 but not for $dmop2. The Class for Foo has a NoDefMeth for op2 and a DefMeth for op1. The Name for $dmop2 is simply discarded. In *interface-file* class declarations: - When parsing, we see if there's an explicit programmer-supplied default method because there's an '=' sign to indicate it: class Foo a where op1 = :: <type> -- NB the '=' op2 :: <type> We use this info to generate a DefMeth with a suitable RdrName for op1, and a NoDefMeth for op2 - The interface file has a separate definition for $dmop1, with unfolding etc. - The renamer renames it to a Name. - The renamer treats $dmop1 as a free variable of the declaration, so that the binding for $dmop1 will be sucked in. (See RnHsSyn.tyClDeclFVs) This doesn't happen for source code class decls, because they *bind* the default method. Dictionary functions ~~~~~~~~~~~~~~~~~~~~ Each instance declaration gives rise to one dictionary function binding. The type checker makes up new source-code instance declarations (e.g. from 'deriving' or generic default methods --- see TcInstDcls.tcInstDecls1). So we can't generate the names for dictionary functions in advance (we don't know how many we need). On the other hand for interface-file instance declarations, the decl specifies the name of the dictionary function, and it has a binding elsewhere in the interface file: instance {Eq Int} = dEqInt dEqInt :: {Eq Int} <pragma info> So again we treat source code and interface file code slightly differently. Source code: - Source code instance decls have a Nothing in the (Maybe name) field (see data InstDecl below) - The typechecker makes up a Local name for the dict fun for any source-code instance decl, whether it comes from a source-code instance decl, or whether the instance decl is derived from some other construct (e.g. 'deriving'). - The occurrence name it chooses is derived from the instance decl (just for documentation really) --- e.g. dNumInt. Two dict funs may share a common occurrence name, but will have different uniques. E.g. instance Foo [Int] where ... instance Foo [Bool] where ... These might both be dFooList - The CoreTidy phase externalises the name, and ensures the occurrence name is unique (this isn't special to dict funs). So we'd get dFooList and dFooList1. - We can take this relaxed approach (changing the occurrence name later) because dict fun Ids are not captured in a TyCon or Class (unlike default methods, say). Instead, they are kept separately in the InstEnv. This makes it easy to adjust them after compiling a module. (Once we've finished compiling that module, they don't change any more.) Interface file code: - The instance decl gives the dict fun name, so the InstDecl has a (Just name) in the (Maybe name) field. - RnHsSyn.instDeclFVs treats the dict fun name as free in the decl, so that we suck in the dfun binding -} type LTyClDecl name = Located (TyClDecl name) -- | A type or class declaration. data TyClDecl name = -- | @type/data family T :: *->*@ -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType', -- 'ApiAnnotation.AnnData', -- 'ApiAnnotation.AnnFamily','ApiAnnotation.AnnDcolon', -- 'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpenP', -- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnCloseP', -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnRarrow', -- 'ApiAnnotation.AnnVbar' -- For details on above see note [Api annotations] in ApiAnnotation FamDecl { tcdFam :: FamilyDecl name } | -- | @type@ declaration -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType', -- 'ApiAnnotation.AnnEqual', -- For details on above see note [Api annotations] in ApiAnnotation SynDecl { tcdLName :: Located name -- ^ Type constructor , tcdTyVars :: LHsTyVarBndrs name -- ^ Type variables; for an associated type -- these include outer binders , tcdRhs :: LHsType name -- ^ RHS of type declaration , tcdFVs :: PostRn name NameSet } | -- | @data@ declaration -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnData', -- 'ApiAnnotation.AnnFamily', -- 'ApiAnnotation.AnnNewType', -- 'ApiAnnotation.AnnNewType','ApiAnnotation.AnnDcolon' -- 'ApiAnnotation.AnnWhere', -- For details on above see note [Api annotations] in ApiAnnotation DataDecl { tcdLName :: Located name -- ^ Type constructor , tcdTyVars :: LHsTyVarBndrs name -- ^ Type variables; for an associated type -- these include outer binders -- Eg class T a where -- type F a :: * -- type F a = a -> a -- Here the type decl for 'f' includes 'a' -- in its tcdTyVars , tcdDataDefn :: HsDataDefn name , tcdFVs :: PostRn name NameSet } | ClassDecl { tcdCtxt :: LHsContext name, -- ^ Context... tcdLName :: Located name, -- ^ Name of the class tcdTyVars :: LHsTyVarBndrs name, -- ^ Class type variables tcdFDs :: [Located (FunDep (Located name))], -- ^ Functional deps tcdSigs :: [LSig name], -- ^ Methods' signatures tcdMeths :: LHsBinds name, -- ^ Default methods tcdATs :: [LFamilyDecl name], -- ^ Associated types; tcdATDefs :: [LTyFamDefltEqn name], -- ^ Associated type defaults tcdDocs :: [LDocDecl], -- ^ Haddock docs tcdFVs :: PostRn name NameSet } -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnClass', -- 'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- - The tcdFDs will have 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnComma' -- 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId id) => Data (TyClDecl id) -- This is used in TcTyClsDecls to represent -- strongly connected components of decls -- No familiy instances in here -- The role annotations must be grouped with their decls for the -- type-checker to infer roles correctly data TyClGroup name = TyClGroup { group_tyclds :: [LTyClDecl name] , group_roles :: [LRoleAnnotDecl name] } deriving (Typeable) deriving instance (DataId id) => Data (TyClGroup id) tyClGroupConcat :: [TyClGroup name] -> [LTyClDecl name] tyClGroupConcat = concatMap group_tyclds mkTyClGroup :: [LTyClDecl name] -> TyClGroup name mkTyClGroup decls = TyClGroup { group_tyclds = decls, group_roles = [] } -- Simple classifiers for TyClDecl -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- | @True@ <=> argument is a @data@\/@newtype@ -- declaration. isDataDecl :: TyClDecl name -> Bool isDataDecl (DataDecl {}) = True isDataDecl _other = False -- | type or type instance declaration isSynDecl :: TyClDecl name -> Bool isSynDecl (SynDecl {}) = True isSynDecl _other = False -- | type class isClassDecl :: TyClDecl name -> Bool isClassDecl (ClassDecl {}) = True isClassDecl _ = False -- | type/data family declaration isFamilyDecl :: TyClDecl name -> Bool isFamilyDecl (FamDecl {}) = True isFamilyDecl _other = False -- | type family declaration isTypeFamilyDecl :: TyClDecl name -> Bool isTypeFamilyDecl (FamDecl (FamilyDecl { fdInfo = info })) = case info of OpenTypeFamily -> True ClosedTypeFamily {} -> True _ -> False isTypeFamilyDecl _ = False -- | open type family info isOpenTypeFamilyInfo :: FamilyInfo name -> Bool isOpenTypeFamilyInfo OpenTypeFamily = True isOpenTypeFamilyInfo _ = False -- | closed type family info isClosedTypeFamilyInfo :: FamilyInfo name -> Bool isClosedTypeFamilyInfo (ClosedTypeFamily {}) = True isClosedTypeFamilyInfo _ = False -- | data family declaration isDataFamilyDecl :: TyClDecl name -> Bool isDataFamilyDecl (FamDecl (FamilyDecl { fdInfo = DataFamily })) = True isDataFamilyDecl _other = False -- Dealing with names tyFamInstDeclName :: TyFamInstDecl name -> name tyFamInstDeclName = unLoc . tyFamInstDeclLName tyFamInstDeclLName :: TyFamInstDecl name -> Located name tyFamInstDeclLName (TyFamInstDecl { tfid_eqn = (L _ (TyFamEqn { tfe_tycon = ln })) }) = ln tyClDeclLName :: TyClDecl name -> Located name tyClDeclLName (FamDecl { tcdFam = FamilyDecl { fdLName = ln } }) = ln tyClDeclLName decl = tcdLName decl tcdName :: TyClDecl name -> name tcdName = unLoc . tyClDeclLName tyClDeclTyVars :: TyClDecl name -> LHsTyVarBndrs name tyClDeclTyVars (FamDecl { tcdFam = FamilyDecl { fdTyVars = tvs } }) = tvs tyClDeclTyVars d = tcdTyVars d countTyClDecls :: [TyClDecl name] -> (Int, Int, Int, Int, Int) -- class, synonym decls, data, newtype, family decls countTyClDecls decls = (count isClassDecl decls, count isSynDecl decls, -- excluding... count isDataTy decls, -- ...family... count isNewTy decls, -- ...instances count isFamilyDecl decls) where isDataTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = DataType } } = True isDataTy _ = False isNewTy DataDecl{ tcdDataDefn = HsDataDefn { dd_ND = NewType } } = True isNewTy _ = False -- | Does this declaration have a complete, user-supplied kind signature? -- See Note [Complete user-supplied kind signatures] hsDeclHasCusk :: TyClDecl name -> Bool hsDeclHasCusk (FamDecl { tcdFam = fam_decl }) = famDeclHasCusk fam_decl hsDeclHasCusk (SynDecl { tcdTyVars = tyvars, tcdRhs = rhs }) = hsTvbAllKinded tyvars && rhs_annotated rhs where rhs_annotated (L _ ty) = case ty of HsParTy lty -> rhs_annotated lty HsKindSig {} -> True _ -> False hsDeclHasCusk (DataDecl { tcdTyVars = tyvars }) = hsTvbAllKinded tyvars hsDeclHasCusk (ClassDecl { tcdTyVars = tyvars }) = hsTvbAllKinded tyvars -- Pretty-printing TyClDecl -- ~~~~~~~~~~~~~~~~~~~~~~~~ instance OutputableBndr name => Outputable (TyClDecl name) where ppr (FamDecl { tcdFam = decl }) = ppr decl ppr (SynDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdRhs = rhs }) = hang (ptext (sLit "type") <+> pp_vanilla_decl_head ltycon tyvars [] <+> equals) 4 (ppr rhs) ppr (DataDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdDataDefn = defn }) = pp_data_defn (pp_vanilla_decl_head ltycon tyvars) defn ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars, tcdFDs = fds, tcdSigs = sigs, tcdMeths = methods, tcdATs = ats, tcdATDefs = at_defs}) | null sigs && isEmptyBag methods && null ats && null at_defs -- No "where" part = top_matter | otherwise -- Laid out = vcat [ top_matter <+> ptext (sLit "where") , nest 2 $ pprDeclList (map (pprFamilyDecl NotTopLevel . unLoc) ats ++ map ppr_fam_deflt_eqn at_defs ++ pprLHsBindsForUser methods sigs) ] where top_matter = ptext (sLit "class") <+> pp_vanilla_decl_head lclas tyvars (unLoc context) <+> pprFundeps (map unLoc fds) instance OutputableBndr name => Outputable (TyClGroup name) where ppr (TyClGroup { group_tyclds = tyclds, group_roles = roles }) = ppr tyclds $$ ppr roles pp_vanilla_decl_head :: OutputableBndr name => Located name -> LHsTyVarBndrs name -> HsContext name -> SDoc pp_vanilla_decl_head thing tyvars context = hsep [pprHsContext context, pprPrefixOcc (unLoc thing), ppr tyvars] pprTyClDeclFlavour :: TyClDecl a -> SDoc pprTyClDeclFlavour (ClassDecl {}) = ptext (sLit "class") pprTyClDeclFlavour (SynDecl {}) = ptext (sLit "type") pprTyClDeclFlavour (FamDecl { tcdFam = FamilyDecl { fdInfo = info }}) = pprFlavour info <+> text "family" pprTyClDeclFlavour (DataDecl { tcdDataDefn = HsDataDefn { dd_ND = nd } }) = ppr nd {- ********************************************************************* * * Data and type family declarations * * ********************************************************************* -} -- Note [FamilyResultSig] -- ~~~~~~~~~~~~~~~~~~~~~~ -- -- This data type represents the return signature of a type family. Possible -- values are: -- -- * NoSig - the user supplied no return signature: -- type family Id a where ... -- -- * KindSig - the user supplied the return kind: -- type family Id a :: * where ... -- -- * TyVarSig - user named the result with a type variable and possibly -- provided a kind signature for that variable: -- type family Id a = r where ... -- type family Id a = (r :: *) where ... -- -- Naming result of a type family is required if we want to provide -- injectivity annotation for a type family: -- type family Id a = r | r -> a where ... -- -- See also: Note [Injectivity annotation] -- Note [Injectivity annotation] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- A user can declare a type family to be injective: -- -- type family Id a = r | r -> a where ... -- -- * The part after the "|" is called "injectivity annotation". -- * "r -> a" part is called "injectivity condition"; at the moment terms -- "injectivity annotation" and "injectivity condition" are synonymous -- because we only allow a single injectivity condition. -- * "r" is the "LHS of injectivity condition". LHS can only contain the -- variable naming the result of a type family. -- * "a" is the "RHS of injectivity condition". RHS contains space-separated -- type and kind variables representing the arguments of a type -- family. Variables can be omitted if a type family is not injective in -- these arguments. Example: -- type family Foo a b c = d | d -> a c where ... -- -- Note that: -- a) naming of type family result is required to provide injectivity -- annotation -- b) for associated types if the result was named then injectivity annotation -- is mandatory. Otherwise result type variable is indistinguishable from -- associated type default. -- -- It is possible that in the future this syntax will be extended to support -- more complicated injectivity annotations. For example we could declare that -- if we know the result of Plus and one of its arguments we can determine the -- other argument: -- -- type family Plus a b = (r :: Nat) | r a -> b, r b -> a where ... -- -- Here injectivity annotation would consist of two comma-separated injectivity -- conditions. -- -- See also Note [Injective type families] in TyCon type LFamilyResultSig name = Located (FamilyResultSig name) data FamilyResultSig name = -- see Note [FamilyResultSig] NoSig -- ^ - 'ApiAnnotation.AnnKeywordId' : -- For details on above see note [Api annotations] in ApiAnnotation | KindSig (LHsKind name) -- ^ - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnOpenP','ApiAnnotation.AnnDcolon', -- 'ApiAnnotation.AnnCloseP' -- For details on above see note [Api annotations] in ApiAnnotation | TyVarSig (LHsTyVarBndr name) -- ^ - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnOpenP','ApiAnnotation.AnnDcolon', -- 'ApiAnnotation.AnnCloseP', 'ApiAnnotation.AnnEqual' -- For details on above see note [Api annotations] in ApiAnnotation deriving ( Typeable ) deriving instance (DataId name) => Data (FamilyResultSig name) type LFamilyDecl name = Located (FamilyDecl name) data FamilyDecl name = FamilyDecl { fdInfo :: FamilyInfo name -- type/data, closed/open , fdLName :: Located name -- type constructor , fdTyVars :: LHsTyVarBndrs name -- type variables , fdResultSig :: LFamilyResultSig name -- result signature , fdInjectivityAnn :: Maybe (LInjectivityAnn name) -- optional injectivity ann } -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType', -- 'ApiAnnotation.AnnData', 'ApiAnnotation.AnnFamily', -- 'ApiAnnotation.AnnWhere', 'ApiAnnotation.AnnOpenP', -- 'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnCloseP', -- 'ApiAnnotation.AnnEqual', 'ApiAnnotation.AnnRarrow', -- 'ApiAnnotation.AnnVbar' -- For details on above see note [Api annotations] in ApiAnnotation deriving ( Typeable ) deriving instance (DataId id) => Data (FamilyDecl id) type LInjectivityAnn name = Located (InjectivityAnn name) -- | If the user supplied an injectivity annotation it is represented using -- InjectivityAnn. At the moment this is a single injectivity condition - see -- Note [Injectivity annotation]. `Located name` stores the LHS of injectivity -- condition. `[Located name]` stores the RHS of injectivity condition. Example: -- -- type family Foo a b c = r | r -> a c where ... -- -- This will be represented as "InjectivityAnn `r` [`a`, `c`]" data InjectivityAnn name = InjectivityAnn (Located name) [Located name] -- ^ - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnRarrow', 'ApiAnnotation.AnnVbar' -- For details on above see note [Api annotations] in ApiAnnotation deriving ( Data, Typeable ) data FamilyInfo name = DataFamily | OpenTypeFamily -- | 'Nothing' if we're in an hs-boot file and the user -- said "type family Foo x where .." | ClosedTypeFamily (Maybe [LTyFamInstEqn name]) deriving( Typeable ) deriving instance (DataId name) => Data (FamilyInfo name) -- | Does this family declaration have a complete, user-supplied kind signature? famDeclHasCusk :: FamilyDecl name -> Bool famDeclHasCusk (FamilyDecl { fdInfo = ClosedTypeFamily _ , fdTyVars = tyvars , fdResultSig = L _ resultSig }) = hsTvbAllKinded tyvars && hasReturnKindSignature resultSig famDeclHasCusk _ = True -- all open families have CUSKs! -- | Does this family declaration have user-supplied return kind signature? hasReturnKindSignature :: FamilyResultSig a -> Bool hasReturnKindSignature NoSig = False hasReturnKindSignature (TyVarSig (L _ (UserTyVar _))) = False hasReturnKindSignature _ = True -- | Maybe return name of the result type variable resultVariableName :: FamilyResultSig a -> Maybe a resultVariableName (TyVarSig sig) = Just $ hsLTyVarName sig resultVariableName _ = Nothing {- Note [Complete user-supplied kind signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We kind-check declarations differently if they have a complete, user-supplied kind signature (CUSK). This is because we can safely generalise a CUSKed declaration before checking all of the others, supporting polymorphic recursion. See ghc.haskell.org/trac/ghc/wiki/GhcKinds/KindInference#Proposednewstrategy and #9200 for lots of discussion of how we got here. A declaration has a CUSK if we can know its complete kind without doing any inference, at all. Here are the rules: - A class or datatype is said to have a CUSK if and only if all of its type variables are annotated. Its result kind is, by construction, Constraint or * respectively. - A type synonym has a CUSK if and only if all of its type variables and its RHS are annotated with kinds. - A closed type family is said to have a CUSK if and only if all of its type variables and its return type are annotated. - An open type family always has a CUSK -- unannotated type variables (and return type) default to *. -} instance (OutputableBndr name) => Outputable (FamilyDecl name) where ppr = pprFamilyDecl TopLevel pprFamilyDecl :: OutputableBndr name => TopLevelFlag -> FamilyDecl name -> SDoc pprFamilyDecl top_level (FamilyDecl { fdInfo = info, fdLName = ltycon , fdTyVars = tyvars , fdResultSig = L _ result , fdInjectivityAnn = mb_inj }) = vcat [ pprFlavour info <+> pp_top_level <+> pp_vanilla_decl_head ltycon tyvars [] <+> pp_kind <+> pp_inj <+> pp_where , nest 2 $ pp_eqns ] where pp_top_level = case top_level of TopLevel -> text "family" NotTopLevel -> empty pp_kind = case result of NoSig -> empty KindSig kind -> dcolon <+> ppr kind TyVarSig tv_bndr -> text "=" <+> ppr tv_bndr pp_inj = case mb_inj of Just (L _ (InjectivityAnn lhs rhs)) -> hsep [ text "|", ppr lhs, text "->", hsep (map ppr rhs) ] Nothing -> empty (pp_where, pp_eqns) = case info of ClosedTypeFamily mb_eqns -> ( ptext (sLit "where") , case mb_eqns of Nothing -> ptext (sLit "..") Just eqns -> vcat $ map ppr_fam_inst_eqn eqns ) _ -> (empty, empty) pprFlavour :: FamilyInfo name -> SDoc pprFlavour DataFamily = ptext (sLit "data") pprFlavour OpenTypeFamily = ptext (sLit "type") pprFlavour (ClosedTypeFamily {}) = ptext (sLit "type") instance Outputable (FamilyInfo name) where ppr info = pprFlavour info <+> text "family" {- ********************************************************************* * * Data types and data constructors * * ********************************************************************* -} data HsDataDefn name -- The payload of a data type defn -- Used *both* for vanilla data declarations, -- *and* for data family instances = -- | Declares a data type or newtype, giving its constructors -- @ -- data/newtype T a = <constrs> -- data/newtype instance T [a] = <constrs> -- @ HsDataDefn { dd_ND :: NewOrData, dd_ctxt :: LHsContext name, -- ^ Context dd_cType :: Maybe (Located CType), dd_kindSig:: Maybe (LHsKind name), -- ^ Optional kind signature. -- -- @(Just k)@ for a GADT-style @data@, -- or @data instance@ decl, with explicit kind sig -- -- Always @Nothing@ for H98-syntax decls dd_cons :: [LConDecl name], -- ^ Data constructors -- -- For @data T a = T1 | T2 a@ -- the 'LConDecl's all have 'ResTyH98'. -- For @data T a where { T1 :: T a }@ -- the 'LConDecls' all have 'ResTyGADT'. dd_derivs :: Maybe (Located [LHsType name]) -- ^ Derivings; @Nothing@ => not specified, -- @Just []@ => derive exactly what is asked -- -- These "types" must be of form -- @ -- forall ab. C ty1 ty2 -- @ -- Typically the foralls and ty args are empty, but they -- are non-empty for the newtype-deriving case -- -- - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnDeriving', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation } deriving( Typeable ) deriving instance (DataId id) => Data (HsDataDefn id) data NewOrData = NewType -- ^ @newtype Blah ...@ | DataType -- ^ @data Blah ...@ deriving( Eq, Data, Typeable ) -- Needed because Demand derives Eq type LConDecl name = Located (ConDecl name) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when -- in a GADT constructor list -- For details on above see note [Api annotations] in ApiAnnotation -- | -- -- @ -- data T b = forall a. Eq a => MkT a b -- MkT :: forall b a. Eq a => MkT a b -- -- data T b where -- MkT1 :: Int -> T Int -- -- data T = Int `MkT` Int -- | MkT2 -- -- data T a where -- Int `MkT` Int :: T Int -- @ -- -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnCLose', -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnDarrow','ApiAnnotation.AnnDarrow', -- 'ApiAnnotation.AnnForall','ApiAnnotation.AnnDot' -- For details on above see note [Api annotations] in ApiAnnotation data ConDecl name = ConDecl { con_names :: [Located name] -- ^ Constructor names. This is used for the DataCon itself, and for -- the user-callable wrapper Id. -- It is a list to deal with GADT constructors of the form -- T1, T2, T3 :: <payload> , con_explicit :: HsExplicitFlag -- ^ Is there an user-written forall? (cf. 'HsTypes.HsForAllTy') , con_qvars :: LHsTyVarBndrs name -- ^ Type variables. Depending on 'con_res' this describes the -- following entities -- -- - ResTyH98: the constructor's *existential* type variables -- - ResTyGADT: *all* the constructor's quantified type variables -- -- If con_explicit is Implicit, then con_qvars is irrelevant -- until after renaming. , con_cxt :: LHsContext name -- ^ The context. This /does not/ include the \"stupid theta\" which -- lives only in the 'TyData' decl. , con_details :: HsConDeclDetails name -- ^ The main payload , con_res :: ResType (LHsType name) -- ^ Result type of the constructor , con_doc :: Maybe LHsDocString -- ^ A possible Haddock comment. , con_old_rec :: Bool -- ^ TEMPORARY field; True <=> user has employed now-deprecated syntax for -- GADT-style record decl C { blah } :: T a b -- Remove this when we no longer parse this stuff, and hence do not -- need to report decprecated use } deriving (Typeable) deriving instance (DataId name) => Data (ConDecl name) type HsConDeclDetails name = HsConDetails (LBangType name) (Located [LConDeclField name]) hsConDeclArgTys :: HsConDeclDetails name -> [LBangType name] hsConDeclArgTys (PrefixCon tys) = tys hsConDeclArgTys (InfixCon ty1 ty2) = [ty1,ty2] hsConDeclArgTys (RecCon flds) = map (cd_fld_type . unLoc) (unLoc flds) data ResType ty = ResTyH98 -- Constructor was declared using Haskell 98 syntax | ResTyGADT SrcSpan ty -- Constructor was declared using GADT-style syntax, -- and here is its result type, and the SrcSpan -- of the original sigtype, for API Annotations deriving (Data, Typeable) instance Outputable ty => Outputable (ResType ty) where -- Debugging only ppr ResTyH98 = ptext (sLit "ResTyH98") ppr (ResTyGADT _ ty) = ptext (sLit "ResTyGADT") <+> ppr ty pp_data_defn :: OutputableBndr name => (HsContext name -> SDoc) -- Printing the header -> HsDataDefn name -> SDoc pp_data_defn pp_hdr (HsDataDefn { dd_ND = new_or_data, dd_ctxt = L _ context , dd_kindSig = mb_sig , dd_cons = condecls, dd_derivs = derivings }) | null condecls = ppr new_or_data <+> pp_hdr context <+> pp_sig | otherwise = hang (ppr new_or_data <+> pp_hdr context <+> pp_sig) 2 (pp_condecls condecls $$ pp_derivings) where pp_sig = case mb_sig of Nothing -> empty Just kind -> dcolon <+> ppr kind pp_derivings = case derivings of Nothing -> empty Just (L _ ds) -> hsep [ptext (sLit "deriving"), parens (interpp'SP ds)] instance OutputableBndr name => Outputable (HsDataDefn name) where ppr d = pp_data_defn (\_ -> ptext (sLit "Naked HsDataDefn")) d instance Outputable NewOrData where ppr NewType = ptext (sLit "newtype") ppr DataType = ptext (sLit "data") pp_condecls :: OutputableBndr name => [LConDecl name] -> SDoc pp_condecls cs@(L _ ConDecl{ con_res = ResTyGADT _ _ } : _) -- In GADT syntax = hang (ptext (sLit "where")) 2 (vcat (map ppr cs)) pp_condecls cs -- In H98 syntax = equals <+> sep (punctuate (ptext (sLit " |")) (map ppr cs)) instance (OutputableBndr name) => Outputable (ConDecl name) where ppr = pprConDecl pprConDecl :: OutputableBndr name => ConDecl name -> SDoc pprConDecl (ConDecl { con_names = [L _ con] -- NB: non-GADT means 1 con , con_explicit = expl, con_qvars = tvs , con_cxt = cxt, con_details = details , con_res = ResTyH98, con_doc = doc }) = sep [ppr_mbDoc doc, pprHsForAll expl tvs cxt, ppr_details details] where ppr_details (InfixCon t1 t2) = hsep [ppr t1, pprInfixOcc con, ppr t2] ppr_details (PrefixCon tys) = hsep (pprPrefixOcc con : map (pprParendHsType . unLoc) tys) ppr_details (RecCon fields) = pprPrefixOcc con <+> pprConDeclFields (unLoc fields) pprConDecl (ConDecl { con_names = cons, con_explicit = expl, con_qvars = tvs , con_cxt = cxt, con_details = PrefixCon arg_tys , con_res = ResTyGADT _ res_ty, con_doc = doc }) = ppr_mbDoc doc <+> ppr_con_names cons <+> dcolon <+> sep [pprHsForAll expl tvs cxt, ppr (foldr mk_fun_ty res_ty arg_tys)] where mk_fun_ty a b = noLoc (HsFunTy a b) pprConDecl (ConDecl { con_names = cons, con_explicit = expl, con_qvars = tvs , con_cxt = cxt, con_details = RecCon fields , con_res = ResTyGADT _ res_ty, con_doc = doc }) = sep [ppr_mbDoc doc <+> ppr_con_names cons <+> dcolon <+> pprHsForAll expl tvs cxt, pprConDeclFields (unLoc fields) <+> arrow <+> ppr res_ty] pprConDecl decl@(ConDecl { con_details = InfixCon ty1 ty2, con_res = ResTyGADT {} }) = pprConDecl (decl { con_details = PrefixCon [ty1,ty2] }) -- In GADT syntax we don't allow infix constructors -- so if we ever trip over one (albeit I can't see how that -- can happen) print it like a prefix one -- this fallthrough would happen with a non-GADT-syntax ConDecl with more -- than one constructor, which should indeed be impossible pprConDecl (ConDecl { con_names = cons }) = pprPanic "pprConDecl" (ppr cons) ppr_con_names :: (OutputableBndr name) => [Located name] -> SDoc ppr_con_names = pprWithCommas (pprPrefixOcc . unLoc) {- ************************************************************************ * * Instance declarations * * ************************************************************************ Note [Type family instance declarations in HsSyn] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The data type TyFamEqn represents one equation of a type family instance. It is parameterised over its tfe_pats field: * An ordinary type family instance declaration looks like this in source Haskell type instance T [a] Int = a -> a (or something similar for a closed family) It is represented by a TyFamInstEqn, with *type* in the tfe_pats field. * On the other hand, the *default instance* of an associated type looks like this in source Haskell class C a where type T a b type T a b = a -> b -- The default instance It is represented by a TyFamDefltEqn, with *type variables* in the tfe_pats field. -} ----------------- Type synonym family instances ------------- type LTyFamInstEqn name = Located (TyFamInstEqn name) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' -- when in a list -- For details on above see note [Api annotations] in ApiAnnotation type LTyFamDefltEqn name = Located (TyFamDefltEqn name) type HsTyPats name = HsWithBndrs name [LHsType name] -- ^ Type patterns (with kind and type bndrs) -- See Note [Family instance declaration binders] type TyFamInstEqn name = TyFamEqn name (HsTyPats name) type TyFamDefltEqn name = TyFamEqn name (LHsTyVarBndrs name) -- See Note [Type family instance declarations in HsSyn] -- | One equation in a type family instance declaration -- See Note [Type family instance declarations in HsSyn] data TyFamEqn name pats = TyFamEqn { tfe_tycon :: Located name , tfe_pats :: pats , tfe_rhs :: LHsType name } -- ^ -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual' -- For details on above see note [Api annotations] in ApiAnnotation deriving( Typeable ) deriving instance (DataId name, Data pats) => Data (TyFamEqn name pats) type LTyFamInstDecl name = Located (TyFamInstDecl name) data TyFamInstDecl name = TyFamInstDecl { tfid_eqn :: LTyFamInstEqn name , tfid_fvs :: PostRn name NameSet } -- ^ -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType', -- 'ApiAnnotation.AnnInstance', -- For details on above see note [Api annotations] in ApiAnnotation deriving( Typeable ) deriving instance (DataId name) => Data (TyFamInstDecl name) ----------------- Data family instances ------------- type LDataFamInstDecl name = Located (DataFamInstDecl name) data DataFamInstDecl name = DataFamInstDecl { dfid_tycon :: Located name , dfid_pats :: HsTyPats name -- LHS , dfid_defn :: HsDataDefn name -- RHS , dfid_fvs :: PostRn name NameSet } -- Free vars for dependency analysis -- ^ -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnData', -- 'ApiAnnotation.AnnNewType','ApiAnnotation.AnnInstance', -- 'ApiAnnotation.AnnDcolon' -- 'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation deriving( Typeable ) deriving instance (DataId name) => Data (DataFamInstDecl name) ----------------- Class instances ------------- type LClsInstDecl name = Located (ClsInstDecl name) data ClsInstDecl name = ClsInstDecl { cid_poly_ty :: LHsType name -- Context => Class Instance-type -- Using a polytype means that the renamer conveniently -- figures out the quantified type variables for us. , cid_binds :: LHsBinds name -- Class methods , cid_sigs :: [LSig name] -- User-supplied pragmatic info , cid_tyfam_insts :: [LTyFamInstDecl name] -- Type family instances , cid_datafam_insts :: [LDataFamInstDecl name] -- Data family instances , cid_overlap_mode :: Maybe (Located OverlapMode) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation } -- ^ -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnInstance', -- 'ApiAnnotation.AnnWhere', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId id) => Data (ClsInstDecl id) ----------------- Instances of all kinds ------------- type LInstDecl name = Located (InstDecl name) data InstDecl name -- Both class and family instances = ClsInstD { cid_inst :: ClsInstDecl name } | DataFamInstD -- data family instance { dfid_inst :: DataFamInstDecl name } | TyFamInstD -- type family instance { tfid_inst :: TyFamInstDecl name } deriving (Typeable) deriving instance (DataId id) => Data (InstDecl id) {- Note [Family instance declaration binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A {Ty|Data}FamInstDecl is a data/type family instance declaration the pats field is LHS patterns, and the tvs of the HsBSig tvs are fv(pat_tys), *including* ones that are already in scope Eg class C s t where type F t p :: * instance C w (a,b) where type F (a,b) x = x->a The tcdTyVars of the F decl are {a,b,x}, even though the F decl is nested inside the 'instance' decl. However after the renamer, the uniques will match up: instance C w7 (a8,b9) where type F (a8,b9) x10 = x10->a8 so that we can compare the type patter in the 'instance' decl and in the associated 'type' decl -} instance (OutputableBndr name) => Outputable (TyFamInstDecl name) where ppr = pprTyFamInstDecl TopLevel pprTyFamInstDecl :: OutputableBndr name => TopLevelFlag -> TyFamInstDecl name -> SDoc pprTyFamInstDecl top_lvl (TyFamInstDecl { tfid_eqn = eqn }) = ptext (sLit "type") <+> ppr_instance_keyword top_lvl <+> ppr_fam_inst_eqn eqn ppr_instance_keyword :: TopLevelFlag -> SDoc ppr_instance_keyword TopLevel = ptext (sLit "instance") ppr_instance_keyword NotTopLevel = empty ppr_fam_inst_eqn :: OutputableBndr name => LTyFamInstEqn name -> SDoc ppr_fam_inst_eqn (L _ (TyFamEqn { tfe_tycon = tycon , tfe_pats = pats , tfe_rhs = rhs })) = pp_fam_inst_lhs tycon pats [] <+> equals <+> ppr rhs ppr_fam_deflt_eqn :: OutputableBndr name => LTyFamDefltEqn name -> SDoc ppr_fam_deflt_eqn (L _ (TyFamEqn { tfe_tycon = tycon , tfe_pats = tvs , tfe_rhs = rhs })) = text "type" <+> pp_vanilla_decl_head tycon tvs [] <+> equals <+> ppr rhs instance (OutputableBndr name) => Outputable (DataFamInstDecl name) where ppr = pprDataFamInstDecl TopLevel pprDataFamInstDecl :: OutputableBndr name => TopLevelFlag -> DataFamInstDecl name -> SDoc pprDataFamInstDecl top_lvl (DataFamInstDecl { dfid_tycon = tycon , dfid_pats = pats , dfid_defn = defn }) = pp_data_defn pp_hdr defn where pp_hdr ctxt = ppr_instance_keyword top_lvl <+> pp_fam_inst_lhs tycon pats ctxt pprDataFamInstFlavour :: DataFamInstDecl name -> SDoc pprDataFamInstFlavour (DataFamInstDecl { dfid_defn = (HsDataDefn { dd_ND = nd }) }) = ppr nd pp_fam_inst_lhs :: OutputableBndr name => Located name -> HsTyPats name -> HsContext name -> SDoc pp_fam_inst_lhs thing (HsWB { hswb_cts = typats }) context -- explicit type patterns = hsep [ pprHsContext context, pprPrefixOcc (unLoc thing) , hsep (map (pprParendHsType.unLoc) typats)] instance (OutputableBndr name) => Outputable (ClsInstDecl name) where ppr (ClsInstDecl { cid_poly_ty = inst_ty, cid_binds = binds , cid_sigs = sigs, cid_tyfam_insts = ats , cid_overlap_mode = mbOverlap , cid_datafam_insts = adts }) | null sigs, null ats, null adts, isEmptyBag binds -- No "where" part = top_matter | otherwise -- Laid out = vcat [ top_matter <+> ptext (sLit "where") , nest 2 $ pprDeclList $ map (pprTyFamInstDecl NotTopLevel . unLoc) ats ++ map (pprDataFamInstDecl NotTopLevel . unLoc) adts ++ pprLHsBindsForUser binds sigs ] where top_matter = ptext (sLit "instance") <+> ppOverlapPragma mbOverlap <+> ppr inst_ty ppOverlapPragma :: Maybe (Located OverlapMode) -> SDoc ppOverlapPragma mb = case mb of Nothing -> empty Just (L _ (NoOverlap _)) -> ptext (sLit "{-# NO_OVERLAP #-}") Just (L _ (Overlappable _)) -> ptext (sLit "{-# OVERLAPPABLE #-}") Just (L _ (Overlapping _)) -> ptext (sLit "{-# OVERLAPPING #-}") Just (L _ (Overlaps _)) -> ptext (sLit "{-# OVERLAPS #-}") Just (L _ (Incoherent _)) -> ptext (sLit "{-# INCOHERENT #-}") instance (OutputableBndr name) => Outputable (InstDecl name) where ppr (ClsInstD { cid_inst = decl }) = ppr decl ppr (TyFamInstD { tfid_inst = decl }) = ppr decl ppr (DataFamInstD { dfid_inst = decl }) = ppr decl -- Extract the declarations of associated data types from an instance instDeclDataFamInsts :: [LInstDecl name] -> [DataFamInstDecl name] instDeclDataFamInsts inst_decls = concatMap do_one inst_decls where do_one (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = fam_insts } })) = map unLoc fam_insts do_one (L _ (DataFamInstD { dfid_inst = fam_inst })) = [fam_inst] do_one (L _ (TyFamInstD {})) = [] {- ************************************************************************ * * \subsection[DerivDecl]{A stand-alone instance deriving declaration} * * ************************************************************************ -} type LDerivDecl name = Located (DerivDecl name) data DerivDecl name = DerivDecl { deriv_type :: LHsType name , deriv_overlap_mode :: Maybe (Located OverlapMode) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnDeriving', -- 'ApiAnnotation.AnnInstance' -- For details on above see note [Api annotations] in ApiAnnotation } deriving (Typeable) deriving instance (DataId name) => Data (DerivDecl name) instance (OutputableBndr name) => Outputable (DerivDecl name) where ppr (DerivDecl ty o) = hsep [ptext (sLit "deriving instance"), ppOverlapPragma o, ppr ty] {- ************************************************************************ * * \subsection[DefaultDecl]{A @default@ declaration} * * ************************************************************************ There can only be one default declaration per module, but it is hard for the parser to check that; we pass them all through in the abstract syntax, and that restriction must be checked in the front end. -} type LDefaultDecl name = Located (DefaultDecl name) data DefaultDecl name = DefaultDecl [LHsType name] -- ^ - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnDefault', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId name) => Data (DefaultDecl name) instance (OutputableBndr name) => Outputable (DefaultDecl name) where ppr (DefaultDecl tys) = ptext (sLit "default") <+> parens (interpp'SP tys) {- ************************************************************************ * * \subsection{Foreign function interface declaration} * * ************************************************************************ -} -- foreign declarations are distinguished as to whether they define or use a -- Haskell name -- -- * the Boolean value indicates whether the pre-standard deprecated syntax -- has been used -- type LForeignDecl name = Located (ForeignDecl name) data ForeignDecl name = ForeignImport (Located name) -- defines this name (LHsType name) -- sig_ty (PostTc name Coercion) -- rep_ty ~ sig_ty ForeignImport | ForeignExport (Located name) -- uses this name (LHsType name) -- sig_ty (PostTc name Coercion) -- sig_ty ~ rep_ty ForeignExport -- ^ -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForeign', -- 'ApiAnnotation.AnnImport','ApiAnnotation.AnnExport', -- 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId name) => Data (ForeignDecl name) {- In both ForeignImport and ForeignExport: sig_ty is the type given in the Haskell code rep_ty is the representation for this type, i.e. with newtypes coerced away and type functions evaluated. Thus if the declaration is valid, then rep_ty will only use types such as Int and IO that we know how to make foreign calls with. -} noForeignImportCoercionYet :: PlaceHolder noForeignImportCoercionYet = PlaceHolder noForeignExportCoercionYet :: PlaceHolder noForeignExportCoercionYet = PlaceHolder -- Specification Of an imported external entity in dependence on the calling -- convention -- data ForeignImport = -- import of a C entity -- -- * the two strings specifying a header file or library -- may be empty, which indicates the absence of a -- header or object specification (both are not used -- in the case of `CWrapper' and when `CFunction' -- has a dynamic target) -- -- * the calling convention is irrelevant for code -- generation in the case of `CLabel', but is needed -- for pretty printing -- -- * `Safety' is irrelevant for `CLabel' and `CWrapper' -- CImport (Located CCallConv) -- ccall or stdcall (Located Safety) -- interruptible, safe or unsafe (Maybe Header) -- name of C header CImportSpec -- details of the C entity (Located SourceText) -- original source text for -- the C entity deriving (Data, Typeable) -- details of an external C entity -- data CImportSpec = CLabel CLabelString -- import address of a C label | CFunction CCallTarget -- static or dynamic function | CWrapper -- wrapper to expose closures -- (former f.e.d.) deriving (Data, Typeable) -- specification of an externally exported entity in dependence on the calling -- convention -- data ForeignExport = CExport (Located CExportSpec) -- contains the calling -- convention (Located SourceText) -- original source text for -- the C entity deriving (Data, Typeable) -- pretty printing of foreign declarations -- instance OutputableBndr name => Outputable (ForeignDecl name) where ppr (ForeignImport n ty _ fimport) = hang (ptext (sLit "foreign import") <+> ppr fimport <+> ppr n) 2 (dcolon <+> ppr ty) ppr (ForeignExport n ty _ fexport) = hang (ptext (sLit "foreign export") <+> ppr fexport <+> ppr n) 2 (dcolon <+> ppr ty) instance Outputable ForeignImport where ppr (CImport cconv safety mHeader spec _) = ppr cconv <+> ppr safety <+> char '"' <> pprCEntity spec <> char '"' where pp_hdr = case mHeader of Nothing -> empty Just (Header _ header) -> ftext header pprCEntity (CLabel lbl) = ptext (sLit "static") <+> pp_hdr <+> char '&' <> ppr lbl pprCEntity (CFunction (StaticTarget _ lbl _ isFun)) = ptext (sLit "static") <+> pp_hdr <+> (if isFun then empty else ptext (sLit "value")) <+> ppr lbl pprCEntity (CFunction (DynamicTarget)) = ptext (sLit "dynamic") pprCEntity (CWrapper) = ptext (sLit "wrapper") instance Outputable ForeignExport where ppr (CExport (L _ (CExportStatic _ lbl cconv)) _) = ppr cconv <+> char '"' <> ppr lbl <> char '"' {- ************************************************************************ * * \subsection{Transformation rules} * * ************************************************************************ -} type LRuleDecls name = Located (RuleDecls name) -- Note [Pragma source text] in BasicTypes data RuleDecls name = HsRules { rds_src :: SourceText , rds_rules :: [LRuleDecl name] } deriving (Typeable) deriving instance (DataId name) => Data (RuleDecls name) type LRuleDecl name = Located (RuleDecl name) data RuleDecl name = HsRule -- Source rule (Located (SourceText,RuleName)) -- Rule name -- Note [Pragma source text] in BasicTypes Activation [LRuleBndr name] -- Forall'd vars; after typechecking this -- includes tyvars (Located (HsExpr name)) -- LHS (PostRn name NameSet) -- Free-vars from the LHS (Located (HsExpr name)) -- RHS (PostRn name NameSet) -- Free-vars from the RHS -- ^ -- - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnTilde', -- 'ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnForall','ApiAnnotation.AnnDot', -- 'ApiAnnotation.AnnEqual', -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId name) => Data (RuleDecl name) flattenRuleDecls :: [LRuleDecls name] -> [LRuleDecl name] flattenRuleDecls decls = concatMap (rds_rules . unLoc) decls type LRuleBndr name = Located (RuleBndr name) data RuleBndr name = RuleBndr (Located name) | RuleBndrSig (Located name) (HsWithBndrs name (LHsType name)) -- ^ -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId name) => Data (RuleBndr name) collectRuleBndrSigTys :: [RuleBndr name] -> [HsWithBndrs name (LHsType name)] collectRuleBndrSigTys bndrs = [ty | RuleBndrSig _ ty <- bndrs] instance OutputableBndr name => Outputable (RuleDecls name) where ppr (HsRules _ rules) = ppr rules instance OutputableBndr name => Outputable (RuleDecl name) where ppr (HsRule name act ns lhs _fv_lhs rhs _fv_rhs) = sep [text "{-# RULES" <+> doubleQuotes (ftext $ snd $ unLoc name) <+> ppr act, nest 4 (pp_forall <+> pprExpr (unLoc lhs)), nest 4 (equals <+> pprExpr (unLoc rhs) <+> text "#-}") ] where pp_forall | null ns = empty | otherwise = forAllLit <+> fsep (map ppr ns) <> dot instance OutputableBndr name => Outputable (RuleBndr name) where ppr (RuleBndr name) = ppr name ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty {- ************************************************************************ * * \subsection{Vectorisation declarations} * * ************************************************************************ A vectorisation pragma, one of {-# VECTORISE f = closure1 g (scalar_map g) #-} {-# VECTORISE SCALAR f #-} {-# NOVECTORISE f #-} {-# VECTORISE type T = ty #-} {-# VECTORISE SCALAR type T #-} -} type LVectDecl name = Located (VectDecl name) data VectDecl name = HsVect SourceText -- Note [Pragma source text] in BasicTypes (Located name) (LHsExpr name) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsNoVect SourceText -- Note [Pragma source text] in BasicTypes (Located name) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsVectTypeIn -- pre type-checking SourceText -- Note [Pragma source text] in BasicTypes Bool -- 'TRUE' => SCALAR declaration (Located name) (Maybe (Located name)) -- 'Nothing' => no right-hand side -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnType','ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnEqual' -- For details on above see note [Api annotations] in ApiAnnotation | HsVectTypeOut -- post type-checking Bool -- 'TRUE' => SCALAR declaration TyCon (Maybe TyCon) -- 'Nothing' => no right-hand side | HsVectClassIn -- pre type-checking SourceText -- Note [Pragma source text] in BasicTypes (Located name) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClass','ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation | HsVectClassOut -- post type-checking Class | HsVectInstIn -- pre type-checking (always SCALAR) !!!FIXME: should be superfluous now (LHsType name) | HsVectInstOut -- post type-checking (always SCALAR) !!!FIXME: should be superfluous now ClsInst deriving (Typeable) deriving instance (DataId name) => Data (VectDecl name) lvectDeclName :: NamedThing name => LVectDecl name -> Name lvectDeclName (L _ (HsVect _ (L _ name) _)) = getName name lvectDeclName (L _ (HsNoVect _ (L _ name))) = getName name lvectDeclName (L _ (HsVectTypeIn _ _ (L _ name) _)) = getName name lvectDeclName (L _ (HsVectTypeOut _ tycon _)) = getName tycon lvectDeclName (L _ (HsVectClassIn _ (L _ name))) = getName name lvectDeclName (L _ (HsVectClassOut cls)) = getName cls lvectDeclName (L _ (HsVectInstIn _)) = panic "HsDecls.lvectDeclName: HsVectInstIn" lvectDeclName (L _ (HsVectInstOut _)) = panic "HsDecls.lvectDeclName: HsVectInstOut" lvectInstDecl :: LVectDecl name -> Bool lvectInstDecl (L _ (HsVectInstIn _)) = True lvectInstDecl (L _ (HsVectInstOut _)) = True lvectInstDecl _ = False instance OutputableBndr name => Outputable (VectDecl name) where ppr (HsVect _ v rhs) = sep [text "{-# VECTORISE" <+> ppr v, nest 4 $ pprExpr (unLoc rhs) <+> text "#-}" ] ppr (HsNoVect _ v) = sep [text "{-# NOVECTORISE" <+> ppr v <+> text "#-}" ] ppr (HsVectTypeIn _ False t Nothing) = sep [text "{-# VECTORISE type" <+> ppr t <+> text "#-}" ] ppr (HsVectTypeIn _ False t (Just t')) = sep [text "{-# VECTORISE type" <+> ppr t, text "=", ppr t', text "#-}" ] ppr (HsVectTypeIn _ True t Nothing) = sep [text "{-# VECTORISE SCALAR type" <+> ppr t <+> text "#-}" ] ppr (HsVectTypeIn _ True t (Just t')) = sep [text "{-# VECTORISE SCALAR type" <+> ppr t, text "=", ppr t', text "#-}" ] ppr (HsVectTypeOut False t Nothing) = sep [text "{-# VECTORISE type" <+> ppr t <+> text "#-}" ] ppr (HsVectTypeOut False t (Just t')) = sep [text "{-# VECTORISE type" <+> ppr t, text "=", ppr t', text "#-}" ] ppr (HsVectTypeOut True t Nothing) = sep [text "{-# VECTORISE SCALAR type" <+> ppr t <+> text "#-}" ] ppr (HsVectTypeOut True t (Just t')) = sep [text "{-# VECTORISE SCALAR type" <+> ppr t, text "=", ppr t', text "#-}" ] ppr (HsVectClassIn _ c) = sep [text "{-# VECTORISE class" <+> ppr c <+> text "#-}" ] ppr (HsVectClassOut c) = sep [text "{-# VECTORISE class" <+> ppr c <+> text "#-}" ] ppr (HsVectInstIn ty) = sep [text "{-# VECTORISE SCALAR instance" <+> ppr ty <+> text "#-}" ] ppr (HsVectInstOut i) = sep [text "{-# VECTORISE SCALAR instance" <+> ppr i <+> text "#-}" ] {- ************************************************************************ * * \subsection[DocDecl]{Document comments} * * ************************************************************************ -} type LDocDecl = Located (DocDecl) data DocDecl = DocCommentNext HsDocString | DocCommentPrev HsDocString | DocCommentNamed String HsDocString | DocGroup Int HsDocString deriving (Data, Typeable) -- Okay, I need to reconstruct the document comments, but for now: instance Outputable DocDecl where ppr _ = text "<document comment>" docDeclDoc :: DocDecl -> HsDocString docDeclDoc (DocCommentNext d) = d docDeclDoc (DocCommentPrev d) = d docDeclDoc (DocCommentNamed _ d) = d docDeclDoc (DocGroup _ d) = d {- ************************************************************************ * * \subsection[DeprecDecl]{Deprecations} * * ************************************************************************ We use exported entities for things to deprecate. -} type LWarnDecls name = Located (WarnDecls name) -- Note [Pragma source text] in BasicTypes data WarnDecls name = Warnings { wd_src :: SourceText , wd_warnings :: [LWarnDecl name] } deriving (Data, Typeable) type LWarnDecl name = Located (WarnDecl name) data WarnDecl name = Warning [Located name] WarningTxt deriving (Data, Typeable) instance OutputableBndr name => Outputable (WarnDecls name) where ppr (Warnings _ decls) = ppr decls instance OutputableBndr name => Outputable (WarnDecl name) where ppr (Warning thing txt) = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"] {- ************************************************************************ * * \subsection[AnnDecl]{Annotations} * * ************************************************************************ -} type LAnnDecl name = Located (AnnDecl name) data AnnDecl name = HsAnnotation SourceText -- Note [Pragma source text] in BasicTypes (AnnProvenance name) (Located (HsExpr name)) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnType' -- 'ApiAnnotation.AnnModule' -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId name) => Data (AnnDecl name) instance (OutputableBndr name) => Outputable (AnnDecl name) where ppr (HsAnnotation _ provenance expr) = hsep [text "{-#", pprAnnProvenance provenance, pprExpr (unLoc expr), text "#-}"] data AnnProvenance name = ValueAnnProvenance (Located name) | TypeAnnProvenance (Located name) | ModuleAnnProvenance deriving (Data, Typeable, Functor) deriving instance Foldable AnnProvenance deriving instance Traversable AnnProvenance annProvenanceName_maybe :: AnnProvenance name -> Maybe name annProvenanceName_maybe (ValueAnnProvenance (L _ name)) = Just name annProvenanceName_maybe (TypeAnnProvenance (L _ name)) = Just name annProvenanceName_maybe ModuleAnnProvenance = Nothing pprAnnProvenance :: OutputableBndr name => AnnProvenance name -> SDoc pprAnnProvenance ModuleAnnProvenance = ptext (sLit "ANN module") pprAnnProvenance (ValueAnnProvenance (L _ name)) = ptext (sLit "ANN") <+> ppr name pprAnnProvenance (TypeAnnProvenance (L _ name)) = ptext (sLit "ANN type") <+> ppr name {- ************************************************************************ * * \subsection[RoleAnnot]{Role annotations} * * ************************************************************************ -} type LRoleAnnotDecl name = Located (RoleAnnotDecl name) -- See #8185 for more info about why role annotations are -- top-level declarations data RoleAnnotDecl name = RoleAnnotDecl (Located name) -- type constructor [Located (Maybe Role)] -- optional annotations -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType', -- 'ApiAnnotation.AnnRole' -- For details on above see note [Api annotations] in ApiAnnotation deriving (Data, Typeable) instance OutputableBndr name => Outputable (RoleAnnotDecl name) where ppr (RoleAnnotDecl ltycon roles) = ptext (sLit "type role") <+> ppr ltycon <+> hsep (map (pp_role . unLoc) roles) where pp_role Nothing = underscore pp_role (Just r) = ppr r roleAnnotDeclName :: RoleAnnotDecl name -> name roleAnnotDeclName (RoleAnnotDecl (L _ name) _) = name
siddhanathan/ghc
compiler/hsSyn/HsDecls.hs
bsd-3-clause
76,938
0
17
22,674
12,663
6,926
5,737
901
7
module Refact where import qualified Refact.Types as R import HSE.All toRefactSrcSpan :: SrcSpan -> R.SrcSpan toRefactSrcSpan ss = R.SrcSpan (srcSpanStartLine ss) (srcSpanStartColumn ss) (srcSpanEndLine ss) (srcSpanEndColumn ss) toSS :: Annotated a => a S -> R.SrcSpan toSS = toRefactSrcSpan . toSrcSpan . ann
eigengrau/hlint
src/Refact.hs
bsd-3-clause
408
0
7
141
105
56
49
10
1
-- -- Patricia Fasel -- Los Alamos National Laboratory -- 1990 August -- module ChargeDensity (chargeDensity) where import PicType import Consts import Data.Array -- Phase I: calculate the charge density rho -- Each particle represents an amount of charge distributed over an entire cell. -- In discretizing the charge density at the grid points we split the cell into -- four rectangles and assign to each corner an amount of charge proportional -- to the area of the opposite diagonal sub rectangle -- So each particle contributes a portion of charge to four quadrants -- particle position is (i+dx, j+dy) -- nw quadrant (1-dx)(1-dy)(charge) is added to rho(i,j) -- ne quadrant (dx)(1-dy)(charge) is added to rho(i,j+1) -- sw quadrant (1-dx)(dy)(charge) is added to rho(i+1,j) -- se quadrant (dx)(dy)(charge) is added to rho(i+1,j+1) -- wrap around used for edges and corners chargeDensity :: ParticleHeap -> Rho chargeDensity (xyPos, xyVel) = accumArray (+) 0 ((0,0), (n,n)) (accumCharge xyPos) where n = nCell-1 -- for each particle, calculate the distribution of density -- based on (x,y), a proportion of the charge goes to each rho accumCharge :: [Position] -> [MeshAssoc] accumCharge [] = [] accumCharge ((x,y):xys) = [((i ,j ) , charge * (1-dx) * (1-dy))] ++ [((i',j ) , charge * dx * (1-dy))] ++ [((i ,j') , charge * (1-dx) * dy)] ++ [((i',j') , charge * dx * dy)] ++ accumCharge xys where i = truncate x i' = (i+1) `rem` nCell j = truncate y j' = (j+1) `rem` nCell dx = x - fromIntegral i dy = y - fromIntegral j
PaulBone/mercury
benchmarks/progs/pic/haskell/ChargeDensity.hs
gpl-2.0
1,595
16
14
334
389
231
158
22
1
module PackageTests.CMain.Check ( checkBuild ) where import Test.Tasty.HUnit import System.FilePath import PackageTests.PackageTester dir :: FilePath dir = "PackageTests" </> "CMain" checkBuild :: FilePath -> Assertion checkBuild ghcPath = do let spec = PackageSpec { directory = dir , distPref = Nothing , configOpts = [] } buildResult <- cabal_build spec ghcPath assertBuildSucceeded buildResult
kosmikus/cabal
Cabal/tests/PackageTests/CMain/Check.hs
bsd-3-clause
475
0
12
130
108
60
48
15
1
{-# OPTIONS_GHC -fwarn-missing-import-lists #-} -- Test #1789 module T1789 where import Prelude import Data.Map import Data.Map (size) import Data.Maybe (Maybe(..)) import Data.Maybe hiding (isJust) import qualified Data.Set as Set
sdiehl/ghc
testsuite/tests/rename/should_compile/T1789.hs
bsd-3-clause
233
0
6
30
57
38
19
8
0
{-# LANGUAGE ConstraintKinds, TypeFamilies #-} module T11515 where type family ShowSyn a where ShowSyn a = Show a foo :: (ShowSyn a, _) => a -> String foo x = show x
sdiehl/ghc
testsuite/tests/partial-sigs/should_fail/T11515.hs
bsd-3-clause
169
0
6
35
56
31
25
5
1
{-# LANGUAGE OverloadedStrings #-} module System.Apotiki.Signature (sign_msg, get_key) where import System.Time (getClockTime, ClockTime(..)) import Crypto.Random import Data.OpenPGP import Data.String import qualified Data.Binary as Binary import qualified Data.OpenPGP.CryptoAPI as PGP import qualified Data.ByteString.Lazy as B import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BC import Codec.Encryption.OpenPGP.ASCIIArmor as Armor import Codec.Encryption.OpenPGP.ASCIIArmor.Types as Armor get_key keypath = do let payload = BC.pack keypath let Right decoded_key = Armor.decode payload let ((Armor _ _ bskey):_) = decoded_key let key = Binary.decode bskey TOD tod _ <- getClockTime rng <- newGenIO :: IO SystemRandom let time = (fromIntegral tod :: Integer) return (key, (time, rng)) sign_msg :: (CryptoRandomGen g) => Message -> Integer -> g -> BS.ByteString -> BS.ByteString sign_msg keys time rng payload = Armor.encode [armor] where wtime = (fromIntegral time :: Binary.Word32) lazy_payload = B.fromChunks [payload] pgp_payload = LiteralDataPacket 'b' "" wtime lazy_payload input = (DataSignature pgp_payload []) (DataSignature _ [sig], _) = PGP.sign keys input SHA256 [] time rng options = [("Version", "OpenPrivacy 0.99"), ("Hash", "SHA256")] encoded_sig = Binary.encode sig armor = Armor.Armor Armor.ArmorSignature options encoded_sig
pyr/apotiki
System/Apotiki/Signature.hs
isc
1,430
0
13
228
454
253
201
33
1
import Data.List import Control.Arrow data Encoded a = Single a | Multiple Int a deriving (Show) encode :: Eq a => [a] -> [(Int, a)] encode = map (length &&& head) . group encodeX :: Eq a => [a] -> [Encoded a] encodeX = map encodeHelper . encode where encodeHelper (1,x) = Single x encodeHelper (n,x) = Multiple n x decodeX :: Eq a => [Encoded a] -> [a] decodeX = concatMap decodeHelper where decodeHelper (Single x) = [x] decodeHelper (Multiple n x) = replicate n x
tamasgal/haskell_exercises
99questions/Problem12.hs
mit
511
9
10
131
215
117
98
14
2
-- Surrounding Primes for a value -- http://www.codewars.com/kata/560b8d7106ede725dd0000e2/ module Codewars.G964.PrimBefAft where import Control.Arrow ((***)) primeBefAft :: Integer -> (Integer, Integer) primeBefAft n = (f *** f) (b, a) where b = if odd n then [n-2, n-4 ..] else [n-1, n-3 ..] a = if odd n then [n+2, n+4 ..] else [n+1, n+3 ..] f = head . filter isPrime isPrime x = all (\d -> x `mod` d /= 0) [3 .. floor . sqrt . fromIntegral $ x]
gafiatulin/codewars
src/6 kyu/PrimBefAft.hs
mit
488
0
11
120
215
125
90
8
3
module CFDI ( module CFDI.Types , module CSD , module XN , addCsdCerData , findAddendumByName , getStampComplement , originalChain , parseCfdiFile , parseCfdiXml , ppParseError , ppXmlParseError , signWith , toXML ) where import CFDI.Chainable (chain) import CFDI.CSD (signWithCSD) import CFDI.CSD as CSD (CsdCerData(..)) import CFDI.Types import CFDI.XmlNode (parseNode, renderNode) import CFDI.XmlNode as XN (XmlParseError(..)) import Control.Error.Safe (justErr) import Data.List (find, intercalate) import Data.Text (Text, append) import Text.XML.Light ( Element(..) , QName(..) , parseXMLDoc , ppcElement , prettyConfigPP ) import Text.XML.Light.Lexer (XmlSource) addCsdCerData :: CsdCerData -> CFDI -> CFDI addCsdCerData CsdCerData { cerNumber = cn, cerToText = ct } cfdi = cfdi { certNum = Just (CertificateNumber cn), certText = Just ct } findAddendumByName :: String -> CFDI -> Maybe Element findAddendumByName _ CFDI { addenda = Nothing } = Nothing findAddendumByName name CFDI { addenda = Just (Addenda xs) } = find match xs where match Element { elName = QName n _ _ } = n == name getStampComplement :: CFDI -> Maybe PacStamp getStampComplement cfdi = stampComplement =<< complement cfdi originalChain :: CFDI -> Text originalChain cfdi = "||" `append` chain cfdi `append` "||" parseCfdiFile :: FilePath -> IO (Either XmlParseError CFDI) parseCfdiFile fp = parseCfdiXml <$> readFile fp parseCfdiXml :: XmlSource s => s -> Either XmlParseError CFDI parseCfdiXml xmlSource = justErr MalformedXML (parseXMLDoc xmlSource) >>= parseNode ppParseError :: ParseError -> String ppParseError (InvalidValue v) = '"' : v ++ "\" no es un valor válido para este atributo." ppParseError (DoesNotMatchExpr e) = "No cumple con la expresión \"" ++ e ++ "\"." ppParseError NotInCatalog = "No se encuentra en el catálogo de valores permitidos publicado por el SAT." ppXmlParseError :: String -> XmlParseError -> String ppXmlParseError indentationStr = intercalate "\n" . fst . foldl addIndentation ([], "") . errMsgLines where addIndentation (ls, s) l = (ls ++ [s ++ l], s ++ indentationStr) errMsgLines (AttrNotFound a) = ["No se encontró el atributo \"" ++ a ++ "\"."] errMsgLines (AttrParseError a pe) = ["No se pudo interpretar el atributo \"" ++ a ++ "\":", ppParseError pe] errMsgLines (ElemNotFound e) = ["No se encontró el elemento \"" ++ e ++ "\"."] errMsgLines (ExpectedAtLeastOne e) = ["Se necesita al menos un \"" ++ e ++ "\"."] errMsgLines MalformedXML = ["XML malformado o inválido."] errMsgLines (ParseErrorInChild e xpe) = ("Se encontró un error en el elemento \"" ++ e ++ "\":") : errMsgLines xpe errMsgLines UnknownComplement = ["Complemento desconocido."] signWith :: FilePath -> CFDI -> IO (Either Text CFDI) signWith csdPemPath cfdi = fmap (fmap addSignatureToCFDI) . signWithCSD csdPemPath $ originalChain cfdi where addSignatureToCFDI sig = cfdi { signature = Just sig } toXML :: CFDI -> String toXML cfdi = unlines [ "<?xml version='1.0' encoding='UTF-8' ?>" , ppcElement prettyConfigPP (renderNode cfdi) ]
yusent/cfdis
src/CFDI.hs
mit
3,269
0
11
693
928
504
424
81
7
{-# LANGUAGE OverloadedStrings #-} module Models.Common where import Data.Text import Data.Aeson data AppResponse = AppError Text | AppSuccess Text instance ToJSON AppResponse where toJSON (AppError t) = object [ "error" .= t ] toJSON (AppSuccess t) = object [ "success" .= t ]
folsen/haskell-startapp
src/Models/Common.hs
mit
291
0
8
56
87
47
40
10
0
{-# LANGUAGE NoImplicitPrelude #-} module Prelude.Source.Prelude ( ($!), ) where import Prelude ( ($!), )
scott-fleischman/cafeteria-prelude
src/Prelude/Source/Prelude.hs
mit
120
0
5
29
27
20
7
5
0
module Tarefa6_li1g175 where import Bomberman import Data.Maybe import qualified Data.Map as Map import Data.List import qualified Data.Set as Set bot :: [String] -> Int -> Int -> Maybe Char bot mapa player ticks = decide (parse mapa) player ticks decide :: Mapa -> Int -> Int -> Maybe Char decide m i tk = let ply = (players m!!i) in case ply of Nothing -> Nothing Just ply' -> let fl = sort $ floodBF tk i m [] [((psy ply'),[])] in case fl of [] -> Just 'B' (h:_) -> zoneToAction h {-| a zone represents a reachable position and associated stats |-} data Zone = Z { live :: Bool, psz :: (Int,Int), path :: [Int], danger :: [Int], powrs :: Bool, boxes :: Int, plys :: Int, dist :: Float } deriving (Show, Eq) instance Ord (Zone) where z1 <= z2 = rank z1 <= rank z2 rank :: Zone -> (Int,Float,Int,Int,Float,Int,Int,Float,Int) rank z = (lv,ds,pw,pl,di,dsw,plw,di,lp) where lp = length (path z) ds = foldr (\a b -> (fromIntegral a) + (0.9 * b)) 0 (danger z) dsw = lp pl = - plys z plw = if (pl == 0) then 0 else lp pw = fromEnum (powrs z && lp <= 1) di = dist z lv = fromEnum $ not (live z) {-| decides how to act given the target zone (moves unless already there, in which case bombs if something to destroy) |-} zoneToAction :: Zone -> Maybe Char zoneToAction (Z _ _ [] _ _ 0 0 _) = Nothing zoneToAction (Z _ _ [] _ _ y b _) = Just 'B' zoneToAction (Z _ _ l _ _ y b _) = case last l of 0 -> Just $ dirToDir 0 1 -> Just $ dirToDir 1 2 -> Just $ dirToDir 2 3 -> Just $ dirToDir 3 _ -> Nothing floodBF :: Int -> Int -> Mapa -> [(Int,Int)] -> [((Int,Int),[Int])] -> [Zone] floodBF _ _ _ _ [] = [] floodBF tk i m vs qs = map (zonify tk m i) qs ++ floodBF tk i m vs' (candidatesTop tk m vs' qs) where vs' = vs ++ map fst qs zonify :: Int -> Mapa -> Int -> ((Int,Int),[Int]) -> Zone zonify tk m i (pos,pth) = Z liv pos pth dangers sur_pw sur_bx sur_pl (distance pos (center m)) where dangers = [fromEnum (pos `elem` explosionTime m i) + fromEnum (Just pos == espirala0 tk (length (grid m)) i) | i <- [1..6]] sur_pl = (length $ getSurPlayerExcept i m pos) sur_pw = (isJust (getPower m pos)) sur_bx = (length $ getSuroundingBoxes m pos) liv = safe tk m pos (if pth == [] then 1 else length pth) candidatesTop :: Int -> Mapa -> [(Int,Int)] -> [((Int,Int),[Int])] -> [((Int,Int),[Int])] candidatesTop _ _ _ [] = [] candidatesTop tk m vs (p:t) = let cs = candidates tk m vs p in cs ++ candidatesTop tk m (map fst cs ++ vs) t candidates :: Int -> Mapa -> [(Int,Int)] -> ((Int,Int),[Int]) -> [((Int,Int),[Int])] candidates tk m vs (pos,pth) | length pth >= 10 = [] | otherwise = filter vld [(stepDir pos i, i:pth) | i <- [0..3]] where vld (p,h) = canMove m p && safe tk m p (length h) && not (p `elem` vs)
hpacheco/HAAP
examples/gameworker/li1g175/Tarefa6_li1g175.hs
mit
3,229
1
19
1,091
1,476
792
684
66
5
module Network.Skype.Protocol.Misc where import Data.Typeable (Typeable) data ConnectionStatus = ConnectionStatusOffline | ConnectionStatusConnecting | ConnectionStatusPausing | ConnectionStatusOnline deriving (Eq, Show, Typeable)
emonkak/skype4hs
src/Network/Skype/Protocol/Misc.hs
mit
301
0
6
90
49
30
19
7
0
-- | Definition of 'VmScript' an artifact encapsulating several virtual machines -- disk images that can be mounted in an execution environment like -- "B9.LibVirtLXC". A 'VmScript' is embedded by in an -- 'B9.Artifact.Generator.ArtifactGenerator'. module B9.Vm ( VmScript (..), substVmScript, ) where import B9.Artifact.Content.StringTemplate import B9.B9Error import B9.DiskImages import B9.Environment import B9.ExecEnv import B9.ShellScript import Control.Eff import Control.Parallel.Strategies import Data.Binary import Data.Data import Data.Generics.Aliases hiding (Generic) import Data.Generics.Schemes import Data.Hashable import GHC.Generics (Generic) -- | Describe a virtual machine, i.e. a set up disk images to create and a shell -- script to put things together. data VmScript = VmScript CPUArch [SharedDirectory] Script | NoVmScript deriving (Read, Show, Typeable, Data, Eq, Generic) instance Hashable VmScript instance Binary VmScript instance NFData VmScript substVmScript :: forall e. (Member EnvironmentReader e, Member ExcB9 e) => VmScript -> Eff e VmScript substVmScript = everywhereM gsubst where gsubst :: GenericM (Eff e) gsubst = mkM substMountPoint `extM` substSharedDir `extM` substScript substMountPoint NotMounted = pure NotMounted substMountPoint (MountPoint x) = MountPoint <$> substStr x substSharedDir (SharedDirectory fp mp) = SharedDirectory <$> substStr fp <*> pure mp substSharedDir (SharedDirectoryRO fp mp) = SharedDirectoryRO <$> substStr fp <*> pure mp substSharedDir s = pure s substScript (In fp s) = In <$> substStr fp <*> pure s substScript (Run fp args) = Run <$> substStr fp <*> mapM substStr args substScript (As fp s) = As <$> substStr fp <*> pure s substScript s = pure s
sheyll/b9-vm-image-builder
src/lib/B9/Vm.hs
mit
1,834
0
9
352
466
247
219
-1
-1
module Lusk.Eval where import Control.Monad import Control.Monad.State import Control.Monad.Error import qualified Data.Map as M import Lusk.Parser -- for eval patterns import Lusk.Functions import Lusk.Value type SymbolTable = M.Map String Value -- The main state of the interpreter data LuskState = LuskState { -- Local symbol table symbolTable :: SymbolTable, -- The return value in a function call retVal :: Value, -- True after a return statement ret :: Bool, -- True after a break statement brk :: Bool, -- True after a continue statement cont :: Bool, -- Parent state parent :: Maybe LuskState } globalTable :: SymbolTable globalTable = M.fromList [ ("pi", Number pi), ("print", HIOFun lPrint), ("type", HFun lType) ] globalState :: LuskState globalState = LuskState { symbolTable = globalTable, retVal = Nil, ret = False, brk = False, cont = False, parent = Nothing } -- State Monad type SM m a = StateT LuskState (ErrorT String m) a modifyST :: LuskState -> SymbolTable -> LuskState modifyST s st = s { symbolTable = st } -- Create a new state that is a child of [p] newState :: LuskState -> LuskState newState p = LuskState { symbolTable = M.fromList [], retVal = Nil, ret = False, brk = False, cont = False, parent = Just p } -- Pushes a new state a level down, this means the beginning of a loop or function pushState :: (Monad m) => (MonadIO m) => SM m () pushState = do liftIO $ putStrLn "push" cs <- get put $ newState cs -- Pop the current state and make it's parent the current state -- Occurs at the end of a function or a loop popState :: (Monad m) => (MonadIO m) => SM m () popState = do liftIO $ putStrLn "push" cs <- get let (Just p) = parent cs put p -- lua considers only "nil" and "false" as false values -- everything else is true toBool :: Value -> Bool toBool Nil = False toBool (Boolean b) = b toBool v = True -- map operators to haskell funcions evalUnaryOp :: OpType -> Value -> Value evalUnaryOp Sub = negate evalUnaryOp Not = \a -> Boolean $ not (toBool a) evalOp :: OpType -> Value -> Value -> Value evalOp Add a b = (+) a b evalOp Sub a b = (-) a b evalOp Mul a b = (*) a b evalOp Div a b = (/) a b evalOp Pow a b = (**) a b evalOp Concat a b = String $ (++) (show a) (show b) evalOp Lt a b = Boolean $ (<) a b evalOp Gt a b = Boolean $ (>) a b evalOp LtEq a b = Boolean $ (<=) a b evalOp GtEq a b = Boolean $ (>=) a b evalOp Eq a b = Boolean $ (==) a b evalOp NotEq a b = Boolean $ not ((==) a b) evalList :: (Monad m) => (MonadIO m) => [SyntaxTree] -> [Value] -> SM m [Value] evalList [] vs' = return $ reverse vs' evalList (v:vs) vs' = do v' <- eval v evalList vs (v':vs') -- main evaluation function eval :: (Monad m) => (MonadIO m) => SyntaxTree -> SM m Value eval (Empty) = return Nil eval (NumberLit n) = return $ Number n eval (StringLit str) = return $ String str eval (BoolLit b) = return $ Boolean b eval (TableLit vs) = do vs' <- evalList vs [] return $ Table (zip [Number (fromIntegral x) | x <- [1..length vs]] vs') eval (Paren p) = eval p eval (UnaryOp op r) = eval r >>= \v -> return (evalUnaryOp op $ v) eval (BinaryOp op (l, r)) = case op of And -> eval l >>= \l' -> if toBool l' then eval r >>= \r' -> return r' else return l' Or -> eval l >>= \l' -> if not (toBool l') then eval r >>= \r' -> return r' else return l' _ -> eval l >>= \l' -> eval r >>= \r' -> return (evalOp op l' r') -- takes a list of names and a list of values -- evaluates all the values first (in case of 'variable swaping') -- then zip that into a list of pairs and add to a symbol table eval (Assign ns vs) = do vs' <- evalList vs [] doMultipleAssign $ zip (Prelude.map (\(Var s) -> s) ns) vs' where doMultipleAssign [] = return Nil doMultipleAssign (p:ps) = do let (name, value) = p s <- get let t = symbolTable s put (modifyST s (M.insert name value t)) doMultipleAssign ps eval (Var s) = do st <- get getVar s st where getVar s st = do let t = symbolTable st case M.lookup s t of Just v -> return v Nothing -> do let p = parent st case p of Just prnt -> do getVar s prnt Nothing -> return Nil eval (Call fn args) = do fn' <- eval fn args' <- evalList args [] case fn' of (HFun f) -> callHFun $ f args' (HIOFun f) -> callHIOFun $ f args' _ -> return Nil where callHFun r = do case r of Left err -> throwError err Right val -> return val callHIOFun f = do r <- liftIO f case r of Left err -> throwError err Right val -> return val -- Table subscript eval (Subscript t k) = do t' <- eval t k' <- eval k extract t' k' where -- Extract a value from the table with the given [key] extract (Table pairs) key = do let found = (filter (\(tk, tv) -> tk == key) pairs) if length found > 0 then return $ snd $ head found else return Nil eval (IfStat c t r) = do c' <- eval c if toBool c' then eval t else eval r return Nil eval (WhileStat c b) = do pushState >> doWhile c b >>= \v -> popState >> return v where doWhile c b = do c' <- eval c case toBool c' of True -> do eval b doWhile c b False -> do return Nil eval (Block (s:stats)) = do eval s case stats of [] -> return Nil _ -> eval $ Block stats eval (Chunk (s:stats)) = do res <- eval s case stats of [] -> return res _ -> eval $ Chunk stats
glhrmfrts/lusk
Lusk/Eval.hs
mit
5,738
0
19
1,694
2,267
1,140
1,127
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Functionality.Util where import Control.Monad (liftM, return, (>=>), (>>=)) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Aeson (FromJSON, Value) import Data.Default (def) import Data.Either (Either (Left, Right)) import Data.Function (const, id, ($), (.)) import Data.Functor (fmap, (<$>)) import Data.JsonSchema.Draft4 (FilesystemValidationFailure (..), SchemaWithURI (..), emptySchema, fetchFilesystemAndValidate, _schemaRef) import Data.Maybe (Maybe (Just, Nothing)) import Data.Monoid ((<>)) import Data.String (IsString, String, fromString, unwords) import Data.Text (pack) import Data.UUID (toString) import qualified Database.Couch.Explicit.Database as Database (create, delete) import qualified Database.Couch.Response as Response (asBool) import Database.Couch.Types (Context (Context), Error, Port (Port), Result) import GHC.Err (error) import Network.HTTP.Client (Manager, defaultManagerSettings, newManager) import System.FilePath ((</>)) import System.IO (FilePath, IO) import System.Random (randomIO) import Test.Tasty (TestName, TestTree, defaultMain, testGroup, withResource) import Test.Tasty.HUnit (assertFailure, testCaseSteps, (@=?)) import Text.Show (show) dbContext :: MonadIO m => IO Manager -> m Context dbContext getManager = do manager <- liftIO getManager uuid <- liftM (fromString . ("test-" <>) . toString) (liftIO randomIO) return $ Context manager "localhost" (Port 5984) Nothing def (Just uuid) serverContext :: MonadIO m => IO Manager -> m Context serverContext getManager = do manager <- liftIO getManager return $ Context manager "localhost" (Port 5984) Nothing def Nothing releaseContext :: Context -> IO () releaseContext = const $ return () runTests :: (IO Manager -> TestTree) -> IO () runTests testTree = do let manager = newManager defaultManagerSettings defaultMain $ testTree manager testAgainstFailure :: String -> (Context -> IO (Result Value)) -> Error -> IO Context -> TestTree testAgainstFailure desc function exception getContext = testCaseSteps desc $ \step -> do step "Make request" getContext >>= function >>= checkException step exception checkException :: (String -> IO ()) -> Error -> Result Value -> IO () checkException step exception res = do step "Got an exception" case res of -- HttpException isn't Eqable, so we simply coerce with show Left err -> show exception @=? show err Right val -> assertFailure $ unwords [ "Didn't get expected exception" , show exception , "instead" , show val ] throwOnError :: FromJSON a => Result a -> IO () throwOnError res = case res of Left err -> error $ show err Right _ -> return () withDb :: (IO Context -> TestTree) -> IO Context -> TestTree withDb test getContext = withResource (getContext >>= createTempDb) (fmap Response.asBool . Database.delete >=> throwOnError) test where createTempDb ctx = do Response.asBool <$> Database.create ctx >>= throwOnError return ctx testAgainstSchema :: String -> (Context -> IO (Result Value)) -> FilePath -> IO Context -> TestTree testAgainstSchema desc function schema = testAgainstSchemaAndValue desc function schema id (const . const (return ())) testAgainstSchemaAndValue :: String -> (Context -> IO (Result Value)) -> FilePath -> (Result Value -> Result a) -> ((String -> IO ()) -> a -> IO ()) -> IO Context -> TestTree testAgainstSchemaAndValue desc function schema decoder checker getContext = testCaseSteps desc $ \step -> do step "Make request" getContext >>= function >>= checkCookiesAndSchema step schema decoder checker checkCookiesAndSchema :: (String -> IO ()) -> FilePath -> (Result Value -> Result a) -> ((String -> IO ()) -> a -> IO ()) -> Result Value -> IO () checkCookiesAndSchema step schemaFile decoder checker res = do step "No exception" case res of Left err -> assertFailure (show err) Right (json, cookieJar) -> do step "Empty cookie jar" def @=? cookieJar checkSchema step json schemaFile step $ "Decoding json: " <> show json case decoder res of Left err -> assertFailure (show err) Right (val, _) -> do step "Checking value" checker step val checkSchema :: IsString s => (s -> IO ()) -> Value -> FilePath -> IO () checkSchema step value schemaName = do step "Checking result against schema" let schema = SchemaWithURI { _swSchema = emptySchema {_schemaRef = Just $ pack schemaName}, _swURI = Just $ pack $ "test/schema/schema" </> schemaName} res <- liftIO $ fetchFilesystemAndValidate schema value case res of Right () -> return () Left (FVRead _) -> error "Error fetching a referenced schema (either during IO or parsing)." Left (FVSchema _) -> error "Our 'schema' itself was invalid." Left f@(FVData _) -> assertFailure $ unwords ["Failed to validate", show value, ":", show f] class TestInput a where makeTests :: TestName -> [IO Context -> TestTree] -> a -> TestTree makeTests desc tests input = testGroup desc $ fmap (applyInput input) tests applyInput :: a -> (IO Context -> TestTree) -> TestTree instance TestInput (IO Manager) where applyInput input = ($ dbContext input) instance TestInput (IO Context) where applyInput input = ($ input)
mdorman/couch-simple
test/Functionality/Util.hs
mit
7,199
0
17
2,808
1,859
961
898
-1
-1
-- -- The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. -- Find the sum of all the primes below two million. -- import List import Maybe primes :: [Integer] primes = 2 : 3 : filter isPrime [5,7..] where isPrime n = all (notDivs n) $ takeWhile (\ p -> p * p <= n) (tail primes) notDivs n p = n `mod` p /= 0 main = putStrLn $ show $ sum $ takeWhile (< 2000000) primes
stu-smith/project-euler-haskell
Euler-010.hs
mit
410
1
12
127
139
76
63
7
1
-- To move n discs (stacked in increasing size) from peg a to peg b -- using peg c as temporary storage, -- 1. move n − 1 discs from a to c using b as temporary storage -- 2. move the top disc from a to b -- 3. move n − 1 discs from c to b using a as temporary storage. -- For this exercise, define a function hanoi with the following type: -- type Peg = String -- type Move = (Peg, Peg) -- hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] -- Given the number of discs and names for the three pegs, hanoi should -- return a list of moves to be performed to move the stack of discs from -- the first peg to the second. -- Note that a type declaration, like type Peg = String above, -- makes a type synonym. -- In this case Peg is declared as a synonym for String, and the two names Peg and String -- can now be used interchangeably. -- Giving more descriptive names to types in this way can be used to give shorter -- names to complicated types, or (as here) simply to help with documentation. -- Example: hanoi 2 "a" "b" "c" == [("a","c"), ("a","b"), ("c","b")] type Peg = String type Move = (Peg, Peg) hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi 1 peg1 peg2 _ = [(peg1, peg2)] hanoi n peg1 peg2 peg3 = hanoi (n-1) peg1 peg3 peg2 ++ [(peg1, peg2)] ++ hanoi (n-1) peg3 peg2 peg1 -- Nick question -- can I ask haskell to show the calls being made with the parameters being passed
NickAger/LearningHaskell
CIS194/lecture1-exercise2.hs
mit
1,405
0
9
298
150
92
58
5
1
{- Flatten a nested list structure. -} flattenList :: [[a]] -> [a] flattenList [] = [] flattenList [x] = x flattenList (h:t) = h ++ flattenList t
andrewaguiar/s99-haskell
p07.hs
mit
146
0
7
27
65
35
30
4
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGDocument (js_createEvent, createEvent, js_getRootElement, getRootElement, SVGDocument, castToSVGDocument, gTypeSVGDocument) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"createEvent\"]($2)" js_createEvent :: JSRef SVGDocument -> JSString -> IO (JSRef Event) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGDocument.createEvent Mozilla SVGDocument.createEvent documentation> createEvent :: (MonadIO m, ToJSString eventType) => SVGDocument -> eventType -> m (Maybe Event) createEvent self eventType = liftIO ((js_createEvent (unSVGDocument self) (toJSString eventType)) >>= fromJSRef) foreign import javascript unsafe "$1[\"rootElement\"]" js_getRootElement :: JSRef SVGDocument -> IO (JSRef SVGSVGElement) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGDocument.rootElement Mozilla SVGDocument.rootElement documentation> getRootElement :: (MonadIO m) => SVGDocument -> m (Maybe SVGSVGElement) getRootElement self = liftIO ((js_getRootElement (unSVGDocument self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SVGDocument.hs
mit
1,954
14
11
275
495
299
196
33
1
import Data.Char -- Matheus Santiago Neto -- 11621BSI252 -- Rodrigo Souza Rezende -- 11621BSI245 -- Hugo Sousa Nasciutti -- 11621BSI260 {--------------------------------------------------------------------------------- 1. Faça uma função que devolva a mesma lista de strings recebida na entrada, exceto que as letras em cada palavra ficarão invertidas entre maiúsculas e minúsculas. Por exemplo, onde tem ‘e’ troque por ‘E’, onde tem ‘E’ troque por ‘e’, e assim por diante. Dica: Para inverter um caractere, veja como ele está atualmente (funções isUpper e isLower da biblioteca Data.Char) e altere-o (funções toUpper e toLower, também da Data.Char). Exemplo: *Main> inverte ["AUla","de","progrAMACao"] ["auLA","DE","PROGRamacAO"] -} inverter_map :: String -> String inverter_map [] = "" inverter_map (x:xs) | isLower x == True = toUpper x : inverter_map xs | otherwise = toLower x : inverter_map xs inverte :: [String] -> [String] inverte lista = map inverter_map lista {--------------------------------------------------------------------------------- 2. Função maior :: Int -> [Int] -> Int que considera um número e o compara com os elementos de uma lista. Caso esse número seja maior que todos os elementos da lista, ele será retornado pela função. Caso contrário, a função retorna o maior elemento da lista. Por exemplo: *Main> maior 18 [3 ,6 ,12 ,4 ,55 ,11] 55 *Main> maior 111 [3 ,6 ,12 ,4 ,55 ,11] 111 -} maior :: Int -> [Int] -> Int maior a b = foldr max a b {--------------------------------------------------------------------------------- 3. Faça uma função que devolva uma lista das strings formadas por palavras que se iniciem por uma letra específica. *Main> letraEsp 'a' ["bola","arara","casa","abobora"] ["arara","abobora"] -} letraEsp_map :: Char -> String -> Bool letraEsp_map letra word | letra == head(word) = True | otherwise = False letraEsp :: Char -> [String] -> [String] letraEsp letter lista = filter (letraEsp_map letter) lista {--------------------------------------------------------------------------------- 4. Faça uma função que receba um caractere e uma lista de strings e devolva o comprimento da maior string que comece com o caractere dado. *Main> maiorComprimento 'e' ["esse","exercicio","eh","simples"] 9 -} maiorComprimento :: Char -> [String] -> Int maiorComprimento letra word = foldr (max) 0 (map length word)
hugonasciutti/Exercises
Haskell/Teste3/teste3.hs
mit
2,462
2
10
402
278
144
134
18
1
import Graphics.Rendering.Cairo data Point = Point Double Double points = [Point 200 100, Point 100 300, Point 300 200] red = (0.88, 0.29, 0.22) fileName = "red-dots.png" drawOneMarker bw (r,g,b) = do rectangle (-0.5*bw) (-0.5*bw) bw bw setSourceRGBA r g b 0.8 fill drawMarkerAt (Point x y) = do save translate x y drawOneMarker 20.0 red restore paintCanvas = do setSourceRGB 1 1 1 paint mapM_ drawMarkerAt points createPng fileName = do let w = 400 h = 400 img <- createImageSurface FormatARGB32 w h renderWith img paintCanvas surfaceWriteToPNG img fileName liftIO ( do putStrLn ("Created: " ++ fileName) putStrLn ("Size: " ++ show w ++ "x" ++ show h ++ " pixels") ) main = do createPng fileName
jsavatgy/xroads-game
code/red-dots.hs
gpl-2.0
758
1
17
180
313
148
165
29
1
module FloretSphere ( tetrahedron , cube , dodecahedron , stubRhombicosidodecahedron , rhombicosidodecahedron , snubDodecahedron , pentagonalHexecontahedron , icosahedron , snubRhombiMix , thinFloret , pentaFloret , polyhedrons ) where import Control.Exception (assert) import Data.List (elemIndex) import Data.Maybe (fromJust) import ListUtil import Geometry import Geometry (Point3f, Normal, modelAutoNormals) -- some polyhedrons created along the way... tetrahedron :: RealFloat a => Model a tetrahedron = modelAutoNormals tetrahedronPoints tetrahedronFaces cube :: RealFloat a => Model a cube = modelAutoNormals cubePoints cubeFaces dodecahedron :: RealFloat a => Model a dodecahedron = modelAutoNormals dodecahedronPoints dodecahedronFaces stubRhombicosidodecahedron :: RealFloat a => Model a stubRhombicosidodecahedron = modelAutoNormals stubRhombicosidodecahedronPoints rhombicosidodecahedronFaces rhombicosidodecahedron :: RealFloat a => Model a rhombicosidodecahedron = modelAutoNormals rhombicosidodecahedronPoints rhombicosidodecahedronFaces snubDodecahedron :: RealFloat a => Model a snubDodecahedron = modelAutoNormals snubDodecahedronPoints snubDodecahedronFaces pentagonalHexecontahedron :: RealFloat a => Model a pentagonalHexecontahedron = modelAutoNormals pentagonalHexecontahedronPoints pentagonalHexecontahedronFaces icosahedron :: RealFloat a => Model a icosahedron = modelAutoNormals icosahedronPoints icosahedronFaces snubRhombiMix :: RealFloat a => Model a snubRhombiMix = modelAutoNormals snubDodecahedronPoints rhombicosidodecahedronFaces thinFloret :: RealFloat a => Model a thinFloret = modelAutoNormals thinFloretPoints thinFloretFaces pentaFloret :: RealFloat a => Model a pentaFloret = modelAutoNormals pentaFloretPoints pentaFloretFaces polyhedrons :: RealFloat a => [Model a] polyhedrons = [ tetrahedron , cube , dodecahedron , stubRhombicosidodecahedron , rhombicosidodecahedron , snubDodecahedron , pentagonalHexecontahedron , icosahedron , snubRhombiMix , thinFloret , pentaFloret ] -- polyhedron geometry functions -- tetrahedron tetrahedronPoints :: RealFloat a => [Point3f a] tetrahedronPoints = [ Point3f 1 1 1 , Point3f (-1) 1 (-1) , Point3f 1 (-1) (-1) , Point3f (-1) (-1) 1 ] tetrahedronFaces :: [[Int]] tetrahedronFaces = [ [0,2,1] , [0,1,3] , [0,3,2] , [1,2,3] ] -- cube cubePoints :: RealFloat a => [Point3f a] cubePoints = [ Point3f 1 1 1 , Point3f (-1) 1 1 , Point3f (-1) 1 (-1) , Point3f 1 1 (-1) , Point3f (-1) (-1) (-1) , Point3f 1 (-1) (-1) , Point3f 1 (-1) 1 , Point3f (-1) (-1) 1 ] cubeFaces :: [[Int]] cubeFaces = [ [0,3,2,1] , [4,5,6,7] , [0,6,5,3] , [1,2,4,7] ] -- Dodecahedron -- vertice of a dodecahedron of edge length 2/gold dodecahedronPoints :: RealFloat a => [Point3f a] dodecahedronPoints = [ Point3f 1 1 1 , Point3f 1 1 (-1) , Point3f 1 (-1) 1 , Point3f 1 (-1) (-1) , Point3f (-1) 1 1 , Point3f (-1) 1 (-1) , Point3f (-1) (-1) 1 , Point3f (-1) (-1) (-1) , Point3f 0 (1/gold) gold , Point3f 0 (1/gold) (-gold) , Point3f 0 (-1/gold) gold , Point3f 0 (-1/gold) (-gold) , Point3f (1/gold) gold 0 , Point3f (1/gold) (-gold) 0 , Point3f (-1/gold) gold 0 , Point3f (-1/gold) (-gold) 0 , Point3f gold 0 (1/gold) , Point3f gold 0 (-1/gold) , Point3f (-gold) 0 (1/gold) , Point3f (-gold) 0 (-1/gold) ] dodecahedronFaces :: [[Int]] dodecahedronFaces = [ [12,0,16,17,1] -- 0 , [0,8,10,2,16] -- 5 , [14,12,1,9,5] -- 10 , [14,5,19,18,4] -- 15 , [18,19,7,15,6] -- 20 , [7,11,3,13,15] -- 25 , [6,15,13,2,10] -- 30 , [2,13,3,17,16] -- 35 , [7,19,5,9,11] -- 40 , [0,12,14,4,8] -- 45 , [8,4,18,6,10] -- 50 , [1,17,3,11,9] -- 55 ] -- Rhombicosidodecahedron -- triangles which tips each touch the tip of a pentagon rhombicosidodecahedronTriangles :: [[Int]] rhombicosidodecahedronTriangles = [ [1,45,5] , [4,55,12] , [8,33,35] , [27,57,37] , [19,51,48] , [14,42,16] , [24,30,53] , [22,40,25] , [6,49,50] , [13,59,43] , [7,54,34] , [26,44,58] , [0,11,46] , [28,36,32] , [10,15,47] , [23,29,31] , [2,9,39] , [3,38,56] , [18,20,52] , [17,41,21] ] -- quads joining each 2 pentagons rhombicosidodecahedronQuads :: [[Int]] rhombicosidodecahedronQuads = [ [45,1,0,46] , [5,45,49,6] , [1,5,9,2] , [55,4,3,56] , [12,55,59,13] , [4,12,11,0] , [33,8,7,34] , [35,33,32,36] , [8,35,39,9] , [57,27,26,58] , [37,57,56,38] , [27,37,36,28] , [51,19,18,52] , [48,51,50,49] , [19,48,47,15] , [42,14,13,43] , [16,42,41,17] , [14,16,15,10] , [30,24,23,31] , [53,30,34,54] , [24,53,52,20] , [40,22,21,41] , [25,40,44,26] , [22,25,29,23] , [6,50,54,7] , [43,59,58,44] , [46,11,10,47] , [28,32,31,29] , [2,39,38,3] , [20,18,17,21] ] -- used to expands the faces of a dodecahedron of edge length 2/gold into a rhombicosidodecahedron magicTranslation :: RealFloat a => a magicTranslation = 1.1755705 -- re use dodecahedron's points -- take the 5 points of each face of the dodecahedron -- put them into a single list (length 12 * 5) -- translate to using the magic translation along the normal of their face -- -> rhombicosidodecahedron vertice stubRhombicosidodecahedronPoints :: RealFloat a => [Point3f a] stubRhombicosidodecahedronPoints = rhombicosidodecahedronPointsFactory 0 rhombicosidodecahedronPoints :: RealFloat a => [Point3f a] rhombicosidodecahedronPoints = rhombicosidodecahedronPointsFactory magicTranslation rhombicosidodecahedronPointsFactory :: RealFloat a => a -> [Point3f a] rhombicosidodecahedronPointsFactory expansionStep = foldr (++) [] $ map asList dodecahedronFaces where asList is = expandFace $ map (\i -> dodecahedronPoints !! i) is expandFace ps = map (add $ forceNorm expansionStep $ faceSum ps) ps faceSum ps = foldr add (Point3f 0 0 0) ps rhombicosidodecahedronFaces :: [[Int]] rhombicosidodecahedronFaces = rhombicosidodecahedronTriangles ++ rhombicosidodecahedronQuads ++ (chop 5 $ take 60 [0..]) -- pentagonal faces where toPoints (i,j,k) = [dodecahedronPoints !! i, dodecahedronPoints !! j, dodecahedronPoints !! k] -- Snub Dodecahedron -- used to expands the faces of a dodecahedron of edge length 2/gold into a rhombicosidodecahedron magicSnubTranslation :: RealFloat a => a magicSnubTranslation = 1.072163 -- used to rotate the pentagonal faces into a snub dodecahedron magicSnubRotation :: RealFloat a => a magicSnubRotation = 0.2287498 -- expand and rotate each face of the dodecahedron snubDodecahedronPoints :: RealFloat a => [Point3f a] snubDodecahedronPoints = foldr (++) [] $ map asList dodecahedronFaces where asList is = expandFace $ map (\i -> dodecahedronPoints !! i) is expandFace ps = map ((rotateFace ps ). (add $ times magicSnubTranslation $ faceNorm ps)) ps rotateFace ps = rotate magicSnubRotation $ faceNorm ps faceNorm ps = normalized $ foldr add (Point3f 0 0 0) ps -- re use rhombicosidodecahedronFaces as much as possible, just split the quads intro triangles snubDodecahedronFaces :: [[Int]] snubDodecahedronFaces = rhombicosidodecahedronTriangles ++ (concatMap split rhombicosidodecahedronQuads) ++ (chop 5 $ take 60 [0..]) -- pentagonal faces where split [i,j,k,l] = [[i,j,k],[i,k,l]] -- Pentagonal Hexecontahedron -- dual of snub -> convert faces to vertice pentagonalHexecontahedronPoints :: RealFloat a => [Point3f a] pentagonalHexecontahedronPoints = map (center . toPoints) snubDodecahedronFaces where toPoints (i:is) = (snubDodecahedronPoints !! i) : toPoints is toPoints [] = [] center ps = times ((/) 1 $ fromIntegral $ length ps) $ foldr add (Point3f 0 0 0) ps snubFaceCount = length snubDodecahedronFaces snubPentagonCount = 12 -- per dodecahedron origin snubTriangleCount = snubFaceCount - snubPentagonCount snubPentagons = drop snubTriangleCount snubDodecahedronFaces snubTriangles = take snubTriangleCount snubDodecahedronFaces pentagonalHexecontahedronFaces :: [[Int]] pentagonalHexecontahedronFaces = map toFaceIds stripsFromAllPentagons where toFaceIds l = map toFaceId l toFaceId indice = fromJust $ elemIndex indice snubDodecahedronFaces stripsFromAllPentagons :: [[[Int]]] stripsFromAllPentagons = concatMap stripsFromPentagon snubPentagons stripsFromPentagon :: [Int] -> [[[Int]]] stripsFromPentagon pentagonVerticeIds = map addPentagon $ map (findTriangleStrip snubTriangles (-1)) $ cyclicConsecutivePairs pentagonVerticeIds where addPentagon l = pentagonVerticeIds : l findTriangleStrip :: [[Int]] -> Int -> (Int, Int) -> [[Int]] findTriangleStrip triangles notK (i, j) = if triangle == [] then [] else triangle : findTriangleStrip triangles i (k, j) where triangle = findTriangle i j notK triangles k = head $ dropWhile (\e -> e == i) $ dropWhile (\e -> e == j) triangle findTriangle :: Int -> Int -> Int -> [[Int]] -> [Int] findTriangle i j notK triangles = if result == [] then [] else head result where result = filter (notElem notK) $ filter (elem i) $ filter (elem j) triangles -- icosahedron icosahedronPoints :: RealFloat a => [Point3f a] icosahedronPoints = [ Point3f 0 (1) gold , Point3f 0 (-1) gold , Point3f 0 (-1) (-gold) , Point3f 0 (1) (-gold) , Point3f (1) (gold) 0 , Point3f (-1) (gold) 0 , Point3f (-1) (-gold) 0 , Point3f (1) (-gold) 0 , Point3f (gold) 0 (1) , Point3f (gold) 0 (-1) , Point3f (-gold) 0 (-1) , Point3f (-gold) 0 (1) ] -- faces are pointing inward icosahedronFaces :: [[Int]] icosahedronFaces = [ [0,1,8] , [0,11,1] , [2,3,9] , [2,10,3] , [4,5,0] , [4,3,5] , [6,7,1] , [6,2,7] , [8,9,4] , [8,7,9] , [10,11,5] , [10,6,11] , [0,8,4] , [0,5,11] , [1,7,8] , [1,11,6] , [2,9,7] , [2,6,10] , [3,4,9] , [3,10,5] ] icosahedronRadius :: RealFloat a => a icosahedronRadius = sqrt(gold * gold + 1) -- floret tessellation of icosahedron magicAngle :: RealFloat a => a magicAngle = acos $ 3 / 14 * sqrt 21 magicScale :: RealFloat a => a magicScale = 2 / 21 * sqrt 21 magicRotate :: RealFloat a => Normal a -> Point3f a -> Point3f a magicRotate = rotate magicAngle -- push the vertex of the floret solids onto their bounding sphere floretPushing :: Bool floretPushing = False toFloretFace :: RealFloat a => [Point3f a] -> [[Point3f a]] toFloretFace [p0, p1, p2] = assert (n1 == n2 && n2 == n0) [ [p0, p3, p9, p5, p8] , [p1, p4, p9, p3, p6] , [p2, p5, p9, p4, p7] ] where n0 = norm p0 n1 = norm p1 n2 = norm p2 push = if floretPushing then forceNorm n0 else id p9 = push $ (1/3) `times` (p0 `add` p1 `add` p2) transform = times magicScale . (magicRotate $ normalized p9) p3 = push $ p0 `add` (transform $ vec p0 p1) p4 = push $ p1 `add` (transform $ vec p1 p2) p5 = push $ p2 `add` (transform $ vec p2 p0) p6 = push $ p1 `add` (transform $ vec p1 p0) p7 = push $ p2 `add` (transform $ vec p2 p1) p8 = push $ p0 `add` (transform $ vec p0 p2) thinFloretIco :: RealFloat a => [[Point3f a]] thinFloretIco = concatMap ((map $ take 4) . toFloretFace . idsToFace) icosahedronFaces where idsToFace [i,j,k] = [icosahedronPoints !! i, icosahedronPoints !! j, icosahedronPoints !! k] pentagonalFloretIco :: RealFloat a => [[Point3f a]] pentagonalFloretIco = concatMap (toFloretFace . idsToFace) icosahedronFaces where idsToFace [i,j,k] = [icosahedronPoints !! i, icosahedronPoints !! j, icosahedronPoints !! k] floretPoints :: RealFloat a => [[Point3f a]] -> [Point3f a] floretPoints floretIco = concatMap id floretIco floretFaces :: RealFloat a => [[Point3f a]] -> [[Int]] floretFaces floretIco = replaceWithId 0 floretIco where replaceWithId _ [] = [] replaceWithId n (face:faces) = take (length face) [n..] : (replaceWithId (n+length face) faces) thinFloretPoints :: RealFloat a => [Point3f a] thinFloretPoints = floretPoints thinFloretIco thinFloretFaces = floretFaces thinFloretIco pentaFloretPoints :: RealFloat a => [Point3f a] pentaFloretPoints = floretPoints pentagonalFloretIco pentaFloretFaces = floretFaces pentagonalFloretIco
makemeunsee/interpolateme
FloretSphere.hs
gpl-3.0
14,906
0
13
5,062
4,782
2,745
2,037
305
2
module Main (main) where import Prelude hiding (words) import Anagram import Control.Monad import Options.Applicative import Data.List hiding (words) import Text.Printf import Control.DeepSeq (force) import Control.Exception (evaluate) -- | Finds anagrams -- If words are given on the command-line anagrams are found for these -- words, printed to stdout and then the program exits. Otherwise -- the program will run in interactive mode continually prompting -- for new words to find anagrams for until the program is interrupted. main :: IO () main = do params <- execParser options ana <- anagrams <$> (getWords . dictFile) params >>= evaluate . force case words params of [] -> forever $ interactive ana xs -> xs `forM_` \ x -> printResult x (ana x) interactive :: (String -> [String]) -> IO () interactive ana = getLine >>= \ x -> printResult x (ana x) printResult :: String -> [String] -> IO () printResult x y = printf "%s -> %s\n" x $ intercalate "," y getWords :: FilePath -> IO [String] getWords p = lines <$> readFile p data Params = Params { words :: [String] , dictFile :: FilePath } paramsP :: Parser Params paramsP = Params <$> (many . strArgument) ( metavar "WORDS" <> help "The words to find anagrams for" ) <*> dictOption where dictOption = strOption ( long "dict" <> metavar "PATH" <> help "Path to the dictionary to use" ) <|> pure "/usr/share/dict/words" options :: ParserInfo Params options = info (helper <*> paramsP) ( fullDesc <> progDesc ( "Finds anagrams in WORDS. If WORDS are not present the program " ++ "runs in interactive mode." ) )
fredefox/anagrams
src/Main.hs
gpl-3.0
1,757
0
14
461
453
239
214
42
2
removeAt :: Int -> [a] -> (a, [a]) removeAt x xs = (xs !! (x-1), (take (x-1) xs)++(drop x xs))
carlosavieira/self-study
programming/Haskell/99 problems/solutions/20.hs
gpl-3.0
94
0
10
19
80
44
36
2
1
module Structural (rules) where import AbsAST rules = [ "(AdjCN * $1) -> $1" , "(AdvVP $1 *) -> $1" ]
cunger/mule
src/rules/Structural.hs
gpl-3.0
123
0
5
42
23
15
8
4
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} module Main (main) where import Control.Lens (view, _1, _2, _3, _4, _5) import Control.Monad (filterM, forM, forM_, when) import Data.Bool (bool) import qualified Data.ByteString.Char8 as BS import Data.Foldable (foldrM) import Data.Hashable (Hashable) import Data.List (isInfixOf, minimumBy, nub) import Data.Maybe (catMaybes, fromJust) import Data.Ord (comparing) import qualified Data.Vector.Mutable as VM import GHC.Generics (Generic) import System.Directory (getDirectoryContents) import System.FilePath ((</>)) import MLLabs.Types (Class (..), Dataset) cast :: Int -> Double cast = fromInteger . toInteger -- list of 10 tuples: subject, body, class (true -- nonspam) datasetRaw :: IO [[([Int], [Int], Bool)]] datasetRaw = do subdirs <- readDir resdir forM subdirs (\set -> mapM (readSourceFile set) =<< readDir (resdir </> set)) where resdir = "./resources/lab3/" readDir x = filter (\a -> a /= "." && a /= "..") <$> getDirectoryContents x readInt :: BS.ByteString -> Int readInt = fst . fromJust . BS.readInt readSourceFile set filePath = do let legit = "legit" `isInfixOf` filePath [header0,_,body0] <- BS.lines <$> BS.readFile (resdir </> set </> filePath) let header = map readInt $ tail $ BS.words header0 let body = map readInt $ BS.words body0 pure (header, body, legit) data EmailClass = Valid | Spam deriving (Show,Enum,Eq,Ord,Generic) instance Hashable EmailClass instance Class EmailClass where enumAll = [Valid, Spam] type Message = [Int] -- features... type MailDataset = Dataset Message EmailClass -- Transformed dataset split by training classes datasetSamples :: IO [MailDataset] datasetSamples = do raw <- datasetRaw let toClass = bool Spam Valid transform :: ([Int], [Int], Bool) -> (Message, EmailClass) transform (header,subj,c) = (header ++ subj, toClass c) pure $! map (map transform) $! raw data BayesClassifier label = BayesClassifier { fromBayes :: ![(label, (Double, VM.IOVector Double))] } bayesClassify :: (lbl -> Double) -> BayesClassifier lbl -> Message -> IO lbl bayesClassify penalty (BayesClassifier fromBayes) (nub -> message) = do pairs <- forM fromBayes $ \(c, (cprob, featprob)) -> do features <- forM message $ \i -> do e <- VM.read featprob i pure $ bool (Just e) Nothing (e == 0) pure (c, penalty c + log cprob + sum (map log $ catMaybes features)) pure $! fst $! minimumBy (comparing snd) pairs train :: (Ord lbl, Class lbl, Hashable lbl, Show lbl) => Double -> Dataset Message lbl -> IO (BayesClassifier lbl) train _ [] = error "can't train 0 samples" train maxCount dataset = do (freqs :: VM.IOVector Double) <- VM.replicate vecsize 0 forM_ (concatMap fst dataset) $ \word -> VM.modify freqs (+1) word BayesClassifier <$> (genBayes freqs) where wordsTotal :: Int wordsTotal = sum $ map (length . fst) dataset --vecsize = maximum (map (maximum . fst) dataset) + 1 vecsize = 30000 classes = nub $ map snd dataset n = length dataset genBayes freqs = forM classes $ \c -> do let related = filter ((== c) . snd) dataset priorRaw = cast . length $ related prior = priorRaw / cast n (accumulator :: VM.IOVector Double) <- VM.replicate vecsize 0 forM_ (concatMap fst related) $ \word -> do count <- VM.read freqs word --when (count <= maxCount) $ VM.modify accumulator (+1) word --when (count <= maxCount) $ VM.modify accumulator (const 1) word when (count <= maxCount) $ VM.modify accumulator (const count) word vecsumTotal <- foldrM (\i s -> (+s) <$> VM.read accumulator i) 0 [0..(vecsize-1)] forM_ [0..(vecsize-1)] $ VM.modify accumulator (/ vecsumTotal) pure (c, (prior, accumulator)) trainAndTestSets :: [Dataset obj lbl] -> [(Dataset obj lbl, Dataset obj lbl)] trainAndTestSets xs = flip map [0..length xs-1] $ \i -> let (a, b:c) = splitAt i xs in (concat (a ++ c), b) accuracy :: (Eq lbl, Monad m) => (obj -> m lbl) -> Dataset obj lbl -> m Double accuracy algo testData = do correct <- count (\(x,y) -> (== y) <$> algo x) testData pure $ fromIntegral correct / fromIntegral total where total = length testData count p xs = length <$> filterM p xs exec :: Double -> Double -> IO () exec pen maxCount = do let penalty :: EmailClass -> Double penalty Valid = pen penalty Spam = 0 putStrLn "Reading" --dta <- shuffleM =<< (concat <$> datasetSamples) dta <- datasetSamples --putStrLn $ "Calculating scores, test samples: " ++ show (length dta) --scores <- forM (kfold 10 dta) $ \(trainSet, testSet) -> do scores <- forM (trainAndTestSets dta) $ \(trainSet, testSet) -> do let spams = map fst . filter ((== Spam) . snd) $ testSet let valids = map fst . filter ((== Valid) . snd) $ testSet let sumpair :: (Int,Int) -> (Int,Int) -> (Int,Int) sumpair (a,b) (c,d) = (a+c,b+d) classifier <- train maxCount trainSet acc <- accuracy (bayesClassify penalty classifier) testSet (spamValid, spamSpam) <- foldr1 sumpair <$> forM spams (\spam -> do cls <- bayesClassify penalty classifier spam pure $ if cls == Valid then (1,0) else (0,1)) (validValid, validSpam) <- foldr1 sumpair <$> forM valids (\valid -> do cls <- bayesClassify penalty classifier valid pure $ if cls == Valid then (1,0) else (0,1)) -- putStrLn "-------------------" -- putStrLn $ "accuracy: " ++ show acc -- putStrLn $ "validValid: " ++ show validValid -- putStrLn $ "validSpam: " ++ show validSpam -- putStrLn $ "spamValid: " ++ show spamValid -- putStrLn $ "spamSpam: " ++ show spamSpam pure (acc,validValid,validSpam,spamValid,spamSpam) --putStrLn "Scores: " >> mapM_ print scores let average xs = sum xs / cast (length xs) let vv = sum $ map (view _2) scores let vs = sum $ map (view _3) scores let sv = sum $ map (view _4) scores let ss = sum $ map (view _5) scores let precision = cast ss / cast (ss + vs) let recall = cast ss / cast (sv + ss) let f1 = 2 * precision * recall / (precision + recall) putStrLn $ "validValid: " ++ show vv putStrLn $ "validSpam: " ++ show vs putStrLn $ "spamValid: " ++ show sv putStrLn $ "spamSpam: " ++ show ss putStrLn $ "f1: " ++ show f1 putStrLn $ "Accuracy avg: " ++ show (average $ map (view _1) scores) main = forM_ [0,2..10] $ \pen -> forM_ [1/0] $ \maxCount -> putStrLn "---------" >> print (pen, maxCount) >> exec pen maxCount
zhenyavinogradov/ml-labs
src/Lab3/Main.hs
gpl-3.0
7,432
0
21
2,090
2,505
1,301
1,204
146
4
module Constant where -- Exercise: Constant Instance -- Write an Applicative instance for Constant. newtype Constant a b = Constant { getConstant :: a } deriving (Eq, Ord, Show) instance Functor (Constant a) where fmap f (Constant a) = Constant a instance Monoid a => Applicative (Constant a) where pure _ = Constant mempty (Constant f) <*> (Constant a) = Constant a
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
Applicative/src/Constant.hs
gpl-3.0
382
0
8
77
127
67
60
7
0
{-# OPTIONS_GHC -optc-DDBUS_API_SUBJECT_TO_CHANGE #-} {-# LINE 1 "DBus/Message.hsc" #-} {-# LANGUAGE PatternSignatures, TypeSynonymInstances, FlexibleInstances #-} {-# LINE 2 "DBus/Message.hsc" #-} {-# OPTIONS -fglasgow-exts #-} -- HDBus -- Haskell bindings for D-Bus. -- Copyright (C) 2006 Evan Martin <[email protected]> {-# LINE 7 "DBus/Message.hsc" #-} {-# LINE 8 "DBus/Message.hsc" #-} module DBus.Message ( -- * Messages Message, newSignal, newMethodCall, -- * Accessors Type(..), getType, getSignature, getPath, getInterface, getMember, getErrorName, getDestination, getSender, -- * Arguments Arg(..), args, addArgs, signature, stringSig, variantSig {- Arg(..), args, addArgs, -- ** Dictionaries -- | D-Bus functions that expect a dictionary must be passed a 'Dict', -- which is trivially constructable from an appropriate list. Dict, dict, -- ** Variants -- | Some D-Bus functions allow variants, which are similar to -- 'Data.Dynamic' dynamics but restricted to D-Bus data types. Variant, variant -} ) where import Control.Monad (when) import Data.Int import Data.Word import Data.Char import Data.Dynamic import Foreign import Foreign.C.String import Foreign.C.Types (CInt) import System.IO.Unsafe import DBus.Internal import DBus.Shared import qualified Data.ByteString as B import qualified Data.ByteString.Internal as B type Message = ForeignPtr MessageTag foreign import ccall unsafe "dbus_message_new_signal" message_new_signal :: CString -> CString -> CString -> IO MessageP foreign import ccall unsafe "dbus_message_new_method_call" message_new_method_call :: CString -> CString -> CString -> CString -> IO MessageP newSignal :: PathName -- ^Path. -> InterfaceName -- ^Interface. -> String -- ^Method name. -> IO Message newSignal path iface name = withCString path $ \cpath -> withCString iface $ \ciface -> withCString name $ \cname -> do msg <- message_new_signal cpath ciface cname messagePToMessage msg False newMethodCall :: ServiceName -- ^Bus name. -> PathName -- ^Path. -> InterfaceName -- ^Interface. -> String -- ^Method name. -> IO Message newMethodCall busname path iface method = withCString busname $ \cbusname -> withCString path $ \cpath -> withCString iface $ \ciface -> withCString method $ \cmethod -> do msg <- message_new_method_call cbusname cpath ciface cmethod messagePToMessage msg False data Type = MethodCall | MethodReturn | Error | Signal | Other Int deriving Show instance Enum Type where toEnum 1 = MethodCall {-# LINE 87 "DBus/Message.hsc" #-} toEnum 2 = MethodReturn {-# LINE 88 "DBus/Message.hsc" #-} toEnum 3 = Error {-# LINE 89 "DBus/Message.hsc" #-} toEnum 4 = Signal {-# LINE 90 "DBus/Message.hsc" #-} toEnum x = Other x fromEnum = error "not implemented" foreign import ccall unsafe "dbus_message_get_type" message_get_type :: MessageP -> IO Int getType :: Message -> IO Type getType msg = withForeignPtr msg message_get_type >>= return . toEnum getOptionalString :: (MessageP -> IO CString) -> Message -> IO (Maybe String) getOptionalString getter msg = withForeignPtr msg getter >>= maybePeek peekCString foreign import ccall unsafe dbus_message_get_path :: MessageP -> IO CString foreign import ccall unsafe dbus_message_get_interface :: MessageP -> IO CString foreign import ccall unsafe dbus_message_get_member :: MessageP -> IO CString foreign import ccall unsafe dbus_message_get_error_name :: MessageP -> IO CString foreign import ccall unsafe dbus_message_get_sender :: MessageP -> IO CString foreign import ccall unsafe dbus_message_get_signature :: MessageP -> IO CString foreign import ccall unsafe dbus_message_get_destination :: MessageP -> IO CString getPath, getInterface, getMember, getErrorName, getDestination, getSender :: Message -> IO (Maybe String) getPath = getOptionalString dbus_message_get_path getInterface = getOptionalString dbus_message_get_interface getMember = getOptionalString dbus_message_get_member getErrorName = getOptionalString dbus_message_get_error_name getDestination = getOptionalString dbus_message_get_destination getSender = getOptionalString dbus_message_get_sender getSignature :: Message -> IO String getSignature msg = withForeignPtr msg dbus_message_get_signature >>= peekCString type IterTag = () type Iter = Ptr IterTag data Arg = Byte Word8 | Boolean Bool | Int16 Int16 | Word16 Word16 | Int32 Int32 | Word32 Word32 | Int64 Int64 | Word64 Word64 | Double Double | String String | ObjectPath {- ? -} | TypeSignature {- ? -} | Array String [Arg] | Variant Arg | Struct [Arg] | DictEntry Arg Arg | ByteString B.ByteString | Invalid deriving (Show,Read,Typeable) stringSig :: String stringSig = signature String{} variantSig = signature Variant{} signature Byte{} = "y" {-# LINE 136 "DBus/Message.hsc" #-} signature Boolean{} = "b" {-# LINE 137 "DBus/Message.hsc" #-} signature Int32{} = "i" {-# LINE 138 "DBus/Message.hsc" #-} signature (Array sig _) = "a" ++ sig {-# LINE 139 "DBus/Message.hsc" #-} signature ByteString{} = signature (Array (signature (Byte 0)) []) signature (DictEntry argA argB) = "{"++signature argA ++ signature argB ++ "}" signature Variant{} = "v" {-# LINE 142 "DBus/Message.hsc" #-} signature String{} = "s" {-# LINE 143 "DBus/Message.hsc" #-} signature (Struct args) = "{" ++ concatMap signature args ++ "}" signature arg = error $ "DBus.Message.signature: " ++ show arg decodeArgs iter = let loop = unsafeInterleaveIO $ do arg <- decodeArg iter has_next <- message_iter_next iter if has_next then fmap (arg:) loop else return [arg] in loop decodeArg iter = do arg_type <- message_iter_get_arg_type iter case arg_type of 105 -> fmap Int32 getBasic {-# LINE 158 "DBus/Message.hsc" #-} 117 -> fmap Word32 getBasic {-# LINE 159 "DBus/Message.hsc" #-} 115 -> fmap String (getBasic >>= peekCString) {-# LINE 160 "DBus/Message.hsc" #-} 97 -> decodeArray iter {-# LINE 161 "DBus/Message.hsc" #-} 98-> fmap Boolean getBasic {-# LINE 162 "DBus/Message.hsc" #-} 0-> return Invalid {-# LINE 163 "DBus/Message.hsc" #-} 114 -> decodeStruct iter {-# LINE 164 "DBus/Message.hsc" #-} _ -> error $ "Unknown argument type: " ++ show arg_type ++ " ("++show (chr arg_type)++")" where getBasic :: Storable a => IO a getBasic = alloca $ \ptr -> do message_iter_get_basic iter ptr peek ptr decodeArray iter = withIter $ \sub -> do message_iter_recurse iter sub len <- message_iter_get_array_len iter elt_type <- message_iter_get_element_type iter case elt_type of 121 -> if len > 0 then decodeByteArray iter {-# LINE 177 "DBus/Message.hsc" #-} else return $ ByteString B.empty _other -> withIter $ \sub -> do message_iter_recurse iter sub sig <- getIterSignature sub lst <- if len > 0 then getArray sub else return [] return $ Array sig lst where getArray sub = do x <- decodeArg sub has_next <- message_iter_next sub if has_next then do xs <- getArray sub return (x:xs) else return [x] decodeByteArray iter = alloca $ \elts_ptr -> alloca $ \n_ptr -> do message_iter_get_fixed_array iter elts_ptr n_ptr byte_ptr <- peek elts_ptr len <- peek n_ptr fptr <- newForeignPtr_ byte_ptr return $ ByteString $ B.fromForeignPtr fptr 0 (fromIntegral len) decodeStruct iter = withIter $ \sub -> do message_iter_recurse iter sub let fetch = do arg <- decodeArg sub has_next <- message_iter_next sub if has_next then fmap (arg:) fetch else return [arg] fmap Struct fetch encodeArg iter arg = case arg of Int32 i32 -> putSimple 105 i32 {-# LINE 211 "DBus/Message.hsc" #-} Word32 u32 -> putSimple 117 u32 {-# LINE 212 "DBus/Message.hsc" #-} String str -> withCString str $ \cstr -> putSimple 115 cstr {-# LINE 213 "DBus/Message.hsc" #-} Array sig lst -> encodeArray iter sig lst DictEntry argA argB -> encodeDict iter argA argB _ -> error $ "Can't encode argument: " ++ show arg where putSimple ty val = with val $ putBasic iter ty encodeArray iter sig lst = withCString sig $ \csig -> withContainer iter 97 csig $ \sub -> {-# LINE 221 "DBus/Message.hsc" #-} mapM_ (encodeArg sub) lst encodeDict iter argA argB = withContainer iter 101 nullPtr $ \sub -> {-# LINE 225 "DBus/Message.hsc" #-} do message_iter_recurse iter sub encodeArg sub argA encodeArg sub argB {- class Show a => Arg a where toIter :: a -> Iter -> IO () fromIter :: Iter -> IO a signature :: a -> String -- for collection types, this does from/to inside the collection's iter toIterInternal :: a -> Iter -> IO () toIterInternal = toIter fromIterInternal :: Iter -> IO a fromIterInternal = fromIter assertArgType iter expected_type = do arg_type <- message_iter_get_arg_type iter when (arg_type /= expected_type) $ fail $ "Expected arg type " ++ show expected_type ++ " but got " ++ show arg_type -} putBasic iter typ val = catchOom (message_iter_append_basic iter typ val) withContainer iter typ sig f = withIter $ \sub -> do catchOom $ (message_iter_open_container iter typ sig sub) f sub catchOom $ (message_iter_close_container iter sub) {- instance Arg () where toIter _ _ = return () fromIter _ = return () signature _ = "()" -- not really correct, but we should never need this. instance Arg String where fromIter iter = do assertArgType iter #{const DBUS_TYPE_STRING} alloca $ \str -> do message_iter_get_basic iter str peek str >>= peekCString toIter arg iter = -- we need a pointer to a CString (which itself is Ptr CChar) withCString arg $ \cstr -> with cstr $ putBasic iter #{const DBUS_TYPE_STRING} signature _ = "s" instance Arg Int32 where fromIter iter = do assertArgType iter #{const DBUS_TYPE_INT32} alloca $ \int -> do message_iter_get_basic iter int peek int toIter arg iter = with arg $ putBasic iter #{const DBUS_TYPE_INT32} signature _ = "i" instance Arg Word32 where fromIter iter = do assertArgType iter #{const DBUS_TYPE_UINT32} alloca $ \int -> do message_iter_get_basic iter int peek int toIter arg iter = with arg $ putBasic iter #{const DBUS_TYPE_UINT32} signature _ = "u" data Variant = forall a. Arg a => Variant a variant :: Arg a => a -> Variant variant = Variant instance Show Variant where show (Variant a) = "[variant]" ++ show a instance Arg Variant where fromIter iter = do assertArgType iter #{const DBUS_TYPE_VARIANT} elem_type <- message_iter_get_element_type iter withIter $ \sub -> do message_iter_recurse iter sub variantFromIterType sub elem_type where -- XXX there ought to be a more clever way to do this. variantFromIterType iter #{const DBUS_TYPE_STRING} = do (v :: String) <- fromIter iter; return $ Variant v variantFromIterType iter #{const DBUS_TYPE_INT32} = do (v :: Int32) <- fromIter iter; return $ Variant v variantFromIterType iter #{const DBUS_TYPE_UINT32} = do (v :: Word32) <- fromIter iter; return $ Variant v toIter (Variant arg) iter = do withIter $ \sub -> withCString (signature arg) $ \sig -> withContainer iter #{const DBUS_TYPE_VARIANT} sig $ \sub -> toIter arg sub where signature _ = "v" instance Arg a => Arg [a] where fromIter iter = do assertArgType iter #{const DBUS_TYPE_ARRAY} len <- message_iter_get_array_len iter if len > 0 then withIter $ \sub -> do message_iter_recurse iter sub array <- getArray sub return array else return [] where getArray sub = do x <- fromIter sub has_next <- message_iter_next sub if has_next then do xs <- getArray sub return (x:xs) else return [x] toIter arg iter = withIter $ \sub -> withCString (signature (undefined :: a)) $ \sig -> withContainer iter #{const DBUS_TYPE_ARRAY} sig $ \sub -> mapM_ (\v -> toIter v sub) arg signature a = "a" ++ signature (undefined :: a) --instance (Show a,Show b,Show c,Show d,Show e,Show f,Show g,Show h) => Show (a,b,c,d,e,f,g,h) where -- show _ = "[show not implemented]" newtype DictEntry a b = DictEntry (a,b) instance (Show a, Show b) => Show (DictEntry a b) where show (DictEntry pair) = "[DictEntry] " ++ show pair instance (Arg a, Arg b) => Arg (DictEntry a b) where toIter (DictEntry pair) iter = withContainer iter #{const DBUS_TYPE_DICT_ENTRY} nullPtr $ \sub -> do toIterInternal pair sub fromIter iter = do pair <- fromIter iter return (DictEntry pair) signature _ = "{" ++ signature (undefined :: a) ++ signature (undefined :: b) ++ "}" type Dict a b = [DictEntry a b] dict :: (Arg a, Arg b) => [(a, b)] -> Dict a b dict = map DictEntry -- tuple instances generated by codegen/TupleInstances.hs instance (Arg a,Arg b) => Arg (a,b) where toIter arg iter = withContainer iter #{const DBUS_TYPE_STRUCT} nullPtr $ \sub -> do toIterInternal arg sub fromIter iter = withIter $ \sub -> do message_iter_recurse iter sub fromIterInternal sub signature _ = "{" ++ signature (undefined :: a) ++ signature (undefined :: b) ++ "}" toIterInternal (a,b) iter = do toIter a iter; toIter b iter return () fromIterInternal iter = do a <- fromIter iter; next <- message_iter_next iter b <- fromIter iter; next <- message_iter_next iter return (a,b) instance (Arg a,Arg b,Arg c,Arg d,Arg e,Arg f,Arg g,Arg h) => Arg (a,b,c,d,e,f,g,h) where toIter arg iter = withContainer iter #{const DBUS_TYPE_STRUCT} nullPtr $ \sub -> do toIterInternal arg sub fromIter iter = withIter $ \sub -> do message_iter_recurse iter sub fromIterInternal sub signature _ = "{" ++ signature (undefined :: a) ++ signature (undefined :: b) ++ signature (undefined :: c) ++ signature (undefined :: d) ++ signature (undefined :: e) ++ signature (undefined :: f) ++ signature (undefined :: g) ++ signature (undefined :: h) ++ "}" toIterInternal (a,b,c,d,e,f,g,h) iter = do toIter a iter; toIter b iter; toIter c iter; toIter d iter; toIter e iter; toIter f iter; toIter g iter; toIter h iter return () fromIterInternal iter = do a <- fromIter iter; next <- message_iter_next iter b <- fromIter iter; next <- message_iter_next iter c <- fromIter iter; next <- message_iter_next iter d <- fromIter iter; next <- message_iter_next iter e <- fromIter iter; next <- message_iter_next iter f <- fromIter iter; next <- message_iter_next iter g <- fromIter iter; next <- message_iter_next iter h <- fromIter iter; next <- message_iter_next iter return (a,b,c,d,e,f,g,h) dynTag :: Dynamic -> Int32 dynTag x = case fromDynamic x of Just (i :: Int32) -> #{const DBUS_TYPE_INT32} Nothing -> case fromDynamic x of Just (word :: Word32) -> #{const DBUS_TYPE_UINT32} Nothing -> case fromDynamic x of Just (s :: String) -> #{const DBUS_TYPE_STRING} Nothing -> case fromDynamic x of Just (arr :: [Dynamic]) -> #{const DBUS_TYPE_ARRAY} Nothing -> case fromDynamic x of Just (a :: [Dynamic], b :: [Dynamic]) -> #{const DBUS_TYPE_DICT_ENTRY} Nothing -> case fromDynamic x of Just (b :: Bool) -> #{const DBUS_TYPE_BOOLEAN} Nothing -> #{const DBUS_TYPE_INVALID} instance Arg [Dynamic] where fromIter iter = let loop list False = return (reverse list) loop list True = do argt <- message_iter_get_arg_type iter let next x = do { valid <- message_iter_next iter; loop (x:list) valid } -- putStr $ "argt is " ++ show argt ++ "\n" case argt of #{const DBUS_TYPE_INVALID} -> return (reverse list) #{const DBUS_TYPE_UINT32} -> do (word :: Word32) <- fromIter iter next (toDyn word) #{const DBUS_TYPE_INT32} -> do (i :: Int32) <- fromIter iter next (toDyn i) #{const DBUS_TYPE_STRING} -> do (s :: String) <- fromIter iter next (toDyn s) #{const DBUS_TYPE_ARRAY} -> do (arr :: [[Dynamic]]) <- fromIter iter -- this could be better next (toDyn arr) #{const DBUS_TYPE_DICT_ENTRY} -> do (DictEntry (a :: [Dynamic], b :: [Dynamic])) <- fromIter iter next (toDyn (a,b)) #{const DBUS_TYPE_STRUCT} -> do withIter $ \sub -> do message_iter_recurse iter sub (inner :: [Dynamic]) <- fromIter sub next (toDyn inner) #{const DBUS_TYPE_BOOLEAN} -> do (b :: Bool) <- alloca $ \int -> do { message_iter_get_basic iter int; peek int } next (toDyn b) #{const DBUS_TYPE_VARIANT} -> do withIter $ \sub -> do message_iter_recurse iter sub (inner :: [Dynamic]) <- fromIter sub next (toDyn inner) in loop [] True toIter list iter = let loop [] iter = return () loop (x:xs) iter = do case dynTag x of #{const DBUS_TYPE_INVALID} -> fail $ "Unsupported dynamic value: " ++ show x #{const DBUS_TYPE_UINT32} -> toIter (fromDyn x (0 :: Word32)) iter #{const DBUS_TYPE_INT32} -> toIter (fromDyn x (0 :: Int32)) iter #{const DBUS_TYPE_STRING} -> toIter (fromDyn x ("" :: String)) iter loop xs iter in loop list iter signature _ = "d" -} foreign import ccall unsafe "dbus_message_iter_init" message_iter_init :: MessageP -> Iter -> IO Bool foreign import ccall unsafe "dbus_message_iter_init_append" message_iter_init_append :: MessageP -> Iter -> IO () foreign import ccall unsafe "dbus_message_iter_get_arg_type" message_iter_get_arg_type :: Iter -> IO Int foreign import ccall unsafe "dbus_message_iter_get_element_type" message_iter_get_element_type :: Iter -> IO Int foreign import ccall unsafe "dbus_message_iter_get_fixed_array" message_iter_get_fixed_array :: Iter -> Ptr a -> Ptr CInt -> IO () foreign import ccall unsafe "dbus_message_iter_get_signature" message_iter_get_signature :: Iter -> IO CString foreign import ccall unsafe "dbus_message_iter_get_basic" message_iter_get_basic :: Iter -> Ptr a -> IO () foreign import ccall unsafe "dbus_message_iter_get_array_len" message_iter_get_array_len :: Iter -> IO CInt foreign import ccall unsafe "dbus_message_iter_recurse" message_iter_recurse :: Iter -> Iter -> IO () foreign import ccall unsafe "dbus_message_iter_next" message_iter_next :: Iter -> IO Bool foreign import ccall unsafe "dbus_message_iter_append_basic" message_iter_append_basic :: Iter -> CInt -> Ptr a -> IO Bool foreign import ccall unsafe "dbus_message_iter_open_container" message_iter_open_container :: Iter -> CInt -> CString -> Iter -> IO Bool foreign import ccall unsafe "dbus_message_iter_close_container" message_iter_close_container :: Iter -> Iter -> IO Bool getIterSignature :: Iter -> IO String getIterSignature iter = message_iter_get_signature iter >>= peekCString withIter = allocaBytes (72) {-# LINE 510 "DBus/Message.hsc" #-} -- |Retrieve the arguments from a message. args :: Message -> [Arg] args msg = unsafePerformIO $ withForeignPtr msg $ \msg -> do withIter $ \iter -> do has_args <- message_iter_init msg iter if has_args then decodeArgs iter else return [] -- |Add arguments to a message. addArgs :: Message -> [Arg] -> IO () addArgs msg args = withForeignPtr msg $ \msg -> allocInit (72) (message_iter_init_append msg) $ \iter -> {-# LINE 525 "DBus/Message.hsc" #-} mapM_ (encodeArg iter) args -- vim: set ts=2 sw=2 tw=72 et ft=haskell :
hamaxx/unity-2d-for-xmonad
xmonad-files/DBus-0.4/dist/build/DBus/Message.hs
gpl-3.0
21,072
17
19
5,650
2,787
1,427
1,360
229
8
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} -- | Information cached by user. module RSCoin.User.Cache ( UserCache , mkUserCache , invalidateUserCache , getOwnersByTxId , getOwnersByTx , getOwnersByAddrid ) where import Control.Concurrent.STM (TVar, atomically, modifyTVar, newTVarIO, readTVarIO, writeTVar) import Control.Lens (view, _1) import Control.Monad.Trans (MonadIO (liftIO)) import qualified RSCoin.Core as C data CacheData = CacheData { cdMintettes :: (C.PeriodId, C.Mintettes) } deriving (Show) nullCacheData :: CacheData nullCacheData = CacheData { cdMintettes = (-1, []) } type UserCache = TVar CacheData instance Show UserCache where show _ = "UserCache" mkUserCache :: MonadIO m => m UserCache mkUserCache = liftIO $ newTVarIO nullCacheData invalidateUserCache :: MonadIO m => UserCache -> m () invalidateUserCache = liftIO . atomically . flip writeTVar nullCacheData getMintettesList :: C.WorkMode m => Maybe UserCache -> C.PeriodId -> m [C.Mintette] getMintettesList maybeCache p = maybe loadAndCache return =<< tryCache maybeCache where tryCache Nothing = return Nothing tryCache (Just c) = do (storedPeriodId,storedMintettes) <- cdMintettes <$> liftIO (readTVarIO c) return $ if storedPeriodId == p then Just storedMintettes else Nothing loadAndCache = do loaded <- C.getMintettes case maybeCache of Nothing -> return () Just c -> liftIO . atomically $ modifyTVar c (\cd -> cd { cdMintettes = (p, loaded) }) return loaded getOwnersByTxId :: C.WorkMode m => Maybe UserCache -> C.PeriodId -> C.TransactionId -> m [(C.Mintette, C.MintetteId)] getOwnersByTxId maybeCache p tId = toOwners <$> getMintettesList maybeCache p where toOwners mts = map (\i -> (mts !! i, i)) $ C.owners mts tId getOwnersByTx :: C.WorkMode m => Maybe UserCache -> C.PeriodId -> C.Transaction -> m [(C.Mintette, C.MintetteId)] getOwnersByTx cache p = getOwnersByTxId cache p . C.hash getOwnersByAddrid :: C.WorkMode m => Maybe UserCache -> C.PeriodId -> C.AddrId -> m [(C.Mintette, C.MintetteId)] getOwnersByAddrid cache p = getOwnersByTxId cache p . view _1
input-output-hk/rscoin-haskell
src/RSCoin/User/Cache.hs
gpl-3.0
2,675
0
18
889
710
375
335
80
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.SQL.Users.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a user from a Cloud SQL instance. -- -- /See:/ <https://cloud.google.com/sql/docs/reference/latest Cloud SQL Administration API Reference> for @sql.users.delete@. module Network.Google.Resource.SQL.Users.Delete ( -- * REST Resource UsersDeleteResource -- * Creating a Request , usersDelete , UsersDelete -- * Request Lenses , udProject , udName , udHost , udInstance ) where import Network.Google.Prelude import Network.Google.SQLAdmin.Types -- | A resource alias for @sql.users.delete@ method which the -- 'UsersDelete' request conforms to. type UsersDeleteResource = "sql" :> "v1beta4" :> "projects" :> Capture "project" Text :> "instances" :> Capture "instance" Text :> "users" :> QueryParam "host" Text :> QueryParam "name" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Operation -- | Deletes a user from a Cloud SQL instance. -- -- /See:/ 'usersDelete' smart constructor. data UsersDelete = UsersDelete' { _udProject :: !Text , _udName :: !Text , _udHost :: !Text , _udInstance :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UsersDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udProject' -- -- * 'udName' -- -- * 'udHost' -- -- * 'udInstance' usersDelete :: Text -- ^ 'udProject' -> Text -- ^ 'udName' -> Text -- ^ 'udHost' -> Text -- ^ 'udInstance' -> UsersDelete usersDelete pUdProject_ pUdName_ pUdHost_ pUdInstance_ = UsersDelete' { _udProject = pUdProject_ , _udName = pUdName_ , _udHost = pUdHost_ , _udInstance = pUdInstance_ } -- | Project ID of the project that contains the instance. udProject :: Lens' UsersDelete Text udProject = lens _udProject (\ s a -> s{_udProject = a}) -- | Name of the user in the instance. udName :: Lens' UsersDelete Text udName = lens _udName (\ s a -> s{_udName = a}) -- | Host of the user in the instance. udHost :: Lens' UsersDelete Text udHost = lens _udHost (\ s a -> s{_udHost = a}) -- | Database instance ID. This does not include the project ID. udInstance :: Lens' UsersDelete Text udInstance = lens _udInstance (\ s a -> s{_udInstance = a}) instance GoogleRequest UsersDelete where type Rs UsersDelete = Operation type Scopes UsersDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/sqlservice.admin"] requestClient UsersDelete'{..} = go _udProject _udInstance (Just _udHost) (Just _udName) (Just AltJSON) sQLAdminService where go = buildClient (Proxy :: Proxy UsersDeleteResource) mempty
rueshyna/gogol
gogol-sqladmin/gen/Network/Google/Resource/SQL/Users/Delete.hs
mpl-2.0
3,739
0
17
973
550
325
225
83
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DoubleClickSearch.Conversion.UpdateAvailability -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the availabilities of a batch of floodlight activities in -- DoubleClick Search. -- -- /See:/ <https://developers.google.com/doubleclick-search/ DoubleClick Search API Reference> for @doubleclicksearch.conversion.updateAvailability@. module Network.Google.Resource.DoubleClickSearch.Conversion.UpdateAvailability ( -- * REST Resource ConversionUpdateAvailabilityResource -- * Creating a Request , conversionUpdateAvailability , ConversionUpdateAvailability -- * Request Lenses , cuaPayload ) where import Network.Google.DoubleClickSearch.Types import Network.Google.Prelude -- | A resource alias for @doubleclicksearch.conversion.updateAvailability@ method which the -- 'ConversionUpdateAvailability' request conforms to. type ConversionUpdateAvailabilityResource = "doubleclicksearch" :> "v2" :> "conversion" :> "updateAvailability" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] UpdateAvailabilityRequest :> Post '[JSON] UpdateAvailabilityResponse -- | Updates the availabilities of a batch of floodlight activities in -- DoubleClick Search. -- -- /See:/ 'conversionUpdateAvailability' smart constructor. newtype ConversionUpdateAvailability = ConversionUpdateAvailability' { _cuaPayload :: UpdateAvailabilityRequest } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ConversionUpdateAvailability' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cuaPayload' conversionUpdateAvailability :: UpdateAvailabilityRequest -- ^ 'cuaPayload' -> ConversionUpdateAvailability conversionUpdateAvailability pCuaPayload_ = ConversionUpdateAvailability' { _cuaPayload = pCuaPayload_ } -- | Multipart request metadata. cuaPayload :: Lens' ConversionUpdateAvailability UpdateAvailabilityRequest cuaPayload = lens _cuaPayload (\ s a -> s{_cuaPayload = a}) instance GoogleRequest ConversionUpdateAvailability where type Rs ConversionUpdateAvailability = UpdateAvailabilityResponse type Scopes ConversionUpdateAvailability = '["https://www.googleapis.com/auth/doubleclicksearch"] requestClient ConversionUpdateAvailability'{..} = go (Just AltJSON) _cuaPayload doubleClickSearchService where go = buildClient (Proxy :: Proxy ConversionUpdateAvailabilityResource) mempty
rueshyna/gogol
gogol-doubleclick-search/gen/Network/Google/Resource/DoubleClickSearch/Conversion/UpdateAvailability.hs
mpl-2.0
3,387
0
13
694
310
191
119
52
1
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..)) import System.Exit (ExitCode(..), exitWith) import qualified LinkedList as L exitProperly :: IO Counts -> IO () exitProperly m = do counts <- m exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess testCase :: String -> Assertion -> Test testCase label assertion = TestLabel label (TestCase assertion) main :: IO () main = exitProperly $ runTestTT $ TestList [ TestList listTests ] listTests :: [Test] listTests = [ testCase "constructor" $ do True @=? L.isNil L.nil 1 @=? L.datum one True @=? L.isNil (L.next one) 2 @=? L.datum two 1 @=? L.datum (L.next two) True @=? L.isNil (L.next $ L.next two) , testCase "toList" $ do ([] :: [Int]) @=? L.toList L.nil [1] @=? L.toList one [2, 1] @=? L.toList two , testCase "fromList" $ do True @=? L.isNil (L.fromList []) let one_a = L.fromList [1 :: Int] 1 @=? L.datum one_a True @=? L.isNil (L.next one_a) let two_a = L.fromList [2, 1 :: Int] 2 @=? L.datum two_a 1 @=? L.datum (L.next two_a) True @=? L.isNil (L.next $ L.next two_a) , testCase "reverseList" $ do True @=? L.isNil (L.reverseLinkedList L.nil) let one_r = L.reverseLinkedList one 1 @=? L.datum one_r True @=? L.isNil (L.next one_r) let two_r = L.reverseLinkedList two 1 @=? L.datum two_r 2 @=? L.datum (L.next two_r) True @=? L.isNil (L.next $ L.next two_r) let three_r = L.reverseLinkedList three 1 @=? L.datum three_r 2 @=? L.datum (L.next three_r) 3 @=? L.datum (L.next (L.next three_r)) , testCase "roundtrip" $ do ([] :: [Int]) @=? (L.toList . L.fromList) [] ([1] :: [Int]) @=? (L.toList . L.fromList) [1] ([1, 2] :: [Int]) @=? (L.toList . L.fromList) [1, 2] ([1..10] :: [Int]) @=? (L.toList . L.fromList) [1..10] ] where one = L.new (1 :: Int) L.nil two = L.new 2 one three = L.new 3 two
mscoutermarsh/exercism_coveralls
assignments/haskell/simple-linked-list/simple-linked-list_test.hs
agpl-3.0
1,977
0
15
477
982
486
496
55
2
{-# LANGUAGE OverloadedStrings #-} module Lang.SystemF.Infer.Render where import Lang.SystemF import Lang.SystemF.Infer import Lang.SystemF.Render import qualified Text.PrettyPrint.ANSI.Leijen as L import qualified Data.List.NonEmpty as NE ppInferError :: InferError -> L.Doc ppInferError e = case e of InvalidVar v d -> let detail = "index" L.<+> L.int v L.<+> "at depth" L.<+> L.int d in "There is no binder for the given index, namely:" <?> detail InvalidApp aie -> ppAppInferError aie NoUniversalType tp -> "Can't apply a type to a term without a universal type, namely:" <?> ppTyping tp InvalidTyVars vs d -> "Type annotation uses invalid type variables, namely:" <?> commaAnd (L.int <$> vs) ppAppInferError :: AppInferError -> L.Doc ppAppInferError e = case e of NoFun tp t -> let detail = ppTyping tp L.<> L.comma L.<+> "but expected a function with argument type" L.<+> ppType t in "Can't apply a term to a non-function type, namely:" <?> detail ParamTypeMismatch tye tya -> "Parameter type mismatch: " <?> d where d = "expected" L.<+> ppTypeSq tye L.<> ", actual" L.<+> ppTypeSq tya ppTypeSq :: Type -> L.Doc ppTypeSq = L.squotes . ppType ppTyping :: Typing -> L.Doc ppTyping (Typing t ty) = L.squotes (ppTerm t) L.<+> "typed as" L.<+> ppTypeSq ty -- | Add some more detail indented on a new line. (<?>) :: L.Doc -> L.Doc -> L.Doc title <?> detail = title L.<$> L.indent 4 detail commaAnd :: NE.NonEmpty L.Doc -> L.Doc commaAnd (d NE.:| ds) = case ds of [] -> d _ -> comma ds L.<+> "and" L.<+> d comma :: [L.Doc] -> L.Doc comma = L.cat . L.punctuate ", "
muesli4/systemf
src/Lang/SystemF/Infer/Render.hs
lgpl-3.0
1,798
0
16
497
519
266
253
39
4
main = do stdin <- getContents let floor = foldl changeFloor 0 stdin putStrLn $ "Santa is on floor " ++ show floor increment = '(' decrement = ')' changeFloor :: Int -> Char -> Int changeFloor currentFloor instruction | instruction == increment = currentFloor + 1 | instruction == decrement = currentFloor - 1 | otherwise = currentFloor
bennett000/advent-of-code
src/2015/1/a/hs/solution.hs
lgpl-3.0
363
0
10
85
116
55
61
11
1
{-# LANGUAGE OverloadedStrings, EmptyDataDecls, ScopedTypeVariables, TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving, DeriveDataTypeable #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} -- Bits.popCount only introduced in 7.6 {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Applicative and Monoid required < 7.9 module Development.NSIS.Sugar( Compressor(..), HKEY(..), MessageBoxType(..), Page(..), Level(..), Visibility(..), FileMode(..), SectionFlag(..), ShowWindow(..), FinishOptions(..), DetailsPrint(..), module Development.NSIS.Sugar, Label, SectionId ) where import Development.NSIS.Type import Data.Char import Data.List import Data.Maybe import Data.Monoid import Data.String import Data.Data import Data.Bits import Control.Applicative import Control.Monad import Control.Monad.Trans.State import Data.Generics.Uniplate.Data --------------------------------------------------------------------- -- INTERNALS data S = S {uniques :: Int ,stream :: [NSIS] ,scopes :: [[(String,(TypeRep,Val))]] -- nearest scope is here } -- | Monad in which installers are defined. A useful command to start with is 'section'. newtype Action a = Action (State S a) deriving (Functor, Monad, Applicative) -- | A 'Value', only used by 'Exp', which can be produced using 'return'. -- The @ty@ argument should be one of 'String', 'Int' or 'Bool'. newtype Value ty = Value {fromValue :: Val} tyString = typeOf (undefined :: String) tyInt = typeOf (undefined :: Int) unique :: Action Int unique = Action $ do s <- get put s{uniques = uniques s + 1} return $ uniques s var :: Action Var var = fmap Var unique newSectionId :: Action SectionId newSectionId = fmap SectionId unique val x = [Var_ x] lit x = [Literal x | x /= ""] -- | Create a new label, used with 'goto' and 'label' to write line jump based programming. -- Where possible you should use structured alternatives, such as 'iff', 'while' and 'loop'. -- Each created label must be used with one call to 'label', and any number of calls to -- 'goto'. As an example: -- -- @ -- abort <- 'newLabel' -- 'while' var $ do -- 'iff_' cond1 $ 'goto' abort -- 'iff_' cond2 $ 'goto' abort -- var '@=' 'strDrop' 1 var -- 'label' abort -- @ -- -- Note that the above example could have been written in a simpler manner with 'loop'. newLabel :: Action Label newLabel = fmap Label unique emit :: NSIS -> Action () emit x = Action $ modify $ \s -> s{stream = stream s ++ [x]} rval :: Exp a -> Action Var rval act = do (xs, res) <- capture act case res of _ | not $ null xs -> error $ "An R-value may not emit any statements: " ++ show xs Value [Var_ x] -> return x _ -> error $ "An R-value must be a single value, found: " ++ show (fromValue res) capture :: Action a -> Action ([NSIS], a) capture (Action act) = Action $ do s0 <- get put s0{stream=[]} res <- act s1 <- get put s1{stream=stream s0} return (stream s1, res) runAction :: Action () -> [NSIS] runAction (Action act) = stream $ execState act s0 where s0 = S 1 [] [("NSISDIR",(tyString,[Builtin "{NSISDIR}"])):[(x, (tyString, [Builtin x])) | x <- builtin]] builtin = words $ "ADMINTOOLS APPDATA CDBURN_AREA CMDLINE COMMONFILES COMMONFILES32 COMMONFILES64 COOKIES DESKTOP DOCUMENTS " ++ "EXEDIR EXEFILE EXEPATH FAVORITES FONTS HISTORY HWNDPARENT INSTDIR INTERNET_CACHE LANGUAGE LOCALAPPDATA " ++ "MUSIC NETHOOD OUTDIR PICTURES PLUGINSDIR PRINTHOOD PROFILE PROGRAMFILES PROGRAMFILES32 PROGRAMFILES64 " ++ "QUICKLAUNCH RECENT RESOURCES RESOURCES_LOCALIZED SENDTO SMPROGRAMS SMSTARTUP STARTMENU SYSDIR TEMP " ++ "TEMPLATES VIDEOS WINDIR" -- | Set all 'file' actions to automatically take 'NonFatal'. alwaysNonFatal :: Action () -> Action () alwaysNonFatal act = do (xs, _) <- capture act mapM_ emit $ transformBi f xs where f (File x) = File x{fileNonFatal=True} f x = x -- | The type of expressions - namely an 'Action' producing a 'Value'. There are instances -- for 'Num' and 'IsString', and turning on @{-\# LANGUAGE OverloadedStrings \#-}@ is -- strongly recommended. -- -- The 'fromString' function converts any embedded @$VAR@ into a variable lookup, which may refer to one of -- the builtin NSIS variables (e.g. @$SMPROGRAMS@, @$TEMP@, @$PROGRAMFILES@), or a named variable -- created with 'constant' or 'mutable'. The string @$$@ is used to escape @$@ values. -- Bracket the variables to put text characters afterwards (e.g. @$(SMPROGRAMS)XXX@). In contrast -- to standard strings, @\/@ is treated as @\\@ and @\/\/@ is treated as @\/@. Remember to escape any -- slashes occuring in URLs. -- -- If the string is @'Exp' 'String'@ then any 'Int' variables used will be automatically shown (see 'strShow'). -- If the string is @'Exp' ty@ then it must be of the form @\"$VAR\"@ where @$VAR@ is a variable of type @ty@. -- -- The 'Eq' and 'Ord' instances for 'Exp' throw errors for all comparisons (use '%==', '%<=' etc), -- but 'min' and 'max' are defined. The 'Num' (arithmetic) and 'Monoid' (string concatenation) instances are both -- fully implemented. From 'Integral' and 'Fractional', only '/', 'mod' and 'div' are implemented, and -- all as integer arithmetic. No functions from 'Enum' or 'Real' are implemented. -- -- When using a single expression multiple times, to ensure it is not evaluated -- repeatedly, use 'share'. type Exp ty = Action (Value ty) instance forall a . Typeable a => IsString (Exp a) where fromString o = do scopes <- Action $ gets scopes let rty = typeOf (undefined :: a) let grab good name = case lookup name $ concat scopes of Nothing -> error $ "Couldn't find variable, $" ++ name ++ ", in " ++ show o Just (ty,y) | ty `notElem` good -> error $ "Type mismatch, $" ++ name ++ " has " ++ show ty ++ ", but you want one of " ++ show good ++ ", in " ++ show o | otherwise -> y -- "$VAR" permits any type, everything else requires string case parseString o of [Right var] -> return $ Value $ grab [rty] var _ | rty /= tyString -> error $ "Cannot use concatenated variables/literals to produce anything other than String, but you tried " ++ show rty ++ ", in " ++ show o xs -> fmap (Value . fromValue) $ strConcat $ flip map xs $ \i -> return $ Value $ case i of Left x -> lit x Right name -> grab [tyString,tyInt] name parseString :: String -> [Either String String] parseString "" = [] parseString ('/':'/':xs) = Left "/" : parseString xs parseString ('/':xs) = Left "\\" : parseString xs parseString ('$':'$':xs) = Left "$" : parseString xs parseString ('$':'(':xs) = Right a : parseString (drop 1 b) where (a,b) = break (== ')') xs parseString ('$':xs) = Right a : parseString b where (a,b) = span isAlphaNum xs parseString (x:xs) = Left [x] : parseString xs instance Show (Exp a) where show _ = error "show is not available for Exp" instance Eq (Exp a) where _ == _ = error "(==) is not available for Exp, try (%==) instead" instance Num (Exp Int) where fromInteger = return . Value . lit . show (+) = intOp "+" (*) = intOp "*" (-) = intOp "-" abs a = share a $ \a -> a %< 0 ? (negate a, a) signum a = share a $ \a -> a %== 0 ? (0, a %< 0 ? (-1, 1)) instance Integral (Exp Int) where mod = intOp "%" toInteger = error "toInteger is not available for Exp" div = intOp "/" quotRem = error "quotRem is not available for Exp" instance Enum (Exp Int) where toEnum = error "toEnum is not available for Exp" fromEnum = error "toEnum is not available for Exp" instance Real (Exp Int) where toRational = error "toRational is not available for Exp" instance Ord (Exp Int) where compare = error "compare is not available for Exp" min a b = share a $ \a -> share b $ \b -> a %<= b ? (a, b) max a b = share a $ \a -> share b $ \b -> a %<= b ? (b, a) instance Fractional (Exp Int) where fromRational = error "fromRational is not available for Exp, only Int is supported" (/) = intOp "/" instance Monoid (Exp String) where mempty = fromString "" mappend x y = mconcat [x,y] mconcat xs = do xs <- sequence xs return $ Value $ f $ concatMap fromValue xs where f (Literal "":xs) = f xs f (Literal x:Literal y:zs) = f $ Literal (x++y) : zs f (x:xs) = x : f xs f [] = [] instance Bits (Exp Int) where (.&.) = intOp "&" (.|.) = intOp "|" xor = intOp "^" complement a = intOp "~" a 0 shiftL a b = intOp "<<" a (fromInteger $ toInteger b) shiftR a b = intOp ">>" a (fromInteger $ toInteger b) rotate = error "rotate is not available for Exp" bitSize = error "bitSize is not available for Exp" isSigned _ = True testBit i = error "testBit is not available for Exp" bit i = fromInteger $ toInteger (bit i :: Int) intOp :: String -> Exp Int -> Exp Int -> Exp Int intOp cmd x y = do Value x <- x; Value y <- y; v <- var; emit $ IntOp v x cmd y; return $ Value $ val v emit1 :: (Val -> NSIS) -> Exp a -> Action () emit1 f x1 = do Value x1 <- x1; emit $ f x1 emit2 :: (Val -> Val -> NSIS) -> Exp a -> Exp b -> Action () emit2 f x1 x2 = do Value x1 <- x1; Value x2 <- x2; emit $ f x1 x2 emit3 :: (Val -> Val -> Val -> NSIS) -> Exp a -> Exp b -> Exp c -> Action () emit3 f x1 x2 x3 = do Value x1 <- x1; Value x2 <- x2; Value x3 <- x3; emit $ f x1 x2 x3 infix 1 @= -- | Assign a value to a mutable variable. The variable must have been originally created with -- 'mutable' or 'mutable_', or there will be an error when generating the install file. (@=) :: Exp t -> Exp t -> Action () (@=) v w = do v <- rval v; Value w <- w; emit $ Assign v w -- | Introduce a variable scope. Scopes are automatically introduced by operations -- such as 'iff', 'loop', 'while' etc. Inside a scope you may define new variables -- whose names may clash with variables outside the scope, but the local versions will be used. -- -- If you have any non-evaluated expressions, before introducing any potentially clashing -- variables in the scope you should 'share' them or use 'constant_' on them. For example: -- -- @ -- operate x = do -- x <- 'constant_' x -- 'scope' $ do -- 'constant' \"TEST\" 0 -- @ -- -- It is important to turn @x@ into a 'constant_' before defining a new constant @$TEST@, since -- if @x@ refers to @$TEST@ after the new definition, it will pick up the wrong variable. scope :: Action a -> Action a scope (Action act) = Action $ do s0 <- get put s0{scopes=[] : scopes s0} res <- act modify $ \s -> s{scopes = scopes s0} return res addScope :: forall t . Typeable t => String -> Value t -> Action () addScope name v = Action $ modify $ \s -> let now:rest = scopes s in if name `elem` map fst now then error $ "Defined twice in one scope, " ++ name else s{scopes=((name,(typeOf (undefined :: t), fromValue v)):now):rest} -- | Create a mutable variable a name, which can be modified with '@='. -- After defining the expression, you can refer to it with @$NAME@ in a 'String'. -- To introduce a new scope, see 'scope'. -- -- @ -- h <- 'mutable' \"HELLO\" \"Hello World\" -- \"$HELLO\" '@=' \"$HELLO!\" -- h '@=' \"$HELLO!\" -- equivalent to the above -- 'alert' \"$HELLO\" -- with 2 exclamation marks -- @ mutable :: Typeable t => String -> Exp t -> Action (Exp t) mutable name x = do v <- mutable_ x vv <- v addScope name vv return v -- | Create an unnamed mutable variable, which can be modified with '@='. -- -- @ -- h <- 'mutable' \"Hello World\" -- h '@=' 'h' '&' \"!\" -- 'alert' h -- @ mutable_ :: Exp t -> Action (Exp t) mutable_ x = do v <- var let v2 = return $ Value $ val v v2 @= x return v2 -- | Create a constant with a name, ensuring the expression is shared. -- After defining the expression, you can refer to it with @$NAME@ in a 'String'. -- To introduce a new scope, see 'scope'. -- -- @ -- 'constant' \"HELLO\" \"Hello World\" -- 'alert' \"$HELLO!\" -- @ constant :: Typeable t => String -> Exp t -> Action (Exp t) constant name x = do x <- constant_ x; xx <- x; addScope name xx; return x -- | Create a constant with no name, ensuring the expression is shared. -- Equivalent to @'share' 'return'@. constant_ :: Exp t -> Action (Exp t) constant_ x = do -- either the expression is entirely constant, or has mutable variables inside it Value x <- x if null [() | Var_{} <- x] then -- if it's totally constant, we want to leave it that way so it works in non-eval settings (e.g. file) return $ return $ Value x else do -- if it's mutable, we want to share the value, but also snapshot it so that the mutable variables -- don't change afterwards v <- var return (Value $ val v) @= return (Value x) -- add the Literal so that assignment throws an error in future return $ return $ Value [Var_ v, Literal ""] -- | The 'Exp' language is call-by-name, meaning you must use share to avoid evaluating an exression -- multiple times. Using 'share', if the expression has any side effects -- they will be run immediately, but not on subsequent uses. When defining functions operating on -- 'Exp', if you use the same input expression twice, you should share it. For example: -- -- @ -- strPalindrom x = 'share' x $ \\x -> x '%==' strReverse x -- @ -- -- If the expression was not shared, and @x@ read from a file, then the file would be read twice. share :: Exp t -> (Exp t -> Action a) -> Action a share v act = do v <- constant_ v; act v -- | Versions of 'mutable' and 'constant' restricted to 'Exp' 'Int', used to avoid -- ambiguous type errors. mutableInt, constantInt :: String -> Exp Int -> Action (Exp Int) mutableInt = mutable constantInt = constant -- | Versions of 'mutable_' and 'constant_' restricted to 'Exp' 'Int', used to avoid -- ambiguous type errors. mutableInt_, constantInt_ :: Exp Int -> Action (Exp Int) mutableInt_ = mutable_ constantInt_ = constant_ -- | Versions of 'mutable' and 'constant' restricted to 'Exp' 'String', used to avoid -- ambiguous type errors. mutableStr, constantStr :: String -> Exp String -> Action (Exp String) mutableStr = mutable constantStr = constant -- | Versions of 'mutable_' and 'constant_' restricted to 'Exp' 'String', used to avoid -- ambiguous type errors. mutableStr_, constantStr_ :: Exp String -> Action (Exp String) mutableStr_ = mutable_ constantStr_ = constant_ --------------------------------------------------------------------- -- EXPRESSION WRAPPERS -- | Perform string concatenation on a list of expressions. strConcat :: [Exp String] -> Exp String strConcat = mconcat -- | Boolean negation. not_ :: Exp Bool -> Exp Bool not_ a = a ? (false, true) infix 4 %==, %/=, %<=, %<, %>=, %> -- | The standard equality operators, lifted to 'Exp'. (%==), (%/=) :: Exp a -> Exp a -> Exp Bool (%==) a b = do Value a <- a Value b <- b v <- mutable_ false eq <- newLabel end <- newLabel emit $ StrCmpS a b eq end label eq v @= true label end v (%/=) a b = not_ (a %== b) -- | The standard comparison operators, lifted to 'Exp'. (%<=), (%<), (%>=), (%>) :: Exp Int -> Exp Int -> Exp Bool (%<=) = comp True True False (%<) = comp False True False (%>=) = comp True False True (%>) = comp False False True comp :: Bool -> Bool -> Bool -> Exp Int -> Exp Int -> Exp Bool comp eq lt gt a b = do Value a <- a Value b <- b v <- mutable_ false yes <- newLabel end <- newLabel let f b = if b then yes else end emit $ IntCmp a b (f eq) (f lt) (f gt) label yes v @= true label end v -- | Boolean constants corresponding to 'True' and 'False' true, false :: Exp Bool false = return $ Value [] true = return $ Value [Literal "1"] -- | Lift a 'Bool' into an 'Exp' bool :: Bool -> Exp Bool bool x = if x then true else false -- | Lift a 'String' into an 'Exp' str :: String -> Exp String str = return . Value . lit -- | Lift an 'Int' into an 'Exp' int :: Int -> Exp Int int = return . Value . lit . show -- | Erase the type of an Exp, only useful with 'plugin'. exp_ :: Exp a -> Exp () exp_ = fmap (Value . fromValue) -- | Pop a value off the stack, will set an error if there is nothing on the stack. -- Only useful with 'plugin'. pop :: Exp String pop = do v <- var; emit $ Pop v; return $ Value $ val v -- | Push a value onto the stack. Only useful with 'plugin'. push :: Exp a -> Action () push a = do Value a <- a; emit $ Push a -- | Call a plugin. If the arguments are of different types use 'exp_'. As an example: -- -- @ -- encrypt x = 'share' x $ \\x -> do -- 'plugin' \"Base64\" \"Encrypt\" ['exp_' x, 'exp_' $ 'strLength' x] -- @ -- -- The only thing to be careful about is that we use the @x@ parameter twice, so should 'share' -- it to ensure it is only evaluated once. plugin :: String -> String -> [Exp a] -> Action () plugin dll name args = do args <- mapM (fmap fromValue) args; emit $ Plugin dll name args -- | Add a plugin directory addPluginDir :: Exp String -> Action () addPluginDir a = do Value a <- a; emit $ AddPluginDir a -- | Return the length of a string, @strLength \"test\" '%==' 4@. strLength :: Exp String -> Exp Int strLength a = do Value a <- a; v <- var; emit $ StrLen v a; return $ Value $ val v -- | Take the first @n@ characters from a string, @strTake 2 \"test\" '%==' \"te\"@. strTake :: Exp Int -> Exp String -> Exp String strTake n x = do Value n <- n; Value x <- x; v <- var; emit $ StrCpy v x n (lit ""); return $ Value $ val v -- | Drop the first @n@ characters from a string, @strDrop 2 \"test\" '%==' \"st\"@. strDrop :: Exp Int -> Exp String -> Exp String strDrop n x = do Value n <- n; Value x <- x; v <- var; emit $ StrCpy v x (lit "") n; return $ Value $ val v -- | Gets the last write time of the file, you should only use the result to compare for equality -- with other results from 'getFileTime'. On failure the error flag is set. getFileTime :: Exp FilePath -> Exp String getFileTime x = do Value x <- x; v1 <- var; v2 <- var; emit $ GetFileTime x v1 v2; strConcat [return $ Value $ val v1, "#", return $ Value $ val v2] readRegStr :: HKEY -> Exp String -> Exp String -> Exp String readRegStr k a b = do v <- var; emit2 (ReadRegStr v k) a b; return $ Value $ val v deleteRegKey :: HKEY -> Exp String -> Action () deleteRegKey k = emit1 $ DeleteRegKey k deleteRegValue :: HKEY -> Exp String -> Exp String -> Action () deleteRegValue k = emit2 $ DeleteRegValue k envVar :: Exp String -> Exp String envVar a = do v <- var; emit1 (ReadEnvStr v) a; return $ Value $ val v --------------------------------------------------------------------- -- ATTRIBUTES data Attrib = Solid | Final | RebootOK | Silent | FilesOnly | NonFatal | Recursive | Unselected | Expanded | Description (Exp String) | Required | Target (Exp String) | Parameters (Exp String) | IconFile (Exp String) | IconIndex (Exp Int) | StartOptions String | KeyboardShortcut String | Id SectionId | Timeout Int | OName (Exp String) deriving Show --------------------------------------------------------------------- -- STATEMENT WRAPPERS -- | Define the location of a 'label', see 'newLabel' for details. This function will fail -- if the same 'Label' is passed to 'label' more than once. label :: Label -> Action () label lbl = emit $ Labeled lbl -- | Jump to a 'label', see 'newLabel' for details. This function will fail -- if 'label' is not used on the 'Label'. goto :: Label -> Action () goto lbl = emit $ Goto lbl infix 2 ? -- | An expression orientated version of 'iff', returns the first component if -- the first argument is 'true' or the second if it is 'false'. -- -- @ -- x '%==' 12 '?' (x, x '+' 5) -- @ (?) :: Exp Bool -> (Exp t, Exp t) -> Exp t (?) test (true, false) = do v <- var let v2 = return $ Value $ val v iff test (v2 @= true) (v2 @= false) v2 -- | Test a boolean expression, reunning the first action if it is 'true' and the second if it is 'false'. -- The appropriate branch action will be run within a 'scope'. See '?' for an expression orientated version. -- -- @ -- 'iff' (x '%==' 12) ('alert' \"is 12\") ('alert' \"is not 12\") -- @ iff :: Exp Bool -> Action () -> Action () -> Action () iff test true false = do thn <- newLabel els <- newLabel end <- newLabel Value t <- test emit $ StrCmpS t (lit "") thn els label thn scope false goto end label els scope true label end -- | A version of 'iff' where there is no else action. iff_ :: Exp Bool -> Action () -> Action () iff_ test true = iff test true (return ()) -- | A while loop, run the second argument while the first argument is true. -- The action is run in a 'scope'. See also 'loop'. -- -- @ -- x <- 'mutable_' x -- 'while' (x '%<' 10) $ do -- x '@=' x '+' 1 -- @ while :: Exp Bool -> Action () -> Action () while test act = do start <- newLabel label start iff_ test (scope act >> goto start) -- | A loop with a @break@ command. Run the action repeatedly until the breaking action -- is called. The action is run in a 'scope'. See also 'while'. -- -- @ -- x <- 'mutable_' x -- 'loop' $ \\break -> do -- 'iff_' (x '%>=' 10) break -- x '@=' x '+' 1 -- @ loop :: (Action () -> Action ()) -> Action () loop body = do end <- newLabel beg <- newLabel label beg scope $ body $ goto end goto beg label end -- | Run an intitial action, and if that action causes an error, run the second action. -- Unlike other programming languages, any uncaught errors are silently ignored. -- All actions are run in 'scope'. -- -- @ -- 'onError' ('exec' \"\\\"$WINDIR/notepad.exe\\\"\") ('alert' \"Failed to run notepad\") -- @ onError :: Action () -> Action () -> Action () onError act catch = do emit ClearErrors scope act end <- newLabel err <- newLabel emit $ IfErrors err end label err scope catch label end -- | Checks for existence of file(s) (which can be a wildcard, or a directory). -- If you want to check to see if a file is a directory, use @fileExists "DIRECTORY/*.*"@. -- -- > iff_ (fileExists "$WINDIR/notepad.exe") $ -- > messageBox [MB_OK] "notepad is installed" fileExists :: Exp FilePath -> Exp Bool fileExists x = do v <- mutable_ false Value x <- x yes <- newLabel end <- newLabel emit $ IfFileExists x yes end label yes v @= true label end v -- | Performs a search for filespec, running the action with each file found. -- If no files are found the error flag is set. Note that the filename output is without path. -- -- > findEach "$INSTDIR/*.txt" $ \x -> -- > detailPrint x -- -- If you jump from inside the loop to after the loop then you may leak a search handle. findEach :: Exp FilePath -> (Exp FilePath -> Action ()) -> Action () findEach spec act = do Value spec <- spec hdl <- var v <- var emit $ FindFirst hdl v spec while (return (Value $ val v)) $ do scope $ act $ return $ Value $ val v emit $ FindNext (val hdl) v emit $ FindClose $ val hdl infixr 5 & -- | Concatenate two strings, for example @\"$FOO\" & \"$BAR\"@ is equivalent -- to @\"$FOO$BAR\"@. (&) :: Exp String -> Exp String -> Exp String (&) a b = strConcat [a,b] -- | Convert an 'Int' to a 'String' by showing it. strShow :: Exp Int -> Exp String strShow = fmap (Value . fromValue) -- | Convert a 'String' to an 'Int', any errors are silently ignored. strRead :: Exp String -> Exp Int strRead = fmap (Value . fromValue) -- | Show an alert, equivalent to @messageBox [MB_ICONEXCLAMATION]@. alert :: Exp String -> Action () alert x = do _ <- messageBox [MB_ICONEXCLAMATION] x return () --------------------------------------------------------------------- -- SETTINGS WRAPPERS -- | Sets the name of the installer. The name is usually simply the product name such as \'MyApp\' or \'Company MyApp\'. -- -- > name "MyApp" name :: Exp String -> Action () name = emit1 Name -- | Specifies the output file that @MakeNSIS@ should write the installer to. -- This is just the file that MakeNSIS writes, it doesn't affect the contents of the installer. -- Usually should end with @.exe@. -- -- > outFile "installer.exe" outFile :: Exp FilePath -> Action () outFile = emit1 OutFile -- | Sets the output path (@$OUTDIR@) and creates it (recursively if necessary), if it does not exist. -- Must be a full pathname, usually is just @$INSTDIR@. -- -- > setOutPath "$INSTDIR" setOutPath :: Exp FilePath -> Action () setOutPath = emit1 SetOutPath -- | Sets the default installation directory. -- Note that the part of this string following the last @\\@ will be used if the user selects 'browse', and -- may be appended back on to the string at install time (to disable this, end the directory with a @\\@). -- If this doesn't make any sense, play around with the browse button a bit. -- -- > installDir "$PROGRAMFILES/MyApp" installDir :: Exp FilePath -> Action () installDir = emit1 InstallDir -- | Writes the uninstaller to the filename (and optionally path) specified. -- Only valid from within an install section, and requires that you have an 'uninstall' section in your script. -- You can call this one or more times to write out one or more copies of the uninstaller. -- -- > writeUninstaller "$INSTDIR/uninstaller.exe" writeUninstaller :: Exp FilePath -> Action () writeUninstaller = emit1 WriteUninstaller -- | Set the icon used for the installer\/uninstaller. -- -- > installIcon "$NSISDIR/Contrib/Graphics/Icons/modern-install.ico" installIcon, uninstallIcon :: Exp FilePath -> Action () installIcon = emit1 InstallIcon uninstallIcon = emit1 UninstallIcon -- | Set the image used for the header splash. Pass 'Nothing' to use the default header image. -- -- > headerImage $ Just "$NSISDIR/Contrib/Graphics/Header/win.bmp" headerImage :: Maybe (Exp FilePath) -> Action () headerImage Nothing = emit $ HeaderImage Nothing headerImage (Just x) = emit1 (HeaderImage . Just) x -- | Creates (recursively if necessary) the specified directory. Errors can be caught -- using 'onError'. You should always specify an absolute path. -- -- > createDirectory "$INSTDIR/some/directory" createDirectory :: Exp FilePath -> Action () createDirectory = emit1 CreateDirectory -- | This attribute tells the installer to check a string in the registry, -- and use it for the install dir if that string is valid. If this attribute is present, -- it will override the 'installDir' attribute if the registry key is valid, otherwise -- it will fall back to the 'installDir' default. When querying the registry, this command -- will automatically remove any quotes. If the string ends in \".exe\", it will automatically -- remove the filename component of the string (i.e. if the string is \"C:/program files/foo/foo.exe\", -- it will know to use \"C:/program files/foo\"). -- -- > installDirRegKey HKLM "Software/NSIS" "" -- > installDirRegKey HKLM "Software/ACME/Thingy" "InstallLocation" installDirRegKey :: HKEY -> Exp String -> Exp String -> Action () installDirRegKey k = emit2 $ InstallDirRegKey k -- | Execute the specified program and continue immediately. Note that the file specified -- must exist on the target system, not the compiling system. @$OUTDIR@ is used for the working -- directory. Errors can be caught using 'onError'. Note, if the command could have spaces, -- you should put it in quotes to delimit it from parameters. e.g.: @exec \"\\\"$INSTDIR/command.exe\\\" parameters\"@. -- If you don't put it in quotes it will not work on Windows 9x with or without parameters. -- -- > exec "\"$INSTDIR/someprogram.exe\"" -- > exec "\"$INSTDIR/someprogram.exe\" some parameters" exec :: Exp String -> Action () exec = emit1 Exec execWait :: Exp String -> Action () execWait = emit1 ExecWait execShell :: [ShowWindow] -> Exp String -> Action () execShell sw x = do Value x <- x let d = def{esCommand=x} emit $ ExecShell $ if null sw then d else d{esShow=last sw} sectionSetText :: SectionId -> Exp String -> Action () sectionSetText x = emit1 $ SectionSetText x sectionGetText :: SectionId -> Exp String sectionGetText x = do v <- var; emit $ SectionGetText x v; return $ Value $ val v data SectionFlag = SF_Selected | SF_SectionGroup | SF_SectionGroupEnd | SF_Bold | SF_ReadOnly | SF_Expand | SF_PartiallySelected deriving (Show,Data,Typeable,Read,Bounded,Enum,Eq,Ord) sectionGet :: SectionId -> SectionFlag -> Exp Bool sectionGet sec flag = do v <- var emit $ SectionGetFlags sec v let b = bit $ fromEnum flag :: Exp Int b %== (return (Value $ val v) .&. b) sectionSet :: SectionId -> SectionFlag -> Exp Bool -> Action () sectionSet sec flag set = do v <- var emit $ SectionGetFlags sec v v <- return (return $ Value $ val v :: Exp Int) iff set (emit1 (SectionSetFlags sec) $ setBit v (fromEnum flag)) (emit1 (SectionSetFlags sec) $ clearBit v (fromEnum flag)) -- don't want to accidentally dupe the message box, so make it in Action Exp messageBox :: [MessageBoxType] -> Exp String -> Action (Exp String) messageBox ty x = do let a*b = (a, words b) let alts = [MB_OK * "OK" ,MB_OKCANCEL * "OK CANCEL" ,MB_ABORTRETRYIGNORE * "ABORT RETRY IGNORE" ,MB_RETRYCANCEL * "RETRY CANCEL" ,MB_YESNO * "YES NO" ,MB_YESNOCANCEL * "YES NO CANCEL"] let (btns,rest) = partition (`elem` map fst alts) ty let btn = last $ MB_OK : btns let alt = fromJust $ lookup btn alts end <- newLabel lbls <- replicateM (length alt) newLabel v <- mutable_ "" Value x <- x emit $ MessageBox (btn:rest) x $ zip alt lbls forM_ (zip alt lbls) $ \(a,l) -> do label l v @= fromString a goto end label end return v writeRegStr :: HKEY -> Exp String -> Exp String -> Exp String -> Action () writeRegStr k = emit3 $ WriteRegStr k writeRegExpandStr :: HKEY -> Exp String -> Exp String -> Exp String -> Action () writeRegExpandStr k = emit3 $ WriteRegExpandStr k writeRegDWORD :: HKEY -> Exp String -> Exp String -> Exp Int -> Action () writeRegDWORD k = emit3 $ WriteRegDWORD k -- | While the action is executing, do not update the progress bar. -- Useful for functions which do a large amount of computation, or have loops. hideProgress :: Action a -> Action a hideProgress act = do fun <- fmap newFun unique (xs, v) <- capture act emit $ Function fun xs emit $ Call fun return v -- | Sleep time in milliseconds sleep :: Exp Int -> Action () sleep = emit1 Sleep -- | Create a function, useful for registering actions event :: String -> Action () -> Action () event name act = do (xs, _) <- capture act emit $ Function (Fun name) xs onSelChange :: Action () -> Action () onSelChange = event ".onSelChange" onPageShow, onPagePre, onPageLeave :: Page -> Action () -> Action () -- these names are special and bound by Show onPageShow p = event $ "Show" ++ showPageCtor p onPagePre p = event $ "Pre" ++ showPageCtor p onPageLeave p = event $ "Show" ++ showPageCtor p allowRootDirInstall :: Bool -> Action () allowRootDirInstall = emit . AllowRootDirInstall caption :: Exp String -> Action () caption = emit1 Caption detailPrint :: Exp String -> Action () detailPrint = emit1 DetailPrint setDetailsPrint :: DetailsPrint -> Action () setDetailsPrint = emit . SetDetailsPrint showInstDetails :: Visibility -> Action () showInstDetails = emit . ShowInstDetails showUninstDetails :: Visibility -> Action () showUninstDetails = emit . ShowUninstDetails -- | Note: Requires NSIS 3.0 unicode :: Bool -> Action () unicode = emit . Unicode -- | The type of a file handle, created by 'fileOpen'. data FileHandle deriving Typeable -- | Open a file, which must be closed explicitly with 'fileClose'. -- Often it is better to use 'Development.NSIS.Sugar.writeFile'' or -- 'Development.NSIS.Sugar.withFile' instead. -- -- @ -- h <- 'fileOpen' 'ModeWrite' \"C:/log.txt\" -- 'fileWrite' h \"Hello world!\" -- 'fileClose' h -- @ fileOpen :: FileMode -> Exp FilePath -> Action (Exp FileHandle) fileOpen mode name = do Value name <- name v <- var emit $ FileOpen v name mode return $ return $ Value $ val v -- | Write a string to a file openned with 'fileOpen'. fileWrite :: Exp FileHandle -> Exp String -> Action () fileWrite = emit2 FileWrite -- | Close a file file openned with 'fileOpen'. fileClose :: Exp FileHandle -> Action () fileClose = emit1 FileClose setCompressor :: Compressor -> [Attrib] -> Action () setCompressor x as = emit $ SetCompressor $ foldl f def{compType=x} as where f c Final = c{compFinal=True} f c Solid = c{compSolid=True} f c x = error $ "Invalid attribute to setCompress: " ++ show x file :: [Attrib] -> Exp FilePath -> Action () file as x = do Value x <- x; emit . File =<< foldM f def{filePath=x} as where f c Recursive = return c{fileRecursive=True} f c NonFatal = return c{fileNonFatal=True} f c (OName x) = do Value x <- x; return c{fileOName=Just x} f c x = error $ "Invalid attribute to file: " ++ show x section :: Exp String -> [Attrib] -> Action () -> Action SectionId section name as act = do sec <- newSectionId Value name <- name (xs, _) <- capture $ scope act x <- foldM f def{secId=sec, secName=name} as emit $ Section x xs return $ secId x where f c Unselected = return c{secUnselected=True} f c Required = return c{secRequired=True} f c (Description x) = do Value x <- x; return c{secDescription=x} f c (Id x) = return c{secId=x} f c x = error $ "Invalid attribute to section: " ++ show x sectionGroup :: Exp String -> [Attrib] -> Action () -> Action SectionId sectionGroup name as act = do sec <- newSectionId Value name <- name (xs, _) <- capture $ scope act x <- foldM f def{secgId=sec, secgName=name} as emit $ SectionGroup x xs return $ secgId x where f c Expanded = return c{secgExpanded=True} f c (Description x) = do Value x <- x; return c{secgDescription=x} f c (Id x) = return c{secgId=x} f c x = error $ "Invalid attribute to sectionGroup: " ++ show x uninstall :: Action () -> Action () uninstall = void . section "Uninstall" [] -- | Delete file (which can be a file or wildcard, but should be specified with a full path) from the target system. -- If 'RebootOK' is specified and the file cannot be deleted then the file is deleted when the system reboots -- -- if the file will be deleted on a reboot, the reboot flag will be set. The error flag is set if files are found -- and cannot be deleted. The error flag is not set from trying to delete a file that does not exist. -- -- > delete [] "$INSTDIR/somefile.dat" delete :: [Attrib] -> Exp FilePath -> Action () delete as x = do Value x <- x emit $ Delete $ foldl f def{delFile=x} as where f c RebootOK = c{delRebootOK=True} f c x = error $ "Invalid attribute to delete: " ++ show x -- | Remove the specified directory (fully qualified path with no wildcards). Without 'Recursive', -- the directory will only be removed if it is completely empty. If 'Recursive' is specified, the -- directory will be removed recursively, so all directories and files in the specified directory -- will be removed. If 'RebootOK' is specified, any file or directory which could not have been -- removed during the process will be removed on reboot -- if any file or directory will be -- removed on a reboot, the reboot flag will be set. -- The error flag is set if any file or directory cannot be removed. -- -- > rmdir [] "$INSTDIR" -- > rmdir [] "$INSTDIR/data" -- > rmdir [Recursive, RebootOK] "$INSTDIR" -- > rmdir [RebootOK] "$INSTDIR/DLLs" -- -- Note that the current working directory can not be deleted. The current working directory is -- set by 'setOutPath'. For example, the following example will not delete the directory. -- -- > setOutPath "$TEMP/dir" -- > rmdir [] "$TEMP/dir" -- -- The next example will succeed in deleting the directory. -- -- > setOutPath "$TEMP/dir" -- > setOutPath "$TEMP" -- > rmdir [] "$TEMP/dir" -- -- Warning: using @rmdir [Recursive] "$INSTDIR"@ in 'uninstall' is not safe. Though it is unlikely, -- the user might select to install to the Program Files folder and so this command will wipe out -- the entire Program Files folder, including other programs that has nothing to do with the uninstaller. -- The user can also put other files but the program's files and would expect them to get deleted with -- the program. Solutions are available for easily uninstalling only files which were installed by the installer. rmdir :: [Attrib] -> Exp FilePath -> Action () rmdir as x = do Value x <- x emit $ RMDir $ foldl f def{rmDir=x} as where f c RebootOK = c{rmRebootOK=True} f c Recursive = c{rmRecursive=True} f c x = error $ "Invalid attribute to rmdir: " ++ show x -- | Both file paths are on the installing system. Do not use relative paths. copyFiles :: [Attrib] -> Exp FilePath -> Exp FilePath -> Action () copyFiles as from to = do Value from <- from Value to <- to emit $ CopyFiles $ foldl f def{cpFrom=from, cpTo=to} as where f c Silent = c{cpSilent=True} f c FilesOnly = c{cpFilesOnly=True} f c x = error $ "Invalid attribute to copyFiles: " ++ show x -- | Creates a shortcut file that links to a 'Traget' file, with optional 'Parameters'. The icon used for the shortcut -- is 'IconFile','IconIndex'. 'StartOptions' should be one of: SW_SHOWNORMAL, SW_SHOWMAXIMIZED, SW_SHOWMINIMIZED. -- 'KeyboardShortcut' should be in the form of 'flag|c' where flag can be a combination (using |) of: ALT, CONTROL, EXT, or SHIFT. -- c is the character to use (a-z, A-Z, 0-9, F1-F24, etc). Note that no spaces are allowed in this string. A good example is -- \"ALT|CONTROL|F8\". @$OUTDIR@ is used for the working directory. You can change it by using 'setOutPath' before creating -- the Shortcut. 'Description' should be the description of the shortcut, or comment as it is called under XP. -- The error flag is set if the shortcut cannot be created (i.e. either of the paths (link or target) does not exist, or some other error). -- -- > createDirectory "$SMPROGRAMS/My Company" -- > createShortcut "$SMPROGRAMS/My Company/My Program.lnk" -- > [Target "$INSTDIR/My Program.exe" -- > ,Parameters "some command line parameters" -- > ,IconFile "$INSTDIR/My Program.exe", IconIndex 2 -- > ,StartOptions "SW_SHOWNORMAL" -- > ,KeyboardShortcut "ALT|CONTROL|SHIFT|F5" -- > ,Description "a description"] createShortcut :: Exp FilePath -> [Attrib] -> Action () createShortcut name as = do Value name <- name; x <- foldM f def{scFile=name} as; emit $ CreateShortcut x where f c (Target x) = do Value x <- x; return c{scTarget=x} f c (Parameters x) = do Value x <- x; return c{scParameters=x} f c (IconFile x) = do Value x <- x; return c{scIconFile=x} f c (IconIndex x) = do Value x <- x; return c{scIconIndex=x} f c (StartOptions x) = return c{scStartOptions=x} f c (KeyboardShortcut x) = return c{scKeyboardShortcut=x} f c (Description x) = do Value x <- x; return c{scDescription=x} f c x = error $ "Invalid attribute to shortcut: " ++ show x page :: Page -> Action () page = emit . Page finishOptions :: FinishOptions finishOptions = def unpage :: Page -> Action () unpage = emit . Unpage requestExecutionLevel :: Level -> Action () requestExecutionLevel = emit . RequestExecutionLevel type HWND = Exp Int hwndParent :: HWND hwndParent = return $ Value [Builtin "HWNDPARENT"] findWindow :: Exp String -> Exp String -> Maybe HWND -> Action HWND findWindow a b c = do v <- var Value a <- a Value b <- b c <- maybe (return Nothing) (fmap (Just . fromValue)) c emit $ FindWindow v a b c Nothing return $ return $ Value $ val v getDlgItem :: HWND -> Exp Int -> Action HWND getDlgItem a b = do v <- var Value a <- a Value b <- b emit $ GetDlgItem v a b return $ return $ Value $ val v sendMessage :: [Attrib] -> HWND -> Exp Int -> Exp a -> Exp b -> Action (Exp Int) sendMessage as a b c d = do v <- var Value a <- a Value b <- b Value c <- c Value d <- d as <- return $ foldl f Nothing as emit $ SendMessage a b c d v as return $ return $ Value $ val v where f c (Timeout x) = Just x f c x = error $ "Invalid attribute to sendMessage: " ++ show x abort :: Exp String -> Action () abort = emit1 Abort -- | Inject arbitrary text into a non-global section of the script. unsafeInject :: String -> Action () unsafeInject = emit . UnsafeInject -- | Inject arbitrary text into the script's global header section. unsafeInjectGlobal :: String -> Action () unsafeInjectGlobal = emit . UnsafeInjectGlobal
idleberg/NSIS
Development/NSIS/Sugar.hs
apache-2.0
41,654
0
22
9,718
10,593
5,363
5,230
-1
-1
-- Based on http://hackage.haskell.org/package/thumbnail module ShopData.Thumbnail ( ImageFormat(..) , Thumbnail(..) , mkThumbnail , mkThumbnail' , defaultBounds) where import Prelude import Graphics.GD import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as L data ImageFormat = Gif | Jpeg | Png data Thumbnail = Thumbnail { fmt :: ImageFormat -- ^ Image Format Type , img :: Image -- ^ Thumbnail Image , sz :: Size -- ^ Thumbnail Size , lbs :: L.ByteString -- ^ Thumbnail Data , orgImg :: Image -- ^ Original Image , orgSZ :: Size -- ^ Original Size , saveFile :: FilePath -> IO () } -- | Create a thumbnails with the default size mkThumbnail :: L.ByteString -> IO (Either String Thumbnail) mkThumbnail = mkThumbnail' defaultBounds -- | Create a thumbnail from a specific subregion of the image mkThumbnail' :: ((Int,Int),(Int,Int)) -> L.ByteString -> IO (Either String Thumbnail) mkThumbnail' sizeBounds = thumbnail . L.unpack where thumbnail ws | length ws >= 3 = thumbnail' ws -- FIXME! | otherwise = return $ Left "unsupported image format" thumbnail' ws@(0xff:0xd8:_) = thumbnailJpeg ws thumbnail' ws@(0x89:0x50:_) = thumbnailPng ws thumbnail' ws@(0x47:0x49:0x46:_) = thumbnailGif ws thumbnail' _ = return $ Left "unsupported image format" thumbnailJpeg ws = do src <- loadJpegByteString $ BS.pack ws size <- imageSize src dest <- copyImage src let size' = newSize sizeBounds size thm <- uncurry resizeImage size' dest bs <- saveJpegByteString 90 thm let save fp = saveJpegFile 90 fp thm return $ Right Thumbnail { fmt=Jpeg , img=thm , sz=size' , lbs=strictToLazy bs , orgImg=src , orgSZ=size , saveFile=save } thumbnailPng ws = do src <- loadPngByteString $ BS.pack ws size <- imageSize src dest <- copyImage src let size' = newSize sizeBounds size thm <- uncurry resizeImage size' dest bs <- savePngByteString thm let save fp = savePngFile fp thm return $ Right Thumbnail { fmt=Png , img=thm , sz=size' , lbs=strictToLazy bs , orgImg=src , orgSZ=size , saveFile=save } thumbnailGif ws = do src <- loadGifByteString $ BS.pack ws size <- imageSize src dest <- copyImage src let size' = newSize sizeBounds size thm <- uncurry resizeImage size' dest bs <- saveGifByteString thm let save fp = saveGifFile fp thm return $ Right Thumbnail { fmt=Gif , img=thm , sz=size' , lbs=strictToLazy bs , orgImg=src , orgSZ=size , saveFile=save } strictToLazy = L.pack . BS.unpack newSize :: ((Int,Int),(Int,Int)) -> Size -> Size newSize ((wMin,hMin),(wMax,hMax)) (w, h) | w >= h && wMax*h`div`w > wMin = (wMax, wMax*h`div`w) | w >= h && h >= hMin = (hMin*w`div`h, hMin) | w < h && hMax*w`div`h > hMin = (hMax*w`div`h, hMax) | w < h && w >= wMin = (wMin, wMin*h`div`w) | otherwise = (w, h) defaultBounds :: ((Int,Int),(Int,Int)) defaultBounds = ((20,20),(60,60))
rjohnsondev/haskellshop
src/ShopData/Thumbnail.hs
bsd-2-clause
4,022
0
13
1,695
1,141
613
528
82
4
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-} module TimeEdit where import Data.List import Data.Maybe import Data.Time import Data.Time.Format import Data.Time.Clock import Control.Monad.Reader import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.IO as T import qualified Data.Text.Lazy.Encoding as E import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.ByteString.Char8 as BS import Data.ByteString.Lazy.Search (replace) import qualified Data.Vector as V import Text.HTML.TagSoup import Data.Csv import Debug.Trace (trace) import Network.HTTP.Client.Conduit default (Text) debug = flip trace -- TODO: get iCal link for courses data RoomStatus = FreeUntil TimeOfDay | Occupied | Free deriving (Show) data Room = Room Text RoomStatus deriving (Show) roomStatus :: TimeOfDay -> SearchResults -> [Room] roomStatus time = map toRoom where toRoom (name, lessons) = Room name status where status | any (isDuring time) lessons = Occupied | otherwise = maybe Free FreeUntil . find (> time) . map startTime . sortOn startTime $ lessons isDuring :: TimeOfDay -> Lesson -> Bool isDuring time lesson = startTime lesson <= time && time <= endTime lesson roomStatusSearch :: Text -> ReaderT Manager IO (Either Text [Room]) roomStatusSearch query = do currentTime <- liftIO $ localTimeOfDay <$> now search (roomStatus currentTime) RoomQuery query scheduleToday :: Text -> ReaderT Manager IO () scheduleToday query = do roomResult <- search textFromSearch RoomQuery query case roomResult of Right result -> liftIO $ T.putStr result Left _ -> do courseResult <- search textFromSearch CourseQuery query case courseResult of Right result -> liftIO $ T.putStr result Left _ -> liftIO $ T.putStrLn $ T.concat [ "No room or course found for \"", query, "\""] -- * Searching timeEdit type SearchResults = [(TimeEditName, [Lesson])] search :: (SearchResults -> a) -> QueryType -> Text -> ReaderT Manager IO (Either Text a) search f searchType query = do manager <- newManager html <- httpGet $ searchUrl searchType query case parseTimeEditSearchResults $ textFromLazyBS html of [] -> return . Left $ T.concat ["No ", T.toLower (tshow searchType), " found for \"", query, "\""] nameids -> Right . f <$> (mapM.mapM) downloadTodaysSchedule nameids textFromSearch :: SearchResults -> Text textFromSearch = T.unlines . map (uncurry prettySchedule) downloadTodaysSchedule :: TimeEditId -> ReaderT Manager IO [Lesson] downloadTodaysSchedule id = do today <- liftIO $ localDay <$> now csv <- httpGet $ scheduleUrl today today [id] return $ parseCsv $ replace ", " ("," :: BS.ByteString) csv -- TODO: prettySchedule for different search types now :: IO LocalTime now = do timeZone <- getCurrentTimeZone utcToLocalTime timeZone <$> getCurrentTime parseTimeM True defaultTimeLocale "%y%m%d %H:%M" "151014 10:30" prettySchedule :: TimeEditName -> [Lesson] -> Text prettySchedule name lessons = T.unlines (name : schedule lessons) where schedule [] = ["-"] schedule lessons = map prettyTimes lessons format = T.pack . formatTime defaultTimeLocale "%H:%M" prettyTimes lesson = T.intercalate "–" $ map (\f -> format $ f lesson) [startTime, endTime] -- * Convenience httpGet :: Text -> ReaderT Manager IO L.ByteString httpGet url = do request <- parseUrl $ T.unpack url responseBody <$> httpLbs request textFromLazyBS :: L.ByteString -> Text textFromLazyBS = E.decodeUtf8 tshow :: Show a => a -> Text tshow = T.pack . show -- * Search types data QueryType = RoomQuery | CourseQuery instance Show QueryType where show RoomQuery = "Room" show CourseQuery = "Course" stringFromSearchType :: QueryType -> Text stringFromSearchType searchType = case searchType of RoomQuery -> "186" CourseQuery -> "182" -- * Html Scraping type TimeEditId = Text type TimeEditName = Text parseTimeEditSearchResults :: Text -> [(TimeEditName, TimeEditId)] parseTimeEditSearchResults = map extract . filter (~== TagOpen "div" [(attrId, ""), (attrName, "")]) . parseTags where extract div = (fromAttrib attrName div, fromAttrib attrId div) attrId = "data-id" attrName = "data-name" -- * CSV scraping data Lesson = Lesson { startDate :: Day , startTime :: TimeOfDay , endDate :: Day , endTime :: TimeOfDay , courseName :: Maybe Text , rooms :: Rooms } deriving (Show) data Rooms = Rooms [Text] deriving (Show) instance FromRecord Lesson where parseRecord v = Lesson <$> v .! 0 <*> v .! 1 <*> v .! 2 <*> v .! 3 <*> v .! 4 <*> v .! 5 instance FromField Day where parseField = pure . parseTimeOrError True defaultTimeLocale "%Y-%m-%d" . BS.unpack instance FromField TimeOfDay where parseField = pure . parseTimeOrError True defaultTimeLocale "%H:%M" . BS.unpack instance FromField Rooms where parseField = pure . Rooms . map E.decodeUtf8 . L.words . L.fromStrict parseCsv :: L.ByteString -> [Lesson] parseCsv csv = V.toList vector where vector = either error id (decode HasHeader cleanCsv) cleanCsv = dropLines 3 csv dropLines :: Int -> L.ByteString -> L.ByteString dropLines n = L.unlines . drop n . L.lines -- * urls -- TODO remove unnecessary stuff from urls baseUrl :: Text baseUrl = "https://se.timeedit.net/web/chalmers/db1/public/" searchUrl :: QueryType -> Text -> Text searchUrl searchType query = T.concat [ baseUrl, "objects.html?fr=t&partajax=t&im=f&sid=1004&l=sv", "&search_text=", query, "&types=", typeString] where typeString = stringFromSearchType searchType scheduleUrl :: Day -> Day -> [TimeEditId] -> Text scheduleUrl startTime endTime ids = T.concat [ baseUrl, "ri.csv?sid=3&l=en_US", "&p=", format startTime, "-", format endTime, "&objects=", T.intercalate "," ids] where format = T.pack . formatTime defaultTimeLocale "%y%m%d"
pnutus/slask
src/TimeEdit.hs
bsd-3-clause
6,293
2
17
1,422
1,820
968
852
169
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} import Language.TRM import Control.Applicative import Data.Monoid import Test.QuickCheck hiding (label) import Test.QuickCheck.All import Prelude hiding (compare) instance Arbitrary Letter where arbitrary = do b <- arbitrary :: Gen Bool case b of True -> return One False -> return Hash deriving instance Arbitrary Word instance Arbitrary Register where arbitrary = fromIntegral <$> (arbitrary :: Gen (Positive Integer)) prop_succBB_ :: NonNegative Integer -> Bool prop_succBB_ x = case phi succBB' [(1, encodeBB x)] of Just x' -> decodeBB x' == x + 1 _ -> False prop_plusBB_ :: NonNegative Integer -> NonNegative Integer -> Bool prop_plusBB_ x y = case phi plusBB' [(1, encodeBB x), (2, encodeBB y)] of Just z -> decodeBB z == x + y _ -> False prop_compare_ :: Word -> Word -> Bool prop_compare_ x y = case phi compare' [(1, x), (2, y)] of Just "1" -> x == y Just "" -> x /= y _ -> False prop_clear :: Register -> Word -> Bool prop_clear r x = case lookup r $ runL' (clear r) [(r, x)] of Just "" -> True _ -> False prop_move :: Register -> Register -> Word -> Word -> Property prop_move src dest x y = src /= dest ==> case (lookup src rs, lookup dest rs) of (Just "", Just z) -> z == y `mappend` x _ -> False where rs = runL' (move src dest) [(src, x), (dest, y)] prop_copy :: Register -> Register -> Word -> Word -> Property prop_copy src dest x y = src /= dest ==> case (lookup src rs, lookup dest rs) of (Just x', Just z) -> x == x' && z == y `mappend` x _ -> False where rs = runL' (copy src dest) [(src, x), (dest, y)] prop_compare :: Register -> Register -> Word -> Word -> Property prop_compare r1 r2 x y = r1 /= r2 ==> case lookup r1 $ runL' (compare r1 r2) [(r1, x), (r2, y)] of Just "1" -> x == y Just "" -> x /= y _ -> False prop_succBB :: Register -> NonNegative Integer -> Bool prop_succBB r x = case lookup r $ runL' (succBB r) [(r, encodeBB x)] of Just x' -> decodeBB x' == x + 1 _ -> False prop_addBB :: Register -> Register -> NonNegative Integer -> NonNegative Integer -> Property prop_addBB r1 r2 x y = r1 /= r2 ==> case lookup r1 $ runL' (addBB r1 r2) [(r1, encodeBB x), (r2, encodeBB y)] of Just z -> decodeBB z == x + y _ -> False prop_multBB :: Register -> Register -> NonNegative Integer -> NonNegative Integer -> Property prop_multBB r1 r2 x y = r1 /= r2 ==> case lookup r1 $ runL' (multBB r1 r2) [(r1, encodeBB x), (r2, encodeBB y)] of Just z -> decodeBB z == x * y _ -> False prop_exptBB :: Register -> Register -> NonNegative Integer -> NonNegative Integer -> Property prop_exptBB r1 r2 x y = r1 /= r2 ==> case lookup r1 $ runL' (exptBB r1 r2) [(r1, encodeBB x), (r2, encodeBB y)] of Just z -> decodeBB z == x ^ y _ -> False runTests = $quickCheckAll
acfoltzer/text-register-machine
Language/TRM/Properties.hs
bsd-3-clause
3,229
0
12
946
1,299
666
633
81
3
module Lib where import qualified Data.HashMap.Strict as HM import qualified Data.Set as S import Text.Printf --import qualified Data.ByteString.Char8 as BS2 --import Data.Hashable.Class.Hashable type Token = String -- BS2.ByteString type Dictionary = S.Set Token type Sentence = [Token] type SentencePair = (Sentence,Sentence) type Corpus = [SentencePair] type Probs = HM.HashMap (Token, Token) Double type Counts = HM.HashMap (Token, Token) Double type Totals = HM.HashMap Token Double readCorpus :: String -> String -> IO (Corpus) readCorpus filef filee = do fr <- readFile filef en <- readFile filee return $ map (\(x,y) -> ( "NULL":(words x), words y)) $ zipWith (\x y -> (x,y)) (lines fr) (lines en) -- return $ map (\(x,y) -> (map BS2.pack $ "NULL":(words x), map BS2.pack $ words y)) $ zipWith (\x y -> (x,y)) (lines fr) (lines en) initProbs :: Corpus -> Probs initProbs corpus = foldl initializer HM.empty corpus where initializer = foldPair insertProbs insertProbs _ e f ac = HM.insert (e,f) probs ac probs = 1 / ( fromIntegral . S.size . snd . extractDict $ corpus) extractDict :: Corpus -> (Dictionary, Dictionary) extractDict = foldr (\(f, e) (dice, dicf) -> (foldr S.insert dice e , foldr S.insert dicf f)) (S.empty, S.empty) foldPair :: (SentencePair -> Token -> Token -> a -> a) -> a -> SentencePair -> a foldPair insfun cnt k@(f,e) = foldr (\x acc -> foldr (\y ac -> insfun k x y ac ) acc f) cnt e step :: Corpus -> Probs -> Probs step corpus probs = {-# SCC "step"#-} HM.mapWithKey (\k@(_,f) _ -> val k f) $ probs where val k f = (/) ((HM.!) counts k) ((HM.!) totals f) (counts,totals) = foldl counter (HM.empty, HM.empty) corpus counter = foldPair inserter inserter k x y ac = (insertCount k x y ac, insertTotal k x y ac) insertCount k x y ac = HM.insertWith (+) -- operation (x,y) -- key (((HM.!) probs (x,y)) / ((HM.!) (normalization k) x)) -- value to add $ fst ac -- map insertTotal k x y ac = HM.insertWith (+) y (((HM.!) probs (x,y)) / ((HM.!) (normalization k) x)) $ snd ac normalization = foldPair (\_ x y acc -> HM.insertWith (+) x ((HM.!) probs (x,y)) acc) HM.empty loop corpus = (step corpus):(loop corpus) iterations n corpus = foldr (.) id $ take n (loop corpus) showProbs :: Probs -> String showProbs = HM.foldrWithKey (\(e,f) a acc -> if a>0.001 then (unwords [f,e, (printf "%.4f\n" a)])++acc else acc) [] --showProbs = HM.foldrWithKey (\(e,f) a acc -> if a>0.001 then (unwords [BS2.unpack f,BS2.unpack e, (printf "%.4f\n" a)])++acc else acc) [] perplexity :: Corpus -> Probs -> Double perplexity corpus probs = foldr (\k acc -> acc - (logBase 2 (prob k))) 0 corpus where prob (f,e) = foldr (\(x, y) ac -> ac * (probs HM.! (y,x))) 1 $ zip f e
Antystenes/IBM1
src/Lib.hs
bsd-3-clause
3,081
0
15
873
1,187
653
534
50
2
----------------------------------------------------------- -- | -- Module : DBInfo -- Copyright : HWT Group (c) 2004, [email protected] -- License : BSD-style -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable -- -- This is the "core" file of the DBSpec files. It defines -- a DBInfo and important functions on it. -- -- ----------------------------------------------------------- module Database.HaskellDB.DBSpec.DBInfo (DBInfo(..),TInfo(..),CInfo(..),DBOptions(..),makeDBSpec, makeTInfo,makeCInfo,ppDBInfo,ppTInfo,ppCInfo,ppDBOptions, dbInfoToDoc,finalizeSpec,constructNonClashingDBInfo) where import qualified Database.HaskellDB.DBSpec.PPHelpers as PP import Database.HaskellDB.FieldType (FieldDesc, FieldType(BStrT, StringT), ) import Data.Char (toLower, isAlpha) import Text.PrettyPrint.HughesPJ -- | Defines a database layout, top level data DBInfo = DBInfo {dbname :: String -- ^ The name of the database ,opts :: DBOptions -- ^ Any options (i.e whether to use -- Bounded Strings) ,tbls :: [TInfo] -- ^ Tables this database contains } deriving (Show) data TInfo = TInfo {tname :: String -- ^ The name of the table ,cols :: [CInfo] -- ^ The columns in this table } deriving (Eq,Show) data CInfo = CInfo {cname :: String -- ^ The name of this column ,descr :: FieldDesc -- ^ The description of this column } deriving (Eq,Show) data DBOptions = DBOptions {useBString :: Bool -- ^ Use Bounded Strings? ,makeIdent :: PP.MakeIdentifiers -- ^ Conversion routines from Database identifiers to Haskell identifiers } instance Show DBOptions where showsPrec p opts = showString "DBOptions {useBString = " . shows (useBString opts) . showString "}" -- | Creates a valid declaration of a DBInfo. The variable name will be the -- same as the database name dbInfoToDoc :: DBInfo -> Doc dbInfoToDoc dbi@(DBInfo {dbname = n , opts = opt}) = fixedName <+> text ":: DBInfo" $$ fixedName <+> equals <+> ppDBInfo dbi where fixedName = text . PP.identifier (makeIdent opt) $ n -- | Pretty prints a DBInfo ppDBInfo :: DBInfo -> Doc ppDBInfo (DBInfo {dbname=n, opts=o, tbls = t}) = text "DBInfo" <+> braces (vcat (punctuate comma ( text "dbname =" <+> doubleQuotes (text n) : text "opts =" <+> ppDBOptions o : text "tbls =" <+> brackets (vcat (punctuate comma (map ppTInfo t))) : []))) ppTInfo :: TInfo -> Doc ppTInfo (TInfo {tname=n,cols=c}) = text "TInfo" <+> braces (vcat (punctuate comma ( text "tname =" <+> doubleQuotes (text n) : text "cols =" <+> brackets (vcat (punctuate comma (map ppCInfo c))) : []))) ppCInfo :: CInfo -> Doc ppCInfo (CInfo {cname=n,descr=(val,null)}) = text "CInfo" <+> braces (vcat (punctuate comma ( text "cname =" <+> doubleQuotes (text n) : text "descr =" <+> parens (text (show val) <> comma <+> text (show null)) : []))) ppDBOptions :: DBOptions -> Doc ppDBOptions (DBOptions {useBString = b}) = text "DBOptions" <+> braces (text "useBString =" <+> text (show b)) -- | Does a final "touching up" of a DBInfo before it is used by i.e DBDirect. -- This converts any Bounded Strings to ordinary strings if that flag is set. finalizeSpec :: DBInfo -> DBInfo finalizeSpec dbi = if (useBString (opts dbi)) then dbi else stripBStr dbi -- | Converts all BStrings to ordinary Strings stripBStr :: DBInfo -> DBInfo stripBStr dbi = fixTables dbi where fixTables dbi = dbi{tbls=map fixCols (tbls dbi)} fixCols tbl = tbl{cols=map oneCol (cols tbl)} oneCol col = col{descr = fixDescr (descr col)} fixDescr col = case fst col of BStrT _ -> (StringT,snd col) _ -> col -- | Creates a DBInfo makeDBSpec :: String -- ^ The name of the Database -> DBOptions -- ^ Options -> [TInfo] -- ^ Tables -> DBInfo -- ^ The generated DBInfo makeDBSpec name opt tinfos = DBInfo {dbname = name, opts = opt, tbls = tinfos} -- | Creates a TInfo makeTInfo :: String -- ^ The table name -> [CInfo] -- ^ Columns -> TInfo -- ^ The generated TInfo makeTInfo name cinfs = TInfo {tname = name, cols = cinfs} -- | Creates a CInfo makeCInfo :: String -- ^ The column name -> FieldDesc -- ^ What the column contains -> CInfo -- ^ The generated CInfo makeCInfo name fdef = CInfo {cname = name, descr = fdef} ----------------------------------------------------- -- Functions for avoiding nameclashes ----------------------------------------------------- -- | Constructs a DBInfo that doesn't cause nameclashes constructNonClashingDBInfo :: DBInfo -> DBInfo constructNonClashingDBInfo dbinfo = let db' = makeDBNameUnique dbinfo in if equalObjectNames db' (makeDBNameUnique db') then db' else constructNonClashingDBInfo db' equalObjectNames :: DBInfo -> DBInfo -> Bool equalObjectNames db1 db2 = dbname db1 == dbname db2 && tbls db1 == tbls db2 -- | Makes a table name unique among all other table names makeTblNamesUnique :: [TInfo] -> [TInfo] makeTblNamesUnique [] = [] makeTblNamesUnique (t:[]) = t:[] makeTblNamesUnique (t:tt:ts) | compNames (tname t) (tname tt) = t: (makeTblNamesUnique ((tblNewName tt) : ts)) | True = t : makeTblNamesUnique (tt:ts) where tblNewName tinfo@TInfo{tname=n} = tinfo{tname=newName (Left n)} -- | Makes a field name unique among all other field names makeFieldNamesUnique :: [CInfo] -> [CInfo] makeFieldNamesUnique [] = [] makeFieldNamesUnique (f:[]) = f:[] makeFieldNamesUnique (f:ff:fs) | compNames (cname f) (cname ff) = f: (makeFieldNamesUnique ((fNewName ff) :fs)) | True = f : makeFieldNamesUnique (ff:fs) where fNewName cinfo@CInfo{cname=n} = cinfo{cname=newName (Right n)} -- | makes the dbname unique in a database makeDBNameUnique :: DBInfo -> DBInfo makeDBNameUnique dbinfo = dbinfo{tbls=map (makeTblNameUnique (dbname dbinfo)) (tbls dbinfo)} -- | makes a supplied name unique in a table and its subfields makeTblNameUnique :: String -> TInfo -> TInfo makeTblNameUnique s tinfo | compNames s (tname tinfo) = tinfo{cols=map (makeFieldNameUnique s) (cols tinfo{tname=newName (Left (tname tinfo))})} | True = tinfo{cols=map (makeFieldNameUnique s) (cols tinfo)} -- | makes a supplied name unique in a field makeFieldNameUnique :: String -> CInfo -> CInfo makeFieldNameUnique s cinfo | compNames s (cname cinfo) = cinfo{cname=newName (Right (cname cinfo))} | True = cinfo -- | Gives a String a new name, according to its type newName :: Either String String -- ^ Either a Table or a Field -> String -- ^ The new name newName (Left t) = t ++ "T" newName (Right n) = n ++ "F" -- | Case insensitive String comparison (there probably is a standard function -- for this, there ought to be anyway compNames :: String -> String -> Bool compNames s1 s2 = map toLower s1 == map toLower s2
chrisdone/haskelldb-demo
lib/haskelldb/src/Database/HaskellDB/DBSpec/DBInfo.hs
bsd-3-clause
7,070
78
21
1,516
2,039
1,102
937
130
2
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ATI.TextureFloat -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ATI.TextureFloat ( -- * Extension Support glGetATITextureFloat, gl_ATI_texture_float, -- * Enums pattern GL_ALPHA_FLOAT16_ATI, pattern GL_ALPHA_FLOAT32_ATI, pattern GL_INTENSITY_FLOAT16_ATI, pattern GL_INTENSITY_FLOAT32_ATI, pattern GL_LUMINANCE_ALPHA_FLOAT16_ATI, pattern GL_LUMINANCE_ALPHA_FLOAT32_ATI, pattern GL_LUMINANCE_FLOAT16_ATI, pattern GL_LUMINANCE_FLOAT32_ATI, pattern GL_RGBA_FLOAT16_ATI, pattern GL_RGBA_FLOAT32_ATI, pattern GL_RGB_FLOAT16_ATI, pattern GL_RGB_FLOAT32_ATI ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
haskell-opengl/OpenGLRaw
src/Graphics/GL/ATI/TextureFloat.hs
bsd-3-clause
1,029
0
5
135
102
69
33
18
0
module Printer(header, footer, modeSelection, weaponsSelection, battleSequence, score, scoreLog) where import GameModes (GameMode, gameModeNames) import Reactions (getReaction) import ScoreBoard (ScoreBoard, Score) import Weapons (Weapon, weaponsIn) header :: IO () header = printText ["######## ######## ####### ", "## ## ## ## ### ##", "######## ######## ###### ", "## ## ## ## ### ", "## ## ## ####### "] footer :: IO () footer = printText ["- Game over -"] modeSelection :: IO () modeSelection = let formatted = indent . padRight <$> gameModeNames in printText $ "- Choose a game mode -" : divider : formatted weaponsSelection :: GameMode -> IO () weaponsSelection gameMode = let numberWeapon wpn num = show num ++ ". " ++ show wpn weapons = weaponsIn gameMode numbered = zipWith numberWeapon weapons [1..] formatted = indent . padRight <$> numbered in printText $ ("<> " ++ show gameMode ++ " <>") : divider : "- Choose your weapon -" : divider : formatted battleSequence :: Weapon -> Weapon -> Ordering -> IO () battleSequence w1 w2 outcome = printText ["You pick: " ++ show w1 ++ "!", "Your enemy picks: " ++ show w2 ++ "!", "", getReaction w1 w2, eval outcome] score :: Score -> IO () score s = printText $ "- Current score -" : "" : show s : divider : "" : ["Play again? (y/n)"] scoreLog :: ScoreBoard -> IO () scoreLog scores = let reversed = tail . reverse $ scores numLog s n = "Round" ++ space n ++ show n ++ ": " ++ show s numbered = zipWith numLog reversed [1..] formatted = indent . padRight <$> numbered in printText $ "- Score log -" : "" : formatted eval :: Ordering -> String eval GT = "YOU WIN!" eval EQ = "IT'S A TIE!" eval LT = "YOU LOSE!" printText :: [String] -> IO () printText txt = let formatted = "" : divider2 : txt ++ [divider] in mapM_ putStrLn $ padCenter <$> formatted padCenter :: String -> String padCenter s | length s < gameWidth = padCenter $ " " ++ s ++ " " | otherwise = s padRight :: String -> String padRight s | length s < gameWidth = padRight $ s ++ " " | otherwise = s indent :: String -> String indent = (" " ++) space :: Int -> String space n | n < 10 = " " | n < 100 = " " | otherwise = "" divider :: String divider = mkDivider " -" divider2 :: String divider2 = mkDivider " =" mkDivider :: String -> String mkDivider s = const s `concatMap` [1 .. gameWidth `div` 2] gameWidth :: Int gameWidth = 50
joelchelliah/rock-paper-scissors-hs
src/Printer.hs
bsd-3-clause
3,401
0
15
1,503
874
451
423
80
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} ------------------------------------------------------------------- -- | -- Module : Irreverent.Bitbucket.Options -- Copyright : (C) 2017 Irreverent Pixel Feats -- License : BSD-style (see the file /LICENSE.md) -- Maintainer : Dom De Re -- ------------------------------------------------------------------- module Irreverent.Bitbucket.Options ( -- * Parsers ownerP , ownerArgP , repoNameP , repoNameArgP , repoSlugP , authP , envvarNameToDeleteP , forceEnvVarSetP , gitURLTypeP , newRepoP , newPipelineEnvVarP , pipelineCfgUpdateP , privateKeyPathP , privilegeLevelP , publicKeyPathP , accessKeyLabelP , groupNameP , groupOwnerP ) where import Irreverent.Bitbucket.Core.Data.Common ( Username(..) , ForkPolicy(..) , GitURLType(..) , GroupName(..) , GroupOwner(..) , HasWiki(..) , HasIssues(..) , Language(..) , PipelinesEnvironmentVariableSecurity(..) , Privacy(..) , PrivilegeLevel(..) , ProjectKey(..) , RepoDescription(..) , RepoName(..) , RepoSlug(..) , Scm(..) , privilegeLevelFromText ) import Irreverent.Bitbucket.Core.Data.Auth (Auth(..)) import Irreverent.Bitbucket.Core.Data.NewRepository (NewRepository(..)) import Irreverent.Bitbucket.Core.Data.Pipelines.NewEnvironmentVariable (NewPipelinesEnvironmentVariable(..)) import Irreverent.Bitbucket.Core.Data.Pipelines.UpdateConfig (UpdatePipelinesConfig(..)) import qualified Ultra.Data.Text as T import Ultra.Options.Applicative ( Parser , argument , eitherTextReader , envvar , flag , flag' , help , long , metavar , option , short , str ) import Data.Monoid ((<>)) import Preamble hiding ((<>)) httpsURLTypeP :: Parser GitURLType httpsURLTypeP = flag' HTTPSGitURLType $ long "https" <> help "Provide HTTPS Git URL" sshGitURLTypeP :: Parser GitURLType sshGitURLTypeP = flag' SSHGitURLType $ long "ssh" <> help "Provide SSH Git URL" gitURLTypeP :: Parser GitURLType gitURLTypeP = httpsURLTypeP <|> sshGitURLTypeP ownerP :: T.Text -> Parser Username ownerP htext = option (Username . T.pack <$> str) $ short 'o' <> long "owner" <> help (T.unpack htext) ownerArgP :: T.Text -> Parser Username ownerArgP htext = argument (Username . T.pack <$> str) $ metavar "OWNER" <> help (T.unpack htext) repoNameP :: T.Text -> Parser RepoName repoNameP htext = option (RepoName . T.pack <$> str) $ short 'r' <> long "repository" <> help (T.unpack htext) repoSlugP :: T.Text -> Parser RepoSlug repoSlugP htext = option (RepoSlug . T.pack <$> str) $ short 'r' <> long "repository" <> help (T.unpack htext) repoNameArgP :: T.Text -> Parser RepoName repoNameArgP htext = argument (RepoName . T.pack <$> str) $ metavar "REPONAME" <> help (T.unpack htext) authP :: [(T.Text, T.Text)] -> Parser Auth authP env = option (eitherTextReader authReader) $ short 'a' <> long "auth" <> envvar (either (const Nothing) pure . authReader) env "BITBUCKET_API_AUTH" "Bitbucket app password login information, in the form of \"username:password\"" repoDescP :: Parser RepoDescription repoDescP = option (RepoDescription . T.pack <$> str) $ short 'd' <> long "description" <> metavar "DESCRIPTION" <> help "Description to use for the repo" gitScmP :: Parser Scm gitScmP = flag' Git $ long "git" <> help "Sets the Scm to Git (Default)" mercurialScmP :: Parser Scm mercurialScmP = flag' Mercurial $ short 'm' <> long "mercurial" <> help "Sets the Scm to Mercurial" scmP :: Parser Scm scmP = gitScmP <|> mercurialScmP <|> pure Git projectKeyP :: Parser ProjectKey projectKeyP = option (ProjectKey . T.pack <$> str) $ short 'p' <> long "project" <> metavar "PROJECT_KEY" <> help "The key for the project you wish to assign this repo to" enumWithDefaultP :: forall a. (Eq a) => a -> NonEmpty (a, T.Text, T.Text) -> Parser a enumWithDefaultP def = let p :: a -> T.Text -> T.Text -> Parser a p fp long' help' = flag' fp $ long (T.unpack long') <> help (T.unpack help') f :: (a, T.Text, T.Text) -> Parser a -> Parser a f (x, long', help') parser = p x long' (help' <> (if x == def then " (Default)" else "")) <|> parser in foldr f (pure def) forkPolicyP :: Parser ForkPolicy forkPolicyP = enumWithDefaultP NoPublicForksPolicy [ (NoForksPolicy, "no-forks", "Allows No Forks on this repo") , (NoPublicForksPolicy, "no-public-forks", "Allows only private forks on the project") , (ForkAwayPolicy, "forks", "Allows public and private forks") ] privacyP :: Parser Privacy privacyP = enumWithDefaultP Private [ (Public, "public", "Repo will be public") , (Private, "private", "Repo will be private") ] languageP :: Parser Language languageP = option (Language . T.pack <$> str) $ short 'l' <> long "lang" <> metavar "LANGUAGE" <> help "The predominant language that is to be used" hasWikiP :: Parser HasWiki hasWikiP = enumWithDefaultP NoWiki [ (HasWiki, "has-wiki", "A Wiki will be created for this repo") , (NoWiki, "no-wiki", "No Wiki will be created for this wiki, if there previously was one, it will be deleted") ] hasIssuesP :: Parser HasIssues hasIssuesP = enumWithDefaultP HasIssues [ (HasIssues, "has-issues", "Issue tracking will be setup for this repo") , (NoIssues, "no-issues", "There will be no issue tracking for this repo") ] newRepoP :: Parser NewRepository newRepoP = NewRepository <$> repoDescP <*> scmP <*> optional projectKeyP <*> forkPolicyP <*> privacyP <*> languageP <*> hasWikiP <*> hasIssuesP pipelineCfgUpdateP :: Parser UpdatePipelinesConfig pipelineCfgUpdateP = UpdatePipelinesConfig <$> pipelineEnabledP enablePipelineP :: Parser Bool enablePipelineP = flag' True $ long "enabled" <> help "Turns the pipeline on" disablePipelineP :: Parser Bool disablePipelineP = flag' False $ long "disabled" <> help "Turns the pipeline off" pipelineEnabledP :: Parser Bool pipelineEnabledP = enablePipelineP <|> disablePipelineP authReader :: T.Text -> Either T.Text Auth authReader t = case T.splitOn ":" t of [] -> Left t username:password -> pure . Basic username $ T.intercalate ":" password newPipelineEnvVarP :: Parser NewPipelinesEnvironmentVariable newPipelineEnvVarP = NewPipelinesEnvironmentVariable <$> envvarNameP <*> envvarValueP <*> envvarSecurityP forceEnvVarSetP :: Parser (Maybe ()) forceEnvVarSetP = flag Nothing (pure ()) $ short 'f' <> long "force" <> help "If environment variable already exists, overwrite it, otherwise operation will fail if environment variable already exists" envvarNameP :: Parser T.Text envvarNameP = option (T.pack <$> str) $ short 'n' <> long "name" <> metavar "NAME" <> help "The name for the environment variable you wish to add to pipelines" envvarNameToDeleteP :: Parser T.Text envvarNameToDeleteP = option (T.pack <$> str) $ short 'n' <> long "name" <> metavar "NAME" <> help "The name for the environment variable you wish to remove" envvarValueP :: Parser T.Text envvarValueP = option (T.pack <$> str) $ long "value" <> metavar "VALUE" <> help "The value you wish to set the pipeline environment variable to" envvarSecurityP :: Parser PipelinesEnvironmentVariableSecurity envvarSecurityP = flag SecuredVariable UnsecuredVariable $ long "unsecured" <> help "Will expose the environment variable in the REST API, GUI and Logs, the default behaviour if this is unspecified is \"secured\" behaviour where you cannot retrieve the value via the REST API, GUI or logs, the value is only exposed to the builds" publicKeyPathP :: Parser T.Text publicKeyPathP = option (T.pack <$> str) $ long "public-key" <> metavar "PATH" <> help "Path to the public SSH key" privateKeyPathP :: Parser T.Text privateKeyPathP = option (T.pack <$> str) $ long "private-key" <> metavar "PATH" <> help "Path to the private SSH key" accessKeyLabelP :: Parser T.Text accessKeyLabelP = option (T.pack <$> str) $ long "label" <> help "A label for the Access Key" groupOwnerP :: T.Text -> Parser GroupOwner groupOwnerP htext = option (GroupOwner . T.pack <$> str) $ long "group-owner" <> help (T.unpack htext) groupNameP :: T.Text -> Parser GroupName groupNameP htext = option (GroupName . T.pack <$> str) $ short 'g' <> long "group" <> help (T.unpack htext) privilegeLevelP :: Parser PrivilegeLevel privilegeLevelP = let reader' :: T.Text -> Either T.Text PrivilegeLevel reader' t = maybe (Left t) pure . privilegeLevelFromText $ t in option (eitherTextReader reader') $ short 'p' <> long "privileges" <> help "The desired privilege level: read, write or admin"
irreverent-pixel-feats/bitbucket
bitbucket-optparse/src/Irreverent/Bitbucket/Options.hs
bsd-3-clause
8,924
0
15
1,779
2,344
1,233
1,111
246
2
{-# LANGUAGE ForeignFunctionInterface #-} module IGraph (Color, subgraphIsomorphisms) where import Utilities import Control.Exception (bracket) import Data.Array import Data.IORef import Data.List (genericLength) import qualified Data.Map as M import Foreign.C import Foreign.Marshal import Foreign.Marshal.Unsafe import Foreign.Ptr import qualified Data.Graph.Wrapper as G import qualified Data.Graph.Wrapper.Internal as G type Color = Int subgraphIsomorphisms :: Ord a => G.Graph a Color -> G.Graph a Color -> [M.Map a a] subgraphIsomorphisms g_smaller g_larger = [M.fromList [(i_smaller, G.indexGVertexArray g_larger ! n_larger) | (i_smaller, n_larger) <- fromJust (elems (G.indexGVertexArray g_smaller) `zipEqual` raw_subiso)] | raw_subiso <- raw_subisos] where raw_subisos = subgraphIsomorphisms' [(G.gVertexVertexArray g_smaller ! m, ns) | (m, ns) <- assocs (G.graph g_smaller)] [(G.gVertexVertexArray g_larger ! m, ns) | (m, ns) <- assocs (G.graph g_larger)] type Callback = Ptr CDouble -> IO CInt foreign import ccall "wrapper" mkCallback :: Callback -> IO (FunPtr Callback) foreign import ccall find_graph_subisomorphisms :: CInt -> Ptr CInt -> CInt -> Ptr CDouble -> CInt -> Ptr CInt -> CInt -> Ptr CDouble -> FunPtr Callback -> IO () type OutgoingEdges = [Int] type AdjacencyList = [(Color, OutgoingEdges)] type Subisomorphism = [Int] subgraphIsomorphisms' :: AdjacencyList -> AdjacencyList -> [Subisomorphism] subgraphIsomorphisms' g_smaller g_larger = unsafeLocalState $ withArray (map (fromIntegral . fst) g_smaller) $ \smaller_colors -> withArray (map (fromIntegral . fst) g_larger) $ \larger_colors -> withArray [fromIntegral i | (from, tos) <- [0..] `zip` map snd g_smaller, to <- tos, i <- [from, to]] $ \smaller_edges -> withArray [fromIntegral i | (from, tos) <- [0..] `zip` map snd g_larger, to <- tos, i <- [from, to]] $ \larger_edges -> do isos <- newIORef [] let callback mapping_ptr = do mapping <- peekArray (genericLength g_smaller) mapping_ptr --trace (show mapping) $ return () modifyIORef isos (map (\x -> round (x :: CDouble) - 1) mapping :) return 1 bracket (mkCallback callback) freeHaskellFunPtr $ \callback -> find_graph_subisomorphisms (genericLength g_smaller) smaller_colors (genericLength (concatMap snd g_smaller)) smaller_edges (genericLength g_larger) larger_colors (genericLength (concatMap snd g_larger)) larger_edges callback readIORef isos
osa1/chsc
IGraph.hs
bsd-3-clause
3,054
0
27
985
858
458
400
44
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main where import Ivory.Tower import Ivory.Language import Tower.AADL import Ivory.Tower.Config simpleTower :: Tower e () simpleTower = do towerModule towerDepModule towerDepends towerDepModule (c1in, c1out) <- channel (chtx, chrx) <- channel per <- period (Microseconds 1000) monitor "periodicM" $ do s <- state "local_st" handler per "tickh" $ do e <- emitter c1in 1 callback $ \_ -> do emit e (constRef (s :: Ref 'Global ('Stored Uint8))) monitor "withsharedM" $ do s <- state "last_m2_chan1_message" handler c1out "fromActiveh" $ do e <- emitter chtx 1 callback $ \m -> do refCopy s m emitV e true handler chrx "readStateh" $ do callback $ \_m -> do s' <- deref s call_ debug_print "rsh: " call_ debug_printhex8 s' call_ debug_println "" -------------------------------------------------------------------------------- debug_println :: Def('[IString] ':-> ()) debug_println = importProc "debug_println" "debug.h" debug_printhex8 :: Def('[Uint8] ':-> ()) debug_printhex8 = importProc "debug_printhex8" "debug.h" debug_print :: Def('[IString] ':-> ()) debug_print = importProc "debug_print" "debug.h" [ivory| struct Foo { foo :: Stored Uint8 } |] fooMod :: Module fooMod = package "foo" (defStruct (Proxy :: Proxy "Foo")) simpleTower2 :: Tower e () simpleTower2 = do towerModule fooMod towerDepends fooMod (c1in, c1out) <- channel per <- period (Microseconds 1000) monitor "m1" $ do s <- state "local_st" handler per "tick" $ do e <- emitter c1in 1 callback $ \_ -> emit e (constRef (s :: Ref 'Global ('Struct "Foo"))) -- callback $ \_ -> emit e (constRef (s :: Ref Global (Array 3 (Stored Uint8)))) monitor "m2" $ do s <- state "last_m2_chan1_message" handler c1out "chan1msg" $ do callback $ \m -> refCopy s m -------------------------------------------------------------------------------- main :: IO () main = compileTowerAADL id p simpleTower where p topts = fmap fst $ getConfig' topts $ aadlConfigParser (defaultAADLConfig { configSystemOS = EChronos , configSystemAddr = Nothing , configSystemHW = PIXHAWK }) [ivory| import (stdio.h, printf) void printf(string x, uint8_t y) |] towerDepModule :: Module towerDepModule = package "towerDeps" $ do incl debug_println incl debug_print incl debug_printhex8 incl printf
GaloisInc/tower
tower-aadl/test-echronos/Simple.hs
bsd-3-clause
2,801
0
24
637
783
380
403
79
1
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable -} module Fragment.Annotation.Ast ( module X ) where import Fragment.Annotation.Ast.Term as X
dalaing/type-systems
src/Fragment/Annotation/Ast.hs
bsd-3-clause
251
0
4
47
23
17
6
3
0
-- File created: 2009-07-15 11:00:10 module Haschoo.Evaluator.Standard (context) where import Haschoo.Types (ScmValue, Context, mkContext) import qualified Haschoo.Evaluator.Standard.Boolean as Boolean import qualified Haschoo.Evaluator.Standard.Characters as Characters import qualified Haschoo.Evaluator.Standard.Control as Control import qualified Haschoo.Evaluator.Standard.Equivalence as Equivalence import qualified Haschoo.Evaluator.Standard.Eval as Eval import qualified Haschoo.Evaluator.Standard.IO as IO import qualified Haschoo.Evaluator.Standard.Numeric as Numeric import qualified Haschoo.Evaluator.Standard.PairsLists as PairsLists import qualified Haschoo.Evaluator.Standard.Strings as Strings import qualified Haschoo.Evaluator.Standard.Symbols as Symbols import qualified Haschoo.Evaluator.Standard.Vectors as Vectors procedures :: [(String, ScmValue)] procedures = concat [ Boolean.procedures , Characters.procedures , Control.procedures , Equivalence.procedures , Eval.procedures , IO.procedures , Numeric.procedures , PairsLists.procedures , Strings.procedures , Symbols.procedures , Vectors.procedures ] context :: Context context = mkContext procedures
Deewiant/haschoo
Haschoo/Evaluator/Standard.hs
bsd-3-clause
1,432
0
7
362
229
160
69
27
1
import Data.HBDD.Operations import Control.Monad.State.Strict import Data.HBDD.ROBDDContext import Data.HBDD.ROBDDState import Data.List import Data.Either import Prelude hiding(and,or,not) import qualified Data.Map as M -- | USA graph coloring, but with fewer states (to make computation times more acceptable). main :: IO () main = let (numToState, bdd) = usa in let (bdd', context) = runState bdd mkContext in case getSat context bdd' >>= (return . outputColors numToState) of Nothing -> return () Just s -> putStrLn s -- | Outputs the color of a state on the format "STATE Color\n\r" outputColors :: M.Map Int String -> [Either Int Int] -> String outputColors numToState result = foldr1 (++) $ map numberToState goodColors where goodColors = rights result numToColor = M.fromList $ [(0, "red"), (1, "green"), (2, "blue"), (3, "yellow")] numberToState num = let nameId = (num `div` 4) * 4 colorId = num `mod` 4 in M.findWithDefault undefined nameId numToState ++ " " ++ M.findWithDefault undefined colorId numToColor ++ "\n\r" -- | Restriction saying that the neighbourgs of a node cannot have the same color edge :: Int -> Int -> ROBDDState Int edge state1 state2 = (state1Color1 .=>. notState2Color1) .&. (state1Color2 .=>. notState2Color2) .&. (state1Color3 .=>. notState2Color3) .&. (state1Color4 .=>. notState2Color4) where state1Color1 = singletonC $ state1 + 0 -- r state1Color2 = singletonC $ state1 + 1 -- g state1Color3 = singletonC $ state1 + 2 -- b state1Color4 = singletonC $ state1 + 3 -- y notState2Color1 = singletonNotC $ state2 + 0 -- r notState2Color2 = singletonNotC $ state2 + 1 -- g notState2Color3 = singletonNotC $ state2 + 2 -- b notState2Color4 = singletonNotC $ state2 + 3 -- y -- | Restrictions saying that a state has only one color oneColor :: Int -> ROBDDState Int oneColor statec = foldr1 (.|.) $ map forbid colors where forbid i = singletonC i .&. foldr1 (.&.) [ singletonNotC c | c <- colors, c /= i ] color1 = statec + 0 -- r color2 = statec + 1 -- g color3 = statec + 2 -- b color4 = statec + 3 -- y colors = [ color1, color2, color3, color4 ] -- | BDD of the USA graph-coloring problem. usa :: (M.Map Int String, ROBDDState Int) usa = (toName, (foldr1 (.&.) $ map oneColor allStates) .&. edge az ca .&. edge az nv .&. edge ca nv .&. edge ca or_ .&. edge id_ mt .&. edge id_ nv .&. edge id_ or_ .&. edge id_ wa .&. edge nv or_ .&. edge or_ wa) where allStates = [az, ca, id_, mt, nv, or_, wa] toName = M.fromList $ [(az, "AZ"), (ca, "CA"), (id_, "ID"), (mt, "MT"), (nv, "NV") , (or_, "OR"), (wa, "WA") ] az = 3 * 4 :: Int ca = 5 * 4 :: Int id_ = 12 * 4 :: Int mt = 26 * 4 :: Int nv = 28 * 4 :: Int or_ = 37 * 4 :: Int wa = 47 * 4 :: Int
sebcrozet/HBDD
Demos/ColorMapSimpl.hs
bsd-3-clause
3,878
0
18
1,698
990
549
441
63
2
{-# LANGUAGE OverloadedStrings #-} module Gli.Setup where import qualified Data.Attoparsec.Text as P import qualified Data.Map.Strict as M import qualified Data.Text as T import Data.Yaml import Gli.Gitlab import Gli.Types import Network.URI import System.Process setupProject :: String -> IO () setupProject file = do origin <- readProcess "git" ["config", "--get", "remote.origin.url"] "" case P.parseOnly parseGitUrl (T.pack (origin)) of Left msg -> print msg Right gitUrl -> do print gitUrl cfg <- decodeFile file :: IO (Maybe GliCfg) case cfg of Nothing -> putStrLn $ mappend "Unable to parse file " (show file) Just b -> if M.null matchedKeyVal then putStrLn $ mappend "Unable to find a relevent key for \ \the domain, please check the config \ \file " (show file) else do project <- getProject (T.strip (T.pack origin)) (head $ M.elems $ matchedKeyVal) encodeFile localYmlFile (LocalYmlContent (MasterFileConfig file matchedKey) project) appendFile gitInfoExcludeFile localYmlFile where matchedKey = head $ M.keys $ matchedKeyVal matchedKeyVal = fetchKeyFromAccount (accounts b) (domain gitUrl) parseGitUrl :: P.Parser GitUrl parseGitUrl = do _ <- P.string "git@" d <- P.takeTill (':' ==) _ <- P.char ':' r <- P.takeTill ('\n' ==) return $ GitUrl d r fetchKeyFromAccount :: Account -> T.Text -> M.Map T.Text AccountConfig fetchKeyFromAccount a g = M.filter (\v -> g == httpDomainConfig(url v)) (accountMap a) httpDomainConfig :: String -> T.Text httpDomainConfig u = case parseURI u of Nothing -> error "Unable to find remote url" Just a -> case uriAuthority a of Nothing -> error "Unable to parse the url" Just b -> T.pack $ uriRegName b accountMap :: Account -> M.Map T.Text AccountConfig accountMap (Account acc) = acc
goromlagche/gli
src/gli/setup.hs
bsd-3-clause
2,149
0
24
683
615
306
309
53
4
module Limonad.Interface.Types where import qualified Data.ByteString as B import qualified Data.Time as Time import qualified Codec.MIME.Type as MIME import qualified Limonad.Templates.Shortcuts as Tpl import Data.Functor import Limonad.Utils import Limonad.Types data Content = Content (IO B.ByteString) data View = View { getStatusCode :: HttpStatus, getMimeType :: MIME.Type, getDate :: Maybe Time.UTCTime, getExpire :: Maybe Time.UTCTime, getContent :: Content } data Request = Request { getMethod :: Maybe String, getParams :: [(String, String)], getRefer :: Maybe String, getHost :: Maybe String } data Route = Route { getPath :: String, getAllowedMethod :: [String] } type Routes = [Route] class Status a where code :: a -> Int string :: a -> String data HttpStatus = Continue | SwitchingProtocols | Ok | Created | Accepted | NonAuthoritativeInformation | NoContent | ResetContent | PartialContent | MultipleChoices | MovedPermanently | Found | SeeOther | NotModified | UseProxy | TemporaryRedirect | BadRequest | Unauthorized | PaymentRequired | Forbidden | NotFound | MethodNotAllowed | NotAcceptable | ProxyAuthenticationRequired | RequestTimeout | Conflict | Gone | LengthRequired | PreconditionFailed | RequestEntityTooLarge | RequestURITooLong | UnsupportedMediaType | RequestedRangeNotSatisfiable | ExpectationFailed | IMATeapot | InternalServerError | NotImplemented | BadGateway | ServiceUnavailable | GatewayTimeout | HTTPVersionNotSupported instance Status HttpStatus where code Continue = 100 code SwitchingProtocols = 101 code Ok = 200 code Created = 201 code Accepted = 202 code NonAuthoritativeInformation = 203 code NoContent = 204 code ResetContent = 205 code PartialContent = 206 code MultipleChoices = 300 code MovedPermanently = 301 code Found = 302 code SeeOther = 303 code NotModified = 304 code UseProxy = 305 code TemporaryRedirect = 307 code BadRequest = 400 code Unauthorized = 401 code PaymentRequired = 402 code Forbidden = 403 code NotFound = 404 code MethodNotAllowed = 405 code NotAcceptable = 406 code ProxyAuthenticationRequired = 407 code RequestTimeout = 408 code Conflict = 409 code Gone = 410 code LengthRequired = 411 code PreconditionFailed = 412 code RequestEntityTooLarge = 413 code RequestURITooLong = 414 code UnsupportedMediaType = 415 code RequestedRangeNotSatisfiable = 416 code ExpectationFailed = 417 code IMATeapot = 418 code InternalServerError = 500 code NotImplemented = 501 code BadGateway = 502 code ServiceUnavailable = 503 code GatewayTimeout = 504 code HTTPVersionNotSupported = 505 string Continue = "Continue" string SwitchingProtocols = "Switching Protocols" string Ok = "OK" string Created = "Created" string Accepted = "Accepted" string NonAuthoritativeInformation = "Non-Authoritative Information" string NoContent = "No Content" string ResetContent = "Reset Content" string PartialContent = "Partial Content" string MultipleChoices = "Multiple Choices" string MovedPermanently = "Moved Permanently" string Found = "Found" string SeeOther = "See Other" string NotModified = "Not Modified" string UseProxy = "Use Proxy" string TemporaryRedirect = "Temporary Redirect" string BadRequest = "Bad Request" string Unauthorized = "Unauthorized" string PaymentRequired = "Payment Required" string Forbidden = "Forbidden" string NotFound = "Not Found" string MethodNotAllowed = "Method Not Allowed" string NotAcceptable = "Not Acceptable" string ProxyAuthenticationRequired = "Proxy Authentication Required" string RequestTimeout = "Request Timeout" string Conflict = "Conflict" string Gone = "Gone" string LengthRequired = "Length Required" string PreconditionFailed = "Precondition Failed" string RequestEntityTooLarge = "Request Entity Too Large" string ExpectationFailed = "Expectation Failed" string IMATeapot = "I'm a teapot" string InternalServerError = "Internal Server Error" string NotImplemented = "Not Implemented" string BadGateway = "Bad Gateway" string ServiceUnavailable = "Service Unavailable" string GatewayTimeout = "Gateway Timeout" string HTTPVersionNotSupported = "HTTP Version Not Supported" instance Show HttpStatus where show a = show $ code a ++ string a text :: IO String -> View text c = View { getMimeType = MIME.nullType, getDate = Nothing, getExpire = Nothing, getContent = Content (s2bs <$> c) } html :: IO B.ByteString -> View html c = View { getMimeType = MIME.Type { mimeType = MIME.Application "xhtml+xml", mimeParams = [] }, getDate = Nothing, getExpire = Nothing, getContent = Content $ c } tpl :: FilePath -> Env -> View tpl f e = View { getMimeType = MIME.Type { mimeType = MIME.Application "xhtml+xml", mimeParams = [] }, getDate = Nothing, getExpire = Nothing, getContent = Content (s2bs <$> Tpl.renderFile f e) } css :: IO B.ByteString -> View css c = View { getMimeType = MIME.Type { mimeType = MIME.Text "css", mimeParams = [] }, getDate = Nothing, getExpire = Nothing, getContent = Content $ c } js :: IO B.ByteString -> View js c = View { getMimeType = MIME.Type { mimeType = MIME.Text "javascript", mimeParams = [] }, getDate = Nothing, getExpire = Nothing, getContent = Content $ c } mkEnv :: Request -> Env mkEnv r = Env [Static a b |(a, b) <- getParams r] defaultRoute :: String -> Route defaultRoute p = Route { getPath = p } (/+) :: Routes -> String -> Routes (/+) r n = r /: (defaultRoute n) (/:) :: Routes -> Route -> Routes (/:) r n = n:r
davbaumgartner/limonad
Limonad/Interface/Types.hs
bsd-3-clause
5,888
81
11
1,324
1,621
890
731
188
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleContexts, FlexibleInstances, TypeSynonymInstances #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} {-| Extension of Funsat.Circuit to generate RPO constraints as boolean circuits -} module Narradar.Constraints.SAT.RPOCircuit (Circuit(..) ,ECircuit(..) ,NatCircuit(..) ,OneCircuit(..), oneDefault, oneExist ,RPOCircuit(..), termGt_, termGe_, termEq_ ,RPOExtCircuit(..) ,ExistCircuit(..) ,AssertCircuit(..), assertCircuits ,CastCircuit(..), CastRPOCircuit(..) ,HasPrecedence(..), precedence ,HasFiltering(..), listAF, inAF ,HasStatus(..), useMul, lexPerm ,Shared(..), FrozenShared(..), runShared ,EvalM, Eval, EvalF(..), BEnv, BIEnv ,runEval, runEvalM, evalB, evalN ,Graph(..), shareGraph, shareGraph' ,Tree(..), simplifyTree, printTree, mapTreeTerms ,ECircuitProblem(..), RPOCircuitProblem(..) ,CNF(..) ,removeComplex, removeExist ,toCNF, toCNF' ,projectECircuitSolution, projectRPOCircuitSolution ,reconstructNatsFromBits ) where {- This file is heavily based on parts of funsat. funsat is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. funsat 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with funsat. If not, see <http://www.gnu.org/licenses/>. Copyright 2008 Denis Bueno -} import Control.Applicative import Control.Arrow (first, second) import Control.Exception as CE (assert) import Control.Monad.Cont import Control.Monad.Reader import Control.Monad.RWS import Control.Monad.State.Strict hiding ((>=>), forM_) import Data.Bimap( Bimap ) import Data.ByteString.Lazy.Char8 (ByteString) import Data.Foldable (Foldable, foldMap) import Data.List( nub, foldl', sortBy, (\\)) import Data.Map( Map ) import Data.Maybe( fromJust ) import Data.Hashable import Data.Monoid import Data.Set( Set ) import Data.Traversable (Traversable, traverse, fmapDefault, foldMapDefault) import Prelude hiding( not, and, or, (>) ) import Funsat.ECircuit ( Circuit(..) , ECircuit(..) , NatCircuit(..) , ExistCircuit(..) , CastCircuit(..) , CircuitHash, falseHash, trueHash , Eval, EvalF(..), BEnv, BIEnv, runEval, fromBinary , ECircuitProblem(..) , projectECircuitSolution, reconstructNatsFromBits) import Funsat.Types( CNF(..), Lit(..), Var(..), var, lit, Solution(..), litSign, litAssignment ) import qualified Narradar.Types.ArgumentFiltering as AF import Narradar.Types hiding (Var,V,var,fresh) import Narradar.Utils ( chunks, selectSafe, safeAtL, on ) import System.Directory (getTemporaryDirectory) import System.FilePath import System.IO import qualified Data.ByteString.Lazy.Char8 as BS import qualified Data.Graph.Inductive.Graph as Graph import qualified Data.Graph.Inductive.Graph as G import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.Traversable as T import qualified Data.Bimap as Bimap import qualified Funsat.Circuit as Circuit import qualified Funsat.ECircuit as ECircuit import qualified Prelude as Prelude import qualified Data.HashMap as HashMap type k :->: v = HashMap.HashMap k v type k :<->: v = Bimap.Bimap k v class Circuit repr => OneCircuit repr where -- | @one bb = length (filter id bb) == 1@ one :: (Ord var, Show var) => [repr var] -> repr var one = oneDefault oneExist :: (Ord v, Show v, ECircuit repr, ExistCircuit repr) => [repr v] -> repr v oneExist [] = false oneExist vv = (`runCont` id) $ do ones <- replicateM (length vv) (cont exists) zeros <- replicateM (length vv) (cont exists) let encoding = andL [ (one_i `iff` ite b_i zero_i1 one_i1) `and` ( zero_i `iff` (not b_i `and` zero_i1)) | (b_i, one_i, zero_i, one_i1, zero_i1) <- zip5 vv ones zeros (tail ones ++ [false]) (tail zeros ++ [true]) ] return (head ones `and` encoding) where zip5 (a:aa) (b:bb) (c:cc) (d:dd) (e:ee) = (a,b,c,d,e) : zip5 aa bb cc dd ee zip5 _ _ _ _ _ = [] oneDefault :: (Ord v, Show v, Circuit repr) => [repr v] -> repr v oneDefault [] = false oneDefault (v:vv) = (v `and` none vv) `or` (not v `and` oneDefault vv) where none = foldr and true . map not class NatCircuit repr => RPOCircuit repr tid tvar | repr -> tid tvar where termGt, termGe, termEq :: (HasPrecedence v tid, HasFiltering v tid, HasStatus v tid ,Ord v, Show v, Hashable v ,Eq tvar, Pretty tvar, Show tvar, Hashable tvar, Ord tvar) => Term (TermF tid) tvar -> Term (TermF tid) tvar -> repr v termGe s t = termGt s t `or` termEq s t class RPOCircuit repr tid tvar => RPOExtCircuit repr tid tvar where exGt, exGe, exEq :: (HasPrecedence v tid, HasFiltering v tid, HasStatus v tid ,Ord v, Hashable v, Show v) => tid -> tid -> [Term (TermF tid) tvar] -> [Term (TermF tid) tvar] -> repr v exGe id_s id_t ss tt = exGt id_s id_t ss tt `or` exEq id_s id_t ss tt class AssertCircuit repr where assertCircuit :: repr v -- * Assertion side-effect -> repr v -- * expression -> repr v -- * expression assertCircuits [] e = e assertCircuits (a:aa) e = assertCircuit a $ assertCircuits aa e class HasPrecedence v a | a -> v where precedence_v :: a -> v class HasFiltering v a | a -> v where listAF_v :: a -> v filtering_vv :: a -> [v] class HasStatus v id | id -> v where useMul_v :: id -> v lexPerm_vv :: id -> Maybe [[v]] precedence :: (NatCircuit repr, HasPrecedence v id, Ord v, Hashable v, Show v) => id -> repr v precedence = nat . precedence_v listAF :: (Circuit repr, HasFiltering v id, Ord v, Hashable v, Show v) => id -> repr v listAF = input . listAF_v {-# INLINE inAF #-} inAF :: (Circuit repr, HasFiltering v id, Ord v, Hashable v, Show v) => Int -> id -> repr v inAF i = input . (!! pred i) . filtering_vv useMul :: (Circuit repr, HasStatus v id, Ord v, Hashable v, Show v) => id -> repr v useMul = input . useMul_v lexPerm :: (Circuit repr, HasStatus v id, Ord v, Hashable v, Show v) => id -> Maybe [[repr v]] lexPerm = (fmap.fmap.fmap) input . lexPerm_vv termGt_, termEq_, termGe_ :: (Hashable id, Ord id, HasStatus var id, HasPrecedence var id, HasFiltering var id ,Ord var, Hashable var, Show var ,Eq tvar, Ord tvar, Hashable tvar, Show tvar, Pretty tvar ,ECircuit repr, RPOExtCircuit repr id tvar) => Term (TermF id) tvar -> Term (TermF id) tvar -> repr var termGt_ s t | s == t = false | Just id_t <- rootSymbol t , Just id_s <- rootSymbol s = cond1 id_s id_t tt_s tt_t `or` cond2 id_s tt_s | Just id_s <- rootSymbol s = cond2 id_s tt_s | otherwise = false where tt_s = directSubterms s tt_t = directSubterms t cond1 id_s id_t tt_s tt_t = all (\(t_j, j) -> inAF j id_t --> (s > t_j)) (zip tt_t [1..]) `and` (listAF id_t --> and (listAF id_s) (or (precedence id_s `gt` precedence id_t) (and (precedence id_s `eq` precedence id_t) (exGt id_s id_t tt_s tt_t)))) cond2 id_s tt_s = any (\(s_i,i) -> inAF i id_s `and` ((s_i > t) `or` (listAF id_s `and` (s_i ~~ t)))) (zip tt_s [1..]) all f = andL . map f any f = orL . map f infixr 8 > infixr 8 ~~ infixr 7 --> s > t = termGt s t s ~~ t = termEq s t a --> b = onlyif a b termGe_ (Pure s) (Pure t) = if s == t then true else false termGe_ s t | s == t = true | isVar s = not(listAF id_t) `and` all (\(t_j,j) -> inAF j id_t --> s ~~ t_j) (zip tt [1..]) | Just id_s <- rootSymbol s , isVar t = ite (listAF id_s) (any (\(s_i,i) -> inAF i id_s /\ s_i >~ t) (zip ss [1..])) (all (\(s_i,i) -> inAF i id_s --> s_i >~ t) (zip ss [1..])) | id_s == id_t = ite (listAF id_s) (exGe id_s id_t ss tt) (all (\(s_i,t_i,i) -> inAF i id_s --> s_i >~ t_i) (zip3 ss tt [1..])) | otherwise = ite (listAF id_s) (ite (listAF id_t) ((precedence id_s `eq` precedence id_t) `and` exGe id_s id_t ss tt) (all (\(t_j,j) -> inAF j id_t --> s >~ t_j) (zip tt [1..]))) (all (\(s_i,i) -> inAF i id_s --> s_i >~ t) (zip ss [1..])) where ss = directSubterms s tt = directSubterms t ~(Just id_s) = rootSymbol s ~(Just id_t) = rootSymbol t all f = andL . map f any f = orL . map f infixr 8 /\, >, >~, ~~ infixr 7 --> s > t = termGt s t s >~ t = termGe s t s ~~ t = termEq s t a /\ b = a `and` b a --> b = onlyif a b termEq_ (Pure s) (Pure t) = if s == t then true else false termEq_ s t | s == t = true | isVar s = not(listAF id_t) `and` all (\(t_j,j) -> inAF j id_t --> s ~~ t_j) (zip tt [1..]) | isVar t = not(listAF id_s) `and` all (\(s_i,i) -> inAF i id_s --> s_i ~~ t) (zip ss [1..]) | id_s == id_t = ite (listAF id_s) (exEq id_s id_t ss tt) (all (\(s_i,i) -> inAF i id_s --> s_i ~~ t) (zip ss [1..])) | otherwise = ite (listAF id_s) (ite (listAF id_t) ((precedence id_s `eq` precedence id_t) `and` exEq id_s id_t ss tt) (all (\(t_j,j) -> inAF j id_t --> s ~~ t_j) (zip tt [1..]))) (all (\(s_i,i) -> inAF i id_s --> s_i ~~ t) (zip ss [1..])) where ss = directSubterms s tt = directSubterms t ~(Just id_s) = rootSymbol s ~(Just id_t) = rootSymbol t all f = andL . map f any f = orL . map f infixr 8 > infixr 8 ~~ infixr 7 --> s > t = termGt s t s ~~ t = termEq s t a --> b = onlyif a b class CastRPOCircuit c cOut tid tvar | c -> tid tvar where castRPOCircuit :: ( HasPrecedence v tid, HasFiltering v tid, HasStatus v tid , Ord v, Hashable v, Show v , Hashable tid, Ord tid , Hashable tvar, Ord tvar, Show tvar, Pretty tvar) => c v -> cOut v instance CastCircuit Circuit.Tree c => CastRPOCircuit Circuit.Tree c id var where castRPOCircuit = castCircuit instance CastCircuit ECircuit.Tree c => CastRPOCircuit ECircuit.Tree c id var where castRPOCircuit = castCircuit -- | A `Circuit' constructed using common-subexpression elimination. This is a -- compact representation that facilitates converting to CNF. See `runShared'. newtype Shared tid tvar var = Shared { unShared :: State (CMaps tid tvar var) CCode } -- | A shared circuit that has already been constructed. data FrozenShared tid tvar var = FrozenShared !CCode !(CMaps tid tvar var) deriving Eq frozenShared code maps = FrozenShared code maps instance (Hashable id, Show id, Hashable tvar, Show tvar, Hashable var, Show var) => Show (FrozenShared id tvar var) where showsPrec p (FrozenShared c maps) = ("FrozenShared " ++) . showsPrec p c . showsPrec p maps{hashCount=[]} -- | Reify a sharing circuit. runShared :: (Hashable id, Ord id, Hashable tvar, Ord tvar) => Shared id tvar var -> FrozenShared id tvar var runShared = runShared' emptyCMaps runShared' :: (Hashable id, Ord id, Hashable tvar, Ord tvar) => CMaps id tvar var -> Shared id tvar var -> FrozenShared id tvar var runShared' maps = uncurry frozenShared . (`runState` emptyCMaps) . unShared getChildren :: (Ord v, Hashable v) => CCode -> CircuitHash :<->: v -> v getChildren code codeMap = case Bimap.lookup (circuitHash code) codeMap of Nothing -> findError Just c -> c where findError = error $ "getChildren: unknown code: " ++ show code getChildren' :: (Ord v) => CCode -> Bimap CircuitHash v -> v getChildren' code codeMap = case Bimap.lookup (circuitHash code) codeMap of Nothing -> findError Just c -> c where findError = error $ "getChildren: unknown code: " ++ show code instance (Hashable id, Ord id, Hashable tvar, Ord tvar, ECircuit c, NatCircuit c, ExistCircuit c) => CastCircuit (Shared id tvar) c where castCircuit = castCircuit . runShared instance (ECircuit c, NatCircuit c, ExistCircuit c) => CastCircuit (FrozenShared id tvar) c where castCircuit (FrozenShared code maps) = runCont (go code) id where go (CTrue{}) = return true go (CFalse{}) = return false go (CExist c) = cont exists go c@(CVar{}) = return $ input $ getChildren' c (varMap maps) go c@(CAnd{}) = liftM(uncurry and) . go2 $ getChildren c (andMap maps) go c@(COr{}) = liftM(uncurry or) . go2 $ getChildren c (orMap maps) go c@(CNot{}) = liftM not . go $ getChildren c (notMap maps) go c@(CXor{}) = liftM (uncurry xor) . go2 $ getChildren c (xorMap maps) go c@(COnlyif{}) = liftM (uncurry onlyif) . go2 $ getChildren c (onlyifMap maps) go c@(CIff{}) = liftM (uncurry iff) . go2 $ getChildren c (iffMap maps) go c@(CIte{}) = liftM (uncurry3 ite) . go3 $ getChildren c (iteMap maps) go c@CEq{} = liftM (uncurry eq) . go2 $ getChildren c (eqMap maps) go c@CLt{} = liftM (uncurry lt) . go2 $ getChildren c (ltMap maps) go c@CNat{} = return $ nat $ getChildren' c (natMap maps) go c@COne{} = liftM oneDefault $ mapM go $ getChildren c (oneMap maps) go2 (a,b) = do {a' <- go a; b' <- go b; return (a',b')} go3 (a,b,c) = do {a' <- go a; b' <- go b; c' <- go c; return (a',b',c')} uncurry3 f (x, y, z) = f x y z instance (Hashable id, Ord id, ECircuit c, NatCircuit c, ExistCircuit c) => CastRPOCircuit (Shared id var) c id var where castRPOCircuit = castCircuit instance (ECircuit c, NatCircuit c, ExistCircuit c) => CastRPOCircuit (FrozenShared id var) c id var where castRPOCircuit = castCircuit data CCode = CTrue { circuitHash :: !CircuitHash } | CFalse { circuitHash :: !CircuitHash } | CVar { circuitHash :: !CircuitHash } | CAnd { circuitHash :: !CircuitHash } | COr { circuitHash :: !CircuitHash } | CNot { circuitHash :: !CircuitHash } | CXor { circuitHash :: !CircuitHash } | COnlyif { circuitHash :: !CircuitHash } | CIff { circuitHash :: !CircuitHash } | CIte { circuitHash :: !CircuitHash } | CNat { circuitHash :: !CircuitHash } | CEq { circuitHash :: !CircuitHash } | CLt { circuitHash :: !CircuitHash } | COne { circuitHash :: !CircuitHash } | CExist { circuitHash :: !CircuitHash } deriving (Eq, Ord, Show, Read) instance Hashable CCode where hash = circuitHash -- | Maps used to implement the common-subexpression sharing implementation of -- the `Circuit' class. See `Shared'. data CMaps tid tvar v = CMaps { hashCount :: ![CircuitHash] -- ^ Source of unique IDs used in `Shared' circuit generation. Should not -- include 0 or 1. , varMap :: !(Bimap CircuitHash v) -- ^ Mapping of generated integer IDs to variables. , freshSet :: !(Set CircuitHash) , andMap :: !(CircuitHash :<->: (CCode, CCode)) , orMap :: !(CircuitHash :<->: (CCode, CCode)) , notMap :: !(CircuitHash :<->: CCode) , xorMap :: !(CircuitHash :<->: (CCode, CCode)) , onlyifMap :: !(CircuitHash :<->: (CCode, CCode)) , iffMap :: !(CircuitHash :<->: (CCode, CCode)) , iteMap :: !(CircuitHash :<->: (CCode, CCode, CCode)) , natMap :: !(CircuitHash :<->: v) , eqMap :: !(CircuitHash :<->: (CCode, CCode)) , ltMap :: !(CircuitHash :<->: (CCode, CCode)) , oneMap :: !(CircuitHash :<->: [CCode]) , termGtMap :: !((Term (TermF tid) tvar, Term (TermF tid) tvar) :->: CCode) , termGeMap :: !((Term (TermF tid) tvar, Term (TermF tid) tvar) :->: CCode) , termEqMap :: !((Term (TermF tid) tvar, Term (TermF tid) tvar) :->: CCode) } deriving instance (Hashable id, Show id, Hashable var, Show var, Hashable tvar, Show tvar) => Show (CMaps id tvar var) deriving instance (Eq id, Hashable id, Eq var, Hashable var, Eq tvar, Hashable tvar) => Eq (CMaps id tvar var) -- | A `CMaps' with an initial `hashCount' of 2. emptyCMaps :: (Hashable id, Ord id, Ord tvar, Hashable tvar) => CMaps id tvar var emptyCMaps = CMaps { hashCount = [2 ..] , varMap = Bimap.empty , freshSet = Set.empty , andMap = Bimap.empty , orMap = Bimap.empty , notMap = Bimap.empty , xorMap = Bimap.empty , onlyifMap = Bimap.empty , iffMap = Bimap.empty , iteMap = Bimap.empty , natMap = Bimap.empty , eqMap = Bimap.empty , ltMap = Bimap.empty , oneMap = Bimap.empty , termGtMap = mempty , termGeMap = mempty , termEqMap = mempty } -- prj: "projects relevant map out of state" -- upd: "stores new map back in state" {-# INLINE recordC #-} recordC :: (Ord a, Hashable a) => (CircuitHash -> b) -> (CMaps id tvar var -> Int :<->: a) -- ^ prj -> (CMaps id tvar var -> Int :<->: a -> CMaps id tvar var) -- ^ upd -> a -> State (CMaps id tvar var) b recordC _ _ _ x | x `seq` False = undefined recordC cons prj upd x = do s <- get c:cs <- gets hashCount maybe (do let s' = upd (s{ hashCount = cs }) (Bimap.insert c x (prj s)) put s' -- trace "updating map" (return ()) return (cons c)) (return . cons) $ Bimap.lookupR x (prj s) {-# INLINE recordC' #-} recordC' :: Ord a => (CircuitHash -> b) -> (CMaps id tvar var -> Bimap Int a) -- ^ prj -> (CMaps id tvar var -> Bimap Int a -> CMaps id tvar var) -- ^ upd -> a -> State (CMaps id tvar var) b recordC' _ _ _ x | x `seq` False = undefined recordC' cons prj upd x = do s <- get c:cs <- gets hashCount maybe (do let s' = upd (s{ hashCount = cs }) (Bimap.insert c x (prj s)) put s' -- trace "updating map" (return ()) return (cons c)) (return . cons) $ Bimap.lookupR x (prj s) instance Circuit (Shared id tvar) where false = Shared falseS true = Shared trueS input v = Shared $ recordC' CVar varMap (\s e -> s{ varMap = e }) v and = liftShared2 and_ where and_ c@CFalse{} _ = return c and_ _ c@CFalse{} = return c and_ CTrue{} c = return c and_ c CTrue{} = return c and_ hl hr = recordC CAnd andMap (\s e -> s{ andMap = e}) (hl, hr) or = liftShared2 or_ where or_ c@CTrue{} _ = return c or_ _ c@CTrue{} = return c or_ CFalse{} c = return c or_ c CFalse{} = return c or_ hl hr = recordC COr orMap (\s e -> s{ orMap = e }) (hl, hr) not = liftShared notS instance ExistCircuit (Shared id tvar) where exists k = Shared $ do c:cs <- gets hashCount modify $ \s -> s{freshSet = Set.insert c (freshSet s), hashCount=cs} unShared . k . Shared . return . CExist $ c instance ECircuit (Shared id tvar) where xor = liftShared2 xor_ where xor_ CTrue{} c = notS c xor_ c CTrue{} = notS c xor_ CFalse{} c = return c xor_ c CFalse{} = return c xor_ hl hr = recordC CXor xorMap (\s e' -> s{ xorMap = e' }) (hl, hr) iff = liftShared2 iffS onlyif = liftShared2 onlyif_ where onlyif_ CFalse{} _ = trueS onlyif_ c CFalse{} = notS c onlyif_ CTrue{} c = return c onlyif_ _ CTrue{} = trueS onlyif_ hl hr | hl == hr = trueS | otherwise = recordC COnlyif onlyifMap (\s e' -> s{ onlyifMap = e' }) (hl, hr) ite x t e = Shared $ do hx <- unShared x ht <- unShared t ; he <- unShared e ite_ hx ht he where ite_ CTrue{} ht _ = return ht ite_ CFalse{} _ he = return he ite_ hx ht he = recordC CIte iteMap (\s e' -> s{ iteMap = e' }) (hx, ht, he) falseS, trueS :: State (CMaps id tvar var) CCode falseS = return $ CFalse falseHash trueS = return $ CTrue trueHash notS CTrue{} = falseS notS CFalse{} = trueS notS (CNot i) = do {s <- get; return $ fromJust $ Bimap.lookup i (notMap s) } notS h = recordC CNot notMap (\s e' -> s{ notMap = e' }) h iffS CTrue{} c = return c iffS c CTrue{} = return c iffS CFalse{} c = notS c iffS c CFalse{} = notS c iffS hl hr | hl == hr = trueS | otherwise = recordC CIff iffMap (\s e' -> s{ iffMap = e' }) (hl, hr) {-# INLINE liftShared #-} liftShared f a = Shared $ do {h <- unShared a; f h} {-# INLINE liftShared2 #-} liftShared2 f a b = Shared $ do va <- unShared a vb <- unShared b f va vb instance OneCircuit (Shared id tvar) where one ss = Shared $ do xx <- sequence $ map unShared ss if null xx then falseS else recordC COne oneMap (\s e' -> s{oneMap = e'}) xx instance NatCircuit (Shared id tvar) where eq xx yy = Shared $ do x <- unShared xx y <- unShared yy if x == y then trueS else recordC CEq eqMap (\s e -> s {eqMap = e}) (x,y) lt xx yy = Shared $ do x <- unShared xx y <- unShared yy if x == y then falseS else recordC CLt ltMap (\s e -> s {ltMap = e}) (x,y) nat = Shared . recordC' CNat natMap (\s e -> s{ natMap = e }) instance (Ord tid, Hashable tid, RPOExtCircuit (Shared tid tvar) tid tvar) => RPOCircuit (Shared tid tvar) tid tvar where termGt s t = Shared $ do env <- get case HashMap.lookup (s,t) (termGtMap env) of Just v -> return v Nothing -> do me <- unShared $ termGt_ s t modify $ \env -> env{termGtMap = HashMap.insert (s,t) me (termGtMap env)} return me termEq s t = Shared $ do env <- get case (HashMap.lookup (s,t) (termEqMap env)) of Just v -> return v Nothing -> do me <- unShared $ termEq_ s t modify $ \env -> env{termEqMap = HashMap.insert (s,t) me (termEqMap env)} return me termGe s t = Shared $ do env <- get case (HashMap.lookup (s,t) (termGeMap env)) of Just v -> return v Nothing -> do me <- unShared $ termGe_ s t modify $ \env -> env{termGeMap = HashMap.insert (s,t) me (termGeMap env)} return me -- | Explicit tree representation, which is a generic description of a circuit. -- This representation enables a conversion operation to any other type of -- circuit. Trees evaluate from variable values at the leaves to the root. data TreeF term (a :: *) = TTrue | TFalse | TNot a | TAnd a a | TOr a a | TXor a a | TIff a a | TOnlyIf a a | TIte a a a | TEq a a | TLt a a | TOne [a] | TTermEq term term | TTermGt term term deriving (Show, Eq, Ord, Functor, Foldable, Traversable) type Tree id var = Tree' (Term (TermF id) var) data Tree' term v = TNat v | TLeaf v | TFix {tfix :: TreeF term (Tree' term v)} deriving (Eq, Ord, Show) tLeaf = TLeaf tNat = TNat tTrue = TFix TTrue tFalse = TFix TFalse tNot = TFix . TNot tOne = TFix . TOne tAnd = (TFix.) . TAnd tOr = (TFix.) . TOr tXor = (TFix.) . TXor tIff = (TFix.) . TIff tOnlyIf = (TFix.) . TOnlyIf tEq = (TFix.) . TEq tLt = (TFix.) . TLt tIte = ((TFix.).) . TIte tTermGt = (TFix.) . TTermGt tTermEq = (TFix.) . TTermEq tOpen (TFix t) = Just t tOpen _ = Nothing tClose = TFix tId TTrue = tTrue tId TFalse = tFalse tId (TNot n) = tNot n tId (TOne n) = tOne n tId (TAnd t1 t2) = tAnd t1 t2 tId (TOr t1 t2) = tOr t1 t2 tId (TXor t1 t2) = tXor t1 t2 tId (TIff t1 t2) = tIff t1 t2 tId (TOnlyIf t1 t2) = tOnlyIf t1 t2 tId (TEq t1 t2) = tEq t1 t2 tId (TLt t1 t2) = tLt t1 t2 tId (TIte c t e) = tIte c t e foldTree fnat _ _ (TNat v) = fnat v foldTree _ fleaf _ (TLeaf v) = fleaf v foldTree fn fl f (TFix t) = f (fmap (foldTree fn fl f) t) mapTreeTerms :: (Term (TermF id) var -> Term (TermF id') var') -> Tree id var v -> Tree id' var' v mapTreeTerms f = foldTree tNat tLeaf f' where f' (TTermGt t u) = tTermGt (f t) (f u) f' (TTermEq t u) = tTermGt (f t) (f u) f' t = tId t printTree :: (Pretty id, Pretty v, Pretty var) => Int -> Tree id var v -> Doc printTree p t = foldTree fn fl f t p where fl v _ = pPrint v fn v _ = pPrint v f TTrue _ = text "true" f TFalse _ = text "false" f (TNot t) p = pP p 9 $ text "!" <> t 9 f (TAnd t1 t2) p = pP p 5 $ text "AND" <+> (t1 5 $$ t2 5) -- f (TAnd t1 t2) p = pP p 5 $ pt 5 t1 <+> text "&" <+> pt 5 t2 f (TOr t1 t2) p = pP p 5 $ text "OR " <+> (t1 5 $$ t2 5) -- f (TOr t1 t2) p = pP p 5 $ t1 5 <+> text "||" <+> pt 5 t2 f (TXor t1 t2) p = pP p 5 $ t1 5 <+> text "xor" <+> t2 5 f (TIff t1 t2) p = pP p 3 $ t1 3 <+> text "<->" <+> t2 3 f (TOnlyIf t1 t2) p = pP p 3 $ t1 3 <+> text "-->" <+> t2 3 f (TIte c t e) p = pP p 2 $ text "IFTE" <+> (c 1 $$ t 1 $$ e 1) f (TEq n1 n2) p = pP p 7 (n1 1 <+> text "==" <+> n2 1) f (TLt n1 n2) p = pP p 7 (n1 1 <+> text "<" <+> n2 1) f (TOne vv) p = pP p 1 $ text "ONE" <+> (fsep $ punctuate comma $ map ($ 1) vv) f (TTermGt t u) p = pP p 6 $ pPrint t <+> text ">" <+> pPrint u f (TTermEq t u) p = pP p 6 $ pPrint t <+> text "=" <+> pPrint u pP prec myPrec doc = if myPrec Prelude.> prec then doc else parens doc collectIdsTree :: Ord id => Tree id var v -> Set id collectIdsTree = foldTree (const mempty) (const mempty) f where f (TNot t1) = t1 f (TAnd t1 t2) = mappend t1 t2 f (TOr t1 t2) = mappend t1 t2 f (TXor t1 t2) = mappend t1 t2 f (TOnlyIf t1 t2) = mappend t1 t2 f (TIff t1 t2) = mappend t1 t2 f (TIte t1 t2 t3) = t1 `mappend` t2 `mappend` t3 f (TTermGt t1 t2) = Set.fromList (collectIds t1) `mappend` Set.fromList (collectIds t2) f (TTermEq t1 t2) = Set.fromList (collectIds t1) `mappend` Set.fromList (collectIds t2) f TOne{} = mempty f TTrue = mempty f TFalse = mempty -- | Performs obvious constant propagations. simplifyTree :: (Eq var, Eq v, Eq id) => Tree id var v -> Tree id var v simplifyTree = foldTree TNat TLeaf f where f TFalse = tFalse f TTrue = tTrue f (TNot (tOpen -> Just TTrue)) = tFalse f (TNot (tOpen -> Just TFalse)) = tTrue f it@(TNot t) = tClose it f (TAnd (tOpen -> Just TFalse) _) = tFalse f (TAnd (tOpen -> Just TTrue) r) = r f (TAnd l (tOpen -> Just TTrue)) = l f (TAnd _ (tOpen -> Just TFalse)) = tFalse f it@TAnd{} = tClose it f (TOr (tOpen -> Just TTrue) _) = tTrue f (TOr (tOpen -> Just TFalse) r) = r f (TOr _ (tOpen -> Just TTrue)) = tTrue f (TOr l (tOpen -> Just TFalse)) = l f it@TOr{} = tClose it f (TXor (tOpen -> Just TTrue) (tOpen -> Just TTrue)) = tFalse f (TXor (tOpen -> Just TFalse) r) = r f (TXor l (tOpen -> Just TFalse)) = l f (TXor (tOpen -> Just TTrue) r) = tNot r f (TXor l (tOpen -> Just TTrue)) = tNot l f it@TXor{} = tClose it f (TIff (tOpen -> Just TFalse) (tOpen -> Just TFalse)) = tTrue f (TIff (tOpen -> Just TFalse) r) = tNot r f (TIff (tOpen -> Just TTrue) r) = r f (TIff l (tOpen -> Just TFalse)) = tNot l f (TIff l (tOpen -> Just TTrue)) = l f it@TIff{} = tClose it f it@(l `TOnlyIf` r) = case (tOpen l, tOpen r) of (Just TFalse,_) -> tTrue (Just TTrue,_) -> r (_, Just TTrue) -> tTrue (_, Just TFalse) -> tNot l _ -> tClose it f it@(TIte x t e) = case (tOpen x, tOpen t, tOpen e) of (Just TTrue,_,_) -> t (Just TFalse,_,_) -> e (_,Just TTrue,_) -> tOr x e (_,Just TFalse,_) -> tAnd (tNot x) e (_,_,Just TTrue) -> tOr (tNot x) t (_,_,Just TFalse) -> tAnd x t _ -> tClose it f t@(TEq x y) = if x == y then tTrue else tClose t f t@(TLt x y) = if x == y then tFalse else tClose t f (TOne []) = tFalse f t@TOne{} = tClose t f (TTermEq s t) | s == t = tTrue f t@TTermEq{} = tClose t f (TTermGt s t) | s == t = tFalse f t@TTermGt{} = tClose t instance (ECircuit c, NatCircuit c, OneCircuit c) => CastCircuit (Tree id var) c where castCircuit = foldTree input nat f where f TTrue = true f TFalse = false f (TAnd t1 t2) = and t1 t2 f (TOr t1 t2) = or t1 t2 f (TXor t1 t2) = xor t1 t2 f (TNot t) = not t f (TIff t1 t2) = iff t1 t2 f (TOnlyIf t1 t2) = onlyif t1 t2 f (TIte x t e) = ite x t e f (TEq t1 t2) = eq t1 t2 f (TLt t1 t2) = lt t1 t2 f (TOne tt) = one tt f c@(TTermEq t u) = error "cannot cast RPO constraints" f c@(TTermGt t u) = error "cannot cast RPO constraints" instance (ECircuit c, NatCircuit c, OneCircuit c, RPOCircuit c tid tvar) => CastRPOCircuit (Tree tid tvar) c tid tvar where castRPOCircuit = foldTree input nat f where f TTrue = true f TFalse = false f (TAnd t1 t2) = and t1 t2 f (TOr t1 t2) = or t1 t2 f (TXor t1 t2) = xor t1 t2 f (TNot t) = not t f (TIff t1 t2) = iff t1 t2 f (TOnlyIf t1 t2) = onlyif t1 t2 f (TIte x t e) = ite x t e f (TEq t1 t2) = eq t1 t2 f (TLt t1 t2) = lt t1 t2 f (TOne tt) = one tt f c@(TTermEq t u) = termEq t u f c@(TTermGt t u) = termGt t u instance Circuit (Tree id var) where true = tTrue false = tFalse input = tLeaf and = tAnd or = tOr not = tNot instance ECircuit (Tree id var) where xor = tXor iff = tIff onlyif = tOnlyIf ite = tIte instance NatCircuit (Tree id var) where eq = tEq lt = tLt nat = TNat instance OneCircuit (Tree id var) where one = tOne instance RPOCircuit (Tree id var) id var where termGt = tTermGt termEq = tTermEq -- ------------------ -- ** Circuit evaluator -- ------------------ newtype Flip t a b = Flip {unFlip::t b a} type EvalM = Flip EvalF fromLeft :: Either l r -> l fromLeft (Left l) = l fromRight :: Either l r -> r fromRight (Right r) = r runEvalM :: BIEnv e -> EvalM e a -> a runEvalM env = flip unEval env . unFlip instance Functor (EvalM v) where fmap f (Flip (Eval m)) = Flip $ Eval $ \env -> f(m env) instance Monad (EvalM v) where return x = Flip $ Eval $ \_ -> x m >>= f = Flip $ Eval $ \env -> runEvalM env $ f $ runEvalM env m instance MonadReader (BIEnv v) (EvalM v) where ask = Flip $ Eval $ \env -> env local f m = Flip $ Eval $ \env -> runEvalM (f env) m instance OneCircuit Eval where one tt = Eval (\env -> Right $ case filter id $ map (fromRight . (`unEval` env)) tt of (_:[]) -> True _ -> False) instance (Ord id) => RPOCircuit Eval id var where termGt t u = unFlip (Right `liftM` (>) evalRPO t u) termEq t u = unFlip (Right `liftM` (~~) evalRPO t u) data RPOEval v a = RPO {(>), (>~), (~~) :: a -> a -> Flip EvalF v Bool} evalB :: Eval v -> EvalM v Bool evalN :: Eval v -> EvalM v Int evalB c = liftM (fromRight :: Either Int Bool -> Bool) (eval c) evalN c = liftM (fromLeft :: Either Int Bool -> Int) (eval c) eval c = do {env <- ask; return (runEval env c)} evalRPO :: forall id v var. (Eq id, Ord id, HasPrecedence v id, HasStatus v id, HasFiltering v id ,Ord v, Hashable v, Show v ,Eq var ) => RPOEval v (Term (TermF id) var) evalRPO = RPO{..} where infixr 4 > infixr 4 >~ infixr 4 ~~ s >~ t = s > t <|> s ~~ t s ~~ t | s == t = return True | Just id_s <- rootSymbol s, tt_s <- directSubterms s , Just id_t <- rootSymbol t, tt_t <- directSubterms t , id_s == id_t = do af_s <- compFiltering id_s case af_s of Left i -> (tt_s !! pred i) ~~ t _ -> exeq s t | Just id_s <- rootSymbol s, tt_s <- directSubterms s , Just id_t <- rootSymbol t, tt_t <- directSubterms t = do af_s <- compFiltering id_s af_t <- compFiltering id_t case (af_s,af_t) of (Left i, _) -> safeAtL "RPOCircuit:928" tt_s (pred i) ~~ t (_, Left j) -> s ~~ safeAtL "RPOCircuit:929" tt_t (pred j) (_,_) -> evalB (precedence id_s `eq` precedence id_t) <&> exeq s t | Just id_s <- rootSymbol s, tt_s <- directSubterms s = do af_s <- compFiltering id_s case af_s of Left i-> safeAtL "RPOCircuit:935" tt_s (pred i) ~~ t _ -> return False | Just id_t <- rootSymbol t, tt_t <- directSubterms t = do af_t <- compFiltering id_t case af_t of Left j -> s ~~ safeAtL "RPOCircuit:941" tt_t (pred j) _ -> return False | otherwise = return False s > t | Just id_t <- rootSymbol t, tt_t <- directSubterms t , Just id_s <- rootSymbol s, tt_s <- directSubterms s , id_s == id_t = do af_s <- compFiltering id_s af_t <- compFiltering id_t case (af_s, af_t) of (Left i, _) -> safeAtL "RPOCircuit:955" tt_s (pred i) > t (_, Left j) -> s > safeAtL "RPOCircuit:956" tt_t (pred j) (Right ii,Right jj) -> anyM (>~ t) (sel 3 ii tt_s) <|> (allM (s >) (sel 4 jj tt_t) <&> exgt s t) | Just id_t <- rootSymbol t, tt_t <- directSubterms t , Just id_s <- rootSymbol s, tt_s <- directSubterms s = do af_s <- compFiltering id_s af_t <- compFiltering id_t case (af_s, af_t) of (Left i, Left j) -> safeAtL "RPOCircuit:698" tt_s (pred i) > safeAtL "RPOCircuit:698" tt_t (pred j) (Left i, _) -> safeAtL "RPOCircuit:698" tt_s (pred i) > t (_, Left j) -> s > safeAtL "RPOCircuit:699" tt_t (pred j) (Right ii,Right jj) -> anyM (>~ t) (sel 3 ii tt_s) <|> (allM (s >) (sel 4 jj tt_t) <&> (evalB (precedence id_s `gt` precedence id_t) <|> (evalB (precedence id_s `eq` precedence id_t) <&> exgt s t))) | Just id_s <- rootSymbol s, tt_s <- directSubterms s = do af_s <- compFiltering id_s case af_s of Left i -> safeAtL "RPOCircuit:709" tt_s (pred i) > t Right ii -> anyM (>~ t) (sel 5 ii tt_s) | otherwise = return False exgt, exeq :: Term (TermF id) var -> Term (TermF id) var -> Flip EvalF v Bool exgt s t | Just id_t <- rootSymbol t, tt <- directSubterms t , Just id_s <- rootSymbol s, ss <- directSubterms s = do af_s <- compFiltering id_s af_t <- compFiltering id_t let ss' = applyFiltering af_s ss tt' = applyFiltering af_t tt mul_s <- evalB (useMul id_s) mul_t <- evalB (useMul id_t) case (mul_s, mul_t) of (True, True) -> mulD ss' tt' (False, False) -> do ps <- evalPerm id_s pt <- evalPerm id_t lexD (maybe ss' (permute ss) ps) (maybe tt' (permute tt) pt) _ -> error "exgt: Cannot compare two symbols with incompatible statuses" exeq s t | Just id_t <- rootSymbol t, tt <- directSubterms t , Just id_s <- rootSymbol s, ss <- directSubterms s = do af_s <- compFiltering id_s af_t <- compFiltering id_t let ss' = applyFiltering af_s ss tt' = applyFiltering af_t tt mul_s <- evalB (useMul id_s) mul_t <- evalB (useMul id_t) case (mul_s, mul_t) of (True, True) -> muleqD ss' tt' (False, False) -> do ps <- evalPerm id_s pt <- evalPerm id_t lexeqD (maybe ss' (permute ss) ps) (maybe tt' (permute tt) pt) _ -> error "exeq:Cannot compare two symbols with incompatible statuses" lexD [] _ = return False lexD _ [] = return True lexD (f:ff) (g:gg) = (f > g) <|> (f ~~ g <&> lexD ff gg) lexeqD [] [] = return True lexeqD _ [] = return False lexeqD [] _ = return False lexeqD (f:ff) (g:gg) = (f ~~ g <&> lexeqD ff gg) mulD m1 m2 = do m1' <- differenceByM (~~) m1 m2 m2' <- differenceByM (~~) m2 m1 forall m2' $ \y-> exists m1' (> y) muleqD [] [] = return True muleqD (m:m1) m2 = acmatchM (~~m) m2 >>= \it -> case it of Just (_,m2) -> muleqD m1 m2 _ -> return False muleqD _ _ = return False differenceByM p = foldM rem1 where rem1 [] _ = return [] rem1 (x:xx) y = p x y >>= \b -> if b then return xx else rem1 xx y acmatchM p = go [] where go acc [] = return Nothing go acc (x:xs) = p x >>= \b -> if b then return $ Just (x, reverse acc ++ xs) else go (x:acc) xs infixr 3 <&> infixr 2 <|> (<|>) = liftM2 (||) (<&>) = liftM2 (&&) forall = flip allM exists = flip anyM allM f xx = Prelude.and `liftM` mapM f xx anyM f xx = Prelude.or `liftM` mapM f xx sel n ii = selectSafe ("Narradar.Constraints.SAT.RPOCircuit.Eval - " ++ show n) (map pred ii) permute ff ii = map fst $ dropWhile ( (<0) . snd) $ sortBy (compare `on` snd) (zip ff ii) on cmp f x y = f x `cmp` f y -- evalPerm :: HasStatus id v => id -> Flip Eval v (Maybe [Int]) evalPerm id = do bits <- (T.mapM . mapM . mapM) evalB (lexPerm id) let perm = (fmap.fmap) (\perm_i -> head ([i | (i,True) <- zip [1..] perm_i] ++ [-1])) bits return perm compFiltering id = do isList:filtering <- mapM (evalB.input) (listAF_v id : filtering_vv id) let positions = [ i | (i, True) <- zip [1..] filtering ] return $ if isList then Right positions else CE.assert (length positions == 1) $ Left (head positions) applyFiltering (Right ii) tt = selectSafe "RPOCircuit.verifyRPOAF.applyFiltering" (map pred ii) tt applyFiltering (Left j) tt = [safeAtL "RPOCircuit.verifyRPOAF.applyFiltering" tt (pred j)] sel6 = sel 6 sel7 = sel 7 sel8 = sel 8 sel9 = sel 9 -- ** Graph circuit -- | A circuit type that constructs a `G.Graph' representation. This is useful -- for visualising circuits, for example using the @graphviz@ package. newtype Graph v = Graph { unGraph :: State Graph.Node (Graph.Node, [Graph.LNode (NodeType v)], [Graph.LEdge EdgeType]) } -- | Node type labels for graphs. data NodeType v = NInput v | NTrue | NFalse | NAnd | NOr | NNot | NXor | NIff | NOnlyIf | NIte | NNat v | NEq | NLt | NOne | NTermGt String String | NTermEq String String deriving (Eq, Ord, Show, Read) data EdgeType = ETest -- ^ the edge is the condition for an `ite' element | EThen -- ^ the edge is the /then/ branch for an `ite' element | EElse -- ^ the edge is the /else/ branch for an `ite' element | EVoid -- ^ no special annotation | ELeft | ERight deriving (Eq, Ord, Show, Read) runGraph :: (G.DynGraph gr) => Graph v -> gr (NodeType v) EdgeType runGraph graphBuilder = let (_, nodes, edges) = evalState (unGraph graphBuilder) 1 in Graph.mkGraph nodes edges instance Circuit Graph where input v = Graph $ do n <- newNode return $ (n, [(n, NInput v)], []) true = Graph $ do n <- newNode return $ (n, [(n, NTrue)], []) false = Graph $ do n <- newNode return $ (n, [(n, NFalse)], []) not gs = Graph $ do (node, nodes, edges) <- unGraph gs n <- newNode return (n, (n, NNot) : nodes, (node, n, EVoid) : edges) and = binaryNode NAnd EVoid EVoid or = binaryNode NOr EVoid EVoid instance ECircuit Graph where xor = binaryNode NXor EVoid EVoid iff = binaryNode NIff EVoid EVoid onlyif = binaryNode NOnlyIf ELeft ERight ite x t e = Graph $ do (xNode, xNodes, xEdges) <- unGraph x (tNode, tNodes, tEdges) <- unGraph t (eNode, eNodes, eEdges) <- unGraph e n <- newNode return (n, (n, NIte) : xNodes ++ tNodes ++ eNodes , (xNode, n, ETest) : (tNode, n, EThen) : (eNode, n, EElse) : xEdges ++ tEdges ++ eEdges) instance NatCircuit Graph where eq = binaryNode NEq EVoid EVoid lt = binaryNode NLt ELeft ERight nat x = Graph $ do {n <- newNode; return (n, [(n, NNat x)],[])} instance OneCircuit Graph where one tt = Graph$ do (tips, nodes, edges) <- unzip3 `liftM` mapM unGraph tt me <- newNode let nodes' = (me, NOne) : concat nodes edges' = [(n, me, EVoid) | n <- tips ] ++ concat edges return (me, nodes', edges') instance Pretty id => RPOCircuit Graph id var where termGt t u = Graph $ do n <- newNode let me = (n, NTermGt (show$ pPrint t) (show$ pPrint u)) return (n, [me], []) termEq t u = Graph $ do n <- newNode let me = (n, NTermEq (show$ pPrint t) (show$ pPrint u)) return (n, [me], []) --binaryNode :: NodeType v -> Graph v -> Graph v -> Graph v {-# INLINE binaryNode #-} binaryNode ty ledge redge l r = Graph $ do (lNode, lNodes, lEdges) <- unGraph l (rNode, rNodes, rEdges) <- unGraph r n <- newNode return (n, (n, ty) : lNodes ++ rNodes, (lNode, n, ledge) : (rNode, n, redge) : lEdges ++ rEdges) newNode :: State Graph.Node Graph.Node newNode = do i <- get ; put (succ i) ; return i {- defaultNodeAnnotate :: (Show v) => LNode (FrozenShared v) -> [GraphViz.Attribute] defaultNodeAnnotate (_, FrozenShared (output, cmaps)) = go output where go CTrue{} = "true" go CFalse{} = "false" go (CVar _ i) = show $ extract i varMap go (CNot{}) = "NOT" go (CAnd{hlc=h}) = maybe "AND" goHLC h go (COr{hlc=h}) = maybe "OR" goHLC h goHLC (Xor{}) = "XOR" goHLC (Onlyif{}) = go (output{ hlc=Nothing }) goHLC (Iff{}) = "IFF" extract code f = IntMap.findWithDefault (error $ "shareGraph: unknown code: " ++ show code) code (f cmaps) defaultEdgeAnnotate = undefined dotGraph :: (Graph gr) => gr (FrozenShared v) (FrozenShared v) -> DotGraph dotGraph g = graphToDot g defaultNodeAnnotate defaultEdgeAnnotate -} -- | Given a frozen shared circuit, construct a `G.DynGraph' that exactly -- represents it. Useful for debugging constraints generated as `Shared' -- circuits. shareGraph :: (G.DynGraph gr, Eq v, Hashable v, Show v, Eq id, Pretty id, Hashable id, Eq tvar, Hashable tvar) => FrozenShared id tvar v -> gr (FrozenShared id tvar v) (FrozenShared id tvar v) shareGraph (FrozenShared output cmaps) = (`runReader` cmaps) $ do (_, nodes, edges) <- go output return $ Graph.mkGraph (nub nodes) (nub edges) where -- Invariant: The returned node is always a member of the returned list of -- nodes. Returns: (node, node-list, edge-list). go c@(CVar i) = return (i, [(i, frz c)], []) go c@(CTrue i) = return (i, [(i, frz c)], []) go c@(CFalse i) = return (i, [(i, frz c)], []) go c@(CNot i) = do (child, nodes, edges) <- extract i notMap >>= go return (i, (i, frz c) : nodes, (child, i, frz c) : edges) go c@(CAnd i) = extract i andMap >>= tupM2 go >>= addKids c go c@(COr i) = extract i orMap >>= tupM2 go >>= addKids c go c@(CXor i) = extract i xorMap >>= tupM2 go >>= addKids c go c@(COnlyif i) = extract i onlyifMap >>= tupM2 go >>= addKids c go c@(CIff i) = extract i iffMap >>= tupM2 go >>= addKids c go c@(CIte i) = do (x, y, z) <- extract i iteMap ( (cNode, cNodes, cEdges) ,(tNode, tNodes, tEdges) ,(eNode, eNodes, eEdges)) <- liftM3 (,,) (go x) (go y) (go z) return (i, (i, frz c) : cNodes ++ tNodes ++ eNodes ,(cNode, i, frz c) : (tNode, i, frz c) : (eNode, i, frz c) : cEdges ++ tEdges ++ eEdges) go c@(CEq i) = extract i eqMap >>= tupM2 go >>= addKids c go c@(CLt i) = extract i ltMap >>= tupM2 go >>= addKids c go c@(CNat i) = return (i, [(i, frz c)], []) go c@(CExist i) = return (i, [(i, frz c)], []) addKids ccode ((lNode, lNodes, lEdges), (rNode, rNodes, rEdges)) = let i = circuitHash ccode in return (i, (i, frz ccode) : lNodes ++ rNodes, (lNode, i, frz ccode) : (rNode, i, frz ccode) : lEdges ++ rEdges) tupM2 f (x, y) = liftM2 (,) (f x) (f y) frz ccode = FrozenShared ccode cmaps extract code f = do maps <- ask let lookupError = error $ "shareGraph: unknown code: " ++ show code case Bimap.lookup code (f maps) of Nothing -> lookupError Just x -> return x shareGraph' :: (G.DynGraph gr, Ord v, Hashable v, Show v, Pretty id, Ord id) => FrozenShared id tvar v -> gr String String shareGraph' (FrozenShared output cmaps) = (`runReader` cmaps) $ do (_, nodes, edges) <- go output return $ Graph.mkGraph (nub nodes) (nub edges) where -- Invariant: The returned node is always a member of the returned list of -- nodes. Returns: (node, node-list, edge-list). go c@(CVar i) = return (i, [(i, frz c)], []) go c@(CTrue i) = return (i, [(i, frz c)], []) go c@(CFalse i) = return (i, [(i, frz c)], []) go c@(CNot i) = do (child, nodes, edges) <- extract i notMap >>= go return (i, (i, frz c) : nodes, (child, i, frz c) : edges) go c@(CAnd i) = extract i andMap >>= tupM2 go >>= addKids c go c@(COr i) = extract i orMap >>= tupM2 go >>= addKids c go c@(CXor i) = extract i xorMap >>= tupM2 go >>= addKids c go c@(COnlyif i) = extract i onlyifMap >>= tupM2 go >>= addKids c go c@(CIff i) = extract i iffMap >>= tupM2 go >>= addKids c go c@(CIte i) = do (x, y, z) <- extract i iteMap ( (cNode, cNodes, cEdges) ,(tNode, tNodes, tEdges) ,(eNode, eNodes, eEdges)) <- liftM3 (,,) (go x) (go y) (go z) return (i, (i, frz c) : cNodes ++ tNodes ++ eNodes ,(cNode, i, "if") : (tNode, i, "then") : (eNode, i, "else") : cEdges ++ tEdges ++ eEdges) go c@(CEq i) = extract i eqMap >>= tupM2 go >>= addKids c go c@(CLt i) = extract i ltMap >>= tupM2 go >>= addKids c go c@(CNat i) = return (i, [(i, frz c)], []) go c@(CExist i) = return (i, [(i, frz c)], []) go c@(COne i) = extract i oneMap >>= mapM go >>= addKidsOne i addKids ccode ((lNode, lNodes, lEdges), (rNode, rNodes, rEdges)) = let i = circuitHash ccode in return (i, (i, frz ccode) : lNodes ++ rNodes, (lNode, i, "l") : (rNode, i, "r") : lEdges ++ rEdges) addKidsOne me tt = do let (tips, nodes, edges) = unzip3 tt let nodes' = (me, "ONE") : concat nodes edges' = [(n, me, "") | n <- tips ] ++ concat edges return (me, nodes', edges') tupM2 f (x, y) = liftM2 (,) (f x) (f y) -- frz (CVar i) = "v" ++ show i frz (CVar i) = show $ fromJust $ Bimap.lookup i (varMap cmaps) frz CFalse{} = "false" frz CTrue{} = "true" frz CNot{} = "not" frz CAnd{} = "/\\" frz COr{} = "\\/" frz CIff{} = "<->" frz COnlyif{} = "->" frz CXor{} = "xor" frz CIte{} = "if-then-else" frz (CNat c) = "n" ++ show c frz CEq{} = "==" frz CLt{} = "<" frz COne{} = "ONE" frz (CExist i) = "v" ++ show i ++ "?" extract code f = do maps <- ask let lookupError = error $ "shareGraph: unknown code: " ++ show code case Bimap.lookup code (f maps) of Nothing -> lookupError Just x -> return x removeExist :: (Hashable id, Ord id, Ord v, Hashable v, Show v, ECircuit c, NatCircuit c, OneCircuit c) => FrozenShared id tvar v -> c v removeExist (FrozenShared code maps) = go code where -- dumb (for playing): remove existentials by replacing them with their assigned value (if any) existAssigs = Map.fromList $ [ (f, val)| (f@CExist{}, val) <- Bimap.elems(iffMap maps)] ++ [ (f, val)| (val, f@CExist{}) <- Bimap.elems(iffMap maps)] go (CTrue{}) = true go (CFalse{}) = false go c@(CVar{}) = input $ getChildren' c (varMap maps) go c@CExist{} = go $ Map.findWithDefault (error "removeExist: CExist") c existAssigs go c@(COr{}) = uncurry or (go `onTup` getChildren c (orMap maps)) go c@(CAnd{}) = uncurry and (go `onTup` getChildren c (andMap maps)) go c@(CNot{}) = not . go $ getChildren c (notMap maps) go c@(COne{}) = one . map go $ getChildren c (oneMap maps) go c@(CXor{}) = uncurry xor (go `onTup` getChildren c (xorMap maps)) go c@(COnlyif{}) = uncurry onlyif (go `onTup` getChildren c (onlyifMap maps)) go c@(CIff{}) = uncurry iff (go `onTup` getChildren c (iffMap maps)) go c@(CIte{}) = let (cc, tc, ec) = getChildren c (iteMap maps) [cond, t, e] = map go [cc, tc, ec] in ite cond t e go c@CNat{} = nat $ getChildren' c (natMap maps) go c@CEq{} = uncurry eq (go `onTup` getChildren c (eqMap maps)) go c@CLt{} = uncurry lt (go `onTup` getChildren c (ltMap maps)) onTup f (x, y) = (f x, f y) -- | Returns an equivalent circuit with no iff, xor, onlyif, ite, nat, eq and lt nodes. removeComplex :: (Hashable id, Ord id, Ord tvar, Hashable tvar, Ord v, Hashable v, Show v, Circuit c) => [v] -> FrozenShared id tvar v -> (c v, v :->: [v]) removeComplex freshVars c = assert disjoint $ (go code, bitnats) where -- casting removes the one constraints FrozenShared code maps = runShared (castCircuit c) `asTypeOf` c -- encoding nats as binary numbers bitwidth = fst . head . dropWhile ( (< Bimap.size (natMap maps)) . snd) . zip [1..] . iterate (*2) $ 2 bitnats = HashMap.fromList (Bimap.elems (natMap maps) `zip` chunks bitwidth freshVars) disjoint = all (`notElem` Bimap.elems (varMap maps)) (concat $ HashMap.elems bitnats) lookupBits c = fromJust $ HashMap.lookup (getChildren' c (natMap maps)) bitnats -- dumb (for playing): remove existentials by replacing them with their assigned value (if any) existAssigs = Map.fromList $ [ (f, val)| (f@CExist{}, val) <- Bimap.elems(iffMap maps)] ++ [ (f, val)| (val, f@CExist{}) <- Bimap.elems(iffMap maps)] go (CTrue{}) = true go (CFalse{}) = false go c@(CVar{}) = input $ getChildren' c (varMap maps) go c@CExist{} = go $ Map.findWithDefault (error "removeComplex: CExist") c existAssigs go c@(COr{}) = uncurry or (go `onTup` getChildren c (orMap maps)) go c@(CAnd{}) = uncurry and (go `onTup` getChildren c (andMap maps)) go c@(CNot{}) = not . go $ getChildren c (notMap maps) go c@(CXor{}) = let (l, r) = go `onTup` getChildren c (xorMap maps) in (l `or` r) `and` not (l `and` r) go c@(COnlyif{}) = let (p, q) = go `onTup` getChildren c (onlyifMap maps) in not p `or` q go c@(CIff{}) = let (p, q) = go `onTup` getChildren c (iffMap maps) in iff p q go c@(CIte{}) = let (cc, tc, ec) = getChildren c (iteMap maps) [cond, t, e] = map go [cc, tc, ec] in ite cond t e go CNat{} = typeError "removeComplex: expected a boolean." go c@CEq{} | (a@CNat{}, b@CNat{}) <- getChildren c (eqMap maps) , na <- lookupBits a , nb <- lookupBits b = eq na nb | otherwise = typeError "removeComplex: expected a boolean." go c@(CLt{}) | (a@CNat{}, b@CNat{}) <- getChildren c (ltMap maps) , na <- lookupBits a , nb <- lookupBits b = lt na nb | otherwise = typeError "removeComplex: expected a boolean." -- fresh = do { v:vv <- get; put vv; return (input v)} iff p q = (not p `or` q) `and` (not q `or` p) ite cond t e = (cond `and` t) `or` (not cond `and` e) eq (p:pp) (q:qq) = ( (not (input p) `and` not (input q)) `or` (input p `and` input q) ) `and` eq pp qq eq [] [] = true eq [] qq = not $ orL $ map input qq eq pp [] = not $ orL $ map input pp lt (p:pp) (q:qq) = lt pp qq `or` (not (input p) `and` input q `and` eq pp qq) lt [] [] = false lt [] qq = orL $ map input qq lt _ [] = false onTup f (x, y) = (f x, f y) -- ----------------------- -- ** Convert circuit to CNF -- ----------------------- -- this data is private to toCNF. data CNFResult = CP !Lit [Set Lit] data CNFState = CNFS{ toCnfVars :: !([Var]) -- ^ infinite fresh var source, starting at 1 , toCnfMap :: !(Var :<->: CCode) -- ^ record var mapping , toBitMap :: !(CCode :->: [Var]) -- , toBitMap :: !(Var :<->: (CCode,Int)) , numCnfClauses :: !Int } emptyCNFState :: CNFState emptyCNFState = CNFS{ toCnfVars = [V 1 ..] , numCnfClauses = 0 , toCnfMap = Bimap.empty , toBitMap = mempty} -- retrieve and create (if necessary) a cnf variable for the given ccode. --findVar :: (MonadState CNFState m) => CCode -> m Lit findVar ccode = do m <- gets toCnfMap v:vs <- gets toCnfVars case Bimap.lookupR ccode m of Nothing -> do modify $ \s -> s{ toCnfMap = Bimap.insert v ccode m , toCnfVars = vs } return . lit $ v Just v' -> return . lit $ v' findVar' ccode kfound knot = do m <- gets toCnfMap v:vs <- gets toCnfVars case Bimap.lookupR ccode m of Nothing -> do modify $ \s -> s{ toCnfMap = Bimap.insert v ccode m , toCnfVars = vs } knot $ lit v Just v' -> kfound $ lit v' recordVar ccode comp = do m <- gets toCnfMap case Bimap.lookupR ccode m of Nothing -> do l <- comp modify $ \s -> s{ toCnfMap = Bimap.insert (var l) ccode (toCnfMap s) } return l Just v -> return (lit v) -- | A circuit problem packages up the CNF corresponding to a given -- `FrozenShared' circuit, and the mapping between the variables in the CNF and -- the circuit elements of the circuit. data RPOCircuitProblem id tvar v = RPOCircuitProblem { rpoProblemCnf :: CNF , rpoProblemCircuit :: !(FrozenShared id tvar v) , rpoProblemCodeMap :: !(Var :<->: CCode) , rpoProblemBitMap :: !(Var :->: (CCode,Int)) } -- Optimal CNF conversion toCNF' :: (Hashable id, Ord id, Hashable tvar, Ord tvar, Ord v, Hashable v, Show v) => [v] -> FrozenShared id tvar v -> (ECircuitProblem v, v :->: [v]) toCNF' freshv = first(ECircuit.toCNF . ECircuit.runShared) . removeComplex freshv -- Fast CNF conversion toCNF :: (Hashable id, Ord id, Ord v, Hashable v, Show v, Hashable tvar, Show tvar, Show id) => FrozenShared id tvar v -> RPOCircuitProblem id tvar v toCNF c@(FrozenShared !sharedCircuit !circuitMaps) = let (m,cnf) = (\x -> execRWS x circuitMaps emptyCNFState) $ do l <- toCNF' sharedCircuit writeClauses [[l]] bitMap = HashMap.fromList [ (v, (c,i)) | (c,vv) <- HashMap.toList (toBitMap m), (v,i) <- zip vv [0..]] in RPOCircuitProblem { rpoProblemCnf = CNF { numVars = pred $ unVar $ head (toCnfVars m) , numClauses = numCnfClauses m , clauses = cnf } , rpoProblemCircuit = c , rpoProblemCodeMap = toCnfMap m , rpoProblemBitMap = bitMap} where debug msg = hPutStrLn stderr ("toCNFRpo - " ++ msg) >> hFlush stderr writeClauses cc = incC (length cc) >> tell cc bitWidth = fst . head . dropWhile ( (< Bimap.size (natMap circuitMaps)) . snd ) . zip [1..] . iterate (*2) $ 2 -- Returns l where {l} U the accumulated c is CNF equisatisfiable with the input -- circuit. Note that CNF conversion only has cases for And, Or, Not, True, -- False, and Var circuits. We therefore remove the complex circuit before -- passing stuff to this function. toCNF' c@(CVar{}) = findVar' c goOn goOn toCNF' c@CExist{} = findVar' c goOn goOn toCNF' c@(CTrue{}) = true toCNF' c@(CFalse{}) = false -- -- x <-> -y -- -- <-> (-x, -y) & (y, x) toCNF' c@(CNot i) = findVar' c goOn $ \notLit -> do eTree <- extract i notMap eLit <- toCNF' eTree writeClauses [ [negate notLit, negate eLit] , [eLit, notLit] ] return notLit -- -- x <-> (y | z) -- -- <-> (-y, x) & (-z, x) & (-x, y, z) toCNF' c@(COr i) = findVar' c goOn $ \orLit -> do (l, r) <- extract i orMap lLit <- toCNF' l rLit <- toCNF' r writeClauses [ [negate lLit, orLit] , [negate rLit, orLit] , [negate orLit, lLit, rLit]] return orLit -- -- x <-> (y & z) -- -- <-> (-x, y), (-x, z) & (-y, -z, x) toCNF' c@(CAnd i) = findVar' c goOn $ \andLit -> do (l, r) <- extract i andMap lLit <- toCNF' l rLit <- toCNF' r writeClauses [ [negate andLit, lLit] , [negate andLit, rLit] , [negate lLit, negate rLit, andLit]] return andLit toCNF' c@(CXor i) = recordVar c $ do (l,r) <- extract i xorMap lLit <- toCNF' l rLit <- toCNF' r (lLit `or` rLit) `andM` notM (lLit `and` rLit) toCNF' c@(COnlyif i) = recordVar c $ do (l,r) <- extract i onlyifMap lLit <- toCNF' l rLit <- toCNF' r (negate lLit `or` rLit) toCNF' c@(CIff i) = recordVar c $ do (l,r) <- extract i iffMap lLit <- toCNF' l rLit <- toCNF' r iff lLit rLit toCNF' c@(CIte i) = recordVar c $ do (c,t,e) <- extract i iteMap cLit <- toCNF' c tLit <- toCNF' t eLit <- toCNF' e ite cLit tLit eLit toCNF' c@(CEq i) = recordVar c $ do (nl,nr) <- extract i eqMap ll <- findNat nl rr <- findNat nr eq ll rr toCNF' c@(CLt i) = recordVar c $ do (nl,nr) <- extract i ltMap ll <- findNat nl rr <- findNat nr lt ll rr toCNF' c@(COne i) = recordVar c $ do cc <- extract i oneMap case cc of [] -> false _ -> do vv <- mapM toCNF' cc ones <- replicateM (length vv) fresh zeros <- replicateM (length vv) fresh f <- false t <- true writeClauses =<< mapM sequence [ [( return one_i `iffM` ite b_i zero_i1 one_i1) `andM` ( return zero_i `iffM` (negate b_i `and` zero_i1))] | (b_i, one_i, zero_i, one_i1, zero_i1) <- zip5 vv ones zeros (tail ones ++ [f]) (tail zeros ++ [t]) ] return (head ones) where zip5 (a:aa) (b:bb) (c:cc) (d:dd) (e:ee) = (a,b,c,d,e) : zip5 aa bb cc dd ee zip5 _ _ _ _ _ = [] toCNF' c = do m <- ask error $ "toCNF' bug: unknown code: " ++ show c ++ " with maps:\n" ++ show (m{hashCount=[]}) true = findVar' (CTrue trueHash) goOn $ \l -> do writeClauses [[l]] return l false = findVar' (CFalse falseHash) goOn $ \l -> do writeClauses [ [negate l]] return l orM l r = do { vl <- l; vr <- r; or vl vr} -- or lLit rLit | trace ("or " ++ show lLit ++ " " ++ show rLit) False = undefined or lLit rLit = do me <- fresh writeClauses [ [negate lLit, me] , [negate rLit, me] , [negate me, lLit, rLit]] return me andM l r = do { vl <- l; vr <- r; and vl vr} -- and lLit rLit | trace ("and " ++ show lLit ++ " " ++ show rLit) False = undefined and lLit rLit = do me <- fresh writeClauses [ [negate me, lLit] , [negate me, rLit] , [negate lLit, negate rLit,me]] return me notM = liftM negate -- iff lLit rLit | trace ("iff " ++ show lLit ++ " " ++ show rLit) False = undefined iffM ml mr = do {l <- ml; r <- mr; iff l r} iff lLit rLit = (negate lLit `or` rLit) `andM` (negate rLit `or` lLit) ite cLit tLit eLit = (cLit `and` tLit) `orM` (negate cLit `and` eLit) eq [] [] = true eq [] rr = notM $ foldr orM false (map return rr) eq ll [] = notM $ foldr orM false (map return ll) eq (l:ll) (r:rr) = iff l r `andM` eq ll rr lt [] [] = false lt _ [] = false lt [] rr = foldr orM false $ map return rr lt (l:ll) (r:rr) = lt ll rr `orM` ((negate l `and` r) `andM` eq ll rr) incC i = modify $ \m -> m{numCnfClauses = numCnfClauses m + i} extract code f = do m <- asks f case Bimap.lookup code m of Nothing -> error $ "toCNFRpo: unknown code: " ++ show code Just x -> return x findNat c@CNat{} = do bm <- gets toBitMap case HashMap.lookup c bm of Nothing -> do bits <- replicateM bitWidth fresh modify $ \s -> s{ toBitMap = HashMap.insert c (map var bits) bm } return bits Just vv -> return (map lit vv) goOn c = return c fresh = do v:vs <- gets toCnfVars modify $ \s -> s{toCnfVars=vs} return (lit v) projectRPOCircuitSolution sol prbl = case sol of Sat lits -> projectLits lits Unsat lits -> projectLits lits where RPOCircuitProblem _ (FrozenShared _ maps) codeMap bitsMap = prbl projectLits lits = Map.map Right vm `mappend` Map.map (Left . fromBinary . map snd . sortBy (compare `on` fst)) bm where (vm, bm) = foldl (\m l -> case litHash l of Var h -> insertVar h l m Bit h_i -> insertNat h_i l m Auxiliar-> m) (initiallyAllFalseMap, initiallyAllZeroMap) (litAssignment lits) initiallyAllFalseMap = Map.fromList [(v,False) | v <- Bimap.elems (varMap maps)] initiallyAllZeroMap = Map.empty -- 8fromList [(v,0) | v <- Bimap.elems (natMap maps)] insertVar h l (mb,mn) = (mb',mn) where mb' = case Bimap.lookup h (varMap maps) of Nothing -> mb Just v -> Map.insert v (litSign l) mb insertNat (h,i) l (mb,mn) = (mb,mn') where mn' = case Bimap.lookup h (natMap maps) of Nothing -> mn Just n -> Map.insertWith (++) n [(i, litSign l)] mn litHash l = case Bimap.lookup (var l) codeMap of Nothing -> case HashMap.lookup (var l) bitsMap of Just (code,bit) -> Bit (circuitHash code, bit) Nothing -> Auxiliar Just code -> Var (circuitHash code) safeAt l i = CE.assert (i < length l) (l !! i) data ProjectionCase = Var CircuitHash | Bit (CircuitHash, Int) | Auxiliar -- ------------------------ -- Hashable instances -- ------------------------ {- instance Hashable Var where newtype Var :->: x = VarTrie (Int :->: x) empty = VarTrie HashMap.empty lookup (V i) (VarTrie t) = HashMap.lookup i t insert (V i) v (VarTrie t) = VarTrie (HashMap.insert i v t) toList (VarTrie t) = map (first V) (HashMap.toList t) -} instance Hashable Var where hash (V i) = i -- ------- -- Errors -- ------- typeError :: String -> a typeError msg = error (msg ++ "\nPlease send an email to the [email protected] requesting a typed circuit language.")
pepeiborra/narradar
src/Narradar/Constraints/SAT/RPOCircuit.hs
bsd-3-clause
66,319
16
24
21,545
26,723
13,795
12,928
1,460
49
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE StandaloneDeriving #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Types -- Copyright : (c) David Himmelstrup 2005 -- Duncan Coutts 2011 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Various common data types for the entire cabal-install system ----------------------------------------------------------------------------- module Distribution.Client.Types where import Distribution.Package ( PackageName, PackageId, Package(..), ComponentId(..) , ComponentId(..) , HasComponentId(..), PackageInstalled(..) ) import Distribution.InstalledPackageInfo ( InstalledPackageInfo ) import Distribution.PackageDescription ( Benchmark(..), GenericPackageDescription(..), FlagAssignment , TestSuite(..) ) import Distribution.PackageDescription.Configuration ( mapTreeData ) import Distribution.Client.PackageIndex ( PackageIndex ) import Distribution.Client.ComponentDeps ( ComponentDeps ) import qualified Distribution.Client.ComponentDeps as CD import Distribution.Version ( VersionRange ) import Distribution.Text (display) import Data.Map (Map) import Network.URI (URI, nullURI) import Data.ByteString.Lazy (ByteString) import Control.Exception ( SomeException ) newtype Username = Username { unUsername :: String } newtype Password = Password { unPassword :: String } -- | This is the information we get from a @00-index.tar.gz@ hackage index. -- data SourcePackageDb = SourcePackageDb { packageIndex :: PackageIndex SourcePackage, packagePreferences :: Map PackageName VersionRange } -- ------------------------------------------------------------ -- * Various kinds of information about packages -- ------------------------------------------------------------ -- | Subclass of packages that have specific versioned dependencies. -- -- So for example a not-yet-configured package has dependencies on version -- ranges, not specific versions. A configured or an already installed package -- depends on exact versions. Some operations or data structures (like -- dependency graphs) only make sense on this subclass of package types. -- class Package pkg => PackageFixedDeps pkg where depends :: pkg -> ComponentDeps [ComponentId] instance PackageFixedDeps InstalledPackageInfo where depends = CD.fromInstalled . installedDepends -- | In order to reuse the implementation of PackageIndex which relies on -- 'ComponentId', we need to be able to synthesize these IDs prior -- to installation. Eventually, we'll move to a representation of -- 'ComponentId' which can be properly computed before compilation -- (of course, it's a bit of a misnomer since the packages are not actually -- installed yet.) In any case, we'll synthesize temporary installed package -- IDs to use as keys during install planning. These should never be written -- out! Additionally, they need to be guaranteed unique within the install -- plan. fakeComponentId :: PackageId -> ComponentId fakeComponentId = ComponentId . (".fake."++) . display -- | A 'ConfiguredPackage' is a not-yet-installed package along with the -- total configuration information. The configuration information is total in -- the sense that it provides all the configuration information and so the -- final configure process will be independent of the environment. -- data ConfiguredPackage = ConfiguredPackage SourcePackage -- package info, including repo FlagAssignment -- complete flag assignment for the package [OptionalStanza] -- list of enabled optional stanzas for the package (ComponentDeps [ConfiguredId]) -- set of exact dependencies (installed or source). -- These must be consistent with the 'buildDepends' -- in the 'PackageDescription' that you'd get by -- applying the flag assignment and optional stanzas. deriving Show -- | A ConfiguredId is a package ID for a configured package. -- -- Once we configure a source package we know it's ComponentId -- (at least, in principle, even if we have to fake it currently). It is still -- however useful in lots of places to also know the source ID for the package. -- We therefore bundle the two. -- -- An already installed package of course is also "configured" (all it's -- configuration parameters and dependencies have been specified). -- -- TODO: I wonder if it would make sense to promote this datatype to Cabal -- and use it consistently instead of ComponentIds? data ConfiguredId = ConfiguredId { confSrcId :: PackageId , confInstId :: ComponentId } instance Show ConfiguredId where show = show . confSrcId instance Package ConfiguredPackage where packageId (ConfiguredPackage pkg _ _ _) = packageId pkg instance PackageFixedDeps ConfiguredPackage where depends (ConfiguredPackage _ _ _ deps) = fmap (map confInstId) deps instance HasComponentId ConfiguredPackage where installedComponentId = fakeComponentId . packageId -- | Like 'ConfiguredPackage', but with all dependencies guaranteed to be -- installed already, hence itself ready to be installed. data GenericReadyPackage srcpkg ipkg = ReadyPackage srcpkg -- see 'ConfiguredPackage'. (ComponentDeps [ipkg]) -- Installed dependencies. deriving (Eq, Show) type ReadyPackage = GenericReadyPackage ConfiguredPackage InstalledPackageInfo instance Package srcpkg => Package (GenericReadyPackage srcpkg ipkg) where packageId (ReadyPackage srcpkg _deps) = packageId srcpkg instance (Package srcpkg, HasComponentId ipkg) => PackageFixedDeps (GenericReadyPackage srcpkg ipkg) where depends (ReadyPackage _ deps) = fmap (map installedComponentId) deps instance HasComponentId srcpkg => HasComponentId (GenericReadyPackage srcpkg ipkg) where installedComponentId (ReadyPackage pkg _) = installedComponentId pkg -- | A package description along with the location of the package sources. -- data SourcePackage = SourcePackage { packageInfoId :: PackageId, packageDescription :: GenericPackageDescription, packageSource :: PackageLocation (Maybe FilePath), packageDescrOverride :: PackageDescriptionOverride } deriving Show -- | We sometimes need to override the .cabal file in the tarball with -- the newer one from the package index. type PackageDescriptionOverride = Maybe ByteString instance Package SourcePackage where packageId = packageInfoId data OptionalStanza = TestStanzas | BenchStanzas deriving (Eq, Ord, Show) enableStanzas :: [OptionalStanza] -> GenericPackageDescription -> GenericPackageDescription enableStanzas stanzas gpkg = gpkg { condBenchmarks = flagBenchmarks $ condBenchmarks gpkg , condTestSuites = flagTests $ condTestSuites gpkg } where enableTest t = t { testEnabled = TestStanzas `elem` stanzas } enableBenchmark bm = bm { benchmarkEnabled = BenchStanzas `elem` stanzas } flagBenchmarks = map (\(n, bm) -> (n, mapTreeData enableBenchmark bm)) flagTests = map (\(n, t) -> (n, mapTreeData enableTest t)) -- ------------------------------------------------------------ -- * Package locations and repositories -- ------------------------------------------------------------ data PackageLocation local = -- | An unpacked package in the given dir, or current dir LocalUnpackedPackage FilePath -- | A package as a tarball that's available as a local tarball | LocalTarballPackage FilePath -- | A package as a tarball from a remote URI | RemoteTarballPackage URI local -- | A package available as a tarball from a repository. -- -- It may be from a local repository or from a remote repository, with a -- locally cached copy. ie a package available from hackage | RepoTarballPackage Repo PackageId local --TODO: -- * add support for darcs and other SCM style remote repos with a local cache -- | ScmPackage deriving (Show, Functor) data RemoteRepo = RemoteRepo { remoteRepoName :: String, remoteRepoURI :: URI, -- | Enable secure access to Hackage? remoteRepoSecure :: Bool, -- | Root key IDs (for bootstrapping) remoteRepoRootKeys :: [String], -- | Threshold for verification during bootstrapping remoteRepoKeyThreshold :: Int, -- | Normally a repo just specifies an HTTP or HTTPS URI, but as a -- special case we may know a repo supports both and want to try HTTPS -- if we can, but still allow falling back to HTTP. -- -- This field is not currently stored in the config file, but is filled -- in automagically for known repos. remoteRepoShouldTryHttps :: Bool } deriving (Show,Eq,Ord) -- | Construct a partial 'RemoteRepo' value to fold the field parser list over. emptyRemoteRepo :: String -> RemoteRepo emptyRemoteRepo name = RemoteRepo name nullURI False [] 0 False data Repo = -- | Local repositories RepoLocal { repoLocalDir :: FilePath } -- | Standard (unsecured) remote repositores | RepoRemote { repoRemote :: RemoteRepo , repoLocalDir :: FilePath } deriving instance Show Repo -- | Check if this is a remote repo maybeRepoRemote :: Repo -> Maybe RemoteRepo maybeRepoRemote (RepoLocal _localDir ) = Nothing maybeRepoRemote (RepoRemote r _localDir ) = Just r -- ------------------------------------------------------------ -- * Build results -- ------------------------------------------------------------ type BuildResult = Either BuildFailure BuildSuccess data BuildFailure = PlanningFailed | DependentFailed PackageId | DownloadFailed SomeException | UnpackFailed SomeException | ConfigureFailed SomeException | BuildFailed SomeException | TestsFailed SomeException | InstallFailed SomeException data BuildSuccess = BuildOk DocsResult TestsResult (Maybe InstalledPackageInfo) data DocsResult = DocsNotTried | DocsFailed | DocsOk data TestsResult = TestsNotTried | TestsOk
randen/cabal
cabal-install/Distribution/Client/Types.hs
bsd-3-clause
10,462
0
11
2,200
1,346
806
540
132
1
module Main (main) where import Distribution.Simple (defaultMain) main = defaultMain
bmillwood/notcpp
Setup.hs
bsd-3-clause
85
0
5
10
24
15
9
3
1
{-# LANGUAGE OverloadedStrings #-} module Point where import Control.Applicative ((<|>)) import qualified Data.Attoparsec.ByteString as A import Data.Attoparsec.ByteString.Char8 (decimal) import qualified Data.Attoparsec.Combinator as A import Data.ByteString (ByteString, scanl1) import qualified Data.Map.Strict as Map import Data.Time.Clock import Data.Time.Clock.POSIX import Data.Word import Types import Debug.Trace import Prelude hiding (scanl1) instance Stored Point where parse = A.parseOnly point testPointBS :: ByteString testPointBS = "cpu,region=us-\\ west,host=serverA,env=prod,target=servers,zone=1c value=1" point :: A.Parser Point point = do name <- nameP <* comma keys <- Map.fromList <$> pairsP <* space values <- Map.fromList <$> pairsP time <- timeP <* A.endOfInput return $ Point name keys time values commaWord :: Word8 commaWord = fromIntegral $ fromEnum ',' spaceWord :: Word8 spaceWord = fromIntegral $ fromEnum ' ' equalWord :: Word8 equalWord = fromIntegral $ fromEnum '=' escapeWord :: Word8 escapeWord = fromIntegral $ fromEnum '\\' comma :: A.Parser Word8 comma = A.word8 commaWord space :: A.Parser Word8 space = A.word8 spaceWord equal :: A.Parser Word8 equal = A.word8 equalWord nameP :: A.Parser ByteString nameP = A.takeTill (== commaWord) pairsP :: A.Parser [(ByteString, ByteString)] pairsP = keyValue `A.sepBy` comma keyValue :: A.Parser (ByteString, ByteString) keyValue = (,) <$> (A.takeTill (== equalWord) <* equal) <*> escapedValue timeP :: A.Parser (Maybe UTCTime) timeP = (pure . convertToUTCTime <$> (space *> decimal)) <|> return Nothing convertToUTCTime :: Integer -> UTCTime convertToUTCTime = posixSecondsToUTCTime . fromIntegral escapedValue :: A.Parser ByteString escapedValue = A.scan False fun where fun True 44 = Just False fun True 32 = Just False fun False 44 = Nothing fun False 32 = Nothing fun _ 92 = Just True fun _ _ = Just False
chemist/series-storage
src/Point.hs
bsd-3-clause
2,123
0
10
496
609
332
277
57
6
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Hugs -- Copyright : Isaac Jones 2003-2006 -- Duncan Coutts 2009 -- -- Maintainer : [email protected] -- Portability : portable -- -- This module contains most of the NHC-specific code for configuring, building -- and installing packages. {- Copyright (c) 2003-2005, Isaac Jones All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Distribution.Simple.Hugs ( configure, getInstalledPackages, buildLib, buildExe, install, registerPackage, ) where import Distribution.Package ( PackageName, PackageIdentifier(..), InstalledPackageId(..) , packageName ) import Distribution.InstalledPackageInfo ( InstalledPackageInfo, emptyInstalledPackageInfo , InstalledPackageInfo_( InstalledPackageInfo, installedPackageId , sourcePackageId ) , parseInstalledPackageInfo, showInstalledPackageInfo ) import Distribution.PackageDescription ( PackageDescription(..), BuildInfo(..), hcOptions, allExtensions , Executable(..), withExe, Library(..), withLib, libModules ) import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as ModuleName import Distribution.Simple.Compiler ( CompilerFlavor(..), CompilerId(..) , Compiler(..), Flag, languageToFlags, extensionsToFlags , PackageDB(..), PackageDBStack ) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.PackageIndex (PackageIndex) import Distribution.Simple.Program ( Program(programFindVersion) , ProgramConfiguration, userMaybeSpecifyPath , requireProgram, requireProgramVersion , rawSystemProgramConf, programPath , ffihugsProgram, hugsProgram ) import Distribution.Version ( Version(..), orLaterVersion ) import Distribution.Simple.PreProcess ( ppCpp, runSimplePreProcessor ) import Distribution.Simple.PreProcess.Unlit ( unlit ) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), ComponentLocalBuildInfo(..) , InstallDirs(..), absoluteInstallDirs ) import Distribution.Simple.BuildPaths ( autogenModuleName, autogenModulesDir, dllExtension ) import Distribution.Simple.Setup ( CopyDest(..) ) import Distribution.Simple.Utils ( createDirectoryIfMissingVerbose , installOrdinaryFiles, setFileExecutable , withUTF8FileContents, writeFileAtomic, writeUTF8File , copyFileVerbose, findFile, findFileWithExtension, findModuleFiles , rawSystemStdInOut , die, info, notice ) import Language.Haskell.Extension ( Language(Haskell98), Extension(..), KnownExtension(..) ) import System.FilePath ( (</>), takeExtension, (<.>), searchPathSeparator, normalise, takeDirectory ) import Distribution.System ( OS(..), buildOS ) import Distribution.Text ( display, simpleParse ) import Distribution.ParseUtils ( ParseResult(..) ) import Distribution.Verbosity import Data.Char ( isSpace ) import Data.Maybe ( mapMaybe, catMaybes ) import Data.Monoid ( Monoid(..) ) import Control.Monad ( unless, when, filterM ) import Data.List ( nub, sort, isSuffixOf ) import System.Directory ( doesFileExist, doesDirectoryExist, getDirectoryContents , removeDirectoryRecursive, getHomeDirectory ) import System.Exit ( ExitCode(ExitSuccess) ) import Distribution.Compat.Exception -- ----------------------------------------------------------------------------- -- Configuring configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramConfiguration -> IO (Compiler, ProgramConfiguration) configure verbosity hcPath _hcPkgPath conf = do (_ffihugsProg, conf') <- requireProgram verbosity ffihugsProgram (userMaybeSpecifyPath "ffihugs" hcPath conf) (_hugsProg, version, conf'') <- requireProgramVersion verbosity hugsProgram' (orLaterVersion (Version [2006] [])) conf' let comp = Compiler { compilerId = CompilerId Hugs version, compilerLanguages = hugsLanguages, compilerExtensions = hugsLanguageExtensions } return (comp, conf'') where hugsProgram' = hugsProgram { programFindVersion = getVersion } getVersion :: Verbosity -> FilePath -> IO (Maybe Version) getVersion verbosity hugsPath = do (output, _err, exit) <- rawSystemStdInOut verbosity hugsPath [] (Just (":quit", False)) False if exit == ExitSuccess then return $! findVersion output else return Nothing where findVersion output = do (monthStr, yearStr) <- selectWords output year <- convertYear yearStr month <- convertMonth monthStr return (Version [year, month] []) selectWords output = case [ (month, year) | [_,_,"Version:", month, year,_] <- map words (lines output) ] of [(month, year)] -> Just (month, year) _ -> Nothing convertYear year = case reads year of [(y, [])] | y >= 1999 && y < 2020 -> Just y _ -> Nothing convertMonth month = lookup month (zip months [1..]) months = [ "January", "February", "March", "April", "May", "June", "July" , "August", "September", "October", "November", "December" ] hugsLanguages :: [(Language, Flag)] hugsLanguages = [(Haskell98, "")] --default is 98 mode -- | The flags for the supported extensions hugsLanguageExtensions :: [(Extension, Flag)] hugsLanguageExtensions = let doFlag (f, (enable, disable)) = [(EnableExtension f, enable), (DisableExtension f, disable)] alwaysOn = ("", ""{- wrong -}) ext98 = ("-98", ""{- wrong -}) in concatMap doFlag [(OverlappingInstances , ("+o", "-o")) ,(IncoherentInstances , ("+oO", "-O")) ,(HereDocuments , ("+H", "-H")) ,(TypeSynonymInstances , ext98) ,(RecursiveDo , ext98) ,(ParallelListComp , ext98) ,(MultiParamTypeClasses , ext98) ,(FunctionalDependencies , ext98) ,(Rank2Types , ext98) ,(PolymorphicComponents , ext98) ,(ExistentialQuantification , ext98) ,(ScopedTypeVariables , ext98) ,(ImplicitParams , ext98) ,(ExtensibleRecords , ext98) ,(RestrictedTypeSynonyms , ext98) ,(FlexibleContexts , ext98) ,(FlexibleInstances , ext98) ,(ForeignFunctionInterface , alwaysOn) ,(EmptyDataDecls , alwaysOn) ,(CPP , alwaysOn) ] getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration -> IO PackageIndex getInstalledPackages verbosity packagedbs conf = do homedir <- getHomeDirectory (hugsProg, _) <- requireProgram verbosity hugsProgram conf let hugsbindir = takeDirectory (programPath hugsProg) hugslibdir = takeDirectory hugsbindir </> "lib" </> "hugs" dbdirs = nub (concatMap (packageDbPaths homedir hugslibdir) packagedbs) indexes <- mapM getIndividualDBPackages dbdirs return $! mconcat indexes where getIndividualDBPackages :: FilePath -> IO PackageIndex getIndividualDBPackages dbdir = do pkgdirs <- getPackageDbDirs dbdir pkgs <- sequence [ getInstalledPackage pkgname pkgdir | (pkgname, pkgdir) <- pkgdirs ] let pkgs' = map setInstalledPackageId (catMaybes pkgs) return (PackageIndex.fromList pkgs') packageDbPaths :: FilePath -> FilePath -> PackageDB -> [FilePath] packageDbPaths home hugslibdir db = case db of GlobalPackageDB -> [ hugslibdir </> "packages" , "/usr/local/lib/hugs/packages" ] UserPackageDB -> [ home </> "lib/hugs/packages" ] SpecificPackageDB path -> [ path ] getPackageDbDirs :: FilePath -> IO [(PackageName, FilePath)] getPackageDbDirs dbdir = do dbexists <- doesDirectoryExist dbdir if not dbexists then return [] else do entries <- getDirectoryContents dbdir pkgdirs <- sequence [ do pkgdirExists <- doesDirectoryExist pkgdir return (pkgname, pkgdir, pkgdirExists) | (entry, Just pkgname) <- [ (entry, simpleParse entry) | entry <- entries ] , let pkgdir = dbdir </> entry ] return [ (pkgname, pkgdir) | (pkgname, pkgdir, True) <- pkgdirs ] getInstalledPackage :: PackageName -> FilePath -> IO (Maybe InstalledPackageInfo) getInstalledPackage pkgname pkgdir = do let pkgconfFile = pkgdir </> "package.conf" pkgconfExists <- doesFileExist pkgconfFile let pathsModule = pkgdir </> ("Paths_" ++ display pkgname) <.> "hs" pathsModuleExists <- doesFileExist pathsModule case () of _ | pkgconfExists -> getFullInstalledPackageInfo pkgname pkgconfFile | pathsModuleExists -> getPhonyInstalledPackageInfo pkgname pathsModule | otherwise -> return Nothing getFullInstalledPackageInfo :: PackageName -> FilePath -> IO (Maybe InstalledPackageInfo) getFullInstalledPackageInfo pkgname pkgconfFile = withUTF8FileContents pkgconfFile $ \contents -> case parseInstalledPackageInfo contents of ParseOk _ pkginfo | packageName pkginfo == pkgname -> return (Just pkginfo) _ -> return Nothing -- | This is a backup option for existing versions of Hugs which do not supply -- proper installed package info files for the bundled libs. Instead we look -- for the Paths_pkgname.hs file and extract the package version from that. -- We don't know any other details for such packages, in particular we pretend -- that they have no dependencies. -- getPhonyInstalledPackageInfo :: PackageName -> FilePath -> IO (Maybe InstalledPackageInfo) getPhonyInstalledPackageInfo pkgname pathsModule = do content <- readFile pathsModule case extractVersion content of Nothing -> return Nothing Just version -> return (Just pkginfo) where pkgid = PackageIdentifier pkgname version pkginfo = emptyInstalledPackageInfo { sourcePackageId = pkgid } where -- search through the Paths_pkgname.hs file, looking for a line like: -- -- > version = Version {versionBranch = [2,0], versionTags = []} -- -- and parse it using 'Read'. Yes we are that evil. -- extractVersion content = case [ version | ("version":"=":rest) <- map words (lines content) , (version, []) <- reads (concat rest) ] of [version] -> Just version _ -> Nothing -- Older installed package info files did not have the installedPackageId -- field, so if it is missing then we fill it as the source package ID. setInstalledPackageId :: InstalledPackageInfo -> InstalledPackageInfo setInstalledPackageId pkginfo@InstalledPackageInfo { installedPackageId = InstalledPackageId "", sourcePackageId = pkgid } = pkginfo { --TODO use a proper named function for the conversion -- from source package id to installed package id installedPackageId = InstalledPackageId (display pkgid) } setInstalledPackageId pkginfo = pkginfo -- ----------------------------------------------------------------------------- -- Building -- |Building a package for Hugs. buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildLib verbosity pkg_descr lbi lib _clbi = do let pref = scratchDir lbi createDirectoryIfMissingVerbose verbosity True pref copyFileVerbose verbosity (autogenModulesDir lbi </> paths_modulename) (pref </> paths_modulename) compileBuildInfo verbosity pref [] (libModules lib) (libBuildInfo lib) lbi where paths_modulename = ModuleName.toFilePath (autogenModuleName pkg_descr) <.> ".hs" --TODO: switch to using autogenModulesDir as a search dir, rather than -- always copying the file over. -- |Building an executable for Hugs. buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildExe verbosity pkg_descr lbi exe@Executable {modulePath=mainPath, buildInfo=bi} _clbi = do let pref = scratchDir lbi createDirectoryIfMissingVerbose verbosity True pref let destDir = pref </> "programs" let exeMods = otherModules bi srcMainFile <- findFile (hsSourceDirs bi) mainPath let exeDir = destDir </> exeName exe let destMainFile = exeDir </> hugsMainFilename exe copyModule verbosity (EnableExtension CPP `elem` allExtensions bi) bi lbi srcMainFile destMainFile let destPathsFile = exeDir </> paths_modulename copyFileVerbose verbosity (autogenModulesDir lbi </> paths_modulename) destPathsFile compileBuildInfo verbosity exeDir (maybe [] (hsSourceDirs . libBuildInfo) (library pkg_descr)) exeMods bi lbi compileFiles verbosity bi lbi exeDir [destMainFile, destPathsFile] where paths_modulename = ModuleName.toFilePath (autogenModuleName pkg_descr) <.> ".hs" compileBuildInfo :: Verbosity -> FilePath -- ^output directory -> [FilePath] -- ^library source dirs, if building exes -> [ModuleName] -- ^Modules -> BuildInfo -> LocalBuildInfo -> IO () --TODO: should not be using mLibSrcDirs at all compileBuildInfo verbosity destDir mLibSrcDirs mods bi lbi = do -- Pass 1: copy or cpp files from build directory to scratch directory let useCpp = EnableExtension CPP `elem` allExtensions bi let srcDir = buildDir lbi srcDirs = nub $ srcDir : hsSourceDirs bi ++ mLibSrcDirs info verbosity $ "Source directories: " ++ show srcDirs flip mapM_ mods $ \ m -> do fs <- findFileWithExtension suffixes srcDirs (ModuleName.toFilePath m) case fs of Nothing -> die ("can't find source for module " ++ display m) Just srcFile -> do let ext = takeExtension srcFile copyModule verbosity useCpp bi lbi srcFile (destDir </> ModuleName.toFilePath m <.> ext) -- Pass 2: compile foreign stubs in scratch directory stubsFileLists <- fmap catMaybes $ sequence [ findFileWithExtension suffixes [destDir] (ModuleName.toFilePath modu) | modu <- mods] compileFiles verbosity bi lbi destDir stubsFileLists suffixes :: [String] suffixes = ["hs", "lhs"] -- Copy or cpp a file from the source directory to the build directory. copyModule :: Verbosity -> Bool -> BuildInfo -> LocalBuildInfo -> FilePath -> FilePath -> IO () copyModule verbosity cppAll bi lbi srcFile destFile = do createDirectoryIfMissingVerbose verbosity True (takeDirectory destFile) (exts, opts, _) <- getOptionsFromSource srcFile let ghcOpts = [ op | (GHC, ops) <- opts, op <- ops ] if cppAll || EnableExtension CPP `elem` exts || "-cpp" `elem` ghcOpts then do runSimplePreProcessor (ppCpp bi lbi) srcFile destFile verbosity return () else copyFileVerbose verbosity srcFile destFile compileFiles :: Verbosity -> BuildInfo -> LocalBuildInfo -> FilePath -> [FilePath] -> IO () compileFiles verbosity bi lbi modDir fileList = do ffiFileList <- filterM testFFI fileList unless (null ffiFileList) $ do notice verbosity "Compiling FFI stubs" mapM_ (compileFFI verbosity bi lbi modDir) ffiFileList -- Only compile FFI stubs for a file if it contains some FFI stuff testFFI :: FilePath -> IO Bool testFFI file = withHaskellFile file $ \inp -> return $! "foreign" `elem` symbols (stripComments False inp) compileFFI :: Verbosity -> BuildInfo -> LocalBuildInfo -> FilePath -> FilePath -> IO () compileFFI verbosity bi lbi modDir file = do (_, opts, file_incs) <- getOptionsFromSource file let ghcOpts = [ op | (GHC, ops) <- opts, op <- ops ] let pkg_incs = ["\"" ++ inc ++ "\"" | inc <- includes bi] let incs = nub (sort (file_incs ++ includeOpts ghcOpts ++ pkg_incs)) let pathFlag = "-P" ++ modDir ++ [searchPathSeparator] let hugsArgs = "-98" : pathFlag : map ("-i" ++) incs cfiles <- getCFiles file let cArgs = ["-I" ++ dir | dir <- includeDirs bi] ++ ccOptions bi ++ cfiles ++ ["-L" ++ dir | dir <- extraLibDirs bi] ++ ldOptions bi ++ ["-l" ++ lib | lib <- extraLibs bi] ++ concat [["-framework", f] | f <- frameworks bi] rawSystemProgramConf verbosity ffihugsProgram (withPrograms lbi) (hugsArgs ++ file : cArgs) includeOpts :: [String] -> [String] includeOpts [] = [] includeOpts ("-#include" : arg : opts) = arg : includeOpts opts includeOpts (_ : opts) = includeOpts opts -- get C file names from CFILES pragmas throughout the source file getCFiles :: FilePath -> IO [String] getCFiles file = withHaskellFile file $ \inp -> let cfiles = [ normalise cfile | "{-#" : "CFILES" : rest <- map words $ lines $ stripComments True inp , last rest == "#-}" , cfile <- init rest] in seq (length cfiles) (return cfiles) -- List of terminal symbols in a source file. symbols :: String -> [String] symbols cs = case lex cs of (sym, cs'):_ | not (null sym) -> sym : symbols cs' _ -> [] -- Get the non-literate source of a Haskell module. withHaskellFile :: FilePath -> (String -> IO a) -> IO a withHaskellFile file action = withUTF8FileContents file $ \text -> if ".lhs" `isSuffixOf` file then either action die (unlit file text) else action text -- ------------------------------------------------------------ -- * options in source files -- ------------------------------------------------------------ -- |Read the initial part of a source file, before any Haskell code, -- and return the contents of any LANGUAGE, OPTIONS and INCLUDE pragmas. getOptionsFromSource :: FilePath -> IO ([Extension], -- LANGUAGE pragma, if any [(CompilerFlavor,[String])], -- OPTIONS_FOO pragmas [String] -- INCLUDE pragmas ) getOptionsFromSource file = withHaskellFile file $ (return $!) . foldr appendOptions ([],[],[]) . map getOptions . takeWhileJust . map getPragma . filter textLine . map (dropWhile isSpace) . lines . stripComments True where textLine [] = False textLine ('#':_) = False textLine _ = True getPragma :: String -> Maybe [String] getPragma line = case words line of ("{-#" : rest) | last rest == "#-}" -> Just (init rest) _ -> Nothing getOptions ("OPTIONS":opts) = ([], [(GHC, opts)], []) getOptions ("OPTIONS_GHC":opts) = ([], [(GHC, opts)], []) getOptions ("OPTIONS_NHC98":opts) = ([], [(NHC, opts)], []) getOptions ("OPTIONS_HUGS":opts) = ([], [(Hugs, opts)], []) getOptions ("LANGUAGE":ws) = (mapMaybe readExtension ws, [], []) where readExtension :: String -> Maybe Extension readExtension w = case reads w of [(ext, "")] -> Just ext [(ext, ",")] -> Just ext _ -> Nothing getOptions ("INCLUDE":ws) = ([], [], ws) getOptions _ = ([], [], []) appendOptions (exts, opts, incs) (exts', opts', incs') = (exts++exts', opts++opts', incs++incs') -- takeWhileJust f = map fromJust . takeWhile isJust takeWhileJust :: [Maybe a] -> [a] takeWhileJust (Just x:xs) = x : takeWhileJust xs takeWhileJust _ = [] -- |Strip comments from Haskell source. stripComments :: Bool -- ^ preserve pragmas? -> String -- ^ input source text -> String stripComments keepPragmas = stripCommentsLevel 0 where stripCommentsLevel :: Int -> String -> String stripCommentsLevel 0 ('"':cs) = '"':copyString cs stripCommentsLevel 0 ('-':'-':cs) = -- FIX: symbols like --> stripCommentsLevel 0 (dropWhile (/= '\n') cs) stripCommentsLevel 0 ('{':'-':'#':cs) | keepPragmas = '{' : '-' : '#' : copyPragma cs stripCommentsLevel n ('{':'-':cs) = stripCommentsLevel (n+1) cs stripCommentsLevel 0 (c:cs) = c : stripCommentsLevel 0 cs stripCommentsLevel n ('-':'}':cs) = stripCommentsLevel (n-1) cs stripCommentsLevel n (_:cs) = stripCommentsLevel n cs stripCommentsLevel _ [] = [] copyString ('\\':c:cs) = '\\' : c : copyString cs copyString ('"':cs) = '"' : stripCommentsLevel 0 cs copyString (c:cs) = c : copyString cs copyString [] = [] copyPragma ('#':'-':'}':cs) = '#' : '-' : '}' : stripCommentsLevel 0 cs copyPragma (c:cs) = c : copyPragma cs copyPragma [] = [] -- ----------------------------------------------------------------------------- -- |Install for Hugs. -- For install, copy-prefix = prefix, but for copy they're different. -- The library goes in \<copy-prefix>\/lib\/hugs\/packages\/\<pkgname> -- (i.e. \<prefix>\/lib\/hugs\/packages\/\<pkgname> on the target system). -- Each executable goes in \<copy-prefix>\/lib\/hugs\/programs\/\<exename> -- (i.e. \<prefix>\/lib\/hugs\/programs\/\<exename> on the target system) -- with a script \<copy-prefix>\/bin\/\<exename> pointing at -- \<prefix>\/lib\/hugs\/programs\/\<exename>. install :: Verbosity -- ^verbosity -> LocalBuildInfo -> FilePath -- ^Library install location -> FilePath -- ^Program install location -> FilePath -- ^Executable install location -> FilePath -- ^Program location on target system -> FilePath -- ^Build location -> (FilePath,FilePath) -- ^Executable (prefix,suffix) -> PackageDescription -> IO () --FIXME: this script should be generated at build time, just installed at this stage install verbosity lbi libDir installProgDir binDir targetProgDir buildPref (progprefix,progsuffix) pkg_descr = do removeDirectoryRecursive libDir `catchIO` \_ -> return () withLib pkg_descr $ \ lib -> findModuleFiles [buildPref] hugsInstallSuffixes (libModules lib) >>= installOrdinaryFiles verbosity libDir let buildProgDir = buildPref </> "programs" when (any (buildable . buildInfo) (executables pkg_descr)) $ createDirectoryIfMissingVerbose verbosity True binDir withExe pkg_descr $ \ exe -> do let bi = buildInfo exe let theBuildDir = buildProgDir </> exeName exe let installDir = installProgDir </> exeName exe let targetDir = targetProgDir </> exeName exe removeDirectoryRecursive installDir `catchIO` \_ -> return () findModuleFiles [theBuildDir] hugsInstallSuffixes (ModuleName.main : autogenModuleName pkg_descr : otherModules (buildInfo exe)) >>= installOrdinaryFiles verbosity installDir let targetName = "\"" ++ (targetDir </> hugsMainFilename exe) ++ "\"" let hugsOptions = hcOptions Hugs (buildInfo exe) ++ languageToFlags (compiler lbi) (defaultLanguage bi) ++ extensionsToFlags (compiler lbi) (allExtensions bi) --TODO: also need to consider options, extensions etc of deps -- see ticket #43 let baseExeFile = progprefix ++ (exeName exe) ++ progsuffix let exeFile = case buildOS of Windows -> binDir </> baseExeFile <.> ".bat" _ -> binDir </> baseExeFile let script = case buildOS of Windows -> let args = hugsOptions ++ [targetName, "%*"] in unlines ["@echo off", unwords ("runhugs" : args)] _ -> let args = hugsOptions ++ [targetName, "\"$@\""] in unlines ["#! /bin/sh", unwords ("runhugs" : args)] writeFileAtomic exeFile script setFileExecutable exeFile hugsInstallSuffixes :: [String] hugsInstallSuffixes = [".hs", ".lhs", dllExtension] -- |Filename used by Hugs for the main module of an executable. -- This is a simple filename, so that Hugs will look for any auxiliary -- modules it uses relative to the directory it's in. hugsMainFilename :: Executable -> FilePath hugsMainFilename exe = "Main" <.> ext where ext = takeExtension (modulePath exe) -- ----------------------------------------------------------------------------- -- Registering registerPackage :: Verbosity -> InstalledPackageInfo -> PackageDescription -> LocalBuildInfo -> Bool -> PackageDBStack -> IO () registerPackage verbosity installedPkgInfo pkg lbi inplace _packageDbs = do --TODO: prefer to have it based on the packageDbs, but how do we know -- the package subdir based on the name? the user can set crazy libsubdir let installDirs = absoluteInstallDirs pkg lbi NoCopyDest pkgdir | inplace = buildDir lbi | otherwise = libdir installDirs createDirectoryIfMissingVerbose verbosity True pkgdir writeUTF8File (pkgdir </> "package.conf") (showInstalledPackageInfo installedPkgInfo)
alphaHeavy/cabal
Cabal/Distribution/Simple/Hugs.hs
bsd-3-clause
27,656
0
23
7,332
6,315
3,351
2,964
464
13
module Transaction.IO where import Transaction.Scheme (Scheme(..), selectScheme) import Transaction.CSV (ParseError, parseCSV, csvContents) import Transaction.Types (Transaction) import Utils (loadFile, injectNothingAs, injectErrorAs) import Control.Monad (join) data LoadError = FileNotFound | InvalidCSV ParseError | UnknownScheme deriving (Show, Eq) -- |Concatenates transactions succesfully loaded from specified paths. loadTransactionFiles :: [FilePath] -> IO [Transaction] loadTransactionFiles paths = do tss <- mapM loadTransactionFile paths return $ concat (map removeFailed tss) where removeFailed (Right ts) = ts removeFailed (Left _) = [] -- |Loads transactions from the CSV file at the specified path. loadTransactionFile :: FilePath -> IO (Either LoadError [Transaction]) loadTransactionFile path = fmap (join . (parseTs <$> scheme <*>)) input where scheme = injectNothingAs UnknownScheme $ selectScheme path input = injectNothingAs FileNotFound <$> loadFile path parseTs sch inp = injectErrorAs InvalidCSV (parseTransactions sch inp) -- |Deserializes a string of transaction according to specified scheme. parseTransactions :: Scheme -> String -> Either ParseError [Transaction] parseTransactions scheme input = do doc <- parseCSV (schemeHeaderP scheme) input return $ (schemeMap scheme) `map` (csvContents doc)
bartfrenk/haskell-transaction
src/Transaction/IO.hs
bsd-3-clause
1,383
0
10
223
370
197
173
23
2
module Util.String ( pack , unpack ) where import UHC.Base ( PackedString, packedStringToString ) pack :: String -> PackedString pack = __toPackedString unpack :: PackedString -> String unpack = packedStringToString foreign import prim "primStringToPackedString" __toPackedString :: String -> PackedString
johanneshilden/liquid-epsilon
Util/String.hs
bsd-3-clause
341
0
6
74
71
42
29
-1
-1
module FooParser where import Control.Monad (void) import Text.Megaparsec import Text.Megaparsec.String -- input stream is of type ‘String’ import qualified Text.Megaparsec.Lexer as L data Section = Section { sectionUsername :: String , sectionParagraphs :: [[String]] } deriving (Eq, Show) spaceConsumer :: Parser () spaceConsumer = L.space (void spaceChar) lineCmnt blockCmnt where lineCmnt = L.skipLineComment "//" blockCmnt = L.skipBlockComment "/*" "*/" parseLexeme :: Parser a -> Parser a parseLexeme = L.lexeme spaceConsumer parseWord :: Parser String parseWord = parseLexeme $ do _ <- char '<' word <- some (alphaNumChar <|> char '-') _ <- char '>' return word parseWords :: Parser [String] parseWords = some parseWord parseParagraphs :: Parser [[String]] parseParagraphs = parseWords `sepBy` parseLexeme (string "%%%%") parseSection :: Parser Section parseSection = do username' <- parseLexeme $ some alphaNumChar _ <- parseLexeme $ char ':' _ <- parseLexeme $ char '{' paragraphs' <- parseParagraphs _ <- parseLexeme $ char '}' return $ Section username' paragraphs' parseSections :: Parser [Section] parseSections = some parseSection
frontrowed/pragmatic-haskell
src/FooParser.hs
bsd-3-clause
1,235
0
12
248
375
192
183
34
1
module Spec.CSR where import Utility.Utility import Data.Int import Data.Bits import Data.Maybe import Data.Tuple import Prelude import qualified Prelude as P -- Machine-level CSRs. data CSR = MHartID | MISA | MStatus | MTVec | MEDeleg | MIDeleg | MIP | MIE | MCycle | MInstRet | MCounterEn | MScratch | MEPC | MCause | MTVal | MHPMCounter3 | MHPMCounter4 | MHPMCounter5 | MHPMCounter6 | MHPMCounter7 | MHPMCounter8 | MHPMCounter9 | MHPMCounter10 | MHPMCounter11 | MHPMCounter12 | MHPMCounter13 | MHPMCounter14 | MHPMCounter15 | MHPMCounter16 | MHPMCounter17 | MHPMCounter18 | MHPMCounter19 | MHPMCounter20 | MHPMCounter21 | MHPMCounter22 | MHPMCounter23 | MHPMCounter24 | MHPMCounter25 | MHPMCounter26 | MHPMCounter27 | MHPMCounter28 | MHPMCounter29 | MHPMCounter30 | MHPMCounter31 | -- Supervisor-level CSRs SStatus | SEDeleg | SIDeleg | STVec | SIP | SIE | SCounterEn | SScratch | SEPC | SCause | STVal | SATP | -- User-mode CSRs UStatus | UIE | UTVec | UScratch | UEPC | UCause | UTVal | UIP | FFlags | FRM | FCSR | Time | Cycle | InstRet | InvalidCSR deriving Eq -- For Clash's sake; otherwise, this could be an enum. lookupCSR :: MachineInt -> CSR lookupCSR x | x == 0x300 = MStatus | x == 0x301 = MISA | x == 0x302 = MEDeleg | x == 0x303 = MIDeleg | x == 0x304 = MIE | x == 0x305 = MTVec | x == 0x306 = MCounterEn | x == 0x340 = MScratch | x == 0x341 = MEPC | x == 0x342 = MCause | x == 0x343 = MTVal | x == 0x344 = MIP | x == 0xB00 = MCycle | x == 0xB02 = MInstRet | x == 0xB03 = MHPMCounter3 | x == 0xB04 = MHPMCounter4 | x == 0xB05 = MHPMCounter5 | x == 0xB06 = MHPMCounter6 | x == 0xB07 = MHPMCounter7 | x == 0xB08 = MHPMCounter8 | x == 0xB09 = MHPMCounter9 | x == 0xB0A = MHPMCounter10 | x == 0xB0B = MHPMCounter11 | x == 0xB0C = MHPMCounter12 | x == 0xB0D = MHPMCounter13 | x == 0xB0E = MHPMCounter14 | x == 0xB0F = MHPMCounter15 | x == 0xB10 = MHPMCounter16 | x == 0xB11 = MHPMCounter17 | x == 0xB12 = MHPMCounter18 | x == 0xB13 = MHPMCounter19 | x == 0xB14 = MHPMCounter20 | x == 0xB15 = MHPMCounter21 | x == 0xB16 = MHPMCounter22 | x == 0xB17 = MHPMCounter23 | x == 0xB18 = MHPMCounter24 | x == 0xB19 = MHPMCounter25 | x == 0xB1A = MHPMCounter26 | x == 0xB1B = MHPMCounter27 | x == 0xB1C = MHPMCounter28 | x == 0xB1D = MHPMCounter29 | x == 0xB1E = MHPMCounter30 | x == 0xB1F = MHPMCounter31 | x == 0x100 = SStatus | x == 0x102 = SEDeleg | x == 0x103 = SIDeleg | x == 0x104 = SIE | x == 0x105 = STVec | x == 0x106 = SCounterEn | x == 0x140 = SScratch | x == 0x141 = SEPC | x == 0x142 = SCause | x == 0x143 = STVal | x == 0x144 = SIP | x == 0x180 = SATP | x == 0x000 = UStatus | x == 0x001 = FFlags | x == 0x002 = FRM | x == 0x003 = FCSR | x == 0x004 = UIE | x == 0x005 = UTVec | x == 0x040 = UScratch | x == 0x041 = UEPC | x == 0x042 = UCause | x == 0x043 = UTVal | x == 0x044 = UIP | x == 0xC00 = Cycle | x == 0xC01 = Time | x == 0xC02 = InstRet | x == 0xF14 = MHartID | otherwise = InvalidCSR
mit-plv/riscv-semantics
src/Spec/CSR.hs
bsd-3-clause
3,131
0
8
837
1,197
607
590
90
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, BangPatterns #-} module Data.Tree23.SortedSet ( Set, empty, singleton, null, size, insert, insertAll, delete, deleteAll, member, notMember, fromList, toList, map, mapMonotonic, filter, partition, unionL, unionR, union, unions, difference, intersection, clean, findMin, findMax, ) where import Prelude hiding (null, findMin, minimum, map, filter) import Data.Maybe import Data.Ord import qualified Data.List as L import Data.Monoid (Monoid, mempty, mappend, (<>), mconcat) import Data.Foldable (Foldable(..)) import qualified Data.Foldable as F import qualified Data.Tree23.Tree23 as T23 import qualified Data.Tree23.Entry as E type Set k = T23.Tree k () empty :: Set k empty = T23.empty null :: Set k -> Bool null = T23.null singleton :: k -> Set k singleton x = T23.singleton x () -- | size O(log n) size :: Set k -> Int size = T23.size -- | insert O( log n) insert :: Ord k => k -> Set k -> Set k insert k !set = T23.insertWith (const) (k, ()) set insertAll :: (Ord k, Foldable t) => t k -> Set k -> Set k insertAll xs set = F.foldl' (flip insert) set xs -- | delete O( log n) delete :: Ord k => k -> Set k -> Set k delete = T23.delete deleteAll :: (Ord k, Foldable t) => t k -> Set k -> Set k deleteAll xs set = F.foldl' (flip delete) set xs -- | member O( log n) member, notMember :: Ord k => k -> Set k -> Bool member = T23.member notMember k = not . T23.member k --------------------------------------------------------------- -- | fromList O( n) fromList :: (Ord k, Foldable t) => t k -> Set k fromList xs = insertAll xs empty -- | toList O( n) uses DList to append the subtrees and nodes results toList :: Set k -> [k] toList = fst . L.unzip . T23.toList --------------------------------------------------------------- -- | map through list conversion map :: (Ord k1, Ord k2) => (k1 -> k2) -> Set k1 -> Set k2 map f = fromList . L.map f . toList mapMonotonic :: (Ord k1, Ord k2) => (k1 -> k2) -> Set k1 -> Set k2 mapMonotonic f = T23.mapEntriesKeysMonotonic (E.mapEntryKey f) ---------------------------------------------------------------- filter :: (k -> Bool) -> Set k -> Set k filter prop = T23.mapEntries (E.filterEntry prop) partition :: (k -> Bool) -> Set k -> (Set k, Set k) partition p xs = (filter p xs, filter (not . p) xs) ---------------------------------------------------------------- unionL, unionR, union :: Ord k => Set k -> Set k -> Set k unionR tx ty = insertAll (toList ty) tx -- on collision it keeps last inserted unionL tx ty = insertAll (toList tx) ty -- on collision it keeps last inserted union = unionL instance (Ord a) => Monoid (Set a) where -- requires extensions TypeSynonymInstances, FlexibleInstances mempty = empty mappend = union difference, intersection :: (Ord k) => Set k -> Set k -> Set k -- difference O(m · log n) difference tx ty = deleteAll (toList ty) tx {- -- intersection intersection tx ty = flipValidity diff -- turn valids off, invalids on where diff = difference tx' ty tx' = clean tx flipValidity = T23.mapEntries E.flipEntryValid -} -- intersection O(n · log m) intersection tx ty = insertAll xs empty where xs = [x | x <- toList tx, x `member` ty] ---------------------------------------------------------------- unions :: (Ord k) => [Set k] -> Set k unions [] = T23.empty unions (hd:tl) = insertAll tailElems hd where tailElems = L.concatMap toList tl ---------------------------------------------------------------- -- remove deleted clean :: Ord k => Set k -> Set k clean = fromList . toList ---------------------------------------------------------------- findMin, findMax :: Ord k => Set k -> Maybe k findMin s = T23.minimum s >>= return . fst findMax s = T23.maximum s >>= return . fst
griba2001/tree23-map-set
src/Data/Tree23/SortedSet.hs
bsd-3-clause
3,848
0
10
765
1,271
683
588
76
1
{-| Module for small utility functions. -} module Cardano.Cluster.Util ( -- * Miscellaneous (|>) , oneSecond , getsModify , runAsync -- * List , unsafeElemIndex , indexedForM , indexedForM_ , stripFilterPrefix , rotations , sizedSubsequences -- * String , kToS , sToK , split -- * Unsafe Type-Coercion from String , unsafeIPFromString , unsafeBoolFromString , unsafeNetworkAddressFromString , unsafeSeverityFromString , unsafePOSIXTimeFromString , unsafeIntFromString -- * CLI <--> Arg , ArgType , varFromParser , execParserEnv -- * NetworkAddress , nextNtwrkAddr , nextStringAddr , ntwrkAddrToString , ntwrkAddrToBaseUrl , ntwrkAddrToNodeAddr ) where import qualified Prelude import Universum hiding (takeWhile) import Control.Concurrent.Async (Async, async, race, wait) import Control.Lens (at) import qualified Data.Aeson as Aeson import Data.Attoparsec.ByteString.Char8 (parseOnly, skipSpace, skipWhile, string, takeWhile) import qualified Data.Attoparsec.Internal.Types as Atto.Internal import qualified Data.ByteString.Char8 as B8 import qualified Data.Char as Char import Data.IP (IP) import Data.List (elemIndex, stripPrefix, (\\)) import Data.Map (Map) import Data.Maybe (fromJust) import Data.Time (NominalDiffTime, defaultTimeLocale, parseTimeM) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Options.Applicative (ParseError (ShowHelpText), Parser, ParserHelp (..), ParserInfo, ParserResult, execFailure, execParserPure, info, parserFailure) import qualified Options.Applicative as Parser import Options.Applicative.Help.Chunk (Chunk (..)) import qualified Safe import Servant.Client (BaseUrl (..), Scheme (..)) import qualified Text.Megaparsec as Parsec import Pos.Core.NetworkAddress (NetworkAddress, addrParser) import Pos.Infra.Network.DnsDomains (NodeAddr (..)) import Pos.Util.Log.Severity (Severity (..)) -- * Miscellaneous -- | Provide a default value for an Alternative (|>) :: Alternative f => f a -> a -> f a f |> a = f <|> pure a infix 4 |> -- | One second in micro-seconds oneSecond :: Int oneSecond = 1000000 -- | Apply a function using the current state that returns a value and modifies -- the state. getsModify :: (s -> (a, s)) -> State s a getsModify f = do (a, s') <- gets f put s' >> return a -- | Run an 'Async' non-terminating action giving some result to a caller -- continuation. -- -- Example: -- -- (handle, res) <- runAsync $ \yield -> do -- print "This happens in an asynchronous thread" -- yield 14 -- threadDelay 10000000 -- return 42 -- -- print res -- 14, immediately -- wait handle >>= print -- 42, after 10s runAsync :: ((b -> IO ()) -> IO a) -> IO (Async a, b) runAsync action = do -- In case an error is thrown in action', the 'takeMVar' will block -- indefinitely. As a result, caller will fail with a very non-helpful -- message if we were simply going for `takeMVar mvar`: -- -- "thread blocked indefinitely in an MVar operation" -- -- With this little trick, we make sure not to wait indefinitely on the -- MVar. Beside, we shouldn't _ever_ reach the `Left` case below because -- 'wait' will re-throw any exception that occurs in the async action. -- So, the only way to reach the `Left` case here is to have `handle` -- terminating "normally" which can't happen. mvar <- newEmptyMVar handle <- async (action (putMVar mvar)) result <- race (wait handle) (takeMVar mvar) case result of Left _ -> fail "Action terminated unexpectedly" Right b -> return (handle, b) -- * String manipulation -- | kebab-case to UPPER_SNAKE_CASE kToS :: String -> String kToS = map (Char.toUpper . replaceIf '-' '_') -- | UPPER_SNAKE_CASE to kebab-case sToK :: String -> String sToK = map (Char.toLower . replaceIf '_' '-') -- | Split a string on the given character split :: Char -> String -> [String] split c s = case break (== c) s of (s', "") -> [s'] (s', rest) -> s' : split c (drop 1 rest) -- | (Internal) Replace third argument by the second one if it matches the first one. replaceIf :: Char -> Char -> Char -> Char replaceIf want to x | x == want = to replaceIf _ _ x = x -- * List -- | Monadic iteration over a list, with indexes indexedForM :: Monad m => [a] -> ((a, Int) -> m b) -> m [b] indexedForM xs = forM $ zip xs (iterate (+1) 0) -- | Monadic iteration over a list, with indexes, discarding the result indexedForM_ :: Monad m => [a] -> ((a, Int) -> m b) -> m () indexedForM_ xs = void . indexedForM xs -- | Get index of an element from a list, throw meaningful error upon failure unsafeElemIndex :: (Eq a, Show a) => a -> [a] -> Int unsafeElemIndex x xs = maybe (error $ "expected '" <> show x <> "' to be an element of " <> show xs) identity (x `elemIndex` xs) -- | Only consider tuples (key, value) where keys have the given prefix stripFilterPrefix :: String -> [(String, a)] -> [(String, a)] stripFilterPrefix p = mapMaybe choose where choose :: (String, a) -> Maybe (String, a) choose (k, v) = (,) <$> stripPrefix p k <*> pure v -- | Get permutations of the size (n-1) for a list of n elements, alongside with -- the element left aside. -- Only safe on sets. rotations :: Eq a => [a] -> [(a, [a])] rotations xs = map (\ys -> (h ys, ys)) (sizedSubsequences (length xs - 1) xs) where -- NOTE Safe on sets h ys = Prelude.head (xs \\ ys) -- | Get all subsequences of a given size sizedSubsequences :: Int -> [a] -> [[a]] sizedSubsequences 0 = const [] sizedSubsequences n = filter ((== n) . length) . subsequences -- * Unsafe Type-Coercion from string -- | Parse a 'ByteString' into an 'IP'. unsafeIPFromString :: String -> IP unsafeIPFromString bytes = case Safe.readMay bytes of Nothing -> error $ "'unsafeIPFromBS' was given a malformed value that can't\ \ be parsed to an IP: " <> toText bytes Just ip -> ip unsafeBoolFromString :: String -> Bool unsafeBoolFromString str = case Safe.readMay str of Nothing -> error $ "Tried to convert a 'String' to a 'Bool' but failed: " <> toText str Just b -> b unsafeIntFromString :: String -> Int unsafeIntFromString str = case Safe.readMay str of Nothing -> error $ "Tried to convert a 'String' to a 'Int' but failed: " <> toText str Just b -> b unsafeNetworkAddressFromString :: String -> NetworkAddress unsafeNetworkAddressFromString str = case Parsec.parse addrParser "" str of Left err -> error $ "Tried to convert a 'String' to a 'NetworkAddress' but failed: " <> toText str <> ", " <> show err Right addr -> addr unsafeSeverityFromString :: String -> Severity unsafeSeverityFromString str = case Aeson.decodeStrict ("\"" <> B8.pack str <> "\"") of Nothing -> error $ "Tried to convert a 'String' to a 'Severity' but failed." Just severity -> severity unsafePOSIXTimeFromString :: String -> NominalDiffTime unsafePOSIXTimeFromString str = case parseTimeM True defaultTimeLocale "%s" str of Nothing -> error $ "Tried to convert a 'String' to a 'NominalDiffTime' but failed: " <> toText str Just b -> utcTimeToPOSIXSeconds b -- * ENV var <--> CLI args -- We want to comprehend any ENVironment variables as if they were CLI -- arguments and flags, such that we can re-use code to parse them and build -- **Args structure from them. -- -- The tricky thing here is that ENVironment "flags" don't exist so to speak, -- so we have to reflect on the opt-applicative@Parser to see whether we expect -- a var to be an 'Arg' or 'Flag'. If we expect a 'Flag' then the underlying -- ENV var should be set to 'True' or 'False' -- -- This also makes sure that we don't forget any CLI args and that's why, we -- need to setup a full ENVironment before we actually start parsing. If one -- variable is missing, it will throw a great deal. data ArgType = Arg | Flag deriving Show -- | Extract the list of ENV var from a 'Options.Applicative.Parser' varFromParser :: Parser a -- Target parser -> [(String, ArgType)] varFromParser parser = foldParse (helpToByteString help) where -- Here is the little trick, we leverage the parserFailure which displays -- a usage with all possible arguments and flags and from this usage, -- we capture all arguments and flags as tuple (String, ArgType) (help, _, _) = let pInfo = info parser mempty in execFailure (parserFailure Parser.defaultPrefs pInfo ShowHelpText mempty) "" -- NOTE: 'fromJust' is safe here as there's always a usage helpToByteString :: ParserHelp -> ByteString helpToByteString = B8.pack . show . fromJust . unChunk . helpUsage -- | Convert a string argument to its corresponding ENV var argToVar :: String -> (String, ArgType) argToVar arg = case elemIndex ' ' arg of Nothing -> (kToS (drop 2 arg), Flag) Just i -> (kToS (drop 2 (take i arg)), Arg) foldParse :: ByteString -> [(String, ArgType)] foldParse = rights . fmap (fmap (argToVar . B8.unpack) . parseOnly capture) . B8.lines capture :: Atto.Internal.Parser ByteString ByteString capture = (skipWhile (/= '[') *> string "[" *> takeWhile (/= ']') <* string "]") <|> (do skipSpace _ <- string "--" str <- takeWhile (not . Char.isSpace) marg <- fmap (fromMaybe "") . optional $ do _ <- string " " str2 <- takeWhile (not . Char.isSpace) pure (" " <> str2) pure ("--" <> str <> marg) ) -- | Run a parser from environment variables rather than command-line arguments execParserEnv :: Map String String -- ^ The full environment ENV -> [(String, ArgType)] -- ^ The restricted variables to consider within the ENV -> ParserInfo a -- ^ A corresponding CLI -> ParserResult a execParserEnv env vars pInfo = do let args = mapMaybe (lookupEnv >=> varToArg) vars execParserPure Parser.defaultPrefs pInfo args where -- | Lookup a value at a given 'Key' in the environment and add it to -- the tuple ('Key', 'ArgType') lookupEnv :: (String, ArgType) -> Maybe (String, ArgType, String) lookupEnv (k, t) = (k, t, ) <$> (env ^. at k) -- | Convert an environment variable to its argument, with value. Returns -- 'Nothing' when Flags are given and turned off. 'Just arg' otherwise. varToArg :: (String, ArgType, String) -> Maybe String varToArg = \case (k, Flag, "True") -> Just ("--" <> sToK k) (_, Flag, _) -> Nothing (k, Arg, v) -> Just ("--" <> sToK k <> "=" <> v) -- * 'NetworkAddress' manipulations -- | Get the next 'NetworkAddress' given an index nextNtwrkAddr :: Word16 -> NetworkAddress -> NetworkAddress nextNtwrkAddr i (host, port) = (host, port + i) -- | Get the next 'NextworkAddress' from a string nextStringAddr :: Word16 -> String -> String nextStringAddr i = ntwrkAddrToString . nextNtwrkAddr i . unsafeNetworkAddressFromString -- | Convert a 'NetworkAddress' to an ENV var ntwrkAddrToString :: NetworkAddress -> String ntwrkAddrToString (host, port) = B8.unpack host <> ":" <> show port ntwrkAddrToBaseUrl :: NetworkAddress -> BaseUrl ntwrkAddrToBaseUrl (host, port) = BaseUrl Https (B8.unpack host) (fromIntegral port) mempty ntwrkAddrToNodeAddr :: NetworkAddress -> NodeAddr a ntwrkAddrToNodeAddr (addr, port) = NodeAddrExact (unsafeIPFromString $ B8.unpack addr) (Just port)
input-output-hk/pos-haskell-prototype
cluster/src/Cardano/Cluster/Util.hs
mit
12,225
0
19
3,236
2,703
1,494
1,209
-1
-1
module ImportTwo where import ImportTwo1 import ImportTwo2 main = x + y
roberth/uu-helium
test/correct/ImportTwo.hs
gpl-3.0
74
0
5
14
19
12
7
4
1
-- file test/Main.hs module Main where import qualified HSpecTests import Test.Hspec main :: IO () main = hspec (parallel HSpecTests.spec)
rodrigo-machado/verigraph
tests/HSpecRunner.hs
gpl-3.0
151
0
8
32
40
23
17
5
1
module Builder.Handlelike where import qualified Data.ByteString.Char8 as BS import Network.Socket import OpenSSL.Session import System.IO class Monad m => HandlelikeM m where hlPutStrLn :: String -> m () hlGetLine :: m String hlGet :: Int -> m String class Handlelike h where hlPutStrLn' :: h -> String -> IO () hlGetLine' :: h -> IO String hlGet' :: h -> Int -> IO String instance Handlelike Handle where hlPutStrLn' h str = hPutStrLn h str hlGetLine' h = hGetLine h hlGet' h n = let f n' = do bs <- BS.hGet h n' return (BS.unpack bs, BS.length bs) in hlGetLoop f n instance Handlelike SSL where hlPutStrLn' s str = mapM_ doChunk $ chunk (str ++ "\n") where chunk "" = [] chunk xs = case splitAt 1024 xs of (ys, zs) -> ys : chunk zs doChunk xs = write s (BS.pack xs) hlGetLine' s = do let f acc = do str <- OpenSSL.Session.read s 1 case BS.unpack str of "\n" -> return (reverse acc) [c] -> f (c : acc) _ -> error "XXX hlGetLine' Socket: Bad recv" f "" hlGet' s n = let f n' = do bs <- OpenSSL.Session.read s n' return (BS.unpack bs, BS.length bs) in hlGetLoop f n instance Handlelike Socket where hlPutStrLn' s str = do _ <- send s (str ++ "\n") return () -- XXX Efficiency of "recv s 1"!: hlGetLine' s = do let f acc = do str <- recv s 1 case str of "\n" -> return (reverse acc) [c] -> f (c : acc) _ -> error "XXX hlGetLine' Socket: Bad recv" f "" hlGet' s n = let f n' = do str <- recv s n' return (str, length str) in hlGetLoop f n hlGetLoop :: (Int -> IO (String, Int)) -> Int -> IO String hlGetLoop f n | n <= 0 = return "" | otherwise = do (str, len) <- f n rest <- hlGetLoop f (n - len) return (str ++ rest) -- XXX This is now rather misnamed: data HandleOrSsl = Handle Handle | Ssl SSL | Socket Socket instance Handlelike HandleOrSsl where hlPutStrLn' (Handle h) str = hlPutStrLn' h str hlPutStrLn' (Ssl s) str = hlPutStrLn' s str hlPutStrLn' (Socket s) str = hlPutStrLn' s str hlGetLine' (Handle h) = hlGetLine' h hlGetLine' (Ssl s) = hlGetLine' s hlGetLine' (Socket s) = hlGetLine' s hlGet' (Handle h) n = hlGet' h n hlGet' (Ssl s) n = hlGet' s n hlGet' (Socket s) n = hlGet' s n
haskell/ghc-builder
common/Builder/Handlelike.hs
bsd-3-clause
2,912
0
18
1,241
1,007
482
525
66
1
{-# LANGUAGE OverloadedStrings #-} import Criterion.Main import System.Metrics (newStore) import Network.Wai.Metrics import Web.Scotty (scottyApp, middleware, get, html) import Network.Wai (Application) import Control.Monad (replicateM_, when) import Data.Int (Int64) import qualified System.Metrics.Counter as Counter import qualified Network.Wai.Test as WT import qualified Data.ByteString as BS testServer :: Bool -> (Application -> IO a) -> Int -> IO WaiMetrics testServer measure action times = do store <- newStore waiMetrics <- registerWaiMetrics store app <- scottyApp $ do when (measure) (middleware (metrics waiMetrics)) get "/" $ html "Ping" replicateM_ times (action app) return waiMetrics readRequestCounter :: Bool -> (Application -> IO a) -> Int -> IO Int64 readRequestCounter measure action times = do waiMetrics <- testServer measure action times Counter.read (requestCounter waiMetrics) -- Send a GET request to a WAI Application httpGet :: BS.ByteString -> Application -> IO WT.SResponse httpGet path = WT.runSession (WT.srequest (WT.SRequest req "")) where req = WT.setRawPathInfo WT.defaultRequest path -- As to version 0.2.1, the middleware costs 0.7 microseconds per request -- Most of this time is spent with the latency measure main :: IO() main = defaultMain [ bgroup "fib" [ bench "with metrics" $ nfIO (readRequestCounter True (httpGet "") 10000) , bench "without metrics" $ nfIO (readRequestCounter False (httpGet "") 10000) ] ]
Helkafen/wai-middleware-metrics
Benchmark.hs
bsd-3-clause
1,543
0
15
289
452
233
219
32
1
----------------------------------------------------------------------------- -- | -- Module : Control.Monad.ST.Lazy -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (requires universal quantification for runST) -- -- This module presents an identical interface to "Control.Monad.ST", -- except that the monad delays evaluation of state operations until -- a value depending on them is required. -- ----------------------------------------------------------------------------- module Control.Monad.ST.Lazy ( -- * The 'ST' monad ST, runST, fixST, -- * Converting between strict and lazy 'ST' strictToLazyST, lazyToStrictST, -- * Converting 'ST' To 'IO' RealWorld, stToIO, -- * Unsafe operations unsafeInterleaveST, unsafeIOToST ) where import Prelude import Control.Monad.Fix import Control.Monad.ST (RealWorld) import qualified Control.Monad.ST as ST #ifdef __GLASGOW_HASKELL__ import qualified GHC.ST import GHC.Base import Control.Monad #endif #ifdef __HUGS__ import Hugs.LazyST #endif #ifdef __GLASGOW_HASKELL__ -- | The lazy state-transformer monad. -- A computation of type @'ST' s a@ transforms an internal state indexed -- by @s@, and returns a value of type @a@. -- The @s@ parameter is either -- -- * an unstantiated type variable (inside invocations of 'runST'), or -- -- * 'RealWorld' (inside invocations of 'stToIO'). -- -- It serves to keep the internal states of different invocations of -- 'runST' separate from each other and from invocations of 'stToIO'. -- -- The '>>=' and '>>' operations are not strict in the state. For example, -- -- @'runST' (writeSTRef _|_ v >>= readSTRef _|_ >> return 2) = 2@ newtype ST s a = ST (State s -> (a, State s)) data State s = S# (State# s) instance Functor (ST s) where fmap f m = ST $ \ s -> let ST m_a = m (r,new_s) = m_a s in (f r,new_s) instance Monad (ST s) where return a = ST $ \ s -> (a,s) m >> k = m >>= \ _ -> k fail s = error s (ST m) >>= k = ST $ \ s -> let (r,new_s) = m s ST k_a = k r in k_a new_s {-# NOINLINE runST #-} -- | Return the value computed by a state transformer computation. -- The @forall@ ensures that the internal state used by the 'ST' -- computation is inaccessible to the rest of the program. runST :: (forall s. ST s a) -> a runST st = case st of ST the_st -> let (r,_) = the_st (S# realWorld#) in r -- | Allow the result of a state transformer computation to be used (lazily) -- inside the computation. -- Note that if @f@ is strict, @'fixST' f = _|_@. fixST :: (a -> ST s a) -> ST s a fixST m = ST (\ s -> let ST m_r = m r (r,s') = m_r s in (r,s')) #endif instance MonadFix (ST s) where mfix = fixST -- --------------------------------------------------------------------------- -- Strict <--> Lazy #ifdef __GLASGOW_HASKELL__ {-| Convert a strict 'ST' computation into a lazy one. The strict state thread passed to 'strictToLazyST' is not performed until the result of the lazy state thread it returns is demanded. -} strictToLazyST :: ST.ST s a -> ST s a strictToLazyST m = ST $ \s -> let pr = case s of { S# s# -> GHC.ST.liftST m s# } r = case pr of { GHC.ST.STret _ v -> v } s' = case pr of { GHC.ST.STret s2# _ -> S# s2# } in (r, s') {-| Convert a lazy 'ST' computation into a strict one. -} lazyToStrictST :: ST s a -> ST.ST s a lazyToStrictST (ST m) = GHC.ST.ST $ \s -> case (m (S# s)) of (a, S# s') -> (# s', a #) unsafeInterleaveST :: ST s a -> ST s a unsafeInterleaveST = strictToLazyST . ST.unsafeInterleaveST . lazyToStrictST #endif unsafeIOToST :: IO a -> ST s a unsafeIOToST = strictToLazyST . ST.unsafeIOToST -- | A monad transformer embedding lazy state transformers in the 'IO' -- monad. The 'RealWorld' parameter indicates that the internal state -- used by the 'ST' computation is a special one supplied by the 'IO' -- monad, and thus distinct from those used by invocations of 'runST'. stToIO :: ST RealWorld a -> IO a stToIO = ST.stToIO . lazyToStrictST
alekar/hugs
packages/base/Control/Monad/ST/Lazy.hs
bsd-3-clause
4,279
24
15
961
872
490
382
19
1
import Java import java "java.lang.Math" main :: IO () main = java $ do d <- Math.sqrt 25.0 io $ print d
rahulmutt/ghcvm
tests/suite/java-imports/run/StaticMethod.hs
bsd-3-clause
113
1
10
30
53
24
29
-1
-1
module Tests.Language.Parser.Functions ( parserFunctionTests ) where import Test.Framework ( Test , testGroup ) import Test.Framework.Providers.HUnit ( testCase ) import Test.HUnit ( Assertion ) import TestHelpers.Util ( parserTest ) import Language.Ast parserFunctionTests :: Test parserFunctionTests = testGroup "Function Tests" [ testCase "parses simple function call" test_parses_simple_application , testCase "parses function call with variable arg" test_parses_application_with_var_arg , testCase "parses no arguments function call" test_parses_noargs_application , testCase "parses function with block" test_parses_function_blocks ] test_parses_simple_application :: Assertion test_parses_simple_application = let program = "cube(1, 1, i)\n\n" cube = Application (LocalVariable "cube") [ ApplicationSingleArg $ EVal $ Number 1 , ApplicationSingleArg $ EVal $ Number 1 , ApplicationSingleArg $ EVar $ LocalVariable "i" ] Nothing expected = Program [StExpression $ EApp cube] in parserTest program expected test_parses_application_with_var_arg :: Assertion test_parses_application_with_var_arg = let program = "a = 2\ncube(1, a, 3)\n\n" assign = StAssign $ AbsoluteAssignment "a" $ EVal $ Number 2 cube = StExpression $ EApp $ Application (LocalVariable "cube") [ ApplicationSingleArg $ EVal $ Number 1 , ApplicationSingleArg $ EVar $ LocalVariable "a" , ApplicationSingleArg $ EVal $ Number 3 ] Nothing expected = Program [assign, cube] in parserTest program expected test_parses_noargs_application :: Assertion test_parses_noargs_application = let program = "foo()" cube = Application (LocalVariable "foo") [] Nothing expected = Program [StExpression $ EApp cube] in parserTest program expected test_parses_function_blocks :: Assertion test_parses_function_blocks = let program = "box(a, a, 2)\n\tb = 2 * 0.5\n\tbox(a, b, 1)\n" ass = ElAssign $ AbsoluteAssignment "b" $ BinaryOp "*" (EVal $ Number 2) (EVal $ Number 0.5) box2 = ElExpression $ EApp $ Application (LocalVariable "box") [ ApplicationSingleArg $ EVar $ LocalVariable "a" , ApplicationSingleArg $ EVar $ LocalVariable "b" , ApplicationSingleArg $ EVal $ Number 1 ] Nothing box1 = StExpression $ EApp $ Application (LocalVariable "box") [ ApplicationSingleArg $ EVar $ LocalVariable "a" , ApplicationSingleArg $ EVar $ LocalVariable "a" , ApplicationSingleArg $ EVal $ Number 2 ] $ Just (Lambda [] Nothing $ Block [ass, box2]) expected = Program [box1] in parserTest program expected
rumblesan/improviz
test/Tests/Language/Parser/Functions.hs
bsd-3-clause
3,185
0
14
1,059
653
336
317
68
1
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Network.WebSockets.Tests ( tests ) where -------------------------------------------------------------------------------- import qualified Blaze.ByteString.Builder as Builder import Control.Applicative ((<$>)) import Control.Concurrent (forkIO) import Control.Monad (forM_, replicateM) import qualified Data.ByteString.Lazy as BL import Data.List (intersperse) import Data.Maybe (catMaybes) import Test.Framework (Test, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit ((@=?)) import Test.QuickCheck (Arbitrary (..), Gen, Property) import qualified Test.QuickCheck as QC import qualified Test.QuickCheck.Monadic as QC -------------------------------------------------------------------------------- import Network.WebSockets import qualified Network.WebSockets.Hybi13 as Hybi13 import Network.WebSockets.Hybi13.Demultiplex import Network.WebSockets.Protocol import qualified Network.WebSockets.Stream as Stream import Network.WebSockets.Tests.Util import Network.WebSockets.Types -------------------------------------------------------------------------------- tests :: Test tests = testGroup "Network.WebSockets.Test" [ testProperty "simple encode/decode Hybi13" (testSimpleEncodeDecode Hybi13) , testProperty "framgmented Hybi13" testFragmentedHybi13 ] -------------------------------------------------------------------------------- testSimpleEncodeDecode :: Protocol -> Property testSimpleEncodeDecode protocol = QC.monadicIO $ QC.forAllM QC.arbitrary $ \msgs -> QC.run $ do echo <- Stream.makeEchoStream parse <- decodeMessages protocol echo write <- encodeMessages protocol ClientConnection echo _ <- forkIO $ forM_ msgs write msgs' <- catMaybes <$> replicateM (length msgs) parse Stream.close echo msgs @=? msgs' -------------------------------------------------------------------------------- testFragmentedHybi13 :: Property testFragmentedHybi13 = QC.monadicIO $ QC.forAllM QC.arbitrary $ \fragmented -> QC.run $ do echo <- Stream.makeEchoStream parse <- Hybi13.decodeMessages echo -- is' <- Streams.filter isDataMessage =<< Hybi13.decodeMessages is -- Simple hacky encoding of all frames _ <- forkIO $ do mapM_ (Stream.write echo) [ Builder.toLazyByteString (Hybi13.encodeFrame Nothing f) | FragmentedMessage _ frames <- fragmented , f <- frames ] Stream.close echo -- Check if we got all data msgs <- filter isDataMessage <$> parseAll parse [msg | FragmentedMessage msg _ <- fragmented] @=? msgs where isDataMessage (ControlMessage _) = False isDataMessage (DataMessage _) = True parseAll parse = do mbMsg <- parse case mbMsg of Just msg -> (msg :) <$> parseAll parse Nothing -> return [] -------------------------------------------------------------------------------- instance Arbitrary FrameType where arbitrary = QC.elements [ ContinuationFrame , TextFrame , BinaryFrame , CloseFrame , PingFrame , PongFrame ] -------------------------------------------------------------------------------- instance Arbitrary Frame where arbitrary = do fin <- arbitrary rsv1 <- arbitrary rsv2 <- arbitrary rsv3 <- arbitrary t <- arbitrary payload <- case t of TextFrame -> arbitraryUtf8 _ -> BL.pack <$> arbitrary return $ Frame fin rsv1 rsv2 rsv3 t payload -------------------------------------------------------------------------------- instance Arbitrary Message where arbitrary = do payload <- BL.pack <$> arbitrary closecode <- arbitrary QC.elements [ ControlMessage (Close closecode payload) , ControlMessage (Ping payload) , ControlMessage (Pong payload) , DataMessage (Text payload) , DataMessage (Binary payload) ] -------------------------------------------------------------------------------- data FragmentedMessage = FragmentedMessage Message [Frame] deriving (Show) -------------------------------------------------------------------------------- instance Arbitrary FragmentedMessage where arbitrary = do -- Pick a frametype and a corresponding random payload ft <- QC.elements [TextFrame, BinaryFrame] payload <- case ft of TextFrame -> arbitraryUtf8 _ -> arbitraryByteString fragments <- arbitraryFragmentation payload let fs = makeFrames $ zip (ft : repeat ContinuationFrame) fragments msg = case ft of TextFrame -> DataMessage (Text payload) BinaryFrame -> DataMessage (Binary payload) _ -> error "Arbitrary FragmentedMessage crashed" interleaved <- arbitraryInterleave genControlFrame fs return $ FragmentedMessage msg interleaved -- return $ FragmentedMessage msg fs where makeFrames [] = [] makeFrames [(ft, pl)] = [Frame True False False False ft pl] makeFrames ((ft, pl) : fr) = Frame False False False False ft pl : makeFrames fr genControlFrame = QC.elements [ Frame True False False False PingFrame "Herp" , Frame True True True True PongFrame "Derp" ] -------------------------------------------------------------------------------- arbitraryFragmentation :: BL.ByteString -> Gen [BL.ByteString] arbitraryFragmentation bs = arbitraryFragmentation' bs where len :: Int len = fromIntegral $ BL.length bs arbitraryFragmentation' bs' = do -- TODO: we currently can't send packets of length 0. We should -- investigate why (regardless of the spec). n <- QC.choose (1, len - 1) let (l, r) = BL.splitAt (fromIntegral n) bs' case r of "" -> return [l] _ -> (l :) <$> arbitraryFragmentation' r -------------------------------------------------------------------------------- arbitraryInterleave :: Gen a -> [a] -> Gen [a] arbitraryInterleave sep xs = fmap concat $ sequence $ [sep'] ++ intersperse sep' [return [x] | x <- xs] ++ [sep'] where sep' = QC.sized $ \size -> do num <- QC.choose (1, size) replicateM num sep
zodiac/websockets
tests/haskell/Network/WebSockets/Tests.hs
bsd-3-clause
7,239
0
19
2,159
1,479
773
706
127
3
{-# OPTIONS_GHC -Wall #-} module AST.Expression.Valid where import AST.PrettyPrint import Text.PrettyPrint as P import qualified AST.Expression.General as General import AST.Type (RawType) import qualified AST.Variable as Var import qualified AST.Annotation as Annotation import qualified AST.Pattern as Pattern {-| "Normal" expressions. When the compiler checks that type annotations and ports are all paired with definitions in the appropriate order, it collapses them into a Def that is easier to work with in later phases of compilation. -} type Expr = General.Expr Annotation.Region Def Var.Raw type Expr' = General.Expr' Annotation.Region Def Var.Raw data Def = Definition Pattern.RawPattern Expr (Maybe RawType) deriving (Show) instance Pretty Def where pretty (Definition pattern expr maybeTipe) = P.vcat [ annotation, definition ] where definition = pretty pattern <+> P.equals <+> pretty expr annotation = case maybeTipe of Nothing -> P.empty Just tipe -> pretty pattern <+> P.colon <+> pretty tipe
JoeyEremondi/haskelm
src/AST/Expression/Valid.hs
bsd-3-clause
1,095
0
13
228
232
131
101
20
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module Distribution.Types.TestSuite ( TestSuite(..), emptyTestSuite, testType, testModules, testModulesAutogen ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Types.BuildInfo import Distribution.Types.TestType import Distribution.Types.TestSuiteInterface import Distribution.Types.UnqualComponentName import Distribution.ModuleName -- | A \"test-suite\" stanza in a cabal file. -- data TestSuite = TestSuite { testName :: UnqualComponentName, testInterface :: TestSuiteInterface, testBuildInfo :: BuildInfo } deriving (Generic, Show, Read, Eq, Typeable, Data) instance Binary TestSuite instance Monoid TestSuite where mempty = TestSuite { testName = mempty, testInterface = mempty, testBuildInfo = mempty } mappend = (<>) instance Semigroup TestSuite where a <> b = TestSuite { testName = combine' testName, testInterface = combine testInterface, testBuildInfo = combine testBuildInfo } where combine field = field a `mappend` field b combine' field = case ( unUnqualComponentName $ field a , unUnqualComponentName $ field b) of ("", _) -> field b (_, "") -> field a (x, y) -> error $ "Ambiguous values for test field: '" ++ x ++ "' and '" ++ y ++ "'" emptyTestSuite :: TestSuite emptyTestSuite = mempty testType :: TestSuite -> TestType testType test = case testInterface test of TestSuiteExeV10 ver _ -> TestTypeExe ver TestSuiteLibV09 ver _ -> TestTypeLib ver TestSuiteUnsupported testtype -> testtype -- | Get all the module names from a test suite. testModules :: TestSuite -> [ModuleName] testModules test = (case testInterface test of TestSuiteLibV09 _ m -> [m] _ -> []) ++ otherModules (testBuildInfo test) -- | Get all the auto generated module names from a test suite. -- This are a subset of 'testModules'. testModulesAutogen :: TestSuite -> [ModuleName] testModulesAutogen test = autogenModules (testBuildInfo test)
mydaum/cabal
Cabal/Distribution/Types/TestSuite.hs
bsd-3-clause
2,335
0
15
674
506
279
227
53
3
yes = qux (if a then 1 else if b then 1 else 2)
mpickering/hlint-refactor
tests/examples/Default11.hs
bsd-3-clause
48
0
8
14
28
16
12
1
3
{-# LANGUAGE DeriveGeneric #-} module Distribution.Types.ComponentRequestedSpec ( -- $buildable_vs_enabled_components ComponentRequestedSpec(..), ComponentDisabledReason(..), defaultComponentRequestedSpec, componentNameRequested, componentEnabled, componentDisabledReason, ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Text import Distribution.Types.Component -- TODO: maybe remove me? import Distribution.Types.ComponentName -- $buildable_vs_enabled_components -- #buildable_vs_enabled_components# -- -- = Note: Buildable versus requested versus enabled components -- What's the difference between a buildable component (ala -- 'componentBuildable'), a requested component -- (ala 'componentNameRequested'), and an enabled component (ala -- 'componentEnabled')? -- -- A component is __buildable__ if, after resolving flags and -- conditionals, there is no @buildable: False@ property in it. -- This is a /static/ property that arises from the -- Cabal file and the package description flattening; once we have -- a 'PackageDescription' buildability is known. -- -- A component is __requested__ if a user specified, via a -- the flags and arguments passed to configure, that it should be -- built. E.g., @--enable-tests@ or @--enable-benchmarks@ request -- all tests and benchmarks, if they are provided. What is requested -- can be read off directly from 'ComponentRequestedSpec'. A requested -- component is not always buildable; e.g., a user may @--enable-tests@ -- but one of the test suites may have @buildable: False@. -- -- A component is __enabled__ if it is BOTH buildable -- and requested. Once we have a 'LocalBuildInfo', whether or not a -- component is enabled is known. -- -- Generally speaking, most Cabal API code cares if a component -- is enabled. (For example, if you want to run a preprocessor on each -- component prior to building them, you want to run this on each -- /enabled/ component.) -- -- Note that post-configuration, you will generally not see a -- non-buildable 'Component'. This is because 'flattenPD' will drop -- any such components from 'PackageDescription'. See #3858 for -- an example where this causes problems. -- | Describes what components are enabled by user-interaction. -- See also this note in -- "Distribution.Types.ComponentRequestedSpec#buildable_vs_enabled_components". -- -- @since 2.0.0.0 data ComponentRequestedSpec = ComponentRequestedSpec { testsRequested :: Bool , benchmarksRequested :: Bool } | OneComponentRequestedSpec ComponentName deriving (Generic, Read, Show, Eq) instance Binary ComponentRequestedSpec -- | The default set of enabled components. Historically tests and -- benchmarks are NOT enabled by default. -- -- @since 2.0.0.0 defaultComponentRequestedSpec :: ComponentRequestedSpec defaultComponentRequestedSpec = ComponentRequestedSpec False False -- | Is this component enabled? See also this note in -- "Distribution.Types.ComponentRequestedSpec#buildable_vs_enabled_components". -- -- @since 2.0.0.0 componentEnabled :: ComponentRequestedSpec -> Component -> Bool componentEnabled enabled = isNothing . componentDisabledReason enabled -- | Is this component name enabled? See also this note in -- "Distribution.Types.ComponentRequestedSpec#buildable_vs_enabled_components". -- -- @since 2.0.0.0 componentNameRequested :: ComponentRequestedSpec -> ComponentName -> Bool componentNameRequested enabled = isNothing . componentNameNotRequestedReason enabled -- | Is this component disabled, and if so, why? -- -- @since 2.0.0.0 componentDisabledReason :: ComponentRequestedSpec -> Component -> Maybe ComponentDisabledReason componentDisabledReason enabled comp | not (componentBuildable comp) = Just DisabledComponent | otherwise = componentNameNotRequestedReason enabled (componentName comp) -- | Is this component name disabled, and if so, why? -- -- @since 2.0.0.0 componentNameNotRequestedReason :: ComponentRequestedSpec -> ComponentName -> Maybe ComponentDisabledReason componentNameNotRequestedReason ComponentRequestedSpec{ testsRequested = False } (CTestName _) = Just DisabledAllTests componentNameNotRequestedReason ComponentRequestedSpec{ benchmarksRequested = False } (CBenchName _) = Just DisabledAllBenchmarks componentNameNotRequestedReason ComponentRequestedSpec{} _ = Nothing componentNameNotRequestedReason (OneComponentRequestedSpec cname) c | c == cname = Nothing | otherwise = Just (DisabledAllButOne (display cname)) -- | A reason explaining why a component is disabled. -- -- @since 2.0.0.0 data ComponentDisabledReason = DisabledComponent | DisabledAllTests | DisabledAllBenchmarks | DisabledAllButOne String
mydaum/cabal
Cabal/Distribution/Types/ComponentRequestedSpec.hs
bsd-3-clause
4,911
0
10
840
471
280
191
46
1
module Test where import Foo.Bar import Foo.Bar.Blub import Ugah.Argh import Control.Monad
jystic/hsimport
tests/inputFiles/SymbolTest4.hs
bsd-3-clause
91
0
4
11
25
16
9
5
0
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} #if __GLASGOW_HASKELL__ >= 707 {-# LANGUAGE RoleAnnotations #-} #endif #if __GLASGOW_HASKELL__ >= 711 {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.Internal.Bazaar -- Copyright : (C) 2012-2015 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable -- ---------------------------------------------------------------------------- module Control.Lens.Internal.Bazaar ( Bizarre(..) , Bazaar(..), Bazaar' , BazaarT(..), BazaarT' , Bizarre1(..) , Bazaar1(..), Bazaar1' , BazaarT1(..), BazaarT1' ) where import Control.Applicative import Control.Arrow as Arrow import Control.Category import Control.Comonad import Control.Lens.Internal.Context import Control.Lens.Internal.Indexed import Data.Functor.Apply import Data.Functor.Compose import Data.Functor.Contravariant import Data.Functor.Identity import Data.Semigroup import Data.Profunctor import Data.Profunctor.Rep import Data.Profunctor.Sieve import Data.Profunctor.Unsafe import Prelude hiding ((.),id) ------------------------------------------------------------------------------ -- Bizarre ------------------------------------------------------------------------------ -- | This class is used to run the various 'Bazaar' variants used in this -- library. class Profunctor p => Bizarre p w | w -> p where bazaar :: Applicative f => p a (f b) -> w a b t -> f t ------------------------------------------------------------------------------ -- Bazaar ------------------------------------------------------------------------------ -- | This is used to characterize a 'Control.Lens.Traversal.Traversal'. -- -- a.k.a. indexed Cartesian store comonad, indexed Kleene store comonad, or an indexed 'FunList'. -- -- <http://twanvl.nl/blog/haskell/non-regular1> -- -- A 'Bazaar' is like a 'Control.Lens.Traversal.Traversal' that has already been applied to some structure. -- -- Where a @'Context' a b t@ holds an @a@ and a function from @b@ to -- @t@, a @'Bazaar' a b t@ holds @N@ @a@s and a function from @N@ -- @b@s to @t@, (where @N@ might be infinite). -- -- Mnemonically, a 'Bazaar' holds many stores and you can easily add more. -- -- This is a final encoding of 'Bazaar'. newtype Bazaar p a b t = Bazaar { runBazaar :: forall f. Applicative f => p a (f b) -> f t } -- type role Bazaar representatonal nominal nominal nominal -- | This alias is helpful when it comes to reducing repetition in type signatures. -- -- @ -- type 'Bazaar'' p a t = 'Bazaar' p a a t -- @ type Bazaar' p a = Bazaar p a a instance IndexedFunctor (Bazaar p) where ifmap f (Bazaar k) = Bazaar (fmap f . k) {-# INLINE ifmap #-} instance Conjoined p => IndexedComonad (Bazaar p) where iextract (Bazaar m) = runIdentity $ m (arr Identity) {-# INLINE iextract #-} iduplicate (Bazaar m) = getCompose $ m (Compose #. distrib sell . sell) {-# INLINE iduplicate #-} instance Corepresentable p => Sellable p (Bazaar p) where sell = cotabulate $ \ w -> Bazaar $ tabulate $ \k -> pure (cosieve k w) {-# INLINE sell #-} instance Profunctor p => Bizarre p (Bazaar p) where bazaar g (Bazaar f) = f g {-# INLINE bazaar #-} instance Functor (Bazaar p a b) where fmap = ifmap {-# INLINE fmap #-} instance Apply (Bazaar p a b) where Bazaar mf <.> Bazaar ma = Bazaar $ \ pafb -> mf pafb <*> ma pafb {-# INLINE (<.>) #-} instance Applicative (Bazaar p a b) where pure a = Bazaar $ \_ -> pure a {-# INLINE pure #-} Bazaar mf <*> Bazaar ma = Bazaar $ \ pafb -> mf pafb <*> ma pafb {-# INLINE (<*>) #-} instance (a ~ b, Conjoined p) => Comonad (Bazaar p a b) where extract = iextract {-# INLINE extract #-} duplicate = iduplicate {-# INLINE duplicate #-} instance (a ~ b, Conjoined p) => ComonadApply (Bazaar p a b) where (<@>) = (<*>) {-# INLINE (<@>) #-} ------------------------------------------------------------------------------ -- BazaarT ------------------------------------------------------------------------------ -- | 'BazaarT' is like 'Bazaar', except that it provides a questionable 'Contravariant' instance -- To protect this instance it relies on the soundness of another 'Contravariant' type, and usage conventions. -- -- For example. This lets us write a suitably polymorphic and lazy 'Control.Lens.Traversal.taking', but there -- must be a better way! newtype BazaarT p (g :: * -> *) a b t = BazaarT { runBazaarT :: forall f. Applicative f => p a (f b) -> f t } #if __GLASGOW_HASKELL__ >= 707 type role BazaarT representational nominal nominal nominal nominal #endif -- | This alias is helpful when it comes to reducing repetition in type signatures. -- -- @ -- type 'BazaarT'' p g a t = 'BazaarT' p g a a t -- @ type BazaarT' p g a = BazaarT p g a a instance IndexedFunctor (BazaarT p g) where ifmap f (BazaarT k) = BazaarT (fmap f . k) {-# INLINE ifmap #-} instance Conjoined p => IndexedComonad (BazaarT p g) where iextract (BazaarT m) = runIdentity $ m (arr Identity) {-# INLINE iextract #-} iduplicate (BazaarT m) = getCompose $ m (Compose #. distrib sell . sell) {-# INLINE iduplicate #-} instance Corepresentable p => Sellable p (BazaarT p g) where sell = cotabulate $ \ w -> BazaarT (`cosieve` w) {-# INLINE sell #-} instance Profunctor p => Bizarre p (BazaarT p g) where bazaar g (BazaarT f) = f g {-# INLINE bazaar #-} instance Functor (BazaarT p g a b) where fmap = ifmap {-# INLINE fmap #-} instance Apply (BazaarT p g a b) where BazaarT mf <.> BazaarT ma = BazaarT $ \ pafb -> mf pafb <*> ma pafb {-# INLINE (<.>) #-} instance Applicative (BazaarT p g a b) where pure a = BazaarT $ tabulate $ \_ -> pure (pure a) {-# INLINE pure #-} BazaarT mf <*> BazaarT ma = BazaarT $ \ pafb -> mf pafb <*> ma pafb {-# INLINE (<*>) #-} instance (a ~ b, Conjoined p) => Comonad (BazaarT p g a b) where extract = iextract {-# INLINE extract #-} duplicate = iduplicate {-# INLINE duplicate #-} instance (a ~ b, Conjoined p) => ComonadApply (BazaarT p g a b) where (<@>) = (<*>) {-# INLINE (<@>) #-} instance (Profunctor p, Contravariant g) => Contravariant (BazaarT p g a b) where contramap _ = (<$) (error "contramap: BazaarT") {-# INLINE contramap #-} instance Contravariant g => Semigroup (BazaarT p g a b t) where BazaarT a <> BazaarT b = BazaarT $ \f -> a f <* b f {-# INLINE (<>) #-} instance Contravariant g => Monoid (BazaarT p g a b t) where mempty = BazaarT $ \_ -> pure (error "mempty: BazaarT") {-# INLINE mempty #-} BazaarT a `mappend` BazaarT b = BazaarT $ \f -> a f <* b f {-# INLINE mappend #-} ------------------------------------------------------------------------------ -- Bizarre1 ------------------------------------------------------------------------------ class Profunctor p => Bizarre1 p w | w -> p where bazaar1 :: Apply f => p a (f b) -> w a b t -> f t ------------------------------------------------------------------------------ -- Bazaar1 ------------------------------------------------------------------------------ -- | This is used to characterize a 'Control.Lens.Traversal.Traversal'. -- -- a.k.a. indexed Cartesian store comonad, indexed Kleene store comonad, or an indexed 'FunList'. -- -- <http://twanvl.nl/blog/haskell/non-regular1> -- -- A 'Bazaar1' is like a 'Control.Lens.Traversal.Traversal' that has already been applied to some structure. -- -- Where a @'Context' a b t@ holds an @a@ and a function from @b@ to -- @t@, a @'Bazaar1' a b t@ holds @N@ @a@s and a function from @N@ -- @b@s to @t@, (where @N@ might be infinite). -- -- Mnemonically, a 'Bazaar1' holds many stores and you can easily add more. -- -- This is a final encoding of 'Bazaar1'. newtype Bazaar1 p a b t = Bazaar1 { runBazaar1 :: forall f. Apply f => p a (f b) -> f t } -- type role Bazaar1 representatonal nominal nominal nominal -- | This alias is helpful when it comes to reducing repetition in type signatures. -- -- @ -- type 'Bazaar1'' p a t = 'Bazaar1' p a a t -- @ type Bazaar1' p a = Bazaar1 p a a instance IndexedFunctor (Bazaar1 p) where ifmap f (Bazaar1 k) = Bazaar1 (fmap f . k) {-# INLINE ifmap #-} instance Conjoined p => IndexedComonad (Bazaar1 p) where iextract (Bazaar1 m) = runIdentity $ m (arr Identity) {-# INLINE iextract #-} iduplicate (Bazaar1 m) = getCompose $ m (Compose #. distrib sell . sell) {-# INLINE iduplicate #-} instance Corepresentable p => Sellable p (Bazaar1 p) where sell = cotabulate $ \ w -> Bazaar1 $ tabulate $ \k -> pure (cosieve k w) {-# INLINE sell #-} instance Profunctor p => Bizarre1 p (Bazaar1 p) where bazaar1 g (Bazaar1 f) = f g {-# INLINE bazaar1 #-} instance Functor (Bazaar1 p a b) where fmap = ifmap {-# INLINE fmap #-} instance Apply (Bazaar1 p a b) where Bazaar1 mf <.> Bazaar1 ma = Bazaar1 $ \ pafb -> mf pafb <.> ma pafb {-# INLINE (<.>) #-} instance (a ~ b, Conjoined p) => Comonad (Bazaar1 p a b) where extract = iextract {-# INLINE extract #-} duplicate = iduplicate {-# INLINE duplicate #-} instance (a ~ b, Conjoined p) => ComonadApply (Bazaar1 p a b) where Bazaar1 mf <@> Bazaar1 ma = Bazaar1 $ \ pafb -> mf pafb <.> ma pafb {-# INLINE (<@>) #-} ------------------------------------------------------------------------------ -- BazaarT1 ------------------------------------------------------------------------------ -- | 'BazaarT1' is like 'Bazaar1', except that it provides a questionable 'Contravariant' instance -- To protect this instance it relies on the soundness of another 'Contravariant' type, and usage conventions. -- -- For example. This lets us write a suitably polymorphic and lazy 'Control.Lens.Traversal.taking', but there -- must be a better way! newtype BazaarT1 p (g :: * -> *) a b t = BazaarT1 { runBazaarT1 :: forall f. Apply f => p a (f b) -> f t } #if __GLASGOW_HASKELL__ >= 707 type role BazaarT1 representational nominal nominal nominal nominal #endif -- | This alias is helpful when it comes to reducing repetition in type signatures. -- -- @ -- type 'BazaarT1'' p g a t = 'BazaarT1' p g a a t -- @ type BazaarT1' p g a = BazaarT1 p g a a instance IndexedFunctor (BazaarT1 p g) where ifmap f (BazaarT1 k) = BazaarT1 (fmap f . k) {-# INLINE ifmap #-} instance Conjoined p => IndexedComonad (BazaarT1 p g) where iextract (BazaarT1 m) = runIdentity $ m (arr Identity) {-# INLINE iextract #-} iduplicate (BazaarT1 m) = getCompose $ m (Compose #. distrib sell . sell) {-# INLINE iduplicate #-} instance Corepresentable p => Sellable p (BazaarT1 p g) where sell = cotabulate $ \ w -> BazaarT1 (`cosieve` w) {-# INLINE sell #-} instance Profunctor p => Bizarre1 p (BazaarT1 p g) where bazaar1 g (BazaarT1 f) = f g {-# INLINE bazaar1 #-} instance Functor (BazaarT1 p g a b) where fmap = ifmap {-# INLINE fmap #-} instance Apply (BazaarT1 p g a b) where BazaarT1 mf <.> BazaarT1 ma = BazaarT1 $ \ pafb -> mf pafb <.> ma pafb {-# INLINE (<.>) #-} instance (a ~ b, Conjoined p) => Comonad (BazaarT1 p g a b) where extract = iextract {-# INLINE extract #-} duplicate = iduplicate {-# INLINE duplicate #-} instance (a ~ b, Conjoined p) => ComonadApply (BazaarT1 p g a b) where BazaarT1 mf <@> BazaarT1 ma = BazaarT1 $ \ pafb -> mf pafb <.> ma pafb {-# INLINE (<@>) #-} instance (Profunctor p, Contravariant g) => Contravariant (BazaarT1 p g a b) where contramap _ = (<$) (error "contramap: BazaarT1") {-# INLINE contramap #-} instance Contravariant g => Semigroup (BazaarT1 p g a b t) where BazaarT1 a <> BazaarT1 b = BazaarT1 $ \f -> a f <. b f {-# INLINE (<>) #-}
rpglover64/lens
src/Control/Lens/Internal/Bazaar.hs
bsd-3-clause
11,898
0
12
2,218
2,882
1,561
1,321
-1
-1