code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{- |
Module : Bracket
Description : Handling multiple environments with bracket-like apis
Maintainer : robertkennedy@clearwateranalytics.com
Stability : stable
This module is meant for ie Sql or mongo connections, where you may wish for some number of easy to grab
environments. In particular, this assumes your connection has some initialization/release functions
This module creates bugs with any optimizations enabled. The bugs do not occur if the program is in the same
module.
-}
module T13916_Bracket (
-- * Data Types
Spawner(..), Limit(..), Cache,
-- * Usage
withEnvCache, withEnv
) where
import Control.Concurrent.STM
import Control.Concurrent.STM.TSem
import Control.Exception hiding (handle)
import Control.Monad
import Data.Vector (Vector)
import qualified Data.Vector as Vector
-- * Data Types
-- | Tells the program how many environments it is allowed to spawn.
-- A `Lax` limit will spawn extra connections if the `Cache` is empty,
-- while a `Hard` limit will not spawn any more than the given number of connections simultaneously.
--
-- @since 0.3.7
data Limit = Hard {getLimit :: {-# unpack #-} !Int}
data Spawner env = Spawner
{ maker :: IO env
, killer :: env -> IO ()
, isDead :: env -> IO Bool
}
type VCache env = Vector (TMVar env)
data Cache env = Unlimited { spawner :: Spawner env
, vcache :: !(VCache env)
}
| Limited { spawner :: Spawner env
, vcache :: !(VCache env)
, envsem :: TSem
}
-- ** Initialization
withEnvCache :: Limit -> Spawner env -> (Cache env -> IO a) -> IO a
withEnvCache limit spawner = bracket starter releaseCache
where starter = case limit of
Hard n -> Limited spawner <$> initializeEmptyCache n <*> atomically (newTSem n)
-- ** Using a single value
withEnv :: Cache env -> (env -> IO a) -> IO a
withEnv cache = case cache of
Unlimited{..} -> withEnvUnlimited spawner vcache
Limited{..} -> withEnvLimited spawner vcache envsem
-- *** Unlimited
-- | Takes an env and returns it on completion of the function.
-- If all envs are already taken or closed, this will spin up a new env.
-- When the function finishes, this will attempt to put the env into the cache. If it cannot,
-- it will kill the env. Note this can lead to many concurrent connections.
--
-- @since 0.3.5
withEnvUnlimited :: Spawner env -> VCache env -> (env -> IO a) -> IO a
withEnvUnlimited Spawner{..} cache = bracket taker putter
where
taker = do
mpipe <- atomically $ tryTakeEnv cache
case mpipe of
Nothing -> maker
Just env -> isDead env >>= \b -> if not b then return env else killer env >> maker
putter env = do
accepted <- atomically $ tryPutEnv cache env
unless accepted $ killer env
-- *** Limited
-- | Takes an env and returns it on completion of the function.
-- If all envs are already taken, this will wait. This should have a constant number of environments
--
-- @since 0.3.6
withEnvLimited :: Spawner env -> VCache env -> TSem -> (env -> IO a) -> IO a
withEnvLimited spawner vcache envsem = bracket taker putter
where
taker = limitMakeEnv spawner vcache envsem
putter env = atomically $ putEnv vcache env
limitMakeEnv :: Spawner env -> VCache env -> TSem -> IO env
limitMakeEnv Spawner{..} vcache envsem = go
where
go = do
eenvpermission <- atomically $ ( Left <$> takeEnv vcache )
`orElse` ( Right <$> waitTSem envsem )
case eenvpermission of
Right () -> maker
Left env -> do
-- Given our env, we check if it's dead. If it's not, we are done and return it.
-- If it is dead, we release it, signal that a new env can be created, and then recurse
isdead <- isDead env
if not isdead then return env
else do
killer env
atomically $ signalTSem envsem
go
-- * Low level
initializeEmptyCache :: Int -> IO (VCache env)
initializeEmptyCache n | n < 1 = return mempty
| otherwise = Vector.replicateM n newEmptyTMVarIO
takeEnv :: VCache env -> STM env
takeEnv = Vector.foldl folding retry
where folding m stmenv = m `orElse` takeTMVar stmenv
tryTakeEnv :: VCache env -> STM (Maybe env)
tryTakeEnv cache = (Just <$> takeEnv cache) `orElse` pure Nothing
putEnv :: VCache env -> env -> STM ()
putEnv cache env = Vector.foldl folding retry cache
where folding m stmenv = m `orElse` putTMVar stmenv env
tryPutEnv :: VCache env -> env -> STM Bool
tryPutEnv cache env = (putEnv cache env *> return True) `orElse` pure False
releaseCache :: Cache env -> IO ()
releaseCache cache = Vector.mapM_ qkRelease (vcache cache)
where qkRelease tenv = atomically (tryTakeTMVar tenv)
>>= maybe (return ()) (killer $ spawner cache)
| ezyang/ghc | testsuite/tests/concurrent/should_run/T13916_Bracket.hs | bsd-3-clause | 5,114 | 0 | 18 | 1,407 | 1,190 | 608 | 582 | 79 | 3 |
x = "abc"
main = print x
| ghc-android/ghc | testsuite/tests/ghci/scripts/T9367.hs | bsd-3-clause | 27 | 0 | 5 | 9 | 14 | 7 | 7 | 2 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module T5597a where
import Language.Haskell.TH
f :: Q Type -> Q Exp
f t = [| (3,4) :: $t |]
| wxwxwwxxx/ghc | testsuite/tests/th/T5597a.hs | bsd-3-clause | 126 | 0 | 6 | 25 | 37 | 22 | 15 | 5 | 1 |
module TH_lookupName_Lib where
import Language.Haskell.TH
f :: String
f = "TH_lookupName_Lib.f"
lookup_f :: Q Exp
lookup_f = do { Just n <- lookupValueName "f"; varE n }
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/th/TH_lookupName_Lib.hs | bsd-3-clause | 173 | 0 | 8 | 30 | 55 | 30 | 25 | 6 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module CFDI.Types.Type where
import Control.Error.Safe (justErr)
import Data.Bifunctor (first)
import Data.Ratio (denominator, numerator)
import Data.Text (Text, pack, unpack)
import Data.Text.Read (rational)
import Data.Time.LocalTime (LocalTime)
import Data.Time.Format (defaultTimeLocale, formatTime, parseTimeM)
import Numeric (fromRat, showFFloat)
data ParseError
= InvalidValue String
| DoesNotMatchExpr String
| NotInCatalog
deriving (Eq, Show)
class Type t where
parse :: String -> Either ParseError t
parse = parseExpr . sanitize
parseExpr :: String -> Either ParseError t
render :: t -> String
instance Type LocalTime where
parseExpr = justErr (DoesNotMatchExpr expr)
. parseTimeM True defaultTimeLocale "%Y-%m-%dT%H:%M:%S"
where
expr = "(20[1-9][0-9])-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T(([01]\
\[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9])"
render = formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S"
instance Type Rational where
parseExpr e = first (const $ InvalidValue e) . fmap fst . rational $ pack e
render r
| denominator r == 1 = show $ numerator r
| otherwise = showFFloat Nothing (fromRat r :: Double) ""
instance Type Text where
parseExpr = Right . pack
render = unpack
sanitize :: String -> String
sanitize = collapse . removePipes
where
collapse = unwords . words
removePipes = filter (/= '|')
| yusent/cfdis | src/CFDI/Types/Type.hs | mit | 1,489 | 0 | 12 | 316 | 404 | 219 | 185 | 37 | 1 |
module Main where
import Test.DocTest
main :: IO ()
main = doctest ["Boggle.hs"]
| jmitchell/boggle | test/doctests.hs | mit | 83 | 0 | 6 | 15 | 30 | 17 | 13 | 4 | 1 |
module Words where
-----------------------------------------------------------------------------
import qualified Data.HashMap as HashMap
-----------------------------------------------------------------------------
followers :: String -> [String] -> [String]
followers string = followers' []
where followers' fs (x:y:xs)
| x == string = followers' (fs ++ [y]) xs
followers' fs (_:xs) = followers' fs xs
followers' fs [] = fs
followerCounts :: [String] -> HashMap.Map String Integer
followerCounts xs = foldr (HashMap.adjust (+1)) initCounts xs
where initCounts = HashMap.fromList $ map (\x -> (x, 0)) xs
| hawkw/wordfreq | src/Words.hs | mit | 657 | 0 | 11 | 126 | 206 | 111 | 95 | 11 | 3 |
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Generics.K.FromK
-- Copyright : (c) David Lazar, 2011
-- License : MIT
--
-- Maintainer : lazar6@illinois.edu
-- Stability : experimental
-- Portability : unknown
--
-- Convert K terms to 'Data' values.
-----------------------------------------------------------------------------
module Data.Generics.K.FromK where
import Data.Char (chr)
import Data.Generics
import Text.Printf
import Language.K.Core.Syntax
import Language.Haskell.Exts.Syntax -- Issue 198 (see below)
import Control.Monad.Instances -- fix for earlier versions of base
fromK :: (Data a) => K -> a
fromK = defaultFromK
`extR` kToInt
`extR` kToInteger
`extR` kToBool
`extR` kToString
`extR` kToChar
`extR` kToLiteral -- Issue 198 (see below)
`extR` kToExp
kToExp :: K -> Exp
kToExp (KApp (KLabel (Syntax "ListExp" : _)) ks) = fromConstrK (toConstr (List [])) ks
kToExp k = defaultFromK k
-- Workaround for Issue 198 in K.
kToLiteral :: K -> Literal
kToLiteral (KApp (KLabel (Syntax "IntLit" : _)) [KApp (KInt i) []]) = Int i
kToLiteral (KApp (KLabel (Syntax "StringLit" : _)) [KApp (KString s) []]) = String s
kToLiteral k = defaultFromK k
kToInt :: K -> Int
kToInt (KApp (KInt i) []) = fromIntegral i
kToInteger :: K -> Integer
kToInteger (KApp (KInt i) []) = i
kToBool :: K -> Bool
kToBool (KApp (KBool b) []) = b
kToString :: K -> String
kToString (KApp (KString s) []) = s
kToChar :: K -> Char
kToChar (KApp (KInt i) []) = chr (fromIntegral i)
defaultFromK :: forall a. (Data a) => K -> a
defaultFromK (KApp (KLabel ((Syntax conStr) : _)) ks) =
let dataType = dataTypeOf (undefined :: a)
-- TODO: better error handling:
con = either error id $ str2con dataType conStr
in fromConstrK con ks
-- There's probably a better way to do this:
data KS x = KS { ks :: [K] , unKS :: x }
fromConstrK :: (Data a) => Constr -> [K] -> a
fromConstrK c ks = unKS $ gunfold s z c
where
s :: forall b r. Data b => KS (b -> r) -> KS r
s (KS (k:ks) f) = KS ks (f $ fromK k)
z :: forall r. r -> KS r
z = KS ks
-- | Turn the given string into a constructor of the requested result type,
-- returning 'Left' if the string doesn't represent a constructor of this
-- data type.
str2con :: DataType -> String -> Either String Constr
str2con dataType conName =
case readConstr dataType conName of
Just con -> Right con
Nothing -> Left failString
where failString = printf formatString (show conName) (show dataType)
formatString = "Failed to parse %s as a constructor of type %s."
| davidlazar/generic-k | src/Data/Generics/K/FromK.hs | mit | 2,721 | 0 | 13 | 598 | 867 | 466 | 401 | 53 | 2 |
{-# LANGUAGE CPP #-}
{-|
Definitions of lazy Deque.
The typical `toList` and `fromList` conversions are provided by means of
the `Foldable` and `IsList` instances.
-}
module Deque.Lazy.Defs
where
import Control.Monad (fail)
import Deque.Prelude hiding (tail, init, last, head, null, dropWhile, takeWhile, reverse, filter, take)
import qualified Data.List as List
import qualified Deque.Prelude as Prelude
-- |
-- Lazy double-ended queue (aka Dequeue or Deque) based on head-tail linked list.
data Deque a = Deque ![a] ![a]
-- |
-- \(\mathcal{O}(1)\).
-- Construct from cons and snoc lists.
fromConsAndSnocLists :: [a] -> [a] -> Deque a
fromConsAndSnocLists consList snocList = Deque consList snocList
-- |
-- \(\mathcal{O}(n)\).
-- Leave only the elements satisfying the predicate.
filter :: (a -> Bool) -> Deque a -> Deque a
filter predicate (Deque consList snocList) = Deque (List.filter predicate consList) (List.filter predicate snocList)
-- |
-- \(\mathcal{O}(n)\).
-- Leave only the specified amount of first elements.
take :: Int -> Deque a -> Deque a
take amount (Deque consList snocList) = let
newConsList = let
buildFromConsList amount = if amount > 0
then \ case
head : tail -> head : buildFromConsList (pred amount) tail
_ -> buildFromSnocList amount (List.reverse snocList)
else const []
buildFromSnocList amount = if amount > 0
then \ case
head : tail -> head : buildFromSnocList (pred amount) tail
_ -> []
else const []
in buildFromConsList amount consList
in Deque newConsList []
-- |
-- \(\mathcal{O}(n)\).
-- Drop the specified amount of first elements.
drop :: Int -> Deque a -> Deque a
drop amount (Deque consList snocList) = let
buildFromConsList amount = if amount > 0
then \ case
_ : tail -> buildFromConsList (pred amount) tail
_ -> buildFromSnocList amount (List.reverse snocList)
else \ tail -> Deque tail snocList
buildFromSnocList amount = if amount > 0
then \ case
_ : tail -> buildFromSnocList (pred amount) tail
_ -> Deque [] []
else \ tail -> Deque tail []
in buildFromConsList amount consList
-- |
-- \(\mathcal{O}(n)\).
-- Leave only the first elements satisfying the predicate.
takeWhile :: (a -> Bool) -> Deque a -> Deque a
takeWhile predicate (Deque consList snocList) = let
newConsList = List.foldr
(\ a nextState -> if predicate a
then a : nextState
else [])
(List.takeWhile predicate (List.reverse snocList))
consList
in Deque newConsList []
-- |
-- \(\mathcal{O}(n)\).
-- Drop the first elements satisfying the predicate.
dropWhile :: (a -> Bool) -> Deque a -> Deque a
dropWhile predicate (Deque consList snocList) = let
newConsList = List.dropWhile predicate consList
in case newConsList of
[] -> Deque (List.dropWhile predicate (List.reverse snocList)) []
_ -> Deque newConsList snocList
-- |
-- \(\mathcal{O}(n)\).
-- Perform `takeWhile` and `dropWhile` in a single operation.
span :: (a -> Bool) -> Deque a -> (Deque a, Deque a)
span predicate (Deque consList snocList) = case List.span predicate consList of
(consPrefix, consSuffix) -> if List.null consSuffix
then case List.span predicate (List.reverse snocList) of
(snocPrefix, snocSuffix) -> let
prefix = Deque (consPrefix <> snocPrefix) []
suffix = Deque snocSuffix []
in (prefix, suffix)
else let
prefix = Deque consPrefix []
suffix = Deque consSuffix snocList
in (prefix, suffix)
-- |
-- \(\mathcal{O}(1)\), occasionally \(\mathcal{O}(n)\).
-- Move the first element to the end.
--
-- @
-- λ toList . shiftLeft $ fromList [1,2,3]
-- [2,3,1]
-- @
shiftLeft :: Deque a -> Deque a
shiftLeft deque = maybe deque (uncurry snoc) (uncons deque)
-- |
-- \(\mathcal{O}(1)\), occasionally \(\mathcal{O}(n)\).
-- Move the last element to the beginning.
--
-- @
-- λ toList . shiftRight $ fromList [1,2,3]
-- [3,1,2]
-- @
shiftRight :: Deque a -> Deque a
shiftRight deque = maybe deque (uncurry cons) (unsnoc deque)
-- |
-- \(\mathcal{O}(1)\).
-- Add element in the beginning.
cons :: a -> Deque a -> Deque a
cons a (Deque consList snocList) = Deque (a : consList) snocList
-- |
-- \(\mathcal{O}(1)\).
-- Add element in the ending.
snoc :: a -> Deque a -> Deque a
snoc a (Deque consList snocList) = Deque consList (a : snocList)
-- |
-- \(\mathcal{O}(1)\), occasionally \(\mathcal{O}(n)\).
-- Get the first element and deque without it if it's not empty.
uncons :: Deque a -> Maybe (a, Deque a)
uncons (Deque consList snocList) = case consList of
head : tail -> Just (head, Deque tail snocList)
_ -> case List.reverse snocList of
head : tail -> Just (head, Deque tail [])
_ -> Nothing
-- |
-- \(\mathcal{O}(1)\), occasionally \(\mathcal{O}(n)\).
-- Get the last element and deque without it if it's not empty.
unsnoc :: Deque a -> Maybe (a, Deque a)
unsnoc (Deque consList snocList) = case snocList of
head : tail -> Just (head, Deque consList tail)
_ -> case List.reverse consList of
head : tail -> Just (head, Deque [] tail)
_ -> Nothing
-- |
-- \(\mathcal{O}(n)\).
prepend :: Deque a -> Deque a -> Deque a
prepend (Deque consList1 snocList1) (Deque consList2 snocList2) = let
consList = consList1
snocList = snocList2 ++ foldl' (flip (:)) snocList1 consList2
in Deque consList snocList
-- |
-- \(\mathcal{O}(1)\).
-- Reverse the deque.
reverse :: Deque a -> Deque a
reverse (Deque consList snocList) = Deque snocList consList
-- |
-- \(\mathcal{O}(1)\).
-- Check whether deque is empty.
null :: Deque a -> Bool
null (Deque consList snocList) = List.null snocList && List.null consList
-- |
-- \(\mathcal{O}(1)\), occasionally \(\mathcal{O}(n)\).
-- Get the first element if deque is not empty.
head :: Deque a -> Maybe a
head = fmap fst . uncons
-- |
-- \(\mathcal{O}(1)\), occasionally \(\mathcal{O}(n)\).
-- Keep all elements but the first one.
--
-- In case of empty deque returns an empty deque.
tail :: Deque a -> Deque a
tail = fromMaybe <$> id <*> fmap snd . uncons
-- |
-- \(\mathcal{O}(1)\), occasionally \(\mathcal{O}(n)\).
-- Keep all elements but the last one.
--
-- In case of empty deque returns an empty deque.
init :: Deque a -> Deque a
init = fromMaybe <$> id <*> fmap snd . unsnoc
-- |
-- \(\mathcal{O}(1)\), occasionally \(\mathcal{O}(n)\).
-- Get the last element if deque is not empty.
last :: Deque a -> Maybe a
last = fmap fst . unsnoc
instance Eq a => Eq (Deque a) where
(==) a b = toList a == toList b
instance Show a => Show (Deque a) where
show = show . toList
instance Semigroup (Deque a) where
(<>) = prepend
instance Monoid (Deque a) where
mempty =
Deque [] []
mappend =
(<>)
instance Foldable Deque where
foldr step init (Deque consList snocList) = foldr step (foldl' (flip step) init snocList) consList
foldl' step init (Deque consList snocList) = foldr' (flip step) (foldl' step init consList) snocList
instance Traversable Deque where
traverse f (Deque cs ss) =
(\cs' ss' -> Deque cs' (List.reverse ss')) <$> traverse f cs <*> traverse f (List.reverse ss)
deriving instance Functor Deque
instance Applicative Deque where
pure a = Deque [] [a]
(<*>) (Deque fnConsList fnSnocList) (Deque argConsList argSnocList) = let
consList = let
fnStep fn resultConsList = let
argStep arg = (:) (fn arg)
in foldr argStep (foldr argStep resultConsList (List.reverse argSnocList)) argConsList
in foldr fnStep (foldr fnStep [] (List.reverse fnSnocList)) fnConsList
in Deque consList []
instance Monad Deque where
return = pure
(>>=) (Deque aConsList aSnocList) k = let
consList = let
aStep a accBConsList = case k a of
Deque bConsList bSnocList -> bConsList <> foldl' (flip (:)) accBConsList bSnocList
in foldr aStep (foldr aStep [] (List.reverse aSnocList)) aConsList
in Deque consList []
#if !(MIN_VERSION_base(4,13,0))
fail = const mempty
#endif
instance Alternative Deque where
empty = mempty
(<|>) = mappend
instance MonadPlus Deque where
mzero = empty
mplus = (<|>)
instance MonadFail Deque where
fail = const mempty
-- |
-- \(\mathcal{O}(1)\).
instance IsList (Deque a) where
type Item (Deque a) = a
fromList = flip Deque []
toList (Deque consList snocList) = consList <> List.reverse snocList
deriving instance Generic (Deque a)
deriving instance Generic1 Deque
instance Hashable a => Hashable (Deque a)
instance NFData a => NFData (Deque a)
instance NFData1 Deque
| nikita-volkov/deque | library/Deque/Lazy/Defs.hs | mit | 8,493 | 0 | 21 | 1,742 | 2,591 | 1,334 | 1,257 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE RankNTypes #-}
module Data.Extensible.Product2F where
import Data.Typeable
import Data.Extensible.Type
import Data.Extensible.Sum(AltLoc(..))
import Data.Monoid
import Data.Promotion.Prelude.List
import Data.Extensible.Product
import Data.Extensible.Sum2F
data Interp2F g f = Interp2F (forall a' b' . f g a' b' -> g a' b')
data HK2FList k (p :: [(* -> * -> *) -> * -> * -> *]) where
HK2FCons :: k x -> HK2FList k xs -> HK2FList k (x ': xs)
HK2FNil :: HK2FList k '[]
infixr 5 #:
(#:) :: (forall a' b' . x g a' b' -> g a' b')
-> HK2FList (Interp2F g) xs
-> HK2FList (Interp2F g) (x ': xs)
(#:) fxn rest = HK2FCons (Interp2F fxn) rest
| jadaska/extensible-sp | src/Data/Extensible/Product2F.hs | mit | 1,018 | 6 | 11 | 170 | 291 | 171 | 120 | 29 | 1 |
module Main where
import Data.Maybe (listToMaybe)
import System.Environment (getArgs)
import Hello (hello)
main :: IO ()
main = do
name <- listToMaybe `fmap` getArgs
putStrLn $ hello $ maybe "Haskell" id name
| kagamilove0707/learn-cabal | Main.hs | mit | 220 | 0 | 8 | 43 | 78 | 43 | 35 | 8 | 1 |
module GHCJS.TypeScript.Convert.Collect (collect) where
import qualified Data.Map as M
import Data.Monoid
import GHCJS.TypeScript.Convert.Munge
import GHCJS.TypeScript.Convert.Types
import GHCJS.TypeScript.Convert.Util
import Language.TypeScript
collect :: [DeclarationElement] -> M.Map ModuleName (M.Map String Decl)
collect des =
-- Move declaration name into an inner map.
M.mapKeysWith M.union fst $
M.map (uncurry M.singleton) $
-- Combine declarations by concatenating their members.
M.fromListWith (\(k, x) (_, y) -> (k, combine x y)) $
map (\(mn, decl) -> ((mn, declName decl), (declName decl, decl))) $
concatMap collectDeclarationElement des
combine :: Decl -> Decl -> Decl
combine (InterfaceDecl (Interface cp1 name mparams1 mrefs1 (TypeBody body1)))
(InterfaceDecl (Interface cp2 _ mparams2 mrefs2 (TypeBody body2))) =
-- FIXME: bring back this check once there's a good way to equality compare these
--
-- if mparams1 /= mparams2 || mrefs1 /= mrefs2
-- then error $ "Mismatched signatures in declarations for " ++ name
-- else
InterfaceDecl $ Interface cp1 name mparams1 mrefs1 $ TypeBody $ body1 ++ body2
declName :: Decl -> String
declName (InterfaceDecl (Interface _ name _ _ _)) = name
collectDeclarationElement :: DeclarationElement -> [(ModuleName, Decl)]
collectDeclarationElement (AmbientDeclaration _ _ ambient) =
collectAmbientDeclaration (ModuleName []) ambient
collectDeclarationElement (InterfaceDeclaration _ _ iface) =
[collectInterface (ModuleName []) iface]
collectDeclarationElement x =
skip x
collectAmbientDeclaration :: ModuleName -> Ambient -> [(ModuleName, Decl)]
collectAmbientDeclaration mn (AmbientModuleDeclaration _ names decls) =
concatMap (collectAmbientDeclaration (mn <> ModuleName names)) decls
collectAmbientDeclaration mn (AmbientExternalModuleDeclaration _ name xs) =
concatMap (collectAmbientExternalModuleElement (mn <> ModuleName [capitalize name])) xs
collectAmbientDeclaration mn (AmbientInterfaceDeclaration iface) =
[collectInterface mn iface]
collectAmbientDeclaration mn (AmbientClassDeclaration cp name typarams tyrefs1 tyrefs2 body) =
--TODO: what are tyrefs1 / tyrefs2?
[collectInterface mn $
Interface cp name typarams tyrefs1 (TypeBody (map (\(cp, cbe) -> (cp, classBodyElementToTypeMember cbe)) body))]
collectAmbientDeclaration _ x = skip x
collectAmbientExternalModuleElement :: ModuleName -> AmbientExternalModuleElement -> [(ModuleName, Decl)]
collectAmbientExternalModuleElement mn (AmbientModuleElement ambient) =
collectAmbientDeclaration mn ambient
collectAmbientExternalModuleElement _ x = skip x
-- TODO: revisit spec - I'm thinking the interface for a class doesn't
-- have the class's constructor.
classBodyElementToTypeMember :: AmbientClassBodyElement -> TypeMember
classBodyElementToTypeMember (AmbientConstructorDeclaration params) =
ConstructSignature Nothing params Nothing
classBodyElementToTypeMember (AmbientMemberDeclaration mpublicOrPrivate mstatic name fieldOrFunc) =
case fieldOrFunc of
Left field -> PropertySignature name Nothing field
Right func -> MethodSignature name Nothing func
classBodyElementToTypeMember (AmbientIndexSignature indexSig) =
TypeIndexSignature indexSig
collectInterface :: ModuleName -> Interface -> (ModuleName, Decl)
collectInterface mn iface = (mn, InterfaceDecl iface)
| mgsloan/ghcjs-typescript | ghcjs-typescript-convert/GHCJS/TypeScript/Convert/Collect.hs | mit | 3,420 | 0 | 15 | 517 | 880 | 465 | 415 | 53 | 2 |
{-# htermination liftM3 :: (a -> b -> c -> d) -> ([] a -> [] b -> [] c -> [] d) #-}
import Monad
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Monad_liftM3_2.hs | mit | 97 | 0 | 3 | 26 | 5 | 3 | 2 | 1 | 0 |
{-# LANGUAGE OverloadedStrings#-}
{-# LANGUAGE TemplateHaskell #-}
module Web.Twitter.PleaseCaption.Replies (getReminderText) where
import Control.Monad.IO.Class (liftIO, MonadIO(..))
import Data.Text (Text)
import Data.Random.Extras (choice)
import Data.Random.RVar (runRVar)
import Data.Random.Source.DevRandom (DevRandom(DevURandom))
import Web.Twitter.PleaseCaption.Replies.Assert (assertAllLength)
reminders :: [Text]
-- Warning! Can't be more than 132 characters
reminders = $(assertAllLength 132
[ "please don't forget to caption your tweets!"
, "hey, this tweet's images don't all have alt text!"
, "psst, you missed the alt text in this tweet"
, "this tweet's images don't have alt text, please add some next time!"
, "visually-impaired people may have trouble seeing this tweet, please add captions!"
, "please remember to caption your images, it makes twitter more accessible!"
, "hey, please add alt text to your images next time"
, "this tweet is pretty cool, but you know what's even cooler? alt text"
, "help make twitter more accessible by adding descriptions to your images!"
-- add more here!
])
getReminderText :: (MonadIO m) => m Text
getReminderText = liftIO $ runRVar (choice reminders) DevURandom
| stillinbeta/pleasecaption | src/Web/Twitter/PleaseCaption/Replies.hs | mit | 1,247 | 0 | 8 | 194 | 183 | 115 | 68 | 22 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecursiveDo #-}
-- | Dynamics and events related to actions on scenario objects
module Program.Scenario.Object
( QEventTag (..)
, objectSelectionsDyn
, colorObjectsOnSelection
, moveSelectedObjects
) where
import Commons
--import qualified Data.Map.Strict as Map
import Data.Maybe (isJust, maybeToList, mapMaybe, fromMaybe)
import Data.Foldable (foldl')
import Reflex
import Reflex.Dom.Widget.Animation (AnimationHandler)
import qualified Reflex.Dom.Widget.Animation as Animation
import Control.Lens
import Control.Applicative ((<|>))
import Numeric.DataFrame (fromHom, eye, fromScalar) -- Mat44f, (%*))
import qualified QuaTypes
import Model.Camera (Camera)
import Model.Scenario (Scenario)
import qualified Model.Scenario as Scenario
import Model.Scenario.Object (ObjectId (..))
import qualified Model.Scenario.Object as Object
import Model.Scenario.Properties
import Program.UserAction
import Program.Camera
import Program.Scenario
import qualified SmallGL
--import qualified SmallGL.Types as SmallGL
-- | Selected object id events.
-- They happen when user clicks on a canvas;
-- Either some object is selected, or nothing (clicked on empty or non-selectable space).
-- The dynamic returned is guaranteed to change on every update.
objectSelectionsDyn :: Reflex t
=> AnimationHandler t
-> SmallGL.RenderingApi
-> QuaWidget t x (Dynamic t (Maybe ObjectId))
objectSelectionsDyn aHandler renderingApi = do
autoSelectE <- askEvent $ UserAction AskSelectObject
selectorClickE <- performEvent $ getClicked renderingApi
<$> Animation.downPointersB aHandler
<@ select (Animation.pointerEvents aHandler) PClickEvent
selIdD <- accumMaybe (\i j -> if i == j then Nothing else Just j)
Nothing $ leftmost [ selectorClickE, autoSelectE ]
logDebugEvents' @JSString "Program.Scenario.Object" $ (,) "selectedObjId" . Just <$> updated selIdD
return selIdD
-- | Color objects when they are selected or unselected.
colorObjectsOnSelection :: Reflex t
=> Behavior t Scenario
-> Dynamic t (Maybe ObjectId)
-> QuaViewM t ()
colorObjectsOnSelection scB selObjD =
registerEvent (SmallGLInput SmallGL.SetObjectColor) . nonEmptyOnly
$ ( \scenario oldOId newOId ->
do
(i, mainObj) <- getObj scenario oldOId
obj <- mainObj : getGroup i scenario mainObj
return ( obj^.Object.renderingId
, Scenario.resolvedObjectColor scenario obj ^. colorVeci )
<>
do
(i, mainObj) <- getObj scenario newOId
( mainObj^.Object.renderingId
, selectedColor scenario $ mainObj^.Object.objectBehavior )
: do
obj <- getGroup i scenario mainObj
return ( obj^.Object.renderingId
, scenario^.Scenario.selectedGroupColor.colorVeci
)
)
<$> scB <*> current selObjD <@> updated selObjD
where
getObj scenario moid = maybeToList $ moid >>= \i -> (,) i <$> scenario ^. Scenario.objects . at i
getGroup j scenario obj = maybeToList (obj^.Object.groupID)
>>= (\i -> scenario^..Scenario.viewState
.Scenario.objectGroups
.at i._Just
.to (filter (j /=))
.traverse)
>>= (\i -> scenario^..Scenario.objects.at i._Just)
selectedColor sc Object.Dynamic = sc^.Scenario.selectedDynamicColor.colorVeci
selectedColor sc Object.Static = sc^.Scenario.selectedStaticColor.colorVeci
{- | Move objects when they are selected and dragged.
This function must be quite complicated, because we have to update object geometry only on
end-of-transform events to avoid object shivering and other graphics artifacts and make object
motion more stable (pointer-move events are too often, which leads to all sorts of these problems).
Therefore, we have to keep a snapshot of object geometry everytime we select an object.
Thus, on every pointer-move we can update visual position of an object (in webgl) while not
touching the real recorded object position.
Then, on pointer-up event we update real position with a well-defined transform matrix.
This monadic function consists of several steps:
1. Record (as a behavior) center of the last selected group of objects (used for rotation).
2. Use `objectTransformEvents` when selected object dynamic is not Nothing.
3. Ask SmallGL to take snapshots of geometry on checkpoint events.
4. Ask SmallGL to temporary update geometry on pointer-move events.
5. Persist changes on checkpoint events by firing ObjectLocationUpdated events
(and event consumer (Program.Scenario) should ask SmallGL to update geometry one more time)
6. Return bool behavior whether camera should be locked by object actions
-}
moveSelectedObjects :: Reflex t
=> AnimationHandler t
-> SmallGL.RenderingApi
-> Behavior t Camera
-> Behavior t Scenario
-> Dynamic t (Maybe ObjectId)
-> QuaViewM t (Behavior t Bool)
moveSelectedObjects aHandler renderingApi cameraB scenarioB selObjIdD = do
canMove <- fmap (not . QuaTypes.isViewerOnly . QuaTypes.permissions) <$> quaSettings
-- if the object is pointerDown'ed
let downsE = gate (current canMove)
$ push (fmap Just . getClicked renderingApi)
$ Animation.curPointersB aHandler
<@ gate -- track pointer-downs only when an object is selected and dynamic
((\mo -> mo ^? _Just . Object.objectBehavior == Just Object.Dynamic) <$> selectedObjB)
(select (Animation.pointerEvents aHandler) PDownEvent)
-- We lock camera movemement and activate object transform when a pointer is down on a selected
-- object. If there are more than one pointer, we reset object motion every up or down event
-- to change motion mode correcty. However, if camera is not locked before pointer up event,
-- the event should not fire to avoid unnecessary trivial geometry updates.
rec camLockedD <- holdDyn False camLockedE
ptrNB <- accum (&) (0 :: Int)
$ leftmost [ (+1) <$ downsE
, (\n -> max 0 (n-1)) <$ upsE
, (\n -> max 0 (n-1)) <$ clicksE
, (const 0 :: Int -> Int) <$ cancelsE
]
let upsE = select (Animation.pointerEvents aHandler) PUpEvent
clicksE = select (Animation.pointerEvents aHandler) PClickEvent
cancelsE = select (Animation.pointerEvents aHandler) PCancelEvent
downME = downF <$> ptrNB <*> current camLockedD <*> selectedGroupObjIdsB <@> downsE
downF :: Int -> Bool -> [ObjectId] -> Maybe ObjectId -> Maybe Bool
downF ptrN wasLocked wasSelected isPressed
| ptrN > 0 && wasLocked = Just True
| ptrN > 0 && not wasLocked = Nothing
| Just i <- isPressed
, i `elem` wasSelected = Just True
| otherwise = Nothing
clickME = upF <$> ptrNB <*> current camLockedD <@ clicksE
upME = upF <$> ptrNB <*> current camLockedD <@ upsE
upF :: Int -> Bool -> Maybe Bool
upF ptrN wasLocked
| wasLocked && ptrN > 1 = Just True
| wasLocked = Just False
| otherwise = Nothing
cancelME = cancelF <$> current camLockedD <@ cancelsE
cancelF wasLocked
| wasLocked = Just False
| otherwise = Nothing
camLockedE = fmapMaybe id $ leftmost [cancelME, upME, clickME, downME]
-- events of object transforms
let transformE = gate (current camLockedD)
$ leftmost
[ eye <$ updated camLockedD
, objectTransformEvents aHandler cameraB centerPosB
]
transformB <- hold eye transformE
-- Every time camera UNLOCKED event happens, or LOCKED->LOCKED event happens,
-- we need to persist current changes
let persistGeomChangeE = fmapMaybe id
$ (\oids m wasLocked -> if wasLocked && not (null oids)
then Just (oids,m) else Nothing )
<$> selectedGroupObjIdsB
<*> transformB
<*> current camLockedD
<@ updated camLockedD
registerEvent (ScenarioUpdate ObjectLocationUpdated) persistGeomChangeE
registerEvent (SmallGLInput SmallGL.PersistGeomTransforms)
$ (\s (is, m) -> (\o -> (o ^. Object.renderingId,m))
<$> mapMaybe (\i -> s ^. Scenario.objects . at i) is
)
<$> scenarioB
<@> persistGeomChangeE
registerEvent (SmallGLInput SmallGL.TransformObject)
$ nonEmptyOnly
$ (\ids m -> flip (,) m <$> ids)
<$> selectedRenderingIdsB <@> transformE
logDebugEvents' @JSString "Program.Object"
$ (,) "Camera-locked state:" . Just
<$> updated camLockedD
return $ current camLockedD
where
selectedObjB = (\s mi -> mi >>= \i -> s ^. Scenario.objects . at i)
<$> scenarioB <*> current selObjIdD
selectedGroupIdB = preview (_Just.Object.groupID._Just) <$> selectedObjB
selectedGroupObjIdsB = (\selOid s mi -> fromMaybe [] $
(mi >>= \i -> s ^. Scenario.viewState.Scenario.objectGroups.at i)
<|> fmap (:[]) selOid
)
<$> current selObjIdD <*> scenarioB <*> selectedGroupIdB
selectedGroupB = (\s is -> is >>= \i -> s ^.. Scenario.objects . at i . _Just)
<$> scenarioB <*> selectedGroupObjIdsB
selectedRenderingIdsB = map (view Object.renderingId) <$> selectedGroupB
-- find center position for correct rotation
centerPosB = (\cs -> foldl' (+) 0 cs / fromScalar (max 1 . fromIntegral $ length cs))
. map (fromHom . view Object.center)
<$> selectedGroupB
nonEmptyOnly :: Reflex t => Event t [a] -> Event t [a]
nonEmptyOnly = ffilter (not . null)
-- | Helper function to determine ObjectId of a currently hovered object.
getClicked :: MonadIO m => SmallGL.RenderingApi -> [(Double,Double)] -> m (Maybe ObjectId)
getClicked _ []
= pure Nothing
getClicked renderingApi ((x,y):xs)
= (fmap f . liftIO $ SmallGL.getHoveredSelId renderingApi (round x, round y))
-- try one more time
>>= \mi -> if isJust mi then pure mi else getClicked renderingApi xs
where
f oid = if oid == 0xFFFFFFFF then Nothing else Just (ObjectId oid)
| achirkin/qua-view | src/Program/Scenario/Object.hs | mit | 11,686 | 6 | 21 | 3,774 | 2,445 | 1,258 | 1,187 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Commands.Main where
-- import Commands.Playground
import System.Environment (getArgs)
main = mainWith =<< getArgs
mainWith = \case
_ -> return()
| sboosali/commands-core | sources/Commands/Main.hs | mit | 259 | 0 | 9 | 58 | 46 | 27 | 19 | 7 | 1 |
module Main
( main
) where
import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test)
main :: IO ()
main = defaultMain []
| danstiner/hfmt | test/pure/Spec.hs | mit | 222 | 0 | 6 | 66 | 60 | 36 | 24 | 7 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE FunctionalDependencies,
FlexibleInstances,
TypeSynonymInstances,
GeneralizedNewtypeDeriving,
DeriveDataTypeable #-}
{- |
This module exports a domain specific language for specifying policy
module policies. It is recommended that /all/ policy modules use this
code when specifying security policies as it simplifies auditing and
building trust in the authors. Policy modules are described in
"Hails.PolicyModule", which is a pre-required reading to this
module\'s documentation.
Consider creating a policy module where anybody can read and write
freely to the databse. In this databsae we wish to create a simple
user model collecting user names and passwords. This collection
\"users\" is also readable and writable by anybody. However, the
passwords must always belong to the named user. Specifically, only the
user (or policy module) may read and modify the password. This policy
is implemented below:
@
data UsersPolicyModule = UsersPolicyModuleTCB DCPriv
deriving Typeable
instance PolicyModule UsersPolicyModule where
'initPolicyModule' priv = do
'setPolicy' priv $ do
'database' $ do
'readers' '==>' 'unrestricted'
'writers' '==>' 'unrestricted'
'admins' '==>' this
'collection' \"users\" $ do
'access' $ do
'readers' '==>' 'unrestricted'
'writers' '==>' 'unrestricted'
'clearance' $ do
'secrecy' '==>' this
'integrity' '==>' 'unrestricted'
'document' $ \doc -> do
'readers' '==>' 'unrestricted'
'writers' '==>' 'unrestricted'
'field' \"name\" $ 'searchable'
'field' \"password\" $ 'labeled' $ \doc -> do
let user = \"name\" ``at`` doc :: String
'readers' '==>' this \\/ user
'writers' '==>' this \\/ user
return $ UsersPolicyModuleTCB priv
where this = 'privDesc' priv
@
Notice that the database is public, as described above, but only this
policy module may modify the internal collection names (as indicated
by the 'admin' keyword). Similarly the collection is publicly
accessible (as set with the 'access' keyword), and may contain data at
most as sensitve as the policy module can read (i.e., the
'clearance').
Documents retrieved from the \"users\" 'collection' are public (as
indicated by the 'document' data-dependent policy that sets the
'readers' and 'writers'). The 'field' \"name\" is 'searchable' (i.e.,
it is a 'SearchableField') and thus can be used in query predicates.
Conversely, the \"password\" 'field' is 'labeled' using a
data-dependent policy. Specifically the field is labed using the
\"name\" value contained in the document (i.e., the user\'s name):
hence only the user having the right privilege or the policy module
(@this@) may read and create such data.
-}
module Hails.PolicyModule.DSL (
setPolicy
-- * Label components (or roles)
, readers, secrecy
, writers, integrity
, unrestricted
, admins
, (==>), (<==)
-- * Creating databases label policies
, database
-- * Creating collection policies
, collection
, access
, clearance
, document
-- * Creating field policies
, field, searchable, key, labeled
) where
import Data.Maybe
import Data.List (isPrefixOf)
import Data.Map (Map)
import Data.Traversable (forM)
import Data.Typeable
import qualified Data.Map as Map
import qualified Data.Text as T
import Control.Applicative
import Control.Monad hiding (forM)
import Control.Monad.Trans
import Control.Monad.Trans.Reader hiding (ask)
import Control.Monad.Trans.State hiding (put, get)
import Control.Monad.Trans.Error
import Control.Monad.State.Class
import Control.Monad.Reader.Class
import Control.Exception
import LIO
import LIO.DCLabel
import Hails.PolicyModule
import Hails.Database
-- | Type denoting readers.
data Readers = Readers
instance Show Readers where show _ = "readers"
-- | Set secrecy component of the label, i.e., the principals that can
-- read.
readers, secrecy :: Readers
readers = Readers
secrecy = Readers
-- | Type denoting writers.
data Writers = Writers
instance Show Writers where show _ = "writers"
-- | Set integrity component of the label, i.e., the principals that can
-- write.
writers, integrity :: Writers
writers = Writers
integrity = Writers
-- | Used when setting integrity component of the collection-set label, i.e.,
-- the principals/administrators that can modify a database's underlying
-- collections.
data Admins = Admins
instance Show Admins where show _ = "admins"
-- | Synonym for 'Admins'.
admins :: Admins
admins = Admins
infixl 5 ==>, <==
-- | Class used for creating micro policies.
class MonadState s m => Role r s m where
-- | @r ==> c@ effectively states that role @r@ (i.e., 'readers',
-- 'writers', 'admins' must imply label component @c@).
(==>) :: (ToCNF c) => r -> c -> m ()
-- | Inverse implication. Purely provided for readability. The
-- direction is not relevant to the internal representation.
(<==) :: (ToCNF c) => r -> c -> m ()
(<==) = (==>)
--
--
--
-- | Type representing a database expression.
--
-- > database $ do
-- > readers ==> "Alice" \/ "Bob"
-- > writers ==> "Alice"
-- > admins ==> "Alice"
--
data DBExp = DBExp CNF CNF CNF
deriving Show
-- | Database expression solely contains a list of components.
type DBExpS = Map String CNF
-- | Database expression composition monad
newtype DBExpM a = DBExpM (ErrorT String (State DBExpS) a)
deriving (Monad, MonadState DBExpS, Functor, Applicative)
instance Role Readers DBExpS DBExpM where
_ ==> c = DBExpM $ do
s <- get
case Map.lookup (show readers) s of
Just _ -> fail "Database readers already specified."
Nothing -> put $ Map.insert (show readers) (toCNF c) s
instance Role Writers DBExpS DBExpM where
_ ==> c = DBExpM $ do
s <- get
case Map.lookup (show writers) s of
Just _ -> fail "Database writers already specified."
Nothing -> put $ Map.insert (show writers) (toCNF c) s
instance Role Admins DBExpS DBExpM where
_ ==> c = DBExpM $ do
s <- get
case Map.lookup (show admins) s of
Just _ -> fail "Database admins already specified."
Nothing -> put $ Map.insert (show admins) (toCNF c) s
-- | Create a database lebeling policy The policy must set the label
-- of the database, i.e., the 'readers' and 'writers'. Additionally it
-- must state the 'admins' that can modify the underlying collection-set
--
-- For example, the policy
--
-- > database $ do
-- > readers ==> "Alice" \/ "Bob" \/ "Clarice"
-- > writers ==> "Alice" \/ "Bob"
-- > admins ==> "Alice"
--
-- states that Alice, Bob, and Clarice can read from the database,
-- including the collections in the database (the 'readers' is used as
-- the secrecy component in the collection-set label). Only Alice or
-- Bob may, however, write to the database. Finally, only Alice can
-- add additional collections in the policy module code.
--
database :: DBExpM () -> PolicyExpM ()
database (DBExpM e) = do
s <- get
case Map.lookup "database" s of
Just _ -> fail "Database labels already set"
Nothing -> case evalState (runErrorT e') Map.empty of
Left err -> fail err
Right dbExp -> put $ Map.insert "database"
(PolicyDBExpT dbExp) s
where e' = do e
s <- get
r <- lookup' (show readers) s
w <- lookup' (show writers) s
a <- lookup' (show admins ) s
return $ DBExp r w a
lookup' k s = maybe (fail $ "Missing " ++ show k)
return $ Map.lookup k s
--------------------------------------------------------------
-- | Type representing a collection access label expression.
--
-- > access $ do
-- > readers ==> "Alice" \/ "Bob"
-- > writers ==> "Alice"
--
data ColAccExp = ColAccExp CNF CNF
deriving Show
-- | Access expression solely contains a list of components.
type ColAccExpS = Map String CNF
-- | Access expression composition monad
newtype ColAccExpM a =
ColAccExpM (ErrorT String (StateT ColAccExpS (Reader CollectionName)) a)
deriving (Monad, MonadState ColAccExpS, MonadReader CollectionName, Functor, Applicative)
instance Role Readers ColAccExpS ColAccExpM where
_ ==> c = ColAccExpM $ do
s <- get
cName <- ask
case Map.lookup (show readers) s of
Just _ -> fail $ "Collection " ++ show cName
++ " access readers already specified."
Nothing -> put $ Map.insert (show readers) (toCNF c) s
instance Role Writers ColAccExpS ColAccExpM where
_ ==> c = ColAccExpM $ do
s <- get
cName <- ask
case Map.lookup (show writers) s of
Just _ -> fail $ "Collection " ++ show cName
++ " access writers already specified."
Nothing -> put $ Map.insert (show writers) (toCNF c) s
--------------------------------------------------------------
-- | Type representing a collection clearance label expression.
--
-- > clearance $ do
-- > readers ==> "Alice" \/ "Bob"
-- > writers ==> "Alice"
--
data ColClrExp = ColClrExp CNF CNF
deriving Show
-- | Clress expression solely contains a list of components.
type ColClrExpS = Map String CNF
-- | Database expression composition monad
newtype ColClrExpM a =
ColClrExpM (ErrorT String (StateT ColClrExpS (Reader CollectionName)) a)
deriving (Monad, MonadState ColClrExpS, MonadReader CollectionName, Functor, Applicative)
instance Role Readers ColClrExpS ColClrExpM where
_ ==> c = ColClrExpM $ do
s <- get
cName <- ask
case Map.lookup (show readers) s of
Just _ -> fail $ "Collection " ++ show cName
++ " clearance readers already specified."
Nothing -> lift . put $ Map.insert (show readers) (toCNF c) s
instance Role Writers ColClrExpS ColClrExpM where
_ ==> c = ColClrExpM $ do
s <- get
cName <- ask
case Map.lookup (show writers) s of
Just _ -> fail $ "Collection " ++ show cName
++ " clearance writers already specified."
Nothing -> put $ Map.insert (show writers) (toCNF c) s
--------------------------------------------------------------
-- | Type representing a collection document label expression.
--
-- > document $ \doc -> do
-- > readers ==> "Alice" \/ "Bob"
-- > writers ==> "Alice"
--
data ColDocExp = ColDocExp (HsonDocument -> LabelExp)
instance Show ColDocExp where show _ = "ColDocExp {- function -}"
-- | A Label expression has two components.
data LabelExp = LabelExp CNF CNF
-- | Document expression solely contains a list of components.
type ColDocExpS = Map String CNF
-- | Document expression composition monad
newtype ColDocExpM a =
ColDocExpM (ErrorT String (StateT ColDocExpS (Reader CollectionName)) a)
deriving (Monad, MonadState ColDocExpS, MonadReader CollectionName, Functor, Applicative)
instance Role Readers ColDocExpS ColDocExpM where
_ ==> c = ColDocExpM $ do
s <- get
cName <- ask
case Map.lookup (show readers) s of
Just _ -> fail $ "Collection " ++ show cName
++ " document readers already specified."
Nothing -> lift . put $ Map.insert (show readers) (toCNF c) s
instance Role Writers ColDocExpS ColDocExpM where
_ ==> c = ColDocExpM $ do
s <- get
cName <- ask
case Map.lookup (show writers) s of
Just _ -> fail $ "Collection " ++ show cName
++ " document writers already specified."
Nothing -> put $ Map.insert (show writers) (toCNF c) s
--------------------------------------------------------------
-- | Type representing a collection field policy expression.
--
-- > field "name" searchable
-- > field "password" $ labeled $ \doc -> do
-- > readers ==> (((T.pack "name") `at`doc) :: String)
-- > writers ==> (((T.pack "name") `at`doc) :: String)
--
data ColFieldExp = ColFieldSearchable
| ColLabFieldExp (HsonDocument -> LabelExp)
instance Show ColFieldExp where
show ColFieldSearchable = "ColFieldSearchable"
show (ColLabFieldExp _) = "ColLabFieldExp {- function -}"
-- | Labeled field expression solely contains a list of components.
type ColLabFieldExpS = Map String CNF
-- | Labeled field expression composition monad.
newtype ColLabFieldExpM a =
ColLabFieldExpM (ErrorT String (StateT ColLabFieldExpS (Reader (FieldName, CollectionName))) a)
deriving (Monad, MonadState ColLabFieldExpS, MonadReader (FieldName, CollectionName), Functor, Applicative)
instance Role Readers ColLabFieldExpS ColLabFieldExpM where
_ ==> c = ColLabFieldExpM $ do
s <- get
(fName, cName) <- ask
case Map.lookup (show readers) s of
Just _ -> fail $ "Collection " ++ show cName ++ " field " ++ show fName
++ " readers already specified."
Nothing -> lift . put $ Map.insert (show readers) (toCNF c) s
instance Role Writers ColLabFieldExpS ColLabFieldExpM where
_ ==> c = ColLabFieldExpM $ do
s <- get
(fName, cName) <- ask
case Map.lookup (show writers) s of
Just _ -> fail $ "Collection " ++ show cName ++ " field " ++ show fName
++ " writers already specified."
Nothing -> put $ Map.insert (show writers) (toCNF c) s
-- | Field expression composition monad.
newtype ColFieldExpM a =
ColFieldExpM (ErrorT String (StateT (Maybe ColFieldExp) (Reader (FieldName, CollectionName))) a)
deriving (Monad, MonadState (Maybe ColFieldExp), MonadReader (FieldName, CollectionName), Functor, Applicative)
-- | Set the underlying field to be a searchable key.
--
-- > field "name" searchable
searchable :: ColFieldExpM ()
searchable = do
s <- get
(fName, cName) <- ask
when (isJust s) $ fail $ "Collection " ++ show cName ++ " field " ++
show fName ++ " policy already specified."
put (Just ColFieldSearchable)
-- | Synonym for 'searchable'
key :: ColFieldExpM ()
key = searchable
-- | Set data-dependent document label
--
-- > field "password" $ labeled $ \doc -> do
-- > readers ==> (("name" `at`doc) :: String)
-- > writers ==> (("name" `at`doc) :: String)
labeled :: (HsonDocument -> ColLabFieldExpM ()) -> ColFieldExpM ()
labeled fpol = do
s <- get
(fN, cN) <- ask
when (isJust s) $ fail $ "Collection " ++ show cN ++ " field " ++
show fN ++ " policy already specified."
let labFieldE = ColLabFieldExp $ \doc ->
fromRight $ eval (fpol' doc fN cN) fN cN
put (Just labFieldE)
where eval (ColLabFieldExpM e) fN cN =
runReader (evalStateT (runErrorT e) Map.empty) (fN, cN)
fpol' doc fN cN = do fpol doc
s <- get
r <- lookup' fN cN (show readers) s
w <- lookup' fN cN (show writers) s
return $ LabelExp r w
lookup' fN cN k s = maybe (fail $ "Missing " ++ show k ++
" in field label " ++ show fN
++ " of collection " ++ show cN)
return $ Map.lookup k s
--------------------------------------------------------------
-- | Type representing a collection expression.
--
-- > collection "w00t" $ do
-- > access $ do
-- > readers ==> "Alice" \/ "Bob"
-- > writers ==> "Alice"
-- > clearance $ do
-- > secrecy ==> "Users"
-- > integrity ==> "Alice"
-- > document $ \doc -> do
-- > readers ==> unrestricted
-- > writers ==> "Alice" \/ (("name" `at`doc) :: String)
-- > field "name" searchable
-- > field "password" $ labeled $ \doc -> do
-- > readers ==> (("name" `at`doc) :: String)
-- > writers ==> (("name" `at`doc) :: String)
--
data ColExp = ColExp CollectionName ColAccExp
ColClrExp
ColDocExp
(Map FieldName ColFieldExp)
deriving Show
-- | Internal state of collection
data ColExpT = ColAccT ColAccExp
| ColClrT ColClrExp
| ColDocT ColDocExp
| ColFldT ColFieldExp
deriving Show
-- | Collection expression may contain an access label expression,
-- a collection label expression, etc.
type ColExpS = Map String ColExpT
-- | Database expression composition monad
newtype ColExpM a =
ColExpM (ErrorT String (StateT ColExpS (Reader CollectionName)) a)
deriving (Monad, MonadState ColExpS, MonadReader CollectionName, Functor, Applicative)
--------------------------------------------------------------
-- | Type representing a policy
data PolicyExp = PolicyExp DBExp (Map CollectionName ColExp)
deriving Show
-- | Internal state of policy
data PolicyExpT = PolicyDBExpT DBExp
| PolicyColExpT ColExp
deriving Show
-- | Policy expression may contain a databse expression, or
-- a number of collection expressions.
type PolicyExpS = Map String PolicyExpT
-- | Policy expression composition monad
newtype PolicyExpM a = PolicyExpM (ErrorT String (State PolicyExpS) a)
deriving (Monad, MonadState PolicyExpS, Functor, Applicative)
--------------------------------------------------------------
-- | Set the collection access label. For example,
--
-- > collection "w00t" $ do
-- > ...
-- > access $ do
-- > readers ==> "Alice" \/ "Bob"
-- > writers ==> "Alice"
--
-- states that Alice and Bob can read documents from the collection,
-- but only Alice can insert new documents or modify existing ones.
access :: ColAccExpM () -> ColExpM ()
access (ColAccExpM acc) = do
s <- get
cN <- ask
case Map.lookup "access" s of
Just _ -> fail $ "Collection " ++ show cN
++ " access label already specified."
_ -> let r = runReader (evalStateT (runErrorT (acc' cN)) Map.empty) cN
in case r of
Left e -> fail e
Right accT -> put (Map.insert "access" accT s)
where acc' cN= do
acc
s <- get
r <- lookup' cN (show readers) s
w <- lookup' cN (show writers) s
return . ColAccT $ ColAccExp r w
lookup' cN k s = maybe (fail $ "Missing " ++ show k ++
" in access of " ++ show cN)
return $ Map.lookup k s
-- | Set the collection clearance. For example,
--
-- > collection "w00t" $ do
-- > ...
-- > clearance $ do
-- > secrecy ==> "Alice" \/ "Bob"
-- > integrity ==> "Alice"
--
-- states that all data in the collection is always readable by Alice
-- and Bob, and no more trustworthy than data Alice can create.
clearance :: ColClrExpM () -> ColExpM ()
clearance (ColClrExpM acc) = do
s <- get
cN <- ask
case Map.lookup "clearance" s of
Just _ -> fail $ "Collection " ++ show cN
++ " clearance label already specified."
_ -> let r = runReader (evalStateT (runErrorT (acc' cN)) Map.empty) cN
in case r of
Left e -> fail e
Right accT -> put (Map.insert "clearance" accT s)
where acc' cN = do
acc
s <- get
r <- lookup' cN (show readers) s
w <- lookup' cN (show writers) s
return . ColClrT $ ColClrExp r w
lookup' cN k s = maybe (fail $ "Missing " ++ show k ++
" in clearance of " ++ show cN)
return $ Map.lookup k s
-- | Set data-dependent document label. For example,
--
-- > collection "w00t" $ do
-- > ...
-- > document $ \doc -> do
-- > readers ==> 'unrestricted'
-- > writers ==> "Alice" \/ (("name" `at`doc) :: String)
--
-- states that every document in the collection is readable by anybody,
-- and only Alice or the principal named by the @name@ value in the
-- document can modify or insert such data.
document :: (HsonDocument -> ColDocExpM ()) -> ColExpM ()
document fpol = do
s <- get
cN <- ask
case Map.lookup "document" s of
Just _ -> fail $ "Collection " ++ show cN
++ " document policy already specified."
_ -> let docT = ColDocT $ ColDocExp $ \doc ->
fromRight $ eval (fpol' doc cN) cN
in put (Map.insert "document" docT s)
where eval (ColDocExpM e) cN =
runReader (evalStateT (runErrorT e) Map.empty) cN
fpol' doc cN = do fpol doc
s <- get
r <- lookup' cN (show readers) s
w <- lookup' cN (show writers) s
return $ LabelExp r w
lookup' cN k s = maybe (fail $ "Missing " ++ show k ++
" in document label of collection "
++ show cN)
return $ Map.lookup k s
-- | Set field policy. A field can be declared to be a 'searchable'
-- key or a 'labeled' value.
--
-- Declaring a field to be a 'searchable' key is straight forward:
--
-- > collection "w00t" $ do
-- > ...
-- > field "name" searchable
--
-- The 'labeled' field declaration is similar to the 'document' policy, but
-- sets the label of a specific field. For example
--
-- > collection "w00t" $ do
-- > ...
-- > field "password" $ labeled $ \doc -> do
-- > let user = "name" `at` doc :: String
-- > readers ==> user
-- > writers ==> user
--
-- states that every @password@ field in the is readable and writable
-- only by or the principal named by the @name@ value of the document can
-- modify or insert such data.
field :: FieldName -> ColFieldExpM () -> ColExpM ()
field fName (ColFieldExpM e) = do
s <- get
cN <- ask
let _fName = "field." ++ T.unpack fName
case Map.lookup _fName s of
Just _ -> fail $ "Collection " ++ show cN ++ " field " ++ show fName
++ " policy already specified."
_ -> case runReader (evalStateT (runErrorT e') Nothing) (fName, cN) of
Left er -> fail er
Right Nothing -> fail $ "Collection " ++ show cN ++ " field " ++
show fName ++ " policy not specified."
Right (Just fieldE) -> put (Map.insert _fName (ColFldT fieldE) s)
where e' = do e >> get
-- | Set the collection labels and policies. Each @collection@, must
-- at least specify who can 'access' the collection, what the
-- 'clearance' of the data in the collection is, and how 'document's
-- are labeled. Below is an example that also labels the @password@
-- field and declares @name@ a searchable key.
--
-- > collection "w00t" $ do
-- > access $ do
-- > readers ==> "Alice" \/ "Bob"
-- > writers ==> "Alice"
-- > clearance $ do
-- > secrecy ==> "Users"
-- > integrity ==> "Alice"
-- > document $ \doc -> do
-- > readers ==> 'unrestricted'
-- > writers ==> "Alice" \/ (("name" `at`doc) :: String)
-- > field "name" searchable
-- > field "password" $ labeled $ \doc -> do
-- > readers ==> (("name" `at`doc) :: String)
-- > writers ==> (("name" `at`doc) :: String)
--
collection :: CollectionName -> ColExpM () -> PolicyExpM ()
collection cN (ColExpM e) = do
s <- get
let _cN = "collection." ++ T.unpack cN
case Map.lookup _cN s of
Just _ -> fail $ "Collection " ++ show cN ++ " policy already set"
Nothing -> case runReader (evalStateT (runErrorT e') Map.empty) cN of
Left err -> fail err
Right colExp -> put $ Map.insert _cN (PolicyColExpT colExp) s
where e' = do
e
s <- get
(ColAccT a) <- lookup' "access" s
(ColClrT c) <- lookup' "clearance" s
(ColDocT d) <- lookup' "document" s
let fs = Map.mapKeys (T.pack . (drop (length "field."))) $
Map.map (\(ColFldT f) -> f) $
Map.filterWithKey (\k _ -> "field." `isPrefixOf` k) s
return $ ColExp cN a c d fs
lookup' k s = maybe (fail $ "Missing " ++ show k ++
" for collection " ++ show cN)
return $ Map.lookup k s
--------------------------------------------------------------
-- | Compile a policy.
runPolicy :: PolicyExpM () -> Either String PolicyExp
runPolicy (PolicyExpM e) = evalState (runErrorT e') Map.empty
where e' = do
e
s <- get
(PolicyDBExpT db) <- maybe (fail $ "Missing database policy")
return $ Map.lookup "database" s
let cs = Map.mapKeys (T.pack . (drop (length "collection."))) $
Map.map (\(PolicyColExpT f) -> f) $
Map.filterWithKey (\k _ -> "collection." `isPrefixOf` k) s
return $ PolicyExp db cs
-- | High level function used to set the policy in a 'PolicyModule'.
-- This function takes the policy module's privileges and a policy
-- expression, and produces a 'PMAction' that sets the policy.
setPolicy :: DCPriv -> PolicyExpM () -> PMAction ()
setPolicy priv pol =
case runPolicy pol of
Left err -> liftLIO $ throwLIO $ PolicyCompileError err
Right policy -> execPolicy policy
where execPolicy (PolicyExp db cs) = do
execPolicyDB db
void $ forM cs execPolicyCol
--
execPolicyDB (DBExp r w a) = do
setDatabaseLabelP priv (r %% w)
setCollectionSetLabelP priv (r %% a)
--
execPolicyCol (ColExp n (ColAccExp lr lw) (ColClrExp cr cw) doc fs) =
let cps = mkColPol doc fs
in createCollectionP priv n (lr %% lw) (cr %% cw) cps
--
mkColPol (ColDocExp fdocE) cs =
let fdoc = unDataPolicy fdocE
in CollectionPolicy { documentLabelPolicy = fdoc
, fieldLabelPolicies = Map.map unFieldExp cs }
--
unDataPolicy fpolE = \doc ->
let (LabelExp s i) = fpolE doc
in s %% i
--
unFieldExp ColFieldSearchable = SearchableField
unFieldExp (ColLabFieldExp f) = FieldPolicy (unDataPolicy f)
-- | Exception thrown if a policy cannot be \"compiled\" or if we
-- deternmine that it's faulty at \"runtime\".
data PolicySpecificiationError = PolicyCompileError String
| PolicyRuntimeError String
deriving (Show, Typeable)
instance Exception PolicySpecificiationError
--
-- Helpers
fromRight :: Either String b -> b
fromRight (Right x) = x
fromRight (Left e) = throw . PolicyRuntimeError $ e
unrestricted :: CNF
unrestricted = cTrue
| scslab/hails | Hails/PolicyModule/DSL.hs | mit | 26,910 | 0 | 20 | 7,541 | 5,609 | 2,872 | 2,737 | -1 | -1 |
module Mips where
type Reg = String
type Imm = String
type Addr = String
-- Type and functions for the abstract syntax of MIPS
--data Instruction = RType :+:
-- data Instruction = RType
-- | IType
-- | JType
-- | Misc
-- data RType = ADD Reg Reg Reg
-- | SUB Reg Reg Reg
-- | MUL Reg Reg Reg
-- | DIV Reg Reg Reg
-- | XOR Reg Reg Reg
-- | SLT Reg Reg Reg
-- data IType = SUBI Reg Reg Imm
-- | XORI Reg Reg Imm
-- | SLTI Reg Reg Imm
-- | BEQ Reg Reg Addr
-- | BNE Reg Reg Addr
data Instruction = Label String
| Comment String
| LA Reg Addr
| LUI Reg Imm
| LB String String String
| LW String String Imm
| SW String String Imm
| SB String String String
| ADD Reg Reg Reg
| ADDI Reg Reg Imm
| SUB Reg Reg Reg
| SUBI Reg Reg Imm
| MUL Reg Reg Reg
| DIV Reg Reg Reg
| XOR Reg Reg Reg
| XORI Reg Reg Imm
| SLT Reg Reg Reg
| SLTI Reg Reg Imm
| BEQ Reg Reg Addr
| BNE Reg Reg Addr
| J Addr
| JR Reg -- Because of code in RegAlloc, may only be used for returning from function
| JAL Addr
| Nop
| Syscall
| Globl String
| Text String
| Data String
| Space String
| Ascii String
| Asciiz String
| Align String
-- Mips program headers below here
| DeclGlobal String
| DotText deriving (Show, Eq)
| Sword-Smith/hfasto | src/Mips.hs | mit | 1,966 | 0 | 6 | 1,054 | 288 | 175 | 113 | 38 | 0 |
-- | Source files for 'B9.Artifact.Generator's.
--
-- @since 0.5.62
module B9.Artifact.Readable.Source
( ArtifactSource (..),
getArtifactSourceFiles,
)
where
import B9.Artifact.Content.Readable
import B9.Artifact.Content.StringTemplate
import B9.QCUtil
import Control.Parallel.Strategies
import Data.Data
import GHC.Generics (Generic)
import System.FilePath ((</>))
import Test.QuickCheck
-- | Describe how input files for artifacts to build are obtained. The general
-- structure of each constructor is __FromXXX__ /destination/ /source/
data ArtifactSource
= -- | Copy a 'B9.Artifact.Content.StringTemplate.SourceFile'
-- potentially replacing variable defined in 'Let'-like
-- parent elements.
FromFile
FilePath
SourceFile
| -- | Create a file from some 'Content'
FromContent
FilePath
Content
| -- | Set the unix /file permissions/ to all files generated
-- by the nested list of 'ArtifactSource's.
SetPermissions
Int
Int
Int
[ArtifactSource]
| -- | Assume a local directory as starting point for all
-- relative source files in the nested 'ArtifactSource's.
FromDirectory
FilePath
[ArtifactSource]
| -- | Specify an output directory for all the files
-- generated by the nested 'ArtifactSource's
IntoDirectory
FilePath
[ArtifactSource]
deriving (Read, Show, Eq, Data, Typeable, Generic)
instance NFData ArtifactSource
-- | Return all source files generated by an 'ArtifactSource'.
getArtifactSourceFiles :: ArtifactSource -> [FilePath]
getArtifactSourceFiles (FromContent f _) = [f]
getArtifactSourceFiles (FromFile f _) = [f]
getArtifactSourceFiles (IntoDirectory pd as) =
(pd </>) <$> (as >>= getArtifactSourceFiles)
getArtifactSourceFiles (FromDirectory _ as) = as >>= getArtifactSourceFiles
getArtifactSourceFiles (SetPermissions _ _ _ as) =
as >>= getArtifactSourceFiles
instance Arbitrary ArtifactSource where
arbitrary =
oneof
[ FromFile <$> smaller arbitraryFilePath <*> smaller arbitrary,
FromContent <$> smaller arbitraryFilePath <*> smaller arbitrary,
SetPermissions
<$> choose (0, 7)
<*> choose (0, 7)
<*> choose (0, 7)
<*> smaller arbitrary,
FromDirectory <$> smaller arbitraryFilePath <*> smaller arbitrary,
IntoDirectory <$> smaller arbitraryFilePath <*> smaller arbitrary
]
| sheyll/b9-vm-image-builder | src/lib/B9/Artifact/Readable/Source.hs | mit | 2,428 | 0 | 13 | 512 | 438 | 247 | 191 | 51 | 1 |
{-# LANGUAGE OverloadedStrings, RankNTypes, BangPatterns #-}
module Main (main) where
import Debug.Trace
import Game.World
import System.Exit
import Control.Monad.RWS.Strict
--import Control.Monad.Identity
--import Control.Monad.Reader
--import Control.Monad.Writer
import Control.Monad as CM
--import qualified Data.Binary as B
import Control.Wire
import qualified Prelude as P
import Prelude hiding ((.), until)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Network hiding (accept, sClose)
import Network.Socket
import Control.Concurrent
import Network.Simple.TCP
import Control.Concurrent.Async
import qualified Data.Monoid as Monoid
import Control.Concurrent.STM
import Pipes as P
import Pipes.Network.TCP
import Pipes.Concurrent
import Control.Lens
import qualified Data.Set as Set
import qualified Pipes.Binary as PB
import Game.World.Common
import Game.Game
import Control.Monad.State.Strict
import Data.Tiled
import qualified Game.Input.Actions as A
import Game.World.AI.Basic
import Game.Network.Client
type ProdDecoder a = (Monad m)
=> Producer B.ByteString m r
-> Producer (PB.ByteOffset, a) m (Either (PB.DecodingError, Producer B.ByteString m r) r)
decodeAction :: ProdDecoder FromClientData
-- decodeAction = PB.decodeMany
decodeAction bytes = bytes^.PB.decoded -- decodeMany
type FromClientData = (Float, Int, A.Action)
type ClientData = ([(Int, A.Action)], Rational)
collect :: [(Int, A.Action)] -> Pipe FromClientData ClientData IO [(Int, A.Action)]
collect actions = do
(_, pId, action) <- P.await
if action == A.ActionUpdateGameState then
return (actions ++ [(pId, action)])
else
collect (actions ++ [(pId, action)])
--produceWorld :: WorldSession ->
--Pipe FromClientData ClientData IO ()
produceWorld session' lastDt total = do
--(t, action) <- P.await
actions <- collect []
(dt, session) <- lift $ stepSession session'
let time = dt
let
finalTime :: Rational
finalTime = (realToFrac . dtime $ time) + lastDt
let steps = [16.0/1000 | _ <- [0..(floor (finalTime/16*1000) - 1)]]
let final = foldr (\_ time -> if time > 16/1000.0 then time - 16/1000.0 else time) finalTime [0..floor (finalTime/16*1000)]
mapM_ (\time -> P.yield (actions, realToFrac time)) steps
let total' = if length steps > 1 then
total + 1 else total
lift $ writeFile "time.log" (show total')
final' <- if final > 15/1000 then do
P.yield (actions, realToFrac final)
return 0
else
return final
produceWorld session final' total'
--getDeltaTime (dt, deltaWorld, world) = dt
--getWorld (dt, dWorld, world) = world
--debug = do
-- p <- P.await
-- lift $ print p
-- P.yield p
fakeClient !game = do
(_, (actions, dt)) <- await
let !manager2 = worldManagerUpdate (game^.gameWorldManager) actions
let ((!actions1, !actions2), !newGame) = runState (do
gameWorldManager .= manager2
--updateGame dt
updateOnlyGame dt
world <- use gameLogicWorld
worldDelta <- use gameLastDelta
manager <- use gameWorldManager
let (A.InputActions aiInput1) = runAI 3 world worldDelta dt
let (A.InputActions aiInput2) = runAI 4 world worldDelta dt
return (aiInput1, aiInput2)
) game
mapM_ (\a -> P.yield (0, 3, a)) $ Set.toList actions1
mapM_ (\a -> P.yield (0, 4, a)) $ Set.toList actions2
newGame `seq` fakeClient newGame
runFakeClient input output game =
void (decodeSteps (fromInput input)) >-> fakeClient game >-> toOutput output
runGame :: Input FromClientData -> Output C.ByteString -> IO ()
runGame recvEvents output = do
let session = clockSession_
let
worldProducer :: Pipe (Float, Int, A.Action) ClientData IO ()
worldProducer = produceWorld session (0::Rational) 0
--eventProducer :: Producer (Float, A.Action) IO ()
eventProducer = P.for (fromInput recvEvents) P.yield
runEffect $
P.for (eventProducer >-> worldProducer) PB.encode
>-> toOutput output
performGC
--eventUpdate :: Producer (Float, Int, A.Action) IO ()
eventUpdate n = do
P.yield (0, -1, A.ActionUpdateGameState)
let n' = if n > 10 then 0 else n + 1
lift $ threadDelay (1000000 `div` 60)
eventUpdate n'
main :: IO ()
main = withSocketsDo $ do
(output1, input1) <- spawn Unbounded
-- (output2, input2) <- spawn Unbounded
(output3, input3) <- spawn Unbounded
(sendEvents1, recvEvents1) <- spawn Unbounded :: IO (Output FromClientData, Input FromClientData)
--(sendEvents2, recvEvents2) <- spawn Unbounded
--(sendEvents3, recvEvents3) <- spawn Unbounded
numClient <- newTVarIO (0 :: Int)
let recvEvents = recvEvents1
--let sendEvents = sens
-- let output = output1 Monoid.<> output2 Monoid.<> output3
let output = output1 Monoid.<> output3
_ <- async $ do
runEffect $ eventUpdate 0 >-> toOutput sendEvents1
performGC
game <- newGame "test"
a1 <- async $ runGame recvEvents output
a2 <- async $ do
runEffect $ runFakeClient input3 sendEvents1 game
performGC
_ <- async $
serve HostIPv4 "5002" (connCb (numClient, sendEvents1, input1, input1))
mapM_ wait [a2]
return ()
forward :: Pipe (PB.ByteOffset, (Float, Int, A.Action)) (Float, Int, A.Action) IO ()
forward = do
(off, d) <- P.await
--lift $ print (off, d)
CM.unless (off < 0) $ do
P.yield d
forward
--connCb :: (Output (Float, A.Action), Input C.ByteString, Input C.ByteString)
-- -> (Socket, SockAddr)
-- > IO ()
connCb :: (TVar Int, Output (Float, Int, A.Action), Input C.ByteString, Input C.ByteString)
-> (Socket, SockAddr) -> IO ()
connCb (numClient, sendEvents, input1, input2) (sock, _) = do
--print "Server info: player joined"
cl <- atomically $ do
n <- readTVar numClient
if n == 2 then
return (-1)
else do
writeTVar numClient (n+1)
return n
CM.unless (cl == -1) $ do
let toClient = toSocket sock
let toClientFirst = toSocket sock
--print "Send player id"
runEffect $ PB.encode cl >-> toClientFirst
--print "Sent player id"
let fromClient = fromSocket sock 4096
let
--testX :: Producer (PB.ByteOffset, (Float, Int, A.Action)) IO ()
testX = decodeAction fromClient >>= (\e ->
case e of
Right _ -> do
P.yield (-1, (0, -1, A.ActionNothing))
return ()
Left _ -> do
P.yield (-2, (0, -1, A.ActionNothing))
return ()
)
--runEffect $ (P.yield "Test" >-> cons)
_ <- async $ do
-- runEffect $ fromInput (if cl == 0 then input1 else input2) >-> toClient
runEffect $ fromInput input1 >-> toClient
performGC
a2 <- async $ do
runEffect $ testX >-> forward >-> toOutput sendEvents
performGC
--print "Wait for quit"
mapM_ wait [a2]
_ <- atomically $ do
n <- readTVar numClient
writeTVar numClient (n-1)
return n
return ()
--print ("Server info: player left", cl)
| mfpi/q-inqu | src/server/Server.hs | mit | 6,712 | 79 | 24 | 1,264 | 2,194 | 1,166 | 1,028 | 159 | 4 |
type Jugador = [Char]
type Participante = [Char]
type Club = [Char]
type Puesto = [Char]
type Cotizacion = Integer
type Puntaje = Integer
type MinutosJugados = Integer
type Evaluacion = (Jugador, Puntaje, MinutosJugados)
type Fecha = [Evaluacion]
participantes = [ ("Natalia", ["Abbondazieri","Lluy","Battaglia", "Lazzaro"]),
("Romina", ["Islas", "Lluy", "Battaglia", "Lazzaro"]),
("Jessica", ["Islas"])
]
clubes = ["Boca", "Racing", "Tigre"]
jugadores = [ ("Abbondazieri", "Boca", "Arquero", 6500000),
("Islas", "Tigre", "Arquero", 5500000),
("Lluy", "Racing", "Defensor", 1800000),
("Battaglia", "Boca", "Volante", 8000000),
("Lazzaro", "Tigre", "Delantero", 5200000)
]
darJugador (jugador, _, _, _) = jugador
darClub (_, club, _, _) = club
darPuesto (_, _, puesto, _) = puesto
darCotizacion (_, _, _, cotizacion) = cotizacion
fechas = [ quinta, sexta, septima, octava ]
quinta = [("Lluy", 8, 90), ("Lazzaro", 6, 90)]
sexta = [("Lazzaro", 7, 77), ("Islas", 6, 90), ("Lluy", 7, 90)]
septima = [("Battaglia", 13, 90), ("Lluy", 6, 90), ("Lazzaro", 8, 77)]
octava = [("Islas", 4, 84), ("Battaglia", 8, 90)]
darJugadorFecha (jugador, _, _) = jugador
darPuntaje (_, puntaje, _) = puntaje
darMinutosJugados (_, _, minutos) = minutos
-- 1) cotizacionDe, recibe el nombre de un jugador y devuelve su cotizacion.
cotizacionDe :: Jugador -> Cotizacion
cotizacionDe = darCotizacion . darFichaJugador
puestoDe = darPuesto . darFichaJugador
darFichaJugador jugador = head (filter (coincideJugador jugador) jugadores)
coincideJugador jugador = (== jugador) . darJugador
-- 2) cotizacionEquipoDe, recibe un participante y devuelve la cotizacion de su equipo.
cotizacionEquipoDe :: Participante -> Cotizacion
cotizacionEquipoDe participante = sum (map cotizacionDe (darJugadoresPorParticipante participante))
darJugadoresPorParticipante participante = (snd . head) (filter ((== participante) . fst) participantes)
-- 3) fueUsadoPor, recibe el nombre de un jugador y un participante y devuelve cierto o falso si el participante tiene a ese jugador en su equipo.
fueUsadoPor :: Jugador -> Participante -> Bool
fueUsadoPor jugador participante = any (== jugador) (darJugadoresPorParticipante participante)
-- 4) nombresJugadoresClub, recibe a un club y devuelve la lista de nombre de sus jugadores.
nombresJugadoresClub :: Club -> [Jugador]
nombresJugadoresClub club = map darJugador (filter ((== club) . darClub) jugadores)
-- 5) nombresTodoslosJugadores, devuelve la lista de los nombres de todos los jugadores participantes de torneo.
nombresTodoslosJugadores :: [Jugador]
nombresTodoslosJugadores = map darJugador todosLosJugadores
todosLosJugadores = filter estaEnUnEquipo jugadores
estaEnUnEquipo (_, club, _, _) = elem club clubes
-- 6) jugoFechaJugador, recibe una fecha y el nombre de un jugador y devuelve si jugo ese jugador en esa fecha.
jugoFechaJugador :: Fecha -> Jugador -> Bool
jugoFechaJugador fecha jugador = elem jugador (darJugadoresPorFecha fecha)
darJugadoresPorFecha fecha = map darJugadorFecha fecha
-- 7) minutosFechaJugador, recibe una fecha y el nombre de un jugador y devuelve los minutos jugados por ese jugador en esa fecha. Sino participo devuelve cero.
minutosFechaJugador :: Fecha -> Jugador -> Integer
minutosFechaJugador fecha jugador = aplicarFecha darMinutosJugados jugador fecha
aplicarFecha funcion jugador fecha | jugoFechaJugador fecha jugador = funcion (evaluacionFechaJugador jugador fecha)
| otherwise = 0
evaluacionFechaJugador jugador fecha = head (filter (coincideJugadorFecha jugador) fecha)
coincideJugadorFecha jugador = (== jugador) . darJugadorFecha
-- 8) totalPuntosJugador, recibe el nombre de un jugador y devuelve el total de puntos logrados por ese jugador durante todo el torneo.
totalPuntosJugador :: Jugador -> Puntaje
totalPuntosJugador jugador = sum (map (puntosPorFecha jugador) fechas)
puntosPorFecha jugador fecha = aplicarFecha darPuntaje jugador fecha
-- 9) promedioPuntosJugador, recibe el nombre de un jugador y devuelve el promedio de puntos logrados por ese jugador durante todo el torneo.
promedioPuntosJugador :: Jugador -> Float
promedioPuntosJugador jugador = fromIntegral (totalPuntosJugador jugador) / fromIntegral (cantidadPartidosDisputados jugador)
cantidadPartidosDisputados jugador = length (filter (flip jugoFechaJugador jugador) fechas)
-- 10) mejorJugadorPor, recibe un criterio y devuelve el mejor jugador de acuerdo a ese criterio.
mejorJugadorPor criterio = fst(maximo (map (aplicarCriterio criterio) nombresTodoslosJugadores))
aplicarCriterio criterio jugador = (jugador, criterio jugador)
maximo [] = ("", 0)
maximo (x:xs) | snd x > snd (maximo xs) = x
| otherwise = maximo xs
-- mejorJugadorPor totalPuntosJugador
-- "Lazzaro"
-- mejorJugadorPor cotizacionDe
-- "Battaglia"
-- mejorJugadorPor (flip puntosPorFecha quinta)
-- "Lluy"
-- mejorJugadorPor promedioPuntosJugador
-- "Battaglia"
-- 13) nombresJugadoresDeValorMenorADelPuesto, recibe un importe un puesto y devuelve los nombres de los jugadores de ese con una cotizacion menor o igual al importe recibido.
nombresJugadoresDeValorMenorADelPuesto :: Cotizacion -> Puesto -> [Jugador]
nombresJugadoresDeValorMenorADelPuesto cotizacion puesto = filter (cumpleCondicionParaPuesto cotizacion puesto) nombresTodoslosJugadores
cumpleCondicionParaPuesto cotizacion puesto jugador = (cotizacion >= (cotizacionDe jugador)) && puesto == (puestoDe jugador)
| matiasm15/Haskell | TP MiniDT.hs | mit | 5,598 | 0 | 11 | 927 | 1,286 | 731 | 555 | 69 | 1 |
{- | Support for resource pagination.
-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
module Pos.Util.Pagination (
Page(..)
, PerPage(..)
, maxPerPageEntries
, defaultPerPageEntries
, PaginationMetadata(..)
, PaginationParams(..)
) where
import Universum
import Control.Lens (at, ix, (?~))
import Data.Aeson (Value (Number))
import qualified Data.Aeson.Options as Aeson
import Data.Aeson.TH
import qualified Data.Char as Char
import Data.Default
import Data.Swagger as S
import Formatting (bprint, build, (%))
import qualified Formatting.Buildable
import Test.QuickCheck (Arbitrary (..), choose, getPositive)
import Web.HttpApiData
-- | A `Page` is used in paginated endpoints to request access to a particular
-- subset of a collection.
newtype Page = Page Int
deriving (Show, Eq, Ord, Num)
deriveJSON Aeson.defaultOptions ''Page
instance Arbitrary Page where
arbitrary = Page . getPositive <$> arbitrary
instance FromHttpApiData Page where
parseQueryParam qp = case parseQueryParam qp of
Right (p :: Int) | p < 1 -> Left "A page number cannot be less than 1."
Right (p :: Int) -> Right (Page p)
Left e -> Left e
instance ToHttpApiData Page where
toQueryParam (Page p) = fromString (show p)
instance ToSchema Page where
declareNamedSchema =
pure . NamedSchema (Just "Page") . paramSchemaToSchema
instance ToParamSchema Page where
toParamSchema _ = mempty
& type_ .~ SwaggerInteger
& default_ ?~ (Number 1) -- Always show the first page by default.
& minimum_ ?~ 1
-- | If not specified otherwise, return first page.
instance Default Page where
def = Page 1
instance Buildable Page where
build (Page p) = bprint build p
-- | A `PerPage` is used to specify the number of entries which should be returned
-- as part of a paginated response.
newtype PerPage = PerPage Int
deriving (Show, Eq, Num, Ord)
deriveJSON Aeson.defaultOptions ''PerPage
instance ToSchema PerPage where
declareNamedSchema =
pure . NamedSchema (Just "PerPage") . paramSchemaToSchema
instance ToParamSchema PerPage where
toParamSchema _ = mempty
& type_ .~ SwaggerInteger
& default_ ?~ (Number $ fromIntegral defaultPerPageEntries)
& minimum_ ?~ 1
& maximum_ ?~ (fromIntegral maxPerPageEntries)
-- | The maximum number of entries a paginated request can return on a single call.
-- This value is currently arbitrary and it might need to be tweaked down to strike
-- the right balance between number of requests and load of each of them on the system.
maxPerPageEntries :: Int
maxPerPageEntries = 50
-- | If not specified otherwise, a default number of 10 entries from the collection will
-- be returned as part of each paginated response.
defaultPerPageEntries :: Int
defaultPerPageEntries = 10
instance Arbitrary PerPage where
arbitrary = PerPage <$> choose (1, maxPerPageEntries)
instance FromHttpApiData PerPage where
parseQueryParam qp = case parseQueryParam qp of
Right (p :: Int) | p < 1 -> Left "per_page should be at least 1."
Right (p :: Int) | p > maxPerPageEntries ->
Left $ fromString $ "per_page cannot be greater than " <> show maxPerPageEntries <> "."
Right (p :: Int) -> Right (PerPage p)
Left e -> Left e
instance ToHttpApiData PerPage where
toQueryParam (PerPage p) = fromString (show p)
instance Default PerPage where
def = PerPage defaultPerPageEntries
instance Buildable PerPage where
build (PerPage p) = bprint build p
-- | Extra information associated with pagination
data PaginationMetadata = PaginationMetadata
{ metaTotalPages :: Int -- ^ The total pages returned by this query.
, metaPage :: Page -- ^ The current page number (index starts at 1).
, metaPerPage :: PerPage -- ^ The number of entries contained in this page.
, metaTotalEntries :: Int -- ^ The total number of entries in the collection.
} deriving (Show, Eq, Generic)
deriveJSON Aeson.defaultOptions ''PaginationMetadata
instance Arbitrary PaginationMetadata where
arbitrary = PaginationMetadata <$> fmap getPositive arbitrary
<*> arbitrary
<*> arbitrary
<*> fmap getPositive arbitrary
instance ToSchema PaginationMetadata where
declareNamedSchema proxy = do
schm <- genericDeclareNamedSchema defaultSchemaOptions
{ S.fieldLabelModifier =
over (ix 0) Char.toLower . drop 4 -- length "meta"
} proxy
pure $ over schema (over properties adjustPropsSchema) schm
where
totalSchema = Inline $ mempty
& type_ .~ SwaggerNumber
& minimum_ ?~ 0
& maximum_ ?~ fromIntegral (maxBound :: Int)
adjustPropsSchema s = s
& at "totalPages" ?~ totalSchema
& at "totalEntries" ?~ totalSchema
instance Buildable PaginationMetadata where
build PaginationMetadata{..} =
bprint (build%"/"%build%" total="%build%" per_page="%build)
metaPage
metaTotalPages
metaTotalEntries
metaPerPage
-- | `PaginationParams` is datatype which combines request params related
-- to pagination together.
data PaginationParams = PaginationParams
{ ppPage :: Page -- ^ Greater than 0.
, ppPerPage :: PerPage
} deriving (Show, Eq, Generic)
instance Buildable PaginationParams where
build PaginationParams{..} =
bprint ("page=" % build % ", per_page=" % build)
ppPage
ppPerPage
| input-output-hk/pos-haskell-prototype | lib/src/Pos/Util/Pagination.hs | mit | 5,923 | 0 | 15 | 1,593 | 1,264 | 672 | 592 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
import Control.Lens hiding (index)
import Control.Monad.State
import Control.Monad.Trans.Maybe
import Data.Acid
import Data.List hiding (insert)
import Data.SafeCopy
import Data.Time
import Graphics.UI.Gtk as Gtk hiding (get)
import Types
--local imports
import Handlers.AboutBtn
import Handlers.InfoDiagramBtn
import Handlers.TreeSelection
import System.IO.Unsafe
import Utils
--AcidState
$(deriveSafeCopy 0 'base ''Item)
$(deriveSafeCopy 0 'base ''ItemList)
$(makeAcidic ''ItemList ['insert, 'deleteByPos, 'edit, 'getItemList])
main :: IO()
main = do
--Read saved items and sort it
database <- openLocalState (ItemList [])
quariedItemList <- query database GetItemList
itemList <- listStoreNew []
mapM_ (listStoreAppend itemList) (sort quariedItemList)
--Initialize GUI
_ <- initGUI
window <- windowNew
Gtk.set window [windowTitle := "Учёт расходов", windowDefaultWidth := 500,
windowDefaultHeight := 400, containerBorderWidth := 10]
--mainBox
mainBox <- vBoxNew False 1
containerAdd window mainBox
--aboutDeveloper
aboutDeveloperBtn <- buttonNewWithLabel "О разработчике"
--descriptionLabel
histlbl <- labelNew(Just "История расходов/доходов")
--ListView
treeview <- treeViewNewWithModel itemList
treeViewSetHeadersVisible treeview False
col <- treeViewColumnNew
rend <- cellRendererTextNew
cellLayoutPackStart col rend False
cellLayoutSetAttributes col rend itemList
(\i -> [cellText := show i])
_ <- treeViewAppendColumn treeview col
-- Make ability to scroll task's list
itemsScrwin <- scrolledWindowNew Nothing Nothing
scrolledWindowAddWithViewport itemsScrwin treeview
scrolledWindowSetPolicy itemsScrwin PolicyAutomatic PolicyAutomatic
--set selection
selection <- treeViewGetSelection treeview
treeViewColumnsAutosize treeview
treeSelectionSetMode selection SelectionSingle
--infoBox
infoBox <- hBoxNew False 1
infoBox1 <- hBoxNew False 1
infoBox2 <- hBoxNew False 1
let curBalance = getBalance quariedItemList
balanceLbl <- labelNew(Just $ show curBalance)
infoLbl <- labelNew(Just ("Баланс = " ++ show curBalance))
infoDiagramBtn <- buttonNewWithLabel "Статистика"
boxPackStart infoBox1 infoLbl PackGrow 1
boxPackEnd infoBox2 infoDiagramBtn PackGrow 1
boxPackStart infoBox infoBox1 PackGrow 148
boxPackEnd infoBox infoBox2 PackGrow 1
--DescriptionPrice
descPriceBox <- hBoxNew False 1
descPriceBox1 <- vBoxNew False 1
descPriceBox2 <- vBoxNew False 1
descPriceBox3 <- vBoxNew False 1
descPriceBox4 <- vBoxNew False 1
descLbl <- labelNew(Just "Описание")
priceLbl <- labelNew(Just "Цена")
boxPackStart descPriceBox2 descLbl PackGrow 0
boxPackStart descPriceBox3 priceLbl PackGrow 0
boxPackStart descPriceBox descPriceBox1 PackGrow 1
boxPackStart descPriceBox descPriceBox2 PackGrow 20
boxPackStart descPriceBox descPriceBox3 PackGrow 20
boxPackStart descPriceBox descPriceBox4 PackGrow 35
--addBox
addBox <- hBoxNew False 2
addBox1 <- vBoxNew False 2
addBox2 <- vBoxNew False 2
addBox3 <- vBoxNew False 2
addBox4 <- vBoxNew False 2
addBox41 <- hBoxNew False 2
addLbl <- labelNew(Just "Новый:")
addDescEdt <- entryNew
addPriceEdt <- entryNew
addConsBtn <- buttonNewWithLabel "Расход"
addIncBtn <- buttonNewWithLabel "Доход"
boxPackStart addBox1 addLbl PackGrow 0
boxPackStart addBox2 addDescEdt PackGrow 0
boxPackStart addBox3 addPriceEdt PackGrow 0
boxPackStart addBox41 addConsBtn PackGrow 0
boxPackStart addBox41 addIncBtn PackGrow 0
boxPackStart addBox4 addBox41 PackGrow 0
boxPackStart addBox addBox1 PackGrow 0
boxPackStart addBox addBox2 PackGrow 0
boxPackStart addBox addBox3 PackGrow 0
boxPackStart addBox addBox4 PackGrow 0
--editBox
editBox <- hBoxNew False 2
editBox1 <- vBoxNew False 2
editBox2 <- vBoxNew False 2
editBox3 <- vBoxNew False 2
editBox4 <- vBoxNew False 2
edtLbl <- labelNew(Just "Изменить:")
editDescEdt <- entryNew
editPriceEdt <- entryNew
saveBtn <- buttonNewWithLabel "Сохранить"
boxPackStart addBox1 edtLbl PackGrow 0
boxPackStart addBox2 editDescEdt PackGrow 0
boxPackStart addBox3 editPriceEdt PackGrow 0
boxPackStart addBox4 saveBtn PackGrow 0
boxPackStart editBox editBox1 PackGrow 0
boxPackStart editBox editBox2 PackGrow 0
boxPackStart editBox editBox3 PackGrow 0
boxPackStart editBox editBox4 PackGrow 0
--delButton
delBtn <- buttonNewWithLabel "Удалить"
--packing into mainBox
boxPackStart mainBox aboutDeveloperBtn PackNatural 0
boxPackStart mainBox histlbl PackNatural 0
boxPackStart mainBox itemsScrwin PackGrow 0
boxPackStart mainBox infoBox PackNatural 0
boxPackStart mainBox descPriceBox PackNatural 0
boxPackStart mainBox addBox PackNatural 0
boxPackStart mainBox editBox PackNatural 0
boxPackStart mainBox delBtn PackNatural 0
--adding new consume
_ <- ($) onClicked addConsBtn $ do
--check for not null and all isDigit
curPrice <- runMaybeT $ getValidPrice addPriceEdt
case curPrice of
Nothing -> do
--no comment
dialog <- messageDialogNew (Just window) [DialogDestroyWithParent]
MessageError ButtonsNone "Цена должна состоять только из цифр"
widgetShowAll dialog
Just curPrice' -> do
--get description of consume
curDescription <- entryGetText addDescEdt
now <- getCurrentTime
unless (null curDescription) $ do
let newItem1 = Item "Расход" curDescription curPrice' now
--add to treeSelection
_ <- listStoreAppend itemList newItem1
--add to database
update database (Insert newItem1)
--update current balance of user
curBalance' <- labelGetText balanceLbl
let updatedBalance1 = show (read curBalance' - curPrice')
labelSetText infoLbl ("Баланс = " ++ updatedBalance1)
labelSetText balanceLbl updatedBalance1
entrySetText addDescEdt ""
entrySetText addPriceEdt ""
--all is the same as above, except income
--adding new income
_ <- ($) onClicked addIncBtn $ do
curPrice <- runMaybeT $ getValidPrice addPriceEdt
case curPrice of
Nothing -> do
dialog <- messageDialogNew (Just window) [DialogDestroyWithParent]
MessageError ButtonsNone "Цена должна состоять только из цифр"
widgetShowAll dialog
Just curPrice' -> do
curDescription <- entryGetText addDescEdt
now <- getCurrentTime
unless (null curDescription) $ do
let newItem2 = Item "Доход" curDescription curPrice' now
_ <- listStoreAppend itemList newItem2
update database (Insert newItem2)
curBalance' <- labelGetText balanceLbl
let updatedBalance2 = show (read curBalance' + curPrice')
labelSetText infoLbl ("Баланс = " ++ updatedBalance2)
labelSetText balanceLbl updatedBalance2
entrySetText addDescEdt ""
entrySetText addPriceEdt ""
--edit consume/income
_ <- ($) onClicked saveBtn $ do
selRows <- treeSelectionGetSelectedRows selection
unless (length selRows < 1) $ do
let index = head (head selRows)
curPrice <- runMaybeT $ getValidPrice editPriceEdt
case curPrice of
Nothing -> do
dialog <- messageDialogNew (Just window) [DialogDestroyWithParent]
MessageError ButtonsNone "Цена должна состоять только из цифр"
widgetShowAll dialog
Just curPrice' -> do
curDescription <- entryGetText editDescEdt :: IO String
v <- listStoreGetValue itemList index
unless (null curDescription) $ do
let newItem = Item (v^.typo) curDescription curPrice' (v^.time)
--edit treeView
listStoreSetValue itemList index newItem
--edit database
update database (Edit index newItem)
--update current balance of user
let curBalance' = read $ unsafePerformIO $ labelGetText balanceLbl
let updatedBalance = show $ if newItem^.typo == "Доход" then curBalance' + curPrice' - (v^.price) else curBalance' - curPrice' + (v^.price)
labelSetText infoLbl ("Баланс = " ++ updatedBalance)
labelSetText balanceLbl updatedBalance
entrySetText editDescEdt ""
entrySetText editPriceEdt ""
--delete income/consume
_ <- ($) onClicked delBtn $ do
--get selected rows
selRows <- treeSelectionGetSelectedRows selection
unless (null selRows) $ do
let index = head (head selRows)
--edit treeView
v <- listStoreGetValue itemList index
let curBalance' = read $ unsafePerformIO $ labelGetText balanceLbl
--update current balance of user
let updatedBalance = show $ if v^.typo == "Доход" then curBalance' - (v^.price) else curBalance' + (v^.price)
labelSetText infoLbl ("Баланс = " ++ updatedBalance)
labelSetText balanceLbl updatedBalance
--remove from database
update database (DeleteByPos index)
listStoreRemove itemList index
entrySetText editDescEdt ""
entrySetText editPriceEdt ""
--set entry's values to selectied item values
_ <- ($) onSelectionChanged selection $ onSelectionChangedHandler itemList editPriceEdt editDescEdt selection
--open new window with some info about developer
_ <- ($) onClicked aboutDeveloperBtn aboutDeveloperBtnHandler
--open new window, which configurates diagrams
_ <- ($) onClicked infoDiagramBtn $ do
updQuariedItemList <- query database GetItemList
infoDiagramBtnHandler updQuariedItemList
_ <- onDestroy window mainQuit
_ <- onDestroy window (closeAcidState database)
widgetShowAll window
mainGUI
| deynekalex/Money-Haskell-Project- | src/Main.hs | gpl-2.0 | 11,285 | 0 | 33 | 3,278 | 2,523 | 1,152 | 1,371 | 206 | 6 |
{-# LANGUAGE UnicodeSyntax, OverloadedStrings #-}
module Audit.ObjectHistory
( ObjectEdit
, VersionedObject
, ObjectHistory
, AuditTreeDelta
, describeChangeTree
)
where
import BaseImport
import Data.Tree.NTree.TypeDefs
import Audit.EditAction
import Audit.ContentHistory
import Audit.VersionedChange
import Diff.DiffTree
import Diff.ObjectTree
import ExtRep.XmlToObjectTree
import Util.EntityKey (EntityKey)
import Util.Hxt
type ObjectEdit = EditAction EntityKey Text
type VersionedObject = VersionedChange EntityKey Text
type ObjectHistory = ContentHistory EntityKey Text
type AuditTree = ObjectTree NTree
type AuditTreeDelta = DiffTree NTree ObjectNode
--
-- diff previous object tree with current.
-- note: if new object, tree delta will have all nodes marked as new;
-- if deleted object, tree delta will be empty.
--
describeChangeTree ∷ ObjectEdit → AuditTreeDelta
describeChangeTree = uncurry diff ∘ prevAndCurrentTrees ∘ auditedContent
where
prevAndCurrentTrees (NewContent x) = (fromText "", fromText x)
prevAndCurrentTrees (ModContent x₁ x₂) = (fromText x₁, fromText x₂)
prevAndCurrentTrees (DelContent x) = (fromText x, fromText "")
fromText ∷ Text → AuditTree
fromText = fromXml ∘ toXTree
| c0c0n3/audidoza | app/Audit/ObjectHistory.hs | gpl-3.0 | 1,306 | 8 | 9 | 232 | 268 | 151 | 117 | 29 | 3 |
{-# LANGUAGE GADTs #-}
-- | A package that links all submodules together into a program.
module Dep (main) where
import Control.Monad(liftM,void)
import Data.ByteString(hPut)
import Data.Char(toLower,toUpper)
import Data.EnumSet(T,fromEnum,fromEnums,toEnums)
import Data.Function(on)
import Data.List(find)
import Data.Maybe(isNothing,isJust,fromJust)
import Data.Text(strip,pack,unpack)
import Data.Time.Clock(utctDay,getCurrentTime)
import Data.Time.Calendar(toGregorian)
import Graphics.UI.Gtk(mainGUI,widgetShowAll,onDestroy,mainQuit)
import System.Console.ANSI(ConsoleIntensity(BoldIntensity,NormalIntensity),SGR(SetConsoleIntensity),setSGR)
import System.Console.GetOpt(ArgDescr(NoArg,ReqArg),ArgOrder(Permute),getOpt,OptDescr(Option),usageInfo)
import System.Console.Terminal.Size(size,Window(width))
import System.Environment(getArgs)
import System.IO(Handle,hClose,hFlush,hPutStrLn,IOMode(WriteMode),openFile,stdout)
import Dep.Algorithms.Comb(synthetize)
import Dep.Algorithms.Seq(concatReduceFSM,graySequence)
import Dep.Algorithms.Cpu(CiscProgram)
import Dep.Cisc.Parser()
import Dep.Ui(clearAndExit,runMinimizeFsm,runShowKarnaugh,runSynthetize)
import Dep.Gui.Utils(initDepGui,depWindow)
import Dep.Utils(similarity,argmin)
import Dep.Structures as Str
-- | The list of input/output datatypes the program supports.
data IOType = IOInt -- ^ An integral number.
| IOCT -- ^ A combinatorial table.
| IOKC -- ^ A Karnaugh card.
| IOEC -- ^ An electronics circuit.
| IOMST -- ^ A finite state machine, any flavor.
| IOMoST -- ^ A finite state machine, Moore flavor.
| IOMyST -- ^ A finite state machine, Mealy flavor.
| IOMET -- ^ An encoded finite state machine, any flavor.
| IOMoET -- ^ An encoded finite state machine, Moore flavor.
| IOMyET -- ^ An encoded finite state machine, Mealy flavor.
| IOBS -- ^ A bitstring.
| IOBSs -- ^ A sequence of bitstrings.
| IOCisc -- ^ A CISC program.
| IOBin -- ^ A binary stream.
deriving (Bounded,Enum,Eq,Ord,Read)
data Command = Cmnd {info :: Description, function :: Driver -> String -> String -> Handle -> IO (), interactiveFunction :: Maybe (String -> String -> IO())}
data CmndFun q i o where
CmndQ :: (Read q, Read i, Printable o) => (q -> i -> o) -> CmndFun q i o --command with query
CmndN :: (Read i, Printable o) => (i -> o) -> CmndFun String i o --command without query
-- | A description for a given functionality for the dep program.
data Description = Desc {
name :: String -- ^ The name of the function, used to call the function.
,excerpt :: String -- ^ The excerpt of the function, used to shortly describe the functionality.
,input :: IOType -- ^ The type of input of the function, for instance a combinatorial table.
,output :: IOType -- ^ The type of output of the function, for instance a binary stream.
}
-- The options that can be passed to the program in order to perform the correct functionality. Some are mandatory.
data ProgramOptions = Options {
optShowVersion :: Bool -- ^ An option indicating whether the version of the program should be shown.
,optShowHelp :: Bool -- ^ An option indicating whether the help manual should be shown.
,fullDocument :: Bool -- ^ An option indicating whether a standalone document should be generated.
,outputDriver :: Driver -- ^ The driver that is called, determining the output format.
,query :: String -- ^ The query with which the proper function is called.
,interactive :: Bool -- A boolean indicating whether interactive mode is required.
,outputFile :: Maybe String -- ^ The name of the output file. If Nothing, redirects to stdout.
}
-- | The name of each input/output type.
instance Show IOType where
show IOInt = "integer"
show IOBS = "bitstring"
show IOBSs = "Sequence of bitstrings"
show IOCT = "combinatorial table"
show IOKC = "Karnaugh card"
show IOEC = "electronic circuit"
show IOMoST = "Moore state table"
show IOMyST = "Mealy state table"
show IOMST = "State table"
show IOMoET = "Moore encoding table"
show IOMyET = "Mealy encoding table"
show IOMET = "Encoding table"
show IOCisc = "CISC Assembler source code"
show IOBin = "Binary"
-- | The description of each input/output type.
instance Describeable IOType where
description IOInt = "An integral number."
description IOBS = "A sequence of bits, potentially a bit can be a don't care."
description IOBSs = "A sequence of bitstrings. Potentially a bit can be a don't care."
description IOCT = "A table consists out of two columns. Each entry contains a bitstring."
description IOCisc = "Assembler source code for the CISC processor. You can build/simulate programs with the compiler/interpreter."
description IOBin = "A sequence of zeros and ones. You better use I/O redirection to load/save it to a file."
description _ = ""
-- | The list of supported commands. Each command contains a description as well as the proper functions to provide the described functionality.
commands :: [Command]
commands = [
Cmnd (Desc "expand" "Takes as input a combinatorial table and expands the combinatorial table (don't care expansion)." IOCT IOCT) (toProg (expand :: CombTable -> CombTable)) Nothing,
Cmnd (Desc "reduce" "Takes as input a combinatorial table and reduces it by placing don't cares at the input side." IOCT IOCT) (toProg (reduce :: CombTable -> CombTable)) Nothing,
Cmnd (Desc "lookup" "Takes as input a combinatorial table and as query a bit sequence (optionally with don't cares)." IOCT IOBS) (toProgQ (btlookupThJust :: BitThSeq -> CombTable -> BitThSeq)) Nothing,
Cmnd (Desc "showKarnaugh" "Takes as input a combinatorial table and prints the corresponding Karnaugh card(s)." IOCT IOKC) (toProg KC) (Just runShowKarnaugh),
Cmnd (Desc "synthetize" "Generate a sum-of-products for the given combinatorial table." IOCT IOKC) (toProg synthetize) (Just runSynthetize),
Cmnd (Desc "minimize-fsm" "Minimize the given finite state machine to a finite state machine with a minimum amount of states. This commands works on both Moore and Mealy machines." IOMST IOMST) (toProg (concatReduceFSM :: FSM String BitThSeq BitThSeq -> FSM String BitThSeq BitThSeq)) (Just runMinimizeFsm),
Cmnd (Desc "generate-gray" "Generate for the given number, the sequence of Gray codes with the given number of bits." IOInt IOBSs) (toProg graySequence) Nothing,
Cmnd (Desc "compile-cisc" "Compile the CISC assembler-language input to CISC machine code." IOCisc IOBin) (toProgB (id :: CiscProgram -> CiscProgram)) Nothing
]
-- | A function that maps the input/output types on a set of supported drivers. By default, only the ASCII driver is supported.
supportedDrivers :: IOType -- ^ The given I/O type to determine the supported output drivers from.
-> T Int Driver -- ^ The resulting set of output drivers.
supportedDrivers IOCT = Data.EnumSet.fromEnums [ASCII,SVG,LaTeX]
supportedDrivers IOKC = Data.EnumSet.fromEnum ASCII
supportedDrivers IOEC = Data.EnumSet.fromEnum ASCII
supportedDrivers _ = Data.EnumSet.fromEnum ASCII
-- | Convert the given function into an IO program that takes as input a driver, query and input.
toProg :: (Read a, Printable b) => (a -> b) -> Driver -> String -> String -> Handle -> IO ()
toProg f d _ ip h = do
cw <- consoleWidth
hPutStrLn h $ Str.print d cw $ f $ read ip
toProgS :: (Read a) => (a -> String) -> Driver -> String -> String -> Handle -> IO ()
toProgS f _ _ ip h = hPutStrLn h $ f $ read ip
toProgQ :: (Read a, Read q, Printable b) => (q -> a -> b) -> Driver -> String -> String -> Handle -> IO ()
toProgQ f d q ip h = do
cw <- consoleWidth
hPutStrLn h $ Str.print d cw $ f (read q) $ read ip
toProgB :: (Read a, Serializeable b) => (a -> b) -> Driver -> String -> String -> Handle -> IO ()
toProgB f _ _ ip h = hPut h $ Str.serializeByteString $ f $ read ip
defaultOptions :: ProgramOptions
defaultOptions = Options {
optShowVersion = False,
optShowHelp = False,
outputDriver = ASCII,
fullDocument = False,
query = [],
interactive = False,
outputFile = Nothing
}
getOutputHandle :: ProgramOptions -> IO Handle
getOutputHandle p | Just fn <- outputFile p = openFile fn WriteMode
| otherwise = return stdout
options :: [OptDescr (ProgramOptions -> ProgramOptions)]
options =
[ Option "v" ["version"]
(NoArg (\opts -> opts { optShowVersion = True }))
"Show version number."
, Option "h?" ["help"]
(NoArg (\opts -> opts { optShowHelp = True }))
"Show this help sequence."
, Option [] ["ascii"]
(NoArg (\opts -> opts { outputDriver = ASCII }))
"Print output using the ASCII driver."
, Option [] ["svg"]
(NoArg (\opts -> opts { outputDriver = SVG }))
"Print output using the HTML/SVG driver."
, Option [] ["html"]
(NoArg (\opts -> opts { outputDriver = SVG }))
"Print output using the HTML/SVG driver."
, Option [] ["latex"]
(NoArg (\opts -> opts { outputDriver = LaTeX }))
"Print output using the LaTeX driver."
, Option "s" ["standalone"]
(NoArg (\opts -> opts { fullDocument = True }))
"Create a standalone document (only when using the HTML/SVG or LaTeX driver)."
, Option "o" ["output"]
(ReqArg (\q opts -> opts {outputFile = Just q}) "file")
"Write the output to the specified file instead of STDOUT."
, Option "q" ["query"]
(ReqArg (\q opts -> opts { query = q }) "query")
"Provide a query context (for the specified command)."
, Option "i" ["interactive"]
(NoArg (\opts -> opts { interactive = True }))
"The program will - if possible for the given task - use an text-based interactive user interface. The terminal in which the program runs should support the ANSI terminal standard."
]
compilerOpts :: [String] -> IO (ProgramOptions, [String])
compilerOpts argv =
case getOpt Permute options argv of
(o,n,[] ) -> return (foldl (flip id) defaultOptions o, n)
(_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
where header = "Usage: dep command [OPTIONS...]"
stripTitle :: String -> String
stripTitle = unpack.strip.pack
stripContent :: String -> String
stripContent x = ' ':' ':(unpack.strip.pack) x
printHeader :: String -> IO ()
printHeader t = do
ic <- isConsole
if ic then do
setSGR [SetConsoleIntensity BoldIntensity]
putStrLn $ map toUpper $ stripTitle t
setSGR [SetConsoleIntensity NormalIntensity]
else putStrLn $ map toUpper $ stripTitle t
printChapter :: String -> String -> IO ()
printChapter t c = do
printHeader t
putStrLn $ stripContent c
putStrLn []
printChapterList :: String -> (a -> IO ()) -> [a] -> IO ()
printChapterList t f vs = do
printHeader t
putStrLn []
mapM_ f vs
putStrLn []
showExcerpt :: Command -> IO()
showExcerpt (Cmnd d _ _) = do
ic <- isConsole
if ic then do
setSGR [SetConsoleIntensity BoldIntensity]
putStrLn $ " "++name d
setSGR [SetConsoleIntensity NormalIntensity]
putStrLn $ " "++excerpt d
else do
putStrLn $ " "++name d
putStrLn $ " "++excerpt d
-- | Get the current date according the Gergorian calendar represented as a tuple containing the year, month and day.
date :: IO (Integer,Int,Int) -- ^ An I/O operation returning a tuple contain the year, month and day.
date = liftM (toGregorian . utctDay) getCurrentTime
header :: IO ()
header = putStrLn $ unlines [" ____ ",
"| _ \\ ___ _ __ ",
"| | | |/ _ \\ '_ \\ ",
"| |_| | __/ |_) |",
"|____/ \\___| .__/ ",
" |_|"]
copyright :: IO ()
copyright = do
(yr,_,_) <- date
printChapter ca $ (++) cb (if yr > 2015 then '-':show yr++cc else cc)
where ca = "copyright"
cb = "dep is copyright (c) 2015"
cc = " by Willem M. A. Van Onsem"
printNegation :: Bool -> String
printNegation False = " not"
printNegation True = ""
showFunctionHelp :: String -> Command -> Description -> IO ()
showFunctionHelp s c d = do
printChapter "name" $ "dep "++s++" - "++excerpt d
printChapter "input" $ namedescribe $ input d
printChapter "output" $ namedescribe (output d)++"\n\n Supported output formats:\n"++unlines (map (\x -> " - "++show x) $ toEnums $ supportedDrivers $ output d)
printChapter "interactive" $ "Interactive mode is"++printNegation (isJust $ interactiveFunction c)++" supported."
copyright
processCommand :: String -> Maybe Command -> ProgramOptions -> String -> IO ()
processCommand s Nothing _ _ = error ("Command \""++s++"\" unknown. Perhaps you meant \""++argmin (on similarity maplow s) cns++"\"?")
where cns = map (name.info) commands
maplow = map toLower
processCommand s (Just c) po inp | optShowHelp po = showFunctionHelp s c d
| not $ interactive po = do
h <- getOutputHandle po
function c (outputDriver po) (query po) inp h
hFlush h
hClose h
| isNothing ic = error ("No interactive mode supported for command \""++s++"\".")
| otherwise = void (fic (query po) inp >> clearAndExit)
where d = info c
ic = interactiveFunction c
fic = fromJust ic
isConsole :: IO Bool
isConsole = liftM isJust size
consoleWidth :: IO (Maybe Int)
consoleWidth = liftM f size
where f (Just wind) = Just $ width wind
f Nothing = Nothing
--consoleWidth = liftM f (size :: IO (Maybe (Window Int)))
-- where f :: Maybe (Window Int) -> Maybe Int
-- f (Just wind) = width wind
-- f Nothing = Nothing
fetchInput :: [String] -> IO String
fetchInput (_:fn:_) = readFile fn
fetchInput _ = getContents
-- | The main entry of the program: it reads the parameters and from stdin and calls the appropriate function.
main :: IO ()
main = do
args <- getArgs
(po,er) <- compilerOpts args
if length er <= 0
then do
header
printChapter "name" "dep - digital electronics synthesis and analysis"
printChapter "synopsis" "dep [COMMAND] [OPTIONS] [FILE]\n dep [COMMAND] [OPTIONS] --interactive FILE\n dep [COMMAND] --help"
printChapter "description" "A companion program for the book \"Digitale Elektronica en Processoren\" by Willem M. A. Van Onsem."
printChapterList "commands" showExcerpt commands
printChapter "options" $ usageInfo "" options
printChapter "input" "By default, the program reads from STDIN, if a FILE is provided, it reads from the file.\n In case interactive mode is used, the program cannot read from STDIN (since it reads keystrokes), in that case you should provide a FILE."
copyright
else do
inp <- fetchInput er
processCommand (head er) (find ((==) (head er) . name . info) commands) po inp
| KommuSoft/dep-software | Dep.hs | gpl-3.0 | 15,477 | 0 | 18 | 3,787 | 3,727 | 1,976 | 1,751 | 260 | 2 |
module HEP.Automation.MadGraph.Dataset.Set20110428set3 where
import HEP.Storage.WebDAV
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Model.ZpHFull
import HEP.Automation.MadGraph.Dataset.Common
import HEP.Automation.MadGraph.Dataset.Processes
import qualified Data.ByteString as B
psetup_zphfull_TZpLep :: ProcessSetup ZpHFull
psetup_zphfull_TZpLep = PS {
mversion = MadGraph4
, model = ZpHFull
, process = preDefProcess TZpLep
, processBrief = "TZpLep"
, workname = "428ZpH_TZpLep"
}
zpHFullParamSet :: [ModelParam ZpHFull]
zpHFullParamSet = [ ZpHFullParam m g (0.28)
| m <-[140.0]
, g <- [0.90] ]
psetuplist :: [ProcessSetup ZpHFull]
psetuplist = [ psetup_zphfull_TZpLep ]
sets :: [Int]
sets = [102,103..110] -- [101]
zptasklist :: ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
zptasklist ssetup csetup =
[ WS ssetup (psetup_zphfull_TZpLep)
(RS { param = p
, numevent = 10000
, machine = TeVatron
, rgrun = Fixed
, rgscale = 200.0
, match = NoMatch
, cut = DefCut
, pythia = RunPYTHIA
, usercut = NoUserCutDef
, pgs = RunPGS
, setnum = num
})
csetup
(WebDAVRemoteDir "mc/TeVatronFor3/ZpHFull0428Big")
| p <- zpHFullParamSet , num <- sets ]
totaltasklistEvery :: Int -> Int -> ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
totaltasklistEvery n r ssetup csetup =
let lst = zip [1..] (zptasklist ssetup csetup)
in map snd . filter (\(x,_)-> x `mod` n == r) $ lst
| wavewave/madgraph-auto-dataset | src/HEP/Automation/MadGraph/Dataset/Set20110428set3.hs | gpl-3.0 | 1,794 | 0 | 13 | 470 | 466 | 276 | 190 | 46 | 1 |
import Control.Monad( liftM, replicateM_ )
summ :: Int -> Int -> Int
summ a b = a + b
testCase = do
[a,b] <- liftM words $ getLine
putStrLn . dropWhile (=='0') . reverse . show $ summ (read $ reverse a) (read $ reverse b)
main = do
num <- getLine
replicateM_ (read num) testCase
| zhensydow/ljcsandbox | lang/haskell/spoj/solved/ADDREV.hs | gpl-3.0 | 292 | 0 | 12 | 69 | 143 | 72 | 71 | 9 | 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.MapsEngine.RasterCollections.Process
-- 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)
--
-- Process a raster collection asset.
--
-- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> for @mapsengine.rasterCollections.process@.
module Network.Google.Resource.MapsEngine.RasterCollections.Process
(
-- * REST Resource
RasterCollectionsProcessResource
-- * Creating a Request
, rasterCollectionsProcess
, RasterCollectionsProcess
-- * Request Lenses
, rcpId
) where
import Network.Google.MapsEngine.Types
import Network.Google.Prelude
-- | A resource alias for @mapsengine.rasterCollections.process@ method which the
-- 'RasterCollectionsProcess' request conforms to.
type RasterCollectionsProcessResource =
"mapsengine" :>
"v1" :>
"rasterCollections" :>
Capture "id" Text :>
"process" :>
QueryParam "alt" AltJSON :>
Post '[JSON] ProcessResponse
-- | Process a raster collection asset.
--
-- /See:/ 'rasterCollectionsProcess' smart constructor.
newtype RasterCollectionsProcess = RasterCollectionsProcess'
{ _rcpId :: Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'RasterCollectionsProcess' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rcpId'
rasterCollectionsProcess
:: Text -- ^ 'rcpId'
-> RasterCollectionsProcess
rasterCollectionsProcess pRcpId_ =
RasterCollectionsProcess'
{ _rcpId = pRcpId_
}
-- | The ID of the raster collection.
rcpId :: Lens' RasterCollectionsProcess Text
rcpId = lens _rcpId (\ s a -> s{_rcpId = a})
instance GoogleRequest RasterCollectionsProcess where
type Rs RasterCollectionsProcess = ProcessResponse
type Scopes RasterCollectionsProcess =
'["https://www.googleapis.com/auth/mapsengine"]
requestClient RasterCollectionsProcess'{..}
= go _rcpId (Just AltJSON) mapsEngineService
where go
= buildClient
(Proxy :: Proxy RasterCollectionsProcessResource)
mempty
| rueshyna/gogol | gogol-maps-engine/gen/Network/Google/Resource/MapsEngine/RasterCollections/Process.hs | mpl-2.0 | 2,918 | 0 | 13 | 644 | 303 | 186 | 117 | 49 | 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.Cloudbuild.Projects.Builds.Create
-- 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)
--
-- Starts a build with the specified configuration. The long-running
-- Operation returned by this method will include the ID of the build,
-- which can be passed to GetBuild to determine its status (e.g., success
-- or failure).
--
-- /See:/ <https://cloud.google.com/container-builder/docs/ Google Cloud Container Builder API Reference> for @cloudbuild.projects.builds.create@.
module Network.Google.Resource.Cloudbuild.Projects.Builds.Create
(
-- * REST Resource
ProjectsBuildsCreateResource
-- * Creating a Request
, projectsBuildsCreate
, ProjectsBuildsCreate
-- * Request Lenses
, pXgafv
, pUploadProtocol
, pPp
, pAccessToken
, pUploadType
, pPayload
, pBearerToken
, pProjectId
, pCallback
) where
import Network.Google.ContainerBuilder.Types
import Network.Google.Prelude
-- | A resource alias for @cloudbuild.projects.builds.create@ method which the
-- 'ProjectsBuildsCreate' request conforms to.
type ProjectsBuildsCreateResource =
"v1" :>
"projects" :>
Capture "projectId" Text :>
"builds" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Build :> Post '[JSON] Operation
-- | Starts a build with the specified configuration. The long-running
-- Operation returned by this method will include the ID of the build,
-- which can be passed to GetBuild to determine its status (e.g., success
-- or failure).
--
-- /See:/ 'projectsBuildsCreate' smart constructor.
data ProjectsBuildsCreate = ProjectsBuildsCreate'
{ _pXgafv :: !(Maybe Xgafv)
, _pUploadProtocol :: !(Maybe Text)
, _pPp :: !Bool
, _pAccessToken :: !(Maybe Text)
, _pUploadType :: !(Maybe Text)
, _pPayload :: !Build
, _pBearerToken :: !(Maybe Text)
, _pProjectId :: !Text
, _pCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProjectsBuildsCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pXgafv'
--
-- * 'pUploadProtocol'
--
-- * 'pPp'
--
-- * 'pAccessToken'
--
-- * 'pUploadType'
--
-- * 'pPayload'
--
-- * 'pBearerToken'
--
-- * 'pProjectId'
--
-- * 'pCallback'
projectsBuildsCreate
:: Build -- ^ 'pPayload'
-> Text -- ^ 'pProjectId'
-> ProjectsBuildsCreate
projectsBuildsCreate pPPayload_ pPProjectId_ =
ProjectsBuildsCreate'
{ _pXgafv = Nothing
, _pUploadProtocol = Nothing
, _pPp = True
, _pAccessToken = Nothing
, _pUploadType = Nothing
, _pPayload = pPPayload_
, _pBearerToken = Nothing
, _pProjectId = pPProjectId_
, _pCallback = Nothing
}
-- | V1 error format.
pXgafv :: Lens' ProjectsBuildsCreate (Maybe Xgafv)
pXgafv = lens _pXgafv (\ s a -> s{_pXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pUploadProtocol :: Lens' ProjectsBuildsCreate (Maybe Text)
pUploadProtocol
= lens _pUploadProtocol
(\ s a -> s{_pUploadProtocol = a})
-- | Pretty-print response.
pPp :: Lens' ProjectsBuildsCreate Bool
pPp = lens _pPp (\ s a -> s{_pPp = a})
-- | OAuth access token.
pAccessToken :: Lens' ProjectsBuildsCreate (Maybe Text)
pAccessToken
= lens _pAccessToken (\ s a -> s{_pAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pUploadType :: Lens' ProjectsBuildsCreate (Maybe Text)
pUploadType
= lens _pUploadType (\ s a -> s{_pUploadType = a})
-- | Multipart request metadata.
pPayload :: Lens' ProjectsBuildsCreate Build
pPayload = lens _pPayload (\ s a -> s{_pPayload = a})
-- | OAuth bearer token.
pBearerToken :: Lens' ProjectsBuildsCreate (Maybe Text)
pBearerToken
= lens _pBearerToken (\ s a -> s{_pBearerToken = a})
-- | ID of the project.
pProjectId :: Lens' ProjectsBuildsCreate Text
pProjectId
= lens _pProjectId (\ s a -> s{_pProjectId = a})
-- | JSONP
pCallback :: Lens' ProjectsBuildsCreate (Maybe Text)
pCallback
= lens _pCallback (\ s a -> s{_pCallback = a})
instance GoogleRequest ProjectsBuildsCreate where
type Rs ProjectsBuildsCreate = Operation
type Scopes ProjectsBuildsCreate =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsBuildsCreate'{..}
= go _pProjectId _pXgafv _pUploadProtocol (Just _pPp)
_pAccessToken
_pUploadType
_pBearerToken
_pCallback
(Just AltJSON)
_pPayload
containerBuilderService
where go
= buildClient
(Proxy :: Proxy ProjectsBuildsCreateResource)
mempty
| rueshyna/gogol | gogol-containerbuilder/gen/Network/Google/Resource/Cloudbuild/Projects/Builds/Create.hs | mpl-2.0 | 5,900 | 0 | 20 | 1,469 | 943 | 549 | 394 | 128 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.CreateAccountAlias
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates an alias for your AWS account. For information about using an
-- AWS account alias, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html Using an Alias for Your AWS Account ID>
-- in the /IAM User Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccountAlias.html AWS API Reference> for CreateAccountAlias.
module Network.AWS.IAM.CreateAccountAlias
(
-- * Creating a Request
createAccountAlias
, CreateAccountAlias
-- * Request Lenses
, caaAccountAlias
-- * Destructuring the Response
, createAccountAliasResponse
, CreateAccountAliasResponse
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'createAccountAlias' smart constructor.
newtype CreateAccountAlias = CreateAccountAlias'
{ _caaAccountAlias :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateAccountAlias' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'caaAccountAlias'
createAccountAlias
:: Text -- ^ 'caaAccountAlias'
-> CreateAccountAlias
createAccountAlias pAccountAlias_ =
CreateAccountAlias'
{ _caaAccountAlias = pAccountAlias_
}
-- | The account alias to create.
caaAccountAlias :: Lens' CreateAccountAlias Text
caaAccountAlias = lens _caaAccountAlias (\ s a -> s{_caaAccountAlias = a});
instance AWSRequest CreateAccountAlias where
type Rs CreateAccountAlias =
CreateAccountAliasResponse
request = postQuery iAM
response = receiveNull CreateAccountAliasResponse'
instance ToHeaders CreateAccountAlias where
toHeaders = const mempty
instance ToPath CreateAccountAlias where
toPath = const "/"
instance ToQuery CreateAccountAlias where
toQuery CreateAccountAlias'{..}
= mconcat
["Action" =: ("CreateAccountAlias" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"AccountAlias" =: _caaAccountAlias]
-- | /See:/ 'createAccountAliasResponse' smart constructor.
data CreateAccountAliasResponse =
CreateAccountAliasResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateAccountAliasResponse' with the minimum fields required to make a request.
--
createAccountAliasResponse
:: CreateAccountAliasResponse
createAccountAliasResponse = CreateAccountAliasResponse'
| olorin/amazonka | amazonka-iam/gen/Network/AWS/IAM/CreateAccountAlias.hs | mpl-2.0 | 3,302 | 0 | 9 | 633 | 366 | 225 | 141 | 52 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.TargetHTTPProxies.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 the list of TargetHttpProxy resources available to the
-- specified project.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetHttpProxies.list@.
module Network.Google.Resource.Compute.TargetHTTPProxies.List
(
-- * REST Resource
TargetHTTPProxiesListResource
-- * Creating a Request
, targetHTTPProxiesList
, TargetHTTPProxiesList
-- * Request Lenses
, thttpplOrderBy
, thttpplProject
, thttpplFilter
, thttpplPageToken
, thttpplMaxResults
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.targetHttpProxies.list@ method which the
-- 'TargetHTTPProxiesList' request conforms to.
type TargetHTTPProxiesListResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"targetHttpProxies" :>
QueryParam "orderBy" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] TargetHTTPProxyList
-- | Retrieves the list of TargetHttpProxy resources available to the
-- specified project.
--
-- /See:/ 'targetHTTPProxiesList' smart constructor.
data TargetHTTPProxiesList = TargetHTTPProxiesList'
{ _thttpplOrderBy :: !(Maybe Text)
, _thttpplProject :: !Text
, _thttpplFilter :: !(Maybe Text)
, _thttpplPageToken :: !(Maybe Text)
, _thttpplMaxResults :: !(Textual Word32)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'TargetHTTPProxiesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'thttpplOrderBy'
--
-- * 'thttpplProject'
--
-- * 'thttpplFilter'
--
-- * 'thttpplPageToken'
--
-- * 'thttpplMaxResults'
targetHTTPProxiesList
:: Text -- ^ 'thttpplProject'
-> TargetHTTPProxiesList
targetHTTPProxiesList pThttpplProject_ =
TargetHTTPProxiesList'
{ _thttpplOrderBy = Nothing
, _thttpplProject = pThttpplProject_
, _thttpplFilter = Nothing
, _thttpplPageToken = Nothing
, _thttpplMaxResults = 500
}
-- | Sorts list results by a certain order. By default, results are returned
-- in alphanumerical order based on the resource name. You can also sort
-- results in descending order based on the creation timestamp using
-- orderBy=\"creationTimestamp desc\". This sorts results based on the
-- creationTimestamp field in reverse chronological order (newest result
-- first). Use this to sort resources like operations so that the newest
-- operation is returned first. Currently, only sorting by name or
-- creationTimestamp desc is supported.
thttpplOrderBy :: Lens' TargetHTTPProxiesList (Maybe Text)
thttpplOrderBy
= lens _thttpplOrderBy
(\ s a -> s{_thttpplOrderBy = a})
-- | Project ID for this request.
thttpplProject :: Lens' TargetHTTPProxiesList Text
thttpplProject
= lens _thttpplProject
(\ s a -> s{_thttpplProject = a})
-- | Sets a filter expression for filtering listed resources, in the form
-- filter={expression}. Your {expression} must be in the format: field_name
-- comparison_string literal_string. The field_name is the name of the
-- field you want to compare. Only atomic field types are supported
-- (string, number, boolean). The comparison_string must be either eq
-- (equals) or ne (not equals). The literal_string is the string value to
-- filter to. The literal value must be valid for the type of field you are
-- filtering by (string, number, boolean). For string fields, the literal
-- value is interpreted as a regular expression using RE2 syntax. The
-- literal value must match the entire field. For example, to filter for
-- instances that do not have a name of example-instance, you would use
-- filter=name ne example-instance. You can filter on nested fields. For
-- example, you could filter on instances that have set the
-- scheduling.automaticRestart field to true. Use filtering on nested
-- fields to take advantage of labels to organize and search for results
-- based on label values. To filter on multiple expressions, provide each
-- separate expression within parentheses. For example,
-- (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple
-- expressions are treated as AND expressions, meaning that resources must
-- match all expressions to pass the filters.
thttpplFilter :: Lens' TargetHTTPProxiesList (Maybe Text)
thttpplFilter
= lens _thttpplFilter
(\ s a -> s{_thttpplFilter = a})
-- | Specifies a page token to use. Set pageToken to the nextPageToken
-- returned by a previous list request to get the next page of results.
thttpplPageToken :: Lens' TargetHTTPProxiesList (Maybe Text)
thttpplPageToken
= lens _thttpplPageToken
(\ s a -> s{_thttpplPageToken = a})
-- | The maximum number of results per page that should be returned. If the
-- number of available results is larger than maxResults, Compute Engine
-- returns a nextPageToken that can be used to get the next page of results
-- in subsequent list requests.
thttpplMaxResults :: Lens' TargetHTTPProxiesList Word32
thttpplMaxResults
= lens _thttpplMaxResults
(\ s a -> s{_thttpplMaxResults = a})
. _Coerce
instance GoogleRequest TargetHTTPProxiesList where
type Rs TargetHTTPProxiesList = TargetHTTPProxyList
type Scopes TargetHTTPProxiesList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient TargetHTTPProxiesList'{..}
= go _thttpplProject _thttpplOrderBy _thttpplFilter
_thttpplPageToken
(Just _thttpplMaxResults)
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy TargetHTTPProxiesListResource)
mempty
| rueshyna/gogol | gogol-compute/gen/Network/Google/Resource/Compute/TargetHTTPProxies/List.hs | mpl-2.0 | 7,012 | 0 | 18 | 1,502 | 678 | 409 | 269 | 101 | 1 |
#!/usr/local/bin/perl
$buffer = $ENV{'QUERY_STRING'};
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
local ($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~
s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
$value =~ s/~!/ ~!/g;
$FORM{$name} = $value;
}
##return =true
1;
| drlouie/public-views | _client-workareas/COASTLINE/backup/03022001/parse_query.hs | apache-2.0 | 325 | 21 | 13 | 65 | 214 | 108 | 106 | -1 | -1 |
{-
Copyright 2020 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 = blank
foo = blank | google/codeworld | codeworld-compiler/test/testcases/indentedDecl/source.hs | apache-2.0 | 639 | 1 | 5 | 122 | 14 | 7 | 7 | -1 | -1 |
module Palindromes.A249629Spec (main, spec) where
import Test.Hspec
import Palindromes.A249629 (a249629)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A249629" $
it "correctly computes the first 10 elements" $
take 10 (map a249629 [0..]) `shouldBe` expectedValue where
expectedValue = [0,0,4,28,124,532,2164,8788,35284,141628]
| peterokagey/haskellOEIS | test/Palindromes/A249629Spec.hs | apache-2.0 | 357 | 0 | 10 | 59 | 130 | 75 | 55 | 10 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.V1.GCEPersistentDiskVolumeSource where
import GHC.Generics
import Data.Text
import qualified Data.Aeson
-- | GCEPersistentDiskVolumeSource represents a Persistent Disk resource in Google Compute Engine.\n\nA GCE PD must exist and be formatted before mounting to a container. The disk must also be in the same GCE project and zone as the kubelet. A GCE PD can only be mounted as read/write once.
data GCEPersistentDiskVolumeSource = GCEPersistentDiskVolumeSource
{ pdName :: Text -- ^ Unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk
, fsType :: Text -- ^ Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk
, partition :: Maybe Integer -- ^ The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty). More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk
, readOnly :: Maybe Bool -- ^ ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON GCEPersistentDiskVolumeSource
instance Data.Aeson.ToJSON GCEPersistentDiskVolumeSource
| minhdoboi/deprecated-openshift-haskell-api | openshift/lib/Openshift/V1/GCEPersistentDiskVolumeSource.hs | apache-2.0 | 1,859 | 0 | 9 | 259 | 107 | 66 | 41 | 17 | 0 |
module Main where
import qualified Data.Avro as AV
import Test.Framework (defaultMain, testGroup, Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Providers.HUnit (testCase)
import Test.QuickCheck
import Test.HUnit
import qualified Data.ByteString.Char8 as B
import qualified Data.Aeson as AE
import qualified Data.Text as T
import Data.Avro
tests = [
testGroup "cases" $ zipWith (testCase . show) [1::Int ..] $
[ case_parsePrimitiveSchema
, case_readSimpleAvro
]
, testGroup "properties" $ zipWith (testProperty . show) [1::Int ..] $
[ property prop_theProperty]
]
--------------------------------------------------
case_parsePrimitiveSchema = assertEqual "Failed to parse the primitive schema" expected obtained
where
expected = ABytes
obtained = decode $ B.pack "bytes"
--------------------------------------------------
case_readSimpleAvro = assertEqual "Failed reading data from file" expected obtained
where
expected = AvroFile AInt [1,2,3]
obtained = undefined
--------------------------------------------------
-- objectSchema = B.pack "{\"type\":\"record\",\"name\":\"myRecord\"}"
--
-- case_parseJsonObject = assertEqual "Failed to parse the Json object schema definition" expected obtained
-- where
-- expected = ARecord "myRecord"
-- obtained = decode objectSchema
--------------------------------------------------
prop_theProperty = True
-- Main program
main = defaultMain tests
| tonicebrian/avro-haskell | tests/Main.hs | apache-2.0 | 1,553 | 0 | 10 | 281 | 270 | 165 | 105 | 25 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.Kafka.Types where
import qualified Codec.Compression.GZip as GZip
import Control.Applicative
import Control.Lens
import Control.Monad
import Debug.Trace
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as L
import Data.Digest.CRC32
import Data.Hashable
import Data.Int
import qualified Data.IntMap.Strict as I
import Data.IORef
import qualified Data.Vector as V
import qualified Data.Vector.Generic as G
import GHC.Generics hiding (to)
import GHC.TypeLits
import Network.Simple.TCP (HostName, ServiceName, Socket)
import Network.Kafka.Exports
newtype CorrelationId = CorrelationId { fromCorrelationId :: Int32 }
deriving (Show, Eq, Ord, Binary, ByteSize)
newtype Utf8 = Utf8 { fromUtf8 :: ByteString }
deriving (Show, Eq, Hashable)
instance Binary Utf8 where
get = do
len <- fromIntegral <$> getInt16be
Utf8 <$> getByteString len
put (Utf8 str) = if BS.null str
then putInt16be (-1)
else do
putInt16be $ fromIntegral $ BS.length str
putByteString str
instance ByteSize Utf8 where
byteSize (Utf8 bs) = 2 + fromIntegral (BS.length bs)
data Acks
= All
| LeaderOnly
| NoAck
instance Enum Acks where
toEnum (-1) = All
toEnum 0 = NoAck
toEnum 1 = LeaderOnly
fromEnum All = -1
fromEnum NoAck = 0
fromEnum LeaderOnly = 1
data ResetPolicy
= Earliest
| Latest
| None
| Anything
data KafkaConfig = KafkaConfig
{ kafkaConfigFetchMaxWaitTime :: !Int
, kafkaConfigFetchMinBytes :: !Int
, kafkaConfigFetchMaxBytes :: !Int
, kafkaConfigBootstrapServers :: !(V.Vector (HostName, ServiceName))
, kafkaConfigAcks :: !Acks
, kafkaConfigBufferMemory :: !Int
, kafkaConfigRetries :: !Int
, kafkaConfigBatchSize :: !Int
, kafkaConfigClientId :: !Utf8
, kafkaConfigGroupId :: !Utf8
, kafkaConfigClientMaxIdleMs :: !Int
, kafkaConfigLingerMs :: !Int
, kafkaConfigMaxRequestSize :: !Int
, kafkaConfigReceiveBufferBytes :: !Int
, kafkaConfigSendBufferBytes :: !Int
, kafkaConfigBlockOnBufferFull :: !Bool
, kafkaConfigMaxInFlightRequestsPerConnection :: !Int
, kafkaConfigMetadataFetchTimeout :: !Int
, kafkaConfigMetadataMaxAgeMs :: !Int
, kafkaConfigReconnectBackoffMs :: !Int
, kafkaConfigRetryBackoffMs :: !Int
, kafkaConfigHeartbeatIntervalMs :: !Int
, kafkaConfigMaxPartitionFetchBytes :: !Int
, kafkaConfigSessionTimeout :: !Int
, kafkaConfigAutoOffsetReset :: !ResetPolicy
, kafkaConfigConnectionMaxIdleMs :: !Int
, kafkaConfigEnableAutoCommit :: !Bool
, kafkaConfigAutoCommitInterval :: !Int
, kafkaConfigCheckCrcs :: !Bool
, kafkaConfigTimeoutMs :: !Int
}
makeFields ''KafkaConfig
defaultConfig :: KafkaConfig
defaultConfig = KafkaConfig
{ kafkaConfigFetchMaxWaitTime = 500
, kafkaConfigFetchMinBytes = 1024
, kafkaConfigFetchMaxBytes = 1024 * 1024
, kafkaConfigBootstrapServers = V.empty
, kafkaConfigAcks = LeaderOnly
, kafkaConfigBufferMemory = 33554432
, kafkaConfigRetries = 0
, kafkaConfigBatchSize = 16384
, kafkaConfigClientId = Utf8 "hs-kafka"
, kafkaConfigGroupId = Utf8 ""
, kafkaConfigClientMaxIdleMs = 540000
, kafkaConfigLingerMs = 0
, kafkaConfigMaxRequestSize = 1048576
, kafkaConfigReceiveBufferBytes = 32768
, kafkaConfigSendBufferBytes = 131072
, kafkaConfigBlockOnBufferFull = False
, kafkaConfigMaxInFlightRequestsPerConnection = 5
, kafkaConfigMetadataFetchTimeout = 60000
, kafkaConfigMetadataMaxAgeMs = 300000
, kafkaConfigReconnectBackoffMs = 50
, kafkaConfigRetryBackoffMs = 100
, kafkaConfigHeartbeatIntervalMs = 3000
, kafkaConfigMaxPartitionFetchBytes = 1048576
, kafkaConfigSessionTimeout = 30000
, kafkaConfigAutoOffsetReset = Latest
, kafkaConfigConnectionMaxIdleMs = 540000
, kafkaConfigEnableAutoCommit = True
, kafkaConfigAutoCommitInterval = 5000
, kafkaConfigCheckCrcs = True
, kafkaConfigTimeoutMs = 30000
}
putL :: Binary a => Getter s a -> s -> Put
putL l = put . view l
data JoinGroup
data Heartbeat
data LeaveGroup
data SyncGroup
data DescribeGroups
data ListGroups
newtype ApiKey = ApiKey { fromApiKey :: Int16 }
deriving (Show, Eq, Ord, Binary, ByteSize)
theApiKey :: Int16 -> a -> ApiKey
theApiKey x = const $ ApiKey x
class RequestApiKey req where
apiKey :: Request req -> ApiKey
instance RequestApiKey JoinGroup where
apiKey = theApiKey 11
instance RequestApiKey Heartbeat where
apiKey = theApiKey 12
instance RequestApiKey LeaveGroup where
apiKey = theApiKey 13
instance RequestApiKey SyncGroup where
apiKey = theApiKey 14
instance RequestApiKey DescribeGroups where
apiKey = theApiKey 15
instance RequestApiKey ListGroups where
apiKey = theApiKey 16
newtype Bytes = Bytes { fromBytes :: L.ByteString }
deriving (Show, Eq, Hashable)
instance Binary Bytes where
get = do
len <- fromIntegral <$> getInt32be
if len == -1
then pure $ Bytes L.empty
else Bytes <$> getLazyByteString len
put (Bytes bs) = if L.null bs
then putInt32be (-1)
else do
putInt32be $ fromIntegral $ L.length bs
putLazyByteString bs
instance ByteSize Bytes where
byteSize (Bytes bs) = 4 + fromIntegral (L.length bs)
data Request req = Request
{ requestCorrelationId :: !CorrelationId
, requestClientId :: !Utf8
, requestMessage :: !req
} deriving (Show, Eq, Generic)
makeFields ''Request
instance (RequestApiVersion req,
RequestApiKey req,
ByteSize req,
Binary req) => Binary (Request req) where
get = do
_ <- get :: Get ApiKey
_ <- get :: Get ApiVersion
Request <$> get <*> get <*> get
put p = do
put $ apiKey p
put $ apiVersion p
put $ requestCorrelationId p
put $ requestClientId p
put $ requestMessage p
class RequestApiVersion req where
apiVersion :: req -> ApiVersion
instance RequestApiVersion req => RequestApiVersion (Request req) where
apiVersion r = apiVersion $ requestMessage r
newtype Array v a = Array { fromArray :: v a }
deriving (Show, Eq, Generic)
instance (Binary a, G.Vector v a) => Binary (Array v a) where
get = do
len <- fromIntegral <$> getInt32be
Array <$> G.replicateM len get
put (Array v) = do
putInt32be $ fromIntegral $ G.length v
G.mapM_ put v
instance (ByteSize a, Functor f, Foldable f) => ByteSize (Array f a) where
byteSize f = 4 + sum (byteSize <$> fromArray f)
instance ByteSize a => ByteSize (V.Vector a) where
byteSize v = 4 + G.sum (G.map byteSize v)
newtype FixedArray v a = FixedArray { fromFixedArray :: v a }
deriving (Show, Eq, Generic)
instance (Binary a, G.Vector v a) => Binary (FixedArray v a) where
get = (FixedArray . fromArray) <$> get
put = put . Array . fromFixedArray
instance (ByteSize a, G.Vector v a) => ByteSize (FixedArray v a) where
byteSize (FixedArray v) = 4 + (fromIntegral (G.length v) * singleSize v undefined)
where
singleSize :: ByteSize b => f b -> b -> Int32
singleSize _ = byteSize
data ErrorCode
= NoError
| Unknown
| OffsetOutOfRange
| CorruptMessage
| UnknownTopicOrPartition
| InvalidMessageSize
| LeaderNotAvailable
| NotLeaderForPartition
| RequestTimedOut
| BrokerNotAvailable
| ReplicaNotAvailable
| MessageSizeTooLarge
| StaleControllerEpoch
| OffsetMetadataTooLarge
| GroupLoadInProgress
| GroupCoordinatorNotAvailable
| NotCoordinatorForGroup
| InvalidTopic
| RecordListTooLarge
| NotEnoughReplicas
| NotEnoughReplicasAfterAppend
| InvalidRequiredAcks
| IllegalGeneration
| InconsistentGroupProtocol
| InvalidGroupId
| UnknownMemberId
| InvalidSessionTimeout
| RebalanceInProgress
| InvalidCommitOffsetSize
| TopicAuthorizationFailed
| GroupAuthorizationFailed
| ClusterAuthorizationFailed
deriving (Show, Eq, Generic)
retriable :: ErrorCode -> Bool
retriable c = case c of
CorruptMessage -> True
UnknownTopicOrPartition -> True
LeaderNotAvailable -> True
NotLeaderForPartition -> True
RequestTimedOut -> True
GroupLoadInProgress -> True
GroupCoordinatorNotAvailable -> True
NotCoordinatorForGroup -> True
NotEnoughReplicas -> True
NotEnoughReplicasAfterAppend -> True
_ -> False
instance Enum ErrorCode where
toEnum c = case c of
0 -> NoError
1 -> OffsetOutOfRange
2 -> CorruptMessage
3 -> UnknownTopicOrPartition
4 -> InvalidMessageSize
5 -> LeaderNotAvailable
6 -> NotLeaderForPartition
7 -> RequestTimedOut
8 -> BrokerNotAvailable
9 -> ReplicaNotAvailable
10 -> MessageSizeTooLarge
11 -> StaleControllerEpoch
12 -> OffsetMetadataTooLarge
14 -> GroupLoadInProgress
15 -> GroupCoordinatorNotAvailable
16 -> NotCoordinatorForGroup
17 -> InvalidTopic
18 -> RecordListTooLarge
19 -> NotEnoughReplicas
20 -> NotEnoughReplicasAfterAppend
21 -> InvalidRequiredAcks
22 -> IllegalGeneration
23 -> InconsistentGroupProtocol
24 -> InvalidGroupId
25 -> UnknownMemberId
26 -> InvalidSessionTimeout
27 -> RebalanceInProgress
28 -> InvalidCommitOffsetSize
29 -> TopicAuthorizationFailed
30 -> GroupAuthorizationFailed
31 -> ClusterAuthorizationFailed
_ -> Unknown
fromEnum c = case c of
NoError -> 0
Unknown -> -1
OffsetOutOfRange -> 1
CorruptMessage -> 2
UnknownTopicOrPartition -> 3
InvalidMessageSize -> 4
LeaderNotAvailable -> 5
NotLeaderForPartition -> 6
RequestTimedOut -> 7
BrokerNotAvailable -> 8
ReplicaNotAvailable -> 9
MessageSizeTooLarge -> 10
StaleControllerEpoch -> 11
OffsetMetadataTooLarge -> 12
GroupLoadInProgress -> 14
GroupCoordinatorNotAvailable -> 15
NotCoordinatorForGroup -> 16
InvalidTopic -> 17
RecordListTooLarge -> 18
NotEnoughReplicas -> 19
NotEnoughReplicasAfterAppend -> 20
InvalidRequiredAcks -> 21
IllegalGeneration -> 22
InconsistentGroupProtocol -> 23
InvalidGroupId -> 24
UnknownMemberId -> 25
InvalidSessionTimeout -> 26
RebalanceInProgress -> 27
InvalidCommitOffsetSize -> 28
TopicAuthorizationFailed -> 29
GroupAuthorizationFailed -> 30
ClusterAuthorizationFailed -> 31
instance Binary ErrorCode where
get = (toEnum . fromIntegral) <$> (get :: Get Int16)
put = (\x -> put (x :: Int16)) . fromIntegral . fromEnum
instance ByteSize ErrorCode where
byteSize = const 2
newtype ApiVersion = ApiVersion { fromApiVersion :: Int16 }
deriving (Show, Eq, Ord, Binary, ByteSize, Num)
newtype CoordinatorId = CoordinatorId { fromCoordinatorId :: Int32 }
deriving (Show, Eq, Ord, Binary, ByteSize)
newtype NodeId = NodeId { fromNodeId :: Int32 }
deriving (Show, Eq, Ord, Binary, ByteSize, Integral, Enum, Real, Num)
newtype PartitionId = PartitionId { fromPartitionId :: Int32 }
deriving (Show, Eq, Ord, Binary, ByteSize)
newtype ConsumerId = ConsumerId { fromConsumerId :: Utf8 }
deriving (Show, Eq, Binary, ByteSize, Hashable)
data CompressionCodec = NoCompression
| GZip
| Snappy
deriving (Show, Eq)
newtype Attributes = Attributes { attributesCompression :: CompressionCodec }
deriving (Show, Eq)
instance ByteSize Attributes where
byteSize = const 1
instance Binary Attributes where
get = do
x <- get :: Get Int8
return $ Attributes $! case x of
0 -> NoCompression
1 -> GZip
2 -> Snappy
_ -> error "Unsupported compression codec"
put (Attributes c) = do
let x = case c of
NoCompression -> 0
GZip -> 1
Snappy -> 2
put (x :: Int8)
data Message = Message
-- messageCrc would go here
{ messageAttributes :: !Attributes
, messageKey :: !Bytes
, messageValue :: !Bytes
} deriving (Show, Eq, Generic)
makeFields ''Message
instance ByteSize Message where
byteSize m = 5 + -- crc, magic byte
byteSize (messageAttributes m) +
byteSize (messageKey m) +
byteSize (messageValue m)
{-# INLINE byteSize #-}
-- TODO, make crc checking optional
instance Binary Message where
get = do
crc <- get :: Get Word32
bsStart <- bytesRead
let messageGetter = do
get :: Get Int8
msg <- Message <$> get <*> get <*> get
bsEnd <- bytesRead
return (msg, bsEnd)
(msg, bsEnd) <- lookAhead messageGetter
crcChunk <- getByteString $ fromIntegral (bsEnd - bsStart)
let crcFinal = crc32 crcChunk
if crcFinal /= crc
then fail ("Invalid CRC: expected " ++ show crc ++ ", got " ++ show crcFinal)
else return msg
put p = do
let rest = runPut $ do
put (0 :: Int8)
putL attributes p
put $ messageKey p
put $ messageValue p
msgCrc = crc32 rest
put msgCrc
putLazyByteString rest
data MessageSetItem = MessageSetItem
{ messageSetItemOffset :: !Int64
, messageSetItemMessage :: !Message
} deriving (Show, Eq, Generic)
makeFields ''MessageSetItem
instance Binary MessageSetItem where
get = do
o <- get
s <- get :: Get Int32
m <- isolate (fromIntegral s) get
return $ MessageSetItem o m
{-# INLINE get #-}
put i = do
putL offset i
putL (message . to byteSize) i
putL message i
{-# INLINE put #-}
instance ByteSize MessageSetItem where
byteSize m = byteSize (messageSetItemOffset m) +
4 + -- MessageSize
byteSize (messageSetItemMessage m)
{-# INLINE byteSize #-}
type MessageSet = [MessageSetItem]
messageSetByteSize :: MessageSet -> Int32
messageSetByteSize = sum . map byteSize
getMessageSet :: Int32 -> Get MessageSet
getMessageSet c = fmap reverse $ isolate (fromIntegral c) $ go
where
go = do
rs <- firstPass []
case rs of
[m] -> case m of
-- handle decompression and return inner message set
(MessageSetItem _ (Message (Attributes GZip) _ (Bytes v))) ->
let decompressed = GZip.decompress v in
case runGetOrFail (getMessageSet $ fromIntegral $ L.length decompressed) decompressed of
Left (_, _, err) -> fail err
-- TODO, double reverse and unwrapping is really gross
Right (_, _, rs') -> return $ reverse rs'
_ -> return rs
_ -> return rs
firstPass xs = do
pred <- isEmpty
if pred
then return xs
else do
mx <- optional get
case mx of
Nothing -> do
consumed <- bytesRead
let rem = c - fromIntegral consumed
void $ getByteString $ fromIntegral rem
return xs
Just x -> firstPass (x:xs)
putMessageSet :: MessageSet -> Put
putMessageSet = mapM_ put
newtype GenerationId = GenerationId Int32
deriving (Eq, Show, Binary, ByteSize)
newtype RetentionTime = RetentionTime Int64
deriving (Eq, Show, Binary, ByteSize)
data Response resp = Response
{ responseCorrelationId :: !CorrelationId
, responseMessage :: !resp
} deriving (Show, Eq, Generic)
makeFields ''Response
instance (ByteSize resp, Binary resp) => Binary (Response resp) where
get = Response <$> get <*> get
put p = do
put $ responseCorrelationId p
put $ responseMessage p
instance (ByteSize resp) => ByteSize (Response resp) where
byteSize p = byteSize (responseCorrelationId p) +
byteSize (responseMessage p)
instance (ByteSize req, RequestApiVersion req) => ByteSize (Request req) where
byteSize p = byteSize (undefined :: ApiKey) +
byteSize (apiVersion p) +
byteSize (requestCorrelationId p) +
byteSize (requestClientId p) +
byteSize (requestMessage p)
newMessage :: Message -> MessageSetItem
newMessage = MessageSetItem 0
uncompressed :: L.ByteString -> L.ByteString -> MessageSetItem
uncompressed k v = newMessage $ Message (Attributes NoCompression) (Bytes k) (Bytes v)
gzipCompressed :: MessageSet -> MessageSet
gzipCompressed = (:[]) . newMessage . gzippedMessage
gzippedMessage :: MessageSet -> Message
gzippedMessage = Message (Attributes GZip) (Bytes "") .
Bytes .
GZip.compress .
runPut .
putMessageSet
snappyCompressed :: L.ByteString -> L.ByteString -> Message
snappyCompressed k v = error "Not implemented"
data RecordMetadata = RecordMetadata
{ recordMetadataOffset :: Int64
, recordMetadataPartition :: PartitionId
, recordMetadataTopic :: Utf8
} deriving (Show, Eq, Generic)
makeFields ''RecordMetadata
| iand675/hs-kafka | src/Network/Kafka/Types.hs | bsd-3-clause | 18,705 | 18 | 29 | 5,544 | 4,575 | 2,418 | 2,157 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{- |
Module : AlexWeb.hs
Description : File containing the main starting point for the server.
Maintainer : <AlexGagne>
This module defines the configuration for the server and handles routing
-}
module AlexWeb where
import qualified AlexHtml as Html
import Control.Monad
import Data.Data
import qualified Happstack.Server as Happ
import System.Console.CmdArgs.Implicit ((&=))
import qualified System.Console.CmdArgs.Implicit as I
import qualified Text.Blaze.Html5 as H
main :: IO ()
main = do
config <- I.cmdArgs aConfig
posts <- Html.renderBlogPosts
Happ.simpleHTTP (hConf config) $ myApp posts
myApp :: H.Html -> Happ.ServerPart Happ.Response
myApp blogPosts = msum[Happ.dir "resume" $ Happ.serveDirectory Happ.DisableBrowsing ["data.txt"] "data",
Happ.ok $ Happ.toResponse blogPosts]
-- Config
--------------------------------------------------------------------------------
data Config =
Config { port :: Int, timeout :: Int } deriving ( Show, Eq, Data, Typeable )
hConf :: Config -> Happ.Conf
hConf Config {..} = Happ.nullConf { Happ.timeout = timeout, Happ.port = port }
aConfig :: Config
aConfig =
Config { port = 8000 &= I.help "Port number"
&= I.typ "INT"
, timeout = 30 &= I.help "Timeout"
&= I.typ "SECONDS"
}
&= I.summary "AlexWeb server"
&= I.program "server"
| AlexGagne/haskell-happstack-website | src/AlexWeb.hs | bsd-3-clause | 1,604 | 0 | 12 | 414 | 356 | 198 | 158 | 31 | 1 |
module DobadoBots.GameEngine.LevelLoader (
loadLevel
) where
import Data.Aeson (eitherDecode)
import Data.Text (Text(..))
import qualified Data.Text.Lazy as TL (fromStrict)
import Data.Text.Lazy.Encoding (encodeUtf8)
import DobadoBots.GameEngine.Data (Level(..))
loadLevel :: Text -> Either String Level
loadLevel = eitherDecode . encodeUtf8 . TL.fromStrict
| NinjaTrappeur/DobadoBots | src/DobadoBots/GameEngine/LevelLoader.hs | bsd-3-clause | 362 | 0 | 6 | 42 | 106 | 66 | 40 | 9 | 1 |
module Simple where
import Test.Framework (defaultMain, testGroup, Test)
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test)
import System.Environment (getArgs)
import Text.Syntactical
import Text.Syntactical.Data
table :: Table String
table = buildTable
[ [ closed_ "(" Distfix ")"
, closed_ "⟨" SExpression "⟩"
, closed "</" Distfix"/>"
, closed "[" Distfix "|" `distfix` "]"
, closed "{" Distfix "}"
]
, [ infx RightAssociative "?'" `distfix` ":'"
, postfx "!"
, postfx "_/" `distfix` "/."
]
, [ postfx "%"
, prefx "#"
]
, [ postfx "°"
, infx LeftAssociative "*"
, infx LeftAssociative "/"
]
, [ infx LeftAssociative "+"
, infx LeftAssociative "-"
]
, [ infx LeftAssociative "<<"
, infx LeftAssociative ">>"
, infx RightAssociative "?" `distfix` ":"
]
, [ prefx "if" `distfix` "then" `distfix` "else"
]
, [ infx RightAssociative ","
]
, [ Op1 True "\\" [(SExpression,"->")] Prefix 0
]
, [ prefx "let" `distfix` "in"
, infx RightAssociative "where"
, prefx "case" `distfix` "of"
]
, [ infx NonAssociative "="
]
, [ infx RightAssociative ";"
]
, [ infx RightAssociative "::" `distfix` ";;"
, infx RightAssociative "==" `distfix` ";;"
]
]
-- [(input, expected output)]
tests :: [(String,String)]
tests = [
("1","1"),
("a","a"),
("1 + 2","⟨␣+␣ 1 2⟩"),
("a + 2","⟨␣+␣ a 2⟩"),
("1 + b","⟨␣+␣ 1 b⟩"),
("a + b","⟨␣+␣ a b⟩"),
("1 * 2","⟨␣*␣ 1 2⟩"),
("1 + 2 + 3","⟨␣+␣ ⟨␣+␣ 1 2⟩ 3⟩"),
("1 + 2 * 3","⟨␣+␣ 1 ⟨␣*␣ 2 3⟩⟩"),
("1 * 2 + 3","⟨␣+␣ ⟨␣*␣ 1 2⟩ 3⟩")
, ("0 << 1 + 2 * 3", "⟨␣<<␣ 0 ⟨␣+␣ 1 ⟨␣*␣ 2 3⟩⟩⟩")
, ("0 + 1 << 2 * 3", "⟨␣<<␣ ⟨␣+␣ 0 1⟩ ⟨␣*␣ 2 3⟩⟩")
, ("0 + 1 * 2 << 3", "⟨␣<<␣ ⟨␣+␣ 0 ⟨␣*␣ 1 2⟩⟩ 3⟩")
, ("0 << 1 * 2 + 3", "⟨␣<<␣ 0 ⟨␣+␣ ⟨␣*␣ 1 2⟩ 3⟩⟩")
, ("0 * 1 << 2 + 3", "⟨␣<<␣ ⟨␣*␣ 0 1⟩ ⟨␣+␣ 2 3⟩⟩")
, ("0 * 1 + 2 << 3", "⟨␣<<␣ ⟨␣+␣ ⟨␣*␣ 0 1⟩ 2⟩ 3⟩")
, ("(0 << 1) + 2 * 3", "⟨␣+␣ ⟨␣<<␣ 0 1⟩ ⟨␣*␣ 2 3⟩⟩")
, ("0 << (1 + 2) * 3", "⟨␣<<␣ 0 ⟨␣*␣ ⟨␣+␣ 1 2⟩ 3⟩⟩")
, ("0 << 1 + (2 * 3)", "⟨␣<<␣ 0 ⟨␣+␣ 1 ⟨␣*␣ 2 3⟩⟩⟩")
, ("((0 << 1) + 2) * 3", "⟨␣*␣ ⟨␣+␣ ⟨␣<<␣ 0 1⟩ 2⟩ 3⟩")
, ("(((0 << 1) + 2) * 3)", "⟨␣*␣ ⟨␣+␣ ⟨␣<<␣ 0 1⟩ 2⟩ 3⟩")
, ("⟨<< 0 1⟩ + 2 * 3", "⟨␣+␣ ⟨<< 0 1⟩ ⟨␣*␣ 2 3⟩⟩")
, ("⟨+ ⟨<< 0 1⟩ 2⟩ * 3", "⟨␣*␣ ⟨+ ⟨<< 0 1⟩ 2⟩ 3⟩")
, ("f a","⟨f a⟩"),
("f 1","⟨f 1⟩"),
("f a b","⟨f a b⟩"),
("f 1 b","⟨f 1 b⟩"),
("f a 1","⟨f a 1⟩"),
("f 1 2","⟨f 1 2⟩"),
("f 1 2 3","⟨f 1 2 3⟩"),
("f a + 1","⟨␣+␣ ⟨f a⟩ 1⟩"),
("1 + f a","⟨␣+␣ 1 ⟨f a⟩⟩"),
("(a)","a"),
("((a))","a"),
("1 + (a)","⟨␣+␣ 1 a⟩"),
("1 + ((a))","⟨␣+␣ 1 a⟩"),
("(1 + 2)","⟨␣+␣ 1 2⟩"),
("(1 + (a))","⟨␣+␣ 1 a⟩"),
("(1 + ((a)))","⟨␣+␣ 1 a⟩"),
("1 * (2 + 3)","⟨␣*␣ 1 ⟨␣+␣ 2 3⟩⟩"),
("(1 + 2) * 3","⟨␣*␣ ⟨␣+␣ 1 2⟩ 3⟩"),
("1 + (f a)","⟨␣+␣ 1 ⟨f a⟩⟩"),
("(f a) + 1","⟨␣+␣ ⟨f a⟩ 1⟩"),
("(f a b) 1","⟨⟨f a b⟩ 1⟩"),
("(f a b) 1 2","⟨⟨f a b⟩ 1 2⟩"),
("1 + (f a) 2","⟨␣+␣ 1 ⟨⟨f a⟩ 2⟩⟩")
, ("f (a + b) (1 - 2)", "⟨f ⟨␣+␣ a b⟩ ⟨␣-␣ 1 2⟩⟩")
, ("⟨1⟩", "⟨1⟩")
, ("⟨a⟩", "⟨a⟩")
, ("⟨⟨1⟩⟩", "⟨⟨1⟩⟩")
, ("⟨⟨a⟩⟩", "⟨⟨a⟩⟩")
, ("⟨+ a b⟩", "⟨+ a b⟩")
, ("⟨+ a b⟩ * (1 - 2)", "⟨␣*␣ ⟨+ a b⟩ ⟨␣-␣ 1 2⟩⟩")
, ("(a + b) * ⟨- 1 2⟩", "⟨␣*␣ ⟨␣+␣ a b⟩ ⟨- 1 2⟩⟩")
, ("⟨␣*␣ (a + b) (1 - 2)⟩", "⟨␣*␣ ⟨␣+␣ a b⟩ ⟨␣-␣ 1 2⟩⟩")
, ("⟨␣*␣ (a + b) ⟨- 1 2⟩⟩", "⟨␣*␣ ⟨␣+␣ a b⟩ ⟨- 1 2⟩⟩")
, ("true ? 1 : 0", "⟨␣?␣:␣ true 1 0⟩")
, ("true ? 1 : 0 + 1", "⟨␣?␣:␣ true 1 ⟨␣+␣ 0 1⟩⟩")
, ("true ?' 1 :' 0 + 1", "⟨␣+␣ ⟨␣?'␣:'␣ true 1 0⟩ 1⟩")
, ("# a", "⟨#␣ a⟩")
, ("a # b", "⟨a ⟨#␣ b⟩⟩")
, ("# # a", "⟨#␣ ⟨#␣ a⟩⟩")
, ("a !", "⟨␣! a⟩")
, ("a ! b", "⟨⟨␣! a⟩ b⟩")
, ("a ! !", "⟨␣! ⟨␣! a⟩⟩")
, ("# a °", "⟨␣° ⟨#␣ a⟩⟩")
, ("# a !", "⟨#␣ ⟨␣! a⟩⟩")
, ("a ! # b", "⟨⟨␣! a⟩ ⟨#␣ b⟩⟩")
, ("1 + # b", "⟨␣+␣ 1 ⟨#␣ b⟩⟩")
, ("# b 1", "⟨#␣ ⟨b 1⟩⟩")
, ("b 1 !", "⟨␣! ⟨b 1⟩⟩")
, ("if true then 1 else 0", "⟨if␣then␣else␣ true 1 0⟩")
, ("if 2 then 1 else 0", "⟨if␣then␣else␣ 2 1 0⟩")
, ("if a b then 1 else 0", "⟨if␣then␣else␣ ⟨a b⟩ 1 0⟩")
, ("if true then a b else 0", "⟨if␣then␣else␣ true ⟨a b⟩ 0⟩")
, ("if true then 1 else a b", "⟨if␣then␣else␣ true 1 ⟨a b⟩⟩")
, ("1 + if true then 1 else 0", "⟨␣+␣ 1 ⟨if␣then␣else␣ true 1 0⟩⟩")
, ("1 + if true then 1 else a b + c", "⟨␣+␣ 1 ⟨if␣then␣else␣ true 1 ⟨␣+␣ ⟨a b⟩ c⟩⟩⟩")
, ("f if true then 1 else 0", "⟨f ⟨if␣then␣else␣ true 1 0⟩⟩")
, ("true ? 1 : if true then 1 else 0", "⟨␣?␣:␣ true 1 ⟨if␣then␣else␣ true 1 0⟩⟩")
, ("</ a />","⟨</␣/> a⟩")
, ("</ 0 />","⟨</␣/> 0⟩")
, ("</ f a b />","⟨</␣/> ⟨f a b⟩⟩")
, ("</ f 1 2 />","⟨</␣/> ⟨f 1 2⟩⟩")
, ("</ a + b />","⟨</␣/> ⟨␣+␣ a b⟩⟩")
, ("</ a + b * 2 />","⟨</␣/> ⟨␣+␣ a ⟨␣*␣ b 2⟩⟩⟩")
, ("</ a /> + 1","⟨␣+␣ ⟨</␣/> a⟩ 1⟩")
, ("1 + </ a />","⟨␣+␣ 1 ⟨</␣/> a⟩⟩")
, ("1 + </ a - b /> * 2","⟨␣+␣ 1 ⟨␣*␣ ⟨</␣/> ⟨␣-␣ a b⟩⟩ 2⟩⟩")
, ("</ a + b /> c","⟨⟨</␣/> ⟨␣+␣ a b⟩⟩ c⟩")
, ("f </ a />","⟨f ⟨</␣/> a⟩⟩")
, ("f </ a + b />","⟨f ⟨</␣/> ⟨␣+␣ a b⟩⟩⟩")
, ("</ # 0 />","⟨</␣/> ⟨#␣ 0⟩⟩")
, ("</ 1 + # 0 />","⟨</␣/> ⟨␣+␣ 1 ⟨#␣ 0⟩⟩⟩")
, ("[ a | b ]","⟨[␣|␣] a b⟩")
, ("a = b ; c = d", "⟨␣;␣ ⟨␣=␣ a b⟩ ⟨␣=␣ c d⟩⟩")
, ("a = let { b = c } in b", "⟨␣=␣ a ⟨let␣in␣ ⟨{␣} ⟨␣=␣ b c⟩⟩ b⟩⟩")
, ("a = let { b } in b ; d", "⟨␣;␣ ⟨␣=␣ a ⟨let␣in␣ ⟨{␣} b⟩ b⟩⟩ d⟩")
, ("a = let { b = c } in b ; d = e",
"⟨␣;␣ ⟨␣=␣ a ⟨let␣in␣ ⟨{␣} ⟨␣=␣ b c⟩⟩ b⟩⟩ ⟨␣=␣ d e⟩⟩")
, ("a = let { b = c ; f = g } in b ; d = e",
"⟨␣;␣ ⟨␣=␣ a ⟨let␣in␣ ⟨{␣} ⟨␣;␣ ⟨␣=␣ b c⟩ ⟨␣=␣ f g⟩⟩⟩ b⟩⟩ ⟨␣=␣ d e⟩⟩")
, ("a = b where { c } ; d", "⟨␣;␣ ⟨␣=␣ a ⟨␣where␣ b ⟨{␣} c⟩⟩⟩ d⟩")
, ("f a b = let { c } in case d of { e }",
"⟨␣=␣ ⟨f a b⟩ ⟨let␣in␣ ⟨{␣} c⟩ ⟨case␣of␣ d ⟨{␣} e⟩⟩⟩⟩")
, ("# true ? 1 : 0", "⟨␣?␣:␣ ⟨#␣ true⟩ 1 0⟩")
, ("a _/ b /.", "⟨␣_/␣/. a b⟩")
, ("a _/ 1 + 2 /.", "⟨␣_/␣/. a ⟨␣+␣ 1 2⟩⟩")
, ("a _/ (b) /.", "⟨␣_/␣/. a b⟩")
, ("a _/ 1 + 2 /. b", "⟨⟨␣_/␣/. a ⟨␣+␣ 1 2⟩⟩ b⟩")
, ("a + b _/ c /.", "⟨␣+␣ a ⟨␣_/␣/. b c⟩⟩")
, ("a + b * c _/ 1 + 2 /.", "⟨␣+␣ a ⟨␣*␣ b ⟨␣_/␣/. c ⟨␣+␣ 1 2⟩⟩⟩⟩")
, ("if true then if true then 1 else 0 else 2",
"⟨if␣then␣else␣ true ⟨if␣then␣else␣ true 1 0⟩ 2⟩")
, ("if true then 1 else # 0", "⟨if␣then␣else␣ true 1 ⟨#␣ 0⟩⟩")
, ("if true then # 1 else 0", "⟨if␣then␣else␣ true ⟨#␣ 1⟩ 0⟩")
, ("# if true then 1 else 0", "⟨#␣ ⟨if␣then␣else␣ true 1 0⟩⟩")
, ("[ a + b | c ]", "⟨[␣|␣] ⟨␣+␣ a b⟩ c⟩")
, ("[ a | b + c ]", "⟨[␣|␣] a ⟨␣+␣ b c⟩⟩")
, ("[ a + b | c * d ]", "⟨[␣|␣] ⟨␣+␣ a b⟩ ⟨␣*␣ c d⟩⟩")
, ("⟨⟩", "⟨⟩")
, ("⟨⟩ a", "⟨⟨⟩ a⟩")
, ("f ⟨⟩ 1", "⟨f ⟨⟩ 1⟩")
, ("\\ a b -> a + b", "⟨\\␣->␣ ⟨a b⟩ ⟨␣+␣ a b⟩⟩")
, ("\\ a 2 -> a + b", "⟨\\␣->␣ ⟨a 2⟩ ⟨␣+␣ a b⟩⟩")
, ("\\ 1 2 -> a + b", "⟨\\␣->␣ ⟨1 2⟩ ⟨␣+␣ a b⟩⟩")
-- See the Note in Yard.hs.
, ("1 2", "⟨1 2⟩")
, ("(1 2)", "⟨1 2⟩")
, ("f (1 2)", "⟨f ⟨1 2⟩⟩")
, ("</ 1 2 />", "⟨</␣/> ⟨1 2⟩⟩")
, ("1 2 + 3", "⟨␣+␣ ⟨1 2⟩ 3⟩")
, ("1 (1 + 2)", "⟨1 ⟨␣+␣ 1 2⟩⟩")
, ("1 a", "⟨1 a⟩")
]
tests' :: [(String, Failure String)]
tests' =
[ ("true then 1 else 0", MissingBefore [["if"]] "then")
, ("if true 1 else 0", MissingBefore [["if","then"]] "else")
, ("true 1 else 0", MissingBefore [["if","then"]] "else")
, ("if true then 1", MissingAfter ["else"] ["if","then"])
, ("[ a | b", MissingAfter ["]"] ["[","|"])
, ("a | b ]", MissingBefore [["["]] "|")
, ("[ a b ]", MissingBefore [["[","|"]] "]")
, ("1 + * 3", MissingSubBetween "+" "*")
, ("1 * + 3", MissingSubBetween "*" "+")
, ("()", MissingSubBetween "(" ")")
, ("[ | b ]", MissingSubBetween "[" "|")
, ("[ a | ]", MissingSubBetween "|" "]")
, ("true ? 1 : true then 1 else 0", MissingBefore [["if"]] "then")
, ("true ? 1 : then 1 else 0", MissingBefore [["if"]] "then")
, ("a _/ /.", MissingSubBetween "_/" "/.")
, ("a _/ b", MissingAfter ["/."] ["_/"])
, ("(+ 2)", MissingSubBetween "(" "+")
, ("true : 1 + 2", MissingBefore [["?"]] ":")
, ("+ 1 2", MissingSubBefore "+")
, ("+", MissingSubBefore "+")
, ("+ 1", MissingSubBefore "+")
, ("1 +", MissingSubAfter "+")
, ("|", MissingBefore [["["]] "|")
, ("[", MissingAfter ["|"] ["["])
, ("]", MissingBefore [["[","|"]] "]")
, ("(", MissingAfter [")"] ["("])
, (")", MissingBefore [["("]] ")")
, ("⟨", MissingAfter ["⟩"] ["⟨"])
, ("⟩", MissingBefore [["⟨"]] "⟩")
, ("_/ b /.", MissingSubBefore "_/")
]
| noteed/syntactical | tests/Simple.hs | bsd-3-clause | 10,219 | 0 | 10 | 2,209 | 2,147 | 1,350 | 797 | 204 | 1 |
{-# OPTIONS_GHC -F -pgmF inch #-}
{-# LANGUAGE RankNTypes, GADTs, KindSignatures, ScopedTypeVariables,
NPlusKPatterns #-}
module Layout where
data Ex :: (Num -> *) -> * where
Ex :: forall (f :: Num -> *) (n :: Num) . f n -> Ex f
data Ex2 :: (Num -> *) -> (Num -> *) -> * where
Ex2 :: forall (f g :: Num -> *) (p :: Num) . f p -> g p -> Ex2 f g
data Layout :: (Num -> Num -> *) -> Num -> Num -> * where
Stuff :: forall (s :: Num -> Num -> *)(w d :: Nat) .
s w d -> Layout s w d
Empty :: forall (s :: Num -> Num -> *)(w d :: Nat) .
Layout s w d
Horiz :: forall (s :: Num -> Num -> *)(w d :: Nat) .
pi (x :: Nat) . x <= w =>
Layout s x d -> Layout s (w-x) d -> Layout s w d
Vert :: forall (s :: Num -> Num -> *)(w d :: Nat) .
pi (y :: Nat) . y <= d =>
Layout s w y -> Layout s w (d-y) -> Layout s w d
deriving Show
data K :: * -> Num -> Num -> * where
K :: forall a . a -> K a 1 1
deriving Show
unK :: forall a (m n :: Num) . K a m n -> a
unK (K c) = c
horizPad :: forall (s :: Num -> Num -> *) . pi (w1 d1 w2 d2 :: Nat) .
Layout s w1 d1 -> Layout s w2 d2 -> Layout s (w1 + w2) (max d1 d2)
horizPad {w1} {d1} {w2} {d2} l1 l2
| {d1 > d2} = Horiz {w1} l1 (Vert {d2} l2 Empty)
| {d1 ~ d2} = Horiz {w1} l1 l2
| {d1 < d2} = Horiz {w1} (Vert {d1} l1 Empty) l2
stuffAt :: forall a (w d :: Num) . pi (x y :: Nat) .
(x < w, y < d) => Layout (K a) w d -> Maybe a
stuffAt {x} {y} (Stuff (K i)) = Just i
stuffAt {x} {y} Empty = Nothing
stuffAt {x} {y} (Horiz {wx} l1 l2) | {x < wx} = stuffAt {x} {y} l1
| {x >= wx} = stuffAt {x - wx} {y} l2
stuffAt {x} {y} (Vert {dy} l1 l2) | {y < dy} = stuffAt {x} {y} l1
| {y >= dy} = stuffAt {x} {y - dy} l2
-- Layout is an indexed monad
mapLayout :: forall (s t :: Num -> Num -> *)(w d :: Num) .
(forall (w' d' :: Nat) . s w' d' -> t w' d') ->
Layout s w d -> Layout t w d
mapLayout f (Stuff x) = Stuff (f x)
mapLayout f Empty = Empty
mapLayout f (Horiz {x} l1 l2) = Horiz {x} (mapLayout f l1) (mapLayout f l2)
mapLayout f (Vert {y} l1 l2) = Vert {y} (mapLayout f l1) (mapLayout f l2)
joinLayout :: forall (s :: Num -> Num -> *)(w d :: Num) .
Layout (Layout s) w d -> Layout s w d
joinLayout (Stuff l) = l
joinLayout Empty = Empty
joinLayout (Horiz {x} l1 l2) = Horiz {x} (joinLayout l1) (joinLayout l2)
joinLayout (Vert {y} l1 l2) = Vert {y} (joinLayout l1) (joinLayout l2)
bindLayout :: forall (s t :: Num -> Num -> *)(w d :: Num) .
(forall (w' d' :: Nat) . s w' d' -> Layout t w' d') ->
Layout s w d -> Layout t w d
bindLayout f l = joinLayout (mapLayout f l)
returnLayout = Stuff
-- Tiling needs multiplication, otherwise it only works for 1x1 tiles
tile :: forall (s :: Num -> Num -> *) . pi (w d :: Num) . (1 <= w, 1 <= d) =>
Layout s 1 1 -> Layout s w d
tile {1} {1} l = l
tile {w+2} {1} l = Horiz {1} l (tile {w+1} {1} l)
tile {w} {d+2} l = Vert {1} (tile {w} {1} l) (tile {w} {d+1} l)
data Proxy :: Num -> * where
Proxy :: forall (n :: Num) . Proxy n
tilen :: forall (s :: Num -> Num -> *) .
(forall a (m n :: Nat) . Proxy m -> Proxy n -> (0 <= m * n => a) -> a) ->
(pi (w d x y :: Num) .
(0 <= w, 0 <= d, 1 <= x, 1 <= y) =>
Layout s w d -> Layout s (w*x) (d*y))
tilen lem {w} {d} {1} {1} l = l
tilen lem {w} {d} {x+2} {1} l = lem (Proxy :: Proxy x) (Proxy :: Proxy w)
(Horiz {w} l (tilen lem {w} {d} {x+1} {1} l))
tilen lem {w} {d} {x} {y+2} l = lem (Proxy :: Proxy x) (Proxy :: Proxy w)
(lem (Proxy :: Proxy y) (Proxy :: Proxy d)
(Vert {d} (tilen lem {w} {d} {x} {1} l) (tilen lem {w} {d} {x} {y+1} l)))
-- Vectors and matrices
data Vec :: * -> Num -> * where
Nil :: forall a . Vec a 0
Cons :: forall a (n :: Nat) . a -> Vec a n -> Vec a (n+1)
deriving Show
vappend :: forall a (m n :: Nat) . Vec a m -> Vec a n -> Vec a (m+n)
vappend Nil ys = ys
vappend (Cons x xs) ys = Cons x (vappend xs ys)
vmap :: forall a b (m :: Nat) . (a -> b) -> Vec a m -> Vec b m
vmap f Nil = Nil
vmap f (Cons x xs) = Cons (f x) (vmap f xs)
vzipWith :: forall a b c (m :: Nat) .
(a -> b -> c) -> Vec a m -> Vec b m -> Vec c m
vzipWith f Nil Nil = Nil
vzipWith f (Cons x xs) (Cons y ys) = Cons (f x y) (vzipWith f xs ys)
returnVec :: forall a . pi (m :: Nat) . a -> Vec a m
returnVec {0} x = Nil
returnVec {m+1} x = Cons x (returnVec {m} x)
data M :: * -> Num -> Num -> * where
M :: forall a (x y :: Num) . Vec (Vec a x) y -> M a x y
deriving Show
unM (M xss) = xss
mOne a = M (Cons (Cons (Just a) Nil) Nil)
mHoriz :: forall a . pi (w d x :: Nat) . x <= w =>
M a x d -> M a (w-x) d -> M a w d
mHoriz {w} {d} {x} (M l) (M r) = M (vzipWith vappend l r)
mVert :: forall a . pi (w d y :: Nat) . y <= d =>
M a w y -> M a w (d-y) -> M a w d
mVert {w} {d} {y} (M t) (M b) = M (vappend t b)
returnM :: forall a . a -> (pi (w d :: Nat) . M a w d)
returnM x {w} {d} = M (returnVec {d} (returnVec {w} x))
-- A scary-looking fold for layouts, and an application of it to convert to matrices
foldLayout :: forall (s t :: Num -> Num -> *) a . pi (w d :: Num) .
(pi (w' d' :: Nat) . s w' d' -> t w' d') ->
(pi (w' d' :: Nat) . t w' d') ->
(pi (w' d' x :: Nat) . x <= w' => t x d' -> t (w'-x) d' -> t w' d') ->
(pi (w' d' y :: Nat) . y <= d' => t w' y -> t w' (d'-y) -> t w' d') ->
Layout s w d -> t w d
foldLayout {w} {d} s e h v (Stuff x) = s {w} {d} x
foldLayout {w} {d} s e h v Empty = e {w} {d}
foldLayout {w} {d} s e h v (Horiz {x} l1 l2) =
h {w} {d} {x} (foldLayout {x} {d} s e h v l1)
(foldLayout {w-x} {d} s e h v l2)
foldLayout {w} {d} s e h v (Vert {y} l1 l2) =
v {w} {d} {y} (foldLayout {w} {y} s e h v l1)
(foldLayout {w} {d-y} s e h v l2)
render :: forall a . pi (w d :: Num) . Layout (K a) w d -> M (Maybe a) w d
render {w} {d} l =
let
s :: forall a . pi (w' d' :: Nat) . (K a) w' d' -> M (Maybe a) w' d'
s {w'} {d'} (K c) = mOne c
in foldLayout {w} {d} s (returnM Nothing) mHoriz mVert l
append [] ys = ys
append (x:xs) ys = x : append xs ys
showV :: forall (n :: Num) . Vec (Maybe Char) n -> [Char]
showV Nil = ""
showV (Cons Nothing xs) = ' ' : showV xs
showV (Cons (Just i) xs) = i : showV xs
showM :: forall (w d :: Num) . M (Maybe Char) w d -> [Char]
showM (M Nil) = ""
showM (M (Cons x xs)) = append (showV x) ('\n' : showM (M xs))
renderM {w} {d} l = showM (render {w} {d} l)
-- Cropping a w*d layout to produce a wc*dc layout starting from (x, y)
crop :: forall (s :: Num -> Num -> *) .
(pi (w' d' x' y' wc' dc' :: Nat) . (x' + wc' <= w', y' + dc' <= d') =>
s w' d' -> Layout s wc' dc') ->
(pi (w d x y wc dc :: Nat) . (x + wc <= w, y + dc <= d) =>
Layout s w d -> Layout s wc dc)
crop f {w} {d} {x} {y} {wc} {dc} (Stuff s) = f {w} {d} {x} {y} {wc} {dc} s
crop f {w} {d} {x} {y} {wc} {dc} Empty = Empty
crop f {w} {d} {x} {y} {wc} {dc} (Horiz {wx} l1 l2) | {x >= wx}
= crop f {w-wx} {d} {x-wx} {y} {wc} {dc} l2
crop f {w} {d} {x} {y} {wc} {dc} (Horiz {wx} l1 l2) | {x + wc <= wx}
= crop f {wx} {d} {x} {y} {wc} {dc} l1
crop f {w} {d} {x} {y} {wc} {dc} (Horiz {wx} l1 l2) | {x < wx, x + wc > wx}
= Horiz {wx-x} (crop f {wx} {d} {x} {y} {wx-x} {dc} l1)
(crop f {w-wx} {d} {0} {y} {wc-(wx-x)} {dc} l2)
crop f {w} {d} {x} {y} {wc} {dc} (Vert {dy} l1 l2) | {y >= dy}
= crop f {w} {d-dy} {x} {y-dy} {wc} {dc} l2
crop f {w} {d} {x} {y} {wc} {dc} (Vert {dy} l1 l2) | {y + dc <= dy}
= crop f {w} {dy} {x} {y} {wc} {dc} l1
crop f {w} {d} {x} {y} {wc} {dc} (Vert {dy} l1 l2) | {y < dy, y + dc > dy}
= Vert {dy-y} (crop f {w} {dy} {x} {y} {wc} {dy-y} l1)
(crop f {w} {d-dy} {x} {0} {wc} {dc-(dy-y)} l2)
cropK :: forall a . pi (w d x y wc dc :: Nat) . (x + wc <= w, y + dc <= d) =>
K a w d -> Layout (K a) wc dc
cropK {w} {d} {x} {y} {wc} {dc} (K u) | {wc > 0, dc > 0} = Stuff (K u)
cropK {w} {d} {x} {y} {wc} {dc} (K u) | True = Empty
crop' = crop cropK
-- Overlaying two layouts so the empty bits of the second layout are transparent
overlay :: forall (s :: Num -> Num -> *) .
(pi (w d x y wc dc :: Nat) . (x + wc <= w, y + dc <= d) =>
Layout s w d -> Layout s wc dc) ->
(pi (w d :: Num) .
Layout s w d -> Layout s w d -> Layout s w d)
overlay cropf {w} {d} l Empty = l
overlay cropf {w} {d} Empty l' = l'
overlay cropf {w} {d} l (Stuff s) = Stuff s
overlay cropf {w} {d} l (Horiz {x} l1' l2') =
Horiz {x} (overlay cropf {x} {d} (cropf {w} {d} {0} {0} {x} {d} l) l1')
(overlay cropf {w-x} {d} (cropf {w} {d} {x} {0} {w-x} {d} l) l2')
overlay cropf {w} {d} l (Vert {y} l1' l2') =
Vert {y} (overlay cropf {w} {y} (cropf {w} {d} {0} {0} {w} {y} l) l1')
(overlay cropf {w} {d-y} (cropf {w} {d} {0} {y} {w} {d-y} l) l2')
-- Layout transformations: flipping
horizFlip :: forall (s :: Num -> Num -> *) . pi (w d :: Num) . Layout s w d -> Layout s w d
horizFlip {w} {d} Empty = Empty
horizFlip {w} {d} (Stuff s) = Stuff s
horizFlip {w} {d} (Horiz {x} l r) = Horiz {w-x} r l
horizFlip {w} {d} (Vert {y} t b) = Vert {y} (horizFlip {w} {y} t) (horizFlip {w} {d-y} b)
vertFlip :: forall (s :: Num -> Num -> *) . pi (w d :: Num) . Layout s w d -> Layout s w d
vertFlip {w} {d} Empty = Empty
vertFlip {w} {d} (Stuff s) = Stuff s
vertFlip {w} {d} (Horiz {x} l r) = Horiz {x} (vertFlip {x} {d} l) (vertFlip {w-x} {d} r)
vertFlip {w} {d} (Vert {y} t b) = Vert {d-y} b t
-- Oh no, it's a zipper
data LContext :: (Num -> Num -> *) -> Num -> Num -> Num -> Num -> * where
Root :: forall (s :: Num -> Num -> *)(w d :: Nat) .
LContext s w d w d
HorizLeft :: forall (s :: Num -> Num -> *)(wr dr w d :: Nat) .
pi (x :: Nat) . x <= w =>
LContext s wr dr w d -> Layout s (w-x) d -> LContext s wr dr x d
HorizRight :: forall (s :: Num -> Num -> *)(wr dr w d :: Nat) .
pi (x :: Nat) . x <= w =>
Layout s x d -> LContext s wr dr w d -> LContext s wr dr (w-x) d
VertTop :: forall (s :: Num -> Num -> *)(wr dr w d :: Nat) .
pi (y :: Nat) . y <= d =>
LContext s wr dr w d -> Layout s w (d-y) -> LContext s wr dr w y
VertBottom :: forall (s :: Num -> Num -> *)(wr dr w d :: Nat) .
pi (y :: Nat) . y <= d =>
Layout s w y -> LContext s wr dr w d -> LContext s wr dr w (d-y)
data LZip :: (Num -> Num -> *) -> Num -> Num -> * where
LZip :: forall (s :: Num -> Num -> *)(wr dr wh dh :: Num) .
LContext s wr dr wh dh -> Layout s wh dh -> LZip s wr dr
lzZip = LZip Root
lzIn :: forall (s :: Num -> Num -> *)(w d :: Nat) . LZip s w d -> Maybe (LZip s w d)
lzIn (LZip c Empty) = Nothing
lzIn (LZip c (Stuff s)) = Nothing
lzIn (LZip c (Horiz {x} l r)) = Just (LZip (HorizLeft {x} c r) l)
lzIn (LZip c (Vert {y} t b)) = Just (LZip (VertTop {y} c b) t)
lzOut :: forall (s :: Num -> Num -> *)(w d :: Nat) . LZip s w d -> Maybe (LZip s w d)
lzOut (LZip Root h) = Nothing
lzOut (LZip (HorizLeft {x} c r) h) = Just (LZip c (Horiz {x} h r))
lzOut (LZip (HorizRight {x} l c) h) = Just (LZip c (Horiz {x} l h))
lzOut (LZip (VertTop {y} c b) h) = Just (LZip c (Vert {y} h b))
lzOut (LZip (VertBottom {y} t c) h) = Just (LZip c (Vert {y} t h))
lzLeft :: forall (s :: Num -> Num -> *)(w d :: Nat) . LZip s w d -> Maybe (LZip s w d)
lzLeft (LZip (HorizRight {x} l c) h) = Just (LZip (HorizLeft {x} c h) l)
lzLeft _ = Nothing
lzRight :: forall (s :: Num -> Num -> *)(w d :: Nat) . LZip s w d -> Maybe (LZip s w d)
lzRight (LZip (HorizLeft {x} c r) h) = Just (LZip (HorizRight {x} h c) r)
lzRight _ = Nothing
lzTop :: forall (s :: Num -> Num -> *)(w d :: Nat) . LZip s w d -> Maybe (LZip s w d)
lzTop (LZip (VertBottom {x} l c) h) = Just (LZip (VertTop {x} c h) l)
lzTop _ = Nothing
lzBottom :: forall (s :: Num -> Num -> *)(w d :: Nat) . LZip s w d -> Maybe (LZip s w d)
lzBottom (LZip (VertTop {x} c r) h) = Just (LZip (VertBottom {x} h c) r)
lzBottom _ = Nothing
lzSnd :: forall (s :: Num -> Num -> *)(w d :: Num) a .
(forall (wh dh :: Num) . Layout s wh dh -> a) ->
LZip s w d ->
a
lzSnd f (LZip _ l) = f l
-- Test things
l2x1 = Horiz {1} (Stuff (K 'A')) (Stuff (K 'B'))
l1xn :: forall a (n :: Num) . 1 <= n => a -> Layout (K a) 1 n
l1xn x = Vert {1} (Stuff (K x)) Empty
l1x2 :: a -> Layout (K a) 1 2
l1x2 = l1xn
grid {x} {y} a b c d = Vert {y} (Horiz {x} (Stuff a) (Stuff b))
(Horiz {x} (Stuff c) (Stuff d))
as {w} {d} = tile {w} {d} (Stuff (K 'A'))
bs {w} {d} = tile {w} {d} (Stuff (K 'B'))
abcd = grid {1} {1} (K 'A') (K 'B') (K 'C') (K 'D')
getD = stuffAt {1} {1} abcd
rabcd = render {2} {2} abcd
abcdabcd = joinLayout (grid {2} {2} abcd Empty Empty abcd)
rabcdabcd = render {4} {4} abcdabcd
{-
instance Functor Layout where
fmap = mapLayout
instance Monad Layout where
(>>=) = flip bindLayout
return = returnLayout
-} | adamgundry/inch | examples/Layout.hs | bsd-3-clause | 13,823 | 248 | 26 | 4,720 | 5,089 | 3,328 | 1,761 | -1 | -1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : lemmih@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Entry point to the default cabal-install front-end.
-----------------------------------------------------------------------------
module Main (main) where
import Distribution.Client.Setup
( GlobalFlags(..), globalCommand, withRepoContext
, ConfigFlags(..)
, ConfigExFlags(..), defaultConfigExFlags, configureExCommand
, reconfigureCommand
, configCompilerAux', configPackageDB'
, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..)
, buildCommand, replCommand, testCommand, benchmarkCommand
, InstallFlags(..), defaultInstallFlags
, installCommand, upgradeCommand, uninstallCommand
, FetchFlags(..), fetchCommand
, FreezeFlags(..), freezeCommand
, genBoundsCommand
, GetFlags(..), getCommand, unpackCommand
, checkCommand
, formatCommand
, updateCommand
, ListFlags(..), listCommand
, InfoFlags(..), infoCommand
, UploadFlags(..), uploadCommand
, ReportFlags(..), reportCommand
, runCommand
, InitFlags(initVerbosity), initCommand
, SDistFlags(..), SDistExFlags(..), sdistCommand
, Win32SelfUpgradeFlags(..), win32SelfUpgradeCommand
, ActAsSetupFlags(..), actAsSetupCommand
, SandboxFlags(..), sandboxCommand
, ExecFlags(..), execCommand
, UserConfigFlags(..), userConfigCommand
, reportCommand
, manpageCommand
)
import Distribution.Simple.Setup
( HaddockTarget(..)
, HaddockFlags(..), haddockCommand, defaultHaddockFlags
, HscolourFlags(..), hscolourCommand
, ReplFlags(..)
, CopyFlags(..), copyCommand
, RegisterFlags(..), registerCommand
, CleanFlags(..), cleanCommand
, TestFlags(..), BenchmarkFlags(..)
, Flag(..), fromFlag, fromFlagOrDefault, flagToMaybe, toFlag
, configAbsolutePaths
)
import Distribution.Client.SetupWrapper
( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
import Distribution.Client.Config
( SavedConfig(..), loadConfig, defaultConfigFile, userConfigDiff
, userConfigUpdate, createDefaultConfigFile, getConfigFilePath )
import Distribution.Client.Targets
( readUserTargets )
import qualified Distribution.Client.List as List
( list, info )
import qualified Distribution.Client.CmdConfigure as CmdConfigure
import qualified Distribution.Client.CmdBuild as CmdBuild
import qualified Distribution.Client.CmdRepl as CmdRepl
import qualified Distribution.Client.CmdFreeze as CmdFreeze
import Distribution.Client.Install (install)
import Distribution.Client.Configure (configure, writeConfigFlags)
import Distribution.Client.Update (update)
import Distribution.Client.Exec (exec)
import Distribution.Client.Fetch (fetch)
import Distribution.Client.Freeze (freeze)
import Distribution.Client.GenBounds (genBounds)
import Distribution.Client.Check as Check (check)
--import Distribution.Client.Clean (clean)
import qualified Distribution.Client.Upload as Upload
import Distribution.Client.Run (run, splitRunArgs)
import Distribution.Client.SrcDist (sdist)
import Distribution.Client.Get (get)
import Distribution.Client.Reconfigure (Check(..), reconfigure)
import Distribution.Client.Sandbox (sandboxInit
,sandboxAddSource
,sandboxDelete
,sandboxDeleteSource
,sandboxListSources
,sandboxHcPkg
,dumpPackageEnvironment
,loadConfigOrSandboxConfig
,findSavedDistPref
,initPackageDBIfNeeded
,maybeWithSandboxDirOnSearchPath
,maybeWithSandboxPackageInfo
,tryGetIndexFilePath
,sandboxBuildDir
,updateSandboxConfigFileFlag
,updateInstallDirs
,getPersistOrConfigCompiler)
import Distribution.Client.Sandbox.PackageEnvironment (setPackageDB)
import Distribution.Client.Sandbox.Timestamp (maybeAddCompilerTimestampRecord)
import Distribution.Client.Sandbox.Types (UseSandbox(..), whenUsingSandbox)
import Distribution.Client.Tar (createTarGzFile)
import Distribution.Client.Types (Password (..))
import Distribution.Client.Init (initCabal)
import Distribution.Client.Manpage (manpage)
import qualified Distribution.Client.Win32SelfUpgrade as Win32SelfUpgrade
import Distribution.Client.Utils (determineNumJobs
#if defined(mingw32_HOST_OS)
,relaxEncodingErrors
#endif
)
import Distribution.Package (packageId)
import Distribution.PackageDescription
( BuildType(..), Executable(..), buildable )
import Distribution.PackageDescription.Parse
( readPackageDescription )
import Distribution.PackageDescription.PrettyPrint
( writeGenericPackageDescription )
import qualified Distribution.Simple as Simple
import qualified Distribution.Make as Make
import Distribution.Simple.Build
( startInterpreter )
import Distribution.Simple.Command
( CommandParse(..), CommandUI(..), Command, CommandSpec(..)
, CommandType(..), commandsRun, commandAddAction, hiddenCommand
, commandFromSpec, commandShowOptions )
import Distribution.Simple.Compiler (Compiler(..), PackageDBStack)
import Distribution.Simple.Configure
( configCompilerAuxEx, ConfigStateFileError(..)
, getPersistBuildConfig, interpretPackageDbFlags
, tryGetPersistBuildConfig )
import qualified Distribution.Simple.LocalBuildInfo as LBI
import Distribution.Simple.Program (defaultProgramDb
,configureAllKnownPrograms
,simpleProgramInvocation
,getProgramInvocationOutput)
import Distribution.Simple.Program.Db (reconfigurePrograms)
import qualified Distribution.Simple.Setup as Cabal
import Distribution.Simple.Utils
( cabalVersion, die, info, notice, topHandler
, findPackageDesc, tryFindPackageDesc )
import Distribution.Text
( display )
import Distribution.Verbosity as Verbosity
( Verbosity, normal )
import Distribution.Version
( Version(..), orLaterVersion )
import qualified Paths_cabal_install (version)
import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure, exitSuccess)
import System.FilePath ( dropExtension, splitExtension
, takeExtension, (</>), (<.>))
import System.IO ( BufferMode(LineBuffering), hSetBuffering
#ifdef mingw32_HOST_OS
, stderr
#endif
, stdout )
import System.Directory (doesFileExist, getCurrentDirectory)
import Data.List (intercalate)
import Data.Maybe (listToMaybe)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (Monoid(..))
import Control.Applicative (pure, (<$>))
#endif
import Data.Monoid (Any(..))
import Distribution.Compat.Semigroup ((<>))
import Control.Exception (SomeException(..), try)
import Control.Monad (when, unless, void)
-- | Entry point
--
main :: IO ()
main = do
-- Enable line buffering so that we can get fast feedback even when piped.
-- This is especially important for CI and build systems.
hSetBuffering stdout LineBuffering
-- The default locale encoding for Windows CLI is not UTF-8 and printing
-- Unicode characters to it will fail unless we relax the handling of encoding
-- errors when writing to stderr and stdout.
#ifdef mingw32_HOST_OS
relaxEncodingErrors stdout
relaxEncodingErrors stderr
#endif
getArgs >>= mainWorker
mainWorker :: [String] -> IO ()
mainWorker args = topHandler $
case commandsRun (globalCommand commands) commands args of
CommandHelp help -> printGlobalHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo (globalFlags, commandParse) ->
case commandParse of
_ | fromFlagOrDefault False (globalVersion globalFlags)
-> printVersion
| fromFlagOrDefault False (globalNumericVersion globalFlags)
-> printNumericVersion
CommandHelp help -> printCommandHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo action -> do
globalFlags' <- updateSandboxConfigFileFlag globalFlags
action globalFlags'
where
printCommandHelp help = do
pname <- getProgName
putStr (help pname)
printGlobalHelp help = do
pname <- getProgName
configFile <- defaultConfigFile
putStr (help pname)
putStr $ "\nYou can edit the cabal configuration file to set defaults:\n"
++ " " ++ configFile ++ "\n"
exists <- doesFileExist configFile
when (not exists) $
putStrLn $ "This file will be generated with sensible "
++ "defaults if you run 'cabal update'."
printOptionsList = putStr . unlines
printErrors errs = die $ intercalate "\n" errs
printNumericVersion = putStrLn $ display Paths_cabal_install.version
printVersion = putStrLn $ "cabal-install version "
++ display Paths_cabal_install.version
++ "\ncompiled using version "
++ display cabalVersion
++ " of the Cabal library "
commands = map commandFromSpec commandSpecs
commandSpecs =
[ regularCmd installCommand installAction
, regularCmd updateCommand updateAction
, regularCmd listCommand listAction
, regularCmd infoCommand infoAction
, regularCmd fetchCommand fetchAction
, regularCmd freezeCommand freezeAction
, regularCmd getCommand getAction
, hiddenCmd unpackCommand unpackAction
, regularCmd checkCommand checkAction
, regularCmd sdistCommand sdistAction
, regularCmd uploadCommand uploadAction
, regularCmd reportCommand reportAction
, regularCmd runCommand runAction
, regularCmd initCommand initAction
, regularCmd configureExCommand configureAction
, regularCmd reconfigureCommand reconfigureAction
, regularCmd buildCommand buildAction
, regularCmd replCommand replAction
, regularCmd sandboxCommand sandboxAction
, regularCmd haddockCommand haddockAction
, regularCmd execCommand execAction
, regularCmd userConfigCommand userConfigAction
, regularCmd cleanCommand cleanAction
, regularCmd genBoundsCommand genBoundsAction
, wrapperCmd copyCommand copyVerbosity copyDistPref
, wrapperCmd hscolourCommand hscolourVerbosity hscolourDistPref
, wrapperCmd registerCommand regVerbosity regDistPref
, regularCmd testCommand testAction
, regularCmd benchmarkCommand benchmarkAction
, hiddenCmd uninstallCommand uninstallAction
, hiddenCmd formatCommand formatAction
, hiddenCmd upgradeCommand upgradeAction
, hiddenCmd win32SelfUpgradeCommand win32SelfUpgradeAction
, hiddenCmd actAsSetupCommand actAsSetupAction
, hiddenCmd manpageCommand (manpageAction commandSpecs)
, regularCmd CmdConfigure.configureCommand CmdConfigure.configureAction
, regularCmd CmdBuild.buildCommand CmdBuild.buildAction
, regularCmd CmdRepl.replCommand CmdRepl.replAction
, regularCmd CmdFreeze.freezeCommand CmdFreeze.freezeAction
]
type Action = GlobalFlags -> IO ()
regularCmd :: CommandUI flags -> (flags -> [String] -> action)
-> CommandSpec action
regularCmd ui action =
CommandSpec ui ((flip commandAddAction) action) NormalCommand
hiddenCmd :: CommandUI flags -> (flags -> [String] -> action)
-> CommandSpec action
hiddenCmd ui action =
CommandSpec ui (\ui' -> hiddenCommand (commandAddAction ui' action))
HiddenCommand
wrapperCmd :: Monoid flags => CommandUI flags -> (flags -> Flag Verbosity)
-> (flags -> Flag String) -> CommandSpec Action
wrapperCmd ui verbosity distPref =
CommandSpec ui (\ui' -> wrapperAction ui' verbosity distPref) NormalCommand
wrapperAction :: Monoid flags
=> CommandUI flags
-> (flags -> Flag Verbosity)
-> (flags -> Flag String)
-> Command Action
wrapperAction command verbosityFlag distPrefFlag =
commandAddAction command
{ commandDefaultFlags = mempty } $ \flags extraArgs globalFlags -> do
let verbosity = fromFlagOrDefault normal (verbosityFlag flags)
load <- try (loadConfigOrSandboxConfig verbosity globalFlags)
let config = either (\(SomeException _) -> mempty) snd load
distPref <- findSavedDistPref config (distPrefFlag flags)
let setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref }
setupWrapper verbosity setupScriptOptions Nothing
command (const flags) extraArgs
configureAction :: (ConfigFlags, ConfigExFlags)
-> [String] -> Action
configureAction (configFlags, configExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
(useSandbox, config) <- fmap
(updateInstallDirs (configUserInstall configFlags))
(loadConfigOrSandboxConfig verbosity globalFlags)
distPref <- findSavedDistPref config (configDistPref configFlags)
let configFlags' = savedConfigureFlags config `mappend` configFlags
configExFlags' = savedConfigureExFlags config `mappend` configExFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, progdb) <- configCompilerAuxEx configFlags'
-- If we're working inside a sandbox and the user has set the -w option, we
-- may need to create a sandbox-local package DB for this compiler and add a
-- timestamp record for this compiler to the timestamp file.
let configFlags'' = case useSandbox of
NoSandbox -> configFlags'
(UseSandbox sandboxDir) -> setPackageDB sandboxDir
comp platform configFlags'
writeConfigFlags verbosity distPref (configFlags'', configExFlags')
-- What package database(s) to use
let packageDBs :: PackageDBStack
packageDBs
= interpretPackageDbFlags
(fromFlag (configUserInstall configFlags''))
(configPackageDBs configFlags'')
whenUsingSandbox useSandbox $ \sandboxDir -> do
initPackageDBIfNeeded verbosity configFlags'' comp progdb
-- NOTE: We do not write the new sandbox package DB location to
-- 'cabal.sandbox.config' here because 'configure -w' must not affect
-- subsequent 'install' (for UI compatibility with non-sandboxed mode).
indexFile <- tryGetIndexFilePath config
maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile
(compilerId comp) platform
maybeWithSandboxDirOnSearchPath useSandbox $
withRepoContext verbosity globalFlags' $ \repoContext ->
configure verbosity packageDBs repoContext
comp platform progdb configFlags'' configExFlags' extraArgs
reconfigureAction :: (ConfigFlags, ConfigExFlags)
-> [String] -> Action
reconfigureAction flags _ globalFlags = do
let (configFlags, _) = flags
verbosity = fromFlag (configVerbosity configFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
dist <- findSavedDistPref config (configDistPref configFlags)
let checkFlags = Check $ \_ saved -> do
let flags' = saved <> flags
unless (saved == flags') $ info verbosity message
pure (Any True, flags')
where
-- This message is correct, but not very specific: it will list all
-- of the new flags, even if some have not actually changed. The
-- *minimal* set of changes is more difficult to determine.
message =
"flags changed: "
++ unwords (commandShowOptions configureExCommand flags)
_ <-
reconfigure configureAction
verbosity dist useSandbox DontSkipAddSourceDepsCheck NoFlag
checkFlags [] globalFlags config
pure ()
buildAction :: (BuildFlags, BuildExFlags) -> [String] -> Action
buildAction (buildFlags, buildExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags)
noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (buildDistPref buildFlags)
-- Calls 'configureAction' to do the real work, so nothing special has to be
-- done to support sandboxes.
config' <-
reconfigure configureAction
verbosity distPref useSandbox noAddSource (buildNumJobs buildFlags)
mempty [] globalFlags config
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config' distPref buildFlags extraArgs
-- | Actually do the work of building the package. This is separate from
-- 'buildAction' so that 'testAction' and 'benchmarkAction' do not invoke
-- 'reconfigure' twice.
build :: Verbosity -> SavedConfig -> FilePath -> BuildFlags -> [String] -> IO ()
build verbosity config distPref buildFlags extraArgs =
setupWrapper verbosity setupOptions Nothing
(Cabal.buildCommand progDb) mkBuildFlags extraArgs
where
progDb = defaultProgramDb
setupOptions = defaultSetupScriptOptions { useDistPref = distPref }
mkBuildFlags version = filterBuildFlags version config buildFlags'
buildFlags' = buildFlags
{ buildVerbosity = toFlag verbosity
, buildDistPref = toFlag distPref
}
-- | Make sure that we don't pass new flags to setup scripts compiled against
-- old versions of Cabal.
filterBuildFlags :: Version -> SavedConfig -> BuildFlags -> BuildFlags
filterBuildFlags version config buildFlags
| version >= Version [1,19,1] [] = buildFlags_latest
-- Cabal < 1.19.1 doesn't support 'build -j'.
| otherwise = buildFlags_pre_1_19_1
where
buildFlags_pre_1_19_1 = buildFlags {
buildNumJobs = NoFlag
}
buildFlags_latest = buildFlags {
-- Take the 'jobs' setting '~/.cabal/config' into account.
buildNumJobs = Flag . Just . determineNumJobs $
(numJobsConfigFlag `mappend` numJobsCmdLineFlag)
}
numJobsConfigFlag = installNumJobs . savedInstallFlags $ config
numJobsCmdLineFlag = buildNumJobs buildFlags
replAction :: (ReplFlags, BuildExFlags) -> [String] -> Action
replAction (replFlags, buildExFlags) extraArgs globalFlags = do
cwd <- getCurrentDirectory
pkgDesc <- findPackageDesc cwd
either (const onNoPkgDesc) (const onPkgDesc) pkgDesc
where
verbosity = fromFlagOrDefault normal (replVerbosity replFlags)
-- There is a .cabal file in the current directory: start a REPL and load
-- the project's modules.
onPkgDesc = do
let noAddSource = case replReload replFlags of
Flag True -> SkipAddSourceDepsCheck
_ -> fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (replDistPref replFlags)
-- Calls 'configureAction' to do the real work, so nothing special has to
-- be done to support sandboxes.
_ <-
reconfigure configureAction
verbosity distPref useSandbox noAddSource NoFlag
mempty [] globalFlags config
let progDb = defaultProgramDb
setupOptions = defaultSetupScriptOptions
{ useCabalVersion = orLaterVersion $ Version [1,18,0] []
, useDistPref = distPref
}
replFlags' = replFlags
{ replVerbosity = toFlag verbosity
, replDistPref = toFlag distPref
}
maybeWithSandboxDirOnSearchPath useSandbox $
setupWrapper verbosity setupOptions Nothing
(Cabal.replCommand progDb) (const replFlags') extraArgs
-- No .cabal file in the current directory: just start the REPL (possibly
-- using the sandbox package DB).
onNoPkgDesc = do
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
let configFlags = savedConfigureFlags config
(comp, platform, programDb) <- configCompilerAux' configFlags
programDb' <- reconfigurePrograms verbosity
(replProgramPaths replFlags)
(replProgramArgs replFlags)
programDb
startInterpreter verbosity programDb' comp platform
(configPackageDB' configFlags)
installAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> Action
installAction (configFlags, _, installFlags, _) _ globalFlags
| fromFlagOrDefault False (installOnly installFlags) = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
load <- try (loadConfigOrSandboxConfig verbosity globalFlags)
let config = either (\(SomeException _) -> mempty) snd load
distPref <- findSavedDistPref config (configDistPref configFlags)
let setupOpts = defaultSetupScriptOptions { useDistPref = distPref }
setupWrapper verbosity setupOpts Nothing installCommand (const mempty) []
installAction (configFlags, configExFlags, installFlags, haddockFlags)
extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
(useSandbox, config) <- fmap
(updateInstallDirs (configUserInstall configFlags))
(loadConfigOrSandboxConfig verbosity globalFlags)
targets <- readUserTargets verbosity extraArgs
-- TODO: It'd be nice if 'cabal install' picked up the '-w' flag passed to
-- 'configure' when run inside a sandbox. Right now, running
--
-- $ cabal sandbox init && cabal configure -w /path/to/ghc
-- && cabal build && cabal install
--
-- performs the compilation twice unless you also pass -w to 'install'.
-- However, this is the same behaviour that 'cabal install' has in the normal
-- mode of operation, so we stick to it for consistency.
let sandboxDistPref = case useSandbox of
NoSandbox -> NoFlag
UseSandbox sandboxDir -> Flag $ sandboxBuildDir sandboxDir
distPref <- findSavedDistPref config
(configDistPref configFlags `mappend` sandboxDistPref)
let configFlags' = maybeForceTests installFlags' $
savedConfigureFlags config `mappend`
configFlags { configDistPref = toFlag distPref }
configExFlags' = defaultConfigExFlags `mappend`
savedConfigureExFlags config `mappend` configExFlags
installFlags' = defaultInstallFlags `mappend`
savedInstallFlags config `mappend` installFlags
haddockFlags' = defaultHaddockFlags `mappend`
savedHaddockFlags config `mappend`
haddockFlags { haddockDistPref = toFlag distPref }
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, progdb) <- configCompilerAux' configFlags'
-- TODO: Redesign ProgramDB API to prevent such problems as #2241 in the
-- future.
progdb' <- configureAllKnownPrograms verbosity progdb
-- If we're working inside a sandbox and the user has set the -w option, we
-- may need to create a sandbox-local package DB for this compiler and add a
-- timestamp record for this compiler to the timestamp file.
configFlags'' <- case useSandbox of
NoSandbox -> configAbsolutePaths $ configFlags'
(UseSandbox sandboxDir) -> return $ setPackageDB sandboxDir comp platform
configFlags'
whenUsingSandbox useSandbox $ \sandboxDir -> do
initPackageDBIfNeeded verbosity configFlags'' comp progdb'
indexFile <- tryGetIndexFilePath config
maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile
(compilerId comp) platform
-- TODO: Passing 'SandboxPackageInfo' to install unconditionally here means
-- that 'cabal install some-package' inside a sandbox will sometimes reinstall
-- modified add-source deps, even if they are not among the dependencies of
-- 'some-package'. This can also prevent packages that depend on older
-- versions of add-source'd packages from building (see #1362).
maybeWithSandboxPackageInfo verbosity configFlags'' globalFlags'
comp platform progdb useSandbox $ \mSandboxPkgInfo ->
maybeWithSandboxDirOnSearchPath useSandbox $
withRepoContext verbosity globalFlags' $ \repoContext ->
install verbosity
(configPackageDB' configFlags'')
repoContext
comp platform progdb'
useSandbox mSandboxPkgInfo
globalFlags' configFlags'' configExFlags'
installFlags' haddockFlags'
targets
where
-- '--run-tests' implies '--enable-tests'.
maybeForceTests installFlags' configFlags' =
if fromFlagOrDefault False (installRunTests installFlags')
then configFlags' { configTests = toFlag True }
else configFlags'
testAction :: (TestFlags, BuildFlags, BuildExFlags) -> [String] -> GlobalFlags
-> IO ()
testAction (testFlags, buildFlags, buildExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (testVerbosity testFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (testDistPref testFlags)
let noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
buildFlags' = buildFlags
{ buildVerbosity = testVerbosity testFlags }
checkFlags = Check $ \_ flags@(configFlags, configExFlags) ->
if fromFlagOrDefault False (configTests configFlags)
then pure (mempty, flags)
else do
info verbosity "reconfiguring to enable tests"
let flags' = ( configFlags { configTests = toFlag True }
, configExFlags
)
pure (Any True, flags')
-- reconfigure also checks if we're in a sandbox and reinstalls add-source
-- deps if needed.
_ <-
reconfigure configureAction
verbosity distPref useSandbox noAddSource (buildNumJobs buildFlags')
checkFlags [] globalFlags config
let setupOptions = defaultSetupScriptOptions { useDistPref = distPref }
testFlags' = testFlags { testDistPref = toFlag distPref }
-- The package was just configured, so the LBI must be available.
names <- componentNamesFromLBI verbosity distPref "test suites"
(\c -> case c of { LBI.CTest{} -> True; _ -> False })
let extraArgs'
| null extraArgs = case names of
ComponentNamesUnknown -> []
ComponentNames names' -> [ name | LBI.CTestName name <- names' ]
| otherwise = extraArgs
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config distPref buildFlags' extraArgs'
maybeWithSandboxDirOnSearchPath useSandbox $
setupWrapper verbosity setupOptions Nothing
Cabal.testCommand (const testFlags') extraArgs'
data ComponentNames = ComponentNamesUnknown
| ComponentNames [LBI.ComponentName]
-- | Return the names of all buildable components matching a given predicate.
componentNamesFromLBI :: Verbosity -> FilePath -> String
-> (LBI.Component -> Bool)
-> IO ComponentNames
componentNamesFromLBI verbosity distPref targetsDescr compPred = do
eLBI <- tryGetPersistBuildConfig distPref
case eLBI of
Left err -> case err of
-- Note: the build config could have been generated by a custom setup
-- script built against a different Cabal version, so it's crucial that
-- we ignore the bad version error here.
ConfigStateFileBadVersion _ _ _ -> return ComponentNamesUnknown
_ -> die (show err)
Right lbi -> do
let pkgDescr = LBI.localPkgDescr lbi
names = map LBI.componentName
. filter (buildable . LBI.componentBuildInfo)
. filter compPred $
LBI.pkgComponents pkgDescr
if null names
then do notice verbosity $ "Package has no buildable "
++ targetsDescr ++ "."
exitSuccess -- See #3215.
else return $! (ComponentNames names)
benchmarkAction :: (BenchmarkFlags, BuildFlags, BuildExFlags)
-> [String] -> GlobalFlags
-> IO ()
benchmarkAction (benchmarkFlags, buildFlags, buildExFlags)
extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal
(benchmarkVerbosity benchmarkFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (benchmarkDistPref benchmarkFlags)
let buildFlags' = buildFlags
{ buildVerbosity = benchmarkVerbosity benchmarkFlags }
noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
let checkFlags = Check $ \_ flags@(configFlags, configExFlags) ->
if fromFlagOrDefault False (configBenchmarks configFlags)
then pure (mempty, flags)
else do
info verbosity "reconfiguring to enable benchmarks"
let flags' = ( configFlags { configBenchmarks = toFlag True }
, configExFlags
)
pure (Any True, flags')
-- reconfigure also checks if we're in a sandbox and reinstalls add-source
-- deps if needed.
config' <-
reconfigure configureAction
verbosity distPref useSandbox noAddSource (buildNumJobs buildFlags')
checkFlags [] globalFlags config
let setupOptions = defaultSetupScriptOptions { useDistPref = distPref }
benchmarkFlags'= benchmarkFlags { benchmarkDistPref = toFlag distPref }
-- The package was just configured, so the LBI must be available.
names <- componentNamesFromLBI verbosity distPref "benchmarks"
(\c -> case c of { LBI.CBench{} -> True; _ -> False; })
let extraArgs'
| null extraArgs = case names of
ComponentNamesUnknown -> []
ComponentNames names' -> [name | LBI.CBenchName name <- names']
| otherwise = extraArgs
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config' distPref buildFlags' extraArgs'
maybeWithSandboxDirOnSearchPath useSandbox $
setupWrapper verbosity setupOptions Nothing
Cabal.benchmarkCommand (const benchmarkFlags') extraArgs'
haddockAction :: HaddockFlags -> [String] -> Action
haddockAction haddockFlags extraArgs globalFlags = do
let verbosity = fromFlag (haddockVerbosity haddockFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (haddockDistPref haddockFlags)
config' <-
reconfigure configureAction
verbosity distPref useSandbox DontSkipAddSourceDepsCheck NoFlag
mempty [] globalFlags config
let haddockFlags' = defaultHaddockFlags `mappend`
savedHaddockFlags config' `mappend`
haddockFlags { haddockDistPref = toFlag distPref }
setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref }
setupWrapper verbosity setupScriptOptions Nothing
haddockCommand (const haddockFlags') extraArgs
when (haddockForHackage haddockFlags == Flag ForHackage) $ do
pkg <- fmap LBI.localPkgDescr (getPersistBuildConfig distPref)
let dest = distPref </> name <.> "tar.gz"
name = display (packageId pkg) ++ "-docs"
docDir = distPref </> "doc" </> "html"
createTarGzFile dest docDir name
notice verbosity $ "Documentation tarball created: " ++ dest
cleanAction :: CleanFlags -> [String] -> Action
cleanAction cleanFlags extraArgs globalFlags = do
load <- try (loadConfigOrSandboxConfig verbosity globalFlags)
let config = either (\(SomeException _) -> mempty) snd load
distPref <- findSavedDistPref config (cleanDistPref cleanFlags)
let setupScriptOptions = defaultSetupScriptOptions
{ useDistPref = distPref
, useWin32CleanHack = True
}
cleanFlags' = cleanFlags { cleanDistPref = toFlag distPref }
setupWrapper verbosity setupScriptOptions Nothing
cleanCommand (const cleanFlags') extraArgs
where
verbosity = fromFlagOrDefault normal (cleanVerbosity cleanFlags)
listAction :: ListFlags -> [String] -> Action
listAction listFlags extraArgs globalFlags = do
let verbosity = fromFlag (listVerbosity listFlags)
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let configFlags' = savedConfigureFlags config
configFlags = configFlags' {
configPackageDBs = configPackageDBs configFlags'
`mappend` listPackageDBs listFlags
}
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, _, progdb) <- configCompilerAux' configFlags
withRepoContext verbosity globalFlags' $ \repoContext ->
List.list verbosity
(configPackageDB' configFlags)
repoContext
comp
progdb
listFlags
extraArgs
infoAction :: InfoFlags -> [String] -> Action
infoAction infoFlags extraArgs globalFlags = do
let verbosity = fromFlag (infoVerbosity infoFlags)
targets <- readUserTargets verbosity extraArgs
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let configFlags' = savedConfigureFlags config
configFlags = configFlags' {
configPackageDBs = configPackageDBs configFlags'
`mappend` infoPackageDBs infoFlags
}
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, _, progdb) <- configCompilerAuxEx configFlags
withRepoContext verbosity globalFlags' $ \repoContext ->
List.info verbosity
(configPackageDB' configFlags)
repoContext
comp
progdb
globalFlags'
infoFlags
targets
updateAction :: Flag Verbosity -> [String] -> Action
updateAction verbosityFlag extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'update' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag verbosityFlag
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
withRepoContext verbosity globalFlags' $ \repoContext ->
update verbosity repoContext
upgradeAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> Action
upgradeAction _ _ _ = die $
"Use the 'cabal install' command instead of 'cabal upgrade'.\n"
++ "You can install the latest version of a package using 'cabal install'. "
++ "The 'cabal upgrade' command has been removed because people found it "
++ "confusing and it often led to broken packages.\n"
++ "If you want the old upgrade behaviour then use the install command "
++ "with the --upgrade-dependencies flag (but check first with --dry-run "
++ "to see what would happen). This will try to pick the latest versions "
++ "of all dependencies, rather than the usual behaviour of trying to pick "
++ "installed versions of all dependencies. If you do use "
++ "--upgrade-dependencies, it is recommended that you do not upgrade core "
++ "packages (e.g. by using appropriate --constraint= flags)."
fetchAction :: FetchFlags -> [String] -> Action
fetchAction fetchFlags extraArgs globalFlags = do
let verbosity = fromFlag (fetchVerbosity fetchFlags)
targets <- readUserTargets verbosity extraArgs
config <- loadConfig verbosity (globalConfigFile globalFlags)
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, progdb) <- configCompilerAux' configFlags
withRepoContext verbosity globalFlags' $ \repoContext ->
fetch verbosity
(configPackageDB' configFlags)
repoContext
comp platform progdb globalFlags' fetchFlags
targets
freezeAction :: FreezeFlags -> [String] -> Action
freezeAction freezeFlags _extraArgs globalFlags = do
let verbosity = fromFlag (freezeVerbosity freezeFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, progdb) <- configCompilerAux' configFlags
maybeWithSandboxPackageInfo verbosity configFlags globalFlags'
comp platform progdb useSandbox $ \mSandboxPkgInfo ->
maybeWithSandboxDirOnSearchPath useSandbox $
withRepoContext verbosity globalFlags' $ \repoContext ->
freeze verbosity
(configPackageDB' configFlags)
repoContext
comp platform progdb
mSandboxPkgInfo
globalFlags' freezeFlags
genBoundsAction :: FreezeFlags -> [String] -> GlobalFlags -> IO ()
genBoundsAction freezeFlags _extraArgs globalFlags = do
let verbosity = fromFlag (freezeVerbosity freezeFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, progdb) <- configCompilerAux' configFlags
maybeWithSandboxPackageInfo verbosity configFlags globalFlags'
comp platform progdb useSandbox $ \mSandboxPkgInfo ->
maybeWithSandboxDirOnSearchPath useSandbox $
withRepoContext verbosity globalFlags' $ \repoContext ->
genBounds verbosity
(configPackageDB' configFlags)
repoContext
comp platform progdb
mSandboxPkgInfo
globalFlags' freezeFlags
uploadAction :: UploadFlags -> [String] -> Action
uploadAction uploadFlags extraArgs globalFlags = do
config <- loadConfig verbosity (globalConfigFile globalFlags)
let uploadFlags' = savedUploadFlags config `mappend` uploadFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
tarfiles = extraArgs
when (null tarfiles && not (fromFlag (uploadDoc uploadFlags'))) $
die "the 'upload' command expects at least one .tar.gz archive."
checkTarFiles extraArgs
maybe_password <-
case uploadPasswordCmd uploadFlags'
of Flag (xs:xss) -> Just . Password <$>
getProgramInvocationOutput verbosity
(simpleProgramInvocation xs xss)
_ -> pure $ flagToMaybe $ uploadPassword uploadFlags'
withRepoContext verbosity globalFlags' $ \repoContext -> do
if fromFlag (uploadDoc uploadFlags')
then do
when (length tarfiles > 1) $
die $ "the 'upload' command can only upload documentation "
++ "for one package at a time."
tarfile <- maybe (generateDocTarball config) return $ listToMaybe tarfiles
Upload.uploadDoc verbosity
repoContext
(flagToMaybe $ uploadUsername uploadFlags')
maybe_password
(fromFlag (uploadCandidate uploadFlags'))
tarfile
else do
Upload.upload verbosity
repoContext
(flagToMaybe $ uploadUsername uploadFlags')
maybe_password
(fromFlag (uploadCandidate uploadFlags'))
tarfiles
where
verbosity = fromFlag (uploadVerbosity uploadFlags)
checkTarFiles tarfiles
| not (null otherFiles)
= die $ "the 'upload' command expects only .tar.gz archives: "
++ intercalate ", " otherFiles
| otherwise = sequence_
[ do exists <- doesFileExist tarfile
unless exists $ die $ "file not found: " ++ tarfile
| tarfile <- tarfiles ]
where otherFiles = filter (not . isTarGzFile) tarfiles
isTarGzFile file = case splitExtension file of
(file', ".gz") -> takeExtension file' == ".tar"
_ -> False
generateDocTarball config = do
notice verbosity $
"No documentation tarball specified. "
++ "Building a documentation tarball with default settings...\n"
++ "If you need to customise Haddock options, "
++ "run 'haddock --for-hackage' first "
++ "to generate a documentation tarball."
haddockAction (defaultHaddockFlags { haddockForHackage = Flag ForHackage })
[] globalFlags
distPref <- findSavedDistPref config NoFlag
pkg <- fmap LBI.localPkgDescr (getPersistBuildConfig distPref)
return $ distPref </> display (packageId pkg) ++ "-docs" <.> "tar.gz"
checkAction :: Flag Verbosity -> [String] -> Action
checkAction verbosityFlag extraArgs _globalFlags = do
unless (null extraArgs) $
die $ "'check' doesn't take any extra arguments: " ++ unwords extraArgs
allOk <- Check.check (fromFlag verbosityFlag)
unless allOk exitFailure
formatAction :: Flag Verbosity -> [String] -> Action
formatAction verbosityFlag extraArgs _globalFlags = do
let verbosity = fromFlag verbosityFlag
path <- case extraArgs of
[] -> do cwd <- getCurrentDirectory
tryFindPackageDesc cwd
(p:_) -> return p
pkgDesc <- readPackageDescription verbosity path
-- Uses 'writeFileAtomic' under the hood.
writeGenericPackageDescription path pkgDesc
uninstallAction :: Flag Verbosity -> [String] -> Action
uninstallAction _verbosityFlag extraArgs _globalFlags = do
let package = case extraArgs of
p:_ -> p
_ -> "PACKAGE_NAME"
die $ "This version of 'cabal-install' does not support the 'uninstall' "
++ "operation. "
++ "It will likely be implemented at some point in the future; "
++ "in the meantime you're advised to use either 'ghc-pkg unregister "
++ package ++ "' or 'cabal sandbox hc-pkg -- unregister " ++ package ++ "'."
sdistAction :: (SDistFlags, SDistExFlags) -> [String] -> Action
sdistAction (sdistFlags, sdistExFlags) extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'sdist' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag (sDistVerbosity sdistFlags)
load <- try (loadConfigOrSandboxConfig verbosity globalFlags)
let config = either (\(SomeException _) -> mempty) snd load
distPref <- findSavedDistPref config (sDistDistPref sdistFlags)
let sdistFlags' = sdistFlags { sDistDistPref = toFlag distPref }
sdist sdistFlags' sdistExFlags
reportAction :: ReportFlags -> [String] -> Action
reportAction reportFlags extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'report' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag (reportVerbosity reportFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags)
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
reportFlags' = savedReportFlags config `mappend` reportFlags
withRepoContext verbosity globalFlags' $ \repoContext ->
Upload.report verbosity repoContext
(flagToMaybe $ reportUsername reportFlags')
(flagToMaybe $ reportPassword reportFlags')
runAction :: (BuildFlags, BuildExFlags) -> [String] -> Action
runAction (buildFlags, buildExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (buildDistPref buildFlags)
let noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
-- reconfigure also checks if we're in a sandbox and reinstalls add-source
-- deps if needed.
config' <-
reconfigure configureAction
verbosity distPref useSandbox noAddSource (buildNumJobs buildFlags)
mempty [] globalFlags config
lbi <- getPersistBuildConfig distPref
(exe, exeArgs) <- splitRunArgs verbosity lbi extraArgs
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config' distPref buildFlags ["exe:" ++ exeName exe]
maybeWithSandboxDirOnSearchPath useSandbox $
run verbosity lbi exe exeArgs
getAction :: GetFlags -> [String] -> Action
getAction getFlags extraArgs globalFlags = do
let verbosity = fromFlag (getVerbosity getFlags)
targets <- readUserTargets verbosity extraArgs
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
withRepoContext verbosity (savedGlobalFlags config) $ \repoContext ->
get verbosity
repoContext
globalFlags'
getFlags
targets
unpackAction :: GetFlags -> [String] -> Action
unpackAction getFlags extraArgs globalFlags = do
getAction getFlags extraArgs globalFlags
initAction :: InitFlags -> [String] -> Action
initAction initFlags extraArgs globalFlags = do
when (extraArgs /= []) $
die $ "'init' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag (initVerbosity initFlags)
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let configFlags = savedConfigureFlags config
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, _, progdb) <- configCompilerAux' configFlags
withRepoContext verbosity globalFlags' $ \repoContext ->
initCabal verbosity
(configPackageDB' configFlags)
repoContext
comp
progdb
initFlags
sandboxAction :: SandboxFlags -> [String] -> Action
sandboxAction sandboxFlags extraArgs globalFlags = do
let verbosity = fromFlag (sandboxVerbosity sandboxFlags)
case extraArgs of
-- Basic sandbox commands.
["init"] -> sandboxInit verbosity sandboxFlags globalFlags
["delete"] -> sandboxDelete verbosity sandboxFlags globalFlags
("add-source":extra) -> do
when (noExtraArgs extra) $
die "The 'sandbox add-source' command expects at least one argument"
sandboxAddSource verbosity extra sandboxFlags globalFlags
("delete-source":extra) -> do
when (noExtraArgs extra) $
die ("The 'sandbox delete-source' command expects " ++
"at least one argument")
sandboxDeleteSource verbosity extra sandboxFlags globalFlags
["list-sources"] -> sandboxListSources verbosity sandboxFlags globalFlags
-- More advanced commands.
("hc-pkg":extra) -> do
when (noExtraArgs extra) $
die $ "The 'sandbox hc-pkg' command expects at least one argument"
sandboxHcPkg verbosity sandboxFlags globalFlags extra
["buildopts"] -> die "Not implemented!"
-- Hidden commands.
["dump-pkgenv"] -> dumpPackageEnvironment verbosity sandboxFlags globalFlags
-- Error handling.
[] -> die $ "Please specify a subcommand (see 'help sandbox')"
_ -> die $ "Unknown 'sandbox' subcommand: " ++ unwords extraArgs
where
noExtraArgs = (<1) . length
execAction :: ExecFlags -> [String] -> Action
execAction execFlags extraArgs globalFlags = do
let verbosity = fromFlag (execVerbosity execFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
let configFlags = savedConfigureFlags config
(comp, platform, progdb) <- getPersistOrConfigCompiler configFlags
exec verbosity useSandbox comp platform progdb extraArgs
userConfigAction :: UserConfigFlags -> [String] -> Action
userConfigAction ucflags extraArgs globalFlags = do
let verbosity = fromFlag (userConfigVerbosity ucflags)
force = fromFlag (userConfigForce ucflags)
case extraArgs of
("init":_) -> do
path <- configFile
fileExists <- doesFileExist path
if (not fileExists || (fileExists && force))
then void $ createDefaultConfigFile verbosity path
else die $ path ++ " already exists."
("diff":_) -> mapM_ putStrLn =<< userConfigDiff globalFlags
("update":_) -> userConfigUpdate verbosity globalFlags
-- Error handling.
[] -> die $ "Please specify a subcommand (see 'help user-config')"
_ -> die $ "Unknown 'user-config' subcommand: " ++ unwords extraArgs
where configFile = getConfigFilePath (globalConfigFile globalFlags)
-- | See 'Distribution.Client.Install.withWin32SelfUpgrade' for details.
--
win32SelfUpgradeAction :: Win32SelfUpgradeFlags -> [String] -> Action
win32SelfUpgradeAction selfUpgradeFlags (pid:path:_extraArgs) _globalFlags = do
let verbosity = fromFlag (win32SelfUpgradeVerbosity selfUpgradeFlags)
Win32SelfUpgrade.deleteOldExeFile verbosity (read pid) path -- TODO: eradicateNoParse
win32SelfUpgradeAction _ _ _ = return ()
-- | Used as an entry point when cabal-install needs to invoke itself
-- as a setup script. This can happen e.g. when doing parallel builds.
--
actAsSetupAction :: ActAsSetupFlags -> [String] -> Action
actAsSetupAction actAsSetupFlags args _globalFlags =
let bt = fromFlag (actAsSetupBuildType actAsSetupFlags)
in case bt of
Simple -> Simple.defaultMainArgs args
Configure -> Simple.defaultMainWithHooksArgs
Simple.autoconfUserHooks args
Make -> Make.defaultMainArgs args
Custom -> error "actAsSetupAction Custom"
(UnknownBuildType _) -> error "actAsSetupAction UnknownBuildType"
manpageAction :: [CommandSpec action] -> Flag Verbosity -> [String] -> Action
manpageAction commands _ extraArgs _ = do
unless (null extraArgs) $
die $ "'manpage' doesn't take any extra arguments: " ++ unwords extraArgs
pname <- getProgName
let cabalCmd = if takeExtension pname == ".exe"
then dropExtension pname
else pname
putStrLn $ manpage cabalCmd commands
| sopvop/cabal | cabal-install/Main.hs | bsd-3-clause | 52,238 | 3 | 24 | 13,282 | 10,570 | 5,478 | 5,092 | 914 | 10 |
{-# language CPP #-}
-- No documentation found for Chapter "Device"
module OpenXR.Core10.Device ( getSystem
, getSystemProperties
, createSession
, withSession
, destroySession
, enumerateEnvironmentBlendModes
, SystemId(..)
, SystemGetInfo(..)
, SystemProperties(..)
, SystemGraphicsProperties(..)
, SystemTrackingProperties(..)
, SessionCreateInfo(..)
) where
import OpenXR.CStruct.Utils (FixedArray)
import OpenXR.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 GHC.Show (showParen)
import Numeric (showHex)
import Data.ByteString (packCString)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Data.Vector (generateM)
import OpenXR.CStruct (FromCStruct)
import OpenXR.CStruct (FromCStruct(..))
import OpenXR.CStruct (ToCStruct)
import OpenXR.CStruct (ToCStruct(..))
import OpenXR.Zero (Zero)
import OpenXR.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.Type.Equality ((:~:)(Refl))
import Data.Typeable (Typeable)
import Foreign.C.Types (CChar)
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.Word (Word64)
import Data.ByteString (ByteString)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Data.Vector (Vector)
import OpenXR.CStruct.Utils (advancePtrBytes)
import OpenXR.Core10.FundamentalTypes (bool32ToBool)
import OpenXR.Core10.FundamentalTypes (boolToBool32)
import OpenXR.CStruct.Extends (forgetExtensions)
import OpenXR.CStruct.Utils (lowerArrayPtr)
import OpenXR.CStruct.Utils (pokeFixedLengthNullTerminatedByteString)
import OpenXR.NamedType ((:::))
import OpenXR.Core10.FundamentalTypes (Bool32)
import OpenXR.CStruct.Extends (Chain)
import OpenXR.Core10.Enums.EnvironmentBlendMode (EnvironmentBlendMode)
import OpenXR.Core10.Enums.EnvironmentBlendMode (EnvironmentBlendMode(..))
import OpenXR.CStruct.Extends (Extends)
import OpenXR.CStruct.Extends (Extendss)
import OpenXR.CStruct.Extends (Extensible(..))
import OpenXR.Core10.Enums.FormFactor (FormFactor)
import {-# SOURCE #-} OpenXR.Extensions.XR_KHR_D3D11_enable (GraphicsBindingD3D11KHR)
import {-# SOURCE #-} OpenXR.Extensions.XR_KHR_D3D12_enable (GraphicsBindingD3D12KHR)
import {-# SOURCE #-} OpenXR.Extensions.XR_MNDX_egl_enable (GraphicsBindingEGLMNDX)
import {-# SOURCE #-} OpenXR.Extensions.XR_KHR_opengl_es_enable (GraphicsBindingOpenGLESAndroidKHR)
import {-# SOURCE #-} OpenXR.Extensions.XR_KHR_opengl_enable (GraphicsBindingOpenGLWaylandKHR)
import {-# SOURCE #-} OpenXR.Extensions.XR_KHR_opengl_enable (GraphicsBindingOpenGLWin32KHR)
import {-# SOURCE #-} OpenXR.Extensions.XR_KHR_opengl_enable (GraphicsBindingOpenGLXcbKHR)
import {-# SOURCE #-} OpenXR.Extensions.XR_KHR_opengl_enable (GraphicsBindingOpenGLXlibKHR)
import {-# SOURCE #-} OpenXR.Extensions.XR_KHR_vulkan_enable (GraphicsBindingVulkanKHR)
import {-# SOURCE #-} OpenXR.Extensions.XR_MSFT_holographic_window_attachment (HolographicWindowAttachmentMSFT)
import OpenXR.Core10.Handles (Instance)
import OpenXR.Core10.Handles (Instance(..))
import OpenXR.Core10.Handles (Instance(Instance))
import OpenXR.Dynamic (InstanceCmds(pXrCreateSession))
import OpenXR.Dynamic (InstanceCmds(pXrDestroySession))
import OpenXR.Dynamic (InstanceCmds(pXrEnumerateEnvironmentBlendModes))
import OpenXR.Dynamic (InstanceCmds(pXrGetSystem))
import OpenXR.Dynamic (InstanceCmds(pXrGetSystemProperties))
import OpenXR.Core10.Handles (Instance_T)
import OpenXR.Core10.APIConstants (MAX_SYSTEM_NAME_SIZE)
import OpenXR.Exception (OpenXrException(..))
import OpenXR.CStruct.Extends (PeekChain)
import OpenXR.CStruct.Extends (PeekChain(..))
import OpenXR.CStruct.Extends (PokeChain)
import OpenXR.CStruct.Extends (PokeChain(..))
import OpenXR.Core10.Enums.Result (Result)
import OpenXR.Core10.Enums.Result (Result(..))
import OpenXR.Core10.Handles (Session)
import OpenXR.Core10.Handles (Session(..))
import OpenXR.Core10.Handles (Session(Session))
import OpenXR.Core10.Enums.SessionCreateFlagBits (SessionCreateFlags)
import {-# SOURCE #-} OpenXR.Extensions.XR_EXTX_overlay (SessionCreateInfoOverlayEXTX)
import OpenXR.Core10.Handles (Session_T)
import OpenXR.CStruct.Extends (SomeStruct)
import OpenXR.Core10.Enums.StructureType (StructureType)
import {-# SOURCE #-} OpenXR.Extensions.XR_EXT_eye_gaze_interaction (SystemEyeGazeInteractionPropertiesEXT)
import {-# SOURCE #-} OpenXR.Extensions.XR_MSFT_hand_tracking_mesh (SystemHandTrackingMeshPropertiesMSFT)
import {-# SOURCE #-} OpenXR.Extensions.XR_EXT_hand_tracking (SystemHandTrackingPropertiesEXT)
import OpenXR.Core10.Enums.ViewConfigurationType (ViewConfigurationType)
import OpenXR.Core10.Enums.ViewConfigurationType (ViewConfigurationType(..))
import OpenXR.Core10.Enums.Result (Result(SUCCESS))
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_SESSION_CREATE_INFO))
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_SYSTEM_GET_INFO))
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_SYSTEM_PROPERTIES))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkXrGetSystem
:: FunPtr (Ptr Instance_T -> Ptr SystemGetInfo -> Ptr SystemId -> IO Result) -> Ptr Instance_T -> Ptr SystemGetInfo -> Ptr SystemId -> IO Result
-- | xrGetSystem - Gets a system identifier
--
-- == Parameter Descriptions
--
-- = Description
--
-- To get an
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >,
-- an application specifies its desired
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#form_factor_description form factor>
-- to 'getSystem' and gets the runtime’s
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >
-- associated with that configuration.
--
-- If the form factor is supported but temporarily unavailable, 'getSystem'
-- /must/ return
-- 'OpenXR.Core10.Enums.Result.ERROR_FORM_FACTOR_UNAVAILABLE'. A runtime
-- /may/ return 'OpenXR.Core10.Enums.Result.SUCCESS' on a subsequent call
-- for a form factor it previously returned
-- 'OpenXR.Core10.Enums.Result.ERROR_FORM_FACTOR_UNAVAILABLE'. For example,
-- connecting or warming up hardware might cause an unavailable form factor
-- to become available.
--
-- == Return Codes
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>]
--
-- - 'OpenXR.Core10.Enums.Result.SUCCESS'
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>]
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_FORM_FACTOR_UNAVAILABLE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_FORM_FACTOR_UNSUPPORTED'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE'
--
-- = See Also
--
-- 'OpenXR.Core10.APIConstants.NULL_SYSTEM_ID',
-- 'OpenXR.Core10.Handles.Instance', 'SystemGetInfo',
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >
getSystem :: forall io
. (MonadIO io)
=> -- | @instance@ is the handle of the instance from which to get the
-- information.
--
-- #VUID-xrGetSystem-instance-parameter# @instance@ /must/ be a valid
-- 'OpenXR.Core10.Handles.Instance' handle
Instance
-> -- | @getInfo@ is a pointer to an 'SystemGetInfo' structure containing the
-- application’s requests for a system.
--
-- #VUID-xrGetSystem-getInfo-parameter# @getInfo@ /must/ be a pointer to a
-- valid 'SystemGetInfo' structure
SystemGetInfo
-> io (SystemId)
getSystem instance' getInfo = liftIO . evalContT $ do
let xrGetSystemPtr = pXrGetSystem (case instance' of Instance{instanceCmds} -> instanceCmds)
lift $ unless (xrGetSystemPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrGetSystem is null" Nothing Nothing
let xrGetSystem' = mkXrGetSystem xrGetSystemPtr
getInfo' <- ContT $ withCStruct (getInfo)
pSystemId <- ContT $ bracket (callocBytes @SystemId 8) free
r <- lift $ traceAroundEvent "xrGetSystem" (xrGetSystem' (instanceHandle (instance')) getInfo' (pSystemId))
lift $ when (r < SUCCESS) (throwIO (OpenXrException r))
systemId <- lift $ peek @SystemId pSystemId
pure $ (systemId)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkXrGetSystemProperties
:: FunPtr (Ptr Instance_T -> SystemId -> Ptr (SomeStruct SystemProperties) -> IO Result) -> Ptr Instance_T -> SystemId -> Ptr (SomeStruct SystemProperties) -> IO Result
-- | xrGetSystemProperties - Gets the properties of a particular system
--
-- == Parameter Descriptions
--
-- = Description
--
-- An application /can/ call 'getSystemProperties' to retrieve information
-- about the system such as vendor ID, system name, and graphics and
-- tracking properties.
--
-- == Return Codes
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>]
--
-- - 'OpenXR.Core10.Enums.Result.SUCCESS'
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>]
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_OUT_OF_MEMORY'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_SYSTEM_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE'
--
-- = See Also
--
-- 'OpenXR.Core10.Handles.Instance',
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >,
-- 'SystemProperties'
getSystemProperties :: forall a io
. (Extendss SystemProperties a, PokeChain a, PeekChain a, MonadIO io)
=> -- | @instance@ is the instance from which @systemId@ was retrieved.
--
-- #VUID-xrGetSystemProperties-instance-parameter# @instance@ /must/ be a
-- valid 'OpenXR.Core10.Handles.Instance' handle
Instance
-> -- | @systemId@ is the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >
-- whose properties will be queried.
SystemId
-> io (SystemProperties a)
getSystemProperties instance' systemId = liftIO . evalContT $ do
let xrGetSystemPropertiesPtr = pXrGetSystemProperties (case instance' of Instance{instanceCmds} -> instanceCmds)
lift $ unless (xrGetSystemPropertiesPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrGetSystemProperties is null" Nothing Nothing
let xrGetSystemProperties' = mkXrGetSystemProperties xrGetSystemPropertiesPtr
pProperties <- ContT (withZeroCStruct @(SystemProperties _))
r <- lift $ traceAroundEvent "xrGetSystemProperties" (xrGetSystemProperties' (instanceHandle (instance')) (systemId) (forgetExtensions (pProperties)))
lift $ when (r < SUCCESS) (throwIO (OpenXrException r))
properties <- lift $ peekCStruct @(SystemProperties _) pProperties
pure $ (properties)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkXrCreateSession
:: FunPtr (Ptr Instance_T -> Ptr (SomeStruct SessionCreateInfo) -> Ptr (Ptr Session_T) -> IO Result) -> Ptr Instance_T -> Ptr (SomeStruct SessionCreateInfo) -> Ptr (Ptr Session_T) -> IO Result
-- | xrCreateSession - Creates an XrSession
--
-- == Parameter Descriptions
--
-- = Description
--
-- Creates a session using the provided @createInfo@ and returns a handle
-- to that session. This session is created in the
-- 'OpenXR.Core10.Enums.SessionState.SESSION_STATE_IDLE' state, and a
-- corresponding 'OpenXR.Core10.OtherTypes.EventDataSessionStateChanged'
-- event to the 'OpenXR.Core10.Enums.SessionState.SESSION_STATE_IDLE' state
-- /must/ be generated as the first such event for the new session.
--
-- == Return Codes
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>]
--
-- - 'OpenXR.Core10.Enums.Result.SUCCESS'
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>]
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_OUT_OF_MEMORY'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_LIMIT_REACHED'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_SYSTEM_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_GRAPHICS_DEVICE_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING'
--
-- = See Also
--
-- 'OpenXR.Core10.Instance.ExtensionProperties',
-- 'OpenXR.Core10.Handles.Instance', 'OpenXR.Core10.Handles.Session',
-- 'OpenXR.Core10.Enums.SessionCreateFlagBits.SessionCreateFlags',
-- 'SessionCreateInfo', 'OpenXR.Core10.Session.beginSession',
-- 'destroySession', 'OpenXR.Core10.Session.endSession'
createSession :: forall a io
. (Extendss SessionCreateInfo a, PokeChain a, MonadIO io)
=> -- | @instance@ is the instance from which @systemId@ was retrieved.
--
-- #VUID-xrCreateSession-instance-parameter# @instance@ /must/ be a valid
-- 'OpenXR.Core10.Handles.Instance' handle
Instance
-> -- | @createInfo@ is a pointer to an 'SessionCreateInfo' structure containing
-- information about how to create the session.
--
-- #VUID-xrCreateSession-createInfo-parameter# @createInfo@ /must/ be a
-- pointer to a valid 'SessionCreateInfo' structure
(SessionCreateInfo a)
-> io (Session)
createSession instance' createInfo = liftIO . evalContT $ do
let cmds = case instance' of Instance{instanceCmds} -> instanceCmds
let xrCreateSessionPtr = pXrCreateSession cmds
lift $ unless (xrCreateSessionPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrCreateSession is null" Nothing Nothing
let xrCreateSession' = mkXrCreateSession xrCreateSessionPtr
createInfo' <- ContT $ withCStruct (createInfo)
pSession <- ContT $ bracket (callocBytes @(Ptr Session_T) 8) free
r <- lift $ traceAroundEvent "xrCreateSession" (xrCreateSession' (instanceHandle (instance')) (forgetExtensions createInfo') (pSession))
lift $ when (r < SUCCESS) (throwIO (OpenXrException r))
session <- lift $ peek @(Ptr Session_T) pSession
pure $ (((\h -> Session h cmds ) session))
-- | A convenience wrapper to make a compatible pair of calls to
-- 'createSession' and 'destroySession'
--
-- To ensure that 'destroySession' 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.
--
withSession :: forall a io r . (Extendss SessionCreateInfo a, PokeChain a, MonadIO io) => Instance -> SessionCreateInfo a -> (io Session -> (Session -> io ()) -> r) -> r
withSession instance' createInfo b =
b (createSession instance' createInfo)
(\(o0) -> destroySession o0)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkXrDestroySession
:: FunPtr (Ptr Session_T -> IO Result) -> Ptr Session_T -> IO Result
-- | xrDestroySession - Destroys an XrSession
--
-- == Parameter Descriptions
--
-- = Description
--
-- 'OpenXR.Core10.Handles.Session' handles are destroyed using
-- 'destroySession'. When an 'OpenXR.Core10.Handles.Session' is destroyed,
-- all handles that are children of that 'OpenXR.Core10.Handles.Session'
-- are also destroyed.
--
-- The application is responsible for ensuring that it has no calls using
-- @session@ in progress when the session is destroyed.
--
-- 'destroySession' can be called when the session is in any session state.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-xrDestroySession-session-parameter# @session@ /must/ be a
-- valid 'OpenXR.Core10.Handles.Session' handle
--
-- == Thread Safety
--
-- - Access to @session@, and any child handles, /must/ be externally
-- synchronized
--
-- == Return Codes
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>]
--
-- - 'OpenXR.Core10.Enums.Result.SUCCESS'
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>]
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID'
--
-- = See Also
--
-- 'OpenXR.Core10.Handles.Session', 'OpenXR.Core10.Session.beginSession',
-- 'createSession', 'OpenXR.Core10.Session.endSession'
destroySession :: forall io
. (MonadIO io)
=> -- | @session@ is the session to destroy.
Session
-> io ()
destroySession session = liftIO $ do
let xrDestroySessionPtr = pXrDestroySession (case session of Session{instanceCmds} -> instanceCmds)
unless (xrDestroySessionPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrDestroySession is null" Nothing Nothing
let xrDestroySession' = mkXrDestroySession xrDestroySessionPtr
r <- traceAroundEvent "xrDestroySession" (xrDestroySession' (sessionHandle (session)))
when (r < SUCCESS) (throwIO (OpenXrException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkXrEnumerateEnvironmentBlendModes
:: FunPtr (Ptr Instance_T -> SystemId -> ViewConfigurationType -> Word32 -> Ptr Word32 -> Ptr EnvironmentBlendMode -> IO Result) -> Ptr Instance_T -> SystemId -> ViewConfigurationType -> Word32 -> Ptr Word32 -> Ptr EnvironmentBlendMode -> IO Result
-- | xrEnumerateEnvironmentBlendModes - Lists environment blend modes
--
-- == Parameter Descriptions
--
-- - @instance@ is the instance from which @systemId@ was retrieved.
--
-- - @systemId@ is the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >
-- whose environment blend modes will be enumerated.
--
-- - @viewConfigurationType@ is the
-- 'OpenXR.Core10.Enums.ViewConfigurationType.ViewConfigurationType' to
-- enumerate.
--
-- - @environmentBlendModeCapacityInput@ is the capacity of the
-- @environmentBlendModes@ array, or 0 to indicate a request to
-- retrieve the required capacity.
--
-- - @environmentBlendModeCountOutput@ is a pointer to the count of
-- @environmentBlendModes@ written, or a pointer to the required
-- capacity in the case that @environmentBlendModeCapacityInput@ is 0.
--
-- - @environmentBlendModes@ is a pointer to an array of
-- 'OpenXR.Core10.Enums.EnvironmentBlendMode.EnvironmentBlendMode'
-- values, but /can/ be @NULL@ if @environmentBlendModeCapacityInput@
-- is 0.
--
-- - See
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#buffer-size-parameters Buffer Size Parameters>
-- chapter for a detailed description of retrieving the required
-- @environmentBlendModes@ size.
--
-- = Description
--
-- Enumerates the set of environment blend modes that this runtime supports
-- for a given view configuration of the system. Environment blend modes
-- /should/ be in order from highest to lowest runtime preference.
--
-- Runtimes /must/ always return identical buffer contents from this
-- enumeration for the given @systemId@ and @viewConfigurationType@ for the
-- lifetime of the instance.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-xrEnumerateEnvironmentBlendModes-instance-parameter#
-- @instance@ /must/ be a valid 'OpenXR.Core10.Handles.Instance' handle
--
-- - #VUID-xrEnumerateEnvironmentBlendModes-viewConfigurationType-parameter#
-- @viewConfigurationType@ /must/ be a valid
-- 'OpenXR.Core10.Enums.ViewConfigurationType.ViewConfigurationType'
-- value
--
-- - #VUID-xrEnumerateEnvironmentBlendModes-environmentBlendModeCountOutput-parameter#
-- @environmentBlendModeCountOutput@ /must/ be a pointer to a
-- @uint32_t@ value
--
-- - #VUID-xrEnumerateEnvironmentBlendModes-environmentBlendModes-parameter#
-- If @environmentBlendModeCapacityInput@ is not @0@,
-- @environmentBlendModes@ /must/ be a pointer to an array of
-- @environmentBlendModeCapacityInput@
-- 'OpenXR.Core10.Enums.EnvironmentBlendMode.EnvironmentBlendMode'
-- values
--
-- == Return Codes
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>]
--
-- - 'OpenXR.Core10.Enums.Result.SUCCESS'
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>]
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_SYSTEM_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_SIZE_INSUFFICIENT'
--
-- = See Also
--
-- 'OpenXR.Core10.Enums.EnvironmentBlendMode.EnvironmentBlendMode',
-- 'OpenXR.Core10.Handles.Instance',
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >,
-- 'OpenXR.Core10.Enums.ViewConfigurationType.ViewConfigurationType'
enumerateEnvironmentBlendModes :: forall io
. (MonadIO io)
=> -- No documentation found for Nested "xrEnumerateEnvironmentBlendModes" "instance"
Instance
-> -- No documentation found for Nested "xrEnumerateEnvironmentBlendModes" "systemId"
SystemId
-> -- No documentation found for Nested "xrEnumerateEnvironmentBlendModes" "viewConfigurationType"
ViewConfigurationType
-> io (("environmentBlendModes" ::: Vector EnvironmentBlendMode))
enumerateEnvironmentBlendModes instance' systemId viewConfigurationType = liftIO . evalContT $ do
let xrEnumerateEnvironmentBlendModesPtr = pXrEnumerateEnvironmentBlendModes (case instance' of Instance{instanceCmds} -> instanceCmds)
lift $ unless (xrEnumerateEnvironmentBlendModesPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrEnumerateEnvironmentBlendModes is null" Nothing Nothing
let xrEnumerateEnvironmentBlendModes' = mkXrEnumerateEnvironmentBlendModes xrEnumerateEnvironmentBlendModesPtr
let instance'' = instanceHandle (instance')
pEnvironmentBlendModeCountOutput <- ContT $ bracket (callocBytes @Word32 4) free
r <- lift $ traceAroundEvent "xrEnumerateEnvironmentBlendModes" (xrEnumerateEnvironmentBlendModes' instance'' (systemId) (viewConfigurationType) (0) (pEnvironmentBlendModeCountOutput) (nullPtr))
lift $ when (r < SUCCESS) (throwIO (OpenXrException r))
environmentBlendModeCountOutput <- lift $ peek @Word32 pEnvironmentBlendModeCountOutput
pEnvironmentBlendModes <- ContT $ bracket (callocBytes @EnvironmentBlendMode ((fromIntegral (environmentBlendModeCountOutput)) * 4)) free
r' <- lift $ traceAroundEvent "xrEnumerateEnvironmentBlendModes" (xrEnumerateEnvironmentBlendModes' instance'' (systemId) (viewConfigurationType) ((environmentBlendModeCountOutput)) (pEnvironmentBlendModeCountOutput) (pEnvironmentBlendModes))
lift $ when (r' < SUCCESS) (throwIO (OpenXrException r'))
environmentBlendModeCountOutput' <- lift $ peek @Word32 pEnvironmentBlendModeCountOutput
environmentBlendModes' <- lift $ generateM (fromIntegral (environmentBlendModeCountOutput')) (\i -> peek @EnvironmentBlendMode ((pEnvironmentBlendModes `advancePtrBytes` (4 * (i)) :: Ptr EnvironmentBlendMode)))
pure $ (environmentBlendModes')
-- | XrSystemId - Identifier for a system
--
-- = Description
--
-- An
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >
-- is an opaque atom used by the runtime to identify a system. The value
-- 'OpenXR.Core10.APIConstants.NULL_SYSTEM_ID' is considered an invalid
-- system.
--
-- = See Also
--
-- 'OpenXR.Core10.APIConstants.NULL_SYSTEM_ID', 'SessionCreateInfo',
-- 'SystemProperties',
-- 'OpenXR.Extensions.XR_KHR_vulkan_enable2.VulkanDeviceCreateInfoKHR',
-- 'OpenXR.Extensions.XR_KHR_vulkan_enable2.VulkanGraphicsDeviceGetInfoKHR',
-- 'OpenXR.Extensions.XR_KHR_vulkan_enable2.VulkanInstanceCreateInfoKHR',
-- 'enumerateEnvironmentBlendModes',
-- 'OpenXR.Core10.ViewConfigurations.enumerateViewConfigurationViews',
-- 'OpenXR.Core10.ViewConfigurations.enumerateViewConfigurations',
-- 'OpenXR.Extensions.XR_KHR_D3D11_enable.getD3D11GraphicsRequirementsKHR',
-- 'OpenXR.Extensions.XR_KHR_D3D12_enable.getD3D12GraphicsRequirementsKHR',
-- 'OpenXR.Extensions.XR_KHR_opengl_es_enable.getOpenGLESGraphicsRequirementsKHR',
-- 'OpenXR.Extensions.XR_KHR_opengl_enable.getOpenGLGraphicsRequirementsKHR',
-- 'getSystem', 'getSystemProperties',
-- 'OpenXR.Core10.ViewConfigurations.getViewConfigurationProperties',
-- 'OpenXR.Extensions.XR_KHR_vulkan_enable.getVulkanDeviceExtensionsKHR',
-- 'OpenXR.Extensions.XR_KHR_vulkan_enable.getVulkanGraphicsDeviceKHR',
-- 'OpenXR.Extensions.XR_KHR_vulkan_enable2.getVulkanGraphicsRequirements2KHR',
-- 'OpenXR.Extensions.XR_KHR_vulkan_enable.getVulkanGraphicsRequirementsKHR',
-- 'OpenXR.Extensions.XR_KHR_vulkan_enable.getVulkanInstanceExtensionsKHR'
newtype SystemId = SystemId Word64
deriving newtype (Eq, Ord, Storable, Zero)
instance Show SystemId where
showsPrec p (SystemId x) = showParen (p >= 11) (showString "SystemId 0x" . showHex x)
-- | XrSystemGetInfo - Specifies desired attributes of the system
--
-- == Member Descriptions
--
-- = Description
--
-- The 'SystemGetInfo' structure specifies attributes about a system as
-- desired by an application.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- 'OpenXR.Core10.Enums.FormFactor.FormFactor',
-- 'OpenXR.Core10.Enums.StructureType.StructureType', 'getSystem'
data SystemGetInfo = SystemGetInfo
{ -- | @formFactor@ is the 'OpenXR.Core10.Enums.FormFactor.FormFactor'
-- requested by the application.
--
-- #VUID-XrSystemGetInfo-formFactor-parameter# @formFactor@ /must/ be a
-- valid 'OpenXR.Core10.Enums.FormFactor.FormFactor' value
formFactor :: FormFactor }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SystemGetInfo)
#endif
deriving instance Show SystemGetInfo
instance ToCStruct SystemGetInfo where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SystemGetInfo{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_GET_INFO)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr FormFactor)) (formFactor)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_GET_INFO)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr FormFactor)) (zero)
f
instance FromCStruct SystemGetInfo where
peekCStruct p = do
formFactor <- peek @FormFactor ((p `plusPtr` 16 :: Ptr FormFactor))
pure $ SystemGetInfo
formFactor
instance Storable SystemGetInfo where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SystemGetInfo where
zero = SystemGetInfo
zero
-- | XrSystemProperties - Properties of a particular system
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- 'OpenXR.Core10.Enums.StructureType.StructureType',
-- 'SystemGraphicsProperties',
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >,
-- 'SystemTrackingProperties', 'getSystem', 'getSystemProperties'
data SystemProperties (es :: [Type]) = SystemProperties
{ -- | @next@ is @NULL@ or a pointer to the next structure in a structure
-- chain. No such structures are defined in core OpenXR.
--
-- #VUID-XrSystemProperties-next-next# @next@ /must/ be @NULL@ or a valid
-- pointer to the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain>.
-- See also:
-- 'OpenXR.Extensions.XR_EXT_eye_gaze_interaction.SystemEyeGazeInteractionPropertiesEXT',
-- 'OpenXR.Extensions.XR_MSFT_hand_tracking_mesh.SystemHandTrackingMeshPropertiesMSFT',
-- 'OpenXR.Extensions.XR_EXT_hand_tracking.SystemHandTrackingPropertiesEXT'
next :: Chain es
, -- | @systemId@ is the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >
-- identifying the system.
systemId :: SystemId
, -- | @vendorId@ is a unique identifier for the vendor of the system.
vendorId :: Word32
, -- | @systemName@ is a string containing the name of the system.
systemName :: ByteString
, -- | @graphicsProperties@ is an 'SystemGraphicsProperties' structure
-- specifying the system graphics properties.
graphicsProperties :: SystemGraphicsProperties
, -- | @trackingProperties@ is an 'SystemTrackingProperties' structure
-- specifying system tracking properties.
trackingProperties :: SystemTrackingProperties
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SystemProperties (es :: [Type]))
#endif
deriving instance Show (Chain es) => Show (SystemProperties es)
instance Extensible SystemProperties where
extensibleTypeName = "SystemProperties"
setNext SystemProperties{..} next' = SystemProperties{next = next', ..}
getNext SystemProperties{..} = next
extends :: forall e b proxy. Typeable e => proxy e -> (Extends SystemProperties e => b) -> Maybe b
extends _ f
| Just Refl <- eqT @e @SystemHandTrackingMeshPropertiesMSFT = Just f
| Just Refl <- eqT @e @SystemHandTrackingPropertiesEXT = Just f
| Just Refl <- eqT @e @SystemEyeGazeInteractionPropertiesEXT = Just f
| otherwise = Nothing
instance (Extendss SystemProperties es, PokeChain es) => ToCStruct (SystemProperties es) where
withCStruct x f = allocaBytes 304 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SystemProperties{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_PROPERTIES)
next'' <- fmap castPtr . ContT $ withChain (next)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) next''
lift $ poke ((p `plusPtr` 16 :: Ptr SystemId)) (systemId)
lift $ poke ((p `plusPtr` 24 :: Ptr Word32)) (vendorId)
lift $ pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 28 :: Ptr (FixedArray MAX_SYSTEM_NAME_SIZE CChar))) (systemName)
lift $ poke ((p `plusPtr` 284 :: Ptr SystemGraphicsProperties)) (graphicsProperties)
lift $ poke ((p `plusPtr` 296 :: Ptr SystemTrackingProperties)) (trackingProperties)
lift $ f
cStructSize = 304
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_PROPERTIES)
pNext' <- fmap castPtr . ContT $ withZeroChain @es
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext'
lift $ poke ((p `plusPtr` 16 :: Ptr SystemId)) (zero)
lift $ poke ((p `plusPtr` 24 :: Ptr Word32)) (zero)
lift $ pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 28 :: Ptr (FixedArray MAX_SYSTEM_NAME_SIZE CChar))) (mempty)
lift $ poke ((p `plusPtr` 284 :: Ptr SystemGraphicsProperties)) (zero)
lift $ poke ((p `plusPtr` 296 :: Ptr SystemTrackingProperties)) (zero)
lift $ f
instance (Extendss SystemProperties es, PeekChain es) => FromCStruct (SystemProperties es) where
peekCStruct p = do
next <- peek @(Ptr ()) ((p `plusPtr` 8 :: Ptr (Ptr ())))
next' <- peekChain (castPtr next)
systemId <- peek @SystemId ((p `plusPtr` 16 :: Ptr SystemId))
vendorId <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32))
systemName <- packCString (lowerArrayPtr ((p `plusPtr` 28 :: Ptr (FixedArray MAX_SYSTEM_NAME_SIZE CChar))))
graphicsProperties <- peekCStruct @SystemGraphicsProperties ((p `plusPtr` 284 :: Ptr SystemGraphicsProperties))
trackingProperties <- peekCStruct @SystemTrackingProperties ((p `plusPtr` 296 :: Ptr SystemTrackingProperties))
pure $ SystemProperties
next' systemId vendorId systemName graphicsProperties trackingProperties
instance es ~ '[] => Zero (SystemProperties es) where
zero = SystemProperties
()
zero
zero
mempty
zero
zero
-- | XrSystemGraphicsProperties - Graphics-related properties of a particular
-- system
--
-- == Member Descriptions
--
-- = See Also
--
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >,
-- 'SystemProperties', 'SystemTrackingProperties', 'getSystem',
-- 'getSystemProperties'
data SystemGraphicsProperties = SystemGraphicsProperties
{ -- | @maxSwapchainImageHeight@ is the maximum swapchain image pixel height
-- supported by this system.
maxSwapchainImageHeight :: Word32
, -- | @maxSwapchainImageWidth@ is the maximum swapchain image pixel width
-- supported by this system.
maxSwapchainImageWidth :: Word32
, -- | @maxLayerCount@ is the maximum number of composition layers supported by
-- this system. The runtime /must/ support at least
-- 'OpenXR.Core10.APIConstants.MIN_COMPOSITION_LAYERS_SUPPORTED' layers.
maxLayerCount :: Word32
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SystemGraphicsProperties)
#endif
deriving instance Show SystemGraphicsProperties
instance ToCStruct SystemGraphicsProperties where
withCStruct x f = allocaBytes 12 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SystemGraphicsProperties{..} f = do
poke ((p `plusPtr` 0 :: Ptr Word32)) (maxSwapchainImageHeight)
poke ((p `plusPtr` 4 :: Ptr Word32)) (maxSwapchainImageWidth)
poke ((p `plusPtr` 8 :: Ptr Word32)) (maxLayerCount)
f
cStructSize = 12
cStructAlignment = 4
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr Word32)) (zero)
poke ((p `plusPtr` 4 :: Ptr Word32)) (zero)
poke ((p `plusPtr` 8 :: Ptr Word32)) (zero)
f
instance FromCStruct SystemGraphicsProperties where
peekCStruct p = do
maxSwapchainImageHeight <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32))
maxSwapchainImageWidth <- peek @Word32 ((p `plusPtr` 4 :: Ptr Word32))
maxLayerCount <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32))
pure $ SystemGraphicsProperties
maxSwapchainImageHeight maxSwapchainImageWidth maxLayerCount
instance Storable SystemGraphicsProperties where
sizeOf ~_ = 12
alignment ~_ = 4
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SystemGraphicsProperties where
zero = SystemGraphicsProperties
zero
zero
zero
-- | XrSystemTrackingProperties - Tracking-related properties of a particular
-- system
--
-- == Member Descriptions
--
-- = See Also
--
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrBool32 >,
-- 'SystemGraphicsProperties',
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >,
-- 'SystemProperties', 'getSystem', 'getSystemProperties'
data SystemTrackingProperties = SystemTrackingProperties
{ -- | @orientationTracking@ is set to 'OpenXR.Core10.FundamentalTypes.TRUE' to
-- indicate the system supports orientational tracking of the view pose(s),
-- 'OpenXR.Core10.FundamentalTypes.FALSE' otherwise.
orientationTracking :: Bool
, -- | @positionTracking@ is set to 'OpenXR.Core10.FundamentalTypes.TRUE' to
-- indicate the system supports positional tracking of the view pose(s),
-- 'OpenXR.Core10.FundamentalTypes.FALSE' otherwise.
positionTracking :: Bool
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SystemTrackingProperties)
#endif
deriving instance Show SystemTrackingProperties
instance ToCStruct SystemTrackingProperties where
withCStruct x f = allocaBytes 8 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SystemTrackingProperties{..} f = do
poke ((p `plusPtr` 0 :: Ptr Bool32)) (boolToBool32 (orientationTracking))
poke ((p `plusPtr` 4 :: Ptr Bool32)) (boolToBool32 (positionTracking))
f
cStructSize = 8
cStructAlignment = 4
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 4 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct SystemTrackingProperties where
peekCStruct p = do
orientationTracking <- peek @Bool32 ((p `plusPtr` 0 :: Ptr Bool32))
positionTracking <- peek @Bool32 ((p `plusPtr` 4 :: Ptr Bool32))
pure $ SystemTrackingProperties
(bool32ToBool orientationTracking) (bool32ToBool positionTracking)
instance Storable SystemTrackingProperties where
sizeOf ~_ = 8
alignment ~_ = 4
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SystemTrackingProperties where
zero = SystemTrackingProperties
zero
zero
-- | XrSessionCreateInfo - Creates a session
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- 'OpenXR.Core10.Enums.SessionCreateFlagBits.SessionCreateFlags',
-- 'OpenXR.Core10.Enums.StructureType.StructureType',
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >,
-- 'createSession'
data SessionCreateInfo (es :: [Type]) = SessionCreateInfo
{ -- | @next@ is @NULL@ or a pointer to the next structure in a structure
-- chain. No such structures are defined in core OpenXR. Note that in most
-- cases one graphics API extension specific struct needs to be in this
-- next chain.
--
-- @next@, unless otherwise specified via an extension, /must/ contain
-- exactly one graphics API binding structure (a structure whose name
-- begins with @\"XrGraphicsBinding\"@) or
-- 'OpenXR.Core10.Enums.Result.ERROR_GRAPHICS_DEVICE_INVALID' /must/ be
-- returned.
--
-- #VUID-XrSessionCreateInfo-next-next# @next@ /must/ be @NULL@ or a valid
-- pointer to the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain>.
-- See also:
-- 'OpenXR.Extensions.XR_KHR_D3D11_enable.GraphicsBindingD3D11KHR',
-- 'OpenXR.Extensions.XR_KHR_D3D12_enable.GraphicsBindingD3D12KHR',
-- 'OpenXR.Extensions.XR_MNDX_egl_enable.GraphicsBindingEGLMNDX',
-- 'OpenXR.Extensions.XR_KHR_opengl_es_enable.GraphicsBindingOpenGLESAndroidKHR',
-- 'OpenXR.Extensions.XR_KHR_opengl_enable.GraphicsBindingOpenGLWaylandKHR',
-- 'OpenXR.Extensions.XR_KHR_opengl_enable.GraphicsBindingOpenGLWin32KHR',
-- 'OpenXR.Extensions.XR_KHR_opengl_enable.GraphicsBindingOpenGLXcbKHR',
-- 'OpenXR.Extensions.XR_KHR_opengl_enable.GraphicsBindingOpenGLXlibKHR',
-- 'OpenXR.Extensions.XR_KHR_vulkan_enable.GraphicsBindingVulkanKHR',
-- 'OpenXR.Extensions.XR_MSFT_holographic_window_attachment.HolographicWindowAttachmentMSFT',
-- 'OpenXR.Extensions.XR_EXTX_overlay.SessionCreateInfoOverlayEXTX'
next :: Chain es
, -- | @createFlags@ identifies
-- 'OpenXR.Core10.Enums.SessionCreateFlagBits.SessionCreateFlags' that
-- apply to the creation.
--
-- #VUID-XrSessionCreateInfo-createFlags-zerobitmask# @createFlags@ /must/
-- be @0@
createFlags :: SessionCreateFlags
, -- | @systemId@ is the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >
-- representing the system of devices to be used by this session.
--
-- @systemId@ /must/ be a valid
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrSystemId >
-- or 'OpenXR.Core10.Enums.Result.ERROR_SYSTEM_INVALID' /must/ be returned.
systemId :: SystemId
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SessionCreateInfo (es :: [Type]))
#endif
deriving instance Show (Chain es) => Show (SessionCreateInfo es)
instance Extensible SessionCreateInfo where
extensibleTypeName = "SessionCreateInfo"
setNext SessionCreateInfo{..} next' = SessionCreateInfo{next = next', ..}
getNext SessionCreateInfo{..} = next
extends :: forall e b proxy. Typeable e => proxy e -> (Extends SessionCreateInfo e => b) -> Maybe b
extends _ f
| Just Refl <- eqT @e @HolographicWindowAttachmentMSFT = Just f
| Just Refl <- eqT @e @GraphicsBindingEGLMNDX = Just f
| Just Refl <- eqT @e @SessionCreateInfoOverlayEXTX = Just f
| Just Refl <- eqT @e @GraphicsBindingVulkanKHR = Just f
| Just Refl <- eqT @e @GraphicsBindingOpenGLESAndroidKHR = Just f
| Just Refl <- eqT @e @GraphicsBindingD3D12KHR = Just f
| Just Refl <- eqT @e @GraphicsBindingD3D11KHR = Just f
| Just Refl <- eqT @e @GraphicsBindingOpenGLWaylandKHR = Just f
| Just Refl <- eqT @e @GraphicsBindingOpenGLXcbKHR = Just f
| Just Refl <- eqT @e @GraphicsBindingOpenGLXlibKHR = Just f
| Just Refl <- eqT @e @GraphicsBindingOpenGLWin32KHR = Just f
| otherwise = Nothing
instance (Extendss SessionCreateInfo es, PokeChain es) => ToCStruct (SessionCreateInfo es) where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SessionCreateInfo{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SESSION_CREATE_INFO)
next'' <- fmap castPtr . ContT $ withChain (next)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) next''
lift $ poke ((p `plusPtr` 16 :: Ptr SessionCreateFlags)) (createFlags)
lift $ poke ((p `plusPtr` 24 :: Ptr SystemId)) (systemId)
lift $ f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SESSION_CREATE_INFO)
pNext' <- fmap castPtr . ContT $ withZeroChain @es
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) pNext'
lift $ poke ((p `plusPtr` 24 :: Ptr SystemId)) (zero)
lift $ f
instance (Extendss SessionCreateInfo es, PeekChain es) => FromCStruct (SessionCreateInfo es) where
peekCStruct p = do
next <- peek @(Ptr ()) ((p `plusPtr` 8 :: Ptr (Ptr ())))
next' <- peekChain (castPtr next)
createFlags <- peek @SessionCreateFlags ((p `plusPtr` 16 :: Ptr SessionCreateFlags))
systemId <- peek @SystemId ((p `plusPtr` 24 :: Ptr SystemId))
pure $ SessionCreateInfo
next' createFlags systemId
instance es ~ '[] => Zero (SessionCreateInfo es) where
zero = SessionCreateInfo
()
zero
zero
| expipiplus1/vulkan | openxr/src/OpenXR/Core10/Device.hs | bsd-3-clause | 44,424 | 0 | 19 | 7,333 | 7,879 | 4,415 | 3,464 | -1 | -1 |
{-# LANGUAGE TypeOperators, TypeFamilies, TemplateHaskell #-}
module Control.Monad.Unpack (module Control.Monad.Unpack.Class, (:~>), unpack, ($~), unpack1Instance, unpackInstance, noUnpackInstance) where
import Data.Functor.Identity
import Control.Monad
import Control.Monad.Unpack.Class
import Control.Monad.Unpack.TH
import Data.ByteString (ByteString)
import Data.Primitive.Addr
import Data.Primitive.Array
import Data.Primitive.ByteArray
import qualified Data.Vector as V
import qualified Data.Vector.Primitive as P
import qualified Data.Vector.Storable as S
import Foreign.ForeignPtr
import Foreign.Ptr
import Data.Word
import Data.Int
$(unpack1Instance ''Int)
$(unpack1Instance ''Int8)
$(unpack1Instance ''Int16)
$(unpack1Instance ''Int32)
$(unpack1Instance ''Int64)
$(unpack1Instance ''Word)
$(unpack1Instance ''Word8)
$(unpack1Instance ''Word16)
$(unpack1Instance ''Word32)
$(unpack1Instance ''Word64)
$(unpack1Instance ''Char)
$(unpack1Instance ''Array)
$(unpack1Instance ''MutableArray)
$(unpack1Instance ''ByteArray)
$(unpack1Instance ''MutableByteArray)
$(unpack1Instance ''Ptr)
$(unpack1Instance ''Addr)
$(unpack1Instance ''ForeignPtr)
$(unpackInstance ''ByteString)
$(unpackInstance ''V.Vector)
$(unpackInstance ''P.Vector)
$(unpackInstance ''S.Vector)
$(unpackInstance ''V.MVector)
$(unpackInstance ''P.MVector)
$(unpackInstance ''S.MVector)
$(noUnpackInstance ''Bool)
$(noUnpackInstance ''Maybe)
$(noUnpackInstance ''Either)
$(liftM concat (mapM tupleInstance [2..10]))
instance Unpackable () where
newtype UnpackedReaderT () m a = Result {runResult :: m a}
runUnpackedReaderT func _ = runResult func
unpackedReaderT func = Result $ func ()
type (:~>) arg = UnpackedReaderT arg Identity
infixr 0 :~>
{-# INLINE ($~) #-}
($~) :: Unpackable arg => (arg :~> a) -> arg -> a
f $~ arg = runIdentity (f `runUnpackedReaderT` arg)
{-# INLINE unpack #-}
unpack :: Unpackable arg => (arg -> a) -> (arg :~> a)
unpack f = unpackedReaderT $ Identity . f | lowasser/unpack-funcs | Control/Monad/Unpack.hs | bsd-3-clause | 1,970 | 0 | 10 | 218 | 696 | 353 | 343 | 58 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-} -- Needed for the recursive type family WhereReader
module Control.Applicative.Reader (
ApplicativeReader(..), ApplicativeReaderC (..), HasApplicativeReader
) where
import Control.Applicative
import Data.Functor.Compose
import Data.Functor.Compose.Where
-- This is the same as MonadReader
class Applicative f => ApplicativeReader r f | f -> r where
ask :: f r
ask = reader id
local :: (r -> r) -> f a -> f a
reader :: (r -> a) -> f a
reader f = fmap f ask
instance ApplicativeReader r ((->) r) where
ask = id
local f m = m . f
reader = id
-- When instancing for compose, the Reader is either in the left or right branch, and to pick an
-- instance that works for this, we need a type that indicates which branch it is in, otherwise
-- the instances overlap.
-- https://wiki.haskell.org/GHC/AdvancedOverlap#Solution_1_.28using_safer_overlapping_instances.29
class Applicative f => ApplicativeReaderC flag r f | f -> r where
local' :: flag -> (r -> r) -> f a -> f a
ask' :: flag -> f r
reader' :: flag -> (r -> a) -> f a
-- TODO: should each impl be specified here?
reader' x f = fmap f (ask' x)
ask' x = reader' x id
instance (Applicative g,ApplicativeReader r f) => ApplicativeReaderC OnLeft r (Compose f g) where
local' _ f (Compose a) = Compose (local f a)
instance (Applicative f,ApplicativeReader r g) => ApplicativeReaderC OnRight r (Compose f g) where
local' _ f (Compose a) =
Compose (fmap (local f) a)
type HasApplicativeReader con re r f g flag = (WhereIs (re r) con (con f g) ~ flag, ApplicativeReaderC flag r (con f g))
instance (Applicative f,Applicative g,HasApplicativeReader Compose (->) r f g flag) => ApplicativeReader r (Compose f g) where
local = local' (undefined :: flag)
| nkpart/applicatives | src/Control/Applicative/Reader.hs | bsd-3-clause | 2,068 | 0 | 10 | 446 | 586 | 315 | 271 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoMonomorphismRestriction #-}module AI.Heukarya.Test where
import AI.Heukarya.Gene.Dynamic
import AI.Heukarya.Gene.Dynamic.Double
import AI.Heukarya.Jungle
import System.Random
import Data.Sequence as S
import Data.List as L
testGene = [toDyn "flip" (flip::(Int->Int->Int)->Int->Int->Int),toDyn "negate" (negate::Int->Int),toDyn "(+)" ((+)::Int->Int->Int),toDyn "10" (10::Int),toDyn "5" (5::Int), toDyn "(*)" ((*)::Int->Int->Int)]
evalSort = \x-> return . S.sort =<< evalJungle =<< x
testJungle1 =
genJungle (mkStdGen 10) 5 testGene "Int" 100
testCrossed11 = testJungle1 >>= \z ->
crossJungle (mkStdGen 149562) 5 z 0
testCrossed12 = testJungle1 >>= \z ->
crossJungle (mkStdGen 12) 5 z 1
testCrossed13 = testJungle1 >>= \z ->
crossJungle (mkStdGen 12) 5 z 0.5
testMutated11 = testJungle1 >>= \z ->
mutateJungle (mkStdGen 575783) 5 testGene z 0
testMutated12 = testJungle1 >>= \z ->
mutateJungle (mkStdGen 13) 5 testGene z 1
testMutated13 = testJungle1 >>= \z ->
mutateJungle (mkStdGen 13) 5 testGene z 0.5
--test1 = evalSort testJungle1 == evalSort testCrossed11 && evalSort testJungle1 == evalSort testMutated11
testJungle2 =
genJungle (mkStdGen 10) 5 testGene "Int -> Int" 100
testCrossed21 = testJungle2 >>= \z ->
crossJungle (mkStdGen 149562) 5 z 0
testCrossed22 = testJungle2 >>= \z ->
crossJungle (mkStdGen 358112) 5 z 1
testCrossed23 = testJungle2 >>= \z ->
crossJungle (mkStdGen 2154362) 5 z 0.5
testMutated21 = testJungle2 >>= \z ->
mutateJungle (mkStdGen 575783) 5 testGene z 0
testMutated22 = testJungle2 >>= \z ->
mutateJungle (mkStdGen 13) 5 testGene z 1
testMutated23 = testJungle2 >>= \z ->
mutateJungle (mkStdGen 13) 5 testGene z 0.5
--test2 = evalSort testJungle2 == evalSort testCrossed21 && evalSort testJungle2 == evalSort testMutated21
| t3476/heukarya | src/AI/Heukarya/Test.hs | bsd-3-clause | 1,843 | 0 | 11 | 287 | 615 | 335 | 280 | 38 | 1 |
{-# OPTIONS -fglasgow-exts -W #-}
-- Relating Final and Initial Typed Tagless representations
-- Based on the simplified code from the paper by
-- Jacques Carette, Oleg Kiselyov, and Chung-chieh Shan
module InFin where
{-
The language is simply-typed lambda-calculus with fixpoint,
integers, booleans and comparison.
Lam hoas_fn | App e e | Fix hoas_fn |
I Int | B Bool | Add ie1 ie2 | Mul ie1 ie2 | Leq ie1 ie2 |
IF b e-then e-else
The language is just expressive enough for the Gibonacci function
and the power function.
The compiler, the interpreter and the source and target languages
are *all* typed. The interpreter and the compiler use no tags.
There is no pattern-match failure possible: the evaluators never
get stuck.
-}
-- ======================================================================
-- Final Tagless representation
-- This class defines syntax (and its instances, semantics) of our language
-- This class is Haskell98!
class Symantics repr where
int :: Int -> repr Int -- int literal
bool :: Bool -> repr Bool -- bool literal
lam :: (repr a -> repr b) -> repr (a->b)
app :: repr (a->b) -> repr a -> repr b
fix :: (repr a -> repr a) -> repr a
add :: repr Int -> repr Int -> repr Int
mul :: repr Int -> repr Int -> repr Int
if_ :: repr Bool -> repr a -> repr a -> repr a
leq :: repr Int -> repr Int -> repr Bool
test1 () = add (int 1) (int 2)
test2 () = lam (\x -> add x x)
test3 () = lam (\x -> add (app x (int 1)) (int 2))
testgib () = lam (\x -> lam (\y ->
fix (\self -> lam (\n ->
if_ (leq n (int 0)) x
(if_ (leq n (int 1)) y
(add (app self (add n (int (-1))))
(app self (add n (int (-2))))))))))
testgib1 () = app (app (app (testgib ()) (int 1)) (int 1)) (int 5)
testgib2 () = lam (\x -> (lam (\y ->app (app (app (testgib ()) x) y) (int 5))))
testpowfix () = lam (\x ->
fix (\self -> lam (\n ->
if_ (leq n (int 0)) (int 1)
(mul x (app self (add n (int (-1))))))))
testpowfix7 () = lam (\x -> app (app (testpowfix ()) x) (int 7))
-- ------------------------------------------------------------------------
-- The interpreter
-- It is a typed, tagless interpreter: R is not a tag. The interpreter
-- never gets stuck, because it evaluates typed terms only
newtype R a = R a deriving Show
unR (R x) = x
instance Symantics R where
int x = R x
bool b = R b
lam f = R (unR . f . R)
app e1 e2 = R( (unR e1) (unR e2) )
fix f = R( fx (unR . f . R)) where fx f = f (fx f)
add e1 e2 = R( (unR e1) + (unR e2) )
mul e1 e2 = R( (unR e1) * (unR e2) )
leq e1 e2 = R( (unR e1) <= (unR e2) )
if_ be et ee = R( if (unR be) then unR et else unR ee )
compR = unR
mkrtest f = compR (f ())
rtest1 = mkrtest test1
rtest2 = mkrtest test2
rtest3 = mkrtest test3
rtestgib = mkrtest testgib
rtestgib1 = mkrtest testgib1
rtestgib2 = mkrtest testgib2
rtestpw = mkrtest testpowfix
rtestpw7 = mkrtest testpowfix7
rtestpw72 = mkrtest (\() -> app (testpowfix7 ()) (int 2))
{-
The expression "R (unR . f . R)" _looks_ like tag introduction and
elimination.
But the function unR is *total*. There is no run-time error
is possible at all -- and this fact is fully apparent to the
compiler.
-}
-- ------------------------------------------------------------------------
-- Another interpreter: it interprets each term to give its size
-- (the number of constructors)
-- It is a typed, tagless interpreter: L is not a tag. The interpreter
-- never gets stuck, because it evaluates typed terms only.
-- This interpreter is also total: it determines the size of the term
-- even if the term itself is divergent.
newtype L a = L Int deriving Show
unL (L x) = x
instance Symantics L where
int _ = L 1
bool _ = L 1
lam f = L( unL (f (L 0)) + 1 )
app e1 e2 = L( unL e1 + unL e2 + 1 )
fix f = L( unL (f (L 0)) + 1 )
add e1 e2 = L( unL e1 + unL e2 + 1 )
mul e1 e2 = L( unL e1 + unL e2 + 1 )
leq e1 e2 = L( unL e1 + unL e2 + 1 )
if_ be et ee = L( unL be + unL et + unL ee + 1 )
compL = unL
ltest1 = compL . test1 $ ()
ltest2 = compL . test2 $ ()
ltest3 = compL . test3 $ ()
ltestgib = compL . testgib $ ()
ltestgib1 = compL . testgib1 $ ()
ltestgib2 = compL . testgib2 $ ()
ltestpw = compL . testpowfix $ ()
ltestpw7 = compL . testpowfix7 $ ()
ltestpw72 = compL (app (testpowfix7 ()) (int 2))
-- ======================================================================
-- Initial Tagless representation, using GADT with HOAS
-- The HVar operation is used only during evaluation
-- it corresponds to a CSP in MetaOCaml or Lift in Xi, Chen and Chen (POPL2003)
-- The parameter h is the `hypothetical environment'
data IR h t where
Var :: h t -> IR h t
INT :: Int -> IR h Int
BOOL :: Bool -> IR h Bool
Lam :: (IR h t1 -> IR h t2) -> IR h (t1->t2)
App :: IR h (t1->t2) -> IR h t1 -> IR h t2
Fix :: (IR h t -> IR h t) -> IR h t
Add :: IR h Int -> IR h Int -> IR h Int
Mul :: IR h Int -> IR h Int -> IR h Int
Leq :: IR h Int -> IR h Int -> IR h Bool
IF :: IR h Bool -> IR h t -> IR h t -> IR h t
-- deriving instance (Show (h t)) => Show (IR h t)
-- An evaluator for IR: the virtual machine
-- It is total (modulo potential non-termination in fix)
-- No exceptions are to be raised, and no pattern-match failure
-- may occur. All pattern-matching is _syntactically_, patently complete.
evalI :: IR R t -> t
evalI (INT n) = n
evalI (BOOL n) = n
evalI (Add e1 e2) = evalI e1 + evalI e2
evalI (Mul e1 e2) = evalI e1 * evalI e2
evalI (Leq e1 e2) = evalI e1 <= evalI e2
evalI (IF be et ee) = if (evalI be) then evalI et else evalI ee
evalI (Var v) = unR v
evalI (Lam b) = \x -> evalI (b . Var . R $ x)
evalI (App e1 e2) = (evalI e1) (evalI e2)
evalI (Fix f) = evalI (f (Fix f))
-- ======================================================================
-- Relating Initial and Final Tagless representations
-- Conversion from the Final to the Initial representations
instance Symantics (IR h) where
int = INT
bool = BOOL
lam = Lam
app = App
fix = Fix
add = Add
mul = Mul
leq = Leq
if_ = IF
compI :: IR h t -> IR h t
compI = id
itest1 = compI . test1 $ ()
itest1r = evalI . test1 $ () -- 3
itest2 = compI . test2 $ ()
itest2r = evalI . test2 $ ()
itest3 = compI . test3 $ ()
itest3r = (evalI . test3 $ ()) (+ 5) -- 8
itestgib1 = compI . testgib1 $ ()
itestgib1r = evalI . testgib1 $ () -- 8, or gib 5
itestpw = compI . testpowfix $ ()
itestpw7 = compI . testpowfix7 $ ()
itestpw72 = evalI (app (testpowfix7 ()) (int 2)) -- 128
-- Converter from the Initial to the Final representations
itf :: Symantics repr => IR repr t -> repr t
itf (INT n) = int n
itf (BOOL n) = bool n
itf (Add e1 e2) = add (itf e1) (itf e2)
itf (Mul e1 e2) = mul (itf e1) (itf e2)
itf (Leq e1 e2) = leq (itf e1) (itf e2)
itf (IF be et ee) = if_ (itf be) (itf et) (itf ee)
itf (Var v) = v
itf (Lam b) = lam(\x -> itf (b (Var x))) -- should not give any pattern-match
itf (App e1 e2) = app (itf e1) (itf e2) -- errors
itf (Fix b) = fix(\x -> itf (b (Var x)))
-- Verifying Initial -> Final -> Initial
-- ifi :: IR (IR h) t -> IR h t
ifi ir = compI . itf $ ir
ifi_12i = (evalI (Lam (\x -> App x (INT 1)))) (+6) -- 7
ifi_12r = (evalI (ifi (Lam (\x -> App x (INT 1))))) (+6) -- 7
ifi_gib1i = evalI (testgib1 ()) -- 8
ifi_gib1r = evalI (ifi (testgib1 ())) -- 8
-- Verifying Final -> Initial -> Final
-- fif :: (Symantics h) => IR h t -> h t
fif fr = itf . compI $ fr
fif_gib1i = compR (testgib1 ()) -- 8
fif_gib1r = compR (fif (testgib1 ())) -- 8
-- Using a different final interpreter
fif_gibl1i = compL (testgib1 ()) -- 23
fif_gibl1r = compL (fif (testgib1 ())) -- 23
| rosenbergdm/language-r | src/Language/R/sketches/InFin.hs | bsd-3-clause | 7,956 | 0 | 29 | 2,138 | 3,051 | 1,553 | 1,498 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Data.ByteString.Lazy.ShowDouble(showDouble) where
import Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Internal as B
import qualified Data.ByteString.Lazy.Char8 as L
import Foreign
import Foreign.C.Types
------------------------------------------------------------------------
--
-- show a Double into a lazy bytestring
--
showDouble :: Double -> ByteString
showDouble d = L.fromChunks . return . unsafePerformIO . B.createAndTrim lim $ \p ->
B.useAsCString fmt $ \cfmt -> do
n <- c_printf_double (castPtr p) (fromIntegral lim) cfmt (realToFrac d)
return (min lim (fromIntegral n)) -- snprintf might truncate
where
lim = 100 -- n.b.
fmt = B.pack "%f"
foreign import ccall unsafe "static stdio.h snprintf"
c_printf_double :: Ptr CChar -> CSize -> Ptr CChar -> CDouble -> IO CInt | runebak/wcc | Source/Data/ByteString/Lazy/ShowDouble.hs | bsd-3-clause | 948 | 0 | 15 | 165 | 238 | 135 | 103 | 17 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.Core31.Types
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- This module corresponds to table 2.2 in section 2.3 (Command Syntax) of the
-- OpenGL 3.1 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.Core31.Types (
GLboolean,
GLbyte,
GLubyte,
GLchar,
GLshort,
GLushort,
GLint,
GLuint,
GLsizei,
GLenum,
GLintptr,
GLsizeiptr,
GLbitfield,
GLhalf,
GLfloat,
GLclampf,
GLdouble,
GLclampd
) where
import Graphics.Rendering.OpenGL.Raw.Types
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/Core31/Types.hs | bsd-3-clause | 827 | 0 | 4 | 155 | 88 | 65 | 23 | 20 | 0 |
--
-- TensorUtilities.hs
--
-- Functions to make defining tensor expressions easier.
--
-- Gregory Wright, 30 August 2011
--
module Math.Symbolic.Wheeler.TensorUtilities where
import System.IO.Unsafe
import Math.Symbolic.Wheeler.Common
import {-# SOURCE #-} Math.Symbolic.Wheeler.Expr
import Math.Symbolic.Wheeler.Symbol
import Math.Symbolic.Wheeler.Tensor
import Math.Symbolic.Wheeler.UniqueID
mkIndex :: Manifold -> String -> VarIndex
mkIndex m n = Contravariant $ Abstract $ Index { indexManifold = m
, indexName = n
, indexTeXName = n
, indexType = Regular
, indexIsDummy = False }
mkIndex_ :: Manifold -> String -> String -> VarIndex
mkIndex_ m n texn = Contravariant $ Abstract $ Index { indexManifold = m
, indexName = n
, indexTeXName = texn
, indexType = Regular
, indexIsDummy = False}
mkPatternIndex :: String -> VarIndex
mkPatternIndex n = Contravariant $ Abstract $ Index { indexManifold = emptyManifold
, indexName = n
, indexTeXName = n
, indexType = Pattern
, indexIsDummy = False}
emptyManifold :: Manifold
emptyManifold = Manifold { manifoldType = Pattern
, manifoldName = ""
, manifoldTeXName = ""
, manifoldDimension = 0
, manifoldDimensionDelta = Nothing
, metricity = NoMetric }
getIndex :: VarIndex -> Index
getIndex (Covariant (Abstract s)) = s
getIndex (Covariant (Component _)) = error "getIndex called on non-abstract index"
getIndex (Contravariant (Abstract s)) = s
getIndex (Contravariant (Component _)) = error "getIndex called on non-abstract index"
-- uniqueDummy produces a contravariant index with a
-- unique name and marked as an explicit dummy.
--
uniqueDummy :: Manifold -> IO VarIndex
uniqueDummy m = do
n <- nextDummy
return $ Contravariant $ Abstract $ Index { indexManifold = m
, indexName = show n
, indexTeXName = show n
, indexType = Regular
, indexIsDummy = True }
mkTestDummy :: Manifold -> String -> VarIndex
mkTestDummy m n = Contravariant $ Abstract $ Index { indexManifold = m
, indexName = n
, indexTeXName = n
, indexType = Regular
, indexIsDummy = True }
isCovariant :: VarIndex -> Bool
isCovariant (Covariant _) = True
isCovariant _ = False
isContravariant :: VarIndex -> Bool
isContravariant (Contravariant _) = True
isContravariant _ = False
toCovariant :: VarIndex -> VarIndex
toCovariant (Contravariant i) = Covariant i
toCovariant (Covariant i) = Covariant i
toContravariant :: VarIndex -> VarIndex
toContravariant (Contravariant i) = Contravariant i
toContravariant (Covariant i) = Contravariant i
isDummy :: VarIndex -> Bool
isDummy (Covariant (Abstract i)) = indexIsDummy i
isDummy (Contravariant (Abstract i)) = indexIsDummy i
isDummy _ = False
-- is a tensor a metric, Kronecker delta or Levi-Civita symbol?
--
isMetric :: Expr -> Bool
isMetric (Symbol (Tensor t)) = tensorClass t == Metric
isMetric _ = False
isKroneckerDelta :: Expr -> Bool
isKroneckerDelta (Symbol (Tensor t)) = tensorClass t == KroneckerDelta
isKroneckerDelta _ = False
isLeviCivita :: Expr -> Bool
isLeviCivita (Symbol (Tensor t)) = tensorClass t == LeviCivita
isLeviCivita _ = False
tensorIndices :: Expr -> [ VarIndex ]
tensorIndices (Symbol (Tensor t)) = slots t
tensorIndices _ = []
tensorManifold :: Expr -> Manifold
tensorManifold (Symbol (Tensor t)) = manifold t
tensorManifold _ = error "tensorManifold applied to non-tensor expression"
-- Take a tensor and replace its indices by dummies
--
dummyize :: Expr -> Expr
dummyize (Symbol (Tensor t)) = Symbol $ Tensor $ t { slots = t' }
where
m = manifold t
t' = map (\i -> if isContravariant i
then unsafePerformIO $ uniqueDummy m
else - (unsafePerformIO $ uniqueDummy m)) $ slots t
dummyize e = e
| gwright83/Wheeler | src/Math/Symbolic/Wheeler/TensorUtilities.hs | bsd-3-clause | 5,026 | 0 | 15 | 2,003 | 1,086 | 594 | 492 | 89 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module SecondFront.Workers.Data where
import qualified Data.ByteString as B
import Data.ByteString.Char8 (pack)
import SecondTransfer(Headers)
bad404ResponseData :: B.ByteString
bad404ResponseData = "404: SecondFront: Didn't find that"
bad501ResponseData :: B.ByteString
bad501ResponseData = "501: You are seeing this instead of some non-implemented, more specific slap"
-- TODO: It could be a really bad idea to give the server indication always....
-- We may need a way to control these ancilliary headers somewhere...
serverPair :: (B.ByteString, B.ByteString)
serverPair = ("server", "second-front--0.1")
standardErrorHeaders :: Headers
standardErrorHeaders = [
("content-type", "text/plain")
,serverPair
]
bad404ResponseHeaders :: Headers
bad404ResponseHeaders = [
(":status", "404")
,serverPair
,("content-length", ( pack . show $ B.length bad404ResponseData))
]++ standardErrorHeaders
bad501ResponseHeaders :: Headers
bad501ResponseHeaders = [
(":status", "501")
,serverPair
,("content-length", ( pack . show $ B.length bad501ResponseData ))
]++ standardErrorHeaders
good200ResponseHeaders :: B.ByteString -> Int -> Headers
good200ResponseHeaders mime_type content_length = [
(":status", "200")
,("content-length", ( pack . show $ content_length ) )
,serverPair
,("content-type", mime_type)
] | alcidesv/second-front | hs-src/SecondFront/Workers/Data.hs | bsd-3-clause | 1,427 | 0 | 11 | 247 | 277 | 169 | 108 | 33 | 1 |
module Butters.Ast where
data Value =
BList [Value]
| Constructor String
| TypeVar Char
| App Value [Value]
| Name String
deriving (Show, Eq)
data TopLevelDefinition =
DataDef String [Char] [Value]
| SubsumptionDef String String [(Value, Value)]
| ValueDef Value Value Value
deriving (Show, Eq)
| mjgpy3/butters | src/Butters/Ast.hs | bsd-3-clause | 317 | 0 | 8 | 67 | 111 | 65 | 46 | 13 | 0 |
{-| Module : PhaseResolveOperators
License : GPL
Maintainer : helium@cs.uu.nl
Stability : experimental
Portability : portable
-}
module Helium.Main.PhaseResolveOperators(phaseResolveOperators) where
import Helium.Main.CompileUtils
import Helium.Parser.ResolveOperators(resolveOperators, operatorsFromModule, ResolveError)
import qualified Helium.Syntax.UHA_Pretty as PP(sem_Module,wrap_Module,Inh_Module(..),text_Syn_Module)
import qualified Data.Map as M
phaseResolveOperators ::
Module -> [ImportEnvironment] -> [Option] ->
Phase ResolveError Module
phaseResolveOperators moduleBeforeResolve importEnvs options = do
enterNewPhase "Resolving operators" options
let importOperatorTable =
M.unions (operatorsFromModule moduleBeforeResolve : map operatorTable importEnvs)
(module_, resolveErrors) =
resolveOperators importOperatorTable moduleBeforeResolve
case resolveErrors of
_:_ ->
return (Left resolveErrors)
[] ->
do when (DumpUHA `elem` options) $
print $ PP.text_Syn_Module $ PP.wrap_Module (PP.sem_Module module_) PP.Inh_Module
return (Right module_)
| roberth/uu-helium | src/Helium/Main/PhaseResolveOperators.hs | gpl-3.0 | 1,278 | 0 | 17 | 321 | 257 | 139 | 118 | 21 | 2 |
{- |
Module : $Header$
Description : Static analysis of CspCASL
Copyright : (c) Andy Gimblett, Liam O'Reilly, Markus Roggenbach,
Swansea University 2008, C. Maeder, DFKI 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
Static analysis of CSP-CASL specifications, following "Tool Support
for CSP-CASL", MPhil thesis by Andy Gimblett, 2008.
<http://www.cs.swan.ac.uk/~csandy/mphil/>
-}
module CspCASL.StatAnaCSP where
import CASL.AS_Basic_CASL
import CASL.Fold
import CASL.MixfixParser
import CASL.Quantification
import CASL.Sign
import CASL.StaticAna
import CASL.ToDoc ()
import Common.AS_Annotation
import Common.Result
import Common.GlobalAnnotations
import Common.Id
import Common.Lib.State
import Common.ExtSign
import qualified Common.Lib.MapSet as MapSet
import CspCASL.AS_CspCASL
import CspCASL.AS_CspCASL_Process
import qualified CspCASL.LocalTop as LocalTop
import CspCASL.Print_CspCASL
import CspCASL.SignCSP
import CspCASL.Symbol
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Maybe
import Control.Monad
type CspBasicSpec = BASIC_SPEC CspBasicExt () CspSen
{- | The first element of the returned pair (CspBasicSpec) is the same
as the inputted version just with some very minor optimisations -
none in our case, but for CASL - brackets are otimized. This all
that happens, the mixfixed terms are still mixed fixed terms in
the returned version. -}
basicAnalysisCspCASL :: (CspBasicSpec, CspCASLSign, GlobalAnnos)
-> Result (CspBasicSpec, ExtSign CspCASLSign CspSymbol, [Named CspCASLSen])
basicAnalysisCspCASL inp@(_, insig, _) = do
(bs, ExtSign sig syms, sens) <- basicAnaAux inp
-- check for local top elements in the subsort relation
appendDiags $ LocalTop.checkLocalTops $ sortRel sig
let ext = extendedInfo sig
return (bs, ExtSign sig $ Set.unions
$ Set.map caslToCspSymbol syms
: toSymbolSet (diffCspSig ext $ extendedInfo insig), sens)
basicAnaAux :: (CspBasicSpec, CspCASLSign, GlobalAnnos)
-> Result (CspBasicSpec, ExtSign CspCASLSign Symbol, [Named CspCASLSen])
basicAnaAux =
basicAnalysis (const return) ana_BASIC_CSP (const return) emptyMix
ana_BASIC_CSP :: Ana CspBasicExt CspBasicExt () CspSen CspSign
ana_BASIC_CSP mix bs = do
let caslMix = emptyMix
{ mixRules = mixRules mix }
case bs of
Channels cs _ -> mapM_ (anaChanDecl . item) cs
ProcItems ps _ -> mapM_ (anaProcItem caslMix) ps
return bs
-- Static analysis of channel declarations
-- | Statically analyse a CspCASL channel declaration.
anaChanDecl :: CHANNEL_DECL -> State CspCASLSign ()
anaChanDecl (ChannelDecl chanNames chanSort) = do
checkSorts [chanSort] -- check channel sort is known
sig <- get
let ext = extendedInfo sig
oldChanMap = chans ext
newChanMap <- foldM (anaChannelName chanSort) oldChanMap chanNames
sig2 <- get
put sig2 { extendedInfo = ext { chans = newChanMap }}
-- | Statically analyse a CspCASL channel name.
anaChannelName :: SORT -> ChanNameMap -> CHANNEL_NAME
-> State CspCASLSign ChanNameMap
anaChannelName s m chanName = do
sig <- get
if Set.member chanName (sortSet sig)
then do
let err = "channel name already in use as a sort name"
addDiags [mkDiag Error err chanName]
return m
else do
when (MapSet.member chanName s m) $
addDiags [mkDiag Warning "redeclared channel" chanName]
return $ MapSet.insert chanName s m
-- Static analysis of process items
-- | Statically analyse a CspCASL process item.
anaProcItem :: Mix b s () () -> Annoted PROC_ITEM -> State CspCASLSign ()
anaProcItem mix annotedProcItem = case item annotedProcItem of
Proc_Decl name argSorts alpha -> anaProcDecl name argSorts alpha
Proc_Defn name args alpha procTerm -> do
let vs = flatVAR_DECLs args
argSorts = map snd vs
alpha' = case alpha of
ProcAlphabet alpha'' -> Set.fromList alpha''
procProfile = ProcProfile argSorts alpha'
pn = ParmProcname (FQ_PROCESS_NAME name procProfile) $ map fst vs
anaProcDecl name argSorts alpha
anaProcEq mix annotedProcItem pn procTerm
Proc_Eq parmProcName procTerm ->
anaProcEq mix annotedProcItem parmProcName procTerm
-- Static analysis of process declarations
-- | Statically analyse a CspCASL process declaration.
anaProcDecl :: PROCESS_NAME -> PROC_ARGS -> PROC_ALPHABET
-> State CspCASLSign ()
anaProcDecl name argSorts comms = do
sig <- get
let ext = extendedInfo sig
oldProcDecls = procSet ext
newProcDecls <- do
-- new process declation
profile <- anaProcAlphabet argSorts comms
-- we no longer add (channel and) proc symbols to the CASL signature
if isNameInProcNameMap name profile oldProcDecls
-- Check the name (with profile) is new (for warning only)
then -- name with profile already in signature
do let warn = "process name redeclared with same profile '" ++
show (printProcProfile profile) ++ "':"
addDiags [mkDiag Warning warn name]
return oldProcDecls
else {- New name with profile - add the name to the signature in the
state -}
return $ addProcNameToProcNameMap name profile oldProcDecls
sig2 <- get
put sig2 { extendedInfo = ext {procSet = newProcDecls }}
-- Static analysis of process equations
{- | Find a profile for a process name. Either the profile is given via a parsed
fully qualified process name, in which case we check everything is valid and
the process name with the profile is known. Or its a plain process name where
we must deduce a unique profile if possible. We also know how many variables
/ parameters the process name has. -}
findProfileForProcName :: FQ_PROCESS_NAME -> Int -> ProcNameMap ->
State CspCASLSign (Maybe ProcProfile)
findProfileForProcName pn numParams procNameMap =
case pn of
FQ_PROCESS_NAME pn' (ProcProfile argSorts comms) -> do
procProfile <- anaProcAlphabet argSorts $ ProcAlphabet $ Set.toList comms
if MapSet.member pn' procProfile procNameMap
then return $ Just procProfile
else do
addDiags [mkDiag Error
"Fully qualified process name not in signature" pn]
return Nothing
PROCESS_NAME pn' ->
let resProfile = getUniqueProfileInProcNameMap pn' numParams procNameMap
in case resultToMaybe resProfile of
Nothing ->
do addDiags $ diags resProfile
return Nothing
Just profile' ->
return $ Just profile'
{- | Analyse a process name an return a fully qualified one if possible. We also
know how many variables / parameters the process name has. -}
anaProcName :: FQ_PROCESS_NAME -> Int
-> State CspCASLSign (Maybe FQ_PROCESS_NAME)
anaProcName pn numParams = do
sig <- get
let ext = extendedInfo sig
procDecls = procSet ext
simpPn = procNameToSimpProcName pn
maybeProf <- findProfileForProcName pn numParams procDecls
case maybeProf of
Nothing -> return Nothing
Just procProfile ->
-- We now construct the real fully qualified process name
return $ Just $ FQ_PROCESS_NAME simpPn procProfile
-- | Statically analyse a CspCASL process equation.
anaProcEq :: Mix b s () () -> Annoted a -> PARM_PROCNAME -> PROCESS
-> State CspCASLSign ()
anaProcEq mix a (ParmProcname pn vs) proc =
{- the 'annoted a' contains the annotation of the process equation. We do not
care what the underlying item is in the annotation (but it probably will be
the proc eq) -}
do
maybeFqPn <- anaProcName pn (length vs)
case maybeFqPn of
-- Only analyse a process if its name and profile is known
Nothing -> return ()
Just fqPn ->
case fqPn of
PROCESS_NAME _ ->
error "CspCasl.StatAnaCSP.anaProcEq: Impossible case"
FQ_PROCESS_NAME _ (ProcProfile argSorts commAlpha) -> do
gVars <- anaProcVars pn
argSorts vs {- compute global
vars Change a procVarList to a FQProcVarList We do
not care about the range as we are building fully
qualified variables and they have already been
checked to be ok. -}
let mkFQProcVar (v, s) = Qual_var v s nullRange
fqGVars = map mkFQProcVar gVars
(termAlpha, fqProc) <-
anaProcTerm mix proc (Map.fromList gVars) Map.empty
checkCommAlphaSub termAlpha commAlpha proc "process equation"
{- put CspCASL Sentences back in to the state with new sentence
BUG - What should the constituent alphabet be for this
process? probably the same as the inner one! -}
addSentences [makeNamedSen $
{- We take the annotated item and replace the
inner item, thus preserving the annotations. We
then take this annotated sentence and make it a
named sentence in accordance to the (if
existing) name in the annotations. -}
a {item = ExtFORMULA
$ ProcessEq fqPn fqGVars commAlpha fqProc}]
-- | Statically analyse a CspCASL process equation's global variable names.
anaProcVars :: FQ_PROCESS_NAME -> [SORT] -> [VAR] ->
State CspCASLSign ProcVarList
anaProcVars pn ss vs =
let msg str = addDiags [mkDiag Error ("process name applied to " ++ str) pn]
>> return []
in fmap reverse $ case compare (length ss) $ length vs of
LT -> msg "too many arguments"
GT -> msg "not enough arguments"
EQ -> foldM anaProcVar [] (zip vs ss)
-- | Statically analyse a CspCASL process-global variable name.
anaProcVar :: ProcVarList -> (VAR, SORT) -> State CspCASLSign ProcVarList
anaProcVar old (v, s) =
if v `elem` map fst old
then do
addDiags [mkDiag Error "Process argument declared more than once" v]
return old
else return ((v, s) : old)
-- Static analysis of process terms
{- BUG in fucntion below
not returing FQProcesses
Statically analyse a CspCASL process term.
The process that is returned is a fully qualified process. -}
anaProcTerm :: Mix b s () () -> PROCESS -> ProcVarMap -> ProcVarMap
-> State CspCASLSign (CommAlpha, PROCESS)
anaProcTerm mix proc gVars lVars = case proc of
NamedProcess name args r ->
do addDiags [mkDiag Debug "Named process" proc]
(fqName, al, fqArgs) <-
anaNamedProc mix proc name args (lVars `Map.union` gVars)
let fqProc = FQProcess (NamedProcess fqName fqArgs r) al r
return (al, fqProc)
Skip r ->
do addDiags [mkDiag Debug "Skip" proc]
let fqProc = FQProcess (Skip r) Set.empty r
return (Set.empty, fqProc)
Stop r ->
do addDiags [mkDiag Debug "Stop" proc]
let fqProc = FQProcess (Stop r) Set.empty r
return (Set.empty, fqProc)
Div r ->
do addDiags [mkDiag Debug "Div" proc]
let fqProc = FQProcess (Div r) Set.empty r
return (Set.empty, fqProc)
Run es r ->
do addDiags [mkDiag Debug "Run" proc]
(comms, fqEs) <- anaEventSet es
let fqProc = FQProcess (Run fqEs r) comms r
return (comms, fqProc)
Chaos es r ->
do addDiags [mkDiag Debug "Chaos" proc]
(comms, fqEs) <- anaEventSet es
let fqProc = FQProcess (Chaos fqEs r) comms r
return (comms, fqProc)
PrefixProcess e p r ->
do addDiags [mkDiag Debug "Prefix" proc]
(evComms, rcvMap, fqEvent) <-
anaEvent mix e (lVars `Map.union` gVars)
(comms, pFQTerm) <-
anaProcTerm mix p gVars (rcvMap `Map.union` lVars)
let newAlpha = comms `Set.union` evComms
fqProc = FQProcess (PrefixProcess fqEvent pFQTerm r) newAlpha r
return (newAlpha, fqProc)
Sequential p q r ->
do addDiags [mkDiag Debug "Sequential" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(qComms, qFQTerm) <- anaProcTerm mix q gVars Map.empty
let newAlpha = pComms `Set.union` qComms
fqProc = FQProcess (Sequential pFQTerm qFQTerm r) newAlpha r
return (newAlpha, fqProc)
InternalChoice p q r ->
do addDiags [mkDiag Debug "InternalChoice" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(qComms, qFQTerm) <- anaProcTerm mix q gVars lVars
let newAlpha = pComms `Set.union` qComms
fqProc = FQProcess (InternalChoice pFQTerm qFQTerm r) newAlpha r
return (newAlpha, fqProc)
ExternalChoice p q r ->
do addDiags [mkDiag Debug "ExternalChoice" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(qComms, qFQTerm) <- anaProcTerm mix q gVars lVars
let newAlpha = pComms `Set.union` qComms
fqProc = FQProcess (ExternalChoice pFQTerm qFQTerm r) newAlpha r
return (newAlpha, fqProc)
Interleaving p q r ->
do addDiags [mkDiag Debug "Interleaving" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(qComms, qFQTerm) <- anaProcTerm mix q gVars lVars
let newAlpha = pComms `Set.union` qComms
fqProc = FQProcess (Interleaving pFQTerm qFQTerm r) newAlpha r
return (newAlpha, fqProc)
SynchronousParallel p q r ->
do addDiags [mkDiag Debug "Synchronous" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(qComms, qFQTerm) <- anaProcTerm mix q gVars lVars
let newAlpha = pComms `Set.union` qComms
fqProc = FQProcess (SynchronousParallel pFQTerm
qFQTerm r) newAlpha r
return (newAlpha, fqProc)
GeneralisedParallel p es q r ->
do addDiags [mkDiag Debug "Generalised parallel" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(synComms, fqEs) <- anaEventSet es
(qComms, qFQTerm) <- anaProcTerm mix q gVars lVars
let newAlpha = Set.unions [pComms, qComms, synComms]
fqProc = FQProcess (GeneralisedParallel pFQTerm fqEs qFQTerm r)
newAlpha r
return (newAlpha, fqProc)
AlphabetisedParallel p esp esq q r ->
do addDiags [mkDiag Debug "Alphabetised parallel" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(pSynComms, fqEsp) <- anaEventSet esp
checkCommAlphaSub pSynComms pComms proc "alphabetised parallel, left"
(qSynComms, fqEsq) <- anaEventSet esq
(qComms, qFQTerm) <- anaProcTerm mix q gVars lVars
checkCommAlphaSub qSynComms qComms proc
"alphabetised parallel, right"
let newAlpha = pComms `Set.union` qComms
fqProc = FQProcess (AlphabetisedParallel pFQTerm fqEsp fqEsq
qFQTerm r) newAlpha r
return (newAlpha, fqProc)
Hiding p es r ->
do addDiags [mkDiag Debug "Hiding" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(hidComms, fqEs) <- anaEventSet es
return (pComms `Set.union` hidComms
, FQProcess (Hiding pFQTerm fqEs r)
(pComms `Set.union` hidComms) r)
RenamingProcess p renaming r ->
do addDiags [mkDiag Debug "Renaming" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(renAlpha, fqRenaming) <- anaRenaming renaming
let newAlpha = pComms `Set.union` renAlpha
fqProc = FQProcess (RenamingProcess pFQTerm fqRenaming r)
(pComms `Set.union` renAlpha) r
return (newAlpha, fqProc)
ConditionalProcess f p q r ->
do addDiags [mkDiag Debug "Conditional" proc]
(pComms, pFQTerm) <- anaProcTerm mix p gVars lVars
(qComms, qFQTerm) <- anaProcTerm mix q gVars lVars
-- mfs is the fully qualified formula version of f
mfs <- anaFormulaCspCASL mix (gVars `Map.union` lVars) f
let fFQ = fromMaybe f mfs
fComms = maybe Set.empty formulaComms mfs
newAlpha = Set.unions [pComms, qComms, fComms]
fqProc = FQProcess (ConditionalProcess fFQ pFQTerm qFQTerm r)
newAlpha r
return (newAlpha, fqProc)
FQProcess {} ->
error "CspCASL.StatAnaCSP.anaProcTerm: Unexpected FQProcess"
{- | Statically analyse a CspCASL "named process" term. Return the
permitted alphabet of the process and also a list of the fully qualified
version of the inputted terms.
BUG !!! the FQ_PROCESS_NAME may actually need to be a simple process name -}
anaNamedProc :: Mix b s () () -> PROCESS -> FQ_PROCESS_NAME -> [TERM ()]
-> ProcVarMap -> State CspCASLSign (FQ_PROCESS_NAME, CommAlpha, [TERM ()])
anaNamedProc mix proc pn terms procVars = do
maybeFqPn <- anaProcName pn (length terms)
case maybeFqPn of
Nothing ->
{- Return the empty alphabet and the original
terms. There is an error in the spec. -}
return (pn, Set.empty, terms)
Just fqPn ->
case fqPn of
PROCESS_NAME _ ->
error "CspCasl.StatAnaCSP.anaNamedProc: Impossible case"
FQ_PROCESS_NAME _ (ProcProfile argSorts permAlpha) ->
if length terms == length argSorts
then do
fqTerms <-
mapM (anaNamedProcTerm mix procVars) (zip terms argSorts)
{- Return the permitted alphabet of the process and
the fully qualifed terms -}
return (fqPn, permAlpha, fqTerms)
else do
let err = "Wrong number of arguments in named process"
addDiags [mkDiag Error err proc]
{- Return the empty alphabet and the original
terms. There is an error in the spec. -}
return (pn, Set.empty, terms)
{- | Statically analysis a CASL term occurring in a CspCASL "named
process" term. -}
anaNamedProcTerm :: Mix b s () () -> ProcVarMap -> (TERM (), SORT)
-> State CspCASLSign (TERM ())
anaNamedProcTerm mix pm (t, expSort) = do
mt <- anaTermCspCASL mix pm t
sig <- get
case mt of
Nothing -> return t {- CASL term analysis failed. Use old term
as the fully qualified term, there is a
error in the spec anyway. -}
Just at -> do
let Result ds at' = ccTermCast at expSort sig -- attempt cast;
addDiags ds
case at' of
Nothing -> {- Use old term as the fully
qualified term, there is a error
in the spec anyway. -}
return t
Just at'' -> return at'' {- Use the fully
qualified
(possibly cast)
term -}
-- Static analysis of event sets and communication types
{- | Statically analyse a CspCASL event set. Returns the alphabet of
the event set and a fully qualified version of the event set. -}
anaEventSet :: EVENT_SET -> State CspCASLSign (CommAlpha, EVENT_SET)
anaEventSet eventSet =
case eventSet of
EventSet es r ->
do sig <- get
-- fqEsElems is built the reversed order for efficiency.
(comms, fqEsElems) <- foldM (anaCommType sig)
(Set.empty, []) es
vds <- gets envDiags
put sig { envDiags = vds }
-- reverse the list inside the event set
return (comms, EventSet (reverse fqEsElems) r)
{- | Statically analyse a proc alphabet (i.e., a list of channel and sort
identifiers) to yeild a list of sorts and typed channel names. We also check
the parameter sorts and actually construct a process profile. -}
anaProcAlphabet :: PROC_ARGS -> PROC_ALPHABET ->
State CspCASLSign ProcProfile
anaProcAlphabet argSorts (ProcAlphabet commTypes) = do
sig <- get
checkSorts argSorts {- check argument sorts are known build alphabet: set of
CommType values. We do not need the fully qualfied commTypes that are
returned (these area used for analysing Event Sets) -}
(alpha, _ ) <- foldM (anaCommType sig) (Set.empty, []) commTypes
let profile = reduceProcProfile (sortRel sig) (ProcProfile argSorts alpha)
return profile
{- | Statically analyse a CspCASL communication type. Returns the
extended alphabet and the extended list of fully qualified event
set elements - [CommType]. -}
anaCommType :: CspCASLSign -> (CommAlpha, [CommType]) -> CommType ->
State CspCASLSign (CommAlpha, [CommType])
anaCommType sig (alpha, fqEsElems) ct =
let res = return (Set.insert ct alpha, ct : fqEsElems)
old = return (alpha, fqEsElems)
getChSrts ch = Set.toList $ MapSet.lookup ch $ chans
$ extendedInfo sig
chRes ch rs = let tcs = map (CommTypeChan . TypedChanName ch) rs
in return (Set.union alpha $ Set.fromList tcs, tcs ++ fqEsElems)
in case ct of
CommTypeSort sid -> if Set.member sid (sortSet sig) then res else
case getChSrts sid of
[] -> do
addDiags [mkDiag Error "unknown sort or channel" sid]
old
cs -> chRes sid cs
CommTypeChan (TypedChanName ch sid) ->
if Set.member sid (sortSet sig) then
case getChSrts ch of
[] -> do
addDiags [mkDiag Error "unknown channel" ch]
old
ts -> case filter (\ s -> s == sid || Set.member sid
(subsortsOf s sig) || Set.member s (subsortsOf sid sig)) ts of
[] -> do
let mess = "found no suitably sort '"
++ shows sid "' for channel"
addDiags [mkDiag Error mess ch]
old
rs -> chRes ch rs
else do
let mess = "unknow sort '" ++ shows sid "' for channel"
addDiags [mkDiag Error mess ch]
old
-- Static analysis of events
{- | Statically analyse a CspCASL event. Returns a constituent
communication alphabet of the event, mapping for any new
locally bound variables and a fully qualified version of the event. -}
anaEvent :: Mix b s () () -> EVENT -> ProcVarMap
-> State CspCASLSign (CommAlpha, ProcVarMap, EVENT)
anaEvent mix e vars =
case e of
TermEvent t range ->
do addDiags [mkDiag Debug "Term event" e]
(alpha, newVars, fqTerm) <- anaTermEvent mix t vars
let fqEvent = FQTermEvent fqTerm range
return (alpha, newVars, fqEvent)
InternalPrefixChoice v s range ->
do addDiags [mkDiag Debug "Internal prefix event" e]
(alpha, newVars, fqVar) <- anaPrefixChoice v s
let fqEvent = FQInternalPrefixChoice fqVar range
return (alpha, newVars, fqEvent)
ExternalPrefixChoice v s range ->
do addDiags [mkDiag Debug "External prefix event" e]
(alpha, newVars, fqVar) <- anaPrefixChoice v s
let fqEvent = FQExternalPrefixChoice fqVar range
return (alpha, newVars, fqEvent)
ChanSend c t range ->
do addDiags [mkDiag Debug "Channel send event" e]
{- mfqChan is a maybe fully qualified
channel. It will be Nothing if
annChanSend failed - i.e. we forget
about the channel. -}
(alpha, newVars, mfqChan, fqTerm) <- anaChanSend mix c t vars
let fqEvent = FQChanSend mfqChan fqTerm range
return (alpha, newVars, fqEvent)
ChanNonDetSend c v s range ->
do addDiags [mkDiag Debug "Channel nondeterministic send event" e]
{- mfqChan is the same as in chanSend case.
fqVar is the fully qualfied version of the variable. -}
(alpha, newVars, mfqChan, fqVar) <- anaChanBinding c v s
let fqEvent = FQChanNonDetSend mfqChan fqVar range
return (alpha, newVars, fqEvent)
ChanRecv c v s range ->
do addDiags [mkDiag Debug "Channel receive event" e]
{- mfqChan is the same as in chanSend case.
fqVar is the fully qualfied version of the variable. -}
(alpha, newVars, mfqChan, fqVar) <- anaChanBinding c v s
let fqEvent = FQChanRecv mfqChan fqVar range
return (alpha, newVars, fqEvent)
_ -> error
"CspCASL.StatAnaCSP.anaEvent: Unexpected Fully qualified event"
{- | Statically analyse a CspCASL term event. Returns a constituent
communication alphabet of the event and a mapping for any new
locally bound variables and the fully qualified version of the
term. -}
anaTermEvent :: Mix b s () () -> TERM () -> ProcVarMap
-> State CspCASLSign (CommAlpha, ProcVarMap, TERM ())
anaTermEvent mix t vars = do
mt <- anaTermCspCASL mix vars t
let (alpha, t') = case mt of
-- return the alphabet and the fully qualified term
Just at -> ([CommTypeSort (sortOfTerm at)], at)
-- return the empty alphabet and the original term
Nothing -> ([], t)
return (Set.fromList alpha, Map.empty, t')
{- | Statically analyse a CspCASL internal or external prefix choice
event. Returns a constituent communication alphabet of the event
and a mapping for any new locally bound variables and the fully
qualified version of the variable. -}
anaPrefixChoice :: VAR -> SORT ->
State CspCASLSign (CommAlpha, ProcVarMap, TERM ())
anaPrefixChoice v s = do
checkSorts [s] -- check sort is known
let alpha = Set.singleton $ CommTypeSort s
let binding = Map.singleton v s
let fqVar = Qual_var v s nullRange
return (alpha, binding, fqVar)
{- | Statically analyse a CspCASL channel send event. Returns a
constituent communication alphabet of the event, a mapping for
any new locally bound variables, a fully qualified channel (if
possible) and the fully qualified version of the term. -}
anaChanSend :: Mix b s () () -> CHANNEL_NAME -> TERM () -> ProcVarMap
-> State CspCASLSign
(CommAlpha, ProcVarMap, (CHANNEL_NAME, SORT), TERM ())
anaChanSend mix c t vars = do
sig <- get
let ext = extendedInfo sig
msg = "CspCASL.StatAnaCSP.anaChanSend: Channel Error"
case Set.toList $ MapSet.lookup c $ chans ext of
[] -> do
addDiags [mkDiag Error "unknown channel" c]
{- Use old term as the fully qualified term and forget about the
channel, there is an error in the spec -}
return (Set.empty, Map.empty, error msg, t)
chanSorts -> do
mt <- anaTermCspCASL mix vars t
case mt of
Nothing ->
{- CASL analysis failed. Use old term as the fully
qualified term and forget about the channel,
there is an error in the spec. -}
return (Set.empty, Map.empty, error msg, t)
Just at -> do
let rs = map (\ s -> ccTermCast at s sig) chanSorts
addDiags $ concatMap diags rs
case filter (isJust . maybeResult . fst) $ zip rs chanSorts of
[] ->
{- cast failed. Use old term as the fully
qualified term, and forget about the
channel there is an error in the spec. -}
return (Set.empty, Map.empty, error msg, t)
[(_, castSort)] ->
let alpha = [ CommTypeSort castSort
, CommTypeChan $ TypedChanName c castSort]
{- Use the real fully qualified term. We do
not want to use a cast term here. A cast
must be possible, but we do not want to
force it! -}
in return (Set.fromList alpha, Map.empty, (c, castSort), at)
cts -> do -- fail due to an ambiguous chan sort
addDiags [mkDiag Error
("ambiguous channel sorts " ++ show (map snd cts)) t]
{- Use old term as the fully qualified term and forget about the
channel, there is an error in the spec. -}
return (Set.empty, Map.empty, error msg, t)
getDeclaredChanSort :: (CHANNEL_NAME, SORT) -> CspCASLSign -> Result SORT
getDeclaredChanSort (c, s) sig =
let cm = chans $ extendedInfo sig
in case Set.toList $ MapSet.lookup c cm of
[] -> mkError "unknown channel" c
css -> case filter (\ cs -> cs == s || Set.member s (subsortsOf cs sig))
css of
[] -> mkError "sort not a subsort of channel's sort" s
[cs] -> return cs
fcs -> mkError ("ambiguous channel sorts " ++ show fcs) s
{- | Statically analyse a CspCASL "binding" channel event (which is
either a channel nondeterministic send event or a channel receive
event). Returns a constituent communication alphabet of the event,
a mapping for any new locally bound variables, a fully qualified
channel and the fully qualified version of the
variable. -}
anaChanBinding :: CHANNEL_NAME -> VAR -> SORT
-> State CspCASLSign
(CommAlpha, ProcVarMap, (CHANNEL_NAME, SORT), TERM ())
anaChanBinding c v s = do
checkSorts [s] -- check sort is known
sig <- get
let qv = Qual_var v s nullRange
fqChan = (c, s)
Result ds ms = getDeclaredChanSort fqChan sig
addDiags ds
case ms of
Nothing -> return (Set.empty, Map.empty, fqChan, qv)
Just _ ->
let alpha = [CommTypeSort s, CommTypeChan (TypedChanName c s)]
binding = [(v, s)]
{- Return the alphabet, var mapping, the fully qualfied channel and
fully qualfied variable. Notice that the fully qualified
channel's sort should be the lowest sort we can communicate in
i.e. the sort of the variable. -}
in return (Set.fromList alpha, Map.fromList binding, fqChan, qv)
-- Static analysis of renaming and renaming items
{- | Statically analyse a CspCASL renaming. Returns the alphabet and
the fully qualified renaming. -}
anaRenaming :: RENAMING -> State CspCASLSign (CommAlpha, RENAMING)
anaRenaming renaming = case renaming of
Renaming r -> do
fqRenamingTerms <- mapM anaRenamingItem r
let rs = concat fqRenamingTerms
return ( Set.map CommTypeSort $ Set.unions $ map alphaOfRename rs
, Renaming rs)
alphaOfRename :: Rename -> Set.Set SORT
alphaOfRename (Rename _ cm) = case cm of
Just (_, Just (s1, s2)) -> Set.fromList [s1, s2]
_ -> Set.empty
{- | Statically analyse a CspCASL renaming item. Return the alphabet
and the fully qualified list of renaming functions and predicates. -}
anaRenamingItem :: Rename -> State CspCASLSign [Rename]
anaRenamingItem r@(Rename ri cm) = let
predToRen p = Rename ri $ Just (BinPred, Just p)
opToRen (o, p) = Rename ri
$ Just (if o == Total then TotOp else PartOp, Just p)
in case cm of
Just (k, ms) -> case k of
BinPred -> do
ps <- getBinPredsById ri
let realPs = case ms of
Nothing -> ps
Just p -> filter (== p) ps
when (null realPs)
$ addDiags [mkDiag Error "renaming predicate not found" r]
unless (isSingle realPs)
$ addDiags [mkDiag Warning "multiple predicates found" r]
return $ map predToRen realPs
_ -> do
os <- getUnaryOpsById ri
-- we ignore the user given op kind here!
let realOs = case ms of
Nothing -> os
Just p -> filter ((== p) . snd) os
when (null realOs)
$ addDiags [mkDiag Error "renaming operation not found" r]
unless (isSingle realOs)
$ addDiags [mkDiag Warning "multiple operations found" r]
when (k == TotOp) $
mapM_ (\ (o, (s1, s2)) -> when (o == Partial)
$ addDiags [mkDiag Error
("operation of type '"
++ shows s1 " -> "
++ shows s2 "' is not total") r]) realOs
return $ map opToRen realOs
Nothing -> do
ps <- getBinPredsById ri
os <- getUnaryOpsById ri
let rs = map predToRen ps ++ map opToRen os
when (null rs)
$ addDiags [mkDiag Error "renaming predicate or operation not found" ri]
unless (isSingle rs)
$ addDiags [mkDiag Warning "multiple renamings found" ri]
return rs
{- | Given a CASL identifier, find all
unary operations with that name in the CASL signature, and return a
list of corresponding profiles, i.e. kind, argument sort and result sort. -}
getUnaryOpsById :: Id -> State CspCASLSign [(OpKind, (SORT, SORT))]
getUnaryOpsById ri = do
om <- gets opMap
return $ Set.fold (\ oty -> case oty of
OpType k [s1] s2 -> ((k, (s1, s2)) :)
_ -> id) [] $ MapSet.lookup ri om
{- | Given a CASL identifier find all binary predicates with that name in the
CASL signature, and return a list of corresponding profiles. -}
getBinPredsById :: Id -> State CspCASLSign [(SORT, SORT)]
getBinPredsById ri = do
pm <- gets predMap
return $ Set.fold (\ pty -> case pty of
PredType [s1, s2] -> ((s1, s2) :)
_ -> id) [] $ MapSet.lookup ri pm
{- | Given two CspCASL communication alphabets, check that the first's
subsort closure is a subset of the second's subsort closure. -}
checkCommAlphaSub :: CommAlpha -> CommAlpha -> PROCESS -> String
-> State CspCASLSign ()
checkCommAlphaSub sub super proc context = do
sr <- gets sortRel
let extras = closeCspCommAlpha sr sub
`Set.difference` closeCspCommAlpha sr super
unless (Set.null extras) $
let err = "Communication alphabet subset violations (" ++
context ++ ")" ++ show (printCommAlpha extras)
in addDiags [mkDiag Error err proc]
-- Static analysis of CASL terms occurring in CspCASL process terms.
{- | Statically analyse a CASL term appearing in a CspCASL process;
any in-scope process variables are added to the signature before
performing the analysis. -}
anaTermCspCASL :: Mix b s () () -> ProcVarMap -> TERM ()
-> State CspCASLSign (Maybe (TERM ()))
anaTermCspCASL mix pm t = do
sig <- get
let newVars = Map.union pm (varMap sig)
sigext = sig { varMap = newVars }
Result ds mt = anaTermCspCASL' mix sigext t
addDiags ds
return mt
idSetOfSig :: CspCASLSign -> IdSets
idSetOfSig sig =
unite [mkIdSets (allConstIds sig) (allOpIds sig) $ allPredIds sig]
{- | Statically analyse a CASL term in the context of a CspCASL
signature. If successful, returns a fully-qualified term. -}
anaTermCspCASL' :: Mix b s () () -> CspCASLSign -> TERM () -> Result (TERM ())
anaTermCspCASL' mix sig trm = fmap snd $ anaTerm (const return) mix
(ccSig2CASLSign sig) Nothing (getRange trm) trm
-- | Attempt to cast a CASL term to a particular CASL sort.
ccTermCast :: TERM () -> SORT -> CspCASLSign -> Result (TERM ())
ccTermCast t cSort sig = let
pos = getRange t
msg = (++ "cast term to sort " ++ show cSort)
in case optTermSort t of
Nothing -> mkError "term without type" t
Just termSort
| termSort == cSort -> return t
| Set.member termSort $ subsortsOf cSort sig ->
hint (Sorted_term t cSort pos) (msg "up") pos
| Set.member termSort $ supersortsOf cSort sig ->
hint (Cast t cSort pos) (msg "down") pos
| otherwise -> fatal_error (msg "cannot ") pos
{- Static analysis of CASL formulae occurring in CspCASL process
terms. -}
{- | Statically analyse a CASL formula appearing in a CspCASL process;
any in-scope process variables are added to the signature before
performing the analysis. -}
anaFormulaCspCASL :: Mix b s () () -> ProcVarMap -> FORMULA ()
-> State CspCASLSign (Maybe (FORMULA ()))
anaFormulaCspCASL mix pm f = do
addDiags [mkDiag Debug "anaFormulaCspCASL" f]
sig <- get
let newVars = Map.union pm (varMap sig)
sigext = sig { varMap = newVars }
Result ds mt = anaFormulaCspCASL' mix sigext f
addDiags ds
return mt
{- | Statically analyse a CASL formula in the context of a CspCASL
signature. If successful, returns a fully-qualified formula. -}
anaFormulaCspCASL' :: Mix b s () () -> CspCASLSign -> FORMULA ()
-> Result (FORMULA ())
anaFormulaCspCASL' mix sig =
fmap snd . anaForm (const return) mix (ccSig2CASLSign sig)
{- | Compute the communication alphabet arising from a formula
occurring in a CspCASL process term. -}
formulaComms :: FORMULA () -> CommAlpha
formulaComms = Set.map CommTypeSort . foldFormula
(constRecord (const Set.empty) Set.unions Set.empty)
{ foldQuantification = \ _ _ varDecls f _ ->
let vdSort (Var_decl _ s _) = s in
Set.union f $ Set.fromList (map vdSort varDecls)
, foldQual_var = \ _ _ s _ -> Set.singleton s
, foldApplication = \ _ o _ _ -> case o of
Op_name _ -> Set.empty
Qual_op_name _ ty _ -> Set.singleton $ res_OP_TYPE ty
, foldSorted_term = \ _ _ s _ -> Set.singleton s
, foldCast = \ _ _ s _ -> Set.singleton s }
| keithodulaigh/Hets | CspCASL/StatAnaCSP.hs | gpl-2.0 | 37,316 | 95 | 27 | 10,758 | 8,359 | 4,315 | 4,044 | 619 | 18 |
module Main (
main
) where
import Graphics.UI.Gtk (postGUIAsync)
import GHCJS.DOM (runWebGUI, webViewGetDomDocument)
main =
runWebGUI $ \ webView -> postGUIAsync $ do
Just doc <- webViewGetDomDocument webView
putStrLn "Bewleksah is a version of Leksah that can run in a web browser."
putStrLn "Nothing working yet."
| cocreature/leksah | bew/Main.hs | gpl-2.0 | 338 | 0 | 11 | 68 | 76 | 40 | 36 | 9 | 1 |
module Turbinado.Environment.Routes (
addRoutesToEnvironment,
runRoutes
) where
import Control.Concurrent.MVar
import Text.Regex
import Data.Maybe
import Data.Typeable
import Data.Dynamic
import qualified Data.Map as M
import Data.Time
import Control.Monad
import qualified Network.HTTP as HTTP
import qualified Network.URI as URI
import Turbinado.Controller.Monad
import Turbinado.Controller.Exception
import Turbinado.Environment.Types
import Turbinado.Environment.Logger
import Turbinado.Environment.Request
import Turbinado.Environment.Settings
import qualified Turbinado.Environment.Settings as S
import Turbinado.Utility.Data
import qualified Config.Routes
addRoutesToEnvironment :: (HasEnvironment m) => m ()
addRoutesToEnvironment = do e <- getEnvironment
let CodeStore mv = fromJust' "Turbinado.Environment.Routes.addRoutesToEnvironment : no CodeStore" $ getCodeStore e
cm <- liftIO $ takeMVar mv
let cm' = addStaticControllers Config.Routes.staticControllers cm
cm'' = addStaticViews (Config.Routes.staticViews ++ Config.Routes.staticLayouts) cm'
liftIO $ putMVar mv cm''
setEnvironment $ e {
getRoutes = Just $ Routes $ parseRoutes Config.Routes.routes}
------------------------------------------------------------------------------
-- Given an Environment
------------------------------------------------------------------------------
runRoutes :: (HasEnvironment m) => m ()
runRoutes = do debugM $ " Routes.runRoutes : starting"
e <- getEnvironment
let Routes rs = fromJust' "Routes : runRoutes : getRoutes" $ getRoutes e
r = fromJust' "Routes : runRoutes : getRequest" $ getRequest e
p = URI.uriPath $ HTTP.rqURI r
sets = filter (not . null) $ map (\(r, k) -> maybe [] (zip k) (matchRegex r p)) rs
case sets of
[] -> do setSetting "controller" $ last Config.Routes.routes -- no match, so use the last route
addDefaultAction
_ -> do mapM (\(k, v) -> setSetting k v) $ head sets
addDefaultAction
addDefaultAction :: (HasEnvironment m) => m ()
addDefaultAction = do e <- getEnvironment
let s = fromJust' "Routes : addDefaultAction : getSettings" $ getSettings e
setEnvironment $ e {getSettings = Just (M.insertWith (\ a b -> b) "action" (toDyn "Index") s)}
------------------------------------------------------------------------------
-- Generate the Routes from [String]
------------------------------------------------------------------------------
parseRoutes = map (\s -> (routeRegex s, extractKeys s))
extractKeys = map (drop 1) . filter (\l -> (take 1 l) == ":") . ( \s -> concat $ map (splitOn '/') $ splitOn '.' s)
routeRegex = mkRegex . generateRouteRegex
generateRouteKeysRegexString = "([^/^\\.]+)"
generateRouteRegexRegex = mkRegex generateRouteKeysRegexString
generateRouteRegex = \s -> subRegex generateRouteRegexRegex (escapePeriods s) "([^/^\\.]+)"
escapePeriods [] = []
escapePeriods ('.':cs) = "\\." ++ escapePeriods cs
escapePeriods ( c :cs) = c : escapePeriods cs
splitOn :: Char -> String -> [String]
splitOn c l = reverse $ worker c l []
where worker c [] r = r
worker c (l:ls) [] = if (l == c)
then worker c ls []
else worker c ls [[l]]
worker c (l:ls) (r:rs) = if (l == c)
then worker c ls ([]:r:rs)
else worker c ls ((r++[l]):rs)
----------------------------------------------------------------------------
-- Handle static routes
----------------------------------------------------------------------------
--addStaticViews :: [(String, String, View VHtml)] -> CodeMap -> CodeMap
addStaticViews [] cm = cm
addStaticViews ((p,f,v):vs) cm = let cm' = M.insert (p,f) (CodeLoadView v $ UTCTime (ModifiedJulianDay 1000000) (secondsToDiffTime 0)) cm in
addStaticViews vs cm'
addStaticControllers [] cm = cm
addStaticControllers ((p,f,c):cs) cm = let cm' = M.insert (p,f) (CodeLoadController c $ UTCTime (ModifiedJulianDay 1000000) (secondsToDiffTime 0)) cm in
addStaticControllers cs cm'
| alsonkemp/turbinado | Turbinado/Environment/Routes.hs | bsd-3-clause | 4,577 | 0 | 16 | 1,242 | 1,212 | 639 | 573 | 71 | 5 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
module Snap.Internal.Http.Server.Date
( getDateString
, getLogDateString
) where
------------------------------------------------------------------------------
import Control.Exception (mask_)
import Control.Monad (when)
import Data.ByteString (ByteString)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Foreign.C.Types (CTime)
import System.IO.Unsafe (unsafePerformIO)
import System.PosixCompat.Time (epochTime)
------------------------------------------------------------------------------
import Snap.Internal.Http.Types (formatHttpTime, formatLogTime)
------------------------------------------------------------------------------
data DateState = DateState {
_cachedDateString :: !(IORef ByteString)
, _cachedLogString :: !(IORef ByteString)
, _lastFetchTime :: !(IORef CTime)
}
------------------------------------------------------------------------------
dateState :: DateState
dateState = unsafePerformIO $ do
(s1, s2, date) <- fetchTime
bs1 <- newIORef $! s1
bs2 <- newIORef $! s2
dt <- newIORef $! date
return $! DateState bs1 bs2 dt
{-# NOINLINE dateState #-}
------------------------------------------------------------------------------
fetchTime :: IO (ByteString,ByteString,CTime)
fetchTime = do
!now <- epochTime
!t1 <- formatHttpTime now
!t2 <- formatLogTime now
let !out = (t1, t2, now)
return out
------------------------------------------------------------------------------
updateState :: DateState -> IO ()
updateState (DateState dateString logString time) = do
(s1, s2, now) <- fetchTime
writeIORef dateString $! s1
writeIORef logString $! s2
writeIORef time $! now
return $! ()
------------------------------------------------------------------------------
ensureFreshDate :: IO ()
ensureFreshDate = mask_ $ do
now <- epochTime
old <- readIORef $ _lastFetchTime dateState
when (now > old) $! updateState dateState
------------------------------------------------------------------------------
getDateString :: IO ByteString
getDateString = mask_ $ do
ensureFreshDate
readIORef $ _cachedDateString dateState
------------------------------------------------------------------------------
getLogDateString :: IO ByteString
getLogDateString = mask_ $ do
ensureFreshDate
readIORef $ _cachedLogString dateState
| k-bx/snap-server | src/Snap/Internal/Http/Server/Date.hs | bsd-3-clause | 2,592 | 0 | 11 | 515 | 536 | 282 | 254 | 58 | 1 |
module FunIn2a where
--Any unused parameter to a definition can be removed.
--In this example: remove the parameter 'x' to 'foo'
inc,foo :: Int -> Int
foo x= h + t where (h,t) = head $ zip [1..7] [3..15]
inc x=x+1
main :: Int
main = foo 4
| RefactoringTools/HaRe | test/testdata/RmOneParameter/FunIn2a.hs | bsd-3-clause | 245 | 0 | 9 | 54 | 87 | 49 | 38 | 6 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
module TH_RichKinds where
import Data.Kind (Type, Constraint)
import Language.Haskell.TH hiding (Type)
$(do tys <- sequence [ [t| forall a. (a :: Bool) |]
, [t| forall a. (a :: Constraint) |]
, [t| forall a. (a :: [Type]) |]
, [t| forall a. (a :: (Type, Bool)) |]
, [t| forall a. (a :: ()) |]
, [t| forall a. (a :: (Type -> Bool)
-> ((Type, Type -> Type) -> Bool)) |]
]
reportWarning (pprint tys)
return [])
| sdiehl/ghc | testsuite/tests/th/TH_RichKinds.hs | bsd-3-clause | 751 | 0 | 11 | 289 | 113 | 75 | 38 | 17 | 0 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE FlexibleInstances #-}
-- | Same as SH_Overlap1, but module where overlap occurs (SH_Overlap3) is
-- marked `Unsafe`. Compilation should succeed (symmetry with inferring safety).
module SH_Overlap3 where
import SH_Overlap3_A
instance
C [a] where
f _ = "[a]"
test :: String
test = f ([1,2,3,4] :: [Int])
| ezyang/ghc | testsuite/tests/safeHaskell/overlapping/SH_Overlap3.hs | bsd-3-clause | 350 | 0 | 7 | 63 | 64 | 40 | 24 | 9 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
import Test.Cabal.Prelude
import Data.IORef
import Control.Monad.IO.Class
import Control.Exception (ErrorCall)
import qualified Control.Monad.Catch as Catch
main = setupTest $ do
-- the following is a hack to check that `setup configure` indeed
-- fails: all tests use `assertFailure` which uses `error` if the fail
--
-- note: we cannot use `fails $ do ...` here since that only checks that all
-- assertions fail. If there is no assertion in `m`, then `fails m` will *succeed*.
-- That's not what we want. So `fails (return ())` for example succeeds, even though
-- `return ()` doesn't fail.
succeededRef <- liftIO $ newIORef True
setup "configure" [] `Catch.catch` \(_ :: ErrorCall) ->
liftIO $ writeIORef succeededRef False
succeeded <- liftIO $ readIORef succeededRef
assertBool "test should have failed, but succeeded instead (configure exits with failure)" $ not succeeded
| themoritz/cabal | cabal-testsuite/tests/fail.test.hs | bsd-3-clause | 945 | 0 | 11 | 167 | 135 | 75 | 60 | 12 | 1 |
{-# LANGUAGE CPP #-}
module Control.AutoUpdate.Util
( atomicModifyIORef'
) where
#ifndef MIN_VERSION_base
#define MIN_VERSION_base(x,y,z) 1
#endif
#if MIN_VERSION_base(4,6,0)
import Data.IORef (atomicModifyIORef')
#else
import Data.IORef (IORef, atomicModifyIORef)
-- | Strict version of 'atomicModifyIORef'. This forces both the value stored
-- in the 'IORef' as well as the value returned.
atomicModifyIORef' :: IORef a -> (a -> (a,b)) -> IO b
atomicModifyIORef' ref f = do
c <- atomicModifyIORef ref
(\x -> let (a, b) = f x -- Lazy application of "f"
in (a, a `seq` b)) -- Lazy application of "seq"
-- The following forces "a `seq` b", so it also forces "f x".
c `seq` return c
#endif
| jberryman/wai | auto-update/Control/AutoUpdate/Util.hs | mit | 782 | 0 | 5 | 203 | 29 | 21 | 8 | 4 | 0 |
{-# LANGUAGE MultiWayIf #-}
module MultiWayIf where
foo = if | test1 -> e1
| test2 witharg -> e2
| otherwise -> def
bar = if { | test1 -> if { | test2 -> e1
| test3 -> e2 }
| test4 -> e3
}
-- taken from GHC's test suite
x = 10
x1 = if | x < 10 -> "< 10" | otherwise -> ""
x2 = if | x < 10 -> "< 10"
| otherwise -> ""
x3 = if | x < 10 -> "< 10"
| otherwise -> ""
x4 = if | True -> "yes"
x5 = if | True -> if | False -> 1 | True -> 2
x6 = if | x < 10 -> if | True -> "yes"
| False -> "no"
| otherwise -> "maybe"
x7 = (if | True -> 0)
-- issue #98
spam = if | () <- () -> ()
| ezyang/ghc | testsuite/tests/printer/Ppr039.hs | bsd-3-clause | 691 | 4 | 10 | 278 | 309 | 151 | 158 | 21 | 3 |
-- Aluno: Salomão Rodrigues Jacinto
-- Matrícula UFSC: 15104097
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString.Lazy as BS
import Data.ByteString.Lazy (ByteString)
import System.Environment
import System.FilePath
import System.IO
-- Header infos, offset is needed to jump to the bgr rows
data BMPHeader = BMPHeader {
bm :: Word16,
size :: Word32,
u1 :: Word16,
u2 :: Word16,
offset :: Word32
} deriving (Show)
-- Bitmap info header, width e bpp~are needed to check the padding of the bitmap
data DIBHeader = DIBHeader {
headerSize :: Word32,
width :: Word32,
height :: Word32,
planes :: Word16,
bpp :: Word16,
compression :: Word32,
dataSize :: Word32,
ppmh :: Word32,
ppmv :: Word32,
palleteSize :: Word32,
important :: Word32
} deriving (Show)
-- The headers and the data part
data Bitmap = Bitmap {
bmp :: BMPHeader,
dib :: DIBHeader,
bytes :: ByteString
}
-- More infos can be found at [https://en.wikipedia.org/wiki/BMP_file_format]
-- The padding info is necessary because not every bmp image has a multiple of 4
-- row and that would crash the program. Pixel storage of the wiki above explain
-- Another interesting fact, .bmp is little-endian
-- Data type for the rgb values
data BGRPixel = BGRPixel {
b :: Word8,
g :: Word8,
r :: Word8
}
-- Tuple and list of rgb values
type BGR = ([Word8], [Word8], [Word8])
type BGRList = [[Word8]]
-- The next Get's are used with runGet to get from a bytestring the values of the
-- headers
getBMPHeader :: Get BMPHeader
getBMPHeader = do
bm <- getWord16le
size <- getWord32le
u1 <- getWord16le
u2 <- getWord16le
offset <- getWord32le
return $ BMPHeader bm size u1 u2 offset
getDIBHeader :: Get DIBHeader
getDIBHeader = do
headerSize <- getWord32le
width <- getWord32le
height <- getWord32le
planes <- getWord16le
bpp <- getWord16le
compression <- getWord32le
dataSize <- getWord32le
ppmh <- getWord32le
ppmv <- getWord32le
palleteSize <- getWord32le
important <- getWord32le
return (DIBHeader headerSize width height planes bpp compression dataSize
ppmh ppmv palleteSize important)
getHeaders :: Get (BMPHeader, DIBHeader)
getHeaders = do
b <- getBMPHeader
d <- getDIBHeader
return (b, d)
-- The bytestring of the .bmp file creates the Bitmap, separeting the headers and
-- the data part using the offset
getBitmap :: ByteString -> Bitmap
getBitmap bytes = let
(b, d) = runGet getHeaders bytes
o = fromIntegral $ offset b
in Bitmap b d (BS.drop o bytes)
-- Get the width of the rows of the bitmap
bmpWidth :: Bitmap -> Int
bmpWidth bmp = fromIntegral $ width (dib bmp)
bytesPerPixel :: Bitmap -> Int
bytesPerPixel bmp = bitsPerPixel `div` 8
where bitsPerPixel = fromIntegral $ bpp (dib bmp)
-- The rows are multiple of four, if not a padding is added, this checks how long
-- is this padding to read the file the right way
padding :: Int -> Int -> Int
padding width bpp = (4 - (width*bpp `mod` 4)) `mod` 4
-- Separate the rows of the data part, creating a list of rows and eliminating the
-- padding if there is any
getRows :: Int -> Int -> [Word8] -> [[Word8]]
getRows _ _ [] = []
getRows width bpp bytes = row:(getRows width bpp remainder)
where p = padding width bpp
size = width * bpp
(padded, remainder) = splitAt (size+p) bytes
row = take size padded
-- Transform the rows into type BGRPixel, splits at every 3 words8
rowToPixels :: [Word8] -> [BGRPixel]
rowToPixels [] = []
rowToPixels row = let
([b, g, r], remainder) = splitAt 3 row
in (BGRPixel b g r):(rowToPixels remainder)
-- Makes a composition to go from the bitmap file to a list of BGRPixels
getPixels :: Bitmap -> [BGRPixel]
getPixels bmp = let
w = bmpWidth bmp
bpp = bytesPerPixel bmp
rows = getRows w bpp . BS.unpack $ bytes bmp
in concat $ map rowToPixels rows
-- Splits the list of BRGPixels into BGR 3-tuple, this tuple has 3 lists, one for
-- eache color, and the value are stored there
splitBGR :: [BGRPixel] -> BGR
splitBGR [] = ([], [], [])
splitBGR (BGRPixel b g r:ps) = (b:bs, g:gs, r:rs)
where (bs, gs, rs) = splitBGR ps
-- Converts a 3-tuple into a list to use zip to write the files
toList :: (a, a, a) -> [a]
toList (b, g, r) = [b, g, r]
-- Here is used all the above functions to go from a bitmap file to a 3-tuple with
-- the list of values from each color
bmpToBGR :: Bitmap -> BGR
bmpToBGR = splitBGR . getPixels
-- Converts the bytes to float values
toFloat :: Word8 -> Float
toFloat color = fromIntegral color / 255
-- Close all the files
closeAll :: [Handle] -> IO [()]
closeAll handlers = sequence $ map hClose handlers
-- Open all the files
openAll :: [String] -> IO [Handle]
openAll filenames = sequence [openFile filename WriteMode |
filename <- filenames]
-- Output the content values into the filenames using specified IO function, in our
-- case it is used zip function to put each pixel bgr value into the right file
outputAll :: (Handle -> a -> IO ()) -> [Handle] -> [a] -> IO [()]
outputAll outputFunction filenames contents = do
sequence [outputFunction filename contents |
(filename, contents) <- zip filenames contents]
-- The suffixes that are going to name the files
suffixes :: [String]
suffixes = ["_blue.out", "_green.out", "_red.out"]
-- Concat the bitmap filename with the suffixes
concatSuffixes :: [String] -> String -> [String]
concatSuffixes suffixes prefix = map (prefix++) suffixes
-- Create the names of the output files
outnames :: String -> [FilePath]
outnames = concatSuffixes suffixes
-- Get the file name and the bitmap file and outputs to the files
splitFileText :: String -> Bitmap -> IO ()
splitFileText prefix bitmap = do
outputs <- openAll $ outnames prefix
outputAll hPrint outputs $ [map toFloat color |
color <- toList $ bmpToBGR bitmap]
closeAll outputs
return ()
-- Use above functions to split the bitmap rgb file into three text files of
-- floating points
main = do
args <- getArgs
case args of
[filename] -> do
input <- BS.readFile filename
let prefix = takeBaseName filename
let bitmap = getBitmap input
splitFileText prefix bitmap
_ -> putStrLn "Usage: ./newrgb FILE.bmp"
-- This does not work if the .bmp file has a alpha channel. Just splits into rgb
-- 24bit rgb files
-- This was made by Tarcisio Eduardo Moreira Crocomo, with the help of Salomão
-- Rodrigues Jacinto and Evandro Chagas Ribeiro Rosa based on the work from
-- Gustavo Zambonim
| MaoRodriguesJ/INE5416 | Functional/newrgb.hs | mit | 6,777 | 2 | 12 | 1,583 | 1,625 | 890 | 735 | 137 | 2 |
module Handler.TechWithIdSpec (spec) where
import TestImport
spec :: Spec
spec = withApp $ do
describe "getTechWithIdR" $ do
error "Spec not implemented: getTechWithIdR"
| swamp-agr/carbuyer-advisor | test/Handler/TechWithIdSpec.hs | mit | 186 | 0 | 11 | 39 | 44 | 23 | 21 | 6 | 1 |
module Web.Blog.Hatena.Diary (
entryURLsOf
, archiveURLs
, entryURLsFromArchiveURL
) where
import Web.Blog.Type
-- import Network.URI
-- import Data.Maybe (fromJust)
import Text.XML.HXT.Core
import Text.HandsomeSoup
import Network.HTTP.Conduit (simpleHttp)
import Data.ByteString.Lazy.Char8 as BL8 (unpack)
import System.FilePath.Posix ((</>))
import Control.Applicative ((<$>))
import Data.List (nub, sort,isPrefixOf)
-- import Control.Monad (forM_, mapM_)
import Control.Monad.IO.Class (liftIO)
-- | entryURLsOf
-- > entryURLsOf $ fromJust $ parseURI "http://d.hatena.ne.jp/suzuki-shin/"
-- [http://d.hatena.ne.jp/suzuki-shin/2014/06/02/hogehoge,http://d.hatena.ne.jp/suzuki-shin/2014/06/01/fugafuga]
entryURLsOf :: Url -> IO [Url]
entryURLsOf baseUri = do
aURLs <- archiveURLs baseUri
concat <$> mapM (liftIO . entryURLsFromArchiveURL) aURLs
-- | archiveURLs
-- > archiveURLs "http://d.hatena.ne.jp/hogehoge"
-- ["http://d.hatena.ne.jp/hogehoge/archive?word=&of=50","http://d.hatena.ne.jp/hogehoge/archive?word=&of=100","http://d.hatena.ne.jp/hogehoge/archive?word=&of=150","http://d.hatena.ne.jp/hogehoge/archive?word=&of=200","http://d.hatena.ne.jp/hogehoge/archive?word=&of=250","http://d.hatena.ne.jp/hogehoge/archive?word=&of=300"]
archiveURLs :: Url -> IO [Url]
archiveURLs baseUrl = do
let archiveUrl = baseUrl </> "archive"
c <- simpleHttp archiveUrl
let doc = readString [withParseHTML yes, withWarnings no] $ BL8.unpack c
links <- runX $ doc //> css "div" >>> hasAttrValue "id" (== "pager-top") >>> css "a" ! "href"
return $ sort $ nub $ archiveUrl:links
-- | entryURLsFromArchiveURL
-- > entryURLsFromArchiveURL "http://d.hatena.ne.jp/hogehoge/archive"
-- ["
entryURLsFromArchiveURL :: Url -> IO [Url]
entryURLsFromArchiveURL archiveURL = do
c <- simpleHttp archiveURL
let doc = readString [withParseHTML yes, withWarnings no] $ BL8.unpack c
links <- runX $ doc //> css "li" >>> hasAttrValue "class" (== "archive archive-section") >>> css "a" ! "href"
return $ sort $ exceptArchiveLinks $ nub links
where
exceptArchiveLinks :: [Url] -> [Url]
exceptArchiveLinks = filter (isPrefixOf "http")
| suzuki-shin/blogtools | Web/Blog/Hatena/Diary.hs | mit | 2,145 | 0 | 13 | 261 | 476 | 256 | 220 | 32 | 1 |
module ProjectEuler.Problem048 (solve) where
import Data.List
import ProjectEuler.Prelude
solve :: Integer
solve = read $ toString $ takeLast 10 $ digits total
where
total = foldl' (\n x -> n + x ^ x) 0 terms
terms = [1..1000]
| hachibu/project-euler | src/ProjectEuler/Problem048.hs | mit | 239 | 0 | 11 | 51 | 91 | 50 | 41 | 7 | 1 |
module Commands.RHS
( module Commands.RHS.Types
, module Commands.RHS.Derived
-- , module Commands.RHS.Finite
) where
import Commands.RHS.Types
import Commands.RHS.Derived
--import Commands.RHS.Finite
| sboosali/commands | commands-core/sources/Commands/RHS.hs | mit | 209 | 0 | 5 | 28 | 36 | 25 | 11 | 5 | 0 |
module Oden.Compiler.MonomorphizationSpec where
import Data.Set as Set
import Test.Hspec
import Oden.Core.Definition
import Oden.Core.Expr
import Oden.Core.Monomorphed as Monomorphed
import Oden.Core.Package
import Oden.Core.Typed as Typed
import Oden.Identifier
import Oden.QualifiedName
import qualified Oden.Type.Monomorphic as Mono
import qualified Oden.Type.Polymorphic as Poly
import Oden.Compiler.Monomorphization.Fixtures
import Oden.Assertions
identityDef :: TypedDefinition
identityDef =
Definition
missing
(nameInUniverse "identity")
(Poly.Forall missing [Poly.TVarBinding missing tvA] Set.empty (Poly.TFn missing a a),
Fn missing (NameBinding missing (Identifier "x")) (Symbol missing (Identifier "x") a)
(Poly.TFn missing a a))
identity2Def :: TypedDefinition
identity2Def =
Definition
missing
(nameInUniverse "identity2")
(Poly.Forall missing [Poly.TVarBinding missing tvA] Set.empty (Poly.TFn missing a a),
Fn missing (NameBinding missing (Identifier "x")) (Application missing (Symbol missing (Identifier "identity") (Poly.TFn missing a a))
(Symbol missing (Identifier "x") a)
a)
(Poly.TFn missing a a))
usingIdentityDef :: TypedDefinition
usingIdentityDef =
Definition
missing
(nameInUniverse "using_identity")
(Poly.Forall missing [] Set.empty typeInt,
Application missing
(Symbol missing (Identifier "identity") (Poly.TFn missing typeInt typeInt))
(Literal missing (Int 1) typeInt)
typeInt)
usingIdentity2Def :: TypedDefinition
usingIdentity2Def =
Definition
missing
(nameInUniverse "using_identity2")
(Poly.Forall missing [] Set.empty typeInt,
Application missing
(Symbol missing (Identifier "identity2") (Poly.TFn missing typeInt typeInt))
(Literal missing (Int 1) typeInt)
typeInt)
usingIdentityMonomorphed :: MonomorphedDefinition
usingIdentityMonomorphed =
MonomorphedDefinition
missing
(Identifier "__using_identity")
monoInt
(Application missing
(Symbol missing (Identifier "__identity_inst_int_to_int") (Mono.TFn missing monoInt monoInt))
(Literal missing (Int 1) monoInt)
monoInt)
letBoundIdentity :: TypedDefinition
letBoundIdentity =
Definition
missing
(nameInUniverse "let_bound_identity")
( Poly.Forall missing [] Set.empty typeInt
, Let
missing
(NameBinding missing (Identifier "identity"))
(Fn missing
(NameBinding missing (Identifier "x"))
(Symbol missing (Identifier "x") a) (Poly.TFn missing a a))
(Application
missing
(Symbol missing (Identifier "identity") (Poly.TFn missing typeInt typeInt))
(Literal missing (Int 1) typeInt)
typeInt)
typeInt
)
usingIdentity2Monomorphed :: MonomorphedDefinition
usingIdentity2Monomorphed =
MonomorphedDefinition
missing
(Identifier "__using_identity2")
monoInt
(Application
missing
(Symbol missing (Identifier "__identity2_inst_int_to_int") (Mono.TFn missing monoInt monoInt))
(Literal missing (Int 1) monoInt)
monoInt)
letBoundIdentityMonomorphed :: MonomorphedDefinition
letBoundIdentityMonomorphed =
MonomorphedDefinition
missing
(Identifier "__let_bound_identity")
monoInt
(Let
missing
(NameBinding missing (Identifier "__identity_inst_int_to_int"))
(Fn missing (NameBinding missing (Identifier "x")) (Symbol missing (Identifier "x") monoInt) (Mono.TFn missing monoInt monoInt))
(Application missing (Symbol missing (Identifier "__identity_inst_int_to_int") (Mono.TFn missing monoInt monoInt))
(Literal missing (Int 1) monoInt)
monoInt)
monoInt)
identityInstIntToInt :: InstantiatedDefinition
identityInstIntToInt =
InstantiatedDefinition
(nameInUniverse "identity")
missing
(Identifier "__identity_inst_int_to_int")
(Fn
missing
(NameBinding missing (Identifier "x"))
(Symbol missing (Identifier "x") monoInt)
(Mono.TFn missing monoInt monoInt))
identity2InstIntToInt :: InstantiatedDefinition
identity2InstIntToInt =
InstantiatedDefinition
(nameInUniverse "identity2")
missing
(Identifier "__identity2_inst_int_to_int")
(Fn
missing
(NameBinding missing (Identifier "x"))
(Application
missing
(Symbol missing (Identifier "__identity_inst_int_to_int") (Mono.TFn missing monoInt monoInt))
(Symbol missing (Identifier "x") monoInt)
monoInt)
(Mono.TFn missing monoInt monoInt))
sliceLenDef :: TypedDefinition
sliceLenDef =
Definition
missing
(nameInUniverse "slice_len")
(Poly.Forall missing [] Set.empty typeInt,
Application
missing
(Symbol missing (Identifier "len") (Poly.TForeignFn missing False [Poly.TSlice missing typeBool] [typeInt]))
(Slice missing [Literal missing (Bool True) typeBool] (Poly.TSlice missing typeBool))
typeInt)
sliceLenMonomorphed :: MonomorphedDefinition
sliceLenMonomorphed =
MonomorphedDefinition
missing
(Identifier "__slice_len")
monoInt
(Application
missing
(Symbol missing (Identifier "len") (Mono.TForeignFn missing False [Mono.TSlice missing monoBool] [monoInt]))
(Slice missing [Literal missing (Bool True) monoBool] (Mono.TSlice missing monoBool))
monoInt)
letWithShadowing :: TypedDefinition
letWithShadowing =
Definition
missing
(nameInUniverse "let_with_shadowing")
(Poly.Forall missing [] Set.empty typeInt,
Let
missing
(NameBinding missing (Identifier "x"))
(Literal missing (Int 1) typeInt)
(Let
missing
(NameBinding missing (Identifier "x"))
(Symbol missing (Identifier "x") typeInt)
(Symbol missing (Identifier "x") typeInt)
typeInt)
typeInt)
letWithShadowingMonomorphed :: MonomorphedDefinition
letWithShadowingMonomorphed =
MonomorphedDefinition
missing
(Identifier "__let_with_shadowing")
monoInt
(Let
missing
(NameBinding missing (Identifier "x"))
(Literal missing (Int 1) monoInt)
(Let
missing
(NameBinding missing (Identifier "x"))
(Symbol missing (Identifier "x") monoInt)
(Symbol missing (Identifier "x") monoInt)
monoInt)
monoInt)
monomorphicValue :: TypedDefinition
monomorphicValue =
Definition
missing
(FQN (NativePackageName ["dependency", "pkg"]) (Identifier "number"))
( Poly.Forall missing [] Set.empty typeInt
, Literal missing (Int 1) typeInt)
usingMonomorphicValueFromImportedPackage :: TypedDefinition
usingMonomorphicValueFromImportedPackage =
Definition
missing
(FQN (NativePackageName ["my", "pkg"]) (Identifier "usingMonomorphic"))
( Poly.Forall missing [] Set.empty typeInt
, MemberAccess
missing
(Typed.PackageMemberAccess
(Identifier "pkg")
(Identifier "number"))
typeInt)
monomorphicValuePrefixed :: MonomorphedDefinition
monomorphicValuePrefixed =
MonomorphedDefinition
missing
(Identifier "__dependency_pkg__number")
monoInt
(Literal missing (Int 1) monoInt)
usingMonomorphicValueFromImportedPackageMonomorphed :: MonomorphedDefinition
usingMonomorphicValueFromImportedPackageMonomorphed =
MonomorphedDefinition
missing
(Identifier "__my_pkg__usingMonomorphic")
monoInt
(Symbol missing (Identifier "__dependency_pkg__number") monoInt)
spec :: Spec
spec =
describe "monomorphPackage" $ do
it "compiles empty package" $
monomorphPackage (TypedPackage myPkg [] [])
`shouldSucceedWith`
MonomorphedPackage
myPkg
[]
Set.empty
Set.empty
it "excludes unused polymorphic definitions" $
monomorphPackage (TypedPackage myPkg [] [identityDef])
`shouldSucceedWith`
MonomorphedPackage
myPkg
[]
Set.empty
Set.empty
it "monomorphs polymorphic function usage" $
monomorphPackage (TypedPackage myPkg [] [identityDef, usingIdentityDef])
`shouldSucceedWith`
MonomorphedPackage
myPkg
[]
(Set.singleton identityInstIntToInt)
(Set.singleton usingIdentityMonomorphed)
it "monomorphs polymorphic function usage recursively" $
monomorphPackage (TypedPackage myPkg [] [identityDef, identity2Def, usingIdentity2Def])
`shouldSucceedWith`
MonomorphedPackage
myPkg
[]
(Set.fromList [identityInstIntToInt, identity2InstIntToInt])
(Set.singleton usingIdentity2Monomorphed)
it "monomorphs let bound polymorphic function" $
monomorphPackage (TypedPackage myPkg [] [letBoundIdentity])
`shouldSucceedWith`
MonomorphedPackage
myPkg
[]
Set.empty
(Set.singleton letBoundIdentityMonomorphed)
it "uses polymorphic predefined Go funcs" $
monomorphPackage (TypedPackage myPkg [] [sliceLenDef])
`shouldSucceedWith`
MonomorphedPackage
myPkg
[]
Set.empty
(Set.singleton sliceLenMonomorphed)
it "monomorphs let with shadowing" $
monomorphPackage (TypedPackage myPkg [] [letWithShadowing])
`shouldSucceedWith`
MonomorphedPackage
myPkg
[]
Set.empty
(Set.singleton letWithShadowingMonomorphed)
it "includes used imported monomorphic definitions with prefixed names" $
monomorphPackage (TypedPackage
myPkg
[ImportedPackage
(ImportReference missing ["my", "pkg"])
(Identifier "pkg")
(TypedPackage
dependencyPkg
[]
[monomorphicValue])
]
[usingMonomorphicValueFromImportedPackage])
`shouldSucceedWith`
MonomorphedPackage
myPkg
[]
Set.empty
(Set.fromList
[ monomorphicValuePrefixed
, usingMonomorphicValueFromImportedPackageMonomorphed
])
| oden-lang/oden | test/Oden/Compiler/MonomorphizationSpec.hs | mit | 10,375 | 0 | 17 | 2,655 | 2,565 | 1,314 | 1,251 | 298 | 1 |
import Control.Monad (guard)
import Data.Char
data Literal = Literal Bool Int Int Int deriving Show
type Clause = [Literal]
readValue v
| v `elem` ['1'..'9'] = (ord v) - (ord '1') + 1
| v `elem` ['A'..'Z'] = (ord v) - (ord 'A') + 1
| otherwise = error ("WTF? Cell value out of range: '" ++ (show v) ++ "'")
formatLiteral :: Int -> Literal -> Int
formatLiteral n (Literal b r c v) = if b then i else -i
where i = v + (c-1) * (n^2) + (r-1) * (n^4)
formatClauses :: Int -> [Clause] -> [[Int]]
formatClauses n cs = map f cs
where f c = (map (formatLiteral n) c) ++ [0]
printClauses :: Int -> [Clause] -> IO ()
printClauses n cs = mapM_ f (formatClauses n cs)
where f c = putStrLn $ unwords $ map show c
c1 :: Int -> [Clause]
c1 n = do r <- [1..n^2]; c <- [1..n^2]
return [(Literal True r c v) | v <- [1..n^2]]
c2 :: Int -> [Clause]
c2 n = do r <- [1..n^2]; c <- [1..n^2]
v <- [1..n^2]; v' <- [1..n^2]
guard (v /= v')
return [(Literal False r c v), (Literal False r c v')]
c3 :: Int -> [Clause]
c3 n = do r <- [1..n^2]; c <- [1..n^2]
v <- [1..n^2]; r' <- [1..n^2]
guard (r /= r')
return [(Literal False r c v), (Literal False r' c v)]
c4 :: Int -> [Clause]
c4 n = do r <- [1..n^2]; c <- [1..n^2]
v <- [1..n^2]; c' <- [1..n^2]
guard (c /= c')
return [(Literal False r c v), (Literal False r c' v)]
c5 :: Int -> [Clause]
c5 n = do r <- [1..n^2]; c <- [1..n^2]; v <- [1..n^2]
let i = (r-1) `div` n
let j = (c-1) `div` n
r' <- [(i*n+1)..(i*n+n)]
c' <- [(j*n+1)..(j*n+n)]
guard (r /= r')
guard (c /= c')
return [(Literal False r c v), (Literal False r' c' v)]
c6 :: Int -> String -> [Clause]
c6 n q = map toLit rcvs
where rcvs = filter ((/= '_') . snd) $ zip rcs $ filter (/= '\n') q
rcs = [(r, c) | r <- [1..n^2], c <- [1..n^2]]
toLit ((r, c), v) = [(Literal True r c (readValue v))]
main = do input <- getContents
let nsqrd = length $ head $ lines input
let n = floor $ sqrt $ (fromInteger (toInteger (nsqrd))::Float)
let cs = (c1 n) ++ (c2 n) ++ (c3 n) ++ (c4 n) ++ (c5 n) ++ (c6 n input)
putStrLn ("p cnf " ++ show (n^6) ++ " " ++ show (length cs))
printClauses n cs
| damelang/sdk2cnf | sdk2cnf.hs | mit | 2,332 | 0 | 16 | 720 | 1,471 | 761 | 710 | 55 | 2 |
{-# LANGUAGE CPP #-}
module Import where
import Yesod.Fay
import Language.Haskell.TH.Syntax (Exp)
import System.Process (readProcess)
-- | In a standard scaffolded site, @development@ is provided by
-- @Settings.Development@.
development :: Bool
#ifdef PRODUCTION
development = False
#else
development = True
#endif
fayFile' :: Exp -> FayFile
fayFile' staticR moduleName
| development = fayFileReload settings
| otherwise = fayFileProd settings
where
settings = (yesodFaySettings moduleName)
{ yfsSeparateRuntime = Just ("static", staticR)
-- , yfsPostProcess = readProcess "java" ["-jar", "closure-compiler.jar"]
, yfsExternal = Just ("static", staticR)
}
| fpco/yesod-fay | sample/Import.hs | mit | 708 | 0 | 10 | 136 | 133 | 77 | 56 | 14 | 1 |
module Output where
import Data.Text (Text)
import qualified Data.Text as Text
import System.Console.ANSI
printNorm :: Text -> IO ()
printNorm = putStr . Text.unpack
printInfo :: Text -> IO ()
printInfo txt = do
setSGR [ SetColor Foreground Dull Green ]
putStr (Text.unpack txt)
setSGR [Reset]
printInfoBold :: Text -> IO ()
printInfoBold txt = do
setSGR [ SetColor Foreground Dull Magenta ]
putStr (Text.unpack txt)
setSGR [Reset]
printWarn :: Text -> IO ()
printWarn txt = do
setSGR [ SetColor Foreground Dull Yellow ]
putStr (Text.unpack txt)
setSGR [Reset]
printError :: Text -> IO ()
printError txt = do
setSGR [ SetColor Foreground Dull Red ]
putStr (Text.unpack txt)
setSGR [Reset]
| toddmohney/branch-deleter | app/Output.hs | mit | 719 | 0 | 10 | 142 | 297 | 144 | 153 | 26 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Graphics.Urho3D.Graphics.Light(
Light
, PODVectorLightPtr
, BiasParameters(..)
, HasBias(..)
, HasSlopeScaleBias(..)
, CascadeParameters(..)
, HasSplit1(..)
, HasSplit2(..)
, HasSplit3(..)
, HasSplit4(..)
, HasFadeStart(..)
, HasBiasAutoAdjust(..)
, FocusParameters(..)
, HasFocus(..)
, HasNonUniform(..)
, HasAutoSize(..)
, HasQuantize(..)
, HasMinView(..)
, LightType(..)
, lightContext
, lightSetLightType
, lightSetRange
, lightSetPerVertex
, lightSetColor
, lightSetSpecularIntensity
, lightSetBrightness
, lightSetFov
, lightSetAspectRatio
, lightSetFadeDistance
, lightSetShadowFadeDistance
, lightSetShadowBias
, lightSetShadowCascade
, lightSetShadowFocus
, lightSetShadowIntensity
, lightSetShadowResolution
, lightSetShadowNearFarRatio
, lightSetRampTexture
, lightSetShapeTexture
, lightGetLightType
, lightGetPerVertex
, lightGetColor
, lightGetSpecularIntensity
, lightGetBrightness
, lightGetEffectiveColor
, lightGetEffectiveSpecularIntensity
, lightGetRange
, lightGetFov
, lightGetAspectRatio
, lightGetFadeDistance
, lightGetShadowFadeDistance
, lightGetShadowBias
, lightGetShadowCascade
, lightGetShadowFocus
, lightGetShadowIntensity
, lightGetShadowResolution
, lightGetShadowNearFarRatio
, lightGetRampTexture
, lightGetShapeTexture
, lightGetFrustum
, lightGetNumShadowSplits
, lightIsNegative
, LightSetIntensitySortValue(..)
, lightSetLightQueue
, lightGetVolumeTransform
, lightGetLightQueue
, lightGetIntensityDivisor
, lightSetRampTextureAttr
, lightSetShapeTextureAttr
, lightGetRampTextureAttr
, lightGetShapeTextureAttr
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import Graphics.Urho3D.Graphics.Internal.Light
import Graphics.Urho3D.Monad
import Data.Monoid
import System.IO.Unsafe (unsafePerformIO)
import Foreign
import Text.RawString.QQ
import Graphics.Urho3D.Math.StringHash
import Graphics.Urho3D.Scene.Node
import Graphics.Urho3D.Core.Object
import Graphics.Urho3D.Core.Variant
import Graphics.Urho3D.Container.Vector
import Graphics.Urho3D.Scene.Serializable
import Graphics.Urho3D.Scene.Animatable
import Graphics.Urho3D.Graphics.Internal.Drawable
import Graphics.Urho3D.Graphics.Texture
import Graphics.Urho3D.Graphics.Batch
import Graphics.Urho3D.Graphics.Camera
import Graphics.Urho3D.Scene.Component
import Graphics.Urho3D.Parent
import Graphics.Urho3D.Math.Color
import Graphics.Urho3D.Math.Frustum
import Graphics.Urho3D.Math.BoundingBox
import Graphics.Urho3D.Math.Matrix3x4
C.context (C.cppCtx
<> lightCntx
<> componentContext
<> stringHashContext
<> drawableCntx
<> animatableContext
<> serializableContext
<> objectContext
<> colorContext
<> frustumContext
<> textureContext
<> boundingBoxContext
<> batchContext
<> matrix3x4Context
<> variantContext
<> cameraContext)
C.include "<Urho3D/Graphics/Light.h>"
C.using "namespace Urho3D"
C.verbatim [r|
template <class T>
class Traits
{
public:
struct AlignmentFinder
{
char a;
T b;
};
enum {AlignmentOf = sizeof(AlignmentFinder) - sizeof(T)};
};
|]
podVectorPtr "Light"
lightContext :: C.Context
lightContext = lightCntx <> componentContext <> stringHashContext
deriveParents [''Object, ''Serializable, ''Animatable, ''Component, ''Drawable] ''Light
instance NodeComponent Light where
nodeComponentType _ = unsafePerformIO $ StringHash . fromIntegral <$> [C.exp|
unsigned int { Light::GetTypeStatic().Value() } |]
-- | Light types
data LightType =
LT'Directional
| LT'Spot
| LT'Point
deriving (Eq, Show, Read, Enum, Bounded)
instance Storable BiasParameters where
sizeOf _ = fromIntegral $ [C.pure| int { (int)sizeof(BiasParameters) } |]
alignment _ = fromIntegral $ [C.pure| int { (int)Traits<BiasParameters>::AlignmentOf } |]
peek ptr = do
_biasParametersBias <- realToFrac <$> [C.exp| float {$(BiasParameters* ptr)->constantBias_} |]
_biasParametersSlopeScaleBias <- realToFrac <$> [C.exp| float {$(BiasParameters* ptr)->slopeScaledBias_} |]
return BiasParameters {..}
poke ptr (BiasParameters {..}) = [C.block| void {
$(BiasParameters* ptr)->constantBias_ = $(float _biasParametersBias');
$(BiasParameters* ptr)->slopeScaledBias_ = $(float _biasParametersSlopeScaleBias');
} |]
where
_biasParametersBias' = realToFrac _biasParametersBias
_biasParametersSlopeScaleBias' = realToFrac _biasParametersSlopeScaleBias
instance Storable CascadeParameters where
sizeOf _ = fromIntegral $ [C.pure| int { (int)sizeof(CascadeParameters) } |]
alignment _ = fromIntegral $ [C.pure| int { (int)Traits<CascadeParameters>::AlignmentOf } |]
peek ptr = do
_cascadeParametersSplit1 <- realToFrac <$> [C.exp| float { $(CascadeParameters* ptr)->splits_[0] } |]
_cascadeParametersSplit2 <- realToFrac <$> [C.exp| float { $(CascadeParameters* ptr)->splits_[1] } |]
_cascadeParametersSplit3 <- realToFrac <$> [C.exp| float { $(CascadeParameters* ptr)->splits_[2] } |]
_cascadeParametersSplit4 <- realToFrac <$> [C.exp| float { $(CascadeParameters* ptr)->splits_[3] } |]
_cascadeParametersFadeStart <- realToFrac <$> [C.exp| float { $(CascadeParameters* ptr)->fadeStart_ } |]
_cascadeParametersBiasAutoAdjust <- realToFrac <$> [C.exp| float { $(CascadeParameters* ptr)->biasAutoAdjust_ } |]
return CascadeParameters {..}
poke ptr (CascadeParameters {..}) = [C.block| void {
$(CascadeParameters* ptr)->splits_[0] = $(float _cascadeParametersSplit1');
$(CascadeParameters* ptr)->splits_[1] = $(float _cascadeParametersSplit2');
$(CascadeParameters* ptr)->splits_[2] = $(float _cascadeParametersSplit3');
$(CascadeParameters* ptr)->splits_[3] = $(float _cascadeParametersSplit4');
$(CascadeParameters* ptr)->fadeStart_ = $(float _cascadeParametersFadeStart');
$(CascadeParameters* ptr)->biasAutoAdjust_ = $(float _cascadeParametersBiasAutoAdjust');
} |]
where
_cascadeParametersSplit1' = realToFrac _cascadeParametersSplit1
_cascadeParametersSplit2' = realToFrac _cascadeParametersSplit2
_cascadeParametersSplit3' = realToFrac _cascadeParametersSplit3
_cascadeParametersSplit4' = realToFrac _cascadeParametersSplit4
_cascadeParametersFadeStart' = realToFrac _cascadeParametersFadeStart
_cascadeParametersBiasAutoAdjust' = realToFrac _cascadeParametersBiasAutoAdjust
instance Storable FocusParameters where
sizeOf _ = fromIntegral $ [C.pure| int { (int)sizeof(FocusParameters) } |]
alignment _ = fromIntegral $ [C.pure| int { (int)Traits<FocusParameters>::AlignmentOf } |]
peek ptr = do
_focusParametersFocus <- toBool <$> [C.exp| int { (int)$(FocusParameters* ptr)->focus_ } |]
_focusParametersNonUniform <- toBool <$> [C.exp| int { (int)$(FocusParameters* ptr)->nonUniform_ } |]
_focusParametersAutoSize <- toBool <$> [C.exp| int { (int)$(FocusParameters* ptr)->autoSize_ } |]
_focusParametersQuantize <- realToFrac <$> [C.exp| float { $(FocusParameters* ptr)->quantize_ } |]
_focusParametersMinView <- realToFrac <$> [C.exp| float { $(FocusParameters* ptr)->minView_ } |]
return FocusParameters {..}
poke ptr (FocusParameters {..}) = [C.block| void {
$(FocusParameters* ptr)->focus_ = $(int _focusParametersFocus') != 0;
$(FocusParameters* ptr)->nonUniform_ = $(int _focusParametersNonUniform') != 0;
$(FocusParameters* ptr)->autoSize_ = $(int _focusParametersAutoSize') != 0;
$(FocusParameters* ptr)->quantize_ = $(float _focusParametersQuantize');
$(FocusParameters* ptr)->minView_ = $(float _focusParametersMinView');
} |]
where
_focusParametersFocus' = fromBool _focusParametersFocus
_focusParametersNonUniform' = fromBool _focusParametersNonUniform
_focusParametersAutoSize' = fromBool _focusParametersAutoSize
_focusParametersQuantize' = realToFrac _focusParametersQuantize
_focusParametersMinView' = realToFrac _focusParametersMinView
-- | Set light type
lightSetLightType :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to light
-> LightType -- ^ Type of light
-> m ()
lightSetLightType p lt = liftIO $ do
let ptr = parentPointer p
i = fromIntegral $ fromEnum lt
[C.exp| void { $(Light* ptr)->SetLightType((LightType)$(int i)) } |]
-- | Set range.
lightSetRange :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to light
-> Float -- ^ Light max range
-> m ()
lightSetRange p v = liftIO $ do
let ptr = parentPointer p
v' = realToFrac v
[C.exp| void { $(Light* ptr)->SetRange($(float v')) } |]
-- | Set vertex lighting mode.
lightSetPerVertex :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Bool -- ^ enable
-> m ()
lightSetPerVertex p e = liftIO $ do
let ptr = parentPointer p
e' = fromBool e
[C.exp| void {$(Light* ptr)->SetPerVertex($(int e') != 0)} |]
-- | Set color.
lightSetColor :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Color -- ^ color
-> m ()
lightSetColor p c = liftIO $ with c $ \c' -> do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetColor(*$(Color* c'))} |]
-- | Set specular intensity. Zero disables specular calculations.
lightSetSpecularIntensity :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Float -- ^ intensity
-> m ()
lightSetSpecularIntensity p d = liftIO $ do
let ptr = parentPointer p
d' = realToFrac d
[C.exp| void {$(Light* ptr)->SetSpecularIntensity($(float d'))} |]
-- | Set light brightness multiplier. Both the color and specular intensity are multiplied with this to get final values for rendering.
lightSetBrightness :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Float -- ^ brightness
-> m ()
lightSetBrightness p d = liftIO $ do
let ptr = parentPointer p
d' = realToFrac d
[C.exp| void {$(Light* ptr)->SetBrightness($(float d'))} |]
-- | Set spotlight field of view.
lightSetFov :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Float -- ^ fov
-> m ()
lightSetFov p d = liftIO $ do
let ptr = parentPointer p
d' = realToFrac d
[C.exp| void {$(Light* ptr)->SetFov($(float d'))} |]
-- | Set spotlight aspect ratio.
lightSetAspectRatio :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Float -- ^ aspect ratio
-> m ()
lightSetAspectRatio p d = liftIO $ do
let ptr = parentPointer p
d' = realToFrac d
[C.exp| void {$(Light* ptr)->SetAspectRatio($(float d'))} |]
-- | Set fade out start distance.
lightSetFadeDistance :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Float -- ^ distance
-> m ()
lightSetFadeDistance p d = liftIO $ do
let ptr = parentPointer p
d' = realToFrac d
[C.exp| void {$(Light* ptr)->SetFadeDistance($(float d'))} |]
-- | Set shadow fade out start distance. Only has effect if shadow distance is also non-zero.
lightSetShadowFadeDistance :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Float -- ^ distance
-> m ()
lightSetShadowFadeDistance p d = liftIO $ do
let ptr = parentPointer p
d' = realToFrac d
[C.exp| void {$(Light* ptr)->SetShadowFadeDistance($(float d'))} |]
-- | Set shadow depth bias parameters.
lightSetShadowBias :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> BiasParameters -- ^ parameters
-> m ()
lightSetShadowBias p bp = liftIO $ with bp $ \bp' -> do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetShadowBias(*$(BiasParameters* bp'))} |]
-- | Set directional light cascaded shadow parameters.
lightSetShadowCascade :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> CascadeParameters -- ^ parameters
-> m ()
lightSetShadowCascade p cp = liftIO $ with cp $ \cp' -> do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetShadowCascade(*$(CascadeParameters* cp'))} |]
-- | Set shadow map focusing parameters.
lightSetShadowFocus :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> FocusParameters -- ^ parameters
-> m ()
lightSetShadowFocus p fp = liftIO $ with fp $ \fp' -> do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetShadowFocus(*$(FocusParameters* fp'))} |]
-- | Set light intensity in shadow between 0.0 - 1.0. 0.0 (the default) gives fully dark shadows.
lightSetShadowIntensity :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Float -- ^ itensity
-> m ()
lightSetShadowIntensity p i = liftIO $ do
let ptr = parentPointer p
i' = realToFrac i
[C.exp| void {$(Light* ptr)->SetShadowIntensity($(float i'))} |]
-- | Set shadow resolution between 0.25 - 1.0. Determines the shadow map to use.
lightSetShadowResolution :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Float -- ^ resoulution
-> m ()
lightSetShadowResolution p rs = liftIO $ do
let ptr = parentPointer p
rs' = realToFrac rs
[C.exp| void {$(Light* ptr)->SetShadowResolution($(float rs'))} |]
-- | Set shadow camera near/far clip distance ratio.
lightSetShadowNearFarRatio :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Float -- ^ near far ration
-> m ()
lightSetShadowNearFarRatio p rs = liftIO $ do
let ptr = parentPointer p
rs' = realToFrac rs
[C.exp| void {$(Light* ptr)->SetShadowNearFarRatio($(float rs'))} |]
-- | Set range attenuation texture.
lightSetRampTexture :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Ptr Texture -- ^ texture
-> m ()
lightSetRampTexture p ptex = liftIO $ do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetRampTexture($(Texture* ptex))} |]
-- | Set spotlight attenuation texture.
lightSetShapeTexture :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Ptr Texture -- ^ texture
-> m ()
lightSetShapeTexture p ptex = liftIO $ do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetShapeTexture($(Texture* ptex))} |]
-- | Return light type.
lightGetLightType :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m LightType
lightGetLightType p = liftIO $ do
let ptr = parentPointer p
toEnum . fromIntegral <$> [C.exp| int {(int)$(Light* ptr)->GetLightType()} |]
-- | Return vertex lighting mode.
lightGetPerVertex :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Bool
lightGetPerVertex p = liftIO $ do
let ptr = parentPointer p
toBool <$> [C.exp| int {(int)$(Light* ptr)->GetPerVertex()} |]
-- | Return color.
lightGetColor :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Color
lightGetColor p = liftIO $ do
let ptr = parentPointer p
peek =<< [C.exp| const Color* {&$(Light* ptr)->GetColor()} |]
-- | Return specular intensity.
lightGetSpecularIntensity :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetSpecularIntensity p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetSpecularIntensity()} |]
-- | Return brightness multiplier.
lightGetBrightness :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetBrightness p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetBrightness()} |]
-- | Return effective color, multiplied by brightness. Do not multiply the alpha so that can compare against the default black color to detect a light with no effect.
lightGetEffectiveColor :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Color
lightGetEffectiveColor p = liftIO $ alloca $ \resptr -> do
let ptr = parentPointer p
[C.exp| void {
*($(Color* resptr)) = $(Light* ptr)->GetEffectiveColor()
} |]
peek resptr
-- | Return effective specular intensity, multiplied by absolute value of brightness.
lightGetEffectiveSpecularIntensity :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetEffectiveSpecularIntensity p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetEffectiveSpecularIntensity()} |]
-- | Return range.
lightGetRange :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetRange p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetRange()} |]
-- | Return spotlight field of view.
lightGetFov :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetFov p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetFov()} |]
-- | Return spotlight aspect ratio.
lightGetAspectRatio :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetAspectRatio p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetAspectRatio()} |]
-- | Return fade start distance.
lightGetFadeDistance :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetFadeDistance p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetFadeDistance()} |]
-- | Return shadow fade start distance.
lightGetShadowFadeDistance :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetShadowFadeDistance p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetShadowFadeDistance()} |]
-- | Return shadow depth bias parameters.
lightGetShadowBias :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m BiasParameters
lightGetShadowBias p = liftIO $ do
let ptr = parentPointer p
peek =<< [C.exp| const BiasParameters* {&$(Light* ptr)->GetShadowBias()} |]
-- | Return directional light cascaded shadow parameters.
lightGetShadowCascade :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m CascadeParameters
lightGetShadowCascade p = liftIO $ do
let ptr = parentPointer p
peek =<< [C.exp| const CascadeParameters* {&$(Light* ptr)->GetShadowCascade()} |]
-- | Return shadow map focus parameters.
lightGetShadowFocus :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m FocusParameters
lightGetShadowFocus p = liftIO $ do
let ptr = parentPointer p
peek =<< [C.exp| const FocusParameters* {&$(Light* ptr)->GetShadowFocus()} |]
-- | Return light intensity in shadow.
lightGetShadowIntensity :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetShadowIntensity p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetShadowIntensity()} |]
-- | Return shadow camera near/far clip distance ratio.
lightGetShadowResolution :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetShadowResolution p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetShadowResolution()} |]
-- | Return shadow camera near/far clip distance ratio.
lightGetShadowNearFarRatio :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetShadowNearFarRatio p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetShadowNearFarRatio()} |]
-- | Return range attenuation texture.
lightGetRampTexture :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m (Ptr Texture)
lightGetRampTexture p = liftIO $ do
let ptr = parentPointer p
[C.exp| Texture* {$(Light* ptr)->GetRampTexture()} |]
-- | Return spotlight attenuation texture.
lightGetShapeTexture :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m (Ptr Texture)
lightGetShapeTexture p = liftIO $ do
let ptr = parentPointer p
[C.exp| Texture* {$(Light* ptr)->GetShapeTexture()} |]
-- | Return spotlight frustum.
lightGetFrustum :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Frustum
lightGetFrustum p = liftIO $ alloca $ \resptr -> do
let ptr = parentPointer p
[C.exp| void {
*($(Frustum* resptr)) = $(Light* ptr)->GetFrustum()
} |]
peek resptr
-- | Return number of shadow map cascade splits for a directional light, considering also graphics API limitations.
lightGetNumShadowSplits :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Int
lightGetNumShadowSplits p = liftIO $ do
let ptr = parentPointer p
fromIntegral <$> [C.exp| int {$(Light* ptr)->GetNumShadowSplits()} |]
-- | Return whether light has negative (darkening) color.
lightIsNegative :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Bool
lightIsNegative p = liftIO $ do
let ptr = parentPointer p
toBool <$> [C.exp| int {(int)$(Light* ptr)->IsNegative()} |]
class LightSetIntensitySortValue a where
lightSetIntensitySortValue :: (Parent Light b, Pointer p b, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> a -- ^ value
-> m ()
-- | Set sort value based on intensity and view distance.
instance LightSetIntensitySortValue Float where
lightSetIntensitySortValue p d = liftIO $ do
let ptr = parentPointer p
d' = realToFrac d
[C.exp| void {$(Light* ptr)->SetIntensitySortValue($(float d'))} |]
-- | Set sort value based on overall intensity over a bounding box.
instance LightSetIntensitySortValue BoundingBox where
lightSetIntensitySortValue p b = liftIO $ with b $ \b' -> do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetIntensitySortValue(*$(BoundingBox* b'))} |]
-- | Set light queue used for this light. Called by View.
lightSetLightQueue :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Ptr LightBatchQueue
-> m ()
lightSetLightQueue p pb = liftIO $ do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetLightQueue($(LightBatchQueue* pb))} |]
-- | Return light volume model transform.
lightGetVolumeTransform :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> Ptr Camera -- ^ camera
-> m Matrix3x4
lightGetVolumeTransform p pcam = liftIO $ alloca $ \resptr -> do
let ptr = parentPointer p
[C.exp| void {
*($(Matrix3x4* resptr)) = $(Light* ptr)->GetVolumeTransform($(Camera* pcam))
} |]
peek resptr
-- | Return light queue. Called by View.
lightGetLightQueue :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m (Ptr LightBatchQueue)
lightGetLightQueue p = liftIO $ do
let ptr = parentPointer p
[C.exp| LightBatchQueue* {$(Light* ptr)->GetLightQueue()} |]
-- | Return a divisor value based on intensity for calculating the sort value.
lightGetIntensityDivisor :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m Float
lightGetIntensityDivisor p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Light* ptr)->GetIntensityDivisor()} |]
-- | Set ramp texture attribute.
lightSetRampTextureAttr :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> ResourceRef -- ^ value
-> m ()
lightSetRampTextureAttr p rf = liftIO $ with rf $ \rf' -> do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetRampTextureAttr(*$(ResourceRef* rf'))} |]
-- | Set shape texture attribute.
lightSetShapeTextureAttr :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> ResourceRef -- ^ value
-> m ()
lightSetShapeTextureAttr p rf = liftIO $ with rf $ \rf' -> do
let ptr = parentPointer p
[C.exp| void {$(Light* ptr)->SetShapeTextureAttr(*$(ResourceRef* rf'))} |]
-- | Return ramp texture attribute.
lightGetRampTextureAttr :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m ResourceRef
lightGetRampTextureAttr p = liftIO $ alloca $ \resptr -> do
let ptr = parentPointer p
[C.exp| void {
*($(ResourceRef* resptr)) = $(Light* ptr)->GetRampTextureAttr()
} |]
peek resptr
-- | Return shape texture attribute.
lightGetShapeTextureAttr :: (Parent Light a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to Light or ascentor
-> m ResourceRef
lightGetShapeTextureAttr p = liftIO $ alloca $ \resptr -> do
let ptr = parentPointer p
[C.exp| void {
*($(ResourceRef* resptr)) = $(Light* ptr)->GetShapeTextureAttr()
} |]
peek resptr
| Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/Graphics/Light.hs | mit | 25,129 | 0 | 22 | 4,577 | 5,544 | 3,014 | 2,530 | -1 | -1 |
{-# LANGUAGE OverloadedLists #-}
module Data.Json.Schema.Validation
(
isValidFor
, validate
, schemaToJSON
) where
import Data.Json.Schema.Types
import Data.Aeson hiding (Object, Number, Array, String, Bool)
import qualified Data.Aeson as A
import Data.Maybe
import qualified Data.HashMap.Strict as HM
import Data.Text hiding (all, any)
isValidFor :: Value -> Schema -> Bool
isValidFor = flip validate
validate :: Schema -> Value -> Bool
validate (Bool _) (A.Bool _) = True
validate (Number _) (A.Number _) = True
validate (String _) (A.String _) = True
validate (Array ss) (A.Array vs) = all (\v -> any (`validate` v) ss) vs
validate (Object ss) (A.Object vs) = HM.foldlWithKey' (\a k s -> a && validateField s vs k) True ss
validate _ _ = False
validateField :: Field -> HM.HashMap Text Value -> Text -> Bool
validateField (Field Plain s) m key = fromMaybe False $ validate s <$> HM.lookup key m
validateField (Field Exact s) m key = fromMaybe False $ (== schemaToJSON s) <$> HM.lookup key m
validateField (Field Optional s) m key = fromMaybe True $ validate s <$> HM.lookup key m
validateField (Field Flat s@(Array ss)) m key = case HM.lookup key m of
Just v -> validate s (A.Array [v])
_ -> False
validateField _ _ _ = False
schemaToJSON :: Schema -> Value
schemaToJSON (Bool b) = A.Bool b
schemaToJSON (Number n) = A.Number n
schemaToJSON (String s) = A.String s
schemaToJSON (Array a) = A.Array (schemaToJSON <$> a)
schemaToJSON (Object o) = A.Object $ (\(Field _ s) -> schemaToJSON s) <$> o
| benweitzman/quick-schema | src/Data/Json/Schema/Validation.hs | mit | 1,537 | 0 | 11 | 291 | 675 | 352 | 323 | 35 | 2 |
module T where
import Tests.KesterelBasis
-- Information flows backwards, so it's not constructive.
e = signalE $ \s ->
(presentE s
pauseE
nothingE)
>>> emitE s
c = unitA >>> runE e
prop_correct = property (\xs -> simulate c xs == zip (bottom : bottom : repeat false) xs)
test_constructive = isNothing (isConstructive c)
ok_netlist = runNL c
| peteg/ADHOC | Tests/08_Kesterel/022_signal_present_non_constructive.hs | gpl-2.0 | 361 | 4 | 12 | 77 | 123 | 64 | 59 | 11 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Baum.RedBlack.Type where
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
data RedBlackColor = Red | Black
deriving ( Eq, Typeable )
data RedBlackTree a = Empty
| RedBlackTree RedBlackColor ( RedBlackTree a ) a ( RedBlackTree a )
deriving ( Eq, Typeable )
$(derives [makeReader, makeToDoc] [''RedBlackTree])
$(derives [makeReader, makeToDoc] [''RedBlackColor])
instance Functor RedBlackTree where
fmap f = foldt ( \ color left key right -> RedBlackTree color left ( f key ) right ) Empty
isLeaf :: RedBlackTree a -> Bool
isLeaf Empty = True
isLeaf _ = False
foldt redblacktree empty Empty = empty
foldt redblacktree empty ( RedBlackTree color left key right ) = redblacktree color ( foldt redblacktree empty left ) key ( foldt redblacktree empty right )
| Erdwolf/autotool-bonn | src/Baum/RedBlack/Type.hs | gpl-2.0 | 856 | 0 | 11 | 153 | 275 | 145 | 130 | 19 | 1 |
{-
################################################################################
# Changelog #
################################################################################
#
# 17.04.2009, chbauman:
# renamed 'test' to 'haskell_backend_internal_equality_test'
-}
--haskell_backend_internal_equality_test :: (Ord a, Fractional a) => a -> a -> Bool
haskell_backend_internal_equality_test x y = (abs (x - y)) < (1 / (10^15))
| collective/ECSpooler | backends/haskell/toleranceTest.hs | gpl-2.0 | 503 | 0 | 9 | 115 | 44 | 24 | 20 | 1 | 1 |
module Network.Refraction.FairExchange.Alice
( runAlice
) where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Chan (Chan, readChan)
import Control.Monad (guard, liftM)
import Control.Monad.CryptoRandom (crandomRs)
import Crypto.Random.DRBG (CtrDRBG, newGenIO)
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Lazy as BL
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Maybe (fromMaybe)
import qualified Data.Serialize as S
import Data.Word
import Debug.Trace
import Network.Haskoin.Crypto
import Network.Haskoin.Script
import Network.Haskoin.Transaction
import Network.Haskoin.Util
import Network.Refraction.BitcoinUtils
import Network.Refraction.Blockchain (broadcastTx, fetchTx, fetchSpentTxId)
import Network.Refraction.Discover (Location)
import Network.Refraction.FairExchange.Types
import Network.Refraction.Generator
import Network.Refraction.PeerToPeer (Msg, sendMessage)
import Network.Refraction.Tor(secureConnect)
runAlice :: Chan Msg -> KeyPair -> KeyPair -> Tx -> [Secret] -> Location -> IO ()
runAlice chan keypair refundKeypair lastTx mySecrets theirLocation = do
putStrLn "Running Alice fair exchange protocol..."
(bPub, bRefundPub, sumHashes) <- setupAliceSecrets chan keypair refundKeypair mySecrets theirLocation
(aCommit, bCommit, bCommitRedeem) <- aliceCommit chan keypair bPub sumHashes lastTx theirLocation
aliceClaim keypair aCommit bCommit bCommitRedeem mySecrets
putStrLn "alice is done"
setupAliceSecrets :: Chan Msg
-> KeyPair
-> KeyPair
-> [Secret]
-> Location
-> IO (PubKey, PubKey, [Text])
setupAliceSecrets chan (_, aPub) (_, refundPub) mySecrets theirLocation = do
putStrLn "Alice setting up secrets..."
send theirLocation . BL.toStrict . A.encode $ AliceKeysMessage aPub refundPub mySecrets
bobKeys <- liftM (fromMaybe undefined . A.decodeStrict') $ readChan chan
indices <- liftM (take numChallenges) $ shuffle [0..numSecrets - 1]
send theirLocation . BL.toStrict . A.encode $ indices
bobSecrets <- liftM decodeSecrets (readChan chan)
verifySecrets bobSecrets mySecrets (map decodeHashes $ bHashes bobKeys) (map decodeHashes $ bSumHashes bobKeys)
putStrLn "Alice done setting up secrets!"
return (bKey1 bobKeys, bKey2 bobKeys, bSumHashes bobKeys)
where
decodeHashes = either printErr id . S.decode . hexTextToBs
decodeSecrets = fromMaybe undefined . A.decodeStrict'
verifySecrets :: [Secret] -> [Secret] -> [Hash256] -> [Hash256] -> IO Bool
verifySecrets bSecrets aSecrets bHashes sumHashes = return True
shuffle :: [a] -> IO [a]
shuffle [] = return []
shuffle xs = do
g <- newGenIO :: IO CtrDRBG
let (ys, (v:zs)) = splitAt (head $ crandomRs (0, length xs - 1) g) xs
liftM ((:) v) $ shuffle (ys ++ zs)
hexTextToBs :: Text -> B.ByteString
hexTextToBs = fromMaybe undefined . decodeHex . encodeUtf8
where
-- TODO(hudon): is this a re-implementation of Haskoin.Util.decodeHex?
decodeHex bs =
let (x, b) = B16.decode bs
in guard (b == B.empty) >> return x
aliceCommit :: Chan Msg -> KeyPair -> PubKey -> [Text] -> Tx -> Location -> IO (Tx, Tx, Script)
aliceCommit chan (prv, pub) bPub sumHashes lastTx theirLocation = do
putStrLn "Alice is committing..."
bCommitRedeem <- liftM (either printErr id . S.decode . fromMaybe undefined . decodeHex) $ readChan chan
print "received bob's redeem script"
print bCommitRedeem
--verifyRedeem bCommitRedeem
send theirLocation . encodeHex $ S.encode "ok"
bCommitHash <- liftM (either printErr id . S.decode . fromMaybe undefined . decodeHex) $ readChan chan
print "received bob's commit hash"
print bCommitHash
bCommit <- liftM (fromMaybe undefined) $ fetchTx bCommitHash
-- TODO(hudon) wait for bob commit confirmations
-- NOTE: assumes the first output is the ad message op_return so naively selects the second
let (_:utxo:_) = getUTXOs lastTx
-- TODO(hudon) clean up these fromEither/fromMaybe
bsToHash256 bs = either (const Nothing) Just (S.decode bs)
sumHashes256 = map (fromMaybe undefined . bsToHash256 . fromMaybe undefined . decodeHex . encodeUtf8) sumHashes
let Right (tx, aCommitRedeem) = makeAliceCommit [utxo] [prv] pub bPub sumHashes256
print "Sending redeem script"
print aCommitRedeem
send theirLocation . encodeHex $ S.encode aCommitRedeem
bobVerification <- readChan chan
broadcastTx tx
putStrLn "Sending commit hash to bob..."
print $ txHash tx
send theirLocation . encodeHex . S.encode $ txHash tx
putStrLn "Alice committed!"
return (tx, bCommit, bCommitRedeem)
aliceClaim :: KeyPair -> Tx -> Tx -> Script -> [Integer] -> IO ()
aliceClaim (prv, pub) aCommit bCommit bCommitRedeem aSecrets = do
putStrLn "Alice is claiming..."
bClaim <- liftM (fromMaybe undefined) $ waitForBobClaim aCommit
-- TODO(hudon) expand pattern we're matching on to catch errors
let Right bSecret = getBSecret bClaim aSecrets
(utxo:_) = getUTXOs bCommit
Right tx = makeAliceClaim [utxo] [prv] bCommitRedeem bSecret pub
broadcastTx tx
putStrLn "Alice claimed!"
waitForBobClaim :: Tx -> IO (Maybe Tx)
waitForBobClaim tx = do
putStrLn "Waiting for bob's claim..."
fetchSpentTxId (txHash tx) 0 >>= maybe loop fetchTx
where loop = threadDelay 30000000 >> waitForBobClaim tx
-- TODO(hudon) don't assume it's the first input
getBSecret :: Tx -> [Integer] -> Either String Integer
getBSecret tx aSecrets = do
sums <- decodeSums $ head $ txIn tx
return $ (head sums) - (head aSecrets)
where
decodeSums txin = do
r <- S.decode $ scriptInput txin
let ops = scriptOps r
-- TODO(hudon) in the future we'll only have (numSecrets - numChallenges) inputs
opsSplit = splitAt numSecrets ops
getPushData (OP_PUSHDATA bs _) = S.decode bs
mapM getPushData $ fst opsSplit
-- TODO(hudon) implement me
verifyRedeem :: a -> Bool
verifyRedeem = const True
send :: Location -> Msg -> IO ()
send loc x = secureConnect loc (sendMessage x) >> return ()
printErr x = traceShow x undefined
| hudon/refraction-hs | src/Network/Refraction/FairExchange/Alice.hs | gpl-3.0 | 6,343 | 0 | 16 | 1,268 | 1,905 | 956 | 949 | 120 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Applicative
import Control.Monad (liftM, mzero)
import Data.Aeson
import Data.Aeson.Types (parseMaybe)
import Data.HashMap.Strict (toList)
import Data.List (intercalate)
import Data.Time (LocalTime)
import Data.Time.Calendar (addDays, Day)
import Data.Time.Clock (getCurrentTime, addUTCTime, UTCTime)
import Data.Time.Format (readTime, formatTime, FormatTime, defaultTimeLocale)
import Data.Time.LocalTime (localDay)
import Network.Google.OAuth2
import Network.HTTP.Base (urlEncode)
import Network.HTTP.Conduit (simpleHttp)
import System.Directory (doesFileExist)
import System.Environment (getArgs)
import System.Posix.Env (getEnv)
import System.Posix.Files
import System.Process (rawSystem)
import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Data.Text as T
data Event = Event { summary :: String
, description :: Maybe String
, start :: DateTime
, end :: DateTime
} deriving Show
instance FromJSON Event where
parseJSON (Object v) = Event <$>
v .: "summary" <*>
v .:? "description" <*>
v .: "start" <*>
v .: "end"
data DateTime = Date Day | DateTime LocalTime
instance Show DateTime where
show (Date d) = formatLocalTime "%F %a" d
show (DateTime dt) = formatLocalTime "%F %a %R" dt
instance FromJSON DateTime where
parseJSON (Object hm) = return $
let [x] = toList hm >>= parse in x where
parse ("date", String d) = [Date $ textToTime "%F" d]
parse ("dateTime", String dt) = [DateTime $ textToTime "%FT%T%z" dt]
parse _ = []
textToTime fmt = readTime defaultTimeLocale fmt . T.unpack
data Calendar = Calendar { calendarId :: T.Text
, calendarSummary :: T.Text
} deriving Show
instance FromJSON Calendar where
parseJSON (Object o) = Calendar <$>
o .: "id" <*>
o .: "summary"
oAuthClient = OAuth2Client { clientId = "200701486136-td9daeuse8917ai8v4ojgpkf8ofblvv6.apps.googleusercontent.com"
, clientSecret = "n45wv56dJvFOqW6eaDz9Td7g"
}
permissionUrl = formUrl oAuthClient
["https://www.googleapis.com/auth/calendar.readonly"]
oAuthTokenFile :: IO String
oAuthTokenFile = do
maybeFile <- getEnv "HS_GCAL2ORG_OAUTH_TOKEN_FILE"
case maybeFile of
Just file -> return file
Nothing -> liftM defaultFile $ getEnv "HOME"
where defaultFile (Just home) = home ++ "/.hs-gcal2org-oauth-token"
defaultFile Nothing = error "cannot find user home"
oAuthToken :: IO String
oAuthToken = do
file <- oAuthTokenFile
tokenExists <- doesFileExist file
tokens <- if tokenExists
then do oldTokensStr <- readFile file
refreshTokens oAuthClient $ read oldTokensStr
else do putStrLn $ "Load URL: " ++ show permissionUrl
rawSystem "xdg-open" [permissionUrl]
putStrLn "Please paste the verification code:"
getLine >>= exchangeCode oAuthClient
writeFile file $ show tokens
setFileMode file $ unionFileModes ownerReadMode ownerWriteMode
return $ accessToken tokens
formatLocalTime :: FormatTime t => String -> t -> String
formatLocalTime = formatTime defaultTimeLocale
timeAround :: UTCTime -> (String, String)
timeAround t = let dt = 60 * 60 * 24 * 7
add d = formatLocalTime "%FT%T%z" $ addUTCTime d t
in (add (negate dt), add dt)
listEventsUri :: String -> String -> String -> String -> String
listEventsUri accessToken timeMin timeMax calendarId =
"https://www.googleapis.com/calendar/v3/calendars/" ++
urlEncode calendarId ++ "/events?" ++
parameters [ ("singleEvents", "true")
, ("timeMin", timeMin)
, ("timeMax", timeMax)
, ("access_token", accessToken)
]
where parameters xs = intercalate "&" $ map pairToParam xs
pairToParam (k, v) = k ++ "=" ++ urlEncode v
orgTimestamp :: DateTime -> DateTime -> String
orgTimestamp s@(Date s1) (Date e2)
| s1 == e1 = "<" ++ show s ++ ">"
| otherwise = "<" ++ show s ++ ">--<" ++ show e ++ ">"
where e1 = addDays (-1) e2
e = Date e1
orgTimestamp s@(DateTime s1) e@(DateTime e1)
| localDay s1 == localDay e1 = "<" ++ show s ++ "-" ++
formatLocalTime "%R" e1 ++ ">"
| otherwise = "<" ++ show s ++ ">--<" ++ show e ++ ">"
eventToOrg :: Event -> String
eventToOrg (Event s d st ed) = "** " ++ s ++ "\n" ++
" " ++ orgTimestamp st ed ++
case d of Just d -> '\n' : d
Nothing -> ""
printEvents :: String -> [Event] -> IO ()
printEvents title xs = do putStrLn $ "* " ++ title
mapM_ (putStrLn . eventToOrg) xs
decodeJSON :: (FromJSON a) => BS.ByteString -> T.Text -> (a -> b) -> b
decodeJSON json key f = case decode json >>= parseMaybe (.: key) of
Just x -> f x
Nothing -> error $ "cannot decode JSON: " ++ BS.unpack json
printCalendar :: String -> UTCTime -> String -> IO ()
printCalendar token time id = do
let (timeMin, timeMax) = timeAround time
json <- simpleHttp $ listEventsUri token timeMin timeMax id
decodeJSON json "items" $ printEvents id
calendarList :: String -> IO [Calendar]
calendarList token = do
let uri = "https://www.googleapis.com/calendar/v3/users/me/calendarList" ++
"?access_token=" ++ token
json <- simpleHttp uri
decodeJSON json "items" return
main = do
calendarIds <- getArgs
token <- oAuthToken
time <- getCurrentTime
case calendarIds of
[] -> calendarList token >>= mapM_ print
_ -> mapM_ (printCalendar token time) calendarIds
| Yuhta/hs-gcal2org | Main.hs | gpl-3.0 | 6,088 | 0 | 13 | 1,795 | 1,761 | 900 | 861 | 134 | 3 |
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS -Wall -Werror #-}
module InferAssert where
import AnnotatedExpr
import Control.Applicative ((<$>), Applicative(..))
import Control.Lens.Operators
import Control.Monad (void)
import Control.Monad.Trans.State (runStateT, runState)
import InferWrappers
import Lamdu.Data.Arbitrary () -- Arbitrary instance
import Lamdu.Data.Expression.IRef (DefI)
import System.IO (hPutStrLn, stderr)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (assertBool)
import Utils
import qualified Control.DeepSeq as DeepSeq
import qualified Control.Exception as E
import qualified Control.Lens as Lens
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Lamdu.Data.Expression as Expr
import qualified Lamdu.Data.Expression.IRef as ExprIRef
import qualified Lamdu.Data.Expression.Infer as Infer
import qualified Lamdu.Data.Expression.Infer.ImplicitVariables as ImplicitVariables
import qualified Lamdu.Data.Expression.Utils as ExprUtil
import qualified System.Random as Random
import qualified Test.Framework as TestFramework
import qualified Test.HUnit as HUnit
canonizeInferred :: InferResults t -> InferResults t
canonizeInferred =
ExprUtil.randomizeParamIdsG ExprUtil.debugNameGen Map.empty canonizePayload
where
canonizePayload gen guidMap (ival, ityp) =
( ExprUtil.randomizeParamIdsG gen1 guidMap (\_ _ x -> x) ival
, ExprUtil.randomizeParamIdsG gen2 guidMap (\_ _ x -> x) ityp
)
where
(gen1, gen2) = ExprUtil.ngSplit gen
assertCompareInferred ::
InferResults t -> InferResults t -> HUnit.Assertion
assertCompareInferred result expected =
assertBool errorMsg (null resultErrs)
where
resultC = canonizeInferred result
expectedC = canonizeInferred expected
(resultErrs, errorMsg) =
errorMessage $ ExprUtil.matchExpression match mismatch resultC expectedC
check s x y
| ExprUtil.alphaEq x y = pure []
| otherwise = fmap (: []) . addAnnotation $
List.intercalate "\n"
[ " expected " ++ s ++ ":" ++ (show . simplifyDef) y
, " result " ++ s ++ ":" ++ (show . simplifyDef) x
]
match (v0, t0) (v1, t1) =
(++) <$> check " type" t0 t1 <*> check "value" v0 v1
mismatch e0 e1 =
error $ concat
[ "Result must have same expression shape:"
, "\n Result: ", redShow e0
, "\n vs. Expected: ", redShow e1
, "\n whole result: ", redShow resultC
, "\n whole expected: ", redShow expectedC
]
redShow = ansiAround ansiRed . show . void
inferAssertion :: InferResults t -> HUnit.Assertion
inferAssertion expr =
assertCompareInferred inferredExpr expr
where
inferredExpr = inferResults . fst . doInfer_ $ void expr
inferWVAssertion :: InferResults t -> InferResults t -> HUnit.Assertion
inferWVAssertion expr wvExpr = do
-- TODO: assertCompareInferred should take an error prefix string,
-- and do ALL the error printing itself. It has more information
-- about what kind of error string would be useful.
assertCompareInferred (inferResults inferredExpr) expr
`E.onException` printOrig
assertCompareInferred (inferResults wvInferredExpr) wvExpr
`E.onException` (printOrig >> printWV)
where
printOrig = hPutStrLn stderr $ "WithoutVars:\n" ++ showInferredValType inferredExpr
printWV = hPutStrLn stderr $ "WithVars:\n" ++ showInferredValType wvInferredExpr
(inferredExpr, inferContext) = doInfer_ $ void expr
wvInferredExpr = fst <$> wvInferredExprPL
(wvInferredExprPL, _) =
either error id $
(`runStateT` inferContext)
(ImplicitVariables.add (Random.mkStdGen 0)
loader (flip (,) () <$> inferredExpr))
allowFailAssertion :: HUnit.Assertion -> HUnit.Assertion
allowFailAssertion assertion =
(assertion >> successOccurred) `E.catch`
\(E.SomeException _) -> errorOccurred
where
successOccurred =
hPutStrLn stderr . ansiAround ansiYellow $ "NOTE: doesn't fail. Remove AllowFail?"
errorOccurred =
hPutStrLn stderr . ansiAround ansiYellow $ "WARNING: Allowing failure in:"
testInfer :: String -> InferResults t -> TestFramework.Test
testInfer name = testCase name . inferAssertion
testInferAllowFail :: String -> InferResults t -> TestFramework.Test
testInferAllowFail name expr =
testCase name . allowFailAssertion $ inferAssertion expr
type InferredExpr t = ExprIRef.Expression t (Infer.Inferred (DefI t))
testResume ::
String ->
InferResults t ->
Lens.Traversal' (InferredExpr t) (InferredExpr t) ->
InferResults t ->
TestFramework.Test
testResume name origExpr position newExpr =
testCase name $ assertResume origExpr position newExpr
assertResume ::
InferResults t ->
Lens.Traversal' (InferredExpr t) (InferredExpr t) ->
InferResults t ->
HUnit.Assertion
assertResume origExpr position newExpr =
void . E.evaluate . DeepSeq.force . (`runState` inferContext) $
doInferM point newExpr
where
(tExpr, inferContext) = doInfer_ origExpr
Just point = tExpr ^? position . Expr.ePayload . Lens.to Infer.iPoint
| Mathnerd314/lamdu | test/InferAssert.hs | gpl-3.0 | 5,076 | 0 | 14 | 940 | 1,349 | 733 | 616 | -1 | -1 |
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | A tuple represents the types of multiple cassandra columns. It is used
-- to check that column-types match.
module Database.CQL.Protocol.Tuple
( Tuple
, count
, check
, tuple
, store
, Row
, mkRow
, fromRow
, columnTypes
, rowLength
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Data.Serialize
import Data.Word
import Database.CQL.Protocol.Class
import Database.CQL.Protocol.Codec (putValue)
import Database.CQL.Protocol.Types
import Database.CQL.Protocol.Tuple.TH
genInstances 48
| twittner/cql | src/Database/CQL/Protocol/Tuple.hs | mpl-2.0 | 921 | 0 | 5 | 190 | 106 | 73 | 33 | 23 | 0 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
module Data.Vec.Quaternion
( Quaternion(..)
, qconj
, realq
, imagq
, qscale
, qrotate
, qpow
, slerp
, toAxisAngle
, fromAxisAngle
, toRotationMatrix
, qintegrate
) where
import Prelude hiding (head,tail,foldr,foldl,map,zipWith,last)
import Data.Vec
-- TODO: use Packed
newtype Quaternion a = Q (Vec4 a)
deriving instance Access N0 a (Quaternion a)
deriving instance Access N1 a (Quaternion a)
deriving instance Access N2 a (Quaternion a)
deriving instance Access N3 a (Quaternion a)
instance Head (Quaternion a) a where
head (Q v) = head v
instance Tail (Quaternion a) (Vec3 a) where
tail (Q v) = tail v
instance Last (Quaternion a) a where
last (Q v) = last v
instance Fold (Quaternion a) a where
fold f (Q v) = fold f v
foldl f a (Q v) = foldl f a v
foldr f a (Q v) = foldr f a v
instance Map a b (Quaternion a) (Quaternion b) where
map f (Q v) = Q (map f v)
instance ZipWith a b c (Quaternion a) (Quaternion b) (Quaternion c) where
zipWith f (Q u) (Q v) = Q (zipWith f u v)
deriving instance Show a => Show (Quaternion a)
deriving instance Eq a => Eq (Quaternion a)
qconj :: Num a => Quaternion a -> Quaternion a
qconj (Q (s :. v)) = Q (s :. negate v)
-- | Construct a quaternion with the given real part, and zero imaginary parts.
realq :: Num a => a -> Quaternion a
realq a = Q (a :. vec 0)
-- | Construct a quaternion with the given imaginary parts, and zero real part.
imagq :: Num a => Vec3 a -> Quaternion a
imagq w = Q (0 :. w)
-- | @qscale a q@ is equivalent to, but more efficient than, @realq a * q@.
qscale :: Num a => a -> Quaternion a -> Quaternion a
qscale a (Q q) = Q (vec a * q)
-- | Unlike the 'Vec' instance for 'Num', multiplication is defined as the quaternion multiplication operator, not element-by-element. 'fromInteger' creates a real-valued quaternion (that is, one with zero imaginary parts).
-- 'abs' returns the real-valued quaternion equal to the argument's Euclidean norm. 'signum' is the same as 'normalize' (NOT an element-by-element signum). In this way, the identity @q == abs q * signum q@ is satisfied for all but the zero quaternion, which of course becomes @NaN@ when normalized.
instance (Num a, Floating a) => Num (Quaternion a) where
Q a + Q b = Q (a+b)
Q a - Q b = Q (a-b)
Q (as:.av) * Q (bs:.bv) = Q ((as*bs - dot av bv) :. (vec as*bv + vec bs*av + cross av bv))
negate (Q q) = Q (negate q)
fromInteger n = Q (fromInteger n :. vec 0)
abs q = Q (norm q :. vec 0)
signum = normalize
-- | '(/)' is defined as right division, @q * r^-1@. Note that this is not equivalent to left division, @r^-1 * q@.
-- 'fromRational' produces a real-valued quaternion.
instance Floating a => Fractional (Quaternion a) where
recip q = qscale (recip (dot q q)) (qconj q)
-- Right division. Not equivalent to left division.
q / r = q * recip r
fromRational t = Q (fromRational t :. vec 0)
-- | All functions in 'Floating' are defined as appropriate over the quaternions, and do not operate element-by-element.
-- 'pi' is a real-valued quaternion.
instance RealFloat a => Floating (Quaternion a) where
pi = Q (pi :. vec 0)
exp (Q (s:.v)) = Q ((exp s * cos nv) :. (v * vec (exp s * sin_recip nv))) where nv = norm v
log q@(Q (s:.v)) = Q (log (norm q) :. (normalize v * vec (acos (s / norm q))))
q ** p = exp (log q * p)
-- TODO: use a more efficient formula for sqrt
sqrt q = q ** 0.5
-- TODO: for sin, cos, sinh, cosh, use the Taylor series expansions when nv is close to zero.
sin (Q (s:.v)) = Q ((sin s * cosh nv) :. (v * vec (cos s * sinh_recip nv))) where nv = norm v
cos (Q (s:.v)) = Q ((cos s * cosh nv) :. (v * vec (- sin s * sinh_recip nv))) where nv = norm v
sinh (Q (s:.v)) = Q ((sinh s * cos nv) :. (v * vec (cosh s * sin_recip nv))) where nv = norm v
cosh (Q (s:.v)) = Q ((cosh s * cos nv) :. (v * vec (sinh s * sin_recip nv))) where nv = norm v
tan q = sin q / cos q
tanh q = sin q / cos q
asinh q = log (q + sqrt (q*q + 1))
acosh q = log (q + sqrt (q*q - 1))
atanh q = qscale 0.5 (log (1+q) - log (1-q))
asin q@(Q (_:.v)) = -u*asinh(q*u) where u = Q (0:.normalize v)
acos q@(Q (_:.v)) = -u*acosh(q) where u = Q (0:.normalize v)
atan q@(Q (_:.v)) = -u*atanh(q*u) where u = Q (0:.normalize v)
-- | Rotation of a 3-dimensional vector by a quaternion.
qrotate :: Floating a => Quaternion a -> Vec3 a -> Vec3 a
qrotate q v = tail (q * Q (0:.v) * qconj q)
-- | Real power of a quaternion. @qpow q p@ is equivalent to, but more efficient than, @q ** 'realq' p@.
qpow :: RealFloat a => Quaternion a -> a -> Quaternion a
qpow q p = exp (qscale p (log q))
-- | Spherical linear interpolation of quaternion rotations.
--slerp q0 _ 0 = q0 -- otherwise qpow gives NaN
slerp :: RealFloat a => Quaternion a -> Quaternion a -> a -> Quaternion a
slerp q0 q1 t = qpow (q1 / q0) t * q0
-- | Convert from a unit quaternion to an axis-angle representation.
toAxisAngle :: RealFloat a => Quaternion a -> (a, Vec3 a)
toAxisAngle q = if | w > 1 -> toAxisAngle (normalize q)
| s < epsilon -> (0, 1:.0:.0:.())
| otherwise -> (2.0*acos w, vec (recip s) * tail q)
where w = head q
s = sqrt (1-w*w)
-- | Convert from an axis-angle representation of rotation to a unit quaternion (if the axis is a unit vector).
fromAxisAngle :: Floating a => Vec3 a -> a -> Quaternion a
fromAxisAngle axis angle = Q (cos (0.5*angle) :. (vec (sin (0.5*angle)) * axis))
toRotationMatrix :: Floating a => Quaternion a -> Vec3 (Vec3 a)
-- TODO: use more efficient formula
toRotationMatrix q = (qrotate q (1:.0:.0) :. qrotate q (0:.1:.0) :. qrotate q (0:.0:.1) :. ())
-- XXX: why doesn't this one work?
{-
toRotationMatrix (Q (w:.x:.y:.z:.())) =
( ((1-2*y*y-z*z) :. (2*x*y-2*w*z) :. (2*x*z+2*w*y) :. ())
:.((2*x*y+2*w*z) :. (1-x*x-z*z) :. (2*y*z+2*w*x) :. ())
:.((2*x*z-2*w*y) :. (2*y*z+2*w*x) :. (1-x*x-y*y) :. ()):.())
-}
-- | "Euler integration": apply an angular velocity to a quaternion. The angular velocity is a vector parallel to the axis of rotation, with magnitude equal to the speed times the time step.
qintegrate :: (RealFloat a, Ord a) => Vec3 a -> Quaternion a -> Quaternion a
qintegrate w q = dq * q
where dq = Q (c :. (vec s * theta))
mThetaSq = normSq theta
mTheta = sqrt mThetaSq
theta = vec 0.5 * w
-- Taylor approximation is used when mTheta is close to zero (sin x / x becomes unstable)
(c,s) = if mThetaSq*mThetaSq/24 < epsilon
then (1 - mThetaSq/2, 1 - mThetaSq/6)
else (cos mTheta, sin mTheta / mTheta)
--
-- numerics junk
--
-- | Machine epsilon. (Requires @ScopedTypeVariables@)
epsilon :: forall a. RealFloat a => a
epsilon = encodeFloat 1 (fromIntegral $ 1-floatDigits (undefined :: a))
eps120_4 :: RealFloat a => a
eps120_4 = (120*epsilon) ** (1/4)
-- | @sin_recip x == sin x / x@, even when x is close to zero.
sin_recip :: RealFloat a => a -> a
sin_recip x = if abs x < eps120_4 then 1 - x*x/6 else sin x / x
-- | @sinh_recip x == sinh x / x@, even when x is close to zero.
sinh_recip :: RealFloat a => a -> a
sinh_recip x = if abs x < eps120_4 then 1 + x*x/6 else sinh x / x
| gmaslov/rigbo3 | src/Data/Vec/Quaternion.hs | lgpl-3.0 | 7,670 | 1 | 16 | 1,854 | 2,843 | 1,434 | 1,409 | 117 | 3 |
module Problem046 where
main =
print $ head $ filter (not . goldbach) $ filter (not . isPrime) [9, 11 ..]
goldbach x = any isPrime $ map (\s -> x - s) $ takeWhile (< x) squares2
squares2 = map (\n -> 2 * n * n) [1..]
isPrime = primeF primes
primes = 2 : 3 : filter (primeF primes) [5, 7 ..]
primeF (p:ps) x = p * p > x || x `rem` p /= 0 && primeF ps x
| vasily-kartashov/playground | euler/problem-046.hs | apache-2.0 | 359 | 0 | 10 | 91 | 209 | 112 | 97 | 8 | 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.
-}
import NonExistentModule
program = drawingOf(blank)
| alphalambda/codeworld | codeworld-compiler/test/testcases/missingModule/source.hs | apache-2.0 | 663 | 0 | 6 | 121 | 16 | 9 | 7 | 2 | 1 |
removeNonUppercase :: String -> String
removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]
addThree :: Int -> Int -> Int -> Int
addThree x y z = x + y + z
factorial :: Integer -> Integer
factorial x = product [1..x]
circumference :: Float -> Float
circumference r = 2 * pi * r
circumference' :: Double -> Double
circumference' r = 2 * pi * r
| gregsymons/learn-you-a-haskell | chapter-2.hs | apache-2.0 | 354 | 0 | 8 | 76 | 156 | 82 | 74 | 10 | 1 |
{-
Copyright 2015 Tristan Aubrey-Jones
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.
-}
{-|
Copyright : (c) Tristan Aubrey-Jones, 2015
License : Apache-2
Maintainer : developer@flocc.net
Stability : experimental
For more information please see <http://www.flocc.net/>
-}
module Compiler.Types.Solver where
import Compiler.Front.Indices (IdxMonad)
import Compiler.Front.Common (Mappable(..), FunctorM(..), listIdx, listGet)
import qualified Compiler.Types.TypeInfo as TI
import Compiler.Types.Substitutions
import Compiler.Types.TermLanguage (Term(..), FunctionToken(Tok, TupTok), Constr((:=:)), getVarIdsInTerm)
import Compiler.Types.TypeAssignment (TyToken(Ty))
import Compiler.Types.EmbeddedFunctions (applyDimGens)
import Compiler.Types.FillGaps (possibleSubs)
import qualified Data.IntMap.Strict as IM
import qualified Data.Map.Strict as M
import Control.Monad.State.Strict (StateT, gets, modify, lift, runStateT, execStateT)
import Debug.Trace (trace)
import qualified Data.List as L
import qualified Data.Set as S
import Data.Set (Set)
import Data.Maybe (fromJust, isJust)
debugOn = True
type Tm = Term (FunctionToken TyToken)
type TmEnv = IM.IntMap Tm
mapEnv :: (Tm -> Tm) -> TmEnv -> TmEnv
mapEnv f env = fmap f env
mapEnvM :: Monad m => (Tm -> m Tm) -> TmEnv -> m TmEnv
mapEnvM f env = do
let l = IM.toAscList env
l' <- mapM (\(i,t) -> do t' <- f t; return (i, t')) l
return $ IM.fromAscList l'
applySubsToTm :: SubstMap Tm -> Tm -> Tm
applySubsToTm subs val = case val of
(Term t l) -> applySubsts subs $ Term t (map (applySubsToTm subs) l)
other -> applySubsts subs other
type Con = Constr Tm
type Cons = [Con]
emptyCons = []
instance Functor Constr where
fmap f (a :=: b) = (f a) :=: (f b)
mapCons f l = fmap (fmap f) l
instance FunctorM Constr where
fmapM f (a :=: b) = do
a' <- f a
b' <- f b
return (a' :=: b')
mapMCons f l = fmapM (fmapM f) l
type Subs = SubstMap Tm
emptySubs = emptySubstMap
singletonSub k v = M.singleton k v
data Choice =
TyChoice
| FunChoice
type Choices = [Choice]
noChoices=[]
-- |Returns the number of non Term terms at the
-- |leaves of this expression.
countLeavesInTm :: Tm -> Int
countLeavesInTm t = case t of
(Term t l) -> sum $ map countLeavesInTm l
other -> 1
-- |For all FFun terms, checks that all the Vars in each id tree
-- |are distinct.
checkVarsInEq :: Tm -> Bool
checkVarsInEq (Term (Tok (Ty "FFun")) [idT, expT]) = if length vars < cnt
then error ("checkVarsInEq: False: " ++ (show idT)) {-False-}
else (if length vars > cnt
then error ("checkVarsInEq: " ++ (show idT))
else True)
where vars = getVarIdsInTerm idT
cnt = countLeavesInTm idT
checkVarsInEq (Term t l) = and $ map checkVarsInEq l
checkVarsInEq other = True
-- |For all terms in the env, checks that the Vars in each FFun's
-- |id tree, are all distinct.
checkFunVarsInEq :: TmEnv -> Bool
checkFunVarsInEq env = and $ map checkVarsInEq $ IM.elems env
{-
-- Old version 2: needed to create inequality constraints at beginning, and then
-- check them at the end. Simpler to do version 3, just check that vars in FFun
-- id trees are all distinct.
-- |Constraint that represents in equality of all pairs
-- |of terms drawn from a set.
data InEqCon = InEq (Set Tm)
deriving (Eq, Show, Ord)
-- |Searches all sub terms for FFuns, returning an InEqCon for each set of
-- |argument vars.
buildInEqCons :: Tm -> Set InEqCon
buildInEqCons term = case term of
(Term (Tok (Ty "FFun")) [idT, expT]) -> (S.singleton $ InEq $ S.fromList $ map Var $ getVarIdsInTerm idT) `S.union` (buildInEqCons expT)
(Term t l) -> S.unions $ map buildInEqCons l
other -> S.empty
-- |Searches all terms, returning an InEqCon for each set
-- |of argument vars in FFun terms.
buildInEqConsFromEnv :: TmEnv -> Set InEqCon
buildInEqConsFromEnv env = s
where l = IM.elems env
s = S.unions $ map buildInEqCons l
-- |Applies substituions to an inequality constraint, returning a new
-- |constraint if all pairs of vars remain unequal, and Nothing if
-- |any of the members become the same (i.e. the size of the var set reduces).
applySubsToInEqCon :: SubstMap Tm -> InEqCon -> Maybe (InEqCon)
applySubsToInEqCon subs (InEq l) = if S.size l' < S.size l then Nothing else Just $ InEq l'
where l' = S.map (applySubsToTm subs) l
-- |Applies substitutions to all inequality constraints, returning the new constraints
-- |if they all still hold, and Nothing if one of them is now infringed (i.e. if
-- |two unequal variables are now the same).
applySubsToInEqCons :: SubstMap Tm -> Set InEqCon -> Maybe (Set InEqCon)
applySubsToInEqCons subs l = if S.member Nothing l' then Nothing else Just $ S.map fromJust l'
where l' = S.map (applySubsToInEqCon subs) l-}
{-
-- Old version 1: that checks constraints by comparing all pairings.
-- Not as efficient as updating the set of vars, and seeing if it's size
-- has reduced (e.g. two elements have become equal, above).
-- |Constraint that represents in equality of all pairs
-- |of terms drawn from a set.
data InEqCon = InEq [Tm]
deriving (Eq, Show, Ord)
-- |Searches all sub terms for FFuns, returning an InEqCon for each set of
-- |argument vars.
buildInEqCons :: Tm -> Set InEqCon
buildInEqCons term = case term of
(Term (Tok (Ty "FFun")) [idT, expT]) -> (S.singleton $ InEq $ map Var $ getVarIdsInTerm idT) `S.union` (buildInEqCons expT)
(Term t l) -> S.unions $ map buildInEqCons l
other -> S.empty
-- |Searches all terms, returning an InEqCon for each set
-- |of argument vars in FFun terms.
buildInEqConsFromEnv :: TmEnv -> Set InEqCon
buildInEqConsFromEnv env = s
where l = IM.elems env
s = S.unions $ map buildInEqCons l
-- |Returns all pairs drawn from a set.
pairs :: [a] -> [(a,a)]
pairs (v1:r) = (map (\v2 -> (v1,v2)) r) ++ (pairs r)
pairs [] = []
-- |Returns true iff none of the
checkInEqCon :: InEqCon -> Bool
checkInEqCon (InEq l) = and $ map (\(v1,v2) -> v1 /= v2) cons
where cons = pairs l
-- |Applies subst
applySubsToInEqCon :: SubstMap Tm -> InEqCon -> InEqCon
applySubsToInEqCon subs (InEq l) = InEq $ S.map (applySubsToTm subs) l
applySubsToInEqCons :: SubstMap Tm -> Set InEqCon -> Set InEqCon
applySubsToInEqCons subs l = S.map (applySubsToInEqCon subs) l
-}
-- |applyDimGensInEnv env. Applies all dim generators in the env, and
-- |returns any constraints that they create.
applyDimGensInEnv :: Monad m => TmEnv -> IdxMonad m (TmEnv, Cons, Subs)
applyDimGensInEnv env = do
(env', (cl', subs)) <- runStateT (mapEnvM (\t -> do (t',cl,subs) <- lift $ applyDimGens t; modify (\(c,s) -> (c++cl,s++subs)); return t') env) ([],[])
let subs' = fromDisjointList subs
let env'' = mapEnv (applySubsToTm subs') env' -- apply subs to env (so any changes are made across whole env)
return (env'', cl', subs')
-- |Encapsulates a term and overrides Eq so that two encapsulated terms
-- |are equal iff they unify.
{-data EqTm = BijEqTm Tm
deriving Show
instance Eq BijEqTm where
(BijEqTm t) == (BijEqTm t') = case t == t' of
True -> trace ("\neq: " ++ (show t) ++ " == " ++ (show t') ++ "\n") $ True
False -> case bijTm [] [t :=: t'] of
Left subs -> trace ("\n\nunifies: " ++ (show t) ++ " == " ++ (show t') ++ "\n" ++ (show subs) ++ "\n") $ True
Right _ -> trace ("\n\nfails: " ++ (show t) ++ " == " ++ (show t') ++ "\n") $ False
fromBijEqTm :: BijEqTm -> Tm
fromBijEqTm (BijEqTm t) = t-}
-- |Extends a bijective relation with a new mapping, as long as
-- |neither the element from the domain, or the one from the range
-- |exists in either the dom or range already.
extendBij :: [(Tm,Tm)] -> Tm -> Tm -> Maybe [(Tm,Tm)]
extendBij rel a b = case (lookup a rel, lookup b invRel) of
-- if this exact one exists, leave as it is
(Just b', Just a') | b' == b && a' == a -> Just rel
-- if a is not in dom, and b is not in range so add
(Nothing, Nothing) -> Just $ (a,b):rel
-- otherwise fail
_ -> Nothing
where (dom,ran) = unzip rel
invRel = zip ran dom
-- TODO is it safe to add a condition that passes a constraint if they are
-- syntactically equivalent? (no probs not, what if a mapping for one the terms already exists.).
-- |Tries to find a bijection between two terms, and returns
-- |the constraint that failed if it can't
bijTm :: [(Tm,Tm)] -> [Con] -> Either [(Tm,Tm)] Con
bijTm rel (h:r) = case h of
(Var a :=: b) -> case extendBij rel (Var a) b of
Just rel' -> bijTm rel' r
Nothing -> Right h
(a :=: Var b) -> case extendBij rel a (Var b) of
Just rel' -> bijTm rel' r
Nothing -> Right h
(Term t l :=: Term t' l') | t == t' && length l == length l' -> bijTm rel (r ++ (map (\(a,b) -> a :=: b) $ zip l l'))
other -> Right h
bijTm rel [] = Left rel
-- |Compares two terms and returns True if it can find a bijection between them
-- |otherwise fails.
bijTmEq :: Tm -> Tm -> Bool
bijTmEq a b = case bijTm [] [a :=: b] of
Left _ -> True
Right _ -> False
{-removeDuplicates :: Eq a => [a] -> [a] -> [a]
removeDuplicates res (h:r) = if elem h res then removeDuplicates res r else removeDuplicates (h:res) r
removeDuplicates res [] = res-}
-- |fillGapsInEnv termEnv. Searches the terms in the env, looking for gaps,
-- |finds possible values for each one, groups by term var id, and returns
-- |a map from term var ids to possible lists of values.
fillGapsInEnv :: Monad m => TmEnv -> IdxMonad m (IM.IntMap [Tm])
fillGapsInEnv env = do
-- get possible subs from all terms in the env
let env' = IM.toAscList env
maps <- mapM (\(k,t) -> do l <- possibleSubs t; return l) env'
-- union all possibilities for each term var together (where we use 'unifySimple' for equality)
let m = IM.unionsWith (L.unionBy bijTmEq) maps
return m
-- |processCons constrs. Applies term simplification (expanding
-- |embedded functions, and dim generators) to the terms in
-- |constrs, returning new constraints, with any new ones added
-- |and the substitutions that were performed by the simplification.
processCons :: Monad m => Cons -> IdxMonad m (Cons, Subs)
processCons cons = do
-- simplify terms
res <- mapMCons applyDimGens cons
-- extract simplified constraints, new constrs and substitutions from result
let cons' = map (\((t1,_,_) :=: (t2,_,_)) -> t1 :=: t2) res
let newCons = concat $ map (\((_,c1,_) :=: (_,c2,_)) -> c1 ++ c2) res
let subsLst = concat $ map (\((_,_,s1) :=: (_,_,s2)) -> s1 ++ s2) res
let subs = fromDisjointList subsLst
return (cons' ++ newCons, subs)
-- |For terms a, b returns True iff a occurs somewhere in b
occursInTm :: Eq t => (Term t) -> (Term t) -> Bool
occursInTm a b | a == b = True
occursInTm a (Term t l) = or $ map (occursInTm a) l
occursInTm _ _ = False
isVar :: Tm -> Bool
isVar (Var _) = True
isVar _ = False
-- |unifyPartFuns (funTerm1, funTerm2). Tries to unify two
-- |embedded partition functions, to return substitutions
-- |that replace the two input functions, with a new common
-- |function which subsumes them both.
unifyPartFuns :: Con -> Maybe Subs
--unifyPartFuns con = error $ "unifyPartFuns called: " ++ (show con)
unifyPartFuns con@(a :=: b) = case con of
-- pattern match two embedded functions
-- and find bijection between arg tuples
((Term (Tok (Ty "FFun")) [aItT, aExpT]) :=:
(Term (Tok (Ty "FFun")) [bItT, bExpT])) ->
case bijTm [] [aItT :=: bItT] of
-- replace both funs with "least common function"
Left bij -> {-error $ "unify funs: " ++ (show con) ++ "\n" ++ (show resFun) --} Just $ fromDisjointList [(a, resFun), (b, resFun)]
where -- check to see if
-- convert bij to subs
bij' = map (\(a,b) -> if isVar a then (a, b) else (b, a)) bij
subs = fromDisjointList bij'
-- apply to exps
aExpT' = applySubsToTm subs aExpT
bExpT' = applySubsToTm subs bExpT
-- get vars from each
vids1 = getVarIdsInTerm aExpT'
vids2 = getVarIdsInTerm bExpT'
-- get intersection of both
vids3 = L.nub $ L.intersect vids1 vids2
-- make function
aItT' = applySubsToTm subs aItT
resTup = case vids3 of
[] -> (Term (Tok (Ty "VNull")) [])
[v] -> Var v
l -> Term TupTok $ map Var vids3
resFun = (Term (Tok (Ty "FFun")) [aItT', resTup])
-- error
Right err -> error $ "can't unify partition functions " ++ (show con)
-- can't be unified yet
other -> iterUnify [con] --Nothing --error $ "Types:Solver:unifyPartFuns: invalid constraint: "++ (show con)
-- |getVarIdListInTerm term. Returns the var ids that appear in
-- |term in the order they occur in term (depth first traversal)
-- |with duplicates.
getVarIdListInTerm :: Show t => Term t -> [Int]
getVarIdListInTerm term = case term of
(Term tok l) -> concat $ map getVarIdListInTerm l
(Var idx) -> [idx]
other -> error $ "Types:Solver:getVarIdListInTerm: invalid term " ++ (show other)
-- |unifyLayoutFuns (funTerm1, funTerm2). Tries to unify two
-- |embedded partition functions, to return substitutions
-- |that replace the two input functions, with a new common
-- |function which subsumes them both.
unifyLayoutFuns :: Con -> Maybe Subs
unifyLayoutFuns con@(a :=: b) = case con of
-- pattern match two embedded functions
-- and find bijection between arg tuples
((Term (Tok (Ty "FFun")) [aItT, aExpT]) :=:
(Term (Tok (Ty "FFun")) [bItT, bExpT])) ->
case bijTm [] [aItT :=: bItT] of
-- replace both funs with "least common function"
Left bij -> case vids3 of
Just l -> Just $ fromDisjointList [(a, resFun), (b, resFun)]
where -- make function
aItT' = applySubsToTm subs aItT
resTup = case vids3 of
Just [] -> (Term (Tok (Ty "VNull")) [])
Just [v] -> Var v
Just l -> Term TupTok $ map Var l
resFun = (Term (Tok (Ty "FFun")) [aItT', resTup])
Nothing -> Nothing
where -- check to see if
-- convert bij to subs
bij' = map (\(a,b) -> if isVar a then (a, b) else (b, a)) bij
subs = fromDisjointList bij'
-- apply to exps
aExpT' = applySubsToTm subs aExpT
bExpT' = applySubsToTm subs bExpT
-- get vars from each
vids1 = getVarIdListInTerm aExpT'
vids2 = getVarIdListInTerm bExpT'
-- see if one is a prefix of the other
vids3 = (if L.isPrefixOf vids1 vids2
then Just vids2
else if L.isPrefixOf vids2 vids1
then Just vids1
else Nothing)
-- error
Right err -> error $ "can't unify layout functions " ++ (show con)
-- can't be unified yet
other -> iterUnify [con] --Nothing
-- |iterUnify cons. Tries to unify all constraints in cons.
iterUnify :: Cons -> Maybe Subs
iterUnify [] = Just emptySubstMap
iterUnify (c:l) = case unify c of
Just (Left subs) -> case iterUnify (mapCons (applySubsToTm subs) l) of
Nothing -> Nothing
Just subs2 -> Just $ composeSubsts subs2 subs
Just (Right cons) -> iterUnify (cons ++ l)
Nothing -> Nothing
-- TODO
-- NEED TO RE-CODE UNIFY TO RETURN A PAIR OF SUBS
-- AND CONS. RETURNING WHICHEVER CONS DID UNIFY, AND
-- ANY THAT DIDN'T. OTHERWISE MIGHT NOT MAKE PROGRESS
-- IF ONE PART OF A TERM NEEDS TO BE UNIFIED BEFORE
-- ANOTHER. (e.g. multiple co-depedent functions in a term)
-- |unify con. Tries to unify a constraint, returning
-- |Just Left substitutions or Just Right constraints if succeeded
-- |and created a new subsitution or constraints, and Nothing
-- |if it failed.
unify :: Con -> Maybe (Either Subs Cons)
--unify c = error $ "unify called " ++ (show c)
unify c = case c of
(Var a :=: Var a') | a == a' -> Just $ Left emptySubs
(s :=: x@(Var i)) -> if debugOn && (occursInTm x s)
then error $ "Solver:unify: circular constraint " ++ (show c)
else Just $ Left $ singletonSub x s
(x@(Var i) :=: t) -> if debugOn && (occursInTm x t)
then error $ "Solver:unify: circular constraint " ++ (show c)
else Just $ Left $ singletonSub x t
-- Types that contain embedded functions
-- Note: as don't apply intermediate subs, assumes
-- Vars used in functions, and other parts are disjoint.
((Term (Tok (Ty n1)) l1) :=: (Term (Tok (Ty n2)) l2)) | n1 == n2 && TI.funs n1 /= [] -> {-error $ "bla: " ++ (show c)-}
-- if all unified return substs
if pfunsUnify && lfunsUnify && isJust otherRes
then Just $ Left $ foldl composeSubsts emptySubstMap $ (map fromJust lfunRes) ++ (map fromJust pfunRes) ++ [fromJust otherRes]
-- else return nothing
else Nothing
where -- try and unify partition functions
pfunLocs = TI.partFuns n1
pfunCons = map (\idx -> (listGet "Solver:unify:1" l1 idx) :=: (listGet "Solver:unify:2" l2 idx)) pfunLocs
pfunRes = map unifyPartFuns pfunCons
pfunsUnify = all isJust pfunRes
-- try and unify layout functions
lfunLocs = TI.layFuns n1
lfunCons = map (\idx -> (listGet "Solver:unify:3" l1 idx) :=: (listGet "Solver:unify:4" l2 idx)) lfunLocs
lfunRes = map unifyLayoutFuns lfunCons
lfunsUnify = all isJust pfunRes
-- try and unify other parts of type term
otherLocs = [0..((length l1)-1)] L.\\ (pfunLocs ++ lfunLocs)
otherCons = map (\idx -> (l1 `listIdx` idx) :=: (l2 `listIdx` idx)) otherLocs
otherRes = iterUnify otherCons
-- This method should never unify functions, should always be caught be case above.
((Term (Tok (Ty "FFun")) _) :=: (Term (Tok (Ty "FFun")) _)) ->
error $ "Solver:unify: unify should never be used to unify functions!\n" ++ (show c)
--fmap Left (unifyPartFuns c)
-- back to normal:
(Term t l :=: Term t' l') | t == t' && length l == length l' ->
Just $ Right $ map (\(a,b) -> a :=: b) $ zip l l'
other -> Nothing
unify2 :: Con -> Maybe (Subs, Cons)
unify2 c = case c of
(Var a :=: Var a') | a == a' -> Just $ (emptySubs, [])
(s :=: x@(Var i)) -> if debugOn && (occursInTm x s)
then error $ "Solver:unify: circular constraint " ++ (show c)
else Just $ (singletonSub x s, [])
(x@(Var i) :=: t) -> if debugOn && (occursInTm x t)
then error $ "Solver:unify: circular constraint " ++ (show c)
else Just $ (singletonSub x t, [])
-- Types that contain embedded functions
-- Note: as don't apply intermediate subs, assumes
-- Vars used in functions, and other parts are disjoint.
((Term (Tok (Ty n1)) l1) :=: (Term (Tok (Ty n2)) l2)) | n1 == n2 && TI.funs n1 /= [] ->
-- if functions unified return substs
if pfunsUnify && lfunsUnify
then Just ((foldl composeSubsts emptySubstMap $ (map fromJust lfunRes) ++ (map fromJust pfunRes)), otherCons)
-- else return nothing
else Nothing
where -- try and unify partition functions
pfunLocs = TI.partFuns n1
pfunCons = map (\idx -> (listGet "Solver:unify2:1" l1 idx) :=: (listGet "Solver:unify2:2" l2 idx)) pfunLocs
pfunRes = map unifyPartFuns pfunCons
pfunsUnify = all isJust pfunRes
-- try and unify layout functions
lfunLocs = TI.layFuns n1
lfunCons = map (\idx -> (listGet "Solver:unify2:3" l1 idx) :=: (listGet "Solver:unify2:4" l2 idx)) lfunLocs
lfunRes = map unifyLayoutFuns lfunCons
lfunsUnify = all isJust lfunRes
-- try and unify other parts of type term
otherLocs = [0..((length l1)-1)] L.\\ (pfunLocs ++ lfunLocs)
otherCons = map (\idx -> (listGet "Solver:unify2:5" l1 idx) :=: (listGet "Solver:unify2:6" l2 idx)) otherLocs
-- This method should never unify functions, should always be caught be case above.
((Term (Tok (Ty "FFun")) _) :=: (Term (Tok (Ty "FFun")) _)) ->
error $ "Solver:unify: unify should never be used to unify functions!\n" ++ (show c)
-- back to normal:
(Term t l :=: Term t' l') | t == t' && length l == length l' ->
Just $ (emptySubstMap, map (\(a,b) -> a :=: b) $ zip l l')
other -> Nothing
{-unifySimple :: Subs -> [Con] -> Either Subs Con
unifySimple subs (h:r) = case unify h of
-- made a new subst
Just (Left subs') -> unifySimple (subs' `composeSubsts` subs) $ mapCons (applySubsToTm subs') r
-- expanded to more constrs
Just (Right moreCons) -> unifySimple subs (r ++ moreCons)
-- fail
Nothing -> Right h
unifySimple subs [] = Left subs-}
-- |State carried by unifyConsM.
data UnifyState = UnifyState {
usNewCons :: Cons, -- new constraints (to be unified)
usFailedCons :: Cons, -- failed constraints (don't unify)
usSubs :: Subs -- substitutions
} deriving (Show)
-- |unifyConsM constrs. Tries to unify the constraints, applying any substitutions
-- |that have been made to latter constraints before unifying them. Any that don't
-- |unify and any new constraints and the substitutions are returned in the state monad.
unifyConsM :: Monad m => Cons -> StateT UnifyState (IdxMonad m) ()
unifyConsM (h:r) = do
subs0 <- gets usSubs
let h' = fmap (applySubsToTm subs0) h
case unify h' of
Nothing -> modify (\s -> s { usFailedCons=h:(usFailedCons s) }) >> unifyConsM r
Just (Left subs) -> modify (\s -> s { usSubs=subs `composeSubsts` (usSubs s) }) >> unifyConsM r
Just (Right cons) -> modify (\s -> s { usNewCons=(usNewCons s) ++ cons}) >> unifyConsM r
unifyConsM [] = return ()
-- |unifyCons constrs subs. Unifies all constrs that will unify, applying
-- |new substitutions to subs. Returns any constraints that won't unify,
-- |the final set of substitutions, and the number of the original constraints
-- |that unified (not counting children of the initial constraints).
unifyCons :: Monad m => Cons -> Subs -> IdxMonad m (Cons, Subs, Int)
unifyCons cl subs = do
-- unify as many of the current constraints as possible
res <- execStateT (unifyConsM cl) $ UnifyState { usNewCons=emptyCons, usFailedCons=emptyCons, usSubs=subs }
-- count how many of the original constraints unified
let count = (length cl) - (length $ usFailedCons res) -- num of constrs that unified
-- if some new constraints were created, then unify those too...
let newcons = usNewCons res
if length newcons > 0
then do
-- unify new constraints
let subs' = usSubs res
let newcons' = mapCons (applySubsToTm subs') newcons
(failedCons, finalSubs, _) <- unifyCons newcons' subs'
-- apply final subs to existing failed constrs, and concat with recursive failed constrs
let allFailedCons = (mapCons (applySubsToTm finalSubs) (usFailedCons res)) ++ failedCons
-- return failed constrs, final subs, and the num of constrs that unified for this call
return (allFailedCons, finalSubs, count)
else do
let finalSubs = usSubs res
-- apply final subs to existing failed constrs
let failedcons = mapCons (applySubsToTm finalSubs) $ usFailedCons res
return (failedcons, finalSubs, count)
-- TODO add fill gaps to choose
-- add choose to solve
-- (if we apply fill gaps later, we have no guarantee
-- that the subs suggested satisfy the inequality constraints,
-- and the simplification constraints)
-- TODO Extend choose to choose combinator implementations, not just fill gaps
choose :: Monad m => TmEnv -> Cons -> IdxMonad m [(Choice, Subs)]
choose env cons = do
gapFillers <- fillGapsInEnv env
case IM.toList gapFillers of
[] -> return []
((vid, vals):r) -> do
let subs = map (\v -> M.singleton (Var vid) v) vals
let choices = map (\sub -> (TyChoice, sub)) subs
return choices
-- |enumerateChoices env subs cons choices. Runs solve for each of the choices.
enumerateChoices :: Monad m => TmEnv -> Subs -> Cons -> [(Choice, Subs)] -> IdxMonad m [(Choices, Subs, TmEnv)]
enumerateChoices env subs cons choicesAndSubs = do
-- solve for each of the possible choices
let (choices, choiceSubs) = unzip choicesAndSubs
sols <- mapM (\s -> solve env (s `composeSubsts` subs) (mapCons (applySubsToTm s) cons)) choiceSubs
-- combine solutions into one list, and return it
let sols' = concat $ map (\(ch1,sub1) -> map (\(ch2,sub2,env2) -> (ch1:ch2,sub2,env2)) sub1) $ zip choices sols
return sols'
-- |solve termEnv substs constrs. Solves the constraints by iteratively
-- |unifying those that will unify, simplifying terms in the constraints, and
-- |simplifying terms in the environment. All substitutions are accumulated in
-- |substs. When this returns these substs should be applied once more to the
-- |resulting termEnv to get the final terms. When unsolvable constraints exist
-- |a 'choice' is made which should make some more constraints solvable. If
-- |at any point constraints remain and no more choices can be made, there
-- |is no solution and an error is thrown.
solve :: Monad m => TmEnv -> Subs -> Cons -> IdxMonad m [(Choices, Subs, TmEnv)]
solve env subs cl = do
-- simplify terms in constraints, and record simplifications in subs'
(cl', subs') <- processCons $ trace ("Solver:solve: " ++ (show cl) ++ "\n\n") $ cl
-- check if there are any constraints left
if length cl' <= 0
then do
-- if no constraints left
-- simplify env, and if generates constrs, solve them:
-- -------------------------------------------------
-- apply subs to term environment
let subs'' = subs' `composeSubsts` subs
let env' = mapEnv (applySubsToTm subs'') env
-- simplify term env
(env'', envCons, envSubs) <- applyDimGensInEnv env'
let subs''' = envSubs `composeSubsts` subs''
-- if created more constraints
if length envCons > 0
-- then solve them
then solve env'' subs''' (trace ("Solver:solve: simplification of term env created new constraints: \n" ++ (show envCons) ++ "\n\n") envCons)
-- else return
else do
-- apply final subs to env
let finalEnv = mapEnv (applySubsToTm subs''') env''
-- finally check inequality constraints i.e. Check function vars in arg tuples differ from each other
if checkFunVarsInEq finalEnv
-- if inequalities hold then return
then do
choicesAndSubs <- choose finalEnv []
if length choicesAndSubs > 0
then enumerateChoices finalEnv subs''' [] choicesAndSubs
-- no more choices to be made, so finished
else return [(noChoices, subs''', finalEnv)] -- *** WHERE SOLUTION RETURNS ***
-- if they don't then this isn't a solution
else return []
else do
-- unify any constraints that can be, returning:
-- -------------------------------------------------
-- nextCons: constraints that wouldn't unify
-- allSubs : initial substs extended with any substs returned due to constrs
-- numUnified: number of initial constraints that unified
(nextCons, allSubs, numUnified) <- unifyCons cl' (subs' `composeSubsts` subs)
-- if none were unified, make a new choice
if numUnified <= 0
then do
-- apply subs to term environment
let newEnv = mapEnv (applySubsToTm allSubs) env
-- get a list of possible choices that could be made next
choicesAndSubs <- choose newEnv nextCons
-- if there are some choices possible
if length choicesAndSubs > 0
-- solve for each of the possible choices
then enumerateChoices newEnv allSubs nextCons choicesAndSubs
-- if no choices possible then die because cannot solve the constraints
else error $ "Solver: solve failed: residual constraints, but no more choices possible:\n" ++ (show nextCons)
-- if some were unified, simplify and unify again
else do
solve env allSubs (trace ("Solver:solve: some constraints were unified, iterating...\n") nextCons)
{-
-- OLD version: doesn't simplify env and solve constraints created by it.
solve :: Monad m => TmEnv -> Subs -> Cons -> IdxMonad m [(Choices, Subs, TmEnv)]
solve env subs cl = do
-- simplify terms in constraints, and record simplifications in subs'
(cl', subs') <- processCons cl
-- check if there are any constraints left
if length cl' <= 0
then do
-- no constraints left
return [(noChoices, (subs' `composeSubsts` subs), env)]
else do
-- unify any constraints that can be, returning:
-- nextCons: constraints that wouldn't unify
-- allSubs : initial substs extended with any substs returned due to constrs
-- numUnified: number of initial constraints that unified
(nextCons, allSubs, numUnified) <- unifyCons cl' (subs' `composeSubsts` subs)
-- if none were unified, make a new choice
if numUnified <= 0
then do
-- apply subs to term environment
let newEnv = mapEnv (applySubsToTm allSubs) env
-- get a list of possible choices that could be made next
choicesAndSubs <- choose newEnv nextCons
-- if there are some choices possible
if length choicesAndSubs > 0
then do
-- solve for each of the possible choices
let (choices, choiceSubs) = unzip choicesAndSubs
sols <- mapM (\s -> solve newEnv (s `composeSubsts` allSubs) (mapCons (applySubsToTm s) nextCons)) choiceSubs
-- combine solutions into one list, and return it
let sols' = concat $ map (\(ch1,sub1) -> map (\(ch2,sub2,env2) -> (ch1:ch2,sub2,env2)) sub1) $ zip choices sols
return sols'
-- if no choices possible then die because cannot solve the constraints
else error $ "Solver: solve failed: residual constraints, but no more choices possible:\n" ++ (show nextCons)
-- if some were unified, simplify and unify again
else do
solve env allSubs nextCons-}
| flocc-net/flocc | v0.1/Compiler/Types/Solver.hs | apache-2.0 | 30,368 | 0 | 24 | 7,121 | 6,339 | 3,359 | 2,980 | 310 | 10 |
{-|
Copyright : (C) 2012-2016, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <christiaan.baaij@gmail.com>
Type and instance definitions for Rewrite modules
-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module CLaSH.Rewrite.Types where
import Control.Concurrent.Supply (Supply, freshId)
import Control.Lens (use, (.=), (<<%=))
import Control.Monad
import Control.Monad.Fix (MonadFix (..), fix)
import Control.Monad.Reader (MonadReader (..))
import Control.Monad.State (MonadState (..))
import Control.Monad.Writer (MonadWriter (..))
import Data.HashMap.Strict (HashMap)
import Data.IntMap.Strict (IntMap)
import Data.Monoid (Any)
import Unbound.Generics.LocallyNameless (Fresh (..))
import Unbound.Generics.LocallyNameless.Name (Name (..))
import CLaSH.Core.Term (Term, TmName)
import CLaSH.Core.Type (Type)
import CLaSH.Core.TyCon (TyCon, TyConName)
import CLaSH.Core.Var (Id, TyVar)
import CLaSH.Netlist.Types (HWType)
import CLaSH.Util
-- | Context in which a term appears
data CoreContext
= AppFun -- ^ Function position of an application
| AppArg -- ^ Argument position of an application
| TyAppC -- ^ Function position of a type application
| LetBinding Id [Id] -- ^ RHS of a Let-binder with the sibling LHS'
| LetBody [Id] -- ^ Body of a Let-binding with the bound LHS'
| LamBody Id -- ^ Body of a lambda-term with the abstracted variable
| TyLamBody TyVar -- ^ Body of a TyLambda-term with the abstracted
-- type-variable
| CaseAlt [Id] -- ^ RHS of a case-alternative with the variables bound by
-- the pattern on the LHS
| CaseScrut -- ^ Subject of a case-decomposition
deriving (Eq,Show)
-- | State of a rewriting session
data RewriteState extra
= RewriteState
{ _transformCounter :: {-# UNPACK #-} !Int
-- ^ Number of applied transformations
, _bindings :: !(HashMap TmName (Type,Term))
-- ^ Global binders
, _uniqSupply :: !Supply
-- ^ Supply of unique numbers
, _curFun :: TmName -- Initially set to undefined: no strictness annotation
-- ^ Function which is currently normalized
, _nameCounter :: {-# UNPACK #-} !Int
-- ^ Used for 'Fresh'
, _extra :: !extra
-- ^ Additional state
}
makeLenses ''RewriteState
-- | Debug Message Verbosity
data DebugLevel
= DebugNone -- ^ Don't show debug messages
| DebugFinal -- ^ Show completely normalized expressions
| DebugName -- ^ Names of applied transformations
| DebugApplied -- ^ Show sub-expressions after a successful rewrite
| DebugAll -- ^ Show all sub-expressions on which a rewrite is attempted
deriving (Eq,Ord,Read)
-- | Read-only environment of a rewriting session
data RewriteEnv
= RewriteEnv
{ _dbgLevel :: DebugLevel
-- ^ Lvl at which we print debugging messages
, _typeTranslator :: HashMap TyConName TyCon -> Type
-> Maybe (Either String HWType)
-- ^ Hardcode Type -> HWType translator
, _tcCache :: HashMap TyConName TyCon
-- ^ TyCon cache
, _tupleTcCache :: IntMap TyConName
-- ^ Tuple TyCon cache
, _evaluator :: HashMap TyConName TyCon -> Bool -> Term -> Term
-- ^ Hardcoded evaluator (delta-reduction)}
}
makeLenses ''RewriteEnv
-- | Monad that keeps track how many transformations have been applied and can
-- generate fresh variables and unique identifiers. In addition, it keeps track
-- if a transformation/rewrite has been successfully applied.
newtype RewriteMonad extra a = R
{ runR :: RewriteEnv -> RewriteState extra -> (a,RewriteState extra,Any) }
instance Functor (RewriteMonad extra) where
fmap f m = R (\r s -> case runR m r s of (a,s',w) -> (f a,s',w))
instance Applicative (RewriteMonad extra) where
pure = return
(<*>) = ap
instance Monad (RewriteMonad extra) where
return a = R (\_ s -> (a, s, mempty))
m >>= k = R (\r s -> case runR m r s of
(a,s',w) -> case runR (k a) r s' of
(b,s'',w') -> let w'' = mappend w w'
in seq w'' (b,s'',w''))
instance MonadState (RewriteState extra) (RewriteMonad extra) where
get = R (\_ s -> (s,s,mempty))
put s = R (\_ _ -> ((),s,mempty))
state f = R (\_ s -> case f s of (a,s') -> (a,s',mempty))
instance Fresh (RewriteMonad extra) where
fresh (Fn s _) = do
n <- nameCounter <<%= (+1)
let n' = toInteger n
n' `seq` return (Fn s n')
fresh nm@(Bn {}) = return nm
instance MonadUnique (RewriteMonad extra) where
getUniqueM = do
sup <- use uniqSupply
let (a,sup') = freshId sup
uniqSupply .= sup'
a `seq` return a
instance MonadWriter Any (RewriteMonad extra) where
writer (a,w) = R (\_ s -> (a,s,w))
tell w = R (\_ s -> ((),s,w))
listen m = R (\r s -> case runR m r s of (a,s',w) -> ((a,w),s',w))
pass m = R (\r s -> case runR m r s of ((a,f),s',w) -> (a, s', f w))
instance MonadReader RewriteEnv (RewriteMonad extra) where
ask = R (\r s -> (r,s,mempty))
local f m = R (\r s -> runR m (f r) s)
reader f = R (\r s -> (f r,s,mempty))
instance MonadFix (RewriteMonad extra) where
mfix f = R (\r s -> fix $ \ ~(a,_,_) -> runR (f a) r s)
-- | Monadic action that transforms a term given a certain context
type Transform m = [CoreContext] -> Term -> m Term
-- | A 'Transform' action in the context of the 'RewriteMonad'
type Rewrite extra = Transform (RewriteMonad extra)
| ggreif/clash-compiler | clash-lib/src/CLaSH/Rewrite/Types.hs | bsd-2-clause | 5,920 | 0 | 19 | 1,622 | 1,568 | 898 | 670 | 107 | 0 |
module League.Types.Region where
import Data.Aeson
import Data.Monoid
import Data.Text (Text)
data Region = BR
| EUNE
| EUW
| KR
| LAS
| LAN
| NA
| OCE
| TR
| RU
| Global
deriving (Show, Read, Eq)
instance FromJSON Region where
parseJSON (String s) =
case s of
"BR" -> return BR
"EUNE" -> return EUNE
"EUW" -> return EUW
"KR" -> return KR
"LAS" -> return LAS
"LAN" -> return LAN
"NA" -> return NA
"OCE" -> return OCE
"TR" -> return TR
"RU" -> return RU
"Global" -> return Global
_ -> mempty
parseJSON _ = mempty
regionalEndpoint :: Region -> Text
regionalEndpoint BR = "https://br.api.pvp.net"
regionalEndpoint EUNE = "https://eune.api.pvp.net"
regionalEndpoint EUW = "https://euw.api.pvp.net"
regionalEndpoint KR = "https://kr.api.pvp.net"
regionalEndpoint LAS = "https://las.api.pvp.net"
regionalEndpoint LAN = "https://lan.api.pvp.net"
regionalEndpoint NA = "https://na.api.pvp.net"
regionalEndpoint OCE = "https://oce.api.pvp.net"
regionalEndpoint TR = "https://tr.api.pvp.net"
regionalEndpoint RU = "https://ru.api.pvp.net"
regionalEndpoint Global = "https://global.api.pvp.net"
shortRegion :: Region -> Text
shortRegion BR = "br"
shortRegion EUNE = "eune"
shortRegion EUW = "euw"
shortRegion KR = "kr"
shortRegion LAS = "las"
shortRegion LAN = "lan"
shortRegion NA = "na"
shortRegion OCE = "oce"
shortRegion TR = "tr"
shortRegion RU = "ru"
shortRegion Global = "global"
| intolerable/league-of-legends | src/League/Types/Region.hs | bsd-3-clause | 1,583 | 0 | 9 | 405 | 412 | 211 | 201 | 56 | 1 |
{-# LANGUAGE OverloadedStrings, UnicodeSyntax, RecursiveDo #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MonoLocalBinds #-}
module MainW where
import Reflex.Dom (text, display, count, elAttr, (=:), (&), domEvent
, MonadWidget, foldDyn, Dynamic, constDyn
, EventName (..), mergeWith, holdDyn)
import Reflex.Dom.Core (mainWidget)
import Data.Monoid ((<>))
import Language.Javascript.JSaddle (JSM)
import qualified Reflex.Dom.HTML5.Attrs as A
import qualified Reflex.Dom.HTML5.Elements as E
--------------------------------------------------------------------------------
mainW ∷ JSM ()
mainW = mainWidget $ do
E.h1N $ text "Welcome to reflex-dom-htmlea"
intro
caveats
examples
intro ∷ MonadWidget t m ⇒ m ()
intro = do
E.divN $ do
E.pN $ do
text "Why? Reflex-dom-htmlea -lib "
E.bN $ text " helps "
text $ " to avoid some of the run-time "
<> "errors that are very easy to introduce with typos in attribute or "
<> "element names. Simply said: I hate runtime debugging! Especially "
<> "if the compiler is able to help."
E.pN $
text $ "In addition to that, the aim is to provide smart "
<> "constructors "
<> "for some of the common usage-patterns in order to help avoid combining "
<> "the elements in non-conforming way. "
<> "At the moment there ain't much support for that. "
E.pN $ do
text "There is some support to"
E.ulN $ do
E.liN $ text "let elements have only those attributes the specification says"
E.liN $ text "use a set of pre-defined element and attribute names"
E.pN $ do
text "This example app uses the "
E.a ( A.href ( A.URL "https://gist.github.com/3noch/ee335c94b92ea01b7fee9e6291e833be") E.defA)
$ text "turbo-charged ghcid settings (auto-reloading)"
text " to enable fluent work flow."
E.pN $ do
text $ ("Note that the structure of this lib is simple and "
<> " it is very easy to use. ")
caveats ∷ MonadWidget t m ⇒ m ()
caveats = do
E.h2N $ text "Caveats"
E.divN $ do
E.pN $ text "See README.md"
E.pN $ text $ "This lib is probably going to go through some "
<> "renaming, reshaping and other things as this lib "
<> "is still in its infancy. "
<> "Author is open to suggestions, PRs etc. (with usual disclaimers). "
E.pN $ text $ "And bugs are more than likely. There ain't any "
<> "test cases (just example programs) so some of the "
<> "element or attribute names may have typos atm. "
<> "Anyhow, given with little time, they are probably going to get "
<> "removed. "
examples ∷ MonadWidget t m ⇒ m ()
examples = do
E.h2N $ text "Other examples (take a look at the code)"
E.divN $ do
E.pN $ text "Note that you can "
E.ulN $ do
elAttr "li" (A.attrMap $ A.id_ "li1" $ A.defGlobals)
$ text "combine"
elAttr "li" (A.attrMap $ A.id_ "li2" $ A.defGlobals)
$ text "the defined elements"
elAttr "li" (A.attrMap li3Attrs) $ text "and attributes with"
-- Combining the Maps and provided combinators is possible.
elAttr "li" ("badAttr" =: "badValue" <> A.attrMap li3Attrs)
$ text "el-family of functions."
E.p (A.title "hmm" $ A.className "pclass" E.defP) $ text "A paragraph example."
-- E.p ( A.href (A.URL "hmm") $ A.className "pclass" $ E.defP)
-- text "Paragraph3"
-- No instance of p-tag has href-attr. So it cannot be used.
dialogEx
linkEx
embedEx
listEx
where
li3Attrs ∷ A.Globals
li3Attrs = A.className "myclass" $ A.id_ "li3" A.defGlobals
dialogEx ∷ forall t m. MonadWidget t m ⇒ m ()
dialogEx = do
E.h2N $ text "Dialog example"
E.div (A.setClasses [A.ClassName "hmm"] $ A.id_ "myId" $ E.defDiv) $ do
-- Note: Interactive elements have functions that end with C and
-- CD, those return Click-events.
evBtn ← E.buttonC E.defButton $ text "Open/Close dialog"
-- We could use other events and the associated information as well:
-- (evResBtn,_) ← E.button' E.defButton $ text "Open/Close dialog"
-- let evBtn = domEvent Mouseup evResBtn
rec
dOpen ← foldDyn ($) False
$ mergeWith (.) [ (\b → not b) <$ evBtn
, (\_ → False) <$ evCls
]
let dAttrs ∷ Dynamic t E.Dialog
= (\b →
if b
then E.defDialog
& A.title "Open title" & A.setClasses [A.ClassName "hmm"]
& A.open
else E.defDialog
& A.title "My closed title"
) <$> dOpen
evCls ← E.dialogD dAttrs $ do
E.h2N $ text "Dialog-box"
text "A user defined dialog (take a look of the attributes)"
E.buttonC E.defButton $ text "Close dialog"
pure ()
linkEx ∷ MonadWidget t m ⇒ m ()
linkEx = do
E.h2N $ text "Link example"
elAttr "p" (A.attrMap p1Attrs) $ do
text ("Paragraph-example with badly formed attributes. "
<> "(Look at the attributes of this paragraph.) ")
ev ← E.aC ( A.href (A.URL "#") $ A.className "myWarning" $ E.defA
) $ text "Here is a link with counter."
numbs ← foldDyn (+) (0 ∷ Int) (1 <$ ev)
text " Clicked the previous link "
display numbs
text " times and the following "
cnt ∷ Dynamic t Int
← count =<< (E.aC (A.href (A.URL "#") E.defA) $ text "link")
display cnt
text " times."
E.br_
where
-- Note that by using AnyAttr's, it is still easy to write non-valid
-- attributes (p-element doesn't have href-attributes).
p1Attrs ∷ A.AnyAttr
p1Attrs = A.href (A.URL "http://localhost") $ A.id_ "p1" $ A.defAnyAttr
-- By using the element-related attribute-structures, that wouldn't be
-- possible. E.g. try the E.p .. text "Paragraph3" above at "examples".
embedEx ∷ MonadWidget t m ⇒ m ()
embedEx = do
E.h2N $ text "Embdedded content examples"
E.divN $ do
text "Embedded content div "
fcnt ∷ Dynamic t Int
← count =<<
E.embedC ( A.width 200
$ A.src (A.URL "./figs/eveninglandscape.jpg") E.defEmbed)
text "Clicked the previous fig "
display fcnt
text " times."
E.br_
_ev ← E.iFrameC
( A.sbAllowSameOrigin
$ A.srcDoc "<p>Some HTML.</p><br><div>And more of it.</div>" E.defIFrame
) $ text "Alternative text if iframe not shown."
E.br_
E.divN $ do
text "Text input: "
_ev2 ← E.input (A.placeholder "your input" $ E.defInput) $ text " An input. "
E.br_
E.divN $ do
E.pN $ do
text "Note that you probably want to use the functions in "
E.a ( A.href (A.URL "https://github.com/reflex-frp/reflex-dom/blob/develop/reflex-dom-core/src/Reflex/Dom/Widget/Input.hs") E.defA)
$ text "Reflex.Dom.Widget.Input"
text " or in "
E.a (A.href (A.URL "https://github.com/reflex-frp/reflex-dom-contrib") E.defA)
$ text "reflex-dom-contrib -package"
text (" instead of the ones defined in "
<> "the Interactive-module of this lib.")
E.br_
listEx ∷ forall t m. MonadWidget t m ⇒ m()
listEx = do
E.h2N $ text "List examples"
E.ulN $ do
E.liN $ do
text "A list (1), reversed with given values"
E.ol (A.reversed E.defOl) $ do
E.li (A.valueOlLi 1 E.defLi) $ text "Value 1 given"
E.li (A.valueOlLi 2 E.defLi) $ text "Value 2 given"
E.li (A.valueOlLi 3 E.defLi) $ text "Value 3 given"
E.liN $ do
text "A list (2), reversed without given values"
E.ol (A.reversed E.defOl) $ do
E.liN $ text "No value given (1st in list)"
E.liN $ text "No value given (2st in list)"
E.liN $ text "No value given (3st in list)"
E.liN $ do
text "A list (3), default attributes"
E.olN $ do
E.liN $ text "No value given (1st in list)"
E.liN $ text "No value given (2st in list)"
E.liN $ text "No value given (3st in list)"
E.liN $ do
text "A list (4), with given values "
E.olN $ do
E.li (A.valueOlLi 1 E.defLi) $ text "Value 1 given"
E.li (A.valueOlLi 4 E.defLi) $ text "Value 4 given"
E.li (A.valueOlLi 3 E.defLi) $ text "Value 3 given"
E.li (A.valueOlLi 4 E.defLi) $ text "Value 4 given"
------------------------------------------------------------------------------
{-
--
hmm1 ∷ Globals
hmm1 = className "cl2" $ className "cl1" $ title "hmm1" def
hmm2 ∷ Globals
hmm2 = className "cl3" $ title "hmm2" def
hmm3 ∷ Globals
hmm3 = className "cl4" $ contentInheritEditable $ def
hmg1 ∷ Globals
hmg1 = hmm1 <> hmm2
hmg2 ∷ Globals
hmg2 = hmm2 <> hmm1
hmg3 ∷ Globals
hmg3 = hmm3 <> hmm1
hmg4 ∷ Globals
hmg4 = hmm1 <> hmm3
hmg5 ∷ Globals
hmg5 = hmm3 <> hmm1 <> hmm2 <> hmm3
-}
| gspia/reflex-dom-htmlea | example1/libEx1/MainW.hs | bsd-3-clause | 9,149 | 0 | 24 | 2,670 | 2,157 | 1,016 | 1,141 | 185 | 2 |
module Main (main) where
import Test.QuickCheck
import Test.QuickCheck.Test
import Test.QuickCheck.Random
import System.Exit
import System.Random.TF
-- import System.Process (callCommand)
import Text.Printf
import qualified Database.Concelo.Simulation as Simulation
import qualified Data.Tree.RBTests as RBTests
import qualified Control.Monad as M
check description prop = do
printf "%-25s: " description
result <- quickCheckWithResult
stdArgs { replay = Just (QCGen $ seedTFGen (0, 0, 0, 0), 0) } prop
M.unless (isSuccess result) $ do
putStrLn $ "Use " ++ show (usedSeed result) ++ " as the initial seed"
putStrLn $ "Use " ++ show (usedSize result) ++ " as the initial size"
exitFailure
main = do
Simulation.runTests check
RBTests.runTests check
-- callCommand "make test"
| Concelo/concelo | test/Main.hs | bsd-3-clause | 810 | 0 | 15 | 143 | 226 | 123 | 103 | 21 | 1 |
module Protocol.Types
( PeerId
, InfoHash
, Piece(..)
, PieceNum
, PieceSize
, PieceBlock(..)
, PieceBlockSize
, PieceBlockOffset
, PieceArray
, PieceHaveMap
, Capabilities(..)
) where
import Data.Array (Array)
import qualified Data.ByteString as B
import qualified Data.Map as M
type PeerId = String
type InfoHash = B.ByteString
data Piece = Piece
{ pieceOffset :: Integer
, pieceLength :: Integer
, pieceChecksum :: B.ByteString
} deriving (Show)
type PieceNum = Integer
type PieceSize = Integer
data PieceBlock = PieceBlock
{ blockSize :: PieceBlockSize
, blockOffset :: PieceBlockOffset
} deriving (Eq, Show)
type PieceBlockSize = Integer
type PieceBlockOffset = Integer
type PieceArray = Array PieceNum Piece
type PieceHaveMap = M.Map PieceNum Bool
data Capabilities
= Fast
| Extended
deriving (Show)
| artems/FlashBit | src/Protocol/Types.hs | bsd-3-clause | 906 | 0 | 9 | 218 | 226 | 143 | 83 | 36 | 0 |
{-# language CPP #-}
-- | = Name
--
-- XR_EXT_win32_appcontainer_compatible - instance extension
--
-- = Specification
--
-- See
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_EXT_win32_appcontainer_compatible XR_EXT_win32_appcontainer_compatible>
-- in the main specification for complete information.
--
-- = Registered Extension Number
--
-- 58
--
-- = Revision
--
-- 1
--
-- = Extension and Version Dependencies
--
-- - Requires OpenXR 1.0
--
-- = See Also
--
-- No cross-references are available
--
-- = Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_EXT_win32_appcontainer_compatible OpenXR Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module OpenXR.Extensions.XR_EXT_win32_appcontainer_compatible ( EXT_win32_appcontainer_compatible_SPEC_VERSION
, pattern EXT_win32_appcontainer_compatible_SPEC_VERSION
, EXT_WIN32_APPCONTAINER_COMPATIBLE_EXTENSION_NAME
, pattern EXT_WIN32_APPCONTAINER_COMPATIBLE_EXTENSION_NAME
) where
import Data.String (IsString)
type EXT_win32_appcontainer_compatible_SPEC_VERSION = 1
-- No documentation found for TopLevel "XR_EXT_win32_appcontainer_compatible_SPEC_VERSION"
pattern EXT_win32_appcontainer_compatible_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_win32_appcontainer_compatible_SPEC_VERSION = 1
type EXT_WIN32_APPCONTAINER_COMPATIBLE_EXTENSION_NAME = "XR_EXT_win32_appcontainer_compatible"
-- No documentation found for TopLevel "XR_EXT_WIN32_APPCONTAINER_COMPATIBLE_EXTENSION_NAME"
pattern EXT_WIN32_APPCONTAINER_COMPATIBLE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_WIN32_APPCONTAINER_COMPATIBLE_EXTENSION_NAME = "XR_EXT_win32_appcontainer_compatible"
| expipiplus1/vulkan | openxr/src/OpenXR/Extensions/XR_EXT_win32_appcontainer_compatible.hs | bsd-3-clause | 2,085 | 0 | 8 | 441 | 145 | 99 | 46 | -1 | -1 |
{-# LANGUAGE Rank2Types, BangPatterns, MagicHash, TypeOperators #-}
module Data.TrieMap.Utils where
import Control.Monad.Unpack
import Control.Monad.Primitive
import Data.Bits
import qualified Data.Foldable
import Data.Vector.Generic
import Data.Vector.Generic.Mutable
import Data.Vector.Fusion.Stream (MStream)
import GHC.Exts
{-# INLINE mapInput #-}
mapInput :: (Unpackable a, Unpackable b) => (a -> b) -> (b :~> c) -> (a :~> c)
mapInput f func = unpack $ \ a -> func $~ f a
{-# INLINE toVectorN #-}
toVectorN :: Vector v a => (forall b . (a -> b -> b) -> b -> f -> b) -> (f -> Int) -> f -> v a
toVectorN fold size xs = create $ do
!mv <- unsafeNew (size xs)
fold (\ x m i# -> unsafeWrite mv (I# i#) x >> m (i# +# 1#)) (\ _ -> return mv) xs 0#
{-# INLINE unstreamM #-}
unstreamM :: (Vector v a, PrimMonad m) => MStream m a -> m (v a)
unstreamM strm = munstream strm >>= unsafeFreeze
{-# INLINE toVectorF #-}
toVectorF :: (Vector v b, Data.Foldable.Foldable f) => (a -> b) -> (f a -> Int) -> f a -> v b
toVectorF g = toVectorN (\ f -> Data.Foldable.foldr (f . g))
{-# INLINE quoPow #-}
quoPow :: Int -> Int -> Int
n `quoPow` 1 = n
n `quoPow` 2 = n `shiftR` 1
n `quoPow` 4 = n `shiftR` 2
n `quoPow` 8 = n `shiftR` 3
n `quoPow` 16 = n `shiftR` 4
n `quoPow` 32 = n `shiftR` 5
n `quoPow` 64 = n `shiftR` 6
n `quoPow` k = n `quot` k
{-# INLINE remPow #-}
remPow :: Int -> Int -> Int
n `remPow` k = if k .&. (k-1) == 0 then n .&. (k-1) else n `rem` k
compl :: Word -> Word
compl (W# w#) = W# (not# w#)
(.<<.) :: Word -> Int -> Word
W# w# .<<. I# i# = W# (uncheckedShiftL# w# i#)
(.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(f .: g) a b = f (g a b)
{-# RULES
"or 0" forall w# . or# w# 0## = w#;
"0 or" forall w# . or# 0## w# = w#;
"shiftL 0" forall w# . uncheckedShiftL# w# 0# = w#;
"plusAddr 0" forall a# . plusAddr# a# 0# = a#;
#-} | lowasser/TrieMap | Data/TrieMap/Utils.hs | bsd-3-clause | 1,853 | 0 | 14 | 408 | 823 | 446 | 377 | 48 | 2 |
module Data.Problem13 where
input = "37107287533902102798797998220837590246510135740250\n\
\46376937677490009712648124896970078050417018260538\n\
\74324986199524741059474233309513058123726617309629\n\
\91942213363574161572522430563301811072406154908250\n\
\23067588207539346171171980310421047513778063246676\n\
\89261670696623633820136378418383684178734361726757\n\
\28112879812849979408065481931592621691275889832738\n\
\44274228917432520321923589422876796487670272189318\n\
\47451445736001306439091167216856844588711603153276\n\
\70386486105843025439939619828917593665686757934951\n\
\62176457141856560629502157223196586755079324193331\n\
\64906352462741904929101432445813822663347944758178\n\
\92575867718337217661963751590579239728245598838407\n\
\58203565325359399008402633568948830189458628227828\n\
\80181199384826282014278194139940567587151170094390\n\
\35398664372827112653829987240784473053190104293586\n\
\86515506006295864861532075273371959191420517255829\n\
\71693888707715466499115593487603532921714970056938\n\
\54370070576826684624621495650076471787294438377604\n\
\53282654108756828443191190634694037855217779295145\n\
\36123272525000296071075082563815656710885258350721\n\
\45876576172410976447339110607218265236877223636045\n\
\17423706905851860660448207621209813287860733969412\n\
\81142660418086830619328460811191061556940512689692\n\
\51934325451728388641918047049293215058642563049483\n\
\62467221648435076201727918039944693004732956340691\n\
\15732444386908125794514089057706229429197107928209\n\
\55037687525678773091862540744969844508330393682126\n\
\18336384825330154686196124348767681297534375946515\n\
\80386287592878490201521685554828717201219257766954\n\
\78182833757993103614740356856449095527097864797581\n\
\16726320100436897842553539920931837441497806860984\n\
\48403098129077791799088218795327364475675590848030\n\
\87086987551392711854517078544161852424320693150332\n\
\59959406895756536782107074926966537676326235447210\n\
\69793950679652694742597709739166693763042633987085\n\
\41052684708299085211399427365734116182760315001271\n\
\65378607361501080857009149939512557028198746004375\n\
\35829035317434717326932123578154982629742552737307\n\
\94953759765105305946966067683156574377167401875275\n\
\88902802571733229619176668713819931811048770190271\n\
\25267680276078003013678680992525463401061632866526\n\
\36270218540497705585629946580636237993140746255962\n\
\24074486908231174977792365466257246923322810917141\n\
\91430288197103288597806669760892938638285025333403\n\
\34413065578016127815921815005561868836468420090470\n\
\23053081172816430487623791969842487255036638784583\n\
\11487696932154902810424020138335124462181441773470\n\
\63783299490636259666498587618221225225512486764533\n\
\67720186971698544312419572409913959008952310058822\n\
\95548255300263520781532296796249481641953868218774\n\
\76085327132285723110424803456124867697064507995236\n\
\37774242535411291684276865538926205024910326572967\n\
\23701913275725675285653248258265463092207058596522\n\
\29798860272258331913126375147341994889534765745501\n\
\18495701454879288984856827726077713721403798879715\n\
\38298203783031473527721580348144513491373226651381\n\
\34829543829199918180278916522431027392251122869539\n\
\40957953066405232632538044100059654939159879593635\n\
\29746152185502371307642255121183693803580388584903\n\
\41698116222072977186158236678424689157993532961922\n\
\62467957194401269043877107275048102390895523597457\n\
\23189706772547915061505504953922979530901129967519\n\
\86188088225875314529584099251203829009407770775672\n\
\11306739708304724483816533873502340845647058077308\n\
\82959174767140363198008187129011875491310547126581\n\
\97623331044818386269515456334926366572897563400500\n\
\42846280183517070527831839425882145521227251250327\n\
\55121603546981200581762165212827652751691296897789\n\
\32238195734329339946437501907836945765883352399886\n\
\75506164965184775180738168837861091527357929701337\n\
\62177842752192623401942399639168044983993173312731\n\
\32924185707147349566916674687634660915035914677504\n\
\99518671430235219628894890102423325116913619626622\n\
\73267460800591547471830798392868535206946944540724\n\
\76841822524674417161514036427982273348055556214818\n\
\97142617910342598647204516893989422179826088076852\n\
\87783646182799346313767754307809363333018982642090\n\
\10848802521674670883215120185883543223812876952786\n\
\71329612474782464538636993009049310363619763878039\n\
\62184073572399794223406235393808339651327408011116\n\
\66627891981488087797941876876144230030984490851411\n\
\60661826293682836764744779239180335110989069790714\n\
\85786944089552990653640447425576083659976645795096\n\
\66024396409905389607120198219976047599490197230297\n\
\64913982680032973156037120041377903785566085089252\n\
\16730939319872750275468906903707539413042652315011\n\
\94809377245048795150954100921645863754710598436791\n\
\78639167021187492431995700641917969777599028300699\n\
\15368713711936614952811305876380278410754449733078\n\
\40789923115535562561142322423255033685442488917353\n\
\44889911501440648020369068063960672322193204149535\n\
\41503128880339536053299340368006977710650566631954\n\
\81234880673210146739058568557934581403627822703280\n\
\82616570773948327592232845941706525094512325230608\n\
\22918802058777319719839450180888072429661980811197\n\
\77158542502016545090413245809786882778948721859617\n\
\72107838435069186155435662884062257473692284509516\n\
\20849603980134001723930671666823555245252804609722\n\
\53503534226472524250874054075591789781264330331690"
| anup-2s/project-euler | src/data/Problem13.hs | bsd-3-clause | 5,931 | 0 | 4 | 502 | 11 | 7 | 4 | 2 | 1 |
{-# LANGUAGE TupleSections #-}
{- |
Function for making an automaton complete (transition on every symbol at every state)
-}
module FST.Complete (
complete
) where
import FST.Automaton
import Data.List ( (\\) )
-- | Make a automaton complete (transition on every symbol at every state)
complete :: Eq a => Automaton a -> Automaton a
complete auto =
construct (firstState auto, sink) newTrans
(alphabet auto) (initials auto)
(finals auto) where
sink = lastState auto + 1
sinkTr = (sink, map (,sink) (alphabet auto))
newTrans = sinkTr:completeStates auto sink (states auto) []
completeStates :: Eq a => Automaton a -> StateTy -> [StateTy] -> [(StateTy,Transitions a)] -> [(StateTy,Transitions a)]
completeStates _ _ [] trans = trans
completeStates auto sink (state:states) trans
= completeStates auto sink states ((state, tr ++ nTr):trans)
where
tr = transitionList auto state
nTr = map (,sink) (alphabet auto \\ map fst tr)
| johnjcamilleri/fst | FST/Complete.hs | bsd-3-clause | 998 | 0 | 12 | 221 | 327 | 174 | 153 | 19 | 1 |
module Main where
import System.Console.GetOpt
import System.Environment
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Parse
import Info
import Icon
data Options = Options
{ optVersion :: Bool
, optHelp :: Bool
, optDzen :: Bool
, optIcon :: Bool
, optFg :: String
, optBg :: String
, optFormat :: String
} deriving Show
defaultOptions = Options
{ optVersion = False
, optHelp = False
, optDzen = False
, optIcon = False
, optFg = "#999999"
, optBg = "#666666"
, optFormat = "music volume temp wifi load time"
}
options :: [OptDescr (Options -> Options)]
options =
[ Option ['v'] ["version"]
(NoArg (\opts -> opts { optVersion = True }))
"shows program version"
, Option ['h'] ["help"]
(NoArg (\opts -> opts { optHelp = True }))
"displays usage info"
, Option ['d'] ["dzen"]
(NoArg (\opts -> opts { optDzen = True }))
"formats output for dzen2"
, Option ['i'] ["icons"]
(NoArg (\opts -> opts { optDzen = True, optIcon = True }))
"adds icons. implies --dzen"
, Option ['f'] ["fg"]
(ReqArg (\f opts -> opts { optFg = f }) "COLOUR")
"sets the colour of the text"
, Option ['b'] ["bg"]
(ReqArg (\b opts -> opts { optBg = b }) "COLOUR")
"sets the colour of the background"
, Option ['F'] ["format"]
(ReqArg (\f opts -> opts { optFormat = f }) "\"FORMAT\"")
"formats info according to FORMAT"
]
header = "Usage: hinfo [OPTIONS]\n"
footer = "\nReport bugs to <kaashif@kaashif.co.uk>"
progOpts :: [String] -> IO Options
progOpts argv =
case getOpt Permute options argv of
(o,_,[]) -> return (foldl (flip id) defaultOptions o)
(_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
handleOpts :: Options -> IO ()
handleOpts opts
| optVersion opts = putStrLn "hinfo 1.0.0.0"
| optHelp opts = putStrLn $ (usageInfo header options) ++ footer
| optDzen opts = (getAllDzenInfo dzenopts $ parse $ optFormat opts) >>= TI.putStrLn
| otherwise = (getAllInfo $ parse $ optFormat opts) >>= TI.putStrLn
where dzenopts = DzenOpts { fg = T.pack $ optFg opts
, bg = T.pack $ optBg opts
, icons = optIcon opts
}
main = do
argv <- getArgs
opts <- progOpts argv
ensureConfig
handleOpts opts
| kaashif/hinfo | src/Main.hs | bsd-3-clause | 2,409 | 0 | 13 | 661 | 789 | 439 | 350 | 69 | 2 |
{-#LANGUAGE OverloadedStrings#-}
{-#LANGUAGE FlexibleContexts#-}
{-#LANGUAGE TemplateHaskell#-}
{-#LANGUAGE QuasiQuotes#-}
{-#LANGUAGE ScopedTypeVariables#-}
import Test.Hspec
import Language.Cube
import Graphics.Formats.STL
-- | Generate house which is for demo.
house :: Block Cube
house = let house'' = (house' + square)*line
in rfmap (12 * dz +) house''
where
house' :: Block Cube
house' = block $ [cube 1 x y| x<-[-10..10], y<-[-10..10], y < x , y < (-x)]
square :: Block Cube
square = rfmap ((+) (-12 * dz)) $ block $ [cube 1 x y| x<-[-5..5], y<-[-5..5]]
line :: Block Cube
line = block $ [cube x 0 0 | x<-[-5..5]]
main :: IO ()
main =
hspec $ do
describe "Cube(quoternion)" $ do
it "dx" $ do
cube 1 0 0 `shouldBe` dx
it "dy" $ do
cube 0 1 0 `shouldBe` dy
it "dz" $ do
cube 0 0 1 `shouldBe` dz
it "dx + dx" $ do
dx + dx `shouldBe` cube 2 0 0
it "2 * dx" $ do
2 * dx `shouldBe` cube 2 0 0
it "-2 * dx" $ do
(-2) * dx `shouldBe` cube (-2) 0 0
it "route pi/2" $ do
(dR (pi/2) dz dx) `shouldBe` cube 0 1 0
it "route pi" $ do
(dR (pi) dz dx) `shouldBe` cube (-1) 0 0
it "route 3*pi/2" $ do
(dR (3*pi/2) dz dx) `shouldBe` cube 0 (-1) 0
it "route 2*pi" $ do
(dR (2*pi) dz dx) `shouldBe` cube 1 0 0
it "multi" $ do
dx * dy `shouldBe` (dz :: Cube)
it "multi" $ do
dy * dx `shouldBe` (-dz :: Cube)
describe "Block" $ do
it "dx" $ do
block [dx,dx] `shouldBe` (block [dx] :: Block Cube)
it "dx+dy" $ do
block [dx] + block [dy] `shouldBe` (block [dx,dy] :: Block Cube)
it "[dx,dy]-dy" $ do
block [dx,dy] - block [dy] `shouldBe` (block [dx] :: Block Cube)
it "convolution(dx * [-2*dx,2*dx])" $ do
block [dx] * block [-2*dx,2*dx] `shouldBe` (block [-dx,3*dx] :: Block Cube)
describe "Compaction" $ do
it "num triangle of one block" $ do
length (triangles (toSTL (block [dx] :: Block Cube))) `shouldBe` 12
it "num triangle of two block" $ do
length (triangles (toSTL (block [dx,2*dx] :: Block Cube))) `shouldBe` 20
it "flip triangle" $ do
(flipTriangle (Triangle Nothing ((5.0,0,0),(1,0,0),(2,0,0)))) `shouldBe` (Triangle Nothing ((5.0,0,0),(2,0,0),(1,0,0)))
describe "ToSTL" $ do
it "Block Cube" $ do
writeFileStl "tmp.stl" (block [dx] :: Block Cube) `shouldReturn` ()
writeFileStl "house.stl" house `shouldReturn` ()
| junjihashimoto/cube | tests/test.hs | bsd-3-clause | 2,568 | 0 | 23 | 760 | 1,249 | 640 | 609 | 65 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Data.Syslog
( Facility(..)
, Priority(..)
, syslogCode
) where
import Data.Typeable
data Priority =
EMERGENCY
| ALERT
| CRITICAL
| ERROR
| WARNING
| NOTICE
| INFO
| DEBUG
deriving (Eq, Ord, Bounded, Enum, Show, Read, Typeable)
data Facility =
KERN
| USER
| MAIL
| DAEMON
| AUTH
| SYSLOG
| LPR
| NEWS
| UUCP
| CRON
| AUTHPRIV
| FTP
| NTP
| LOG_AUDIT
| LOG_ALERT
| CLOCK
| LOCAL0
| LOCAL1
| LOCAL2
| LOCAL3
| LOCAL4
| LOCAL5
| LOCAL6
| LOCAL7
deriving (Eq, Ord, Bounded, Enum, Show, Read, Typeable)
syslogCode :: Integral n => Facility -> Priority -> n
syslogCode x y = 8 * fromIntegral (fromEnum x) + fromIntegral (fromEnum y)
{-# INLINE syslogCode #-}
| lpsmith/modern-syslog | src/Data/Syslog.hs | bsd-3-clause | 830 | 0 | 9 | 262 | 254 | 149 | 105 | 45 | 1 |
-- Copyright (c) 2015, Travis Bemann
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- o Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- o Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- o Neither the name of the copyright holder nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{-# LANGUAGE OverloadedStrings #-}
module Network.IRC.Client.Amphibian.Ctcp
(checkCtcp,
parseCtcp,
formatCtcp,
escapeCtcp,
unescapeCtcp)
where
import Network.IRC.Client.Amphibian.Types
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.UTF8 as BUTF8
import Data.Char (isSpace)
import Data.Strings (byteToChar)
-- | Is a message or notice a CTCP request or reply?
checkCtcp :: MessageComment -> Maybe MessageComment
checkCtcp comment =
case BUTF8.uncons $ unescapeCtcp comment of
Just ('\x1', rest) ->
let len = BUTF8.length rest of
if len > 0
then let (body, end) = BUTF8.splitAt (len - 1) rest in
if end == '\x1'
then Just body
else Nothing
else Nothing
Nothing -> Nothing
-- | Parse CTCP request or response.
parseCtcp :: MessageComment -> Maybe (CtcpCommand, Maybe CtcpArgument)
parseCtcp comment =
let (command, rest) = BUTF8.break isSpace comment in
if command /= B.empty
then case BUTF8.uncons rest of
Just (_, argument) -> Just (command, Just argument)
Nothing -> Just (command, Nothing)
else Nothing
-- | Format CTCP request or response.
formatCtcp :: CtcpCommand -> Maybe CtcpArgument -> MessageComment
formatCtcp command (Just argument) = escapeCtcp $ B.concat ["\x1", command, " ", argument, "\x1"]
formatCtcp command nothing = escapeCtcp $ B.concat ["\x1", command, "\x1"]
-- | Escape CTCP data.
escapeCtcp :: B.ByteString -> MessageComment
escapeCtcp data =
B.concat $ B.foldr' doEscape [] data
where doEscape byte accum =
case byteToChar byte of
'\r' -> "\x10r" : accum
'\n' -> "\x10n" : accum
'\x0' -> B.append "\x10" "0" : accum
'\x10' -> "\x10\x10": accum
_ -> B.singleton byte : accum
-- | Unescape CTCP data.
unescapeCtcp :: MessageComment -> B.ByteString
unescapeCtcp comment = unescapeCtcp' comment []
where unescapeCtcp' data accum =
case B.uncons data of
Just (byte, rest)
| byteToChar byte == '\x10' ->
case B.uncons rest of
Just (byte, rest)
| byteToChar byte == 'r' -> unescapeCtcp' rest ("\r" : accum)
| byteToChar byte == 'n' -> unescapeCtcp' rest ("\n" : accum)
| byteToChar byte == '0' -> unescapeCtcp' rest ("\x0" : accum)
| byteToChar byte == '\x10' -> unescapeCtcp' rest ("\x10" : accum)
_ -> unescapeCtcp' rest ("\x10" : accum)
| otherwise -> unescapeCtcp' data (B.singleton byte : accum)
Nothing -> B.concat $ reverse accum
| tabemann/amphibian | src_old/Network/IRC/Client/Amphibian/Ctcp.hs | bsd-3-clause | 4,204 | 13 | 15 | 926 | 764 | 423 | 341 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.