code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-| Module : Language.SAL Description : Public API for sal-lang, a package for representing and generating SAL models and syntax. Copyright : (c) Galois Inc, 2015 License : MIT Maintainer : Benjamin F Jones <[email protected]> Stability : experimental Portability : Yes See "Language.SAL.Syntax" for details on the syntax representation. TODO -- better package-wide description here -} module Language.SAL (module X) where import Language.SAL.Syntax as X import Language.SAL.Pretty as X import Language.SAL.Helpers as X
GaloisInc/language-sal
src/Language/SAL.hs
mit
554
0
4
107
37
27
10
4
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# OPTIONS_GHC -Wno-orphans #-} module ConfigSpec ( configSpec ) where import DarkSky.App.Config import DarkSky.Types (Coordinate(..), Degrees) import Data.Aeson (decode) import qualified Data.ByteString.Lazy as BL import Data.Monoid ((<>)) import Data.Scientific (fromFloatDigits) import Test.Hspec import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes import Text.RawString.QQ instance EqProp Coordinate where (=-=) = eq instance EqProp Config where (=-=) = eq configSpec :: IO () configSpec = do hspec $ do describe "Config" $ describe "FromJSON" $ do it "full" $ decode sampleFullConfigJSON `shouldBe` Just sampleFullConfig it "empty" $ decode sampleEmptyConfigJSON `shouldBe` Just (mempty :: Config) describe "Monoid" $ do it "mappends full onto empty" $ mempty <> sampleFullConfig `shouldBe` sampleFullConfig it "mappends empty onto full" $ sampleFullConfig <> mempty `shouldBe` sampleFullConfig it "mappends full onto full" $ Config (Just "key456") (Just (Coordinate 3 4)) <> sampleFullConfig `shouldBe` sampleFullConfig quickBatch $ monoid (undefined :: Config) instance Arbitrary Config where arbitrary = Config <$> arbitrary <*> arbitrary instance Arbitrary Coordinate where arbitrary = Coordinate <$> arbitraryDegrees <*> arbitraryDegrees arbitraryDegrees :: Gen Degrees arbitraryDegrees = fromFloatDigits <$> (arbitrary :: Gen Double) sampleFullConfigJSON :: BL.ByteString sampleFullConfigJSON = [r|{ "key": "key123", "latitude": 1, "longitude": 2 }|] sampleFullConfig :: Config sampleFullConfig = Config { key = Just "key123" , coordinate = Just (Coordinate 1 2) } sampleEmptyConfigJSON :: BL.ByteString sampleEmptyConfigJSON = "{}"
peterstuart/dark-sky
test/ConfigSpec.hs
mit
1,944
0
20
419
468
258
210
54
1
module Text.Noise.Parser ( parse , ParseError ) where import Control.Applicative import Text.ParserCombinators.Parsec (ParseError, sepBy1, eof, option) import Text.Parsec.Prim (try, (<?>)) import Text.Parsec.Pos (initialPos) import qualified Text.Parsec.Expr as Expr import qualified Text.Parsec.Prim (runParser) import Text.Noise.Parser.Token (Parser, ranged) import qualified Text.Noise.Parser.Token as Token import qualified Text.Noise.Parser.AST as AST parse :: String -> String -> Either ParseError AST.SourceFile parse = Text.Parsec.Prim.runParser sourceFile (initialPos "" ) qualifiedIdentifier :: Parser AST.QualifiedIdentifier qualifiedIdentifier = ranged (AST.QualifiedIdentifier <$> sepBy1 Token.identifier Token.dot) floatLiteral :: Parser AST.Expression floatLiteral = ranged (AST.FloatLiteral <$> Token.number) colorLiteral :: Parser AST.Expression colorLiteral = ranged (AST.ColorLiteral <$> Token.colorLiteral) stringLiteral :: Parser AST.Expression stringLiteral = ranged (AST.StringLiteral <$> Token.stringLiteral) functionCall :: Parser AST.Expression functionCall = ranged $ AST.FunctionCall <$> qualifiedIdentifier <*> option [] (Token.parens (Token.commaSeparated argument)) <*> option Nothing (Just <$> block) block :: Parser AST.Block block = ranged $ AST.Block <$> reserved "with" <*> many statement <*> reserved "end" operator :: AST.OperatorFunction -> Parser AST.Operator operator op = ranged $ do Token.reservedOp str return (AST.Operator op) where str = case op of AST.Add -> "+" AST.Sub -> "-" AST.Mul -> "*" AST.Div -> "/" expression :: Parser AST.Expression expression = Expr.buildExpressionParser opTable term where opTable = [ [prefix AST.Sub] , [infixLeft AST.Mul, infixLeft AST.Div] , [infixLeft AST.Add, infixLeft AST.Sub] ] infixLeft op = Expr.Infix (AST.InfixOperation <$> operator op) Expr.AssocLeft prefix op = Expr.Prefix (AST.PrefixOperation <$> operator op) term = colorLiteral <|> floatLiteral <|> stringLiteral <|> functionCall <|> Token.parens expression <?> "expression" expressionStatement :: Parser AST.Statement expressionStatement = AST.ExpressionStatement <$> expression argumentPrototype :: Parser AST.ArgumentPrototype argumentPrototype = ranged (AST.RequiredArgumentPrototype <$> Token.identifier) functionPrototype :: Parser AST.FunctionPrototype functionPrototype = ranged $ AST.FunctionPrototype <$> qualifiedIdentifier <*> option [] (Token.parens (Token.commaSeparated argumentPrototype)) reserved :: String -> Parser AST.Reserved reserved str = ranged $ Token.reserved str >> return (AST.Reserved str) functionDefStatement :: Parser AST.Statement functionDefStatement = ranged $ AST.DefinitionStatement <$> reserved "let" <*> functionPrototype <* Token.symbol "=" <*> expression statement :: Parser AST.Statement statement = functionDefStatement <|> expressionStatement <?> "statement" keywordArgument :: Parser AST.Argument keywordArgument = ranged $ AST.KeywordArgument <$> try (Token.identifier <* Token.symbol ":") <*> expression positionalArgument :: Parser AST.Argument positionalArgument = AST.PositionalArgument <$> expression argument :: Parser AST.Argument argument = keywordArgument <|> positionalArgument <?> "argument" sourceFile :: Parser AST.SourceFile sourceFile = do Token.whiteSpace ast <- ranged (AST.SourceFile <$> many statement) eof return ast
brow/noise
src/Text/Noise/Parser.hs
mit
3,577
0
12
624
1,008
527
481
90
4
{-# LANGUAGE OverloadedStrings #-} ---------------------------------- -- | There are two ways in which to use this module. -- -- The first is to use the renderer directly with the pandoc API. A -- very simple program to render the API documentation as a mediawiki -- document might look as follows. -- -- > import Text.Pandoc -- > import Servant.Docs.Pandoc -- > import Servant.Docs -- > import Data.Default (def) -- > -- > myApi :: Proxy MyAPI -- > myApi = Proxy -- > -- > writeDocs :: API -> IO () -- > writeDocs api = writeFile "api.mw" (writeMediaWiki def (pandoc api)) -- -- The second approach is to use `makeFilter` to make a filter which can be -- used directly with pandoc from the command line. This filter will just -- append the API documentation to the end of the document. -- Example usage -- -- > -- api.hs -- > main :: IO () -- > main = makeFilter (docs myApi) -- -- >> pandoc -o api.pdf --filter=api.hs manual.md -- -- A more sophisticated filter can be used to actually convert -- introduction and note bodies into Markdown for pandoc to be able to -- process: -- -- > import Data.Monoid (mconcat, (<>)) -- > import Servant.Docs.Pandoc (pandoc) -- > import Text.Pandoc (readMarkdown) -- > import Text.Pandoc.JSON (Block(Para, Plain), Inline(Str), Pandoc(Pandoc), -- > toJSONFilter) -- > import Text.Pandoc.Options (def) -- > import Text.Pandoc.Walk (walkM) -- > -- > main :: IO () -- > main = toJSONFilter append -- > where -- > append :: Pandoc -> Pandoc -- > append = (<> mconcat (walkM parseMarkdown (pandoc myApi))) -- > -- > parseMarkdown :: Block -> [Block] -- > parseMarkdown bl = case bl of -- > Para [Str str] -> toMarkdown str -- > Plain [Str str] -> toMarkdown str -- > _ -> [bl] -- > where -- > toMarkdown = either (const [bl]) unPandoc . readMarkdown def -- > -- > unPandoc (Pandoc _ bls) = bls module Servant.Docs.Pandoc ( pandoc , pandocWith , makeFilter ) where import Servant.Docs (API, Action, DocAuthentication, DocCapture, DocNote, DocQueryParam, Endpoint, ParamKind(Flag, List), RenderingOptions, Response, ShowContentTypes(AllContentTypes, FirstContentType), apiEndpoints, apiIntros, authDataRequired, authInfo, authIntro, capDesc, capSymbol, captures, defRenderingOptions, headers, introBody, introTitle, method, noteBody, noteTitle, notes, notesHeading, paramDesc, paramKind, paramName, paramValues, params, path, requestExamples, respBody, respStatus, respTypes, response, responseExamples, rqbody, rqtypes) import Control.Lens (mapped, view, (%~), (^.)) import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy.Char8 as B import Data.CaseInsensitive (foldedCase) import Data.Foldable (fold, foldMap) import qualified Data.HashMap.Strict as HM import Data.List (sort) import Data.List.NonEmpty (NonEmpty((:|)), groupWith) import qualified Data.List.NonEmpty as NE import Data.Maybe (isJust) import Data.Monoid (mappend, mconcat, mempty, (<>)) import Data.String.Conversions (convertString) import Data.Text (Text, unpack) import qualified Data.Text as T import Network.HTTP.Media (MediaType) import qualified Network.HTTP.Media as M import Text.Pandoc.Builder (Blocks, Inlines) import qualified Text.Pandoc.Builder as B import Text.Pandoc.Definition (Pandoc) import Text.Pandoc.JSON (toJSONFilter) -------------------------------------------------------------------------------- -- | Helper function which can be used to make a pandoc filter which -- appends the generate docs to the end of the document. -- -- This function is exposed for convenience. More experienced authors can -- of course define a more complicated filter to inject the API -- documentation. makeFilter :: API -> IO () makeFilter api = toJSONFilter inject where inject :: Pandoc -> Pandoc inject p = p <> pandoc api -- | Define these values for consistency rather than magic numbers. topLevel, endpointLevel, sectionLevel, subsectionLevel :: Int topLevel = 1 endpointLevel = topLevel + 1 sectionLevel = endpointLevel + 1 subsectionLevel = sectionLevel + 1 -- | Generate a 'Pandoc' representation of a given -- `API`. -- -- This is equivalent to @'pandocWith' 'defRenderingOptions'@. pandoc :: API -> Pandoc pandoc = pandocWith defRenderingOptions -- | Generate a 'Pandoc' representation of a given API using the specified options. -- -- These options allow you to customise aspects such as: -- -- * Choose how many content-types for each request body example are -- shown with 'requestExamples'. -- -- * Choose how many content-types for each response body example -- are shown with 'responseExamples'. -- -- * Whether all 'notes' should be grouped together under a common -- heading with 'notesHeading'. -- -- For example, to only show the first content-type of each example: -- -- @ -- markdownWith ('defRenderingOptions' -- & 'requestExamples' '.~' 'FirstContentType' -- & 'responseExamples' '.~' 'FirstContentType' ) -- myAPI -- @ -- -- @since 0.5.0.0 pandocWith :: RenderingOptions -> API -> Pandoc pandocWith renderOpts api = B.doc $ intros <> mconcat endpoints where printEndpoint :: Endpoint -> Action -> Blocks printEndpoint endpoint action = mconcat [ B.header endpointLevel hdrStr , notesStr (action ^. notes) , authStr (action ^. authInfo) , capturesStr (action ^. captures) , headersStr (action ^. headers) , paramsStr (action ^. params) , rqbodyStrs (action ^. rqtypes) (action ^. rqbody) , responseStr (action ^. response) ] where hdrStr :: Inlines hdrStr = mconcat [ B.str (convertString (endpoint ^. method)) , B.space , B.code (showPath (endpoint ^. path)) ] intros = if null (api ^. apiIntros) then mempty else intros' intros' = foldMap printIntro (api ^. apiIntros) printIntro i = B.header topLevel (B.str $ i ^. introTitle) <> paraStr (i ^. introBody) endpoints = map (uncurry printEndpoint) . sort . HM.toList $ api ^. apiEndpoints notesStr :: [DocNote] -> Blocks notesStr = addHeading . foldMap noteStr where addHeading = maybe id (mappend . B.header sectionLevel . B.str) (renderOpts ^. notesHeading) noteStr :: DocNote -> Blocks noteStr nt = B.header lvl (B.text (nt ^. noteTitle)) <> paraStr (nt ^. noteBody) where lvl = if isJust (renderOpts ^. notesHeading) then subsectionLevel else sectionLevel authStr :: [DocAuthentication] -> Blocks authStr [] = mempty authStr auths = mconcat [ B.header sectionLevel "Authentication" , paraStr (mapped %~ view authIntro $ auths) , B.para "Clients must supply the following data" , B.bulletList (map (B.plain . B.str) (mapped %~ view authDataRequired $ auths)) ] capturesStr :: [DocCapture] -> Blocks capturesStr [] = mempty capturesStr l = B.header sectionLevel "Captures" <> B.bulletList (map captureStr l) captureStr cap = B.plain $ B.emph (B.str $ cap ^. capSymbol) <> ":" <> B.space <> B.text (cap ^. capDesc) headersStr :: [Text] -> Blocks headersStr [] = mempty headersStr l = B.header sectionLevel "Headers" <> B.bulletList (map (B.para . headerStr) l) where headerStr hname = "This endpoint is sensitive to the value of the" <> B.space <> (B.strong . B.str $ unpack hname) <> B.space <> "HTTP header." paramsStr :: [DocQueryParam] -> Blocks paramsStr [] = mempty paramsStr l = B.header sectionLevel "Query Parameters" <> B.bulletList (map paramStr l) paramStr :: DocQueryParam -> Blocks paramStr param = B.plain (B.str (param ^. paramName)) <> B.definitionList ( [(B.strong "Values", [B.plain (B.emph (foldr1 (\a b -> a <> "," <> B.space <> b) (map B.str values)))]) | not (null values), param ^. paramKind /= Flag] ++ [(B.strong "Description", [B.plain $ B.str (param ^. paramDesc)])]) <> B.bulletList ( [B.plain $ "This parameter is a" <> B.space <> B.strong "list" <> ". All query parameters with the name" <> B.space <> B.str (param ^. paramName) <> B.space <> B.code "[]" <> B.space <> "will forward their values in a list to the handler." | param ^. paramKind == List] ++ [B.plain $ "This parameter is a" <> B.space <> B.strong "flag" <> ". This means no value is expected to be associated to this parameter." | param ^. paramKind == Flag] ) where values = param ^. paramValues rqbodyStrs :: [MediaType] -> [(Text, MediaType, ByteString)] -> Blocks rqbodyStrs [] [] = mempty rqbodyStrs types bs = B.header sectionLevel "Request Body" <> B.bulletList (formatTypes types : formatBodies (renderOpts ^. requestExamples) bs) formatTypes [] = mempty formatTypes ts = mconcat [ B.plain "Supported content types are:" , B.bulletList (map (B.plain . B.code . show) ts) ] -- This assumes that when the bodies are created, identical -- labels and representations are located next to each other. formatBodies :: ShowContentTypes -> [(Text, M.MediaType, ByteString)] -> [Blocks] formatBodies ex bds = map formatBody (select bodyGroups) where bodyGroups :: [(Text, NonEmpty M.MediaType, ByteString)] bodyGroups = map (\grps -> let (t,_,b) = NE.head grps in (t, fmap (\(_,m,_) -> m) grps, b)) . groupWith (\(t,_,b) -> (t,b)) $ bds select = case ex of AllContentTypes -> id FirstContentType -> map (\(t,ms,b) -> (t, NE.head ms :| [], b)) formatBody :: (Text, NonEmpty M.MediaType, ByteString) -> Blocks formatBody (t, medias, b) = mconcat [ B.para . mconcat $ [ title , " (" , mediaList medias , "): " ] , codeStr media b ] where mediaList = fold . NE.intersperse ", " . fmap (B.code . show) media = NE.head medias title | T.null t = "Example" | otherwise = B.text (convertString t) codeStr :: MediaType -> ByteString -> Blocks codeStr media b = B.codeBlockWith ("",[markdownForType media],[]) (B.unpack b) responseStr :: Response -> Blocks responseStr resp = B.header sectionLevel "Response" <> B.bulletList ( B.plain ("Status code" <> B.space <> (B.str . show) (resp ^. respStatus)) : formatTypes (resp ^. respTypes) : case resp ^. respBody of [] -> [B.plain "No response body"] [("", t, r)] -> [B.plain "Response body as below.", codeStr t r] xs -> formatBodies (renderOpts ^. responseExamples) xs) -- Pandoc has a wide range of syntax highlighting available, -- many (all?) of which seem to correspond to the sub-type of -- their corresponding media type. markdownForType :: MediaType -> String markdownForType mt = case M.subType mt of "x-www-form-urlencoded" -> "html" t -> convertString (foldedCase t) paraStr :: [String] -> Blocks paraStr = foldMap (B.para . B.str) -- Duplicate of Servant.Docs.Internal showPath :: [String] -> String showPath [] = "/" showPath ps = concatMap ('/':) ps
mpickering/servant-pandoc
src/Servant/Docs/Pandoc.hs
mit
12,712
0
24
3,999
2,723
1,530
1,193
186
13
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module DB.Model.Internal.Remove where import DB.Model.Internal.Prelude import DB.Model.Internal.Class import DB.Model.Internal.Value import Control.Monad.Reader (ask) import Database.HDBC (IConnection, withTransaction, quickQuery) import qualified Database.HDBC as H import Data.Aeson (fromJSON, toJSON, FromJSON, ToJSON, GToJSON, GFromJSON) import qualified Data.Aeson as A nonRecursiveRemove :: (IConnection con) => [(String, Relation A.Value)] -> [(String, A.Value)] -> Model con () nonRecursiveRemove rel val = do deleteFromTable False keyVal $ head keys mapM_ (deleteFromTable False keyVal) $ tail keys where (kField, IsKey keys) = findIsKey rel keyVal = findKeyVal rel val deleteFromTable :: (IConnection con) => Bool -> Integer -> (Table, Column) -> Model con () deleteFromTable mustExist keyVal (table, keyCol) = do cnn <- ask modified <- liftIO $ withTransaction cnn (\cnn -> run cnn stmt [toSql keyVal]) when (mustExist && modified == 0) $ throwError $ printf "Could not find a row to delete when executing 'DELETE FROM %s WHERE %s=%d'." table keyCol keyVal where stmt = printf "DELETE FROM %s WHERE %s=?" table keyCol
YLiLarry/db-model
src/DB/Model/Internal/Remove.hs
mit
1,618
0
14
295
387
217
170
35
1
{-# LANGUAGE PatternSynonyms #-} module Fun.Desugar (desugar) where import ClassyPrelude import Data.Traversable (mapAccumR) import GHC.Err (errorWithoutStackTrace) import Fun.SExpression (pattern A, Expression (..), pattern ID, pattern KW, pattern L, pattern LIT, Literal (..), pattern OP, unPos) type E = Expression desugar :: E -> E desugar (L (KW "package" : ID name p : topLevels)) = L $ [ KW "package", ID name p ] <> imports <> decls where (imports, decls) = swapWith addReturn . swapPrintf . swapPrint . span isImport $ topLevels swapPrint = swapAddImport importFmt (eq (KW "print")) (ID "fmt.Println" Nothing) swapPrintf = swapAddImport importFmt (eq (KW "printf")) (ID "fmt.Printf" Nothing) desugar e = e -- Ignore non-package -- TODO: add more eq checks when needed eq :: Expression -> Expression -> Bool eq (KW x) (KW y) = x == y eq _ _ = False importFmt :: E importFmt = L [ KW "import" , LIT (String "fmt") Nothing ] -- TODO: Probably a problem with inserting expressions without position. isImport :: E -> Bool isImport (L (KW "import" : _)) = True isImport _ = False swapAddImport :: E -> (E -> Bool) -> E -> ([E], [E]) -> ([E], [E]) swapAddImport imp cond to (imports, decls) = mapAccumR go imports decls where go :: [E] -> E -> ([E], E) go imps ex | cond ex = (addImport imps, updatePos ex to) | L xs <- ex = L <$> mapAccumR go imps xs | otherwise = (imps, ex) addImport :: [E] -> [E] addImport xs = ordNub $ imp : xs updatePos :: Expression -> Expression -> Expression updatePos src (Atom x _) = Atom x (unPos src) updatePos src (List xs _) = List xs (unPos src) swapWith :: (E -> E) -> ([E], [E]) -> ([E], [E]) swapWith f (imports, decls) = (imports, fmap f decls) addReturn :: E -> E addReturn (L [ KW "func" , name , args , results , body ]) = L [ KW "func" , name , args , results , withReturn body ] addReturn (L [ KW "method" , recv , name , args , results , body ]) = L [ KW "method" , recv , name , args , results , withReturn body ] addReturn (L xs) = L (addReturn <$> xs) addReturn ex = ex withReturn :: E -> E withReturn (A a) = L [KW "return" , A a ] withReturn ret@(L (KW "return" : _ )) = ret withReturn b | isExpression b = L [KW "return" , b ] | L exprs <- b = case unsnoc exprs of Just (xs, x) -> L $ xs `snoc` withReturn x -- Throwing exceptions here for to catch edge cases. -- These conditions should not be met. Nothing -> errorWithoutStackTrace ("addReturn: " <> show b) | otherwise = errorWithoutStackTrace ("addReturn: " <> show b) isExpression :: E -> Bool isExpression (Atom _ _) = True isExpression (List ( OP _ _ : _ ) _) = True isExpression (List ( ID _ _ : _ ) _) = True isExpression (List ( KW "val" : _ ) _) = True isExpression (List ( KW "func" : _ ) _) = True isExpression _ = False
jBugman/fun-lang
src/Fun/Desugar.hs
mit
3,221
0
12
1,020
1,239
654
585
63
2
{-# LANGUAGE Arrows #-} module World where -------------------- -- Global Imports -- import Prelude hiding ((.)) import Control.Wire import Linear.V2 ------------------- -- Local Imports -- import Render import Snake import Food ---------- -- Code -- -- | The world data type. data World = World Int Food Snake instance Renderable World where render appinfo assets (World _ f s) = do render appinfo assets f render appinfo assets s -- | Checking if the current @'Food'@ and @'Snake'@ collide anywhere. overlaps :: Wire s () IO (Food, Snake) Bool overlaps = mkSF_ $ \(Food _ f, Snake l) -> f `elem` l -- | Checking if the @'Snake'@'s head overlaps with any other part of itself. lose :: Wire s () IO Snake Bool lose = mkSF_ $ \(Snake (h:b)) -> h `elem` b -- | Handling incrementing the score. scoreHandler :: Int -> Wire s () IO (Food, Bool) Int scoreHandler score = mkSFN $ \(Food t _, inc) -> if not inc then (score, scoreHandler score) else let score' = score + fromEnum t in score' `seq` (score, scoreHandler score') -- | The world wire. worldWire :: Wire s () IO (V2 Int) World worldWire = proc dir -> do rec f <- food -< o s <- snake (V2 0 1) -< (dir, o) o <- overlaps -< (f, s) sc <- scoreHandler 0 -< (f, o) returnA -< World sc f s
crockeo/netwire-vinyl
src/World.hs
mit
1,360
1
14
357
456
246
210
36
2
module Render ( renderRay ) where import Color ( Color(..) ) import Core ( Ray ) import Scene ( Scene, Intersection(..), sceneIntersection ) import Surface ( Surface(..) ) renderRay :: Ray -> Scene -> Color renderRay ray scene = getColor maybeIntersection where maybeIntersection = sceneIntersection scene ray getColor Nothing = Color 0.0 0.0 0.0 getColor (Just (Intersection _ (Surface _ c) _ _)) = c
stu-smith/rendering-in-haskell
src/experiment01/Render.hs
mit
470
0
13
133
146
82
64
13
2
module Main (main) where import System.FilePath.Glob (glob) import Test.DocTest (doctest) includeDirs :: [String] includeDirs = [] doctestWithIncludeDirs :: [String] -> IO () doctestWithIncludeDirs fs = doctest (map ((++) "-I") includeDirs ++ fs) main :: IO () main = do glob "src/**/*.hs" >>= doctestWithIncludeDirs
rcook/github-api-haskell
test/Main.hs
mit
324
0
10
50
118
65
53
10
1
main = do putStrLn "Hello! What's your name?" inpStr <- getLine putStrLn $ "Welcome to HaskHell, " ++ inpStr ++ "!"
nadyac/haskell-gol
src/input.hs
mit
118
0
9
23
34
15
19
4
1
module Main where import Idris.Core.TT import Idris.AbsSyntax import Idris.ElabDecls import Idris.REPL import Idris.Main import Idris.ModeCommon import IRTS.Compiler import IRTS.CodegenClean import System.Environment import System.Exit import Paths_idris_clean data Opts = Opts { inputs :: [FilePath] , output :: FilePath } showUsage = do putStrLn "Usage: idris-codegen-clean <ibc-files> [-o <output-file>]" exitSuccess getOpts :: IO Opts getOpts = do xs <- getArgs return $ process (Opts [] "out.icl") xs where process opts ("-o":o:xs) = process (opts { output = o }) xs process opts (x:xs) = process (opts { inputs = x:inputs opts }) xs process opts [] = opts run :: Opts -> Idris () run opts = do elabPrims loadInputs (inputs opts) Nothing mainProg <- elabMain ir <- compile (Via IBCFormat "clean") (output opts) (Just mainProg) runIO $ codegenClean ir main :: IO () main = do opts <- getOpts if null (inputs opts) then showUsage else runMain (run opts)
timjs/idris-clean
Sources/Main.hs
mit
1,062
0
12
253
370
191
179
38
3
module Reversi.AI.Common where import System.Random (StdGen) import Reversi (Reversi, Row, Col) -- | Type representing a general AI function -- | If there are no valid moves, AI should return bottom (error) type AI = StdGen -> Reversi -> (Row, Col)
sunjay/reversi
src/Reversi/AI/Common.hs
mit
252
0
7
44
53
34
19
4
0
module Handler.PoolSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "getPoolR" $ do error "Spec not implemented: getPoolR"
sramekj/lunchvote
test/Handler/PoolSpec.hs
mit
168
0
11
39
44
23
21
6
1
{- | Filter.hs Gregory W. Schwartz Pertains to functions that help filter the fasta file for clone size -} {-# LANGUAGE OverloadedStrings #-} module Filter where -- Built-in import Data.List import Data.Function (on) import qualified Data.Text.Lazy as T -- Local import Data.Fasta.Text.Lazy -- | Filter those entities greater than or equal to n occurrences filterCommonEntities :: Int -> Int -> [FastaSequence] -> [FastaSequence] filterCommonEntities ind n = concat . filter ((>= n) . length) . groupBy ((==) `on` getClone ind) . sortBy (compare `on` getClone ind) where getClone x = (!! (x - 1)) . T.splitOn "|" . fastaHeader -- | Filter those entities greater than or equal to n occurrences, where -- n is now inside the header filterCounts :: Int -> Int -> [FastaSequence] -> [FastaSequence] filterCounts ind n = filter ((>= n) . getCount ind) where getCount x = read . T.unpack . (!! (x - 1)) . T.splitOn "|" . fastaHeader
GregorySchwartz/clone-size-filter
src/Filter.hs
gpl-2.0
1,027
0
12
255
261
149
112
15
1
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} {- | Module : $Header$ Description : Comorphism from CASL to OWL2 Copyright : (c) C. Maeder, DFKI GmbH 2012 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable (via Logic.Logic) -} module OWL2.CASL2OWL where import Logic.Logic as Logic import Logic.Comorphism import Common.AS_Annotation import Common.DocUtils import Common.Result import Common.Id import Common.ProofTree import Common.Utils import qualified Common.Lib.MapSet as MapSet import qualified Data.Set as Set import qualified Data.Map as Map import Data.List import Data.Maybe -- OWL = codomain import OWL2.Logic_OWL2 import OWL2.MS import OWL2.AS import OWL2.ProfilesAndSublogics import OWL2.ManchesterPrint () import OWL2.Morphism import OWL2.Symbols import OWL2.Sign as OS import OWL2.Translate -- CASL = domain import CASL.Logic_CASL import CASL.AS_Basic_CASL import CASL.Disambiguate import CASL.Sign as CS import qualified CASL.MapSentence as MapSen import CASL.Morphism import CASL.SimplifySen import CASL.Sublogic import CASL.ToDoc import CASL.Overload data CASL2OWL = CASL2OWL deriving Show instance Language CASL2OWL instance Comorphism CASL2OWL -- comorphism CASL -- lid domain CASL_Sublogics -- sublogics domain CASLBasicSpec -- Basic spec domain CASLFORMULA -- sentence domain SYMB_ITEMS -- symbol items domain SYMB_MAP_ITEMS -- symbol map items domain CASLSign -- signature domain CASLMor -- morphism domain Symbol -- symbol domain RawSymbol -- rawsymbol domain ProofTree -- proof tree domain OWL2 -- lid codomain ProfSub -- sublogics codomain OntologyDocument -- Basic spec codomain Axiom -- sentence codomain SymbItems -- symbol items codomain SymbMapItems -- symbol map items codomain OS.Sign -- signature codomain OWLMorphism -- morphism codomain Entity -- symbol codomain RawSymb -- rawsymbol codomain ProofTree -- proof tree codomain where sourceLogic CASL2OWL = CASL sourceSublogic CASL2OWL = caslTop { sub_features = LocFilSub } targetLogic CASL2OWL = OWL2 mapSublogic CASL2OWL _ = Just topS map_theory CASL2OWL = mapTheory {- names must be disambiguated as is done in CASL.Qualify or SuleCFOL2SoftFOL. Ops or preds in the overload relation denote the same objectProperty! -} toC :: Id -> ClassExpression toC = Expression . idToIRI toO :: Id -> Int -> ObjectPropertyExpression toO i = ObjectProp . idToNumberedIRI i toACE :: Id -> (Annotations, ClassExpression) toACE i = ([], toC i) toEBit :: Id -> ListFrameBit toEBit i = ExpressionBit [toACE i] mkDR :: DomainOrRange -> Id -> FrameBit mkDR dr = ListFrameBit (Just $ DRRelation dr) . toEBit mkObjEnt :: String -> Id -> Int -> String -> FrameBit -> Named Axiom mkObjEnt s i n m = makeNamed (s ++ show i ++ (if n < 0 then "" else '_' : show n) ++ m) . PlainAxiom (ObjectEntity $ toO i n) toSubClass :: Id -> [ClassExpression] -> Axiom toSubClass i = PlainAxiom (ClassEntity $ toC i) . ListFrameBit (Just SubClass) . ExpressionBit . map (\ c -> ([], c)) getPropSens :: Id -> [SORT] -> Maybe SORT -> [Named Axiom] getPropSens i args mres = let ncs = number args opOrPred = if isJust mres then "op " else "pred " in makeNamed (opOrPred ++ show i) (toSubClass i [ObjectJunction IntersectionOf $ maybeToList (fmap toC mres) ++ map (\ (a, n) -> ObjectValuesFrom SomeValuesFrom (toO i n) $ toC a) ncs]) : concatMap (\ (a, n) -> let mki = mkObjEnt opOrPred i n in maybeToList (fmap (mki " domain" . mkDR ADomain) mres) ++ [mki " range" $ mkDR ARange a]) ncs getPropNames :: (a -> [b]) -> MapSet.MapSet Id a -> Set.Set QName getPropNames f = Map.foldWithKey (\ i s l -> case Set.toList s of [] -> l h : _ -> Set.union l $ Set.fromList $ map (idToNumberedIRI i . snd) $ number $ f h) Set.empty . MapSet.toMap commonType :: CS.Sign f e -> [[SORT]] -> Result [SORT] commonType csig l = case map (keepMaximals csig) $ transpose l of hl | all (not . null) hl -> return $ map head hl _ -> fail $ "no common types for " ++ show l commonOpType :: CS.Sign f e -> Set.Set OpType -> Result OpType commonOpType csig os = do l <- commonType csig $ map (\ o -> opRes o : opArgs o) $ Set.toList os case l of r : args -> return $ mkTotOpType args r _ -> fail $ "no common types for " ++ showDoc os "" commonPredType :: CS.Sign f e -> Set.Set PredType -> Result PredType commonPredType csig ps = do args <- commonType csig $ map predArgs $ Set.toList ps case args of _ : _ -> return $ PredType args _ -> fail $ "no common types for " ++ showDoc ps "" getCommonSupers :: CS.Sign f e -> [SORT] -> Set.Set SORT getCommonSupers csig s = let supers t = Set.insert t $ supersortsOf t csig in if null s then Set.empty else foldr1 Set.intersection $ map supers s keepMaximals :: CS.Sign f e -> [SORT] -> [SORT] keepMaximals csig = keepMinimals1 True csig id . Set.toList . getCommonSupers csig mapSign :: CS.Sign f e -> Result (OS.Sign, [Named Axiom]) mapSign csig = let esorts = emptySortSet csig srel = sortRel csig (eqs, subss) = eqAndSubsorts False srel (isos, rels) = singleAndRelatedSorts srel disjSorts = concatMap (\ l -> case l of _ : _ : _ -> [makeNamed ("disjoint " ++ show l) $ mkMisc Disjoint l] _ -> []) . sequence $ map (: []) isos ++ map (keepMaximals csig) rels ss = sortSet csig nsorts = Set.difference ss esorts mkMisc ed l = PlainAxiom (Misc []) $ ListFrameBit (Just $ EDRelation ed) $ ExpressionBit $ map toACE l eqSorts = map (\ es -> makeNamed ("equal sorts " ++ show es) $ mkMisc Equivalent es) eqs subSens = map (\ (s, ts) -> makeNamed ("subsort " ++ show s ++ " of " ++ show ts) $ toSC s ts) subss nonEmptySens = map (\ s -> mkIndi True s [s]) $ Set.toList nsorts sortSens = eqSorts ++ disjSorts ++ subSens ++ nonEmptySens mkIndi b i ts = makeNamed ("individual " ++ show i ++ " of class " ++ showDoc ts "") $ PlainAxiom (SimpleEntity $ Entity NamedIndividual $ idToAnonIRI b i) $ ListFrameBit (Just Types) $ ExpressionBit $ map toACE ts om = opMap csig keepMaxs = keepMaximals csig mk s i = mkObjEnt s i (-1) toSC i = toSubClass i . map toC toIris = Set.map idToIRI (cs, ncs) = MapSet.partition (null . opArgs) om (sos, os) = MapSet.partition isSingleArgOp ncs (props, nps) = MapSet.partition (null . predArgs) pm (sps, rps) = MapSet.partition (isSingle . predArgs) nps (bps, ps) = MapSet.partition isBinPredType rps pm = predMap csig osig = OS.emptySign { concepts = toIris $ Set.unions [ ss, MapSet.keysSet sps, MapSet.keysSet props , MapSet.keysSet os, MapSet.keysSet ps] , objectProperties = Set.unions [ toIris $ Set.union (MapSet.keysSet sos) $ MapSet.keysSet bps , getPropNames predArgs ps, getPropNames opArgs os ] , individuals = toIris $ MapSet.keysSet cs } in do s1 <- Map.foldWithKey (\ i s ml -> do l <- ml return $ mkIndi False i (keepMinimals csig id $ map opRes $ Set.toList s) : l) (return sortSens) (MapSet.toMap cs) s2 <- Map.foldWithKey (\ i s ml -> do l <- ml let sl = Set.toList s mki = mk "plain function " i case (keepMaxs $ concatMap opArgs sl, keepMaxs $ map opRes sl) of ([a], [r]) -> return $ [ mki " character" $ ListFrameBit Nothing $ ObjectCharacteristics [([], Functional)] , mki " domain" $ mkDR ADomain a, mki " range" $ mkDR ARange r] ++ l (as, rs) -> fail $ "CASL2OWL.mapSign2: " ++ show i ++ " args: " ++ show as ++ " resulttypes: " ++ show rs) (return s1) (MapSet.toMap sos) s3 <- Map.foldWithKey (\ i s ml -> do l <- ml let mkp = mk "binary predicate " i pTy <- commonPredType csig s case predArgs pTy of [a, r] -> return $ [mkp " domain" $ mkDR ADomain a, mkp " range" $ mkDR ARange r] ++ l ts -> fail $ "CASL2OWL.mapSign3: " ++ show i ++ " types: " ++ show ts) (return s2) (MapSet.toMap bps) s4 <- Map.foldWithKey (\ i s ml -> case keepMaxs $ concatMap predArgs $ Set.toList s of [r] -> do l <- ml return $ makeNamed ("plain predicate " ++ show i) (toSC i [r]) : l ts -> fail $ "CASL2OWL.mapSign4: " ++ show i ++ " types: " ++ show ts) (return s3) (MapSet.toMap sps) s5 <- Map.foldWithKey (\ i s ml -> do l <- ml ot <- commonOpType csig s return $ getPropSens i (opArgs ot) (Just $ opRes ot) ++ l ) (return s4) (MapSet.toMap os) s6 <- Map.foldWithKey (\ i s ml -> do l <- ml pt <- commonPredType csig s return $ getPropSens i (predArgs pt) Nothing ++ l ) (return s5) (MapSet.toMap ps) return (osig, s6) {- binary predicates and single argument functions should become objectProperties. Serge also turned constructors into concepts. How to treat multi-argument predicates and functions? Maybe create tuple concepts? -} mapTheory :: (FormExtension f, TermExtension f) => (CS.Sign f e, [Named (FORMULA f)]) -> Result (OS.Sign, [Named Axiom]) mapTheory (sig, sens) = do let mor = disambigSig sig tar = mtarget mor nss = map (mapNamed $ MapSen.mapMorphForm (const id) mor) sens (s, l) <- mapSign tar ll <- mapM (\ ns -> case sentence ns of Sort_gen_ax cs b -> return $ mapSortGenAx cs b _ -> flip (hint []) nullRange . ("not translated\n" ++) . show . printTheoryFormula $ mapNamed (simplifySen (const return) (const id) tar) ns ) nss return (s, l ++ concat ll) mapSortGenAx :: [Constraint] -> Bool -> [Named Axiom] mapSortGenAx cs b = map (\ (s, as) -> let is = map (\ (Qual_op_name n ty _) -> case args_OP_TYPE ty of [] -> ObjectOneOf [idToIRI n] [_] -> ObjectValuesFrom SomeValuesFrom (toO n (-1)) $ toC s _ -> toC n) as in makeNamed ("generated " ++ show s) $ PlainAxiom (ClassEntity $ toC s) $ if b && not (isSingle is) then AnnFrameBit [] $ ClassDisjointUnion is else ListFrameBit (Just $ EDRelation Equivalent) $ ExpressionBit [([], case is of [i] -> i _ -> ObjectJunction UnionOf is)]) $ recoverSortGen cs
nevrenato/HetsAlloy
OWL2/CASL2OWL.hs
gpl-2.0
10,653
0
25
2,788
3,745
1,891
1,854
244
5
solve :: Int -> Int -> Int -> Int solve num n start = sum $ map aux [start..upper] where upper = ceiling $ (fromIntegral num) ** (1 / (fromIntegral n)) aux x | num - x^n == 0 = 1 | num - x^n < 0 = 0 | otherwise = solve (num - x^n) n (x + 1) main = do contents <- getContents let [num, n] = map (read :: String -> Int) (lines contents) putStrLn $ show $ solve num n 1
m00nlight/hackerrank
functional/recursion/The-Sum-of-Powers/main.hs
gpl-2.0
437
0
12
156
226
112
114
11
1
{-# OPTIONS -w -O0 #-} {- | Module : SoftFOL/ATC_SoftFOL.der.hs Description : generated Typeable, ShATermConvertible instances Copyright : (c) DFKI Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable(overlapping Typeable instances) Automatic derivation of instances via DrIFT-rule Typeable, ShATermConvertible for the type(s): 'SoftFOL.Sign.Sign' 'SoftFOL.Sign.Generated' 'SoftFOL.Sign.SFSymbol' 'SoftFOL.Sign.SFSymbType' 'SoftFOL.Sign.SPProblem' 'SoftFOL.Sign.SPLogicalPart' 'SoftFOL.Sign.SPSymbolList' 'SoftFOL.Sign.SPSignSym' 'SoftFOL.Sign.SPSortSym' 'SoftFOL.Sign.SPDeclaration' 'SoftFOL.Sign.SPFormulaList' 'SoftFOL.Sign.SPClauseList' 'SoftFOL.Sign.SPOriginType' 'SoftFOL.Sign.SPClauseType' 'SoftFOL.Sign.NSPClause' 'SoftFOL.Sign.NSPClauseBody' 'SoftFOL.Sign.TermWsList' 'SoftFOL.Sign.SPTerm' 'SoftFOL.Sign.SPLiteral' 'SoftFOL.Sign.SPQuantSym' 'SoftFOL.Sign.SPSymbol' 'SoftFOL.Sign.SPProofList' 'SoftFOL.Sign.SPProofStep' 'SoftFOL.Sign.SPReference' 'SoftFOL.Sign.SPResult' 'SoftFOL.Sign.SPRuleAppl' 'SoftFOL.Sign.SPUserRuleAppl' 'SoftFOL.Sign.SPParent' 'SoftFOL.Sign.SPKey' 'SoftFOL.Sign.SPValue' 'SoftFOL.Sign.SPDescription' 'SoftFOL.Sign.SPLogState' 'SoftFOL.Sign.SPSetting' 'SoftFOL.Sign.SPSettingBody' 'SoftFOL.Sign.SPHypothesis' 'SoftFOL.Sign.SPSettingLabel' 'SoftFOL.Sign.SPCRBIND' -} {- Generated by 'genRules' (automatic rule generation for DrIFT). Don't touch!! dependency files: SoftFOL/Sign.hs -} module SoftFOL.ATC_SoftFOL () where import ATC.AS_Annotation import ATerm.Lib import Common.AS_Annotation import Common.DefaultMorphism import Common.Id import Data.Char import Data.Typeable import SoftFOL.Sign import qualified Common.Lib.Rel as Rel import qualified Data.Map as Map import qualified Data.Set as Set {-! for SoftFOL.Sign.Sign derive : Typeable !-} {-! for SoftFOL.Sign.Generated derive : Typeable !-} {-! for SoftFOL.Sign.SFSymbol derive : Typeable !-} {-! for SoftFOL.Sign.SFSymbType derive : Typeable !-} {-! for SoftFOL.Sign.SPProblem derive : Typeable !-} {-! for SoftFOL.Sign.SPLogicalPart derive : Typeable !-} {-! for SoftFOL.Sign.SPSymbolList derive : Typeable !-} {-! for SoftFOL.Sign.SPSignSym derive : Typeable !-} {-! for SoftFOL.Sign.SPSortSym derive : Typeable !-} {-! for SoftFOL.Sign.SPDeclaration derive : Typeable !-} {-! for SoftFOL.Sign.SPFormulaList derive : Typeable !-} {-! for SoftFOL.Sign.SPClauseList derive : Typeable !-} {-! for SoftFOL.Sign.SPOriginType derive : Typeable !-} {-! for SoftFOL.Sign.SPClauseType derive : Typeable !-} {-! for SoftFOL.Sign.NSPClause derive : Typeable !-} {-! for SoftFOL.Sign.NSPClauseBody derive : Typeable !-} {-! for SoftFOL.Sign.TermWsList derive : Typeable !-} {-! for SoftFOL.Sign.SPTerm derive : Typeable !-} {-! for SoftFOL.Sign.SPLiteral derive : Typeable !-} {-! for SoftFOL.Sign.SPQuantSym derive : Typeable !-} {-! for SoftFOL.Sign.SPSymbol derive : Typeable !-} {-! for SoftFOL.Sign.SPProofList derive : Typeable !-} {-! for SoftFOL.Sign.SPProofStep derive : Typeable !-} {-! for SoftFOL.Sign.SPReference derive : Typeable !-} {-! for SoftFOL.Sign.SPResult derive : Typeable !-} {-! for SoftFOL.Sign.SPRuleAppl derive : Typeable !-} {-! for SoftFOL.Sign.SPUserRuleAppl derive : Typeable !-} {-! for SoftFOL.Sign.SPParent derive : Typeable !-} {-! for SoftFOL.Sign.SPKey derive : Typeable !-} {-! for SoftFOL.Sign.SPValue derive : Typeable !-} {-! for SoftFOL.Sign.SPDescription derive : Typeable !-} {-! for SoftFOL.Sign.SPLogState derive : Typeable !-} {-! for SoftFOL.Sign.SPSetting derive : Typeable !-} {-! for SoftFOL.Sign.SPSettingBody derive : Typeable !-} {-! for SoftFOL.Sign.SPHypothesis derive : Typeable !-} {-! for SoftFOL.Sign.SPSettingLabel derive : Typeable !-} {-! for SoftFOL.Sign.SPCRBIND derive : Typeable !-} {-! for SoftFOL.Sign.Sign derive : ShATermConvertible !-} {-! for SoftFOL.Sign.Generated derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SFSymbol derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SFSymbType derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPProblem derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPLogicalPart derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPSymbolList derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPSignSym derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPSortSym derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPDeclaration derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPFormulaList derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPClauseList derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPOriginType derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPClauseType derive : ShATermConvertible !-} {-! for SoftFOL.Sign.NSPClause derive : ShATermConvertible !-} {-! for SoftFOL.Sign.NSPClauseBody derive : ShATermConvertible !-} {-! for SoftFOL.Sign.TermWsList derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPTerm derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPLiteral derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPQuantSym derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPSymbol derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPProofList derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPProofStep derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPReference derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPResult derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPRuleAppl derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPUserRuleAppl derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPParent derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPKey derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPValue derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPDescription derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPLogState derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPSetting derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPSettingBody derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPHypothesis derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPSettingLabel derive : ShATermConvertible !-} {-! for SoftFOL.Sign.SPCRBIND derive : ShATermConvertible !-}
nevrenato/Hets_Fork
SoftFOL/ATC_SoftFOL.der.hs
gpl-2.0
6,229
0
4
691
151
126
25
13
0
module H40 where primes :: (Integral i) => [i] primes = sieve [2..] where sieve (p:ps) = p : sieve [p' | p' <- ps, p' `mod` p /= 0] primesN n = takeWhile (< n) primes goldbach :: (Integral i) => i -> (i, i) goldbach n | n <= 2 || n `mod` 2 /= 0 = error "invalid parameter" | otherwise = findSum n (primesN n) where findSum n xs = head $ filter (\(x, y) -> x + y == n) (cross xs xs) cross [] _ = [] cross [x] ys = map (\y -> (x,y)) ys cross (x:xs) ys = cross [x] ys ++ cross xs ys
hsinhuang/codebase
h99/H40.hs
gpl-2.0
542
0
12
175
308
163
145
13
3
-- find the prime factors of a number -- and the multiple of the number import Data.List (group) p35 n = f n primes where f n p@(x:xs) | n < 2 = [] | mod n x == 0 = x : f (div n x) p | otherwise = f n xs primes = sieve [2..] where sieve (x:xs) = x : sieve [ z | z <- xs, mod z x /= 0 ] p36 n = map encode . group . p35 $ n where encode l@(x:_) = (x, length l)
yalpul/CENG242
H99/31-41/p36.hs
gpl-3.0
450
0
14
185
220
110
110
10
1
type IO a = RealWorld -> (a, RealWorld)
hmemcpy/milewski-ctfp-pdf
src/content/3.5/code/haskell/snippet33.hs
gpl-3.0
39
0
6
7
18
11
7
1
0
module Problem34Spec where import Test.Hspec import Problem34 (totient) spec :: Spec spec = context "" $ do describe "subsets" $ do it "determine that totien of 10 is 4" $ do totient 10 `shouldBe` 4
wando-hs/H-99
test/Problem34Spec.hs
gpl-3.0
223
0
15
59
66
34
32
9
1
-- | module ExercisesMonad where
capitanbatata/sandbox
my-typeclassopedia/my-typeclassopedia-haskell/src/ExercisesMonad.hs
gpl-3.0
34
0
2
6
5
4
1
1
0
module S.Gen where import S.Type import S.Table import qualified Data.Map as M import Data.List (nub, inits) import Data.Maybe (isJust) import Control.Applicative ( (<$>), (<*>) ) invert :: M.Map (Int,Int) Int -> M.Map Int [Maybe (Int,Int)] invert m = M.fromListWith (++) $ (0, [Nothing]) : do ((p,q),r) <- M.toList m return (r, [ Just (p,q) ]) au = invert $ complete trans -- | non-normalizing terms, increasing size nono = concat $ generate au M.! 38 type TS = [[T]] -- | by increasing size, starting with 0 -- | for each state, a lazy list of terms -- that are accepted in that state. generate :: M.Map Int [Maybe (Int,Int)] -> M.Map Int [[T]] generate au = m where m = M.fromList $ do r <- M.keys au let series = unions $ do v <- au M.! r return $ case v of Nothing -> [ [s]] Just (p,q) -> [] : crosses app (m M.! p) (m M.! q) return (r, series) unions = foldr union [] union xs [] = xs union [] ys = ys union (xs:xss) (ys:yss) = nub (xs ++ ys) : union xss yss crosses f = cross ( \xs ys -> f <$> xs <*> ys ) cross :: Eq c => (a->b->[c]) -> [a] -> [b] -> [[c]] cross f xs ys = let lift xs = map Just xs ++ repeat Nothing unlift (Just x:ys) = x ++ unlift ys unlift (Nothing:ys) = unlift ys unlift _ = [] in map (nub . unlift) $ takeWhile ( any isJust ) $ cross_inf (\ x y -> f <$> x <*> y) ( lift xs) (lift ys) cross_inf :: (a->b->c) -> [a] -> [b] -> [[c]] cross_inf f xs ys = do xs' <- tail $ inits xs return $ zipWith f (reverse xs') ys
jwaldmann/s
S/Gen.hs
gpl-3.0
1,705
0
23
567
811
429
382
46
3
{-# 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.CloudIOT.Projects.Locations.Registries.BindDeviceToGateway -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Associates the device with the gateway. -- -- /See:/ <https://cloud.google.com/iot Cloud IoT API Reference> for @cloudiot.projects.locations.registries.bindDeviceToGateway@. module Network.Google.Resource.CloudIOT.Projects.Locations.Registries.BindDeviceToGateway ( -- * REST Resource ProjectsLocationsRegistriesBindDeviceToGatewayResource -- * Creating a Request , projectsLocationsRegistriesBindDeviceToGateway , ProjectsLocationsRegistriesBindDeviceToGateway -- * Request Lenses , plrbdtgParent , plrbdtgXgafv , plrbdtgUploadProtocol , plrbdtgAccessToken , plrbdtgUploadType , plrbdtgPayload , plrbdtgCallback ) where import Network.Google.CloudIOT.Types import Network.Google.Prelude -- | A resource alias for @cloudiot.projects.locations.registries.bindDeviceToGateway@ method which the -- 'ProjectsLocationsRegistriesBindDeviceToGateway' request conforms to. type ProjectsLocationsRegistriesBindDeviceToGatewayResource = "v1" :> CaptureMode "parent" "bindDeviceToGateway" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] BindDeviceToGatewayRequest :> Post '[JSON] BindDeviceToGatewayResponse -- | Associates the device with the gateway. -- -- /See:/ 'projectsLocationsRegistriesBindDeviceToGateway' smart constructor. data ProjectsLocationsRegistriesBindDeviceToGateway = ProjectsLocationsRegistriesBindDeviceToGateway' { _plrbdtgParent :: !Text , _plrbdtgXgafv :: !(Maybe Xgafv) , _plrbdtgUploadProtocol :: !(Maybe Text) , _plrbdtgAccessToken :: !(Maybe Text) , _plrbdtgUploadType :: !(Maybe Text) , _plrbdtgPayload :: !BindDeviceToGatewayRequest , _plrbdtgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsRegistriesBindDeviceToGateway' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plrbdtgParent' -- -- * 'plrbdtgXgafv' -- -- * 'plrbdtgUploadProtocol' -- -- * 'plrbdtgAccessToken' -- -- * 'plrbdtgUploadType' -- -- * 'plrbdtgPayload' -- -- * 'plrbdtgCallback' projectsLocationsRegistriesBindDeviceToGateway :: Text -- ^ 'plrbdtgParent' -> BindDeviceToGatewayRequest -- ^ 'plrbdtgPayload' -> ProjectsLocationsRegistriesBindDeviceToGateway projectsLocationsRegistriesBindDeviceToGateway pPlrbdtgParent_ pPlrbdtgPayload_ = ProjectsLocationsRegistriesBindDeviceToGateway' { _plrbdtgParent = pPlrbdtgParent_ , _plrbdtgXgafv = Nothing , _plrbdtgUploadProtocol = Nothing , _plrbdtgAccessToken = Nothing , _plrbdtgUploadType = Nothing , _plrbdtgPayload = pPlrbdtgPayload_ , _plrbdtgCallback = Nothing } -- | Required. The name of the registry. For example, -- \`projects\/example-project\/locations\/us-central1\/registries\/my-registry\`. plrbdtgParent :: Lens' ProjectsLocationsRegistriesBindDeviceToGateway Text plrbdtgParent = lens _plrbdtgParent (\ s a -> s{_plrbdtgParent = a}) -- | V1 error format. plrbdtgXgafv :: Lens' ProjectsLocationsRegistriesBindDeviceToGateway (Maybe Xgafv) plrbdtgXgafv = lens _plrbdtgXgafv (\ s a -> s{_plrbdtgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plrbdtgUploadProtocol :: Lens' ProjectsLocationsRegistriesBindDeviceToGateway (Maybe Text) plrbdtgUploadProtocol = lens _plrbdtgUploadProtocol (\ s a -> s{_plrbdtgUploadProtocol = a}) -- | OAuth access token. plrbdtgAccessToken :: Lens' ProjectsLocationsRegistriesBindDeviceToGateway (Maybe Text) plrbdtgAccessToken = lens _plrbdtgAccessToken (\ s a -> s{_plrbdtgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plrbdtgUploadType :: Lens' ProjectsLocationsRegistriesBindDeviceToGateway (Maybe Text) plrbdtgUploadType = lens _plrbdtgUploadType (\ s a -> s{_plrbdtgUploadType = a}) -- | Multipart request metadata. plrbdtgPayload :: Lens' ProjectsLocationsRegistriesBindDeviceToGateway BindDeviceToGatewayRequest plrbdtgPayload = lens _plrbdtgPayload (\ s a -> s{_plrbdtgPayload = a}) -- | JSONP plrbdtgCallback :: Lens' ProjectsLocationsRegistriesBindDeviceToGateway (Maybe Text) plrbdtgCallback = lens _plrbdtgCallback (\ s a -> s{_plrbdtgCallback = a}) instance GoogleRequest ProjectsLocationsRegistriesBindDeviceToGateway where type Rs ProjectsLocationsRegistriesBindDeviceToGateway = BindDeviceToGatewayResponse type Scopes ProjectsLocationsRegistriesBindDeviceToGateway = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloudiot"] requestClient ProjectsLocationsRegistriesBindDeviceToGateway'{..} = go _plrbdtgParent _plrbdtgXgafv _plrbdtgUploadProtocol _plrbdtgAccessToken _plrbdtgUploadType _plrbdtgCallback (Just AltJSON) _plrbdtgPayload cloudIOTService where go = buildClient (Proxy :: Proxy ProjectsLocationsRegistriesBindDeviceToGatewayResource) mempty
brendanhay/gogol
gogol-cloudiot/gen/Network/Google/Resource/CloudIOT/Projects/Locations/Registries/BindDeviceToGateway.hs
mpl-2.0
6,409
0
16
1,347
782
457
325
126
1
{-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -Wall #-} -- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP -- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP ---------------------------------------------------------------------- -- | -- Module : Shady.CompileImageSimple -- Copyright : (c) 2015 Tabula, Inc. -- -- Maintainer : [email protected] -- Stability : experimental -- -- Compile a parametrized image. For now, just animated, i.e., time-dependent. ---------------------------------------------------------------------- module Shady.CompileImageSimple (ImageB, imageBProg) where -- TODO: explicit exports import Control.Applicative (liftA2) -- import TypeUnary.Vec((<+>),vec4) import Shady.Complex(Complex(..)) import Shady.Language.Type (R1,R2) import Shady.Language.Exp ((:=>),vec4) import Shady.Color -- (white,HasColor(..)) import Shady.Image (Image,Point) import Shady.CompileEs ((:-^),(:-*),(:->)(ShaderVF),ShaderVF,shaderProgram,GLSL) -- ,compile -- | 2D animation type ImageB c = R1 :=> Image c imageBShader :: HasColor c => ImageB c -> (R1 :=> ShaderVF Point) imageBShader imb = liftA2 ShaderVF vert frag where vert :: R1 :=> (Point :-^ Point) frag :: R1 :=> (Point :-* ()) vert _t p@(x :+ y) = (vec4 x y 0 1, p) frag t p = (colorToR4 (toColor (imb t p)), ()) -- frag t p = (colorToR4 white, ()) -- | GLSL program for an 'ImageB'. imageBProg :: HasColor c => ImageB c -> GLSL R1 R2 imageBProg = shaderProgram . imageBShader
conal/shady-graphics
src/Shady/CompileImageSimple.hs
agpl-3.0
1,494
0
12
239
339
203
136
20
1
module Main ( main ) where import Control.Monad.State import Data.Maybe import Data.List import System.Console.GetOpt import System.Environment import System.Exit import System.IO import Text.Printf import Robotics.NXT data Option = Help | Device FilePath deriving (Eq, Show) isDevice :: Option -> Bool isDevice (Device _) = True isDevice _ = False options :: [OptDescr Option] options = [ Option "h" ["help"] (NoArg Help) "show this help", Option "d" ["device"] (ReqArg Device "filename") "serial port device" ] main :: IO () main = do programName <- getProgName let header = programName ++ " [option ...]" ++ "\n\nOptions:" usage = "Usage:\n" ++ usageInfo header options args <- getArgs opts <- case getOpt Permute options args of (o, [], []) -> return o (_, _, []) -> do hPutStrLn stderr $ "Error(s):\n" ++ "excess argument(s)\n\n" ++ usage exitWith $ ExitFailure 1 (_, _, errs) -> do hPutStrLn stderr $ "Error(s):\n" ++ concat errs ++ "\n" ++ usage exitWith $ ExitFailure 1 when (Help `elem` opts) $ do putStrLn "Prints status of the NXT brick.\n" putStrLn usage exitWith ExitSuccess let Device device = fromMaybe (Device defaultDevice) . find isDevice $ opts withNXT device $ do DeviceInfo name btaddress btstrength flashfree <- getDeviceInfo Version (FirmwareVersion fmajor fminor) (ProtocolVersion pmajor pminor) <- getVersion battery <- getBatteryLevel rechargeable <- isBatteryRechargeable sleeplimit <- getSleepTimeout let fversion = printf "%d.%02d" fmajor fminor :: String pversion = printf "%d.%02d" pmajor pminor :: String liftIO $ hPutStrLn stderr $ printf "Connected to %s at %s." name btaddress liftIO $ hPutStrLn stderr $ printf "Running firmware version %s with protocol version %s." fversion pversion liftIO $ hPutStrLn stderr $ printf "Battery level: %f V (%s)" (realToFrac battery :: Double) (if rechargeable then "rechargeable" else "not rechargeable") liftIO $ hPutStrLn stderr $ printf "Free space: %d bytes" flashfree liftIO $ hPutStrLn stderr $ printf "Signal strength: %d" btstrength liftIO $ hPutStrLn stderr $ printf "Sleep time limit: %f s" (realToFrac sleeplimit :: Double)
mitar/nxt
src/Status.hs
lgpl-3.0
2,364
0
17
575
693
339
354
52
4
{-# LANGUAGE OverloadedStrings #-} module Main where import Graphics.UI.Gtk import Control.Concurrent.MVar import Control.Monad ( liftM ) import Data.Maybe ( fromMaybe ) import Data.List ( findIndex ) import Control.Monad.IO.Class (MonadIO(..)) import qualified Data.Text as T main = do initGUI win <- windowNew on win deleteEvent $ liftIO mainQuit >> return False combo <- comboBoxNewWithEntry comboBoxSetModelText combo mapM_ (comboBoxAppendText combo) (T.words "ice-cream turkey pasta sandwich steak") -- select the first item comboBoxSetActive combo 0 -- Get the entry widget that the ComboBoxEntry uses. (Just w) <- binGetChild combo let entry = castToEntry w -- Whenever the user has completed editing the text, append the new -- text to the store unless it's already in there. on entry entryActivated $ do str <- entryGetText entry store <- comboBoxGetModelText combo elems <- listStoreToList store comboBoxSetActive combo (-1) idx <- case (findIndex ((==) str) elems) of Just idx -> return idx Nothing -> listStoreAppend store str comboBoxSetActive combo idx return () containerAdd win combo widgetShowAll win mainGUI
juhp/gtk2hs
gtk/demo/menu/ComboDemo.hs
lgpl-3.0
1,214
0
15
250
321
156
165
33
2
--題目:https://zerojudge.tw/ShowProblem?problemid=a034 {- 內容 還記得計算機概論嗎?還記得二進位嗎? 現在我們來計算一下將一個10進位的數字換成二進位數字 輸入說明 一個十進位的數值 輸出說明 輸出二進位制的結果 範例輸入 3 6 範例輸出 11 110 -} main :: IO() main = do
bestian/haskell-sandbox
Quizs/q034_binary.hs
unlicense
350
1
6
31
17
10
7
-1
-1
module Main where import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.Framework.Providers.HUnit import qualified Haskoin.Script.Tests (tests) import qualified Units (tests) main = defaultMain ( Haskoin.Script.Tests.tests ++ Units.tests )
OttoAllmendinger/haskoin-script
testsuite/Main.hs
unlicense
283
0
8
44
65
42
23
9
1
import Test.Tasty import PackItForms.MsgFmtTests import PackItForms.ICS213Tests import PackItForms.LADamageTests main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [ packItFormsMsgFmtTests , ics213Tests , laDamageTests ]
pack-it-forms/msgfmt
tests/main.hs
apache-2.0
308
0
6
85
63
35
28
10
1
import Network import System.IO import Text.Printf main = "Hello World"
selbert/haskell-irc-client
main.hs
bsd-2-clause
72
0
4
10
19
11
8
4
1
-- | Core Process code {-# LANGUAGE ExistentialQuantification, FlexibleInstances, GeneralizedNewtypeDeriving, ScopedTypeVariables, DeriveDataTypeable, MultiParamTypeClasses, CPP #-} module Process ( -- * Types Process -- * Interface , runP , spawnP , catchP , cleanupP , stopP -- * Log Interface , Logging(..) , logP , infoP , debugP , warningP , criticalP , errorP ) where import Control.Concurrent import Control.Exception import Control.Monad.Reader import Control.Monad.State.Strict import Data.Typeable import Prelude hiding (catch, log) import System.Log.Logger -- | A @Process a b c@ is the type of processes with access to configuration data @a@, state @b@ -- returning values of type @c@. Usually, the read-only data are configuration parameters and -- channels, and the state the internal process state. It is implemented by means of a transformer -- stack on top of IO. newtype Process a b c = Process (ReaderT a (StateT b IO) c) deriving (Functor, Monad, MonadIO, MonadState b, MonadReader a) data StopException = StopException deriving (Show, Typeable) instance Exception StopException stopP :: Process a b c stopP = throw StopException -- | Run the process monad given a configuation of type @a@ and a initial state of type @b@ runP :: a -> b -> Process a b c -> IO (c, b) runP c st (Process p) = runStateT (runReaderT p c) st -- | Spawn and run a process monad spawnP :: a -> b -> Process a b () -> IO ThreadId spawnP c st p = forkIO proc where proc = runP c st p >> return () -- | Run the process monad for its side effect, with a stopHandler if exceptions -- are raised in the process catchP :: Logging a => Process a b () -> Process a b () -> Process a b () catchP proc stopH = cleanupP proc stopH (return ()) -- | Run the process monad for its side effect. @cleanupP p sh ch@ describes to -- run @p@. If @p@ dies by a kill from a supervisor, run @ch@. Otherwise it runs -- @ch >> sh@ on death. cleanupP :: Logging a => Process a b () -> Process a b () -> Process a b () -> Process a b () cleanupP proc stopH cleanupH = do st <- get c <- ask (a, s') <- liftIO $ runP c st proc `catches` [ Handler (\ThreadKilled -> runP c st ( do infoP $ "Process Terminated by Supervisor" cleanupH )) , Handler (\StopException -> runP c st (do infoP $ "Process Terminating gracefully" cleanupH >> stopH)) -- This one is ok , Handler (\(ex :: SomeException) -> runP c st (do criticalP $ "Process exiting due to ex: " ++ show ex cleanupH >> stopH)) ] put s' return a ------ LOGGING -- -- | The class of types where we have a logger inside them somewhere class Logging a where -- | Returns a channel for logging and an Identifying string to use logName :: a -> String logP :: Logging a => Priority -> String -> Process a b () logP prio msg = do n <- asks logName liftIO $ logM n prio (n ++ ":\t" ++ msg) infoP, debugP, criticalP, warningP, errorP :: Logging a => String -> Process a b () infoP = logP INFO #ifdef NDEBUG debugP _ = return () #else debugP = logP DEBUG #endif criticalP = logP CRITICAL warningP = logP WARNING errorP = logP ERROR
beni55/combinatorrent
src/Process.hs
bsd-2-clause
3,459
0
18
984
845
447
398
68
1
module Nlp4 (answers) where import Zak.Utf8 import Zak.Morph import qualified Data.ByteString.Char8 as BS import Data.ByteString.Char8 (ByteString) import Control.Monad import Data.List (group, sort, sortBy) import Data.List.HT (chop) import Control.Arrow import Graphics.Gnuplot.Simple answers = map (morphemeBook >>=) [q30, q31, q32, q33, q34, q35, q36, q37, q38, q39] morphemeBook :: IO [[Morph]] morphemeBook = buildMorphBook . chop (u "EOS" ==) . BS.lines <$> BS.readFile "input/neko.txt.mecab" f39 :: [[Morph]] -> [Int] f39 = map fst . frequency q39 :: [[Morph]] -> IO () q39 = plotList attr . f39 where attr = [ Custom "logscale" [] , Title "Zipf's law" , XLabel "Index" , YLabel "Usage count" , Key Nothing ] f38 :: [[Morph]] -> [(Int, Int)] f38 = runlength . map ((*10) . (`div` 10) . fst) . frequency q38 :: [[Morph]] -> IO () q38 = plotListStyle attr (defaultStyle { plotType = Boxes }) . f38 where attr = [ Custom "boxwidth" ["10"] , Title "Histogram" , XLabel "Usage count" , YLabel "Number of kind of words" , XRange (0.0, 10**4) , YRange (0.0, 50.0) , Key Nothing ] f37 :: [(Int, ByteString)] -> String f37 = unlines . map (\(n,s) -> "\"" ++ utf8unpack s ++ "\" " ++ show n) q37 :: [[Morph]] -> IO () q37 morphs = do let option = [";set title \"Top 10 of most freqently used Morph\"" , "set xlabel \"Morphemes\"" , "set ylabel \"Usage count\"" , "set yrange [0:1e4]" , "unset key" ] plotCmd = "; plot \"" ++ outfile ++ "\" using 0:2:xtic(1) with boxes; #\\" attr = [Custom "boxwidth" ["0.5", "relative", unlines option ++ plotCmd]] dat = f37 $ f36 morphs writeFile outfile dat plotList attr ([] :: [Int]) where outfile = "output/top10.dat" f36 :: [[Morph]] -> [(Int, ByteString)] f36 = take 10 . frequency frequency :: [[Morph]] -> [(Int, ByteString)] frequency = sortBy (flip compare) . runlengthF . sort . map base . join runlength :: (Eq a) => [a] -> [(a, Int)] runlength = map (head &&& length) . group runlengthF :: (Eq a) => [a] -> [(Int, a)] runlengthF = map (length &&& head) . group f35 :: [[Morph]] -> [ByteString] f35 = join . map (map (BS.concat . map surface) . filter ((2 <=) . length) . chop (not . isNoun)) f34 :: [[Morph]] -> [ByteString] f34 = join . map aofb where aofb :: [Morph] -> [ByteString] aofb (a:o:b:ms) | isNoun a && (surface o == u"の") && isNoun b = (:) (BS.concat $ map surface [a, o, b]) (aofb $ b:ms) | otherwise = aofb $ o:b:ms aofb _ = [] f33 :: [[Morph]] -> [ByteString] f33 = map surface . filter ((u"サ変接続" ==) . pos1) . join f32 :: [[Morph]] -> [ByteString] f32 = map base . filter isVerb . join f31 :: [[Morph]] -> [ByteString] f31 = map surface . filter isVerb . join q36 = putStr . unlines . map (\(l,s) -> show l ++ "\t" ++ utf8unpack s) . f36 q35 = BS.putStr . BS.unlines . f35 q34 = BS.putStr . BS.unlines . f34 q33 = BS.putStr . BS.unlines . f33 q32 = BS.putStr . BS.unlines . f32 q31 = BS.putStr . BS.unlines . f31 q30 = print . join
Iruyan-Zak/Nlp100
src/Nlp4.hs
bsd-3-clause
3,213
0
14
836
1,368
755
613
83
2
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Quantity.RO.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Quantity.RO.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "RO Tests" [ makeCorpusTest [Seal Quantity] corpus ]
facebookincubator/duckling
tests/Duckling/Quantity/RO/Tests.hs
bsd-3-clause
507
0
9
78
79
50
29
11
1
{-# LANGUAGE OverloadedStrings #-} module Lichen.Diagnostics.Main where import System.Directory import Data.Aeson import Data.Aeson.Types (Pair) import Data.Aeson.Encode.Pretty (encodePretty) import Data.Semigroup ((<>)) import qualified Data.Text as T import qualified Data.Text.Lazy.Encoding as T.L.E import qualified Data.Text.Lazy.IO as T.L.IO import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BS.L import Text.Blaze.Html.Renderer.Utf8 import qualified Text.Blaze.Html5 as H import Control.Monad.Reader import Control.Monad.Except import Options.Applicative import Lichen.Util import Lichen.Error import Lichen.Config import Lichen.Languages import Lichen.Diagnostics.Config import Lichen.Diagnostics.Render diagnosticsJSON :: Language -> FilePath -> Erring Pair diagnosticsJSON (Language _ _ _ lr pr) p = do src <- liftIO $ BS.readFile p tokens <- lr p src nodes <- pr p src return $ T.pack p .= object [ "tokens" .= toJSON tokens , "nodes" .= toJSON nodes ] diagnosticsHTML :: Language -> FilePath -> Erring H.Html diagnosticsHTML (Language _ _ _ lr _) p = do src <- liftIO $ BS.readFile p tokens <- lr p src tokensPage <- liftIO $ renderTokens p tokens return $ renderPage tokensPage parseOptions :: Config -> Parser Config parseOptions dc = Config <$> strOption (long "config-file" <> short 'c' <> metavar "PATH" <> showDefault <> value (configFile dc) <> help "Configuration file") <*> (languageChoice (language dc) <$> (optional . strOption $ long "language" <> short 'l' <> metavar "LANG" <> help "Language of student code")) <*> strOption (long "output-format" <> short 'f' <> metavar "FORMAT" <> showDefault <> value (outputFormat dc) <> help "Output format") <*> many (argument str (metavar "SOURCE")) realMain :: Config -> IO () realMain ic = do iopts <- liftIO . execParser $ opts ic mcsrc <- readSafe BS.L.readFile Nothing $ configFile iopts options <- case mcsrc of Just csrc -> do c <- case eitherDecode csrc of Left e -> (printError . JSONDecodingError $ T.pack e) >> pure ic Right t -> pure t liftIO . execParser $ opts c Nothing -> pure iopts flip runConfigured options $ do config <- ask if null $ sourceFiles config then throwError $ InvocationError "No source files provided" else do ps <- liftIO . mapM canonicalizePath $ sourceFiles config case outputFormat config of "html" -> do page <- lift . diagnosticsHTML (language config) $ head ps liftIO . T.L.IO.putStrLn . T.L.E.decodeUtf8 $ renderHtml page "dense" -> do os <- lift $ mapM (diagnosticsJSON (language config)) ps liftIO . T.L.IO.putStrLn . T.L.E.decodeUtf8 . encode $ object os _ -> do os <- lift $ mapM (diagnosticsJSON (language config)) ps liftIO . T.L.IO.putStrLn . T.L.E.decodeUtf8 . encodePretty $ object os where opts c = info (helper <*> parseOptions c) (fullDesc <> progDesc "Output diagnostic information about source files" <> header "diagnostics - output assorted information about source code")
Submitty/AnalysisTools
src/Lichen/Diagnostics/Main.hs
bsd-3-clause
3,572
0
24
1,084
1,052
530
522
71
6
module JDec.Class.Typesafe.MethodHandle ( MethodHandle(GetFieldMethodHandle, GetStaticMethodHandle, PutFieldMethodHandle, PutStaticMethodHandle, InvokeVirtualMethodHandle, InvokeStaticMethodHandle, InvokeSpecialMethodHandle, NewInvokeSpecialMethodHandle, InvokeInterfaceMethodHandle), getFieldRef, getStaticFieldRef, putFieldRef, putStaticFieldRef, invokeVirtualMethodRef, invokeStaticMethodRef, invokeSpecialMethodRef, newInvokeSpecialMethodRef, invokeInterfaceMethodRef ) where import JDec.Class.Typesafe.FieldRef(FieldRef) import JDec.Class.Typesafe.MethodRef(MethodRef) import JDec.Class.Typesafe.InterfaceMethodRef(InterfaceMethodRef) -- | A method handle. Method handle's kind indicates an equivalent instruction sequence of the method handle (it's bytecode behavior). Here C is the class or interface in which the field or method is to be found, f is the name of the field, m is the name of the method, T is the descriptor of the field or method, A* is the argument type sequence of the method data MethodHandle = GetFieldMethodHandle { -- ^ getfield C.f:T getFieldRef :: FieldRef -- ^ A reference to a field. } | GetStaticMethodHandle { -- ^ getstatic C.f:T getStaticFieldRef :: FieldRef -- ^ A reference to a field. } | PutFieldMethodHandle { -- ^ putfield C.f:T putFieldRef :: FieldRef -- ^ A reference to a field. } | PutStaticMethodHandle { -- ^ putstatic C.f:T putStaticFieldRef :: FieldRef -- ^ A reference to a field. } | InvokeVirtualMethodHandle { -- ^ invokevirtual C.m:(A*)T invokeVirtualMethodRef :: MethodRef -- ^ A reference to a class method. The name of the method must not be <init> or <clinit>. } | InvokeStaticMethodHandle { -- ^ invokestatic C.m:(A*)T invokeStaticMethodRef :: MethodRef -- ^ A reference to a class method. The name of the method must not be <init> or <clinit>. } | InvokeSpecialMethodHandle { -- ^ invokespecial C.m:(A*)T invokeSpecialMethodRef :: MethodRef -- ^ A reference to a class method. The name of the method must not be <init> or <clinit>. } | NewInvokeSpecialMethodHandle { -- ^ new C; dup; invokespecial C.<init>:(A*)void newInvokeSpecialMethodRef :: MethodRef -- ^ A reference to a class method. The name of the method must be <init>. } | InvokeInterfaceMethodHandle { -- ^ invokeinterface C.m:(A*)T invokeInterfaceMethodRef :: InterfaceMethodRef -- ^ A reference to an interface method. The name of the method must not be <init> or <clinit>. } deriving Show
rel-eng/jdec
src/JDec/Class/Typesafe/MethodHandle.hs
bsd-3-clause
2,488
0
8
396
221
156
65
35
0
----------------------------------------------------------------------------- -- | -- Module : XMonad.Util.StringProp -- Description : Internal utility functions for storing Strings with the root window. -- Copyright : (c) Nicolas Pouillard 2009 -- License : BSD-style (see LICENSE) -- -- Maintainer : Nicolas Pouillard <[email protected]> -- Stability : unstable -- Portability : unportable -- -- Internal utility functions for storing Strings with the root window. -- -- Used for global state like IORefs with string keys, but more latency, -- persistent between xmonad restarts. module XMonad.Util.StringProp ( StringProp, getStringProp, setStringProp, getStringListProp, setStringListProp, ) where import XMonad import Foreign.C.String (castCCharToChar,castCharToCChar) type StringProp = String withStringProp :: (MonadIO m) => StringProp -> Display -> (Window -> Atom -> m b) -> m b withStringProp prop dpy f = do rootw <- io $ rootWindow dpy $ defaultScreen dpy a <- io $ internAtom dpy prop False f rootw a -- | Set the value of a string property. setStringProp :: (MonadIO m) => Display -> StringProp -> [Char] -> m () setStringProp dpy prop string = withStringProp prop dpy $ \rootw a -> io $ changeProperty8 dpy rootw a a propModeReplace $ map castCharToCChar string -- | Get the name of a string property and returns it as a 'Maybe'. getStringProp :: (MonadIO m) => Display -> StringProp -> m (Maybe [Char]) getStringProp dpy prop = withStringProp prop dpy $ \rootw a -> do p <- io $ getWindowProperty8 dpy a rootw return $ map castCCharToChar <$> p -- | Given a property name, returns its contents as a list. It uses the empty -- list as default value. getStringListProp :: (MonadIO m) => Display -> StringProp -> m [String] getStringListProp dpy prop = maybe [] words <$> getStringProp dpy prop -- | Given a property name and a list, sets the value of this property with -- the list given as argument. setStringListProp :: (MonadIO m) => Display -> StringProp -> [String] -> m () setStringListProp dpy prop str = setStringProp dpy prop (unwords str)
xmonad/xmonad-contrib
XMonad/Util/StringProp.hs
bsd-3-clause
2,150
0
12
406
462
246
216
25
1
-- | This module implements QuickCheck tests to test the Series module. module Tests where import Test.QuickCheck import Series -- I import (~==) to enable use of approximate equality on test cases. import Data.AEq(AEq, (~==)) import Data.List (sort, nub) -- |The first and second examples given in the assignment pdf. This should return True. example1and2 :: Bool example1and2 = let fstNum = first 1 growthRate = grow fstNum 5062.5 ss = series fstNum growthRate ssRounded = seriesN fstNum growthRate 5 in fstNum ~== 1.62 && growthRate ~== 2.5 && take 5 ss ~== [1.62, 4.05, 6.561, 10.62882, 17.2186884] && ssRounded ~== [1.5, 4, 6.5, 10.75, 17.25] && special1 ssRounded ~== Right 6.5 && special2 1000 160 ssRounded ~== Right 6.5 -- |The length of a series with n elements, is at most n elements. -- (It can be less due to the series never generating new elements, -- such as 0.0 0.0 2.) prop_lengthOfSeriesN :: Double -> Double -> Int -> Property prop_lengthOfSeriesN fstNum growthRate len = len >= 0 ==> (length (seriesN fstNum growthRate len) <= len) -- |A list is sorted if all pairs of elements are. sorted :: Ord a => [a] -> Bool sorted [] = True sorted [_] = True sorted (x : y : xs) = x <= y && sorted (y : xs) -- |Property that states that every series of N length should be sorted prop_sorted :: Double -> Double -> Int -> Bool prop_sorted fstNum growthRate len = sorted $ seriesN fstNum growthRate len -- |Check whether something is part of a list using approximately equals. aElem :: AEq a => a -> [a] -> Bool aElem = any . (~==) -- |A number is rounded to a quarter, when after removing the integral part -- it is either 0.0, 0.25, 0.5 or 0.75. isQuarter :: (AEq a, RealFrac a) => [a] -> Bool isQuarter = foldr (\ x -> (&&) ((x - fromIntegral (floor x :: Integer)) `aElem` [0.0, 0.25, 0.5, 0.75])) True -- |All numbers in an n-series should be rounded to quarters prop_quarters :: Double -> Double -> Int -> Property prop_quarters fstNum growthRate len = len >= 0 ==> isQuarter $ seriesN fstNum growthRate len -- |Takes the third largest element of a list, without doing any safety checks. third :: Ord a => [a] -> a third = head. tail . tail . reverse . sort -- |Checks that any series of length 3 has a third largest element and checks whether -- the error checking version is then equivalent to the naive version. prop_isThirdLargest :: Double -> Double -> Int -> Property prop_isThirdLargest fstNum growthRate len = let ss = seriesN fstNum growthRate len in length ss >= 3 ==> case special1 ss of Left _ -> False -- We got an error message despite the list being length 3 Right x -> x == third ss -- |A series of N numbers should be equal to the same series filtered for duplicates. prop_isUnique :: Double -> Double -> Int -> Bool prop_isUnique fstNum growthRate len = let ss = seriesN fstNum growthRate len in ss == nub ss -- |Call QuickCheck with 5000 tests instead. quickCheck5000 :: Testable prop => prop -> IO () quickCheck5000 = quickCheckWith stdArgs { maxSuccess = 5000 } -- |Apply QuickCheck to all properties. quickCheckAllTests :: IO () quickCheckAllTests = do quickCheck example1and2 mapM_ quickCheck5000 [prop_lengthOfSeriesN, prop_quarters, prop_isThirdLargest ] quickCheck5000 prop_sorted quickCheck5000 prop_isUnique
nebasuke/Gamesys
src/Tests.hs
bsd-3-clause
3,623
0
17
947
827
438
389
60
2
{-# LANGUAGE TupleSections #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RecordWildCards #-} -- | Main stack tool entry point. module Main (main) where #ifndef HIDE_DEP_VERSIONS import qualified Build_stack #endif import Control.Exception import Control.Monad hiding (mapM, forM) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (local) import Control.Monad.Trans.Either (EitherT) import Control.Monad.Writer.Lazy (Writer) import Data.Attoparsec.Args (parseArgs, EscapingMode (Escaping)) import Data.Attoparsec.Interpreter (getInterpreterArgs) import qualified Data.ByteString.Lazy as L import Data.List import qualified Data.Map as Map import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Data.Traversable import Data.Typeable (Typeable) import Data.Version (showVersion) import System.Process.Read #ifdef USE_GIT_INFO import Development.GitRev (gitCommitCount, gitHash) #endif import Distribution.System (buildArch, buildPlatform) import Distribution.Text (display) import GHC.IO.Encoding (mkTextEncoding, textEncodingName) import Lens.Micro import Options.Applicative import Options.Applicative.Help (errorHelp, stringChunk, vcatChunks) import Options.Applicative.Builder.Extra import Options.Applicative.Complicated #ifdef USE_GIT_INFO import Options.Applicative.Simple (simpleVersion) #endif import Options.Applicative.Types (ParserHelp(..)) import Path import Path.IO import qualified Paths_stack as Meta import Prelude hiding (pi, mapM) import Stack.Build import Stack.BuildPlan import Stack.Clean (CleanOpts, clean) import Stack.Config import Stack.ConfigCmd as ConfigCmd import Stack.Constants import Stack.Coverage import qualified Stack.Docker as Docker import Stack.Dot import Stack.Exec import Stack.GhcPkg (findGhcPkgField) import qualified Stack.Nix as Nix import Stack.Fetch import Stack.FileWatch import Stack.Ghci import Stack.Hoogle import qualified Stack.IDE as IDE import qualified Stack.Image as Image import Stack.Init import Stack.New import Stack.Options.BuildParser import Stack.Options.CleanParser import Stack.Options.DockerParser import Stack.Options.DotParser import Stack.Options.ExecParser import Stack.Options.GhciParser import Stack.Options.GlobalParser import Stack.Options.HpcReportParser import Stack.Options.NewParser import Stack.Options.NixParser import Stack.Options.SolverParser import Stack.Options.Utils import qualified Stack.PackageIndex import qualified Stack.Path import Stack.Runners import Stack.SDist (getSDistTarball, checkSDistTarball, checkSDistTarball') import Stack.SetupCmd import qualified Stack.Sig as Sig import Stack.Solver (solveExtraDeps) import Stack.Types.Version import Stack.Types.Config import Stack.Types.Compiler import Stack.Types.Resolver import Stack.Types.Nix import Stack.Types.StackT import Stack.Upgrade import qualified Stack.Upload as Upload import qualified System.Directory as D import System.Environment (getProgName, getArgs, withArgs) import System.Exit import System.FilePath (pathSeparator) import System.IO (hIsTerminalDevice, stderr, stdin, stdout, hSetBuffering, BufferMode(..), hPutStrLn, Handle, hGetEncoding, hSetEncoding) -- | Change the character encoding of the given Handle to transliterate -- on unsupported characters instead of throwing an exception hSetTranslit :: Handle -> IO () hSetTranslit h = do menc <- hGetEncoding h case fmap textEncodingName menc of Just name | '/' `notElem` name -> do enc' <- mkTextEncoding $ name ++ "//TRANSLIT" hSetEncoding h enc' _ -> return () versionString' :: String #ifdef USE_GIT_INFO versionString' = concat $ concat [ [$(simpleVersion Meta.version)] -- Leave out number of commits for --depth=1 clone -- See https://github.com/commercialhaskell/stack/issues/792 , [" (" ++ commitCount ++ " commits)" | commitCount /= ("1"::String) && commitCount /= ("UNKNOWN" :: String)] , [" ", display buildArch] , [depsString] ] where commitCount = $gitCommitCount #else versionString' = showVersion Meta.version ++ ' ' : display buildArch ++ depsString where #endif #ifdef HIDE_DEP_VERSIONS depsString = " hpack-" ++ VERSION_hpack #else depsString = "\nCompiled with:\n" ++ unlines (map ("- " ++) Build_stack.deps) #endif main :: IO () main = do -- Line buffer the output by default, particularly for non-terminal runs. -- See https://github.com/commercialhaskell/stack/pull/360 hSetBuffering stdout LineBuffering hSetBuffering stdin LineBuffering hSetBuffering stderr LineBuffering hSetTranslit stdout hSetTranslit stderr args <- getArgs progName <- getProgName isTerminal <- hIsTerminalDevice stdout execExtraHelp args Docker.dockerHelpOptName (dockerOptsParser False) ("Only showing --" ++ Docker.dockerCmdName ++ "* options.") execExtraHelp args Nix.nixHelpOptName (nixOptsParser False) ("Only showing --" ++ Nix.nixCmdName ++ "* options.") eGlobalRun <- try $ commandLineHandler progName False case eGlobalRun of Left (exitCode :: ExitCode) -> throwIO exitCode Right (globalMonoid,run) -> do let global = globalOptsFromMonoid isTerminal globalMonoid when (globalLogLevel global == LevelDebug) $ hPutStrLn stderr versionString' case globalReExecVersion global of Just expectVersion -> do expectVersion' <- parseVersionFromString expectVersion unless (checkVersion MatchMinor expectVersion' (fromCabalVersion Meta.version)) $ throwIO $ InvalidReExecVersion expectVersion (showVersion Meta.version) _ -> return () run global `catch` \e -> -- This special handler stops "stack: " from being printed before the -- exception case fromException e of Just ec -> exitWith ec Nothing -> do printExceptionStderr e exitFailure -- Vertically combine only the error component of the first argument with the -- error component of the second. vcatErrorHelp :: ParserHelp -> ParserHelp -> ParserHelp vcatErrorHelp (ParserHelp e1 _ _ _ _) (ParserHelp e2 h2 u2 b2 f2) = ParserHelp (vcatChunks [e2, e1]) h2 u2 b2 f2 commandLineHandler :: String -> Bool -> IO (GlobalOptsMonoid, GlobalOpts -> IO ()) commandLineHandler progName isInterpreter = complicatedOptions Meta.version (Just versionString') VERSION_hpack "stack - The Haskell Tool Stack" "" "stack's documentation is available at https://docs.haskellstack.org/" (globalOpts OuterGlobalOpts) (Just failureCallback) addCommands where failureCallback f args = case stripPrefix "Invalid argument" (fst (renderFailure f "")) of Just _ -> if isInterpreter then parseResultHandler args f else secondaryCommandHandler args f >>= interpreterHandler args Nothing -> parseResultHandler args f parseResultHandler args f = if isInterpreter then do let hlp = errorHelp $ stringChunk (unwords ["Error executing interpreter command:" , progName , unwords args]) handleParseResult (overFailure (vcatErrorHelp hlp) (Failure f)) else handleParseResult (Failure f) addCommands = do unless isInterpreter (do addBuildCommand' "build" "Build the package(s) in this directory/configuration" buildCmd (buildOptsParser Build) addBuildCommand' "install" "Shortcut for 'build --copy-bins'" buildCmd (buildOptsParser Install) addCommand' "uninstall" "DEPRECATED: This command performs no actions, and is present for documentation only" uninstallCmd (many $ strArgument $ metavar "IGNORED") addBuildCommand' "test" "Shortcut for 'build --test'" buildCmd (buildOptsParser Test) addBuildCommand' "bench" "Shortcut for 'build --bench'" buildCmd (buildOptsParser Bench) addBuildCommand' "haddock" "Shortcut for 'build --haddock'" buildCmd (buildOptsParser Haddock) addCommand' "new" "Create a new project from a template. Run `stack templates' to see available templates." newCmd newOptsParser addCommand' "templates" "List the templates available for `stack new'." templatesCmd (pure ()) addCommand' "init" "Create stack project config from cabal or hpack package specifications" initCmd initOptsParser addCommand' "solver" "Add missing extra-deps to stack project config" solverCmd solverOptsParser addCommand' "setup" "Get the appropriate GHC for your project" setupCmd setupParser addCommand' "path" "Print out handy path information" pathCmd Stack.Path.pathParser addCommand' "unpack" "Unpack one or more packages locally" unpackCmd (some $ strArgument $ metavar "PACKAGE") addCommand' "update" "Update the package index" updateCmd (pure ()) addCommand' "upgrade" "Upgrade to the latest stack" upgradeCmd upgradeOpts addCommand' "upload" "Upload a package to Hackage" uploadCmd ((,,,,) <$> many (strArgument $ metavar "TARBALL/DIR") <*> optional pvpBoundsOption <*> ignoreCheckSwitch <*> switch (long "no-signature" <> help "Do not sign & upload signatures") <*> strOption (long "sig-server" <> metavar "URL" <> showDefault <> value "https://sig.commercialhaskell.org" <> help "URL")) addCommand' "sdist" "Create source distribution tarballs" sdistCmd ((,,,,) <$> many (strArgument $ metavar "DIR") <*> optional pvpBoundsOption <*> ignoreCheckSwitch <*> switch (long "sign" <> help "Sign & upload signatures") <*> strOption (long "sig-server" <> metavar "URL" <> showDefault <> value "https://sig.commercialhaskell.org" <> help "URL")) addCommand' "dot" "Visualize your project's dependency graph using Graphviz dot" dotCmd (dotOptsParser False) -- Default for --external is False. addCommand' "ghc" "Run ghc" execCmd (execOptsParser $ Just ExecGhc) addCommand' "hoogle" ("Run hoogle, the Haskell API search engine. Use 'stack exec' syntax " ++ "to pass Hoogle arguments, e.g. stack hoogle -- --count=20") hoogleCmd ((,,) <$> many (strArgument (metavar "ARG")) <*> boolFlags True "setup" "If needed: install hoogle, build haddocks and generate a hoogle database" idm <*> switch (long "rebuild" <> help "Rebuild the hoogle database")) ) -- These are the only commands allowed in interpreter mode as well addCommand' "exec" "Execute a command" execCmd (execOptsParser Nothing) addGhciCommand' "ghci" "Run ghci in the context of package(s) (experimental)" ghciCmd ghciOptsParser addGhciCommand' "repl" "Run ghci in the context of package(s) (experimental) (alias for 'ghci')" ghciCmd ghciOptsParser addCommand' "runghc" "Run runghc" execCmd (execOptsParser $ Just ExecRunGhc) addCommand' "runhaskell" "Run runghc (alias for 'runghc')" execCmd (execOptsParser $ Just ExecRunGhc) unless isInterpreter (do addCommand' "eval" "Evaluate some haskell code inline. Shortcut for 'stack exec ghc -- -e CODE'" evalCmd (evalOptsParser "CODE") addCommand' "clean" "Clean the local packages" cleanCmd cleanOptsParser addCommand' "list-dependencies" "List the dependencies" listDependenciesCmd listDepsOptsParser addCommand' "query" "Query general build information (experimental)" queryCmd (many $ strArgument $ metavar "SELECTOR...") addSubCommands' "ide" "IDE-specific commands" (do addCommand' "packages" "List all available local loadable packages" idePackagesCmd (pure ()) addCommand' "targets" "List all available stack targets" ideTargetsCmd (pure ())) addSubCommands' Docker.dockerCmdName "Subcommands specific to Docker use" (do addCommand' Docker.dockerPullCmdName "Pull latest version of Docker image from registry" dockerPullCmd (pure ()) addCommand' "reset" "Reset the Docker sandbox" dockerResetCmd (switch (long "keep-home" <> help "Do not delete sandbox's home directory")) addCommand' Docker.dockerCleanupCmdName "Clean up Docker images and containers" dockerCleanupCmd dockerCleanupOptsParser) addSubCommands' ConfigCmd.cfgCmdName "Subcommands specific to modifying stack.yaml files" (addCommand' ConfigCmd.cfgCmdSetName "Sets a field in the project's stack.yaml to value" cfgSetCmd configCmdSetParser) addSubCommands' Image.imgCmdName "Subcommands specific to imaging" (addCommand' Image.imgDockerCmdName "Build a Docker image for the project" imgDockerCmd ((,) <$> boolFlags True "build" "building the project before creating the container" idm <*> many (textOption (long "image" <> help "A specific container image name to build")))) addSubCommands' "hpc" "Subcommands specific to Haskell Program Coverage" (addCommand' "report" "Generate unified HPC coverage report from tix files and project targets" hpcReportCmd hpcReportOptsParser) ) where ignoreCheckSwitch = switch (long "ignore-check" <> help "Do not check package for common mistakes") -- addCommand hiding global options addCommand' :: String -> String -> (a -> GlobalOpts -> IO ()) -> Parser a -> AddCommand addCommand' cmd title constr = addCommand cmd title globalFooter constr (globalOpts OtherCmdGlobalOpts) addSubCommands' :: String -> String -> AddCommand -> AddCommand addSubCommands' cmd title = addSubCommands cmd title globalFooter (globalOpts OtherCmdGlobalOpts) -- Additional helper that hides global options and shows build options addBuildCommand' :: String -> String -> (a -> GlobalOpts -> IO ()) -> Parser a -> AddCommand addBuildCommand' cmd title constr = addCommand cmd title globalFooter constr (globalOpts BuildCmdGlobalOpts) -- Additional helper that hides global options and shows some ghci options addGhciCommand' :: String -> String -> (a -> GlobalOpts -> IO ()) -> Parser a -> AddCommand addGhciCommand' cmd title constr = addCommand cmd title globalFooter constr (globalOpts GhciCmdGlobalOpts) globalOpts :: GlobalOptsContext -> Parser GlobalOptsMonoid globalOpts kind = extraHelpOption hide progName (Docker.dockerCmdName ++ "*") Docker.dockerHelpOptName <*> extraHelpOption hide progName (Nix.nixCmdName ++ "*") Nix.nixHelpOptName <*> globalOptsParser kind (if isInterpreter then Just $ LevelOther "silent" else Nothing) where hide = kind /= OuterGlobalOpts globalFooter = "Run 'stack --help' for global options that apply to all subcommands." type AddCommand = EitherT (GlobalOpts -> IO ()) (Writer (Mod CommandFields (GlobalOpts -> IO (), GlobalOptsMonoid))) () -- | fall-through to external executables in `git` style if they exist -- (i.e. `stack something` looks for `stack-something` before -- failing with "Invalid argument `something'") secondaryCommandHandler :: [String] -> ParserFailure ParserHelp -> IO (ParserFailure ParserHelp) secondaryCommandHandler args f = -- don't even try when the argument looks like a path or flag if elem pathSeparator cmd || "-" `isPrefixOf` head args then return f else do mExternalExec <- D.findExecutable cmd case mExternalExec of Just ex -> do menv <- getEnvOverride buildPlatform -- TODO show the command in verbose mode -- hPutStrLn stderr $ unwords $ -- ["Running", "[" ++ ex, unwords (tail args) ++ "]"] _ <- runNoLoggingT (exec menv ex (tail args)) return f Nothing -> return $ fmap (vcatErrorHelp (noSuchCmd cmd)) f where -- FIXME this is broken when any options are specified before the command -- e.g. stack --verbosity silent cmd cmd = stackProgName ++ "-" ++ head args noSuchCmd name = errorHelp $ stringChunk ("Auxiliary command not found in path `" ++ name ++ "'") interpreterHandler :: Monoid t => [String] -> ParserFailure ParserHelp -> IO (GlobalOptsMonoid, (GlobalOpts -> IO (), t)) interpreterHandler args f = do -- args can include top-level config such as --extra-lib-dirs=... (set by -- nix-shell) - we need to find the first argument which is a file, everything -- afterwards is an argument to the script, everything before is an argument -- to Stack (stackArgs, fileArgs) <- spanM (fmap not . D.doesFileExist) args case fileArgs of (file:fileArgs') -> runInterpreterCommand file stackArgs fileArgs' [] -> parseResultHandler (errorCombine (noSuchFile firstArg)) where firstArg = head args spanM _ [] = return ([], []) spanM p xs@(x:xs') = do r <- p x if r then do (ys, zs) <- spanM p xs' return (x:ys, zs) else return ([], xs) -- if the first argument contains a path separator then it might be a file, -- or a Stack option referencing a file. In that case we only show the -- interpreter error message and exclude the command related error messages. errorCombine = if pathSeparator `elem` firstArg then overrideErrorHelp else vcatErrorHelp overrideErrorHelp (ParserHelp e1 _ _ _ _) (ParserHelp _ h2 u2 b2 f2) = ParserHelp e1 h2 u2 b2 f2 parseResultHandler fn = handleParseResult (overFailure fn (Failure f)) noSuchFile name = errorHelp $ stringChunk ("File does not exist or is not a regular file `" ++ name ++ "'") runInterpreterCommand path stackArgs fileArgs = do progName <- getProgName iargs <- getInterpreterArgs path let parseCmdLine = commandLineHandler progName True separator = if "--" `elem` iargs then [] else ["--"] cmdArgs = stackArgs ++ iargs ++ separator ++ path : fileArgs -- TODO show the command in verbose mode -- hPutStrLn stderr $ unwords $ -- ["Running", "[" ++ progName, unwords cmdArgs ++ "]"] (a,b) <- withArgs cmdArgs parseCmdLine return (a,(b,mempty)) pathCmd :: [Text] -> GlobalOpts -> IO () pathCmd keys go = withBuildConfig go (Stack.Path.path keys) setupCmd :: SetupCmdOpts -> GlobalOpts -> IO () setupCmd sco@SetupCmdOpts{..} go@GlobalOpts{..} = do lc <- loadConfigWithOpts go when (scoUpgradeCabal && nixEnable (configNix (lcConfig lc))) $ do throwIO UpgradeCabalUnusable withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk -> do let getCompilerVersion = loadCompilerVersion go lc runStackTGlobal (lcConfig lc) go $ Docker.reexecWithOptionalContainer (lcProjectRoot lc) Nothing (runStackTGlobal (lcConfig lc) go $ Nix.reexecWithOptionalShell (lcProjectRoot lc) getCompilerVersion $ runStackTGlobal () go $ do (wantedCompiler, compilerCheck, mstack) <- case scoCompilerVersion of Just v -> return (v, MatchMinor, Nothing) Nothing -> do bc <- lcLoadBuildConfig lc globalCompiler return ( view wantedCompilerVersionL bc , configCompilerCheck (lcConfig lc) , Just $ view stackYamlL bc ) miniConfig <- loadMiniConfig (lcConfig lc) runStackTGlobal miniConfig go $ setup sco wantedCompiler compilerCheck mstack ) Nothing (Just $ munlockFile lk) cleanCmd :: CleanOpts -> GlobalOpts -> IO () cleanCmd opts go = withBuildConfigAndLock go (const (clean opts)) -- | Helper for build and install commands buildCmd :: BuildOptsCLI -> GlobalOpts -> IO () buildCmd opts go = do when (any (("-prof" `elem`) . either (const []) id . parseArgs Escaping) (boptsCLIGhcOptions opts)) $ do hPutStrLn stderr "When building with stack, you should not use the -prof GHC option" hPutStrLn stderr "Instead, please use --library-profiling and --executable-profiling" hPutStrLn stderr "See: https://github.com/commercialhaskell/stack/issues/1015" error "-prof GHC option submitted" case boptsCLIFileWatch opts of FileWatchPoll -> fileWatchPoll stderr inner FileWatch -> fileWatch stderr inner NoFileWatch -> inner $ const $ return () where inner setLocalFiles = withBuildConfigAndLock go' $ \lk -> Stack.Build.build setLocalFiles lk opts -- Read the build command from the CLI and enable it to run go' = case boptsCLICommand opts of Test -> set (globalOptsBuildOptsMonoidL.buildOptsMonoidTestsL) (Just True) go Haddock -> set (globalOptsBuildOptsMonoidL.buildOptsMonoidHaddockL) (Just True) go Bench -> set (globalOptsBuildOptsMonoidL.buildOptsMonoidBenchmarksL) (Just True) go Install -> set (globalOptsBuildOptsMonoidL.buildOptsMonoidInstallExesL) (Just True) go Build -> go -- Default case is just Build uninstallCmd :: [String] -> GlobalOpts -> IO () uninstallCmd _ go = withConfigAndLock go $ do $logError "stack does not manage installations in global locations" $logError "The only global mutation stack performs is executable copying" $logError "For the default executable destination, please run 'stack path --local-bin-path'" -- | Unpack packages to the filesystem unpackCmd :: [String] -> GlobalOpts -> IO () unpackCmd names go = withConfigAndLock go $ do menv <- getMinimalEnvOverride mMiniBuildPlan <- case globalResolver go of Nothing -> return Nothing Just ar -> fmap Just $ do r <- makeConcreteResolver ar case r of ResolverSnapshot snapName -> do config <- view configL miniConfig <- loadMiniConfig config runInnerStackT miniConfig (loadMiniBuildPlan snapName) ResolverCompiler _ -> error "unpack does not work with compiler resolvers" ResolverCustom _ _ -> error "unpack does not work with custom resolvers" Stack.Fetch.unpackPackages menv mMiniBuildPlan "." names -- | Update the package index updateCmd :: () -> GlobalOpts -> IO () updateCmd () go = withConfigAndLock go $ getMinimalEnvOverride >>= Stack.PackageIndex.updateAllIndices upgradeCmd :: UpgradeOpts -> GlobalOpts -> IO () upgradeCmd upgradeOpts' go = withGlobalConfigAndLock go $ upgrade (globalConfigMonoid go) (globalResolver go) #ifdef USE_GIT_INFO (find (/= "UNKNOWN") [$gitHash]) #else Nothing #endif upgradeOpts' -- | Upload to Hackage uploadCmd :: ([String], Maybe PvpBounds, Bool, Bool, String) -> GlobalOpts -> IO () uploadCmd ([], _, _, _, _) _ = error "To upload the current package, please run 'stack upload .'" uploadCmd (args, mpvpBounds, ignoreCheck, don'tSign, sigServerUrl) go = do let partitionM _ [] = return ([], []) partitionM f (x:xs) = do r <- f x (as, bs) <- partitionM f xs return $ if r then (x:as, bs) else (as, x:bs) (files, nonFiles) <- partitionM D.doesFileExist args (dirs, invalid) <- partitionM D.doesDirectoryExist nonFiles unless (null invalid) $ error $ "stack upload expects a list sdist tarballs or cabal directories. Can't find " ++ show invalid let getUploader :: (HasConfig config) => StackT config IO Upload.Uploader getUploader = do config <- view configL liftIO $ Upload.mkUploader config Upload.defaultUploadSettings withBuildConfigAndLock go $ \_ -> do uploader <- getUploader unless ignoreCheck $ mapM_ (resolveFile' >=> checkSDistTarball) files forM_ files (\file -> do tarFile <- resolveFile' file liftIO (Upload.upload uploader (toFilePath tarFile)) unless don'tSign (void $ Sig.sign sigServerUrl tarFile)) unless (null dirs) $ forM_ dirs $ \dir -> do pkgDir <- resolveDir' dir (tarName, tarBytes) <- getSDistTarball mpvpBounds pkgDir unless ignoreCheck $ checkSDistTarball' tarName tarBytes liftIO $ Upload.uploadBytes uploader tarName tarBytes tarPath <- parseRelFile tarName unless don'tSign (void $ Sig.signTarBytes sigServerUrl tarPath tarBytes) sdistCmd :: ([String], Maybe PvpBounds, Bool, Bool, String) -> GlobalOpts -> IO () sdistCmd (dirs, mpvpBounds, ignoreCheck, sign, sigServerUrl) go = withBuildConfig go $ do -- No locking needed. -- If no directories are specified, build all sdist tarballs. dirs' <- if null dirs then liftM Map.keys getLocalPackages else mapM resolveDir' dirs forM_ dirs' $ \dir -> do (tarName, tarBytes) <- getSDistTarball mpvpBounds dir distDir <- distDirFromDir dir tarPath <- (distDir </>) <$> parseRelFile tarName ensureDir (parent tarPath) liftIO $ L.writeFile (toFilePath tarPath) tarBytes unless ignoreCheck (checkSDistTarball tarPath) $logInfo $ "Wrote sdist tarball to " <> T.pack (toFilePath tarPath) when sign (void $ Sig.sign sigServerUrl tarPath) -- | Execute a command. execCmd :: ExecOpts -> GlobalOpts -> IO () execCmd ExecOpts {..} go@GlobalOpts{..} = case eoExtra of ExecOptsPlain -> do (cmd, args) <- case (eoCmd, eoArgs) of (ExecCmd cmd, args) -> return (cmd, args) (ExecGhc, args) -> return ("ghc", args) (ExecRunGhc, args) -> return ("runghc", args) lc <- liftIO $ loadConfigWithOpts go withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk -> do let getCompilerVersion = loadCompilerVersion go lc runStackTGlobal (lcConfig lc) go $ Docker.reexecWithOptionalContainer (lcProjectRoot lc) -- Unlock before transferring control away, whether using docker or not: (Just $ munlockFile lk) (runStackTGlobal (lcConfig lc) go $ do config <- view configL menv <- liftIO $ configEnvOverride config plainEnvSettings Nix.reexecWithOptionalShell (lcProjectRoot lc) getCompilerVersion (runStackTGlobal (lcConfig lc) go $ exec menv cmd args)) Nothing Nothing -- Unlocked already above. ExecOptsEmbellished {..} -> withBuildConfigAndLock go $ \lk -> do let targets = concatMap words eoPackages unless (null targets) $ Stack.Build.build (const $ return ()) lk defaultBuildOptsCLI { boptsCLITargets = map T.pack targets } config <- view configL menv <- liftIO $ configEnvOverride config eoEnvSettings (cmd, args) <- case (eoCmd, eoArgs) of (ExecCmd cmd, args) -> return (cmd, args) (ExecGhc, args) -> getGhcCmd "" menv eoPackages args -- NOTE: this won't currently work for GHCJS, because it doesn't have -- a runghcjs binary. It probably will someday, though. (ExecRunGhc, args) -> getGhcCmd "run" menv eoPackages args munlockFile lk -- Unlock before transferring control away. exec menv cmd args where -- return the package-id of the first package in GHC_PACKAGE_PATH getPkgId menv wc name = do mId <- findGhcPkgField menv wc [] name "id" case mId of Just i -> return (head $ words (T.unpack i)) -- should never happen as we have already installed the packages _ -> error ("Could not find package id of package " ++ name) getPkgOpts menv wc pkgs = do ids <- mapM (getPkgId menv wc) pkgs return $ map ("-package-id=" ++) ids getGhcCmd prefix menv pkgs args = do wc <- view $ actualCompilerVersionL.whichCompilerL pkgopts <- getPkgOpts menv wc pkgs return (prefix ++ compilerExeName wc, pkgopts ++ args) -- | Evaluate some haskell code inline. evalCmd :: EvalOpts -> GlobalOpts -> IO () evalCmd EvalOpts {..} go@GlobalOpts {..} = execCmd execOpts go where execOpts = ExecOpts { eoCmd = ExecGhc , eoArgs = ["-e", evalArg] , eoExtra = evalExtra } -- | Run GHCi in the context of a project. ghciCmd :: GhciOpts -> GlobalOpts -> IO () ghciCmd ghciOpts go@GlobalOpts{..} = withBuildConfigAndLock go $ \lk -> do munlockFile lk -- Don't hold the lock while in the GHCI. bopts <- view buildOptsL -- override env so running of tests and benchmarks is disabled let boptsLocal = bopts { boptsTestOpts = (boptsTestOpts bopts) { toDisableRun = True } , boptsBenchmarkOpts = (boptsBenchmarkOpts bopts) { beoDisableRun = True } } local (set buildOptsL boptsLocal) (ghci ghciOpts) -- | List packages in the project. idePackagesCmd :: () -> GlobalOpts -> IO () idePackagesCmd () go = withBuildConfig go IDE.listPackages -- | List targets in the project. ideTargetsCmd :: () -> GlobalOpts -> IO () ideTargetsCmd () go = withBuildConfig go IDE.listTargets -- | Pull the current Docker image. dockerPullCmd :: () -> GlobalOpts -> IO () dockerPullCmd _ go@GlobalOpts{..} = do lc <- liftIO $ loadConfigWithOpts go -- TODO: can we eliminate this lock if it doesn't touch ~/.stack/? withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ -> runStackTGlobal (lcConfig lc) go $ Docker.preventInContainer Docker.pull -- | Reset the Docker sandbox. dockerResetCmd :: Bool -> GlobalOpts -> IO () dockerResetCmd keepHome go@GlobalOpts{..} = do lc <- liftIO (loadConfigWithOpts go) -- TODO: can we eliminate this lock if it doesn't touch ~/.stack/? withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ -> runStackTGlobal (lcConfig lc) go $ Docker.preventInContainer $ Docker.reset (lcProjectRoot lc) keepHome -- | Cleanup Docker images and containers. dockerCleanupCmd :: Docker.CleanupOpts -> GlobalOpts -> IO () dockerCleanupCmd cleanupOpts go@GlobalOpts{..} = do lc <- liftIO $ loadConfigWithOpts go -- TODO: can we eliminate this lock if it doesn't touch ~/.stack/? withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ -> runStackTGlobal (lcConfig lc) go $ Docker.preventInContainer $ Docker.cleanup cleanupOpts cfgSetCmd :: ConfigCmd.ConfigCmdSet -> GlobalOpts -> IO () cfgSetCmd co go@GlobalOpts{..} = withMiniConfigAndLock go (cfgCmdSet co) imgDockerCmd :: (Bool, [Text]) -> GlobalOpts -> IO () imgDockerCmd (rebuild,images) go@GlobalOpts{..} = do mProjectRoot <- lcProjectRoot <$> loadConfigWithOpts go withBuildConfigExt go Nothing (\lk -> do when rebuild $ Stack.Build.build (const (return ())) lk defaultBuildOptsCLI Image.stageContainerImageArtifacts mProjectRoot images) (Just $ Image.createContainerImageFromStage mProjectRoot images) -- | Project initialization initCmd :: InitOpts -> GlobalOpts -> IO () initCmd initOpts go = do pwd <- getCurrentDir withMiniConfigAndLock go (initProject IsInitCmd pwd initOpts (globalResolver go)) -- | Create a project directory structure and initialize the stack config. newCmd :: (NewOpts,InitOpts) -> GlobalOpts -> IO () newCmd (newOpts,initOpts) go@GlobalOpts{..} = withMiniConfigAndLock go $ do dir <- new newOpts (forceOverwrite initOpts) initProject IsNewCmd dir initOpts globalResolver -- | List the available templates. templatesCmd :: () -> GlobalOpts -> IO () templatesCmd _ go@GlobalOpts{..} = withConfigAndLock go listTemplates -- | Fix up extra-deps for a project solverCmd :: Bool -- ^ modify stack.yaml automatically? -> GlobalOpts -> IO () solverCmd fixStackYaml go = withBuildConfigAndLock go (\_ -> solveExtraDeps fixStackYaml) -- | Visualize dependencies dotCmd :: DotOpts -> GlobalOpts -> IO () dotCmd dotOpts go = withBuildConfigDot dotOpts go $ dot dotOpts -- | List the dependencies listDependenciesCmd :: ListDepsOpts -> GlobalOpts -> IO () listDependenciesCmd opts go = withBuildConfigDot (listDepsDotOpts opts) go $ listDependencies opts -- Plumbing for --test and --bench flags withBuildConfigDot :: DotOpts -> GlobalOpts -> StackT EnvConfig IO () -> IO () withBuildConfigDot opts go f = withBuildConfig go' f where go' = (if dotTestTargets opts then set (globalOptsBuildOptsMonoidL.buildOptsMonoidTestsL) (Just True) else id) $ (if dotBenchTargets opts then set (globalOptsBuildOptsMonoidL.buildOptsMonoidBenchmarksL) (Just True) else id) go -- | Query build information queryCmd :: [String] -> GlobalOpts -> IO () queryCmd selectors go = withBuildConfig go $ queryBuildInfo $ map T.pack selectors -- | Generate a combined HPC report hpcReportCmd :: HpcReportOpts -> GlobalOpts -> IO () hpcReportCmd hropts go = withBuildConfig go $ generateHpcReportForTargets hropts data MainException = InvalidReExecVersion String String | UpgradeCabalUnusable deriving (Typeable) instance Exception MainException instance Show MainException where show (InvalidReExecVersion expected actual) = concat [ "When re-executing '" , stackProgName , "' in a container, the incorrect version was found\nExpected: " , expected , "; found: " , actual] show UpgradeCabalUnusable = "--upgrade-cabal cannot be used when nix is activated"
deech/stack
src/main/Main.hs
bsd-3-clause
39,081
0
27
12,976
8,004
4,050
3,954
766
7
{-# language CPP #-} -- No documentation found for Chapter "ImageTiling" module Vulkan.Core10.Enums.ImageTiling (ImageTiling( IMAGE_TILING_OPTIMAL , IMAGE_TILING_LINEAR , IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT , .. )) where import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import GHC.Show (showsPrec) import Vulkan.Zero (Zero) import Foreign.Storable (Storable) import Data.Int (Int32) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) -- | VkImageTiling - Specifies the tiling arrangement of data in an image -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'Vulkan.Core10.Image.ImageCreateInfo', -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceImageFormatInfo2', -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceSparseImageFormatInfo2', -- 'Vulkan.Extensions.VK_NV_external_memory_capabilities.getPhysicalDeviceExternalImageFormatPropertiesNV', -- 'Vulkan.Core10.DeviceInitialization.getPhysicalDeviceImageFormatProperties', -- 'Vulkan.Core10.SparseResourceMemoryManagement.getPhysicalDeviceSparseImageFormatProperties' newtype ImageTiling = ImageTiling Int32 deriving newtype (Eq, Ord, Storable, Zero) -- | 'IMAGE_TILING_OPTIMAL' specifies optimal tiling (texels are laid out in -- an implementation-dependent arrangement, for more efficient memory -- access). pattern IMAGE_TILING_OPTIMAL = ImageTiling 0 -- | 'IMAGE_TILING_LINEAR' specifies linear tiling (texels are laid out in -- memory in row-major order, possibly with some padding on each row). pattern IMAGE_TILING_LINEAR = ImageTiling 1 -- | 'IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT' indicates that the image’s tiling -- is defined by a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#glossary-drm-format-modifier Linux DRM format modifier>. -- The modifier is specified at image creation with -- 'Vulkan.Extensions.VK_EXT_image_drm_format_modifier.ImageDrmFormatModifierListCreateInfoEXT' -- or -- 'Vulkan.Extensions.VK_EXT_image_drm_format_modifier.ImageDrmFormatModifierExplicitCreateInfoEXT', -- and /can/ be queried with -- 'Vulkan.Extensions.VK_EXT_image_drm_format_modifier.getImageDrmFormatModifierPropertiesEXT'. pattern IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT = ImageTiling 1000158000 {-# complete IMAGE_TILING_OPTIMAL, IMAGE_TILING_LINEAR, IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT :: ImageTiling #-} conNameImageTiling :: String conNameImageTiling = "ImageTiling" enumPrefixImageTiling :: String enumPrefixImageTiling = "IMAGE_TILING_" showTableImageTiling :: [(ImageTiling, String)] showTableImageTiling = [ (IMAGE_TILING_OPTIMAL , "OPTIMAL") , (IMAGE_TILING_LINEAR , "LINEAR") , (IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT, "DRM_FORMAT_MODIFIER_EXT") ] instance Show ImageTiling where showsPrec = enumShowsPrec enumPrefixImageTiling showTableImageTiling conNameImageTiling (\(ImageTiling x) -> x) (showsPrec 11) instance Read ImageTiling where readPrec = enumReadPrec enumPrefixImageTiling showTableImageTiling conNameImageTiling ImageTiling
expipiplus1/vulkan
src/Vulkan/Core10/Enums/ImageTiling.hs
bsd-3-clause
3,479
1
10
584
336
209
127
-1
-1
{-# LANGUAGE ScopedTypeVariables, FlexibleContexts, OverlappingInstances, GADTs, RecordWildCards, TypeFamilies #-} module YaLedger.Reports.Turnovers where import YaLedger.Reports.API data Turnovers = Turnovers data TOptions = TNoZeros | TLedgerBalances | TBothBalances | TShowTotals | TShowSaldo | Common CommonFlags deriving (Eq) instance ReportClass Turnovers where type Options Turnovers = TOptions type Parameters Turnovers = Maybe Path defaultOptions Turnovers = [] reportHelp _ = "Show debit/credit, and, optionally, total turnovers for each account." reportOptions _ = [Option "l" ["ledger"] (NoArg TLedgerBalances) "Show ledger balances instead of available balances", Option "b" ["both"] (NoArg TBothBalances) "Show both available and ledger balances", Option "z" ["no-zeros"] (NoArg TNoZeros) "Do not show accounts with zero balance", Option "t" ["show-totals"] (NoArg TShowTotals) "Show total turnovers", Option "s" ["show-saldo"] (NoArg TShowSaldo) "Show saldo (credit - debit)", Option "R" ["rategroup"] (ReqArg (Common . CRateGroup) "GROUP") "Use specified exchange rates group for account groups balances calculation, instead of default", Option "C" ["csv"] (OptArg (Common . CCSV) "SEPARATOR") "Output data in CSV format using given fields delimiter (semicolon by default)", Option "H" ["html"] (NoArg (Common CHTML)) "Output data in HTML format"] initReport _ options _ = setOutputFormat (commonFlags options) runReportL _ queries opts mbPath = turnoversL queries opts mbPath `catchWithSrcLoc` (\l (e :: InvalidPath) -> handler l e) `catchWithSrcLoc` (\l (e :: NoSuchRate) -> handler l e) runReport _ qry opts mbPath = turnoversL [qry] opts mbPath `catchWithSrcLoc` (\l (e :: InvalidPath) -> handler l e) `catchWithSrcLoc` (\l (e :: NoSuchRate) -> handler l e) data TRecord v = TRecord { trCredit :: v, trDebit :: v, trIncSaldo :: BalanceInfo v, trOutSaldo :: BalanceInfo v, trTotals :: Maybe v, trSaldo :: Maybe v } deriving (Eq, Show) commonFlags :: [TOptions] -> [CommonFlags] commonFlags opts = [flag | Common flag <- opts] sumTurnovers mbDate rgroup calcTotals calcSaldo ag list = do let c = agCurrency ag list' <- forM list $ \tr -> do cr' :# _ <- convert mbDate rgroup c (trCredit tr) dt' :# _ <- convert mbDate rgroup c (trDebit tr) inc' <- convertBalanceInfo mbDate rgroup c (trIncSaldo tr) out' <- convertBalanceInfo mbDate rgroup c (trOutSaldo tr) t' <- case trTotals tr of Nothing -> return Nothing Just t -> do x :# _ <- convert mbDate rgroup c t return (Just x) s <- case trSaldo tr of Nothing -> return Nothing Just s -> do x :# _ <- convert mbDate rgroup c s return (Just x) return $ TRecord { trCredit = cr', trDebit = dt', trIncSaldo = inc', trOutSaldo = out', trTotals = t', trSaldo = s } let credits = sum $ map trCredit list' debits = sum $ map trDebit list' inc = sumBalanceInfo c $ map trIncSaldo list' out = sumBalanceInfo c $ map trOutSaldo list' totals = if calcTotals then Just $ (sum $ map (fromJust . trTotals) list') :# c else Nothing saldo = if calcSaldo then Just $ (sum $ map (fromJust . trSaldo) list') :# c else Nothing return $ TRecord { trCredit = credits :# c, trDebit = debits :# c, trIncSaldo = inc, trOutSaldo = out, trTotals = totals, trSaldo = saldo } allTurnovers bqry calcTotals calcSaldo qry account = do cr :# c <- creditTurnovers qry account dt :# _ <- debitTurnovers qry account opts <- gets lsConfig incomingSaldo <- case qStart qry of Nothing -> return $ BalanceInfo (Just 0) (Just 0) Just start -> runAtomically $ getBalanceInfoAt (Just start) bqry account outgoingSaldo <- runAtomically $ getBalanceInfoAt (qEnd qry) bqry account return $ TRecord { trCredit = cr :# c, trDebit = dt :# c, trIncSaldo = balanceInfoSetCurrency incomingSaldo c, trOutSaldo = balanceInfoSetCurrency outgoingSaldo c, trTotals = if calcTotals then Just $ (cr + dt) :# c else Nothing , trSaldo = if calcSaldo then Just $ if isAssets opts (getAttrs account) then (dt - cr) :# c else (cr - dt) :# c else Nothing } noZeroTurns tr = case trTotals tr of Nothing -> isNotZero (trCredit tr) || isNotZero (trDebit tr) Just t -> isNotZero t turnoversL :: (Throws InvalidPath l, Throws NoSuchRate l, Throws InternalError l) => [Query] -> [TOptions] -> Maybe Path -> Ledger l () turnoversL queries options mbPath = do coa <- getCoAItemL mbPath case coa of Leaf {..} -> byOneAccount queries options leafData _ -> forM_ queries $ \qry -> do outputText $ showInterval qry turnovers qry options coa byOneAccount queries options account = do let calcTotals = TShowTotals `elem` options calcSaldo = TShowSaldo `elem` options bqry = if TBothBalances `elem` options then BothBalances else if TLedgerBalances `elem` options then Only LedgerBalance else Only AvailableBalance turns <- forM queries $ \qry -> allTurnovers bqry calcTotals calcSaldo qry account let check | TNoZeros `elem` options = noZeroTurns | otherwise = const True xs = [(tr,qry) | (tr,qry) <- zip turns queries, check tr] turns' = map fst xs queries' = map snd xs let credits = map trCredit turns' debits = map trDebit turns' inc = map trIncSaldo turns' out = map trOutSaldo turns' totals = map trTotals turns' saldo = map trSaldo turns' starts = map qStart queries' ends = map qEnd queries' oformat <- getOutputFormat let format = case oformat of OASCII ASCII -> tableColumns ASCII OCSV csv -> tableColumns csv OHTML html -> tableColumns html outputText $ unlinesText $ format $ [([output "FROM"], ALeft, map showMaybeDate starts), ([output "TO"], ALeft, map showMaybeDate ends), ([output "BALANCE C/F"], ARight, map prettyPrint inc), ([output "DEBIT"], ARight, map prettyPrint debits), ([output "CREDIT"], ARight, map prettyPrint credits), ([output "BALANCE B/D"], ARight, map prettyPrint out)] ++ (if calcTotals then [([output "TOTALS"], ARight, map (prettyPrint . fromJust) totals)] else []) ++ (if calcSaldo then [([output "SALDO"], ARight, map (prettyPrint . fromJust) saldo)] else []) turnovers qry options coa = do let calcTotals = TShowTotals `elem` options calcSaldo = TShowSaldo `elem` options bqry = if TBothBalances `elem` options then BothBalances else if TLedgerBalances `elem` options then Only LedgerBalance else Only AvailableBalance rgroup = selectRateGroup (commonFlags options) tree <- mapTreeM (sumTurnovers (qEnd qry) rgroup calcTotals calcSaldo) (allTurnovers bqry calcTotals calcSaldo qry) coa let tree' = if TNoZeros `elem` options then filterLeafs noZeroTurns tree else tree oformat <- getOutputFormat let struct = case oformat of OASCII _ -> showTreeStructure tree' OCSV _ -> map (output . intercalate "/") (allPaths tree') OHTML _ -> showTreeStructure tree' nodes = allNodes tree' credits = map trCredit nodes debits = map trDebit nodes inc = map trIncSaldo nodes out = map trOutSaldo nodes totals = map trTotals nodes saldo = map trSaldo nodes oformat <- getOutputFormat let format = case oformat of OASCII ASCII -> tableColumns ASCII OCSV csv -> tableColumns csv OHTML html -> tableColumns html outputText $ unlinesText $ format $ [([output "ACCOUNT"], ALeft, struct), ([output "BALANCE C/F"], ARight, map prettyPrint inc), ([output "DEBIT"], ARight, map prettyPrint debits), ([output "CREDIT"], ARight, map prettyPrint credits), ([output "BALANCE B/D"], ARight, map prettyPrint out)] ++ (if calcTotals then [([output "TOTALS"], ARight, map (prettyPrint . fromJust) totals)] else []) ++ (if calcSaldo then [([output "SALDO"], ARight, map (prettyPrint . fromJust) saldo)] else [])
portnov/yaledger
YaLedger/Reports/Turnovers.hs
bsd-3-clause
9,532
0
20
3,283
2,756
1,428
1,328
210
10
module Main where import Prelude hiding (lines) import Botworld hiding (limit, Error(..), memory, contents) import Control.Arrow import Control.Applicative import Control.Monad import Data.Char import Data.List (elemIndex) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import System.Environment import System.Exit (exitSuccess, exitFailure) import System.IO (hPutStrLn, stderr) import Text.Parsec hiding ((<|>), many, spaces) import Text.Parsec.String (Parser) import Text.Printf (printf) type Name = String type Size = Maybe Int type Declaration = (Name, Size, Value) data Value = Code [INSTRUCTION] | Data Constree deriving Show -- These are the instructions recognized in ct files. -- COPY, EXEC, and WRITE require that you have a register named NIL. -- If you want the instructions to act like they sound, NIL should always -- contain exactly Nil. data INSTRUCTION = NILIFY Name | CONS Name Name Name | DEST Name Name Name | COPY Name Name | CONDCOPY Name Name Name | EXEC Name | CONDEXEC Name Name | PUSH Name Name | POP Name Name | WRITE Name | CONDWRITE Name Name deriving Show data Error = NoSuchRegister Name | DuplicateDeclaration Name deriving Show type File = [Declaration] names :: File -> [Name] names f = [n | (n, _, _) <- f] validate :: [Declaration] -> Either Error File validate decls = case safeSet $ names decls of Left dup -> Left $ DuplicateDeclaration dup Right _ -> Right decls safeSet :: Ord k => [k] -> Either k (Set k) safeSet = foldM safeInsert Set.empty where safeInsert s x = if Set.member x s then Left x else Right $ Set.insert x s convert :: File -> Either Error [Register] convert f = mapM compile f where compile (_, s, Code l) = (make s . encode) <$> mapM instruct l compile (_, s, Data t) = Right $ make s t make Nothing t = R (size t) t make (Just s) t = R s (trim s t) instruct (NILIFY tgt) = Nilify <$> r tgt instruct (CONS fnt bck tgt) = Construct <$> r fnt <*> r bck <*> r tgt instruct (DEST src fnt bck) = Deconstruct <$> r src <*> r fnt <*> r bck instruct (COPY src dst) = CopyIfNil <$> r "NIL" <*> r src <*> r dst instruct (CONDCOPY tst src dst) = CopyIfNil <$> r tst <*> r src <*> r dst instruct (EXEC prg) = CopyIfNil <$> r "NIL" <*> r prg <*> return 0 instruct (CONDEXEC tst prg) = CopyIfNil <$> r tst <*> r prg <*> return 0 instruct (PUSH src stk) = Construct <$> r src <*> r stk <*> r stk instruct (POP stk tgt) = Deconstruct <$> r stk <*> r tgt <*> r stk instruct (WRITE src) = CopyIfNil <$> r "NIL" <*> r src <*> return 2 instruct (CONDWRITE tst src) = CopyIfNil <$> r tst <*> r src <*> return 2 r x = maybe (Left $ NoSuchRegister x) Right (elemIndex x $ names f) file :: Parser [Declaration] file = many declaration spaces :: Parser () spaces = void $ many $ satisfy isSpace spaces1 :: Parser () spaces1 = void $ many1 $ satisfy isSpace declaration :: Parser Declaration declaration = (,,) <$> h <*> s <*> v where h = bullshit *> name s = spaces *> limit <* spaces <* char ':' <* spaces <* bullshit v = try (Data <$> (tdata <* bullshit)) <|> (Code <$> many (instruction <* bullshit)) <?> "a value" bullshit :: Parser () bullshit = void $ many ignored where ignored = try spaces1 <|> try comment <?> "ignored text" comment :: Parser () comment = char ';' *> skipMany (noneOf "\r\n") limit :: Parser Size limit = optionMaybe (read <$> many1 digit) name :: Parser Name name = (:) <$> satisfy isAlpha_ <*> many (satisfy isAlphaNum_) where isAlpha_ = (||) <$> isAlpha <*> (== '_') isAlphaNum_ = (||) <$> isAlphaNum <*> (== '_') instruction :: Parser INSTRUCTION instruction = try (string "CONS" *> (CONS <$> ref <*> ref <*> ref)) <|> try (string "DEST" *> (DEST <$> ref <*> ref <*> ref)) <|> try (string "COPY" *> (COPY <$> ref <*> ref)) <|> try (string "CONDCOPY" *> (CONDCOPY <$> ref <*> ref <*> ref)) <|> try (string "EXEC" *> (EXEC <$> ref)) <|> try (string "CONDEXEC" *> (CONDEXEC <$> ref <*> ref)) <|> try (string "PUSH" *> (PUSH <$> ref <*> ref)) <|> try (string "POP" *> (POP <$> ref <*> ref)) <|> try (string "WRITE" *> (WRITE <$> ref)) <|> try (string "CONDWRITE" *> (CONDWRITE <$> ref <*> ref)) <?> "an instruction" where ref = spaces *> name <* spaces encreg :: Parser Register encreg = R <$> (string "R" *> spaces1 *> int <* spaces1) <*> tdata memory :: Parser Memory memory = listOf encreg int :: Parser Int int = read <$> many1 digit direction :: Parser Direction direction = try (string "N" *> pure N) <|> try (string "NE" *> pure NE) <|> try (string "E" *> pure E) <|> try (string "SE" *> pure SE) <|> try (string "S" *> pure S) <|> try (string "SW" *> pure SW) <|> try (string "W" *> pure W) <|> try (string "NW" *> pure NW) <?> "a direction" command :: Parser Command command = try (Move <$> (string "Move" *> spaces1 *> direction)) <|> try (Lift <$> (string "Lift" *> spaces1 *> int)) <|> try (Drop <$> (string "Drop" *> spaces1 *> int)) <|> try (Inspect <$> (string "Inspect" *> spaces1 *> int)) <|> try (Destroy <$> (string "Destroy" *> spaces1 *> int)) <|> try (Build <$> (string "Build" *> spaces1 *> listOf int <* spaces1) <*> memory) <|> try (string "Pass" *> pure Pass) <?> "a command" instr :: Parser Instruction instr = try (Nilify <$> (string "Nilify" *> spaces1 *> int)) <|> try (Construct <$> (string "Construct" *> spaces1 *> int <* spaces1) <*> (int <* spaces1) <*> int) <|> try (Deconstruct <$> (string "Deconstruct" *> spaces1 *> int <* spaces1) <*> (int <* spaces1) <*> int) <|> try (CopyIfNil <$> (string "CopyIfNil" *> spaces1 *> int <* spaces1) <*> (int <* spaces1) <*> int) <?> "a literal instruction" constree :: Parser Constree constree = try (string "Nil" *> pure Nil) <|> try (Cons <$> (string "Cons" *> spaces1 *> constree <* spaces1) <*> constree) <?> "some constree" listOf :: Parser a -> Parser [a] listOf p = bracketed (sepBy p (spaces *> char ',' <* spaces)) where bracketed = between (char '[' *> spaces) (spaces <* char ']') treeTuple :: Parser Constree treeTuple = treeify <$> bracketed (sepBy1 tdata (spaces *> char ',' <* spaces)) where bracketed = between (char '(' *> spaces) (spaces <* char ')') treeify [] = error "sepBy1 failure" treeify [x] = x treeify (x:xs) = Cons x (treeify xs) tdata :: Parser Constree tdata = try (encode <$> int) <|> try (encode <$> command) <|> try (encode <$> instr) <|> try constree <|> try treeTuple <|> try (encode <$> listOf tdata) <?> "valid data" load :: String -> String -> Either String File load fname txt = do decls <- left show $ parse file fname txt left show $ validate decls main :: IO () main = do args <- getArgs when (null args) $ do hPutStrLn stderr "Not enough arguments. (Try ct2hs --help.)" exitFailure let basename = head args when (basename == "-h" || basename == "--help") $ do putStrLn "ct2hs NAME [MODULE]" putStrLn "" putStrLn "NAME should specify a .ct file WITHOUT the .ct extension." putStrLn "MODULE determines the haskell module name; it defaults to NAME." putStrLn "Output will be written to stdout; redirect it as neccessary." putStrLn "" putStrLn "example:" putStrLn " > ct2hs Omega Precommit.Omega > Omega.hs" exitSuccess when (length args > 2) $ do hPutStrLn stderr "Too many arguments. (Try ct2hs --help.)" exitFailure let modname = if length args > 1 then args !! 1 else basename let filename = basename <> ".ct" contents <- readFile filename case load filename contents of Left e -> putStrLn e Right f -> either print (printModule modname $ names f) (convert f) template :: String template = unlines [ "module %s (machine, registerNames, inspect, view) where" , "import Botworld" , "import Botworld.Debug" , "" , "machine :: Memory" , "machine = %s" , "" , "registerNames :: [String]" , "registerNames = %s" , "" , "inspect :: Memory -> [String]" , "inspect = inspectMemory registerNames" , "" , "view :: Robot -> IO ()" , "view = putStrLn . unlines . inspect . memory" ] moduleFor :: String -> [String] -> Memory -> String moduleFor modname rs m = printf template modname (show m) (show rs) printModule :: String -> [String] -> Memory -> IO () printModule modname rnames m = putStr (moduleFor modname rnames m)
machine-intelligence/Botworld
ct2hs.hs
bsd-3-clause
8,583
0
21
2,024
3,269
1,645
1,624
207
13
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Distance.IT.Tests ( tests ) where import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Distance.IT.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "IT Tests" [ makeCorpusTest [Seal Distance] corpus ]
facebookincubator/duckling
tests/Duckling/Distance/IT/Tests.hs
bsd-3-clause
494
0
9
78
76
48
28
10
1
{-| Module : Reactive.DOM.Widget.Tabular Description : Definition of tabs, for tabular widgets. Copyright : (c) Alexander Vieth, 2016 Licence : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} module Reactive.DOM.Widget.Tabular where import Reactive.Sequence import Reactive.Banana.Combinators import Reactive.Banana.Frameworks import Reactive.DOM.Node import Reactive.DOM.Children.Algebraic import Data.Profunctor import Data.Semigroup import Data.List.NonEmpty as NonEmpty -- | Given a total function on some bounded enum, pack the resulting widgets -- as siblings. It's called tabs because, if the resulting OpenWidget is -- closed and styled with flex rows, you'll get something resembling tabs. -- -- The widgets in the image of the function on the bounded enum take a -- Sequence Bool, which will be synthesized here, to indciate whether they are -- the "active" tab, i.e. the one whose output event has most recently fired. -- You may want to use this event to derive the widget's style. -- -- Useful in combination with oneOf from Reactive.DOM.Widget.OneOf, which -- lends itself well to defining the content which the tabs control. tabs :: forall enum s . ( Enum enum , Bounded enum , Ord enum ) => (enum -> ClosedWidget (s, Sequence Bool) (Event ())) -> OpenWidget (s, enum) (Event enum) tabs mkThing = tieKnot (rmap getOutput contents) loop where things :: [(enum, ClosedWidget (s, Sequence Bool) (Event ()))] things = (\e -> (e, mkThing e)) <$> [minBound..maxBound] -- Ok so here we need the s input to be uniform... aha, we must first -- generalize the Event Bool to an Event enum. contents :: OpenWidget (s, Sequence enum) (SemigroupEvent (First enum)) contents = widgetProductUniform (withEnumEvent <$> things) -- Use the input to wire up the Event Bool, and make the output event -- give the enum and wrap it in SemigroupEvent so we can use it in -- widgetProductUniform. withEnumEvent :: forall s . (enum, ClosedWidget (s, Sequence Bool) (Event ())) -> ClosedWidget (s, Sequence enum) (SemigroupEvent (First enum)) withEnumEvent (enum, ClosedWidget tag w) = ClosedWidget tag w' where w' = modify (modifier input) (modifier output) w output ev = pure (SemigroupEvent (fmap (const (First enum)) ev)) input (s, seqnc) = do let initial = sequenceFirst seqnc chngs <- sequenceChanges seqnc let pickTrue (old, new) = old /= new && new == enum let pickFalse (old, new) = old /= new && old == enum let evboolTrue = const True <$> filterE pickTrue chngs let evboolFalse = const False <$> filterE pickFalse chngs let evbool = unionWith const evboolTrue evboolFalse pure (s, (initial == enum) |> evbool) -- Use this to tie the output of contents back to its input. loop :: forall tag . Event enum -> (s, enum) -> ElementBuilder tag (s, Sequence enum) loop ev (s, initial) = pure (s, initial |> ev) getOutput :: SemigroupEvent (First enum) -> Event enum getOutput = fmap getFirst . runSemigroupEvent
avieth/reactive-dom
Reactive/DOM/Widget/Tabular.hs
bsd-3-clause
3,434
0
17
829
731
394
337
50
1
module Data.String.Additional where import Data.Char (toLower) import Data.Char (isUpper) import Data.Char (isLower) -- | Convert "CamelCASEDString" to "camel_cased_string" camelToUnderscore :: String -> String camelToUnderscore = map toLower . go2 . go1 where go1 "" = "" go1 (x:u:l:xs) | isUpper u && isLower l = x : "_" ++ u : l : go1 xs go1 (x:xs) = x : go1 xs go2 "" = "" go2 (l:u:xs) | isLower l && isUpper u = l : "_" ++ u : go2 xs go2 (x:xs) = x : go2 xs
k-bx/redis-tlz
src/Data/String/Additional.hs
bsd-3-clause
519
0
11
146
233
118
115
12
5
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} module Scripts.ComadIntake where import Appian.Client import Scripts.Common import Scripts.ReviewCommon import Scripts.ComadReview import Control.Monad.Logger import ClassyPrelude import Data.Aeson import Control.Lens import Control.Lens.Action.Reified import Appian import Appian.Instances import Appian.Types import Appian.Lens import Scripts.Execute import Stats.CsvStream import Control.Monad.Except import Appian.Internal.Arbitrary comadIntake :: Login -> Appian Value comadIntake _ = do executeActionByName "Initiate COMAD" sendUpdates1 "Select Funding Year" (dropdownUpdateF1 "Funding Year" "2017") sendUpdates1 "Click 'No' Button" (buttonUpdateF "No") mGF <- usesValue (^? getGridFieldCell . traverse) case mGF of Nothing -> fail "Could not find grid field!" Just gf -> sendUpdates1 "Select FRN in grid" (selectGridfieldUpdateF (IntIdent $ AppianInt 24) gf) sendUpdates1Handle notPrimaryOrgSelected "Click 'Add FRNs' button" (buttonUpdateWithF isAddAllButton "Could not find Add FRNs button") mComponents <- usesValue (^? getGridWidget . asGWC . gwVal . traverse . _2 . runFold ( (,,) <$> Fold (at "Primary FRN" . traverse . _GWCheckbox) <*> Fold (at "Recovery Type" . traverse . _GWDropdown) <*> Fold (at "Adjustment Reason" . traverse . _GWDropdown) ) ) case mComponents of Nothing -> fail "Could not find components" Just tpl -> rowUpdate tpl sendUpdates1 "Click 'Continue' Button" (buttonUpdateF "Continue") sendUpdates1 "Enter 'Nickname'" (textFieldArbitraryF "Nickname" 255) sendUpdates1 "Enter 'Narrative'" (paragraphArbitraryUpdate "Narrative" 4000) sendUpdates1 "Select 'Origin'" (dropdownArbitraryUpdateF "Origin") sendUpdates1 "Click 'Submit' Button" (buttonUpdateF "Submit") use appianValue notPrimaryOrgSelected :: ScriptError -> Bool notPrimaryOrgSelected (ValidationsError (["Please select an FRN to determine the primary affected organizations"], _, _)) = True notPrimaryOrgSelected _ = False isAddAllButton :: Text -> Bool isAddAllButton label = isPrefixOf "Add" label && isSuffixOf "FRNs" label runComadIntake :: Bounds -> HostUrl -> LogMode -> CsvPath -> RampupTime -> NThreads -> IO [Maybe (Either ServantError (Either ScriptError Value))] runComadIntake = runIt comadIntake rowUpdate :: (CheckboxField, DropdownField, DropdownField) -> Appian () rowUpdate (cbox, recoveryDf, adjustmentDf) = do let cbox' = cbfValue .~ (Just [1]) $ cbox recoveryDf' <- dropdownArbitrarySelect recoveryDf adjustmentDf' <- dropdownArbitrarySelect adjustmentDf sendUpdates1 "Select 'Primary FRN' Checkbox" (componentUpdateWithF "Could not find primary FRN Checkbox" $ to $ const $ cbox') sendUpdates1 "Select 'Recovery Type' Checkbox" (componentUpdateWithF "Could not find primary Recovery Type Checkbox" $ to $ const $ recoveryDf') sendUpdates1 "Select 'Adjustment Type' Checkbox" (componentUpdateWithF "Could not find primary Adjustment Type Checkbox" $ to $ const $ adjustmentDf') asGWC = to (id :: GridWidget GridWidgetCell -> GridWidget GridWidgetCell)
limaner2002/EPC-tools
USACScripts/src/Scripts/ComadIntake.hs
bsd-3-clause
3,378
0
20
684
774
386
388
61
3
{-# LANGUAGE QuasiQuotes #-} -- | This module defines a generator for @getopt_long@ based command -- line argument parsing. Each option is associated with arbitrary C -- code that will perform side effects, usually by setting some global -- variables. module Futhark.CodeGen.Backends.GenericC.Options ( Option (..) , OptionArgument (..) , generateOptionParser ) where import Data.Maybe import qualified Language.C.Syntax as C import qualified Language.C.Quote.C as C -- | Specification if a single command line option. The option must -- have a long name, and may also have a short name. -- -- In the action, the option argument (if any) is stored as in the -- @char*@-typed variable @optarg@. data Option = Option { optionLongName :: String , optionShortName :: Maybe Char , optionArgument :: OptionArgument , optionAction :: C.Stm } -- | Whether an option accepts an argument. data OptionArgument = NoArgument | RequiredArgument | OptionalArgument -- | Generate an option parser as a function of the given name, that -- accepts the given command line options. The result is a function -- that should be called with @argc@ and @argv@. The function returns -- the number of @argv@ elements that have been processed. -- -- If option parsing fails for any reason, the entire process will -- terminate with error code 1. generateOptionParser :: String -> [Option] -> C.Func generateOptionParser fname options = [C.cfun|int $id:fname(int argc, char* const argv[]) { int $id:chosen_option; static struct option long_options[] = { $inits:option_fields, {0, 0, 0, 0} }; while (($id:chosen_option = getopt_long(argc, argv, $string:option_string, long_options, NULL)) != -1) { $stms:option_applications if ($id:chosen_option == ':') { errx(-1, "Missing argument for option %s", argv[optind-1]); } if ($id:chosen_option == '?') { errx(-1, "Unknown option %s", argv[optind-1]); } } return optind; } |] where chosen_option = "ch" option_string = ':' : optionString options option_applications = optionApplications chosen_option options option_fields = optionFields options optionFields :: [Option] -> [C.Initializer] optionFields = zipWith field [(1::Int)..] where field i option = [C.cinit| { $string:(optionLongName option), $id:arg, NULL, $int:i } |] where arg = case optionArgument option of NoArgument -> "no_argument" RequiredArgument -> "required_argument" OptionalArgument -> "optional_argument" optionApplications :: String -> [Option] -> [C.Stm] optionApplications chosen_option = zipWith check [(1::Int)..] where check i option = [C.cstm|if ($exp:cond) $stm:(optionAction option)|] where cond = case optionShortName option of Nothing -> [C.cexp|$id:chosen_option == $int:i|] Just c -> [C.cexp|($id:chosen_option == $int:i) || ($id:chosen_option == $char:c)|] optionString :: [Option] -> String optionString = concat . mapMaybe optionStringChunk where optionStringChunk option = do short <- optionShortName option return $ short : case optionArgument option of NoArgument -> "" RequiredArgument -> ":" OptionalArgument -> "::"
CulpaBS/wbBach
src/Futhark/CodeGen/Backends/GenericC/Options.hs
bsd-3-clause
3,657
0
12
1,057
460
272
188
46
3
module Distribution.FreeBSD.Update where import Control.Applicative import Control.Arrow import Control.Monad import Control.Monad.Reader import Data.Char import Data.Function import Data.List import Data.Maybe import Data.Version import qualified Data.Map as DM import qualified Data.Text as DT import Distribution.FreeBSD.Common import Distribution.FreeBSD.Port hiding (normalize, getBaseLibs) import Distribution.Package import Distribution.PackageDescription import Distribution.PackageDescription.Parse import Distribution.Version import Network.HTTP import System.Directory import System.FilePath.Posix import Text.ParserCombinators.ReadP import Text.Printf import Debug.Trace toVersion :: String -> Version toVersion = fst . last . readP_to_S parseVersion hackageLog,portVersionsFile,bsdHackageMk,mkfile :: FilePath [hackageLog,portVersionsFile,bsdHackageMk,mkfile] = [ "hackage.log" , "portversions" , "lang/ghc/bsd.hackage.mk" , "Makefile" ] hackageLogURI :: String hackageLogURI = "http://haskell.inf.elte.hu/hackage.log" cabal :: FilePath -> FilePath cabal = (<.> "cabal") getCabalURI :: (String,String) -> String getCabalURI (n,v) = hackageURI </> (n ++ "-" ++ v) </> cabal n downloadFile :: String -> IO String downloadFile url = simpleHTTP (getRequest url) >>= getResponseBody getHackageDescription :: (PackageName,Version) -> IO GenericPackageDescription getHackageDescription (PackageName p,v) = do dump <- downloadFile $ getCabalURI (p,showVersion v) ParseOk _ gpkg <- return $ parsePackageDescription dump return gpkg buildHackageDatabase :: FilePath -> HPM HDM buildHackageDatabase log = do core <- asks cfgBaseLibs entries <- liftIO $ map extractEntry . DT.lines . DT.pack <$> readFile log let retainCoreVersion pk@(pn,_) = case (lookup pn core) of Just v -> (pn,[v]) Nothing -> pk return $ DM.fromList $ map retainCoreVersion $ map (packName &&& versions) $ prepare entries where prepare = groupBy ((==) `on` fst) . sort packName = PackageName . DT.unpack . fst . head versions = map (toVersion . DT.unpack . snd) extractEntry line = (n,v) where (n:v:_) = DT.splitOn (DT.pack "/") line buildCabalDatabase :: HPM CPM buildCabalDatabase = do dbdir <- asks cfgDbDir contents <- liftIO $ getDirectoryContents dbdir let files = map (dbdir </>) $ filterDots contents entries <- mapM getEntry files return $ DM.fromList entries where filterDots = filter (flip notElem [".",".."]) getEntry location = do let pack = package . packageDescription let file = takeFileName location dump <- liftIO $ readFile location result <- return $ parsePackageDescription dump case result of ParseOk _ gpkg -> return $ ((pkgName . pack &&& pkgVersion . pack) &&& id $ gpkg) _ -> fail $ printf "Could not parse description for \"%s\"." file getCabalVersions :: CPM -> HDM getCabalVersions = DM.fromList . map (\l -> (fst . head $ l, map snd l)) . groupBy ((==) `on` fst) . map fst . DM.toList getDependencies :: GenericPackageDescription -> [Dependency] getDependencies gpkgd = libdeps ++ exedeps where libdeps = case (condLibrary gpkgd) of Just x -> condTreeConstraints x Nothing -> [] exedeps = concatMap (condTreeConstraints . snd) . condExecutables $ gpkgd normalize :: [DT.Text] -> [DT.Text] normalize = filter nonEmpty . map (DT.strip . uncomment) where nonEmpty = (not . DT.null) uncomment = DT.takeWhile (/= '#') getBaseLibs :: Platform -> [(PackageName,Version)] getBaseLibs (Platform p) = map translate . normalize . DT.lines . DT.pack $ p where translate l = (PackageName $ n,toVersion v) where (n:v:_) = DT.unpack <$> DT.words l addConstraint :: (PackageName,Version,PackageName,VersionRange) -> VCM -> VCM addConstraint (orig,v,p,vr) = DM.alter f p where f Nothing = Just $ DM.singleton (orig,v) vr f (Just vs) = Just $ DM.insert (orig,v) vr vs getVersionConstraints :: CPM -> VCM getVersionConstraints = DM.fold f DM.empty where f :: GenericPackageDescription -> VCM -> VCM f p m = foldr addConstraint m $ translate <$> getDependencies p where translate (Dependency pk vr) = (packageName p,packageVersion p, pk,vr) addCoreVersionConstraints :: VCM -> [(PackageName,Version)] -> VCM addCoreVersionConstraints m = foldr addConstraint m . map translate where translate (p,v) = (p,v,p,thisVersion v) sumVersionConstraints :: CPM -> [(PackageName,Version)] -> VCM sumVersionConstraints cpm core = flip addCoreVersionConstraints core $ getVersionConstraints cpm buildVersionConstraints :: CPM -> HPM VCM buildVersionConstraints cpm = do baselibs <- fmap getBaseLibs $ asks cfgPlatform return $ sumVersionConstraints cpm baselibs formatPackage :: (String,[Int]) -> (PackageName,Version) formatPackage = first PackageName . second (flip Version []) isVersionAllowed :: HDM -> CPM -> VCM -> (PackageName,Version) -> HPM ([((PackageName,Version),VersionRange)],[(PackageName,VersionRange)]) isVersionAllowed hdm cpm vcm i@(p,v) = do unsatisifed <- unsatisfiedDependencies hdm cpm vcm i return (constraints,unsatisifed) where constraints = case (DM.lookup p vcm) of Nothing -> [] Just res -> filter (versionFilter hdm cpm vcm i) $ DM.toList res versionFilter :: HDM -> CPM -> VCM -> (PackageName,Version) -> ((PackageName,Version),VersionRange) -> Bool versionFilter hdm cpm vcm (_,v) ((p,pv),vr) | not (v `withinRange` vr) = True | otherwise = False unsatisfiedDependencies :: HDM -> CPM -> VCM -> (PackageName,Version) -> HPM [(PackageName,VersionRange)] unsatisfiedDependencies hdm cpm vcm (p,v) = do baselibs <- asks cfgBaseLibs let f (Dependency pk vr) = case (lookup pk baselibs) of Just v -> not $ v `withinRange` vr Nothing -> not $ all ((`withinRange` vr)) $ hdm %!% pk return [ (pn,vr) | Dependency pn vr <- filter f $ getDependencies $ cpm %!% (p,v) ] satisfyingDependencies :: HDM -> CPM -> (PackageName,Version) -> HPM [(PackageName,Version)] satisfyingDependencies hdm cpm (p,v) = do baselibs <- asks cfgBaseLibs let f (Dependency pk vr) = case (lookup pk baselibs) of Nothing -> Just $ (pk, maximum allowed) _ -> Nothing where allowed = filterAllowed vr pk return $ mapMaybe f $ getDependencies $ cpm %!% (p,v) where filterAllowed vr pk = filter (`withinRange` vr) $ hdm %!% pk getPortVersions :: FilePath -> HPM Ports getPortVersions fn = do contents <- (map DT.words . DT.lines . DT.pack) <$> liftIO (readFile fn) return $ Ports $ sort $ (translate . map DT.unpack) <$> contents where translate (n:c:v:_) = (PackageName n,Category c,toVersion v) isThereUpdate :: HDM -> CPM -> VCM -> (PackageName,Category,Version) -> HPM (Maybe PortUpdate) isThereUpdate hdm cpm vcm (p,ct,v) = do let versions = hdm %!% p let candidates = (repeat p) `zip` versions checked <- mapM (isVersionAllowed hdm cpm vcm) candidates let allowed = versions `zip` checked let f (_,(x,y)) = length x + length y let (v',(r',d')) = minimumBy (compare `on` f) allowed return $ if (v /= v') then Just $ PU { puPackage = p , puCategory = ct , puOldVersion = v , puNewVersion = v' , puRestrictedBy = map (fst . fst) r' , puUnsatisfiedBy = map fst d' } else Nothing learnUpdates :: (HDM,CPM,VCM,Ports) -> HPM [PortUpdate] learnUpdates (hdm,cpm,vcm,Ports ports) = fmap catMaybes $ mapM (isThereUpdate hdm cpm vcm) ports prettyUpdateLine :: PortUpdate -> Maybe String prettyUpdateLine (PU { puPackage = PackageName p , puCategory = Category c , puOldVersion = v , puNewVersion = v1 , puRestrictedBy = rs , puUnsatisfiedBy = dp }) | v < v1 && null rs && null dp = Just $ printf "%-32s %-12s ---> %-12s" port v' v1' | v < v1 && null rs = Just $ printf "%-32s %-12s -/-> %-12s (U: %s)" port v' v1' udeps | v < v1 && null dp = Just $ printf "%-32s %-12s -/-> %-12s (R: %s)" port v' v1' restricts | v < v1 = Just $ printf "%-32s %-12s -/-> %-12s (R: %s, U: %s)" port v' v1' restricts udeps | otherwise = Nothing where port = (printf "%s (%s)" p c) :: String [v',v1'] = showVersion <$> [v,v1] restricts = intercalate ", " [ p | PackageName p <- rs ] udeps = intercalate ", " [ d | PackageName d <- dp ] compactUpdateLine :: PortUpdate -> Maybe String compactUpdateLine (PU { puPackage = PackageName p , puCategory = Category c , puOldVersion = v , puNewVersion = v1 }) = Just $ printf "%s/hs-%s: %s --> %s" c p (showVersion v) (showVersion v1) initialize :: HPM (HDM,CPM,VCM,Ports) initialize = do cpm <- buildCabalDatabase let hdm = getCabalVersions cpm vcm <- buildVersionConstraints cpm ports <- getPortVersions portVersionsFile return $ (hdm,cpm,vcm,ports) createPortFiles :: FilePath -> Port -> IO () createPortFiles path port = do createDirectoryIfMissing True path writeFile (path </> "Makefile") $ makefile port writeFile (path </> "distinfo") $ distinfo port writeFile (path </> "pkg-descr") $ pkgDescr port
freebsd-haskell/hsporter
Distribution/FreeBSD/Update.hs
bsd-3-clause
9,356
0
19
2,051
3,400
1,780
1,620
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} module React.Flux.Mui.Toggle where import Protolude import Data.Aeson import Data.Aeson.Casing import Data.String (String) import React.Flux import React.Flux.Mui.Types import React.Flux.Mui.Util data Toggle = Toggle { toggleDefaultToggled :: !(Maybe Bool) , toggleDisabled :: !(Maybe Bool) , toggleLabelPosition :: !(Maybe (MuiSymbolEnum '[ "left", "right"])) , toggleToggled :: !(Maybe Bool) } deriving (Generic, Show) instance ToJSON Toggle where toJSON = genericToJSON $ aesonDrop (length ("Toggle" :: String)) camelCase defToggle :: Toggle defToggle = Toggle { toggleDefaultToggled = Just False , toggleDisabled = Just False , toggleLabelPosition = Just (MuiSymbolEnum (Proxy :: Proxy "left")) , toggleToggled = Nothing } toggle_ :: Toggle -> [PropertyOrHandler handler] -> ReactElementM handler () toggle_ args props = foreign_ "Toggle" (fromMaybe [] (toProps args) ++ props) mempty
pbogdan/react-flux-mui
react-flux-mui/src/React/Flux/Mui/Toggle.hs
bsd-3-clause
1,015
0
15
161
297
167
130
37
1
{-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Quant.MatchingEngine.Tests (main,runTests) where import Data.List import qualified Data.Set as S import Quant.MatchingEngine.BasicTypes import Quant.MatchingEngine.Book import Test.QuickCheck instance Arbitrary OrderBuy where arbitrary = do source <- elements (map ClientID [1,2,3,4,5,6]) size <- elements (map ShareCount [1,10,100,1000]) price <- elements (map Price [100,101,102,103,104,105,106,107,108,109,110]) oid <- elements (map OrderID [1000..1200]) time <- elements (map Time [5000..5500]) return (OrderBuy price time size source oid) instance Arbitrary OrderSell where arbitrary = do source <- elements (map ClientID [1,2,3,4,5,6]) size <- elements (map ShareCount [1,10,100,1000]) price <- elements (map Price [100,101,102,103,104,105,106,107,108,109,110]) oid <- elements (map OrderID [1000..1200]) time <- elements (map Time [5000..5500]) return (OrderSell price time size source oid) instance Arbitrary Book where arbitrary = do unorderedBuys <- arbitrary unorderedSells <- arbitrary return $ Book (S.fromList unorderedBuys) (S.fromList unorderedSells) -- sum of the qty of generated trades is less or equal to the size of the buy order: propBuySizeNotExceeded :: OrderBuy -> Book -> Bool propBuySizeNotExceeded buy book = sum (map tradeSize trades) <= bSize buy where (_, trades) = processBuy book buy propSellSizeNotExceeded :: OrderSell -> Book -> Bool propSellSizeNotExceeded sell book = sum (map tradeSize trades) <= sSize sell where (_, trades) = processSell book sell propBuyQtyMatch :: OrderBuy -> Book -> Bool propBuyQtyMatch buy book = bookLiquidity book + bSize buy - (2 * sum (map tradeSize trades)) == bookLiquidity newBook where (newBook, trades) = processBuy book buy propSellQtyMatch :: OrderSell -> Book -> Bool propSellQtyMatch sell book = bookLiquidity book + sSize sell - (2 * sum (map tradeSize trades)) == bookLiquidity newBook where (newBook, trades) = processSell book sell bookLiquidity :: Book -> ShareCount bookLiquidity Book{..} = sum (map bSize (S.toList bBuyOrders)) + sum (map sSize (S.toList bSellOrders)) propBookWellFormed :: [OrderBuy] -> [OrderSell] -> Bool propBookWellFormed buys sells = isWellFormed sellsBook && isWellFormed finalBook where sellsBook = foldl' (\x y -> fst (processSell x y)) (Book S.empty S.empty) sells finalBook = foldl' (\x y -> fst (processBuy x y)) (Book S.empty S.empty) buys isWellFormed :: Book -> Bool isWellFormed Book{..} = let x = reverse (map bPrice (S.toList bBuyOrders)) ++ map sPrice (S.toList bSellOrders) in sort x == x -- TODO -- test number of trades generated -- test trades are not generated with 0 qty -- test residual is added to book for limit orders -- test that the book remains well formed when processing orders main :: IO () main = do let testArgs = stdArgs { maxSuccess = 1000} quickCheckWith testArgs propBuySizeNotExceeded quickCheckWith testArgs propSellSizeNotExceeded quickCheckWith testArgs propBuyQtyMatch quickCheckWith testArgs propSellQtyMatch quickCheckWith testArgs propBookWellFormed runTests :: IO () runTests = undefined
tdoris/StockExchange
Quant/MatchingEngine/Tests.hs
bsd-3-clause
3,293
0
15
610
1,142
588
554
60
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Test.Mismi.Arbitrary where import Network.AWS.Types import Test.Mismi.Kernel.Arbitrary () import Test.QuickCheck import Test.QuickCheck.Instances () import Data.Text.Encoding import P instance Arbitrary Region where -- Shorter list than possible, aws doesn't support all potential Regions. arbitrary = elements [Ireland, Tokyo, Singapore, Sydney, NorthCalifornia, Oregon, NorthVirginia] instance Arbitrary AccessKey where arbitrary = AccessKey <$> (encodeUtf8 <$> arbitrary) instance Arbitrary SecretKey where arbitrary = SecretKey <$> (encodeUtf8 <$> arbitrary) instance Arbitrary SessionToken where arbitrary = SessionToken <$> (encodeUtf8 <$> arbitrary)
ambiata/mismi
mismi-core/test/Test/Mismi/Arbitrary.hs
bsd-3-clause
850
0
8
165
159
96
63
18
0
import Data.Char (isDigit) import Data.Either import Data.List import System.Console.GetOpt import System.Directory import System.Environment import System.Exit import System.IO import System.Process import Text.ParserCombinators.ReadP import Text.Printf (printf) -- The basic data structure. Most of the time, we will use [Du], because -- a single du run may have multiple roots. The path of a child is relative -- to its parent. data Du = Du { path :: String, size :: Int, children :: [Du]} deriving (Show, Eq) -- Parse du output. readDu :: String -> [Du] readDu s = let ls = reverse (map readDuLine (lines s)) (r, []) = unflattenDuUnder Nothing ls in r -- Helper for readDu. Build a hierarchical [Du] out of a flat [Du], reading -- all entries with path under parent (all entries if parent is Nothing). Input -- must be ordered hierarchically with parents before children--basically, -- the reverse of du output. Returns the hierarchical [Du] and the -- remaining input. Example, if parent is Just "a": -- -- [ Du "a/b" _ [], -- Du "a/b/c" _ [], -- Du "a/c" _ [], -- Du "b" _ [] -- Du "b/a" _ [] ] -- ----------> -- ( [ Du "b" _ [ -- Du "c" _ [] ], -- Du "c" _ [] ] ], -- [ Du "b" _, [] -- Du "b/a" _ [] ] unflattenDuUnder :: Maybe String -> [Du] -> ([Du], [Du]) unflattenDuUnder parent [] = ([], []) unflattenDuUnder parent ls@(Du p s [] : ls') = case relativeTo parent p of Just p' -> let (cs, ls'') = unflattenDuUnder (Just p) ls' (dus, ls''') = unflattenDuUnder parent ls'' in (Du p' s cs : dus, ls''') Nothing -> ([], ls) readDuLine :: String -> Du readDuLine l = let [(s, p)] = readP_to_S readPDuLine l in Du p (read s) [] readPDuLine :: ReadP String readPDuLine = do s <- munch1 (isDigit) skipSpaces return s -- Return a path relative to a parent, if it is a sub-path. When parent is -- Nothing, return the path. relativeTo :: Maybe String -> String -> Maybe String relativeTo Nothing s = Just s relativeTo (Just parent) s = relativeTo' parent s where relativeTo' "" ('/' : s') = Just s' relativeTo' "/" ('/' : s') = Just s' relativeTo' (c1 : s1) (c2 : s2) | c1 == c2 = relativeTo' s1 s2 relativeTo' _ _ = Nothing -- Turn a hierarchical [Du] into a flat [Du]. flattenDu :: [Du] -> [Du] flattenDu dus = flattenDu' dus [] where flattenDu' :: [Du] -> ([Du] -> [Du]) flattenDu' = foldr (\du -> (flattenDu1 du .)) id flattenDu1 :: Du -> ([Du] -> [Du]) flattenDu1 (Du p s cs) = flattenDu' (map (addParent p) cs) . (Du p s [] :) -- Add a parent component to a path. addParent :: String -> Du -> Du addParent parent (Du p s cs) = Du (parentWithSlash ++ p) s cs where parentWithSlash = if "/" `isSuffixOf` parent then parent else parent ++ "/" -- Show [Du] in unified diff format. showDuDiff :: String -> String -> [Du] -> String showDuDiff f1 f2 dus = case showsDu' dus [] of [] -> "" ls -> unlines (("--- " ++ f1) : ("+++ " ++ f2) : ls) showDu :: [Du] -> String showDu dus = unlines (showsDu' dus []) showsDu' :: [Du] -> ([String] -> [String]) showsDu' = foldr (\du -> (showsDu1 du .)) id showsDu1 :: Du -> ([String] -> [String]) showsDu1 (Du p s cs) = showsDu' cs . ((printf "%+-8d " s ++ p) :) sortOn, sortOnRev :: Ord b => (a -> b) -> [a] -> [a] sortOn f = sortBy (\a1 a2 -> f a1 `compare` f a2) sortOnRev f = sortBy (\a1 a2 -> f a2 `compare` f a1) sortDuOn :: Ord a => (Du -> a) -> [Du] -> [Du] sortDuOn f = sortOn f . map (\(Du p s cs) -> Du p s (sortDuOn f cs)) -- Sort [Du] largest first, using the maximum size of an entry and its -- children. sortDuOnMaxSize :: [Du] -> [Du] sortDuOnMaxSize = map snd . sort' where sort' :: [Du] -> [(Int, Du)] sort' = sortOnRev fst . map sort1 -- returns (the maximum size of the entry and its children, the entry sorted) sort1 :: Du -> (Int, Du) sort1 (Du p s cs) = let r = sort' cs maxS = case r of [] -> s ((s', _) : _) -> max s s' in (maxS, Du p s (map snd r)) -- Remove a prefix, replacing it with "." (or do nothing for Nothing). The -- Du must all be under this prefix. Handles trailing '/'s in prefix. delPrefixDu :: Maybe String -> [Du] -> [Du] delPrefixDu prefix = map delDu where delDu (Du p s cs) = Du (del p) s cs del = delPrefix prefix delPrefix :: Maybe String -> String -> String delPrefix Nothing = id delPrefix (Just prefix) = del where prefix' = reverse (dropWhile (== '/') (reverse prefix)) len = length prefix' del s = '.' : '/' : dropWhile (== '/') (drop len s) -- Restore a prefix, replacing the leading "." added by delPrefix (or do -- nothing for Nothing), where positive diffs get prefix2 and negative diffs -- get prefix1. The Du must all be under ".". addPrefixDu :: Maybe String -> Maybe String -> [Du] -> [Du] addPrefixDu prefix1 prefix2 dus = map addDu dus where addDu (Du p s cs) = Du (if s>0 then add2 p else add1 p) s cs add1 = addPrefix prefix1 add2 = addPrefix prefix2 addPrefix :: Maybe String -> String -> String addPrefix Nothing = id -- "." -> "." if prefix didn't have trailing slash, "./" if it did. This -- round-trips in a way consistent with GNU diff. addPrefix (Just prefix) = add where rprefix = reverse prefix trailingSlash = head rprefix == '/' prefix' = reverse (dropWhile (== '/') rprefix) dotPrefix = prefix' ++ if trailingSlash then "/" else "" prependPrefix = (prefix' ++) add "./" = dotPrefix add ('.':s) = prependPrefix s -- Prune a du, removing entries in prunes. pruneDu :: [String] -> [Du] -> [Du] pruneDu prunes = map pruneDu' where pruneDu' (Du p s cs) | p `elem` prunes = Du p s [] pruneDu' (Du p s cs) = Du p s (map pruneDu' cs) -- Find the diff between two [Du]s (positive if the second input is larger, -- negative if the first). Ignores children of entries in only one input. -- Inputs must be sorted on path. diffDu :: [Du] -> [Du] -> [Du] diffDu [] [] = [] diffDu (Du p1 s1 cs1 : dus1) [] = Du p1 (-s1) [] : diffDu dus1 [] diffDu [] (Du p2 s2 cs2 : dus2) = Du p2 s2 [] : diffDu [] dus2 diffDu (du1@(Du p1 s1 cs1) : dus1) (du2@(Du p2 s2 cs2) : dus2) = case p1 `compare` p2 of LT -> Du p1 (-s1) [] : diffDu dus1 (du2 : dus2) GT -> Du p2 s2 [] : diffDu (du1 : dus1) dus2 EQ -> Du p1 (s2-s1) (diffDu cs1 cs2) : diffDu dus1 dus2 -- Removes entries under a threshold. The Thresher is applied to the size -- of the entry, and the total size of its descenents accepted by the Thresher -- (Nothing if none); and returns the reported size of the entry (if -- accepted) or Nothing (to remove). threshDu :: Thresher -> [Du] -> [Du] threshDu t dus = snd (threshDu' dus) where -- Returns the total size accepted and the accepted [Du]. threshDu' :: [Du] -> (Maybe Int, [Du]) threshDu' dus = foldr (\du (s, rs) -> let (s', rs') = threshDu1 du in (s `addMaybe` s', rs' ++ rs)) (Nothing, []) dus threshDu1 :: Du -> (Maybe Int, [Du]) threshDu1 (Du p s cs) = let (rptSize, rs) = threshDu' cs in case t s rptSize of Just s' -> (Just s, [Du p s' rs]) Nothing -> (rptSize, map (addParent p) rs) addMaybe :: Maybe Int -> Maybe Int -> Maybe Int addMaybe (Just x) (Just y) = Just (x+y) addMaybe (Just x) Nothing = Just x addMaybe Nothing (Just y) = Just y addMaybe Nothing Nothing = Nothing -- size -> accepted size of children -> report as size type Thresher = Int -> Maybe Int -> Maybe Int simpleThresher, smartThresher, deepestThresher :: Int -> Thresher -- Report all entries above threshold as their actual size. simpleThresher t s _ = if abs s >= t then Just s else Nothing -- Exclude size of accepted children. smartThresher t s (Just rptSize) = let s' = s - rptSize in if abs s' >= t then Just s' else Nothing smartThresher t s Nothing = if abs s >= t then Just s else Nothing -- Do not report parents of accepted children. deepestThresher _ _ (Just _) = Nothing deepestThresher t s Nothing = if abs s >= t then Just s else Nothing -- Get raw du output from a file (possibly gzipped) or by running du. getDu :: Opts -> String -> IO String getDu Opts { optDuProg = du, optDuArgs = as } f = doesFileExist f >>= \b -> if b then if ".gz" `isSuffixOf` f then readProc "zcat" [f] else readFile f else doesDirectoryExist f >>= \b -> if b then readProc du (as ++ [f]) else do hPutStrLn stderr (printf "%s does not exist" f) exitFailure -- Run a process, reading the output. readProc :: String -> [String] -> IO String readProc cmd args = do (r, out, err) <- readProcessWithExitCode cmd args "" hPutStr stderr err case r of ExitSuccess -> return out ExitFailure r -> do hPutStrLn stderr (printf "%s: exit %d " cmd r) exitWith (ExitFailure r) -- Command line options. data Opts = Opts { optHelp :: Bool, optThreshold :: Int, optPrune :: [String], optDuProg :: String, optDuArgs :: [String] } deriving Show defaultOpts = Opts { optHelp = False, optThreshold = 1, optPrune = [], optDuProg = "du", optDuArgs = [] } type OptsTrans = Either (Opts -> Opts) String setOptHelp = Left (\o -> o { optHelp = True }) setOptThreshold t = case reads t of [(t', "")] -> Left (\o -> o { optThreshold = t' }) _ -> Right (printf "threshold %s not an int\n" t) addOptPrune p = Left (\o@Opts { optPrune = ps } -> o { optPrune = p : ps }) setOptDuProg p = Left (\o -> o { optDuProg = p }) addOptDuArg a = Left (\o@Opts { optDuArgs = as } -> o { optDuArgs = a : as }) opts :: [OptDescr OptsTrans] opts = [ Option ['h'] ["help"] (NoArg setOptHelp) "print this message", Option ['t'] ["threshold"] (ReqArg setOptThreshold "N") "ignore differences below this threshold", Option ['p'] ["prune"] (ReqArg addOptPrune "NAME") "ignore entries below directiory NAME (eg. .git)", Option [] ["du-prog"] (ReqArg setOptDuProg "PROG") "use PROG as du", Option [] ["du-arg"] (ReqArg addOptDuArg "ARG") "pass ARG on to du" ] usage = usageInfo ( "Usage: diff-du [--threshold N] [--prune PATH]... PATH PATH\n" ++ "PATH is either\n" ++ "- a directory to run du on OR\n" ++ "- a file (possibly gzipped) containing du output" ) opts -- Helper to apply the record transformations and return the final Opts. getOpts :: ArgOrder OptsTrans -> [OptDescr OptsTrans] -> [String] -> (Opts, [String], [String]) getOpts argOrder opts args = let (os, args', errs) = getOpt argOrder opts args (os', errs') = foldr addOpt (defaultOpts, []) os in (os', args', errs ++ errs') where addOpt :: OptsTrans -> (Opts, [String]) -> (Opts, [String]) addOpt (Left f) (os, errs) = (f os, errs) addOpt (Right err) (os, errs) = (os, errs ++ [err]) main = do args <- getArgs case getOpts RequireOrder opts args of (Opts { optHelp = True }, _, []) -> do putStr usage exitSuccess (o@Opts { optThreshold = t, optPrune = prunes }, [f1, f2], []) -> do s1 <- getDu o f1 s2 <- getDu o f2 comparingDirs <- doesDirectoryExist f1 >>= \d1 -> doesDirectoryExist f2 >>= \d2 -> return (d1 && d2) let (prefix1, prefix2) = if comparingDirs then (Just f1, Just f2) else (Nothing, Nothing) let du1 = sortDuOn path (pruneDu prunes (delPrefixDu prefix1 (readDu s1))) let du2 = sortDuOn path (pruneDu prunes (delPrefixDu prefix2 (readDu s2))) let r = sortDuOnMaxSize ( flattenDu ( addPrefixDu prefix1 prefix2 ( threshDu (smartThresher t) ( diffDu du1 du2)))) putStr (showDuDiff f1 f2 r) (_, _, errs) -> do hPutStr stderr (concat errs ++ usage) exitFailure
pimlott/diff-du
diff-du.hs
bsd-3-clause
12,003
0
23
3,152
4,182
2,219
1,963
216
4
{-# LANGUAGE UndecidableSuperClasses #-} {-# LANGUAGE TypeApplications #-} module Algebra4 where import qualified Prelude as P import LocalPrelude hiding ((.)) import Lattice import Tests import Topology1 hiding (Lawful (..), Semigroup (..), isLawful) -- import Union import Category import Test.SmallCheck.Series hiding (NonNegative) import Test.Tasty import qualified Test.Tasty.SmallCheck as SC import qualified Test.Tasty.QuickCheck as QC import Test.QuickCheck hiding (Testable,NonNegative) import Debug.Trace -- import GHC.Generics import Unsafe.Coerce ------------------------------------------------------------------------------- class Semigroup a where (+) :: a -> a -> a type ValidScalar a = (Scalar a~a, Module a) -- class (ValidScalar (Scalar a), Semigroup a) => Module a where class (Module (Scalar a), Semigroup a) => Module a where -- class Semigroup a => Module a where (.*) :: a -> Scalar a -> a class Module a => Hilbert a where (<>) :: a -> a -> Scalar a -------------------------------------------------------------------------------- unTag :: e (TagAT t1 t2) a -> e (NestAT t1 t2) a unTag = unsafeCoerce reTag :: e (NestAT t1 t2) a -> e (TagAT t1 t2) a reTag = unsafeCoerce -------------------------------------------------------------------------------- instance (Show (AppAT t a), Num (AppAT t a)) => Num (G Semigroup 'Id t a) where fromInteger = Gi . fromInteger instance (Show (AppAT t a), Num (AppAT t a)) => Num (G Module 'Id t a) where fromInteger = GM . fromInteger -- instance (Show (AppAT t a), Num (AppAT t a)) => Num (G Hilbert t a) -- where fromInteger = GH . fromInteger type instance Scalar (G cxt s t a) = G cxt s (NestAT 'Scalar t) a -------------------- class GAlgebra (alg::Type->Constraint) where data G alg (s::AT) (t::AT) a runG :: alg (AppAT t a) => G alg s t a -> AppAT (TagAT s t) a mkG :: AppAT t a -> G alg 'Id t a class (GAlgebra cxt1, GAlgebra cxt2) => EmbedG cxt1 s cxt2 where embedG :: G cxt2 s t a -> G cxt1 s t a instance GAlgebra cxt => EmbedG cxt 'Id cxt where embedG a = a -------------------- instance GAlgebra Semigroup where data G Semigroup s t a where Gi :: AppAT t a -> G Semigroup 'Id t a Gp :: ( EmbedG Semigroup 'Id cxt ) => G cxt 'Id t a -> G cxt 'Id t a -> G Semigroup 'Id t a runG (Gi a) = a runG (Gp a1 a2) = runG a1' + runG a2' where a1' = embedG @Semigroup @'Id a1 a2' = embedG @Semigroup @'Id a2 mkG = Gi instance Semigroup (G Semigroup 'Id t a) where (+) e1 e2 = Gp e1 e2 instance Show (AppAT t a) => Show (G Semigroup s t a) where show (Gi a) = show a show (Gp a1 a2) = "("++show a1'++"+"++show a2'++")" where a1' = embedG @Semigroup @'Id a1 a2' = embedG @Semigroup @'Id a2 -------------------- instance GAlgebra Module where data G Module s t a where GM :: {-#UNPACK#-}!(G Semigroup s t a) -> G Module s t a Gm :: ( EmbedG Module 'Id cxt1 , EmbedG Module 'Scalar cxt2 ) => G cxt1 'Id t a -> G cxt2 'Scalar t a -> G Module 'Id t a runG (GM m) = runG m runG (Gm a1 a2) = runG a1'.*runG a2' where a1' = embedG @Module @'Id a1 a2' = embedG @Module @'Scalar a2 mkG = GM . mkG instance EmbedG Semigroup 'Id Module where embedG (GM a) = a -- instance EmbedG Module 'Scalar Module where embedG a = unsafeCoerce a -- instance Semigroup (G Module 'Id t a) where (+ ) e1 e2 = GM $ Gp e1 e2 -- instance (NestAT 'Scalar (NestAT 'Scalar t) ~ NestAT 'Scalar t) => Module (G Module s t a) where (.*) e1 e2 = _ -- Gm e1 (reTag e2) -- -- instance -- ( Show (AppAT t a) -- , Show (Scalar (AppAT t a)) -- , ValidScalar (Scalar (AppAT t a)) -- ) => Show (G Module t a) -- where -- show (GM a) = show a -- show (Gm a1 a2) = "("++show a1'++".*"++show a2'++")" -- where -- a1' = embedG @Module @'Id a1 -- a2' = embedG @Module @'Scalar a2 -------------------------------------------------------------------------------- instance (Show (AppAT t a), Num (AppAT t a)) => Num (F Semigroup t a) where fromInteger = unTag . Fi . fromInteger instance (Show (AppAT t a), Num (AppAT t a)) => Num (F Module t a) where fromInteger = unTag . FM . fromInteger -- instance (Show (AppAT t a), Num (AppAT t a)) => Num (F Hilbert t a) -- where fromInteger = FH . fromInteger type instance Scalar (F cxt t a) = F cxt (NestAT 'Scalar t) a class FAlgebra (cxt::Type->Constraint) where data F cxt (t::AT) a runF :: cxt (AppAT t a) => F cxt (TagAT t' t) a -> AppAT (TagAT t' t) a mkF :: {-Show (AppAT t a) =>-} AppAT t a -> F cxt (TagAT 'Id t) a -- laws :: [Law cxt t a] -- -- data Law cxt t a = Law -- { name :: String -- , lhs :: F cxt t a -- , rhs :: F cxt t a -- } class (FAlgebra cxt1, FAlgebra cxt2) => EmbedF cxt1 t cxt2 where embedF :: F cxt2 t' a -> F cxt1 (TagAT t t') a instance FAlgebra cxt => EmbedF cxt 'Id cxt where embedF a = reTag a -- instance Semigroup <: Module where -- embedF = FM -- -- instance Semigroup <: Hilbert where -- embedF = FH . embedF -- -- instance Module <: Hilbert where -- embedF = FH -------------------- instance FAlgebra Semigroup where data F Semigroup t a where Fi :: {-Show (AppAT t a) =>-} AppAT t a -> F Semigroup (TagAT 'Id t) a Fp :: -- ( Show (F cxt t a) ( EmbedF Semigroup 'Id cxt ) => F cxt t a -> F cxt t a -> F Semigroup (TagAT 'Id t) a runF (Fi a) = a runF (Fp a1 a2) = runF a1' + runF a2' where a1' = embedF @Semigroup @'Id a1 a2' = embedF @Semigroup @'Id a2 mkF = Fi instance Semigroup (F Semigroup t a) where (+) e1 e2 = unTag $ Fp e1 e2 instance Show (AppAT t a) => Show (F Semigroup t a) where show (Fi a) = show a show (Fp a1 a2) = "("++show a1'++"+"++show a2'++")" where a1' = embedF @Semigroup @'Id a1 a2' = embedF @Semigroup @'Id a2 -------------------- instance FAlgebra Module where data F Module t a where FM :: {-#UNPACK#-}!(F Semigroup (TagAT 'Id t) a) -> F Module (TagAT 'Id t) a Fm :: -- ( FAlgebra cxt -- , Show (F cxt t a) -- , Show (F cxt ('TagAT 'Scalar t) a) -- , Module (AppAT t a) ( EmbedF Module 'Id cxt1 , EmbedF Module 'Scalar cxt2 ) => F cxt1 t a -> F cxt2 (TagAT 'Scalar t) a -> F Module (TagAT 'Id t) a -- runF (FM m) = runF m -- runF (Fm a1 a2) = runF a1'.*runF a2' -- where -- a1' = embedF @Module @'Id a1 -- a2' = embedF @Module @'Scalar a2 mkF = FM . mkF instance EmbedF Semigroup 'Id Module where embedF (FM a) = reTag a instance EmbedF Module 'Scalar Module where embedF a = unsafeCoerce a -- instance EmbedF Module 'Scalar Module where embedF (FM a) = _reTag a instance Semigroup (F Module t a) where (+ ) e1 e2 = unTag $ FM $ Fp e1 e2 instance (NestAT 'Scalar (NestAT 'Scalar t) ~ NestAT 'Scalar t) => Module (F Module t a) where (.*) e1 e2 = unTag $ Fm e1 (reTag e2) -- instance (Semigroup (AppAT t a)) => Semigroup (F Module t a) where (+ ) a1 a2 = FM $ Fp a1 a2 -- instance (Module (AppAT t a)) => Module (F Module t a) where (.*) a1 a2 = Fm a1 (reTag a2) instance ( Show (AppAT t a) , Show (Scalar (AppAT t a)) , ValidScalar (Scalar (AppAT t a)) ) => Show (F Module t a) where show (FM a) = show a show (Fm a1 a2) = "("++show a1'++".*"++show a2'++")" where a1' = embedF @Module @'Id a1 a2' = embedF @Module @'Scalar a2 -------------------- instance FAlgebra Hilbert where data F Hilbert t a where FH :: {-#UNPACK#-}!(F Module t a) -> F Hilbert t a Fd :: {-Hilbert (AppAT t a) =>-} F Hilbert t a -> F Hilbert t a -> F Hilbert (TagAT 'Scalar t) a runF (FH h) = runF h -- runF (Fd a1 a2) = runF a1<>runF a2 -- mkF = FH . mkF -- -- instance (Semigroup (AppAT t a)) => Semigroup (F Hilbert t a) where (+ ) a1 a2 = FH $ FM $ Fp a1 a2 -- instance (Module (AppAT t a)) => Module (F Hilbert t a) where (.*) a1 a2 = FH $ Fm a1 (reTag a2) -- instance (Hilbert (AppAT t a)) => Hilbert (F Hilbert t a) where (<>) a1 a2 = unTag $ Fd a1 a2 -- -- instance Show (F Hilbert t a) where -- show (FH a) = show a -- show (Fd a1 a2) = "("++show a1++"<>"++show a2++")" -------------------------------------------------------------------------------- data Box t a where Box :: AppAT t a -> Box t a data A a where Ai :: a -> A a Ad :: Box 'Id (A a) -> Box 'Id (A a) -> A (Box 'Scalar (A a)) -------------------------------------------------------------------------------- instance Num (AppAT t a) => Num (B t a) where fromInteger = unTag . Bi . fromInteger type instance Scalar (B t a) = B (NestAT 'Scalar t) a data B (t::AT) a where Bi :: AppAT t a -> B (TagAT 'Id t) a Bp :: B (TagAT 'Id t) a -> B (TagAT 'Id t) a -> B (TagAT 'Id t) a Bm :: B (TagAT 'Id t) a -> B (TagAT 'Scalar t) a -> B (TagAT 'Id t) a Bd :: B (TagAT 'Id t) a -> B (TagAT 'Id t) a -> B (TagAT 'Scalar t) a instance Semigroup (B t a) where (+) e1 e2 = unTag $ Bp (reTag e1) (reTag e2) instance Module (B t a) where (.*) e1 e2 = unTag $ Bm (reTag e1) (reTag e2) instance Hilbert (B t a) where (<>) e1 e2 = unTag $ Bd (reTag e1) (reTag e2) goB :: Hilbert (AppAT t a) => B (TagAT t' t) a -> AppAT (TagAT t' t) a goB (Bi a) = a goB (Bp e1 e2) = goB e1+goB e2 goB (Bm e1 e2) = goB e1.*goB e2 goB (Bd e1 e2) = goB e1<>goB e2 instance ( Show (AppAT t a) ) => Show (B (TagAT t' t) a) where show (Bi e) = show e show (Bp e1 e2) = "("++show e1++"+"++show e2++")" show (Bm e1 e2) = "("++show e1++"*"++show e2++")" show (Bd e1 e2) = "("++show e1++"<>"++show e2++")" -------------------------------------------------------------------------------- instance (Num a) => Num (C a b) where fromInteger = Ci . fromInteger type instance Scalar (C a b) = C (Scalar a) b data C a b where Ci :: a -> C a b Cp :: C a b -> C a b -> C a b Cm :: C a b -> Scalar (C a b) -> C a b -- Cm :: C a b -> C (Scalar a) b -> C a b Cd :: C a a -> C a a -> C (Scalar a) a instance Semigroup (C a b) where (+ ) = Cp instance (Scalar (Scalar a)~(Scalar a)) => Module (C a b) where (.*) = Cm instance (Scalar (Scalar a)~(Scalar a)) => Hilbert (C a a) where (<>) = Cd goC :: (Module a, Hilbert b) => C a b -> a goC (Ci a) = a goC (Cp a1 a2) = goC a1+goC a2 -- goC (Cm a1 a2) = goC a1.*goC a2 goC (Cd a1 a2) = goC a1<>goC a2 instance (Show a, Show (Scalar a), Scalar (Scalar a)~Scalar a) => Show (C a b) where show (Ci a) = show a show (Cp e1 e2) = "("++show e1++"+"++show e2++")" show (Cm e1 e2) = "("++show e1++"*"++show e2++")" -- show (Cd e1 e2) = "("++show e1++"<>"++show e2++")" -------------------------------------------------------------------------------- -- instance (Show (AppAT t a), Num (AppAT t a)) => Num (D t a) where fromInteger = Di . fromInteger type instance Scalar (D a b) = D a (Scalar b) data D (t::AT) b where Di :: FixAT t a -> D t a Dp :: FixAT t a -> FixAT t a -> D t a Dm :: FixAT t a -> Scalar (FixAT t a) -> D t a Dd :: FixAT t a -> FixAT t a -> D (TagAT 'Scalar t) a newtype Fix f e = Fix (f (Fix f e)) type D' a b = Fix (D a) b type family FixAT (t::AT) a where FixAT t (Fix (D t) a) = Fix (D t) a FixAT t a = AppAT t a type instance Scalar (Fix (D t) a) = Fix (D (NestAT 'Scalar t)) a instance Semigroup (D' t a) where (+) e1 e2 = Fix $ Dp e1 e2 -- instance Module (D' t a) where (.*) e1 e2 = Fix $ Dm e1 e2 -- instance Hilbert (D' (TagAT 'Scalar t) a) where (<>) e1 e2 = Fix $ Dd e1 e2 runD :: Hilbert (FixAT t a) => D t a -> FixAT t a runD (Di a ) = a runD (Dp a1 a2) = a1+a2 runD (Dm a1 a2) = a1.*a2 -- runD (Dd a1 a2) = a1<>a2 -------------------------------------------------------------------------------- instance (Show (AppAT t a), Num (AppAT t a)) => Num (E t a) where fromInteger = Ei . fromInteger type instance Scalar (E t a) = E (NestAT 'Scalar t) a data E (t::AT) a where Ei :: Show (AppAT t a) => AppAT t a -> E t a Ep :: Semigroup (AppAT t a) => E t a -> E t a -> E t a Em :: Module (AppAT t a) => E t a -> E (TagAT 'Scalar t) a -> E t a Ed :: Hilbert (AppAT t a) => E t a -> E t a -> E (TagAT 'Scalar t) a instance Semigroup (AppAT t a) => Semigroup (E t a) where (+) e1 e2 = Ep e1 e2 -- instance Module (AppAT t a) => Module (E t a) where (.*) e1 e2 = Em e1 (reTag e2) -- instance Hilbert (AppAT t a) => Hilbert (E t a) where (<>) e1 e2 = unTag (Ed e1 e2) instance ( Module (AppAT t a) , AppAT (NestAT 'Scalar t) a~Scalar (AppAT t a) , Scalar (Scalar (AppAT t a))~Scalar (AppAT t a) , NestAT 'Scalar (NestAT 'Scalar t) ~ NestAT 'Scalar t ) => Module (E t a) where (.*) e1 e2 = Em e1 (reTag e2) instance ( Hilbert (AppAT t a) , AppAT (NestAT 'Scalar t) a~Scalar (AppAT t a) , Scalar (Scalar (AppAT t a))~Scalar (AppAT t a) , NestAT 'Scalar (NestAT 'Scalar t) ~ NestAT 'Scalar t ) => Hilbert (E t a) where (<>) e1 e2 = unTag (Ed e1 e2) go :: E t a -> AppAT t a go (Ei a) = a go (Ep e1 e2) = go e1+go e2 go (Em e1 e2) = go e1.*go e2 go (Ed e1 e2) = go e1<>go e2 instance Show (E t a) where show (Ei e) = show e show (Ep e1 e2) = "("++show e1++"+"++show e2++")" show (Em e1 e2) = "("++show e1++"*"++show e2++")" show (Ed e1 e2) = "("++show e1++"<>"++show e2++")" -------------------------------------------------------------------------------- data AT = Id | Scalar | Logic | TagAT AT AT type family AppAT (t::AT) (a::Type) :: Type type instance AppAT 'Id a = a type instance AppAT 'Scalar a = Scalar a type instance AppAT (TagAT t t') a = AppAT t (AppAT t' a) type family NestAT (t::AT) (a::AT) :: AT type instance NestAT 'Id t = t type instance NestAT t 'Id = t type instance NestAT t1 (TagAT 'Id t) = (TagAT t1 t) -- type instance NestAT 'Scalar 'Scalar = 'Scalar -- type instance NestAT 'Scalar (TagAT 'Scalar t) = (TagAT 'Scalar t) -------------------------------------------------------------------------------- type instance Scalar Integer = Integer instance Semigroup Integer where (+) = (P.+) instance Module Integer where (.*) = (P.*) instance Hilbert Integer where (<>) = (P.*) type instance Scalar Int = Int instance Semigroup Int where (+) = (P.+) instance Module Int where (.*) = (P.*) instance Hilbert Int where (<>) = (P.*) type instance Scalar (a,b) = Scalar b instance (Semigroup a,Semigroup b) => Semigroup (a,b) where (a1,b1)+(a2,b2) =(a1+a2,b1+b2) instance (Module a, Module b, Scalar a~Scalar b) => Module (a,b) where (a1,b1).*r =(a1.*r,b1.*r) instance (Hilbert a, Hilbert b, Scalar a~Scalar b, ValidScalar b) => Hilbert (a,b) where (a1,b1)<>(a2,b2) =(a1<>a2)+(b1<>b2) instance (Num a, Num b) => Num (Int,Int) where fromInteger i = (fromInteger i, fromInteger i)
mikeizbicki/homoiconic
old/Algebra4.hs
bsd-3-clause
15,422
0
13
4,302
6,073
3,141
2,932
-1
-1
-- | Possibly convenient facilities for constructing constants. module Futhark.IR.Prop.Constants ( IsValue (..), constant, intConst, floatConst, ) where import Futhark.IR.Syntax.Core -- | If a Haskell type is an instance of 'IsValue', it means that a -- value of that type can be converted to a Futhark 'PrimValue'. -- This is intended to cut down on boilerplate when writing compiler -- code - for example, you'll quickly grow tired of writing @Constant -- (LogVal True) loc@. class IsValue a where value :: a -> PrimValue instance IsValue Int8 where value = IntValue . Int8Value instance IsValue Int16 where value = IntValue . Int16Value instance IsValue Int32 where value = IntValue . Int32Value instance IsValue Int64 where value = IntValue . Int64Value instance IsValue Word8 where value = IntValue . Int8Value . fromIntegral instance IsValue Word16 where value = IntValue . Int16Value . fromIntegral instance IsValue Word32 where value = IntValue . Int32Value . fromIntegral instance IsValue Word64 where value = IntValue . Int64Value . fromIntegral instance IsValue Double where value = FloatValue . Float64Value instance IsValue Float where value = FloatValue . Float32Value instance IsValue Bool where value = BoolValue instance IsValue PrimValue where value = id instance IsValue IntValue where value = IntValue instance IsValue FloatValue where value = FloatValue -- | Create a 'Constant' 'SubExp' containing the given value. constant :: IsValue v => v -> SubExp constant = Constant . value -- | Utility definition for reasons of type ambiguity. intConst :: IntType -> Integer -> SubExp intConst t v = constant $ intValue t v -- | Utility definition for reasons of type ambiguity. floatConst :: FloatType -> Double -> SubExp floatConst t v = constant $ floatValue t v
HIPERFIT/futhark
src/Futhark/IR/Prop/Constants.hs
isc
1,844
0
7
348
388
213
175
42
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.KMS.Types.Sum -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.AWS.KMS.Types.Sum where import Network.AWS.Prelude data DataKeySpec = AES128 | AES256 deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic) instance FromText DataKeySpec where parser = takeLowerText >>= \case "aes_128" -> pure AES128 "aes_256" -> pure AES256 e -> fromTextError $ "Failure parsing DataKeySpec from value: '" <> e <> "'. Accepted values: AES_128, AES_256" instance ToText DataKeySpec where toText = \case AES128 -> "AES_128" AES256 -> "AES_256" instance Hashable DataKeySpec instance ToByteString DataKeySpec instance ToQuery DataKeySpec instance ToHeader DataKeySpec instance ToJSON DataKeySpec where toJSON = toJSONText data GrantOperation = CreateGrant | Decrypt | Encrypt | GenerateDataKey | GenerateDataKeyWithoutPlaintext | ReEncryptFrom | ReEncryptTo | RetireGrant deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic) instance FromText GrantOperation where parser = takeLowerText >>= \case "creategrant" -> pure CreateGrant "decrypt" -> pure Decrypt "encrypt" -> pure Encrypt "generatedatakey" -> pure GenerateDataKey "generatedatakeywithoutplaintext" -> pure GenerateDataKeyWithoutPlaintext "reencryptfrom" -> pure ReEncryptFrom "reencryptto" -> pure ReEncryptTo "retiregrant" -> pure RetireGrant e -> fromTextError $ "Failure parsing GrantOperation from value: '" <> e <> "'. Accepted values: CreateGrant, Decrypt, Encrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, ReEncryptFrom, ReEncryptTo, RetireGrant" instance ToText GrantOperation where toText = \case CreateGrant -> "CreateGrant" Decrypt -> "Decrypt" Encrypt -> "Encrypt" GenerateDataKey -> "GenerateDataKey" GenerateDataKeyWithoutPlaintext -> "GenerateDataKeyWithoutPlaintext" ReEncryptFrom -> "ReEncryptFrom" ReEncryptTo -> "ReEncryptTo" RetireGrant -> "RetireGrant" instance Hashable GrantOperation instance ToByteString GrantOperation instance ToQuery GrantOperation instance ToHeader GrantOperation instance ToJSON GrantOperation where toJSON = toJSONText instance FromJSON GrantOperation where parseJSON = parseJSONText "GrantOperation" data KeyUsageType = EncryptDecrypt deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic) instance FromText KeyUsageType where parser = takeLowerText >>= \case "encrypt_decrypt" -> pure EncryptDecrypt e -> fromTextError $ "Failure parsing KeyUsageType from value: '" <> e <> "'. Accepted values: ENCRYPT_DECRYPT" instance ToText KeyUsageType where toText = \case EncryptDecrypt -> "ENCRYPT_DECRYPT" instance Hashable KeyUsageType instance ToByteString KeyUsageType instance ToQuery KeyUsageType instance ToHeader KeyUsageType instance ToJSON KeyUsageType where toJSON = toJSONText instance FromJSON KeyUsageType where parseJSON = parseJSONText "KeyUsageType"
olorin/amazonka
amazonka-kms/gen/Network/AWS/KMS/Types/Sum.hs
mpl-2.0
3,648
0
12
795
655
338
317
86
0
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QShowEvent.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QShowEvent ( QqShowEvent(..) ,QqShowEvent_nf(..) ,qShowEvent_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui class QqShowEvent x1 where qShowEvent :: x1 -> IO (QShowEvent ()) instance QqShowEvent (()) where qShowEvent () = withQShowEventResult $ qtc_QShowEvent foreign import ccall "qtc_QShowEvent" qtc_QShowEvent :: IO (Ptr (TQShowEvent ())) instance QqShowEvent ((QShowEvent t1)) where qShowEvent (x1) = withQShowEventResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QShowEvent1 cobj_x1 foreign import ccall "qtc_QShowEvent1" qtc_QShowEvent1 :: Ptr (TQShowEvent t1) -> IO (Ptr (TQShowEvent ())) class QqShowEvent_nf x1 where qShowEvent_nf :: x1 -> IO (QShowEvent ()) instance QqShowEvent_nf (()) where qShowEvent_nf () = withObjectRefResult $ qtc_QShowEvent instance QqShowEvent_nf ((QShowEvent t1)) where qShowEvent_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QShowEvent1 cobj_x1 qShowEvent_delete :: QShowEvent a -> IO () qShowEvent_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QShowEvent_delete cobj_x0 foreign import ccall "qtc_QShowEvent_delete" qtc_QShowEvent_delete :: Ptr (TQShowEvent a) -> IO ()
uduki/hsQt
Qtc/Gui/QShowEvent.hs
bsd-2-clause
1,815
0
12
298
431
232
199
43
1
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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 HOLDER 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 Test.Ganeti.OpCodes ( testOpCodes , genOpCodeFromId , OpCodes.OpCode(..) ) where import Prelude () import Ganeti.Prelude import Test.HUnit as HUnit import Test.QuickCheck as QuickCheck import Control.Monad (when) import Data.Char import Data.List import Data.Maybe import qualified Data.Map as Map import qualified Text.JSON as J import Text.Printf (printf) import Test.Ganeti.Objects import Test.Ganeti.Query.Language () import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.Types (genReasonTrail) import Ganeti.BasicTypes import qualified Ganeti.Constants as C import qualified Ganeti.ConstantUtils as CU import qualified Ganeti.OpCodes as OpCodes import Ganeti.Types import Ganeti.OpParams import Ganeti.Objects import Ganeti.JSON {-# ANN module "HLint: ignore Use camelCase" #-} -- * Arbitrary instances arbitraryOpTagsGet :: Gen OpCodes.OpCode arbitraryOpTagsGet = do kind <- arbitrary OpCodes.OpTagsSet kind <$> genTags <*> genOpCodesTagName kind arbitraryOpTagsSet :: Gen OpCodes.OpCode arbitraryOpTagsSet = do kind <- arbitrary OpCodes.OpTagsSet kind <$> genTags <*> genOpCodesTagName kind arbitraryOpTagsDel :: Gen OpCodes.OpCode arbitraryOpTagsDel = do kind <- arbitrary OpCodes.OpTagsDel kind <$> genTags <*> genOpCodesTagName kind $(genArbitrary ''OpCodes.ReplaceDisksMode) $(genArbitrary ''DiskAccess) instance Arbitrary OpCodes.DiskIndex where arbitrary = choose (0, C.maxDisks - 1) >>= OpCodes.mkDiskIndex instance Arbitrary INicParams where arbitrary = INicParams <$> genMaybe genNameNE <*> genMaybe genName <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genName <*> genMaybe genNameNE <*> genMaybe genNameNE instance Arbitrary IDiskParams where arbitrary = IDiskParams <$> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> genMaybe genNameNE <*> arbitrary <*> genMaybe genNameNE <*> genAndRestArguments instance Arbitrary RecreateDisksInfo where arbitrary = oneof [ pure RecreateDisksAll , RecreateDisksIndices <$> arbitrary , RecreateDisksParams <$> arbitrary ] instance Arbitrary DdmOldChanges where arbitrary = oneof [ DdmOldIndex <$> arbitrary , DdmOldMod <$> arbitrary ] instance (Arbitrary a) => Arbitrary (SetParamsMods a) where arbitrary = oneof [ pure SetParamsEmpty , SetParamsDeprecated <$> arbitrary , SetParamsNew <$> arbitrary ] instance Arbitrary ExportTarget where arbitrary = oneof [ ExportTargetLocal <$> genNodeNameNE , ExportTargetRemote <$> pure [] ] arbitraryDataCollector :: Gen (GenericContainer String Bool) arbitraryDataCollector = do els <- listOf . elements $ CU.toList C.dataCollectorNames activation <- vector $ length els return . GenericContainer . Map.fromList $ zip els activation arbitraryDataCollectorInterval :: Gen (Maybe (GenericContainer String Int)) arbitraryDataCollectorInterval = do els <- listOf . elements $ CU.toList C.dataCollectorNames intervals <- vector $ length els genMaybe . return . containerFromList $ zip els intervals genOpCodeFromId :: String -> Maybe ConfigData -> Gen OpCodes.OpCode genOpCodeFromId op_id cfg = case op_id of "OP_TEST_DELAY" -> OpCodes.OpTestDelay <$> arbitrary <*> arbitrary <*> genNodeNamesNE <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_REPLACE_DISKS" -> OpCodes.OpInstanceReplaceDisks <$> getInstanceName <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> genDiskIndices <*> genMaybe genNodeNameNE <*> return Nothing <*> genMaybe genNameNE "OP_INSTANCE_FAILOVER" -> OpCodes.OpInstanceFailover <$> getInstanceName <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNodeNameNE <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNameNE "OP_INSTANCE_MIGRATE" -> OpCodes.OpInstanceMigrate <$> getInstanceName <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe getNodeName <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> arbitrary <*> arbitrary "OP_TAGS_GET" -> arbitraryOpTagsGet "OP_TAGS_SEARCH" -> OpCodes.OpTagsSearch <$> genNameNE "OP_TAGS_SET" -> arbitraryOpTagsSet "OP_TAGS_DEL" -> arbitraryOpTagsDel "OP_CLUSTER_POST_INIT" -> pure OpCodes.OpClusterPostInit "OP_CLUSTER_RENEW_CRYPTO" -> OpCodes.OpClusterRenewCrypto <$> arbitrary -- Node SSL certificates <*> arbitrary -- renew_ssh_keys <*> arbitrary -- ssh_key_type <*> arbitrary -- ssh_key_bits <*> arbitrary -- verbose <*> arbitrary -- debug "OP_CLUSTER_DESTROY" -> pure OpCodes.OpClusterDestroy "OP_CLUSTER_QUERY" -> pure OpCodes.OpClusterQuery "OP_CLUSTER_VERIFY" -> OpCodes.OpClusterVerify <$> arbitrary <*> arbitrary <*> genListSet Nothing <*> genListSet Nothing <*> arbitrary <*> genMaybe getGroupName <*> arbitrary "OP_CLUSTER_VERIFY_CONFIG" -> OpCodes.OpClusterVerifyConfig <$> arbitrary <*> arbitrary <*> genListSet Nothing <*> arbitrary "OP_CLUSTER_VERIFY_GROUP" -> OpCodes.OpClusterVerifyGroup <$> getGroupName <*> arbitrary <*> arbitrary <*> genListSet Nothing <*> genListSet Nothing <*> arbitrary <*> arbitrary "OP_CLUSTER_VERIFY_DISKS" -> OpCodes.OpClusterVerifyDisks <$> genMaybe getGroupName <*> arbitrary "OP_GROUP_VERIFY_DISKS" -> OpCodes.OpGroupVerifyDisks <$> getGroupName <*> arbitrary "OP_CLUSTER_REPAIR_DISK_SIZES" -> OpCodes.OpClusterRepairDiskSizes <$> getInstanceNames "OP_CLUSTER_CONFIG_QUERY" -> OpCodes.OpClusterConfigQuery <$> genFieldsNE "OP_CLUSTER_RENAME" -> OpCodes.OpClusterRename <$> genNameNE "OP_CLUSTER_SET_PARAMS" -> OpCodes.OpClusterSetParams <$> arbitrary -- force <*> emptyMUD -- hv_state <*> emptyMUD -- disk_state <*> genMaybe genName -- vg_name <*> genMaybe arbitrary -- enabled_hypervisors <*> genMaybe genEmptyContainer -- hvparams <*> emptyMUD -- beparams <*> genMaybe genEmptyContainer -- os_hvp <*> genMaybe genEmptyContainer -- osparams <*> genMaybe genEmptyContainer -- osparams_private_cluster <*> genMaybe genEmptyContainer -- diskparams <*> genMaybe arbitrary -- candidate_pool_size <*> genMaybe arbitrary -- max_running_jobs <*> genMaybe arbitrary -- max_tracked_jobs <*> arbitrary -- uid_pool <*> arbitrary -- add_uids <*> arbitrary -- remove_uids <*> arbitrary -- maintain_node_health <*> arbitrary -- prealloc_wipe_disks <*> arbitrary -- nicparams <*> emptyMUD -- ndparams <*> emptyMUD -- ipolicy <*> genMaybe genPrintableAsciiString -- drbd_helper <*> genMaybe genPrintableAsciiString -- default_iallocator <*> emptyMUD -- default_iallocator_params <*> genMaybe genMacPrefix -- mac_prefix <*> genMaybe genPrintableAsciiString -- master_netdev <*> arbitrary -- master_netmask <*> genMaybe (listOf genPrintableAsciiStringNE) -- reserved_lvs <*> genMaybe (listOf ((,) <$> arbitrary <*> genPrintableAsciiStringNE)) -- hidden_os <*> genMaybe (listOf ((,) <$> arbitrary <*> genPrintableAsciiStringNE)) -- blacklisted_os <*> arbitrary -- use_external_mip_script <*> arbitrary -- enabled_disk_templates <*> arbitrary -- modify_etc_hosts <*> arbitrary -- modify_ssh_config <*> genMaybe genName -- file_storage_dir <*> genMaybe genName -- shared_file_storage_dir <*> genMaybe genName -- gluster_file_storage_dir <*> genMaybe genPrintableAsciiString -- install_image <*> genMaybe genPrintableAsciiString -- instance_communication_network <*> genMaybe genPrintableAsciiString -- zeroing_image <*> genMaybe (listOf genPrintableAsciiStringNE) -- compression_tools <*> arbitrary -- enabled_user_shutdown <*> genMaybe arbitraryDataCollector -- enabled_data_collectors <*> arbitraryDataCollectorInterval -- data_collector_interval <*> genMaybe genName -- diagnose_data_collector_filename <*> genMaybe (fromPositive <$> arbitrary) -- maintd round interval <*> genMaybe arbitrary -- enable maintd balancing <*> genMaybe arbitrary -- maintd balancing threshold <*> arbitrary -- enabled_predictive_queue "OP_CLUSTER_REDIST_CONF" -> pure OpCodes.OpClusterRedistConf "OP_CLUSTER_ACTIVATE_MASTER_IP" -> pure OpCodes.OpClusterActivateMasterIp "OP_CLUSTER_DEACTIVATE_MASTER_IP" -> pure OpCodes.OpClusterDeactivateMasterIp "OP_QUERY" -> OpCodes.OpQuery <$> arbitrary <*> arbitrary <*> genNamesNE <*> pure Nothing "OP_QUERY_FIELDS" -> OpCodes.OpQueryFields <$> arbitrary <*> genMaybe genNamesNE "OP_OOB_COMMAND" -> OpCodes.OpOobCommand <$> getNodeNames <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> (arbitrary `suchThat` (>0)) "OP_NODE_REMOVE" -> OpCodes.OpNodeRemove <$> getNodeName <*> return Nothing <*> arbitrary <*> arbitrary "OP_NODE_ADD" -> OpCodes.OpNodeAdd <$> getNodeName <*> emptyMUD <*> emptyMUD <*> genMaybe genNameNE <*> genMaybe genNameNE <*> arbitrary <*> genMaybe genNameNE <*> arbitrary <*> arbitrary <*> emptyMUD <*> arbitrary <*> arbitrary <*> arbitrary "OP_NODE_QUERYVOLS" -> OpCodes.OpNodeQueryvols <$> genNamesNE <*> genNodeNamesNE "OP_NODE_QUERY_STORAGE" -> OpCodes.OpNodeQueryStorage <$> genNamesNE <*> arbitrary <*> getNodeNames <*> genMaybe genNameNE "OP_NODE_MODIFY_STORAGE" -> OpCodes.OpNodeModifyStorage <$> getNodeName <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> pure emptyJSObject "OP_REPAIR_NODE_STORAGE" -> OpCodes.OpRepairNodeStorage <$> getNodeName <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> arbitrary "OP_NODE_SET_PARAMS" -> OpCodes.OpNodeSetParams <$> getNodeName <*> return Nothing <*> arbitrary <*> emptyMUD <*> emptyMUD <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> emptyMUD <*> arbitrary <*> arbitrary <*> arbitrary "OP_NODE_POWERCYCLE" -> OpCodes.OpNodePowercycle <$> getNodeName <*> return Nothing <*> arbitrary "OP_NODE_MIGRATE" -> OpCodes.OpNodeMigrate <$> getNodeName <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe getNodeName <*> return Nothing <*> arbitrary <*> arbitrary <*> genMaybe genNameNE "OP_NODE_EVACUATE" -> OpCodes.OpNodeEvacuate <$> arbitrary <*> getNodeName <*> return Nothing <*> genMaybe getNodeName <*> return Nothing <*> genMaybe genNameNE <*> arbitrary <*> arbitrary "OP_INSTANCE_CREATE" -> OpCodes.OpInstanceCreate <$> genFQDN -- instance_name <*> arbitrary -- force_variant <*> arbitrary -- wait_for_sync <*> arbitrary -- name_check <*> arbitrary -- ignore_ipolicy <*> arbitrary -- opportunistic_locking <*> pure emptyJSObject -- beparams <*> arbitrary -- disks <*> arbitrary -- disk_template <*> genMaybe getGroupName -- group_name <*> arbitrary -- file_driver <*> genMaybe genNameNE -- file_storage_dir <*> pure emptyJSObject -- hvparams <*> arbitrary -- hypervisor <*> genMaybe genNameNE -- iallocator <*> arbitrary -- identify_defaults <*> arbitrary -- ip_check <*> arbitrary -- conflicts_check <*> arbitrary -- mode <*> arbitrary -- nics <*> arbitrary -- no_install <*> pure emptyJSObject -- osparams <*> genMaybe arbitraryPrivateJSObj -- osparams_private <*> genMaybe arbitrarySecretJSObj -- osparams_secret <*> genMaybe genNameNE -- os_type <*> genMaybe getNodeName -- pnode <*> return Nothing -- pnode_uuid <*> genMaybe getNodeName -- snode <*> return Nothing -- snode_uuid <*> genMaybe (pure []) -- source_handshake <*> genMaybe genNodeNameNE -- source_instance_name <*> arbitrary -- source_shutdown_timeout <*> genMaybe genNodeNameNE -- source_x509_ca <*> return Nothing -- src_node <*> genMaybe genNodeNameNE -- src_node_uuid <*> genMaybe genNameNE -- src_path <*> genPrintableAsciiString -- compress <*> arbitrary -- start <*> arbitrary -- forthcoming <*> arbitrary -- commit <*> (genTags >>= mapM mkNonEmpty) -- tags <*> arbitrary -- instance_communication <*> arbitrary -- helper_startup_timeout <*> arbitrary -- helper_shutdown_timeout "OP_INSTANCE_MULTI_ALLOC" -> OpCodes.OpInstanceMultiAlloc <$> arbitrary <*> genMaybe genNameNE <*> pure [] "OP_INSTANCE_REINSTALL" -> OpCodes.OpInstanceReinstall <$> getInstanceName <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> genMaybe (pure emptyJSObject) <*> genMaybe arbitraryPrivateJSObj <*> genMaybe arbitrarySecretJSObj <*> arbitrary <*> arbitrary <*> genMaybe (listOf genPrintableAsciiString) <*> genMaybe (listOf genPrintableAsciiString) "OP_INSTANCE_REMOVE" -> OpCodes.OpInstanceRemove <$> getInstanceName <*> return Nothing <*> arbitrary <*> arbitrary "OP_INSTANCE_RENAME" -> OpCodes.OpInstanceRename <$> getInstanceName <*> return Nothing <*> (genFQDN >>= mkNonEmpty) <*> arbitrary <*> arbitrary "OP_INSTANCE_STARTUP" -> OpCodes.OpInstanceStartup <$> getInstanceName <*> -- instance_name return Nothing <*> -- instance_uuid arbitrary <*> -- force arbitrary <*> -- ignore_offline_nodes pure emptyJSObject <*> -- hvparams pure emptyJSObject <*> -- beparams arbitrary <*> -- no_remember arbitrary <*> -- startup_paused arbitrary -- shutdown_timeout "OP_INSTANCE_SHUTDOWN" -> OpCodes.OpInstanceShutdown <$> getInstanceName <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_REBOOT" -> OpCodes.OpInstanceReboot <$> getInstanceName <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_MOVE" -> OpCodes.OpInstanceMove <$> getInstanceName <*> return Nothing <*> arbitrary <*> arbitrary <*> getNodeName <*> return Nothing <*> genPrintableAsciiString <*> arbitrary "OP_INSTANCE_CONSOLE" -> OpCodes.OpInstanceConsole <$> getInstanceName <*> return Nothing "OP_INSTANCE_ACTIVATE_DISKS" -> OpCodes.OpInstanceActivateDisks <$> getInstanceName <*> return Nothing <*> arbitrary <*> arbitrary "OP_INSTANCE_DEACTIVATE_DISKS" -> OpCodes.OpInstanceDeactivateDisks <$> genFQDN <*> return Nothing <*> arbitrary "OP_INSTANCE_RECREATE_DISKS" -> OpCodes.OpInstanceRecreateDisks <$> getInstanceName <*> return Nothing <*> arbitrary <*> genNodeNamesNE <*> return Nothing <*> genMaybe getNodeName "OP_INSTANCE_QUERY_DATA" -> OpCodes.OpInstanceQueryData <$> arbitrary <*> getInstanceNames <*> arbitrary "OP_INSTANCE_SET_PARAMS" -> OpCodes.OpInstanceSetParams <$> getInstanceName -- instance_name <*> return Nothing -- instance_uuid <*> arbitrary -- force <*> arbitrary -- force_variant <*> arbitrary -- ignore_ipolicy <*> arbitrary -- nics <*> arbitrary -- disks <*> pure emptyJSObject -- beparams <*> arbitrary -- runtime_mem <*> pure emptyJSObject -- hvparams <*> arbitrary -- disk_template <*> pure emptyJSObject -- ext_params <*> arbitrary -- file_driver <*> genMaybe genNameNE -- file_storage_dir <*> genMaybe getNodeName -- pnode <*> return Nothing -- pnode_uuid <*> genMaybe getNodeName -- remote_node <*> return Nothing -- remote_node_uuid <*> genMaybe genNameNE -- iallocator <*> genMaybe genNameNE -- os_name <*> pure emptyJSObject -- osparams <*> genMaybe arbitraryPrivateJSObj -- osparams_private <*> arbitrary -- clear_osparams <*> arbitrary -- clear_osparams_private <*> genMaybe (listOf genPrintableAsciiString) -- remove_osparams <*> genMaybe (listOf genPrintableAsciiString) -- remove_osparams_private <*> arbitrary -- wait_for_sync <*> arbitrary -- offline <*> arbitrary -- conflicts_check <*> arbitrary -- hotplug <*> arbitrary -- hotplug_if_possible <*> arbitrary -- instance_communication "OP_INSTANCE_GROW_DISK" -> OpCodes.OpInstanceGrowDisk <$> getInstanceName <*> return Nothing <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary "OP_INSTANCE_CHANGE_GROUP" -> OpCodes.OpInstanceChangeGroup <$> getInstanceName <*> return Nothing <*> arbitrary <*> genMaybe genNameNE <*> genMaybe (resize maxNodes (listOf genNameNE)) "OP_GROUP_ADD" -> OpCodes.OpGroupAdd <$> genNameNE <*> arbitrary <*> emptyMUD <*> genMaybe genEmptyContainer <*> emptyMUD <*> emptyMUD <*> emptyMUD "OP_GROUP_ASSIGN_NODES" -> OpCodes.OpGroupAssignNodes <$> getGroupName <*> arbitrary <*> getNodeNames <*> return Nothing "OP_GROUP_SET_PARAMS" -> OpCodes.OpGroupSetParams <$> getGroupName <*> arbitrary <*> emptyMUD <*> genMaybe genEmptyContainer <*> emptyMUD <*> emptyMUD <*> emptyMUD "OP_GROUP_REMOVE" -> OpCodes.OpGroupRemove <$> getGroupName "OP_GROUP_RENAME" -> OpCodes.OpGroupRename <$> getGroupName <*> genNameNE "OP_GROUP_EVACUATE" -> OpCodes.OpGroupEvacuate <$> getGroupName <*> arbitrary <*> genMaybe genNameNE <*> genMaybe genNamesNE <*> arbitrary <*> arbitrary "OP_OS_DIAGNOSE" -> OpCodes.OpOsDiagnose <$> genFieldsNE <*> genNamesNE "OP_EXT_STORAGE_DIAGNOSE" -> OpCodes.OpOsDiagnose <$> genFieldsNE <*> genNamesNE "OP_BACKUP_PREPARE" -> OpCodes.OpBackupPrepare <$> getInstanceName <*> return Nothing <*> arbitrary "OP_BACKUP_EXPORT" -> OpCodes.OpBackupExport <$> getInstanceName -- instance_name <*> return Nothing -- instance_uuid <*> genPrintableAsciiString -- compress <*> arbitrary -- shutdown_timeout <*> arbitrary -- target_node <*> return Nothing -- target_node_uuid <*> arbitrary -- shutdown <*> arbitrary -- remove_instance <*> arbitrary -- ignore_remove_failures <*> arbitrary -- mode <*> genMaybe (pure []) -- x509_key_name <*> genMaybe genNameNE -- destination_x509_ca <*> arbitrary -- zero_free_space <*> arbitrary -- zeroing_timeout_fixed <*> arbitrary -- zeroing_timeout_per_mib <*> arbitrary -- long_sleep "OP_BACKUP_REMOVE" -> OpCodes.OpBackupRemove <$> getInstanceName <*> return Nothing "OP_TEST_ALLOCATOR" -> OpCodes.OpTestAllocator <$> arbitrary <*> arbitrary <*> genNameNE <*> genMaybe (pure []) <*> genMaybe (pure []) <*> arbitrary <*> genMaybe genNameNE <*> (genTags >>= mapM mkNonEmpty) <*> arbitrary <*> arbitrary <*> genMaybe genNameNE <*> arbitrary <*> genMaybe genNodeNamesNE <*> arbitrary <*> genMaybe genNamesNE <*> arbitrary <*> arbitrary <*> genMaybe getGroupName "OP_TEST_JQUEUE" -> OpCodes.OpTestJqueue <$> arbitrary <*> arbitrary <*> resize 20 (listOf genFQDN) <*> arbitrary "OP_TEST_OS_PARAMS" -> OpCodes.OpTestOsParams <$> genMaybe arbitrarySecretJSObj "OP_TEST_DUMMY" -> OpCodes.OpTestDummy <$> pure J.JSNull <*> pure J.JSNull <*> pure J.JSNull <*> pure J.JSNull "OP_NETWORK_ADD" -> OpCodes.OpNetworkAdd <$> genNameNE <*> genIPv4Network <*> genMaybe genIPv4Address <*> pure Nothing <*> pure Nothing <*> genMaybe genMacPrefix <*> genMaybe (listOf genIPv4Address) <*> arbitrary <*> (genTags >>= mapM mkNonEmpty) "OP_NETWORK_REMOVE" -> OpCodes.OpNetworkRemove <$> genNameNE <*> arbitrary "OP_NETWORK_SET_PARAMS" -> OpCodes.OpNetworkSetParams <$> genNameNE <*> genMaybe genIPv4Address <*> pure Nothing <*> pure Nothing <*> genMaybe genMacPrefix <*> genMaybe (listOf genIPv4Address) <*> genMaybe (listOf genIPv4Address) "OP_NETWORK_CONNECT" -> OpCodes.OpNetworkConnect <$> getGroupName <*> genNameNE <*> arbitrary <*> genNameNE <*> genPrintableAsciiString <*> arbitrary "OP_NETWORK_DISCONNECT" -> OpCodes.OpNetworkDisconnect <$> getGroupName <*> genNameNE "OP_RESTRICTED_COMMAND" -> OpCodes.OpRestrictedCommand <$> arbitrary <*> getNodeNames <*> return Nothing <*> genNameNE "OP_REPAIR_COMMAND" -> OpCodes.OpRepairCommand <$> getNodeName <*> genNameNE <*> genMaybe genPrintableAsciiStringNE _ -> fail $ "Undefined arbitrary for opcode " ++ op_id where getInstanceName = case cfg of Just c -> fmap (fromMaybe "") . genValidInstanceName $ c Nothing -> genFQDN getNodeName = maybe genFQDN genValidNodeName cfg >>= mkNonEmpty getGroupName = maybe genName genValidGroupName cfg >>= mkNonEmpty getInstanceNames = resize maxNodes (listOf getInstanceName) >>= mapM mkNonEmpty getNodeNames = resize maxNodes (listOf getNodeName) instance Arbitrary OpCodes.OpCode where arbitrary = do op_id <- elements OpCodes.allOpIDs genOpCodeFromId op_id Nothing instance Arbitrary OpCodes.CommonOpParams where arbitrary = OpCodes.CommonOpParams <$> arbitrary <*> arbitrary <*> arbitrary <*> resize 5 arbitrary <*> genMaybe genName <*> genReasonTrail -- * Helper functions -- | Empty JSObject. emptyJSObject :: J.JSObject J.JSValue emptyJSObject = J.toJSObject [] -- | Empty maybe unchecked dictionary. emptyMUD :: Gen (Maybe (J.JSObject J.JSValue)) emptyMUD = genMaybe $ pure emptyJSObject -- | Generates an empty container. genEmptyContainer :: (Ord a) => Gen (GenericContainer a b) genEmptyContainer = pure . GenericContainer $ Map.fromList [] -- | Generates list of disk indices. genDiskIndices :: Gen [DiskIndex] genDiskIndices = do cnt <- choose (0, C.maxDisks) genUniquesList cnt arbitrary -- | Generates a list of node names. genNodeNames :: Gen [String] genNodeNames = resize maxNodes (listOf genFQDN) -- | Generates a list of node names in non-empty string type. genNodeNamesNE :: Gen [NonEmptyString] genNodeNamesNE = genNodeNames >>= mapM mkNonEmpty -- | Gets a node name in non-empty type. genNodeNameNE :: Gen NonEmptyString genNodeNameNE = genFQDN >>= mkNonEmpty -- | Gets a name (non-fqdn) in non-empty type. genNameNE :: Gen NonEmptyString genNameNE = genName >>= mkNonEmpty -- | Gets a list of names (non-fqdn) in non-empty type. genNamesNE :: Gen [NonEmptyString] genNamesNE = resize maxNodes (listOf genNameNE) -- | Returns a list of non-empty fields. genFieldsNE :: Gen [NonEmptyString] genFieldsNE = genFields >>= mapM mkNonEmpty -- | Generate a 3-byte MAC prefix. genMacPrefix :: Gen NonEmptyString genMacPrefix = do octets <- vectorOf 3 $ choose (0::Int, 255) mkNonEmpty . intercalate ":" $ map (printf "%02x") octets -- | JSObject of arbitrary data. -- -- Since JSValue does not implement Arbitrary, I'll simply generate -- (String, String) objects. arbitraryPrivateJSObj :: Gen (J.JSObject (Private J.JSValue)) arbitraryPrivateJSObj = constructor <$> (fromNonEmpty <$> genNameNE) <*> (fromNonEmpty <$> genNameNE) where constructor k v = showPrivateJSObject [(k, v)] -- | JSObject of arbitrary secret data. arbitrarySecretJSObj :: Gen (J.JSObject (Secret J.JSValue)) arbitrarySecretJSObj = constructor <$> (fromNonEmpty <$> genNameNE) <*> (fromNonEmpty <$> genNameNE) where constructor k v = showSecretJSObject [(k, v)] -- | Arbitrary instance for MetaOpCode, defined here due to TH ordering. $(genArbitrary ''OpCodes.MetaOpCode) -- | Small helper to check for a failed JSON deserialisation isJsonError :: J.Result a -> Bool isJsonError (J.Error _) = True isJsonError _ = False -- * Test cases -- | Check that opcode serialization is idempotent. prop_serialization :: OpCodes.OpCode -> Property prop_serialization = testSerialisation -- | Check that Python and Haskell defined the same opcode list. case_AllDefined :: HUnit.Assertion case_AllDefined = do py_stdout <- runPython "from ganeti import opcodes\n\ \from ganeti import serializer\n\ \import sys\n\ \print serializer.Dump([opid for opid in opcodes.OP_MAPPING])\n" "" >>= checkPythonResult py_ops <- case J.decode py_stdout::J.Result [String] of J.Ok ops -> return ops J.Error msg -> HUnit.assertFailure ("Unable to decode opcode names: " ++ msg) -- this already raised an expection, but we need it -- for proper types >> fail "Unable to decode opcode names" let hs_ops = sort OpCodes.allOpIDs extra_py = py_ops \\ hs_ops extra_hs = hs_ops \\ py_ops HUnit.assertBool ("Missing OpCodes from the Haskell code:\n" ++ unlines extra_py) (null extra_py) HUnit.assertBool ("Extra OpCodes in the Haskell code:\n" ++ unlines extra_hs) (null extra_hs) -- | Custom HUnit test case that forks a Python process and checks -- correspondence between Haskell-generated OpCodes and their Python -- decoded, validated and re-encoded version. -- -- Note that we have a strange beast here: since launching Python is -- expensive, we don't do this via a usual QuickProperty, since that's -- slow (I've tested it, and it's indeed quite slow). Rather, we use a -- single HUnit assertion, and in it we manually use QuickCheck to -- generate 500 opcodes times the number of defined opcodes, which -- then we pass in bulk to Python. The drawbacks to this method are -- two fold: we cannot control the number of generated opcodes, since -- HUnit assertions don't get access to the test options, and for the -- same reason we can't run a repeatable seed. We should probably find -- a better way to do this, for example by having a -- separately-launched Python process (if not running the tests would -- be skipped). case_py_compat_types :: HUnit.Assertion case_py_compat_types = do let num_opcodes = length OpCodes.allOpIDs * 100 opcodes <- genSample (vectorOf num_opcodes (arbitrary::Gen OpCodes.MetaOpCode)) let with_sum = map (\o -> (OpCodes.opSummary $ OpCodes.metaOpCode o, o)) opcodes serialized = J.encode opcodes -- check for non-ASCII fields, usually due to 'arbitrary :: String' mapM_ (\op -> when (any (not . isAscii) (J.encode op)) . HUnit.assertFailure $ "OpCode has non-ASCII fields: " ++ show op ) opcodes py_stdout <- runPython "from ganeti import opcodes\n\ \from ganeti import serializer\n\ \import sys\n\ \op_data = serializer.Load(sys.stdin.read())\n\ \decoded = [opcodes.OpCode.LoadOpCode(o) for o in op_data]\n\ \for op in decoded:\n\ \ op.Validate(True)\n\ \encoded = [(op.Summary(), op.__getstate__())\n\ \ for op in decoded]\n\ \print serializer.Dump(\ \ encoded,\ \ private_encoder=serializer.EncodeWithPrivateFields)" serialized >>= checkPythonResult let deserialised = J.decode py_stdout::J.Result [(String, OpCodes.MetaOpCode)] decoded <- case deserialised of J.Ok ops -> return ops J.Error msg -> HUnit.assertFailure ("Unable to decode opcodes: " ++ msg) -- this already raised an expection, but we need it -- for proper types >> fail "Unable to decode opcodes" HUnit.assertEqual "Mismatch in number of returned opcodes" (length decoded) (length with_sum) mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding") ) $ zip with_sum decoded -- | Custom HUnit test case that forks a Python process and checks -- correspondence between Haskell OpCodes fields and their Python -- equivalent. case_py_compat_fields :: HUnit.Assertion case_py_compat_fields = do let hs_fields = sort $ map (\op_id -> (op_id, OpCodes.allOpFields op_id)) OpCodes.allOpIDs py_stdout <- runPython "from ganeti import opcodes\n\ \import sys\n\ \from ganeti import serializer\n\ \fields = [(k, sorted([p[0] for p in v.OP_PARAMS]))\n\ \ for k, v in opcodes.OP_MAPPING.items()]\n\ \print serializer.Dump(fields)" "" >>= checkPythonResult let deserialised = J.decode py_stdout::J.Result [(String, [String])] py_fields <- case deserialised of J.Ok v -> return $ sort v J.Error msg -> HUnit.assertFailure ("Unable to decode op fields: " ++ msg) -- this already raised an expection, but we need it -- for proper types >> fail "Unable to decode op fields" HUnit.assertEqual "Mismatch in number of returned opcodes" (length hs_fields) (length py_fields) HUnit.assertEqual "Mismatch in defined OP_IDs" (map fst hs_fields) (map fst py_fields) mapM_ (\((py_id, py_flds), (hs_id, hs_flds)) -> do HUnit.assertEqual "Mismatch in OP_ID" py_id hs_id HUnit.assertEqual ("Mismatch in fields for " ++ hs_id) py_flds hs_flds ) $ zip hs_fields py_fields -- | Checks that setOpComment works correctly. prop_setOpComment :: OpCodes.MetaOpCode -> String -> Property prop_setOpComment op comment = let (OpCodes.MetaOpCode common _) = OpCodes.setOpComment comment op in OpCodes.opComment common ==? Just comment -- | Tests wrong (negative) disk index. prop_mkDiskIndex_fail :: QuickCheck.Positive Int -> Property prop_mkDiskIndex_fail (Positive i) = case mkDiskIndex (negate i) of Bad msg -> counterexample "error message " $ "Invalid value" `isPrefixOf` msg Ok v -> failTest $ "Succeeded to build disk index '" ++ show v ++ "' from negative value " ++ show (negate i) -- | Tests a few invalid 'readRecreateDisks' cases. case_readRecreateDisks_fail :: Assertion case_readRecreateDisks_fail = do assertBool "null" $ isJsonError (J.readJSON J.JSNull::J.Result RecreateDisksInfo) assertBool "string" $ isJsonError (J.readJSON (J.showJSON "abc")::J.Result RecreateDisksInfo) -- | Tests a few invalid 'readDdmOldChanges' cases. case_readDdmOldChanges_fail :: Assertion case_readDdmOldChanges_fail = do assertBool "null" $ isJsonError (J.readJSON J.JSNull::J.Result DdmOldChanges) assertBool "string" $ isJsonError (J.readJSON (J.showJSON "abc")::J.Result DdmOldChanges) -- | Tests a few invalid 'readExportTarget' cases. case_readExportTarget_fail :: Assertion case_readExportTarget_fail = do assertBool "null" $ isJsonError (J.readJSON J.JSNull::J.Result ExportTarget) assertBool "int" $ isJsonError (J.readJSON (J.showJSON (5::Int))::J.Result ExportTarget) testSuite "OpCodes" [ 'prop_serialization , 'case_AllDefined , 'case_py_compat_types , 'case_py_compat_fields , 'prop_setOpComment , 'prop_mkDiskIndex_fail , 'case_readRecreateDisks_fail , 'case_readDdmOldChanges_fail , 'case_readExportTarget_fail ]
onponomarev/ganeti
test/hs/Test/Ganeti/OpCodes.hs
bsd-2-clause
36,499
0
58
10,558
6,331
3,199
3,132
636
78
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings ( widgetFile , PersistConfig , staticRoot , staticDir , Extra (..) , parseExtra , cassiusFile , juliusFile ) where import Prelude import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Database.Persist.Postgresql (PostgresConf) import Yesod.Default.Config import Yesod.Default.Util import Data.Text (Text) import Data.Yaml import Control.Applicative import Settings.Development import Data.Default (def) import Text.Hamlet import qualified Text.Cassius as C import qualified Text.Julius as J -- | Which Persistent backend this site is using. type PersistConfig = PostgresConf -- Static setting below. Changing these requires a recompile -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticRoot :: AppConfig DefaultEnv x -> Text staticRoot conf = [st|#{appRoot conf}/static|] -- | Settings for 'widgetFile', such as which template languages to support and -- default Hamlet settings. widgetFileSettings :: WidgetFileSettings widgetFileSettings = def { wfsHamletSettings = defaultHamletSettings { hamletNewlines = AlwaysNewlines } } -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if development then widgetFileReload else widgetFileNoReload) widgetFileSettings cassiusFile = (if development then C.cassiusFileReload else C.cassiusFile) juliusFile = (if development then J.juliusFileReload else J.juliusFile) data Extra = Extra { extraCopyright :: Text , extraAnalytics :: Maybe Text -- ^ Google Analytics } deriving Show parseExtra :: DefaultEnv -> Object -> Parser Extra parseExtra _ o = Extra <$> o .: "copyright" <*> o .:? "analytics"
danse/haskellers
tests/Settings.hs
bsd-2-clause
3,044
0
9
612
369
234
135
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module OpenCV.JSON ( ) where import "aeson" Data.Aeson import "aeson" Data.Aeson.Types ( Parser ) import "aeson" Data.Aeson.TH import "base" Data.Int ( Int32 ) import "base" Data.Monoid ( (<>) ) import "base" Data.Proxy ( Proxy(..) ) import qualified "base64-bytestring" Data.ByteString.Base64 as B64 ( encode, decode ) import "linear" Linear.V2 ( V2(..) ) import "linear" Linear.V3 ( V3(..) ) import qualified "text" Data.Text.Encoding as TE ( encodeUtf8, decodeUtf8 ) import "text" Data.Text ( Text ) import qualified "text" Data.Text as T ( unpack ) import "this" OpenCV.Core.Types import "this" OpenCV.Core.Types.Mat.HMat import "this" OpenCV.TypeLevel import "transformers" Control.Monad.Trans.Except -------------------------------------------------------------------------------- newtype J a = J {unJ :: a} instance (ToJSON a) => ToJSON (J (V2 a)) where toJSON (J (V2 x y)) = toJSON (x, y) instance (ToJSON a) => ToJSON (J (V3 a)) where toJSON (J (V3 x y z)) = toJSON (x, y, z) instance (FromJSON a) => FromJSON (J (V2 a)) where parseJSON = fmap (\(x, y) -> J $ V2 x y) . parseJSON instance (FromJSON a) => FromJSON (J (V3 a)) where parseJSON = fmap (\(x, y, z) -> J $ V3 x y z) . parseJSON -------------------------------------------------------------------------------- #define IsoJSON(A, B, A_to_B, B_to_A) \ instance ToJSON A where { \ toJSON = toJSON . (A_to_B :: A -> B); \ }; \ instance FromJSON A where { \ parseJSON = fmap (B_to_A :: B -> A) . parseJSON; \ } -------------------------------------------------------------------------------- IsoJSON(Point2i, J (V2 Int32 ), J . fromPoint, toPoint . unJ) IsoJSON(Point2f, J (V2 Float ), J . fmap realToFrac . fromPoint, toPoint . fmap realToFrac . unJ) IsoJSON(Point2d, J (V2 Double), J . fmap realToFrac . fromPoint, toPoint . fmap realToFrac . unJ) IsoJSON(Point3i, J (V3 Int32 ), J . fromPoint, toPoint . unJ) IsoJSON(Point3f, J (V3 Float ), J . fmap realToFrac . fromPoint, toPoint . fmap realToFrac . unJ) IsoJSON(Point3d, J (V3 Double), J . fmap realToFrac . fromPoint, toPoint . fmap realToFrac . unJ) IsoJSON(Size2i , J (V2 Int32 ), J . fromSize , toSize . unJ) IsoJSON(Size2f , J (V2 Float ), J . fmap realToFrac . fromSize , toSize . fmap realToFrac . unJ) instance ToJSON (Mat shape channels depth) where toJSON = toJSON . matToHMat instance ( ToShapeDS (Proxy shape) , ToChannelsDS (Proxy channels) , ToDepthDS (Proxy depth) ) => FromJSON (Mat shape channels depth) where parseJSON value = do matDyn <- hMatToMat <$> parseJSON value case runExcept $ coerceMat (matDyn :: Mat 'D 'D 'D) of Left err -> fail $ show err Right mat -> pure mat -------------------------------------------------------------------------------- instance ToJSON HElems where toJSON = \case HElems_8U v -> f "8U" v HElems_8S v -> f "8S" v HElems_16U v -> f "16U" v HElems_16S v -> f "16S" v HElems_32S v -> f "32S" v HElems_32F v -> f "32F" v HElems_64F v -> f "64F" v HElems_USRTYPE1 v -> f "USR" $ fmap (TE.decodeUtf8 . B64.encode) v where f :: (ToJSON a) => Text -> a -> Value f typ v = object [ "type" .= typ , "elems" .= v ] instance FromJSON HElems where parseJSON = withObject "HElems" $ \obj -> do typ <- obj .: "type" let elems :: (FromJSON a) => Parser a elems = obj .: "elems" case typ of "8U" -> HElems_8U <$> elems "8S" -> HElems_8S <$> elems "16U" -> HElems_16U <$> elems "16S" -> HElems_16S <$> elems "32S" -> HElems_32S <$> elems "32F" -> HElems_32F <$> elems "64F" -> HElems_64F <$> elems "USR" -> HElems_USRTYPE1 <$> (mapM (either fail pure . B64.decode . TE.encodeUtf8) =<< elems) _ -> fail $ "Unknown Helems type " <> T.unpack typ -------------------------------------------------------------------------------- deriveJSON defaultOptions {fieldLabelModifier = drop 2} ''HMat
Cortlandd/haskell-opencv
src/OpenCV/JSON.hs
bsd-3-clause
4,709
0
20
1,457
1,412
747
665
-1
-1
{-# OPTIONS -#include "HsPosix.h" #-} -- Haskell Binding for dl{open,sym,...} -*-haskell-*- -- -- Author : Volker Stolz <[email protected]> -- -- Created: 2001-11-22 -- -- Derived from GModule.chs by M.Weber & M.Chakravarty which is part of c2hs -- I left the API more or less the same, mostly the flags are different. -- -- License: BSD -- -- Usage: -- ****** -- -- Let's assume you want to open a local shared library 'foo' (./libfoo.so) -- offering a function -- char * mogrify (char*,int) -- and invoke str = mogrify("test",1): -- -- type Fun = CString -> Int -> IO CString -- foreign import dynamic unsafe fun__ :: FunPtr Fun -> Fun -- -- withModule (Just ".") ("libfoo.so") [RTLD_NOW] $ \ mod -> do -- funptr <- moduleSymbol mod "mogrify" -- let fun = fun__ funptr -- withCString "test" $ \ str -> do -- strptr <- fun str 1 -- strstr <- peekCString strptr -- ... module DL {-# DEPRECATED "Use System.Posix.DynamicLinker and System.Posix.DynamicLinker.Prim.Module instead" #-} ( module DLPrim , moduleOpen -- :: String -> ModuleFlags -> IO Module , moduleSymbol -- :: Source -> String -> IO (FunPtr a) , moduleClose -- :: Module -> IO Bool , moduleError -- :: IO String , withModule -- :: Maybe String -- -> String -- -> [ModuleFlags ] -- -> (Module -> IO a) -- -> IO a , withModule_ -- :: Maybe String -- -> String -- -> [ModuleFlags] -- -> (Module -> IO a) -- -> IO () ) where import DLPrim import Foreign.Ptr ( Ptr, nullPtr, FunPtr, nullFunPtr ) import Foreign.C.String ( CString, withCString, peekCString ) -- abstract handle for dynamically loaded module (EXPORTED) -- newtype Module = Module (Ptr ()) unModule :: Module -> (Ptr ()) unModule (Module adr) = adr -- Opens a module (EXPORTED) -- moduleOpen :: String -> [ModuleFlags] -> IO Module moduleOpen mod flags = do modPtr <- withCString mod $ \ modAddr -> dlopen modAddr (packModuleFlags flags) if (modPtr == nullPtr) then moduleError >>= \ err -> ioError (userError ("dlopen: " ++ err)) else return $ Module modPtr -- Gets a symbol pointer from a module (EXPORTED) -- moduleSymbol :: Module -> String -> IO (FunPtr a) moduleSymbol mod sym = do withCString sym $ \ symPtr -> do ptr <- dlsym (unModule mod) symPtr if (ptr /= nullFunPtr) then return ptr else moduleError >>= \ err -> ioError (userError ("dlsym: " ++ err)) -- Closes a module (EXPORTED) -- moduleClose :: Module -> IO () moduleClose mod = dlclose (unModule mod) -- Gets a string describing the last module error (EXPORTED) -- moduleError :: IO String moduleError = peekCString =<< dlerror -- Convenience function, cares for module open- & closing -- additionally returns status of `moduleClose' (EXPORTED) -- withModule :: Maybe String -> String -> [ModuleFlags] -> (Module -> IO a) -> IO a withModule dir mod flags p = do let modPath = case dir of Nothing -> mod Just p -> p ++ if ((head (reverse p)) == '/') then mod else ('/':mod) mod <- moduleOpen modPath flags result <- p mod moduleClose mod return result withModule_ :: Maybe String -> String -> [ModuleFlags] -> (Module -> IO a) -> IO () withModule_ dir mod flags p = withModule dir mod flags p >>= \ _ -> return ()
alekar/hugs
fptools/hslibs/posix/DL.hs
bsd-3-clause
3,627
15
18
1,057
683
380
303
54
3
-- (c) The University of Glasgow 2006 {-# LANGUAGE CPP, DeriveDataTypeable #-} module TcEvidence ( -- HsWrapper HsWrapper(..), (<.>), mkWpTyApps, mkWpEvApps, mkWpEvVarApps, mkWpTyLams, mkWpLams, mkWpLet, mkWpCast, mkWpFun, idHsWrapper, isIdHsWrapper, pprHsWrapper, -- Evidence bindings TcEvBinds(..), EvBindsVar(..), EvBindMap(..), emptyEvBindMap, extendEvBinds, lookupEvBind, evBindMapBinds, foldEvBindMap, EvBind(..), emptyTcEvBinds, isEmptyTcEvBinds, mkGivenEvBind, mkWantedEvBind, EvTerm(..), mkEvCast, evVarsOfTerm, mkEvScSelectors, EvLit(..), evTermCoercion, EvCallStack(..), EvTypeable(..), -- TcCoercion TcCoercion(..), TcCoercionR, TcCoercionN, LeftOrRight(..), pickLR, mkTcReflCo, mkTcNomReflCo, mkTcRepReflCo, mkTcTyConAppCo, mkTcAppCo, mkTcAppCos, mkTcFunCo, mkTcAxInstCo, mkTcUnbranchedAxInstCo, mkTcForAllCo, mkTcForAllCos, mkTcSymCo, mkTcTransCo, mkTcNthCo, mkTcLRCo, mkTcSubCo, maybeTcSubCo, tcDowngradeRole, mkTcTransAppCo, mkTcAxiomRuleCo, mkTcPhantomCo, tcCoercionKind, coVarsOfTcCo, isEqVar, mkTcCoVarCo, isTcReflCo, getTcCoVar_maybe, tcCoercionRole, eqVarRole, unwrapIP, wrapIP ) where #include "HsVersions.h" import Var import Coercion import PprCore () -- Instance OutputableBndr TyVar import TypeRep -- Knows type representation import TcType import Type import TyCon import Class( Class ) import CoAxiom import PrelNames import VarEnv import VarSet import Name import Util import Bag import Pair #if __GLASGOW_HASKELL__ < 709 import Control.Applicative import Data.Traversable (traverse, sequenceA) #endif import qualified Data.Data as Data import Outputable import FastString import SrcLoc import Data.IORef( IORef ) {- Note [TcCoercions] ~~~~~~~~~~~~~~~~~~ | TcCoercions are a hack used by the typechecker. Normally, Coercions have free variables of type (a ~# b): we call these CoVars. However, the type checker passes around equality evidence (boxed up) at type (a ~ b). An TcCoercion is simply a Coercion whose free variables have the boxed type (a ~ b). After we are done with typechecking the desugarer finds the free variables, unboxes them, and creates a resulting real Coercion with kosher free variables. We can use most of the Coercion "smart constructors" to build TcCoercions. However, mkCoVarCo will not work! The equivalent is mkTcCoVarCo. The data type is similar to Coercion.Coercion, with the following differences * Most important, TcLetCo adds let-bindings for coercions. This is what lets us unify two for-all types and generate equality constraints underneath * The kind of a TcCoercion is t1 ~ t2 (resp. Coercible t1 t2) of a Coercion is t1 ~# t2 (resp. t1 ~#R t2) * UnsafeCo aren't required, but we do have TcPhantomCo * Representation invariants are weaker: - we are allowed to have type synonyms in TcTyConAppCo - the first arg of a TcAppCo can be a TcTyConAppCo - TcSubCo is not applied as deep as done with mkSubCo Reason: they'll get established when we desugar to Coercion * TcAxiomInstCo has a [TcCoercion] parameter, and not a [Type] parameter. This differs from the formalism, but corresponds to AxiomInstCo (see [Coercion axioms applied to coercions]). Note [mkTcTransAppCo] ~~~~~~~~~~~~~~~~~~~~~ Suppose we have co1 :: a ~R Maybe co2 :: b ~R Int and we want co3 :: a b ~R Maybe Int This seems sensible enough. But, we can't let (co3 = co1 co2), because that's ill-roled! Note that mkTcAppCo requires a *nominal* second coercion. The way around this is to use transitivity: co3 = (co1 <b>_N) ; (Maybe co2) :: a b ~R Maybe Int Or, it's possible everything is the other way around: co1' :: Maybe ~R a co2' :: Int ~R b and we want co3' :: Maybe Int ~R a b then co3' = (Maybe co2') ; (co1' <b>_N) This is exactly what `mkTcTransAppCo` builds for us. Information for all the arguments tends to be to hand at call sites, so it's quicker than using, say, tcCoercionKind. -} type TcCoercionN = TcCoercion -- A Nominal corecion ~N type TcCoercionR = TcCoercion -- A Representational corecion ~R data TcCoercion = TcRefl Role TcType | TcTyConAppCo Role TyCon [TcCoercion] | TcAppCo TcCoercion TcCoercion | TcForAllCo TyVar TcCoercion | TcCoVarCo EqVar | TcAxiomInstCo (CoAxiom Branched) Int -- Int specifies branch number [TcCoercion] -- See [CoAxiom Index] in Coercion.hs -- This is number of types and coercions are expected to match to CoAxiomRule -- (i.e., the CoAxiomRules are always fully saturated) | TcAxiomRuleCo CoAxiomRule [TcType] [TcCoercion] | TcPhantomCo TcType TcType | TcSymCo TcCoercion | TcTransCo TcCoercion TcCoercion | TcNthCo Int TcCoercion | TcLRCo LeftOrRight TcCoercion | TcSubCo TcCoercion -- Argument is never TcRefl | TcCastCo TcCoercion TcCoercion -- co1 |> co2 | TcLetCo TcEvBinds TcCoercion | TcCoercion Coercion -- embed a Core Coercion deriving (Data.Data, Data.Typeable) isEqVar :: Var -> Bool -- Is lifted coercion variable (only!) isEqVar v = case tyConAppTyCon_maybe (varType v) of Just tc -> tc `hasKey` eqTyConKey Nothing -> False isTcReflCo_maybe :: TcCoercion -> Maybe TcType isTcReflCo_maybe (TcRefl _ ty) = Just ty isTcReflCo_maybe (TcCoercion co) = isReflCo_maybe co isTcReflCo_maybe _ = Nothing isTcReflCo :: TcCoercion -> Bool isTcReflCo (TcRefl {}) = True isTcReflCo (TcCoercion co) = isReflCo co isTcReflCo _ = False getTcCoVar_maybe :: TcCoercion -> Maybe CoVar getTcCoVar_maybe (TcCoVarCo v) = Just v getTcCoVar_maybe _ = Nothing mkTcReflCo :: Role -> TcType -> TcCoercion mkTcReflCo = TcRefl mkTcNomReflCo :: TcType -> TcCoercion mkTcNomReflCo = TcRefl Nominal mkTcRepReflCo :: TcType -> TcCoercion mkTcRepReflCo = TcRefl Representational mkTcFunCo :: Role -> TcCoercion -> TcCoercion -> TcCoercion mkTcFunCo role co1 co2 = mkTcTyConAppCo role funTyCon [co1, co2] mkTcTyConAppCo :: Role -> TyCon -> [TcCoercion] -> TcCoercion mkTcTyConAppCo role tc cos -- No need to expand type synonyms -- See Note [TcCoercions] | Just tys <- traverse isTcReflCo_maybe cos = TcRefl role (mkTyConApp tc tys) -- See Note [Refl invariant] | otherwise = TcTyConAppCo role tc cos -- Input coercion is Nominal -- mkSubCo will do some normalisation. We do not do it for TcCoercions, but -- defer that to desugaring; just to reduce the code duplication a little bit mkTcSubCo :: TcCoercion -> TcCoercion mkTcSubCo (TcRefl _ ty) = TcRefl Representational ty mkTcSubCo co = ASSERT2( tcCoercionRole co == Nominal, ppr co) TcSubCo co -- See Note [Role twiddling functions] in Coercion -- | Change the role of a 'TcCoercion'. Returns 'Nothing' if this isn't -- a downgrade. tcDowngradeRole_maybe :: Role -- desired role -> Role -- current role -> TcCoercion -> Maybe TcCoercion tcDowngradeRole_maybe Representational Nominal = Just . mkTcSubCo tcDowngradeRole_maybe Nominal Representational = const Nothing tcDowngradeRole_maybe Phantom _ = panic "tcDowngradeRole_maybe Phantom" -- not supported (not needed at the moment) tcDowngradeRole_maybe _ Phantom = const Nothing tcDowngradeRole_maybe _ _ = Just -- See Note [Role twiddling functions] in Coercion -- | Change the role of a 'TcCoercion'. Panics if this isn't a downgrade. tcDowngradeRole :: Role -- ^ desired role -> Role -- ^ current role -> TcCoercion -> TcCoercion tcDowngradeRole r1 r2 co = case tcDowngradeRole_maybe r1 r2 co of Just co' -> co' Nothing -> pprPanic "tcDowngradeRole" (ppr r1 <+> ppr r2 <+> ppr co) -- | If the EqRel is ReprEq, makes a TcSubCo; otherwise, does nothing. -- Note that the input coercion should always be nominal. maybeTcSubCo :: EqRel -> TcCoercion -> TcCoercion maybeTcSubCo NomEq = id maybeTcSubCo ReprEq = mkTcSubCo mkTcAxInstCo :: Role -> CoAxiom br -> Int -> [TcType] -> TcCoercion mkTcAxInstCo role ax index tys | ASSERT2( not (role == Nominal && ax_role == Representational) , ppr (ax, tys) ) arity == n_tys = tcDowngradeRole role ax_role $ TcAxiomInstCo ax_br index rtys | otherwise = ASSERT( arity < n_tys ) tcDowngradeRole role ax_role $ foldl TcAppCo (TcAxiomInstCo ax_br index (take arity rtys)) (drop arity rtys) where n_tys = length tys ax_br = toBranchedAxiom ax branch = coAxiomNthBranch ax_br index arity = length $ coAxBranchTyVars branch ax_role = coAxiomRole ax arg_roles = coAxBranchRoles branch rtys = zipWith mkTcReflCo (arg_roles ++ repeat Nominal) tys mkTcAxiomRuleCo :: CoAxiomRule -> [TcType] -> [TcCoercion] -> TcCoercion mkTcAxiomRuleCo = TcAxiomRuleCo mkTcUnbranchedAxInstCo :: Role -> CoAxiom Unbranched -> [TcType] -> TcCoercion mkTcUnbranchedAxInstCo role ax tys = mkTcAxInstCo role ax 0 tys mkTcAppCo :: TcCoercion -> TcCoercion -> TcCoercion -- No need to deal with TyConApp on the left; see Note [TcCoercions] -- Second coercion *must* be nominal mkTcAppCo (TcRefl r ty1) (TcRefl _ ty2) = TcRefl r (mkAppTy ty1 ty2) mkTcAppCo co1 co2 = TcAppCo co1 co2 -- | Like `mkTcAppCo`, but allows the second coercion to be other than -- nominal. See Note [mkTcTransAppCo]. Role r3 cannot be more stringent -- than either r1 or r2. mkTcTransAppCo :: Role -- ^ r1 -> TcCoercion -- ^ co1 :: ty1a ~r1 ty1b -> TcType -- ^ ty1a -> TcType -- ^ ty1b -> Role -- ^ r2 -> TcCoercion -- ^ co2 :: ty2a ~r2 ty2b -> TcType -- ^ ty2a -> TcType -- ^ ty2b -> Role -- ^ r3 -> TcCoercion -- ^ :: ty1a ty2a ~r3 ty1b ty2b mkTcTransAppCo r1 co1 ty1a ty1b r2 co2 ty2a ty2b r3 -- How incredibly fiddly! Is there a better way?? = case (r1, r2, r3) of (_, _, Phantom) -> mkTcPhantomCo (mkAppTy ty1a ty2a) (mkAppTy ty1b ty2b) (_, _, Nominal) -> ASSERT( r1 == Nominal && r2 == Nominal ) mkTcAppCo co1 co2 (Nominal, Nominal, Representational) -> mkTcSubCo (mkTcAppCo co1 co2) (_, Nominal, Representational) -> ASSERT( r1 == Representational ) mkTcAppCo co1 co2 (Nominal, Representational, Representational) -> go (mkTcSubCo co1) (_ , _, Representational) -> ASSERT( r1 == Representational && r2 == Representational ) go co1 where go co1_repr | Just (tc1b, tys1b) <- tcSplitTyConApp_maybe ty1b , nextRole ty1b == r2 = (co1_repr `mkTcAppCo` mkTcNomReflCo ty2a) `mkTcTransCo` (mkTcTyConAppCo Representational tc1b (zipWith mkTcReflCo (tyConRolesX Representational tc1b) tys1b ++ [co2])) | Just (tc1a, tys1a) <- tcSplitTyConApp_maybe ty1a , nextRole ty1a == r2 = (mkTcTyConAppCo Representational tc1a (zipWith mkTcReflCo (tyConRolesX Representational tc1a) tys1a ++ [co2])) `mkTcTransCo` (co1_repr `mkTcAppCo` mkTcNomReflCo ty2b) | otherwise = pprPanic "mkTcTransAppCo" (vcat [ ppr r1, ppr co1, ppr ty1a, ppr ty1b , ppr r2, ppr co2, ppr ty2a, ppr ty2b , ppr r3 ]) mkTcSymCo :: TcCoercion -> TcCoercion mkTcSymCo co@(TcRefl {}) = co mkTcSymCo (TcSymCo co) = co mkTcSymCo co = TcSymCo co mkTcTransCo :: TcCoercion -> TcCoercion -> TcCoercion mkTcTransCo (TcRefl {}) co = co mkTcTransCo co (TcRefl {}) = co mkTcTransCo co1 co2 = TcTransCo co1 co2 mkTcNthCo :: Int -> TcCoercion -> TcCoercion mkTcNthCo n (TcRefl r ty) = TcRefl r (tyConAppArgN n ty) mkTcNthCo n co = TcNthCo n co mkTcLRCo :: LeftOrRight -> TcCoercion -> TcCoercion mkTcLRCo lr (TcRefl r ty) = TcRefl r (pickLR lr (tcSplitAppTy ty)) mkTcLRCo lr co = TcLRCo lr co mkTcPhantomCo :: TcType -> TcType -> TcCoercion mkTcPhantomCo = TcPhantomCo mkTcAppCos :: TcCoercion -> [TcCoercion] -> TcCoercion mkTcAppCos co1 tys = foldl mkTcAppCo co1 tys mkTcForAllCo :: Var -> TcCoercion -> TcCoercion -- note that a TyVar should be used here, not a CoVar (nor a TcTyVar) mkTcForAllCo tv (TcRefl r ty) = ASSERT( isTyVar tv ) TcRefl r (mkForAllTy tv ty) mkTcForAllCo tv co = ASSERT( isTyVar tv ) TcForAllCo tv co mkTcForAllCos :: [Var] -> TcCoercion -> TcCoercion mkTcForAllCos tvs (TcRefl r ty) = ASSERT( all isTyVar tvs ) TcRefl r (mkForAllTys tvs ty) mkTcForAllCos tvs co = ASSERT( all isTyVar tvs ) foldr TcForAllCo co tvs mkTcCoVarCo :: EqVar -> TcCoercion -- ipv :: s ~ t (the boxed equality type) or Coercible s t (the boxed representational equality type) mkTcCoVarCo ipv = TcCoVarCo ipv -- Previously I checked for (ty ~ ty) and generated Refl, -- but in fact ipv may not even (visibly) have a (t1 ~ t2) type, because -- the constraint solver does not substitute in the types of -- evidence variables as it goes. In any case, the optimisation -- will be done in the later zonking phase tcCoercionKind :: TcCoercion -> Pair Type tcCoercionKind co = go co where go (TcRefl _ ty) = Pair ty ty go (TcLetCo _ co) = go co go (TcCastCo _ co) = case getEqPredTys (pSnd (go co)) of (ty1,ty2) -> Pair ty1 ty2 go (TcTyConAppCo _ tc cos)= mkTyConApp tc <$> (sequenceA $ map go cos) go (TcAppCo co1 co2) = mkAppTy <$> go co1 <*> go co2 go (TcForAllCo tv co) = mkForAllTy tv <$> go co go (TcCoVarCo cv) = eqVarKind cv go (TcAxiomInstCo ax ind cos) = let branch = coAxiomNthBranch ax ind tvs = coAxBranchTyVars branch Pair tys1 tys2 = sequenceA (map go cos) in ASSERT( cos `equalLength` tvs ) Pair (substTyWith tvs tys1 (coAxNthLHS ax ind)) (substTyWith tvs tys2 (coAxBranchRHS branch)) go (TcPhantomCo ty1 ty2) = Pair ty1 ty2 go (TcSymCo co) = swap (go co) go (TcTransCo co1 co2) = Pair (pFst (go co1)) (pSnd (go co2)) go (TcNthCo d co) = tyConAppArgN d <$> go co go (TcLRCo lr co) = (pickLR lr . tcSplitAppTy) <$> go co go (TcSubCo co) = go co go (TcAxiomRuleCo ax ts cs) = case coaxrProves ax ts (map tcCoercionKind cs) of Just res -> res Nothing -> panic "tcCoercionKind: malformed TcAxiomRuleCo" go (TcCoercion co) = coercionKind co eqVarRole :: EqVar -> Role eqVarRole cv = getEqPredRole (varType cv) eqVarKind :: EqVar -> Pair Type eqVarKind cv | Just (tc, [_kind,ty1,ty2]) <- tcSplitTyConApp_maybe (varType cv) = ASSERT(tc `hasKey` eqTyConKey) Pair ty1 ty2 | otherwise = pprPanic "eqVarKind, non coercion variable" (ppr cv <+> dcolon <+> ppr (varType cv)) tcCoercionRole :: TcCoercion -> Role tcCoercionRole = go where go (TcRefl r _) = r go (TcTyConAppCo r _ _) = r go (TcAppCo co _) = go co go (TcForAllCo _ co) = go co go (TcCoVarCo cv) = eqVarRole cv go (TcAxiomInstCo ax _ _) = coAxiomRole ax go (TcPhantomCo _ _) = Phantom go (TcSymCo co) = go co go (TcTransCo co1 _) = go co1 -- same as go co2 go (TcNthCo n co) = let Pair ty1 _ = tcCoercionKind co (tc, _) = tcSplitTyConApp ty1 in nthRole (go co) tc n go (TcLRCo _ _) = Nominal go (TcSubCo _) = Representational go (TcAxiomRuleCo c _ _) = coaxrRole c go (TcCastCo c _) = go c go (TcLetCo _ c) = go c go (TcCoercion co) = coercionRole co coVarsOfTcCo :: TcCoercion -> VarSet -- Only works on *zonked* coercions, because of TcLetCo coVarsOfTcCo tc_co = go tc_co where go (TcRefl _ _) = emptyVarSet go (TcTyConAppCo _ _ cos) = mapUnionVarSet go cos go (TcAppCo co1 co2) = go co1 `unionVarSet` go co2 go (TcCastCo co1 co2) = go co1 `unionVarSet` go co2 go (TcForAllCo _ co) = go co go (TcCoVarCo v) = unitVarSet v go (TcAxiomInstCo _ _ cos) = mapUnionVarSet go cos go (TcPhantomCo _ _) = emptyVarSet go (TcSymCo co) = go co go (TcTransCo co1 co2) = go co1 `unionVarSet` go co2 go (TcNthCo _ co) = go co go (TcLRCo _ co) = go co go (TcSubCo co) = go co go (TcLetCo (EvBinds bs) co) = foldrBag (unionVarSet . go_bind) (go co) bs `minusVarSet` get_bndrs bs go (TcLetCo {}) = emptyVarSet -- Harumph. This does legitimately happen in the call -- to evVarsOfTerm in the DEBUG check of setEvBind go (TcAxiomRuleCo _ _ cos) = mapUnionVarSet go cos go (TcCoercion co) = -- the use of coVarsOfTcCo in dsTcCoercion will -- fail if there are any proper, unlifted covars ASSERT( isEmptyVarSet (coVarsOfCo co) ) emptyVarSet -- We expect only coercion bindings, so use evTermCoercion go_bind :: EvBind -> VarSet go_bind (EvBind { eb_rhs =tm }) = go (evTermCoercion tm) get_bndrs :: Bag EvBind -> VarSet get_bndrs = foldrBag (\ (EvBind { eb_lhs = b }) bs -> extendVarSet bs b) emptyVarSet -- Pretty printing instance Outputable TcCoercion where ppr = pprTcCo pprTcCo, pprParendTcCo :: TcCoercion -> SDoc pprTcCo co = ppr_co TopPrec co pprParendTcCo co = ppr_co TyConPrec co ppr_co :: TyPrec -> TcCoercion -> SDoc ppr_co _ (TcRefl r ty) = angleBrackets (ppr ty) <> ppr_role r ppr_co p co@(TcTyConAppCo _ tc [_,_]) | tc `hasKey` funTyConKey = ppr_fun_co p co ppr_co p (TcTyConAppCo r tc cos) = pprTcApp p ppr_co tc cos <> ppr_role r ppr_co p (TcLetCo bs co) = maybeParen p TopPrec $ sep [ptext (sLit "let") <+> braces (ppr bs), ppr co] ppr_co p (TcAppCo co1 co2) = maybeParen p TyConPrec $ pprTcCo co1 <+> ppr_co TyConPrec co2 ppr_co p (TcCastCo co1 co2) = maybeParen p FunPrec $ ppr_co FunPrec co1 <+> ptext (sLit "|>") <+> ppr_co FunPrec co2 ppr_co p co@(TcForAllCo {}) = ppr_forall_co p co ppr_co _ (TcCoVarCo cv) = parenSymOcc (getOccName cv) (ppr cv) ppr_co p (TcAxiomInstCo con ind cos) = pprPrefixApp p (ppr (getName con) <> brackets (ppr ind)) (map pprParendTcCo cos) ppr_co p (TcTransCo co1 co2) = maybeParen p FunPrec $ ppr_co FunPrec co1 <+> ptext (sLit ";") <+> ppr_co FunPrec co2 ppr_co p (TcPhantomCo t1 t2) = pprPrefixApp p (ptext (sLit "PhantomCo")) [pprParendType t1, pprParendType t2] ppr_co p (TcSymCo co) = pprPrefixApp p (ptext (sLit "Sym")) [pprParendTcCo co] ppr_co p (TcNthCo n co) = pprPrefixApp p (ptext (sLit "Nth:") <+> int n) [pprParendTcCo co] ppr_co p (TcLRCo lr co) = pprPrefixApp p (ppr lr) [pprParendTcCo co] ppr_co p (TcSubCo co) = pprPrefixApp p (ptext (sLit "Sub")) [pprParendTcCo co] ppr_co p (TcAxiomRuleCo co ts ps) = maybeParen p TopPrec $ ppr_tc_axiom_rule_co co ts ps ppr_co p (TcCoercion co) = pprPrefixApp p (text "Core co:") [ppr co] ppr_tc_axiom_rule_co :: CoAxiomRule -> [TcType] -> [TcCoercion] -> SDoc ppr_tc_axiom_rule_co co ts ps = ppr (coaxrName co) <> ppTs ts $$ nest 2 (ppPs ps) where ppTs [] = Outputable.empty ppTs [t] = ptext (sLit "@") <> ppr_type TopPrec t ppTs ts = ptext (sLit "@") <> parens (hsep $ punctuate comma $ map pprType ts) ppPs [] = Outputable.empty ppPs [p] = pprParendTcCo p ppPs (p : ps) = ptext (sLit "(") <+> pprTcCo p $$ vcat [ ptext (sLit ",") <+> pprTcCo q | q <- ps ] $$ ptext (sLit ")") ppr_role :: Role -> SDoc ppr_role r = underscore <> pp_role where pp_role = case r of Nominal -> char 'N' Representational -> char 'R' Phantom -> char 'P' ppr_fun_co :: TyPrec -> TcCoercion -> SDoc ppr_fun_co p co = pprArrowChain p (split co) where split :: TcCoercion -> [SDoc] split (TcTyConAppCo _ f [arg,res]) | f `hasKey` funTyConKey = ppr_co FunPrec arg : split res split co = [ppr_co TopPrec co] ppr_forall_co :: TyPrec -> TcCoercion -> SDoc ppr_forall_co p ty = maybeParen p FunPrec $ sep [pprForAll tvs, ppr_co TopPrec rho] where (tvs, rho) = split1 [] ty split1 tvs (TcForAllCo tv ty) = split1 (tv:tvs) ty split1 tvs ty = (reverse tvs, ty) {- ************************************************************************ * * HsWrapper * * ************************************************************************ -} data HsWrapper = WpHole -- The identity coercion | WpCompose HsWrapper HsWrapper -- (wrap1 `WpCompose` wrap2)[e] = wrap1[ wrap2[ e ]] -- -- Hence (\a. []) `WpCompose` (\b. []) = (\a b. []) -- But ([] a) `WpCompose` ([] b) = ([] b a) | WpFun HsWrapper HsWrapper TcType TcType -- (WpFun wrap1 wrap2 t1 t2)[e] = \(x:t1). wrap2[ e wrap1[x] ] :: t2 -- So note that if wrap1 :: exp_arg <= act_arg -- wrap2 :: act_res <= exp_res -- then WpFun wrap1 wrap2 : (act_arg -> arg_res) <= (exp_arg -> exp_res) -- This isn't the same as for mkTcFunCo, but it has to be this way -- because we can't use 'sym' to flip around these HsWrappers | WpCast TcCoercion -- A cast: [] `cast` co -- Guaranteed not the identity coercion -- At role Representational -- Evidence abstraction and application -- (both dictionaries and coercions) | WpEvLam EvVar -- \d. [] the 'd' is an evidence variable | WpEvApp EvTerm -- [] d the 'd' is evidence for a constraint -- Kind and Type abstraction and application | WpTyLam TyVar -- \a. [] the 'a' is a type/kind variable (not coercion var) | WpTyApp KindOrType -- [] t the 't' is a type (not coercion) | WpLet TcEvBinds -- Non-empty (or possibly non-empty) evidence bindings, -- so that the identity coercion is always exactly WpHole deriving (Data.Data, Data.Typeable) (<.>) :: HsWrapper -> HsWrapper -> HsWrapper WpHole <.> c = c c <.> WpHole = c c1 <.> c2 = c1 `WpCompose` c2 mkWpFun :: HsWrapper -> HsWrapper -> TcType -> TcType -> HsWrapper mkWpFun WpHole WpHole _ _ = WpHole mkWpFun WpHole (WpCast co2) t1 _ = WpCast (mkTcFunCo Representational (mkTcRepReflCo t1) co2) mkWpFun (WpCast co1) WpHole _ t2 = WpCast (mkTcFunCo Representational (mkTcSymCo co1) (mkTcRepReflCo t2)) mkWpFun (WpCast co1) (WpCast co2) _ _ = WpCast (mkTcFunCo Representational (mkTcSymCo co1) co2) mkWpFun co1 co2 t1 t2 = WpFun co1 co2 t1 t2 mkWpCast :: TcCoercion -> HsWrapper mkWpCast co | isTcReflCo co = WpHole | otherwise = ASSERT2(tcCoercionRole co == Representational, ppr co) WpCast co mkWpTyApps :: [Type] -> HsWrapper mkWpTyApps tys = mk_co_app_fn WpTyApp tys mkWpEvApps :: [EvTerm] -> HsWrapper mkWpEvApps args = mk_co_app_fn WpEvApp args mkWpEvVarApps :: [EvVar] -> HsWrapper mkWpEvVarApps vs = mkWpEvApps (map EvId vs) mkWpTyLams :: [TyVar] -> HsWrapper mkWpTyLams ids = mk_co_lam_fn WpTyLam ids mkWpLams :: [Var] -> HsWrapper mkWpLams ids = mk_co_lam_fn WpEvLam ids mkWpLet :: TcEvBinds -> HsWrapper -- This no-op is a quite a common case mkWpLet (EvBinds b) | isEmptyBag b = WpHole mkWpLet ev_binds = WpLet ev_binds mk_co_lam_fn :: (a -> HsWrapper) -> [a] -> HsWrapper mk_co_lam_fn f as = foldr (\x wrap -> f x <.> wrap) WpHole as mk_co_app_fn :: (a -> HsWrapper) -> [a] -> HsWrapper -- For applications, the *first* argument must -- come *last* in the composition sequence mk_co_app_fn f as = foldr (\x wrap -> wrap <.> f x) WpHole as idHsWrapper :: HsWrapper idHsWrapper = WpHole isIdHsWrapper :: HsWrapper -> Bool isIdHsWrapper WpHole = True isIdHsWrapper _ = False {- ************************************************************************ * * Evidence bindings * * ************************************************************************ -} data TcEvBinds = TcEvBinds -- Mutable evidence bindings EvBindsVar -- Mutable because they are updated "later" -- when an implication constraint is solved | EvBinds -- Immutable after zonking (Bag EvBind) deriving( Data.Typeable ) data EvBindsVar = EvBindsVar (IORef EvBindMap) Unique -- The Unique is only for debug printing instance Data.Data TcEvBinds where -- Placeholder; we can't travers into TcEvBinds toConstr _ = abstractConstr "TcEvBinds" gunfold _ _ = error "gunfold" dataTypeOf _ = Data.mkNoRepType "TcEvBinds" ----------------- newtype EvBindMap = EvBindMap { ev_bind_varenv :: DVarEnv EvBind } -- Map from evidence variables to evidence terms -- We use @DVarEnv@ here to get deterministic ordering when we -- turn it into a Bag. -- If we don't do that, when we generate let bindings for -- dictionaries in dsTcEvBinds they will be generated in random -- order. -- -- For example: -- -- let $dEq = GHC.Classes.$fEqInt in -- let $$dNum = GHC.Num.$fNumInt in ... -- -- vs -- -- let $dNum = GHC.Num.$fNumInt in -- let $dEq = GHC.Classes.$fEqInt in ... -- -- See Note [Deterministic UniqFM] in UniqDFM for explanation why -- @UniqFM@ can lead to nondeterministic order. emptyEvBindMap :: EvBindMap emptyEvBindMap = EvBindMap { ev_bind_varenv = emptyDVarEnv } extendEvBinds :: EvBindMap -> EvBind -> EvBindMap extendEvBinds bs ev_bind = EvBindMap { ev_bind_varenv = extendDVarEnv (ev_bind_varenv bs) (eb_lhs ev_bind) ev_bind } lookupEvBind :: EvBindMap -> EvVar -> Maybe EvBind lookupEvBind bs = lookupDVarEnv (ev_bind_varenv bs) evBindMapBinds :: EvBindMap -> Bag EvBind evBindMapBinds = foldEvBindMap consBag emptyBag foldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a foldEvBindMap k z bs = foldDVarEnv k z (ev_bind_varenv bs) ----------------- -- All evidence is bound by EvBinds; no side effects data EvBind = EvBind { eb_lhs :: EvVar , eb_rhs :: EvTerm , eb_is_given :: Bool -- True <=> given -- See Note [Tracking redundant constraints] in TcSimplify } mkWantedEvBind :: EvVar -> EvTerm -> EvBind mkWantedEvBind ev tm = EvBind { eb_is_given = False, eb_lhs = ev, eb_rhs = tm } mkGivenEvBind :: EvVar -> EvTerm -> EvBind mkGivenEvBind ev tm = EvBind { eb_is_given = True, eb_lhs = ev, eb_rhs = tm } data EvTerm = EvId EvId -- Any sort of evidence Id, including coercions | EvCoercion TcCoercion -- (Boxed) coercion bindings -- See Note [Coercion evidence terms] | EvCast EvTerm TcCoercion -- d |> co, the coercion being at role representational | EvDFunApp DFunId -- Dictionary instance application [Type] [EvId] | EvDelayedError Type FastString -- Used with Opt_DeferTypeErrors -- See Note [Deferring coercion errors to runtime] -- in TcSimplify | EvSuperClass EvTerm Int -- n'th superclass. Used for both equalities and -- dictionaries, even though the former have no -- selector Id. We count up from _0_ | EvLit EvLit -- Dictionary for KnownNat and KnownSymbol classes. -- Note [KnownNat & KnownSymbol and EvLit] | EvCallStack EvCallStack -- Dictionary for CallStack implicit parameters | EvTypeable Type EvTypeable -- Dictionary for (Typeable ty) deriving( Data.Data, Data.Typeable ) -- | Instructions on how to make a 'Typeable' dictionary. -- See Note [Typeable evidence terms] data EvTypeable = EvTypeableTyCon -- ^ Dictionary for @Typeable (T k1..kn)@ | EvTypeableTyApp EvTerm EvTerm -- ^ Dictionary for @Typeable (s t)@, -- given a dictionaries for @s@ and @t@ | EvTypeableTyLit EvTerm -- ^ Dictionary for a type literal, -- e.g. @Typeable "foo"@ or @Typeable 3@ -- The 'EvTerm' is evidence of, e.g., @KnownNat 3@ -- (see Trac #10348) deriving ( Data.Data, Data.Typeable ) data EvLit = EvNum Integer | EvStr FastString deriving( Data.Data, Data.Typeable ) -- | Evidence for @CallStack@ implicit parameters. data EvCallStack -- See Note [Overview of implicit CallStacks] = EvCsEmpty | EvCsPushCall Name RealSrcSpan EvTerm -- ^ @EvCsPushCall name loc stk@ represents a call to @name@, occurring at -- @loc@, in a calling context @stk@. | EvCsTop FastString RealSrcSpan EvTerm -- ^ @EvCsTop name loc stk@ represents a use of an implicit parameter -- @?name@, occurring at @loc@, in a calling context @stk@. deriving( Data.Data, Data.Typeable ) {- Note [Typeable evidence terms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The EvTypeable data type looks isomorphic to Type, but the EvTerms inside can be EvIds. Eg f :: forall a. Typeable a => a -> TypeRep f x = typeRep (undefined :: Proxy [a]) Here for the (Typeable [a]) dictionary passed to typeRep we make evidence dl :: Typeable [a] = EvTypeable [a] (EvTypeableTyApp EvTypeableTyCon (EvId d)) where d :: Typable a is the lambda-bound dictionary passed into f. Note [Coercion evidence terms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A "coercion evidence term" takes one of these forms co_tm ::= EvId v where v :: t1 ~ t2 | EvCoercion co | EvCast co_tm co We do quite often need to get a TcCoercion from an EvTerm; see 'evTermCoercion'. INVARIANT: The evidence for any constraint with type (t1~t2) is a coercion evidence term. Consider for example [G] d :: F Int a If we have ax7 a :: F Int a ~ (a ~ Bool) then we do NOT generate the constraint [G] (d |> ax7 a) :: a ~ Bool because that does not satisfy the invariant (d is not a coercion variable). Instead we make a binding g1 :: a~Bool = g |> ax7 a and the constraint [G] g1 :: a~Bool See Trac [7238] and Note [Bind new Givens immediately] in TcRnTypes Note [EvBinds/EvTerm] ~~~~~~~~~~~~~~~~~~~~~ How evidence is created and updated. Bindings for dictionaries, and coercions and implicit parameters are carried around in TcEvBinds which during constraint generation and simplification is always of the form (TcEvBinds ref). After constraint simplification is finished it will be transformed to t an (EvBinds ev_bag). Evidence for coercions *SHOULD* be filled in using the TcEvBinds However, all EvVars that correspond to *wanted* coercion terms in an EvBind must be mutable variables so that they can be readily inlined (by zonking) after constraint simplification is finished. Conclusion: a new wanted coercion variable should be made mutable. [Notice though that evidence variables that bind coercion terms from super classes will be "given" and hence rigid] Note [KnownNat & KnownSymbol and EvLit] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A part of the type-level literals implementation are the classes "KnownNat" and "KnownSymbol", which provide a "smart" constructor for defining singleton values. Here is the key stuff from GHC.TypeLits class KnownNat (n :: Nat) where natSing :: SNat n newtype SNat (n :: Nat) = SNat Integer Conceptually, this class has infinitely many instances: instance KnownNat 0 where natSing = SNat 0 instance KnownNat 1 where natSing = SNat 1 instance KnownNat 2 where natSing = SNat 2 ... In practice, we solve `KnownNat` predicates in the type-checker (see typecheck/TcInteract.hs) because we can't have infinately many instances. The evidence (aka "dictionary") for `KnownNat` is of the form `EvLit (EvNum n)`. We make the following assumptions about dictionaries in GHC: 1. The "dictionary" for classes with a single method---like `KnownNat`---is a newtype for the type of the method, so using a evidence amounts to a coercion, and 2. Newtypes use the same representation as their definition types. So, the evidence for `KnownNat` is just a value of the representation type, wrapped in two newtype constructors: one to make it into a `SNat` value, and another to make it into a `KnownNat` dictionary. Also note that `natSing` and `SNat` are never actually exposed from the library---they are just an implementation detail. Instead, users see a more convenient function, defined in terms of `natSing`: natVal :: KnownNat n => proxy n -> Integer The reason we don't use this directly in the class is that it is simpler and more efficient to pass around an integer rather than an entier function, especialy when the `KnowNat` evidence is packaged up in an existential. The story for kind `Symbol` is analogous: * class KnownSymbol * newtype SSymbol * Evidence: EvLit (EvStr n) Note [Overview of implicit CallStacks] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (See https://ghc.haskell.org/trac/ghc/wiki/ExplicitCallStack/ImplicitLocations) The goal of CallStack evidence terms is to reify locations in the program source as runtime values, without any support from the RTS. We accomplish this by assigning a special meaning to implicit parameters of type GHC.Stack.CallStack. A use of a CallStack IP, e.g. head [] = error (show (?loc :: CallStack)) head (x:_) = x will be solved with the source location that gave rise to the IP constraint (here, the use of ?loc). If there is already a CallStack IP in scope, e.g. passed-in as an argument head :: (?loc :: CallStack) => [a] -> a head [] = error (show (?loc :: CallStack)) head (x:_) = x we will push the new location onto the CallStack that was passed in. These two cases are reflected by the EvCallStack evidence type. In the first case, we will create an evidence term EvCsTop "?loc" <?loc's location> EvCsEmpty and in the second we'll have a given constraint [G] d :: IP "loc" CallStack in scope, and will create an evidence term EvCsTop "?loc" <?loc's location> d When we call a function that uses a CallStack IP, e.g. f = head xs we create an evidence term EvCsPushCall "head" <head's location> EvCsEmpty again pushing onto a given evidence term if one exists. This provides a lightweight mechanism for building up call-stacks explicitly, but is notably limited by the fact that the stack will stop at the first function whose type does not include a CallStack IP. For example, using the above definition of head: f :: [a] -> a f = head g = f [] the resulting CallStack will include use of ?loc inside head and the call to head inside f, but NOT the call to f inside g, because f did not explicitly request a CallStack. Important Details: - GHC should NEVER report an insoluble CallStack constraint. - A CallStack (defined in GHC.Stack) is a [(String, SrcLoc)], where the String is the name of the binder that is used at the SrcLoc. SrcLoc is defined in GHC.SrcLoc and contains the package/module/file name, as well as the full source-span. Both CallStack and SrcLoc are kept abstract so only GHC can construct new values. - Consider the use of ?stk in: head :: (?stk :: CallStack) => [a] -> a head [] = error (show ?stk) When solving the use of ?stk we'll have a given [G] d :: IP "stk" CallStack in scope. In the interaction phase, GHC would normally solve the use of ?stk directly from the given, i.e. re-using the dicionary. But this is NOT what we want! We want to generate a *new* CallStack with ?loc's SrcLoc pushed onto the given CallStack. So we must take care in TcInteract.interactDict to prioritize solving wanted CallStacks. - We will automatically solve any wanted CallStack regardless of the name of the IP, i.e. f = show (?stk :: CallStack) g = show (?loc :: CallStack) are both valid. However, we will only push new SrcLocs onto existing CallStacks when the IP names match, e.g. in head :: (?loc :: CallStack) => [a] -> a head [] = error (show (?stk :: CallStack)) the printed CallStack will NOT include head's call-site. This reflects the standard scoping rules of implicit-parameters. (See TcInteract.interactDict) - An EvCallStack term desugars to a CoreExpr of type `IP "some str" CallStack`. The desugarer will need to unwrap the IP newtype before pushing a new call-site onto a given stack (See DsBinds.dsEvCallStack) - We only want to intercept constraints that arose due to the use of an IP or a function call. In particular, we do NOT want to intercept the (?stk :: CallStack) => [a] -> a ~ (?stk :: CallStack) => [a] -> a constraint that arises from the ambiguity check on `head`s type signature. (See TcEvidence.isCallStackIP) -} mkEvCast :: EvTerm -> TcCoercion -> EvTerm mkEvCast ev lco | ASSERT2(tcCoercionRole lco == Representational, (vcat [ptext (sLit "Coercion of wrong role passed to mkEvCast:"), ppr ev, ppr lco])) isTcReflCo lco = ev | otherwise = EvCast ev lco mkEvScSelectors :: EvTerm -> Class -> [TcType] -> [(TcPredType, EvTerm)] mkEvScSelectors ev cls tys = zipWith mk_pr (immSuperClasses cls tys) [0..] where mk_pr pred i = (pred, EvSuperClass ev i) emptyTcEvBinds :: TcEvBinds emptyTcEvBinds = EvBinds emptyBag isEmptyTcEvBinds :: TcEvBinds -> Bool isEmptyTcEvBinds (EvBinds b) = isEmptyBag b isEmptyTcEvBinds (TcEvBinds {}) = panic "isEmptyTcEvBinds" evTermCoercion :: EvTerm -> TcCoercion -- Applied only to EvTerms of type (s~t) -- See Note [Coercion evidence terms] evTermCoercion (EvId v) = mkTcCoVarCo v evTermCoercion (EvCoercion co) = co evTermCoercion (EvCast tm co) = TcCastCo (evTermCoercion tm) co evTermCoercion tm = pprPanic "evTermCoercion" (ppr tm) evVarsOfTerm :: EvTerm -> VarSet evVarsOfTerm (EvId v) = unitVarSet v evVarsOfTerm (EvCoercion co) = coVarsOfTcCo co evVarsOfTerm (EvDFunApp _ _ evs) = mkVarSet evs evVarsOfTerm (EvSuperClass v _) = evVarsOfTerm v evVarsOfTerm (EvCast tm co) = evVarsOfTerm tm `unionVarSet` coVarsOfTcCo co evVarsOfTerm (EvDelayedError _ _) = emptyVarSet evVarsOfTerm (EvLit _) = emptyVarSet evVarsOfTerm (EvCallStack cs) = evVarsOfCallStack cs evVarsOfTerm (EvTypeable _ ev) = evVarsOfTypeable ev evVarsOfTerms :: [EvTerm] -> VarSet evVarsOfTerms = mapUnionVarSet evVarsOfTerm evVarsOfCallStack :: EvCallStack -> VarSet evVarsOfCallStack cs = case cs of EvCsEmpty -> emptyVarSet EvCsTop _ _ tm -> evVarsOfTerm tm EvCsPushCall _ _ tm -> evVarsOfTerm tm evVarsOfTypeable :: EvTypeable -> VarSet evVarsOfTypeable ev = case ev of EvTypeableTyCon -> emptyVarSet EvTypeableTyApp e1 e2 -> evVarsOfTerms [e1,e2] EvTypeableTyLit e -> evVarsOfTerm e {- ************************************************************************ * * Pretty printing * * ************************************************************************ -} instance Outputable HsWrapper where ppr co_fn = pprHsWrapper (ptext (sLit "<>")) co_fn pprHsWrapper :: SDoc -> HsWrapper -> SDoc -- In debug mode, print the wrapper -- otherwise just print what's inside pprHsWrapper doc wrap = getPprStyle (\ s -> if debugStyle s then (help (add_parens doc) wrap False) else doc) where help :: (Bool -> SDoc) -> HsWrapper -> Bool -> SDoc -- True <=> appears in function application position -- False <=> appears as body of let or lambda help it WpHole = it help it (WpCompose f1 f2) = help (help it f2) f1 help it (WpFun f1 f2 t1 _) = add_parens $ ptext (sLit "\\(x") <> dcolon <> ppr t1 <> ptext (sLit ").") <+> help (\_ -> it True <+> help (\_ -> ptext (sLit "x")) f1 True) f2 False help it (WpCast co) = add_parens $ sep [it False, nest 2 (ptext (sLit "|>") <+> pprParendTcCo co)] help it (WpEvApp id) = no_parens $ sep [it True, nest 2 (ppr id)] help it (WpTyApp ty) = no_parens $ sep [it True, ptext (sLit "@") <+> pprParendType ty] help it (WpEvLam id) = add_parens $ sep [ ptext (sLit "\\") <> pp_bndr id, it False] help it (WpTyLam tv) = add_parens $ sep [ptext (sLit "/\\") <> pp_bndr tv, it False] help it (WpLet binds) = add_parens $ sep [ptext (sLit "let") <+> braces (ppr binds), it False] pp_bndr v = pprBndr LambdaBind v <> dot add_parens, no_parens :: SDoc -> Bool -> SDoc add_parens d True = parens d add_parens d False = d no_parens d _ = d instance Outputable TcEvBinds where ppr (TcEvBinds v) = ppr v ppr (EvBinds bs) = ptext (sLit "EvBinds") <> braces (vcat (map ppr (bagToList bs))) instance Outputable EvBindsVar where ppr (EvBindsVar _ u) = ptext (sLit "EvBindsVar") <> angleBrackets (ppr u) instance Outputable EvBind where ppr (EvBind { eb_lhs = v, eb_rhs = e, eb_is_given = is_given }) = sep [ pp_gw <+> ppr v , nest 2 $ equals <+> ppr e ] where pp_gw = brackets (if is_given then char 'G' else char 'W') -- We cheat a bit and pretend EqVars are CoVars for the purposes of pretty printing instance Outputable EvTerm where ppr (EvId v) = ppr v ppr (EvCast v co) = ppr v <+> (ptext (sLit "`cast`")) <+> pprParendTcCo co ppr (EvCoercion co) = ptext (sLit "CO") <+> ppr co ppr (EvSuperClass d n) = ptext (sLit "sc") <> parens (ppr (d,n)) ppr (EvDFunApp df tys ts) = ppr df <+> sep [ char '@' <> ppr tys, ppr ts ] ppr (EvLit l) = ppr l ppr (EvCallStack cs) = ppr cs ppr (EvDelayedError ty msg) = ptext (sLit "error") <+> sep [ char '@' <> ppr ty, ppr msg ] ppr (EvTypeable ty ev) = ppr ev <+> dcolon <+> ptext (sLit "Typeable") <+> ppr ty instance Outputable EvLit where ppr (EvNum n) = integer n ppr (EvStr s) = text (show s) instance Outputable EvCallStack where ppr EvCsEmpty = ptext (sLit "[]") ppr (EvCsTop name loc tm) = angleBrackets (ppr (name,loc)) <+> ptext (sLit ":") <+> ppr tm ppr (EvCsPushCall name loc tm) = angleBrackets (ppr (name,loc)) <+> ptext (sLit ":") <+> ppr tm instance Outputable EvTypeable where ppr EvTypeableTyCon = ptext (sLit "TC") ppr (EvTypeableTyApp t1 t2) = parens (ppr t1 <+> ppr t2) ppr (EvTypeableTyLit t1) = ptext (sLit "TyLit") <> ppr t1 ---------------------------------------------------------------------- -- Helper functions for dealing with IP newtype-dictionaries ---------------------------------------------------------------------- -- | Create a 'Coercion' that unwraps an implicit-parameter or -- overloaded-label dictionary to expose the underlying value. We -- expect the 'Type' to have the form `IP sym ty` or `IsLabel sym ty`, -- and return a 'Coercion' `co :: IP sym ty ~ ty` or -- `co :: IsLabel sym ty ~ Proxy# sym -> ty`. See also -- Note [Type-checking overloaded labels] in TcExpr. unwrapIP :: Type -> Coercion unwrapIP ty = case unwrapNewTyCon_maybe tc of Just (_,_,ax) -> mkUnbranchedAxInstCo Representational ax tys Nothing -> pprPanic "unwrapIP" $ text "The dictionary for" <+> quotes (ppr tc) <+> text "is not a newtype!" where (tc, tys) = splitTyConApp ty -- | Create a 'Coercion' that wraps a value in an implicit-parameter -- dictionary. See 'unwrapIP'. wrapIP :: Type -> Coercion wrapIP ty = mkSymCo (unwrapIP ty)
elieux/ghc
compiler/typecheck/TcEvidence.hs
bsd-3-clause
45,142
0
17
12,154
9,082
4,696
4,386
581
17
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/Attoparsec/Types.hs" #-} -- | -- Module : Data.Attoparsec.Types -- Copyright : Bryan O'Sullivan 2007-2015 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : unknown -- -- Simple, efficient parser combinators for strings, loosely based on -- the Parsec library. module Data.Attoparsec.Types ( Parser , IResult(..) , Chunk(chunkElemToChar) ) where import Data.Attoparsec.Internal.Types (Parser(..), IResult(..), Chunk(..))
phischu/fragnix
tests/packages/scotty/Data.Attoparsec.Types.hs
bsd-3-clause
559
0
6
112
69
52
17
10
0
{-# LANGUAGE CPP #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Buffer.Region -- License : GPL-2 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- This module defines buffer operation on regions module Yi.Buffer.Region ( module Yi.Region , swapRegionsB , deleteRegionB , replaceRegionB , readRegionB , mapRegionB , modifyRegionB , winRegionB , inclusiveRegionB , blockifyRegion , joinLinesB , concatLinesB , linesOfRegionB ) where import Control.Monad (when) import Data.Char (isSpace) import Data.List (sort) import Yi.Buffer.Misc import Yi.Region import Yi.Rope (YiString) import qualified Yi.Rope as R (YiString, cons, dropWhile, filter , lines, lines', map, null, length) import Yi.String (overInit) import Yi.Utils (SemiNum ((~-))) import Yi.Window (winRegion) winRegionB :: BufferM Region winRegionB = askWindow winRegion -- | Delete an arbitrary part of the buffer deleteRegionB :: Region -> BufferM () deleteRegionB r = deleteNAt (regionDirection r) (fromIntegral (regionEnd r ~- regionStart r)) (regionStart r) readRegionB :: Region -> BufferM YiString readRegionB r = nelemsB (fromIntegral (regionEnd r - i)) i where i = regionStart r -- | Replace a region with a given rope. replaceRegionB :: Region -> YiString -> BufferM () replaceRegionB r s = do deleteRegionB r insertNAt s $ regionStart r -- | Map the given function over the characters in the region. mapRegionB :: Region -> (Char -> Char) -> BufferM () mapRegionB r f = do text <- readRegionB r replaceRegionB r (R.map f text) -- | Swap the content of two Regions swapRegionsB :: Region -> Region -> BufferM () swapRegionsB r r' | regionStart r > regionStart r' = swapRegionsB r' r | otherwise = do w0 <- readRegionB r w1 <- readRegionB r' replaceRegionB r' w0 replaceRegionB r w1 -- | Modifies the given region according to the given -- string transformation function modifyRegionB :: (R.YiString -> R.YiString) -- ^ The string modification function -> Region -- ^ The region to modify -> BufferM () modifyRegionB f region = f <$> readRegionB region >>= replaceRegionB region -- | Extend the right bound of a region to include it. inclusiveRegionB :: Region -> BufferM Region inclusiveRegionB r = if regionStart r <= regionEnd r then mkRegion (regionStart r) <$> pointAfterCursorB (regionEnd r) else mkRegion <$> pointAfterCursorB (regionStart r) <*> pure (regionEnd r) -- | See a region as a block/rectangular region, -- since regions are represented by two point, this returns -- a list of small regions form this block region. blockifyRegion :: Region -> BufferM [Region] blockifyRegion r = savingPointB $ do [lowCol, highCol] <- sort <$> mapM colOf [regionStart r, regionEnd r] startLine <- lineOf $ regionStart r endLine <- lineOf $ regionEnd r when (startLine > endLine) $ fail "blockifyRegion: impossible" mapM (\line -> mkRegion <$> pointOfLineColB line lowCol <*> pointOfLineColB line (1 + highCol)) [startLine..endLine] -- | Joins lines in the region with a single space, skipping any empty -- lines. joinLinesB :: Region -> BufferM () joinLinesB = savingPointB . modifyRegionB g' where g' = overInit $ mconcat . pad . R.lines pad :: [R.YiString] -> [R.YiString] pad [] = [] pad (x:xs) = x : fmap (skip (R.cons ' ' . R.dropWhile isSpace)) xs skip g x = if R.null x then x else g x -- | Concatenates lines in the region preserving the trailing newline -- if any. concatLinesB :: Region -> BufferM () concatLinesB = savingPointB . modifyRegionB (overInit $ R.filter (/= '\n')) -- | Gets the lines of a region (as a region), preserving newlines. Thus the -- resulting list of regions is a partition of the original region. -- -- The direction of the region is preserved and all smaller regions will -- retain that direction. -- -- Note that regions should never be empty, so it would be odd for this to -- return an empty list... linesOfRegionB :: Region -> BufferM [Region] linesOfRegionB region = do let start = regionStart region direction = regionDirection region ls <- R.lines' <$> readRegionB region return $ case ls of [] -> [] (l:ls') -> let initialRegion = mkRegion' direction start (start + fromIntegral (R.length l)) in scanl nextRegion initialRegion ls' -- | Given some text and the previous region, finds the next region -- (used for implementing linesOfRegionB, not generally useful) nextRegion :: Region -> R.YiString -> Region nextRegion r l = mkRegion' (regionDirection r) (regionEnd r) (regionEnd r + len) where len = fromIntegral $ R.length l
noughtmare/yi
yi-core/src/Yi/Buffer/Region.hs
gpl-2.0
5,095
0
21
1,317
1,235
643
592
88
3
-- | A non-validating XML parser. For the input grammar, see -- <http://www.w3.org/TR/REC-xml>. module Text.XML.HaXml.ParseLazy ( -- * Parse a whole document xmlParse -- , xmlParse' -- * Parse just a DTD , dtdParse -- , dtdParse' -- * Parse a partial document , xmlParseWith -- * Individual parsers for use with /xmlParseWith/ and module SAX , document, element, content , comment, chardata , reference, doctypedecl , processinginstruction , elemtag, qname, name, tok , elemOpenTag, elemCloseTag , emptySTs, XParser -- * These general utility functions don't belong here , fst3, snd3, thd3 ) where -- An XML parser, written using a slightly extended version of the -- Hutton/Meijer parser combinators. The input is tokenised internally -- by the lexer xmlLex. Whilst parsing, we gather a symbol -- table of entity references. PERefs must be defined before use, so we -- expand their uses as we encounter them, forcing the remainder of the -- input to be re-lexed and re-parsed. GERefs are simply stored for -- later retrieval. import Prelude hiding (either,maybe,sequence,catch) import qualified Prelude (either) import Data.Maybe hiding (maybe) import Data.List (intersperse) -- debugging only import Data.Char (isSpace,isDigit,isHexDigit) import Control.Monad hiding (sequence) import Numeric (readDec,readHex) --import Control.Exception (catch) import Text.XML.HaXml.Types import Text.XML.HaXml.Namespaces import Text.XML.HaXml.Posn import Text.XML.HaXml.Lex import Text.ParserCombinators.Poly.StateLazy import System.FilePath (combine, dropFileName) #if ( defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ > 502 ) || \ ( defined(__NHC__) && __NHC__ > 114 ) || defined(__HUGS__) import System.IO.Unsafe (unsafePerformIO) #elif defined(__GLASGOW_HASKELL__) import IOExts (unsafePerformIO) #elif defined(__NHC__) import IOExtras (unsafePerformIO) #elif defined(__HBC__) import UnsafePerformIO #endif -- #define DEBUG #if defined(DEBUG) # if ( defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ > 502 ) || \ ( defined(__NHC__) && __NHC__ > 114 ) || defined(__HUGS__) import Debug.Trace(trace) # elif defined(__GLASGOW_HASKELL__) import IOExts(trace) # elif defined(__NHC__) || defined(__HBC__) import NonStdTrace # endif v `debug` s = trace s v #else v `debug` _ = v #endif debug :: a -> String -> a -- | To parse a whole document, @xmlParse file content@ takes a filename -- (for generating error reports) and the string content of that file. -- A parse error causes program failure, with message to stderr. xmlParse :: String -> String -> Document Posn {- -- | To parse a whole document, @xmlParse' file content@ takes a filename -- (for generating error reports) and the string content of that file. -- Any parse error message is passed back to the caller through the -- @Either@ type. xmlParse' :: String -> String -> Either String (Document Posn) -} -- | To parse just a DTD, @dtdParse file content@ takes a filename -- (for generating error reports) and the string content of that -- file. If no DTD was found, you get @Nothing@ rather than an error. -- However, if a DTD is found but contains errors, the program crashes. dtdParse :: String -> String -> Maybe DocTypeDecl {- -- | To parse just a DTD, @dtdParse' file content@ takes a filename -- (for generating error reports) and the string content of that -- file. If no DTD was found, you get @Right Nothing@. -- If a DTD was found but contains errors, you get a @Left message@. dtdParse' :: String -> String -> Either String (Maybe DocTypeDecl) xmlParse' name inp = xmlParse name inp `catch` (Left . show) dtdParse' name inp = dtdParse name inp `catch` (Left . show) -} xmlParse name = fst3 . runParser (toEOF document) emptySTs . xmlLex name dtdParse name = fst3 . runParser justDTD emptySTs . xmlLex name toEOF :: XParser a -> XParser a toEOF = id -- there are other possible implementations... -- | To parse a partial document, e.g. from an XML-based stream protocol, -- where you may later want to get more document elements from the same -- stream. Arguments are: a parser for the item you want, and the -- already-lexed input to parse from. Returns the item you wanted -- (or an error message), plus the remainder of the input. xmlParseWith :: XParser a -> [(Posn,TokenT)] -> (Either String a, [(Posn,TokenT)]) xmlParseWith p = (\(v,_,s)->(Right v,s)) . runParser p emptySTs ---- Symbol table stuff ---- type SymTabs = (SymTab PEDef, SymTab EntityDef) -- | Some empty symbol tables for GE and PE references. emptySTs :: SymTabs emptySTs = (emptyST, emptyST) addPE :: String -> PEDef -> SymTabs -> SymTabs addPE n v (pe,ge) = (addST n v pe, ge) addGE :: String -> EntityDef -> SymTabs -> SymTabs addGE n v (pe,ge) = let newge = addST n v ge in newge `seq` (pe, newge) lookupPE :: String -> SymTabs -> Maybe PEDef lookupPE s (pe,_ge) = lookupST s pe flattenEV :: EntityValue -> String flattenEV (EntityValue evs) = concatMap flatten evs where flatten (EVString s) = s flatten (EVRef (RefEntity r)) = "&" ++r++";" flatten (EVRef (RefChar r)) = "&#"++show r++";" -- flatten (EVPERef n) = "%" ++n++";" ---- Misc ---- fst3 :: (a,b,c) -> a snd3 :: (a,b,c) -> b thd3 :: (a,b,c) -> c fst3 (a,_,_) = a snd3 (_,a,_) = a thd3 (_,_,a) = a ---- Auxiliary Parsing Functions ---- -- | XParser is just a specialisation of the PolyStateLazy parser. type XParser a = Parser SymTabs (Posn,TokenT) a -- | Return the next token from the input only if it matches the given token. tok :: TokenT -> XParser TokenT tok t = do (p,t') <- next case t' of TokError _ -> report failBad (show t) p t' _ | t'==t -> return t | otherwise -> report fail (show t) p t' nottok :: [TokenT] -> XParser TokenT nottok ts = do (p,t) <- next if t`elem`ts then report fail ("no "++show t) p t else return t -- | Return a qualified name (although the namespace qualification is not -- processed here; this is merely to get the correct type). qname :: XParser QName qname = fmap N name -- | Return just a name, e.g. element name, attribute name. name :: XParser Name name = do (p,tok) <- next case tok of TokName s -> return s TokError _ -> report failBad "a name" p tok _ -> report fail "a name" p tok string, freetext :: XParser String string = do (p,t) <- next case t of TokName s -> return s _ -> report fail "text" p t freetext = do (p,t) <- next case t of TokFreeText s -> return s _ -> report fail "text" p t maybe :: XParser a -> XParser (Maybe a) maybe p = ( p >>= return . Just) `onFail` ( return Nothing) either :: XParser a -> XParser b -> XParser (Either a b) either p q = ( p >>= return . Left) `onFail` ( q >>= return . Right) word :: String -> XParser () word s = do { x <- next ; case x of (_p,TokName n) | s==n -> return () (_p,TokFreeText n) | s==n -> return () ( p,t@(TokError _)) -> report failBad (show s) p t ( p,t) -> report fail (show s) p t } posn :: XParser Posn posn = do { x@(p,_) <- next ; reparse [x] ; return p } nmtoken :: XParser NmToken nmtoken = (string `onFail` freetext) failP, failBadP :: String -> XParser a failP msg = do { p <- posn; fail (msg++"\n at "++show p) } failBadP msg = do { p <- posn; failBad (msg++"\n at "++show p) } report :: (String->XParser a) -> String -> Posn -> TokenT -> XParser a report fail expect p t = fail ("Expected "++expect++" but found "++show t ++"\n in "++show p) adjustErrP :: XParser a -> (String->String) -> XParser a p `adjustErrP` f = p `onFail` do pn <- posn (p `adjustErr` f) `adjustErr` (++show pn) peRef :: XParser a -> XParser a peRef p = p `onFail` do pn <- posn n <- pereference tr <- stQuery (lookupPE n) `debug` ("Looking up %"++n) case tr of Just (PEDefEntityValue ev) -> do reparse (xmlReLex (posInNewCxt ("macro %"++n++";") (Just pn)) (flattenEV ev)) `debug` (" defn: "++flattenEV ev) peRef p Just (PEDefExternalID (PUBLIC _ (SystemLiteral f))) -> do let f' = combine (dropFileName $ posnFilename pn) f val = unsafePerformIO (readFile f') reparse (xmlReLex (posInNewCxt f' (Just pn)) val) `debug` (" reading from file "++f') peRef p Just (PEDefExternalID (SYSTEM (SystemLiteral f))) -> do let f' = combine (dropFileName $ posnFilename pn) f val = unsafePerformIO (readFile f') reparse (xmlReLex (posInNewCxt f' (Just pn)) val) `debug` (" reading from file "++f') peRef p Nothing -> fail ("PEReference use before definition: "++"%"++n++";" ++"\n at "++show pn) blank :: XParser a -> XParser a blank p = p `onFail` do n <- pereference tr <- stQuery (lookupPE n) `debug` ("Looking up %"++n++" (is blank?)") case tr of Just (PEDefEntityValue ev) | all isSpace (flattenEV ev) -> do blank p `debug` "Empty macro definition" Just _ -> failP ("expected a blank PERef macro: "++"%"++n++";") Nothing -> failP ("PEReference use before definition: "++"%"++n++";") ---- XML Parsing Functions ---- justDTD :: XParser (Maybe DocTypeDecl) justDTD = do (ExtSubset _ ds) <- extsubset `debug` "Trying external subset" if null ds then fail "empty" else return (Just (DTD (N "extsubset") Nothing (concatMap extract ds))) `onFail` do (Prolog _ _ dtd _) <- prolog return dtd where extract (ExtMarkupDecl m) = [m] extract (ExtConditionalSect (IncludeSect i)) = concatMap extract i extract (ExtConditionalSect (IgnoreSect _)) = [] -- | Return an entire XML document including prolog and trailing junk. document :: XParser (Document Posn) document = do -- p <- prolog `adjustErr` ("unrecognisable XML prolog\n"++) -- e <- element -- ms <- many misc -- (_,ge) <- stGet -- return (Document p ge e ms) return Document `apply` (prolog `adjustErr` ("unrecognisable XML prolog\n"++)) `apply` (fmap snd stGet) `apply` element `apply` many misc -- | Return an XML comment. comment :: XParser Comment comment = do bracket (tok TokCommentOpen) (tok TokCommentClose) freetext -- tok TokCommentOpen -- commit $ do -- c <- freetext -- tok TokCommentClose -- return c -- | Parse a processing instruction. processinginstruction :: XParser ProcessingInstruction processinginstruction = do tok TokPIOpen commit $ do n <- string `onFail` failP "processing instruction has no target" f <- freetext tok TokPIClose `onFail` failP ("missing ?> in <?"++n) return (n, f) cdsect :: XParser CDSect cdsect = do tok TokSectionOpen bracket (tok (TokSection CDATAx)) (commit $ tok TokSectionClose) chardata prolog :: XParser Prolog prolog = do x <- maybe xmldecl m1 <- many misc dtd <- maybe doctypedecl m2 <- many misc return (Prolog x m1 dtd m2) xmldecl :: XParser XMLDecl xmldecl = do tok TokPIOpen (word "xml" `onFail` word "XML") p <- posn s <- freetext tok TokPIClose `onFail` failBadP "missing ?> in <?xml ...?>" -- raise ((runParser aux emptySTs . xmlReLex p) s) return (fst3 ((runParser aux emptySTs . xmlReLex p) s)) where aux = do v <- versioninfo `onFail` failP "missing XML version info" e <- maybe encodingdecl s <- maybe sddecl return (XMLDecl v e s) -- raise (Left err, _, _) = failP err -- raise (Right ok, _, _) = return ok versioninfo :: XParser VersionInfo versioninfo = do (word "version" `onFail` word "VERSION") tok TokEqual bracket (tok TokQuote) (commit $ tok TokQuote) freetext misc :: XParser Misc misc = oneOf' [ ("<!--comment-->", comment >>= return . Comment) , ("<?PI?>", processinginstruction >>= return . PI) ] -- | Return a DOCTYPE decl, indicating a DTD. doctypedecl :: XParser DocTypeDecl doctypedecl = do tok TokSpecialOpen tok (TokSpecial DOCTYPEx) commit $ do n <- qname eid <- maybe externalid es <- maybe (bracket (tok TokSqOpen) (commit $ tok TokSqClose) (many (peRef markupdecl))) blank (tok TokAnyClose) `onFail` failP "missing > in DOCTYPE decl" return (DTD n eid (case es of { Nothing -> []; Just e -> e })) -- | Return a DTD markup decl, e.g. ELEMENT, ATTLIST, etc markupdecl :: XParser MarkupDecl markupdecl = oneOf' [ ("ELEMENT", elementdecl >>= return . Element) , ("ATTLIST", attlistdecl >>= return . AttList) , ("ENTITY", entitydecl >>= return . Entity) , ("NOTATION", notationdecl >>= return . Notation) , ("misc", misc >>= return . MarkupMisc) ] `adjustErrP` ("when looking for a markup decl,\n"++) -- (\ (ELEMENT, ATTLIST, ENTITY, NOTATION, <!--comment-->, or <?PI?>") extsubset :: XParser ExtSubset extsubset = do td <- maybe textdecl ds <- many (peRef extsubsetdecl) return (ExtSubset td ds) extsubsetdecl :: XParser ExtSubsetDecl extsubsetdecl = ( markupdecl >>= return . ExtMarkupDecl) `onFail` ( conditionalsect >>= return . ExtConditionalSect) sddecl :: XParser SDDecl sddecl = do (word "standalone" `onFail` word "STANDALONE") commit $ do tok TokEqual `onFail` failP "missing = in 'standalone' decl" bracket (tok TokQuote) (commit $ tok TokQuote) ( (word "yes" >> return True) `onFail` (word "no" >> return False) `onFail` failP "'standalone' decl requires 'yes' or 'no' value" ) {- element :: XParser (Element Posn) element = do tok TokAnyOpen (ElemTag n as) <- elemtag oneOf' [ ("self-closing tag <"++n++"/>" , do tok TokEndClose return (Elem n as [])) , ("after open tag <"++n++">" , do tok TokAnyClose cs <- many content p <- posn m <- bracket (tok TokEndOpen) (commit $ tok TokAnyClose) qname checkmatch p n m return (Elem n as cs)) ] `adjustErr` (("in element tag "++n++",\n")++) -} -- | Return a complete element including all its inner content. element :: XParser (Element Posn) element = do tok TokAnyOpen (ElemTag n as) <- elemtag return (Elem n as) `apply` ( do tok TokEndClose return [] `onFail` do tok TokAnyClose commit $ manyFinally content (do p <- posn m <- bracket (tok TokEndOpen) (commit $ tok TokAnyClose) qname checkmatch p n m) ) `adjustErrBad` (("in element tag "++printableName n++",\n")++) checkmatch :: Posn -> QName -> QName -> XParser () checkmatch p n m = if n == m then return () else failBad ("tag <"++printableName n++"> terminated by </"++printableName m ++">\n at "++show p) -- | Parse only the parts between angle brackets in an element tag. elemtag :: XParser ElemTag elemtag = do n <- qname `adjustErrBad` ("malformed element tag\n"++) as <- many attribute return (ElemTag n as) -- | For use with stream parsers - returns the complete opening element tag. elemOpenTag :: XParser ElemTag elemOpenTag = do tok TokAnyOpen e <- elemtag tok TokAnyClose return e -- | For use with stream parsers - accepts a closing tag, provided it -- matches the given element name. elemCloseTag :: QName -> XParser () elemCloseTag n = do tok TokEndOpen p <- posn m <- qname tok TokAnyClose checkmatch p n m attribute :: XParser Attribute attribute = do n <- qname `adjustErr` ("malformed attribute name\n"++) tok TokEqual `onFail` failBadP "missing = in attribute" v <- attvalue `onFail` failBadP "missing attvalue" return (n,v) -- | Return a content particle, e.g. text, element, reference, etc content :: XParser (Content Posn) content = do { p <- posn ; c' <- content' ; return (c' p) } where content' = oneOf' [ ("element", element >>= return . CElem) , ("chardata", chardata >>= return . CString False) , ("reference", reference >>= return . CRef) , ("CDATA", cdsect >>= return . CString True) , ("misc", misc >>= return . CMisc) ] `adjustErrP` ("when looking for a content item,\n"++) -- (\ (element, text, reference, CDATA section, <!--comment-->, or <?PI?>") elementdecl :: XParser ElementDecl elementdecl = do tok TokSpecialOpen tok (TokSpecial ELEMENTx) n <- peRef qname `adjustErrBad` ("expecting identifier in ELEMENT decl\n"++) c <- peRef contentspec `adjustErrBad` (("in content spec of ELEMENT decl: " ++printableName n++"\n")++) blank (tok TokAnyClose) `onFail` failBadP ("expected > terminating ELEMENT decl" ++"\n element name was "++show (printableName n) ++"\n contentspec was "++(\ (ContentSpec p)-> debugShowCP p) c) return (ElementDecl n c) contentspec :: XParser ContentSpec contentspec = oneOf' [ ("EMPTY", peRef (word "EMPTY") >> return EMPTY) , ("ANY", peRef (word "ANY") >> return ANY) , ("mixed", peRef mixed >>= return . Mixed) , ("simple", peRef cp >>= return . ContentSpec) ] -- `adjustErr` ("when looking for content spec,\n"++) -- `adjustErr` (++"\nLooking for content spec (EMPTY, ANY, mixed, etc)") choice :: XParser [CP] choice = do bracket (tok TokBraOpen `debug` "Trying choice") (blank (tok TokBraClose `debug` "Succeeded with choice")) (peRef cp `sepBy1` blank (tok TokPipe)) sequence :: XParser [CP] sequence = do bracket (tok TokBraOpen `debug` "Trying sequence") (blank (tok TokBraClose `debug` "Succeeded with sequence")) (peRef cp `sepBy1` blank (tok TokComma)) cp :: XParser CP cp = oneOf [ ( do n <- qname m <- modifier let c = TagName n m return c `debug` ("ContentSpec: name "++debugShowCP c)) , ( do ss <- sequence m <- modifier let c = Seq ss m return c `debug` ("ContentSpec: sequence "++debugShowCP c)) , ( do cs <- choice m <- modifier let c = Choice cs m return c `debug` ("ContentSpec: choice "++debugShowCP c)) ] `adjustErr` (++"\nwhen looking for a content particle") modifier :: XParser Modifier modifier = oneOf [ ( tok TokStar >> return Star ) , ( tok TokQuery >> return Query ) , ( tok TokPlus >> return Plus ) , ( return None ) ] -- just for debugging debugShowCP :: CP -> String debugShowCP cp = case cp of TagName n m -> printableName n++debugShowModifier m Choice cps m -> '(': concat (intersperse "|" (map debugShowCP cps))++")"++debugShowModifier m Seq cps m -> '(': concat (intersperse "," (map debugShowCP cps))++")"++debugShowModifier m debugShowModifier :: Modifier -> String debugShowModifier modifier = case modifier of None -> "" Query -> "?" Star -> "*" Plus -> "+" ---- mixed :: XParser Mixed mixed = do tok TokBraOpen peRef (do tok TokHash word "PCDATA") commit $ oneOf [ ( do cs <- many (peRef (do tok TokPipe peRef qname)) blank (tok TokBraClose >> tok TokStar) return (PCDATAplus cs)) , ( blank (tok TokBraClose >> tok TokStar) >> return PCDATA) , ( blank (tok TokBraClose) >> return PCDATA) ] `adjustErrP` (++"\nLooking for mixed content spec (#PCDATA | ...)*\n") attlistdecl :: XParser AttListDecl attlistdecl = do tok TokSpecialOpen tok (TokSpecial ATTLISTx) n <- peRef qname `adjustErrBad` ("expecting identifier in ATTLIST\n"++) ds <- peRef (many1 (peRef attdef)) blank (tok TokAnyClose) `onFail` failBadP "missing > terminating ATTLIST" return (AttListDecl n ds) attdef :: XParser AttDef attdef = do n <- peRef qname `adjustErr` ("expecting attribute name\n"++) t <- peRef atttype `adjustErr` (("within attlist defn: " ++printableName n++",\n")++) d <- peRef defaultdecl `adjustErr` (("in attlist defn: " ++printableName n++",\n")++) return (AttDef n t d) atttype :: XParser AttType atttype = oneOf' [ ("CDATA", word "CDATA" >> return StringType) , ("tokenized", tokenizedtype >>= return . TokenizedType) , ("enumerated", enumeratedtype >>= return . EnumeratedType) ] `adjustErr` ("looking for ATTTYPE,\n"++) -- `adjustErr` (++"\nLooking for ATTTYPE (CDATA, tokenized, or enumerated") tokenizedtype :: XParser TokenizedType tokenizedtype = oneOf [ ( word "ID" >> return ID) , ( word "IDREF" >> return IDREF) , ( word "IDREFS" >> return IDREFS) , ( word "ENTITY" >> return ENTITY) , ( word "ENTITIES" >> return ENTITIES) , ( word "NMTOKEN" >> return NMTOKEN) , ( word "NMTOKENS" >> return NMTOKENS) ] `onFail` do { t <- next ; failP ("Expected one of" ++" (ID, IDREF, IDREFS, ENTITY, ENTITIES, NMTOKEN, NMTOKENS)" ++"\nbut got "++show t) } enumeratedtype :: XParser EnumeratedType enumeratedtype = oneOf' [ ("NOTATION", notationtype >>= return . NotationType) , ("enumerated", enumeration >>= return . Enumeration) ] `adjustErr` ("looking for an enumerated or NOTATION type,\n"++) notationtype :: XParser NotationType notationtype = do word "NOTATION" bracket (tok TokBraOpen) (commit $ blank $ tok TokBraClose) (peRef name `sepBy1` peRef (tok TokPipe)) enumeration :: XParser Enumeration enumeration = bracket (tok TokBraOpen) (commit $ blank $ tok TokBraClose) (peRef nmtoken `sepBy1` blank (peRef (tok TokPipe))) defaultdecl :: XParser DefaultDecl defaultdecl = oneOf' [ ("REQUIRED", tok TokHash >> word "REQUIRED" >> return REQUIRED) , ("IMPLIED", tok TokHash >> word "IMPLIED" >> return IMPLIED) , ("FIXED", do f <- maybe (tok TokHash >> word "FIXED" >> return FIXED) a <- peRef attvalue return (DefaultTo a f) ) ] `adjustErr` ("looking for an attribute default decl,\n"++) conditionalsect :: XParser ConditionalSect conditionalsect = oneOf' [ ( "INCLUDE" , do tok TokSectionOpen peRef (tok (TokSection INCLUDEx)) p <- posn tok TokSqOpen `onFail` failBadP "missing [ after INCLUDE" i <- many (peRef extsubsetdecl) tok TokSectionClose `onFail` failBadP ("missing ]]> for INCLUDE section" ++"\n begun at "++show p) return (IncludeSect i)) , ( "IGNORE" , do tok TokSectionOpen peRef (tok (TokSection IGNOREx)) p <- posn tok TokSqOpen `onFail` failBadP "missing [ after IGNORE" i <- many newIgnore -- many ignoresectcontents tok TokSectionClose `onFail` failBadP ("missing ]]> for IGNORE section" ++"\n begun at "++show p) return (IgnoreSect [])) ] `adjustErr` ("in a conditional section,\n"++) newIgnore :: XParser Ignore newIgnore = ( do tok TokSectionOpen many newIgnore `debug` "IGNORING conditional section" tok TokSectionClose return Ignore `debug` "end of IGNORED conditional section") `onFail` ( do t <- nottok [TokSectionOpen,TokSectionClose] return Ignore `debug` ("ignoring: "++show t)) --- obsolete? --ignoresectcontents :: XParser IgnoreSectContents --ignoresectcontents = do -- i <- ignore -- is <- many (do tok TokSectionOpen -- ic <- ignoresectcontents -- tok TokSectionClose -- ig <- ignore -- return (ic,ig)) -- return (IgnoreSectContents i is) -- --ignore :: XParser Ignore --ignore = do -- is <- many1 (nottok [TokSectionOpen,TokSectionClose]) -- return Ignore `debug` ("ignored all of: "++show is) ---- -- | Return either a general entity reference, or a character reference. reference :: XParser Reference reference = do bracket (tok TokAmp) (commit $ tok TokSemi) (freetext >>= val) where val ('#':'x':i) | all isHexDigit i = return . RefChar . fst . head . readHex $ i val ('#':i) | all isDigit i = return . RefChar . fst . head . readDec $ i val name = return . RefEntity $ name {- -- following is incorrect reference = ( charref >>= return . RefChar) `onFail` ( entityref >>= return . RefEntity) entityref :: XParser EntityRef entityref = do bracket (tok TokAmp) (commit $ tok TokSemi) name charref :: XParser CharRef charref = do bracket (tok TokAmp) (commit $ tok TokSemi) (freetext >>= readCharVal) where readCharVal ('#':'x':i) = return . fst . head . readHex $ i readCharVal ('#':i) = return . fst . head . readDec $ i readCharVal _ = mzero -} pereference :: XParser PEReference pereference = do bracket (tok TokPercent) (tok TokSemi) nmtoken entitydecl :: XParser EntityDecl entitydecl = ( gedecl >>= return . EntityGEDecl) `onFail` ( pedecl >>= return . EntityPEDecl) gedecl :: XParser GEDecl gedecl = do tok TokSpecialOpen tok (TokSpecial ENTITYx) n <- name e <- entitydef `adjustErrBad` (("in general entity defn "++n++",\n")++) tok TokAnyClose `onFail` failBadP ("expected > terminating G ENTITY decl "++n) stUpdate (addGE n e) `debug` ("added GE defn &"++n++";") return (GEDecl n e) pedecl :: XParser PEDecl pedecl = do tok TokSpecialOpen tok (TokSpecial ENTITYx) tok TokPercent n <- name e <- pedef `adjustErrBad` (("in parameter entity defn "++n++",\n")++) tok TokAnyClose `onFail` failBadP ("expected > terminating P ENTITY decl "++n) stUpdate (addPE n e) `debug` ("added PE defn %"++n++";\n"++show e) return (PEDecl n e) entitydef :: XParser EntityDef entitydef = oneOf' [ ("entityvalue", entityvalue >>= return . DefEntityValue) , ("external", do eid <- externalid ndd <- maybe ndatadecl return (DefExternalID eid ndd)) ] pedef :: XParser PEDef pedef = oneOf' [ ("entityvalue", entityvalue >>= return . PEDefEntityValue) , ("externalid", externalid >>= return . PEDefExternalID) ] externalid :: XParser ExternalID externalid = oneOf' [ ("SYSTEM", do word "SYSTEM" s <- systemliteral return (SYSTEM s) ) , ("PUBLIC", do word "PUBLIC" p <- pubidliteral s <- systemliteral return (PUBLIC p s) ) ] `adjustErr` ("looking for an external id,\n"++) ndatadecl :: XParser NDataDecl ndatadecl = do word "NDATA" n <- name return (NDATA n) textdecl :: XParser TextDecl textdecl = do tok TokPIOpen (word "xml" `onFail` word "XML") v <- maybe versioninfo e <- encodingdecl tok TokPIClose `onFail` failP "expected ?> terminating text decl" return (TextDecl v e) --extparsedent :: XParser (ExtParsedEnt Posn) --extparsedent = do -- t <- maybe textdecl -- c <- content -- return (ExtParsedEnt t c) -- --extpe :: XParser ExtPE --extpe = do -- t <- maybe textdecl -- e <- many (peRef extsubsetdecl) -- return (ExtPE t e) encodingdecl :: XParser EncodingDecl encodingdecl = do (word "encoding" `onFail` word "ENCODING") tok TokEqual `onFail` failBadP "expected = in 'encoding' decl" f <- bracket (tok TokQuote) (commit $ tok TokQuote) freetext return (EncodingDecl f) notationdecl :: XParser NotationDecl notationdecl = do tok TokSpecialOpen tok (TokSpecial NOTATIONx) n <- name e <- either externalid publicid tok TokAnyClose `onFail` failBadP ("expected > terminating NOTATION decl "++n) return (NOTATION n e) publicid :: XParser PublicID publicid = do word "PUBLIC" p <- pubidliteral return (PUBLICID p) entityvalue :: XParser EntityValue entityvalue = do -- evs <- bracket (tok TokQuote) (commit $ tok TokQuote) (many (peRef ev)) tok TokQuote pn <- posn evs <- many ev tok TokQuote `onFail` failBadP "expected quote to terminate entityvalue" -- quoted text must be rescanned for possible PERefs st <- stGet -- Prelude.either failBad (return . EntityValue) . fst3 $ return . EntityValue . fst3 $ (runParser (many ev) st (reLexEntityValue (\s-> stringify (lookupPE s st)) pn (flattenEV (EntityValue evs)))) where stringify (Just (PEDefEntityValue ev)) = Just (flattenEV ev) stringify _ = Nothing ev :: XParser EV ev = oneOf' [ ("string", (string`onFail`freetext) >>= return . EVString) , ("reference", reference >>= return . EVRef) ] `adjustErr` ("looking for entity value,\n"++) attvalue :: XParser AttValue attvalue = do avs <- bracket (tok TokQuote) (commit $ tok TokQuote) (many (either freetext reference)) return (AttValue avs) systemliteral :: XParser SystemLiteral systemliteral = do s <- bracket (tok TokQuote) (commit $ tok TokQuote) freetext return (SystemLiteral s) -- note: refs &...; not permitted pubidliteral :: XParser PubidLiteral pubidliteral = do s <- bracket (tok TokQuote) (commit $ tok TokQuote) freetext return (PubidLiteral s) -- note: freetext is too liberal here -- | Return parsed freetext (i.e. until the next markup) chardata :: XParser CharData chardata = freetext
alexbaluta/courseography
dependencies/HaXml-1.25.3/src/Text/XML/HaXml/ParseLazy.hs
gpl-3.0
31,573
0
22
9,488
8,206
4,206
4,000
589
4
module Foo where -- | -- -- >>> import Acme.Dont -- >>> don't foo foo :: IO () foo = error "foo"
juhp/stack
test/integration/tests/4783-doctest-deps/files/src/Foo.hs
bsd-3-clause
98
0
6
23
26
16
10
3
1
{- ToDo [Oct 2013] ~~~~~~~~~~~~~~~ 1. Nuke ForceSpecConstr for good (it is subsumed by GHC.Types.SPEC in ghc-prim) 2. Nuke NoSpecConstr (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[SpecConstr]{Specialise over constructors} -} {-# LANGUAGE CPP #-} module SpecConstr( specConstrProgram #ifdef GHCI , SpecConstrAnnotation(..) #endif ) where #include "HsVersions.h" import CoreSyn import CoreSubst import CoreUtils import CoreUnfold ( couldBeSmallEnoughToInline ) import CoreFVs ( exprsFreeVars ) import CoreMonad import Literal ( litIsLifted ) import HscTypes ( ModGuts(..) ) import WwLib ( mkWorkerArgs ) import DataCon import Coercion hiding( substTy, substCo ) import Rules import Type hiding ( substTy ) import TyCon ( isRecursiveTyCon, tyConName ) import Id import PprCore ( pprParendExpr ) import MkCore ( mkImpossibleExpr ) import Var import VarEnv import VarSet import Name import BasicTypes import DynFlags ( DynFlags(..) ) import StaticFlags ( opt_PprStyle_Debug ) import Maybes ( orElse, catMaybes, isJust, isNothing ) import Demand import Serialized ( deserializeWithData ) import Util import Pair import UniqSupply import Outputable import FastString import UniqFM import MonadUtils import Control.Monad ( zipWithM ) import Data.List import PrelNames ( specTyConName ) -- See Note [Forcing specialisation] #ifndef GHCI type SpecConstrAnnotation = () #else import TyCon ( TyCon ) import GHC.Exts( SpecConstrAnnotation(..) ) #endif {- ----------------------------------------------------- Game plan ----------------------------------------------------- Consider drop n [] = [] drop 0 xs = [] drop n (x:xs) = drop (n-1) xs After the first time round, we could pass n unboxed. This happens in numerical code too. Here's what it looks like in Core: drop n xs = case xs of [] -> [] (y:ys) -> case n of I# n# -> case n# of 0 -> [] _ -> drop (I# (n# -# 1#)) xs Notice that the recursive call has an explicit constructor as argument. Noticing this, we can make a specialised version of drop RULE: drop (I# n#) xs ==> drop' n# xs drop' n# xs = let n = I# n# in ...orig RHS... Now the simplifier will apply the specialisation in the rhs of drop', giving drop' n# xs = case xs of [] -> [] (y:ys) -> case n# of 0 -> [] _ -> drop' (n# -# 1#) xs Much better! We'd also like to catch cases where a parameter is carried along unchanged, but evaluated each time round the loop: f i n = if i>0 || i>n then i else f (i*2) n Here f isn't strict in n, but we'd like to avoid evaluating it each iteration. In Core, by the time we've w/wd (f is strict in i) we get f i# n = case i# ># 0 of False -> I# i# True -> case n of { I# n# -> case i# ># n# of False -> I# i# True -> f (i# *# 2#) n At the call to f, we see that the argument, n is known to be (I# n#), and n is evaluated elsewhere in the body of f, so we can play the same trick as above. Note [Reboxing] ~~~~~~~~~~~~~~~ We must be careful not to allocate the same constructor twice. Consider f p = (...(case p of (a,b) -> e)...p..., ...let t = (r,s) in ...t...(f t)...) At the recursive call to f, we can see that t is a pair. But we do NOT want to make a specialised copy: f' a b = let p = (a,b) in (..., ...) because now t is allocated by the caller, then r and s are passed to the recursive call, which allocates the (r,s) pair again. This happens if (a) the argument p is used in other than a case-scrutinisation way. (b) the argument to the call is not a 'fresh' tuple; you have to look into its unfolding to see that it's a tuple Hence the "OR" part of Note [Good arguments] below. ALTERNATIVE 2: pass both boxed and unboxed versions. This no longer saves allocation, but does perhaps save evals. In the RULE we'd have something like f (I# x#) = f' (I# x#) x# If at the call site the (I# x) was an unfolding, then we'd have to rely on CSE to eliminate the duplicate allocation.... This alternative doesn't look attractive enough to pursue. ALTERNATIVE 3: ignore the reboxing problem. The trouble is that the conservative reboxing story prevents many useful functions from being specialised. Example: foo :: Maybe Int -> Int -> Int foo (Just m) 0 = 0 foo x@(Just m) n = foo x (n-m) Here the use of 'x' will clearly not require boxing in the specialised function. The strictness analyser has the same problem, in fact. Example: f p@(a,b) = ... If we pass just 'a' and 'b' to the worker, it might need to rebox the pair to create (a,b). A more sophisticated analysis might figure out precisely the cases in which this could happen, but the strictness analyser does no such analysis; it just passes 'a' and 'b', and hopes for the best. So my current choice is to make SpecConstr similarly aggressive, and ignore the bad potential of reboxing. Note [Good arguments] ~~~~~~~~~~~~~~~~~~~~~ So we look for * A self-recursive function. Ignore mutual recursion for now, because it's less common, and the code is simpler for self-recursion. * EITHER a) At a recursive call, one or more parameters is an explicit constructor application AND That same parameter is scrutinised by a case somewhere in the RHS of the function OR b) At a recursive call, one or more parameters has an unfolding that is an explicit constructor application AND That same parameter is scrutinised by a case somewhere in the RHS of the function AND Those are the only uses of the parameter (see Note [Reboxing]) What to abstract over ~~~~~~~~~~~~~~~~~~~~~ There's a bit of a complication with type arguments. If the call site looks like f p = ...f ((:) [a] x xs)... then our specialised function look like f_spec x xs = let p = (:) [a] x xs in ....as before.... This only makes sense if either a) the type variable 'a' is in scope at the top of f, or b) the type variable 'a' is an argument to f (and hence fs) Actually, (a) may hold for value arguments too, in which case we may not want to pass them. Supose 'x' is in scope at f's defn, but xs is not. Then we'd like f_spec xs = let p = (:) [a] x xs in ....as before.... Similarly (b) may hold too. If x is already an argument at the call, no need to pass it again. Finally, if 'a' is not in scope at the call site, we could abstract it as we do the term variables: f_spec a x xs = let p = (:) [a] x xs in ...as before... So the grand plan is: * abstract the call site to a constructor-only pattern e.g. C x (D (f p) (g q)) ==> C s1 (D s2 s3) * Find the free variables of the abstracted pattern * Pass these variables, less any that are in scope at the fn defn. But see Note [Shadowing] below. NOTICE that we only abstract over variables that are not in scope, so we're in no danger of shadowing variables used in "higher up" in f_spec's RHS. Note [Shadowing] ~~~~~~~~~~~~~~~~ In this pass we gather up usage information that may mention variables that are bound between the usage site and the definition site; or (more seriously) may be bound to something different at the definition site. For example: f x = letrec g y v = let x = ... in ...(g (a,b) x)... Since 'x' is in scope at the call site, we may make a rewrite rule that looks like RULE forall a,b. g (a,b) x = ... But this rule will never match, because it's really a different 'x' at the call site -- and that difference will be manifest by the time the simplifier gets to it. [A worry: the simplifier doesn't *guarantee* no-shadowing, so perhaps it may not be distinct?] Anyway, the rule isn't actually wrong, it's just not useful. One possibility is to run deShadowBinds before running SpecConstr, but instead we run the simplifier. That gives the simplest possible program for SpecConstr to chew on; and it virtually guarantees no shadowing. Note [Specialising for constant parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This one is about specialising on a *constant* (but not necessarily constructor) argument foo :: Int -> (Int -> Int) -> Int foo 0 f = 0 foo m f = foo (f m) (+1) It produces lvl_rmV :: GHC.Base.Int -> GHC.Base.Int lvl_rmV = \ (ds_dlk :: GHC.Base.Int) -> case ds_dlk of wild_alH { GHC.Base.I# x_alG -> GHC.Base.I# (GHC.Prim.+# x_alG 1) T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) -> GHC.Prim.Int# T.$wfoo = \ (ww_sme :: GHC.Prim.Int#) (w_smg :: GHC.Base.Int -> GHC.Base.Int) -> case ww_sme of ds_Xlw { __DEFAULT -> case w_smg (GHC.Base.I# ds_Xlw) of w1_Xmo { GHC.Base.I# ww1_Xmz -> T.$wfoo ww1_Xmz lvl_rmV }; 0 -> 0 } The recursive call has lvl_rmV as its argument, so we could create a specialised copy with that argument baked in; that is, not passed at all. Now it can perhaps be inlined. When is this worth it? Call the constant 'lvl' - If 'lvl' has an unfolding that is a constructor, see if the corresponding parameter is scrutinised anywhere in the body. - If 'lvl' has an unfolding that is a inlinable function, see if the corresponding parameter is applied (...to enough arguments...?) Also do this is if the function has RULES? Also Note [Specialising for lambda parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ foo :: Int -> (Int -> Int) -> Int foo 0 f = 0 foo m f = foo (f m) (\n -> n-m) This is subtly different from the previous one in that we get an explicit lambda as the argument: T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) -> GHC.Prim.Int# T.$wfoo = \ (ww_sm8 :: GHC.Prim.Int#) (w_sma :: GHC.Base.Int -> GHC.Base.Int) -> case ww_sm8 of ds_Xlr { __DEFAULT -> case w_sma (GHC.Base.I# ds_Xlr) of w1_Xmf { GHC.Base.I# ww1_Xmq -> T.$wfoo ww1_Xmq (\ (n_ad3 :: GHC.Base.Int) -> case n_ad3 of wild_alB { GHC.Base.I# x_alA -> GHC.Base.I# (GHC.Prim.-# x_alA ds_Xlr) }) }; 0 -> 0 } I wonder if SpecConstr couldn't be extended to handle this? After all, lambda is a sort of constructor for functions and perhaps it already has most of the necessary machinery? Furthermore, there's an immediate win, because you don't need to allocate the lambda at the call site; and if perchance it's called in the recursive call, then you may avoid allocating it altogether. Just like for constructors. Looks cool, but probably rare...but it might be easy to implement. Note [SpecConstr for casts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data family T a :: * data instance T Int = T Int foo n = ... where go (T 0) = 0 go (T n) = go (T (n-1)) The recursive call ends up looking like go (T (I# ...) `cast` g) So we want to spot the constructor application inside the cast. That's why we have the Cast case in argToPat Note [Local recursive groups] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For a *local* recursive group, we can see all the calls to the function, so we seed the specialisation loop from the calls in the body, not from the calls in the RHS. Consider: bar m n = foo n (n,n) (n,n) (n,n) (n,n) where foo n p q r s | n == 0 = m | n > 3000 = case p of { (p1,p2) -> foo (n-1) (p2,p1) q r s } | n > 2000 = case q of { (q1,q2) -> foo (n-1) p (q2,q1) r s } | n > 1000 = case r of { (r1,r2) -> foo (n-1) p q (r2,r1) s } | otherwise = case s of { (s1,s2) -> foo (n-1) p q r (s2,s1) } If we start with the RHSs of 'foo', we get lots and lots of specialisations, most of which are not needed. But if we start with the (single) call in the rhs of 'bar' we get exactly one fully-specialised copy, and all the recursive calls go to this fully-specialised copy. Indeed, the original function is later collected as dead code. This is very important in specialising the loops arising from stream fusion, for example in NDP where we were getting literally hundreds of (mostly unused) specialisations of a local function. In a case like the above we end up never calling the original un-specialised function. (Although we still leave its code around just in case.) However, if we find any boring calls in the body, including *unsaturated* ones, such as letrec foo x y = ....foo... in map foo xs then we will end up calling the un-specialised function, so then we *should* use the calls in the un-specialised RHS as seeds. We call these "boring call patterns", and callsToPats reports if it finds any of these. Note [Seeding top-level recursive groups] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This seeding is done in the binding for seed_calls in specRec. 1. If all the bindings in a top-level recursive group are local (not exported), then all the calls are in the rest of the top-level bindings. This means we can specialise with those call patterns ONLY, and NOT with the RHSs of the recursive group (exactly like Note [Local recursive groups]) 2. But if any of the bindings are exported, the function may be called with any old arguments, so (for lack of anything better) we specialise based on (a) the call patterns in the RHS (b) the call patterns in the rest of the top-level bindings NB: before Apr 15 we used (a) only, but Dimitrios had an example where (b) was crucial, so I added that. Adding (b) also improved nofib allocation results: multiplier: 4% better minimax: 2.8% better Actually in case (2), instead of using the calls from the RHS, it would be better to specialise in the importing module. We'd need to add an INLINEABLE pragma to the function, and then it can be specialised in the importing scope, just as is done for type classes in Specialise.specImports. This remains to be done (#10346). Note [Top-level recursive groups] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To get the call usage information from "the rest of the top level bindings" (c.f. Note [Seeding top-level recursive groups]), we work backwards through the top-level bindings so we see the usage before we get to the binding of the function. Before we can collect the usage though, we go through all the bindings and add them to the environment. This is necessary because usage is only tracked for functions in the environment. These two passes are called 'go' and 'goEnv' in specConstrProgram. (Looks a bit revolting to me.) Note [Do not specialise diverging functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Specialising a function that just diverges is a waste of code. Furthermore, it broke GHC (simpl014) thus: {-# STR Sb #-} f = \x. case x of (a,b) -> f x If we specialise f we get f = \x. case x of (a,b) -> fspec a b But fspec doesn't have decent strictness info. As it happened, (f x) :: IO t, so the state hack applied and we eta expanded fspec, and hence f. But now f's strictness is less than its arity, which breaks an invariant. Note [Forcing specialisation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With stream fusion and in other similar cases, we want to fully specialise some (but not necessarily all!) loops regardless of their size and the number of specialisations. We allow a library to do this, in one of two ways (one which is deprecated): 1) Add a parameter of type GHC.Types.SPEC (from ghc-prim) to the loop body. 2) (Deprecated) Annotate a type with ForceSpecConstr from GHC.Exts, and then add *that* type as a parameter to the loop body The reason #2 is deprecated is because it requires GHCi, which isn't available for things like a cross compiler using stage1. Here's a (simplified) example from the `vector` package. You may bring the special 'force specialization' type into scope by saying: import GHC.Types (SPEC(..)) or by defining your own type (again, deprecated): data SPEC = SPEC | SPEC2 {-# ANN type SPEC ForceSpecConstr #-} (Note this is the exact same definition of GHC.Types.SPEC, just without the annotation.) After that, you say: foldl :: (a -> b -> a) -> a -> Stream b -> a {-# INLINE foldl #-} foldl f z (Stream step s _) = foldl_loop SPEC z s where foldl_loop !sPEC z s = case step s of Yield x s' -> foldl_loop sPEC (f z x) s' Skip -> foldl_loop sPEC z s' Done -> z SpecConstr will spot the SPEC parameter and always fully specialise foldl_loop. Note that * We have to prevent the SPEC argument from being removed by w/w which is why (a) SPEC is a sum type, and (b) we have to seq on the SPEC argument. * And lastly, the SPEC argument is ultimately eliminated by SpecConstr itself so there is no runtime overhead. This is all quite ugly; we ought to come up with a better design. ForceSpecConstr arguments are spotted in scExpr' and scTopBinds which then set sc_force to True when calling specLoop. This flag does four things: * Ignore specConstrThreshold, to specialise functions of arbitrary size (see scTopBind) * Ignore specConstrCount, to make arbitrary numbers of specialisations (see specialise) * Specialise even for arguments that are not scrutinised in the loop (see argToPat; Trac #4488) * Only specialise on recursive types a finite number of times (see is_too_recursive; Trac #5550; Note [Limit recursive specialisation]) This flag is inherited for nested non-recursive bindings (which are likely to be join points and hence should be fully specialised) but reset for nested recursive bindings. What alternatives did I consider? Annotating the loop itself doesn't work because (a) it is local and (b) it will be w/w'ed and having w/w propagating annotations somehow doesn't seem like a good idea. The types of the loop arguments really seem to be the most persistent thing. Annotating the types that make up the loop state doesn't work, either, because (a) it would prevent us from using types like Either or tuples here, (b) we don't want to restrict the set of types that can be used in Stream states and (c) some types are fixed by the user (e.g., the accumulator here) but we still want to specialise as much as possible. Alternatives to ForceSpecConstr ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Instead of giving the loop an extra argument of type SPEC, we also considered *wrapping* arguments in SPEC, thus data SPEC a = SPEC a | SPEC2 loop = \arg -> case arg of SPEC state -> case state of (x,y) -> ... loop (SPEC (x',y')) ... S2 -> error ... The idea is that a SPEC argument says "specialise this argument regardless of whether the function case-analyses it". But this doesn't work well: * SPEC must still be a sum type, else the strictness analyser eliminates it * But that means that 'loop' won't be strict in its real payload This loss of strictness in turn screws up specialisation, because we may end up with calls like loop (SPEC (case z of (p,q) -> (q,p))) Without the SPEC, if 'loop' were strict, the case would move out and we'd see loop applied to a pair. But if 'loop' isn't strict this doesn't look like a specialisable call. Note [Limit recursive specialisation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is possible for ForceSpecConstr to cause an infinite loop of specialisation. Because there is no limit on the number of specialisations, a recursive call with a recursive constructor as an argument (for example, list cons) will generate a specialisation for that constructor. If the resulting specialisation also contains a recursive call with the constructor, this could proceed indefinitely. For example, if ForceSpecConstr is on: loop :: [Int] -> [Int] -> [Int] loop z [] = z loop z (x:xs) = loop (x:z) xs this example will create a specialisation for the pattern loop (a:b) c = loop' a b c loop' a b [] = (a:b) loop' a b (x:xs) = loop (x:(a:b)) xs and a new pattern is found: loop (a:(b:c)) d = loop'' a b c d which can continue indefinitely. Roman's suggestion to fix this was to stop after a couple of times on recursive types, but still specialising on non-recursive types as much as possible. To implement this, we count the number of recursive constructors in each function argument. If the maximum is greater than the specConstrRecursive limit, do not specialise on that pattern. This is only necessary when ForceSpecConstr is on: otherwise the specConstrCount will force termination anyway. See Trac #5550. Note [NoSpecConstr] ~~~~~~~~~~~~~~~~~~~ The ignoreDataCon stuff allows you to say {-# ANN type T NoSpecConstr #-} to mean "don't specialise on arguments of this type". It was added before we had ForceSpecConstr. Lacking ForceSpecConstr we specialised regardless of size; and then we needed a way to turn that *off*. Now that we have ForceSpecConstr, this NoSpecConstr is probably redundant. (Used only for PArray.) ----------------------------------------------------- Stuff not yet handled ----------------------------------------------------- Here are notes arising from Roman's work that I don't want to lose. Example 1 ~~~~~~~~~ data T a = T !a foo :: Int -> T Int -> Int foo 0 t = 0 foo x t | even x = case t of { T n -> foo (x-n) t } | otherwise = foo (x-1) t SpecConstr does no specialisation, because the second recursive call looks like a boxed use of the argument. A pity. $wfoo_sFw :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int# $wfoo_sFw = \ (ww_sFo [Just L] :: GHC.Prim.Int#) (w_sFq [Just L] :: T.T GHC.Base.Int) -> case ww_sFo of ds_Xw6 [Just L] { __DEFAULT -> case GHC.Prim.remInt# ds_Xw6 2 of wild1_aEF [Dead Just A] { __DEFAULT -> $wfoo_sFw (GHC.Prim.-# ds_Xw6 1) w_sFq; 0 -> case w_sFq of wild_Xy [Just L] { T.T n_ad5 [Just U(L)] -> case n_ad5 of wild1_aET [Just A] { GHC.Base.I# y_aES [Just L] -> $wfoo_sFw (GHC.Prim.-# ds_Xw6 y_aES) wild_Xy } } }; 0 -> 0 Example 2 ~~~~~~~~~ data a :*: b = !a :*: !b data T a = T !a foo :: (Int :*: T Int) -> Int foo (0 :*: t) = 0 foo (x :*: t) | even x = case t of { T n -> foo ((x-n) :*: t) } | otherwise = foo ((x-1) :*: t) Very similar to the previous one, except that the parameters are now in a strict tuple. Before SpecConstr, we have $wfoo_sG3 :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int# $wfoo_sG3 = \ (ww_sFU [Just L] :: GHC.Prim.Int#) (ww_sFW [Just L] :: T.T GHC.Base.Int) -> case ww_sFU of ds_Xws [Just L] { __DEFAULT -> case GHC.Prim.remInt# ds_Xws 2 of wild1_aEZ [Dead Just A] { __DEFAULT -> case ww_sFW of tpl_B2 [Just L] { T.T a_sFo [Just A] -> $wfoo_sG3 (GHC.Prim.-# ds_Xws 1) tpl_B2 -- $wfoo1 }; 0 -> case ww_sFW of wild_XB [Just A] { T.T n_ad7 [Just S(L)] -> case n_ad7 of wild1_aFd [Just L] { GHC.Base.I# y_aFc [Just L] -> $wfoo_sG3 (GHC.Prim.-# ds_Xws y_aFc) wild_XB -- $wfoo2 } } }; 0 -> 0 } We get two specialisations: "SC:$wfoo1" [0] __forall {a_sFB :: GHC.Base.Int sc_sGC :: GHC.Prim.Int#} Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int a_sFB) = Foo.$s$wfoo1 a_sFB sc_sGC ; "SC:$wfoo2" [0] __forall {y_aFp :: GHC.Prim.Int# sc_sGC :: GHC.Prim.Int#} Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int (GHC.Base.I# y_aFp)) = Foo.$s$wfoo y_aFp sc_sGC ; But perhaps the first one isn't good. After all, we know that tpl_B2 is a T (I# x) really, because T is strict and Int has one constructor. (We can't unbox the strict fields, because T is polymorphic!) ************************************************************************ * * \subsection{Top level wrapper stuff} * * ************************************************************************ -} specConstrProgram :: ModGuts -> CoreM ModGuts specConstrProgram guts = do dflags <- getDynFlags us <- getUniqueSupplyM annos <- getFirstAnnotations deserializeWithData guts let binds' = reverse $ fst $ initUs us $ do -- Note [Top-level recursive groups] (env, binds) <- goEnv (initScEnv dflags annos) (mg_binds guts) -- binds is identical to (mg_binds guts), except that the -- binders on the LHS have been replaced by extendBndr -- (SPJ this seems like overkill; I don't think the binders -- will change at all; and we don't substitute in the RHSs anyway!!) go env nullUsage (reverse binds) return (guts { mg_binds = binds' }) where -- See Note [Top-level recursive groups] goEnv env [] = return (env, []) goEnv env (bind:binds) = do (env', bind') <- scTopBindEnv env bind (env'', binds') <- goEnv env' binds return (env'', bind' : binds') -- Arg list of bindings is in reverse order go _ _ [] = return [] go env usg (bind:binds) = do (usg', bind') <- scTopBind env usg bind binds' <- go env usg' binds return (bind' : binds') {- ************************************************************************ * * \subsection{Environment: goes downwards} * * ************************************************************************ Note [Work-free values only in environment] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The sc_vals field keeps track of in-scope value bindings, so that if we come across (case x of Just y ->...) we can reduce the case from knowing that x is bound to a pair. But only *work-free* values are ok here. For example if the envt had x -> Just (expensive v) then we do NOT want to expand to let y = expensive v in ... because the x-binding still exists and we've now duplicated (expensive v). This seldom happens because let-bound constructor applications are ANF-ised, but it can happen as a result of on-the-fly transformations in SpecConstr itself. Here is Trac #7865: let { a'_shr = case xs_af8 of _ { [] -> acc_af6; : ds_dgt [Dmd=<L,A>] ds_dgu [Dmd=<L,A>] -> (expensive x_af7, x_af7 } } in let { ds_sht = case a'_shr of _ { (p'_afd, q'_afe) -> TSpecConstr_DoubleInline.recursive (GHC.Types.: @ GHC.Types.Int x_af7 wild_X6) (q'_afe, p'_afd) } } in When processed knowing that xs_af8 was bound to a cons, we simplify to a'_shr = (expensive x_af7, x_af7) and we do NOT want to inline that at the occurrence of a'_shr in ds_sht. (There are other occurrences of a'_shr.) No no no. It would be possible to do some on-the-fly ANF-ising, so that a'_shr turned into a work-free value again, thus a1 = expensive x_af7 a'_shr = (a1, x_af7) but that's more work, so until its shown to be important I'm going to leave it for now. -} data ScEnv = SCE { sc_dflags :: DynFlags, sc_size :: Maybe Int, -- Size threshold sc_count :: Maybe Int, -- Max # of specialisations for any one fn -- See Note [Avoiding exponential blowup] sc_recursive :: Int, -- Max # of specialisations over recursive type. -- Stops ForceSpecConstr from diverging. sc_force :: Bool, -- Force specialisation? -- See Note [Forcing specialisation] sc_subst :: Subst, -- Current substitution -- Maps InIds to OutExprs sc_how_bound :: HowBoundEnv, -- Binds interesting non-top-level variables -- Domain is OutVars (*after* applying the substitution) sc_vals :: ValueEnv, -- Domain is OutIds (*after* applying the substitution) -- Used even for top-level bindings (but not imported ones) -- The range of the ValueEnv is *work-free* values -- such as (\x. blah), or (Just v) -- but NOT (Just (expensive v)) -- See Note [Work-free values only in environment] sc_annotations :: UniqFM SpecConstrAnnotation } --------------------- -- As we go, we apply a substitution (sc_subst) to the current term type InExpr = CoreExpr -- _Before_ applying the subst type InVar = Var type OutExpr = CoreExpr -- _After_ applying the subst type OutId = Id type OutVar = Var --------------------- type HowBoundEnv = VarEnv HowBound -- Domain is OutVars --------------------- type ValueEnv = IdEnv Value -- Domain is OutIds data Value = ConVal AltCon [CoreArg] -- _Saturated_ constructors -- The AltCon is never DEFAULT | LambdaVal -- Inlinable lambdas or PAPs instance Outputable Value where ppr (ConVal con args) = ppr con <+> interpp'SP args ppr LambdaVal = ptext (sLit "<Lambda>") --------------------- initScEnv :: DynFlags -> UniqFM SpecConstrAnnotation -> ScEnv initScEnv dflags anns = SCE { sc_dflags = dflags, sc_size = specConstrThreshold dflags, sc_count = specConstrCount dflags, sc_recursive = specConstrRecursive dflags, sc_force = False, sc_subst = emptySubst, sc_how_bound = emptyVarEnv, sc_vals = emptyVarEnv, sc_annotations = anns } data HowBound = RecFun -- These are the recursive functions for which -- we seek interesting call patterns | RecArg -- These are those functions' arguments, or their sub-components; -- we gather occurrence information for these instance Outputable HowBound where ppr RecFun = text "RecFun" ppr RecArg = text "RecArg" scForce :: ScEnv -> Bool -> ScEnv scForce env b = env { sc_force = b } lookupHowBound :: ScEnv -> Id -> Maybe HowBound lookupHowBound env id = lookupVarEnv (sc_how_bound env) id scSubstId :: ScEnv -> Id -> CoreExpr scSubstId env v = lookupIdSubst (text "scSubstId") (sc_subst env) v scSubstTy :: ScEnv -> Type -> Type scSubstTy env ty = substTy (sc_subst env) ty scSubstCo :: ScEnv -> Coercion -> Coercion scSubstCo env co = substCo (sc_subst env) co zapScSubst :: ScEnv -> ScEnv zapScSubst env = env { sc_subst = zapSubstEnv (sc_subst env) } extendScInScope :: ScEnv -> [Var] -> ScEnv -- Bring the quantified variables into scope extendScInScope env qvars = env { sc_subst = extendInScopeList (sc_subst env) qvars } -- Extend the substitution extendScSubst :: ScEnv -> Var -> OutExpr -> ScEnv extendScSubst env var expr = env { sc_subst = extendSubst (sc_subst env) var expr } extendScSubstList :: ScEnv -> [(Var,OutExpr)] -> ScEnv extendScSubstList env prs = env { sc_subst = extendSubstList (sc_subst env) prs } extendHowBound :: ScEnv -> [Var] -> HowBound -> ScEnv extendHowBound env bndrs how_bound = env { sc_how_bound = extendVarEnvList (sc_how_bound env) [(bndr,how_bound) | bndr <- bndrs] } extendBndrsWith :: HowBound -> ScEnv -> [Var] -> (ScEnv, [Var]) extendBndrsWith how_bound env bndrs = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndrs') where (subst', bndrs') = substBndrs (sc_subst env) bndrs hb_env' = sc_how_bound env `extendVarEnvList` [(bndr,how_bound) | bndr <- bndrs'] extendBndrWith :: HowBound -> ScEnv -> Var -> (ScEnv, Var) extendBndrWith how_bound env bndr = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndr') where (subst', bndr') = substBndr (sc_subst env) bndr hb_env' = extendVarEnv (sc_how_bound env) bndr' how_bound extendRecBndrs :: ScEnv -> [Var] -> (ScEnv, [Var]) extendRecBndrs env bndrs = (env { sc_subst = subst' }, bndrs') where (subst', bndrs') = substRecBndrs (sc_subst env) bndrs extendBndr :: ScEnv -> Var -> (ScEnv, Var) extendBndr env bndr = (env { sc_subst = subst' }, bndr') where (subst', bndr') = substBndr (sc_subst env) bndr extendValEnv :: ScEnv -> Id -> Maybe Value -> ScEnv extendValEnv env _ Nothing = env extendValEnv env id (Just cv) | valueIsWorkFree cv -- Don't duplicate work!! Trac #7865 = env { sc_vals = extendVarEnv (sc_vals env) id cv } extendValEnv env _ _ = env extendCaseBndrs :: ScEnv -> OutExpr -> OutId -> AltCon -> [Var] -> (ScEnv, [Var]) -- When we encounter -- case scrut of b -- C x y -> ... -- we want to bind b, to (C x y) -- NB1: Extends only the sc_vals part of the envt -- NB2: Kill the dead-ness info on the pattern binders x,y, since -- they are potentially made alive by the [b -> C x y] binding extendCaseBndrs env scrut case_bndr con alt_bndrs = (env2, alt_bndrs') where live_case_bndr = not (isDeadBinder case_bndr) env1 | Var v <- stripTicksTopE (const True) scrut = extendValEnv env v cval | otherwise = env -- See Note [Add scrutinee to ValueEnv too] env2 | live_case_bndr = extendValEnv env1 case_bndr cval | otherwise = env1 alt_bndrs' | case scrut of { Var {} -> True; _ -> live_case_bndr } = map zap alt_bndrs | otherwise = alt_bndrs cval = case con of DEFAULT -> Nothing LitAlt {} -> Just (ConVal con []) DataAlt {} -> Just (ConVal con vanilla_args) where vanilla_args = map Type (tyConAppArgs (idType case_bndr)) ++ varsToCoreExprs alt_bndrs zap v | isTyVar v = v -- See NB2 above | otherwise = zapIdOccInfo v decreaseSpecCount :: ScEnv -> Int -> ScEnv -- See Note [Avoiding exponential blowup] decreaseSpecCount env n_specs = env { sc_count = case sc_count env of Nothing -> Nothing Just n -> Just (n `div` (n_specs + 1)) } -- The "+1" takes account of the original function; -- See Note [Avoiding exponential blowup] --------------------------------------------------- -- See Note [Forcing specialisation] ignoreType :: ScEnv -> Type -> Bool ignoreDataCon :: ScEnv -> DataCon -> Bool forceSpecBndr :: ScEnv -> Var -> Bool #ifndef GHCI ignoreType _ _ = False ignoreDataCon _ _ = False #else /* GHCI */ ignoreDataCon env dc = ignoreTyCon env (dataConTyCon dc) ignoreType env ty = case tyConAppTyCon_maybe ty of Just tycon -> ignoreTyCon env tycon _ -> False ignoreTyCon :: ScEnv -> TyCon -> Bool ignoreTyCon env tycon = lookupUFM (sc_annotations env) tycon == Just NoSpecConstr #endif /* GHCI */ forceSpecBndr env var = forceSpecFunTy env . snd . splitForAllTys . varType $ var forceSpecFunTy :: ScEnv -> Type -> Bool forceSpecFunTy env = any (forceSpecArgTy env) . fst . splitFunTys forceSpecArgTy :: ScEnv -> Type -> Bool forceSpecArgTy env ty | Just ty' <- coreView ty = forceSpecArgTy env ty' forceSpecArgTy env ty | Just (tycon, tys) <- splitTyConApp_maybe ty , tycon /= funTyCon = tyConName tycon == specTyConName #ifdef GHCI || lookupUFM (sc_annotations env) tycon == Just ForceSpecConstr #endif || any (forceSpecArgTy env) tys forceSpecArgTy _ _ = False {- Note [Add scrutinee to ValueEnv too] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: case x of y (a,b) -> case b of c I# v -> ...(f y)... By the time we get to the call (f y), the ValueEnv will have a binding for y, and for c y -> (a,b) c -> I# v BUT that's not enough! Looking at the call (f y) we see that y is pair (a,b), but we also need to know what 'b' is. So in extendCaseBndrs we must *also* add the binding b -> I# v else we lose a useful specialisation for f. This is necessary even though the simplifier has systematically replaced uses of 'x' with 'y' and 'b' with 'c' in the code. The use of 'b' in the ValueEnv came from outside the case. See Trac #4908 for the live example. Note [Avoiding exponential blowup] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The sc_count field of the ScEnv says how many times we are prepared to duplicate a single function. But we must take care with recursive specialisations. Consider let $j1 = let $j2 = let $j3 = ... in ...$j3... in ...$j2... in ...$j1... If we specialise $j1 then in each specialisation (as well as the original) we can specialise $j2, and similarly $j3. Even if we make just *one* specialisation of each, because we also have the original we'll get 2^n copies of $j3, which is not good. So when recursively specialising we divide the sc_count by the number of copies we are making at this level, including the original. ************************************************************************ * * \subsection{Usage information: flows upwards} * * ************************************************************************ -} data ScUsage = SCU { scu_calls :: CallEnv, -- Calls -- The functions are a subset of the -- RecFuns in the ScEnv scu_occs :: !(IdEnv ArgOcc) -- Information on argument occurrences } -- The domain is OutIds type CallEnv = IdEnv [Call] data Call = Call Id [CoreArg] ValueEnv -- The arguments of the call, together with the -- env giving the constructor bindings at the call site -- We keep the function mainly for debug output instance Outputable ScUsage where ppr (SCU { scu_calls = calls, scu_occs = occs }) = ptext (sLit "SCU") <+> braces (sep [ ptext (sLit "calls =") <+> ppr calls , ptext (sLit "occs =") <+> ppr occs ]) instance Outputable Call where ppr (Call fn args _) = ppr fn <+> fsep (map pprParendExpr args) nullUsage :: ScUsage nullUsage = SCU { scu_calls = emptyVarEnv, scu_occs = emptyVarEnv } combineCalls :: CallEnv -> CallEnv -> CallEnv combineCalls = plusVarEnv_C (++) where -- plus cs ds | length res > 1 -- = pprTrace "combineCalls" (vcat [ ptext (sLit "cs:") <+> ppr cs -- , ptext (sLit "ds:") <+> ppr ds]) -- res -- | otherwise = res -- where -- res = cs ++ ds combineUsage :: ScUsage -> ScUsage -> ScUsage combineUsage u1 u2 = SCU { scu_calls = combineCalls (scu_calls u1) (scu_calls u2), scu_occs = plusVarEnv_C combineOcc (scu_occs u1) (scu_occs u2) } combineUsages :: [ScUsage] -> ScUsage combineUsages [] = nullUsage combineUsages us = foldr1 combineUsage us lookupOccs :: ScUsage -> [OutVar] -> (ScUsage, [ArgOcc]) lookupOccs (SCU { scu_calls = sc_calls, scu_occs = sc_occs }) bndrs = (SCU {scu_calls = sc_calls, scu_occs = delVarEnvList sc_occs bndrs}, [lookupVarEnv sc_occs b `orElse` NoOcc | b <- bndrs]) data ArgOcc = NoOcc -- Doesn't occur at all; or a type argument | UnkOcc -- Used in some unknown way | ScrutOcc -- See Note [ScrutOcc] (DataConEnv [ArgOcc]) -- How the sub-components are used type DataConEnv a = UniqFM a -- Keyed by DataCon {- Note [ScrutOcc] ~~~~~~~~~~~~~~~~~~~ An occurrence of ScrutOcc indicates that the thing, or a `cast` version of the thing, is *only* taken apart or applied. Functions, literal: ScrutOcc emptyUFM Data constructors: ScrutOcc subs, where (subs :: UniqFM [ArgOcc]) gives usage of the *pattern-bound* components, The domain of the UniqFM is the Unique of the data constructor The [ArgOcc] is the occurrences of the *pattern-bound* components of the data structure. E.g. data T a = forall b. MkT a b (b->a) A pattern binds b, x::a, y::b, z::b->a, but not 'a'! -} instance Outputable ArgOcc where ppr (ScrutOcc xs) = ptext (sLit "scrut-occ") <> ppr xs ppr UnkOcc = ptext (sLit "unk-occ") ppr NoOcc = ptext (sLit "no-occ") evalScrutOcc :: ArgOcc evalScrutOcc = ScrutOcc emptyUFM -- Experimentally, this vesion of combineOcc makes ScrutOcc "win", so -- that if the thing is scrutinised anywhere then we get to see that -- in the overall result, even if it's also used in a boxed way -- This might be too aggressive; see Note [Reboxing] Alternative 3 combineOcc :: ArgOcc -> ArgOcc -> ArgOcc combineOcc NoOcc occ = occ combineOcc occ NoOcc = occ combineOcc (ScrutOcc xs) (ScrutOcc ys) = ScrutOcc (plusUFM_C combineOccs xs ys) combineOcc UnkOcc (ScrutOcc ys) = ScrutOcc ys combineOcc (ScrutOcc xs) UnkOcc = ScrutOcc xs combineOcc UnkOcc UnkOcc = UnkOcc combineOccs :: [ArgOcc] -> [ArgOcc] -> [ArgOcc] combineOccs xs ys = zipWithEqual "combineOccs" combineOcc xs ys setScrutOcc :: ScEnv -> ScUsage -> OutExpr -> ArgOcc -> ScUsage -- _Overwrite_ the occurrence info for the scrutinee, if the scrutinee -- is a variable, and an interesting variable setScrutOcc env usg (Cast e _) occ = setScrutOcc env usg e occ setScrutOcc env usg (Tick _ e) occ = setScrutOcc env usg e occ setScrutOcc env usg (Var v) occ | Just RecArg <- lookupHowBound env v = usg { scu_occs = extendVarEnv (scu_occs usg) v occ } | otherwise = usg setScrutOcc _env usg _other _occ -- Catch-all = usg {- ************************************************************************ * * \subsection{The main recursive function} * * ************************************************************************ The main recursive function gathers up usage information, and creates specialised versions of functions. -} scExpr, scExpr' :: ScEnv -> CoreExpr -> UniqSM (ScUsage, CoreExpr) -- The unique supply is needed when we invent -- a new name for the specialised function and its args scExpr env e = scExpr' env e scExpr' env (Var v) = case scSubstId env v of Var v' -> return (mkVarUsage env v' [], Var v') e' -> scExpr (zapScSubst env) e' scExpr' env (Type t) = return (nullUsage, Type (scSubstTy env t)) scExpr' env (Coercion c) = return (nullUsage, Coercion (scSubstCo env c)) scExpr' _ e@(Lit {}) = return (nullUsage, e) scExpr' env (Tick t e) = do (usg, e') <- scExpr env e return (usg, Tick t e') scExpr' env (Cast e co) = do (usg, e') <- scExpr env e return (usg, Cast e' (scSubstCo env co)) scExpr' env e@(App _ _) = scApp env (collectArgs e) scExpr' env (Lam b e) = do let (env', b') = extendBndr env b (usg, e') <- scExpr env' e return (usg, Lam b' e') scExpr' env (Case scrut b ty alts) = do { (scrut_usg, scrut') <- scExpr env scrut ; case isValue (sc_vals env) scrut' of Just (ConVal con args) -> sc_con_app con args scrut' _other -> sc_vanilla scrut_usg scrut' } where sc_con_app con args scrut' -- Known constructor; simplify = do { let (_, bs, rhs) = findAlt con alts `orElse` (DEFAULT, [], mkImpossibleExpr ty) alt_env' = extendScSubstList env ((b,scrut') : bs `zip` trimConArgs con args) ; scExpr alt_env' rhs } sc_vanilla scrut_usg scrut' -- Normal case = do { let (alt_env,b') = extendBndrWith RecArg env b -- Record RecArg for the components ; (alt_usgs, alt_occs, alts') <- mapAndUnzip3M (sc_alt alt_env scrut' b') alts ; let scrut_occ = foldr combineOcc NoOcc alt_occs scrut_usg' = setScrutOcc env scrut_usg scrut' scrut_occ -- The combined usage of the scrutinee is given -- by scrut_occ, which is passed to scScrut, which -- in turn treats a bare-variable scrutinee specially ; return (foldr combineUsage scrut_usg' alt_usgs, Case scrut' b' (scSubstTy env ty) alts') } sc_alt env scrut' b' (con,bs,rhs) = do { let (env1, bs1) = extendBndrsWith RecArg env bs (env2, bs2) = extendCaseBndrs env1 scrut' b' con bs1 ; (usg, rhs') <- scExpr env2 rhs ; let (usg', b_occ:arg_occs) = lookupOccs usg (b':bs2) scrut_occ = case con of DataAlt dc -> ScrutOcc (unitUFM dc arg_occs) _ -> ScrutOcc emptyUFM ; return (usg', b_occ `combineOcc` scrut_occ, (con, bs2, rhs')) } scExpr' env (Let (NonRec bndr rhs) body) | isTyVar bndr -- Type-lets may be created by doBeta = scExpr' (extendScSubst env bndr rhs) body | otherwise = do { let (body_env, bndr') = extendBndr env bndr ; rhs_info <- scRecRhs env (bndr',rhs) ; let body_env2 = extendHowBound body_env [bndr'] RecFun -- Note [Local let bindings] rhs' = ri_new_rhs rhs_info body_env3 = extendValEnv body_env2 bndr' (isValue (sc_vals env) rhs') ; (body_usg, body') <- scExpr body_env3 body -- NB: For non-recursive bindings we inherit sc_force flag from -- the parent function (see Note [Forcing specialisation]) ; (spec_usg, specs) <- specNonRec env body_usg rhs_info ; return (body_usg { scu_calls = scu_calls body_usg `delVarEnv` bndr' } `combineUsage` spec_usg, -- Note [spec_usg includes rhs_usg] mkLets [NonRec b r | (b,r) <- specInfoBinds rhs_info specs] body') } -- A *local* recursive group: see Note [Local recursive groups] scExpr' env (Let (Rec prs) body) = do { let (bndrs,rhss) = unzip prs (rhs_env1,bndrs') = extendRecBndrs env bndrs rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun force_spec = any (forceSpecBndr env) bndrs' -- Note [Forcing specialisation] ; rhs_infos <- mapM (scRecRhs rhs_env2) (bndrs' `zip` rhss) ; (body_usg, body') <- scExpr rhs_env2 body -- NB: start specLoop from body_usg ; (spec_usg, specs) <- specRec NotTopLevel (scForce rhs_env2 force_spec) body_usg rhs_infos -- Do not unconditionally generate specialisations from rhs_usgs -- Instead use them only if we find an unspecialised call -- See Note [Local recursive groups] ; let all_usg = spec_usg `combineUsage` body_usg -- Note [spec_usg includes rhs_usg] bind' = Rec (concat (zipWith specInfoBinds rhs_infos specs)) ; return (all_usg { scu_calls = scu_calls all_usg `delVarEnvList` bndrs' }, Let bind' body') } {- Note [Local let bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~ It is not uncommon to find this let $j = \x. <blah> in ...$j True...$j True... Here $j is an arbitrary let-bound function, but it often comes up for join points. We might like to specialise $j for its call patterns. Notice the difference from a letrec, where we look for call patterns in the *RHS* of the function. Here we look for call patterns in the *body* of the let. At one point I predicated this on the RHS mentioning the outer recursive function, but that's not essential and might even be harmful. I'm not sure. -} scApp :: ScEnv -> (InExpr, [InExpr]) -> UniqSM (ScUsage, CoreExpr) scApp env (Var fn, args) -- Function is a variable = ASSERT( not (null args) ) do { args_w_usgs <- mapM (scExpr env) args ; let (arg_usgs, args') = unzip args_w_usgs arg_usg = combineUsages arg_usgs ; case scSubstId env fn of fn'@(Lam {}) -> scExpr (zapScSubst env) (doBeta fn' args') -- Do beta-reduction and try again Var fn' -> return (arg_usg `combineUsage` mkVarUsage env fn' args', mkApps (Var fn') args') other_fn' -> return (arg_usg, mkApps other_fn' args') } -- NB: doing this ignores any usage info from the substituted -- function, but I don't think that matters. If it does -- we can fix it. where doBeta :: OutExpr -> [OutExpr] -> OutExpr -- ToDo: adjust for System IF doBeta (Lam bndr body) (arg : args) = Let (NonRec bndr arg) (doBeta body args) doBeta fn args = mkApps fn args -- The function is almost always a variable, but not always. -- In particular, if this pass follows float-in, -- which it may, we can get -- (let f = ...f... in f) arg1 arg2 scApp env (other_fn, args) = do { (fn_usg, fn') <- scExpr env other_fn ; (arg_usgs, args') <- mapAndUnzipM (scExpr env) args ; return (combineUsages arg_usgs `combineUsage` fn_usg, mkApps fn' args') } ---------------------- mkVarUsage :: ScEnv -> Id -> [CoreExpr] -> ScUsage mkVarUsage env fn args = case lookupHowBound env fn of Just RecFun -> SCU { scu_calls = unitVarEnv fn [Call fn args (sc_vals env)] , scu_occs = emptyVarEnv } Just RecArg -> SCU { scu_calls = emptyVarEnv , scu_occs = unitVarEnv fn arg_occ } Nothing -> nullUsage where -- I rather think we could use UnkOcc all the time arg_occ | null args = UnkOcc | otherwise = evalScrutOcc ---------------------- scTopBindEnv :: ScEnv -> CoreBind -> UniqSM (ScEnv, CoreBind) scTopBindEnv env (Rec prs) = do { let (rhs_env1,bndrs') = extendRecBndrs env bndrs rhs_env2 = extendHowBound rhs_env1 bndrs RecFun prs' = zip bndrs' rhss ; return (rhs_env2, Rec prs') } where (bndrs,rhss) = unzip prs scTopBindEnv env (NonRec bndr rhs) = do { let (env1, bndr') = extendBndr env bndr env2 = extendValEnv env1 bndr' (isValue (sc_vals env) rhs) ; return (env2, NonRec bndr' rhs) } ---------------------- scTopBind :: ScEnv -> ScUsage -> CoreBind -> UniqSM (ScUsage, CoreBind) {- scTopBind _ usage _ | pprTrace "scTopBind_usage" (ppr (scu_calls usage)) False = error "false" -} scTopBind env body_usage (Rec prs) | Just threshold <- sc_size env , not force_spec , not (all (couldBeSmallEnoughToInline (sc_dflags env) threshold) rhss) -- No specialisation = do { (rhs_usgs, rhss') <- mapAndUnzipM (scExpr env) rhss ; return (body_usage `combineUsage` combineUsages rhs_usgs, Rec (bndrs `zip` rhss')) } | otherwise -- Do specialisation = do { rhs_infos <- mapM (scRecRhs env) prs ; (spec_usage, specs) <- specRec TopLevel (scForce env force_spec) body_usage rhs_infos ; return (body_usage `combineUsage` spec_usage, Rec (concat (zipWith specInfoBinds rhs_infos specs))) } where (bndrs,rhss) = unzip prs force_spec = any (forceSpecBndr env) bndrs -- Note [Forcing specialisation] scTopBind env usage (NonRec bndr rhs) -- Oddly, we don't seem to specialise top-level non-rec functions = do { (rhs_usg', rhs') <- scExpr env rhs ; return (usage `combineUsage` rhs_usg', NonRec bndr rhs') } ---------------------- scRecRhs :: ScEnv -> (OutId, InExpr) -> UniqSM RhsInfo scRecRhs env (bndr,rhs) = do { let (arg_bndrs,body) = collectBinders rhs (body_env, arg_bndrs') = extendBndrsWith RecArg env arg_bndrs ; (body_usg, body') <- scExpr body_env body ; let (rhs_usg, arg_occs) = lookupOccs body_usg arg_bndrs' ; return (RI { ri_rhs_usg = rhs_usg , ri_fn = bndr, ri_new_rhs = mkLams arg_bndrs' body' , ri_lam_bndrs = arg_bndrs, ri_lam_body = body , ri_arg_occs = arg_occs }) } -- The arg_occs says how the visible, -- lambda-bound binders of the RHS are used -- (including the TyVar binders) -- Two pats are the same if they match both ways ---------------------- specInfoBinds :: RhsInfo -> [OneSpec] -> [(Id,CoreExpr)] specInfoBinds (RI { ri_fn = fn, ri_new_rhs = new_rhs }) specs = [(id,rhs) | OS _ _ id rhs <- specs] ++ -- First the specialised bindings [(fn `addIdSpecialisations` rules, new_rhs)] -- And now the original binding where rules = [r | OS _ r _ _ <- specs] {- ************************************************************************ * * The specialiser itself * * ************************************************************************ -} data RhsInfo = RI { ri_fn :: OutId -- The binder , ri_new_rhs :: OutExpr -- The specialised RHS (in current envt) , ri_rhs_usg :: ScUsage -- Usage info from specialising RHS , ri_lam_bndrs :: [InVar] -- The *original* RHS (\xs.body) , ri_lam_body :: InExpr -- Note [Specialise original body] , ri_arg_occs :: [ArgOcc] -- Info on how the xs occur in body } data SpecInfo = SI [OneSpec] -- The specialisations we have generated Int -- Length of specs; used for numbering them (Maybe ScUsage) -- Just cs => we have not yet used calls in the -- from calls in the *original* RHS as -- seeds for new specialisations; -- if you decide to do so, here is the -- RHS usage (which has not yet been -- unleashed) -- Nothing => we have -- See Note [Local recursive groups] -- See Note [spec_usg includes rhs_usg] -- One specialisation: Rule plus definition data OneSpec = OS CallPat -- Call pattern that generated this specialisation CoreRule -- Rule connecting original id with the specialisation OutId OutExpr -- Spec id + its rhs ---------------------- specNonRec :: ScEnv -> ScUsage -- Body usage -> RhsInfo -- Structure info usage info for un-specialised RHS -> UniqSM (ScUsage, [OneSpec]) -- Usage from RHSs (specialised and not) -- plus details of specialisations specNonRec env body_usg rhs_info = do { (spec_usg, SI specs _ _) <- specialise env (scu_calls body_usg) rhs_info (SI [] 0 (Just (ri_rhs_usg rhs_info))) ; return (spec_usg, specs) } ---------------------- specRec :: TopLevelFlag -> ScEnv -> ScUsage -- Body usage -> [RhsInfo] -- Structure info and usage info for un-specialised RHSs -> UniqSM (ScUsage, [[OneSpec]]) -- Usage from all RHSs (specialised and not) -- plus details of specialisations specRec top_lvl env body_usg rhs_infos = do { (spec_usg, spec_infos) <- go seed_calls nullUsage init_spec_infos ; return (spec_usg, [ s | SI s _ _ <- spec_infos ]) } where (seed_calls, init_spec_infos) -- Note [Seeding top-level recursive groups] | isTopLevel top_lvl , any (isExportedId . ri_fn) rhs_infos -- Seed from body and RHSs = (all_calls, [SI [] 0 Nothing | _ <- rhs_infos]) | otherwise -- Seed from body only = (calls_in_body, [SI [] 0 (Just (ri_rhs_usg ri)) | ri <- rhs_infos]) calls_in_body = scu_calls body_usg calls_in_rhss = foldr (combineCalls . scu_calls . ri_rhs_usg) emptyVarEnv rhs_infos all_calls = calls_in_rhss `combineCalls` calls_in_body -- Loop, specialising, until you get no new specialisations go seed_calls usg_so_far spec_infos | isEmptyVarEnv seed_calls = return (usg_so_far, spec_infos) | otherwise = do { specs_w_usg <- zipWithM (specialise env seed_calls) rhs_infos spec_infos ; let (extra_usg_s, new_spec_infos) = unzip specs_w_usg extra_usg = combineUsages extra_usg_s all_usg = usg_so_far `combineUsage` extra_usg ; go (scu_calls extra_usg) all_usg new_spec_infos } ---------------------- specialise :: ScEnv -> CallEnv -- Info on newly-discovered calls to this function -> RhsInfo -> SpecInfo -- Original RHS plus patterns dealt with -> UniqSM (ScUsage, SpecInfo) -- New specialised versions and their usage -- See Note [spec_usg includes rhs_usg] -- Note: this only generates *specialised* bindings -- The original binding is added by specInfoBinds -- -- Note: the rhs here is the optimised version of the original rhs -- So when we make a specialised copy of the RHS, we're starting -- from an RHS whose nested functions have been optimised already. specialise env bind_calls (RI { ri_fn = fn, ri_lam_bndrs = arg_bndrs , ri_lam_body = body, ri_arg_occs = arg_occs }) spec_info@(SI specs spec_count mb_unspec) | isBottomingId fn -- Note [Do not specialise diverging functions] -- and do not generate specialisation seeds from its RHS = return (nullUsage, spec_info) | isNeverActive (idInlineActivation fn) -- See Note [Transfer activation] || null arg_bndrs -- Only specialise functions = case mb_unspec of -- Behave as if there was a single, boring call Just rhs_usg -> return (rhs_usg, SI specs spec_count Nothing) -- See Note [spec_usg includes rhs_usg] Nothing -> return (nullUsage, spec_info) | Just all_calls <- lookupVarEnv bind_calls fn = -- pprTrace "specialise entry {" (ppr fn <+> ppr (length all_calls)) $ do { (boring_call, pats) <- callsToPats env specs arg_occs all_calls -- Bale out if too many specialisations ; let n_pats = length pats spec_count' = n_pats + spec_count ; case sc_count env of Just max | not (sc_force env) && spec_count' > max -> if (debugIsOn || opt_PprStyle_Debug) -- Suppress this scary message for then pprTrace "SpecConstr" msg $ -- ordinary users! Trac #5125 return (nullUsage, spec_info) else return (nullUsage, spec_info) where msg = vcat [ sep [ ptext (sLit "Function") <+> quotes (ppr fn) , nest 2 (ptext (sLit "has") <+> speakNOf spec_count' (ptext (sLit "call pattern")) <> comma <+> ptext (sLit "but the limit is") <+> int max) ] , ptext (sLit "Use -fspec-constr-count=n to set the bound") , extra ] extra | not opt_PprStyle_Debug = ptext (sLit "Use -dppr-debug to see specialisations") | otherwise = ptext (sLit "Specialisations:") <+> ppr (pats ++ [p | OS p _ _ _ <- specs]) _normal_case -> do { -- ; if (not (null pats) || isJust mb_unspec) then -- pprTrace "specialise" (vcat [ ppr fn <+> text "with" <+> int (length pats) <+> text "good patterns" -- , text "mb_unspec" <+> ppr (isJust mb_unspec) -- , text "arg_occs" <+> ppr arg_occs -- , text "good pats" <+> ppr pats]) $ -- return () -- else return () ; let spec_env = decreaseSpecCount env n_pats ; (spec_usgs, new_specs) <- mapAndUnzipM (spec_one spec_env fn arg_bndrs body) (pats `zip` [spec_count..]) -- See Note [Specialise original body] ; let spec_usg = combineUsages spec_usgs -- If there were any boring calls among the seeds (= all_calls), then those -- calls will call the un-specialised function. So we should use the seeds -- from the _unspecialised_ function's RHS, which are in mb_unspec, by returning -- then in new_usg. (new_usg, mb_unspec') = case mb_unspec of Just rhs_usg | boring_call -> (spec_usg `combineUsage` rhs_usg, Nothing) _ -> (spec_usg, mb_unspec) -- ; pprTrace "specialise return }" (ppr fn -- <+> ppr (scu_calls new_usg)) ; return (new_usg, SI (new_specs ++ specs) spec_count' mb_unspec') } } | otherwise -- No new seeds, so return nullUsage = return (nullUsage, spec_info) --------------------- spec_one :: ScEnv -> OutId -- Function -> [InVar] -- Lambda-binders of RHS; should match patterns -> InExpr -- Body of the original function -> (CallPat, Int) -> UniqSM (ScUsage, OneSpec) -- Rule and binding -- spec_one creates a specialised copy of the function, together -- with a rule for using it. I'm very proud of how short this -- function is, considering what it does :-). {- Example In-scope: a, x::a f = /\b \y::[(a,b)] -> ....f (b,c) ((:) (a,(b,c)) (x,v) (h w))... [c::*, v::(b,c) are presumably bound by the (...) part] ==> f_spec = /\ b c \ v::(b,c) hw::[(a,(b,c))] -> (...entire body of f...) [b -> (b,c), y -> ((:) (a,(b,c)) (x,v) hw)] RULE: forall b::* c::*, -- Note, *not* forall a, x v::(b,c), hw::[(a,(b,c))] . f (b,c) ((:) (a,(b,c)) (x,v) hw) = f_spec b c v hw -} spec_one env fn arg_bndrs body (call_pat@(qvars, pats), rule_number) = do { spec_uniq <- getUniqueM ; let spec_env = extendScSubstList (extendScInScope env qvars) (arg_bndrs `zip` pats) fn_name = idName fn fn_loc = nameSrcSpan fn_name fn_occ = nameOccName fn_name spec_occ = mkSpecOcc fn_occ -- We use fn_occ rather than fn in the rule_name string -- as we don't want the uniq to end up in the rule, and -- hence in the ABI, as that can cause spurious ABI -- changes (#4012). rule_name = mkFastString ("SC:" ++ occNameString fn_occ ++ show rule_number) spec_name = mkInternalName spec_uniq spec_occ fn_loc -- ; pprTrace "{spec_one" (ppr (sc_count env) <+> ppr fn <+> ppr pats <+> text "-->" <+> ppr spec_name) $ -- return () -- Specialise the body ; (spec_usg, spec_body) <- scExpr spec_env body -- ; pprTrace "done spec_one}" (ppr fn) $ -- return () -- And build the results ; let spec_id = mkLocalId spec_name (mkPiTypes spec_lam_args body_ty) -- See Note [Transfer strictness] `setIdStrictness` spec_str `setIdArity` count isId spec_lam_args spec_str = calcSpecStrictness fn spec_lam_args pats -- Conditionally use result of new worker-wrapper transform (spec_lam_args, spec_call_args) = mkWorkerArgs (sc_dflags env) qvars NoOneShotInfo body_ty -- Usual w/w hack to avoid generating -- a spec_rhs of unlifted type and no args spec_rhs = mkLams spec_lam_args spec_body body_ty = exprType spec_body rule_rhs = mkVarApps (Var spec_id) spec_call_args inline_act = idInlineActivation fn rule = mkRule True {- Auto -} True {- Local -} rule_name inline_act fn_name qvars pats rule_rhs -- See Note [Transfer activation] ; return (spec_usg, OS call_pat rule spec_id spec_rhs) } calcSpecStrictness :: Id -- The original function -> [Var] -> [CoreExpr] -- Call pattern -> StrictSig -- Strictness of specialised thing -- See Note [Transfer strictness] calcSpecStrictness fn qvars pats = mkClosedStrictSig spec_dmds topRes where spec_dmds = [ lookupVarEnv dmd_env qv `orElse` topDmd | qv <- qvars, isId qv ] StrictSig (DmdType _ dmds _) = idStrictness fn dmd_env = go emptyVarEnv dmds pats go :: DmdEnv -> [Demand] -> [CoreExpr] -> DmdEnv go env ds (Type {} : pats) = go env ds pats go env ds (Coercion {} : pats) = go env ds pats go env (d:ds) (pat : pats) = go (go_one env d pat) ds pats go env _ _ = env go_one :: DmdEnv -> Demand -> CoreExpr -> DmdEnv go_one env d (Var v) = extendVarEnv_C bothDmd env v d go_one env d e | Just ds <- splitProdDmd_maybe d -- NB: d does not have to be strict , (Var _, args) <- collectArgs e = go env ds args go_one env _ _ = env {- Note [spec_usg includes rhs_usg] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In calls to 'specialise', the returned ScUsage must include the rhs_usg in the passed-in SpecInfo, unless there are no calls at all to the function. The caller can, indeed must, assume this. He should not combine in rhs_usg himself, or he'll get rhs_usg twice -- and that can lead to an exponential blowup of duplicates in the CallEnv. This is what gave rise to the massive performace loss in Trac #8852. Note [Specialise original body] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The RhsInfo for a binding keeps the *original* body of the binding. We must specialise that, *not* the result of applying specExpr to the RHS (which is also kept in RhsInfo). Otherwise we end up specialising a specialised RHS, and that can lead directly to exponential behaviour. Note [Transfer activation] ~~~~~~~~~~~~~~~~~~~~~~~~~~ This note is for SpecConstr, but exactly the same thing happens in the overloading specialiser; see Note [Auto-specialisation and RULES] in Specialise. In which phase should the specialise-constructor rules be active? Originally I made them always-active, but Manuel found that this defeated some clever user-written rules. Then I made them active only in Phase 0; after all, currently, the specConstr transformation is only run after the simplifier has reached Phase 0, but that meant that specialisations didn't fire inside wrappers; see test simplCore/should_compile/spec-inline. So now I just use the inline-activation of the parent Id, as the activation for the specialiation RULE, just like the main specialiser; This in turn means there is no point in specialising NOINLINE things, so we test for that. Note [Transfer strictness] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We must transfer strictness information from the original function to the specialised one. Suppose, for example f has strictness SS and a RULE f (a:as) b = f_spec a as b Now we want f_spec to have strictness LLS, otherwise we'll use call-by-need when calling f_spec instead of call-by-value. And that can result in unbounded worsening in space (cf the classic foldl vs foldl') See Trac #3437 for a good example. The function calcSpecStrictness performs the calculation. ************************************************************************ * * \subsection{Argument analysis} * * ************************************************************************ This code deals with analysing call-site arguments to see whether they are constructor applications. Note [Free type variables of the qvar types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a call (f @a x True), that we want to specialise, what variables should we quantify over. Clearly over 'a' and 'x', but what about any type variables free in x's type? In fact we don't need to worry about them because (f @a) can only be a well-typed application if its type is compatible with x, so any variables free in x's type must be free in (f @a), and hence either be gathered via 'a' itself, or be in scope at f's defn. Hence we just take (exprsFreeVars pats). BUT phantom type synonyms can mess this reasoning up, eg x::T b with type T b = Int So we apply expandTypeSynonyms to the bound Ids. See Trac # 5458. Yuk. -} type CallPat = ([Var], [CoreExpr]) -- Quantified variables and arguments callsToPats :: ScEnv -> [OneSpec] -> [ArgOcc] -> [Call] -> UniqSM (Bool, [CallPat]) -- Result has no duplicate patterns, -- nor ones mentioned in done_pats -- Bool indicates that there was at least one boring pattern callsToPats env done_specs bndr_occs calls = do { mb_pats <- mapM (callToPats env bndr_occs) calls ; let good_pats :: [(CallPat, ValueEnv)] good_pats = catMaybes mb_pats done_pats = [p | OS p _ _ _ <- done_specs] is_done p = any (samePat p) done_pats no_recursive = map fst (filterOut (is_too_recursive env) good_pats) ; return (any isNothing mb_pats, filterOut is_done (nubBy samePat no_recursive)) } is_too_recursive :: ScEnv -> (CallPat, ValueEnv) -> Bool -- Count the number of recursive constructors in a call pattern, -- filter out if there are more than the maximum. -- This is only necessary if ForceSpecConstr is in effect: -- otherwise specConstrCount will cause specialisation to terminate. -- See Note [Limit recursive specialisation] is_too_recursive env ((_,exprs), val_env) = sc_force env && maximum (map go exprs) > sc_recursive env where go e | Just (ConVal (DataAlt dc) args) <- isValue val_env e , isRecursiveTyCon (dataConTyCon dc) = 1 + sum (map go args) |App f a <- e = go f + go a | otherwise = 0 callToPats :: ScEnv -> [ArgOcc] -> Call -> UniqSM (Maybe (CallPat, ValueEnv)) -- The [Var] is the variables to quantify over in the rule -- Type variables come first, since they may scope -- over the following term variables -- The [CoreExpr] are the argument patterns for the rule callToPats env bndr_occs (Call _ args con_env) | length args < length bndr_occs -- Check saturated = return Nothing | otherwise = do { let in_scope = substInScope (sc_subst env) ; (interesting, pats) <- argsToPats env in_scope con_env args bndr_occs ; let pat_fvs = varSetElems (exprsFreeVars pats) in_scope_vars = getInScopeVars in_scope qvars = filterOut (`elemVarSet` in_scope_vars) pat_fvs -- Quantify over variables that are not in scope -- at the call site -- See Note [Free type variables of the qvar types] -- See Note [Shadowing] at the top (tvs, ids) = partition isTyVar qvars qvars' = tvs ++ map sanitise ids -- Put the type variables first; the type of a term -- variable may mention a type variable sanitise id = id `setIdType` expandTypeSynonyms (idType id) -- See Note [Free type variables of the qvar types] ; -- pprTrace "callToPats" (ppr args $$ ppr bndr_occs) $ if interesting then return (Just ((qvars', pats), con_env)) else return Nothing } -- argToPat takes an actual argument, and returns an abstracted -- version, consisting of just the "constructor skeleton" of the -- argument, with non-constructor sub-expression replaced by new -- placeholder variables. For example: -- C a (D (f x) (g y)) ==> C p1 (D p2 p3) argToPat :: ScEnv -> InScopeSet -- What's in scope at the fn defn site -> ValueEnv -- ValueEnv at the call site -> CoreArg -- A call arg (or component thereof) -> ArgOcc -> UniqSM (Bool, CoreArg) -- Returns (interesting, pat), -- where pat is the pattern derived from the argument -- interesting=True if the pattern is non-trivial (not a variable or type) -- E.g. x:xs --> (True, x:xs) -- f xs --> (False, w) where w is a fresh wildcard -- (f xs, 'c') --> (True, (w, 'c')) where w is a fresh wildcard -- \x. x+y --> (True, \x. x+y) -- lvl7 --> (True, lvl7) if lvl7 is bound -- somewhere further out argToPat _env _in_scope _val_env arg@(Type {}) _arg_occ = return (False, arg) argToPat env in_scope val_env (Tick _ arg) arg_occ = argToPat env in_scope val_env arg arg_occ -- Note [Notes in call patterns] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Ignore Notes. In particular, we want to ignore any InlineMe notes -- Perhaps we should not ignore profiling notes, but I'm going to -- ride roughshod over them all for now. --- See Note [Notes in RULE matching] in Rules argToPat env in_scope val_env (Let _ arg) arg_occ = argToPat env in_scope val_env arg arg_occ -- See Note [Matching lets] in Rule.hs -- Look through let expressions -- e.g. f (let v = rhs in (v,w)) -- Here we can specialise for f (v,w) -- because the rule-matcher will look through the let. {- Disabled; see Note [Matching cases] in Rule.hs argToPat env in_scope val_env (Case scrut _ _ [(_, _, rhs)]) arg_occ | exprOkForSpeculation scrut -- See Note [Matching cases] in Rule.hhs = argToPat env in_scope val_env rhs arg_occ -} argToPat env in_scope val_env (Cast arg co) arg_occ | isReflCo co -- Substitution in the SpecConstr itself -- can lead to identity coercions = argToPat env in_scope val_env arg arg_occ | not (ignoreType env ty2) = do { (interesting, arg') <- argToPat env in_scope val_env arg arg_occ ; if not interesting then wildCardPat ty2 else do { -- Make a wild-card pattern for the coercion uniq <- getUniqueM ; let co_name = mkSysTvName uniq (fsLit "sg") co_var = mkCoVar co_name (mkCoercionType Representational ty1 ty2) ; return (interesting, Cast arg' (mkCoVarCo co_var)) } } where Pair ty1 ty2 = coercionKind co {- Disabling lambda specialisation for now It's fragile, and the spec_loop can be infinite argToPat in_scope val_env arg arg_occ | is_value_lam arg = return (True, arg) where is_value_lam (Lam v e) -- Spot a value lambda, even if | isId v = True -- it is inside a type lambda | otherwise = is_value_lam e is_value_lam other = False -} -- Check for a constructor application -- NB: this *precedes* the Var case, so that we catch nullary constrs argToPat env in_scope val_env arg arg_occ | Just (ConVal (DataAlt dc) args) <- isValue val_env arg , not (ignoreDataCon env dc) -- See Note [NoSpecConstr] , Just arg_occs <- mb_scrut dc = do { let (ty_args, rest_args) = splitAtList (dataConUnivTyVars dc) args ; (_, args') <- argsToPats env in_scope val_env rest_args arg_occs ; return (True, mkConApp dc (ty_args ++ args')) } where mb_scrut dc = case arg_occ of ScrutOcc bs | Just occs <- lookupUFM bs dc -> Just (occs) -- See Note [Reboxing] _other | sc_force env -> Just (repeat UnkOcc) | otherwise -> Nothing -- Check if the argument is a variable that -- (a) is used in an interesting way in the function body -- (b) we know what its value is -- In that case it counts as "interesting" argToPat env in_scope val_env (Var v) arg_occ | sc_force env || case arg_occ of { UnkOcc -> False; _other -> True }, -- (a) is_value, -- (b) not (ignoreType env (varType v)) = return (True, Var v) where is_value | isLocalId v = v `elemInScopeSet` in_scope && isJust (lookupVarEnv val_env v) -- Local variables have values in val_env | otherwise = isValueUnfolding (idUnfolding v) -- Imports have unfoldings -- I'm really not sure what this comment means -- And by not wild-carding we tend to get forall'd -- variables that are in scope, which in turn can -- expose the weakness in let-matching -- See Note [Matching lets] in Rules -- Check for a variable bound inside the function. -- Don't make a wild-card, because we may usefully share -- e.g. f a = let x = ... in f (x,x) -- NB: this case follows the lambda and con-app cases!! -- argToPat _in_scope _val_env (Var v) _arg_occ -- = return (False, Var v) -- SLPJ : disabling this to avoid proliferation of versions -- also works badly when thinking about seeding the loop -- from the body of the let -- f x y = letrec g z = ... in g (x,y) -- We don't want to specialise for that *particular* x,y -- The default case: make a wild-card -- We use this for coercions too argToPat _env _in_scope _val_env arg _arg_occ = wildCardPat (exprType arg) wildCardPat :: Type -> UniqSM (Bool, CoreArg) wildCardPat ty = do { uniq <- getUniqueM ; let id = mkSysLocal (fsLit "sc") uniq ty ; return (False, varToCoreExpr id) } argsToPats :: ScEnv -> InScopeSet -> ValueEnv -> [CoreArg] -> [ArgOcc] -- Should be same length -> UniqSM (Bool, [CoreArg]) argsToPats env in_scope val_env args occs = do { stuff <- zipWithM (argToPat env in_scope val_env) args occs ; let (interesting_s, args') = unzip stuff ; return (or interesting_s, args') } isValue :: ValueEnv -> CoreExpr -> Maybe Value isValue _env (Lit lit) | litIsLifted lit = Nothing | otherwise = Just (ConVal (LitAlt lit) []) isValue env (Var v) | Just cval <- lookupVarEnv env v = Just cval -- You might think we could look in the idUnfolding here -- but that doesn't take account of which branch of a -- case we are in, which is the whole point | not (isLocalId v) && isCheapUnfolding unf = isValue env (unfoldingTemplate unf) where unf = idUnfolding v -- However we do want to consult the unfolding -- as well, for let-bound constructors! isValue env (Lam b e) | isTyVar b = case isValue env e of Just _ -> Just LambdaVal Nothing -> Nothing | otherwise = Just LambdaVal isValue env (Tick t e) | not (tickishIsCode t) = isValue env e isValue _env expr -- Maybe it's a constructor application | (Var fun, args, _) <- collectArgsTicks (not . tickishIsCode) expr = case isDataConWorkId_maybe fun of Just con | args `lengthAtLeast` dataConRepArity con -- Check saturated; might be > because the -- arity excludes type args -> Just (ConVal (DataAlt con) args) _other | valArgCount args < idArity fun -- Under-applied function -> Just LambdaVal -- Partial application _other -> Nothing isValue _env _expr = Nothing valueIsWorkFree :: Value -> Bool valueIsWorkFree LambdaVal = True valueIsWorkFree (ConVal _ args) = all exprIsWorkFree args samePat :: CallPat -> CallPat -> Bool samePat (vs1, as1) (vs2, as2) = all2 same as1 as2 where same (Var v1) (Var v2) | v1 `elem` vs1 = v2 `elem` vs2 | v2 `elem` vs2 = False | otherwise = v1 == v2 same (Lit l1) (Lit l2) = l1==l2 same (App f1 a1) (App f2 a2) = same f1 f2 && same a1 a2 same (Type {}) (Type {}) = True -- Note [Ignore type differences] same (Coercion {}) (Coercion {}) = True same (Tick _ e1) e2 = same e1 e2 -- Ignore casts and notes same (Cast e1 _) e2 = same e1 e2 same e1 (Tick _ e2) = same e1 e2 same e1 (Cast e2 _) = same e1 e2 same e1 e2 = WARN( bad e1 || bad e2, ppr e1 $$ ppr e2) False -- Let, lambda, case should not occur bad (Case {}) = True bad (Let {}) = True bad (Lam {}) = True bad _other = False {- Note [Ignore type differences] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We do not want to generate specialisations where the call patterns differ only in their type arguments! Not only is it utterly useless, but it also means that (with polymorphic recursion) we can generate an infinite number of specialisations. Example is Data.Sequence.adjustTree, I think. -}
christiaanb/ghc
compiler/specialise/SpecConstr.hs
bsd-3-clause
83,984
5
27
25,551
10,943
5,807
5,136
-1
-1
module B1 where import Control.Parallel.Strategies -- test when already import strategies the import doesn't change. qsort (x:xs) = lsort_2 ++ [x] ++ hsort_2 where lsort = qsort (filter (<) x xs) hsort = qsort (filter (>=) x xs) (lsort_2, hsort_2) = runEval (do lsort_2 <- rpar lsort hsort_2 <- rpar hsort return (lsort_2, hsort_2))
RefactoringTools/HaRe
old/testing/evalAddEvalMon/B1_TokOut.hs
bsd-3-clause
419
0
12
140
129
69
60
10
1
module SubPatternIn3 where -- takes into account general type variables -- within type implementation. -- here T has its arguments instantiated within g -- selecting 'b' should instantiate list patterns -- selecting 'c' should give an error. -- data T a b = C1 a b | C2 b g :: Int -> T Int [Int] -> Int g z (C1 b c) = b g z (C2 x) = hd x f :: [Int] -> Int f x@[] = hd x + hd (tl x) f x@(y:ys) = hd x + hd (tl x) hd x = head x tl x = tail x
kmate/HaRe
old/testing/subIntroPattern/SubPatternIn3.hs
bsd-3-clause
449
0
8
114
183
97
86
10
1
import StockMarket import Data.Tuple.Curry (uncurryN) import GTL.Data.Mockup (Mockup, Role(..), mockupToArray, arrayToMockup) import GTL.Data.History.Instances (History0) import GTL.Numeric.Probability ((?!)) import Numeric.Probability.Distribution hiding (pretty, map) import Control.Monad (replicateM_) import Text.Printf (printf) import GTL.Interaction.Learning2 (Comp, Param(..), Var(..), runComp, logVar, oneStep) initMock1 :: Mockup Order Price History0 History0 initMock1 = const $ choose 1 High Low initMock2 :: Mockup Order Price History0 History0 initMock2 = const $ choose 0 High Low tMax :: Int tMax = 100 comp :: Comp Environment State Order Price History0 History0 State Order Price History0 History0 () comp = logVar >> oneStep main :: IO () main = putStr $ concat $ ["time phigh1 phigh2\n"] ++ (map (uncurryN $ printf "%5d %.6f %.6f\n") $ zip3 ([0..] :: [Int]) ps1 ps2 :: [String]) where vals = runComp (replicateM_ (tMax + 1) comp) p v ps1 = map pHigh1 vals ps2 = map pHigh2 vals pHigh arr = arrayToMockup arr minBound ?! High pHigh1 = pHigh . mockupArray1 pHigh2 = pHigh . mockupArray2 arr1 = mockupToArray initMock1 arr2 = mockupToArray initMock2 step = 0.1 epsi = 0 rol = Role dyn util 0.95 p = Param rol rol sig2 epsi epsi (const step) (const step) 1 v = Var arr1 arr2 1
dudebout/cdc_2012_dudebout_shamma
simulations/simulation_theoretical.hs
isc
1,426
0
11
334
487
271
216
32
1
-- Bin to Decimal -- https://www.codewars.com/kata/57a5c31ce298a7e6b7000334 module BinToDecimal where import Data.Char (digitToInt) binToDec :: String -> Int binToDec = sum . zipWith (\p n -> n*2^p) [0..] . map digitToInt . reverse
gafiatulin/codewars
src/8 kyu/BinToDecimal.hs
mit
235
0
12
35
71
40
31
4
1
module Parser.TestUtils where import Data.Either (isRight) import Parser.Internal import Test.Hspec import Text.Parsec import Text.Parsec.String shouldSucceed :: (Show a, Eq a) => Parser a -> String -> IO () shouldSucceed parser input = input `shouldSatisfy` succeeds parser shouldFail :: (Show a, Eq a) => Parser a -> String -> IO () shouldFail parser input = input `shouldNotSatisfy` succeeds parser succeeds :: Parser a -> String -> Bool succeeds parser = succeedsWithLeftover $ parser >> eof succeedsWithLeftover :: Parser a -> String -> Bool succeedsWithLeftover parser input = isRight $ parseWithoutSource parser input succeedsAnywhere :: Parser a -> String -> Bool succeedsAnywhere p s = or $ map (succeedsWithLeftover p) (tails s) where tails :: [a] -> [[a]] tails [] = [[]] tails ass@(_:as) = ass : tails as fails :: Parser a -> String -> Bool fails parser input = not $ succeeds parser input testInputSource :: String testInputSource = "Test input" parseShouldSucceedAs :: (Show a, Eq a) => Parser a -> String -> a -> IO () parseShouldSucceedAs parser input a = parseFromSource parser testInputSource input `shouldBe` Right a parseShouldBe :: (Show a, Eq a) => Parser a -> String -> Either ParseError a -> IO () parseShouldBe parser input result = parseFromSource parser testInputSource input `shouldBe` result parseWithoutSource :: Parser a -> String -> Either ParseError a parseWithoutSource parser input = parseFromSource parser testInputSource input
badi/super-user-spark
test/Parser/TestUtils.hs
mit
1,547
0
10
309
542
278
264
29
2
module RE where -- Regular Expression import DFA import State import Prelude hiding (concat) import Data.List hiding (concat, union) import Control.Monad data RE a = Concat [RE a] | Union [RE a] | Closure (RE a) | Symbol a | Epsilon | EmptySet instance (Eq a) => Eq (RE a) where Concat xs == Concat ys = xs == ys Union xs == Union ys = xs == ys Closure x == Closure y = x == y Symbol a == Symbol b = a == b Epsilon == Epsilon = True EmptySet == EmptySet = True _ == _ = False concat :: (Eq a) => [RE a] -> RE a concat xs = case length xs' of 0 -> Epsilon 1 -> head xs' _ -> Concat xs' where xs' = if any (== EmptySet) xs then [] else filter (/= Epsilon) xs union :: (Eq a) => [RE a] -> RE a union xs = case length xs' of 0 -> Epsilon 1 -> head xs' _ -> Union xs' where xs' = nub $ filter (/= EmptySet) xs closure :: RE a -> RE a closure Epsilon = Epsilon closure x = Closure x {- {- For debug uses -} union = Union closure = Closure concat = Concat -} instance (Show a) => Show (RE a) where show (Concat xs) = join $ map optAddParen xs where optAddParen x = case x of Closure _ -> "(" ++ show x ++ ")" Union _ -> "(" ++ show x ++ ")" _ -> show x show (Union xs) = intercalate "+" $ map show xs show (Closure xs) = optAddParen xs ++ "*" where optAddParen x = case x of Symbol _ -> show x Closure _ -> show x _ -> "(" ++ show x ++ ")" show (Symbol a) = show a show Epsilon = "ε" show EmptySet = "∅" kPath :: (IntState s, Eq s, Eq i) => Integer -> Integer -> Integer -> -- i,j,k DFA s i -> RE i kPath i j 0 (DFA _ _ transFunc) = if i == j then Epsilon else case find (\(s,_,s') -> noToState i == s && noToState j == s') transtbl of Just (_,input,_) -> Symbol input Nothing -> EmptySet where transtbl = transFuncToTable transFunc kPath i j k dfa = union [kPath i j (k - 1) dfa ,concat [kPath i k (k - 1) dfa ,closure (kPath k k (k - 1) dfa) ,kPath k j (k - 1) dfa ]] -- kPath :: DFA (Integer)
shouya/thinking-dumps
automata/RE.hs
mit
2,260
0
13
795
968
486
482
66
4
{-# LANGUAGE NoImplicitPrelude #-} module Prelude.String ( module Prelude.String.Type, module Prelude.String.Show, module Prelude.String.Read, ) where import Prelude.String.Type import Prelude.String.Show import Prelude.String.Read
scott-fleischman/cafeteria-prelude
src/Prelude/String.hs
mit
248
0
5
37
49
34
15
8
0
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} {-| Module : Main Description : Main module for 'update-breadu-server' program. Stability : experimental Portability : POSIX This program updates 'breadu-exe' server. Assumed that: 1. New executable, common food and static files already copied here from the CI-server. 2. Current user can do sudo-commands without password, for simplicity. 3. Nginx web server is already installed on production server. 4. Nginx config /etc/nginx/sites-enabled/default already contains 'proxy_pass'-record for 127.0.0.1:3000. -} module Main where import Data.Conduit.Shell import Data.Conduit.Shell.Segments ( strings ) import System.FilePath.Posix ( (</>) ) import Control.Applicative ( (<|>) ) import Data.Monoid ( (<>) ) -- | Helper types. type Port = String type PID = String newtype FromPort = From Port newtype ToPort = To Port main :: IO () main = run $ do mv pathToTmpExecutable pathToExecutable lookPIDOfCurrentProcess >>= \case Nothing -> startNewServerOn defaultPort Just pid -> updateServer pid where lookPIDOfCurrentProcess :: Segment (Maybe PID) lookPIDOfCurrentProcess = strings ( pgrep "-l" executableName <|> return () $| awk "{print $1}") >>= \output -> return $ case output of [] -> Nothing (pid:_) -> Just pid updateServer :: PID -> Segment () updateServer pidOfCurrentProcess = strings ( sudo "netstat" "-antulp" -- There's no operator to combine 'sudo' with command... :-( $| grep executableName $| awk "{split($4,a,\":\"); print a[2]}") >>= \output -> case output of [] -> do -- It's really strange: there's no port, but it must be here! startNewServerOn defaultPort switchNginxToNewServer (From alternativePort) (To defaultPort) stopOldServerBy pidOfCurrentProcess (currentPort:_) -> do if currentPort == defaultPort then do startNewServerOn alternativePort switchNginxToNewServer (From defaultPort) (To alternativePort) else do startNewServerOn defaultPort switchNginxToNewServer (From alternativePort) (To defaultPort) stopOldServerBy pidOfCurrentProcess startNewServerOn :: Port -> Segment () startNewServerOn port = startStopDaemon "--start" "-b" "-q" "-x" pathToExecutable "--" "-p" port "-f" pathToCommonFood stopOldServerBy :: PID -> Segment () stopOldServerBy pid = startStopDaemon "--stop" "-o" "-q" "--pid" pid switchNginxToNewServer :: FromPort -> ToPort -> Segment () switchNginxToNewServer (From currentPort) (To newPort) = do sudo "sed" "-i" replaceProxyPass pathToNginxConfig sudo "nginx" "-s" "reload" where replaceProxyPass = mconcat ["s#", proxyPass <> currentPort, "#", proxyPass <> newPort, "#g"] proxyPass = "proxy_pass http://127.0.0.1:" -- Main constants. executableName = "breadu-exe" rootDirectory = "/home/dshevchenko/breadu-root" pathToCommonFood = rootDirectory </> "food/common" pathToExecutable = rootDirectory </> executableName pathToTmpExecutable = "/tmp" </> executableName pathToNginxConfig = "/etc/nginx/sites-enabled/default" defaultPort = "3000" alternativePort = "3010"
denisshevchenko/breadu.info
src/update/Main.hs
mit
3,799
0
19
1,207
654
338
316
61
5
module Lab3 where ----------------------------------------------------------------------------------------------------------------------------- -- LIST COMPREHENSIONS ------------------------------------------------------------------------------------------------------------------------------ -- =================================== -- Ex. 0 - 2 -- =================================== evens :: [Integer] -> [Integer] evens xs = [x | x <- xs, even x] -- =================================== -- Ex. 3 - 4 -- =================================== -- complete the following line with the correct type signature for this function squares :: Integer -> [Integer] squares n = [x * x | x <- [ 1..n ]] sumSquares :: Integer -> Integer sumSquares n = sum (squares n) -- =================================== -- Ex. 5 - 7 -- =================================== -- complete the following line with the correct type signature for this function squares' :: Integer -> Integer -> [Integer] squares' count offset = [x * x | x <- [ (offset+1)..(count+offset) ]] {-squares' count offset = drop offset (take count (squares count + offset))-} sumSquares' :: Integer -> Integer sumSquares' x = sum . uncurry squares' $ (x, x) -- =================================== -- Ex. 8 -- =================================== coords :: Integer -> Integer -> [(Integer,Integer)] coords m n = [(x, y) | x <- [0..m], y <- [0..n]]
adz/real_world_haskell
edx-fp1/lab3.hs
mit
1,400
0
10
190
290
167
123
13
1
-- some definitions for OR import Prelude hiding ((||)) False || False = False _ || _ = True False || b = b True || _ = True b || False = b _ || True = True b || c | b == c = b | otherwise = True b || c | b == c = c | otherwise = True test = [ ("F || F", False || False), ("F || T", False || True), ("T || F", True || False), ("T || T", True || True)]
calebgregory/fp101x
wk2/disjunction.hs
mit
387
0
8
127
196
100
96
18
1
module POV (fromPOV, tracePathBetween) where import Data.Tree (Tree) fromPOV :: Eq a => a -> Tree a -> Maybe (Tree a) fromPOV x tree = error "You need to implement this function." tracePathBetween :: Eq a => a -> a -> Tree a -> Maybe [a] tracePathBetween from to tree = error "You need to implement this function."
exercism/xhaskell
exercises/practice/pov/src/POV.hs
mit
318
0
10
61
115
58
57
6
1
-- file: ch03/Tree.hs -- From chapter 3, http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html data Tree a = Node a (Tree a) (Tree a) | Empty deriving (Show) simpleTree = Node "parent" (Node "left child" Empty Empty) (Node "right child" Empty Empty)
Sgoettschkes/learning
haskell/RealWorldHaskell/ch03/Tree.hs
mit
291
0
8
50
71
38
33
5
1
{-# LANGUAGE OverloadedLists #-} -- | This is simply a test to make sure things work until I can come up with -- some real examples. module Main where import qualified Linear as L import qualified Iris.Backends.GLFW as W import Iris.Camera import Iris.Reactive import Iris.SceneGraph import Iris.Transformation import Iris.Visuals main :: IO () main = do win <- W.makeWindow "Line Plot" (640, 640) canvas <- W.initGLFW win line <- lineInit $ lineSpec { lineSpecVertices = lineVerts , lineSpecColors = L.V3 0.2 0.5 1 } mesh <- meshInit $ meshSpec { meshSpecData = Vertexes meshVerts , meshSpecColors = ConstantMeshColor (L.V3 0.2 1 0.1) } mesh2 <- meshInit $ meshSpec { meshSpecData = Faces meshFaceVerts meshFaceIndices , meshSpecColors = ConstantMeshColor (L.V3 1 0.2 0.1) } mesh3 <- meshInit $ meshSpec { meshSpecData = Vertexes meshVerts , meshSpecColors = VectorMeshColor meshVertColors } let items = groupNode [ line , mesh , transNode (translation (L.V3 2 2 0)) mesh2 , transNode (translation (L.V3 (-1) 1 0)) mesh , transNode (translation (L.V3 (-2) 3 0)) mesh3 ] cam = panZoomCamera { panZoomCenter = L.V2 1 2 , panZoomWidth = 10 , panZoomHeight = 7 } network <- compile $ sceneWithCamera canvas (pure items) cam actuate network W.mainLoop canvas lineVerts :: LineVertices lineVerts = [ L.V3 1 1 0 , L.V3 1 2 0 , L.V3 2 2 0 ] meshVerts :: MeshVertices meshVerts = [ L.V3 (L.V3 0 0 0) (L.V3 1 1 0) (L.V3 0 1 0) , L.V3 (L.V3 0 0 0) (L.V3 1 0 0) (L.V3 1 1 0) ] meshVertColors :: MeshVectorColor meshVertColors = [ L.V3 0 1 0 , L.V3 1 0 0 , L.V3 0 0 1 , L.V3 1 1 0 , L.V3 0 1 1 , L.V3 1 0 1 ] meshFaceVerts :: MeshFaceVertices meshFaceVerts = [ L.V3 0 0 0 , L.V3 1 1 0 , L.V3 1 2 0 , L.V3 0 1 0 ] meshFaceIndices :: MeshFaceIndices meshFaceIndices = [ L.V3 0 1 2 , L.V3 2 3 0 ]
jdreaver/iris
examples/Line.hs
mit
2,498
0
18
1,052
749
392
357
59
1
module HarmLang.ChordProgressionDatabase where --import qualified Data.Text import Data.List import Data.Maybe import qualified Data.Map import HarmLang.Types import HarmLang.Interpreter import HarmLang.Utility --TODO This should be generic, so they could be used with TimedChordProgression and TimedTimedChordProgression. data ChordProgressionDatabase = ChordProgressionDatabase [((Data.Map.Map String String), TimedChordProgression)] deriving Show --splitByCriterion :: ChordProgressionDatabase -> String -> [(String, [TimedChordProgression]) getProgressionsInCategoryByCriterion :: ChordProgressionDatabase -> String -> String -> [TimedChordProgression] getProgressionsInCategoryByCriterion (ChordProgressionDatabase list) criterion category = map snd (filter (\ (map, _) -> ((==) ((flip Data.Map.lookup) map criterion) (Just category))) list) getCategoriesInCriterion :: ChordProgressionDatabase -> String -> [String] --getCategoriesInCriterion (ChordProgressionDatabase list) criterion = Data.Map.mapMaybe ((flip Data.Map.lookup) criterion $ fst) list getCategoriesInCriterion (ChordProgressionDatabase list) criterion = nub $ Data.Maybe.mapMaybe (\ cpMap -> Data.Map.lookup criterion cpMap) (map fst list) getProgressionsCategorizedByCriterion :: ChordProgressionDatabase -> String -> [(String, [TimedChordProgression])] getProgressionsCategorizedByCriterion cpd criterion = map (\catName -> (catName, getProgressionsInCategoryByCriterion cpd criterion catName)) $ getCategoriesInCriterion cpd criterion compareBy :: (Ord b) => (a -> b) -> (a -> a -> Ordering) compareBy f = (\ a1 a2 -> compare (f a1) (f a2)) sortGroupsByName :: [(String, [TimedChordProgression])] -> [(String, [TimedChordProgression])] sortGroupsByName = sortBy (compareBy fst) sortGroupsBySize :: [(String, [TimedChordProgression])] -> [(String, [TimedChordProgression])] sortGroupsBySize = sortBy (compareBy (length . snd)) cpdEntryFromString :: String -> ((Data.Map.Map String String), TimedChordProgression) cpdEntryFromString str = let greatSplits :: [String] greatSplits = separateBy ';' str minorSplits :: [[String]] minorSplits = map (separateBy ':') greatSplits progression :: TimedChordProgression progression = interpretTimedChordProgression $ last greatSplits allButLastMinorSplit :: [[String]] allButLastMinorSplit = (take ((-) (length minorSplits) 1) minorSplits) progMap = Data.Map.fromList (map (\ l -> (l !! 0, l !! 1)) allButLastMinorSplit) in (progMap, progression) cpdDbFromStrings :: [String] -> ChordProgressionDatabase cpdDbFromStrings strings = ChordProgressionDatabase (map cpdEntryFromString (filter (\ str -> (not $ null str) && ((/=) '#' (head str))) strings)) loadChordProgressionDatabase :: String -> IO ChordProgressionDatabase loadChordProgressionDatabase fileName = do wholeFile <- readFile fileName return $ cpdDbFromStrings (lines wholeFile) testCPDLoader = do db <- loadChordProgressionDatabase "res/progressions.txt" putStrLn . show $ db
cyruscousins/HarmLang
src/HarmLang/ChordProgressionDatabase.hs
mit
3,006
0
16
371
817
449
368
42
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.RTCIceCandidate ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.RTCIceCandidate #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.RTCIceCandidate #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/RTCIceCandidate.hs
mit
358
0
5
33
33
26
7
4
0
-- | Parallel quicksort. import Control.Monad import Control.Monad.ST (ST (..), runST) import Data.Array.ST import Control.Parallel.Strategies qsortImpl :: (Integral i, Ix i, Ord e, MArray arr e m) => arr i e -> i -> i -> m () qsortImpl arr l r = when (r > l) $ do let mid = l + (r - l) `div` 2 nmid <- partition arr l r mid withStrategy rpar $ qsortImpl arr l (nmid - 1) qsortImpl arr (nmid + 1) r partition :: (Integral i, Ix i, Ord e, MArray arr e m) => arr i e -> i -> i -> i -> m i partition arr l r mid = do pivot <- readArray arr mid swap arr mid r slot <- foreach [l..r-1] l (\slot i -> do val <- readArray arr i if val < pivot then swap arr i slot >> return (slot+1) else return slot) swap arr slot r >> return slot swap :: (Ix i, MArray arr e m) => arr i e -> i -> i -> m () swap arr ia ib = do a <- readArray arr ia b <- readArray arr ib writeArray arr ia b writeArray arr ib a foreach :: (Monad m, Foldable t) => t a -> b -> (b -> a -> m b) -> m b foreach xs v f = foldM f v xs qsort :: [Int] -> [Int] qsort xs = runST $ do let len = length xs - 1 arr <- newListArray (0, len) xs :: ST s (STArray s Int Int) qsortImpl arr 0 len >> getElems arr main = print $ qsort [1,3,5,7,9,2,4,6,8,0]
sighingnow/sighingnow.github.io
resource/quicksort_in_haskell/par-sort.hs
mit
1,348
0
17
424
712
355
357
34
2
{- - Map file loader -} module Resources.Map ( MapData(..) , loadData ) where import Control.Monad (replicateM) import qualified Data.ByteString as B import Data.Binary.Strict.Get import Data.Bits import Data.Char (chr) import Data.Word import Utils (bytesToString, bsToListOfWord8 ,encodeWord16le, bytesToInt) numHeaders :: Int numHeaders = 100 mapPlanes :: Int mapPlanes = 2 mapWidth :: Int mapWidth = 64 mapHeight :: Int mapHeight = 64 data MapFileType = MapFileType { rlewTag :: Word16 , headerOffsets :: [Int] , tileInfo :: [Word8] } deriving (Show) data MapType = MapType { planeStart :: (Int, Int, Int) , planeLength :: (Int, Int, Int) , mapWh :: (Int, Int) -- width, height , name :: String } deriving (Show) data MapData = MapData { mapSize :: (Int, Int) , mapData :: ([Word8], [Word8]) -- data per planes } deriving (Show) -- | -- getTileInfo :: Get [Word8] getTileInfo = do e <- isEmpty if e then return [] else do ti <- getWord8 rest <- getTileInfo return $ ti : rest -- | -- parseHeader :: Get MapFileType parseHeader = do e <- isEmpty if e then return $ MapFileType undefined undefined undefined else do tag <- getWord16le ofs <- replicateM numHeaders getWord32le tif <- getTileInfo return $ MapFileType tag (map fromIntegral ofs) tif -- | -- getHeader :: B.ByteString -> MapFileType getHeader raw = do let res = runGet parseHeader raw in case res of ((Right mft), _) -> mft ((Left err), _) -> error "Map: unable to parse header" -- | -- parseMapInfo :: Get MapType parseMapInfo = do e <- isEmpty if e then return $ MapType undefined undefined undefined undefined else do pl1 <- getWord32le pl2 <- getWord32le pl3 <- getWord32le plLen1 <- getWord16le -- TODO: combine into one tuple with planes? plLen2 <- getWord16le plLen3 <- getWord16le w <- getWord16le h <- getWord16le name <- replicateM 16 getWord8 return $ MapType (fromIntegral pl1, fromIntegral pl2, fromIntegral pl3) (fromIntegral plLen1, fromIntegral plLen2, fromIntegral plLen3) (fromIntegral w, fromIntegral h) (bytesToString name) -- | -- getMapInfo :: B.ByteString -> MapType getMapInfo raw = do let res = runGet parseMapInfo raw in case res of ((Right mt), _) -> mt ((Left err), _) -> error "Map: unable to parse gamemap" -- | -- TODO rlewExpand :: Word16 -> [Word8] -> [Word8] rlewExpand _ [] = [] rlewExpand tag (lo:hi:xs) = if lo == tagLo && hi == tagHi then (concat $ replicate cnt val) ++ rlewExpand tag (drop 4 xs) else lo : hi : rlewExpand tag xs where (tagHi, tagLo) = encodeWord16le tag [cntLo, cntHi] = take 2 xs cnt = bytesToInt [cntLo, cntHi, 0, 0] val = take 2 $ drop 2 xs nearTag, farTag :: Word8 nearTag = 0xa7 farTag = 0xa8 unp ls [] = ls unp ls (c:t:xs) = case t of _ | t == nearTag -> if c == 0 then unp (ls ++ [head xs, t]) (tail xs) else unp (ls ++ take (fromIntegral c * 2) dbck) (tail xs) | t == farTag -> if c == 0 then unp (ls ++ [head xs, t]) (tail xs) else unp (ls ++ take (fromIntegral c * 2) dfwd) (drop 2 xs) | otherwise -> unp (ls ++ [c, t]) xs where dbck = drop ((length ls) - (fromIntegral (head xs)) * 2) ls [farLo, farHi] = take 2 xs dfwd = drop (fromIntegral (bytesToInt [farLo, farHi, 0, 0]) * 2) ls carmackExpand :: [Word8] -> [Word8] carmackExpand [] = [] carmackExpand d = unp [] d -- | -- TODO getMapData :: B.ByteString -> MapType -> MapFileType -> ([Word8], [Word8]) getMapData md mt mft = do let tag = rlewTag mft (pl1ofs, pl2ofs, _) = planeStart mt (pl1len, pl2len, _) = planeLength mt pl1comp = B.drop 2 . B.take pl1len . B.drop pl1ofs $ md -- carmacized data, drop length pl2comp = B.drop 2 . B.take pl2len . B.drop pl2ofs $ md pl1dec = rlewExpand tag . drop 2 $ carmackExpand $ bsToListOfWord8 pl1comp pl2dec = rlewExpand tag . drop 2 $ carmackExpand $ bsToListOfWord8 pl2comp (,) pl1dec pl2dec -- | -- loadData :: B.ByteString -> B.ByteString -> [MapData] loadData md hdr = map (\d -> MapData (mapWh d) (getMapData md d mft)) mdsc where mft = getHeader hdr hdrs = filter (/= 0) $ headerOffsets mft -- skip zero offsets as unused mdsc = map (\i -> getMapInfo $ B.drop i md) hdrs
vTurbine/w3dhs
src/Resources/Map.hs
mit
5,263
0
16
1,982
1,711
907
804
134
3
module Rebase.Data.Tree ( module Data.Tree ) where import Data.Tree
nikita-volkov/rebase
library/Rebase/Data/Tree.hs
mit
71
0
5
12
20
13
7
4
0
module Problem28 where main = print $ sum $ takeWhile (<=1001^2) $ iterate (\n -> n + (ringDelta n)) 1 ringDelta :: Int -> Int ringDelta n = let n' = floor $ sqrt (fromIntegral n) in if even n' then n' else n' + 1
DevJac/haskell-project-euler
src/Problem28.hs
mit
272
0
12
104
111
58
53
7
2
{-# LANGUAGE TypeOperators , Arrows , TypeFamilies , OverloadedStrings , ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Document.Phase.Expressions where -- -- Modules -- import Document.ExprScope as ES import Document.Pipeline import Document.Phase as P import Document.Phase.Parameters import Document.Phase.Transient import Document.Phase.Types import Document.Proof import Document.Scope import Document.Visitor import Logic.Expr.Parser import UnitB.Expr import UnitB.Syntax as AST hiding (invariant) -- -- Libraries -- import Control.Arrow hiding (left,app) -- (Arrow,arr,(>>>)) import qualified Control.Category as C import Control.Lens as L hiding ((|>),(<.>),(<|),indices,Context) import Control.Lens.Misc import Control.Monad import Control.Monad.Reader.Class import Control.Monad.Reader (Reader) import Control.Monad.State.Class import Control.Monad.Trans.RWS as RWS ( RWS ) import qualified Control.Monad.Writer as W import Control.Precondition import Data.Either import Data.Existential import Data.Functor.Compose import Data.List as L hiding ( union, insert, inits ) import qualified Data.List.NonEmpty as NE import Data.Map as M hiding ( map, (\\), (!) ) import qualified Data.Map as M import Data.Semigroup import qualified Data.Traversable as T import Test.QuickCheck hiding (label) import Test.QuickCheck.Report import Test.QuickCheck.ZoomEq import Text.Printf.TH import Text.Show.With import Utilities.Syntactic withHierarchy :: Pipeline MM (Hierarchy MachineId,MMap a) (MMap b) -> Pipeline MM (SystemP a) (SystemP b) withHierarchy cmd = proc (SystemP ref tab) -> do tab' <- cmd -< (ref,tab) returnA -< SystemP ref tab' run_phase3_exprs :: Pipeline MM SystemP2 SystemP3 run_phase3_exprs = -- withHierarchy $ _ *** expressions >>> _ -- (C.id &&& expressions) >>> _ -- liftP (uncurry wrapup) proc (SystemP ref tab) -> do es <- expressions -< tab x <- liftP id -< wrapup ref tab es returnA -< SystemP ref x where err_msg :: Label -> String err_msg = [s|Multiple expressions with the label %s|] . pretty wrapup :: Hierarchy MachineId -> MMap MachineP2 -> Maybe [Map MachineId [(Label, ExprScope)]] -> MM' Input (MMap MachineP3) wrapup r_ord p2 es = do let es' :: Maybe (MMap [(Label, ExprScope)]) es' = inherit2 p2 r_ord . unionsWith (++) <$> es exprs <- triggerM =<< make_all_tables' err_msg =<< triggerM es' let _ = exprs :: MMap (Map Label ExprScope) T.sequence $ make_phase3 <$> p2 <.> exprs expressions = run_phase [ assignment , bcmeq_assgn , bcmsuch_assgn , bcmin_assgn , guard_decl , guard_removal , coarse_removal , fine_removal , fine_sch_decl , C.id &&& coarse_sch_decl >>> arr snd &&& default_schedule_decl >>> arr (\(x,y) -> M.unionWith (++) <$> x <*> y) , initialization , assumption , invariant , mch_theorem , transient_prop , transientB_prop , constraint_prop , progress_prop , safetyA_prop , safetyB_prop , remove_assgn , remove_init , init_witness_decl , witness_decl ] make_phase3 :: MachineP2 -> Map Label ExprScope -> MM' c MachineP3 make_phase3 p2 exprs' = triggerLenient $ do m <- join $ upgradeM newThy newMch <$> liftEvent toOldEvtExpr <*> liftEvent2 toNewEvtExpr toNewEvtExprDefault <*> pure p2 return m -- & pNewEvents %~ removeDefault where exprs :: [(Label, ExprScope)] exprs = M.toList exprs' liftEvent2 :: ( Label -> ExprScope -> Reader MachineP2 [Either Error (EventId, [EventP3Field])]) -> ( Label -> ExprScope -> Reader MachineP2 [Either Error (EventId, [EventP3Field])]) -> MM' c (MachineP2 -> SkipOrEvent -> EventP2 -> MM' c EventP3) liftEvent2 f g = do m <- fromListWith (++).L.map (first Right) <$> liftFieldMLenient f p2 exprs m' <- fromListWith (++).L.map (first Right) <$> liftFieldMLenient g p2 exprs let _ = m :: Map SkipOrEvent [EventP3Field] let ms = M.unionsWith (++) [m', m, M.singleton (Left SkipEvent) [ECoarseSched "default" zfalse]] return $ \_ eid e -> return $ makeEventP3 e (findWithDefault [] eid ms) liftEvent :: ( Label -> ExprScope -> Reader MachineP2 [Either Error (EventId, [EventP3Field])]) -> MM' c ( MachineP2 -> SkipOrEvent -> EventP2 -> MM' c EventP3) liftEvent f = liftEvent2 f (\_ _ -> return []) newMch :: MachineP2 -> MM' c (MachineP3' EventP2 EventP2 TheoryP2) newMch m = makeMachineP3' m <$> (makePropertySet' <$> liftFieldMLenient toOldPropSet m exprs) <*> (makePropertySet' <$> liftFieldMLenient toNewPropSet m exprs) <*> liftFieldMLenient toMchExpr m exprs newThy t = makeTheoryP3 t <$> liftFieldMLenient toThyExpr t exprs assignment :: MPipeline MachineP2 [(Label,ExprScope)] assignment = machineCmd "\\evassignment" $ \(Conc evt, NewLabel lbl, Expr xs) _m p2 -> do ev <- get_event p2 $ as_label (evt :: EventId) pred <- parse_expr'' (event_parser p2 ev & is_step .~ True) xs let frame = M.elems $ (p2^.pStateVars) `M.difference` (p2^.pAbstractVars) act = BcmSuchThat frame pred li <- ask return [(lbl,evtScope ev (Action (InhAdd (pure (ev,li),act)) Local $ pure li))] bcmeq_assgn :: MPipeline MachineP2 [(Label,ExprScope)] bcmeq_assgn = machineCmd "\\evbcmeq" $ \(Conc evt, NewLabel lbl, VarName v, Expr xs) _m p2 -> do let _ = lbl :: Label ev <- get_event p2 $ as_label (evt :: EventId) var@(Var _ t) <- bind ([s|variable '%s' undeclared|] $ render v) $ v `M.lookup` (p2^.pStateVars) li <- ask xp <- parse_expr'' (event_parser p2 ev & expected_type .~ Just t) xs _ <- check_types $ Right (Word var :: RawExpr) `mzeq` Right (asExpr xp) let act = Assign var xp return [(lbl,evtScope ev (Action (InhAdd (pure (ev,li),act)) Local $ pure li))] bcmsuch_assgn :: MPipeline MachineP2 [(Label,ExprScope)] bcmsuch_assgn = machineCmd "\\evbcmsuch" $ \(Conc evt, NewLabel lbl, vs, Expr xs) _m p2 -> do ev <- get_event p2 $ as_label (evt :: EventId) li <- ask xp <- parse_expr'' (event_parser p2 ev & is_step .~ True) xs vars <- bind_all (map getVarName vs) ([s|variable '%s' undeclared|] . render) $ (`M.lookup` (p2^.pStateVars)) let act = BcmSuchThat vars xp return [(lbl,evtScope ev (Action (InhAdd (pure (ev,li),act)) Local $ pure li))] bcmin_assgn :: MPipeline MachineP2 [(Label,ExprScope)] bcmin_assgn = machineCmd "\\evbcmin" $ \(Conc evt, NewLabel lbl, VarName v, Expr xs) _m p2 -> do ev <- get_event p2 $ as_label (evt :: EventId) var@(Var _ t) <- bind ([s|variable '%s' undeclared|] $ render v) $ v `M.lookup` (p2^.pStateVars) li <- ask xp <- parse_expr'' (event_parser p2 ev & expected_type .~ Just (set_type t) ) xs let act = BcmIn var xp _ <- check_types $ Right (Word var) `zelem` Right (asExpr xp) return [(lbl,evtScope ev (Action (InhAdd (pure (ev,li),act)) Local $ pure li))] instance IsExprScope Initially where toNewEvtExprDefault _ _ = return [] toMchExpr lbl i = do vs <- view pDelVars mid <- view pMachineId return $ case (i^.inhStatus,i^.declSource) of (InhAdd x,_) | L.null lis' -> [Right $ PInit lbl x] | otherwise -> [Left $ MLError msg $ ([s|predicate %s|] $ pretty lbl,li) :| lis'] where lis = L.map (first $ view name) $ M.elems $ vs `M.intersection` used_var' x lis' = L.map (first ([s|deleted variable %s|] . render)) lis msg = [s|In '%s', initialization predicate '%s' refers to deleted symbols|] (pretty mid) (pretty lbl) (InhDelete (Just x),Local) -> [Right $ PDelInits lbl x] (InhDelete (Just _),Inherited) -> [] (InhDelete Nothing,_) -> [Left $ Error msg li] where msg = [s|initialization predicate '%s' was deleted but does not exist|] $ pretty lbl where li = i^.lineInfo toThyExpr _ _ = return [] toNewPropSet _ _ = return [] toOldPropSet _ _ = return [] toNewEvtExpr _ _ = return [] toOldEvtExpr _ _ = return [] remove_init :: MPipeline MachineP2 [(Label,ExprScope)] remove_init = machineCmd "\\removeinit" $ \(Identity lbls) _m _p2 -> do li <- ask return [(lbl,makeCell $ Initially (InhDelete Nothing) Local li) | Abs (InitLbl lbl) <- lbls ] remove_assgn :: MPipeline MachineP2 [(Label,ExprScope)] remove_assgn = machineCmd "\\removeact" $ \(Conc evt, lbls) _m p2 -> do ev <- get_event p2 $ as_label (evt :: EventId) li <- ask return [(lbl,evtScope ev (Action (InhDelete Nothing) Local $ pure li)) | Abs (ActionLbl lbl) <- lbls ] witness_decl :: MPipeline MachineP2 [(Label,ExprScope)] witness_decl = machineCmd "\\witness" $ \(Conc evt, VarName var, Expr xp) _m p2 -> do ev <- get_event p2 $ as_label (evt :: EventId) li <- ask let disappear = (DeletedVar, ) <$> (p2^.pAbstractVars) `M.difference` (p2^.pStateVars) newIndices = (AddedIndex, ) <$> p2^.evtMergeAdded ev eIndices delParams = (DeletedParam,) <$> p2^.evtMergeDel ev eIndices (isVar,v) <- bind ([s|'%s' is not a disappearing variable or a new index|] (render var)) (var `M.lookup` (disappear `M.union` newIndices `M.union` delParams)) p <- parse_expr'' (event_parser p2 ev &~ do is_step .= True decls %= insert_symbol v ) xp return $ case isVar of DeletedVar -> [(label $ render var,evtScope ev (Witness v p Local $ pure li))] AddedIndex -> [(label $ render var,evtScope ev (IndexWitness v p Local $ pure li))] DeletedParam -> [(label $ render var,evtScope ev (ParamWitness v p Local $ pure li))] instance ZoomEq EventExpr where instance Scope EventExpr where kind (EventExpr m) = show $ ShowString . kind <$> m keep_from s (EventExpr m) = Just $ EventExpr $ M.mapMaybe (keep_from s) m make_inherited (EventExpr m) = Just $ EventExpr (M.map f m) where f x = set declSource Inherited x error_item (EventExpr m) = setToNeList $ sconcat $ NE.fromList $ map sequenceA $ elems $ mapWithKey msg m where msg (Right k) sc | inheritedFrom sc `elem` [[],[k]] = ([s|%s (event '%s')|] (kind sc) (pretty k) :: String, view lineInfo sc) | otherwise = ([s|%s (event '%s', from '%s')|] (kind sc) (pretty k) parents :: String, view lineInfo sc) where parents = intercalate "," $ map pretty $ inheritedFrom sc msg (Left _) sc = ([s|%s (initialization)|] (kind sc) :: String, view lineInfo sc) merge_scopes' (EventExpr m0) (EventExpr m1) = EventExpr <$> scopeUnion merge_scopes' m0 m1 rename_events' lookup (EventExpr es) = map EventExpr $ concatMap f $ toList es where f (Right eid,x) = [ singleton (Right e) $ setSource eid (x^.lineInfo) x | e <- lookup eid ] f (Left InitEvent,x) = [singleton (Left InitEvent) x] checkLocalExpr' :: ( HasInhStatus decl (InhStatus expr) , PrettyPrintable decl , HasLineInfo decl (NonEmptyListSet LineInfo) ) => String -> (expr -> Map Name Var) -> EventId -> Label -> decl -> Reader MachineP2 [Either Error a] checkLocalExpr' expKind free eid lbl sch = do vs <- view pDelVars is <- view $ getEvent eid.eDelIndices mid <- view $ pMachineId.to pretty return $ case sch^.inhStatus of InhAdd expr -> let msg = [s|In '%s', event '%s', %s '%s' refers to deleted symbols|] mid (pretty eid) expKind (pretty lbl) fv = symbKind "variable" fi = symbKind "index" symbKind :: (HasName s1 Name) => String -> Map k1 (s1, d1) -> Map k1 (String, d1) symbKind sym = M.map $ first $ [s|deleted %s '%s'|] sym . render . view name fvars = free expr errs = fv (vs `M.intersection` fvars) `M.union` fi (is `M.intersection` fvars) schLI = ([s|%s '%s'|] expKind $ pretty lbl,) <$> sch^.lineInfo varsLI = M.elems errs app (x :| xs) ys = x :| (xs ++ ys) in if M.null errs then [] else [Left $ MLError msg $ setToNeList schLI `app` varsLI] InhDelete Nothing -> let msg = [s|event '%s', %s '%s' was deleted but does not exist|] (pretty eid) expKind (pretty lbl) li = isOne . setToNeList $ ([s|%s '%s'|] expKind $ pretty lbl,) <$> sch^.lineInfo in [Left $ either (MLError msg) (Error msg.snd) li] _ -> [] where isOne (x:|[]) = Right x isOne (x:|xs) = Left (x:|xs) parseEvtExpr :: ( HasInhStatus decl (EventInhStatus Expr) , HasLineInfo decl (NonEmptyListSet LineInfo) , PrettyPrintable decl , HasDeclSource decl DeclSource) => String -> (Label -> Expr -> field) -> RefScope -> EventId -> Label -> decl -> Reader MachineP2 [Either Error (EventId,[field])] parseEvtExpr expKind = parseEvtExpr' expKind used_var' parseEvtExpr' :: ( HasInhStatus decl (EventInhStatus expr) , HasLineInfo decl (NonEmptyListSet LineInfo) , PrettyPrintable decl , HasDeclSource decl DeclSource) => String -> (expr -> Map Name Var) -> (Label -> expr -> field) -> RefScope -> EventId -> Label -> decl -> Reader MachineP2 [Either Error (EventId,[field])] parseEvtExpr' expKind fvars field = parseEvtExpr'' expKind fvars (const . field) parseEvtExpr'' :: ( HasInhStatus decl (EventInhStatus expr) , HasLineInfo decl (NonEmptyListSet LineInfo) , PrettyPrintable decl , HasDeclSource decl DeclSource) => String -> (expr -> Map Name Var) -> (Label -> NonEmptyListSet LineInfo -> expr -> field) -> RefScope -> EventId -> Label -> decl -> Reader MachineP2 [Either Error (EventId,[field])] parseEvtExpr'' expKind fvars field scope evt lbl decl = do (++) <$> check <*> -- (old_xs, del_xs, new_xs) case (decl^.inhStatus, decl^.declSource) of (InhAdd e, Inherited) -> return $ old e ++ new e (InhAdd e, Local) -> return $ new e (InhDelete _, Inherited) -> return [] (InhDelete (Just e), Local) -> return $ old e (InhDelete Nothing, Local) -> return [] where check = case scope of Old -> return [] New -> checkLocalExpr' expKind (fvars.snd) evt lbl decl old = case scope of Old -> \(evts,e) -> [Right (ev,[field lbl (pure li) e]) | (ev,li) <- setToList evts] New -> const [] new = case scope of Old -> const [] New -> \(_,e) -> [Right (evt,[field lbl (decl^.lineInfo) e])] instance IsEvtExpr CoarseSchedule where toMchScopeExpr _ _ = return [] defaultEvtWitness _ _ = return [] toEvtScopeExpr = parseEvtExpr "coarse schedule" ECoarseSched instance IsEvtExpr FineSchedule where toMchScopeExpr _ _ = return [] defaultEvtWitness _ _ = return [] toEvtScopeExpr = parseEvtExpr "fine schedule" EFineSched instance IsEvtExpr Guard where toMchScopeExpr _ _ = return [] defaultEvtWitness _ _ = return [] toEvtScopeExpr = parseEvtExpr "guard" EGuards guard_decl :: MPipeline MachineP2 [(Label,ExprScope)] guard_decl = machineCmd "\\evguard" $ \(Conc evt, NewLabel lbl, Expr xs) _m p2 -> do ev <- get_event p2 $ as_label (evt :: EventId) li <- ask xp <- parse_expr'' (event_parser p2 ev) xs return [(lbl,evtScope ev (Guard (InhAdd (pure (ev,li),xp)) Local $ pure li))] guard_removal :: MPipeline MachineP2 [(Label,ExprScope)] guard_removal = machineCmd "\\removeguard" $ \(Conc evt_lbl,lbls) _m p2 -> do ev <- get_event p2 $ as_label (evt_lbl :: EventId) li <- ask return [(lbl,evtScope ev (Guard (InhDelete Nothing) Local $ pure li)) | Abs (GuardLbl lbl) <- lbls ] coarse_removal :: MPipeline MachineP2 [(Label,ExprScope)] coarse_removal = machineCmd "\\removecoarse" $ \(Conc evt_lbl, lbls) _m p2 -> do ev <- get_event p2 $ as_label (evt_lbl :: EventId) li <- ask return [(lbl,evtScope ev (CoarseSchedule (InhDelete Nothing) Local $ pure li)) | Abs (CoarseSchLbl lbl) <- lbls ] fine_removal :: MPipeline MachineP2 [(Label,ExprScope)] fine_removal = machineCmd "\\removefine" $ \(Conc evt_lbl,lbls) _m p2 -> do ev <- get_event p2 $ as_label (evt_lbl :: EventId) li <- ask return [(lbl,evtScope ev (FineSchedule (InhDelete Nothing) Local $ pure li)) | Abs (FineSchLbl lbl) <- lbls ] coarse_sch_decl :: MPipeline MachineP2 [(Label,ExprScope)] coarse_sch_decl = machineCmd "\\cschedule" $ \(Conc evt, NewLabel lbl, Expr xs) _m p2 -> do ev <- get_event p2 $ as_label (evt :: EventId) li <- ask xp <- parse_expr'' (schedule_parser p2 ev) xs return [(lbl,evtScope ev (CoarseSchedule (InhAdd (pure (ev,li),xp)) Local $ pure li))] fine_sch_decl :: MPipeline MachineP2 [(Label,ExprScope)] fine_sch_decl = machineCmd "\\fschedule" $ \(Conc evt, NewLabel lbl, Expr xs) _m p2 -> do ev <- get_event p2 $ as_label (evt :: EventId) li <- ask xp <- parse_expr'' (schedule_parser p2 ev) xs return [(lbl,evtScope ev (FineSchedule (InhAdd (pure (ev,li),xp)) Local $ pure li))] ------------------------- -- Theory Properties -- ------------------------- parseExpr' :: (HasMchExpr b a, Ord label) => Lens' MachineP3 (Map label a) -> [(label,b)] -> RWS () [Error] MachineP3 () parseExpr' ln xs = modify $ ln %~ M.union (M.fromList $ map (second $ view mchExpr) xs) instance IsExprScope Axiom where toNewEvtExprDefault _ _ = return [] toMchExpr _ _ = return [] toThyExpr lbl x = return [Right $ PAssumptions lbl $ x^.mchExpr] toNewPropSet _ _ = return [] toOldPropSet _ _ = return [] toNewEvtExpr _ _ = return [] toOldEvtExpr _ _ = return [] assumption :: MPipeline MachineP2 [(Label,ExprScope)] assumption = machineCmd "\\assumption" $ \(NewLabel lbl,Expr xs) _m p2 -> do li <- ask xp <- parse_expr'' (p2^.pCtxSynt) xs return [(lbl,makeCell $ Axiom xp Local li)] -------------------------- -- Program properties -- -------------------------- initialization :: MPipeline MachineP2 [(Label,ExprScope)] initialization = machineCmd "\\initialization" $ \(NewLabel lbl,Expr xs) _m p2 -> do li <- ask xp <- parse_expr'' (p2^.pMchSynt) xs return [(lbl,makeCell $ Initially (InhAdd xp) Local li)] makeEvtCell :: IsEvtExpr a => InitOrEvent -> a -> ExprScope makeEvtCell evt exp = makeCell $ EventExpr $ singleton evt $ makeCell exp default_schedule_decl :: Pipeline MM (MMap MachineP2, Maybe (MMap [(Label, ExprScope)])) (Maybe (MMap [(Label, ExprScope)])) default_schedule_decl = arr $ \(p2,csch) -> Just $ addDefSch <$> p2 <.> evtsWith csch -- .traverse._CoarseSchedule._) where --asCell' = asCell :: Prism' ExprScope EventExpr addDefSch m evts = m^.pNewEvents.eEventId._Right.to (default_sch evts) evtsWith :: Maybe (Map MachineId [(Label, ExprScope)]) -> Map MachineId [(EventId, LineInfo)] evtsWith csch = csch^.traverse & traverse %~ rights.(traverse %~ _1 id).referencedEvents referencedEvents :: [(Label, ExprScope)] -> [(InitOrEvent,LineInfo)] referencedEvents m = m^.traverse._2._EventExpr'.withKey'.traverse.to (\(eid,s) -> (eid,) <$> s^.lineInfo.to setToList) -- _1.to (:[]) li = LI "default" 1 1 makeDelete (InhAdd x) = InhDelete (Just x) makeDelete (InhDelete x) = InhDelete x default_sch :: [(EventId, LineInfo)] -> EventId -> [(Label, ExprScope)] default_sch evts e = case e `L.lookup` evts of Just _li -> map ((def,) . makeEvtCell (Right e)) [sch,sch'] Nothing -> map ((def,) . makeEvtCell (Right e)) [sch] where def = label "default" sch = CoarseSchedule (InhAdd (pure (e,li),zfalse)) Inherited $ pure li sch' = sch & inhStatus %~ makeDelete & declSource .~ Local instance IsExprScope Invariant where toNewEvtExprDefault _ _ = return [] toMchExpr lbl e = return [Right $ PInvariant lbl $ e^.mchExpr] toThyExpr _ _ = return [] toNewPropSet lbl x = return $ if x^.declSource == Local then [Right $ Inv lbl $ x^.mchExpr] else [] toOldPropSet lbl x = return $ if x^.declSource == Inherited then [Right $ Inv lbl $ x^.mchExpr] else [] toNewEvtExpr _ _ = return [] toOldEvtExpr _ _ = return [] invariant :: MPipeline MachineP2 [(Label,ExprScope)] invariant = machineCmd "\\invariant" $ \(NewLabel lbl,Expr xs) _m p2 -> do li <- ask xp <- parse_expr'' (p2^.pMchSynt) xs return [(lbl,makeCell $ Invariant xp Local li)] instance IsExprScope InvTheorem where toNewEvtExprDefault _ _ = return [] toMchExpr lbl e = return [Right $ PInvariant lbl $ e^.mchExpr] toThyExpr _ _ = return [] toNewPropSet lbl x = return $ if x^.declSource == Local then [Right $ Inv_thm lbl $ x^.mchExpr] else [] toOldPropSet lbl x = return $ if x^.declSource == Inherited then [Right $ Inv_thm lbl $ x^.mchExpr] else [] toNewEvtExpr _ _ = return [] toOldEvtExpr _ _ = return [] mch_theorem :: MPipeline MachineP2 [(Label,ExprScope)] mch_theorem = machineCmd "\\theorem" $ \(NewLabel lbl,Expr xs) _m p2 -> do li <- ask xp <- parse_expr'' (p2^.pMchSynt) xs return [(lbl,makeCell $ InvTheorem xp Local li)] instance IsExprScope TransientProp where toNewEvtExprDefault _ _ = return [] toMchExpr lbl e = return [Right $ PTransient lbl $ e^.mchExpr] toThyExpr _ _ = return [] toNewPropSet lbl x = return $ if x^.declSource == Local then [Right $ Transient lbl $ x^.mchExpr] else [] toOldPropSet lbl x = return $ if x^.declSource == Inherited then [Right $ Transient lbl $ x^.mchExpr] else [] toNewEvtExpr _ _ = return [] toOldEvtExpr _ _ = return [] transient_prop :: MPipeline MachineP2 [(Label,ExprScope)] transient_prop = machineCmd "\\transient" $ \(evts', NewLabel lbl, Expr xs) _m p2 -> do let evts = map (as_label.getConcrete) evts' _ = evts' :: [Conc EventId] es <- get_events p2 =<< bind "Expecting at least one event" (NE.nonEmpty evts) li <- ask tr <- parse_expr'' (p2^.pMchSynt & free_dummies .~ True) xs let withInd = L.filter (not . M.null . (^. eIndices) . ((p2 ^. pEvents) !)) (NE.toList es) toEither $ error_list [ ( not $ L.null withInd , [s|event(s) %s have indices and require witnesses|] $ intercalate "," $ map pretty withInd) ] let vs = used_var' tr fv = vs `M.intersection` (p2^.pDummyVars) prop = Tr fv tr es empty_hint return [(lbl,makeCell $ TransientProp prop Local li)] transientB_prop :: MPipeline MachineP2 [(Label,ExprScope)] transientB_prop = machineCmd "\\transientB" $ \(evts', NewLabel lbl, PlainText hint, Expr xs) _m p2 -> do let evts = map (as_label.getConcrete) evts' _ = evts' :: [Conc EventId] es <- get_events p2 =<< bind "Expecting at least one event" (NE.nonEmpty evts) li <- ask tr <- parse_expr'' (p2^.pMchSynt & free_dummies .~ True) xs let fv = free_vars' ds tr ds = p2^.pDummyVars evts' <- bind "Expecting non-empty list of events" $ NE.nonEmpty evts hint <- tr_hint p2 fv evts' hint let prop = transientProp p2 tr es hint return [(lbl,makeCell $ TransientProp prop Local li)] instance IsExprScope ConstraintProp where toNewEvtExprDefault _ _ = return [] toMchExpr _ _ = return [] toThyExpr _ _ = return [] toNewPropSet lbl x = return $ if x^.declSource == Local then [Right $ Constraint lbl $ x^.mchExpr] else [] toOldPropSet lbl x = return $ if x^.declSource == Inherited then [Right $ Constraint lbl $ x^.mchExpr] else [] toNewEvtExpr _ _ = return [] toOldEvtExpr _ _ = return [] constraint_prop :: MPipeline MachineP2 [(Label,ExprScope)] constraint_prop = machineCmd "\\constraint" $ \(NewLabel lbl,Expr xs) _m p2 -> do li <- ask pre <- parse_expr'' (p2^.pMchSynt & free_dummies .~ True & is_step .~ True) xs let vars = elems $ free_vars' ds pre ds = p2^.pDummyVars prop = Co vars pre return [(lbl,makeCell $ ConstraintProp prop Local li)] instance IsExprScope SafetyDecl where toNewEvtExprDefault _ _ = return [] toMchExpr lbl e = return [Right $ PSafety lbl $ e^.mchExpr] toThyExpr _ _ = return [] toNewPropSet lbl x = return $ if x^.declSource == Local then [Right $ Safety lbl $ x^.mchExpr] else [] toOldPropSet lbl x = return $ if x^.declSource == Inherited then [Right $ Safety lbl $ x^.mchExpr] else [] toNewEvtExpr _ _ = return [] toOldEvtExpr _ _ = return [] safety_prop :: Label -> StringLi -> StringLi -> MachineId -> MachineP2 -> M [(Label,ExprScope)] safety_prop lbl pCt qCt _m p2 = do li <- ask p <- unfail $ parse_expr'' (p2^.pMchSynt & free_dummies .~ True) pCt q <- unfail $ parse_expr'' (p2^.pMchSynt & free_dummies .~ True) qCt p <- trigger p q <- trigger q let new_prop = unlessProp p2 p q return [(lbl,makeCell $ SafetyProp new_prop Local li)] safetyA_prop :: MPipeline MachineP2 [(Label,ExprScope)] safetyA_prop = machineCmd "\\safety" $ \(NewLabel lbl, Expr pCt, Expr qCt) -> safety_prop lbl pCt qCt safetyB_prop :: MPipeline MachineP2 [(Label,ExprScope)] safetyB_prop = machineCmd "\\safetyB" $ \(NewLabel lbl, evt, Expr pCt, Expr qCt) _ _ -> do let _ = safety_prop lbl pCt qCt _ = evt :: Abs EventId bind "OBSOLETE FEATURE: p UNLESS q EXCEPT evt is no longer supported" Nothing instance IsExprScope ProgressDecl where toNewEvtExprDefault _ _ = return [] toMchExpr lbl e = return [Right $ PProgress (PId lbl) $ e^.mchExpr] toThyExpr _ _ = return [] toNewPropSet lbl x = return $ if x^.declSource == Local then [Right $ Progress (PId lbl) $ x^.mchExpr] else [] toOldPropSet lbl x = return $ if x^.declSource == Inherited then [Right $ Progress (PId lbl) $ x^.mchExpr] else [] toNewEvtExpr _ _ = return [] toOldEvtExpr _ _ = return [] transientProp :: (HasTheoryP2 p,HasExpr expr) => p -> expr -> NonEmpty EventId -> TrHint' expr -> Transient' expr transientProp p2 p = Tr dum p where ds = p2^.pDummyVars dum = free_vars' ds p unlessProp :: (HasTheoryP2 p,HasExpr expr) => p -> expr -> expr -> SafetyProp' expr unlessProp p2 p q = Unless (M.elems dum) p q where ds = p2^.pDummyVars dum = free_vars' ds p `union` free_vars' ds q leadsTo :: (HasTheoryP2 p,HasExpr expr) => p -> expr -> expr -> ProgressProp' expr leadsTo p2 p q = LeadsTo (M.elems dum) p q where ds = p2^.pDummyVars dum = free_vars' ds p `union` free_vars' ds q progress_prop :: MPipeline MachineP2 [(Label,ExprScope)] progress_prop = machineCmd "\\progress" $ \(NewLabel lbl, Expr pCt, Expr qCt) _m p2 -> do li <- ask p <- unfail $ parse_expr'' (p2^.pMchSynt & free_dummies .~ True) pCt q <- unfail $ parse_expr'' (p2^.pMchSynt & free_dummies .~ True) qCt p <- trigger p q <- trigger q let new_prop = leadsTo p2 p q return [(lbl,makeCell $ ProgressProp new_prop Local li)] instance IsEvtExpr IndexWitness where defaultEvtWitness _ _ = return [] toMchScopeExpr _ _ = return [] toEvtScopeExpr Old evt _ w | w^.declSource == Local = return [Right (evt,[EIndWitness (v^.name) (WitSuch v $ w^.evtExpr)])] | otherwise = return [] where v = w^.ES.var toEvtScopeExpr New _ _ _ = return [] setSource _ _ x = x inheritedFrom _ = [] instance IsEvtExpr ParamWitness where defaultEvtWitness _ _ = return [] toMchScopeExpr _ _ = return [] toEvtScopeExpr New evt _ w | w^.declSource == Local = return [Right (evt,[EParamWitness (v^.name) (WitSuch v $ w^.evtExpr)])] | otherwise = return [] where v = w^.ES.var toEvtScopeExpr Old _ _ _ = return [] setSource _ _ x = x inheritedFrom _ = [] instance IsEvtExpr ES.Witness where defaultEvtWitness _ _ = return [] toMchScopeExpr _ w | w^.declSource == Local = return [Right $ PInitWitness (v^.name) (WitSuch v $ w^.evtExpr)] | otherwise = return [] where v = w^.ES.var toEvtScopeExpr Old _ _ _ = return [] toEvtScopeExpr New evt _ w | w^.declSource == Local = return [Right (evt,[EWitness (v^.name) (WitSuch v $ w^.evtExpr)])] | otherwise = return [] where v = w^.ES.var setSource _ _ x = x inheritedFrom _ = [] instance IsEvtExpr ActionDecl where defaultEvtWitness ev scope = case (scope^.inhStatus, scope^.declSource) of (InhDelete (Just (_,act)),Local) -> do vs <- view pDelVars return [Right $ (ev,[EWitness (v^.name) (witnessOf v act) | v <- M.elems $ frame' act `M.intersection` vs ])] _ -> return [] toMchScopeExpr _ _ = return [] toEvtScopeExpr scope eid lbl decl = do x <- parseEvtExpr'' "action" (uncurry M.union . (frame' &&& used_var'.ba_pred)) (curry . lmap (_1 %~ setToNeList) . EActions) scope eid lbl decl return x newtype Compose3 f g h a = Compose3 { getCompose3 :: f (g (h a)) } deriving (Functor) instance (Applicative f,Applicative g,Applicative h) => Applicative (Compose3 f g h) where pure = Compose3 . pure.pure.pure Compose3 f <*> Compose3 x = Compose3 $ uncomp $ comp f <*> comp x where comp = Compose . Compose uncomp = getCompose . getCompose _EventExpr' :: Prism' ExprScope (Map InitOrEvent EvtExprScope) _EventExpr' = _ExprScope._Cell._EventExpr instance IsExprScope EventExpr where toNewEvtExprDefault _ (EventExpr m) = fmap (concat.M.elems) $ M.traverseWithKey defaultEvtWitness $ M.mapKeysMonotonic fromRight' $ M.filterWithKey (const.isRight) m toMchExpr lbl (EventExpr m) = fmap concat $ mapM (toMchScopeExpr lbl) $ M.elems $ M.filterWithKey (const.isLeft) m toThyExpr _ _ = return [] toNewPropSet _ _ = return [] toOldPropSet _ _ = return [] toNewEvtExpr lbl (EventExpr m) = fmap concat $ mapM g $ rights $ map f $ M.toList m where f (x,y) = (,y) <$> x g (x,y) = toEvtScopeExpr New x lbl y toOldEvtExpr lbl (EventExpr m) = do concat <$> mapM fields (rights $ map f $ M.toList m) where f (x,y) = (,y) <$> x fields :: (EventId, EvtExprScope) -> Reader MachineP2 [Either Error (EventId, [EventP3Field])] fields (x,y) = toEvtScopeExpr Old x lbl y init_witness_decl :: MPipeline MachineP2 [(Label,ExprScope)] init_witness_decl = machineCmd "\\initwitness" $ \(VarName var, Expr xp) _m p2 -> do -- ev <- get_event p2 evt li <- ask p <- parse_expr'' (p2^.pMchSynt) xp v <- bind ([s|'%s' is not a disappearing variable|] $ render var) (var `M.lookup` (L.view pAbstractVars p2 `M.difference` L.view pStateVars p2)) return [(label $ render var, makeEvtCell (Left InitEvent) (Witness v p Local $ pure li))] event_parser :: HasMachineP2 phase => phase -> EventId -> ParserSetting event_parser p2 ev = (p2 ^. pEvtSynt) ! ev schedule_parser :: HasMachineP2 phase => phase -> EventId -> ParserSetting schedule_parser p2 ev = (p2 ^. pSchSynt) ! ev machine_events :: HasMachineP1 phase => phase -> Map Label EventId machine_events p2 = L.view pEventIds p2 evtScope :: IsEvtExpr a => EventId -> a -> ExprScope evtScope ev x = makeCell $ EventExpr $ M.singleton (Right ev) (makeCell x) addEvtExpr :: IsEvtExpr a => W.WriterT [(UntypedExpr,[String])] M (EventId,[(UntypedExpr,[String])] -> a) -> M ExprScope addEvtExpr m = do ((ev,f),w) <- W.runWriterT m return $ evtScope ev (f w) check_types :: Either [String] a -> M a check_types c = do li <- ask hoistEither $ either (\xs -> Left $ map (`Error` li) xs) Right c defaultInitWitness :: MachineP2 -> [MachineP3'Field a b c] -> [MachineP3'Field a b c] defaultInitWitness p2 xs = concatMap f xs ++ xs where vs = p2^.pDelVars f (PDelInits _lbl expr) = [PInitWitness (v^.name) (WitSuch v expr) | v <- M.elems $ used_var' expr `M.intersection` vs ] f _ = [] return [] check_props :: (PropName -> Property -> IO (a, Result)) -> IO ([a], Bool) check_props = $forAllProperties' instance Arbitrary ExprScope where arbitrary = ExprScope <$> $(arbitraryCell' ''IsExprScope [ [t| ExprScope |] ]) instance Arbitrary EvtExprScope where arbitrary = do s <- $(arbitraryCell' ''IsEvtExpr [ [t| EvtExprScope |] ]) return $ EvtExprScope s instance Arbitrary EventExpr where arbitrary = EventExpr . fromList <$> listOf1 arbitrary
literate-unitb/literate-unitb
src/Document/Phase/Expressions.hs
mit
37,497
6
20
12,643
12,828
6,581
6,247
-1
-1
module Main where import Data.List (find) main :: IO () main = print $ find productOfThreeDigits palindromes palindrome :: Int -> Int -> Int -> Int palindrome x y z = 100000 * x + 10000 * y + 1000 * z + 100 * z + 10 * y + x palindromes :: [Int] palindromes = [palindrome x y z | x <- [9,8..1], y <- [9,8..0], z <- [9,8..0]] productOfThreeDigits :: Int -> Bool productOfThreeDigits x = any (\(n, m) -> n * m == x) [(n, m) | n <- [999,998..100], m <- [999,998..100]]
jBugman/euler
part1/p004.hs
mit
470
0
14
102
263
144
119
10
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Network.MessagePack import Network.Simple.TCP import qualified Data.Map as M -- | Echo server main :: IO () main = withSocketsDo $ runRPC methods HostAny "3000" where methods = M.singleton "echo" echo echo = return . Right
rodrigosetti/messagepack-rpc
tests/Main.hs
mit
300
0
8
60
74
43
31
10
1
{-| Module : Datatypes Description : Helper module to get data types and functions on them. License : CC0 Maintainer : [email protected] Stability : experimental -} module System.KSP.Datatypes ( Object(..) , Celestial(..) , Body(..) , Orbit(..) , System(..) , GravConst , KSystem , getNextUp , getPathUp , getDivid , sOrbitInSystem , pathOBetween , pathBetween_ , pathBetween' , speeds ) where import System.KSP.DataConstructors import System.KSP.DataDestructors
frosch03/kerbal
src/System/KSP/Datatypes.hs
cc0-1.0
544
0
5
142
87
60
27
18
0
module Logic.AbstractLogic where import Notes import Functions.Application.Macro import Logic.FirstOrderLogic.Macro import Logic.PropositionalLogic.Macro import Logic.AbstractLogic.Macro import Logic.AbstractLogic.Terms abstractLogic :: Note abstractLogic = section "Abstract Logic" $ do s ["It is hard to speak about logic in a pure mathematical fashion as it originated, and still borders on, philosophy"] formulaDefinition theoryDefinition axiomSchemaDefinition theoremNotation knowledgeBaseDefinition entailmentDefinition inferenceDefinition inferenceNotation soundDefinition completeDefinition exampleTheoryIntegers exampleModusPonens formulaDefinition :: Note formulaDefinition = do de $ s ["A ", formula', " is a string of characters"] nte $ s ["In fact a formula can be equivalently be defined in other ways but this definition suffices"] theoryDefinition :: Note theoryDefinition = do de $ do lab theoryDefinitionLabel lab logicDefinitionLabel lab axiomDefinitionLabel lab grammarDefinitionLabel lab semanticsDefinitionLabel lab sentenceDefinitionLabel s ["A ", theory', or, logic', " is a mathematical framework for proving properties about a certain object domain"] s ["Those properties are called ", theorems'] s ["A ", theory, " consists of a ", grammar', ", a set of ", axioms', and , semantics', " for formulae"] enumerate $ do item $ do s ["A ", grammar', " defines well-formed formulae"] s ["A well-formed ", formula, " is also called a ", sentence'] s ["A ", formula', " represents an expression if it adheres to the ", grammar] item $ do s ["An ", axiom', " is a ", theorem, " that can be asserted without ", inference] item $ do s ["Semantics dictate the ", emph "meaning", " of formulae in the ", logic] nte $ do s ["Theorems are obtained from the axioms by a finite amount of applications of the inference rules"] theoremNotation :: Note theoremNotation = de $ do lab theoremDefinitionLabel s ["A ", theorem' , " ", m logicf, " is a well-formed formula that is provable in a ", theory, " ", m logict] s ["This is denoted as ", m (la logicf)] knowledgeBaseDefinition :: Note knowledgeBaseDefinition = de $ do lab knowledgeBaseDefinitionLabel s ["A ", knowledgeBase', " is a set of formulae"] s ["A ", knowledgeBase, " is called valid if all its formula are theorems in the given ", theory] entailmentDefinition :: Note entailmentDefinition = de $ do lab entailsDefinitionLabel s ["Let ", m logict , " be a ", theory, and, m lkb, " a ", knowledgeBase] s ["We say that a ", knowledgeBase, " ", m lkb, " ", entails', " a formula ", m alpha, " if ", m alpha, " is ", true, " for all valid ", knowledgeBase, "s ", m lkb] ma $ lkb `lent` alpha inferenceDefinition :: Note inferenceDefinition = de $ do lab inferenceDefinitionLabel s ["An ", inference', " ", m logicir, " in a theory ", m logict, " is a procedure for proving sentences from a ", knowledgeBase] s ["If a theorem ", m logict, " can be proven using ", m logicir, " we denote this as ", m (lpvm logicir "" logicf)] inferenceNotation :: Note inferenceNotation = de $ do s ["An inference rule is written as follows"] s ["It means that if theorems ", m (commaSeparated fs), " can be asserted, we may assert ", m (f 0), " as a theorem"] ma $ linf fs (f 0) s ["The sentences above the line are called the ", defineTerm "hypotheses", or, "antecedents", and, "the sentence below the line is called the ", defineTerm "conclusion"] where fs = [f 1, f 2, dotsc, f "n"] f n = logicf !: n soundDefinition :: Note soundDefinition = de $ do lab soundDefinitionLabel s ["An ", inference, " ", m "i", " is called ", sound', " if every ", theorem, " produced by ", m "i", " is a true ", formula] ma $ fa (commaSeparated [alpha, lkb]) (lpvm "i" lkb alpha ⇒ lkb `lent` alpha) completeDefinition :: Note completeDefinition = de $ do s ["An ", inference, " ", m "i", " is called ", complete', " if every true ", formula, " can be established as a theorem by ", m "i"] ma $ fa (commaSeparated [alpha, lkb]) (lkb `lent` alpha ⇒ lpvm "i" lkb alpha) exampleModusPonens :: Note exampleModusPonens = de $ do lab modusPonensDefinitionLabel s ["The ", modusPonens', " ", inference, " rule is common to many theories"] ma $ linf ["p", "p" ⇒ "q"] "q" axiomSchemaDefinition :: Note axiomSchemaDefinition = de $ s ["An axiom schema defines multiple (possibly even infinitely many) axioms via the use of a variable"] exampleTheoryIntegers :: Note exampleTheoryIntegers = ex $ do s ["Let ", m (mathbb "I"), " be a theory with a ", grammar , " ", m g, " a set ", m i, " of inference rules and a set ", m a , " of axioms"] enumerate $ do item $ do m g " defines a formula to be well-formed if it is of the following form: " itemize $ do item $ do quoted $ m (i1 `eq` i2) s [" where ", m (i1), " and ", m (i2), " are integer expressions"] item $ do quoted $ m (i1 `lt` i2) s [" where ", m (i1), " and ", m (i2), " are integer expressions"] item $ do quoted $ m ((¬) b) s [" where ", m b, " is a boolean expression"] item $ do quoted $ m (b1 ⇒ b2) s [" where ", m b1, " and ", m b2, " are boolean expressions"] s ["An ", quoted "integer expression", " is an expression of one the following forms"] itemize $ do item $ m 0 item $ "A variable " <> m "n" item $ s [m (su "n"), " Where ", m "n", " is an integer expression"] item $ do "The axioms are " m (la $ 0 <: su 0) " and the axioms defined by the following axiom schema:" ma $ la $ "f" <: "g" ⇒ su "f" <: su "g" "In this example theory, the following could be a sound, but not complete, inference rule:" ma $ linf [su 0, fa "f" (p "f" ⇒ p (su "f"))] (fa "f" $ p "f") "This rule is called " defineTerm "induction" "." where p = fn "P" su = fn "S" i1 = "i" !: 1 i2 = "i" !: 2 b = "b" b1 = b !: 1 b2 = b !: 2 g = ("G" !: mathbb "I") i = ("I" !: mathbb "I") a = ("A" !: mathbb "I")
NorfairKing/the-notes
src/Logic/AbstractLogic.hs
gpl-2.0
6,700
6
23
1,986
1,850
951
899
139
1
import Test.QuickCheck myLast :: [a] -> Maybe a myLast [] = Nothing myLast xs = Just $ reverse xs !! 0 testMyLast :: [Int] -> Bool testMyLast xs = case myLast xs of Nothing -> null xs Just x -> last xs == x main = quickCheck testMyLast
CmdrMoozy/haskell99
001.hs
gpl-3.0
244
2
9
56
112
55
57
10
2
{-# LANGUAGE ForeignFunctionInterface #-} module HelloWorld where import Foreign.C.Types import Foreign.C.String foreign export ccall hello :: CString -> IO CInt hello :: CString -> IO CInt hello c_str = do str <- peekCString c_str result <- hsHello str return $ fromIntegral result hsHello :: String -> IO Int hsHello str = do putStrLn $ "Hello, " ++ str return (length str)
KenetJervet/mapensee
haskell/ffi/DotNet/HelloWorld/HelloWorld.hs
gpl-3.0
393
0
9
78
127
63
64
15
1
{-# LANGUAGE TypeFamilies, UndecidableInstances #-} module Data.VectorSpace.QuickCheck where import Data.VectorSpace import Test.QuickCheck import Control.Monad (liftM) import Foreign.Storable import System.Random (Random) -- | Normalized vector newtype NormalizedV a = NormalizedV a deriving (Show, Eq) instance (s ~ Scalar v, Num v, Ord v, Floating s, InnerSpace v, Arbitrary v) => Arbitrary (NormalizedV v) where arbitrary = do NonZero a <- arbitrary return $ NormalizedV $ normalized a -- | Number in [0,1] newtype Normalized a = Normalized a deriving (Show, Eq) instance (Random a, Num a) => Arbitrary (Normalized a) where arbitrary = choose (0,1) >>= (return . Normalized) newtype Parallel a = Parallel (a, a) deriving (Show, Eq) instance (s ~ Scalar v, Floating s, InnerSpace v, Arbitrary v) => Arbitrary (Parallel v) where arbitrary = do a <- arbitrary b <- arbitrary return $ Parallel (a, project b a)
bgamari/GGen
Data/VectorSpace/QuickCheck.hs
gpl-3.0
1,081
0
11
310
338
182
156
22
0
module GUI.InfoConsole ( configInfoConsoleTV , printInfoMsg , printErrorMsg) where import Graphics.UI.Gtk hiding (get) import GUI.Utils import GUI.GState import qualified GUI.Console as Console import Control.Lens import Control.Monad.Trans.RWS configInfoConsoleTV :: TextView -> TextBuffer -> IO () configInfoConsoleTV = Console.configConsoleTV printInfoMsg :: String -> GuiMonad () printInfoMsg msg = ask >>= \content -> let infoBuf = content ^. (gFunInfoConsole . infoConTBuffer) in let infoTV = content ^. (gFunInfoConsole . infoConTView) in io $ Console.printInfoMsg msg infoBuf infoTV printErrorMsg :: String -> GuiMonad () printErrorMsg msg = ask >>= \content -> let infoBuf = content ^. (gFunInfoConsole . infoConTBuffer) in let infoTV = content ^. (gFunInfoConsole . infoConTView) in io $ Console.printErrorMsg msg infoBuf infoTV
alexgadea/fun-gui
GUI/InfoConsole.hs
gpl-3.0
1,008
0
15
280
260
140
120
21
1
{-# LANGUAGE UnicodeSyntax, NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ConstraintKinds #-} module KlcParse ( parseKlcLayout ) where import BasePrelude hiding (try) import Prelude.Unicode import Data.Monoid.Unicode ((∅), (⊕)) import Util (parseString, (>$>), lookupR, tellMaybeT) import Control.Monad.Trans (lift) import Control.Monad.Trans.Maybe (MaybeT(..)) import Control.Monad.Writer (runWriterT, writer, tell) import qualified Data.Text.Lazy as L (Text) import Lens.Micro.Platform (ASetter, view, set, over, makeLenses, ix, _1) import Text.Megaparsec hiding (Pos, many, some) import Text.Megaparsec.Char import Layout.Key (Key(..), baseCharToChar) import Layout.Layout (Layout(..)) import Layout.Types import Lookup.Windows import WithBar (WithBar(..)) type Parser = MonadParsec Void L.Text data KlcParseLayout = KlcParseLayout { __parseInformation ∷ Information , __parseShiftstates ∷ [Shiftstate] , __parseKeys ∷ [Key] , __parseLigatures ∷ [(Pos, Int, String)] , __parseDeadKeys ∷ [(Char, ActionMap)] } makeLenses ''KlcParseLayout instance Semigroup KlcParseLayout where KlcParseLayout a1 a2 a3 a4 a5 <> KlcParseLayout b1 b2 b3 b4 b5 = KlcParseLayout (a1 ⊕ b1) (a2 ⊕ b2) (a3 ⊕ b3) (a4 ⊕ b4) (a5 ⊕ b5) instance Monoid KlcParseLayout where mempty = KlcParseLayout (∅) (∅) (∅) (∅) (∅) mappend = (<>) layout ∷ (Logger m, Parser m, MonadFail m) ⇒ m Layout layout = do KlcParseLayout info states keys ligs deads ← klcLayout ($ keys) $ map (set _shiftlevels (map (WithBar ∘ (:| [])) states)) >>> Layout info (∅) (∅) (∅) >>> setDeads deads >$> setLigatures ligs setDeads ∷ Logger m ⇒ [(Char, ActionMap)] → Layout → m Layout setDeads = _keys ∘ traverse ∘ _letters ∘ traverse ∘ setDeadKey setDeadKey ∷ Logger m ⇒ [(Char, ActionMap)] → Letter → m Letter setDeadKey deads dead@(CustomDead i d) = case find ((≡) (__baseChar d) ∘ BaseChar ∘ fst) deads of Just (_, m) → pure (CustomDead i d { __actionMap = m }) Nothing → dead <$ tell ["dead key ‘" ⊕ c ⊕ "’ is not defined"] where c = maybe "unknown" (:[]) (baseCharToChar (__baseChar d)) setDeadKey _ l = pure l setLigatures ∷ [(Pos, Int, String)] → Layout → Layout setLigatures = over (_keys ∘ traverse) ∘ setLigatures' setLigatures' ∷ [(Pos, Int, String)] → Key → Key setLigatures' xs key = foldr setLigature key ligs where ligs = filter ((≡) (view _pos key) ∘ view _1) xs setLigature (_, i, s) = set (_letters ∘ ix i) (Ligature Nothing s) klcLayout ∷ (Logger m, Parser m, MonadFail m) ⇒ m KlcParseLayout klcLayout = many >$> mconcat $ set' _parseInformation <$> try kbdField <|> set' _parseShiftstates <$> try shiftstates <|> set' _parseKeys <$> klcKeys <|> set' _parseLigatures <$> try ligatures <|> set' _parseDeadKeys <$> try deadKey <|> (∅) <$ try descriptions <|> (∅) <$ try languageNames <|> (∅) <$ try keyName <|> (∅) <$ try endKbd <|> (try nameValue >>= (uncurry field >$> set' _parseInformation)) <|> (readLine >>= \xs → (∅) <$ tell ["uknown line ‘" ⊕ show xs ⊕ "’"]) where set' ∷ Monoid α ⇒ ASetter α α' β β' → β' → α' set' f = flip (set f) (∅) field ∷ Logger m ⇒ String → String → m Information field "COPYRIGHT" = pure ∘ set' _copyright ∘ Just field "COMPANY" = pure ∘ set' _company ∘ Just field "LOCALENAME" = const (pure (∅)) field "LOCALEID" = pure ∘ set' _localeId ∘ Just field "VERSION" = pure ∘ set' _version ∘ Just field f = const $ (∅) <$ tell ["unknown field ‘" ⊕ f ⊕ "’"] kbdField ∷ (Parser m, MonadFail m) ⇒ m Information kbdField = do ["KBD", l1, l2] ← readLine pure ∘ set _name l1 ∘ set _fullName l2 $ (∅) shiftstates ∷ (Parser m, MonadFail m) ⇒ m [Shiftstate] shiftstates = do ["SHIFTSTATE"] ← readLine map shiftstateFromWinShiftstate <$> many (try shiftstate) shiftstate ∷ (Parser m, MonadFail m) ⇒ m Int shiftstate = do [i] ← readLine maybe (fail $ "‘" ⊕ show i ⊕ "’ is not an integer") pure (readMaybe i) klcKeys ∷ (Logger m, Parser m) ⇒ m [Key] klcKeys = do try $ spacing *> string "LAYOUT" *> endLine *> pure () catMaybes <$> many (isHex *> klcKey) klcKey ∷ (Logger m, Parser m) ⇒ m (Maybe Key) klcKey = runMaybeT $ do sc:vk:caps:letters ← lift readLine Key <$> parseScancode sc <*> (Just <$> parseShortcutPos vk) <*> pure [] <*> traverse parseLetter letters <*> (Just <$> parseCapslock caps) parseScancode ∷ Logger m ⇒ String → MaybeT m Pos parseScancode xs = maybe e pure (readMaybe ('0':'x':xs) >>= (`lookupR` posAndScancode)) where e = tellMaybeT ["unknown position ‘" ⊕ xs ⊕ "’"] parseShortcutPos ∷ Logger m ⇒ String → MaybeT m Pos parseShortcutPos xs = maybe e pure (lookupR xs posAndVkString <|> parseString xs) where e = tellMaybeT ["unknown position ‘" ⊕ xs ⊕ "’"] parseCapslock ∷ Logger m ⇒ String → MaybeT m Bool parseCapslock xs = maybe e (pure ∘ flip testBit 0) (readMaybe xs ∷ Maybe Int) where e = tellMaybeT ["‘" ⊕ xs ⊕ "’ is not a boolean value"] parseLetter ∷ Logger m ⇒ String → m Letter parseLetter "" = pure LNothing parseLetter "-1" = pure LNothing parseLetter [x] = pure (Char x) parseLetter "%%" = pure LNothing parseLetter xs | last xs ≡ '@' = case chr <$> readMaybe ('0':'x':init xs) of Just c → pure (CustomDead Nothing (DeadKey [c] (BaseChar c) (∅))) Nothing → LNothing <$ tell ["no number in dead key ‘" ⊕ xs ⊕ "’"] | otherwise = case chr <$> readMaybe ('0':'x':xs) of Just c → pure (Char c) Nothing → LNothing <$ tell ["unknown letter ‘" ⊕ xs ⊕ "’"] ligatures ∷ (Logger m, Parser m, MonadFail m) ⇒ m [(Pos, Int, String)] ligatures = do ["LIGATURE"] ← readLine catMaybes <$> many (try ligature) ligature ∷ (Logger m, Parser m, MonadFail m) ⇒ m (Maybe (Pos, Int, String)) ligature = do sc:i:chars ← readLine guard (not (null chars)) runMaybeT $ do pos ← parseShortcutPos sc i' ← maybe (tellMaybeT ["unknown index ‘" ⊕ i ⊕ "’"]) pure $ readMaybe ('0':'x':i) s ← mapMaybe letterToChar <$> traverse parseLetter chars pure (pos, i', s) where letterToChar (Char c) = Just c letterToChar _ = Nothing deadKey ∷ (Logger m, Parser m, MonadFail m) ⇒ m [(Char, ActionMap)] deadKey = do ["DEADKEY", s] ← readLine let i = maybeToList (readMaybe ('0':'x':s)) c ← chr <$> i <$ when (null i) (tell ["unknown dead key ‘" ⊕ s ⊕ "’"]) m ← many (isHex *> deadPair) pure (zip c [m]) deadPair ∷ (Parser m, MonadFail m) ⇒ m (Letter, ActionResult) deadPair = do [x, y] ← map (\s → maybe '\0' chr (readMaybe ('0':'x':s))) <$> readLine pure (Char x, OutString [y]) keyName ∷ (Parser m, MonadFail m) ⇒ m [(String, String)] keyName = do ['K':'E':'Y':'N':'A':'M':'E':_] ← readLine many (try nameValue) descriptions ∷ (Parser m, MonadFail m) ⇒ m () descriptions = do ["DESCRIPTIONS"] ← readLine void $ many (some hexDigitChar *> spacing *> endLine) pure () languageNames ∷ (Parser m, MonadFail m) ⇒ m () languageNames = do ["LANGUAGENAMES"] ← readLine void $ many (some hexDigitChar *> spacing *> endLine) pure () endKbd ∷ (Parser m, MonadFail m) ⇒ m () endKbd = do ["ENDKBD"] ← readLine pure () nameValue ∷ (Parser m, MonadFail m) ⇒ m (String, String) nameValue = do [name, value] ← readLine pure (name, value) readLine ∷ Parser m ⇒ m [String] readLine = takeWhile (not ∘ isComment) <$> some (klcValue <* spacing) <* emptyOrCommentLines where isComment (';':_) = True isComment ('/':'/':_) = True isComment _ = False klcValue ∷ Parser m ⇒ m String klcValue = try (char '"' *> manyTill anySingle (char '"')) <|> try (some (noneOf [' ','\t','\r','\n'])) <?> "klc value" isHex ∷ Parser m ⇒ m Char isHex = (lookAhead ∘ try) (spacing *> satisfy ((∧) <$> isHexDigit <*> not ∘ isUpper)) spacing ∷ Parser m ⇒ m String spacing = many (oneOf [' ','\t']) comment ∷ Parser m ⇒ m String comment = spacing *> (string ";" <|> string "//") *> manyTill anySingle (try eol) endLine ∷ Parser m ⇒ m String endLine = manyTill anySingle (try eol) <* emptyOrCommentLines emptyLine ∷ Parser m ⇒ m String emptyLine = spacing <* eol emptyOrCommentLines ∷ Parser m ⇒ m [String] emptyOrCommentLines = many (try emptyLine <|> try comment) parseKlcLayout ∷ Logger m ⇒ String → L.Text → Either String (m Layout) parseKlcLayout fname = parse (runWriterT (emptyOrCommentLines *> layout <* eof)) fname >>> bimap errorBundlePretty writer
39aldo39/klfc
src/KlcParse.hs
gpl-3.0
9,053
0
25
1,918
3,652
1,894
1,758
201
6
{-# 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.Logging.Folders.Exclusions.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the description of an exclusion. -- -- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.folders.exclusions.get@. module Network.Google.Resource.Logging.Folders.Exclusions.Get ( -- * REST Resource FoldersExclusionsGetResource -- * Creating a Request , foldersExclusionsGet , FoldersExclusionsGet -- * Request Lenses , fegXgafv , fegUploadProtocol , fegAccessToken , fegUploadType , fegName , fegCallback ) where import Network.Google.Logging.Types import Network.Google.Prelude -- | A resource alias for @logging.folders.exclusions.get@ method which the -- 'FoldersExclusionsGet' request conforms to. type FoldersExclusionsGetResource = "v2" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] LogExclusion -- | Gets the description of an exclusion. -- -- /See:/ 'foldersExclusionsGet' smart constructor. data FoldersExclusionsGet = FoldersExclusionsGet' { _fegXgafv :: !(Maybe Xgafv) , _fegUploadProtocol :: !(Maybe Text) , _fegAccessToken :: !(Maybe Text) , _fegUploadType :: !(Maybe Text) , _fegName :: !Text , _fegCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'FoldersExclusionsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fegXgafv' -- -- * 'fegUploadProtocol' -- -- * 'fegAccessToken' -- -- * 'fegUploadType' -- -- * 'fegName' -- -- * 'fegCallback' foldersExclusionsGet :: Text -- ^ 'fegName' -> FoldersExclusionsGet foldersExclusionsGet pFegName_ = FoldersExclusionsGet' { _fegXgafv = Nothing , _fegUploadProtocol = Nothing , _fegAccessToken = Nothing , _fegUploadType = Nothing , _fegName = pFegName_ , _fegCallback = Nothing } -- | V1 error format. fegXgafv :: Lens' FoldersExclusionsGet (Maybe Xgafv) fegXgafv = lens _fegXgafv (\ s a -> s{_fegXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). fegUploadProtocol :: Lens' FoldersExclusionsGet (Maybe Text) fegUploadProtocol = lens _fegUploadProtocol (\ s a -> s{_fegUploadProtocol = a}) -- | OAuth access token. fegAccessToken :: Lens' FoldersExclusionsGet (Maybe Text) fegAccessToken = lens _fegAccessToken (\ s a -> s{_fegAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). fegUploadType :: Lens' FoldersExclusionsGet (Maybe Text) fegUploadType = lens _fegUploadType (\ s a -> s{_fegUploadType = a}) -- | Required. The resource name of an existing exclusion: -- \"projects\/[PROJECT_ID]\/exclusions\/[EXCLUSION_ID]\" -- \"organizations\/[ORGANIZATION_ID]\/exclusions\/[EXCLUSION_ID]\" -- \"billingAccounts\/[BILLING_ACCOUNT_ID]\/exclusions\/[EXCLUSION_ID]\" -- \"folders\/[FOLDER_ID]\/exclusions\/[EXCLUSION_ID]\" Example: -- \"projects\/my-project-id\/exclusions\/my-exclusion-id\". fegName :: Lens' FoldersExclusionsGet Text fegName = lens _fegName (\ s a -> s{_fegName = a}) -- | JSONP fegCallback :: Lens' FoldersExclusionsGet (Maybe Text) fegCallback = lens _fegCallback (\ s a -> s{_fegCallback = a}) instance GoogleRequest FoldersExclusionsGet where type Rs FoldersExclusionsGet = LogExclusion type Scopes FoldersExclusionsGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/logging.admin", "https://www.googleapis.com/auth/logging.read"] requestClient FoldersExclusionsGet'{..} = go _fegName _fegXgafv _fegUploadProtocol _fegAccessToken _fegUploadType _fegCallback (Just AltJSON) loggingService where go = buildClient (Proxy :: Proxy FoldersExclusionsGetResource) mempty
brendanhay/gogol
gogol-logging/gen/Network/Google/Resource/Logging/Folders/Exclusions/Get.hs
mpl-2.0
5,042
0
15
1,085
709
417
292
103
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS -fwarn-unused-imports -fno-warn-incomplete-patterns #-} {-| This module introduces the types 'Script' and 'Trace'. A 'Script' is a list of events called 'ScriptItem's (HTTP requests, browser events, etc.). A 'Script' can be printed for inspection, serialized, compiled to python, or (most interestingly) run through an interpreter that produces a 'Trace'. The 'Trace' contains the events together with their effects (responses from the backend, browser, etc.). Both legal and illegal (as far as the REST counterpart is concerned) request sequences can be tested (the properties are free to expect either success or error in any context). The requests in a 'Script' depend on each other, and there is a reference mechanism (see e.g. reduceRefsTrace), for using earlier effects in the constructions of later events. [1] Koen Claessen, John Hughes, Testing Monadic Code with QuickCheck, Department of Computer Science, Chalmers University of Technology -} module Test.WebApp.Script where import Control.Applicative import Control.Arrow import Control.Monad hiding (mapM) import Data.Char import Data.Data import Data.Function import Data.List import Data.Maybe import Data.Monoid import Data.Set (Set) import Data.String.Conversions import Data.Traversable (mapM) import GHC.Generics import Network.HTTP import Network.URI import Prelude hiding (mapM) import Safe import System.Directory import System.FilePath import Test.QuickCheck as QC import Test.QuickCheck.Property as QC import Test.QuickCheck.Store as QC import Text.Printf import Text.Regex.Easy import Text.Show.Pretty import qualified Data.Aeson as JS import qualified Data.Aeson.Encode.Pretty as JS import qualified Data.ByteString as SBS import qualified Data.ByteString.Lazy as LBS import qualified Data.Serialize as Cereal import qualified Data.Set as Set hiding (Set) import Test.QuickCheck.Missing import Test.WebApp.Arbitrary import Test.WebApp.HTTP.Util import Test.WebApp.Orphans () -- * Script requests -- | One event in a 'Script'. The serial number is needed when -- constructing later script items from earlier ones and when writing -- 'Trace' properties. See 'Script' type for more info on serial -- numbers. -- -- HTTP: For convenience, the body may be stored in a typed way, and -- will be serialized using 'ToJSON', but it is also possible to write -- requests with arbitrarily broken bodies. The path is either a -- 'URI', or a reference that is passed to a path constructor function -- (see below). -- -- For instance, you may reference an earlier @POST@ request, retrieve -- the path of an object that has been stored, and use that path in a -- @GET@ request to retrieve it. -- -- WebDriver: coming up... -- -- (Future work: constructor 'ScriptItemRT' (RunTime) makes use of -- past effects (not only script items) in order to generate script items -- dynamically. This constructor will lack many nice features such as -- compilability to python.) data ScriptItem sid content = ScriptItemHTTP { siSerial :: Ix , siFromState :: Maybe sid , siThisState :: Maybe sid , siMethod :: RequestMethod , siBody :: Either SBS content , siGetParams :: [(SBS, SBS)] , siPostParams :: [(SBS, SBS)] , siHeaders :: [(SBS, SBS)] , siHTTPPath :: Either URI PathRef } {- | ScriptItemDWD { siSerial :: Ix , siDWD :: (MonadIO wd, WebDriver wd) => wd (Either Element content) } -} deriving (Show, Eq, Typeable, Generic) instance (Cereal.Serialize sid, Cereal.Serialize content) => Cereal.Serialize (ScriptItem sid content) -- | Serial numbers for 'Script's and 'Trace's. newtype Ix = Ix { fromIx :: Int } deriving (Eq, Ord, Enum, Typeable, Generic) instance Show Ix where showsPrec n (Ix ix) = showsPrec n ix instance Read Ix where readsPrec n s = case readsPrec n s of [(i, s)] -> [(Ix i, s)] -- | PathRef either refers to an 'Ix', or to a dedicated root 'URI' (see -- below). data PathRef = PathRef Ix | PathRefRoot deriving (Show, Eq, Ord, Typeable, Generic) instance Cereal.Serialize Ix instance Cereal.Serialize PathRef pathRef :: Either URI PathRef -> Maybe Ix pathRef (Right (PathRef x)) = Just x pathRef _ = Nothing -- * Scripts -- | A 'Script' is a list of requests. Scripts are run head-to-last. -- The 'ScriptItem' type has a serial number. Serial numbers are -- unique (no serial number is used twice), but not continuous -- (possibly N is not used, but N+1 is) and not monotonous (numbers -- may alternatingly increase and decrease over time). newtype Script sid content = Script { scriptItems :: [ScriptItem sid content] } deriving (Show, Eq, Typeable, Generic) instance (Cereal.Serialize sid, Cereal.Serialize content) => Cereal.Serialize (Script sid content) -- | In script concatenation, no sanitation of serial numbers or -- pathrefs is taking place. (FIXME: this should either crash on -- unsound concatenations or sanitize them where possible.) instance Monoid (Script sid content) where mappend (Script xs) (Script ys) = Script $ xs ++ ys mempty = Script [] -- ** Constructing scripts -- | Very basic DSL for writing scripts in a more convenient form -- (this is work in progress). newScript :: forall sid content . [(String, String, Ix -> PathRef -> ScriptItem sid content)] -> Script sid content newScript = Script . f (Ix 0) [("/", PathRefRoot)] where f :: Ix -> [(String, PathRef)] -> [(String, String, Ix -> PathRef -> ScriptItem sid content)] -> [ScriptItem sid content] f _ _ [] = [] f i ctx ((label, refstring, x):xs) = case lookup refstring ctx of Just pathref -> x i pathref : f (nextIx i) ((label, PathRef i):ctx) xs Nothing -> error $ printf "item %i: could not find label %s" (fromIx i) (show label) nextIx :: Ix -> Ix nextIx = Ix . (+1) . fromIx nextIxCtx :: RefCtx -> Ix nextIxCtx (RefCtx serials _ _) = Ix . maybe 0 ((+1) . fst) . Set.maxView . Set.map fromIx $ serials mapSerials :: forall sid content . (Ix -> Ix) -> (Script sid content) -> (Script sid content) mapSerials f (Script rqs) = Script $ map q rqs where q :: ScriptItem sid content -> ScriptItem sid content q rq = rq { siHTTPPath = case siHTTPPath rq of x@(Left e) -> x x@(Right PathRefRoot) -> x (Right (PathRef r)) -> Right (PathRef $ f r) } -- | Parse body from lines of json code. readReqBody :: JS.FromJSON content => [LBS] -> Either SBS content readReqBody (LBS.intercalate "\n" -> s) = maybe (Left $ cs s) (Right) $ JS.decode s emptyReqBody :: Either SBS content emptyReqBody = Left "" newLabelledItem :: String -> RequestMethod -> String -> Either SBS content -> [(SBS, SBS)] -> [(SBS, SBS)] -> [(SBS, SBS)] -> (String, String, Ix -> PathRef -> ScriptItem sid content) newLabelledItem label meth refstring body getparams postparams headers = (label, refstring, \ ix ref -> ScriptItemHTTP ix Nothing Nothing meth body getparams postparams headers (Right ref)) newItem :: RequestMethod -> String -> Either SBS content -> [(SBS, SBS)] -> [(SBS, SBS)] -> [(SBS, SBS)] -> (String, String, Ix -> PathRef -> ScriptItem sid content) newItem = newLabelledItem "" sanitizeScript :: JS.FromJSON content => Script sid content -> Script sid content sanitizeScript (Script rqs) = Script $ map sanitizeScriptItem rqs sanitizeScriptItem :: JS.FromJSON content => ScriptItem sid content -> ScriptItem sid content sanitizeScriptItem r@(ScriptItemHTTP _ _ _ _ b _ _ _ _) = r { siBody = sanitizeScriptItemContent b } sanitizeScriptItemContent :: JS.FromJSON content => Either SBS content -> Either SBS content sanitizeScriptItemContent (Right c) = Right c sanitizeScriptItemContent (Left s) = maybe (Left s) (Right) . JS.decode $ cs s -- ** Arbitrary scripts instance (Arbitrary content, Show content, Eq sid, Eq content) => Arbitrary (Script sid content) where arbitrary = arbitraryScript mempty Nothing shrink = shrinkScript instance (Arbitrary content, Show content, Eq content) => Arbitrary (ScriptItem sid content) where arbitrary = arbitraryScriptItem mempty Nothing shrink = shrinkScriptItem -- | Generate arbitrary 'Script's. This is slightly more -- sophisticated than 'listOf', since the path refs are context -- sensitive. Takes a 'RefCtx' and an (optional) probability -- distribution over request methods. arbitraryScript :: forall sid content . (Arbitrary content, Show content) => RefCtx -> Maybe [(Int, RequestMethod)] -> Gen (Script sid content) arbitraryScript ctx desiredMethods = Script . reverse . fst <$> (listOf (arbitrary :: Gen ()) >>= foldM f ([], ctx)) where f :: ([ScriptItem sid content], RefCtx) -> () -> Gen ([ScriptItem sid content], RefCtx) f (rqs, ctx) () = do rq <- arbitraryScriptItem ctx desiredMethods return (rq:rqs, ctx <> scriptItemContext rq) -- | The default shrink method for 'Script's is to shrink the list of -- script items and call 'dropDanglingReferences' on all outcomes. shrinkScript :: (Eq sid, Eq content, Show content, Arbitrary content) => Script sid content -> [Script sid content] shrinkScript = nub . fmap (dropDanglingReferences . Script) . shrink . scriptItems -- | In a given 'RefCtx' and with an (optional) given request method -- distribution, construct a request with fresh serial number, -- arbitrary but sound 'PathRef', arbitrary but sound method and -- content, and empty get and post params and headers. If request -- method distribution is 'Nothing', a plausible default is used. arbitraryScriptItem :: forall sid content . (Arbitrary content, Show content) => RefCtx -> Maybe [(Int, RequestMethod)] -> Gen (ScriptItem sid content) arbitraryScriptItem ctx desiredMethods = do let defaultMethods :: [(Int, RequestMethod)] defaultMethods = [ (7, GET) , (5, PUT) , (5, POST) , (2, DELETE) , (1, OPTIONS) , (1, HEAD) ] let ix = nextIxCtx ctx pathref <- fmap Right . QC.elements . Set.toList $ refCtx ctx method <- QC.frequency . map (second pure) . maybe defaultMethods id $ desiredMethods content <- Right <$> arbitrary return $ ScriptItemHTTP ix Nothing Nothing method content [] [] [] pathref -- | Default shrink method for 'ScriptItem's just shrinks the content. shrinkScriptItem :: forall sid content . (Arbitrary content) => ScriptItem sid content -> [ScriptItem sid content] shrinkScriptItem item = case siBody item of Left s -> upd <$> [Left ""] Right c -> upd . Right <$> shrink c where upd :: Either SBS content -> ScriptItem sid content upd b = item { siBody = b } -- | All scripts must have distinct serial numbers. prop_arbitraryScriptIx :: (Script sid content) -> Property prop_arbitraryScriptIx (Script rqs) = mkprop $ length rqs == (length . nub . map siSerial $ rqs) -- | All scripts must not have dangling references. prop_arbitraryScriptPathRef :: (Script sid content) -> Property prop_arbitraryScriptPathRef (Script rqs) = mkprop $ refs `Set.isSubsetOf` ixs where refs = Set.fromList . catMaybes . map (pathRef . siHTTPPath) $ rqs ixs = Set.fromList . map siSerial $ rqs -- ** Fuzzing scripts instance (Fuzz content, JS.ToJSON content) => Fuzz (Script sid content) where fuzz = fuzzLastNRqs 10 fuzzLastNRqs :: (Fuzz content, JS.ToJSON content) => Int -> Script sid content -> Gen (Script sid content) fuzzLastNRqs n (Script rqs) = do i <- choose (0, max 0 (length rqs - n)) case splitAt i rqs of (notToBeFuzzed, toBeFuzzed) -> Script . (notToBeFuzzed ++) <$> mapM fuzz toBeFuzzed -- | Leave serial number and path ref alone. breaking the former is -- not interesting, because it would only attack consistency of the -- test code, not the code under test. breaking the latter is more -- interesting if we have a 'RefCtx' to do it, so we need to do -- it when fuzzing a 'Script'. -- -- FIXME: fuzz path refs, get and post params, ... instance forall sid content . (Fuzz content, JS.ToJSON content) => Fuzz (ScriptItem sid content) where fuzz (ScriptItemHTTP i _ _ m b gps pps h r) = oneof [tweakMethod, tweakBody, tweakHeaders] where tweakMethod :: Gen (ScriptItem sid content) tweakMethod = (\ m' -> ScriptItemHTTP i Nothing Nothing m' b gps pps h r) <$> arbitrary tweakBody :: Gen (ScriptItem sid content) tweakBody = (\ b' -> ScriptItemHTTP i Nothing Nothing m (Left b') gps pps h r) <$> either fuzz (fuzz . (cs :: LBS -> SBS) . JS.encode) b tweakHeaders :: Gen (ScriptItem sid content) tweakHeaders = (\ h' -> ScriptItemHTTP i Nothing Nothing m b gps pps h' r) <$> forM h (\ (k, v) -> frequency [ (50, (k,) <$> fuzz v) , (50, (,v) <$> fuzz k) ]) -- ** Script contexts -- | The context of a script at any given point in the request list -- with respect to references is defined by three sets: (1) All serial -- numbers in scope, (2) all added path refs (PathRefRoot and the -- serial numbers of all requests that have created (not modified) a -- path using methods @POST@, @PUT@), and (3) all removed path refs -- (method @DELETE@). The set of active path refs is defined as -- @added \\ removed@ (see 'refCtx'). data RefCtx = RefCtx { ctxSerials :: Set Ix , ctxAddedPaths :: Set PathRef , ctxRemovedPaths :: Set PathRef } deriving (Show, Eq, Ord, Generic) -- | The empty context contains 'PathRefRoot' in the set of added -- refs. Append crashes if the two sets of serial numbers overlap. instance Monoid RefCtx where mempty = RefCtx Set.empty (Set.singleton PathRefRoot) Set.empty mappend :: RefCtx -> RefCtx -> RefCtx mappend (RefCtx serials added removed) (RefCtx serials' added' removed') | (Set.null $ Set.intersection serials serials') = RefCtx (Set.union serials serials') (Set.union added added') (Set.union removed removed') -- | The set of all active references (@added \\ removed@) in a given -- context. refCtx :: RefCtx -> Set PathRef refCtx ctx = ctxAddedPaths ctx Set.\\ ctxRemovedPaths ctx -- | Derive the context from a 'Script'. scriptContext :: (Show content) => Script sid content -> RefCtx scriptContext = foldl (<>) mempty . map scriptItemContext . scriptItems -- | Derive the context from a 'ScriptItem'. If item is a POST or -- PUT, add pathref to "added"; if it is a DELETE, add to "removed"; -- otherwise, neither. (FIXME: This may or may not be what you need. -- This library should offer something more configurable.) scriptItemContext :: (Show content) => ScriptItem sid content -> RefCtx scriptItemContext rq = RefCtx (Set.singleton (siSerial rq)) added removed where yes :: Set PathRef yes = Set.singleton . PathRef . siSerial $ rq no :: Set PathRef no = Set.empty added :: Set PathRef removed :: Set PathRef (added, removed) = case (siHTTPPath rq, siMethod rq) of (Right _, POST) -> (yes, no) (Right _, PUT) -> (yes, no) (Right _, DELETE) -> (no, yes) (_, _) -> (no, no) -- ** Reference maintenance dropDanglingReferences :: (Show content, Eq content) => Script sid content -> Script sid content dropDanglingReferences = dropDanglingReferences'3 newtype DropDanglingReferences = DropDanglingReferences (Script Int Int) deriving (Show, Eq, Typeable, Generic) instance Cereal.Serialize DropDanglingReferences instance Arbitrary DropDanglingReferences where arbitrary = DropDanglingReferences <$> arbitrary shrink (DropDanglingReferences x) = DropDanglingReferences <$> shrink x -- | A nano-study of different ways of iterating through a list with -- state. prop_DropDanglingReferences :: DropDanglingReferences -> QC.Property prop_DropDanglingReferences (DropDanglingReferences script) = mkprop . all good . shrink_ $ script where shrink_ = join . take 7 . shrink . join . take 7 . shrink . take 7 . shrink good :: (Show content, Eq sid, Eq content) => Script sid content -> Bool good script = dropDanglingReferences'1 script == dropDanglingReferences'2 script && dropDanglingReferences'2 script == dropDanglingReferences'3 script -- | Variant 1: Peek into prefix of generated list. dropDanglingReferences'1 :: forall sid content . Script sid content -> Script sid content dropDanglingReferences'1 (Script rs) = Script $ catMaybes rs' where -- Set elements whose path ref points to a deleted item to -- 'Nothing'. This way, we can 'take' the first @i@ -- elements of rs' during construction and always be sure -- not to run into a loop. rs' :: [Maybe (ScriptItem sid content)] rs' = map (\ (i, r) -> case siHTTPPath r of Left _ -> Just r Right PathRefRoot -> Just r Right (PathRef ix) -> let context = map siSerial . catMaybes . take i $ rs' in if ix `elem` context then Just r else Nothing) $ zip [0..] rs -- | Variant 2: 'foldl'. ('foldr' could make do without the -- 'reverse'; not sure about space complexity.) dropDanglingReferences'2 :: forall sid content . (Show content) => Script sid content -> Script sid content dropDanglingReferences'2 = Script . reverse . snd . foldl f (mempty, []) . scriptItems where f :: (RefCtx, [ScriptItem sid content]) -> ScriptItem sid content -> (RefCtx, [ScriptItem sid content]) f (ctx, rqs) rq = if maybe False (`Set.member` ctxAddedPaths ctx) . fmap PathRef . pathRef . siHTTPPath $ rq then (ctx <> scriptItemContext rq, rq:rqs) else (ctx, rqs) -- | Variant 3: tail recursion. This is my favorite :) dropDanglingReferences'3 :: forall sid content . (Show content) => Script sid content -> Script sid content dropDanglingReferences'3 (Script rqs) = Script $ f mempty rqs where f :: RefCtx -> [ScriptItem sid content] -> [ScriptItem sid content] f ctx [] = [] f ctx (rq:rqs) = if maybe False (`Set.member` ctxAddedPaths ctx) . fmap PathRef . pathRef . siHTTPPath $ rq then rq : f (ctx <> scriptItemContext rq) rqs else f ctx rqs -- * Traces -- | A 'Trace' is an interpreted 'Script'. 'TraceItem's are arranged -- in a list in the same order as in the 'Script', i.e. last item was -- played last, and associated with an optional test outcome. See -- 'runScript'', 'runScript'. newtype Trace sid content = Trace { traceItems :: [(TraceItem sid content, Maybe Bool)] } deriving (Typeable) data TraceItem sid content = TraceItemHTTP { tiScriptItem :: ScriptItem sid content , tiEffectHTTP :: Maybe (Response LBS) } deriving (Show, Typeable, Generic) instance (Show sid, Show content) => Show (Trace sid content) where show (Trace []) = "(empty Trace)\n" show (Trace xs@(_:_)) = ("Trace\n " <>) . intercalate "\n " . lines . concat . map f $ xs where f :: (TraceItem sid content, Maybe Bool) -> String f (TraceItemHTTP rq rsp, check) = ">>>>>\n" <> ppShow rq <> "\n" <> case rsp of Just rsp_ -> "<<<<<\n" <> show rsp_ <> "\n" <> cs (rspBody rsp_) <> "\n" Nothing -> "<<<<<\n(skipped)\n" <> "<<<<< [" <> show check <> "]\n" instance Monoid (Trace sid content) where mappend (Trace xs) (Trace ys) = Trace $ xs ++ ys mempty = Trace [] getTraceItem :: Trace sid content -> Ix -> Either (TraceError sid content) (TraceItem sid content) getTraceItem (Trace trace) serial = case filter ((== serial) . siSerial . tiScriptItem . fst) trace of [fst -> result@(TraceItemHTTP rq (Just rsp@(rspCode -> (2, _, _))))] -> Right result [fst -> result@(TraceItemHTTP rq (Just rsp@(rspCode -> code)))] -> Left (TraceErrorHTTP code) [fst -> result@(TraceItemHTTP rq Nothing)] -> Left (TraceErrorSkipped rq) [] -> Left TraceErrorSerialNotFound data TraceError sid content = TraceErrorSerialNotFound | TraceErrorHTTP ResponseCode | TraceErrorSkipped (ScriptItem sid content) | TraceErrorJSON deriving (Show, Eq) -- * Reference reduction -- | Headers and body of a 'ScriptItemHTTP' may contain (sub-)strings -- of the form @___SCRIPT_REF___<i>@, or @___SCRIPT_REF___@, which -- index into earlier 'Script' items and into 'PathRefRoot', -- respectively. 'reduceRefs' calls a transformer on each occurrance -- and substitutes it by the resulting string. It accepts a 'RefCtx' -- so that references to non-existing items can trigger an informative -- error message. -- -- The first argument states whether surrounding quotes (double or -- single) should be matched away together with the reference string -- (this is necessary for code generation where a string literal is to -- be replaced by a string variable). reduceRefs :: Bool -> RefCtx -> (PathRef -> Maybe LBS) -> LBS -> LBS reduceRefs quoted ctx rewrite js = if null badrefs then replaceRegexAll js pattern (\ match -> extract quoted match >>= rewrite) else error $ "reduceRefs: illegal references: " ++ show badrefs where pattern :: SBS = q <> "___SCRIPT_REF___(\\d+)?" <> q where q = if quoted then "(\"|\')" else "" extract :: Bool -> [(LBS, (MatchOffset, MatchLength))] -> Maybe PathRef extract False [_, (readMay . cs . fst) -> Just i] = Just $ PathRef i extract False [_, ("", (-1, 0))] = Just $ PathRefRoot extract True [_, ("'", _), (readMay . cs . fst) -> Just i, ("'", _)] = Just $ PathRef i extract True [_, ("'", _), ("", (-1, 0)), ("'", _)] = Just $ PathRefRoot extract True [_, ("\"", _), (readMay . cs . fst) -> Just i, ("\"", _)] = Just $ PathRef i extract True [_, ("\"", _), ("", (-1, 0)), ("\"", _)] = Just $ PathRefRoot extract _ _ = Nothing refs :: Set Ix = Set.fromList . catMaybes . map (pathRef . Right) . catMaybes . map (extract quoted) $ js =~++ pattern badrefs :: [Ix] = Set.toList $ refs Set.\\ ctxSerials ctx -- | (Just a quick in-place unit test for 'reduceRefs'.) test_reduceRefs :: Bool test_reduceRefs = f True == ["PathRefRoot","PathRef 0"] && f False == ["PathRefRoot","PathRef 0"] where f quote = map (reduceRefs quote ctx (Just . cs . show) . scriptRefToSBS quote) refs ctx = RefCtx (Set.fromList [Ix 0]) (Set.fromList refs) Set.empty refs = [PathRefRoot, PathRef (Ix 0)] -- | Render 'PathRef' into a string suitable for being replaced by -- 'reduceRefs'. This is needed for things like header strings -- containing path refs. The boolean flag is for double-quotation -- (yes means double-quotes). scriptRefToSBS :: Bool -> PathRef -> LBS scriptRefToSBS False PathRefRoot = "___SCRIPT_REF___" scriptRefToSBS False (PathRef i) = "___SCRIPT_REF___" <> cs (show i) scriptRefToSBS True PathRefRoot = "\"___SCRIPT_REF___\"" scriptRefToSBS True (PathRef i) = "\"___SCRIPT_REF___" <> cs (show i) <> "\"" -- | Dynamic 'reduceRefs', as needed for 'runScript''. (See 'reduceRefsPy' -- for a static variant.) reduceRefsTrace :: forall sid content . (Show content, JS.FromJSON content, JS.ToJSON content) => Bool -> URI -> (TraceItem sid content -> Maybe URI) -> Trace sid content -> SBS -> SBS reduceRefsTrace quoted rootPath constructPath trace = cs . reduceRefs quoted ctx (fmap (qu . ru) . lu) . cs where script :: Script sid content = Script . map (tiScriptItem . fst) $ traceItems trace ctx :: RefCtx = scriptContext script lu :: PathRef -> Maybe URI -- lookup xref lu PathRefRoot = Just rootPath lu (PathRef i) = case filter ((== i) . siSerial . tiScriptItem . fst) $ traceItems trace of [fst -> item] -> constructPath item ru :: URI -> LBS -- render uri ru = cs . uriPath qu :: LBS -> LBS -- re-quote (if applicable) qu = if quoted then cs . show else id reduceRefsTraceAssoc :: forall sid content . (Show content, JS.FromJSON content, JS.ToJSON content) => URI -> (TraceItem sid content -> Maybe URI) -> Trace sid content -> [(SBS, SBS)] -> [(SBS, SBS)] reduceRefsTraceAssoc root construct trace = map (first f . second f) where f = reduceRefsTrace False root construct trace reduceRefsTraceBody :: forall sid content . (Show content, JS.FromJSON content, JS.ToJSON content) => URI -> (TraceItem sid content -> Maybe URI) -> Trace sid content -> Either SBS content -> Either SBS content reduceRefsTraceBody root construct trace (Left s) = Left (reduceRefsTrace True root construct trace s) reduceRefsTraceBody root construct trace (Right c) = sanitizeScriptItemContent . Left . reduceRefsTrace True root construct trace . cs $ JS.encode c -- * interpreter data RunScriptSetup sid content = RunScriptSetup { runVerbose :: Bool , runRootPath :: URI , runExtractPath :: TraceItem sid content -> Maybe URI } -- | Run a 'Script' and return a 'Trace'. For every 'TraceItem', a -- boolean test outcome is computed from it and the 'Trace' history, -- and associated with the 'TraceItem' in the new history. Requests -- on paths missing due to earlier errors are skipped (effect is -- 'Nothing'). runScript' :: forall sid content . (Show sid, Show content, JS.FromJSON content, JS.ToJSON content) => RunScriptSetup sid content -> Script sid content -> (TraceItem sid content -> Trace sid content -> Maybe Bool) -> IO (Trace sid content) runScript' (RunScriptSetup verbose rootPath extractPath) (Script items) test = foldM f (Trace []) items where f :: Trace sid content -> ScriptItem sid content -> IO (Trace sid content) f trace rq@(ScriptItemHTTP serial _ _ method body getparams postparams headers pathref) = do let pathMay :: Maybe URI = case pathref of Right (PathRef ix) -> case getTraceItem trace ix of Right item -> extractPath item Left TraceErrorSerialNotFound -> error $ "runScript': dangling pathref: " ++ ppShow (pathref, trace) Left (TraceErrorHTTP _) -> Nothing Left (TraceErrorSkipped _) -> Nothing Right PathRefRoot -> Just rootPath Left uri -> Just uri case pathMay of Just path -> do let body' = reduceRefsTraceBody rootPath extractPath trace body getparams' = evl getparams postparams' = evl postparams headers' = evl headers evl = reduceRefsTraceAssoc rootPath extractPath trace response <- performReq verbose method path getparams' postparams' headers' body' let traceItem = TraceItemHTTP rq (Just response) checkResult = test traceItem trace return $ trace <> Trace [(traceItem, checkResult)] Nothing -> do return $ trace <> Trace [(TraceItemHTTP rq Nothing, Nothing)] -- | Run a 'Script' and return a 'Trace'. Requests on paths missing -- due to earlier errors are skipped (effect is 'Nothing'). Check -- results are 'Nothing' for all 'TraceItem's. runScript :: forall sid content . (Show sid, Show content, JS.FromJSON content, JS.ToJSON content) => RunScriptSetup sid content -> Script sid content -> IO (Trace sid content) runScript (RunScriptSetup verbose rootPath extractPath) (Script items) = runScript' (RunScriptSetup verbose rootPath extractPath) (Script items) (\ _ _ -> Nothing) -- | Transform a property of 'Trace's (which you usually would want to -- write) into a property of 'Script's (which are more -- straight-forward to run). This also requires a setup object naming -- verbosity level, server coordinates, ... dynamicScriptProp :: forall sid content . (Show sid, Show content, JS.FromJSON content, JS.ToJSON content) => (Trace sid content -> Property) -> RunScriptSetup sid content -> (Script sid content -> Property) dynamicScriptProp prop setup script = QC.morallyDubiousIOProperty $ prop <$> runScript setup script -- FIXME: dynamicScriptProp'? (it acts to runScript' as -- dynamicScriptProp acts to runScript. (hm... what does that even -- mean?)) -- * Compile to python scriptToPyFile :: (JS.ToJSON content, Show content) => Script sid content -> FilePath -> IO () scriptToPyFile script filepath = SBS.writeFile filepath . SBS.intercalate "\n" . scriptToPySBS $ script scriptToPySBS :: (JS.ToJSON content, Show content) => Script sid content -> [SBS] scriptToPySBS (Script rqs) = pyHeader ++ rqs' ++ ["", "print 'success!'", ""] where rqs' :: [SBS] rqs' = concatMap (uncurry scriptItemToPy) $ zip ctxs rqs ctxs :: [RefCtx] ctxs = map (scriptContext . Script) $ inits rqs pyHeader :: [SBS] pyHeader = "#!/usr/bin/python" : "# -*- encoding: utf-8 -*-" : "" : "import os" : "import json" : "import requests" : "" : "null = None # for more javascript-ish json representation" : "" : [] -- | FIXME: get params and put params are not supported. scriptItemToPy :: (JS.ToJSON content) => RefCtx -> ScriptItem sid content -> [SBS] scriptItemToPy ctx (ScriptItemHTTP x _ _ m b [] [] hs r) = ("data = " <> case either cs (cs . reduceRefsPy True ctx . JS.encodePretty) b of "" -> "''" s -> "json.dumps(" <> s <> ")") : "print '====================================================================== [REQUEST]'" : "print ' method: ' + " <> mss : "print ' uri: ' + " <> path : "print ' data: ' + data" : (resp <> " = requests." <> ms <> "(" <> path <> ", data=data, headers=" <> headers <> ")") : "print ''" : "" : "print '---------------------------------------------------------------------- [RESPONSE]'" : "print ' code: ' + str(" <> resp <> ".status_code)" : "if " <> resp <> ".status_code == 200:" : " print ' data: ' + json.dumps(" <> resp <> ".json())" : " print ''" : "" : "else:" : " print ' data: ' + " <> resp <> ".text" : " print ''" : " print 'giving up!'" : " exit(1)" : "" : [] where ms :: SBS = cs . map toLower . show $ m mss :: SBS = (<> "'") . ("'" <>) $ ms xs :: SBS = cs . show $ x rs :: SBS = cs . show $ r resp :: SBS = "resp_" <> xs showRef :: Either URI PathRef -> SBS showRef (Right (PathRef i)) = "resp_" <> cs (show i) <> ".json()['path']" showRef (Right PathRefRoot) = "rootpath" showRef (Left uri) = cs $ show uri path :: SBS = "server + " <> showRef r headers :: SBS = cs . mconcat $ "{" : "'content-type': 'text/json'," : map render hs ++ "}" : [] where render :: (SBS, SBS) -> SBS render (k, v) | not ('\'' `elem` cs (k <> v) || '\\' `elem` cs (k <> v)) = " '" <> k <> "': " <> (cs . reduceRefsPy False ctx . cs $ v) <> "," reduceRefsPy :: Bool -> RefCtx -> LBS -> LBS reduceRefsPy quoted ctx = reduceRefs quoted ctx f where f PathRefRoot = Just "rootpath" f (PathRef i) = Just $ "resp_" <> cs (show i) <> ".json()['path']" -- * Quickcheck Store helpers -- | List all unit test cases in the DB, together with their filenames. readStore :: forall a sid content . (Show a, Typeable a, Cereal.Serialize a) => (a -> Script sid content) -> IO [(FilePath, Script sid content)] readStore toScript = do let path = (storeRoot </> show (typeOf (undefined :: a))) filenames <- filter (not . (`elem` [".", ".."])) <$> getDirectoryContents path mapM (\ filename -> (path </> filename,) . toScript <$> decodeConfidently (path </> filename)) filenames -- | Given a function that transforms a given type into a 'Script', -- compile all test cases of that type into Haskell and Python. compileStore :: forall a sid content . (Show a, Typeable a, Cereal.Serialize a, Show sid, Show content, JS.ToJSON content) => (a -> Script sid content) -> IO () compileStore toScript = readStore toScript >>= mapM_ (compileTestCase toScript) -- | Test cases that are newtype-wrapped 'Script's can be compiled to -- both Haskell data (for inspection and modification) and python (for -- convenience and inclusion in external test workflows). compileTestCase :: forall a sid content . (Show a, Typeable a, Cereal.Serialize a, Show sid, Show content, JS.ToJSON content) => (a -> Script sid content) -> (FilePath, Script sid content) -> IO () compileTestCase _ (filename, testData) = do writeFile (dropExtension filename <.> "hs") $ ppShow testData scriptToPyFile testData (dropExtension filename <.> "py") -- * More helpers getScriptItem :: Script sid content -> Ix -> Maybe (ScriptItem sid content) getScriptItem (Script rqs) serial = case filter ((== serial) . siSerial) rqs of [] -> Nothing [rq] -> Just rq getScriptItemContent :: ScriptItem sid content -> Maybe content getScriptItemContent (ScriptItemHTTP _ _ _ _ (Right body) _ _ _ _) = Just body getScriptItemContent (ScriptItemHTTP _ _ _ _ _ _ _ _ _) = Nothing getScriptContent :: Script sid content -> Ix -> Maybe content getScriptContent (Script rqs) serial = case filter ((== serial) . siSerial) rqs of [] -> Nothing [rq] -> getScriptItemContent rq -- | ratio of 200 responses vs. all others. errorRate :: Trace sid content -> Double errorRate (Trace trace) = fromIntegral (length errors) / fromIntegral (length trace) where errors = filter (\ (TraceItemHTTP _ rsp, _) -> (rspCode <$> rsp) /= Just (2, 0, 0)) trace -- | ratio of requests not sent due to earlier errors vs. all others. skipRate :: Trace sid content -> Double skipRate (Trace trace) = fromIntegral (length skipped) / fromIntegral (length trace) where skipped = filter (isNothing . tiEffectHTTP . fst) trace
zerobuzz/webtest
src/Test/WebApp/Script.hs
agpl-3.0
35,786
1
42
9,248
9,444
4,993
4,451
494
9
module Haskoin.Crypto -- ECDSA module ( ECDSA , Signature , withECDSA , signMessage , verifyMessage -- Hash module , Hash256 , Hash160 , CheckSum32 , hash256 , hash256BS , hash160 , hash160BS , doubleHash256 , doubleHash256BS , chksum32 -- Keys module , PublicKey , PrivateKey , derivePublicKey , publicKeyAddress , makePrivateKey , makePrivateKeyU , isCompressed , isPrivateKeyCompressed , fromWIF , toWIF ) where import Haskoin.Crypto.ECDSA import Haskoin.Crypto.Keys import Haskoin.Crypto.Hash
lynchronan/haskoin-crypto
src/Haskoin/Crypto.hs
unlicense
504
0
4
76
104
70
34
29
0
-- These are the tests for our api. The only real interesting parts are -- the 'testDbDSLInServant' and 'app' functions. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module Main (main) where import Control.Monad (when) import Control.Monad.Error.Class (throwError) import Control.Monad.IO.Class (liftIO) import Control.Monad.Operational (ProgramViewT(..), view) import Control.Monad.Trans.Either (EitherT) import Data.Aeson (ToJSON, encode) import Data.ByteString (ByteString) import Data.IntMap.Lazy (IntMap) import qualified Data.IntMap.Lazy as IntMap import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Database.Persist (Key) import Database.Persist.Sql (fromSqlKey, toSqlKey) import Network.HTTP.Types.Method (methodPost, methodPut) import Network.Wai (Application) import Network.Wai.Test (SResponse) import Servant.Server (ServantErr(..), serve) import Test.Hspec (Spec, describe, hspec, it) import Test.Hspec.Wai ( WaiExpectation, WaiSession, delete, get, matchBody, request , shouldRespondWith, with ) import Lib (BlogPost(..), DbAction(..), DbDSL, blogPostApiProxy, server) -- | This is our dsl interpreter for these unit tests. It's very similar -- to 'Lib.runDbDSLInServant', except that it doesn't actually access -- a database. Instead, it just uses an 'IntMap' to simulate a database. -- It's similar to 'runDbDSLInServant' in that if you curry the 'IORef' -- argument, then you get a function @'DbDSL' a -> 'EitherT' 'ServantErr' -- IO a@. It takes a 'DbDSL' and evaluates it in a Servant context (e.g. -- the @'EitherT' 'ServantErrr' IO@ monad). -- -- It's using an 'IORef' to hold a tuple of the the 'IntMap' and 'Int' -- corresponding to the id count for simplicity, but it could easily be -- rewritten to use something like a 'State' monad. -- -- The 'Int' corresponding to the id count is simply the highest id of -- something in the database. Everytime we insert something we increase -- it by 1. testDbDSLInServant :: IORef (IntMap BlogPost, Int) -> DbDSL a -> EitherT ServantErr IO a testDbDSLInServant dbRef dbDSL = do case view dbDSL of Return a -> return a -- This evaluates a 'GetDb' request to actually get -- a 'BlogPost' from the hashmap. (GetDb key) :>>= nextStep -> do -- Get the 'IntMap' from the 'IORef'. (intMap, _) <- liftIO $ readIORef dbRef -- Lookup the key of the 'BlogPost' in the 'IntMap'. let maybeBlogPost = IntMap.lookup (sqlKeyToInt key) intMap -- Run the next step of the dsl, passing it the 'BlogPost'. testDbDSLInServant dbRef $ nextStep maybeBlogPost -- Evaluate a 'InsertDb' request to insert a 'BlogPost' in to the -- hashmap. (InsertDb blogPost) :>>= nextStep -> do (intMap, idCounter) <- liftIO $ readIORef dbRef let newIntMap = IntMap.insert idCounter blogPost intMap newCounter = idCounter + 1 liftIO $ writeIORef dbRef (newIntMap, newCounter) testDbDSLInServant dbRef . nextStep $ intToSqlKey idCounter -- Evaluate a 'DelDb' request to delete a 'BlogPost' from the -- hashmap. (DelDb key) :>>= nextStep -> do (intMap, counter) <- liftIO $ readIORef dbRef let newIntMap = IntMap.delete (sqlKeyToInt key) intMap liftIO $ writeIORef dbRef (newIntMap, counter) testDbDSLInServant dbRef $ nextStep () -- Evaluate an 'UpdateDb' request to update a 'BlogPost' in the -- hashmap. (UpdateDb key blogPost) :>>= nextStep -> do (intMap, counter) <- liftIO $ readIORef dbRef let newIntMap = IntMap.insert (sqlKeyToInt key) blogPost intMap when (sqlKeyToInt key `IntMap.member` intMap) $ liftIO $ writeIORef dbRef (newIntMap, counter) testDbDSLInServant dbRef $ nextStep () -- Throw an error to indicate that something went wrong. (ThrowDb servantErr) :>>= _ -> throwError servantErr where -- | Turn a 'Key' 'BlogPost' into an 'Int'. This is for storing a 'Key' -- 'BlogPost' in our 'IntMap'. sqlKeyToInt :: Key BlogPost -> Int sqlKeyToInt key = fromInteger . toInteger $ fromSqlKey key -- | Opposite of 'sqlKeyToInt'. intToSqlKey :: Int -> Key BlogPost intToSqlKey int = toSqlKey . fromInteger $ toInteger int -- | This creates a Wai 'Application'. -- -- It just creates a new 'IORef' to our 'IntMap', and passes it to -- 'testDbDSLInServant'. It then uses the 'serve' function to create a Wai -- 'Application'. app :: IO Application app = do -- Create an 'IORef' to a tuple of an 'IntMap' and 'Int'. -- The 'IntMap' will be our database. The 'Int' will be a count -- holding the highest id in the database. dbRef <- newIORef (IntMap.empty, 1) return . serve blogPostApiProxy $ server (testDbDSLInServant dbRef) -- | These are our actual unit tests. They should be relatively -- straightforward. -- -- This function is using 'app', which in turn uses our test dsl interpreter -- ('testDbDSLInServant'). spec :: Spec spec = with app $ do describe "GET blogpost" $ do it "responds with 200 after inserting something" $ do postJson "/create" testBlogPost `shouldRespondWith` 201 get "/read/1" `shouldRespondWithJson` (200, testBlogPost) it "responds with 404 because nothing has been inserted" $ do get "/read/1" `shouldRespondWith` 404 describe "PUT blogpost" $ do it "responds with 204 even when key doesn't exist in DB" $ do putJson "/update/1" testBlogPost `shouldRespondWith` 204 it "can't GET after PUT" $ do putJson "/update/1" testBlogPost `shouldRespondWith` 204 get "/read/1" `shouldRespondWith` 404 describe "DELETE blogpost" $ do it "responds with 204 even when key doesn't exist in DB" $ do delete "/delete/1" `shouldRespondWith` 204 it "GET after DELETE returns 404" $ do postJson "/create" testBlogPost `shouldRespondWith` 201 get "/read/1" `shouldRespondWith` 200 delete "/delete/1" `shouldRespondWith` 204 get "/read/1" `shouldRespondWith` 404 where -- Send a type that can be turned into JSON (@a@) to the Wai -- 'Application' at the 'ByteString' url. This returns a 'SResponse' -- in the 'WaiSession' monad. This is similar to the 'post' function. postJson :: (ToJSON a) => ByteString -> a -> WaiSession SResponse postJson path = request methodPost path [("Content-Type", "application/json")] . encode -- Similar to 'postJson'. putJson :: (ToJSON a) => ByteString -> a -> WaiSession SResponse putJson path = request methodPut path [("Content-Type", "application/json")] . encode -- Similar to 'shouldRespondWith', but converts the second argument to -- JSON before it compares with the 'SResponse'. shouldRespondWithJson :: (ToJSON a) => WaiSession SResponse -> (Integer, a) -> WaiExpectation shouldRespondWithJson req (expectedStatus, expectedValue) = let matcher = (fromInteger expectedStatus) { matchBody = Just $ encode expectedValue } in shouldRespondWith req matcher -- An example blog post to use in tests. testBlogPost :: BlogPost testBlogPost = BlogPost "title" "content" main :: IO () main = hspec spec
cdepillabout/testing-code-that-accesses-db-in-haskell
without-db/free-monad/test/Test.hs
apache-2.0
7,693
0
17
1,907
1,406
759
647
104
6
module Data.MarkovChain where import Data.Default import Data.List import qualified Data.Map as Map import Data.Map(Map) import qualified Data.RandSet as RandSet import Data.RandSet(RandSet) import System.Random newtype NGram a = NGram [a] deriving (Eq, Ord, Show) shiftAppend :: NGram a -> a -> NGram a shiftAppend (NGram []) y = NGram [y] shiftAppend (NGram (_:xs)) y = NGram (xs ++ [y]) emptyNGram :: (Default a) => Int -> NGram a emptyNGram n = NGram (replicate n def) newtype MarkovChain a = MarkovChain (Map (NGram a) (RandSet Int a)) empty :: MarkovChain a empty = MarkovChain Map.empty null :: MarkovChain a -> Bool null (MarkovChain m) = Map.null m addElement :: (Ord a) => (NGram a, MarkovChain a) -> a -> (NGram a, MarkovChain a) addElement (n, MarkovChain m) a = (n', MarkovChain m') where n' = shiftAppend n a m' = case Map.lookup n m of Nothing -> Map.insert n (RandSet.add (a,1) RandSet.empty) m Just r -> Map.insert n (RandSet.add (a,1) r) m nextElement :: (RandomGen g, Ord a) => MarkovChain a -> (NGram a, g) -> Maybe (a, (NGram a, g)) nextElement (MarkovChain m) (n,g) = fmap choose $ Map.lookup n m where choose r = (a, (shiftAppend n a, g')) where (g',a) = RandSet.randomChoice g r construct1GramMC :: [String] -> MarkovChain String construct1GramMC = snd . foldl' addElement (emptyNGram 1, empty) generateFrom1GramMC :: (RandomGen g) => MarkovChain String -> g -> [String] generateFrom1GramMC m g = unfoldr (nextElement m) (emptyNGram 1, g)
jameseb7/markov
Data/MarkovChain.hs
bsd-2-clause
1,713
0
13
491
690
366
324
35
2