code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, CPP, DeriveDataTypeable, FlexibleContexts, GeneralizedNewtypeDeriving, MultiParamTypeClasses, TemplateHaskell, TypeFamilies, RecordWildCards #-}
import Control.Applicative ((<$>), optional)
import Control.Exception ( bracket )
import Control.Monad ( msum, forM_, mapM_ )
import Control.Monad.Reader ( ask )
import Control.Monad.State ( get, put )
import Data.Data ( Data, Typeable )
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text.Lazy (unpack)
import Happstack.Server (Response, ServerPart, dir, nullDir, nullConf, ok, simpleHTTP, toResponse, Method(..), method, seeOther, look, lookText, decodeBody, BodyPolicy, defaultBodyPolicy )
import Data.Acid ( AcidState, Query, Update
, makeAcidic, openLocalState )
import Data.Acid.Advanced ( query', update' )
import Data.Acid.Local ( createCheckpointAndClose )
import Data.SafeCopy ( base, deriveSafeCopy, SafeCopy )
import Text.Blaze.Html5 (Html, (!), a, form, input, p, toHtml, label)
import Text.Blaze.Html5.Attributes (action, enctype, href, name, size, type_, value)
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Data.IxSet ( Indexable(..), IxSet(..), (@=)
, Proxy(..), getOne, ixFun, ixSet, toList, insert )
-- types for characters
newtype CharacterId = CharacterId { unCharacterId :: Integer }
deriving (Eq, Ord, Read, Show, Data, Enum, Typeable, SafeCopy)
type Initiative = (Integer, Integer) -- base and num of dice
data Character = Character {
charId :: CharacterId,
charName :: String,
charInitiative :: Maybe Initiative
} deriving (Eq, Ord, Read, Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''Character)
instance Indexable Character where
empty = ixSet
[ ixFun $ \bp -> [charId bp]
]
-- global app state
data AppState = AppState {
stateNextCharId :: Integer,
stateCharacters :: IxSet Character
} deriving (Eq, Ord, Read, Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''AppState)
initialAppState :: AppState
initialAppState = AppState 1 empty
-- state manipulation
peekCharacters :: Query AppState [Character]
peekCharacters = do
AppState{..} <- ask
return $ toList stateCharacters
addCharacter :: Character -> Update AppState [Character]
addCharacter c = do
a@AppState{..} <- get
let newChars = insert (c { charId = CharacterId stateNextCharId }) stateCharacters
let newNextId = stateNextCharId + 1
put $ a { stateCharacters = newChars, stateNextCharId = newNextId }
return $ toList newChars
$(makeAcidic ''AppState [ 'peekCharacters, 'addCharacter ])
-- web templates
templateCharacters :: [Character] -> ServerPart Response
templateCharacters cs =
ok $ template "characters" $ do
H.h1 "Characters"
H.table $ forM_ cs (\c ->
H.tr $ do
H.td $ (toHtml (unCharacterId $ charId c))
H.td $ (toHtml (charName c))
H.td $ (toHtml (show (charInitiative c)))
)
H.form ! action "/char" ! enctype "multipart/form-data" ! A.method "POST" $ do
label ! A.for "msg" $ "enter new name"
input ! type_ "text" ! A.id "name" ! name "name"
input ! type_ "submit" ! value "add character"
myPolicy :: BodyPolicy
myPolicy = (defaultBodyPolicy "/tmp/" 0 1000 1000)
handlers :: AcidState AppState -> ServerPart Response
handlers acid = do
decodeBody myPolicy
msum
[ dir "char" $ do
method GET
cs <- query' acid PeekCharacters
templateCharacters cs
, dir "char" $ do
method POST
name <- look "name"
-- decodeBody
c <- update' acid (AddCharacter (Character (CharacterId 0) name Nothing))
seeOther ("/char" :: String) (toResponse ())
, homePage
]
main :: IO ()
main =
bracket (openLocalState initialAppState)
(createCheckpointAndClose)
(\acid ->
simpleHTTP nullConf (handlers acid))
template :: Text -> Html -> Response
template title body = toResponse $
H.html $ do
H.head $ do
H.title (toHtml title)
H.body $ do
body
p $ a ! href "/" $ "back home"
homePage :: ServerPart Response
homePage =
ok $ template "home page" $ do
H.h1 "Hello!"
|
jpschaumloeffel/sr5gm
|
sr5gm/sr5gm.hs
|
Haskell
|
mit
| 4,167
|
{-# LANGUAGE OverloadedStrings #-}
import Data.Hash.MD5
import qualified Database.Redis as R
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import Web.Scotty
import Network.HTTP.Types
import Control.Monad.Trans (liftIO)
import qualified Data.Text.Lazy.Encoding as TL
import Data.Tuple (swap)
import Data.List (unfoldr)
shorten :: String -> Int -> String
shorten = shorten' (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'])
shorten' :: String -> String -> Int -> String
shorten' charset url len = toCharset charset (convertToBase urlhash ((fromIntegral . length) charset))
where
urlhash = md5i (Str url) `mod` (fromIntegral (length charset) ^ len)
toCharset :: Integral a => String -> [a] -> String
toCharset ch = map ((ch!!) . fromIntegral)
convertToBase :: Integral a => a -> a -> [a]
convertToBase n b = unfoldr (tomb . swap . (`divMod` b)) n
where tomb x@(0, 0) = Nothing
tomb x = Just x
-- convertToBase n b = map snd $ takeWhile (\(a, b) -> a /= 0 || b /= 0) h
-- where h = divMod n b : map (\(a, _) -> divMod a b) h
addUrl :: String -> IO (Maybe String)
addUrl url = do conn <- R.connect R.defaultConnectInfo
R.runRedis conn $ do
u <- R.get (B.pack shortUrl)
case u of
Right Nothing -> do R.set (B.pack shortUrl) (B.pack url)
return (Just shortUrl)
Right (Just a) -> if a == B.pack url
then return (Just shortUrl)
else return Nothing
otherwise -> return Nothing
where shortUrl = shorten url 3
runServer :: IO ()
runServer = scotty 3000 $ do
get "/:short" $ do
short <- param "short"
con <- liftIO $ R.connect R.defaultConnectInfo
u <- liftIO $ R.runRedis con (R.get short)
case u of
Right (Just url) -> redirect (TL.decodeUtf8 (BL.fromStrict url))
otherwise -> do liftIO $ putStrLn "not found"
status status404
html "404 - not found"
|
EDmitry/shortener-hs
|
shortener.hs
|
Haskell
|
mit
| 2,150
|
import Control.Monad.Reader
data Expr
= Val Int
| Add Expr Expr
| Var String
deriving (Show)
type Env = [(String, Int)]
type Eval a = ReaderT Env Maybe a
eval :: Expr -> Eval Int
eval (Val n) = return n
eval (Add x y) = liftM2 (+) (eval x) (eval y)
eval (Var x) = do
env <- ask
val <- lift (lookup x env)
return val
ex :: Eval Int
ex = eval (Add (Val 2) (Add (Val 1) (Var "x")))
env :: Env
env = [("x", 2), ("y", 5)]
example1, example2 :: Maybe Int
example1 = runReaderT ex env
example2 = runReaderT ex []
|
riwsky/wiwinwlh
|
src/transformer.hs
|
Haskell
|
mit
| 527
|
{-# LANGUAGE OverloadedStrings #-}
module Data.Time.Calendar.BankHolidaySpec (spec) where
import Data.Time
import Data.Time.Calendar.BankHoliday (isWeekday, isWeekend)
import Test.Hspec
spec :: Spec
spec = do
describe "isWeekday" $ do
it "is accurate" $ do
all (\d -> isWeekday d) [
(fromGregorian 1987 1 1)
, (fromGregorian 1999 5 3)
, (fromGregorian 1999 11 19)
, (fromGregorian 2014 7 4)
, (fromGregorian 2015 11 4)
, (fromGregorian 2015 12 16)
, (fromGregorian 2016 1 1)
]
describe "isWeekend" $ do
it "is accurate" $ do
all (\d -> isWeekend d) [
(fromGregorian 1987 1 10)
, (fromGregorian 1999 11 20)
, (fromGregorian 2015 11 15)
, (fromGregorian 2015 12 12)
, (fromGregorian 2015 7 4)
, (fromGregorian 2015 12 13)
, (fromGregorian 2015 11 14)
]
|
tippenein/BankHoliday
|
test/Data/Time/Calendar/BankHolidaySpec.hs
|
Haskell
|
mit
| 911
|
module Aldus.Types where
|
lgastako/aldus
|
src/Aldus/Types.hs
|
Haskell
|
mit
| 26
|
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TypeOperators,
FlexibleContexts #-}
module Main where
import Control.Monad
import Data.List
import Data.Yaml
import Flow
import Flow.Builder ( rule )
import Flow.Kernel
import Kernel.Binning
import Kernel.Cleaning
import Kernel.Data
import Kernel.Degrid
import Kernel.Facet
import Kernel.FFT
import Kernel.Gridder
import Kernel.IO
import Kernel.Scheduling
import System.Environment
import System.Directory
import System.FilePath
-- ----------------------------------------------------------------------------
-- --- Functional ---
-- ----------------------------------------------------------------------------
-- Gridding
createGrid :: Flow UVGrid
createGrid = flow "create grid"
grid :: Flow Vis -> Flow GCFs -> Flow UVGrid -> Flow UVGrid
grid = flow "grid"
degrid :: Flow GCFs -> Flow FullUVGrid -> Flow Vis -> Flow Vis
degrid = flow "degrid"
gcf :: Flow Vis -> Flow GCFs
gcf = flow "gcf"
-- FFT
dft :: Flow Image -> Flow FullUVGrid
dft = flow "dft"
idft :: Flow UVGrid -> Flow Image
idft = flow "idft"
-- Image summation for continuum
createImage :: Flow Image
createImage = flow "create image"
facetSum :: Flow Image -> Flow Image -> Flow Image
facetSum = flow "facet sum"
sumImage :: Flow Image -> Flow Image -> Flow Image
sumImage = flow "sum image"
-- Cleaning
psfVis :: Flow Vis -> Flow Vis
psfVis = flow "make PSF visibilities"
clean :: Flow Image -> Flow Image -> Flow Image -> Flow Cleaned
clean = flow "clean"
splitModel :: Flow Cleaned -> Flow Image
splitModel = flow "model from cleaning"
splitResidual :: Flow Cleaned -> Flow Image
splitResidual = flow "residual from cleaning"
-- Compound actors
gridder :: Flow Vis -> Flow Vis -> Flow Image
gridder vis0 vis = idft (grid vis (gcf vis0) createGrid)
summed :: Flow Vis -> Flow Vis -> Flow Image
summed vis0 vis = sumImage (facetSum (gridder vis0 vis) createImage) createImage
-- | Calculate a point spread function, which tells us the image shape
-- of a single point source in the middle of the field of view
psf :: Flow Vis -> Flow Image
psf vis = summed vis (psfVis vis)
-- | Update a model by gridding the given (possibly corrected)
-- visibilities and cleaning the result.
model :: Flow Vis -> Flow Vis -> Flow Image -> Flow Image
model vis0 vis mdl = splitModel $ clean (psf vis0) (summed vis0 vis) mdl
-- | Calculate a residual by gridding the given visibilities and
-- cleaning the result.
residual :: Flow Vis -> Flow Vis -> Flow Image
residual vis0 vis = splitResidual $ clean (psf vis0) (summed vis0 vis) createImage
-- | Degrid a model, producing corrected visibilities where we
-- have attempted to eliminate the effects of sources in the model.
degridModel :: Flow Vis -> Flow Image -> Flow Vis
degridModel vis mdl = degrid (gcf vis) (dft mdl) vis
-- | Major loop iteration: From visibilities infer components in the
-- image and return the updated model.
loopIter :: Flow Vis -> Flow Image -> Flow Image
loopIter vis mdl = model vis (degridModel vis mdl) mdl
-- | Final major loop iteration: Do the same steps as usual, but
-- return just the residual.
finalLoopIter :: Flow Vis -> Flow Image -> Flow Image
finalLoopIter vis mdl = residual vis (degridModel vis mdl)
-- ----------------------------------------------------------------------------
-- --- Strategy ---
-- ----------------------------------------------------------------------------
cpuHints, allCpuHints :: [ProfileHint]
cpuHints = [floatHint, memHint]
allCpuHints = ioHint:cpuHints
-- | Implement one major iteration of continuum gridding (@loopIter@) for
-- the given input 'Flow's over a number of datasets given by the data
-- set domains @ddoms@. Internally, we will distribute twice over
-- @DDom@ and once over @UVDom@.
continuumGridStrat :: Config -> [DDom] -> TDom -> [UVDom] -> [LMDom]
-> Flow Index -> Flow Vis -> Flow Vis
-> Strategy (Flow Image)
continuumGridStrat cfg [ddomss,ddoms,ddom] tdom [uvdoms,uvdom] [_lmdoms,lmdom]
ixs vis0 vis
= implementing (summed vis0 vis) $ do
-- Helpers
let dkern :: IsKernelDef kf => kf -> kf
dkern = regionKernel ddom
gpar = cfgGrid cfg
gcfpar = cfgGCF cfg
strat = cfgStrategy cfg
-- Intermediate Flow nodes
let gridded = grid vis (gcf vis0) createGrid -- grid from vis
images = facetSum (idft gridded) createImage
summed' = summed vis0 vis -- images, summed over channels
-- Distribute over nodes
distribute ddoms ParSchedule $ do
-- Loop over data sets
distribute ddom SeqSchedule $ do
-- Loop over facets
distribute (fst lmdom) (fst $ stratFacetSched strat) $
distribute (snd lmdom) (snd $ stratFacetSched strat) $ do
let fkern :: IsKernelDef kf => kf -> kf
fkern = regionKernel (fst lmdom) . regionKernel (snd lmdom)
rkern :: IsKernelDef kf => kf -> kf
rkern = dkern . fkern
-- Read in visibilities
rebind ixs $ scheduleSplit ddomss ddom
bind vis0 $ hints [ioHint{hintReadBytes = cfgPoints cfg * 5 * 8 {-sizeof double-}}] $
oskarReader ddom tdom (cfgInput cfg) 0 0 ixs
-- Create w-binned domain, split
wdoms <- makeBinDomain $ dkern $ binSizer gpar tdom uvdom vis0
wdom <- split wdoms (gridBins gpar)
-- Create GCF u/v domains
gudom <- makeBinDomain $ dkern $ gcfSizer gcfpar wdom
gvdom <- makeBinDomain $ dkern $ gcfSizer gcfpar wdom
let guvdom = (gudom, gvdom)
-- Loop over tiles
distribute (snd uvdom) (snd $ stratTileSched strat) $
distribute (fst uvdom) (fst $ stratTileSched strat) $ do
-- Load GCFs
bindRule gcf $ rkern $ const $ hints allCpuHints $ gcfKernel gcfpar wdom guvdom
distribute wdom SeqSchedule $ calculate $ gcf vis0
-- Rotate visibilities
rebind vis0 $ dkern $ hints cpuHints $ rotateKernel cfg lmdom tdom
-- Bin visibilities (could distribute, but there's no benefit)
rebind vis0 $ rkern $ hints allCpuHints $ binner gpar tdom uvdom wdom
-- Degrid / generate PSF (depending on vis)
rule degrid $ \(gcfs :. uvgrid :. vis' :. Z) -> do
rebind uvgrid $ distributeGrid ddomss ddom lmdom gpar
bind (degrid gcfs uvgrid vis') $ rkern $
degridKernel (stratDegridder strat) gpar gcfpar uvdom wdom guvdom gcfs uvgrid vis'
bindRule psfVis $ rkern $ psfVisKernel uvdom wdom
calculate vis
-- Gridding
bind createGrid $ rkern $ gridInit gcfpar uvdom
bindRule grid $ rkern $ gridKernel (stratGridder strat) gpar gcfpar uvdoms wdom guvdom uvdom
calculate gridded
-- Compute the result by detiling & iFFT on tiles
bind createGrid $ rkern $ gridInitDetile uvdoms
bind gridded $ rkern $ gridDetiling gcfpar uvdom uvdoms gridded createGrid
bindRule idft $ rkern $ hints cpuHints $ ifftKern gpar uvdoms
calculate $ idft gridded
-- Sum up facets
bind createImage $ dkern $ imageInit gpar
let fsize = gridImageWidth gpar * gridImageHeight gpar * 8 {-sizeof double-}
bind images $ dkern $ hints [floatHint, memHint{hintMemoryReadBytes = fsize}] $
imageDefacet gpar lmdom (idft gridded) createImage
-- Sum up images locally
bind createImage $ regionKernel ddoms $ imageInit gpar
bindRule sumImage $ imageSum gpar ddom ddoms
calculate summed'
-- Sum up images over nodes
recover summed' $ regionKernel ddoms $ imageInit gpar
bind createImage $ regionKernel ddomss $ imageInit gpar
bind summed' $ imageSum gpar ddoms ddomss summed' createImage
continuumGridStrat _ _ _ _ _ _ _ _ = fail "continuumGridStrat: Not enough domain splits provided!"
majorIterationStrat :: Config -> [DDom] -> TDom -> [UVDom] -> [LMDom]
-> Flow Index -> Flow Vis -> Flow Image
-> Strategy (Flow Image, Flow Image)
majorIterationStrat cfg ddom_s tdom uvdom_s lmdom_s ixs vis mdl = do
-- Calculate model grid using FFT (once)
let gpar = cfgGrid cfg
bindRule dft $ regionKernel (head ddom_s) $ hints allCpuHints $ fftKern gpar
calculate (dft mdl)
-- Do continuum gridding for degridded visibilities. The actual
-- degridding will be done in the inner loop, see continuumGridStrat.
let vis' = degridModel vis mdl
void $ continuumGridStrat cfg ddom_s tdom uvdom_s lmdom_s ixs vis vis'
-- Clean
let cpar = cfgClean cfg
bindRule (\psfImg img mdl' -> splitModel $ clean psfImg img mdl') $
regionKernel (head ddom_s) $ cleanModel gpar cpar
bindRule (\mdl' psfImg img -> splitResidual $ clean psfImg img mdl') $
regionKernel (head ddom_s) $ const $ cleanResidual gpar cpar
-- (Note that the order of parameters to bindRule determines the
-- order the Flows get passed to the kernel. So in the above
-- definition, the "const" removes mdl' and passes the concrete
-- Flows for psfImg and img to the kernel)
return (loopIter vis mdl,
finalLoopIter vis mdl)
continuumStrat :: Config -> Strategy ()
continuumStrat cfg = do
-- Make index and point domains for visibilities
(ddomss, ixs) <- makeOskarDomain cfg (cfgParallelism cfg)
tdom <- makeRangeDomain 0 (cfgPoints cfg)
-- Split index domain - first into bins per node, then into
-- individual data sets. The repeatSplit must be large enough to
-- split the largest repeat possible.
let repeatSplits = 1 + maximum (map oskarRepeat (cfgInput cfg))
ddoms <- split ddomss (cfgParallelism cfg)
ddom <- split ddoms repeatSplits
let ddom_s = [ddomss, ddoms, ddom]
-- Data flows we want to calculate
vis <- uniq $ flow "vis" ixs
-- Create ranged domains for image coordinates (split into facets)
let gpar = cfgGrid cfg
ldoms <- makeRangeDomain 0 (gridImageWidth gpar)
mdoms <- makeRangeDomain 0 (gridImageHeight gpar)
ldom <- split ldoms (gridFacets gpar)
mdom <- split mdoms (gridFacets gpar)
let lmdom_s = [(ldoms, mdoms), (ldom, mdom)]
-- Create ranged domains for grid coordinates (split into tiles)
udoms <- makeRangeDomain 0 (gridWidth gpar)
vdoms <- makeRangeDomain 0 (gridHeight gpar)
vdom <- split vdoms (gridTiles gpar)
udom <- split udoms (gridTiles gpar)
let uvdom_s = [(udoms, vdoms), (udom, vdom)]
-- Compute PSF
psfFlow <- continuumGridStrat cfg ddom_s tdom uvdom_s lmdom_s ixs vis (psfVis vis)
void $ bindNew $ regionKernel ddomss $ imageWriter gpar "psf.img" psfFlow
-- Major loops
let start = (createImage, createImage)
(finalMod, finalRes) <- (\f -> foldM f start [1..cfgLoops cfg]) $ \(mod', _res) i -> do
-- Calculate/create model
bindRule createImage $ regionKernel ddomss $ imageInit gpar
when (i > 1) $ calculate createImage -- workaround
calculate mod'
-- Run major loop iteration
majorIterationStrat cfg ddom_s tdom uvdom_s lmdom_s ixs vis mod'
-- Write out model grid
bind createImage $ regionKernel ddomss $ imageInit gpar
void $ bindNew $ regionKernel ddomss $
imageWriter gpar (cfgOutput cfg ++ ".mod") finalMod
bind createImage $ regionKernel ddomss $ imageInit gpar
void $ bindNew $ regionKernel ddomss $
imageWriter gpar (cfgOutput cfg) finalRes
main :: IO ()
main = do
-- Determine work directory (might be given on the command line)
args <- getArgs
dir <- case find ((== "--workdir") . fst) $ zip args (tail args) of
Just (_, wdir) -> return wdir
Nothing -> getCurrentDirectory
-- Read configuration
let configFile = dir </> "continuum.yaml"
putStrLn $ "Reading configuration from " ++ configFile
m_config <- decodeFileEither configFile
case m_config of
Left err -> putStrLn $ "Failed to read configuration file: " ++ show err
Right config -> do
print $ stratFacetSched $ cfgStrategy config
-- Show strategy - but only for the root process
when (not ("--internal-rank" `elem` args)) $ do
dumpSteps $ continuumStrat config
putStrLn "----------------------------------------------------------------"
putStrLn ""
-- Execute strategy
execStrategyDNA (stratUseFiles $ cfgStrategy config) $ continuumStrat config
|
SKA-ScienceDataProcessor/RC
|
MS6/programs/continuum.hs
|
Haskell
|
apache-2.0
| 12,331
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.Unversioned.ListMeta where
import GHC.Generics
import Data.Text
import qualified Data.Aeson
-- | ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
data ListMeta = ListMeta
{ selfLink :: Maybe Text -- ^ SelfLink is a URL representing this object. Populated by the system. Read-only.
, resourceVersion :: Maybe Text -- ^ String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON ListMeta
instance Data.Aeson.ToJSON ListMeta
|
minhdoboi/deprecated-openshift-haskell-api
|
openshift/lib/Openshift/Unversioned/ListMeta.hs
|
Haskell
|
apache-2.0
| 1,103
|
{- MathHmatrix.hs
- Mapping of Linear algebra routines via the hMatrix library.
- hMatrix uses GSL and a BLAS implementation such as ATLAS.
-
- Timothy A. Chagnon
- CS 636 - Spring 2009
-}
module MathHmatrix where
import Numeric.LinearAlgebra
deg2rad :: RealT -> RealT
deg2rad d = d * pi / 180
type RealT = Double
type Vec3f = Vector Double
vec3f :: Double -> Double -> Double -> Vector Double
vec3f x y z = (3 |>) [x,y,z]
zeroVec3f :: Vec3f
zeroVec3f = vec3f 0 0 0
svMul :: Double -> Vec3f -> Vec3f
svMul = scale
dot :: Vec3f -> Vec3f -> Double
dot = Numeric.LinearAlgebra.dot
cross :: Vec3f -> Vec3f -> Vec3f
cross v1 v2 =
let [a, b, c] = toList v1 in
let [d, e, f] = toList v2 in
vec3f (b*f-c*e) (c*d-a*f) (a*e-b*d)
mag :: Vec3f -> Double
mag v = sqrt (magSq v)
magSq :: Vec3f -> Double
magSq v = v `Numeric.LinearAlgebra.dot` v
norm :: Vec3f -> Vec3f
norm v = (1/(mag v)) `svMul` v
type Mat4f = Matrix Double
mat4f :: Vec4f -> Vec4f -> Vec4f -> Vec4f -> Mat4f
mat4f a b c d = fromRows [a,b,c,d]
type Vec4f = Vector Double
vec4f :: Double -> Double -> Double -> Double -> Vector Double
vec4f x y z w = (4 |>) [x,y,z,w]
mvMul :: Mat4f -> Vec4f -> Vec4f
mvMul = (<>)
mmMul :: Mat4f -> Mat4f -> Mat4f
mmMul = (<>)
id4f :: Mat4f
id4f = ident 4
point4f :: Vec3f -> Vec4f
point4f v = 4 |> ((toList v) ++ [1.0])
point3f :: Vec4f -> Vec3f
point3f v =
let [x, y, z, w] = toList v in
if w == 0
then error "point3f divide by zero"
else vec3f (x/w) (y/w) (z/w)
direction4f :: Vec3f -> Vec4f
direction4f v = 4 |> ((toList v) ++ [0.0])
direction3f :: Vec4f -> Vec3f
direction3f = subVector 0 3
vec3fElts :: Vec3f -> (RealT, RealT, RealT)
vec3fElts v =
let [x,y,z] = toList v in
(x,y,z)
type ColMat3f = Matrix Double
colMat3f :: Vec3f -> Vec3f -> Vec3f -> ColMat3f
colMat3f a b c = fromColumns [a,b,c]
detMat3f :: ColMat3f -> RealT
detMat3f = det
|
tchagnon/cs636-raytracer
|
a1/MathHmatrix.hs
|
Haskell
|
apache-2.0
| 1,933
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
{-# OPTIONS_GHC -Wall -funbox-strict-fields -fno-warn-orphans -fno-warn-type-defaults -O2 #-}
#ifdef ST_HACK
{-# OPTIONS_GHC -fno-full-laziness #-}
#endif
--------------------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett 2015
-- License : BSD-style
-- Maintainer : Edward Kmett <[email protected]>
-- Portability : non-portable
--
-- This module suppose a Word64-based array-mapped PATRICIA Trie.
--
-- The most significant nybble is isolated by using techniques based on
-- <https://www.fpcomplete.com/user/edwardk/revisiting-matrix-multiplication/part-4>
-- but modified to work nybble-by-nybble rather than bit-by-bit.
--
--------------------------------------------------------------------------------
module Data.Discrimination.Internal.WordMap
( WordMap
, singleton
, empty
, insert
, lookup
, member
, fromList
) where
import Control.Applicative hiding (empty)
import Control.DeepSeq
import Control.Monad.ST hiding (runST)
import Data.Bits
import Data.Discrimination.Internal.SmallArray
import Data.Foldable
import Data.Functor
import Data.Monoid
import Data.Traversable
import Data.Word
import qualified GHC.Exts as Exts
import Prelude hiding (lookup, length, foldr)
import GHC.Types
import GHC.ST
type Key = Word64
type Mask = Word16
type Offset = Int
ptrEq :: a -> a -> Bool
ptrEq x y = isTrue# (Exts.reallyUnsafePtrEquality# x y Exts.==# 1#)
{-# INLINEABLE ptrEq #-}
ptrNeq :: a -> a -> Bool
ptrNeq x y = isTrue# (Exts.reallyUnsafePtrEquality# x y Exts./=# 1#)
{-# INLINEABLE ptrNeq #-}
data WordMap v
= Full !Key !Offset !(SmallArray (WordMap v))
| Node !Key !Offset !Mask !(SmallArray (WordMap v))
| Tip !Key v
| Nil
deriving Show
node :: Key -> Offset -> Mask -> SmallArray (WordMap v) -> WordMap v
node k o 0xffff a = Full k o a
node k o m a = Node k o m a
{-# INLINE node #-}
instance NFData v => NFData (WordMap v) where
rnf (Full _ _ a) = rnf a
rnf (Node _ _ _ a) = rnf a
rnf (Tip _ v) = rnf v
rnf Nil = ()
instance Functor WordMap where
fmap f = go where
go (Full k o a) = Full k o (fmap go a)
go (Node k o m a) = Node k o m (fmap go a)
go (Tip k v) = Tip k (f v)
go Nil = Nil
{-# INLINEABLE fmap #-}
instance Foldable WordMap where
foldMap f = go where
go (Full _ _ a) = foldMap go a
go (Node _ _ _ a) = foldMap go a
go (Tip _ v) = f v
go Nil = mempty
{-# INLINEABLE foldMap #-}
instance Traversable WordMap where
traverse f = go where
go (Full k o a) = Full k o <$> traverse go a
go (Node k o m a) = Node k o m <$> traverse go a
go (Tip k v) = Tip k <$> f v
go Nil = pure Nil
{-# INLINEABLE traverse #-}
-- Note: 'level 0' will return a negative shift, don't use it
level :: Key -> Int
level w = 60 - (countLeadingZeros w .&. 0x7c)
{-# INLINE level #-}
maskBit :: Key -> Offset -> Int
maskBit k o = fromIntegral (unsafeShiftR k o .&. 0xf)
{-# INLINE maskBit #-}
mask :: Key -> Offset -> Word16
mask k o = unsafeShiftL 1 (maskBit k o)
{-# INLINE mask #-}
-- offset :: Int -> Word16 -> Int
-- offset k w = popCount $ w .&. (unsafeShiftL 1 k - 1)
-- {-# INLINE offset #-}
fork :: Int -> Key -> WordMap v -> Key -> WordMap v -> WordMap v
fork o k n ok on = Node (k .&. unsafeShiftL 0xfffffffffffffff0 o) o (mask k o .|. mask ok o) $ runST $ do
arr <- newSmallArray 2 n
writeSmallArray arr (fromEnum (k < ok)) on
unsafeFreezeSmallArray arr
insert :: Key -> v -> WordMap v -> WordMap v
insert !k v xs0 = go xs0 where
go on@(Full ok n as)
| wd > 0xf = fork (level okk) k (Tip k v) ok on
| !oz <- indexSmallArray as d
, !z <- go oz
, ptrNeq z oz = Full ok n (update16 d z as)
| otherwise = on
where
okk = xor ok k
wd = unsafeShiftR okk n
d = fromIntegral wd
go on@(Node ok n m as)
| wd > 0xf = fork (level okk) k (Tip k v) ok on
| m .&. b == 0 = node ok n (m .|. b) (insertSmallArray odm (Tip k v) as)
| !oz <- indexSmallArray as odm
, !z <- go oz
, ptrNeq z oz = Node ok n m (updateSmallArray odm z as)
| otherwise = on
where
okk = xor ok k
wd = unsafeShiftR okk n
d = fromIntegral wd
b = unsafeShiftL 1 d
odm = popCount $ m .&. (b - 1)
go on@(Tip ok ov)
| k /= ok = fork (level (xor ok k)) k (Tip k v) ok on
| ptrEq v ov = on
| otherwise = Tip k v
go Nil = Tip k v
{-# INLINEABLE insert #-}
lookup :: Key -> WordMap v -> Maybe v
lookup !k (Full ok o a)
| z <- unsafeShiftR (xor k ok) o, z <= 0xf = lookup k $ indexSmallArray a (fromIntegral z)
| otherwise = Nothing
lookup k (Node ok o m a)
| z <= 0xf && m .&. b /= 0 = lookup k (indexSmallArray a (popCount (m .&. (b - 1))))
| otherwise = Nothing
where
z = unsafeShiftR (xor k ok) o
b = unsafeShiftL 1 (fromIntegral z)
lookup k (Tip ok ov)
| k == ok = Just ov
| otherwise = Nothing
lookup _ Nil = Nothing
{-# INLINEABLE lookup #-}
member :: Key -> WordMap v -> Bool
member !k (Full ok o a)
| z <- unsafeShiftR (xor k ok) o = z <= 0xf && member k (indexSmallArray a (fromIntegral z))
member k (Node ok o m a)
| z <- unsafeShiftR (xor k ok) o
= z <= 0xf && let b = unsafeShiftL 1 (fromIntegral z) in
m .&. b /= 0 && member k (indexSmallArray a (popCount (m .&. (b - 1))))
member k (Tip ok _) = k == ok
member _ Nil = False
{-# INLINEABLE member #-}
updateSmallArray :: Int -> a -> SmallArray a -> SmallArray a
updateSmallArray !k a i = runST $ do
let n = length i
o <- newSmallArray n undefined
copySmallArray o 0 i 0 n
writeSmallArray o k a
unsafeFreezeSmallArray o
{-# INLINEABLE updateSmallArray #-}
update16 :: Int -> a -> SmallArray a -> SmallArray a
update16 !k a i = runST $ do
o <- clone16 i
writeSmallArray o k a
unsafeFreezeSmallArray o
{-# INLINEABLE update16 #-}
insertSmallArray :: Int -> a -> SmallArray a -> SmallArray a
insertSmallArray !k a i = runST $ do
let n = length i
o <- newSmallArray (n + 1) a
copySmallArray o 0 i 0 k
copySmallArray o (k+1) i k (n-k)
unsafeFreezeSmallArray o
{-# INLINEABLE insertSmallArray #-}
clone16 :: SmallArray a -> ST s (SmallMutableArray s a)
clone16 i = do
o <- newSmallArray 16 undefined
indexSmallArrayM i 0 >>= writeSmallArray o 0
indexSmallArrayM i 1 >>= writeSmallArray o 1
indexSmallArrayM i 2 >>= writeSmallArray o 2
indexSmallArrayM i 3 >>= writeSmallArray o 3
indexSmallArrayM i 4 >>= writeSmallArray o 4
indexSmallArrayM i 5 >>= writeSmallArray o 5
indexSmallArrayM i 6 >>= writeSmallArray o 6
indexSmallArrayM i 7 >>= writeSmallArray o 7
indexSmallArrayM i 8 >>= writeSmallArray o 8
indexSmallArrayM i 9 >>= writeSmallArray o 9
indexSmallArrayM i 10 >>= writeSmallArray o 10
indexSmallArrayM i 11 >>= writeSmallArray o 11
indexSmallArrayM i 12 >>= writeSmallArray o 12
indexSmallArrayM i 13 >>= writeSmallArray o 13
indexSmallArrayM i 14 >>= writeSmallArray o 14
indexSmallArrayM i 15 >>= writeSmallArray o 15
return o
{-# INLINE clone16 #-}
-- | Build a singleton WordMap
singleton :: Key -> v -> WordMap v
singleton !k v = Tip k v
{-# INLINE singleton #-}
fromList :: [(Word64,v)] -> WordMap v
fromList xs = foldl' (\r (k,v) -> insert k v r) Nil xs
{-# INLINE fromList #-}
empty :: WordMap a
empty = Nil
{-# INLINE empty #-}
|
markus1189/discrimination
|
src/Data/Discrimination/Internal/WordMap.hs
|
Haskell
|
bsd-2-clause
| 7,597
|
{-| Module describing an instance.
The instance data type holds very few fields, the algorithm
intelligence is in the "Node" and "Cluster" modules.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.HTools.Instance
( Instance(..)
, Disk(..)
, AssocList
, List
, create
, isRunning
, isOffline
, notOffline
, instanceDown
, usesSecMem
, applyIfOnline
, setIdx
, setName
, setAlias
, setPri
, setSec
, setBoth
, setMovable
, specOf
, getTotalSpindles
, instBelowISpec
, instAboveISpec
, instMatchesPolicy
, shrinkByType
, localStorageTemplates
, hasSecondary
, requiredNodes
, allNodes
, usesLocalStorage
, mirrorType
) where
import Control.Monad (liftM2)
import Ganeti.BasicTypes
import qualified Ganeti.HTools.Types as T
import qualified Ganeti.HTools.Container as Container
import Ganeti.HTools.Nic (Nic)
import Ganeti.Utils
-- * Type declarations
data Disk = Disk
{ dskSize :: Int -- ^ Size in bytes
, dskSpindles :: Maybe Int -- ^ Number of spindles
} deriving (Show, Eq)
-- | The instance type.
data Instance = Instance
{ name :: String -- ^ The instance name
, alias :: String -- ^ The shortened name
, mem :: Int -- ^ Memory of the instance
, dsk :: Int -- ^ Total disk usage of the instance
, disks :: [Disk] -- ^ Sizes of the individual disks
, vcpus :: Int -- ^ Number of VCPUs
, runSt :: T.InstanceStatus -- ^ Original run status
, pNode :: T.Ndx -- ^ Original primary node
, sNode :: T.Ndx -- ^ Original secondary node
, idx :: T.Idx -- ^ Internal index
, util :: T.DynUtil -- ^ Dynamic resource usage
, movable :: Bool -- ^ Can and should the instance be moved?
, autoBalance :: Bool -- ^ Is the instance auto-balanced?
, diskTemplate :: T.DiskTemplate -- ^ The disk template of the instance
, spindleUse :: Int -- ^ The numbers of used spindles
, allTags :: [String] -- ^ List of all instance tags
, exclTags :: [String] -- ^ List of instance exclusion tags
, arPolicy :: T.AutoRepairPolicy -- ^ Instance's auto-repair policy
, nics :: [Nic] -- ^ NICs of the instance
} deriving (Show, Eq)
instance T.Element Instance where
nameOf = name
idxOf = idx
setAlias = setAlias
setIdx = setIdx
allNames n = [name n, alias n]
-- | Check if instance is running.
isRunning :: Instance -> Bool
isRunning (Instance {runSt = T.Running}) = True
isRunning (Instance {runSt = T.ErrorUp}) = True
isRunning _ = False
-- | Check if instance is offline.
isOffline :: Instance -> Bool
isOffline (Instance {runSt = T.StatusOffline}) = True
isOffline _ = False
-- | Helper to check if the instance is not offline.
notOffline :: Instance -> Bool
notOffline = not . isOffline
-- | Check if instance is down.
instanceDown :: Instance -> Bool
instanceDown inst | isRunning inst = False
instanceDown inst | isOffline inst = False
instanceDown _ = True
-- | Apply the function if the instance is online. Otherwise use
-- the initial value
applyIfOnline :: Instance -> (a -> a) -> a -> a
applyIfOnline = applyIf . notOffline
-- | Helper for determining whether an instance's memory needs to be
-- taken into account for secondary memory reservation.
usesSecMem :: Instance -> Bool
usesSecMem inst = notOffline inst && autoBalance inst
-- | Constant holding the local storage templates.
--
-- /Note:/ Currently Ganeti only exports node total/free disk space
-- for LVM-based storage; file-based storage is ignored in this model,
-- so even though file-based storage uses in reality disk space on the
-- node, in our model it won't affect it and we can't compute whether
-- there is enough disk space for a file-based instance. Therefore we
-- will treat this template as \'foreign\' storage.
localStorageTemplates :: [T.DiskTemplate]
localStorageTemplates = [ T.DTDrbd8, T.DTPlain ]
-- | Constant holding the movable disk templates.
--
-- This only determines the initial 'movable' state of the
-- instance. Further the movable state can be restricted more due to
-- user choices, etc.
movableDiskTemplates :: [T.DiskTemplate]
movableDiskTemplates =
[ T.DTDrbd8
, T.DTBlock
, T.DTSharedFile
, T.DTRbd
, T.DTExt
]
-- | A simple name for the int, instance association list.
type AssocList = [(T.Idx, Instance)]
-- | A simple name for an instance map.
type List = Container.Container Instance
-- * Initialization
-- | Create an instance.
--
-- Some parameters are not initialized by function, and must be set
-- later (via 'setIdx' for example).
create :: String -> Int -> Int -> [Disk] -> Int -> T.InstanceStatus
-> [String] -> Bool -> T.Ndx -> T.Ndx -> T.DiskTemplate -> Int
-> [Nic] -> Instance
create name_init mem_init dsk_init disks_init vcpus_init run_init tags_init
auto_balance_init pn sn dt su nics_init =
Instance { name = name_init
, alias = name_init
, mem = mem_init
, dsk = dsk_init
, disks = disks_init
, vcpus = vcpus_init
, runSt = run_init
, pNode = pn
, sNode = sn
, idx = -1
, util = T.baseUtil
, movable = supportsMoves dt
, autoBalance = auto_balance_init
, diskTemplate = dt
, spindleUse = su
, allTags = tags_init
, exclTags = []
, arPolicy = T.ArNotEnabled
, nics = nics_init
}
-- | Changes the index.
--
-- This is used only during the building of the data structures.
setIdx :: Instance -- ^ The original instance
-> T.Idx -- ^ New index
-> Instance -- ^ The modified instance
setIdx t i = t { idx = i }
-- | Changes the name.
--
-- This is used only during the building of the data structures.
setName :: Instance -- ^ The original instance
-> String -- ^ New name
-> Instance -- ^ The modified instance
setName t s = t { name = s, alias = s }
-- | Changes the alias.
--
-- This is used only during the building of the data structures.
setAlias :: Instance -- ^ The original instance
-> String -- ^ New alias
-> Instance -- ^ The modified instance
setAlias t s = t { alias = s }
-- * Update functions
-- | Changes the primary node of the instance.
setPri :: Instance -- ^ the original instance
-> T.Ndx -- ^ the new primary node
-> Instance -- ^ the modified instance
setPri t p = t { pNode = p }
-- | Changes the secondary node of the instance.
setSec :: Instance -- ^ the original instance
-> T.Ndx -- ^ the new secondary node
-> Instance -- ^ the modified instance
setSec t s = t { sNode = s }
-- | Changes both nodes of the instance.
setBoth :: Instance -- ^ the original instance
-> T.Ndx -- ^ new primary node index
-> T.Ndx -- ^ new secondary node index
-> Instance -- ^ the modified instance
setBoth t p s = t { pNode = p, sNode = s }
-- | Sets the movable flag on an instance.
setMovable :: Instance -- ^ The original instance
-> Bool -- ^ New movable flag
-> Instance -- ^ The modified instance
setMovable t m = t { movable = m }
-- | Try to shrink the instance based on the reason why we can't
-- allocate it.
shrinkByType :: Instance -> T.FailMode -> Result Instance
shrinkByType inst T.FailMem = let v = mem inst - T.unitMem
in if v < T.unitMem
then Bad "out of memory"
else Ok inst { mem = v }
shrinkByType inst T.FailDisk =
let newdisks = [d {dskSize = dskSize d - T.unitDsk}| d <- disks inst]
v = dsk inst - (length . disks $ inst) * T.unitDsk
in if any (< T.unitDsk) $ map dskSize newdisks
then Bad "out of disk"
else Ok inst { dsk = v, disks = newdisks }
shrinkByType inst T.FailCPU = let v = vcpus inst - T.unitCpu
in if v < T.unitCpu
then Bad "out of vcpus"
else Ok inst { vcpus = v }
shrinkByType inst T.FailSpindles =
case disks inst of
[Disk ds sp] -> case sp of
Nothing -> Bad "No spindles, shouldn't have happened"
Just sp' -> let v = sp' - T.unitSpindle
in if v < T.unitSpindle
then Bad "out of spindles"
else Ok inst { disks = [Disk ds (Just v)] }
d -> Bad $ "Expected one disk, but found " ++ show d
shrinkByType _ f = Bad $ "Unhandled failure mode " ++ show f
-- | Get the number of disk spindles
getTotalSpindles :: Instance -> Maybe Int
getTotalSpindles inst =
foldr (liftM2 (+) . dskSpindles ) (Just 0) (disks inst)
-- | Return the spec of an instance.
specOf :: Instance -> T.RSpec
specOf Instance { mem = m, dsk = d, vcpus = c, disks = dl } =
let sp = case dl of
[Disk _ (Just sp')] -> sp'
_ -> 0
in T.RSpec { T.rspecCpu = c, T.rspecMem = m,
T.rspecDsk = d, T.rspecSpn = sp }
-- | Checks if an instance is smaller/bigger than a given spec. Returns
-- OpGood for a correct spec, otherwise Bad one of the possible
-- failure modes.
instCompareISpec :: Ordering -> Instance-> T.ISpec -> Bool -> T.OpResult ()
instCompareISpec which inst ispec exclstor
| which == mem inst `compare` T.iSpecMemorySize ispec = Bad T.FailMem
| which `elem` map ((`compare` T.iSpecDiskSize ispec) . dskSize)
(disks inst) = Bad T.FailDisk
| which == vcpus inst `compare` T.iSpecCpuCount ispec = Bad T.FailCPU
| exclstor &&
case getTotalSpindles inst of
Nothing -> True
Just sp_sum -> which == sp_sum `compare` T.iSpecSpindleUse ispec
= Bad T.FailSpindles
| not exclstor && which == spindleUse inst `compare` T.iSpecSpindleUse ispec
= Bad T.FailSpindles
| diskTemplate inst /= T.DTDiskless &&
which == length (disks inst) `compare` T.iSpecDiskCount ispec
= Bad T.FailDiskCount
| otherwise = Ok ()
-- | Checks if an instance is smaller than a given spec.
instBelowISpec :: Instance -> T.ISpec -> Bool -> T.OpResult ()
instBelowISpec = instCompareISpec GT
-- | Checks if an instance is bigger than a given spec.
instAboveISpec :: Instance -> T.ISpec -> Bool -> T.OpResult ()
instAboveISpec = instCompareISpec LT
-- | Checks if an instance matches a min/max specs pair
instMatchesMinMaxSpecs :: Instance -> T.MinMaxISpecs -> Bool -> T.OpResult ()
instMatchesMinMaxSpecs inst minmax exclstor = do
instAboveISpec inst (T.minMaxISpecsMinSpec minmax) exclstor
instBelowISpec inst (T.minMaxISpecsMaxSpec minmax) exclstor
-- | Checks if an instance matches any specs of a policy
instMatchesSpecs :: Instance -> [T.MinMaxISpecs] -> Bool -> T.OpResult ()
-- Return Ok for no constraints, though this should never happen
instMatchesSpecs _ [] _ = Ok ()
instMatchesSpecs inst minmaxes exclstor =
-- The initial "Bad" should be always replaced by a real result
foldr eithermatch (Bad T.FailInternal) minmaxes
where eithermatch mm (Bad _) = instMatchesMinMaxSpecs inst mm exclstor
eithermatch _ y@(Ok ()) = y
-- | Checks if an instance matches a policy.
instMatchesPolicy :: Instance -> T.IPolicy -> Bool -> T.OpResult ()
instMatchesPolicy inst ipol exclstor = do
instMatchesSpecs inst (T.iPolicyMinMaxISpecs ipol) exclstor
if diskTemplate inst `elem` T.iPolicyDiskTemplates ipol
then Ok ()
else Bad T.FailDisk
-- | Checks whether the instance uses a secondary node.
--
-- /Note:/ This should be reconciled with @'sNode' ==
-- 'Node.noSecondary'@.
hasSecondary :: Instance -> Bool
hasSecondary = (== T.DTDrbd8) . diskTemplate
-- | Computed the number of nodes for a given disk template.
requiredNodes :: T.DiskTemplate -> Int
requiredNodes T.DTDrbd8 = 2
requiredNodes _ = 1
-- | Computes all nodes of an instance.
allNodes :: Instance -> [T.Ndx]
allNodes inst = case diskTemplate inst of
T.DTDrbd8 -> [pNode inst, sNode inst]
_ -> [pNode inst]
-- | Checks whether a given disk template uses local storage.
usesLocalStorage :: Instance -> Bool
usesLocalStorage = (`elem` localStorageTemplates) . diskTemplate
-- | Checks whether a given disk template supported moves.
supportsMoves :: T.DiskTemplate -> Bool
supportsMoves = (`elem` movableDiskTemplates)
-- | A simple wrapper over 'T.templateMirrorType'.
mirrorType :: Instance -> T.MirrorType
mirrorType = T.templateMirrorType . diskTemplate
|
apyrgio/snf-ganeti
|
src/Ganeti/HTools/Instance.hs
|
Haskell
|
bsd-2-clause
| 13,964
|
{-# LANGUAGE BangPatterns #-}
{-|
Convenience 'Pipe's, analogous to those in "Control.Pipe.List", for 'Pipe's
containing binary data.
-}
module Control.Pipe.Binary
( -- * Producers
produce
-- ** Infinite streams
, iterate
, iterateM
, repeat
, repeatM
-- ** Bounded streams
, replicate
, replicateM
, unfold
, unfoldM
-- * Consumers
, consume
, consume'
, fold
, foldM
, mapM_
-- * Pipes
-- ** Maps
, map
, mapM
, concatMap
, concatMapM
-- ** Accumulating maps
, mapAccum
, mapAccumM
, concatMapAccum
, concatMapAccumM
-- ** Dropping input
, filter
, filterM
, drop
, dropWhile
, take
, takeWhile
, takeUntilByte
-- ** Other
, lines
, words
)
where
import Control.Monad (Monad (..), forever, liftM, when)
import Control.Monad.Trans (lift)
import Control.Pipe.Common
import qualified Control.Pipe.List as PL
import Data.Bool (Bool)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Data.Function ((.), ($))
import Data.Functor (fmap)
import Data.Maybe (Maybe (..))
import Data.Word (Word8)
import Prelude (Int, (+), (-), Ord (..), fromIntegral, otherwise)
------------------------------------------------------------------------------
-- | Produces a stream of byte chunks given a lazy 'L.ByteString'.
produce :: Monad m => L.ByteString -> Producer ByteString m ()
produce = PL.produce . L.toChunks
------------------------------------------------------------------------------
-- | @'iterate' f x@ produces an infinite stream of repeated applications of
-- @f@ to @x@.
iterate :: Monad m => (Word8 -> Word8) -> Word8 -> Producer ByteString m b
iterate f a = produce (L.iterate f a) >> discard
------------------------------------------------------------------------------
-- | Similar to 'iterate', except the iteration function is monadic.
iterateM :: Monad m => (Word8 -> m Word8) -> Word8 -> Producer ByteString m b
iterateM f a = PL.iterateM f a >+> pipe B.singleton
------------------------------------------------------------------------------
-- | Produces an infinite stream of a single byte.
repeat :: Monad m => Word8 -> Producer ByteString m b
repeat a = produce (L.repeat a) >> discard
------------------------------------------------------------------------------
-- | Produces an infinite stream of values. Each value is computed by the
-- underlying monad.
repeatM :: Monad m => m Word8 -> Producer ByteString m b
repeatM m = forever $ lift m >>= yield . B.singleton
------------------------------------------------------------------------------
-- | @'replicate' n x@ produces a stream containing @n@ copies of @x@.
replicate :: Monad m => Int -> Word8 -> Producer ByteString m ()
replicate n = produce . L.replicate (fromIntegral n)
------------------------------------------------------------------------------
-- | @'replicateM' n x@ produces a stream containing @n@ bytes, where each
-- byte is computed by the underlying monad.
replicateM :: Monad m => Int -> m Word8 -> Producer ByteString m ()
replicateM n m = PL.replicateM n m >+> pipe B.singleton
------------------------------------------------------------------------------
-- | Produces a stream of bytes by repeatedly applying a function to some
-- state, until 'Nothing' is returned.
unfold :: Monad m => (c -> Maybe (Word8, c)) -> c -> Producer ByteString m ()
unfold f = produce . L.unfoldr f
------------------------------------------------------------------------------
-- | Produces a stream of bytes by repeatedly applying a computation to some
-- state, until 'Nothing' is returned.
unfoldM
:: Monad m
=> (c -> m (Maybe (Word8, c)))
-> c
-> Producer ByteString m ()
unfoldM f c = PL.unfoldM f c >+> pipe B.singleton
------------------------------------------------------------------------------
-- | Consumes all input chunks and returns a lazy 'L.ByteString'.
consume :: Monad m => Consumer ByteString m L.ByteString
consume = L.fromChunks `liftM` PL.consume
------------------------------------------------------------------------------
-- | Consumes all input chunks and concatenate them into a strict
-- 'ByteString'.
consume' :: Monad m => Consumer ByteString m ByteString
consume' = B.concat `liftM` PL.consume
------------------------------------------------------------------------------
-- | Consume the entire input stream with a strict left monadic fold, one byte
-- at a time.
fold :: Monad m => (b -> Word8 -> b) -> b -> Consumer ByteString m b
fold = PL.fold . B.foldl
------------------------------------------------------------------------------
-- | Consume the entire input stream with a strict left fold, one byte at a
-- time.
foldM :: Monad m => (b -> Word8 -> m b) -> b -> Consumer ByteString m b
foldM f = PL.foldM $ \b -> B.foldl (\mb w -> mb >>= \b -> f b w) (return b)
------------------------------------------------------------------------------
-- | For every byte in a stream, run a computation and discard its result.
mapM_ :: Monad m => (Word8 -> m b) -> Consumer ByteString m r
mapM_ f = foldM (\() a -> f a >> return ()) () >> discard
------------------------------------------------------------------------------
-- | 'map' transforms a byte stream by applying a transformation to each byte
-- in the stream.
map :: Monad m => (Word8 -> Word8) -> Pipe ByteString ByteString m r
map = pipe . B.map
------------------------------------------------------------------------------
-- | 'map' transforms a byte stream by applying a monadic transformation to
-- each byte in the stream.
mapM :: Monad m => (Word8 -> m Word8) -> Pipe ByteString ByteString m r
mapM f = concatMapM (liftM B.singleton . f)
------------------------------------------------------------------------------
-- | 'concatMap' transforms a byte stream by applying a transformation to each
-- byte in the stream and concatenating the results.
concatMap
:: Monad m
=> (Word8 -> ByteString)
-> Pipe ByteString ByteString m r
concatMap = pipe . B.concatMap
------------------------------------------------------------------------------
-- | 'concatMapM' transforms a byte stream by applying a monadic
-- transformation to each byte in the stream and concatenating the results.
concatMapM
:: Monad m
=> (Word8 -> m ByteString)
-> Pipe ByteString ByteString m r
concatMapM f = forever $ do
await >>= B.foldl (\m w -> m >> lift (f w) >>= yield) (return ())
------------------------------------------------------------------------------
-- | Similar to 'map', but with a stateful step function.
mapAccum
:: Monad m
=> (c -> Word8 -> (c, Word8))
-> c
-> Pipe ByteString ByteString m r
mapAccum f = go
where
go !c = do
bs <- await
let (c', bs') = B.mapAccumL f c bs
yield bs'
go c'
------------------------------------------------------------------------------
-- | Similar to 'mapM', but with a stateful step function.
mapAccumM
:: Monad m
=> (c -> Word8 -> m (c, Word8))
-> c
-> Pipe ByteString ByteString m r
mapAccumM f = concatMapAccumM (\c w -> liftM (fmap B.singleton) (f c w))
------------------------------------------------------------------------------
-- | Similar to 'concatMap', but with a stateful step function.
concatMapAccum
:: Monad m
=> (c -> Word8 -> (c, ByteString))
-> c
-> Pipe ByteString ByteString m r
concatMapAccum f = concatMapAccumM (\c w -> return (f c w))
------------------------------------------------------------------------------
-- | Similar to 'concatMapM', but with a stateful step function.
concatMapAccumM
:: Monad m
=> (c -> Word8 -> m (c, ByteString))
-> c
-> Pipe ByteString ByteString m r
concatMapAccumM f = go
where
go c = await >>= B.foldl (\mc w -> do
c <- mc
(c', bs) <- lift (f c w)
yield bs
return c') (return c) >>= go
------------------------------------------------------------------------------
-- | @'filter' p@ keeps only the bytes in the stream which match the predicate
-- @p@.
filter :: Monad m => (Word8 -> Bool) -> Pipe ByteString ByteString m r
filter = pipe . B.filter
------------------------------------------------------------------------------
-- | @'filter' p@ keeps only the bytes in the stream which match the monadic
-- predicate @p@.
filterM :: Monad m => (Word8 -> m Bool) -> Pipe ByteString ByteString m r
filterM f = go
where
go = await >>= B.foldl (\m w -> do
m
bool <- lift (f w)
when bool $ yield $ B.singleton w) (return ()) >> go
------------------------------------------------------------------------------
-- | @'drop' n@ discards the first @n@ bytes from the stream.
drop :: Monad m => Int -> Pipe ByteString ByteString m ()
drop n = do
bs <- await
let n' = n - B.length bs
if n' > 0 then drop n' else do unuse $ B.drop n bs
------------------------------------------------------------------------------
-- | @'dropWhile' p@ discards bytes from the stream until they no longer match
-- the predicate @p@.
dropWhile :: Monad m => (Word8 -> Bool) -> Pipe ByteString ByteString m ()
dropWhile p = go
where
go = do
bs <- await
let (bad, good) = B.span p bs
if B.null good then go else unuse good
------------------------------------------------------------------------------
-- | @'take' n@ allows the first @n@ bytes to pass through the stream, and
-- then terminates.
take :: Monad m => Int -> Pipe ByteString ByteString m ()
take n = do
bs <- await
let n' = n - B.length bs
if n' > 0 then yield bs >> take n' else do
let (good, bad) = B.splitAt n bs
unuse bad
yield good
------------------------------------------------------------------------------
-- | @'takeWhile' p@ allows bytes to pass through the stream as long as they
-- match the predicate @p@, and terminates after the first byte that does not
-- match @p@.
takeWhile :: Monad m => (Word8 -> Bool) -> Pipe ByteString ByteString m ()
takeWhile p = go
where
go = do
bs <- await
let (good, bad) = B.span p bs
yield good
if B.null bad then go else unuse bad
------------------------------------------------------------------------------
-- | @'takeUntilByte' c@ allows bytes to pass through the stream until the
-- byte @w@ is found in the stream. This is equivalent to 'takeWhile'
-- @(not . (==c))@, but is more efficient.
takeUntilByte :: Monad m => Word8 -> Pipe ByteString ByteString m ()
takeUntilByte w = go
where
go = do
bs <- await
let (good, bad) = B.breakByte w bs
yield good
if B.null bad then go else unuse bad
------------------------------------------------------------------------------
-- | Split the input bytes into lines. This makes each input chunk correspend
-- to exactly one line, even if that line was originally spread across several
-- chunks.
lines :: Monad m => Pipe ByteString ByteString m r
lines = forever $ do
((takeUntilByte 10 >> return B.empty) >+> consume') >>= yield
drop 1
------------------------------------------------------------------------------
-- | Split the input bytes into words. This makes each input chunk correspend
-- to exactly one word, even if that word was originally spread across several
-- chunks.
words :: Monad m => Pipe ByteString ByteString m r
words = forever $ do
((takeUntilByte 32 >> return B.empty) >+> consume') >>= yield
drop 1
|
duairc/pipes
|
src/Control/Pipe/Binary.hs
|
Haskell
|
bsd-3-clause
| 11,736
|
{-# LANGUAGE TemplateHaskell #-}
module Database.Sqroll.TH (
initializeAllTablesDec
) where
import Database.Sqroll.Internal (Sqroll, HasTable, sqrollInitializeTable)
import Data.Maybe
import Language.Haskell.TH
-- | create a function 'initializeAllTables :: Sqroll -> IO ()' that, when run,
-- will initialize tables for all datatypes with HasTable instances in scope in
-- the module where this is spliced.
--
-- Currently, only data types with kind * will be included. So if the
-- following are in scope:
--
-- > instance HasTable Foo
-- > instance HasTable (Bar Int)
-- > instance HasTable (Foo,Foo)
--
-- initializeAllTables will only initialize the table for 'Foo'
initializeAllTablesDec :: Q [Dec]
initializeAllTablesDec = do
ClassI _ instances <- reify ''HasTable
sqNm <- newName "sqroll"
let sqP = varP sqNm
sqE = varE sqNm
exprs = catMaybes $ map fromAppT instances
let allTheExprs = lamE [sqP] $ foldr accExpr [| return () |] exprs
accExpr x acc = [| sqrollInitializeTable $(sqE) $(x) >> $(acc) |]
[d| initializeAllTables :: Sqroll -> IO (); initializeAllTables = $(allTheExprs) |]
fromAppT :: Dec -> Maybe ExpQ
fromAppT (InstanceD _ (AppT (ConT cls) (ConT typName)) _) | cls == ''HasTable = Just $ sigE [|undefined|] (conT typName)
-- TODO: match on newtype and data instances
fromAppT _ = Nothing
|
pacak/sqroll
|
src/Database/Sqroll/TH.hs
|
Haskell
|
bsd-3-clause
| 1,364
|
{-# LANGUAGE RankNTypes, GADTs,
MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, AllowAmbiguousTypes #-}
module HLib61
where
import Control.Category ((>>>))
import Control.Monad ((>=>))
import Data.Dynamic
type UserInput = String
class (Read n, Show n) => Serializable n
instance forall n. (Read n, Show n) => Serializable [n]
instance (Serializable a, Serializable b) => Serializable (a, b)
instance Serializable Int
instance Serializable ()
data Node s o = QNode {
execQNode :: (Serializable s, Serializable o) => s -> UserInput -> Target o
} | ANode {
execANode :: (Serializable s, Serializable o) => s -> Target o
}
data Target o where
Continuation :: forall o o'. (Serializable o, Serializable o') => Target (Node o o')
Recursion :: forall o o'. (Serializable o, Serializable o') => Target (Node o o')
EOD :: forall o. (Serializable o) => o -> Target o
Start :: forall o o'. {- (Serializable o, Serializable o') => -} (o' -> o) -> Node () o' -> Target o
Fork :: forall o o' o''. (Serializable o, Serializable o', Serializable o'') => o' -> Node o' o'' -> Node o'' o -> Target o
-- data Target o =
-- forall o'. Continuation (Node o o')
-- | forall o'. Recursion (Node o o')
-- | EOD o
-- | forall o'. Start (o' -> o) (Node () o')
-- | forall o' o''. Fork o' (Node o' o'') (Node o'' o)
askForANumber :: Node () Int
askForANumber = QNode {
execQNode = const $ EOD . read
}
getTwoNumbers :: Node [Int] [Int]
getTwoNumbers = ANode {
-- execQNode = \ s -> if length s < 2 then (3:s, Recursion getTwoNumbers) else (s, EOD)
execANode = \ s -> if length s < 2 then Start (:s) askForANumber else EOD s
}
getOperation :: Node () String
getOperation = QNode {
-- what do you want to do with these numbers?
execQNode = const EOD
}
getTwoNumbersAndOperation :: Node () ([Int], String)
getTwoNumbersAndOperation = ANode {
-- give us two numbers and an operation
execANode = const $ Fork [] getTwoNumbers makeOperation
}
makeOperation :: Node [Int] ([Int], String)
makeOperation = ANode {
-- mempty
execANode = \ s -> Start (\ b -> (s, b)) getOperation
}
applyOperation :: Node ([Int], String) Int
applyOperation = ANode {
-- and the result is
execANode = \ (num, op) -> EOD $ sum num
}
someOperation :: Node () Int
someOperation = ANode {
execANode = const $ Fork () getTwoNumbersAndOperation applyOperation
}
execNode :: (Serializable s, Serializable o) => s -> Node s o -> IO (Target o)
execNode s (QNode f) = do
i <- getLine
return $ f s i
execNode s (ANode f) = return $ f s
data ConversatioNodes n where
SomeOperation :: ConversatioNodes (Node () Int)
GetTwoNumbersAndOperation :: ConversatioNodes (Node () ([Int], String))
getNode :: ConversatioNodes n -> n
getNode SomeOperation = someOperation
getNode GetTwoNumbersAndOperation = getTwoNumbersAndOperation
getNode' :: String -> Dynamic
getNode' "A" = toDyn askForANumber
class (Serializable s, Serializable o) => Executable n s o where
exec :: n -> s -> (UserInput -> Target o)
instance (Serializable i, Serializable o) => Executable (Node i o) i o where
exec (ANode f) = const . f
exec (QNode f) = f
-- woo :: (Executable (Node [Int] [Int]) s o, Executable (Node () Int) s o) => String -> s -> UserInput -> Target o
woo "A" = exec askForANumber -- someOperation
woo "B" = exec getTwoNumbers
woo "C" = exec someOperation
-- woo = maybe (return $ EOD 0) id (execNode () <$> Just askForANumber)
-- woo' :: IO (Target Int)
-- woo' :: (Executable (Node [Int] [Int]) () o, Executable (Node () Int) () o) => Target o
woo' key s = do
r <- getLine
return $ woo key s r
hoop :: (Executable (Node [Int] [Int]) () o, Executable (Node [Int] [Int]) s o, Executable (Node () Int) s o) => s -> UserInput -> Target o
hoop = woo "A"
--
-- boop :: IO ()
-- boop = getLine >>= \r -> let a = hoop () r in return ()
-- tee :: (Serializable i, Serializable o, Executable n i o) => n -> IO ()
-- tee n = getLine >>= \r -> let a = exec askForANumber () r in return ()
data Func where
Func :: (A -> B) -> Func
-- data B b where
-- BInt :: Int -> B Int
-- BString :: String -> B String
data A = AInt Int | AString String deriving (Show)
data B = BInt Int | BString String deriving (Show)
class Funcable f where
fexec :: (Show b) => f -> A -> B
instance Funcable Func where
fexec (Func f) = f
f1 :: Func
f1 = Func $ \ (AInt i) -> BInt $ i * 2
--
f2 :: Func
f2 = Func $ \ (AString i) -> BString $ i ++ "!"
-- getF :: (Funcable f, Show a, Show b) => String -> a -> B
getF "f1" = f1
getF "f2" = f2
-- getF "f2" = f2
|
homam/fsm-conversational-ui
|
src/HLib61.hs
|
Haskell
|
bsd-3-clause
| 4,576
|
module Evolution.Internal
( EvolutionRules
( EvolutionRules
, mutation
, breeding
, selection
, deaths
, expression
, optimumForGeneration
)
, evolution
) where
import Data.Random
import Data.Functor ()
import Individual
import Population
import Phenotype
import Expression
data EvolutionRules =
EvolutionRules
{ mutation :: ![Mutation]
, breeding :: ![Phenotype -> Int -> Breeding]
, selection :: ![Phenotype -> Selection]
, deaths :: ![Int -> PopulationChange]
, expression :: !ExpressionStrategy
, optimumForGeneration :: !(Int -> Phenotype)
}
step :: [PopulationChange] -> RVar [Individual] -> RVar [Individual]
step changes population = foldl (>>=) population changes
evolution :: Int -> EvolutionRules -> RVar Population -> RVar [Population]
evolution 0 _ _ = return []
evolution genToGen spec population = do
p <- population
let g = 1 + generation p
let todayOptimum = optimumForGeneration spec g
let breedingForGeneration = map (\f -> f todayOptimum g) $ breeding spec
let mutationForGeneration = mutation spec
let selectionForGeneration = map (\f -> f todayOptimum) $ selection spec
let deathForGeneration = map (\f -> f g) $ deaths spec
let stepAlgo = breedingForGeneration ++
mutationForGeneration ++
selectionForGeneration ++
deathForGeneration
newIndividuals <- step stepAlgo $ individuals <$> population
rest <- evolution (genToGen - 1) spec <$> return $ Population g newIndividuals
return (p : rest)
|
satai/FrozenBeagle
|
Simulation/Lib/src/Evolution/Internal.hs
|
Haskell
|
bsd-3-clause
| 1,805
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{- |
Module : Verifier.SAW.Cryptol.Monadify
Copyright : Galois, Inc. 2021
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (language extensions)
This module implements a "monadification" transformation, which converts "pure"
SAW core terms that use inconsistent operations like @fix@ and convert them to
monadic SAW core terms that use monadic versions of these operations that are
consistent. The monad that is used is the @CompM@ monad that is axiomatized in
the SAW cxore prelude. This is only a partial transformation, meaning that it
will fail on some SAW core terms. Specifically, it requires that all
applications @f arg@ in a term either have a non-dependent function type for @f@
(i.e., a function with type @'Pi' x a b@ where @x@ does not occur in @b@) or a
pure argument @arg@ that does not use any of the inconsistent operations.
FIXME: explain this better
Type-level translation:
MT(Pi x (sort 0) b) = Pi x (sort 0) CompMT(b)
MT(Pi x Num b) = Pi x Num CompMT(b)
MT(Pi _ a b) = MT(a) -> CompMT(b)
MT(#(a,b)) = #(MT(a),MT(b))
MT(seq n a) = mseq n MT(a)
MT(f arg) = f MT(arg) -- NOTE: f must be a pure function!
MT(cnst) = cnst
MT(dt args) = dt MT(args)
MT(x) = x
MT(_) = error
CompMT(tp = Pi _ _ _) = MT(tp)
CompMT(n : Num) = n
CompMT(tp) = CompM MT(tp)
Term-level translation:
MonArg(t : tp) ==> MT(tp)
MonArg(t) =
case Mon(t) of
m : CompM MT(a) => shift \k -> m >>= \x -> k x
_ => t
Mon(t : tp) ==> MT(tp) or CompMT(tp) (which are the same type for pis)
Mon((f : Pi x a b) arg) = Mon(f) MT(arg)
Mon((f : Pi _ a b) arg) = Mon(f) MonArg(arg)
Mon(Lambda x a t) = Lambda x MT(a) Mon(t)
Mon((t,u)) = (MonArg(t),MonArg(u))
Mon(c args) = c MonArg(args)
Mon(x) = x
Mon(fix) = fixM (of some form...)
Mon(cnst) = cnstM if cnst is impure and monadifies to constM
Mon(cnst) = cnst otherwise
-}
module Verifier.SAW.Cryptol.Monadify where
import Data.Maybe
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Cont
import qualified Control.Monad.Fail as Fail
-- import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Data.Text as T
import qualified Text.URI as URI
import Verifier.SAW.Name
import Verifier.SAW.Term.Functor
import Verifier.SAW.SharedTerm
import Verifier.SAW.OpenTerm
-- import Verifier.SAW.SCTypeCheck
import Verifier.SAW.Recognizer
-- import Verifier.SAW.Position
import Verifier.SAW.Cryptol.PreludeM
import Debug.Trace
-- Type-check the Prelude, Cryptol, and CryptolM modules at compile time
{-
import Language.Haskell.TH
import Verifier.SAW.Cryptol.Prelude
$(runIO (mkSharedContext >>= \sc ->
scLoadPreludeModule sc >> scLoadCryptolModule sc >>
scLoadCryptolMModule sc >> return []))
-}
----------------------------------------------------------------------
-- * Typing All Subterms
----------------------------------------------------------------------
-- | A SAW core term where all of the subterms are typed
data TypedSubsTerm
= TypedSubsTerm { tpSubsIndex :: Maybe TermIndex,
tpSubsFreeVars :: BitSet,
tpSubsTermF :: TermF TypedSubsTerm,
tpSubsTypeF :: TermF TypedSubsTerm,
tpSubsSort :: Sort }
-- | Convert a 'Term' to a 'TypedSubsTerm'
typeAllSubterms :: SharedContext -> Term -> IO TypedSubsTerm
typeAllSubterms = error "FIXME HERE"
-- | Convert a 'TypedSubsTerm' back to a 'Term'
typedSubsTermTerm :: TypedSubsTerm -> Term
typedSubsTermTerm = error "FIXME HERE"
-- | Get the type of a 'TypedSubsTerm' as a 'TypedSubsTerm'
typedSubsTermType :: TypedSubsTerm -> TypedSubsTerm
typedSubsTermType tst =
TypedSubsTerm { tpSubsIndex = Nothing, tpSubsFreeVars = tpSubsFreeVars tst,
tpSubsTermF = tpSubsTypeF tst,
tpSubsTypeF = FTermF (Sort (tpSubsSort tst) False),
tpSubsSort = sortOf (tpSubsSort tst) }
-- | Count the number of right-nested pi-abstractions of a 'TypedSubsTerm'
typedSubsTermArity :: TypedSubsTerm -> Int
typedSubsTermArity (TypedSubsTerm { tpSubsTermF = Pi _ _ tst }) =
1 + typedSubsTermArity tst
typedSubsTermArity _ = 0
-- | Count the number of right-nested pi abstractions in a term, which
-- represents a type. This assumes that the type is in WHNF.
typeArity :: Term -> Int
typeArity tp = length $ fst $ asPiList tp
class ToTerm a where
toTerm :: a -> Term
instance ToTerm Term where
toTerm = id
instance ToTerm TypedSubsTerm where
toTerm = typedSubsTermTerm
unsharedApply :: Term -> Term -> Term
unsharedApply f arg = Unshared $ App f arg
----------------------------------------------------------------------
-- * Monadifying Types
----------------------------------------------------------------------
-- | Test if a 'Term' is a first-order function type
isFirstOrderType :: Term -> Bool
isFirstOrderType (asPi -> Just (_, asPi -> Just _, _)) = False
isFirstOrderType (asPi -> Just (_, _, tp_out)) = isFirstOrderType tp_out
isFirstOrderType _ = True
-- | A global definition, which is either a primitive or a constant. As
-- described in the documentation for 'ExtCns', the names need not be unique,
-- but the 'VarIndex' is, and this is what is used to index 'GlobalDef's.
data GlobalDef = GlobalDef { globalDefName :: NameInfo,
globalDefIndex :: VarIndex,
globalDefType :: Term,
globalDefTerm :: Term,
globalDefBody :: Maybe Term }
instance Eq GlobalDef where
gd1 == gd2 = globalDefIndex gd1 == globalDefIndex gd2
instance Ord GlobalDef where
compare gd1 gd2 = compare (globalDefIndex gd1) (globalDefIndex gd2)
instance Show GlobalDef where
show = show . globalDefName
-- | Get the 'String' name of a 'GlobalDef'
globalDefString :: GlobalDef -> String
globalDefString = T.unpack . toAbsoluteName . globalDefName
-- | Build an 'OpenTerm' from a 'GlobalDef'
globalDefOpenTerm :: GlobalDef -> OpenTerm
globalDefOpenTerm = closedOpenTerm . globalDefTerm
-- | Recognize a named global definition, including its type
asTypedGlobalDef :: Recognizer Term GlobalDef
asTypedGlobalDef t =
case unwrapTermF t of
FTermF (Primitive pn) ->
Just $ GlobalDef (ModuleIdentifier $
primName pn) (primVarIndex pn) (primType pn) t Nothing
Constant ec body ->
Just $ GlobalDef (ecName ec) (ecVarIndex ec) (ecType ec) t body
FTermF (ExtCns ec) ->
Just $ GlobalDef (ecName ec) (ecVarIndex ec) (ecType ec) t Nothing
_ -> Nothing
data MonKind = MKType Sort | MKNum | MKFun MonKind MonKind deriving Eq
-- | Convert a kind to a SAW core sort, if possible
monKindToSort :: MonKind -> Maybe Sort
monKindToSort (MKType s) = Just s
monKindToSort _ = Nothing
-- | Convert a 'MonKind' to the term it represents
monKindOpenTerm :: MonKind -> OpenTerm
monKindOpenTerm (MKType s) = sortOpenTerm s
monKindOpenTerm MKNum = dataTypeOpenTerm "Cryptol.Num" []
monKindOpenTerm (MKFun k1 k2) =
arrowOpenTerm "_" (monKindOpenTerm k1) (monKindOpenTerm k2)
data MonType
= MTyForall LocalName MonKind (MonType -> MonType)
| MTyArrow MonType MonType
| MTySeq OpenTerm MonType
| MTyPair MonType MonType
| MTyRecord [(FieldName, MonType)]
| MTyBase MonKind OpenTerm -- A "base type" or type var of a given kind
| MTyNum OpenTerm
-- | Make a base type of sort 0 from an 'OpenTerm'
mkMonType0 :: OpenTerm -> MonType
mkMonType0 = MTyBase (MKType $ mkSort 0)
-- | Make a 'MonType' for the Boolean type
boolMonType :: MonType
boolMonType = mkMonType0 $ globalOpenTerm "Prelude.Bool"
-- | Test that a monadification type is monomorphic, i.e., has no foralls
monTypeIsMono :: MonType -> Bool
monTypeIsMono (MTyForall _ _ _) = False
monTypeIsMono (MTyArrow tp1 tp2) = monTypeIsMono tp1 && monTypeIsMono tp2
monTypeIsMono (MTyPair tp1 tp2) = monTypeIsMono tp1 && monTypeIsMono tp2
monTypeIsMono (MTyRecord tps) = all (monTypeIsMono . snd) tps
monTypeIsMono (MTySeq _ tp) = monTypeIsMono tp
monTypeIsMono (MTyBase _ _) = True
monTypeIsMono (MTyNum _) = True
-- | Test if a monadification type @tp@ is considered a base type, meaning that
-- @CompMT(tp) = CompM MT(tp)@
isBaseType :: MonType -> Bool
isBaseType (MTyForall _ _ _) = False
isBaseType (MTyArrow _ _) = False
isBaseType (MTySeq _ _) = True
isBaseType (MTyPair _ _) = True
isBaseType (MTyRecord _) = True
isBaseType (MTyBase (MKType _) _) = True
isBaseType (MTyBase _ _) = True
isBaseType (MTyNum _) = False
-- | If a 'MonType' is a type-level number, return its 'OpenTerm', otherwise
-- return 'Nothing'
monTypeNum :: MonType -> Maybe OpenTerm
monTypeNum (MTyNum t) = Just t
monTypeNum (MTyBase MKNum t) = Just t
monTypeNum _ = Nothing
-- | Get the kind of a 'MonType', assuming it has one
monTypeKind :: MonType -> Maybe MonKind
monTypeKind (MTyForall _ _ _) = Nothing
monTypeKind (MTyArrow t1 t2) =
do s1 <- monTypeKind t1 >>= monKindToSort
s2 <- monTypeKind t2 >>= monKindToSort
return $ MKType $ maxSort [s1, s2]
monTypeKind (MTyPair tp1 tp2) =
do sort1 <- monTypeKind tp1 >>= monKindToSort
sort2 <- monTypeKind tp2 >>= monKindToSort
return $ MKType $ maxSort [sort1, sort2]
monTypeKind (MTyRecord tps) =
do sorts <- mapM (monTypeKind . snd >=> monKindToSort) tps
return $ MKType $ maxSort sorts
monTypeKind (MTySeq _ tp) =
do sort <- monTypeKind tp >>= monKindToSort
return $ MKType sort
monTypeKind (MTyBase k _) = Just k
monTypeKind (MTyNum _) = Just MKNum
-- | Get the 'Sort' @s@ of a 'MonType' if it has kind @'MKType' s@
monTypeSort :: MonType -> Maybe Sort
monTypeSort = monTypeKind >=> monKindToSort
-- | Convert a SAW core 'Term' to a monadification kind, if possible
monadifyKind :: Term -> Maybe MonKind
monadifyKind (asDataType -> Just (num, []))
| primName num == "Cryptol.Num" = return MKNum
monadifyKind (asSort -> Just s) = return $ MKType s
monadifyKind (asPi -> Just (_, tp_in, tp_out)) =
MKFun <$> monadifyKind tp_in <*> monadifyKind tp_out
monadifyKind _ = Nothing
-- | Get the kind of a type constructor with kind @k@ applied to type @t@, or
-- return 'Nothing' if the kinds do not line up
applyKind :: MonKind -> MonType -> Maybe MonKind
applyKind (MKFun k1 k2) t
| Just kt <- monTypeKind t
, kt == k1 = Just k2
applyKind _ _ = Nothing
-- | Perform 'applyKind' for 0 or more argument types
applyKinds :: MonKind -> [MonType] -> Maybe MonKind
applyKinds = foldM applyKind
-- | Convert a 'MonType' to the argument type @MT(tp)@ it represents
toArgType :: MonType -> OpenTerm
toArgType (MTyForall x k body) =
piOpenTerm x (monKindOpenTerm k) (\tp -> toCompType (body $ MTyBase k tp))
toArgType (MTyArrow t1 t2) =
arrowOpenTerm "_" (toArgType t1) (toCompType t2)
toArgType (MTySeq n t) =
applyOpenTermMulti (globalOpenTerm "CryptolM.mseq") [n, toArgType t]
toArgType (MTyPair mtp1 mtp2) =
pairTypeOpenTerm (toArgType mtp1) (toArgType mtp2)
toArgType (MTyRecord tps) =
recordTypeOpenTerm $ map (\(f,tp) -> (f, toArgType tp)) tps
toArgType (MTyBase _ t) = t
toArgType (MTyNum n) = n
-- | Convert a 'MonType' to the computation type @CompMT(tp)@ it represents
toCompType :: MonType -> OpenTerm
toCompType mtp@(MTyForall _ _ _) = toArgType mtp
toCompType mtp@(MTyArrow _ _) = toArgType mtp
toCompType mtp = applyOpenTerm (globalOpenTerm "Prelude.CompM") (toArgType mtp)
-- | The mapping for monadifying Cryptol typeclasses
-- FIXME: this is no longer needed, as it is now the identity
typeclassMonMap :: [(Ident,Ident)]
typeclassMonMap =
[("Cryptol.PEq", "Cryptol.PEq"),
("Cryptol.PCmp", "Cryptol.PCmp"),
("Cryptol.PSignedCmp", "Cryptol.PSignedCmp"),
("Cryptol.PZero", "Cryptol.PZero"),
("Cryptol.PLogic", "Cryptol.PLogic"),
("Cryptol.PRing", "Cryptol.PRing"),
("Cryptol.PIntegral", "Cryptol.PIntegral"),
("Cryptol.PLiteral", "Cryptol.PLiteral")]
-- | A context of local variables used for monadifying types, which includes the
-- variable names, their original types (before monadification), and, if their
-- types corespond to 'MonKind's, a local 'MonType' that quantifies over them.
--
-- NOTE: the reason this type is different from 'MonadifyCtx', the context type
-- for monadifying terms, is that monadifying arrow types does not introduce a
-- local 'MonTerm' argument, since they are not dependent functions and so do
-- not use a HOAS encoding.
type MonadifyTypeCtx = [(LocalName,Term,Maybe MonType)]
-- | Pretty-print a 'Term' relative to a 'MonadifyTypeCtx'
ppTermInTypeCtx :: MonadifyTypeCtx -> Term -> String
ppTermInTypeCtx ctx t =
scPrettyTermInCtx defaultPPOpts (map (\(x,_,_) -> x) ctx) t
-- | Extract the variables and their original types from a 'MonadifyTypeCtx'
typeCtxPureCtx :: MonadifyTypeCtx -> [(LocalName,Term)]
typeCtxPureCtx = map (\(x,tp,_) -> (x,tp))
-- | Make a monadification type that is to be considered a base type
mkTermBaseType :: MonadifyTypeCtx -> MonKind -> Term -> MonType
mkTermBaseType ctx k t =
MTyBase k $ openOpenTerm (typeCtxPureCtx ctx) t
-- | Monadify a type and convert it to its corresponding argument type
monadifyTypeArgType :: MonadifyTypeCtx -> Term -> OpenTerm
monadifyTypeArgType ctx t = toArgType $ monadifyType ctx t
-- | Apply a monadified type to a type or term argument in the sense of
-- 'applyPiOpenTerm', meaning give the type of applying @f@ of a type to a
-- particular argument @arg@
applyMonType :: MonType -> Either MonType ArgMonTerm -> MonType
applyMonType (MTyArrow _ tp_ret) (Right _) = tp_ret
applyMonType (MTyForall _ _ f) (Left mtp) = f mtp
applyMonType _ _ = error "applyMonType: application at incorrect type"
-- | Convert a SAW core 'Term' to a monadification type
monadifyType :: MonadifyTypeCtx -> Term -> MonType
{-
monadifyType ctx t
| trace ("\nmonadifyType:\n" ++ ppTermInTypeCtx ctx t) False = undefined
-}
monadifyType ctx (asPi -> Just (x, tp_in, tp_out))
| Just k <- monadifyKind tp_in =
MTyForall x k (\tp' -> monadifyType ((x,tp_in,Just tp'):ctx) tp_out)
monadifyType ctx tp@(asPi -> Just (_, _, tp_out))
| inBitSet 0 (looseVars tp_out) =
error ("monadifyType: " ++
"dependent function type with non-kind argument type: " ++
ppTermInTypeCtx ctx tp)
monadifyType ctx tp@(asPi -> Just (x, tp_in, tp_out)) =
MTyArrow (monadifyType ctx tp_in)
(monadifyType ((x,tp,Nothing):ctx) tp_out)
monadifyType ctx (asPairType -> Just (tp1, tp2)) =
MTyPair (monadifyType ctx tp1) (monadifyType ctx tp2)
monadifyType ctx (asRecordType -> Just tps) =
MTyRecord $ map (\(fld,tp) -> (fld, monadifyType ctx tp)) $ Map.toList tps
monadifyType ctx (asDataType -> Just (eq_pn, [k_trm, tp1, tp2]))
| primName eq_pn == "Prelude.Eq"
, isJust (monadifyKind k_trm) =
-- NOTE: technically this is a Prop and not a sort 0, but it doesn't matter
mkMonType0 $ dataTypeOpenTerm "Prelude.Eq" [monadifyTypeArgType ctx tp1,
monadifyTypeArgType ctx tp2]
monadifyType ctx (asDataType -> Just (pn, args))
| Just pn_k <- monadifyKind (primType pn)
, margs <- map (monadifyType ctx) args
, Just k_out <- applyKinds pn_k margs =
-- NOTE: this case only recognizes data types whose arguments are all types
-- and/or Nums
MTyBase k_out $ dataTypeOpenTerm (primName pn) (map toArgType margs)
monadifyType ctx (asVectorType -> Just (len, tp)) =
let lenOT = openOpenTerm (typeCtxPureCtx ctx) len in
MTySeq (ctorOpenTerm "Cryptol.TCNum" [lenOT]) $ monadifyType ctx tp
monadifyType ctx tp@(asApplyAll -> ((asGlobalDef -> Just seq_id), [n, a]))
| seq_id == "Cryptol.seq" =
case monTypeNum (monadifyType ctx n) of
Just n_trm -> MTySeq n_trm (monadifyType ctx a)
Nothing ->
error ("Monadify type: not a number: " ++ ppTermInTypeCtx ctx n
++ " in type: " ++ ppTermInTypeCtx ctx tp)
monadifyType ctx (asApp -> Just ((asGlobalDef -> Just f), arg))
| Just f_trans <- lookup f typeclassMonMap =
MTyBase (MKType $ mkSort 1) $
applyOpenTerm (globalOpenTerm f_trans) $ monadifyTypeArgType ctx arg
monadifyType _ (asGlobalDef -> Just bool_id)
| bool_id == "Prelude.Bool" =
mkMonType0 (globalOpenTerm "Prelude.Bool")
{-
monadifyType ctx (asApplyAll -> (f, args))
| Just glob <- asTypedGlobalDef f
, Just ec_k <- monadifyKind $ globalDefType glob
, margs <- map (monadifyType ctx) args
, Just k_out <- applyKinds ec_k margs =
MTyBase k_out (applyOpenTermMulti (globalDefOpenTerm glob) $
map toArgType margs)
-}
monadifyType ctx tp@(asCtor -> Just (pn, _))
| primName pn == "Cryptol.TCNum" || primName pn == "Cryptol.TCInf" =
MTyNum $ openOpenTerm (typeCtxPureCtx ctx) tp
monadifyType ctx (asLocalVar -> Just i)
| i < length ctx
, (_,_,Just tp) <- ctx!!i = tp
monadifyType ctx tp =
error ("monadifyType: not a valid type for monadification: "
++ ppTermInTypeCtx ctx tp)
----------------------------------------------------------------------
-- * Monadified Terms
----------------------------------------------------------------------
-- | A representation of a term that has been translated to argument type
-- @MT(tp)@
data ArgMonTerm
-- | A monadification term of a base type @MT(tp)@
= BaseMonTerm MonType OpenTerm
-- | A monadification term of non-depedent function type
| FunMonTerm LocalName MonType MonType (ArgMonTerm -> MonTerm)
-- | A monadification term of polymorphic type
| ForallMonTerm LocalName MonKind (MonType -> MonTerm)
-- | A representation of a term that has been translated to computational type
-- @CompMT(tp)@
data MonTerm
= ArgMonTerm ArgMonTerm
| CompMonTerm MonType OpenTerm
-- | Get the monadification type of a monadification term
class GetMonType a where
getMonType :: a -> MonType
instance GetMonType ArgMonTerm where
getMonType (BaseMonTerm tp _) = tp
getMonType (ForallMonTerm x k body) = MTyForall x k (getMonType . body)
getMonType (FunMonTerm _ tp_in tp_out _) = MTyArrow tp_in tp_out
instance GetMonType MonTerm where
getMonType (ArgMonTerm t) = getMonType t
getMonType (CompMonTerm tp _) = tp
-- | Convert a monadification term to a SAW core term of type @CompMT(tp)@
class ToCompTerm a where
toCompTerm :: a -> OpenTerm
instance ToCompTerm ArgMonTerm where
toCompTerm (BaseMonTerm mtp t) =
applyOpenTermMulti (globalOpenTerm "Prelude.returnM") [toArgType mtp, t]
toCompTerm (FunMonTerm x tp_in _ body) =
lambdaOpenTerm x (toArgType tp_in) (toCompTerm . body . fromArgTerm tp_in)
toCompTerm (ForallMonTerm x k body) =
lambdaOpenTerm x (monKindOpenTerm k) (toCompTerm . body . MTyBase k)
instance ToCompTerm MonTerm where
toCompTerm (ArgMonTerm amtrm) = toCompTerm amtrm
toCompTerm (CompMonTerm _ trm) = trm
-- | Convert an 'ArgMonTerm' to a SAW core term of type @MT(tp)@
toArgTerm :: ArgMonTerm -> OpenTerm
toArgTerm (BaseMonTerm _ t) = t
toArgTerm t = toCompTerm t
-- | Build a monadification term from a term of type @MT(tp)@
class FromArgTerm a where
fromArgTerm :: MonType -> OpenTerm -> a
instance FromArgTerm ArgMonTerm where
fromArgTerm (MTyForall x k body) t =
ForallMonTerm x k (\tp -> fromCompTerm (body tp) (applyOpenTerm t $
toArgType tp))
fromArgTerm (MTyArrow t1 t2) t =
FunMonTerm "_" t1 t2 (\x -> fromCompTerm t2 (applyOpenTerm t $ toArgTerm x))
fromArgTerm tp t = BaseMonTerm tp t
instance FromArgTerm MonTerm where
fromArgTerm mtp t = ArgMonTerm $ fromArgTerm mtp t
-- | Build a monadification term from a computational term of type @CompMT(tp)@
fromCompTerm :: MonType -> OpenTerm -> MonTerm
fromCompTerm mtp t | isBaseType mtp = CompMonTerm mtp t
fromCompTerm mtp t = ArgMonTerm $ fromArgTerm mtp t
-- | Build a monadification term from a function on terms which, when viewed as
-- a lambda, is a "semi-pure" function of the given monadification type, meaning
-- it maps terms of argument type @MT(tp)@ to an output value of argument type;
-- i.e., it has type @SemiP(tp)@, defined as:
--
-- > SemiP(Pi x (sort 0) b) = Pi x (sort 0) SemiP(b)
-- > SemiP(Pi x Num b) = Pi x Num SemiP(b)
-- > SemiP(Pi _ a b) = MT(a) -> SemiP(b)
-- > SemiP(a) = MT(a)
fromSemiPureTermFun :: MonType -> ([OpenTerm] -> OpenTerm) -> ArgMonTerm
fromSemiPureTermFun (MTyForall x k body) f =
ForallMonTerm x k $ \tp ->
ArgMonTerm $ fromSemiPureTermFun (body tp) (f . (toArgType tp:))
fromSemiPureTermFun (MTyArrow t1 t2) f =
FunMonTerm "_" t1 t2 $ \x ->
ArgMonTerm $ fromSemiPureTermFun t2 (f . (toArgTerm x:))
fromSemiPureTermFun tp f = BaseMonTerm tp (f [])
-- | Like 'fromSemiPureTermFun' but use a term rather than a term function
fromSemiPureTerm :: MonType -> OpenTerm -> ArgMonTerm
fromSemiPureTerm mtp t = fromSemiPureTermFun mtp (applyOpenTermMulti t)
-- | Build a 'MonTerm' that 'fail's when converted to a term
failMonTerm :: MonType -> String -> MonTerm
failMonTerm mtp str = fromArgTerm mtp (failOpenTerm str)
-- | Build an 'ArgMonTerm' that 'fail's when converted to a term
failArgMonTerm :: MonType -> String -> ArgMonTerm
failArgMonTerm tp str = fromArgTerm tp (failOpenTerm str)
-- | Apply a monadified term to a type or term argument
applyMonTerm :: MonTerm -> Either MonType ArgMonTerm -> MonTerm
applyMonTerm (ArgMonTerm (FunMonTerm _ _ _ f)) (Right arg) = f arg
applyMonTerm (ArgMonTerm (ForallMonTerm _ _ f)) (Left mtp) = f mtp
applyMonTerm _ _ = error "applyMonTerm: application at incorrect type"
-- | Apply a monadified term to 0 or more arguments
applyMonTermMulti :: MonTerm -> [Either MonType ArgMonTerm] -> MonTerm
applyMonTermMulti = foldl applyMonTerm
-- | Build a 'MonTerm' from a global of a given argument type
mkGlobalArgMonTerm :: MonType -> Ident -> ArgMonTerm
mkGlobalArgMonTerm tp ident = fromArgTerm tp (globalOpenTerm ident)
-- | Build a 'MonTerm' from a 'GlobalDef' of semi-pure type
mkSemiPureGlobalDefTerm :: GlobalDef -> ArgMonTerm
mkSemiPureGlobalDefTerm glob =
fromSemiPureTerm (monadifyType [] $
globalDefType glob) (globalDefOpenTerm glob)
-- | Build a 'MonTerm' from a constructor with the given 'PrimName'
mkCtorArgMonTerm :: PrimName Term -> ArgMonTerm
mkCtorArgMonTerm pn
| not (isFirstOrderType (primType pn)) =
failArgMonTerm (monadifyType [] $ primType pn)
("monadification failed: cannot handle constructor "
++ show (primName pn) ++ " with higher-order type")
mkCtorArgMonTerm pn =
fromSemiPureTermFun (monadifyType [] $ primType pn) (ctorOpenTerm $ primName pn)
----------------------------------------------------------------------
-- * Monadification Environments and Contexts
----------------------------------------------------------------------
-- | A monadification macro is a function that inspects its first @N@ arguments
-- before deciding how to monadify itself
data MonMacro = MonMacro {
macroNumArgs :: Int,
macroApply :: GlobalDef -> [Term] -> MonadifyM MonTerm }
-- | Make a simple 'MonMacro' that inspects 0 arguments and just returns a term
monMacro0 :: MonTerm -> MonMacro
monMacro0 mtrm = MonMacro 0 (\_ _ -> return mtrm)
-- | Make a 'MonMacro' that maps a named global to a global of semi-pure type.
-- (See 'fromSemiPureTermFun'.) Because we can't get access to the type of the
-- global until we apply the macro, we monadify its type at macro application
-- time.
semiPureGlobalMacro :: Ident -> Ident -> MonMacro
semiPureGlobalMacro from to =
MonMacro 0 $ \glob args ->
if globalDefName glob == ModuleIdentifier from && args == [] then
return $ ArgMonTerm $
fromSemiPureTerm (monadifyType [] $ globalDefType glob) (globalOpenTerm to)
else
error ("Monadification macro for " ++ show from ++ " applied incorrectly")
-- | Make a 'MonMacro' that maps a named global to a global of argument
-- type. Because we can't get access to the type of the global until we apply
-- the macro, we monadify its type at macro application time.
argGlobalMacro :: NameInfo -> Ident -> MonMacro
argGlobalMacro from to =
MonMacro 0 $ \glob args ->
if globalDefName glob == from && args == [] then
return $ ArgMonTerm $
mkGlobalArgMonTerm (monadifyType [] $ globalDefType glob) to
else
error ("Monadification macro for " ++ show from ++ " applied incorrectly")
-- | An environment of named primitives and how to monadify them
type MonadifyEnv = Map NameInfo MonMacro
-- | A context for monadifying 'Term's which maintains, for each deBruijn index
-- in scope, both its original un-monadified type along with either a 'MonTerm'
-- or 'MonType' for the translation of the variable to a local variable of
-- monadified type or monadified kind
type MonadifyCtx = [(LocalName,Term,Either MonType MonTerm)]
-- | Convert a 'MonadifyCtx' to a 'MonadifyTypeCtx'
ctxToTypeCtx :: MonadifyCtx -> MonadifyTypeCtx
ctxToTypeCtx = map (\(x,tp,arg) ->
(x,tp,case arg of
Left mtp -> Just mtp
Right _ -> Nothing))
-- | Pretty-print a 'Term' relative to a 'MonadifyCtx'
ppTermInMonCtx :: MonadifyCtx -> Term -> String
ppTermInMonCtx ctx t =
scPrettyTermInCtx defaultPPOpts (map (\(x,_,_) -> x) ctx) t
-- | A memoization table for monadifying terms
type MonadifyMemoTable = IntMap MonTerm
-- | The empty memoization table
emptyMemoTable :: MonadifyMemoTable
emptyMemoTable = IntMap.empty
----------------------------------------------------------------------
-- * The Monadification Monad
----------------------------------------------------------------------
-- | The read-only state of a monadification computation
data MonadifyROState = MonadifyROState {
-- | The monadification environment
monStEnv :: MonadifyEnv,
-- | The monadification context
monStCtx :: MonadifyCtx,
-- | The monadified return type of the top-level term being monadified
monStTopRetType :: OpenTerm
}
-- | The monad for monadifying SAW core terms
newtype MonadifyM a =
MonadifyM { unMonadifyM ::
ReaderT MonadifyROState (StateT MonadifyMemoTable
(Cont MonTerm)) a }
deriving (Functor, Applicative, Monad,
MonadReader MonadifyROState, MonadState MonadifyMemoTable)
instance Fail.MonadFail MonadifyM where
fail str =
do ret_tp <- topRetType
shiftMonadifyM $ \_ -> failMonTerm (mkMonType0 ret_tp) str
-- | Capture the current continuation and pass it to a function, which must
-- return the final computation result. Note that this is slightly differnet
-- from normal shift, and I think corresponds to the C operator, but my quick
-- googling couldn't find the right name...
shiftMonadifyM :: ((a -> MonTerm) -> MonTerm) -> MonadifyM a
shiftMonadifyM f = MonadifyM $ lift $ lift $ cont f
-- | Locally run a 'MonadifyM' computation with an empty memoization table,
-- making all binds be local to that computation, and return the result
resetMonadifyM :: OpenTerm -> MonadifyM MonTerm -> MonadifyM MonTerm
resetMonadifyM ret_tp m =
do ro_st <- ask
return $ runMonadifyM (monStEnv ro_st) (monStCtx ro_st) ret_tp m
-- | Get the monadified return type of the top-level term being monadified
topRetType :: MonadifyM OpenTerm
topRetType = monStTopRetType <$> ask
-- | Run a monadification computation
--
-- FIXME: document the arguments
runMonadifyM :: MonadifyEnv -> MonadifyCtx -> OpenTerm ->
MonadifyM MonTerm -> MonTerm
runMonadifyM env ctx top_ret_tp m =
let ro_st = MonadifyROState env ctx top_ret_tp in
runCont (evalStateT (runReaderT (unMonadifyM m) ro_st) emptyMemoTable) id
-- | Run a monadification computation using a mapping for identifiers that have
-- already been monadified and generate a SAW core term
runCompleteMonadifyM :: MonadIO m => SharedContext -> MonadifyEnv ->
Term -> MonadifyM MonTerm -> m Term
runCompleteMonadifyM sc env top_ret_tp m =
liftIO $ completeOpenTerm sc $ toCompTerm $
runMonadifyM env [] (toArgType $ monadifyType [] top_ret_tp) m
-- | Memoize a computation of the monadified term associated with a 'TermIndex'
memoizingM :: TermIndex -> MonadifyM MonTerm -> MonadifyM MonTerm
memoizingM i m =
(IntMap.lookup i <$> get) >>= \case
Just ret ->
return ret
Nothing ->
do ret <- m
modify (IntMap.insert i ret)
return ret
-- | Turn a 'MonTerm' of type @CompMT(tp)@ to a term of argument type @MT(tp)@
-- by inserting a monadic bind if the 'MonTerm' is computational
argifyMonTerm :: MonTerm -> MonadifyM ArgMonTerm
argifyMonTerm (ArgMonTerm mtrm) = return mtrm
argifyMonTerm (CompMonTerm mtp trm) =
do let tp = toArgType mtp
top_ret_tp <- topRetType
shiftMonadifyM $ \k ->
CompMonTerm (mkMonType0 top_ret_tp) $
applyOpenTermMulti (globalOpenTerm "Prelude.bindM")
[tp, top_ret_tp, trm,
lambdaOpenTerm "x" tp (toCompTerm . k . fromArgTerm mtp)]
-- | Build a proof of @isFinite n@ by calling @assertFiniteM@ and binding the
-- result to an 'ArgMonTerm'
assertIsFinite :: MonType -> MonadifyM ArgMonTerm
assertIsFinite (MTyNum n) =
argifyMonTerm (CompMonTerm
(mkMonType0 (applyOpenTerm
(globalOpenTerm "CryptolM.isFinite") n))
(applyOpenTerm (globalOpenTerm "CryptolM.assertFiniteM") n))
assertIsFinite _ =
fail ("assertIsFinite applied to non-Num argument")
----------------------------------------------------------------------
-- * Monadification
----------------------------------------------------------------------
-- | Monadify a type in the context of the 'MonadifyM' monad
monadifyTypeM :: Term -> MonadifyM MonType
monadifyTypeM tp =
do ctx <- monStCtx <$> ask
return $ monadifyType (ctxToTypeCtx ctx) tp
-- | Monadify a term to a monadified term of argument type
monadifyArg :: Maybe MonType -> Term -> MonadifyM ArgMonTerm
monadifyArg mtp t = monadifyTerm mtp t >>= argifyMonTerm
-- | Monadify a term to argument type and convert back to a term
monadifyArgTerm :: Maybe MonType -> Term -> MonadifyM OpenTerm
monadifyArgTerm mtp t = toArgTerm <$> monadifyArg mtp t
-- | Monadify a term
monadifyTerm :: Maybe MonType -> Term -> MonadifyM MonTerm
{-
monadifyTerm _ t
| trace ("Monadifying term: " ++ showTerm t) False
= undefined
-}
monadifyTerm mtp t@(STApp { stAppIndex = ix }) =
memoizingM ix $ monadifyTerm' mtp t
monadifyTerm mtp t =
monadifyTerm' mtp t
-- | The main implementation of 'monadifyTerm', which monadifies a term given an
-- optional monadification type. The type must be given for introduction forms
-- (i.e.,, lambdas, pairs, and records), but is optional for elimination forms
-- (i.e., applications, projections, and also in this case variables). Note that
-- this means monadification will fail on terms with beta or tuple redexes.
monadifyTerm' :: Maybe MonType -> Term -> MonadifyM MonTerm
monadifyTerm' (Just mtp) t@(asLambda -> Just _) =
ask >>= \(MonadifyROState { monStEnv = env, monStCtx = ctx }) ->
return $ monadifyLambdas env ctx mtp t
{-
monadifyTerm' (Just mtp@(MTyForall _ _ _)) t =
ask >>= \ro_st ->
get >>= \table ->
return $ monadifyLambdas (monStEnv ro_st) table (monStCtx ro_st) mtp t
monadifyTerm' (Just mtp@(MTyArrow _ _)) t =
ask >>= \ro_st ->
get >>= \table ->
return $ monadifyLambdas (monStEnv ro_st) table (monStCtx ro_st) mtp t
-}
monadifyTerm' (Just mtp@(MTyPair mtp1 mtp2)) (asPairValue ->
Just (trm1, trm2)) =
fromArgTerm mtp <$> (pairOpenTerm <$>
monadifyArgTerm (Just mtp1) trm1 <*>
monadifyArgTerm (Just mtp2) trm2)
monadifyTerm' (Just mtp@(MTyRecord fs_mtps)) (asRecordValue -> Just trm_map)
| length fs_mtps == Map.size trm_map
, (fs,mtps) <- unzip fs_mtps
, Just trms <- mapM (\f -> Map.lookup f trm_map) fs =
fromArgTerm mtp <$> recordOpenTerm <$> zip fs <$>
zipWithM monadifyArgTerm (map Just mtps) trms
monadifyTerm' _ (asPairSelector -> Just (trm, False)) =
do mtrm <- monadifyArg Nothing trm
mtp <- case getMonType mtrm of
MTyPair t _ -> return t
_ -> fail "Monadification failed: projection on term of non-pair type"
return $ fromArgTerm mtp $
pairLeftOpenTerm $ toArgTerm mtrm
monadifyTerm' (Just mtp@(MTySeq n mtp_elem)) (asFTermF ->
Just (ArrayValue _ trms)) =
do trms' <- traverse (monadifyArgTerm $ Just mtp_elem) trms
return $ fromArgTerm mtp $
applyOpenTermMulti (globalOpenTerm "CryptolM.seqToMseq")
[n, toArgType mtp_elem,
flatOpenTerm $ ArrayValue (toArgType mtp_elem) trms']
monadifyTerm' _ (asPairSelector -> Just (trm, True)) =
do mtrm <- monadifyArg Nothing trm
mtp <- case getMonType mtrm of
MTyPair _ t -> return t
_ -> fail "Monadification failed: projection on term of non-pair type"
return $ fromArgTerm mtp $
pairRightOpenTerm $ toArgTerm mtrm
monadifyTerm' _ (asRecordSelector -> Just (trm, fld)) =
do mtrm <- monadifyArg Nothing trm
mtp <- case getMonType mtrm of
MTyRecord mtps | Just mtp <- lookup fld mtps -> return mtp
_ -> fail ("Monadification failed: " ++
"record projection on term of incorrect type")
return $ fromArgTerm mtp $ projRecordOpenTerm (toArgTerm mtrm) fld
monadifyTerm' _ (asLocalVar -> Just ix) =
(monStCtx <$> ask) >>= \case
ctx | ix >= length ctx -> fail "Monadification failed: vaiable out of scope!"
ctx | (_,_,Right mtrm) <- ctx !! ix -> return mtrm
_ -> fail "Monadification failed: type variable used in term position!"
monadifyTerm' _ (asCtor -> Just (pn, args)) =
monadifyApply (ArgMonTerm $ mkCtorArgMonTerm pn) args
monadifyTerm' _ (asApplyAll -> (asTypedGlobalDef -> Just glob, args)) =
(Map.lookup (globalDefName glob) <$> monStEnv <$> ask) >>= \case
Just macro ->
do let (macro_args, reg_args) = splitAt (macroNumArgs macro) args
mtrm_f <- macroApply macro glob macro_args
monadifyApply mtrm_f reg_args
Nothing -> error ("Monadification failed: unhandled constant: "
++ globalDefString glob)
monadifyTerm' _ (asApp -> Just (f, arg)) =
do mtrm_f <- monadifyTerm Nothing f
monadifyApply mtrm_f [arg]
monadifyTerm' _ t =
(monStCtx <$> ask) >>= \ctx ->
fail ("Monadifiction failed: no case for term: " ++ ppTermInMonCtx ctx t)
-- | Monadify the application of a monadified term to a list of terms, using the
-- type of the already monadified to monadify the arguments
monadifyApply :: MonTerm -> [Term] -> MonadifyM MonTerm
monadifyApply f (t : ts)
| MTyArrow tp_in _ <- getMonType f =
do mtrm <- monadifyArg (Just tp_in) t
monadifyApply (applyMonTerm f (Right mtrm)) ts
monadifyApply f (t : ts)
| MTyForall _ _ _ <- getMonType f =
do mtp <- monadifyTypeM t
monadifyApply (applyMonTerm f (Left mtp)) ts
monadifyApply _ (_:_) = fail "monadifyApply: application at incorrect type"
monadifyApply f [] = return f
-- | FIXME: documentation; get our type down to a base type before going into
-- the MonadifyM monad
monadifyLambdas :: MonadifyEnv -> MonadifyCtx -> MonType -> Term -> MonTerm
monadifyLambdas env ctx (MTyForall _ k tp_f) (asLambda ->
Just (x, x_tp, body)) =
-- FIXME: check that monadifyKind x_tp == k
ArgMonTerm $ ForallMonTerm x k $ \mtp ->
monadifyLambdas env ((x,x_tp,Left mtp) : ctx) (tp_f mtp) body
monadifyLambdas env ctx (MTyArrow tp_in tp_out) (asLambda ->
Just (x, x_tp, body)) =
-- FIXME: check that monadifyType x_tp == tp_in
ArgMonTerm $ FunMonTerm x tp_in tp_out $ \arg ->
monadifyLambdas env ((x,x_tp,Right (ArgMonTerm arg)) : ctx) tp_out body
monadifyLambdas env ctx tp t =
monadifyEtaExpand env ctx tp tp t []
-- | FIXME: documentation
monadifyEtaExpand :: MonadifyEnv -> MonadifyCtx -> MonType -> MonType -> Term ->
[Either MonType ArgMonTerm] -> MonTerm
monadifyEtaExpand env ctx top_mtp (MTyForall x k tp_f) t args =
ArgMonTerm $ ForallMonTerm x k $ \mtp ->
monadifyEtaExpand env ctx top_mtp (tp_f mtp) t (args ++ [Left mtp])
monadifyEtaExpand env ctx top_mtp (MTyArrow tp_in tp_out) t args =
ArgMonTerm $ FunMonTerm "_" tp_in tp_out $ \arg ->
monadifyEtaExpand env ctx top_mtp tp_out t (args ++ [Right arg])
monadifyEtaExpand env ctx top_mtp mtp t args =
applyMonTermMulti
(runMonadifyM env ctx (toArgType mtp) (monadifyTerm (Just top_mtp) t))
args
----------------------------------------------------------------------
-- * Handling the Primitives
----------------------------------------------------------------------
-- | The macro for unsafeAssert, which checks the type of the objects being
-- compared and dispatches to the proper comparison function
unsafeAssertMacro :: MonMacro
unsafeAssertMacro = MonMacro 1 $ \_ ts ->
let numFunType =
MTyForall "n" (MKType $ mkSort 0) $ \n ->
MTyForall "m" (MKType $ mkSort 0) $ \m ->
MTyBase (MKType $ mkSort 0) $
dataTypeOpenTerm "Prelude.Eq"
[dataTypeOpenTerm "Cryptol.Num" [],
toArgType n, toArgType m] in
case ts of
[(asDataType -> Just (num, []))]
| primName num == "Cryptol.Num" ->
return $ ArgMonTerm $
mkGlobalArgMonTerm numFunType "CryptolM.numAssertEqM"
_ ->
fail "Monadification failed: unsafeAssert applied to non-Num type"
-- | The macro for if-then-else, which contains any binds in a branch to that
-- branch
iteMacro :: MonMacro
iteMacro = MonMacro 4 $ \_ args ->
do let (tp, cond, branch1, branch2) =
case args of
[t1, t2, t3, t4] -> (t1, t2, t3, t4)
_ -> error "iteMacro: wrong number of arguments!"
atrm_cond <- monadifyArg (Just boolMonType) cond
mtp <- monadifyTypeM tp
mtrm1 <- resetMonadifyM (toArgType mtp) $ monadifyTerm (Just mtp) branch1
mtrm2 <- resetMonadifyM (toArgType mtp) $ monadifyTerm (Just mtp) branch2
case (mtrm1, mtrm2) of
(ArgMonTerm atrm1, ArgMonTerm atrm2) ->
return $ fromArgTerm mtp $
applyOpenTermMulti (globalOpenTerm "Prelude.ite")
[toArgType mtp, toArgTerm atrm_cond, toArgTerm atrm1, toArgTerm atrm2]
_ ->
return $ fromCompTerm mtp $
applyOpenTermMulti (globalOpenTerm "Prelude.ite")
[toCompType mtp, toArgTerm atrm_cond,
toCompTerm mtrm1, toCompTerm mtrm2]
-- | Make a 'MonMacro' that maps a named global whose first argument is @n:Num@
-- to a global of semi-pure type that takes an additional argument of type
-- @isFinite n@
fin1Macro :: Ident -> Ident -> MonMacro
fin1Macro from to =
MonMacro 1 $ \glob args ->
do if globalDefName glob == ModuleIdentifier from && length args == 1 then
return ()
else error ("Monadification macro for " ++ show from ++
" applied incorrectly")
-- Monadify the first arg, n, and build a proof it is finite
n_mtp <- monadifyTypeM (head args)
let n = toArgType n_mtp
fin_pf <- assertIsFinite n_mtp
-- Apply the type of @glob@ to n, and apply @to@ to n and fin_pf
let glob_tp = monadifyType [] $ globalDefType glob
let glob_tp_app = applyMonType glob_tp $ Left n_mtp
let to_app = applyOpenTermMulti (globalOpenTerm to) [n, toArgTerm fin_pf]
-- Finally, return @to n fin_pf@ as a MonTerm of monadified type @to_tp n@
return $ ArgMonTerm $ fromSemiPureTerm glob_tp_app to_app
-- | Helper function: build a @LetRecType@ for a nested pi type
lrtFromMonType :: MonType -> OpenTerm
lrtFromMonType (MTyForall x k body_f) =
ctorOpenTerm "Prelude.LRT_Fun"
[monKindOpenTerm k,
lambdaOpenTerm x (monKindOpenTerm k) (\tp -> lrtFromMonType $
body_f $ MTyBase k tp)]
lrtFromMonType (MTyArrow mtp1 mtp2) =
ctorOpenTerm "Prelude.LRT_Fun"
[toArgType mtp1,
lambdaOpenTerm "_" (toArgType mtp1) (\_ -> lrtFromMonType mtp2)]
lrtFromMonType mtp =
ctorOpenTerm "Prelude.LRT_Ret" [toArgType mtp]
-- | The macro for fix
--
-- FIXME: does not yet handle mutual recursion
fixMacro :: MonMacro
fixMacro = MonMacro 2 $ \_ args -> case args of
[tp@(asPi -> Just _), f] ->
do mtp <- monadifyTypeM tp
amtrm_f <- monadifyArg (Just $ MTyArrow mtp mtp) f
return $ fromCompTerm mtp $
applyOpenTermMulti (globalOpenTerm "Prelude.multiArgFixM")
[lrtFromMonType mtp, toCompTerm amtrm_f]
[(asRecordType -> Just _), _] ->
fail "Monadification failed: cannot yet handle mutual recursion"
_ -> error "fixMacro: malformed arguments!"
-- | A "macro mapping" maps a single pure identifier to a 'MonMacro' for it
type MacroMapping = (NameInfo, MonMacro)
-- | Build a 'MacroMapping' for an identifier to a semi-pure named function
mmSemiPure :: Ident -> Ident -> MacroMapping
mmSemiPure from_id to_id =
(ModuleIdentifier from_id, semiPureGlobalMacro from_id to_id)
-- | Build a 'MacroMapping' for an identifier to a semi-pure named function
-- whose first argument is a @Num@ that requires an @isFinite@ proof
mmSemiPureFin1 :: Ident -> Ident -> MacroMapping
mmSemiPureFin1 from_id to_id =
(ModuleIdentifier from_id, fin1Macro from_id to_id)
-- | Build a 'MacroMapping' for an identifier to itself as a semi-pure function
mmSelf :: Ident -> MacroMapping
mmSelf self_id =
(ModuleIdentifier self_id, semiPureGlobalMacro self_id self_id)
-- | Build a 'MacroMapping' from an identifier to a function of argument type
mmArg :: Ident -> Ident -> MacroMapping
mmArg from_id to_id = (ModuleIdentifier from_id,
argGlobalMacro (ModuleIdentifier from_id) to_id)
-- | Build a 'MacroMapping' from an identifier and a custom 'MonMacro'
mmCustom :: Ident -> MonMacro -> MacroMapping
mmCustom from_id macro = (ModuleIdentifier from_id, macro)
-- | The default monadification environment
defaultMonEnv :: MonadifyEnv
defaultMonEnv =
Map.fromList
[
-- Prelude functions
mmCustom "Prelude.unsafeAssert" unsafeAssertMacro
, mmCustom "Prelude.ite" iteMacro
, mmCustom "Prelude.fix" fixMacro
-- Top-level sequence functions
, mmArg "Cryptol.seqMap" "CryptolM.seqMapM"
, mmSemiPure "Cryptol.seq_cong1" "CryptolM.mseq_cong1"
, mmArg "Cryptol.eListSel" "CryptolM.eListSelM"
-- List comprehensions
, mmArg "Cryptol.from" "CryptolM.fromM"
-- FIXME: continue here...
-- PEq constraints
, mmSemiPureFin1 "Cryptol.PEqSeq" "CryptolM.PEqMSeq"
, mmSemiPureFin1 "Cryptol.PEqSeqBool" "CryptolM.PEqMSeqBool"
-- PCmp constraints
, mmSemiPureFin1 "Cryptol.PCmpSeq" "CryptolM.PCmpMSeq"
, mmSemiPureFin1 "Cryptol.PCmpSeqBool" "CryptolM.PCmpMSeqBool"
-- PSignedCmp constraints
, mmSemiPureFin1 "Cryptol.PSignedCmpSeq" "CryptolM.PSignedCmpMSeq"
, mmSemiPureFin1 "Cryptol.PSignedCmpSeqBool" "CryptolM.PSignedCmpMSeqBool"
-- PZero constraints
, mmSemiPureFin1 "Cryptol.PZeroSeq" "CryptolM.PZeroMSeq"
-- PLogic constraints
, mmSemiPure "Cryptol.PLogicSeq" "CryptolM.PLogicMSeq"
, mmSemiPureFin1 "Cryptol.PLogicSeqBool" "CryptolM.PLogicMSeqBool"
-- PRing constraints
, mmSemiPure "Cryptol.PRingSeq" "CryptolM.PRingMSeq"
, mmSemiPureFin1 "Cryptol.PRingSeqBool" "CryptolM.PRingMSeqBool"
-- PIntegral constraints
, mmSemiPureFin1 "Cryptol.PIntegeralSeqBool" "CryptolM.PIntegeralMSeqBool"
-- PLiteral constraints
, mmSemiPureFin1 "Cryptol.PLiteralSeqBool" "CryptolM.PLiteralSeqBoolM"
-- The Cryptol Literal primitives
, mmSelf "Cryptol.ecNumber"
, mmSelf "Cryptol.ecFromZ"
-- The Ring primitives
, mmSelf "Cryptol.ecPlus"
, mmSelf "Cryptol.ecMinus"
, mmSelf "Cryptol.ecMul"
, mmSelf "Cryptol.ecNeg"
, mmSelf "Cryptol.ecToInteger"
-- The comparison primitives
, mmSelf "Cryptol.ecEq"
, mmSelf "Cryptol.ecNotEq"
, mmSelf "Cryptol.ecLt"
, mmSelf "Cryptol.ecLtEq"
, mmSelf "Cryptol.ecGt"
, mmSelf "Cryptol.ecGtEq"
-- Sequences
, mmSemiPure "Cryptol.ecShiftL" "CryptolM.ecShiftLM"
, mmSemiPure "Cryptol.ecShiftR" "CryptolM.ecShiftRM"
, mmSemiPure "Cryptol.ecSShiftR" "CryptolM.ecSShiftRM"
, mmSemiPureFin1 "Cryptol.ecRotL" "CryptolM.ecRotLM"
, mmSemiPureFin1 "Cryptol.ecRotR" "CryptolM.ecRotRM"
, mmSemiPureFin1 "Cryptol.ecCat" "CryptolM.ecCatM"
, mmSemiPure "Cryptol.ecTake" "CryptolM.ecTakeM"
, mmSemiPureFin1 "Cryptol.ecDrop" "CryptolM.ecDropM"
, mmSemiPure "Cryptol.ecJoin" "CryptolM.ecJoinM"
, mmSemiPure "Cryptol.ecSplit" "CryptolM.ecSplitM"
, mmSemiPureFin1 "Cryptol.ecReverse" "CryptolM.ecReverseM"
, mmSemiPure "Cryptol.ecTranspose" "CryptolM.ecTransposeM"
, mmArg "Cryptol.ecAt" "CryptolM.ecAtM"
-- , mmArgFin1 "Cryptol.ecAtBack" "CryptolM.ecAtBackM"
-- , mmSemiPureFin2 "Cryptol.ecFromTo" "CryptolM.ecFromToM"
, mmSemiPureFin1 "Cryptol.ecFromToLessThan" "CryptolM.ecFromToLessThanM"
-- , mmSemiPureNthFin 5 "Cryptol.ecFromThenTo" "CryptolM.ecFromThenToM"
, mmSemiPure "Cryptol.ecInfFrom" "CryptolM.ecInfFromM"
, mmSemiPure "Cryptol.ecInfFromThen" "CryptolM.ecInfFromThenM"
, mmArg "Cryptol.ecError" "CryptolM.ecErrorM"
]
----------------------------------------------------------------------
-- * Top-Level Entrypoints
----------------------------------------------------------------------
-- | Ensure that the @CryptolM@ module is loaded
ensureCryptolMLoaded :: SharedContext -> IO ()
ensureCryptolMLoaded sc =
scModuleIsLoaded sc (mkModuleName ["CryptolM"]) >>= \is_loaded ->
if is_loaded then return () else
scLoadCryptolMModule sc
-- | Monadify a type to its argument type and complete it to a 'Term'
monadifyCompleteArgType :: SharedContext -> Term -> IO Term
monadifyCompleteArgType sc tp =
completeOpenTerm sc $ monadifyTypeArgType [] tp
-- | Monadify a term of the specified type to a 'MonTerm' and then complete that
-- 'MonTerm' to a SAW core 'Term', or 'fail' if this is not possible
monadifyCompleteTerm :: SharedContext -> MonadifyEnv -> Term -> Term -> IO Term
monadifyCompleteTerm sc env trm tp =
runCompleteMonadifyM sc env tp $
monadifyTerm (Just $ monadifyType [] tp) trm
-- | Convert a name of a definition to the name of its monadified version
monadifyName :: NameInfo -> IO NameInfo
monadifyName (ModuleIdentifier ident) =
return $ ModuleIdentifier $ mkIdent (identModule ident) $
T.append (identBaseName ident) (T.pack "M")
monadifyName (ImportedName uri _) =
do frag <- URI.mkFragment (T.pack "M")
return $ ImportedName (uri { URI.uriFragment = Just frag }) []
-- | Monadify a 'Term' of the specified type with an optional body, bind the
-- result to a fresh SAW core constant generated from the supplied name, and
-- then convert that constant back to a 'MonTerm'
monadifyNamedTerm :: SharedContext -> MonadifyEnv ->
NameInfo -> Maybe Term -> Term -> IO MonTerm
monadifyNamedTerm sc env nmi maybe_trm tp =
trace ("Monadifying " ++ T.unpack (toAbsoluteName nmi)) $
do let mtp = monadifyType [] tp
nmi' <- monadifyName nmi
comp_tp <- completeOpenTerm sc $ toCompType mtp
const_trm <-
case maybe_trm of
Just trm ->
do trm' <- monadifyCompleteTerm sc env trm tp
scConstant' sc nmi' trm' comp_tp
Nothing -> scOpaqueConstant sc nmi' tp
return $ fromCompTerm mtp $ closedOpenTerm const_trm
-- | Monadify a term with the specified type along with all constants it
-- contains, adding the monadifications of those constants to the monadification
-- environment
monadifyTermInEnv :: SharedContext -> MonadifyEnv -> Term -> Term ->
IO (Term, MonadifyEnv)
monadifyTermInEnv sc top_env top_trm top_tp =
flip runStateT top_env $
do lift $ ensureCryptolMLoaded sc
let const_infos =
map snd $ Map.toAscList $ getConstantSet top_trm
forM_ const_infos $ \(nmi,tp,maybe_body) ->
get >>= \env ->
if Map.member nmi env then return () else
do mtrm <- lift $ monadifyNamedTerm sc env nmi maybe_body tp
put $ Map.insert nmi (monMacro0 mtrm) env
env <- get
lift $ monadifyCompleteTerm sc env top_trm top_tp
|
GaloisInc/saw-script
|
cryptol-saw-core/src/Verifier/SAW/Cryptol/Monadify.hs
|
Haskell
|
bsd-3-clause
| 48,330
|
module HEP.Data.LHEF.Type where
import Data.IntMap (IntMap)
import HEP.Kinematics (HasFourMomentum (..))
import HEP.Kinematics.Vector.LorentzVector (setXYZT)
data EventInfo = EventInfo
{ nup :: Int -- ^ Number of particle entries in the event.
, idprup :: Int -- ^ ID of the process for the event.
, xwgtup :: Double -- ^ Event weight.
, scalup :: Double -- ^ Scale of the event in GeV.
, aqedup :: Double -- ^ The QED coupling \alpha_{QED} used for the event.
, aqcdup :: Double -- ^ The QCD coupling \alpha_{QCD} used for the event.
} deriving Show
data Particle = Particle
{ -- | Particle ID according to Particle Data Group convention.
idup :: Int
-- | Status code.
, istup :: Int
-- | Index of first and last mother.
, mothup :: (Int, Int)
-- | Integer tag for the color flow line passing through the
-- (anti-)color of the particle.
, icolup :: (Int, Int)
-- | Lab frame momentum (P_x, P_y, P_z, E, M) of particle in GeV.
, pup :: (Double, Double, Double, Double, Double)
-- | Invariant lifetime (distance from production to decay) in mm.
, vtimup :: Double
-- | Consine of the angle between the spin-vector of particle and
-- the three-momentum of the decaying particle, specified in the
-- lab frame.
, spinup :: Double
} deriving Show
instance HasFourMomentum Particle where
fourMomentum Particle { pup = (x, y, z, e, _) } = setXYZT x y z e
{-# INLINE fourMomentum #-}
pt Particle { pup = (x, y, _, _, _) } = sqrt $ x ** 2 + y ** 2
{-# INLINE pt #-}
epxpypz Particle { pup = (x, y, z, e, _) } = (e, x, y, z)
{-# INLINE epxpypz #-}
pxpypz Particle { pup = (x, y, z, _, _) } = (x, y, z)
{-# INLINE pxpypz #-}
pxpy Particle { pup = (x, y, _, _, _) } = (x, y)
{-# INLINE pxpy #-}
px Particle { pup = (x, _, _, _, _) } = x
{-# INLINE px #-}
py Particle { pup = (_, y, _, _, _) } = y
{-# INLINE py #-}
pz Particle { pup = (_, _, z, _, _) } = z
{-# INLINE pz #-}
energy Particle { pup = (_, _, _, e, _) } = e
{-# INLINE energy #-}
type EventEntry = IntMap Particle
type Event = (EventInfo, EventEntry)
newtype ParticleType = ParticleType { getParType :: [Int] } deriving (Show, Eq)
|
cbpark/lhef-tools
|
src/HEP/Data/LHEF/Type.hs
|
Haskell
|
bsd-3-clause
| 2,679
|
{-# LANGUAGE QuasiQuotes, TypeFamilies #-}
import Prelude hiding (product, sum)
import Text.Papillon
import Data.Char
import System.Environment
main :: IO ()
main = do
arg : _ <- getArgs
case expr $ parse arg of
Right (r, _) -> print r
Left _ -> putStrLn "parse error"
[papillon|
value :: Int
= ds:(d:[isDigit d] { d })+ { read ds }
/ '(' e:expr ')' { e }
;
product :: Int
= v0:value ops:(op:('*' { (*) } / '/' { div }) v:value { (`op` v) })*
{ foldl (flip ($)) v0 ops }
;
expr :: Int
= p0:product ops:(op:('+' { (+) } / '-' { (-) }) p:product { (`op` p) })*
{ foldl (flip ($)) p0 ops }
;
|]
|
YoshikuniJujo/papillon
|
examples/arith_old.hs
|
Haskell
|
bsd-3-clause
| 618
|
{-# LANGUAGE TypeFamilies #-}
module Network.EasyBitcoin.Internal.Transaction
where
import Network.EasyBitcoin.Internal.Words
import Network.EasyBitcoin.Internal.Base58 ( encodeBase58
, decodeBase58
, addRedundancy
, liftRedundacy
)
import Network.EasyBitcoin.Internal.ByteString
import Network.EasyBitcoin.Internal.InstanciationHelpers
import Network.EasyBitcoin.Internal.Signatures
import Network.EasyBitcoin.Keys
import Network.EasyBitcoin.BitcoinUnits
import Network.EasyBitcoin.Address
import Network.EasyBitcoin.Internal.Script
import Network.EasyBitcoin.Internal.InstanciationHelpers
import Network.EasyBitcoin.Internal.HashFunctions
import Data.Bits (testBit, clearBit, setBit)
import Control.Applicative
import Control.Monad(replicateM,forM_)
import qualified Data.ByteString as BS
import Data.Char
import Data.Binary
import Data.Aeson(ToJSON(..),FromJSON(..))
import Data.Binary.Get ( getWord64be
, getWord32be
, getWord64le
, getWord8
, getWord16le
, getWord32le
, getByteString
, Get
)
import Data.Binary.Put( putWord64be
, putWord32be
, putWord32le
, putWord64le
, putWord16le
, putWord8
, putByteString
)
import Data.Maybe(fromMaybe)
--------------------------------------------------------------------------------
-- | Bitcoin transaction.
-- When parsed, only syntax validation is performanced, particulary, signature validation is not.
data Tx net = Tx { txVersion :: Int -- !Word32
, txIn :: [TxIn]
, txOut :: [TxOut]
, txLockTime :: Int -- Either a b -- Word32
} deriving (Eq)
data TxIn = TxIn { prevOutput :: Outpoint -- ^ Reference the previous transaction output (hash + position)
, scriptInput :: Script
, txInSequence :: Int
} deriving (Show,Eq)
data TxOut = TxOut { outValue :: Int -- Word64 -- change to ¿BTC?
, scriptOutput :: Script
} deriving (Show,Eq)
instance Binary (Tx net) where
get = Tx <$> (fmap fromIntegral getWord32le)
<*> (replicateList =<< get)
<*> (replicateList =<< get)
<*> (fmap fromIntegral getWord32le)
where
replicateList (VarInt c) = replicateM (fromIntegral c) get
put (Tx v is os l) = do putWord32le (fromIntegral v)
put $ VarInt $ fromIntegral $ length is
forM_ is put
put $ VarInt $ fromIntegral $ length os
forM_ os put
putWord32le (fromIntegral l)
instance Binary TxOut where
get = do val <- getWord64le
VarInt len <- get
raw_script <- getByteString $ fromIntegral len
case decodeToMaybe raw_script of
Just script -> return$TxOut (fromIntegral val) script
_ -> fail "could not decode the pub-script"
put (TxOut o s) = do putWord64le (fromIntegral o)
let s_ = encode' s
put $ VarInt $ BS.length s_
putByteString s_
instance Binary TxIn where
get = do outpoint <- get
VarInt len <- get
raw_script <- getByteString $ fromIntegral len
val <- getWord32le
case decodeToMaybe raw_script of
Just script -> return$TxIn outpoint script (fromIntegral val)
_ -> fail "could not decode the sig-script"
put (TxIn o s q) = do put o
let s_ = encode' s
put $ VarInt $ BS.length s_
putByteString s_
putWord32le (fromIntegral q)
-- | Represents a reference to a transaction output, that is, a transaction hash ('Txid') plus the output position
-- within the output vector of the referenced transaction.
data Outpoint = Outpoint Txid Int deriving (Eq,Show,Ord,Read)
-- | A transaction identification as a hash of the transaction. 2 transaction are consider different if they have different
-- 'Txid's. In some cases, it might be possible for a peer to modify a transaction into an equivalent one having a different
-- 'Txid', for futher info read about the "transaction-malleability-issue".
--------------------------------------------------------------------------------------------------------------------------------------
-- | A transaction hash used to indentify a transaction. Notice that due to the "transaction-malleability-issue", it is possible for an adversary,
-- to derivated a new equivalent transaction with a different Txid.
data Txid = Txid{ txidHash :: Word256} deriving (Eq,Ord)
-- | Compute the 'Txid' of a given transaction.
txid:: Tx net -> Txid
txid = Txid . fromIntegral . doubleHash256 . encode'
instance Show (Txid) where
show (Txid x) = bsToHex . BS.reverse $ encode' x
instance Read Txid where
readsPrec _ str = case readsPrec__ str of
( Just result, rest) -> [(result,rest)]
_ -> []
where
readsPrec__ str = let (word , rest) = span (not.isSpace)$ dropWhile isSpace str
in (fmap Txid . decodeToMaybe . BS.reverse =<< hexToBS word ,rest)
instance Binary Txid where
get = Txid <$> get
put = put . txidHash
instance ToJSON Txid where
toJSON = toJSON.show
instance ToJSON (Tx net) where
toJSON = toJSON.show
instance Binary Outpoint where
get = Outpoint <$> get <*> (fromIntegral<$>getWord32le)
put (Outpoint h i) = put h >> putWord32le (fromIntegral i)
instance Show (Tx net) where
show = showAsBinary
instance Read (Tx net) where
readsPrec = readsPrecAsBinary
---------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------
---------------------------------------------------------------------------------
-- Todo, create here the function "signatureOfTransaction..." so it does not need to export txSigHash
txSigHash :: Tx net -- ^ Transaction to sign.
-> Script -- ^ Output script that is being spent.
-> Int -- ^ Index of the input that is being signed.
-> SigHash -- ^ What parts of the transaction should be signed.
-> Word256 -- ^ Result hash to be signed.
txSigHash tx out i sh = do let newIn = buildInputs (txIn tx) out i sh
fromMaybe (setBit 0 248) -- When SigSingle and input index > outputs, then sign integer 1
$ do newOut <- buildOutputs (txOut tx) i sh
let newTx = tx{ txIn = newIn, txOut = newOut }
return $ doubleHash256 $ encode' newTx `BS.append` encodeSigHash32 sh
-- error $ (bsToHex $ encode' newTx) -- `BS.append` encodeSigHash32 sh)
-- ++ " ------------------------ " ++
-- (bsToHex.encode'.doubleHash256 $ encode' newTx `BS.append` encodeSigHash32 sh)
-- Builds transaction inputs for computing SigHashes
buildInputs :: [TxIn] -> Script -> Int -> SigHash -> [TxIn]
buildInputs txins out i sh
| anyoneCanPay sh = [ (txins !! i) { scriptInput = out } ]
| isSigAll sh || isSigUnknown sh = single
| otherwise = map noSeq $ zip single [0..]
where
empty = map (\ti -> ti{ scriptInput = Script [] }) txins
single = updateIndex i empty $ \ti -> ti{ scriptInput = out }
noSeq (ti,j)
| i == j = ti
| otherwise = ti{ txInSequence = 0 }
-- Build transaction outputs for computing SigHashes
buildOutputs :: [TxOut] -> Int -> SigHash -> Maybe [TxOut]
buildOutputs txos i sh
| isSigAll sh || isSigUnknown sh = return txos
| isSigNone sh = return []
| i >= length txos = Nothing
| otherwise = return $ buffer ++ [txos !! i]
where
buffer = replicate i $ TxOut (-1) (Script [])
updateIndex::Int -> [a] -> (a->a) -> [a]
updateIndex i xs f
| i < 0 || i >= length xs = xs
| otherwise = l ++ (f h : r)
where
(l,h:r) = splitAt i xs
-- | Encodes a 'SigHash' to a 32 bit-long bytestring.
encodeSigHash32 :: SigHash -> BS.ByteString
encodeSigHash32 sh = encode' sh `BS.append` BS.pack [0,0,0]
------------------------------------------------------------------------------------------------------
data SigHash = SigAll { anyoneCanPay :: !Bool }
| SigNone { anyoneCanPay :: !Bool }
| SigSingle { anyoneCanPay :: !Bool }
| SigUnknown { anyoneCanPay :: !Bool
, getSigCode :: !Word8
}
deriving (Eq, Show, Read)
data TxSignature = TxSignature { txSignature :: !Signature
, sigHashType :: !SigHash
} deriving (Eq, Show, Read)
instance Binary TxSignature where
put (TxSignature sig sh) = put sig >> put sh
get = TxSignature <$> get <*> get
instance Binary SigHash where
get = do w <- getWord8
let acp = testBit w 7
return $ case clearBit w 7 of
1 -> SigAll acp
2 -> SigNone acp
3 -> SigSingle acp
_ -> SigUnknown acp w
put sh = putWord8 $ case sh of
SigAll acp
| acp -> 0x81
| otherwise -> 0x01
SigNone acp
| acp -> 0x82
| otherwise -> 0x02
SigSingle acp
| acp -> 0x83
| otherwise -> 0x03
SigUnknown _ w -> w
-------------------------------------------------------------------------------------------------------
-- Returns True if the 'SigHash' has the value SigAll.
isSigAll :: SigHash -> Bool
isSigAll sh = case sh of
SigAll _ -> True
_ -> False
-- Returns True if the 'SigHash' has the value SigNone.
isSigNone :: SigHash -> Bool
isSigNone sh = case sh of
SigNone _ -> True
_ -> False
-- Returns True if the 'SigHash' has the value SigSingle.
isSigSingle :: SigHash -> Bool
isSigSingle sh = case sh of
SigSingle _ -> True
_ -> False
-- Returns True if the 'SigHash' has the value SigUnknown.
isSigUnknown :: SigHash -> Bool
isSigUnknown sh = case sh of
SigUnknown _ _ -> True
_ -> False
|
vwwv/easy-bitcoin
|
Network/EasyBitcoin/Internal/Transaction.hs
|
Haskell
|
bsd-3-clause
| 12,007
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Numeric.Units.Dimensional.DK.HaTeX
where
import Text.LaTeX.Base
import Numeric.Units.Dimensional.DK
instance (Texy v, KnownDimension d, Fractional v) => Texy (Quantity d v) where
texy val = texy (val /~ siUnit)
|
bjornbm/dimensional-dk-experimental
|
src/Numeric/Units/Dimensional/DK/HaTeX.hs
|
Haskell
|
bsd-3-clause
| 332
|
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
module FunPtr where
import Ivory.Compile.C.CmdlineFrontend
import Ivory.Language
f :: Def ('[Sint32] :-> Sint32)
f = proc "f" (\ n -> body (ret (n + 1)))
invoke :: Def ('[ ProcPtr ('[Sint32] :-> Sint32), Sint32] :-> Sint32)
invoke = proc "invoke" (\ k n -> body (ret =<< indirect k n))
test :: Def ('[] :-> Sint32)
test = proc "fun_ptr_test" (body (ret =<< call invoke (procPtr f) 10))
runFunPtr :: IO ()
runFunPtr = runCompiler [cmodule] [] initialOpts { outDir = Nothing }
cmodule :: Module
cmodule = package "FunPtr" $ do
incl f
incl test
incl invoke
|
Hodapp87/ivory
|
ivory-examples/examples/FunPtr.hs
|
Haskell
|
bsd-3-clause
| 628
|
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Type alias for case insensitive strict text.
-- Copyright: (c) 2014 Peter Trsko
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: NoImplicitPrelude
--
-- Type alias for case insensitive strict text.
module Skeletos.Type.CIText (CIText)
where
import Data.CaseInsensitive (CI)
import qualified Data.Text as Strict (Text)
-- | Case insensitive strict 'Strict.Text'.
type CIText = CI Strict.Text
|
trskop/skeletos
|
src/Skeletos/Type/CIText.hs
|
Haskell
|
bsd-3-clause
| 544
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.SGIX.BlendAlphaMinmax
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/SGIX/blend_alpha_minmax.txt SGIX_blend_alpha_minmax> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.SGIX.BlendAlphaMinmax (
-- * Enums
gl_ALPHA_MAX_SGIX,
gl_ALPHA_MIN_SGIX
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/SGIX/BlendAlphaMinmax.hs
|
Haskell
|
bsd-3-clause
| 689
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
DeriveDataTypeable, TypeSynonymInstances, PatternGuards #-}
module Idris.AbsSyntaxTree where
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Typecheck
import Idris.Docstrings
import IRTS.Lang
import IRTS.CodegenCommon
import Util.Pretty
import Util.DynamicLinker
import Idris.Colours
import System.Console.Haskeline
import System.IO
import Prelude hiding ((<$>))
import Control.Applicative ((<|>))
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Except
import qualified Control.Monad.Trans.Class as Trans (lift)
import Data.Data (Data)
import Data.Function (on)
import Data.Generics.Uniplate.Data (universe)
import Data.List hiding (group)
import Data.Char
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import Data.Either
import qualified Data.Set as S
import Data.Word (Word)
import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
import Data.Traversable (Traversable)
import Data.Typeable
import Data.Foldable (Foldable)
import Debug.Trace
import Text.PrettyPrint.Annotated.Leijen
data ElabWhat = ETypes | EDefns | EAll
deriving (Show, Eq)
-- Data to pass to recursively called elaborators; e.g. for where blocks,
-- paramaterised declarations, etc.
-- rec_elabDecl is used to pass the top level elaborator into other elaborators,
-- so that we can have mutually recursive elaborators in separate modules without
-- having to muck about with cyclic modules.
data ElabInfo = EInfo { params :: [(Name, PTerm)],
inblock :: Ctxt [Name], -- names in the block, and their params
liftname :: Name -> Name,
namespace :: Maybe [String],
elabFC :: Maybe FC,
rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl ->
Idris () }
toplevel :: ElabInfo
toplevel = EInfo [] emptyContext id Nothing Nothing (\_ _ _ -> fail "Not implemented")
eInfoNames :: ElabInfo -> [Name]
eInfoNames info = map fst (params info) ++ M.keys (inblock info)
data IOption = IOption { opt_logLevel :: Int,
opt_typecase :: Bool,
opt_typeintype :: Bool,
opt_coverage :: Bool,
opt_showimp :: Bool, -- ^^ show implicits
opt_errContext :: Bool,
opt_repl :: Bool,
opt_verbose :: Bool,
opt_nobanner :: Bool,
opt_quiet :: Bool,
opt_codegen :: Codegen,
opt_outputTy :: OutputType,
opt_ibcsubdir :: FilePath,
opt_importdirs :: [FilePath],
opt_triple :: String,
opt_cpu :: String,
opt_cmdline :: [Opt], -- remember whole command line
opt_origerr :: Bool,
opt_autoSolve :: Bool, -- ^ automatically apply "solve" tactic in prover
opt_autoImport :: [FilePath], -- ^ e.g. Builtins+Prelude
opt_optimise :: [Optimisation],
opt_printdepth :: Maybe Int,
opt_evaltypes :: Bool -- ^ normalise types in :t
}
deriving (Show, Eq)
defaultOpts = IOption { opt_logLevel = 0
, opt_typecase = False
, opt_typeintype = False
, opt_coverage = True
, opt_showimp = False
, opt_errContext = False
, opt_repl = True
, opt_verbose = True
, opt_nobanner = False
, opt_quiet = False
, opt_codegen = Via "c"
, opt_outputTy = Executable
, opt_ibcsubdir = ""
, opt_importdirs = []
, opt_triple = ""
, opt_cpu = ""
, opt_cmdline = []
, opt_origerr = False
, opt_autoSolve = True
, opt_autoImport = []
, opt_optimise = defaultOptimise
, opt_printdepth = Just 5000
, opt_evaltypes = True
}
data PPOption = PPOption {
ppopt_impl :: Bool -- ^^ whether to show implicits
, ppopt_depth :: Maybe Int
} deriving (Show)
data Optimisation = PETransform -- partial eval and associated transforms
deriving (Show, Eq)
defaultOptimise = [PETransform]
-- | Pretty printing options with default verbosity.
defaultPPOption :: PPOption
defaultPPOption = PPOption { ppopt_impl = False , ppopt_depth = Just 200 }
-- | Pretty printing options with the most verbosity.
verbosePPOption :: PPOption
verbosePPOption = PPOption { ppopt_impl = True, ppopt_depth = Just 200 }
-- | Get pretty printing options from the big options record.
ppOption :: IOption -> PPOption
ppOption opt = PPOption {
ppopt_impl = opt_showimp opt,
ppopt_depth = opt_printdepth opt
}
-- | Get pretty printing options from an idris state record.
ppOptionIst :: IState -> PPOption
ppOptionIst = ppOption . idris_options
data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
-- | The output mode in use
data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle
| IdeMode Integer Handle -- ^ Send IDE output for some request ID to the handle
deriving Show
-- | How wide is the console?
data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
| ColsWide Int -- ^ Manually specified - must be positive
| AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
deriving (Show, Eq)
-- | The global state used in the Idris monad
data IState = IState {
tt_ctxt :: Context, -- ^ All the currently defined names and their terms
idris_constraints :: S.Set ConstraintFC,
-- ^ A list of universe constraints and their corresponding source locations
idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
idris_implicits :: Ctxt [PArg],
idris_statics :: Ctxt [Bool],
idris_classes :: Ctxt ClassInfo,
idris_dsls :: Ctxt DSL,
idris_optimisation :: Ctxt OptInfo,
idris_datatypes :: Ctxt TypeInfo,
idris_namehints :: Ctxt [Name],
idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
-- ^ list of lhs/rhs, and a list of missing clauses
idris_flags :: Ctxt [FnOpt],
idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
idris_calledgraph :: Ctxt [Name],
idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]),
idris_moduledocs :: Ctxt (Docstring DocTerm),
-- ^ module documentation is saved in a special MN so the context
-- mechanism can be used for disambiguation
idris_tyinfodata :: Ctxt TIData,
idris_fninfo :: Ctxt FnInfo,
idris_transforms :: Ctxt [(Term, Term)],
idris_autohints :: Ctxt [Name],
idris_totcheck :: [(FC, Name)], -- names to check totality on
idris_defertotcheck :: [(FC, Name)], -- names to check at the end
idris_totcheckfail :: [(FC, String)],
idris_options :: IOption,
idris_name :: Int,
idris_lineapps :: [((FilePath, Int), PTerm)],
-- ^ Full application LHS on source line
idris_metavars :: [(Name, (Maybe Name, Int, Bool))],
-- ^ The currently defined but not proven metavariables. The Int
-- is the number of vars to display as a context, the Maybe Name
-- is its top-level function, and the Bool is whether :p is
-- allowed
idris_coercions :: [Name],
idris_errRev :: [(Term, Term)],
syntax_rules :: SyntaxRules,
syntax_keywords :: [String],
imported :: [FilePath], -- ^ The imported modules
idris_scprims :: [(Name, (Int, PrimFn))],
idris_objs :: [(Codegen, FilePath)],
idris_libs :: [(Codegen, String)],
idris_cgflags :: [(Codegen, String)],
idris_hdrs :: [(Codegen, String)],
idris_imported :: [(FilePath, Bool)], -- ^ Imported ibc file names, whether public
proof_list :: [(Name, (Bool, [String]))],
errSpan :: Maybe FC,
parserWarnings :: [(FC, Err)],
lastParse :: Maybe Name,
indent_stack :: [Int],
brace_stack :: [Maybe Int],
lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
idris_parsedSpan :: Maybe FC,
hide_list :: [(Name, Maybe Accessibility)],
default_access :: Accessibility,
default_total :: Bool,
ibc_write :: [IBCWrite],
compiled_so :: Maybe String,
idris_dynamic_libs :: [DynamicLib],
idris_language_extensions :: [LanguageExt],
idris_outputmode :: OutputMode,
idris_colourRepl :: Bool,
idris_colourTheme :: ColourTheme,
idris_errorhandlers :: [Name], -- ^ Global error handlers
idris_nameIdx :: (Int, Ctxt (Int, Name)),
idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
module_aliases :: M.Map [T.Text] [T.Text],
idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
idris_postulates :: S.Set Name,
idris_externs :: S.Set (Name, Int),
idris_erasureUsed :: [(Name, Int)], -- ^ Function/constructor name, argument position is used
idris_whocalls :: Maybe (M.Map Name [Name]),
idris_callswho :: Maybe (M.Map Name [Name]),
idris_repl_defs :: [Name], -- ^ List of names that were defined in the repl, and can be re-/un-defined
elab_stack :: [(Name, Bool)], -- ^ Stack of names currently being elaborated, Bool set if it's an instance
-- (instances appear twice; also as a funtion name)
idris_symbols :: M.Map Name Name, -- ^ Symbol table (preserves sharing of names)
idris_exports :: [Name], -- ^ Functions with ExportList
idris_highlightedRegions :: [(FC, OutputAnnotation)], -- ^ Highlighting information to output
idris_parserHighlights :: [(FC, OutputAnnotation)] -- ^ Highlighting information from the parser
}
-- Required for parsers library, and therefore trifecta
instance Show IState where
show = const "{internal state}"
data SizeChange = Smaller | Same | Bigger | Unknown
deriving (Show, Eq)
{-!
deriving instance Binary SizeChange
deriving instance NFData SizeChange
!-}
type SCGEntry = (Name, [Maybe (Int, SizeChange)])
type UsageReason = (Name, Int) -- fn_name, its_arg_number
data CGInfo = CGInfo { argsdef :: [Name],
calls :: [(Name, [[Name]])],
scg :: [SCGEntry],
argsused :: [Name],
usedpos :: [(Int, [UsageReason])] }
deriving Show
{-!
deriving instance Binary CGInfo
deriving instance NFData CGInfo
!-}
primDefs = [sUN "unsafePerformPrimIO",
sUN "mkLazyForeignPrim",
sUN "mkForeignPrim",
sUN "void"]
-- information that needs writing for the current module's .ibc file
data IBCWrite = IBCFix FixDecl
| IBCImp Name
| IBCStatic Name
| IBCClass Name
| IBCInstance Bool Bool Name Name
| IBCDSL Name
| IBCData Name
| IBCOpt Name
| IBCMetavar Name
| IBCSyntax Syntax
| IBCKeyword String
| IBCImport (Bool, FilePath) -- True = import public
| IBCImportDir FilePath
| IBCObj Codegen FilePath
| IBCLib Codegen String
| IBCCGFlag Codegen String
| IBCDyLib String
| IBCHeader Codegen String
| IBCAccess Name Accessibility
| IBCMetaInformation Name MetaInformation
| IBCTotal Name Totality
| IBCFlags Name [FnOpt]
| IBCFnInfo Name FnInfo
| IBCTrans Name (Term, Term)
| IBCErrRev (Term, Term)
| IBCCG Name
| IBCDoc Name
| IBCCoercion Name
| IBCDef Name -- i.e. main context
| IBCNameHint (Name, Name)
| IBCLineApp FilePath Int PTerm
| IBCErrorHandler Name
| IBCFunctionErrorHandler Name Name Name
| IBCPostulate Name
| IBCExtern (Name, Int)
| IBCTotCheckErr FC String
| IBCParsedRegion FC
| IBCModDocs Name -- ^ The name is the special name used to track module docs
| IBCUsage (Name, Int)
| IBCExport Name
| IBCAutoHint Name Name
deriving Show
-- | The initial state for the compiler
idrisInit :: IState
idrisInit = IState initContext S.empty []
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext emptyContext emptyContext
emptyContext emptyContext emptyContext emptyContext
emptyContext
[] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] []
[] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] []
(RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty
AutomaticWidth S.empty S.empty [] Nothing Nothing [] [] M.empty [] [] []
-- | The monad for the main REPL - reading and processing files and updating
-- global state (hence the IO inner monad).
--type Idris = WriterT [Either String (IO ())] (State IState a))
type Idris = StateT IState (ExceptT Err IO)
catchError :: Idris a -> (Err -> Idris a) -> Idris a
catchError = liftCatch catchE
throwError :: Err -> Idris a
throwError = Trans.lift . throwE
-- Commands in the REPL
data Codegen = Via String
-- | ViaC
-- | ViaJava
-- | ViaNode
-- | ViaJavaScript
-- | ViaLLVM
| Bytecode
deriving (Show, Eq)
{-!
deriving instance NFData Codegen
!-}
data HowMuchDocs = FullDocs | OverviewDocs
-- | REPL commands
data Command = Quit
| Help
| Eval PTerm
| NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
| Undefine [Name]
| Check PTerm
| Core PTerm
| DocStr (Either Name Const) HowMuchDocs
| TotCheck Name
| Reload
| Load FilePath (Maybe Int) -- up to maximum line number
| ChangeDirectory FilePath
| ModImport String
| Edit
| Compile Codegen String
| Execute PTerm
| ExecVal PTerm
| Metavars
| Prove Bool Name -- ^ If false, use prover, if true, use elab shell
| AddProof (Maybe Name)
| RmProof Name
| ShowProof Name
| Proofs
| Universes
| LogLvl Int
| Spec PTerm
| WHNF PTerm
| TestInline PTerm
| Defn Name
| Missing Name
| DynamicLink FilePath
| ListDynamic
| Pattelab PTerm
| Search [String] PTerm
| CaseSplitAt Bool Int Name
| AddClauseFrom Bool Int Name
| AddProofClauseFrom Bool Int Name
| AddMissing Bool Int Name
| MakeWith Bool Int Name
| MakeLemma Bool Int Name
| DoProofSearch Bool Bool Int Name [Name]
-- ^ the first bool is whether to update,
-- the second is whether to search recursively (i.e. for the arguments)
| SetOpt Opt
| UnsetOpt Opt
| NOP
| SetColour ColourType IdrisColour
| ColourOn
| ColourOff
| ListErrorHandlers
| SetConsoleWidth ConsoleWidth
| SetPrinterDepth (Maybe Int)
| Apropos [String] String
| WhoCalls Name
| CallsWho Name
| Browse [String]
| MakeDoc String -- IdrisDoc
| Warranty
| PrintDef Name
| PPrint OutputFmt Int PTerm
| TransformInfo Name
-- Debugging commands
| DebugInfo Name
| DebugUnify PTerm PTerm
data OutputFmt = HTMLOutput | LaTeXOutput
data Opt = Filename String
| Quiet
| NoBanner
| ColourREPL Bool
| Idemode
| IdemodeSocket
| ShowLibs
| ShowLibdir
| ShowIncs
| ShowPkgs
| NoBasePkgs
| NoPrelude
| NoBuiltins -- only for the really primitive stuff!
| NoREPL
| OLogging Int
| Output String
| Interface
| TypeCase
| TypeInType
| DefaultTotal
| DefaultPartial
| WarnPartial
| WarnReach
| EvalTypes
| NoCoverage
| ErrContext
| ShowImpl
| Verbose
| Port String -- REPL TCP port
| IBCSubDir String
| ImportDir String
| PkgBuild String
| PkgInstall String
| PkgClean String
| PkgCheck String
| PkgREPL String
| PkgMkDoc String -- IdrisDoc
| PkgTest String
| PkgIndex FilePath
| WarnOnly
| Pkg String
| BCAsm String
| DumpDefun String
| DumpCases String
| UseCodegen Codegen
| CodegenArgs String
| OutputTy OutputType
| Extension LanguageExt
| InterpretScript String
| EvalExpr String
| TargetTriple String
| TargetCPU String
| OptLevel Int
| AddOpt Optimisation
| RemoveOpt Optimisation
| Client String
| ShowOrigErr
| AutoWidth -- ^ Automatically adjust terminal width
| AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
| UseConsoleWidth ConsoleWidth
| DumpHighlights
deriving (Show, Eq)
data ElabShellCmd = EQED | EAbandon | EUndo | EProofState | EProofTerm
| EEval PTerm | ECheck PTerm | ESearch PTerm
| EDocStr (Either Name Const)
deriving (Show, Eq)
-- Parsed declarations
data Fixity = Infixl { prec :: Int }
| Infixr { prec :: Int }
| InfixN { prec :: Int }
| PrefixN { prec :: Int }
deriving Eq
{-!
deriving instance Binary Fixity
deriving instance NFData Fixity
!-}
instance Show Fixity where
show (Infixl i) = "infixl " ++ show i
show (Infixr i) = "infixr " ++ show i
show (InfixN i) = "infix " ++ show i
show (PrefixN i) = "prefix " ++ show i
data FixDecl = Fix Fixity String
deriving Eq
instance Show FixDecl where
show (Fix f s) = show f ++ " " ++ s
{-!
deriving instance Binary FixDecl
deriving instance NFData FixDecl
!-}
instance Ord FixDecl where
compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
data Static = Static | Dynamic
deriving (Show, Eq, Data, Typeable)
{-!
deriving instance Binary Static
deriving instance NFData Static
!-}
-- Mark bindings with their explicitness, and laziness
data Plicity = Imp { pargopts :: [ArgOpt],
pstatic :: Static,
pparam :: Bool,
pscoped :: Maybe ImplicitInfo -- Nothing, if top level
}
| Exp { pargopts :: [ArgOpt],
pstatic :: Static,
pparam :: Bool } -- this is a param (rather than index)
| Constraint { pargopts :: [ArgOpt],
pstatic :: Static }
| TacImp { pargopts :: [ArgOpt],
pstatic :: Static,
pscript :: PTerm }
deriving (Show, Eq, Data, Typeable)
{-!
deriving instance Binary Plicity
deriving instance NFData Plicity
!-}
is_scoped :: Plicity -> Maybe ImplicitInfo
is_scoped (Imp _ _ _ s) = s
is_scoped _ = Nothing
impl = Imp [] Dynamic False Nothing
forall_imp = Imp [] Dynamic False (Just (Impl False))
forall_constraint = Imp [] Dynamic False (Just (Impl True))
expl = Exp [] Dynamic False
expl_param = Exp [] Dynamic True
constraint = Constraint [] Static
tacimpl t = TacImp [] Dynamic t
data FnOpt = Inlinable -- always evaluate when simplifying
| TotalFn | PartialFn | CoveringFn
| Coinductive | AssertTotal
| Dictionary -- type class dictionary, eval only when
-- a function argument, and further evaluation resutls
| Implicit -- implicit coercion
| NoImplicit -- do not apply implicit coercions
| CExport String -- export, with a C name
| ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
| ErrorReverse -- ^^ attempt to reverse normalise before showing in error
| Reflection -- a reflecting function, compile-time only
| Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
| Constructor -- Data constructor type
| AutoHint -- use in auto implicit search
| PEGenerated -- generated by partial evaluator
deriving (Show, Eq)
{-!
deriving instance Binary FnOpt
deriving instance NFData FnOpt
!-}
type FnOpts = [FnOpt]
inlinable :: FnOpts -> Bool
inlinable = elem Inlinable
dictionary :: FnOpts -> Bool
dictionary = elem Dictionary
-- | Type provider - what to provide
data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
| ProvPostulate t -- ^ goal type must be Type, so only term
deriving (Show, Eq, Functor)
type ProvideWhat = ProvideWhat' PTerm
-- | Top-level declarations such as compiler directives, definitions,
-- datatypes and typeclasses.
data PDecl' t
= PFix FC Fixity [String] -- ^ Fixity declaration
| PTy (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC FnOpts Name FC t -- ^ Type declaration (last FC is precise name location)
| PPostulate Bool -- external def if true
(Docstring (Either Err PTerm)) SyntaxInfo FC FC FnOpts Name t -- ^ Postulate, second FC is precise name location
| PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
| PCAF FC Name t -- ^ Top level constant
| PData (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
| PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
| PNamespace String FC [PDecl' t]
-- ^ New namespace, where FC is accurate location of the
-- namespace in the file
| PRecord (Docstring (Either Err PTerm)) SyntaxInfo FC DataOpts
Name -- Record name
FC -- Record name precise location
[(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span
[(Name, Docstring (Either Err PTerm))] -- Param Docs
[((Maybe (Name, FC)), Plicity, t, Maybe (Docstring (Either Err PTerm)))] -- Fields
(Maybe (Name, FC)) -- Optional constructor name and location
(Docstring (Either Err PTerm)) -- Constructor doc
SyntaxInfo -- Constructor SyntaxInfo
-- ^ Record declaration
| PClass (Docstring (Either Err PTerm)) SyntaxInfo FC
[(Name, t)] -- constraints
Name -- class name
FC -- accurate location of class name
[(Name, FC, t)] -- parameters and precise locations
[(Name, Docstring (Either Err PTerm))] -- parameter docstrings
[(Name, FC)] -- determining parameters and precise locations
[PDecl' t] -- declarations
(Maybe (Name, FC)) -- instance constructor name and location
(Docstring (Either Err PTerm)) -- instance constructor docs
-- ^ Type class: arguments are documentation, syntax info, source location, constraints,
-- class name, class name location, parameters, method declarations, optional constructor name
| PInstance
(Docstring (Either Err PTerm)) -- Instance docs
[(Name, Docstring (Either Err PTerm))] -- Parameter docs
SyntaxInfo
FC [(Name, t)] -- constraints
Name -- class
FC -- precise location of class
[t] -- parameters
t -- full instance type
(Maybe Name) -- explicit name
[PDecl' t]
-- ^ Instance declaration: arguments are documentation, syntax info, source
-- location, constraints, class name, parameters, full instance
-- type, optional explicit name, and definitions
| PDSL Name (DSL' t) -- ^ DSL declaration
| PSyntax FC Syntax -- ^ Syntax definition
| PMutual FC [PDecl' t] -- ^ Mutual block
| PDirective Directive -- ^ Compiler directive.
| PProvider (Docstring (Either Err PTerm)) SyntaxInfo FC FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term. The second FC is precise highlighting location.
| PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
-- bool is True, lhs and rhs must be convertible
deriving Functor
{-!
deriving instance Binary PDecl'
deriving instance NFData PDecl'
!-}
-- | The set of source directives
data Directive = DLib Codegen String |
DLink Codegen String |
DFlag Codegen String |
DInclude Codegen String |
DHide Name |
DFreeze Name |
DAccess Accessibility |
DDefault Bool |
DLogging Integer |
DDynamicLibs [String] |
DNameHint Name FC [(Name, FC)] |
DErrorHandlers Name FC Name FC [(Name, FC)] |
DLanguage LanguageExt |
DUsed FC Name Name
-- | A set of instructions for things that need to happen in IState
-- after a term elaboration when there's been reflected elaboration.
data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type
| RClausesInstrs Name [([Name], Term, Term)]
| RAddInstance Name Name
-- | For elaborator state
data EState = EState {
case_decls :: [(Name, PDecl)],
delayed_elab :: [(Int, Elab' EState ())],
new_tyDecls :: [RDeclInstructions],
highlighting :: [(FC, OutputAnnotation)]
}
initEState :: EState
initEState = EState [] [] [] []
type ElabD a = Elab' EState a
highlightSource :: FC -> OutputAnnotation -> ElabD ()
highlightSource fc annot =
updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux })
-- | One clause of a top-level definition. Term arguments to constructors are:
--
-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
--
-- 2. The list of extra 'with' patterns
--
-- 3. The right-hand side
--
-- 4. The where block (PDecl' t)
data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
| PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t]
| PClauseR FC [t] t [PDecl' t]
| PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t]
deriving Functor
{-!
deriving instance Binary PClause'
deriving instance NFData PClause'
!-}
-- | Data declaration
data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
d_name_fc :: FC, -- ^ The precise location of the type constructor name
d_tcon :: t, -- ^ Type constructor
d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors
}
-- ^ Data declaration
| PLaterdecl { d_name :: Name, d_name_fc :: FC, d_tcon :: t }
-- ^ "Placeholder" for data whose constructors are defined later
deriving Functor
{-!
deriving instance Binary PData'
deriving instance NFData PData'
!-}
-- Handy to get a free function for applying PTerm -> PTerm functions
-- across a program, by deriving Functor
type PDecl = PDecl' PTerm
type PData = PData' PTerm
type PClause = PClause' PTerm
-- get all the names declared in a decl
declared :: PDecl -> [Name]
declared (PFix _ _ _) = []
declared (PTy _ _ _ _ _ n fc t) = [n]
declared (PPostulate _ _ _ _ _ _ n t) = [n]
declared (PClauses _ _ n _) = [] -- not a declaration
declared (PCAF _ n _) = [n]
declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
where fstt (_, _, a, _, _, _, _) = a
declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n]
declared (PParams _ _ ds) = concatMap declared ds
declared (PNamespace _ _ ds) = concatMap declared ds
declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms)
declared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
declared (PDSL n _) = [n]
declared (PSyntax _ _) = []
declared (PMutual _ ds) = concatMap declared ds
declared (PDirective _) = []
declared _ = []
-- get the names declared, not counting nested parameter blocks
tldeclared :: PDecl -> [Name]
tldeclared (PFix _ _ _) = []
tldeclared (PTy _ _ _ _ _ n _ t) = [n]
tldeclared (PPostulate _ _ _ _ _ _ n t) = [n]
tldeclared (PClauses _ _ n _) = [] -- not a declaration
tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
where fstt (_, _, a, _, _, _, _) = a
tldeclared (PParams _ _ ds) = []
tldeclared (PMutual _ ds) = concatMap tldeclared ds
tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds
tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms)
tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
tldeclared _ = []
defined :: PDecl -> [Name]
defined (PFix _ _ _) = []
defined (PTy _ _ _ _ _ n _ t) = []
defined (PPostulate _ _ _ _ _ _ n t) = []
defined (PClauses _ _ n _) = [n] -- not a declaration
defined (PCAF _ n _) = [n]
defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
where fstt (_, _, a, _, _, _, _) = a
defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = []
defined (PParams _ _ ds) = concatMap defined ds
defined (PNamespace _ _ ds) = concatMap defined ds
defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms)
defined (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
defined (PDSL n _) = [n]
defined (PSyntax _ _) = []
defined (PMutual _ ds) = concatMap defined ds
defined (PDirective _) = []
defined _ = []
updateN :: [(Name, Name)] -> Name -> Name
updateN ns n | Just n' <- lookup n ns = n'
updateN _ n = n
updateNs :: [(Name, Name)] -> PTerm -> PTerm
updateNs [] t = t
updateNs ns t = mapPT updateRef t
where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f)
updateRef t = t
-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
-- updateDNs [] t = t
-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
-- where updateCNs ns (PClause n l ts r ds)
-- = PClause (updateN ns n) (fmap (updateNs ns) l)
-- (map (fmap (updateNs ns)) ts)
-- (fmap (updateNs ns) r)
-- (map (updateDNs ns) ds)
-- updateDNs ns c = c
data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show, Data, Typeable)
-- | High level language terms
data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language
| PRef FC [FC] Name -- ^ A reference to a variable. The FC is its precise source location for highlighting. The list of FCs is a collection of additional highlighting locations.
| PInferRef FC [FC] Name -- ^ A name to be defined later
| PPatvar FC Name -- ^ A pattern variable
| PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span.
| PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable
| PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location)
| PTyped PTerm PTerm -- ^ Term with explicit type
| PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
| PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only)
| PAppBind FC PTerm [PArg] -- ^ implicitly bound application
| PMatchApp FC Name -- ^ Make an application by type matching
| PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse
| PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs
| PTrue FC PunInfo -- ^ Unit type..?
| PResolveTC FC -- ^ Solve this dictionary by type class resolution
| PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type
| PPair FC [FC] PunInfo PTerm PTerm -- ^ A pair (a, b) and whether it's a product type or a pair (solved by elaboration). The list of FCs is its punctuation.
| PDPair FC [FC] PunInfo PTerm PTerm PTerm -- ^ A dependent pair (tm : a ** b) and whether it's a sigma type or a pair that inhabits one (solved by elaboration). The [FC] is its punctuation.
| PAs FC Name PTerm -- ^ @-pattern, valid LHS only
| PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames.
| PHidden PTerm -- ^ Irrelevant or hidden pattern
| PType FC -- ^ 'Type' type
| PUniverse Universe -- ^ Some universe
| PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions
| PConstant FC Const -- ^ Builtin types
| Placeholder -- ^ Underscore
| PDoBlock [PDo] -- ^ Do notation
| PIdiom FC PTerm -- ^ Idiom brackets
| PReturn FC
| PMetavar FC Name -- ^ A metavariable, ?name, and its precise location
| PProof [PTactic] -- ^ Proof script
| PTactics [PTactic] -- ^ As PProof, but no auto solving
| PElabError Err -- ^ Error to report on elaboration
| PImpossible -- ^ Special case for declaring when an LHS can't typecheck
| PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
| PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
| PUnifyLog PTerm -- ^ dump a trace of unifications when building term
| PNoImplicits PTerm -- ^ never run implicit converions on the term
| PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
| PUnquote PTerm -- ^ ~Term
| PQuoteName Name FC -- ^ `{n} where the FC is the precise highlighting for the name in particular
| PRunElab FC PTerm [String] -- ^ %runElab tm - New-style proof script. Args are location, script, enclosing namespace.
| PConstSugar FC PTerm -- ^ A desugared constant. The FC is a precise source location that will be used to highlight it later.
deriving (Eq, Data, Typeable)
data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed
| FirstSuccess
| TryImplicit
deriving (Eq, Data, Typeable)
-- | Transform the FCs in a PTerm. The first function transforms the
-- general-purpose FCs, and the second transforms those that are used
-- for semantic source highlighting, so they can be treated specially.
mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm
mapPTermFC f g (PQuote q) = PQuote q
mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n
mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n
mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n
mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PLet fc n fc' t1 t2 t3) = PLet (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls
mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n
mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
mapPTermFC f g (PCase fc t cases) = PCase (f fc) (mapPTermFC f g t) (map (\(l,r) -> (mapPTermFC f g l, mapPTermFC f g r)) cases)
mapPTermFC f g (PTrue fc info) = PTrue (f fc) info
mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc)
mapPTermFC f g (PRewrite fc t1 t2 t3) = PRewrite (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3)
mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PDPair fc hls info t1 t2 t3) = PDPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t)
mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts)
mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t)
mapPTermFC f g (PType fc) = PType (f fc)
mapPTermFC f g (PUniverse u) = PUniverse u
mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2)
mapPTermFC f g (PConstant fc c) = PConstant (f fc) c
mapPTermFC f g Placeholder = Placeholder
mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos)
where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t)
mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t)
mapPDoFC (DoBindP fc t1 t2 alts) =
DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts)
mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t)
mapPTermFC f g (PReturn fc) = PReturn (f fc)
mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n
mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs)
mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs)
mapPTermFC f g (PElabError err) = PElabError err
mapPTermFC f g PImpossible = PImpossible
mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t)
mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t)
mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t)
mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t)
mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2)
mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t)
mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns
mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm)
mapPTermFC f g (PQuoteName n fc) = PQuoteName n (g fc)
{-!
dg instance Binary PTerm
deriving instance NFData PTerm
!-}
mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
mapPT f t = f (mpt t) where
mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s)
mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s)
mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)
mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
(fmap (mapPT f) g)
mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e)
mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r)
mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r)
mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as)
mpt (PHidden t) = PHidden (mapPT f t)
mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
mpt x = x
data PTactic' t = Intro [Name] | Intros | Focus Name
| Refine Name [Bool] | Rewrite t | DoUnify
| Induction t
| CaseTac t
| Equiv t
| Claim Name t
| Unfocus
| MatchRefine Name
| LetTac Name t | LetTacTy Name t t
| Exact t | Compute | Trivial | TCInstance
| ProofSearch Bool Bool Int (Maybe Name) [Name]
-- ^ the bool is whether to search recursively
| Solve
| Attack
| ProofState | ProofTerm | Undo
| Try (PTactic' t) (PTactic' t)
| TSeq (PTactic' t) (PTactic' t)
| ApplyTactic t -- see Language.Reflection module
| ByReflection t
| Reflect t
| Fill t
| GoalType String (PTactic' t)
| TCheck t
| TEval t
| TDocStr (Either Name Const)
| TSearch t
| Skip
| TFail [ErrorReportPart]
| Qed | Abandon
| SourceFC
deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable)
{-!
deriving instance Binary PTactic'
deriving instance NFData PTactic'
!-}
instance Sized a => Sized (PTactic' a) where
size (Intro nms) = 1 + size nms
size Intros = 1
size (Focus nm) = 1 + size nm
size (Refine nm bs) = 1 + size nm + length bs
size (Rewrite t) = 1 + size t
size (Induction t) = 1 + size t
size (LetTac nm t) = 1 + size nm + size t
size (Exact t) = 1 + size t
size Compute = 1
size Trivial = 1
size Solve = 1
size Attack = 1
size ProofState = 1
size ProofTerm = 1
size Undo = 1
size (Try l r) = 1 + size l + size r
size (TSeq l r) = 1 + size l + size r
size (ApplyTactic t) = 1 + size t
size (Reflect t) = 1 + size t
size (Fill t) = 1 + size t
size Qed = 1
size Abandon = 1
size Skip = 1
size (TFail ts) = 1 + size ts
size SourceFC = 1
size DoUnify = 1
size (CaseTac x) = 1 + size x
size (Equiv t) = 1 + size t
size (Claim x y) = 1 + size x + size y
size Unfocus = 1
size (MatchRefine x) = 1 + size x
size (LetTacTy x y z) = 1 + size x + size y + size z
size TCInstance = 1
type PTactic = PTactic' PTerm
data PDo' t = DoExp FC t
| DoBind FC Name FC t -- ^ second FC is precise name location
| DoBindP FC t t [(t,t)]
| DoLet FC Name FC t t -- ^ second FC is precise name location
| DoLetP FC t t
deriving (Eq, Functor, Data, Typeable)
{-!
deriving instance Binary PDo'
deriving instance NFData PDo'
!-}
instance Sized a => Sized (PDo' a) where
size (DoExp fc t) = 1 + size fc + size t
size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t
size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r
size (DoLetP fc l r) = 1 + size fc + size l + size r
type PDo = PDo' PTerm
-- The priority gives a hint as to elaboration order. Best to elaborate
-- things early which will help give a more concrete type to other
-- variables, e.g. a before (interpTy a).
data PArg' t = PImp { priority :: Int,
machine_inf :: Bool, -- true if the machine inferred it
argopts :: [ArgOpt],
pname :: Name,
getTm :: t }
| PExp { priority :: Int,
argopts :: [ArgOpt],
pname :: Name,
getTm :: t }
| PConstraint { priority :: Int,
argopts :: [ArgOpt],
pname :: Name,
getTm :: t }
| PTacImplicit { priority :: Int,
argopts :: [ArgOpt],
pname :: Name,
getScript :: t,
getTm :: t }
deriving (Show, Eq, Functor, Data, Typeable)
data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg | UnknownImp
deriving (Show, Eq, Data, Typeable)
instance Sized a => Sized (PArg' a) where
size (PImp p _ l nm trm) = 1 + size nm + size trm
size (PExp p l nm trm) = 1 + size nm + size trm
size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
{-!
deriving instance Binary PArg'
deriving instance NFData PArg'
!-}
pimp n t mach = PImp 1 mach [] n t
pexp t = PExp 1 [] (sMN 0 "arg") t
pconst t = PConstraint 1 [] (sMN 0 "carg") t
ptacimp n s t = PTacImplicit 2 [] n s t
type PArg = PArg' PTerm
-- | Get the highest FC in a term, if one exists
highestFC :: PTerm -> Maybe FC
highestFC (PQuote _) = Nothing
highestFC (PRef fc _ _) = Just fc
highestFC (PInferRef fc _ _) = Just fc
highestFC (PPatvar fc _) = Just fc
highestFC (PLam fc _ _ _ _) = Just fc
highestFC (PPi _ _ _ _ _) = Nothing
highestFC (PLet fc _ _ _ _ _) = Just fc
highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty
highestFC (PApp fc _ _) = Just fc
highestFC (PAppBind fc _ _) = Just fc
highestFC (PMatchApp fc _) = Just fc
highestFC (PCase fc _ _) = Just fc
highestFC (PIfThenElse fc _ _ _) = Just fc
highestFC (PTrue fc _) = Just fc
highestFC (PResolveTC fc) = Just fc
highestFC (PRewrite fc _ _ _) = Just fc
highestFC (PPair fc _ _ _ _) = Just fc
highestFC (PDPair fc _ _ _ _ _) = Just fc
highestFC (PAs fc _ _) = Just fc
highestFC (PAlternative _ _ args) =
case mapMaybe highestFC args of
[] -> Nothing
(fc:_) -> Just fc
highestFC (PHidden _) = Nothing
highestFC (PType fc) = Just fc
highestFC (PUniverse _) = Nothing
highestFC (PGoal fc _ _ _) = Just fc
highestFC (PConstant fc _) = Just fc
highestFC Placeholder = Nothing
highestFC (PDoBlock lines) =
case map getDoFC lines of
[] -> Nothing
(fc:_) -> Just fc
where
getDoFC (DoExp fc t) = fc
getDoFC (DoBind fc nm nfc t) = fc
getDoFC (DoBindP fc l r alts) = fc
getDoFC (DoLet fc nm nfc l r) = fc
getDoFC (DoLetP fc l r) = fc
highestFC (PIdiom fc _) = Just fc
highestFC (PReturn fc) = Just fc
highestFC (PMetavar fc _) = Just fc
highestFC (PProof _) = Nothing
highestFC (PTactics _) = Nothing
highestFC (PElabError _) = Nothing
highestFC PImpossible = Nothing
highestFC (PCoerced tm) = highestFC tm
highestFC (PDisamb _ opts) = highestFC opts
highestFC (PUnifyLog tm) = highestFC tm
highestFC (PNoImplicits tm) = highestFC tm
highestFC (PQuasiquote _ _) = Nothing
highestFC (PUnquote tm) = highestFC tm
highestFC (PQuoteName _ fc) = Just fc
highestFC (PRunElab fc _ _) = Just fc
highestFC (PConstSugar fc _) = Just fc
highestFC (PAppImpl t _) = highestFC t
-- Type class data
data ClassInfo = CI { instanceCtorName :: Name,
class_methods :: [(Name, (FnOpts, PTerm))],
class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
class_default_superclasses :: [PDecl],
class_params :: [Name],
class_instances :: [(Name, Bool)], -- the Bool is whether to include in instance search, so named instances are excluded
class_determiners :: [Int] }
deriving Show
{-!
deriving instance Binary ClassInfo
deriving instance NFData ClassInfo
!-}
-- Type inference data
data TIData = TIPartial -- ^ a function with a partially defined type
| TISolution [Term] -- ^ possible solutions to a metavariable in a type
deriving Show
-- | Miscellaneous information about functions
data FnInfo = FnInfo { fn_params :: [Int] }
deriving Show
{-!
deriving instance Binary FnInfo
deriving instance NFData FnInfo
!-}
data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
detaggable :: Bool }
deriving Show
{-!
deriving instance Binary OptInfo
deriving instance NFData OptInfo
!-}
-- | Syntactic sugar info
data DSL' t = DSL { dsl_bind :: t,
dsl_return :: t,
dsl_apply :: t,
dsl_pure :: t,
dsl_var :: Maybe t,
index_first :: Maybe t,
index_next :: Maybe t,
dsl_lambda :: Maybe t,
dsl_let :: Maybe t,
dsl_pi :: Maybe t
}
deriving (Show, Functor)
{-!
deriving instance Binary DSL'
deriving instance NFData DSL'
!-}
type DSL = DSL' PTerm
data SynContext = PatternSyntax | TermSyntax | AnySyntax
deriving Show
{-!
deriving instance Binary SynContext
deriving instance NFData SynContext
!-}
data Syntax = Rule [SSymbol] PTerm SynContext
deriving Show
syntaxNames :: Syntax -> [Name]
syntaxNames (Rule syms _ _) = mapMaybe ename syms
where ename (Keyword n) = Just n
ename _ = Nothing
syntaxSymbols :: Syntax -> [SSymbol]
syntaxSymbols (Rule ss _ _) = ss
{-!
deriving instance Binary Syntax
deriving instance NFData Syntax
!-}
data SSymbol = Keyword Name
| Symbol String
| Binding Name
| Expr Name
| SimpleExpr Name
deriving (Show, Eq)
{-!
deriving instance Binary SSymbol
deriving instance NFData SSymbol
!-}
newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] }
emptySyntaxRules :: SyntaxRules
emptySyntaxRules = SyntaxRules []
updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules
updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules
where
newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr)
ruleSort [] [] = EQ
ruleSort [] _ = LT
ruleSort _ [] = GT
ruleSort (s1:ss1) (s2:ss2) =
case symCompare s1 s2 of
EQ -> ruleSort ss1 ss2
r -> r
-- Better than creating Ord instance for SSymbol since
-- in general this ordering does not really make sense.
symCompare (Keyword n1) (Keyword n2) = compare n1 n2
symCompare (Keyword _) _ = LT
symCompare (Symbol _) (Keyword _) = GT
symCompare (Symbol s1) (Symbol s2) = compare s1 s2
symCompare (Symbol _) _ = LT
symCompare (Binding _) (Keyword _) = GT
symCompare (Binding _) (Symbol _) = GT
symCompare (Binding b1) (Binding b2) = compare b1 b2
symCompare (Binding _) _ = LT
symCompare (Expr _) (Keyword _) = GT
symCompare (Expr _) (Symbol _) = GT
symCompare (Expr _) (Binding _) = GT
symCompare (Expr e1) (Expr e2) = compare e1 e2
symCompare (Expr _) _ = LT
symCompare (SimpleExpr _) (Keyword _) = GT
symCompare (SimpleExpr _) (Symbol _) = GT
symCompare (SimpleExpr _) (Binding _) = GT
symCompare (SimpleExpr _) (Expr _) = GT
symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2
initDSL = DSL (PRef f [] (sUN ">>="))
(PRef f [] (sUN "return"))
(PRef f [] (sUN "<*>"))
(PRef f [] (sUN "pure"))
Nothing
Nothing
Nothing
Nothing
Nothing
Nothing
where f = fileFC "(builtin)"
data Using = UImplicit Name PTerm
| UConstraint Name [Name]
deriving (Show, Eq, Data, Typeable)
{-!
deriving instance Binary Using
deriving instance NFData Using
!-}
data SyntaxInfo = Syn { using :: [Using],
syn_params :: [(Name, PTerm)],
syn_namespace :: [String],
no_imp :: [Name],
imp_methods :: [Name], -- class methods. When expanding
-- implicits, these should be expanded even under
-- binders
decoration :: Name -> Name,
inPattern :: Bool,
implicitAllowed :: Bool,
maxline :: Maybe Int,
mut_nesting :: Int,
dsl_info :: DSL,
syn_in_quasiquote :: Int }
deriving Show
{-!
deriving instance NFData SyntaxInfo
deriving instance Binary SyntaxInfo
!-}
defaultSyntax = Syn [] [] [] [] [] id False False Nothing 0 initDSL 0
expandNS :: SyntaxInfo -> Name -> Name
expandNS syn n@(NS _ _) = n
expandNS syn n = case syn_namespace syn of
[] -> n
xs -> sNS n xs
-- For inferring types of things
bi = fileFC "builtin"
inferTy = sMN 0 "__Infer"
inferCon = sMN 0 "__infer"
inferDecl = PDatadecl inferTy NoFC
(PType bi)
[(emptyDocstring, [], inferCon, NoFC, PPi impl (sMN 0 "iType") NoFC (PType bi) (
PPi expl (sMN 0 "ival") NoFC (PRef bi [] (sMN 0 "iType"))
(PRef bi [] inferTy)), bi, [])]
inferOpts = []
infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
infP = P (TCon 6 0) inferTy (TType (UVal 0))
getInferTerm, getInferType :: Term -> Term
getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
getInferTerm (App _ (App _ _ _) tm) = tm
getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
where toTy (Lam t) = Pi Nothing t (TType (UVar 0))
toTy (PVar t) = PVTy t
toTy b = b
getInferType (App _ (App _ _ ty) _) = ty
-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
primNames = [inferTy, inferCon]
unitTy = sUN "Unit"
unitCon = sUN "MkUnit"
falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $
"The empty type, also known as the trivially false proposition." ++
"\n\n" ++
"Use `void` or `absurd` to prove anything if you have a variable " ++
"of type `Void` in scope."
falseTy = sUN "Void"
pairTy = sNS (sUN "Pair") ["Builtins"]
pairCon = sNS (sUN "MkPair") ["Builtins"]
upairTy = sNS (sUN "UPair") ["Builtins"]
upairCon = sNS (sUN "MkUPair") ["Builtins"]
eqTy = sUN "="
eqCon = sUN "Refl"
eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $
"The propositional equality type. A proof that `x` = `y`." ++
"\n\n" ++
"To use such a proof, pattern-match on it, and the two equal things will " ++
"then need to be the _same_ pattern." ++
"\n\n" ++
"**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++
"is possible to state equalities between values of potentially different " ++
"types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++
"\n\n" ++
"You may need to use `(~=~)` to explicitly request heterogeneous equality."
eqDecl = PDatadecl eqTy NoFC (piBindp impl [(n "A", PType bi), (n "B", PType bi)]
(piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))]
(PType bi)))
[(reflDoc, reflParamDoc,
eqCon, NoFC, PPi impl (n "A") NoFC (PType bi) (
PPi impl (n "x") NoFC (PRef bi [] (n "A"))
(PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False,
pimp (n "B") Placeholder False,
pexp (PRef bi [] (n "x")),
pexp (PRef bi [] (n "x"))])), bi, [])]
where n a = sUN a
reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $
"A proof that `x` in fact equals `x`. To construct this, you must have already " ++
"shown that both sides are in fact equal."
reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"),
(n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")]
eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"),
(n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality")
]
where n a = sUN a
eqOpts = []
-- | The special name to be used in the module documentation context -
-- not for use in the main definition context. The namespace around it
-- will determine the module to which the docs adhere.
modDocName :: Name
modDocName = sMN 0 "ModuleDocs"
-- Defined in builtins.idr
sigmaTy = sNS (sUN "Sigma") ["Builtins"]
sigmaCon = sNS (sUN "MkSigma") ["Builtins"]
piBind :: [(Name, PTerm)] -> PTerm -> PTerm
piBind = piBindp expl
piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
piBindp p [] t = t
piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t)
-- Pretty-printing declarations and terms
-- These "show" instances render to an absurdly wide screen because inserted line breaks
-- could interfere with interactive editing, which calls "show".
instance Show PTerm where
showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
instance Show PDecl where
showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d
instance Show PClause where
showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
instance Show PData where
showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
instance Pretty PTerm OutputAnnotation where
pretty = prettyImp defaultPPOption
-- | Colourise annotations according to an Idris state. It ignores the names
-- in the annotation, as there's no good way to show extended information on a
-- terminal.
consoleDecorate :: IState -> OutputAnnotation -> String -> String
consoleDecorate ist _ | not (idris_colourRepl ist) = id
consoleDecorate ist (AnnConst c) = let theme = idris_colourTheme ist
in if constIsType c
then colouriseType theme
else colouriseData theme
consoleDecorate ist (AnnData _ _) = colouriseData (idris_colourTheme ist)
consoleDecorate ist (AnnType _ _) = colouriseType (idris_colourTheme ist)
consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
theme = idris_colourTheme ist
in case () of
_ | isDConName n ctxt -> colouriseData theme
_ | isFnName n ctxt -> colouriseFun theme
_ | isTConName n ctxt -> colouriseType theme
_ | isPostulateName n ist -> colourisePostulate theme
_ | otherwise -> id -- don't colourise unknown names
consoleDecorate ist (AnnFC _) = id
consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
where colour BoldText = IdrisColour Nothing True False True False
colour UnderlineText = IdrisColour Nothing True True False False
colour ItalicText = IdrisColour Nothing True False False True
consoleDecorate ist (AnnTerm _ _) = id
consoleDecorate ist (AnnSearchResult _) = id
consoleDecorate ist (AnnErr _) = id
consoleDecorate ist (AnnNamespace _ _) = id
consoleDecorate ist (AnnLink url) =
\txt -> Idris.Colours.colourise (IdrisColour Nothing True True False False) txt ++ " (" ++ url ++ ")"
isPostulateName :: Name -> IState -> Bool
isPostulateName n ist = S.member n (idris_postulates ist)
-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
prettyImp :: PPOption -- ^^ pretty printing options
-> PTerm -- ^^ the term to pretty-print
-> Doc OutputAnnotation
prettyImp impl = pprintPTerm impl [] [] []
-- | Serialise something to base64 using its Binary instance.
-- | Do the right thing for rendering a term in an IState
prettyIst :: IState -> PTerm -> Doc OutputAnnotation
prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
-- | Pretty-print a high-level Idris term in some bindings context with infix info
pprintPTerm :: PPOption -- ^^ pretty printing options
-> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
-> [Name] -- ^^ names to always show in pi, even if not used
-> [FixDecl] -- ^^ Fixity declarations
-> PTerm -- ^^ the term to pretty-print
-> Doc OutputAnnotation
pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
where
startPrec = 0
funcAppPrec = 10
prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
prettySe d p bnd (PQuote r) =
text "![" <> pretty r <> text "]"
prettySe d p bnd (PPatvar fc n) = pretty n
prettySe d p bnd e
| Just str <- slist d p bnd e = depth d $ str
| Just n <- snat d p e = depth d $ annotate (AnnData "Nat" "") (text (show n))
prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n
prettySe d p bnd (PLam fc n nfc ty sc) =
depth d . bracket p startPrec . group . align . hang 2 $
text "\\" <> prettyBindingOf n False <+> text "=>" <$>
prettySe (decD d) startPrec ((n, False):bnd) sc
prettySe d p bnd (PLet fc n nfc ty v sc) =
depth d . bracket p startPrec . group . align $
kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>
kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)
prettySe d p bnd (PPi (Exp l s _) n _ ty sc)
| n `elem` allNamesIn sc || ppopt_impl ppo || n `elem` docArgs =
depth d . bracket p startPrec . group $
enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
| otherwise =
depth d . bracket p startPrec . group $
group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$>
group (prettySe (decD d) startPrec ((n, False):bnd) sc)
where
st =
case s of
Static -> text "[static]" <> space
_ -> empty
prettySe d p bnd (PPi (Imp l s _ fa) n _ ty sc)
| ppopt_impl ppo =
depth d . bracket p startPrec $
lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
| otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc
where
st =
case s of
Static -> text "[static]" <> space
_ -> empty
prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) =
depth d . bracket p startPrec $
prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc
prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch _ _ _ _ _])) n _ ty sc) =
lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) =
depth d . bracket p startPrec $
lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
-- This case preserves the behavior of the former constructor PEq.
-- It should be removed if feasible when the pretty-printing of infix
-- operators in general is improved.
prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r])
| n == eqTy, ppopt_impl ppo =
depth d . bracket p eqPrec $
enclose lparen rparen eq <+>
align (group (vsep (map (prettyArgS (decD d) bnd)
[lt, rt, l, r])))
| n == eqTy =
depth d . bracket p eqPrec . align . group $
prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r))
where eq = annName eqTy (text "=")
eqPrec = startPrec
prettyTerm = prettySe (decD d) (eqPrec + 1) bnd
prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args
| UN nm <- basename f
, not (ppopt_impl ppo) && null (getShowArgs args) =
prettyName True (ppopt_impl ppo) bnd f
prettySe d p bnd (PAppBind _ (PRef _ _ f) [])
| not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f
prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators
| UN nm <- basename op
, not (tnull nm) &&
(not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
case getShowArgs args of
[] -> opName True
[x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x)))
[l,r] -> let precedence = maybe (startPrec - 1) prec f
in depth d . bracket p precedence $ inFix (getTm l) (getTm r)
(l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) ->
depth d . bracket p funcAppPrec $
enclose lparen rparen (inFix (getTm l) (getTm r)) <+>
align (group (vsep (map (prettyArgS d bnd) rest)))
as -> opName True <+> align (vsep (map (prettyArgS d bnd) as))
where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op
f = getFixity (opStr op)
left = case f of
Nothing -> funcAppPrec + 1
Just (Infixl p') -> p'
Just f' -> prec f' + 1
right = case f of
Nothing -> funcAppPrec + 1
Just (Infixr p') -> p'
Just f' -> prec f' + 1
inFix l r = align . group $
(prettySe (decD d) left bnd l <+> opName False) <$>
group (prettySe (decD d) right bnd r)
prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo
| PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm,
f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str))
prettySe d p bnd (PApp _ f as) = -- Normal prefix applications
let args = getShowArgs as
fp = prettySe (decD d) (startPrec + 1) bnd f
shownArgs = if ppopt_impl ppo then as else args
in
depth d . bracket p funcAppPrec . group $
if null shownArgs
then fp
else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs))
prettySe d p bnd (PCase _ scr cases) =
align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$>
depth d (indent 2 (vsep (map ppcase cases)))
where
ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec
([(n, False) | n <- vars l] ++ bnd)
in nest nestingSize $
prettyCase l <+> text "=>" <+> prettyCase r
-- Warning: this is a bit of a hack. At this stage, we don't have the
-- global context, so we can't determine which names are constructors,
-- which are types, and which are pattern variables on the LHS of the
-- case pattern. We use the heuristic that names without a namespace
-- are patvars, because right now case blocks in PTerms are always
-- delaborated from TT before being sent to the pretty-printer. If they
-- start getting printed directly, THIS WILL BREAK.
-- Potential solution: add a list of known patvars to the cases in
-- PCase, and have the delaborator fill it out, kind of like the pun
-- disambiguation on PDPair.
vars tm = filter noNS (allNamesIn tm)
noNS (NS _ _) = False
noNS _ = True
prettySe d p bnd (PIfThenElse _ c t f) =
depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $
[ kwd "if" <+> prettySe (decD d) startPrec bnd c
, kwd "then" <+> prettySe (decD d) startPrec bnd t
, kwd "else" <+> prettySe (decD d) startPrec bnd f
]
prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
prettySe d p bnd (PResolveTC _) = kwd "%instance"
prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
prettySe d p bnd (PRewrite _ l r _) =
depth d . bracket p startPrec $
text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l <+> text "in" <+> prettySe (decD d) startPrec bnd r
prettySe d p bnd (PTyped l r) =
lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen
prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser
| Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) .
align . group . vsep . punctuate (ann comma) $
map (prettySe (decD d) startPrec bnd) elts
where ann = case pun of
TypeOrTerm -> id
IsType -> annName pairTy
IsTerm -> annName pairCon
prettySe d p bnd (PDPair _ _ pun l t r) =
depth d $
annotated lparen <>
left <+>
annotated (text "**") <+>
prettySe (decD d) startPrec (addBinding bnd) r <>
annotated rparen
where annotated = case pun of
IsType -> annName sigmaTy
IsTerm -> annName sigmaCon
TypeOrTerm -> id
(left, addBinding) = case (l, pun) of
(PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :))
_ -> (prettySe (decD d) startPrec bnd l, id)
prettySe d p bnd (PAlternative ns a as) =
lparen <> text "|" <> prettyAs <> text "|" <> rparen
where
prettyAs =
foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (depth d . prettySe (decD d) startPrec bnd) as
prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type"
prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u)
prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c))
-- XXX: add pretty for tactics
prettySe d p bnd (PProof ts) =
kwd "proof" <+> lbrace <> ellipsis <> rbrace
prettySe d p bnd (PTactics ts) =
kwd "tactics" <+> lbrace <> ellipsis <> rbrace
prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n
prettySe d p bnd (PReturn f) = kwd "return"
prettySe d p bnd PImpossible = kwd "impossible"
prettySe d p bnd Placeholder = text "_"
prettySe d p bnd (PDoBlock dos) =
bracket p startPrec $
kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos)))
where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos
ppdo bnd (DoBind _ bn _ tm : dos) =
(prettyBindingOf bn False <+> text "<-" <+>
group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) :
ppdo ((bn, False):bnd) dos
ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab
text "no pretty printer for pattern-matching do binding" :
ppdo bnd dos
ppdo bnd (DoLet _ ln _ ty v : dos) =
(kwd "let" <+> prettyBindingOf ln False <+>
(if ty /= Placeholder
then colon <+> prettySe (decD d) startPrec bnd ty <+> text "="
else text "=") <+>
group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) :
ppdo ((ln, False):bnd) dos
ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab
text "no pretty printer for pattern-matching do binding" :
ppdo bnd dos
ppdo _ [] = []
prettySe d p bnd (PCoerced t) = prettySe d p bnd t
prettySe d p bnd (PElabError s) = pretty s
-- Quasiquote pprinting ignores bound vars
prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")"
prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")"
prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t
prettySe d p bnd (PQuoteName n _) = text "`{" <> prettyName True (ppopt_impl ppo) bnd n <> text "}"
prettySe d p bnd (PRunElab _ tm _) =
bracket p funcAppPrec . group . align . hang 2 $
text "%runElab" <$>
prettySe (decD d) funcAppPrec bnd tm
prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
prettySe d p bnd _ = text "missing pretty-printer for term"
prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation
prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n))
where display (UN n) = T.unpack n
display (MN _ n) = T.unpack n
-- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings
display (NS n ns) = (concat . intersperse "." . map T.unpack . reverse) ns ++ "." ++ display n
display n = show n
prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm)
prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm
prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm
prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm)
prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg
prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace
prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
annName n = annotate (AnnName n Nothing Nothing Nothing)
opStr :: Name -> String
opStr (NS n _) = opStr n
opStr (UN n) = T.unpack n
slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation]
slist' (Just d) _ _ _ | d <= 0 = Nothing
slist' d _ _ e
| containsHole e = Nothing
slist' d p bnd (PApp _ (PRef _ _ nil) _)
| not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
slist' d p bnd (PRef _ _ nil)
| not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
slist' d p bnd (PApp _ (PRef _ _ cons) args)
| nsroot cons == sUN "::",
(PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
all isImp imps,
Just tl' <- slist' (decD d) p bnd tl
= Just (prettySe d startPrec bnd hd : tl')
where
isImp (PImp {}) = True
isImp _ = False
slist' _ _ _ tm = Nothing
slist d p bnd e | Just es <- slist' d p bnd e = Just $
case es of
[] -> annotate (AnnData "" "") $ text "[]"
[x] -> enclose left right . group $ x
xs -> enclose left right .
align . group . vsep .
punctuate comma $ xs
where left = (annotate (AnnData "" "") (text "["))
right = (annotate (AnnData "" "") (text "]"))
comma = (annotate (AnnData "" "") (text ","))
slist _ _ _ _ = Nothing
pairElts :: PTerm -> Maybe [PTerm]
pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts)
| otherwise = Just [x, y]
pairElts _ = Nothing
natns = "Prelude.Nat."
snat :: Maybe Int -> Int -> PTerm -> Maybe Integer
snat (Just x) _ _ | x <= 0 = Nothing
snat d p (PRef _ _ z)
| show z == (natns++"Z") || show z == "Z" = Just 0
snat d p (PApp _ s [PExp {getTm=n}])
| show s == (natns++"S") || show s == "S",
Just n' <- snat (decD d) p n
= Just $ 1 + n'
snat _ _ _ = Nothing
bracket outer inner doc
| outer > inner = lparen <> doc <> rparen
| otherwise = doc
ellipsis = text "..."
depth Nothing = id
depth (Just d) = if d <= 0 then const (ellipsis) else id
decD = fmap (\x -> x - 1)
kwd = annotate AnnKeyword . text
fixities :: M.Map String Fixity
fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
getFixity :: String -> Maybe Fixity
getFixity = flip M.lookup fixities
-- | Strip away namespace information
basename :: Name -> Name
basename (NS n _) = basename n
basename n = n
-- | Determine whether a name was the one inserted for a hole or
-- guess by the delaborator
isHoleName :: Name -> Bool
isHoleName (UN n) = n == T.pack "[__]"
isHoleName _ = False
-- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess
containsHole :: PTerm -> Bool
containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm]
-- | Pretty-printer helper for names that attaches the correct annotations
prettyName
:: Bool -- ^^ whether the name should be parenthesised if it is an infix operator
-> Bool -- ^^ whether to show namespaces
-> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
-> Name -- ^^ the name to pprint
-> Doc OutputAnnotation
prettyName infixParen showNS bnd n
| (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_"
| (UN n') <- n, T.unpack n' == "_" = text "_"
| Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName
| otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName
where fullName = text nameSpace <> parenthesise (text (baseName n))
baseName (UN n) = T.unpack n
baseName (NS n ns) = baseName n
baseName (MN i s) = T.unpack s
baseName other = show other
nameSpace = case n of
(NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else ""
_ -> ""
isInfix = case baseName n of
"" -> False
(c : _) -> not (isAlpha c)
parenthesise = if isInfix && infixParen then enclose lparen rparen else id
showCImp :: PPOption -> PClause -> Doc OutputAnnotation
showCImp ppo (PClause _ n l ws r w)
= prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
<+> text "where" <+> text (show w)
where
showWs [] = empty
showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
showCImp ppo (PWith _ n l ws r pn w)
= prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
<+> braces (text (show w))
where
showWs [] = empty
showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
showDImp :: PPOption -> PData -> Doc OutputAnnotation
showDImp ppo (PDatadecl n nfc ty cons)
= text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
(indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons))
showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
showDecls o ds = vsep (map (showDeclImp o) ds)
showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
indent 2 (vsep (map (showCImp o) cs))
showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _)
= text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
showDeclImp o (PInstance _ _ _ _ cs n _ _ t _ ds)
= text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
showDeclImp _ _ = text "..."
-- showDeclImp (PImport o) = "import " ++ o
getImps :: [PArg] -> [(Name, PTerm)]
getImps [] = []
getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
getImps (_ : xs) = getImps xs
getExps :: [PArg] -> [PTerm]
getExps [] = []
getExps (PExp _ _ _ tm : xs) = tm : getExps xs
getExps (_ : xs) = getExps xs
getShowArgs :: [PArg] -> [PArg]
getShowArgs [] = []
getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs
getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs
| PImp _ _ _ _ tm <- e
, containsHole tm = e : getShowArgs xs
getShowArgs (_ : xs) = getShowArgs xs
getConsts :: [PArg] -> [PTerm]
getConsts [] = []
getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
getConsts (_ : xs) = getConsts xs
getAll :: [PArg] -> [PTerm]
getAll = map getTm
-- | Show Idris name
showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
-> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
-> PPOption -- ^^ pretty printing options
-> Bool -- ^^ whether to colourise
-> Name -- ^^ the term to show
-> String
showName ist bnd ppo colour n = case ist of
Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
Nothing -> showbasic n
where name = if ppopt_impl ppo then show n else showbasic n
showbasic n@(UN _) = showCG n
showbasic (MN i s) = str s
showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
showbasic (SN s) = show s
fst3 (x, _, _) = x
colourise n t = let ctxt' = fmap tt_ctxt ist in
case ctxt' of
Nothing -> name
Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
else colouriseBound t name
| isDConName n ctxt -> colouriseData t name
| isFnName n ctxt -> colouriseFun t name
| isTConName n ctxt -> colouriseType t name
-- The assumption is that if a name is not bound and does not exist in the
-- global context, then we're somewhere in which implicit info has been lost
-- (like error messages). Thus, unknown vars are colourised as implicits.
| otherwise -> colouriseImplicit t name
showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
-> PTerm -- ^^ the term to show
-> String
showTm ist = displayDecorated (consoleDecorate ist) .
renderPretty 0.8 100000 .
prettyImp (ppOptionIst ist)
-- | Show a term with implicits, no colours
showTmImpls :: PTerm -> String
showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
instance Sized PTerm where
size (PQuote rawTerm) = size rawTerm
size (PRef fc _ name) = size name
size (PLam fc name _ ty bdy) = 1 + size ty + size bdy
size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy
size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy
size (PTyped trm ty) = 1 + size trm + size ty
size (PApp fc name args) = 1 + size args
size (PAppBind fc name args) = 1 + size args
size (PCase fc trm bdy) = 1 + size trm + size bdy
size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f])
size (PTrue fc _) = 1
size (PResolveTC fc) = 1
size (PRewrite fc left right _) = 1 + size left + size right
size (PPair fc _ _ left right) = 1 + size left + size right
size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right
size (PAlternative _ a alts) = 1 + size alts
size (PHidden hidden) = size hidden
size (PUnifyLog tm) = size tm
size (PDisamb _ tm) = size tm
size (PNoImplicits tm) = size tm
size (PType _) = 1
size (PUniverse _) = 1
size (PConstant fc const) = 1 + size fc + size const
size Placeholder = 1
size (PDoBlock dos) = 1 + size dos
size (PIdiom fc term) = 1 + size term
size (PReturn fc) = 1
size (PMetavar _ name) = 1
size (PProof tactics) = size tactics
size (PElabError err) = size err
size PImpossible = 1
size _ = 0
getPArity :: PTerm -> Int
getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc
getPArity _ = 0
-- Return all names, free or globally bound, in the given term.
allNamesIn :: PTerm -> [Name]
allNamesIn tm = nub $ ni [] tm
where -- TODO THINK added niTacImp, but is it right?
ni env (PRef _ _ n)
| not (n `elem` env) = [n]
ni env (PPatvar _ n) = [n]
ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
ni env (PIfThenElse _ c t f) = ni env c ++ ni env t ++ ni env f
ni env (PLam fc n _ ty sc) = ni env ty ++ ni (n:env) sc
ni env (PPi p n _ ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
ni env (PLet _ n _ ty val sc) = ni env ty ++ ni env val ++ ni (n:env) sc
ni env (PHidden tm) = ni env tm
ni env (PRewrite _ l r _) = ni env l ++ ni env r
ni env (PTyped l r) = ni env l ++ ni env r
ni env (PPair _ _ _ l r) = ni env l ++ ni env r
ni env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : ni env r
ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r
ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r
ni env (PAlternative ns a ls) = concatMap (ni env) ls
ni env (PUnifyLog tm) = ni env tm
ni env (PDisamb _ tm) = ni env tm
ni env (PNoImplicits tm) = ni env tm
ni env _ = []
niTacImp env (TacImp _ _ scr) = ni env scr
niTacImp _ _ = []
-- Return all names defined in binders in the given term
boundNamesIn :: PTerm -> [Name]
boundNamesIn tm = S.toList (ni S.empty tm)
where -- TODO THINK Added niTacImp, but is it right?
ni set (PApp _ f as) = niTms (ni set f) (map getTm as)
ni set (PAppBind _ f as) = niTms (ni set f) (map getTm as)
ni set (PCase _ c os) = niTms (ni set c) (map snd os)
ni set (PIfThenElse _ c t f) = niTms set [c, t, f]
ni set (PLam fc n _ ty sc) = S.insert n $ ni (ni set ty) sc
ni set (PLet fc n nfc ty val sc) = S.insert n $ ni (ni (ni set ty) val) sc
ni set (PPi p n _ ty sc) = niTacImp (S.insert n $ ni (ni set ty) sc) p
ni set (PRewrite _ l r _) = ni (ni set l) r
ni set (PTyped l r) = ni (ni set l) r
ni set (PPair _ _ _ l r) = ni (ni set l) r
ni set (PDPair _ _ _ (PRef _ _ n) t r) = ni (ni set t) r
ni set (PDPair _ _ _ l t r) = ni (ni (ni set l) t) r
ni set (PAlternative ns a as) = niTms set as
ni set (PHidden tm) = ni set tm
ni set (PUnifyLog tm) = ni set tm
ni set (PDisamb _ tm) = ni set tm
ni set (PNoImplicits tm) = ni set tm
ni set _ = set
niTms set [] = set
niTms set (x : xs) = niTms (ni set x) xs
niTacImp set (TacImp _ _ scr) = ni set scr
niTacImp set _ = set
-- Return names which are valid implicits in the given term (type).
implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
implicitNamesIn uvars ist tm = nub $ ni [] tm
where
ni env (PRef _ _ n)
| not (n `elem` env)
= case lookupTy n (tt_ctxt ist) of
[] -> [n]
_ -> if n `elem` uvars then [n] else []
ni env (PApp _ f@(PRef _ _ n) as)
| n `elem` uvars = ni env f ++ concatMap (ni env) (map getTm as)
| otherwise = concatMap (ni env) (map getTm as)
ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PCase _ c os) = ni env c ++
-- names in 'os', not counting the names bound in the cases
(nub (concatMap (ni env) (map snd os))
\\ nub (concatMap (ni env) (map fst os)))
ni env (PIfThenElse _ c t f) = concatMap (ni env) [c, t, f]
ni env (PLam fc n _ ty sc) = ni env ty ++ ni (n:env) sc
ni env (PPi p n _ ty sc) = ni env ty ++ ni (n:env) sc
ni env (PRewrite _ l r _) = ni env l ++ ni env r
ni env (PTyped l r) = ni env l ++ ni env r
ni env (PPair _ _ _ l r) = ni env l ++ ni env r
ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r
ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r
ni env (PAlternative ns a as) = concatMap (ni env) as
ni env (PHidden tm) = ni env tm
ni env (PUnifyLog tm) = ni env tm
ni env (PDisamb _ tm) = ni env tm
ni env (PNoImplicits tm) = ni env tm
ni env _ = []
-- Return names which are free in the given term.
namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
namesIn uvars ist tm = nub $ ni [] tm
where
ni env (PRef _ _ n)
| not (n `elem` env)
= case lookupTy n (tt_ctxt ist) of
[] -> [n]
_ -> if n `elem` (map fst uvars) then [n] else []
ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PCase _ c os) = ni env c ++
-- names in 'os', not counting the names bound in the cases
(nub (concatMap (ni env) (map snd os))
\\ nub (concatMap (ni env) (map fst os)))
ni env (PIfThenElse _ c t f) = concatMap (ni env) [c, t, f]
ni env (PLam fc n nfc ty sc) = ni env ty ++ ni (n:env) sc
ni env (PPi p n _ ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
ni env (PRewrite _ l r _) = ni env l ++ ni env r
ni env (PTyped l r) = ni env l ++ ni env r
ni env (PPair _ _ _ l r) = ni env l ++ ni env r
ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r
ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r
ni env (PAlternative ns a as) = concatMap (ni env) as
ni env (PHidden tm) = ni env tm
ni env (PUnifyLog tm) = ni env tm
ni env (PDisamb _ tm) = ni env tm
ni env (PNoImplicits tm) = ni env tm
ni env _ = []
niTacImp env (TacImp _ _ scr) = ni env scr
niTacImp _ _ = []
-- Return which of the given names are used in the given term.
usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
usedNamesIn vars ist tm = nub $ ni [] tm
where -- TODO THINK added niTacImp, but is it right?
ni env (PRef _ _ n)
| n `elem` vars && not (n `elem` env)
= case lookupDefExact n (tt_ctxt ist) of
Nothing -> [n]
_ -> []
ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
ni env (PIfThenElse _ c t f) = concatMap (ni env) [c, t, f]
ni env (PLam fc n _ ty sc) = ni env ty ++ ni (n:env) sc
ni env (PPi p n _ ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
ni env (PRewrite _ l r _) = ni env l ++ ni env r
ni env (PTyped l r) = ni env l ++ ni env r
ni env (PPair _ _ _ l r) = ni env l ++ ni env r
ni env (PDPair _ _ _ (PRef _ _ n) t r) = ni env t ++ ni (n:env) r
ni env (PDPair _ _ _ l t r) = ni env l ++ ni env t ++ ni env r
ni env (PAlternative ns a as) = concatMap (ni env) as
ni env (PHidden tm) = ni env tm
ni env (PUnifyLog tm) = ni env tm
ni env (PDisamb _ tm) = ni env tm
ni env (PNoImplicits tm) = ni env tm
ni env _ = []
niTacImp env (TacImp _ _ scr) = ni env scr
niTacImp _ _ = []
-- Return the list of inaccessible (= dotted) positions for a name.
getErasureInfo :: IState -> Name -> [Int]
getErasureInfo ist n =
case lookupCtxtExact n (idris_optimisation ist) of
Just (Optimise inacc detagg) -> map fst inacc
Nothing -> []
|
athanclark/Idris-dev
|
src/Idris/AbsSyntaxTree.hs
|
Haskell
|
bsd-3-clause
| 95,914
|
module MainSpec (main, spec) where
import Test.Hspec
import Test.HUnit (assertEqual, Assertion)
import Control.Exception
import System.Directory (getCurrentDirectory, setCurrentDirectory)
import System.FilePath
import Runner (Summary(..))
import Run hiding (doctest)
import System.IO.Silently
import System.IO
withCurrentDirectory :: FilePath -> IO a -> IO a
withCurrentDirectory workingDir action = do
bracket getCurrentDirectory setCurrentDirectory $ \_ -> do
setCurrentDirectory workingDir
action
-- | Construct a doctest specific 'Assertion'.
doctest :: FilePath -- ^ current directory of `doctest` process
-> [String] -- ^ args, given to `doctest`
-> Summary -- ^ expected test result
-> Assertion
doctest workingDir args summary = do
r <- withCurrentDirectory ("test/integration" </> workingDir) (hSilence [stderr] $ doctest_ args)
assertEqual label summary r
where
label = workingDir ++ " " ++ show args
cases :: Int -> Summary
cases n = Summary n n 0 0
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "doctest" $ do
it "testSimple" $ do
doctest "." ["testSimple/Fib.hs"]
(cases 1)
it "failing" $ do
doctest "." ["failing/Foo.hs"]
(cases 1) {sFailures = 1}
it "skips subsequent examples from the same group if an example fails" $
doctest "." ["failing-multiple/Foo.hs"]
(cases 4) {sTried = 2, sFailures = 1}
it "testImport" $ do
doctest "testImport" ["ModuleA.hs"]
(cases 3)
doctest ".." ["-iintegration/testImport", "integration/testImport/ModuleA.hs"]
(cases 3)
it "testCommentLocation" $ do
doctest "." ["testCommentLocation/Foo.hs"]
(cases 11)
it "testPutStr" $ do
doctest "testPutStr" ["Fib.hs"]
(cases 3)
it "fails on multi-line expressions, introduced with :{" $ do
doctest "testFailOnMultiline" ["Fib.hs"]
(cases 2) {sErrors = 2}
it "testBlankline" $ do
doctest "testBlankline" ["Fib.hs"]
(cases 1)
it "examples from the same Haddock comment share the same scope" $ do
doctest "testCombinedExample" ["Fib.hs"]
(cases 4)
it "testDocumentationForArguments" $ do
doctest "testDocumentationForArguments" ["Fib.hs"]
(cases 1)
it "template-haskell" $ do
doctest "template-haskell" ["Foo.hs"]
(cases 2)
it "handles source files with CRLF line endings" $ do
doctest "dos-line-endings" ["Fib.hs"]
(cases 1)
it "runs $setup before each test group" $ do
doctest "setup" ["Foo.hs"]
(cases 2)
it "skips subsequent tests from a module, if $setup fails" $ do
doctest "setup-skip-on-failure" ["Foo.hs"]
(cases 3) {sTried = 1, sFailures = 1}
it "works with additional object files" $ do
doctest "with-cbits" ["Bar.hs", "../../../dist/build/spec/spec-tmp/test/integration/with-cbits/foo.o"]
(cases 1)
it "ignores trailing whitespace when matching test output" $ do
doctest "trailing-whitespace" ["Foo.hs"]
(cases 1)
describe "doctest as a runner for QuickCheck properties" $ do
it "runs a boolean property" $ do
doctest "property-bool" ["Foo.hs"]
(cases 1)
it "runs an explicitly quantified property" $ do
doctest "property-quantified" ["Foo.hs"]
(cases 1)
it "runs an implicitly quantified property" $ do
doctest "property-implicitly-quantified" ["Foo.hs"]
(cases 1)
it "reports a failing property" $ do
doctest "property-failing" ["Foo.hs"]
(cases 1) {sFailures = 1}
it "runs a boolean property with an explicit type signature" $ do
doctest "property-bool-with-type-signature" ["Foo.hs"]
(cases 1)
it "runs $setup before each property" $ do
doctest "property-setup" ["Foo.hs"]
(cases 3)
describe "doctest (regression tests)" $ do
it "bugfixWorkingDirectory" $ do
doctest "bugfixWorkingDirectory" ["Fib.hs"]
(cases 1)
doctest "bugfixWorkingDirectory" ["examples/Fib.hs"]
(cases 2)
it "bugfixOutputToStdErr" $ do
doctest "bugfixOutputToStdErr" ["Fib.hs"]
(cases 2)
it "bugfixImportHierarchical" $ do
doctest "bugfixImportHierarchical" ["ModuleA.hs", "ModuleB.hs"]
(cases 3)
it "bugfixMultipleModules" $ do
doctest "bugfixMultipleModules" ["ModuleA.hs"]
(cases 5)
it "testCPP" $ do
doctest "testCPP" ["-cpp", "Foo.hs"]
(cases 1) {sFailures = 1}
doctest "testCPP" ["-cpp", "-DFOO", "Foo.hs"]
(cases 1)
it "template-haskell-bugfix" $ do
doctest "template-haskell-bugfix" ["Main.hs"]
(cases 2)
|
ekmett/doctest
|
test/MainSpec.hs
|
Haskell
|
mit
| 4,830
|
{-
Copyright 2012-2013 Google Inc. 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.
-}
module Plush.Job (
-- * Shell Thread
startShell,
ShellThread,
-- * Jobs
submitJob,
pollJobs,
offerInput,
withHistory,
) where
import Control.Applicative ((<$>))
import Control.Concurrent
import Control.Monad (forM_, unless, void)
import qualified Control.Monad.Exception as Exception
import System.Exit
import System.Posix
import qualified System.Posix.Missing as PM
import Plush.Job.History
import Plush.Job.Output
import Plush.Job.StdIO
import Plush.Job.Types
import Plush.Run
import Plush.Run.Execute (execute)
import Plush.Run.ExecuteType (execType, ExecuteType(..))
import Plush.Run.Posix.Utilities (writeStr)
import Plush.Run.Script (parse)
import Plush.Run.ShellExec (getFlags, setFlags)
import qualified Plush.Run.ShellFlags as F
import Plush.Run.Types (statusExitCode)
-- | An opaque type, holding information about a running job.
-- See 'gatherOutput'
data RunningState = RS {
rsIO :: RunningIO
, rsProcessID :: Maybe ProcessID
, rsCheckDone :: IO ()
, rsHistory :: HistoryFile
}
-- | A job can be in one of these states:
data Status
= Running RunningState
-- ^ the 'RunningState' value can be used with 'gatherOutput'
| JobDone ExitCode [OutputItem]
-- ^ the exit status of the job, and any remaining gathered output
| ParseError String
-- ^ the command didn't parse
type ScoreBoard = [(JobName, Status)]
-- | A handle to the shell thread.
data ShellThread = ShellThread
{ stJobRequest :: MVar CommandRequest
, stScoreBoard :: MVar ScoreBoard
, stHistory :: MVar History
}
-- | Start the shell as an indpendent thread, which will process jobs and
-- report on their status.
--
-- N.B.: The shell uses 'stdout' and 'stderr' for its own purposes, and so after
-- the shell is stated, they must not be used for communicating. The returned
-- handles are tied to the original 'stdout' and 'stderr' and can be used to
-- communicate to the original streams.
startShell :: IO Runner -> IO (ShellThread, Fd, Fd)
startShell mkRunner = do
origInFd <- PM.dupFdCloseOnExec stdInput upperFd
origOutFd <- PM.dupFdCloseOnExec stdOutput upperFd
origErrFd <- PM.dupFdCloseOnExec stdError upperFd
reserveShellFds
foregroundStdIOParts <- makeStdIOParts
foregroundRIO <- stdIOLocalPrep foregroundStdIOParts
runner <- mkRunner
jobRequestVar <- newEmptyMVar
scoreBoardVar <- newMVar []
historyVar <- initHistory runner >>= newMVar
let st = ShellThread jobRequestVar scoreBoardVar historyVar
let childPrep = do
mapM_ closeFd [origInFd, origOutFd, origErrFd]
stdIOCloseMasters foregroundStdIOParts
_ <- forkIO $ shellThread st foregroundRIO origErrFd childPrep runner
return (st, origOutFd, origErrFd)
where
upperFd = Fd 20
-- | Reserve FDs 0 - 9 as these can addressed by shell commands.
reserveShellFds = do
devNullFd <- openFd "/dev/null" ReadWrite Nothing defaultFileFlags
forM_ [0..9] $ \fd -> do
unless (devNullFd == fd) $ void $ dupTo devNullFd fd
setFdOption fd CloseOnExec True
unless (devNullFd <= 0) $ closeFd devNullFd
shellThread :: ShellThread -> RunningIO -> Fd -> IO () -> Runner -> IO ()
shellThread st foregroundRIO origErrFd childPrep = go
where
go runner =
(takeMVar (stJobRequest st) >>= runJob' runner >>= go)
`Exception.catchAll`
(\e -> writeStr origErrFd (show e) >> go runner)
runJob' = runJob st foregroundRIO childPrep
runJob :: ShellThread -> RunningIO -> IO () -> Runner -> CommandRequest -> IO Runner
runJob st foregroundRIO childPrep r0
cr@(CommandRequest j record (CommandItem cmd)) = do
(pr, r1) <- run (parse cmd) r0
-- This won't echo even if verbose (-v) or parseout (-P) are set
case pr of
Left errs -> parseError errs >> return r1
Right (cl, _rest) -> do
(et, r2) <- run (execType cl) r1
case et of
ExecuteForeground -> foreground cl r2
ExecuteMidground -> background cl r2
ExecuteBackground -> foreground cl r2 -- TODO: fix!
where
foreground cl runner = do
setUp Nothing foregroundRIO (return ())
(status, runner') <- runCommand cl runner
cleanUp (return ()) $ statusExitCode status
return runner'
background cl runner = do
sp <- makeStdIOParts
pid <- forkProcess $ do
childPrep
stdIOChildPrep sp
(status, _runner') <- runCommand cl runner
exitWith $ statusExitCode status
rio <- stdIOMasterPrep sp
setUp (Just pid) rio $ checkUp (stdIOCloseMasters sp) pid
return runner
runCommand cl runner = run (runEnv $ execute cl) runner
runEnv act = if record
then act
else Exception.bracket getFlags setFlags $
\f -> setFlags (utilFlags f) >> act
-- If the command is not being recorded, it is being run by the
-- the front end itself. In this case, don't let the noexec (-n)
-- or xtrace (-x) interfere with the execution or output.
utilFlags f = f { F.noexec = False, F.xtrace = False }
parseError errs =
modifyMVar_ (stScoreBoard st) $ \sb ->
return $ (j, ParseError errs) : sb
setUp mpid rio checker = do
hFd <- modifyMVar (stHistory st) $ startHistory cr
let rs = RS rio mpid checker hFd
writeHistory (rsHistory rs) (HiCommand $ CommandItem cmd)
modifyMVar_ (stScoreBoard st) $ \sb ->
return $ (j, Running rs) : sb
checkUp closeMs pid = do
mStat <- getProcessStatus False False pid
case mStat of
Nothing -> return ()
Just (Exited ec) -> cleanUp closeMs ec
Just Terminated {} -> cleanUp closeMs $ ExitFailure 129
Just (Stopped _) -> return ()
cleanUp closeMs exitCode = do
modifyMVar_ (stScoreBoard st) $ \sb -> do
let (f,sb') = findJob j sb
case f of
Just (Running rs') -> do
oi <- gatherOutput rs'
writeHistory (rsHistory rs')
$ HiFinished $ FinishedItem exitCode
endHistory (rsHistory rs')
return $ (j, JobDone exitCode oi):sb'
_ -> return sb
closeMs
-- | Submit a job for processing.
-- N.B.: This may block until the shell thread is able to receive a request.
submitJob :: ShellThread -> CommandRequest -> IO ()
submitJob st cr = putMVar (stJobRequest st) cr
-- | Poll jobs for status. A `RunningItem` or `FinishedItem` is returned for
-- each job the shell knows about. `OutputItem` entries may be returned for
-- either kind of job, and will come first.
--
-- N.B.: Finished jobs are removed from internal book-keeping once reviewed.
pollJobs :: ShellThread -> IO [ReportOne StatusItem]
pollJobs st = do
readMVar (stScoreBoard st) >>= sequence_ . map checker
modifyMVar (stScoreBoard st) $ \sb -> do
r <- mapM (uncurry report) sb
return (filter running sb, concat r)
where
checker (_, Running rs) = rsCheckDone rs
checker _ = return ()
running (_, Running _) = True
running _ = False
report :: JobName -> Status -> IO [ReportOne StatusItem]
report job (Running rs) = do
ois <- gatherOutput rs
report' job ois $ SiRunning RunningItem
report job (JobDone e ois) =
report' job ois $ SiFinished (FinishedItem e)
report job (ParseError e) = return $ map (ReportOne job)
[ SiParseError (ParseErrorItem e)
, SiFinished (FinishedItem $ ExitFailure 2)
]
report' job ois si = return $ map (ReportOne job) $ map SiOutput ois ++ [si]
-- | Gather as much output is available from stdout, stderr, and jsonout.
-- Note that the order of output to stderr and stdout is lost given the way we
-- collect these from separate pttys. This infelicity is the trade off for being
-- able which text came from stderr vs. stdout. stderr is gathered and reported
-- which tends to work better. It also ensures that xtrace (-x) output preceeds
-- the command's output.
gatherOutput :: RunningState -> IO [OutputItem]
gatherOutput rs = do
err <- wrap OutputItemStdErr <$> getAvailable (rioStdErr $ rsIO rs)
out <- wrap OutputItemStdOut <$> getAvailable (rioStdOut $ rsIO rs)
jout <- wrap OutputItemJsonOut <$> getAvailable (rioJsonOut $ rsIO rs)
let ois = err ++ out ++ jout
mapM_ (writeOutput (rsHistory rs)) ois
return ois
where
wrap _ [] = []
wrap c vs = [c vs]
-- | Find a job by name in a 'ScoreBoard'. Returns the first 'Status' found,
-- if any, and a copy of the 'ScoreBoard' without that job enry.
findJob :: JobName -> ScoreBoard -> (Maybe Status, ScoreBoard)
findJob j ((j',s):sbs) | j == j' = (Just s,sbs)
findJob j (sb:sbs) = let (s,sbs') = findJob j sbs in (s,sb:sbs')
findJob _ [] = (Nothing,[])
-- | Give input to a running job. If the job isn't running, then the input is
-- dropped on the floor.
offerInput :: ShellThread -> JobName -> InputItem -> IO ()
offerInput st job input = modifyMVar_ (stScoreBoard st) $ \sb -> do
case findJob job sb of
(Just (Running rs), _) -> send input rs
-- TODO: should catch errors here
_ -> return ()
return sb
where
send (InputItemInput s) rs = writeStr (rioStdIn $ rsIO rs) s
send (InputItemEof) rs = closeFd (rioStdIn $ rsIO rs)
send (InputItemSignal sig) rs =
maybe (return ()) (signalProcess sig) $ rsProcessID rs
-- | Wrapper for adapting functions on History.
withHistory :: ShellThread -> (History -> IO a) -> IO a
withHistory st = withMVar (stHistory st)
|
kustomzone/plush
|
src/Plush/Job.hs
|
Haskell
|
apache-2.0
| 10,433
|
{-# OPTIONS -Wall #-}
module Examples.HMM where
import Prelude hiding (Real)
import Language.Hakaru.Syntax
import Language.Hakaru.Expect (Expect(..))
import Language.Hakaru.Sample (Sample(..))
import System.Random.MWC (withSystemRandom)
import Control.Monad (replicateM)
import Data.Number.LogFloat (LogFloat)
-- Conditional probability tables (ignore Expect and unExpect on first reading)
type Table = Vector (Vector Prob)
reflect :: (Mochastic repr, Lambda repr, Integrate repr) =>
repr Table -> Expect repr (Int -> Measure Int)
reflect m = lam (\i -> let v = index (Expect m) i
in weight (summateV v) (categorical v))
reify :: (Mochastic repr, Lambda repr, Integrate repr) =>
repr Int -> repr Int ->
Expect repr (Int -> Measure Int) -> repr Table
reify domainSize rangeSize m =
vector domainSize (\i ->
vector rangeSize (\j ->
app (snd_ (app (unExpect m) i)) (lam (\j' -> if_ (equal j j') 1 0))))
--------------------------------------------------------------------------------
-- Model: A one-dimensional random walk among 20 discrete states (numbered
-- 0 through 19 and arranged in a row) starting at state 10 at time 0.
-- Query: Given that the state is less than 8 at time 6,
-- what's the posterior distribution over states at time 12?
type Time = Int
type State = Int
-- hmm is a model that disintegration might produce: it already incorporates
-- the observed data, hence "emission ... bind_ ... unit".
hmm :: (Mochastic repr, Lambda repr) => repr (Measure State)
hmm = liftM snd_ (app (chain (vector (12+1) $ \t ->
lam $ \s ->
emission t s `bind_`
transition s `bind` \s' ->
dirac (pair unit s')))
10)
emission :: (Mochastic repr) =>
repr Time -> repr State -> repr (Measure ())
emission t s = if_ (equal t 6)
(if_ (less s 8) (dirac unit) (superpose []))
(dirac unit)
transition :: (Mochastic repr) => repr State -> repr (Measure State)
transition s = categorical (vector 20 (\s' ->
if_ (and_ [less (s-2) s', less s' (s+2)]) 1 0))
-- Because our observed data has substantial probability (unlike in practice),
-- we can even sample blindly to answer the query approximately.
try :: IO [Maybe (Int, LogFloat)]
try = replicateM 100
$ withSystemRandom
$ unSample (hmm :: Sample IO (Measure State)) 1
-- Using the default implementation of "chain" in terms of "reduce",
-- and eliminating the "unit"s, we can simplify "hmm" to
hmm' :: (Mochastic repr, Lambda repr) => repr (Measure State)
hmm' = app (chain' (vector 13 $ \t ->
lam $ \s ->
emission t s `bind_`
transition s `bind` \s' ->
dirac s'))
10
chain' :: (Mochastic repr, Lambda repr) =>
repr (Vector (a -> Measure a)) -> repr (a -> Measure a)
chain' = reduce bindo (lam dirac)
-- in which the type of reduced elements is "State -> Measure State".
-- To compute this exactly in polynomial time, we just need to represent these
-- elements as tables instead. That is, we observe that all our values of type
-- "State -> Measure State" have the form "reflect m", and
-- bindo (reflect m) (reflect n) == reflect (bindo' m n)
-- in which bindo', defined below, runs in polynomial time given m and n.
-- So we can simplify "hmm'" to
hmm'' :: (Mochastic repr, Lambda repr, Integrate repr) =>
Expect repr (Measure State)
hmm'' = app (reflect (chain'' (vector 13 $ \t ->
reify 20 20 $
lam $ \s ->
emission (Expect t) s `bind_`
transition s `bind` \s' ->
dirac s')))
10
chain'' :: (Mochastic repr, Lambda repr, Integrate repr) =>
repr (Vector Table) -> repr Table
chain'' = reduce bindo' (reify 20 20 (lam dirac))
bindo' :: (Mochastic repr, Lambda repr, Integrate repr) =>
repr Table -> repr Table -> repr Table
bindo' m n = reify 20 20 (bindo (reflect m) (reflect n))
-- Of course bindo' can be optimized a lot further internally, but this is the
-- main idea. We are effectively multiplying matrix*matrix*...*matrix*vector,
-- so it would also be better to associate these multiplications to the right.
|
bitemyapp/hakaru
|
Examples/HMM.hs
|
Haskell
|
bsd-3-clause
| 4,483
|
module HLearn.Models.Classifiers.Perceptron
where
import qualified Data.Map as Map
import qualified Data.Vector.Unboxed as VU
import HLearn.Algebra
import HLearn.Models.Distributions
import HLearn.Models.Classifiers.Common
import HLearn.Models.Classifiers.Centroid
import HLearn.Models.Classifiers.NaiveNN
-------------------------------------------------------------------------------
-- data structures
data Perceptron label dp = Perceptron
{ centroids :: Map.Map label (Centroid dp)
}
-- deriving (Read,Show,Eq,Ord)
deriving instance (Show (Centroid dp), Show label) => Show (Perceptron label dp)
-------------------------------------------------------------------------------
-- algebra
instance (Ord label, Monoid (Centroid dp)) => Monoid (Perceptron label dp) where
mempty = Perceptron mempty
p1 `mappend` p2 = Perceptron
{ centroids = Map.unionWith (<>) (centroids p1) (centroids p2)
}
-------------------------------------------------------------------------------
-- model
instance
( Monoid dp
, Num (Scalar dp)
, Ord label
) => HomTrainer (Perceptron label dp)
where
type Datapoint (Perceptron label dp) = (label,dp)
train1dp (label,dp) = Perceptron $ Map.singleton label $ train1dp dp
-------------------------------------------------------------------------------
-- classification
instance Probabilistic (Perceptron label dp) where
type Probability (Perceptron label dp) = Scalar dp
-- instance
-- ( Ord label
-- , Ord (Scalar dp)
-- , MetricSpace (Centroid dp)
-- , Monoid dp
-- , HasScalar dp
-- , label ~ Scalar dp
-- ) => ProbabilityClassifier (Perceptron label dp)
-- where
-- type ResultDistribution (Perceptron label dp) = (Categorical (Scalar dp) label)
--
-- probabilityClassify model dp = probabilityClassify nn (train1dp (dp) :: Centroid dp)
-- where
-- nn = NaiveNN $ Map.toList $ centroids model
--
-- instance
-- ( ProbabilityClassifier (Perceptron label dp)
-- , Ord dp
-- , Ord (Scalar dp)
-- , Ord label
-- , Num (Scalar dp)
-- ) => Classifier (Perceptron label dp)
-- where
-- classify model dp = mean $ probabilityClassify model dp
|
iamkingmaker/HLearn
|
src/HLearn/Models/Classifiers/Perceptron.hs
|
Haskell
|
bsd-3-clause
| 2,296
|
{-# LANGUAGE FlexibleContexts #-}
-- | Likes handling
-- <http://instagram.com/developer/endpoints/likes/#>
module Instagram.Likes (
getLikes
,like
,unlike
)where
import Instagram.Monad
import Instagram.Types
import qualified Network.HTTP.Types as HT
-- | Get a list of users who have liked this media.
getLikes :: (MonadBaseControl IO m, MonadResource m) => MediaID
-> Maybe OAuthToken
-> InstagramT m (Envelope [User])
getLikes mid token =getGetEnvelopeM ["/v1/media/",mid,"/likes"] token ([]::HT.Query)
-- | Set a like on this media by the currently authenticated user.
like :: (MonadBaseControl IO m, MonadResource m) => MediaID
-> OAuthToken
-> InstagramT m (Envelope NoResult)
like mid token =getPostEnvelope ["/v1/media/",mid,"/likes"] token ([]::HT.Query)
-- | Remove a like on this media by the currently authenticated user.
unlike :: (MonadBaseControl IO m, MonadResource m) => MediaID
-> OAuthToken
-> InstagramT m (Envelope NoResult)
unlike mid token =getDeleteEnvelope ["/v1/media/",mid,"/likes"] token ([]::HT.Query)
|
potomak/ig
|
src/Instagram/Likes.hs
|
Haskell
|
bsd-3-clause
| 1,068
|
-------------------------------------------------------------------------------
-- |
-- Module : OpenAI.Gym.Data
-- License : BSD3
-- Stability : experimental
-- Portability: non-portable
-------------------------------------------------------------------------------
module Data.Gym
where
{-
( GymEnv (..)
, InstID (..)
, Environment (..)
, Observation (..)
, Step (..)
, Outcome (..)
, Info (..)
, Action (..)
, Monitor (..)
, Config (..)
) where
import Reinforce.Prelude
import Data.HashMap.Strict
import Data.Aeson -- ((.=), ToJSON(..), FromJSON(..))
data GymEnv
-- | Classic Control Environments
= CartPoleV0 -- ^ Balance a pole on a cart (for a short time).
| CartPoleV1 -- ^ Balance a pole on a cart.
| AcrobotV1 -- ^ Swing up a two-link robot.
| MountainCarV0 -- ^ Drive up a big hill.
| MountainCarContinuousV0 -- ^ Drive up a big hill with continuous control.
| PendulumV0 -- ^ Swing up a pendulum.
-- Toy text games
| FrozenLakeV0 -- ^ Swing up a pendulum.
-- | Atari Games
| PongRamV0 -- ^ Maximize score in the game Pong, with RAM as input
| PongV0 -- ^ Maximize score in the game Pong
deriving (Eq, Enum, Ord)
instance Show GymEnv where
show CartPoleV0 = "CartPole-v0"
show CartPoleV1 = "CartPole-v1"
show AcrobotV1 = "Acrobot-v1"
show MountainCarV0 = "MountainCar-v0"
show MountainCarContinuousV0 = "MountainCarContinuous-v0"
show PendulumV0 = "Pendulum-v0"
show FrozenLakeV0 = "FrozenLake-v0"
show PongRamV0 = "Pong-ram-v0"
show PongV0 = "Pong-v0"
instance ToJSON GymEnv where
toJSON env = object [ "env_id" .= show env ]
data InstID = InstID !Text
deriving (Eq, Show, Generic)
instance ToJSON InstID where
toJSON (InstID i) = toSingleton "instance_id" i
instance FromJSON InstID where
parseJSON = parseSingleton InstID "instance_id"
newtype Environment = Environment { all_envs :: HashMap Text Text }
deriving (Eq, Show, Generic)
instance ToJSON Environment
instance FromJSON Environment
data Observation = Observation !Value
deriving (Eq, Show, Generic)
instance ToJSON Observation where
toJSON (Observation v) = toSingleton "observation" v
instance FromJSON Observation where
parseJSON = parseSingleton Observation "observation"
data Step = Step
{ action :: !Value
, render :: !Bool
} deriving (Eq, Generic, Show)
instance ToJSON Step
data Outcome = Outcome
{ observation :: !Value
, reward :: !Double
, done :: !Bool
, info :: !Object
} deriving (Eq, Show, Generic)
instance ToJSON Outcome
instance FromJSON Outcome
data Info = Info !Object
deriving (Eq, Show, Generic)
instance ToJSON Info where
toJSON (Info v) = toSingleton "info" v
instance FromJSON Info where
parseJSON = parseSingleton Info "info"
data Action = Action !Value
deriving (Eq, Show, Generic)
instance ToJSON Action where
toJSON (Action v) = toSingleton "action" v
instance FromJSON Action where
parseJSON = parseSingleton Action "action"
data Monitor = Monitor
{ directory :: !Text
, force :: !Bool
, resume :: !Bool
, video_callable :: !Bool
} deriving (Generic, Eq, Show)
instance ToJSON Monitor
data Config = Config
{ training_dir :: !Text
, algorithm_id :: !Text
, api_key :: !Text
} deriving (Generic, Eq, Show)
instance ToJSON Config
-}
|
stites/reinforce
|
reinforce-environments/src/Data/Gym.hs
|
Haskell
|
bsd-3-clause
| 3,572
|
-- | Interface to the management event bus.
module Control.Distributed.Process.Management.Internal.Bus
( publishEvent
) where
import Control.Distributed.Process.Internal.CQueue
( enqueue
)
import Control.Distributed.Process.Internal.Types
( MxEventBus(..)
, Message
)
import Data.Foldable (forM_)
import System.Mem.Weak (deRefWeak)
publishEvent :: MxEventBus -> Message -> IO ()
publishEvent MxEventBusInitialising _ = return ()
publishEvent (MxEventBus _ _ wqRef _) msg = do
mQueue <- deRefWeak wqRef
forM_ mQueue $ \queue -> enqueue queue msg
|
qnikst/distributed-process
|
src/Control/Distributed/Process/Management/Internal/Bus.hs
|
Haskell
|
bsd-3-clause
| 571
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sr-SP">
<title>Groovy Support</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/groovy/src/main/javahelp/org/zaproxy/zap/extension/groovy/resources/help_sr_SP/helpset_sr_SP.hs
|
Haskell
|
apache-2.0
| 959
|
-- Refactoring: move myFringe to module D3. This example aims to test the change of qualifiers,
-- and the import/exports.
module C3(Tree(..), SameOrNot(..)) where
data Tree a = Leaf a | Branch (Tree a) (Tree a)
sumTree:: (Num a) => Tree a -> a
sumTree (Leaf x ) = x
sumTree (Branch left right) = sumTree left + sumTree right
class SameOrNot a where
isSame :: a -> a -> Bool
isNotSame :: a -> a -> Bool
instance SameOrNot Int where
isSame a b = a == b
isNotSame a b = a /= b
|
SAdams601/HaRe
|
old/testing/moveDefBtwMods/C3_TokOut.hs
|
Haskell
|
bsd-3-clause
| 500
|
import Control.Concurrent
import Control.Exception
-- Test blocking of async exceptions in an exception handler.
-- The exception raised in the main thread should not be delivered
-- until the first exception handler finishes.
main = do
main_thread <- myThreadId
m <- newEmptyMVar
forkIO (do { takeMVar m; throwTo main_thread (ErrorCall "foo") })
(do { throwIO (ErrorCall "wibble")
`Control.Exception.catch`
(\e -> let _ = e::ErrorCall in
do putMVar m (); evaluate (sum [1..10000]); putStrLn "done.")
; myDelay 500000 })
`Control.Exception.catch`
\e -> putStrLn ("caught: " ++ show (e::SomeException))
-- compensate for the fact that threadDelay is non-interruptible
-- on Windows with the threaded RTS in 6.6.
myDelay usec = do
m <- newEmptyMVar
forkIO $ do threadDelay usec; putMVar m ()
takeMVar m
|
tjakway/ghcjvm
|
testsuite/tests/concurrent/should_run/conc014.hs
|
Haskell
|
bsd-3-clause
| 864
|
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies,
FlexibleInstances, UndecidableInstances #-}
-- UndecidableInstances now needed because the Coverage Condition fails
module ShouldFail where
-- A stripped down functional-dependency
-- example that causes GHC 4.08.1 to crash with:
-- "basicTypes/Var.lhs:194: Non-exhaustive patterns in function readMutTyVar"
-- Reported by Thomas Hallgren Nov 00
-- July 07: I'm changing this from "should fail" to "should succeed"
-- See Note [Important subtlety in oclose] in FunDeps
primDup :: Int -> IO Int
primDup = undefined
dup () = call primDup
-- call :: Call c h => c -> h
--
-- call primDup :: {Call (Int -> IO Int) h} => h with
-- Using the instance decl gives
-- call primDup :: {Call (IO Int) h'} => Int -> h'
-- The functional dependency means that h must be constant
-- Hence program is rejected because it can't find an instance
-- for {Call (IO Int) h'}
class Call c h | c -> h where
call :: c -> h
instance Call c h => Call (Int->c) (Int->h) where
call f = call . f
|
lukexi/ghc-7.8-arm64
|
testsuite/tests/typecheck/should_fail/tcfail093.hs
|
Haskell
|
bsd-3-clause
| 1,075
|
#! /usr/bin/env nix-shell
#! nix-shell ./shell.nix -i runghc
import Distribution.Simple
main = defaultMain
|
k0001/haskell-money
|
safe-money/Setup.hs
|
Haskell
|
bsd-3-clause
| 107
|
{-# OPTIONS_GHC -Wall -Werror #-}
module ManySecond where
|
holzensp/ghc
|
testsuite/tests/driver/dynamic_flags_002/ManySecond.hs
|
Haskell
|
bsd-3-clause
| 61
|
module Sudoku where
import Data.Maybe (catMaybes, fromJust, isJust, listToMaybe)
import Data.List ((\\), transpose)
type SudokuVal = Int -- The type representing Sudoku values
type EmptyPuzzle = [[ Maybe SudokuVal ]] -- A matrix where Nothing values represent unknowns.
-- The matrix is a list of rows, where each row is
-- a list of values.
type Puzzle = [[ SudokuVal ]] -- A matrix of final Int values. Stored as a list of
-- rows, where each row is a list of values.
-- | Solves a sudoku puzzle, receiving a matrix of Maybe values and returning a
-- matrix of final values
sudoku :: EmptyPuzzle -> Puzzle
sudoku puzzle
| isJust solvedPuzzle = map (map fromJust) $ fromJust solvedPuzzle
| otherwise = error "This puzzle has no solution!"
where solvedPuzzle = populatePuzzle (0, 0) puzzle
-- | Fills the given coordinate, with a valid number for the spot. If there are no
-- valid possibilities, return Nothing
populatePuzzle :: (Int, Int) -> EmptyPuzzle -> Maybe EmptyPuzzle
-- base case on last square in the puzzle
populatePuzzle (8,8) puzzle
| isJust elem = setAsJust elem
| null possible = Nothing
| otherwise = setAsJust (Just $ head possible)
where elem = getElem puzzle (8,8)
possible = getPossible puzzle (8,8)
setAsJust = Just . setElem puzzle (8,8)
-- recursive case for all other squares
populatePuzzle (i,j) puzzle
| isJust elem = setAndCall elem
| null possible = Nothing
| otherwise = if null nextPuzzles
then Nothing
else head nextPuzzles
where elem = getElem puzzle (i,j)
possible = getPossible puzzle (i,j)
setAndCall = populatePuzzle (nextCoord (i,j)) . setElem puzzle (i,j)
nextPuzzles = filter isJust [ setAndCall $ Just elem | elem <- possible ]
-- | Gets all possible values for the given coordinate
getPossible :: EmptyPuzzle -> (Int, Int) -> [Int]
getPossible puzzle (i,j) = (([1..9] \\ getRowVals) \\ getColVals) \\ getSquareVals
where getRowVals = catMaybes $ getRow puzzle i
getColVals = catMaybes $ getCol puzzle j
getSquareVals = catMaybes $ getSquare puzzle (i,j)
------------------------
----- PUZZLE UTILS -----
-- | Gets the row at the given index in the matrix
getRow :: [[a]] -> Int -> [a]
getRow matrix i = matrix !! i
-- | Gets the col at the given index in the matrix
getCol :: [[a]] -> Int -> [a]
getCol matrix j = (transpose matrix) !! j
-- | Gets the square that contains the given index in the matrix
getSquare :: [[a]] -> (Int, Int) -> [a]
getSquare matrix (i,j) = [getElem matrix (x,y) | x <- rows, y <- cols]
where rows = [ (getStart i) .. (getStart i)+2 ]
cols = [ (getStart j) .. (getStart j)+2 ]
getStart val = 3 * (val `quot` 3)
-- | Gets the element at the given coordinate in the matrix
getElem :: [[a]] -> (Int, Int) -> a
getElem matrix (i,j) = (getRow matrix i) !! j
-- | Sets the element at the given coordinate in the matrix
setElem :: [[a]] -> (Int, Int) -> a -> [[a]]
setElem matrix (i,j) val = let (prevRows, row:nextRows) = splitAt i matrix
(prevCols, _:nextCols) = splitAt j row
in prevRows ++ (prevCols ++ val : nextCols) : nextRows
-- | Gets the next coordinate to the given coordinate
nextCoord :: (Int, Int) -> (Int, Int)
nextCoord (i,8) = (i+1, 0)
nextCoord (i,j) = (i, j+1)
|
brandonchinn178/sudoku
|
src/Sudoku.hs
|
Haskell
|
mit
| 3,674
|
module Test.Hspec.Core.Formatters.Pretty.Unicode (
ushow
, ushows
) where
import Prelude ()
import Test.Hspec.Core.Compat
import Data.Char
ushow :: String -> String
ushow xs = ushows xs ""
ushows :: String -> ShowS
ushows = uShowString
uShowString :: String -> ShowS
uShowString cs = showChar '"' . showLitString cs . showChar '"'
showLitString :: String -> ShowS
showLitString [] s = s
showLitString ('"' : cs) s = showString "\\\"" (showLitString cs s)
showLitString (c : cs) s = uShowLitChar c (showLitString cs s)
uShowLitChar :: Char -> ShowS
uShowLitChar c
| isPrint c && not (isAscii c) = showChar c
| otherwise = showLitChar c
|
hspec/hspec
|
hspec-core/src/Test/Hspec/Core/Formatters/Pretty/Unicode.hs
|
Haskell
|
mit
| 688
|
myTuple = (8, 11)
fst' = fst myTuple
snd' = snd myTuple
-- the zip function will merge two lists into tuples
zip' = zip [1,2,3,4,5] [5,5,5,5,5]
lazyZip = zip [1.. ] ["one", "two", "three", "four", "five"]
--triangles problem
triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ]
rightTriangles = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2]
rightTrianglesPerimeter x = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == x]
|
luisgepeto/HaskellLearning
|
02 Starting Out/06_tuples.hs
|
Haskell
|
mit
| 500
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module IHaskell.Display.Widgets.Box.SelectionContainer.Tab
( -- * The Tab widget
TabWidget
-- * Constructor
, mkTab
) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (void)
import Data.Aeson
import Data.IORef (newIORef)
import qualified Data.Scientific as Sci
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
import IHaskell.Display.Widgets.Layout.LayoutWidget
-- | A 'TabWidget' represents a Tab widget from IPython.html.widgets.
type TabWidget = IPythonWidget 'TabType
-- | Create a new box
mkTab :: IO TabWidget
mkTab = do
-- Default properties, with a random uuid
wid <- U.random
layout <- mkLayout
let widgetState = WidgetState $ defaultSelectionContainerWidget "TabView" "TabModel" layout
stateIO <- newIORef widgetState
let box = IPythonWidget wid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen box $ toJSON widgetState
-- Return the widget
return box
instance IHaskellWidget TabWidget where
getCommUUID = uuid
comm widget val _ =
case nestedObjectLookup val ["state", "selected_index"] of
Just (Number num) -> do
void $ setField' widget SelectedIndex $ Just (Sci.coefficient num)
triggerChange widget
Just Null -> do
void $ setField' widget SelectedIndex Nothing
triggerChange widget
_ -> pure ()
|
gibiansky/IHaskell
|
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Box/SelectionContainer/Tab.hs
|
Haskell
|
mit
| 1,810
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.Either.Unwrap
-- Copyright : (c) Gregory Crosswhite
-- License : BSD-style
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Functions for probing and unwrapping values inside of Either.
--
-----------------------------------------------------------------------------
module Data.Either.Unwrap
( isLeft
, isRight
, fromLeft
, fromRight
, eitherM
, whenLeft
, whenRight
, unlessLeft
, unlessRight
) where
-- ---------------------------------------------------------------------------
-- Functions over Either
-- |The 'isLeft' function returns 'True' iff its argument is of the form @Left _@.
isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft _ = False
-- |The 'isRight' function returns 'True' iff its argument is of the form @Right _@.
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
-- | The 'fromLeft' function extracts the element out of a 'Left' and
-- throws an error if its argument take the form @Right _@.
fromLeft :: Either a b -> a
fromLeft (Right _) = error "Either.Unwrap.fromLeft: Argument takes form 'Right _'" -- yuck
fromLeft (Left x) = x
-- | The 'fromRight' function extracts the element out of a 'Right' and
-- throws an error if its argument take the form @Left _@.
fromRight :: Either a b -> b
fromRight (Left _) = error "Either.Unwrap.fromRight: Argument takes form 'Left _'" -- yuck
fromRight (Right x) = x
-- | The 'eitherM' function takes an 'Either' value and two functions which return monads.
-- If the argument takes the form @Left _@ then the element within is passed to the first
-- function, otherwise the element within is passed to the second function.
eitherM :: Monad m => Either a b -> (a -> m c) -> (b -> m c) -> m c
eitherM (Left x) f _ = f x
eitherM (Right x) _ f = f x
-- | The 'whenLeft' function takes an 'Either' value and a function which returns a monad.
-- The monad is only executed when the given argument takes the form @Left _@, otherwise
-- it does nothing.
whenLeft :: Monad m => Either a b -> (a -> m ()) -> m ()
whenLeft (Left x) f = f x
whenLeft _ _ = return ()
-- | The 'whenLeft' function takes an 'Either' value and a function which returns a monad.
-- The monad is only executed when the given argument takes the form @Right _@, otherwise
-- it does nothing.
whenRight :: Monad m => Either a b -> (b -> m ()) -> m ()
whenRight (Right x) f = f x
whenRight _ _ = return ()
-- | A synonym of 'whenRight'.
unlessLeft :: Monad m => Either a b -> (b -> m ()) -> m ()
unlessLeft = whenRight
-- | A synonym of 'whenLeft'.
unlessRight :: Monad m => Either a b -> (a -> m ()) -> m ()
unlessRight = whenLeft
|
Spawek/HCPParse
|
src/Data/Either/Unwrap.hs
|
Haskell
|
mit
| 2,954
|
-- Prints Hello World N Times
--
hello_worlds 0 = return()
hello_worlds n = do
putStrLn "Hello World"
hello_worlds (n-1)
-- Complete this function
-- This part is related to the Input/Output and can be used as it is
-- Do not modify it
main = do
n <- readLn :: IO Int
hello_worlds n
|
jmeline/secret-meme
|
hackerrank/functional_programming/haskell/hello_world_n.hs
|
Haskell
|
mit
| 304
|
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
import Control.Applicative
import Control.Monad
import Control.Monad.Reader
import qualified GHCJS.Types as T
import qualified GHCJS.Foreign as F
import qualified GHCJS.Marshal as M
import WebGL
import Simple
fragmentShaderSrc = [src|
precision mediump float;
varying vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
|]
vertexShaderSrc = [src|
attribute vec3 aVertexPosition;
attribute vec4 aVertexColor;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
varying vec4 vColor;
void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
vColor = aVertexColor;
}
|]
data GLInfo = GLInfo { glContext :: GL
, glWidth :: Int
, glHeight :: Int
}
data ColorShader = ColorShader { wsProgram :: ShaderProgram
, wsVertexP :: ShaderAttribute
, sVertexColor :: ShaderAttribute
, wsPMatrix :: ShaderUniform
, wsMVMatrix :: ShaderUniform
}
initGL :: Canvas -> IO GLInfo
initGL canvas = GLInfo <$> js_getContext canvas <*> js_getCanvasWidth canvas <*> js_getCanvasHeight canvas
-- We could use an extra type for a compiled shader... Maybe later.
makeShaders :: GLIO (Shader VertexShader, Shader FragmentShader)
makeShaders = do
fragmentShader <- makeShader fragmentShaderSrc createFragmentShader
vertexShader <- makeShader vertexShaderSrc createVertexShader
return (vertexShader, fragmentShader)
makeProgram :: (Shader VertexShader, Shader FragmentShader) -> GLIO ColorShader
makeProgram (vertexShader, fragmentShader) = do
program <- buildProgram vertexShader fragmentShader
useProgram program
vertexPosition <- getAttribLocation program $ glStr "aVertexPosition"
vertexColor <- getAttribLocation program $ glStr "aVertexColor"
pMatrixU <- getUniformLocation program (glStr "uPMatrix")
mvMatrixU <- getUniformLocation program (glStr "uMVMatrix")
enableVAA vertexPosition
enableVAA vertexColor
return $ ColorShader program vertexPosition vertexColor pMatrixU mvMatrixU
initBuffers :: GLIO (BufferInfo, BufferInfo, BufferInfo, BufferInfo)
initBuffers = do
triangle <- toBuffer $ V3L [ ( 0.0, 1.0, 0.0)
, (-1.0, -1.0, 0.0)
, (1.0, -1.0, 0.0)
]
square <- toBuffer $ V3L [ ( 1.0, 1.0, 0.0)
, (-1.0, 1.0, 0.0)
, ( 1.0, -1.0, 0.0)
, (-1.0, -1.0, 0.0)
]
triangleColors <- toBuffer $ V4L [ (1.0, 0.0, 0.0, 1.0)
, (0.0, 1.0, 0.0, 1.0)
, (0.0, 0.0, 1.0, 1.0)
]
squareColors <- toBuffer $ V4L $ replicate 4 (0.5, 0.5, 1.0, 1.0)
return (triangle, square, triangleColors, squareColors)
drawScene :: (Int, Int) -> ColorShader -> (BufferInfo, BufferInfo, BufferInfo, BufferInfo) -> GLIO ()
drawScene (width, height) shader (triangle, square, triangleColors, squareColors) = do
clear
viewport 0 0 width height
-- This will run without the call to viewport
moveMatrix <- mat4
positionMatrix <- mat4
mat4perspective 45 (fromIntegral width / fromIntegral height) 0.1 100.0 positionMatrix
mat4identity moveMatrix
-- move is a 3-element list...
-- Some of the types here are still quite loose.
let moveAndDraw move shape colors = do
mat4translate moveMatrix =<< glList move
bindBuffer arrayBuffer (buffer shape)
vertexAttribPointer (wsVertexP shader) (itemSize shape)
bindBuffer arrayBuffer (buffer colors)
vertexAttribPointer (sVertexColor shader) (itemSize colors)
uniformMatrix4fv (wsPMatrix shader) positionMatrix
uniformMatrix4fv (wsMVMatrix shader) moveMatrix
-- The original draws 'triangles' for the triangle and a strip for the square...
-- Probably for didactic reasons. We can refactor that out when we need to.
drawArrays drawTriangleStrip 0 (numItems shape)
moveAndDraw [-1.4, 0.0, -7.0] triangle triangleColors
moveAndDraw [3.0, 0.0, 0.0] square squareColors
main = runLesson1 =<< initGL =<< js_documentGetElementById "lesson01-canvas"
runLesson1 glInfo = flip runReaderT (glContext glInfo) $ do
clearColor 0.0 0.0 0.0 1.0
enableDepthTest
shaderProgram <- makeProgram =<< makeShaders
buffers <- initBuffers
drawScene (glWidth glInfo, glHeight glInfo) shaderProgram buffers
|
jmillikan/webgl-lessons-ghcjs
|
src/Lesson02.hs
|
Haskell
|
mit
| 4,723
|
module Tach.Wavelet.Core where
import Tach.Wavelet.Core.Internal
|
smurphy8/tach
|
core-libs/tach-wavelet-core/src/Tach/Wavelet/Core.hs
|
Haskell
|
mit
| 66
|
{-# LANGUAGE DeriveGeneric #-}
module Data.Monoid.Colorful.Term (
Term(..)
, getTerm
, hGetTerm
) where
import Data.List (isPrefixOf, isInfixOf)
import System.Environment (getEnv)
import System.IO (Handle, hIsTerminalDevice, stdout)
import GHC.Generics (Generic)
-- | Terminal type. For less capable terminals the color depth is automatically reduced.
data Term
= TermDumb -- ^ Dumb terminal - no color output
| Term8 -- ^ 8 colors supported
| Term256 -- ^ 256 colors supported
| TermRGB -- ^ True colors supported
| TermWin -- ^ Windows terminal. Will use emulation (Not yet implemented).
deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic)
getTerm :: IO Term
getTerm = hGetTerm stdout
-- | The action @(hGetTerm handle)@ determines the terminal type of the file @handle@.
--
-- The terminal type is determined by checking if the file handle points to a device
-- and by looking at the @$TERM@ environment variable.
hGetTerm :: Handle -> IO Term
hGetTerm h = do
term <- hIsTerminalDevice h
if term
then envToTerm <$> getEnv "TERM"
else pure TermDumb
-- | Determine the terminal type from the value of the @$TERM@ environment variable.
-- TODO improve this
envToTerm :: String -> Term
envToTerm "dumb" = TermDumb
envToTerm term | any (`isPrefixOf` term) rgbTerminals = TermRGB
| "256" `isInfixOf` term = Term256
| otherwise = Term8
where rgbTerminals = ["xterm", "konsole", "gnome", "st", "linux"]
|
minad/colorful-monoids
|
src/Data/Monoid/Colorful/Term.hs
|
Haskell
|
mit
| 1,476
|
module GearScript.AST where
data Type = Type
{ typeName :: String
, typeParent :: Maybe Type
}
deriving (Show, Eq)
data Typed a = Typed
{ typedType :: Maybe Type
, typedVal :: a
}
data TopStatement = FunctionDef
{ functionName :: String
, functionArguments :: [String]
, functionBody :: [Statement]
}
| TopPlainStatement Statement
deriving (Show, Eq)
data Statement = ExprStatement Expression
deriving (Show, Eq)
data Expression = Call
{ callObject :: Maybe Expression
, callFunctionName :: String
, callArguments :: [Expression]
}
| GlobalVariable String
| LocalVariable String
| StringLiteral String
| NumberLiteral Double
| Plus Expression Expression
| Minus Expression Expression
| Mult Expression Expression
| Div Expression Expression
| Mod Expression Expression
deriving (Show, Eq)
|
teozkr/GearScript
|
src/GearScript/AST.hs
|
Haskell
|
mit
| 1,237
|
-- | Debugging functions.
module RWPAS.Debug
( logShow )
where
import Control.Concurrent
import System.IO
import System.IO.Unsafe
logLock :: MVar ()
logLock = unsafePerformIO $ newMVar ()
{-# NOINLINE logLock #-}
logShow :: Show a => a -> b -> b
logShow thing result = unsafePerformIO $ withMVar logLock $ \_ -> do
withFile "debug_log.txt" AppendMode $ \handle ->
hPrint handle thing
return result
|
Noeda/rwpas
|
src/RWPAS/Debug.hs
|
Haskell
|
mit
| 415
|
-- http://www.codewars.com/kata/5266876b8f4bf2da9b000362
module Likes where
likes :: [String] -> String
likes [] = "no one likes this"
likes (x:[]) = x++" likes this"
likes (x:y:[]) = x++" and "++y++" like this"
likes (x:y:z:[]) = x++", "++y++" and "++z++" like this"
likes (x:y:zs) = x++", "++y++" and "++show (length zs)++" others like this"
|
Bodigrim/katas
|
src/haskell/6-Who-likes-it.hs
|
Haskell
|
bsd-2-clause
| 344
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QSplashScreen_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:27
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QSplashScreen_h (
QdrawContents_h(..)
) where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QSplashScreen ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QSplashScreen_unSetUserMethod" qtc_QSplashScreen_unSetUserMethod :: Ptr (TQSplashScreen a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QSplashScreenSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QSplashScreen ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QSplashScreenSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QSplashScreen ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QSplashScreenSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QSplashScreen ()) (QSplashScreen x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QSplashScreen setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QSplashScreen_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QSplashScreen_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setUserMethod" qtc_QSplashScreen_setUserMethod :: Ptr (TQSplashScreen a) -> CInt -> Ptr (Ptr (TQSplashScreen x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QSplashScreen :: (Ptr (TQSplashScreen x0) -> IO ()) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QSplashScreen_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QSplashScreenSc a) (QSplashScreen x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QSplashScreen setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QSplashScreen_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QSplashScreen_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QSplashScreen ()) (QSplashScreen x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QSplashScreen setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QSplashScreen_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QSplashScreen_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setUserMethodVariant" qtc_QSplashScreen_setUserMethodVariant :: Ptr (TQSplashScreen a) -> CInt -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QSplashScreen :: (Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QSplashScreen_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QSplashScreenSc a) (QSplashScreen x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QSplashScreen setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QSplashScreen_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QSplashScreen_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QSplashScreen ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QSplashScreen_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QSplashScreen_unSetHandler" qtc_QSplashScreen_unSetHandler :: Ptr (TQSplashScreen a) -> CWString -> IO (CBool)
instance QunSetHandler (QSplashScreenSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QSplashScreen_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> QPainter t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler1" qtc_QSplashScreen_setHandler1 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen1 :: (Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> QPainter t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
class QdrawContents_h x0 x1 where
drawContents_h :: x0 -> x1 -> IO ()
instance QdrawContents_h (QSplashScreen ()) ((QPainter t1)) where
drawContents_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_drawContents cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_drawContents" qtc_QSplashScreen_drawContents :: Ptr (TQSplashScreen a) -> Ptr (TQPainter t1) -> IO ()
instance QdrawContents_h (QSplashScreenSc a) ((QPainter t1)) where
drawContents_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_drawContents cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler2" qtc_QSplashScreen_setHandler2 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen2 :: (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QSplashScreen ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_event cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_event" qtc_QSplashScreen_event :: Ptr (TQSplashScreen a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QSplashScreenSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_event cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler3" qtc_QSplashScreen_setHandler3 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen3 :: (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QmousePressEvent_h (QSplashScreen ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_mousePressEvent" qtc_QSplashScreen_mousePressEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QSplashScreenSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mousePressEvent cobj_x0 cobj_x1
instance QactionEvent_h (QSplashScreen ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_actionEvent" qtc_QSplashScreen_actionEvent :: Ptr (TQSplashScreen a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QSplashScreenSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_actionEvent cobj_x0 cobj_x1
instance QchangeEvent_h (QSplashScreen ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_changeEvent" qtc_QSplashScreen_changeEvent :: Ptr (TQSplashScreen a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QSplashScreenSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_changeEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QSplashScreen ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_closeEvent" qtc_QSplashScreen_closeEvent :: Ptr (TQSplashScreen a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QSplashScreenSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_closeEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QSplashScreen ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_contextMenuEvent" qtc_QSplashScreen_contextMenuEvent :: Ptr (TQSplashScreen a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QSplashScreenSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler4" qtc_QSplashScreen_setHandler4 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen4 :: (Ptr (TQSplashScreen x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdevType_h (QSplashScreen ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_devType cobj_x0
foreign import ccall "qtc_QSplashScreen_devType" qtc_QSplashScreen_devType :: Ptr (TQSplashScreen a) -> IO CInt
instance QdevType_h (QSplashScreenSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_devType cobj_x0
instance QdragEnterEvent_h (QSplashScreen ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_dragEnterEvent" qtc_QSplashScreen_dragEnterEvent :: Ptr (TQSplashScreen a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QSplashScreenSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QSplashScreen ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_dragLeaveEvent" qtc_QSplashScreen_dragLeaveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QSplashScreenSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QSplashScreen ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_dragMoveEvent" qtc_QSplashScreen_dragMoveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QSplashScreenSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QSplashScreen ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_dropEvent" qtc_QSplashScreen_dropEvent :: Ptr (TQSplashScreen a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QSplashScreenSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dropEvent cobj_x0 cobj_x1
instance QenterEvent_h (QSplashScreen ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_enterEvent" qtc_QSplashScreen_enterEvent :: Ptr (TQSplashScreen a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QSplashScreenSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_enterEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QSplashScreen ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_focusInEvent" qtc_QSplashScreen_focusInEvent :: Ptr (TQSplashScreen a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QSplashScreenSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QSplashScreen ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_focusOutEvent" qtc_QSplashScreen_focusOutEvent :: Ptr (TQSplashScreen a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QSplashScreenSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler5" qtc_QSplashScreen_setHandler5 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen5 :: (Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QheightForWidth_h (QSplashScreen ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QSplashScreen_heightForWidth" qtc_QSplashScreen_heightForWidth :: Ptr (TQSplashScreen a) -> CInt -> IO CInt
instance QheightForWidth_h (QSplashScreenSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QSplashScreen ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_hideEvent" qtc_QSplashScreen_hideEvent :: Ptr (TQSplashScreen a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QSplashScreenSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_hideEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler6" qtc_QSplashScreen_setHandler6 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen6 :: (Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QSplashScreen ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QSplashScreen_inputMethodQuery" qtc_QSplashScreen_inputMethodQuery :: Ptr (TQSplashScreen a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QSplashScreenSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent_h (QSplashScreen ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_keyPressEvent" qtc_QSplashScreen_keyPressEvent :: Ptr (TQSplashScreen a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QSplashScreenSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QSplashScreen ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_keyReleaseEvent" qtc_QSplashScreen_keyReleaseEvent :: Ptr (TQSplashScreen a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QSplashScreenSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QSplashScreen ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_leaveEvent" qtc_QSplashScreen_leaveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QSplashScreenSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_leaveEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler7" qtc_QSplashScreen_setHandler7 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen7 :: (Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QSplashScreen ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_minimumSizeHint cobj_x0
foreign import ccall "qtc_QSplashScreen_minimumSizeHint" qtc_QSplashScreen_minimumSizeHint :: Ptr (TQSplashScreen a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QSplashScreenSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QSplashScreen ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QSplashScreen_minimumSizeHint_qth" qtc_QSplashScreen_minimumSizeHint_qth :: Ptr (TQSplashScreen a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QSplashScreenSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QmouseDoubleClickEvent_h (QSplashScreen ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_mouseDoubleClickEvent" qtc_QSplashScreen_mouseDoubleClickEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QSplashScreenSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QSplashScreen ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_mouseMoveEvent" qtc_QSplashScreen_mouseMoveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QSplashScreenSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseMoveEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QSplashScreen ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_mouseReleaseEvent" qtc_QSplashScreen_mouseReleaseEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QSplashScreenSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseReleaseEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QSplashScreen ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_moveEvent" qtc_QSplashScreen_moveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QSplashScreenSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler8" qtc_QSplashScreen_setHandler8 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen8 :: (Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QSplashScreen ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_paintEngine cobj_x0
foreign import ccall "qtc_QSplashScreen_paintEngine" qtc_QSplashScreen_paintEngine :: Ptr (TQSplashScreen a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QSplashScreenSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_paintEngine cobj_x0
instance QpaintEvent_h (QSplashScreen ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_paintEvent" qtc_QSplashScreen_paintEvent :: Ptr (TQSplashScreen a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QSplashScreenSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_paintEvent cobj_x0 cobj_x1
instance QresizeEvent_h (QSplashScreen ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_resizeEvent" qtc_QSplashScreen_resizeEvent :: Ptr (TQSplashScreen a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QSplashScreenSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_resizeEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler9" qtc_QSplashScreen_setHandler9 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen9 :: (Ptr (TQSplashScreen x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QSplashScreen ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QSplashScreen_setVisible" qtc_QSplashScreen_setVisible :: Ptr (TQSplashScreen a) -> CBool -> IO ()
instance QsetVisible_h (QSplashScreenSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QSplashScreen ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_showEvent" qtc_QSplashScreen_showEvent :: Ptr (TQSplashScreen a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QSplashScreenSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_showEvent cobj_x0 cobj_x1
instance QqsizeHint_h (QSplashScreen ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_sizeHint cobj_x0
foreign import ccall "qtc_QSplashScreen_sizeHint" qtc_QSplashScreen_sizeHint :: Ptr (TQSplashScreen a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QSplashScreenSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_sizeHint cobj_x0
instance QsizeHint_h (QSplashScreen ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QSplashScreen_sizeHint_qth" qtc_QSplashScreen_sizeHint_qth :: Ptr (TQSplashScreen a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QSplashScreenSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QtabletEvent_h (QSplashScreen ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_tabletEvent" qtc_QSplashScreen_tabletEvent :: Ptr (TQSplashScreen a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QSplashScreenSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_tabletEvent cobj_x0 cobj_x1
instance QwheelEvent_h (QSplashScreen ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_wheelEvent" qtc_QSplashScreen_wheelEvent :: Ptr (TQSplashScreen a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QSplashScreenSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_wheelEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler10" qtc_QSplashScreen_setHandler10 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen10 :: (Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QSplashScreen ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QSplashScreen_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QSplashScreen_eventFilter" qtc_QSplashScreen_eventFilter :: Ptr (TQSplashScreen a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QSplashScreenSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QSplashScreen_eventFilter cobj_x0 cobj_x1 cobj_x2
|
keera-studios/hsQt
|
Qtc/Gui/QSplashScreen_h.hs
|
Haskell
|
bsd-2-clause
| 62,301
|
--------------------------------------------------------------------------------
module WhatMorphism.Dump
( Dump (..)
) where
--------------------------------------------------------------------------------
import Coercion (Coercion)
import CoreSyn
import Data.List (intercalate)
import DataCon (DataCon)
import Literal (Literal)
import Name (Name)
import qualified Name as Name
import Module (Module)
import qualified Module as Module
import OccName (OccName)
import qualified OccName as OccName
import TyCon (TyCon)
import qualified TyCon as TyCon
import TypeRep (Type)
import Var (Var)
import qualified Var as Var
--------------------------------------------------------------------------------
class Dump a where
dump :: a -> String
--------------------------------------------------------------------------------
instance (Dump a, Dump b) => Dump (a, b) where
dump (x, y) = "(" ++ dump x ++ ", " ++ dump y ++ ")"
--------------------------------------------------------------------------------
instance (Dump a, Dump b, Dump c) => Dump (a, b, c) where
dump (x, y, z) = "(" ++ dump x ++ ", " ++ dump y ++ ", " ++ dump z ++ ")"
--------------------------------------------------------------------------------
instance Dump a => Dump [a] where
dump xs = "[" ++ intercalate ", " (map dump xs) ++ "]"
--------------------------------------------------------------------------------
instance Dump a => Dump (Maybe a) where
dump Nothing = "Nothing"
dump (Just x) = "(Just " ++ dump x ++ ")"
--------------------------------------------------------------------------------
instance Dump Name where
dump name = OccName.occNameString (Name.getOccName name) ++ "_" ++
show (Name.nameUnique name)
--------------------------------------------------------------------------------
instance Dump OccName where
dump = OccName.occNameString
--------------------------------------------------------------------------------
instance Dump Var where
dump = dump . Var.varName
--------------------------------------------------------------------------------
instance Dump DataCon where
dump = OccName.occNameString . Name.getOccName
--------------------------------------------------------------------------------
instance Dump TyCon where
dump tc = "@" ++ dump (TyCon.tyConName tc)
--------------------------------------------------------------------------------
instance Dump AltCon where
dump (DataAlt x) = dc "DataAlt" [dump x]
dump (LitAlt x) = dc "Literal" [dump x]
dump DEFAULT = dc "DEFAULT" []
--------------------------------------------------------------------------------
instance Dump Module where
dump = Module.moduleNameString . Module.moduleName
--------------------------------------------------------------------------------
instance Dump Literal where
dump _ = "<Literal>"
--------------------------------------------------------------------------------
instance Dump Coercion where
dump _ = "<Coercion>"
--------------------------------------------------------------------------------
instance Dump Type where
dump _ = "<Type>"
--------------------------------------------------------------------------------
instance Dump (Tickish a) where
dump _ = "<Tickish>"
--------------------------------------------------------------------------------
instance Dump b => Dump (Bind b) where
dump (NonRec x y) = dc "NonRec" [dump x, dump y]
dump (Rec x) = dc "Rec" [dump x]
--------------------------------------------------------------------------------
instance Dump b => Dump (Expr b) where
dump (Var x) = dc "Var" [dump x]
dump (Lit x) = dc "Lit" [dump x]
dump (App x y) = dc "App" [dump x, dump y]
dump (Lam x y) = dc "Lam" [dump x, dump y]
dump (Let x y) = dc "Let" [dump x, dump y]
dump (Case x y z w) = dc "Case" [dump x, dump y, dump z, dump w]
dump (Cast x y) = dc "Cast" [dump x, dump y]
dump (Tick x y) = dc "Tick" [dump x, dump y]
dump (Type x) = dc "Type" [dump x]
dump (Coercion x) = dc "Coercion" [dump x]
--------------------------------------------------------------------------------
dc :: String -> [String] -> String
dc constr [] = constr
dc constr args = "(" ++ constr ++ " " ++ intercalate " " args ++ ")"
|
jaspervdj/what-morphism
|
src/WhatMorphism/Dump.hs
|
Haskell
|
bsd-3-clause
| 4,541
|
{-
BezCurve.hs (adapted from bezcurve.c which is (c) Silicon Graphics, Inc)
Copyright (c) Sven Panne 2002-2005 <[email protected]>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program uses evaluators to draw a Bezier curve.
-}
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
ctrlPoints :: [Vertex3 GLfloat]
ctrlPoints = [ Vertex3 (-4)(-4) 0, Vertex3 (-2) 4 0,
Vertex3 2 (-4) 0, Vertex3 4 4 0 ]
myInit :: IO ()
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
m <- newMap1 (0, 1) ctrlPoints
map1 $= Just (m :: GLmap1 Vertex3 GLfloat)
display :: DisplayCallback
display = do
clear [ ColorBuffer ]
-- resolve overloading, not needed in "real" programs
let color3f = color :: Color3 GLfloat -> IO ()
color3f (Color3 1 1 1)
renderPrimitive LineStrip $
mapM_ evalCoord1 [ i/30.0 :: GLfloat | i <- [0..30] ]
-- The following code displays the control points as dots.
pointSize $= 5
color3f (Color3 1 1 0)
renderPrimitive Points $
mapM_ vertex ctrlPoints
flush
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
let wf = fromIntegral w
hf = fromIntegral h
if w <= h
then ortho (-5.0) 5.0 (-5.0*hf/wf) (5.0*hf/wf) (-5.0) 5.0
else ortho (-5.0*wf/hf) (5.0*wf/hf) (-5.0) 5.0 (-5.0) 5.0
matrixMode $= Modelview 0
loadIdentity
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 500 500
initialWindowPosition $= Position 100 100
createWindow progName
myInit
displayCallback $= display
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just keyboard
mainLoop
|
FranklinChen/hugs98-plus-Sep2006
|
packages/GLUT/examples/RedBook/BezCurve.hs
|
Haskell
|
bsd-3-clause
| 2,027
|
import Data.Char (isDigit)
data YorthData = YNil
| YInt Integer
| YOpAdd
| YOpSub
| YOpMul
| YOpDiv
| YError String
deriving (Show, Eq, Ord)
data Closure = DoneToken
| Closure [YorthData] Closure [(YorthData, [Closure])] Closure
deriving (Show, Eq, Ord)
empty_closure = (Closure [] empty_closure [] empty_closure)
parse :: Closure -> [String] -> Closure -> Closure
parse enclosure inputs caller = (Closure (stacks inputs) enclosure [] caller)
where stacks [] = []
stacks (input:is)
| foldl1 (&&) (map isDigit input) = (YInt (read input)):(stacks is)
| otherwise (case input of
"+" -> YOpAdd
"-" -> YOpSub
"*" -> YOpMul
"/" -> YOpDiv
"}" -> YNil
_ -> YError "Undefined token"
):(stacks is)
step :: Closure -> (YorthData, Closure)
step (Closure [] enclosure scope caller) = (YNil, DoneToken)
step (Closure (stack:ss) enclosure scope caller) = (YNil, empty_closure)
|
tricorder42/yorth
|
yorth.hs
|
Haskell
|
bsd-3-clause
| 959
|
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FunctionalDependencies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Indexed.Traversable
-- Copyright : (C) 2012 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Indexed Traversable Functors
-----------------------------------------------------------------------------
module Indexed.Traversable
( ITraversable(..)
) where
import Control.Applicative
import Indexed.Functor
import Indexed.Foldable
-- | Indexed Traversable Functor
class (IFunctor t, IFoldable t) => ITraversable t where
itraverse :: Applicative f => (forall x. a x -> f (b x)) -> t a y -> f (t b y)
|
ekmett/indexed
|
src/Indexed/Traversable.hs
|
Haskell
|
bsd-3-clause
| 904
|
import Data.Text (unpack)
import Data.List (sortOn)
import Lib
main :: IO ()
main = do
mod <- parseModuleFromFile "test/Test1.purs"
putStrLn ""
putStrLn $ show mod
putStrLn ""
putStrLn "% facts"
putStrLn . unpack . formatAtomsProlog . sortForProlog . factsFromModule $ mod
putStrLn ""
putStrLn "% rules"
putStrLn . unpack . formatRulesProlog $ definedInStar
-- putStrLn ""
-- putStrLn $ (formatDatomic . factsFromModule $ mod)
where
sortForProlog = sortOn (\(Pred name _) -> name)
|
epost/psc-query
|
test/Spec.hs
|
Haskell
|
bsd-3-clause
| 540
|
{-# LANGUAGE OverloadedStrings #-}
import System.Random
import System.Environment
import Debug.Trace
import Data.List
import Control.Monad.Par
import Control.DeepSeq
import Data.Map (Map)
import qualified Data.Map as Map
-- ----------------------------------------------------------------------------
-- <<Talk
newtype Talk = Talk Int
deriving (Eq,Ord)
instance NFData Talk
instance Show Talk where
show (Talk t) = show t
-- >>
-- <<Person
data Person = Person
{ name :: String
, talks :: [Talk]
}
deriving (Show)
-- >>
-- <<TimeTable
type TimeTable = [[Talk]]
-- >>
-- ----------------------------------------------------------------------------
-- The parallel skeleton
-- <<search_type
search :: ( partial -> Maybe solution ) -- <1>
-> ( partial -> [ partial ] ) -- <2>
-> partial -- <3>
-> [solution] -- <4>
-- >>
-- <<search
search finished refine emptysoln = generate emptysoln
where
generate partial
| Just soln <- finished partial = [soln]
| otherwise = concat (map generate (refine partial))
-- >>
-- <<parsearch
parsearch :: NFData solution
=> Int
-> ( partial -> Maybe solution ) -- finished?
-> ( partial -> [ partial ] ) -- refine a solution
-> partial -- initial solution
-> [solution]
parsearch maxdepth finished refine emptysoln
= runPar $ generate 0 emptysoln
where
generate d partial | d >= maxdepth -- <1>
= return (search finished refine partial)
generate d partial
| Just soln <- finished partial = return [soln]
| otherwise = do
solnss <- parMapM (generate (d+1)) (refine partial)
return (concat solnss)
-- >>
-- ----------------------------------------------------------------------------
-- <<Partial
type Partial = (Int, Int, [[Talk]], [Talk], [Talk], [Talk])
-- >>
-- <<timetable
timetable :: [Person] -> [Talk] -> Int -> Int -> [TimeTable]
timetable people allTalks maxTrack maxSlot =
parsearch 3 finished refine emptysoln
where
emptysoln = (0, 0, [], [], allTalks, allTalks)
finished (slotNo, trackNo, slots, slot, slotTalks, talks)
| slotNo == maxSlot = Just slots
| otherwise = Nothing
clashes :: Map Talk [Talk]
clashes = Map.fromListWith union
[ (t, ts)
| s <- people
, (t, ts) <- selects (talks s) ]
refine (slotNo, trackNo, slots, slot, slotTalks, talks)
| trackNo == maxTrack = [(slotNo+1, 0, slot:slots, [], talks, talks)]
| otherwise =
[ (slotNo, trackNo+1, slots, t:slot, slotTalks', talks')
| (t, ts) <- selects slotTalks
, let clashesWithT = Map.findWithDefault [] t clashes
, let slotTalks' = filter (`notElem` clashesWithT) ts
, let talks' = filter (/= t) talks
]
-- >>
-- ----------------------------------------------------------------------------
-- Utils
-- <<selects
selects :: [a] -> [(a,[a])]
selects xs0 = go [] xs0
where
go xs [] = []
go xs (y:ys) = (y,xs++ys) : go (y:xs) ys
-- >>
-- ----------------------------------------------------------------------------
-- Benchmarking / Testing
bench :: Int -> Int -> Int -> Int -> Int -> StdGen
-> ([Person],[Talk],[TimeTable])
bench nslots ntracks ntalks npersons c_per_s gen =
(persons,talks, timetable persons talks ntracks nslots)
where
total_talks = nslots * ntracks
talks = map Talk [1..total_talks]
persons = mkpersons npersons gen
mkpersons :: Int -> StdGen -> [Person]
mkpersons 0 g = []
mkpersons n g = Person ('P':show n) (take c_per_s cs) : rest
where
(g1,g2) = split g
rest = mkpersons (n-1) g2
cs = nub [ talks !! n | n <- randomRs (0,ntalks-1) g ]
main = do
[ a, b, c, d, e ] <- fmap (fmap read) getArgs
let g = mkStdGen 1001
let (ss,cs,ts) = bench a b c d e g
print ss
print (length ts)
-- [ a, b ] <- fmap (fmap read) getArgs
-- print (head (test2 a b))
test = timetable testPersons cs 2 2
where
cs@[c1,c2,c3,c4] = map Talk [1..4]
testPersons =
[ Person "P" [c1,c2]
, Person "Q" [c2,c3]
, Person "R" [c3,c4]
]
test2 n m = timetable testPersons cs m n
where
cs = map Talk [1 .. (n * m)]
testPersons =
[ Person "1" (take n cs)
]
|
mono0926/ParallelConcurrentHaskell
|
timetable3.hs
|
Haskell
|
bsd-3-clause
| 4,343
|
----------------------
-- PARELM --
----------------------
module Parelm where
import LPPE
import Usage
-- This function removes global parameters that are never used.
parelm :: PSpecification -> PSpecification
parelm (lppe, initial, dataspec) = (lppeReduced, initial2, dataspec)
where
unused = [parNr | parNr <- [0..length (getLPPEPars lppe) - 1],
and [not (isUsedInSummand summand parNr (fst ((getLPPEPars lppe)!!parNr)) False) | summand <- (getPSummands lppe)]]
(lppeReduced,initial2,_) = removeParametersFromLPPE (lppe,initial,dataspec) unused
|
utwente-fmt/scoop
|
src/Parelm.hs
|
Haskell
|
bsd-3-clause
| 607
|
{-# LANGUAGE TypeOperators #-}
module Data.Semigroupoid.Category where
import Data.Semigroupoid.Semigroupoid
class Semigroupoid (~>) => Category (~>) where
id ::
a ~> a
instance Category (->) where
id a =
a
|
tonymorris/type-class
|
src/Data/Semigroupoid/Category.hs
|
Haskell
|
bsd-3-clause
| 222
|
module D18Spec (main, spec) where
import Test.Hspec
import D18Lib
import qualified Data.Vector as V
import qualified Text.Parsec as P
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
describe "parsing" $ do
it "parses a row" $ do
let r = P.parse rowP "fixture" ".^\n"
r `shouldBe` Right (V.fromList [Safe, Trap])
describe "succRow" $ do
it "builds the next row" $ do
let r0 = V.fromList [Safe, Safe, Trap, Trap, Safe]
let r1 = V.fromList [Safe, Trap, Trap, Trap, Trap]
let r2 = V.fromList [Trap, Trap, Safe, Safe, Trap]
succRow r0 `shouldBe` r1
succRow r1 `shouldBe` r2
describe "nsafe" $ do
it "counts safe tiles" $ do
let r0 = V.fromList [Safe, Safe, Trap, Trap, Safe]
nsafe r0 3 `shouldBe` 6
|
wfleming/advent-of-code-2016
|
2016/test/D18Spec.hs
|
Haskell
|
bsd-3-clause
| 862
|
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod
import Control.Exception (throw)
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Yaml (decodeEither')
import Database.Persist.Sqlite (SqliteConf)
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings(..), widgetFileNoReload,
widgetFileReload)
import Yesod.Default.Util (defaultTemplateLanguages)
import Yesod.Default.Util (TemplateLanguage(..))
import Yesod.Markdown (markdownToHtml, Markdown(..))
import Text.Shakespeare.Text (textFile, textFileReload)
import qualified Data.Text as T
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: SqliteConf
-- ^ Configuration settings for accessing the database.
, appRoot :: Text
-- ^ Base for all generated URLs.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appDetailedRequestLogging :: Bool
-- ^ Use detailed request logging system
, appShouldLogAll :: Bool
-- ^ Should all log messages be displayed?
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
-- Example app-specific configuration values.
, appCopyright :: Text
-- ^ Copyright text to appear in the footer of the page
, appAnalytics :: Maybe Text
-- ^ Google Analytics code
, appPackageDBs :: [Text]
, appTrustedPkgs :: [String]
, appDistrustedPkgs :: [String]
, appDistribPort :: String
, appWSAddress :: Text
}
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#if DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabaseConf <- o .: "database"
appRoot <- o .: "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev
appShouldLogAll <- o .:? "should-log-all" .!= defaultDev
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
appCopyright <- o .: "copyright"
appAnalytics <- o .:? "analytics"
appPackageDBs <- o .:? "package-dbs" .!= []
appTrustedPkgs <- o .:? "trusted-packages" .!= []
appDistrustedPkgs <- o .:? "distrusted-packages" .!= []
appDistribPort <- (fmap (show :: Int -> String) <$> o .:? "distributed-port")
.!= ""
appWSAddress <- o .:? "websock-addr"
.!= T.replace "http" "ws" appRoot
return AppSettings {..}
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def { wfsLanguages = \hset -> defaultTemplateLanguages hset ++
[ TemplateLanguage True "md" markdownFile markdownFileReload
] }
markdownFile fs = [| markdownToHtml (Markdown $(textFile fs)) |]
markdownFileReload fs = [| markdownToHtml (Markdown $(textFileReload fs)) |]
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
{-
fayFile :: String -> Q Exp
fayFile fp =
let setting = (yesodFaySettings fp)
{yfsPackages = ["fay-base", "fay-ref", "fay-jquery", "fay-text", "fay-base"]
,yfsSeparateRuntime = Just ("static", ConE (mkName "StaticR"))}
in if appReloadTemplates compileTimeAppSettings
then fayFileReload setting
else fayFileProd setting
-}
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either throw id $ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
|
konn/leport
|
leport-web/Settings.hs
|
Haskell
|
bsd-3-clause
| 6,896
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
import Plots
import Network.Wreq
import Control.Lens
import Data.Csv hiding ((.=))
import Plots.Axis
import qualified Data.Vector as V
import Data.ByteString.Lazy (ByteString)
import Control.Arrow
import Control.Monad.State (MonadState, execStateT)
import Data.Foldable
import Control.Monad.IO.Class
import Data.Time.Clock.POSIX
-- import Plots.Axis
import Diagrams.Backend.Rasterific
import Data.Time
import Control.Monad
import Diagrams
import Data.Maybe
-- Incomplete example using mtl to perform IO in the axis do notation.
-- The axis show dates but currently the tick positions and the start of
-- the dates are not aligned properly. (the ticks might be 1.2 years
-- apart but the labels will just show the year, which is misleading)
parseStocks :: ByteString -> [(String, Double)]
parseStocks bs = toListOf (each . to (view _1 &&& view _7)) v
where
Right v = decode HasHeader bs :: Either String (V.Vector (String, Double, Double, Double, Double, Double, Double))
filterStocks :: [(String, Double)] -> [(Double, Double)]
filterStocks = mapMaybe f
where
f (s, d) = do
date <- s ^? timeFormat "%F"
start <- "2014" ^? timeFormat "%Y"
guard $ date > start
return $ (date ^. realUTC, d)
myaxis :: IO (Axis B V2 Double)
myaxis = execStateT ?? r2Axis $ do
goog <- liftIO $ get "http://ichart.yahoo.com/table.csv?s=GOOG"
appl <- liftIO $ get "http://ichart.yahoo.com/table.csv?s=AAPL"
for_ [goog, appl] $
linePlotOf (responseBody . to (filterStocks . parseStocks) . each)
axisTickLabels . _x . tickLabelFun .= autoTimeLabels
xAxisLabel .= "date"
yAxisLabel .= "closing (dollars)"
main :: IO ()
main = myaxis >>= make . renderAxis
make :: Diagram B -> IO ()
make = renderRasterific "examples/stocks.png" (mkWidth 600) . frame 30
------------------------------------------------------------------------
linePlotOf
:: (PointLike V2 n p, TypeableFloat n, MonadState (Axis b V2 n) m, Renderable (Path V2 n) b)
=> Fold s p -- ^ Fold over data
-> s -- ^ Data
-> m () -- ^ Monad action on axis
linePlotOf f s = addPlotable (Path [mkTrailOf f s])
------------------------------------------------------------------------
-- Time
------------------------------------------------------------------------
-- | Same as 'timeFormat' but with the option of choosing the
-- 'TimeLocale'.
localeTimeFormat
:: (ParseTime a, FormatTime a)
=> TimeLocale -> String -> Prism' String a
localeTimeFormat tl s = prism' (formatTime tl s) (parseTimeM False tl s)
{-# INLINE localeTimeFormat #-}
-- | A prism between a parse-able format and its string representation
-- from the given format string using the 'defaultTimeLocale'. See
-- 'formatTime' for a description of the format string.
--
-- @
-- >>> timeFormat "%F" # ModifiedJulianDay 91424
-- "2109-03-10"
--
-- >>> "2109-03-10" ^? timeFormat "%F" :: Maybe UTCTime
-- Just 2109-03-10 00:00:00 UTC
-- @
--
timeFormat
:: (ParseTime a, FormatTime a)
=> String -> Prism' String a
timeFormat = localeTimeFormat defaultTimeLocale
{-# INLINE timeFormat #-}
-- | Automatically choose a suitable time axis, based upon the time range
-- of data.
-- XXX: This is a terrible way to do it if the ticks aren't aligned
-- properly.
autoTimeLabels :: RealFloat n => [n] -> (n,n) -> [(n, String)]
autoTimeLabels ts (t0, t1)
| d < minute = fmt "%S%Q"
| d < hour = fmt "%M:%S"
| d < day = fmt "%H:%M"
| d < month = fmt "%F %H"
| d < year = fmt "%F"
| d < 2*year = fmt "%F"
| otherwise = fmt "%Y"
where
d = t1 - t0
fmt a = map (\n -> (n, formatTime defaultTimeLocale a (realToUTC n))) ts
minute = 60
hour = 60 * minute
day = 24 * hour
month = 30 * day
year = 365 * day
realToUTC :: Real a => a -> UTCTime
realToUTC = posixSecondsToUTCTime . realToFrac
realUTC :: (Real a, Fractional a) => Iso' UTCTime a
realUTC = iso (realToFrac . utcTimeToPOSIXSeconds) realToUTC
|
bergey/plots
|
examples/stocks.hs
|
Haskell
|
bsd-3-clause
| 4,014
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.HcPkg
-- Copyright : Duncan Coutts 2009, 2013
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides an library interface to the @hc-pkg@ program.
-- Currently only GHC, GHCJS and LHC have hc-pkg programs.
module Distribution.Simple.Program.HcPkg (
HcPkgInfo(..),
init,
invoke,
register,
reregister,
unregister,
expose,
hide,
dump,
list,
-- * View operations
createView,
addPackageToView,
removePackageFromView,
-- * Program invocations
initInvocation,
registerInvocation,
reregisterInvocation,
unregisterInvocation,
exposeInvocation,
hideInvocation,
dumpInvocation,
listInvocation,
) where
import Prelude hiding (init)
import Distribution.Package
( PackageId, InstalledPackageId(..) )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo, InstalledPackageInfo_(..)
, showInstalledPackageInfo
, emptyInstalledPackageInfo, fieldsInstalledPackageInfo )
import Distribution.ParseUtils
import Distribution.Simple.Compiler
( PackageDB(..), PackageDBStack )
import Distribution.Simple.Program.Types
( ConfiguredProgram(programId) )
import Distribution.Simple.Program.Run
( ProgramInvocation(..), IOEncoding(..), programInvocation
, runProgramInvocation, getProgramInvocationOutput )
import Distribution.Text
( display, simpleParse )
import Distribution.Simple.Utils
( die )
import Distribution.Verbosity
( Verbosity, deafening, silent )
import Distribution.Compat.Exception
( catchExit )
import Control.Monad
( when )
import Data.Char
( isSpace )
import Data.List
( stripPrefix )
import qualified Data.List as List
import System.FilePath as FilePath
( (</>), splitPath, splitDirectories, joinPath, isPathSeparator )
import qualified System.FilePath.Posix as FilePath.Posix
-- | Information about the features and capabilities of an @hc-pkg@
-- program.
--
data HcPkgInfo = HcPkgInfo
{ hcPkgProgram :: ConfiguredProgram
, noPkgDbStack :: Bool -- ^ no package DB stack supported
, noVerboseFlag :: Bool -- ^ hc-pkg does not support verbosity flags
, flagPackageConf :: Bool -- ^ use package-conf option instead of package-db
, useSingleFileDb :: Bool -- ^ requires single file package database
, multInstEnabled :: Bool -- ^ ghc-pkg supports --enable-multi-instance
, supportsView :: Bool -- ^ views are supported.
}
-- | Call @hc-pkg@ to initialise a package database at the location {path}.
--
-- > hc-pkg init {path}
--
init :: HcPkgInfo -> Verbosity -> FilePath -> IO ()
init hpi verbosity path =
runProgramInvocation verbosity (initInvocation hpi verbosity path)
-- | Run @hc-pkg@ using a given package DB stack, directly forwarding the
-- provided command-line arguments to it.
invoke :: HcPkgInfo -> Verbosity -> PackageDBStack -> [String] -> IO ()
invoke hpi verbosity dbStack extraArgs =
runProgramInvocation verbosity invocation
where
args = packageDbStackOpts hpi dbStack ++ extraArgs
invocation = programInvocation (hcPkgProgram hpi) args
-- | Call @hc-pkg@ to register a package.
--
-- > hc-pkg register {filename | -} [--user | --global | --package-db]
--
register :: HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath
InstalledPackageInfo
-> IO ()
register hpi verbosity packagedb pkgFile =
runProgramInvocation verbosity
(registerInvocation hpi verbosity packagedb pkgFile)
-- | Call @hc-pkg@ to re-register a package.
--
-- > hc-pkg register {filename | -} [--user | --global | --package-db]
--
reregister :: HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath
InstalledPackageInfo
-> IO ()
reregister hpi verbosity packagedb pkgFile =
runProgramInvocation verbosity
(reregisterInvocation hpi verbosity packagedb pkgFile)
-- | Call @hc-pkg@ to unregister a package
--
-- > hc-pkg unregister [pkgid] [--user | --global | --package-db]
--
unregister :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId -> IO ()
unregister hpi verbosity packagedb pkgid =
runProgramInvocation verbosity
(unregisterInvocation hpi verbosity packagedb pkgid)
-- | Call @hc-pkg@ to expose a package.
--
-- > hc-pkg expose [pkgid] [--user | --global | --package-db]
--
expose :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId -> IO ()
expose hpi verbosity packagedb pkgid =
runProgramInvocation verbosity
(exposeInvocation hpi verbosity packagedb pkgid)
-- | Call @hc-pkg@ to hide a package.
--
-- > hc-pkg hide [pkgid] [--user | --global | --package-db]
--
hide :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId -> IO ()
hide hpi verbosity packagedb pkgid =
runProgramInvocation verbosity
(hideInvocation hpi verbosity packagedb pkgid)
-- | Call @hc-pkg@ to get all the details of all the packages in the given
-- package database.
--
dump :: HcPkgInfo -> Verbosity -> PackageDB -> IO [InstalledPackageInfo]
dump hpi verbosity packagedb = do
output <- getProgramInvocationOutput verbosity
(dumpInvocation hpi verbosity packagedb)
`catchExit` \_ -> die $ programId (hcPkgProgram hpi) ++ " dump failed"
case parsePackages output of
Left ok -> return ok
_ -> die $ "failed to parse output of '"
++ programId (hcPkgProgram hpi) ++ " dump'"
where
parsePackages str =
let parsed = map parseInstalledPackageInfo' (splitPkgs str)
in case [ msg | ParseFailed msg <- parsed ] of
[] -> Left [ setInstalledPackageId
. maybe id mungePackagePaths (pkgRoot pkg)
$ pkg
| ParseOk _ pkg <- parsed ]
msgs -> Right msgs
parseInstalledPackageInfo' =
parseFieldsFlat fieldsInstalledPackageInfo emptyInstalledPackageInfo
--TODO: this could be a lot faster. We're doing normaliseLineEndings twice
-- and converting back and forth with lines/unlines.
splitPkgs :: String -> [String]
splitPkgs = checkEmpty . map unlines . splitWith ("---" ==) . lines
where
-- Handle the case of there being no packages at all.
checkEmpty [s] | all isSpace s = []
checkEmpty ss = ss
splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith p xs = ys : case zs of
[] -> []
_:ws -> splitWith p ws
where (ys,zs) = break p xs
mungePackagePaths :: FilePath -> InstalledPackageInfo -> InstalledPackageInfo
-- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
-- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
-- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
-- The "pkgroot" is the directory containing the package database.
mungePackagePaths pkgroot pkginfo =
pkginfo {
importDirs = mungePaths (importDirs pkginfo),
includeDirs = mungePaths (includeDirs pkginfo),
libraryDirs = mungePaths (libraryDirs pkginfo),
frameworkDirs = mungePaths (frameworkDirs pkginfo),
haddockInterfaces = mungePaths (haddockInterfaces pkginfo),
haddockHTMLs = mungeUrls (haddockHTMLs pkginfo)
}
where
mungePaths = map mungePath
mungeUrls = map mungeUrl
mungePath p = case stripVarPrefix "${pkgroot}" p of
Just p' -> pkgroot </> p'
Nothing -> p
mungeUrl p = case stripVarPrefix "${pkgrooturl}" p of
Just p' -> toUrlPath pkgroot p'
Nothing -> p
toUrlPath r p = "file:///"
-- URLs always use posix style '/' separators:
++ FilePath.Posix.joinPath (r : FilePath.splitDirectories p)
stripVarPrefix var p =
case splitPath p of
(root:path') -> case stripPrefix var root of
Just [sep] | isPathSeparator sep -> Just (joinPath path')
_ -> Nothing
_ -> Nothing
-- Older installed package info files did not have the installedPackageId
-- field, so if it is missing then we fill it as the source package ID.
setInstalledPackageId :: InstalledPackageInfo -> InstalledPackageInfo
setInstalledPackageId pkginfo@InstalledPackageInfo {
installedPackageId = InstalledPackageId "",
sourcePackageId = pkgid
}
= pkginfo {
--TODO use a proper named function for the conversion
-- from source package id to installed package id
installedPackageId = InstalledPackageId (display pkgid)
}
setInstalledPackageId pkginfo = pkginfo
-- | Call @hc-pkg@ to get the source package Id of all the packages in the
-- given package database.
--
-- This is much less information than with 'dump', but also rather quicker.
-- Note in particular that it does not include the 'InstalledPackageId', just
-- the source 'PackageId' which is not necessarily unique in any package db.
--
list :: HcPkgInfo -> Verbosity -> PackageDB
-> IO [PackageId]
list hpi verbosity packagedb = do
output <- getProgramInvocationOutput verbosity
(listInvocation hpi verbosity packagedb)
`catchExit` \_ -> die $ programId (hcPkgProgram hpi) ++ " list failed"
case parsePackageIds output of
Just ok -> return ok
_ -> die $ "failed to parse output of '"
++ programId (hcPkgProgram hpi) ++ " list'"
where
parsePackageIds = sequence . map simpleParse . words
-- Create a view from either name or symlink via filepath.
createView :: HcPkgInfo -> Verbosity -> Either String FilePath -> IO ()
createView hpi verbosity view =
when (supportsView hpi) $ runProgramInvocation verbosity invocation
where
invocation = programInvocation (hcPkgProgram hpi) args
args = ["view", "create", packageDbOpts hpi UserPackageDB] ++
case view of
Left name -> [name]
Right path -> ["--view-file", path]
-- | Adds a package to the given view.
addPackageToView :: HcPkgInfo -> Verbosity
-> String -> InstalledPackageId -> IO ()
addPackageToView hpi verbosity view ipid = do
removePackageFromView hpi verbosity view pkgid
when (supportsView hpi) $ runProgramInvocation verbosity invocation
where
invocation = programInvocation (hcPkgProgram hpi) args
args = ["view-modify",
view, "add-package",
"--ipid", display ipid,
packageDbOpts hpi UserPackageDB]
-- init clashes with this module's init.
pkgid = List.init . reverse . snd . (span (/= '-')) . reverse $
display ipid
-- | Removes a package from the given view. As only one instance of package can
-- be in a view we do not need ipid. TODO: Fourth argument type must be
-- PackageId but there is no suitable InstalledPackageId to PackageId function
-- now.
removePackageFromView :: HcPkgInfo -> Verbosity
-> String -> String -> IO ()
removePackageFromView hpi verbosity view packageId =
when (supportsView hpi) $ runProgramInvocation verbosity invocation
where
invocation = programInvocation (hcPkgProgram hpi) args
args = ["view-modify",
view,
"remove-package",
packageId,
packageDbOpts hpi UserPackageDB]
-- TODO:
-- getPackagesInView -- For GC
--------------------------
-- The program invocations
--
initInvocation :: HcPkgInfo -> Verbosity -> FilePath -> ProgramInvocation
initInvocation hpi verbosity path =
programInvocation (hcPkgProgram hpi) args
where
args = ["init", path]
++ verbosityOpts hpi verbosity
registerInvocation, reregisterInvocation
:: HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath InstalledPackageInfo
-> ProgramInvocation
registerInvocation = registerInvocation' "register"
reregisterInvocation = registerInvocation' "update"
registerInvocation' :: String -> HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath InstalledPackageInfo
-> ProgramInvocation
registerInvocation' cmdname hpi verbosity packagedbs (Left pkgFile) =
programInvocation (hcPkgProgram hpi) args
where
args' = [cmdname, pkgFile]
++ (if noPkgDbStack hpi
then [packageDbOpts hpi (last packagedbs)]
else packageDbStackOpts hpi packagedbs)
++ verbosityOpts hpi verbosity
args = (if multInstEnabled hpi
then args' ++ ["--enable-multi-instance"]
else args')
registerInvocation' cmdname hpi verbosity packagedbs (Right pkgInfo) =
(programInvocation (hcPkgProgram hpi) args) {
progInvokeInput = Just (showInstalledPackageInfo pkgInfo),
progInvokeInputEncoding = IOEncodingUTF8
}
where
args' = [cmdname, "-"]
++ (if noPkgDbStack hpi
then [packageDbOpts hpi (last packagedbs)]
else packageDbStackOpts hpi packagedbs)
++ verbosityOpts hpi verbosity
args = (if multInstEnabled hpi
then args' ++ ["--enable-multi-instance"]
else args')
unregisterInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId
-> ProgramInvocation
unregisterInvocation hpi verbosity packagedb pkgid =
programInvocation (hcPkgProgram hpi) $
["unregister", packageDbOpts hpi packagedb, display pkgid]
++ verbosityOpts hpi verbosity
exposeInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId
-> ProgramInvocation
exposeInvocation hpi verbosity packagedb pkgid =
programInvocation (hcPkgProgram hpi) $
["expose", packageDbOpts hpi packagedb, display pkgid]
++ verbosityOpts hpi verbosity
hideInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId
-> ProgramInvocation
hideInvocation hpi verbosity packagedb pkgid =
programInvocation (hcPkgProgram hpi) $
["hide", packageDbOpts hpi packagedb, display pkgid]
++ verbosityOpts hpi verbosity
dumpInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> ProgramInvocation
dumpInvocation hpi _verbosity packagedb =
(programInvocation (hcPkgProgram hpi) args) {
progInvokeOutputEncoding = IOEncodingUTF8
}
where
args = ["dump", packageDbOpts hpi packagedb]
++ verbosityOpts hpi silent
-- We use verbosity level 'silent' because it is important that we
-- do not contaminate the output with info/debug messages.
listInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> ProgramInvocation
listInvocation hpi _verbosity packagedb =
(programInvocation (hcPkgProgram hpi) args) {
progInvokeOutputEncoding = IOEncodingUTF8
}
where
args = ["list", "--simple-output", packageDbOpts hpi packagedb]
++ verbosityOpts hpi silent
-- We use verbosity level 'silent' because it is important that we
-- do not contaminate the output with info/debug messages.
packageDbStackOpts :: HcPkgInfo -> PackageDBStack -> [String]
packageDbStackOpts hpi dbstack = case dbstack of
(GlobalPackageDB:UserPackageDB:dbs) -> "--global"
: "--user"
: map specific dbs
(GlobalPackageDB:dbs) -> "--global"
: ("--no-user-" ++ packageDbFlag hpi)
: map specific dbs
_ -> ierror
where
specific (SpecificPackageDB db) = "--" ++ packageDbFlag hpi ++ "=" ++ db
specific _ = ierror
ierror :: a
ierror = error ("internal error: unexpected package db stack: " ++ show dbstack)
packageDbFlag :: HcPkgInfo -> String
packageDbFlag hpi
| flagPackageConf hpi
= "package-conf"
| otherwise
= "package-db"
packageDbOpts :: HcPkgInfo -> PackageDB -> String
packageDbOpts _ GlobalPackageDB = "--global"
packageDbOpts _ UserPackageDB = "--user"
packageDbOpts hpi (SpecificPackageDB db) = "--" ++ packageDbFlag hpi ++ "=" ++ db
verbosityOpts :: HcPkgInfo -> Verbosity -> [String]
verbosityOpts hpi v
| noVerboseFlag hpi
= []
| v >= deafening = ["-v2"]
| v == silent = ["-v0"]
| otherwise = []
|
fugyk/cabal
|
Cabal/Distribution/Simple/Program/HcPkg.hs
|
Haskell
|
bsd-3-clause
| 16,572
|
{-# LANGUAGE NoImplicitPrelude #-}
module Jetski.Foreign.Return (
Return(..)
, storableReturn
, withReturn
, retVoid
, retInt8
, retInt16
, retInt32
, retInt64
, retWord8
, retWord16
, retWord32
, retWord64
, retFloat
, retDouble
, retCChar
, retCUChar
, retCWchar
, retCInt
, retCUInt
, retCLong
, retCULong
, retCSize
, retCTime
, retPtr
, retFunPtr
, retByteString
, retByteStringCopy
) where
import Data.Word (Word8, Word16, Word32, Word64)
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as B
import Foreign.Marshal (alloca)
import Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)
import Foreign.Storable (Storable(..))
import Foreign.C.Types (CChar, CUChar, CWchar)
import Foreign.C.Types (CInt, CUInt, CLong, CULong)
import Foreign.C.Types (CSize, CTime)
import Jetski.Foreign.Binding
import P
import System.IO (IO)
data Return a =
Return {
returnType :: !(Ptr CType)
, returnWith :: (Ptr CValue -> IO ()) -> IO a
}
instance Functor Return where
fmap f (Return typ withPoke) =
Return typ (fmap f . withPoke)
withReturn :: (a -> IO b) -> Return a -> Return b
withReturn f (Return typ withPoke) =
Return typ (withPoke >=> f)
storableReturn :: Storable a => Ptr CType -> Return a
storableReturn typ =
Return typ $ \write ->
alloca $ \ptr -> do
write (castPtr ptr)
peek ptr
retVoid :: Return ()
retVoid =
Return ffi_type_void $ \write -> do
write nullPtr
return ()
retInt8 :: Return Int8
retInt8 =
storableReturn ffi_type_sint8
retInt16 :: Return Int16
retInt16 =
storableReturn ffi_type_sint16
retInt32 :: Return Int32
retInt32 =
storableReturn ffi_type_sint32
retInt64 :: Return Int64
retInt64 =
storableReturn ffi_type_sint64
retWord8 :: Return Word8
retWord8 =
storableReturn ffi_type_uint8
retWord16 :: Return Word16
retWord16 =
storableReturn ffi_type_uint16
retWord32 :: Return Word32
retWord32 =
storableReturn ffi_type_uint32
retWord64 :: Return Word64
retWord64 =
storableReturn ffi_type_uint64
retFloat :: Return Float
retFloat =
storableReturn ffi_type_float
retDouble :: Return Double
retDouble =
storableReturn ffi_type_double
retCChar :: Return CChar
retCChar =
storableReturn ffi_type_schar
retCUChar :: Return CUChar
retCUChar =
storableReturn ffi_type_uchar
retCWchar :: Return CWchar
retCWchar =
storableReturn ffi_type_schar
retCInt :: Return CInt
retCInt =
storableReturn ffi_type_sint
retCUInt :: Return CUInt
retCUInt =
storableReturn ffi_type_uint
retCLong :: Return CLong
retCLong =
storableReturn ffi_type_slong
retCULong :: Return CULong
retCULong =
storableReturn ffi_type_ulong
retCSize :: Return CSize
retCSize =
storableReturn ffi_type_size
retCTime :: Return CTime
retCTime =
storableReturn ffi_type_time
retFunPtr :: Return a -> Return (FunPtr a)
retFunPtr _ =
storableReturn ffi_type_pointer
retPtr :: Return a -> Return (Ptr a)
retPtr _ =
storableReturn ffi_type_pointer
retByteString :: Return B.ByteString
retByteString =
withReturn B.packCString (retPtr retCChar)
retByteStringCopy :: Return B.ByteString
retByteStringCopy =
withReturn B.unsafePackMallocCString (retPtr retCChar)
|
ambiata/jetski
|
src/Jetski/Foreign/Return.hs
|
Haskell
|
bsd-3-clause
| 3,333
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.SMT.SMT
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Abstraction of SMT solvers
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DefaultSignatures #-}
module Data.SBV.SMT.SMT where
import qualified Control.Exception as C
import Control.Concurrent (newEmptyMVar, takeMVar, putMVar, forkIO)
import Control.DeepSeq (NFData(..))
import Control.Monad (when, zipWithM)
import Data.Char (isSpace)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.List (intercalate, isPrefixOf, isInfixOf)
import Data.Word (Word8, Word16, Word32, Word64)
import System.Directory (findExecutable)
import System.Process (runInteractiveProcess, waitForProcess, terminateProcess)
import System.Exit (ExitCode(..))
import System.IO (hClose, hFlush, hPutStr, hGetContents, hGetLine)
import qualified Data.Map as M
import Data.Typeable
import Data.SBV.BitVectors.AlgReals
import Data.SBV.BitVectors.Data
import Data.SBV.BitVectors.PrettyNum
import Data.SBV.Utils.Lib (joinArgs)
import Data.SBV.Utils.TDiff
-- | Extract the final configuration from a result
resultConfig :: SMTResult -> SMTConfig
resultConfig (Unsatisfiable c) = c
resultConfig (Satisfiable c _) = c
resultConfig (Unknown c _) = c
resultConfig (ProofError c _) = c
resultConfig (TimeOut c) = c
-- | A 'prove' call results in a 'ThmResult'
newtype ThmResult = ThmResult SMTResult
-- | A 'sat' call results in a 'SatResult'
-- The reason for having a separate 'SatResult' is to have a more meaningful 'Show' instance.
newtype SatResult = SatResult SMTResult
-- | An 'allSat' call results in a 'AllSatResult'. The boolean says whether
-- we should warn the user about prefix-existentials.
newtype AllSatResult = AllSatResult (Bool, [SMTResult])
-- | User friendly way of printing theorem results
instance Show ThmResult where
show (ThmResult r) = showSMTResult "Q.E.D."
"Unknown" "Unknown. Potential counter-example:\n"
"Falsifiable" "Falsifiable. Counter-example:\n" r
-- | User friendly way of printing satisfiablity results
instance Show SatResult where
show (SatResult r) = showSMTResult "Unsatisfiable"
"Unknown" "Unknown. Potential model:\n"
"Satisfiable" "Satisfiable. Model:\n" r
-- | The Show instance of AllSatResults. Note that we have to be careful in being lazy enough
-- as the typical use case is to pull results out as they become available.
instance Show AllSatResult where
show (AllSatResult (e, xs)) = go (0::Int) xs
where uniqueWarn | e = " (Unique up to prefix existentials.)"
| True = ""
go c (s:ss) = let c' = c+1
(ok, o) = sh c' s
in c' `seq` if ok then o ++ "\n" ++ go c' ss else o
go c [] = case c of
0 -> "No solutions found."
1 -> "This is the only solution." ++ uniqueWarn
_ -> "Found " ++ show c ++ " different solutions." ++ uniqueWarn
sh i c = (ok, showSMTResult "Unsatisfiable"
"Unknown" "Unknown. Potential model:\n"
("Solution #" ++ show i ++ ":\n[Backend solver returned no assignment to variables.]") ("Solution #" ++ show i ++ ":\n") c)
where ok = case c of
Satisfiable{} -> True
_ -> False
-- | The result of an 'sAssert' call
data SafeResult = SafeNeverFails
| SafeAlwaysFails String
| SafeFailsInModel String SMTConfig SMTModel
deriving Typeable
-- | The show instance for SafeResult. Note that this is for display purposes only,
-- user programs are likely to pattern match on the output and proceed accordingly.
instance Show SafeResult where
show SafeNeverFails = "No safety violations detected."
show (SafeAlwaysFails s) = intercalate "\n" ["Assertion failure: " ++ show s, "*** Fails in all assignments to inputs"]
show (SafeFailsInModel s cfg md) = intercalate "\n" ["Assertion failure: " ++ show s, showModel cfg md]
-- | If a 'prove' or 'sat' call comes accross an 'sAssert' call that fails, they will throw a 'SafeResult' as an exception.
instance C.Exception SafeResult
-- | Instances of 'SatModel' can be automatically extracted from models returned by the
-- solvers. The idea is that the sbv infrastructure provides a stream of 'CW''s (constant-words)
-- coming from the solver, and the type @a@ is interpreted based on these constants. Many typical
-- instances are already provided, so new instances can be declared with relative ease.
--
-- Minimum complete definition: 'parseCWs'
class SatModel a where
-- | Given a sequence of constant-words, extract one instance of the type @a@, returning
-- the remaining elements untouched. If the next element is not what's expected for this
-- type you should return 'Nothing'
parseCWs :: [CW] -> Maybe (a, [CW])
-- | Given a parsed model instance, transform it using @f@, and return the result.
-- The default definition for this method should be sufficient in most use cases.
cvtModel :: (a -> Maybe b) -> Maybe (a, [CW]) -> Maybe (b, [CW])
cvtModel f x = x >>= \(a, r) -> f a >>= \b -> return (b, r)
default parseCWs :: Read a => [CW] -> Maybe (a, [CW])
parseCWs (CW _ (CWUserSort (_, s)) : r) = Just (read s, r)
parseCWs _ = Nothing
-- | Parse a signed/sized value from a sequence of CWs
genParse :: Integral a => Kind -> [CW] -> Maybe (a, [CW])
genParse k (x@(CW _ (CWInteger i)):r) | kindOf x == k = Just (fromIntegral i, r)
genParse _ _ = Nothing
-- | Base case for 'SatModel' at unit type. Comes in handy if there are no real variables.
instance SatModel () where
parseCWs xs = return ((), xs)
-- | 'Bool' as extracted from a model
instance SatModel Bool where
parseCWs xs = do (x, r) <- genParse KBool xs
return ((x :: Integer) /= 0, r)
-- | 'Word8' as extracted from a model
instance SatModel Word8 where
parseCWs = genParse (KBounded False 8)
-- | 'Int8' as extracted from a model
instance SatModel Int8 where
parseCWs = genParse (KBounded True 8)
-- | 'Word16' as extracted from a model
instance SatModel Word16 where
parseCWs = genParse (KBounded False 16)
-- | 'Int16' as extracted from a model
instance SatModel Int16 where
parseCWs = genParse (KBounded True 16)
-- | 'Word32' as extracted from a model
instance SatModel Word32 where
parseCWs = genParse (KBounded False 32)
-- | 'Int32' as extracted from a model
instance SatModel Int32 where
parseCWs = genParse (KBounded True 32)
-- | 'Word64' as extracted from a model
instance SatModel Word64 where
parseCWs = genParse (KBounded False 64)
-- | 'Int64' as extracted from a model
instance SatModel Int64 where
parseCWs = genParse (KBounded True 64)
-- | 'Integer' as extracted from a model
instance SatModel Integer where
parseCWs = genParse KUnbounded
-- | 'AlgReal' as extracted from a model
instance SatModel AlgReal where
parseCWs (CW KReal (CWAlgReal i) : r) = Just (i, r)
parseCWs _ = Nothing
-- | 'Float' as extracted from a model
instance SatModel Float where
parseCWs (CW KFloat (CWFloat i) : r) = Just (i, r)
parseCWs _ = Nothing
-- | 'Double' as extracted from a model
instance SatModel Double where
parseCWs (CW KDouble (CWDouble i) : r) = Just (i, r)
parseCWs _ = Nothing
-- | 'CW' as extracted from a model; trivial definition
instance SatModel CW where
parseCWs (cw : r) = Just (cw, r)
parseCWs [] = Nothing
-- | A rounding mode, extracted from a model. (Default definition suffices)
instance SatModel RoundingMode
-- | A list of values as extracted from a model. When reading a list, we
-- go as long as we can (maximal-munch). Note that this never fails, as
-- we can always return the empty list!
instance SatModel a => SatModel [a] where
parseCWs [] = Just ([], [])
parseCWs xs = case parseCWs xs of
Just (a, ys) -> case parseCWs ys of
Just (as, zs) -> Just (a:as, zs)
Nothing -> Just ([], ys)
Nothing -> Just ([], xs)
-- | Tuples extracted from a model
instance (SatModel a, SatModel b) => SatModel (a, b) where
parseCWs as = do (a, bs) <- parseCWs as
(b, cs) <- parseCWs bs
return ((a, b), cs)
-- | 3-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c) => SatModel (a, b, c) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c), ds) <- parseCWs bs
return ((a, b, c), ds)
-- | 4-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c, SatModel d) => SatModel (a, b, c, d) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c, d), es) <- parseCWs bs
return ((a, b, c, d), es)
-- | 5-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c, SatModel d, SatModel e) => SatModel (a, b, c, d, e) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c, d, e), fs) <- parseCWs bs
return ((a, b, c, d, e), fs)
-- | 6-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c, SatModel d, SatModel e, SatModel f) => SatModel (a, b, c, d, e, f) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c, d, e, f), gs) <- parseCWs bs
return ((a, b, c, d, e, f), gs)
-- | 7-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c, SatModel d, SatModel e, SatModel f, SatModel g) => SatModel (a, b, c, d, e, f, g) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c, d, e, f, g), hs) <- parseCWs bs
return ((a, b, c, d, e, f, g), hs)
-- | Various SMT results that we can extract models out of.
class Modelable a where
-- | Is there a model?
modelExists :: a -> Bool
-- | Extract a model, the result is a tuple where the first argument (if True)
-- indicates whether the model was "probable". (i.e., if the solver returned unknown.)
getModel :: SatModel b => a -> Either String (Bool, b)
-- | Extract a model dictionary. Extract a dictionary mapping the variables to
-- their respective values as returned by the SMT solver. Also see `getModelDictionaries`.
getModelDictionary :: a -> M.Map String CW
-- | Extract a model value for a given element. Also see `getModelValues`.
getModelValue :: SymWord b => String -> a -> Maybe b
getModelValue v r = fromCW `fmap` (v `M.lookup` getModelDictionary r)
-- | Extract a representative name for the model value of an uninterpreted kind.
-- This is supposed to correspond to the value as computed internally by the
-- SMT solver; and is unportable from solver to solver. Also see `getModelUninterpretedValues`.
getModelUninterpretedValue :: String -> a -> Maybe String
getModelUninterpretedValue v r = case v `M.lookup` getModelDictionary r of
Just (CW _ (CWUserSort (_, s))) -> Just s
_ -> Nothing
-- | A simpler variant of 'getModel' to get a model out without the fuss.
extractModel :: SatModel b => a -> Maybe b
extractModel a = case getModel a of
Right (_, b) -> Just b
_ -> Nothing
-- | Return all the models from an 'allSat' call, similar to 'extractModel' but
-- is suitable for the case of multiple results.
extractModels :: SatModel a => AllSatResult -> [a]
extractModels (AllSatResult (_, xs)) = [ms | Right (_, ms) <- map getModel xs]
-- | Get dictionaries from an all-sat call. Similar to `getModelDictionary`.
getModelDictionaries :: AllSatResult -> [M.Map String CW]
getModelDictionaries (AllSatResult (_, xs)) = map getModelDictionary xs
-- | Extract value of a variable from an all-sat call. Similar to `getModelValue`.
getModelValues :: SymWord b => String -> AllSatResult -> [Maybe b]
getModelValues s (AllSatResult (_, xs)) = map (s `getModelValue`) xs
-- | Extract value of an uninterpreted variable from an all-sat call. Similar to `getModelUninterpretedValue`.
getModelUninterpretedValues :: String -> AllSatResult -> [Maybe String]
getModelUninterpretedValues s (AllSatResult (_, xs)) = map (s `getModelUninterpretedValue`) xs
-- | 'ThmResult' as a generic model provider
instance Modelable ThmResult where
getModel (ThmResult r) = getModel r
modelExists (ThmResult r) = modelExists r
getModelDictionary (ThmResult r) = getModelDictionary r
-- | 'SatResult' as a generic model provider
instance Modelable SatResult where
getModel (SatResult r) = getModel r
modelExists (SatResult r) = modelExists r
getModelDictionary (SatResult r) = getModelDictionary r
-- | 'SMTResult' as a generic model provider
instance Modelable SMTResult where
getModel (Unsatisfiable _) = Left "SBV.getModel: Unsatisfiable result"
getModel (Unknown _ m) = Right (True, parseModelOut m)
getModel (ProofError _ s) = error $ unlines $ "Backend solver complains: " : s
getModel (TimeOut _) = Left "Timeout"
getModel (Satisfiable _ m) = Right (False, parseModelOut m)
modelExists (Satisfiable{}) = True
modelExists (Unknown{}) = False -- don't risk it
modelExists _ = False
getModelDictionary (Unsatisfiable _) = M.empty
getModelDictionary (Unknown _ m) = M.fromList (modelAssocs m)
getModelDictionary (ProofError _ _) = M.empty
getModelDictionary (TimeOut _) = M.empty
getModelDictionary (Satisfiable _ m) = M.fromList (modelAssocs m)
-- | Extract a model out, will throw error if parsing is unsuccessful
parseModelOut :: SatModel a => SMTModel -> a
parseModelOut m = case parseCWs [c | (_, c) <- modelAssocs m] of
Just (x, []) -> x
Just (_, ys) -> error $ "SBV.getModel: Partially constructed model; remaining elements: " ++ show ys
Nothing -> error $ "SBV.getModel: Cannot construct a model from: " ++ show m
-- | Given an 'allSat' call, we typically want to iterate over it and print the results in sequence. The
-- 'displayModels' function automates this task by calling 'disp' on each result, consecutively. The first
-- 'Int' argument to 'disp' 'is the current model number. The second argument is a tuple, where the first
-- element indicates whether the model is alleged (i.e., if the solver is not sure, returing Unknown)
displayModels :: SatModel a => (Int -> (Bool, a) -> IO ()) -> AllSatResult -> IO Int
displayModels disp (AllSatResult (_, ms)) = do
inds <- zipWithM display [a | Right a <- map (getModel . SatResult) ms] [(1::Int)..]
return $ last (0:inds)
where display r i = disp i r >> return i
-- | Show an SMTResult; generic version
showSMTResult :: String -> String -> String -> String -> String -> SMTResult -> String
showSMTResult unsatMsg unkMsg unkMsgModel satMsg satMsgModel result = case result of
Unsatisfiable _ -> unsatMsg
Satisfiable _ (SMTModel [] [] []) -> satMsg
Satisfiable _ m -> satMsgModel ++ showModel cfg m
Unknown _ (SMTModel [] [] []) -> unkMsg
Unknown _ m -> unkMsgModel ++ showModel cfg m
ProofError _ [] -> "*** An error occurred. No additional information available. Try running in verbose mode"
ProofError _ ls -> "*** An error occurred.\n" ++ intercalate "\n" (map ("*** " ++) ls)
TimeOut _ -> "*** Timeout"
where cfg = resultConfig result
-- | Show a model in human readable form
showModel :: SMTConfig -> SMTModel -> String
showModel cfg m = intercalate "\n" (map shM assocs ++ concatMap shUI uninterps ++ concatMap shUA arrs)
where assocs = modelAssocs m
uninterps = modelUninterps m
arrs = modelArrays m
shM (s, v) = " " ++ s ++ " = " ++ shCW cfg v
-- | Show a constant value, in the user-specified base
shCW :: SMTConfig -> CW -> String
shCW = sh . printBase
where sh 2 = binS
sh 10 = show
sh 16 = hexS
sh n = \w -> show w ++ " -- Ignoring unsupported printBase " ++ show n ++ ", use 2, 10, or 16."
-- | Print uninterpreted function values from models. Very, very crude..
shUI :: (String, [String]) -> [String]
shUI (flong, cases) = (" -- uninterpreted: " ++ f) : map shC cases
where tf = dropWhile (/= '_') flong
f = if null tf then flong else tail tf
shC s = " " ++ s
-- | Print uninterpreted array values from models. Very, very crude..
shUA :: (String, [String]) -> [String]
shUA (f, cases) = (" -- array: " ++ f) : map shC cases
where shC s = " " ++ s
-- | Helper function to spin off to an SMT solver.
pipeProcess :: SMTConfig -> String -> [String] -> SMTScript -> (String -> String) -> IO (Either String [String])
pipeProcess cfg execName opts script cleanErrs = do
let nm = show (name (solver cfg))
mbExecPath <- findExecutable execName
case mbExecPath of
Nothing -> return $ Left $ "Unable to locate executable for " ++ nm
++ "\nExecutable specified: " ++ show execName
Just execPath ->
do solverResult <- dispatchSolver cfg execPath opts script
case solverResult of
Left s -> return $ Left s
Right (ec, contents, allErrors) ->
let errors = dropWhile isSpace (cleanErrs allErrors)
in case (null errors, xformExitCode (solver cfg) ec) of
(True, ExitSuccess) -> return $ Right $ map clean (filter (not . null) (lines contents))
(_, ec') -> let errors' = if null errors
then (if null (dropWhile isSpace contents)
then "(No error message printed on stderr by the executable.)"
else contents)
else errors
finalEC = case (ec', ec) of
(ExitFailure n, _) -> n
(_, ExitFailure n) -> n
_ -> 0 -- can happen if ExitSuccess but there is output on stderr
in return $ Left $ "Failed to complete the call to " ++ nm
++ "\nExecutable : " ++ show execPath
++ "\nOptions : " ++ joinArgs opts
++ "\nExit code : " ++ show finalEC
++ "\nSolver output: "
++ "\n" ++ line ++ "\n"
++ intercalate "\n" (filter (not . null) (lines errors'))
++ "\n" ++ line
++ "\nGiving up.."
where clean = reverse . dropWhile isSpace . reverse . dropWhile isSpace
line = replicate 78 '='
-- | A standard solver interface. If the solver is SMT-Lib compliant, then this function should suffice in
-- communicating with it.
standardSolver :: SMTConfig -> SMTScript -> (String -> String) -> ([String] -> a) -> ([String] -> a) -> IO a
standardSolver config script cleanErrs failure success = do
let msg = when (verbose config) . putStrLn . ("** " ++)
smtSolver= solver config
exec = executable smtSolver
opts = options smtSolver
isTiming = timing config
nmSolver = show (name smtSolver)
msg $ "Calling: " ++ show (unwords (exec:[joinArgs opts]))
case smtFile config of
Nothing -> return ()
Just f -> do msg $ "Saving the generated script in file: " ++ show f
writeFile f (scriptBody script)
contents <- timeIf isTiming nmSolver $ pipeProcess config exec opts script cleanErrs
msg $ nmSolver ++ " output:\n" ++ either id (intercalate "\n") contents
case contents of
Left e -> return $ failure (lines e)
Right xs -> return $ success (mergeSExpr xs)
-- | Wrap the solver call to protect against any exceptions
dispatchSolver :: SMTConfig -> FilePath -> [String] -> SMTScript -> IO (Either String (ExitCode, String, String))
dispatchSolver cfg execPath opts script = rnf script `seq` (Right `fmap` runSolver cfg execPath opts script) `C.catch` (\(e::C.SomeException) -> bad (show e))
where bad s = return $ Left $ unlines [ "Failed to start the external solver: " ++ s
, "Make sure you can start " ++ show execPath
, "from the command line without issues."
]
-- | A variant of 'readProcessWithExitCode'; except it knows about continuation strings
-- and can speak SMT-Lib2 (just a little).
runSolver :: SMTConfig -> FilePath -> [String] -> SMTScript -> IO (ExitCode, String, String)
runSolver cfg execPath opts script
= do (send, ask, cleanUp, pid) <- do
(inh, outh, errh, pid) <- runInteractiveProcess execPath opts Nothing Nothing
let send l = hPutStr inh (l ++ "\n") >> hFlush inh
recv = hGetLine outh
ask l = send l >> recv
cleanUp response
= do hClose inh
outMVar <- newEmptyMVar
out <- hGetContents outh
_ <- forkIO $ C.evaluate (length out) >> putMVar outMVar ()
err <- hGetContents errh
_ <- forkIO $ C.evaluate (length err) >> putMVar outMVar ()
takeMVar outMVar
takeMVar outMVar
hClose outh
hClose errh
ex <- waitForProcess pid
return $ case response of
Nothing -> (ex, out, err)
Just (r, vals) -> -- if the status is unknown, prepare for the possibility of not having a model
-- TBD: This is rather crude and potentially Z3 specific
let finalOut = intercalate "\n" (r : vals)
notAvail = "model is not available" `isInfixOf` (finalOut ++ out ++ err)
in if "unknown" `isPrefixOf` r && notAvail
then (ExitSuccess, "unknown" , "")
else (ex, finalOut ++ "\n" ++ out, err)
return (send, ask, cleanUp, pid)
let executeSolver = do mapM_ send (lines (scriptBody script))
response <- case scriptModel script of
Nothing -> do send $ satCmd cfg
return Nothing
Just ls -> do r <- ask $ satCmd cfg
vals <- if any (`isPrefixOf` r) ["sat", "unknown"]
then do let mls = lines ls
when (verbose cfg) $ do putStrLn "** Sending the following model extraction commands:"
mapM_ putStrLn mls
mapM ask mls
else return []
return $ Just (r, vals)
cleanUp response
executeSolver `C.onException` terminateProcess pid
-- | In case the SMT-Lib solver returns a response over multiple lines, compress them so we have
-- each S-Expression spanning only a single line. We'll ignore things line parentheses inside quotes
-- etc., as it should not be an issue
mergeSExpr :: [String] -> [String]
mergeSExpr [] = []
mergeSExpr (x:xs)
| d == 0 = x : mergeSExpr xs
| True = let (f, r) = grab d xs in unwords (x:f) : mergeSExpr r
where d = parenDiff x
parenDiff :: String -> Int
parenDiff = go 0
where go i "" = i
go i ('(':cs) = let i'= i+1 in i' `seq` go i' cs
go i (')':cs) = let i'= i-1 in i' `seq` go i' cs
go i (_ :cs) = go i cs
grab i ls
| i <= 0 = ([], ls)
grab _ [] = ([], [])
grab i (l:ls) = let (a, b) = grab (i+parenDiff l) ls in (l:a, b)
|
Copilot-Language/sbv-for-copilot
|
Data/SBV/SMT/SMT.hs
|
Haskell
|
bsd-3-clause
| 26,491
|
{-
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.0
Kubernetes API version: v1.9.12
Generated by Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
-}
{-|
Module : Kubernetes.OpenAPI.API.Events
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-unused-binds -fno-warn-unused-imports #-}
module Kubernetes.OpenAPI.API.Events where
import Kubernetes.OpenAPI.Core
import Kubernetes.OpenAPI.MimeTypes
import Kubernetes.OpenAPI.Model as M
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep)
import qualified Data.Foldable as P
import qualified Data.Map as Map
import qualified Data.Maybe as P
import qualified Data.Proxy as P (Proxy(..))
import qualified Data.Set as Set
import qualified Data.String as P
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Time as TI
import qualified Network.HTTP.Client.MultipartFormData as NH
import qualified Network.HTTP.Media as ME
import qualified Network.HTTP.Types as NH
import qualified Web.FormUrlEncoded as WH
import qualified Web.HttpApiData as WH
import Data.Text (Text)
import GHC.Base ((<|>))
import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor)
import qualified Prelude as P
-- * Operations
-- ** Events
-- *** getAPIGroup
-- | @GET \/apis\/events.k8s.io\/@
--
-- get information of a group
--
-- AuthMethod: 'AuthApiKeyBearerToken'
--
getAPIGroup
:: Accept accept -- ^ request accept ('MimeType')
-> KubernetesRequest GetAPIGroup MimeNoContent V1APIGroup accept
getAPIGroup _ =
_mkRequest "GET" ["/apis/events.k8s.io/"]
`_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyBearerToken)
data GetAPIGroup
-- | @application/json@
instance Consumes GetAPIGroup MimeJSON
-- | @application/yaml@
instance Consumes GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Consumes GetAPIGroup MimeVndKubernetesProtobuf
-- | @application/json@
instance Produces GetAPIGroup MimeJSON
-- | @application/yaml@
instance Produces GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Produces GetAPIGroup MimeVndKubernetesProtobuf
|
denibertovic/haskell
|
kubernetes/lib/Kubernetes/OpenAPI/API/Events.hs
|
Haskell
|
bsd-3-clause
| 2,712
|
module ELc.Arbitrary where
import Language.ELc
import Lc.Arbitrary
import Test.QuickCheck
--------------------------------------------------------------
-- QuickCheck - Arbitratry
--------------------------------------------------------------
instance Arbitrary ELc where
arbitrary = arbitraryELc
instance Arbitrary Let where
arbitrary = arbitraryLet
arbitraryELc :: Gen ELc
arbitraryELc = oneof [ELcLet <$> arbitraryLet, ELc <$> arbitrary]
arbitraryLet :: Gen Let
arbitraryLet = Let <$> string <*> arbitrary
|
d-dorazio/lc
|
test/ELc/Arbitrary.hs
|
Haskell
|
bsd-3-clause
| 522
|
{-# LANGUAGE BangPatterns #-}
module Scrabble (makeDict,process,validHand,prettySC
,ScrabbleCommand(..),Sort(..),Dict,FilePath,Score) where
import Data.Array.Unboxed((!))
import Data.Ix(inRange)
import Data.List(group,sort)
import Data.Char(toUpper)
import Tiles(freqArray)
import Dict(Dict,build)
import Lookup(HandTiles(..),Hist(..),Score,lookupTiles,withTemplate,withTemplates)
--import Best(best)
import Control.OldException(catchJust,ioErrors)
import Data.List(sortBy)
hist :: [Int] -> Hist -- [(Int,Int)]
hist = Hist . map hist' . group . sort
where hist' xs = (head xs, length xs)
makeDict :: FilePath -> IO (Either String Dict)
makeDict file = catchJust ioErrors
(fmap (Right . build . lines) (readFile file))
(\e -> return (Left (show e)))
data Sort = Sort {iMethod :: Int, bReversed :: Bool} deriving Show
sortMethod :: Sort -> [(Score,String)] -> [(Score,String)]
sortMethod (Sort 1 False) = sortBy (flip compare)
sortMethod (Sort 1 True) = sort
sortMethod (Sort 2 False) = sortBy (flip compare `on` (length . snd))
sortMethod (Sort 2 True) = sortBy (compare `on` (length . snd))
sortMethod (Sort 3 False) = sortBy (compare `on` snd)
sortMethod (Sort 3 True) = sortBy (flip compare `on` snd)
sortMethod err = error $ "Scrabble.sortMethod failed "++show err
data ScrabbleCommand = LookupCommand {sTiles :: String, getSort :: Sort}
| TemplateCommand {sTiles :: String, sTemplate :: String, getSort :: Sort}
| TemplatesCommand {sTiles :: String, sTemplate :: String, getSort :: Sort}
deriving Show
prettySC :: ScrabbleCommand -> Score -> String
prettySC (LookupCommand {sTiles=hand}) bestScore = (show bestScore) ++ " " ++ hand
prettySC (TemplateCommand {sTiles=hand,sTemplate=template}) bestScore = (show bestScore) ++ " " ++ hand ++ " " ++ template
prettySC (TemplatesCommand {sTiles=hand,sTemplate=template}) bestScore = (show bestScore) ++ " " ++ hand ++ " " ++ template
parseTiles :: String -> HandTiles
--parseTiles :: String -> (Int, [(Int,Int)], Int)
parseTiles tiles = HandTiles wilds h (length tiles)
where wilds = length (filter (dot ==) tiles)
h = hist . map fromEnum . map toUpper . filter (dot /=) $ tiles
dot = '.'
-- Returns sorted (and perhaps limited) results
process :: Dict -> ScrabbleCommand -> [(Score,String)]
process t command = post . sortMethod (getSort command) $ results where
hand = parseTiles (sTiles command)
post | validHand hand = id
| otherwise = take 100
results = case command of
LookupCommand {} -> lookupTiles t hand
TemplateCommand {} -> withTemplate t hand (sTemplate command)
TemplatesCommand {} -> withTemplates t hand (sTemplate command)
on :: (b->b->c) -> (a->b) -> (a -> a -> c)
f `on` g = (\a b -> (g a) `f` (g b))
validHand :: HandTiles -> Bool
validHand (HandTiles wilds (Hist h) n) = inRange (0,2) wilds && inRange (1,7) n && and (map validCharFreq h)
where validCharFreq (c,f) = inRange (1,freqArray ! c) f
|
ChrisKuklewicz/XWords
|
src/Scrabble.hs
|
Haskell
|
bsd-3-clause
| 3,074
|
{-# LANGUAGE OverloadedStrings #-}
module CryptoTest (tests, cbTests) where
import System.IO
import System.IO.Temp
import System.Posix.IO
import Control.Monad (liftM, when)
import Control.Monad.Trans.Maybe
import Control.Monad.IO.Class
import Control.Monad.Catch
import Control.Concurrent
import Data.List (isInfixOf)
import Data.ByteString.Char8 ()
import Data.Maybe ( fromJust )
import qualified Data.ByteString as BS
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase)
import Test.Tasty.QuickCheck
import Test.HUnit hiding (assert)
import Test.QuickCheck.Monadic
import Crypto.Gpgme
import Crypto.Gpgme.Types ( GpgmeError (GpgmeError)
, SignMode ( Clear, Detach, Normal )
)
import TestUtil
tests :: TestTree
tests = testGroup "crypto"
[ testProperty "bob_encrypt_for_alice_decrypt_prompt_no_travis"
$ bob_encrypt_for_alice_decrypt False
, testProperty "bob_encrypt_sign_for_alice_decrypt_verify_prompt_no_travis"
$ bob_encrypt_sign_for_alice_decrypt_verify False
, testProperty "bob_encrypt_for_alice_decrypt_short_prompt_no_travis"
bob_encrypt_for_alice_decrypt_short
, testProperty "bob_encrypt_sign_for_alice_decrypt_verify_short_prompt_no_travis"
bob_encrypt_sign_for_alice_decrypt_verify_short
, testCase "decrypt_garbage" decrypt_garbage
, testCase "encrypt_wrong_key" encrypt_wrong_key
, testCase "bob_encrypt_symmetrically_prompt_no_travis" bob_encrypt_symmetrically
, testCase "bob_detach_sign_and_verify_specify_key_prompt_no_travis" bob_detach_sign_and_verify_specify_key_prompt
, testCase "bob_clear_sign_and_verify_specify_key_prompt_no_travis" bob_clear_sign_and_verify_specify_key_prompt
, testCase "bob_clear_sign_and_verify_default_key_prompt_no_travis" bob_clear_sign_and_verify_default_key_prompt
, testCase "bob_normal_sign_and_verify_specify_key_prompt_no_travis" bob_normal_sign_and_verify_specify_key_prompt
, testCase "bob_normal_sign_and_verify_default_key_prompt_no_travis" bob_normal_sign_and_verify_default_key_prompt
, testCase "encrypt_file_no_travis" encrypt_file
, testCase "encrypt_stream_no_travis" encrypt_stream
]
cbTests :: IO TestTree
cbTests = do
supported <- withCtx "test/bob" "C" OpenPGP $ \ctx ->
return $ isPassphraseCbSupported ctx
if supported
then return $ testGroup "passphrase-cb"
[ testProperty "bob_encrypt_for_alice_decrypt"
$ bob_encrypt_for_alice_decrypt True
, testProperty "bob_encrypt_sign_for_alice_decrypt_verify_with_passphrase_cb_prompt_no_travis"
$ bob_encrypt_sign_for_alice_decrypt_verify True
]
else return $ testGroup "passphrase-cb" []
hush :: Monad m => m (Either e a) -> MaybeT m a
hush = MaybeT . liftM (either (const Nothing) Just)
withPassphraseCb :: String -> Ctx -> IO ()
withPassphraseCb passphrase ctx = do
setPassphraseCallback ctx (Just callback)
where
callback _ _ _ = return (Just passphrase)
bob_encrypt_for_alice_decrypt :: Bool -> Plain -> Property
bob_encrypt_for_alice_decrypt passphrCb plain =
not (BS.null plain) ==> monadicIO $ do
dec <- run encr_and_decr
assert $ dec == plain
where encr_and_decr =
do -- encrypt
Just enc <- withCtx "test/bob" "C" OpenPGP $ \bCtx -> runMaybeT $ do
aPubKey <- MaybeT $ getKey bCtx alice_pub_fpr NoSecret
hush $ encrypt bCtx [aPubKey] NoFlag plain
-- decrypt
dec <- withCtx "test/alice" "C" OpenPGP $ \aCtx -> do
when passphrCb $ withPassphraseCb "alice123" aCtx
decrypt aCtx enc
return $ fromRight dec
bob_encrypt_for_alice_decrypt_short :: Plain -> Property
bob_encrypt_for_alice_decrypt_short plain =
not (BS.null plain) ==> monadicIO $ do
dec <- run encr_and_decr
assert $ dec == plain
where encr_and_decr =
do -- encrypt
enc <- encrypt' "test/bob" alice_pub_fpr plain
-- decrypt
dec <- decrypt' "test/alice" (fromRight enc)
return $ fromRight dec
bob_encrypt_sign_for_alice_decrypt_verify :: Bool -> Plain -> Property
bob_encrypt_sign_for_alice_decrypt_verify passphrCb plain =
not (BS.null plain) ==> monadicIO $ do
dec <- run encr_and_decr
assert $ dec == plain
where encr_and_decr =
do -- encrypt
Just enc <- withCtx "test/bob" "C" OpenPGP $ \bCtx -> runMaybeT $ do
aPubKey <- MaybeT $ getKey bCtx alice_pub_fpr NoSecret
hush $ encryptSign bCtx [aPubKey] NoFlag plain
-- decrypt
dec <- withCtx "test/alice" "C" OpenPGP $ \aCtx -> do
when passphrCb $ withPassphraseCb "alice123" aCtx
decryptVerify aCtx enc
return $ fromRight dec
bob_encrypt_sign_for_alice_decrypt_verify_short :: Plain -> Property
bob_encrypt_sign_for_alice_decrypt_verify_short plain =
not (BS.null plain) ==> monadicIO $ do
dec <- run encr_and_decr
assert $ dec == plain
where encr_and_decr =
do -- encrypt
enc <- encryptSign' "test/bob" alice_pub_fpr plain
-- decrypt
dec <- decryptVerify' "test/alice" (fromRight enc)
return $ fromRight dec
encrypt_wrong_key :: Assertion
encrypt_wrong_key = do
res <- encrypt' "test/bob" "INEXISTENT" "plaintext"
assertBool "should fail" (isLeft res)
let err = fromLeft res
assertBool "should contain key" ("INEXISTENT" `isInfixOf` err)
decrypt_garbage :: Assertion
decrypt_garbage = do
val <- withCtx "test/bob" "C" OpenPGP $ \bCtx ->
decrypt bCtx (BS.pack [1,2,3,4,5,6])
isLeft val @? "should be left " ++ show val
bob_encrypt_symmetrically :: Assertion
bob_encrypt_symmetrically = do
-- encrypt
cipher <- fmap fromRight $
withCtx "test/bob" "C" OpenPGP $ \ctx ->
encrypt ctx [] NoFlag "plaintext"
assertBool "must not be plain" (cipher /= "plaintext")
-- decrypt
plain <- fmap fromRight $
withCtx "test/alice" "C" OpenPGP $ \ctx ->
decrypt ctx cipher
assertEqual "should decrypt to same" "plaintext" plain
bob_detach_sign_and_verify_specify_key_prompt :: Assertion
bob_detach_sign_and_verify_specify_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
key <- getKey ctx bob_pub_fpr NoSecret
let msgToSign = "Clear text message from bob!!"
resSign <-sign ctx [(fromJust key)] Detach msgToSign
verifyDetached ctx (fromRight resSign) msgToSign
assertBool "Could not verify bob's signature was correct" $ isVerifyDetachValid resVerify
bob_clear_sign_and_verify_specify_key_prompt :: Assertion
bob_clear_sign_and_verify_specify_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
key <- getKey ctx bob_pub_fpr NoSecret
resSign <- sign ctx [(fromJust key)] Clear "Clear text message from bob specifying signing key"
verifyPlain ctx (fromRight resSign) ""
assertBool "Could not verify bob's signature was correct" $ isVerifyValid resVerify
bob_clear_sign_and_verify_default_key_prompt :: Assertion
bob_clear_sign_and_verify_default_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
resSign <- sign ctx [] Clear "Clear text message from bob with default key"
verifyPlain ctx (fromRight resSign) ""
assertBool "Could not verify bob's signature was correct" $ isVerifyValid resVerify
bob_normal_sign_and_verify_specify_key_prompt :: Assertion
bob_normal_sign_and_verify_specify_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
key <- getKey ctx bob_pub_fpr NoSecret
resSign <- sign ctx [(fromJust key)] Normal "Normal text message from bob specifying signing key"
verify ctx (fromRight resSign)
assertBool "Could not verify bob's signature was correct" $ isVerifyValid resVerify
bob_normal_sign_and_verify_default_key_prompt :: Assertion
bob_normal_sign_and_verify_default_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
resSign <- sign ctx [] Normal "Normal text message from bob with default key"
verify ctx (fromRight resSign)
assertBool "Could not verify bob's signature was correct" $ isVerifyValid resVerify
encrypt_file :: Assertion
encrypt_file =
withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
withPassphraseCb "bob123" ctx
withTestTmpFiles $ \pp ph cp ch dp dh -> do
plainFd <- handleToFd ph
cipherFd <- handleToFd ch
decryptedFd <- handleToFd dh
key <- getKey ctx bob_pub_fpr NoSecret
-- Add plaintext content
writeFile pp "Plaintext contents. 1234go!"
-- Encrypt plaintext
resEnc <- encryptFd ctx [(fromJust key)] NoFlag plainFd cipherFd
if (resEnc == Right ())
then return ()
else assertFailure $ show resEnc
-- Recreate the cipher FD because it is closed (or something) from the encrypt command
cipherHandle' <- openFile cp ReadWriteMode
cipherFd' <- handleToFd cipherHandle'
-- Decrypt ciphertext
resDec <- decryptFd ctx cipherFd' decryptedFd
if (resDec == Right ())
then return ()
else assertFailure $ show resDec
-- Compare plaintext and decrypted text
plaintext <- readFile pp
decryptedtext <- readFile dp
plaintext @=? decryptedtext
-- Encrypt from FD pipe into a FD file
encrypt_stream :: Assertion
encrypt_stream =
withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
withPassphraseCb "bob123" ctx
withTestTmpFiles $ \_ _ cp ch dp dh -> do
cipherFd <- handleToFd ch
decryptedFd <- handleToFd dh
-- Use bob's key
key <- getKey ctx bob_pub_fpr NoSecret
-- Create pipe
(pipeRead, pipeWrite) <- createPipe
-- Write to pipe
-- Add plaintext content
let testString = take (1000) $ repeat '.'
_ <- forkIO $ do
threadWaitWrite pipeWrite
_ <- fdWrite pipeWrite testString
closeFd pipeWrite
-- Start encrypting in thread
_ <- forkIO $ do
threadWaitRead pipeRead
_ <- encryptFd ctx [(fromJust key)] NoFlag pipeRead cipherFd
closeFd pipeRead
-- Wait a second for threads to finish
threadDelay (1000 * 1000 * 1)
-- Check result
-- Recreate the cipher FD because it is closed (or something) from the encrypt command
threadWaitRead cipherFd
ch' <- openFile cp ReadWriteMode
cipherFd' <- handleToFd ch'
-- Decrypt ciphertext
resDec <- decryptFd ctx cipherFd' decryptedFd
if (resDec == Right ())
then return ()
else assertFailure $ show resDec
-- Compare plaintext and decrypted text
decryptedtext <-readFile dp
testString @=? decryptedtext
withTestTmpFiles :: (MonadIO m, MonadMask m)
=> ( FilePath -> Handle -- Plaintext
-> FilePath -> Handle -- Ciphertext
-> FilePath -> Handle -- Decrypted text
-> m a)
-> m a
withTestTmpFiles f =
withSystemTempFile "plain" $ \pp ph ->
withSystemTempFile "cipher" $ \cp ch ->
withSystemTempFile "decrypt" $ \dp dh ->
f pp ph cp ch dp dh
-- Verify that the signature verification is successful
isVerifyValid :: Either t ([(GpgmeError, [SignatureSummary], t1)], t2) -> Bool
isVerifyValid (Right ((v:[]), _)) = (isVerifyValid' v)
isVerifyValid (Right ((v:vs), t)) = (isVerifyValid' v) && isVerifyValid (Right (vs,t))
isVerifyValid _ = False
isVerifyValid' :: (GpgmeError, [SignatureSummary], t) -> Bool
isVerifyValid' (GpgmeError 0, [Green,Valid], _) = True
isVerifyValid' _ = False
-- Verify that the signature verification is successful for verifyDetach
isVerifyDetachValid :: Either t [(GpgmeError, [SignatureSummary], t1)] -> Bool
isVerifyDetachValid (Right ((v:[]))) = (isVerifyDetachValid' v)
isVerifyDetachValid (Right ((v:vs))) = (isVerifyDetachValid' v) && isVerifyDetachValid (Right vs)
isVerifyDetachValid _ = False
isVerifyDetachValid' :: (GpgmeError, [SignatureSummary], t) -> Bool
isVerifyDetachValid' (GpgmeError 0, [Green,Valid], _) = True
isVerifyDetachValid' _ = False
|
mmhat/h-gpgme
|
test/CryptoTest.hs
|
Haskell
|
mit
| 12,536
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE CPP #-}
module Network.Wai.Handler.Warp.HTTP2.Worker (
Respond
, response
, worker
) where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative
#endif
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception (Exception, SomeException(..), AsyncException(..))
import qualified Control.Exception as E
import Control.Monad (void, when)
import Data.Typeable
import qualified Network.HTTP.Types as H
import Network.HTTP2
import Network.HTTP2.Priority
import Network.Wai
import Network.Wai.Handler.Warp.HTTP2.EncodeFrame
import Network.Wai.Handler.Warp.HTTP2.Manager
import Network.Wai.Handler.Warp.HTTP2.Types
import Network.Wai.Handler.Warp.IORef
import Network.Wai.HTTP2
( Chunk(..)
, HTTP2Application
, PushPromise
, Responder(runResponder)
, RespondFunc
)
import qualified Network.Wai.Handler.Warp.Settings as S
import qualified Network.Wai.Handler.Warp.Timeout as T
----------------------------------------------------------------
-- | An 'HTTP2Application' takes a function of status, headers, trailers, and
-- body; this type implements that by currying some internal arguments.
--
-- The token type of the RespondFunc is set to be (). This is a bit
-- anti-climactic, but the real benefit of the token type is that the
-- application is forced to call the responder, and making it a boring type
-- doesn't break that property.
--
-- This is the argument to a 'Responder'.
type Respond = IO () -> Stream -> RespondFunc ()
-- | This function is passed to workers. They also pass responses from
-- 'HTTP2Application's to this function. This function enqueues commands for
-- the HTTP/2 sender.
response :: Context -> Manager -> ThreadContinue -> Respond
response ctx mgr tconf tickle strm s h strmbdy = do
-- TODO(awpr) HEAD requests will still stream.
-- We must not exit this WAI application.
-- If the application exits, streaming would be also closed.
-- So, this work occupies this thread.
--
-- We need to increase the number of workers.
myThreadId >>= replaceWithAction mgr
-- After this work, this thread stops to decrease the number of workers.
setThreadContinue tconf False
runStream ctx OResponse tickle strm s h strmbdy
-- | Set up a waiter thread and run the stream body with functions to enqueue
-- 'Sequence's on the stream's queue.
runStream :: Context
-> (Stream -> H.Status -> H.ResponseHeaders -> Aux -> Output)
-> Respond
runStream Context{outputQ} mkOutput tickle strm s h strmbdy = do
-- Since 'Body' is loop, we cannot control it.
-- So, let's serialize 'Builder' with a designated queue.
sq <- newTBQueueIO 10 -- fixme: hard coding: 10
tvar <- newTVarIO SyncNone
let out = mkOutput strm s h (Persist sq tvar)
-- Since we must not enqueue an empty queue to the priority
-- queue, we spawn a thread to ensure that the designated
-- queue is not empty.
void $ forkIO $ waiter tvar sq strm outputQ
atomically $ writeTVar tvar (SyncNext out)
let write chunk = do
atomically $ writeTBQueue sq $ case chunk of
BuilderChunk b -> SBuilder b
FileChunk path part -> SFile path part
tickle
flush = atomically $ writeTBQueue sq SFlush
trailers <- strmbdy write flush
atomically $ writeTBQueue sq $ SFinish trailers
-- | Handle abnormal termination of a stream: mark it as closed, send a reset
-- frame, and call the user's 'settingsOnException' handler if applicable.
cleanupStream :: Context -> S.Settings -> Stream -> Maybe Request -> Maybe SomeException -> IO ()
cleanupStream ctx@Context{outputQ} set strm req me = do
closed strm Killed ctx
let sid = streamNumber strm
frame = resetFrame InternalError sid
enqueue outputQ sid controlPriority $ OFrame frame
case me of
Nothing -> return ()
Just e -> S.settingsOnException set req e
-- | Push the given 'Responder' to the client if the settings allow it
-- (specifically 'enablePush' and 'maxConcurrentStreams'). Returns 'True' if
-- the stream was actually pushed.
--
-- This is the push function given to an 'HTTP2Application'.
pushResponder :: Context -> S.Settings -> Stream -> PushPromise -> Responder -> IO Bool
pushResponder ctx set strm promise responder = do
let Context{ http2settings
, pushConcurrency
} = ctx
cnt <- readIORef pushConcurrency
settings <- readIORef http2settings
let enabled = enablePush settings
fits = maybe True (cnt <) $ maxConcurrentStreams settings
canPush = fits && enabled
if canPush then
actuallyPushResponder ctx set strm promise responder
else
return False
-- | Set up a pushed stream and run the 'Responder' in its own thread. Waits
-- for the sender thread to handle the push request. This can fail to push the
-- stream and return 'False' if the sender dequeued the push request after the
-- associated stream was closed.
actuallyPushResponder :: Context -> S.Settings -> Stream -> PushPromise -> Responder -> IO Bool
actuallyPushResponder ctx set strm promise responder = do
let Context{ http2settings
, nextPushStreamId
, pushConcurrency
, streamTable
} = ctx
-- Claim the next outgoing stream.
newSid <- atomicModifyIORef nextPushStreamId $ \sid -> (sid+2, sid)
ws <- initialWindowSize <$> readIORef http2settings
newStrm <- newStream pushConcurrency newSid ws
-- Section 5.3.5 of RFC 7540 defines the weight of push promise is 16.
-- But we need not to follow the spec. So, this value would change
-- if necessary.
writeIORef (streamPriority newStrm) $
defaultPriority { streamDependency = streamNumber strm }
opened newStrm
insert streamTable newSid newStrm
-- Set up a channel for the sender to report back whether it pushed the
-- stream.
mvar <- newEmptyMVar
let mkOutput = OPush strm promise mvar
tickle = return ()
respond = runStream ctx mkOutput
-- TODO(awpr): synthesize a Request for 'settingsOnException'?
_ <- forkIO $ runResponder responder (respond tickle newStrm) `E.catch`
(cleanupStream ctx set strm Nothing . Just)
takeMVar mvar
data Break = Break deriving (Show, Typeable)
instance Exception Break
worker :: Context
-> S.Settings
-> T.Manager
-> HTTP2Application
-> (ThreadContinue -> Respond)
-> IO ()
worker ctx@Context{inputQ} set tm app respond = do
tid <- myThreadId
sinfo <- newStreamInfo
tcont <- newThreadContinue
let setup = T.register tm $ E.throwTo tid Break
E.bracket setup T.cancel $ go sinfo tcont
where
go sinfo tcont th = do
setThreadContinue tcont True
ex <- E.try $ do
T.pause th
Input strm req <- atomically $ readTQueue inputQ
setStreamInfo sinfo strm req
T.resume th
T.tickle th
let responder = app req $ pushResponder ctx set strm
runResponder responder $ respond tcont (T.tickle th) strm
cont1 <- case ex of
Right () -> return True
Left e@(SomeException _)
| Just Break <- E.fromException e -> do
cleanup sinfo Nothing
return True
-- killed by the sender
| Just ThreadKilled <- E.fromException e -> do
cleanup sinfo Nothing
return False
| otherwise -> do
cleanup sinfo (Just e)
return True
cont2 <- getThreadContinue tcont
when (cont1 && cont2) $ go sinfo tcont th
cleanup sinfo me = do
m <- getStreamInfo sinfo
case m of
Nothing -> return ()
Just (strm,req) -> do
cleanupStream ctx set strm (Just req) me
clearStreamInfo sinfo
-- | A dedicated waiter thread to re-enqueue the stream in the priority tree
-- whenever output becomes available. When the sender drains the queue and
-- moves on to another stream, it drops a message in the 'TVar', and this
-- thread wakes up, waits for more output to become available, and re-enqueues
-- the stream.
waiter :: TVar Sync -> TBQueue Sequence -> Stream -> PriorityTree Output -> IO ()
waiter tvar sq strm outQ = do
-- waiting for actions other than SyncNone
mx <- atomically $ do
mout <- readTVar tvar
case mout of
SyncNone -> retry
SyncNext out -> do
writeTVar tvar SyncNone
return $ Just out
SyncFinish -> return Nothing
case mx of
Nothing -> return ()
Just out -> do
-- ensuring that the streaming queue is not empty.
atomically $ do
isEmpty <- isEmptyTBQueue sq
when isEmpty retry
-- ensuring that stream window is greater than 0.
enqueueWhenWindowIsOpen outQ out
waiter tvar sq strm outQ
----------------------------------------------------------------
-- | It would nice if responders could return values to workers.
-- Unfortunately, 'ResponseReceived' is already defined in WAI 2.0.
-- It is not wise to change this type.
-- So, a reference is shared by a 'Respond' and its worker.
-- The reference refers a value of this type as a return value.
-- If 'True', the worker continue to serve requests.
-- Otherwise, the worker get finished.
newtype ThreadContinue = ThreadContinue (IORef Bool)
newThreadContinue :: IO ThreadContinue
newThreadContinue = ThreadContinue <$> newIORef True
setThreadContinue :: ThreadContinue -> Bool -> IO ()
setThreadContinue (ThreadContinue ref) x = writeIORef ref x
getThreadContinue :: ThreadContinue -> IO Bool
getThreadContinue (ThreadContinue ref) = readIORef ref
----------------------------------------------------------------
-- | The type to store enough information for 'settingsOnException'.
newtype StreamInfo = StreamInfo (IORef (Maybe (Stream,Request)))
newStreamInfo :: IO StreamInfo
newStreamInfo = StreamInfo <$> newIORef Nothing
clearStreamInfo :: StreamInfo -> IO ()
clearStreamInfo (StreamInfo ref) = writeIORef ref Nothing
setStreamInfo :: StreamInfo -> Stream -> Request -> IO ()
setStreamInfo (StreamInfo ref) strm req = writeIORef ref $ Just (strm,req)
getStreamInfo :: StreamInfo -> IO (Maybe (Stream, Request))
getStreamInfo (StreamInfo ref) = readIORef ref
|
soenkehahn/wai
|
warp/Network/Wai/Handler/Warp/HTTP2/Worker.hs
|
Haskell
|
mit
| 10,706
|
{-|
Types used in both Events and Effects.
-}
module Urbit.Arvo.Common
( KingId(..), ServId(..)
, Json, JsonNode(..)
, Desk(..), Mime(..)
, Port(..), Turf(..)
, HttpServerConf(..), PEM(..), Key, Cert
, HttpEvent(..), Method, Header(..), ResponseHeader(..)
, ReOrg(..), reorgThroughNoun
, AmesDest(..), Ipv4(..), Ipv6(..), Patp(..), Galaxy, AmesAddress(..)
) where
import Urbit.Prelude hiding (Term)
import qualified Network.HTTP.Types.Method as H
import qualified Urbit.Ob as Ob
-- Misc Types ------------------------------------------------------------------
{-|
Domain Name in TLD order:
["org", "urbit", "dns"] -> dns.urbit.org
-}
newtype Turf = Turf { unTurf :: [Cord] }
deriving newtype (Eq, Ord, Show, ToNoun, FromNoun)
newtype KingId = KingId { unKingId :: UV }
deriving newtype (Eq, Ord, Show, Num, Real, Enum, Integral, FromNoun, ToNoun)
newtype ServId = ServId { unServId :: UV }
deriving newtype (Eq, Ord, Show, Num, Enum, Integral, Real, FromNoun, ToNoun)
-- Http Common -----------------------------------------------------------------
data Header = Header Cord Bytes
deriving (Eq, Ord, Show)
data ResponseHeader = ResponseHeader
{ statusCode :: Word
, headers :: [Header]
}
deriving (Eq, Ord, Show)
data HttpEvent
= Start ResponseHeader (Maybe File) Bool
| Continue (Maybe File) Bool
| Cancel ()
deriving (Eq, Ord, Show)
deriveNoun ''ResponseHeader
deriveNoun ''Header
deriveNoun ''HttpEvent
-- Http Requests ---------------------------------------------------------------
type Method = H.StdMethod
-- TODO Hack! Don't write instances for library types. Write them for
-- our types instead.
instance ToNoun H.StdMethod where
toNoun = toNoun . MkBytes . H.renderStdMethod
instance FromNoun H.StdMethod where
parseNoun n = named "StdMethod" $ do
MkBytes bs <- parseNoun n
case H.parseMethod bs of
Left md -> fail ("Unexpected method: " <> unpack (decodeUtf8 md))
Right m -> pure m
-- Http Server Configuration ---------------------------------------------------
newtype PEM = PEM { unPEM :: Wain }
deriving newtype (Eq, Ord, Show, ToNoun, FromNoun)
type Key = PEM
type Cert = PEM
data HttpServerConf = HttpServerConf
{ hscSecure :: Maybe (Key, Cert)
, hscProxy :: Bool
, hscLog :: Bool
, hscRedirect :: Bool
}
deriving (Eq, Ord, Show)
deriveNoun ''HttpServerConf
-- Desk and Mime ---------------------------------------------------------------
newtype Desk = Desk { unDesk :: Cord }
deriving newtype (Eq, Ord, Show, ToNoun, FromNoun)
data Mime = Mime Path File
deriving (Eq, Ord, Show)
deriveNoun ''Mime
-- Json ------------------------------------------------------------------------
type Json = Nullable JsonNode
data JsonNode
= JNA [Json]
| JNB Bool
| JNO (HoonMap Cord Json)
| JNN Knot
| JNS Cord
deriving (Eq, Ord, Show)
deriveNoun ''JsonNode
-- Ames Destinations -------------------------------------------------
newtype Patp a = Patp { unPatp :: a }
deriving newtype (Eq, Ord, Enum, Real, Integral, Num, ToNoun, FromNoun)
-- Network Port
newtype Port = Port { unPort :: Word16 }
deriving newtype (Eq, Ord, Show, Enum, Real, Integral, Num, ToNoun, FromNoun)
-- @if
newtype Ipv4 = Ipv4 { unIpv4 :: Word32 }
deriving newtype (Eq, Ord, Show, Enum, Real, Integral, Num, ToNoun, FromNoun)
-- @is
newtype Ipv6 = Ipv6 { unIpv6 :: Word128 }
deriving newtype (Eq, Ord, Show, Enum, Real, Integral, Num, ToNoun, FromNoun)
type Galaxy = Patp Word8
instance Integral a => Show (Patp a) where
show = show . Ob.renderPatp . Ob.patp . fromIntegral . unPatp
data AmesAddress
= AAIpv4 Ipv4 Port
| AAVoid Void
deriving (Eq, Ord, Show)
deriveNoun ''AmesAddress
type AmesDest = Each Galaxy (Jammed AmesAddress)
-- Path+Tagged Restructuring ---------------------------------------------------
{-|
This reorganized events and effects to be easier to parse. This is
complicated and gross, and a better way should be found!
ReOrg takes in nouns with the following shape:
[[fst snd rest] [tag val]]
And turns that into:
ReOrg fst snd tag rest val
For example,
[//behn/5 %doze ~ 9999]
Becomes:
Reorg "" "behn" "doze" ["5"] 9999
This is convenient, since we can then use our head-tag based FromNoun
and ToNoun instances.
NOTE:
Also, in the wild, I ran into this event:
[//term/1 %init]
So, I rewrite atom-events as follows:
[x y=@] -> [x [y ~]]
Which rewrites the %init example to:
[//term/1 [%init ~]]
TODO The reverse translation is not done yet.
-}
data ReOrg = ReOrg Cord Cord Cord EvilPath Noun
instance FromNoun ReOrg where
parseNoun = named "ReOrg" . \case
A _ -> expected "got atom"
C (A _) _ -> expected "empty route"
C h (A a) -> parseNoun (C h (C (A a) (A 0)))
C (C _ (A _)) (C _ _) -> expected "route is too short"
C (C f (C s p)) (C t v) -> do
fst :: Cord <- named "first-route" $ parseNoun f
snd :: Cord <- named "second-route" $ parseNoun s
pax :: EvilPath <- named "rest-of-route" $ parseNoun p
tag :: Cord <- named "tag" $ parseNoun t
val :: Noun <- pure v
pure (ReOrg fst snd tag pax val)
where
expected got = fail ("expected route+tagged; " <> got)
instance ToNoun ReOrg where
toNoun (ReOrg fst snd tag pax val) =
toNoun ((fst, snd, pax), (tag, val))
{-|
Given something parsed from a ReOrg Noun, convert that back to
a ReOrg.
This code may crash, but only if the FromNoun/ToNoun instances for
the effects are incorrect.
-}
reorgThroughNoun :: ToNoun x => (Cord, x) -> ReOrg
reorgThroughNoun =
fromNounCrash . toNoun >>> \case
(f, s, t, p, v) -> ReOrg f s t p v
where
fromNounCrash :: FromNoun a => Noun -> a
fromNounCrash =
fromNounErr >>> \case
Left err -> error (show err)
Right vl -> vl
|
jfranklin9000/urbit
|
pkg/hs/urbit-king/lib/Urbit/Arvo/Common.hs
|
Haskell
|
mit
| 6,142
|
-- | See "Control.Super.Monad.Functions".
module Control.Supermonad.Functions
( module Control.Super.Monad.Functions
) where
import Control.Super.Monad.Functions
|
jbracker/supermonad-plugin
|
src/Control/Supermonad/Functions.hs
|
Haskell
|
bsd-3-clause
| 168
|
{-# LANGUAGE CPP #-}
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..))
import System.Exit (ExitCode(..), exitWith)
import Gigasecond (fromDay)
import Data.Time.Clock (UTCTime)
import System.Locale (iso8601DateFormat)
#if __GLASGOW_HASKELL__ >= 710
import Data.Time.Format (TimeLocale, ParseTime, parseTimeOrError, defaultTimeLocale)
readTime :: ParseTime t => TimeLocale -> String -> String -> t
readTime = parseTimeOrError True
#else
import System.Locale (defaultTimeLocale)
import Data.Time.Format (readTime)
#endif
dt :: String -> UTCTime
dt = readTime defaultTimeLocale (iso8601DateFormat (Just "%T%Z"))
exitProperly :: IO Counts -> IO ()
exitProperly m = do
counts <- m
exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
main :: IO ()
main = exitProperly $ runTestTT $ TestList
[ TestList gigasecondTests ]
gigasecondTests :: [Test]
gigasecondTests =
[ testCase "from apr 25 2011" $
dt "2043-01-01T01:46:40Z" @=? fromDay (dt "2011-04-25T00:00:00Z")
, testCase "from jun 13 1977" $
dt "2009-02-19T01:46:40Z" @=? fromDay (dt "1977-06-13T00:00:00Z")
, testCase "from jul 19 1959" $
dt "1991-03-27T01:46:40Z" @=? fromDay (dt "1959-07-19T00:00:00Z")
-- customize this to test your birthday and find your gigasecond date:
]
|
stevejb71/xhaskell
|
gigasecond/gigasecond_test.hs
|
Haskell
|
mit
| 1,429
|
{-| Cluster checker.
-}
{-
Copyright (C) 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.HTools.Program.Hcheck
( main
, options
, arguments
) where
import Control.Monad
import qualified Data.IntMap as IntMap
import Data.List (transpose)
import System.Exit
import Text.Printf (printf)
import Ganeti.HTools.AlgorithmParams (fromCLIOptions)
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Cluster as Cluster
import qualified Ganeti.HTools.Cluster.Metrics as Metrics
import qualified Ganeti.HTools.Cluster.Utils as ClusterUtils
import qualified Ganeti.HTools.GlobalN1 as GlobalN1
import qualified Ganeti.HTools.Group as Group
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Program.Hbal as Hbal
import Ganeti.HTools.RedundancyLevel (redundancy)
import Ganeti.Common
import Ganeti.HTools.CLI
import Ganeti.HTools.ExtLoader
import Ganeti.HTools.Loader
import Ganeti.HTools.Types
import Ganeti.Utils
-- | Options list and functions.
options :: IO [OptType]
options = do
luxi <- oLuxiSocket
return
[ oDataFile
, oDiskMoves
, oAvoidDiskMoves
, oDynuFile
, oIgnoreDyn
, oEvacMode
, oExInst
, oExTags
, oIAllocSrc
, oInstMoves
, luxi
, oMachineReadable
, oMaxCpu
, oMaxSolLength
, oMinDisk
, oMinGain
, oMinGainLim
, oMinScore
, oIgnoreSoftErrors
, oNoSimulation
, oOfflineNode
, oQuiet
, oRapiMaster
, oSelInst
, oNoCapacityChecks
, oVerbose
]
-- | The list of arguments supported by the program.
arguments :: [ArgCompletion]
arguments = []
-- | Check phase - are we before (initial) or after rebalance.
data Phase = Initial
| Rebalanced
-- | Level of presented statistics.
data Level = GroupLvl String -- ^ Group level, with name
| ClusterLvl -- ^ Cluster level
-- | A type alias for a group index and node\/instance lists.
type GroupInfo = (Gdx, (Node.List, Instance.List))
-- | A type alias for group stats.
type GroupStats = ((Group.Group, Double, Int), [Int])
-- | Prefix for machine readable names.
htcPrefix :: String
htcPrefix = "HCHECK"
-- | Data showed both per group and per cluster.
commonData :: Options -> [(String, String)]
commonData opts =
[ ("N1_FAIL", "Nodes not N+1 happy")
, ("CONFLICT_TAGS", "Nodes with conflicting instances")
, ("OFFLINE_PRI", "Instances having the primary node offline")
, ("OFFLINE_SEC", "Instances having a secondary node offline")
]
++ [ ("GN1_FAIL", "Nodes not directly evacuateable") | optCapacity opts ]
-- | Data showed per group.
groupData :: Options -> [(String, String)]
groupData opts = commonData opts ++ [("SCORE", "Group score")]
++ [("REDUNDANCY", "Group redundancy level")]
-- | Data showed per cluster.
clusterData :: Options -> [(String, String)]
clusterData opts = commonData opts ++
[ ("REDUNDANCY", "Cluster redundancy level") ] ++
[ ("NEED_REBALANCE", "Cluster is not healthy") ]
-- | Phase-specific prefix for machine readable version.
phasePrefix :: Phase -> String
phasePrefix Initial = "INIT"
phasePrefix Rebalanced = "FINAL"
-- | Level-specific prefix for machine readable version.
levelPrefix :: Level -> String
levelPrefix GroupLvl {} = "GROUP"
levelPrefix ClusterLvl = "CLUSTER"
-- | Machine-readable keys to show depending on given level.
keysData :: Options -> Level -> [String]
keysData opts GroupLvl {} = map fst $ groupData opts
keysData opts ClusterLvl = map fst $ clusterData opts
-- | Description of phases for human readable version.
phaseDescr :: Phase -> String
phaseDescr Initial = "initially"
phaseDescr Rebalanced = "after rebalancing"
-- | Description to show depending on given level.
descrData :: Options -> Level -> [String]
descrData opts GroupLvl {} = map snd $ groupData opts
descrData opts ClusterLvl = map snd $ clusterData opts
-- | Human readable prefix for statistics.
phaseLevelDescr :: Phase -> Level -> String
phaseLevelDescr phase (GroupLvl name) =
printf "Statistics for group %s %s\n" name $ phaseDescr phase
phaseLevelDescr phase ClusterLvl =
printf "Cluster statistics %s\n" $ phaseDescr phase
-- | Format a list of key, value as a shell fragment.
printKeysHTC :: [(String, String)] -> IO ()
printKeysHTC = printKeys htcPrefix
-- | Prepare string from boolean value.
printBool :: Bool -- ^ Whether the result should be machine readable
-> Bool -- ^ Value to be converted to string
-> String
printBool True True = "1"
printBool True False = "0"
printBool False b = show b
-- | Print mapping from group idx to group uuid (only in machine
-- readable mode).
printGroupsMappings :: Group.List -> IO ()
printGroupsMappings gl = do
let extract_vals g = (printf "GROUP_UUID_%d" $ Group.idx g :: String,
Group.uuid g)
printpairs = map extract_vals (Container.elems gl)
printKeysHTC printpairs
-- | Prepare a single key given a certain level and phase of simulation.
prepareKey :: Level -> Phase -> String -> String
prepareKey level@ClusterLvl phase suffix =
printf "%s_%s_%s" (phasePrefix phase) (levelPrefix level) suffix
prepareKey level@(GroupLvl idx) phase suffix =
printf "%s_%s_%s_%s" (phasePrefix phase) (levelPrefix level) idx suffix
-- | Print all the statistics for given level and phase.
printStats :: Options
-> Bool -- ^ If the output should be machine readable
-> Level -- ^ Level on which we are printing
-> Phase -- ^ Current phase of simulation
-> [String] -- ^ Values to print
-> IO ()
printStats opts True level phase values = do
let keys = map (prepareKey level phase) (keysData opts level)
printKeysHTC $ zip keys values
printStats opts False level phase values = do
let prefix = phaseLevelDescr phase level
descr = descrData opts level
unless (optVerbose opts < 1) $ do
putStrLn ""
putStr prefix
mapM_ (uncurry (printf " %s: %s\n")) (zip descr values)
-- | Extract name or idx from group.
extractGroupData :: Bool -> Group.Group -> String
extractGroupData True grp = show $ Group.idx grp
extractGroupData False grp = Group.name grp
-- | Prepare values for group.
prepareGroupValues :: [Int] -> Double -> Int -> [String]
prepareGroupValues stats score redundancyLevel =
map show stats ++ [printf "%.8f" score] ++ [show redundancyLevel]
-- | Prepare values for cluster.
prepareClusterValues :: Bool -> [Int] -> [Bool] -> [String]
prepareClusterValues machineread stats bstats =
map show stats ++ map (printBool machineread) bstats
-- | Print all the statistics on a group level.
printGroupStats :: Options -> Bool -> Phase -> GroupStats -> IO ()
printGroupStats opts machineread phase
((grp, score, redundancyLevel), stats) = do
let values = prepareGroupValues stats score redundancyLevel
extradata = extractGroupData machineread grp
printStats opts machineread (GroupLvl extradata) phase values
-- | Print all the statistics on a cluster (global) level.
printClusterStats :: Options -> Bool -> Phase -> [Int] -> Bool -> Int -> IO ()
printClusterStats opts machineread phase stats needhbal gRed = do
let values = prepareClusterValues machineread (stats ++ [gRed]) [needhbal]
printStats opts machineread ClusterLvl phase values
-- | Check if any of cluster metrics is non-zero.
clusterNeedsRebalance :: [Int] -> Bool
clusterNeedsRebalance stats = sum stats > 0
{- | Check group for N+1 hapiness, conflicts of primaries on nodes and
instances residing on offline nodes.
-}
perGroupChecks :: Options -> Group.List -> GroupInfo -> GroupStats
perGroupChecks opts gl (gidx, (nl, il)) =
let grp = Container.find gidx gl
offnl = filter Node.offline (Container.elems nl)
n1violated = length . fst $ Cluster.computeBadItems nl il
gn1fail = length . filter (not . GlobalN1.canEvacuateNode (nl, il))
$ IntMap.elems nl
conflicttags = length $ filter (>0)
(map Node.conflictingPrimaries (Container.elems nl))
offline_pri = sum . map length $ map Node.pList offnl
offline_sec = length $ map Node.sList offnl
score = Metrics.compCV nl
redundancyLvl = redundancy (fromCLIOptions opts) nl il
groupstats = [ n1violated
, conflicttags
, offline_pri
, offline_sec
]
++ [ gn1fail | optCapacity opts ]
in ((grp, score, redundancyLvl), groupstats)
-- | Use Hbal's iterateDepth to simulate group rebalance.
executeSimulation :: Options -> Cluster.Table -> Double
-> Gdx -> Node.List -> Instance.List
-> IO GroupInfo
executeSimulation opts ini_tbl min_cv gidx nl il = do
let imlen = maximum . map (length . Instance.alias) $ Container.elems il
nmlen = maximum . map (length . Node.alias) $ Container.elems nl
(fin_tbl, _) <- Hbal.iterateDepth False (fromCLIOptions opts) ini_tbl
(optMaxLength opts)
nmlen imlen [] min_cv
let (Cluster.Table fin_nl fin_il _ _) = fin_tbl
return (gidx, (fin_nl, fin_il))
-- | Simulate group rebalance if group's score is not good
maybeSimulateGroupRebalance :: Options -> GroupInfo -> IO GroupInfo
maybeSimulateGroupRebalance opts (gidx, (nl, il)) = do
let ini_cv = Metrics.compCV nl
ini_tbl = Cluster.Table nl il ini_cv []
min_cv = optMinScore opts + Metrics.optimalCVScore nl
if ini_cv < min_cv
then return (gidx, (nl, il))
else executeSimulation opts ini_tbl min_cv gidx nl il
-- | Decide whether to simulate rebalance.
maybeSimulateRebalance :: Bool -- ^ Whether to simulate rebalance
-> Options -- ^ Command line options
-> [GroupInfo] -- ^ Group data
-> IO [GroupInfo]
maybeSimulateRebalance True opts cluster =
mapM (maybeSimulateGroupRebalance opts) cluster
maybeSimulateRebalance False _ cluster = return cluster
-- | Prints the final @OK@ marker in machine readable output.
printFinalHTC :: Bool -> IO ()
printFinalHTC = printFinal htcPrefix
-- | Main function.
main :: Options -> [String] -> IO ()
main opts args = do
unless (null args) $ exitErr "This program doesn't take any arguments."
let verbose = optVerbose opts
machineread = optMachineReadable opts
nosimulation = optNoSimulation opts
(ClusterData gl fixed_nl ilf _ _) <- loadExternalData opts
nlf <- setNodeStatus opts fixed_nl
let splitcluster = ClusterUtils.splitCluster nlf ilf
when machineread $ printGroupsMappings gl
let groupsstats = map (perGroupChecks opts gl) splitcluster
clusterstats = map sum . transpose . map snd $ groupsstats
globalRedundancy = minimum $ map (\((_, _, r), _) -> r) groupsstats
needrebalance = clusterNeedsRebalance clusterstats
unless (verbose < 1 || machineread) .
putStrLn $ if nosimulation
then "Running in no-simulation mode."
else if needrebalance
then "Cluster needs rebalancing."
else "No need to rebalance cluster, no problems found."
mapM_ (printGroupStats opts machineread Initial) groupsstats
printClusterStats opts machineread Initial clusterstats needrebalance
globalRedundancy
let exitOK = nosimulation || not needrebalance
simulate = not nosimulation && needrebalance
rebalancedcluster <- maybeSimulateRebalance simulate opts splitcluster
when (simulate || machineread) $ do
let newgroupstats = map (perGroupChecks opts gl) rebalancedcluster
newclusterstats = map sum . transpose . map snd $ newgroupstats
newGlobalRedundancy = minimum $ map (\((_, _, r), _) -> r)
newgroupstats
newneedrebalance = clusterNeedsRebalance clusterstats
mapM_ (printGroupStats opts machineread Rebalanced) newgroupstats
printClusterStats opts machineread Rebalanced newclusterstats
newneedrebalance newGlobalRedundancy
printFinalHTC machineread
unless exitOK . exitWith $ ExitFailure 1
|
andir/ganeti
|
src/Ganeti/HTools/Program/Hcheck.hs
|
Haskell
|
bsd-2-clause
| 13,579
|
{-
(c) The University of Glasgow, 2004-2006
Module
~~~~~~~~~~
Simply the name of a module, represented as a FastString.
These are Uniquable, hence we can build Maps with Modules as
the keys.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RecordWildCards #-}
module Module
(
-- * The ModuleName type
ModuleName,
pprModuleName,
moduleNameFS,
moduleNameString,
moduleNameSlashes, moduleNameColons,
moduleStableString,
mkModuleName,
mkModuleNameFS,
stableModuleNameCmp,
-- * The UnitId type
UnitId,
fsToUnitId,
unitIdFS,
stringToUnitId,
unitIdString,
stableUnitIdCmp,
-- * Wired-in UnitIds
-- $wired_in_packages
primUnitId,
integerUnitId,
baseUnitId,
rtsUnitId,
thUnitId,
dphSeqUnitId,
dphParUnitId,
mainUnitId,
thisGhcUnitId,
holeUnitId, isHoleModule,
interactiveUnitId, isInteractiveModule,
wiredInUnitIds,
-- * The Module type
Module(Module),
moduleUnitId, moduleName,
pprModule,
mkModule,
stableModuleCmp,
HasModule(..),
ContainsModule(..),
-- * The ModuleLocation type
ModLocation(..),
addBootSuffix, addBootSuffix_maybe, addBootSuffixLocn,
-- * Module mappings
ModuleEnv,
elemModuleEnv, extendModuleEnv, extendModuleEnvList,
extendModuleEnvList_C, plusModuleEnv_C,
delModuleEnvList, delModuleEnv, plusModuleEnv, lookupModuleEnv,
lookupWithDefaultModuleEnv, mapModuleEnv, mkModuleEnv, emptyModuleEnv,
moduleEnvKeys, moduleEnvElts, moduleEnvToList,
unitModuleEnv, isEmptyModuleEnv,
foldModuleEnv, extendModuleEnvWith, filterModuleEnv,
-- * ModuleName mappings
ModuleNameEnv,
-- * Sets of Modules
ModuleSet,
emptyModuleSet, mkModuleSet, moduleSetElts, extendModuleSet, elemModuleSet
) where
import Config
import Outputable
import Unique
import UniqFM
import FastString
import Binary
import Util
import {-# SOURCE #-} Packages
import GHC.PackageDb (BinaryStringRep(..))
import Data.Data
import Data.Map (Map)
import qualified Data.Map as Map
import qualified FiniteMap as Map
import System.FilePath
{-
************************************************************************
* *
\subsection{Module locations}
* *
************************************************************************
-}
-- | Where a module lives on the file system: the actual locations
-- of the .hs, .hi and .o files, if we have them
data ModLocation
= ModLocation {
ml_hs_file :: Maybe FilePath,
-- The source file, if we have one. Package modules
-- probably don't have source files.
ml_hi_file :: FilePath,
-- Where the .hi file is, whether or not it exists
-- yet. Always of form foo.hi, even if there is an
-- hi-boot file (we add the -boot suffix later)
ml_obj_file :: FilePath
-- Where the .o file is, whether or not it exists yet.
-- (might not exist either because the module hasn't
-- been compiled yet, or because it is part of a
-- package with a .a file)
} deriving Show
instance Outputable ModLocation where
ppr = text . show
{-
For a module in another package, the hs_file and obj_file
components of ModLocation are undefined.
The locations specified by a ModLocation may or may not
correspond to actual files yet: for example, even if the object
file doesn't exist, the ModLocation still contains the path to
where the object file will reside if/when it is created.
-}
addBootSuffix :: FilePath -> FilePath
-- ^ Add the @-boot@ suffix to .hs, .hi and .o files
addBootSuffix path = path ++ "-boot"
addBootSuffix_maybe :: Bool -> FilePath -> FilePath
-- ^ Add the @-boot@ suffix if the @Bool@ argument is @True@
addBootSuffix_maybe is_boot path
| is_boot = addBootSuffix path
| otherwise = path
addBootSuffixLocn :: ModLocation -> ModLocation
-- ^ Add the @-boot@ suffix to all file paths associated with the module
addBootSuffixLocn locn
= locn { ml_hs_file = fmap addBootSuffix (ml_hs_file locn)
, ml_hi_file = addBootSuffix (ml_hi_file locn)
, ml_obj_file = addBootSuffix (ml_obj_file locn) }
{-
************************************************************************
* *
\subsection{The name of a module}
* *
************************************************************************
-}
-- | A ModuleName is essentially a simple string, e.g. @Data.List@.
newtype ModuleName = ModuleName FastString
deriving Typeable
instance Uniquable ModuleName where
getUnique (ModuleName nm) = getUnique nm
instance Eq ModuleName where
nm1 == nm2 = getUnique nm1 == getUnique nm2
-- Warning: gives an ordering relation based on the uniques of the
-- FastStrings which are the (encoded) module names. This is _not_
-- a lexicographical ordering.
instance Ord ModuleName where
nm1 `compare` nm2 = getUnique nm1 `compare` getUnique nm2
instance Outputable ModuleName where
ppr = pprModuleName
instance Binary ModuleName where
put_ bh (ModuleName fs) = put_ bh fs
get bh = do fs <- get bh; return (ModuleName fs)
instance BinaryStringRep ModuleName where
fromStringRep = mkModuleNameFS . mkFastStringByteString
toStringRep = fastStringToByteString . moduleNameFS
instance Data ModuleName where
-- don't traverse?
toConstr _ = abstractConstr "ModuleName"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "ModuleName"
stableModuleNameCmp :: ModuleName -> ModuleName -> Ordering
-- ^ Compares module names lexically, rather than by their 'Unique's
stableModuleNameCmp n1 n2 = moduleNameFS n1 `compare` moduleNameFS n2
pprModuleName :: ModuleName -> SDoc
pprModuleName (ModuleName nm) =
getPprStyle $ \ sty ->
if codeStyle sty
then ztext (zEncodeFS nm)
else ftext nm
moduleNameFS :: ModuleName -> FastString
moduleNameFS (ModuleName mod) = mod
moduleNameString :: ModuleName -> String
moduleNameString (ModuleName mod) = unpackFS mod
-- | Get a string representation of a 'Module' that's unique and stable
-- across recompilations.
-- eg. "$aeson_70dylHtv1FFGeai1IoxcQr$Data.Aeson.Types.Internal"
moduleStableString :: Module -> String
moduleStableString Module{..} =
"$" ++ unitIdString moduleUnitId ++ "$" ++ moduleNameString moduleName
mkModuleName :: String -> ModuleName
mkModuleName s = ModuleName (mkFastString s)
mkModuleNameFS :: FastString -> ModuleName
mkModuleNameFS s = ModuleName s
-- |Returns the string version of the module name, with dots replaced by slashes.
--
moduleNameSlashes :: ModuleName -> String
moduleNameSlashes = dots_to_slashes . moduleNameString
where dots_to_slashes = map (\c -> if c == '.' then pathSeparator else c)
-- |Returns the string version of the module name, with dots replaced by underscores.
--
moduleNameColons :: ModuleName -> String
moduleNameColons = dots_to_colons . moduleNameString
where dots_to_colons = map (\c -> if c == '.' then ':' else c)
{-
************************************************************************
* *
\subsection{A fully qualified module}
* *
************************************************************************
-}
-- | A Module is a pair of a 'UnitId' and a 'ModuleName'.
data Module = Module {
moduleUnitId :: !UnitId, -- pkg-1.0
moduleName :: !ModuleName -- A.B.C
}
deriving (Eq, Ord, Typeable)
instance Uniquable Module where
getUnique (Module p n) = getUnique (unitIdFS p `appendFS` moduleNameFS n)
instance Outputable Module where
ppr = pprModule
instance Binary Module where
put_ bh (Module p n) = put_ bh p >> put_ bh n
get bh = do p <- get bh; n <- get bh; return (Module p n)
instance Data Module where
-- don't traverse?
toConstr _ = abstractConstr "Module"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Module"
-- | This gives a stable ordering, as opposed to the Ord instance which
-- gives an ordering based on the 'Unique's of the components, which may
-- not be stable from run to run of the compiler.
stableModuleCmp :: Module -> Module -> Ordering
stableModuleCmp (Module p1 n1) (Module p2 n2)
= (p1 `stableUnitIdCmp` p2) `thenCmp`
(n1 `stableModuleNameCmp` n2)
mkModule :: UnitId -> ModuleName -> Module
mkModule = Module
pprModule :: Module -> SDoc
pprModule mod@(Module p n) =
pprPackagePrefix p mod <> pprModuleName n
pprPackagePrefix :: UnitId -> Module -> SDoc
pprPackagePrefix p mod = getPprStyle doc
where
doc sty
| codeStyle sty =
if p == mainUnitId
then empty -- never qualify the main package in code
else ztext (zEncodeFS (unitIdFS p)) <> char '_'
| qualModule sty mod = ppr (moduleUnitId mod) <> char ':'
-- the PrintUnqualified tells us which modules have to
-- be qualified with package names
| otherwise = empty
class ContainsModule t where
extractModule :: t -> Module
class HasModule m where
getModule :: m Module
{-
************************************************************************
* *
\subsection{UnitId}
* *
************************************************************************
-}
-- | A string which uniquely identifies a package. For wired-in packages,
-- it is just the package name, but for user compiled packages, it is a hash.
-- ToDo: when the key is a hash, we can do more clever things than store
-- the hex representation and hash-cons those strings.
newtype UnitId = PId FastString deriving( Eq, Typeable )
-- here to avoid module loops with PackageConfig
instance Uniquable UnitId where
getUnique pid = getUnique (unitIdFS pid)
-- Note: *not* a stable lexicographic ordering, a faster unique-based
-- ordering.
instance Ord UnitId where
nm1 `compare` nm2 = getUnique nm1 `compare` getUnique nm2
instance Data UnitId where
-- don't traverse?
toConstr _ = abstractConstr "UnitId"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "UnitId"
stableUnitIdCmp :: UnitId -> UnitId -> Ordering
-- ^ Compares package ids lexically, rather than by their 'Unique's
stableUnitIdCmp p1 p2 = unitIdFS p1 `compare` unitIdFS p2
instance Outputable UnitId where
ppr pk = getPprStyle $ \sty -> sdocWithDynFlags $ \dflags ->
case unitIdPackageIdString dflags pk of
Nothing -> ftext (unitIdFS pk)
Just pkg -> text pkg
-- Don't bother qualifying if it's wired in!
<> (if qualPackage sty pk && not (pk `elem` wiredInUnitIds)
then char '@' <> ftext (unitIdFS pk)
else empty)
instance Binary UnitId where
put_ bh pid = put_ bh (unitIdFS pid)
get bh = do { fs <- get bh; return (fsToUnitId fs) }
instance BinaryStringRep UnitId where
fromStringRep = fsToUnitId . mkFastStringByteString
toStringRep = fastStringToByteString . unitIdFS
fsToUnitId :: FastString -> UnitId
fsToUnitId = PId
unitIdFS :: UnitId -> FastString
unitIdFS (PId fs) = fs
stringToUnitId :: String -> UnitId
stringToUnitId = fsToUnitId . mkFastString
unitIdString :: UnitId -> String
unitIdString = unpackFS . unitIdFS
-- -----------------------------------------------------------------------------
-- $wired_in_packages
-- Certain packages are known to the compiler, in that we know about certain
-- entities that reside in these packages, and the compiler needs to
-- declare static Modules and Names that refer to these packages. Hence
-- the wired-in packages can't include version numbers, since we don't want
-- to bake the version numbers of these packages into GHC.
--
-- So here's the plan. Wired-in packages are still versioned as
-- normal in the packages database, and you can still have multiple
-- versions of them installed. However, for each invocation of GHC,
-- only a single instance of each wired-in package will be recognised
-- (the desired one is selected via @-package@\/@-hide-package@), and GHC
-- will use the unversioned 'UnitId' below when referring to it,
-- including in .hi files and object file symbols. Unselected
-- versions of wired-in packages will be ignored, as will any other
-- package that depends directly or indirectly on it (much as if you
-- had used @-ignore-package@).
-- Make sure you change 'Packages.findWiredInPackages' if you add an entry here
integerUnitId, primUnitId,
baseUnitId, rtsUnitId,
thUnitId, dphSeqUnitId, dphParUnitId,
mainUnitId, thisGhcUnitId, interactiveUnitId :: UnitId
primUnitId = fsToUnitId (fsLit "ghc-prim")
integerUnitId = fsToUnitId (fsLit n)
where
n = case cIntegerLibraryType of
IntegerGMP -> "integer-gmp"
IntegerSimple -> "integer-simple"
baseUnitId = fsToUnitId (fsLit "base")
rtsUnitId = fsToUnitId (fsLit "rts")
thUnitId = fsToUnitId (fsLit "template-haskell")
dphSeqUnitId = fsToUnitId (fsLit "dph-seq")
dphParUnitId = fsToUnitId (fsLit "dph-par")
thisGhcUnitId = fsToUnitId (fsLit "ghc")
interactiveUnitId = fsToUnitId (fsLit "interactive")
-- | This is the package Id for the current program. It is the default
-- package Id if you don't specify a package name. We don't add this prefix
-- to symbol names, since there can be only one main package per program.
mainUnitId = fsToUnitId (fsLit "main")
-- | This is a fake package id used to provide identities to any un-implemented
-- signatures. The set of hole identities is global over an entire compilation.
holeUnitId :: UnitId
holeUnitId = fsToUnitId (fsLit "hole")
isInteractiveModule :: Module -> Bool
isInteractiveModule mod = moduleUnitId mod == interactiveUnitId
isHoleModule :: Module -> Bool
isHoleModule mod = moduleUnitId mod == holeUnitId
wiredInUnitIds :: [UnitId]
wiredInUnitIds = [ primUnitId,
integerUnitId,
baseUnitId,
rtsUnitId,
thUnitId,
thisGhcUnitId,
dphSeqUnitId,
dphParUnitId ]
{-
************************************************************************
* *
\subsection{@ModuleEnv@s}
* *
************************************************************************
-}
-- | A map keyed off of 'Module's
newtype ModuleEnv elt = ModuleEnv (Map Module elt)
filterModuleEnv :: (Module -> a -> Bool) -> ModuleEnv a -> ModuleEnv a
filterModuleEnv f (ModuleEnv e) = ModuleEnv (Map.filterWithKey f e)
elemModuleEnv :: Module -> ModuleEnv a -> Bool
elemModuleEnv m (ModuleEnv e) = Map.member m e
extendModuleEnv :: ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnv (ModuleEnv e) m x = ModuleEnv (Map.insert m x e)
extendModuleEnvWith :: (a -> a -> a) -> ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnvWith f (ModuleEnv e) m x = ModuleEnv (Map.insertWith f m x e)
extendModuleEnvList :: ModuleEnv a -> [(Module, a)] -> ModuleEnv a
extendModuleEnvList (ModuleEnv e) xs = ModuleEnv (Map.insertList xs e)
extendModuleEnvList_C :: (a -> a -> a) -> ModuleEnv a -> [(Module, a)]
-> ModuleEnv a
extendModuleEnvList_C f (ModuleEnv e) xs = ModuleEnv (Map.insertListWith f xs e)
plusModuleEnv_C :: (a -> a -> a) -> ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv_C f (ModuleEnv e1) (ModuleEnv e2) = ModuleEnv (Map.unionWith f e1 e2)
delModuleEnvList :: ModuleEnv a -> [Module] -> ModuleEnv a
delModuleEnvList (ModuleEnv e) ms = ModuleEnv (Map.deleteList ms e)
delModuleEnv :: ModuleEnv a -> Module -> ModuleEnv a
delModuleEnv (ModuleEnv e) m = ModuleEnv (Map.delete m e)
plusModuleEnv :: ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv (ModuleEnv e1) (ModuleEnv e2) = ModuleEnv (Map.union e1 e2)
lookupModuleEnv :: ModuleEnv a -> Module -> Maybe a
lookupModuleEnv (ModuleEnv e) m = Map.lookup m e
lookupWithDefaultModuleEnv :: ModuleEnv a -> a -> Module -> a
lookupWithDefaultModuleEnv (ModuleEnv e) x m = Map.findWithDefault x m e
mapModuleEnv :: (a -> b) -> ModuleEnv a -> ModuleEnv b
mapModuleEnv f (ModuleEnv e) = ModuleEnv (Map.mapWithKey (\_ v -> f v) e)
mkModuleEnv :: [(Module, a)] -> ModuleEnv a
mkModuleEnv xs = ModuleEnv (Map.fromList xs)
emptyModuleEnv :: ModuleEnv a
emptyModuleEnv = ModuleEnv Map.empty
moduleEnvKeys :: ModuleEnv a -> [Module]
moduleEnvKeys (ModuleEnv e) = Map.keys e
moduleEnvElts :: ModuleEnv a -> [a]
moduleEnvElts (ModuleEnv e) = Map.elems e
moduleEnvToList :: ModuleEnv a -> [(Module, a)]
moduleEnvToList (ModuleEnv e) = Map.toList e
unitModuleEnv :: Module -> a -> ModuleEnv a
unitModuleEnv m x = ModuleEnv (Map.singleton m x)
isEmptyModuleEnv :: ModuleEnv a -> Bool
isEmptyModuleEnv (ModuleEnv e) = Map.null e
foldModuleEnv :: (a -> b -> b) -> b -> ModuleEnv a -> b
foldModuleEnv f x (ModuleEnv e) = Map.foldRightWithKey (\_ v -> f v) x e
-- | A set of 'Module's
type ModuleSet = Map Module ()
mkModuleSet :: [Module] -> ModuleSet
extendModuleSet :: ModuleSet -> Module -> ModuleSet
emptyModuleSet :: ModuleSet
moduleSetElts :: ModuleSet -> [Module]
elemModuleSet :: Module -> ModuleSet -> Bool
emptyModuleSet = Map.empty
mkModuleSet ms = Map.fromList [(m,()) | m <- ms ]
extendModuleSet s m = Map.insert m () s
moduleSetElts = Map.keys
elemModuleSet = Map.member
{-
A ModuleName has a Unique, so we can build mappings of these using
UniqFM.
-}
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
type ModuleNameEnv elt = UniqFM elt
|
siddhanathan/ghc
|
compiler/basicTypes/Module.hs
|
Haskell
|
bsd-3-clause
| 18,321
|
{-# LANGUAGE CPP, BangPatterns #-}
module Main where
import Control.Monad
import Data.Int
import Network.Socket
( AddrInfo, AddrInfoFlag (AI_PASSIVE), HostName, ServiceName, Socket
, SocketType (Stream), SocketOption (ReuseAddr)
, accept, addrAddress, addrFlags, addrFamily, bindSocket, defaultProtocol
, defaultHints
, getAddrInfo, listen, setSocketOption, socket, sClose, withSocketsDo )
import System.Environment (getArgs, withArgs)
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import System.IO (withFile, IOMode(..), hPutStrLn, Handle, stderr)
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (newEmptyMVar, takeMVar, putMVar)
import qualified Network.Socket as N
import Debug.Trace
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack, unpack)
import qualified Data.ByteString as BS
import qualified Network.Socket.ByteString as NBS
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import Data.ByteString.Internal as BSI
import Foreign.Storable (pokeByteOff, peekByteOff)
import Foreign.C (CInt(..))
import Foreign.ForeignPtr (withForeignPtr)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
foreign import ccall unsafe "htonl" htonl :: CInt -> CInt
foreign import ccall unsafe "ntohl" ntohl :: CInt -> CInt
passive :: Maybe AddrInfo
passive = Just (defaultHints { addrFlags = [AI_PASSIVE] })
main = do
[pingsStr] <- getArgs
serverReady <- newEmptyMVar
clientDone <- newEmptyMVar
-- Start the server
forkIO $ do
-- Initialize the server
serverAddr:_ <- getAddrInfo passive Nothing (Just "8080")
sock <- socket (addrFamily serverAddr) Stream defaultProtocol
setSocketOption sock ReuseAddr 1
bindSocket sock (addrAddress serverAddr)
listen sock 1
-- Set up multiplexing channel
multiplexChannel <- newChan
-- Wait for incoming connections (pings from the client)
putMVar serverReady ()
(clientSock, pingAddr) <- accept sock
forkIO $ socketToChan clientSock multiplexChannel
-- Reply to the client
forever $ readChan multiplexChannel >>= send clientSock
-- Start the client
forkIO $ do
takeMVar serverReady
serverAddr:_ <- getAddrInfo Nothing (Just "127.0.0.1") (Just "8080")
clientSock <- socket (addrFamily serverAddr) Stream defaultProtocol
N.connect clientSock (addrAddress serverAddr)
ping clientSock (read pingsStr)
putMVar clientDone ()
-- Wait for the client to finish
takeMVar clientDone
socketToChan :: Socket -> Chan ByteString -> IO ()
socketToChan sock chan = go
where
go = do bs <- recv sock
when (BS.length bs > 0) $ do
writeChan chan bs
go
pingMessage :: ByteString
pingMessage = pack "ping123"
ping :: Socket -> Int -> IO ()
ping sock pings = go pings
where
go :: Int -> IO ()
go 0 = do
putStrLn $ "client did " ++ show pings ++ " pings"
go !i = do
before <- getCurrentTime
send sock pingMessage
bs <- recv sock
after <- getCurrentTime
-- putStrLn $ "client received " ++ unpack bs
let latency = (1e6 :: Double) * realToFrac (diffUTCTime after before)
hPutStrLn stderr $ show i ++ " " ++ show latency
go (i - 1)
-- | Receive a package
recv :: Socket -> IO ByteString
recv sock = do
header <- NBS.recv sock 4
length <- decodeLength header
NBS.recv sock (fromIntegral (length :: Int32))
-- | Send a package
send :: Socket -> ByteString -> IO ()
send sock bs = do
length <- encodeLength (fromIntegral (BS.length bs))
NBS.sendMany sock [length, bs]
-- | Encode length (manual for now)
encodeLength :: Int32 -> IO ByteString
encodeLength i32 =
BSI.create 4 $ \p ->
pokeByteOff p 0 (htonl (fromIntegral i32))
-- | Decode length (manual for now)
decodeLength :: ByteString -> IO Int32
decodeLength bs =
let (fp, _, _) = BSI.toForeignPtr bs in
withForeignPtr fp $ \p -> do
w32 <- peekByteOff p 0
return (fromIntegral (ntohl w32))
|
tweag/network-transport-zeromq
|
benchmarks/subparts/h-tcp-chan.hs
|
Haskell
|
bsd-3-clause
| 4,012
|
module Infix4 (f) where
-- define an infix constructor and attempt to remove it...
data T1 a b = b :#: a
{- g :: T1 Int Int -> Int -}
{- g (x :$: y) = x + y -}
f x y = error
"g (x :$: y) no longer defined for T1 at line: 5"
|
kmate/HaRe
|
old/testing/removeCon/Infix4_TokOut.hs
|
Haskell
|
bsd-3-clause
| 241
|
module ListSort () where
import Language.Haskell.Liquid.Prelude
{-@ type OList a = [a]<{\fld v -> (v >= fld)}> @-}
{-@ predicate Pr X Y = (((len Y) > 1) => ((len Y) < (len X))) @-}
{-@ split :: xs:[a]
-> ({v:[a] | (Pr xs v)}, {v:[a]|(Pr xs v)})
<{\x y -> ((len x) + (len y) = (len xs))}>
@-}
split :: [a] -> ([a], [a])
split (x:(y:zs)) = (x:xs, y:ys) where (xs, ys) = split zs
split xs = (xs, [])
{-@ Decrease merge 4 @-}
{-@ merge :: Ord a => xs:(OList a) -> ys:(OList a) -> d:{v:Int| v = (len xs) + (len ys)} -> {v:(OList a) | (len v) = d} @-}
merge :: Ord a => [a] -> [a] -> Int -> [a]
merge xs [] _ = xs
merge [] ys _ = ys
merge (x:xs) (y:ys) d
| x <= y
= x:(merge xs (y:ys) (d-1))
| otherwise
= y:(merge (x:xs) ys (d-1))
{-@ mergesort :: (Ord a) => xs:[a] -> {v:(OList a) | (len v) = (len xs)} @-}
mergesort :: Ord a => [a] -> [a]
mergesort [] = []
mergesort [x] = [x]
mergesort xs = merge (mergesort xs1) (mergesort xs2) d
where (xs1, xs2) = split xs
d = length xs
|
ssaavedra/liquidhaskell
|
tests/pos/ListMSort.hs
|
Haskell
|
bsd-3-clause
| 1,062
|
module Conflict1 where
f :: Int -> Int
f x = x + 1
f1 :: Int -> Int
f1 x = x - 1
f3 :: Int -> (Int, Int)
f3 x y = (x + 1, y - 1)
|
kmate/HaRe
|
old/testing/merging/Conflict1_TokOut.hs
|
Haskell
|
bsd-3-clause
| 133
|
{-# LANGUAGE RecordWildCards #-}
-- | See:
--
-- * \"The Probabilistic Relevance Framework: BM25 and Beyond\"
-- <www.soi.city.ac.uk/~ser/papers/foundations_bm25_review.pdf>
--
-- * \"An Introduction to Information Retrieval\"
-- <http://nlp.stanford.edu/IR-book/pdf/irbookonlinereading.pdf>
--
module Distribution.Server.Features.Search.BM25F (
Context(..),
FeatureFunction(..),
Doc(..),
score,
Explanation(..),
explain,
) where
import Data.Ix
data Context term field feature = Context {
numDocsTotal :: !Int,
avgFieldLength :: field -> Float,
numDocsWithTerm :: term -> Int,
paramK1 :: !Float,
paramB :: field -> Float,
-- consider minimum length to prevent massive B bonus?
fieldWeight :: field -> Float,
featureWeight :: feature -> Float,
featureFunction :: feature -> FeatureFunction
}
data Doc term field feature = Doc {
docFieldLength :: field -> Int,
docFieldTermFrequency :: field -> term -> Int,
docFeatureValue :: feature -> Float
}
-- | The BM25F score for a document for a given set of terms.
--
score :: (Ix field, Bounded field, Ix feature, Bounded feature) =>
Context term field feature ->
Doc term field feature -> [term] -> Float
score ctx doc terms =
sum (map (weightedTermScore ctx doc) terms)
+ sum (map (weightedNonTermScore ctx doc) features)
where
features = range (minBound, maxBound)
weightedTermScore :: (Ix field, Bounded field) =>
Context term field feature ->
Doc term field feature -> term -> Float
weightedTermScore ctx doc t =
weightIDF ctx t * tf'
/ (k1 + tf')
where
tf' = weightedDocTermFrequency ctx doc t
k1 = paramK1 ctx
weightIDF :: Context term field feature -> term -> Float
weightIDF ctx t =
log ((n - n_t + 0.5) / (n_t + 0.5))
where
n = fromIntegral (numDocsTotal ctx)
n_t = fromIntegral (numDocsWithTerm ctx t)
weightedDocTermFrequency :: (Ix field, Bounded field) =>
Context term field feature ->
Doc term field feature -> term -> Float
weightedDocTermFrequency ctx doc t =
sum [ w_f * tf_f / _B_f
| field <- range (minBound, maxBound)
, let w_f = fieldWeight ctx field
tf_f = fromIntegral (docFieldTermFrequency doc field t)
_B_f = lengthNorm ctx doc field
]
lengthNorm :: Context term field feature ->
Doc term field feature -> field -> Float
lengthNorm ctx doc field =
(1-b_f) + b_f * sl_f / avgsl_f
where
b_f = paramB ctx field
sl_f = fromIntegral (docFieldLength doc field)
avgsl_f = avgFieldLength ctx field
weightedNonTermScore :: (Ix feature, Bounded feature) =>
Context term field feature ->
Doc term field feature -> feature -> Float
weightedNonTermScore ctx doc feature =
w_f * _V_f f_f
where
w_f = featureWeight ctx feature
_V_f = applyFeatureFunction (featureFunction ctx feature)
f_f = docFeatureValue doc feature
data FeatureFunction
= LogarithmicFunction Float -- ^ @log (\lambda_i + f_i)@
| RationalFunction Float -- ^ @f_i / (\lambda_i + f_i)@
| SigmoidFunction Float Float -- ^ @1 / (\lambda + exp(-(\lambda' * f_i))@
applyFeatureFunction :: FeatureFunction -> (Float -> Float)
applyFeatureFunction (LogarithmicFunction p1) = \fi -> log (p1 + fi)
applyFeatureFunction (RationalFunction p1) = \fi -> fi / (p1 + fi)
applyFeatureFunction (SigmoidFunction p1 p2) = \fi -> 1 / (p1 + exp (-fi * p2))
------------------
-- Explanation
--
-- | A breakdown of the BM25F score, to explain somewhat how it relates to
-- the inputs, and so you can compare the scores of different documents.
--
data Explanation field feature term = Explanation {
-- | The overall score is the sum of the 'termScores', 'positionScore'
-- and 'nonTermScore'
overallScore :: Float,
-- | There is a score contribution from each query term. This is the
-- score for the term across all fields in the document (but see
-- 'termFieldScores').
termScores :: [(term, Float)],
{-
-- | There is a score contribution for positional information. Terms
-- appearing in the document close together give a bonus.
positionScore :: [(field, Float)],
-}
-- | The document can have an inate bonus score independent of the terms
-- in the query. For example this might be a popularity score.
nonTermScores :: [(feature, Float)],
-- | This does /not/ contribute to the 'overallScore'. It is an
-- indication of how the 'termScores' relates to per-field scores.
-- Note however that the term score for all fields is /not/ simply
-- sum of the per-field scores. The point of the BM25F scoring function
-- is that a linear combination of per-field scores is wrong, and BM25F
-- does a more cunning non-linear combination.
--
-- However, it is still useful as an indication to see scores for each
-- field for a term, to see how the compare.
--
termFieldScores :: [(term, [(field, Float)])]
}
deriving Show
instance Functor (Explanation field feature) where
fmap f e@Explanation{..} =
e {
termScores = [ (f t, s) | (t, s) <- termScores ],
termFieldScores = [ (f t, fs) | (t, fs) <- termFieldScores ]
}
explain :: (Ix field, Bounded field, Ix feature, Bounded feature) =>
Context term field feature ->
Doc term field feature -> [term] -> Explanation field feature term
explain ctx doc ts =
Explanation {..}
where
overallScore = sum (map snd termScores)
-- + sum (map snd positionScore)
+ sum (map snd nonTermScores)
termScores = [ (t, weightedTermScore ctx doc t) | t <- ts ]
-- positionScore = [ (f, 0) | f <- range (minBound, maxBound) ]
nonTermScores = [ (feature, weightedNonTermScore ctx doc feature)
| feature <- range (minBound, maxBound) ]
termFieldScores =
[ (t, fieldScores)
| t <- ts
, let fieldScores =
[ (f, weightedTermScore ctx' doc t)
| f <- range (minBound, maxBound)
, let ctx' = ctx { fieldWeight = fieldWeightOnly f }
]
]
fieldWeightOnly f f' | sameField f f' = fieldWeight ctx f'
| otherwise = 0
sameField f f' = index (minBound, maxBound) f
== index (minBound, maxBound) f'
|
ocharles/hackage-server
|
Distribution/Server/Features/Search/BM25F.hs
|
Haskell
|
bsd-3-clause
| 6,758
|
{-# LANGUAGE TypeFamilies #-}
module B where
import A
data B
type instance F (B,b) = ()
b :: () -> F (B,b)
b = id
|
shlevy/ghc
|
testsuite/tests/driver/recomp017/B.hs
|
Haskell
|
bsd-3-clause
| 114
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
-- A very bogus program (multiple errors) but
-- sent GHC 6.12 into a loop
module T3330a where
newtype Writer w a = Writer { runWriter :: (a, w) }
execWriter :: Writer w a -> w
execWriter m = snd (runWriter m)
data AnyF (s :: * -> *) = AnyF
class HFunctor (f :: (* -> *) -> * -> *)
type family PF (phi :: * -> *) :: (* -> *) -> * -> *
children :: s ix -> (PF s) r ix -> [AnyF s]
children p x = execWriter (hmapM p collect x)
{-
0 from instantiating hmap
2 from instantiating collect
(forall ixx. (phi0 ixx -> r0 ixx -> m0 (r'0 ixx) ~ s ix))
phi0 ix0 ~ s2 ix2 -> r2 ix2 -> Writer [AnyF s2] (r2 ix2)
f0 r0 ix0 ~ PF s r ix
m0 (f0 r'0 ix0) ~ Writer [AnyF s] a0
Hence ix0 := ix
r0 := r
f0 := PF s
phi0 := (->) s2 ix2
m0 := Writer [AnyF s]
a0 : = f0 r'0 ix0
(forall ixx. ((->) (s2 ix2 -> ixx) (r ixx -> Writer [AnyF s] (r'0 ixx)) ~ s ix))
s2 ix2 ix0 ~ (->) (s2 ix2) (r2 ix2 -> Writer [AnyF s2] (r2 ix2))
-}
collect :: HFunctor (PF s) => s ix -> r ix -> Writer [AnyF s] (r ix)
collect = error "collect"
hmapM :: (forall ix. phi ix -> r ix -> m (r' ix))
-> phi ix -> f r ix -> m (f r' ix)
hmapM _ = error "hmapM"
|
ezyang/ghc
|
testsuite/tests/indexed-types/should_fail/T3330a.hs
|
Haskell
|
bsd-3-clause
| 1,260
|
{-# LANGUAGE BangPatterns, MagicHash, UnboxedTuples #-}
-- Test allocation of statically sized arrays. There's an optimization
-- that targets these and we want to make sure that the code generated
-- in the optimized case is correct.
--
-- The tests proceeds by allocating a bunch of arrays of different
-- sizes and reading elements from them, to try to provoke GC crashes,
-- which would be a symptom of the optimization not generating correct
-- code.
module Main where
import Control.Monad
import GHC.Exts
import GHC.IO
import Prelude hiding (read)
main :: IO ()
main = do
loop 1000
putStrLn "success"
where
loop :: Int -> IO ()
loop 0 = return ()
loop i = do
-- Sizes have been picked to match the triggering of the
-- optimization and to match boundary conditions. Sizes are
-- given explicitly as to not rely on other optimizations to
-- make the static size known to the compiler.
marr0 <- newArray 0
marr1 <- newArray 1
marr2 <- newArray 2
marr3 <- newArray 3
marr4 <- newArray 4
marr5 <- newArray 5
marr6 <- newArray 6
marr7 <- newArray 7
marr8 <- newArray 8
marr9 <- newArray 9
marr10 <- newArray 10
marr11 <- newArray 11
marr12 <- newArray 12
marr13 <- newArray 13
marr14 <- newArray 14
marr15 <- newArray 15
marr16 <- newArray 16
marr17 <- newArray 17
let marrs = [marr0, marr1, marr2, marr3, marr4, marr5, marr6, marr7,
marr8, marr9, marr10, marr11, marr12, marr13, marr14,
marr15, marr16, marr17]
total <- sumManyArrays marrs
unless (total == 153) $
putStrLn "incorrect sum"
loop (i-1)
sumManyArrays :: [MArray] -> IO Int
sumManyArrays = go 0
where
go !acc [] = return acc
go acc (marr:marrs) = do
n <- sumArray marr
go (acc+n) marrs
sumArray :: MArray -> IO Int
sumArray marr = go 0 0
where
go :: Int -> Int -> IO Int
go !acc i
| i < len = do
k <- read marr i
go (acc + k) (i+1)
| otherwise = return acc
len = lengthM marr
data MArray = MArray { unMArray :: !(MutableArray# RealWorld Int) }
newArray :: Int -> IO MArray
newArray (I# sz#) = IO $ \s -> case newArray# sz# 1 s of
(# s', marr #) -> (# s', MArray marr #)
{-# INLINE newArray #-} -- to make sure optimization triggers
lengthM :: MArray -> Int
lengthM marr = I# (sizeofMutableArray# (unMArray marr))
read :: MArray -> Int -> IO Int
read marr i@(I# i#)
| i < 0 || i >= len =
error $ "bounds error, offset " ++ show i ++ ", length " ++ show len
| otherwise = IO $ \ s -> readArray# (unMArray marr) i# s
where len = lengthM marr
|
urbanslug/ghc
|
testsuite/tests/codeGen/should_run/StaticArraySize.hs
|
Haskell
|
bsd-3-clause
| 2,785
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Impl.MVar1 where
import Control.Concurrent.MVar
import Control.Monad.IO.Class
import Control.Monad.Trans.Either
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as Map
import Data.Proxy
import Data.Time
import Network.Wai.Handler.Warp (run)
import Servant.API
import Servant.Server
import API
data Environment
= Environment
{ serverFortuneMap :: MVar (HashMap Email Fortune)
}
runApp :: IO ()
runApp = do
env <- createEnvironment
run 8080 $ serve (Proxy :: Proxy API)
( createPlayer env
:<|> tradeFortunes env)
createEnvironment :: IO Environment
createEnvironment = do
fm <- newMVar Map.empty
return $ Environment fm
createPlayer :: Environment -> NewPlayer -> EitherT ServantErr IO ()
createPlayer env player = do
now <- liftIO getCurrentTime
let f = Fortune (npFortune player) now
m <- liftIO $ takeMVar (serverFortuneMap env)
let m' = Map.insert (npEmail player) f m
liftIO $ putMVar (serverFortuneMap env) m'
tradeFortunes :: Environment -> Email -> Email -> EitherT ServantErr IO FortunePair
tradeFortunes env from to = do
m <- liftIO $ takeMVar (serverFortuneMap env)
let mgiven = Map.lookup from m
mreceived = Map.lookup to m
case (mgiven, mreceived) of
(Just given, Just received) -> do
let m' = Map.insert from received m
m'' = Map.insert to given m'
liftIO $ putMVar (serverFortuneMap env) m''
return $ FortunePair given received
_ -> left err404
|
AndrewRademacher/whimsy
|
src/Impl/MVar1.hs
|
Haskell
|
mit
| 1,786
|
{-
- Comonad implementation of an infinite cellular automata grid, adapted with
- minor modifications from Kukuruku's implementation here:
- http://kukuruku.co/hub/haskell/cellular-automata-using-comonads
-
-}
module Universe where
import Control.Applicative (pure)
import Control.Comonad (Comonad(..))
-- Universe: a comonad/zipper infinite list
data Universe a = Universe [a] a [a]
-- Shift the zipper one element to the left or right
left, right :: Universe a -> Universe a
left (Universe (a:as) x bs) = Universe as a (x:bs)
right (Universe as x (b:bs)) = Universe (x:as) b bs
-- Create a new Universe given functions to create the infinite lists
makeUniverse :: (a -> a) -> (a -> a) -> a -> Universe a
makeUniverse fl fr x = Universe (tail $ iterate fl x) x (tail $ iterate fr x)
-- Build a Universe using a finite list and a default value
fromList :: a -> [a] -> Universe a
fromList def (x:xs) = Universe (repeat def) x (xs ++ repeat def)
instance Functor Universe where
fmap f (Universe as x bs) = Universe (fmap f as) (f x) (fmap f bs)
instance Comonad Universe where
duplicate = makeUniverse left right
extract (Universe _ x _) = x
-- Get the center item and the two adjacent items
nearest3 :: Universe a -> [a]
nearest3 u = map extract [left u, u, right u]
-- Return a range from the zipper using the lower and upper indicies, inclusive.
-- e.g., takeRange (-10, 10) will return the center element and 10 elements
-- from each side
takeRange :: (Int, Int) -> Universe a -> [a]
takeRange (a, b) u = take (b-a+1) x
where Universe _ _ x
| a < 0 = iterate left u !! (-a + 1)
| otherwise = iterate right u !! (a - 1)
-- Two-dimensional comonad/zipper
newtype Universe2D a = Universe2D { getUniverse2D :: Universe (Universe a) }
instance Functor Universe2D where
fmap f = Universe2D . (fmap . fmap) f . getUniverse2D
instance Comonad Universe2D where
extract = extract . extract . getUniverse2D
duplicate = fmap Universe2D . Universe2D . shifted . shifted . getUniverse2D
where shifted :: Universe (Universe a) -> Universe (Universe (Universe a))
shifted = makeUniverse (fmap left) (fmap right)
-- Build a Universe2D given a list of lists and a default value
fromList2D :: a -> [[a]] -> Universe2D a
fromList2D def = Universe2D . fromList udef . fmap (fromList def)
where udef = Universe (repeat def) def (repeat def)
-- Return a rectangle from the 2D zipper using a bounding box, inclusive.
takeRange2D :: (Int, Int) -> (Int, Int) -> Universe2D a -> [[a]]
takeRange2D (x0, y0) (x1, y1)
= takeRange (y0, y1) . fmap (takeRange (x0, x1)) . getUniverse2D
-- Get the 8 cells surrounding the center cell in a Universe2D
neighbors :: Universe2D a -> [a]
neighbors u =
[ nearest3 . extract . left -- 3 cells in row above
, pure . extract . left . extract -- cell to the left
, pure . extract . right . extract -- cell to the right
, nearest3 . extract . right -- 3 cells in row below
] >>= ($ getUniverse2D u)
|
billpmurphy/conway-combat
|
Universe.hs
|
Haskell
|
mit
| 3,075
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Nauva.Product.Varna.Shared
( root
, batteryCard
) where
import qualified Data.Aeson as A
import Nauva.View
import Nauva.Service.Head
import Nauva.Product.Varna.Element.Card
import Prelude hiding (rem)
root :: HeadH -> Element
root = component_ rootComponent
rootComponent :: Component HeadH () () ()
rootComponent = createComponent $ \cId -> Component
{ componentId = cId
, componentDisplayName = "Root"
, initialComponentState = \p -> pure ((), [], [updateHead p])
, componentEventListeners = \_ -> []
, componentHooks = emptyHooks
, processLifecycleEvent = \_ _ s -> (s, [])
, receiveProps = \_ s -> pure (s, [], [])
, update = \_ p _ -> ((), [updateHead p])
, renderComponent = render
, componentSnapshot = \_ -> A.Null
, restoreComponent = \_ s -> Right (s, [])
}
where
updateHead :: HeadH -> IO (Maybe ())
updateHead headH = do
hReplace headH
[ style_ [str_ "*,*::before,*::after{box-sizing:inherit}body{margin:0;box-sizing:border-box}"]
, title_ [str_ "Varna"]
]
pure Nothing
render _ _ = div_ [style_ rootStyle] $
[ navbar
, batteries
[ batteryCard
[ batteryCardBodyParagraph True [str_ "This looks like a fresh battery. Congratulations on your purchase."]
, batteryCardBodyPrimaryButton "charge battery"
, batteryCardBodySecondaryButton "discharge battery"
]
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
]
]
where
rootStyle :: Style
rootStyle = mkStyle $ do
height (vh 100)
display flex
flexDirection column
fontFamily "museo-slab, serif"
navbar :: Element
navbar = div_ [style_ rootStyle]
[ div_ [style_ navbarItemStyle] [ str_ "Home" ]
, div_ [style_ navbarItemStyle] [ str_ "Create Battery" ]
, null_
, div_ [style_ navbarItemStyle] [ str_ "Account" ]
]
where
rootStyle :: Style
rootStyle = mkStyle $ do
display flex
flexDirection row
height (rem 3)
backgroundColor "rgb(126, 120, 3)"
color "rgb(228, 228, 238)"
fontSize (rem 1.8)
lineHeight (rem 3)
flexShrink "0"
navbarItemStyle :: Style
navbarItemStyle = mkStyle $ do
padding (rem 0) (rem 0.5)
cursor pointer
onHover $ do
backgroundColor "#999"
batteries :: [Element] -> Element
batteries = div_ [style_ rootStyle]
where
rootStyle = mkStyle $ do
marginTop (rem 1)
display flex
flexDirection row
flexWrap wrap
|
wereHamster/nauva
|
product/varna/shared/src/Nauva/Product/Varna/Shared.hs
|
Haskell
|
mit
| 3,087
|
{-# LANGUAGE TupleSections, RecordWildCards, DeriveGeneric #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
------------------------------------------------------------------------------
-- |
-- Module : Mahjong.Kyoku
-- Copyright : (C) 2014 Samuli Thomasson
-- License : MIT (see the file LICENSE)
-- Maintainer : Samuli Thomasson <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- This module provides a mahjong state machine @Machine@ with state
-- @Kyoku@.
------------------------------------------------------------------------------
module Mahjong.Kyoku
( -- * Types
InKyoku, Machine(..), MachineInput(..), Flag(..)
-- * Actions
, step
, dealGameEvent
, updatePlayerNick
, tellPlayerState
, maybeNextDeal
-- * Utility
, playerToKaze
, getShouts
, nextRound
, getValuedHand
, module Mahjong.Kyoku.Internal
) where
------------------------------------------------------------------------------
import Import
import Mahjong.Tiles
import Mahjong.Hand
import Mahjong.Configuration
------------------------------------------------------------------------------
import Mahjong.Kyoku.Flags
import Mahjong.Kyoku.Internal
------------------------------------------------------------------------------
import qualified Data.Map as Map
import Data.Monoid (Endo(..))
import qualified Data.List as L (delete, findIndex, (!!))
-- | Context of game and deal flow.
--
-- Don't use the state monad yourself! always use tellEvent
type InKyoku m =
( MonadState Kyoku m
, MonadWriter [GameEvent] m
, MonadError Text m
, Functor m
, Applicative m
, Monad m )
handOf :: Kaze -> Lens Kyoku Kyoku (Maybe Hand) (Maybe Hand)
handOf pk = sHands.at pk
----------------------------------------------------------------------------------------
-- * Logic
-- | Game automata
data Machine = KyokuNone -- ^ No tiles in the table atm
| KyokuStartIn Int -- ^ Number of seconds before kyoku starts. Tiles dealt.
| CheckEndConditionsAfterDiscard
| WaitingDraw Kaze Bool
| WaitingDiscard Kaze
| WaitingShouts (Set Kaze) [Int] [(Kaze, Shout)] Bool -- ^ set of players who could shout but have not (passed), index of now winning shout(s), flag: chankan? (to continue with discard)
| KyokuEnded KyokuResults
| HasEnded FinalPoints -- ^ This game has ended
deriving (Eq, Show, Read, Generic)
-- | @MachineInput@ consists of two parts: actions from clients a la
-- @GameAction@, and actions from the managing process i.e. advances to
-- next rounds and automatic advances after timeouts.
data MachineInput = InpAuto -- ^ Whatever the current state is, do an action that advances it to the next state
| InpTurnAction Kaze TurnAction -- ^ An action from player in turn
| InpShout Kaze Shout -- ^ A call
| InpPass Kaze -- ^ Ignore call
deriving (Show, Read)
-- | Remember to publish the turn action when successful
step :: InKyoku m => Machine -> MachineInput -> m Machine
step KyokuNone _ = return KyokuNone
step (KyokuStartIn _) InpAuto = sendDealStarts >> waitForDraw -- startDeal
step (WaitingDraw pk wanpai) InpAuto = draw pk wanpai >> askForTurnAction 15 >> return (WaitingDiscard pk) -- TODO hard-coded timeout
step (WaitingDraw pk wanpai) (InpTurnAction pk' (TurnTileDraw wanpai' _))
| wanpai /= wanpai' = throwError "You are not supposed to draw there"
| pk /= pk' = throwError $ "Not your (" ++ tshow pk' ++ ") turn, it's turn of " ++ tshow pk
| otherwise = draw pk wanpai >> askForTurnAction 15 >> return (WaitingDiscard pk) -- TODO hard-coded timeout
step (WaitingDiscard pk) InpAuto = autoDiscard pk
step (WaitingDiscard pk) (InpTurnAction pk' ta)
| pk /= pk' = throwError $ "Not your (" ++ tshow pk' ++ ") turn, it's turn of " ++ tshow pk
| TurnTileDiscard d <- ta = processDiscard pk d
| TurnAnkan t <- ta = processAnkan pk t
| TurnTsumo <- ta = endKyoku =<< endTsumo pk
| TurnShouminkan t <- ta = processShouminkan pk t
step (WaitingShouts _ winning shouts chankan) InpAuto
| null winning = proceedWithoutShoutsAfterDiscard chankan
| otherwise = processShouts (map (shouts L.!!) winning) chankan
step (WaitingShouts couldShout winning shouts chankan) (InpPass pk) = do
let couldShout' = deleteSet pk couldShout
p <- kazeToPlayer pk
tellEvent $ DealWaitForShout (p, pk, 0, [])
if' (null couldShout') (flip step InpAuto) return $ WaitingShouts couldShout' winning shouts chankan
step (WaitingShouts couldShout winning shouts chankan) (InpShout pk shout)
| pk `onotElem` couldShout, elemOf (each._1) pk shouts = throwError "You have already called on that tile"
| Just i <- L.findIndex (== (pk, shout)) shouts = do
res <- use pTurn >>= \tk -> case winning of
j:js -> case shoutPrecedence tk (shouts L.!! j) (pk, shout) of -- XXX: Would be prettier with a view-pattern
EQ -> return $ WaitingShouts (deleteSet pk couldShout) (i:j:js) shouts chankan -- new goes through with old ones
GT -> return $ WaitingShouts couldShout (j:js) shouts chankan -- old takes precedence (XXX: this branch should never even be reached
LT -> return $ WaitingShouts (deleteSet pk couldShout) [i] shouts chankan -- new takes precedence
[] -> return $ WaitingShouts (deleteSet pk couldShout) [i] shouts chankan
p <- kazeToPlayer pk
tellEvent $ DealWaitForShout (p, pk, 0, [])
case res of
WaitingShouts couldShout' _ _ _ | null couldShout' -> step res InpAuto
_ -> return res
| otherwise = throwError $ "Call '" ++ tshow shout ++ "' not possible (Your possible calls at the moment are: "
++ tshow (filter ((==pk).fst) shouts) ++ ")"
step CheckEndConditionsAfterDiscard InpAuto = checkEndConditions
step (KyokuEnded{}) InpAuto = do
k <- get
case maybeGameResults k of
Nothing -> return KyokuNone
Just res -> endGame res
step HasEnded{} _ = throwError "This game has ended!"
step st inp = throwError $ "Kyoku.step: Invalid input in state " <> tshow st <> ": " <> tshow inp
-- | chankan?
proceedWithoutShoutsAfterDiscard :: InKyoku m => Bool -> m Machine
proceedWithoutShoutsAfterDiscard chankan = if' chankan (WaitingDiscard <$> use pTurn) (return CheckEndConditionsAfterDiscard)
dealGameEvent :: GameEvent -> Kyoku -> Kyoku
dealGameEvent ev = appEndo . mconcat $ case ev of
DealTurnBegins p ->
[ Endo $ pTurn .~ p
, Endo $ sWaiting .~ Nothing ]
DealTurnAction p ta ->
[ dealTurnAction p ta ]
DealTurnShouted p _shout ->
[ Endo $ pTurn .~ p ]
-- TODO get rid these in favor of finer control?
DealPublicHandChanged _pk _hp -> [ ]
-- [ Endo $ sHands.ix pk.handPublic .~ hp ]
DealPrivateHandChanged _ pk h ->
[ Endo $ sHands.ix pk .~ h ]
DealEnded how ->
[ Endo $ pResults .~ Just how ]
DealNick pk player nick ->
[ Endo $ pPlayers . ix pk . _3 .~ nick
, Endo $ pPlayers . ix pk . _1 .~ player ]
-- player-private
DealStarts{} -> [ ]
DealWaitForShout ws ->
[ Endo $ sWaiting %~ Just . Right . maybe [ws] (either (const [ws]) (|> ws)) ]
DealWaitForTurnAction wt ->
[ Endo $ sWaiting .~ Just (Left wt) ]
DealRiichi _pk ->
[ Endo $ pRiichi +~ 1000 ]
DealFlipDora td -> [ Endo $ pDora %~ (|> td) ]
GamePoints pk ps ->
[ Endo $ pPlayers.ix pk._2 +~ ps ]
GameEnded _ -> []
dealTurnAction :: Kaze -> TurnAction -> Endo Kyoku
dealTurnAction p ta = mconcat $ case ta of
TurnTileDiscard dc ->
[ Endo $ sHands.ix p.handDiscards %~ (|> dc) ]
TurnTileDraw _w _ ->
[ Endo $ pWallTilesLeft -~ 1 ]
TurnAnkan _ ->
[ ]
-- [ Endo $ sHands.ix p.handCalled %~ (|> kantsu tile) ]
TurnShouminkan _ ->
[ ]
-- let isShoum m = mentsuKind m == Koutsu && mentsuTile m == t
-- in [ Endo $ sHands.ix p.handPublic.handCalled.each . filtered isShoum %~ promoteToKantsu ]
TurnTsumo ->
[] -- XXX: should something happen?
-- | Results are returned if west or higher round has just ended and
-- someone is winning (over 30000 points).
maybeGameResults :: Kyoku -> Maybe FinalPoints
maybeGameResults kyoku@Kyoku{..}
| minimumOf (traversed._2) _pPlayers < Just 0 = return score -- if anyone below zero end immediately
| otherwise = do
guard (nextRound kyoku ^. _1 > Nan) -- Don't end before *last* south deal
unless (nextRound kyoku ^. _1 > Shaa) $ -- Require point-difference, unless last deal of an extra-round ended
guard (maximumOf (traversed._2) _pPlayers > Just 30000)
return score
where
score = finalPoints $ mapFromList $ _pPlayers ^.. each.to (\(p,ps,_) -> (p, ps))
nextRound :: Kyoku -> Round
nextRound Kyoku{..} = case _pResults of
Just DealAbort{..} -> _pRound & _3 +~ 1
Just DealDraw{..} -> _pRound & if elemOf (each._1) Ton dTenpais then _3 +~ 1 else set _3 (_pRound^._3 + 1) . roundRotates
Just DealRon{..} -> _pRound & if elemOf (each._1) Ton dWinners then _3 +~ 1 else roundRotates
Just DealTsumo{..} -> _pRound & if elemOf (each._1) Ton dWinners then _3 +~ 1 else roundRotates
Nothing -> _pRound
where
roundRotates (k, 4, _) = (succCirc k, 1, 0)
roundRotates (k, r, _) = (k, r + 1, 0)
-- | Advance the game to next deal, or end it.
-- TODO move to Round.hs
maybeNextDeal :: Kyoku -> IO (Either FinalPoints Kyoku)
maybeNextDeal deal = maybe (Right <$> nextDeal deal) (return . Left) $ maybeGameResults deal
-- | TODO move to Round.hs. Everything but tile shuffling could be in
-- events.
nextDeal :: Kyoku -> IO Kyoku
nextDeal kyoku = do tiles <- shuffleTiles
return $ go $ dealTiles tiles kyoku
where
go = set pRound newRound
. set pTurn Ton
. set pHonba (newRound^._3)
. if' rotate (pOja .~ nextOja) id
. if' rotate (over pPlayers rotatePlayers) id
. if' riichiTransfers (pRiichi .~ 0) id
. set pResults Nothing
newRound = nextRound kyoku
rotate = newRound^._2 /= kyoku^.pRound._2
riichiTransfers = case kyoku^?!pResults of
Just DealAbort{} -> False
Just DealDraw{} -> False
_ -> True
nextOja = kyoku ^?! pPlayers.ix Nan . _1 :: Player
rotatePlayers :: Map Kaze a -> Map Kaze a
rotatePlayers = mapFromList . map (_1 %~ predCirc) . mapToList
nagashiOrDraw :: InKyoku m => m Machine
nagashiOrDraw = do
hands <- use sHands
wins <- iforM hands $ \pk hand -> if handInNagashi hand then return $ handWinsNagashi pk hand else return Nothing
let winners = map fst $ catMaybes $ map snd $ mapToList wins :: [Winner]
payers = map (\xs@((p,_):_) -> (p, sumOf (traversed._2) xs)) $ groupBy (equating fst) $ (concatMap snd $ catMaybes $ map snd $ mapToList wins) :: [Payer]
res <- if null winners then endDraw else return $ DealTsumo winners payers
endKyoku res
handWinsNagashi :: Kaze -> Hand -> Maybe (Winner, [Payer])
handWinsNagashi pk hand =
-- TODO perhaps this could be placed in YakuCheck too
let points = floor $ if' (pk == Ton) 1.5 1 * 8000
value = Value [Yaku 5 "Nagashi Mangan"] 0 5 0 (Just "Mangan")
winner = (pk, points, ValuedHand (hand^.handCalled) (hand^.handConcealed) value)
-- TODO fails when not four players
payers = map (\payer -> (payer, if' (payer == Ton) 2 1 * 2000)) $ L.delete pk [Ton .. Pei]
in Just (winner, payers)
processAnkan :: InKyoku m => Kaze -> Tile -> m Machine
processAnkan pk t = do
handOf' pk >>= ankanOn t >>= updateHand pk
otherHands <- use sHands <&> filter ((/=pk).fst) . Map.toList
let kokushiWins = filter ((== NotFuriten) . _handFuriten . snd) $
filter ((== Just (-1)) . shantenBy kokushiShanten . (handConcealed %~ cons t) . snd) otherHands
if null kokushiWins -- chankan on ankan only when kokushi could win from it
then return $ WaitingDraw pk True
else return $ WaitingShouts (setFromList $ map fst kokushiWins) [] (each._2 .~ Shout Chankan pk t [] $ kokushiWins) True
processShouminkan :: InKyoku m => Kaze -> Tile -> m Machine
processShouminkan pk t = do
handOf' pk >>= shouminkanOn t >>= updateHand pk
chankanShouts <- getShouts True t
if null chankanShouts then return (WaitingDraw pk True)
else do tellEvents . map DealWaitForShout =<< toWaitShouts chankanShouts
return (WaitingShouts (setFromList $ map fst chankanShouts) [] chankanShouts True)
checkEndConditions :: InKyoku m => m Machine
checkEndConditions = do
updateTempFuritens
tilesLeft <- use pWallTilesLeft
dora <- use pDora
everyoneRiichi <- use sHands <&> allOf (each.handRiichi) (/= NoRiichi)
firstDiscards <- use sHands <&> toListOf (each.handDiscards._head.dcTile)
let fourWindTiles = length firstDiscards == 4 && isKaze (headEx firstDiscards) && allSame firstDiscards
case () of
_ | length dora == 5 -> endKyoku $ DealAbort SuuKaikan -- TODO check that someone is not waiting for the yakuman
| tilesLeft == 0 -> nagashiOrDraw
| everyoneRiichi -> endKyoku $ DealAbort SuuchaRiichi
| fourWindTiles -> endKyoku $ DealAbort SuufonRenda
| otherwise -> advanceTurn <&> (`WaitingDraw` False)
where
allSame :: [Tile] -> Bool
allSame [] = True
allSame (x:xs) = all (x ==~) xs
-- ** Beginning
-- | Send the very first Kyoku events to everyone. Contains the game state.
sendDealStarts :: InKyoku m => m ()
sendDealStarts = do
deal <- get
imapM_ (\pk (player,_,_) -> tellEvent . DealStarts $ PlayerKyoku player pk deal) (deal^.pPlayers)
-- ** Drawing
-- | WaitingDraw, not wanpai
waitForDraw :: InKyoku m => m Machine
waitForDraw = do
pk <- use pTurn
h <- handOf' pk
updateHand pk $ h & handState .~ DrawFromWall
tellEvent $ DealTurnBegins pk
return $ WaitingDraw pk False
draw :: InKyoku m => Kaze -> Bool -> m ()
draw pk wanpai = do
firstRound <- use $ pFlags.to (member FirstRoundUninterrupted)
when firstRound $ do
allHandsInterrupted <- use sHands <&> allOf (each.handFlags) (notMember HandFirsRoundUninterrupted)
when allHandsInterrupted $ unsetFlag FirstRoundUninterrupted
updateHand pk =<< (if wanpai then drawDeadWall else drawWall) =<< handOf' pk
tellEvent $ DealTurnAction pk $ TurnTileDraw wanpai Nothing
drawWall :: InKyoku m => Hand -> m Hand
drawWall hand = do
wallHead <- preuse (sWall._head) >>= maybe (throwError "Wall is empty") return
sWall %= tailEx
wallHead `toHand` hand
drawDeadWall :: InKyoku m => Hand -> m Hand
drawDeadWall hand = do
lastTileInWall <- preuse (sWall._last) >>= maybe (throwError "Wall is empty") return
fromWanpai <- wanpaiGetSupplement lastTileInWall
flipNewDora -- TODO should it flip now or after the discard?
fromWanpai `toHandWanpai` hand
-- ** Discarding
processDiscard :: InKyoku m => Kaze -> Discard -> m Machine
processDiscard pk d' = do
let d = d' & dcTo .~ Nothing
when (d^.dcRiichi) $ doRiichi pk
updateHand pk =<< discard d =<< handOf' pk
shouts <- getShouts False (d^.dcTile)
waiting <- toWaitShouts shouts
tellEvents $ map DealWaitForShout waiting
return $ if null waiting
then CheckEndConditionsAfterDiscard
else WaitingShouts (setFromList $ map fst shouts) [] shouts False
doRiichi :: InKyoku m => Kaze -> m ()
doRiichi pk = do
pointsAfterRiichi <- use $ pPlayers.at pk.singular _Just._2.to (\a -> a - 1000)
when (pointsAfterRiichi < 0) $ throwError "Cannot riichi: not enough points"
tellEvents [DealRiichi pk, GamePoints pk (-1000)]
autoDiscard :: InKyoku m => Kaze -> m Machine
autoDiscard tk = processDiscard tk =<< handAutoDiscard =<< handOf' tk
-- | Update temporary furiten state of all players after a discard.
updateTempFuritens :: InKyoku m => m ()
updateTempFuritens = do
pk <- use pTurn
tile <- _dcTile . lastEx . _handDiscards <$> handOf' pk
handOf' pk >>= \h -> case h^.handFuriten of
NotFuriten | tile `elem` handGetAgari h -> updateHand pk $ h & handFuriten .~ TempFuriten
TempFuriten -> updateHand pk $ h & handFuriten .~ NotFuriten
_ -> return ()
forM_ (L.delete pk [Ton .. Pei]) $ \k -> handOf' k >>= \h -> case h^.handFuriten of
NotFuriten | tile `elem` handGetAgari h -> updateHand k $ h & handFuriten .~ TempFuriten
_ -> return ()
-- ** Turn-passing
-- | Next player who draws a tile
advanceTurn :: InKyoku m => m Kaze
advanceTurn = do
pk <- use pTurn <&> succCirc
updateHand pk . set handState DrawFromWall =<< handOf' pk
tellEvent $ DealTurnBegins pk
return pk
-- ** Wanpai
-- | Flip a new dora from wanpai. If the kyoku would end in suukaikan after
-- the next discard, set the @SuuKaikanAfterDiscard@ flag.
--
-- Note: does not check if the filp is valid.
flipNewDora :: InKyoku m => m ()
flipNewDora = tellEvent . DealFlipDora =<< wanpaiGetDora
-- | Reveals opened ura-dora from the wanpai. Toggles the @OpenedUraDora@
-- flag.
revealUraDora :: InKyoku m => m ()
revealUraDora = do
count <- use (pDora.to length)
ura <- use (sWanpai.wUraDora) <&> take count
tellEvent $ DealFlipDora ura
setFlag . OpenedUraDora $ map TileEq ura
-- | Get supplementary tile from wanpai. Argument must be a tile from
-- the wall to append to the wall.
wanpaiGetSupplement :: InKyoku m => Tile -> m Tile
wanpaiGetSupplement fromWall = preuse (sWanpai.wSupplement._Cons) >>= \case
Just (x, xs) -> do sWanpai.wSupplement .= xs
sWanpai.wBlank %= flip snoc fromWall
return x
Nothing -> throwError "Four kantsu already called"
wanpaiGetDora :: InKyoku m => m Tile
wanpaiGetDora = preuse (sWanpai.wDora._Cons) >>= \case
Just (x, xs) -> sWanpai.wDora .= xs >> return x
Nothing -> throwError "Internal error: no dora left in wanpai"
-- ** Waiting
-- | n seconds
askForTurnAction :: InKyoku m => Int -> m ()
askForTurnAction n = do
tk <- use pTurn
tp <- kazeToPlayer tk
rt <- handOf' tk <&> handCanRiichiWith
tellEvent $ DealWaitForTurnAction (tp, tk, n, rt)
-- | @processShout shouts chankan?@
--
-- Multiple shouts are allowed only when they go out
processShouts :: InKyoku m => [(Kaze, Shout)] -> Bool -> m Machine
processShouts [] _ = return $ CheckEndConditionsAfterDiscard
processShouts shouts@((fsk,fs):_) _chank = do
tk <- use pTurn
th <- handOf' tk
(th':_) <- forM shouts $ \(sk, s) -> do
sh <- handOf' sk
th' <- shoutFromHand sk s th
sh' <- if null (shoutTo s) then rons s sh else meldTo s sh -- if null then kokushi. can't use a mentsu 'cause mentsu have >=2 tiles
updateHand sk sh'
tellEvent $ DealTurnShouted sk s
return th'
updateHand tk th'
case () of
_ | shoutKind fs `elem` [Ron, Chankan] -> endRon (map fst shouts) tk >>= endKyoku
| shoutKind fs == Kan -> unsetFlag FirstRoundUninterrupted >> return (WaitingDraw fsk True)
| otherwise -> do
unsetFlag FirstRoundUninterrupted
tellEvent $ DealTurnBegins fsk
return (WaitingDiscard fsk)
-- ** Ending
endKyoku :: InKyoku m => KyokuResults -> m Machine
endKyoku res = return (KyokuEnded res)
endGame :: InKyoku m => FinalPoints -> m Machine
endGame points = do tellEvent $ GameEnded points
return $ HasEnded points
endTsumo :: InKyoku m => Kaze -> m KyokuResults
endTsumo winner = do
handOf' winner >>= updateHand winner . setAgariTsumo
vh <- getValuedHand winner
honba <- use pHonba
riichi <- use pRiichi
payers <- use pPlayers <&> tsumoPayers honba (vh^.vhValue.vaValue) . L.delete winner . map fst . itoList
let win = (winner, - sumOf (each._2) payers + riichi, vh)
dealEnds $ DealTsumo [win] payers
endDraw :: InKyoku m => m KyokuResults
endDraw = do
hands <- use sHands
let x@(tenpaiHands, nootenHands) = partition (tenpai.snd) (itoList hands) -- & both.each %~ fst
(receive, pay) | null tenpaiHands || null nootenHands = (0, 0)
| otherwise = x & both %~ div 3000.fromIntegral.length
dealEnds $ DealDraw (map (\(k,h) -> (k,receive,h^.handCalled,h^.handConcealed)) tenpaiHands) (map ((,-pay) . fst) nootenHands)
endRon :: InKyoku m => [Kaze] -> Kaze -> m KyokuResults
endRon winners payer = do
valuedHands <- mapM getValuedHand winners
honba <- use pHonba
riichi <- use pRiichi
let pointsFromPayer = zipWith valuedHandPointsForRon winners valuedHands
pointsRiichi = riichi
pointsHonba = honba * 300
Just extraGoesTo = payer ^.. iterated succCirc & find (`elem` winners) -- Iterate every kaze, so one must be an element. unless no one won.
winEntries = map (\x -> if x^._1 == extraGoesTo then x & _2 +~ pointsHonba + pointsRiichi else x) $ zip3 winners pointsFromPayer valuedHands
dealEnds $ DealRon winEntries [(payer, negate $ pointsHonba + sum pointsFromPayer)]
-- *** Helpers
valuedHandPointsForRon :: Kaze -> ValuedHand -> Points
valuedHandPointsForRon pk vh = roundKyokuPoints $ if' (pk == Ton) 6 4 * (vh^.vhValue.vaValue)
-- | Apply KyokuResults and pay points.
dealEnds :: InKyoku m => KyokuResults -> m KyokuResults
dealEnds results = do
tellEvents $ DealEnded results : payPoints results
return results
-- | Value the hand. If the hand would be valueless (no yaku, just extras),
-- raise an error.
getValuedHand :: InKyoku m => Kaze -> m ValuedHand
getValuedHand pk = do
revealUraDora -- TODO wrong place for this
vh <- valueHand pk <$> handOf' pk <*> use id
when (length (vh^..vhValue.vaYaku.each.filtered yakuNotExtra) == 0) $
throwError $ "Need at least one yaku that ain't dora to win.\nThe ValuedHand: " ++ tshow vh
return vh
-- ** Scoring
payPoints :: KyokuResults -> [GameEvent]
payPoints res = case res of
DealAbort{} -> []
DealDraw{..} -> map (uncurry GamePoints) $ map (\x -> (x^._1,x^._2)) dTenpais ++ dNooten
_ -> map f (dWinners res) ++ map (uncurry GamePoints) (dPayers res)
where f (p, v, _) = GamePoints p v
-- |
-- >>> roundKyokuPoints 150
-- 200
--
-- >>> roundKyokuPoints 500
-- 500
roundKyokuPoints :: Points -> Points
roundKyokuPoints x = case x `divMod` 100 of
(a, b) | b > 0 -> (a + 1) * 100
| otherwise -> a * 100
-- |
-- @tsumoPayers honba winner basicPoints payers@
--
-- >>> tsumoPayers 0 320 [Nan, Shaa, Pei]
-- [(Nan,-700),(Shaa,-700),(Pei,-700)]
--
-- >>> tsumoPayers 1 320 [Ton, Shaa, Pei]
-- [(Ton,-800),(Shaa,-500),(Pei,-500)]
--
tsumoPayers :: Int -> Points -> [Kaze] -> [Payer]
tsumoPayers honba basic payers
| Ton `elem` payers = map (\p -> (p, negate $ roundKyokuPoints $ basic * if' (p == Ton) 2 1 + honba * 100)) payers
| otherwise = map ( , negate $ roundKyokuPoints $ basic * 2 + honba * 100) payers
-- * Final scoring
-- |
-- >>> finalPoints (Map.fromList [(Player 0,25000), (Player 1,25000), (Player 2,25000), (Player 3,25000)])
-- FinalPoints (fromList [(Player 0,35),(Player 1,5),(Player 2,-15),(Player 3,-25)])
--
-- >>> finalPoints (Map.fromList [(Player 0, 35700), (Player 1, 32400), (Player 2, 22200), (Player 3, 9700)])
-- FinalPoints (fromList [(Player 0,46),(Player 1,12),(Player 2,-18),(Player 3,-40)])
finalPoints :: PointsStatus -> FinalPoints
finalPoints xs = final & _head._2 -~ sumOf (each._2) final -- fix sum to 0
& Map.fromList & FinalPoints
where
target = 30000 -- TODO configurable target score
oka = 5000 * 4 -- TODO could be something else
uma = [20, 10, -10, -20] -- TODO This too
final = Map.toList xs & sortBy (flip $ comparing snd)
& each._2 -~ target
& _head._2 +~ oka
& each._2 %~ roundFinalPoints
& zipWith (\s (p, s') -> (p, s + s')) uma
-- |
-- >>> roundFinalPoints 15000
-- 15
-- >>> roundFinalPoints (-5000)
-- -5
roundFinalPoints :: Int -> Int
roundFinalPoints x = case x `divMod` 1000 of
(r, b) | b >= 500 -> r + 1
| otherwise -> r
----------------------------------------------------------------------------------------
-- * Events
tellPlayerState :: InKyoku m => Player -> m ()
tellPlayerState p = do
pk <- playerToKaze p
deal <- get
tellEvent . DealStarts $ PlayerKyoku p pk deal
updatePlayerNick :: InKyoku m => Player -> Text -> m ()
updatePlayerNick p nick = playerToKaze p >>= \pk -> tellEvent (DealNick pk p nick)
-- | Set the hand of player
updateHand :: InKyoku m => Kaze -> Hand -> m ()
updateHand pk new = do
p <- kazeToPlayer pk
sHands.at pk .= Just new
tellEvent (DealPrivateHandChanged p pk new)
tellEvent (DealPublicHandChanged pk $ PlayerHand new)
tellEvent :: InKyoku m => GameEvent -> m ()
tellEvent ev = do
modify $ dealGameEvent ev
tell [ev]
tellEvents :: InKyoku m => [GameEvent] -> m ()
tellEvents = mapM_ tellEvent
----------------------------------------------------------------------------------------
-- * Query info
playerToKaze :: InKyoku m => Player -> m Kaze
playerToKaze player = do
mp <- use pPlayers <&> ifind (\_ x -> x^._1 == player)
maybe (throwError $ "Player `" ++ tshow player ++ "' not found") (return . fst) mp
kazeToPlayer :: InKyoku m => Kaze -> m Player
kazeToPlayer pk = do
rp <- use pPlayers <&> view (at pk)
maybe (throwError $ "Player `" ++ tshow pk ++ "' not found") (return . (^._1)) rp
handOf' :: InKyoku m => Kaze -> m Hand
handOf' p = use (handOf p) >>= maybe (throwError "handOf': Player not found") return
----------------------------------------------------------------------------------------
-- * Waiting
-- | Get all possible shouts from all players for a given tile.
filterCouldShout :: Tile -- ^ Tile to shout
-> Kaze -- ^ Whose tile
-> Map Kaze Hand -- ^ All hands
-> [(Kaze, Shout)] -- ^ Sorted in correct precedence (highest priority as head)
filterCouldShout dt np = sortBy (shoutPrecedence np)
. concatMap flatten . Map.toList
. Map.mapWithKey (shoutsOn np dt)
. Map.filter ((== NotFuriten) . _handFuriten) -- discard furiten
where flatten (k, xs) = map (k,) xs
-- | Flag for chankan.
getShouts :: InKyoku m => Bool -> Tile -> m [(Kaze, Shout)]
getShouts chankan dt = do
lastTile <- use pWallTilesLeft <&> (== 0)
shouts <- filterCouldShout dt <$> use pTurn <*> use sHands
filterM couldContainYaku $
if' chankan (over (each._2) toChankan . filter ((== Ron) . shoutKind.snd)) id $
if' lastTile (filter $ (== Ron) . shoutKind . snd) id -- when there are no tiles, only go-out shouts are allowed
shouts
yakuNotExtra :: Yaku -> Bool
yakuNotExtra Yaku{} = True
yakuNotExtra YakuExtra{} = False
toChankan :: Shout -> Shout
toChankan s = s { shoutKind = Chankan }
-- | The shout wouldn't result in a 0-yaku mahjong call
couldContainYaku :: InKyoku m => (Kaze, Shout) -> m Bool
couldContainYaku (k, s)
| Ron <- shoutKind s = do
h <- handOf' k
vh <- valueHand k <$> meldTo s h <*> get
return $ length (vh^..vhValue.vaYaku.each.filtered yakuNotExtra) /= 0
| otherwise = return True
toWaitShouts :: InKyoku m => [(Kaze, Shout)] -> m [WaitShout]
toWaitShouts shouts = do
let grouped = map (liftA2 (,) (^?!_head._1) (^..each._2)) $ groupBy ((==) `on` view _1) shouts
forM grouped $ \(k, s) -> do
player <- kazeToPlayer k
return (player, k, 15, s)
-- * Flags
unsetFlag, setFlag :: InKyoku m => Flag -> m ()
setFlag f = void $ pFlags %= insertSet f
unsetFlag f = void $ pFlags %= deleteSet f
|
SimSaladin/hajong
|
hajong-server/src/Mahjong/Kyoku.hs
|
Haskell
|
mit
| 28,620
|
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableSuperClasses #-}
{-# LANGUAGE PolyKinds #-}
module QuickForm.Validation where
import Data.Default
import QuickForm.Form
import QuickForm.TypeLevel
-- | Validation functions
data Validator (q :: QuickForm) where
ValidatedVal :: (FormOutput q -> Either e a) -> Validator q -> Validator (Validated e a q)
FieldVal :: Validator (Field n a)
FieldsVal :: TList (Map Validator qs) -> Validator (Fields qs)
class ValidateForm q where
validateForm :: Validator q -> Form q -> Result q
instance FormOutput (Field n a) ~ ToForm (Field n a) => ValidateForm (Field n a) where
validateForm FieldVal (Form a) = Success a
{-# INLINE validateForm #-}
instance (JoinFields qs, ValidateFields qs)
=> ValidateForm (Fields qs) where
validateForm fs as = joinFields $ validateFields fs as
{-# INLINE validateForm #-}
instance (Default (FormError q), ValidateForm q)
=> ValidateForm (Validated e a q) where
validateForm (ValidatedVal f sub) (Form b)
= runValidated f $ validateForm sub $ Form b
{-# INLINE validateForm #-}
instance Default (Validator (Field n a)) where
def = FieldVal
instance Default (TList (Map Validator qs))
=> Default (Validator (Fields qs)) where
def = FieldsVal def
class ValidateFields qs where
validateFields
:: Validator (Fields qs) -> Form (Fields qs) -> TList (Map Result qs)
instance ValidateFields '[] where
validateFields (FieldsVal Nil) (Form Nil) = Nil
instance
( ValidateForm q, ValidateFields qs
) => ValidateFields (q ': qs) where
validateFields (FieldsVal (f :| fs)) (Form (a :| as)) =
validateForm f (Form a) :| validateFields @qs (FieldsVal fs) (Form as)
-- | Result of running a validation
data Result q
= Error (FormError q)
| Success (FormOutput q)
deriving instance (Eq (FormError q), Eq (FormOutput q)) => Eq (Result q)
deriving instance (Show (FormError q), Show (FormOutput q)) => Show (Result q)
class JoinFields qs where
joinFields :: TList (Map Result qs) -> Result (Fields qs)
instance JoinFields '[] where
joinFields Nil = Success Nil
instance
( Default (TList (Map FormError qs))
, Default (FormError q)
, JoinFields qs
) => JoinFields (q ': qs) where
joinFields (e :| es) = case (e, joinFields @qs es) of
(Error e', Error (FieldsError es')) -> Error $ FieldsError $ e' :| es'
(Error e', _) -> Error $ FieldsError $ e' :| def
(_, Error (FieldsError es')) -> Error $ FieldsError $ def :| es'
(Success a, Success as) -> Success $ a :| as
runValidated
:: (Default (FormError q))
=> (FormOutput q -> Either e a) -> Result q -> Result (Validated e a q)
runValidated f q = case q of
Error e -> Error $ ValidatedError Nothing e
Success hs -> case f hs of
Left e -> Error $ ValidatedError (Just e) def
Right a -> Success a
|
tomsmalley/quickform
|
src/QuickForm/Validation.hs
|
Haskell
|
mit
| 3,284
|
-- | This module contains the algorithm for determining the best possible move
-- in a game of tic-tac-toe.
module Minimax (findOptimalMove) where
-------------------
-- Local Imports --
import Board
----------
-- Code --
-- | Accessing the third element in a 3-tuple.
thd :: (a, b, c) -> c
thd (_, _, c) = c
-- | Finding the maximum score of a move.
maxScore :: BoardState -> Int
maxScore X = -2
maxScore O = 2
maxScore Nil = 0
-- | Finding the distance between two numbers.
distance :: Num a => a -> a -> a
distance a b = abs $ a - b
-- | Finding the better of two (Int, Int, Point)s.
findBetter :: Int -> (Int, Int, Point) -> (Int, Int, Point) -> (Int, Int, Point)
findBetter target (m1, s1, p1) (m2, s2, p2)
| distance target s1 < distance target s2 = (m1, s1, p1)
| distance target s2 < distance target s1 = (m2, s2, p1)
| distance target s1 == distance target s2 =
if m1 < m2
then (m1, s1, p1)
else (m2, s2, p2)
-- | The back-end to finding an optimal move in a board.
findOptimalMove' :: Int -> Point -> BoardState -> Board -> (Int, Int, Point)
findOptimalMove' numMoves pnt move board
| isOver board = (numMoves, boardStateToInt $ findWinner board, pnt)
| otherwise =
foldl1 (findBetter (maxScore move)) $
map (\p -> findOptimalMove' (numMoves + 1) p (otherState move) (boardPush p move board)) moves
where moves = validMoves board
-- | Finding the optimal move in a board.
findOptimalMove :: BoardState -> Board -> Point
findOptimalMove Nil = const (-1, -1)
findOptimalMove s = thd . findOptimalMove' 0 (-1, -1) s
|
crockeo/tic-taskell
|
src/Minimax.hs
|
Haskell
|
mit
| 1,584
|
{-|
Module : BreadU.Pages.Markup.Common.Header
Description : HTML markup for pages' top area.
Stability : experimental
Portability : POSIX
HTML markup for pages' top area.
Please don't confuse it with <head>-tag, it's defined in another module.
-}
module BreadU.Pages.Markup.Common.Header
( commonHeader
) where
import BreadU.Types ( LangCode(..), allLanguages )
import BreadU.Pages.Types ( HeaderContent(..) )
import BreadU.Pages.CSS.Names ( ClassName(..) )
import BreadU.API ( indexPageLink )
import BreadU.Pages.Markup.Common.Utils
import Prelude hiding ( div, span )
import TextShow ( showt )
import Data.Text ( toUpper )
import Data.List ( delete )
import Data.Monoid ( (<>) )
import Text.Blaze.Html5
import qualified Text.Blaze.Html5.Attributes as A
-- | Header for all pages.
commonHeader :: HeaderContent -> LangCode -> Html
commonHeader headerContent@HeaderContent{..} langCode = header $ do
row_ $ do
aboutModal headerContent
col_6 languageSwitcher
col_6 about
h1 $ toHtml siteName
where
-- All supported languages are here.
languageSwitcher =
div ! A.class_ "btn-group" $ do
button ! A.class_ (toValue $ "btn btn-outline-info btn-sm btn-rounded waves-effect dropdown-toggle "
<> showt LanguageSwitcher)
! A.type_ "button"
! dataAttribute "toggle" "dropdown"
! customAttribute "aria-haspopup" "true"
! customAttribute "aria-expanded" "false" $ toHtml $ showt langCode
div ! A.class_ "dropdown-menu" $
mapM_ (\lCode -> a ! A.class_ "dropdown-item"
! A.href (toValue $ indexPageLink lCode) $
toHtml . toUpper . showt $ lCode)
otherLanguages
otherLanguages = delete langCode allLanguages
about = div ! A.class_ "text-right" $
button ! A.type_ "button"
! A.class_ "btn btn-outline-info btn-sm btn-rounded waves-effect"
! A.title (toValue aboutTitle)
! dataAttribute "toggle" "modal"
! dataAttribute "target" "#aboutModal" $ toHtml aboutLabel
-- | Show modal window with info about the service.
aboutModal :: HeaderContent -> Html
aboutModal HeaderContent{..} =
div ! A.class_ "modal"
! A.id "aboutModal"
! A.tabindex "-1"
! customAttribute "role" "dialog"
! customAttribute "aria-labelledby" "aboutModalLabel"
! customAttribute "aria-hidden" "true" $
div ! A.class_ "modal-dialog modal-lg"
! customAttribute "role" "document" $
div ! A.class_ "modal-content" $ do
div ! A.class_ "modal-header" $ do
h3 ! A.class_ "modal-title w-100"
! A.id "aboutModalLabel" $ toHtml siteName
closeButton
div ! A.class_ (toValue $ "modal-body " <> showt AboutInfo) $ do
p $ toHtml briefDescription
p $ toHtml buDescription
h4 $ toHtml howToUseItTitle
p $ toHtml howToUseItFood
p $ toHtml howToUseItQuantity
p $ toHtml howToUseItAddFood
p $ toHtml howToUseItCalculate
h4 $ toHtml ossTitle
p $ preEscapedToHtml oss
h4 $ toHtml disclaimerTitle
p $ toHtml disclaimer
where
closeButton =
button ! A.type_ "button"
! A.class_ "close"
! dataAttribute "dismiss" "modal"
! customAttribute "aria-label" "Close" $
span ! customAttribute "aria-hidden" "true" $
preEscapedToHtml ("×" :: String)
|
denisshevchenko/breadu.info
|
src/lib/BreadU/Pages/Markup/Common/Header.hs
|
Haskell
|
mit
| 4,202
|
module System.Flannel.BuilderTreeSpec
( spec
) where
import qualified System.Flannel.Argument as A
import System.Flannel.Command
import System.Flannel.CommandBuilder
import System.Flannel.BuilderTree
import Test.Hspec
spec :: Spec
spec = do
describe "define" $ do
context "when there is no previous definition" $ do
let expected =
[ (A.Optional, A.Flag "beta" ["-b", "--beta"] "beta flag")
, (A.Optional, A.Argument "alpha" "the first argument")
]
it "defines the CommandBuilder" $ do
let definition = runDsl $ do
define $ do
desc "description"
flag "beta" ["-b", "--beta"] "beta flag"
arg "alpha" "the first argument"
command $ do
run $ print "yay"
length definition `shouldBe` 1
case head definition of
Namespace _ _ -> False `shouldBe` True
Builder (BuilderState d a _) -> do
d `shouldBe` "description"
a `shouldBe` expected
context "when there is a previous definition" $ do
it "does not overide it" $ do
let definition = runDsl $ do
define $ do
desc "d1"
define $ do
desc "d2"
length definition `shouldBe` 1
case head definition of
Namespace _ _ -> False `shouldBe` True
Builder (BuilderState d _ _) -> do
d `shouldBe` "d1"
describe "namespace" $ do
it "wraps a new Dsl" $ do
let definition = runDsl $ do
namespace "new namespace" $ return ()
length definition `shouldBe` 1
case head definition of
Builder _ -> False `shouldBe` True
Namespace d _ ->
d `shouldBe` "new namespace"
|
nahiluhmot/flannel
|
spec/System/Flannel/BuilderTreeSpec.hs
|
Haskell
|
mit
| 2,162
|
-- |
module Constraint.Term where
import qualified Syntax
constrain env term ty = case term of
Literal lit -> Literal.constrain env lit ty
|
cpehle/faust
|
src/Constraint/Term.hs
|
Haskell
|
mit
| 153
|
{-# LANGUAGE OverloadedStrings,
RecordWildCards,
LambdaCase,
ViewPatterns,
ScopedTypeVariables,
NoMonomorphismRestriction #-}
module Network.AWS.Connection where
import qualified Prelude as P
import qualified Data.List as L
import System.Environment (getEnvironment)
import Network.AWS.Core
---------------------------------------------------------------------
-- AWS Type Classes
-- Abstracts some common capabilities of AWS-related types.
---------------------------------------------------------------------
-- | Class of things which contain AWS configuration.
class AwsCfg a where
getCon :: Str s => a s -> AwsConnection s
-- | The class of types from which we can generate CanonicalHeaders.
class AwsCfg a => Canonical a where
-- | Builds the canonical list of headers.
canonicalHeaders :: Str s => a s -> [(s, s)]
-- | Munges information from the command into a "canonical request".
canonicalRequest :: Str s => a s -> s
---------------------------------------------------------------------
-- Data types
-- The @str@ in these types must be a type that implements @Str@.
---------------------------------------------------------------------
-- | Stores the key id and secret key for an AWS transaction.
data AwsCredentials str = AwsCredentials
{ awsKeyId :: str
, awsSecretKey :: str
} deriving (Show)
-- | Configures commonly-used AWS options.
data AwsConfig str = AwsConfig
{ awsHostName :: str
, awsRegion :: str
, awsIsSecure :: Bool
, awsService :: str
, awsGivenCredentials :: CredentialSource str
} deriving (Show)
-- | Credentials can either be supplied directly, provided through a file,
-- or given in the environment.
data CredentialSource s = FromEnv
| FromFile s
| Directly (AwsCredentials s)
deriving (Show)
-- | Combines static config from the user with credentials which might be
-- determined at run-time.
data AwsConnection str = AwsConnection
{ awsConfig :: AwsConfig str
, awsCredentials :: AwsCredentials str
} deriving (Show)
instance AwsCfg AwsConnection where
getCon = id
-- | Various getters for AwsCfg types:
getCreds :: (AwsCfg aws, Str s) => aws s -> AwsCredentials s
getCreds = awsCredentials . getCon
getKeyId :: (AwsCfg aws, Str s) => aws s -> s
getKeyId = awsKeyId . getCreds
getSecretKey :: (AwsCfg aws, Str s) => aws s -> s
getSecretKey = awsSecretKey . getCreds
getConfig :: (AwsCfg aws, Str s) => aws s -> AwsConfig s
getConfig = awsConfig . getCon
getHostName :: (AwsCfg aws, Str s) => aws s -> s
getHostName = awsHostName . getConfig
getRegion :: (AwsCfg aws, Str s) => aws s -> s
getRegion = awsRegion . getConfig
getSecurity :: (AwsCfg aws, Str s) => aws s -> Bool
getSecurity = awsIsSecure . getConfig
getService :: (AwsCfg aws, Str s) => aws s -> s
getService = awsService . getConfig
---------------------------------------------------------------------
-- Loading configurations
---------------------------------------------------------------------
-- | The key (either in the env or in a config file) for the AWS access key.
accessIdKey :: P.String
accessIdKey = "AWS_ACCESS_KEY_ID"
-- | The key (either in the env or in a config file) for the AWS secret key.
secretKeyKey :: P.String
secretKeyKey = "AWS_SECRET_ACCESS_KEY"
-- | Creates an AwsConnection using a config.
createConnection :: (Functor io, MonadIO io, Str s)
=> AwsConfig s -> io (AwsConnection s)
createConnection cfg@AwsConfig{..} = AwsConnection cfg <$> creds where
creds = case awsGivenCredentials of
Directly creds -> return creds
FromFile file -> findCredentialsFromFile file >>= \case
Just creds -> return creds
Nothing -> error $ unlines [ "Couldn't get credentials from file "
<> show file <> "."
, "The file should use ConfigFile format, "
<> "and have the keys " <> show accessIdKey
<> " (access id) and " <> show secretKeyKey
<> " (secred access key)."]
FromEnv -> findCredentialsFromEnv >>= \case
Just creds -> return creds
Nothing -> error $ unlines [ "No credentials found in environment."
, "An access key id should be under the "
<> "variable " <> show accessIdKey <> "."
, "A secret access key should be under the "
<> "variable " <> show secretKeyKey <> "."]
-- | Chooses some reasonably sane defaults.
defaultConfig :: Str s => AwsConfig s
defaultConfig = AwsConfig { awsHostName = "s3.amazonaws.com"
, awsRegion = "us-east-1"
, awsService = "s3"
, awsIsSecure = False
, awsGivenCredentials = FromEnv }
-- | Uses the default config to create an AwsConnection.
defaultConnection :: (Functor io, MonadIO io, Str s) => io (AwsConnection s)
defaultConnection = createConnection defaultConfig
-- | Looks for credentials in the environment.
findCredentialsFromEnv :: (Functor io, MonadIO io, Str s)
=> io (Maybe (AwsCredentials s))
findCredentialsFromEnv = do
let getEnvKey s = liftIO $ fmap fromString . L.lookup s <$> getEnvironment
keyid <- getEnvKey accessIdKey
secret <- getEnvKey secretKeyKey
if isNothing keyid || isNothing secret then return Nothing
else return $ Just $ AwsCredentials (fromJust keyid) (fromJust secret)
-- | Looks for credentials in a config file.
findCredentialsFromFile :: (Functor io, MonadIO io, Str s)
=> s -> io (Maybe (AwsCredentials s))
findCredentialsFromFile (toString -> path) = P.undefined
---------------------------------------------------------------------
-- AWS Monad
---------------------------------------------------------------------
-- | Many operations take place in the context of some AWS connection. We can
-- put them in a monad transformer to simplify them.
type AwsT s = ReaderT (AwsConnection s)
-- | Runs a series of actions in the context of a single connection.
withConnection :: (Str s, MonadIO io, Functor io)
=> AwsConnection s -> AwsT s io a -> io a
withConnection con = flip runReaderT con
withDefaultConnection :: (Str s, MonadIO io, Functor io) => AwsT s io a -> io a
withDefaultConnection actions = do
con <- defaultConnection
withConnection con actions
|
thinkpad20/s3-streams
|
src/Network/AWS/Connection.hs
|
Haskell
|
mit
| 6,597
|
-- A module with some code to explore theorems in the monadic lambda calculus
module TP where
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Foldable hiding (concat,any,all)
import Control.Monad.State
import DataTypes
import Control.Parallel (par, pseq)
debShow (LeftContext l lc f r,c) = show $ (LeftContext (map formula l) (map formula lc) (formula f) (map formula r), formula c)
debShow (RightContext l f rc r,c) = show $ (RightContext (map formula l) (formula f) (map formula rc) (map formula r), formula c)
debShow (ContextLess l f r,c) = show $ (ContextLess (map formula l) (formula f) (map formula r), formula c)
startState :: S
startState = S (-1) Map.empty
-- |Returns the current state integer and decrease the state by one.
getAndDec :: NonDeterministicState S Int
getAndDec = do
s <- get
i <- return $ counter s
modify (\x -> x{counter = (i-1)})
return i
-- |Takes a sequent of formulae and generates fresh variables for each formula, wrapping it in a non-deterministic state
toDecorated :: Sequent -> NonDeterministicState S DecoratedSequent
toDecorated (gamma,f) = do
aux <- return $ \x -> do
i <- getAndDec
j <- getAndDec
return $ DF i (V j) x
gamma' <- mapM aux gamma
f' <- aux f
return (gamma',f')
-- |Takes a decorated sequent and generates fresh variables for each formula, wrapping it in a non-deterministic state and returning a map from the new variables to the original constant terms
toDecoratedWithConstants :: ([(LambdaTerm,Formula)],Formula) -> NonDeterministicState S (DecoratedSequent,Map Int LambdaTerm)
toDecoratedWithConstants (gamma,f) = do
aux <- return $ \(c,x) -> do
i <- getAndDec
j <- getAndDec
return $ (DF i (V j) x,(i,c))
gamma' <- mapM aux gamma
f' <- do
i <- getAndDec
j <- getAndDec
return $ DF i (V j) f
return ((map fst gamma',f'),Map.fromList $ map snd gamma')
-- |Associates two formulae in the variable-formula binding map in the state
associate :: Formula -> Formula -> NonDeterministicState S ()
associate f g = do
s <- get
m <- return $ vars s
modify (\x -> x{vars = Map.insert f g m})
return ()
-- |Looks up the binding of a formula in the variable-formula binding map of the state
getBinding :: Formula -> NonDeterministicState S (Maybe Formula)
getBinding f = aux f [f] where
aux f vs = do
s <- get
m <- return $ vars s
res <- return $ Map.lookup f m
case res of
Nothing -> return Nothing
Just v@(Var _) -> case Data.List.elem v vs of
False -> aux v (v : vs)
True -> return $ Just f
Just f -> return $ Just f
-- |Tries to unify to formulae: returns 'True' in case of success (and associate the unified formulae) and 'False' otherwise (without changing the state)
unify :: Formula -> Formula -> NonDeterministicState S Bool
unify v1@(Var _) v2@(Var _) =
do
binding1 <- getBinding v1
binding2 <- getBinding v2
case binding1 of
Nothing -> do
associate v1 v2
return True
Just g -> case binding2 of
Nothing -> do
associate v2 v1
return True
Just f -> return $ f == g
unify v@(Var _) f =
do
binding <- getBinding v
case binding of
Nothing -> do
associate v f
return True
Just g -> return $ g == f
unify f v@(Var _) = unify v f
unify f g = return $ f == g
provable :: Sequent -> Bool
provable s = not $ null $ evaluateState m startState where
m = do
ds <- toDecorated s
proofs ds
-- |Returns all the proofs for a given sequent
proofs :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
proofs s@(gamma,f) =
every $ map (\r -> r s) [lIR,rIR,mR,tR] ++
map (\(r,foc) -> r foc) [ (r,(foc,f)) | r <- [i,mL,tL]
, foc <- createAllContextLessFocuses gamma] ++
map (\foc -> lIL foc) [(foc,f) | foc <- createAllLeftContextFocuses gamma] ++
map (\foc -> rIL foc) [(foc,f) | foc <- createAllRightContextFocuses gamma]
-- do
-- every $ map (\r -> r s) [iR,mR,tR] ++ map (\(r,g) -> r g (delete g gamma,f))
-- [(r,g) | r <- [i,iL,mL,tL]
-- , g <- gamma]
-- |The identity rule
i :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
i (f,a') = do
guard $ all null $ getContexts f
a <- return $ getFocus f
res <- unify (formula a) (formula a')
case res of
False -> failure
True -> do
i <- getAndDec
x <- return $ V i
return $ Leaf Id ([DF (identifier a) x (formula a)]
, DF (identifier a') x (formula a'))
-- |The left left-implication rule
-- Y => A X[B] => C
-- -----------------
-- X[(Y,A\B)] => C
lIL :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
lIL (LeftContext bigXLeft bigY f@(DF _ _ (LI a b)) bigXRight,c) = do
a_id <- getAndDec
b_id <- getAndDec
t <- getAndDec >>= \i -> return $ V i
x <- getAndDec >>= \j -> return $ V j
l <- proofs (bigY,DF a_id t a)
r <- proofs (bigXLeft ++ [DF b_id x b] ++ bigXRight,c)
(l,r) <- return $ l `par` (r `pseq` (l,r))
(newBigY,a') <- return $ getVal l
(newBigX, c') <- return $ getVal r
b' <- return $ lookupFormula b_id newBigX
(newBigXLeft,newBigXRight) <- return $ deleteWithRemainders b' newBigX
y <- getAndDec >>= \i -> return $ V i
return $ Branch LImplL l (newBigXLeft ++ newBigY ++ [DF (identifier f) y (LI a b)] ++ newBigXRight ,DF (identifier c') (sub (App y (term a')) (term b') (term c')) (formula c')) r
lIL _ = failure
-- |The left right-implication rule
-- Y => A X[B] => C
-- -----------------
-- X[(B/A,Y)] => C
rIL :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
rIL (RightContext bigXLeft f@(DF _ _ (RI a b)) bigY bigXRight,c) = do
a_id <- getAndDec
b_id <- getAndDec
t <- getAndDec >>= \i -> return $ V i
x <- getAndDec >>= \j -> return $ V j
l <- proofs (bigY,DF a_id t a)
r <- proofs (bigXLeft ++ [DF b_id x b] ++ bigXRight,c)
(l,r) <- return $ l `par` (r `pseq` (l,r))
(newBigY,a') <- return $ getVal l
((newBigX), c') <- return $ getVal r
b' <- return $ lookupFormula b_id newBigX
(newBigXLeft,newBigXRight) <- return $ deleteWithRemainders b' newBigX
y <- getAndDec >>= \i -> return $ V i
return $ Branch RImplL l (newBigXLeft ++ [DF (identifier f) y (RI a b)] ++ newBigY ++ newBigXRight ,DF (identifier c') (sub (App y (term a')) (term b') (term c')) (formula c')) r
rIL _ = failure
-- |The left diamond rule
-- X[A] => <>B
-- ----------------
-- X[<>A] => <> B
mL :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
mL (ContextLess bigXLeft ma@(DF _ y (M t a)) bigXRight, f@(DF j _ (M t' b))) = do
guard (t == t')
id_a <- getAndDec
x <- getAndDec >>= \i -> return $ V i
c <- proofs (bigXLeft ++ [DF id_a x a] ++ bigXRight, f)
(gamma_and_a,mb) <- return $ getVal c
a <- return $ lookupFormula id_a gamma_and_a
(newBigXLeft,newBigXRight) <- return $ deleteWithRemainders a gamma_and_a
return $ Unary (MonL t) (newBigXLeft ++ [ma] ++ newBigXRight, DF j (Bind t y (Lambda (term a) (term mb))) (M t b)) c
mL _ = failure
-- |The left tensor rule
-- X[(A,B)] => C
-- -------------
-- X[A*B] => C
tL :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
tL (ContextLess bigXLeft ab@(DF _ y (P a b)) bigXRight, c) = do
a_id <- getAndDec
b_id <- getAndDec
f <- getAndDec >>= \i -> return $ V i
g <- getAndDec >>= \i -> return $ V i
child <- proofs (bigXLeft ++ [DF a_id f a,DF b_id g b] ++ bigXRight,c)
(gamma_and_a_and_b,c') <- return $ getVal child
a <- return $ lookupFormula a_id gamma_and_a_and_b
b <- return $ lookupFormula b_id gamma_and_a_and_b
(newBigXLeft,tmp) <- return $ deleteWithRemainders a gamma_and_a_and_b
(_,newBigXRight) <- return $ deleteWithRemainders b tmp
return $ Unary TensL (newBigXLeft ++ [ab] ++ newBigXRight,
DF (identifier c)
(sub (FirstProjection y)
(term a)
(sub (SecondProjection y)
(term b)
(term c')))
(formula c)) child
tL _ = failure
-- |The right left-implication rule
-- (A,X) => B
-- ----------
-- X => A\B
lIR :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
lIR (gamma, DF i _ f@(LI a b)) = do
a_id <- getAndDec
b_id <- getAndDec
x <- getAndDec >>= \i -> return $ V i
t <- getAndDec >>= \i -> return $ V i
c <- proofs (DF a_id x a : gamma, DF b_id t b)
(gamma_and_a,b) <- return $ getVal c
a <- return $ lookupFormula a_id gamma_and_a
gamma <- return $ delete a gamma_and_a
return $ Unary LImplR (gamma, DF i (Lambda (term a) (term b)) f) c
lIR _ = failure
-- |The right right-implication rule
-- (X,A) => B
-- ----------
-- X => B/A
rIR :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
rIR (gamma, DF i _ f@(RI a b)) = do
a_id <- getAndDec
b_id <- getAndDec
x <- getAndDec >>= \i -> return $ V i
t <- getAndDec >>= \i -> return $ V i
c <- proofs (gamma ++ [DF a_id x a], DF b_id t b)
(gamma_and_a,b) <- return $ getVal c
a <- return $ lookupFormula a_id gamma_and_a
gamma <- return $ delete a gamma_and_a
return $ Unary RImplR (gamma, DF i (Lambda (term a) (term b)) f) c
rIR _ = failure
-- |The right diamond rule
mR :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
mR (gamma,DF i _ ma@(M t a)) = do
a_id <- getAndDec
x <- getAndDec >>= \i -> return $ V i
c <- proofs (gamma,DF a_id x a)
(gamma,a) <- return $ getVal c
return $ Unary (MonR t) (gamma,DF i (Eta t (term a)) ma) c
mR _ = failure
-- |The right tensor rule
tR :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
tR (gamma,DF i _ f@(P a b)) = do
a_id <- getAndDec
b_id <- getAndDec
t <- getAndDec >>= \i -> return $ V i
u <- getAndDec >>= \i -> return $ V i
splits <- return $ split gamma
proveChildren <- return $ \(g,g') -> do
l <- proofs (g,DF a_id t a)
r <- proofs (g',DF b_id u b)
return (l,r)
(l,r) <- every $ map proveChildren splits
(gamma,a) <- return $ getVal l
(delta,b) <- return $ getVal r
return $ Branch TensR l (gamma ++ delta, DF i (Pair (term a) (term b)) f) r
tR _ = failure
-- |This function searches for a formula in a list of formulae by comparing their unique ids.
-- It's meant to be used only by the left implication and left monad rules.
-- Raises an error if no formula with the given id is found
lookupFormula :: Int -> [DecoratedFormula] -> DecoratedFormula
lookupFormula _ [] = error "This will never be reached by the rules"
lookupFormula n (f : rest) | n == (identifier f) = f
| otherwise = lookupFormula n rest
-- |Substitute a term for another inside a third term (should be the substitution of a variable with a term)
sub :: LambdaTerm -> -- the new term
LambdaTerm -> -- the variable/old term
LambdaTerm -> -- the context
LambdaTerm -- the new term
sub _ _ c@(C _) = c
sub new old t@(V _) | t == old = new
| otherwise = t
sub new old t@(Lambda v b) | v == old = t
| otherwise = Lambda v $ sub new old b
sub new old (App f a) = App (sub new old f) (sub new old a)
sub new old (Eta t f) = Eta t (sub new old f)
sub new old (Bind t m k) = Bind t (sub new old m) (sub new old k)
sub new old (Pair a b) = Pair (sub new old a) (sub new old b)
sub new old (FirstProjection a) = FirstProjection $ sub new old a
sub new old (SecondProjection a) = SecondProjection $ sub new old a
-- |Collects all variables from a proof
collectVars :: BinTree DecoratedSequent -> Set LambdaTerm
collectVars t = Set.fromList $ foldMap aux t where
aux = concat . (map f) . (map term) . j
j (c,f) = f : c
f v@(V _) = [v]
f (C _) = []
f (Lambda v t) = f v ++ f t
f (App g a) = f g ++ f a
f (Eta _ x) = f x
f (Bind _ m k) = f m ++ f k
f (Pair a b) = f a ++ f b
f (FirstProjection a) = f a
f (SecondProjection a) = f a
-- |Changes all the negative indices used in the vars to contiguos positive integers
sanitizeVars :: BinTree DecoratedSequent -> BinTree DecoratedSequent
sanitizeVars t = fmap sanitize t where
sanitize (gamma,f) = (map deepSub gamma,deepSub f)
deepSub (DF i lt f) = DF i (zub lt) f
zub (V i) = V $ fromJust $ lookup i m
zub c@(C _) = c
zub (Lambda x t) = Lambda (zub x) (zub t)
zub (App f g) = App (zub f) (zub g)
zub (Eta t x) = Eta t (zub x)
zub (Bind t m k) = Bind t (zub m) (zub k)
zub (Pair a b) = Pair (zub a) (zub b)
zub (FirstProjection a) = FirstProjection $ zub a
zub (SecondProjection a) = SecondProjection $ zub a
m = zip (map (\(V i) -> i) $ Set.toList $ collectVars t) [0..]
replaceWithConstants :: BinTree DecoratedSequent -> (Map Int LambdaTerm) -> BinTree DecoratedSequent
replaceWithConstants t m = fmap (\n -> replaceWithConstantsInNode n m) t
replaceWithConstantsInNode :: DecoratedSequent -> (Map Int LambdaTerm) -> DecoratedSequent
replaceWithConstantsInNode (gamma,f) m = new where
new = (map fst gamma', deepSub f)
gamma' = map replace gamma
n = map fromJust $ filter isJust $ map snd gamma'
replace df@(DF i v f) = case Map.lookup i m of
Nothing -> (df,Nothing)
Just c -> (DF i c f,Just (v,c))
deepSub (DF i lt f) = (DF i (zub lt) f)
zub v@(V _) = case lookup v n of
Nothing -> v
Just c -> c
zub c@(C _) = c
zub (Lambda x t) = Lambda (zub x) (zub t)
zub (App f g) = App (zub f) (zub g)
zub (Eta t x) = Eta t (zub x)
zub (Bind t m k) = Bind t (zub m) (zub k)
zub (Pair a b) = Pair (zub a) (zub b)
zub (FirstProjection a) = FirstProjection $ zub a
zub (SecondProjection a) = SecondProjection $ zub a
alphaEquivalent :: LambdaTerm -> LambdaTerm -> Map Int Int -> Bool
alphaEquivalent c1@(C _) c2@(C _) _ = c1 == c2
alphaEquivalent (V i) (V j) m = case Map.lookup i m of
Just h -> j == h
Nothing -> i == j
alphaEquivalent (Lambda (V i) t) (Lambda (V j) u) m = alphaEquivalent t u (Map.insert i j m)
alphaEquivalent (App t s) (App d z) m = (alphaEquivalent t d m) && (alphaEquivalent s z m)
alphaEquivalent (Eta t x) (Eta t' y) m = t == t' && alphaEquivalent x y m
alphaEquivalent (Bind t x y) (Bind t' w z) m = t == t' && (alphaEquivalent x w m) && (alphaEquivalent y z m)
alphaEquivalent (Pair a b) (Pair a' b') m = alphaEquivalent a a' m && alphaEquivalent b b' m
alphaEquivalent (FirstProjection a) (FirstProjection b) m = alphaEquivalent a b m
alphaEquivalent (SecondProjection a) (SecondProjection b) m = alphaEquivalent a b m
alphaEquivalent _ _ _ = False
-- |This function works only under the assumption that all the formulae in the hypothesis are distinct, otherwise the answer is NO!
equivalentDecoratedSequent :: DecoratedSequent -> DecoratedSequent -> Bool
equivalentDecoratedSequent s1 s2 = f1 == f2 && hypEqual && noDuplicates && alphaEquivalent t1 t2 e where
noDuplicates = (length $ Set.toList $ Set.fromList (map formula hyp1)) == length hyp1 &&
(length $ Set.toList $ Set.fromList (map formula hyp2)) == length hyp2
hyp1 = fst s1
hyp2 = fst s2
hypEqual = (Set.fromList (map formula hyp1)) == (Set.fromList (map formula hyp2))
varId (V i) = i
varId _ = -1
m1 = Map.fromList $ map (\x -> (formula x, varId $ term x)) hyp1
m2 = Map.fromList $ map (\x -> (formula x, varId $ term x)) hyp2
e = mixMaps m1 m2
t1 = betaReduce $ monadReduce $ etaReduce $ term $ snd $ s1
t2 = betaReduce $ monadReduce $ etaReduce $ term $ snd $ s2
f1 = formula $ snd $ s1
f2 = formula $ snd $ s2
simplifiedEquivalentDecoratedSequent s1 s2 = alphaEquivalent t1 t2 e where
hyp1 = fst s1
hyp2 = fst s2
varId (V i) = i
varId _ = -1
m1 = Map.fromList $ map (\x -> (formula x, varId $ term x)) hyp1
m2 = Map.fromList $ map (\x -> (formula x, varId $ term x)) hyp2
e = mixMaps m1 m2
t1 = betaReduce $ monadReduce $ etaReduce $ term $ snd $ s1
t2 = betaReduce $ monadReduce $ etaReduce $ term $ snd $ s2
mixMaps :: Map Formula Int -> Map Formula Int -> Map Int Int
mixMaps m n = Map.fromList $ aux (Map.toList m) where
aux [] = []
aux ((f,i) : rest) = (i,n Map.! f) : aux rest
etaReduce :: LambdaTerm -> LambdaTerm
etaReduce c@(C _) = c
etaReduce v@(V _) = v
etaReduce (App f g) = App (etaReduce f) (etaReduce g)
etaReduce (Eta t m) = Eta t $ etaReduce m
etaReduce (Bind t m k) = Bind t (etaReduce m) (etaReduce k)
etaReduce (Pair a b) = Pair (etaReduce a) (etaReduce b)
etaReduce (FirstProjection a) = FirstProjection $ etaReduce a
etaReduce (SecondProjection a) = SecondProjection $ etaReduce a
etaReduce (Lambda (V i) (App f (V j))) | i == j = etaReduce f
| otherwise = Lambda (V i) (App (etaReduce f) (V j))
etaReduce (Lambda x t) = let x' = etaReduce x
t' = etaReduce t
in if t == t' then
Lambda x' t'
else
etaReduce (Lambda x' t')
betaReduce :: LambdaTerm -> LambdaTerm
betaReduce t = aux t Map.empty where
aux c@(C _) _ = c
aux v@(V i) m = case Map.lookup i m of
Nothing -> v
Just t -> t
aux (App (Lambda (V i) body) x) m = aux body (Map.insert i x m)
aux (App f x) m = let f' = aux f m
in if f == f' then
(App f (aux x m))
else
aux (App f' x) m
aux (Lambda x b) m = Lambda (aux x m) (aux b m)
aux (Eta t x) m = Eta t $ aux x m
aux (Bind t n k) m = Bind t (aux n m) (aux k m)
aux (Pair a b) m = Pair (aux a m) (aux b m)
aux (FirstProjection a) m = FirstProjection $ aux a m
aux (SecondProjection a) m = SecondProjection $ aux a m
monadReduce :: LambdaTerm -> LambdaTerm
monadReduce (Bind _ (Eta _ t) u) = App (monadReduce u) (monadReduce t) -- here there should be a check on types...
monadReduce (Bind ty t (Lambda (V i) (Eta ty' (V j)))) | i == j = monadReduce t
| otherwise = Bind ty (monadReduce t) (Lambda (V i) (Eta ty' (V j)))
monadReduce v@(V _) = v
monadReduce c@(C _) = c
monadReduce (App t u) = App (monadReduce t) (monadReduce u)
monadReduce (Lambda x t) = Lambda (monadReduce x) (monadReduce t)
monadReduce (Eta t x) = Eta t $ monadReduce x
monadReduce (Pair a b) = Pair (monadReduce a) (monadReduce b)
monadReduce (FirstProjection a) = FirstProjection $ monadReduce a
monadReduce (SecondProjection a) = SecondProjection $ monadReduce a
monadReduce (Bind ty t u) = let t' = monadReduce t
u' = monadReduce u
in if t == t' && u == u' then
Bind ty t' u'
else
monadReduce (Bind ty t' u')
|
gianlucagiorgolo/lambek-monad
|
TP.hs
|
Haskell
|
mit
| 19,668
|
module Main where
import Text.ParserCombinators.UU
import Text.ParserCombinators.UU.Utils
import Text.ParserCombinators.UU.BasicInstances hiding (Parser, input)
import System.Console.Haskeline
import System.Environment (getArgs)
type Parser a = P (Str Char String LineColPos) a
main :: IO ()
main = do
args <- getArgs
if null args then interactive
else putStrLn $ run timeExpr (unwords args)
interactive :: IO ()
interactive = runInputT defaultSettings loop
where
loop :: InputT IO ()
loop = do minput <- getInputLine "> "
case minput of
Nothing -> return ()
Just "quit" -> return ()
Just input -> do outputStrLn $ run timeExpr input
loop
run :: Parser String -> String -> String
run p inp = do let (a, errors) = parse ( (,) <$> p <*> pEnd) (createStr (LineColPos 0 0 0) inp)
if null errors then a
else "Error in expression"
timeExpr :: Parser String
timeExpr = format <$> expr
where format :: Double -> String
format x = let minutes :: Integer
seconds :: Integer
(minutes,secondsMultiplier) = properFraction x
seconds = round $ secondsMultiplier * 60
showSeconds s | s < 10 = "0" ++ show s
| otherwise = show s
in show minutes ++ ":" ++ showSeconds seconds
expr :: Parser Double
expr = foldr pChainl ( pDouble <|> pTime <|>pParens expr) (map same_prio operators)
where
operators = [[('+', (+)), ('-', (-))], [('*' , (*))], [('/' , (/))]]
same_prio ops = foldr (<|>) empty [ op <$ lexeme (pSym c) | (c, op) <- ops]
pTime :: Parser Double
pTime = lexeme pRawMinuteTime <|> lexeme pRawHourTime
pRawMinuteTime :: Parser Double
pRawMinuteTime = makeTime <$> pIntegerRaw <* pSym ':' <*> pIntegerRaw <?> "min:sec"
where makeTime x y = x + (y / 60.0)
pRawHourTime :: Parser Double
pRawHourTime = makeTime <$> pIntegerRaw <* pSym ':' <*> pIntegerRaw <* pSym ':' <*> pIntegerRaw <?> "hour:min:sec"
where makeTime x y z = x * 60 + y + z / 60.0
|
chriseidhof/TimeCalc
|
TimeCalc.hs
|
Haskell
|
mit
| 2,186
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Defines what each type of server does upon receiving each type of message.
-- Thus, the consensus protocol is largely defined here.
-- Note that each message receipt will be in an atomic transaction.
module Hetcons.Receive () where
import Hetcons.Conflicting_2as ( conflicting_2as )
import Hetcons.Hetcons_Exception (Hetcons_Exception(Hetcons_Exception_Invalid_Proposal_1a))
import Hetcons.Hetcons_State
( Participant_State, Observer_State, Hetcons_State )
import Hetcons.Instances_1b_2a ( well_formed_2a )
import Hetcons.Instances_Proof_of_Consensus ( observers_proven )
import Hetcons.Receive_Message
( Sendable(send)
,Receivable
,receive
,Hetcons_Transaction
,update_state
,put_state
,get_state
,get_my_private_key
,get_my_crypto_id
,get_witness)
import Hetcons.Send ()
import Hetcons.Signed_Message
( Encodable
,Parsable
,Recursive_2a(Recursive_2a)
,Recursive_1b(Recursive_1b)
,recursive_1b_non_recursive
,recursive_1b_proposal
,recursive_1b_conflicting_phase2as
,Verified
,Recursive_1a
,Recursive_2b(Recursive_2b)
,Recursive(non_recursive)
,Recursive_Proof_of_Consensus(Recursive_Proof_of_Consensus)
,Monad_Verify(verify)
,signed
,sign
,original )
import Hetcons.Value
( Contains_Value(extract_value)
,Contains_1a(extract_1a)
,Contains_1bs(extract_1bs)
,extract_ballot
,Value
,valid
,conflicts
)
import Charlotte_Consts ( sUPPORTED_SIGNED_HASH_TYPE_DESCRIPTOR )
import Charlotte_Types
( Signed_Message(signed_Message_signature)
,Phase_2a(phase_2a_phase_1bs)
,Signed_Hash(signed_Hash_crypto_id)
,Phase_1b(phase_1b_conflicting_phase2as, phase_1b_proposal)
,Phase_2b(phase_2b_phase_1bs)
,Proof_of_Consensus(proof_of_Consensus_phase_2bs)
,default_Proof_of_Consensus
,default_Phase_2b
,default_Phase_1b
,default_Invalid_Proposal_1a
,invalid_Proposal_1a_offending_witness
,invalid_Proposal_1a_offending_proposal
,invalid_Proposal_1a_explanation)
import Control.Monad ( mapM, mapM_ )
import Control.Monad.Except ( MonadError(throwError) )
import Crypto.Random ( drgNew )
import Data.Foldable ( maximum )
import Data.Hashable (Hashable)
import Data.HashSet ( HashSet, toList, member, insert, fromList, size )
import qualified Data.HashSet as HashSet ( map, filter, empty )
-- | Helper function which signs a message using the Crypto_ID and Private_Key provided by the Mondic environment.
sign_m :: (Value v, Encodable a, Hetcons_State s) => a -> Hetcons_Transaction s v Signed_Message
sign_m m = do
{ crypto_id <- get_my_crypto_id
; private_key <- get_my_private_key
; gen <- drgNew
; sign crypto_id private_key sUPPORTED_SIGNED_HASH_TYPE_DESCRIPTOR gen m}
--------------------------------------------------------------------------------
-- Participants --
--------------------------------------------------------------------------------
-- | Participant receives 1A
-- If we've seen anything with this Ballot number or higher before (featuring the same Quorums), then do nothing.
-- Otherwise, send a 1B.
instance (Value v, Eq v, Hashable v, Parsable (Hetcons_Transaction (Participant_State v) v v)) => Receivable (Participant_State v) v (Verified (Recursive_1a v)) where
receive r1a = do
{ let naive_1b = default_Phase_1b {phase_1b_proposal = signed r1a}
; let naive_r1b = Recursive_1b {recursive_1b_non_recursive = naive_1b
,recursive_1b_proposal = r1a
,recursive_1b_conflicting_phase2as = HashSet.empty}
; state <- get_state
-- TODO: non-pairwise conflicts
; let conflicting_ballots = HashSet.map extract_ballot $ HashSet.filter (conflicts . fromList . (:[naive_r1b]) . original ) state
-- If we've seen this 1a before, or we've seen one with a greater ballot that conflicts
; if ((member naive_r1b $ HashSet.map original state) || ((not (null conflicting_ballots)) && ((extract_ballot r1a) <= (maximum conflicting_ballots))))
then return ()
else do { witness <- get_witness
; validity_check <- valid witness r1a
; if validity_check -- Checking validity here may seem odd, since we receive values inside other stuff, like 1bs.
then return () -- However, the first time we receive a value, we always must end up here.
else throwError $ Hetcons_Exception_Invalid_Proposal_1a default_Invalid_Proposal_1a {
invalid_Proposal_1a_offending_proposal = non_recursive $ original r1a
,invalid_Proposal_1a_offending_witness = Just witness
,invalid_Proposal_1a_explanation = Just "This value is not itself considered valid."}
; conflicting <- mapM sign_m $ toList $ conflicting_2as state r1a
; send (naive_1b {phase_1b_conflicting_phase2as = fromList conflicting})}}
-- | Participant receives 1B
-- If we've received this 1B before, or one that conflicts but has a higher ballot number, do nothing.
-- Otherwise, we try to assemble a 2A out of all the 1Bs we've received for this ballot, and if we have enough (if that 2A is valid), we send it.
instance forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Participant_State v) v v)) =>
Receivable (Participant_State v) v (Verified (Recursive_1b v)) where
receive r1b = do
{ old_state <- get_state
-- TODO: non-pairwise conflicts
; let conflicting_ballots = HashSet.map extract_ballot $ HashSet.filter (conflicts . fromList . (:[r1b])) old_state
; if ((member r1b old_state) || -- If we've received this 1b before, or received something of greater ballot number (below)
((not (null conflicting_ballots)) &&
((extract_ballot r1b) < (maximum conflicting_ballots))))
then return ()
else do { my_crypto_id <- get_my_crypto_id
; if (Just my_crypto_id) == (signed_Hash_crypto_id $ signed_Message_signature $ signed r1b) -- if this 1b is from me
then return ()
else receive ((extract_1a r1b) :: Verified (Recursive_1a v)) -- ensure we've received the 1a for this message before we store any 1bs
; mapM_ receive ((extract_1bs $ original r1b) :: (HashSet (Verified (Recursive_1b v)))) -- receive all prior 1bs contained herein
; state <- update_state (\s -> let new_state = insert r1b s in (new_state, new_state))
; let potential_2a = Recursive_2a $
HashSet.filter ((((extract_1a r1b) :: Verified (Recursive_1a v)) ==) . extract_1a) $ -- all the 1bs with the same proposal
HashSet.filter ((((extract_value r1b) :: v) ==) . extract_value) state
; case well_formed_2a potential_2a of
(Right _)-> do { signed <- sign_m $ ((non_recursive potential_2a) :: Phase_2a)
; (v :: (Verified (Recursive_2a v))) <- verify signed
; send v}
(Left _) -> return ()
; send r1b}} -- echo the 1b
-- | Participant receives 2A
-- Upon receiving a 2A, send a corresponding 2B.
-- Note that the only way for a participant to receive a 2A is for that participant to itself send it.
-- It can't come in over the wire.
instance (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Participant_State v) v v)) => Receivable (Participant_State v) v (Verified (Recursive_2a v)) where
-- | Recall that there is no actual way to receive a 2a other than sending it to yourself.
-- Therefore, we can be assured that this 2a comes to us exactly once, and that all 1bs therein have been received.
receive r2a = send $ default_Phase_2b {phase_2b_phase_1bs = phase_2a_phase_1bs $ non_recursive $ original r2a}
--------------------------------------------------------------------------------
-- Observers --
--------------------------------------------------------------------------------
-- | Observer receives 2B
-- If we've received this 2b before, do nothing.
-- Otherwise, assemble all received 2Bs with the same proposal and value, and see if those form a valid Proof_of_Consensus
-- If they do, send that Proof_of_Consensus
instance forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Observer_State v) v v)) => Receivable (Observer_State v) v (Verified (Recursive_2b v)) where
receive r2b = do
{ old_state <- get_state
; if (member r2b old_state)
then return () -- Else, we make a Proof_of_Consensus using what we've received, and see if that's valid.
else do { let state = insert r2b old_state
; put_state state
; let potential_proof' =
HashSet.filter ((((extract_1a r2b) :: Verified (Recursive_1a v)) ==) . extract_1a) $ -- all the 2bs with the same proposal
HashSet.filter ((((extract_value r2b) :: v) ==) . extract_value) state -- all the 2bs with the same value
-- filter for only the longest 2bs from each sender
; let potential_proof = HashSet.filter(\v2b->let same_crypto_id = HashSet.filter (((signed_Hash_crypto_id $ signed_Message_signature $ signed v2b) ==) .
signed_Hash_crypto_id . signed_Message_signature . signed)
potential_proof'
in all (\x -> let (Recursive_2b y) = original x
(Recursive_2b r) = original v2b
in (size y) <= (size r))
same_crypto_id)
potential_proof'
; if (length (observers_proven potential_proof)) > 0
then do { signed <- sign_m (default_Proof_of_Consensus { proof_of_Consensus_phase_2bs = HashSet.map signed potential_proof})
; (v :: (Verified (Recursive_Proof_of_Consensus v))) <- verify signed
; send v}
else return ()
; send r2b}}
-- | Observer receives Proof_of_Consensus
-- Note that this can only be received if this Observer sends it to itself.
-- It cannot come in over the wire.
-- TODO: what do we do here? We have consensus (at least for some observers).
instance (Value v) => Receivable (Observer_State v) v (Verified (Recursive_Proof_of_Consensus v)) where
receive rpoc = return ()
|
isheff/hetcons
|
src/Hetcons/Receive.hs
|
Haskell
|
mit
| 11,350
|
{-****************************************************************************
* Hamster Balls *
* Purpose: Rendering code for terrains in the game *
* Author: David, Harley, Alex, Matt *
* Copyright (c) Yale University, 2010 *
****************************************************************************-}
module Terrain where
import Vec3d
import Graphics.Rendering.OpenGL hiding (Texture)
import GHC.Float
import BoundingVolume
import Data.Maybe
import Render
{---------------------------------------------------------------------------------------------------------------
TO DO:
Add orientation and scale to definition of TerrainElement
Existential types for the bounding boxes
Apply transformations to bounding boxes
Restore colors (do not need this, for now)
Only allow compound terrains to have associated transforms
This ways is much cleaner, but either way should be fine.
MAYBE:
Generate commands instead of executing them (easier for textures). Then, in
renderTerrainElement, just generate commands and execute them.
---------------------------------------------------------------------------------------------------------------}
data Col = Col{cspecular :: Color4 GLfloat,
cdiffuse :: Color4 GLfloat,
cambient :: Color4 GLfloat,
cemissive :: Color4 GLfloat,
cshininess :: GLfloat}
deriving Show
data Transform = Transform{toffset :: Vec3d,
tscale :: Vec3d, -- Also let orientation be set
ttheta :: Float,
tphi :: Float}
deriving Show
data Surface = Color Col
| Texture TextureObject -- Has how to render as well
| Mirror -- Mirror and Transparent are essentially the same (get the framebuffer?)
| Transparent
| NoSurface
deriving Show
{-
-- Hmm lazy way: orphan instance
instance Show QuadricPrimitive where
show _ = "QuadricPrimitive"
instance Show QuadricStyle where
show _ = "QuadricStyle"
-}
-- Maybe not best form (only CompoundTerrain should have transform). But saves lots of work
data Geometry = GLUQuadric QuadricPrimitive QuadricStyle Transform
| Cube Height Transform
| Quad Vec3d Vec3d Vec3d Vec3d Transform
| Tri Vec3d Vec3d Vec3d Transform
| Plane -- For later
| Trimesh -- For later
-- deriving Show
data TerrainElement = SimpleTerrain Geometry Surface -- Is Flavour part of TerrainElement or of Geometry?
| CompoundTerrain Transform [TerrainElement]
-- deriving Show
instance Show TerrainElement where
show _ = "TerrainElement"
-- Restore surface color properties
restoreSurfaceColor :: IO()
restoreSurfaceColor = do
materialDiffuse FrontAndBack $= Color4 0.0 0.0 0.0 1.0 -- For now, always FrontAndBack
materialSpecular FrontAndBack $= Color4 0.0 0.0 0.0 1.0
materialAmbient FrontAndBack $= Color4 0.0 0.0 0.0 1.0
materialEmission FrontAndBack $= Color4 0.0 0.0 0.0 1.0
-- Execute commands while preserving surface characteristics
-- Still have issues for texturing
preservingSurface :: Surface -> IO() -> IO()
preservingSurface (Terrain.Color (Col{cspecular=spec, cdiffuse=diff, cambient=amb,cemissive=emis,cshininess=shin})) commands = do
-- clear [ColorBuffer]
{-
let curDiff = materialDiffuse FrontAndBack
curSpec = materialSpecular FrontAndBack
curAmb = materialAmbient FrontAndBack
curEmis = materialEmission FrontAndBack
-}
-- Store colors
materialDiffuse FrontAndBack $= diff -- For now, always FrontAndBack
materialSpecular FrontAndBack $= spec
materialAmbient FrontAndBack $= amb
materialEmission FrontAndBack $= emis
-- materialShininess FrontAndBack $= shin
commands -- Execute commands
restoreSurfaceColor
-- flush
-- clearColor $= Color4 0.0 0.0 0.0 0.0 -- Reset colors (not working right now)
preservingSurface (Terrain.Texture tex) commands = do
-- materialDiffuse FrontAndBack $= Color4 0.4 0.5 0.6 1
texture Texture2D $= Enabled
textureFunction $= Decal
textureBinding Texture2D $= Just tex
commands
texture Texture2D $= Disabled
-- return ()
preservingSurface NoSurface commands = do
commands
preservingSurface _ commands = do
print "Surface functionality not yet implemented"
commands
{-
preservingSurface (Terrain.Texture tex) commands = do
-- materialDiffuse FrontAndBack $= Color4 0.4 0.5 0.6 1
texture Texture2D $= Enabled
textureFunction $= Decal
textureBinding Texture2D $= Just tex
commands
texture Texture2D $= Disabled
-- return ()
-- Then
renderTerrainElement (SimpleTerrain (Quad p1 p2 p3 p4 transform) (Texture texObj) flav) = do
-- print "Rendering quad with texture"
loadIdentity
preservingMatrix $ do
preservingSurface (Texture texObj) $ do
--loadIdentity
applyTransform transform
displaySprite3D (Just texObj) (vertex3 p1) (vertex3 p2) (vertex3 p3) (vertex3 p4) (0,0) (1,1)
-- renderQuad (Just texObj) (vertex3 p1) (vertex3 p2) (vertex3 p3) (vertex3 p4)
-}
applyTransform :: Transform -> IO()
applyTransform Transform{toffset=offset, tscale=Vec3d(sx,sy,sz), ttheta = thetaAngle, tphi = phiAngle} = do
translate $ vector3 offset
Graphics.Rendering.OpenGL.scale sx sy sz
rotate thetaAngle $ vector3 (Vec3d(0.0, 0.0, 1.0))
rotate phiAngle $ vector3 (Vec3d(1.0, 0.0, 0.0))
applyTransform2 :: Transform -> Vec3d -> Vec3d
applyTransform2 Transform{toffset=Vec3d(dx,dy,dz), tscale=Vec3d(sx,sy,sz), ttheta = thetaAngle, tphi = phiAngle} (Vec3d (x,y,z)) =
Vec3d (sx*x + dx, sy*y + dy, sz*z + dz) -- Bounding boxes are axis aligned... but still may need to make slightly larger
renderTerrainElement :: TerrainElement -> IO()
renderTerrainElement t@(SimpleTerrain (GLUQuadric qprimitive qstyle transform) surf) = do
-- print "Rendering GLUQuadric"
preservingMatrix $ do
preservingSurface surf $ do
applyTransform transform
renderQuadric qstyle qprimitive
-- renderBoundingVolume $ getTerrainBounds t
renderTerrainElement (SimpleTerrain (Cube height transform) (Texture texObj)) = do
-- print "Rendering glutobject with texture"
-- loadIdentity
preservingMatrix $ do
preservingSurface (Texture texObj) $ do
-- loadIdentity
let h2 = (float height)/2
p1 = Vertex3 (h2) (h2) (h2)
p2 = Vertex3 (h2) (h2) (-h2)
p3 = Vertex3 (h2) (-h2) (-h2)
p4 = Vertex3 (h2) (-h2) (h2)
p5 = Vertex3 (-h2) (h2) (h2)
p6 = Vertex3 (-h2) (h2) (-h2)
p7 = Vertex3 (-h2) (-h2) (-h2)
p8 = Vertex3 (-h2) (-h2) (h2)
applyTransform transform
renderQuad (Just texObj) p1 p2 p3 p4
renderQuad (Just texObj) p1 p5 p8 p4
renderQuad (Just texObj) p5 p6 p7 p8
renderQuad (Just texObj) p6 p7 p3 p2
renderQuad (Just texObj) p1 p2 p6 p5
renderQuad (Just texObj) p3 p4 p8 p7
--handle texture
renderTerrainElement (SimpleTerrain (Quad p1 p2 p3 p4 transform) (Texture texObj)) = do
-- print "Rendering quad with texture"
-- loadIdentity
preservingMatrix $ do
preservingSurface (Texture texObj) $ do
--loadIdentity
applyTransform transform
renderQuad (Just texObj) (vertex3 p1) (vertex3 p2) (vertex3 p3) (vertex3 p4)
renderTerrainElement (SimpleTerrain (Quad p1 p2 p3 p4 transform) surf) = do
-- print "Rendering quad"
-- loadIdentity
preservingMatrix $ do
preservingSurface surf $ do
-- loadIdentity
applyTransform transform
renderPrimitive Quads $ do
clear [ColorBuffer]
-- color $ (Color3 (1.0::GLfloat) 0 0)
-- materialDiffuse FrontAndBack $= Color4 1.0 0.0 0.0 1.0
-- materialEmission FrontAndBack $= Color4 1.0 0.0 0.0 1.0
vertex $ vertex3 p1
vertex $ vertex3 p2
vertex $ vertex3 p3
vertex $ vertex3 p4
renderTerrainElement (SimpleTerrain (Tri p1 p2 p3 transform) surf) = do
-- print "Rendering quad"
-- loadIdentity
preservingMatrix $ do
preservingSurface surf $ do
-- loadIdentity
blend $= Enabled
blendFunc $= (SrcAlpha, OneMinusSrcAlpha)
applyTransform transform
renderPrimitive Triangles $ do
clear [ColorBuffer]
-- color $ (Color3 (1.0::GLfloat) 0 0)
-- materialDiffuse FrontAndBack $= Color4 1.0 0.0 0.0 1.0
-- materialEmission FrontAndBack $= Color4 1.0 0.0 0.0 1.0
vertex $ vertex3 p1
vertex $ vertex3 p2
vertex $ vertex3 p3
renderTerrainElement (SimpleTerrain (Trimesh) _) = do
print "Rendering trimesh terrain"
renderTerrainElement (CompoundTerrain transform telements) = do
-- print "Rendering compound terrain"
-- loadIdentity
preservingMatrix $ do
applyTransform transform
foldr (>>) (return ()) $ map renderTerrainElement telements
renderTerrainElement _ = error "Undefined terrain element"
-- Need to consider transforms
getTerrainBounds :: TerrainElement -> BoundingVolume
getTerrainBounds (SimpleTerrain (Cube height trans) _) =
BoundingBox (applyTransform2 trans (Vec3d (-h2,-h2,-h2))) (applyTransform2 trans (Vec3d (h2,h2,h2)))
where h2 = float height/2
getTerrainBounds (SimpleTerrain (GLUQuadric (Cylinder innerRad outerRad height _ _) _ trans) _) =
BoundingBox (applyTransform2 trans (Vec3d (-maxR,-maxR,0.0))) (applyTransform2 trans (Vec3d (maxR,maxR,h)))
where h = float height
maxR = max (float outerRad) (float innerRad)
{-
getTerrainBounds (SimpleTerrain (GLUTObject (Sphere' radius _ _) Transform{toffset=position}) _ _) =
BoundingEmpty
getTerrainBounds (SimpleTerrain (GLUTObject _ Transform{toffset=position}) _ _) = -- Other GLUT objects. Implement later
BoundingEmpty
-}
getTerrainBounds (CompoundTerrain trans telements) =
MultipleVolumes $ map (bvTransform (applyTransform2 trans) . getTerrainBounds) telements
getTerrainBounds (SimpleTerrain (Quad p1 p2 p3 p4 trans) _) =
BoundingBox (Vec3d (minx,miny,minz)) (Vec3d (maxx,maxy,maxz))
where ps = map (applyTransform2 trans) [p1,p2,p3,p4]
minx = minimum $ map getx ps
miny = minimum $ map gety ps
minz = minimum $ map getz ps
maxx = maximum $ map getx ps
maxy = maximum $ map gety ps
maxz = maximum $ map getz ps
getTerrainBounds _ = BoundingEmpty
{-
processSurface :: Surface -> IO()
processSurface (Terrain.Color (Col{cspecular=spec, cdiffuse=diff, cambient=amb,cemissive=emis,cshininess=shin})) = do
clearColor $= Color4 0.0 0.0 0.0 0.0
materialDiffuse FrontAndBack $= diff -- For now, always FrontAndBack
processSurface (Terrain.Texture) = do
print "Processing texture"
processSurface _ = do
print "Surface functionality not yet implemented"
materialDiffuse FrontAndBack $= Color4 1.0 1.0 1.0 1.0 -- Default to white
-}
{-
preservingTransform :: Transform -> IO() -> IO()
preservingTransform Transform{toffset=offset, tscale=Vec3d(sx,sy,sz), ttheta = thetaAngle, tphi = phiAngle} commands = do
translate $ vector3 offset
Graphics.Rendering.OpenGL.scale sx sy sz
preservingMatrix $ do
Graphics.Rendering.OpenGL.scale sx sy sz
translate $ vector3 offset
rotate thetaAngle $ vector3 (Vec3d(0.0, 0.0, 1.0))
rotate phiAngle $ vector3 (Vec3d(1.0, 0.0, 0.0))
commands
-}
-- For debugging purposes
{-
tempTex = (Texture (fromJust $ unsafePerformIO (getAndCreateTexture "bricks")))
renderBoundingVolume (BoundingBox v1 v2) = do
renderTerrainElement (SimpleTerrain (Cube 1.0 transform) tempTex)
print "Coordinates are:"
print v1
print v2
where height = (getz v2) ^-^ (getz v1)
transform = Transform{toffset=Vec3d(0.0,0.0,height/2),tscale=(v2 ^-^ v1), ttheta=0.0,tphi=0.0}
-}
|
harley/hamball
|
src/Terrain.hs
|
Haskell
|
mit
| 11,981
|
{-
- Module to parse Lisp
-
-
- Copyright 2013 -- name removed for blind review, all rights reserved! Please push a git request to receive author's name! --
- 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.
-}
{-# OPTIONS_GHC -Wall #-}
module LispParser (pGetLisp,parse,LispTree(..),LispPrimitive(..),SourcePos) where
import Text.ParserCombinators.Parsec (getPosition,SourcePos,parse,space,spaces,many,string,(<|>),Parser,noneOf,anyChar,unexpected,oneOf,digit,(<?>),eof)
import Data.Char (toUpper)
data LispTree = LispCons SourcePos LispTree LispTree | LispTreePrimitive SourcePos LispPrimitive deriving (Show)
data LispPrimitive = LispInt Int | LispString String | LispSymbol String deriving (Eq,Show)
pGetLisp :: Parser [LispTree]
pGetLisp
= do spaces
e<-many lispTree
_<-eof
return (e)
where
lispTree :: Parser LispTree
lispTree
= do { pos<-getPosition ;
do{_<-string "(";spaces;lts<-innerLispTree pos;_<-string ")";spaces;return lts} <|>
do{_<-string "'";spaces;lt<-lispTree;spaces;return$ LispCons pos (LispTreePrimitive pos$ LispSymbol "QUOTE") (LispCons pos lt $ LispTreePrimitive pos $ LispSymbol "NIL")} <|>
do{p<-lispPrimitive;spaces;return$ LispTreePrimitive pos p} <?> "LISP expression"
}
innerLispTree pos = do{_<-string ".";_<-space <?> "space. Symbols starting with . should be enclosed in ||'s";spaces;lt<-lispTree;spaces;return lt}
<|> do{lt <- lispTree;spaces;rt<-innerLispTree pos;spaces;return$ LispCons pos lt rt} <|> (return$ LispTreePrimitive pos$LispSymbol "NIL")
lispPrimitive :: Parser LispPrimitive
lispPrimitive
= do{_<-string "\""; str<-lp "\""; return$ LispString str} <|>
-- note: we are a bit stricter on digits: any symbol starting with a digit, should be an integer
do{d<-digit; s<-many digit; return (LispInt (read$ d:s))} <|>
-- we also fail on any of these:
do{_<-oneOf "-;#\\.`"; unexpected "character. Symbols starting with . - ; \\ ` or # should be enclosed in ||'s"} <|>
do{s<-symb; return$LispSymbol s}
where lp s = do{_<-string s; return ""} <|> do{_<-string "\\"; c<-anyChar; r<-lp s; return (c:r)} <|> do{c<-anyChar; r<-lp s; return (c:r)} <?> "end of "++s++"-delimited string"
symb :: Parser String
symb = do{_<-string "|"; p<-lp "|"; r<-symb <|> (return ""); return$ p++r} <|>
do{c<-noneOf " \t\r\n()|;#"; r<-symb <|> (return ""); return$ (toUpper c):r}
|
DatePaper616/code
|
lispParser.hs
|
Haskell
|
apache-2.0
| 3,029
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
module Lycopene.Web.Api where
import Servant
import Lycopene.Application (AppEngine)
import Lycopene.Web.Trans (lyco)
import Lycopene.Web.Request
import qualified Lycopene.Core as Core
type LycopeneApi
= "ping" :> Get '[JSON] String
:<|> "projects" :> ProjectApi
:<|> Raw
type ProjectApi
= Get '[JSON] [Core.Project]
:<|> Capture "name" Core.Name :> Get '[JSON] Core.Project
:<|> ReqBody '[JSON] String :> Post '[JSON] Core.Project
:<|> Capture "name" Core.Name :> DeleteNoContent '[JSON] NoContent
:<|> Capture "name" Core.Name :> "sprints" :> SprintApi
type SprintApi
= Get '[JSON] [Core.Sprint]
:<|> Capture "name" Core.Name :> Get '[JSON] Core.Sprint
:<|> Capture "name" Core.Name :> "issues" :> IssueApi
type IssueApi
= QueryParam "status" Core.IssueStatus :> Get '[JSON] [Core.Issue]
:<|> Capture "id" Core.IssueId :> Get '[JSON] Core.Issue
:<|> ReqBody '[JSON] String :> Post '[JSON] Core.Issue
:<|> Capture "id" Core.IssueId :> DeleteNoContent '[JSON] NoContent
api :: Proxy LycopeneApi
api = Proxy
server :: FilePath -> AppEngine -> Server LycopeneApi
server dir engine
= ping
:<|> projectServer engine
:<|> serveDirectory dir
where
ping = return "pong"
projectServer :: AppEngine -> Server ProjectApi
projectServer engine
= allProjects
:<|> fetchByName
:<|> newProject
:<|> removeProject
:<|> sprintHandler
where
allProjects = lyco engine $ Core.AllProject
fetchByName n = lyco engine $ (Core.FetchProject n)
newProject n = lyco engine $ Core.NewProject n Nothing
removeProject n = NoContent <$ (lyco engine $ Core.RemoveProject n)
sprintHandler pj = sprintServer pj engine
sprintServer :: Core.Name -> AppEngine -> Server SprintApi
sprintServer pj engine
= fetchSprints
:<|> fetchSprint
:<|> issueHandler
where
fetchSprints = lyco engine $ (Core.FetchProjectSprint pj)
fetchSprint sp = lyco engine $ (Core.FetchSprint pj sp)
issueHandler sp = issueServer pj sp engine
issueServer :: Core.Name -> Core.Name -> AppEngine -> Server IssueApi
issueServer pj sp engine
= fetchIssues
:<|> fetchIssue
:<|> newIssue
:<|> removeIssue
where
fetchIssues (Just st) = lyco engine $ (Core.FetchIssues pj sp st)
fetchIssues Nothing = lyco engine $ (Core.FetchIssues pj sp Core.IssueOpen)
newIssue t = lyco engine $ Core.NewIssue pj sp t
fetchIssue issueId = lyco engine $ Core.FetchIssue issueId
removeIssue issueId = NoContent <$ (lyco engine $ Core.RemoveIssue issueId)
|
utky/lycopene
|
src/Lycopene/Web/Api.hs
|
Haskell
|
apache-2.0
| 2,660
|
-- |
-- Common Data Types
--
-- <https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf saml-core-2.0-os> §1.3
module SAML2.Core.Datatypes where
import Prelude hiding (String)
import qualified SAML2.XML.Schema.Datatypes as XS
-- |§1.3.1
type XString = XS.String
-- |§1.3.2
type AnyURI = XS.AnyURI
-- |§1.3.3
type DateTime = XS.DateTime
-- |§1.3.4
type ID = XS.ID
-- |§1.3.4
type NCName = XS.NCName
|
dylex/hsaml2
|
SAML2/Core/Datatypes.hs
|
Haskell
|
apache-2.0
| 420
|
{-# LANGUAGE TemplateHaskell, DeriveFunctor #-}
{-| Some common Ganeti types.
This holds types common to both core work, and to htools. Types that
are very core specific (e.g. configuration objects) should go in
'Ganeti.Objects', while types that are specific to htools in-memory
representation should go into 'Ganeti.HTools.Types'.
-}
{-
Copyright (C) 2012, 2013, 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Types
( AllocPolicy(..)
, allocPolicyFromRaw
, allocPolicyToRaw
, InstanceStatus(..)
, instanceStatusFromRaw
, instanceStatusToRaw
, DiskTemplate(..)
, diskTemplateToRaw
, diskTemplateFromRaw
, TagKind(..)
, tagKindToRaw
, tagKindFromRaw
, NonNegative
, fromNonNegative
, mkNonNegative
, Positive
, fromPositive
, mkPositive
, Negative
, fromNegative
, mkNegative
, NonEmpty
, fromNonEmpty
, mkNonEmpty
, NonEmptyString
, QueryResultCode
, IPv4Address
, mkIPv4Address
, IPv4Network
, mkIPv4Network
, IPv6Address
, mkIPv6Address
, IPv6Network
, mkIPv6Network
, MigrationMode(..)
, migrationModeToRaw
, VerifyOptionalChecks(..)
, verifyOptionalChecksToRaw
, DdmSimple(..)
, DdmFull(..)
, ddmFullToRaw
, CVErrorCode(..)
, cVErrorCodeToRaw
, Hypervisor(..)
, hypervisorFromRaw
, hypervisorToRaw
, OobCommand(..)
, oobCommandToRaw
, OobStatus(..)
, oobStatusToRaw
, StorageType(..)
, storageTypeToRaw
, EvacMode(..)
, evacModeToRaw
, FileDriver(..)
, fileDriverToRaw
, InstCreateMode(..)
, instCreateModeToRaw
, RebootType(..)
, rebootTypeToRaw
, ExportMode(..)
, exportModeToRaw
, IAllocatorTestDir(..)
, iAllocatorTestDirToRaw
, IAllocatorMode(..)
, iAllocatorModeToRaw
, NICMode(..)
, nICModeToRaw
, JobStatus(..)
, jobStatusToRaw
, jobStatusFromRaw
, FinalizedJobStatus(..)
, finalizedJobStatusToRaw
, JobId
, fromJobId
, makeJobId
, makeJobIdS
, RelativeJobId
, JobIdDep(..)
, JobDependency(..)
, absoluteJobDependency
, getJobIdFromDependency
, OpSubmitPriority(..)
, opSubmitPriorityToRaw
, parseSubmitPriority
, fmtSubmitPriority
, OpStatus(..)
, opStatusToRaw
, opStatusFromRaw
, ELogType(..)
, eLogTypeToRaw
, ReasonElem
, ReasonTrail
, StorageUnit(..)
, StorageUnitRaw(..)
, StorageKey
, addParamsToStorageUnit
, diskTemplateToStorageType
, VType(..)
, vTypeFromRaw
, vTypeToRaw
, NodeRole(..)
, nodeRoleToRaw
, roleDescription
, DiskMode(..)
, diskModeToRaw
, BlockDriver(..)
, blockDriverToRaw
, AdminState(..)
, adminStateFromRaw
, adminStateToRaw
, AdminStateSource(..)
, adminStateSourceFromRaw
, adminStateSourceToRaw
, StorageField(..)
, storageFieldToRaw
, DiskAccessMode(..)
, diskAccessModeToRaw
, LocalDiskStatus(..)
, localDiskStatusFromRaw
, localDiskStatusToRaw
, localDiskStatusName
, ReplaceDisksMode(..)
, replaceDisksModeToRaw
, RpcTimeout(..)
, rpcTimeoutFromRaw -- FIXME: no used anywhere
, rpcTimeoutToRaw
, HotplugTarget(..)
, hotplugTargetToRaw
, HotplugAction(..)
, hotplugActionToRaw
, Private(..)
, showPrivateJSObject
, HvParams
, OsParams
, OsParamsPrivate
, TimeStampObject(..)
, UuidObject(..)
, SerialNoObject(..)
, TagsObject(..)
) where
import Control.Applicative
import Control.Monad (liftM)
import qualified Text.JSON as JSON
import Text.JSON (JSON, readJSON, showJSON)
import Data.Ratio (numerator, denominator)
import qualified Data.Set as Set
import System.Time (ClockTime)
import qualified Ganeti.ConstantUtils as ConstantUtils
import Ganeti.JSON
import qualified Ganeti.THH as THH
import Ganeti.Utils
-- * Generic types
-- | Type that holds a non-negative value.
newtype NonNegative a = NonNegative { fromNonNegative :: a }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'NonNegative'.
mkNonNegative :: (Monad m, Num a, Ord a, Show a) => a -> m (NonNegative a)
mkNonNegative i | i >= 0 = return (NonNegative i)
| otherwise = fail $ "Invalid value for non-negative type '" ++
show i ++ "'"
instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (NonNegative a) where
showJSON = JSON.showJSON . fromNonNegative
readJSON v = JSON.readJSON v >>= mkNonNegative
-- | Type that holds a positive value.
newtype Positive a = Positive { fromPositive :: a }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'Positive'.
mkPositive :: (Monad m, Num a, Ord a, Show a) => a -> m (Positive a)
mkPositive i | i > 0 = return (Positive i)
| otherwise = fail $ "Invalid value for positive type '" ++
show i ++ "'"
instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (Positive a) where
showJSON = JSON.showJSON . fromPositive
readJSON v = JSON.readJSON v >>= mkPositive
-- | Type that holds a negative value.
newtype Negative a = Negative { fromNegative :: a }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'Negative'.
mkNegative :: (Monad m, Num a, Ord a, Show a) => a -> m (Negative a)
mkNegative i | i < 0 = return (Negative i)
| otherwise = fail $ "Invalid value for negative type '" ++
show i ++ "'"
instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (Negative a) where
showJSON = JSON.showJSON . fromNegative
readJSON v = JSON.readJSON v >>= mkNegative
-- | Type that holds a non-null list.
newtype NonEmpty a = NonEmpty { fromNonEmpty :: [a] }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'NonEmpty'.
mkNonEmpty :: (Monad m) => [a] -> m (NonEmpty a)
mkNonEmpty [] = fail "Received empty value for non-empty list"
mkNonEmpty xs = return (NonEmpty xs)
instance (JSON.JSON a) => JSON.JSON (NonEmpty a) where
showJSON = JSON.showJSON . fromNonEmpty
readJSON v = JSON.readJSON v >>= mkNonEmpty
-- | A simple type alias for non-empty strings.
type NonEmptyString = NonEmpty Char
type QueryResultCode = Int
newtype IPv4Address = IPv4Address { fromIPv4Address :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv4Address :: Monad m => String -> m IPv4Address
mkIPv4Address address =
return IPv4Address { fromIPv4Address = address }
instance JSON.JSON IPv4Address where
showJSON = JSON.showJSON . fromIPv4Address
readJSON v = JSON.readJSON v >>= mkIPv4Address
newtype IPv4Network = IPv4Network { fromIPv4Network :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv4Network :: Monad m => String -> m IPv4Network
mkIPv4Network address =
return IPv4Network { fromIPv4Network = address }
instance JSON.JSON IPv4Network where
showJSON = JSON.showJSON . fromIPv4Network
readJSON v = JSON.readJSON v >>= mkIPv4Network
newtype IPv6Address = IPv6Address { fromIPv6Address :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv6Address :: Monad m => String -> m IPv6Address
mkIPv6Address address =
return IPv6Address { fromIPv6Address = address }
instance JSON.JSON IPv6Address where
showJSON = JSON.showJSON . fromIPv6Address
readJSON v = JSON.readJSON v >>= mkIPv6Address
newtype IPv6Network = IPv6Network { fromIPv6Network :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv6Network :: Monad m => String -> m IPv6Network
mkIPv6Network address =
return IPv6Network { fromIPv6Network = address }
instance JSON.JSON IPv6Network where
showJSON = JSON.showJSON . fromIPv6Network
readJSON v = JSON.readJSON v >>= mkIPv6Network
-- * Ganeti types
-- | Instance disk template type. The disk template is a name for the
-- constructor of the disk configuration 'DiskLogicalId' used for
-- serialization, configuration values, etc.
$(THH.declareLADT ''String "DiskTemplate"
[ ("DTDiskless", "diskless")
, ("DTFile", "file")
, ("DTSharedFile", "sharedfile")
, ("DTPlain", "plain")
, ("DTBlock", "blockdev")
, ("DTDrbd8", "drbd")
, ("DTRbd", "rbd")
, ("DTExt", "ext")
, ("DTGluster", "gluster")
])
$(THH.makeJSONInstance ''DiskTemplate)
instance THH.PyValue DiskTemplate where
showValue = show . diskTemplateToRaw
instance HasStringRepr DiskTemplate where
fromStringRepr = diskTemplateFromRaw
toStringRepr = diskTemplateToRaw
-- | Data type representing what items the tag operations apply to.
$(THH.declareLADT ''String "TagKind"
[ ("TagKindInstance", "instance")
, ("TagKindNode", "node")
, ("TagKindGroup", "nodegroup")
, ("TagKindCluster", "cluster")
, ("TagKindNetwork", "network")
])
$(THH.makeJSONInstance ''TagKind)
-- | The Group allocation policy type.
--
-- Note that the order of constructors is important as the automatic
-- Ord instance will order them in the order they are defined, so when
-- changing this data type be careful about the interaction with the
-- desired sorting order.
$(THH.declareLADT ''String "AllocPolicy"
[ ("AllocPreferred", "preferred")
, ("AllocLastResort", "last_resort")
, ("AllocUnallocable", "unallocable")
])
$(THH.makeJSONInstance ''AllocPolicy)
-- | The Instance real state type.
$(THH.declareLADT ''String "InstanceStatus"
[ ("StatusDown", "ADMIN_down")
, ("StatusOffline", "ADMIN_offline")
, ("ErrorDown", "ERROR_down")
, ("ErrorUp", "ERROR_up")
, ("NodeDown", "ERROR_nodedown")
, ("NodeOffline", "ERROR_nodeoffline")
, ("Running", "running")
, ("UserDown", "USER_down")
, ("WrongNode", "ERROR_wrongnode")
])
$(THH.makeJSONInstance ''InstanceStatus)
-- | Migration mode.
$(THH.declareLADT ''String "MigrationMode"
[ ("MigrationLive", "live")
, ("MigrationNonLive", "non-live")
])
$(THH.makeJSONInstance ''MigrationMode)
-- | Verify optional checks.
$(THH.declareLADT ''String "VerifyOptionalChecks"
[ ("VerifyNPlusOneMem", "nplusone_mem")
])
$(THH.makeJSONInstance ''VerifyOptionalChecks)
-- | Cluster verify error codes.
$(THH.declareLADT ''String "CVErrorCode"
[ ("CvECLUSTERCFG", "ECLUSTERCFG")
, ("CvECLUSTERCERT", "ECLUSTERCERT")
, ("CvECLUSTERCLIENTCERT", "ECLUSTERCLIENTCERT")
, ("CvECLUSTERFILECHECK", "ECLUSTERFILECHECK")
, ("CvECLUSTERDANGLINGNODES", "ECLUSTERDANGLINGNODES")
, ("CvECLUSTERDANGLINGINST", "ECLUSTERDANGLINGINST")
, ("CvEINSTANCEBADNODE", "EINSTANCEBADNODE")
, ("CvEINSTANCEDOWN", "EINSTANCEDOWN")
, ("CvEINSTANCELAYOUT", "EINSTANCELAYOUT")
, ("CvEINSTANCEMISSINGDISK", "EINSTANCEMISSINGDISK")
, ("CvEINSTANCEFAULTYDISK", "EINSTANCEFAULTYDISK")
, ("CvEINSTANCEWRONGNODE", "EINSTANCEWRONGNODE")
, ("CvEINSTANCESPLITGROUPS", "EINSTANCESPLITGROUPS")
, ("CvEINSTANCEPOLICY", "EINSTANCEPOLICY")
, ("CvEINSTANCEUNSUITABLENODE", "EINSTANCEUNSUITABLENODE")
, ("CvEINSTANCEMISSINGCFGPARAMETER", "EINSTANCEMISSINGCFGPARAMETER")
, ("CvENODEDRBD", "ENODEDRBD")
, ("CvENODEDRBDVERSION", "ENODEDRBDVERSION")
, ("CvENODEDRBDHELPER", "ENODEDRBDHELPER")
, ("CvENODEFILECHECK", "ENODEFILECHECK")
, ("CvENODEHOOKS", "ENODEHOOKS")
, ("CvENODEHV", "ENODEHV")
, ("CvENODELVM", "ENODELVM")
, ("CvENODEN1", "ENODEN1")
, ("CvENODENET", "ENODENET")
, ("CvENODEOS", "ENODEOS")
, ("CvENODEORPHANINSTANCE", "ENODEORPHANINSTANCE")
, ("CvENODEORPHANLV", "ENODEORPHANLV")
, ("CvENODERPC", "ENODERPC")
, ("CvENODESSH", "ENODESSH")
, ("CvENODEVERSION", "ENODEVERSION")
, ("CvENODESETUP", "ENODESETUP")
, ("CvENODETIME", "ENODETIME")
, ("CvENODEOOBPATH", "ENODEOOBPATH")
, ("CvENODEUSERSCRIPTS", "ENODEUSERSCRIPTS")
, ("CvENODEFILESTORAGEPATHS", "ENODEFILESTORAGEPATHS")
, ("CvENODEFILESTORAGEPATHUNUSABLE", "ENODEFILESTORAGEPATHUNUSABLE")
, ("CvENODESHAREDFILESTORAGEPATHUNUSABLE",
"ENODESHAREDFILESTORAGEPATHUNUSABLE")
, ("CvENODEGLUSTERSTORAGEPATHUNUSABLE",
"ENODEGLUSTERSTORAGEPATHUNUSABLE")
, ("CvEGROUPDIFFERENTPVSIZE", "EGROUPDIFFERENTPVSIZE")
])
$(THH.makeJSONInstance ''CVErrorCode)
-- | Dynamic device modification, just add/remove version.
$(THH.declareLADT ''String "DdmSimple"
[ ("DdmSimpleAdd", "add")
, ("DdmSimpleRemove", "remove")
])
$(THH.makeJSONInstance ''DdmSimple)
-- | Dynamic device modification, all operations version.
--
-- TODO: DDM_SWAP, DDM_MOVE?
$(THH.declareLADT ''String "DdmFull"
[ ("DdmFullAdd", "add")
, ("DdmFullRemove", "remove")
, ("DdmFullModify", "modify")
])
$(THH.makeJSONInstance ''DdmFull)
-- | Hypervisor type definitions.
$(THH.declareLADT ''String "Hypervisor"
[ ("Kvm", "kvm")
, ("XenPvm", "xen-pvm")
, ("Chroot", "chroot")
, ("XenHvm", "xen-hvm")
, ("Lxc", "lxc")
, ("Fake", "fake")
])
$(THH.makeJSONInstance ''Hypervisor)
instance THH.PyValue Hypervisor where
showValue = show . hypervisorToRaw
instance HasStringRepr Hypervisor where
fromStringRepr = hypervisorFromRaw
toStringRepr = hypervisorToRaw
-- | Oob command type.
$(THH.declareLADT ''String "OobCommand"
[ ("OobHealth", "health")
, ("OobPowerCycle", "power-cycle")
, ("OobPowerOff", "power-off")
, ("OobPowerOn", "power-on")
, ("OobPowerStatus", "power-status")
])
$(THH.makeJSONInstance ''OobCommand)
-- | Oob command status
$(THH.declareLADT ''String "OobStatus"
[ ("OobStatusCritical", "CRITICAL")
, ("OobStatusOk", "OK")
, ("OobStatusUnknown", "UNKNOWN")
, ("OobStatusWarning", "WARNING")
])
$(THH.makeJSONInstance ''OobStatus)
-- | Storage type.
$(THH.declareLADT ''String "StorageType"
[ ("StorageFile", "file")
, ("StorageSharedFile", "sharedfile")
, ("StorageGluster", "gluster")
, ("StorageLvmPv", "lvm-pv")
, ("StorageLvmVg", "lvm-vg")
, ("StorageDiskless", "diskless")
, ("StorageBlock", "blockdev")
, ("StorageRados", "rados")
, ("StorageExt", "ext")
])
$(THH.makeJSONInstance ''StorageType)
-- | Storage keys are identifiers for storage units. Their content varies
-- depending on the storage type, for example a storage key for LVM storage
-- is the volume group name.
type StorageKey = String
-- | Storage parameters
type SPExclusiveStorage = Bool
-- | Storage units without storage-type-specific parameters
data StorageUnitRaw = SURaw StorageType StorageKey
-- | Full storage unit with storage-type-specific parameters
data StorageUnit = SUFile StorageKey
| SUSharedFile StorageKey
| SUGluster StorageKey
| SULvmPv StorageKey SPExclusiveStorage
| SULvmVg StorageKey SPExclusiveStorage
| SUDiskless StorageKey
| SUBlock StorageKey
| SURados StorageKey
| SUExt StorageKey
deriving (Eq)
instance Show StorageUnit where
show (SUFile key) = showSUSimple StorageFile key
show (SUSharedFile key) = showSUSimple StorageSharedFile key
show (SUGluster key) = showSUSimple StorageGluster key
show (SULvmPv key es) = showSULvm StorageLvmPv key es
show (SULvmVg key es) = showSULvm StorageLvmVg key es
show (SUDiskless key) = showSUSimple StorageDiskless key
show (SUBlock key) = showSUSimple StorageBlock key
show (SURados key) = showSUSimple StorageRados key
show (SUExt key) = showSUSimple StorageExt key
instance JSON StorageUnit where
showJSON (SUFile key) = showJSON (StorageFile, key, []::[String])
showJSON (SUSharedFile key) = showJSON (StorageSharedFile, key, []::[String])
showJSON (SUGluster key) = showJSON (StorageGluster, key, []::[String])
showJSON (SULvmPv key es) = showJSON (StorageLvmPv, key, [es])
showJSON (SULvmVg key es) = showJSON (StorageLvmVg, key, [es])
showJSON (SUDiskless key) = showJSON (StorageDiskless, key, []::[String])
showJSON (SUBlock key) = showJSON (StorageBlock, key, []::[String])
showJSON (SURados key) = showJSON (StorageRados, key, []::[String])
showJSON (SUExt key) = showJSON (StorageExt, key, []::[String])
-- FIXME: add readJSON implementation
readJSON = fail "Not implemented"
-- | Composes a string representation of storage types without
-- storage parameters
showSUSimple :: StorageType -> StorageKey -> String
showSUSimple st sk = show (storageTypeToRaw st, sk, []::[String])
-- | Composes a string representation of the LVM storage types
showSULvm :: StorageType -> StorageKey -> SPExclusiveStorage -> String
showSULvm st sk es = show (storageTypeToRaw st, sk, [es])
-- | Mapping from disk templates to storage types.
diskTemplateToStorageType :: DiskTemplate -> StorageType
diskTemplateToStorageType DTExt = StorageExt
diskTemplateToStorageType DTFile = StorageFile
diskTemplateToStorageType DTSharedFile = StorageSharedFile
diskTemplateToStorageType DTDrbd8 = StorageLvmVg
diskTemplateToStorageType DTPlain = StorageLvmVg
diskTemplateToStorageType DTRbd = StorageRados
diskTemplateToStorageType DTDiskless = StorageDiskless
diskTemplateToStorageType DTBlock = StorageBlock
diskTemplateToStorageType DTGluster = StorageGluster
-- | Equips a raw storage unit with its parameters
addParamsToStorageUnit :: SPExclusiveStorage -> StorageUnitRaw -> StorageUnit
addParamsToStorageUnit _ (SURaw StorageBlock key) = SUBlock key
addParamsToStorageUnit _ (SURaw StorageDiskless key) = SUDiskless key
addParamsToStorageUnit _ (SURaw StorageExt key) = SUExt key
addParamsToStorageUnit _ (SURaw StorageFile key) = SUFile key
addParamsToStorageUnit _ (SURaw StorageSharedFile key) = SUSharedFile key
addParamsToStorageUnit _ (SURaw StorageGluster key) = SUGluster key
addParamsToStorageUnit es (SURaw StorageLvmPv key) = SULvmPv key es
addParamsToStorageUnit es (SURaw StorageLvmVg key) = SULvmVg key es
addParamsToStorageUnit _ (SURaw StorageRados key) = SURados key
-- | Node evac modes.
--
-- This is part of the 'IAllocator' interface and it is used, for
-- example, in 'Ganeti.HTools.Loader.RqType'. However, it must reside
-- in this module, and not in 'Ganeti.HTools.Types', because it is
-- also used by 'Ganeti.Constants'.
$(THH.declareLADT ''String "EvacMode"
[ ("ChangePrimary", "primary-only")
, ("ChangeSecondary", "secondary-only")
, ("ChangeAll", "all")
])
$(THH.makeJSONInstance ''EvacMode)
-- | The file driver type.
$(THH.declareLADT ''String "FileDriver"
[ ("FileLoop", "loop")
, ("FileBlktap", "blktap")
, ("FileBlktap2", "blktap2")
])
$(THH.makeJSONInstance ''FileDriver)
-- | The instance create mode.
$(THH.declareLADT ''String "InstCreateMode"
[ ("InstCreate", "create")
, ("InstImport", "import")
, ("InstRemoteImport", "remote-import")
])
$(THH.makeJSONInstance ''InstCreateMode)
-- | Reboot type.
$(THH.declareLADT ''String "RebootType"
[ ("RebootSoft", "soft")
, ("RebootHard", "hard")
, ("RebootFull", "full")
])
$(THH.makeJSONInstance ''RebootType)
-- | Export modes.
$(THH.declareLADT ''String "ExportMode"
[ ("ExportModeLocal", "local")
, ("ExportModeRemote", "remote")
])
$(THH.makeJSONInstance ''ExportMode)
-- | IAllocator run types (OpTestIAllocator).
$(THH.declareLADT ''String "IAllocatorTestDir"
[ ("IAllocatorDirIn", "in")
, ("IAllocatorDirOut", "out")
])
$(THH.makeJSONInstance ''IAllocatorTestDir)
-- | IAllocator mode. FIXME: use this in "HTools.Backend.IAlloc".
$(THH.declareLADT ''String "IAllocatorMode"
[ ("IAllocatorAlloc", "allocate")
, ("IAllocatorMultiAlloc", "multi-allocate")
, ("IAllocatorReloc", "relocate")
, ("IAllocatorNodeEvac", "node-evacuate")
, ("IAllocatorChangeGroup", "change-group")
])
$(THH.makeJSONInstance ''IAllocatorMode)
-- | Network mode.
$(THH.declareLADT ''String "NICMode"
[ ("NMBridged", "bridged")
, ("NMRouted", "routed")
, ("NMOvs", "openvswitch")
, ("NMPool", "pool")
])
$(THH.makeJSONInstance ''NICMode)
-- | The JobStatus data type. Note that this is ordered especially
-- such that greater\/lesser comparison on values of this type makes
-- sense.
$(THH.declareLADT ''String "JobStatus"
[ ("JOB_STATUS_QUEUED", "queued")
, ("JOB_STATUS_WAITING", "waiting")
, ("JOB_STATUS_CANCELING", "canceling")
, ("JOB_STATUS_RUNNING", "running")
, ("JOB_STATUS_CANCELED", "canceled")
, ("JOB_STATUS_SUCCESS", "success")
, ("JOB_STATUS_ERROR", "error")
])
$(THH.makeJSONInstance ''JobStatus)
-- | Finalized job status.
$(THH.declareLADT ''String "FinalizedJobStatus"
[ ("JobStatusCanceled", "canceled")
, ("JobStatusSuccessful", "success")
, ("JobStatusFailed", "error")
])
$(THH.makeJSONInstance ''FinalizedJobStatus)
-- | The Ganeti job type.
newtype JobId = JobId { fromJobId :: Int }
deriving (Show, Eq, Ord)
-- | Builds a job ID.
makeJobId :: (Monad m) => Int -> m JobId
makeJobId i | i >= 0 = return $ JobId i
| otherwise = fail $ "Invalid value for job ID ' " ++ show i ++ "'"
-- | Builds a job ID from a string.
makeJobIdS :: (Monad m) => String -> m JobId
makeJobIdS s = tryRead "parsing job id" s >>= makeJobId
-- | Parses a job ID.
parseJobId :: (Monad m) => JSON.JSValue -> m JobId
parseJobId (JSON.JSString x) = makeJobIdS $ JSON.fromJSString x
parseJobId (JSON.JSRational _ x) =
if denominator x /= 1
then fail $ "Got fractional job ID from master daemon?! Value:" ++ show x
-- FIXME: potential integer overflow here on 32-bit platforms
else makeJobId . fromIntegral . numerator $ x
parseJobId x = fail $ "Wrong type/value for job id: " ++ show x
instance JSON.JSON JobId where
showJSON = JSON.showJSON . fromJobId
readJSON = parseJobId
-- | Relative job ID type alias.
type RelativeJobId = Negative Int
-- | Job ID dependency.
data JobIdDep = JobDepRelative RelativeJobId
| JobDepAbsolute JobId
deriving (Show, Eq, Ord)
instance JSON.JSON JobIdDep where
showJSON (JobDepRelative i) = showJSON i
showJSON (JobDepAbsolute i) = showJSON i
readJSON v =
case JSON.readJSON v::JSON.Result (Negative Int) of
-- first try relative dependency, usually most common
JSON.Ok r -> return $ JobDepRelative r
JSON.Error _ -> liftM JobDepAbsolute (parseJobId v)
-- | From job ID dependency and job ID, compute the absolute dependency.
absoluteJobIdDep :: (Monad m) => JobIdDep -> JobId -> m JobIdDep
absoluteJobIdDep (JobDepAbsolute jid) _ = return $ JobDepAbsolute jid
absoluteJobIdDep (JobDepRelative rjid) jid =
liftM JobDepAbsolute . makeJobId $ fromJobId jid + fromNegative rjid
-- | Job Dependency type.
data JobDependency = JobDependency JobIdDep [FinalizedJobStatus]
deriving (Show, Eq, Ord)
instance JSON JobDependency where
showJSON (JobDependency dep status) = showJSON (dep, status)
readJSON = liftM (uncurry JobDependency) . readJSON
-- | From job dependency and job id compute an absolute job dependency.
absoluteJobDependency :: (Monad m) => JobDependency -> JobId -> m JobDependency
absoluteJobDependency (JobDependency jdep fstats) jid =
liftM (flip JobDependency fstats) $ absoluteJobIdDep jdep jid
-- | From a job dependency get the absolute job id it depends on,
-- if given absolutely.
getJobIdFromDependency :: JobDependency -> [JobId]
getJobIdFromDependency (JobDependency (JobDepAbsolute jid) _) = [jid]
getJobIdFromDependency _ = []
-- | Valid opcode priorities for submit.
$(THH.declareIADT "OpSubmitPriority"
[ ("OpPrioLow", 'ConstantUtils.priorityLow)
, ("OpPrioNormal", 'ConstantUtils.priorityNormal)
, ("OpPrioHigh", 'ConstantUtils.priorityHigh)
])
$(THH.makeJSONInstance ''OpSubmitPriority)
-- | Parse submit priorities from a string.
parseSubmitPriority :: (Monad m) => String -> m OpSubmitPriority
parseSubmitPriority "low" = return OpPrioLow
parseSubmitPriority "normal" = return OpPrioNormal
parseSubmitPriority "high" = return OpPrioHigh
parseSubmitPriority str = fail $ "Unknown priority '" ++ str ++ "'"
-- | Format a submit priority as string.
fmtSubmitPriority :: OpSubmitPriority -> String
fmtSubmitPriority OpPrioLow = "low"
fmtSubmitPriority OpPrioNormal = "normal"
fmtSubmitPriority OpPrioHigh = "high"
-- | Our ADT for the OpCode status at runtime (while in a job).
$(THH.declareLADT ''String "OpStatus"
[ ("OP_STATUS_QUEUED", "queued")
, ("OP_STATUS_WAITING", "waiting")
, ("OP_STATUS_CANCELING", "canceling")
, ("OP_STATUS_RUNNING", "running")
, ("OP_STATUS_CANCELED", "canceled")
, ("OP_STATUS_SUCCESS", "success")
, ("OP_STATUS_ERROR", "error")
])
$(THH.makeJSONInstance ''OpStatus)
-- | Type for the job message type.
$(THH.declareLADT ''String "ELogType"
[ ("ELogMessage", "message")
, ("ELogRemoteImport", "remote-import")
, ("ELogJqueueTest", "jqueue-test")
, ("ELogDelayTest", "delay-test")
])
$(THH.makeJSONInstance ''ELogType)
-- | Type of one element of a reason trail, of form
-- @(source, reason, timestamp)@.
type ReasonElem = (String, String, Integer)
-- | Type representing a reason trail.
type ReasonTrail = [ReasonElem]
-- | The VTYPES, a mini-type system in Python.
$(THH.declareLADT ''String "VType"
[ ("VTypeString", "string")
, ("VTypeMaybeString", "maybe-string")
, ("VTypeBool", "bool")
, ("VTypeSize", "size")
, ("VTypeInt", "int")
, ("VTypeFloat", "float")
])
$(THH.makeJSONInstance ''VType)
instance THH.PyValue VType where
showValue = THH.showValue . vTypeToRaw
-- * Node role type
$(THH.declareLADT ''String "NodeRole"
[ ("NROffline", "O")
, ("NRDrained", "D")
, ("NRRegular", "R")
, ("NRCandidate", "C")
, ("NRMaster", "M")
])
$(THH.makeJSONInstance ''NodeRole)
-- | The description of the node role.
roleDescription :: NodeRole -> String
roleDescription NROffline = "offline"
roleDescription NRDrained = "drained"
roleDescription NRRegular = "regular"
roleDescription NRCandidate = "master candidate"
roleDescription NRMaster = "master"
-- * Disk types
$(THH.declareLADT ''String "DiskMode"
[ ("DiskRdOnly", "ro")
, ("DiskRdWr", "rw")
])
$(THH.makeJSONInstance ''DiskMode)
-- | The persistent block driver type. Currently only one type is allowed.
$(THH.declareLADT ''String "BlockDriver"
[ ("BlockDrvManual", "manual")
])
$(THH.makeJSONInstance ''BlockDriver)
-- * Instance types
$(THH.declareLADT ''String "AdminState"
[ ("AdminOffline", "offline")
, ("AdminDown", "down")
, ("AdminUp", "up")
])
$(THH.makeJSONInstance ''AdminState)
$(THH.declareLADT ''String "AdminStateSource"
[ ("AdminSource", "admin")
, ("UserSource", "user")
])
$(THH.makeJSONInstance ''AdminStateSource)
instance THH.PyValue AdminStateSource where
showValue = THH.showValue . adminStateSourceToRaw
-- * Storage field type
$(THH.declareLADT ''String "StorageField"
[ ( "SFUsed", "used")
, ( "SFName", "name")
, ( "SFAllocatable", "allocatable")
, ( "SFFree", "free")
, ( "SFSize", "size")
])
$(THH.makeJSONInstance ''StorageField)
-- * Disk access protocol
$(THH.declareLADT ''String "DiskAccessMode"
[ ( "DiskUserspace", "userspace")
, ( "DiskKernelspace", "kernelspace")
])
$(THH.makeJSONInstance ''DiskAccessMode)
-- | Local disk status
--
-- Python code depends on:
-- DiskStatusOk < DiskStatusUnknown < DiskStatusFaulty
$(THH.declareILADT "LocalDiskStatus"
[ ("DiskStatusFaulty", 3)
, ("DiskStatusOk", 1)
, ("DiskStatusUnknown", 2)
])
localDiskStatusName :: LocalDiskStatus -> String
localDiskStatusName DiskStatusFaulty = "faulty"
localDiskStatusName DiskStatusOk = "ok"
localDiskStatusName DiskStatusUnknown = "unknown"
-- | Replace disks type.
$(THH.declareLADT ''String "ReplaceDisksMode"
[ -- Replace disks on primary
("ReplaceOnPrimary", "replace_on_primary")
-- Replace disks on secondary
, ("ReplaceOnSecondary", "replace_on_secondary")
-- Change secondary node
, ("ReplaceNewSecondary", "replace_new_secondary")
, ("ReplaceAuto", "replace_auto")
])
$(THH.makeJSONInstance ''ReplaceDisksMode)
-- | Basic timeouts for RPC calls.
$(THH.declareILADT "RpcTimeout"
[ ("Urgent", 60) -- 1 minute
, ("Fast", 5 * 60) -- 5 minutes
, ("Normal", 15 * 60) -- 15 minutes
, ("Slow", 3600) -- 1 hour
, ("FourHours", 4 * 3600) -- 4 hours
, ("OneDay", 86400) -- 1 day
])
-- | Hotplug action.
$(THH.declareLADT ''String "HotplugAction"
[ ("HAAdd", "hotadd")
, ("HARemove", "hotremove")
, ("HAMod", "hotmod")
])
$(THH.makeJSONInstance ''HotplugAction)
-- | Hotplug Device Target.
$(THH.declareLADT ''String "HotplugTarget"
[ ("HTDisk", "hotdisk")
, ("HTNic", "hotnic")
])
$(THH.makeJSONInstance ''HotplugTarget)
-- * Private type and instances
-- | A container for values that should be happy to be manipulated yet
-- refuses to be shown unless explicitly requested.
newtype Private a = Private { getPrivate :: a }
deriving (Eq, Ord, Functor)
instance (Show a, JSON.JSON a) => JSON.JSON (Private a) where
readJSON = liftM Private . JSON.readJSON
showJSON (Private x) = JSON.showJSON x
-- | "Show" the value of the field.
--
-- It would be better not to implement this at all.
-- Alas, Show OpCode requires Show Private.
instance Show a => Show (Private a) where
show _ = "<redacted>"
instance THH.PyValue a => THH.PyValue (Private a) where
showValue (Private x) = "Private(" ++ THH.showValue x ++ ")"
instance Applicative Private where
pure = Private
Private f <*> Private x = Private (f x)
instance Monad Private where
(Private x) >>= f = f x
return = Private
showPrivateJSObject :: (JSON.JSON a) =>
[(String, a)] -> JSON.JSObject (Private JSON.JSValue)
showPrivateJSObject value = JSON.toJSObject $ map f value
where f (k, v) = (k, Private $ JSON.showJSON v)
-- | The hypervisor parameter type. This is currently a simple map,
-- without type checking on key/value pairs.
type HvParams = Container JSON.JSValue
-- | The OS parameters type. This is, and will remain, a string
-- container, since the keys are dynamically declared by the OSes, and
-- the values are always strings.
type OsParams = Container String
type OsParamsPrivate = Container (Private String)
-- | Class of objects that have timestamps.
class TimeStampObject a where
cTimeOf :: a -> ClockTime
mTimeOf :: a -> ClockTime
-- | Class of objects that have an UUID.
class UuidObject a where
uuidOf :: a -> String
-- | Class of object that have a serial number.
class SerialNoObject a where
serialOf :: a -> Int
-- | Class of objects that have tags.
class TagsObject a where
tagsOf :: a -> Set.Set String
|
ganeti-github-testing/ganeti-test-1
|
src/Ganeti/Types.hs
|
Haskell
|
bsd-2-clause
| 32,269
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionFrameV2.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:21
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStyleOptionFrameV2 (
QqStyleOptionFrameV2(..)
,QqStyleOptionFrameV2_nf(..)
,qStyleOptionFrameV2_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QStyleOptionFrameV2
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqStyleOptionFrameV2 x1 where
qStyleOptionFrameV2 :: x1 -> IO (QStyleOptionFrameV2 ())
instance QqStyleOptionFrameV2 (()) where
qStyleOptionFrameV2 ()
= withQStyleOptionFrameV2Result $
qtc_QStyleOptionFrameV2
foreign import ccall "qtc_QStyleOptionFrameV2" qtc_QStyleOptionFrameV2 :: IO (Ptr (TQStyleOptionFrameV2 ()))
instance QqStyleOptionFrameV2 ((QStyleOptionFrameV2 t1)) where
qStyleOptionFrameV2 (x1)
= withQStyleOptionFrameV2Result $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionFrameV21 cobj_x1
foreign import ccall "qtc_QStyleOptionFrameV21" qtc_QStyleOptionFrameV21 :: Ptr (TQStyleOptionFrameV2 t1) -> IO (Ptr (TQStyleOptionFrameV2 ()))
instance QqStyleOptionFrameV2 ((QStyleOptionFrame t1)) where
qStyleOptionFrameV2 (x1)
= withQStyleOptionFrameV2Result $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionFrameV22 cobj_x1
foreign import ccall "qtc_QStyleOptionFrameV22" qtc_QStyleOptionFrameV22 :: Ptr (TQStyleOptionFrame t1) -> IO (Ptr (TQStyleOptionFrameV2 ()))
class QqStyleOptionFrameV2_nf x1 where
qStyleOptionFrameV2_nf :: x1 -> IO (QStyleOptionFrameV2 ())
instance QqStyleOptionFrameV2_nf (()) where
qStyleOptionFrameV2_nf ()
= withObjectRefResult $
qtc_QStyleOptionFrameV2
instance QqStyleOptionFrameV2_nf ((QStyleOptionFrameV2 t1)) where
qStyleOptionFrameV2_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionFrameV21 cobj_x1
instance QqStyleOptionFrameV2_nf ((QStyleOptionFrame t1)) where
qStyleOptionFrameV2_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionFrameV22 cobj_x1
instance Qfeatures (QStyleOptionFrameV2 a) (()) (IO (FrameFeatures)) where
features x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionFrameV2_features cobj_x0
foreign import ccall "qtc_QStyleOptionFrameV2_features" qtc_QStyleOptionFrameV2_features :: Ptr (TQStyleOptionFrameV2 a) -> IO CLong
instance QsetFeatures (QStyleOptionFrameV2 a) ((FrameFeatures)) where
setFeatures x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionFrameV2_setFeatures cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QStyleOptionFrameV2_setFeatures" qtc_QStyleOptionFrameV2_setFeatures :: Ptr (TQStyleOptionFrameV2 a) -> CLong -> IO ()
qStyleOptionFrameV2_delete :: QStyleOptionFrameV2 a -> IO ()
qStyleOptionFrameV2_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionFrameV2_delete cobj_x0
foreign import ccall "qtc_QStyleOptionFrameV2_delete" qtc_QStyleOptionFrameV2_delete :: Ptr (TQStyleOptionFrameV2 a) -> IO ()
|
uduki/hsQt
|
Qtc/Gui/QStyleOptionFrameV2.hs
|
Haskell
|
bsd-2-clause
| 3,434
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.