code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE Trustworthy #-} -- | Abstraction layer for network functionality. -- -- The intention is to -- (i) separate the logic of the protocol from its binary encoding, and -- (ii) allow a simulated network in place of actual network IO. module Network.Tox.Network.Networked where import Control.Monad.Random (RandT) import Control.Monad.Reader (ReaderT) import Control.Monad.State (MonadState, StateT) import Control.Monad.Trans.Class (lift) import Control.Monad.Writer (WriterT, execWriterT, runWriterT, tell) import Data.Binary (Binary) import Network.Tox.Network.MonadRandomBytes (MonadRandomBytes) import Network.Tox.NodeInfo.NodeInfo (NodeInfo) import Network.Tox.Protocol.Packet (Packet (..)) import Network.Tox.Timed (Timed) class Monad m => Networked m where sendPacket :: (Binary payload, Show payload) => NodeInfo -> Packet payload -> m () -- | actual network IO instance Networked (StateT NetworkState IO) where -- | TODO sendPacket _ _ = return () -- | TODO: sockets etc type NetworkState = () type NetworkEvent = String newtype NetworkLogged m a = NetworkLogged (WriterT [NetworkEvent] m a) deriving (Monad, Applicative, Functor, MonadState s, MonadRandomBytes, Timed) runNetworkLogged :: Monad m => NetworkLogged m a -> m (a, [NetworkEvent]) runNetworkLogged (NetworkLogged m) = runWriterT m evalNetworkLogged :: (Monad m, Applicative m) => NetworkLogged m a -> m a evalNetworkLogged = (fst <$>) . runNetworkLogged execNetworkLogged :: Monad m => NetworkLogged m a -> m [NetworkEvent] execNetworkLogged (NetworkLogged m) = execWriterT m -- | just log network events instance Monad m => Networked (NetworkLogged m) where sendPacket to packet = NetworkLogged $ tell [">>> " ++ show to ++ " : " ++ show packet] instance Networked m => Networked (ReaderT r m) where sendPacket = (lift .) . sendPacket instance (Monoid w, Networked m) => Networked (WriterT w m) where sendPacket = (lift .) . sendPacket instance Networked m => Networked (RandT s m) where sendPacket = (lift .) . sendPacket instance Networked m => Networked (StateT s m) where sendPacket = (lift .) . sendPacket
iphydf/hs-toxcore
src/Network/Tox/Network/Networked.hs
gpl-3.0
2,566
0
12
680
649
360
289
41
1
module Main where import Carnap.GHCJS.Action.TruthTable main :: IO () main = truthTableAction
gleachkr/Carnap
Carnap-GHCJS/TruthTable/Main.hs
gpl-3.0
96
0
6
14
26
16
10
4
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="zh-CN"> <title>Forced Browse Add-On</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>搜索</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/bruteforce/src/main/javahelp/org/zaproxy/zap/extension/bruteforce/resources/help_zh_CN/helpset_zh_CN.hs
apache-2.0
966
81
66
158
413
209
204
-1
-1
{-# LANGUAGE FlexibleInstances #-} module BlockRamTest where import CLaSH.Prelude topEntity :: Signal (Unsigned 7) -> Signal (Unsigned 7) -> Signal (Bool) -> Signal (Vec 4 Bit) -> Signal (Vec 4 Bit) topEntity = blockRam (replicate d128 (repeat high))
christiaanb/clash-compiler
tests/shouldwork/Signal/BlockRamTest.hs
bsd-2-clause
293
0
11
80
99
50
49
-1
-1
{-# LANGUAGE CPP #-} import Text.LaTeX import Text.LaTeX.Base.Parser import Test.Tasty import qualified Test.Tasty.QuickCheck as QC #if !MIN_VERSION_parsec(3,1,9) instance Eq ParseError where _ == _ = undefined #endif main :: IO () main = defaultMain $ testGroup "HaTeX" [ testGroup "LaTeX" [ QC.testProperty "LaTeX mempty" $ \l -> (mempty <> l) == (l <> mempty) && (mempty <> l) == (l :: LaTeX) , QC.testProperty "LaTeX mappend" $ \l1 l2 l3 -> l1 <> (l2 <> l3) == (l1 <> l2) <> (l3 :: LaTeX) ] , testGroup "Parser" [ QC.testProperty "render . parse = id" $ \l -> let t = render (l :: LaTeX) in fmap render (parseLaTeX t) == Right t ] ]
dmcclean/HaTeX
test/Main.hs
bsd-3-clause
724
0
17
202
253
137
116
19
1
{-# LANGUAGE TemplateHaskell #-} module Annotations where {-# ANN module (1 :: Int) #-} {-# ANN module (1 :: Integer) #-} {-# ANN module (1 :: Double) #-} {-# ANN module $([| 1 :: Int |]) #-} {-# ANN module "Hello" #-} {-# ANN module (Just (1 :: Int)) #-} {-# ANN module [1 :: Int, 2, 3] #-} {-# ANN module ([1..10] :: [Integer]) #-} {-# ANN module ''Foo #-} {-# ANN module (-1 :: Int) #-} {-# ANN type Foo (1 :: Int) #-} {-# ANN type Foo (1 :: Integer) #-} {-# ANN type Foo (1 :: Double) #-} {-# ANN type Foo $([| 1 :: Int |]) #-} {-# ANN type Foo "Hello" #-} {-# ANN type Foo (Just (1 :: Int)) #-} {-# ANN type Foo [1 :: Int, 2, 3] #-} {-# ANN type Foo ([1..10] :: [Integer]) #-} {-# ANN type Foo ''Foo #-} {-# ANN type Foo (-1 :: Int) #-} data Foo = Bar Int {-# ANN f (1 :: Int) #-} {-# ANN f (1 :: Integer) #-} {-# ANN f (1 :: Double) #-} {-# ANN f $([| 1 :: Int |]) #-} {-# ANN f "Hello" #-} {-# ANN f (Just (1 :: Int)) #-} {-# ANN f [1 :: Int, 2, 3] #-} {-# ANN f ([1..10] :: [Integer]) #-} {-# ANN f 'f #-} {-# ANN f (-1 :: Int) #-} f x = x {-# ANN foo "HLint: ignore" #-};foo = map f (map g x)
mpickering/ghc-exactprint
tests/examples/ghc710/Annotations.hs
bsd-3-clause
1,107
1
7
256
73
54
19
35
1
-- -- Copyright © 2013-2015 Anchor Systems, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of -- the 3-clause BSD licence. -- -- | Description: Check and fix style differences with stylish-haskell module Main where import Control.Monad import Data.Algorithm.Diff import Data.Algorithm.DiffOutput import Data.Foldable import Data.List hiding (and) import Data.Monoid hiding (First) import Data.Traversable import Git.Vogue.PluginCommon import Language.Haskell.Stylish import Prelude hiding (and) import System.Exit import System.IO hiding (hGetContents) import System.IO.Strict (hGetContents) main :: IO () main = do cmd <- getPluginCommand "Check your Haskell project for stylish-haskell-related problems." "git-vogue-stylish - check for stylish-haskell problems" cfg <- getConfig f cfg cmd where hsFiles = filter (isSuffixOf ".hs") f _ CmdName = putStrLn "stylish" f cfg (CmdCheck check_fs_list _) = do files <- read <$> readFile check_fs_list rs <- traverse (stylishCheckFile cfg) (hsFiles files) if and rs then do outputGood $ "Checked " <> show (length rs) <> " file(s)" exitSuccess else exitFailure f cfg (CmdFix check_fs_list _) = do files <- read <$> readFile check_fs_list let files' = hsFiles files -- Fix all of the things first traverse_ (stylishRunFile cfg) files' -- Now double check they are fixed rs <- traverse (stylishCheckFile cfg) files' if and rs then outputGood "Style converged" else do outputBad "Style did not converge, bailing" exitFailure -- | Try various configuration locations as per stylish-haskell binary getConfig :: IO Config getConfig = -- Don't spew every file checked to stdout let v = makeVerbose False in do config <- configFilePath v Nothing loadConfig v config -- | Checks whether running Stylish over a given file produces any differences. -- Returns TRUE if there's nothing left to change. -- Prints results and returns FALSE if there are things left to change. stylishCheckFile :: Config -- ^ Stylish Haskell config -> FilePath -- ^ File to run through Stylish -> IO Bool stylishCheckFile cfg fp = stylishFile fp cfg (\original stylish -> case getStyleDiffs original stylish of [] -> return True x -> do outputBad $ "\x1b[33m" <> fp <> "\x1b[0m" <> " has differing style:\n" <> ppDiff x return False ) -- | Runs Stylish over a given file. If there are changes, write them. stylishRunFile :: Config -- ^ Stylish Haskell config -> FilePath -- ^ File to run through Stylish -> IO () stylishRunFile cfg fp = stylishFile fp cfg $ \original stylish -> unless (null $ getStyleDiffs original stylish) (writeFile fp stylish) -- | Get diffs and filter out equivalent ones getStyleDiffs :: String -> String -> [Diff [String]] getStyleDiffs original stylish = filter filterDiff $ getGroupedDiff (lines original) (lines stylish) -- | Filters out equal diffs filterDiff :: (Eq a) => Diff a -> Bool filterDiff (Both a b) = a /= b filterDiff _ = True -- | Takes an original file, the Stylish version of the file, and does something -- depending on the outcome of the Stylish transformation. stylishFile :: FilePath -- ^ File to run through Stylish -> Config -- ^ Stylish Haskell config -> (String -> String -> IO a) -> IO a stylishFile fp cfg fn = do original <- readUTF8File fp stylish <- stylishFile' (Just fp) cfg fn original stylish -- | Processes a single file, or stdin if no filepath is given stylishFile' :: Maybe FilePath -- ^ File to run through Stylish -> Config -- ^ Stylish Haskell config -> IO String stylishFile' mfp conf = do contents <- maybe getContents readUTF8File mfp let result = runSteps (configLanguageExtensions conf) mfp (configSteps conf) $ lines contents case result of Left err -> do hPutStrLn stderr err return contents Right ok -> return $ unlines ok -- | Loads a UTF8 file. readUTF8File :: FilePath -- ^ Filepath to read -> IO String -- ^ File data readUTF8File fp = withFile fp ReadMode $ \h -> do hSetEncoding h utf8 hGetContents h
anchor/git-vogue
src/git-vogue-stylish.hs
bsd-3-clause
4,850
0
17
1,463
980
492
488
106
5
{-# LANGUAGE QuasiQuotes,OverlappingInstances #-} import Control.Monad import Criterion.Types import Criterion.Measurement import HLearn.Algebra hiding (Product) import HLearn.Evaluation.RSquared import HLearn.Models.Classifiers.Common hiding (Regression(..)) import HLearn.Models.Regression import HLearn.Models.Regression.Parsing fib :: Double->Double fib 1 = 1 fib 2 = 1 fib n = fib (n-1) + fib (n-2) main = do -- let runtimeL = [1.1,2.3,3.1,4.1,5.8,6.8] let inputL = concat $ replicate 1 [1..35] runtimeL <- sequence $ map (\x -> time_ $ run (nf fib x) 1) inputL let dataset = zip runtimeL inputL let model = train dataset :: Product '[ Regression (Just Linear) (Just [expr| 1+x |]) (Double,Double) , Regression (Just Linear) (Just [expr| 1+x^2 |]) (Double,Double) , Regression (Just Linear) (Just [expr| 1+x^3 |]) (Double,Double) , Regression (Just Linear) (Just [expr| 1+x^4 |]) (Double,Double) , Regression (Just Linear) (Just [expr| 1+log x |]) (Double,Double) , Regression (Just Linear) (Just [expr| 1+(log x)*x |]) (Double,Double) , Regression (Just Linear) (Just [expr| 1+2^x |]) (Double,Double) , Regression (Just Linear) (Just [expr| 1+(1/2)^x |]) (Double,Double) , Regression (Just Linear) (Just [expr| 1+x^x |]) (Double,Double) ] sequence_ $ hlist2list $ hmap (RunTest dataset) $ unProduct model putStrLn "done" type ProblemGen a = Int -> a intMaker :: ProblemGen Int intMaker = id data RunTest = RunTest [(Double,Double)] instance ( Floating (Label (Datapoint m)) , Show (Label (Datapoint m)) , Show m , NumDP m , Classifier m , Ring m ~ Label (Datapoint m) , Datapoint m ~ (Double,Double) ) => Function RunTest m (IO ()) where function (RunTest xs) m = do let r = rsquared m xs let str = show m putStrLn $ str ++ replicate (50-length str) ' ' ++ "R^2 = " ++ show r runtest m xs = do let r = rsquared m xs let str = show m putStrLn $ str ++ replicate (50 - length str) ' ' ++ "R^2 = " ++ show r instance HasRing Double where type Ring Double = Double ------------------------------------------------------------------------------- instance HomTrainer (HList '[]) where type Datapoint (HList '[]) = () train1dp _ = HNil instance ( HomTrainer x , HomTrainer (HList xs) , HCons (Datapoint x) (Datapoint (HList xs)) ~ HList ( t ': ts) , t ~ Datapoint x , HList ts ~ Datapoint (HList xs) ) => HomTrainer (HList (x ': xs)) where type Datapoint (HList (x ': xs)) = Datapoint x `HCons` Datapoint (HList xs) train1dp (x ::: xs) = train1dp x ::: train1dp xs --------------------------------------- newtype Product (xs :: [*]) = Product { unProduct :: HList xs } deriving instance (Show (HList xs)) => Show (Product xs) instance Monoid (Product '[]) where mempty = Product HNil mappend a b = Product HNil instance (Monoid x, Monoid (HList xs)) => Monoid (Product (x ': xs)) where mempty = Product $ mempty:::mempty mappend (Product (a:::as)) (Product (b:::bs)) = Product $ a<>b ::: as<>bs instance ( HomTrainer (Product xs) , Monoid (HList xs) , HomTrainer x , Datapoint x ~ Datapoint (Product xs) ) => HomTrainer (Product (x ': xs)) where type Datapoint (Product (x ': xs)) = Datapoint x train1dp x = Product $ train1dp x ::: (unProduct $ (train1dp x :: Product xs)) instance ( HomTrainer x ) => HomTrainer (Product '[x]) where type Datapoint (Product '[x]) = Datapoint x train1dp dp = Product $ train1dp dp ::: HNil instance HMap f (HList xs) (HList ys) => HMap f (Product xs) (Product ys) where hmap f (Product xs) = Product $ hmap f xs
iamkingmaker/HLearn
examples/old/runtimes/runtimes.hs
bsd-3-clause
3,838
0
15
960
1,592
834
758
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Docker where
dataember/docker-client
src/Docker.hs
bsd-3-clause
56
0
2
8
5
4
1
2
0
module Fib where -- | Calculate Fibonacci number of given 'Num'. -- -- First let's set `n` to ten: -- -- >>> let n = 10 -- -- And now calculate the 10th Fibonacci number: -- -- >>> fib n -- 55 -- -- >>> let x = 10 -- >>> x -- 10 fib :: Integer -> Integer fib 0 = 0 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2)
snoyberg/doctest-haskell
test/integration/testCombinedExample/Fib.hs
mit
310
0
8
80
75
46
29
5
1
module CodeGen ( genModuleBody, genTodoItems, makeKnownSymbolsMap ) where import Module (Module(..), Decl(..), DeclBody(..), isAttr) import qualified Api import qualified HaddockDocs (Span(..), formatParasFragment, formatSections, formatParas, formatSpans, haddockSection) import HaddockDocs (Span(..)) import Marshal (CSymbol(..), ParameterKind(..), EnumKind(..), KnownSymbols, genMarshalParameter, genMarshalResult, genMarshalOutParameter, genCall, genMarshalProperty, convertSignalType) import Names (cParamNameToHsName, cFuncNameToHsName, hsTypeNameToCGetType) import Utils import MarshalFixup (maybeNullParameter, maybeNullResult, leafClass, nukeParameterDocumentation) import Prelude hiding (Enum, lines) import Data.List (groupBy, sortBy, partition, intersperse) import Data.Maybe (fromMaybe, catMaybes, isNothing) import qualified Data.Map as Map import Data.Map (Map) import Data.Version import Numeric (showHex) import Data.List (foldl') import Data.Word (Word16) import Data.Char (ord) ------------------------------------------------------------------------------- -- More doc formatting utils ------------------------------------------------------------------------------- deprecated name comment = pragma $ text "DEPRECATED" <+> name <+> doubleQuotes comment pragma d = text "{-#" <+> d <+> text "#-}" c2hsHook name d = text "{#" <+> text name <+> d <+> text "#}" tuple [] = empty tuple [x] = x tuple xs = parens (hsep $ punctuate comma xs) tuple' xs = parens (hsep $ punctuate comma xs) ------------------------------------------------------------------------------- -- Now lets actually generate some code fragments based on the api info ------------------------------------------------------------------------------- genDecl :: KnownSymbols -> Decl -> Doc genDecl knownSymbols decl = --TODO: re-enable hashes and make it work reliably {- hashes $$-} formattedDocs $$ formattedCode $$ deprecatedNote where generatedDocs = case decl_doc decl of Nothing -> empty Just [] -> comment <+> char '|' $$ comment Just doc -> HaddockDocs.formatParas 77 doc $$ comment handWrittenDocs = vcat (map text $ decl_user_docs decl) generatedDocsHash = hash generatedDocs handWrittenDocsHash = hash handWrittenDocs formattedDocs | decl_user_docs_hash decl == generatedDocsHash = handWrittenDocs | otherwise = generatedDocs generatedCode = genDeclCode knownSymbols decl handWrittenCode = vcat (map text $ decl_user_code decl) generatedCodeHash = hash generatedCode handWrittenCodeHash = hash handWrittenCode formattedCode | decl_user_code_hash decl == generatedCodeHash = handWrittenCode | otherwise = generatedCode dhash | generatedDocsHash == handWrittenDocsHash = empty | otherwise = text "d:" <> text generatedDocsHash chash | generatedCodeHash == handWrittenCodeHash = empty | otherwise = text "c:" <> text generatedCodeHash hashes | isEmpty chash && isEmpty dhash = empty | otherwise = comment <+> text "%hash" <+> chash <+> dhash -- $$ comment <+> text "%hash" <+> text "c:" <> text (decl_user_code_hash decl) -- <+> text "d:" <> text (decl_user_docs_hash decl) hash :: Doc -> String hash = ($[]) . showHex . foldl' (\h c -> h * 33 + (fromIntegral (ord c))) (5381 :: Word16) . render deprecatedNote | decl_deprecated decl = deprecated (text $ decl_name decl) (text $ decl_deprecated_comment decl) | otherwise = empty genDeclCode :: KnownSymbols -> Decl -> Doc genDeclCode knownSymbols Decl{ decl_body = method@(Method {}) } = text functionName <+> text "::" <+> classContext <+> firstLineParamsType $$ nest 1 multiLineParamsType $$ text functionName <+> formattedParamNames <+> equals $$ nest 2 codebody where functionName = cFuncNameToHsName (method_cname method) (classConstraints, paramTypes', paramMarshalers) = unzip3 [ case genMarshalParameter knownSymbols (method_cname method) (changeIllegalNames (cParamNameToHsName (Api.parameter_name p))) (Api.parameter_type p) of (c, ty, m) -> (c, (ty, Api.parameter_name p), m) | p <- method_parameters method ] inParamTypes = [ (paramType, lookup name paramDocMap) | (InParam paramType, name) <- paramTypes' ] inParamNames = [ changeIllegalNames (cParamNameToHsName (Api.parameter_name p)) | ((InParam _, _), p) <- zip paramTypes' (method_parameters method) ] outParamTypes = [ (paramType, lookup name paramDocMap) | (OutParam paramType, name) <- paramTypes' ] formattedParamNames = hsep $ map text inParamNames (returnType', returnMarshaler) = genMarshalResult knownSymbols (method_cname method) (method_is_constructor method) (method_return_type method) returnType | null outParamTypes = ("IO " ++ returnType', lookup "Returns" paramDocMap) | otherwise = case unzip outParamTypes of (types', docs') -> let types | returnType' == "()" = types' | otherwise = returnType' : types' docs = mergeParamDocs (lookup "Returns" paramDocMap) docs' in (case types of [t] -> "IO " ++ t _ -> "IO (" ++ concat (intersperse ", " types) ++ ")" ,docs) (outParamMarshalersBefore, outParamMarshalersAfter, returnOutParamFragments) = unzip3 [ genMarshalOutParameter outParamType (changeIllegalNames (cParamNameToHsName name)) | (OutParam outParamType, name) <- paramTypes' ] returnOutParams body | null outParamTypes = body | otherwise = body $$ text "return" <+> tuple' returnOutParamFragments codebody = foldl (\body marshaler -> marshaler body) call (paramMarshalers ++ [ (\body -> frag $$ body) | frag <- reverse outParamMarshalersBefore ] ++ [ (\body -> body $$ frag) | frag <- outParamMarshalersAfter ] ++ [returnMarshaler,returnOutParams]) call = genCall (fromMaybe (method_cname method) (method_shortcname method)) (method_is_unsafe_ffi method) docNullsAllFixed = maybeNullResult (method_cname method) || or [ maybeNullParameter (method_cname method) (cParamNameToHsName (Api.parameter_name p)) | p <- method_parameters method ] paramDocMap = [ (name ,(if name == "Returns" then [SpanText "returns "] else [SpanMonospace [SpanText (Names.cParamNameToHsName name)] ,SpanText " - "] ) ++ paragraph) | (name, paragraph) <- method_param_docs method , not $ nukeParameterDocumentation (method_cname method) (cParamNameToHsName name) ] classContext = case catMaybes classConstraints of [] -> empty cs -> tuple (map text cs) <+> text "=>" (firstLineParams, multiLineParams) = span (isNothing.snd) (inParamTypes ++ [returnType]) firstLineParamsType :: Doc firstLineParamsType = hsep . intersperse (text "->") . map (text.fst) $ firstLineParams multiLineParamsType :: Doc multiLineParamsType = vcat . (\lines -> case lines of [] -> [] (l:ls) | null firstLineParams -> nest 3 l : map (text "->" <+>) ls | otherwise -> map (text "->" <+>) lines) . map (\(type_, doc) -> case doc of Nothing -> text type_ Just doc -> text type_ <> text (replicate (columnIndent - length type_) ' ') <+> HaddockDocs.haddockSection (char '^') (HaddockDocs.formatSpans 3 (80 - columnIndent - 8) doc)) $ multiLineParams columnIndent = maximum [ length parmType | (parmType, Just _) <- multiLineParams ] genDeclCode knownSymbols decl@(Decl{ decl_body = attr@(AttributeProp { attribute_is_child = False }) }) = genAtter decl propertyName classConstraint getterType setterType False (Right body) where propertyName = decl_name decl (propertyType, gvalueKind, needsGetTypeCCall) = genMarshalProperty knownSymbols (attribute_type attr) body = text attrType <> text "AttrFrom" <> text gvalueKind <> text "Property" <+> doubleQuotes (text (attribute_cname attr)) $$ if needsGetTypeCCall then let attrType = attribute_type attr ccall_name = text (hsTypeNameToCGetType attrType) in nest 2 $ c2hsHook "call pure unsafe" ccall_name else empty where attrType | not (attribute_constructonly attr) && attribute_readable attr && attribute_writeable attr = "new" | attribute_readable attr = "read" | attribute_writeable attr = "write" getterType | attribute_readable attr = Just propertyType | otherwise = Nothing (setterType, classConstraint) | attribute_writeable attr && gvalueKind == "Object" && not (attribute_constructonly attr) = if leafClass (attribute_type attr) then (Just propertyType, Nothing) else let typeVar = lowerCaseFirstWord propertyType classConstraint' = propertyType ++ "Class " ++ typeVar in (Just typeVar, Just classConstraint') | not (attribute_constructonly attr) && attribute_writeable attr = (Just propertyType, Nothing) | otherwise = (Nothing, Nothing) genDeclCode knownSymbols decl@(Decl{ decl_body = attr@(AttributeProp { attribute_is_child = True }) }) = genAtter decl propertyName classConstraint getterType setterType True (Right body) where propertyName = decl_name decl (propertyType, gvalueKind, needsGetTypeCCall) = genMarshalProperty knownSymbols (attribute_type attr) body = text attrType <> text "AttrFromContainerChild" <> text gvalueKind <> text "Property" <+> doubleQuotes (text (attribute_cname attr)) $$ if needsGetTypeCCall then let attrType = attribute_type attr ccall_name = text (hsTypeNameToCGetType attrType) in nest 2 $ c2hsHook "call pure unsafe" ccall_name else empty where attrType | not (attribute_constructonly attr) && attribute_readable attr && attribute_writeable attr = "new" | attribute_readable attr = "read" | attribute_writeable attr = "write" getterType | attribute_readable attr = Just propertyType | otherwise = Nothing (setterType, classConstraint) | attribute_writeable attr && gvalueKind == "Object" && not (attribute_constructonly attr) = if leafClass (attribute_type attr) then (Just propertyType, Nothing) else let typeVar = lowerCaseFirstWord propertyType classConstraint' = propertyType ++ "Class " ++ typeVar ++ ", WidgetClass child" in (Just typeVar, Just classConstraint') | not (attribute_constructonly attr) && attribute_writeable attr = (Just propertyType, Just "WidgetClass child") | otherwise = (Nothing, Just "WidgetClass child") genDeclCode knownSymbols decl@(Decl{ decl_body = attr@(AttributeGetSet {}) }) = genAtter decl propertyName classConstraint (Just getterType) (Just setterType) False (Left (text (decl_name getter), text (decl_name setter))) where propertyName = decl_name decl (getterType, _) = genMarshalResult knownSymbols (method_cname getter_body) False (method_return_type getter_body) (classConstraint, setterType) = case let param = method_parameters setter_body !! 1 paramName = changeIllegalNames (cParamNameToHsName (Api.parameter_name param)) paramType = Api.parameter_type param in genMarshalParameter knownSymbols (method_cname setter_body) paramName paramType of (classConstraint', InParam setterType', _) -> (classConstraint', setterType') (_, OutParam _, _) -> (Nothing, "{- FIXME: should be in param -}") getter@Decl { decl_body = getter_body } = attribute_getter attr setter@Decl { decl_body = setter_body } = attribute_setter attr genDeclCode knownSymbols Decl{ decl_module = module_, decl_name = signalName, decl_body = signal@Module.Signal {} } | signal_is_old_style signal = text signalName <+> text "::" <+> oldSignalType $$ text signalName <+> equals <+> text "connect_" <> connectCall <+> signalCName <+> text (show $ signal_is_after signal) | otherwise = text (lowerCaseFirstWord signalName) <+> text "::" <+> signalType $$ text (lowerCaseFirstWord signalName) <+> equals <+> text "Signal" <+> parens (text "connect_" <> connectCall <+> signalCName) where connectCall = let paramCategories' = if null paramCategories then [text "NONE"] else map text paramCategories in hcat (punctuate (char '_') paramCategories') <> text "__" <> text returnCategory -- strip off the object arg to the signal handler params = case Module.signal_parameters signal of (param:params') | Api.parameter_type param == (module_cname module_) ++ "*" -> params' params' -> params' (paramCategories, paramTypes) = unzip [ convertSignalType knownSymbols (Api.parameter_type parameter) | parameter <- params ] (returnCategory, returnType) = convertSignalType knownSymbols (Module.signal_return_type signal) signalType = text (module_name module_) <> text "Class self => Signal self" <+> callbackType True oldSignalType = text (module_name module_) <> text "Class self => self" $$ nest nestLevel (text "->" <+> callbackType False $$ text "->" <+> text "IO (ConnectId self)") where nestLevel = -(length signalName + 3) callbackType needsParens | null paramTypes = (if needsParens then parens else id) (text "IO" <+> text returnType) | otherwise = parens (hsep . intersperse (text "->") . map text $ (paramTypes ++ ["IO " ++ returnType])) signalCName = doubleQuotes (text $ Module.signal_cname signal) genDeclCode _ Decl { decl_body = Instance { instance_class_name = className, instance_type_name = typeName }} = text "instance" <+> text className <+> text typeName mergeParamDocs :: Maybe [Span] -> [Maybe [Span]] -> Maybe [Span] mergeParamDocs doc docs = case catMaybes (doc:docs) of [] -> Nothing [doc'] -> Just doc' docs' -> let (varNames, paramDocs) = unzip [ case doc' of (SpanMonospace [SpanText varName] : _) -> (cParamNameToHsName varName, doc') _ -> ("_", doc') | doc' <- docs' ] returnValName = SpanMonospace [SpanText $ "(" ++ concat (intersperse ", " varNames) ++ ")"] fixmeMessage = SpanText " {FIXME: merge return value docs} " in Just $ returnValName : fixmeMessage : concat paramDocs changeIllegalNames :: String -> String changeIllegalNames "type" = "type_" --these are common variable names in C but changeIllegalNames "where" = "where_" --of course are keywords in Haskell changeIllegalNames "data" = "data_" changeIllegalNames other = other genModuleBody :: KnownSymbols -> Module -> Doc genModuleBody knownTypes module_ = summary $$ comment $$ (if Module.module_deprecated module_ then text "module" <+> moduleName $$ deprecatedNote <+> lparen else text "module" <+> moduleName <+> lparen) $+$ documentation $+$ exports $$ nest 2 (rparen <+> text "where") $+$ imports $+$ (if module_needs_c2hs module_ then context else empty) $+$ decls where summary = HaddockDocs.formatParasFragment (module_summary module_) moduleName | isEmpty prefix = name | otherwise = prefix <> char '.' <> name where name = text (Module.module_name module_) prefix = text (Module.module_prefix module_) deprecatedNote | Module.module_deprecated module_ = deprecated empty (text "this module should not be used in newly-written code.") | otherwise = empty documentation = HaddockDocs.formatSections (module_description module_) exports = genExports module_ imports = genImports module_ context = c2hsHook "context" $ text "lib" <> equals <> doubleQuotes (text $ module_context_lib module_) <+> text "prefix" <> equals <> doubleQuotes (text $ module_context_prefix module_) decls = genDecls knownTypes module_ genDecls :: KnownSymbols -> Module -> Doc genDecls knownSymbols module_ = doVersionIfDefs vsep . map adjustDeprecatedAndSinceVersion $ sectionHeader "Interfaces" [ (genDecl knownSymbols decl, (since, deprecated)) | decl@Decl { decl_since = since, decl_deprecated = deprecated, decl_body = Instance { } } <- module_decls module_ ] ++ sectionHeader "Constructors" [ (genDecl knownSymbols decl, (since, deprecated)) | decl@Decl { decl_since = since, decl_deprecated = deprecated, decl_body = Method { method_is_constructor = True } } <- module_decls module_ ] ++ sectionHeader "Methods" [ (genDecl knownSymbols decl, (since, deprecated)) | decl@Decl { decl_since = since, decl_deprecated = deprecated, decl_body = Method { method_is_constructor = False } } <- module_decls module_ ] ++ sectionHeader "Attributes" [ (genDecl knownSymbols decl, (since, deprecated)) | decl@Decl { decl_since = since, decl_deprecated = deprecated } <- module_decls module_, isAttr decl ] ++ sectionHeader "Child Attributes" [ (genDecl knownSymbols decl, (since, deprecated)) | decl@Decl { decl_since = since, decl_deprecated = deprecated, decl_body = AttributeProp { attribute_is_child = True } } <- module_decls module_ ] ++ sectionHeader "Signals" [ (genDecl knownSymbols decl, (since, deprecated)) | decl@Decl { decl_since = since, decl_deprecated = deprecated@False, decl_body = Module.Signal {} } <- module_decls module_ ] ++ sectionHeader "Deprecated Signals" [ (genDecl knownSymbols decl, (since, deprecated)) | decl@Decl { decl_since = since, decl_deprecated = deprecated@True, decl_body = Module.Signal {} } <- module_decls module_ ] where sectionHeader _ [] = [] sectionHeader name entries = let header = (text "--------------------" $$ comment <+> text name, (Nothing, False)) in header : entries adjustDeprecatedAndSinceVersion (doc, (since, deprecated)) = (doc, (module_since module_ `max` since, Module.module_deprecated module_ || deprecated)) genAtter :: Decl -> String -> Maybe String -> Maybe String -> Maybe String -> Bool -> Either (Doc, Doc) Doc -> Doc genAtter Decl { decl_module = module_ } propertyName classConstraint getterType setterType isChild attrImpl = text propertyName <+> text "::" <+> classContext <+> child <+> attrType <+> objectParamType <+> attrArgs $$ text propertyName <+> equals <+> body $$ nest 2 body' where objectType = text (module_name module_) objectParamType | leafClass (module_cname module_) = objectType | otherwise = text "self" classContext = case (leafClass (module_cname module_), classConstraint) of (True, Nothing) -> empty (False, Nothing) -> objectType <> text "Class self =>" (True, Just classConstraint') -> text classConstraint' <+> text "=>" (False, Just classConstraint') -> parens (objectType <> text "Class self" <> comma <+> text classConstraint') <+> text "=>" (attrType, attrConstructor, attrArgs) = case (getterType, setterType) of (Just gt, Nothing) -> (text "ReadAttr", text "readAttr", text gt) (Nothing, Just st) -> (text "WriteAttr", text "writeAttr", text st) (Just gt, Just st) | gt == st -> (text "Attr", text "newAttr", text gt) | length (words st) > 1 -> (text "ReadWriteAttr", text "newAttr", text gt <+> parens (text st)) | otherwise -> (text "ReadWriteAttr", text "newAttr", text gt <+> text st) _ -> error $ "no getter or setter for " ++ module_name module_ ++ " :: " ++ propertyName child | isChild = text "child" <+> text "->" | otherwise = empty body = case attrImpl of Left _ -> attrConstructor Right b -> b body' = case attrImpl of Left (getter, setter) -> case (getterType, setterType) of (Just _, Nothing) -> getter (Nothing, Just _) -> setter (Just _, Just _) -> getter $$ setter Right _ -> empty makeKnownSymbolsMap :: Api.API -> KnownSymbols makeKnownSymbolsMap api = (Map.fromListWith (\a b -> b) . concat) [ [ (Api.enum_cname enum ,case Api.enum_variety enum of Api.EnumVariety -> SymEnumType EnumKind Api.FlagsVariety -> SymEnumType FlagsKind) | enum <- Api.namespace_enums namespace ] ++ [ (Api.object_cname object, objectKind object) | object <- Api.namespace_objects namespace ] ++ [ (Api.class_cname class_, SymClassType) | class_ <- Api.namespace_classes namespace ] ++ [ (Api.boxed_cname boxed, SymBoxedType) | boxed <- Api.namespace_boxed namespace ] ++ [ (Api.member_cname member, SymEnumValue) | enum <- Api.namespace_enums namespace , member <- Api.enum_members enum ] ++ [ (Api.misc_cname misc, miscToCSymbol misc ) | misc <- Api.namespace_misc namespace ] | namespace <- api ] -- find if an object inherits via GtkObject or directly from GObject where objectKind :: Api.Object -> CSymbol objectKind object | "GObject" `elem` parents || "GInitiallyUnowned" `elem` parents = SymObjectType parents | Api.object_parent object == "GTypeInstance" = SymStructType -- FIXME: These hacks should go elsewhere | otherwise = SymObjectType [Api.object_cname object, "GObject"] where parents = objectParents object objectParents :: Api.Object -> [String] objectParents object = Api.object_cname object : case Api.object_parent object `Map.lookup` objectMap of Nothing -> [Api.object_parent object] Just parent -> objectParents parent objectMap :: Map String Api.Object objectMap = Map.fromList [ (Api.object_cname object, object) | namespace <- api , object <- Api.namespace_objects namespace ] miscToCSymbol (Api.Struct _ _) = SymStructType miscToCSymbol (Api.Alias _ _) = SymTypeAlias miscToCSymbol (Api.Callback _ _) = SymCallbackType genExports :: Module -> Doc genExports module_ = doVersionIfDefs vcat . map adjustDeprecatedAndSinceVersion $ sectionHeader False "Types" [(text (Module.module_name module_), defaultAttrs) ,(text (Module.module_name module_) <> text "Class", defaultAttrs) ,(text "castTo" <> text (Module.module_name module_), defaultAttrs) ,(text "to" <> text (Module.module_name module_), defaultAttrs)] ++ sectionHeader True "Constructors" [ (text name, (since, False)) | Decl { decl_name = name, decl_since = since, decl_deprecated = False, decl_body = Method { method_is_constructor = True } } <- exports ] ++ sectionHeader True "Methods" [ (text name, (since, False)) | Decl { decl_name = name, decl_since = since, decl_deprecated = False, decl_body = Method { method_is_constructor = False } } <- exports ] ++ sectionHeader True "Attributes" [ (text name, (since, False)) | decl@Decl { decl_since = since, decl_deprecated = False, decl_name = name } <- module_decls module_ , isAttr decl ] ++ sectionHeader True "Child Attributes" [ (text name, (since, False)) | Decl { decl_name = name, decl_since = since, decl_deprecated = False, decl_body = AttributeProp { attribute_is_child = True } } <- module_decls module_ ] ++ sectionHeader True "Signals" [ (text name, (since, False)) | Decl { decl_name = name, decl_since = since, decl_deprecated = False, decl_body = Module.Signal { signal_is_old_style = False } } <- exports ] ++ sectionHeader True "Deprecated" [ (text name, (since, True)) | Decl { decl_name = name, decl_since = since, decl_deprecated = True } <- exports ] where defaultAttrs = (Nothing, False) sectionHeader _ _ [] = [] sectionHeader False name entries = (text "-- * " <> text name, defaultAttrs) : map (\(doc, attrs) -> (nest 2 (doc <> comma), attrs)) entries sectionHeader True name entries = (emptyLine, defaultAttrs) : (text "-- * " <> text name, defaultAttrs) : map (\(doc, attrs) -> (nest 2 (doc <> comma), attrs)) entries adjustDeprecatedAndSinceVersion (doc, (since, deprecated)) = (doc, (Module.module_since module_ `max` since, Module.module_deprecated module_ || deprecated)) exports = sortBy (comparing decl_index_export) (module_decls module_) genImports :: Module -> Doc genImports module_ = (case [ text importLine | (_, importLine) <- stdModules ] of [] -> empty mods -> vcat mods) $+$ vcat [ text importLine | (_, importLine) <- extraModules ] where (stdModules, extraModules) | null (Module.module_imports module_) = ([(undefined, "import Control.Monad\t(liftM)")] ,[(undefined, "import System.Glib.FFI") ,(undefined, "{#import Graphics.UI.Gtk.Types#}") ,(undefined, "-- CHECKME: extra imports may be required")]) | otherwise = partition (\(m, _) -> m `elem` knownStdModules) (Module.module_imports module_) knownStdModules = ["Maybe", "Monad", "Char", "List", "Data.IORef"] genTodoItems :: Module -> Doc genTodoItems Module { module_todos = varargsFunctions } | null varargsFunctions = empty | otherwise = comment <+> text "TODO: the following varargs functions were not bound" $$ (commentBlock . map ((text " " <>) . text)) varargsFunctions $$ comment type Deprecated = Bool type Since = Maybe Version doVersionIfDefs :: ([Doc] -> Doc) -> [(Doc, (Since, Deprecated))] -> Doc doVersionIfDefs sep = sep . layoutChunks True empty . makeChunks [Nothing] False . map (\group@((_,(since, deprecated)):_) -> (map fst group, since, deprecated)) . groupBy (equating snd) where makeChunks :: [Since] -> Deprecated -> [([Doc], Since, Deprecated)] -> [Chunk] makeChunks sinceStack True [] = EndChunk : makeChunks sinceStack False [] makeChunks (_:[]) _ [] = [] makeChunks (_:sinceStack) _ [] = EndChunk : makeChunks sinceStack False [] makeChunks sinceStack@(sinceContext:_) prevDeprecated whole@((group, since, deprecated):rest) | deprecated < prevDeprecated = EndChunk : makeChunks sinceStack deprecated whole | since < sinceContext = EndChunk : makeChunks (tail sinceStack) prevDeprecated whole | deprecated > prevDeprecated = BeginDeprecatedChunk : makeChunks sinceStack deprecated whole | since > sinceContext = BeginSinceChunk since : makeChunks (since:sinceStack) prevDeprecated whole | otherwise = SimpleChunk group : makeChunks sinceStack prevDeprecated rest layoutChunks :: Bool -> Doc -> [Chunk] -> [Doc] layoutChunks _ doc [] = doc : [] layoutChunks _ doc (EndChunk :chunks) = layoutChunks False (doc $$ endif) chunks layoutChunks False doc (SimpleChunk group :chunks) = doc : layoutChunks False (sep group) chunks layoutChunks True doc (SimpleChunk group :chunks) = layoutChunks False (doc $$ sep group) chunks layoutChunks _ doc (BeginDeprecatedChunk :chunks) = doc : layoutChunks True ifndefDeprecated chunks layoutChunks _ doc (BeginSinceChunk since :chunks) = doc : layoutChunks True (ifSinceVersion since) chunks ifSinceVersion (Just Version { versionBranch = [major,minor] }) = text "#if GTK_CHECK_VERSION(" <> int major <> comma <> int minor <> text ",0)" ifndefDeprecated = text "#ifndef DISABLE_DEPRECATED" endif = text "#endif" data Chunk = SimpleChunk [Doc] | BeginDeprecatedChunk | BeginSinceChunk Since | EndChunk
k0001/gtk2hs
tools/apiGen/src/CodeGen.hs
gpl-3.0
31,961
0
22
10,374
8,494
4,378
4,116
575
14
module Year ( Year , toYear , fromYear ) where import BasicPrelude ( Integer , Show , error , otherwise , (<) , (>) ) import Data.Aeson ( ToJSON ) import GHC.Generics ( Generic ) import Text.InterpolatedString.Perl6 ( qq ) toYear :: Integer -> Year toYear i | i < 1800 = error [qq| Can't create years before 1800: $i |] | i > 2025 = error [qq| Can't create years after 2025: $i |] | otherwise = MakeYear i fromYear :: Year -> Integer fromYear (MakeYear i) = i newtype Year = MakeYear Integer deriving ( Generic, Show ) instance ToJSON Year
dogweather/nevada-revised-statutes-parser
src/Year.hs
bsd-3-clause
960
0
8
523
188
108
80
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.GHC.IPI641 -- Copyright : (c) The University of Glasgow 2004 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- {- 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 the University 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.GHC.IPI641 ( InstalledPackageInfo, toCurrent, ) where import qualified Distribution.InstalledPackageInfo as Current import qualified Distribution.Package as Current hiding (depends) import Distribution.Text (display) import Distribution.Simple.GHC.IPI642 ( PackageIdentifier, convertPackageId , License, convertLicense, convertModuleName ) -- | This is the InstalledPackageInfo type used by ghc-6.4 and 6.4.1. -- -- It's here purely for the 'Read' instance so that we can read the package -- database used by those ghc versions. It is a little hacky to read the -- package db directly, but we do need the info and until ghc-6.9 there was -- no better method. -- -- In ghc-6.4.2 the format changed a bit. See "Distribution.Simple.GHC.IPI642" -- data InstalledPackageInfo = InstalledPackageInfo { package :: PackageIdentifier, license :: License, copyright :: String, maintainer :: String, author :: String, stability :: String, homepage :: String, pkgUrl :: String, description :: String, category :: String, exposed :: Bool, exposedModules :: [String], hiddenModules :: [String], importDirs :: [FilePath], libraryDirs :: [FilePath], hsLibraries :: [String], extraLibraries :: [String], includeDirs :: [FilePath], includes :: [String], depends :: [PackageIdentifier], hugsOptions :: [String], ccOptions :: [String], ldOptions :: [String], frameworkDirs :: [FilePath], frameworks :: [String], haddockInterfaces :: [FilePath], haddockHTMLs :: [FilePath] } deriving Read mkInstalledPackageId :: Current.PackageIdentifier -> Current.InstalledPackageId mkInstalledPackageId = Current.InstalledPackageId . display toCurrent :: InstalledPackageInfo -> Current.InstalledPackageInfo toCurrent ipi@InstalledPackageInfo{} = Current.InstalledPackageInfo { Current.installedPackageId = mkInstalledPackageId (convertPackageId (package ipi)), Current.sourcePackageId = convertPackageId (package ipi), Current.license = convertLicense (license ipi), Current.copyright = copyright ipi, Current.maintainer = maintainer ipi, Current.author = author ipi, Current.stability = stability ipi, Current.homepage = homepage ipi, Current.pkgUrl = pkgUrl ipi, Current.synopsis = "", Current.description = description ipi, Current.category = category ipi, Current.exposed = exposed ipi, Current.exposedModules = map convertModuleName (exposedModules ipi), Current.hiddenModules = map convertModuleName (hiddenModules ipi), Current.trusted = Current.trusted Current.emptyInstalledPackageInfo, Current.importDirs = importDirs ipi, Current.libraryDirs = libraryDirs ipi, Current.hsLibraries = hsLibraries ipi, Current.extraLibraries = extraLibraries ipi, Current.extraGHCiLibraries = [], Current.includeDirs = includeDirs ipi, Current.includes = includes ipi, Current.depends = map (mkInstalledPackageId.convertPackageId) (depends ipi), Current.hugsOptions = hugsOptions ipi, Current.ccOptions = ccOptions ipi, Current.ldOptions = ldOptions ipi, Current.frameworkDirs = frameworkDirs ipi, Current.frameworks = frameworks ipi, Current.haddockInterfaces = haddockInterfaces ipi, Current.haddockHTMLs = haddockHTMLs ipi }
jwiegley/ghc-release
libraries/Cabal/cabal/Distribution/Simple/GHC/IPI641.hs
gpl-3.0
5,564
0
11
1,354
761
458
303
73
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.InstallPlan -- Copyright : (c) Duncan Coutts 2008 -- License : BSD-like -- -- Maintainer : duncan@community.haskell.org -- Stability : provisional -- Portability : portable -- -- Package installation plan -- ----------------------------------------------------------------------------- module Distribution.Client.InstallPlan ( InstallPlan, ConfiguredPackage(..), PlanPackage(..), -- * Operations on 'InstallPlan's new, toList, ready, processing, completed, failed, remove, showPlanIndex, showInstallPlan, -- ** Query functions planPlatform, planCompiler, -- * Checking validity of plans valid, closed, consistent, acyclic, configuredPackageValid, -- ** Details on invalid plans PlanProblem(..), showPlanProblem, PackageProblem(..), showPackageProblem, problems, configuredPackageProblems, -- ** Querying the install plan dependencyClosure, ) where import Distribution.Client.Types ( SourcePackage(packageDescription), ConfiguredPackage(..) , ReadyPackage(..), readyPackageToConfiguredPackage , InstalledPackage, BuildFailure, BuildSuccess(..), enableStanzas , InstalledPackage(..), fakeInstalledPackageId , ConfiguredId(..) ) import Distribution.Package ( PackageIdentifier(..), PackageName(..), Package(..), packageName , Dependency(..), PackageId, InstalledPackageId , HasInstalledPackageId(..) ) import Distribution.Version ( Version, withinRange ) import Distribution.PackageDescription ( GenericPackageDescription(genPackageFlags) , Flag(flagName), FlagName(..) , SetupBuildInfo(..), setupBuildInfo ) import Distribution.Client.PackageUtils ( externalBuildDepends ) import Distribution.Client.PackageIndex ( PackageFixedDeps(..) ) import Distribution.Client.ComponentDeps (ComponentDeps) import qualified Distribution.Client.ComponentDeps as CD import Distribution.PackageDescription.Configuration ( finalizePackageDescription ) import Distribution.Simple.PackageIndex ( PackageIndex ) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Client.PlanIndex ( FakeMap ) import qualified Distribution.Client.PlanIndex as PlanIndex import Distribution.Text ( display ) import Distribution.System ( Platform ) import Distribution.Compiler ( CompilerInfo(..) ) import Distribution.Client.Utils ( duplicates, duplicatesBy, mergeBy, MergeResult(..) ) import Distribution.Simple.Utils ( comparing, intercalate ) import qualified Distribution.InstalledPackageInfo as Installed import Data.List ( sort, sortBy, nubBy ) import Data.Maybe ( fromMaybe, maybeToList ) import qualified Data.Graph as Graph import Data.Function (on) import Data.Graph (Graph) import Control.Exception ( assert ) import Data.Maybe (catMaybes) import qualified Data.Map as Map import qualified Data.Traversable as T type PlanIndex = PackageIndex PlanPackage -- When cabal tries to install a number of packages, including all their -- dependencies it has a non-trivial problem to solve. -- -- The Problem: -- -- In general we start with a set of installed packages and a set of source -- packages. -- -- Installed packages have fixed dependencies. They have already been built and -- we know exactly what packages they were built against, including their exact -- versions. -- -- Source package have somewhat flexible dependencies. They are specified as -- version ranges, though really they're predicates. To make matters worse they -- have conditional flexible dependencies. Configuration flags can affect which -- packages are required and can place additional constraints on their -- versions. -- -- These two sets of package can and usually do overlap. There can be installed -- packages that are also available as source packages which means they could -- be re-installed if required, though there will also be packages which are -- not available as source and cannot be re-installed. Very often there will be -- extra versions available than are installed. Sometimes we may like to prefer -- installed packages over source ones or perhaps always prefer the latest -- available version whether installed or not. -- -- The goal is to calculate an installation plan that is closed, acyclic and -- consistent and where every configured package is valid. -- -- An installation plan is a set of packages that are going to be used -- together. It will consist of a mixture of installed packages and source -- packages along with their exact version dependencies. An installation plan -- is closed if for every package in the set, all of its dependencies are -- also in the set. It is consistent if for every package in the set, all -- dependencies which target that package have the same version. -- Note that plans do not necessarily compose. You might have a valid plan for -- package A and a valid plan for package B. That does not mean the composition -- is simultaneously valid for A and B. In particular you're most likely to -- have problems with inconsistent dependencies. -- On the other hand it is true that every closed sub plan is valid. -- | Packages in an install plan -- -- NOTE: 'ConfiguredPackage', 'ReadyPackage' and 'PlanPackage' intentionally -- have no 'PackageInstalled' instance. `This is important: PackageInstalled -- returns only library dependencies, but for package that aren't yet installed -- we know many more kinds of dependencies (setup dependencies, exe, test-suite, -- benchmark, ..). Any functions that operate on dependencies in cabal-install -- should consider what to do with these dependencies; if we give a -- 'PackageInstalled' instance it would be too easy to get this wrong (and, -- for instance, call graph traversal functions from Cabal rather than from -- cabal-install). Instead, see 'PackageFixedDeps'. data PlanPackage = PreExisting InstalledPackage | Configured ConfiguredPackage | Processing ReadyPackage | Installed ReadyPackage BuildSuccess | Failed ConfiguredPackage BuildFailure -- ^ NB: packages in the Failed state can be *either* Ready -- or Configured. instance Package PlanPackage where packageId (PreExisting pkg) = packageId pkg packageId (Configured pkg) = packageId pkg packageId (Processing pkg) = packageId pkg packageId (Installed pkg _) = packageId pkg packageId (Failed pkg _) = packageId pkg instance PackageFixedDeps PlanPackage where depends (PreExisting pkg) = depends pkg depends (Configured pkg) = depends pkg depends (Processing pkg) = depends pkg depends (Installed pkg _) = depends pkg depends (Failed pkg _) = depends pkg instance HasInstalledPackageId PlanPackage where installedPackageId (PreExisting pkg) = installedPackageId pkg installedPackageId (Configured pkg) = installedPackageId pkg installedPackageId (Processing pkg) = installedPackageId pkg -- NB: defer to the actual installed package info in this case installedPackageId (Installed _ (BuildOk _ _ (Just ipkg))) = installedPackageId ipkg installedPackageId (Installed pkg _) = installedPackageId pkg installedPackageId (Failed pkg _) = installedPackageId pkg data InstallPlan = InstallPlan { planIndex :: PlanIndex, planFakeMap :: FakeMap, planGraph :: Graph, planGraphRev :: Graph, planPkgOf :: Graph.Vertex -> PlanPackage, planVertexOf :: InstalledPackageId -> Graph.Vertex, planPlatform :: Platform, planCompiler :: CompilerInfo, planIndepGoals :: Bool } invariant :: InstallPlan -> Bool invariant plan = valid (planPlatform plan) (planCompiler plan) (planFakeMap plan) (planIndepGoals plan) (planIndex plan) internalError :: String -> a internalError msg = error $ "InstallPlan: internal error: " ++ msg showPlanIndex :: PlanIndex -> String showPlanIndex index = intercalate "\n" (map showPlanPackage (PackageIndex.allPackages index)) where showPlanPackage p = showPlanPackageTag p ++ " " ++ display (packageId p) ++ " (" ++ display (installedPackageId p) ++ ")" showInstallPlan :: InstallPlan -> String showInstallPlan plan = showPlanIndex (planIndex plan) ++ "\n" ++ "fake map:\n " ++ intercalate "\n " (map showKV (Map.toList (planFakeMap plan))) where showKV (k,v) = display k ++ " -> " ++ display v showPlanPackageTag :: PlanPackage -> String showPlanPackageTag (PreExisting _) = "PreExisting" showPlanPackageTag (Configured _) = "Configured" showPlanPackageTag (Processing _) = "Processing" showPlanPackageTag (Installed _ _) = "Installed" showPlanPackageTag (Failed _ _) = "Failed" -- | Build an installation plan from a valid set of resolved packages. -- new :: Platform -> CompilerInfo -> Bool -> PlanIndex -> Either [PlanProblem] InstallPlan new platform cinfo indepGoals index = -- NB: Need to pre-initialize the fake-map with pre-existing -- packages let isPreExisting (PreExisting _) = True isPreExisting _ = False fakeMap = Map.fromList . map (\p -> (fakeInstalledPackageId (packageId p), installedPackageId p)) . filter isPreExisting $ PackageIndex.allPackages index in case problems platform cinfo fakeMap indepGoals index of [] -> Right InstallPlan { planIndex = index, planFakeMap = fakeMap, planGraph = graph, planGraphRev = Graph.transposeG graph, planPkgOf = vertexToPkgId, planVertexOf = fromMaybe noSuchPkgId . pkgIdToVertex, planPlatform = platform, planCompiler = cinfo, planIndepGoals = indepGoals } where (graph, vertexToPkgId, pkgIdToVertex) = PlanIndex.dependencyGraph fakeMap index noSuchPkgId = internalError "package is not in the graph" probs -> Left probs toList :: InstallPlan -> [PlanPackage] toList = PackageIndex.allPackages . planIndex -- | Remove packages from the install plan. This will result in an -- error if there are remaining packages that depend on any matching -- package. This is primarily useful for obtaining an install plan for -- the dependencies of a package or set of packages without actually -- installing the package itself, as when doing development. -- remove :: (PlanPackage -> Bool) -> InstallPlan -> Either [PlanProblem] InstallPlan remove shouldRemove plan = new (planPlatform plan) (planCompiler plan) (planIndepGoals plan) newIndex where newIndex = PackageIndex.fromList $ filter (not . shouldRemove) (toList plan) -- | The packages that are ready to be installed. That is they are in the -- configured state and have all their dependencies installed already. -- The plan is complete if the result is @[]@. -- ready :: InstallPlan -> [ReadyPackage] ready plan = assert check readyPackages where check = if null readyPackages && null processingPackages then null configuredPackages else True configuredPackages = [ pkg | Configured pkg <- toList plan ] processingPackages = [ pkg | Processing pkg <- toList plan] readyPackages :: [ReadyPackage] readyPackages = [ ReadyPackage srcPkg flags stanzas deps | pkg@(ConfiguredPackage srcPkg flags stanzas _) <- configuredPackages -- select only the package that have all of their deps installed: , deps <- maybeToList (hasAllInstalledDeps pkg) ] hasAllInstalledDeps :: ConfiguredPackage -> Maybe (ComponentDeps [Installed.InstalledPackageInfo]) hasAllInstalledDeps = T.mapM (mapM isInstalledDep) . depends isInstalledDep :: InstalledPackageId -> Maybe Installed.InstalledPackageInfo isInstalledDep pkgid = -- NB: Need to check if the ID has been updated in planFakeMap, in which case we -- might be dealing with an old pointer case PlanIndex.fakeLookupInstalledPackageId (planFakeMap plan) (planIndex plan) pkgid of Just (Configured _) -> Nothing Just (Processing _) -> Nothing Just (Failed _ _) -> internalError depOnFailed Just (PreExisting (InstalledPackage instPkg _)) -> Just instPkg Just (Installed _ (BuildOk _ _ (Just instPkg))) -> Just instPkg Just (Installed _ (BuildOk _ _ Nothing)) -> internalError depOnNonLib Nothing -> internalError incomplete incomplete = "install plan is not closed" depOnFailed = "configured package depends on failed package" depOnNonLib = "configured package depends on a non-library package" -- | Marks packages in the graph as currently processing (e.g. building). -- -- * The package must exist in the graph and be in the configured state. -- processing :: [ReadyPackage] -> InstallPlan -> InstallPlan processing pkgs plan = assert (invariant plan') plan' where plan' = plan { planIndex = PackageIndex.merge (planIndex plan) processingPkgs } processingPkgs = PackageIndex.fromList [Processing pkg | pkg <- pkgs] -- | Marks a package in the graph as completed. Also saves the build result for -- the completed package in the plan. -- -- * The package must exist in the graph and be in the processing state. -- * The package must have had no uninstalled dependent packages. -- completed :: InstalledPackageId -> BuildSuccess -> InstallPlan -> InstallPlan completed pkgid buildResult plan = assert (invariant plan') plan' where plan' = plan { -- NB: installation can change the IPID, so better -- record it in the fake mapping... planFakeMap = insert_fake_mapping buildResult $ planFakeMap plan, planIndex = PackageIndex.insert installed . PackageIndex.deleteInstalledPackageId pkgid $ planIndex plan } -- ...but be sure to use the *old* IPID for the lookup for the -- preexisting record installed = Installed (lookupProcessingPackage plan pkgid) buildResult insert_fake_mapping (BuildOk _ _ (Just ipi)) = Map.insert pkgid (installedPackageId ipi) insert_fake_mapping _ = id -- | Marks a package in the graph as having failed. It also marks all the -- packages that depended on it as having failed. -- -- * The package must exist in the graph and be in the processing -- state. -- failed :: InstalledPackageId -- ^ The id of the package that failed to install -> BuildFailure -- ^ The build result to use for the failed package -> BuildFailure -- ^ The build result to use for its dependencies -> InstallPlan -> InstallPlan failed pkgid buildResult buildResult' plan = assert (invariant plan') plan' where -- NB: failures don't update IPIDs plan' = plan { planIndex = PackageIndex.merge (planIndex plan) failures } pkg = lookupProcessingPackage plan pkgid failures = PackageIndex.fromList $ Failed (readyPackageToConfiguredPackage pkg) buildResult : [ Failed pkg' buildResult' | Just pkg' <- map checkConfiguredPackage $ packagesThatDependOn plan pkgid ] -- | Lookup the reachable packages in the reverse dependency graph. -- packagesThatDependOn :: InstallPlan -> InstalledPackageId -> [PlanPackage] packagesThatDependOn plan pkgid = map (planPkgOf plan) . tail . Graph.reachable (planGraphRev plan) . planVertexOf plan $ Map.findWithDefault pkgid pkgid (planFakeMap plan) -- | Lookup a package that we expect to be in the processing state. -- lookupProcessingPackage :: InstallPlan -> InstalledPackageId -> ReadyPackage lookupProcessingPackage plan pkgid = -- NB: processing packages are guaranteed to not indirect through -- planFakeMap case PackageIndex.lookupInstalledPackageId (planIndex plan) pkgid of Just (Processing pkg) -> pkg _ -> internalError $ "not in processing state or no such pkg " ++ display pkgid -- | Check a package that we expect to be in the configured or failed state. -- checkConfiguredPackage :: PlanPackage -> Maybe ConfiguredPackage checkConfiguredPackage (Configured pkg) = Just pkg checkConfiguredPackage (Failed _ _) = Nothing checkConfiguredPackage pkg = internalError $ "not configured or no such pkg " ++ display (packageId pkg) -- ------------------------------------------------------------ -- * Checking validity of plans -- ------------------------------------------------------------ -- | A valid installation plan is a set of packages that is 'acyclic', -- 'closed' and 'consistent'. Also, every 'ConfiguredPackage' in the -- plan has to have a valid configuration (see 'configuredPackageValid'). -- -- * if the result is @False@ use 'problems' to get a detailed list. -- valid :: Platform -> CompilerInfo -> FakeMap -> Bool -> PlanIndex -> Bool valid platform cinfo fakeMap indepGoals index = null $ problems platform cinfo fakeMap indepGoals index data PlanProblem = PackageInvalid ConfiguredPackage [PackageProblem] | PackageMissingDeps PlanPackage [PackageIdentifier] | PackageCycle [PlanPackage] | PackageInconsistency PackageName [(PackageIdentifier, Version)] | PackageStateInvalid PlanPackage PlanPackage showPlanProblem :: PlanProblem -> String showPlanProblem (PackageInvalid pkg packageProblems) = "Package " ++ display (packageId pkg) ++ " has an invalid configuration, in particular:\n" ++ unlines [ " " ++ showPackageProblem problem | problem <- packageProblems ] showPlanProblem (PackageMissingDeps pkg missingDeps) = "Package " ++ display (packageId pkg) ++ " depends on the following packages which are missing from the plan: " ++ intercalate ", " (map display missingDeps) showPlanProblem (PackageCycle cycleGroup) = "The following packages are involved in a dependency cycle " ++ intercalate ", " (map (display.packageId) cycleGroup) showPlanProblem (PackageInconsistency name inconsistencies) = "Package " ++ display name ++ " is required by several packages," ++ " but they require inconsistent versions:\n" ++ unlines [ " package " ++ display pkg ++ " requires " ++ display (PackageIdentifier name ver) | (pkg, ver) <- inconsistencies ] showPlanProblem (PackageStateInvalid pkg pkg') = "Package " ++ display (packageId pkg) ++ " is in the " ++ showPlanState pkg ++ " state but it depends on package " ++ display (packageId pkg') ++ " which is in the " ++ showPlanState pkg' ++ " state" where showPlanState (PreExisting _) = "pre-existing" showPlanState (Configured _) = "configured" showPlanState (Processing _) = "processing" showPlanState (Installed _ _) = "installed" showPlanState (Failed _ _) = "failed" -- | For an invalid plan, produce a detailed list of problems as human readable -- error messages. This is mainly intended for debugging purposes. -- Use 'showPlanProblem' for a human readable explanation. -- problems :: Platform -> CompilerInfo -> FakeMap -> Bool -> PlanIndex -> [PlanProblem] problems platform cinfo fakeMap indepGoals index = [ PackageInvalid pkg packageProblems | Configured pkg <- PackageIndex.allPackages index , let packageProblems = configuredPackageProblems platform cinfo pkg , not (null packageProblems) ] ++ [ PackageMissingDeps pkg (catMaybes (map (fmap packageId . PlanIndex.fakeLookupInstalledPackageId fakeMap index) missingDeps)) | (pkg, missingDeps) <- PlanIndex.brokenPackages fakeMap index ] ++ [ PackageCycle cycleGroup | cycleGroup <- PlanIndex.dependencyCycles fakeMap index ] ++ [ PackageInconsistency name inconsistencies | (name, inconsistencies) <- PlanIndex.dependencyInconsistencies fakeMap indepGoals index ] ++ [ PackageStateInvalid pkg pkg' | pkg <- PackageIndex.allPackages index , Just pkg' <- map (PlanIndex.fakeLookupInstalledPackageId fakeMap index) (CD.nonSetupDeps (depends pkg)) , not (stateDependencyRelation pkg pkg') ] -- | The graph of packages (nodes) and dependencies (edges) must be acyclic. -- -- * if the result is @False@ use 'PackageIndex.dependencyCycles' to find out -- which packages are involved in dependency cycles. -- acyclic :: FakeMap -> PlanIndex -> Bool acyclic fakeMap = null . PlanIndex.dependencyCycles fakeMap -- | An installation plan is closed if for every package in the set, all of -- its dependencies are also in the set. That is, the set is closed under the -- dependency relation. -- -- * if the result is @False@ use 'PackageIndex.brokenPackages' to find out -- which packages depend on packages not in the index. -- closed :: FakeMap -> PlanIndex -> Bool closed fakeMap = null . PlanIndex.brokenPackages fakeMap -- | An installation plan is consistent if all dependencies that target a -- single package name, target the same version. -- -- This is slightly subtle. It is not the same as requiring that there be at -- most one version of any package in the set. It only requires that of -- packages which have more than one other package depending on them. We could -- actually make the condition even more precise and say that different -- versions are OK so long as they are not both in the transitive closure of -- any other package (or equivalently that their inverse closures do not -- intersect). The point is we do not want to have any packages depending -- directly or indirectly on two different versions of the same package. The -- current definition is just a safe approximation of that. -- -- * if the result is @False@ use 'PackageIndex.dependencyInconsistencies' to -- find out which packages are. -- consistent :: FakeMap -> PlanIndex -> Bool consistent fakeMap = null . PlanIndex.dependencyInconsistencies fakeMap False -- | The states of packages have that depend on each other must respect -- this relation. That is for very case where package @a@ depends on -- package @b@ we require that @dependencyStatesOk a b = True@. -- stateDependencyRelation :: PlanPackage -> PlanPackage -> Bool stateDependencyRelation (PreExisting _) (PreExisting _) = True stateDependencyRelation (Configured _) (PreExisting _) = True stateDependencyRelation (Configured _) (Configured _) = True stateDependencyRelation (Configured _) (Processing _) = True stateDependencyRelation (Configured _) (Installed _ _) = True stateDependencyRelation (Processing _) (PreExisting _) = True stateDependencyRelation (Processing _) (Installed _ _) = True stateDependencyRelation (Installed _ _) (PreExisting _) = True stateDependencyRelation (Installed _ _) (Installed _ _) = True stateDependencyRelation (Failed _ _) (PreExisting _) = True -- failed can depends on configured because a package can depend on -- several other packages and if one of the deps fail then we fail -- but we still depend on the other ones that did not fail: stateDependencyRelation (Failed _ _) (Configured _) = True stateDependencyRelation (Failed _ _) (Processing _) = True stateDependencyRelation (Failed _ _) (Installed _ _) = True stateDependencyRelation (Failed _ _) (Failed _ _) = True stateDependencyRelation _ _ = False -- | A 'ConfiguredPackage' is valid if the flag assignment is total and if -- in the configuration given by the flag assignment, all the package -- dependencies are satisfied by the specified packages. -- configuredPackageValid :: Platform -> CompilerInfo -> ConfiguredPackage -> Bool configuredPackageValid platform cinfo pkg = null (configuredPackageProblems platform cinfo pkg) data PackageProblem = DuplicateFlag FlagName | MissingFlag FlagName | ExtraFlag FlagName | DuplicateDeps [PackageIdentifier] | MissingDep Dependency | ExtraDep PackageIdentifier | InvalidDep Dependency PackageIdentifier showPackageProblem :: PackageProblem -> String showPackageProblem (DuplicateFlag (FlagName flag)) = "duplicate flag in the flag assignment: " ++ flag showPackageProblem (MissingFlag (FlagName flag)) = "missing an assignment for the flag: " ++ flag showPackageProblem (ExtraFlag (FlagName flag)) = "extra flag given that is not used by the package: " ++ flag showPackageProblem (DuplicateDeps pkgids) = "duplicate packages specified as selected dependencies: " ++ intercalate ", " (map display pkgids) showPackageProblem (MissingDep dep) = "the package has a dependency " ++ display dep ++ " but no package has been selected to satisfy it." showPackageProblem (ExtraDep pkgid) = "the package configuration specifies " ++ display pkgid ++ " but (with the given flag assignment) the package does not actually" ++ " depend on any version of that package." showPackageProblem (InvalidDep dep pkgid) = "the package depends on " ++ display dep ++ " but the configuration specifies " ++ display pkgid ++ " which does not satisfy the dependency." configuredPackageProblems :: Platform -> CompilerInfo -> ConfiguredPackage -> [PackageProblem] configuredPackageProblems platform cinfo (ConfiguredPackage pkg specifiedFlags stanzas specifiedDeps') = [ DuplicateFlag flag | ((flag,_):_) <- duplicates specifiedFlags ] ++ [ MissingFlag flag | OnlyInLeft flag <- mergedFlags ] ++ [ ExtraFlag flag | OnlyInRight flag <- mergedFlags ] ++ [ DuplicateDeps pkgs | pkgs <- CD.nonSetupDeps (fmap (duplicatesBy (comparing packageName)) specifiedDeps) ] ++ [ MissingDep dep | OnlyInLeft dep <- mergedDeps ] ++ [ ExtraDep pkgid | OnlyInRight pkgid <- mergedDeps ] ++ [ InvalidDep dep pkgid | InBoth dep pkgid <- mergedDeps , not (packageSatisfiesDependency pkgid dep) ] where specifiedDeps :: ComponentDeps [PackageId] specifiedDeps = fmap (map confSrcId) specifiedDeps' mergedFlags = mergeBy compare (sort $ map flagName (genPackageFlags (packageDescription pkg))) (sort $ map fst specifiedFlags) packageSatisfiesDependency (PackageIdentifier name version) (Dependency name' versionRange) = assert (name == name') $ version `withinRange` versionRange dependencyName (Dependency name _) = name mergedDeps :: [MergeResult Dependency PackageId] mergedDeps = mergeDeps requiredDeps (CD.flatDeps specifiedDeps) mergeDeps :: [Dependency] -> [PackageId] -> [MergeResult Dependency PackageId] mergeDeps required specified = let sortNubOn f = nubBy ((==) `on` f) . sortBy (compare `on` f) in mergeBy (\dep pkgid -> dependencyName dep `compare` packageName pkgid) (sortNubOn dependencyName required) (sortNubOn packageName specified) -- TODO: It would be nicer to use ComponentDeps here so we can be more precise -- in our checks. That's a bit tricky though, as this currently relies on -- the 'buildDepends' field of 'PackageDescription'. (OTOH, that field is -- deprecated and should be removed anyway.) -- As long as we _do_ use a flat list here, we have to allow for duplicates -- when we fold specifiedDeps; once we have proper ComponentDeps here we -- should get rid of the `nubOn` in `mergeDeps`. requiredDeps :: [Dependency] requiredDeps = --TODO: use something lower level than finalizePackageDescription case finalizePackageDescription specifiedFlags (const True) platform cinfo [] (enableStanzas stanzas $ packageDescription pkg) of Right (resolvedPkg, _) -> externalBuildDepends resolvedPkg ++ maybe [] setupDepends (setupBuildInfo resolvedPkg) Left _ -> error "configuredPackageInvalidDeps internal error" -- | Compute the dependency closure of a _source_ package in a install plan -- -- See `Distribution.Simple.dependencyClosure` dependencyClosure :: InstallPlan -> [PackageIdentifier] -> Either (PackageIndex PlanPackage) [(PlanPackage, [InstalledPackageId])] dependencyClosure installPlan pids = PlanIndex.dependencyClosure (planFakeMap installPlan) (planIndex installPlan) (map (resolveFakeId . fakeInstalledPackageId) pids) where resolveFakeId :: InstalledPackageId -> InstalledPackageId resolveFakeId ipid = Map.findWithDefault ipid ipid (planFakeMap installPlan)
Helkafen/cabal
cabal-install/Distribution/Client/InstallPlan.hs
bsd-3-clause
29,290
0
18
6,564
5,212
2,806
2,406
416
8
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ro-RO"> <title>ToDo-List</title> <maps> <homeID>todo</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/todo/src/main/javahelp/help_ro_RO/helpset_ro_RO.hs
apache-2.0
955
77
67
155
408
207
201
-1
-1
module ListIn2 where f :: [Int] -> Int f [42,56] = case [11,2] of [x,y] -> x _ -> 1
kmate/HaRe
old/testing/simplifyExpr/ListIn2.hs
bsd-3-clause
105
0
8
41
58
34
24
5
2
suCC :: Int -> Int suCC x = x + 1 isdivs :: Int -> Int -> Bool isdivs n x = mod x n /= 0 --the_filter :: [Int] -> [Int] --the_filter (n:ns) = filter (isdivs n) ns the_filter :: [Int] -> [Int] the_filter (n:ns) = f ns where f [] = [] f (x:ns) | isdivs n x = (x:f ns) f (_:ns) = f ns primes :: [Int] primes = map head (iterate the_filter (iterate suCC 2)) --primes = map head (iterate the_filter [2 .. ]) main = do --[arg] <- getArgs print $ primes !! 2000 -- (read arg)
m-alvarez/jhc
examples/Primes.hs
mit
490
0
10
124
210
109
101
13
3
{- From: Kevin Hammond <kh> To: partain Subject: Nasty Overloading Date: Wed, 23 Oct 91 16:19:46 BST -} module Main where class Foo a where o1 :: a -> a -> Bool o2 :: a -> Int -- o2 :: Int -- Lennart: The type of method o2 does not contain the variable a -- (and it must according to line 1 page 29 of the manual). class Foo tyvar => Bar tyvar where o3 :: a -> tyvar -> tyvar -- class (Eq a, Foo a) => Baz a where class (Ord a, Foo a) => Baz a where o4 :: a -> a -> (String,String,String,a) instance (Ord a, Foo a) => Foo [a] where o2 x = 100 o1 a b = a < b || o1 (head a) (head b) -- instance Bar [a] where instance (Ord a, Foo a) => Bar [a] where o3 x l = [] -- -- Lennart: I guess the instance declaration -- instance Bar [w] where -- o3 x l = [] -- is wrong because to be a Bar you have to be a Foo. For [w] to -- be a Foo, w has to be Ord and Foo. But w is not Ord or Foo in -- this instance declaration so it must be wrong. (Page 31, line -- 7: The context c' must imply ...) instance Baz a => Baz [a] where o4 [] [] = ("Nil", "Nil", "Nil", []) o4 l1 l2 = (if o1 l1 l2 then "Y" else "N", if l1 == l2 then "Y" else "N", -- if o4 (head l1) (head l2) then "Y" else "N", case o4 (head l1) (head l2) of (_,_,_,l3) -> if (o1 (head l1) l3) then "Y" else "N", l1 ++ l2 ) instance Foo Int where o2 x = x o1 i j = i == j instance Bar Int where o3 _ j = j + 1 instance Baz Int where -- o4 i j = i > j o4 i j = (if i>j then "Y" else "Z", "p", "q", i+j) --simpl:o4 i j = ("Z", "p", "q", i+j) {- also works w/ glhc! -} main = if o4 [1,2,3] [1,3,2::Int] /= ("Y","N","Y",[1,2,3,1,3,2]) then (print "43\n") else (print "144\n") {- works: glhc main = case o4 [1,2,3] [1,3,2::Int] of (s1,s2,s3,x) -> print s1 main = case o4 ([]::[Int]) ([]::[Int]) of (s1,s2,s3,x) -> print s1 -} {- simple main: breaks nhc, works w/ glhc main = case o4 (3::Int) (4::Int) of (s1,s2,s3,x) -> print s1 -}
olsner/ghc
testsuite/tests/codeGen/should_run/cgrun013.hs
bsd-3-clause
2,222
0
14
770
581
326
255
31
2
-- This test checks that the magic treatment of RULES -- for 'seq' works right. -- -- See Note [RULES for seq] in MkId for more details module Main where {-# NOINLINE f #-} f x = not x {-# RULES "f/seq" forall n e. seq (f n) e = True #-} main = print (seq (f True) False)
ryantm/ghc
testsuite/tests/simplCore/should_run/SeqRule.hs
bsd-3-clause
287
0
9
73
43
25
18
6
1
{-# LANGUAGE PartialTypeSignatures #-} module WildcardInTypeSynonymLHS where type Foo _ = Int
urbanslug/ghc
testsuite/tests/partial-sigs/should_fail/WildcardInTypeSynonymLHS.hs
bsd-3-clause
95
0
4
13
12
9
3
-1
-1
-- !!! Repeated variable in instance predicate module M where instance Eq a => Eq (Either a a)
urbanslug/ghc
testsuite/tests/module/mod41.hs
bsd-3-clause
95
0
7
18
27
14
13
2
0
{-# LANGUAGE OverloadedStrings #-} {-| Module : Haste.GAPI.GPlus Description : Google+ API bindings for haste-gapi Copyright : (c) Jonathan Skårstedt, 2016 License : MIT Maintainer : jonathan.skarstedt@gmail.com Stability : experimental Portability : Haste Contains default function and result mappings for the Google+ API. -} module Haste.GAPI.GPlus ( peopleGet, peopleSearch, peopleListByActivity, peopleList, -- | = Google+ datatypes: -- | == Google+ Person module Haste.GAPI.GPlus.Person ) where import Haste.GAPI.Types import Haste.GAPI.GPlus.Person import Haste.GAPI.Request import Haste.JSString as J import Haste (JSString) -- | Fetches a user by ID peopleGet :: UserID -> RequestM (Result Person) peopleGet uid = request' $ "plus/v1/people/" `append` uid -- | Search after users given a query string -- -- Optional parameters: -- -- [@language@] @language@ to search with. See Google API documentation -- for valid language codes -- -- [@maxResult@] Maximum number of people to include in the response. -- Acceptable values of @maxResult@ ranges between 1-50, -- default is 25. -- -- [@pageToken@] Token used for pagination in large result sets. peopleSearch :: JSString -> [Param] -> RequestM [Result Person] peopleSearch query ps = do r <- request "plus/v1/people" $ ("query", query):ps r' <- get r "items" childs <- children r' case childs of Just childs' -> return childs' Nothing -> fail "peopleSearch: Child was not found!" -- | List users by activity -- -- Valid collections are "@plusoners@" and "@resharers@". -- -- Optional parameters: -- -- [@maxResult@] Maximum number of people to include in the response. -- Acceptable values of @maxResult@ ranges between 1-100, -- default is 20. -- -- [@pageToken@] Token used for pagination in large result sets. peopleListByActivity :: ActivityID -> Collection -> [Param] -> RequestM [Result Person] peopleListByActivity actId col ps = do r <- request (J.concat ["plus/v1/activities/", actId, "/people/", col]) ps r' <- get r "items" childs <- children r' case childs of Just childs' -> return childs' Nothing -> fail "peopleSearch: Child was not found!" -- | List people in a specific collection -- -- Accepted collections are: -- -- [@connected@] The list of visible people in the authenticated user's -- circles who also use the requesting app. This list -- is limited to users who made their app activities visible -- to the authenticated user. -- -- [@visible@] The list of people who this user has added to one or more -- circles, limited to the circles visible to the requesting -- application. -- -- Optional parameters: -- -- [@maxResult@] Maximum number of people to include in the response. -- Acceptable values of @maxResult@ ranges between 1-100, -- default is 100. -- -- [@orderBy@] The order to return people in. Valid inputs are -- "@alphabetical@" and "@best@" -- -- [@pageToken@] Token used for pagination in large result sets. peopleList :: UserID -> Collection -> [Param] -> RequestM [Result Person] peopleList uid c ps = do r <- request (J.concat ["plus/v1/people/", uid, "/people/", c]) ps r' <- get r "items" childs <- children r' case childs of Just childs' -> return childs' Nothing -> fail "peopleSearch: Child was not found!"
nyson/haste-gapi
Haste/GAPI/GPlus.hs
mit
3,552
0
11
837
505
282
223
39
2
{-# LANGUAGE NoMonomorphismRestriction #-} import Graphics.Rendering.OpenGL.GL.CoordTrans ( Position(..), Size(..) ) import Graphics.Rendering.OpenGL.GL.StateVar ( ($=), ($=!), get ) import Graphics.UI.GLUT.Begin import Graphics.UI.GLUT.Callbacks.Window import Graphics.UI.GLUT.Callbacks.Global import Graphics.UI.GLUT.Initialization import Graphics.UI.GLUT.Window import Graphics.Rendering.OpenGL.Raw.Core import Graphics.Rendering.OpenGL.Raw.ARB.Compatibility import Data.List (sort,unfoldr) import System.Random import Control.Monad import System.Exit import Data.List.Split import Data.Maybe(fromJust, listToMaybe, catMaybes) import Data.IORef import System.Environment type IntPoint = Point Int type GLPoint = Point GLfloat type Point a = (a, a) data Line a = Line (Point a) (Point a) myInit :: IO () myInit = do glClearColor 0 0 0 0 glTranslatef 0.375 0.375 0 -- draw to center of pixels --display :: Some IORefs -> DisplayCallback display numLines sfn fn stripe = do n <- get numLines sn <- get sfn fn <- get fn stripe' <- get stripe glClear gl_COLOR_BUFFER_BIT replicateM n (sn (fn stripe')) glFlush swapBuffers displayLine line stripe alg = do line' <- get line stripe' <- get stripe alg' <- get alg glClear gl_COLOR_BUFFER_BIT alg' stripe' line' --actually draws everything glFlush swapBuffers reshape :: ReshapeCallback reshape (Size w h) = do glViewport 0 0 (fromIntegral w) (fromIntegral h) glMatrixMode gl_PROJECTION glLoadIdentity let wf = fromIntegral w hf = fromIntegral h glOrtho 0 wf 0 hf 0 1 --set coordinates, bottom left -> 0,0 glMatrixMode gl_MODELVIEW keyboard :: KeyboardMouseCallback keyboard (Char '\27') Down _ _ = exitWith ExitSuccess keyboard _ _ _ _ = return () main :: IO () main = do (progName, _args) <- getArgsAndInitialize initialDisplayMode $= [ DoubleBuffered, RGBMode ] initialWindowSize $= Size 640 640 initialWindowPosition $= Position 100 100 createWindow progName myInit numLines <- newIORef 0 --lines to draw sfn <- newIORef randomLongLine --long or short lines alg <- newIORef (bresenham :: Maybe Int -> Line Int -> IO ()) -- line drawing algorithm stripe <- newIORef (Nothing :: Maybe Int) -- stripe lines, default to no line <- newIORef $ Line (0,0) (0,0) --set stripe when running program first time case _args of [_, "-s", n] -> stripe $= Just (read n :: Int) ["-s", n] -> stripe $= Just (read n :: Int) _ -> stripe $= Nothing reshapeCallback $= Just reshape keyboardMouseCallback $= Just keyboard displayCallback $= let (a:rgs) = _args in if a == "-line" then (displayLine line stripe alg) else (display numLines sfn alg stripe) idleCallback $= let (a:rgs) = _args in if a == "-line" then Just (idleLine line alg) else Just (idleRand numLines sfn alg stripe) mainLoop idleRand numLines sfn alg stripe = do processInput numLines sfn alg stripe postRedisplay Nothing idleLine line alg = do processInputForLine line alg postRedisplay Nothing {- <algorithm> <line_length> <# of lines> -} --processInput :: Very ugly type signature. processInput numLines sfn alg stripe = do cmd <- getLine let cmd' = splitOn " " cmd [c1, c2, c3] | length cmd' >= 3 = take 3 cmd' | otherwise = take 3 $ cmd' ++ repeat " " n = maybeRead c3 :: (Maybe Int) lineMappings = [("short", randomShortLine), ("long", randomLongLine)] algMappings = [("bresenham", bresenham), ("std", lineFromTo)] f = lookup c1 lineMappings g = lookup c2 algMappings numLines `assignMaybe` n sfn `assignMaybe` f alg `assignMaybe` g case (head cmd') of "exit" -> do putStrLn "Goodbye!" exitWith ExitSuccess _ -> return () {- <algorithm> x1 y1 x2 y2 -} processInputForLine line alg = do cmd <- getLine ln <- get line let cmd' = splitOn " " cmd cmds@[alg', x1, y1, x2, y2] | length cmd' >= 5 = take 5 cmd' | otherwise = take 5 $ cmd' ++ repeat " " pts@[x1', y1', x2', y2'] = catMaybes $ fmap (\x -> maybeRead x :: Maybe Int) (tail cmds) newLine | (length pts) == 4 = Just $ Line (x1', y1') (x2', y2') | otherwise = Nothing algMappings = [("bresenham", bresenham), ("std", lineFromTo)] newAlg = lookup alg' algMappings line `assignMaybe` newLine alg `assignMaybe` newAlg case (head cmd') of "exit" -> do putStrLn "Goodbye!" exitWith ExitSuccess _ -> return () assignMaybe :: IORef a -> Maybe a -> IO () assignMaybe a (Just b) = a $= b assignMaybe a Nothing = return () maybeRead :: Read a => String -> Maybe a maybeRead = fmap fst . listToMaybe . reads --draw a line from point a to point b using the basic algorithm lineFromTo :: Maybe Int -> Line Int -> IO () lineFromTo stripe (Line a@(x1, y1) b@(x2, y2)) = let dx = abs $ x2-x1 dy = abs $ y2-y1 in if dx >= dy && x2 < x1 then lineFromTo' stripe (Line b a) else if dy >= dx && y2 < y1 then lineFromTo' stripe (Line b a) else lineFromTo' stripe (Line a b) lineFromTo' :: Maybe Int -> Line Int -> IO () lineFromTo' stripe (Line (x1, y1) (x2, y2)) = do glBegin gl_POINTS if ( dy < dx ) then forM_ [x1..x2] $ \x -> do glColor3f 1 1 1 let skip = case stripe of (Just s) -> x+1 `mod` s == 0 || x `mod` s == 0 _ -> False if (not skip) then (uncurry glVertex2f) (xFunc x) else return () else forM_ [y1..y2] $ \y -> do glColor3f 1 1 1 let skip = case stripe of (Just s) -> y+1 `mod` s == 0 || y `mod` s == 0 _ -> False if (not skip) then (uncurry glVertex2f) (yFunc y) else return () glEnd where dx = abs $ x2 - x1 dy = abs $ y2 - y1 xFunc x = toGLPoint (x, y1 + (dy * (x - x1)) `safeDiv` dx) yFunc y = toGLPoint (x1 + (dx * (y - y1)) `safeDiv` dy, y) pts | dy < dx = fmap xFunc [x1..x2] | otherwise = fmap yFunc [y1..y2] safeDiv x y | y == 0 = 0 | otherwise = x `div` y --draw a line from a to b using bresenham bresenham :: Maybe Int -> Line Int -> IO () bresenham stripe (Line a@(x0, y0) b@(x1, y1)) = drawPoints $ catMaybes $ unfoldr go (err, x0', y0') where skip x = case stripe of (Just s) -> x+1 `mod` s == 0 || x `mod` s == 0 _ -> False fixIfSteep (a, b) = if steep then (b, a) else (a, b) steep = abs (x1-x0) < abs (y1-y0) [(x0',y0'), (x1',y1')] = sort $ fmap fixIfSteep [a, b] (dx, dy) = (x1'-x0', abs $ y1'-y0') err = dx `div` 2 ystep = if y0' < y1' then 1 else -1 go (err, x, y) | x > x1' = Nothing | otherwise = Just $ (point, (err'', x+1, y')) where err' = err - dy (err'', y') | err' < 0 = (err' + dx, y + ystep) | otherwise = (err', y) point = case skip x of False -> Just $ toGLPoint $ fixIfSteep (x, y) True -> Nothing toGLPoint :: IntPoint -> GLPoint toGLPoint (a, b) = (fromIntegral a, fromIntegral b) swapCoords :: (a, b) -> (b, a) swapCoords (a, b) = (b, a) drawPoints xs = do glBegin gl_POINTS glColor3f 1 1 1 mapM_ (uncurry glVertex2f) xs glEnd randomShortLine alg = do x <- getStdRandom $ randomR (10, 630) y <- getStdRandom $ randomR (10, 630) dx <- getStdRandom $ randomR (-10, 10) dy <- getStdRandom $ randomR (-10, 10) alg $ Line (x, y) (x + dx, y + dy) randomLongLine alg = do x <- getStdRandom $ randomR (0, 640) y <- getStdRandom $ randomR (0, 640) dx <- getStdRandom $ randomR (-640, 640) dy <- getStdRandom $ randomR (-640, 640) alg $ Line (x, y) (x + dx, y + dy) {---------- TESTING ----------} bresenhamTest :: Maybe Int -> Line Int -> IO [GLPoint] bresenhamTest stripe (Line a@(x0, y0) b@(x1, y1)) = do let xs = catMaybes $ unfoldr go (err, x0', y0') return xs where skip x = case stripe of (Just s) -> x+1 `mod` s == 0 || x `mod` s == 0 _ -> False fixIfSteep (a, b) = if steep then (b, a) else (a, b) steep = abs (x1-x0) < abs (y1-y0) [(x0',y0'), (x1',y1')] = sort $ fmap fixIfSteep [a, b] (dx, dy) = (x1'-x0', abs $ y1'-y0') err = dx `div` 2 ystep = if y0' < y1' then 1 else -1 go (err, x, y) | x > x1' = Nothing | otherwise = Just $ (point, (err'', x+1, y')) where err' = err - dy (err'', y') | err' < 0 = (err' + dx, y + ystep) | otherwise = (err', y) point = case skip x of False -> Just $ toGLPoint $ fixIfSteep (x, y) True -> Nothing --draw a line from point a to point b using the basic algorithm lineFromToTest :: Maybe Int -> Line Int -> IO () lineFromToTest stripe (Line a@(x1, y1) b@(x2, y2)) = let dx = abs $ x2-x1 dy = abs $ y2-y1 in if dx >= dy && x2 < x1 then lineFromToTest' stripe (Line b a) else if dy >= dx && y2 < y1 then lineFromToTest' stripe (Line b a) else lineFromToTest' stripe (Line a b) lineFromToTest' :: Maybe Int -> Line Int -> IO () lineFromToTest' stripe (Line (x1, y1) (x2, y2)) = do if ( dy < dx ) then forM_ [x1..x2] $ \x -> do let skip = case stripe of (Just s) -> x+1 `mod` s == 0 || x `mod` s == 0 _ -> False if (not skip) then return () else return () else forM_ [y1..y2] $ \y -> do let skip = case stripe of (Just s) -> y+1 `mod` s == 0 || y `mod` s == 0 _ -> False if (not skip) then return () else return () where dx = abs $ x2 - x1 dy = abs $ y2 - y1 xFunc x = toGLPoint (x, y1 + (dy * (x - x1)) `safeDiv` dx) yFunc y = toGLPoint (x1 + (dx * (y - y1)) `safeDiv` dy, y) pts | dy < dx = fmap xFunc [x1..x2] | otherwise = fmap yFunc [y1..y2] safeDiv x y | y == 0 = 0 | otherwise = x `div` y shortLinesB n = replicateM_ n $ randomShortLine (bresenhamTest Nothing) longLinesB n = replicateM_ n $ randomLongLine (bresenhamTest Nothing) shortLinesS n = replicateM_ n $ randomShortLine (lineFromToTest Nothing) longLinesS n = replicateM_ n $ randomLongLine (lineFromToTest Nothing)
5outh/Haskell-Graphics-Projects
graphics_test.hs
mit
10,659
8
23
3,276
4,395
2,278
2,117
264
6
module Compiler.JIT where import Control.Applicative import Control.Monad.Except import Compiler.Type.Pipeline import Compiler.PreAST.Type import LLVM.General import qualified LLVM.General.AST as IR import LLVM.General.Context import LLVM.General.ExecutionEngine as EE import Foreign.Ptr foreign import ccall "dynamic" mkFun :: FunPtr (IO ()) -> (IO ()) runForeignFunction :: FunPtr a -> IO () runForeignFunction fn = mkFun (castFunPtr fn :: FunPtr (IO ())) jit :: Context -> (EE.MCJIT -> IO a) -> IO a jit context = EE.withMCJIT context optLvl model ptrElim fPreASTIns where optLvl = Just 2 -- optimization level model = Nothing -- code model ( Default ) ptrElim = Nothing -- frame pointer elimination fPreASTIns = Nothing -- fPreAST instruction withModuleFromIR :: (Module -> IO a) -> IR.Module -> Pipeline a withModuleFromIR f mod = do result <- liftIO $ withContext $ \context -> do runExceptT $ withModuleFromAST context mod f case result of Left err -> throwError $ CompileErrorClass err Right as -> return as runJIT :: IR.Module -> Pipeline () runJIT = withModuleFromIR $ \mod -> withContext $ \context -> jit context $ \engine -> EE.withModuleInEngine engine mod $ \ee -> do mainFunction <- EE.getFunction ee (IR.Name "main") case mainFunction of Just fn -> runForeignFunction fn Nothing -> void $ putStrLn "function not found" toAssembly :: IR.Module -> Pipeline String toAssembly = withModuleFromIR moduleLLVMAssembly
banacorn/mini-pascal
src/Compiler/JIT.hs
mit
1,679
0
19
462
473
245
228
37
2
-- Multiply characters -- http://www.codewars.com/kata/52e9aa89b5acdd26d3000127 module CWSpam where spam :: Int -> String spam i = take (3*i) (cycle "hue")
gafiatulin/codewars
src/7 kyu/CWSpam.hs
mit
158
0
7
22
41
23
18
3
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Test.Pos.Chain.Block.Arbitrary ( HeaderAndParams (..) , BlockHeaderList (..) , genMainBlockHeader , genMainBlockBody , genMainBlockBodyForSlot , genMainBlock , genHeaderAndParams , genStubbedBHL ) where import qualified Prelude import Universum import qualified Data.List as List import qualified Data.Set as Set import Formatting (bprint, build, (%)) import qualified Formatting.Buildable as Buildable import System.Random (Random, mkStdGen, randomR) import Test.QuickCheck (Arbitrary (..), Gen, choose, suchThat) import Test.QuickCheck.Arbitrary.Generic (genericArbitrary, genericShrink) import Pos.Binary.Class (biSize) import Pos.Chain.Block (ConsensusEraLeaders (..), HeaderHash, headerLastSlotInfo, mkMainBlock, mkMainBlockExplicit) import qualified Pos.Chain.Block as Block import qualified Pos.Chain.Block.Slog.LastBlkSlots as LastBlkSlots import qualified Pos.Chain.Delegation as Core import Pos.Chain.Genesis (GenesisHash (..)) import Pos.Chain.Update (ConsensusEra (..), ObftConsensusStrictness (..)) import Pos.Core (BlockCount (..), EpochOrSlot (..), SlotId (..), getEpochOrSlot, localSlotIndexMaxBound, localSlotIndexMinBound) import qualified Pos.Core as Core import Pos.Core.Attributes (areAttributesKnown) import Pos.Core.Chrono (OldestFirst (..)) import Pos.Core.Slotting (LocalSlotIndex (..), SlotCount (..), epochOrSlotToSlot) import Pos.Crypto (ProtocolMagic, PublicKey, SecretKey, createPsk, toPublic) import Test.Pos.Chain.Delegation.Arbitrary (genDlgPayload) import Test.Pos.Chain.Genesis.Dummy (dummyEpochSlots, dummyGenesisHash) import Test.Pos.Chain.Ssc.Arbitrary (SscPayloadDependsOnSlot (..), genSscPayload, genSscPayloadForSlot) import Test.Pos.Chain.Txp.Arbitrary (genTxPayload) import Test.Pos.Chain.Update.Arbitrary (genUpdatePayload) import Test.Pos.Core.Arbitrary (genSlotId) newtype BodyDependsOnSlot body = BodyDependsOnSlot { genBodyDepsOnSlot :: SlotId -> Gen body } ------------------------------------------------------------------------------------------ -- Arbitrary instances for Blockchain related types ------------------------------------------------------------------------------------------ instance Arbitrary Block.BlockHeader where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary Block.BlockSignature where arbitrary = genericArbitrary shrink = genericShrink ------------------------------------------------------------------------------------------ -- GenesisBlockchain ------------------------------------------------------------------------------------------ instance Arbitrary Block.GenesisExtraHeaderData where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary Block.GenesisExtraBodyData where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary Block.GenesisBlockHeader where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary Block.GenesisProof where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary Block.GenesisConsensusData where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary (BodyDependsOnSlot Block.GenesisBody) where arbitrary = pure $ BodyDependsOnSlot $ \_ -> arbitrary instance Arbitrary Block.GenesisBody where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary Block.GenesisBlock where arbitrary = Block.mkGenesisBlock <$> arbitrary <*> (maybe (Left dummyGenesisHash) Right <$> arbitrary) <*> arbitrary <*> arbitrary shrink = genericShrink ------------------------------------------------------------------------------------------ -- MainBlockchain ------------------------------------------------------------------------------------------ -- | Generate a 'MainBlockHeader' given a parent hash, difficulty and body. genMainBlockHeader :: ProtocolMagic -> HeaderHash -> Core.ChainDifficulty -> Block.MainBody -> Gen Block.MainBlockHeader genMainBlockHeader pm prevHash difficulty body = Block.mkMainHeaderExplicit pm <$> pure prevHash <*> pure difficulty <*> genSlotId dummyEpochSlots <*> arbitrary -- SecretKey <*> pure Nothing <*> pure body <*> arbitrary instance Arbitrary Block.MainBlockHeader where arbitrary = do prevHash <- arbitrary difficulty <- arbitrary body <- arbitrary pm <- arbitrary genMainBlockHeader pm prevHash difficulty body shrink = genericShrink instance Arbitrary Block.MainExtraHeaderData where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary Block.MainExtraBodyData where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary Block.MainProof where arbitrary = genericArbitrary shrink Block.MainProof {..} = [Block.MainProof txp mpcp prxp updp | (txp, mpcp, prxp, updp) <- shrink (mpTxProof, mpMpcProof, mpProxySKsProof, mpUpdateProof) ] instance Arbitrary Block.MainConsensusData where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary Block.MainToSign where arbitrary = genericArbitrary shrink = genericShrink -- | In the main blockchain's body, the number of transactions must be the -- same as the number of transaction witnesses. -- -- Furthermore, for every transaction in index i of the list, the length of -- its output list must be the same as the length of the i-th item in the -- TxDistribution list. -- -- Because of this, the Arbitrary instance for @Body -- MainBlockchain@ ensures that for every transaction generated, a -- transaction witness is generated as well, and the lengths of its list of -- outputs must also be the same as the length of its corresponding -- TxDistribution item. {-# ANN module ("HLint: ignore Reduce duplication" :: Text) #-} genMainBlockBody :: ProtocolMagic -> Core.EpochIndex -- ^ For the delegation payload. -> Gen Block.MainBody genMainBlockBody pm epoch = Block.MainBody <$> genTxPayload pm <*> genSscPayload pm <*> genDlgPayload pm epoch <*> genUpdatePayload pm genMainBlockBodyForSlot :: ProtocolMagic -> SlotId -> Gen Block.MainBody genMainBlockBodyForSlot pm slotId = do txpPayload <- genTxPayload pm sscPayload <- genSscPayloadForSlot pm slotId dlgPayload <- genDlgPayload pm (Core.siEpoch slotId) updPayload <- genUpdatePayload pm pure $ Block.MainBody txpPayload sscPayload dlgPayload updPayload instance Arbitrary (BodyDependsOnSlot Block.MainBody) where arbitrary = pure $ BodyDependsOnSlot $ \slotId -> do txPayload <- arbitrary generator <- genPayloadDependsOnSlot <$> arbitrary mpcData <- generator slotId pm <- arbitrary dlgPayload <- genDlgPayload pm $ Core.siEpoch slotId mpcUpload <- arbitrary return $ Block.MainBody txPayload mpcData dlgPayload mpcUpload instance Arbitrary Block.MainBody where arbitrary = genericArbitrary shrink mb = [ Block.MainBody txp sscp dlgp updp | (txp, sscp, dlgp, updp) <- shrink (mb ^. Block.mbTxPayload, mb ^. Block.mbSscPayload, mb ^. Block.mbDlgPayload, mb ^. Block.mbUpdatePayload) ] -- | Generate a main block (slot is chosen arbitrarily). -- You choose the previous header hash. genMainBlock :: ProtocolMagic -> HeaderHash -> Core.ChainDifficulty -> Gen Block.MainBlock genMainBlock pm prevHash difficulty = do bv <- arbitrary sv <- arbitrary slot <- genSlotId dummyEpochSlots sk <- arbitrary body <- genMainBlockBodyForSlot pm slot pure $ mkMainBlockExplicit pm bv sv prevHash difficulty slot sk Nothing body instance Arbitrary Block.MainBlock where arbitrary = do slot <- arbitrary pm <- arbitrary bv <- arbitrary sv <- arbitrary prevHeader <- maybe (Left dummyGenesisHash) Right <$> arbitrary sk <- arbitrary BodyDependsOnSlot {..} <- arbitrary :: Gen (BodyDependsOnSlot Block.MainBody) body <- genBodyDepsOnSlot slot pure $ mkMainBlock pm bv sv prevHeader slot sk Nothing body shrink = genericShrink instance Buildable (Block.BlockHeader, PublicKey) where build (block, key) = bprint ( build%"\n"% build%"\n" ) block key newtype BlockHeaderList = BHL { getHeaderList :: ([Block.BlockHeader], [PublicKey]) } deriving (Eq) instance Show BlockHeaderList where show = toString . unlines . map pretty . uncurry zip . getHeaderList -- | Generation of arbitrary, valid headerchain along with a list of leaders -- for each epoch. -- -- Because 'verifyHeaders' assumes the head of the list is the most recent -- block, this function is tail-recursive: while keeping track of the current -- block and epoch/slot, it adds the most recent one to the head of the -- header list it'll return when done. -- -- The @[Either SecretKey (SecretKey, SecretKey, Bool)]@ type is for -- determining what kind of signature the slot's block will have. If it's -- @Left sk@, it'll be a simple 'BlockSignature'; if it's @Right (issuerSK, -- delegateSK, b)@, it will be a proxy signature, and if @b :: Bool@ is -- false, it'll be a simple proxy secret key. Otherwise, it'll be a proxy -- secret key with epochs, whose lower and upper epoch bounds will be -- randomly generated. -- -- Beware that -- * genesis blocks have no leaders, and that -- * if an epoch is `n` slots long, every `n+1`-th block will be of the -- genesis kind. recursiveHeaderGen :: ProtocolMagic -> ConsensusEra -> GenesisHash -> Bool -- ^ Whether to create genesis block before creating main block for 0th slot -> [Either SecretKey (SecretKey, SecretKey)] -> [SlotId] -> [Block.BlockHeader] -> Gen [Block.BlockHeader] recursiveHeaderGen pm era gHash genesis (eitherOfLeader : leaders) (SlotId{..} : rest) blockchain | genesis && era == Original && Core.getSlotIndex siSlot == 0 = do gBody <- arbitrary let pHeader = maybe (Left gHash) Right ((fmap fst . uncons) blockchain) gHeader = Block.BlockHeaderGenesis $ Block.mkGenesisHeader pm pHeader siEpoch gBody mHeader <- genMainHeader (Just gHeader) recursiveHeaderGen pm era gHash True leaders rest (mHeader : gHeader : blockchain) | otherwise = do curHeader <- genMainHeader ((fmap fst . uncons) blockchain) recursiveHeaderGen pm era gHash True leaders rest (curHeader : blockchain) where genMainHeader prevHeader = do body <- arbitrary extraHData <- arbitrary -- These two values may not be used at all. If the slot in question -- will have a simple signature, laziness will prevent them from -- being calculated. Otherwise, they'll be the proxy secret key's ω. let slotId = SlotId siEpoch siSlot (leader, proxySK) = case eitherOfLeader of Left sk -> (sk, Nothing) Right (issuerSK, delegateSK) -> let delegatePK = toPublic delegateSK proxy = ( createPsk pm issuerSK delegatePK (Core.HeavyDlgIndex siEpoch) , toPublic issuerSK) in (delegateSK, Just proxy) pure $ Block.BlockHeaderMain $ Block.mkMainHeader pm (maybe (Left gHash) Right prevHeader) slotId leader proxySK body extraHData recursiveHeaderGen _ _ _ _ [] _ b = return b recursiveHeaderGen _ _ _ _ _ [] b = return b -- | Maximum start epoch in block header verification tests bhlMaxStartingEpoch :: Integral a => a bhlMaxStartingEpoch = 1000000 -- | Amount of full epochs in block header verification tests bhlEpochs :: Integral a => a bhlEpochs = 2 -- | This type is used to generate a blockchain, as well a list of leaders -- for every slot with which the chain will be paired. The leaders are in -- reverse order to the chain - the list goes from first to last leader. This -- is used in a `verifyHeader` test. -- -- Note that every non-empty blockchain has at least one epoch, which may be -- complete or incomplete. To simulate this behavior, two random numbers are -- generated: one that stands for the number of complete epochs we have, and -- the other for the number of incomplete slots of the last epoch, which, in -- this instance, must exist. -- -- A blockchain with only complete epochs is a subset of some blockchain with -- one incomplete epoch, so if the former is desired, a simple list -- `takeWhile` of the list this instance generates will be enough. -- -- Note that a leader is generated for each slot. -- (Not exactly a leader - see previous comment) instance Arbitrary BlockHeaderList where arbitrary = do pm <- arbitrary era <- arbitrary genStubbedBHL pm era genStubbedBHL :: ProtocolMagic -> ConsensusEra -> Gen BlockHeaderList genStubbedBHL pm era = do incompleteEpochSize <- choose (1, dummyEpochSlots - 1) let slot = SlotId 0 localSlotIndexMinBound generateBHL pm era dummyGenesisHash True slot (dummyEpochSlots * bhlEpochs + incompleteEpochSize) generateBHL :: ProtocolMagic -> ConsensusEra -> GenesisHash -> Bool -- ^ Whether to create genesis block before creating main -- block for 0th slot -> SlotId -- ^ Start slot -> SlotCount -- ^ Slot count -> Gen BlockHeaderList generateBHL pm era gHash createInitGenesis startSlot slotCount = BHL <$> do leadersList <- genLeaderKeyList $ fromIntegral slotCount let actualLeaders = map (toPublic . either identity (view _1)) leadersList slotIdsRange = take (fromIntegral slotCount) $ map (Core.unflattenSlotId dummyEpochSlots) [Core.flattenSlotId dummyEpochSlots startSlot ..] (, actualLeaders) <$> recursiveHeaderGen pm era gHash createInitGenesis leadersList slotIdsRange [] -- Generate a unique list of leader keys of the specified length. Needs to be -- unique so that block vaidation doesn't fail when validating ObftLenient. genLeaderKeyList :: Int -> Gen [Either SecretKey (SecretKey, SecretKey)] genLeaderKeyList count = loop 0 [] where loop :: Int -> [Either SecretKey (SecretKey, SecretKey)] -> Gen [Either SecretKey (SecretKey, SecretKey)] loop n !acc | n >= count = pure acc | otherwise = do key <- correctLeaderGen -- New keys that are already present in the list are discarded. if key `elem` acc then loop n acc else loop (n + 1) (key : acc) correctLeaderGen :: Gen (Either SecretKey (SecretKey, SecretKey)) correctLeaderGen = -- We don't want to create blocks with self-signed psks let issDelDiff (Left _) = True issDelDiff (Right (i,d)) = i /= d in arbitrary `suchThat` issDelDiff -- | This type is used to generate a valid blockheader and associated header -- verification params. With regards to the block header function -- 'Pos.Types.Blocks.Functions.verifyHeader', the blockheaders that may be -- part of the verification parameters are guaranteed to be valid, as are the -- slot leaders and the current slot. data HeaderAndParams = HeaderAndParams { hapHeader :: Block.BlockHeader , hapParams :: Block.VerifyHeaderParams } deriving (Eq, Show) -- This generator produces a header and a set of params for testing that header. genHeaderAndParams :: ProtocolMagic -> ConsensusEra -> Gen HeaderAndParams genHeaderAndParams pm era = do -- This Int is used as a seed to randomly choose a slot down below seed <- arbitrary :: Gen Int -- If the blkSecurityParam is too low (ie < 10) then ObftLenient is likely -- to fail. blkSecurityParam <- BlockCount <$> choose (10, 50) slotsPerEpoch <- SlotCount . (getBlockCount blkSecurityParam *) <$> choose (2, 10) startSlot <- SlotId <$> choose (0, bhlMaxStartingEpoch) <*> (UnsafeLocalSlotIndex <$> choose (0, fromIntegral (getSlotCount slotsPerEpoch) - 1)) -- Create up to 10 slots, and trim them later. slotCount <- choose (2, 10) headers <- reverse . fst . getHeaderList <$> generateBHL pm era dummyGenesisHash True startSlot slotCount -- 'skip' is the random number of headers that should be skipped in -- the header chain. This ensures different parts of it are chosen -- each time. skip <- choose (0, length headers - 2) let (prev, header) = case take 2 $ drop skip headers of [h] -> (Nothing, h) [h1, h2] -> (Just h1, h2) [] -> error "[BlockSpec] empty headerchain" _ -> error "[BlockSpec] the headerchain doesn't have enough headers" -- A helper function. Given integers 'x' and 'y', it chooses a -- random integer in the interval [x, y] betweenXAndY :: Random a => a -> a -> a betweenXAndY x y = fst . randomR (x, y) $ mkStdGen seed -- One of the fields in the 'VerifyHeaderParams' type is 'Just -- SlotId'. The following binding is where it is calculated. randomSlotBeforeThisHeader = case header of -- If the header is of the genesis kind, this field is -- not needed. Block.BlockHeaderGenesis _ -> Nothing -- If it's a main blockheader, then a valid "current" -- SlotId for testing is any with an epoch greater than -- the header's epoch and with any slot index, or any in -- the same epoch but with a greater or equal slot index -- than the header. Block.BlockHeaderMain h -> let (SlotId e s) = view Block.headerSlotL h rndEpoch :: Core.EpochIndex rndEpoch = betweenXAndY e maxBound rndSlotIdx :: LocalSlotIndex rndSlotIdx = if rndEpoch > e then betweenXAndY localSlotIndexMinBound (localSlotIndexMaxBound slotsPerEpoch) else betweenXAndY s (localSlotIndexMaxBound slotsPerEpoch) rndSlot = SlotId rndEpoch rndSlotIdx in Just rndSlot hasUnknownAttributes = not . areAttributesKnown $ case header of Block.BlockHeaderGenesis h -> h ^. Block.gbhExtra . Block.gehAttributes Block.BlockHeaderMain h -> h ^. Block.gbhExtra . Block.mehAttributes thisEpochLeaderSchedule :: Maybe (NonEmpty (Core.AddressHash PublicKey)) thisEpochLeaderSchedule = mkEpochLeaderSchedule era (getEpochOrSlot header) headers params = Block.VerifyHeaderParams { Block.vhpPrevHeader = prev , Block.vhpCurrentSlot = randomSlotBeforeThisHeader , Block.vhpLeaders = case era of Original -> OriginalLeaders <$> thisEpochLeaderSchedule OBFT ObftStrict -> ObftStrictLeaders <$> thisEpochLeaderSchedule OBFT ObftLenient -> pure $ ObftLenientLeaders (Set.fromList $ mapMaybe (fmap Core.addressHash . Block.headerLeaderKey) headers) blkSecurityParam (LastBlkSlots.updateMany (LastBlkSlots.create (fromIntegral $ getBlockCount blkSecurityParam)) . OldestFirst $ mapMaybe (headerLastSlotInfo slotsPerEpoch) headers) , Block.vhpMaxSize = Just (biSize header) , Block.vhpVerifyNoUnknown = not hasUnknownAttributes , Block.vhpConsensusEra = era } return $ HeaderAndParams header params -- Pad the head of a list of block headers to generate a list that is long enough -- to index correctly during validation. Use the EpochOrSlot of the target -- BlockHeader to and the header index to calculate the number of fake leader -- keys to prepend to the header mkEpochLeaderSchedule :: ConsensusEra -> EpochOrSlot -> [Block.BlockHeader] -> Maybe (NonEmpty (Core.AddressHash PublicKey)) mkEpochLeaderSchedule era eos hdrs = case List.elemIndex eos (map getEpochOrSlot hdrs) of Nothing -> Nothing Just idx -> let count = prependCount idx in nonEmpty . (if count >= 0 then (replicate count fakeLeaderKey ++) else List.drop (- count - extra) ) $ mapMaybe (fmap Core.addressHash . Block.headerLeaderKey) hdrs where fakeLeaderKey :: Core.AddressHash PublicKey fakeLeaderKey = Core.unsafeAddressHash ("fake leader key" :: ByteString) prependCount :: Int -> Int prependCount idx = fromIntegral (getSlotIndex . siSlot $ epochOrSlotToSlot eos) - idx -- Need this because in the validation code, the indexing for the slot -- leader schedule starts at 1 for the Original chain (due to the epoch -- boundary block) but at 0 for ObftStrict. extra :: Int extra = case era of Original -> 1 OBFT ObftStrict -> 0 OBFT ObftLenient -> -- This should never happen. Prelude.error "Test.Pos.Chain.Block.Arbitrary.mkEpochLeaderSchedule ObftLenient" -- | A lot of the work to generate a valid sequence of blockheaders has -- already been done in the 'Arbitrary' instance of the 'BlockHeaderList' -- type, so it is used here and at most 3 blocks are taken from the generated -- list. instance Arbitrary HeaderAndParams where arbitrary = do pm <- arbitrary era <- arbitrary genHeaderAndParams pm era
input-output-hk/pos-haskell-prototype
chain/test/Test/Pos/Chain/Block/Arbitrary.hs
mit
23,124
0
25
6,267
4,134
2,216
1,918
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Database.Dblp -- Description : Communication protocols for dblp -- Maintainer : coskuacay@gmail.com -- Stability : experimental ----------------------------------------------------------------------------- module Database.Dblp (fetchString) where import Control.Monad.Except import Control.Monad.IO.Class (MonadIO (..)) import Network.Curl.Download (openURIString) import Args (BibSize (..)) import Reference import Utility.Except fetchString :: (MonadError String m, MonadIO m) => BibSize -> SourceKey -> m String fetchString size key = do res <- liftIO $ openURIString (getUrl size key) liftEither res getUrl :: BibSize -> SourceKey -> String getUrl size (SourceKey key) = "http://dblp.uni-trier.de/rec/" ++ parseSize size ++ "/" ++ key ++ ".bib" where parseSize :: BibSize -> String parseSize Condensed = "bib0" parseSize Standard = "bib1" parseSize Crossref = "bib2"
cacay/bibdb
src/Database/Dblp.hs
mit
1,017
0
11
164
225
125
100
-1
-1
module GHCJS.DOM.FocusEvent ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/FocusEvent.hs
mit
40
0
3
7
10
7
3
1
0
module Glucose.Parser where import Control.Applicative hiding ((<**>)) import Control.Comonad import Control.Lens hiding (traverse1) import Data.Monoid import Glucose.AST as AST import Glucose.Error import Glucose.Identifier as AST hiding (identifier) import Glucose.Lexer.Location import Glucose.Token as Token import Glucose.Parser.EOFOr import Glucose.Parser.Monad import Glucose.Parser.Source infixl 4 <$$>, <$$, <**>, <**, **> (<$$>) :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b) (<$$>) = (<$>) . (<$>) (<$$) :: (Functor f, Functor g) => a -> f (g b) -> f (g a) a <$$ b = const a <$$> b (<**>) :: (Applicative f, Applicative g) => f (g (a -> b)) -> f (g a) -> f (g b) f <**> a = (<*>) <$> f <*> a (**>) :: (Applicative f, Applicative g) => f (g a) -> f (g b) -> f (g b) a **> b = flip const <$$> a <**> b (<**) :: (Applicative f, Applicative g) => f (g a) -> f (g b) -> f (g a) a <** b = const <$$> a <**> b type Parse a = Parser Location (FromSource Token) [FromSource Token] (FromSource a) parse :: (MonadThrow (ParseError Location (FromSource Token)) m) => Location -> [FromSource Token] -> m Module parse eofLocation = runParser parser (maybeEOF eofLocation startLocation) where parser = Module <$> many ((definition <|> typeDefinition) <* endOfDefinition) <* eof definition :: Parse AST.Definition definition = AST.Definition <$$> name <**> expr where name = duplicate <$> identifier <* operator Assign expr = duplicate <$> expression typeDefinition :: Parse AST.Definition typeDefinition = AST.TypeDefinition <$$ keyword Type <**> name <**> constructors where name = duplicate <$> identifier <* operator Assign constructors = traverse1 duplicate <$> identifier `separatedBy` operator Bar expression :: Parse AST.Expression expression = AST.Variable <$$> identifier <|> AST.Literal <$$> literal endOfDefinition :: Parse () endOfDefinition = (lexeme "end of definition" . traverse $ is _endOfDefinition) <|> pure <$> eof identifier :: Parse AST.Identifier identifier = lexeme "identifier" . traverse $ AST.Identifier <$$> preview _identifier keyword :: Keyword -> Parse () keyword kw = lexeme ("\"" ++ show kw ++ "\"") . traverse . is $ _keyword . filtered (kw ==) operator :: Operator -> Parse () operator op = lexeme ("\"" ++ show op ++ "\"") . traverse . is $ _operator . filtered (op ==) literal :: Parse Literal literal = lexeme "literal" . traverse $ \t -> integerLiteral t <|> floatLiteral t where integerLiteral = AST.IntegerLiteral . fromInteger <$$> preview _integerLiteral floatLiteral = AST.FloatLiteral . fromRational <$$> preview _floatLiteral beginLambda :: Parse () beginLambda = lexeme "lambda" (traverse $ is _beginLambda) is :: Getting (First ()) s a -> s -> Maybe () is a = preview $ a . like ()
sardonicpresence/glucose
src/Glucose/Parser.hs
mit
2,857
0
13
568
1,137
595
542
-1
-1
{-| - A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, - - a2 + b2 = c2 - For example, 32 + 42 = 9 + 16 = 25 = 52. - - There exists exactly one Pythagorean triplet for which a + b + c = 1000. - Find the product abc. - -} tripletProduct n = head $ take 1 [a*b*c | a <- [1..n-2], b <- [a..(n-a-1)], c <- [n-a-b], a^2 + b^2 == c^2] --tripletProduct 1000
MakerBar/haskell-euler
9/9.hs
mit
390
0
13
98
115
60
55
1
1
module Main where import Kernel import Runtime import Parser import Control.Monad.Trans.State run :: [Expression] -> IO Value run expressions = do let action = sequence (map lispEval expressions) (result, _) <- runStateT action globalEnvironment return (last result) fromStr :: String -> IO Value fromStr input = run . parseProgram $ input
patrickgombert/Hisp
Main.hs
mit
350
0
12
61
121
63
58
12
1
--------------------------------------------------------------- -- -- Module: Quark.Frontend.HSCurses -- Author: Stefan Peterson -- License: MIT License -- -- Maintainer: Stefan Peterson (stefan.j.peterson@gmail.com) -- Stability: Stable -- Portability: Unknown -- -- ---------------------------------------------------------- -- -- Frontend module for HSCurses -- --------------------------------------------------------------- module Quark.Frontend.HSCurses ( Window ( TitleBar , UtilityBar , TextView , ProjectView ) , windowSize , setTextColor , addString , mvAddString , move , clear , clear' , refresh , wOffset , wSetOffset , Layout ( MinimalLayout , BasicLayout , HSplitLayout , VSplitLayout ) , windowList , titleBar , utilityBar , primaryPane , secondaryPane , projectPane , start , end , onResize , getKey , updateCursor , showCursor , hideCursor , defaultLayout , basicLayout , minimalLayout , vSplitLayout , hSplitLayout , layoutWidth , projectPaneWidth ) where import qualified UI.HSCurses.Curses as Curses import Data.Char ( isPrint , ord ) import Quark.Colors import Quark.Types ( Key ( CharKey , WideCharKey , CtrlKey , FnKey , SpecialKey , ResizeKey , InvalidKey ) , ColorPair , Cursor , Offset , Size ) import Quark.Settings ( lineWidthHint ) import System.Posix.Signals ( Handler ( Catch ) , installHandler ) ----------------------------- -- Start and end functions -- ----------------------------- start :: IO () start = do Curses.initScr hasColors <- Curses.hasColors if hasColors then do Curses.startColor Curses.useDefaultColors defineColors else return () Curses.resetParams Curses.wclear Curses.stdScr Curses.refresh Curses.keypad Curses.stdScr True case (Curses.cursesSigWinch, Curses.keyResizeCode) of (Just sig, Just key) -> do installHandler sig (Catch $ sigwinch sig key) Nothing return () _ -> return () where sigwinch sig key = do Curses.ungetCh key -- installHandler sig (Catch $ sigwinch sig key) Nothing return () end :: IO () end = Curses.endWin onResize :: IO () onResize = do Curses.endWin Curses.werase Curses.stdScr Curses.refresh ------------ -- getKey -- ------------ getKey :: IO Key getKey = translateKey' =<< Curses.getCh translateKey' :: Curses.Key -> IO Key translateKey' (Curses.KeyChar c) | ord c >= 240 = WideCharKey <$> (c:) <$> getMoreChars 3 | ord c >= 224 = WideCharKey <$> (c:) <$> getMoreChars 2 | ord c >= 192 = WideCharKey <$> (c:) <$> getMoreChars 1 translateKey' k = return $ translateKey k getMoreChars :: Int -> IO String getMoreChars n | n <= 0 = return "" | otherwise = do k <- Curses.getCh case k of (Curses.KeyChar c) -> (c:) <$> (getMoreChars (n - 1)) _ -> Curses.ungetCh 1 >> return "" translateKey :: Curses.Key -> Key translateKey k@(Curses.KeyChar c) | c == '\r' = SpecialKey "Return" | c == '\DEL' = SpecialKey "Backspace" | c == '\t' = SpecialKey "Tab" | c == '\ESC' = SpecialKey "Esc" | c == '\SOH' = CtrlKey 'a' | c == '\STX' = CtrlKey 'b' | c == '\ETX' = CtrlKey 'c' | c == '\EOT' = CtrlKey 'd' | c == '\ENQ' = CtrlKey 'e' | c == '\ACK' = CtrlKey 'f' | c == '\a' = CtrlKey 'g' -- | c == '\t' = CtrlKey 'i' -- identical to Tab | c == '\n' = CtrlKey 'j' | c == '\v' = CtrlKey 'k' | c == '\f' = CtrlKey 'l' -- | c == '\r' = CtrlKey 'm' -- identical to Return | c == '\SO' = CtrlKey 'n' | c == '\SI' = CtrlKey 'o' | c == '\DLE' = CtrlKey 'p' | c == '\DC1' = CtrlKey 'q' | c == '\DC2' = CtrlKey 'r' | c == '\DC3' = CtrlKey 's' | c == '\DC4' = CtrlKey 't' | c == '\NAK' = CtrlKey 'u' | c == '\SYN' = CtrlKey 'v' | c == '\ETB' = CtrlKey 'w' | c == '\CAN' = CtrlKey 'x' | c == '\EM' = CtrlKey 'y' | c == '\SUB' = CtrlKey 'z' | otherwise = if isPrint c then CharKey c else InvalidKey $ show k translateKey k = case k of Curses.KeyDC -> SpecialKey "Delete" Curses.KeySDC -> SpecialKey "Shift-Delete" Curses.KeyBTab -> SpecialKey "Shift-Tab" Curses.KeyHome -> SpecialKey "Home" Curses.KeySHome -> SpecialKey "Shift-Home" Curses.KeyUnknown 538 -> SpecialKey "Ctrl-Home" Curses.KeyUnknown 539 -> SpecialKey "Ctrl-Shift-Home" Curses.KeyEnd -> SpecialKey "End" Curses.KeySEnd -> SpecialKey "Shift-End" Curses.KeyUnknown 533 -> SpecialKey "Ctrl-End" Curses.KeyUnknown 534 -> SpecialKey "Ctrl-Shift-End" Curses.KeyPPage -> SpecialKey "PgUp" Curses.KeySPrevious -> SpecialKey "Shift-PgUp" Curses.KeyNPage -> SpecialKey "PgDn" Curses.KeySNext -> SpecialKey "Shift-PgDn" Curses.KeyIC -> SpecialKey "Insert" Curses.KeyUp -> SpecialKey "Up" Curses.KeyUnknown 573 -> SpecialKey "Ctrl-Up" Curses.KeyUnknown 574 -> SpecialKey "Ctrl-Shift-Up" Curses.KeyDown -> SpecialKey "Down" Curses.KeyUnknown 530 -> SpecialKey "Ctrl-Down" Curses.KeyUnknown 531 -> SpecialKey "Ctrl-Shift-Down" Curses.KeyLeft -> SpecialKey "Left" Curses.KeySLeft -> SpecialKey "Shift-Left" Curses.KeyUnknown 552 -> SpecialKey "Ctrl-Left" Curses.KeyUnknown 553 -> SpecialKey "Ctrl-Shift-Left" Curses.KeyRight -> SpecialKey "Right" Curses.KeySRight -> SpecialKey "Shift-Right" Curses.KeyUnknown 567 -> SpecialKey "Ctrl-Right" Curses.KeyUnknown 568 -> SpecialKey "Ctrl-Shift-Right" Curses.KeyBackspace -> CtrlKey 'h' Curses.KeyResize -> ResizeKey Curses.KeyF k -> FnKey k _ -> InvalidKey $ show k --------------------- -- Color functions -- --------------------- cursesPair :: ColorPair -> Int cursesPair (x, y) | (x, y) == ((-1), (-1)) = 0 | (x, y) == lineNumberPair = lineNumberInt | (x, y) == titleBarPair = titleBarInt | (x, y) == treeDefaultPair = treeDefaultInt | (x, y) == treeActivePair = treeActiveInt | y == (-1) = x | y == selectionColor = x + if x == (-1) then 18 else 17 | y == highlightColor = x + if x == (-1) then 35 else 34 | x == y = errorColorInt | otherwise = x defineColors :: IO () defineColors = do nColors <- Curses.colors mapM_ (\(n, f, b) -> defineColor n f b) $ colorTriples nColors where defineColor n f b = Curses.initPair (Curses.Pair n) (Curses.Color f) (Curses.Color b) ---------------------- -- Cursor functions -- ---------------------- updateCursor :: Window -> Offset -> Cursor -> IO () updateCursor (TextView w _ _) (x0, y0) (x, y) = Curses.wMove w (x - x0) (y - y0) updateCursor (UtilityBar w (rr, cc)) (r, c) (_, y) = Curses.wMove w (min r rr) (min (y + c) cc) showCursor :: IO Curses.CursorVisibility showCursor = Curses.cursSet Curses.CursorVisible hideCursor :: IO Curses.CursorVisibility hideCursor = Curses.cursSet Curses.CursorInvisible ------------------------------- -- Window type and functions -- ------------------------------- data Window = TitleBar Curses.Window Size | UtilityBar Curses.Window Size | TextView Curses.Window Size Offset | ProjectView Curses.Window Size Int deriving Show cursesWindow :: Window -> Curses.Window cursesWindow (TitleBar w _) = w cursesWindow (UtilityBar w _) = w cursesWindow (TextView w _ _) = w cursesWindow (ProjectView w _ _) = w windowSize :: Window -> Size windowSize (TitleBar _ s) = s windowSize (UtilityBar _ s) = s windowSize (TextView _ s _) = s windowSize (ProjectView _ s _) = s setTextColor :: Window -> ColorPair -> IO () setTextColor w pair = Curses.wAttrSet (cursesWindow w) ( Curses.attr0 , Curses.Pair $ cursesPair pair ) addString :: Window -> String -> IO () addString = Curses.wAddStr . cursesWindow mvAddString :: Window -> Int -> Int -> String -> IO () mvAddString = Curses.mvWAddStr . cursesWindow move :: Window -> Int -> Int -> IO () move = Curses.wMove . cursesWindow refresh :: Window -> IO () refresh = Curses.wRefresh . cursesWindow clear :: Window -> IO () clear = Curses.werase . cursesWindow clear' :: Window -> Int -> IO () clear' t@(TextView w (r, c) (_, cc)) k | rulerCol >= c || rulerCol < cc = Curses.werase w | otherwise = do Curses.werase w setTextColor t rulerPair mapM_ (\x -> Curses.mvWAddStr w x 0 rulerLine) $ take r [0..] Curses.wMove w 0 0 where rulerCol = length rulerLine rulerLine = drop cc (replicate (lineWidthHint + k) ' ') ++ "\9474" wOffset :: Window -> Offset wOffset (TextView _ _ offset') = offset' wOffset _ = (0, 0) wSetOffset :: Offset -> Window -> Window wSetOffset offset' (TextView w s _) = TextView w s offset' wSetOffset offset' w = w ------------------------------- -- Layout type and functions -- ------------------------------- data Layout = MinimalLayout { titleBar :: Window , utilityBar :: Window , primaryPane :: Window , projectPaneWidth' :: Int } | BasicLayout { titleBar :: Window , utilityBar :: Window , projectPane :: Window , primaryPane :: Window } | VSplitLayout { titleBar :: Window , utilityBar :: Window , projectPane :: Window , primaryPane :: Window , secondaryPane :: Window } | HSplitLayout { titleBar :: Window , utilityBar :: Window , projectPane :: Window , primaryPane :: Window , secondaryPane :: Window } deriving Show windowList :: Layout -> [Window] windowList (MinimalLayout a b c _) = [a, b, c] windowList (BasicLayout a b c d) = [a, b, c, d] windowList (VSplitLayout a b c d e) = [a, b, c, d, e] windowList (HSplitLayout a b c d e) = [a, b, c, d, e] layoutWidth :: Layout -> Int layoutWidth = snd . windowSize . titleBar projectPaneWidth :: Layout -> Int projectPaneWidth (MinimalLayout _ _ _ c) = c projectPaneWidth layout = ((1 +) . snd . windowSize . projectPane) layout defaultLayout :: Int -> IO Layout defaultLayout k = do (r, c) <- Curses.scrSize let dpWidth = if k < 0 then min 24 (c -32) else k layout <- if c > 85 + 16 then basicLayout dpWidth else minimalLayout dpWidth return layout basicLayout :: Int -> IO Layout basicLayout dpWidth = do (r, c) <- Curses.scrSize let dpWidth' = min dpWidth (div c 2) - 1 let mainHeight = r - 4 let mainWidth = c - dpWidth cTitleBar <- Curses.newWin 2 c 0 0 cUtilityBar <- Curses.newWin 2 c (r - 2) 0 cDirectoryPane <- Curses.newWin mainHeight dpWidth' 2 0 cMainView <- Curses.newWin mainHeight mainWidth 2 dpWidth let qTitleBar = TitleBar cTitleBar (1, c) let qUtilityBar = UtilityBar cUtilityBar (1, c) let qDirectoryPane = ProjectView cDirectoryPane (mainHeight, dpWidth') 0 let qPrimaryPane = TextView cMainView (mainHeight, mainWidth) (0, 0) return $ BasicLayout qTitleBar qUtilityBar qDirectoryPane qPrimaryPane minimalLayout :: Int -> IO Layout minimalLayout dpWidth = do (r, c) <- Curses.scrSize let mainHeight = r - 4 cTitleBar <- Curses.newWin 2 c 0 0 cUtilityBar <- Curses.newWin 2 c (r - 2) 0 cMainView <- Curses.newWin mainHeight c 2 0 let qTitleBar = TitleBar cTitleBar (1, c) let qUtilityBar = UtilityBar cUtilityBar (1, c) let qPrimaryPane = TextView cMainView (mainHeight, c) (0, 0) return $ MinimalLayout qTitleBar qUtilityBar qPrimaryPane $ min dpWidth (div c 2) - 1 vSplitLayout :: IO Layout vSplitLayout = do (r, c) <- Curses.scrSize let dpWidth = min 24 (c - 32) let dpWidth' = dpWidth - 1 let mainHeight = r - 4 let secondaryWidth = div (c - dpWidth) 2 let primaryWidth = c - dpWidth - secondaryWidth cTitleBar <- Curses.newWin 2 c 0 0 cUtilityBar <- Curses.newWin 2 c (r - 2) 0 cDirectoryPane <- Curses.newWin mainHeight dpWidth' 2 0 cPrimaryPane <- Curses.newWin mainHeight primaryWidth 2 dpWidth cSecondaryPane <- Curses.newWin mainHeight secondaryWidth 2 (dpWidth + primaryWidth) let qTitleBar = TitleBar cTitleBar (1, c) let qUtilityBar = UtilityBar cUtilityBar (1, c) let qDirectoryPane = ProjectView cDirectoryPane (mainHeight, dpWidth') 0 let qPrimaryPane = TextView cPrimaryPane (mainHeight, primaryWidth) (0, 0) let qSecondaryPane = TextView cSecondaryPane (mainHeight, secondaryWidth) (0, 0) return $ VSplitLayout qTitleBar qUtilityBar qDirectoryPane qPrimaryPane qSecondaryPane hSplitLayout :: IO Layout hSplitLayout = do (r, c) <- Curses.scrSize let dpWidth = min 24 (c - 32) let dpWidth' = dpWidth - 1 let mainHeight = r - 4 let secondaryHeight = div mainHeight 2 let primaryHeight = mainHeight - secondaryHeight let mainWidth = c - dpWidth cTitleBar <- Curses.newWin 2 c 0 0 cUtilityBar <- Curses.newWin 2 c (r - 2) 0 cDirectoryPane <- Curses.newWin mainHeight dpWidth' 2 0 cPrimaryPane <- Curses.newWin primaryHeight mainWidth 2 dpWidth cSecondaryPane <- Curses.newWin secondaryHeight mainWidth (2 + primaryHeight) dpWidth let qTitleBar = TitleBar cTitleBar (1, c) let qUtilityBar = UtilityBar cUtilityBar (1, c) let qDirectoryPane = ProjectView cDirectoryPane (mainHeight, dpWidth') 0 let qPrimaryPane = TextView cPrimaryPane (primaryHeight, mainWidth) (0, 0) let qSecondaryPane = TextView cSecondaryPane (secondaryHeight, mainWidth) (0, 0) return $ HSplitLayout qTitleBar qUtilityBar qDirectoryPane qPrimaryPane qSecondaryPane
sjpet/quark
src/Quark/Frontend/HSCurses.hs
mit
15,703
0
15
5,336
4,566
2,311
2,255
343
35
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} module Graph.Bisekt.Plain where -- $Id$ import Graph.Bisekt.Data import Graph.Util import Autolib.Dot ( peng, Layout_Program (..) ) import Autolib.Graph.Adj ( adjazenz_matrix , schoen ) import Autolib.Graph.Ops ( unlinks ) import Autolib.Xml import Autolib.Reader import Autolib.Set import Inter.Types import Autolib.Set import qualified Challenger as C import qualified Autolib.Reporter.Set import Data.Typeable data Bisect = Bisect deriving ( Eq, Ord, Show, Read, Typeable ) instance OrderScore Bisect where scoringOrder _ = Increasing instance ( GraphC a, Show a) => C.Partial Bisect (Int, Graph a) (Solution a) where report _ (_,g) = do inform $ vcat $ map text [ "Gegeben ist die Adjazenzmatrix" , schoen $ adjazenz_matrix g , "des Graphen G." , "Gesucht ist eine Kantenmenge M von Kanten von G, die G bisektiert." , "" , "Eine Kantenmenge M bisektiert G, wenn durch Entfernen von M der Graph G in zwei Teilgraphen zerfällt," , "die sich in ihrer Knotenzahl um höchstens 1 unterscheiden und zwischen denen keine Kanten verlaufen." , "" , "Sie sollen die Kantenmenge M und die Knotenmengen der beiden Teilgraphen angeben." ] initial _ (w,g) = let ks = head $ drop w $ teilmengen (pred w) (kanten g) n = cardinality (knoten g) ns = head $ drop (div n 2) $ teilmengen (div n 2) (knoten g) in Solution { schnittkanten = ks , knoten1 = ns , knoten2 = knoten g `minusSet` ns } partial _ (_,g) (Solution { schnittkanten =ks, knoten1=l,knoten2=r} ) = do inform $ text "Unterscheiden sich die Knotenanzahlen höchstens um 1?" when ( abs ((cardinality l) - (cardinality r)) > 1 ) $ reject $ text "Nein." inform $ text "Ja." let s1 = ( text "Kantenmenge E(G) des Graphen" , kanten g ) s2 = ( text "Kantenmenge M in Ihrer Lösung" , ks ) Autolib.Reporter.Set.subeq s2 s1 let sl = ( text "Erste Knotenmenge in Ihrer Lösung" , l ) sr = ( text "Zweite Knotenmenge in Ihrer Lösung" , r ) sk = ( text "Knotenmenge des Graphen" , knoten g ) Autolib.Reporter.Set.partition [sl,sr] sk total _ (_,g) (Solution { schnittkanten =ks, knoten1=l,knoten2=r}) = do let u = unlinks g $ setToList ks inform $ text "Der Graph, der durch Entfernen der Kanten in Ihrer Lösung entsteht, hat die Gestalt:" peng $ u { layout_program = Circo , layout_hints = [ "-Nshape=ellipse" , "-Gsize=\"5,5\"" ] } inform $ vcat [ text "Verlaufen keine Kanten zwischen den Knotenmengen" , nest 4 $ toDoc l , text "und" , nest 4 $ toDoc r , text "?" ] let no = do nl <- setToList l nr <- setToList r guard $ or [ kante nl nr `elementOf` kanten u , kante nr nl `elementOf` kanten u ] return (nl,nr) when ( not $ null no ) $ reject $ vcat [ text "Nein, diese Knoten sind durch eine Kante miteinander verbunden:" , nest 4 $ toDoc $ mkSet no ] inform $ text "Ja." instance ( GraphC a, Show a ) => C.Measure Bisect (Int, Graph a) (Solution a) where measure _ _ s = fromIntegral $ cardinality $ schnittkanten s {- instance ( Ord a , ToDoc a, ToDoc [a] , Reader a , Reader [a] ) => Container (Set (Kante a),Set a,Set a) String where label _ = "(Kantenmenge,Knotenmenge,Knotenmenge)" pack = show unpack = read -} ------------------------------------------------------------------------------- make :: Make make = direct Bisect ( 5 :: Int, mkGraph (mkSet ns) (mkSet es) ) where ns = [ 1..6 ] :: [Int] es = map (uncurry kante) [ (1,2) ,(1,4),(1,5) ,(2,1) ,(2,3) ,(2,5),(2,6) ,(3,2) ,(3,4),(3,5),(3,6) ,(4,1) ,(4,3) ,(4,5) ,(5,1),(5,2),(5,3),(5,4) ,(5,6) ,(6,2),(6,3) ,(6,5) ]:: [ Kante Int ]
Erdwolf/autotool-bonn
src/Graph/Bisekt/Plain.hs
gpl-2.0
4,030
60
18
1,116
973
611
362
84
1
{-# LANGUAGE OverloadedStrings #-} module Nirum.Constructs.Docs ( Docs (Docs) , docsAnnotationName , docsAnnotationParameter , title , toBlock , toCode , toCodeWithPrefix , toText ) where import Data.String (IsString (fromString)) import qualified Data.Text as T import Nirum.Constructs (Construct (toCode)) import Nirum.Constructs.Identifier (Identifier) import Nirum.Docs (Block (Document, Heading), parse) docsAnnotationName :: Identifier docsAnnotationName = "docs" docsAnnotationParameter :: Identifier docsAnnotationParameter = "docs" -- | Docstring for constructs. newtype Docs = Docs T.Text deriving (Eq, Ord, Show) -- | Convert the docs to a tree. toBlock :: Docs -> Block toBlock (Docs docs') = parse docs' -- | Gets the heading title of the module if it has any title. title :: Docs -> Maybe Block title docs = case toBlock docs of Document (firstBlock@Heading {} : _) -> Just firstBlock _ -> Nothing -- | Convert the docs to text. toText :: Docs -> T.Text toText (Docs docs') = docs' -- | Similar to 'toCode' except it takes 'Maybe Docs' instead of 'Docs'. -- If the given docs is 'Nothing' it simply returns an empty string. -- Otherwise it returns a code string with the prefix. toCodeWithPrefix :: T.Text -- ^ The prefix to be prepended if not empty. -> Maybe Docs -- ^ The docs to convert to code. -> T.Text toCodeWithPrefix _ Nothing = "" toCodeWithPrefix prefix (Just docs') = T.append prefix $ toCode docs' instance Construct Docs where toCode (Docs docs') = let d = if "\n" `T.isSuffixOf` docs' then T.dropEnd 1 docs' else docs' in T.append "# " $ T.replace "\n" "\n# " d instance IsString Docs where fromString s = let t = T.pack s in Docs (if "\n" `T.isSuffixOf` t then t else t `T.snoc` '\n')
dahlia/nirum
src/Nirum/Constructs/Docs.hs
gpl-3.0
2,195
0
12
758
462
258
204
46
2
{- Copyright 2013 Matthew Gordon. This file is part of Gramophone. Gramophone is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gramophone is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Gramophone. If not, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE TypeFamilies, QuasiQuotes, MultiParamTypeClasses, TemplateHaskell, OverloadedStrings #-} module Gramophone.GUI.BrowseForFiles (getBrowseForFilesR) where import Prelude hiding (concat) import Gramophone.GUI.Foundation import Yesod (addScriptRemote, newIdent, toWidget, hamlet, cassius, julius, Html, defaultLayout, liftIO, notFound, permissionDenied, setTitle, whamlet) import Text.Julius (rawJS) import System.FilePath (takeFileName, combine) import System.Directory (getDirectoryContents, doesFileExist, doesDirectoryExist) import System.IO.Error (isDoesNotExistError, isPermissionError) import Data.List (sort) import Control.Exception (try) import Control.Monad(liftM, filterM) import Data.Text (pack, concat) fileListWidget :: [FilePath] -> Widget fileListWidget files = do fileListID <- newIdent toWidget [hamlet| <div> <h2>Files: <ol id="#{fileListID}"> $forall file <- sort files <li>#{takeFileName file}|] toWidget [cassius| ol##{fileListID} list-style-type: none|] dirListWidget :: [FilePath] -> Widget dirListWidget dirs = do addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" divID <- newIdent dirListID <- newIdent toWidget [hamlet| <div id="#{divID}"> <h2>Subfolders: <ol id="#{dirListID}"> $forall dir <- sort dirs <li><a href=@{BrowseForFilesR (RawFilePath dir)}>#{takeFileName dir}</a> <br>|] toWidget [cassius| ol##{dirListID} list-style-type:none ol##{dirListID} li float: left min-width: 5em white-space: nowrap div##{divID} br clear: left div##{divID} margin-bottom: 1em|] -- This javascript finds the largest width of any list item (directory name) and sets the width -- of all the list items to that width. Together with the above CSS, this creates a multi-column -- list where the columns are always wide enough to accomodate their contents. Each column has -- a minumum width of 5 ems. toWidget [julius| $('ol##{rawJS dirListID}').ready(function() { elementWidth = Math.max.apply( null, $('ol##{rawJS dirListID} > li').map( function() { return $(this).innerWidth(true); }).get() ); $('ol##{rawJS dirListID} > li').width(elementWidth); });|] getBrowseForFilesR :: RawFilePath -> Handler Html getBrowseForFilesR (RawFilePath path) = defaultLayout $ do dirContentsOrError <- liftIO $ try $ (liftM $ map $ combine path) $ getDirectoryContents path case dirContentsOrError of Left e | isDoesNotExistError e -> notFound | isPermissionError e -> permissionDenied $ concat ["You are not allowed access to \"", (pack path), "\""] | otherwise -> notFound Right dirContents -> do setTitle "Gramophone - Browse Filesystem" toWidget [hamlet|<h1>#{path}|] files <- liftIO $ filterM doesFileExist $ map (combine path) dirContents fileListWidget files subDirs <- liftIO $ filterM doesDirectoryExist $ map (combine path) dirContents dirListWidget subDirs [whamlet|<div><a href=@{TestR}>Back to testing functions</a>|]
matthewscottgordon/gramophone
src/Gramophone/GUI/BrowseForFiles.hs
gpl-3.0
4,192
0
17
1,087
529
287
242
43
2
module Amoeba.View.Output.Types where import Data.Word (Word16) type ViewPointCoordinates = (Int, Int) type UserViewPoint = ViewPointCoordinates type ScreenPoint = (Word16, Word16) data Screen = Screen Int Int Int
graninas/The-Amoeba-World
src/Amoeba/View/Output/Types.hs
gpl-3.0
219
0
6
32
61
39
22
6
0
{-| Module : Hypercube.Input Description : Input handling Copyright : (c) Jaro Reinders, 2017 License : GPL-3 Maintainer : noughtmare@openmailbox.org This module contains all input handling code. -} module Hypercube.Input where import Hypercube.Types import Control.Monad.Trans.State import Control.Monad.IO.Class import Control.Lens import Control.Monad import Linear import qualified Graphics.UI.GLFW as GLFW toggleCursor :: GLFW.Window -> IO () toggleCursor win = do currentMode <- GLFW.getCursorInputMode win GLFW.setCursorInputMode win $ case currentMode of GLFW.CursorInputMode'Normal -> GLFW.CursorInputMode'Disabled _ -> GLFW.CursorInputMode'Normal keyCallback :: GLFW.Window -> GLFW.Key -> Int -> GLFW.KeyState -> GLFW.ModifierKeys -> IO () keyCallback win GLFW.Key'R _ GLFW.KeyState'Pressed _ = toggleCursor win keyCallback _ _ _ _ _ = return () keyboard :: GLFW.Window -> Float -> StateT Game IO () keyboard win deltaTime = do let handle :: (GLFW.KeyState -> Bool) -> GLFW.Key -> StateT Game IO () -> StateT Game IO () handle f key action = f <$> liftIO (GLFW.getKey win key) >>= \x -> when x action isPressed GLFW.KeyState'Pressed = True isPressed _ = False moveAmount <- (deltaTime *) <$> use (cam . speed) curJaw <- use (cam . jaw) let forward = moveAmount *^ rotate (axisAngle (V3 0 1 0) curJaw) (V3 0 0 (-1)) right = moveAmount *^ rotate (axisAngle (V3 0 1 0) curJaw) (V3 1 0 0) up = moveAmount *^ V3 0 1 0 zipWithM_ (handle isPressed) [GLFW.Key'W, GLFW.Key'A, GLFW.Key'S, GLFW.Key'D, GLFW.Key'Space, GLFW.Key'LeftShift] (map (cam . camPos +=) [forward, -right, -forward, right, up, -up]) handle isPressed GLFW.Key'LeftControl $ cam . speed .= 50 handle (not . isPressed) GLFW.Key'LeftControl $ cam . speed .= 5 handle isPressed GLFW.Key'Escape $ liftIO $ GLFW.setWindowShouldClose win True mouse :: GLFW.Window -> Float -> StateT Game IO () mouse win deltaTime = do currentCursorPos <- fmap realToFrac . uncurry V2 <$> liftIO (GLFW.getCursorPos win) camSensitivity <- use (cam . sensitivity) prevCursorPos <- use cursorPos let cursorDelta = deltaTime * camSensitivity *^ (prevCursorPos - currentCursorPos) cursorPos .= currentCursorPos cam . jaw += cursorDelta ^. _x cam . pitch += cursorDelta ^. _y
noughtmare/hypercube
src/Hypercube/Input.hs
gpl-3.0
2,342
0
15
455
812
408
404
-1
-1
-- Copyright 2017 Keaton Bruce -- -- This file is part of MatrixRedux. -- -- MatrixRedux is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- MatrixRedux is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with MatrixRedux. If not, see <http://www.gnu.org/licenses/>. -- import MatrixFunctions import System.Environment -- Run this binary with the matrix as the first argument and do not include -- spaces in the matrix. A valid matrix would be [[4,0,3,5],[5,3,0,5],[0,0,3,6]] -- but an invalid matrix argument would be [[4, 0, 3, 5],[5,3,0,5],[0,0,3,6]]. -- Only the first argument is currently read. main = do args <- getArgs let matrix = args !! 0 putStrLn (show (simplify (read matrix)))
Karce/MatrixRedux
MatrixRun.hs
gpl-3.0
1,154
0
13
205
79
49
30
6
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.Compute.Projects.GetXpnHost -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the shared VPC host project that this project links to. May be -- empty if no link exists. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.projects.getXpnHost@. module Network.Google.Resource.Compute.Projects.GetXpnHost ( -- * REST Resource ProjectsGetXpnHostResource -- * Creating a Request , projectsGetXpnHost , ProjectsGetXpnHost -- * Request Lenses , pgxhProject ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.projects.getXpnHost@ method which the -- 'ProjectsGetXpnHost' request conforms to. type ProjectsGetXpnHostResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "getXpnHost" :> QueryParam "alt" AltJSON :> Get '[JSON] Project -- | Gets the shared VPC host project that this project links to. May be -- empty if no link exists. -- -- /See:/ 'projectsGetXpnHost' smart constructor. newtype ProjectsGetXpnHost = ProjectsGetXpnHost' { _pgxhProject :: Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsGetXpnHost' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pgxhProject' projectsGetXpnHost :: Text -- ^ 'pgxhProject' -> ProjectsGetXpnHost projectsGetXpnHost pPgxhProject_ = ProjectsGetXpnHost' {_pgxhProject = pPgxhProject_} -- | Project ID for this request. pgxhProject :: Lens' ProjectsGetXpnHost Text pgxhProject = lens _pgxhProject (\ s a -> s{_pgxhProject = a}) instance GoogleRequest ProjectsGetXpnHost where type Rs ProjectsGetXpnHost = Project type Scopes ProjectsGetXpnHost = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient ProjectsGetXpnHost'{..} = go _pgxhProject (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy ProjectsGetXpnHostResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Projects/GetXpnHost.hs
mpl-2.0
2,970
0
13
649
308
190
118
50
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.AppsLicensing -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Licensing API to view and manage license for your domain. -- -- /See:/ <https://developers.google.com/google-apps/licensing/ Enterprise License Manager API Reference> module Network.Google.AppsLicensing ( -- * Service Configuration appsLicensingService -- * OAuth Scopes , appsLicensingScope -- * API Declaration , AppsLicensingAPI -- * Resources -- ** licensing.licenseAssignments.delete , module Network.Google.Resource.Licensing.LicenseAssignments.Delete -- ** licensing.licenseAssignments.get , module Network.Google.Resource.Licensing.LicenseAssignments.Get -- ** licensing.licenseAssignments.insert , module Network.Google.Resource.Licensing.LicenseAssignments.Insert -- ** licensing.licenseAssignments.listForProduct , module Network.Google.Resource.Licensing.LicenseAssignments.ListForProduct -- ** licensing.licenseAssignments.listForProductAndSku , module Network.Google.Resource.Licensing.LicenseAssignments.ListForProductAndSKU -- ** licensing.licenseAssignments.patch , module Network.Google.Resource.Licensing.LicenseAssignments.Patch -- ** licensing.licenseAssignments.update , module Network.Google.Resource.Licensing.LicenseAssignments.Update -- * Types -- ** LicenseAssignmentInsert , LicenseAssignmentInsert , licenseAssignmentInsert , laiUserId -- ** LicenseAssignmentList , LicenseAssignmentList , licenseAssignmentList , lalEtag , lalNextPageToken , lalKind , lalItems -- ** LicenseAssignment , LicenseAssignment , licenseAssignment , laEtags , laKind , laSKUId , laUserId , laSelfLink , laProductId ) where import Network.Google.AppsLicensing.Types import Network.Google.Prelude import Network.Google.Resource.Licensing.LicenseAssignments.Delete import Network.Google.Resource.Licensing.LicenseAssignments.Get import Network.Google.Resource.Licensing.LicenseAssignments.Insert import Network.Google.Resource.Licensing.LicenseAssignments.ListForProduct import Network.Google.Resource.Licensing.LicenseAssignments.ListForProductAndSKU import Network.Google.Resource.Licensing.LicenseAssignments.Patch import Network.Google.Resource.Licensing.LicenseAssignments.Update {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Enterprise License Manager API service. type AppsLicensingAPI = LicenseAssignmentsInsertResource :<|> LicenseAssignmentsPatchResource :<|> LicenseAssignmentsGetResource :<|> LicenseAssignmentsListForProductAndSKUResource :<|> LicenseAssignmentsListForProductResource :<|> LicenseAssignmentsDeleteResource :<|> LicenseAssignmentsUpdateResource
rueshyna/gogol
gogol-apps-licensing/gen/Network/Google/AppsLicensing.hs
mpl-2.0
3,348
0
10
610
278
209
69
51
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Engine ( Engine , engineHandleEvent , engineHandleKeyboardEvent , withEngine , embedGame , loadGame , saveGame ) where import Control.Lens hiding (Context) import Control.Monad.Reader.Class import Control.Monad.State.Class import Control.Monad.Trans import Control.Monad.Trans.State (StateT(..)) import Control.Monad.Trans.Maybe (MaybeT(..)) import Control.Monad.Trans.Reader (ReaderT(..)) import Linear (V2(V2)) import SDL import Coordinate import Camera import Environment import Game import Link import Ui import Ui.Menu import World newtype Engine a = Engine { unwrapEngine :: EnvironmentT (MaybeT (StateT GameState IO)) a } deriving (Functor, Applicative, Monad, MonadState GameState, MonadReader Environment, MonadIO) withEngine :: Engine () -> String -> Environment -> IO () withEngine engine name env = do -- Loading game gs <- loadGame name -- Running engine ngs <- fmap snd $ flip runStateT gs $ runMaybeT $ flip runReaderT env $ unwrapEngine engine -- Save new game state saveGame ngs embedGame :: Game a -> Engine a embedGame game = Engine $ ReaderT $ \env -> MaybeT $ StateT $ \gs -> liftIO $ runGame env gs game loadGame :: String -> IO GameState loadGame name = do ctx <- initContext (Just 1000) ("data/" ++ name ++ "/") gs <- readLink ctx defaultLink case gs of Just tgs -> return $ tgs & gameContext .~ ctx Nothing -> error "Unable to load game state" -- TODO: should create a new game saveGame :: GameState -> IO () saveGame gs = do writeLink ctx defaultLink gs saveContext ctx where ctx = view gameContext gs -- | This function takes care of all events in the engine and dispatches them to the appropriate handlers. engineHandleEvent :: Event -> Game Bool engineHandleEvent event = do case eventPayload event of KeyboardEvent d -> engineHandleKeyboardEvent d WindowResizedEvent d -> engineHandleWindowResizedEvent d QuitEvent -> return True _ -> return False engineHandleWindowResizedEvent :: WindowResizedEventData -> Game Bool engineHandleWindowResizedEvent wred = do tileSize <- gameEnv envTileSize let V2 width height = windowResizedEventSize wred modify $ gameCamera . cameraWindowSize .~ V2 (fromIntegral width) (fromIntegral height) modify $ gameCamera . cameraViewport .~ V2 (fromIntegral width `div` fromIntegral tileSize) (fromIntegral height `div` fromIntegral tileSize) return False -- | This function handles keyboard events in the engine engineHandleKeyboardEvent :: KeyboardEventData -> Game Bool engineHandleKeyboardEvent ked = do -- Modifier keys case keycode of KeycodeLShift -> modify $ gameKeyShift .~ (keymotion == Pressed) KeycodeRShift -> modify $ gameKeyShift .~ (keymotion == Pressed) KeycodeLAlt -> modify $ gameKeyAlt .~ (keymotion == Pressed) KeycodeRAlt -> modify $ gameKeyAlt .~ (keymotion == Pressed) _ -> return () -- Bare keys if (keymotion == Pressed) then do -- TODO: I don't like that part (newKeycode, shouldHalt) <- uiMenuInterceptKeycode keycode if shouldHalt then return True else engineHandleBareKeycode newKeycode else return False -- $ scancode == ScancodeEscape where keymotion = keyboardEventKeyMotion ked -- ^ Wether the key is being pressed or released keysym = keyboardEventKeysym ked -- ^ Key symbol information: keycode or scancode representation keycode = keysymKeycode keysym -- ^ Which character is received from the operating system -- scancode = keysymScancode keysym -- ^ Physical key location as it would be on a US QWERTY keyboard engineHandleBareKeycode :: Keycode -> Game Bool engineHandleBareKeycode keycode = do player <- use gamePlayer shift <- use gameKeyShift case keycode of KeycodeW -> if shift then worldRotateObject player North else worldMoveObject player North KeycodeS -> if shift then worldRotateObject player South else worldMoveObject player South KeycodeA -> if shift then worldRotateObject player West else worldMoveObject player West KeycodeD -> if shift then worldRotateObject player East else worldMoveObject player East -- TODO: zoom levels with caching -- KeycodeKPPlus -> modify $ gameCamera %~ cameraZoom (subtract 1) -- KeycodeKPMinus -> modify $ gameCamera %~ cameraZoom (+1) KeycodeUp -> modify $ gameCamera %~ cameraMove North KeycodeDown -> modify $ gameCamera %~ cameraMove South KeycodeRight -> modify $ gameCamera %~ cameraMove East KeycodeLeft -> modify $ gameCamera %~ cameraMove West -- TODO: toggling centered camera and/or camera following when moving near edges -- KeycodeY -> modify $ id -- gameCamera %~ (fromMaybe id (cameraTogglePinned <$> sysWorldCoordObjectId world player)) -- TODO: eeeww KeycodeE -> modify $ gameUi %~ uiMenuSwitch UiMenuMain KeycodeEscape -> modify $ gameUi %~ uiMenuClear _ -> modify $ id return False
nitrix/lspace
legacy/Engine.hs
unlicense
5,418
0
12
1,406
1,201
615
586
-1
-1
-- Copyright © 2014 Garrison Jensen -- License -- This code and text are dedicated to the public domain. -- You can copy, modify, distribute and perform the work, -- even for commercial purposes, all without asking permission. module Parser(parseString, parseFile) where import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Language import qualified Text.ParserCombinators.Parsec.Token as Token import Data.Char() import Data.Either() import Nock languageDef = emptyDef { Token.commentLine = "::" } lexer = Token.makeTokenParser languageDef integer = Token.integer lexer whiteSpace = Token.whiteSpace lexer brack :: Parser Noun -> Parser Noun brack p = do whiteSpace char '[' whiteSpace e <- p whiteSpace char ']' whiteSpace return e cell :: Parser Noun cell = do n <- sepBy noun spaces return $ foldr1 Cell n atom :: Parser Noun atom = do whiteSpace n <- integer whiteSpace return $ Atom $ n noun :: Parser Noun noun = atom <|> brack cell whileParser :: Parser Noun whileParser = whiteSpace >> noun parseString :: String -> Maybe Noun parseString str = case parse whileParser "" str of Left _ -> Nothing Right r -> Just r parseFile :: String -> IO Noun parseFile file = do program <- readFile file case parse whileParser "" program of Left e -> print e >> fail "parse error" Right r -> return r
GarrisonJ/Nock
src/Parser.hs
unlicense
1,401
0
11
295
402
200
202
47
2
{-# OPTIONS_GHC -fno-warn-orphans #-} module ProjectM36.DataTypes.Interval where import ProjectM36.AtomFunctionBody import ProjectM36.Base import ProjectM36.AtomType import ProjectM36.DataTypes.Primitive import ProjectM36.AtomFunctionError import qualified Data.HashSet as HS import qualified Data.Map as M import Control.Monad (when) import Data.Maybe type OpenInterval = Bool intervalSubType :: AtomType -> AtomType intervalSubType typ = if isIntervalAtomType typ then case typ of ConstructedAtomType _ tvMap -> fromMaybe err (M.lookup "a" tvMap) _ -> err else err where err = error "intervalSubType on non-interval type" -- in lieu of typeclass support, we just hard-code the types which can be part of an interval supportsInterval :: AtomType -> Bool supportsInterval typ = case typ of IntAtomType -> True IntegerAtomType -> True ScientificAtomType -> True DoubleAtomType -> True TextAtomType -> False -- just because it supports ordering, doesn't mean it makes sense in an interval DayAtomType -> True DateTimeAtomType -> True ByteStringAtomType -> False BoolAtomType -> False UUIDAtomType -> False RelationAtomType _ -> False ConstructedAtomType _ _ -> False --once we support an interval-style typeclass, we might enable this RelationalExprAtomType -> False TypeVariableType _ -> False supportsOrdering :: AtomType -> Bool supportsOrdering typ = case typ of IntAtomType -> True IntegerAtomType -> True ScientificAtomType -> True DoubleAtomType -> True TextAtomType -> True DayAtomType -> True DateTimeAtomType -> True ByteStringAtomType -> False BoolAtomType -> False UUIDAtomType -> False RelationAtomType _ -> False RelationalExprAtomType -> False ConstructedAtomType _ _ -> False --once we support an interval-style typeclass, we might enable this TypeVariableType _ -> False atomCompare :: Atom -> Atom -> Either AtomFunctionError Ordering atomCompare a1 a2 = let aType = atomTypeForAtom a1 go a b = Right (compare a b) typError = Left (AtomTypeDoesNotSupportOrderingError (prettyAtomType aType)) in if atomTypeForAtom a1 /= atomTypeForAtom a2 then Left AtomFunctionTypeMismatchError else if not (supportsOrdering aType) then typError else case (a1, a2) of (IntegerAtom a, IntegerAtom b) -> go a b (IntAtom a, IntAtom b) -> go a b (DoubleAtom a, DoubleAtom b) -> go a b (TextAtom a, TextAtom b) -> go a b (DayAtom a, DayAtom b) -> go a b (DateTimeAtom a, DateTimeAtom b) -> go a b _ -> typError --check that interval is properly ordered and that the boundaries make sense createInterval :: Atom -> Atom -> OpenInterval -> OpenInterval -> Either AtomFunctionError Atom createInterval atom1 atom2 bopen eopen = do cmp <- atomCompare atom1 atom2 case cmp of GT -> Left InvalidIntervalOrderingError EQ -> if bopen || eopen then Left InvalidIntervalBoundariesError else Right valid LT -> Right valid where valid = ConstructedAtom "Interval" iType [atom1, atom2, BoolAtom bopen, BoolAtom eopen] iType = intervalAtomType (atomTypeForAtom atom1) intervalAtomType :: AtomType -> AtomType intervalAtomType typ = ConstructedAtomType "Interval" (M.singleton "a" typ) intervalAtomFunctions :: AtomFunctions intervalAtomFunctions = HS.fromList [ Function { funcName = "interval", funcType = [TypeVariableType "a", TypeVariableType "a", BoolAtomType, BoolAtomType, intervalAtomType (TypeVariableType "a")], funcBody = compiledAtomFunctionBody $ \(atom1:atom2:BoolAtom bopen:BoolAtom eopen:_) -> do let aType = atomTypeForAtom atom1 if supportsInterval aType then createInterval atom1 atom2 bopen eopen else Left (AtomTypeDoesNotSupportIntervalError (prettyAtomType aType)) }, Function { funcName = "interval_overlaps", funcType = [intervalAtomType (TypeVariableType "a"), intervalAtomType (TypeVariableType "a"), BoolAtomType], funcBody = compiledAtomFunctionBody $ \(i1@ConstructedAtom{}:i2@ConstructedAtom{}:_) -> BoolAtom <$> intervalOverlaps i1 i2 }] isIntervalAtomType :: AtomType -> Bool isIntervalAtomType (ConstructedAtomType nam tvMap) = nam == "Interval" && M.keys tvMap == ["a"] && case M.lookup "a" tvMap of Nothing -> False Just subType -> supportsInterval subType || subType == TypeVariableType "a" isIntervalAtomType _ = False intervalOverlaps :: Atom -> Atom -> Either AtomFunctionError Bool intervalOverlaps (ConstructedAtom dCons1 typ1 [i1start, i1end, BoolAtom i1startopen, BoolAtom i1endopen]) (ConstructedAtom dCons2 typ2 [i2start, i2end, BoolAtom i2startopen, BoolAtom i2endopen]) = do when (dCons1 /= "Interval" || dCons2 /= "Interval" || not (isIntervalAtomType typ1) || not (isIntervalAtomType typ2)) (Left AtomFunctionTypeMismatchError) cmp1 <- atomCompare i1start i2end cmp2 <- atomCompare i2start i1end let startcmp = if i1startopen || i2endopen then oplt else oplte endcmp = if i2startopen || i1endopen then oplt else oplte oplte op = op == LT || op == EQ oplt op = op == LT pure (startcmp cmp1 && endcmp cmp2) intervalOverlaps _ _ = Left AtomFunctionTypeMismatchError intervalTypeConstructorMapping :: TypeConstructorMapping intervalTypeConstructorMapping = [(ADTypeConstructorDef "Interval" ["a"], [])]
agentm/project-m36
src/lib/ProjectM36/DataTypes/Interval.hs
unlicense
6,648
0
18
2,287
1,472
751
721
127
14
------------------------------------------------------------------------------ -- Copyright 2012 Microsoft Corporation. -- -- This is free software; you can redistribute it and/or modify it under the -- terms of the Apache License, Version 2.0. A copy of the License can be -- found in the file "license.txt" at the root of this distribution. ----------------------------------------------------------------------------- {--} ----------------------------------------------------------------------------- module Kind.Unify( Context(..), unify, mgu, match ) where import Lib.PPrint import Common.Range import Common.Message( docFromRange, table) import Kind.Kind import Kind.InferKind import Kind.InferMonad {--------------------------------------------------------------- Unify ---------------------------------------------------------------} data Context = Check String Range | Infer Range unify :: Context -> Range -> InfKind -> InfKind -> KInfer () unify context range kind1 kind2 = do skind1 <- subst kind1 skind2 <- subst kind2 -- trace ("unify: " ++ show skind1 ++ " and " ++ show skind2) $ case mgu skind1 skind2 of Ok sub' -> extendKSub sub' err -> do cscheme <- getColorScheme kindError cscheme context range err skind1 skind2 kindError colors context range err kind1 kind2 = addError range $ text message <$> table ([(text "type context", docFromRange colors rangeContext) ,(text "type", docFromRange colors range) ,(text "inferred kind", niceKind2) ,(text expected, niceKind1) ] ++ extra) where (rangeContext,expected,extra) = case context of Check msg range -> (range,"expected kind",[(text "because", text msg)]) Infer range -> (range,"expected kind", []) [niceKind1,niceKind2] = niceInfKinds colors [kind1,kind2] message = case err of InfiniteKind -> "Invalid type (due to an infinite kind)" _ -> "Invalid type" {--------------------------------------------------------------- MGU ---------------------------------------------------------------} data Unify = Ok KSub | InfiniteKind | NoMatch mgu :: InfKind -> InfKind -> Unify -- constants mgu (KIVar id1) (KIVar id2) | id1 == id2 = Ok ksubEmpty mgu (KICon kind1) (KICon kind2) = if (match kind1 kind2) then Ok ksubEmpty else NoMatch mgu (KIApp k1 k2) (KIApp l1 l2) = case mgu k1 l1 of Ok sub1 -> case mgu (sub1 |=> k2) (sub1 |=> l2) of Ok sub2 -> Ok (sub2 @@ sub1) err -> err err -> err -- pull up KApp's mgu (KICon (KApp k1 k2)) (KIApp l1 l2) = mgu (KIApp (KICon k1) (KICon k2)) (KIApp l1 l2) mgu (KIApp k1 k2) (KICon (KApp l1 l2)) = mgu (KIApp k1 k2) (KIApp (KICon l1) (KICon l2)) -- unify variables mgu (KIVar id) kind = unifyVar id kind mgu kind (KIVar id) = unifyVar id kind -- no match mgu _ _ = NoMatch unifyVar id kind = if kvsMember id (fkv kind) then InfiniteKind else Ok (ksubSingle id kind) match :: Kind -> Kind -> Bool match (KCon c1) (KCon c2) = (c1 == c2) match (KApp k1 k2) (KApp l1 l2) = (match k1 l1) && (match k2 l2) match _ _ = False
lpeterse/koka
src/Kind/Unify.hs
apache-2.0
3,445
0
13
961
949
493
456
69
4
-- Copyright (c) 2013-2015 PivotCloud, Inc. -- -- Aws.Kinesis.Client.Consumer.Internal.SavedStreamState -- -- Please feel free to contact us at licensing@pivotmail.com with any -- contributions, additions, or other feedback; we would love to hear from -- you. -- -- Licensed under the Apache License, Version 2.0 (the "License"); you may -- not use this file except in compliance with the License. You may obtain a -- copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations -- under the License. {-# LANGUAGE UnicodeSyntax #-} -- | -- Module: Aws.Kinesis.Client.Consumer.Internal.SavedStreamState -- Copyright: Copyright © 2013-2015 PivotCloud, Inc. -- License: Apache-2.0 -- Maintainer: Jon Sterling <jsterling@alephcloud.com> -- Stability: experimental -- module Aws.Kinesis.Client.Consumer.Internal.SavedStreamState ( SavedStreamState , _SavedStreamState ) where import Aws.Kinesis import Control.Applicative (pure) import Control.Applicative.Unicode import Control.Lens hiding ((.=)) import Data.Aeson import qualified Data.Map as M import qualified Data.HashMap.Strict as HM import Data.Traversable import Prelude.Unicode newtype SavedStreamState = SavedStreamState { _savedStreamState ∷ M.Map ShardId SequenceNumber } -- | An iso for 'SavedStreamState'. -- _SavedStreamState ∷ Iso' SavedStreamState (M.Map ShardId SequenceNumber) _SavedStreamState = iso _savedStreamState SavedStreamState instance ToJSON SavedStreamState where toJSON (SavedStreamState m) = Object ∘ HM.fromList ∘ flip fmap (M.toList m) $ \(sid, sn) → let String sid' = toJSON sid in sid' .= sn instance FromJSON SavedStreamState where parseJSON = withObject "SavedStreamState" $ \xs → do fmap (SavedStreamState ∘ M.fromList) ∘ for (HM.toList xs) $ \(sid, sn) → do pure (,) ⊛ parseJSON (String sid) ⊛ parseJSON sn
alephcloud/hs-aws-kinesis-client
src/Aws/Kinesis/Client/Consumer/Internal/SavedStreamState.hs
apache-2.0
2,195
0
18
353
342
200
142
30
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeApplications #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | Protocol/versioning related communication types. module Pos.Infra.Communication.Types.Protocol ( checkInSpecs , Conversation (..) , convH , HandlerSpec (..) , HandlerSpecs , InSpecs (..) , Listener , listenerMessageCode , ListenerSpec (..) , MkListeners (..) , notInSpecs , N.ConversationActions (..) , NodeId , OutSpecs (..) , PackingType , PeerId (..) , PeerData , N.Converse (..) , SendActions (..) , EnqueueMsg , enqueueMsg' , waitForDequeues , waitForConversations , toOutSpecs , VerInfo (..) , NodeType (..) , MsgType (..) , Origin (..) , Msg , MsgSubscribe (..) , MsgSubscribe1 (..) , mlMsgSubscribe , mlMsgSubscribe1 , recvLimited ) where import Universum import qualified Control.Concurrent.Async as Async import qualified Control.Concurrent.STM as STM import Control.Exception (throwIO) import Data.Aeson (FromJSON (..), ToJSON (..), Value) import Data.Aeson.Types (Parser) import qualified Data.ByteString.Base64 as B64 (decode, encode) import qualified Data.ByteString.Lazy as LBS import qualified Data.HashMap.Strict as HM import qualified Data.Text.Encoding as Text (decodeUtf8, encodeUtf8) import qualified Data.Text.Internal.Builder as B import Formatting (bprint, build, hex, sformat, shown, (%)) import qualified Formatting.Buildable as B import qualified Network.Broadcast.OutboundQueue as OQ import Network.Transport (EndPointAddress (..)) import qualified Node as N import Node.Message.Class (Message (..), MessageCode) import Serokell.Util.Base16 (base16F) import Serokell.Util.Text (listJson, mapJson) import Pos.Binary.Class (Bi (..), Cons (..), Field (..), decodeKnownCborDataItem, decodeUnknownCborDataItem, deriveSimpleBi, encodeKnownCborDataItem, encodeListLen, encodeUnknownCborDataItem, enforceSize) import Pos.Binary.Limit (Limit (..)) import Pos.Chain.Update (BlockVersion) import Pos.Infra.Communication.BiP (BiP) import Pos.Infra.Network.Types (MsgType (..), NodeId (..), NodeType (..), Origin (..)) import Pos.Util.Util (cborError, toAesonError) type PackingType = BiP type PeerData = VerInfo type Listener = N.Listener PackingType PeerData type Msg = MsgType NodeId data SendActions = SendActions { -- | Establish a bi-direction conversation session with a node. -- -- A NonEmpty of Conversations is given as a sort of multi-version -- handling thing. The one to use is determined by trying to match -- in- and out-specs using VerInfo of our node and the peer. -- -- FIXME change this. Surely there is a more straightforward way. -- Why use in- and out-specs at all? Why not just a version number? withConnectionTo :: forall t . NodeId -> (PeerData -> NonEmpty (Conversation t)) -> IO t , enqueueMsg :: forall t . Msg -> (NodeId -> PeerData -> NonEmpty (Conversation t)) -- TOOD may as well change this type while we're at it, to include -- the TVar. -> IO (Map NodeId (IO t)) } type EnqueueMsg = forall t . Msg -> (NodeId -> PeerData -> NonEmpty (Conversation t)) -> IO (Map NodeId (STM.TVar (OQ.PacketStatus t))) -- | Enqueue a conversation with a bunch of peers and then wait for all of -- the results. enqueueMsg' :: forall t . SendActions -> Msg -> (NodeId -> PeerData -> NonEmpty (Conversation t)) -> IO (Map NodeId t) enqueueMsg' sendActions msg k = enqueueMsg sendActions msg k >>= waitForConversations waitForDequeues :: forall m t . ( MonadIO m ) => Map NodeId (STM.TVar (OQ.PacketStatus t)) -> Map NodeId (m t) waitForDequeues = fmap waitOne waitOne :: forall m t . (MonadIO m) => STM.TVar (OQ.PacketStatus t) -> m t waitOne statusVar = liftIO . join . atomically $ do st <- readTVar statusVar case st of OQ.PacketEnqueued -> STM.retry OQ.PacketAborted -> pure (throwIO OQ.Aborted) OQ.PacketDequeued thread -> pure (Async.wait thread) -- | Wait for enqueued conversations to complete (useful in a bind with -- 'enqueueMsg'). waitForConversations :: Map NodeId (IO t) -> IO (Map NodeId t) waitForConversations = sequenceA -- FIXME do not demand Message on rcv. That's only done for the benefit of -- this in- and out-spec motif. See TW-152. data Conversation t where Conversation :: ( Bi snd, Message snd, Bi rcv, Message rcv ) => (N.ConversationActions snd rcv -> IO t) -> Conversation t newtype PeerId = PeerId ByteString deriving (Eq, Ord, Show, Generic, Hashable) instance ToJSON PeerId where toJSON (PeerId bs) = toJSONBS bs instance ToJSON NodeId where toJSON (NodeId (EndPointAddress bs)) = toJSON (Text.decodeUtf8 (B64.encode bs)) toJSONBS :: ByteString -> Value toJSONBS = toJSON . Text.decodeUtf8 . B64.encode instance FromJSON PeerId where parseJSON = fromJSONBS PeerId instance FromJSON NodeId where parseJSON = fromJSONBS (NodeId . EndPointAddress) fromJSONBS :: (ByteString -> a) -> Value -> Parser a fromJSONBS f v = do bs <- Text.encodeUtf8 <$> parseJSON v toAesonError . bimap fromString f $ B64.decode bs instance Buildable PeerId where build (PeerId bs) = buildBS bs instance Buildable NodeId where build (NodeId (EndPointAddress bs)) = bprint shown bs buildBS :: ByteString -> B.Builder buildBS = bprint base16F data HandlerSpec -- | ConvHandler hsReplyType = ConvHandler !MessageCode | UnknownHandler !Word8 !ByteString deriving (Show, Generic, Eq) instance Bi HandlerSpec where encode input = case input of ConvHandler mname -> encodeListLen 2 <> encode (0 :: Word8) <> encodeKnownCborDataItem mname UnknownHandler word8 bs -> encodeListLen 2 <> encode word8 <> encodeUnknownCborDataItem (LBS.fromStrict bs) decode = do enforceSize "HandlerSpec" 2 tag <- decode @Word8 case tag of 0 -> ConvHandler <$> decodeKnownCborDataItem _ -> UnknownHandler tag <$> decodeUnknownCborDataItem convH :: (Message snd, Message rcv) => Proxy snd -> Proxy rcv -> (MessageCode, HandlerSpec) convH pSnd pReply = (messageCode pSnd, ConvHandler $ messageCode pReply) instance Buildable HandlerSpec where build (ConvHandler replyType) = bprint ("Conv "%hex) replyType build (UnknownHandler htype hcontent) = bprint ("UnknownHandler "%hex%" "%base16F) htype hcontent instance Buildable (MessageCode, HandlerSpec) where build (rcvType, h) = bprint (hex % " -> " % build) rcvType h type HandlerSpecs = HashMap MessageCode HandlerSpec instance Buildable HandlerSpecs where build x = bprint ("HandlerSpecs: "%listJson) (HM.toList x) -- FIXME don't use types which contain arbitrarily big values (like -- HandlerSpecs i.e. HashMap) because this VerInfo will have to be read in -- from peers. -- Why not just use a version number? data VerInfo = VerInfo { vIMagic :: Int32 , vIBlockVersion :: BlockVersion , vIInHandlers :: HandlerSpecs , vIOutHandlers :: HandlerSpecs } deriving (Eq, Generic, Show) deriveSimpleBi ''VerInfo [ Cons 'VerInfo [ Field [| vIMagic :: Int32 |], Field [| vIBlockVersion :: BlockVersion |], Field [| vIInHandlers :: HandlerSpecs |], Field [| vIOutHandlers :: HandlerSpecs |] ]] instance Buildable VerInfo where build VerInfo {..} = bprint ("VerInfo { magic="%hex%", blockVersion=" %build%", inSpecs="%mapJson%", outSpecs=" %mapJson%"}") vIMagic vIBlockVersion (HM.toList vIInHandlers) (HM.toList vIOutHandlers) checkInSpecs :: (MessageCode, HandlerSpec) -> HandlerSpecs -> Bool checkInSpecs (name, sp) specs = case name `HM.lookup` specs of Just sp' -> sp == sp' _ -> False notInSpecs :: (MessageCode, HandlerSpec) -> HandlerSpecs -> Bool notInSpecs sp' = not . checkInSpecs sp' -- ListenerSpec makes no sense like this. Surely the HandlerSpec must also -- depend upon the VerInfo. data ListenerSpec = ListenerSpec { lsHandler :: VerInfo -> Listener -- ^ Handler accepts out verInfo and returns listener , lsInSpec :: (MessageCode, HandlerSpec) } -- | The MessageCode that the listener responds to. listenerMessageCode :: Listener -> MessageCode listenerMessageCode (N.Listener (_ :: PeerData -> NodeId -> N.ConversationActions snd rcv -> IO ())) = messageCode (Proxy @rcv) newtype InSpecs = InSpecs HandlerSpecs deriving (Eq, Show, Generic) newtype OutSpecs = OutSpecs HandlerSpecs deriving (Eq, Show, Generic) instance Semigroup InSpecs where (InSpecs a) <> (InSpecs b) = InSpecs $ HM.unionWithKey merger a b where merger name h1 h2 = error $ sformat ("Conflicting key in input spec: "%build%" "%build) (name, h1) (name, h2) instance Monoid InSpecs where mempty = InSpecs mempty mappend = (<>) instance Semigroup OutSpecs where (OutSpecs a) <> (OutSpecs b) = OutSpecs $ HM.unionWithKey merger a b where merger name h1 h2 = if h1 == h2 then h1 else error $ sformat ("Conflicting key output spec: "%build%" "%build) (name, h1) (name, h2) instance Monoid OutSpecs where mempty = OutSpecs mempty mappend = (<>) toOutSpecs :: [(MessageCode, HandlerSpec)] -> OutSpecs toOutSpecs = OutSpecs . merge . fmap (uncurry HM.singleton) where merge = foldr (HM.unionWithKey merger) mempty merger name h1 h2 = error $ sformat ("Conflicting key output spec in toOutSpecs: "%build%" at "%build%" "%build) name h1 h2 -- | Data type to represent listeners, provided upon our version info and peerData -- received from other node, in and out specs for all listeners which may be provided data MkListeners = MkListeners { mkListeners :: VerInfo -> PeerData -> [Listener] -- ^ Accepts our version info and their peerData and returns set of listeners , inSpecs :: InSpecs -- ^ Aggregated specs for what we accept on incoming connections , outSpecs :: OutSpecs -- ^ Aggregated specs for which outgoing connections we might initiate } instance Semigroup MkListeners where a <> b = MkListeners act (inSpecs a <> inSpecs b) (outSpecs a <> outSpecs b) where act vI pD = (++) (mkListeners a vI pD) (mkListeners b vI pD) instance Monoid MkListeners where mempty = MkListeners (\_ _ -> []) mempty mempty mappend = (<>) -- | 'Subscribe' message -- -- Node A can send a MsgSubscribe to Node B to request that Node B adds Node A -- to the list of known peers in its outbound queue, so that Node B will send -- messages to node A. -- -- This is used by behind-NAT nodes, who join the network by sending a -- MsgSubscribe to a relay nodes. -- -- Note that after node A subscribes, it doesn't send anything to node B -- anymore. Therefore it might happen that due to problems within the network -- (e.g. router failures, see -- https://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html -- for more detailed information) node B closes the subscription channel after -- it tries to send data to node A and fails, whereas node A will be oblivious -- to that event and won't try to reestablish the channel. To remedy that node A -- needs to periodically send keep-alive like data to node B in order to ensure -- that the connection is valid. -- data MsgSubscribe = MsgSubscribe | MsgSubscribeKeepAlive deriving (Generic, Show, Eq) instance Bi MsgSubscribe where encode = \case MsgSubscribe -> encode (42 :: Word8) MsgSubscribeKeepAlive -> encode (43 :: Word8) decode = decode @Word8 >>= \case 42 -> pure MsgSubscribe 43 -> pure MsgSubscribeKeepAlive n -> cborError $ "MsgSubscribe wrong byte: " <> show n instance Message MsgSubscribe where messageCode _ = 14 formatMessage _ = "Subscribe" -- | Old version of MsgSubscribe. data MsgSubscribe1 = MsgSubscribe1 deriving (Generic, Show, Eq) -- deriveSimpleBi is not happy with constructors without arguments -- "fake" deriving as per `MempoolMsg`. -- TODO: Shall we encode this as `CBOR` TkNull? instance Bi MsgSubscribe1 where encode MsgSubscribe1 = encode (42 :: Word8) decode = decode @Word8 >>= \case 42 -> pure MsgSubscribe1 n -> cborError $ "MsgSubscribe1 wrong byte:" <> show n instance Message MsgSubscribe1 where messageCode _ = 13 formatMessage _ = "Subscribe1" mlMsgSubscribe :: Limit MsgSubscribe mlMsgSubscribe = 0 mlMsgSubscribe1 :: Limit MsgSubscribe1 mlMsgSubscribe1 = 0 recvLimited :: forall rcv snd . N.ConversationActions snd rcv -> Limit rcv -> IO (Maybe rcv) recvLimited conv = N.recv conv . getLimit
input-output-hk/cardano-sl
infra/src/Pos/Infra/Communication/Types/Protocol.hs
apache-2.0
13,730
0
17
3,645
3,201
1,777
1,424
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE ViewPatterns #-} import Control.Arrow ((&&&)) import Control.Concurrent import Control.Monad import Control.Monad.IO.Class import qualified Data.IntSet as IntSet import Data.IORef import Data.Maybe import qualified Data.Sequence as Seq import Data.Void (absurd) import System.IO.Unsafe import qualified System.Log.Logger as Logger import System.Log.Logger (Priority(DEBUG),rootLoggerName,setLevel,updateGlobalLogger) import System.Log.Logger.TH import System.Random (randomIO) import Test.Framework import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 import Test.HUnit hiding (Path,Test) import Test.QuickCheck.Instances () import Test.QuickCheck.Property (ioProperty) import LogicGrowsOnTrees import LogicGrowsOnTrees.Checkpoint import LogicGrowsOnTrees.Parallel.ExplorationMode import LogicGrowsOnTrees.Parallel.Purity import LogicGrowsOnTrees.Path import LogicGrowsOnTrees.Parallel.Common.Worker import LogicGrowsOnTrees.Testing import LogicGrowsOnTrees.Workload main :: IO () main = do -- updateGlobalLogger rootLoggerName (setLevel DEBUG) defaultMain [tests] tests :: Test tests = testGroup "LogicGrowsOnTrees.Parallel.Common.Worker" [testGroup "forkWorkerThread" [testCase "abort" $ do termination_result_mvar ← newEmptyMVar semaphore ← newEmptyMVar WorkerEnvironment{..} ← forkWorkerThread AllMode io_purity (putMVar termination_result_mvar) (liftIO (takeMVar semaphore) `mplus` error "should never get here") entire_workload absurd sendAbortRequest workerPendingRequests putMVar semaphore () termination_result ← takeMVar termination_result_mvar case termination_result of WorkerFinished _ → assertFailure "worker faled to abort" WorkerFailed exception → assertFailure ("worker threw exception: " ++ show exception) WorkerAborted → return () workerInitialPath @?= Seq.empty tryTakeMVar workerTerminationFlag >>= assertBool "is the termination flag set?" . isJust ,testGroup "obtains all solutions" [testProperty "with no initial path" $ \(tree :: Tree [Int]) → unsafePerformIO $ do solutions_mvar ← newEmptyMVar _ ← forkWorkerThread AllMode Pure (putMVar solutions_mvar) tree entire_workload absurd Progress checkpoint solutions ← (takeMVar solutions_mvar) >>= \termination_reason → case termination_reason of WorkerFinished final_progress → return final_progress other → error ("terminated unsuccessfully with reason " ++ show other) checkpoint @?= Explored solutions @?= exploreTree tree return True ,testProperty "with an initial path" $ \(tree :: Tree [Int]) → randomPathForTree tree >>= \path → return . unsafePerformIO $ do solutions_mvar ← newEmptyMVar _ ← forkWorkerThread AllMode Pure (putMVar solutions_mvar) tree (Workload path Unexplored) absurd Progress checkpoint solutions ← (takeMVar solutions_mvar) >>= \termination_reason → case termination_reason of WorkerFinished final_progress → return final_progress other → error ("terminated unsuccessfully with reason " ++ show other) checkpoint @?= checkpointFromInitialPath path Explored solutions @?= (exploreTree . sendTreeDownPath path $ tree) return True ] ,testGroup "progress updates correctly capture current and remaining progress" $ let runAnalysis tree termination_flag termination_result_mvar progress_updates_ref = do termination_result ← takeMVar termination_result_mvar remaining_solutions ← case termination_result of WorkerFinished (progressResult → solutions) → return solutions WorkerFailed exception → error ("worker threw exception: " ++ show exception) WorkerAborted → error "worker aborted prematurely" tryTakeMVar termination_flag >>= assertBool "is the termination flag set?" . isJust progress_updates ← reverse <$> readIORef progress_updates_ref let correct_solutions = exploreTree tree update_solutions = map (progressResult . progressUpdateProgress) progress_updates all_solutions = remaining_solutions:update_solutions forM_ (zip [0::Int ..] all_solutions) $ \(i,solutions_1) → forM_ (zip [0::Int ..] all_solutions) $ \(j,solutions_2) → unless (i == j) $ assertBool "Is there an overlap between non-intersecting solutions?" (IntSet.null $ solutions_1 `IntSet.intersection` solutions_2) let total_solutions = mconcat all_solutions assertEqual "Are the total solutions correct?" correct_solutions total_solutions let accumulated_update_solutions = scanl1 mappend update_solutions sequence_ $ zipWith (\accumulated_solutions (ProgressUpdate (Progress checkpoint _) remaining_workload) → do let remaining_solutions = exploreTreeWithinWorkload remaining_workload tree assertBool "Is there overlap between the accumulated solutions and the remaining solutions?" (IntSet.null $ accumulated_solutions `IntSet.intersection` remaining_solutions) assertEqual "Do the accumulated and remaining solutions sum to the correct solutions?" correct_solutions (accumulated_solutions `mappend` remaining_solutions) assertEqual "Is the checkpoint equal to the the remaining solutions?" remaining_solutions (exploreTreeStartingFromCheckpoint checkpoint tree) assertEqual "Is the inverted checkpoint equal to the the accumulated solutions?" accumulated_solutions (exploreTreeStartingFromCheckpoint (invertCheckpoint checkpoint) tree) ) accumulated_update_solutions progress_updates return True in [testProperty "continuous progress update requests" $ \(UniqueTree tree) → unsafePerformIO $ do starting_flag ← newEmptyMVar termination_result_mvar ← newEmptyMVar WorkerEnvironment{..} ← forkWorkerThread AllMode io_purity (putMVar termination_result_mvar) ((liftIO . takeMVar $ starting_flag) >> endowTree tree) entire_workload absurd progress_updates_ref ← newIORef [] let sendMyProgressUpdateRequest = sendProgressUpdateRequest workerPendingRequests submitProgressUpdate submitProgressUpdate progress_update = do atomicModifyIORef progress_updates_ref ((progress_update:) &&& const ()) sendMyProgressUpdateRequest sendMyProgressUpdateRequest putMVar starting_flag () runAnalysis tree workerTerminationFlag termination_result_mvar progress_updates_ref ,testProperty "progress update requests at random leaves" $ \(UniqueTree tree) → unsafePerformIO $ do termination_result_mvar ← newEmptyMVar progress_updates_ref ← newIORef [] rec WorkerEnvironment{..} ← forkWorkerThread AllMode io_purity (putMVar termination_result_mvar) (do value ← endowTree tree liftIO $ randomIO >>= flip when submitMyProgressUpdateRequest return value ) entire_workload absurd let submitMyProgressUpdateRequest = sendProgressUpdateRequest workerPendingRequests (atomicModifyIORef progress_updates_ref . (&&& const ()) . (:)) runAnalysis tree workerTerminationFlag termination_result_mvar progress_updates_ref ] ,testCase "terminates successfully with null tree" $ do termination_result_mvar ← newEmptyMVar WorkerEnvironment{..} ← forkWorkerThread AllMode Pure (putMVar termination_result_mvar) (mzero :: Tree [Int]) entire_workload absurd termination_result ← takeMVar termination_result_mvar case termination_result of WorkerFinished (progressResult → solutions) → solutions @?= mempty WorkerFailed exception → assertFailure ("worker threw exception: " ++ show exception) WorkerAborted → assertFailure "worker prematurely aborted" workerInitialPath @?= Seq.empty tryTakeMVar workerTerminationFlag >>= assertBool "is the termination flag set?" . isJust ,testGroup "work stealing correctly preserves total workload" $ let runManyStealsAnalysis tree termination_flag termination_result_mvar steals_ref = do termination_result ← takeMVar termination_result_mvar (Progress _ remaining_solutions) ← case termination_result of WorkerFinished final_progress → return final_progress WorkerFailed exception → error ("worker threw exception: " ++ show exception) WorkerAborted → error "worker aborted prematurely" tryTakeMVar termination_flag >>= assertBool "is the termination flag set?" . isJust steals ← reverse <$> readIORef steals_ref let correct_solutions = exploreTree tree prestolen_solutions = map ( progressResult . progressUpdateProgress . stolenWorkloadProgressUpdate ) steals stolen_solutions = map ( flip exploreTreeWithinWorkload tree . stolenWorkload ) steals all_solutions = remaining_solutions:(prestolen_solutions ++ stolen_solutions) total_solutions = mconcat all_solutions forM_ (zip [0::Int ..] all_solutions) $ \(i,solutions_1) → forM_ (zip [0::Int ..] all_solutions) $ \(j,solutions_2) → unless (i == j) $ assertBool "Is there overlap between non-intersecting solutions?" (IntSet.null $ solutions_1 `IntSet.intersection` solutions_2) assertEqual "Do the steals together include all of the solutions?" correct_solutions total_solutions let accumulated_prestolen_solutions = scanl1 mappend prestolen_solutions accumulated_stolen_solutions = scanl1 mappend stolen_solutions sequence_ $ zipWith3 (\acc_prestolen acc_stolen (StolenWorkload (ProgressUpdate (Progress checkpoint _) remaining_workload) _) → do let remaining_solutions = exploreTreeWithinWorkload remaining_workload tree accumulated_solutions = acc_prestolen `mappend` acc_stolen assertBool "Is there overlap between the accumulated solutions and the remaining solutions?" (IntSet.null $ accumulated_solutions `IntSet.intersection` remaining_solutions) assertEqual "Do the accumulated and remaining solutions sum to the correct solutions?" correct_solutions (accumulated_solutions `mappend` remaining_solutions) assertEqual "Is the checkpoint equal to the stolen plus the remaining solutions?" (acc_stolen `mappend` remaining_solutions) (exploreTreeStartingFromCheckpoint checkpoint tree) ) accumulated_prestolen_solutions accumulated_stolen_solutions steals return True in [testProperty "single steal" $ \(UniqueTree tree :: UniqueTree) → unsafePerformIO $ do -- {{{ reached_position_mvar ← newEmptyMVar blocking_value_mvar ← newEmptyMVar let tree_with_blocking_value = mplus (mplus (liftIO $ do _ ← tryPutMVar reached_position_mvar () readMVar blocking_value_mvar ) (return (IntSet.singleton 101010101)) ) (endowTree tree) termination_result_mvar ← newEmptyMVar WorkerEnvironment{..} ← forkWorkerThread AllMode io_purity (putMVar termination_result_mvar) tree_with_blocking_value entire_workload absurd maybe_workload_ref ← newIORef Nothing takeMVar reached_position_mvar sendWorkloadStealRequest workerPendingRequests $ writeIORef maybe_workload_ref putMVar blocking_value_mvar (IntSet.singleton 202020202) Progress _ remaining_solutions ← takeMVar termination_result_mvar >>= \termination_result → case termination_result of WorkerFinished final_progress → return final_progress WorkerFailed exception → error ("worker threw exception: " ++ show exception) WorkerAborted → error "worker aborted prematurely" isEmptyMVar workerTerminationFlag >>= assertBool "is the termination flag set?" . not StolenWorkload (ProgressUpdate (Progress checkpoint prestolen_solutions) remaining_workload) stolen_workload ← fmap (fromMaybe (error "stolen workload not available")) $ readIORef maybe_workload_ref assertBool "Does the checkpoint have unexplored nodes?" $ simplifyCheckpointRoot checkpoint /= Explored exploreTreeTWithinWorkload remaining_workload tree_with_blocking_value >>= (remaining_solutions @?=) exploreTreeTStartingFromCheckpoint (invertCheckpoint checkpoint) tree_with_blocking_value >>= (prestolen_solutions @?=) correct_solutions ← exploreTreeT tree_with_blocking_value stolen_solutions ← exploreTreeTWithinWorkload stolen_workload tree_with_blocking_value correct_solutions @=? mconcat [prestolen_solutions,remaining_solutions,stolen_solutions] assertEqual "There is no overlap between the prestolen solutions and the remaining solutions." IntSet.empty (prestolen_solutions `IntSet.intersection` remaining_solutions) assertEqual "There is no overlap between the prestolen solutions and the stolen solutions." IntSet.empty (prestolen_solutions `IntSet.intersection` stolen_solutions) assertEqual "There is no overlap between the stolen solutions and the remaining solutions." IntSet.empty (stolen_solutions `IntSet.intersection` remaining_solutions) return True ,testProperty "continuous stealing" $ \(UniqueTree tree) → unsafePerformIO $ do starting_flag ← newEmptyMVar termination_result_mvar ← newEmptyMVar WorkerEnvironment{..} ← forkWorkerThread AllMode io_purity (putMVar termination_result_mvar) ((liftIO . takeMVar $ starting_flag) >> endowTree tree) entire_workload absurd steals_ref ← newIORef [] let submitMyWorkloadStealRequest = sendWorkloadStealRequest workerPendingRequests submitStolenWorkload submitStolenWorkload Nothing = submitMyWorkloadStealRequest submitStolenWorkload (Just steal) = do atomicModifyIORef steals_ref ((steal:) &&& const ()) submitMyWorkloadStealRequest submitMyWorkloadStealRequest putMVar starting_flag () runManyStealsAnalysis tree workerTerminationFlag termination_result_mvar steals_ref ,testProperty "stealing at random leaves" $ \(UniqueTree tree) → unsafePerformIO $ do termination_result_mvar ← newEmptyMVar steals_ref ← newIORef [] rec WorkerEnvironment{..} ← forkWorkerThread AllMode io_purity (putMVar termination_result_mvar) (do value ← endowTree tree liftIO $ randomIO >>= flip when submitMyWorkloadStealRequest return value ) entire_workload absurd let submitMyWorkloadStealRequest = sendWorkloadStealRequest workerPendingRequests (maybe (return ()) $ atomicModifyIORef steals_ref . (&&& const ()) . (:)) runManyStealsAnalysis tree workerTerminationFlag termination_result_mvar steals_ref ] ] ,testProperty "exploreTreeUntilFirst" $ \(tree :: Tree String) → ioProperty $ do termination_reason ← exploreTreeGeneric FirstMode Pure tree case termination_reason of WorkerFinished maybe_final_progress → return $ (progressResult <$> maybe_final_progress) == exploreTreeUntilFirst tree _ → fail $ "returned " ++ show termination_reason ++ " instead of WorkerFinished" ]
gcross/LogicGrowsOnTrees
LogicGrowsOnTrees/tests/test-Worker.hs
bsd-2-clause
20,674
0
31
7,858
3,243
1,585
1,658
316
15
{-# LANGUAGE BangPatterns, CPP, ForeignFunctionInterface, GeneralizedNewtypeDeriving, MagicHash, UnliftedFFITypes #-} #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif -- | -- Module : Data.Text.Encoding -- Copyright : (c) 2009, 2010, 2011 Bryan O'Sullivan, -- (c) 2009 Duncan Coutts, -- (c) 2008, 2009 Tom Harper -- -- License : BSD-style -- Maintainer : bos@serpentine.com -- Portability : portable -- -- Functions for converting 'Text' values to and from 'ByteString', -- using several standard encodings. -- -- To gain access to a much larger family of encodings, use the -- <http://hackage.haskell.org/package/text-icu text-icu package>. module Data.Text.Encoding ( -- * Decoding ByteStrings to Text -- $strict decodeASCII , decodeLatin1 , decodeUtf8 , decodeUtf16LE , decodeUtf16BE , decodeUtf32LE , decodeUtf32BE -- ** Catchable failure , decodeUtf8' -- ** Controllable error handling , decodeUtf8With , decodeUtf16LEWith , decodeUtf16BEWith , decodeUtf32LEWith , decodeUtf32BEWith -- ** Stream oriented decoding -- $stream , streamDecodeUtf8 , streamDecodeUtf8With , Decoding(..) -- * Encoding Text to ByteStrings , encodeUtf8 , encodeUtf16LE , encodeUtf16BE , encodeUtf32LE , encodeUtf32BE -- * Encoding Text using ByteString Builders , encodeUtf8Builder , encodeUtf8BuilderEscaped ) where #if __GLASGOW_HASKELL__ >= 702 import Control.Monad.ST.Unsafe (unsafeIOToST, unsafeSTToIO) #else import Control.Monad.ST (unsafeIOToST, unsafeSTToIO) #endif import Control.Exception (evaluate, try) import Control.Monad.ST (runST) import Data.ByteString as B import Data.ByteString.Internal as B hiding (c2w) import Data.Text.Encoding.Error (OnDecodeError, UnicodeException, strictDecode) import Data.Text.Internal (Text(..), safe, text) import Data.Text.Internal.Unsafe.Char (unsafeWrite) import Data.Text.Show () import Data.Text.Unsafe (unsafeDupablePerformIO) import Data.Word (Word8, Word32) #if __GLASGOW_HASKELL__ >= 703 import Foreign.C.Types (CSize) #else import Foreign.C.Types (CSize) #endif import Foreign.ForeignPtr (withForeignPtr) import Foreign.Marshal.Utils (with) import Foreign.Ptr (Ptr, minusPtr, nullPtr, plusPtr) import Foreign.Storable (Storable, peek, poke) import GHC.Base (MutableByteArray#) import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Builder.Internal as B hiding (empty, append) import qualified Data.ByteString.Builder.Prim as BP import qualified Data.ByteString.Builder.Prim.Internal as BP import qualified Data.Text.Array as A import qualified Data.Text.Internal.Encoding.Fusion as E import qualified Data.Text.Internal.Fusion as F #include "text_cbits.h" -- $strict -- -- All of the single-parameter functions for decoding bytestrings -- encoded in one of the Unicode Transformation Formats (UTF) operate -- in a /strict/ mode: each will throw an exception if given invalid -- input. -- -- Each function has a variant, whose name is suffixed with -'With', -- that gives greater control over the handling of decoding errors. -- For instance, 'decodeUtf8' will throw an exception, but -- 'decodeUtf8With' allows the programmer to determine what to do on a -- decoding error. -- | /Deprecated/. Decode a 'ByteString' containing 7-bit ASCII -- encoded text. decodeASCII :: ByteString -> Text decodeASCII = decodeUtf8 {-# DEPRECATED decodeASCII "Use decodeUtf8 instead" #-} -- | Decode a 'ByteString' containing Latin-1 (aka ISO-8859-1) encoded text. -- -- 'decodeLatin1' is semantically equivalent to -- @Data.Text.pack . Data.ByteString.Char8.unpack@ decodeLatin1 :: ByteString -> Text decodeLatin1 s = F.unstream (E.streamASCII s) -- | Decode a 'ByteString' containing UTF-8 encoded text. decodeUtf8With :: OnDecodeError -> ByteString -> Text decodeUtf8With onErr s@(PS fp off len) = runST $ do dest <- A.new len unsafeIOToST $ do withForeignPtr fp $ \ptr -> with (0::CSize) $ \destOffPtr ->do let curPtr = ptr `plusPtr` off let end = ptr `plusPtr` (off + len) curPtr' <- c_decode_utf8 (A.maBA dest) destOffPtr curPtr end if curPtr' == end then do n <- peek destOffPtr dest' <- unsafeSTToIO (A.unsafeFreeze dest) return (Text dest' 0 (fromIntegral n)) else do return (F.unstream (E.streamUtf8 onErr s)) {- INLINE[0] decodeUtf8With #-} -- $stream -- -- The 'streamDecodeUtf8' and 'streamDecodeUtf8With' functions accept -- a 'ByteString' that represents a possibly incomplete input (e.g. a -- packet from a network stream) that may not end on a UTF-8 boundary. -- -- 1. The maximal prefix of 'Text' that could be decoded from the -- given input. -- -- 2. The suffix of the 'ByteString' that could not be decoded due to -- insufficient input. -- -- 3. A function that accepts another 'ByteString'. That string will -- be assumed to directly follow the string that was passed as -- input to the original function, and it will in turn be decoded. -- -- To help understand the use of these functions, consider the Unicode -- string @\"hi &#9731;\"@. If encoded as UTF-8, this becomes @\"hi -- \\xe2\\x98\\x83\"@; the final @\'&#9731;\'@ is encoded as 3 bytes. -- -- Now suppose that we receive this encoded string as 3 packets that -- are split up on untidy boundaries: @[\"hi \\xe2\", \"\\x98\", -- \"\\x83\"]@. We cannot decode the entire Unicode string until we -- have received all three packets, but we would like to make progress -- as we receive each one. -- -- @ -- ghci> let s0\@('Some' _ _ f0) = 'streamDecodeUtf8' \"hi \\xe2\" -- ghci> s0 -- 'Some' \"hi \" \"\\xe2\" _ -- @ -- -- We use the continuation @f0@ to decode our second packet. -- -- @ -- ghci> let s1\@('Some' _ _ f1) = f0 \"\\x98\" -- ghci> s1 -- 'Some' \"\" \"\\xe2\\x98\" -- @ -- -- We could not give @f0@ enough input to decode anything, so it -- returned an empty string. Once we feed our second continuation @f1@ -- the last byte of input, it will make progress. -- -- @ -- ghci> let s2\@('Some' _ _ f2) = f1 \"\\x83\" -- ghci> s2 -- 'Some' \"\\x2603\" \"\" _ -- @ -- -- If given invalid input, an exception will be thrown by the function -- or continuation where it is encountered. -- | A stream oriented decoding result. -- -- @since 1.0.0.0 data Decoding = Some Text ByteString (ByteString -> Decoding) instance Show Decoding where showsPrec d (Some t bs _) = showParen (d > prec) $ showString "Some " . showsPrec prec' t . showChar ' ' . showsPrec prec' bs . showString " _" where prec = 10; prec' = prec + 1 newtype CodePoint = CodePoint Word32 deriving (Eq, Show, Num, Storable) newtype DecoderState = DecoderState Word32 deriving (Eq, Show, Num, Storable) -- | Decode, in a stream oriented way, a 'ByteString' containing UTF-8 -- encoded text that is known to be valid. -- -- If the input contains any invalid UTF-8 data, an exception will be -- thrown (either by this function or a continuation) that cannot be -- caught in pure code. For more control over the handling of invalid -- data, use 'streamDecodeUtf8With'. -- -- @since 1.0.0.0 streamDecodeUtf8 :: ByteString -> Decoding streamDecodeUtf8 = streamDecodeUtf8With strictDecode -- | Decode, in a stream oriented way, a 'ByteString' containing UTF-8 -- encoded text. -- -- @since 1.0.0.0 streamDecodeUtf8With :: OnDecodeError -> ByteString -> Decoding streamDecodeUtf8With onErr = decodeChunk B.empty 0 0 where -- We create a slightly larger than necessary buffer to accommodate a -- potential surrogate pair started in the last buffer decodeChunk :: ByteString -> CodePoint -> DecoderState -> ByteString -> Decoding decodeChunk undecoded0 codepoint0 state0 bs@(PS fp off len) = runST $ (unsafeIOToST . decodeChunkToBuffer) =<< A.new (len+1) where decodeChunkToBuffer :: A.MArray s -> IO Decoding decodeChunkToBuffer dest = withForeignPtr fp $ \ptr -> with (0::CSize) $ \destOffPtr -> with codepoint0 $ \codepointPtr -> with state0 $ \statePtr -> with nullPtr $ \curPtrPtr -> let end = ptr `plusPtr` (off + len) loop curPtr = do poke curPtrPtr curPtr curPtr' <- c_decode_utf8_with_state (A.maBA dest) destOffPtr curPtrPtr end codepointPtr statePtr state <- peek statePtr case state of UTF8_REJECT -> do -- We encountered an encoding error x <- peek curPtr' poke statePtr 0 case onErr desc (Just x) of Nothing -> loop $ curPtr' `plusPtr` 1 Just c -> do destOff <- peek destOffPtr w <- unsafeSTToIO $ unsafeWrite dest (fromIntegral destOff) (safe c) poke destOffPtr (destOff + fromIntegral w) loop $ curPtr' `plusPtr` 1 _ -> do -- We encountered the end of the buffer while decoding n <- peek destOffPtr codepoint <- peek codepointPtr chunkText <- unsafeSTToIO $ do arr <- A.unsafeFreeze dest return $! text arr 0 (fromIntegral n) lastPtr <- peek curPtrPtr let left = lastPtr `minusPtr` curPtr !undecoded = case state of UTF8_ACCEPT -> B.empty _ -> B.append undecoded0 (B.drop left bs) return $ Some chunkText undecoded (decodeChunk undecoded codepoint state) in loop (ptr `plusPtr` off) desc = "Data.Text.Internal.Encoding.streamDecodeUtf8With: Invalid UTF-8 stream" -- | Decode a 'ByteString' containing UTF-8 encoded text that is known -- to be valid. -- -- If the input contains any invalid UTF-8 data, an exception will be -- thrown that cannot be caught in pure code. For more control over -- the handling of invalid data, use 'decodeUtf8'' or -- 'decodeUtf8With'. decodeUtf8 :: ByteString -> Text decodeUtf8 = decodeUtf8With strictDecode {-# INLINE[0] decodeUtf8 #-} {-# RULES "STREAM stream/decodeUtf8 fusion" [1] forall bs. F.stream (decodeUtf8 bs) = E.streamUtf8 strictDecode bs #-} -- | Decode a 'ByteString' containing UTF-8 encoded text. -- -- If the input contains any invalid UTF-8 data, the relevant -- exception will be returned, otherwise the decoded text. decodeUtf8' :: ByteString -> Either UnicodeException Text decodeUtf8' = unsafeDupablePerformIO . try . evaluate . decodeUtf8With strictDecode {-# INLINE decodeUtf8' #-} -- | Encode text to a ByteString 'B.Builder' using UTF-8 encoding. -- -- @since 1.1.0.0 encodeUtf8Builder :: Text -> B.Builder encodeUtf8Builder = \t -> B.builder (textCopyStep t) {-# INLINE encodeUtf8Builder #-} textCopyStep :: Text -> B.BuildStep a -> B.BuildStep a textCopyStep !(Text arr off len) k = go 0 len where go !ip !ipe !(B.BufferRange op ope) | inpRemaining <= outRemaining = do A.copyToPtr op 0 arr (off + ip) inpRemaining let !br' = B.BufferRange (op `plusPtr` inpRemaining) ope k br' | otherwise = do A.copyToPtr op 0 arr (off + ip) outRemaining let !ip' = ip + outRemaining return $ B.bufferFull 1 ope (go ip' ipe) where outRemaining = ope `minusPtr` op inpRemaining = ipe - ip {-# INLINE textCopyStep #-} -- | Encode text using UTF-8 encoding and escape the ASCII characters using -- a 'BP.BoundedPrim'. -- -- Use this function is to implement efficient encoders for text-based formats -- like JSON or HTML. -- -- @since 1.1.0.0 {-# INLINE encodeUtf8BuilderEscaped #-} -- TODO: Extend documentation with references to source code in @blaze-html@ -- or @aeson@ that uses this function. encodeUtf8BuilderEscaped :: BP.BoundedPrim Word8 -> Text -> B.Builder encodeUtf8BuilderEscaped be = -- manual eta-expansion to ensure inlining works as expected \txt -> B.builder (mkBuildstep txt) where bound = max 4 $ BP.sizeBound be mkBuildstep (Text arr off len) !k = outerLoop off where iend = off + len outerLoop !i0 !br@(B.BufferRange op0 ope) | i0 >= iend = k br | outRemaining > 0 = goPartial (i0 + min outRemaining inpRemaining) -- TODO: Use a loop with an integrated bound's check if outRemaining -- is smaller than 8, as this will save on divisions. | otherwise = return $ B.bufferFull bound op0 (outerLoop i0) where outRemaining = (ope `minusPtr` op0) `div` bound inpRemaining = iend - i0 goPartial !iendTmp = go i0 op0 where go !i !op | i < iendTmp = case () of _ | a <= 0x7F -> BP.runB be (fromIntegral a) op >>= go (i + 1) | 0xC2 <= a && a <= 0xDF -> do poke8 0 a poke8 1 b go (i + 2) (op `plusPtr` 2) | 0xE0 <= a && a <= 0xEF -> do poke8 0 a poke8 1 b poke8 2 c go (i + 3) (op `plusPtr` 3) | otherwise -> do poke8 0 a poke8 1 b poke8 2 c poke8 3 d go (i + 4) (op `plusPtr` 4) | otherwise = outerLoop i (B.BufferRange op ope) where poke8 j v = poke (op `plusPtr` j) (fromIntegral v :: Word8) a = A.unsafeIndex arr i b = A.unsafeIndex arr (i+1) c = A.unsafeIndex arr (i+2) d = A.unsafeIndex arr (i+3) -- | Encode text using UTF-8 encoding. encodeUtf8 :: Text -> ByteString encodeUtf8 (Text arr off len) | len == 0 = B.empty | otherwise = B.unsafeCreate len (\op -> A.copyToPtr op 0 arr off len) -- | Decode text from little endian UTF-16 encoding. decodeUtf16LEWith :: OnDecodeError -> ByteString -> Text decodeUtf16LEWith onErr bs = F.unstream (E.streamUtf16LE onErr bs) {-# INLINE decodeUtf16LEWith #-} -- | Decode text from little endian UTF-16 encoding. -- -- If the input contains any invalid little endian UTF-16 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use 'decodeUtf16LEWith'. decodeUtf16LE :: ByteString -> Text decodeUtf16LE = decodeUtf16LEWith strictDecode {-# INLINE decodeUtf16LE #-} -- | Decode text from big endian UTF-16 encoding. decodeUtf16BEWith :: OnDecodeError -> ByteString -> Text decodeUtf16BEWith onErr bs = F.unstream (E.streamUtf16BE onErr bs) {-# INLINE decodeUtf16BEWith #-} -- | Decode text from big endian UTF-16 encoding. -- -- If the input contains any invalid big endian UTF-16 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use 'decodeUtf16BEWith'. decodeUtf16BE :: ByteString -> Text decodeUtf16BE = decodeUtf16BEWith strictDecode {-# INLINE decodeUtf16BE #-} -- | Encode text using little endian UTF-16 encoding. encodeUtf16LE :: Text -> ByteString encodeUtf16LE txt = E.unstream (E.restreamUtf16LE (F.stream txt)) {-# INLINE encodeUtf16LE #-} -- | Encode text using big endian UTF-16 encoding. encodeUtf16BE :: Text -> ByteString encodeUtf16BE txt = E.unstream (E.restreamUtf16BE (F.stream txt)) {-# INLINE encodeUtf16BE #-} -- | Decode text from little endian UTF-32 encoding. decodeUtf32LEWith :: OnDecodeError -> ByteString -> Text decodeUtf32LEWith onErr bs = F.unstream (E.streamUtf32LE onErr bs) {-# INLINE decodeUtf32LEWith #-} -- | Decode text from little endian UTF-32 encoding. -- -- If the input contains any invalid little endian UTF-32 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use 'decodeUtf32LEWith'. decodeUtf32LE :: ByteString -> Text decodeUtf32LE = decodeUtf32LEWith strictDecode {-# INLINE decodeUtf32LE #-} -- | Decode text from big endian UTF-32 encoding. decodeUtf32BEWith :: OnDecodeError -> ByteString -> Text decodeUtf32BEWith onErr bs = F.unstream (E.streamUtf32BE onErr bs) {-# INLINE decodeUtf32BEWith #-} -- | Decode text from big endian UTF-32 encoding. -- -- If the input contains any invalid big endian UTF-32 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use 'decodeUtf32BEWith'. decodeUtf32BE :: ByteString -> Text decodeUtf32BE = decodeUtf32BEWith strictDecode {-# INLINE decodeUtf32BE #-} -- | Encode text using little endian UTF-32 encoding. encodeUtf32LE :: Text -> ByteString encodeUtf32LE txt = E.unstream (E.restreamUtf32LE (F.stream txt)) {-# INLINE encodeUtf32LE #-} -- | Encode text using big endian UTF-32 encoding. encodeUtf32BE :: Text -> ByteString encodeUtf32BE txt = E.unstream (E.restreamUtf32BE (F.stream txt)) {-# INLINE encodeUtf32BE #-} foreign import ccall unsafe "_hs_text_utf_8_decode_utf8" c_decode_utf8 :: MutableByteArray# s -> Ptr CSize -> Ptr Word8 -> Ptr Word8 -> IO (Ptr Word8) foreign import ccall unsafe "_hs_text_utf_8_decode_utf8_state" c_decode_utf8_with_state :: MutableByteArray# s -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr Word8 -> Ptr CodePoint -> Ptr DecoderState -> IO (Ptr Word8)
text-utf8/text
Data/Text/Encoding.hs
bsd-2-clause
17,775
4
39
4,530
3,181
1,728
1,453
241
4
module Internal.Types ( Session(..), TorrentSt(..), Torrent(..), Activity(..), LogLevel(..), WhiteoutException(..), PieceNum ) where import Control.Concurrent import Control.Concurrent.STM import Control.Exception import Data.Array.IArray (Array) import Data.ByteString (ByteString) import qualified Data.Map as M import Data.Map (Map) import Data.Typeable import Data.Word (Word32) import Network.Socket (HostAddress, PortNumber) import {-# SOURCE #-} Internal.Peers.Handler (PeerSt) -- | A Whiteout session. Contains various internal state. data Session = Session { -- | Map from infohashes to torrents. torrents :: TVar (M.Map ByteString TorrentSt), sPeerId :: ByteString, logChan :: Maybe (TChan (LogLevel, String)), listenPort :: PortNumber, listenerThreadId :: Maybe ThreadId } -- | The state of a torrent. data TorrentSt = TorrentSt { sTorrent :: Torrent, sPath :: FilePath, -- | Is a given piece completed? For now (2009-05-24) this only reflects -- whether a piece's hash has been checked and found correct. sCompletion :: TArray PieceNum Bool, sActivity :: TVar Activity, -- | Map from threadIds to peers. sPeers :: TVar (Map ThreadId PeerSt), -- | How many connection attempts are in progress. sPotentialPeers :: TVar [(HostAddress, PortNumber)], sTimeToAnnounce :: TVar (TVar Bool) } -- | The static information about a torrent, i.e. that stored in a file named -- @foo.torrent@. data Torrent = Torrent { -- | The announce URL. tAnnounce :: ByteString, -- | The name of the top-level directory or the file if it is a single file -- torrent. tName :: ByteString, -- | Length of a piece in bytes. tPieceLen :: Int, -- | Map piece numbers to their SHA-1 hashes. tPieceHashes :: Array PieceNum ByteString, -- | Either the length of the single file or a list of filenames and their -- lengths. tFiles :: Either Integer [(Integer, FilePath)], -- | SHA-1 of the bencoded info dictionary. tInfohash :: ByteString } deriving (Show) -- | What is being done with a torrent at a given moment. data Activity = Stopped -- ^ Twiddling its thumbs. | Stopping -- ^ Closing its peer connections in preparation for thumb-twiddling. | Verifying -- ^ Checking the piece hashes. | Running -- ^ Actively seeking and sending pieces to peers. deriving (Eq, Ord, Show) type PieceNum = Word32 data LogLevel = Debug -- ^ Messages of interest only for debugging Whiteout. | Low -- ^ Boring messages e.g. new peer connections. | Medium -- ^ Slightly less boring messages e.g. announces. | Critical -- ^ Problems which obstruct the primary functionality of Whiteout -- e.g. an error reading from disk. deriving (Show, Eq) data WhiteoutException = CouldntParseTorrent | HTTPDownloadFailed | CouldntParseURL | BadState -- ^ Tried to perform some action on a torrent precluded by the current state -- of the torrent. E.g. Tried to verify a torrent that is already Verifying. | BadFiles deriving (Show, Typeable, Eq) instance Exception WhiteoutException
enolan/whiteout
src/Internal/Types.hs
bsd-3-clause
3,227
0
12
750
514
322
192
62
0
{-# LANGUAGE OverloadedStrings #-} module HttpServer (run) where import Web.Spock import Web.Spock.Config import Network.Wai.Middleware.Static run :: Int -> IO () run port = do spockCfg <- defaultSpockCfg () PCNoDatabase () runSpock port (spock spockCfg app) app :: SpockM () () () () app = middleware $ staticPolicy $ (addBase "static") -- >-> (policy $ \x -> Just $ x ++ ".html")
mat-hek/jump
src/HttpServer.hs
bsd-3-clause
404
0
9
83
126
67
59
12
1
module Main where import Ivory.Tower.Config import Ivory.Tower.Options import Ivory.OS.FreeRTOS.Tower.STM32 import Tower.AADL import Tower.AADL.Build.Common import Tower.AADL.Build.EChronos import BSP.Tests.Platforms import BSP.Tests.CAN.TestApp (app) main :: IO () main = compileTowerAADLForPlatform f p $ app (stm32config_clock . testplatform_stm32) testplatform_can testplatform_leds where f :: TestPlatform -> (AADLConfig, OSSpecific STM32Config) f tp = ( defaultAADLConfig { configSystemOS = EChronos , configSystemHW = PIXHAWK } , defaultEChronosOS (testplatform_stm32 tp) ) p :: TOpts -> IO TestPlatform p topts = fmap fst (getConfig' topts testPlatformParser)
GaloisInc/ivory-tower-stm32
ivory-bsp-tests/tests/CANAADLTest.hs
bsd-3-clause
793
0
10
202
189
109
80
20
1
module Colorimetry.Illuminant.BlackBody ( blackBody , idealizedD65 ) where -- | A perfect black body emitter. Gives the energy for a given temperature blackbody emitter -- in power per m^2 of area per nm of wavelength using Planck's energy distribution formula. -- given the temperature of the emitter in degrees Kelven and the wavelength blackBody :: Floating a => a -> a -> a blackBody temp wlnm= (3.74183e-16 * (wlm ^^ (-5 :: Int))) * 44 / (exp(1.4388e-2 / (wlm * temp)) - 1) where wlm = wlnm * 1e-9 {-# INLINE blackBody #-} -- | Idealized approximation of the cie standard illuminant D65 idealizedD65 :: Double -> Double idealizedD65 = blackBody 6504
ekmett/colorimetry
Colorimetry/Illuminant/BlackBody.hs
bsd-3-clause
666
0
12
123
132
75
57
9
1
module Integers where import Data.Char (ord) import Text.Trifecta parseDigit :: Parser Char parseDigit = oneOf ['0'..'9'] <?> "Digit" base10Integer :: Parser Integer base10Integer = do chars <- some parseDigit let digits = map (toInteger . (\x -> x - 48) . ord) chars return . snd $ foldr (\d (coeff, res) -> (coeff + 1, res + (10 ^ coeff) * d)) (0, 0) digits base10Integer' :: Parser Integer base10Integer' = do skipMany $ char '+' minus <- optional $ char '-' value <- base10Integer return $ case minus of Just _ -> -value Nothing -> value
vasily-kirichenko/haskell-book
src/Parsing/Integers.hs
bsd-3-clause
614
0
16
169
241
124
117
22
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} -- | Construct a @Plan@ for how to build module Stack.Build.ConstructPlan ( constructPlan ) where import Control.Arrow ((&&&)) import Control.Exception.Lifted import Control.Monad import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.RWS.Strict import Control.Monad.Trans.Resource import Data.Either import Data.Function import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import qualified Data.Map.Strict as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import qualified Distribution.Package as Cabal import qualified Distribution.Version as Cabal import GHC.Generics (Generic) import Generics.Deriving.Monoid (memptydefault, mappenddefault) import Network.HTTP.Client.Conduit (HasHttpManager) import Prelude hiding (pi, writeFile) import Stack.Build.Cache import Stack.Build.Haddock import Stack.Build.Installed import Stack.Build.Source import Stack.BuildPlan import Stack.Package import Stack.PackageDump import Stack.PackageIndex import Stack.Types data PackageInfo = PIOnlyInstalled InstallLocation Installed | PIOnlySource PackageSource | PIBoth PackageSource Installed combineSourceInstalled :: PackageSource -> (InstallLocation, Installed) -> PackageInfo combineSourceInstalled ps (location, installed) = assert (piiVersion ps == installedVersion installed) $ assert (piiLocation ps == location) $ case location of -- Always trust something in the snapshot Snap -> PIOnlyInstalled location installed Local -> PIBoth ps installed type CombinedMap = Map PackageName PackageInfo combineMap :: SourceMap -> InstalledMap -> CombinedMap combineMap = Map.mergeWithKey (\_ s i -> Just $ combineSourceInstalled s i) (fmap PIOnlySource) (fmap (uncurry PIOnlyInstalled)) data AddDepRes = ADRToInstall Task | ADRFound InstallLocation Installed deriving Show data W = W { wFinals :: !(Map PackageName (Either ConstructPlanException Task)) , wInstall :: !(Map Text InstallLocation) -- ^ executable to be installed, and location where the binary is placed , wDirty :: !(Map PackageName Text) -- ^ why a local package is considered dirty , wDeps :: !(Set PackageName) -- ^ Packages which count as dependencies , wWarnings :: !([Text] -> [Text]) -- ^ Warnings } deriving Generic instance Monoid W where mempty = memptydefault mappend = mappenddefault type M = RWST Ctx W (Map PackageName (Either ConstructPlanException AddDepRes)) IO data Ctx = Ctx { mbp :: !MiniBuildPlan , baseConfigOpts :: !BaseConfigOpts , loadPackage :: !(PackageName -> Version -> Map FlagName Bool -> [Text] -> IO Package) , combinedMap :: !CombinedMap , toolToPackages :: !(Cabal.Dependency -> Map PackageName VersionRange) , ctxEnvConfig :: !EnvConfig , callStack :: ![PackageName] , extraToBuild :: !(Set PackageName) , getVersions :: !(PackageName -> IO (Set Version)) , wanted :: !(Set PackageName) , localNames :: !(Set PackageName) , logFunc :: Loc -> LogSource -> LogLevel -> LogStr -> IO () } instance HasStackRoot Ctx instance HasPlatform Ctx instance HasGHCVariant Ctx instance HasConfig Ctx instance HasBuildConfig Ctx where getBuildConfig = getBuildConfig . getEnvConfig instance HasEnvConfig Ctx where getEnvConfig = ctxEnvConfig constructPlan :: forall env m. (MonadCatch m, MonadReader env m, HasEnvConfig env, MonadIO m, MonadLoggerIO m, MonadBaseControl IO m, HasHttpManager env) => MiniBuildPlan -> BaseConfigOpts -> [LocalPackage] -> Set PackageName -- ^ additional packages that must be built -> [DumpPackage () ()] -- ^ locally registered -> (PackageName -> Version -> Map FlagName Bool -> [Text] -> IO Package) -- ^ load upstream package -> SourceMap -> InstalledMap -> m Plan constructPlan mbp0 baseConfigOpts0 locals extraToBuild0 localDumpPkgs loadPackage0 sourceMap installedMap = do let locallyRegistered = Map.fromList $ map (dpGhcPkgId &&& dpPackageIdent) localDumpPkgs getVersions0 <- getPackageVersionsIO econfig <- asks getEnvConfig let onWanted = void . addDep False . packageName . lpPackage let inner = do mapM_ onWanted $ filter lpWanted locals mapM_ (addDep False) $ Set.toList extraToBuild0 lf <- askLoggerIO ((), m, W efinals installExes dirtyReason deps warnings) <- liftIO $ runRWST inner (ctx econfig getVersions0 lf) M.empty mapM_ $logWarn (warnings []) let toEither (_, Left e) = Left e toEither (k, Right v) = Right (k, v) (errlibs, adrs) = partitionEithers $ map toEither $ M.toList m (errfinals, finals) = partitionEithers $ map toEither $ M.toList efinals errs = errlibs ++ errfinals if null errs then do let toTask (_, ADRFound _ _) = Nothing toTask (name, ADRToInstall task) = Just (name, task) tasks = M.fromList $ mapMaybe toTask adrs takeSubset = case boptsCLIBuildSubset $ bcoBuildOptsCLI baseConfigOpts0 of BSAll -> id BSOnlySnapshot -> stripLocals BSOnlyDependencies -> stripNonDeps deps return $ takeSubset Plan { planTasks = tasks , planFinals = M.fromList finals , planUnregisterLocal = mkUnregisterLocal tasks dirtyReason locallyRegistered sourceMap , planInstallExes = if boptsInstallExes $ bcoBuildOpts baseConfigOpts0 then installExes else Map.empty } else throwM $ ConstructPlanExceptions errs (bcStackYaml $ getBuildConfig econfig) where ctx econfig getVersions0 lf = Ctx { mbp = mbp0 , baseConfigOpts = baseConfigOpts0 , loadPackage = loadPackage0 , combinedMap = combineMap sourceMap installedMap , toolToPackages = \(Cabal.Dependency name _) -> maybe Map.empty (Map.fromSet (const Cabal.anyVersion)) $ Map.lookup (T.pack . packageNameString . fromCabalPackageName $ name) toolMap , ctxEnvConfig = econfig , callStack = [] , extraToBuild = extraToBuild0 , getVersions = getVersions0 , wanted = wantedLocalPackages locals , localNames = Set.fromList $ map (packageName . lpPackage) locals , logFunc = lf } -- TODO Currently, this will only consider and install tools from the -- snapshot. It will not automatically install build tools from extra-deps -- or local packages. toolMap = getToolMap mbp0 -- | Determine which packages to unregister based on the given tasks and -- already registered local packages mkUnregisterLocal :: Map PackageName Task -> Map PackageName Text -> Map GhcPkgId PackageIdentifier -> SourceMap -> Map GhcPkgId (PackageIdentifier, Maybe Text) mkUnregisterLocal tasks dirtyReason locallyRegistered sourceMap = Map.unions $ map toUnregisterMap $ Map.toList locallyRegistered where toUnregisterMap (gid, ident) = case M.lookup name tasks of Nothing -> case M.lookup name sourceMap of Just (PSUpstream _ Snap _ _ _) -> Map.singleton gid ( ident , Just "Switching to snapshot installed package" ) _ -> Map.empty Just _ -> Map.singleton gid ( ident , Map.lookup name dirtyReason ) where name = packageIdentifierName ident addFinal :: LocalPackage -> Package -> Bool -> M () addFinal lp package isAllInOne = do depsRes <- addPackageDeps False package res <- case depsRes of Left e -> return $ Left e Right (missing, present, _minLoc) -> do ctx <- ask return $ Right Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskConfigOpts = TaskConfigOpts missing $ \missing' -> let allDeps = Map.union present missing' in configureOpts (getEnvConfig ctx) (baseConfigOpts ctx) allDeps True -- local Local package , taskPresent = present , taskType = TTLocal lp , taskAllInOne = isAllInOne } tell mempty { wFinals = Map.singleton (packageName package) res } addDep :: Bool -- ^ is this being used by a dependency? -> PackageName -> M (Either ConstructPlanException AddDepRes) addDep treatAsDep' name = do ctx <- ask let treatAsDep = treatAsDep' || name `Set.notMember` wanted ctx when treatAsDep $ markAsDep name m <- get case Map.lookup name m of Just res -> return res Nothing -> do res <- if name `elem` callStack ctx then return $ Left $ DependencyCycleDetected $ name : callStack ctx else local (\ctx' -> ctx' { callStack = name : callStack ctx' }) $ case Map.lookup name $ combinedMap ctx of -- TODO look up in the package index and see if there's a -- recommendation available Nothing -> return $ Left $ UnknownPackage name Just (PIOnlyInstalled loc installed) -> do -- slightly hacky, no flags since they likely won't affect executable names tellExecutablesUpstream name (installedVersion installed) loc Map.empty return $ Right $ ADRFound loc installed Just (PIOnlySource ps) -> do tellExecutables name ps installPackage treatAsDep name ps Nothing Just (PIBoth ps installed) -> do tellExecutables name ps installPackage treatAsDep name ps (Just installed) modify $ Map.insert name res return res tellExecutables :: PackageName -> PackageSource -> M () tellExecutables _ (PSLocal lp) | lpWanted lp = tellExecutablesPackage Local $ lpPackage lp | otherwise = return () -- Ignores ghcOptions because they don't matter for enumerating -- executables. tellExecutables name (PSUpstream version loc flags _ghcOptions _gitSha) = tellExecutablesUpstream name version loc flags tellExecutablesUpstream :: PackageName -> Version -> InstallLocation -> Map FlagName Bool -> M () tellExecutablesUpstream name version loc flags = do ctx <- ask when (name `Set.member` extraToBuild ctx) $ do p <- liftIO $ loadPackage ctx name version flags [] tellExecutablesPackage loc p tellExecutablesPackage :: InstallLocation -> Package -> M () tellExecutablesPackage loc p = do cm <- asks combinedMap -- Determine which components are enabled so we know which ones to copy let myComps = case Map.lookup (packageName p) cm of Nothing -> assert False Set.empty Just (PIOnlyInstalled _ _) -> Set.empty Just (PIOnlySource ps) -> goSource ps Just (PIBoth ps _) -> goSource ps goSource (PSLocal lp) | lpWanted lp = exeComponents (lpComponents lp) | otherwise = Set.empty goSource (PSUpstream{}) = Set.empty tell mempty { wInstall = Map.fromList $ map (, loc) $ Set.toList $ filterComps myComps $ packageExes p } where filterComps myComps x | Set.null myComps = x | otherwise = Set.intersection x myComps installPackage :: Bool -- ^ is this being used by a dependency? -> PackageName -> PackageSource -> Maybe Installed -> M (Either ConstructPlanException AddDepRes) installPackage treatAsDep name ps minstalled = do ctx <- ask case ps of PSUpstream version _ flags ghcOptions _ -> do package <- liftIO $ loadPackage ctx name version flags ghcOptions resolveDepsAndInstall False treatAsDep ps package minstalled PSLocal lp -> case lpTestBench lp of Nothing -> resolveDepsAndInstall False treatAsDep ps (lpPackage lp) minstalled Just tb -> do -- Attempt to find a plan which performs an all-in-one -- build. Ignore the writer action + reset the state if -- it fails. s <- get res <- pass $ do res <- addPackageDeps treatAsDep tb let writerFunc w = case res of Left _ -> mempty _ -> w return (res, writerFunc) case res of Right deps -> do adr <- installPackageGivenDeps True ps tb minstalled deps -- FIXME: this redundantly adds the deps (but -- they'll all just get looked up in the map) addFinal lp tb True return $ Right adr Left _ -> do -- Reset the state to how it was before -- attempting to find an all-in-one build -- plan. put s -- Otherwise, fall back on building the -- tests / benchmarks in a separate step. res' <- resolveDepsAndInstall False treatAsDep ps (lpPackage lp) minstalled when (isRight res') $ do -- Insert it into the map so that it's -- available for addFinal. modify $ Map.insert name res' addFinal lp tb False return res' resolveDepsAndInstall :: Bool -> Bool -> PackageSource -> Package -> Maybe Installed -> M (Either ConstructPlanException AddDepRes) resolveDepsAndInstall isAllInOne treatAsDep ps package minstalled = do res <- addPackageDeps treatAsDep package case res of Left err -> return $ Left err Right deps -> liftM Right $ installPackageGivenDeps isAllInOne ps package minstalled deps installPackageGivenDeps :: Bool -> PackageSource -> Package -> Maybe Installed -> ( Set PackageIdentifier , Map PackageIdentifier GhcPkgId , InstallLocation ) -> M AddDepRes installPackageGivenDeps isAllInOne ps package minstalled (missing, present, minLoc) = do let name = packageName package ctx <- ask mRightVersionInstalled <- case (minstalled, Set.null missing) of (Just installed, True) -> do shouldInstall <- checkDirtiness ps installed package present (wanted ctx) return $ if shouldInstall then Nothing else Just installed (Just _, False) -> do let t = T.intercalate ", " $ map (T.pack . packageNameString . packageIdentifierName) (Set.toList missing) tell mempty { wDirty = Map.singleton name $ "missing dependencies: " <> addEllipsis t } return Nothing (Nothing, _) -> return Nothing return $ case mRightVersionInstalled of Just installed -> ADRFound (piiLocation ps) installed Nothing -> ADRToInstall Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskConfigOpts = TaskConfigOpts missing $ \missing' -> let allDeps = Map.union present missing' destLoc = piiLocation ps <> minLoc in configureOpts (getEnvConfig ctx) (baseConfigOpts ctx) allDeps (psLocal ps) -- An assertion to check for a recurrence of -- https://github.com/commercialhaskell/stack/issues/345 (assert (destLoc == piiLocation ps) destLoc) package , taskPresent = present , taskType = case ps of PSLocal lp -> TTLocal lp PSUpstream _ loc _ _ sha -> TTUpstream package (loc <> minLoc) sha , taskAllInOne = isAllInOne } addEllipsis :: Text -> Text addEllipsis t | T.length t < 100 = t | otherwise = T.take 97 t <> "..." addPackageDeps :: Bool -- ^ is this being used by a dependency? -> Package -> M (Either ConstructPlanException (Set PackageIdentifier, Map PackageIdentifier GhcPkgId, InstallLocation)) addPackageDeps treatAsDep package = do ctx <- ask deps' <- packageDepsWithTools package deps <- forM (Map.toList deps') $ \(depname, range) -> do eres <- addDep treatAsDep depname let getLatestApplicable = do vs <- liftIO $ getVersions ctx depname return (latestApplicableVersion range vs) case eres of Left e -> do let bd = case e of UnknownPackage name -> assert (name == depname) NotInBuildPlan _ -> Couldn'tResolveItsDependencies mlatestApplicable <- getLatestApplicable return $ Left (depname, (range, mlatestApplicable, bd)) Right adr -> do inRange <- if adrVersion adr `withinRange` range then return True else do let warn reason = tell mempty { wWarnings = (msg:) } where msg = T.concat [ "WARNING: Ignoring out of range dependency" , reason , ": " , T.pack $ packageIdentifierString $ PackageIdentifier depname (adrVersion adr) , ". " , T.pack $ packageNameString $ packageName package , " requires: " , versionRangeText range ] allowNewer <- asks $ configAllowNewer . getConfig if allowNewer then do warn " (allow-newer enabled)" return True else do x <- inSnapshot (packageName package) (packageVersion package) y <- inSnapshot depname (adrVersion adr) if x && y then do warn " (trusting snapshot over Hackage revisions)" return True else return False if inRange then case adr of ADRToInstall task -> return $ Right (Set.singleton $ taskProvides task, Map.empty, taskLocation task) ADRFound loc (Executable _) -> return $ Right (Set.empty, Map.empty, loc) ADRFound loc (Library ident gid) -> return $ Right (Set.empty, Map.singleton ident gid, loc) else do mlatestApplicable <- getLatestApplicable return $ Left (depname, (range, mlatestApplicable, DependencyMismatch $ adrVersion adr)) case partitionEithers deps of ([], pairs) -> return $ Right $ mconcat pairs (errs, _) -> return $ Left $ DependencyPlanFailures package (Map.fromList errs) where adrVersion (ADRToInstall task) = packageIdentifierVersion $ taskProvides task adrVersion (ADRFound _ installed) = installedVersion installed checkDirtiness :: PackageSource -> Installed -> Package -> Map PackageIdentifier GhcPkgId -> Set PackageName -> M Bool checkDirtiness ps installed package present wanted = do ctx <- ask moldOpts <- flip runLoggingT (logFunc ctx) $ tryGetFlagCache installed let configOpts = configureOpts (getEnvConfig ctx) (baseConfigOpts ctx) present (psLocal ps) (piiLocation ps) -- should be Local always package buildOpts = bcoBuildOpts (baseConfigOpts ctx) wantConfigCache = ConfigCache { configCacheOpts = configOpts , configCacheDeps = Set.fromList $ Map.elems present , configCacheComponents = case ps of PSLocal lp -> Set.map renderComponent $ lpComponents lp PSUpstream{} -> Set.empty , configCacheHaddock = shouldHaddockPackage buildOpts wanted (packageName package) || -- Disabling haddocks when old config had haddocks doesn't make dirty. maybe False configCacheHaddock moldOpts } let mreason = case moldOpts of Nothing -> Just "old configure information not found" Just oldOpts | Just reason <- describeConfigDiff config oldOpts wantConfigCache -> Just reason | True <- psForceDirty ps -> Just "--force-dirty specified" | Just files <- psDirty ps -> Just $ "local file changes: " <> addEllipsis (T.pack $ unwords $ Set.toList files) | otherwise -> Nothing config = getConfig ctx case mreason of Nothing -> return False Just reason -> do tell mempty { wDirty = Map.singleton (packageName package) reason } return True describeConfigDiff :: Config -> ConfigCache -> ConfigCache -> Maybe Text describeConfigDiff config old new | not (configCacheDeps new `Set.isSubsetOf` configCacheDeps old) = Just "dependencies changed" | not $ Set.null newComponents = Just $ "components added: " `T.append` T.intercalate ", " (map (decodeUtf8With lenientDecode) (Set.toList newComponents)) | not (configCacheHaddock old) && configCacheHaddock new = Just "rebuilding with haddocks" | oldOpts /= newOpts = Just $ T.pack $ concat [ "flags changed from " , show oldOpts , " to " , show newOpts ] | otherwise = Nothing where stripGhcOptions = go where go [] = [] go ("--ghc-option":x:xs) = go' x xs go ("--ghc-options":x:xs) = go' x xs go ((T.stripPrefix "--ghc-option=" -> Just x):xs) = go' x xs go ((T.stripPrefix "--ghc-options=" -> Just x):xs) = go' x xs go (x:xs) = x : go xs go' x xs = checkKeepers x $ go xs checkKeepers x xs = case filter isKeeper $ T.words x of [] -> xs keepers -> "--ghc-options" : T.unwords keepers : xs -- GHC options which affect build results and therefore should always -- force a rebuild -- -- For the most part, we only care about options generated by Stack -- itself isKeeper = (== "-fhpc") -- more to be added later userOpts = filter (not . isStackOpt) . (if configRebuildGhcOptions config then id else stripGhcOptions) . map T.pack . (\(ConfigureOpts x y) -> x ++ y) . configCacheOpts (oldOpts, newOpts) = removeMatching (userOpts old) (userOpts new) removeMatching (x:xs) (y:ys) | x == y = removeMatching xs ys removeMatching xs ys = (xs, ys) newComponents = configCacheComponents new `Set.difference` configCacheComponents old psForceDirty :: PackageSource -> Bool psForceDirty (PSLocal lp) = lpForceDirty lp psForceDirty (PSUpstream {}) = False psDirty :: PackageSource -> Maybe (Set FilePath) psDirty (PSLocal lp) = lpDirtyFiles lp psDirty (PSUpstream {}) = Nothing -- files never change in an upstream package psLocal :: PackageSource -> Bool psLocal (PSLocal _) = True psLocal (PSUpstream {}) = False -- | Get all of the dependencies for a given package, including guessed build -- tool dependencies. packageDepsWithTools :: Package -> M (Map PackageName VersionRange) packageDepsWithTools p = do ctx <- ask -- TODO: it would be cool to defer these warnings until there's an -- actual issue building the package. -- TODO: check if the tool is on the path before warning? let toEither (Cabal.Dependency (Cabal.PackageName name) _) mp = case Map.toList mp of [] -> Left (NoToolFound name (packageName p)) [_] -> Right mp xs -> Left (AmbiguousToolsFound name (packageName p) (map fst xs)) (warnings, toolDeps) = partitionEithers $ map (\dep -> toEither dep (toolToPackages ctx dep)) (packageTools p) tell mempty { wWarnings = (map toolWarningText warnings ++) } when (any isNoToolFound warnings) $ do let msg = T.unlines [ "Missing build-tools may be caused by dependencies of the build-tool being overridden by extra-deps." , "This should be fixed soon - see this issue https://github.com/commercialhaskell/stack/issues/595" ] tell mempty { wWarnings = (msg:) } return $ Map.unionsWith intersectVersionRanges $ packageDeps p : toolDeps data ToolWarning = NoToolFound String PackageName | AmbiguousToolsFound String PackageName [PackageName] isNoToolFound :: ToolWarning -> Bool isNoToolFound NoToolFound{} = True isNoToolFound _ = False toolWarningText :: ToolWarning -> Text toolWarningText (NoToolFound toolName pkgName) = "No packages found in snapshot which provide a " <> T.pack (show toolName) <> " executable, which is a build-tool dependency of " <> T.pack (show (packageNameString pkgName)) toolWarningText (AmbiguousToolsFound toolName pkgName options) = "Multiple packages found in snapshot which provide a " <> T.pack (show toolName) <> " exeuctable, which is a build-tool dependency of " <> T.pack (show (packageNameString pkgName)) <> ", so none will be installed.\n" <> "Here's the list of packages which provide it: " <> T.intercalate ", " (map packageNameText options) <> "\nSince there's no good way to choose, you may need to install it manually." -- | Strip out anything from the @Plan@ intended for the local database stripLocals :: Plan -> Plan stripLocals plan = plan { planTasks = Map.filter checkTask $ planTasks plan , planFinals = Map.empty , planUnregisterLocal = Map.empty , planInstallExes = Map.filter (/= Local) $ planInstallExes plan } where checkTask task = case taskType task of TTLocal _ -> False TTUpstream _ Local _ -> False TTUpstream _ Snap _ -> True stripNonDeps :: Set PackageName -> Plan -> Plan stripNonDeps deps plan = plan { planTasks = Map.filter checkTask $ planTasks plan , planFinals = Map.empty , planInstallExes = Map.empty -- TODO maybe don't disable this? } where checkTask task = packageIdentifierName (taskProvides task) `Set.member` deps markAsDep :: PackageName -> M () markAsDep name = tell mempty { wDeps = Set.singleton name } -- | Is the given package/version combo defined in the snapshot? inSnapshot :: PackageName -> Version -> M Bool inSnapshot name version = do p <- asks mbp ls <- asks localNames return $ fromMaybe False $ do guard $ not $ name `Set.member` ls mpi <- Map.lookup name (mbpPackages p) return $ mpiVersion mpi == version
sjakobi/stack
src/Stack/Build/ConstructPlan.hs
bsd-3-clause
30,000
0
31
10,750
7,033
3,529
3,504
613
11
{-# LANGUAGE OverloadedStrings #-} module DictCC.Serialize (handlePage) where import Control.Applicative ((<$>), (<*>)) import Control.Arrow import Control.Monad import Data.Bool import qualified Data.Text as T import DictCC.Util (slice) import Text.XML.Cursor hiding (bool) type TranslationTable = ((T.Text, T.Text), [(T.Text, T.Text)]) {-| Extract translations from the central <table> element on the HTML page. -} findTranslations :: Cursor -> Either T.Text TranslationTable findTranslations = ( bool <$> return . ( listToTuple . join . fmap ($/ contentsOfBTags) . slice 1 3 . ($/ element "td") . head &&& fmap ( listToTuple . fmap (T.intercalate " " . ($/ contentsOfAAndNestedBTags)) . slice 1 3 . child ) . contentRows ) <*> const (Left "No translations found, sorry.") <*> null . contentRows ) . ($// element "tr") where contentRows = join . fmap ($| hasAttribute "id") contentsOfBTags = (element "b" &/ orSelf (element "a" >=> child)) >=> content contentsOfAAndNestedBTags = (element "a" &/ orSelf (element "b" >=> child)) >=> content listToTuple [a, b] = (a, b) {-| Attempts to parse the provided HTML and extract a list of translations. -} handlePage :: Cursor -> Either T.Text TranslationTable handlePage c = let main = attributeIs "id" "maincontent" &/ element "table" in case c $// main of [_, transTable, _] -> findTranslations transTable _ -> Left "No translations found"
JustusAdam/dictcc
lib/DictCC/Serialize.hs
bsd-3-clause
1,675
0
23
499
454
248
206
-1
-1
-- | -- Module : Crypto.Number.Serialize -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : Good -- -- fast serialization primitives for integer {-# LANGUAGE BangPatterns #-} module Crypto.Number.Serialize ( i2osp , os2ip , i2ospOf , i2ospOf_ ) where import Crypto.Number.Basic import Crypto.Internal.Compat (unsafeDoIO) import qualified Crypto.Internal.ByteArray as B import qualified Crypto.Number.Serialize.Internal as Internal -- | os2ip converts a byte string into a positive integer os2ip :: B.ByteArrayAccess ba => ba -> Integer os2ip bs = unsafeDoIO $ B.withByteArray bs (\p -> Internal.os2ip p (B.length bs)) -- | i2osp converts a positive integer into a byte string -- -- first byte is MSB (most significant byte), last byte is the LSB (least significant byte) i2osp :: B.ByteArray ba => Integer -> ba i2osp 0 = B.allocAndFreeze 1 (\p -> Internal.i2osp 0 p 1 >> return ()) i2osp m = B.allocAndFreeze sz (\p -> Internal.i2osp m p sz >> return ()) where !sz = numBytes m -- | just like i2osp, but take an extra parameter for size. -- if the number is too big to fit in @len bytes, nothing is returned -- otherwise the number is padded with 0 to fit the @len required. i2ospOf :: B.ByteArray ba => Int -> Integer -> Maybe ba i2ospOf len m | len <= 0 = Nothing | m < 0 = Nothing | sz > len = Nothing | otherwise = Just $ B.unsafeCreate len (\p -> Internal.i2ospOf m p len >> return ()) where !sz = numBytes m -- | just like i2ospOf except that it doesn't expect a failure: i.e. -- an integer larger than the number of output bytes requested -- -- for example if you just took a modulo of the number that represent -- the size (example the RSA modulo n). i2ospOf_ :: B.ByteArray ba => Int -> Integer -> ba i2ospOf_ len = maybe (error "i2ospOf_: integer is larger than expected") id . i2ospOf len
nomeata/cryptonite
Crypto/Number/Serialize.hs
bsd-3-clause
1,970
0
12
428
427
228
199
25
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} import Database.Curry import Database.Redis import Options.Applicative -- import System.Remote.Monitoring (forkServer) import Filesystem.Path.CurrentOS (decodeString) data Option = Option { optPort :: Int , optPath :: Maybe FilePath } opts :: Parser Option opts = Option <$> option ( long "port" & short 'p' & metavar "PORT" & value 8854 & help "Port Number" ) <*> option ( long "file" & short 'f' & metavar "FILE" & reader (Just . Just) & value Nothing & help "dump file" ) main :: IO () main = execParser optsInfo >>= \Option{..} -> do -- forkServer "localhost" 8000 -- monitoring (`runServer` serverSettings optPort "*") $ def { configPath = fmap decodeString optPath , configSaveStrategy = [ SaveByFrequency 900 1 , SaveByFrequency 300 10 , SaveByFrequency 60 10000 ] } where optsInfo = info (helper <*> opts) ( fullDesc & header "curry-redis - a redis clone over CurryDB" )
tanakh/CurryDB
redis/main.hs
bsd-3-clause
1,114
0
13
318
287
149
138
31
1
-- | -- Module : StreamDOps -- Copyright : (c) 2018 Harendra Kumar -- -- License : BSD3 -- Maintainer : streamly@composewell.com {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} module StreamDOps where import Control.Monad (when) import Data.Maybe (isJust) import Prelude (Monad, Int, (+), ($), (.), return, (>), even, (<=), div, subtract, undefined, Maybe(..), not, (>>=), maxBound, fmap, odd, (==), flip, (<$>), (<*>), round, (/), (**), (<)) import qualified Prelude as P import qualified Streamly.Streams.StreamD as S import qualified Streamly.Internal.Data.Unfold as UF -- We try to keep the total number of iterations same irrespective of nesting -- of the loops so that the overhead is easy to compare. value, value2, value3, value16, maxValue :: Int value = 100000 value2 = round (P.fromIntegral value**(1/2::P.Double)) -- double nested loop value3 = round (P.fromIntegral value**(1/3::P.Double)) -- triple nested loop value16 = round (P.fromIntegral value**(1/16::P.Double)) -- triple nested loop maxValue = value ------------------------------------------------------------------------------- -- Stream generation and elimination ------------------------------------------------------------------------------- type Stream m a = S.Stream m a {-# INLINE sourceUnfoldr #-} sourceUnfoldr :: Monad m => Int -> Stream m Int sourceUnfoldr n = S.unfoldr step n where step cnt = if cnt > n + value then Nothing else Just (cnt, cnt + 1) {-# INLINE sourceUnfoldrN #-} sourceUnfoldrN :: Monad m => Int -> Int -> Stream m Int sourceUnfoldrN m n = S.unfoldr step n where step cnt = if cnt > n + m then Nothing else Just (cnt, cnt + 1) {-# INLINE sourceUnfoldrMN #-} sourceUnfoldrMN :: Monad m => Int -> Int -> Stream m Int sourceUnfoldrMN m n = S.unfoldrM step n where step cnt = if cnt > n + m then return Nothing else return (Just (cnt, cnt + 1)) {-# INLINE sourceUnfoldrM #-} sourceUnfoldrM :: Monad m => Int -> Stream m Int sourceUnfoldrM n = S.unfoldrM step n where step cnt = if cnt > n + value then return Nothing else return (Just (cnt, cnt + 1)) {-# INLINE sourceIntFromTo #-} sourceIntFromTo :: Monad m => Int -> Stream m Int sourceIntFromTo n = S.enumerateFromToIntegral n (n + value) {-# INLINE sourceFromList #-} sourceFromList :: Monad m => Int -> Stream m Int sourceFromList n = S.fromList [n..n+value] {-# INLINE source #-} source :: Monad m => Int -> Stream m Int source = sourceUnfoldrM ------------------------------------------------------------------------------- -- Elimination ------------------------------------------------------------------------------- {-# INLINE runStream #-} runStream :: Monad m => Stream m a -> m () runStream = S.drain {-# INLINE mapM_ #-} mapM_ :: Monad m => Stream m a -> m () mapM_ = S.mapM_ (\_ -> return ()) {-# INLINE toNull #-} toNull :: Monad m => Stream m Int -> m () toNull = runStream {-# INLINE uncons #-} {-# INLINE nullTail #-} {-# INLINE headTail #-} uncons, nullTail, headTail :: Monad m => Stream m Int -> m () uncons s = do r <- S.uncons s case r of Nothing -> return () Just (_, t) -> uncons t {-# INLINE tail #-} tail :: Monad m => Stream m a -> m () tail s = S.tail s >>= P.mapM_ tail nullTail s = do r <- S.null s when (not r) $ S.tail s >>= P.mapM_ nullTail headTail s = do h <- S.head s when (isJust h) $ S.tail s >>= P.mapM_ headTail {-# INLINE toList #-} toList :: Monad m => Stream m Int -> m [Int] toList = S.toList {-# INLINE foldl #-} foldl :: Monad m => Stream m Int -> m Int foldl = S.foldl' (+) 0 {-# INLINE last #-} last :: Monad m => Stream m Int -> m (Maybe Int) last = S.last ------------------------------------------------------------------------------- -- Transformation ------------------------------------------------------------------------------- {-# INLINE transform #-} transform :: Monad m => Stream m a -> m () transform = runStream {-# INLINE composeN #-} composeN :: Monad m => Int -> (Stream m Int -> Stream m Int) -> Stream m Int -> m () composeN n f = case n of 1 -> transform . f 2 -> transform . f . f 3 -> transform . f . f . f 4 -> transform . f . f . f . f _ -> undefined {-# INLINE scan #-} {-# INLINE map #-} {-# INLINE fmap #-} {-# INLINE mapM #-} {-# INLINE mapMaybe #-} {-# INLINE mapMaybeM #-} {-# INLINE filterEven #-} {-# INLINE filterAllOut #-} {-# INLINE filterAllIn #-} {-# INLINE takeOne #-} {-# INLINE takeAll #-} {-# INLINE takeWhileTrue #-} {-# INLINE takeWhileMTrue #-} {-# INLINE dropOne #-} {-# INLINE dropAll #-} {-# INLINE dropWhileTrue #-} {-# INLINE dropWhileMTrue #-} {-# INLINE dropWhileFalse #-} {-# INLINE foldrS #-} {-# INLINE foldlS #-} {-# INLINE concatMap #-} {-# INLINE intersperse #-} scan, map, fmap, mapM, mapMaybe, mapMaybeM, filterEven, filterAllOut, filterAllIn, takeOne, takeAll, takeWhileTrue, takeWhileMTrue, dropOne, dropAll, dropWhileTrue, dropWhileMTrue, dropWhileFalse, foldrS, foldlS, concatMap, intersperse :: Monad m => Int -> Stream m Int -> m () scan n = composeN n $ S.scanl' (+) 0 fmap n = composeN n $ Prelude.fmap (+1) map n = composeN n $ S.map (+1) mapM n = composeN n $ S.mapM return mapMaybe n = composeN n $ S.mapMaybe (\x -> if Prelude.odd x then Nothing else Just x) mapMaybeM n = composeN n $ S.mapMaybeM (\x -> if Prelude.odd x then return Nothing else return $ Just x) filterEven n = composeN n $ S.filter even filterAllOut n = composeN n $ S.filter (> maxValue) filterAllIn n = composeN n $ S.filter (<= maxValue) takeOne n = composeN n $ S.take 1 takeAll n = composeN n $ S.take maxValue takeWhileTrue n = composeN n $ S.takeWhile (<= maxValue) takeWhileMTrue n = composeN n $ S.takeWhileM (return . (<= maxValue)) dropOne n = composeN n $ S.drop 1 dropAll n = composeN n $ S.drop maxValue dropWhileTrue n = composeN n $ S.dropWhile (<= maxValue) dropWhileMTrue n = composeN n $ S.dropWhileM (return . (<= maxValue)) dropWhileFalse n = composeN n $ S.dropWhile (> maxValue) foldrS n = composeN n $ S.foldrS S.cons S.nil foldlS n = composeN n $ S.foldlS (flip S.cons) S.nil concatMap n = composeN n $ (\s -> S.concatMap (\_ -> s) s) intersperse n = composeN n $ S.intersperse maxValue ------------------------------------------------------------------------------- -- Iteration ------------------------------------------------------------------------------- iterStreamLen, maxIters :: Int iterStreamLen = 10 maxIters = 10000 {-# INLINE iterateSource #-} iterateSource :: Monad m => (Stream m Int -> Stream m Int) -> Int -> Int -> Stream m Int iterateSource g i n = f i (sourceUnfoldrMN iterStreamLen n) where f (0 :: Int) m = g m f x m = g (f (x P.- 1) m) {-# INLINE iterateMapM #-} {-# INLINE iterateScan #-} {-# INLINE iterateFilterEven #-} {-# INLINE iterateTakeAll #-} {-# INLINE iterateDropOne #-} {-# INLINE iterateDropWhileFalse #-} {-# INLINE iterateDropWhileTrue #-} iterateMapM, iterateScan, iterateFilterEven, iterateTakeAll, iterateDropOne, iterateDropWhileFalse, iterateDropWhileTrue :: Monad m => Int -> Stream m Int -- this is quadratic iterateScan = iterateSource (S.scanl' (+) 0) (maxIters `div` 10) iterateDropWhileFalse = iterateSource (S.dropWhile (> maxValue)) (maxIters `div` 10) iterateMapM = iterateSource (S.mapM return) maxIters iterateFilterEven = iterateSource (S.filter even) maxIters iterateTakeAll = iterateSource (S.take maxValue) maxIters iterateDropOne = iterateSource (S.drop 1) maxIters iterateDropWhileTrue = iterateSource (S.dropWhile (<= maxValue)) maxIters ------------------------------------------------------------------------------- -- Zipping and concat ------------------------------------------------------------------------------- {-# INLINE eqBy #-} eqBy :: (Monad m, P.Eq a) => S.Stream m a -> m P.Bool eqBy src = S.eqBy (==) src src {-# INLINE cmpBy #-} cmpBy :: (Monad m, P.Ord a) => S.Stream m a -> m P.Ordering cmpBy src = S.cmpBy P.compare src src {-# INLINE zip #-} zip :: Monad m => Stream m Int -> m () zip src = transform $ S.zipWith (,) src src {-# INLINE concatMapRepl4xN #-} concatMapRepl4xN :: Monad m => Stream m Int -> m () concatMapRepl4xN src = transform $ (S.concatMap (S.replicate 4) src) {-# INLINE concatMapURepl4xN #-} concatMapURepl4xN :: Monad m => Stream m Int -> m () concatMapURepl4xN src = transform $ S.concatMapU (UF.replicateM 4) src ------------------------------------------------------------------------------- -- Mixed Composition ------------------------------------------------------------------------------- {-# INLINE scanMap #-} {-# INLINE dropMap #-} {-# INLINE dropScan #-} {-# INLINE takeDrop #-} {-# INLINE takeScan #-} {-# INLINE takeMap #-} {-# INLINE filterDrop #-} {-# INLINE filterTake #-} {-# INLINE filterScan #-} {-# INLINE filterMap #-} scanMap, dropMap, dropScan, takeDrop, takeScan, takeMap, filterDrop, filterTake, filterScan, filterMap :: Monad m => Int -> Stream m Int -> m () scanMap n = composeN n $ S.map (subtract 1) . S.scanl' (+) 0 dropMap n = composeN n $ S.map (subtract 1) . S.drop 1 dropScan n = composeN n $ S.scanl' (+) 0 . S.drop 1 takeDrop n = composeN n $ S.drop 1 . S.take maxValue takeScan n = composeN n $ S.scanl' (+) 0 . S.take maxValue takeMap n = composeN n $ S.map (subtract 1) . S.take maxValue filterDrop n = composeN n $ S.drop 1 . S.filter (<= maxValue) filterTake n = composeN n $ S.take maxValue . S.filter (<= maxValue) filterScan n = composeN n $ S.scanl' (+) 0 . S.filter (<= maxBound) filterMap n = composeN n $ S.map (subtract 1) . S.filter (<= maxValue) ------------------------------------------------------------------------------- -- Nested Composition ------------------------------------------------------------------------------- {-# INLINE toNullApNested #-} toNullApNested :: Monad m => Stream m Int -> m () toNullApNested s = runStream $ do (+) <$> s <*> s {-# INLINE toNullNested #-} toNullNested :: Monad m => Stream m Int -> m () toNullNested s = runStream $ do x <- s y <- s return $ x + y {-# INLINE toNullNested3 #-} toNullNested3 :: Monad m => Stream m Int -> m () toNullNested3 s = runStream $ do x <- s y <- s z <- s return $ x + y + z {-# INLINE filterAllOutNested #-} filterAllOutNested :: Monad m => Stream m Int -> m () filterAllOutNested str = runStream $ do x <- str y <- str let s = x + y if s < 0 then return s else S.nil {-# INLINE filterAllInNested #-} filterAllInNested :: Monad m => Stream m Int -> m () filterAllInNested str = runStream $ do x <- str y <- str let s = x + y if s > 0 then return s else S.nil
harendra-kumar/asyncly
benchmark/StreamDOps.hs
bsd-3-clause
11,067
0
12
2,393
3,473
1,834
1,639
266
5
module Main where import Graphics.UI.SDL import Control.Monad import Control.Lens import Control.Monad.Trans.Class import Control.Monad.IO.Class import Control.Monad.State.Class import Rendering import Environment import Ship import Config main :: IO () main = withInit [InitEverything] $ do screen <- setVideoMode screenWidth screenHeight 32 [SWSurface] runMain $ do loadShipAssets ship <- runGame $ newShip screenCenter addAgent ship forever $ do start <- liftIO getTicks runGame $ updateEnvironment frameSeconds environment' <- use environment liftIO $ do renderEnvironment screen environment' end <- getTicks when (end - start < frameTicks) $ delay $ frameTicks - (end - start)
alexisVallet/haskell-shmup
Main.hs
bsd-3-clause
753
0
23
161
222
112
110
26
1
module Main where import Perceptron main :: IO () main = do putStrLn "AND" putStrLn $ show $ p_and $ v00 putStrLn $ show $ p_and $ v01 putStrLn $ show $ p_and $ v10 putStrLn $ show $ p_and $ v11 putStrLn "NAND" putStrLn $ show $ p_nand $ v00 putStrLn $ show $ p_nand $ v01 putStrLn $ show $ p_nand $ v10 putStrLn $ show $ p_nand $ v11 putStrLn "OR" putStrLn $ show $ p_or $ v00 putStrLn $ show $ p_or $ v01 putStrLn $ show $ p_or $ v10 putStrLn $ show $ p_or $ v11 putStrLn "XOR" putStrLn $ show $ p_xor $ v00 putStrLn $ show $ p_xor $ v01 putStrLn $ show $ p_xor $ v10 putStrLn $ show $ p_xor $ v11
chupaaaaaaan/nn-with-haskell
app/Main02.hs
bsd-3-clause
646
0
9
178
286
133
153
24
1
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell import Language.Haskell.Liquid.Prelude [lq| include <len.hquals> |] [lq| measure rlen :: [a] -> Int rlen ([]) = {v | v = 0} rlen (y:ys) = {v | v = (1 + rlen(ys))} |] [lq| foo :: a -> {v:[b] | rlen(v) = 0} |] foo x = [] [lq| mylen :: xs:[a] -> {v:Int | v = rlen(xs)} |] mylen :: [a] -> Int mylen [] = 0 mylen (_:xs) = 1 + mylen xs [lq| mymap :: (a -> b) -> xs:[a] -> {v:[b] | rlen(v) = rlen(xs)} |] mymap f [] = [] mymap f (x:xs) = (f x) : (mymap f xs)
spinda/liquidhaskell
tests/gsoc15/unknown/pos/meas8.hs
bsd-3-clause
547
0
7
155
150
86
64
14
1
module Blog.Widgets.StreamOfConsciousness.Twitter ( start_twitter_tweets, start_twitter_replies ) where import qualified Blog.Widgets.StreamOfConsciousness.Thought as T import Blog.Widgets.StreamOfConsciousness.Controller ( SoCController, Worker ( .. ), commit ) import Data.List (isPrefixOf) import Text.ParserCombinators.Parsec import qualified System.Log.Logger as L import Network.HTTP import Network.HTTP.Headers import Network.URI ( parseURI ) import Data.Maybe ( fromJust ) import Data.List ( elemIndex, intersperse ) import qualified Text.XHtml.Strict as X import Text.JSON import qualified Codec.Binary.Base64.String as B64 import Blog.Widgets.JsonUtilities import Blog.BackEnd.HttpPoller data Kind = Tweet | Reply method :: Kind -> String method Tweet = "user_timeline" method Reply = "replies" handler :: Kind -> SoCController -> String -> String -> IO () handler Tweet = handle_tweets handler Reply = handle_replies log_handle :: Kind -> String log_handle Tweet = "TwitterTweets" log_handle Reply = "TwitterReplies" twitter_period :: Int twitter_period = 15 * 60 * 10^6 -- fifteen minutes in milliseconds start_twitter_tweets :: SoCController -> String -> String -> IO Worker start_twitter_tweets = start_twitter Tweet start_twitter_replies :: SoCController -> String -> String -> IO Worker start_twitter_replies = start_twitter Reply start_twitter :: Kind -> SoCController -> String -> String -> IO Worker start_twitter kind socc user password = do { let req = build_request kind user password ; p <- start_poller (log_handle kind) req ((handler kind) socc user) twitter_period ; return $ Worker socc p } build_request :: Kind -> String -> String -> Request String build_request kind user password = Request uri GET heads "" where uri = fromJust $ parseURI $ "http://twitter.com/statuses/" ++ (method kind) ++ ".json" heads = [ Header HdrAuthorization $ (++) "Basic " $ B64.encode $ user ++ ":" ++ password ] handle_tweets :: SoCController -> String -> String -> IO () handle_tweets socc user body = case parse_utf8_json body of Right v@(JSArray _) -> commit socc $ tweets_to_thoughts user v Right _ -> L.errorM (log_handle Tweet) $ "Unexpected non-array JSON response that starts with: " ++ (take 100 body) ++ " [...]" Left err_message -> L.errorM (log_handle Tweet) err_message tweets_to_thoughts :: String -> JSValue -> [T.Thought] tweets_to_thoughts user v = map (\ (d,u,t) -> T.Thought T.TwitterTweet d u t Nothing) $ zip3 times urls texts where texts = map (tweet_body_to_xhtml . uns) $ una $ v </> "text" times = map (convert_twitter_tstmp . uns) $ una $ v </> "created_at" urls = map ((tweet_id_to_link user) . show . unn) $ una $ v </> "id" handle_replies :: SoCController -> String -> String -> IO () handle_replies socc user body = case parse_utf8_json body of Right v@(JSArray _) -> commit socc $ replies_to_thoughts user v Right _ -> L.errorM (log_handle Reply) $ "Unexpected non-array JSON response that starts with: " ++ (take 100 body) ++ " [...]" Left err_message -> L.errorM (log_handle Reply) err_message replies_to_thoughts :: String -> JSValue -> [T.Thought] replies_to_thoughts user v = map (\ (d,u,t) -> T.Thought T.TwitterReply d u t Nothing) $ zip3 times urls texts where tweet_ids = map (show . unn) $ una $ v </> "id" users = uns_ $ v </> "user" </> "screen_name" urls = map (uncurry tweet_id_to_link) $ zip users tweet_ids pre_texts = uns_ $ v </> "text" texts = map (tweet_body_to_xhtml . (uncurry $ process_reply user)) $ zip users pre_texts times = map convert_twitter_tstmp $ uns_ $ v </> "created_at" tweet_id_to_link :: String -> String -> String tweet_id_to_link user t_id = "http://twitter.com/" ++ user ++ "/statuses/" ++ t_id tweet_body_to_xhtml :: String -> String tweet_body_to_xhtml = X.showHtmlFragment . (X.thespan X.! [ X.theclass "tweet_text" ]) . X.primHtml . pre_process convert_twitter_tstmp :: String -> String convert_twitter_tstmp ts = concat [ y, "-", mo', "-", d, "T", tm, "Z" ] where mo = take 3 $ drop 4 ts mo' = pad $ 1 + ( fromJust $ elemIndex mo [ "Jan", "Feb", "Mar", "Apr", "May", "Jun" , "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] ) pad = \n -> if n <10 then ('0':show n) else show n y = take 4 $ drop 26 ts d = take 2 $ drop 8 ts tm = take 8 $ drop 11 ts pre_process :: String -> String pre_process s = case parse pre_process_parser "" s of Left err -> error . show $ err Right v -> v pre_process_parser :: Parser String pre_process_parser = do { ts <- tok `sepBy` (many1 space) ; return $ concat . (intersperse " ") $ ts } tok :: Parser String tok = try http_link <|> try at_someone <|> try paren_http_link <|> try sqb_at_someone <|> word word :: Parser String word = many1 $ noneOf " " sqb_at_someone :: Parser String sqb_at_someone = do { string "[@" ; s <- many1 $ noneOf " ]" ; char ']' ; return $ "[from <a href=\"http://twitter.com/" ++ (urlEncode s) ++ "\">@" ++ s ++ "</a>] " } at_someone :: Parser String at_someone = do { char '@' ; s <- many1 $ noneOf " " ; return $ "<a href=\"http://twitter.com/" ++ (urlEncode s) ++ "\">@" ++ s ++ "</a>" } http_link :: Parser String http_link = do { string "http://" ; s <- many1 $ noneOf " " ; return $ "<a href=\"http://" ++ s ++ "\">" ++ s ++ "</a>" } paren_http_link :: Parser String paren_http_link = do { string "(http://" ; s <- many1 $ noneOf " )" ; char ')' ; return $ "(<a href=\"http://" ++ s ++ "\">" ++ s ++ "</a>)" } process_reply :: String -> String -> String -> String process_reply user from_user body = "[@" ++ from_user ++ "] " ++ userless_body where ul = length user userless_body = if ('@':user) `isPrefixOf` body then drop (ul + 1) body else body
prb/perpubplat
src/Blog/Widgets/StreamOfConsciousness/Twitter.hs
bsd-3-clause
6,387
0
15
1,712
2,011
1,050
961
125
3
module Camera( -- * Primitives yaw,yawGoal,pitch,pitchGoal,scl,sclGoal,center,centerGoal, -- * Utilities zoomIn,zoomOut, cameraLeft,cameraRight,cameraUp,cameraDown ) where import Graphics import Utils -- |The horizontal angle yaw = mkRef (0::GLfloat) -- |The horizontal angle goal yawGoal = mkRef (25::GLfloat) -- |The vertical angle pitch = mkRef (0::GLfloat) -- |The vertical angle goal pitchGoal = mkRef (15::GLfloat) -- |The scale scl = mkRef (1::GLfloat) -- |The scale goal sclGoal = mkRef (1::GLfloat) -- |The center of view center = mkRef (pure 0::Vector3 GLfloat) -- |The center goal centerGoal = mkRef (pure 0::Vector3 GLfloat) zoomIn = sclGoal $~ (*1.05) ; zoomOut = sclGoal $~ (/1.05) cameraLeft angle = yawGoal $~ subtract angle cameraRight angle = yawGoal $~ (+angle) cameraUp angle = pitchGoal $~ (inRange (-90,90).(+angle)) cameraDown angle = pitchGoal $~ (inRange (-90,90).subtract angle)
lih/Epsilon
src/Camera.hs
bsd-3-clause
929
1
10
150
309
182
127
19
1
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} module Language.Loop.Syntax where import Data.Foldable import Data.Traversable data Stmt reg = Inc reg | Dec reg | Clr reg | Output reg | Input reg | While reg [Stmt reg] deriving (Show, Functor, Foldable, Traversable)
gergoerdi/brainfuck
language-registermachine/src/Language/Loop/Syntax.hs
bsd-3-clause
371
0
8
127
80
47
33
11
0
module Logo.TokenParser (tokenize) where import Logo.Types import Control.Applicative ((<|>), (<$>), many) import Text.ParserCombinators.Parsec ( char, letter, digit, alphaNum, string, space, parse, many1, skipMany, notFollowedBy, noneOf, try, (<?>), eof, ParseError, Parser) import Text.ParserCombinators.Parsec.Number (natFloat, sign) tokenize :: String -> String -> Either ParseError [LogoToken] tokenize progName = parse logo progName logo :: Parser [LogoToken] logo = do skipMany space expressions <- many1 logoExpr skipMany space eof return $ concat expressions logoExpr :: Parser [LogoToken] logoExpr = try comment <|> try list <|> try binaryExpr <|> try parenExpr <|> try word <?> "Logo Expression" comment :: Parser [LogoToken] comment = do skipMany space string ";" skipMany $ noneOf "\n" skipMany space return [] word :: Parser [LogoToken] word = try identifier <|> try stringLiteral <|> try varLiteral <|> try numLiteral <?> "Logo terminal" identifier :: Parser [LogoToken] identifier = do skipMany space s <- letter i <- many alphaNum return . return $ (Identifier (s:i)) -- FIXME support escaping stringLiteral :: Parser [LogoToken] stringLiteral = do skipMany space char '"' s <- many1 $ noneOf "\t\n []()\"" return . return $ StrLiteral s varLiteral :: Parser [LogoToken] varLiteral = do skipMany space char ':' s <- letter v <- many alphaNum return . return $ VarLiteral (s:v) numLiteral :: Parser [LogoToken] numLiteral = do skipMany space s <- sign n <- natFloat return . return . NumLiteral . s $ case n of Left i -> fromInteger i Right f -> f operExpr :: Parser [LogoToken] operExpr = try parenExpr <|> try word binaryExpr :: Parser [LogoToken] binaryExpr = do lhs <- operExpr op <- operLiteral rhs <- try binaryExpr <|> operExpr return . concat $ [lhs, op, rhs] operLiteral :: Parser [LogoToken] operLiteral = do s <- many space (return . OperLiteral) <$> ( string "+" <|> if (length s) == 0 then (string "-") else ((string "-") >> notFollowedBy digit >> (return "-")) <|> string "*" <|> string "/" <|> string "%" <|> string "^" <|> try (string ">=") <|> try (string "<=") <|> try (string "<>") <|> string "=" <|> string "<" <|> string ">" ) list :: Parser [LogoToken] list = do skipMany space char '[' expr <- many logoExpr skipMany space char ']' return . return $ LogoList (concat expr) parenExpr :: Parser [LogoToken] parenExpr = do skipMany space char '(' skipMany space expr <- many logoExpr skipMany space char ')' return . return $ LogoExpr (concat expr)
deepakjois/hs-logo
src/Logo/TokenParser.hs
bsd-3-clause
2,716
0
25
632
1,031
499
532
106
2
module Language.Css.Values ( module X , CssBackgroundValue (..) , CssBGAttachment (..) , CssBGPosition (..) , CssBGPositionFloatX (..) , CssBGPositionFloatY (..) , CssBGPositionValue (..) , CssBorder (..) , CssBorderStyle (..) , CssBorderWidth (..) , CssBreak (..) , CssClear (..) , CssCollapse (..) , CssContent (..) , CssCursor (..) , CssDirection (..) , CssDisplay (..) , CssEmptyCells (..) , CssFloat (..) , CssFont (..) , CssFontStyle (..) , CssFontVariant (..) , CssFontWeight (..) , CssGenericFontFamily (..) , CssIdentifier , CssListStyle (..) , CssListStylePosition (..) , CssListStyleType (..) , CssOutline (..) , CssOutlineColor (..) , CssOverflow (..) , CssPageBreak (..) , CssPosition (..) , CssRepeat (..) , CssShape (..) , CssSide (..) , CssTableLayout (..) , CssTextAlign (..) , CssTextDecoration (..) , CssTextTransform (..) , CssUnicodeBidi (..) , CssValue (..) , CssVerticalAlign (..) , CssVisibility (..) , CssWhiteSpace (..) ) where import Language.Css.Values.Lengths as X import Language.Css.Values.Other as X import Language.Css.Values.Urls as X import Language.Css.Colors import Data.List.NonEmpty data CssValue a = CssValue a | CssInherit | CssInitial deriving (Show, Eq) data CssBGAttachment = CssBGScroll | CssBGFixed deriving (Show, Eq) data CssBGPositionFloatX = CssLeft | CssRight | CssCenterX deriving (Show, Eq) data CssBGPositionFloatY = CssTop | CssBottom | CssCenterY deriving (Show, Eq) data CssBGPositionValue a = CssBGPositionValue a | CssBGPositionPercentage CssPercentage | CssBGPositionLength CssLength deriving (Show, Eq) data CssBGPosition = CssBGPositionAbsolute (CssBGPositionValue CssBGPositionFloatX) (CssBGPositionValue CssBGPositionFloatY) | CssBGPositionRelative (Maybe (CssBGPositionValue CssBGPositionFloatX)) (Maybe (CssBGPositionValue CssBGPositionFloatY)) deriving (Show, Eq) data CssBackgroundValue = CssBackgroundValue (Maybe CssBGAttachment) (Maybe CssColor) (Maybe (Maybe CssUrl)) (Maybe CssBGPosition) (Maybe CssRepeat) deriving (Show, Eq) data CssRepeat = CssRepeat | CssRepeatX | CssRepeatY | CssNoRepeat deriving (Show, Eq) data CssCollapse = CssCollapse | CssSeparate deriving (Show, Eq) data CssBorderStyle = CssBorderHidden | CssBorderDotted | CssBorderDashed | CssBorderSolid | CssBorderDouble | CssBorderGroove | CssBorderRidge | CssBorderInset | CssBorderOutset deriving (Show, Eq) data CssBorderWidth = CssBorderThin | CssBorderMedium | CssBorderThick deriving (Show, Eq) data CssBorder = CssBorder (Maybe CssBorderStyle) (Maybe CssBorderWidth) (Maybe CssColor) deriving (Show, Eq) data CssShape = CssShape { shapeLeft :: Maybe CssLength , shapeRight :: Maybe CssLength , shapeTop :: Maybe CssLength , shapeBottom :: Maybe CssLength } deriving (Show, Eq) data CssContentChunk = CssContentString String | CssContentUrl CssUrl | CssContentCounter CssCounter | CssContentAttrIdentifier CssIdentifier | CssContentOpenQuote | CssContentCloseQuote | CssContentNoOpenQuote | CssContentNoCloseQuote deriving (Show, Eq) data CssContent = CssContentNormal | CssContent (NonEmpty CssContentChunk) deriving (Show, Eq) type CssCounter = String type CssIdentifier = String data CssSide = CssSideLeft | CssSideRight deriving (Show, Eq) data CssClear = CssClearLeft | CssClearRight | CssClearBoth deriving (Show, Eq) data CssCursor = CssCrossHair | CssCursorDefualt | CssPointer | CssMove | CssEResize | CssNEResize | CssNWResize | CssNResize | CssSEResize | CssSWResize | CssSResize | CssWResize | CssCursorText | CssWait | CssHelp | CssProgress deriving (Show, Eq) data CssDirection = CssLTR | CssRTL deriving (Show, Eq) data CssDisplay = CssInline | CssBlock | CssListItem | CssInlineBlock | CssTable | CssInlineTable | CssTableRowGroup | CssTableHeaderGroup | CssTableFooterGroup | CssTableRow | CssTableColumnGroup | CssTableColumn | CssTableCell | CssTableCaption deriving (Show, Eq) data CssEmptyCells = CssCellShow | CssCellHide deriving (Show, Eq) data CssFloat = CssFloatLeft | CssFloatRight deriving (Show, Eq) data CssFontStyle = CssItalic | CssOblique deriving (Show, Eq) data CssFontVariant = CssSmallCaps deriving (Show, Eq) data CssFontWeight = CssBold | CssBolder | CssLighter | CssFontWeight100 | CssFontWeight200 | CssFontWeight300 | CssFontWeight400 | CssFontWeight500 | CssFontWeight600 | CssFontWeight700 | CssFontWeight800 | CssFontWeight900 deriving (Show, Eq) data CssGenericFontFamily = CssFontSerif | CssFontSansSerif | CssFontCursive | CssFontFantasy | CssFontMonospace deriving (Show, Eq) data CssFontSpec = CssFontSpec { fontStyle :: Maybe CssFontStyle , fontVariant :: Maybe CssFontVariant , fontWeight :: Maybe CssFontWeight , fontSize :: CssLength , lineHeight :: Maybe CssLength , fontFamily :: NonEmpty CssGenericFontFamily } deriving (Show, Eq) data CssFont = CssFont CssFontSpec | CssFontCaption | CssFontIcon | CssFontMenu | CssFontMessageBox | CssSmallCaption | CssStatusBar deriving (Show, Eq) data CssListStylePosition = CssListStyleInside | CssListStyleOutside deriving (Show, Eq) data CssListStyleType = CssDisc | CssCircle | CssSquare | CssDecimal | CssDecimalLeadingZero | CssLowerRoman | CssUpperRoman | CssLowerGreek | CssLowerLatin | CssUpperLatin | CssArmenian | CssGeorgian | CssLowerAlpha | CssUpperAlpha deriving (Show, Eq) data CssListStyle = CssListStyle (Maybe CssListStyleType) (Maybe CssListStylePosition) (Maybe CssUrl) deriving (Show, Eq) data CssOutlineColor = CssInvert deriving (Show, Eq) data CssOutline = CssOutline (Maybe (Either CssOutlineColor CssColor)) (Maybe CssBorderStyle) (Maybe CssBorderWidth) deriving (Show, Eq) data CssOverflow = CssVisible | CssHidden | CssScroll deriving (Show, Eq) data CssBreak = CssAvoid deriving (Show, Eq) data CssPageBreak = CssPageAlways | CssPageLeft | CssPageRight deriving (Show, Eq) data CssPosition = CssStatic | CssRelative | CssAbsolute | CssFixed deriving (Show, Eq) data CssTableLayout = CssTableFixed deriving (Show, Eq) data CssTextAlign = CssTextLeft | CssTextRight | CssTextCenter | CssTextJustify deriving (Show, Eq) data CssTextUnderline = CssTextUnderline deriving (Show, Eq) data CssTextOverline = CssTextOverline deriving (Show, Eq) data CssTextLineThrough = CssTextLineThrough deriving (Show, Eq) data CssTextBlink = CssTextBlink deriving (Show, Eq) data CssTextDecoration = CssTextDecoration (Maybe CssTextUnderline) (Maybe CssTextOverline) (Maybe CssTextLineThrough) (Maybe CssTextBlink) deriving (Show, Eq) data CssTextTransform = CssTextCapitalize | CssTextUppercase | CssTextLowercase deriving (Show, Eq) data CssUnicodeBidi = CssUniNormal | CssUniEmbed | CssBidiOverride deriving (Show, Eq) data CssVerticalAlign = CssVBaseline | CssVSub | CssVSuper | CssVTop | CssVTextTop | CssVMiddle | CssVBottom | CssVTextBottom deriving (Show, Eq) data CssVisibility = CssVisVisible | CssVisHidden | CssVisCollapse deriving (Show, Eq) data CssWhiteSpace = CssNormal | CssPre | CssNowrap | CssPreWrap | CssPreLine deriving (Show, Eq)
athanclark/css-grammar
src/Language/Css/Values.hs
bsd-3-clause
7,625
0
10
1,597
1,958
1,178
780
328
0
{-# Language TypeSynonymInstances, FlexibleInstances #-} -- | UIs for live performances module Csound.Air.Live ( -- * Mixer mixer, hmixer, mixMono, -- * Effects FxFun, FxUI(..), fxBox, uiBox, fxColor, fxVer, fxHor, fxSca, fxApp, -- * Instrument choosers hinstrChooser, vinstrChooser, hmidiChooser, vmidiChooser, hpatchChooser, vpatchChooser, -- ** Fx units uiDistort, uiChorus, uiFlanger, uiPhaser, uiDelay, uiEcho, uiFilter, uiReverb, uiGain, uiWhite, uiPink, uiFx, uiRoom, uiHall, uiCave, uiSig, uiMix, uiMidi, uiPatch, -- * Static widgets AdsrBound(..), AdsrInit(..), linAdsr, expAdsr, classicWaves, masterVolume, masterVolumeKnob ) where import Control.Monad import Data.Colour import Data.Boolean import qualified Data.Colour.Names as C import Csound.Typed import Csound.Typed.Gui import Csound.Control.Midi import Csound.Control.Evt import Csound.Control.Instr import Csound.Control.Gui import Csound.Typed.Opcode hiding (space) import Csound.SigSpace import Csound.Air.Wave import Csound.Air.Fx import Csound.Air.Patch import Csound.Air.Misc ---------------------------------------------------------------------- -- mixer -- | The stereo signal processing function. type FxFun = Sig2 -> SE Sig2 instance SigSpace FxFun where mapSig f g = fmap (mapSig f) . g -- | Widget that represents a mixer. mixer :: [(String, SE Sig2)] -> Source Sig2 mixer = genMixer (ver, hor) -- | Widget that represents a mixer with horizontal grouping of elements. hmixer :: [(String, SE Sig2)] -> Source Sig2 hmixer = genMixer (hor, ver) genMixer :: ([Gui] -> Gui, [Gui] -> Gui) -> [(String, SE Sig2)] -> Source Sig2 genMixer (parentGui, childGui) as = source $ do gTags <- mapM box names (gs, vols) <- fmap unzip $ mapM (const $ defSlider "") names (gMutes, mutes) <- fmap unzip $ mapM (const $ toggleSig "" False) names gMasterTag <- box "master" (gMaster, masterVol) <- defSlider "" (gMasterMute, masterMute) <- toggleSig "" False let g = parentGui $ zipWith3 (\tag slid mute -> childGui [sca 0.8 tag, sca 8 slid, sca 1.1 mute]) (gMasterTag : gTags) (gMaster : gs) (gMasterMute : gMutes) muteVols = zipWith appMute mutes vols masterMuteVol = appMute masterMute masterVol res <- mul masterMuteVol $ mean $ zipWith mul muteVols sigs return (g, res) where (names, sigs) = unzip as appMute mute vol = (port (1 - mute) 0.05) * vol -- | Transforms the mono signal to the stereo input -- for the mixer widget. mixMono :: String -> Sig -> (String, SE Sig2) mixMono name asig = (name, return (asig, asig)) defSlider :: String -> Source Sig defSlider tag = slider tag (linSpan 0 1) 0.5 ---------------------------------------------------------------------- -- effects class FxUI a where applyFxArgs :: a -> [Sig] -> Sig2 -> SE Sig2 arityFx :: a -> Int instance FxUI (Sig2 -> Sig2) where applyFxArgs f _ x = return $ f x arityFx = const 0 instance FxUI FxFun where applyFxArgs f _ x = f x arityFx = const 0 instance FxUI a => FxUI (Sig -> a) where applyFxArgs f (a:as) x = applyFxArgs (f a) as x arityFx f = 1 + arityFx (proxy f) where proxy :: (a -> b) -> b proxy _ = undefined -- | Creates a widget that represents a stereo signal processing function. -- The parameters of the widget are updated with sliders. -- For example let's create a simple gain widget. It can be encoded like this: -- -- > uiGain :: Bool -> Double -> Source FxFun -- > uiGain isOn gain = fxBox "Gain" fx isOn [("gain", gain)] -- > where -- > fx :: Sig -> Sig2 -> Sig2 -- > fx = mul -- -- Let's look at the arguments of the function -- -- > fxBox name fx isOn args -- -- * @name@ -- is the name of the widget -- -- * @fx@ -- is signal processing function (see the class @FxUI@). -- -- * @isOn@ -- whether widget in the active state -- -- * @args@ -- list of initial values for arguments and names of the arguments. -- -- It's cool to set the color of the widget with @fxColor@ function. -- we can make our widgets much more intersting to look at. fxBox :: FxUI a => String -> a -> Bool -> [(String, Double)] -> Source FxFun fxBox name fx onOff args = source $ do (gOff0, off) <- toggleSig name onOff let gOff = setFontSize 25 gOff0 offRef <- newGlobalRef (0 :: Sig) writeRef offRef off let (names, initVals) = unzip $ take (arityFx fx) args (gs, as) <- fmap unzip $ mapM (\(name, initVal) -> slider name (linSpan 0 1) initVal) $ zip names initVals let f x = do ref <- newRef (0 :: Sig, 0 :: Sig) goff <- readRef offRef writeRef ref x when1 (goff ==* 1) $ do x2 <- readRef ref writeRef ref =<< applyFxArgs fx as x2 res <- readRef ref return res let gui = setBorder UpBoxBorder $ go (length names) gOff gs return (gui, f) where go n gOff gs | n == 0 = gOff | n < 4 = f (gs ++ replicate (4 - n) space) | otherwise = f gs where f xs = uiGroupGui gOff (ver xs) -- | Creates an FX-box from the given visual representation. -- It insertes a big On/Off button atop of the GUI. uiBox :: String -> Source FxFun -> Bool -> Source FxFun uiBox name fx onOff = mapGuiSource (setBorder UpBoxBorder) $ vlift2' uiOnOffSize uiBoxSize go off fx where off = mapGuiSource (setFontSize 25) $ toggleSig name onOff go off fx arg = mul off $ fx arg uiOnOffSize = 1.7 uiBoxSize = 8 uiGroupGui :: Gui -> Gui -> Gui uiGroupGui a b =ver [sca uiOnOffSize a, sca uiBoxSize b] sourceColor2 :: Color -> Source a -> Source a sourceColor2 col a = source $ do (g, x) <- a return (setColor2 col g, x) -- | Colors the source widgets. fxColor :: Color -> Source a -> Source a fxColor = sourceColor2 -- combine effects fxGroup :: ([Gui] -> Gui) -> [Source FxFun] -> Source FxFun fxGroup guiGroup as = do (gs, fs) <- fmap unzip $ sequence as return (guiGroup gs, foldl (\a b -> a >=> b) return fs) -- | Scales the gui for signal processing widgets. fxSca :: Double -> Source FxFun -> Source FxFun fxSca d a = fxGroup (\xs -> sca d $ head xs) [a] -- | Groups the signal processing widgets. -- The functions are composed the visuals are -- grouped horizontaly. fxHor :: [Source FxFun] -> Source FxFun fxHor = fxGroup hor -- | Groups the signal processing widgets. -- The functions are composed the visuals are -- grouped verticaly. fxVer :: [Source FxFun] -> Source FxFun fxVer = fxGroup ver -- | Applies a function to a signal processing function. fxApp :: FxFun -> Source FxFun -> Source FxFun fxApp f = mapSource (>=> f) -- | The distortion widget. The arguments are -- -- > uiDistort isOn levelOfDistortion drive tone uiDistort :: Bool -> Double -> Double -> Double -> Source FxFun uiDistort isOn level drive tone = sourceColor2 C.red $ fxBox "Distortion" fxDistort2 isOn [("level", level), ("drive", drive), ("tone", tone)] -- | The chorus widget. The arguments are -- -- > uiChorus isOn mix rate depth width uiChorus :: Bool -> Double -> Double -> Double -> Double -> Source FxFun uiChorus isOn mix rate depth width = sourceColor2 C.coral $ fxBox "Chorus" stChorus2 isOn [("mix",mix), ("rate",rate), ("depth",depth), ("width",width)] -- | The flanger widget. The arguments are -- -- > uiFlanger isOn mix feedback rate depth delay uiFlanger :: Bool -> Double -> Double -> Double -> Double -> Double -> Source FxFun uiFlanger isOn mix fback rate depth delay = sourceColor2 C.indigo $ fxBox "Flanger" fxFlanger2 isOn [("mix", mix), ("fback", fback), ("rate",rate), ("depth",depth), ("delay",delay)] -- | The phaser widget. The arguments are -- -- > uiPhaser isOn mix feedback rate depth frequency uiPhaser :: Bool -> Double -> Double -> Double -> Double -> Double -> Source FxFun uiPhaser isOn mix fback rate depth freq = sourceColor2 C.orange $ fxBox "Phaser" fxPhaser2 isOn [("mix", mix), ("fback", fback), ("rate",rate), ("depth",depth), ("freq", freq)] -- | The delay widget. The arguments are -- -- > uiDelay isOn mix feedback delayTime tone uiDelay :: Bool -> Double -> Double -> Double -> Double -> Source FxFun uiDelay isOn mix fback time tone = sourceColor2 C.dodgerblue $ fxBox "Delay" analogDelay2 isOn [("mix",mix), ("fback",fback), ("time",time), ("tone",tone)] -- | The simplified delay widget. The arguments are -- -- > uiEcho isOn maxDelayTime delayTime feedback uiEcho :: Bool -> D -> Double -> Double -> Source FxFun uiEcho isOn maxDelTime time fback = sourceColor2 C.deepskyblue $ fxBox "Echo" (fxEcho2 maxDelTime) isOn [("time", time), ("fback", fback)] -- | The pair of low and high pass filters -- -- > uiFilter isOn lowPassfrequency highPassFrequency gain uiFilter :: Bool -> Double -> Double -> Double -> Source FxFun uiFilter isOn lpf hpf gain = fxBox "Filter" fxFilter2 isOn [("lpf",lpf), ("hpf",hpf), ("gain",gain)] -- | The reverb widget. The arguments are: -- -- > uiReverb mix depth uiReverb :: Bool -> Double -> Double -> Source FxFun uiReverb isOn mix depth = sourceColor2 C.forestgreen $ fxBox "Reverb" (\mix depth asig -> mul (1 - mix) asig + mul mix (rever2 depth asig)) isOn [("mix", mix), ("depth", depth)] -- | The gain widget. The arguments are -- -- > uiGain isOn amountOfGain uiGain :: Bool -> Double -> Source FxFun uiGain isOn gain = sourceColor2 C.black $ fxBox "Gain" fxGain isOn [("gain", gain)] -- | The filtered white noize widget. The arguments are -- -- > uiWhite isOn centerFreqOfFilter amountOfNoize uiWhite :: Bool -> Double -> Double -> Source FxFun uiWhite isOn freq depth = sourceColor2 C.dimgray $ fxBox "White" fxWhite2 isOn [("freq", freq), ("depth", depth)] -- | The filtered pink noize widget. The arguments are -- -- > uiPink isOn centerFreqOfFilter amountOfNoize uiPink :: Bool -> Double -> Double -> Source FxFun uiPink isOn freq depth = sourceColor2 C.deeppink $ fxBox "Pink" fxPink2 isOn [("freq", freq), ("depth", depth)] -- | The constructor for signal processing functions with no arguments (controlls). uiFx :: FxUI a => String -> a -> Bool -> Source FxFun uiFx name f isOn = fxBox name f isOn [] -- | The reverb for room. uiRoom :: Bool -> Source FxFun uiRoom isOn = sourceColor2 C.limegreen $ uiFx "Room" smallRoom2 isOn -- | The reverb for hall. uiHall :: Bool -> Source FxFun uiHall isOn = sourceColor2 C.mediumseagreen $ uiFx "Hall" largeHall2 isOn -- | The reverb for magic cave. uiCave :: Bool -> Source FxFun uiCave isOn = sourceColor2 C.darkviolet $ uiFx "Cave" magicCave2 isOn -- | Midi chooser implemented as FX-box. uiMidi :: [(String, Msg -> SE Sig2)] -> Int -> Source FxFun uiMidi xs initVal = sourceColor2 C.forestgreen $ uiBox "Midi" fx True where fx = lift1 (\aout arg -> return $ aout + arg) $ vmidiChooser xs initVal -- | Patch chooser implemented as FX-box. uiPatch :: [(String, Patch2)] -> Int -> Source FxFun uiPatch xs initVal = sourceColor2 C.forestgreen $ uiBox "Patch" fx True where fx = lift1 (\aout arg -> return $ aout + arg) $ vpatchChooser xs initVal -- | the widget for mixing in a signal to the signal. uiSig :: String -> Bool -> Source Sig2 -> Source FxFun uiSig name onOff widget = source $ do (gs, asig) <- widget (gOff0, off) <- toggleSig name onOff let gOff = setFontSize 25 gOff0 f x = return $ x + mul (portk off 0.05) asig return (setBorder UpBoxBorder $ uiGroupGui gOff gs, f) -- | A mixer widget represented as an effect. -- The effect sums the signals with given wieghts. uiMix :: Bool -> [(String, SE Sig2)] -> Source FxFun uiMix onOff as = sourceColor2 C.blue $ uiSig "Mix" onOff (mixer as) ---------------------------------------------------------------------- -- Widgets data AdsrBound = AdsrBound { attBound :: Double , decBound :: Double , relBound :: Double } data AdsrInit = AdsrInit { attInit :: Double , decInit :: Double , susInit :: Double , relInit :: Double } expEps :: Fractional a => a expEps = 0.00001 linAdsr :: String -> AdsrBound -> AdsrInit -> Source Sig linAdsr = genAdsr $ \a d s r -> linsegr [0, a, 1, d, s] r 0 expAdsr :: String -> AdsrBound -> AdsrInit -> Source Sig expAdsr = genAdsr $ \a d s r -> expsegr [double expEps, a, 1, d, s] r (double expEps) genAdsr :: (D -> D -> D -> D -> Sig) -> String -> AdsrBound -> AdsrInit -> Source Sig genAdsr mkAdsr name b inits = source $ do (gatt, att) <- knob "A" (linSpan expEps $ attBound b) (attInit inits) (gdec, dec) <- knob "D" (linSpan expEps $ decBound b) (decInit inits) (gsus, sus) <- knob "S" (linSpan expEps 1) (susInit inits) (grel, rel) <- knob "R" (linSpan expEps $ relBound b) (relInit inits) let val = mkAdsr (ir att) (ir dec) (ir sus) (ir rel) gui <- setTitle name $ hor [gatt, gdec, gsus, grel] return (gui, val) -- | A widget with four standard waveforms: pure tone, triangle, square and sawtooth. -- The last parameter is a default waveform (it's set at init time). classicWaves :: String -> Int -> Source (Sig -> Sig) classicWaves name initVal = funnyRadio name [ ("osc", osc) , ("tri", tri) , ("sqr", sqr) , ("saw", saw)] initVal -- | Slider for master volume masterVolume :: Source Sig masterVolume = slider "master" uspan 0.5 -- | Knob for master volume masterVolumeKnob :: Source Sig masterVolumeKnob = knob "master" uspan 0.5 ---------------------------------------------------- -- instrument choosers genMidiChooser chooser xs initVal = joinSource $ lift1 midi $ chooser xs initVal -- | Chooses a midi instrument among several alternatives. It uses the @hradio@ for GUI groupping. hmidiChooser :: Sigs a => [(String, Msg -> SE a)] -> Int -> Source a hmidiChooser = genMidiChooser hinstrChooser -- | Chooses a midi instrument among several alternatives. It uses the @vradio@ for GUI groupping. vmidiChooser :: Sigs a => [(String, Msg -> SE a)] -> Int -> Source a vmidiChooser = genMidiChooser vinstrChooser -- | Chooses an instrument among several alternatives. It uses the @hradio@ for GUI groupping. hinstrChooser :: (Sigs b) => [(String, a -> SE b)] -> Int -> Source (a -> SE b) hinstrChooser = genInstrChooser hradioSig -- | Chooses an instrument among several alternatives. It uses the @vradio@ for GUI groupping. vinstrChooser :: (Sigs b) => [(String, a -> SE b)] -> Int -> Source (a -> SE b) vinstrChooser = genInstrChooser vradioSig genInstrChooser :: (Sigs b) => ([String] -> Int -> Source Sig) -> [(String, a -> SE b)] -> Int -> Source (a -> SE b) genInstrChooser widget xs initVal = lift1 (routeInstr instrs) $ widget names initVal where (names, instrs) = unzip xs -- go instrId arg = fmap sum $ mapM ( $ arg) $ zipWith (\n instr -> playWhen (sig (int n) ==* instrId) instr) [0 ..] instrs routeInstr :: Sigs b => [a -> SE b] -> Sig -> (a -> SE b) routeInstr instrs instrId arg = fmap sum $ mapM ( $ arg) $ zipWith (\n instr -> playWhen (sig (int n) ==* instrId) instr) [0 ..] instrs ---------------------------------------------------- -- effect choosers hpatchChooser :: (SigSpace a, Sigs a) => [(String, Patch D a)] -> Int -> Source a hpatchChooser = genPatchChooser hradioSig vpatchChooser :: (SigSpace a, Sigs a) => [(String, Patch D a)] -> Int -> Source a vpatchChooser = genPatchChooser vradioSig genPatchChooser :: (SigSpace a, Sigs a) => ([String] -> Int -> Source Sig) -> [(String, Patch D a)] -> Int -> Source a genPatchChooser widget xs initVal = joinSource $ lift1 go $ widget names initVal where (names, patches) = unzip xs go instrId = routeInstr fxs instrId =<< midi (routeInstr instrs instrId . ampCps) instrs = fmap patchInstr patches fxs = fmap getPatchFx patches
silky/csound-expression
src/Csound/Air/Live.hs
bsd-3-clause
15,866
0
17
3,452
4,956
2,630
2,326
-1
-1
{-# LANGUAGE NoImplicitPrelude , CPP , TemplateHaskell , FlexibleInstances , TypeSynonymInstances , TypeFamilies , PatternGuards , DeriveDataTypeable , TypeOperators #-} {- Refactoring plan: * need function to compute a (default) species from a Struct. - currently have structToSp :: Struct -> Q Exp. - [X] refactor it into two pieces, Struct -> SpeciesAST and SpeciesAST -> Q Exp. * should really go through and add some comments to things! Unfortunately I wasn't good about that when I wrote the code... =P * Maybe need to do a similar refactoring of the structToTy stuff? * make version of deriveSpecies that takes a SpeciesAST as an argument, and use Struct -> SpeciesAST to generate default * deriveSpecies should pass the SpeciesAST to... other things that currently just destruct the Struct to decide what to do. Will have to pattern-match on both the species and the Struct now and make sure that they match, which is a bit annoying, but can't really be helped. -} ----------------------------------------------------------------------------- -- | -- Module : Math.Combinatorics.Species.CycleIndex -- Copyright : (c) Brent Yorgey 2010 -- License : BSD-style (see LICENSE) -- Maintainer : byorgey@cis.upenn.edu -- Stability : experimental -- -- Use Template Haskell to automatically derive species instances for -- user-defined data types. -- ----------------------------------------------------------------------------- module Math.Combinatorics.Species.TH ( deriveDefaultSpecies , deriveSpecies ) where #if MIN_VERSION_numeric_prelude(0,2,0) import NumericPrelude hiding (cycle) #else import NumericPrelude import PreludeBase hiding (cycle) #endif import Math.Combinatorics.Species.Class import Math.Combinatorics.Species.Enumerate import Math.Combinatorics.Species.Structures import Math.Combinatorics.Species.AST import Math.Combinatorics.Species.AST.Instances () -- only import instances import Control.Arrow (first, second, (***)) import Control.Monad (zipWithM, liftM2, mapM, ap) import Control.Applicative (Applicative(..), (<$>), (<*>)) import Data.Char (toLower) import Data.Maybe (isJust) import Data.Typeable import Language.Haskell.TH import Language.Haskell.TH.Syntax (lift) ------------------------------------------------------------ -- Preliminaries ----------------------------------------- ------------------------------------------------------------ -- | Report a fatal error and stop processing in the 'Q' monad. errorQ :: String -> Q a errorQ msg = reportError msg >> error msg ------------------------------------------------------------ -- Parsing type declarations ----------------------------- ------------------------------------------------------------ -- XXX possible improvement: add special cases to Struct for things -- like Bool, Either, and (,) -- | A data structure to represent data type declarations. data Struct = SId | SList | SConst Type -- ^ for types of kind * | SEnum Type -- ^ for Enumerable type constructors of kind (* -> *) | SSumProd [(Name, [Struct])] -- ^ sum-of-products | SComp Struct Struct -- ^ composition | SSelf -- ^ recursive occurrence deriving Show -- | Extract the relevant information about a type constructor into a -- 'Struct'. nameToStruct :: Name -> Q Struct nameToStruct nm = reify nm >>= infoToStruct where infoToStruct (TyConI d) = decToStruct nm d infoToStruct _ = errorQ (show nm ++ " is not a type constructor.") -- XXX do something with contexts? Later extension... -- | Extract the relevant information about a data type declaration -- into a 'Struct', given the name of the type and the declaraion. decToStruct :: Name -> Dec -> Q Struct decToStruct _ (DataD _ nm [bndr] cons _) = SSumProd <$> mapM (conToStruct nm (tyVarNm bndr)) cons decToStruct _ (NewtypeD _ nm [bndr] con _) = SSumProd . (:[]) <$> conToStruct nm (tyVarNm bndr) con decToStruct _ (TySynD nm [bndr] ty) = tyToStruct nm (tyVarNm bndr) ty decToStruct nm _ = errorQ $ "Processing " ++ show nm ++ ": Only type constructors of kind * -> * are supported." -- | Throw away kind annotations to extract the type variable name. tyVarNm :: TyVarBndr -> Name tyVarNm (PlainTV n) = n tyVarNm (KindedTV n _) = n -- | Extract relevant information about a data constructor. The first -- two arguments are the name of the type constructor, and the name -- of its type argument. Returns the name of the data constructor -- and a list of descriptions of its arguments. conToStruct :: Name -> Name -> Con -> Q (Name, [Struct]) conToStruct nm var (NormalC cnm tys) = (,) cnm <$> mapM (tyToStruct nm var) (map snd tys) conToStruct nm var (RecC cnm tys) = (,) cnm <$> mapM (tyToStruct nm var) (map thrd tys) where thrd (_,_,t) = t conToStruct nm var (InfixC ty1 cnm ty2) = (,) cnm <$> mapM (tyToStruct nm var) [snd ty1, snd ty2] -- XXX do something with ForallC? -- XXX check this... -- | Extract a 'Struct' describing an arbitrary type. tyToStruct :: Name -> Name -> Type -> Q Struct tyToStruct nm var (VarT v) | v == var = return SId | otherwise = errorQ $ "Unknown variable " ++ show v tyToStruct nm var ListT = return SList tyToStruct nm var t@(ConT b) | b == ''[] = return SList | otherwise = return $ SConst t tyToStruct nm var (AppT t (VarT v)) -- F `o` TX === F | v == var && t == (ConT nm) = return $ SSelf -- recursive occurrence | v == var = return $ SEnum t -- t had better be Enumerable | otherwise = errorQ $ "Unknown variable " ++ show v tyToStruct nm var (AppT t1 t2@(AppT _ _)) -- composition = SComp <$> tyToStruct nm var t1 <*> tyToStruct nm var t2 tyToStruct nm vars t@(AppT _ _) = return $ SConst t -- XXX add something to deal with tuples? -- XXX add something to deal with things that are actually OK like Either a [a] -- and so on -- XXX deal with arrow types? ------------------------------------------------------------ -- Misc Struct utilities --------------------------------- ------------------------------------------------------------ -- | Decide whether a type is recursively defined, given its -- description. isRecursive :: Struct -> Bool isRecursive (SSumProd cons) = any isRecursive (concatMap snd cons) isRecursive (SComp s1 s2) = isRecursive s1 || isRecursive s2 isRecursive SSelf = True isRecursive _ = False ------------------------------------------------------------ -- Generating default species ---------------------------- ------------------------------------------------------------ -- | Convert a 'Struct' into a default corresponding species. structToSp :: Struct -> SpeciesAST structToSp SId = X structToSp SList = L structToSp (SConst (ConT t)) | t == ''Bool = N 2 | otherwise = error $ "structToSp: unrecognized type " ++ show t ++ " in SConst" structToSp (SEnum t) = error "SEnum in structToSp" structToSp (SSumProd []) = Zero structToSp (SSumProd ss) = foldl1 (+) $ map conToSp ss structToSp (SComp s1 s2) = structToSp s1 `o` structToSp s2 structToSp SSelf = Omega -- | Convert a data constructor and its arguments into a default -- species. conToSp :: (Name, [Struct]) -> SpeciesAST conToSp (_,[]) = One conToSp (_,ps) = foldl1 (*) $ map structToSp ps ------------------------------------------------------------ -- Generating things from species ------------------------ ------------------------------------------------------------ -- | Given a name to use in recursive occurrences, convert a species -- AST into an actual splice-able expression of type Species s => s. spToExp :: Name -> SpeciesAST -> Q Exp spToExp self = spToExp' where spToExp' Zero = [| 0 |] spToExp' One = [| 1 |] spToExp' (N n) = lift n spToExp' X = [| singleton |] spToExp' E = [| set |] spToExp' C = [| cycle |] spToExp' L = [| linOrd |] spToExp' Subset = [| subset |] spToExp' (KSubset k) = [| ksubset $(lift k) |] spToExp' Elt = [| element |] spToExp' (f :+ g) = [| $(spToExp' f) + $(spToExp' g) |] spToExp' (f :* g) = [| $(spToExp' f) * $(spToExp' g) |] spToExp' (f :. g) = [| $(spToExp' f) `o` $(spToExp' g) |] spToExp' (f :>< g) = [| $(spToExp' f) >< $(spToExp' g) |] spToExp' (f :@ g) = [| $(spToExp' f) @@ $(spToExp' g) |] spToExp' (Der f) = [| oneHole $(spToExp' f) |] spToExp' (OfSize _ _) = error "Can't reify general size predicate into code" spToExp' (OfSizeExactly f k) = [| $(spToExp' f) `ofSizeExactly` $(lift k) |] spToExp' (NonEmpty f) = [| nonEmpty $(spToExp' f) |] spToExp' (Rec _) = [| wrap $(varE self) |] spToExp' Omega = [| wrap $(varE self) |] -- | Generate the structure type for a given species. spToTy :: Name -> SpeciesAST -> Q Type spToTy self = spToTy' where spToTy' Zero = [t| Void |] spToTy' One = [t| Unit |] spToTy' (N n) = [t| Const Integer |] -- was finTy n, but that -- doesn't match up with the -- type annotation on TSpeciesAST spToTy' X = [t| Id |] spToTy' E = [t| Set |] spToTy' C = [t| Cycle |] spToTy' L = [t| [] |] spToTy' Subset = [t| Set |] spToTy' (KSubset _) = [t| Set |] spToTy' Elt = [t| Id |] spToTy' (f :+ g) = [t| $(spToTy' f) :+: $(spToTy' g) |] spToTy' (f :* g) = [t| $(spToTy' f) :*: $(spToTy' g) |] spToTy' (f :. g) = [t| $(spToTy' f) :.: $(spToTy' g) |] spToTy' (f :>< g) = [t| $(spToTy' f) :*: $(spToTy' g) |] spToTy' (f :@ g) = [t| $(spToTy' f) :.: $(spToTy' g) |] spToTy' (Der f) = [t| Star $(spToTy' f) |] spToTy' (OfSize f _) = spToTy' f spToTy' (OfSizeExactly f _) = spToTy' f spToTy' (NonEmpty f) = spToTy' f spToTy' (Rec _) = varT self spToTy' Omega = varT self {- -- | Generate a finite type of a given size, using a binary scheme. finTy :: Integer -> Q Type finTy 0 = [t| Void |] finTy 1 = [t| Unit |] finTy 2 = [t| Const Bool |] finTy n | even n = [t| Prod (Const Bool) $(finTy $ n `div` 2) |] | otherwise = [t| Sum Unit $(finTy $ pred n) |] -} ------------------------------------------------------------ -- Code generation --------------------------------------- ------------------------------------------------------------ -- Enumerable ---------------- -- | Generate an instance of the Enumerable type class, i.e. an -- isomorphism from the user's data type and the structure type -- corresponding to the chosen species (or to the default species if -- the user did not specify one). -- -- If the third argument is @Nothing@, generate a normal -- non-recursive instance. If the third argument is @Just code@, -- then the instance is for a recursive type with the given code. mkEnumerableInst :: Name -> SpeciesAST -> Struct -> Maybe Name -> Q Dec mkEnumerableInst nm sp st code = do clauses <- mkIsoClauses (isJust code) sp st let stTy = case code of Just cd -> [t| Mu $(conT cd) |] Nothing -> spToTy undefined sp -- undefined is OK, it isn't recursive -- so won't use that argument instanceD (return []) (appT (conT ''Enumerable) (conT nm)) -- [ tySynInstD ''StructTy [conT nm] stTy [ tySynInstD ''StructTy (tySynEqn [conT nm] stTy) , return $ FunD 'iso clauses ] -- | Generate the clauses for the definition of the 'iso' method in -- the 'Enumerable' instance, which translates from the structure -- type of the species to the user's data type. The first argument -- indicates whether the type is recursive. mkIsoClauses :: Bool -> SpeciesAST -> Struct -> Q [Clause] mkIsoClauses isRec sp st = (fmap.map) (mkClause isRec) (mkIsoMatches sp st) where mkClause False (pat, exp) = Clause [pat] (NormalB $ exp) [] mkClause True (pat, exp) = Clause [ConP 'Mu [pat]] (NormalB $ exp) [] mkIsoMatches :: SpeciesAST -> Struct -> Q [(Pat, Exp)] mkIsoMatches _ SId = newName "x" >>= \x -> return [(ConP 'Id [VarP x], VarE x)] mkIsoMatches _ (SConst t) | t == ConT ''Bool = return [(ConP 'Const [LitP $ IntegerL 1], ConE 'False) ,(ConP 'Const [LitP $ IntegerL 2], ConE 'True)] | otherwise = error "mkIsoMatches: unrecognized type in SConst case" mkIsoMatches _ (SEnum t) = newName "x" >>= \x -> return [(VarP x, AppE (VarE 'iso) (VarE x))] mkIsoMatches _ (SSumProd []) = return [] mkIsoMatches sp (SSumProd [con]) = mkIsoConMatches sp con mkIsoMatches sp (SSumProd cons) = addInjs 0 <$> zipWithM mkIsoConMatches (terms sp) cons where terms (f :+ g) = terms f ++ [g] terms f = [f] addInjs :: Int -> [[(Pat, Exp)]] -> [(Pat, Exp)] addInjs n [ps] = map (addInj (n-1) 'Inr) ps addInjs n (ps:pss) = map (addInj n 'Inl) ps ++ addInjs (n+1) pss addInj 0 c = first (ConP c . (:[])) addInj n c = first (ConP 'Inr . (:[])) . addInj (n-1) c -- XXX the below is not correct... -- should really do iso1 . fmap iso2 where iso1 = ... iso2 = ... -- which are obtained from recursive calls. mkIsoMatches _ (SComp s1 s2) = newName "x" >>= \x -> return [ (ConP 'Comp [VarP x] , AppE (VarE 'iso) (AppE (AppE (VarE 'fmap) (VarE 'iso)) (VarE x))) ] mkIsoMatches _ SSelf = newName "s" >>= \s -> return [(VarP s, AppE (VarE 'iso) (VarE s))] mkIsoConMatches :: SpeciesAST -> (Name, [Struct]) -> Q [(Pat, Exp)] mkIsoConMatches _ (cnm, []) = return [(ConP 'Unit [], ConE cnm)] mkIsoConMatches sp (cnm, ps) = map mkProd . sequence <$> zipWithM mkIsoMatches (factors sp) ps where factors (f :* g) = factors f ++ [g] factors f = [f] mkProd :: [(Pat, Exp)] -> (Pat, Exp) mkProd = (foldl1 (\x y -> (ConP '(:*:) [x, y])) *** foldl AppE (ConE cnm)) . unzip -- Species definition -------- -- | Given a name n, generate the declaration -- -- > n :: Species s => s -- mkSpeciesSig :: Name -> Q Dec mkSpeciesSig nm = sigD nm [t| Species s => s |] -- XXX can this use quasiquoting? -- | Given a name n and a species, generate a declaration for it of -- that name. The third parameter indicates whether the species is -- recursive, and if so what the name of the code is. mkSpecies :: Name -> SpeciesAST -> Maybe Name -> Q Dec mkSpecies nm sp (Just code) = valD (varP nm) (normalB (appE (varE 'rec) (conE code))) [] mkSpecies nm sp Nothing = valD (varP nm) (normalB (spToExp undefined sp)) [] {- structToSpAST :: Name -> Struct -> Q Exp structToSpAST _ SId = [| TX |] structToSpAST _ (SConst t) = error "SConst in structToSpAST?" structToSpAST self (SEnum t) = typeToSpAST self t structToSpAST _ (SSumProd []) = [| TZero |] structToSpAST self (SSumProd ss) = foldl1 (\x y -> [| annI $x :+ annI $y |]) $ map (conToSpAST self) ss structToSpAST self (SComp s1 s2) = [| annI $(structToSpAST self s1) :. annI $(structToSpAST self s2) |] structToSpAST self SSelf = varE self conToSpAST :: Name -> (Name, [Struct]) -> Q Exp conToSpAST _ (_,[]) = [| TOne |] conToSpAST self (_,ps) = foldl1 (\x y -> [| annI $x :* annI $y |]) $ map (structToSpAST self) ps typeToSpAST :: Name -> Type -> Q Exp typeToSpAST _ ListT = [| TL |] typeToSpAST self (ConT c) | c == ''[] = [| TL |] | otherwise = nameToStruct c >>= structToSpAST self -- XXX this is wrong! Need to do something else for recursive types? typeToSpAST _ _ = error "non-constructor in typeToSpAST?" -} ------------------------------------------------------------ -- Putting it all together ------------------------------- ------------------------------------------------------------ -- XXX need to add something to check whether the type and given -- species are compatible. -- | Generate default species declarations for the given user-defined -- data type. To use it: -- -- > {-# LANGUAGE TemplateHaskell, -- > TypeFamilies, -- > DeriveDataTypeable, -- > FlexibleInstances, -- > UndecidableInstances #-} -- > -- > data MyType = ... -- > -- > $(deriveDefaultSpecies ''MyType) -- -- Yes, you really do need all those extensions. And don't panic -- about the @UndecidableInstances@; the instances generated -- actually are decidable, but GHC just can't tell. -- -- This is what you get: -- -- * An 'Enumerable' instance for @MyType@ (and various other -- supporting things like a code and an 'ASTFunctor' instance if -- your data type is recursive) -- -- * A declaration of @myType :: Species s => s@ (the same name as -- the type constructor but with the first letter lowercased) -- -- You can then use @myType@ in any species expression, or as input -- to any function expecting a species. For example, to count your -- data type's distinct shapes, you can do -- -- > take 10 . unlabeled $ myType -- deriveDefaultSpecies :: Name -> Q [Dec] deriveDefaultSpecies nm = do st <- nameToStruct nm deriveSpecies nm (structToSp st) -- | Like 'deriveDefaultSpecies', except that you specify the species -- expression that your data type should be isomorphic to. Note: this -- is currently experimental (read: bug-ridden). deriveSpecies :: Name -> SpeciesAST -> Q [Dec] deriveSpecies nm sp = do st <- nameToStruct nm let spNm = mkName . map toLower . nameBase $ nm if (isRecursive st) then mkEnumerableRec nm spNm st sp else mkEnumerableNonrec nm spNm st sp where mkEnumerableRec nm spNm st sp = do codeNm <- newName (nameBase nm) self <- newName "self" let declCode = DataD [] codeNm [] [NormalC codeNm []] [''Typeable] [showCode] <- [d| instance Show $(conT codeNm) where show _ = $(lift (nameBase nm)) |] [interpCode] <- [d| type instance Interp $(conT codeNm) $(varT self) = $(spToTy self sp) |] applyBody <- NormalB <$> [| unwrap $(spToExp self sp) |] let astFunctorInst = InstanceD [] (AppT (ConT ''ASTFunctor) (ConT codeNm)) [FunD 'apply [Clause [WildP, VarP self] applyBody []]] [showMu] <- [d| instance Show a => Show (Mu $(conT codeNm) a) where show = show . unMu |] enum <- mkEnumerableInst nm sp st (Just codeNm) sig <- mkSpeciesSig spNm spD <- mkSpecies spNm sp (Just codeNm) return $ [ declCode , showCode , interpCode , astFunctorInst , showMu , enum , sig , spD ] mkEnumerableNonrec nm spNm st sp = sequence [ mkEnumerableInst nm sp st Nothing , mkSpeciesSig spNm , mkSpecies spNm sp Nothing ]
timsears/species
Math/Combinatorics/Species/TH.hs
bsd-3-clause
19,648
0
18
5,244
4,110
2,245
1,865
231
21
module Main where import Data.Binary import qualified Data.ByteString.Lazy as BL import Control.Monad (forM_, unless) import Control.Monad.IO.Class (MonadIO(..)) import Dxedrine.Blocks import Dxedrine.Model import Dxedrine.Parsing parseDxUnions :: MonadIO m => m (ParseResult DxUnion) parseDxUnions = do contents <- liftIO BL.getContents return $ getRepeated get contents main :: IO () main = do putStrLn "parsing" e <- parseDxUnions let numFailed = length $ keepFailed e unless (numFailed == 0) $ fail $ "number of failed messages: " ++ show numFailed let unions = keepSuccessful e forM_ unions $ \x -> do case getEntries x of Nothing -> return () Just p@(context, entries) -> putStrLn $ show (x, context, entries) putStrLn "done" return ()
ejconlon/dxedrine
app/Main.hs
bsd-3-clause
789
0
16
157
280
142
138
26
2
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Setup -- Copyright : (c) David Himmelstrup 2005 -- License : BSD-like -- -- Maintainer : lemmih@gmail.com -- Stability : provisional -- Portability : portable -- -- ----------------------------------------------------------------------------- module Distribution.Client.Setup ( globalCommand, GlobalFlags(..), defaultGlobalFlags, globalRepos , configureCommand, ConfigFlags(..), filterConfigureFlags , configureExCommand, ConfigExFlags(..), defaultConfigExFlags , configureExOptions , buildCommand, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..) , replCommand, testCommand, benchmarkCommand , installCommand, InstallFlags(..), installOptions, defaultInstallFlags , listCommand, ListFlags(..) , updateCommand , upgradeCommand , uninstallCommand , infoCommand, InfoFlags(..) , fetchCommand, FetchFlags(..) , freezeCommand, FreezeFlags(..) , getCommand, unpackCommand, GetFlags(..) , checkCommand , formatCommand , uploadCommand, UploadFlags(..) , reportCommand, ReportFlags(..) , runCommand , initCommand, IT.InitFlags(..) , sdistCommand, SDistFlags(..), SDistExFlags(..), ArchiveFormat(..) , win32SelfUpgradeCommand, Win32SelfUpgradeFlags(..) , sandboxCommand, defaultSandboxLocation, SandboxFlags(..) , execCommand, ExecFlags(..) , userConfigCommand, UserConfigFlags(..) , parsePackageArgs --TODO: stop exporting these: , showRepo , parseRepo ) where import Distribution.Client.Types ( Username(..), Password(..), Repo(..), RemoteRepo(..), LocalRepo(..) ) import Distribution.Client.BuildReports.Types ( ReportLevel(..) ) import Distribution.Client.Dependency.Types ( AllowNewer(..), PreSolver(..) ) import qualified Distribution.Client.Init.Types as IT ( InitFlags(..), PackageType(..) ) import Distribution.Client.Targets ( UserConstraint, readUserConstraint ) import Distribution.Utils.NubList ( NubList, toNubList, fromNubList) import Distribution.Simple.Compiler (PackageDB) import Distribution.Simple.Program ( defaultProgramConfiguration ) import Distribution.Simple.Command hiding (boolOpt, boolOpt') import qualified Distribution.Simple.Command as Command import qualified Distribution.Simple.Setup as Cabal import Distribution.Simple.Setup ( ConfigFlags(..), BuildFlags(..), ReplFlags , TestFlags(..), BenchmarkFlags(..) , SDistFlags(..), HaddockFlags(..) , readPackageDbList, showPackageDbList , Flag(..), toFlag, fromFlag, flagToMaybe, flagToList , optionVerbosity, boolOpt, boolOpt', trueArg, falseArg, optionNumJobs ) import Distribution.Simple.InstallDirs ( PathTemplate, InstallDirs(sysconfdir) , toPathTemplate, fromPathTemplate ) import Distribution.Version ( Version(Version), anyVersion, thisVersion ) import Distribution.Package ( PackageIdentifier, packageName, packageVersion, Dependency(..) ) import Distribution.PackageDescription ( RepoKind(..) ) import Distribution.Text ( Text(..), display ) import Distribution.ReadE ( ReadE(..), readP_to_E, succeedReadE ) import qualified Distribution.Compat.ReadP as Parse ( ReadP, readP_to_S, readS_to_P, char, munch1, pfail, sepBy1, (+++) ) import Distribution.Verbosity ( Verbosity, normal ) import Distribution.Simple.Utils ( wrapText, wrapLine ) import Data.Char ( isSpace, isAlphaNum ) import Data.List ( intercalate, deleteFirstsBy ) import Data.Maybe ( listToMaybe, maybeToList, fromMaybe ) #if !MIN_VERSION_base(4,8,0) import Data.Monoid ( Monoid(..) ) #endif import Control.Monad ( liftM ) import System.FilePath ( (</>) ) import Network.URI ( parseAbsoluteURI, uriToString ) -- ------------------------------------------------------------ -- * Global flags -- ------------------------------------------------------------ -- | Flags that apply at the top level, not to any sub-command. data GlobalFlags = GlobalFlags { globalVersion :: Flag Bool, globalNumericVersion :: Flag Bool, globalConfigFile :: Flag FilePath, globalSandboxConfigFile :: Flag FilePath, globalRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers. globalCacheDir :: Flag FilePath, globalLocalRepos :: NubList FilePath, globalLogsDir :: Flag FilePath, globalWorldFile :: Flag FilePath, globalRequireSandbox :: Flag Bool, globalIgnoreSandbox :: Flag Bool } defaultGlobalFlags :: GlobalFlags defaultGlobalFlags = GlobalFlags { globalVersion = Flag False, globalNumericVersion = Flag False, globalConfigFile = mempty, globalSandboxConfigFile = mempty, globalRemoteRepos = mempty, globalCacheDir = mempty, globalLocalRepos = mempty, globalLogsDir = mempty, globalWorldFile = mempty, globalRequireSandbox = Flag False, globalIgnoreSandbox = Flag False } globalCommand :: [Command action] -> CommandUI GlobalFlags globalCommand commands = CommandUI { commandName = "", commandSynopsis = "Command line interface to the Haskell Cabal infrastructure.", commandUsage = \pname -> "See http://www.haskell.org/cabal/ for more information.\n" ++ "\n" ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n", commandDescription = Just $ \pname -> let commands' = commands ++ [commandAddAction helpCommandUI undefined] cmdDescs = getNormalCommandDescriptions commands' -- if new commands are added, we want them to appear even if they -- are not included in the custom listing below. Thus, we calculate -- the `otherCmds` list and append it under the `other` category. -- Alternatively, a new testcase could be added that ensures that -- the set of commands listed here is equal to the set of commands -- that are actually available. otherCmds = deleteFirstsBy (==) (map fst cmdDescs) [ "help" , "update" , "install" , "fetch" , "list" , "info" , "user-config" , "get" , "init" , "configure" , "build" , "clean" , "run" , "repl" , "test" , "bench" , "check" , "sdist" , "upload" , "report" , "freeze" , "haddock" , "hscolour" , "copy" , "register" , "sandbox" , "exec" ] maxlen = maximum $ [length name | (name, _) <- cmdDescs] align str = str ++ replicate (maxlen - length str) ' ' startGroup n = " ["++n++"]" par = "" addCmd n = case lookup n cmdDescs of Nothing -> "" Just d -> " " ++ align n ++ " " ++ d addCmdCustom n d = case lookup n cmdDescs of -- make sure that the -- command still exists. Nothing -> "" Just _ -> " " ++ align n ++ " " ++ d in "Commands:\n" ++ unlines ( [ startGroup "global" , addCmd "update" , addCmd "install" , par , addCmd "help" , addCmd "info" , addCmd "list" , addCmd "fetch" , addCmd "user-config" , par , startGroup "package" , addCmd "get" , addCmd "init" , par , addCmd "configure" , addCmd "build" , addCmd "clean" , par , addCmd "run" , addCmd "repl" , addCmd "test" , addCmd "bench" , par , addCmd "check" , addCmd "sdist" , addCmd "upload" , addCmd "report" , par , addCmd "freeze" , addCmd "haddock" , addCmd "hscolour" , addCmd "copy" , addCmd "register" , par , startGroup "sandbox" , addCmd "sandbox" , addCmd "exec" , addCmdCustom "repl" "Open interpreter with access to sandbox packages." ] ++ if null otherCmds then [] else par :startGroup "other" :[addCmd n | n <- otherCmds]) ++ "\n" ++ "For more information about a command use:\n" ++ " " ++ pname ++ " COMMAND --help\n" ++ "or " ++ pname ++ " help COMMAND\n" ++ "\n" ++ "To install Cabal packages from hackage use:\n" ++ " " ++ pname ++ " install foo [--dry-run]\n" ++ "\n" ++ "Occasionally you need to update the list of available packages:\n" ++ " " ++ pname ++ " update\n", commandNotes = Nothing, commandDefaultFlags = mempty, commandOptions = \showOrParseArgs -> (case showOrParseArgs of ShowArgs -> take 6; ParseArgs -> id) [option ['V'] ["version"] "Print version information" globalVersion (\v flags -> flags { globalVersion = v }) trueArg ,option [] ["numeric-version"] "Print just the version number" globalNumericVersion (\v flags -> flags { globalNumericVersion = v }) trueArg ,option [] ["config-file"] "Set an alternate location for the config file" globalConfigFile (\v flags -> flags { globalConfigFile = v }) (reqArgFlag "FILE") ,option [] ["sandbox-config-file"] "Set an alternate location for the sandbox config file (default: './cabal.sandbox.config')" globalConfigFile (\v flags -> flags { globalSandboxConfigFile = v }) (reqArgFlag "FILE") ,option [] ["require-sandbox"] "requiring the presence of a sandbox for sandbox-aware commands" globalRequireSandbox (\v flags -> flags { globalRequireSandbox = v }) (boolOpt' ([], ["require-sandbox"]) ([], ["no-require-sandbox"])) ,option [] ["ignore-sandbox"] "Ignore any existing sandbox" globalIgnoreSandbox (\v flags -> flags { globalIgnoreSandbox = v }) trueArg ,option [] ["remote-repo"] "The name and url for a remote repository" globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v }) (reqArg' "NAME:URL" (toNubList . maybeToList . readRepo) (map showRepo . fromNubList)) ,option [] ["remote-repo-cache"] "The location where downloads from all remote repos are cached" globalCacheDir (\v flags -> flags { globalCacheDir = v }) (reqArgFlag "DIR") ,option [] ["local-repo"] "The location of a local repository" globalLocalRepos (\v flags -> flags { globalLocalRepos = v }) (reqArg' "DIR" (\x -> toNubList [x]) fromNubList) ,option [] ["logs-dir"] "The location to put log files" globalLogsDir (\v flags -> flags { globalLogsDir = v }) (reqArgFlag "DIR") ,option [] ["world-file"] "The location of the world file" globalWorldFile (\v flags -> flags { globalWorldFile = v }) (reqArgFlag "FILE") ] } instance Monoid GlobalFlags where mempty = GlobalFlags { globalVersion = mempty, globalNumericVersion = mempty, globalConfigFile = mempty, globalSandboxConfigFile = mempty, globalRemoteRepos = mempty, globalCacheDir = mempty, globalLocalRepos = mempty, globalLogsDir = mempty, globalWorldFile = mempty, globalRequireSandbox = mempty, globalIgnoreSandbox = mempty } mappend a b = GlobalFlags { globalVersion = combine globalVersion, globalNumericVersion = combine globalNumericVersion, globalConfigFile = combine globalConfigFile, globalSandboxConfigFile = combine globalConfigFile, globalRemoteRepos = combine globalRemoteRepos, globalCacheDir = combine globalCacheDir, globalLocalRepos = combine globalLocalRepos, globalLogsDir = combine globalLogsDir, globalWorldFile = combine globalWorldFile, globalRequireSandbox = combine globalRequireSandbox, globalIgnoreSandbox = combine globalIgnoreSandbox } where combine field = field a `mappend` field b globalRepos :: GlobalFlags -> [Repo] globalRepos globalFlags = remoteRepos ++ localRepos where remoteRepos = [ Repo (Left remote) cacheDir | remote <- fromNubList $ globalRemoteRepos globalFlags , let cacheDir = fromFlag (globalCacheDir globalFlags) </> remoteRepoName remote ] localRepos = [ Repo (Right LocalRepo) local | local <- fromNubList $ globalLocalRepos globalFlags ] -- ------------------------------------------------------------ -- * Config flags -- ------------------------------------------------------------ configureCommand :: CommandUI ConfigFlags configureCommand = (Cabal.configureCommand defaultProgramConfiguration) { commandDefaultFlags = mempty } configureOptions :: ShowOrParseArgs -> [OptionField ConfigFlags] configureOptions = commandOptions configureCommand filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags filterConfigureFlags flags cabalLibVersion | cabalLibVersion >= Version [1,22,0] [] = flags_latest -- ^ NB: we expect the latest version to be the most common case. | cabalLibVersion < Version [1,3,10] [] = flags_1_3_10 | cabalLibVersion < Version [1,10,0] [] = flags_1_10_0 | cabalLibVersion < Version [1,14,0] [] = flags_1_14_0 | cabalLibVersion < Version [1,18,0] [] = flags_1_18_0 | cabalLibVersion < Version [1,19,1] [] = flags_1_19_0 | cabalLibVersion < Version [1,19,2] [] = flags_1_19_1 | cabalLibVersion < Version [1,21,1] [] = flags_1_20_0 | cabalLibVersion < Version [1,22,0] [] = flags_1_21_0 | otherwise = flags_latest where -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'. flags_latest = flags { configConstraints = [] } -- Cabal < 1.22 doesn't know about '--disable-debug-info'. flags_1_21_0 = flags_latest { configDebugInfo = NoFlag } -- Cabal < 1.21.1 doesn't know about 'disable-relocatable' -- Cabal < 1.21.1 doesn't know about 'enable-profiling' flags_1_20_0 = flags_1_21_0 { configRelocatable = NoFlag , configProf = NoFlag , configProfExe = configProf flags , configProfLib = mappend (configProf flags) (configProfLib flags) , configCoverage = NoFlag , configLibCoverage = configCoverage flags } -- Cabal < 1.19.2 doesn't know about '--exact-configuration' and -- '--enable-library-stripping'. flags_1_19_1 = flags_1_20_0 { configExactConfiguration = NoFlag , configStripLibs = NoFlag } -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'. flags_1_19_0 = flags_1_19_1 { configDependencies = [] , configConstraints = configConstraints flags } -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir. flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = toNubList [] , configInstallDirs = configInstallDirs_1_18_0} configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag } -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'. flags_1_14_0 = flags_1_18_0 { configBenchmarks = NoFlag } -- Cabal < 1.10.0 doesn't know about '--disable-tests'. flags_1_10_0 = flags_1_14_0 { configTests = NoFlag } -- Cabal < 1.3.10 does not grok the '--constraints' flag. flags_1_3_10 = flags_1_10_0 { configConstraints = [] } -- ------------------------------------------------------------ -- * Config extra flags -- ------------------------------------------------------------ -- | cabal configure takes some extra flags beyond runghc Setup configure -- data ConfigExFlags = ConfigExFlags { configCabalVersion :: Flag Version, configExConstraints:: [UserConstraint], configPreferences :: [Dependency], configSolver :: Flag PreSolver, configAllowNewer :: Flag AllowNewer } defaultConfigExFlags :: ConfigExFlags defaultConfigExFlags = mempty { configSolver = Flag defaultSolver , configAllowNewer = Flag AllowNewerNone } configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags) configureExCommand = configureCommand { commandDefaultFlags = (mempty, defaultConfigExFlags), commandOptions = \showOrParseArgs -> liftOptions fst setFst (filter ((`notElem` ["constraint", "dependency", "exact-configuration"]) . optionName) $ configureOptions showOrParseArgs) ++ liftOptions snd setSnd (configureExOptions showOrParseArgs) } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) configureExOptions :: ShowOrParseArgs -> [OptionField ConfigExFlags] configureExOptions _showOrParseArgs = [ option [] ["cabal-lib-version"] ("Select which version of the Cabal lib to use to build packages " ++ "(useful for testing).") configCabalVersion (\v flags -> flags { configCabalVersion = v }) (reqArg "VERSION" (readP_to_E ("Cannot parse cabal lib version: "++) (fmap toFlag parse)) (map display . flagToList)) , option [] ["constraint"] "Specify constraints on a package (version, installed/source, flags)" configExConstraints (\v flags -> flags { configExConstraints = v }) (reqArg "CONSTRAINT" (fmap (\x -> [x]) (ReadE readUserConstraint)) (map display)) , option [] ["preference"] "Specify preferences (soft constraints) on the version of a package" configPreferences (\v flags -> flags { configPreferences = v }) (reqArg "CONSTRAINT" (readP_to_E (const "dependency expected") (fmap (\x -> [x]) parse)) (map display)) , optionSolver configSolver (\v flags -> flags { configSolver = v }) , option [] ["allow-newer"] ("Ignore upper bounds in all dependencies or " ++ allowNewerArgument) configAllowNewer (\v flags -> flags { configAllowNewer = v}) (optArg allowNewerArgument (fmap Flag allowNewerParser) (Flag AllowNewerAll) allowNewerPrinter) ] where allowNewerArgument = "DEPS" instance Monoid ConfigExFlags where mempty = ConfigExFlags { configCabalVersion = mempty, configExConstraints= mempty, configPreferences = mempty, configSolver = mempty, configAllowNewer = mempty } mappend a b = ConfigExFlags { configCabalVersion = combine configCabalVersion, configExConstraints= combine configExConstraints, configPreferences = combine configPreferences, configSolver = combine configSolver, configAllowNewer = combine configAllowNewer } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Build flags -- ------------------------------------------------------------ data SkipAddSourceDepsCheck = SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck deriving Eq data BuildExFlags = BuildExFlags { buildOnly :: Flag SkipAddSourceDepsCheck } buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags] buildExOptions _showOrParseArgs = option [] ["only"] "Don't reinstall add-source dependencies (sandbox-only)" buildOnly (\v flags -> flags { buildOnly = v }) (noArg (Flag SkipAddSourceDepsCheck)) : [] buildCommand :: CommandUI (BuildFlags, BuildExFlags) buildCommand = parent { commandDefaultFlags = (commandDefaultFlags parent, mempty), commandOptions = \showOrParseArgs -> liftOptions fst setFst (commandOptions parent showOrParseArgs) ++ liftOptions snd setSnd (buildExOptions showOrParseArgs) } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) parent = Cabal.buildCommand defaultProgramConfiguration instance Monoid BuildExFlags where mempty = BuildExFlags { buildOnly = mempty } mappend a b = BuildExFlags { buildOnly = combine buildOnly } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Repl command -- ------------------------------------------------------------ replCommand :: CommandUI (ReplFlags, BuildExFlags) replCommand = parent { commandDefaultFlags = (commandDefaultFlags parent, mempty), commandOptions = \showOrParseArgs -> liftOptions fst setFst (commandOptions parent showOrParseArgs) ++ liftOptions snd setSnd (buildExOptions showOrParseArgs) } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) parent = Cabal.replCommand defaultProgramConfiguration -- ------------------------------------------------------------ -- * Test command -- ------------------------------------------------------------ testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags) testCommand = parent { commandDefaultFlags = (commandDefaultFlags parent, Cabal.defaultBuildFlags, mempty), commandOptions = \showOrParseArgs -> liftOptions get1 set1 (commandOptions parent showOrParseArgs) ++ liftOptions get2 set2 (Cabal.buildOptions progConf showOrParseArgs) ++ liftOptions get3 set3 (buildExOptions showOrParseArgs) } where get1 (a,_,_) = a; set1 a (_,b,c) = (a,b,c) get2 (_,b,_) = b; set2 b (a,_,c) = (a,b,c) get3 (_,_,c) = c; set3 c (a,b,_) = (a,b,c) parent = Cabal.testCommand progConf = defaultProgramConfiguration -- ------------------------------------------------------------ -- * Bench command -- ------------------------------------------------------------ benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags) benchmarkCommand = parent { commandDefaultFlags = (commandDefaultFlags parent, Cabal.defaultBuildFlags, mempty), commandOptions = \showOrParseArgs -> liftOptions get1 set1 (commandOptions parent showOrParseArgs) ++ liftOptions get2 set2 (Cabal.buildOptions progConf showOrParseArgs) ++ liftOptions get3 set3 (buildExOptions showOrParseArgs) } where get1 (a,_,_) = a; set1 a (_,b,c) = (a,b,c) get2 (_,b,_) = b; set2 b (a,_,c) = (a,b,c) get3 (_,_,c) = c; set3 c (a,b,_) = (a,b,c) parent = Cabal.benchmarkCommand progConf = defaultProgramConfiguration -- ------------------------------------------------------------ -- * Fetch command -- ------------------------------------------------------------ data FetchFlags = FetchFlags { -- fetchOutput :: Flag FilePath, fetchDeps :: Flag Bool, fetchDryRun :: Flag Bool, fetchSolver :: Flag PreSolver, fetchMaxBackjumps :: Flag Int, fetchReorderGoals :: Flag Bool, fetchIndependentGoals :: Flag Bool, fetchShadowPkgs :: Flag Bool, fetchStrongFlags :: Flag Bool, fetchVerbosity :: Flag Verbosity } defaultFetchFlags :: FetchFlags defaultFetchFlags = FetchFlags { -- fetchOutput = mempty, fetchDeps = toFlag True, fetchDryRun = toFlag False, fetchSolver = Flag defaultSolver, fetchMaxBackjumps = Flag defaultMaxBackjumps, fetchReorderGoals = Flag False, fetchIndependentGoals = Flag False, fetchShadowPkgs = Flag False, fetchStrongFlags = Flag False, fetchVerbosity = toFlag normal } fetchCommand :: CommandUI FetchFlags fetchCommand = CommandUI { commandName = "fetch", commandSynopsis = "Downloads packages for later installation.", commandUsage = usageAlternatives "fetch" [ "[FLAGS] PACKAGES" ], commandDescription = Just $ \_ -> "Note that it currently is not possible to fetch the dependencies for a\n" ++ "package in the current directory.\n", commandNotes = Nothing, commandDefaultFlags = defaultFetchFlags, commandOptions = \ showOrParseArgs -> [ optionVerbosity fetchVerbosity (\v flags -> flags { fetchVerbosity = v }) -- , option "o" ["output"] -- "Put the package(s) somewhere specific rather than the usual cache." -- fetchOutput (\v flags -> flags { fetchOutput = v }) -- (reqArgFlag "PATH") , option [] ["dependencies", "deps"] "Resolve and fetch dependencies (default)" fetchDeps (\v flags -> flags { fetchDeps = v }) trueArg , option [] ["no-dependencies", "no-deps"] "Ignore dependencies" fetchDeps (\v flags -> flags { fetchDeps = v }) falseArg , option [] ["dry-run"] "Do not install anything, only print what would be installed." fetchDryRun (\v flags -> flags { fetchDryRun = v }) trueArg ] ++ optionSolver fetchSolver (\v flags -> flags { fetchSolver = v }) : optionSolverFlags showOrParseArgs fetchMaxBackjumps (\v flags -> flags { fetchMaxBackjumps = v }) fetchReorderGoals (\v flags -> flags { fetchReorderGoals = v }) fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v }) fetchShadowPkgs (\v flags -> flags { fetchShadowPkgs = v }) fetchStrongFlags (\v flags -> flags { fetchStrongFlags = v }) } -- ------------------------------------------------------------ -- * Freeze command -- ------------------------------------------------------------ data FreezeFlags = FreezeFlags { freezeDryRun :: Flag Bool, freezeTests :: Flag Bool, freezeBenchmarks :: Flag Bool, freezeSolver :: Flag PreSolver, freezeMaxBackjumps :: Flag Int, freezeReorderGoals :: Flag Bool, freezeIndependentGoals :: Flag Bool, freezeShadowPkgs :: Flag Bool, freezeStrongFlags :: Flag Bool, freezeVerbosity :: Flag Verbosity } defaultFreezeFlags :: FreezeFlags defaultFreezeFlags = FreezeFlags { freezeDryRun = toFlag False, freezeTests = toFlag False, freezeBenchmarks = toFlag False, freezeSolver = Flag defaultSolver, freezeMaxBackjumps = Flag defaultMaxBackjumps, freezeReorderGoals = Flag False, freezeIndependentGoals = Flag False, freezeShadowPkgs = Flag False, freezeStrongFlags = Flag False, freezeVerbosity = toFlag normal } freezeCommand :: CommandUI FreezeFlags freezeCommand = CommandUI { commandName = "freeze", commandSynopsis = "Freeze dependencies.", commandDescription = Just $ \_ -> wrapText $ "Calculates a valid set of dependencies and their exact versions. " ++ "If successful, saves the result to the file `cabal.config`.\n" ++ "\n" ++ "The package versions specified in `cabal.config` will be used for " ++ "any future installs.\n" ++ "\n" ++ "An existing `cabal.config` is ignored and overwritten.\n", commandNotes = Nothing, commandUsage = usageFlags "freeze", commandDefaultFlags = defaultFreezeFlags, commandOptions = \ showOrParseArgs -> [ optionVerbosity freezeVerbosity (\v flags -> flags { freezeVerbosity = v }) , option [] ["dry-run"] "Do not freeze anything, only print what would be frozen" freezeDryRun (\v flags -> flags { freezeDryRun = v }) trueArg , option [] ["tests"] "freezing of the dependencies of any tests suites in the package description file." freezeTests (\v flags -> flags { freezeTests = v }) (boolOpt [] []) , option [] ["benchmarks"] "freezing of the dependencies of any benchmarks suites in the package description file." freezeBenchmarks (\v flags -> flags { freezeBenchmarks = v }) (boolOpt [] []) ] ++ optionSolver freezeSolver (\v flags -> flags { freezeSolver = v }) : optionSolverFlags showOrParseArgs freezeMaxBackjumps (\v flags -> flags { freezeMaxBackjumps = v }) freezeReorderGoals (\v flags -> flags { freezeReorderGoals = v }) freezeIndependentGoals (\v flags -> flags { freezeIndependentGoals = v }) freezeShadowPkgs (\v flags -> flags { freezeShadowPkgs = v }) freezeStrongFlags (\v flags -> flags { freezeStrongFlags = v }) } -- ------------------------------------------------------------ -- * Other commands -- ------------------------------------------------------------ updateCommand :: CommandUI (Flag Verbosity) updateCommand = CommandUI { commandName = "update", commandSynopsis = "Updates list of known packages.", commandDescription = Just $ \_ -> "For all known remote repositories, download the package list.\n", commandNotes = Just $ \_ -> relevantConfigValuesText ["remote-repo" ,"remote-repo-cache" ,"local-repo"], commandUsage = usageFlags "update", commandDefaultFlags = toFlag normal, commandOptions = \_ -> [optionVerbosity id const] } upgradeCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags) upgradeCommand = configureCommand { commandName = "upgrade", commandSynopsis = "(command disabled, use install instead)", commandDescription = Nothing, commandUsage = usageFlagsOrPackages "upgrade", commandDefaultFlags = (mempty, mempty, mempty, mempty), commandOptions = commandOptions installCommand } {- cleanCommand :: CommandUI () cleanCommand = makeCommand name shortDesc longDesc emptyFlags options where name = "clean" shortDesc = "Removes downloaded files" longDesc = Nothing emptyFlags = () options _ = [] -} checkCommand :: CommandUI (Flag Verbosity) checkCommand = CommandUI { commandName = "check", commandSynopsis = "Check the package for common mistakes.", commandDescription = Just $ \_ -> wrapText $ "Expects a .cabal package file in the current directory.\n" ++ "\n" ++ "The checks correspond to the requirements to packages on Hackage. " ++ "If no errors and warnings are reported, Hackage will accept this " ++ "package.\n", commandNotes = Nothing, commandUsage = \pname -> "Usage: " ++ pname ++ " check\n", commandDefaultFlags = toFlag normal, commandOptions = \_ -> [] } formatCommand :: CommandUI (Flag Verbosity) formatCommand = CommandUI { commandName = "format", commandSynopsis = "Reformat the .cabal file using the standard style.", commandDescription = Nothing, commandNotes = Nothing, commandUsage = usageAlternatives "format" ["[FILE]"], commandDefaultFlags = toFlag normal, commandOptions = \_ -> [] } uninstallCommand :: CommandUI (Flag Verbosity) uninstallCommand = CommandUI { commandName = "uninstall", commandSynopsis = "Warn about 'uninstall' not being implemented.", commandDescription = Nothing, commandNotes = Nothing, commandUsage = usageAlternatives "uninstall" ["PACKAGES"], commandDefaultFlags = toFlag normal, commandOptions = \_ -> [] } runCommand :: CommandUI (BuildFlags, BuildExFlags) runCommand = CommandUI { commandName = "run", commandSynopsis = "Builds and runs an executable.", commandDescription = Just $ \_ -> wrapText $ "Builds and then runs the specified executable. If no executable is " ++ "specified, but the package contains just one executable, that one " ++ "is built and executed.\n", commandNotes = Nothing, commandUsage = usageAlternatives "run" ["[FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]"], commandDefaultFlags = mempty, commandOptions = \showOrParseArgs -> liftOptions fst setFst (commandOptions parent showOrParseArgs) ++ liftOptions snd setSnd (buildExOptions showOrParseArgs) } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) parent = Cabal.buildCommand defaultProgramConfiguration -- ------------------------------------------------------------ -- * Report flags -- ------------------------------------------------------------ data ReportFlags = ReportFlags { reportUsername :: Flag Username, reportPassword :: Flag Password, reportVerbosity :: Flag Verbosity } defaultReportFlags :: ReportFlags defaultReportFlags = ReportFlags { reportUsername = mempty, reportPassword = mempty, reportVerbosity = toFlag normal } reportCommand :: CommandUI ReportFlags reportCommand = CommandUI { commandName = "report", commandSynopsis = "Upload build reports to a remote server.", commandDescription = Nothing, commandNotes = Just $ \_ -> "You can store your Hackage login in the ~/.cabal/config file\n", commandUsage = usageAlternatives "report" ["[FLAGS]"], commandDefaultFlags = defaultReportFlags, commandOptions = \_ -> [optionVerbosity reportVerbosity (\v flags -> flags { reportVerbosity = v }) ,option ['u'] ["username"] "Hackage username." reportUsername (\v flags -> flags { reportUsername = v }) (reqArg' "USERNAME" (toFlag . Username) (flagToList . fmap unUsername)) ,option ['p'] ["password"] "Hackage password." reportPassword (\v flags -> flags { reportPassword = v }) (reqArg' "PASSWORD" (toFlag . Password) (flagToList . fmap unPassword)) ] } instance Monoid ReportFlags where mempty = ReportFlags { reportUsername = mempty, reportPassword = mempty, reportVerbosity = mempty } mappend a b = ReportFlags { reportUsername = combine reportUsername, reportPassword = combine reportPassword, reportVerbosity = combine reportVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Get flags -- ------------------------------------------------------------ data GetFlags = GetFlags { getDestDir :: Flag FilePath, getPristine :: Flag Bool, getSourceRepository :: Flag (Maybe RepoKind), getVerbosity :: Flag Verbosity } defaultGetFlags :: GetFlags defaultGetFlags = GetFlags { getDestDir = mempty, getPristine = mempty, getSourceRepository = mempty, getVerbosity = toFlag normal } getCommand :: CommandUI GetFlags getCommand = CommandUI { commandName = "get", commandSynopsis = "Download/Extract a package's source code (repository).", commandDescription = Just $ \_ -> wrapText $ "Creates a local copy of a package's source code. By default it gets " ++ "the source\ntarball and unpacks it in a local subdirectory. " ++ "Alternatively, with -s it will\nget the code from the source " ++ "repository specified by the package.\n", commandNotes = Nothing, commandUsage = usagePackages "get", commandDefaultFlags = defaultGetFlags, commandOptions = \_ -> [ optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v }) ,option "d" ["destdir"] "Where to place the package source, defaults to the current directory." getDestDir (\v flags -> flags { getDestDir = v }) (reqArgFlag "PATH") ,option "s" ["source-repository"] "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)." getSourceRepository (\v flags -> flags { getSourceRepository = v }) (optArg "[head|this|...]" (readP_to_E (const "invalid source-repository") (fmap (toFlag . Just) parse)) (Flag Nothing) (map (fmap show) . flagToList)) , option [] ["pristine"] ("Unpack the original pristine tarball, rather than updating the " ++ ".cabal file with the latest revision from the package archive.") getPristine (\v flags -> flags { getPristine = v }) trueArg ] } -- 'cabal unpack' is a deprecated alias for 'cabal get'. unpackCommand :: CommandUI GetFlags unpackCommand = getCommand { commandName = "unpack", commandUsage = usagePackages "unpack" } instance Monoid GetFlags where mempty = GetFlags { getDestDir = mempty, getPristine = mempty, getSourceRepository = mempty, getVerbosity = mempty } mappend a b = GetFlags { getDestDir = combine getDestDir, getPristine = combine getPristine, getSourceRepository = combine getSourceRepository, getVerbosity = combine getVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * List flags -- ------------------------------------------------------------ data ListFlags = ListFlags { listInstalled :: Flag Bool, listSimpleOutput :: Flag Bool, listVerbosity :: Flag Verbosity, listPackageDBs :: [Maybe PackageDB] } defaultListFlags :: ListFlags defaultListFlags = ListFlags { listInstalled = Flag False, listSimpleOutput = Flag False, listVerbosity = toFlag normal, listPackageDBs = [] } listCommand :: CommandUI ListFlags listCommand = CommandUI { commandName = "list", commandSynopsis = "List packages matching a search string.", commandDescription = Just $ \_ -> wrapText $ "List all packages, or all packages matching one of the search" ++ " strings.\n" ++ "\n" ++ "If there is a sandbox in the current directory and " ++ "config:ignore-sandbox is False, use the sandbox package database. " ++ "Otherwise, use the package database specified with --package-db. " ++ "If not specified, use the user package database.\n", commandNotes = Nothing, commandUsage = usageAlternatives "list" [ "[FLAGS]" , "[FLAGS] STRINGS"], commandDefaultFlags = defaultListFlags, commandOptions = \_ -> [ optionVerbosity listVerbosity (\v flags -> flags { listVerbosity = v }) , option [] ["installed"] "Only print installed packages" listInstalled (\v flags -> flags { listInstalled = v }) trueArg , option [] ["simple-output"] "Print in a easy-to-parse format" listSimpleOutput (\v flags -> flags { listSimpleOutput = v }) trueArg , option "" ["package-db"] "Use a given package database. May be a specific file, 'global', 'user' or 'clear'." listPackageDBs (\v flags -> flags { listPackageDBs = v }) (reqArg' "DB" readPackageDbList showPackageDbList) ] } instance Monoid ListFlags where mempty = ListFlags { listInstalled = mempty, listSimpleOutput = mempty, listVerbosity = mempty, listPackageDBs = mempty } mappend a b = ListFlags { listInstalled = combine listInstalled, listSimpleOutput = combine listSimpleOutput, listVerbosity = combine listVerbosity, listPackageDBs = combine listPackageDBs } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Info flags -- ------------------------------------------------------------ data InfoFlags = InfoFlags { infoVerbosity :: Flag Verbosity, infoPackageDBs :: [Maybe PackageDB] } defaultInfoFlags :: InfoFlags defaultInfoFlags = InfoFlags { infoVerbosity = toFlag normal, infoPackageDBs = [] } infoCommand :: CommandUI InfoFlags infoCommand = CommandUI { commandName = "info", commandSynopsis = "Display detailed information about a particular package.", commandDescription = Just $ \_ -> wrapText $ "If there is a sandbox in the current directory and " ++ "config:ignore-sandbox is False, use the sandbox package database. " ++ "Otherwise, use the package database specified with --package-db. " ++ "If not specified, use the user package database.\n", commandNotes = Nothing, commandUsage = usageAlternatives "info" ["[FLAGS] PACKAGES"], commandDefaultFlags = defaultInfoFlags, commandOptions = \_ -> [ optionVerbosity infoVerbosity (\v flags -> flags { infoVerbosity = v }) , option "" ["package-db"] "Use a given package database. May be a specific file, 'global', 'user' or 'clear'." infoPackageDBs (\v flags -> flags { infoPackageDBs = v }) (reqArg' "DB" readPackageDbList showPackageDbList) ] } instance Monoid InfoFlags where mempty = InfoFlags { infoVerbosity = mempty, infoPackageDBs = mempty } mappend a b = InfoFlags { infoVerbosity = combine infoVerbosity, infoPackageDBs = combine infoPackageDBs } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Install flags -- ------------------------------------------------------------ -- | Install takes the same flags as configure along with a few extras. -- data InstallFlags = InstallFlags { installDocumentation :: Flag Bool, installHaddockIndex :: Flag PathTemplate, installDryRun :: Flag Bool, installMaxBackjumps :: Flag Int, installReorderGoals :: Flag Bool, installIndependentGoals :: Flag Bool, installShadowPkgs :: Flag Bool, installStrongFlags :: Flag Bool, installReinstall :: Flag Bool, installAvoidReinstalls :: Flag Bool, installOverrideReinstall :: Flag Bool, installUpgradeDeps :: Flag Bool, installOnly :: Flag Bool, installOnlyDeps :: Flag Bool, installRootCmd :: Flag String, installSummaryFile :: NubList PathTemplate, installLogFile :: Flag PathTemplate, installBuildReports :: Flag ReportLevel, installReportPlanningFailure :: Flag Bool, installSymlinkBinDir :: Flag FilePath, installOneShot :: Flag Bool, installNumJobs :: Flag (Maybe Int), installRunTests :: Flag Bool } defaultInstallFlags :: InstallFlags defaultInstallFlags = InstallFlags { installDocumentation = Flag False, installHaddockIndex = Flag docIndexFile, installDryRun = Flag False, installMaxBackjumps = Flag defaultMaxBackjumps, installReorderGoals = Flag False, installIndependentGoals= Flag False, installShadowPkgs = Flag False, installStrongFlags = Flag False, installReinstall = Flag False, installAvoidReinstalls = Flag False, installOverrideReinstall = Flag False, installUpgradeDeps = Flag False, installOnly = Flag False, installOnlyDeps = Flag False, installRootCmd = mempty, installSummaryFile = mempty, installLogFile = mempty, installBuildReports = Flag NoReports, installReportPlanningFailure = Flag False, installSymlinkBinDir = mempty, installOneShot = Flag False, installNumJobs = mempty, installRunTests = mempty } where docIndexFile = toPathTemplate ("$datadir" </> "doc" </> "$arch-$os-$compiler" </> "index.html") allowNewerParser :: ReadE AllowNewer allowNewerParser = ReadE $ \s -> case s of "" -> Right AllowNewerNone "False" -> Right AllowNewerNone "True" -> Right AllowNewerAll _ -> case readPToMaybe pkgsParser s of Just pkgs -> Right . AllowNewerSome $ pkgs Nothing -> Left ("Cannot parse the list of packages: " ++ s) where pkgsParser = Parse.sepBy1 parse (Parse.char ',') allowNewerPrinter :: Flag AllowNewer -> [Maybe String] allowNewerPrinter (Flag AllowNewerNone) = [Just "False"] allowNewerPrinter (Flag AllowNewerAll) = [Just "True"] allowNewerPrinter (Flag (AllowNewerSome pkgs)) = [Just . intercalate "," . map display $ pkgs] allowNewerPrinter NoFlag = [] defaultMaxBackjumps :: Int defaultMaxBackjumps = 2000 defaultSolver :: PreSolver defaultSolver = Choose allSolvers :: String allSolvers = intercalate ", " (map display ([minBound .. maxBound] :: [PreSolver])) installCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags) installCommand = CommandUI { commandName = "install", commandSynopsis = "Install packages.", commandUsage = usageAlternatives "install" [ "[FLAGS]" , "[FLAGS] PACKAGES" ], commandDescription = Just $ \_ -> wrapText $ "Installs one or more packages. By default, the installed package" ++ " will be registered in the user's package database or, if a sandbox" ++ " is present in the current directory, inside the sandbox.\n" ++ "\n" ++ "If PACKAGES are specified, downloads and installs those packages." ++ " Otherwise, install the package in the current directory (and/or its" ++ " dependencies) (there must be exactly one .cabal file in the current" ++ " directory).\n" ++ "\n" ++ "When using a sandbox, the flags for `install` only affect the" ++ " current command and have no effect on future commands. (To achieve" ++ " that, `configure` must be used.)\n" ++ " In contrast, without a sandbox, the flags to `install` are saved and" ++ " affect future commands such as `build` and `repl`. See the help for" ++ " `configure` for a list of commands being affected.\n", commandNotes = Just $ \pname -> ( case commandNotes configureCommand of Just desc -> desc pname ++ "\n" Nothing -> "" ) ++ "Examples:\n" ++ " " ++ pname ++ " install " ++ " Package in the current directory\n" ++ " " ++ pname ++ " install foo " ++ " Package from the hackage server\n" ++ " " ++ pname ++ " install foo-1.0 " ++ " Specific version of a package\n" ++ " " ++ pname ++ " install 'foo < 2' " ++ " Constrained package version\n", commandDefaultFlags = (mempty, mempty, mempty, mempty), commandOptions = \showOrParseArgs -> liftOptions get1 set1 (filter ((`notElem` ["constraint", "dependency" , "exact-configuration"]) . optionName) $ configureOptions showOrParseArgs) ++ liftOptions get2 set2 (configureExOptions showOrParseArgs) ++ liftOptions get3 set3 (installOptions showOrParseArgs) ++ liftOptions get4 set4 (haddockOptions showOrParseArgs) } where get1 (a,_,_,_) = a; set1 a (_,b,c,d) = (a,b,c,d) get2 (_,b,_,_) = b; set2 b (a,_,c,d) = (a,b,c,d) get3 (_,_,c,_) = c; set3 c (a,b,_,d) = (a,b,c,d) get4 (_,_,_,d) = d; set4 d (a,b,c,_) = (a,b,c,d) haddockOptions :: ShowOrParseArgs -> [OptionField HaddockFlags] haddockOptions showOrParseArgs = [ opt { optionName = "haddock-" ++ name, optionDescr = [ fmapOptFlags (\(_, lflags) -> ([], map ("haddock-" ++) lflags)) descr | descr <- optionDescr opt] } | opt <- commandOptions Cabal.haddockCommand showOrParseArgs , let name = optionName opt , name `elem` ["hoogle", "html", "html-location" ,"executables", "tests", "benchmarks", "all", "internal", "css" ,"hyperlink-source", "hscolour-css" ,"contents-location"] ] where fmapOptFlags :: (OptFlags -> OptFlags) -> OptDescr a -> OptDescr a fmapOptFlags modify (ReqArg d f p r w) = ReqArg d (modify f) p r w fmapOptFlags modify (OptArg d f p r i w) = OptArg d (modify f) p r i w fmapOptFlags modify (ChoiceOpt xs) = ChoiceOpt [(d, modify f, i, w) | (d, f, i, w) <- xs] fmapOptFlags modify (BoolOpt d f1 f2 r w) = BoolOpt d (modify f1) (modify f2) r w installOptions :: ShowOrParseArgs -> [OptionField InstallFlags] installOptions showOrParseArgs = [ option "" ["documentation"] "building of documentation" installDocumentation (\v flags -> flags { installDocumentation = v }) (boolOpt [] []) , option [] ["doc-index-file"] "A central index of haddock API documentation (template cannot use $pkgid)" installHaddockIndex (\v flags -> flags { installHaddockIndex = v }) (reqArg' "TEMPLATE" (toFlag.toPathTemplate) (flagToList . fmap fromPathTemplate)) , option [] ["dry-run"] "Do not install anything, only print what would be installed." installDryRun (\v flags -> flags { installDryRun = v }) trueArg ] ++ optionSolverFlags showOrParseArgs installMaxBackjumps (\v flags -> flags { installMaxBackjumps = v }) installReorderGoals (\v flags -> flags { installReorderGoals = v }) installIndependentGoals (\v flags -> flags { installIndependentGoals = v }) installShadowPkgs (\v flags -> flags { installShadowPkgs = v }) installStrongFlags (\v flags -> flags { installStrongFlags = v }) ++ [ option [] ["reinstall"] "Install even if it means installing the same version again." installReinstall (\v flags -> flags { installReinstall = v }) (yesNoOpt showOrParseArgs) , option [] ["avoid-reinstalls"] "Do not select versions that would destructively overwrite installed packages." installAvoidReinstalls (\v flags -> flags { installAvoidReinstalls = v }) (yesNoOpt showOrParseArgs) , option [] ["force-reinstalls"] "Reinstall packages even if they will most likely break other installed packages." installOverrideReinstall (\v flags -> flags { installOverrideReinstall = v }) (yesNoOpt showOrParseArgs) , option [] ["upgrade-dependencies"] "Pick the latest version for all dependencies, rather than trying to pick an installed version." installUpgradeDeps (\v flags -> flags { installUpgradeDeps = v }) (yesNoOpt showOrParseArgs) , option [] ["only-dependencies"] "Install only the dependencies necessary to build the given packages" installOnlyDeps (\v flags -> flags { installOnlyDeps = v }) (yesNoOpt showOrParseArgs) , option [] ["dependencies-only"] "A synonym for --only-dependencies" installOnlyDeps (\v flags -> flags { installOnlyDeps = v }) (yesNoOpt showOrParseArgs) , option [] ["root-cmd"] "Command used to gain root privileges, when installing with --global." installRootCmd (\v flags -> flags { installRootCmd = v }) (reqArg' "COMMAND" toFlag flagToList) , option [] ["symlink-bindir"] "Add symlinks to installed executables into this directory." installSymlinkBinDir (\v flags -> flags { installSymlinkBinDir = v }) (reqArgFlag "DIR") , option [] ["build-summary"] "Save build summaries to file (name template can use $pkgid, $compiler, $os, $arch)" installSummaryFile (\v flags -> flags { installSummaryFile = v }) (reqArg' "TEMPLATE" (\x -> toNubList [toPathTemplate x]) (map fromPathTemplate . fromNubList)) , option [] ["build-log"] "Log all builds to file (name template can use $pkgid, $compiler, $os, $arch)" installLogFile (\v flags -> flags { installLogFile = v }) (reqArg' "TEMPLATE" (toFlag.toPathTemplate) (flagToList . fmap fromPathTemplate)) , option [] ["remote-build-reporting"] "Generate build reports to send to a remote server (none, anonymous or detailed)." installBuildReports (\v flags -> flags { installBuildReports = v }) (reqArg "LEVEL" (readP_to_E (const $ "report level must be 'none', " ++ "'anonymous' or 'detailed'") (toFlag `fmap` parse)) (flagToList . fmap display)) , option [] ["report-planning-failure"] "Generate build reports when the dependency solver fails. This is used by the Hackage build bot." installReportPlanningFailure (\v flags -> flags { installReportPlanningFailure = v }) trueArg , option [] ["one-shot"] "Do not record the packages in the world file." installOneShot (\v flags -> flags { installOneShot = v }) (yesNoOpt showOrParseArgs) , option [] ["run-tests"] "Run package test suites during installation." installRunTests (\v flags -> flags { installRunTests = v }) trueArg , optionNumJobs installNumJobs (\v flags -> flags { installNumJobs = v }) ] ++ case showOrParseArgs of -- TODO: remove when "cabal install" -- avoids ParseArgs -> [ option [] ["only"] "Only installs the package in the current directory." installOnly (\v flags -> flags { installOnly = v }) trueArg ] _ -> [] instance Monoid InstallFlags where mempty = InstallFlags { installDocumentation = mempty, installHaddockIndex = mempty, installDryRun = mempty, installReinstall = mempty, installAvoidReinstalls = mempty, installOverrideReinstall = mempty, installMaxBackjumps = mempty, installUpgradeDeps = mempty, installReorderGoals = mempty, installIndependentGoals= mempty, installShadowPkgs = mempty, installStrongFlags = mempty, installOnly = mempty, installOnlyDeps = mempty, installRootCmd = mempty, installSummaryFile = mempty, installLogFile = mempty, installBuildReports = mempty, installReportPlanningFailure = mempty, installSymlinkBinDir = mempty, installOneShot = mempty, installNumJobs = mempty, installRunTests = mempty } mappend a b = InstallFlags { installDocumentation = combine installDocumentation, installHaddockIndex = combine installHaddockIndex, installDryRun = combine installDryRun, installReinstall = combine installReinstall, installAvoidReinstalls = combine installAvoidReinstalls, installOverrideReinstall = combine installOverrideReinstall, installMaxBackjumps = combine installMaxBackjumps, installUpgradeDeps = combine installUpgradeDeps, installReorderGoals = combine installReorderGoals, installIndependentGoals= combine installIndependentGoals, installShadowPkgs = combine installShadowPkgs, installStrongFlags = combine installStrongFlags, installOnly = combine installOnly, installOnlyDeps = combine installOnlyDeps, installRootCmd = combine installRootCmd, installSummaryFile = combine installSummaryFile, installLogFile = combine installLogFile, installBuildReports = combine installBuildReports, installReportPlanningFailure = combine installReportPlanningFailure, installSymlinkBinDir = combine installSymlinkBinDir, installOneShot = combine installOneShot, installNumJobs = combine installNumJobs, installRunTests = combine installRunTests } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Upload flags -- ------------------------------------------------------------ data UploadFlags = UploadFlags { uploadCheck :: Flag Bool, uploadUsername :: Flag Username, uploadPassword :: Flag Password, uploadPasswordCmd :: Flag [String], uploadVerbosity :: Flag Verbosity } defaultUploadFlags :: UploadFlags defaultUploadFlags = UploadFlags { uploadCheck = toFlag False, uploadUsername = mempty, uploadPassword = mempty, uploadPasswordCmd = mempty, uploadVerbosity = toFlag normal } uploadCommand :: CommandUI UploadFlags uploadCommand = CommandUI { commandName = "upload", commandSynopsis = "Uploads source packages to Hackage.", commandDescription = Nothing, commandNotes = Just $ \_ -> "You can store your Hackage login in the ~/.cabal/config file\n" ++ relevantConfigValuesText ["username", "password"], commandUsage = \pname -> "Usage: " ++ pname ++ " upload [FLAGS] TARFILES\n", commandDefaultFlags = defaultUploadFlags, commandOptions = \_ -> [optionVerbosity uploadVerbosity (\v flags -> flags { uploadVerbosity = v }) ,option ['c'] ["check"] "Do not upload, just do QA checks." uploadCheck (\v flags -> flags { uploadCheck = v }) trueArg ,option ['u'] ["username"] "Hackage username." uploadUsername (\v flags -> flags { uploadUsername = v }) (reqArg' "USERNAME" (toFlag . Username) (flagToList . fmap unUsername)) ,option ['p'] ["password"] "Hackage password." uploadPassword (\v flags -> flags { uploadPassword = v }) (reqArg' "PASSWORD" (toFlag . Password) (flagToList . fmap unPassword)) ,option ['P'] ["password-command"] "Command to get Hackage password." uploadPasswordCmd (\v flags -> flags { uploadPasswordCmd = v }) (reqArg' "PASSWORD" (Flag . words) (fromMaybe [] . flagToMaybe)) ] } instance Monoid UploadFlags where mempty = UploadFlags { uploadCheck = mempty, uploadUsername = mempty, uploadPassword = mempty, uploadPasswordCmd = mempty, uploadVerbosity = mempty } mappend a b = UploadFlags { uploadCheck = combine uploadCheck, uploadUsername = combine uploadUsername, uploadPassword = combine uploadPassword, uploadPasswordCmd = combine uploadPasswordCmd, uploadVerbosity = combine uploadVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Init flags -- ------------------------------------------------------------ emptyInitFlags :: IT.InitFlags emptyInitFlags = mempty defaultInitFlags :: IT.InitFlags defaultInitFlags = emptyInitFlags { IT.initVerbosity = toFlag normal } initCommand :: CommandUI IT.InitFlags initCommand = CommandUI { commandName = "init", commandSynopsis = "Create a new .cabal package file (interactively).", commandDescription = Just $ \_ -> wrapText $ "Cabalise a project by creating a .cabal, Setup.hs, and " ++ "optionally a LICENSE file.\n" ++ "\n" ++ "Calling init with no arguments (recommended) uses an " ++ "interactive mode, which will try to guess as much as " ++ "possible and prompt you for the rest. Command-line " ++ "arguments are provided for scripting purposes. " ++ "If you don't want interactive mode, be sure to pass " ++ "the -n flag.\n", commandNotes = Nothing, commandUsage = \pname -> "Usage: " ++ pname ++ " init [FLAGS]\n", commandDefaultFlags = defaultInitFlags, commandOptions = \_ -> [ option ['n'] ["non-interactive"] "Non-interactive mode." IT.nonInteractive (\v flags -> flags { IT.nonInteractive = v }) trueArg , option ['q'] ["quiet"] "Do not generate log messages to stdout." IT.quiet (\v flags -> flags { IT.quiet = v }) trueArg , option [] ["no-comments"] "Do not generate explanatory comments in the .cabal file." IT.noComments (\v flags -> flags { IT.noComments = v }) trueArg , option ['m'] ["minimal"] "Generate a minimal .cabal file, that is, do not include extra empty fields. Also implies --no-comments." IT.minimal (\v flags -> flags { IT.minimal = v }) trueArg , option [] ["overwrite"] "Overwrite any existing .cabal, LICENSE, or Setup.hs files without warning." IT.overwrite (\v flags -> flags { IT.overwrite = v }) trueArg , option [] ["package-dir"] "Root directory of the package (default = current directory)." IT.packageDir (\v flags -> flags { IT.packageDir = v }) (reqArgFlag "DIRECTORY") , option ['p'] ["package-name"] "Name of the Cabal package to create." IT.packageName (\v flags -> flags { IT.packageName = v }) (reqArg "PACKAGE" (readP_to_E ("Cannot parse package name: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option [] ["version"] "Initial version of the package." IT.version (\v flags -> flags { IT.version = v }) (reqArg "VERSION" (readP_to_E ("Cannot parse package version: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option [] ["cabal-version"] "Required version of the Cabal library." IT.cabalVersion (\v flags -> flags { IT.cabalVersion = v }) (reqArg "VERSION_RANGE" (readP_to_E ("Cannot parse Cabal version range: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option ['l'] ["license"] "Project license." IT.license (\v flags -> flags { IT.license = v }) (reqArg "LICENSE" (readP_to_E ("Cannot parse license: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option ['a'] ["author"] "Name of the project's author." IT.author (\v flags -> flags { IT.author = v }) (reqArgFlag "NAME") , option ['e'] ["email"] "Email address of the maintainer." IT.email (\v flags -> flags { IT.email = v }) (reqArgFlag "EMAIL") , option ['u'] ["homepage"] "Project homepage and/or repository." IT.homepage (\v flags -> flags { IT.homepage = v }) (reqArgFlag "URL") , option ['s'] ["synopsis"] "Short project synopsis." IT.synopsis (\v flags -> flags { IT.synopsis = v }) (reqArgFlag "TEXT") , option ['c'] ["category"] "Project category." IT.category (\v flags -> flags { IT.category = v }) (reqArg' "CATEGORY" (\s -> toFlag $ maybe (Left s) Right (readMaybe s)) (flagToList . fmap (either id show))) , option ['x'] ["extra-source-file"] "Extra source file to be distributed with tarball." IT.extraSrc (\v flags -> flags { IT.extraSrc = v }) (reqArg' "FILE" (Just . (:[])) (fromMaybe [])) , option [] ["is-library"] "Build a library." IT.packageType (\v flags -> flags { IT.packageType = v }) (noArg (Flag IT.Library)) , option [] ["is-executable"] "Build an executable." IT.packageType (\v flags -> flags { IT.packageType = v }) (noArg (Flag IT.Executable)) , option [] ["main-is"] "Specify the main module." IT.mainIs (\v flags -> flags { IT.mainIs = v }) (reqArgFlag "FILE") , option [] ["language"] "Specify the default language." IT.language (\v flags -> flags { IT.language = v }) (reqArg "LANGUAGE" (readP_to_E ("Cannot parse language: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option ['o'] ["expose-module"] "Export a module from the package." IT.exposedModules (\v flags -> flags { IT.exposedModules = v }) (reqArg "MODULE" (readP_to_E ("Cannot parse module name: "++) ((Just . (:[])) `fmap` parse)) (maybe [] (fmap display))) , option [] ["extension"] "Use a LANGUAGE extension (in the other-extensions field)." IT.otherExts (\v flags -> flags { IT.otherExts = v }) (reqArg "EXTENSION" (readP_to_E ("Cannot parse extension: "++) ((Just . (:[])) `fmap` parse)) (maybe [] (fmap display))) , option ['d'] ["dependency"] "Package dependency." IT.dependencies (\v flags -> flags { IT.dependencies = v }) (reqArg "PACKAGE" (readP_to_E ("Cannot parse dependency: "++) ((Just . (:[])) `fmap` parse)) (maybe [] (fmap display))) , option [] ["source-dir"] "Directory containing package source." IT.sourceDirs (\v flags -> flags { IT.sourceDirs = v }) (reqArg' "DIR" (Just . (:[])) (fromMaybe [])) , option [] ["build-tool"] "Required external build tool." IT.buildTools (\v flags -> flags { IT.buildTools = v }) (reqArg' "TOOL" (Just . (:[])) (fromMaybe [])) , optionVerbosity IT.initVerbosity (\v flags -> flags { IT.initVerbosity = v }) ] } where readMaybe s = case reads s of [(x,"")] -> Just x _ -> Nothing -- ------------------------------------------------------------ -- * SDist flags -- ------------------------------------------------------------ -- | Extra flags to @sdist@ beyond runghc Setup sdist -- data SDistExFlags = SDistExFlags { sDistFormat :: Flag ArchiveFormat } deriving Show data ArchiveFormat = TargzFormat | ZipFormat -- | ... deriving (Show, Eq) defaultSDistExFlags :: SDistExFlags defaultSDistExFlags = SDistExFlags { sDistFormat = Flag TargzFormat } sdistCommand :: CommandUI (SDistFlags, SDistExFlags) sdistCommand = Cabal.sdistCommand { commandDefaultFlags = (commandDefaultFlags Cabal.sdistCommand, defaultSDistExFlags), commandOptions = \showOrParseArgs -> liftOptions fst setFst (commandOptions Cabal.sdistCommand showOrParseArgs) ++ liftOptions snd setSnd sdistExOptions } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) sdistExOptions = [option [] ["archive-format"] "archive-format" sDistFormat (\v flags -> flags { sDistFormat = v }) (choiceOpt [ (Flag TargzFormat, ([], ["targz"]), "Produce a '.tar.gz' format archive (default and required for uploading to hackage)") , (Flag ZipFormat, ([], ["zip"]), "Produce a '.zip' format archive") ]) ] instance Monoid SDistExFlags where mempty = SDistExFlags { sDistFormat = mempty } mappend a b = SDistExFlags { sDistFormat = combine sDistFormat } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Win32SelfUpgrade flags -- ------------------------------------------------------------ data Win32SelfUpgradeFlags = Win32SelfUpgradeFlags { win32SelfUpgradeVerbosity :: Flag Verbosity } defaultWin32SelfUpgradeFlags :: Win32SelfUpgradeFlags defaultWin32SelfUpgradeFlags = Win32SelfUpgradeFlags { win32SelfUpgradeVerbosity = toFlag normal } win32SelfUpgradeCommand :: CommandUI Win32SelfUpgradeFlags win32SelfUpgradeCommand = CommandUI { commandName = "win32selfupgrade", commandSynopsis = "Self-upgrade the executable on Windows", commandDescription = Nothing, commandNotes = Nothing, commandUsage = \pname -> "Usage: " ++ pname ++ " win32selfupgrade PID PATH\n", commandDefaultFlags = defaultWin32SelfUpgradeFlags, commandOptions = \_ -> [optionVerbosity win32SelfUpgradeVerbosity (\v flags -> flags { win32SelfUpgradeVerbosity = v}) ] } instance Monoid Win32SelfUpgradeFlags where mempty = Win32SelfUpgradeFlags { win32SelfUpgradeVerbosity = mempty } mappend a b = Win32SelfUpgradeFlags { win32SelfUpgradeVerbosity = combine win32SelfUpgradeVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Sandbox-related flags -- ------------------------------------------------------------ data SandboxFlags = SandboxFlags { sandboxVerbosity :: Flag Verbosity, sandboxSnapshot :: Flag Bool, -- FIXME: this should be an 'add-source'-only -- flag. sandboxLocation :: Flag FilePath } defaultSandboxLocation :: FilePath defaultSandboxLocation = ".cabal-sandbox" defaultSandboxFlags :: SandboxFlags defaultSandboxFlags = SandboxFlags { sandboxVerbosity = toFlag normal, sandboxSnapshot = toFlag False, sandboxLocation = toFlag defaultSandboxLocation } sandboxCommand :: CommandUI SandboxFlags sandboxCommand = CommandUI { commandName = "sandbox", commandSynopsis = "Create/modify/delete a sandbox.", commandDescription = Just $ \pname -> concat [ paragraph $ "Sandboxes are isolated package databases that can be used" ++ " to prevent dependency conflicts that arise when many different" ++ " packages are installed in the same database (i.e. the user's" ++ " database in the home directory)." , paragraph $ "A sandbox in the current directory (created by" ++ " `sandbox init`) will be used instead of the user's database for" ++ " commands such as `install` and `build`. Note that (a directly" ++ " invoked) GHC will not automatically be aware of sandboxes;" ++ " only if called via appropriate " ++ pname ++ " commands, e.g. `repl`, `build`, `exec`." , paragraph $ "Currently, " ++ pname ++ " will not search for a sandbox" ++ " in folders above the current one, so cabal will not see the sandbox" ++ " if you are in a subfolder of a sandboxes." , paragraph "Subcommands:" , headLine "init:" , indentParagraph $ "Initialize a sandbox in the current directory." ++ " An existing package database will not be modified, but settings" ++ " (such as the location of the database) can be modified this way." , headLine "delete:" , indentParagraph $ "Remove the sandbox; deleting all the packages" ++ " installed inside." , headLine "add-source:" , indentParagraph $ "Make one or more local package available in the" ++ " sandbox. PATHS may be relative or absolute." ++ " Typical usecase is when you need" ++ " to make a (temporary) modification to a dependency: You download" ++ " the package into a different directory, make the modification," ++ " and add that directory to the sandbox with `add-source`." , indentParagraph $ "Unless given `--snapshot`, any add-source'd" ++ " dependency that was modified since the last build will be" ++ " re-installed automatically." , headLine "delete-source:" , indentParagraph $ "Remove an add-source dependency; however, this will" ++ " not delete the package(s) that have been installed in the sandbox" ++ " from this dependency. You can either unregister the package(s) via" ++ " `" ++ pname ++ " sandbox hc-pkg unregister` or re-create the" ++ " sandbox (`sandbox delete; sandbox init`)." , headLine "list-sources:" , indentParagraph $ "List the directories of local packages made" ++ " available via `" ++ pname ++ " add-source`." , headLine "hc-pkg:" , indentParagraph $ "Similar to `ghc-pkg`, but for the sandbox package" ++ " database. Can be used to list specific/all packages that are" ++ " installed in the sandbox. For subcommands, see the help for" ++ " ghc-pkg. Affected by the compiler version specified by `configure`." ], commandNotes = Just $ \_ -> relevantConfigValuesText ["require-sandbox" ,"ignore-sandbox"], commandUsage = usageAlternatives "sandbox" [ "init [FLAGS]" , "delete [FLAGS]" , "add-source [FLAGS] PATHS" , "delete-source [FLAGS] PATHS" , "list-sources [FLAGS]" , "hc-pkg [FLAGS] [--] COMMAND [--] [ARGS]" ], commandDefaultFlags = defaultSandboxFlags, commandOptions = \_ -> [ optionVerbosity sandboxVerbosity (\v flags -> flags { sandboxVerbosity = v }) , option [] ["snapshot"] "Take a snapshot instead of creating a link (only applies to 'add-source')" sandboxSnapshot (\v flags -> flags { sandboxSnapshot = v }) trueArg , option [] ["sandbox"] "Sandbox location (default: './.cabal-sandbox')." sandboxLocation (\v flags -> flags { sandboxLocation = v }) (reqArgFlag "DIR") ] } instance Monoid SandboxFlags where mempty = SandboxFlags { sandboxVerbosity = mempty, sandboxSnapshot = mempty, sandboxLocation = mempty } mappend a b = SandboxFlags { sandboxVerbosity = combine sandboxVerbosity, sandboxSnapshot = combine sandboxSnapshot, sandboxLocation = combine sandboxLocation } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Exec Flags -- ------------------------------------------------------------ data ExecFlags = ExecFlags { execVerbosity :: Flag Verbosity } defaultExecFlags :: ExecFlags defaultExecFlags = ExecFlags { execVerbosity = toFlag normal } execCommand :: CommandUI ExecFlags execCommand = CommandUI { commandName = "exec", commandSynopsis = "Give a command access to the sandbox package repository.", commandDescription = Just $ \pname -> wrapText $ -- TODO: this is too GHC-focused for my liking.. "A directly invoked GHC will not automatically be aware of any" ++ " sandboxes: the GHC_PACKAGE_PATH environment variable controls what" ++ " GHC uses. `" ++ pname ++ " exec` can be used to modify this variable:" ++ " COMMAND will be executed in a modified environment and thereby uses" ++ " the sandbox package database.\n" ++ "\n" ++ "If there is no sandbox, behaves as identity (executing COMMAND).\n" ++ "\n" ++ "Note that other " ++ pname ++ " commands change the environment" ++ " variable appropriately already, so there is no need to wrap those" ++ " in `" ++ pname ++ " exec`. But with `" ++ pname ++ " exec`, the user" ++ " has more control and can, for example, execute custom scripts which" ++ " indirectly execute GHC.\n" ++ "\n" ++ "See `" ++ pname ++ " sandbox`.", commandNotes = Just $ \pname -> "Examples:\n" ++ " Install the executable package pandoc into a sandbox and run it:\n" ++ " " ++ pname ++ " sandbox init\n" ++ " " ++ pname ++ " install pandoc\n" ++ " " ++ pname ++ " exec pandoc foo.md\n\n" ++ " Install the executable package hlint into the user package database\n" ++ " and run it:\n" ++ " " ++ pname ++ " install --user hlint\n" ++ " " ++ pname ++ " exec hlint Foo.hs\n\n" ++ " Execute runghc on Foo.hs with runghc configured to use the\n" ++ " sandbox package database (if a sandbox is being used):\n" ++ " " ++ pname ++ " exec runghc Foo.hs\n", commandUsage = \pname -> "Usage: " ++ pname ++ " exec [FLAGS] [--] COMMAND [--] [ARGS]\n", commandDefaultFlags = defaultExecFlags, commandOptions = \_ -> [ optionVerbosity execVerbosity (\v flags -> flags { execVerbosity = v }) ] } instance Monoid ExecFlags where mempty = ExecFlags { execVerbosity = mempty } mappend a b = ExecFlags { execVerbosity = combine execVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * UserConfig flags -- ------------------------------------------------------------ data UserConfigFlags = UserConfigFlags { userConfigVerbosity :: Flag Verbosity } instance Monoid UserConfigFlags where mempty = UserConfigFlags { userConfigVerbosity = toFlag normal } mappend a b = UserConfigFlags { userConfigVerbosity = combine userConfigVerbosity } where combine field = field a `mappend` field b userConfigCommand :: CommandUI UserConfigFlags userConfigCommand = CommandUI { commandName = "user-config", commandSynopsis = "Display and update the user's global cabal configuration.", commandDescription = Just $ \_ -> wrapText $ "When upgrading cabal, the set of configuration keys and their default" ++ " values may change. This command provides means to merge the existing" ++ " config in ~/.cabal/config" ++ " (i.e. all bindings that are actually defined and not commented out)" ++ " and the default config of the new version.\n" ++ "\n" ++ "diff: Shows a pseudo-diff of the user's ~/.cabal/config file and" ++ " the default configuration that would be created by cabal if the" ++ " config file did not exist.\n" ++ "update: Applies the pseudo-diff to the configuration that would be" ++ " created by default, and write the result back to ~/.cabal/config.", commandNotes = Nothing, commandUsage = usageAlternatives "user-config" ["diff", "update"], commandDefaultFlags = mempty, commandOptions = \ _ -> [ optionVerbosity userConfigVerbosity (\v flags -> flags { userConfigVerbosity = v }) ] } -- ------------------------------------------------------------ -- * GetOpt Utils -- ------------------------------------------------------------ reqArgFlag :: ArgPlaceHolder -> MkOptDescr (b -> Flag String) (Flag String -> b -> b) b reqArgFlag ad = reqArg ad (succeedReadE Flag) flagToList liftOptions :: (b -> a) -> (a -> b -> b) -> [OptionField a] -> [OptionField b] liftOptions get set = map (liftOption get set) yesNoOpt :: ShowOrParseArgs -> MkOptDescr (b -> Flag Bool) (Flag Bool -> b -> b) b yesNoOpt ShowArgs sf lf = trueArg sf lf yesNoOpt _ sf lf = Command.boolOpt' flagToMaybe Flag (sf, lf) ([], map ("no-" ++) lf) sf lf optionSolver :: (flags -> Flag PreSolver) -> (Flag PreSolver -> flags -> flags) -> OptionField flags optionSolver get set = option [] ["solver"] ("Select dependency solver to use (default: " ++ display defaultSolver ++ "). Choices: " ++ allSolvers ++ ", where 'choose' chooses between 'topdown' and 'modular' based on compiler version.") get set (reqArg "SOLVER" (readP_to_E (const $ "solver must be one of: " ++ allSolvers) (toFlag `fmap` parse)) (flagToList . fmap display)) optionSolverFlags :: ShowOrParseArgs -> (flags -> Flag Int ) -> (Flag Int -> flags -> flags) -> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags) -> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags) -> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags) -> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags) -> [OptionField flags] optionSolverFlags showOrParseArgs getmbj setmbj getrg setrg _getig _setig getsip setsip getstrfl setstrfl = [ option [] ["max-backjumps"] ("Maximum number of backjumps allowed while solving (default: " ++ show defaultMaxBackjumps ++ "). Use a negative number to enable unlimited backtracking. Use 0 to disable backtracking completely.") getmbj setmbj (reqArg "NUM" (readP_to_E ("Cannot parse number: "++) (fmap toFlag (Parse.readS_to_P reads))) (map show . flagToList)) , option [] ["reorder-goals"] "Try to reorder goals according to certain heuristics. Slows things down on average, but may make backtracking faster for some packages." getrg setrg (yesNoOpt showOrParseArgs) -- TODO: Disabled for now because it does not work as advertised (yet). {- , option [] ["independent-goals"] "Treat several goals on the command line as independent. If several goals depend on the same package, different versions can be chosen." getig setig (yesNoOpt showOrParseArgs) -} , option [] ["shadow-installed-packages"] "If multiple package instances of the same version are installed, treat all but one as shadowed." getsip setsip (yesNoOpt showOrParseArgs) , option [] ["strong-flags"] "Do not defer flag choices (this used to be the default in cabal-install <= 1.20)." getstrfl setstrfl (yesNoOpt showOrParseArgs) ] usageFlagsOrPackages :: String -> String -> String usageFlagsOrPackages name pname = "Usage: " ++ pname ++ " " ++ name ++ " [FLAGS]\n" ++ " or: " ++ pname ++ " " ++ name ++ " [PACKAGES]\n" usagePackages :: String -> String -> String usagePackages name pname = "Usage: " ++ pname ++ " " ++ name ++ " [PACKAGES]\n" usageFlags :: String -> String -> String usageFlags name pname = "Usage: " ++ pname ++ " " ++ name ++ " [FLAGS]\n" --TODO: do we want to allow per-package flags? parsePackageArgs :: [String] -> Either String [Dependency] parsePackageArgs = parsePkgArgs [] where parsePkgArgs ds [] = Right (reverse ds) parsePkgArgs ds (arg:args) = case readPToMaybe parseDependencyOrPackageId arg of Just dep -> parsePkgArgs (dep:ds) args Nothing -> Left $ show arg ++ " is not valid syntax for a package name or" ++ " package dependency." readPToMaybe :: Parse.ReadP a a -> String -> Maybe a readPToMaybe p str = listToMaybe [ r | (r,s) <- Parse.readP_to_S p str , all isSpace s ] parseDependencyOrPackageId :: Parse.ReadP r Dependency parseDependencyOrPackageId = parse Parse.+++ liftM pkgidToDependency parse where pkgidToDependency :: PackageIdentifier -> Dependency pkgidToDependency p = case packageVersion p of Version [] _ -> Dependency (packageName p) anyVersion version -> Dependency (packageName p) (thisVersion version) showRepo :: RemoteRepo -> String showRepo repo = remoteRepoName repo ++ ":" ++ uriToString id (remoteRepoURI repo) [] readRepo :: String -> Maybe RemoteRepo readRepo = readPToMaybe parseRepo parseRepo :: Parse.ReadP r RemoteRepo parseRepo = do name <- Parse.munch1 (\c -> isAlphaNum c || c `elem` "_-.") _ <- Parse.char ':' uriStr <- Parse.munch1 (\c -> isAlphaNum c || c `elem` "+-=._/*()@'$:;&!?~") uri <- maybe Parse.pfail return (parseAbsoluteURI uriStr) return $ RemoteRepo { remoteRepoName = name, remoteRepoURI = uri } -- ------------------------------------------------------------ -- * Helpers for Documentation -- ------------------------------------------------------------ headLine :: String -> String headLine = unlines . map unwords . wrapLine 79 . words paragraph :: String -> String paragraph = (++"\n") . unlines . map unwords . wrapLine 79 . words indentParagraph :: String -> String indentParagraph = unlines . map ((" "++).unwords) . wrapLine 77 . words relevantConfigValuesText :: [String] -> String relevantConfigValuesText vs = "Relevant global configuration keys:\n" ++ concat [" " ++ v ++ "\n" |v <- vs]
kosmikus/cabal
cabal-install/Distribution/Client/Setup.hs
bsd-3-clause
85,914
0
37
23,979
17,740
10,005
7,735
1,668
5
{-# LANGUAGE TemplateHaskell #-} module Robots2.Quiz where import Inter.Types import Autolib.ToDoc import Autolib.Reader import Data.Typeable data RC = RC { width :: Integer -- ^ feld geht von (-w.-w) .. (w,w) , num_robots :: Int , num_targets :: Int , at_least :: Int -- ^ req length of solution , search_width :: Int -- ^ at most that many nodes per level } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''RC]) rc :: RC rc = RC { width = 3 , num_robots = 5 , num_targets = 2 , at_least = 5 , search_width = 1000 } -- Local Variables: -- mode: haskell -- End:
florianpilz/autotool
src/Robots2/Quiz.hs
gpl-2.0
622
4
9
156
148
93
55
19
1
{-| Module : LexerMessage License : GPL Maintainer : helium@cs.uu.nl Stability : experimental Portability : portable -} module Helium.Parser.LexerMessage ( LexerError(..) , LexerErrorInfo(..) , LexerWarning(..) , LexerWarningInfo(..) , keepOneTabWarning , sourcePosToRange , isLooksLikeFloatWarningInfo ) where import Text.ParserCombinators.Parsec.Pos import Helium.Syntax.UHA_Syntax(Range(..), Position(..)) import Helium.StaticAnalysis.Messages.Messages import qualified Helium.Utils.Texts as Texts instance HasMessage LexerError where getRanges (LexerError _ (StillOpenAtEOF brackets)) = reverse (map (sourcePosToRange . fst) brackets) getRanges (LexerError pos (UnexpectedClose _ pos2 _)) = map sourcePosToRange [pos, pos2] getRanges (LexerError pos _) = [ sourcePosToRange pos ] getMessage (LexerError _ info) = let (line:rest) = showLexerErrorInfo info in MessageOneLiner (MessageString line) : [ MessageHints Texts.hint [ MessageString s | s <- rest ] ] sourcePosToRange :: SourcePos -> Range sourcePosToRange pos = let name = sourceName pos; line = sourceLine pos; col = sourceColumn pos position = Position_Position name line col in Range_Range position position data LexerError = LexerError SourcePos LexerErrorInfo data LexerErrorInfo = UnterminatedComment | MissingExponentDigits | UnexpectedChar Char | IllegalEscapeInChar | EmptyChar | IllegalCharInChar | NonTerminatedChar (Maybe String) | EOFInChar | EOFInString | IllegalEscapeInString | NewLineInString | IllegalCharInString | TooManyClose Char -- In UnexpectedClose, first char is the closing bracket we see, -- second char is the closing bracket we would like to see first -- e.g. [(1,3] => UnexpectedClose ']' ... ')' | UnexpectedClose Char SourcePos Char | StillOpenAtEOF [(SourcePos, Char)] showLexerErrorInfo :: LexerErrorInfo -> [String] showLexerErrorInfo info = case info of UnterminatedComment -> [ Texts.lexerUnterminatedComment ] MissingExponentDigits -> [ Texts.lexerMissingExponentDigits , correctFloats ] UnexpectedChar c -> [ Texts.lexerUnexpectedChar c ] IllegalEscapeInChar -> [ Texts.lexerIllegalEscapeInChar, correctChars ] EmptyChar -> [ Texts.lexerEmptyChar, correctChars ] IllegalCharInChar -> [ Texts.lexerIllegalCharInChar, correctChars ] NonTerminatedChar mn -> [ Texts.lexerNonTerminatedChar , correctChars ] ++ case mn of Nothing -> [] Just name -> [ Texts.lexerInfixHint name ] EOFInChar -> [ Texts.lexerEOFInChar, correctChars] EOFInString -> [ Texts.lexerEOFInString, correctStrings ] IllegalEscapeInString -> [ Texts.lexerIllegalEscapeInString, correctStrings ] NewLineInString -> [ Texts.lexerNewLineInString, correctStrings ] IllegalCharInString -> [ Texts.lexerIllegalCharInString, correctStrings] TooManyClose c -> [ Texts.lexerTooManyClose c ] UnexpectedClose c1 _ c2 -> Texts.lexerUnexpectedClose c1 c2 StillOpenAtEOF [b] -> [ Texts.lexerStillOpenAtEOF [ show (snd b) ] ] StillOpenAtEOF bs -> [ Texts.lexerStillOpenAtEOF (reverse (map (show.snd) bs)) ] -- 'reverse' because positions will be sorted and brackets are -- reported in reversed order correctFloats, correctChars, correctStrings :: String correctFloats = Texts.lexerCorrectFloats correctChars = Texts.lexerCorrectChars correctStrings = Texts.lexerCorrectStrings instance HasMessage LexerWarning where getRanges (LexerWarning pos (NestedComment pos2)) = map sourcePosToRange [ pos, pos2 ] getRanges (LexerWarning pos _) = [ sourcePosToRange pos ] getMessage (LexerWarning _ info) = let (line:rest) = showLexerWarningInfo info in MessageOneLiner (MessageString (Texts.warning ++ ": " ++ line)) : [ MessageHints Texts.hint [ MessageString s | s <- rest ] ] data LexerWarning = LexerWarning SourcePos LexerWarningInfo data LexerWarningInfo = TabCharacter | LooksLikeFloatNoFraction String | LooksLikeFloatNoDigits String | NestedComment SourcePos | CommentOperator showLexerWarningInfo :: LexerWarningInfo -> [String] showLexerWarningInfo info = case info of TabCharacter -> Texts.lexerTabCharacter LooksLikeFloatNoFraction digits -> Texts.lexerLooksLikeFloatNoFraction digits LooksLikeFloatNoDigits fraction -> Texts.lexerLooksLikeFloatNoDigits fraction NestedComment _ -> Texts.lexerNestedComment CommentOperator -> Texts.lexerCommentOperator keepOneTabWarning :: [LexerWarning] -> [LexerWarning] keepOneTabWarning = keepOneTab True where keepOneTab isFirst (warning@(LexerWarning _ TabCharacter):rest) | isFirst = warning : keepOneTab False rest | otherwise = keepOneTab isFirst rest keepOneTab isFirst (warning:rest) = warning : keepOneTab isFirst rest keepOneTab _ [] = [] isLooksLikeFloatWarningInfo :: LexerWarningInfo -> Bool isLooksLikeFloatWarningInfo warningInfo = case warningInfo of LooksLikeFloatNoFraction _ -> True LooksLikeFloatNoDigits _ -> True _ -> False
roberth/uu-helium
src/Helium/Parser/LexerMessage.hs
gpl-3.0
5,745
0
15
1,565
1,230
658
572
114
17
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Route53Domains.RegisterDomain -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- This operation registers a domain. Domains are registered by the AWS -- registrar partner, Gandi. For some top-level domains (TLDs), this -- operation requires extra parameters. -- -- When you register a domain, Amazon Route 53 does the following: -- -- - Creates a Amazon Route 53 hosted zone that has the same name as the -- domain. Amazon Route 53 assigns four name servers to your hosted -- zone and automatically updates your domain registration with the -- names of these name servers. -- - Enables autorenew, so your domain registration will renew -- automatically each year. We\'ll notify you in advance of the renewal -- date so you can choose whether to renew the registration. -- - Optionally enables privacy protection, so WHOIS queries return -- contact information for our registrar partner, Gandi, instead of the -- information you entered for registrant, admin, and tech contacts. -- - If registration is successful, returns an operation ID that you can -- use to track the progress and completion of the action. If the -- request is not completed successfully, the domain registrant is -- notified by email. -- - Charges your AWS account an amount based on the top-level domain. -- For more information, see -- <http://aws.amazon.com/route53/pricing/ Amazon Route 53 Pricing>. -- -- /See:/ <http://docs.aws.amazon.com/Route53/latest/APIReference/api-RegisterDomain.html AWS API Reference> for RegisterDomain. module Network.AWS.Route53Domains.RegisterDomain ( -- * Creating a Request registerDomain , RegisterDomain -- * Request Lenses , rdPrivacyProtectTechContact , rdPrivacyProtectRegistrantContact , rdAutoRenew , rdPrivacyProtectAdminContact , rdIdNLangCode , rdDomainName , rdDurationInYears , rdAdminContact , rdRegistrantContact , rdTechContact -- * Destructuring the Response , registerDomainResponse , RegisterDomainResponse -- * Response Lenses , rdrsResponseStatus , rdrsOperationId ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.Route53Domains.Types import Network.AWS.Route53Domains.Types.Product -- | The RegisterDomain request includes the following elements. -- -- /See:/ 'registerDomain' smart constructor. data RegisterDomain = RegisterDomain' { _rdPrivacyProtectTechContact :: !(Maybe Bool) , _rdPrivacyProtectRegistrantContact :: !(Maybe Bool) , _rdAutoRenew :: !(Maybe Bool) , _rdPrivacyProtectAdminContact :: !(Maybe Bool) , _rdIdNLangCode :: !(Maybe Text) , _rdDomainName :: !Text , _rdDurationInYears :: !Nat , _rdAdminContact :: !(Sensitive ContactDetail) , _rdRegistrantContact :: !(Sensitive ContactDetail) , _rdTechContact :: !(Sensitive ContactDetail) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'RegisterDomain' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rdPrivacyProtectTechContact' -- -- * 'rdPrivacyProtectRegistrantContact' -- -- * 'rdAutoRenew' -- -- * 'rdPrivacyProtectAdminContact' -- -- * 'rdIdNLangCode' -- -- * 'rdDomainName' -- -- * 'rdDurationInYears' -- -- * 'rdAdminContact' -- -- * 'rdRegistrantContact' -- -- * 'rdTechContact' registerDomain :: Text -- ^ 'rdDomainName' -> Natural -- ^ 'rdDurationInYears' -> ContactDetail -- ^ 'rdAdminContact' -> ContactDetail -- ^ 'rdRegistrantContact' -> ContactDetail -- ^ 'rdTechContact' -> RegisterDomain registerDomain pDomainName_ pDurationInYears_ pAdminContact_ pRegistrantContact_ pTechContact_ = RegisterDomain' { _rdPrivacyProtectTechContact = Nothing , _rdPrivacyProtectRegistrantContact = Nothing , _rdAutoRenew = Nothing , _rdPrivacyProtectAdminContact = Nothing , _rdIdNLangCode = Nothing , _rdDomainName = pDomainName_ , _rdDurationInYears = _Nat # pDurationInYears_ , _rdAdminContact = _Sensitive # pAdminContact_ , _rdRegistrantContact = _Sensitive # pRegistrantContact_ , _rdTechContact = _Sensitive # pTechContact_ } -- | Whether you want to conceal contact information from WHOIS queries. If -- you specify true, WHOIS (\"who is\") queries will return contact -- information for our registrar partner, Gandi, instead of the contact -- information that you enter. -- -- Type: Boolean -- -- Default: 'true' -- -- Valid values: 'true' | 'false' -- -- Required: No rdPrivacyProtectTechContact :: Lens' RegisterDomain (Maybe Bool) rdPrivacyProtectTechContact = lens _rdPrivacyProtectTechContact (\ s a -> s{_rdPrivacyProtectTechContact = a}); -- | Whether you want to conceal contact information from WHOIS queries. If -- you specify true, WHOIS (\"who is\") queries will return contact -- information for our registrar partner, Gandi, instead of the contact -- information that you enter. -- -- Type: Boolean -- -- Default: 'true' -- -- Valid values: 'true' | 'false' -- -- Required: No rdPrivacyProtectRegistrantContact :: Lens' RegisterDomain (Maybe Bool) rdPrivacyProtectRegistrantContact = lens _rdPrivacyProtectRegistrantContact (\ s a -> s{_rdPrivacyProtectRegistrantContact = a}); -- | Indicates whether the domain will be automatically renewed ('true') or -- not ('false'). Autorenewal only takes effect after the account is -- charged. -- -- Type: Boolean -- -- Valid values: 'true' | 'false' -- -- Default: 'true' -- -- Required: No rdAutoRenew :: Lens' RegisterDomain (Maybe Bool) rdAutoRenew = lens _rdAutoRenew (\ s a -> s{_rdAutoRenew = a}); -- | Whether you want to conceal contact information from WHOIS queries. If -- you specify true, WHOIS (\"who is\") queries will return contact -- information for our registrar partner, Gandi, instead of the contact -- information that you enter. -- -- Type: Boolean -- -- Default: 'true' -- -- Valid values: 'true' | 'false' -- -- Required: No rdPrivacyProtectAdminContact :: Lens' RegisterDomain (Maybe Bool) rdPrivacyProtectAdminContact = lens _rdPrivacyProtectAdminContact (\ s a -> s{_rdPrivacyProtectAdminContact = a}); -- | Reserved for future use. rdIdNLangCode :: Lens' RegisterDomain (Maybe Text) rdIdNLangCode = lens _rdIdNLangCode (\ s a -> s{_rdIdNLangCode = a}); -- | The name of a domain. -- -- Type: String -- -- Default: None -- -- Constraints: The domain name can contain only the letters a through z, -- the numbers 0 through 9, and hyphen (-). Internationalized Domain Names -- are not supported. -- -- Required: Yes rdDomainName :: Lens' RegisterDomain Text rdDomainName = lens _rdDomainName (\ s a -> s{_rdDomainName = a}); -- | The number of years the domain will be registered. Domains are -- registered for a minimum of one year. The maximum period depends on the -- top-level domain. -- -- Type: Integer -- -- Default: 1 -- -- Valid values: Integer from 1 to 10 -- -- Required: Yes rdDurationInYears :: Lens' RegisterDomain Natural rdDurationInYears = lens _rdDurationInYears (\ s a -> s{_rdDurationInYears = a}) . _Nat; -- | Provides detailed contact information. -- -- Type: Complex -- -- Children: 'FirstName', 'MiddleName', 'LastName', 'ContactType', -- 'OrganizationName', 'AddressLine1', 'AddressLine2', 'City', 'State', -- 'CountryCode', 'ZipCode', 'PhoneNumber', 'Email', 'Fax', 'ExtraParams' -- -- Required: Yes rdAdminContact :: Lens' RegisterDomain ContactDetail rdAdminContact = lens _rdAdminContact (\ s a -> s{_rdAdminContact = a}) . _Sensitive; -- | Provides detailed contact information. -- -- Type: Complex -- -- Children: 'FirstName', 'MiddleName', 'LastName', 'ContactType', -- 'OrganizationName', 'AddressLine1', 'AddressLine2', 'City', 'State', -- 'CountryCode', 'ZipCode', 'PhoneNumber', 'Email', 'Fax', 'ExtraParams' -- -- Required: Yes rdRegistrantContact :: Lens' RegisterDomain ContactDetail rdRegistrantContact = lens _rdRegistrantContact (\ s a -> s{_rdRegistrantContact = a}) . _Sensitive; -- | Provides detailed contact information. -- -- Type: Complex -- -- Children: 'FirstName', 'MiddleName', 'LastName', 'ContactType', -- 'OrganizationName', 'AddressLine1', 'AddressLine2', 'City', 'State', -- 'CountryCode', 'ZipCode', 'PhoneNumber', 'Email', 'Fax', 'ExtraParams' -- -- Required: Yes rdTechContact :: Lens' RegisterDomain ContactDetail rdTechContact = lens _rdTechContact (\ s a -> s{_rdTechContact = a}) . _Sensitive; instance AWSRequest RegisterDomain where type Rs RegisterDomain = RegisterDomainResponse request = postJSON route53Domains response = receiveJSON (\ s h x -> RegisterDomainResponse' <$> (pure (fromEnum s)) <*> (x .:> "OperationId")) instance ToHeaders RegisterDomain where toHeaders = const (mconcat ["X-Amz-Target" =# ("Route53Domains_v20140515.RegisterDomain" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON RegisterDomain where toJSON RegisterDomain'{..} = object (catMaybes [("PrivacyProtectTechContact" .=) <$> _rdPrivacyProtectTechContact, ("PrivacyProtectRegistrantContact" .=) <$> _rdPrivacyProtectRegistrantContact, ("AutoRenew" .=) <$> _rdAutoRenew, ("PrivacyProtectAdminContact" .=) <$> _rdPrivacyProtectAdminContact, ("IdnLangCode" .=) <$> _rdIdNLangCode, Just ("DomainName" .= _rdDomainName), Just ("DurationInYears" .= _rdDurationInYears), Just ("AdminContact" .= _rdAdminContact), Just ("RegistrantContact" .= _rdRegistrantContact), Just ("TechContact" .= _rdTechContact)]) instance ToPath RegisterDomain where toPath = const "/" instance ToQuery RegisterDomain where toQuery = const mempty -- | The RegisterDomain response includes the following element. -- -- /See:/ 'registerDomainResponse' smart constructor. data RegisterDomainResponse = RegisterDomainResponse' { _rdrsResponseStatus :: !Int , _rdrsOperationId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'RegisterDomainResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rdrsResponseStatus' -- -- * 'rdrsOperationId' registerDomainResponse :: Int -- ^ 'rdrsResponseStatus' -> Text -- ^ 'rdrsOperationId' -> RegisterDomainResponse registerDomainResponse pResponseStatus_ pOperationId_ = RegisterDomainResponse' { _rdrsResponseStatus = pResponseStatus_ , _rdrsOperationId = pOperationId_ } -- | The response status code. rdrsResponseStatus :: Lens' RegisterDomainResponse Int rdrsResponseStatus = lens _rdrsResponseStatus (\ s a -> s{_rdrsResponseStatus = a}); -- | Identifier for tracking the progress of the request. To use this ID to -- query the operation status, use GetOperationDetail. -- -- Type: String -- -- Default: None -- -- Constraints: Maximum 255 characters. rdrsOperationId :: Lens' RegisterDomainResponse Text rdrsOperationId = lens _rdrsOperationId (\ s a -> s{_rdrsOperationId = a});
fmapfmapfmap/amazonka
amazonka-route53-domains/gen/Network/AWS/Route53Domains/RegisterDomain.hs
mpl-2.0
12,291
0
14
2,533
1,463
911
552
160
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.OpsWorks.StopInstance -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Stops a specified instance. When you stop a standard instance, the data -- disappears and must be reinstalled when you restart the instance. You can -- stop an Amazon EBS-backed instance without losing data. For more information, -- see <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-starting.html Starting, Stopping, and Rebooting Instances>. -- -- Required Permissions: To use this action, an IAM user must have a Manage -- permissions level for the stack, or an attached policy that explicitly grants -- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>. -- -- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_StopInstance.html> module Network.AWS.OpsWorks.StopInstance ( -- * Request StopInstance -- ** Request constructor , stopInstance -- ** Request lenses , siInstanceId -- * Response , StopInstanceResponse -- ** Response constructor , stopInstanceResponse ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.OpsWorks.Types import qualified GHC.Exts newtype StopInstance = StopInstance { _siInstanceId :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'StopInstance' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'siInstanceId' @::@ 'Text' -- stopInstance :: Text -- ^ 'siInstanceId' -> StopInstance stopInstance p1 = StopInstance { _siInstanceId = p1 } -- | The instance ID. siInstanceId :: Lens' StopInstance Text siInstanceId = lens _siInstanceId (\s a -> s { _siInstanceId = a }) data StopInstanceResponse = StopInstanceResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'StopInstanceResponse' constructor. stopInstanceResponse :: StopInstanceResponse stopInstanceResponse = StopInstanceResponse instance ToPath StopInstance where toPath = const "/" instance ToQuery StopInstance where toQuery = const mempty instance ToHeaders StopInstance instance ToJSON StopInstance where toJSON StopInstance{..} = object [ "InstanceId" .= _siInstanceId ] instance AWSRequest StopInstance where type Sv StopInstance = OpsWorks type Rs StopInstance = StopInstanceResponse request = post "StopInstance" response = nullResponse StopInstanceResponse
kim/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/StopInstance.hs
mpl-2.0
3,500
0
9
711
363
224
139
48
1
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="en-GB"> <title>Report Alert Generator</title> <maps> <homeID>alertReport</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/alertReport/src/main/javahelp/help/helpset.hs
apache-2.0
988
85
50
170
403
214
189
-1
-1
-- -- 23.TimeCPU.hs -- R_Functional_Programming -- -- Created by RocKK on 2/13/14. -- Copyright (c) 2014 RocKK. -- All rights reserved. -- -- Redistribution and use in source and binary forms are permitted -- provided that the above copyright notice and this paragraph are -- duplicated in all such forms and that any documentation, -- advertising materials, and other materials related to such -- distribution and use acknowledge that the software was developed -- by the RocKK. The name of the -- RocKK may not be used to endorse or promote products derived -- from this software without specific prior written permission. -- THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. import System.CPUTime main = do print cpuTimePrecision getCPUTime >>= print
RocKK-MD/R_Functional_Programming
Sources/23.TimeCPU.hs
bsd-2-clause
930
0
7
168
43
30
13
4
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Server.Util.ServeTarball -- Copyright : (c) 2008 David Himmelstrup -- (c) 2009 Antoine Latter -- License : BSD-like -- -- Maintainer : duncan@haskell.org -- Stability : provisional -- Portability : portable -- -- ----------------------------------------------------------------------------- module Distribution.Server.Util.ServeTarball ( serveTarball , serveTarEntry , constructTarIndexFromFile , constructTarIndex ) where import Happstack.Server.Types import Happstack.Server.Monads import Happstack.Server.Routing (method) import Happstack.Server.Response import Happstack.Server.FileServe as Happstack (mimeTypes) import Distribution.Server.Framework.HappstackUtils (remainingPath) import Distribution.Server.Framework.CacheControl import Distribution.Server.Pages.Template (hackagePage) import Distribution.Server.Framework.ResponseContentTypes as Resource import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Data.TarIndex as TarIndex import Data.TarIndex (TarIndex) import qualified Text.XHtml.Strict as XHtml import qualified Data.ByteString.Lazy as BS import qualified Data.Map as Map import System.FilePath import Control.Monad.Trans (MonadIO, liftIO) import Control.Monad (msum, mzero) import System.IO -- | Serve the contents of a tar file -- file. TODO: This is not a sustainable implementation, -- but it gives us something to test with. serveTarball :: MonadIO m => [FilePath] -- dir index file names (e.g. ["index.html"]) -> FilePath -- root dir in tar to serve -> FilePath -- the tarball -> TarIndex -- index for tarball -> [CacheControl] -> ETag -- the etag -> ServerPartT m Response serveTarball indices tarRoot tarball tarIndex cacheCtls etag = do rq <- askRq action GET $ remainingPath $ \paths -> do -- first we come up with the set of paths in the tarball that -- would match our request let validPaths :: [FilePath] validPaths = (joinPath $ tarRoot:paths) : [joinPath $ tarRoot:paths ++ [index] | index <- indices] msum $ concat [ serveFiles validPaths , serveDirs (rqUri rq) validPaths ] where serveFiles paths = flip map paths $ \path -> case TarIndex.lookup tarIndex path of Just (TarIndex.TarFileEntry off) -> do cacheControl cacheCtls etag tfe <- liftIO $ serveTarEntry tarball off path ok (toResponse tfe) _ -> mzero action act m = method act >> m serveDirs fullPath paths = flip map paths $ \path -> case TarIndex.lookup tarIndex path of Just (TarIndex.TarDir fs) | not (hasTrailingPathSeparator fullPath) -> seeOther (addTrailingPathSeparator fullPath) (toResponse ()) | otherwise -> do cacheControl cacheCtls etag ok $ toResponse $ Resource.XHtml $ renderDirIndex fs _ -> mzero renderDirIndex :: [FilePath] -> XHtml.Html renderDirIndex entries = hackagePage "Directory Listing" [ (XHtml.anchor XHtml.! [XHtml.href e] XHtml.<< e) XHtml.+++ XHtml.br | e <- entries ] serveTarEntry :: FilePath -> Int -> FilePath -> IO Response serveTarEntry tarfile off fname = do htar <- openFile tarfile ReadMode hSeek htar AbsoluteSeek (fromIntegral (off * 512)) header <- BS.hGet htar 512 case Tar.read header of (Tar.Next Tar.Entry{Tar.entryContent = Tar.NormalFile _ size} _) -> do body <- BS.hGet htar (fromIntegral size) let extension = case takeExtension fname of ('.':ext) -> ext ext -> ext mimeType = Map.findWithDefault "text/plain" extension mimeTypes' response = ((setHeader "Content-Length" (show size)) . (setHeader "Content-Type" mimeType)) $ resultBS 200 body return response _ -> fail "oh noes!!" -- | Extended mapping from file extension to mime type mimeTypes' :: Map.Map String String mimeTypes' = Happstack.mimeTypes `Map.union` Map.fromList [("xhtml", "application/xhtml+xml")] constructTarIndexFromFile :: FilePath -> IO TarIndex constructTarIndexFromFile file = do tar <- BS.readFile file case constructTarIndex tar of Left err -> fail err Right tarIndex -> return tarIndex -- | Forcing the Either will force the tar index constructTarIndex :: BS.ByteString -> Either String TarIndex constructTarIndex tar = case extractInfo (Tar.read tar) of Just info -> let tarIndex = TarIndex.construct info in tarIndex `seq` Right tarIndex Nothing -> Left "bad tar file" type Block = Int extractInfo :: Tar.Entries e -> Maybe [(FilePath, Block)] extractInfo = go 0 [] where go _ es' (Tar.Done) = Just es' go _ _ (Tar.Fail _) = Nothing go n es' (Tar.Next e es) = go n' ((Tar.entryPath e, n) : es') es where n' = n + 1 + case Tar.entryContent e of Tar.NormalFile _ size -> blocks size Tar.OtherEntryType _ _ size -> blocks size _ -> 0 blocks s = 1 + ((fromIntegral s - 1) `div` 512)
haskell-infra/hackage-server
Distribution/Server/Util/ServeTarball.hs
bsd-3-clause
5,625
0
21
1,605
1,394
733
661
112
5
module Distribution.Simple.HaskellSuite where import Control.Monad import Data.Maybe import Data.Version import qualified Data.Map as M (empty) import Distribution.Simple.Program import Distribution.Simple.Compiler as Compiler import Distribution.Simple.Utils import Distribution.Simple.BuildPaths import Distribution.Verbosity import Distribution.Text import Distribution.Package import Distribution.InstalledPackageInfo hiding (includeDirs) import Distribution.Simple.PackageIndex as PackageIndex import Distribution.PackageDescription import Distribution.Simple.LocalBuildInfo import Distribution.System (Platform) import Distribution.Compat.Exception import Language.Haskell.Extension import Distribution.Simple.Program.Builtin (haskellSuiteProgram, haskellSuitePkgProgram) configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration) configure verbosity mbHcPath hcPkgPath conf0 = do -- We have no idea how a haskell-suite tool is named, so we require at -- least some information from the user. hcPath <- let msg = "You have to provide name or path of a haskell-suite tool (-w PATH)" in maybe (die msg) return mbHcPath when (isJust hcPkgPath) $ warn verbosity "--with-hc-pkg option is ignored for haskell-suite" (comp, confdCompiler, conf1) <- configureCompiler hcPath conf0 -- Update our pkg tool. It uses the same executable as the compiler, but -- all command start with "pkg" (confdPkg, _) <- requireProgram verbosity haskellSuitePkgProgram conf1 let conf2 = updateProgram confdPkg { programLocation = programLocation confdCompiler , programDefaultArgs = ["pkg"] } conf1 return (comp, Nothing, conf2) where configureCompiler hcPath conf0' = do let haskellSuiteProgram' = haskellSuiteProgram { programFindLocation = \v _p -> findProgramLocation v hcPath } -- NB: cannot call requireProgram right away — it'd think that -- the program is already configured and won't reconfigure it again. -- Instead, call configureProgram directly first. conf1 <- configureProgram verbosity haskellSuiteProgram' conf0' (confdCompiler, conf2) <- requireProgram verbosity haskellSuiteProgram' conf1 extensions <- getExtensions verbosity confdCompiler languages <- getLanguages verbosity confdCompiler (compName, compVersion) <- getCompilerVersion verbosity confdCompiler let comp = Compiler { compilerId = CompilerId (HaskellSuite compName) compVersion, compilerAbiTag = Compiler.NoAbiTag, compilerCompat = [], compilerLanguages = languages, compilerExtensions = extensions, compilerProperties = M.empty } return (comp, confdCompiler, conf2) hstoolVersion :: Verbosity -> FilePath -> IO (Maybe Version) hstoolVersion = findProgramVersion "--hspkg-version" id numericVersion :: Verbosity -> FilePath -> IO (Maybe Version) numericVersion = findProgramVersion "--compiler-version" (last . words) getCompilerVersion :: Verbosity -> ConfiguredProgram -> IO (String, Version) getCompilerVersion verbosity prog = do output <- rawSystemStdout verbosity (programPath prog) ["--compiler-version"] let parts = words output name = concat $ init parts -- there shouldn't be any spaces in the name anyway versionStr = last parts version <- maybe (die "haskell-suite: couldn't determine compiler version") return $ simpleParse versionStr return (name, version) getExtensions :: Verbosity -> ConfiguredProgram -> IO [(Extension, Compiler.Flag)] getExtensions verbosity prog = do extStrs <- lines `fmap` rawSystemStdout verbosity (programPath prog) ["--supported-extensions"] return [ (ext, "-X" ++ display ext) | Just ext <- map simpleParse extStrs ] getLanguages :: Verbosity -> ConfiguredProgram -> IO [(Language, Compiler.Flag)] getLanguages verbosity prog = do langStrs <- lines `fmap` rawSystemStdout verbosity (programPath prog) ["--supported-languages"] return [ (ext, "-G" ++ display ext) | Just ext <- map simpleParse langStrs ] -- Other compilers do some kind of a packagedb stack check here. Not sure -- if we need something like that as well. getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration -> IO InstalledPackageIndex getInstalledPackages verbosity packagedbs conf = liftM (PackageIndex.fromList . concat) $ forM packagedbs $ \packagedb -> do str <- getDbProgramOutput verbosity haskellSuitePkgProgram conf ["dump", packageDbOpt packagedb] `catchExit` \_ -> die $ "pkg dump failed" case parsePackages str of Right ok -> return ok _ -> die "failed to parse output of 'pkg dump'" where parsePackages str = let parsed = map parseInstalledPackageInfo (splitPkgs str) in case [ msg | ParseFailed msg <- parsed ] of [] -> Right [ pkg | ParseOk _ pkg <- parsed ] msgs -> Left msgs splitPkgs :: String -> [String] splitPkgs = map unlines . splitWith ("---" ==) . lines where splitWith :: (a -> Bool) -> [a] -> [[a]] splitWith p xs = ys : case zs of [] -> [] _:ws -> splitWith p ws where (ys,zs) = break p xs buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildLib verbosity pkg_descr lbi lib clbi = do -- In future, there should be a mechanism for the compiler to request any -- number of the above parameters (or their parts) — in particular, -- pieces of PackageDescription. -- -- For now, we only pass those that we know are used. let odir = buildDir lbi bi = libBuildInfo lib srcDirs = hsSourceDirs bi ++ [odir] dbStack = withPackageDB lbi language = fromMaybe Haskell98 (defaultLanguage bi) conf = withPrograms lbi pkgid = packageId pkg_descr runDbProgram verbosity haskellSuiteProgram conf $ [ "compile", "--build-dir", odir ] ++ concat [ ["-i", d] | d <- srcDirs ] ++ concat [ ["-I", d] | d <- [autogenModulesDir lbi, odir] ++ includeDirs bi ] ++ [ packageDbOpt pkgDb | pkgDb <- dbStack ] ++ [ "--package-name", display pkgid ] ++ concat [ ["--package-id", display ipkgid ] | (ipkgid, _) <- componentPackageDeps clbi ] ++ ["-G", display language] ++ concat [ ["-X", display ex] | ex <- usedExtensions bi ] ++ cppOptions (libBuildInfo lib) ++ [ display modu | modu <- libModules lib ] installLib :: Verbosity -> LocalBuildInfo -> FilePath -- ^install location -> FilePath -- ^install location for dynamic libraries -> FilePath -- ^Build location -> PackageDescription -> Library -> ComponentLocalBuildInfo -> IO () installLib verbosity lbi targetDir dynlibTargetDir builtDir pkg lib _clbi = do let conf = withPrograms lbi runDbProgram verbosity haskellSuitePkgProgram conf $ [ "install-library" , "--build-dir", builtDir , "--target-dir", targetDir , "--dynlib-target-dir", dynlibTargetDir , "--package-id", display $ packageId pkg ] ++ map display (libModules lib) registerPackage :: Verbosity -> InstalledPackageInfo -> PackageDescription -> LocalBuildInfo -> Bool -> PackageDBStack -> IO () registerPackage verbosity installedPkgInfo _pkg lbi _inplace packageDbs = do (hspkg, _) <- requireProgram verbosity haskellSuitePkgProgram (withPrograms lbi) runProgramInvocation verbosity $ (programInvocation hspkg ["update", packageDbOpt $ last packageDbs]) { progInvokeInput = Just $ showInstalledPackageInfo installedPkgInfo } initPackageDB :: Verbosity -> ProgramConfiguration -> FilePath -> IO () initPackageDB verbosity conf dbPath = runDbProgram verbosity haskellSuitePkgProgram conf ["init", dbPath] packageDbOpt :: PackageDB -> String packageDbOpt GlobalPackageDB = "--global" packageDbOpt UserPackageDB = "--user" packageDbOpt (SpecificPackageDB db) = "--package-db=" ++ db
trskop/cabal
Cabal/Distribution/Simple/HaskellSuite.hs
bsd-3-clause
8,301
0
21
1,863
2,010
1,045
965
175
4
module NPDA.Nachfolger -- $Id$ ( nachfolger , folgekonfigurationen -- brauchen wir nicht? ) where import NPDA.Type import NPDA.Konfiguration import Autolib.Schichten import Autolib.Set nachfolger :: NPDAC x y z => NPDA x y z -> Konfiguration x y z -> [ Konfiguration x y z ] nachfolger a k = concat $ map setToList $ schichten (folgekonfigurationen a ) k sinnvoll :: NPDAC x y z => Konfiguration x y z -> Bool sinnvoll k = -- length (keller k) <= 2 * length (eingabe k) + 3 True folgekonfigurationen :: NPDAC x y z => NPDA x y z -> Konfiguration x y z -> Set (Konfiguration x y z) folgekonfigurationen a k = mkSet $ filter sinnvoll $ setToList $ epsilon_schritte a k `union` einer_schritte a k epsilon_schritte a k = case keller k of [] -> emptySet -- Keller leer, nichts geht mehr (y : ys) -> mkSet $ do (z', y') <- setToList $ lookupset (transitionen a) (Nothing, zustand k, y) return $ Konfiguration { schritt = succ $ schritt k , eingabe = eingabe k , zustand = z' , keller = y' ++ ys , link = Just k } einer_schritte a k = case keller k of [] -> emptySet (y : ys) -> case eingabe k of [] -> emptySet -- Eingabe leer, nichts geht mehr (x : xs) -> mkSet $ do (z', y') <- setToList $ lookupset (transitionen a) (Just x, zustand k, y) return $ Konfiguration { schritt = succ $ schritt k , eingabe = xs , zustand = z' , keller = y' ++ ys , link = Just k }
Erdwolf/autotool-bonn
src/NPDA/Nachfolger.hs
gpl-2.0
1,534
9
18
451
561
290
271
43
3
----------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Shaders.ProgramBinaries -- Copyright : (c) Sven Panne 2006-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- This module corresponds to section 7.5 (Program Binaries) of the OpenGL 4.4 -- spec. -- ----------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.Shaders.ProgramBinaries ( ProgramBinaryFormat(..), programBinaryFormats, ProgramBinary(..), programBinary ) where import Foreign.Marshal.Alloc import Graphics.Rendering.OpenGL.GL.ByteString import Graphics.Rendering.OpenGL.GL.PeekPoke import Graphics.Rendering.OpenGL.GL.QueryUtils import Graphics.Rendering.OpenGL.GL.Shaders.Program import Graphics.Rendering.OpenGL.GL.StateVar import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- newtype ProgramBinaryFormat = ProgramBinaryFormat GLenum deriving ( Eq, Ord, Show ) programBinaryFormats :: GettableStateVar [ProgramBinaryFormat] programBinaryFormats = makeGettableStateVar $ do n <- getInteger1 fromIntegral GetNumProgramBinaryFormats getEnumN ProgramBinaryFormat GetProgramBinaryFormats n data ProgramBinary = ProgramBinary ProgramBinaryFormat ByteString deriving ( Eq, Ord, Show ) programBinary :: Program -> StateVar ProgramBinary programBinary program = makeStateVar (getProgramBinary program) (setProgramBinary program) getProgramBinary :: Program -> IO ProgramBinary getProgramBinary program = alloca $ \formatBuf -> do let getBin = bind4th formatBuf (glGetProgramBinary . programID) bs <- stringQuery programBinaryLength getBin program format <- peek1 ProgramBinaryFormat formatBuf return $ ProgramBinary format bs bind4th :: d -> (a -> b -> c -> d -> e) -> (a -> b -> c -> e) bind4th x = ((.) . (.) . (.)) ($ x) setProgramBinary :: Program -> ProgramBinary -> IO () setProgramBinary program (ProgramBinary (ProgramBinaryFormat format) bs) = do withByteString bs $ glProgramBinary (programID program) format programBinaryLength :: Program -> GettableStateVar GLsizei programBinaryLength = programVar1 fromIntegral ProgramBinaryLength
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/Shaders/ProgramBinaries.hs
bsd-3-clause
2,361
0
14
324
481
270
211
36
1
a@(b, c) +++ x = (b + x, c+x, a) main = (4, 5) +++ 6
roberth/uu-helium
test/simple/parser/AsPatternBinding3.hs
gpl-3.0
56
0
7
19
53
30
23
2
1
-- -- Copyright (c) 2011 Citrix Systems, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- -- Some utility file functions module Tools.File ( maybeGetContents , filesInDir , module Tools.FileC , doesFileExist ) where import Control.Monad import Directory import System.IO import System.FilePath.Posix import Tools.FileC maybeGetContents :: FilePath -> IO (Maybe String) maybeGetContents p = doesFileExist p >>= maybeRead where maybeRead False = return Nothing maybeRead True = readFile p >>= return . Just -- Get filepaths in directory, without . or .. filesInDir :: FilePath -> IO [FilePath] filesInDir p = do allentries <- getDirectoryContents p let entries = filter interesting allentries return $ map addPrefix entries where interesting e = e /= "." && e /= ".." addPrefix e = joinPath [p, e]
crogers1/manager
disksync/Tools/File.hs
gpl-2.0
1,593
0
10
369
229
127
102
21
2
{-# LANGUAGE MagicHash #-} {-# LANGUAGE TypeFamilies #-} module T17442 where import Control.Monad import GHC.Arr (Ix(..)) import GHC.Base (getTag) import GHC.Exts data family D data instance D = MkD deriving (Eq, Ord, Show) instance Ix D where range (a, b) = let a# = getTag a b# = getTag b in map (\(I# i#) -> tagToEnum# i# :: D) (enumFromTo (I# a#) (I# b#)) unsafeIndex (a, _) c = let a# = getTag a c# = getTag c d# = c# -# a# in I# d# inRange (a, b) c = let a# = getTag a b# = getTag b c# = getTag c in tagToEnum# (c# >=# a#) && tagToEnum# (c# <=# b#) shouldBe :: (Eq a, Show a) => a -> a -> IO () shouldBe x y = unless (x == y) $ fail $ show x ++ " is not equal to " ++ show y ixLaws :: (Ix a, Show a) => a -> a -> a -> IO () ixLaws l u i = do inRange (l,u) i `shouldBe` elem i (range (l,u)) range (l,u) !! index (l,u) i `shouldBe` i map (index (l,u)) (range (l,u)) `shouldBe` [0..rangeSize (l,u)-1] rangeSize (l,u) `shouldBe` length (range (l,u)) dIsLawfulIx :: IO () dIsLawfulIx = ixLaws MkD MkD MkD
sdiehl/ghc
testsuite/tests/cmm/should_compile/T17442.hs
bsd-3-clause
1,148
0
12
353
582
307
275
37
1
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-} module WaiAppEmbeddedTest (embSpec) where import Codec.Compression.GZip (compress) import EmbeddedTestEntries import Network.Wai import Network.Wai.Application.Static (staticApp) import Network.Wai.Test import Test.Hspec import WaiAppStatic.Storage.Embedded import WaiAppStatic.Types defRequest :: Request defRequest = defaultRequest embSpec :: Spec embSpec = do let embedSettings settings = flip runSession (staticApp settings) let embed = embedSettings $(mkSettings mkEntries) describe "embedded, compressed entry" $ do it "served correctly" $ embed $ do req <- request (setRawPathInfo defRequest "e1.txt") assertStatus 200 req assertHeader "Content-Type" "text/plain" req assertHeader "Content-Encoding" "gzip" req assertHeader "ETag" "Etag 1" req assertNoHeader "Last-Modified req" req assertBody (compress $ body 1000 'A') req it "304 when valid if-none-match sent" $ embed $ do req <- request (setRawPathInfo defRequest "e1.txt") { requestHeaders = [("If-None-Match", "Etag 1")] } assertStatus 304 req it "ssIndices works" $ do let testSettings = $(mkSettings mkEntries){ ssIndices = [unsafeToPiece "index.html"] } embedSettings testSettings $ do req <- request defRequest assertStatus 200 req assertBody "index file" req describe "embedded, uncompressed entry" $ do it "too short" $ embed $ do req <- request (setRawPathInfo defRequest "e2.txt") assertStatus 200 req assertHeader "Content-Type" "text/plain" req assertNoHeader "Content-Encoding" req assertHeader "ETag" "Etag 2" req assertBody "ABC" req it "wrong mime" $ embed $ do req <- request (setRawPathInfo defRequest "somedir/e3.txt") assertStatus 200 req assertHeader "Content-Type" "xxx" req assertNoHeader "Content-Encoding" req assertHeader "ETag" "Etag 3" req assertBody (body 1000 'A') req describe "reloadable entry" $ it "served correctly" $ embed $ do req <- request (setRawPathInfo defRequest "e4.css") assertStatus 200 req assertHeader "Content-Type" "text/css" req assertNoHeader "Content-Encoding" req assertHeader "ETag" "Etag 4" req assertBody (body 2000 'Q') req describe "entries without etags" $ do it "embedded entry" $ embed $ do req <- request (setRawPathInfo defRequest "e5.txt") assertStatus 200 req assertHeader "Content-Type" "text/plain" req assertHeader "Content-Encoding" "gzip" req assertNoHeader "ETag" req assertBody (compress $ body 1000 'Z') req it "reload entry" $ embed $ do req <- request (setRawPathInfo defRequest "e6.txt") assertStatus 200 req assertHeader "Content-Type" "text/plain" req assertNoHeader "Content-Encoding" req assertNoHeader "ETag" req assertBody (body 1000 'W') req
rgrinberg/wai
wai-app-static/test/WaiAppEmbeddedTest.hs
mit
3,337
0
19
1,030
807
360
447
74
1
{- This module provides type inference for the base syntax. Here, you will find only the knot-tying top-level definitions. -} module TiBase(Typing,Scheme{-,GetSigs(..),DeclInfo(..)-}) where import Syntax hiding (extend) import SubstituteBase() import NameMapsBase() -- instance AccNames i (HsDeclI i) import TI --import QualNames import TiBaseStruct --import TiModule(tcModule) import TiDs() --import MUtils import PrettyPrint import Data.List(partition) --import Maybe(mapMaybe) --tstTcModule kbs tbs = -- run emptyEnv . extendk kbs . extend tbs . getSubst . tcModule instance (TypeId i,ValueId i,PrintableOp i,Fresh i,HasSrcLoc i,TypedId PId i) => TypeCheckDecl i (HsDeclI i) [HsDeclI i] where tcDecl bs = tcD bs . struct instance Eq i => CheckRecursion i (HsDeclI i) where checkRecursion ds = checkTypeSynRec ds >> checkClassRec ds instance HasMethodSigs [HsDeclI i] where splitMethodSigs = partition isSig where isSig (Dec (HsTypeSig {})) = True isSig _ = False {- instance GetSigs i [Pred i] (Type i) [HsDeclI i] where getSigs = mapMaybe getSig where getSig (Dec (HsTypeSig s is c tp)) = Just (s,is,c,tp) getSig _ = Nothing -} instance (Fresh i,TypeId i,ValueId i,PrintableOp i,HasSrcLoc i,TypedId PId i) => TypeCheck i (HsExpI i) (Typed i (HsExpI i)) where tc (Exp e) = tcE e instance (Fresh i,TypeId i,ValueId i) => TypeCheck i (HsPatI i) (Typed i (HsPatI i)) where tc (Pat p) = tcP p instance (ValueId i,TypeVar i) => DeclInfo i (HsDeclI i) where --explicitlyTyped m c = explicitlyTyped m c . struct explicitlyTyped ks tinfo c = explicitlyTyped ks tinfo c . struct --isTypeDecl = isTypeDecl . struct isUnrestricted expl = isUnrestricted expl . struct instance HasAbstr i (HsDeclI i) where abstract xs = mapRec (abstract xs) instance HasAbstr i (HsExpI i) where abstract xs = mapRec (abstract xs) instance Eq i => HasLocalDef i (HsExpI i) (HsDeclI i) where letvar x e = mapRec (letvar x e) --instance ({-ValueId i,-}TypeVar i) => KindCheck i (HsDeclI i) () where kc = kc . struct instance TypeVar i => KindCheck i (HsDeclI i) () where kc = kc . struct instance HasId i (HsPatI i) where ident = r . ident; isId = isId . struct instance HasId i (HsExpI i) where ident = r . ident; isId = isId . struct --instance HasLit (SrcLoc->HsExpI i) where lit = flip hsLit --instance HasLit (SrcLoc->HsPatI i) where lit = flip hsPLit instance HasCoreSyntax i (HsPatI i) where app (Pat p1) p2 = r $ pApp p1 p2 tuple = hsPTuple loc0 -- !! loc0 list = hsPList loc0 -- !! loc0 --paren = hsPParen instance HasCoreSyntax i (HsExpI i) where app = hsApp tuple = hsTuple list = hsList --paren = hsParen instance HasTypeApp i (HsExpI i) --where spec x sc ts = ident x instance HasTypeApp i (HsPatI i) --where spec x sc ts = ident x instance HasTypeAnnot i (HsExpI i) instance HasTypeAnnot i (HsPatI i) instance HasDef [HsDeclI i] (HsDeclI i) where nullDef = null consDef = (:); noDef = []; appendDef = (++); toDefs = id filterDefs = filter instance TypeVar i => Types i (HsDeclI i) where tmap f = id tv d = [] instance AddDeclsType i [HsDeclI i] where addDeclsType dt = id
kmate/HaRe
old/tools/base/TI/TiBase.hs
bsd-3-clause
3,210
0
12
668
980
514
466
-1
-1
module Renaming.C7(myFringe) where import Renaming.D7 myFringe:: Tree a -> [a] myFringe (Leaf x ) = [x] myFringe (Branch left right) = myFringe left ++ fringe right
kmate/HaRe
test/testdata/Renaming/C7.hs
bsd-3-clause
173
0
7
34
74
39
35
5
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} -- | Parsing command line targets module Stack.Build.Target ( -- * Types ComponentName , UnresolvedComponent (..) , RawTarget (..) , LocalPackageView (..) , SimpleTarget (..) , NeedTargets (..) -- * Parsers , parseRawTarget , parseTargets ) where import Control.Applicative import Control.Arrow (second) import Control.Monad.Catch (MonadThrow, throwM) import Control.Monad.IO.Class import Data.Either (partitionEithers) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (mapMaybe) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Path import Path.IO import Prelude -- Fix redundant import warnings import Stack.Types -- | The name of a component, which applies to executables, test suites, and benchmarks type ComponentName = Text newtype RawInput = RawInput { unRawInput :: Text } -- | Either a fully resolved component, or a component name that could be -- either an executable, test, or benchmark data UnresolvedComponent = ResolvedComponent !NamedComponent | UnresolvedComponent !ComponentName deriving (Show, Eq, Ord) -- | Raw command line input, without checking against any databases or list of -- locals. Does not deal with directories data RawTarget (a :: RawTargetType) where RTPackageComponent :: !PackageName -> !UnresolvedComponent -> RawTarget a RTComponent :: !ComponentName -> RawTarget a RTPackage :: !PackageName -> RawTarget a RTPackageIdentifier :: !PackageIdentifier -> RawTarget 'HasIdents deriving instance Show (RawTarget a) deriving instance Eq (RawTarget a) deriving instance Ord (RawTarget a) data RawTargetType = HasIdents | NoIdents -- | If this function returns @Nothing@, the input should be treated as a -- directory. parseRawTarget :: Text -> Maybe (RawTarget 'HasIdents) parseRawTarget t = (RTPackageIdentifier <$> parsePackageIdentifierFromString s) <|> (RTPackage <$> parsePackageNameFromString s) <|> (RTComponent <$> T.stripPrefix ":" t) <|> parsePackageComponent where s = T.unpack t parsePackageComponent = case T.splitOn ":" t of [pname, "lib"] | Just pname' <- parsePackageNameFromString (T.unpack pname) -> Just $ RTPackageComponent pname' $ ResolvedComponent CLib [pname, cname] | Just pname' <- parsePackageNameFromString (T.unpack pname) -> Just $ RTPackageComponent pname' $ UnresolvedComponent cname [pname, typ, cname] | Just pname' <- parsePackageNameFromString (T.unpack pname) , Just wrapper <- parseCompType typ -> Just $ RTPackageComponent pname' $ ResolvedComponent $ wrapper cname _ -> Nothing parseCompType t' = case t' of "exe" -> Just CExe "test" -> Just CTest "bench" -> Just CBench _ -> Nothing -- | A view of a local package needed for resolving components data LocalPackageView = LocalPackageView { lpvVersion :: !Version , lpvRoot :: !(Path Abs Dir) , lpvCabalFP :: !(Path Abs File) , lpvComponents :: !(Set NamedComponent) , lpvExtraDep :: !Bool } -- | Same as @parseRawTarget@, but also takes directories into account. parseRawTargetDirs :: (MonadIO m, MonadThrow m) => Path Abs Dir -- ^ current directory -> Map PackageName LocalPackageView -> Text -> m (Either Text [(RawInput, RawTarget 'HasIdents)]) parseRawTargetDirs root locals t = case parseRawTarget t of Just rt -> return $ Right [(ri, rt)] Nothing -> do mdir <- resolveDirMaybe root $ T.unpack t case mdir of Nothing -> return $ Left $ "Directory not found: " `T.append` t Just dir -> case mapMaybe (childOf dir) $ Map.toList locals of [] -> return $ Left $ "No local directories found as children of " `T.append` t names -> return $ Right $ map ((ri, ) . RTPackage) names where ri = RawInput t childOf dir (name, lpv) = if (dir == lpvRoot lpv || isParentOf dir (lpvRoot lpv)) && not (lpvExtraDep lpv) then Just name else Nothing data SimpleTarget = STUnknown | STNonLocal | STLocalComps !(Set NamedComponent) | STLocalAll deriving (Show, Eq, Ord) resolveIdents :: Map PackageName Version -- ^ snapshot -> Map PackageName Version -- ^ extra deps -> Map PackageName LocalPackageView -> (RawInput, RawTarget 'HasIdents) -> Either Text ((RawInput, RawTarget 'NoIdents), Map PackageName Version) resolveIdents _ _ _ (ri, RTPackageComponent x y) = Right ((ri, RTPackageComponent x y), Map.empty) resolveIdents _ _ _ (ri, RTComponent x) = Right ((ri, RTComponent x), Map.empty) resolveIdents _ _ _ (ri, RTPackage x) = Right ((ri, RTPackage x), Map.empty) resolveIdents snap extras locals (ri, RTPackageIdentifier (PackageIdentifier name version)) = case mfound of Just (foundPlace, foundVersion) | foundVersion /= version -> Left $ T.pack $ concat [ "Specified target version " , versionString version , " for package " , packageNameString name , " does not match " , foundPlace , " version " , versionString foundVersion ] _ -> Right ( (ri, RTPackage name) , case mfound of -- Add to extra deps since we didn't have it already Nothing -> Map.singleton name version -- Already had it, don't add to extra deps Just _ -> Map.empty ) where mfound = mlocal <|> mextra <|> msnap mlocal = (("local", ) . lpvVersion) <$> Map.lookup name locals mextra = ("extra-deps", ) <$> Map.lookup name extras msnap = ("snapshot", ) <$> Map.lookup name snap resolveRawTarget :: Map PackageName Version -- ^ snapshot -> Map PackageName Version -- ^ extra deps -> Map PackageName LocalPackageView -> (RawInput, RawTarget 'NoIdents) -> Either Text (PackageName, (RawInput, SimpleTarget)) resolveRawTarget snap extras locals (ri, rt) = go rt where go (RTPackageComponent name ucomp) = case Map.lookup name locals of Nothing -> Left $ T.pack $ "Unknown local package: " ++ packageNameString name Just lpv -> case ucomp of ResolvedComponent comp | comp `Set.member` lpvComponents lpv -> Right (name, (ri, STLocalComps $ Set.singleton comp)) | otherwise -> Left $ T.pack $ concat [ "Component " , show comp , " does not exist in package " , packageNameString name ] UnresolvedComponent comp -> case filter (isCompNamed comp) $ Set.toList $ lpvComponents lpv of [] -> Left $ T.concat [ "Component " , comp , " does not exist in package " , T.pack $ packageNameString name ] [x] -> Right (name, (ri, STLocalComps $ Set.singleton x)) matches -> Left $ T.concat [ "Ambiguous component name " , comp , " for package " , T.pack $ packageNameString name , ": " , T.pack $ show matches ] go (RTComponent cname) = let allPairs = concatMap (\(name, lpv) -> map (name,) $ Set.toList $ lpvComponents lpv) (Map.toList locals) in case filter (isCompNamed cname . snd) allPairs of [] -> Left $ "Could not find a component named " `T.append` cname [(name, comp)] -> Right (name, (ri, STLocalComps $ Set.singleton comp)) matches -> Left $ T.concat [ "Ambiugous component name " , cname , ", matches: " , T.pack $ show matches ] go (RTPackage name) = case Map.lookup name locals of Just _lpv -> Right (name, (ri, STLocalAll)) Nothing -> case Map.lookup name extras of Just _ -> Right (name, (ri, STNonLocal)) Nothing -> case Map.lookup name snap of Just _ -> Right (name, (ri, STNonLocal)) Nothing -> Right (name, (ri, STUnknown)) isCompNamed :: Text -> NamedComponent -> Bool isCompNamed _ CLib = False isCompNamed t1 (CExe t2) = t1 == t2 isCompNamed t1 (CTest t2) = t1 == t2 isCompNamed t1 (CBench t2) = t1 == t2 simplifyTargets :: [(PackageName, (RawInput, SimpleTarget))] -> ([Text], Map PackageName SimpleTarget) simplifyTargets = mconcat . map go . Map.toList . Map.fromListWith (++) . fmap (second return) where go :: (PackageName, [(RawInput, SimpleTarget)]) -> ([Text], Map PackageName SimpleTarget) go (_, []) = error "Stack.Build.Target.simplifyTargets: the impossible happened" go (name, [(_, st)]) = ([], Map.singleton name st) go (name, pairs) = case partitionEithers $ map (getLocalComp . snd) pairs of ([], comps) -> ([], Map.singleton name $ STLocalComps $ Set.unions comps) _ -> let err = T.pack $ concat [ "Overlapping targets provided for package " , packageNameString name , ": " , show $ map (unRawInput . fst) pairs ] in ([err], Map.empty) getLocalComp (STLocalComps comps) = Right comps getLocalComp _ = Left () -- | Need targets, e.g. `stack build` or allow none? data NeedTargets = NeedTargets | AllowNoTargets parseTargets :: (MonadThrow m, MonadIO m) => NeedTargets -- ^ need at least one target -> Bool -- ^ using implicit global project? -> Map PackageName Version -- ^ snapshot -> Map PackageName Version -- ^ extra deps -> Map PackageName LocalPackageView -> Path Abs Dir -- ^ current directory -> [Text] -- ^ command line targets -> m (Map PackageName Version, Map PackageName SimpleTarget) parseTargets needTargets implicitGlobal snap extras locals currDir textTargets' = do let textTargets = if null textTargets' then map (T.pack . packageNameString) $ Map.keys $ Map.filter (not . lpvExtraDep) locals else textTargets' erawTargets <- mapM (parseRawTargetDirs currDir locals) textTargets let (errs1, rawTargets) = partitionEithers erawTargets (errs2, unzip -> (rawTargets', newExtras)) = partitionEithers $ map (resolveIdents snap extras locals) $ concat rawTargets (errs3, targetTypes) = partitionEithers $ map (resolveRawTarget snap extras locals) rawTargets' (errs4, targets) = simplifyTargets targetTypes errs = concat [errs1, errs2, errs3, errs4] if null errs then if Map.null targets then case needTargets of AllowNoTargets -> return (Map.empty, Map.empty) NeedTargets -> throwM $ TargetParseException $ if implicitGlobal then ["The specified targets matched no packages.\nPerhaps you need to run 'stack init'?"] else ["The specified targets matched no packages"] else return (Map.unions newExtras, targets) else throwM $ TargetParseException errs
mathhun/stack
src/Stack/Build/Target.hs
bsd-3-clause
13,119
0
21
4,824
3,187
1,683
1,504
284
12
{-# LANGUAGE TypeFamilies #-} module T5417a where import Data.Kind (Type) class C1 a where data F a :: Type
sdiehl/ghc
testsuite/tests/ghci/scripts/T5417a.hs
bsd-3-clause
118
0
6
29
31
19
12
-1
-1
module Test22 where f = let x = do let y = 45 Just y in x
kmate/HaRe
old/testing/refacSlicing/Test22AST.hs
bsd-3-clause
98
0
13
57
35
17
18
4
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE StandaloneDeriving #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Complex -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : portable -- -- Complex numbers. -- ----------------------------------------------------------------------------- module Data.Complex ( -- * Rectangular form Complex((:+)) , realPart , imagPart -- * Polar form , mkPolar , cis , polar , magnitude , phase -- * Conjugate , conjugate ) where import Data.Typeable import Data.Data (Data) import Foreign (Storable, castPtr, peek, poke, pokeElemOff, peekElemOff, sizeOf, alignment) infix 6 :+ -- ----------------------------------------------------------------------------- -- The Complex type -- | Complex numbers are an algebraic type. -- -- For a complex number @z@, @'abs' z@ is a number with the magnitude of @z@, -- but oriented in the positive real direction, whereas @'signum' z@ -- has the phase of @z@, but unit magnitude. data Complex a = !a :+ !a -- ^ forms a complex number from its real and imaginary -- rectangular components. deriving (Eq, Show, Read, Data, Typeable) -- ----------------------------------------------------------------------------- -- Functions over Complex -- | Extracts the real part of a complex number. realPart :: Complex a -> a realPart (x :+ _) = x -- | Extracts the imaginary part of a complex number. imagPart :: Complex a -> a imagPart (_ :+ y) = y -- | The conjugate of a complex number. {-# SPECIALISE conjugate :: Complex Double -> Complex Double #-} conjugate :: Num a => Complex a -> Complex a conjugate (x:+y) = x :+ (-y) -- | Form a complex number from polar components of magnitude and phase. {-# SPECIALISE mkPolar :: Double -> Double -> Complex Double #-} mkPolar :: Floating a => a -> a -> Complex a mkPolar r theta = r * cos theta :+ r * sin theta -- | @'cis' t@ is a complex value with magnitude @1@ -- and phase @t@ (modulo @2*'pi'@). {-# SPECIALISE cis :: Double -> Complex Double #-} cis :: Floating a => a -> Complex a cis theta = cos theta :+ sin theta -- | The function 'polar' takes a complex number and -- returns a (magnitude, phase) pair in canonical form: -- the magnitude is nonnegative, and the phase in the range @(-'pi', 'pi']@; -- if the magnitude is zero, then so is the phase. {-# SPECIALISE polar :: Complex Double -> (Double,Double) #-} polar :: (RealFloat a) => Complex a -> (a,a) polar z = (magnitude z, phase z) -- | The nonnegative magnitude of a complex number. {-# SPECIALISE magnitude :: Complex Double -> Double #-} magnitude :: (RealFloat a) => Complex a -> a magnitude (x:+y) = scaleFloat k (sqrt (sqr (scaleFloat mk x) + sqr (scaleFloat mk y))) where k = max (exponent x) (exponent y) mk = - k sqr z = z * z -- | The phase of a complex number, in the range @(-'pi', 'pi']@. -- If the magnitude is zero, then so is the phase. {-# SPECIALISE phase :: Complex Double -> Double #-} phase :: (RealFloat a) => Complex a -> a phase (0 :+ 0) = 0 -- SLPJ July 97 from John Peterson phase (x:+y) = atan2 y x -- ----------------------------------------------------------------------------- -- Instances of Complex instance (RealFloat a) => Num (Complex a) where {-# SPECIALISE instance Num (Complex Float) #-} {-# SPECIALISE instance Num (Complex Double) #-} (x:+y) + (x':+y') = (x+x') :+ (y+y') (x:+y) - (x':+y') = (x-x') :+ (y-y') (x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x') negate (x:+y) = negate x :+ negate y abs z = magnitude z :+ 0 signum (0:+0) = 0 signum z@(x:+y) = x/r :+ y/r where r = magnitude z fromInteger n = fromInteger n :+ 0 instance (RealFloat a) => Fractional (Complex a) where {-# SPECIALISE instance Fractional (Complex Float) #-} {-# SPECIALISE instance Fractional (Complex Double) #-} (x:+y) / (x':+y') = (x*x''+y*y'') / d :+ (y*x''-x*y'') / d where x'' = scaleFloat k x' y'' = scaleFloat k y' k = - max (exponent x') (exponent y') d = x'*x'' + y'*y'' fromRational a = fromRational a :+ 0 instance (RealFloat a) => Floating (Complex a) where {-# SPECIALISE instance Floating (Complex Float) #-} {-# SPECIALISE instance Floating (Complex Double) #-} pi = pi :+ 0 exp (x:+y) = expx * cos y :+ expx * sin y where expx = exp x log z = log (magnitude z) :+ phase z sqrt (0:+0) = 0 sqrt z@(x:+y) = u :+ (if y < 0 then -v else v) where (u,v) = if x < 0 then (v',u') else (u',v') v' = abs y / (u'*2) u' = sqrt ((magnitude z + abs x) / 2) sin (x:+y) = sin x * cosh y :+ cos x * sinh y cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y) tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy)) where sinx = sin x cosx = cos x sinhy = sinh y coshy = cosh y sinh (x:+y) = cos y * sinh x :+ sin y * cosh x cosh (x:+y) = cos y * cosh x :+ sin y * sinh x tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx) where siny = sin y cosy = cos y sinhx = sinh x coshx = cosh x asin z@(x:+y) = y':+(-x') where (x':+y') = log (((-y):+x) + sqrt (1 - z*z)) acos z = y'':+(-x'') where (x'':+y'') = log (z + ((-y'):+x')) (x':+y') = sqrt (1 - z*z) atan z@(x:+y) = y':+(-x') where (x':+y') = log (((1-y):+x) / sqrt (1+z*z)) asinh z = log (z + sqrt (1+z*z)) acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1))) atanh z = 0.5 * log ((1.0+z) / (1.0-z)) instance Storable a => Storable (Complex a) where sizeOf a = 2 * sizeOf (realPart a) alignment a = alignment (realPart a) peek p = do q <- return $ castPtr p r <- peek q i <- peekElemOff q 1 return (r :+ i) poke p (r :+ i) = do q <-return $ (castPtr p) poke q r pokeElemOff q 1 i
jtojnar/haste-compiler
libraries/ghc-7.10/base/Data/Complex.hs
bsd-3-clause
7,100
2
14
2,464
2,138
1,130
1,008
124
1
module Amount where import Control.Monad import Control.Applicative import Data.Bits import Data.Word import Data.Binary (Binary(..), Get, putWord8) import Data.Binary.Get (getLazyByteString) import Data.Base58Address (RippleAddress) import Control.Error (readMay) import qualified Data.ByteString.Lazy as LZ import qualified Data.Text as T import Data.Aeson ((.=), (.:)) import qualified Data.Aeson as Aeson import qualified Data.Aeson.Types as Aeson import qualified Data.Attoparsec.Number as Aeson readZ :: (MonadPlus m) => (Read a) => String -> m a readZ = maybe mzero return . readMay data Currency = XRP | Currency (Char,Char,Char) RippleAddress deriving (Eq) instance Show Currency where show XRP = "XRP" show (Currency (a,b,c) adr) = [a,b,c,'/'] ++ show adr instance Binary Currency where get = do allZero <- getLazyByteString 12 currency <- getLazyByteString 3 version <- getLazyByteString 2 reserved <- getLazyByteString 3 issuer <- get when (LZ.any (/=0) allZero) (fail "Bad currency format az") when (LZ.any (/=0) version) (fail "Bad currency format ver") when (LZ.any (/=0) reserved) (fail "Bad currency format res") -- Spec says ASCII let [a,b,c] = map (toEnum.fromIntegral) $ LZ.unpack currency return $ Currency (a,b,c) issuer put XRP = fail "XRP does not get encoded as a currency specifier." put (Currency (a,b,c) issuer) = do replicateM_ 12 (putWord8 0) putWord8 $ fromIntegral $ fromEnum a putWord8 $ fromIntegral $ fromEnum b putWord8 $ fromIntegral $ fromEnum c replicateM_ 2 (putWord8 0) replicateM_ 3 (putWord8 0) put issuer data Amount = Amount Rational Currency deriving (Eq) instance Show Amount where show (Amount a c) = show (realToFrac a :: Double) ++ "/" ++ show c instance Aeson.ToJSON Amount where toJSON (Amount v XRP) = Aeson.toJSON $ show (floor (v * 1000000) :: Integer) toJSON (Amount v (Currency (a,b,c) issuer)) = Aeson.object [ T.pack "value" .= show (realToFrac v :: Double), T.pack "currency" .= [a,b,c], T.pack "issuer" .= show issuer ] instance Aeson.FromJSON Amount where parseJSON (Aeson.Object o) = do amountVal <- o .: T.pack "value" amount <- realToFrac <$> case amountVal of Aeson.Number n -> Aeson.parseJSON (Aeson.Number n) :: Aeson.Parser Double Aeson.String s -> readZ (T.unpack s) :: Aeson.Parser Double _ -> fail "No valid amount" currency <- o .: T.pack "currency" guard (length currency == 3 && currency /= "XRP") issuer <- readZ =<< o .: T.pack "issuer" let [a,b,c] = currency return $ Amount amount (Currency (a,b,c) issuer) parseJSON (Aeson.Number (Aeson.I n)) = pure $ Amount (fromIntegral n) XRP parseJSON (Aeson.Number (Aeson.D n)) = pure $ Amount (realToFrac $ floor $ 1000000 * n) XRP parseJSON (Aeson.String s) = case T.find (=='.') s of Nothing -> (Amount . realToFrac) <$> (readZ (T.unpack s) :: Aeson.Parser Integer) <*> pure XRP Just _ -> (\x -> Amount (realToFrac $ x * 1000000)) <$> (readZ (T.unpack s) :: Aeson.Parser Double) <*> pure XRP parseJSON _ = fail "Invalid amount" instance Binary Amount where get = do value <- get :: Get Word64 if testBit value 63 then (flip Amount <$> get <*>) $ pure $ case (clearBit (clearBit value 63) 62 `shiftR` 54, value .&. 0x003FFFFFFFFFFFFF) of (0,0) -> 0 (e,m) -> (if testBit value 62 then 1 else -1) * fromIntegral m * (10 ^^ (fromIntegral e - 97)) else return $ (`Amount` XRP) $ (if testBit value 62 then 1 else -1) * (fromIntegral (clearBit value 62) / 1000000) put (Amount value XRP) = put $ (if value >= 0 then (`setBit` 62) else id) drops where drops = floor $ abs $ value * 1000000 :: Word64 put (Amount 0 currency) = do put (setBit (0 :: Word64) 63) put currency put (Amount value currency) | value > 0 = put (setBit encoded 62) >> put currency | otherwise = put encoded >> put currency where encoded = setBit ((e8 `shiftL` 54) .|. m64) 63 e8 = fromIntegral (fromIntegral (e+97) :: Word8) -- to get the bits m64 = fromIntegral m :: Word64 (m,e) = until ((>= man_min_value) . fst) (\(m,e) -> (m*10,e-1)) $ until ((<= man_max_value) . fst) (\(m,e) -> (m`div`10,e+1)) (abs $ floor (value * (10 ^^ 80)), -80) man_max_value :: Integer man_max_value = 9999999999999999 man_min_value :: Integer man_min_value = 1000000000000000
singpolyma/localripple
Amount.hs
isc
4,344
42
18
868
1,938
1,013
925
-1
-1
import Pitch.Deck import Pitch.Card import Pitch.Game import Pitch.Network import Pitch.Players import System.Random import Control.Monad.State import Control.Monad import Control.Concurrent import System.IO import Network main = do gen <- getStdGen (netPlayer1, g') <- mkNetworkPlayer gen "net1" (netPlayer2, g'') <- mkNetworkPlayer g' "net2" (netPlayer3, g''') <- mkNetworkPlayer g'' "net3" let gameState = mkGameState g''' [mkPlayer "John", netPlayer1, netPlayer2, netPlayer3] runStateT playGame gameState
benweitzman/Pitch
src/Pitch.hs
mit
527
1
12
77
161
84
77
18
1
module GHCJS.DOM.SQLStatementErrorCallback ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SQLStatementErrorCallback.hs
mit
55
0
3
7
10
7
3
1
0
#!/usr/bin/env runhaskell -- Usage: ./Haskeleton.hs New.Module module Haskeleton (main) where import Data.List (groupBy, isInfixOf) import Data.Monoid ((<>)) import System.Directory (createDirectoryIfMissing) import System.Environment (getArgs) import System.FilePath (joinPath, takeDirectory, (<.>)) main :: IO () main = do ms <- getArgs mapM_ createDirectories ms mapM_ writeFiles ms mapM_ updateFiles ms where createDirectories m = do createBenchmarkDirectory m createLibraryDirectory m createTestSuiteDirectory m writeFiles m = do writeBenchmarkFile m writeLibraryFile m writeTestSuiteFile m updateFiles m = do updateCabal m updateCriterion m updateLibrary m -- createDirectory :: FilePath -> IO () createDirectory = createDirectoryIfMissing True . takeDirectory path :: FilePath -> String -> String -> FilePath path d s m = joinPath (d : parts (m <> s)) <.> "hs" parts :: String -> [String] parts = split '.' placeholder :: String placeholder = "New.Module" pragma :: String pragma = "-- HASKELETON: " replace :: (Eq a) => [a] -> [a] -> [a] -> [a] replace [] _ _ = [] replace xs@(h : t) old new = if a == old then new <> replace b old new else h : replace t old new where (a, b) = splitAt (length old) xs split :: (Eq a) => a -> [a] -> [[a]] split x xs = fmap (dropWhile (== x)) (groupBy (const (x /=)) xs) updateFile :: FilePath -> String -> IO () updateFile p m = do contents <- readFile p seq (length contents) (return ()) writeFile p (unlines (go =<< lines contents)) where go line = if pragma `isInfixOf` line then [replace (replace line pragma "") placeholder m, line] else [line] -- Benchmark createBenchmarkDirectory :: String -> IO () createBenchmarkDirectory = createDirectory . benchmarkPath benchmarkDirectory :: String benchmarkDirectory = "benchmark" benchmarkPath :: String -> FilePath benchmarkPath = path benchmarkDirectory benchmarkSuffix benchmarkTemplate :: String -> String benchmarkTemplate m = unlines [ "module " <> m <> "Bench (benchmarks) where" , "" , "import " <> m <> " ()" , "" , "import Criterion" , "" , "benchmarks :: [Benchmark]" , "benchmarks = []" ] benchmarkSuffix :: String benchmarkSuffix = "Bench" writeBenchmarkFile :: String -> IO () writeBenchmarkFile m = writeFile (benchmarkPath m) (benchmarkTemplate m) -- Cabal cabalPath :: FilePath cabalPath = "gruber.cabal" updateCabal :: String -> IO () updateCabal = updateFile cabalPath -- Criterion criterionPath :: FilePath criterionPath = benchmarkPath "" updateCriterion :: String -> IO () updateCriterion = updateFile criterionPath -- Library createLibraryDirectory :: String -> IO () createLibraryDirectory = createDirectory . libraryPath libraryDirectory :: String libraryDirectory = "library" libraryPath :: String -> FilePath libraryPath = path libraryDirectory librarySuffix libraryTemplate :: String -> String libraryTemplate m = unlines [ "-- | TODO" , "module " <> m <> " () where" ] librarySuffix :: String librarySuffix = "" updateLibrary :: String -> IO () updateLibrary = updateFile (libraryPath "Gruber") writeLibraryFile :: String -> IO () writeLibraryFile m = writeFile (libraryPath m) (libraryTemplate m) -- Test Suite createTestSuiteDirectory :: String -> IO () createTestSuiteDirectory = createDirectory . testSuitePath testSuiteDirectory :: String testSuiteDirectory = "test-suite" testSuitePath :: String -> FilePath testSuitePath = path testSuiteDirectory testSuiteSuffix testSuiteTemplate :: String -> String testSuiteTemplate m = unlines [ "module " <> m <> "Spec (spec) where" , "" , "import " <> m <> " ()" , "" , "import Test.Hspec" , "" , "spec :: Spec" , "spec = it \"is\" pending" ] testSuiteSuffix :: String testSuiteSuffix = "Spec" writeTestSuiteFile :: String -> IO () writeTestSuiteFile m = writeFile (testSuitePath m) (testSuiteTemplate m)
MarcoSero/gruber
Haskeleton.hs
mit
4,056
0
12
854
1,220
642
578
115
2
-- Get initials from person name -- https://www.codewars.com/kata/57b56af6b69bfcffb80000d7 module Initials where toInitials :: String -> String toInitials = unwords . map ((: ".") . head) . words
gafiatulin/codewars
src/7 kyu/Initials.hs
mit
199
0
10
30
42
25
17
3
1
-- | Implementation of an execution environment that uses /docker/. module B9.Docker ( Docker (..), ) where import B9.B9Config ( dockerConfigs, getB9Config, ) import B9.B9Config.Docker as X import B9.Container import B9.DiskImages import B9.ShellScript import Control.Lens (view) newtype Docker = Docker DockerConfig instance Backend Docker where getBackendConfig _ = fmap Docker . view dockerConfigs <$> getB9Config -- supportedImageTypes :: proxy config -> [ImageType] supportedImageTypes _ = [Raw] -- runInEnvironment :: -- forall e. -- (Member BuildInfoReader e, CommandIO e) => -- config -> -- ExecEnv -> -- Script -> -- Eff e Bool runInEnvironment (Docker _dcfg) _env scriptIn = do if emptyScript scriptIn then return True else do error "TODO" -- where -- setUp = do -- buildId <- getBuildId -- buildBaseDir <- getBuildDir -- uuid <- randomUUID -- let scriptDirHost = buildDir </> "init-script" -- scriptDirGuest = "/" ++ buildId -- domainFile = buildBaseDir </> uuid' <.> domainConfig -- mkDomain = -- createDomain cfgIn env buildId uuid' scriptDirHost scriptDirGuest -- uuid' = printf "%U" uuid -- setupEnv = -- Begin -- [ Run "export" ["HOME=/root"], -- Run "export" ["USER=root"], -- Run "source" ["/etc/profile"] -- ] -- script = Begin [setupEnv, scriptIn, successMarkerCmd scriptDirGuest] -- buildDir = buildBaseDir </> uuid' -- liftIO $ do -- createDirectoryIfMissing True scriptDirHost -- writeSh (scriptDirHost </> initScript) script -- domain <- mkDomain -- writeFile domainFile domain -- return $ Context scriptDirHost uuid domainFile cfgIn
sheyll/b9-vm-image-builder
src/lib/B9/Docker.hs
mit
1,903
0
11
574
187
119
68
19
0
module Kd2nTree where class Point p where sel :: Int -> p -> Double dim :: p -> Int child :: p -> p -> [Int] -> Int child e1 e2 coords = value2 $ zipWith (>) coordse1 coordse2 where (coordse1, coordse2) = (map (sel' e1) coords, map (sel' e2) coords) sel' = flip sel value2 = foldl hornerBin 0 hornerBin acc b | b = 2*acc + 1 | otherwise = 2*acc dist :: p -> p -> Double dist = sqrt .: dist2 where (.:) = (.).(.) list2Point :: [Double] -> p ptrans :: [Double] -> p -> p ptrans l = list2Point . zipWith (+) l . coordinates pscale :: Double -> p -> p pscale x = list2Point . map (* x) . coordinates coordinates :: Point p => p -> [Double] coordinates p = let dimensions = dim p in [ sel i p | i <- [1..dimensions] ] dist2 :: Point p => p -> p -> Double dist2 p p' = sum [ (c - c')^2 | (c, c') <- coordinates p `zip` coordinates p' ] newtype Point3d = Point3d (Double, Double, Double) deriving (Eq, Ord) instance Point Point3d where sel index (Point3d (x,y,z)) | index == 1 = x | index == 2 = y | index == 3 = z dim _ = 3 list2Point [x,y,z] = Point3d (x,y,z) instance Show Point3d where show (Point3d p) = show p data Kd2nTree t = Node t [Int] [Kd2nTree t] | Empty instance (Point p, Eq p) => Eq (Kd2nTree p) where t1 == t2 = lt1 == lt2 && all (contains t2) elemst1 where (elemst1, elemst2) = (elems t1, elems t2); (lt1, lt2) = (length elemst1, length elemst2) instance (Show t) => Show (Kd2nTree t) where show Empty = "" show (Node elem distr childs) = showNode elem distr ++ showChilds "" childs where showNode elem distr = show elem ++ " " ++ show distr showChilds indent childs = concatMap (show' indent) (map show [0..] `zip` childs) show' _ (_,Empty) = "" show' indent (childIndex, (Node elem distr childs)) = "\n " ++ indent ++ "<" ++ childIndex ++ ">" ++ showNode elem distr ++ showChilds (" " ++ indent) childs insert :: (Point p, Eq p) => Kd2nTree p -> p -> [Int] -> Kd2nTree p insert Empty point distr = Node point distr [] insert t@(Node point distr childs) point' pdistr | point == point' = t | otherwise = Node point distr insert' where childIndex = child point' point distr ldiff = childIndex - (length childs) insert' | ldiff >= 0 = childs ++ (take ldiff (repeat Empty)) ++ [Node point' pdistr []] | otherwise = left ++ insert subtree point' pdistr : right where (left, subtree:right) = splitAt childIndex childs build :: (Point p, Eq p) => [(p,[Int])] -> Kd2nTree p build list = foldl (\tree (point,distr) -> insert tree point distr) Empty list buildIni :: (Point p, Eq p) => [([Double],[Int])] -> Kd2nTree p buildIni list = build [ (list2Point pointl, distr) | (pointl,distr) <- list ] get_all :: Kd2nTree p -> [(p,[Int])] get_all Empty = [] get_all (Node elem distr childs) = (elem, distr) : (concatMap get_all childs) elems :: Kd2nTree p -> [p] elems tree = [ elem | (elem,_) <- get_all tree ] remove :: (Point p, Eq p) => Kd2nTree p -> p -> Kd2nTree p remove Empty _ = Empty remove t@(Node point distr childs) point' | point == point' = build $ tail $ get_all t | childIndex >= (length childs) = t | otherwise = Node point distr (left ++ remove subtree point' : right) where childIndex = child point' point distr (left, subtree:right) = splitAt childIndex childs contains :: (Point p, Eq p) => Kd2nTree p -> p -> Bool contains Empty _ = False contains (Node point distr childs) point' | point == point' = True | childIndex >= (length childs) = False | otherwise = childs !! childIndex `contains` point' where childIndex = child point' point distr nearest :: Point p => Kd2nTree p -> p -> p nearest t p = fst $ argvalmin (dist2 p) (elems t) where argvalmin f (x:xs) = foldl (minDecider f) (x, f x) xs minDecider f m@(amin, vmin) anew | vmin < vnew = m | otherwise = (anew, vnew) where vnew = f anew allinInterval :: Ord p => Kd2nTree p -> p -> p -> [p] allinInterval t pl pr = qsort [ p | p <- elems t, pl <= p, p <= pr ] where qsort [] = [] qsort (x:xs) = (qsort lh) ++ [x] ++ (qsort rh) where lh = [ y | y <- xs, y < x ] rh = [ y | y <- xs, y >= x ] kdmap :: (p -> q) -> Kd2nTree p -> Kd2nTree q kdmap _ Empty = Empty kdmap f (Node elem distr childs) = Node (f elem) distr [ kdmap f s | s <- childs ] translation :: Point p => [Double] -> Kd2nTree p -> Kd2nTree p translation = kdmap . ptrans scale :: Point p => Double -> Kd2nTree p -> Kd2nTree p scale = kdmap . pscale
albertsgrc/practica-lp-kd2ntrees
Kd2nTree.hs
mit
4,858
1
13
1,438
2,233
1,148
1,085
90
2
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE FlexibleInstances #-} {-# CFILES test.c xgboost_wrapper.cpp #-} import Xgboost import Xgboost.Foreign import System.IO.Unsafe import Foreign.C import Foreign.Storable import Foreign.Ptr main :: IO () main = do check_trivial --check_xgboost_read -- Stolen: https://github.com/haskell/pretty/blob/master/tests/Test.hs myAssert :: String -> Bool -> IO () myAssert msg b = putStrLn $ (if b then "Ok, passed " else "Failed test:\n ") ++ msg check_trivial = do putStrLn " = Trivial Tests = " myAssert "Trivial test" True -- --check_xgboost_read = do -- let dat = unsafePerformIO $ (new :: IO (Ptr CFloat)) -- let nrow = 1 :: CULong -- let missing = 0.5 :: CFloat -- let dmh = unsafePerformIO $ (new :: IO (Ptr (Ptr ()))) -- let mat = xgboostMatrixCreateFromMat dat nrow nrow missing dmh -- mat -- let r = unsafePerformIO $ (new :: IO (Ptr CULong)) -- let rs = xgboostMatrixNumRow (unsafePerformIO $ peek dmh) r -- rs -- myAssert "Number of rows is 1" $ (==) (1 :: CULong) $ unsafePerformIO $ peek r
robertzk/xgboost.hs
tests/Test.hs
mit
1,074
0
8
196
131
77
54
16
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE Rank2Types #-} module Graphics.Badge.Barrier.Internal ( BadgeConfig(..) , Badge(..) , makeBadge , Lens' , HasLeftColor(..) , HasRightColor(..) ) where import Language.Haskell.TH import Control.Arrow(second, (***)) import Text.Blaze.Svg11(Svg) import qualified Data.Text as T import qualified Data.HashMap.Strict as S import Graphics.Badge.Barrier.Color advanceDict :: S.HashMap Char Int advanceDict = $( do dat <- runIO $ readFile "data/advance.txt" let convI = litE . integerL . read convC = litE . charL . toEnum . read let kvs = flip map (lines dat) $ tupE . (\(a,b) -> [a,b]) . (convC *** convI) . second tail . break (== '\t') [|S.fromList $(listE kvs)|] ) advance :: Char -> Int advance c = S.lookupDefault 11 c advanceDict measureText :: T.Text -> Int measureText = T.foldl' (\i c -> advance c + i) 0 data BadgeConfig = BadgeConfig { textLeft :: T.Text , textRight :: T.Text , widthLeft :: Int , widthRight :: Int } badge' :: T.Text -> T.Text -> BadgeConfig badge' l r = BadgeConfig l r (measureText l + 10) (measureText r + 10) makeBadge :: Badge b => b -> T.Text -> T.Text -> Svg makeBadge b l r = badge b (badge' l r) class Badge a where badge :: a -> BadgeConfig -> Svg type Lens' s a = forall f. Functor f => (a -> f a) -> s -> f s class HasLeftColor a where left :: Lens' a Color class HasRightColor a where right :: Lens' a Color
philopon/barrier
src/Graphics/Badge/Barrier/Internal.hs
mit
1,515
0
19
369
567
313
254
43
1
{-| Description : Nix-relevant interfaces to NaCl signatures. -} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module System.Nix.Internal.Signature where import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.Coerce (coerce) import Crypto.Saltine.Core.Sign (PublicKey) import Crypto.Saltine.Class (IsEncoding(..)) import qualified Crypto.Saltine.Internal.ByteSizes as NaClSizes -- | A NaCl signature. newtype Signature = Signature ByteString deriving (Eq, Ord) instance IsEncoding Signature where decode s | BS.length s == NaClSizes.sign = Just (Signature s) | otherwise = Nothing encode = coerce -- | A detached NaCl signature attesting to a nix archive's validity. data NarSignature = NarSignature { -- | The public key used to sign the archive. publicKey :: PublicKey , -- | The archive's signature. sig :: Signature } deriving (Eq, Ord)
shlevy/hnix-store
hnix-store-core/src/System/Nix/Internal/Signature.hs
mit
901
0
11
146
186
112
74
18
0