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 Ghci006 where data Q = forall x . Show x => Q x showQ (Q x) = show x -- associated bug is that at the interpreter command line, -- showQ (Q "foo") crashed the interpreter.
urbanslug/ghc
testsuite/tests/ghci/scripts/ghci006.hs
bsd-3-clause
184
0
7
42
44
24
20
-1
-1
module ShouldSucceed where x@_ = x
siddhanathan/ghc
testsuite/tests/typecheck/should_compile/tc011.hs
bsd-3-clause
36
0
5
7
13
8
5
2
1
import Data.Ratio import Data.List.Ordered (minus) import ContinuedFractions toDecimalExpansion :: Rational -> [Integer] toDecimalExpansion r = let num = numerator r den = denominator r ratio = num `div` den rest = num `mod` den in ratio : toDecimalExpansion ((10 * rest) % den) nonPerfectSquares = [1..100] `minus` (map (^2) [1..10]) minimalKExpansion k n = expandSqrtEpsilon (1 % (10^(k+1))) n firstKDigitsSqrt k n = sum $ take k $ toDecimalExpansion $ approximant $ minimalKExpansion k n answer = sum $ map (firstKDigitsSqrt 100) nonPerfectSquares
arekfu/project_euler
p0080/p0080.hs
mit
660
0
12
192
228
123
105
13
1
module Main where import Bindings.Objc import Foreign.Ptr import Foreign.C.String import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Data.List main :: IO () main = do putStrLn "Bindings to the Objective-C Runtime!" arbitraryFunctionTest classes <- getClassList names <- sort <$> mapM getClassName classes if "NSHaskell" `elem` names then putStrLn "Have access to NSHaskell" else putStrLn "Do not have access to NSHaskell" if "NSApplication" `elem` names then putStrLn "Have access to NSApplication" else putStrLn "Do not have access to NSApplication" getClassList :: IO [CClass] getClassList = do num <- c'objc_getClassList nullPtr 0 let num' = fromIntegral num allocaArray num' $ \ptr -> do _ <- c'objc_getClassList ptr num peekArray num' ptr getClassName :: CClass -> IO String getClassName c = c'class_getName c >>= peekCString nsHaskellPrint :: CId -> CSEL -> IO CId nsHaskellPrint cid sel = do putStrLn "nsHaskellPrint was called." print cid return c'Nil arbitraryFunctionTest :: IO () arbitraryFunctionTest = do nsObject <- withCString "NSObject" c'objc_getClass nsHaskell <- withCString "NSHaskell" $ \ptr -> c'objc_allocateClassPair nsObject ptr 0 sel <- withCString "nshaskellprint" c'sel_getUid if (sel == c'nil) then putStrLn "Selector is nil." else putStrLn "Got selector!" nsHP <- mkImp0 nsHaskellPrint added <- withCString "@@:" $ \ptr -> c'class_addMethod0 nsHaskell sel nsHP ptr if (added == c'YES) then do c'objc_registerClassPair nsHaskell nsh <- c'class_createInstance nsHaskell c'objc_msgSend nsh sel return () else putStrLn "Could not add method to NSHaskell." return ()
schell/bindings-objc
src/Example.hs
mit
1,791
0
12
409
464
220
244
50
3
{-# LANGUAGE GADTs #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Handler.FobAssignments ( fobAssignments ) where import qualified Data.Text as T import Model import Handler.Helpers import View.FobAssignments fobAssignments :: App Response fobAssignments = routeResource $ defaultActions { resActionList = fobAssignmentsList , resActionNew = fobAssignmentsNew , resActionEdit = fobAssignmentsEdit , resActionCreate = fobAssignmentsCreate , resActionUpdate = fobAssignmentsUpdate } fobAssignmentsRes :: Resource FobAssignment fobAssignmentsRes = defaultResource { resNewView = fobAssignmentsNewView , resEditView = fobAssignmentsEditView , resIndexUri = "/fobAssignments" } fobAssignmentsList :: App Response fobAssignmentsList = do fobAssignments <- runDB $ selectList [] [] :: App [Entity FobAssignment] fobAssignmentViews <- runDB $ loadAssociations fobAssignments $ FobAssignmentView <$> own entityKey <*> (entityVal <$> belongsTos FobAssignmentPersonId) <*> (entityVal <$> belongsTos FobAssignmentFobId) ok $ toResponse $ fobAssignmentsListView fobAssignmentViews fobAssignmentsNew :: App Response fobAssignmentsNew = do view <- getForm "fobAssignment" (fobAssignmentForm Nothing) ok $ toResponse $ fobAssignmentsNewView view fobAssignmentsEdit :: Entity FobAssignment -> App Response fobAssignmentsEdit ent@(Entity key fobAssignment) = do view <- getForm "fobAssignment" (fobAssignmentForm (Just fobAssignment)) ok $ toResponse $ fobAssignmentsEditView ent view fobAssignmentsCreate :: App Response fobAssignmentsCreate = do post <- runForm "fobAssignment" (fobAssignmentForm Nothing) handleCreate fobAssignmentsRes post fobAssignmentsUpdate :: Entity FobAssignment -> App Response fobAssignmentsUpdate ent@(Entity key fobAssignment) = do post <- runForm "fobAssignment" (fobAssignmentForm (Just fobAssignment)) handleUpdate fobAssignmentsRes ent post fobAssignmentForm :: Formlet Text App FobAssignment fobAssignmentForm fa = monadic $ do people <- runDB $ selectList [] [] fobs <- runDB $ selectList [] [] return $ fobAssignmentFormPure people fobs fa fobAssignmentFormPure :: Monad m => [Entity Person] -> [Entity Fob] -> Formlet Text m FobAssignment fobAssignmentFormPure people fobs fa = FobAssignment <$> "personId" .: foreignKey people (fobAssignmentPersonId <$> fa) <*> "fobId" .: foreignKey fobs (fobAssignmentFobId <$> fa) <*> "startDate" .: dateField (fobAssignmentStartDate <$> fa) <*> "expirationDate" .: optionalDateField (fobAssignmentExpirationDate =<< fa) instance SelectOption Person where toOptionText p = T.pack $ personFirstName p ++ " " ++ personLastName p instance SelectOption Fob where toOptionText e = T.pack $ fobKey e
flipstone/glados
src/Handler/FobAssignments.hs
mit
2,905
0
14
538
721
361
360
66
1
-- SimpleJSON module SimpleJSON ( JValue(..) , getString , getInt , getDouble , getBool , getObject , getArray , isNull ) where data JValue = JString String | JNumber Double | JBool Bool | JNull | JObject [(String, JValue)] | JArray [JValue] deriving (Eq, Show, Ord) getString :: JValue -> Maybe String getString (JString s) = Just s getString _ = Nothing getInt :: JValue -> Maybe Int getInt (JNumber n) = Just (truncate n) getInt _ = Nothing getDouble :: JValue -> Maybe Double getDouble (JNumber n) = Just n getDouble _ = Nothing getBool :: JValue -> Maybe Bool getBool (JBool b) = Just b getBool _ = Nothing getObject :: JValue -> Maybe [(String, JValue)] getObject (JObject o) = Just o getObject _ = Nothing getArray :: JValue -> Maybe [JValue] getArray (JArray a) = Just a getArray _ = Nothing isNull :: JValue -> Bool isNull v = v == JNull
sammyd/Learning-Haskell
ch05/SimpleJSON.hs
mit
1,009
0
8
317
355
189
166
37
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableSuperClasses #-} module TypeLevel where import Data.Proxy import GHC.Exts type family AllAre (c :: k -> Constraint) (xs :: [k]) :: Constraint where AllAre c '[] = () AllAre c (x ': xs) = (c x, AllAre c xs) class Reifiable (xs :: [k]) where reify :: AllAre c xs => Proxy c -> Proxy xs -> (forall a. c a => Proxy a -> b) -> [b] instance Reifiable '[] where reify _ _ _ = [] instance Reifiable xs => Reifiable (x ': xs) where reify p _ f = f (Proxy :: Proxy x) : reify p (Proxy :: Proxy xs) f class (c a, d a) => (c & d) a where instance (c a, d a) => (c & d) a
oisdk/semiring-num
test/TypeLevel.hs
mit
1,160
2
16
396
334
182
152
-1
-1
module Matrix (matrixApply, matrixScale, matrixMap, matrixSub, sumMatrix) where matrixApply :: (Num a) => (a -> a -> a) -> [[a]] -> [[a]] -> [[a]] matrixApply f = zipWith (zipWith f) sub :: (Num a) => a -> a -> a sub x y = x - y matrixSub :: (Num a) => [[a]] -> [[a]] -> [[a]] matrixSub = matrixApply sub sumMatrix :: (Num a) => [[a]] -> a sumMatrix xs = sum $ map sum xs matrixMap :: (Num a, Num b) => (a -> b) -> [[a]] -> [[b]] matrixMap f = map (map f) matrixScale :: (Num a) => [[a]] -> a -> [[a]] matrixScale m x = matrixMap (*x) m
considerate/progp
Haskell/bio/matrix.hs
mit
543
0
10
120
335
188
147
18
1
module Main where import SimpleServer handlers :: Monad m => m () handlers = return () main :: IO () main = simpleServer handlers
ajnsit/SimpleServer
src/Main.hs
mit
133
0
7
27
52
27
25
6
1
-- 2.a -- createSquaredList :: (Integral a) => [a] -> [a] createSquaredList [] = [] createSquaredList theList = [x^2 | x <- theList] -- 2.b -- createSquareRootList :: (Integral a) => [a] -> [a] createSquareRootList theList = [truncate $ sqrt $ fromIntegral n | n <- theList, isSquare n] isSquare :: (Integral a) => a -> Bool isSquare num = num == (^2) (floor $ sqrt $ fromIntegral num) -- 2.c -- getVowelFreeString :: String -> String getVowelFreeString theString = [c | c <- theString, not $ isVowel c] isVowel :: Char -> Bool isVowel c = elem c ['a', 'e', 'i', 'o', 'u'] isConsonant :: Char -> Bool isConsonant c = not $ isVowel c -- 2.d -- generateTwoSixSidedDiceThatValueSeven :: [[Int]] generateTwoSixSidedDiceThatValueSeven = [[dieOne, dieTwo] | dieOne <- [1..6], dieTwo <- [1..6], dieOne + dieTwo == 7] -- 2.e -- makingThreeSimpleSentences :: [String] -> [String] -> [(String, String, String)] makingThreeSimpleSentences namesList verbsList = take 3 [(subject, verb, object) | subject <- namesList, verb <- verbsList, object <- namesList, subject /= object]
pegurnee/2015-01-341
projects/project3_mini_haskell/haskell_mini_project.hs
mit
1,146
0
9
252
430
235
195
28
1
{-| Module : Language.SAL.Helpers Description : Helper functions for constructing SAL syntax Copyright : (c) Galois Inc, 2015 License : MIT Maintainer : Benjamin F Jones <bjones@galois.com> Stability : experimental Portability : Yes -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE FlexibleInstances #-} module Language.SAL.Helpers ( -- * Operators (#=) , (.=) , (./=) , (.<) , (.>) , (.<=) , (.>=) , (.&&) , (.||) , (.=>) , (.<=>) , (.+) , (.-) , (.*) , (./) -- * Concise constructors , lhs , lhs' , rhs , rhsIn , decl ) where import Language.SAL.Syntax -- Syntax Operators ---------------------------------------------------- infix 1 #= (#=) :: Lhs -> RhsDefinition -> SimpleDefinition (#=) = SimpleDefinition -- Infix Operators ----------------------------------------------------- -- fixity to match Haskell ops infixl 7 .*, ./ infixl 6 .+, .- infix 4 .=, ./=, .<, .>, .<=, .>= infixr 3 .&& infixr 2 .|| (.=) :: Expr -> Expr -> Expr x .= y = InfixApp x "=" y (./=) :: Expr -> Expr -> Expr x ./= y = InfixApp x "/=" y (.<) :: Expr -> Expr -> Expr x .< y = InfixApp x "<" y (.>) :: Expr -> Expr -> Expr x .> y = InfixApp x ">" y (.<=) :: Expr -> Expr -> Expr x .<= y = InfixApp x "<=" y (.>=) :: Expr -> Expr -> Expr x .>= y = InfixApp x ">=" y (.&&) :: Expr -> Expr -> Expr x .&& y = InfixApp x "AND" y (.||) :: Expr -> Expr -> Expr x .|| y = InfixApp x "OR" y (.=>) :: Expr -> Expr -> Expr x .=> y = InfixApp x "=>" y (.<=>) :: Expr -> Expr -> Expr x .<=> y = InfixApp x "<=>" y (.+) :: Expr -> Expr -> Expr x .+ y = InfixApp x "+" y (.-) :: Expr -> Expr -> Expr x .- y = InfixApp x "-" y (.*) :: Expr -> Expr -> Expr x .* y = InfixApp x "*" y (./) :: Expr -> Expr -> Expr x ./ y = InfixApp x "/" y -- Concise constructors ------------------------------------------------ lhs :: Identifier -> Lhs lhs v = LhsCurrent v [] lhs' :: Identifier -> Lhs lhs' v = LhsNext v [] rhs :: Expr -> RhsDefinition rhs = RhsExpr rhsIn :: Expr -> RhsDefinition rhsIn = RhsSelection decl :: IsType t => Identifier -> t -> VarDecl decl n t = VarDecl n (toType t) -- Typeclass Helpers --------------------------------------------------- -- | Easily embed components in a 'Type' class IsType a where toType :: a -> Type instance IsType BasicType where toType = TyBasic instance IsType Identifier where toType = TyName instance IsType (Integer,Integer) where toType (Numeral->x, Numeral->y) = TySubRange (Bound (NumLit x)) (Bound (NumLit y))
GaloisInc/language-sal
src/Language/SAL/Helpers.hs
mit
2,561
0
10
574
878
493
385
80
1
module Main where import Test.Tasty (TestTree, defaultMain, testGroup) import Pager.PaperFormat.Test main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "All Tests" [ paperFormatSuite ]
NobbZ/pager
test/Test.hs
mit
269
0
6
89
62
36
26
8
1
main :: IO () -- main = do -- a <- getLine -- b <- getLine -- c <- getLine -- print [a,b,c] main = do rs <- sequence [getLine, getLine, getLine] print rs
timtian090/Playground
Haskell/LearnYouAHaskellForGreatGood/sequence.hs
mit
166
0
9
46
46
25
21
4
1
{-# LANGUAGE OverloadedStrings #-} module Feature.Blog ( visitUserSpecs ) where import TestImport import Helper.DB.SetupTeardown import Factory.Tag import Factory.Article import Factory.Comment visitUserSpecs :: Spec visitUserSpecs = ydescribe "visit initilal /blog" $ do ydescribe "has no contents" $ do yit "one can GET /blog" $ do get BlogViewR statusIs 200 yit "GET /blog" $ do get BlogViewR htmlAllContain "h1" "Article" htmlAllContain "h3" "no articles" ydescribe "has one contents" $ do yit "one can GET /blog" $ withDeleteArticleTable $ do let slug = "testSlug" insertArticleTable slug --when blog has article, one can get BlogArticle get $ PermalinkR slug statusIs 200 htmlAllContain "h2" "test" htmlAllContain "article" "test post" ydescribe "has one content" $ do yit "when article has no comment" $ withDeleteCommentTable $ do let slug = "testSlug" insertArticleTable slug --when blog has article, one can get BlogArticle get $ PermalinkR slug statusIs 200 htmlAnyContain "h3" "There are no comment in this article" yit "when article has one comment" $ withDeleteCommentTable $ do let slug = "testSlug" insertCommentTable slug get $ PermalinkR slug statusIs 200 htmlAnyContain "article" "test comment" ydescribe "Blog has rss Feed img" $ do yit "GET /blog then html has img tag which contains feed-icon" $ do get BlogViewR htmlAllContain "img" "feed-icon" ydescribe "Blog has search form" $ do yit "GET /blog then html has .form-search" $ do get BlogViewR htmlAllContain "form" "form-search" ydescribe "Blog has search path" $ do ydescribe "Blog has no contents" $ do yit "GET /search" $ do get SearchR statusIs 200 htmlAnyContain "p" "no match" yit "GET /search?q=test" $ do request $ do setMethod "GET" setUrl SearchR addGetParam "q" "test post" statusIs 200 htmlAnyContain "p" "no match" ydescribe "Blog has one contents" $ do yit "one can get search result" $ withDeleteArticleTable $ do let slug = "testSlug" insertArticleTable slug --when blog has article, one can get BlogArticle request $ do setMethod "GET" setUrl SearchR addGetParam "q" "test post" statusIs 200 htmlAnyContain "p" "test post" ydescribe "Article has tag" $ do yit "GET TagR 'tag'" $ withDeleteTagTable $ do insertTagTable get $ TagR "tag" statusIs 200 ydescribe "Blog has sidebar" $ do yit "GET /blog then html has .span3" $ do get BlogViewR htmlAllContain "body" "col-md-3" htmlAllContain "body" "align=\"right\"" ydescribe "/blog contains footer" $ do yit "footer contains Code" $ do get BlogViewR let source = "Code" htmlAllContain "footer" source yit "footer contains License" $ do get BlogViewR let license = "MIT License" htmlAllContain "footer" license
cosmo0920/Ahblog
tests/Feature/Blog.hs
mit
3,365
0
23
1,117
717
291
426
90
1
{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} module Bonlang.Runtime ( Scope , BonHandle(..) , OutputHandle , InputHandle , eval , startEval , nullScope , getReference , isReferenceDefined , defineReference , primitiveBindings , liftThrows ) where import Bonlang.ErrorMessages import Bonlang.Lang import Bonlang.Lang.Types import Bonlang.Runtime.Primitives import Control.Monad.IO.Class (liftIO) import qualified Control.Monad.Loops as Loops import Control.Monad.Trans.Except as Except import qualified Data.IORef as IORef import qualified Data.List as L import qualified Data.Map as M import Data.Maybe (fromJust, isJust, isJust, isNothing) import qualified System.IO as IO -- | Adhoc types to use as phantoms for handles, useful for testing input and -- | output from specific IO sources data OutputHandle data InputHandle data BonHandle a = BonHandle IO.Handle type Bindings = M.Map String BonlangValue type Scope = IORef.IORef Bindings nullScope :: IO.IO Scope nullScope = IORef.newIORef M.empty getReference :: Scope -> BonlangValue -> IOThrowsException BonlangValue getReference scope (BonlangRefLookup name) = do s <- liftIO $ IORef.readIORef scope let maybeVal = M.lookup name s maybe (Except.throwE $ UnboundReference name) return maybeVal getReference _ value = Except.throwE $ InternalTypeMismatch "Can't lookup" [value] isReferenceDefined :: Scope -> String -> IO Bool isReferenceDefined scope name = isJust . M.lookup name <$> IORef.readIORef scope defineReference :: Scope -> BonlangValue -> IOThrowsException BonlangValue defineReference scope x = case x of BonlangAlias name value -> define' name value bad -> error' bad where define' name value = do alreadyDefined <- liftIO $ isReferenceDefined scope name if alreadyDefined then Except.throwE $ DefaultError "alreadyDefined" else writeReference scope name value error' bad = Except.throwE $ InternalTypeMismatch "Can't define reference" [bad] writeReference :: Scope -> String -> BonlangValue -> IOThrowsException BonlangValue writeReference scope name value = liftIO $ do s <- IORef.readIORef scope IORef.writeIORef scope $ M.insert name value s return value primitiveBindings :: BonHandle InputHandle -> BonHandle OutputHandle -> IO Scope primitiveBindings (BonHandle _) (BonHandle out) = nullScope >>= flip bindVars (M.fromList primitives') where primitives' :: [(String, BonlangValue)] primitives' = ioPrimitives out ++ primitives bindVars :: Scope -> M.Map String BonlangValue -> IO Scope bindVars scope bindings = do s <- IORef.readIORef scope r <- extendScope (M.toList bindings) (M.toList s) IORef.newIORef r where extendScope bds s = fmap (M.fromList . (++ s)) (mapM return bds) startEval :: Scope -> BonlangValue -> IOThrowsException BonlangValue startEval s (BonlangDirective dir@(ModuleDef m _ is at)) = if m == "Main" then if hasMain is then evalDirective s dir else Except.throwE $ noMainFunction at else Except.throwE $ noMainModule at where hasMain :: Bindings -> Bool hasMain moduleDefs = isJust $ M.lookup "main" moduleDefs startEval _ x = Except.throwE $ cantStartNonModule x eval :: Scope -> BonlangValue -> IOThrowsException BonlangValue eval _ x@BonlangString {} = return x eval _ x@BonlangNumber {} = return x eval _ x@BonlangBool {} = return x eval _ x@BonlangClosure {} = return x eval s (BonlangDirective dir) = evalDirective s dir eval s (BonlangBlock is) = do l <- last <$> sequence (fmap (eval s) is) evalUntilReduced s l eval s (BonlangList xs) = evalList s xs eval s x@BonlangRefLookup {} = getReference s x eval s (BonlangFuncApply x@BonlangPrimFunc {} ps) = evalList s ps >>= runPrim x s eval s (BonlangFuncApply x@BonlangPrimIOFunc {} ps) = evalList s ps >>= runPrim x s eval s (BonlangFuncApply x@BonlangClosure {} ps) = evalList s ps >>= evalClosure s x . unList eval s (BonlangFuncApply r ps) = do ref' <- getReference s r if isReduced ref' then do evaledPs <- evalList s ps if isPrimFunction ref' then runPrim ref' s evaledPs else evalClosure s ref' (unList evaledPs) else do evald' <- eval s ref' eval s (BonlangFuncApply evald' ps) eval s x@BonlangAlias {} = if aliasName x == "main" then eval s (aliasExpression x) else defineReference s x eval s x@BonlangIfThenElse {} = do x' <- evalUntilReduced s $ condition x case x' of BonlangBool True -> eval s $ valueTrue x _ -> eval s $ valueFalse x -- TODO: Clean this up -- TODO: This ranks on my "Top 10 ugliest code", pls forgive me -- TODO: This isn't well tested! eval s x@BonlangPatternMatch {} = do toMatch <- evalUntilReduced s (match x) let maybeClause = L.find (matchingClause toMatch) (clauses x) case maybeClause of Just clause -> evalMatchedClause s clause toMatch Nothing -> Except.throwE $ DefaultError "No match" where matchingClause val ( p, _ ) = matchValue val p matchValue val p = case p of ScalarPattern scalar -> scalar == val ListPattern xs rest -> case val of BonlangList ys -> matchList xs rest ys _ -> False ReferencePattern _ -> True RegexPattern _ -> undefined WildcardPattern -> True matchList xs rest ys -- Trying to match a smaller list -- i.e. `match [1, 2] { [x, y, z] -> ... }` does not match | isNothing rest = length xs == length ys -- Matching exact length lists, or shorter, values must -- match, and `rest` can be present -- i.e. -- `match [1, 2] { [x, y] -> ... } => x = 1, y = 2` -- `match [1, 2, 3] { [ x, y | xs ] -> ... } => x = 1, y = 2, xs = [3]` | otherwise = length ys >= length xs && all (uncurry matchValue) (zip ys xs) evalMatchedClause s' (p, v) matchedValue = case p of ListPattern xs rest -> evalMatchedList s' xs rest matchedValue (eval s' v) _ -> eval s' v -- val = [ 1, 2 ], pattern = [ x | xs ] -- => x = 1, xs = [2] -- val = [ 1, 2, 3 ], pattern = [ x, y | xs ] -- => x = 1, y = 2, xs = [3] -- val = [ 1, 2, 3 ], pattern = [ x, y, z | xs ] -- => x = 1, y = 2, z, = 3, xs = [] -- val = [ 1, 2, 3 ], pattern = [ x | _ ] -- => x = 1 evalMatchedList s' (ReferencePattern ref : xs) rest (BonlangList (y : ys)) end = writeReference s' ref y >> evalMatchedList s' xs rest (BonlangList ys) end evalMatchedList s' (_ : xs) rest (BonlangList (_ : ys)) end = evalMatchedList s' xs rest (BonlangList ys) end evalMatchedList s' [] (Just (ReferencePattern ref)) ys@(BonlangList _) end = writeReference s' ref ys >> end evalMatchedList _ [] Nothing (BonlangList _) end = end evalMatchedList _ [] (Just WildcardPattern) (BonlangList _) end = end evalMatchedList _ _ _ _ _ = Except.throwE $ InternalTypeMismatch "Invalid match statement" [] eval _ x = Except.throwE $ InternalTypeMismatch "Don't know how to eval" [x] evalList :: Scope -> [BonlangValue] -> IOThrowsException BonlangValue evalList s xs = do xs' <- sequence $ evalUntilReduced s <$> xs return $ BonlangList xs' evalUntilReduced :: Scope -> BonlangValue -> IOThrowsException BonlangValue evalUntilReduced s = Loops.iterateUntilM isReduced (eval s) isReduced :: BonlangValue -> Bool isReduced (BonlangList xs) = all isReduced xs isReduced x = isScalar x || isFunction x || isPrimFunction x evalClosure :: Scope -> BonlangValue -> [BonlangValue] -> IOThrowsException BonlangValue evalClosure s c@BonlangClosure {} ps = do s' <- liftIO $ IORef.readIORef s let u = M.union if | notEnoughParams -> return BonlangClosure { cParams = cParams c , cEnv = cEnv c `u` newParams , cBody = cBody c } | tooManyParams -> Except.throwE $ DefaultError "Too many params applied" | otherwise -> do let cBody' = cBody c let newScope = newParams `u` cEnv c `u` s' let primArgs = map snd $ M.toList $ cEnv c `u` newParams s'' <- liftIO $ IORef.newIORef newScope case cBody' of f@BonlangPrimFunc {} -> evalList s'' primArgs >>= runPrim f s'' g@BonlangPrimIOFunc {} -> evalList s'' primArgs >>= runPrim g s'' BonlangClosure {} -> evalClosure s'' cBody' newArgs _ -> eval s'' cBody' where notEnoughParams = existingArgs + length ps < length (cParams c) tooManyParams = existingArgs + length ps > length (cParams c) existingArgs = length $ M.toList (cEnv c) newParams = M.fromList $ zip (drop existingArgs $ cParams c) ps newArgs = map snd $ M.toList newParams evalClosure _ x _ = Except.throwE $ InternalTypeMismatch "Can't eval non closure" [x] runPrim :: BonlangValue -> Scope -> BonlangValue -> IOThrowsException BonlangValue runPrim (BonlangPrimIOFunc f) s (BonlangList ps) = do params <- mapM (eval s) ps f params runPrim (BonlangPrimFunc f) s (BonlangList ps) = do params <- mapM (eval s) ps liftThrows $ f params runPrim x _ _ = Except.throwE $ InternalTypeMismatch "Can't run primary function application on non-primary" [x] evalDirective :: Scope -> BonlangDirectiveType -> IOThrowsException BonlangValue evalDirective s (ModuleDef _ _ is _) = do sequence_ (fmap (\(_, f) -> defineReference s f) is') evalClosure s (aliasExpression . fromJust $ M.lookup "main" is) [] where is' = filter (\(f,_) -> f /= "main") (M.toList is) evalDirective _ (ModuleImport _) = error "TODO: Module imports" evalDirective _ _ = Except.throwE $ InternalTypeMismatch "Attempting eval directive for undefined" [] liftThrows :: ThrowsError a -> IOThrowsException a liftThrows (Left err) = Except.throwE err liftThrows (Right x) = return x
charlydagos/bonlang
src/Bonlang/Runtime.hs
mit
11,227
0
17
3,650
3,135
1,557
1,578
-1
-1
import Control.Concurrent import GHCJS.CommonJS (exportMain, exports) helloWorld = putStrLn "[haskell] Hello World" launchTheMissiles :: IO Int launchTheMissiles = do threadDelay (1000 * 1000 * 5) putStrLn "[haskell] OMG what did I do?!" return 10 main = exportMain [ "helloWorld" `exports` helloWorld , "launchTheMissiles" `exports` launchTheMissiles ]
beijaflor-io/ghcjs-commonjs
examples/webpack/hs/Main.hs
mit
421
0
10
113
95
50
45
12
1
{-# LANGUAGE OverloadedStrings #-} module MuevalSlack.Configuration ( getConfiguration ) where import Data.Configurator (Worth(Required), load, require) import Data.Configurator.Types (Config) parseConfiguration :: Config -> IO String parseConfiguration = flip require "access_token" getConfiguration :: FilePath -> IO String getConfiguration path = load [Required path] >>= parseConfiguration
zalora/slack-mueval
src/MuevalSlack/Configuration.hs
mit
400
0
8
49
98
55
43
9
1
{-# LANGUAGE TemplateHaskell, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} -- for the ~ type signature trick module Propositions (module Propositions, string2Name) where import Text.Parsec import Text.Parsec.Expr import Text.Parsec.String import Data.Functor.Identity import Control.Monad import Data.List import Utils import Unbound.LocallyNameless hiding (Infix) type Var = Name Term -- This could be made more abstract as in the unification-fd package data Term = App Term [Term] | V Var | C Var | Lam (Bind Var Term) deriving Show $(derive [''Term]) data OpAssoc = L | R instance Alpha Term instance Eq Term where (==) = aeq instance Subst Term Term where isvar (V v) = Just (SubstName v) isvar (C v) = Just (SubstName v) isvar _ = Nothing firstFree :: Alpha a => a -> Integer firstFree = (1+) . maximum . (0:) . map anyName2Integer . fvAny type Proposition = Term absTerm :: [Var] -> Term -> Term absTerm vs t = foldr mkLam t vs mkLam :: Var -> Term -> Term mkLam v t = Lam (bind v (const2Var [v] t)) mkApps :: Term -> [Term] -> Term mkApps t [] = t mkApps t ts = App t ts const2Var :: [Var] -> Term -> Term const2Var vs = substs [(v, V v) | v <- vs] name2ExternalString :: Var -> String name2ExternalString n | name2Integer n == 0 = name2String n | otherwise = error $ "name2ExternalString: Invalid external name " ++ show n -- Pretty printer printTerm :: Proposition -> String printTerm p = runLFreshM (avoid (fvAny p) $ prP (0::Int) p) "" where prP :: Int -> Proposition -> LFreshM (String -> String) prP _ (C v) = prN v prP _ (V v) = prN v prP d (App (C f) [a]) | Just p <- isPrefix (name2String f) = prParens (p < d) $ prN f <> prP p a prP d (App (C f) [a1, a2]) | Just (p,_assoc) <- isInFix (name2String f) = prParens (p < d) $ prP (p+1) a1 <> prN f <> prP (p+1) a2 prP d (App (C f) [Lam b]) | isQuant (name2String f) = prParens (1 < d) $ lunbind b $ \(v,t) -> prN f <> prN v <> prS "." <> prP 1 t prP _ (App f args) = prP 4 f <> prS "(" <> prCommas [prP 0 a | a <- args] <> prS ")" prP d (Lam b) = prParens (1 < d) $ lunbind b $ \(v,t) -> prS "Λ" <> prN v <> prS "." <> prP 1 t prN n = prS (name2String n) <> (if i > 0 then prS (map subscriptify (show i)) else return id) where i = name2Integer n prParens :: Bool -> LFreshM (String -> String) -> LFreshM (String -> String) prParens True f = prS "(" <> f <> prS ")" prParens False f = f prCommas = foldr (<>) (return id) . intersperse (prS ",") prS str = return (str++) (<>) :: t ~ LFreshM (String -> String) => t -> t -> t (<>) = liftM2 (.) -- Is it infix? What precedences? isInFix :: String -> Maybe (Int, OpAssoc) isInFix "⋅" = Just (7, L) isInFix "↑" = Just (5, L) isInFix "∧" = Just (4, L) isInFix "∨" = Just (4, L) isInFix "→" = Just (3, R) isInFix ":" = Just (2, R) isInFix _ = Nothing isQuant :: String -> Bool isQuant = (`elem` words "∃ ∀ λ") isPrefix :: String -> Maybe Int isPrefix "¬" = Just 6 isPrefix _ = Nothing -- Parser parseTerm :: String -> Either String Proposition parseTerm = either (Left . show) Right . parse (between spaces eof termP) "" -- For Testing and GHCi readTerm :: String -> Proposition readTerm = either (error . show) id . parseTerm -- lexeme l :: Parser a -> Parser a l = (<* (spaces <?> "")) termP :: Parser Proposition termP = buildExpressionParser table atomP <?> "proposition" table :: OperatorTable String () Identity Proposition table = [ [ binary "⋅" [] AssocLeft ] , [ binary "↑" ["^"] AssocLeft ] , [ binary "∧" ["&"] AssocLeft ] , [ binary "∨" ["|"] AssocLeft ] , [ binary "→" ["->"] AssocRight ] , [ binary ":" [] AssocRight ] ] where binary op alts assoc = Infix ((\a b -> App (C (string2Name op)) [a,b]) <$ l (choice (map string (op:alts)))) assoc quantifiers :: [(Char, [Char])] quantifiers = [ ('∀', ['!']) , ('∃', ['?']) , ('λ', ['\\']) , ('Λ', []) ] mkQuant :: String -> Var -> Term -> Term mkQuant "Λ" n t = mkLam n t mkQuant q n t = App (C (string2Name q)) [mkLam n t] quantP :: Parser String quantP = l $ choice [ (q:"") <$ choice (map char (q:a)) | (q,a) <- quantifiers ] atomP :: Parser Proposition atomP = choice [ l $ string "⊥" >> return (c "⊥") , l $ string "⊤" >> return (c "⊤") , l $ try (string "False") >> return (c "⊥") , l $ try (string "True") >> return (c "⊤") , do _ <- l $ char '¬' <|> char '~' p <- atomP return $ s "¬" [p] , do q <- quantP vname <- nameP _ <- l $ char '.' p <- termP return $ mkQuant q vname $ p , parenthesized termP , do head <- varOrConstP option head $ parenthesized $ App head <$> termP `sepBy1` (l $ char ',') ] where c n = C (string2Name n) s n = App (c n) parenthesized = between (l $ char '(') (l $ char ')') varOrConstP :: Parser Term varOrConstP = choice [ do -- A hack for the test suite etc: prepending the name of a constant with V -- makes it a variable _ <- try (string "V ") num <- l $ option 0 (read <$> many1 digit) s <- l $ many1 alphaNum return $ V $ makeName s num , C <$> nameP ] nameP :: Rep a => Parser (Name a) nameP = l $ string2Name <$> many1 (alphaNum <|> char '_')
nomeata/incredible
logic/Propositions.hs
mit
5,607
0
16
1,561
2,465
1,265
1,200
143
9
module Main where import qualified Data.Attoparsec.Text as D import qualified Data.Text as G import qualified Data.Vector as E import qualified Main.Sample as C import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck import Test.Tasty.Runners import qualified VectorBuilder.Alternative as F import qualified VectorBuilder.Builder as A import qualified VectorBuilder.MonadPlus as H import qualified VectorBuilder.Vector as B import Prelude main = defaultMain $ testGroup "All tests" [ testProperty "samples" $ \(samples :: [C.Sample Int]) -> foldMap C.toVector samples === B.build (foldMap C.toBuilder samples), testCase "Alternative.some" $ assertEqual "" (Right (E.fromList "1234")) (D.parseOnly (F.some D.anyChar) "1234"), testCase "Alternative.some on empty" $ assertEqual "" (Left "not enough input") (D.parseOnly (F.some D.anyChar :: D.Parser (Vector Char)) ""), testProperty "mconcat" $ \(samples :: [C.Sample Int]) -> foldMap C.toVector samples === B.build (mconcat (map C.toBuilder samples)), testProperty "foldable" $ \(elements :: [Int]) -> E.fromList elements === B.build (A.foldable elements), testGroup "MonadPlus" [ testProperty "many" $ \(elements :: [Char]) -> Right (E.fromList elements) === D.parseOnly (H.many D.anyChar) (fromString elements), testProperty "many1" $ \(elements :: [Char]) -> ( if null elements then Left "not enough input" else Right (E.fromList elements) ) === D.parseOnly (H.many1 D.anyChar) (fromString elements), testProperty "sepBy1" $ \(elements :: [Char]) -> ( if null elements then Left "not enough input" else Right (E.fromList elements) ) === D.parseOnly (H.sepBy1 D.anyChar (D.char ',')) (G.intersperse ',' (fromString elements)) ] ]
nikita-volkov/vector-builder
tests/Main.hs
mit
2,164
0
18
685
633
340
293
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell, OverloadedStrings, QuasiQuotes, NamedFieldPuns #-} module Control.OperationalTransformation.JSON.Specs where import qualified Control.OperationalTransformation as C import Control.OperationalTransformation.JSON import Control.OperationalTransformation.JSON.QuasiQuote import Control.OperationalTransformation.JSON.Types import Data.Aeson as A import Test.Hspec import Test.Tasty import Test.Tasty.Hspec -- These tests are taken directly from -- https://github.com/ottypes/json0/blob/master/test/json0.coffee apply :: A.Value -> JSONOperation -> A.Value apply input op = case C.apply op input of Left err -> error err Right x -> x compose :: JSONOperation -> JSONOperation -> JSONOperation compose op1 op2 = case C.compose op1 op2 of Left err -> error err Right operation -> operation transform :: JSONOperation -> JSONOperation -> (JSONOperation, JSONOperation) transform op1 op2 = case C.transform op1 op2 of Left err -> error err Right x -> x transformLeft :: JSONOperation -> JSONOperation -> JSONOperation transformLeft a b = a' where (a', _) = transform a b transformRight :: JSONOperation -> JSONOperation -> JSONOperation transformRight a b = b' where (_, b') = transform a b shouldBe' :: (Eq a, Show a) => a -> a -> Expectation shouldBe' = flip shouldBe specs :: SpecWith () specs = do describe "sanity" $ do describe "compose()" $ do it "od,oi --> od+oi" $ do shouldBe' [l|[{"p":["foo"], "od":1, "oi":2}]|] (compose [s|{"p":["foo"], "od":1}|] [s|{"p":["foo"], "oi":2}|]) shouldBe' [l|[{"p":["foo"], "od":1}, {"p":["bar"], "oi":2}]|] (compose [s|{"p":["foo"], "od":1}|] [s|{"p":["bar"], "oi":2}|]) it "merges od+oi, od+oi -> od+oi" $ do shouldBe' [l|[{"p":["foo"], "od":1, "oi":2}]|] (compose [s|{"p":["foo"], "od":1, "oi":3}|] [s|{"p":["foo"], "od":3, "oi":2}|]) describe "transform() stuff" $ do it "returns sane values" $ do let t = \op1 op2 -> op1 `shouldBe'` transformLeft op1 op2 t [s|{}|] [s|{}|] t [s|{"p":["foo"], "oi":1}|] [s|{}|] t [s|{"p":["foo"], "oi":1}|] [s|{"p":["bar"], "oi":2}|] t [s|{"p":["foo"], "oi":1}|] [s|{"p":["bar"], "oi":2}|] describe "number" $ do it "Adds a number" $ do shouldBe' [v|3|] (apply [v|1|] [s|{"p":[], "na":2}|]) shouldBe' [v|[3]|] (apply [v|[1]|] [s|{"p":[0], "na":2}|]) it "transforms adds" $ do shouldBe' [s|{"p":[], "na": 0}|] (transformRight [s|{"p":[], "na": 0}|] [s|{"p":[], "na": 0}|]) it "compresses two adds together in compose" $ do shouldBe' [l|[{"p":["a", "b"], "na":3}]|] (compose [s|{"p":["a", "b"], "na":1}|] [s|{"p":["a", "b"], "na":2}|]) -- shouldBe' [s|{"p":["a"], "na":1}, {"p":["b"], "na":2}], type.compose [{"p":["a"], "na":1}], [{"p":["b"], "na":2}] -- # Strings should be handled internally by the text type. We"ll just do some basic sanity checks here. describe "string" $ do describe "apply()" $ it "works" $ do shouldBe' [v|"abc"|] (apply [v|"a"|] [s|{"p":[1], "si":"bc"}|]) shouldBe' [v|"bc"|] (apply [v|"abc"|] [s|{"p":[0], "sd":"a"}|]) shouldBe' [v|{x:"abc"}|] (apply [v|{x:"a"}|] [s|{"p":["x", 1], "si":"bc"}|]) describe "transform()" $ do it "splits deletes" $ do shouldBe' [l|[{"p":[0], "sd":"a"}, {"p":[1], "sd":"b"}]|] (transformLeft [l|[{"p":[0], "sd":"ab"}]|] [l|[{"p":[1], "si":"x"}]|]) it "cancels out other deletes" $ do shouldBe' [l|[]|] (transformLeft [s|{"p":["k", 5], "sd":"a"}|] [s|{"p":["k", 5], "sd":"a"}|]) it "does not throw errors with blank inserts" $ do shouldBe' [s|{}|] (transformLeft [s|{"p": ["k", 5], "si":""}|] [s|{"p": ["k", 3], "si": "a"}|]) describe "string subtype" $ do describe "apply()" $ do it "works" $ do shouldBe [v|"abc"|] (apply [v|"a"|] [s|{"p":[], "t":"text0", "o":[{"p":1, "i":"bc"}]}|]) shouldBe [v|{x:"abc"}|] (apply [v|{x:"a"}|] [s|{"p":["x"], "t":"text0", "o":[{"p":1, "i":"bc"}]}|]) shouldBe [v|"bc"|] (apply [v|"abc"|] [s|{"p":[], "t":"text0", "o":[{"p":0, "d":"a"}]}|]) describe "transform()" $ do it "splits deletes" $ do let a = [s|{"p":[], "t":"text0", "o":[{"p":0, "d":"ab"}]}|] let b = [s|{"p":[], "t":"text0", "o":[{"p":1, "i":"x"}]}|] shouldBe' [s|{"p":[], "t":"text0", "o":[{"p":0, "d":"a"}, {"p":1, "d":"b"}]}|] (transformLeft a b) it "cancels out other deletes" $ do shouldBe' [s|{}|] (transformLeft [s|{"p":["k"], "t":"text0", "o":[{"p":5, "d":"a"}]}|] [s|{"p":["k"], "t":"text0", "o":[{"p":5, "d":"a"}]}|]) it "does not throw errors with blank inserts" $ do shouldBe' [s|{}|] (transformLeft [s|{"p":["k"], "t":"text0", "o":[{"p":5, "i":""}]}|] [s|{"p":["k"], "t":"text0", "o":[{"p":3, "i":"a"}]}|]) describe "list" $ do describe "apply" $ do it "inserts" $ do shouldBe' [v|["a", "b", "c"]|] (apply [v|["b", "c"]|] [s|{"p":[0], "li":"a"}|]) shouldBe' [v|["a", "b", "c"]|] (apply [v|["a", "c"]|] [s|{"p":[1], "li":"b"}|]) shouldBe' [v|["a", "b", "c"]|] (apply [v|["a", "b"]|] [s|{"p":[2], "li":"c"}|]) it "deletes" $ do shouldBe' [v|["b", "c"]|] (apply [v|["a", "b", "c"]|] [s|{"p":[0], "ld":"a"}|]) shouldBe' [v|["a", "c"]|] (apply [v|["a", "b", "c"]|] [s|{"p":[1], "ld":"b"}|]) shouldBe' [v|["a", "b"]|] (apply [v|["a", "b", "c"]|] [s|{"p":[2], "ld":"c"}|]) it "replaces" $ do shouldBe' [v|["a", "y", "b"]|] (apply [v|["a", "x", "b"]|] [s|{"p":[1], "ld":"x", "li":"y"}|]) it "moves" $ do shouldBe' [v|["a", "b", "c"]|] (apply [v|["b", "a", "c"]|] [s|{"p":[1], "lm":0}|]) shouldBe' [v|["a", "b", "c"]|] (apply [v|["b", "a", "c"]|] [s|{"p":[0], "lm":1}|]) it "null moves compose to nops" $ do shouldBe' [l|[]|] (compose [l|[]|] [l|[{"p":[3], "lm":3}]|]) shouldBe' [l|[]|] (compose [l|[]|] [l|[{"p":[0,3], "lm":3}]|]) shouldBe' [l|[]|] (compose [l|[]|] [l|[{"p":["x","y",0], "lm":0}]|]) describe "transform()" $ do it "bumps paths when list elements are inserted or removed" $ do shouldBe' [s|{"p":[2, 200], "si":"hi"}|] (transformLeft [s|{"p":[1, 200], "si":"hi"}|] [s|{"p":[0], "li":"x"}|]) shouldBe' [s|{"p":[1, 201], "si":"hi"}|] (transformRight [s|{"p":[0], "li":"x"}|] [s|{"p":[0, 201], "si":"hi"}|]) shouldBe' [s|{"p":[0, 202], "si":"hi"}|] (transformLeft [s|{"p":[0, 202], "si":"hi"}|] [s|{"p":[1], "li":"x"}|]) shouldBe' [s|{"p":[2], "t":"text0", "o":[{"p":200, "i":"hi"}]}|] (transformLeft [s|{"p":[1], "t":"text0", "o":[{"p":200, "i":"hi"}]}|] [s|{"p":[0], "li":"x"}|]) shouldBe' [s|{"p":[1], "t":"text0", "o":[{"p":201, "i":"hi"}]}|] (transformRight [s|{"p":[0], "li":"x"}|] [s|{"p":[0], "t":"text0", "o":[{"p":201, "i":"hi"}]}|]) shouldBe' [s|{"p":[0], "t":"text0", "o":[{"p":202, "i":"hi"}]}|] (transformLeft [s|{"p":[0], "t":"text0", "o":[{"p":202, "i":"hi"}]}|] [s|{"p":[1], "li":"x"}|]) shouldBe' [s|{"p":[0, 203], "si":"hi"}|] (transformLeft [s|{"p":[1, 203], "si":"hi"}|] [s|{"p":[0], "ld":"x"}|]) shouldBe' [s|{"p":[0, 204], "si":"hi"}|] (transformLeft [s|{"p":[0, 204], "si":"hi"}|] [s|{"p":[1], "ld":"x"}|]) -- TODO: seems to be an invalid list insert -- shouldBe' [s|{"p":["x",3], "si": "hi"}|] (transformLeft [s|{"p":["x",3], "si":"hi"}|] [s|{"p":["x",0,"x"], "li":0}|]) shouldBe' [s|{"p":["x",3,2], "si": "hi"}|] (transformLeft [s|{"p":["x",3,2], "si":"hi"}|] [s|{"p":["x",5], "li":0}|]) shouldBe' [s|{"p":["x",4,2], "si": "hi"}|] (transformLeft [s|{"p":["x",3,2], "si":"hi"}|] [s|{"p":["x",0], "li":0}|]) shouldBe' [s|{"p":[1], "ld":2}|] (transformLeft [s|{"p":[0], "ld":2}|] [s|{"p":[0], "li":1}|]) shouldBe' [s|{"p":[1], "ld":2}|] (transformRight [s|{"p":[0], "li":1}|] [s|{"p":[0], "ld":2}|]) shouldBe' [s|{"p":[0], "t":"text0", "o":[{"p":203, "i":"hi"}]}|] (transformLeft [s|{"p":[1], "t":"text0", "o":[{"p":203, "i":"hi"}]}|] [s|{"p":[0], "ld":"x"}|]) shouldBe' [s|{"p":[0], "t":"text0", "o":[{"p":204, "i":"hi"}]}|] (transformLeft [s|{"p":[0], "t":"text0", "o":[{"p":204, "i":"hi"}]}|] [s|{"p":[1], "ld":"x"}|]) -- TODO: this looks like an invalid list insert because the list element is not a pos -- shouldBe' [s|{"p":["x"], "t":"text0", "o":[{"p":3, "i":"hi"}]}|] (transformLeft [s|{"p":["x"], "t":"text0", "o":[{"p":3, "i":"hi"}]}|] [s|{"p":["x",0,"x"], "li":0}|]) it "converts ops on deleted elements to noops" $ do shouldBe' [s|{}|] (transformLeft [s|{"p":[1, 0], "si":"hi"}|] [s|{"p":[1], "ld":"x"}|]) shouldBe' [s|{}|] (transformLeft [s|{"p":[1], "t":"text0", "o":[{"p":0, "i":"hi"}]}|] [s|{"p":[1], "ld":"x"}|]) shouldBe' [s|{"p":[0], "li":"x"}|] (transformLeft [s|{"p":[0], "li":"x"}|] [s|{"p":[0], "ld":"y"}|]) shouldBe' [s|{}|] (transformLeft [s|{"p":[0],"na":-3}|] [s|{"p":[0], "ld":48}|]) shouldBe' [s|{}|] (transformLeft [s|{"p":["baz863",2],"ld":2}|] [s|{"p":["baz863"],"od":[0,1,2,3]}|]) shouldBe' [s|{"p":["baz863"],"od":[0,1,3]}|] (transformRight [s|{"p":["baz863",2],"ld":2}|] [s|{"p":["baz863"],"od":[0,1,2,3]}|]) it "converts ops on replaced elements to noops" $ do shouldBe' [s|{}|] (transformLeft [s|{"p":[1, 0], "si":"hi"}|] [s|{"p":[1], "ld":"x", "li":"y"}|]) shouldBe' [s|{}|] (transformLeft [s|{"p":[1], "t":"text0", "o":[{"p":0, "i":"hi"}]}|] [s|{"p":[1], "ld":"x", "li":"y"}|]) shouldBe' [s|{"p":[0], "li":"hi"}|] (transformLeft [s|{"p":[0], "li":"hi"}|] [s|{"p":[0], "ld":"x", "li":"y"}|]) it "changes deleted data to reflect edits" $ do shouldBe' [s|{"p":[1], "ld":"abc"}|] (transformLeft [s|{"p":[1], "ld":"a"}|] [s|{"p":[1, 1], "si":"bc"}|]) shouldBe' [s|{"p":[1], "ld":"abc"}|] (transformLeft [s|{"p":[1], "ld":"a"}|] [s|{"p":[1], "t":"text0", "o":[{"p":1, "i":"bc"}]}|]) it "doesn't confuse unrelated operations" $ do let op1 = [s|{"p":["foo736"],"oi":null}|] let op2 = [s|{"p":["foo78",1],"ld":null}|] shouldBe' (op1, op2) (transform op1 op2) it "Puts the left op first if two inserts are simultaneous" $ do shouldBe' [s|{"p":[1], "li":"a"}|] (transformLeft [s|{"p":[1], "li":"a"}|] [s|{"p":[1], "li":"b"}|]) shouldBe' [s|{"p":[2], "li":"b"}|] (transformRight [s|{"p":[1], "li":"a"}|] [s|{"p":[1], "li":"b"}|]) it "converts an attempt to re-delete a list element into a no-op" $ do shouldBe' [s|{}|] (transformLeft [s|{"p":[1], "ld":"x"}|] [s|{"p":[1], "ld":"x"}|]) shouldBe' [s|{}|] (transformRight [s|{"p":[1], "ld":"x"}|] [s|{"p":[1], "ld":"x"}|]) describe "compose()" $ do it "composes insert then delete into a no-op" $ do shouldBe' [l|[{}]|] (compose [s|{"p":[1], "li":"abc"}|] [s|{"p":[1], "ld":"abc"}|]) shouldBe' [l|[{"p":[0], "ld":"abc"}]|] (compose [s|{"p":[0], "ld":"abc", "li":null}|] [s|{"p":[0], "ld":null}|]) shouldBe' [s|{"p":[1], "ld":null, "li":"x"}|] (transformRight [s|{"p":[0], "li":"The"}|] [s|{"p":[0], "ld":null, "li":"x"}|]) it "composes together adjacent string ops" $ do shouldBe' [l|[{"p":[100], "si":"hi"}]|] (compose [s|{"p":[100], "si":"h"}|] [s|{"p":[101], "si":"i"}|]) shouldBe' [l|[{"p":[], "t":"text0", "o":[{"p":100, "i":"hi"}]}]|] (compose [s|{"p":[], "t":"text0", "o":[{"p":100, "i":"h"}]}|] [s|{"p":[], "t":"text0", "o":[{"p":101, "i":"i"}]}|]) it "moves ops on a moved element with the element" $ do shouldBe' [s|{"p":[10], "ld":"x"}|] (transformLeft [s|{"p":[4], "ld":"x"}|] [s|{"p":[4], "lm":10}|]) shouldBe' [s|{"p":[10, 1], "si":"a"}|] (transformLeft [s|{"p":[4, 1], "si":"a"}|] [s|{"p":[4], "lm":10}|]) shouldBe' [s|{"p":[10], "t":"text0", "o":[{"p":1, "i":"a"}]}|] (transformLeft [s|{"p":[4], "t":"text0", "o":[{"p":1, "i":"a"}]}|] [s|{"p":[4], "lm":10}|]) shouldBe' [s|{"p":[10, 1], "li":"a"}|] (transformLeft [s|{"p":[4, 1], "li":"a"}|] [s|{"p":[4], "lm":10}|]) shouldBe' [s|{"p":[10, 1], "ld":"b", "li":"a"}|] (transformLeft [s|{"p":[4, 1], "ld":"b", "li":"a"}|] [s|{"p":[4], "lm":10}|]) shouldBe' [s|{"p":[0], "li":null}|] (transformLeft [s|{"p":[0], "li":null}|] [s|{"p":[0], "lm":1}|]) -- -- [_,_,_,_,5,6,7,_] -- -- c: [_,_,_,_,5,"x",6,7,_] p:5 "li":"x" -- -- s: [_,6,_,_,_,5,7,_] p:5 "lm":1 -- -- correct: [_,6,_,_,_,5,"x",7,_] shouldBe' [s|{"p":[6], "li":"x"}|] (transformLeft [s|{"p":[5], "li":"x"}|] [s|{"p":[5], "lm":1}|]) -- -- [_,_,_,_,5,6,7,_] -- -- c: [_,_,_,_,5,6,7,_] p:5 "ld":6 -- -- s: [_,6,_,_,_,5,7,_] p:5 "lm":1 -- -- correct: [_,_,_,_,5,7,_] shouldBe' [s|{"p":[1], "ld":6}|] (transformLeft [s|{"p":[5], "ld":6}|] [s|{"p":[5], "lm":1}|]) shouldBe' [s|{"p":[0], "li":{}}|] (transformRight [s|{"p":[0], "lm":0}|] [s|{"p":[0], "li":{}}|]) shouldBe' [s|{"p":[0], "li":[]}|] (transformLeft [s|{"p":[0], "li":[]}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[2], "li":"x"}|] (transformLeft [s|{"p":[2], "li":"x"}|] [s|{"p":[0], "lm":1}|]) it "moves target index on ld/li" $ do shouldBe' [s|{"p":[0], "lm":1}|] (transformLeft [s|{"p":[0], "lm": 2}|] [s|{"p":[1], "ld":"x"}|]) shouldBe' [s|{"p":[1], "lm":3}|] (transformLeft [s|{"p":[2], "lm": 4}|] [s|{"p":[1], "ld":"x"}|]) shouldBe' [s|{"p":[0], "lm":3}|] (transformLeft [s|{"p":[0], "lm": 2}|] [s|{"p":[1], "li":"x"}|]) shouldBe' [s|{"p":[3], "lm":5}|] (transformLeft [s|{"p":[2], "lm": 4}|] [s|{"p":[1], "li":"x"}|]) shouldBe' [s|{"p":[1], "lm":1}|] (transformLeft [s|{"p":[0], "lm": 0}|] [s|{"p":[0], "li":28}|]) it "tiebreaks lm vs. ld/li" $ do shouldBe' [s|{}|] (transformLeft [s|{"p":[0], "lm": 2}|] [s|{"p":[0], "ld":"x"}|]) shouldBe' [s|{}|] (transformRight [s|{"p":[0], "ld":"x"}|] [s|{"p":[0], "lm": 2}|]) shouldBe' [s|{"p":[1], "lm":3}|] (transformLeft [s|{"p":[0], "lm": 2}|] [s|{"p":[0], "li":"x"}|]) shouldBe' [s|{"p":[1], "lm":3}|] (transformRight [s|{"p":[0], "li":"x"}|] [s|{"p":[0], "lm": 2}|]) it "replacement vs. deletion" $ do shouldBe' [s|{"p":[0], "li":"y"}|] (transformRight [s|{"p":[0], "ld":"x"}|] [s|{"p":[0], "ld":"x", "li":"y"}|]) shouldBe' [s|{}|] (transformLeft [s|{"p":[0], "ld":"x"}|] [s|{"p":[0], "ld":"x", "li":"y"}|]) it "replacement vs. insertion" $ do shouldBe' [s|{"p":[1], "ld":{}, "li":"brillig"}|] (transformLeft [s|{"p":[0], "ld":{}, "li":"brillig"}|] [s|{"p":[0], "li":36}|]) it "replacement vs. replacement" $ do shouldBe' [s|{}|] (transformRight [s|{"p":[0], "ld":null, "li":0}|] [s|{"p":[0], "ld":null, "li":[]}|]) shouldBe' [s|{"p":[0], "ld":[], "li":0}|] (transformLeft [s|{"p":[0], "ld":null, "li":0}|] [s|{"p":[0], "ld":null, "li":[]}|]) it "composes replace with delete of replaced element results in insert" $ do shouldBe' [l|[{"p":[2], "ld":[]}]|] (compose [s|{"p":[2], "ld":[], "li":null}|] [s|{"p":[2], "ld":null}|]) it "lm vs lm" $ do shouldBe' [s|{"p":[0], "lm":2}|] (transformLeft [s|{"p":[0], "lm":2}|] [s|{"p":[2], "lm":1}|]) shouldBe' [s|{"p":[4], "lm":4}|] (transformLeft [s|{"p":[3], "lm":3}|] [s|{"p":[5], "lm":0}|]) shouldBe' [s|{"p":[2], "lm":0}|] (transformLeft [s|{"p":[2], "lm":0}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[2], "lm":1}|] (transformRight [s|{"p":[1], "lm":0}|] [s|{"p":[2], "lm":0}|]) shouldBe' [s|{"p":[3], "lm":1}|] (transformRight [s|{"p":[5], "lm":0}|] [s|{"p":[2], "lm":0}|]) shouldBe' [s|{"p":[3], "lm":0}|] (transformLeft [s|{"p":[2], "lm":0}|] [s|{"p":[5], "lm":0}|]) -- TODO: why is this test duplicated. One side should be right I guess? shouldBe' [s|{"p":[0], "lm":5}|] (transformLeft [s|{"p":[2], "lm":5}|] [s|{"p":[2], "lm":0}|]) shouldBe' [s|{"p":[0], "lm":5}|] (transformLeft [s|{"p":[2], "lm":5}|] [s|{"p":[2], "lm":0}|]) shouldBe' [s|{"p":[0], "lm":0}|] (transformRight [s|{"p":[0], "lm":5}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[0], "lm":0}|] (transformRight [s|{"p":[0], "lm":1}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[1], "lm":1}|] (transformLeft [s|{"p":[0], "lm":1}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[1], "lm":2}|] (transformRight [s|{"p":[5], "lm":0}|] [s|{"p":[0], "lm":1}|]) shouldBe' [s|{"p":[3], "lm":2}|] (transformRight [s|{"p":[5], "lm":0}|] [s|{"p":[2], "lm":1}|]) shouldBe' [s|{"p":[2], "lm":1}|] (transformLeft [s|{"p":[3], "lm":1}|] [s|{"p":[1], "lm":3}|]) shouldBe' [s|{"p":[2], "lm":3}|] (transformLeft [s|{"p":[1], "lm":3}|] [s|{"p":[3], "lm":1}|]) shouldBe' [s|{"p":[2], "lm":6}|] (transformLeft [s|{"p":[2], "lm":6}|] [s|{"p":[0], "lm":1}|]) shouldBe' [s|{"p":[2], "lm":6}|] (transformRight [s|{"p":[0], "lm":1}|] [s|{"p":[2], "lm":6}|]) shouldBe' [s|{"p":[2], "lm":6}|] (transformLeft [s|{"p":[2], "lm":6}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[2], "lm":6}|] (transformRight [s|{"p":[1], "lm":0}|] [s|{"p":[2], "lm":6}|]) shouldBe' [s|{"p":[0], "lm":2}|] (transformLeft [s|{"p":[0], "lm":1}|] [s|{"p":[2], "lm":1}|]) shouldBe' [s|{"p":[2], "lm":0}|] (transformRight [s|{"p":[0], "lm":1}|] [s|{"p":[2], "lm":1}|]) shouldBe' [s|{"p":[1], "lm":1}|] (transformLeft [s|{"p":[0], "lm":0}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[0], "lm":0}|] (transformLeft [s|{"p":[0], "lm":1}|] [s|{"p":[1], "lm":3}|]) shouldBe' [s|{"p":[3], "lm":1}|] (transformLeft [s|{"p":[2], "lm":1}|] [s|{"p":[3], "lm":2}|]) shouldBe' [s|{"p":[3], "lm":3}|] (transformLeft [s|{"p":[3], "lm":2}|] [s|{"p":[2], "lm":1}|]) it "changes indices correctly around a move" $ do shouldBe' [s|{"p":[1,0], "li":{}}|] (transformLeft [s|{"p":[0,0], "li":{}}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[0], "lm":0}|] (transformLeft [s|{"p":[1], "lm":0}|] [s|{"p":[0], "ld":{}}|]) shouldBe' [s|{"p":[0], "lm":0}|] (transformLeft [s|{"p":[0], "lm":1}|] [s|{"p":[1], "ld":{}}|]) shouldBe' [s|{"p":[5], "lm":0}|] (transformLeft [s|{"p":[6], "lm":0}|] [s|{"p":[2], "ld":{}}|]) shouldBe' [s|{"p":[1], "lm":0}|] (transformLeft [s|{"p":[1], "lm":0}|] [s|{"p":[2], "ld":{}}|]) shouldBe' [s|{"p":[1], "lm":1}|] (transformRight [s|{"p":[1], "ld":3}|] [s|{"p":[2], "lm":1}|]) shouldBe' [s|{"p":[1], "ld":{}}|] (transformRight [s|{"p":[1], "lm":2}|] [s|{"p":[2], "ld":{}}|]) shouldBe' [s|{"p":[2], "ld":{}}|] (transformLeft [s|{"p":[1], "ld":{}}|] [s|{"p":[2], "lm":1}|]) shouldBe' [s|{"p":[0], "ld":{}}|] (transformRight [s|{"p":[0], "lm":1}|] [s|{"p":[1], "ld":{}}|]) shouldBe' [s|{"p":[0], "ld":1, "li":2}|] (transformLeft [s|{"p":[1], "ld":1, "li":2}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[1], "lm":0}|] (transformRight [s|{"p":[1], "ld":1, "li":2}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[0], "ld":2, "li":3}|] (transformLeft [s|{"p":[1], "ld":2, "li":3}|] [s|{"p":[0], "lm":1}|]) shouldBe' [s|{"p":[0], "lm":1}|] (transformRight [s|{"p":[1], "ld":2, "li":3}|] [s|{"p":[0], "lm":1}|]) shouldBe' [s|{"p":[1], "ld":3, "li":4}|] (transformLeft [s|{"p":[0], "ld":3, "li":4}|] [s|{"p":[1], "lm":0}|]) shouldBe' [s|{"p":[1], "lm":0}|] (transformRight [s|{"p":[0], "ld":3, "li":4}|] [s|{"p":[1], "lm":0}|]) it "li vs lm" $ do let li = \(p :: Int) -> JSONOperation [ListInsert [] p [v|[]|]] let lm :: Int -> Int -> JSONOperation lm = \f t -> JSONOperation [ListMove [] f t] shouldBe' (li 0) (transformLeft (li 0) (lm 1 3)) shouldBe' (li 1) (transformLeft (li 1) (lm 1 3)) shouldBe' (li 1) (transformLeft (li 2) (lm 1 3)) shouldBe' (li 2) (transformLeft (li 3) (lm 1 3)) shouldBe' (li 4) (transformLeft (li 4) (lm 1 3)) shouldBe' (lm 2 4) (transformRight (li 0) (lm 1 3)) shouldBe' (lm 2 4) (transformRight (li 1) (lm 1 3)) shouldBe' (lm 1 4) (transformRight (li 2) (lm 1 3)) shouldBe' (lm 1 4) (transformRight (li 3) (lm 1 3)) shouldBe' (lm 1 3) (transformRight (li 4) (lm 1 3)) shouldBe' (li 0) (transformLeft (li 0) (lm 1 2)) shouldBe' (li 1) (transformLeft (li 1) (lm 1 2)) shouldBe' (li 1) (transformLeft (li 2) (lm 1 2)) shouldBe' (li 3) (transformLeft (li 3) (lm 1 2)) shouldBe' (li 0) (transformLeft (li 0) (lm 3 1)) shouldBe' (li 1) (transformLeft (li 1) (lm 3 1)) shouldBe' (li 3) (transformLeft (li 2) (lm 3 1)) shouldBe' (li 4) (transformLeft (li 3) (lm 3 1)) shouldBe' (li 4) (transformLeft (li 4) (lm 3 1)) shouldBe' (lm 4 2) (transformRight (li 0) (lm 3 1)) shouldBe' (lm 4 2) (transformRight (li 1) (lm 3 1)) shouldBe' (lm 4 1) (transformRight (li 2) (lm 3 1)) shouldBe' (lm 4 1) (transformRight (li 3) (lm 3 1)) shouldBe' (lm 3 1) (transformRight (li 4) (lm 3 1)) shouldBe' (li 0) (transformLeft (li 0) (lm 2 1)) shouldBe' (li 1) (transformLeft (li 1) (lm 2 1)) shouldBe' (li 3) (transformLeft (li 2) (lm 2 1)) shouldBe' (li 3) (transformLeft (li 3) (lm 2 1)) describe "object" $ do it "passes sanity checks" $ do shouldBe' [v|{x:"a", y:"b"}|] (apply [v|{x:"a"}|] [s|{"p":["y"], "oi":"b"}|]) shouldBe' [v|{}|] (apply [v|{x:"a"}|] [s|{"p":["x"], "od":"a"}|]) shouldBe' [v|{x:"b"}|] (apply [v|{x:"a"}|] [s|{"p":["x"], "od":"a", "oi":"b"}|]) shouldBe' [v|null|] (apply [v|"abc"|] [s|{"p":[], "od":"abc"}|]) shouldBe' [v|42|] (apply [v|"abc"|] [s|{"p":[], "od":"abc", "oi":42}|]) it "Ops on deleted elements become noops" $ do shouldBe' [s|{}|] (transformLeft [s|{"p":["1", 0], "si":"hi"}|] [s|{"p":["1"], "od":"x"}|]) shouldBe' [s|{}|] (transformRight [s|{"p":[], "od":"agimble s","oi":null}|] [s|{"p":[9],"si":"bite "}|]) shouldBe' [s|{}|] (transformLeft [s|{"p":["1"], "t":"text0", "o":[{"p":0, "i":"hi"}]}|] [s|{"p":["1"], "od":"x"}|]) shouldBe' [s|{}|] (transformRight [s|{"p":[], "od":"agimble s","oi":null}|] [s|{"p":[], "t":"text0", "o":[{"p":9, "i":"bite "}]}|]) it "Ops on replaced elements become noops" $ do shouldBe' [s|{}|] (transformLeft [s|{"p":["1", 0], "si":"hi"}|] [s|{"p":["1"], "od":"x", "oi":"y"}|]) shouldBe' [s|{}|] (transformLeft [s|{"p":["1"], "t":"text0", "o":[{"p":0, "i":"hi"}]}|] [s|{"p":["1"], "od":"x", "oi":"y"}|]) it "Deleted data is changed to reflect edits" $ do shouldBe' [s|{"p":["1"], "od":"abc"}|] (transformLeft [s|{"p":["1"], "od":"a"}|] [s|{"p":["1", 1], "si":"bc"}|]) shouldBe' [s|{"p":["1"], "od":"abc"}|] (transformLeft [s|{"p":["1"], "od":"a"}|] [s|{"p":["1"], "t":"text0", "o":[{"p":1, "i":"bc"}]}|]) shouldBe' [s|{"p":[], "od":25,"oi":[]}|] (transformLeft [s|{"p":[], "od":22,"oi":[]}|] [s|{"p":[],"na":3}|]) shouldBe' [s|{"p":[], "od":{"toves":""},"oi":4}|] (transformLeft [s|{"p":[], "od":{"toves":0},"oi":4}|] [s|{"p":["toves"], "od":0,"oi":""}|]) shouldBe' [s|{"p":[], "od":"thou an","oi":[]}|] (transformLeft [s|{"p":[], "od":"thou and ","oi":[]}|] [s|{"p":[7],"sd":"d "}|]) shouldBe' [s|{"p":[], "od":"thou an","oi":[]}|] (transformLeft [s|{"p":[], "od":"thou and ","oi":[]}|] [s|{"p":[], "t":"text0", "o":[{"p":7, "d":"d "}]}|]) shouldBe' [s|{}|] (transformRight [s|{"p":[], "od":{"bird":38},"oi":20}|] [s|{"p":["bird"],"na":2}|]) shouldBe' [s|{"p":[], "od":{"bird":40},"oi":20}|] (transformLeft [s|{"p":[], "od":{"bird":38},"oi":20}|] [s|{"p":["bird"],"na":2}|]) shouldBe' [s|{"p":["He"], "od":[]}|] (transformRight [s|{"p":["The"],"na":-3}|] [s|{"p":["He"], "od":[]}|]) shouldBe' [s|{}|] (transformLeft [s|{"p":["He"],"oi":{}}|] [s|{"p":[], "od":{},"oi":"the"}|]) it "If two inserts are simultaneous, the lefts insert will win" $ do shouldBe' [s|{"p":["1"], "oi":"a", "od":"b"}|] (transformLeft [s|{"p":["1"], "oi":"a"}|] [s|{"p":["1"], "oi":"b"}|]) shouldBe' [s|{}|] (transformRight [s|{"p":["1"], "oi":"a"}|] [s|{"p":["1"], "oi":"b"}|]) it "parallel ops on different keys miss each other" $ do shouldBe' [s|{"p":["a"], "oi": "x"}|] (transformLeft [s|{"p":["a"], "oi":"x"}|] [s|{"p":["b"], "oi":"z"}|]) shouldBe' [s|{"p":["a"], "oi": "x"}|] (transformLeft [s|{"p":["a"], "oi":"x"}|] [s|{"p":["b"], "od":"z"}|]) shouldBe' [s|{"p":["in","he"],"oi":{}}|] (transformRight [s|{"p":["and"], "od":{}}|] [s|{"p":["in","he"],"oi":{}}|]) shouldBe' [s|{"p":["x",0],"si":"his "}|] (transformRight [s|{"p":["y"], "od":0,"oi":1}|] [s|{"p":["x",0],"si":"his "}|]) shouldBe' [s|{"p":["x"], "t":"text0", "o":[{"p":0, "i":"his "}]}|] (transformRight [s|{"p":["y"], "od":0, "oi":1}|] [s|{"p":["x"], "t":"text0", "o":[{"p":0, "i":"his "}]}|]) it "replacement vs. deletion" $ do shouldBe' [s|{"p":[], "oi":{}}|] (transformRight [s|{"p":[], "od":[""]}|] [s|{"p":[], "od":[""], "oi":{}}|]) shouldBe' [s|{"p":[], "oi": 42}|] (transformRight [s|{"p":[], "od":"foo"}|] [s|{"p":[], "od": "foo", "oi": 42}|]) shouldBe' [s|{}|] (transformLeft [s|{"p":[], "od":"foo"}|] [s|{"p":[], "od": "foo", "oi": 42}|]) it "replacement vs. replacement" $ do -- Tie break: with replacements on the same key, the left one wins shouldBe' [s|{"p":["baz219"],"oi":"win","od":"lose"}|] (transformLeft [s|{"p":["baz219"],"oi":"win","od":"old"}|] [s|{"p":["baz219"],"oi":"lose","od":"old"}|]) shouldBe' [s|{}|] (transformRight [s|{"p":["baz219"],"oi":"win","od":"old"}|] [s|{"p":["baz219"],"oi":"lose","od":"old"}|]) shouldBe' [l|[]|] (transformRight [l|[{"p":[], "od":[""]},{"p":[],"oi":null}]|] [l|[{"p":[], "od":[""]},{"p":[],"oi":{}}]|]) shouldBe' [l|[{"p":[], "od":null,"oi":{}}]|] (transformLeft [l|[{"p":[], "od":[""]},{"p":[],"oi":{}}]|] [l|[{"p":[], "od":[""]},{"p":[],"oi":null}]|]) -- shouldBe' [l|[]|] (transformRight' [l|[{"p":[], "od":[""],"oi":null}]|] [l|[{"p":[], "od":[""],"oi":{}}]|]) -- shouldBe' [s|{"p":[], "od":null,"oi":{}}|] (transformLeft [s|{"p":[], "od":[""],"oi":{}}|] [s|{"p":[], "od":[""],"oi":null}|]) -- -- test diamond property -- rightOps = [{"p":[],"od":null,"oi":{}}] -- leftOps = [{"p":[],"od":null,"oi":""}] -- rightHas = apply(null, rightOps) -- leftHas = apply(null, leftOps) -- let [left_, right_] = transformX type, leftOps, rightOps -- shouldBe' leftHas, apply rightHas, left_ -- shouldBe' leftHas, apply leftHas, right_ it "An attempt to re-delete a key becomes a no-op" $ do shouldBe' [s|{}|] (transformLeft [s|{"p":["k"], "od":"x"}|] [s|{"p":["k"], "od":"x"}|]) shouldBe' [s|{}|] (transformRight [s|{"p":["k"], "od":"x"}|] [s|{"p":["k"], "od":"x"}|]) main :: IO () main = (testSpec "JSON specs" specs) >>= defaultMain
thomasjm/ot.hs
test/Control/OperationalTransformation/JSON/Specs.hs
mit
26,734
0
20
4,483
7,016
4,302
2,714
305
2
{- | Module : $Header$ Copyright : (c) C. Maeder, DFKI GmbH 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : experimental Portability : portable -} module Main where import SoftFOL.Sign import SoftFOL.PrintTPTP import Common.AS_Annotation import Common.Id -- | a more pretty alternative for shows using PrintTPTP showPretty2 :: PrintTPTP a => a -> ShowS showPretty2 = shows . printTPTP main :: IO () main = do putStrLn "--- Term-Tests ---" putStrLn $ showPretty2 spSimpleTermTest1 "\n" putStrLn $ showPretty2 spQuantTermTest1 "\n" putStrLn $ showPretty2 spQuantTermTest2 "\n" putStrLn $ showPretty2 spQuantTermTest3 "\n" putStrLn $ showPretty2 spQuantTermTest4 "\n" putStrLn $ showPretty2 spQuantTermTest5 "\n" putStrLn "--- Formula-Test ---" print $ printFormula SPOriginAxioms spFormulaTest putStrLn "\n" putStrLn "--- FormulaList-Tests ---" putStrLn $ showPretty2 spFormulaListTest1 "\n" putStrLn $ showPretty2 spFormulaListTest2 "\n" putStrLn $ showPretty2 spFormulaListTest3 "\n" putStrLn $ showPretty2 spFormulaListTest4 "\n" putStrLn "--- Description-Tests ---" putStrLn $ showPretty2 spDescTest1 "\n" putStrLn $ showPretty2 spDescTest2 "\n" putStrLn "--- Problem-Test ---" putStrLn $ showPretty2 spProblemTest "\n" putStrLn "--- Declaration-Test ---" putStrLn $ showPretty2 spDeclTest "\n" spSimpleTermTest1 :: SPSymbol spSimpleTermTest1 = mkSPCustomSymbol "testsymbol" spQuantTermTest1 :: SPTerm spQuantTermTest1 = SPQuantTerm {quantSym= SPForall, variableList= [simpTerm (mkSPCustomSymbol "a")], qFormula= SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}} spQuantTermTest2 :: SPTerm spQuantTermTest2 = SPQuantTerm {quantSym= SPForall, variableList= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b")], qFormula= SPComplexTerm {symbol= SPEqual, arguments= [ SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "a")]}, SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "b")]} ]}} spQuantTermTest3 :: SPTerm spQuantTermTest3 = SPQuantTerm {quantSym= SPExists, variableList= [SPComplexTerm {symbol=mkSPCustomSymbol "Klein", arguments=[simpTerm (mkSPCustomSymbol "pi")]}, SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "y")]}], qFormula= SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "pi"), simpTerm (mkSPCustomSymbol "y")]}} spQuantTermTest4 :: SPTerm spQuantTermTest4 = SPQuantTerm {quantSym= SPForall, variableList= [ SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "y")]}, SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b"), simpTerm (mkSPCustomSymbol "c")]} ], qFormula= SPComplexTerm {symbol= SPOr, arguments= [ SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "y")]}, SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b"), simpTerm (mkSPCustomSymbol "c")]} ]}} spQuantTermTest5 :: SPTerm spQuantTermTest5 = SPQuantTerm {quantSym= SPCustomQuantSym $ mkSimpleId "T", variableList = [ SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "y")]}, SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b"), simpTerm (mkSPCustomSymbol "c")]}, SPComplexTerm {symbol=SPNot, arguments=[simpTerm (mkSPCustomSymbol "blue")]} ], qFormula= SPComplexTerm {symbol=SPEqual, arguments=[ SPComplexTerm {symbol= SPOr, arguments=[ SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "y")]}, SPComplexTerm {symbol=SPNot, arguments=[simpTerm (mkSPCustomSymbol "blue")]} ]}, SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b"), simpTerm (mkSPCustomSymbol "c")]} ]}} toTestFormula :: SPTerm -> SPFormula toTestFormula = makeNamed "testFormula" spFormulaTest :: SPFormula spFormulaTest = toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]} spFormulaListTest1 :: SPFormulaList spFormulaListTest1 = SPFormulaList {originType= SPOriginAxioms, formulae= [toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]} spFormulaListTest2 :: SPFormulaList spFormulaListTest2 = SPFormulaList {originType= SPOriginConjectures, formulae= [toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]} spFormulaListTest3 :: SPFormulaList spFormulaListTest3 = SPFormulaList {originType= SPOriginAxioms, formulae= [toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}, toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]} spFormulaListTest4 :: SPFormulaList spFormulaListTest4 = SPFormulaList {originType= SPOriginConjectures, formulae= [toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}, toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]} spDescTest1 :: SPDescription spDescTest1 = SPDescription {name="testdesc", author="testauthor", version=Nothing, logic=Nothing, status=SPStateUnknown, desc="Just a test.", date=Nothing} spDescTest2 :: SPDescription spDescTest2 = SPDescription {name="testdesc", author="testauthor", version=Just "0.1", logic=Just "logic description", status=SPStateUnknown, desc="Just a test.", date=Just "today"} spProblemTest :: SPProblem spProblemTest = SPProblem {identifier= "testproblem", description= descr, logicalPart= logical_part, settings= []} where descr = SPDescription {name="testdesc", author="testauthor", version=Nothing, logic=Nothing, status=SPStateUnknown, desc="Just a test.", date=Nothing} logical_part = emptySPLogicalPart { declarationList= Just [spDeclTest, spDeclTest2], formulaLists= [SPFormulaList {originType= SPOriginAxioms, formulae= [toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]},SPFormulaList {originType= SPOriginConjectures, formulae= [toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}, toTestFormula SPComplexTerm {symbol= SPEqual, arguments= [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]}]} spDeclTest :: SPDeclaration spDeclTest = SPSubsortDecl { sortSymA = mkSimpleId "sortSymA" , sortSymB = mkSimpleId "sortSymB" } spDeclTest2 :: SPDeclaration spDeclTest2 = SPTermDecl {termDeclTermList = [ SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "y")]}, SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b"), simpTerm (mkSPCustomSymbol "c")]} ], termDeclTerm= SPComplexTerm {symbol= SPOr, arguments= [ SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "y")]}, SPComplexTerm {symbol=mkSPCustomSymbol "Elem", arguments=[simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b"), simpTerm (mkSPCustomSymbol "c")]} ]}}
nevrenato/Hets_Fork
SoftFOL/tests/PrintTPTPTests.hs
gpl-2.0
7,688
0
19
843
2,239
1,247
992
93
1
module Utils ( betweenCO , ramWithInit , nextPair , combineEnabled , newRegs, setIdx, regIdx, varIdx , syncReadBus ) where import Language.KansasLava import Data.Sized.Ix import Data.Sized.Unsigned import Data.Sized.Matrix (Matrix) import qualified Data.Sized.Matrix as Matrix import Prelude hiding (mapM) import Data.Traversable (mapM) betweenCO :: (Ord a, Rep a) => Signal clk a -> (a, a) -> Signal clk Bool x `betweenCO` (lo, hi) = pureS lo .<=. x .&&. x .<. pureS hi ramWithInit :: (Clock clk, Size a, Eq a, Rep a, Bounded a, Rep d) => (Signal clk a -> Signal clk a) -> (Signal clk a -> Signal clk d) -> Signal clk (Pipe a d) -> (Signal clk (a -> d), Signal clk Bool) ramWithInit next rom pipe = runRTL $ do x <- newReg minBound x' <- newReg minBound filling <- newReg True reading <- newReg False CASE [ IF (reg reading) $ do x := reg x' reading := low filling := reg x ./=. maxBound , IF (reg filling) $ do x' := next (reg x) reading := high ] let (we, writeLine) = unpack pipe we' = reg reading .||. we writeLine' = mux (reg filling) (writeLine, pack (reg x, rom (reg x))) return (writeMemory $ packEnabled we' writeLine', reg filling) nextPair :: (Size a, Size b) => Signal clk (Unsigned a, Unsigned b) -> Signal clk (Unsigned a, Unsigned b) nextPair xy = pack (x + 1, mux nextRow (y, y + 1)) where (x, y) = unpack xy nextRow = x .==. maxBound combineEnabled :: (Clock clk, Rep a) => Signal clk (Enabled a) -> Signal clk (Enabled a) -> Signal clk (Enabled a) combineEnabled s1 s2 = packEnabled (en1 .||. en2) (mux en1 (v2, v1)) where (en1, v1) = unpackEnabled s1 (en2, v2) = unpackEnabled s2 newRegs :: (Clock clk, Rep a, Size n) => Matrix n a -> RTL s clk (Matrix n (Reg s clk a)) newRegs inits = mapM newReg inits setIdx :: (Clock clk, Rep a, Rep n, Size n) => Matrix n (Reg s clk a) -> Signal clk n -> Signal clk a -> RTL s clk () setIdx regs idx val = CASE [ IF (idx .==. pureS i) $ r := val | (i, r) <- Matrix.assocs regs ] regIdx :: (Clock clk, Rep a, Rep n, Size n) => Matrix n (Reg s clk a) -> Signal clk n -> Signal clk a regIdx regs idx = pack (fmap reg regs) .!. idx varIdx :: (Clock clk, Rep a, Rep n, Size n) => Matrix n (Reg s clk a) -> Signal clk n -> Signal clk a varIdx regs idx = pack (fmap var regs) .!. idx syncReadBus :: (Clock clk, Rep a, Size a, Rep d) => Signal clk (a -> d) -> (Signal clk (Enabled a), Signal clk (Enabled a)) -> (Signal clk d, Signal clk (Enabled d)) syncReadBus ram (a1, a2) = runRTL $ do choose2 <- newReg False choose2 := bitNot en1 return (d, packEnabled (reg choose2) d) where (en1, a1') = unpackEnabled a1 (en2, a2') = unpackEnabled a2 a = mux en1 (mux en2 (minBound, a2'), a1') d = syncRead ram a
gergoerdi/chip8-papilio
src/Utils.hs
gpl-2.0
3,123
0
17
995
1,414
715
699
76
1
module Networkie.Coord where type Coord = (Int, Int) type Dim = (Int, Int) pairPlus :: Num a => (a,a) -> (a,a) -> (a,a) pairPlus (a1, a2) (b1, b2) = (a1 + b1, a2 + b2) pairMinus :: Num a => (a,a) -> (a,a) -> (a,a) pairMinus (a1, a2) (b1, b2) = (a1 - b1, a2 - b2) pairDiv :: Integral a => a -> (a,a) -> (a,a) pairDiv n (a1, a2) = (div a1 n, div a2 n) pairNegate :: Num a => (a,a) -> (a,a) pairNegate (a1,a2) = (-a1,-a2) cog :: [Coord] -> Coord cog xs = (pairDiv (length xs)) (foldl1 pairPlus xs)
pmiddend/networkie
src/Networkie/Coord.hs
gpl-2.0
501
0
9
110
337
193
144
13
1
module Types where import Data.Char (toUpper) import Data.Monoid data StackType = [Type] :# Int deriving (Eq) data CExp = Term String | Bool Bool | Int Int | Char Char | String String | Compose CExp CExp | Quote CExp | Empty deriving (Eq) instance Show CExp where show (Term s) = s show (Compose a b) = case (a,b) of (Empty,_) -> show b (_,Empty) -> show a _ -> show a ++ " " ++ show b show (Quote e) = "[" ++ show e ++ "]" show Empty = "" show (Bool b) = if b then "#t" else "#f" show (Int i) = show i show (Char c) = ['`', c, '`'] show (String s) = show s instance Monoid CExp where mappend = Compose mempty = Empty data Type = TVar Int | Scalar String | Fun StackType StackType deriving (Eq) instance Show Type where show (TVar n) | n < 26 = [toEnum (fromEnum n + fromEnum 'a')] | otherwise = reverse $ show (TVar (n `mod` 26)) ++ show (TVar $ n `div` 26 - 1) show (Scalar t) = t show (Fun a b) = show a ++ " -> " ++ show b showStack :: Int -> String showStack = map toUpper . show . TVar instance Show StackType where show (as :# a) = unwords $ showStack a : map showInner (reverse as) where showInner t = case t of Fun _ _ -> "(" ++ show t ++ ")" _ -> show t data Equation = StackType :~ StackType deriving (Eq) instance Show Equation where show (n :~ s) = show n ++ " = " ++ show s
breestanwyck/stack-unification
src/Types.hs
gpl-2.0
1,486
0
13
478
667
345
322
50
1
-- Copyright Edward O'Callaghan, Buy me breakfast license! module Generate where import Data.Binary.Put import Data.Int (Int16) import qualified Data.ByteString.Lazy as BL -- Number of samples should be a multiple of 1024 to match bladeRF -- buffer size constraints nSamples :: Int nSamples = 1024 -- IQ values are in the range [-2048, 2047]. Clamp to 1800 just to -- avoid saturating scale = 1800 -- | .. z :: Int -> (Int16, Int16) z k = (round (scale * cos (theta k)), round (scale * sin (theta k))) where theta k = fromIntegral k * (2 * pi) / fromIntegral nSamples -- | Function to compute to generate bytestream genstream :: Int -> [(Int16, Int16)] genstream n = take n $ map z [0..] mySignalFormat :: [(Int16,Int16)] -> Put mySignalFormat = mapM_ putPair where putPair (x, y) = putInt16le x >> putInt16le y putInt16le = putWord16le . fromIntegral main :: IO () main = BL.writeFile "testsig.bin" $ runPut . mySignalFormat $ genstream nSamples
victoredwardocallaghan/HaskellDSP
Generate.hs
gpl-2.0
973
0
11
189
286
158
128
18
1
module Response.Export (returnPDF, exportTimetableImageResponse, exportTimetablePDFResponse) where import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString as BS import Data.ByteString.Base64.Lazy as BEnc import qualified Data.ByteString.Lazy as L import qualified Data.Text as T import Export.GetImages import Export.ImageConversion (removeFile) import Export.LatexGenerator import Export.PdfGenerator import Happstack.Server import Response.Image (returnImageData) -- | Returns an image of the timetable requested by the user. exportTimetableImageResponse :: T.Text -> String -> ServerPart Response exportTimetableImageResponse session selectedCourses = do (svgFilename, imageFilename) <- liftIO $ getActiveTimetable (T.pack selectedCourses) session liftIO $ returnImageData svgFilename imageFilename -- | Returns a PDF containing graph and timetable requested by the user. exportTimetablePDFResponse :: String -> String -> ServerPart Response exportTimetablePDFResponse selectedCourses graphInfo = do (graphSvg, graphImg) <- liftIO $ getActiveGraphImage graphInfo (fallsvgFilename, fallimageFilename) <- liftIO $ getActiveTimetable (T.pack selectedCourses) "Fall" (springsvgFilename, springimageFilename) <- liftIO $ getActiveTimetable (T.pack selectedCourses) "Spring" pdfName <- liftIO $ returnPDF graphSvg graphImg fallsvgFilename fallimageFilename springsvgFilename springimageFilename liftIO $ returnPdfBS pdfName -- | Returns 64base bytestring of PDF for given name, then deletes PDF from local. returnPdfBS :: String -> IO Response returnPdfBS pdfFilename = do pdfData <- BS.readFile pdfFilename _ <- removeFile pdfFilename return $ toResponseBS "application/pdf" $ BEnc.encode $ L.fromStrict pdfData -- | Returns the name of a generated pdf that contains graphImg and timetableImg -- and deletes all of the img and svg files passed as arguments returnPDF :: String -> String -> String -> String -> String -> String -> IO String returnPDF graphSvg graphImg fallTimetableSvg fallTimetableImg springTimetableSvg springTimetableImg = do rand <- randomName let texName = rand ++ ".tex" pdfName = rand ++ ".pdf" generateTex [graphImg, fallTimetableImg, springTimetableImg] texName -- generate a temporary TEX file createPDF texName -- create PDF using TEX and delete the TEX file afterwards _ <- removeFile (graphSvg ++ " " ++ graphImg ++ " " ++ fallTimetableSvg ++ " " ++ fallTimetableImg ++ " " ++ springTimetableSvg ++ " " ++ springTimetableImg) return pdfName
Courseography/courseography
app/Response/Export.hs
gpl-3.0
2,592
0
19
418
548
286
262
38
1
module Sat.Example.Example where import Sat.Core import Sat.Parser import Sat.Signatures.Figures import Sat.VisualModels.FiguresBoard import Sat.VisualModel (visualToModel) import qualified Data.Map as M -- Elementos: e1 = ElemBoard 1 Nothing [triangulo,chico,rojo] e2 = ElemBoard 2 Nothing [cuadrado,grande,verde] e3 = ElemBoard 3 Nothing [triangulo,chico,azul] e4 = ElemBoard 4 Nothing [circulo,rojo] e5 = ElemBoard 5 Nothing [triangulo,rojo] e6 = ElemBoard 6 Nothing [cuadrado] e7 = ElemBoard 7 Nothing [cuadrado,chico,verde] e8 = ElemBoard 8 Nothing [circulo,verde,grande] e9 = ElemBoard 9 Nothing [triangulo,grande,azul] b = boardDefault { elems = [ (Coord 0 0,e1) , (Coord 1 1,e2) , (Coord 2 2,e3) , (Coord 3 6,e4) , (Coord 7 7,e5) , (Coord 3 3,e6) , (Coord 4 6,e7) , (Coord 7 0,e8) , (Coord 0 7,e9) ] , size = 8 } -- Ahora generemos el modelo correspondiente a esta configuración de tablero model = visualToModel b -- Ahora podríamos evaluar algunas fórmulas: varx = Variable "x" vary = Variable "y" -- Fórmula falsa: f1 = ForAll varx (Pred triangulo (Var varx)) -- Fórmula Verdadera f2 = Exist varx (Exist vary (Rel derecha [Var varx,Var vary]))
manugunther/sat
Sat/Example/Example.hs
gpl-3.0
1,376
0
11
394
460
263
197
32
1
-- | -- Module : Control.Category.Constrained.Prelude -- Copyright : (c) 2013 Justus Sagemüller -- License : GPL v3 (see COPYING) -- Maintainer : (@) jsag $ hvl.no -- {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeFamilies #-} module Control.Category.Constrained.Prelude ( -- * The constrained-categories facilities module Control.Category.Constrained , module Control.Functor.Constrained , module Control.Applicative.Constrained , module Control.Monad.Constrained , module Control.Arrow.Constrained -- * The compatible part of the standard Prelude , module Prelude ) where import Prelude hiding ( id, const, fst, snd, (.), ($), curry, uncurry , Functor(..), (<$>), Applicative(..), (<*>), Monad(..), (=<<), filter , mapM, mapM_, sequence, sequence_ , Foldable, foldMap, fold, traverse_, concatMap , Traversable, traverse, MonadFail(..) ) import Control.Category.Constrained hiding (ConstrainedMorphism) import Control.Functor.Constrained import Control.Applicative.Constrained import Control.Monad.Constrained hiding (MonadPlus(..), MonadZero(..), (>=>), (<=<), guard, forever, void) import Control.Arrow.Constrained (Function, ($), ifThenElse, fst, snd, const) import Control.Applicative.Constrained import Data.Foldable.Constrained (Foldable, foldMap, fold, traverse_, concatMap) import Data.Traversable.Constrained (Traversable, traverse)
leftaroundabout/constrained-categories
Control/Category/Constrained/Prelude.hs
gpl-3.0
1,584
0
6
384
309
218
91
23
0
module HsPredictor.Types.Types where type ThrowsError = Either String type DbPath = String type TeamName = String -- | Match - contains all parsed values data Match = Match { dateM :: Int, homeM :: String, awayM :: String, ghM :: Int, gaM :: Int, odds1M :: Double, oddsxM :: Double, odds2M :: Double} deriving (Show, Eq) -- | Sorting matches by date instance Ord Match where m1 `compare` m2 = dateM m1 `compare` dateM m2 data Result = Win | Draw | Loss | Upcoming data Outcome = HomeWin | NoWinner | AwayWin instance Show Outcome where show HomeWin = "-1" show NoWinner = "0" show AwayWin = "1" data Field = Home | Away -- | Used for export data Scaled = Scaled { winS :: Double, drawS :: Double, loseS :: Double} deriving (Eq) instance Show Scaled where show (Scaled w d l) = show w ++ " " ++ show d ++ " " ++ show l ++ " "
jacekm-git/HsPredictor
library/HsPredictor/Types/Types.hs
gpl-3.0
877
0
11
215
292
168
124
28
0
module Builtin.Atom where import qualified Data.Map as M import String import Object import Eval import AST import Builtin.Utils import Context (replyM_) atomClass = buildClass "Atom" bootstrap bootstrap = M.fromList [ ("==" , VFunction eq (1,Just 2)) , ("to_s" , VFunction to_s (0,Just 0)) ] eq :: [Value] -> EvalM () eq ((VAtom s):_) = do (VAtom t) <- innerValue if s == t then replyM_ VTrue else replyM_ VFalse to_s :: [Value] -> EvalM () to_s _ = do (VAtom slf) <- innerValue replyM_ $ VString $ mkStringLiteral slf
antarestrader/sapphire
Builtin/Atom.hs
gpl-3.0
557
0
10
126
229
123
106
20
2
module System.HComedi.Command where import System.HComedi.Types import System.HComedi.Handle import System.HComedi.Units import qualified System.HComedi.ComediBase as B import Foreign.C.Error import Foreign.C.Types import Foreign.Ptr import Foreign.ForeignPtr import Foreign.Marshal import Foreign.Marshal.Array import Foreign.Storable import Control.Monad import Data.Bits chanListFromCommand :: B.Command -> IO [(Channel,RangeInd,B.Ref,[B.ChanOptFlag])] chanListFromCommand cmd = do cChansOpts <- peekArray nChans (B.cmd_chanlist cmd) return $ map unChanOpt cChansOpts where nChans = fromIntegral $ B.cmd_chanlist_len cmd timedCommand :: Handle -> SubDevice -> Int -> Int -> [(Channel,RangeInd,B.Ref,[B.ChanOptFlag])] -> IO B.Command timedCommand (Handle fn p) (SubDevice s) nScan sPeriodNS chanList = alloca $ \cmdP -> mallocForeignPtr >>= (flip withForeignPtr) (\dataP -> mallocForeignPtrArray nChan >>= (flip withForeignPtr) (\chansP -> do pokeArray chansP $ map mkChanOpt chanList (throwErrnoIf (< 0) ("Comedi error making command") (B.c_comedi_get_cmd_generic_timed p s cmdP (fromIntegral nChan) (fromIntegral sPeriodNS))) cmd <- peek cmdP return $ cmd {B.cmd_stop_src = B.TrigNone ,B.cmd_chanlist = chansP ,B.cmd_chanlist_len = fromIntegral nChan ,B.cmd_data = dataP })) where nChan = length chanList data CommandTestResult = NoChange | SrcChange | ArgChange | ChanListChange deriving (Eq, Ord, Show) newtype ValidCommand = ValidCommand { unValidCommand :: B.Command } deriving (Eq, Show) cToResult :: CInt -> CommandTestResult cToResult n | n == 0 = NoChange | n == 1 = SrcChange | n == 2 = SrcChange | n == 3 = ArgChange | n == 4 = ArgChange | n == 5 = ChanListChange validateCommand :: Handle -> [CommandTestResult] -> B.Command -> IO ValidCommand validateCommand h@(Handle fd p) unacceptableResults cmd = alloca $ \cmdP -> do poke cmdP cmd res <- B.c_comedi_command_test p cmdP cmd' <- peek cmdP aux res cmd' where aux res cmd' | (res < 0) = error ("Comedi command error" ++ show res) | (cToResult res `elem` unacceptableResults) = (error $ unwords ["Comedi error sending command to" ,fd,". validateCommand returned " ,show (cToResult res)]) | (res > 0 && cToResult res `notElem` unacceptableResults) = do putStrLn ("Changed command Res: " ++ show res) validateCommand h unacceptableResults cmd' | (res == 0) = return . ValidCommand $ cmd | otherwise = error "Impossible case" execCommand :: Handle -> ValidCommand -> IO () execCommand (Handle fn p) (ValidCommand cmd) = alloca $ \cmdP -> do poke cmdP cmd (throwErrnoIf (<0) ("Comedi error executing command") (B.c_comedi_command p cmdP)) return () mkChanOpt :: (Channel, RangeInd, B.Ref, [B.ChanOptFlag]) -> CInt mkChanOpt ((Channel c), (RangeInd r), aRef, flags) = B.cr_pack_flags c r (B.refToC aRef) cFlags where cFlags = foldl (.|.) 0 $ map B.chanOptToC flags unChanOpt :: CInt -> (Channel, RangeInd, B.Ref, [B.ChanOptFlag]) unChanOpt cChanOpt = case B.cr_unpack_flags cChanOpt of (ch,rng,ref,fs) -> (Channel $ fromIntegral ch, RangeInd $ fromIntegral rng, B.refFromC ref, fs)
imalsogreg/hComedi
src/System/HComedi/Command.hs
gpl-3.0
3,624
0
22
1,006
1,161
608
553
84
1
module F3LAE where import Prelude hiding (lookup) -- | Several type synonymous to improve readability type Name = String type FormalArg = String type Id = String -- | A type for representing function declaration data FunDec = FunDec Name FormalArg Exp deriving(Show, Eq) -- | The abstract syntax of F3LAE data Exp = Num Integer | Add Exp Exp | Sub Exp Exp | Let Id Exp Exp | Ref Id | App Name Exp | Lambda FormalArg Exp | LambdaApp Exp Exp deriving(Show, Eq) -- | The environment with the list of deferred substitutions. type DefrdSub = [(Id, Value)] -- | The value data type. -- -- In this language (F3LAE), an expression -- is reduced to a value: either a number or -- a closure. A closure is a lambda expression -- that *closes* together its definition with the -- pending substitutions at definition time. -- data Value = NumValue Integer | Closure FormalArg Exp DefrdSub deriving(Show, Eq) -- | The interpreter function \0/ interp :: Exp -> DefrdSub -> [FunDec] -> Value -- the simple interpreter for numbers. interp (Num n) ds decs = NumValue n -- the interpreter for an add expression. interp (Add e1 e2) ds decs = NumValue (v1 + v2) where NumValue v1 = interp e1 ds decs NumValue v2 = interp e2 ds decs -- the interpreter for a sub expression. interp (Sub e1 e2) ds decs = NumValue (v1 - v2) where NumValue v1 = interp e1 ds decs NumValue v2 = interp e2 ds decs -- the interpreter for a let expression. -- note here that, to improve reuse, we actually -- convert a let exprssion in the equivalent -- lambda application (ela), and then interpret it. interp (Let v e1 e2) ds decs = interp ela ds decs where ela = (LambdaApp (Lambda v e2) e1) -- the interpreter for a reference to a variable. -- here, we make a lookup for the reference, in the -- list of deferred substitutions. interp (Ref v) ds decs = let res = lookup v fst ds in case res of (Nothing) -> error $ "variable " ++ v ++ " not found" (Just (_, value)) -> value -- the interpreter for a function application. -- here, we first make a lookup for the function declaration, -- evaluates the actual argument (leading to the parameter pmt), -- and then we interpret the function body in a new "local" environment -- (env). interp (App n a) ds decs = let res = lookup n (\(FunDec n _ _) -> n) decs in case res of (Nothing) -> error $ "funtion " ++ n ++ " not found" (Just (FunDec _ farg body)) -> interp body env decs where pmt = interp a ds decs env = [(farg, pmt)] -- the interpreter for a lambda abstraction. -- that is the most interesting case (IMO). it -- just returns a closure! interp (Lambda farg body) ds decs = Closure farg body ds -- the interpreter for a lambda application. -- plese, infer what is going on here in this -- case interp (LambdaApp e1 e2) ds decs = interp body env decs -- we interpret considering the new environment where Closure farg body ds0 = interp e1 ds decs -- we expect e1 to evaluate to a closure. pmt = interp e2 ds decs -- ds0 is the deferred substitutions at the lambda declaration env = (farg, pmt):ds0 -- env is the original environment (ds0) + a new mapping -- a new lookup function. lookup :: Id -> (a -> String) -> [a] -> Maybe a lookup _ f [] = Nothing lookup v f (x:xs) | v == f x = Just x | otherwise = lookup v f xs
rodrigofegui/UnB
2017.2/Linguagens de Programação/short-plai_Trab 2/c3/F3LAE.hs
gpl-3.0
3,528
0
13
925
843
453
390
52
3
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( getApplicationDev , appMain , develMain , makeFoundation -- * for DevelMain , getApplicationRepl , shutdownApp -- * for GHCI , handler , db ) where import Control.Monad.Logger (liftLoc, runLoggingT) import Database.Persist.Sqlite (createSqlitePool, runSqlPool, sqlDatabase, sqlPoolSize) import Import import Language.Haskell.TH.Syntax (qLocation) import Network.Wai.Handler.Warp (Settings, defaultSettings, defaultShouldDisplayException, runSettings, setHost, setOnException, setPort, getPort) import Network.Wai.Middleware.RequestLogger (Destination (Logger), IPAddrSource (..), OutputFormat (..), destination, mkRequestLogger, outputFormat) import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet, toLogStr) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Common import Handler.Home -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- | This function allocates resources (such as a database connection pool), -- performs initialization and returns a foundation datatype value. This is also -- the place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeFoundation :: AppSettings -> IO App makeFoundation appSettings = do -- Some basic initializations: HTTP connection manager, logger, and static -- subsite. appHttpManager <- newManager appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger appStatic <- (if appMutableStatic appSettings then staticDevel else static) (appStaticDir appSettings) -- We need a log function to create a connection pool. We need a connection -- pool to create our foundation. And we need our foundation to get a -- logging function. To get out of this loop, we initially create a -- temporary foundation without a real connection pool, get a log function -- from there, and then create the real foundation. let mkFoundation appConnPool = App {..} -- The App {..} syntax is an example of record wild cards. For more -- information, see: -- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html tempFoundation = mkFoundation $ error "connPool forced in tempFoundation" logFunc = messageLoggerSource tempFoundation appLogger -- Create the database connection pool pool <- flip runLoggingT logFunc $ createSqlitePool (sqlDatabase $ appDatabaseConf appSettings) (sqlPoolSize $ appDatabaseConf appSettings) -- Perform database migration using our application's logging settings. runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc -- Return the foundation return $ mkFoundation pool -- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and -- applying some additional middlewares. makeApplication :: App -> IO Application makeApplication foundation = do logWare <- mkRequestLogger def { outputFormat = if appDetailedRequestLogging $ appSettings foundation then Detailed True else Apache (if appIpFromHeader $ appSettings foundation then FromFallback else FromSocket) , destination = Logger $ loggerSet $ appLogger foundation } -- Create the WAI application and apply middlewares appPlain <- toWaiAppPlain foundation return $ logWare $ defaultMiddlewaresNoLogging appPlain -- | Warp settings for the given foundation value. warpSettings :: App -> Settings warpSettings foundation = setPort (appPort $ appSettings foundation) $ setHost (appHost $ appSettings foundation) $ setOnException (\_req e -> when (defaultShouldDisplayException e) $ messageLoggerSource foundation (appLogger foundation) $(qLocation >>= liftLoc) "yesod" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) defaultSettings -- | For yesod devel, return the Warp settings and WAI Application. getApplicationDev :: IO (Settings, Application) getApplicationDev = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app <- makeApplication foundation return (wsettings, app) getAppSettings :: IO AppSettings getAppSettings = loadAppSettings [configSettingsYml] [] useEnv -- | main function for use by yesod devel develMain :: IO () develMain = develMainHelper getApplicationDev -- | The @main@ function for an executable running this site. appMain :: IO () appMain = do -- Get the settings from all relevant sources settings <- loadAppSettingsArgs -- fall back to compile-time values, set to [] to require values at runtime [configSettingsYmlValue] -- allow environment variables to override useEnv -- Generate the foundation from the settings foundation <- makeFoundation settings -- Generate a WAI Application from the foundation app <- makeApplication foundation -- Run the application with Warp runSettings (warpSettings foundation) app -------------------------------------------------------------- -- Functions for DevelMain.hs (a way to run the app from GHCi) -------------------------------------------------------------- getApplicationRepl :: IO (Int, App, Application) getApplicationRepl = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app1 <- makeApplication foundation return (getPort wsettings, foundation, app1) shutdownApp :: App -> IO () shutdownApp _ = return () --------------------------------------------- -- Functions for use in development with GHCi --------------------------------------------- -- | Run a handler handler :: Handler a -> IO a handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h -- | Run DB queries db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a db = handler . runDB -- vim:set expandtab:
tmcl/katalogo
backend/sqlite/Application.hs
gpl-3.0
6,818
0
16
1,764
1,013
543
470
-1
-1
{-| hledger - a ledger-compatible accounting tool. Copyright (c) 2007-2011 Simon Michael <simon@joyful.com> Released under GPL version 3 or later. hledger is a partial haskell clone of John Wiegley's "ledger". It generates ledger-compatible register & balance reports from a plain text journal, and demonstrates a functional implementation of ledger. For more information, see http:\/\/hledger.org . This module provides the main function for the hledger command-line executable. It is exposed here so that it can be imported by eg benchmark scripts. You can use the command line: > $ hledger --help or ghci: > $ ghci hledger > > j <- readJournalFile Nothing Nothing True "examples/sample.journal" > > register [] ["income","expenses"] j > 2008/01/01 income income:salary $-1 $-1 > 2008/06/01 gift income:gifts $-1 $-2 > 2008/06/03 eat & shop expenses:food $1 $-1 > expenses:supplies $1 0 > > balance [Depth "1"] [] l > $-1 assets > $2 expenses > $-2 income > $1 liabilities > > l <- myLedger See "Hledger.Data.Ledger" for more examples. -} {-# LANGUAGE QuasiQuotes #-} module Hledger.Cli.Main where -- import Control.Monad import Data.Char (isDigit) import Data.String.Here import Data.List import Data.List.Split (splitOn) import Safe import System.Console.CmdArgs.Explicit as C import System.Environment import System.Exit import System.FilePath import System.Process import Text.Printf import Hledger (ensureJournalFileExists) import Hledger.Cli.Add import Hledger.Cli.Accounts import Hledger.Cli.Balance import Hledger.Cli.Balancesheet import Hledger.Cli.Cashflow import Hledger.Cli.Help import Hledger.Cli.Histogram import Hledger.Cli.Incomestatement import Hledger.Cli.Info import Hledger.Cli.Man import Hledger.Cli.Print import Hledger.Cli.Register import Hledger.Cli.Stats import Hledger.Cli.CliOptions import Hledger.Cli.Tests import Hledger.Cli.Utils import Hledger.Cli.Version import Hledger.Data.Dates (getCurrentDay) import Hledger.Data.RawOptions (RawOpts) import Hledger.Reports.ReportOptions (period_, interval_, queryFromOpts) import Hledger.Utils -- | The overall cmdargs mode describing command-line options for hledger. mainmode addons = defMode { modeNames = [progname ++ " [CMD]"] ,modeArgs = ([], Just $ argsFlag "[ARGS]") ,modeHelp = unlines ["hledger's main command line interface. Runs builtin commands and other hledger executables. Type \"hledger\" to list available commands."] ,modeGroupModes = Group { -- subcommands in the unnamed group, shown first: groupUnnamed = [ ] -- subcommands in named groups: ,groupNamed = [ ] -- subcommands handled but not shown in the help: ,groupHidden = [ oldconvertmode ,accountsmode ,activitymode ,addmode ,balancemode ,balancesheetmode ,cashflowmode ,helpmode ,incomestatementmode ,infomode ,manmode ,printmode ,registermode ,statsmode ,testmode ] ++ map quickAddonCommandMode addons } ,modeGroupFlags = Group { -- flags in named groups: groupNamed = [ ( "General input flags", inputflags) ,("\nGeneral reporting flags", reportflags) ,("\nGeneral help flags", helpflags) ] -- flags in the unnamed group, shown last: ,groupUnnamed = [] -- flags handled but not shown in the help: ,groupHidden = [detailedversionflag] -- ++ inputflags -- included here so they'll not raise a confusing error if present with no COMMAND } ,modeHelpSuffix = lines $ regexReplace "PROGNAME" progname [here|Examples: PROGNAME list commands PROGNAME CMD [--] [OPTS] [ARGS] run a command (use -- with addon commands) PROGNAME-CMD [OPTS] [ARGS] or run addon commands directly PROGNAME -h show general usage PROGNAME CMD -h show command usage PROGNAME help [MANUAL] show any of the hledger manuals in various formats |] } oldconvertmode = (defCommandMode ["convert"]) { modeValue = [("command","convert")] ,modeHelp = "convert is no longer needed, just use -f FILE.csv" ,modeArgs = ([], Just $ argsFlag "[CSVFILE]") ,modeGroupFlags = Group { groupUnnamed = [] ,groupHidden = helpflags ,groupNamed = [] } } builtinCommands :: [Mode RawOpts] builtinCommands = let gs = modeGroupModes $ mainmode [] in concatMap snd (groupNamed gs) ++ groupUnnamed gs ++ groupHidden gs builtinCommandNames :: [String] builtinCommandNames = concatMap modeNames builtinCommands -- | Parse hledger CLI options from these command line arguments and -- add-on command names, or raise any error. argsToCliOpts :: [String] -> [String] -> IO CliOpts argsToCliOpts args addons = do let args' = moveFlagsAfterCommand args cmdargsopts = either usageError id $ process (mainmode addons) args' cmdargsopts' = decodeRawOpts cmdargsopts rawOptsToCliOpts cmdargsopts' -- | A hacky workaround for cmdargs not accepting flags before the -- subcommand name: try to detect and move such flags after the -- command. This allows the user to put them in either position. -- The order of options is not preserved, but this should be ok. -- -- Since we're not parsing flags as precisely as cmdargs here, this is -- imperfect. We make a decent effort to: -- - move all no-argument help/input/report flags -- - move all required-argument help/input/report flags along with their values, space-separated or not -- - not confuse things further or cause misleading errors. moveFlagsAfterCommand :: [String] -> [String] moveFlagsAfterCommand args = moveArgs $ ensureDebugHasArg args where -- quickly! make sure --debug has a numeric argument, or this all goes to hell ensureDebugHasArg as = case break (=="--debug") as of (bs,"--debug":c:cs) | null c || not (all isDigit c) -> bs++"--debug=1":c:cs (bs,"--debug":[]) -> bs++"--debug=1":[] _ -> as -- -h ..., --version ... moveArgs (f:a:as) | isMovableNoArgFlag f = (moveArgs $ a:as) ++ [f] -- -f FILE ..., --alias ALIAS ... moveArgs (f:v:a:as) | isMovableReqArgFlag f, isValue v = (moveArgs $ a:as) ++ [f,v] -- -fFILE ..., --alias=ALIAS ... moveArgs (fv:a:as) | isMovableReqArgFlagAndValue fv = (moveArgs $ a:as) ++ [fv] -- -f(missing arg) moveArgs (f:a:as) | isMovableReqArgFlag f, not (isValue a) = (moveArgs $ a:as) ++ [f] -- anything else moveArgs as = as isMovableNoArgFlag a = "-" `isPrefixOf` a && dropWhile (=='-') a `elem` noargflagstomove isMovableReqArgFlag a = "-" `isPrefixOf` a && dropWhile (=='-') a `elem` reqargflagstomove isMovableReqArgFlagAndValue ('-':'-':a:as) = case break (== '=') (a:as) of (f:fs,_:_) -> (f:fs) `elem` reqargflagstomove _ -> False isMovableReqArgFlagAndValue ('-':shortflag:_:_) = [shortflag] `elem` reqargflagstomove isMovableReqArgFlagAndValue _ = False isValue "-" = True isValue ('-':_) = False isValue _ = True flagstomove = inputflags ++ reportflags ++ helpflags noargflagstomove = concatMap flagNames $ filter ((==FlagNone).flagInfo) flagstomove reqargflagstomove = -- filter (/= "debug") $ concatMap flagNames $ filter ((==FlagReq ).flagInfo) flagstomove -- | Template for the commands list. -- Includes an entry for all known or hypothetical builtin and addon commands; -- these will be filtered based on the commands found at runtime. -- Commands beginning with "hledger" are not filtered ("hledger -h" etc.) -- COUNT is replaced with the number of commands found. -- OTHERCMDS is replaced with an entry for each unknown addon command found. -- The command descriptions here should be synced with each command's builtin help -- and with hledger manual's command list. commandsListTemplate :: String commandsListTemplate = [here|Commands available (COUNT): Standard reports: accounts show chart of accounts balancesheet (bs) show a balance sheet cashflow (cf) show a cashflow statement incomestatement (is) show an income statement transactions (txns) show transactions in some account General reporting: activity show a bar chart of posting counts per interval balance (bal) show accounts and balances budget add automated postings/txns/bucket accts (experimental) chart generate simple balance pie charts (experimental) check check more powerful balance assertions check-dates check transactions are ordered by date check-dupes check for accounts with the same leaf name irr calculate internal rate of return of an investment prices show market price records print show transaction journal entries print-unique show only transactions with unique descriptions register (reg) show postings and running total register-match show best matching transaction for a description stats show some journal statistics Interfaces: add console ui for adding transactions api web api server iadd curses ui for adding transactions ui curses ui web web ui Misc: autosync download/deduplicate/convert OFX data equity generate transactions to zero & restore account balances interest generate interest transactions rewrite add automated postings to certain transactions test run some self tests OTHERCMDS Help: help show any of the hledger manuals in various formats hledger CMD -h show command usage hledger -h show general usage |] knownCommands :: [String] knownCommands = sort $ commandsFromCommandsList commandsListTemplate -- | Extract the command names from a commands list like the above: -- the first word (or words separated by |) of lines beginning with a space. commandsFromCommandsList :: String -> [String] commandsFromCommandsList s = concatMap (splitOn "|") [w | ' ':l <- lines s, let w:_ = words l] -- | Print the commands list, modifying the template above based on -- the currently available addons. Missing addons will be removed, and -- extra addons will be added under Misc. printCommandsList :: [String] -> IO () printCommandsList addonsFound = putStr commandsList where commandsFound = builtinCommandNames ++ addonsFound unknownCommandsFound = addonsFound \\ knownCommands adjustline l | " hledger " `isPrefixOf` l = [l] adjustline (' ':l) | not $ w `elem` commandsFound = [] where w = takeWhile (not . (`elem` "| ")) l adjustline l = [l] commandsList1 = regexReplace "OTHERCMDS" (unlines [' ':w | w <- unknownCommandsFound]) $ unlines $ concatMap adjustline $ lines commandsListTemplate commandsList = regexReplace "COUNT" (show $ length $ commandsFromCommandsList commandsList1) commandsList1 -- | Let's go. main :: IO () main = do -- Choose and run the appropriate internal or external command based -- on the raw command-line arguments, cmdarg's interpretation of -- same, and hledger-* executables in the user's PATH. A somewhat -- complex mishmash of cmdargs and custom processing, hence all the -- debugging support and tests. See also Hledger.Cli.CliOptions and -- command-line.test. -- some preliminary (imperfect) argument parsing to supplement cmdargs args <- getArgs let args' = moveFlagsAfterCommand args isFlag = ("-" `isPrefixOf`) isNonEmptyNonFlag s = not (isFlag s) && not (null s) rawcmd = headDef "" $ takeWhile isNonEmptyNonFlag args' isNullCommand = null rawcmd (argsbeforecmd, argsaftercmd') = break (==rawcmd) args argsaftercmd = drop 1 argsaftercmd' dbgIO :: Show a => String -> a -> IO () dbgIO = tracePrettyAtIO 2 dbgIO "running" prognameandversion dbgIO "raw args" args dbgIO "raw args rearranged for cmdargs" args' dbgIO "raw command is probably" rawcmd dbgIO "raw args before command" argsbeforecmd dbgIO "raw args after command" argsaftercmd -- Search PATH for add-ons, excluding any that match built-in command names addons' <- hledgerAddons let addons = filter (not . (`elem` builtinCommandNames) . dropExtension) addons' -- parse arguments with cmdargs opts <- argsToCliOpts args addons -- select an action and run it. let cmd = command_ opts -- the full matched internal or external command name, if any isInternalCommand = cmd `elem` builtinCommandNames -- not (null cmd) && not (cmd `elem` addons) isExternalCommand = not (null cmd) && cmd `elem` addons -- probably isBadCommand = not (null rawcmd) && null cmd hasVersion = ("--version" `elem`) hasDetailedVersion = ("--version+" `elem`) printUsage = putStr $ showModeUsage $ mainmode addons badCommandError = error' ("command "++rawcmd++" is not recognized, run with no command to see a list") >> exitFailure hasHelpFlag args = any (`elem` args) ["-h","--help"] f `orShowHelp` mode | hasHelpFlag args = putStr $ showModeUsage mode | otherwise = f dbgIO "processed opts" opts dbgIO "command matched" cmd dbgIO "isNullCommand" isNullCommand dbgIO "isInternalCommand" isInternalCommand dbgIO "isExternalCommand" isExternalCommand dbgIO "isBadCommand" isBadCommand d <- getCurrentDay dbgIO "period from opts" (period_ $ reportopts_ opts) dbgIO "interval from opts" (interval_ $ reportopts_ opts) dbgIO "query from opts & args" (queryFromOpts d $ reportopts_ opts) let runHledgerCommand -- high priority flags and situations. -h, then --help, then --info are highest priority. | hasHelpFlag argsbeforecmd = dbgIO "" "-h before command, showing general usage" >> printUsage | not (hasHelpFlag argsaftercmd) && (hasVersion argsbeforecmd || (hasVersion argsaftercmd && isInternalCommand)) = putStrLn prognameandversion | not (hasHelpFlag argsaftercmd) && (hasDetailedVersion argsbeforecmd || (hasDetailedVersion argsaftercmd && isInternalCommand)) = putStrLn prognameanddetailedversion -- \| (null externalcmd) && "binary-filename" `inRawOpts` rawopts = putStrLn $ binaryfilename progname -- \| "--browse-args" `elem` args = System.Console.CmdArgs.Helper.execute "cmdargs-browser" mainmode' args >>= (putStr . show) | isNullCommand = dbgIO "" "no command, showing commands list" >> printCommandsList addons | isBadCommand = badCommandError -- internal commands | cmd == "activity" = withJournalDo opts histogram `orShowHelp` activitymode | cmd == "add" = (journalFilePathFromOpts opts >>= (ensureJournalFileExists . head) >> withJournalDo opts add) `orShowHelp` addmode | cmd == "accounts" = withJournalDo opts accounts `orShowHelp` accountsmode | cmd == "balance" = withJournalDo opts balance `orShowHelp` balancemode | cmd == "balancesheet" = withJournalDo opts balancesheet `orShowHelp` balancesheetmode | cmd == "cashflow" = withJournalDo opts cashflow `orShowHelp` cashflowmode | cmd == "incomestatement" = withJournalDo opts incomestatement `orShowHelp` incomestatementmode | cmd == "print" = withJournalDo opts print' `orShowHelp` printmode | cmd == "register" = withJournalDo opts register `orShowHelp` registermode | cmd == "stats" = withJournalDo opts stats `orShowHelp` statsmode | cmd == "test" = test' opts `orShowHelp` testmode | cmd == "help" = help' opts `orShowHelp` helpmode | cmd == "man" = man opts `orShowHelp` manmode | cmd == "info" = info' opts `orShowHelp` infomode -- an external command | isExternalCommand = do let externalargs = argsbeforecmd ++ filter (not.(=="--")) argsaftercmd let shellcmd = printf "%s-%s %s" progname cmd (unwords' externalargs) :: String dbgIO "external command selected" cmd dbgIO "external command arguments" (map quoteIfNeeded externalargs) dbgIO "running shell command" shellcmd system shellcmd >>= exitWith -- deprecated commands | cmd == "convert" = error' (modeHelp oldconvertmode) >> exitFailure -- shouldn't reach here | otherwise = usageError ("could not understand the arguments "++show args) >> exitFailure runHledgerCommand -- tests_runHledgerCommand = [ -- -- "runHledgerCommand" ~: do -- -- let opts = defreportopts{query_="expenses"} -- -- d <- getCurrentDay -- -- runHledgerCommand addons opts@CliOpts{command_=cmd} args -- ]
mstksg/hledger
hledger/Hledger/Cli/Main.hs
gpl-3.0
17,527
1
20
4,495
2,955
1,583
1,372
212
7
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.Glacier.SetDataRetrievalPolicy -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-SetDataRetrievalPolicy.html> module Network.AWS.Glacier.SetDataRetrievalPolicy ( -- * Request SetDataRetrievalPolicy -- ** Request constructor , setDataRetrievalPolicy -- ** Request lenses , sdrpAccountId , sdrpPolicy -- * Response , SetDataRetrievalPolicyResponse -- ** Response constructor , setDataRetrievalPolicyResponse ) where import Network.AWS.Prelude import Network.AWS.Request.RestJSON import Network.AWS.Glacier.Types import qualified GHC.Exts data SetDataRetrievalPolicy = SetDataRetrievalPolicy { _sdrpAccountId :: Text , _sdrpPolicy :: Maybe DataRetrievalPolicy } deriving (Eq, Read, Show) -- | 'SetDataRetrievalPolicy' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sdrpAccountId' @::@ 'Text' -- -- * 'sdrpPolicy' @::@ 'Maybe' 'DataRetrievalPolicy' -- setDataRetrievalPolicy :: Text -- ^ 'sdrpAccountId' -> SetDataRetrievalPolicy setDataRetrievalPolicy p1 = SetDataRetrievalPolicy { _sdrpAccountId = p1 , _sdrpPolicy = Nothing } sdrpAccountId :: Lens' SetDataRetrievalPolicy Text sdrpAccountId = lens _sdrpAccountId (\s a -> s { _sdrpAccountId = a }) sdrpPolicy :: Lens' SetDataRetrievalPolicy (Maybe DataRetrievalPolicy) sdrpPolicy = lens _sdrpPolicy (\s a -> s { _sdrpPolicy = a }) data SetDataRetrievalPolicyResponse = SetDataRetrievalPolicyResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'SetDataRetrievalPolicyResponse' constructor. setDataRetrievalPolicyResponse :: SetDataRetrievalPolicyResponse setDataRetrievalPolicyResponse = SetDataRetrievalPolicyResponse instance ToPath SetDataRetrievalPolicy where toPath SetDataRetrievalPolicy{..} = mconcat [ "/" , toText _sdrpAccountId , "/policies/data-retrieval" ] instance ToQuery SetDataRetrievalPolicy where toQuery = const mempty instance ToHeaders SetDataRetrievalPolicy instance ToJSON SetDataRetrievalPolicy where toJSON SetDataRetrievalPolicy{..} = object [ "Policy" .= _sdrpPolicy ] instance AWSRequest SetDataRetrievalPolicy where type Sv SetDataRetrievalPolicy = Glacier type Rs SetDataRetrievalPolicy = SetDataRetrievalPolicyResponse request = put response = nullResponse SetDataRetrievalPolicyResponse
dysinger/amazonka
amazonka-glacier/gen/Network/AWS/Glacier/SetDataRetrievalPolicy.hs
mpl-2.0
3,432
0
9
718
414
248
166
55
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AndroidEnterprise.Grouplicenses.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves IDs of all products for which the enterprise has a group -- license. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.grouplicenses.list@. module Network.Google.Resource.AndroidEnterprise.Grouplicenses.List ( -- * REST Resource GrouplicensesListResource -- * Creating a Request , grouplicensesList , GrouplicensesList -- * Request Lenses , glXgafv , glUploadProtocol , glEnterpriseId , glAccessToken , glUploadType , glCallback ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.grouplicenses.list@ method which the -- 'GrouplicensesList' request conforms to. type GrouplicensesListResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "groupLicenses" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] GroupLicensesListResponse -- | Retrieves IDs of all products for which the enterprise has a group -- license. -- -- /See:/ 'grouplicensesList' smart constructor. data GrouplicensesList = GrouplicensesList' { _glXgafv :: !(Maybe Xgafv) , _glUploadProtocol :: !(Maybe Text) , _glEnterpriseId :: !Text , _glAccessToken :: !(Maybe Text) , _glUploadType :: !(Maybe Text) , _glCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GrouplicensesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'glXgafv' -- -- * 'glUploadProtocol' -- -- * 'glEnterpriseId' -- -- * 'glAccessToken' -- -- * 'glUploadType' -- -- * 'glCallback' grouplicensesList :: Text -- ^ 'glEnterpriseId' -> GrouplicensesList grouplicensesList pGlEnterpriseId_ = GrouplicensesList' { _glXgafv = Nothing , _glUploadProtocol = Nothing , _glEnterpriseId = pGlEnterpriseId_ , _glAccessToken = Nothing , _glUploadType = Nothing , _glCallback = Nothing } -- | V1 error format. glXgafv :: Lens' GrouplicensesList (Maybe Xgafv) glXgafv = lens _glXgafv (\ s a -> s{_glXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). glUploadProtocol :: Lens' GrouplicensesList (Maybe Text) glUploadProtocol = lens _glUploadProtocol (\ s a -> s{_glUploadProtocol = a}) -- | The ID of the enterprise. glEnterpriseId :: Lens' GrouplicensesList Text glEnterpriseId = lens _glEnterpriseId (\ s a -> s{_glEnterpriseId = a}) -- | OAuth access token. glAccessToken :: Lens' GrouplicensesList (Maybe Text) glAccessToken = lens _glAccessToken (\ s a -> s{_glAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). glUploadType :: Lens' GrouplicensesList (Maybe Text) glUploadType = lens _glUploadType (\ s a -> s{_glUploadType = a}) -- | JSONP glCallback :: Lens' GrouplicensesList (Maybe Text) glCallback = lens _glCallback (\ s a -> s{_glCallback = a}) instance GoogleRequest GrouplicensesList where type Rs GrouplicensesList = GroupLicensesListResponse type Scopes GrouplicensesList = '["https://www.googleapis.com/auth/androidenterprise"] requestClient GrouplicensesList'{..} = go _glEnterpriseId _glXgafv _glUploadProtocol _glAccessToken _glUploadType _glCallback (Just AltJSON) androidEnterpriseService where go = buildClient (Proxy :: Proxy GrouplicensesListResource) mempty
brendanhay/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Grouplicenses/List.hs
mpl-2.0
4,793
0
18
1,144
708
413
295
105
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Triggers.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a GTM Trigger. -- -- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.triggers.get@. module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Triggers.Get ( -- * REST Resource AccountsContainersWorkspacesTriggersGetResource -- * Creating a Request , accountsContainersWorkspacesTriggersGet , AccountsContainersWorkspacesTriggersGet -- * Request Lenses , acwtgcXgafv , acwtgcUploadProtocol , acwtgcPath , acwtgcAccessToken , acwtgcUploadType , acwtgcCallback ) where import Network.Google.Prelude import Network.Google.TagManager.Types -- | A resource alias for @tagmanager.accounts.containers.workspaces.triggers.get@ method which the -- 'AccountsContainersWorkspacesTriggersGet' request conforms to. type AccountsContainersWorkspacesTriggersGetResource = "tagmanager" :> "v2" :> Capture "path" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Trigger -- | Gets a GTM Trigger. -- -- /See:/ 'accountsContainersWorkspacesTriggersGet' smart constructor. data AccountsContainersWorkspacesTriggersGet = AccountsContainersWorkspacesTriggersGet' { _acwtgcXgafv :: !(Maybe Xgafv) , _acwtgcUploadProtocol :: !(Maybe Text) , _acwtgcPath :: !Text , _acwtgcAccessToken :: !(Maybe Text) , _acwtgcUploadType :: !(Maybe Text) , _acwtgcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsContainersWorkspacesTriggersGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acwtgcXgafv' -- -- * 'acwtgcUploadProtocol' -- -- * 'acwtgcPath' -- -- * 'acwtgcAccessToken' -- -- * 'acwtgcUploadType' -- -- * 'acwtgcCallback' accountsContainersWorkspacesTriggersGet :: Text -- ^ 'acwtgcPath' -> AccountsContainersWorkspacesTriggersGet accountsContainersWorkspacesTriggersGet pAcwtgcPath_ = AccountsContainersWorkspacesTriggersGet' { _acwtgcXgafv = Nothing , _acwtgcUploadProtocol = Nothing , _acwtgcPath = pAcwtgcPath_ , _acwtgcAccessToken = Nothing , _acwtgcUploadType = Nothing , _acwtgcCallback = Nothing } -- | V1 error format. acwtgcXgafv :: Lens' AccountsContainersWorkspacesTriggersGet (Maybe Xgafv) acwtgcXgafv = lens _acwtgcXgafv (\ s a -> s{_acwtgcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). acwtgcUploadProtocol :: Lens' AccountsContainersWorkspacesTriggersGet (Maybe Text) acwtgcUploadProtocol = lens _acwtgcUploadProtocol (\ s a -> s{_acwtgcUploadProtocol = a}) -- | GTM Trigger\'s API relative path. Example: -- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id}\/triggers\/{trigger_id} acwtgcPath :: Lens' AccountsContainersWorkspacesTriggersGet Text acwtgcPath = lens _acwtgcPath (\ s a -> s{_acwtgcPath = a}) -- | OAuth access token. acwtgcAccessToken :: Lens' AccountsContainersWorkspacesTriggersGet (Maybe Text) acwtgcAccessToken = lens _acwtgcAccessToken (\ s a -> s{_acwtgcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). acwtgcUploadType :: Lens' AccountsContainersWorkspacesTriggersGet (Maybe Text) acwtgcUploadType = lens _acwtgcUploadType (\ s a -> s{_acwtgcUploadType = a}) -- | JSONP acwtgcCallback :: Lens' AccountsContainersWorkspacesTriggersGet (Maybe Text) acwtgcCallback = lens _acwtgcCallback (\ s a -> s{_acwtgcCallback = a}) instance GoogleRequest AccountsContainersWorkspacesTriggersGet where type Rs AccountsContainersWorkspacesTriggersGet = Trigger type Scopes AccountsContainersWorkspacesTriggersGet = '["https://www.googleapis.com/auth/tagmanager.edit.containers", "https://www.googleapis.com/auth/tagmanager.readonly"] requestClient AccountsContainersWorkspacesTriggersGet'{..} = go _acwtgcPath _acwtgcXgafv _acwtgcUploadProtocol _acwtgcAccessToken _acwtgcUploadType _acwtgcCallback (Just AltJSON) tagManagerService where go = buildClient (Proxy :: Proxy AccountsContainersWorkspacesTriggersGetResource) mempty
brendanhay/gogol
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Triggers/Get.hs
mpl-2.0
5,523
0
16
1,171
705
413
292
110
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Healthcare.Projects.Locations.DataSets.Hl7V2Stores.SetIAMPolicy -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets the access control policy on the specified resource. Replaces any -- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and -- \`PERMISSION_DENIED\` errors. -- -- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.hl7V2Stores.setIamPolicy@. module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.Hl7V2Stores.SetIAMPolicy ( -- * REST Resource ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicyResource -- * Creating a Request , projectsLocationsDataSetsHl7V2StoresSetIAMPolicy , ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy -- * Request Lenses , pldshvssipXgafv , pldshvssipUploadProtocol , pldshvssipAccessToken , pldshvssipUploadType , pldshvssipPayload , pldshvssipResource , pldshvssipCallback ) where import Network.Google.Healthcare.Types import Network.Google.Prelude -- | A resource alias for @healthcare.projects.locations.datasets.hl7V2Stores.setIamPolicy@ method which the -- 'ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy' request conforms to. type ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicyResource = "v1" :> CaptureMode "resource" "setIamPolicy" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SetIAMPolicyRequest :> Post '[JSON] Policy -- | Sets the access control policy on the specified resource. Replaces any -- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and -- \`PERMISSION_DENIED\` errors. -- -- /See:/ 'projectsLocationsDataSetsHl7V2StoresSetIAMPolicy' smart constructor. data ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy = ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy' { _pldshvssipXgafv :: !(Maybe Xgafv) , _pldshvssipUploadProtocol :: !(Maybe Text) , _pldshvssipAccessToken :: !(Maybe Text) , _pldshvssipUploadType :: !(Maybe Text) , _pldshvssipPayload :: !SetIAMPolicyRequest , _pldshvssipResource :: !Text , _pldshvssipCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pldshvssipXgafv' -- -- * 'pldshvssipUploadProtocol' -- -- * 'pldshvssipAccessToken' -- -- * 'pldshvssipUploadType' -- -- * 'pldshvssipPayload' -- -- * 'pldshvssipResource' -- -- * 'pldshvssipCallback' projectsLocationsDataSetsHl7V2StoresSetIAMPolicy :: SetIAMPolicyRequest -- ^ 'pldshvssipPayload' -> Text -- ^ 'pldshvssipResource' -> ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy projectsLocationsDataSetsHl7V2StoresSetIAMPolicy pPldshvssipPayload_ pPldshvssipResource_ = ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy' { _pldshvssipXgafv = Nothing , _pldshvssipUploadProtocol = Nothing , _pldshvssipAccessToken = Nothing , _pldshvssipUploadType = Nothing , _pldshvssipPayload = pPldshvssipPayload_ , _pldshvssipResource = pPldshvssipResource_ , _pldshvssipCallback = Nothing } -- | V1 error format. pldshvssipXgafv :: Lens' ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy (Maybe Xgafv) pldshvssipXgafv = lens _pldshvssipXgafv (\ s a -> s{_pldshvssipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pldshvssipUploadProtocol :: Lens' ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy (Maybe Text) pldshvssipUploadProtocol = lens _pldshvssipUploadProtocol (\ s a -> s{_pldshvssipUploadProtocol = a}) -- | OAuth access token. pldshvssipAccessToken :: Lens' ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy (Maybe Text) pldshvssipAccessToken = lens _pldshvssipAccessToken (\ s a -> s{_pldshvssipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pldshvssipUploadType :: Lens' ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy (Maybe Text) pldshvssipUploadType = lens _pldshvssipUploadType (\ s a -> s{_pldshvssipUploadType = a}) -- | Multipart request metadata. pldshvssipPayload :: Lens' ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy SetIAMPolicyRequest pldshvssipPayload = lens _pldshvssipPayload (\ s a -> s{_pldshvssipPayload = a}) -- | REQUIRED: The resource for which the policy is being specified. See the -- operation documentation for the appropriate value for this field. pldshvssipResource :: Lens' ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy Text pldshvssipResource = lens _pldshvssipResource (\ s a -> s{_pldshvssipResource = a}) -- | JSONP pldshvssipCallback :: Lens' ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy (Maybe Text) pldshvssipCallback = lens _pldshvssipCallback (\ s a -> s{_pldshvssipCallback = a}) instance GoogleRequest ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy where type Rs ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy = Policy type Scopes ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicy'{..} = go _pldshvssipResource _pldshvssipXgafv _pldshvssipUploadProtocol _pldshvssipAccessToken _pldshvssipUploadType _pldshvssipCallback (Just AltJSON) _pldshvssipPayload healthcareService where go = buildClient (Proxy :: Proxy ProjectsLocationsDataSetsHl7V2StoresSetIAMPolicyResource) mempty
brendanhay/gogol
gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/Hl7V2Stores/SetIAMPolicy.hs
mpl-2.0
6,868
0
16
1,368
784
460
324
126
1
{-# LANGUAGE TypeOperators, CPP, TypeFamilies , DeriveDataTypeable, StandaloneDeriving #-} {-# OPTIONS_GHC -Wall #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Complex -- Copyright : (c) The University of Glasgow 2001, Conal Elliott 2009 -- License : BSD-style -- -- Maintainer : conal@conal.net -- Stability : provisional -- Portability : portable -- -- Complex numbers. This version is modified from Data.Complex in base. -- It eliminates the RealFloat requirement by using a more naive -- definition of 'magnitude'. Also, defines instances for vector-space classes. -- ----------------------------------------------------------------------------- module Shady.Complex ( -- * Rectangular form Complex((:+)) , realPart -- :: Complex a -> a , imagPart -- :: Complex a -> a -- * Polar form , mkPolar -- :: a -> a -> Complex a , cis -- :: a -> Complex a , polar -- :: Complex a -> (a,a) -- , magnitude -- :: Complex a -> a , phase -- :: Complex a -> a -- * Conjugate , conjugate -- :: Complex a -> Complex a -- Complex instances: (Eq,Read,Show,Num,Fractional,Floating) -- Complex instances: (AdditiveGroup, VectorSpace, InnerSpace) -- * Misc interface additions , onRI, onRI2 ) where import Prelude import Data.Typeable #ifdef __GLASGOW_HASKELL__ import Data.Data (Data) #endif #ifdef __HUGS__ import Hugs.Prelude(Num(fromInt), Fractional(fromDouble)) #endif import Data.VectorSpace import Shady.Misc (Unop,Binop,FMod(..),Frac(..)) import Text.PrettyPrint.Leijen (Pretty(..),text) import Text.PrettyPrint.Leijen.DocExpr import Text.PrettyPrint.Leijen.PrettyPrec (PrettyPrec(..)) infix 6 :+ -- ----------------------------------------------------------------------------- -- The Complex type -- | Complex numbers are an algebraic type. -- -- For a complex number @z@, @'abs' z@ is a number with the magnitude of @z@, -- but oriented in the positive real direction, whereas @'signum' z@ -- has the phase of @z@, but unit magnitude. data Complex a = !a :+ !a -- ^ forms a complex number from its real and imaginary -- rectangular components. # if __GLASGOW_HASKELL__ deriving (Eq, Show, Read, Typeable, Data) # else deriving (Eq, Show, Read) # endif -- ----------------------------------------------------------------------------- -- Functions over Complex -- | Extracts the real part of a complex number. realPart :: Complex a -> a realPart (x :+ _) = x -- | Extracts the imaginary part of a complex number. imagPart :: Complex a -> a imagPart (_ :+ y) = y -- | The conjugate of a complex number. {-# SPECIALISE conjugate :: Complex Double -> Complex Double #-} conjugate :: Num a => Unop (Complex a) conjugate (x:+y) = x :+ (-y) -- | Form a complex number from polar components of magnitude and phase. {-# SPECIALISE mkPolar :: Double -> Double -> Complex Double #-} mkPolar :: Floating a => a -> a -> Complex a mkPolar r theta = r * cos theta :+ r * sin theta -- | @'cis' t@ is a complex value with magnitude @1@ -- and phase @t@ (modulo @2*'pi'@). {-# SPECIALISE cis :: Double -> Complex Double #-} cis :: Floating a => a -> Complex a cis theta = cos theta :+ sin theta -- | The function 'polar' takes a complex number and -- returns a (magnitude, phase) pair in canonical form: -- the magnitude is nonnegative, and the phase in the range @(-'pi', 'pi']@; -- if the magnitude is zero, then so is the phase. {-# SPECIALISE polar :: Complex Double -> (Double,Double) #-} polar :: (Eq a, Floating a, AdditiveGroup a) => Complex a -> (a,a) polar z = (magnitude z, phase z) -- | Operate on the real & imaginary components onRI :: Unop a -> Unop (Complex a) onRI f (x :+ y) = f x :+ f y -- | Operate on the real & imaginary components onRI2 :: Binop a -> Binop (Complex a) onRI2 f (x :+ y) (x' :+ y') = f x x' :+ f y y' instance (Eq a, Floating a, AdditiveGroup a) => AdditiveGroup (Complex a) where -- About Eq: see the comment on the Num instance for Complex. Reconsider. { zeroV = 0 ; negateV = negate ; (^+^) = (+) } instance (Eq a, Floating a, AdditiveGroup a) => VectorSpace (Complex a) where type Scalar (Complex a) = a -- s *^ (x :+ y) = s * x :+ s * y (*^) s = onRI (s *) instance (Eq a, Floating a, AdditiveGroup a) => InnerSpace (Complex a) where (x :+ y) <.> (x' :+ y') = x*x' ^+^ y*y' -- TODO: Use (*^) in the VectorSpace and InnerSpace instances. {- -- | The nonnegative magnitude of a complex number. {-# SPECIALISE magnitude :: Complex Double -> Double #-} magnitude :: Floating a => Complex a -> a magnitude = sqrt . magSq magnitudeSq :: Floating a => Complex a -> a -- magnitude (x:+y) = scaleFloat k -- (sqrt (sqr (scaleFloat mk x) + sqr (scaleFloat mk y))) -- where k = max (exponent x) (exponent y) -- mk = - k -- sqr z = z * z -} -- | The phase of a complex number, in the range @(-'pi', 'pi']@. -- If the magnitude is zero, then so is the phase. {-# SPECIALISE phase :: Complex Double -> Double #-} phase :: Floating a => Complex a -> a -- The zero case requires a real EQ instance -- phase (0 :+ 0) = 0 -- SLPJ July 97 from John Peterson phase (x:+y) = atan2' y x -- To avoid reliance on 'RealFloat'. atan2' :: (Floating a) => a -> a -> a atan2' y x = atan (y/x) -- ----------------------------------------------------------------------------- -- Instances of Complex -- #include "Typeable.h" -- INSTANCE_TYPEABLE1(Complex,complexTc,"Complex") instance (Eq a, Floating a, AdditiveGroup a) => Num (Complex a) where -- The Eq here is needed with GHC 7.4.1 & later, given the signum -- (0:+0) case. Reconsider that case. {-# SPECIALISE instance Num (Complex Float) #-} {-# SPECIALISE instance Num (Complex Double) #-} (x:+y) + (x':+y') = (x+x') :+ (y+y') (x:+y) - (x':+y') = (x-x') :+ (y-y') (x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x') negate (x:+y) = negate x :+ negate y abs z = magnitude z :+ 0 signum (0:+0) = 0 signum z@(x:+y) = x/r :+ y/r where r = magnitude z fromInteger n = fromInteger n :+ 0 #ifdef __HUGS__ fromInt n = fromInt n :+ 0 #endif instance (Eq a, Floating a, AdditiveGroup a) => Fractional (Complex a) where {-# SPECIALISE instance Fractional (Complex Float) #-} {-# SPECIALISE instance Fractional (Complex Double) #-} (x:+y) / v@(x':+y') = ((x*x'+y*y') :+ (y*x'-x*y')) ^/ magnitudeSq v -- (x:+y) / (x':+y') = (x*x''+y*y'') / d :+ (y*x''-x*y'') / d -- where x'' = scaleFloat k x' -- y'' = scaleFloat k y' -- k = - max (exponent x') (exponent y') -- d = x'*x'' + y'*y'' fromRational a = fromRational a :+ 0 #ifdef __HUGS__ fromDouble a = fromDouble a :+ 0 #endif instance (Eq a, Floating a, AdditiveGroup a) => Floating (Complex a) where {-# SPECIALISE instance Floating (Complex Float) #-} {-# SPECIALISE instance Floating (Complex Double) #-} pi = pi :+ 0 exp (x:+y) = expx * cos y :+ expx * sin y where expx = exp x log z = log (magnitude z) :+ phase z -- x ** y = exp (log x * y) -- sqrt = (** 0.5) -- Use default sqrt (** 0.5) -- sqrt (0:+0) = 0 -- sqrt z@(x:+y) = u :+ (if y < 0 then -v else v) -- where (u,v) = if x < 0 then (v',u') else (u',v') -- v' = abs y / (u'*2) -- u' = sqrt ((magnitude z + abs x) / 2) sin (x:+y) = sin x * cosh y :+ cos x * sinh y cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y) tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy)) where sinx = sin x cosx = cos x sinhy = sinh y coshy = cosh y sinh (x:+y) = cos y * sinh x :+ sin y * cosh x cosh (x:+y) = cos y * cosh x :+ sin y * sinh x tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx) where siny = sin y cosy = cos y sinhx = sinh x coshx = cosh x asin z@(x:+y) = y':+(-x') where (x':+y') = log (((-y):+x) + sqrt (1 - z*z)) acos z = y'':+(-x'') where (x'':+y'') = log (z + ((-y'):+x')) (x':+y') = sqrt (1 - z*z) atan z@(x:+y) = y':+(-x') where (x':+y') = log (((1-y):+x) / sqrt (1+z*z)) asinh z = log (z + sqrt (1+z*z)) acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1))) atanh z = log ((1+z) / sqrt (1-z*z)) {-------------------------------------------------------------------- Pretty printing --------------------------------------------------------------------} instance Show a => Pretty (Complex a) where pretty = text . show instance Show a => PrettyPrec (Complex a) -- default -- TODO: Revisit this instance. Use p -- infix 6 :+ instance (Show a, HasExpr a) => HasExpr (Complex a) where expr (x :+ y) = op Infix 6 ":+" (expr x) (expr y) -- TODO: Do I really need HasExpr for Complex? I don't generate them in code. {-------------------------------------------------------------------- Misc --------------------------------------------------------------------} instance Frac s => Frac (Complex s) where frac = onRI frac instance FMod s => FMod (Complex s) where fmod = onRI2 fmod
conal/shady-gen
src/Shady/Complex.hs
agpl-3.0
9,989
1
14
2,914
2,378
1,293
1,085
118
1
-- for instance Functor Id => Applicative Id where {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} module APWE where import Control.Applicative import Control.Monad import qualified Data.Map as Map import Prelude hiding (Traversable, traverse) import Test.HUnit import Test.HUnit.Util -- http://www.soi.city.ac.uk/~ross/papers/Applicative.pdf ------------------------------------------------------------------------------ -- p. 2 Example: sequencing commands -- sequencing commands via Monad ap and return -- return :: Monad m => a -> m a -- http://hackage.haskell.org/package/base-4.6.0.0/docs/src/Control-Monad.html#ap liftM2' :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r liftM2' f m1 m2 = m1 >>= \x1 -> m2 >>= \x2 -> return (f x1 x2) -- > return f `ap` x1 `ap` ... `ap` xn -- equivalent to -- > liftMn f x1 x2 ... xn ap' :: (Monad m) => m (a -> b) -> m a -> m b ap' = liftM2' id seq' :: Monad m => [m a] -> m [a] seq' [] = return [] seq' (c : cs) = return (:) `ap'` c `ap'` seq' cs -- p. 4 -- sequencing commands via Applicative <*> and pure -- class Applicative f where -- (<*>) :: Applicative f => f (a -> b) -> f a -> f b -- pure :: Applicative f => a -> f a -- Note: Applicative generalizes S and K combinators (see eval below) -- from threading an environment to threading an effect in general. -- Can be defined using Monad operations (but the power of those operations not strictly needed). -- http://hackage.haskell.org/package/base-4.4.1.0/docs/src/Control-Applicative.html -- instance Applicative [] where -- pure = return -- (<*>) = ap seq'' :: Applicative f => [f a] -> f [a] seq'' [] = pure [] seq'' (c : cs) = pure (:) <*> c <*> seq'' cs ioa = [getLine,getLine,getLine] -- seq' ioa -- seq'' ioa t1 :: [Test] t1 = tt "t1" [ seq' [Just 1, Just 2 ] , seq'' [Just 1, Just 2 ] , (Just (:)) <*> (Just 1) <*> ( (Just (:)) <*> (Just 2) <*> (Just [])) , liftM2 id (Just (:)) (Just 1) <*> ( (Just (:)) <*> (Just 2) <*> (Just [])) , liftM2 id (liftM2 id (Just (:)) (Just 1)) ( (Just (:)) <*> (Just 2) <*> (Just [])) , liftM2 id (liftM2 id (Just (:)) (Just 1)) ( (liftM2 id (Just (:)) (Just 2)) <*> (Just [])) , liftM2 id (liftM2 id (Just (:)) (Just 1)) (liftM2 id (liftM2 id (Just (:)) (Just 2)) (Just [])) , liftM2 id (liftM2 id (Just (:)) (Just 1)) (liftM2 id ( Just (id (:) 2)) (Just [])) , liftM2 id (liftM2 id (Just (:)) (Just 1)) (liftM2 id ( Just ( (:) 2)) (Just [])) , liftM2 id (liftM2 id (Just (:)) (Just 1)) (Just ( (:) 2 [])) , liftM2 id (liftM2 id (Just (:)) (Just 1)) (Just [2 ]) , liftM2 id ( Just ((:) 1)) (Just [2 ]) , Just ( (:) 1 [2 ]) , Just [1, 2 ] ] (Just [1, 2]) ------------------------------------------------------------------------------ -- p. 2 Example: transposing 'matrices' -- typeclassopedia -- collection point of view -- pair functions and inputs elementwise and produce list of resulting outputs transpose :: [[a]] -> [[a]] transpose [] = repeat [] transpose (xs : xss) = zipWith (:) xs (transpose xss) repeat' :: a -> [a] repeat' x = x : repeat' x zapp :: [a -> b] -> [a] -> [b] zapp (f : fs) (x : xs) = f x : zapp fs xs zapp _ _ = [] transpose' :: [[a]] -> [[a]] transpose' [] = repeat [] transpose' (xs : xss) = repeat' (:) `zapp` xs `zapp` transpose' xss v = [[1,2,3],[4,5,6]] t2 :: [Test] t2 = tt "t2" [ (transpose v) , (transpose' v) ] [[1,4],[2,5],[3,6]] -- http://stackoverflow.com/questions/22734551/request-clarification-of-transposition-example-in-mcbride-paterson-applicative-p -- Note: the transpose defined on page 5 is NOT the standard idiom bracket translation: -- typeclassopedia -- non-deterministic computation point of view -- apply function to inputs in turn transpose'' :: [[a]] -> [[a]] transpose'' [] = pure [] transpose'' (xs : xss) = pure (:) <*> xs <*> transpose'' xss t3 :: [Test] t3 = t "t3" (transpose'' v) [[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]] -- Instead, the paper says "where pure = repeat and (~) = zapp" which tranlates to transpose' above. ------------------------------------------------------------------------------ -- p. 3 Example: hiding environment when evaluating expressions data Exp v = Var v | Val Int | Add (Exp v) (Exp v) deriving (Show) type Env v = Map.Map v Int fetch :: Ord v => v -> Env v -> Int fetch v env = env Map.! v -- explicit environment eval :: Ord v => Exp v -> Env v -> Int eval (Var x) env = fetch x env eval (Val i) env = i eval (Add p q) env = eval p env + eval q env -- hiding environment using S and K combinators eval' :: Ord v => Exp v -> Env v -> Int eval' (Var x) = fetch x eval' (Val i) = k i eval' (Add p q) = k (+) `s` eval' p `s` eval' q k :: a -> Env v -> a k x env = x s :: (Env v -> a -> b) -> (Env v -> a) -> (Env v -> b) s ef es env = (ef env) (es env) t4 = tt "t4" [ eval' (Add (Val 3) (Val 4)) (Map.fromList [("x",4)]) , eval' (Add (Val 3) (Var "x")) (Map.fromList [("x",4)]) ] 7 -- p. 4 -- hiding the environment using Applicative eval'' :: Ord v => Exp v -> Env v -> Int eval'' (Var x) = fetch x eval'' (Val i) = pure i eval'' (Add p q) = pure (+) <*> (eval'' p) <*> (eval'' q) t5 = tt "t5" [ eval'' (Add (Val 3) (Val 4)) (Map.fromList [("x",4)]) , eval'' (Add (Val 3) (Var "x")) (Map.fromList [("x",4)]) ] 7 ------------------------------------------------------------------------------ -- p. 5 traversing data structures -- `dist'` is a generalization of `transpose''` to work with any Applicative (not just lists) dist' :: Applicative f => [f a] -> f [a] dist' [] = pure [] dist' (v : vs) = pure (:) <*> v <*> (dist' vs) -- map operation (that might fail) such that any individual failure causes overall failure -- traverses list twice flakyMap :: (a -> Maybe b) -> [a] -> Maybe [b] flakyMap f ss = dist' (fmap f ss) isEven :: Int -> Maybe Int isEven x = if even x then Just x else Nothing t6 = tt "t6" [ flakyMap isEven [3,4] , dist' (fmap isEven [3,4]) , dist' [Nothing,Just 8] , pure (:) <*> Nothing <*> (dist' [Just 8]) , pure (:) <*> Nothing <*> (pure (:) <*> Just 8 <*> (dist' [])) , pure (:) <*> Nothing <*> (pure (:) <*> Just 8 <*> (pure [])) , Just (:) <*> Nothing <*> (Just (:) <*> Just 8 <*> (Just [])) , (liftM2 (id) (Just (:)) Nothing) <*> (Just (:) <*> Just 8 <*> (Just [])) , Nothing <*> (Just (:) <*> Just 8 <*> (Just [])) -- this is the MAGIC step , (liftM2 (id) Nothing (Just (:) <*> Just 8 <*> (Just []))) ] Nothing t7 = t "t7" (flakyMap isEven [2,4]) (Just [2,4]) -- applicative mapping -- same this as `flakyMap`, but traverse list once -- just like `map` for lists, but applicative version traverse' :: Applicative f => (a -> f b) -> [a] -> f [b] traverse' f [] = pure [] traverse' f (x : xs) = pure (:) <*> (f x) <*> (traverse' f xs) t8 = t "t8" (traverse' isEven [5,8]) Nothing t9 = t "t9" (traverse' isEven [6,8]) (Just [6,8]) -- TODO: I do not understand this section. -- generalized `traverse'` (like `fmap` is generalized map) -- fmap :: Functor f => (a -> b) -> f a -> f b -- where `t` is the generalization (of []) -- http://hackage.haskell.org/package/base-4.6.0.1/docs/src/Data-Traversable.html#Traversable class Functor t => Traversable t where traverse :: Applicative f => (a -> f b) -> t a -> f (t b) traverse f = dist . fmap f dist :: Applicative f => t (f a) -> f (t a) dist = traverse id -- note: can use above to define `fmap` where `f` above is `Id` newtype Id a = An { an :: a } deriving (Eq, Show) instance Functor Id where f `fmap` An x = An (f x) instance Applicative Id where pure = An An f <*> An x = An (f x) fmap' :: Traversable t => (a -> b) -> t a -> t b fmap' f = an . traverse (An . f) instance Traversable Maybe where t10 = t "t10" (fmap (An . (*2)) (Just 3)) (Just (An {an = 6})) -- infinite loop: -- (fmap' (*2) (Just 3)) -- :t (An . (*2)) -- => (An . (*2)) :: Num b => b -> Id b -- :t traverse (An . (*2)) (Just 3) -- => traverse (An . (*2)) (Just 3) :: Num b => Id (Maybe b) -- :t (an . traverse (An . (*2))) (Just 3) -- => (an . traverse (An . (*2))) (Just 3) :: Num b => Maybe b -- :t (an . (dist . fmap (An . (*2)))) (Just 3) -- => (an . (dist . fmap (An . (*2)))) (Just 3) :: Num a => Maybe a -- :t (an . (traverse id . fmap (An . (*2)))) (Just 3) -- => (an . (traverse id . fmap (An . (*2)))) (Just 3) :: Num b => Maybe b -- :t (an . ((dist . fmap id) . fmap (An . (*2)))) (Just 3) -- => (an . ((dist . fmap id) . fmap (An . (*2)))) (Just 3) :: Num a => Maybe a -- :t fmap (An . (*2)) -- => fmap (An . (*2)) :: (Functor f, Num b) => f b -> f (Id b) -- p. 6 traverse a tree {- data Tree a = Leaf | Node (Tree a) a (Tree a) deriving (Eq, Show) instance Functor Tree where fmap _ Leaf = Leaf fmap f (Node l a r) = (Node (fmap f l) (f a) (fmap f r)) instance Applicative Tree where pure x = Node (pure x) x (pure x) Leaf <*> _ = Leaf _ <*> Leaf = Leaf (Node l f r) <*> (Node l' v r') = Node (l <*> l') (f v) (r <*> r') instance Traversable Tree where traverse f Leaf = pure (Leaf) traverse f (Node l x r) = pure Node <*> (traverse f l) <*> (f x) <*> (traverse f r) t11 = t "t11" (traverse (*2) (Node Leaf 3 Leaf)) (Node Leaf 6 Leaf) -} ------------------------------------------------------------------------------ -- p. 8/9 Applicative viz Monad -- Monad bind (>>=) enables the value returned by one computation to influence the choice of another. -- Applicative apply (<*>) keeps the structure of a computation fixed, just sequencing the effects. ------------------------------------------------------------------------------ -- http://en.wikibooks.org/wiki/Haskell/Applicative_Functors -- handle variable number of applicative arguments tw1 = tt "tw1" [ (\a -> a * 3) `fmap` (Just 10) -- fmap by itself can only deal with one context/container -- fmap combined with apply (<*>) can handle multiple contexts/containers , (\a b c -> a + b + c) `fmap` (Just 5) <*> (Just 10) <*> (Just 15) , (\a b c -> a + b + c) <$> (Just 5) <*> (Just 10) <*> (Just 15) , pure (\a b c -> a + b + c) <*> (Just 5) <*> (Just 10) <*> (Just 15) , Just (\a b c -> a + b + c) <*> (Just 5) <*> (Just 10) <*> (Just 15) , liftA3 (\a b c -> a + b + c) (Just 5) (Just 10) (Just 15) ] (Just 30) -- this is how it does it tw2 = tt "tw2" [ (\a b c -> a + b + c) `fmap` (Just 5) <*> (Just 10) <*> (Just 15) , Just ((\a b c -> a + b + c) 5) <*> (Just 10) <*> (Just 15) , Just (((\a b c -> a + b + c) 5) 10) <*> (Just 15) , Just ((((\a b c -> a + b + c) 5) 10) 15) ] (Just 30) ------------------------------------------------------------------------------ -- hide an argument until needed (e.g., at `id` below) hide :: Int -> Int -> Int hide 2 = pure 2 hide 5 = pure (+) <*> hide 2 <*> hide 2 hide _ = id th1 = t "th1" ((hide 2) 100) 2 th2 = t "th2" ((hide 5) 100) 4 th3 = t "th3" ((hide 1) 100) 100 ------------------------------------------------------------------------------ runTests :: IO Counts runTests = runTestTT $ TestList $ t1 ++ t2 ++ t3 ++ t4 ++ t5 ++ t6 ++ t7 ++ t8 ++ t9 ++ t10 ++ tw1 ++ tw2 ++ th1 ++ th2 ++ th3 -- End of file
haroldcarr/learn-haskell-coq-ml-etc
haskell/topic/applicatives/mcbride-paterson-applicative-programming-with-effects/APWE.hs
unlicense
12,969
0
20
4,278
4,114
2,218
1,896
167
2
module City where {- Cidade{ String nome Tupla(Int, Int) ponto Int precoHotel } -} data City = City [Char] (Int, Int) Int deriving (Eq, Show) -- distancia entre duas cidades cityDistance :: City -> City -> Float cityDistance (City _ (x1,y1) _) (City _ (x2,y2) _) = sqrt( fromIntegral((x1-x2)^2+(y1-y2)^2) ) -- get custo hotel getCityCost :: City -> Int getCityCost (City _ _ x) = x -- get nome da cidade getCityName :: City -> [Char] getCityName (City x _ _) = x -- set nome da cidade setNameCity :: [[Char]] -> [Char] setNameCity [] = [] setNameCity xs = head xs -- set coordenada X setCoordinateX :: [Char] -> [Char] setCoordinateX (x:xs) | x/=' ' = x:setCoordinateX xs | x==' ' = [] -- set coordenada Y setCoordinateY :: [Char] -> [Char] setCoordinateY (x:xs) | x/=' ' = setCoordinateY xs | x==' ' = xs -- set coordenada da cidade setCoordinateCity :: [[Char]] -> (Int,Int) setCoordinateCity [] = (0,0) -- [] setCoordinateCity xs = (read(setCoordinateX point)::Int, read(setCoordinateY point)::Int) where point = head (drop 1 xs) -- set custo da hospedagem da cidade setCityCost :: [[Char]] -> Int setCityCost [] = 0 setCityCost (x:xs) = (read(x)::Int) -- cria lista de cidades setCityList :: [[Char]] -> [[Char]]-> [City] setCityList [] _ = [] setCityList _ [] = [] setCityList xs ys = (City name coordinate cost):setCityList (drop 2 xs) (drop 1 ys) where name = setNameCity xs coordinate = setCoordinateCity xs cost = setCityCost ys
rhuancaetano/University-Works
Prog-I/program/city_module.hs
unlicense
1,627
0
13
433
629
340
289
31
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module Network.MoeSocks.Type.Bootstrap.Config where import Control.Lens import Data.Aeson (FromJSON, ToJSON) import Data.Text (Text) import GHC.Generics (Generic) data Config = Config { _remoteHost :: Text , _remotePort :: Int , _localHost :: Text , _localPort :: Int , _password :: Text , _method :: Text , _timeout :: Int , _tcpBufferSize :: Int -- in packets , _throttle :: Bool , _throttleSpeed :: Double , _obfuscationFlushBound :: Int -- should be greater then MTU , _fastOpen :: Bool , _socketOption_TCP_NOTSENT_LOWAT :: Bool , _forbidden_IPs :: [Text] } deriving (Show, Eq, Generic) instance FromJSON Config instance ToJSON Config makeLenses ''Config
nfjinjing/moesocks
src/Network/MoeSocks/Type/Bootstrap/Config.hs
apache-2.0
764
0
9
146
184
114
70
26
0
--reverse QSort module Main where rQSort [] = [] rQSort (x:xs) = rQSort larger ++ [x] ++ rQSort smaller where larger = [a | a <- xs, a > x] smaller = [a | a <- xs, a <= x]
Crossroadsman/ProgrammingInHaskell
01/reverseQSort.hs
apache-2.0
228
0
9
96
99
53
46
5
1
data Suit = Club | Diamond | Heart | Spade deriving (Read, Show, Enum, Eq, Ord) data CardValue = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Read, Show, Enum, Eq, Ord) data Card = Card { value :: CardValue, suit :: Suit } deriving (Read, Show, Eq) instance Ord Card where compare c1 c2 = compare (value c1, suit c1) (value c2, suit c2) instance Enum Card where toEnum n = let (v,s) = n`divMod`4 in Card (toEnum v) (toEnum s) fromEnum c = fromEnum (value c) * 4 + fromEnum (suit c) type Deck = [Card] deck::Deck deck = [Card value suit | value <- [Two .. Ace] , suit <- [Club .. Spade] ]
srufle/haskell-fun
playingCards.hs
apache-2.0
731
4
10
224
332
183
149
18
1
-- | Tree -> Graph conversion. Provisional module. module NLP.FeatureStructure.Conv where import NLP.FeatureStructure.Tree import NLP.FeatureStructure.Core import qualified NLP.FeatureStructure.Graph as G import qualified NLP.FeatureStructure.Join as J -- -- | Run the conversion monad. -- runConT -- :: Monad m -- => ConvT m b -- -> m (Maybe (b, G.Graph f a)) -- runConT convT = flip J.runJoinT G.empty $ do -- -- First we run the conversion -- (x, st) <- S.runStateT convT initConS -- -- The second step is to join all nodes which have to be -- -- merged based on the identifiers specified by the user. -- forM_ (M.elems $ conI st) $ \ks -> do -- forM_ (adja $ Set.toList ks) $ \(i, j) -> do -- J.join i j -- -- T.mapM (J.liftGraph . G.getRepr) t1 -- return x -- -- -- -- | Convert a given feature tree to a feature graph. -- -- -- -- TODO: the reason we cannot export this function as it is is -- -- that the ID value returned could possibly change in the "future". -- -- C.f. the `compile(s)` functions. -- convTree -- :: (Monad m, Ord i, Eq a, Ord f) -- => FN i f a -- -> ConT i f a m ID -- convTree = fromFN -- | A regular, 'forward-traveling' state of the conversion monad. data ConF i f a = ConF { -- | A counter for producing new identifiers. conCounter :: Int -- | A mapping from old to new identifiers. , conMapping :: M.Map i (Set.Set ID) } -- | Initial value of the state. initConS :: ConF i f a initConS = ConF { conC = 1 , conI = M.empty } -- | A 'backward-traveling' state of the conversion monad. data ConB i f a = ConB { -- | A mapping from old to new identifiers. , conMapping :: M.Map i (Set.Set ID) }
kawu/feature-structure
src/NLP/FeatureStructure/Conv.hs
bsd-2-clause
1,764
2
12
460
178
123
55
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2013 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable -- -- Bootstrapped /catenable/ non-empty pairing heaps as described in -- -- <https://www.fpcomplete.com/user/edwardk/revisiting-matrix-multiplication/part-5> ----------------------------------------------------------------------------- module Sparse.Matrix.Internal.Heap ( Heap(..) , fby , mix , singleton , head , tail , fromList , fromAscList , streamHeapWith , streamHeapWith0 ) where import Control.Applicative import Control.Lens import Data.Foldable import Data.Monoid import Data.Vector.Fusion.Stream.Monadic hiding (singleton, fromList, head, tail) import Data.Vector.Fusion.Stream.Size import Sparse.Matrix.Internal.Key import Prelude hiding (head, tail) -- | Bootstrapped catenable non-empty pairing heaps data Heap a = Heap {-# UNPACK #-} !Key a [Heap a] [Heap a] [Heap a] deriving (Show,Read) -- | Append two heaps where we know every key in the first occurs before every key in the second -- -- >>> head $ singleton (Key 1 1) 1 `fby` singleton (Key 2 2) 2 -- (Key 1 1,1) fby :: Heap a -> Heap a -> Heap a fby (Heap i a as ls rs) r = Heap i a as ls (r:rs) -- | Interleave two heaps making a new 'Heap' -- -- >>> head $ singleton (Key 1 1) 1 `mix` singleton (Key 2 2) 2 -- (Key 1 1,1) mix :: Heap a -> Heap a -> Heap a mix x@(Heap i a as al ar) y@(Heap j b bs bl br) | i <= j = Heap i a (y:pops as al ar) [] [] | otherwise = Heap j b (x:pops bs bl br) [] [] -- | -- >>> head $ singleton (Key 1 1) 1 -- (Key 1 1,1) head :: Heap a -> (Key, a) head (Heap i a _ _ _) = (i, a) -- | -- >>> tail $ singleton (Key 1 1) 1 -- Nothing tail :: Heap a -> Maybe (Heap a) tail (Heap _ _ xs fs rs) = pop xs fs rs -- | -- >>> singleton (Key 1 1) 1 -- Heap (Key 1 1) 1 [] [] [] singleton :: Key -> a -> Heap a singleton k v = Heap k v [] [] [] -- | Build a 'Heap' from a jumbled up list of elements. fromList :: [(Key,a)] -> Heap a fromList ((k0,v0):xs) = Prelude.foldr (\(k,v) r -> mix (singleton k v) r) (singleton k0 v0) xs fromList [] = error "empty Heap" -- | Build a 'Heap' from an list of elements that must be in strictly ascending Morton order. fromAscList :: [(Key,a)] -> Heap a fromAscList ((k0,v0):xs) = Prelude.foldr (\(k,v) r -> fby (singleton k v) r) (singleton k0 v0) xs fromAscList [] = error "empty Heap" -- * Internals fbys :: Heap a -> [Heap a] -> [Heap a] -> Heap a fbys (Heap i a as [] []) ls' rs' = Heap i a as ls' rs' fbys (Heap i a as ls []) ls' rs' = Heap i a as ls $ rs' <> reverse ls' fbys (Heap i a as ls rs) ls' rs' = Heap i a as ls $ rs' <> reverse ls' <> rs pops :: [Heap a] -> [Heap a] -> [Heap a] -> [Heap a] pops xs [] [] = xs pops (x:xs) ls rs = [fbys (merge x xs) ls rs] pops [] (l:ls) rs = [fbys l ls rs] pops [] [] rs = case reverse rs of f:fs -> [fbys f fs []] _ -> [] -- caught above by the 'go as [] []' case merge :: Heap a -> [Heap a] -> Heap a merge x (y:ys) = case ys of (z:zs) -> mix x y `mix` merge z zs [] -> mix x y merge x [] = x pop :: [Heap a] -> [Heap a] -> [Heap a] -> Maybe (Heap a) pop (x:xs) ls rs = Just $ fbys (merge x xs) ls rs pop [] (l:ls) rs = Just $ fbys l ls rs pop [] [] rs = case reverse rs of f:fs -> Just (fbys f fs []) [] -> Nothing -- * Instances instance Functor Heap where fmap f (Heap k a xs ls rs) = Heap k (f a) (fmap f <$> xs) (fmap f <$> ls) (fmap f <$> rs) instance FunctorWithIndex Key Heap where imap f (Heap k a xs ls rs) = Heap k (f k a) (imap f <$> xs) (imap f <$> ls) (imap f <$> rs) instance Foldable Heap where foldMap f = go where go (Heap _ a xs ls rs) = case pop xs ls rs of Nothing -> f a Just h -> f a `mappend` go h {-# INLINE foldMap #-} instance FoldableWithIndex Key Heap where ifoldMap f = go where go (Heap i a xs ls rs) = case pop xs ls rs of Nothing -> f i a Just h -> f i a `mappend` go h {-# INLINE ifoldMap #-} instance Traversable Heap where traverse f xs = fromAscList <$> traverse (traverse f) (itoList xs) {-# INLINE traverse #-} instance TraversableWithIndex Key Heap where itraverse f xs = fromAscList <$> traverse (\(k,v) -> (,) k <$> f k v) (itoList xs) {-# INLINE itraverse #-} data HeapState a = Start !(Heap a) | Ready {-# UNPACK #-} !Key a !(Heap a) | Final {-# UNPACK #-} !Key a | Finished -- | Convert a 'Heap' into a 'Stream' folding together values with identical keys using the supplied -- addition operator. streamHeapWith :: Monad m => (a -> a -> a) -> Maybe (Heap a) -> Stream m (Key, a) streamHeapWith f h0 = Stream step (maybe Finished Start h0) Unknown where step (Start (Heap i a xs ls rs)) = return $ Skip $ maybe (Final i a) (Ready i a) $ pop xs ls rs step (Ready i a (Heap j b xs ls rs)) = return $ case compare i j of LT -> Yield (i, a) $ maybe (Final j b) (Ready j b) $ pop xs ls rs EQ | c <- f a b -> Skip $ maybe (Final i c) (Ready i c) $ pop xs ls rs GT -> Yield (j, b) $ maybe (Final i a) (Ready i a) $ pop xs ls rs step (Final i a) = return $ Yield (i,a) Finished step Finished = return Done {-# INLINE [1] step #-} {-# INLINE [0] streamHeapWith #-} -- | Convert a 'Heap' into a 'Stream' folding together values with identical keys using the supplied -- addition operator that is allowed to return a sparse 0, by returning 'Nothing'. streamHeapWith0 :: Monad m => (a -> a -> Maybe a) -> Maybe (Heap a) -> Stream m (Key, a) streamHeapWith0 f h0 = Stream step (maybe Finished Start h0) Unknown where step (Start (Heap i a xs ls rs)) = return $ Skip $ maybe (Final i a) (Ready i a) $ pop xs ls rs step (Ready i a (Heap j b xs ls rs)) = return $ case compare i j of LT -> Yield (i, a) $ maybe (Final j b) (Ready j b) $ pop xs ls rs EQ -> case f a b of Nothing -> Skip $ maybe Finished Start $ pop xs ls rs Just c -> Skip $ maybe (Final i c) (Ready i c) $ pop xs ls rs GT -> Yield (j, b) $ maybe (Final i a) (Ready i a) $ pop xs ls rs step (Final i a) = return $ Yield (i,a) Finished step Finished = return Done {-# INLINE [1] step #-} {-# INLINE [0] streamHeapWith0 #-}
ekmett/sparse
src/Sparse/Matrix/Internal/Heap.hs
bsd-2-clause
6,507
0
18
1,569
2,685
1,378
1,307
121
7
module Emulator.ROM where import Emulator.Types import Control.Lens import Data.ByteString (ByteString) data ROMHeader = ROMHeader { _rhStartLocation :: ByteString -- 0x00: B <game_code_start> , _rhNintendoLogo :: ByteString -- 0x04: nintendo logo , _rhGameTitle :: ByteString -- 0xA0: Game title (uppercase ascii, max 12 bytes) , _rhGameCode :: ByteString -- 0xAC: Game code (uppercase ascii, max 4 bytes) , _rhMakerCode :: ByteString -- 0xB0: Maker code (uppercase ascii, max 2 bytes) , _rhMagicByte :: Byte } -- 0xB2: Must be 0x96 deriving (Show, Eq, Ord) makeLensesWith abbreviatedFields ''ROMHeader
intolerable/GroupProject
src/Emulator/ROM.hs
bsd-2-clause
629
0
8
111
102
63
39
-1
-1
{-| Module : Data.Boltzmann.Internal.Annotations Description : System annotation utilities. Copyright : (c) Maciej Bendkowski, 2017-2021 License : BSD3 Maintainer : maciej.bendkowski@tcs.uj.edu.pl Stability : experimental General utilities meant for handing system annotations guiding the tuning and compilation process. -} module Data.Boltzmann.Internal.Annotations ( withDefault , withString , withDouble , withInt , withBool ) where import Data.Maybe ( fromMaybe ) import Data.Char ( toLower ) import Data.Map ( Map ) import qualified Data.Map as M import Text.Read ( readMaybe ) -- | Read a given key value of a map with a default fallback. withDefault :: Read a => Map String String -> String -> a -> a withDefault f x d = case x `M.lookup` f of Nothing -> d Just x' -> fromMaybe d (readMaybe x') -- | Read a given key value of a map with a default string fallback. withString :: Map String String -> String -> String -> String withString f x d = fromMaybe d (x `M.lookup` f) -- | `withDefault` specialised to doubles. withDouble :: Map String String -> String -> Double -> Double withDouble = withDefault -- | `withDefault` specialised to ints. withInt :: Map String String -> String -> Int -> Int withInt = withDefault -- | `withDefault` specialised to bools. withBool :: Map String String -> String -> Bool -> Bool withBool f x d = case x `M.lookup` f of Nothing -> d Just x' -> case map toLower x' of "yes" -> True -- support 'yes' "y" -> True -- .. and alternative 'y' "1" -> True -- .. and alternative '1' "true" -> True "no" -> False "n" -> False "false" -> False "0" -> False _ -> d -- error, fall back to default
maciej-bendkowski/boltzmann-brain
Data/Boltzmann/Internal/Annotations.hs
bsd-3-clause
1,909
0
10
567
390
212
178
34
10
-- | Statically generating blog software. module Blogination where
chrisdone/blogination
src/Blogination.hs
bsd-3-clause
68
0
2
10
5
4
1
1
0
{-# LANGUAGE CPP, TemplateHaskell, NoImplicitPrelude #-} -- turtles: sheep -- patches: grass -- sheep moves forward 1, eats grass -- grass eating increases sheep's energy -- sheep's moving decreases sheep's energy -- grass grows back -- no sheep dies import Language.Logo #ifndef NR_SHEEP #define NR_SHEEP 100 #endif patches_own ["countdown"] breeds ["sheep", "a_sheep"] breeds_own "sheep" ["senergy"] -- Model Parameters grassp = True grass_regrowth_time = 30 initial_number_sheep = NR_SHEEP sheep_gain_from_food = 4 args = ["--max-pxcor=100" ,"--max-pycor=100" ,"--min-pxcor=-100" ,"--min-pycor=-100" ,"--horizontal-wrap=True" ,"--vertical-wrap=True" ] run ["setup", "go"] setup = do ask (atomic $ set_pcolor green) =<< patches when grassp $ ask (do r <- random grass_regrowth_time c <- one_of [green, brown] atomic $ do set_countdown r set_pcolor c ) =<< patches s <- create_sheep initial_number_sheep ask (do s <- random (2 * sheep_gain_from_food) x <- random_xcor y <- random_ycor atomic $ do set_color white set_size 1.5 set_label_color (blue -2) set_senergy s setxy x y ) s reset_ticks go = forever $ do t <- ticks when (t > 1000) (sheep >>= count >>= print >> stop) ask (do move when grassp $ do atomic $ with_senergy (\ e -> e - 1) eat_grass ) =<< turtles -- turtle < unsafe_sheep < sheep when grassp (ask grow_grass =<< patches) tick move = do r <- random 50 l <- random 50 atomic $ do rt r lt l fd 1 eat_grass = atomic $ do c <- pcolor when (c == green) $ do set_pcolor brown with_senergy (+ sheep_gain_from_food) grow_grass = do c <- pcolor when (c == brown) $ do d <- countdown if (d <= 0) then atomic $ set_pcolor green >> set_countdown grass_regrowth_time else atomic $ set_countdown $ d -1
bezirg/hlogo
bench/hlogo/Sheep.hs
bsd-3-clause
2,230
0
20
801
594
283
311
68
2
module Main where import Graphics.Rendering.Cairo as C import Data.Word (Word8) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Binary.Get as G import Text.Printf (printf) import Debug.Trace (trace) debug x = trace (show x) x -- These are the standard Youtube values videoWidth = 320 :: Int videoHeight = 240 :: Int framesPerSecond = 30 :: Double pushTransMatrix :: C.Render a -> C.Render a pushTransMatrix f = do m <- C.getMatrix r <- f C.setMatrix m return r centerText :: String -> C.Render () centerText tx = do pushTransMatrix $ do ex <- C.textExtents tx translate (0-(textExtentsWidth ex / 2)) 0 C.showText tx fill setup :: C.Render () setup = do translate 160 120 scale 240 240 background :: Double -> C.Render () background n = do setSourceRGBA n n n 1 rectangle (-0.67) (-0.67) 1.34 1.34 fill endText = do setSourceRGBA 0 0 0 1 selectFontFace "serif" FontSlantNormal FontWeightNormal setFontSize 0.1 pushTransMatrix $ do ex <- C.textExtents "Obfuscated" translate (0-(textExtentsWidth ex / 2)) (-0.25) C.showText "Obfuscated" fill setFontSize 0.15 pushTransMatrix $ do ex <- C.textExtents "TCP" translate (0-(textExtentsWidth ex / 2)) (-0.1) C.showText "TCP" fill setFontSize 0.075 pushTransMatrix $ do ex <- C.textExtents "code.google.com/p/obstcp" translate (0-(textExtentsWidth ex / 2)) (0) C.showText "code.google.com/p/obstcp" fill pushTransMatrix $ do ex <- C.textExtents "Music by Etherfysh (CC-by-nc-sa)" translate (0-(textExtentsWidth ex / 2)) (0.2) C.showText "Music by Etherfysh (CC-by-nc-sa)" fill blackBackground = background 0 centerWord :: String -> C.Render () centerWord tx = do blackBackground selectFontFace "monospace" FontSlantNormal FontWeightNormal setFontSize 0.1 setSourceRGBA 0.7 0.7 0.7 1 centerText tx fill textAt :: String -> Double -> Double -> C.Render () textAt tx x y = do pushTransMatrix $ do selectFontFace "monospace" FontSlantNormal FontWeightNormal setFontSize 0.1 setSourceRGBA 0.7 0.7 0.7 1 translate x y ex <- C.textExtents tx translate (0-(textExtentsWidth ex / 2)) 0 showText tx fill textMove :: String -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> C.Render () textMove tx x1 y1 x2 y2 delay sustain time | time <= delay = textAt tx x1 y2 | time >= (delay + sustain) = textAt tx x2 y2 | otherwise = do let fraction = (time - delay) / sustain x = x1 + ((x2 - x1) * fraction) y = y1 + ((y2 - y1) * fraction) textAt tx x y backgroundFade :: Double -> Double -> Double -> Double -> C.Render () backgroundFade start end sustain time | time >= sustain = background end | otherwise = background (start + delta * fraction) where delta = end - start fraction = time / sustain data TypeBox = Roman String | Italic String | Superscript String deriving (Show) typeset :: [TypeBox] -> C.Render () typeset boxes = do let setupRoman = do selectFontFace "monospace" FontSlantNormal FontWeightNormal setFontSize 0.1 setupItalic = do selectFontFace "monospace" FontSlantItalic FontWeightNormal setFontSize 0.1 setupSuperscript = do selectFontFace "monospace" FontSlantItalic FontWeightNormal setFontSize 0.05 let boxWidth (Roman s) = setupRoman >> C.textExtents s >>= return . textExtentsXadvance boxWidth (Italic s) = setupItalic >> C.textExtents s >>= return . textExtentsXadvance boxWidth (Superscript s) = setupSuperscript >> C.textExtents s >>= return . textExtentsXadvance let boxDraw :: TypeBox -> C.Render () boxDraw (Roman s) = setupRoman >> C.showText s >> C.fill boxDraw (Italic s) = setupItalic >> C.showText s >> C.fill boxDraw (Superscript s) = do pushTransMatrix $ do setupSuperscript translate 0 (-0.05) C.showText s C.fill blackBackground setSourceRGBA 0.7 0.7 0.7 1 widths <- mapM boxWidth boxes pushTransMatrix $ do translate (0-(sum widths / 2)) 0 mapM_ (\(box, width) -> boxDraw box >> translate width 0) $ zip boxes widths data SceneElement = SStatic (C.Render ()) | SDyn (Double -> C.Render ()) type Scene = [(Double, SceneElement)] dhSceneStart = 72.7 dhScene = [ (72.7 - dhSceneStart, SStatic blackBackground) , (72.7 - dhSceneStart, SStatic $ textAt "Alice" (-0.5) (-0.35)) , (74.2 - dhSceneStart, SStatic $ textAt "Bob" 0.5 (-0.35)) , (77 - dhSceneStart, SStatic $ textAt "a" (-0.45) (-0.1)) , (80 - dhSceneStart, SStatic $ textAt "b" (0.45) (-0.1)) , (82.7 - dhSceneStart, SDyn $ textMove "9a" (-0.45) 0 0.45 0 0.7 1.5) , (82.7 - dhSceneStart, SDyn $ textMove "9b" 0.45 0 (-0.45) 0 0.7 1.5) , (87.5 - dhSceneStart, SStatic $ textAt "9ab" (-0.45) 0.1) , (87.5 - dhSceneStart, SStatic $ textAt "9ab" 0.45 0.1) , (91.2 - dhSceneStart, SStatic $ textAt "81ab" 0 0) ] tcpSceneStart = 243.3 tcpScene = [ (243.3 - tcpSceneStart, SStatic blackBackground) , (243.3 - tcpSceneStart, SStatic $ textAt "Client" (-0.48) (-0.35)) , (244.5 - tcpSceneStart, SStatic $ textAt "Server" 0.48 (-0.35)) , (246.6 - tcpSceneStart, SDyn $ textMove "SYN" (-0.45) (-0.1) (0.45) (-0.1) 0 1) , (250.3 - tcpSceneStart, SDyn $ textMove "SYNACK" (0.45) 0 (-0.45) 0 0 1) , (252.2 - tcpSceneStart, SDyn $ textMove "ACK" (-0.45) (0.1) (0.45) (0.1) 0 1) ] endScene = [ (0, SDyn $ backgroundFade 0 1 4) , (0, SStatic $ endText ) ] startFade = [ (0, SDyn $ backgroundFade 1 0 4) ] sceneDraw :: Scene -> Double -> C.Render () sceneDraw scene time = do let activeElements = [x | x@(start, elem) <- scene, time >= start] r (start, SStatic f) = f r (start, SDyn f) = f (time - start) setup mapM_ r activeElements type Video = [(Double, Scene)] single :: C.Render () -> Scene single f = [(0, SStatic f)] video :: Video video = [ (0, startFade) , (5.3, single $ centerWord "NebuAd") , (6.3, single $ centerWord "Phorm") , (7.3, single $ centerWord "Warrantless") , (7.8, single $ centerWord "Wiretapping") , (10, single $ blackBackground) , (18.9, single $ centerWord "Salsa20/8") , (20.25, single $ centerWord "Poly1305") , (21.7, single $ centerWord "Curve25519") , (24, single $ blackBackground) , (33, single $ centerWord "<section>") , (34, single $ blackBackground) , (35.8, single $ centerWord "SSL/TLS") , (37.8, single $ blackBackground) , (44.25, single $ centerWord "www.google.com") , (45, single $ blackBackground) , (52.9, single $ centerWord "1.") , (54, single $ centerWord "Aggregate security") , (57, single $ blackBackground) , (66.9, single $ centerWord "(i.e. public WiFi)") , (68.9, single $ blackBackground) , (72.7, sceneTimeMangle dhScene) , (104.9, single $ blackBackground) , (117.45, single $ typeset [Italic "x", Roman " = ", Italic "g", Superscript "y", Roman " (mod ", Italic "p", Roman ")"]) , (117.45, single $ typeset [Italic "x", Roman " = ", Italic "g", Superscript "y", Roman " (mod ", Italic "p", Roman ")"]) , (121.75, single $ typeset [Italic "y", Superscript "2", Roman " = ", Italic "x", Superscript "3", Roman " + 486662", Italic "x", Superscript "2", Roman " + ", Italic "x"]) , (124.5, single $ blackBackground) , (128.6, single $ centerWord "<section>") , (129.6, single $ blackBackground) , (145.45, single $ centerWord "2.") , (146.7, single $ centerWord "0 extra RTT") , (148.5, single $ blackBackground) , (149.0, single $ centerWord "<section>") , (150.0, single $ blackBackground) , (169.8, single $ centerWord "3.") , (170.9, single $ centerWord "Transparency") , (175.5, single $ blackBackground) , (183.3, sceneTimeMangle tcpScene) , (197.1, single $ blackBackground) , (202.2, single $ centerWord "80") , (204.2, single $ blackBackground) , (225.4, single $ centerWord "<ol>") , (226.4, single $ blackBackground) , (239.9, single $ centerWord "X-ObsTCP") , (240.9, single $ blackBackground) , (241.3, single $ centerWord "<ol>") , (241.3, single $ blackBackground) , (247.3, single $ centerWord "www.google.com") , (248, single $ centerWord "209.85.173.104") , (250, single $ blackBackground) , (262.7, single $ centerWord "Apache") , (263.7, single $ centerWord "Firefox") , (264.7, single $ centerWord "lighttpd") , (266.7, single $ blackBackground) , (270, sceneTimeMangle endScene) ] timeMangle :: Video -> Video timeMangle = map (\(start, x) -> (start / 1.0, x)) sceneTimeMangle :: Scene -> Scene sceneTimeMangle = map (\(start, x) -> (start / 1.0, x)) waveFrames :: G.Get [B.ByteString] waveFrames = do G.getByteString 44 -- chomp header let sample :: G.Get Word8 sample = do left <- G.getWord16le right <- G.getWord16le let left' = if left >= 32768 then 32768 - (65536 - left) else left + 32768 return $ fromIntegral (left' `div` 256) frame :: Int -> B.ByteString -> G.Get B.ByteString frame n bs | n == 1470 = return bs | otherwise = do s <- sample frame (n + 1) (bs `B.snoc` s) loop = do emptyp <- G.isEmpty if emptyp then return [B.pack $ replicate 1470 0] else do f <- frame 0 B.empty rest <- loop return (f : rest) loop frameToSamples :: B.ByteString -> B.ByteString frameToSamples bs | B.null bs = B.empty | otherwise = average `B.append` frameToSamples rest where (a, rest) = B.splitAt 5 bs values :: [Int] values = map fromIntegral $ B.unpack a average = B.singleton $ fromIntegral $ sum values `div` 5 plotSamples :: B.ByteString -> C.Render () plotSamples bs = do C.setLineWidth 0.004 C.setSourceRGBA 0 0 1 0.5 C.moveTo (-0.6666) 0 let a = 1.333333/294 c = 0.6666666 / 256 points = map (\(x,y) -> ((-0.66666) + a * fromIntegral x, (-0.333333) + fromIntegral y * c)) $ zip [0..294] $ B.unpack bs mapM_ (\(x,y) -> C.lineTo x y) points C.stroke vidrn :: BL.ByteString -> Video -> Double -> IO () vidrn soundInput vid duration = doFrames sound 0 (0 :: Int) where sound = G.runGet waveFrames soundInput frameStep = 1 / framesPerSecond doFrames soundIn currentTime frameno | currentTime > duration = return () | otherwise = do let (start, scene) = head $ reverse $ [x | x@(start, scene) <- vid, currentTime >= start] expired = currentTime - start samples = frameToSamples $ head soundIn printf " : %f %d %f\n" currentTime frameno expired surface <- C.createImageSurface C.FormatARGB32 videoWidth videoHeight renderWith surface (sceneDraw scene expired >> plotSamples samples) surfaceWriteToPNG surface $ printf "out%05d.png" frameno surfaceFinish surface doFrames (tail soundIn) (currentTime + frameStep) (frameno + 1) main = do soundInput <- BL.readFile "/home/agl/Desktop/script.wav" vidrn soundInput (timeMangle video) 277
agl/obstcp
video/Video.hs
bsd-3-clause
11,730
0
19
3,166
4,344
2,240
2,104
285
5
-- Copyright: (c) 2014 Andreas Bock, Johan Astborg -- License: BSD-3 -- Maintainers: Andreas Bock <bock@andreasbock.dk> -- Johan Astborg <joastbg@gmail.com> -- Stability: experimental -- Portability: portable module Presentation where import Utils.Calendar import Utils.Currency import Utils.DayCount import Utils.Graphics.Visualize import Instruments.Instrument import Instruments.Utils.InterestRate import Instruments.Utils.TermStructure import Instruments.FixedIncome.Bonds.Bonds -- Define values to be used when creating bonds settle = read "2014-02-18" :: Date -- Settlement date maturity = read "2016-02-18" :: Date -- Maturity of the bonds face = Cash (10^3) DKK -- Principal dayCount = ACTACT -- Daycount convention rollConv = ModifiedFollowing -- How to roll days myRate = 0.1 -- Interest rate of 10% stms = 2 -- Semiannual coupons -- Examples of fixed income instruments zero = Zero settle maturity face myRate dayCount rollConv bullet = Bullet settle maturity face myRate stms dayCount rollConv consol = Consol settle face myRate stms dayCount rollConv serial = Serial settle maturity face myRate stms dayCount rollConv annuity = Annuity settle maturity face myRate stms dayCount rollConv -- We use an analytical term structure in this example: ts = AnalyticalTermStructure $ \x -> (5 + (1/4)*sqrt x)/100
HIPERFIT/HQL
src/Presentation.hs
bsd-3-clause
1,462
0
12
329
259
150
109
22
1
module Generator where import qualified LLVM.General.AST as A import qualified LLVM.General.AST.Type as T import qualified LLVM.General.AST.Constant as C import qualified LLVM.General.AST.Instruction as I import qualified LLVM.General.AST.IntegerPredicate as IP import qualified LLVM.General.AST.FloatingPointPredicate as FPP import qualified LLVM.General.AST.Global as G import Control.Applicative import Control.Monad.State import Data.Maybe import Scope import AST import Analyzer import Type import Codegen import Native type EStatement = Either (A.Name -> [A.BasicBlock]) [A.BasicBlock] castPrimatyTypeOperand :: (PrimaryType, A.Operand) -> PrimaryType -> Codegen A.Operand castPrimatyTypeOperand (ot, op) t = if ot == t then return op else addInstr $ f ot t op (mapPrimaryType t) [] where f _ TShort = I.SExt f _ TInt = I.SExt f _ TLong = I.SExt f _ TFloat = I.SIToFP f TFloat TDouble = I.FPExt f _ TDouble = I.SIToFP f _ _ = error "cast primary type operand" castOperand :: (Type, A.Operand) -> Type -> Codegen A.Operand castOperand (NullType, _) (ObjectType t) = return . nullConstant $ t castOperand (PrimaryType pt, op) (PrimaryType t) = castPrimatyTypeOperand (pt, op) t castOperand (ObjectType ot, op) (ObjectType t) = if ot == t then return op else error "cast operand" castOperand _ _ = error "cast operand" castList :: [(Type, A.Operand)] -> [Type] -> Codegen [A.Operand] castList ops ts = forM (zip ops ts) (uncurry castOperand) inferOperand :: (Type, A.Operand) -> (Type, A.Operand) -> Codegen (Type, (A.Operand, A.Operand)) inferOperand (t1, o1) (t2, o2) = do let t = fromJust $ infer t1 t2 r1 <- castOperand (t1, o1) t r2 <- castOperand (t2, o2) t return (t, (r1, r2)) genTypedBinaryOpM :: Expression -> Expression -> (Type -> A.Operand -> A.Operand -> Codegen I.Instruction) -> Codegen (Maybe (Type, A.Operand)) genTypedBinaryOpM expr1 expr2 f = do e1 <- fromJust <$> genExpression expr1 e2 <- fromJust <$> genExpression expr2 (t, (o1, o2)) <- inferOperand e1 e2 i <- f t o1 o2 r <- addInstr i return $ Just (t, r) genTypedBinaryOp :: Expression -> Expression -> (Type -> A.Operand -> A.Operand -> I.Instruction) -> Codegen (Maybe (Type, A.Operand)) genTypedBinaryOp expr1 expr2 f = genTypedBinaryOpM expr1 expr2 $ \t o1 o2 -> return $ f t o1 o2 genBinaryOp :: Expression -> Expression -> (A.Operand -> A.Operand -> I.Instruction) -> Codegen (Maybe (Type, A.Operand)) genBinaryOp expr1 expr2 f = genTypedBinaryOp expr1 expr2 $ const f genCmpOp :: Expression -> Expression -> IP.IntegerPredicate -> FPP.FloatingPointPredicate -> Codegen (Maybe (Type, A.Operand)) genCmpOp e1 e2 ip fpp = toBool <$> genTypedBinaryOpM e1 e2 f where f (PrimaryType TFloat) o1 o2 = return $ I.FCmp fpp o1 o2 [] f (PrimaryType TDouble) o1 o2 = return $ I.FCmp fpp o1 o2 [] f (PrimaryType _) o1 o2 = return $ I.ICmp ip o1 o2 [] f _ o1 o2 = do o1i <- addInstr $ I.PtrToInt o1 (T.IntegerType structPtrSize) [] o2i <- addInstr $ I.PtrToInt o2 (T.IntegerType structPtrSize) [] return $ I.ICmp ip o1i o2i [] toBool m = (\(_, o) -> (PrimaryType TBoolean, o)) <$> m genArithmOp :: Expression -> Expression -> (A.Operand -> A.Operand -> I.InstructionMetadata -> I.Instruction) -> (A.Operand -> A.Operand -> I.InstructionMetadata -> I.Instruction) -> Codegen (Maybe (Type, A.Operand)) genArithmOp expr1 expr2 fi ff = genTypedBinaryOp expr1 expr2 f where f (PrimaryType TFloat) o1 o2 = ff o1 o2 [] f (PrimaryType TDouble) o1 o2 = ff o1 o2 [] f (PrimaryType TBoolean) _ _ = error "genExpression" f (PrimaryType _) o1 o2 = fi o1 o2 [] f _ _ _ = error "genExpression" genPrePostOp :: QualifiedName -> (Bool -> Bool -> A.Operand -> A.Operand -> I.InstructionMetadata -> I.Instruction) -> Codegen (Type, A.Operand, A.Operand) genPrePostOp qn f = do (t, qPtr) <- fromJust <$> genQualifiedName qn qVal <- load qPtr newVal <- addInstr $ f False False qVal (oneOp t) [] store qPtr newVal return (t, qVal, newVal) genPreOp :: QualifiedName -> (Bool -> Bool -> A.Operand -> A.Operand -> I.InstructionMetadata -> I.Instruction) -> Codegen (Maybe (Type, A.Operand)) genPreOp qn f = do (t, _, val) <- genPrePostOp qn f return $ Just (t, val) genPostOp :: QualifiedName -> (Bool -> Bool -> A.Operand -> A.Operand -> I.InstructionMetadata -> I.Instruction) -> Codegen (Maybe (Type, A.Operand)) genPostOp qn f = do (t, val, _) <- genPrePostOp qn f return $ Just (t, val) genExpression :: Expression -> Codegen (Maybe (Type, A.Operand)) genExpression (Expr (Assign qn expr) _) = do (qType, qPtr) <- fromJust <$> genQualifiedName qn eRes <- fromJust <$> genExpression expr val <- castOperand eRes qType store qPtr val return $ Just (qType, val) genExpression (Expr (Or e1 e2) _) = genBinaryOp e1 e2 $ \o1 o2 -> I.Or o1 o2 [] genExpression (Expr (And e1 e2) _) = genBinaryOp e1 e2 $ \o1 o2 -> I.And o1 o2 [] genExpression (Expr (Equal e1 e2) _) = genCmpOp e1 e2 IP.EQ FPP.OEQ genExpression (Expr (Ne e1 e2) _) = genCmpOp e1 e2 IP.NE FPP.ONE genExpression (Expr (Lt e1 e2) _) = genCmpOp e1 e2 IP.SLT FPP.OLT genExpression (Expr (Gt e1 e2) _) = genCmpOp e1 e2 IP.SGT FPP.OGT genExpression (Expr (Le e1 e2) _) = genCmpOp e1 e2 IP.SLE FPP.OLE genExpression (Expr (Ge e1 e2) _) = genCmpOp e1 e2 IP.SGE FPP.OGE genExpression (Expr (Plus e1 e2) _) = genArithmOp e1 e2 (I.Add False False) I.FAdd genExpression (Expr (Minus e1 e2) _) = genArithmOp e1 e2 (I.Sub False False) I.FSub genExpression (Expr (Mul e1 e2) _) = genArithmOp e1 e2 (I.Mul False False) I.FMul genExpression (Expr (Div e1 e2) _) = genArithmOp e1 e2 (I.SDiv False) I.FDiv genExpression (Expr (Mod e1 e2) _) = genArithmOp e1 e2 I.SRem I.FRem genExpression (Expr (Pos e1) _) = genExpression e1 genExpression (Expr (Neg e1) l) = genExpression $ Expr (Minus (Expr (Literal $ LInt 0) l) e1) l genExpression (Expr (Not expr) _) = do (t, eRes) <- fromJust <$> genExpression expr notE <- addInstr $ I.Sub False False (literalToOp $ LBoolean True) eRes [] return $ Just (t, notE) genExpression (Expr (PreInc qn) _) = genPreOp qn I.Add genExpression (Expr (PreDec qn) _) = genPreOp qn I.Sub genExpression (Expr (PostInc qn) _) = genPostOp qn I.Add genExpression (Expr (PostDec qn) _) = genPostOp qn I.Sub genExpression (Expr (QN qn) _) = do qRes <- genQualifiedName qn case qRes of Nothing -> return Nothing Just (qType, qPtr) -> do qVal <- load qPtr return $ Just (qType, qVal) genExpression (Expr (Literal l) _) = return $ Just (PrimaryType $ literalType l, literalToOp l) genExpression (Expr Null _) = return $ Just (NullType, A.ConstantOperand $ C.Null T.VoidType) callMethod :: ObjectType -> Method -> A.Operand -> [(Type, A.Operand)] -> Codegen I.Instruction callMethod obj mth this params = do paramsOp <- castList params (map paramType $ methodParams mth) return $ call (genMethodName obj mth) $ this : paramsOp genQualifiedName :: QualifiedName -> Codegen (Maybe (Type, A.Operand)) genQualifiedName (QName (FieldAccess qn field) _) = do (t', op) <- fromJust <$> genQualifiedName qn let t = objType t' (ft, i) <- fromRight "field access" <$> findField t field op' <- load op retOp <- addInstr $ I.GetElementPtr False op' [structFieldAddr 0, structFieldAddr i] [] return $ Just (ft, retOp) genQualifiedName (QName (MethodCall qn mthName params) _) = do (t', op) <- fromJust <$> genQualifiedName qn op' <- load op let t = objType t' paramsOp <- fmap (map fromJust) . mapM genExpression $ params mth <- fromRight "method call" <$> findMethod t mthName (fst $ unzip paramsOp) (\m -> methodType m /= Constructor) instr <- callMethod t mth op' paramsOp case methodType mth of Void -> do addVoidInstr instr return Nothing Constructor -> error "genQualifiedName" ReturnType rt -> do retOp <- addInstr instr ptr <- addInstr $ alloca (mapType rt) store ptr retOp return $ Just (rt, ptr) genQualifiedName (QName (Var var) l) = do mv <- lookupLocalVar var case mv of Just v -> return $ Just v Nothing -> genQualifiedName $ QName (FieldAccess (QName This l) var) l genQualifiedName (QName (New ot params) _) = do paramsOp <- fmap (map fromJust) . mapM genExpression $ params mth <- fromRight "new" <$> findMethod ot ot (fst $ unzip paramsOp) (\m -> methodType m == Constructor) ptr <- new ot instr <- callMethod ot mth ptr paramsOp retOp <- addInstr instr ptr' <- addInstr . alloca . mapType $ ObjectType ot store ptr' retOp return $ Just (ObjectType ot, ptr') genQualifiedName (QName This l) = genQualifiedName $ QName (Var "this") l goToBlock :: A.Name -> Codegen A.BasicBlock goToBlock name = do exitLabel <- nextLabel "GoToBlock" return $ A.BasicBlock exitLabel [] $ I.Do $ I.Br name [] genIfConsAltOk :: A.Name -> A.Operand -> [A.Named I.Instruction] -> [A.BasicBlock] -> [A.BasicBlock] -> [A.BasicBlock] genIfConsAltOk ifLabel flag calcFlag consBlocks altBlocks = A.BasicBlock ifLabel calcFlag (I.Do $ I.CondBr flag consBlockName altBlockName []) : (consBlocks ++ altBlocks) where consBlockName = getBBName . head $ consBlocks altBlockName = getBBName . head $ altBlocks genIfCons :: A.Name -> A.Operand -> [A.Named I.Instruction] -> (A.Name -> [A.BasicBlock]) -> A.Name -> [A.BasicBlock] genIfCons ifLabel flag calcFlag getConsBlocks finBlockName = A.BasicBlock ifLabel calcFlag (I.Do $ I.CondBr flag consBlockName finBlockName []) : consBlocks where consBlocks = getConsBlocks finBlockName consBlockName = getBBName . head $ consBlocks genIfConsAlt :: A.Name -> A.Operand -> [A.Named I.Instruction] -> (A.Name -> [A.BasicBlock]) -> (A.Name -> [A.BasicBlock]) -> A.Name -> [A.BasicBlock] genIfConsAlt ifLabel flag calcFlag getConsBlocks getAltBlocks finBlockName = genIfConsAltOk ifLabel flag calcFlag consBlocks altBlocks where consBlocks = getConsBlocks finBlockName altBlocks = getAltBlocks finBlockName getExpressionRes :: Expression -> Codegen (A.Operand, [A.Named I.Instruction]) getExpressionRes e = do op <- (snd . fromJust) <$> genExpression e calc <- popInstructions return (op, calc) genIf :: If -> Codegen EStatement genIf (If cond cons alt) = do ifLabel <- nextLabel "If" (flag, calcFlag) <- getExpressionRes cond consBlocks' <- genStatement cons let genIfCons' = genIfCons ifLabel flag calcFlag genIfConsAlt' = genIfConsAlt ifLabel flag calcFlag case (consBlocks', alt) of (Left getCons, Nothing) -> return . Left $ genIfCons' getCons (Left getCons, Just alt') -> do altBlocks' <- genStatement alt' case altBlocks' of Left getAlt -> return . Left $ genIfConsAlt' getCons getAlt Right altBlocks -> return . Left $ genIfConsAlt' getCons (const altBlocks) (Right consBlocks, Nothing) -> return . Left $ genIfCons' $ const consBlocks (Right consBlocks, Just alt') -> do altBlocks' <- genStatement alt' case altBlocks' of Left getAlt -> return . Left $ genIfConsAlt' (const consBlocks) getAlt Right altBlocks -> return . Right $ genIfConsAltOk ifLabel flag calcFlag consBlocks altBlocks genWhile :: While -> Codegen (A.Name -> [A.BasicBlock]) genWhile (While cond st) = do whileLabel <- nextLabel "While" lastBlock <- goToBlock whileLabel endWhileLabel <- nextLabel "EndWhile" addLoop (getBBName lastBlock, endWhileLabel) (flag, calcFlag) <- getExpressionRes cond stBlocks' <- genStatement st let stBlocks = case stBlocks' of Left f -> f $ getBBName lastBlock Right b -> b stBlockName = getBBName . head $ stBlocks removeLoop return $ \finBlockName -> let endWhile = emptyBlock endWhileLabel $ I.Br finBlockName [] in [A.BasicBlock whileLabel calcFlag (I.Do $ I.CondBr flag stBlockName endWhileLabel [])] ++ stBlocks ++ [lastBlock, endWhile] genExpressionList :: [Expression] -> Codegen () genExpressionList = mapM_ genExpression genVariable :: Variable -> Codegen () genVariable (Variable t n e) = do ptr <- addNamedInstr (A.Name n) . alloca . mapType $ t void $ newLocalVar n (t, ptr) case e of Just expr -> do eRes <- fromJust <$> genExpression expr eOp <- castOperand eRes t store ptr eOp Nothing -> return () genForInit :: ForInit -> Codegen () genForInit (ForInitEL l) = genExpressionList l genForInit (ForInitVD v) = genVariable v genFor :: For -> Codegen (A.Name -> [A.BasicBlock]) genFor (For fInit cond inc st) = do addScope initLabel <- nextLabel "ForInit" endForLabel <- nextLabel "EndFor" forLabel <- nextLabel "For" incLabel <- nextLabel "ForInc" addLoop (incLabel, endForLabel) genForInit fInit calcInit <- popInstructions (flag, calcFlag) <- getExpressionRes cond stBlocks' <- genStatement st genExpressionList inc calcInc <- popInstructions let initBlock = brBlock initLabel forLabel calcInit incBlock = brBlock incLabel forLabel calcInc stBlocks = case stBlocks' of Left f -> f incLabel Right b -> b stBlockName = getBBName . head $ stBlocks removeLoop removeScope return $ \finBlockName -> let endFor = emptyBlock endForLabel $ I.Br finBlockName [] in [initBlock] ++ [A.BasicBlock forLabel calcFlag (I.Do $ I.CondBr flag stBlockName endForLabel [])] ++ stBlocks ++ [incBlock, endFor] genStatement :: Statement -> Codegen EStatement genStatement (SubBlock b) = genBlock b genStatement (IfStatement st) = genIf st genStatement (WhileStatement st) = Left <$> genWhile st genStatement (ForStatement st) = Left <$> genFor st genStatement (Return mExpr _) = do retLabel <- nextLabel "Ret" case mExpr of Nothing -> return . Right . toList . emptyBlock retLabel $ I.Ret Nothing [] Just expr -> do op <- (snd .fromJust ) <$> genExpression expr instr <- popInstructions return . Right . toList $ A.BasicBlock retLabel instr $ I.Do $ I.Ret (Just op) [] genStatement (Break _) = do l <- lastLoopEnd breakLabel <- nextLabel "Break" return . Right . toList $ emptyBlock breakLabel $ I.Br l [] genStatement (Continue _) = do l <- lastLoopNext continueLabel <- nextLabel "Continue" return . Right . toList $ emptyBlock continueLabel $ I.Br l [] genStatement (ExpressionStatement expr) = do void $ genExpression expr instr <- popInstructions exprLabel <- nextLabel "Expression" return . Left $ genBrBlock exprLabel instr genBlockStatement :: BlockStatement -> Codegen EStatement genBlockStatement (BlockVD v) = do genVariable v instr <- popInstructions vdLabel <- nextLabel "VarDeclaration" return . Left $ genBrBlock vdLabel instr genBlockStatement (Statement st) = genStatement st joinEStatements :: [EStatement] -> EStatement joinEStatements [] = Left $ const [] joinEStatements l = case last l of (Right b) -> Right $ foldESt b $ init l (Left f) -> Left $ \finBlockName -> foldESt (f finBlockName) $ init l where joinESt est bl = case est of Left f -> (f . getBBName . head $ bl) ++ bl Right bl' -> bl' ++ bl foldESt = foldr joinESt genBlock :: Block -> Codegen EStatement genBlock bs = do addScope res <- joinEStatements <$> forM bs genBlockStatement removeScope return res genMethod :: Method -> Codegen A.Definition genMethod mth@(Method mt _ mp b) = do modify $ \s -> s { lastInd = -1, lastLabel = 0, csMethod = Just mth } addScope curClass <- getClassM let params = Parameter (ObjectType . className $ curClass) "this" : mp forM_ params genParam instr <- popInstructions mthInitLabel <- nextLabel "MethodInit" fieldsInit <- if mt == Constructor then genFieldsInit else return . Right $ [] let b' = b ++ [Statement $ Return (Just $ Expr (QN $ QName This 0) 0) 0 | mt == Constructor] blockESt <- genBlock b' mthRet <- nextLabel "MethodExit" let initESt = Left $ genBrBlock mthInitLabel instr est = [initESt, fieldsInit, blockESt] ++ [Right [emptyBlock mthRet $ I.Ret Nothing []] | mt == Void] mthBlocks = fromRight "genMethod join" . joinEStatements $ est removeScope return $ genMethodDefinition curClass mth mthBlocks genField :: Variable -> Codegen () genField (Variable vt vn ve) = do let expr = fromMaybe (nullValue vt) ve void $ genExpression $ Expr (Assign (QName (FieldAccess (QName This 0) vn) 0) expr) 0 genFieldsInit :: Codegen EStatement genFieldsInit = do cls <- getClassM forM_ (classFields cls) genField instr <- popInstructions fieldInitLabel <- nextLabel "FieldsInit" return . Left $ genBrBlock fieldInitLabel instr genClass :: Class -> Codegen [A.Definition] genClass cls = do modify $ \s -> s { csClass = Just cls } let struct = genStruct cls methods <- forM (classMethods cls) genMethod modify $ \s -> s { csClass = Nothing } return $ struct : methods genProgram :: Program -> Codegen A.Module genProgram p = do modify $ \s -> s { csProgram = Just $ nativeClasses ++ p } defs <- concat <$> forM p genClass mainF <- mainFunc nd <- nativeDefinitions let allDefs = mainF : (nd ++ defs) modify $ \s -> s { csProgram = Nothing } return A.defaultModule { A.moduleDefinitions = allDefs } mainFunc :: Codegen A.Definition mainFunc = do addScope let name = "Main" mth <- fromRight "new" <$> findMethod name name [] (\m -> methodType m == Constructor) ptr <- new name i <- callMethod name mth ptr [] addVoidInstr i instr <- popInstructions mainLabel <- nextLabel "main" let block = A.BasicBlock mainLabel instr $ A.Do $ I.Ret (Just $ A.ConstantOperand $ C.Int 32 0) [] removeScope return . A.GlobalDefinition $ G.functionDefaults { G.returnType = T.IntegerType 32 , G.name = A.Name "main" , G.parameters = ([], False) , G.basicBlocks = [block] }
ademinn/JavaWithClasses
src/Generator.hs
bsd-3-clause
18,576
1
19
4,379
7,253
3,558
3,695
409
8
{-# LANGUAGE MultiParamTypeClasses #-} module Math.VectorSpaces.Pearson where import qualified Math.Algebra.AbelianMonoid as AbM import qualified Math.Algebra.Monoid as M import qualified Math.Algebra.Group as G import qualified Math.Algebra.Module as Mod import qualified Math.VectorSpaces.Metric as Met import qualified Math.Algebra.Vector as V import qualified Math.Misc.Nat as Nat import qualified Data.Vector.Unboxed as Vect import Math.Misc.SimpleTypes -- | Do not construct directly, except when using 'Null'. The -- rationale for having a separate 'Null' constructor (which we chose -- not to have for, say, simplices) is the need for an any-dimensional -- null vector. The need for such a creature of course stems from the -- typesystem's lack of knowledge of dimensions. The null vector is -- really considered 0-dimensional, and we allow considering it as -- any-dimensional. -- -- It should be noted that there is a slight difference between 'Null' -- and a non-zero-dimensional vector @v@ with all components -- 0. Although @v == 'Null'@, you're not allowed to add @v@ to a -- vector of different dimension. Use 'Null' for that. Also general -- you should use 'Null' over such a @v@, as @'Null' == 'Null'@ is -- O(1), while all other comparisons are potentially O(n). data Pearson = C (Vect.Vector Double) | Null instance Eq Pearson where Null == Null = True C x == C y = x == y C x == Null = Vect.null (Vect.dropWhile (==0) x) Null == C x = Vect.null (Vect.dropWhile (==0) x) instance Show Pearson where show Null = "0" show (C x) | Vect.null x = "0" | otherwise = (show . Vect.toList) x fromList :: [Double] -> Pearson fromList = C . Vect.fromList components :: Pearson -> Vect.Vector Double components (C x) = x components Null = Vect.empty toList :: Pearson -> [Double] toList = Vect.toList . components dimension :: Pearson -> Nat.N dimension (C x) = (Nat.fromInt . Vect.length) x dimension Null = Nat.zero dimension' :: Pearson -> Int dimension' (C x) = Vect.length x dimension' Null = 0 -- | Turn a (machine-approximate) null vector into 'Null'. Don't use -- needlessly, it's an O(n) operation in the worst case. reduce :: Pearson -> Pearson reduce v | v == Null = Null | otherwise = v instance Ord Pearson where compare v w = compare (dimension v, components v) (dimension w, components w) instance M.AdditiveMonoid Pearson where (C x) <+> (C y) | Vect.length x == Vect.length y = C (Vect.zipWith (M.<+>) x y) | otherwise = error "Trying to add Pearson vectors of different dimension." x <+> Null = x Null <+> x = x nil = Null instance AbM.AbelianAdditiveMonoid Pearson instance G.AdditiveGroup Pearson where negative Null = Null negative (C x) = C (Vect.map G.negative x) instance Mod.Module Double Pearson where action c (C x) = C (Vect.map (c M.<*>) x) action _ Null = Null instance V.Vector Double Pearson -- FIXME: Should really use pseudometric here. This "metric" can certainly take infinite values. instance Met.Metric Pearson where distance _ Null = 1.0 / 0.0 distance Null _ = 1.0 / 0.0 distance (C x) (C y) | Vect.length x /= Vect.length y = error "Trying to compute the distance between Pearson vectors of different dimension." | otherwise = 1.0 - ( (n*ip-sx*sy)/( (sqrt (n*ssx-sx^2)) * (sqrt (n*ssy-sy^2)) ) ) where n = fromIntegral $ Vect.length x sx = Vect.sum x sy = Vect.sum y ssx = Vect.sum (Vect.map M.square x) ssy = Vect.sum (Vect.map M.square y) ip = Vect.sum (Vect.zipWith (M.<*>) x y)
michiexile/hplex
pershom/src/Math/VectorSpaces/Pearson.hs
bsd-3-clause
3,675
0
17
819
1,051
551
500
68
1
{-# LANGUAGE CPP #-} module GHC.Platform.X86_64 where import GhcPrelude #define MACHREGS_NO_REGS 0 #define MACHREGS_x86_64 1 #include "../../../includes/CodeGen.Platform.hs"
sdiehl/ghc
compiler/GHC/Platform/X86_64.hs
bsd-3-clause
178
0
3
21
14
11
3
3
0
module Misc where import Prelude () import Feldspar import qualified Feldspar.Mutable as Feld import Feldspar.SimpleVector import Feldspar.IO import Feldspar.IO.Mutable kernel :: Data Int32 -> Data Int32 kernel n = sum $ map (\x -> x*x) (0...n) prog = while (return true) $ do i <- fget stdin end <- feof stdin iff end break (return ()) o <- ifE (i > 0) (return $ kernel (guaranteePositive i)) (return 0) printf "Sum of squares: %d\n" o where guaranteePositive = cap (Range 1 maxBound) arrProg = do lr <- initRef 20 l <- unsafeFreezeRef lr arr1 :: Arr WordN WordN <- unsafeThawArr $ parallel l (*2) e <- getArr 18 arr1 printf "%d\n" e arr2 :: Arr WordN Int8 <- newArr 123 setArr 23 88 arr2 farr <- freezeArr arr2 123 printf "%d\n" (farr ! 23) mut :: Data WordN -> Feld.M (Data WordN) mut l = do arr <- Feld.newArr_ l Feld.forM l $ \i -> do Feld.setArr arr i i Feld.getArr arr 34 mutProg :: Program () mutProg = do r <- initRef 100 l <- getRef r printf "%d\n" =<< liftMut (mut l)
emilaxelsson/feldspar-io
examples/Misc.hs
bsd-3-clause
1,104
0
14
309
479
227
252
-1
-1
{-# LANGUAGE ScopedTypeVariables, MultiParamTypeClasses, FlexibleInstances #-} module Math.Quaternion ( Quaternion(..) , rotateQuatGL ) where import qualified Graphics.Rendering.OpenGL.GL as GL import Math.Vector import Math.Matrix class Vector q c => Quaternion q c where newQuaternion :: [c] -> q fromQuaternion :: (Quaternion q1 c) => q -> q1 quatToList :: q -> [c] quatToTuple :: q -> (c,c,c,c) quatToVec :: (Vector v c) => q -> v quatProduct :: q -> q -> q quatDot :: q -> q -> c quatInv :: q -> q quatMat :: (Matrix m c) => q -> m quatMatList :: q -> [c] quatConjugate :: q -> q quatMagnitude :: q -> c rotationQuat :: (Vector v c) => c -> v -> q rotateVector :: (Vector v c) => q -> v -> v quatToVec q = newVector $ quatToList q quatProduct q1 q2 = let (x1,y1,z1,w1) = quatToTuple q1 (x2,y2,z2,w2) = quatToTuple q2 qw = w1*w2 - x1*x2 - y1*y2 - z1*z2 qx = w1*x2 + x1*w2 + y1*z2 - z1*y2 qy = w1*y2 - x1*z2 + y1*w2 + z1*x2 qz = w1*z2 + x1*y2 - y1*x2 + z1*w2 in newQuaternion [qx,qy,qz,qw] quatDot q1 q2 = let (x1,y1,z1,w1) = quatToTuple q1 (x2,y2,z2,w2) = quatToTuple q2 in w1*w2 + x1*x2 + y1*y2 + z1*z2 quatInv q = vecMap (*(1/(q `quatDot` (quatConjugate q)))) (quatConjugate q) quatMat q = newMatrix $ quatMatList q -- http://www.genesis3d.com/~kdtop/Quaternions-UsingToRepresentRotation.htm quatMatList q = let (x,y,z,w) = quatToTuple q in [ w*w + x*x - y*y - z*z, 2*x*y + 2*w*z , 2*x*z - 2*w*y , 0 , 2*x*y - 2*w*z , w*w - x*x + y*y - z*z, 2*y*z + 2*w*x , 0 , 2*x*z + 2*w*y , 2*y*z - 2*w*x , w*w - x*x - y*y + z*z, 0 , 0 , 0 , 0 , w*w + x*x + y*y + z*z ] -- http://www.flipcode.com/documents/matrfaq.html#Q54 --quatMatList q = -- let (x,y,z,w) = quatToTuple q -- in [ 1 - 2*y^2 - 2*z^2, 2*x*y - 2*w*z , 2*x*z + 2*w*y , 0 -- , 2*x*y + 2*w*z , 1 - 2*x^2 - 2*z^2, 2*y*z - 2*w*x , 0 -- , 2*x*z - 2*w*y , 2*y*z + 2*w*x , 1 - 2*x^2 - 2*y^2, 0 -- , 0 , 0 , 0 , 1 ] quatConjugate q = let (x,y,z,w) = quatToTuple q in newQuaternion [(-x),(-y),(-z),w] quatMagnitude q = let (x,y,z,w) = quatToTuple q in sqrt (w*w + x*x + y*y + z*z) rotationQuat angle' u' = let u@(GL.Vector3 ux uy uz) = norm $ fromVector u' angle = pi/(360/angle') in newQuaternion [(ux * sin(angle)),(uy * sin(angle)),(uz * sin(angle)),(cos(angle))] rotateVector q v = fromVector $ q `quatProduct` (fromVector v) `quatProduct` (quatInv q) instance (Ord c,Enum c,Floating c,GL.VertexComponent c) => Quaternion (GL.Vertex4 c) c where newQuaternion xs | not(length xs == 4) = error "newQuaternion: list length must be 4" | otherwise = let (x:y:z:w:_) = xs in GL.Vertex4 x y z w fromQuaternion (GL.Vertex4 x y z w) = newQuaternion [x,y,z,w] quatToList (GL.Vertex4 x y z w) = [x,y,z,w] quatToTuple (GL.Vertex4 x y z w) = (x,y,z,w) rotationQuat angle' u' = let u@(GL.Vertex4 ux uy uz _) = norm $ fromVector u' angle = pi/(360/angle') in GL.Vertex4 (ux * sin(angle)) (uy * sin(angle)) (uz * sin(angle)) (cos(angle)) rotateQuatGL :: GL.Vertex4 GL.GLfloat -> IO () rotateQuatGL q = do (m :: GL.GLmatrix GL.GLfloat) <- GL.newMatrix GL.RowMajor $ quatMat q GL.multMatrix m
rakete/ObjViewer
src/Math/Quaternion.hs
bsd-3-clause
3,678
0
17
1,210
1,687
895
792
69
1
{-# LANGUAGE CPP #-} import Prelude hiding (read) import Network.HTTP import Network.Browser hiding (err) import Network.URI import qualified Data.ByteString.Lazy as BS import Data.Version import Data.Maybe (fromJust) import Codec.Compression.BZip import Codec.Archive.Tar import System.Environment (getArgs) import System.Exit import Control.Monad import Haste.Environment import Haste.Version import Control.Shell import Data.Char (isDigit) import Control.Monad.IO.Class (liftIO) import Haste.Args import System.Console.GetOpt import GHC.Paths (libdir) import System.Info (os) import System.Directory (copyPermissions) import System.FilePath (takeDirectory) #if __GLASGOW_HASKELL__ >= 710 ghcMajor = "7.10" libDir = "ghc-7.10" primVersion = "0.4.0.0" #else ghcMajor = "7.8" libDir = "ghc-7.8" primVersion = "0.3.0.0" #endif downloadFile :: String -> Shell BS.ByteString downloadFile f = do (_, rsp) <- liftIO $ Network.Browser.browse $ do setAllowRedirects True request $ Request { rqURI = fromJust $ parseURI f, rqMethod = GET, rqHeaders = [], rqBody = BS.empty } case rspCode rsp of (2, _, _) -> return $ rspBody rsp _ -> fail $ "Failed to download " ++ f ++ ": " ++ rspReason rsp data Cfg = Cfg { getLibs :: Bool, getClosure :: Bool, useLocalLibs :: Bool, tracePrimops :: Bool, forceBoot :: Bool, initialPortableBoot :: Bool, getHasteCabal :: Bool, verbose :: Bool } defCfg :: Cfg #ifdef PORTABLE defCfg = Cfg { getLibs = False, getClosure = False, useLocalLibs = False, tracePrimops = False, forceBoot = False, initialPortableBoot = False, getHasteCabal = True, verbose = False } #else defCfg = Cfg { getLibs = True, getClosure = True, useLocalLibs = False, tracePrimops = False, forceBoot = False, initialPortableBoot = False, getHasteCabal = True, verbose = False } #endif devBoot :: Cfg -> Cfg devBoot cfg = cfg { useLocalLibs = True, forceBoot = True, getClosure = False, getHasteCabal = False } setInitialPortableBoot :: Cfg -> Cfg setInitialPortableBoot cfg = cfg { getLibs = True, useLocalLibs = True, forceBoot = True, getClosure = True, initialPortableBoot = True, getHasteCabal = True } specs :: [OptDescr (Cfg -> Cfg)] specs = [ #ifndef PORTABLE Option "" ["dev"] (NoArg devBoot) $ "Boot Haste for development. Implies --force " ++ "--local --no-closure --no-haste-cabal" , Option "" ["force"] #else Option "" ["force"] #endif (NoArg $ \cfg -> cfg {forceBoot = True}) $ "Re-boot Haste even if already properly booted." , Option "" ["initial"] (NoArg setInitialPortableBoot) $ "Prepare boot files for binary distribution. Should only ever " ++ "be called by the release build scripts, never by users.\n" ++ "Implies --local --force." #ifndef PORTABLE , Option "" ["local"] (NoArg $ \cfg -> cfg {useLocalLibs = True}) $ "Use libraries from source repository rather than " ++ "downloading a matching set from the Internet. " ++ "This is nearly always necessary when installing " ++ "Haste from Git rather than from Hackage. " ++ "When using --local, your current working directory " ++ "must be the root of the Haste source tree." , Option "" ["no-closure"] (NoArg $ \cfg -> cfg {getClosure = False}) $ "Don't download Closure compiler. You won't be able " ++ "to use --opt-minify, unless you manually " ++ "give hastec the path to compiler.jar." , Option "" ["no-haste-cabal"] (NoArg $ \cfg -> cfg {getHasteCabal = False}) $ "Don't install haste-cabal. This is probably not " ++ "what you want." , Option "" ["no-libs"] (NoArg $ \cfg -> cfg {getLibs = False}) $ "Don't install any libraries. This is probably not " ++ "what you want." , Option "" ["trace-primops"] (NoArg $ \cfg -> cfg {tracePrimops = True}) $ "Build standard libs for tracing of primitive " ++ "operations. Only use if you're debugging the code " ++ "generator." , Option "v" ["verbose"] (NoArg $ \cfg -> cfg {verbose = True}) $ "Print absolutely everything." #endif ] hdr :: String hdr = "Fetch, build and install all libraries necessary to use Haste.\n" data CabalOp = Configure | Build | Install | Clean main :: IO () main = do args <- getArgs case parseArgs specs hdr args of Right (mkConfig, _) -> do let cfg = mkConfig defCfg when (hasteNeedsReboot || forceBoot cfg) $ do res <- shell $ if useLocalLibs cfg then bootHaste cfg "." else withTempDirectory "haste" $ bootHaste cfg case res of Right _ -> return () Left err -> putStrLn err >> exitFailure Left halp -> do putStrLn halp bootHaste :: Cfg -> FilePath -> Shell () bootHaste cfg tmpdir = withEnv "nodosfilewarning" (const "1") . inDirectory tmpdir $ do removeBootFile <- isFile bootFile when removeBootFile $ rm bootFile when (getLibs cfg) $ do -- Don't clear dir when it contains binaries; portable should only be built -- by scripts anyway, so this dir ought to be clean. when (not portableHaste) $ do mapM_ clearDir [pkgUserLibDir, jsmodUserDir, pkgUserDir, pkgSysLibDir, jsmodSysDir, pkgSysDir] when (getHasteCabal cfg) $ do installHasteCabal portableHaste tmpdir when (not $ useLocalLibs cfg) $ do fetchLibs tmpdir when (not portableHaste || initialPortableBoot cfg) $ do mkdir True hasteSysDir copyGhcSettings hasteSysDir void $ run hastePkgBinary ["init", pkgSysDir] "" buildLibs cfg when (initialPortableBoot cfg) $ do mapM_ relocate ["array", "bytestring", "containers", "deepseq", "dlist", "haste-prim", "time", "haste-lib", "monads-tf", "old-locale", "transformers", "integer-gmp"] when (getClosure cfg) $ do installClosure file bootFile (showBootVersion bootVersion) clearDir :: FilePath -> Shell () clearDir dir = do exists <- isDirectory dir when exists $ rmdir dir installHasteCabal :: Bool -> FilePath -> Shell () installHasteCabal portable tmpdir = do echo "Downloading haste-cabal from GitHub" f <- decompress `fmap` downloadFile hasteCabalUrl if os == "linux" then do mkdir True hasteCabalRootDir liftIO . unpack hasteCabalRootDir $ read f liftIO $ copyPermissions hasteBinary (hasteCabalRootDir </> "haste-cabal/haste-cabal.bin") file (hasteBinDir </> hasteCabalFile) launcher else do liftIO $ BS.writeFile (hasteBinDir </> hasteCabalFile) f liftIO $ copyPermissions hasteBinary (hasteBinDir </> hasteCabalFile) where baseUrl = "http://valderman.github.io/haste-libs/" hasteCabalUrl | os == "linux" = baseUrl ++ "haste-cabal.linux.tar.bz2" | otherwise = baseUrl ++ "haste-cabal" <.> os <.> "bz2" hasteCabalFile = "haste-cabal" ++ if os == "mingw32" then ".exe" else "" hasteCabalRootDir | portable = hasteBinDir </> ".." | otherwise = hasteSysDir -- We need to determine the haste-cabal libdir at runtime if we're -- portable launcher | portable = unlines [ "#!/bin/bash", "HASTEC=\"$(dirname $0)/hastec\"", "DIR=\"$($HASTEC --print-libdir)/../haste-cabal\"", "export LD_LIBRARY_PATH=$DIR", "exec $DIR/haste-cabal.bin $@" ] | otherwise = unlines [ "#!/bin/bash", "DIR=\"" ++ hasteCabalRootDir </> "haste-cabal" ++ "\"", "export LD_LIBRARY_PATH=$DIR", "exec $DIR/haste-cabal.bin $@" ] -- | Fetch the Haste base libs. fetchLibs :: FilePath -> Shell () fetchLibs tmpdir = do echo "Downloading base libs from GitHub" file <- downloadFile $ mkUrl hasteVersion liftIO . unpack tmpdir . read . decompress $ file where mkUrl v = "http://valderman.github.io/haste-libs/haste-libs-" ++ showVersion v ++ ".tar.bz2" -- | Fetch and install the Closure compiler. installClosure :: Shell () installClosure = do echo "Downloading Google Closure compiler..." downloadClosure `orElse` do echo "Couldn't install Closure compiler; continuing without." where downloadClosure = do downloadFile closureURI >>= (liftIO . BS.writeFile closureCompiler) closureURI = "http://valderman.github.io/haste-libs/compiler.jar" -- | Build haste's base libs. buildLibs :: Cfg -> Shell () buildLibs cfg = do -- Set up dirs and copy includes mkdir True $ pkgSysLibDir cpDir "include" hasteSysDir inDirectory ("utils" </> "unlit") $ do let out = if os == "mingw32" then "unlit.exe" else "unlit" run_ "gcc" ["-o" ++ out, "-O2", "unlit.c", "-static"] "" run_ "strip" ["-s", out] "" cp out (hasteSysDir </> out) run_ hastePkgBinary ["update", "--global", "libraries" </> "rts.pkg"] "" inDirectory "libraries" $ do inDirectory libDir $ do -- Install ghc-prim inDirectory "ghc-prim" $ do #if __GLASGOW_HASKELL__ >= 710 cp "../../../include/ghcplatform.h" "../ghc_boot_platform.h" run_ "cpp" ["-P", "-I../../../include", "../primops.txt.pp", "-o", "primops.txt"] "" #endif hasteCabal Install ["--solver", "topdown"] -- To get the GHC.Prim module in spite of pretending to have -- build-type: Simple run_ hastePkgBinary ["unregister", "--global","ghc-prim"] "" run_ hastePkgBinary ["update", "--global","ghc-prim-"++primVersion++".conf"] "" -- Install integer-gmp; double install shouldn't be needed anymore. inDirectory "integer-gmp" $ do hasteCabal Install ["--solver", "topdown"] -- Install base inDirectory "base" $ do hasteCabal Clean [] hasteCabal Install ["--solver", "topdown", "-finteger-gmp"] -- Install array inDirectory "array" $ hasteCabal Clean [] inDirectory "array" $ hasteCabal Install [] -- Install haste-prim inDirectory "haste-prim" $ hasteCabal Install [] -- Install time inDirectory "time" $ hasteCabal Install [] -- Install haste-lib inDirectory "haste-lib" $ hasteCabal Install [] -- Export monads-tf; it seems to be hidden by default run_ hastePkgBinary ["expose", "monads-tf"] "" where ghcOpts = concat [ if tracePrimops cfg then ["--hastec-option=-debug"] else [], if verbose cfg then ["--verbose"] else []] configOpts = [ "--with-hastec=" ++ hasteBinary , "--with-haste-pkg=" ++ hastePkgBinary , "--libdir=" ++ takeDirectory pkgSysLibDir , "--package-db=clear" , "--package-db=global" #if __GLASGOW_HASKELL__ < 709 , "--hastec-option=-DHASTE_HOST_WORD_SIZE_IN_BITS=" ++ show hostWordSize #endif ] hasteCabal Configure args = withEnv "HASTE_BOOTING" (const "1") $ run_ hasteCabalBinary as "" where as = "configure" : args ++ ghcOpts ++ configOpts hasteCabal Install args = withEnv "HASTE_BOOTING" (const "1") $ run_ hasteCabalBinary as "" where as = "install" : args ++ ghcOpts ++ configOpts hasteCabal Build args = withEnv "HASTE_BOOTING" (const "1") $ run_ hasteCabalBinary as "" where as = "build" : args ++ ghcOpts hasteCabal Clean args = withEnv "HASTE_BOOTING" (const "1") $ run_ hasteCabalBinary as "" where as = "clean" : args vanillaCabal args = run_ "cabal" args "" -- | Copy GHC settings and utils into the given directory. copyGhcSettings :: FilePath -> Shell () copyGhcSettings dest = do cp (libdir </> "platformConstants") (dest </> "platformConstants") #ifdef mingw32_HOST_OS cp ("settings-ghc-" ++ ghcMajor ++ ".windows") (dest </> "settings") cp (libdir </> "touchy.exe") (dest </> "touchy.exe") #else cp (libdir </> "settings") (dest </> "settings") #endif relocate :: String -> Shell () relocate pkg = run_ hastePkgBinary ["relocate", pkg] ""
jtojnar/haste-compiler
src/haste-boot.hs
bsd-3-clause
12,923
11
20
3,758
2,921
1,512
1,409
270
7
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module ServerSpec (spec) where import Control.Concurrent import qualified Control.Exception as E import Data.ByteString.Builder (byteString) import Network.HTTP.Types import Network.Run.TCP import System.Exit import System.Process.Typed import Test.Hspec import Network.HTTP2.Server port :: String port = "8080" host :: String host = "127.0.0.1" spec :: Spec spec = do describe "server" $ do it "handles error cases" $ E.bracket (forkIO runServer) killThread $ \_ -> do runProcess (proc "h2spec" ["-h",host,"-p",port]) `shouldReturn` ExitSuccess runServer :: IO () runServer = runTCPServer (Just host) port runHTTP2Server where runHTTP2Server s = E.bracket (allocSimpleConfig s 4096) freeSimpleConfig (`run` server) server :: Server server req _aux sendResponse = case requestMethod req of Just "GET" -> case requestPath req of Just "/" -> sendResponse responseHello [] _ -> sendResponse response404 [] _ -> sendResponse response405 [] responseHello :: Response responseHello = responseBuilder ok200 header body where header = [("Content-Type", "text/plain")] body = byteString "Hello, world!\n" response404 :: Response response404 = responseNoBody notFound404 [] response405 :: Response response405 = responseNoBody methodNotAllowed405 []
kazu-yamamoto/http2
test2/ServerSpec.hs
bsd-3-clause
1,506
0
18
368
391
212
179
41
3
{-# LAnguage OverloadedStrings, QuasiQuotes #-} module Main where import Data.String.QM import Data.String mobapi = "https://m.tenrox.net/2014R3/tenterprise/api/" org = "OpenBet" wsdlUrl :: String -> String wsdlUrl serv = [qm|https://${org}.tenrox.net/TWebService/${serv}.svc?wsdl|] -- https://openbet.tenrox.net/TWebService/Timesheets.svc -- loginUrl org user pass = main = do org = "OpenBet" putStrLn [qm|https://m.tenrox.net/default.aspx?v=3.0.1&device=ios&organization=${org}|] putStrLn $ wsdlUrl "Timesheets"
tolysz/henrox
src/Main.hs
bsd-3-clause
523
1
8
56
82
48
34
-1
-1
module Day08 where totalCharsDiff :: String -> Int totalCharsDiff = sum . map charDiff . lines totalCharsDiff2 :: String -> Int totalCharsDiff2 = sum . map charDiff2 . lines charDiff2 :: String -> Int charDiff2 s = specialChars s + 2 charDiff :: String -> Int charDiff s = length s + 2 - chars s chars :: String -> Int chars = \case '\\':'\\':cs -> 1 + chars cs '\\':'"':cs -> 1 + chars cs '\\':'x':(isHex -> True):(isHex -> True):cs -> 1 + chars cs _:cs -> 1 + chars cs [] -> 0 specialChars :: String -> Int specialChars = length . filter isSpecial where isSpecial c = c == '\\' || c == '"' isHex :: Char -> Bool isHex = (`elem` hexChars) where hexChars = ['0'..'9'] ++ ['a'..'f'] ++ ['A'..'F']
patrickherrmann/advent
src/Day08.hs
bsd-3-clause
716
0
12
154
316
165
151
-1
-1
{-| Tools for output JSON message in JSend -} module Yesod.Helpers.JSend where import ClassyPrelude.Yesod import Control.Monad.Writer (Writer) import Data.Monoid (Endo) import Text.Julius (rawJS, Javascript, toJavascript) data JSendMsg = JSendSuccess Value | JSendFail Value | JSendError Text (Maybe Integer) (Maybe Value) -- ^ message, code, data deriving (Show, Read, Eq) instance ToJSON JSendMsg where toJSON (JSendSuccess dat) = object [ "status" .= ("success" :: Text) , "data" .= dat ] toJSON (JSendFail dat) = object [ "status" .= ("fail" :: Text) , "data" .= dat ] toJSON (JSendError err_msg m_code m_dat) = object $ catMaybes [ Just $ "status" .= ("error" :: Text) , Just $ "message" .= err_msg , fmap ("data" .= ) m_dat , fmap ("code" .= ) m_code ] instance ToContent JSendMsg where toContent = toContent . toJSON instance ToTypedContent JSendMsg where toTypedContent = toTypedContent . toJSON instance HasContentType JSendMsg where getContentType _ = getContentType (Nothing :: Maybe Value) -- | One way to pack JSendMsg to a JSONP message jsendToJsonp :: Text -> JSendMsg -> Javascript jsendToJsonp callback jmsg = toJavascript $ rawJS $ renderJavascriptUrl dummy_render $ jsendToJsonpU callback jmsg where dummy_render _ _ = error "jsendToJsonp: should never reach here" jsendToJsonpU :: Text -> JSendMsg -> JavascriptUrl url jsendToJsonpU callback (JSendSuccess v) = [julius| #{rawJS callback}([#{v}]); |] jsendToJsonpU callback (JSendFail v) = [julius| #{rawJS callback}([undefined, #{v}]); |] jsendToJsonpU callback (JSendError msg code m_data) = [julius| #{rawJS callback}([undefined, #{toJSON msg}, #{toJSON code}, #{toJSON m_data}]); |] -- | Use this instead of `provideRep`: -- to provide both a jsend and a jsonp response provideRepJsendAndJsonp :: (MonadHandler m) => m JSendMsg -> Writer (Endo [ProvidedRep m]) () provideRepJsendAndJsonp get_jmsg = do provideRep get_jmsg provideRep f where f = do callback <- fmap (fromMaybe "callback") $ lookupGetParam "callback" fmap (jsendToJsonp callback) $ get_jmsg -- vim: set foldmethod=marker:
yoo-e/yesod-helpers
Yesod/Helpers/JSend.hs
bsd-3-clause
2,666
0
13
903
570
305
265
-1
-1
module PieceSelectionSpec where import Data.AEq import qualified Data.Vector.Unboxed as VU import Network.BitTorrent.PieceSelection import qualified Network.BitTorrent.BitField as BF import Numeric.IEEE import Test.Hspec spec :: SpecWith () spec = do it "gets the most demanded piece" $ pending it "does not return anything after completing" $ pending
farnoy/torrent
test/PieceSelectionSpec.hs
bsd-3-clause
366
0
8
59
78
46
32
13
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Diffbot.Types where import Control.Applicative import qualified Data.ByteString.Lazy as BL -- | All information on how to connect to a Diffbot and what should be -- sent in the request. class Request a where toReq :: a -> Req data Req = Req { reqApi :: String , reqContent :: Maybe Content , reqQuery :: [(String, Maybe String)] } appendQuery :: [(String, Maybe String)] -> Req -> Req appendQuery query req = req { reqQuery = query ++ reqQuery req } mkQuery :: String -> Maybe String -> Maybe (String, Maybe String) mkQuery k v = do v' <- v return (k, Just v') mkQueryBool :: String -> Bool -> Maybe (String, Maybe String) mkQueryBool k b = if b then Just (k, Nothing) else Nothing mkQueryFalse :: String -> Bool -> Maybe (String, Maybe String) mkQueryFalse k b = if b then Nothing else Just (k, Just "0") -- | Used to control which fields are returned by the API. class Fields a where fields :: a -> Maybe String setFields :: Maybe String -> a -> a fieldsQuery :: Fields a => a -> Maybe (String, Maybe String) fieldsQuery a = mkQuery "fields" $ fields a class Post a where content :: a -> Maybe Content setContent :: Maybe Content -> a -> a class Timeout a where timeout :: a -> Maybe Int setTimeout :: Maybe Int -> a -> a timeoutQuery :: Timeout a => a -> Maybe (String, Maybe String) timeoutQuery a = mkQuery "timeout" $ show <$> timeout a data Content = Content { contentType :: ContentType -- ^ Type of content. , contentData :: BL.ByteString -- ^ Content to analyze. } data ContentType = TextPlain | TextHtml -- strange behavior: the server returns error with corret "text/plain" -- content-type instance Show ContentType where show TextPlain = "text-plain" show TextHtml = "text-html"
tymmym/diffbot
src/Diffbot/Types.hs
bsd-3-clause
1,910
0
11
459
570
302
268
42
2
import Data.Char (ord, chr) import Data.Ord (comparing) import Data.List (minimumBy, (\\), intercalate, sort) type Square = (Int, Int) -- board :: [Square] board = [ (x, y) | x <- [1 .. 8] , y <- [1 .. 8] ] -- knightMoves :: Square -> [Square] knightMoves (x, y) = filter (`elem` board) jumps where jumps = [ (x + i, y + j) | i <- jv , j <- jv , abs i /= abs j ] jv = [1, -1, 2, -2] -- knightTour :: [Square] -> [Square] knightTour moves | null candMoves = reverse moves | otherwise = knightTour $ newSquare : moves where newSquare = minimumBy (comparing (length . findMoves)) candMoves candMoves = findMoves $ head moves findMoves = (\\ moves) . knightMoves -- toSq :: String -> (Int, Int) toSq [x, y] = (ord x - 96, ord y - 48) -- toAlg :: (Int, Int) -> String toAlg (x, y) = [chr (x + 96), chr (y + 48)] -- TEST ----------------------------------------------------------------------- -- sq :: (Int, Int) sq = toSq "e5" -- Input: starting position on the board, e.g. (5, 5) as "e5" -- main :: IO () main = printTour $ toAlg <$> knightTour [sq] where printTour [] = return () printTour tour = do putStrLn $ intercalate " -> " $ take 8 tour printTour $ drop 8 tour
timm/sandbox
ghc/kt.hs
bsd-3-clause
1,264
5
11
327
456
248
208
29
2
{-# language CPP #-} -- No documentation found for Chapter "ImageView" module Vulkan.Core10.ImageView ( createImageView , withImageView , destroyImageView , ComponentMapping(..) , ImageSubresourceRange(..) , ImageViewCreateInfo(..) , ImageView(..) , ImageViewType(..) , ComponentSwizzle(..) , ImageViewCreateFlagBits(..) , ImageViewCreateFlags ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Data.Typeable (eqT) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (castPtr) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.Type.Equality ((:~:)(Refl)) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Vulkan.CStruct.Extends (forgetExtensions) import Vulkan.NamedType ((:::)) import Vulkan.Core10.AllocationCallbacks (AllocationCallbacks) import Vulkan.CStruct.Extends (Chain) import Vulkan.Core10.Enums.ComponentSwizzle (ComponentSwizzle) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Dynamic (DeviceCmds(pVkCreateImageView)) import Vulkan.Dynamic (DeviceCmds(pVkDestroyImageView)) import Vulkan.Core10.Handles (Device_T) import Vulkan.CStruct.Extends (Extends) import Vulkan.CStruct.Extends (Extendss) import Vulkan.CStruct.Extends (Extensible(..)) import Vulkan.Core10.Enums.Format (Format) import Vulkan.Core10.Handles (Image) import Vulkan.Core10.Enums.ImageAspectFlagBits (ImageAspectFlags) import Vulkan.Core10.Handles (ImageView) import Vulkan.Core10.Handles (ImageView(..)) import {-# SOURCE #-} Vulkan.Extensions.VK_EXT_astc_decode_mode (ImageViewASTCDecodeModeEXT) import Vulkan.Core10.Enums.ImageViewCreateFlagBits (ImageViewCreateFlags) import {-# SOURCE #-} Vulkan.Extensions.VK_EXT_image_view_min_lod (ImageViewMinLodCreateInfoEXT) import Vulkan.Core10.Enums.ImageViewType (ImageViewType) import {-# SOURCE #-} Vulkan.Core11.Promoted_From_VK_KHR_maintenance2 (ImageViewUsageCreateInfo) import Vulkan.CStruct.Extends (PeekChain) import Vulkan.CStruct.Extends (PeekChain(..)) import Vulkan.CStruct.Extends (PokeChain) import Vulkan.CStruct.Extends (PokeChain(..)) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import {-# SOURCE #-} Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion (SamplerYcbcrConversionInfo) import Vulkan.CStruct.Extends (SomeStruct) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Core10.Enums.ComponentSwizzle (ComponentSwizzle(..)) import Vulkan.Core10.Handles (ImageView(..)) import Vulkan.Core10.Enums.ImageViewCreateFlagBits (ImageViewCreateFlagBits(..)) import Vulkan.Core10.Enums.ImageViewCreateFlagBits (ImageViewCreateFlags) import Vulkan.Core10.Enums.ImageViewType (ImageViewType(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCreateImageView :: FunPtr (Ptr Device_T -> Ptr (SomeStruct ImageViewCreateInfo) -> Ptr AllocationCallbacks -> Ptr ImageView -> IO Result) -> Ptr Device_T -> Ptr (SomeStruct ImageViewCreateInfo) -> Ptr AllocationCallbacks -> Ptr ImageView -> IO Result -- | vkCreateImageView - Create an image view from an existing image -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCreateImageView-device-parameter# @device@ /must/ be a valid -- 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkCreateImageView-pCreateInfo-parameter# @pCreateInfo@ /must/ -- be a valid pointer to a valid 'ImageViewCreateInfo' structure -- -- - #VUID-vkCreateImageView-pAllocator-parameter# If @pAllocator@ is not -- @NULL@, @pAllocator@ /must/ be a valid pointer to a valid -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- -- - #VUID-vkCreateImageView-pView-parameter# @pView@ /must/ be a valid -- pointer to a 'Vulkan.Core10.Handles.ImageView' handle -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- = 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.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.ImageView', -- 'ImageViewCreateInfo' createImageView :: forall a io . (Extendss ImageViewCreateInfo a, PokeChain a, MonadIO io) => -- | @device@ is the logical device that creates the image view. Device -> -- | @pCreateInfo@ is a pointer to a 'ImageViewCreateInfo' structure -- containing parameters to be used to create the image view. (ImageViewCreateInfo a) -> -- | @pAllocator@ controls host memory allocation as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation> -- chapter. ("allocator" ::: Maybe AllocationCallbacks) -> io (ImageView) createImageView device createInfo allocator = liftIO . evalContT $ do let vkCreateImageViewPtr = pVkCreateImageView (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkCreateImageViewPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCreateImageView is null" Nothing Nothing let vkCreateImageView' = mkVkCreateImageView vkCreateImageViewPtr pCreateInfo <- ContT $ withCStruct (createInfo) pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) pPView <- ContT $ bracket (callocBytes @ImageView 8) free r <- lift $ traceAroundEvent "vkCreateImageView" (vkCreateImageView' (deviceHandle (device)) (forgetExtensions pCreateInfo) pAllocator (pPView)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pView <- lift $ peek @ImageView pPView pure $ (pView) -- | A convenience wrapper to make a compatible pair of calls to -- 'createImageView' and 'destroyImageView' -- -- To ensure that 'destroyImageView' is always called: pass -- 'Control.Exception.bracket' (or the allocate function from your -- favourite resource management library) as the last argument. -- To just extract the pair pass '(,)' as the last argument. -- withImageView :: forall a io r . (Extendss ImageViewCreateInfo a, PokeChain a, MonadIO io) => Device -> ImageViewCreateInfo a -> Maybe AllocationCallbacks -> (io ImageView -> (ImageView -> io ()) -> r) -> r withImageView device pCreateInfo pAllocator b = b (createImageView device pCreateInfo pAllocator) (\(o0) -> destroyImageView device o0 pAllocator) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkDestroyImageView :: FunPtr (Ptr Device_T -> ImageView -> Ptr AllocationCallbacks -> IO ()) -> Ptr Device_T -> ImageView -> Ptr AllocationCallbacks -> IO () -- | vkDestroyImageView - Destroy an image view object -- -- == Valid Usage -- -- - #VUID-vkDestroyImageView-imageView-01026# All submitted commands -- that refer to @imageView@ /must/ have completed execution -- -- - #VUID-vkDestroyImageView-imageView-01027# If -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were -- provided when @imageView@ was created, a compatible set of callbacks -- /must/ be provided here -- -- - #VUID-vkDestroyImageView-imageView-01028# If no -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were -- provided when @imageView@ was created, @pAllocator@ /must/ be @NULL@ -- -- == Valid Usage (Implicit) -- -- - #VUID-vkDestroyImageView-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkDestroyImageView-imageView-parameter# If @imageView@ is not -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', @imageView@ /must/ be a -- valid 'Vulkan.Core10.Handles.ImageView' handle -- -- - #VUID-vkDestroyImageView-pAllocator-parameter# If @pAllocator@ is -- not @NULL@, @pAllocator@ /must/ be a valid pointer to a valid -- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure -- -- - #VUID-vkDestroyImageView-imageView-parent# If @imageView@ is a valid -- handle, it /must/ have been created, allocated, or retrieved from -- @device@ -- -- == Host Synchronization -- -- - Host access to @imageView@ /must/ be externally synchronized -- -- = 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.AllocationCallbacks.AllocationCallbacks', -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Core10.Handles.ImageView' destroyImageView :: forall io . (MonadIO io) => -- | @device@ is the logical device that destroys the image view. Device -> -- | @imageView@ is the image view to destroy. ImageView -> -- | @pAllocator@ controls host memory allocation as described in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation> -- chapter. ("allocator" ::: Maybe AllocationCallbacks) -> io () destroyImageView device imageView allocator = liftIO . evalContT $ do let vkDestroyImageViewPtr = pVkDestroyImageView (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkDestroyImageViewPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkDestroyImageView is null" Nothing Nothing let vkDestroyImageView' = mkVkDestroyImageView vkDestroyImageViewPtr pAllocator <- case (allocator) of Nothing -> pure nullPtr Just j -> ContT $ withCStruct (j) lift $ traceAroundEvent "vkDestroyImageView" (vkDestroyImageView' (deviceHandle (device)) (imageView) pAllocator) pure $ () -- | VkComponentMapping - Structure specifying a color component mapping -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'Vulkan.Extensions.VK_ANDROID_external_memory_android_hardware_buffer.AndroidHardwareBufferFormatProperties2ANDROID', -- 'Vulkan.Extensions.VK_ANDROID_external_memory_android_hardware_buffer.AndroidHardwareBufferFormatPropertiesANDROID', -- 'Vulkan.Extensions.VK_FUCHSIA_buffer_collection.BufferCollectionPropertiesFUCHSIA', -- 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle', -- 'ImageViewCreateInfo', -- 'Vulkan.Extensions.VK_EXT_border_color_swizzle.SamplerBorderColorComponentMappingCreateInfoEXT', -- 'Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion.SamplerYcbcrConversionCreateInfo' data ComponentMapping = ComponentMapping { -- | @r@ is a 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle' -- specifying the component value placed in the R component of the output -- vector. -- -- #VUID-VkComponentMapping-r-parameter# @r@ /must/ be a valid -- 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle' value r :: ComponentSwizzle , -- | @g@ is a 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle' -- specifying the component value placed in the G component of the output -- vector. -- -- #VUID-VkComponentMapping-g-parameter# @g@ /must/ be a valid -- 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle' value g :: ComponentSwizzle , -- | @b@ is a 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle' -- specifying the component value placed in the B component of the output -- vector. -- -- #VUID-VkComponentMapping-b-parameter# @b@ /must/ be a valid -- 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle' value b :: ComponentSwizzle , -- | @a@ is a 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle' -- specifying the component value placed in the A component of the output -- vector. -- -- #VUID-VkComponentMapping-a-parameter# @a@ /must/ be a valid -- 'Vulkan.Core10.Enums.ComponentSwizzle.ComponentSwizzle' value a :: ComponentSwizzle } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (ComponentMapping) #endif deriving instance Show ComponentMapping instance ToCStruct ComponentMapping where withCStruct x f = allocaBytes 16 $ \p -> pokeCStruct p x (f p) pokeCStruct p ComponentMapping{..} f = do poke ((p `plusPtr` 0 :: Ptr ComponentSwizzle)) (r) poke ((p `plusPtr` 4 :: Ptr ComponentSwizzle)) (g) poke ((p `plusPtr` 8 :: Ptr ComponentSwizzle)) (b) poke ((p `plusPtr` 12 :: Ptr ComponentSwizzle)) (a) f cStructSize = 16 cStructAlignment = 4 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr ComponentSwizzle)) (zero) poke ((p `plusPtr` 4 :: Ptr ComponentSwizzle)) (zero) poke ((p `plusPtr` 8 :: Ptr ComponentSwizzle)) (zero) poke ((p `plusPtr` 12 :: Ptr ComponentSwizzle)) (zero) f instance FromCStruct ComponentMapping where peekCStruct p = do r <- peek @ComponentSwizzle ((p `plusPtr` 0 :: Ptr ComponentSwizzle)) g <- peek @ComponentSwizzle ((p `plusPtr` 4 :: Ptr ComponentSwizzle)) b <- peek @ComponentSwizzle ((p `plusPtr` 8 :: Ptr ComponentSwizzle)) a <- peek @ComponentSwizzle ((p `plusPtr` 12 :: Ptr ComponentSwizzle)) pure $ ComponentMapping r g b a instance Storable ComponentMapping where sizeOf ~_ = 16 alignment ~_ = 4 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero ComponentMapping where zero = ComponentMapping zero zero zero zero -- | VkImageSubresourceRange - Structure specifying an image subresource -- range -- -- = Description -- -- The number of mipmap levels and array layers /must/ be a subset of the -- image subresources in the image. If an application wants to use all mip -- levels or layers in an image after the @baseMipLevel@ or -- @baseArrayLayer@, it /can/ set @levelCount@ and @layerCount@ to the -- special values 'Vulkan.Core10.APIConstants.REMAINING_MIP_LEVELS' and -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS' without knowing the -- exact number of mip levels or layers. -- -- For cube and cube array image views, the layers of the image view -- starting at @baseArrayLayer@ correspond to faces in the order +X, -X, -- +Y, -Y, +Z, -Z. For cube arrays, each set of six sequential layers is a -- single cube, so the number of cube maps in a cube map array view is -- /@layerCount@ \/ 6/, and image array layer (@baseArrayLayer@ + i) is -- face index (i mod 6) of cube /i \/ 6/. If the number of layers in the -- view, whether set explicitly in @layerCount@ or implied by -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', is not a multiple -- of 6, the last cube map in the array /must/ not be accessed. -- -- @aspectMask@ /must/ be only -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_COLOR_BIT', -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_DEPTH_BIT' or -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_STENCIL_BIT' if -- @format@ is a color, depth-only or stencil-only format, respectively, -- except if @format@ is a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-requiring-sampler-ycbcr-conversion multi-planar format>. -- If using a depth\/stencil format with both depth and stencil components, -- @aspectMask@ /must/ include at least one of -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_DEPTH_BIT' and -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_STENCIL_BIT', and -- /can/ include both. -- -- When the 'ImageSubresourceRange' structure is used to select a subset of -- the slices of a 3D image’s mip level in order to create a 2D or 2D array -- image view of a 3D image created with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT', -- @baseArrayLayer@ and @layerCount@ specify the first slice index and the -- number of slices to include in the created image view. Such an image -- view /can/ be used as a framebuffer attachment that refers only to the -- specified range of slices of the selected mip level. However, any layout -- transitions performed on such an attachment view during a render pass -- instance still apply to the entire subresource referenced which includes -- all the slices of the selected mip level. -- -- When using an image view of a depth\/stencil image to populate a -- descriptor set (e.g. for sampling in the shader, or for use as an input -- attachment), the @aspectMask@ /must/ only include one bit, which selects -- whether the image view is used for depth reads (i.e. using a -- floating-point sampler or input attachment in the shader) or stencil -- reads (i.e. using an unsigned integer sampler or input attachment in the -- shader). When an image view of a depth\/stencil image is used as a -- depth\/stencil framebuffer attachment, the @aspectMask@ is ignored and -- both depth and stencil image subresources are used. -- -- When creating a 'Vulkan.Core10.Handles.ImageView', if -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#samplers-YCbCr-conversion sampler Y′CBCR conversion> -- is enabled in the sampler, the @aspectMask@ of a @subresourceRange@ used -- by the 'Vulkan.Core10.Handles.ImageView' /must/ be -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_COLOR_BIT'. -- -- When creating a 'Vulkan.Core10.Handles.ImageView', if sampler Y′CBCR -- conversion is not enabled in the sampler and the image @format@ is -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-requiring-sampler-ycbcr-conversion multi-planar>, -- the image /must/ have been created with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_MUTABLE_FORMAT_BIT', -- and the @aspectMask@ of the 'Vulkan.Core10.Handles.ImageView'’s -- @subresourceRange@ /must/ be -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_0_BIT', -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_1_BIT' or -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_2_BIT'. -- -- == Valid Usage -- -- - #VUID-VkImageSubresourceRange-levelCount-01720# If @levelCount@ is -- not 'Vulkan.Core10.APIConstants.REMAINING_MIP_LEVELS', it /must/ be -- greater than @0@ -- -- - #VUID-VkImageSubresourceRange-layerCount-01721# If @layerCount@ is -- not 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', it /must/ -- be greater than @0@ -- -- - #VUID-VkImageSubresourceRange-aspectMask-01670# If @aspectMask@ -- includes -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_COLOR_BIT', -- then it /must/ not include any of -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_0_BIT', -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_1_BIT', -- or -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_2_BIT' -- -- - #VUID-VkImageSubresourceRange-aspectMask-02278# @aspectMask@ /must/ -- not include @VK_IMAGE_ASPECT_MEMORY_PLANE_i_BIT_EXT@ for any index -- /i/ -- -- == Valid Usage (Implicit) -- -- - #VUID-VkImageSubresourceRange-aspectMask-parameter# @aspectMask@ -- /must/ be a valid combination of -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.ImageAspectFlagBits' values -- -- - #VUID-VkImageSubresourceRange-aspectMask-requiredbitmask# -- @aspectMask@ /must/ not be @0@ -- -- = 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.Enums.ImageAspectFlagBits.ImageAspectFlags', -- 'Vulkan.Core10.OtherTypes.ImageMemoryBarrier', -- 'Vulkan.Core13.Promoted_From_VK_KHR_synchronization2.ImageMemoryBarrier2', -- 'ImageViewCreateInfo', -- 'Vulkan.Core10.CommandBufferBuilding.cmdClearColorImage', -- 'Vulkan.Core10.CommandBufferBuilding.cmdClearDepthStencilImage' data ImageSubresourceRange = ImageSubresourceRange { -- | @aspectMask@ is a bitmask of -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.ImageAspectFlagBits' specifying -- which aspect(s) of the image are included in the view. aspectMask :: ImageAspectFlags , -- | @baseMipLevel@ is the first mipmap level accessible to the view. baseMipLevel :: Word32 , -- | @levelCount@ is the number of mipmap levels (starting from -- @baseMipLevel@) accessible to the view. levelCount :: Word32 , -- | @baseArrayLayer@ is the first array layer accessible to the view. baseArrayLayer :: Word32 , -- | @layerCount@ is the number of array layers (starting from -- @baseArrayLayer@) accessible to the view. layerCount :: Word32 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (ImageSubresourceRange) #endif deriving instance Show ImageSubresourceRange instance ToCStruct ImageSubresourceRange where withCStruct x f = allocaBytes 20 $ \p -> pokeCStruct p x (f p) pokeCStruct p ImageSubresourceRange{..} f = do poke ((p `plusPtr` 0 :: Ptr ImageAspectFlags)) (aspectMask) poke ((p `plusPtr` 4 :: Ptr Word32)) (baseMipLevel) poke ((p `plusPtr` 8 :: Ptr Word32)) (levelCount) poke ((p `plusPtr` 12 :: Ptr Word32)) (baseArrayLayer) poke ((p `plusPtr` 16 :: Ptr Word32)) (layerCount) f cStructSize = 20 cStructAlignment = 4 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr ImageAspectFlags)) (zero) poke ((p `plusPtr` 4 :: Ptr Word32)) (zero) poke ((p `plusPtr` 8 :: Ptr Word32)) (zero) poke ((p `plusPtr` 12 :: Ptr Word32)) (zero) poke ((p `plusPtr` 16 :: Ptr Word32)) (zero) f instance FromCStruct ImageSubresourceRange where peekCStruct p = do aspectMask <- peek @ImageAspectFlags ((p `plusPtr` 0 :: Ptr ImageAspectFlags)) baseMipLevel <- peek @Word32 ((p `plusPtr` 4 :: Ptr Word32)) levelCount <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32)) baseArrayLayer <- peek @Word32 ((p `plusPtr` 12 :: Ptr Word32)) layerCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pure $ ImageSubresourceRange aspectMask baseMipLevel levelCount baseArrayLayer layerCount instance Storable ImageSubresourceRange where sizeOf ~_ = 20 alignment ~_ = 4 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero ImageSubresourceRange where zero = ImageSubresourceRange zero zero zero zero zero -- | VkImageViewCreateInfo - Structure specifying parameters of a newly -- created image view -- -- = Description -- -- Some of the @image@ creation parameters are inherited by the view. In -- particular, image view creation inherits the implicit parameter @usage@ -- specifying the allowed usages of the image view that, by default, takes -- the value of the corresponding @usage@ parameter specified in -- 'Vulkan.Core10.Image.ImageCreateInfo' at image creation time. The -- implicit @usage@ /can/ be overriden by adding a -- 'Vulkan.Core11.Promoted_From_VK_KHR_maintenance2.ImageViewUsageCreateInfo' -- structure to the @pNext@ chain, but the view usage /must/ be a subset of -- the image usage. If @image@ has a depth-stencil format and was created -- with a -- 'Vulkan.Core12.Promoted_From_VK_EXT_separate_stencil_usage.ImageStencilUsageCreateInfo' -- structure included in the @pNext@ chain of -- 'Vulkan.Core10.Image.ImageCreateInfo', the usage is calculated based on -- the @subresource.aspectMask@ provided: -- -- - If @aspectMask@ includes only -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_STENCIL_BIT', -- the implicit @usage@ is equal to -- 'Vulkan.Core12.Promoted_From_VK_EXT_separate_stencil_usage.ImageStencilUsageCreateInfo'::@stencilUsage@. -- -- - If @aspectMask@ includes only -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_DEPTH_BIT', -- the implicit @usage@ is equal to -- 'Vulkan.Core10.Image.ImageCreateInfo'::@usage@. -- -- - If both aspects are included in @aspectMask@, the implicit @usage@ -- is equal to the intersection of -- 'Vulkan.Core10.Image.ImageCreateInfo'::@usage@ and -- 'Vulkan.Core12.Promoted_From_VK_EXT_separate_stencil_usage.ImageStencilUsageCreateInfo'::@stencilUsage@. -- -- If @image@ was created with the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_MUTABLE_FORMAT_BIT' -- flag, and if the @format@ of the image is not -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-requiring-sampler-ycbcr-conversion multi-planar>, -- @format@ /can/ be different from the image’s format, but if @image@ was -- created without the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT' -- flag and they are not equal they /must/ be /compatible/. Image format -- compatibility is defined in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-compatibility-classes Format Compatibility Classes> -- section. Views of compatible formats will have the same mapping between -- texel coordinates and memory locations irrespective of the @format@, -- with only the interpretation of the bit pattern changing. -- -- Note -- -- Values intended to be used with one view format /may/ not be exactly -- preserved when written or read through a different format. For example, -- an integer value that happens to have the bit pattern of a floating -- point denorm or NaN /may/ be flushed or canonicalized when written or -- read through a view with a floating point format. Similarly, a value -- written through a signed normalized format that has a bit pattern -- exactly equal to -2b /may/ be changed to -2b + 1 as described in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-fixedfpconv Conversion from Normalized Fixed-Point to Floating-Point>. -- -- If @image@ was created with the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT' -- flag, @format@ /must/ be /compatible/ with the image’s format as -- described above, or /must/ be an uncompressed format in which case it -- /must/ be /size-compatible/ with the image’s format, as defined for -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#copies-images-format-size-compatibility copying data between images>. -- In this case, the resulting image view’s texel dimensions equal the -- dimensions of the selected mip level divided by the compressed texel -- block size and rounded up. -- -- The 'ComponentMapping' @components@ member describes a remapping from -- components of the image to components of the vector returned by shader -- image instructions. This remapping /must/ be the identity swizzle for -- storage image descriptors, input attachment descriptors, framebuffer -- attachments, and any 'Vulkan.Core10.Handles.ImageView' used with a -- combined image sampler that enables -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#samplers-YCbCr-conversion sampler Y’CBCR conversion>. -- -- If the image view is to be used with a sampler which supports -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#samplers-YCbCr-conversion sampler Y′CBCR conversion>, -- an /identically defined object/ of type -- 'Vulkan.Core11.Handles.SamplerYcbcrConversion' to that used to create -- the sampler /must/ be passed to 'createImageView' in a -- 'Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion.SamplerYcbcrConversionInfo' -- included in the @pNext@ chain of 'ImageViewCreateInfo'. Conversely, if a -- 'Vulkan.Core11.Handles.SamplerYcbcrConversion' object is passed to -- 'createImageView', an identically defined -- 'Vulkan.Core11.Handles.SamplerYcbcrConversion' object /must/ be used -- when sampling the image. -- -- If the image has a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-requiring-sampler-ycbcr-conversion multi-planar> -- @format@ and @subresourceRange.aspectMask@ is -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_COLOR_BIT', then -- the @format@ /must/ be identical to the image @format@, and the sampler -- to be used with the image view /must/ enable -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#samplers-YCbCr-conversion sampler Y′CBCR conversion>. -- -- If @image@ was created with the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_MUTABLE_FORMAT_BIT' -- and the image has a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-requiring-sampler-ycbcr-conversion multi-planar> -- @format@, and if @subresourceRange.aspectMask@ is -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_0_BIT', -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_1_BIT', or -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_2_BIT', -- @format@ /must/ be -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-compatible-planes compatible> -- with the corresponding plane of the image, and the sampler to be used -- with the image view /must/ not enable -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#samplers-YCbCr-conversion sampler Y′CBCR conversion>. -- The @width@ and @height@ of the single-plane image view /must/ be -- derived from the multi-planar image’s dimensions in the manner listed -- for -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-compatible-planes plane compatibility> -- for the plane. -- -- Any view of an image plane will have the same mapping between texel -- coordinates and memory locations as used by the components of the color -- aspect, subject to the formulae relating texel coordinates to -- lower-resolution planes as described in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#textures-chroma-reconstruction Chroma Reconstruction>. -- That is, if an R or B plane has a reduced resolution relative to the G -- plane of the multi-planar image, the image view operates using the -- (/uplane/, /vplane/) unnormalized coordinates of the reduced-resolution -- plane, and these coordinates access the same memory locations as the -- (/ucolor/, /vcolor/) unnormalized coordinates of the color aspect for -- which chroma reconstruction operations operate on the same (/uplane/, -- /vplane/) or (/iplane/, /jplane/) coordinates. -- -- +----------------------------------------------------------------+-----------------------------------------------+ -- | Image View Type | Compatible Image Types | -- +================================================================+===============================================+ -- | 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_1D' | 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_1D' | -- +----------------------------------------------------------------+-----------------------------------------------+ -- | 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_1D_ARRAY' | 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_1D' | -- +----------------------------------------------------------------+-----------------------------------------------+ -- | 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' | 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_2D' | -- | | , | -- | | 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_3D' | -- +----------------------------------------------------------------+-----------------------------------------------+ -- | 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY' | 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_2D' | -- | | , | -- | | 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_3D' | -- +----------------------------------------------------------------+-----------------------------------------------+ -- | 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE' | 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_2D' | -- +----------------------------------------------------------------+-----------------------------------------------+ -- | 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE_ARRAY' | 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_2D' | -- +----------------------------------------------------------------+-----------------------------------------------+ -- | 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_3D' | 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_3D' | -- +----------------------------------------------------------------+-----------------------------------------------+ -- -- Image type and image view type compatibility requirements -- -- == Valid Usage -- -- - #VUID-VkImageViewCreateInfo-image-01003# If @image@ was not created -- with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_CUBE_COMPATIBLE_BIT' -- then @viewType@ /must/ not be -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE_ARRAY' -- -- - #VUID-VkImageViewCreateInfo-viewType-01004# If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-imageCubeArray image cube map arrays> -- feature is not enabled, @viewType@ /must/ not be -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE_ARRAY' -- -- - #VUID-VkImageViewCreateInfo-image-01005# If @image@ was created with -- 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_3D' but without -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT' -- set then @viewType@ /must/ not be -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY' -- -- - #VUID-VkImageViewCreateInfo-image-04970# If @image@ was created with -- 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_3D' and @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY' then -- @subresourceRange.levelCount@ /must/ be 1 -- -- - #VUID-VkImageViewCreateInfo-image-04971# If @image@ was created with -- 'Vulkan.Core10.Enums.ImageType.IMAGE_TYPE_3D' and @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY' then -- 'Vulkan.Core10.Image.ImageCreateInfo'::@flags@ /must/ not contain -- any of -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPARSE_BINDING_BIT', -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPARSE_RESIDENCY_BIT', -- and -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPARSE_ALIASED_BIT' -- -- - #VUID-VkImageViewCreateInfo-image-04972# If @image@ was created with -- a @samples@ value not equal to -- 'Vulkan.Core10.Enums.SampleCountFlagBits.SAMPLE_COUNT_1_BIT' then -- @viewType@ /must/ be either -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY' -- -- - #VUID-VkImageViewCreateInfo-image-04441# @image@ /must/ have been -- created with a @usage@ value containing at least one of the usages -- defined in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#valid-imageview-imageusage valid image usage> -- list for image views -- -- - #VUID-VkImageViewCreateInfo-None-02273# The -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-view-format-features format features> -- of the resultant image view /must/ contain at least one bit -- -- - #VUID-VkImageViewCreateInfo-usage-02274# If @usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_SAMPLED_BIT', -- then the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-view-format-features format features> -- of the resultant image view /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_SAMPLED_IMAGE_BIT' -- -- - #VUID-VkImageViewCreateInfo-usage-02275# If @usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_STORAGE_BIT', -- then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_STORAGE_IMAGE_BIT' -- -- - #VUID-VkImageViewCreateInfo-usage-02276# If @usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_COLOR_ATTACHMENT_BIT', -- then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_COLOR_ATTACHMENT_BIT' -- -- - #VUID-VkImageViewCreateInfo-usage-02277# If @usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT', -- then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT' -- -- - #VUID-VkImageViewCreateInfo-usage-06516# If @usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_COLOR_ATTACHMENT_BIT', -- then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FORMAT_FEATURE_2_LINEAR_COLOR_ATTACHMENT_BIT_NV', -- if the image is created with -- 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_LINEAR' and the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-linearColorAttachment linearColorAttachment> -- feature is enabled -- -- - #VUID-VkImageViewCreateInfo-usage-06517# If @usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_INPUT_ATTACHMENT_BIT', -- then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-view-format-features format features> -- must contain -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FORMAT_FEATURE_2_LINEAR_COLOR_ATTACHMENT_BIT_NV', -- if the image is created with -- 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_LINEAR' and the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-linearColorAttachment linearColorAttachment> -- feature is enabled -- -- - #VUID-VkImageViewCreateInfo-usage-02652# If @usage@ contains -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_INPUT_ATTACHMENT_BIT', -- then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain at least one of -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_COLOR_ATTACHMENT_BIT' -- or -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT' -- -- - #VUID-VkImageViewCreateInfo-subresourceRange-01478# -- @subresourceRange.baseMipLevel@ /must/ be less than the @mipLevels@ -- specified in 'Vulkan.Core10.Image.ImageCreateInfo' when @image@ was -- created -- -- - #VUID-VkImageViewCreateInfo-subresourceRange-01718# If -- @subresourceRange.levelCount@ is not -- 'Vulkan.Core10.APIConstants.REMAINING_MIP_LEVELS', -- @subresourceRange.baseMipLevel@ + @subresourceRange.levelCount@ -- /must/ be less than or equal to the @mipLevels@ specified in -- 'Vulkan.Core10.Image.ImageCreateInfo' when @image@ was created -- -- - #VUID-VkImageViewCreateInfo-image-02571# If @image@ was created with -- @usage@ containing -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT', -- @subresourceRange.levelCount@ /must/ be @1@ -- -- - #VUID-VkImageViewCreateInfo-image-01482# If @image@ is not a 3D -- image created with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT' -- set, or @viewType@ is not -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY', -- @subresourceRange.baseArrayLayer@ /must/ be less than the -- @arrayLayers@ specified in 'Vulkan.Core10.Image.ImageCreateInfo' -- when @image@ was created -- -- - #VUID-VkImageViewCreateInfo-subresourceRange-01483# If -- @subresourceRange.layerCount@ is not -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', @image@ is not -- a 3D image created with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT' -- set, or @viewType@ is not -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY', -- @subresourceRange.layerCount@ /must/ be non-zero and -- @subresourceRange.baseArrayLayer@ + @subresourceRange.layerCount@ -- /must/ be less than or equal to the @arrayLayers@ specified in -- 'Vulkan.Core10.Image.ImageCreateInfo' when @image@ was created -- -- - #VUID-VkImageViewCreateInfo-image-02724# If @image@ is a 3D image -- created with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT' -- set, and @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY', -- @subresourceRange.baseArrayLayer@ /must/ be less than the depth -- computed from @baseMipLevel@ and @extent.depth@ specified in -- 'Vulkan.Core10.Image.ImageCreateInfo' when @image@ was created, -- according to the formula defined in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-miplevel-sizing Image Miplevel Sizing> -- -- - #VUID-VkImageViewCreateInfo-subresourceRange-02725# If -- @subresourceRange.layerCount@ is not -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', @image@ is a 3D -- image created with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT' -- set, and @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY', -- @subresourceRange.layerCount@ /must/ be non-zero and -- @subresourceRange.baseArrayLayer@ + @subresourceRange.layerCount@ -- /must/ be less than or equal to the depth computed from -- @baseMipLevel@ and @extent.depth@ specified in -- 'Vulkan.Core10.Image.ImageCreateInfo' when @image@ was created, -- according to the formula defined in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-miplevel-sizing Image Miplevel Sizing> -- -- - #VUID-VkImageViewCreateInfo-image-01761# If @image@ was created with -- the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_MUTABLE_FORMAT_BIT' -- flag, but without the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT' -- flag, and if the @format@ of the @image@ is not a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-requiring-sampler-ycbcr-conversion multi-planar> -- format, @format@ /must/ be compatible with the @format@ used to -- create @image@, as defined in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-compatibility-classes Format Compatibility Classes> -- -- - #VUID-VkImageViewCreateInfo-image-01583# If @image@ was created with -- the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT' -- flag, @format@ /must/ be compatible with, or /must/ be an -- uncompressed format that is size-compatible with, the @format@ used -- to create @image@ -- -- - #VUID-VkImageViewCreateInfo-image-01584# If @image@ was created with -- the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT' -- flag, the @levelCount@ and @layerCount@ members of -- @subresourceRange@ /must/ both be @1@ -- -- - #VUID-VkImageViewCreateInfo-image-04739# If @image@ was created with -- the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT' -- flag and @format@ is a non-compressed format, @viewType@ /must/ not -- be 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_3D' -- -- - #VUID-VkImageViewCreateInfo-pNext-01585# If a -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo' -- structure was included in the @pNext@ chain of the -- 'Vulkan.Core10.Image.ImageCreateInfo' structure used when creating -- @image@ and -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo'::@viewFormatCount@ -- is not zero then @format@ /must/ be one of the formats in -- 'Vulkan.Core12.Promoted_From_VK_KHR_image_format_list.ImageFormatListCreateInfo'::@pViewFormats@ -- -- - #VUID-VkImageViewCreateInfo-image-01586# If @image@ was created with -- the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_MUTABLE_FORMAT_BIT' -- flag, if the @format@ of the @image@ is a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-requiring-sampler-ycbcr-conversion multi-planar> -- format, and if @subresourceRange.aspectMask@ is one of -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_0_BIT', -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_1_BIT', -- or -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_PLANE_2_BIT', -- then @format@ /must/ be compatible with the -- 'Vulkan.Core10.Enums.Format.Format' for the plane of the @image@ -- @format@ indicated by @subresourceRange.aspectMask@, as defined in -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-compatible-planes> -- -- - #VUID-VkImageViewCreateInfo-image-01762# If @image@ was not created -- with the -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_MUTABLE_FORMAT_BIT' -- flag, or if the @format@ of the @image@ is a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-requiring-sampler-ycbcr-conversion multi-planar> -- format and if @subresourceRange.aspectMask@ is -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_COLOR_BIT', -- @format@ /must/ be identical to the @format@ used to create @image@ -- -- - #VUID-VkImageViewCreateInfo-format-06415# If the image @format@ is -- one of the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-requiring-sampler-ycbcr-conversion formats that require a sampler Y’CBCR conversion>, -- then the @pNext@ chain /must/ include a -- 'Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion.SamplerYcbcrConversionInfo' -- structure with a conversion value other than -- 'Vulkan.Core10.APIConstants.NULL_HANDLE' -- -- - #VUID-VkImageViewCreateInfo-format-04714# If @format@ has a @_422@ -- or @_420@ suffix then @image@ /must/ have been created with a width -- that is a multiple of 2 -- -- - #VUID-VkImageViewCreateInfo-format-04715# If @format@ has a @_420@ -- suffix then @image@ /must/ have been created with a height that is a -- multiple of 2 -- -- - #VUID-VkImageViewCreateInfo-pNext-01970# If the @pNext@ chain -- includes a -- 'Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion.SamplerYcbcrConversionInfo' -- structure with a @conversion@ value other than -- 'Vulkan.Core10.APIConstants.NULL_HANDLE', all members of -- @components@ /must/ have the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-views-identity-mappings identity swizzle> -- -- - #VUID-VkImageViewCreateInfo-image-01020# If @image@ is non-sparse -- then it /must/ be bound completely and contiguously to a single -- 'Vulkan.Core10.Handles.DeviceMemory' object -- -- - #VUID-VkImageViewCreateInfo-subResourceRange-01021# @viewType@ -- /must/ be compatible with the type of @image@ as shown in the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-views-compatibility view type compatibility table> -- -- - #VUID-VkImageViewCreateInfo-image-02399# If @image@ has an -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-external-android-hardware-buffer-external-formats external format>, -- @format@ /must/ be 'Vulkan.Core10.Enums.Format.FORMAT_UNDEFINED' -- -- - #VUID-VkImageViewCreateInfo-image-02400# If @image@ has an -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-external-android-hardware-buffer-external-formats external format>, -- the @pNext@ chain /must/ include a -- 'Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion.SamplerYcbcrConversionInfo' -- structure with a @conversion@ object created with the same external -- format as @image@ -- -- - #VUID-VkImageViewCreateInfo-image-02401# If @image@ has an -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-external-android-hardware-buffer-external-formats external format>, -- all members of @components@ /must/ be the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-views-identity-mappings identity swizzle> -- -- - #VUID-VkImageViewCreateInfo-image-02086# If @image@ was created with -- @usage@ containing -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR', -- @viewType@ /must/ be -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY' -- -- - #VUID-VkImageViewCreateInfo-image-02087# If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-shadingRateImage shadingRateImage feature> -- is enabled, and If @image@ was created with @usage@ containing -- 'Vulkan.Extensions.VK_NV_shading_rate_image.IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV', -- @format@ /must/ be 'Vulkan.Core10.Enums.Format.FORMAT_R8_UINT' -- -- - #VUID-VkImageViewCreateInfo-usage-04550# If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-attachmentFragmentShadingRate attachmentFragmentShadingRate feature> -- is enabled, and the @usage@ for the image view includes -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR', -- then the image view’s -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-view-format-features format features> -- /must/ contain -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR' -- -- - #VUID-VkImageViewCreateInfo-usage-04551# If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-attachmentFragmentShadingRate attachmentFragmentShadingRate feature> -- is enabled, the @usage@ for the image view includes -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR', -- and -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-layeredShadingRateAttachments layeredShadingRateAttachments> -- is 'Vulkan.Core10.FundamentalTypes.FALSE', -- @subresourceRange.layerCount@ /must/ be @1@ -- -- - #VUID-VkImageViewCreateInfo-flags-02572# If -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-fragmentDensityMapDynamic dynamic fragment density map> -- feature is not enabled, @flags@ /must/ not contain -- 'Vulkan.Core10.Enums.ImageViewCreateFlagBits.IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT' -- -- - #VUID-VkImageViewCreateInfo-flags-03567# If -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-fragmentDensityMapDeferred deferred fragment density map> -- feature is not enabled, @flags@ /must/ not contain -- 'Vulkan.Core10.Enums.ImageViewCreateFlagBits.IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DEFERRED_BIT_EXT' -- -- - #VUID-VkImageViewCreateInfo-flags-03568# If @flags@ contains -- 'Vulkan.Core10.Enums.ImageViewCreateFlagBits.IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DEFERRED_BIT_EXT', -- @flags@ /must/ not contain -- 'Vulkan.Core10.Enums.ImageViewCreateFlagBits.IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT' -- -- - #VUID-VkImageViewCreateInfo-image-03569# If @image@ was created with -- @flags@ containing -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SUBSAMPLED_BIT_EXT' -- and @usage@ containing -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_SAMPLED_BIT', -- @subresourceRange.layerCount@ /must/ be less than or equal to -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-maxSubsampledArrayLayers ::maxSubsampledArrayLayers> -- -- - #VUID-VkImageViewCreateInfo-invocationMask-04993# If the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-invocationMask invocationMask feature> -- is enabled, and if @image@ was created with @usage@ containing -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_INVOCATION_MASK_BIT_HUAWEI', -- @format@ /must/ be 'Vulkan.Core10.Enums.Format.FORMAT_R8_UINT' -- -- - #VUID-VkImageViewCreateInfo-flags-04116# If @flags@ does not contain -- 'Vulkan.Core10.Enums.ImageViewCreateFlagBits.IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT' -- and @image@ was created with @usage@ containing -- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT', -- its @flags@ /must/ not contain any of -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_PROTECTED_BIT', -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPARSE_BINDING_BIT', -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPARSE_RESIDENCY_BIT', -- or -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SPARSE_ALIASED_BIT' -- -- - #VUID-VkImageViewCreateInfo-pNext-02662# If the @pNext@ chain -- includes a -- 'Vulkan.Core11.Promoted_From_VK_KHR_maintenance2.ImageViewUsageCreateInfo' -- structure, and @image@ was not created with a -- 'Vulkan.Core12.Promoted_From_VK_EXT_separate_stencil_usage.ImageStencilUsageCreateInfo' -- structure included in the @pNext@ chain of -- 'Vulkan.Core10.Image.ImageCreateInfo', its @usage@ member /must/ not -- include any bits that were not set in the @usage@ member of the -- 'Vulkan.Core10.Image.ImageCreateInfo' structure used to create -- @image@ -- -- - #VUID-VkImageViewCreateInfo-pNext-02663# If the @pNext@ chain -- includes a -- 'Vulkan.Core11.Promoted_From_VK_KHR_maintenance2.ImageViewUsageCreateInfo' -- structure, @image@ was created with a -- 'Vulkan.Core12.Promoted_From_VK_EXT_separate_stencil_usage.ImageStencilUsageCreateInfo' -- structure included in the @pNext@ chain of -- 'Vulkan.Core10.Image.ImageCreateInfo', and -- @subresourceRange.aspectMask@ includes -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_STENCIL_BIT', -- the @usage@ member of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_maintenance2.ImageViewUsageCreateInfo' -- structure /must/ not include any bits that were not set in the -- @usage@ member of the -- 'Vulkan.Core12.Promoted_From_VK_EXT_separate_stencil_usage.ImageStencilUsageCreateInfo' -- structure used to create @image@ -- -- - #VUID-VkImageViewCreateInfo-pNext-02664# If the @pNext@ chain -- includes a -- 'Vulkan.Core11.Promoted_From_VK_KHR_maintenance2.ImageViewUsageCreateInfo' -- structure, @image@ was created with a -- 'Vulkan.Core12.Promoted_From_VK_EXT_separate_stencil_usage.ImageStencilUsageCreateInfo' -- structure included in the @pNext@ chain of -- 'Vulkan.Core10.Image.ImageCreateInfo', and -- @subresourceRange.aspectMask@ includes bits other than -- 'Vulkan.Core10.Enums.ImageAspectFlagBits.IMAGE_ASPECT_STENCIL_BIT', -- the @usage@ member of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_maintenance2.ImageViewUsageCreateInfo' -- structure /must/ not include any bits that were not set in the -- @usage@ member of the 'Vulkan.Core10.Image.ImageCreateInfo' -- structure used to create @image@ -- -- - #VUID-VkImageViewCreateInfo-imageViewType-04973# If @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_1D', -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D', or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_3D'; and -- @subresourceRange.layerCount@ is not -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', then -- @subresourceRange.layerCount@ /must/ be 1 -- -- - #VUID-VkImageViewCreateInfo-imageViewType-04974# If @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_1D', -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D', or -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_3D'; and -- @subresourceRange.layerCount@ is -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', then the -- remaining number of layers /must/ be 1 -- -- - #VUID-VkImageViewCreateInfo-viewType-02960# If @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE' and -- @subresourceRange.layerCount@ is not -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', -- @subresourceRange.layerCount@ /must/ be @6@ -- -- - #VUID-VkImageViewCreateInfo-viewType-02961# If @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE_ARRAY' and -- @subresourceRange.layerCount@ is not -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', -- @subresourceRange.layerCount@ /must/ be a multiple of @6@ -- -- - #VUID-VkImageViewCreateInfo-viewType-02962# If @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE' and -- @subresourceRange.layerCount@ is -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', the remaining -- number of layers /must/ be @6@ -- -- - #VUID-VkImageViewCreateInfo-viewType-02963# If @viewType@ is -- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_CUBE_ARRAY' and -- @subresourceRange.layerCount@ is -- 'Vulkan.Core10.APIConstants.REMAINING_ARRAY_LAYERS', the remaining -- number of layers /must/ be a multiple of @6@ -- -- - #VUID-VkImageViewCreateInfo-imageViewFormatSwizzle-04465# If the -- @VK_KHR_portability_subset@ extension is enabled, and -- 'Vulkan.Extensions.VK_KHR_portability_subset.PhysicalDevicePortabilitySubsetFeaturesKHR'::@imageViewFormatSwizzle@ -- is 'Vulkan.Core10.FundamentalTypes.FALSE', all elements of -- @components@ /must/ have the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-views-identity-mappings identity swizzle> -- -- - #VUID-VkImageViewCreateInfo-imageViewFormatReinterpretation-04466# -- If the @VK_KHR_portability_subset@ extension is enabled, and -- 'Vulkan.Extensions.VK_KHR_portability_subset.PhysicalDevicePortabilitySubsetFeaturesKHR'::@imageViewFormatReinterpretation@ -- is 'Vulkan.Core10.FundamentalTypes.FALSE', the -- 'Vulkan.Core10.Enums.Format.Format' in @format@ /must/ not contain a -- different number of components, or a different number of bits in -- each component, than the format of the 'Vulkan.Core10.Handles.Image' -- in @image@ -- -- == Valid Usage (Implicit) -- -- - #VUID-VkImageViewCreateInfo-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO' -- -- - #VUID-VkImageViewCreateInfo-pNext-pNext# Each @pNext@ member of any -- structure (including this one) in the @pNext@ chain /must/ be either -- @NULL@ or a pointer to a valid instance of -- 'Vulkan.Extensions.VK_EXT_astc_decode_mode.ImageViewASTCDecodeModeEXT', -- 'Vulkan.Extensions.VK_EXT_image_view_min_lod.ImageViewMinLodCreateInfoEXT', -- 'Vulkan.Core11.Promoted_From_VK_KHR_maintenance2.ImageViewUsageCreateInfo', -- 'Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion.SamplerYcbcrConversionInfo', -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkVideoDecodeH264ProfileEXT VkVideoDecodeH264ProfileEXT>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkVideoDecodeH265ProfileEXT VkVideoDecodeH265ProfileEXT>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkVideoEncodeH264ProfileEXT VkVideoEncodeH264ProfileEXT>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkVideoEncodeH265ProfileEXT VkVideoEncodeH265ProfileEXT>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkVideoProfileKHR VkVideoProfileKHR>, -- or -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkVideoProfilesKHR VkVideoProfilesKHR> -- -- - #VUID-VkImageViewCreateInfo-sType-unique# The @sType@ value of each -- struct in the @pNext@ chain /must/ be unique -- -- - #VUID-VkImageViewCreateInfo-flags-parameter# @flags@ /must/ be a -- valid combination of -- 'Vulkan.Core10.Enums.ImageViewCreateFlagBits.ImageViewCreateFlagBits' -- values -- -- - #VUID-VkImageViewCreateInfo-image-parameter# @image@ /must/ be a -- valid 'Vulkan.Core10.Handles.Image' handle -- -- - #VUID-VkImageViewCreateInfo-viewType-parameter# @viewType@ /must/ be -- a valid 'Vulkan.Core10.Enums.ImageViewType.ImageViewType' value -- -- - #VUID-VkImageViewCreateInfo-format-parameter# @format@ /must/ be a -- valid 'Vulkan.Core10.Enums.Format.Format' value -- -- - #VUID-VkImageViewCreateInfo-components-parameter# @components@ -- /must/ be a valid 'ComponentMapping' structure -- -- - #VUID-VkImageViewCreateInfo-subresourceRange-parameter# -- @subresourceRange@ /must/ be a valid 'ImageSubresourceRange' -- structure -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'ComponentMapping', 'Vulkan.Core10.Enums.Format.Format', -- 'Vulkan.Core10.Handles.Image', 'ImageSubresourceRange', -- 'Vulkan.Core10.Enums.ImageViewCreateFlagBits.ImageViewCreateFlags', -- 'Vulkan.Core10.Enums.ImageViewType.ImageViewType', -- 'Vulkan.Core10.Enums.StructureType.StructureType', 'createImageView' data ImageViewCreateInfo (es :: [Type]) = ImageViewCreateInfo { -- | @pNext@ is @NULL@ or a pointer to a structure extending this structure. next :: Chain es , -- | @flags@ is a bitmask of -- 'Vulkan.Core10.Enums.ImageViewCreateFlagBits.ImageViewCreateFlagBits' -- describing additional parameters of the image view. flags :: ImageViewCreateFlags , -- | @image@ is a 'Vulkan.Core10.Handles.Image' on which the view will be -- created. image :: Image , -- | @viewType@ is a 'Vulkan.Core10.Enums.ImageViewType.ImageViewType' value -- specifying the type of the image view. viewType :: ImageViewType , -- | @format@ is a 'Vulkan.Core10.Enums.Format.Format' describing the format -- and type used to interpret texel blocks in the image. format :: Format , -- | @components@ is a 'ComponentMapping' structure specifying a remapping of -- color components (or of depth or stencil components after they have been -- converted into color components). components :: ComponentMapping , -- | @subresourceRange@ is a 'ImageSubresourceRange' structure selecting the -- set of mipmap levels and array layers to be accessible to the view. subresourceRange :: ImageSubresourceRange } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (ImageViewCreateInfo (es :: [Type])) #endif deriving instance Show (Chain es) => Show (ImageViewCreateInfo es) instance Extensible ImageViewCreateInfo where extensibleTypeName = "ImageViewCreateInfo" setNext ImageViewCreateInfo{..} next' = ImageViewCreateInfo{next = next', ..} getNext ImageViewCreateInfo{..} = next extends :: forall e b proxy. Typeable e => proxy e -> (Extends ImageViewCreateInfo e => b) -> Maybe b extends _ f | Just Refl <- eqT @e @ImageViewMinLodCreateInfoEXT = Just f | Just Refl <- eqT @e @ImageViewASTCDecodeModeEXT = Just f | Just Refl <- eqT @e @SamplerYcbcrConversionInfo = Just f | Just Refl <- eqT @e @ImageViewUsageCreateInfo = Just f | otherwise = Nothing instance (Extendss ImageViewCreateInfo es, PokeChain es) => ToCStruct (ImageViewCreateInfo es) where withCStruct x f = allocaBytes 80 $ \p -> pokeCStruct p x (f p) pokeCStruct p ImageViewCreateInfo{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO) pNext'' <- fmap castPtr . ContT $ withChain (next) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext'' lift $ poke ((p `plusPtr` 16 :: Ptr ImageViewCreateFlags)) (flags) lift $ poke ((p `plusPtr` 24 :: Ptr Image)) (image) lift $ poke ((p `plusPtr` 32 :: Ptr ImageViewType)) (viewType) lift $ poke ((p `plusPtr` 36 :: Ptr Format)) (format) lift $ poke ((p `plusPtr` 40 :: Ptr ComponentMapping)) (components) lift $ poke ((p `plusPtr` 56 :: Ptr ImageSubresourceRange)) (subresourceRange) lift $ f cStructSize = 80 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO) pNext' <- fmap castPtr . ContT $ withZeroChain @es lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext' lift $ poke ((p `plusPtr` 24 :: Ptr Image)) (zero) lift $ poke ((p `plusPtr` 32 :: Ptr ImageViewType)) (zero) lift $ poke ((p `plusPtr` 36 :: Ptr Format)) (zero) lift $ poke ((p `plusPtr` 40 :: Ptr ComponentMapping)) (zero) lift $ poke ((p `plusPtr` 56 :: Ptr ImageSubresourceRange)) (zero) lift $ f instance (Extendss ImageViewCreateInfo es, PeekChain es) => FromCStruct (ImageViewCreateInfo es) where peekCStruct p = do pNext <- peek @(Ptr ()) ((p `plusPtr` 8 :: Ptr (Ptr ()))) next <- peekChain (castPtr pNext) flags <- peek @ImageViewCreateFlags ((p `plusPtr` 16 :: Ptr ImageViewCreateFlags)) image <- peek @Image ((p `plusPtr` 24 :: Ptr Image)) viewType <- peek @ImageViewType ((p `plusPtr` 32 :: Ptr ImageViewType)) format <- peek @Format ((p `plusPtr` 36 :: Ptr Format)) components <- peekCStruct @ComponentMapping ((p `plusPtr` 40 :: Ptr ComponentMapping)) subresourceRange <- peekCStruct @ImageSubresourceRange ((p `plusPtr` 56 :: Ptr ImageSubresourceRange)) pure $ ImageViewCreateInfo next flags image viewType format components subresourceRange instance es ~ '[] => Zero (ImageViewCreateInfo es) where zero = ImageViewCreateInfo () zero zero zero zero zero zero
expipiplus1/vulkan
src/Vulkan/Core10/ImageView.hs
bsd-3-clause
70,221
0
17
10,264
5,597
3,491
2,106
-1
-1
{- CIS 194 HW 10 due Monday, 1 April -} module CIS194.HW10.AParser where import Control.Applicative import Data.Char -- A parser for a value of type a is a function which takes a String -- represnting the input to be parsed, and succeeds or fails; if it -- succeeds, it returns the parsed value along with the remainder of -- the input. newtype Parser a = Parser { runParser :: String -> Maybe (a, String) } -- For example, 'satisfy' takes a predicate on Char, and constructs a -- parser which succeeds only if it sees a Char that satisfies the -- predicate (which it then returns). If it encounters a Char that -- does not satisfy the predicate (or an empty input), it fails. satisfy :: (Char -> Bool) -> Parser Char satisfy p = Parser f where f [] = Nothing -- fail on the empty input f (x:xs) -- check if x satisfies the predicate -- if so, return x along with the remainder -- of the input (that is, xs) | p x = Just (x, xs) | otherwise = Nothing -- otherwise, fail -- Using satisfy, we can define the parser 'char c' which expects to -- see exactly the character c, and fails otherwise. char :: Char -> Parser Char char c = satisfy (== c) {- For example: *Parser> runParser (satisfy isUpper) "ABC" Just ('A',"BC") *Parser> runParser (satisfy isUpper) "abc" Nothing *Parser> runParser (char 'x') "xyz" Just ('x',"yz") -} -- For convenience, we've also provided a parser for positive -- integers. posInt :: Parser Integer posInt = Parser f where f xs | null ns = Nothing | otherwise = Just (read ns, rest) where (ns, rest) = span isDigit xs ------------------------------------------------------------ -- Your code goes below here ------------------------------------------------------------
sestrella/cis194
src/CIS194/HW10/AParser.hs
bsd-3-clause
1,849
0
10
449
252
141
111
18
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Types where import GHC.Generics import qualified Post as P import qualified Data.Text as T type Board = [Thread] type ThreadID = Int type Catalog = [Page] type BoardID = T.Text data Thread = Thread { posts :: [P.Post] } deriving (Show, Generic) data Page = Page { page :: Integer , threads :: [ThreadStub] } deriving (Show, Generic) data ThreadStub = ThreadStub { no :: ThreadID } deriving (Show, Generic) boards :: [BoardID] boards = ["a", "b","c","d","e","f","g","gif","h","hr","k","m","o","p","r","s","t","u","v","vg","vr","w","wg","i","ic","r9k","s4s","cm","hm","lgbt","y","3","aco","adv","an","asp","biz","cgl","ck","co","diy","fa","fit","gd","hc","his","int","jp","lit","mlp","mu","n","news","out","po","pol","sci","soc","sp","tg","toy","trv","tv","vp","wsg","x"] data Meme = Meme { alias :: [T.Text] } deriving (Show, Eq, Ord) memes :: [Meme] memes = map Meme [ ["haskell"], ["ocaml"], ["f#"], ["java"], ["c++"], ["c#", "cshart"], ["python"], ["pepe", "sad frog", "frogposter"], ["dank"], ["meme"], ["reddit"], ["epic"], ["trump"], ["rubio"], ["cruz"], ["carson"], ["hillary", "shillary"]]
k4smiley/Chan
src/Types.hs
bsd-3-clause
1,264
0
10
223
527
340
187
44
1
module Diophantine where import Data.Maybe data PQa = PQa {getP :: Int, getQ :: Int, geta :: Int} solvePQa :: Int -> Int -> Int -> ([PQa], [PQa]) -- assumption: q0 /= 0, D > 0, D /= k^2, p0^2 mod q0 = D mod q0 -- at j the 0-based position where second period starts so we need -- elements as position 0,1..(j-1) i.e. j elements solvePQa d p0 q0 = (uptoPeriodicPart, periodicPart) where periodicPart = drop ir uptoPeriodicPart uptoPeriodicPart = take j series d' = sqrt (fromIntegral d :: Double) getA p q = floor $ (fromIntegral p + d') / fromIntegral q -- x = (P + sqrt[D])/Q, x' = (P - sqrt[D])/Q is reduced if x > 1 and -1 < x' < 0 isReduced p q = p' + d' > q' && -q' < p' - d' && p' - d' < 0 where p' = fromIntegral p q' = fromIntegral q series = iterate (\(PQa p q a) -> let p' = a * q - p q' = (d - p' * p') `div` q a' = getA p' q' in PQa p' q' a' ) (PQa p0 q0 (getA p0 q0)) -- ir is the first 0-based position where (Pi + sqrt[D])/Qi is reduced (ir, PQa pir qir _) = head . filter ((\(PQa p q _) -> isReduced p q) . snd) . zip [0 ..] $ series -- j > ir is the 0-based positions where P(ir) = Pj and Q(ir) = Qj j = fst . head . filter ((\(PQa p q _) -> p == pir && q == qir) . snd) . drop (ir + 1) . zip [0 ..] $ series solveLMM :: Int -> Int -> [(Int, Int)] solveLMM d n = catMaybes $ concatMap solveF fs where -- solveLMM : fs ===================== fs = go [1 .. floor (sqrt . fromIntegral $ n :: Double)] where go [] = [] go (x : xs) = case n `quotRem` (x * x) of (m, 0) -> (x, m) : go xs _ -> go xs -- solveLMM : solveF ================== solveF (f, m) = map (getSolution f m . (\z -> solvePQa d z m')) -- find z so that -|m|/2 < z < |m|/2 and z^2 = D (mod |m|) $ filter (\z -> (z * z) `mod` m' == d `mod` m') [-m' `div` 2 .. m' `div` 2] where m' = abs m -- solveLMM : getSolution ============== getSolution f m (pqas, _) | -- if Qi = +-1 then we need G(i-1), B(i-1) v == m = Just (f * g, f * b) | v == -m = case getTU of (Just (t, u)) -> Just (f * (g * t + b * u * d), f * (g * u + b * t)) _ -> Nothing | otherwise = Nothing where -- i is the 0-based first position where Qi = +-1 i = fst . head . filter ((\q -> q == 1 || q == -1) . getQ . snd) . tail . zip [0 ..] $ pqas (g, b) = getGB (i - 1) pqas v = g * g - d * b * b -- solveLMM : getGB ==================== getGB k pqas = go (-p0, 1) (q0, 0) as !! k where p0 = getP . head $ pqas q0 = getQ . head $ pqas as = map geta pqas go _ _ [] = [] go (g, b) (g', b') (a : as') = let g'' = a * g' + g b'' = a * b' + b in (g'', b'') : go (g', b') (g'', b'') as' -- solveLMM : getTU =================== getTU = -- solving x^2-dy^2=-1, p0=0, q0=1, l is odd then G(l-1), B(l-1) let (pqas', pqasPeriodic') = solvePQa d 0 1 l = length pqasPeriodic' in if odd l then Just $ getGB (l - 1) (pqas' ++ pqasPeriodic') else Nothing
adityagupta1089/Project-Euler-Haskell
src/util/Diophantine.hs
bsd-3-clause
3,549
0
21
1,439
1,271
684
587
70
6
module Heed.Utils ( fork , fork_ , progName , Port , defPort , silentProc ) where import Control.Concurrent (ThreadId) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO, liftIO) import qualified SlaveThread as ST import qualified System.Process as Process -- | Lift 'ST.fork' to 'MonadIO' fork :: (MonadIO m) => IO a -> m ThreadId fork = liftIO . ST.fork -- | 'ST.fork' that ignores 'ThreadId' fork_ :: (MonadIO m) => IO a -- ^ Action -> m () fork_ = void . fork -- | Program name progName :: String progName = "heed" type Port = Int -- | Default port for server (assumes TLS so 443) defPort :: Port defPort = 443 -- | 'Process.CreateProcess' with all handles (in,out,err) closed -- we need this since vty doens't handle stdout well silentProc :: FilePath -> [String] -> Process.CreateProcess silentProc fp command = (Process.proc fp command) { Process.std_in = Process.NoStream , Process.std_out = Process.NoStream , Process.std_err = Process.NoStream }
Arguggi/heed
heed-lib/src/Heed/Utils.hs
bsd-3-clause
1,049
0
8
233
248
148
100
32
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveDataTypeable #-} module Render where import Control.Monad.State.Strict import qualified Data.Map.Strict as Map import Control.Lens hiding (view) import Graphics.UI.GLFW.Pal import Graphics.GL.Pal import Data.Maybe import Data.Data import Types data Uniforms = Uniforms { uViewProjection :: UniformLocation (M44 GLfloat) , uInverseModel :: UniformLocation (M44 GLfloat) , uModel :: UniformLocation (M44 GLfloat) , uCamLocation :: UniformLocation (V3 GLfloat) , uDiffuse :: UniformLocation (V4 GLfloat) } deriving (Data, Typeable) resX, resY :: Int resX=1024; resY=768 initRenderer :: IO (Window, Events, Shape Uniforms) initRenderer = do (window, events) <- createWindow "ReliableCubes" resX resY cubeProg <- createShaderProgram "reliable/poly.vert" "reliable/poly.frag" cubeGeo <- cubeGeometry (0.5 :: V3 GLfloat) (V3 1 1 1) cubeShape <- makeShape cubeGeo cubeProg glEnable GL_DEPTH_TEST glClearColor 0 0 0.1 1 glEnable GL_CULL_FACE glCullFace GL_BACK useProgram (sProgram cubeShape) return (window, events, cubeShape) renderFrame :: (MonadIO m, MonadState AppState m) => Window -> Shape Uniforms -> m () renderFrame window cube = do let Uniforms{..} = sUniforms cube glClear (GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT) projection <- getWindowProjection window 45 0.1 100 let playerPos = V3 0 0 5 playerOrient = axisAngle (V3 0 1 0) 0 view = viewMatrix playerPos playerOrient projectionView = projection !*! view uniformV3 uCamLocation playerPos newCubes <- use cubePoses newPlayers <- use playerPoses withVAO (sVAO cube) $ do forM_ (Map.toList newCubes) $ \(objID , pose) -> do let model = mkTransformation (pose ^. posOrientation) (pose ^. posPosition) color <- fromMaybe (V4 0 1 0 1) <$> use (cubeColors . at objID) drawShape' cube model projectionView color forM_ (Map.toList newPlayers) $ \(playerID , pose) -> do let model = mkTransformation (pose ^. posOrientation) (pose ^. posPosition) color <- fromMaybe (V4 0 1 0 1) <$> use (playerColors . at playerID) drawShape' cube model projectionView color swapBuffers window drawShape' :: MonadIO m => Shape Uniforms -> M44 GLfloat -> M44 GLfloat -> Color -> m () drawShape' shape model projectionView color = do let Uniforms{..} = sUniforms shape uniformM44 uViewProjection projectionView uniformM44 uInverseModel (fromMaybe model (inv44 model)) uniformM44 uModel model uniformV4 uDiffuse color let vc = geoVertCount (sGeometry shape) glDrawElements GL_TRIANGLES vc GL_UNSIGNED_INT nullPtr
lukexi/udp-pal
reliable/Render.hs
bsd-3-clause
2,823
0
19
640
898
440
458
65
1
{-# LANGUAGE TypeSynonymInstances #-} {- | Module : ./Maude/Meta/HasName.hs Description : Accessing the names of Maude data types Copyright : (c) Martin Kuehl, Uni Bremen 2008-2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : mkhl@informatik.uni-bremen.de Stability : experimental Portability : portable Accessing the names of Maude data types. Defines a type class 'HasName' that lets us access the names of Maude data types as 'Qid's. Consider importing "Maude.Meta" instead of this module. -} module Maude.Meta.HasName ( -- * The HasName type class HasName (..) ) where import Maude.AS_Maude -- * The HasName type class -- | Represents something that has a name (as a 'Qid'). class HasName a where -- | Extract the name of the input. getName :: a -> Qid -- | Map the name of the input. mapName :: (Qid -> Qid) -> a -> a -- * Predefined instances instance HasName Qid where getName = id mapName = id instance HasName Type where getName typ = case typ of TypeSort sort -> getName sort TypeKind kind -> getName kind mapName mp typ = case typ of TypeSort sort -> TypeSort $ mapName mp sort TypeKind kind -> TypeKind $ mapName mp kind instance HasName Sort where getName (SortId name) = name mapName mp (SortId name) = SortId $ mp name instance HasName Kind where getName (KindId name) = name mapName mp (KindId name) = KindId $ mp name instance HasName ParamId where getName (ParamId name) = name mapName mp (ParamId name) = ParamId $ mp name instance HasName ModId where getName (ModId name) = name mapName mp (ModId name) = ModId $ mp name instance HasName ViewId where getName (ViewId name) = name mapName mp (ViewId name) = ViewId $ mp name instance HasName LabelId where getName (LabelId name) = name mapName mp (LabelId name) = LabelId $ mp name instance HasName OpId where getName (OpId name) = name mapName mp (OpId name) = OpId $ mp name instance HasName Operator where getName (Op name _ _ _) = getName name mapName mp (Op name dom cod as) = Op (mapName mp name) dom cod as instance HasName Module where getName (Module name _ _) = getName name mapName mp (Module name ps ss) = Module (mapName mp name) ps ss instance HasName View where getName (View name _ _ _) = getName name mapName mp (View name from to rnms) = View (mapName mp name) from to rnms instance HasName Spec where getName spec = case spec of SpecMod modul -> getName modul SpecTh theory -> getName theory SpecView view -> getName view mapName mp spec = case spec of SpecMod modul -> SpecMod $ mapName mp modul SpecTh theory -> SpecTh $ mapName mp theory SpecView view -> SpecView $ mapName mp view
spechub/Hets
Maude/Meta/HasName.hs
gpl-2.0
2,835
0
10
711
822
404
418
56
0
{- Problem 38: Pandigital multiples Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? -} module Problem38 where import Pandigital (isPandigital) joinProducts xs = read (concat $ map show xs) :: Integer candidate x = head $ dropWhile tooSmall (concatenatedProducts x) where tooSmall p = p <= 123456789 concatenatedProducts x = [f x n | n<-[2..10^5]] f x n = joinProducts [x * m | m<-[1..n]] pandigitals = filter isPandigital $ map candidate [1..10^5] solve = foldr1 max pandigitals
ajsmith/project-euler-solutions
src/Problem38.hs
gpl-2.0
1,030
0
11
220
178
92
86
9
1
module Common ( agentOut , agentOutObservable , isDead , kill , newAgent , isObservable , sugObservableFromState , BestCellMeasureFunc , selectBestCells , bestCellFunc , bestMeasureSugarLevel , unoccupiedNeighbourhoodOfNeighbours , randomAgent , cellOccupier ) where import Control.Concurrent.STM import Control.Monad.Random import qualified FRP.BearRiver as BR import Data.Maybe import Data.List import Discrete import Model ------------------------------------------------------------------------------------------------------------------------ -- GENERAL FUNCTIONS, independent of monadic / non-monadic implementation ------------------------------------------------------------------------------------------------------------------------ agentOut :: SugAgentOut g agentOut = agentOutAux Nothing agentOutObservable :: SugAgentObservable -> SugAgentOut g agentOutObservable o = agentOutAux $ Just o agentOutAux :: Maybe SugAgentObservable -> SugAgentOut g agentOutAux mo = SugAgentOut { sugAoKill = BR.NoEvent , sugAoNew = [] , sugAoObservable = mo } isDead :: SugAgentOut g -> Bool isDead ao = BR.isEvent $ sugAoKill ao kill :: SugAgentOut g -> SugAgentOut g kill ao = ao { sugAoKill = BR.Event () } newAgent :: AgentId -> SugAgent g -> SugAgentOut g -> SugAgentOut g newAgent aid a ao = ao { sugAoNew = (aid, a) : sugAoNew ao } isObservable :: SugAgentOut g -> Bool isObservable ao = isJust $ sugAoObservable ao sugObservableFromState :: SugAgentState -> SugAgentObservable sugObservableFromState s = SugAgentObservable { sugObsCoord = sugAgCoord s , sugObsVision = sugAgVision s } type BestCellMeasureFunc = (SugEnvCell -> Double) bestCellFunc :: BestCellMeasureFunc bestCellFunc = bestMeasureSugarLevel selectBestCells :: BestCellMeasureFunc -> Discrete2dCoord -> [(Discrete2dCoord, SugEnvCell)] -> [(Discrete2dCoord, SugEnvCell)] selectBestCells measureFunc refCoord cs = bestShortestdistanceManhattanCells where cellsSortedByMeasure = sortBy (\c1 c2 -> compare (measureFunc $ snd c2) (measureFunc $ snd c1)) cs bestCellMeasure = measureFunc $ snd $ head cellsSortedByMeasure bestCells = filter ((==bestCellMeasure) . measureFunc . snd) cellsSortedByMeasure shortestdistanceManhattanBestCells = sortBy (\c1 c2 -> compare (distanceManhattanDisc2d refCoord (fst c1)) (distanceManhattanDisc2d refCoord (fst c2))) bestCells shortestdistanceManhattan = distanceManhattanDisc2d refCoord (fst $ head shortestdistanceManhattanBestCells) bestShortestdistanceManhattanCells = filter ((==shortestdistanceManhattan) . (distanceManhattanDisc2d refCoord) . fst) shortestdistanceManhattanBestCells unoccupiedNeighbourhoodOfNeighbours :: Discrete2dCoord -> SugEnvironment -> STM [(Discrete2dCoord, SugEnvCell)] unoccupiedNeighbourhoodOfNeighbours coord e = do ncs <- neighbours coord False e -- NOTE: this calculates the cells which are in the initial neighbourhood and in the neighbourhood of all the neighbours nncsDupl <- foldM (\acc (coord', _) -> do ncs' <- neighbours coord' False e return $ ncs' ++ acc) ncs ncs -- NOTE: the nncs are not unique, remove duplicates let nncsUnique = nubBy (\(coord1, _) (coord2, _) -> (coord1 == coord2)) nncsDupl return $ filter (isNothing . sugEnvOccupier . snd) nncsUnique bestMeasureSugarLevel :: BestCellMeasureFunc bestMeasureSugarLevel = sugEnvSugarLevel ------------------------------------------------------------------------------------------------------------------------ -- UTILS ------------------------------------------------------------------------------------------------------------------------ cellOccupier :: AgentId -> SugAgentState -> SugEnvCellOccupier cellOccupier aid s = SugEnvCellOccupier { sugEnvOccId = aid , sugEnvOccWealth = sugAgSugarLevel s } randomAgent :: (MonadRandom m, MonadSplit g m, RandomGen g) => (AgentId, Discrete2dCoord) -> (AgentId -> SugAgentState -> SugAgent g) -> (SugAgentState -> SugAgentState) -> m (SugAgent g, SugAgentState) randomAgent (agentId, coord) beh sup = do -- NOTE: need to split here otherwise agents would end up with the same random-values when not already splitting in the calling function _rng <- getSplit randSugarMetab <- getRandomR sugarMetabolismRange randVision <- getRandomR visionRange randSugarEndowment <- getRandomR sugarEndowmentRange let s = SugAgentState { sugAgCoord = coord , sugAgSugarMetab = randSugarMetab , sugAgVision = randVision , sugAgSugarLevel = randSugarEndowment , sugAgSugarInit = randSugarEndowment } let s' = sup s let abeh = beh agentId s' return (abeh, s')
thalerjonathan/phd
thesis/code/concurrent/sugarscape/SugarScapeSTMTArray/src/Common.hs
gpl-3.0
5,192
0
14
1,233
1,068
573
495
99
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.DirectConnect.CreateConnection -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Creates a new connection between the customer network and a specific AWS -- Direct Connect location. -- -- A connection links your internal network to an AWS Direct Connect location -- over a standard 1 gigabit or 10 gigabit Ethernet fiber-optic cable. One end -- of the cable is connected to your router, the other to an AWS Direct Connect -- router. An AWS Direct Connect location provides access to Amazon Web Services -- in the region it is associated with. You can establish connections with AWS -- Direct Connect locations in multiple regions, but a connection in one region -- does not provide connectivity to other regions. -- -- <http://docs.aws.amazon.com/directconnect/latest/APIReference/API_CreateConnection.html> module Network.AWS.DirectConnect.CreateConnection ( -- * Request CreateConnection -- ** Request constructor , createConnection -- ** Request lenses , ccBandwidth , ccConnectionName , ccLocation -- * Response , CreateConnectionResponse -- ** Response constructor , createConnectionResponse -- ** Response lenses , ccrBandwidth , ccrConnectionId , ccrConnectionName , ccrConnectionState , ccrLocation , ccrOwnerAccount , ccrPartnerName , ccrRegion , ccrVlan ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.DirectConnect.Types import qualified GHC.Exts data CreateConnection = CreateConnection { _ccBandwidth :: Text , _ccConnectionName :: Text , _ccLocation :: Text } deriving (Eq, Ord, Read, Show) -- | 'CreateConnection' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ccBandwidth' @::@ 'Text' -- -- * 'ccConnectionName' @::@ 'Text' -- -- * 'ccLocation' @::@ 'Text' -- createConnection :: Text -- ^ 'ccLocation' -> Text -- ^ 'ccBandwidth' -> Text -- ^ 'ccConnectionName' -> CreateConnection createConnection p1 p2 p3 = CreateConnection { _ccLocation = p1 , _ccBandwidth = p2 , _ccConnectionName = p3 } ccBandwidth :: Lens' CreateConnection Text ccBandwidth = lens _ccBandwidth (\s a -> s { _ccBandwidth = a }) ccConnectionName :: Lens' CreateConnection Text ccConnectionName = lens _ccConnectionName (\s a -> s { _ccConnectionName = a }) ccLocation :: Lens' CreateConnection Text ccLocation = lens _ccLocation (\s a -> s { _ccLocation = a }) data CreateConnectionResponse = CreateConnectionResponse { _ccrBandwidth :: Maybe Text , _ccrConnectionId :: Maybe Text , _ccrConnectionName :: Maybe Text , _ccrConnectionState :: Maybe ConnectionState , _ccrLocation :: Maybe Text , _ccrOwnerAccount :: Maybe Text , _ccrPartnerName :: Maybe Text , _ccrRegion :: Maybe Text , _ccrVlan :: Maybe Int } deriving (Eq, Read, Show) -- | 'CreateConnectionResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ccrBandwidth' @::@ 'Maybe' 'Text' -- -- * 'ccrConnectionId' @::@ 'Maybe' 'Text' -- -- * 'ccrConnectionName' @::@ 'Maybe' 'Text' -- -- * 'ccrConnectionState' @::@ 'Maybe' 'ConnectionState' -- -- * 'ccrLocation' @::@ 'Maybe' 'Text' -- -- * 'ccrOwnerAccount' @::@ 'Maybe' 'Text' -- -- * 'ccrPartnerName' @::@ 'Maybe' 'Text' -- -- * 'ccrRegion' @::@ 'Maybe' 'Text' -- -- * 'ccrVlan' @::@ 'Maybe' 'Int' -- createConnectionResponse :: CreateConnectionResponse createConnectionResponse = CreateConnectionResponse { _ccrOwnerAccount = Nothing , _ccrConnectionId = Nothing , _ccrConnectionName = Nothing , _ccrConnectionState = Nothing , _ccrRegion = Nothing , _ccrLocation = Nothing , _ccrBandwidth = Nothing , _ccrVlan = Nothing , _ccrPartnerName = Nothing } -- | Bandwidth of the connection. -- -- Example: 1Gbps (for regular connections), or 500Mbps (for hosted connections) -- -- Default: None ccrBandwidth :: Lens' CreateConnectionResponse (Maybe Text) ccrBandwidth = lens _ccrBandwidth (\s a -> s { _ccrBandwidth = a }) ccrConnectionId :: Lens' CreateConnectionResponse (Maybe Text) ccrConnectionId = lens _ccrConnectionId (\s a -> s { _ccrConnectionId = a }) ccrConnectionName :: Lens' CreateConnectionResponse (Maybe Text) ccrConnectionName = lens _ccrConnectionName (\s a -> s { _ccrConnectionName = a }) ccrConnectionState :: Lens' CreateConnectionResponse (Maybe ConnectionState) ccrConnectionState = lens _ccrConnectionState (\s a -> s { _ccrConnectionState = a }) ccrLocation :: Lens' CreateConnectionResponse (Maybe Text) ccrLocation = lens _ccrLocation (\s a -> s { _ccrLocation = a }) ccrOwnerAccount :: Lens' CreateConnectionResponse (Maybe Text) ccrOwnerAccount = lens _ccrOwnerAccount (\s a -> s { _ccrOwnerAccount = a }) ccrPartnerName :: Lens' CreateConnectionResponse (Maybe Text) ccrPartnerName = lens _ccrPartnerName (\s a -> s { _ccrPartnerName = a }) ccrRegion :: Lens' CreateConnectionResponse (Maybe Text) ccrRegion = lens _ccrRegion (\s a -> s { _ccrRegion = a }) ccrVlan :: Lens' CreateConnectionResponse (Maybe Int) ccrVlan = lens _ccrVlan (\s a -> s { _ccrVlan = a }) instance ToPath CreateConnection where toPath = const "/" instance ToQuery CreateConnection where toQuery = const mempty instance ToHeaders CreateConnection instance ToJSON CreateConnection where toJSON CreateConnection{..} = object [ "location" .= _ccLocation , "bandwidth" .= _ccBandwidth , "connectionName" .= _ccConnectionName ] instance AWSRequest CreateConnection where type Sv CreateConnection = DirectConnect type Rs CreateConnection = CreateConnectionResponse request = post "CreateConnection" response = jsonResponse instance FromJSON CreateConnectionResponse where parseJSON = withObject "CreateConnectionResponse" $ \o -> CreateConnectionResponse <$> o .:? "bandwidth" <*> o .:? "connectionId" <*> o .:? "connectionName" <*> o .:? "connectionState" <*> o .:? "location" <*> o .:? "ownerAccount" <*> o .:? "partnerName" <*> o .:? "region" <*> o .:? "vlan"
kim/amazonka
amazonka-directconnect/gen/Network/AWS/DirectConnect/CreateConnection.hs
mpl-2.0
7,326
0
25
1,642
1,171
691
480
120
1
{- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} program = drawingOf(redWheel) redWheel = colored(wheel, reds) wheel = solidCircle(4)
alphalambda/codeworld
codeworld-compiler/test/testcases/misspelledBuiltin/source.hs
apache-2.0
699
0
6
129
38
21
17
3
1
-- This is a quick hack for uploading packages to Hackage. -- See http://hackage.haskell.org/trac/hackage/wiki/CabalUpload module Distribution.Client.Upload (check, upload, uploadDoc, report) where import Distribution.Client.Types ( Username(..), Password(..) , Repo(..), RemoteRepo(..), maybeRepoRemote ) import Distribution.Client.HttpUtils ( HttpTransport(..), remoteRepoTryUpgradeToHttps ) import Distribution.Simple.Utils (notice, warn, info, die) import Distribution.Verbosity (Verbosity) import Distribution.Text (display) import Distribution.Client.Config import qualified Distribution.Client.BuildReports.Anonymous as BuildReport import qualified Distribution.Client.BuildReports.Upload as BuildReport import Network.URI (URI(uriPath), parseURI) import Network.HTTP (Header(..), HeaderName(..)) import System.IO (hFlush, stdin, stdout, hGetEcho, hSetEcho) import Control.Exception (bracket) import System.FilePath ((</>), takeExtension, takeFileName) import qualified System.FilePath.Posix as FilePath.Posix ((</>)) import System.Directory import Control.Monad (forM_, when) import Data.Maybe (catMaybes) type Auth = Maybe (String, String) checkURI :: URI Just checkURI = parseURI $ "http://hackage.haskell.org/cgi-bin/" ++ "hackage-scripts/check-pkg" upload :: HttpTransport -> Verbosity -> [Repo] -> Maybe Username -> Maybe Password -> [FilePath] -> IO () upload transport verbosity repos mUsername mPassword paths = do targetRepo <- case [ remoteRepo | Just remoteRepo <- map maybeRepoRemote repos ] of [] -> die "Cannot upload. No remote repositories are configured." rs -> remoteRepoTryUpgradeToHttps transport (last rs) let targetRepoURI = remoteRepoURI targetRepo rootIfEmpty x = if null x then "/" else x uploadURI = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> "upload" } Username username <- maybe promptUsername return mUsername Password password <- maybe promptPassword return mPassword let auth = Just (username,password) forM_ paths $ \path -> do notice verbosity $ "Uploading " ++ path ++ "... " handlePackage transport verbosity uploadURI auth path uploadDoc :: HttpTransport -> Verbosity -> [Repo] -> Maybe Username -> Maybe Password -> FilePath -> IO () uploadDoc transport verbosity repos mUsername mPassword path = do targetRepo <- case [ remoteRepo | Just remoteRepo <- map maybeRepoRemote repos ] of [] -> die $ "Cannot upload. No remote repositories are configured." rs -> remoteRepoTryUpgradeToHttps transport (last rs) let targetRepoURI = remoteRepoURI targetRepo rootIfEmpty x = if null x then "/" else x uploadURI = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> "package/" ++ pkgid ++ "/docs" } (reverseSuffix, reversePkgid) = break (== '-') (reverse (takeFileName path)) pkgid = reverse $ tail reversePkgid when (reverse reverseSuffix /= "docs.tar.gz" || null reversePkgid || head reversePkgid /= '-') $ die "Expected a file name matching the pattern <pkgid>-docs.tar.gz" Username username <- maybe promptUsername return mUsername Password password <- maybe promptPassword return mPassword let auth = Just (username,password) headers = [ Header HdrContentType "application/x-tar" , Header HdrContentEncoding "gzip" ] notice verbosity $ "Uploading documentation " ++ path ++ "... " resp <- putHttpFile transport verbosity uploadURI path auth headers case resp of (200,_) -> notice verbosity "Ok" (code,err) -> notice verbosity $ "Error uploading documentation " ++ path ++ ": " ++ "http code " ++ show code ++ "\n" ++ err promptUsername :: IO Username promptUsername = do putStr "Hackage username: " hFlush stdout fmap Username getLine promptPassword :: IO Password promptPassword = do putStr "Hackage password: " hFlush stdout -- save/restore the terminal echoing status passwd <- bracket (hGetEcho stdin) (hSetEcho stdin) $ \_ -> do hSetEcho stdin False -- no echoing for entering the password fmap Password getLine putStrLn "" return passwd report :: Verbosity -> [Repo] -> Maybe Username -> Maybe Password -> IO () report verbosity repos mUsername mPassword = do Username username <- maybe promptUsername return mUsername Password password <- maybe promptPassword return mPassword let auth = (username,password) let remoteRepos = catMaybes (map maybeRepoRemote repos) forM_ remoteRepos $ \remoteRepo -> do dotCabal <- defaultCabalDir let srcDir = dotCabal </> "reports" </> remoteRepoName remoteRepo -- We don't want to bomb out just because we haven't built any packages -- from this repo yet. srcExists <- doesDirectoryExist srcDir when srcExists $ do contents <- getDirectoryContents srcDir forM_ (filter (\c -> takeExtension c ==".log") contents) $ \logFile -> do inp <- readFile (srcDir </> logFile) let (reportStr, buildLog) = read inp :: (String,String) case BuildReport.parse reportStr of Left errs -> warn verbosity $ "Errors: " ++ errs -- FIXME Right report' -> do info verbosity $ "Uploading report for " ++ display (BuildReport.package report') BuildReport.uploadReports verbosity auth (remoteRepoURI remoteRepo) [(report', Just buildLog)] return () check :: HttpTransport -> Verbosity -> [FilePath] -> IO () check transport verbosity paths = forM_ paths $ \path -> do notice verbosity $ "Checking " ++ path ++ "... " handlePackage transport verbosity checkURI Nothing path handlePackage :: HttpTransport -> Verbosity -> URI -> Auth -> FilePath -> IO () handlePackage transport verbosity uri auth path = do resp <- postHttpFile transport verbosity uri path auth case resp of (200,_) -> notice verbosity "Ok" (code,err) -> notice verbosity $ "Error uploading " ++ path ++ ": " ++ "http code " ++ show code ++ "\n" ++ err
randen/cabal
cabal-install/Distribution/Client/Upload.hs
bsd-3-clause
6,674
0
27
1,806
1,771
899
872
127
4
import Testsuite import Data.Array.Parallel.Unlifted $(testcases [ "" <@ [t| ( (), Char, Bool, Int ) |] , "acc" <@ [t| ( (), Int ) |] , "num" <@ [t| ( Int ) |] , "ord" <@ [t| ( (), Char, Bool, Int ) |] , "enum" <@ [t| ( (), Char, Bool, Int ) |] ] [d| -- if this doesn't work nothing else will, so run this first prop_fromU_toU :: (Eq a, UA a) => [a] -> Bool prop_fromU_toU xs = fromU (toU xs) == xs prop_lengthU :: UA a => UArr a -> Bool prop_lengthU arr = lengthU arr == length (fromU arr) prop_nullU :: UA a => UArr a -> Bool prop_nullU arr = nullU arr == (lengthU arr == 0) prop_emptyU :: (Eq a, UA a) => a -> Bool prop_emptyU x = fromU emptyU == tail [x] prop_unitsU :: Len -> Bool prop_unitsU (Len n) = fromU (unitsU n) == replicate n () prop_replicateU :: (Eq a, UA a) => Len -> a -> Bool prop_replicateU (Len n) x = fromU (replicateU n x) == replicate n x prop_indexU :: (Eq a, UA a) => UArr a -> Len -> Property prop_indexU arr (Len i) = i < lengthU arr ==> (arr !: i) == (fromU arr !! i) prop_appendU :: (Eq a, UA a) => UArr a -> UArr a -> Bool prop_appendU arr brr = fromU (arr +:+ brr) == fromU arr ++ fromU brr -- Equality -- -------- prop_eqU_1 :: (Eq a, UA a) => UArr a -> Bool prop_eqU_1 arr = arr == arr prop_eqU_2 :: (Eq a, UA a) => UArr a -> UArr a -> Bool prop_eqU_2 arr brr = (arr == brr) == (fromU arr == fromU brr) |])
mainland/dph
dph-test/old/Unlifted_Basics.hs
bsd-3-clause
1,539
0
9
489
82
56
26
-1
-1
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[PrimOp]{Primitive operations (machine-level)} -} {-# LANGUAGE CPP #-} module PrimOp ( PrimOp(..), PrimOpVecCat(..), allThePrimOps, primOpType, primOpSig, primOpTag, maxPrimOpTag, primOpOcc, tagToEnumKey, primOpOutOfLine, primOpCodeSize, primOpOkForSpeculation, primOpOkForSideEffects, primOpIsCheap, primOpFixity, getPrimOpResultInfo, PrimOpResultInfo(..), PrimCall(..) ) where #include "HsVersions.h" import TysPrim import TysWiredIn import CmmType import Demand import OccName ( OccName, pprOccName, mkVarOccFS ) import TyCon ( TyCon, isPrimTyCon, PrimRep(..) ) import Type import BasicTypes ( Arity, Fixity(..), FixityDirection(..), Boxity(..) ) import ForeignCall ( CLabelString ) import Unique ( Unique, mkPrimOpIdUnique ) import Outputable import FastString import Module ( UnitId ) {- ************************************************************************ * * \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)} * * ************************************************************************ These are in \tr{state-interface.verb} order. -} -- supplies: -- data PrimOp = ... #include "primop-data-decl.hs-incl" -- supplies -- primOpTag :: PrimOp -> Int #include "primop-tag.hs-incl" primOpTag _ = error "primOpTag: unknown primop" instance Eq PrimOp where op1 == op2 = primOpTag op1 == primOpTag op2 instance Ord PrimOp where op1 < op2 = primOpTag op1 < primOpTag op2 op1 <= op2 = primOpTag op1 <= primOpTag op2 op1 >= op2 = primOpTag op1 >= primOpTag op2 op1 > op2 = primOpTag op1 > primOpTag op2 op1 `compare` op2 | op1 < op2 = LT | op1 == op2 = EQ | otherwise = GT instance Outputable PrimOp where ppr op = pprPrimOp op data PrimOpVecCat = IntVec | WordVec | FloatVec -- An @Enum@-derived list would be better; meanwhile... (ToDo) allThePrimOps :: [PrimOp] allThePrimOps = #include "primop-list.hs-incl" tagToEnumKey :: Unique tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp) {- ************************************************************************ * * \subsection[PrimOp-info]{The essential info about each @PrimOp@} * * ************************************************************************ The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may refer to the primitive operation. The conventional \tr{#}-for- unboxed ops is added on later. The reason for the funny characters in the names is so we do not interfere with the programmer's Haskell name spaces. We use @PrimKinds@ for the ``type'' information, because they're (slightly) more convenient to use than @TyCons@. -} data PrimOpInfo = Dyadic OccName -- string :: T -> T -> T Type | Monadic OccName -- string :: T -> T Type | Compare OccName -- string :: T -> T -> Int# Type | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T [TyVar] [Type] Type mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo mkDyadic str ty = Dyadic (mkVarOccFS str) ty mkMonadic str ty = Monadic (mkVarOccFS str) ty mkCompare str ty = Compare (mkVarOccFS str) ty mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty {- ************************************************************************ * * \subsubsection{Strictness} * * ************************************************************************ Not all primops are strict! -} primOpStrictness :: PrimOp -> Arity -> StrictSig -- See Demand.StrictnessInfo for discussion of what the results -- The arity should be the arity of the primop; that's why -- this function isn't exported. #include "primop-strictness.hs-incl" {- ************************************************************************ * * \subsubsection{Fixity} * * ************************************************************************ -} primOpFixity :: PrimOp -> Maybe Fixity #include "primop-fixity.hs-incl" {- ************************************************************************ * * \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops} * * ************************************************************************ @primOpInfo@ gives all essential information (from which everything else, notably a type, can be constructed) for each @PrimOp@. -} primOpInfo :: PrimOp -> PrimOpInfo #include "primop-primop-info.hs-incl" primOpInfo _ = error "primOpInfo: unknown primop" {- Here are a load of comments from the old primOp info: A @Word#@ is an unsigned @Int#@. @decodeFloat#@ is given w/ Integer-stuff (it's similar). @decodeDouble#@ is given w/ Integer-stuff (it's similar). Decoding of floating-point numbers is sorta Integer-related. Encoding is done with plain ccalls now (see PrelNumExtra.hs). A @Weak@ Pointer is created by the @mkWeak#@ primitive: mkWeak# :: k -> v -> f -> State# RealWorld -> (# State# RealWorld, Weak# v #) In practice, you'll use the higher-level data Weak v = Weak# v mkWeak :: k -> v -> IO () -> IO (Weak v) The following operation dereferences a weak pointer. The weak pointer may have been finalized, so the operation returns a result code which must be inspected before looking at the dereferenced value. deRefWeak# :: Weak# v -> State# RealWorld -> (# State# RealWorld, v, Int# #) Only look at v if the Int# returned is /= 0 !! The higher-level op is deRefWeak :: Weak v -> IO (Maybe v) Weak pointers can be finalized early by using the finalize# operation: finalizeWeak# :: Weak# v -> State# RealWorld -> (# State# RealWorld, Int#, IO () #) The Int# returned is either 0 if the weak pointer has already been finalized, or it has no finalizer (the third component is then invalid). 1 if the weak pointer is still alive, with the finalizer returned as the third component. A {\em stable name/pointer} is an index into a table of stable name entries. Since the garbage collector is told about stable pointers, it is safe to pass a stable pointer to external systems such as C routines. \begin{verbatim} makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #) freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #) eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int# \end{verbatim} It may seem a bit surprising that @makeStablePtr#@ is a @IO@ operation since it doesn't (directly) involve IO operations. The reason is that if some optimisation pass decided to duplicate calls to @makeStablePtr#@ and we only pass one of the stable pointers over, a massive space leak can result. Putting it into the IO monad prevents this. (Another reason for putting them in a monad is to ensure correct sequencing wrt the side-effecting @freeStablePtr@ operation.) An important property of stable pointers is that if you call makeStablePtr# twice on the same object you get the same stable pointer back. Note that we can implement @freeStablePtr#@ using @_ccall_@ (and, besides, it's not likely to be used from Haskell) so it's not a primop. Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR] Stable Names ~~~~~~~~~~~~ A stable name is like a stable pointer, but with three important differences: (a) You can't deRef one to get back to the original object. (b) You can convert one to an Int. (c) You don't need to 'freeStableName' The existence of a stable name doesn't guarantee to keep the object it points to alive (unlike a stable pointer), hence (a). Invariants: (a) makeStableName always returns the same value for a given object (same as stable pointers). (b) if two stable names are equal, it implies that the objects from which they were created were the same. (c) stableNameToInt always returns the same Int for a given stable name. These primops are pretty weird. dataToTag# :: a -> Int (arg must be an evaluated data type) tagToEnum# :: Int -> a (result type must be an enumerated type) The constraints aren't currently checked by the front end, but the code generator will fall over if they aren't satisfied. ************************************************************************ * * Which PrimOps are out-of-line * * ************************************************************************ Some PrimOps need to be called out-of-line because they either need to perform a heap check or they block. -} primOpOutOfLine :: PrimOp -> Bool #include "primop-out-of-line.hs-incl" {- ************************************************************************ * * Failure and side effects * * ************************************************************************ Note [PrimOp can_fail and has_side_effects] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Both can_fail and has_side_effects mean that the primop has some effect that is not captured entirely by its result value. ---------- has_side_effects --------------------- A primop "has_side_effects" if it has some *write* effect, visible elsewhere - writing to the world (I/O) - writing to a mutable data structure (writeIORef) - throwing a synchronous Haskell exception Often such primops have a type like State -> input -> (State, output) so the state token guarantees ordering. In general we rely *only* on data dependencies of the state token to enforce write-effect ordering * NB1: if you inline unsafePerformIO, you may end up with side-effecting ops whose 'state' output is discarded. And programmers may do that by hand; see Trac #9390. That is why we (conservatively) do not discard write-effecting primops even if both their state and result is discarded. * NB2: We consider primops, such as raiseIO#, that can raise a (Haskell) synchronous exception to "have_side_effects" but not "can_fail". We must be careful about not discarding such things; see the paper "A semantics for imprecise exceptions". * NB3: *Read* effects (like reading an IORef) don't count here, because it doesn't matter if we don't do them, or do them more than once. *Sequencing* is maintained by the data dependency of the state token. ---------- can_fail ---------------------------- A primop "can_fail" if it can fail with an *unchecked* exception on some elements of its input domain. Main examples: division (fails on zero demoninator) array indexing (fails if the index is out of bounds) An "unchecked exception" is one that is an outright error, (not turned into a Haskell exception,) such as seg-fault or divide-by-zero error. Such can_fail primops are ALWAYS surrounded with a test that checks for the bad cases, but we need to be very careful about code motion that might move it out of the scope of the test. Note [Transformations affected by can_fail and has_side_effects] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The can_fail and has_side_effects properties have the following effect on program transformations. Summary table is followed by details. can_fail has_side_effects Discard NO NO Float in YES YES Float out NO NO Duplicate YES NO * Discarding. case (a `op` b) of _ -> rhs ===> rhs You should not discard a has_side_effects primop; e.g. case (writeIntArray# a i v s of (# _, _ #) -> True Arguably you should be able to discard this, since the returned stat token is not used, but that relies on NEVER inlining unsafePerformIO, and programmers sometimes write this kind of stuff by hand (Trac #9390). So we (conservatively) never discard a has_side_effects primop. However, it's fine to discard a can_fail primop. For example case (indexIntArray# a i) of _ -> True We can discard indexIntArray#; it has can_fail, but not has_side_effects; see Trac #5658 which was all about this. Notice that indexIntArray# is (in a more general handling of effects) read effect, but we don't care about that here, and treat read effects as *not* has_side_effects. Similarly (a `/#` b) can be discarded. It can seg-fault or cause a hardware exception, but not a synchronous Haskell exception. Synchronous Haskell exceptions, e.g. from raiseIO#, are treated as has_side_effects and hence are not discarded. * Float in. You can float a can_fail or has_side_effects primop *inwards*, but not inside a lambda (see Duplication below). * Float out. You must not float a can_fail primop *outwards* lest you escape the dynamic scope of the test. Example: case d ># 0# of True -> case x /# d of r -> r +# 1 False -> 0 Here we must not float the case outwards to give case x/# d of r -> case d ># 0# of True -> r +# 1 False -> 0 Nor can you float out a has_side_effects primop. For example: if blah then case writeMutVar# v True s0 of (# s1 #) -> s1 else s0 Notice that s0 is mentioned in both branches of the 'if', but only one of these two will actually be consumed. But if we float out to case writeMutVar# v True s0 of (# s1 #) -> if blah then s1 else s0 the writeMutVar will be performed in both branches, which is utterly wrong. * Duplication. You cannot duplicate a has_side_effect primop. You might wonder how this can occur given the state token threading, but just look at Control.Monad.ST.Lazy.Imp.strictToLazy! We get something like this p = case readMutVar# s v of (# s', r #) -> (S# s', r) s' = case p of (s', r) -> s' r = case p of (s', r) -> r (All these bindings are boxed.) If we inline p at its two call sites, we get a catastrophe: because the read is performed once when s' is demanded, and once when 'r' is demanded, which may be much later. Utterly wrong. Trac #3207 is real example of this happening. However, it's fine to duplicate a can_fail primop. That is really the only difference between can_fail and has_side_effects. Note [Implementation: how can_fail/has_side_effects affect transformations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How do we ensure that that floating/duplication/discarding are done right in the simplifier? Two main predicates on primpops test these flags: primOpOkForSideEffects <=> not has_side_effects primOpOkForSpeculation <=> not (has_side_effects || can_fail) * The "no-float-out" thing is achieved by ensuring that we never let-bind a can_fail or has_side_effects primop. The RHS of a let-binding (which can float in and out freely) satisfies exprOkForSpeculation; this is the let/app invariant. And exprOkForSpeculation is false of can_fail and has_side_effects. * So can_fail and has_side_effects primops will appear only as the scrutinees of cases, and that's why the FloatIn pass is capable of floating case bindings inwards. * The no-duplicate thing is done via primOpIsCheap, by making has_side_effects things (very very very) not-cheap! -} primOpHasSideEffects :: PrimOp -> Bool #include "primop-has-side-effects.hs-incl" primOpCanFail :: PrimOp -> Bool #include "primop-can-fail.hs-incl" primOpOkForSpeculation :: PrimOp -> Bool -- See Note [PrimOp can_fail and has_side_effects] -- See comments with CoreUtils.exprOkForSpeculation -- primOpOkForSpeculation => primOpOkForSideEffects primOpOkForSpeculation op = primOpOkForSideEffects op && not (primOpOutOfLine op || primOpCanFail op) -- I think the "out of line" test is because out of line things can -- be expensive (eg sine, cosine), and so we may not want to speculate them primOpOkForSideEffects :: PrimOp -> Bool primOpOkForSideEffects op = not (primOpHasSideEffects op) {- Note [primOpIsCheap] ~~~~~~~~~~~~~~~~~~~~ @primOpIsCheap@, as used in \tr{SimplUtils.hs}. For now (HACK WARNING), we just borrow some other predicates for a what-should-be-good-enough test. "Cheap" means willing to call it more than once, and/or push it inside a lambda. The latter could change the behaviour of 'seq' for primops that can fail, so we don't treat them as cheap. -} primOpIsCheap :: PrimOp -> Bool -- See Note [PrimOp can_fail and has_side_effects] primOpIsCheap op = primOpOkForSpeculation op -- In March 2001, we changed this to -- primOpIsCheap op = False -- thereby making *no* primops seem cheap. But this killed eta -- expansion on case (x ==# y) of True -> \s -> ... -- which is bad. In particular a loop like -- doLoop n = loop 0 -- where -- loop i | i == n = return () -- | otherwise = bar i >> loop (i+1) -- allocated a closure every time round because it doesn't eta expand. -- -- The problem that originally gave rise to the change was -- let x = a +# b *# c in x +# x -- were we don't want to inline x. But primopIsCheap doesn't control -- that (it's exprIsDupable that does) so the problem doesn't occur -- even if primOpIsCheap sometimes says 'True'. {- ************************************************************************ * * PrimOp code size * * ************************************************************************ primOpCodeSize ~~~~~~~~~~~~~~ Gives an indication of the code size of a primop, for the purposes of calculating unfolding sizes; see CoreUnfold.sizeExpr. -} primOpCodeSize :: PrimOp -> Int #include "primop-code-size.hs-incl" primOpCodeSizeDefault :: Int primOpCodeSizeDefault = 1 -- CoreUnfold.primOpSize already takes into account primOpOutOfLine -- and adds some further costs for the args in that case. primOpCodeSizeForeignCall :: Int primOpCodeSizeForeignCall = 4 {- ************************************************************************ * * PrimOp types * * ************************************************************************ -} primOpType :: PrimOp -> Type -- you may want to use primOpSig instead primOpType op = case primOpInfo op of Dyadic _occ ty -> dyadic_fun_ty ty Monadic _occ ty -> monadic_fun_ty ty Compare _occ ty -> compare_fun_ty ty GenPrimOp _occ tyvars arg_tys res_ty -> mkSpecForAllTys tyvars (mkFunTys arg_tys res_ty) primOpOcc :: PrimOp -> OccName primOpOcc op = case primOpInfo op of Dyadic occ _ -> occ Monadic occ _ -> occ Compare occ _ -> occ GenPrimOp occ _ _ _ -> occ -- primOpSig is like primOpType but gives the result split apart: -- (type variables, argument types, result type) -- It also gives arity, strictness info primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig) primOpSig op = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity) where arity = length arg_tys (tyvars, arg_tys, res_ty) = case (primOpInfo op) of Monadic _occ ty -> ([], [ty], ty ) Dyadic _occ ty -> ([], [ty,ty], ty ) Compare _occ ty -> ([], [ty,ty], intPrimTy) GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty ) data PrimOpResultInfo = ReturnsPrim PrimRep | ReturnsAlg TyCon -- Some PrimOps need not return a manifest primitive or algebraic value -- (i.e. they might return a polymorphic value). These PrimOps *must* -- be out of line, or the code generator won't work. getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo getPrimOpResultInfo op = case (primOpInfo op) of Dyadic _ ty -> ReturnsPrim (typePrimRep ty) Monadic _ ty -> ReturnsPrim (typePrimRep ty) Compare _ _ -> ReturnsPrim (tyConPrimRep intPrimTyCon) GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc) | otherwise -> ReturnsAlg tc where tc = tyConAppTyCon ty -- All primops return a tycon-app result -- The tycon can be an unboxed tuple, though, which -- gives rise to a ReturnAlg {- We do not currently make use of whether primops are commutable. We used to try to move constants to the right hand side for strength reduction. -} {- commutableOp :: PrimOp -> Bool #include "primop-commutable.hs-incl" -} -- Utils: dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type dyadic_fun_ty ty = mkFunTys [ty, ty] ty monadic_fun_ty ty = mkFunTy ty ty compare_fun_ty ty = mkFunTys [ty, ty] intPrimTy -- Output stuff: pprPrimOp :: PrimOp -> SDoc pprPrimOp other_op = pprOccName (primOpOcc other_op) {- ************************************************************************ * * \subsubsection[PrimCall]{User-imported primitive calls} * * ************************************************************************ -} data PrimCall = PrimCall CLabelString UnitId instance Outputable PrimCall where ppr (PrimCall lbl pkgId) = text "__primcall" <+> ppr pkgId <+> ppr lbl
mcschroeder/ghc
compiler/prelude/PrimOp.hs
bsd-3-clause
23,094
0
11
6,237
1,525
838
687
-1
-1
import Distribution.Simple import System.Cmd main = defaultMainWithHooks simpleUserHooks { preConf = \args confFlags -> do system "./build-parser.sh" preConf simpleUserHooks args confFlags }
artuuge/IHaskell
ghc-parser/Setup.hs
mit
243
0
11
74
50
25
25
6
1
{-# LANGUAGE CPP , DataKinds , FlexibleInstances , FlexibleContexts , KindSignatures , OverloadedStrings , UndecidableInstances #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} module Language.Hakaru.Syntax.Gensym where #if __GLASGOW_HASKELL__ < 710 import Data.Functor ((<$>)) #endif import Control.Monad.State import Data.Number.Nat import Language.Hakaru.Syntax.ABT import Language.Hakaru.Syntax.AST import Language.Hakaru.Syntax.TypeOf import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing class Monad m => Gensym m where freshVarId :: m Nat instance (Monad m, MonadState Nat m) => Gensym m where freshVarId = do vid <- gets succ put vid return vid freshVar :: (Functor m, Gensym m) => Variable (a :: Hakaru) -> m (Variable a) freshVar v = fmap (\n -> v{varID=n}) freshVarId varOfType :: (Functor m, Gensym m) => Sing (a :: Hakaru) -> m (Variable a) varOfType t = fmap (\n -> Variable "" n t) freshVarId varForExpr :: (Functor m, Gensym m, ABT Term abt) => abt '[] a -> m (Variable a) varForExpr v = fmap (\n -> Variable "" n (typeOf v)) freshVarId
zachsully/hakaru
haskell/Language/Hakaru/Syntax/Gensym.hs
bsd-3-clause
1,219
0
10
311
372
202
170
36
1
{-# LANGUAGE Unsafe #-} {-# LANGUAGE MagicHash, UnboxedTuples, RankNTypes #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.ST.Lazy.Imp -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : non-portable (requires universal quantification for runST) -- -- This module presents an identical interface to "Control.Monad.ST", -- except that the monad delays evaluation of state operations until -- a value depending on them is required. -- ----------------------------------------------------------------------------- module Control.Monad.ST.Lazy.Imp ( -- * The 'ST' monad ST, runST, fixST, -- * Converting between strict and lazy 'ST' strictToLazyST, lazyToStrictST, -- * Converting 'ST' To 'IO' RealWorld, stToIO, -- * Unsafe operations unsafeInterleaveST, unsafeIOToST ) where import Control.Monad.Fix import qualified Control.Monad.ST as ST import qualified Control.Monad.ST.Unsafe as ST import qualified GHC.ST as GHC.ST import GHC.Base -- | The lazy state-transformer monad. -- A computation of type @'ST' s a@ transforms an internal state indexed -- by @s@, and returns a value of type @a@. -- The @s@ parameter is either -- -- * an unstantiated type variable (inside invocations of 'runST'), or -- -- * 'RealWorld' (inside invocations of 'stToIO'). -- -- It serves to keep the internal states of different invocations of -- 'runST' separate from each other and from invocations of 'stToIO'. -- -- The '>>=' and '>>' operations are not strict in the state. For example, -- -- @'runST' (writeSTRef _|_ v >>= readSTRef _|_ >> return 2) = 2@ newtype ST s a = ST (State s -> (a, State s)) data State s = S# (State# s) instance Functor (ST s) where fmap f m = ST $ \ s -> let ST m_a = m (r,new_s) = m_a s in (f r,new_s) instance Applicative (ST s) where pure a = ST $ \ s -> (a,s) (<*>) = ap instance Monad (ST s) where fail s = error s (ST m) >>= k = ST $ \ s -> let (r,new_s) = m s ST k_a = k r in k_a new_s {-# NOINLINE runST #-} -- | Return the value computed by a state transformer computation. -- The @forall@ ensures that the internal state used by the 'ST' -- computation is inaccessible to the rest of the program. runST :: (forall s. ST s a) -> a runST st = case st of ST the_st -> let (r,_) = the_st (S# realWorld#) in r -- | Allow the result of a state transformer computation to be used (lazily) -- inside the computation. -- Note that if @f@ is strict, @'fixST' f = _|_@. fixST :: (a -> ST s a) -> ST s a fixST m = ST (\ s -> let ST m_r = m r (r,s') = m_r s in (r,s')) instance MonadFix (ST s) where mfix = fixST -- --------------------------------------------------------------------------- -- Strict <--> Lazy {-| Convert a strict 'ST' computation into a lazy one. The strict state thread passed to 'strictToLazyST' is not performed until the result of the lazy state thread it returns is demanded. -} strictToLazyST :: ST.ST s a -> ST s a strictToLazyST m = ST $ \s -> let pr = case s of { S# s# -> GHC.ST.liftST m s# } r = case pr of { GHC.ST.STret _ v -> v } s' = case pr of { GHC.ST.STret s2# _ -> S# s2# } in (r, s') {-| Convert a lazy 'ST' computation into a strict one. -} lazyToStrictST :: ST s a -> ST.ST s a lazyToStrictST (ST m) = GHC.ST.ST $ \s -> case (m (S# s)) of (a, S# s') -> (# s', a #) -- | A monad transformer embedding lazy state transformers in the 'IO' -- monad. The 'RealWorld' parameter indicates that the internal state -- used by the 'ST' computation is a special one supplied by the 'IO' -- monad, and thus distinct from those used by invocations of 'runST'. stToIO :: ST RealWorld a -> IO a stToIO = ST.stToIO . lazyToStrictST -- --------------------------------------------------------------------------- -- Strict <--> Lazy unsafeInterleaveST :: ST s a -> ST s a unsafeInterleaveST = strictToLazyST . ST.unsafeInterleaveST . lazyToStrictST unsafeIOToST :: IO a -> ST s a unsafeIOToST = strictToLazyST . ST.unsafeIOToST
AlexanderPankiv/ghc
libraries/base/Control/Monad/ST/Lazy/Imp.hs
bsd-3-clause
4,544
0
15
1,156
857
481
376
63
1
module Idris.REPLParser (parseCmd, help, allHelp, setOptions) where import System.FilePath ((</>)) import System.Console.ANSI (Color(..)) import Idris.Colours import Idris.AbsSyntax import Idris.Core.TT import Idris.Help import qualified Idris.Parser as P import Control.Applicative import Control.Monad.State.Strict import Text.Parser.Combinators import Text.Parser.Char(anyChar,oneOf) import Text.Trifecta(Result, parseString) import Text.Trifecta.Delta import Debug.Trace import Data.List import Data.List.Split(splitOn) import Data.Char(isSpace, toLower) import qualified Data.ByteString.UTF8 as UTF8 parseCmd :: IState -> String -> String -> Result (Either String Command) parseCmd i inputname = P.runparser pCmd i inputname . trim where trim = f . f where f = reverse . dropWhile isSpace type CommandTable = [ ( [String], CmdArg, String , String -> P.IdrisParser (Either String Command) ) ] setOptions :: [(String, Opt)] setOptions = [("errorcontext", ErrContext), ("showimplicits", ShowImpl), ("originalerrors", ShowOrigErr), ("autosolve", AutoSolve), ("nobanner", NoBanner), ("warnreach", WarnReach), ("evaltypes", EvalTypes), ("desugarnats", DesugarNats)] help :: [([String], CmdArg, String)] help = (["<expr>"], NoArg, "Evaluate an expression") : [ (map (':' :) names, args, text) | (names, args, text, _) <- parserCommandsForHelp ] allHelp :: [([String], CmdArg, String)] allHelp = [ (map (':' :) names, args, text) | (names, args, text, _) <- parserCommandsForHelp ++ parserCommands ] parserCommandsForHelp :: CommandTable parserCommandsForHelp = [ exprArgCmd ["t", "type"] Check "Check the type of an expression" , exprArgCmd ["core"] Core "View the core language representation of a term" , nameArgCmd ["miss", "missing"] Missing "Show missing clauses" , (["doc"], NameArg, "Show internal documentation", cmd_doc) , (["mkdoc"], NamespaceArg, "Generate IdrisDoc for namespace(s) and dependencies" , genArg "namespace" (many anyChar) MakeDoc) , (["apropos"], SeqArgs (OptionalArg PkgArgs) NameArg, " Search names, types, and documentation" , cmd_apropos) , (["s", "search"], SeqArgs (OptionalArg PkgArgs) ExprArg , " Search for values by type", cmd_search) , nameArgCmd ["wc", "whocalls"] WhoCalls "List the callers of some name" , nameArgCmd ["cw", "callswho"] CallsWho "List the callees of some name" , namespaceArgCmd ["browse"] Browse "List the contents of some namespace" , nameArgCmd ["total"] TotCheck "Check the totality of a name" , noArgCmd ["r", "reload"] Reload "Reload current file" , (["l", "load"], FileArg, "Load a new file" , strArg (\f -> Load f Nothing)) , (["cd"], FileArg, "Change working directory" , strArg ChangeDirectory) , (["module"], ModuleArg, "Import an extra module", moduleArg ModImport) -- NOTE: dragons , noArgCmd ["e", "edit"] Edit "Edit current file using $EDITOR or $VISUAL" , noArgCmd ["m", "metavars"] Metavars "Show remaining proof obligations (metavariables or holes)" , (["p", "prove"], MetaVarArg, "Prove a metavariable" , nameArg (Prove False)) , (["elab"], MetaVarArg, "Build a metavariable using the elaboration shell" , nameArg (Prove True)) , (["a", "addproof"], NameArg, "Add proof to source file", cmd_addproof) , (["rmproof"], NameArg, "Remove proof from proof stack" , nameArg RmProof) , (["showproof"], NameArg, "Show proof" , nameArg ShowProof) , noArgCmd ["proofs"] Proofs "Show available proofs" , exprArgCmd ["x"] ExecVal "Execute IO actions resulting from an expression using the interpreter" , (["c", "compile"], FileArg, "Compile to an executable [codegen] <filename>", cmd_compile) , (["exec", "execute"], OptionalArg ExprArg, "Compile to an executable and run", cmd_execute) , (["dynamic"], FileArg, "Dynamically load a C library (similar to %dynamic)", cmd_dynamic) , (["dynamic"], NoArg, "List dynamically loaded C libraries", cmd_dynamic) , noArgCmd ["?", "h", "help"] Help "Display this help text" , optArgCmd ["set"] SetOpt $ "Set an option (" ++ optionsList ++ ")" , optArgCmd ["unset"] UnsetOpt "Unset an option" , (["color", "colour"], ColourArg , "Turn REPL colours on or off; set a specific colour" , cmd_colour) , (["consolewidth"], ConsoleWidthArg, "Set the width of the console", cmd_consolewidth) , (["printerdepth"], OptionalArg NumberArg, "Set the maximum pretty-printer depth (no arg for infinite)", cmd_printdepth) , noArgCmd ["q", "quit"] Quit "Exit the Idris system" , noArgCmd ["w", "warranty"] Warranty "Displays warranty information" , (["let"], ManyArgs DeclArg , "Evaluate a declaration, such as a function definition, instance implementation, or fixity declaration" , cmd_let) , (["unlet", "undefine"], ManyArgs NameArg , "Remove the listed repl definitions, or all repl definitions if no names given" , cmd_unlet) , nameArgCmd ["printdef"] PrintDef "Show the definition of a function" , (["pp", "pprint"], (SeqArgs OptionArg (SeqArgs NumberArg NameArg)) , "Pretty prints an Idris function in either LaTeX or HTML and for a specified width." , cmd_pprint) ] where optionsList = intercalate ", " $ map fst setOptions parserCommands = [ noArgCmd ["u", "universes"] Universes "Display universe constraints" , noArgCmd ["errorhandlers"] ListErrorHandlers "List registered error handlers" , nameArgCmd ["d", "def"] Defn "Display a name's internal definitions" , nameArgCmd ["transinfo"] TransformInfo "Show relevant transformation rules for a name" , nameArgCmd ["di", "dbginfo"] DebugInfo "Show debugging information for a name" , exprArgCmd ["patt"] Pattelab "(Debugging) Elaborate pattern expression" , exprArgCmd ["spec"] Spec "?" , exprArgCmd ["whnf"] WHNF "(Debugging) Show weak head normal form of an expression" , exprArgCmd ["inline"] TestInline "?" , proofArgCmd ["cs", "casesplit"] CaseSplitAt ":cs <line> <name> splits the pattern variable on the line" , proofArgCmd ["apc", "addproofclause"] AddProofClauseFrom ":apc <line> <name> adds a pattern-matching proof clause to name on line" , proofArgCmd ["ac", "addclause"] AddClauseFrom ":ac <line> <name> adds a clause for the definition of the name on the line" , proofArgCmd ["am", "addmissing"] AddMissing ":am <line> <name> adds all missing pattern matches for the name on the line" , proofArgCmd ["mw", "makewith"] MakeWith ":mw <line> <name> adds a with clause for the definition of the name on the line" , proofArgCmd ["mc", "makecase"] MakeCase ":mc <line> <name> adds a case block for the definition of the metavariable on the line" , proofArgCmd ["ml", "makelemma"] MakeLemma "?" , (["log"], NumberArg, "Set logging verbosity level", cmd_log) , (["lto", "loadto"], SeqArgs NumberArg FileArg , "Load file up to line number", cmd_loadto) , (["ps", "proofsearch"], NoArg , ":ps <line> <name> <names> does proof search for name on line, with names as hints" , cmd_proofsearch) , (["ref", "refine"], NoArg , ":ref <line> <name> <name'> attempts to partially solve name on line, with name' as hint, introducing metavariables for arguments that aren't inferrable" , cmd_refine) , (["debugunify"], SeqArgs ExprArg ExprArg , "(Debugging) Try to unify two expressions", const $ do l <- P.simpleExpr defaultSyntax r <- P.simpleExpr defaultSyntax eof return (Right (DebugUnify l r)) ) ] noArgCmd names command doc = (names, NoArg, doc, noArgs command) nameArgCmd names command doc = (names, NameArg, doc, fnNameArg command) namespaceArgCmd names command doc = (names, NamespaceArg, doc, namespaceArg command) exprArgCmd names command doc = (names, ExprArg, doc, exprArg command) metavarArgCmd names command doc = (names, MetaVarArg, doc, fnNameArg command) optArgCmd names command doc = (names, OptionArg, doc, optArg command) proofArgCmd names command doc = (names, NoArg, doc, proofArg command) pCmd :: P.IdrisParser (Either String Command) pCmd = choice [ do c <- cmd names; parser c | (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ] <|> unrecognized <|> nop <|> eval where nop = do eof; return (Right NOP) unrecognized = do P.lchar ':' cmd <- many anyChar let cmd' = takeWhile (/=' ') cmd return (Left $ "Unrecognized command: " ++ cmd') cmd :: [String] -> P.IdrisParser String cmd xs = try $ do P.lchar ':' docmd sorted_xs where docmd [] = fail "Could not parse command" docmd (x:xs) = try (P.reserved x >> return x) <|> docmd xs sorted_xs = sortBy (\x y -> compare (length y) (length x)) xs noArgs :: Command -> String -> P.IdrisParser (Either String Command) noArgs cmd name = do let emptyArgs = do eof return (Right cmd) let failure = return (Left $ ":" ++ name ++ " takes no arguments") emptyArgs <|> failure eval :: P.IdrisParser (Either String Command) eval = do t <- P.fullExpr defaultSyntax return $ Right (Eval t) exprArg :: (PTerm -> Command) -> String -> P.IdrisParser (Either String Command) exprArg cmd name = do let noArg = do eof return $ Left ("Usage is :" ++ name ++ " <expression>") let justOperator = do (op, fc) <- P.operatorFC eof return $ Right $ cmd (PRef fc [] (sUN op)) let properArg = do t <- P.fullExpr defaultSyntax return $ Right (cmd t) try noArg <|> try justOperator <|> properArg genArg :: String -> P.IdrisParser a -> (a -> Command) -> String -> P.IdrisParser (Either String Command) genArg argName argParser cmd name = do let emptyArgs = do eof; failure oneArg = do arg <- argParser eof return (Right (cmd arg)) try emptyArgs <|> oneArg <|> failure where failure = return $ Left ("Usage is :" ++ name ++ " <" ++ argName ++ ">") nameArg, fnNameArg :: (Name -> Command) -> String -> P.IdrisParser (Either String Command) nameArg = genArg "name" $ fst <$> P.name fnNameArg = genArg "functionname" $ fst <$> P.fnName strArg :: (String -> Command) -> String -> P.IdrisParser (Either String Command) strArg = genArg "string" (many anyChar) moduleArg :: (FilePath -> Command) -> String -> P.IdrisParser (Either String Command) moduleArg = genArg "module" (fmap (toPath . fst) P.identifier) where toPath n = foldl1' (</>) $ splitOn "." n namespaceArg :: ([String] -> Command) -> String -> P.IdrisParser (Either String Command) namespaceArg = genArg "namespace" (fmap (toNS . fst) P.identifier) where toNS = splitOn "." optArg :: (Opt -> Command) -> String -> P.IdrisParser (Either String Command) optArg cmd name = do let emptyArgs = do eof return $ Left ("Usage is :" ++ name ++ " <option>") let oneArg = do o <- pOption P.whiteSpace eof return (Right (cmd o)) let failure = return $ Left "Unrecognized setting" try emptyArgs <|> oneArg <|> failure where pOption :: P.IdrisParser Opt pOption = foldl (<|>) empty $ map (\(a, b) -> do discard (P.symbol a); return b) setOptions proofArg :: (Bool -> Int -> Name -> Command) -> String -> P.IdrisParser (Either String Command) proofArg cmd name = do upd <- option False $ do P.lchar '!' return True l <- fst <$> P.natural n <- fst <$> P.name; return (Right (cmd upd (fromInteger l) n)) cmd_doc :: String -> P.IdrisParser (Either String Command) cmd_doc name = do let constant = do c <- fmap fst P.constant eof return $ Right (DocStr (Right c) FullDocs) let pType = do P.reserved "Type" eof return $ Right (DocStr (Left $ P.mkName ("Type", "")) FullDocs) let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name try constant <|> pType <|> fnName cmd_consolewidth :: String -> P.IdrisParser (Either String Command) cmd_consolewidth name = do w <- pConsoleWidth return (Right (SetConsoleWidth w)) where pConsoleWidth :: P.IdrisParser ConsoleWidth pConsoleWidth = do discard (P.symbol "auto"); return AutomaticWidth <|> do discard (P.symbol "infinite"); return InfinitelyWide <|> do n <- fmap (fromInteger . fst) P.natural return (ColsWide n) cmd_printdepth :: String -> P.IdrisParser (Either String Command) cmd_printdepth _ = do d <- optional (fmap (fromInteger . fst) P.natural) return (Right $ SetPrinterDepth d) cmd_execute :: String -> P.IdrisParser (Either String Command) cmd_execute name = do tm <- option maintm (P.fullExpr defaultSyntax) return (Right (Execute tm)) where maintm = PRef (fileFC "(repl)") [] (sNS (sUN "main") ["Main"]) cmd_dynamic :: String -> P.IdrisParser (Either String Command) cmd_dynamic name = do let optArg = do l <- many anyChar if (l /= "") then return $ Right (DynamicLink l) else return $ Right ListDynamic let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]" try optArg <|> failure cmd_pprint :: String -> P.IdrisParser (Either String Command) cmd_pprint name = do fmt <- ppFormat P.whiteSpace n <- fmap (fromInteger . fst) P.natural P.whiteSpace t <- P.fullExpr defaultSyntax return (Right (PPrint fmt n t)) where ppFormat :: P.IdrisParser OutputFmt ppFormat = (discard (P.symbol "html") >> return HTMLOutput) <|> (discard (P.symbol "latex") >> return LaTeXOutput) cmd_compile :: String -> P.IdrisParser (Either String Command) cmd_compile name = do let defaultCodegen = Via "c" let codegenOption :: P.IdrisParser Codegen codegenOption = do let bytecodeCodegen = discard (P.symbol "bytecode") *> return Bytecode viaCodegen = do x <- fst <$> P.identifier return (Via (map toLower x)) bytecodeCodegen <|> viaCodegen let hasOneArg = do i <- get f <- fst <$> P.identifier eof return $ Right (Compile defaultCodegen f) let hasTwoArgs = do i <- get codegen <- codegenOption f <- fst <$> P.identifier eof return $ Right (Compile codegen f) let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>" try hasTwoArgs <|> try hasOneArg <|> failure cmd_addproof :: String -> P.IdrisParser (Either String Command) cmd_addproof name = do n <- option Nothing $ do x <- fst <$> P.name return (Just x) eof return (Right (AddProof n)) cmd_log :: String -> P.IdrisParser (Either String Command) cmd_log name = do i <- fmap (fromIntegral . fst) P.natural eof return (Right (LogLvl i)) cmd_let :: String -> P.IdrisParser (Either String Command) cmd_let name = do defn <- concat <$> many (P.decl defaultSyntax) return (Right (NewDefn defn)) cmd_unlet :: String -> P.IdrisParser (Either String Command) cmd_unlet name = (Right . Undefine) `fmap` many (fst <$> P.name) cmd_loadto :: String -> P.IdrisParser (Either String Command) cmd_loadto name = do toline <- fmap (fromInteger . fst) P.natural f <- many anyChar; return (Right (Load f (Just toline))) cmd_colour :: String -> P.IdrisParser (Either String Command) cmd_colour name = fmap Right pSetColourCmd where colours :: [(String, Maybe Color)] colours = [ ("black", Just Black) , ("red", Just Red) , ("green", Just Green) , ("yellow", Just Yellow) , ("blue", Just Blue) , ("magenta", Just Magenta) , ("cyan", Just Cyan) , ("white", Just White) , ("default", Nothing) ] pSetColourCmd :: P.IdrisParser Command pSetColourCmd = (do c <- pColourType let defaultColour = IdrisColour Nothing True False False False opts <- sepBy pColourMod (P.whiteSpace) let colour = foldr ($) defaultColour $ reverse opts return $ SetColour c colour) <|> try (P.symbol "on" >> return ColourOn) <|> try (P.symbol "off" >> return ColourOff) pColour :: P.IdrisParser (Maybe Color) pColour = doColour colours where doColour [] = fail "Unknown colour" doColour ((s, c):cs) = (try (P.symbol s) >> return c) <|> doColour cs pColourMod :: P.IdrisParser (IdrisColour -> IdrisColour) pColourMod = try (P.symbol "vivid" >> return doVivid) <|> try (P.symbol "dull" >> return doDull) <|> try (P.symbol "underline" >> return doUnderline) <|> try (P.symbol "nounderline" >> return doNoUnderline) <|> try (P.symbol "bold" >> return doBold) <|> try (P.symbol "nobold" >> return doNoBold) <|> try (P.symbol "italic" >> return doItalic) <|> try (P.symbol "noitalic" >> return doNoItalic) <|> try (pColour >>= return . doSetColour) where doVivid i = i { vivid = True } doDull i = i { vivid = False } doUnderline i = i { underline = True } doNoUnderline i = i { underline = False } doBold i = i { bold = True } doNoBold i = i { bold = False } doItalic i = i { italic = True } doNoItalic i = i { italic = False } doSetColour c i = i { colour = c } -- | Generate the colour type names using the default Show instance. colourTypes :: [(String, ColourType)] colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $ enumFromTo minBound maxBound pColourType :: P.IdrisParser ColourType pColourType = doColourType colourTypes where doColourType [] = fail $ "Unknown colour category. Options: " ++ (concat . intersperse ", " . map fst) colourTypes doColourType ((s,ct):cts) = (try (P.symbol s) >> return ct) <|> doColourType cts idChar = oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_']) cmd_apropos :: String -> P.IdrisParser (Either String Command) cmd_apropos = packageBasedCmd (some idChar) Apropos packageBasedCmd :: P.IdrisParser a -> ([String] -> a -> Command) -> String -> P.IdrisParser (Either String Command) packageBasedCmd valParser cmd name = try (do P.lchar '(' pkgs <- sepBy (some idChar) (P.lchar ',') P.lchar ')' val <- valParser return (Right (cmd pkgs val))) <|> do val <- valParser return (Right (cmd [] val)) cmd_search :: String -> P.IdrisParser (Either String Command) cmd_search = packageBasedCmd (P.typeExpr (defaultSyntax { implicitAllowed = True })) Search cmd_proofsearch :: String -> P.IdrisParser (Either String Command) cmd_proofsearch name = do upd <- option False (do P.lchar '!'; return True) l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name hints <- many (fst <$> P.fnName) return (Right (DoProofSearch upd True l n hints)) cmd_refine :: String -> P.IdrisParser (Either String Command) cmd_refine name = do upd <- option False (do P.lchar '!'; return True) l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name hint <- fst <$> P.fnName return (Right (DoProofSearch upd False l n [hint]))
mrmonday/Idris-dev
src/Idris/REPLParser.hs
bsd-3-clause
20,026
0
21
5,210
6,348
3,287
3,061
-1
-1
{-# LANGUAGE StandaloneKindSignatures #-} {-# LANGUAGE ConstrainedClassMethods #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ExplicitForAll #-} module T16758 where import Data.Kind type C :: forall (a :: Type) -> a ~ Int => Constraint class C a where f :: C a => a -> Int
sdiehl/ghc
testsuite/tests/saks/should_compile/T16758.hs
bsd-3-clause
325
0
8
59
66
39
27
-1
-1
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1993-1998 \section[TcAnnotations]{Typechecking annotations} -} {-# LANGUAGE CPP #-} module TcAnnotations ( tcAnnotations, annCtxt ) where #ifdef GHCI import {-# SOURCE #-} TcSplice ( runAnnotation ) import Module #endif import HsSyn import Annotations import Name import TcRnMonad import SrcLoc import Outputable import FastString #ifndef GHCI tcAnnotations :: [LAnnDecl Name] -> TcM [Annotation] -- No GHCI; emit a warning (not an error) and ignore. cf Trac #4268 tcAnnotations [] = return [] tcAnnotations anns@(L loc _ : _) = do { setSrcSpan loc $ addWarnTc $ (ptext (sLit "Ignoring ANN annotation") <> plural anns <> comma <+> ptext (sLit "because this is a stage-1 compiler or doesn't support GHCi")) ; return [] } #else tcAnnotations :: [LAnnDecl Name] -> TcM [Annotation] -- GHCI exists, typecheck the annotations tcAnnotations anns = mapM tcAnnotation anns tcAnnotation :: LAnnDecl Name -> TcM Annotation tcAnnotation (L loc ann@(HsAnnotation _ provenance expr)) = do -- Work out what the full target of this annotation was mod <- getModule let target = annProvenanceToTarget mod provenance -- Run that annotation and construct the full Annotation data structure setSrcSpan loc $ addErrCtxt (annCtxt ann) $ runAnnotation target expr annProvenanceToTarget :: Module -> AnnProvenance Name -> AnnTarget Name annProvenanceToTarget _ (ValueAnnProvenance (L _ name)) = NamedTarget name annProvenanceToTarget _ (TypeAnnProvenance (L _ name)) = NamedTarget name annProvenanceToTarget mod ModuleAnnProvenance = ModuleTarget mod #endif annCtxt :: OutputableBndr id => AnnDecl id -> SDoc annCtxt ann = hang (ptext (sLit "In the annotation:")) 2 (ppr ann)
urbanslug/ghc
compiler/typecheck/TcAnnotations.hs
bsd-3-clause
1,820
0
14
344
225
122
103
19
1
import SetupDep (message) import Distribution.Simple main = putStrLn ("pkg Setup.hs: " ++ message) >> defaultMain
mydaum/cabal
cabal-testsuite/PackageTests/NewBuild/CustomSetup/LocalPackageWithCustomSetup/Setup.hs
bsd-3-clause
115
1
8
16
36
18
18
3
1
----------------------------------------------------------------------------- -- -- Pretty-printing TyThings -- -- (c) The GHC Team 2005 -- ----------------------------------------------------------------------------- {-# LANGUAGE CPP #-} module PprTyThing ( pprTyThing, pprTyThingInContext, pprTyThingLoc, pprTyThingInContextLoc, pprTyThingHdr, pprTypeForUser, pprFamInst ) where #include "HsVersions.h" import TypeRep ( TyThing(..) ) import CoAxiom ( coAxiomTyCon ) import HscTypes( tyThingParent_maybe ) import MkIface ( tyThingToIfaceDecl ) import Type ( tidyOpenType ) import IfaceSyn ( pprIfaceDecl, ShowSub(..), ShowHowMuch(..) ) import FamInstEnv( FamInst( .. ), FamFlavor(..) ) import TcType import Name import VarEnv( emptyTidyEnv ) import Outputable import FastString -- ----------------------------------------------------------------------------- -- Pretty-printing entities that we get from the GHC API {- Note [Pretty-printing TyThings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We pretty-print a TyThing by converting it to an IfaceDecl, and pretty-printing that (see ppr_ty_thing below). Here is why: * When pretty-printing (a type, say), the idiomatic solution is not to "rename type variables on the fly", but rather to "tidy" the type (which gives each variable a distinct print-name), and then pretty-print it (without renaming). Separate the two concerns. Functions like tidyType do this. * Alas, for type constructors, TyCon, tidying does not work well, because a TyCon includes DataCons which include Types, which mention TyCons. And tidying can't tidy a mutually recursive data structure graph, only trees. * One alternative would be to ensure that TyCons get type variables with distinct print-names. That's ok for type variables but less easy for kind variables. Processing data type declarations is already so complicated that I don't think it's sensible to add the extra requirement that it generates only "pretty" types and kinds. * One place the non-pretty names can show up is in GHCi. But another is in interface files. Look at MkIface.tyThingToIfaceDecl which converts a TyThing (i.e. TyCon, Class etc) to an IfaceDecl. And it already does tidying as part of that conversion! Why? Because interface files contains fast-strings, not uniques, so the names must at least be distinct. So if we convert to IfaceDecl, we get a nice tidy IfaceDecl, and can print that. Of course, that means that pretty-printing IfaceDecls must be careful to display nice user-friendly results, but that's ok. See #7730, #8776 for details -} -------------------- -- | Pretty-prints a 'FamInst' (type/data family instance) with its defining location. pprFamInst :: FamInst -> SDoc -- * For data instances we go via pprTyThing of the representational TyCon, -- because there is already much cleverness associated with printing -- data type declarations that I don't want to duplicate -- * For type instances we print directly here; there is no TyCon -- to give to pprTyThing -- -- FamInstEnv.pprFamInst does a more quick-and-dirty job for internal purposes pprFamInst (FamInst { fi_flavor = DataFamilyInst rep_tc }) = pprTyThingInContextLoc (ATyCon rep_tc) pprFamInst (FamInst { fi_flavor = SynFamilyInst, fi_axiom = axiom , fi_tys = lhs_tys, fi_rhs = rhs }) = showWithLoc (pprDefinedAt (getName axiom)) $ hang (ptext (sLit "type instance") <+> pprTypeApp (coAxiomTyCon axiom) lhs_tys) 2 (equals <+> ppr rhs) ---------------------------- -- | Pretty-prints a 'TyThing' with its defining location. pprTyThingLoc :: TyThing -> SDoc pprTyThingLoc tyThing = showWithLoc (pprDefinedAt (getName tyThing)) (pprTyThing tyThing) -- | Pretty-prints a 'TyThing'. pprTyThing :: TyThing -> SDoc pprTyThing = ppr_ty_thing False [] -- | Pretty-prints the 'TyThing' header. For functions and data constructors -- the function is equivalent to 'pprTyThing' but for type constructors -- and classes it prints only the header part of the declaration. pprTyThingHdr :: TyThing -> SDoc pprTyThingHdr = ppr_ty_thing True [] -- | Pretty-prints a 'TyThing' in context: that is, if the entity -- is a data constructor, record selector, or class method, then -- the entity's parent declaration is pretty-printed with irrelevant -- parts omitted. pprTyThingInContext :: TyThing -> SDoc pprTyThingInContext thing = go [] thing where go ss thing = case tyThingParent_maybe thing of Just parent -> go (getOccName thing : ss) parent Nothing -> ppr_ty_thing False ss thing -- | Like 'pprTyThingInContext', but adds the defining location. pprTyThingInContextLoc :: TyThing -> SDoc pprTyThingInContextLoc tyThing = showWithLoc (pprDefinedAt (getName tyThing)) (pprTyThingInContext tyThing) ------------------------ ppr_ty_thing :: Bool -> [OccName] -> TyThing -> SDoc -- We pretty-print 'TyThing' via 'IfaceDecl' -- See Note [Pretty-printing TyThings] ppr_ty_thing hdr_only path ty_thing = pprIfaceDecl ss (tyThingToIfaceDecl ty_thing) where ss = ShowSub { ss_how_much = how_much, ss_ppr_bndr = ppr_bndr } how_much | hdr_only = ShowHeader | otherwise = ShowSome path name = getName ty_thing ppr_bndr :: OccName -> SDoc ppr_bndr | isBuiltInSyntax name = ppr | otherwise = case nameModule_maybe name of Just mod -> \ occ -> getPprStyle $ \sty -> pprModulePrefix sty mod occ <> ppr occ Nothing -> WARN( True, ppr name ) ppr -- Nothing is unexpected here; TyThings have External names pprTypeForUser :: Type -> SDoc -- We do two things here. -- a) We tidy the type, regardless -- b) Swizzle the foralls to the top, so that without -- -fprint-explicit-foralls we'll suppress all the foralls -- Prime example: a class op might have type -- forall a. C a => forall b. Ord b => stuff -- Then we want to display -- (C a, Ord b) => stuff pprTypeForUser ty = pprSigmaType (mkSigmaTy tvs ctxt tau) where (tvs, ctxt, tau) = tcSplitSigmaTy tidy_ty (_, tidy_ty) = tidyOpenType emptyTidyEnv ty -- Often the types/kinds we print in ghci are fully generalised -- and have no free variables, but it turns out that we sometimes -- print un-generalised kinds (eg when doing :k T), so it's -- better to use tidyOpenType here showWithLoc :: SDoc -> SDoc -> SDoc showWithLoc loc doc = hang doc 2 (char '\t' <> comment <+> loc) -- The tab tries to make them line up a bit where comment = ptext (sLit "--")
wxwxwwxxx/ghc
compiler/main/PprTyThing.hs
bsd-3-clause
6,735
0
15
1,418
843
470
373
70
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE UndecidableInstances #-} {-| Module : Control.Monad.Metrics Description : An easy interface to recording metrics. Copyright : (c) Matt Parsons, 2017 Taylor Fausak, 2016 License : MIT Maintainer : parsonsmatt@gmail.com Stability : experimental Portability : POSIX This module presents an easy interface that you can use to collect metrics about your application. It uses EKG from "System.Metrics" under the hood and is inspired by Taylor Fausak's <https://github.com/tfausak/blunt blunt> application. This module is designed to be imported qualified. -} module Control.Monad.Metrics ( -- * The Type Class MonadMetrics(..) -- * Initializing -- $initializing , initialize , initializeWith , run , run' -- * Collecting Metrics -- $collecting , increment , counter , counter' , gauge , gauge' , distribution , timed , timed' , timedList , label , label' , Resolution(..) -- * The Metrics Type -- $metrictype , Metrics , metricsCounters , metricsGauges , metricsLabels , metricsStore ) where import Control.Monad (liftM, forM_) import Control.Monad.Catch (MonadMask, bracket) import Control.Monad.IO.Class (MonadIO (..)) import Control.Monad.Reader (MonadReader (..), ReaderT (..)) import Control.Monad.Trans (MonadTrans (..)) import Data.Hashable (Hashable) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.IORef (IORef, atomicModifyIORef', newIORef) import Data.Monoid (mempty) import Data.Text (Text) import qualified Data.Text as Text import System.Clock (Clock (..), getTime) import System.IO.Unsafe (unsafeInterleaveIO) import qualified System.Metrics as EKG import System.Metrics.Counter as Counter import System.Metrics.Distribution as Distribution import System.Metrics.Gauge as Gauge import System.Metrics.Label as Label import Prelude import Control.Monad.Metrics.Internal -- | A type can be an instance of 'MonadMetrics' if it can provide a 'Metrics' -- somehow. Commonly, this will be implemented as a 'ReaderT' where some -- field in the environment is the 'Metrics' data. -- -- * /Since v0.1.0.0/ class Monad m => MonadMetrics m where getMetrics :: m Metrics instance {-# OVERLAPPABLE #-} (MonadMetrics m, MonadTrans t, Monad (t m)) => MonadMetrics (t m) where getMetrics = lift getMetrics instance Monad m => MonadMetrics (ReaderT Metrics m) where getMetrics = ask -- $initializing -- This library tends to provide simple functions with plain names and -- generalized functions with apostrophes. When initializing the metrics, -- you can use 'initialize' if you don't need fine control over the store, -- or you can use 'initializeWith' if your application already has a store -- that it uses. -- -- Likewise, we provide 'run' for the simplest case, and 'run'' for the -- more complex case where you have some larger type. -- -- The most flexible way to use the library is to implement the -- 'MonadMetrics' class. -- | Enhances the base monad with metrics. This works for very simple -- cases, where you don't have a 'Reader' involved yet. If your stack -- already has a 'Reader', then you'll get some annoying type problems with -- this. Switch over to 'run'', or alternatively, define your own -- 'MonadMetrics' instance. -- -- */Since v0.1.0.0/ run :: MonadIO m => ReaderT Metrics m a -> m a run = run' id -- | Adds metric recording capabilities to the given action. The first -- parameter is a function which accepts a 'Metrics' value and creates the -- final @r@ value to be used in the action. This is useful when you have -- a preexisting 'ReaderT' in your stack, and you want to enhance it with -- metrics. -- -- @ -- data Config = Config { size :: Int, metrics' :: Metrics } -- -- main = 'runWithMetrics' (Config 10) $ do -- num <- asks size -- forM_ [1 .. size] \_ -> Metrics.increment "foo" -- @ -- -- */Since v0.1.0.0/ run' :: MonadIO m => (Metrics -> r) -> ReaderT r m a -> m a run' k action = do m <- liftIO initialize runReaderT action (k m) -- | Initializes a 'Metrics' value with the given 'System.Metrics.Store'. -- -- */Since v0.1.0.0/ initializeWith :: EKG.Store -> IO Metrics initializeWith _metricsStore = do _metricsCounters <- newIORef mempty _metricsDistributions <- newIORef mempty _metricsGauges <- newIORef mempty _metricsLabels <- newIORef mempty return Metrics{..} -- | Initializes a 'Metrics' value, creating a new 'System.Metrics.Store' -- for it. -- -- * /Since v0.1.0.0/ initialize :: IO Metrics initialize = EKG.newStore >>= initializeWith -- $collecting -- As with initialization, the library provides "common case" functions -- with a plain name and generalized functions with an apostrophe. -- -- * 'increment', 'counter', 'counter'' -- * 'gauge', 'gauge'' -- * 'timed', 'timed'' -- * 'label', 'label'' -- -- Only 'distribution' isn't generalized. -- | Increment the named counter by 1. -- -- * /Since v0.1.0.0/ increment :: (MonadIO m, MonadMetrics m) => Text -> m () increment name = counter name 1 -- | Adds the value to the named 'System.Metrics.Counter.Counter'. -- -- * /Since v0.1.0.0/ counter' :: (MonadIO m, MonadMetrics m, Integral int) => Text -> int -> m () counter' = modifyMetric Counter.add fromIntegral EKG.createCounter _metricsCounters -- | A type specialized version of 'counter'' to avoid ambiguous type -- errors. -- -- * /Since v0.1.0.0/ counter :: (MonadIO m, MonadMetrics m) => Text -> Int -> m () counter = counter' -- | Add the value to the named 'System.Metrics.Distribution.Distribution'. -- -- * /Since v0.1.0.0/ distribution :: (MonadIO m, MonadMetrics m) => Text -> Double -> m () distribution = modifyMetric Distribution.add id EKG.createDistribution _metricsDistributions -- | Set the value of the named 'System.Metrics.Distribution.Gauge'. -- -- * /Since v0.1.0.0/ gauge' :: (MonadIO m, MonadMetrics m, Integral int) => Text -> int -> m () gauge' = modifyMetric Gauge.set fromIntegral EKG.createGauge _metricsGauges -- | A type specialized version of 'gauge'' to avoid ambiguous types. -- -- * /Since v0.1.0.0/ gauge :: (MonadIO m, MonadMetrics m) => Text -> Int -> m () gauge = gauge' -- | Record the time taken to perform the named action. The number is -- stored in a 'System.Metrics.Distribution.Distribution' and is converted -- to the specified 'Resolution'. -- -- * /Since v0.1.0.0/ timed' :: (MonadIO m, MonadMetrics m, MonadMask m) => Resolution -> Text -> m a -> m a timed' resolution name action = timedList resolution [name] action -- | Record the time taken to perform the action, under several names at once. -- The number is stored in a 'System.Metrics.Distribution.Distribution' and is -- converted to the specified 'Resolution'. -- -- This is useful to store the same durations data sectioned by different criteria, e.g.: -- -- @ -- timedList Seconds ["request.byUser." <> userName, "request.byType." <> requestType] $ do -- ... -- @ -- -- So you will have @"request.byUser.someuser"@ storing duration distribution for requests -- of user @"someuser"@ of any type; and @"request.byType.sometype"@ storing -- duration distribution for requests of type @"sometype"@ from any user. -- timedList :: (MonadIO m, MonadMetrics m, MonadMask m) => Resolution -> [Text] -> m a -> m a timedList resolution names action = bracket (liftIO (getTime Monotonic)) finish (const action) where finish start = do end <- liftIO (getTime Monotonic) forM_ names $ \name -> distribution name (diffTime resolution end start) -- | Record the time of executing the given action in seconds. Defers to -- 'timed''. -- -- * /Since v0.1.0.0/ timed :: (MonadIO m, MonadMetrics m, MonadMask m) => Text -> m a -> m a timed = timed' Seconds -- | Set the 'Label' to the given 'Text' value. -- -- * /Since v0.1.0.0/ label :: (MonadIO m, MonadMetrics m) => Text -> Text -> m () label = modifyMetric Label.set id EKG.createLabel _metricsLabels -- | Set the 'Label' to the 'Show'n value of whatever you pass in. -- -- * /Since v0.1.0.0/ label' :: (MonadIO m, MonadMetrics m, Show a) => Text -> a -> m () label' l = label l . Text.pack . show -- $metrictype -- The 'Metric' type contains an 'IORef' to a 'HashMap' from 'Text' labels to -- the various counters, and a 'EKG.Store' to register them with. If you -- must use the 'Metric' value directly, then you are recommended to use -- the lenses provided for compatibility. ------------------------------------------------------------------------------- modifyMetric :: (MonadMetrics m, MonadIO m) => (t -> t1 -> IO b) -- ^ The action to add a value to a metric. -> (t2 -> t1) -- ^ A conversion function from input to metric value. -> (Text -> EKG.Store -> IO t) -- ^ The function for creating a new metric. -> (Metrics -> IORef (HashMap Text t)) -- ^ A way of getting the current metrics. -> Text -- ^ The name of the metric to use. -> t2 -- ^ The value the end user can provide. -> m b modifyMetric adder converter creator getter name value = do bar <- lookupOrCreate getter creator name liftIO $ adder bar (converter value) lookupOrCreate :: (MonadMetrics m, MonadIO m, Eq k, Hashable k) => (Metrics -> IORef (HashMap k a)) -> (k -> EKG.Store -> IO a) -> k -> m a lookupOrCreate getter creator name = do ref <- liftM getter getMetrics -- unsafeInterleaveIO is used here to defer creating the metric into -- the 'atomicModifyIORef'' function. We lazily create the value here, -- and the resulting IO action only gets run to create the metric when -- the named metric is not present in the map. newMetric <- liftIO . unsafeInterleaveIO . creator name =<< liftM _metricsStore getMetrics liftIO $ atomicModifyIORef' ref (\container -> case HashMap.lookup name container of Nothing -> (HashMap.insert name newMetric container, newMetric) Just metric -> (container, metric))
sellerlabs/monad-metrics
src/Control/Monad/Metrics.hs
mit
10,677
0
16
2,494
1,746
986
760
125
2
import Data.List import Data.Function import Boids import Test.HUnit import System.Exit import TestDataSpec import BoidsSpec import ViewPortTransformSpec import NavigationSpec testIsWithinView :: Test testIsWithinView = TestCase (assertBool "Seeing a boid behind me" (not $ isWithinViewOf boid (-10.0, 0.0))) where boid = Boid { boidPosition = (0.0, 0.0) , boidHeading = 0.0 , boidSteer = 0.0 } testGetNearbyBoids :: Test testGetNearbyBoids = TestCase (assertEqual "Got unexpected nearest boids" (sort $ map boidPosition nearestBoids) (sort $ map boidPosition actualResult)) where pivotBoid = Boid { boidPosition = (388.46451, 289.70023) , boidHeading = -pi / 2.0 , boidSteer = 0.0 } nearestBoids = [ Boid { boidPosition = (291.93515, 228.0032) , boidHeading = 0.0 , boidSteer = 0.0 } , Boid { boidPosition = (392.85715, 127.36221) , boidHeading = 0.0 , boidSteer = 0.0 } ] farthestBoids = [ Boid { boidPosition = (505.70178, 58.542339) , boidHeading = 0.0 , boidSteer = 0.0 } , Boid { boidPosition = (404.23859, 333.44159) , boidHeading = 0.0 , boidSteer = 0.0 } , Boid { boidPosition = (349.0011, 426.28027) , boidHeading = 0.0 , boidSteer = 0.0 } ] allBoids = nearestBoids ++ farthestBoids proximity = 203.03714 actualResult = getNearbyBoids pivotBoid proximity allBoids main :: IO Counts main = do results <- runTestTT $ TestList [ TestLabel "Filtering surrounding boids by proximity" testGetNearbyBoids , TestLabel "Test isWithinViewOf" testIsWithinView , TestLabel "TestData.getAllBoids" testGetAllBoids , TestLabel "TestData.getBoidById" testGetBoidById , TestLabel "TestData.getBoidsGroupById" testGetBoidsGroupById , TestLabel "Boids.guideBoidToAngle" testGuideBoidToAngle , TestLabel "Boids.zoomControl" testZoomControl , TestLabel "ViewPortTransform.zoom" testZoom ] if (errors results + failures results == 0) then exitWith ExitSuccess else exitWith (ExitFailure 1)
tsoding/boids
test/Spec.hs
mit
3,049
0
12
1,431
515
293
222
49
2
-- Reversed Words -- http://www.codewars.com/kata/51c8991dee245d7ddf00000e/ module ReverseWords where reverseWords :: String -> String reverseWords = unwords . reverse . words
gafiatulin/codewars
src/6 kyu/ReverseWords.hs
mit
178
0
6
22
28
17
11
3
1
{-| Module : PostgREST.Config Description : Manages PostgREST configuration options. This module provides a helper function to read the command line arguments using the optparse-applicative and the AppConfig type to store them. It also can be used to define other middleware configuration that may be delegated to some sort of external configuration. It currently includes a hardcoded CORS policy but this could easly be turned in configurable behaviour if needed. Other hardcoded options such as the minimum version number also belong here. -} module PostgREST.Config ( prettyVersion , readOptions , corsPolicy , minimumPgVersion , AppConfig (..) ) where import Control.Applicative import qualified Data.ByteString.Char8 as BS import qualified Data.CaseInsensitive as CI import Data.List (intercalate) import Data.String.Conversions (cs) import Data.Text (strip) import Data.Version (versionBranch) import Network.Wai import Network.Wai.Middleware.Cors (CorsResourcePolicy (..)) import Options.Applicative hiding (columns) import Paths_postgrest (version) import Prelude -- | Data type to store all command line options data AppConfig = AppConfig { configDbName :: String , configDbPort :: Int , configDbUser :: String , configDbPass :: String , configDbHost :: String , configPort :: Int , configAnonRole :: String , configSecure :: Bool , configPool :: Int , configV1Schema :: String , configJwtSecret :: String } argParser :: Parser AppConfig argParser = AppConfig <$> strOption (long "db-name" <> short 'd' <> metavar "NAME" <> help "name of database") <*> option auto (long "db-port" <> short 'P' <> metavar "PORT" <> value 5432 <> help "postgres server port" <> showDefault) <*> strOption (long "db-user" <> short 'U' <> metavar "ROLE" <> help "postgres authenticator role") <*> strOption (long "db-pass" <> metavar "PASS" <> value "" <> help "password for authenticator role") <*> strOption (long "db-host" <> metavar "HOST" <> value "localhost" <> help "postgres server hostname" <> showDefault) <*> option auto (long "port" <> short 'p' <> metavar "PORT" <> value 3000 <> help "port number on which to run HTTP server" <> showDefault) <*> strOption (long "anonymous" <> short 'a' <> metavar "ROLE" <> help "postgres role to use for non-authenticated requests") <*> switch (long "secure" <> short 's' <> help "Redirect all requests to HTTPS") <*> option auto (long "db-pool" <> metavar "COUNT" <> value 10 <> help "Max connections in database pool" <> showDefault) <*> strOption (long "v1schema" <> metavar "NAME" <> value "1" <> help "Schema to use for nonspecified version (or explicit v1)" <> showDefault) <*> strOption (long "jwt-secret" <> metavar "SECRET" <> value "secret" <> help "Secret used to encrypt and decrypt JWT tokens)" <> showDefault) defaultCorsPolicy :: CorsResourcePolicy defaultCorsPolicy = CorsResourcePolicy Nothing ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] ["Authorization"] Nothing (Just $ 60*60*24) False False True -- | CORS policy to be used in by Wai Cors middleware corsPolicy :: Request -> Maybe CorsResourcePolicy corsPolicy req = case lookup "origin" headers of Just origin -> Just defaultCorsPolicy { corsOrigins = Just ([origin], True) , corsRequestHeaders = "Authentication":accHeaders , corsExposedHeaders = Just [ "Content-Encoding", "Content-Location", "Content-Range", "Content-Type" , "Date", "Location", "Server", "Transfer-Encoding", "Range-Unit" ] } Nothing -> Nothing where headers = requestHeaders req accHeaders = case lookup "access-control-request-headers" headers of Just hdrs -> map (CI.mk . cs . strip . cs) $ BS.split ',' hdrs Nothing -> [] -- | User friendly version number prettyVersion :: String prettyVersion = intercalate "." $ map show $ versionBranch version -- | Function to read and parse options from the command line readOptions :: IO AppConfig readOptions = customExecParser parserPrefs opts where opts = info (helper <*> argParser) $ fullDesc <> progDesc ( "PostgREST " <> prettyVersion <> " / create a REST API to an existing Postgres database" ) parserPrefs = prefs showHelpOnError -- | Tells the minimum PostgreSQL version required by this version of PostgREST minimumPgVersion :: Integer minimumPgVersion = 90300
pap/postgrest
src/PostgREST/Config.hs
mit
4,814
0
22
1,225
988
518
470
72
3
module Feature.AndOrParamsSpec where import Network.Wai (Application) import Network.HTTP.Types import Test.Hspec import Test.Hspec.Wai import Test.Hspec.Wai.JSON import PostgREST.Types (PgVersion, pgVersion112) import Protolude hiding (get) import SpecHelper spec :: PgVersion -> SpecWith Application spec actualPgVersion = describe "and/or params used for complex boolean logic" $ do context "used with GET" $ do context "or param" $ do it "can do simple logic" $ get "/entities?or=(id.eq.1,id.eq.2)&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } it "can negate simple logic" $ get "/entities?not.or=(id.eq.1,id.eq.2)&select=id" `shouldRespondWith` [json|[{ "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } it "can be combined with traditional filters" $ get "/entities?or=(id.eq.1,id.eq.2)&name=eq.entity 1&select=id" `shouldRespondWith` [json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] } context "embedded levels" $ do it "can do logic on the second level" $ get "/entities?child_entities.or=(id.eq.1,name.eq.child entity 2)&select=id,child_entities(id)" `shouldRespondWith` [json|[ {"id": 1, "child_entities": [ { "id": 1 }, { "id": 2 } ] }, { "id": 2, "child_entities": []}, {"id": 3, "child_entities": []}, {"id": 4, "child_entities": []} ]|] { matchHeaders = [matchContentTypeJson] } it "can do logic on the third level" $ get "/entities?child_entities.grandchild_entities.or=(id.eq.1,id.eq.2)&select=id,child_entities(id,grandchild_entities(id))" `shouldRespondWith` [json|[ {"id": 1, "child_entities": [ { "id": 1, "grandchild_entities": [ { "id": 1 }, { "id": 2 } ]}, { "id": 2, "grandchild_entities": []}]}, {"id": 2, "child_entities": [ { "id": 3, "grandchild_entities": []} ]}, {"id": 3, "child_entities": []}, {"id": 4, "child_entities": []} ]|] { matchHeaders = [matchContentTypeJson] } context "and/or params combined" $ do it "can be nested inside the same expression" $ get "/entities?or=(and(name.eq.entity 2,id.eq.2),and(name.eq.entity 1,id.eq.1))&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } it "can be negated while nested" $ get "/entities?or=(not.and(name.eq.entity 2,id.eq.2),not.and(name.eq.entity 1,id.eq.1))&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } it "can be combined unnested" $ get "/entities?and=(id.eq.1,name.eq.entity 1)&or=(id.eq.1,id.eq.2)&select=id" `shouldRespondWith` [json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] } context "operators inside and/or" $ do it "can handle eq and neq" $ get "/entities?and=(id.eq.1,id.neq.2))&select=id" `shouldRespondWith` [json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] } it "can handle lt and gt" $ get "/entities?or=(id.lt.2,id.gt.3)&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } it "can handle lte and gte" $ get "/entities?or=(id.lte.2,id.gte.3)&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } it "can handle like and ilike" $ get "/entities?or=(name.like.*1,name.ilike.*ENTITY 2)&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } it "can handle in" $ get "/entities?or=(id.in.(1,2),id.in.(3,4))&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } it "can handle is" $ get "/entities?and=(name.is.null,arr.is.null)&select=id" `shouldRespondWith` [json|[{ "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } it "can handle fts" $ do get "/entities?or=(text_search_vector.fts.bar,text_search_vector.fts.baz)&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } get "/tsearch?or=(text_search_vector.plfts(german).Art%20Spass, text_search_vector.plfts(french).amusant%20impossible, text_search_vector.fts(english).impossible)" `shouldRespondWith` [json|[ {"text_search_vector": "'fun':5 'imposs':9 'kind':3" }, {"text_search_vector": "'amus':5 'fair':7 'impossibl':9 'peu':4" }, {"text_search_vector": "'art':4 'spass':5 'unmog':7"} ]|] { matchHeaders = [matchContentTypeJson] } when (actualPgVersion >= pgVersion112) $ it "can handle wfts (websearch_to_tsquery)" $ get "/tsearch?or=(text_search_vector.plfts(german).Art,text_search_vector.plfts(french).amusant,text_search_vector.not.wfts(english).impossible)" `shouldRespondWith` [json|[ {"text_search_vector": "'also':2 'fun':3 'possibl':8" }, {"text_search_vector": "'ate':3 'cat':2 'fat':1 'rat':4" }, {"text_search_vector": "'amus':5 'fair':7 'impossibl':9 'peu':4" }, {"text_search_vector": "'art':4 'spass':5 'unmog':7" } ]|] { matchHeaders = [matchContentTypeJson] } it "can handle cs and cd" $ get "/entities?or=(arr.cs.{1,2,3},arr.cd.{1})&select=id" `shouldRespondWith` [json|[{ "id": 1 },{ "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } it "can handle range operators" $ do get "/ranges?range=eq.[1,3]&select=id" `shouldRespondWith` [json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=neq.[1,3]&select=id" `shouldRespondWith` [json|[{ "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=lt.[1,10]&select=id" `shouldRespondWith` [json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=gt.[8,11]&select=id" `shouldRespondWith` [json|[{ "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=lte.[1,3]&select=id" `shouldRespondWith` [json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=gte.[2,3]&select=id" `shouldRespondWith` [json|[{ "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=cs.[1,2]&select=id" `shouldRespondWith` [json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=cd.[1,6]&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=ov.[0,4]&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=sl.[9,10]&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=sr.[3,4]&select=id" `shouldRespondWith` [json|[{ "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=nxr.[4,7]&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=nxl.[4,7]&select=id" `shouldRespondWith` [json|[{ "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } get "/ranges?range=adj.(3,10]&select=id" `shouldRespondWith` [json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] } it "can handle array operators" $ do get "/entities?arr=eq.{1,2,3}&select=id" `shouldRespondWith` [json|[{ "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=neq.{1,2}&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=lt.{2,3}&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=lt.{2,0}&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=gt.{1,1}&select=id" `shouldRespondWith` [json|[{ "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=gt.{3}&select=id" `shouldRespondWith` [json|[]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=lte.{2,1}&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=lte.{1,2,3}&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=lte.{1,2}&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=cs.{1,2}&select=id" `shouldRespondWith` [json|[{ "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=cd.{1,2,6}&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=ov.{3}&select=id" `shouldRespondWith` [json|[{ "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } get "/entities?arr=ov.{2,3}&select=id" `shouldRespondWith` [json|[{ "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } context "operators with not" $ do it "eq, cs, like can be negated" $ get "/entities?and=(arr.not.cs.{1,2,3},and(id.not.eq.2,name.not.like.*3))&select=id" `shouldRespondWith` [json|[{ "id": 1}]|] { matchHeaders = [matchContentTypeJson] } it "in, is, fts can be negated" $ get "/entities?and=(id.not.in.(1,3),and(name.not.is.null,text_search_vector.not.fts.foo))&select=id" `shouldRespondWith` [json|[{ "id": 2}]|] { matchHeaders = [matchContentTypeJson] } it "lt, gte, cd can be negated" $ get "/entities?and=(arr.not.cd.{1},or(id.not.lt.1,id.not.gte.3))&select=id" `shouldRespondWith` [json|[{"id": 2}, {"id": 3}]|] { matchHeaders = [matchContentTypeJson] } it "gt, lte, ilike can be negated" $ get "/entities?and=(name.not.ilike.*ITY2,or(id.not.gt.4,id.not.lte.1))&select=id" `shouldRespondWith` [json|[{"id": 1}, {"id": 2}, {"id": 3}]|] { matchHeaders = [matchContentTypeJson] } context "and/or params with quotes" $ do it "eq can have quotes" $ get "/grandchild_entities?or=(name.eq.\"(grandchild,entity,4)\",name.eq.\"(grandchild,entity,5)\")&select=id" `shouldRespondWith` [json|[{ "id": 4 }, { "id": 5 }]|] { matchHeaders = [matchContentTypeJson] } it "like and ilike can have quotes" $ get "/grandchild_entities?or=(name.like.\"*ity,4*\",name.ilike.\"*ITY,5)\")&select=id" `shouldRespondWith` [json|[{ "id": 4 }, { "id": 5 }]|] { matchHeaders = [matchContentTypeJson] } it "in can have quotes" $ get "/grandchild_entities?or=(id.in.(\"1\",\"2\"),id.in.(\"3\",\"4\"))&select=id" `shouldRespondWith` [json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] } it "allows whitespace" $ get "/entities?and=( and ( id.in.( 1, 2, 3 ) , id.eq.3 ) , or ( id.eq.2 , id.eq.3 ) )&select=id" `shouldRespondWith` [json|[{ "id": 3 }]|] { matchHeaders = [matchContentTypeJson] } context "multiple and/or conditions" $ do it "cannot have zero conditions" $ get "/entities?or=()" `shouldRespondWith` [json|{ "details": "unexpected \")\" expecting field name (* or [a..z0..9_]), negation operator (not) or logic operator (and, or)", "message": "\"failed to parse logic tree (())\" (line 1, column 4)" }|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] } it "can have a single condition" $ do get "/entities?or=(id.eq.1)&select=id" `shouldRespondWith` [json|[{"id":1}]|] { matchHeaders = [matchContentTypeJson] } get "/entities?and=(id.eq.1)&select=id" `shouldRespondWith` [json|[{"id":1}]|] { matchHeaders = [matchContentTypeJson] } it "can have three conditions" $ do get "/grandchild_entities?or=(id.eq.1, id.eq.2, id.eq.3)&select=id" `shouldRespondWith` [json|[{"id":1}, {"id":2}, {"id":3}]|] { matchHeaders = [matchContentTypeJson] } get "/grandchild_entities?and=(id.in.(1,2), id.in.(3,1), id.in.(1,4))&select=id" `shouldRespondWith` [json|[{"id":1}]|] { matchHeaders = [matchContentTypeJson] } it "can have four conditions combining and/or" $ do get "/grandchild_entities?or=( id.eq.1, id.eq.2, and(id.in.(1,3), id.in.(2,3)), id.eq.4 )&select=id" `shouldRespondWith` [json|[{"id":1}, {"id":2}, {"id":3}, {"id":4}]|] { matchHeaders = [matchContentTypeJson] } get "/grandchild_entities?and=( id.eq.1, not.or(id.eq.2, id.eq.3), id.in.(1,4), or(id.eq.1, id.eq.4) )&select=id" `shouldRespondWith` [json|[{"id":1}]|] { matchHeaders = [matchContentTypeJson] } context "used with POST" $ it "includes related data with filters" $ request methodPost "/child_entities?select=id,entities(id)&entities.or=(id.eq.2,id.eq.3)&entities.order=id" [("Prefer", "return=representation")] [json|[{"id":4,"name":"entity 4","parent_id":1}, {"id":5,"name":"entity 5","parent_id":2}, {"id":6,"name":"entity 6","parent_id":3}]|] `shouldRespondWith` [json|[{"id": 4, "entities":null}, {"id": 5, "entities": {"id": 2}}, {"id": 6, "entities": {"id": 3}}]|] { matchStatus = 201, matchHeaders = [matchContentTypeJson] } context "used with PATCH" $ it "succeeds when using and/or params" $ request methodPatch "/grandchild_entities?or=(id.eq.1,id.eq.2)&select=id,name" [("Prefer", "return=representation")] [json|{ name : "updated grandchild entity"}|] `shouldRespondWith` [json|[{ "id": 1, "name" : "updated grandchild entity"},{ "id": 2, "name" : "updated grandchild entity"}]|] { matchHeaders = [matchContentTypeJson] } context "used with DELETE" $ it "succeeds when using and/or params" $ request methodDelete "/grandchild_entities?or=(id.eq.1,id.eq.2)&select=id,name" [("Prefer", "return=representation")] "" `shouldRespondWith` [json|[{ "id": 1, "name" : "updated grandchild entity"},{ "id": 2, "name" : "updated grandchild entity"}]|] { matchHeaders = [matchContentTypeJson] } it "can query columns that begin with and/or reserved words" $ get "/grandchild_entities?or=(and_starting_col.eq.smth, or_starting_col.eq.smth)" `shouldRespondWith` 200 it "fails when using IN without () and provides meaningful error message" $ get "/entities?or=(id.in.1,2,id.eq.3)" `shouldRespondWith` [json|{ "details": "unexpected \"1\" expecting \"(\"", "message": "\"failed to parse logic tree ((id.in.1,2,id.eq.3))\" (line 1, column 10)" }|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] } it "fails on malformed query params and provides meaningful error message" $ do get "/entities?or=)(" `shouldRespondWith` [json|{ "details": "unexpected \")\" expecting \"(\"", "message": "\"failed to parse logic tree ()()\" (line 1, column 3)" }|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] } get "/entities?and=(ord(id.eq.1,id.eq.1),id.eq.2)" `shouldRespondWith` [json|{ "details": "unexpected \"d\" expecting \"(\"", "message": "\"failed to parse logic tree ((ord(id.eq.1,id.eq.1),id.eq.2))\" (line 1, column 7)" }|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] } get "/entities?or=(id.eq.1,not.xor(id.eq.2,id.eq.3))" `shouldRespondWith` [json|{ "details": "unexpected \"x\" expecting logic operator (and, or)", "message": "\"failed to parse logic tree ((id.eq.1,not.xor(id.eq.2,id.eq.3)))\" (line 1, column 16)" }|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] }
diogob/postgrest
test/Feature/AndOrParamsSpec.hs
mit
17,212
0
20
4,029
2,397
1,425
972
-1
-1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Helper.Form where import Import -- to use Html into forms import Data.Time import Yesod.Markdown import Yesod.Auth import Data.Maybe import qualified Data.Text as T entryForm :: Form (Article, [Text]) entryForm html = postForm Nothing Nothing html modifyForm :: Article -> [Text] -> Form (Article, [Text]) modifyForm art oldTags = postForm (Just art) (Just oldTags) postForm :: Maybe Article -> Maybe [Text] -> Form (Article, [Text]) postForm mart mtags html = do Entity userId _ <- lift requireAuth (r,widget) <- flip (renderBootstrap3 BootstrapBasicForm) html $ let art = Article <$> pure userId <*> areq textField fsTitle (articleTitle <$> mart) <*> areq markdownField fsContent (articleContent <$> mart) <*> areq textField fsSlug (articleSlug <$> mart) <*> areq checkBoxField fsDraft (articleDraft <$> mart) <*> lift (liftIO getCurrentTime) tags = T.words . fromMaybe "" <$> aopt textField fsTag (Just . T.unwords <$> mtags) in (,) <$> art <*> tags return (r,widget) where fsTitle = (fieldSettingsLabel MsgFormArticleTitle) { fsAttrs = [("class", "col-md-12")] } fsContent = (fieldSettingsLabel MsgFormArticleContent) { fsAttrs = [("class", "col-md-12")] } fsSlug = (fieldSettingsLabel MsgFormArticleSlug) { fsAttrs = [("class", "col-md-12")] } fsTag = (fieldSettingsLabel MsgFormArticleTag) { fsAttrs = [("class", "col-md-12")] } fsDraft = (fieldSettingsLabel MsgFormArticleDraft) { fsAttrs = [("class", "col-md-12")] } commentForm :: ArticleId -> Form Comment commentForm articleId extra = do muser <- lift maybeAuth let mname = case muser of Just entity -> userScreenName $ entityVal entity Nothing -> "Anonymous" renderBootstrap3 BootstrapBasicForm (commentAForm mname) extra where commentAForm mname = Comment <$> areq textField fsName (Just mname) <*> (unTextarea <$> areq textareaField fsContent Nothing) <*> pure articleId <*> lift (liftIO getCurrentTime) where fsName = (fieldSettingsLabel MsgFormCommentName) { fsAttrs = [("class", "col-md-12")] } fsContent = (fieldSettingsLabel MsgFormCommentContent) { fsAttrs = [("class", "col-md-12")] }
cosmo0920/Ahblog
Helper/Form.hs
mit
2,438
0
20
620
727
387
340
44
2
module Main (main, spec) where import Test.Hspec.Core.Spec import Test.Hspec.Core.Runner import Test.Hspec.Expectations import Test.QuickCheck main :: IO () main = hspec spec spec :: Spec spec = do describe "reverse" $ do it "reverses a list" $ do reverse [1 :: Int, 2, 3] `shouldBe` [3, 2, 1] it "gives the original list, if applied twice" $ property $ \xs -> (reverse . reverse) xs == (xs :: [Int])
beni55/hspec
hspec-core/example/Spec.hs
mit
427
0
15
94
160
90
70
14
1
import Data.List mostFrequent = snd . minimum . map (\s -> (length s, head s)) . group . sort main = do input <- getContents print . map mostFrequent . transpose . lines $ input
lzlarryli/advent_of_code_2016
day6/part2.hs
mit
184
1
12
41
87
42
45
5
1
{-# LANGUAGE BlockArguments, OverloadedStrings, RecordWildCards #-} module Setting where import Data.Function (on) import Data.List (sortBy) import qualified Data.Map.Strict as M import Data.Text (Text, lines) import Data.YAML import Prelude hiding (lines) import Plugin data Setting = Setting { plugins :: [Plugin] , filetype :: M.Map Text [Text] , syntax :: M.Map Text [Text] , before :: [Text] , after :: [Text] } deriving Eq instance FromYAML Setting where parseYAML = withMap "!!map" \o -> do plugins <- pluginMapToList <$> o .:? "plugin" .!= M.empty filetype <- M.map lines <$> o .:? "filetype" .!= M.empty syntax <- M.map lines <$> o .:? "syntax" .!= M.empty before <- lines <$> o .:? "before" .!= "" after <- lines <$> o .:? "after" .!= "" return Setting {..} where pluginMapToList = sortWith name . M.foldlWithKey' (\a k v -> v { name = k } : a) [] sortWith :: Ord b => (a -> b) -> [a] -> [a] sortWith = sortBy . on compare
itchyny/miv
src/Setting.hs
mit
1,040
0
15
269
372
203
169
-1
-1
-- Copyright (c) 2016-present, SoundCloud Ltd. -- All rights reserved. -- -- This source code is distributed under the terms of a MIT license, -- found in the LICENSE file. {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} module Kubernetes.Model.V1.PodSecurityContext ( PodSecurityContext (..) , seLinuxOptions , runAsUser , runAsNonRoot , supplementalGroups , fsGroup , mkPodSecurityContext ) where import Control.Lens.TH (makeLenses) import Data.Aeson.TH (defaultOptions, deriveJSON, fieldLabelModifier) import GHC.Generics (Generic) import Kubernetes.Model.V1.SELinuxOptions (SELinuxOptions) import Prelude hiding (drop, error, max, min) import qualified Prelude as P import Test.QuickCheck (Arbitrary, arbitrary) import Test.QuickCheck.Instances () -- | PodSecurityContext holds pod-level security attributes and common container settings. Some fields are also present in container.securityContext. Field values of container.securityContext take precedence over field values of PodSecurityContext. data PodSecurityContext = PodSecurityContext { _seLinuxOptions :: !(Maybe SELinuxOptions) , _runAsUser :: !(Maybe Integer) , _runAsNonRoot :: !(Maybe Bool) , _supplementalGroups :: !(Maybe [Integer]) , _fsGroup :: !(Maybe Integer) } deriving (Show, Eq, Generic) makeLenses ''PodSecurityContext $(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''PodSecurityContext) instance Arbitrary PodSecurityContext where arbitrary = PodSecurityContext <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- | Use this method to build a PodSecurityContext mkPodSecurityContext :: PodSecurityContext mkPodSecurityContext = PodSecurityContext Nothing Nothing Nothing Nothing Nothing
soundcloud/haskell-kubernetes
lib/Kubernetes/Model/V1/PodSecurityContext.hs
mit
2,244
0
14
655
344
204
140
44
1
{-# LANGUAGE MultiParamTypeClasses #-} module GatesMatrices ( nameToMatrix, nameToMatrixParameterized) where import Complex import Expr import QMatrix -- |nameToMatrix takes a gate name and returns its matrix nameToMatrix :: (QCMatrix m a, Floating a, Fractional a) => String -> m (Complex a) nameToMatrix "not" = pauliX nameToMatrix "X" = pauliX nameToMatrix "Y" = pauliY nameToMatrix "Z" = pauliZ nameToMatrix "H" = hadamard nameToMatrix "W" = swapSqrt nameToMatrix "swap" = swap nameToMatrix n = error $ "Gate \"" ++ show n ++ "\" is not supported yet" nameToMatrixParameterized :: (QCMatrix m a, FromDouble a, Floating a) => String -> Double -> m (Complex a) nameToMatrixParameterized "R(2pi/%)" n = phaseShift (2 * pi / fromDouble n) nameToMatrixParameterized n _ = error $ "Parameterized gate \"" ++ show n ++ "\" is not supported yet"
miniBill/entangle
src/lib/GatesMatrices.hs
mit
911
0
10
200
240
124
116
19
1
{-| Module : MutableBloomFilterTest Description : QuickCheck tests for Mutable bloom filter -} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module MutableBloomFilterTest where import Control.Monad (liftM) import Control.Monad.ST (runST) import qualified Data.ByteString as S (ByteString) import qualified Data.ByteString.Lazy as L (ByteString) import Hash.Hash import qualified MutableBloomFilter as M import TestTypes -- an element that was inserted is always found prop_elem_inserted_always_exists :: Hashable a => FalsePositiveRate -> a -> Bool prop_elem_inserted_always_exists (FalsePositiveRate falsePositiveRate) element = runST $ M.fromList falsePositiveRate [element] >>= flip M.elem element -- filter count must be either equal to or smaller than the number of elements inserted -- (because the count will not be incremented for the elements ignored due to false -- positives) prop_filt_count_is_less_than_or_equal_num_elems_inserted :: LimitNumElems -> Bool prop_filt_count_is_less_than_or_equal_num_elems_inserted (LimitNumElems numElems) = runST $ M.fromList 0.01 testElems >>= liftM ((>=) (fromIntegral numElems)) . M.getCount where testElems = [1..numElems] -- make sure we generate unique elements to minimize false -- positives main :: IO () main = do runNTests 500 (prop_elem_inserted_always_exists :: FalsePositiveRate -> Char -> Bool) runNTests 500 (prop_elem_inserted_always_exists :: FalsePositiveRate -> Int -> Bool) runNTests 500 (prop_elem_inserted_always_exists :: FalsePositiveRate -> Float -> Bool) runNTests 500 (prop_elem_inserted_always_exists :: FalsePositiveRate -> Double -> Bool) runNTests 500 (prop_elem_inserted_always_exists :: FalsePositiveRate -> String -> Bool) runNTests 500 (prop_elem_inserted_always_exists :: FalsePositiveRate -> L.ByteString -> Bool) runNTests 500 (prop_elem_inserted_always_exists :: FalsePositiveRate -> S.ByteString -> Bool) runNTests 500 (prop_filt_count_is_less_than_or_equal_num_elems_inserted :: LimitNumElems -> Bool) --main = do -- let fp = 0.3080696608225276 -- n = 2100937750 :: Word32 -- --res :: Bool -- --res = runST $ (M.new fp n::ST s (M.MutableBloom s Int)) >>= (flip M.elem) 20 -- mbps = runST $ mutBitsPerSlice `fmap` (M.new fp n::ST s (M.MutableBloom s Int)) -- --print res -- print mbps -- res <- return $ (prop_elem_inserted_exists :: FalsePositiveRate -> String -> Bool) (FalsePositiveRate fp) "a" -- print res
neerajrao/scalable-bloom-filter-haskell
test/MutableBloomFilterTest.hs
mit
2,631
0
11
535
409
227
182
28
1
{-| Module : MasterPlan.Backend.Identity Description : a backend that renders to a text that can be parsed Copyright : (c) Rodrigo Setti, 2017 License : MIT Maintainer : rodrigosetti@gmail.com Stability : experimental Portability : POSIX -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} module MasterPlan.Backend.Identity (render) where import Control.Monad (when) import Control.Monad.RWS hiding (Product, Sum) import Data.List (intersperse) import qualified Data.List.NonEmpty as NE import Data.Monoid ((<>)) import qualified Data.Text as T import MasterPlan.Data type RenderMonad a = RWS [ProjAttribute] T.Text [(ProjectKey, Project a)] -- |Plain text renderer render ∷ Project a → [ProjAttribute] -> T.Text render proj whitelist = snd $ evalRWS (renderDefinition "root" proj) whitelist [] where renderDefinition key p = do tell $ T.pack key when (hasAttribute p) $ do tell " {\n" renderAttr p tell "}" case p of Atomic {} -> pure () Annotated {} -> pure () p' -> tell " " >> expression False p' tell "\n;" modify $ filter ((/= key) . fst) remainingBindings <- get case remainingBindings of [] -> pure () (k, p'):_ -> renderDefinition k p' expression :: Bool -> Project a -> RenderMonad a () expression parens p@(Product _ ps) = maybeBinding p $ combinedE parens "*" ps expression parens p@(Sequence _ ps) = maybeBinding p $ combinedE parens "->" ps expression parens p@(Sum _ ps) = maybeBinding p $ combinedE parens "+" ps expression _ p@Atomic {} = maybeBinding p $ tell $ T.pack $ mkKey p expression _ _ = pure () maybeBinding :: Project a -> RenderMonad a () -> RenderMonad a () maybeBinding p action | hasAttribute p = let key = mkKey p in modify ((key, p):) >> tell (T.pack key) | otherwise = action mkKey :: Project a -> String mkKey (Annotated _) = "?" mkKey (Product props _) = maybe "?" toId $ title props mkKey (Sequence props _) = maybe "?" toId $ title props mkKey (Sum props _) = maybe "?" toId $ title props mkKey (Atomic props _ _ _) = maybe "?" toId $ title props toId :: String -> String toId = mconcat . words combinedE :: Bool -> T.Text -> NE.NonEmpty (Project a) -> RenderMonad a () combinedE parens op ps = let sube = expression True <$> NE.toList ps s = sequence_ $ intersperse (tell $ " " <> op <> " ") sube in if parens && length ps > 1 then tell "(" >> s >> tell ")" else s hasAttribute (Annotated _) = False hasAttribute (Product props _) = hasProperty props hasAttribute (Sequence props _) = hasProperty props hasAttribute (Sum props _) = hasProperty props hasAttribute (Atomic props c t p) = hasProperty props || c /= defaultCost || t /= defaultTrust || p /= defaultProgress hasProperty props = isNonEmpty (title props) || isNonEmpty (description props) || isNonEmpty (owner props) || isNonEmpty (url props) isNonEmpty Nothing = False isNonEmpty (Just "") = False isNonEmpty (Just _) = True percentage n = T.pack $ show (n * 100) <> "%" renderAttr (Annotated _) = pure () renderAttr (Product props _) = renderProps props renderAttr (Sequence props _) = renderProps props renderAttr (Sum props _) = renderProps props renderAttr (Atomic props c t p) = do renderProps props when (c /= defaultCost) $ tell $ "cost " <> T.pack (show $ getCost c) <> "\n" when (t /= defaultTrust) $ tell $ "trust " <> percentage (getTrust t) <> "\n" when (p /= defaultProgress) $ tell $ "progress " <> percentage (getProgress p) <> "\n" renderProps :: ProjectProperties -> RenderMonad a () renderProps p = do let maybeRender :: T.Text -> Maybe String -> RenderMonad a () maybeRender _ Nothing = pure () maybeRender _ (Just "") = pure () maybeRender n (Just x) = tell $ n <> " " <> T.pack (show x) <> "\n" maybeRender "title" (title p) maybeRender "description" (description p) maybeRender "url" (url p) maybeRender "owner" (owner p)
rodrigosetti/master-plan
src/MasterPlan/Backend/Identity.hs
mit
4,769
0
16
1,653
1,578
770
808
89
25