code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Util.Handler (
urlDecode',
title,
titleConcat,
addDomainToTitle,
maybeApiUser,
pageNo
) where
import Import
import Prelude (read)
import Text.Blaze (toMarkup, Markup)
urlDecode' :: Text -> Text
urlDecode' x = decodeUtf8 $ urlDecode True $ encodeUtf8 x
title :: Text -> Markup
title text = toMarkup $ addDomainToTitle text
titleConcat :: [Text] -> Markup
titleConcat parts = toMarkup $ addDomainToTitle $ concat parts
addDomainToTitle :: Text -> Text
addDomainToTitle (text) = text <> " - glot.io"
maybeApiUser :: Maybe UserId -> Handler (Maybe ApiUser)
maybeApiUser Nothing = return Nothing
maybeApiUser (Just userId) = do
Entity _ apiUser <- runDB $ getBy404 $ UniqueApiUser userId
return $ Just apiUser
pageNo :: Maybe Text -> Int
pageNo (Just page) = read $ unpack page
pageNo Nothing = 1
| vinnymac/glot-www | Util/Handler.hs | mit | 838 | 0 | 9 | 163 | 280 | 144 | 136 | 26 | 1 |
import Test.HUnit
import Ex02
testString = TestList [ "Empty string" ~: [] ~=? (splitWith (/='b') "")
, "No splitt" ~: ["aaa"] ~=? (splitWith (/='b') "aaa")
, "Only delimiter" ~: [] ~=? (splitWith (/='b') "bbb")
, "On start" ~: ["aaa"] ~=? (splitWith (/='b') "bbbaaa")
, "On end" ~: ["aaa"] ~=? (splitWith (/='b') "aaabbb")
, "Middle" ~: ["aaa","aaa"] ~=? (splitWith (/='b') "aaabbbaaa")
, "Many" ~: ["a","a","a","a"] ~=? (splitWith (/='b') "babababa")
, "Words" ~: (words " abc de fghi j ") ~=? (splitWith (\x -> x/=' ') " abc de fghi j ")
]
testLists = TestList [ "Complex" ~: [[2,4],[8,10],[12,14]] ~=? (splitWith even [2,4,1,3,5,8,10,3,12,14,5])
, "None" ~: [[1],[3]] ~=? (splitWith odd [1,2,3,4])
]
main = runTestTT $ TestList [ testLists, testString]
| imrehg/rwhaskell | ch04/Ex02test.hs | mit | 978 | 0 | 12 | 340 | 394 | 230 | 164 | 13 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.Particle
-- Copyright : (c) 2016 FP Complete Corporation
-- License : MIT (see LICENSE)
-- Maintainer : [email protected]
--
-- =The Theory
--
-- The particle filter, `runPF`, in this library is applicable to the
-- state space model given by
--
-- \[
-- \begin{aligned}
-- \boldsymbol{x}_i &= \boldsymbol{a}_i(\boldsymbol{x}_{i-1}) + \boldsymbol{\psi}_{i-1} \\
-- \boldsymbol{y}_i &= \boldsymbol{h}_i(\boldsymbol{x}_i) + \boldsymbol{\upsilon}_i
-- \end{aligned}
-- \]
--
-- where
--
-- * \(\boldsymbol{a_i}\)\ is some non-linear vector-valued possibly
-- time-varying state update function.
--
-- * \(\boldsymbol{\psi}_{i}\) are independent normally
-- distributed random variables with mean 0 representing the fact that
-- the state update is noisy: \(\boldsymbol{\psi}_{i} \sim {\cal{N}}(0,Q_i)\).
--
-- * \(\boldsymbol{h}_i\)\ is some non-linear vector-valued possibly time-varying
-- function describing how we observe the hidden state process.
--
-- * \(\boldsymbol{\upsilon}_i\) are independent normally
-- distributed random variables with mean 0 represent the fact that
-- the observations are noisy: \(\boldsymbol{\upsilon}_{i} \sim {\cal{N}}(0,R_i)\).
--
-- Clearly this could be generalised further; anyone wishing for such
-- a generalisation is encouraged to contribute to the library.
--
-- The smoother, `oneSmoothingPath` implements [Forward filtering /
-- backward
-- smoothing](https://en.wikipedia.org/wiki/Particle_filter#Backward_particle_smoothers)
-- and returns just one path from the particle filter; in most cases,
-- this will need to be run many times to provide good estimates of
-- the past. Note that `oneSmoothingPath` uses /all/ observation up
-- until the current time. This could be generalised to select only a
-- window of observations up to the current time. Again, contributions
-- to implement this generalisation are welcomed.
--
-- = An Extended Example
--
-- The equation of motion for a pendulum of unit length subject to
-- [Gaussian white
-- noise](https://en.wikipedia.org/wiki/White_noise#Mathematical_definitions)
-- is
--
-- \[
-- \frac{\mathrm{d}^2\alpha}{\mathrm{d}t^2} = -g\sin\alpha + w(t)
-- \]
--
-- We can discretize this via the usual [Euler method](https://en.wikipedia.org/wiki/Euler_method)
--
-- \[
-- \begin{bmatrix}
-- x_{1,i} \\
-- x_{2,i}
-- \end{bmatrix}
-- =
-- \begin{bmatrix}
-- x_{1,i-1} + x_{2,i-1}\Delta t \\
-- x_{2,i-1} - g\sin x_{1,i-1}\Delta t
-- \end{bmatrix}
-- +
-- \mathbf{q}_{i-1}
-- \]
--
-- where \(q_i \sim {\mathcal{N}}(0,Q)\) and
--
-- \[
-- Q
-- =
-- \begin{bmatrix}
-- \frac{q^c \Delta t^3}{3} & \frac{q^c \Delta t^2}{2} \\
-- \frac{q^c \Delta t^2}{2} & {q^c \Delta t}
-- \end{bmatrix}
-- \]
--
-- Assume that we can only measure the horizontal position of the
-- pendulum and further that this measurement is subject to error so that
--
-- \[
-- y_i = \sin x_i + r_i
-- \]
--
-- where \(r_i \sim {\mathcal{N}}(0,R)\).
--
--
-- First let's set the time step and the acceleration caused by
-- earth's gravity and the covariance matrices for the state and
-- observation.
--
--
-- > {-# LANGUAGE DataKinds #-}
-- >
-- > import Numeric.Particle
-- >
-- > deltaT, g :: Double
-- > deltaT = 0.01
-- > g = 9.81
-- >
-- > bigQ :: Sym 2
-- > bigQ = sym $ matrix bigQl
-- >
-- > qc :: Double
-- > qc = 0.01
-- >
-- > bigQl :: [Double]
-- > bigQl = [ qc * deltaT^3 / 3, qc * deltaT^2 / 2,
-- > qc * deltaT^2 / 2, qc * deltaT
-- > ]
-- >
-- > bigR :: Sym 1
-- > bigR = sym $ matrix [0.2]
-- >
-- > data SystemState a = SystemState { x1 :: a, x2 :: a }
-- > deriving Show
-- >
-- > newtype SystemObs a = SystemObs { y1 :: a }
-- > deriving Show
-- >
--
-- We use the data generated using code made available with Simo
-- Särkkä's
-- [book](http://www.cambridge.org/gb/academic/subjects/statistics-probability/applied-probability-and-stochastic-networks/bayesian-filtering-and-smoothing)
-- which starts with an angle of 1.5 radians and an angular velocity
-- of 0.0 radians per second. We set our prior to have a mean of 1.6, not too far from the actual value.
--
-- > {-# LANGUAGE DataKinds #-}
-- >
-- > m0 :: PendulumState
-- > m0 = vector [1.6, 0]
-- >
-- > bigP :: Sym 2
-- > bigP = sym $ diag 0.1
-- >
-- > initParticles :: R.MonadRandom m =>
-- > m (Particles (SystemState Double))
-- > initParticles = V.replicateM nParticles $ do
-- > r <- R.sample $ R.rvar (Normal m0 bigP)
-- > let x1 = fst $ headTail r
-- > x2 = fst $ headTail $ snd $ headTail r
-- > return $ SystemState { x1 = x1, x2 = x2}
-- >
-- > nObs :: Int
-- > nObs = 200
-- >
-- > nParticles :: Int
-- > nParticles = 20
-- >
-- > (.+), (.*), (.-) :: (Num a) => V.Vector a -> V.Vector a -> V.Vector a
-- > (.+) = V.zipWith (+)
-- > (.*) = V.zipWith (*)
-- > (.-) = V.zipWith (-)
-- >
-- > stateUpdateP :: Particles (SystemState Double) ->
-- > Particles (SystemState Double)
-- > stateUpdateP xPrevs = V.zipWith SystemState x1s x2s
-- > where
-- > ix = V.length xPrevs
-- >
-- > x1Prevs = V.map x1 xPrevs
-- > x2Prevs = V.map x2 xPrevs
-- >
-- > deltaTs = V.replicate ix deltaT
-- > gs = V.replicate ix g
-- > x1s = x1Prevs .+ (x2Prevs .* deltaTs)
-- > x2s = x2Prevs .- (gs .* (V.map sin x1Prevs) .* deltaTs)
--
--
-- <<diagrams/src_Numeric_Particle_diagV.svg#diagram=diagV&height=600&width=500>>
--
-- === Code for Plotting
--
-- The full code for plotting the results:
--
-- > {-# LANGUAGE ExplicitForAll #-}
-- > {-# LANGUAGE TypeOperators #-}
-- > {-# LANGUAGE DataKinds #-}
-- >
-- > import qualified Graphics.Rendering.Chart as C
-- > import Graphics.Rendering.Chart.Backend.Diagrams
-- > import Data.Colour
-- > import Data.Colour.Names
-- > import Data.Default.Class
-- > import Control.Lens
-- >
-- > import Data.Csv
-- > import System.IO hiding ( hGetContents )
-- > import Data.ByteString.Lazy ( hGetContents )
-- > import qualified Data.Vector as V
-- >
-- > import Data.Random.Distribution.Static.MultivariateNormal ( Normal(..) )
-- > import qualified Data.Random as R
-- > import Data.Random.Source.PureMT ( pureMT )
-- > import Control.Monad.State ( evalState, replicateM )
-- >
-- > import Data.List ( transpose )
-- >
-- > import GHC.TypeLits ( KnownNat )
-- >
-- > import Numeric.LinearAlgebra.Static
-- >
-- > chartEstimated :: String ->
-- > [(Double, Double)] ->
-- > [(Double, Double)] ->
-- > [(Double, Double)] ->
-- > C.Renderable ()
-- > chartEstimated title acts obs ests = C.toRenderable layout
-- > where
-- >
-- > actuals = C.plot_lines_values .~ [acts]
-- > $ C.plot_lines_style . C.line_color .~ opaque red
-- > $ C.plot_lines_title .~ "Actual Trajectory"
-- > $ C.plot_lines_style . C.line_width .~ 1.0
-- > $ def
-- >
-- > measurements = C.plot_points_values .~ obs
-- > $ C.plot_points_style . C.point_color .~ opaque blue
-- > $ C.plot_points_title .~ "Measurements"
-- > $ def
-- >
-- > estimas = C.plot_lines_values .~ [ests]
-- > $ C.plot_lines_style . C.line_color .~ opaque black
-- > $ C.plot_lines_title .~ "Inferred Trajectory"
-- > $ C.plot_lines_style . C.line_width .~ 1.0
-- > $ def
-- >
-- > layout = C.layout_title .~ title
-- > $ C.layout_plots .~ [C.toPlot actuals, C.toPlot measurements, C.toPlot estimas]
-- > $ C.layout_y_axis . C.laxis_title .~ "Angle / Horizontal Displacement"
-- > $ C.layout_y_axis . C.laxis_override .~ C.axisGridHide
-- > $ C.layout_x_axis . C.laxis_title .~ "Time"
-- > $ C.layout_x_axis . C.laxis_override .~ C.axisGridHide
-- > $ def
-- >
-- > stateUpdateNoisy :: R.MonadRandom m =>
-- > Sym 2 ->
-- > Particles (SystemState Double) ->
-- > m (Particles (SystemState Double))
-- > stateUpdateNoisy bigQ xPrevs = do
-- > let xs = stateUpdateP xPrevs
-- >
-- > x1s = V.map x1 xs
-- > x2s = V.map x2 xs
-- >
-- > let ix = V.length xPrevs
-- > etas <- replicateM ix $ R.sample $ R.rvar (Normal 0.0 bigQ)
-- >
-- > let eta1s, eta2s :: V.Vector Double
-- > eta1s = V.fromList $ map (fst . headTail) etas
-- > eta2s = V.fromList $ map (fst . headTail . snd . headTail) etas
-- >
-- > return (V.zipWith SystemState (x1s .+ eta1s) (x2s .+ eta2s))
-- >
-- > obsUpdate :: Particles (SystemState Double) ->
-- > Particles (SystemObs Double)
-- > obsUpdate xs = V.map (SystemObs . sin . x1) xs
-- >
-- > weight :: forall a n . KnownNat n =>
-- > (a -> R n) ->
-- > Sym n ->
-- > a -> a -> Double
-- > weight f bigR obs obsNew = R.pdf (Normal (f obsNew) bigR) (f obs)
-- >
-- > runFilter :: Particles (SystemObs Double) -> V.Vector (Particles (SystemState Double))
-- > runFilter pendulumSamples = evalState action (pureMT 19)
-- > where
-- > action = do
-- > xs <- initParticles
-- > scanMapM
-- > (runPF (stateUpdateNoisy bigQ) obsUpdate (weight f bigR))
-- > return
-- > xs
-- > pendulumSamples
-- >
-- > testSmoothing :: Particles (SystemObs Double) -> Int -> [Double]
-- > testSmoothing ss n = V.toList $ evalState action (pureMT 23)
-- > where
-- > action = do
-- > xss <- V.replicateM n $ oneSmoothingPath (stateUpdateNoisy bigQ) (weight h bigQ) nParticles (runFilter ss)
-- > let yss = V.fromList $ map V.fromList $
-- > transpose $
-- > V.toList $ V.map (V.toList) $
-- > xss
-- > return $ V.map (/ (fromIntegral n)) $ V.map V.sum $ V.map (V.map x1) yss
-- >
-- > type PendulumState = R 2
-- >
-- > f :: SystemObs Double -> R 1
-- > f = vector . pure . y1
-- >
-- > h :: SystemState Double -> R 2
-- > h u = vector [x1 u , x2 u]
-- >
-- > diagV = do
-- > h <- openFile "data/matlabRNGs.csv" ReadMode
-- > cs <- hGetContents h
-- > let df = (decode NoHeader cs) :: Either String (V.Vector (Double, Double))
-- > case df of
-- > Left _ -> error "Whatever"
-- > Right generatedSamples -> do
-- > let preObs = V.take nObs $ V.map fst generatedSamples
-- > let obs = V.toList preObs
-- > let acts = V.toList $ V.take nObs $ V.map snd generatedSamples
-- > let nus = take nObs (testSmoothing (V.map SystemObs preObs) 50)
-- > denv <- defaultEnv C.vectorAlignmentFns 600 500
-- > let charte = chartEstimated "Particle Smoother"
-- > (zip [0,1..] acts)
-- > (zip [0,1..] obs)
-- > (zip [0,1..] nus)
-- > return $ fst $ runBackend denv (C.render charte (600, 500))
--
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE BangPatterns #-}
module Numeric.Particle (
runPF
, oneSmoothingPath
, Particles
, Path
) where
import Data.Random hiding ( StdNormal, Normal )
import Control.Monad
import qualified Data.Vector as V
import Data.Vector ( Vector )
import Data.Bits ( shiftR )
type Particles a = Vector a -- ^ As an aid for the reader
type Path a = Vector a -- ^ As an aid for the reader
runPF
:: MonadRandom m
=> (Particles a -> m (Particles a)) -- ^ System evolution at a point
-- \(\boldsymbol{a}_i(\boldsymbol{x})\)
-> (Particles a -> Particles b) -- ^ Measurement operator at a point \(\boldsymbol{h}_i\)
-> (b -> b -> Double) -- ^ Observation probability density function \(p(\boldsymbol{y}_k|\boldsymbol{x}^{(i)}_k)\)
-> Particles a -- ^ Current estimate
-- \(\big\{\big(w^{(i)}_k, \boldsymbol{x}^{(i)}_k\big) : i \in \{1,\ldots,N\}\big\}\)
-- where \(N\) is the number of particles
-> b -- ^ New measurement \(\boldsymbol{y}_i\)
-> m (Particles a) -- ^ New estimate
-- \(\big\{\big(w^{(i)}_{k+1}, \boldsymbol{x}^{(i)}_{k+1}\big) : i \in \{1,\ldots,N\}\big\}\)
-- where \(N\) is the number of particles
runPF stateUpdate obsUpdate weight statePrevs obs = do
stateNews <- stateUpdate statePrevs
let obsNews = obsUpdate stateNews
let weights = V.map (weight obs) obsNews
cumSumWeights = V.tail $ V.scanl (+) 0 weights
totWeight = V.last cumSumWeights
nParticles = V.length statePrevs
vs <- V.replicateM nParticles (sample $ uniform 0.0 totWeight)
let js = indices cumSumWeights vs
stateTildes = V.map (stateNews V.!) js
return stateTildes
oneSmoothingPath
:: MonadRandom m
=> (Particles a -> m (Particles a)) -- ^ System evolution at a point
-- \(\boldsymbol{a}_i(\boldsymbol{x})\)
-> (a -> a -> Double) -- ^ State probability density function \(p(\boldsymbol{x}^{(i)}_k|\boldsymbol{x}^{(i)}_{k-1})\)
-> Int -- ^ Number of particles \(N\)
-> (Vector (Particles a)) -- ^ Filtering estimates
-- \(\bigg\{\big\{\big(w^{(i)}_{k+1}, \boldsymbol{x}^{(i)}_{k+1}\big) : i \in \{1,\ldots,N\}\big\} : k \in \{1,\ldots,T\}\bigg\}\)
-- where \(T\) is the number of timesteps
-> m (Path a)
-- ^ A path for the smoothed particle \(\{\boldsymbol{x}_k : k \in T\}\) where \(T\) is the number of timesteps
oneSmoothingPath stateUpdate weight nParticles filterEstss = do
let ys = filterEstss
ix <- sample $ uniform 0 (nParticles - 1)
let xn = (V.head ys) V.! ix
scanMapM (oneSmoothingStep stateUpdate weight) return xn (V.tail ys)
oneSmoothingStep :: MonadRandom m =>
(Particles a -> m (Particles a)) ->
(a -> a -> Double) ->
a ->
Particles a ->
m a
oneSmoothingStep stateUpdate
stateDensity
smoothingSampleAtiPlus1
filterSamplesAti = do it
where
it = do
mus <- stateUpdate filterSamplesAti
let weights = V.map (stateDensity smoothingSampleAtiPlus1) mus
cumSumWeights = V.tail $ V.scanl (+) 0 weights
totWeight = V.last cumSumWeights
v <- sample $ uniform 0.0 totWeight
let ix = binarySearch cumSumWeights v
xnNew = filterSamplesAti V.! ix
return $ xnNew
indices :: Vector Double -> Vector Double -> Vector Int
indices bs xs = V.map (binarySearch bs) xs
binarySearch :: (Ord a) =>
Vector a -> a -> Int
binarySearch vec x = loop 0 (V.length vec - 1)
where
loop !l !u
| u <= l = l
| otherwise = let e = vec V.! k in if x <= e then loop l k else loop (k+1) u
where k = l + (u - l) `shiftR` 1
scanMapM :: Monad m => (s -> a -> m s) -> (s -> m b) -> s -> Vector a -> m (Vector b)
scanMapM f g !s0 !xs
| V.null xs = do
r <- g s0
return $ V.singleton r
| otherwise = do
s <- f s0 (V.head xs)
r <- g s0
liftM (r `V.cons`) (scanMapM f g s (V.tail xs))
| idontgetoutmuch/Kalman | src/Numeric/Particle.hs | mit | 15,498 | 0 | 14 | 4,169 | 1,449 | 887 | 562 | 82 | 2 |
-- Draw fractal by escape time method
module Escape where
import Graphics.GD
import Data.Complex
import Draw
type C = Complex Double
-- maxTime ->
-- maxRadius ->
-- iteration function ->
-- initial value ->
-- time to escape
escape :: Int -> Double -> (C -> C) -> C -> Int
escape maxTime maxRadius f x = length $ takeWhile (\z -> magnitude z < maxRadius) $ take (maxTime + 1) $ iterate f x
-- exit by difference
escape' :: Int -> Double -> (C -> C) -> C -> Int
escape' maxTime minDiff f x = length $ takeWhile (\(a, b) -> abs (a - b) > minDiff) st where
a = map magnitude $ take (maxTime + 2) $ iterate f x
st = zip a (tail a)
-- f z = z^2 + c, z0 = 0
mandelbrot :: IO ()
mandelbrot = drawFractal "mandelbrot.png" imageSize coorRange colorMagic where
imageSize = (1000, 1000)
coorRange = (-2.0, 1.0, -1.5, 1.5)
colorMagic (x, y)
| t > maxTime = rgb 0 0 0
| otherwise = color
where maxTime = 256
maxRadius = 2.0
f = \z -> z^2 + (x :+ y)
t = (escape maxTime maxRadius f 0) - 1
color = rgb t t t
-- quadratic polynomials is only a small subset of Julia set
-- f z = z^2 + c, z0 unset
julia :: C -> IO ()
julia c = drawFractal "julia.png" imageSize coorRange (colorMagic c) where
imageSize = (1000, 1000)
coorRange = (-2.0, 2.0, -2.0, 2.0)
colorMagic c (x, y)
| t > maxTime = rgb 0 0 0
| otherwise = color
where maxTime = 256
maxRadius = 2.0
f = \z -> z^2 + c
t = (escape maxTime maxRadius f (x :+ y)) - 1
color = rgb t t t
-- f z = (|Re(z)| + i|Im(z)|)^2 + c, z0 = 0
-- using (-) to generate, for better view
burningShip :: IO ()
burningShip = drawFractal "burningShip.png" imageSize coorRange colorMagic where
imageSize = (2000, 1500)
coorRange = (-1.67, -1.65, -0.002, 0.013)
colorMagic (x, y)
| t > maxTime = rgb 0 0 0
| otherwise = color
where maxTime = 256
maxRadius = 2.0
f = \z -> ((abs $ realPart z) :+ (negate . abs $ imagPart z))^2 + (x :+ y)
t = (escape maxTime maxRadius f 0) - 1
color = rgb t t t
-- only a subset of Nova
-- f z = z^p - 1
-- z => z - Rf/f' + c, (c = 0)
nova :: Int -> Double -> IO ()
nova p r = drawFractal "nova.png" imageSize coorRange (colorMagic p r) where
imageSize = (1000, 1000)
coorRange = (-2.0, 2.0, -2.0, 2.0)
colorMagic p r (x, y)
| t > maxTime = rgb 0 0 0
| otherwise = color
where maxTime = 256
minDiff = 0.0001
cr = r :+ 0
f = \z -> z - cr * (z^p - 1) / (fromIntegral p * z^(p-1))
t = (escape' maxTime minDiff f (x :+ y)) - 1
color = rgb t t t
| delta4d/Fractal.hs | Escape.hs | mit | 2,934 | 0 | 16 | 1,068 | 1,046 | 561 | 485 | 60 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE AutoDeriveTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module DB.Model.Internal.Value where
import GHC.Generics hiding (to, from)
import Control.Monad
import Control.Monad.Except
import Control.Monad.Reader
import Database.HDBC as D hiding (run)
import Text.Printf
import Data.Aeson (fromJSON, toJSON, FromJSON, ToJSON, GToJSON, GFromJSON)
import qualified Data.Aeson as A
import Control.Arrow
import Data.List as L
import Data.List.Split as L
import Data.Map (Map)
import qualified Data.Map as M
import DB.Model.Internal.Exception
import DB.Model.Internal.TypeCast
import qualified Data.Vector as V
import Data.Maybe
import Control.Exception
import GHC.IO.Exception
import Generics.Deriving.Show
import Data.Typeable
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as H
import Data.Proxy (Proxy(..))
import qualified Data.Proxy as P
data Value x = Val x
| Many [x]
| Null
deriving (Generic, Show, Eq, Functor)
instance (ToJSON x) => ToJSON (Value x)
instance (FromJSON x) => FromJSON (Value x)
instance (GShow x) => GShow (Value x)
get :: (a Value -> Value b) -> a Value -> b
get f a = let Val x = f a in x
(#) = flip get
-- instance Applicative Value where
-- pure = Val
-- (Val f) <*> (Val a) = (Val $ f a)
-- (Val f) <*> (Many a) = (Many $ map f a)
-- _ <*> _ = Null
-- instance WrapVal Value where
-- wrapVal = Val
-- wrapVals = Many
-- instance Field Value
| YLiLarry/db-model | src/DB/Model/Internal/Value.hs | mit | 1,835 | 0 | 9 | 359 | 412 | 256 | 156 | 47 | 1 |
module Easy where
import Control.Monad
import Data.List
import Data.Maybe
import Text.Trifecta
import Text.Trifecta.Delta
data EasyParsed = EasyArray [Double] | EasyString String
deriving (Show)
test1 = "123"
test2 = "44.234"
test3 = "0x123N"
test4 = "3.23e5"
test5 = "1293712938712938172938172391287319237192837329"
test6 = ".25"
test7 = "123 234 345"
test8 = "2015 4 4`Challenge #`261`Easy"
test9 = "234.2`234ggf 45`00`number string number (0)"
parseTestData t = parseString easyParse (Columns (genericLength t) 0) t
mParseTestData t = parseString mEasyParse (Columns (genericLength t) 0) t
mEasyParse = easyParse `sepBy1` char '`'
easyParse = choice [try arrayParser, stringParser]
arrayParser = EasyArray <$> numberParser `sepBy1` char ' '
stringParser = EasyString <$> some (notChar '`')
numberParser = p <$> option "0" (some digit) <*> optional ((++) <$> numPart '.' <*> option "" (numPart 'e')) <* notFollowedBy (noneOf [' ','`'])
where
p x (Just y) = read (x ++ y)
p x Nothing = read x
numPart c = (:) <$> char c <*> some digit
| z0isch/reddit-dailyprogrammer | Challenge262/src/Easy.hs | mit | 1,112 | 0 | 12 | 233 | 362 | 193 | 169 | 27 | 2 |
module Untyped.Core where
import ClassyPrelude
import Bound
import Control.Monad.Writer hiding (fix)
import Data.Deriving (deriveEq1, deriveOrd1, deriveRead1, deriveShow1)
import Data.Maybe (fromJust)
import qualified Data.Set as Set
import Dashboard (pattern FastAtom)
import Nock
import SimpleNoun
type Nat = Int
data Exp a
= Var a
| App (Exp a) (Exp a)
| Lam (Scope () Exp a)
| Atm Atom
| Cel (Exp a) (Exp a)
| IsC (Exp a)
| Suc (Exp a)
| Eql (Exp a) (Exp a)
| Ift (Exp a) (Exp a) (Exp a)
| Let (Exp a) (Scope () Exp a)
| Jet Atom (Exp a)
| Fix (Scope () Exp a)
| Zap
deriving (Functor, Foldable, Traversable)
deriveEq1 ''Exp
deriveOrd1 ''Exp
deriveRead1 ''Exp
deriveShow1 ''Exp
makeBound ''Exp
deriving instance Eq a => Eq (Exp a)
deriving instance Ord a => Ord (Exp a)
deriving instance Read a => Read (Exp a)
deriving instance Show a => Show (Exp a)
lam :: Eq a => a -> Exp a -> Exp a
lam v e = Lam (abstract1 v e)
ledt :: Eq a => a -> Exp a -> Exp a -> Exp a
ledt v e f = Let e (abstract1 v f)
fix :: Eq a => a -> Exp a -> Exp a
fix v e = Fix (abstract1 v e)
-- | The expression that returns the given noun as a constant.
con :: Noun -> Exp a
con = \case
A a -> Atm a
C n m -> Cel (con n) (con m)
data CExp a
= CVar a
| CSef a
| CApp (CExp a) (CExp a)
| CLam [a] (CExp (Var () Int))
| CAtm Atom
| CCel (CExp a) (CExp a)
| CIsC (CExp a)
| CSuc (CExp a)
| CEql (CExp a) (CExp a)
| CIft (CExp a) (CExp a) (CExp a)
| CLet (CExp a) (CExp (Var () a))
| CJet Atom (CExp a)
| CFix [a] (CExp (Var () Int))
| CZap
deriving (Functor, Foldable, Traversable)
deriveEq1 ''CExp
deriveOrd1 ''CExp
deriveRead1 ''CExp
deriveShow1 ''CExp
deriving instance Eq a => Eq (CExp a)
deriving instance Ord a => Ord (CExp a)
deriving instance Read a => Read (CExp a)
deriving instance Show a => Show (CExp a)
data Manner a
= Direct a
| Selfish a
deriving (Functor, Foldable, Traversable)
rude :: Manner a -> a
rude = \case
Direct x -> x
Selfish x -> x
toCopy :: Ord a => Exp a -> CExp b
toCopy = fst . runWriter . go \v -> error "toCopy: free variable"
where
go :: Ord a => (a -> Manner c) -> Exp a -> Writer (Set a) (CExp c)
go env = \case
Var v -> do
tell (singleton v)
case env v of
Direct v' -> pure (CVar v')
Selfish v' -> pure (CSef v')
App e f -> CApp <$> go env e <*> go env f
Atm a -> pure (CAtm a)
Cel e f -> CCel <$> go env e <*> go env f
IsC e -> CIsC <$> go env e
Suc e -> CSuc <$> go env e
Eql e f -> CEql <$> go env e <*> go env f
Ift e t f -> CIft <$> go env e <*> go env t <*> go env f
Jet a e -> CJet a <$> go env e
Zap -> pure CZap
Let e s -> do
ce <- go env e
let
env' = \case
B () -> Direct (B ())
F x -> fmap F (env x)
cf <- retcon removeBound (go env' (fromScope s))
pure (CLet ce cf)
Fix s -> lam s env CFix Selfish
Lam s -> lam s env CLam Direct
lam s env ctor manner =
writer
( ctor (rude . env <$> Set.toAscList usedLexicals) ce
, usedLexicals
)
where
(ce, usedVars) = runWriter $ go env' $ fromScope s
env' = \case
B () -> manner $ B ()
F v -> env v $> F (Set.findIndex v usedLexicals)
usedLexicals = removeBound usedVars
removeBound :: (Ord a, Ord b) => Set (Var b a) -> Set a
removeBound = mapMaybeSet \case
B _ -> Nothing
F v -> Just v
-- | Like censor, except you can change the type of the log
retcon :: (w -> uu) -> Writer w a -> Writer uu a
retcon f = mapWriter \(a, m) -> (a, f m)
-- I begin to wonder why there aren't primary abstractions around filtering.
mapMaybeSet :: (Ord a, Ord b) => (a -> Maybe b) -> Set a -> Set b
mapMaybeSet f = setFromList . mapMaybe f . toList
-- Possible improvements:
-- - a "quote and unquote" framework for nock code generation (maybe)
copyToNock :: CExp a -> Nock
copyToNock = go \v -> error "copyToNock: free variable"
where
-- if you comment out this declaration, you get a type error!
go :: (a -> Path) -> CExp a -> Nock
go env = \case
CVar v -> N0 (toAxis $ env v)
CSef v -> N2 (N0 $ toAxis $ env v) (N0 $ toAxis $ env v)
CApp e f -> N2 (go env f) (go env e)
CAtm a -> N1 (A a)
CCel e f -> cell (go env e) (go env f)
CIsC e -> N3 (go env e)
CSuc e -> N4 (go env e)
CEql e f -> N5 (go env e) (go env f)
CIft e t f -> N6 (go env e) (go env t) (go env f)
CJet a e -> jet a (go env e)
CZap -> N0 0
CLet e f -> N8 (go env e) (go env' f)
where
env' = \case
B () -> [L]
F v -> R : env v
CLam vs e -> lam (map (go env . CVar) vs) (go (lamEnv vs) e)
CFix vs e ->
N7
(lam (map (go env . CVar) vs) (go (lamEnv vs) e))
(N2 (N0 1) (N0 1))
lamEnv vs = if null vs
then \case
B () -> []
F _ -> error "copyToNock: unexpected lexical"
else \case
B () -> [R]
F i -> L : posIn i (length vs)
jet a ef =
NC
(N1 (A 11))
(NC
(N1
(C (A FastAtom)
(C (A 1) (A a))))
ef)
lam vfs ef = case layOut vfs of
Nothing -> N1 (nockToNoun ef)
Just pr -> NC (N1 (A 8)) $ NC (NC (N1 (A 1)) pr) $ N1 (nockToNoun ef)
cell :: Nock -> Nock -> Nock
cell (N1 n) (N1 m) = N1 (C n m)
cell ef ff = NC ef ff
layOut :: [Nock] -> Maybe Nock
layOut = \case
[] -> Nothing
[x] -> Just x
xs -> Just $ NC (fromJust $ layOut l) (fromJust $ layOut r)
where
(l, r) = splitAt (length xs `div` 2) xs
posIn :: Int -> Int -> Path
posIn 0 1 = []
posIn i n
| i < 0 || n <= i = error ("posIn: " <> show i <> " out of bound " <> show n)
| i < mid = L : posIn i mid
| otherwise = R : posIn (i - mid) (n - mid)
where mid = n `div` 2
-- | The proposed new calling convention
copy :: Ord a => Exp a -> Nock
copy = copyToNock . toCopy
-- | Decrements its argument.
decrement :: Exp String
decrement = lam "a" $ App (fix "f" $ lam "b" $ Ift (Eql (Var "a") (Suc (Var "b"))) (Var "b") (App (Var "f") (Suc (Var "b")))) (Atm 0)
| urbit/urbit | pkg/hs/proto/lib/Untyped/Core.hs | mit | 6,350 | 0 | 21 | 2,117 | 3,191 | 1,562 | 1,629 | -1 | -1 |
module Parser (parse) where
import qualified Data.Map as Map
import Data.Maybe
import Lex
import Rules
data ParseTree = Leaf String | Cmplx :^ [ParseTree]
deriving (Eq, Ord)
instance Show ParseTree where
show (Leaf a) = show a
show (c :^ trees) = show c ++ "^" ++ show trees
type Cell = Map.Map Cmplx [ParseTree]
type Vector = [(Int, Cell)]
(??) :: Ord s => Map.Map s [a] -> s -> [a]
m ?? s = fromMaybe [] (Map.lookup s m)
parse :: Lexicon -> [String] -> [ParseTree]
parse lexicon = process
where
process :: [String] -> [ParseTree]
process input
| size == ncell = cell ?? CmplxLeaf S
| otherwise = []
where (size, vectors) = foldl nextInputToken (0, []) input
(ncell, cell) = last (last vectors)
nextInputToken :: (Int, [Vector]) -> String -> (Int, [Vector])
nextInputToken (size, vectors) token = (size', vectors')
where size' = size + 1
vectors' = [(size', cell)] : updateVectors vectors [(size, cell)] size size'
cell = terminalCell token
updateVectors :: [Vector] -> Vector -> Int -> Int -> [Vector]
updateVectors [] _ _ _ = []
updateVectors (row:rows) col nrow ncol
| scProduct == Map.empty = row : updateVectors rows col nrow' ncol
| otherwise = (row++[(ncol,scProduct)]) : updateVectors rows ((nrow',scProduct):col) nrow' ncol
where scProduct = scalarProduct row col
nrow' = nrow - 1
scalarProduct :: Vector -> Vector -> Cell
scalarProduct [] _ = Map.empty
scalarProduct _ [] = Map.empty
scalarProduct as@((i,a):as') bs@((j,b):bs')
= case compare i j of
LT -> scalarProduct as' bs
GT -> scalarProduct as bs'
EQ -> scalarProduct as' bs' `joinCell` binProduct a b
joinCell :: Cell -> Cell -> Cell
joinCell a b = Map.unionsWith (++) [a, b]
terminalCell :: String -> Cell
terminalCell term = Map.fromList [ (cat, treesFor cat) |
cat <- lexicon Map.! term ]
where treesFor cat = [cat:^[Leaf term]]
binProduct :: Cell -> Cell -> Cell
binProduct acell bcell = Map.unionsWith (++) [ Map.fromList [(c, [c:^ (atree++btree) ])] |
(a, atree) <- Map.toList acell,
(b, btree) <- Map.toList bcell,
c <- applyRules a b ]
| agrasley/HaskellCCG | Parser.hs | mit | 2,437 | 0 | 15 | 768 | 966 | 519 | 447 | 53 | 6 |
import System.IO
import System.Directory (doesFileExist)
import System.Console.ANSI
import Control.Monad
import Control.Monad.Trans
import qualified Data.Map.Strict as M
import Data.List (intercalate)
import Language.HLisp.Expr
import Language.HLisp.Parse
import Language.HLisp.Eval
import Language.HLisp.Prim
import Language.HLisp.Prelude
-- test
consoleColor color act = do
setSGR [SetColor Foreground Vivid color]
act
setSGR [Reset]
consoleWarn = consoleColor Red
consoleOkay = consoleColor Green
consoleInfo = consoleColor White
main = do
hSetBuffering stdout NoBuffering
setSGR [SetColor Foreground Vivid White, SetUnderlining SingleUnderline]
putStrLn "HLisp v0.01"
setSGR [Reset]
-- add primitives to global env here
let globalEnv = registerPrimitives hlispPrelude hlispPrimitives
mainLoop ((),globalEnv,[])
mainLoop state@(userState, lispState, lispStack) = do
putStr ">> "
line <- getLine
case words line of
-- repl commands
[] -> mainLoop state
("quit":_) -> return ()
("globals":_) -> do
let userGlobals = filter isUserGlobal $ M.toList lispState
if length userGlobals > 0
then do
let userBinds = map fst userGlobals
liftIO $ consoleOkay $ putStr "User-defined globals: "
liftIO $ putStrLn $ intercalate " " userBinds
mainLoop state
else do
liftIO $ consoleWarn $ putStrLn "No user-defined globals."
mainLoop state
("clearglobals":_) -> do
let lispState' = M.fromList $ filter (not . isUserGlobal) $ M.toList lispState
liftIO $ consoleOkay $ putStrLn "Removed all user-defined globals."
mainLoop (userState, lispState', lispStack)
("info":bind:_) -> do
case M.lookup bind lispState of
Just val -> do
liftIO $ consoleInfo $ putStr bind
liftIO $ putStrLn $ " : " ++ (show val)
mainLoop state
Nothing -> do
liftIO $ consoleWarn $ putStr $ "No binding found for "
liftIO $ consoleInfo $ putStrLn $ bind ++ "."
mainLoop state
("load":file:_) -> do
fileExists <- doesFileExist file
if fileExists
then do
withFile file ReadMode $ \h -> do
filestr <- hGetContents h
case parseLispFile filestr of
Left err -> do
liftIO $ putStrLn $ show err
mainLoop state
Right exprs -> do
let exprList = LispList exprs
(result, state') <- runLisp state exprList
case result of
Left err -> do
liftIO $ consoleWarn $ putStrLn err
mainLoop state'
Right _ -> do
liftIO $ consoleOkay $ putStrLn "File loaded."
mainLoop state'
else do
liftIO $ consoleWarn $ putStrLn "File doesn't exist!"
mainLoop state
("help":_) -> do
liftIO $ consoleInfo $ putStrLn "Available commands:"
let cmds = [("globals", "show all user-defined globals")
, ("load [file]", "load and execute an HLisp file")
, ("clearglobals", "remove all globals")
, ("quit", "exit repl")]
forM cmds printCmd
mainLoop state
where printCmd (cmd,def) = liftIO $ do
putStr "- "
consoleInfo $ putStr $ cmd ++ ": "
putStrLn def
-- a lisp command
otherwise -> do
case parseLisp line of
Left err -> do
liftIO $ putStrLn $ show err
mainLoop state
Right expr -> do
(result, state') <- runLisp state expr
case result of
Left err -> do
liftIO $ consoleWarn $ putStrLn err
mainLoop state'
-- don't print anything for unit values
Right LispUnit -> do
mainLoop state'
Right val -> do
liftIO $ putStrLn $ show val
mainLoop state'
where isPrim (LispPrimFunc _ _) = True
isPrim _ = False
isUserGlobal (key,val) = not $ isPrim val
| rolph-recto/HLisp | src/HLisp.hs | mit | 4,172 | 0 | 30 | 1,416 | 1,190 | 566 | 624 | 111 | 17 |
module Sequences.Special (
gs1,
gs2,
z,
f
) where
import Sequences.General
gs1 :: Sequence Double
gs1 = recSequence 1 (\n0 -> 1 / (1 + n0))
gs2 :: Sequence Double
gs2 = recSequence (1 / (sqrt 2)) (\n0 -> 1 / (sqrt (2 + n0)))
z :: Sequence Double
z = expSequence (\n -> 1 / (fromInteger . fac $ n))
fac :: Integer -> Integer
fac 1 = 1
fac n | n > 0 = n * (fac (n - 1))
| otherwise = error "fac is only defined for Integers bigger then 0"
f :: Sequence Double
f = expSequence (\n -> let
{- n is starting at 1 but fibs list is starting at 0, so n needs to be converted to be
zero based. (!!) operator only accepts Int arguments. Because n is from type Integer
it needs to be converted. -}
zeroBasedIntN = fromInteger (n - 1) --
in
(dFibs !! zeroBasedIntN) / (dFibs !! (zeroBasedIntN + 1)))
where
dFibs :: Sequence Double
dFibs = map fromInteger fibs
fibs :: Sequence Integer
fibs = 1 : 1 : zipWith (+) fibs (tail fibs) | DevWurm/numeric-sequences-haskell | src/Sequences/Special.hs | mit | 1,127 | 0 | 14 | 400 | 349 | 186 | 163 | 24 | 1 |
-- GENERATED by C->Haskell Compiler, version 0.16.4 Crystal Seed, 24 Jan 2009 (Haskell)
-- Edit the ORIGNAL .chs file instead!
{-# LINE 1 "Input.chs" #-}{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# context lib="hyd" #-}
module Hyd.Input where
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Control.Monad
import Control.Applicative
import Data.Functor
import Hyd.Texture
data HydInputPreset = HydInputPreset
{ name'hyd_input_preset :: String
}
instance Storable HydInputPreset where
sizeOf _ = 40
{-# LINE 23 "Input.chs" #-}
alignment _ = 8
{-# LINE 24 "Input.chs" #-}
peek p = HydInputPreset
<$> ((\ptr -> do {peekByteOff ptr 0 ::IO (Ptr CChar)}) p)
poke p x = do
(\ptr val -> do {pokeByteOff ptr 0 (val::(Ptr CChar))}) p (name'hyd_input_preset x)
type HydInputPresetPtr = Ptr (HydInputPreset)
{-# LINE 30 "Input.chs" #-}
withT = with
hydInputPresetGetActionValue :: HydInputPreset -> String -> IO (Int)
hydInputPresetGetActionValue a1 a2 =
withT a1 $ \a1' ->
withCString a2 $ \a2' ->
hydInputPresetGetActionValue'_ a1' a2' >>= \res ->
let {res' = fromIntegral res} in
return (res')
{-# LINE 37 "Input.chs" #-}
hydInputGetMaxValue :: IO (Int)
hydInputGetMaxValue =
hydInputGetMaxValue'_ >>= \res ->
let {res' = fromIntegral res} in
return (res')
{-# LINE 40 "Input.chs" #-}
foreign import ccall safe "Input.chs.h hyd_input_preset_get_action_value"
hydInputPresetGetActionValue'_ :: ((HydInputPresetPtr) -> ((Ptr CChar) -> (IO CUShort)))
foreign import ccall safe "Input.chs.h hyd_input_get_max_value"
hydInputGetMaxValue'_ :: (IO CUShort)
| Smilex/hyd_engine | bindings/haskell/Hyd/Input.hs | mit | 1,647 | 11 | 17 | 265 | 424 | 233 | 191 | -1 | -1 |
module Main (main) where
import GradientAscentDemo
import UtilDemo
main :: IO ()
main = runUtilDemos >> runGradientAscentDemos
| rcook/mlutil | ch05-logistic-regression/src/Main.hs | mit | 149 | 0 | 6 | 39 | 34 | 20 | 14 | 5 | 1 |
import Control.Applicative ((<$>))
import Control.Monad (unless)
import Data.List (transpose)
import qualified Data.Text as T
import Debug.Trace (traceShowM)
import System.Environment (getArgs)
-- Picross solver implemented in Haskell
-- Sell examples directory for examples of input
type Hints = [Int]
data Field = Unknown | Empty | Marked
deriving (Eq)
instance Show Field where
show Unknown = " "
show Empty = "."
show Marked = "#"
showList fs s = s ++ "[" ++ concatMap show fs ++ "]"
data Board = Board { xhints :: [Hints]
, yhints :: [Hints]
, fields :: [[Field]]
, xdim :: Int
, ydim :: Int
}
deriving (Eq)
instance Show Board where
show b = unlines $ alignRight $
map (++" ") xh ++
zipWith (++) ("" : yh ++ [""]) flines
where formatHints :: Hints -> String
formatHints = unwords . map show
padLeft n s = replicate d ' ' ++ s
where d = n - length s
alignRight :: [String] -> [String]
alignRight ss = map (padLeft ml) ss
where ml = maximum $ map length ss
blines = map (concatMap show) $ fields b
flines = ["┌" ++ replicate (xdim b) '─' ++ "┐"] ++
map (\l -> "│" ++ l ++ "│") blines ++
["└" ++ replicate (xdim b) '─' ++ "┘"]
yh :: [String]
yh = alignRight $ map formatHints $ yhints b
xh :: [String]
xh = transpose $ alignRight $ map formatHints $ xhints b
loadFile :: FilePath -> IO Board
loadFile fileName = do ls <- lines <$> readFile fileName
let (xhs, _ : yhs) = break (== "---") ls
let (xd, yd) = (length xhs, length yhs)
let fs = replicate yd $ replicate xd Unknown
return Board { xhints = map readHint xhs, yhints = map readHint yhs, fields = fs, xdim = xd, ydim = yd }
where readHint :: String -> [Int]
readHint = map (read . T.unpack) . T.splitOn (T.pack " ") . T.pack
-- What are all possible ways we can place the given hints in a row of size n?
allPossiblePlacements :: Hints -> Int -> [[Field]]
allPossiblePlacements [] n = [ replicate n Empty ]
allPossiblePlacements (h:hs) n | h > n = []
| h == n && null hs = [ replicate h Marked ]
| otherwise = map (Empty :) (allPossiblePlacements (h:hs) (n-1)) ++
map ((replicate h Marked ++ [Empty]) ++) (allPossiblePlacements hs (n-h-1))
-- Are two rows compatible with each other?
isCompatiblePlacement :: [Field] -> [Field] -> Bool
isCompatiblePlacement a b = and $ zipWith (\x y -> x == y || x == Unknown || y == Unknown) a b
-- Determine which spots we're sure of.
determineCommonalities :: [[Field]] -> [Field]
determineCommonalities fs = map commonality $ transpose fs
where commonality xs | all (== Marked) xs = Marked
| all (== Empty) xs = Empty
| otherwise = Unknown
-- Put down the fields that we know for sure based on the currently marked fields and hints.
placeGuaranteedFields :: Hints -> [Field] -> Int -> [Field]
placeGuaranteedFields hs r n = determineCommonalities $ filter (isCompatiblePlacement r) $ allPossiblePlacements hs n
-- Go through all rows, and mark any fields we're sure of.
placeGuaranteedRows :: Board -> Board
placeGuaranteedRows b = b { fields = zipWith3 placeGuaranteedFields (yhints b) (fields b) (repeat $ ydim b) }
-- Go through all columns, and mark any fields we're sure of.
placeGuaranteedCols :: Board -> Board
placeGuaranteedCols b = b { fields = transpose $ zipWith3 placeGuaranteedFields (xhints b) (transpose $ fields b) (repeat $ xdim b) }
solve :: Board -> IO Board
solve b = do let b' = placeGuaranteedRows b
unless (b == b') $ traceShowM b
let b'' = placeGuaranteedCols b'
unless (b' == b'') $ traceShowM b'
if b /= b''
then solve b''
else return b
isSolved :: Board -> Bool
isSolved = not . any (elem Unknown) . fields
processFile :: FilePath -> IO ()
processFile fileName = do b <- loadFile fileName
s <- solve b
traceShowM s
unless (isSolved s) $ putStrLn "Board could not be solved using known methods."
return ()
main :: IO ()
main = do files <- getArgs
mapM_ processFile files
| Eckankar/picross-solver | picross.hs | mit | 4,731 | 0 | 15 | 1,623 | 1,511 | 781 | 730 | 85 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module App
( app
) where
import Control.Monad.Except (runExceptT)
import Control.Monad.Reader (asks, liftIO, ReaderT)
import Data.ByteString.Char8 (pack)
import Data.Time.Clock (getCurrentTime)
import Database.Persist.Postgresql ((=.), entityKey, entityVal, get, getBy, insertBy,
selectFirst, selectList, updateGet, ConnectionPool, SelectOpt(..))
import Network.HTTP.Client (defaultManagerSettings, newManager)
import Servant
import Servant.Auth.Client (Token(..))
import Servant.Client (parseBaseUrl)
import AuthAPI.Client (authAPIClient)
import Config (Config(..))
import DirectoryAPI.API (directoryAPIProxy, DirectoryAPI)
import Models (runDB, EntityField(..), File(..), Node(..), NodeId, Unique(..))
-- Type alias custom monad to handle passing our configuration around
type App = ReaderT Config Handler
appToServer :: Config -> Server DirectoryAPI
appToServer cfg = enter (runReaderTNat cfg) server
app :: ConnectionPool -> IO Application
app pool = do
manager <- newManager defaultManagerSettings
authBase <- parseBaseUrl "http://auth-service:8080"
pure $ serve directoryAPIProxy (appToServer $ Config pool manager authBase)
server :: ServerT DirectoryAPI App
server = ls :<|> whereis :<|> roundRobinNode :<|> registerFileServer
-- Return all file records from the database
ls :: Maybe String -> App [File]
ls maybeToken = authenticate maybeToken $
(entityVal <$>) <$> runDB (selectList [] [])
findFile :: FilePath -> App (Maybe File)
findFile path = do
maybeFile <- runDB $ getBy $ UniquePath path
case maybeFile of
Nothing -> pure Nothing
Just file -> pure $ Just $ entityVal file
-- Return the primary node that the file is stored on
whereis :: Maybe String -> FilePath -> App Node
whereis maybeToken path = authenticate maybeToken $ do
maybeFile <- findFile path
case maybeFile of
Nothing -> throwError err404 -- File path does not exist
Just file -> do
maybeNode <- runDB . get . fileNode $ file
case maybeNode of
Nothing -> throwError err500 { errBody = "File node is no longer accessible" }
Just node -> pure node
-- Primary node that the file is stored on or the next round robin primary
roundRobinNode :: Maybe String -> FilePath -> App Node
roundRobinNode maybeToken path = authenticate maybeToken $ do
maybeFile <- findFile path
case maybeFile of
Nothing -> do
maybeLeastRecentNode <- runDB $ selectFirst [] [Asc NodeStoredAt] -- Sort nodes by date ascending to find LRU
case maybeLeastRecentNode of
Nothing -> throwError err500 { errBody = "No nodes registered with directory service" }
Just leastRecentNode -> do
currentTime <- liftIO getCurrentTime
runDB $ updateGet (entityKey leastRecentNode) [NodeStoredAt =. currentTime]
Just file -> do
maybeNode <- runDB $ get (fileNode file)
case maybeNode of
Nothing -> throwError err500 { errBody = "File found but no node found" }
Just node -> pure node
registerFileServer :: Int -> App NodeId
registerFileServer port = do
currentTime <- liftIO getCurrentTime -- Node last stored at time, default current time
newOrExistingNode <- runDB $ insertBy Node { nodePort = port, nodeStoredAt = currentTime }
case newOrExistingNode of
Left existingNode -> pure $ entityKey existingNode
Right newNode -> pure newNode
-- General authentication function, performs action only when succesfully authenticated
authenticate :: Maybe String -> App a -> App a
authenticate Nothing _ = throwError err401 { errBody = "No authentication token provided" }
authenticate (Just token) action = do
manager <- asks manager
authBase <- asks authBase
response <- liftIO $ runExceptT $ verifyJWT (Token $ pack token) manager authBase -- Verify token
case response of
Left _ -> throwError err401 { errBody = "Invalid authentication token" }
Right _ -> action
-- Pattern match out the routes of the AuthAPI
_ :<|> _ :<|> verifyJWT = authAPIClient
| houli/distributed-file-system | directory-service/src/App.hs | mit | 4,046 | 0 | 21 | 790 | 1,100 | 565 | 535 | 79 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputschema.html
module Stratosphere.ResourceProperties.KinesisAnalyticsApplicationInputSchema where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationRecordColumn
import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationRecordFormat
-- | Full data type definition for KinesisAnalyticsApplicationInputSchema. See
-- 'kinesisAnalyticsApplicationInputSchema' for a more convenient
-- constructor.
data KinesisAnalyticsApplicationInputSchema =
KinesisAnalyticsApplicationInputSchema
{ _kinesisAnalyticsApplicationInputSchemaRecordColumns :: [KinesisAnalyticsApplicationRecordColumn]
, _kinesisAnalyticsApplicationInputSchemaRecordEncoding :: Maybe (Val Text)
, _kinesisAnalyticsApplicationInputSchemaRecordFormat :: KinesisAnalyticsApplicationRecordFormat
} deriving (Show, Eq)
instance ToJSON KinesisAnalyticsApplicationInputSchema where
toJSON KinesisAnalyticsApplicationInputSchema{..} =
object $
catMaybes
[ (Just . ("RecordColumns",) . toJSON) _kinesisAnalyticsApplicationInputSchemaRecordColumns
, fmap (("RecordEncoding",) . toJSON) _kinesisAnalyticsApplicationInputSchemaRecordEncoding
, (Just . ("RecordFormat",) . toJSON) _kinesisAnalyticsApplicationInputSchemaRecordFormat
]
-- | Constructor for 'KinesisAnalyticsApplicationInputSchema' containing
-- required fields as arguments.
kinesisAnalyticsApplicationInputSchema
:: [KinesisAnalyticsApplicationRecordColumn] -- ^ 'kaaisRecordColumns'
-> KinesisAnalyticsApplicationRecordFormat -- ^ 'kaaisRecordFormat'
-> KinesisAnalyticsApplicationInputSchema
kinesisAnalyticsApplicationInputSchema recordColumnsarg recordFormatarg =
KinesisAnalyticsApplicationInputSchema
{ _kinesisAnalyticsApplicationInputSchemaRecordColumns = recordColumnsarg
, _kinesisAnalyticsApplicationInputSchemaRecordEncoding = Nothing
, _kinesisAnalyticsApplicationInputSchemaRecordFormat = recordFormatarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputschema.html#cfn-kinesisanalytics-application-inputschema-recordcolumns
kaaisRecordColumns :: Lens' KinesisAnalyticsApplicationInputSchema [KinesisAnalyticsApplicationRecordColumn]
kaaisRecordColumns = lens _kinesisAnalyticsApplicationInputSchemaRecordColumns (\s a -> s { _kinesisAnalyticsApplicationInputSchemaRecordColumns = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputschema.html#cfn-kinesisanalytics-application-inputschema-recordencoding
kaaisRecordEncoding :: Lens' KinesisAnalyticsApplicationInputSchema (Maybe (Val Text))
kaaisRecordEncoding = lens _kinesisAnalyticsApplicationInputSchemaRecordEncoding (\s a -> s { _kinesisAnalyticsApplicationInputSchemaRecordEncoding = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputschema.html#cfn-kinesisanalytics-application-inputschema-recordformat
kaaisRecordFormat :: Lens' KinesisAnalyticsApplicationInputSchema KinesisAnalyticsApplicationRecordFormat
kaaisRecordFormat = lens _kinesisAnalyticsApplicationInputSchemaRecordFormat (\s a -> s { _kinesisAnalyticsApplicationInputSchemaRecordFormat = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsApplicationInputSchema.hs | mit | 3,515 | 0 | 13 | 266 | 354 | 207 | 147 | 36 | 1 |
-- File: ch3/exB5.hs
-- A function that determined if a given list is a palindrome.
isPalindrome :: Eq a => [a] -> Bool
isPalindrome [] = True
isPalindrome [x] = True
isPalindrome xs = (head xs == last xs) && (isPalindrome . init . tail $ xs)
| friedbrice/RealWorldHaskell | ch3/exB5.hs | gpl-2.0 | 246 | 0 | 9 | 50 | 83 | 43 | 40 | 4 | 1 |
module T where
import Tests.KesterelBasis
-- Berry p130, parallel schizophrenia.
sustainE' s = loopE (emitE s >>> (nothingE |||| pauseE))
e sustain = unitA >>>
(signalE $ \s ->
(sustain s) |||| pauseE)
c = runE (e sustainE)
c' = runE (e sustainE')
prop_correct = property (\xs -> simulate c xs == simulate c' xs)
test_constructive0 = isJust (isConstructive c)
test_constructive1 = isNothing (isConstructive c')
ok_netlist0 = runNL c
ok_netlist1 = runNL c'
| peteg/ADHOC | Tests/08_Kesterel/110_sustain_parallel_nothing_schizo.hs | gpl-2.0 | 472 | 0 | 11 | 89 | 174 | 90 | 84 | 13 | 1 |
module Parser
(Parser, parseString, parseFile)
where
import Text.Parsec
type Parser a = Parsec String () a
parseString :: Parser a -> String -> a
parseString p str =
case parse p "" str of
Left e -> error $ show e
Right r -> r
parseFile :: Parser a -> String -> IO a
parseFile p file = do
contents <- readFile file
case parse p file contents of
Left e -> print e >> fail "parse error"
Right r -> return r
| cryptica/slapnet | src/Parser.hs | gpl-3.0 | 486 | 0 | 11 | 164 | 182 | 88 | 94 | 15 | 2 |
-- | Feature extraction for results data. These features and their associated match outcomes can be used to
-- train classifiers that attempt to predict results.
module Anorak.FeatureExtractor (generateFeatures,
MatchFeatures(..),
Outcome,
TeamFeatures(..)) where
import Anorak.Results(Result(..), Team)
import Anorak.RLTParser(LeagueData(..), parseRLTFile)
import Data.Map(Map, (!))
import qualified Data.Map as Map(empty, insert, lookup, member)
-- | There are only three possible outcomes for a match.
data Outcome = HomeWin | Draw | AwayWin deriving (Show)
-- | Team features consist of four values, the weighted win ratio, weighted draw ratio then weighted score and concede ratios.
-- Values take into account all previous matches but each time a new result is added, the influence of previous results is
-- discounted. The most recent result accounts for 25% of the value, second most recent result is 0.75 * 25% or 18.75%, and
-- so on.
data TeamFeatures = TeamFeatures Double Double Double Double
-- | Team features are written out as tab-separted data with 4 columns: win rate, draw rate, score rate and concede rate.
instance Show TeamFeatures where
show (TeamFeatures w d f a) = show w ++ "\t" ++ show d ++ "\t" ++ show f ++ "\t" ++ show a
data MatchFeatures = MatchFeatures (TeamFeatures, TeamFeatures) (TeamFeatures, TeamFeatures) Outcome
-- | Match features are just the home team and away team features combined, giving 16 tab-separated columns.
instance Show MatchFeatures where
show (MatchFeatures (h, hh) (a, aa) o) = show h ++ "\t" ++ show hh ++ "\t" ++ show a ++ "\t" ++ show aa ++ "\t" ++ show o
generateFeatures :: FilePath -> IO ()
generateFeatures dataFile = do LeagueData _ res _ _ _ _ _ <- parseRLTFile dataFile
let features = extractFeatures res Map.empty Map.empty Map.empty
mapM_ print features
-- | Given a list of results, return a list of features and associated match outcomes.
extractFeatures :: [Result] -> Map Team TeamFeatures -> Map Team TeamFeatures -> Map Team TeamFeatures -> [MatchFeatures]
extractFeatures [] _ _ _ = []
extractFeatures (r@(Result _ hteam _ ateam _ _ _):rs) overall home away
-- If we don't have features for the teams involved we initialise them from this result, but we can't generate
-- match features from nothing so we skip the result and continue with subsequent results.
| not $ haveFeatures hteam ateam overall home away = otherFeatures
| otherwise = getResultFeatures r overall home away : otherFeatures
where otherFeatures = extractFeatures rs (updateRecords ateam r $ updateRecords hteam r overall) (updateRecords hteam r home) (updateRecords ateam r away)
haveFeatures :: Team -> Team -> Map Team TeamFeatures -> Map Team TeamFeatures -> Map Team TeamFeatures -> Bool
haveFeatures hteam ateam overall home away = Map.member hteam overall && Map.member ateam overall && Map.member hteam home && Map.member ateam away
-- | After processing a result, we add it to the form records of the teams involved so that it can be used as
-- form data for subsequent matches.
updateRecords :: Team -> Result -> Map Team TeamFeatures -> Map Team TeamFeatures
updateRecords team result teamRecords = Map.insert team features teamRecords
where features = case Map.lookup team teamRecords of
Nothing -> initialFeatures team result
Just f -> addResultToFeatures team f result
-- | Create the intial team features from a team's first result.
initialFeatures :: Team -> Result -> TeamFeatures
initialFeatures team (Result _ ht hg _ ag _ _)
| hg == ag = TeamFeatures 0 1 (fromIntegral hg) (fromIntegral ag)
| team == ht && hg > ag = TeamFeatures 1 0 (fromIntegral hg) (fromIntegral ag)
| team == ht && hg < ag = TeamFeatures 0 0 (fromIntegral hg) (fromIntegral ag)
| ag > hg = TeamFeatures 1 0 (fromIntegral ag) (fromIntegral hg)
| otherwise = TeamFeatures 0 0 (fromIntegral ag) (fromIntegral hg)
-- | Update a team's form record with the result of the specified match.
addResultToFeatures :: Team -> TeamFeatures -> Result -> TeamFeatures
addResultToFeatures team features (Result _ hteam hgoals ateam agoals _ _)
| team == hteam = addScoreToFeatures features hgoals agoals
| team == ateam = addScoreToFeatures features agoals hgoals
| otherwise = features
addScoreToFeatures :: TeamFeatures -> Int -> Int -> TeamFeatures
addScoreToFeatures (TeamFeatures w d f a) scored conceded
| scored > conceded = TeamFeatures (w * 0.75 + 0.25) (d * 0.75) forRate againstRate
| scored == conceded = TeamFeatures (w * 0.75) (d * 0.75 + 0.25) forRate againstRate
| otherwise = TeamFeatures (w * 0.75) (d * 0.75) forRate againstRate
where forRate = f * 0.75 + fromIntegral scored * 0.25
againstRate = a * 0.75 + fromIntegral conceded * 0.25
-- | Get the form data and match outcome for a given result.
getResultFeatures :: Result -> Map Team TeamFeatures -> Map Team TeamFeatures -> Map Team TeamFeatures -> MatchFeatures
getResultFeatures result overallRecords homeRecords awayRecords = MatchFeatures homeRecord awayRecord (getOutcome result)
where homeRecord = (overallRecords ! homeTeam result, homeRecords ! homeTeam result)
awayRecord = (overallRecords ! awayTeam result, awayRecords ! awayTeam result)
-- | Maps a result to one of three possible outcome types (home win, away win or draw).
getOutcome :: Result -> Outcome
getOutcome (Result _ _ hgoals _ agoals _ _)
| hgoals > agoals = HomeWin
| agoals > hgoals = AwayWin
| otherwise = Draw
| dwdyer/anorak | src/haskell/Anorak/FeatureExtractor.hs | gpl-3.0 | 6,136 | 0 | 14 | 1,628 | 1,481 | 748 | 733 | 60 | 2 |
module Core.ClassFoo (
Foo(..)
) where
class Foo a where
foo :: a -> Char
instance Foo Bool where
foo True = 't'
foo False = 'f'
| adarqui/ToyBox | haskell/Core/src/Core/ClassFoo.hs | gpl-3.0 | 135 | 0 | 7 | 33 | 57 | 31 | 26 | 7 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
import Yesod
data Links = Links
mkYesod "Links" [parseRoutes|
/ HomeR GET
/page1 Page1R GET
/page2 Page2R GET
|]
instance Yesod Links
getHomeR = defaultLayout [whamlet|<a href=@{HomeR}>Go to Home!|]
getPage1R = defaultLayout [whamlet|<a href=@{Page1R}>Go to page 1!|]
getPage2R = defaultLayout [whamlet|<a href=@{Page2R}>Go to page 2!|]
main = warp 3000 Links
| prannayk/conj | Learning/Yesod/Links.hs | gpl-3.0 | 520 | 0 | 5 | 99 | 80 | 49 | 31 | 12 | 1 |
{-# LANGUAGE UndecidableInstances #-}
module Syntax.Pretty where
import Common
import Pretty
import Syntax.Types
data SyntaxKind = SKText | SKOper | SKSep | SKLBracket | SKRBracket | SKColon
deriving (Eq, Ord, Show)
instance TokenKind SyntaxKind where
space _ SKSep = False
space SKLBracket _ = False
space _ SKRBracket = False
space _ SKColon = False
space _ _ = True
nameIsText :: String -> Bool
nameIsText [] = error "Empty name in nameIsText"
nameIsText (x : _) = x == '_' || isAlpha x
t1 :: (MonadWriter [Token SyntaxKind] m) => SyntaxKind -> String -> m ()
t1 sk xs = tell [Word xs sk]
colon = t1 SKColon ":"
semi = t1 SKSep ";"
tt :: (MonadWriter [Token SyntaxKind] m) => String -> m ()
tt = t1 SKText
tellBrackets :: (MonadWriter [Token SyntaxKind] m) => String -> String -> m () -> m ()
tellBrackets lb rb m = do
t1 SKLBracket lb
m
t1 SKRBracket rb
instance (Pretty (Expr (TyTag k)) SyntaxKind, Pretty (Expr k) SyntaxKind)
=> Pretty (Binder k) SyntaxKind where
tokens (Binder name Nothing) = tokens name
tokens (Binder name (Just ty)) = tellBrackets "(" ")" $ do
tokens name
colon
tokens ty
instance (Pretty (Expr (TyTag k)) SyntaxKind, Pretty (Expr k) SyntaxKind)
=> Pretty (Binding k) SyntaxKind where
tokens (Binding (Binder name ty) rhs) = do
tokens name
whenJust ty $ \ty -> colon >> tokens ty
tt "is"
tokens rhs
instance Pretty BindName SyntaxKind where
tokens b = case b of
BindName _ xs -> f xs
UniqueName _ n info -> f $ (uniqueOrigName ^$ info) ++ "_" ++ show n
where
f xs =
if nameIsText xs
then tell [Word xs SKText]
else tell [Word ("(" ++ xs ++ ")") SKOper]
instance Pretty (Decl t) SyntaxKind where
tokens (ValField _ name ty) = do
tt "val" -- TODO no "val" when inside a val record
tokens name
colon
tokens ty
semi
tokens (TyField _ name bound) = do
tt "type"
tokens name
whenJust bound $ \(TyBound _ op ty) -> do
tokens op
tokens ty
semi
tokens (ModField _ name ty) = do
tt "module"
tokens name
colon
tokens ty
semi
tokens (Constraint _ a op b) = do
tt "with"
tokens a
tokens op
tokens b
tokens (BindLocal _ b) = tokens b
tokens (BindMod _ b) = tt "module" >> tokens b
tokens (BindSig _ b) = tt "sig" >> tokens b
tokens (BindVal _ b) = tt "val" >> tokens b
tokens (BindTy _ b) = tt "type" >> tokens b
tokens (Infix _ assoc prec bs) = do
tt "infix"
case assoc of
InfixLeft -> tt "left"
InfixRight -> tt "right"
InfixNone -> return ()
tt $ show prec
mapM_ tokens bs
semi
tokens (Data _ mode name parent ty) = do
tt "data"
when (mode == DataOpen) $ tt "open"
tokens name
whenJust parent $ \parent -> t1 SKOper "<:" >> tokens parent
case ty of
Lit _ TyEmpty -> return ()
_ -> tt "is" >> tokens ty
semi
instance Pretty TyCompOp SyntaxKind where
tokens op = t1 SKOper $ case op of
OpSubTy -> "<:"
OpSuperTy -> ">:"
OpEqualTy -> ":"
instance Pretty (Expr t) SyntaxKind where
tokens (Lam _ ps e) = tellBrackets "(" ")" $ do
tt "fn"
mapM_ tokens ps
t1 SKOper "->"
tokens e
tokens (App _ e es) = tokens e >> mapM_ tokens es
tokens (Record _ ds) = do
tt "rec"
tellBrackets "{" "}" $ mapM_ tokens ds
tokens (Ref _ name) = tokens name
tokens (Member _ e names) = do
tokens e
mapM_ (\name -> t1 SKOper "." >> tokens name) names
tokens (OpChain _ x xs o) = f $ mapM_ (\(o, e) -> tokens o >> tokens e) xs
where
f = case (x, o) of
(Nothing, Nothing) -> tellBrackets "(" ")"
(Nothing, Just o) -> tellBrackets "(" ")" . (>> tokens o)
(Just x, Nothing) -> (tokens x >>)
(Just x, Just o) -> tellBrackets "(" ")" . (tokens x >>) . (>> tokens o)
tokens (Let _ ds e) = tellBrackets "(" ")" $ do
tt "let"
tellBrackets "{" "}" $ mapM_ tokens ds
tt "in"
tokens e
tokens (ToDo _) = t1 SKOper "?"
tokens (LamCase _ cs) = do
tt "fn"
tellBrackets "{" "}" $ mapM_ tokens cs
tokens (Case _ e cs) = do
tt "case"
tokens e
tt "of"
tellBrackets "{" "}" $ mapM_ tokens cs
tokens (Do _ es) = tt "do" >> tellBrackets "{" "}" (mapM_ tokens es)
tokens (Lit _ lit) = tokens lit
instance Pretty (Lit t) SyntaxKind where
-- TODO figure out how to get the arrows to appear infix
tokens TyFn = tt "(->)"
tokens TyAuto = t1 SKOper "*"
tokens TyEmpty = tt "(#?EMPTY?#)"
tokens KVal = todo
tokens KMod = todo
tokens KValFn = todo
tokens KModFn = todo
tokens (LInt n) = tt $ show n
tokens (LFloat (a :% b)) = tellBrackets "(" ")" $ do
tt $ show a
t1 SKOper "/"
tt $ show b
-- TODO escape properly
tokens (LString xs) = tt $ "\"" ++ xs ++ "\""
-- TODO escape properly
tokens (LChar x) = tt $ "'" ++ [x] ++ "'"
instance Pretty CaseClause SyntaxKind where
tokens (CaseClause _ pat expr) = do
tt "if"
tokens pat
tt "then"
tokens expr
semi
instance Pretty DoElem SyntaxKind where
tokens (DoLet _ ds) = do
tt "let"
tellBrackets "{" "}" (mapM_ tokens ds)
semi
tokens (DoBind _ pat expr) = do
tokens pat
t1 SKOper "<-"
tokens expr
semi
tokens (DoExpr _ expr) = do
tokens expr
semi
instance Pretty Pat SyntaxKind where
tokens (PatParams _ ps) = mapM_ tokens ps
tokens (PatBind _ name) = tokens name
tokens (PatApp _ expr ps) = tellBrackets "(" ")" $ do
tokens expr
mapM_ tokens ps
tokens (PatLit _ lit) = tokens lit
tokens (PatIgnore _) = tt "_"
| ktvoelker/FLang | src/Syntax/Pretty.hs | gpl-3.0 | 5,587 | 0 | 14 | 1,559 | 2,449 | 1,147 | 1,302 | -1 | -1 |
{-|
Description: Helpers for interacting with the graph database. Incomplete.
This module is responsible for inserting values associated with the graphs
into the database. These functions are just helpers for the main function
in "Svg.Parser", though it is possible to put all of the data retrieval code in
here as well at some point in the future.
-}
module Svg.Database
(insertGraph, insertElements, deleteGraphs) where
import qualified Data.Text as T
import Database.Persist.Sqlite
import Database.Tables hiding (graphDynamic, graphHeight, graphWidth, paths, shapes, texts)
-- | Insert a new graph into the database, returning the key of the new graph.
insertGraph :: T.Text -- ^ The title of the graph that is being inserted.
-> Double -- ^ The width dimension of the graph
-> Double -- ^ The height dimension of the graph
-> Bool -- ^ True if graph is dynamically generated
-> SqlPersistM GraphId -- ^ The unique identifier of the inserted graph.
insertGraph graphName graphWidth graphHeight graphDynamic = do
runMigration migrateAll
insert (Graph graphName graphWidth graphHeight graphDynamic)
-- | Insert graph components into the database.
insertElements :: ([Path], [Shape], [Text]) -> SqlPersistM ()
insertElements (paths, shapes, texts) = do
mapM_ insert_ shapes
mapM_ insert_ paths
mapM_ insert_ texts
-- | Delete graphs from the database.
deleteGraphs :: SqlPersistM ()
deleteGraphs = do
runMigration migrateAll
deleteWhere ([] :: [Filter Graph])
deleteWhere ([] :: [Filter Text])
deleteWhere ([] :: [Filter Shape])
deleteWhere ([] :: [Filter Path])
| Courseography/courseography | app/Svg/Database.hs | gpl-3.0 | 1,671 | 0 | 10 | 342 | 304 | 165 | 139 | 25 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.FirebaseRules.Projects.Releases.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Create a \`Release\`. Release names should reflect the developer\'s
-- deployment practices. For example, the release name may include the
-- environment name, application name, application version, or any other
-- name meaningful to the developer. Once a \`Release\` refers to a
-- \`Ruleset\`, the rules can be enforced by Firebase Rules-enabled
-- services. More than one \`Release\` may be \'live\' concurrently.
-- Consider the following three \`Release\` names for \`projects\/foo\` and
-- the \`Ruleset\` to which they refer. Release Name | Ruleset Name
-- --------------------------------|-------------
-- projects\/foo\/releases\/prod | projects\/foo\/rulesets\/uuid123
-- projects\/foo\/releases\/prod\/beta | projects\/foo\/rulesets\/uuid123
-- projects\/foo\/releases\/prod\/v23 | projects\/foo\/rulesets\/uuid456
-- The table reflects the \`Ruleset\` rollout in progress. The \`prod\` and
-- \`prod\/beta\` releases refer to the same \`Ruleset\`. However,
-- \`prod\/v23\` refers to a new \`Ruleset\`. The \`Ruleset\` reference for
-- a \`Release\` may be updated using the UpdateRelease method, and the
-- custom \`Release\` name may be referenced by specifying the
-- \`X-Firebase-Rules-Release-Name\` header.
--
-- /See:/ <https://firebase.google.com/docs/storage/security Firebase Rules API Reference> for @firebaserules.projects.releases.create@.
module Network.Google.Resource.FirebaseRules.Projects.Releases.Create
(
-- * REST Resource
ProjectsReleasesCreateResource
-- * Creating a Request
, projectsReleasesCreate
, ProjectsReleasesCreate
-- * Request Lenses
, prcrXgafv
, prcrUploadProtocol
, prcrPp
, prcrAccessToken
, prcrUploadType
, prcrPayload
, prcrBearerToken
, prcrName
, prcrCallback
) where
import Network.Google.FirebaseRules.Types
import Network.Google.Prelude
-- | A resource alias for @firebaserules.projects.releases.create@ method which the
-- 'ProjectsReleasesCreate' request conforms to.
type ProjectsReleasesCreateResource =
"v1" :>
Capture "name" Text :>
"releases" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Release :> Post '[JSON] Release
-- | Create a \`Release\`. Release names should reflect the developer\'s
-- deployment practices. For example, the release name may include the
-- environment name, application name, application version, or any other
-- name meaningful to the developer. Once a \`Release\` refers to a
-- \`Ruleset\`, the rules can be enforced by Firebase Rules-enabled
-- services. More than one \`Release\` may be \'live\' concurrently.
-- Consider the following three \`Release\` names for \`projects\/foo\` and
-- the \`Ruleset\` to which they refer. Release Name | Ruleset Name
-- --------------------------------|-------------
-- projects\/foo\/releases\/prod | projects\/foo\/rulesets\/uuid123
-- projects\/foo\/releases\/prod\/beta | projects\/foo\/rulesets\/uuid123
-- projects\/foo\/releases\/prod\/v23 | projects\/foo\/rulesets\/uuid456
-- The table reflects the \`Ruleset\` rollout in progress. The \`prod\` and
-- \`prod\/beta\` releases refer to the same \`Ruleset\`. However,
-- \`prod\/v23\` refers to a new \`Ruleset\`. The \`Ruleset\` reference for
-- a \`Release\` may be updated using the UpdateRelease method, and the
-- custom \`Release\` name may be referenced by specifying the
-- \`X-Firebase-Rules-Release-Name\` header.
--
-- /See:/ 'projectsReleasesCreate' smart constructor.
data ProjectsReleasesCreate = ProjectsReleasesCreate'
{ _prcrXgafv :: !(Maybe Xgafv)
, _prcrUploadProtocol :: !(Maybe Text)
, _prcrPp :: !Bool
, _prcrAccessToken :: !(Maybe Text)
, _prcrUploadType :: !(Maybe Text)
, _prcrPayload :: !Release
, _prcrBearerToken :: !(Maybe Text)
, _prcrName :: !Text
, _prcrCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProjectsReleasesCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'prcrXgafv'
--
-- * 'prcrUploadProtocol'
--
-- * 'prcrPp'
--
-- * 'prcrAccessToken'
--
-- * 'prcrUploadType'
--
-- * 'prcrPayload'
--
-- * 'prcrBearerToken'
--
-- * 'prcrName'
--
-- * 'prcrCallback'
projectsReleasesCreate
:: Release -- ^ 'prcrPayload'
-> Text -- ^ 'prcrName'
-> ProjectsReleasesCreate
projectsReleasesCreate pPrcrPayload_ pPrcrName_ =
ProjectsReleasesCreate'
{ _prcrXgafv = Nothing
, _prcrUploadProtocol = Nothing
, _prcrPp = True
, _prcrAccessToken = Nothing
, _prcrUploadType = Nothing
, _prcrPayload = pPrcrPayload_
, _prcrBearerToken = Nothing
, _prcrName = pPrcrName_
, _prcrCallback = Nothing
}
-- | V1 error format.
prcrXgafv :: Lens' ProjectsReleasesCreate (Maybe Xgafv)
prcrXgafv
= lens _prcrXgafv (\ s a -> s{_prcrXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
prcrUploadProtocol :: Lens' ProjectsReleasesCreate (Maybe Text)
prcrUploadProtocol
= lens _prcrUploadProtocol
(\ s a -> s{_prcrUploadProtocol = a})
-- | Pretty-print response.
prcrPp :: Lens' ProjectsReleasesCreate Bool
prcrPp = lens _prcrPp (\ s a -> s{_prcrPp = a})
-- | OAuth access token.
prcrAccessToken :: Lens' ProjectsReleasesCreate (Maybe Text)
prcrAccessToken
= lens _prcrAccessToken
(\ s a -> s{_prcrAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
prcrUploadType :: Lens' ProjectsReleasesCreate (Maybe Text)
prcrUploadType
= lens _prcrUploadType
(\ s a -> s{_prcrUploadType = a})
-- | Multipart request metadata.
prcrPayload :: Lens' ProjectsReleasesCreate Release
prcrPayload
= lens _prcrPayload (\ s a -> s{_prcrPayload = a})
-- | OAuth bearer token.
prcrBearerToken :: Lens' ProjectsReleasesCreate (Maybe Text)
prcrBearerToken
= lens _prcrBearerToken
(\ s a -> s{_prcrBearerToken = a})
-- | Resource name for the project which owns this \`Release\`. Format:
-- \`projects\/{project_id}\`
prcrName :: Lens' ProjectsReleasesCreate Text
prcrName = lens _prcrName (\ s a -> s{_prcrName = a})
-- | JSONP
prcrCallback :: Lens' ProjectsReleasesCreate (Maybe Text)
prcrCallback
= lens _prcrCallback (\ s a -> s{_prcrCallback = a})
instance GoogleRequest ProjectsReleasesCreate where
type Rs ProjectsReleasesCreate = Release
type Scopes ProjectsReleasesCreate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/firebase"]
requestClient ProjectsReleasesCreate'{..}
= go _prcrName _prcrXgafv _prcrUploadProtocol
(Just _prcrPp)
_prcrAccessToken
_prcrUploadType
_prcrBearerToken
_prcrCallback
(Just AltJSON)
_prcrPayload
firebaseRulesService
where go
= buildClient
(Proxy :: Proxy ProjectsReleasesCreateResource)
mempty
| rueshyna/gogol | gogol-firebase-rules/gen/Network/Google/Resource/FirebaseRules/Projects/Releases/Create.hs | mpl-2.0 | 8,284 | 0 | 19 | 1,733 | 971 | 578 | 393 | 133 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.DetachNetworkInterface
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Detaches a network interface from an instance.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DetachNetworkInterface.html>
module Network.AWS.EC2.DetachNetworkInterface
(
-- * Request
DetachNetworkInterface
-- ** Request constructor
, detachNetworkInterface
-- ** Request lenses
, dniAttachmentId
, dniDryRun
, dniForce
-- * Response
, DetachNetworkInterfaceResponse
-- ** Response constructor
, detachNetworkInterfaceResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data DetachNetworkInterface = DetachNetworkInterface
{ _dniAttachmentId :: Text
, _dniDryRun :: Maybe Bool
, _dniForce :: Maybe Bool
} deriving (Eq, Ord, Read, Show)
-- | 'DetachNetworkInterface' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dniAttachmentId' @::@ 'Text'
--
-- * 'dniDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'dniForce' @::@ 'Maybe' 'Bool'
--
detachNetworkInterface :: Text -- ^ 'dniAttachmentId'
-> DetachNetworkInterface
detachNetworkInterface p1 = DetachNetworkInterface
{ _dniAttachmentId = p1
, _dniDryRun = Nothing
, _dniForce = Nothing
}
-- | The ID of the attachment.
dniAttachmentId :: Lens' DetachNetworkInterface Text
dniAttachmentId = lens _dniAttachmentId (\s a -> s { _dniAttachmentId = a })
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have the
-- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'.
dniDryRun :: Lens' DetachNetworkInterface (Maybe Bool)
dniDryRun = lens _dniDryRun (\s a -> s { _dniDryRun = a })
-- | Specifies whether to force a detachment.
dniForce :: Lens' DetachNetworkInterface (Maybe Bool)
dniForce = lens _dniForce (\s a -> s { _dniForce = a })
data DetachNetworkInterfaceResponse = DetachNetworkInterfaceResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DetachNetworkInterfaceResponse' constructor.
detachNetworkInterfaceResponse :: DetachNetworkInterfaceResponse
detachNetworkInterfaceResponse = DetachNetworkInterfaceResponse
instance ToPath DetachNetworkInterface where
toPath = const "/"
instance ToQuery DetachNetworkInterface where
toQuery DetachNetworkInterface{..} = mconcat
[ "AttachmentId" =? _dniAttachmentId
, "DryRun" =? _dniDryRun
, "Force" =? _dniForce
]
instance ToHeaders DetachNetworkInterface
instance AWSRequest DetachNetworkInterface where
type Sv DetachNetworkInterface = EC2
type Rs DetachNetworkInterface = DetachNetworkInterfaceResponse
request = post "DetachNetworkInterface"
response = nullResponse DetachNetworkInterfaceResponse
| romanb/amazonka | amazonka-ec2/gen/Network/AWS/EC2/DetachNetworkInterface.hs | mpl-2.0 | 3,962 | 0 | 9 | 837 | 469 | 284 | 185 | 57 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Webmasters.Sitemaps.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves information about a specific sitemap.
--
-- /See:/ <https://developers.google.com/webmaster-tools/search-console-api/ Google Search Console API Reference> for @webmasters.sitemaps.get@.
module Network.Google.Resource.Webmasters.Sitemaps.Get
(
-- * REST Resource
SitemapsGetResource
-- * Creating a Request
, sitemapsGet
, SitemapsGet
-- * Request Lenses
, sgXgafv
, sgFeedpath
, sgUploadProtocol
, sgSiteURL
, sgAccessToken
, sgUploadType
, sgCallback
) where
import Network.Google.Prelude
import Network.Google.SearchConsole.Types
-- | A resource alias for @webmasters.sitemaps.get@ method which the
-- 'SitemapsGet' request conforms to.
type SitemapsGetResource =
"webmasters" :>
"v3" :>
"sites" :>
Capture "siteUrl" Text :>
"sitemaps" :>
Capture "feedpath" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] WmxSitemap
-- | Retrieves information about a specific sitemap.
--
-- /See:/ 'sitemapsGet' smart constructor.
data SitemapsGet =
SitemapsGet'
{ _sgXgafv :: !(Maybe Xgafv)
, _sgFeedpath :: !Text
, _sgUploadProtocol :: !(Maybe Text)
, _sgSiteURL :: !Text
, _sgAccessToken :: !(Maybe Text)
, _sgUploadType :: !(Maybe Text)
, _sgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SitemapsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sgXgafv'
--
-- * 'sgFeedpath'
--
-- * 'sgUploadProtocol'
--
-- * 'sgSiteURL'
--
-- * 'sgAccessToken'
--
-- * 'sgUploadType'
--
-- * 'sgCallback'
sitemapsGet
:: Text -- ^ 'sgFeedpath'
-> Text -- ^ 'sgSiteURL'
-> SitemapsGet
sitemapsGet pSgFeedpath_ pSgSiteURL_ =
SitemapsGet'
{ _sgXgafv = Nothing
, _sgFeedpath = pSgFeedpath_
, _sgUploadProtocol = Nothing
, _sgSiteURL = pSgSiteURL_
, _sgAccessToken = Nothing
, _sgUploadType = Nothing
, _sgCallback = Nothing
}
-- | V1 error format.
sgXgafv :: Lens' SitemapsGet (Maybe Xgafv)
sgXgafv = lens _sgXgafv (\ s a -> s{_sgXgafv = a})
-- | The URL of the actual sitemap. For example:
-- \`http:\/\/www.example.com\/sitemap.xml\`.
sgFeedpath :: Lens' SitemapsGet Text
sgFeedpath
= lens _sgFeedpath (\ s a -> s{_sgFeedpath = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sgUploadProtocol :: Lens' SitemapsGet (Maybe Text)
sgUploadProtocol
= lens _sgUploadProtocol
(\ s a -> s{_sgUploadProtocol = a})
-- | The site\'s URL, including protocol. For example:
-- \`http:\/\/www.example.com\/\`.
sgSiteURL :: Lens' SitemapsGet Text
sgSiteURL
= lens _sgSiteURL (\ s a -> s{_sgSiteURL = a})
-- | OAuth access token.
sgAccessToken :: Lens' SitemapsGet (Maybe Text)
sgAccessToken
= lens _sgAccessToken
(\ s a -> s{_sgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sgUploadType :: Lens' SitemapsGet (Maybe Text)
sgUploadType
= lens _sgUploadType (\ s a -> s{_sgUploadType = a})
-- | JSONP
sgCallback :: Lens' SitemapsGet (Maybe Text)
sgCallback
= lens _sgCallback (\ s a -> s{_sgCallback = a})
instance GoogleRequest SitemapsGet where
type Rs SitemapsGet = WmxSitemap
type Scopes SitemapsGet =
'["https://www.googleapis.com/auth/webmasters",
"https://www.googleapis.com/auth/webmasters.readonly"]
requestClient SitemapsGet'{..}
= go _sgSiteURL _sgFeedpath _sgXgafv
_sgUploadProtocol
_sgAccessToken
_sgUploadType
_sgCallback
(Just AltJSON)
searchConsoleService
where go
= buildClient (Proxy :: Proxy SitemapsGetResource)
mempty
| brendanhay/gogol | gogol-searchconsole/gen/Network/Google/Resource/Webmasters/Sitemaps/Get.hs | mpl-2.0 | 4,913 | 0 | 19 | 1,206 | 786 | 458 | 328 | 114 | 1 |
module Parsing.ParseInline (inline) where
import Data.Maybe
import Network.URI (isURI)
import Text.Parsec
import qualified Data.Map.Strict as M
import AST
import Parsing.State
import Parsing.Text
import Parsing.TextUtils
import Parsing.Utils
import Parsing.ParseHtml
nestedBold :: Parser Inline
nestedBold = suppressErr (try (string "****")) >> fail "cannot have empty or nested bold nodes"
bold :: Parser Inline
bold = do
state <- getState
let currentParserStack = inlineParserStack state
failIf $ elem "bold" currentParserStack
s <- betweenWithErrors' "**" "**" "bold"
$ withModifiedState (many1 inline) $ \s -> s {inlineParserStack=("bold" : currentParserStack)}
return $ Bold s
-- The bold and italics parsers are tricky because they both use the same special character.
italics :: Parser Inline
italics = do
state <- getState
let currentParserStack = inlineParserStack state
failIf $ elem "italics" currentParserStack
s <- between
(try ((char' '*' <?> "\"*\" (italics)") >> suppressErr (notFollowedBy (char '*'))))
(char' '*' <?> "closing \"*\" (italics)")
((withModifiedState (many1 inline) $ \s -> s {inlineParserStack=("italics" : currentParserStack)}) <?>
if elem "bold" currentParserStack
then "content in italics node or extra \"*\" to close bold node"
else "content in italics node")
return $ Italics s
code :: Parser Inline
code = fmap Code $ betweenWithErrors' "`" "`" "code" $ many1 $ escapableNoneOf "`"
footnoteRef :: Parser Inline
footnoteRef = do
identifier <- betweenWithErrors' "^[" "]" "footnote reference" $ many1 $ escapableNoneOf "[]"
state <- getState
let f = footnoteIndices state
if M.member identifier f
then fail $ "repeated footnote identifier: " ++ identifier
else return ()
let index = M.size f
let f' = M.insert identifier index f
putState $ state {footnoteIndices=f'}
return $ FootnoteRef index
image :: Parser Inline
image = do
alt <- betweenWithErrors' "![" "]" "image" $ many1 $ escapableNoneOf "[]"
src <- betweenWithErrors' "(" ")" "image src" $ many $ escapableNoneOf "()"
return $ Image {alt=alt, src=src}
link :: Parser Inline
link = do
state <- getState
let currentParserStack = inlineParserStack state
lookAhead (char '[' <?> "\"[\" (link)")
if elem "link" currentParserStack
then fail "links cannot be nested"
else return ()
text <- betweenWithErrors' "[" "]" "link" $ withModifiedState (many1 inline) $ \s -> s {inlineParserStack=("link" : currentParserStack)}
href <- optionMaybe $ betweenWithErrors' "(" ")" "link href" $ many $ escapableNoneOf "()"
if isJust href
then return $ Link {text=text, href=fromJust href}
else do
let text' = unboxPlaintext text where
unboxPlaintext [Plaintext p] = p
unboxPlaintext _ = ""
if isURI text'
then return $ Link {text=text, href=text'}
else fail "link href is required unless link text is a valid absolute URI"
inline :: Parser Inline
inline = choice [nestedBold, bold, italics, code, footnoteRef, link, image, fmap InlineHtml html, fmap Plaintext plaintext]
| alexbecker/blogdown | src/Parsing/ParseInline.hs | agpl-3.0 | 3,281 | 0 | 17 | 765 | 958 | 479 | 479 | -1 | -1 |
module TopicExplorer.Creator.Corpus (
Keywords(Keywords), Corpus.getKeywords,
Identifier(Identifier), Corpus.getIdentifier,
SearchId,
Corpus(..),
toJSONObject,
) where
import qualified TopicExplorer.Configuration.Corpus as Corpus
import TopicExplorer.Configuration.Corpus
(Keywords(Keywords), Identifier(Identifier))
import Control.Applicative (pure, (<*>), (<$>))
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text; import Data.Text (Text)
import qualified Data.Map as Map; import Data.Map (Map)
import Data.Aeson ((.:))
import Data.Int (Int32)
t :: String -> Text
t = Text.pack
type SearchId = Int32
data Corpus =
Corpus {
searchId :: SearchId,
query :: Keywords,
identifier :: Identifier
}
instance Aeson.FromJSON Corpus where
parseJSON =
Aeson.withObject "Corpus" $ \v ->
pure Corpus
<*> v .: t"search_id"
<*> (Keywords <$> v .: t"query")
<*> (Identifier <$> v .: t"identifier")
instance Aeson.ToJSON Corpus where
toJSON = Aeson.toJSON . toJSONObject
toJSONObject :: Corpus -> Map String Aeson.Value
toJSONObject (Corpus searchId_ (Keywords query_) (Identifier identifier_)) =
Map.fromList $
("search_id", Aeson.toJSON searchId_) :
("query", Aeson.toJSON query_) :
("identifier", Aeson.toJSON identifier_) :
[]
| hinneburg/TopicExplorer | creator-server/creator/src-lib/TopicExplorer/Creator/Corpus.hs | agpl-3.0 | 1,349 | 0 | 12 | 261 | 414 | 245 | 169 | 43 | 1 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, RecordWildCards, OverloadedStrings, ScopedTypeVariables, DataKinds #-}
module Model.AssetSegment
( module Model.AssetSegment.Types
, lookupAssetSegment
, lookupSlotAssetSegment
, lookupAssetSlotSegment
, lookupOrigSlotAssetSegment
, lookupSlotSegmentThumb
, auditAssetSegmentDownload
, assetSegmentJSON
, assetSegmentInterp
) where
import Control.Applicative (pure, empty)
import Data.Monoid ((<>))
import Database.PostgreSQL.Typed (pgSQL)
import Database.PostgreSQL.Typed.Query
import Database.PostgreSQL.Typed.Types
import qualified Data.ByteString
import Data.ByteString (ByteString)
import qualified Data.String
import Ops
import Has (peek, view)
import qualified JSON
import Service.DB
import Model.SQL
import Model.Audit
import Model.Id
import Model.Party.Types
import Model.Identity
import Model.Permission
import Model.Segment
import Model.Volume.Types
import Model.Container.Types
import Model.Slot.Types
import Model.Format.Types
import Model.Asset.Types
import Model.AssetSlot
import Model.AssetSegment.Types
import Model.AssetSegment.SQL
lookupAssetSegment :: (MonadHasIdentity c m, MonadDB c m) => Segment -> Id Asset -> m (Maybe AssetSegment)
lookupAssetSegment seg ai = do
ident :: Identity <- peek
dbQuery1 $(selectQuery (selectAssetSegment 'ident 'seg) "$WHERE slot_asset.asset = ${ai} AND slot_asset.segment && ${seg}")
lookupSlotAssetSegment :: (MonadHasIdentity c m, MonadDB c m) => Id Slot -> Id Asset -> m (Maybe AssetSegment)
lookupSlotAssetSegment (Id (SlotId ci seg)) ai = do
ident :: Identity <- peek
dbQuery1 $(selectQuery (selectAssetSegment 'ident 'seg)
"$WHERE slot_asset.container = ${ci} AND slot_asset.asset = ${ai} AND slot_asset.segment && ${seg}")
lookupOrigSlotAssetSegment :: (MonadHasIdentity c m, MonadDB c m) => Id Slot -> Id Asset -> m (Maybe AssetSegment)
lookupOrigSlotAssetSegment (Id (SlotId ci seg)) ai = do
ident :: Identity <- peek
dbQuery1 $(selectQuery (selectAssetSegment 'ident 'seg)
"$inner join asset_revision ar on ar.asset = asset.id WHERE slot_asset.container = ${ci} AND slot_asset.asset = ${ai} AND slot_asset.segment && ${seg}")
lookupAssetSlotSegment :: MonadDB c m => AssetSlot -> Segment -> m (Maybe AssetSegment)
lookupAssetSlotSegment a s =
segmentEmpty seg `unlessReturn` (as <$>
dbQuery1 $(selectQuery excerptRow "$WHERE asset = ${view a :: Id Asset} AND segment @> ${seg}"))
where
as = makeExcerpt a s
seg = assetSegment $ as Nothing
lookupSlotSegmentThumb :: MonadDB c m => Slot -> m (Maybe AssetSegment)
lookupSlotSegmentThumb (Slot c s) =
dbQuery1 $ assetSegmentInterp 0.25 . ($ c) <$> $(selectQuery (selectContainerAssetSegment 's) "$\
\JOIN format ON asset.format = format.id \
\WHERE slot_asset.container = ${containerId $ containerRow c} AND slot_asset.segment && ${s} \
\AND COALESCE(asset.release, ${containerRelease c}) >= ${readRelease (view c)}::release \
\AND (asset.duration IS NOT NULL AND format.mimetype LIKE 'video/%' OR format.mimetype LIKE 'image/%') \
\LIMIT 1")
mapQuery :: ByteString -> ([PGValue] -> a) -> PGSimpleQuery a
mapQuery qry mkResult =
fmap mkResult (rawPGSimpleQuery qry)
auditAssetSegmentDownload :: MonadAudit c m => Bool -> AssetSegment -> m ()
auditAssetSegmentDownload success AssetSegment{ segmentAsset = AssetSlot{ slotAsset = a, assetSlot = as }, assetSegment = seg } = do
ai <- getAuditIdentity
let _tenv_a9v9T = unknownPGTypeEnv
maybe
(dbExecute1'
{- [pgSQL|INSERT INTO audit.asset (audit_action, audit_user, audit_ip, id, volume, format, release) VALUES
(${act}, ${auditWho ai}, ${auditIp ai}, ${assetId $ assetRow a}, ${volumeId $ volumeRow $ assetVolume a}, ${formatId $ assetFormat $ assetRow a}, ${assetRelease $ assetRow a})|] -}
(mapQuery
((\ _p_a9v9U _p_a9v9V _p_a9v9W _p_a9v9X _p_a9v9Y _p_a9v9Z _p_a9va0 ->
(Data.ByteString.concat
[Data.String.fromString
"INSERT INTO audit.asset (audit_action, audit_user, audit_ip, id, volume, format, release) VALUES\n\
\ (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a9v9T
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "audit.action")
_p_a9v9U,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a9v9T
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a9v9V,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a9v9T
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a9v9W,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a9v9T
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a9v9X,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a9v9T
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a9v9Y,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a9v9T
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "smallint")
_p_a9v9Z,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a9v9T
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "release")
_p_a9va0,
Data.String.fromString ")"]))
act
(auditWho ai)
(auditIp ai)
(assetId $ assetRow a)
(volumeId $ volumeRow $ assetVolume a)
(formatId $ assetFormat $ assetRow a)
(assetRelease $ assetRow a))
(\[] -> ())))
(\s -> dbExecute1' [pgSQL|$INSERT INTO audit.slot_asset (audit_action, audit_user, audit_ip, container, segment, asset) VALUES
(${act}, ${auditWho ai}, ${auditIp ai}, ${containerId $ containerRow $ slotContainer s}, ${seg}, ${assetId $ assetRow a})|])
as
where act | success = AuditActionOpen
| otherwise = AuditActionAttempt
assetSegmentJSON :: JSON.ToObject o => AssetSegment -> o
assetSegmentJSON as@AssetSegment{..} =
"segment" JSON..= assetSegment
<> "format" `JSON.kvObjectOrEmpty` (if view segmentAsset == fmt then empty else pure (formatId fmt))
-- "release" `JSON.kvObjectOrEmpty` (view as :: Maybe Release)
<> "permission" JSON..= dataPermission4 getAssetSegmentRelease2 getAssetSegmentVolumePermission2 as
<> "excerpt" `JSON.kvObjectOrEmpty` (excerptRelease <$> assetExcerpt)
where fmt = view as
assetSegmentInterp :: Float -> AssetSegment -> AssetSegment
assetSegmentInterp f as = as{ assetSegment = segmentInterp f $ assetSegment as }
| databrary/databrary | src/Model/AssetSegment.hs | agpl-3.0 | 7,893 | 0 | 22 | 2,111 | 1,482 | 818 | 664 | 138 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Translation
-- Copyright : (c) Masahiro Sakai 2007-2009
-- License : BSD3-style (see LICENSE)
--
-- Maintainer: [email protected]
-- Stability : experimental
-- Portability : non-portable
{-# LANGUAGE TypeOperators, GADTs, TypeSynonymInstances, ScopedTypeVariables #-}
module Translation (translate, catToType) where
import IL
import P
-----------------------------------------------------------------------------
{-
-- 範疇から型への対応
type family Translate x
type instance Translate Sen = Prop
type instance Translate IV = E -> Prop
type instance Translate CN = E -> Prop
type instance Translate Adj = E -> Prop
type instance Translate (a :/ b) = ((S -> Translate b) -> Translate a)
type instance Translate (a :// b) = ((S -> Translate b) -> Translate a)
-}
catToType :: Cat c -> Type
catToType Sen = Prop
catToType IV = E :-> Prop
catToType CN = E :-> Prop
catToType Adj = E :-> Prop -- これで本当にあっている?
catToType (a :/ b) = (S (catToType b)) :-> catToType a
catToType (a :// b) = (S (catToType b)) :-> catToType a
-----------------------------------------------------------------------------
translate :: forall c. P c -> Expr
--- 1. αがgの定義域にあれば,α は,g(α) に翻訳される.
-- 最後に
--- 2. be → λp.λx. p{f^λy.[x = y]}.
--- ここで,変数pのタイプは<s, <<s, <e, t>>, t>>.
translate (B (IV :/ (Sen :/ IV)){- TV -} "be") =
lambda p $ lambda x $
FVar p <@> int (lambda y $ Op2 Id (FVar x) (FVar y))
where
p = ("p", S (S (E :-> Prop) :-> Prop))
x = ("x", E)
y = ("y", E)
--- 3. necessarily → λp[□ext p]. ここで,p のタイプは<s, t>とする.
translate (B (Sen :/ Sen) "necessarily") = lambda p $ Op1 Box (ext (FVar p))
where
p = ("p", S Prop)
--- 4. j, m, b はタイプがe の定数記号,変数P のタイプは<s, <e, t>>とする.
translate (B (Sen :/ IV){- T -} x) = lambda p $ FVar p <@> Const (x, E)
where
p = ("p", S (catToType IV))
--- 5. he_n → λP. P {x_n}.x_ はタイプe の変数.
translate (He n) = lambda p $ FVar p <@> FVar (xn n)
where
p = ("p", S (E :-> Prop))
translate (F2 delta zeta) = trApp delta zeta -- T2
translate (F3 n zeta phi) = -- T3
lambda (xn n) $ Op2 And (translate zeta :@ FVar (xn n)) (translate phi)
translate (F4 alpha delta) = trApp alpha delta -- T4
translate (F5 delta beta) = trApp delta beta -- T5
-- T6 (T5と同じなので省略)
translate (F16 delta phi) = trApp delta phi -- T7
translate (F17 delta beta) = trApp' delta beta -- T8
translate (F6 delta beta) = trApp delta beta -- T9
translate (F7 delta beta) = trApp delta beta -- T10
translate (F8 phi psi) =
case cat :: Cat c of
Sen -> Op2 And (translate phi) (translate psi) -- T11a
IV -> lambda x $ Op2 And (translate phi :@ FVar x) (translate psi :@ FVar x) -- T12a
where
x = ("x", E)
translate (F9 phi psi) =
case cat :: Cat c of
Sen -> Op2 Or (translate phi) (translate psi) -- T11b
IV -> lambda x $ Op2 Or (translate phi :@ FVar x) (translate psi :@ FVar x) -- T12b
where x = ("x", E)
Sen :/ IV -> lambda p $ Op2 Or (translate phi :@ FVar p) (translate psi :@ FVar p) -- T13
where p = ("P", S (E :-> Prop))
-- T14 (講義資料はx_nになるべきところがxになっている)
translate (F10 n alpha phi) =
case cat :: Cat c of
Sen -> translate alpha :@ (int $ lambda (xn n) (translate phi)) -- T14
CN -> lambda y $ translate alpha :@ int (lambda (xn n) (translate phi :@ FVar y)) -- T15
IV -> lambda y $ translate alpha :@ int (lambda (xn n) (translate phi :@ FVar y)) -- T16
where
y = ("y", E)
-- T17
translate (F11 alpha delta) = Op1 Not $ trApp alpha delta
translate (F12 alpha delta) = Op1 F $ trApp alpha delta
translate (F13 alpha delta) = Op1 Not $ Op1 F $ trApp alpha delta
translate (F14 alpha delta) = Op1 H $ trApp alpha delta
translate (F15 alpha delta) = Op1 Not $ Op1 H $ trApp alpha delta
-- T18 (beの扱い以外はT9と同じ)
translate (B (IV :/ Adj) "be") = lambda p $ lambda x $ FVar p <@> FVar x
where
p = ("P", S (E :-> Prop))
x = ("x", E)
-- T19
translate (F19 delta) =
lambda x $ exists y $
translate delta :@ int (lambda p (FVar p <@> FVar y)) :@ FVar x
where
x = ("x", E)
p = ("P", S (E :-> Prop))
y = ("y", E)
translate (F20 delta beta) = trApp delta beta -- T20
translate (F21 delta beta) = trApp delta beta -- T21 (講義資料ではF20を誤って使っている)
-- T22
translate (F22 delta) =
lambda p $ lambda q $ lambda x $
translate delta :@ FVar q :@ FVar p :@ FVar x
where
p = ("P", S (catToType (cat :: Cat T)))
q = ("Q", S (catToType (cat :: Cat T)))
x = ("x", E)
translate (F23 alpha delta) = trApp alpha delta -- T23
translate (F24 alpha beta) = trApp alpha beta -- T24
-- 講義資料のByの解釈は誤り? (型が一致しない)
translate (B (IV :/ (IV :/ (Sen :/ IV)) :/ (Sen :/ IV)){- PP/T -} "by") =
lambda p $ lambda r $ lambda x $
FVar p <@>
(int $ lambda y $ FVar r <@> int (lambda q $ FVar q <@> FVar x) :@ FVar y)
where
p = ("P", S (catToType (Sen :/ IV)))
r = ("R", S (catToType (IV :/ (Sen :/ IV))))
x = ("x", E)
y = ("y", E)
q = ("Q", S (catToType IV))
-- T25
translate (F25 delta) =
lambda x $ exists y $ Op1 H $
translate delta :@
int (lambda p $ FVar p <@> FVar x) :@
(FVar y)
where
x = ("x", E)
y = ("y", E)
p = ("P", S (catToType IV))
-- Det
translate (B (Sen :/ IV :/ CN) s) =
case s of
"a" ->
lambda p $ lambda q $ exists x $
Op2 And (FVar p <@> FVar x) (FVar q <@> FVar x)
"the" ->
lambda p $ lambda q $ exists y $
Op2 And
(forall x $ Op2 Equiv (FVar p <@> FVar x) (Op2 Id (FVar x) (FVar y)))
(FVar q <@> FVar y)
"every" ->
lambda p $ lambda q $ forall x $
Op2 Imply (FVar p <@> FVar x) (FVar q <@> FVar x)
"no" ->
lambda p $ lambda q $ forall x $
Op1 Not (Op2 And (FVar p <@> FVar x) (FVar q <@> FVar x))
_ -> Const (s, catToType (cat :: Cat Det))
where
p = ("p", S (E :-> Prop))
q = ("q", S (E :-> Prop))
x = ("x", E)
y = ("y", E)
-- それ以外
translate (B c x) = Const (x, catToType c)
-- ユーティリティ
trApp :: P (b :/ a) -> P a -> Expr
trApp f a = translate f :@ (int (translate a))
trApp' :: P (b :// a) -> P a -> Expr
trApp' f a = translate f :@ (int (translate a))
xn :: Int -> Name
xn n = ("he_"++show n, E)
| msakai/ptq | src/Translation.hs | lgpl-2.1 | 6,629 | 0 | 16 | 1,622 | 2,714 | 1,378 | 1,336 | 120 | 10 |
-- {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-
Copyright 2019 The CodeWorld Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Main (
main
) where
import GHCJS.DOM
(currentDocument, )
import GHCJS.DOM.NonElementParentNode
import GHCJS.DOM.GlobalEventHandlers
import GHCJS.DOM.Document (getBody, Document(..))
import GHCJS.DOM.Element (setInnerHTML, Element)
import GHCJS.DOM.HTMLButtonElement
import GHCJS.DOM.EventM (on)
import GHCJS.DOM.Types
import GHCJS.Types
import GHCJS.Foreign
import GHCJS.Foreign.Callback
import GHCJS.Marshal
import Data.JSString.Text
import qualified Data.JSString as JStr
import qualified Data.Text as T
import Control.Monad.Trans (liftIO, lift)
import Blockly.Workspace hiding (workspaceToCode)
import Blocks.Parser
import Blocks.CodeGen
import Blocks.Types
import Blockly.Event
import Blockly.General
import Blockly.Block
import Data.Monoid
import Control.Monad
pack = textToJSString
unpack = textFromJSString
setErrorMessage msg = do
Just doc <- liftIO currentDocument
-- Just msgEl <- getElementById doc "message"
liftIO $ putStrLn msg
liftIO $ js_stopErr (JStr.pack msg)
-- setInnerHTML msgEl $ Just msg
programBlocks :: [T.Text]
programBlocks = map T.pack ["cwActivityOf", "cwDrawingOf","cwAnimationOf", "cwSimulationOf", "cwInteractionOf"]
btnStopClick = do
liftIO js_stop
runOrError :: Workspace -> IO ()
runOrError ws = do
(code,errors) <- workspaceToCode ws
case errors of
((Error msg block):es) -> do
putStrLn $ T.unpack msg
setWarningText block msg
addErrorSelect block
js_removeErrorsDelay
setErrorMessage (T.unpack msg)
[] -> do
liftIO $ js_updateEditor (pack code)
liftIO $ js_cwcompile (pack code)
-- Update the hash on the workspace
-- Mainly so that broken programs can be shared
updateCode :: Workspace -> IO ()
updateCode ws = do
(code,errors) <- workspaceToCode ws
liftIO $ js_updateEditor (pack code)
liftIO $ js_cwcompilesilent (pack code)
btnRunClick ws = do
Just doc <- liftIO currentDocument
liftIO $ updateCode ws
blocks <- liftIO $ getTopBlocks ws
(block, w) <- liftIO $ isWarning ws
if T.length w > 0 then do
setErrorMessage (T.unpack w)
liftIO $ addErrorSelect block
liftIO $ js_removeErrorsDelay
else do
if not $ containsProgramBlock blocks
then do
setErrorMessage "No Program block on the workspace"
else do
liftIO $ runOrError ws
return ()
where
containsProgramBlock = any (\b -> getBlockType b `elem` programBlocks)
hookEvent elementName evType func = do
Just doc <- currentDocument
Just btn <- getElementById doc elementName
on (uncheckedCastTo HTMLButtonElement btn) evType func
help = do
js_injectReadOnly (JStr.pack "blocklyDiv")
liftIO setBlockTypes
funblocks = do
Just doc <- currentDocument
Just body <- getBody doc
workspace <- liftIO $ setWorkspace "blocklyDiv" "toolbox"
liftIO $ disableOrphans workspace -- Disable disconnected non-top level blocks
liftIO $ warnOnInputs workspace -- Display warning if inputs are disconnected
hookEvent "btnRun" click (btnRunClick workspace)
hookEvent "btnStop" click btnStopClick
liftIO setBlockTypes -- assign layout and types of Blockly blocks
liftIO $ addChangeListener workspace (onChange workspace)
liftIO js_showEast
liftIO js_openEast
-- Auto start
liftIO $ setRunFunc workspace
-- when (T.length hash > 0) $ liftIO $ runOrError workspace
return ()
main = do
Just doc <- currentDocument
mayTool <- getElementById doc "toolbox"
case mayTool of
Just _ -> funblocks
Nothing -> help
-- Update code in real time
onChange ws event = do
(code, errs) <- workspaceToCode ws
js_updateEditor (pack code)
setRunFunc :: Workspace -> IO ()
setRunFunc ws = do
cb <- syncCallback ContinueAsync (do
runOrError ws)
js_setRunFunc cb
-- FFI
-- call blockworld.js compile
foreign import javascript unsafe "compile($1)"
js_cwcompile :: JSString -> IO ()
foreign import javascript unsafe "compile($1,true)"
js_cwcompilesilent :: JSString -> IO ()
-- call blockworld.js run
-- run (xmlHash, codeHash, msg, error)
foreign import javascript unsafe "run()"
js_cwrun :: JSString -> JSString -> JSString -> Bool -> IO ()
-- call blockworld.js updateUI
foreign import javascript unsafe "updateUI()"
js_updateUI :: IO ()
-- funnily enough, If I'm calling run "" "" "" False I get errors
foreign import javascript unsafe "run('','','',false)"
js_stop :: IO ()
foreign import javascript unsafe "run('','',$1,true)"
js_stopErr :: JSString -> IO ()
foreign import javascript unsafe "updateEditor($1)"
js_updateEditor :: JSString -> IO ()
foreign import javascript unsafe "setTimeout(removeErrors,5000)"
js_removeErrorsDelay :: IO ()
foreign import javascript unsafe "window.mainLayout.show('east')"
js_showEast :: IO ()
foreign import javascript unsafe "window.mainLayout.open('east')"
js_openEast :: IO ()
foreign import javascript unsafe "Blockly.inject($1, {});"
js_injectReadOnly :: JSString -> IO Workspace
foreign import javascript unsafe "runFunc = $1"
js_setRunFunc :: Callback a -> IO ()
| alphalambda/codeworld | funblocks-client/src/Main.hs | apache-2.0 | 6,098 | 24 | 16 | 1,415 | 1,365 | 681 | 684 | 133 | 3 |
--primes = 2 : 3 : 5 : primes'
-- where
-- isPrime (p:ps) n = p*p > n || n `rem` p /= 0 && isPrime ps n
-- primes' = 7 : filter (isPrime primes') (scanl (+) 11 $ cycle [2,4,2,4,6,2,6,4])
primes :: Integral a => [a]
primes = map fromIntegral $ [2, 3] ++ primes'
where
primes' = [5] ++ f 1 7 primes'
f m s (p:ps) = [n | n <- ns, gcd m n == 1] ++ f (m * p) (p * p) ps
where ns = [x + y | x <- [s, s + 6 .. p * p - 2], y <- [0, 4]]
main = do
l <- getContents
let i = map read $ lines l :: [Int]
m = maximum i
p = takeWhile (<=m) primes
o = map (\a -> length $ takeWhile (<=a) p) i
mapM_ print o
| a143753/AOJ | 0009.hs | apache-2.0 | 655 | 0 | 15 | 217 | 286 | 152 | 134 | 12 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Dimple2.Base (
Options(..)
, Context(..)
, Dimple2Error (..)
, defaultOptions
)where
import Data.Typeable (Typeable)
import Data.Data (Data)
import Dimple2.MulticastGroup
data Environment = Prod | Dev
deriving (Show,Eq,Data,Typeable)
data Options = Options {environment :: Environment,
multicastGroup :: MulticastGroup,
multicastPort :: Integer,
apiHost :: Maybe String,
apiPort :: Integer,
localViewSize :: Int,
shuffleInterval :: Int,
interestWait :: Int,
automaticDiscovery :: Bool}
deriving (Show,Eq,Data,Typeable)
defaultOptions :: Options
defaultOptions = Options {environment = Prod,
multicastGroup = read "231.10.10.25",
multicastPort = 29135,
apiHost = Nothing,
apiPort = 47688,
localViewSize = 10,
shuffleInterval = 10,
interestWait = 10,
automaticDiscovery = True}
data Context = Context {peerURL :: String,
options :: Options}
deriving (Show)
data Dimple2Error = InvalidAPIHost
deriving (Show, Eq)
| jwilberding/dimple2-haskell | src/Dimple2/Base.hs | apache-2.0 | 1,458 | 0 | 9 | 624 | 287 | 177 | 110 | 36 | 1 |
module StoneTransfer.A292726 (a292726, a292726_list) where
import Data.List (delete, nub, sort, null)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntMap.Strict (IntMap, toList, adjust, fromList)
-- The best structure for this would probably be a Scala-like Map[Int, Int],
-- which behaves like a histogram.
-- This is much slower than the Ruby implementation.
-- TODO: Implement A292727, A292729, and A292836.
a292726 n = length $ enumerateFrom $ fromList $ (1, n) : map (\i -> (i, 0)) [2..n]
a292726_list = map a292726 [1..]
type State = IntMap Int
-- Given a state return all possible child states. For example:
-- nextGeneration (3, 3, 2, 1, 1)
-- => [(6, 2, 1, 1), (5, 2, 1, 1, 1), (4, 2, 2, 1, 1), (3, 3, 2, 2)]
nextGeneration :: State -> [State]
nextGeneration currentGen = concatMap (`descendants` currentGen) $ multiples currentGen where
multiples as = map fst $ filter (\(_, count) -> count >= 2) $ toList as
descendants pileSize currentGen = map (transferStones pileSize currentGen) [1..pileSize] where
transferStones pileSize currentGen n = foldr (uncurry adjust) currentGen changeSet where
changeSet = [(subtract 2, pileSize), ((+1), pileSize - n), ((+1), pileSize + n)]
enumerateFrom :: State -> Set State
enumerateFrom initialGeneration = recurse [initialGeneration] Set.empty where
recurse :: [State] -> Set State -> Set State
recurse currentGen ledger = if null newGen then updatedLedger else recurse newGen updatedLedger where
newGen = filter ( `Set.notMember` ledger) $ concatMap nextGeneration currentGen
updatedLedger = insertList currentGen ledger
insertList list set = foldr Set.insert set list
| peterokagey/haskellOEIS | src/StoneTransfer/A292726.hs | apache-2.0 | 1,671 | 0 | 13 | 281 | 479 | 267 | 212 | 21 | 2 |
module STLCSyntax where
type Name = String
data Expr
= Var Name
| Lit Ground
| App Expr Expr
| Lam Name Type Expr
deriving (Eq, Show)
data Ground
= LInt Int
| LBool Bool
deriving (Eq, Show)
data Type
= TInt
| TBool
| TArr Type Type
deriving (Eq, Read, Show)
| toonn/wyah | src/STLCSyntax.hs | bsd-2-clause | 286 | 0 | 6 | 80 | 108 | 62 | 46 | 17 | 0 |
{-# LANGUAGE BangPatterns, OverloadedStrings, TypeOperators,
TypeFamilies, FlexibleContexts, RecordWildCards #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Xournal.Simple
-- Copyright : (c) 2011, 2012 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module Data.Xournal.Simple where
-- from other packages
import Control.Applicative
import Control.Lens
import qualified Data.ByteString as S
import Data.ByteString.Char8 hiding (map)
-- import Data.Label
import qualified Data.Serialize as SE
import Data.Strict.Tuple
-- from this package
import Data.Xournal.Util
--
import Prelude hiding ((.),id,putStrLn,fst,snd,curry,uncurry)
-- |
type Title = S.ByteString
-- |
data Stroke = Stroke { stroke_tool :: !S.ByteString
, stroke_color :: !S.ByteString
, stroke_width :: !Double
, stroke_data :: ![Pair Double Double]
}
| VWStroke { stroke_tool :: S.ByteString
, stroke_color :: S.ByteString
, stroke_vwdata :: [(Double,Double,Double)]
}
deriving (Show,Eq,Ord)
-- |
instance SE.Serialize Stroke where
put Stroke{..} = SE.putWord8 0
>> SE.put stroke_tool
>> SE.put stroke_color
>> SE.put stroke_width
>> SE.put stroke_data
put VWStroke{..} = SE.putWord8 1
>> SE.put stroke_tool
>> SE.put stroke_color
>> SE.put stroke_vwdata
get = do tag <- SE.getWord8
case tag of
0 -> Stroke <$> SE.get <*> SE.get <*> SE.get <*> SE.get
1 -> VWStroke <$> SE.get <*> SE.get <*> SE.get
_ -> fail "err in Stroke parsing"
-- |
instance (SE.Serialize a, SE.Serialize b) => SE.Serialize (Pair a b) where
put (x :!: y) = SE.put x
>> SE.put y
get = (:!:) <$> SE.get <*> SE.get
-- |
data Dimension = Dim { dim_width :: !Double, dim_height :: !Double }
deriving Show
-- |
data Background = Background { bkg_type :: !S.ByteString
, bkg_color :: !S.ByteString
, bkg_style :: !S.ByteString
}
| BackgroundPdf { bkg_type :: S.ByteString
, bkg_domain :: Maybe S.ByteString
, bkg_filename :: Maybe S.ByteString
, bkg_pageno :: Int
}
deriving Show
-- |
data Xournal = Xournal { xoj_title :: !Title, xoj_pages :: ![Page] }
deriving Show
-- |
data Page = Page { page_dim :: !Dimension
, page_bkg :: !Background
, page_layers :: ![Layer] }
deriving Show
-- |
data Layer = Layer { layer_strokes :: ![Stroke] }
deriving Show
-- |
getXYtuples :: Stroke -> [(Double,Double)]
getXYtuples (Stroke _t _c _w d) = map (\(x :!: y) -> (x,y)) d
getXYtuples (VWStroke _t _c d) = map ((,)<$>fst3<*>snd3) d
----------------------------
-- Lenses
----------------------------
-- |
s_tool :: Simple Lens Stroke ByteString
s_tool = lens stroke_tool (\f a -> f { stroke_tool = a })
-- |
s_color :: Simple Lens Stroke ByteString
s_color = lens stroke_color (\f a -> f { stroke_color = a } )
-- |
s_title :: Simple Lens Xournal Title
s_title = lens xoj_title (\f a -> f { xoj_title = a } )
-- |
s_pages :: Simple Lens Xournal [Page]
s_pages = lens xoj_pages (\f a -> f { xoj_pages = a } )
-- |
s_dim :: Simple Lens Page Dimension
s_dim = lens page_dim (\f a -> f { page_dim = a } )
-- |
s_bkg :: Simple Lens Page Background
s_bkg = lens page_bkg (\f a -> f { page_bkg = a } )
-- |
s_layers :: Simple Lens Page [Layer]
s_layers = lens page_layers (\f a -> f { page_layers = a } )
-- |
s_strokes :: Simple Lens Layer [Stroke]
s_strokes = lens layer_strokes (\f a -> f { layer_strokes = a } )
--------------------------
-- empty objects
--------------------------
-- |
emptyXournal :: Xournal
emptyXournal = Xournal "" []
-- |
emptyLayer :: Layer
emptyLayer = Layer { layer_strokes = [] }
-- |
emptyStroke :: Stroke
emptyStroke = Stroke "pen" "black" 1.4 []
-- |
defaultBackground :: Background
defaultBackground = Background { bkg_type = "solid"
, bkg_color = "white"
, bkg_style = "lined"
}
-- |
defaultLayer :: Layer
defaultLayer = Layer { layer_strokes = [] }
-- |
defaultPage :: Page
defaultPage = Page { page_dim = Dim 612.0 792.0
, page_bkg = defaultBackground
, page_layers = [ defaultLayer ]
}
-- |
defaultXournal :: Xournal
defaultXournal = Xournal "untitled" [ defaultPage ]
-- |
newPageFromOld :: Page -> Page
newPageFromOld page =
Page { page_dim = page_dim page
, page_bkg = page_bkg page
, page_layers = [emptyLayer] }
| wavewave/xournal-types | src/Data/Xournal/Simple.hs | bsd-2-clause | 5,437 | 0 | 15 | 1,840 | 1,358 | 779 | 579 | 129 | 1 |
{-
(c) The University of Glasgow 2006-2012
(c) The GRASP Project, Glasgow University, 1992-2002
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
module TcSigs(
TcSigInfo(..),
TcIdSigInfo(..), TcIdSigInst,
TcPatSynInfo(..),
TcSigFun,
isPartialSig, hasCompleteSig, tcIdSigName, tcSigInfoName,
completeSigPolyId_maybe,
tcTySigs, tcUserTypeSig, completeSigFromId,
tcInstSig,
TcPragEnv, emptyPragEnv, lookupPragEnv, extendPragEnv,
mkPragEnv, tcSpecPrags, tcSpecWrapper, tcImpPrags, addInlinePrags
) where
#include "HsVersions.h"
import GhcPrelude
import GHC.Hs
import TcHsType
import TcRnTypes
import TcRnMonad
import TcOrigin
import TcType
import TcMType
import TcValidity ( checkValidType )
import TcUnify( tcSkolemise, unifyType )
import Inst( topInstantiate )
import TcEnv( tcLookupId )
import TcEvidence( HsWrapper, (<.>) )
import Type( mkTyVarBinders )
import DynFlags
import Var ( TyVar, tyVarKind )
import Id ( Id, idName, idType, idInlinePragma, setInlinePragma, mkLocalId )
import PrelNames( mkUnboundName )
import BasicTypes
import Module( getModule )
import Name
import NameEnv
import Outputable
import SrcLoc
import Util( singleton )
import Maybes( orElse )
import Data.Maybe( mapMaybe )
import Control.Monad( unless )
{- -------------------------------------------------------------
Note [Overview of type signatures]
----------------------------------------------------------------
Type signatures, including partial signatures, are jolly tricky,
especially on value bindings. Here's an overview.
f :: forall a. [a] -> [a]
g :: forall b. _ -> b
f = ...g...
g = ...f...
* HsSyn: a signature in a binding starts off as a TypeSig, in
type HsBinds.Sig
* When starting a mutually recursive group, like f/g above, we
call tcTySig on each signature in the group.
* tcTySig: Sig -> TcIdSigInfo
- For a /complete/ signature, like 'f' above, tcTySig kind-checks
the HsType, producing a Type, and wraps it in a CompleteSig, and
extend the type environment with this polymorphic 'f'.
- For a /partial/signature, like 'g' above, tcTySig does nothing
Instead it just wraps the pieces in a PartialSig, to be handled
later.
* tcInstSig: TcIdSigInfo -> TcIdSigInst
In tcMonoBinds, when looking at an individual binding, we use
tcInstSig to instantiate the signature forall's in the signature,
and attribute that instantiated (monomorphic) type to the
binder. You can see this in TcBinds.tcLhsId.
The instantiation does the obvious thing for complete signatures,
but for /partial/ signatures it starts from the HsSyn, so it
has to kind-check it etc: tcHsPartialSigType. It's convenient
to do this at the same time as instantiation, because we can
make the wildcards into unification variables right away, raather
than somehow quantifying over them. And the "TcLevel" of those
unification variables is correct because we are in tcMonoBinds.
Note [Scoped tyvars]
~~~~~~~~~~~~~~~~~~~~
The -XScopedTypeVariables flag brings lexically-scoped type variables
into scope for any explicitly forall-quantified type variables:
f :: forall a. a -> a
f x = e
Then 'a' is in scope inside 'e'.
However, we do *not* support this
- For pattern bindings e.g
f :: forall a. a->a
(f,g) = e
Note [Binding scoped type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type variables *brought into lexical scope* by a type signature
may be a subset of the *quantified type variables* of the signatures,
for two reasons:
* With kind polymorphism a signature like
f :: forall f a. f a -> f a
may actually give rise to
f :: forall k. forall (f::k -> *) (a:k). f a -> f a
So the sig_tvs will be [k,f,a], but only f,a are scoped.
NB: the scoped ones are not necessarily the *initial* ones!
* Even aside from kind polymorphism, there may be more instantiated
type variables than lexically-scoped ones. For example:
type T a = forall b. b -> (a,b)
f :: forall c. T c
Here, the signature for f will have one scoped type variable, c,
but two instantiated type variables, c' and b'.
However, all of this only applies to the renamer. The typechecker
just puts all of them into the type environment; any lexical-scope
errors were dealt with by the renamer.
-}
{- *********************************************************************
* *
Utility functions for TcSigInfo
* *
********************************************************************* -}
tcIdSigName :: TcIdSigInfo -> Name
tcIdSigName (CompleteSig { sig_bndr = id }) = idName id
tcIdSigName (PartialSig { psig_name = n }) = n
tcSigInfoName :: TcSigInfo -> Name
tcSigInfoName (TcIdSig idsi) = tcIdSigName idsi
tcSigInfoName (TcPatSynSig tpsi) = patsig_name tpsi
completeSigPolyId_maybe :: TcSigInfo -> Maybe TcId
completeSigPolyId_maybe sig
| TcIdSig sig_info <- sig
, CompleteSig { sig_bndr = id } <- sig_info = Just id
| otherwise = Nothing
{- *********************************************************************
* *
Typechecking user signatures
* *
********************************************************************* -}
tcTySigs :: [LSig GhcRn] -> TcM ([TcId], TcSigFun)
tcTySigs hs_sigs
= checkNoErrs $
do { -- Fail if any of the signatures is duff
-- Hence mapAndReportM
-- See Note [Fail eagerly on bad signatures]
ty_sigs_s <- mapAndReportM tcTySig hs_sigs
; let ty_sigs = concat ty_sigs_s
poly_ids = mapMaybe completeSigPolyId_maybe ty_sigs
-- The returned [TcId] are the ones for which we have
-- a complete type signature.
-- See Note [Complete and partial type signatures]
env = mkNameEnv [(tcSigInfoName sig, sig) | sig <- ty_sigs]
; return (poly_ids, lookupNameEnv env) }
tcTySig :: LSig GhcRn -> TcM [TcSigInfo]
tcTySig (L _ (IdSig _ id))
= do { let ctxt = FunSigCtxt (idName id) False
-- False: do not report redundant constraints
-- The user has no control over the signature!
sig = completeSigFromId ctxt id
; return [TcIdSig sig] }
tcTySig (L loc (TypeSig _ names sig_ty))
= setSrcSpan loc $
do { sigs <- sequence [ tcUserTypeSig loc sig_ty (Just name)
| L _ name <- names ]
; return (map TcIdSig sigs) }
tcTySig (L loc (PatSynSig _ names sig_ty))
= setSrcSpan loc $
do { tpsigs <- sequence [ tcPatSynSig name sig_ty
| L _ name <- names ]
; return (map TcPatSynSig tpsigs) }
tcTySig _ = return []
tcUserTypeSig :: SrcSpan -> LHsSigWcType GhcRn -> Maybe Name
-> TcM TcIdSigInfo
-- A function or expression type signature
-- Returns a fully quantified type signature; even the wildcards
-- are quantified with ordinary skolems that should be instantiated
--
-- The SrcSpan is what to declare as the binding site of the
-- any skolems in the signature. For function signatures we
-- use the whole `f :: ty' signature; for expression signatures
-- just the type part.
--
-- Just n => Function type signature name :: type
-- Nothing => Expression type signature <expr> :: type
tcUserTypeSig loc hs_sig_ty mb_name
| isCompleteHsSig hs_sig_ty
= do { sigma_ty <- tcHsSigWcType ctxt_F hs_sig_ty
; traceTc "tcuser" (ppr sigma_ty)
; return $
CompleteSig { sig_bndr = mkLocalId name sigma_ty
, sig_ctxt = ctxt_T
, sig_loc = loc } }
-- Location of the <type> in f :: <type>
-- Partial sig with wildcards
| otherwise
= return (PartialSig { psig_name = name, psig_hs_ty = hs_sig_ty
, sig_ctxt = ctxt_F, sig_loc = loc })
where
name = case mb_name of
Just n -> n
Nothing -> mkUnboundName (mkVarOcc "<expression>")
ctxt_F = case mb_name of
Just n -> FunSigCtxt n False
Nothing -> ExprSigCtxt
ctxt_T = case mb_name of
Just n -> FunSigCtxt n True
Nothing -> ExprSigCtxt
completeSigFromId :: UserTypeCtxt -> Id -> TcIdSigInfo
-- Used for instance methods and record selectors
completeSigFromId ctxt id
= CompleteSig { sig_bndr = id
, sig_ctxt = ctxt
, sig_loc = getSrcSpan id }
isCompleteHsSig :: LHsSigWcType GhcRn -> Bool
-- ^ If there are no wildcards, return a LHsSigType
isCompleteHsSig (HsWC { hswc_ext = wcs
, hswc_body = HsIB { hsib_body = hs_ty } })
= null wcs && no_anon_wc hs_ty
isCompleteHsSig (HsWC _ (XHsImplicitBndrs nec)) = noExtCon nec
isCompleteHsSig (XHsWildCardBndrs nec) = noExtCon nec
no_anon_wc :: LHsType GhcRn -> Bool
no_anon_wc lty = go lty
where
go (L _ ty) = case ty of
HsWildCardTy _ -> False
HsAppTy _ ty1 ty2 -> go ty1 && go ty2
HsAppKindTy _ ty ki -> go ty && go ki
HsFunTy _ ty1 ty2 -> go ty1 && go ty2
HsListTy _ ty -> go ty
HsTupleTy _ _ tys -> gos tys
HsSumTy _ tys -> gos tys
HsOpTy _ ty1 _ ty2 -> go ty1 && go ty2
HsParTy _ ty -> go ty
HsIParamTy _ _ ty -> go ty
HsKindSig _ ty kind -> go ty && go kind
HsDocTy _ ty _ -> go ty
HsBangTy _ _ ty -> go ty
HsRecTy _ flds -> gos $ map (cd_fld_type . unLoc) flds
HsExplicitListTy _ _ tys -> gos tys
HsExplicitTupleTy _ tys -> gos tys
HsForAllTy { hst_bndrs = bndrs
, hst_body = ty } -> no_anon_wc_bndrs bndrs
&& go ty
HsQualTy { hst_ctxt = L _ ctxt
, hst_body = ty } -> gos ctxt && go ty
HsSpliceTy _ (HsSpliced _ _ (HsSplicedTy ty)) -> go $ L noSrcSpan ty
HsSpliceTy{} -> True
HsTyLit{} -> True
HsTyVar{} -> True
HsStarTy{} -> True
XHsType{} -> True -- Core type, which does not have any wildcard
gos = all go
no_anon_wc_bndrs :: [LHsTyVarBndr GhcRn] -> Bool
no_anon_wc_bndrs ltvs = all (go . unLoc) ltvs
where
go (UserTyVar _ _) = True
go (KindedTyVar _ _ ki) = no_anon_wc ki
go (XTyVarBndr nec) = noExtCon nec
{- Note [Fail eagerly on bad signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a type signature is wrong, fail immediately:
* the type sigs may bind type variables, so proceeding without them
can lead to a cascade of errors
* the type signature might be ambiguous, in which case checking
the code against the signature will give a very similar error
to the ambiguity error.
ToDo: this means we fall over if any top-level type signature in the
module is wrong, because we typecheck all the signatures together
(see TcBinds.tcValBinds). Moreover, because of top-level
captureTopConstraints, only insoluble constraints will be reported.
We typecheck all signatures at the same time because a signature
like f,g :: blah might have f and g from different SCCs.
So it's a bit awkward to get better error recovery, and no one
has complained!
-}
{- *********************************************************************
* *
Type checking a pattern synonym signature
* *
************************************************************************
Note [Pattern synonym signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pattern synonym signatures are surprisingly tricky (see #11224 for example).
In general they look like this:
pattern P :: forall univ_tvs. req_theta
=> forall ex_tvs. prov_theta
=> arg1 -> .. -> argn -> res_ty
For parsing and renaming we treat the signature as an ordinary LHsSigType.
Once we get to type checking, we decompose it into its parts, in tcPatSynSig.
* Note that 'forall univ_tvs' and 'req_theta =>'
and 'forall ex_tvs' and 'prov_theta =>'
are all optional. We gather the pieces at the top of tcPatSynSig
* Initially the implicitly-bound tyvars (added by the renamer) include both
universal and existential vars.
* After we kind-check the pieces and convert to Types, we do kind generalisation.
Note [solveEqualities in tcPatSynSig]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's important that we solve /all/ the equalities in a pattern
synonym signature, because we are going to zonk the signature to
a Type (not a TcType), in TcPatSyn.tc_patsyn_finish, and that
fails if there are un-filled-in coercion variables mentioned
in the type (#15694).
The best thing is simply to use solveEqualities to solve all the
equalites, rather than leaving them in the ambient constraints
to be solved later. Pattern synonyms are top-level, so there's
no problem with completely solving them.
(NB: this solveEqualities wraps newImplicitTKBndrs, which itself
does a solveLocalEqualities; so solveEqualities isn't going to
make any further progress; it'll just report any unsolved ones,
and fail, as it should.)
-}
tcPatSynSig :: Name -> LHsSigType GhcRn -> TcM TcPatSynInfo
-- See Note [Pattern synonym signatures]
-- See Note [Recipe for checking a signature] in TcHsType
tcPatSynSig name sig_ty
| HsIB { hsib_ext = implicit_hs_tvs
, hsib_body = hs_ty } <- sig_ty
, (univ_hs_tvs, hs_req, hs_ty1) <- splitLHsSigmaTyInvis hs_ty
, (ex_hs_tvs, hs_prov, hs_body_ty) <- splitLHsSigmaTyInvis hs_ty1
= do { traceTc "tcPatSynSig 1" (ppr sig_ty)
; (implicit_tvs, (univ_tvs, (ex_tvs, (req, prov, body_ty))))
<- pushTcLevelM_ $
solveEqualities $ -- See Note [solveEqualities in tcPatSynSig]
bindImplicitTKBndrs_Skol implicit_hs_tvs $
bindExplicitTKBndrs_Skol univ_hs_tvs $
bindExplicitTKBndrs_Skol ex_hs_tvs $
do { req <- tcHsContext hs_req
; prov <- tcHsContext hs_prov
; body_ty <- tcHsOpenType hs_body_ty
-- A (literal) pattern can be unlifted;
-- e.g. pattern Zero <- 0# (#12094)
; return (req, prov, body_ty) }
; let ungen_patsyn_ty = build_patsyn_type [] implicit_tvs univ_tvs
req ex_tvs prov body_ty
-- Kind generalisation
; kvs <- kindGeneralizeAll ungen_patsyn_ty
; traceTc "tcPatSynSig" (ppr ungen_patsyn_ty)
-- These are /signatures/ so we zonk to squeeze out any kind
-- unification variables. Do this after kindGeneralize which may
-- default kind variables to *.
; implicit_tvs <- zonkAndScopedSort implicit_tvs
; univ_tvs <- mapM zonkTyCoVarKind univ_tvs
; ex_tvs <- mapM zonkTyCoVarKind ex_tvs
; req <- zonkTcTypes req
; prov <- zonkTcTypes prov
; body_ty <- zonkTcType body_ty
-- Skolems have TcLevels too, though they're used only for debugging.
-- If you don't do this, the debugging checks fail in TcPatSyn.
-- Test case: patsyn/should_compile/T13441
{-
; tclvl <- getTcLevel
; let env0 = mkEmptyTCvSubst $ mkInScopeSet $ mkVarSet kvs
(env1, implicit_tvs') = promoteSkolemsX tclvl env0 implicit_tvs
(env2, univ_tvs') = promoteSkolemsX tclvl env1 univ_tvs
(env3, ex_tvs') = promoteSkolemsX tclvl env2 ex_tvs
req' = substTys env3 req
prov' = substTys env3 prov
body_ty' = substTy env3 body_ty
-}
; let implicit_tvs' = implicit_tvs
univ_tvs' = univ_tvs
ex_tvs' = ex_tvs
req' = req
prov' = prov
body_ty' = body_ty
-- Now do validity checking
; checkValidType ctxt $
build_patsyn_type kvs implicit_tvs' univ_tvs' req' ex_tvs' prov' body_ty'
-- arguments become the types of binders. We thus cannot allow
-- levity polymorphism here
; let (arg_tys, _) = tcSplitFunTys body_ty'
; mapM_ (checkForLevPoly empty) arg_tys
; traceTc "tcTySig }" $
vcat [ text "implicit_tvs" <+> ppr_tvs implicit_tvs'
, text "kvs" <+> ppr_tvs kvs
, text "univ_tvs" <+> ppr_tvs univ_tvs'
, text "req" <+> ppr req'
, text "ex_tvs" <+> ppr_tvs ex_tvs'
, text "prov" <+> ppr prov'
, text "body_ty" <+> ppr body_ty' ]
; return (TPSI { patsig_name = name
, patsig_implicit_bndrs = mkTyVarBinders Inferred kvs ++
mkTyVarBinders Specified implicit_tvs'
, patsig_univ_bndrs = univ_tvs'
, patsig_req = req'
, patsig_ex_bndrs = ex_tvs'
, patsig_prov = prov'
, patsig_body_ty = body_ty' }) }
where
ctxt = PatSynCtxt name
build_patsyn_type kvs imp univ req ex prov body
= mkInvForAllTys kvs $
mkSpecForAllTys (imp ++ univ) $
mkPhiTy req $
mkSpecForAllTys ex $
mkPhiTy prov $
body
tcPatSynSig _ (XHsImplicitBndrs nec) = noExtCon nec
ppr_tvs :: [TyVar] -> SDoc
ppr_tvs tvs = braces (vcat [ ppr tv <+> dcolon <+> ppr (tyVarKind tv)
| tv <- tvs])
{- *********************************************************************
* *
Instantiating user signatures
* *
********************************************************************* -}
tcInstSig :: TcIdSigInfo -> TcM TcIdSigInst
-- Instantiate a type signature; only used with plan InferGen
tcInstSig sig@(CompleteSig { sig_bndr = poly_id, sig_loc = loc })
= setSrcSpan loc $ -- Set the binding site of the tyvars
do { (tv_prs, theta, tau) <- tcInstType newMetaTyVarTyVars poly_id
-- See Note [Pattern bindings and complete signatures]
; return (TISI { sig_inst_sig = sig
, sig_inst_skols = tv_prs
, sig_inst_wcs = []
, sig_inst_wcx = Nothing
, sig_inst_theta = theta
, sig_inst_tau = tau }) }
tcInstSig hs_sig@(PartialSig { psig_hs_ty = hs_ty
, sig_ctxt = ctxt
, sig_loc = loc })
= setSrcSpan loc $ -- Set the binding site of the tyvars
do { traceTc "Staring partial sig {" (ppr hs_sig)
; (wcs, wcx, tv_prs, theta, tau) <- tcHsPartialSigType ctxt hs_ty
-- See Note [Checking partial type signatures] in TcHsType
; let inst_sig = TISI { sig_inst_sig = hs_sig
, sig_inst_skols = tv_prs
, sig_inst_wcs = wcs
, sig_inst_wcx = wcx
, sig_inst_theta = theta
, sig_inst_tau = tau }
; traceTc "End partial sig }" (ppr inst_sig)
; return inst_sig }
{- Note [Pattern bindings and complete signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T a = MkT a a
f :: forall a. a->a
g :: forall b. b->b
MkT f g = MkT (\x->x) (\y->y)
Here we'll infer a type from the pattern of 'T a', but if we feed in
the signature types for f and g, we'll end up unifying 'a' and 'b'
So we instantiate f and g's signature with TyVarTv skolems
(newMetaTyVarTyVars) that can unify with each other. If too much
unification takes place, we'll find out when we do the final
impedance-matching check in TcBinds.mkExport
See Note [Signature skolems] in TcType
None of this applies to a function binding with a complete
signature, which doesn't use tcInstSig. See TcBinds.tcPolyCheck.
-}
{- *********************************************************************
* *
Pragmas and PragEnv
* *
********************************************************************* -}
type TcPragEnv = NameEnv [LSig GhcRn]
emptyPragEnv :: TcPragEnv
emptyPragEnv = emptyNameEnv
lookupPragEnv :: TcPragEnv -> Name -> [LSig GhcRn]
lookupPragEnv prag_fn n = lookupNameEnv prag_fn n `orElse` []
extendPragEnv :: TcPragEnv -> (Name, LSig GhcRn) -> TcPragEnv
extendPragEnv prag_fn (n, sig) = extendNameEnv_Acc (:) singleton prag_fn n sig
---------------
mkPragEnv :: [LSig GhcRn] -> LHsBinds GhcRn -> TcPragEnv
mkPragEnv sigs binds
= foldl' extendPragEnv emptyNameEnv prs
where
prs = mapMaybe get_sig sigs
get_sig :: LSig GhcRn -> Maybe (Name, LSig GhcRn)
get_sig (L l (SpecSig x lnm@(L _ nm) ty inl))
= Just (nm, L l $ SpecSig x lnm ty (add_arity nm inl))
get_sig (L l (InlineSig x lnm@(L _ nm) inl))
= Just (nm, L l $ InlineSig x lnm (add_arity nm inl))
get_sig (L l (SCCFunSig x st lnm@(L _ nm) str))
= Just (nm, L l $ SCCFunSig x st lnm str)
get_sig _ = Nothing
add_arity n inl_prag -- Adjust inl_sat field to match visible arity of function
| Inline <- inl_inline inl_prag
-- add arity only for real INLINE pragmas, not INLINABLE
= case lookupNameEnv ar_env n of
Just ar -> inl_prag { inl_sat = Just ar }
Nothing -> WARN( True, text "mkPragEnv no arity" <+> ppr n )
-- There really should be a binding for every INLINE pragma
inl_prag
| otherwise
= inl_prag
-- ar_env maps a local to the arity of its definition
ar_env :: NameEnv Arity
ar_env = foldr lhsBindArity emptyNameEnv binds
lhsBindArity :: LHsBind GhcRn -> NameEnv Arity -> NameEnv Arity
lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env
= extendNameEnv env (unLoc id) (matchGroupArity ms)
lhsBindArity _ env = env -- PatBind/VarBind
-----------------
addInlinePrags :: TcId -> [LSig GhcRn] -> TcM TcId
addInlinePrags poly_id prags_for_me
| inl@(L _ prag) : inls <- inl_prags
= do { traceTc "addInlinePrag" (ppr poly_id $$ ppr prag)
; unless (null inls) (warn_multiple_inlines inl inls)
; return (poly_id `setInlinePragma` prag) }
| otherwise
= return poly_id
where
inl_prags = [L loc prag | L loc (InlineSig _ _ prag) <- prags_for_me]
warn_multiple_inlines _ [] = return ()
warn_multiple_inlines inl1@(L loc prag1) (inl2@(L _ prag2) : inls)
| inlinePragmaActivation prag1 == inlinePragmaActivation prag2
, noUserInlineSpec (inlinePragmaSpec prag1)
= -- Tiresome: inl1 is put there by virtue of being in a hs-boot loop
-- and inl2 is a user NOINLINE pragma; we don't want to complain
warn_multiple_inlines inl2 inls
| otherwise
= setSrcSpan loc $
addWarnTc NoReason
(hang (text "Multiple INLINE pragmas for" <+> ppr poly_id)
2 (vcat (text "Ignoring all but the first"
: map pp_inl (inl1:inl2:inls))))
pp_inl (L loc prag) = ppr prag <+> parens (ppr loc)
{- *********************************************************************
* *
SPECIALISE pragmas
* *
************************************************************************
Note [Handling SPECIALISE pragmas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The basic idea is this:
foo :: Num a => a -> b -> a
{-# SPECIALISE foo :: Int -> b -> Int #-}
We check that
(forall a b. Num a => a -> b -> a)
is more polymorphic than
forall b. Int -> b -> Int
(for which we could use tcSubType, but see below), generating a HsWrapper
to connect the two, something like
wrap = /\b. <hole> Int b dNumInt
This wrapper is put in the TcSpecPrag, in the ABExport record of
the AbsBinds.
f :: (Eq a, Ix b) => a -> b -> Bool
{-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-}
f = <poly_rhs>
From this the typechecker generates
AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX
-> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ])
From these we generate:
Rule: forall p, q, (dp:Ix p), (dq:Ix q).
f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq
Spec bind: f_spec = wrap_fn <poly_rhs>
Note that
* The LHS of the rule may mention dictionary *expressions* (eg
$dfIxPair dp dq), and that is essential because the dp, dq are
needed on the RHS.
* The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it
can fully specialise it.
From the TcSpecPrag, in DsBinds we generate a binding for f_spec and a RULE:
f_spec :: Int -> b -> Int
f_spec = wrap<f rhs>
RULE: forall b (d:Num b). f b d = f_spec b
The RULE is generated by taking apart the HsWrapper, which is a little
delicate, but works.
Some wrinkles
1. We don't use full-on tcSubType, because that does co and contra
variance and that in turn will generate too complex a LHS for the
RULE. So we use a single invocation of skolemise /
topInstantiate in tcSpecWrapper. (Actually I think that even
the "deeply" stuff may be too much, because it introduces lambdas,
though I think it can be made to work without too much trouble.)
2. We need to take care with type families (#5821). Consider
type instance F Int = Bool
f :: Num a => a -> F a
{-# SPECIALISE foo :: Int -> Bool #-}
We *could* try to generate an f_spec with precisely the declared type:
f_spec :: Int -> Bool
f_spec = <f rhs> Int dNumInt |> co
RULE: forall d. f Int d = f_spec |> sym co
but the 'co' and 'sym co' are (a) playing no useful role, and (b) are
hard to generate. At all costs we must avoid this:
RULE: forall d. f Int d |> co = f_spec
because the LHS will never match (indeed it's rejected in
decomposeRuleLhs).
So we simply do this:
- Generate a constraint to check that the specialised type (after
skolemiseation) is equal to the instantiated function type.
- But *discard* the evidence (coercion) for that constraint,
so that we ultimately generate the simpler code
f_spec :: Int -> F Int
f_spec = <f rhs> Int dNumInt
RULE: forall d. f Int d = f_spec
You can see this discarding happening in
3. Note that the HsWrapper can transform *any* function with the right
type prefix
forall ab. (Eq a, Ix b) => XXX
regardless of XXX. It's sort of polymorphic in XXX. This is
useful: we use the same wrapper to transform each of the class ops, as
well as the dict. That's what goes on in TcInstDcls.mk_meth_spec_prags
-}
tcSpecPrags :: Id -> [LSig GhcRn]
-> TcM [LTcSpecPrag]
-- Add INLINE and SPECIALSE pragmas
-- INLINE prags are added to the (polymorphic) Id directly
-- SPECIALISE prags are passed to the desugarer via TcSpecPrags
-- Pre-condition: the poly_id is zonked
-- Reason: required by tcSubExp
tcSpecPrags poly_id prag_sigs
= do { traceTc "tcSpecPrags" (ppr poly_id <+> ppr spec_sigs)
; unless (null bad_sigs) warn_discarded_sigs
; pss <- mapAndRecoverM (wrapLocM (tcSpecPrag poly_id)) spec_sigs
; return $ concatMap (\(L l ps) -> map (L l) ps) pss }
where
spec_sigs = filter isSpecLSig prag_sigs
bad_sigs = filter is_bad_sig prag_sigs
is_bad_sig s = not (isSpecLSig s || isInlineLSig s || isSCCFunSig s)
warn_discarded_sigs
= addWarnTc NoReason
(hang (text "Discarding unexpected pragmas for" <+> ppr poly_id)
2 (vcat (map (ppr . getLoc) bad_sigs)))
--------------
tcSpecPrag :: TcId -> Sig GhcRn -> TcM [TcSpecPrag]
tcSpecPrag poly_id prag@(SpecSig _ fun_name hs_tys inl)
-- See Note [Handling SPECIALISE pragmas]
--
-- The Name fun_name in the SpecSig may not be the same as that of the poly_id
-- Example: SPECIALISE for a class method: the Name in the SpecSig is
-- for the selector Id, but the poly_id is something like $cop
-- However we want to use fun_name in the error message, since that is
-- what the user wrote (#8537)
= addErrCtxt (spec_ctxt prag) $
do { warnIf (not (isOverloadedTy poly_ty || isInlinePragma inl))
(text "SPECIALISE pragma for non-overloaded function"
<+> quotes (ppr fun_name))
-- Note [SPECIALISE pragmas]
; spec_prags <- mapM tc_one hs_tys
; traceTc "tcSpecPrag" (ppr poly_id $$ nest 2 (vcat (map ppr spec_prags)))
; return spec_prags }
where
name = idName poly_id
poly_ty = idType poly_id
spec_ctxt prag = hang (text "In the pragma:") 2 (ppr prag)
tc_one hs_ty
= do { spec_ty <- tcHsSigType (FunSigCtxt name False) hs_ty
; wrap <- tcSpecWrapper (FunSigCtxt name True) poly_ty spec_ty
; return (SpecPrag poly_id wrap inl) }
tcSpecPrag _ prag = pprPanic "tcSpecPrag" (ppr prag)
--------------
tcSpecWrapper :: UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
-- A simpler variant of tcSubType, used for SPECIALISE pragmas
-- See Note [Handling SPECIALISE pragmas], wrinkle 1
tcSpecWrapper ctxt poly_ty spec_ty
= do { (sk_wrap, inst_wrap)
<- tcSkolemise ctxt spec_ty $ \ _ spec_tau ->
do { (inst_wrap, tau) <- topInstantiate orig poly_ty
; _ <- unifyType Nothing spec_tau tau
-- Deliberately ignore the evidence
-- See Note [Handling SPECIALISE pragmas],
-- wrinkle (2)
; return inst_wrap }
; return (sk_wrap <.> inst_wrap) }
where
orig = SpecPragOrigin ctxt
--------------
tcImpPrags :: [LSig GhcRn] -> TcM [LTcSpecPrag]
-- SPECIALISE pragmas for imported things
tcImpPrags prags
= do { this_mod <- getModule
; dflags <- getDynFlags
; if (not_specialising dflags) then
return []
else do
{ pss <- mapAndRecoverM (wrapLocM tcImpSpec)
[L loc (name,prag)
| (L loc prag@(SpecSig _ (L _ name) _ _)) <- prags
, not (nameIsLocalOrFrom this_mod name) ]
; return $ concatMap (\(L l ps) -> map (L l) ps) pss } }
where
-- Ignore SPECIALISE pragmas for imported things
-- when we aren't specialising, or when we aren't generating
-- code. The latter happens when Haddocking the base library;
-- we don't want complaints about lack of INLINABLE pragmas
not_specialising dflags
| not (gopt Opt_Specialise dflags) = True
| otherwise = case hscTarget dflags of
HscNothing -> True
HscInterpreted -> True
_other -> False
tcImpSpec :: (Name, Sig GhcRn) -> TcM [TcSpecPrag]
tcImpSpec (name, prag)
= do { id <- tcLookupId name
; unless (isAnyInlinePragma (idInlinePragma id))
(addWarnTc NoReason (impSpecErr name))
; tcSpecPrag id prag }
impSpecErr :: Name -> SDoc
impSpecErr name
= hang (text "You cannot SPECIALISE" <+> quotes (ppr name))
2 (vcat [ text "because its definition has no INLINE/INLINABLE pragma"
, parens $ sep
[ text "or its defining module" <+> quotes (ppr mod)
, text "was compiled without -O"]])
where
mod = nameModule name
| sdiehl/ghc | compiler/typecheck/TcSigs.hs | bsd-3-clause | 32,518 | 0 | 21 | 9,855 | 5,026 | 2,594 | 2,432 | 361 | 24 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE UndecidableInstances #-}
module Stack.Types.Resolver
(Resolver
,IsLoaded(..)
,LoadedResolver
,ResolverWith(..)
,parseResolverText
,AbstractResolver(..)
,readAbstractResolver
,resolverRawName
,SnapName(..)
,Snapshots (..)
,renderSnapName
,parseSnapName
,SnapshotHash
,trimmedSnapshotHash
,snapshotHashToBS
,snapshotHashFromBS
,snapshotHashFromDigest
,parseCustomLocation
) where
import Crypto.Hash as Hash (hash, Digest, SHA256)
import Data.Aeson.Extended
(ToJSON, toJSON, FromJSON, parseJSON,
withObject, (.:), withText)
import qualified Data.ByteString as B
import qualified Data.ByteString.Base64.URL as B64URL
import qualified Data.HashMap.Strict as HashMap
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import Data.Text.Read (decimal)
import Data.Time (Day)
import Network.HTTP.Client (Request, parseUrlThrow)
import Options.Applicative (ReadM)
import qualified Options.Applicative.Types as OA
import Path
import Stack.Prelude
import Stack.Types.Compiler
import Stack.Types.PackageIdentifier
import qualified System.FilePath as FP
data IsLoaded = Loaded | NotLoaded
type LoadedResolver = ResolverWith SnapshotHash
type Resolver = ResolverWith (Either Request FilePath)
-- TODO: once GHC 8.0 is the lowest version we support, make these into
-- actual haddock comments...
-- | How we resolve which dependencies to install given a set of packages.
data ResolverWith customContents
= ResolverSnapshot !SnapName -- FIXME rename to ResolverStackage
-- ^ Use an official snapshot from the Stackage project, either an
-- LTS Haskell or Stackage Nightly.
| ResolverCompiler !(CompilerVersion 'CVWanted)
-- ^ Require a specific compiler version, but otherwise provide no
-- build plan. Intended for use cases where end user wishes to
-- specify all upstream dependencies manually, such as using a
-- dependency solver.
| ResolverCustom !Text !customContents
-- ^ A custom resolver based on the given location (as a raw URL
-- or filepath). If @customContents@ is a @Either Request
-- FilePath@, it represents the parsed location value (with
-- filepaths resolved relative to the directory containing the
-- file referring to the custom snapshot). Once it has been loaded
-- from disk, it will be replaced with a @SnapshotHash@ value,
-- which is used to store cached files.
deriving (Generic, Typeable, Show, Data, Eq, Functor, Foldable, Traversable)
instance Store LoadedResolver
instance NFData LoadedResolver
instance ToJSON (ResolverWith a) where
toJSON x = case x of
ResolverSnapshot name -> toJSON $ renderSnapName name
ResolverCompiler version -> toJSON $ compilerVersionText version
ResolverCustom loc _ -> toJSON loc
instance a ~ () => FromJSON (ResolverWith a) where
parseJSON = withText "ResolverWith ()" $ return . parseResolverText
-- | Convert a Resolver into its @Text@ representation for human
-- presentation. When possible, you should prefer @sdResolverName@, as
-- it will handle the human-friendly name inside a custom snapshot.
resolverRawName :: ResolverWith a -> Text
resolverRawName (ResolverSnapshot name) = renderSnapName name
resolverRawName (ResolverCompiler v) = compilerVersionText v
resolverRawName (ResolverCustom loc _ ) = "custom: " <> loc
parseCustomLocation
:: MonadThrow m
=> Maybe (Path Abs Dir) -- ^ directory config value was read from
-> ResolverWith () -- could technically be any type parameter, restricting to help with type safety
-> m Resolver
parseCustomLocation mdir (ResolverCustom t ()) =
ResolverCustom t <$> case parseUrlThrow $ T.unpack t of
Nothing -> Right <$> do
dir <-
case mdir of
Nothing -> throwM $ FilepathInDownloadedSnapshot t
Just x -> return x
let rel =
T.unpack
$ fromMaybe t
$ T.stripPrefix "file://" t <|> T.stripPrefix "file:" t
return $ toFilePath dir FP.</> rel
Just req -> return $ Left req
parseCustomLocation _ (ResolverSnapshot name) = return $ ResolverSnapshot name
parseCustomLocation _ (ResolverCompiler cv) = return $ ResolverCompiler cv
-- | Parse a @Resolver@ from a @Text@
parseResolverText :: Text -> ResolverWith ()
parseResolverText t
| Right x <- parseSnapName t = ResolverSnapshot x
| Just v <- parseCompilerVersion t = ResolverCompiler v
| otherwise = ResolverCustom t ()
-- | Either an actual resolver value, or an abstract description of one (e.g.,
-- latest nightly).
data AbstractResolver
= ARLatestNightly
| ARLatestLTS
| ARLatestLTSMajor !Int
| ARResolver !(ResolverWith ())
| ARGlobal
deriving Show
readAbstractResolver :: ReadM AbstractResolver
readAbstractResolver = do
s <- OA.readerAsk
case s of
"global" -> return ARGlobal
"nightly" -> return ARLatestNightly
"lts" -> return ARLatestLTS
'l':'t':'s':'-':x | Right (x', "") <- decimal $ T.pack x ->
return $ ARLatestLTSMajor x'
_ -> return $ ARResolver $ parseResolverText $ T.pack s
-- | The name of an LTS Haskell or Stackage Nightly snapshot.
data SnapName
= LTS !Int !Int
| Nightly !Day
deriving (Generic, Typeable, Show, Data, Eq)
instance Store SnapName
instance NFData SnapName
data BuildPlanTypesException
= ParseSnapNameException !Text
| ParseResolverException !Text
| FilepathInDownloadedSnapshot !Text
deriving Typeable
instance Exception BuildPlanTypesException
instance Show BuildPlanTypesException where
show (ParseSnapNameException t) = "Invalid snapshot name: " ++ T.unpack t
show (ParseResolverException t) = concat
[ "Invalid resolver value: "
, T.unpack t
, ". Possible valid values include lts-2.12, nightly-YYYY-MM-DD, ghc-7.10.2, and ghcjs-0.1.0_ghc-7.10.2. "
, "See https://www.stackage.org/snapshots for a complete list."
]
show (FilepathInDownloadedSnapshot url) = unlines
[ "Downloaded snapshot specified a 'resolver: { location: filepath }' "
, "field, but filepaths are not allowed in downloaded snapshots.\n"
, "Filepath specified: " ++ T.unpack url
]
-- | Convert a 'SnapName' into its short representation, e.g. @lts-2.8@,
-- @nightly-2015-03-05@.
renderSnapName :: SnapName -> Text
renderSnapName (LTS x y) = T.pack $ concat ["lts-", show x, ".", show y]
renderSnapName (Nightly d) = T.pack $ "nightly-" ++ show d
-- | Parse the short representation of a 'SnapName'.
parseSnapName :: MonadThrow m => Text -> m SnapName
parseSnapName t0 =
case lts <|> nightly of
Nothing -> throwM $ ParseSnapNameException t0
Just sn -> return sn
where
lts = do
t1 <- T.stripPrefix "lts-" t0
Right (x, t2) <- Just $ decimal t1
t3 <- T.stripPrefix "." t2
Right (y, "") <- Just $ decimal t3
return $ LTS x y
nightly = do
t1 <- T.stripPrefix "nightly-" t0
Nightly <$> readMaybe (T.unpack t1)
-- | Most recent Nightly and newest LTS version per major release.
data Snapshots = Snapshots
{ snapshotsNightly :: !Day
, snapshotsLts :: !(IntMap Int)
}
deriving Show
instance FromJSON Snapshots where
parseJSON = withObject "Snapshots" $ \o -> Snapshots
<$> (o .: "nightly" >>= parseNightly)
<*> fmap IntMap.unions (mapM (parseLTS . snd)
$ filter (isLTS . fst)
$ HashMap.toList o)
where
parseNightly t =
case parseSnapName t of
Left e -> fail $ show e
Right (LTS _ _) -> fail "Unexpected LTS value"
Right (Nightly d) -> return d
isLTS = ("lts-" `T.isPrefixOf`)
parseLTS = withText "LTS" $ \t ->
case parseSnapName t of
Left e -> fail $ show e
Right (LTS x y) -> return $ IntMap.singleton x y
Right (Nightly _) -> fail "Unexpected nightly value"
newtype SnapshotHash = SnapshotHash { unSnapshotHash :: StaticSHA256 }
deriving (Generic, Typeable, Show, Data, Eq)
instance Store SnapshotHash
instance NFData SnapshotHash
-- | Return the first 12 characters of the hash as a B64URL-encoded
-- string.
trimmedSnapshotHash :: SnapshotHash -> Text
trimmedSnapshotHash = decodeUtf8 . B.take 12 . B64URL.encode . staticSHA256ToRaw . unSnapshotHash
-- | Return the raw bytes in the hash
snapshotHashToBS :: SnapshotHash -> ByteString
snapshotHashToBS = staticSHA256ToRaw . unSnapshotHash
-- | Create a new SnapshotHash by SHA256 hashing the given contents
snapshotHashFromBS :: ByteString -> SnapshotHash
snapshotHashFromBS = snapshotHashFromDigest . Hash.hash
-- | Create a new SnapshotHash from the given digest
snapshotHashFromDigest :: Digest SHA256 -> SnapshotHash
snapshotHashFromDigest = SnapshotHash . mkStaticSHA256FromDigest
| MichielDerhaeg/stack | src/Stack/Types/Resolver.hs | bsd-3-clause | 9,591 | 0 | 18 | 2,161 | 2,005 | 1,056 | 949 | 220 | 5 |
{-# LANGUAGE FlexibleContexts, TypeOperators, OverloadedStrings, GADTs, ScopedTypeVariables, RankNTypes, KindSignatures, MultiParamTypeClasses, FlexibleInstances, GeneralizedNewtypeDeriving #-}
-- Experiment with the JsonRpc API
import Prelude hiding ((.), id)
import Control.Category
import Data.Aeson
import Control.Natural
import Control.Wakarusa.Join1
import Control.Wakarusa.Session
import Control.Wakarusa.JsonRpc
import Control.Wakarusa.Session.Scotty
import Control.Category ((>>>))
import Web.Scotty
import Square
main = do
let rule = scottyServer "/rpc" $ rpcServer >>> run1 evalSquare
scotty 3000 rule
| ku-fpg/wakarusa | wakarusa-examples/json-rpc/JsonRpcServer.hs | bsd-3-clause | 625 | 0 | 12 | 73 | 113 | 67 | 46 | 15 | 1 |
module Aws.Core.Protocol (
Protocol (..),
defaultPort,
Method (..),
httpMethod,
sig3XJsonMime,
sig3JsonMime, sig4JsonMime,
awsMimeBS
) where
import qualified Data.ByteString.Char8 as B
import qualified Network.HTTP.Types as HTTP
newtype AwsMime = AwsMime B.ByteString
-- | The default port to be used for a protocol if no specific port is specified.
defaultPort :: Protocol -> Int
defaultPort HTTP = 80
defaultPort HTTPS = 443
-- | Protocols supported by AWS.
-- Currently, all AWS services use the HTTP or HTTPS protocols.
data Protocol = HTTP | HTTPS
deriving (Show)
-- | Request method. Not all request methods are supported by all services.
data Method
= Head -- ^ HEAD method. Put all request parameters in a query string and HTTP headers.
| Get -- ^ GET method. Put all request parameters in a query string and HTTP headers.
| PostQuery -- ^ POST method. Put all request parameters in a query string and HTTP headers, but send the query string
-- as a POST payload
| Post -- ^ POST method. Sends a service- and request-specific request body.
| Put -- ^ PUT method.
| Delete -- ^ DELETE method.
deriving (Show, Eq)
-- | HTTP method associated with a request method.
httpMethod :: Method -> HTTP.Method
httpMethod Head = "HEAD"
httpMethod Get = "GET"
httpMethod PostQuery = "POST"
httpMethod Post = "POST"
httpMethod Put = "PUT"
httpMethod Delete = "DELETE"
awsMimeBS :: AwsMime -> B.ByteString
awsMimeBS (AwsMime bs) = bs
sig3JsonMime :: AwsMime
sig3JsonMime = AwsMime "application/json; charset=UTF-8"
sig4JsonMime :: AwsMime
sig4JsonMime = sig3JsonMime
sig3XJsonMime :: AwsMime
sig3XJsonMime = AwsMime "application/x-amz-json-1.0"
| RayRacine/aws | Aws/Core/Protocol.hs | bsd-3-clause | 1,768 | 0 | 7 | 388 | 276 | 166 | 110 | 39 | 1 |
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Type (buildType, elabType, elabType',
elabPostulate, elabExtern) where
import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.DSL
import Idris.Error
import Idris.Delaborate
import Idris.Imports
import Idris.Elab.Term
import Idris.Coverage
import Idris.DataOpts
import Idris.Providers
import Idris.Primitives
import Idris.Inliner
import Idris.PartialEval
import Idris.DeepSeq
import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting)
import IRTS.Lang
import Idris.Elab.Utils
import Idris.Elab.Value
import Idris.Core.TT
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Execute
import Idris.Core.Typecheck
import Idris.Core.CaseTree
import Idris.Docstrings (Docstring)
import Prelude hiding (id, (.))
import Control.Category
import Control.Applicative hiding (Const)
import Control.DeepSeq
import Control.Monad
import Control.Monad.State.Strict as State
import Data.List
import Data.Maybe
import Debug.Trace
import qualified Data.Traversable as Traversable
import qualified Data.Map as Map
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Char(isLetter, toLower)
import Data.List.Split (splitOn)
import Util.Pretty(pretty, text)
buildType :: ElabInfo -> SyntaxInfo -> FC -> FnOpts -> Name -> PTerm ->
Idris (Type, Type, PTerm, [(Int, Name)])
buildType info syn fc opts n ty' = do
ctxt <- getContext
i <- getIState
logLvl 2 $ show n ++ " pre-type " ++ showTmImpls ty' ++ show (no_imp syn)
ty' <- addUsingConstraints syn fc ty'
ty' <- addUsingImpls syn n fc ty'
let ty = addImpl (imp_methods syn) i ty'
logLvl 5 $ show n ++ " type pre-addimpl " ++ showTmImpls ty'
logLvl 2 $ show n ++ " type " ++ show (using syn) ++ "\n" ++ showTmImpls ty
(ElabResult tyT' defer is ctxt' newDecls highlights, log) <-
tclift $ elaborate ctxt (idris_datatypes i) n (TType (UVal 0)) initEState
(errAt "type of " n (erun fc (build i info ETyDecl [] n ty)))
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
let tyT = patToImp tyT'
logLvl 3 $ show ty ++ "\nElaborated: " ++ show tyT'
ds <- checkAddDef True False fc iderr defer
-- if the type is not complete, note that we'll need to infer
-- things later (for solving metavariables)
when (length ds > length is) -- more deferred than case blocks
$ addTyInferred n
mapM_ (elabCaseBlock info opts) is
ctxt <- getContext
logLvl 5 $ "Rechecking"
logLvl 6 $ show tyT
logLvl 10 $ "Elaborated to " ++ showEnvDbg [] tyT
(cty, ckind) <- recheckC fc id [] tyT
-- record the implicit and inaccessible arguments
i <- getIState
let (inaccData, impls) = unzip $ getUnboundImplicits i cty ty
let inacc = inaccessibleImps 0 cty inaccData
logLvl 3 $ show n ++ ": inaccessible arguments: " ++ show inacc ++
" from " ++ show cty ++ "\n" ++ showTmImpls ty
putIState $ i { idris_implicits = addDef n impls (idris_implicits i) }
logLvl 3 ("Implicit " ++ show n ++ " " ++ show impls)
addIBC (IBCImp n)
when (Constructor `notElem` opts) $ do
let pnames = getParamsInType i [] impls cty
let fninfo = FnInfo (param_pos 0 pnames cty)
setFnInfo n fninfo
addIBC (IBCFnInfo n fninfo)
return (cty, ckind, ty, inacc)
where
patToImp (Bind n (PVar t) sc) = Bind n (Pi Nothing t (TType (UVar 0))) (patToImp sc)
patToImp (Bind n b sc) = Bind n b (patToImp sc)
patToImp t = t
param_pos i ns (Bind n (Pi _ t _) sc)
| n `elem` ns = i : param_pos (i + 1) ns sc
| otherwise = param_pos (i + 1) ns sc
param_pos i ns t = []
-- | Elaborate a top-level type declaration - for example, "foo : Int -> Int".
elabType :: ElabInfo -> SyntaxInfo
-> Docstring (Either Err PTerm) -> [(Name, Docstring (Either Err PTerm))]
-> FC -> FnOpts
-> Name -> FC -- ^ The precise location of the name
-> PTerm -> Idris Type
elabType = elabType' False
elabType' :: Bool -> -- normalise it
ElabInfo -> SyntaxInfo ->
Docstring (Either Err PTerm) -> [(Name, Docstring (Either Err PTerm))] ->
FC -> FnOpts -> Name -> FC -> PTerm -> Idris Type
elabType' norm info syn doc argDocs fc opts n nfc ty' = {- let ty' = piBind (params info) ty_in
n = liftname info n_in in -}
do checkUndefined fc n
(cty, _, ty, inacc) <- buildType info syn fc opts n ty'
addStatics n cty ty
let nty = cty -- normalise ctxt [] cty
-- if the return type is something coinductive, freeze the definition
ctxt <- getContext
logLvl 2 $ "Rechecked to " ++ show nty
let nty' = normalise ctxt [] nty
logLvl 2 $ "Rechecked to " ++ show nty'
-- Add normalised type to internals
i <- getIState
rep <- useREPL
when rep $ do
addInternalApp (fc_fname fc) (fst . fc_start $ fc) ty' -- (mergeTy ty' (delab i nty')) -- TODO: Should use span instead of line and filename?
addIBC (IBCLineApp (fc_fname fc) (fst . fc_start $ fc) ty') -- (mergeTy ty' (delab i nty')))
let (fam, _) = unApply (getRetTy nty')
let corec = case fam of
P _ rcty _ -> case lookupCtxt rcty (idris_datatypes i) of
[TI _ True _ _ _] -> True
_ -> False
_ -> False
-- Productivity checking now via checking for guarded 'Delay'
let opts' = opts -- if corec then (Coinductive : opts) else opts
let usety = if norm then nty' else nty
ds <- checkDef fc iderr [(n, (-1, Nothing, usety))]
addIBC (IBCDef n)
let ds' = map (\(n, (i, top, fam)) -> (n, (i, top, fam, True))) ds
addDeferred ds'
setFlags n opts'
checkDocs fc argDocs ty
doc' <- elabDocTerms info doc
argDocs' <- mapM (\(n, d) -> do d' <- elabDocTerms info d
return (n, d')) argDocs
addDocStr n doc' argDocs'
addIBC (IBCDoc n)
addIBC (IBCFlags n opts')
fputState (opt_inaccessible . ist_optimisation n) inacc
addIBC (IBCOpt n)
when (Implicit `elem` opts') $ do addCoercion n
addIBC (IBCCoercion n)
when (AutoHint `elem` opts') $
case fam of
P _ tyn _ -> do addAutoHint tyn n
addIBC (IBCAutoHint tyn n)
t -> ifail $ "Hints must return a data or record type"
-- If the function is declared as an error handler and the language
-- extension is enabled, then add it to the list of error handlers.
errorReflection <- fmap (elem ErrorReflection . idris_language_extensions) getIState
when (ErrorHandler `elem` opts) $ do
if errorReflection
then
-- Check that the declared type is the correct type for an error handler:
-- handler : List (TTName, TT) -> Err -> ErrorReport - for now no ctxt
if tyIsHandler nty'
then do i <- getIState
putIState $ i { idris_errorhandlers = idris_errorhandlers i ++ [n] }
addIBC (IBCErrorHandler n)
else ifail $ "The type " ++ show nty' ++ " is invalid for an error handler"
else ifail "Error handlers can only be defined when the ErrorReflection language extension is enabled."
-- Send highlighting information about the name being declared
sendHighlighting [(nfc, AnnName n Nothing Nothing Nothing)]
-- if it's an export list type, make a note of it
case (unApply usety) of
(P _ ut _, _)
| ut == ffiexport -> do addIBC (IBCExport n)
addExport n
_ -> return ()
return usety
where
-- for making an internalapp, we only want the explicit ones, and don't
-- want the parameters, so just take the arguments which correspond to the
-- user declared explicit ones
mergeTy (PPi e n fc ty sc) (PPi e' n' _ _ sc')
| e == e' = PPi e n fc ty (mergeTy sc sc')
| otherwise = mergeTy sc sc'
mergeTy _ sc = sc
ffiexport = sNS (sUN "FFI_Export") ["FFI_Export"]
err = txt "Err"
maybe = txt "Maybe"
lst = txt "List"
errrep = txt "ErrorReportPart"
tyIsHandler (Bind _ (Pi _ (P _ (NS (UN e) ns1) _) _)
(App _ (P _ (NS (UN m) ns2) _)
(App _ (P _ (NS (UN l) ns3) _)
(P _ (NS (UN r) ns4) _))))
| e == err && m == maybe && l == lst && r == errrep
, ns1 == map txt ["Errors","Reflection","Language"]
, ns2 == map txt ["Maybe", "Prelude"]
, ns3 == map txt ["List", "Prelude"]
, ns4 == map txt ["Reflection","Language"] = True
tyIsHandler _ = False
elabPostulate :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) ->
FC -> FnOpts -> Name -> PTerm -> Idris ()
elabPostulate info syn doc fc opts n ty = do
elabType info syn doc [] fc opts n NoFC ty
putIState . (\ist -> ist{ idris_postulates = S.insert n (idris_postulates ist) }) =<< getIState
addIBC (IBCPostulate n)
-- remove it from the deferred definitions list
solveDeferred n
elabExtern :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) ->
FC -> FnOpts -> Name -> PTerm -> Idris ()
elabExtern info syn doc fc opts n ty = do
cty <- elabType info syn doc [] fc opts n NoFC ty
ist <- getIState
let arity = length (getArgTys (normalise (tt_ctxt ist) [] cty))
putIState . (\ist -> ist{ idris_externs = S.insert (n, arity) (idris_externs ist) }) =<< getIState
addIBC (IBCExtern (n, arity))
-- remove it from the deferred definitions list
solveDeferred n
| BartAdv/Idris-dev | src/Idris/Elab/Type.hs | bsd-3-clause | 10,448 | 0 | 19 | 3,426 | 3,207 | 1,604 | 1,603 | 197 | 10 |
{-# LANGUAGE
RecordWildCards
, DeriveDataTypeable
#-}
{-|
Primitives for the memcached protocol.
-}
module Network.Starling.Core
( Request
, requestOp
, Key
, Value
, set
, add
, replace
, get
, increment
, decrement
, append
, prepend
, delete
, quit
, flush
, noop
, version
, stat
, listAuthMechanisms
, startAuth
, stepAuth
, AuthMechanism
, AuthData
, addOpaque
, addCAS
, Response(..)
, getResponse
, StarlingReadError(..)
, Serialize(..)
, Deserialize(..)
, Opaque
, OpCode(..)
, DataType(..)
, CAS
, nullCAS
, ResponseStatus(..)
) where
import System.IO
import Control.Applicative ((<$>))
import Control.Exception
import Data.Maybe (fromMaybe)
import Data.Typeable
import Data.Word
import Data.Monoid (mconcat)
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BS
import qualified Data.Binary.Builder as B
import qualified Data.Binary.Get as B
type Opaque = Word32
type Key = ByteString
type Value = ByteString
type ErrorInfo = ByteString
-- | Set a value in the cache.
set :: Word32 -> Key -> Value -> Request
set expiry key value
= let extras = setExtras 0 expiry
in request Set extras key value
-- | Add a value to cache. Fails if
-- already present.
add :: Word32 -> Key -> Value -> Request
add expiry key value
= let extras = setExtras 0 expiry
in request Add extras key value
-- | Replaces a value in cahce. Fails if
-- not present.
replace :: Word32 -> Key -> Value -> Request
replace expiry key value
= let extras = setExtras 0 expiry
in request Replace extras key value
setExtras :: Word32 -> Word32 -> ByteString
setExtras flags expiry
= B.toLazyByteString $ mconcat
[ B.putWord32be flags
, B.putWord32be expiry
]
-- | Get a value from cache
get :: Key -> Request
get key = request Get BS.empty key BS.empty
increment :: Key
-> Word64 -- ^ amount
-> Word64 -- ^ initial value
-> Request
increment key amount init
= let extras = incExtras amount init 0
in request Increment extras key BS.empty
decrement :: Key
-> Word64 -- ^ amount
-> Word64 -- ^ initial value
-> Request
decrement key amount init
= let extras = incExtras amount init 0
in request Decrement extras key BS.empty
incExtras :: Word64 -> Word64 -> Word32 -> ByteString
incExtras amount init expiry
= B.toLazyByteString $ mconcat
[ B.putWord64be amount
, B.putWord64be init
, B.putWord32be expiry
]
-- | Delete a cache entry
delete :: Key -> Request
delete key
= request Delete BS.empty key BS.empty
-- | Quit
quit :: Request
quit = request Quit BS.empty BS.empty BS.empty
-- | Flush the cache
flush :: Request
flush
= let extras = B.toLazyByteString $ B.putWord32be 0 -- expiry
in request Flush extras BS.empty BS.empty
-- | Keepalive. Flushes responses for quiet operations.
noop :: Request
noop = request NoOp BS.empty BS.empty BS.empty
-- | Returns the server version
version :: Request
version = request Version BS.empty BS.empty BS.empty
-- | Appends the value to the value in the cache
append :: Key -> Value -> Request
append key value
= request Append BS.empty key value
-- | Prepends the value to the value in the cache
prepend :: Key -> Value -> Request
prepend key value
= request Prepend BS.empty key value
-- | Fetch statistics about the cahce. Returns a sequence
-- of responses.
stat :: Maybe Key -> Request
stat mkey = request Stat BS.empty (fromMaybe BS.empty mkey) BS.empty
-- | List SASL authenitication mechanisms, space delimeted
listAuthMechanisms :: Request
listAuthMechanisms = request ListAuthMechanisms BS.empty BS.empty BS.empty
-- | Begin SASL authentication. May return the further auth
-- required error if further steps are needed.
startAuth :: AuthMechanism -> AuthData -> Request
startAuth mech auth = request StartAuth BS.empty mech auth
-- | Continue SASL authentication. May return the further
-- aut required error if further steps are needed.
stepAuth :: AuthMechanism -> AuthData -> Request
stepAuth mech auth = request StepAuth BS.empty mech auth
type AuthMechanism = ByteString
type AuthData = ByteString
-- | Add an opaque marker to a request.
-- This is returned unchanged in the corresponding
-- response.
addOpaque :: Opaque -> Request -> Request
addOpaque n req = req { rqOpaque = n }
-- | Add a version tag to a request. When
-- added to a set/replace request, the request
-- will fail if the data has been modified since
-- the CAS was retrieved for the item.
addCAS :: CAS -> Request -> Request
addCAS n req = req { rqCas = n }
class Serialize a where
serialize :: a -> B.Builder
class Deserialize a where
deserialize :: B.Get a
data Request
= Req
{ rqMagic :: RqMagic
, rqOp :: OpCode
, rqDataType :: DataType
, rqOpaque :: Opaque
, rqCas :: CAS
, rqExtras :: ByteString
, rqKey :: ByteString
, rqBody :: ByteString
}
deriving (Eq, Ord, Read, Show)
instance Serialize Request where
serialize Req{..} =
let keyLen = BS.length rqKey
extraLen = BS.length rqExtras
bodyLen = BS.length rqBody
in mconcat
[ serialize rqMagic
, serialize rqOp
, B.putWord16be (fromIntegral keyLen)
, B.singleton (fromIntegral extraLen)
, serialize rqDataType
, B.putWord16be 0 -- reserved
, B.putWord32be (fromIntegral $ keyLen + extraLen + bodyLen)
, B.putWord32be rqOpaque
, serialize rqCas
, B.fromLazyByteString rqExtras
, B.fromLazyByteString rqKey
, B.fromLazyByteString rqBody
]
-- | A starter request with fields set to reasonable
-- defaults. The opcode field is left undefined.
baseRequest :: Request
baseRequest
= Req { rqOp = undefined
, rqMagic = Request
, rqKey = BS.empty
, rqExtras = BS.empty
, rqDataType = RawData
, rqBody = BS.empty
, rqOpaque = 0
, rqCas = nullCAS
}
-- | Returns the operation the request will perform
requestOp :: Request -> OpCode
requestOp = rqOp
request :: OpCode
-> BS.ByteString -- ^ Extras
-> BS.ByteString -- ^ Key
-> BS.ByteString -- ^ Body
-> Request
request opCode extras key body
= let extraLen = fromIntegral (BS.length extras)
keyLen = fromIntegral (BS.length key)
in baseRequest
{ rqOp = opCode
, rqExtras = extras
, rqKey = key
, rqBody = body
}
newtype CAS = CAS Word64
deriving (Eq, Ord, Read, Show)
instance Serialize CAS where
serialize (CAS n)
= B.putWord64be n
instance Deserialize CAS where
deserialize = CAS <$> B.getWord64be
nullCAS :: CAS
nullCAS = CAS 0
data Response
= Res
{ rsMagic :: RsMagic
, rsOp :: OpCode
, rsDataType :: DataType
, rsStatus :: ResponseStatus
, rsOpaque :: Opaque
, rsCas :: CAS
, rsExtras :: ByteString
, rsKey :: ByteString
, rsBody :: ByteString
}
deriving (Eq, Ord, Read, Show)
instance Deserialize Response where
deserialize = do
rsMagic <- deserialize
rsOp <- deserialize
rsKeyLen <- B.getWord16be
rsExtraLen <- B.getWord8
rsDataType <- deserialize
rsStatus <- deserialize
rsTotalLen <- B.getWord32be
let totalLen = fromIntegral rsTotalLen
keyLen = fromIntegral rsKeyLen
extraLen = fromIntegral rsExtraLen
rsOpaque <- B.getWord32be
rsCas <- deserialize
rsExtras <- B.getLazyByteString extraLen
rsKey <- B.getLazyByteString keyLen
rsBody <- B.getLazyByteString (totalLen - extraLen - keyLen)
return Res{..}
newtype ResponseHeader
= ResHead
{ rsHeadTotalLen :: Word32 }
instance Deserialize ResponseHeader where
deserialize = do
_ <- B.getBytes 8
rsHeadTotalLen <- B.getWord32be
_ <- B.getBytes 12
return ResHead{..}
-- | Pulls a reponse to an operation
-- off of a handle.
-- May throw a 'StarlingReadError'
getResponse :: Handle -> IO Response
getResponse h = do
chunk <- BS.hGet h 24
if BS.length chunk /= 24 then throw StarlingReadError else do
let resHeader = B.runGet deserialize chunk
bodyLen = rsHeadTotalLen resHeader
rest <- BS.hGet h $ fromIntegral bodyLen
return . B.runGet deserialize $ chunk `BS.append` rest
data StarlingReadError = StarlingReadError
deriving (Show, Typeable)
instance Exception StarlingReadError
data RqMagic = Request
deriving (Eq, Ord, Read, Show)
instance Serialize RqMagic where
serialize Request = B.singleton 0x80
data RsMagic = Response
deriving (Eq, Ord, Read, Show)
instance Deserialize RsMagic where
deserialize = do
magic <- B.getWord8
case magic of
0x81 -> return Response
data DataType = RawData
deriving (Eq, Ord, Read, Show)
instance Serialize DataType where
serialize RawData = B.singleton 0x00
instance Deserialize DataType where
deserialize = do
dtype <- B.getWord8
case dtype of
0x00 -> return RawData
data ResponseStatus
= NoError
| KeyNotFound
| KeyExists
| ValueTooLarge
| InvalidArguments
| ItemNotStored
| IncrDecrOnNonNumeric
| AuthRequired
| FurtherAuthRequired
| UnknownCommand
| OutOfMemory
deriving (Eq, Ord, Read, Show, Typeable)
instance Exception ResponseStatus
instance Deserialize ResponseStatus where
deserialize = do
status <- B.getWord16be
return $ case status of
0x0000 -> NoError
0x0001 -> KeyNotFound
0x0002 -> KeyExists
0x0003 -> ValueTooLarge
0x0004 -> InvalidArguments
0x0005 -> ItemNotStored
0x0006 -> IncrDecrOnNonNumeric
0x0020 -> AuthRequired
0x0021 -> FurtherAuthRequired
0x0081 -> UnknownCommand
0x0082 -> OutOfMemory
data OpCode
= Get
| Set
| Add
| Replace
| Delete
| Increment
| Decrement
| Quit
| Flush
| GetQ
| NoOp
| Version
| GetK
| GetKQ
| Append
| Prepend
| Stat
| SetQ
| AddQ
| ReplaceQ
| DeleteQ
| IncrementQ
| DecrementQ
| QuitQ
| FlushQ
| AppendQ
| PrependQ
| ListAuthMechanisms
| StartAuth
| StepAuth
deriving (Eq, Ord, Read, Show)
instance Serialize OpCode where
serialize Get = B.singleton 0x00
serialize Set = B.singleton 0x01
serialize Add = B.singleton 0x02
serialize Replace = B.singleton 0x03
serialize Delete = B.singleton 0x04
serialize Increment = B.singleton 0x05
serialize Decrement = B.singleton 0x06
serialize Quit = B.singleton 0x07
serialize Flush = B.singleton 0x08
serialize GetQ = B.singleton 0x09
serialize NoOp = B.singleton 0x0a
serialize Version = B.singleton 0x0b
serialize GetK = B.singleton 0x0c
serialize GetKQ = B.singleton 0x0d
serialize Append = B.singleton 0x0e
serialize Prepend = B.singleton 0x0f
serialize Stat = B.singleton 0x10
serialize SetQ = B.singleton 0x11
serialize AddQ = B.singleton 0x12
serialize ReplaceQ = B.singleton 0x13
serialize DeleteQ = B.singleton 0x14
serialize IncrementQ = B.singleton 0x15
serialize DecrementQ = B.singleton 0x16
serialize QuitQ = B.singleton 0x17
serialize FlushQ = B.singleton 0x18
serialize AppendQ = B.singleton 0x19
serialize PrependQ = B.singleton 0x1a
serialize ListAuthMechanisms = B.singleton 0x20
serialize StartAuth = B.singleton 0x21
serialize StepAuth = B.singleton 0x22
instance Deserialize OpCode where
deserialize = do
command <- B.getWord8
return $ case command of
0x00 -> Get
0x01 -> Set
0x02 -> Add
0x03 -> Replace
0x04 -> Delete
0x05 -> Increment
0x06 -> Decrement
0x07 -> Quit
0x08 -> Flush
0x09 -> GetQ
0x0a -> NoOp
0x0b -> Version
0x0c -> GetK
0x0d -> GetKQ
0x0e -> Append
0x0f -> Prepend
0x10 -> Stat
0x11 -> SetQ
0x12 -> AddQ
0x13 -> ReplaceQ
0x14 -> DeleteQ
0x15 -> IncrementQ
0x16 -> DecrementQ
0x17 -> QuitQ
0x18 -> FlushQ
0x19 -> AppendQ
0x1a -> PrependQ
0x20 -> ListAuthMechanisms
0x21 -> StartAuth
0x22 -> StepAuth
| silkapp/starling | Network/Starling/Core.hs | bsd-3-clause | 12,769 | 0 | 14 | 3,665 | 3,268 | 1,729 | 1,539 | -1 | -1 |
{-# LANGUAGE CPP #-}
module Bead.Persistence.Relations (
userAssignmentKeys
, userAssignmentKeyList
, submissionDesc
, submissionListDesc
, submissionDetailsDesc
, groupDescription
, isAdminedSubmission
, canUserCommentOn
, submissionTables
, courseSubmissionTableInfo
, userSubmissionDesc
, userLastSubmissionInfo
, courseOrGroupOfAssignment
, courseOrGroupOfAssessment
, courseNameAndAdmins
, administratedGroupsWithCourseName
, groupsOfUsersCourse
, removeOpenedSubmission
, deleteUserFromCourse -- Deletes a user from a course, searching the roup id for the unsubscription
, isThereASubmissionForGroup -- Checks if the user submitted any solutions for the group
, isThereASubmissionForCourse -- Checks if the user submitted any solutions for the course
, testScriptInfo -- Calculates the test script information for the given test key
, openedSubmissionInfo -- Calculates the opened submissions for the user from the administrated groups and courses
, submissionLimitOfAssignment
, scoreBoards
, scoreInfo
, scoreDesc
, assessmentDesc
, userAssessmentKeys
, notificationReference
#ifdef TEST
, persistRelationsTests
#endif
) where
{-
This module contains higher level functionality for querying information
useing the primitves defined in the Persist module. Mainly Relations module
related information is computed.
-}
import Control.Applicative
import Control.Arrow
import Control.Monad (foldM, forM, when)
import Control.Monad.IO.Class
import Data.Function (on)
import Data.List ((\\), nub, sortBy, intersect, find)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Time (UTCTime, getCurrentTime)
import Bead.Domain.Entities
import qualified Bead.Domain.Entity.Assignment as Assignment
import qualified Bead.Domain.Entity.Notification as Notification
import Bead.Domain.Relationships
import Bead.Domain.Shared.Evaluation
import Bead.Persistence.Persist
import Bead.View.Translation
#ifdef TEST
import Bead.Persistence.Initialization
import Test.Tasty.TestSet
#endif
-- * Combined Persistence Tasks
-- Computes the Group key list, which should contain one element,
-- for a course key and a user, which the user attends in.
groupsOfUsersCourse :: Username -> CourseKey -> Persist [GroupKey]
groupsOfUsersCourse u ck = do
ugs <- nub <$> userGroups u
cgs <- nub <$> groupKeysOfCourse ck
return $ intersect ugs cgs
-- Produces a Just Assignment list, if the user is registered for some courses,
-- otherwise Nothing.
userAssignmentKeys :: Username -> Persist (Map CourseKey (Set AssignmentKey))
userAssignmentKeys u = do
gs <- nub <$> userGroups u
cs <- nub <$> userCourses u
case (cs,gs) of
([],[]) -> return Map.empty
_ -> do
gas <- foldM groupAssignment Map.empty gs
as <- foldM courseAssignment gas cs
return $! as
where
groupAssignment m gk = do
ck <- courseOfGroup gk
(insert ck) <$> (Set.fromList <$> groupAssignments gk) <*> (pure m)
courseAssignment m ck =
(insert ck) <$> (Set.fromList <$> courseAssignments ck) <*> (pure m)
insert k v m =
maybe (Map.insert k v m) (flip (Map.insert k) m . (Set.union v)) $ Map.lookup k m
#ifdef TEST
userAssignmentKeysTest = do
let course = Course "name" "desc" TestScriptSimple
group = Group "name" "desc"
asg = Assignment "name" "desc" Assignment.emptyAspects time time binaryConfig
time = read "2014-06-09 12:55:27.959203 UTC"
user1name = Username "USER1"
user1 = User Student user1name (Email "email") "name"
(TimeZoneName "Europe/Budapest") (Language "hu")
(Uid "USER1")
ioTest "User assignment keys with group and course assignments" $ do
init <- createPersistInit defaultConfig
interp <- createPersistInterpreter defaultConfig
initPersist init
result <- runPersist interp $ do
saveUser user1
c <- saveCourse course
g <- saveGroup c group
a1 <- saveCourseAssignment c asg
a2 <- saveCourseAssignment c asg
a3 <- saveGroupAssignment g asg
a4 <- saveGroupAssignment g asg
keys <- userAssignmentKeys user1name
equals Map.empty keys "The unsubscribed user has some assignment keys"
subscribe user1name c g
keyMap <- userAssignmentKeys user1name
equals
(Map.fromList [ (c,Set.fromList [a1,a2,a3,a4])])
keyMap
"The assignment of the users was different than the sum of the course and group assignment"
return ()
tearDown init
return result
return ()
#endif
-- Produces the assignment key list for the user, it the user
-- is not registered in any course the result is the empty list
userAssignmentKeyList :: Username -> Persist [AssignmentKey]
userAssignmentKeyList u = (nub . concat . map (Set.toList . snd) . Map.toList) <$> (userAssignmentKeys u)
courseOrGroupOfAssignment :: AssignmentKey -> Persist (Either CourseKey GroupKey)
courseOrGroupOfAssignment ak = do
mGk <- groupOfAssignment ak
case mGk of
Just gk -> return . Right $ gk
Nothing -> do
mCk <- courseOfAssignment ak
case mCk of
Just ck -> return . Left $ ck
Nothing -> error $ "Impossible: No course or groupkey was found for the assignment:" ++ show ak
administratedGroupsWithCourseName :: Username -> Persist [(GroupKey, Group, String)]
administratedGroupsWithCourseName u = do
gs <- administratedGroups u
forM gs $ \(gk,g) -> do
fn <- fullGroupName gk
return (gk,g,fn)
-- Produces a full name for a group including the name of the course.
fullGroupName :: GroupKey -> Persist String
fullGroupName gk = do
ck <- courseOfGroup gk
course <- loadCourse ck
group <- loadGroup gk
return $ concat [(courseName course), " - ", (groupName group)]
groupDescription :: GroupKey -> Persist (GroupKey, GroupDesc)
groupDescription gk = do
name <- fullGroupName gk
admins <- mapM (userDescription) =<< (groupAdmins gk)
let gd = GroupDesc {
gName = name
, gAdmins = map ud_fullname admins
}
return (gk,gd)
submissionDesc :: SubmissionKey -> Persist SubmissionDesc
submissionDesc sk = do
submission <- loadSubmission sk
un <- usernameOfSubmission sk
user <- loadUser un
let u = u_name user
let uid = u_uid user
info <- submissionInfo sk
ak <- assignmentOfSubmission sk
asg <- loadAssignment ak
created <- assignmentCreatedTime ak
cgk <- courseOrGroupOfAssignment ak
cs <- commentsOfSubmission sk >>= \cks -> forM cks $ \ck ->
(,) ck <$> loadComment ck
fs <- mapM loadFeedback =<< (feedbacksOfSubmission sk)
case cgk of
Left ck -> do
course <- loadCourse ck
return SubmissionDesc {
eCourse = courseName course
, eGroup = Nothing
, eStudent = u
, eUsername = un
, eUid = uid
, eSolution = submissionValue id (const "zipped") (solution submission)
, eSubmissionInfo = info
, eAssignment = asg
, eAssignmentKey = ak
, eAssignmentDate = created
, eSubmissionDate = solutionPostDate submission
, eComments = Map.fromList cs
, eFeedbacks = fs
}
Right gk -> do
group <- loadGroup gk
let gname = groupName group
ck <- courseOfGroup gk
cname <- courseName <$> loadCourse ck
return SubmissionDesc {
eCourse = cname
, eGroup = Just $ groupName group
, eStudent = u
, eUsername = un
, eUid = uid
, eSolution = submissionValue id (const "zipped") (solution submission)
, eSubmissionInfo = info
, eAssignment = asg
, eAssignmentKey = ak
, eAssignmentDate = created
, eSubmissionDate = solutionPostDate submission
, eComments = Map.fromList cs
, eFeedbacks = fs
}
-- Calculates the opened submissions for the user from the administrated groups and courses
openedSubmissionInfo :: Username -> Persist OpenedSubmissions
openedSubmissionInfo u = do
acs <- map fst <$> administratedCourses u
ags <- map fst <$> administratedGroups u
agcs <- (\\ acs) <$> mapM courseOfGroup ags
courseAsgs <- concat <$> mapM courseAssignments acs
groupAsgs <- concat <$> mapM groupAssignments ags
let isCourseAsg = flip elem courseAsgs
let isGroupAsg = flip elem groupAsgs
relatedCourseAsgs <- concat <$> mapM courseAssignments agcs
let isRelatedCourseAsg = flip elem relatedCourseAsgs
courseUser <- (Set.fromList . concat) <$> mapM subscribedToCourse acs
subscribedToGroupAgs <- (Set.fromList . concat) <$> mapM subscribedToGroup ags
let isGroupUser = flip Set.member subscribedToGroupAgs
subscribedToCourseAgcs <- (flip Set.difference courseUser . Set.fromList . concat) <$> mapM subscribedToCourse agcs
let isRelatedCourseUser = flip Set.member subscribedToCourseAgcs
let isCourseUser = flip Set.member courseUser
-- Non Evaluated Submissions
nonEvalSubs <- openedSubmissionSubset
(Set.fromList $ concat [courseAsgs, groupAsgs, relatedCourseAsgs]) -- Assignments
(foldr1 Set.union [subscribedToGroupAgs, subscribedToCourseAgcs, courseUser]) -- Users
assignmentAndUsers <- mapM assignmentAndUserOfSubmission nonEvalSubs
let filterSubmissions os (sk, ak, student) =
let sku = (sk, ()) in
let separate ak student
| (isRelatedCourseAsg ak && isGroupUser student) = os { osAdminedCourse = sku:osAdminedCourse os }
| (isCourseAsg ak && isGroupUser student) = os { osAdminedCourse = sku:osAdminedCourse os }
| (isGroupAsg ak && isGroupUser student) = os { osAdminedGroup = sku:osAdminedGroup os }
| (isRelatedCourseAsg ak && isRelatedCourseUser student) = os { osRelatedCourse = sku:osRelatedCourse os }
| (isCourseAsg ak && isRelatedCourseUser student) = os { osRelatedCourse = sku:osRelatedCourse os }
| (isCourseAsg ak && isCourseUser student) = os { osRelatedCourse = sku:osRelatedCourse os }
| otherwise = os
in separate ak student
let OpenedSubmissions adminedCourse adminedGroup relatedCourse
= foldl filterSubmissions empty assignmentAndUsers
OpenedSubmissions
<$> mapM (submissionKeyAndDesc . fst) adminedCourse
<*> mapM (submissionKeyAndDesc . fst) adminedGroup
<*> mapM (submissionKeyAndDesc . fst) relatedCourse
where
empty = OpenedSubmissions [] [] []
submissionKeyAndDesc sk =
(,) <$> pure sk <*> submissionDesc sk
assignmentAndUserOfSubmission sk =
(,,) <$> pure sk <*> assignmentOfSubmission sk <*> usernameOfSubmission sk
courseNameAndAdmins :: AssignmentKey -> Persist (CourseName, [UsersFullname])
courseNameAndAdmins ak = do
eCkGk <- courseOrGroupOfAssignment ak
(name, admins) <- case eCkGk of
Left ck -> do
name <- courseName <$> loadCourse ck
admins <- courseAdmins ck
return (name, admins)
Right gk -> do
name <- fullGroupName gk
admins <- groupAdmins gk
return (name, admins)
adminNames <- mapM (fmap ud_fullname . userDescription) admins
return (name, adminNames)
submissionListDesc :: Username -> AssignmentKey -> Persist SubmissionListDesc
submissionListDesc u ak = do
(name, adminNames) <- courseNameAndAdmins ak
asg <- loadAssignment ak
now <- liftIO getCurrentTime
submissions <- do
us <- userSubmissions u ak
mapM submissionStatus us
return SubmissionListDesc {
slGroup = name
, slTeacher = adminNames
, slAssignment = asg
, slSubmissions = submissions
}
where
submissionStatus sk = do
time <- solutionPostDate <$> loadSubmission sk
si <- submissionInfo sk
return (sk, time, si, "TODO: EvaluatedBy")
submissionTime sk = solutionPostDate <$> loadSubmission sk
submissionEvalStr :: SubmissionKey -> Persist (Maybe String)
submissionEvalStr sk = do
mEk <- evaluationOfSubmission sk
case mEk of
Nothing -> return Nothing
Just ek -> eString <$> loadEvaluation ek
where
eString = Just . translateMessage trans . resultString . evaluationResult
submissionDetailsDesc :: SubmissionKey -> Persist SubmissionDetailsDesc
submissionDetailsDesc sk = do
ak <- assignmentOfSubmission sk
(name, adminNames) <- courseNameAndAdmins ak
asg <- loadAssignment ak
sol <- solution <$> loadSubmission sk
cs <- commentsOfSubmission sk >>= \cks -> forM cks $ \ck ->
(,) ck <$> loadComment ck
fs <- mapM loadFeedback =<< (feedbacksOfSubmission sk)
s <- submissionEvalStr sk
return SubmissionDetailsDesc {
sdGroup = name
, sdTeacher = adminNames
, sdAssignment = asg
, sdStatus = s
, sdSubmission = submissionValue id (const "zipped") sol
, sdComments = Map.fromList cs
, sdFeedbacks = fs
}
-- | Checks if the assignment of the submission is adminstrated by the user
isAdminedSubmission :: Username -> SubmissionKey -> Persist Bool
isAdminedSubmission u sk = do
-- Assignment of the submission
ak <- assignmentOfSubmission sk
-- Assignment Course Key
ack <- either return (courseOfGroup) =<< (courseOrGroupOfAssignment ak)
-- All administrated courses
groupCourses <- mapM (courseOfGroup . fst) =<< (administratedGroups u)
courses <- map fst <$> administratedCourses u
let allCourses = nub (groupCourses ++ courses)
return $ elem ack allCourses
-- TODO
canUserCommentOn :: Username -> SubmissionKey -> Persist Bool
canUserCommentOn _u _sk = return True
-- Returns all the submissions of the users for the groups that the
-- user administrates
submissionTables :: Username -> Persist [SubmissionTableInfo]
submissionTables u = do
groupKeys <- map fst <$> administratedGroups u
groupTables <- mapM (groupSubmissionTableInfo) groupKeys
return groupTables
groupSubmissionTableInfo :: GroupKey -> Persist SubmissionTableInfo
groupSubmissionTableInfo gk = do
ck <- courseOfGroup gk
gassignments <- groupAssignments gk
cassignments <- courseAssignments ck
usernames <- subscribedToGroup gk
name <- fullGroupName gk
mkGroupSubmissionTableInfo name usernames cassignments gassignments ck gk
-- Returns the course submission table information for the given course key
courseSubmissionTableInfo :: CourseKey -> Persist SubmissionTableInfo
courseSubmissionTableInfo ck = do
assignments <- courseAssignments ck
usernames <- subscribedToCourse ck
name <- courseName <$> loadCourse ck
mkCourseSubmissionTableInfo name usernames assignments ck
-- Sort the given keys into an ordered list based on the time function
sortKeysByTime :: (key -> Persist UTCTime) -> [key] -> Persist [key]
sortKeysByTime time keys = map snd . sortBy (compare `on` fst) <$> mapM getTime keys
where
getTime k = do
t <- time k
return (t,k)
loadAssignmentInfos :: [AssignmentKey] -> Persist (Map AssignmentKey Assignment)
loadAssignmentInfos as = Map.fromList <$> mapM loadAssignmentInfo as
where
loadAssignmentInfo a = do
asg <- loadAssignment a
return (a,asg)
submissionInfoAsgKey :: Username -> AssignmentKey -> Persist (AssignmentKey, SubmissionInfo)
submissionInfoAsgKey u ak = addKey <$> (userLastSubmissionInfo u ak)
where
addKey s = (ak,s)
-- TODO: Need to be add semantics there
calculateResult :: [SubmissionInfo] -> Maybe Result
calculateResult _ = Nothing
#ifdef TEST
calculateResultTests = do
eqPartitions calculateResult
[ Partition "Empty list" [] Nothing ""
, Partition "One binary submission" [Submission_Result undefined (binaryResult Passed)] Nothing ""
, Partition "One percentage submission" [Submission_Result undefined (percentageResult 0.1)] Nothing ""
]
#endif
mkCourseSubmissionTableInfo
:: String -> [Username] -> [AssignmentKey] -> CourseKey
-> Persist SubmissionTableInfo
mkCourseSubmissionTableInfo courseName us as key = do
assignments <- sortKeysByTime assignmentCreatedTime as
assignmentInfos <- loadAssignmentInfos as
ulines <- forM us $ \u -> do
ud <- userDescription u
asi <- mapM (submissionInfoAsgKey u) as
let result = case asi of
[] -> Nothing
_ -> calculateResult $ map snd asi
return (ud, result, Map.fromList asi)
return CourseSubmissionTableInfo {
stiCourse = courseName
, stiUsers = us
, stiAssignments = assignments
, stiUserLines = ulines
, stiAssignmentInfos = assignmentInfos
, stiCourseKey = key
}
mkGroupSubmissionTableInfo
:: String
-> [Username] -> [AssignmentKey] -> [AssignmentKey]
-> CourseKey -> GroupKey
-> Persist SubmissionTableInfo
mkGroupSubmissionTableInfo courseName us cas gas ckey gkey = do
cgAssignments <- sortKeysByTime createdTime ((map CourseInfo cas) ++ (map GroupInfo gas))
assignmentInfos <- loadAssignmentInfos (cas ++ gas)
ulines <- forM us $ \u -> do
ud <- userDescription u
casi <- mapM (submissionInfoAsgKey u) cas
gasi <- mapM (submissionInfoAsgKey u) gas
let result = case gasi of
[] -> Nothing
_ -> calculateResult $ map snd gasi
return (ud, result, Map.fromList (casi ++ gasi))
return GroupSubmissionTableInfo {
stiCourse = courseName
, stiUsers = us
, stiCGAssignments = cgAssignments
, stiUserLines = ulines
, stiAssignmentInfos = assignmentInfos
, stiCourseKey = ckey
, stiGroupKey = gkey
}
where
createdTime = cgInfoCata
(assignmentCreatedTime)
(assignmentCreatedTime)
submissionInfo :: SubmissionKey -> Persist SubmissionInfo
submissionInfo sk = do
mEk <- evaluationOfSubmission sk
case mEk of
Nothing -> do
fs <- mapM loadFeedback =<< (feedbacksOfSubmission sk)
-- Supposing that only one test result feedback will arrive
-- to a submission.
return . maybe
Submission_Unevaluated
Submission_Tested
$ feedbackTestResult =<< lastTestAgentFeedback fs
Just ek -> (Submission_Result ek . evaluationResult) <$> loadEvaluation ek
where
lastTestAgentFeedback = find isTestedFeedback . reverse . sortBy createdDate
createdDate = compare `on` postDate
-- Produces information for the given score
scoreInfo :: ScoreKey -> Persist ScoreInfo
scoreInfo sk = do
mEk <- evaluationOfScore sk
case mEk of
Nothing -> return Score_Not_Found
Just ek -> Score_Result ek . evaluationResult <$> loadEvaluation ek
-- Produces information of the last submission for the given user and assignment
userLastSubmissionInfo :: Username -> AssignmentKey -> Persist SubmissionInfo
userLastSubmissionInfo u ak =
(maybe (return Submission_Not_Found) (submissionInfo)) =<< (lastSubmission ak u)
userSubmissionDesc :: Username -> AssignmentKey -> Persist UserSubmissionDesc
userSubmissionDesc u ak = do
-- Calculate the normal fields
asgName <- Assignment.name <$> loadAssignment ak
courseOrGroup <- courseOrGroupOfAssignment ak
crName <- case courseOrGroup of
Left ck -> courseName <$> loadCourse ck
Right gk -> fullGroupName gk
student <- ud_fullname <$> userDescription u
keys <- userSubmissions u ak
-- Calculate the submission information list
submissions <- flip mapM keys $ \sk -> do
time <- solutionPostDate <$> loadSubmission sk
sinfo <- submissionInfo sk
return (sk, time, sinfo)
return UserSubmissionDesc {
usCourse = crName
, usAssignmentName = asgName
, usStudent = student
, usSubmissions = submissions
}
-- Helper computation which removes the given submission from
-- the opened submission directory, which is optimized by
-- assignment and username keys, for the quickier lookup
removeOpenedSubmission :: SubmissionKey -> Persist ()
removeOpenedSubmission sk = do
ak <- assignmentOfSubmission sk
u <- usernameOfSubmission sk
removeFromOpened ak u sk
-- Make unsibscribe a user from a course if the user attends in the course
-- otherwise do nothing
deleteUserFromCourse :: CourseKey -> Username -> Persist ()
deleteUserFromCourse ck u = do
cs <- userCourses u
when (ck `elem` cs) $ do
gs <- userGroups u
-- Collects all the courses for the user's group
cgMap <- Map.fromList <$> (forM gs $ runKleisli ((k (courseOfGroup)) &&& (k return)))
-- Unsubscribe the user from a given course with the found group
maybe
(return ()) -- TODO: Logging should be usefull
(unsubscribe u ck)
(Map.lookup ck cgMap)
where
k = Kleisli
testScriptInfo :: TestScriptKey -> Persist TestScriptInfo
testScriptInfo tk = do
script <- loadTestScript tk
return TestScriptInfo {
tsiName = tsName script
, tsiDescription = tsDescription script
, tsiType = tsType script
}
-- Returns True if the given student submitted at least one solution for the
-- assignments for the given group, otherwise False
isThereASubmissionForGroup :: Username -> GroupKey -> Persist Bool
isThereASubmissionForGroup u gk = do
aks <- groupAssignments gk
(not . null . catMaybes) <$> mapM (flip (lastSubmission) u) aks
-- Returns True if the given student submitted at least one solution for the
-- assignments for the given group, otherwise False
isThereASubmissionForCourse :: Username -> CourseKey -> Persist Bool
isThereASubmissionForCourse u ck = do
aks <- courseAssignments ck
(not . null . catMaybes) <$> mapM (flip (lastSubmission) u) aks
-- Returns the number of the possible submission for the given assignment
-- by the given user.
submissionLimitOfAssignment :: Username -> AssignmentKey -> Persist SubmissionLimit
submissionLimitOfAssignment username key =
calcSubLimit <$> (loadAssignment key) <*> (length <$> userSubmissions username key)
scoreBoards :: Username -> Persist (Map (Either CourseKey GroupKey) ScoreBoard)
scoreBoards u = do
groupKeys <- map (Right . fst) <$> administratedGroups u
courseKeys <- map (Left . fst) <$> administratedCourses u
let keys = courseKeys ++ groupKeys
Map.fromList . zip keys <$> mapM scoreBoard keys
scoreBoard :: Either CourseKey GroupKey -> Persist ScoreBoard
scoreBoard key = do
assessmentKeys <- assessmentsOf
users <- subscriptions
board <- foldM boardColumn (Map.empty,Map.empty) assessmentKeys
assessments <- mapM loadAssessment assessmentKeys
userDescriptions <- mapM userDescription users
name <- loadName
return $ mkScoreBoard board name (zip assessmentKeys assessments) userDescriptions
where
mkScoreBoard (scores,infos) n as us =
either (\k -> CourseScoreBoard scores infos k n as us)
(\k -> GroupScoreBoard scores infos k n as us)
key
assessmentsOf = either assessmentsOfCourse assessmentsOfGroup key
subscriptions = either subscribedToCourse subscribedToGroup key
loadName = either (fmap courseName . loadCourse) (fmap groupName . loadGroup) key
boardColumn :: (Map (AssessmentKey,Username) ScoreKey,Map ScoreKey ScoreInfo)
-> AssessmentKey
-> Persist (Map (AssessmentKey,Username) ScoreKey,Map ScoreKey ScoreInfo)
boardColumn board assessment = do
scoresKeys <- scoresOfAssessment assessment
foldM (cell assessment) board scoresKeys
cell assessment (scores,infos) scoreKey = do
user <- usernameOfScore scoreKey
info <- scoreInfo scoreKey
return (Map.insert (assessment,user) scoreKey scores,Map.insert scoreKey info infos)
scoreDesc :: ScoreKey -> Persist ScoreDesc
scoreDesc sk = do
ak <- assessmentOfScore sk
as <- loadAssessment ak
info <- scoreInfo sk
courseOrGroup <- courseOrGroupOfAssessment ak
(course,group,teachers) <- case courseOrGroup of
Left ck -> do
course <- loadCourse ck
teachers <- courseAdmins ck
return (courseName course,Nothing,teachers)
Right gk -> do
group <- loadGroup gk
ck <- courseOfGroup gk
course <- loadCourse ck
teachers <- groupAdmins gk
return (courseName course,Just . groupName $ group,teachers)
teachersName <- mapM ((ud_fullname <$>) . userDescription) teachers
return $ ScoreDesc course group teachersName info as
assessmentDesc :: AssessmentKey -> Persist AssessmentDesc
assessmentDesc ak = do
courseOrGroup <- courseOrGroupOfAssessment ak
(course,group) <- case courseOrGroup of
Left ck -> do
course <- loadCourse ck
return (courseName course,Nothing)
Right gk -> do
group <- loadGroup gk
ck <- courseOfGroup gk
course <- loadCourse ck
return (courseName course,Just . groupName $ group)
assessment <- loadAssessment ak
return $ AssessmentDesc course group ak assessment
courseOrGroupOfAssessment :: AssessmentKey -> Persist (Either CourseKey GroupKey)
courseOrGroupOfAssessment ak = do
maybeGk <- groupOfAssessment ak
case maybeGk of
Just gk -> return . Right $ gk
Nothing -> do
maybeCk <- courseOfAssessment ak
case maybeCk of
Just ck -> return . Left $ ck
Nothing -> error $ "Impossible: No course or groupkey was found for the assessment:" ++ show ak
-- Produces a map from the user's courses to set of every assessment of the course. The map is empty if the user is not subscribed to groups or courses.
-- Per group assessments are included.
userAssessmentKeys :: Username -> Persist (Map CourseKey (Set AssessmentKey))
userAssessmentKeys u = do
gs <- nub <$> userGroups u
cs <- nub <$> userCourses u
case (cs,gs) of
([],[]) -> return Map.empty
_ -> do
gas <- foldM groupAssessment Map.empty gs
as <- foldM courseAssessment gas cs
return $! as
where
groupAssessment m gk = do
ck <- courseOfGroup gk
(insert ck) <$> (Set.fromList <$> assessmentsOfGroup gk) <*> (pure m)
courseAssessment m ck =
(insert ck) <$> (Set.fromList <$> assessmentsOfCourse ck) <*> (pure m)
insert k v m =
maybe (Map.insert k v m) (flip (Map.insert k) m . (Set.union v)) $ Map.lookup k m
notificationReference :: Notification.NotificationType -> Persist Notification.NotificationReference
notificationReference = Notification.notificationType comment evaluation assignment assessment system
where
comment ck = do
sk <- submissionOfComment ck
ak <- assignmentOfSubmission sk
return $ Notification.NRefComment ak sk ck
evaluation ek = do
msubk <- submissionOfEvaluation ek
mscrk <- scoreOfEvaluation ek
case (msubk, mscrk) of
(Nothing, Nothing) -> error "No submission or score are found for evaluation."
(Just _, Just _) -> error "Both submission and score are found for evaluation."
(Just sk, Nothing) -> do
ak <- assignmentOfSubmission sk
return $ Notification.NRefSubmissionEvaluation ak sk ek
(Nothing, Just sk) ->
return $ Notification.NRefScoreEvaluation sk ek
assignment ak = return $ Notification.NRefAssignment ak
assessment ak = return $ Notification.NRefAssessment ak
system = return Notification.NRefSystem
#ifdef TEST
persistRelationsTests = do
userAssignmentKeysTest
calculateResultTests
#endif
| andorp/bead | src/Bead/Persistence/Relations.hs | bsd-3-clause | 27,512 | 0 | 21 | 6,265 | 7,333 | 3,604 | 3,729 | 533 | 4 |
-- ghc -O2 -fspec-constr-recursive=10 -fmax-worker-args=16
-- Convert the input file to camel case and write to stdout
import Data.Maybe (fromJust, isJust)
import System.Environment (getArgs)
import System.IO (Handle, IOMode(..), openFile, stdout)
import qualified Streamly.Prelude as S
import qualified Streamly.Internal.FileSystem.Handle as FH
camelCase :: Handle -> Handle -> IO ()
camelCase src dst =
FH.fromBytes dst
$ S.map fromJust
$ S.filter isJust
$ S.map snd
$ S.scanl' step (True, Nothing)
$ FH.toBytes src
where
step (wasSpace, _) x =
if x == 0x0a || x >= 0x41 && x <= 0x5a
then (False, Just x)
else if x >= 0x61 && x <= 0x7a
then (False, Just $ if wasSpace then x - 32 else x)
else (True, Nothing)
main :: IO ()
main = do
name <- fmap head getArgs
src <- openFile name ReadMode
camelCase src stdout
| harendra-kumar/asyncly | examples/CamelCase.hs | bsd-3-clause | 915 | 0 | 12 | 240 | 303 | 165 | 138 | 24 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module System.Metrics.Prometheus.RegistryT where
import Control.Applicative ((<$>))
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trans.Class (MonadTrans)
import Control.Monad.Trans.State.Strict (StateT (..),
evalStateT,
execStateT, get)
import System.Metrics.Prometheus.Metric.Counter (Counter)
import System.Metrics.Prometheus.Metric.Gauge (Gauge)
import System.Metrics.Prometheus.Metric.Histogram (Histogram)
import qualified System.Metrics.Prometheus.Metric.Histogram as Histogram
import System.Metrics.Prometheus.MetricId (Labels, Name)
import System.Metrics.Prometheus.Registry (Registry,
RegistrySample,
new)
import qualified System.Metrics.Prometheus.Registry as R
newtype RegistryT m a =
RegistryT { unRegistryT :: StateT Registry m a }
deriving (Monad, MonadTrans, Applicative, Functor, MonadIO)
evalRegistryT :: Monad m => RegistryT m a -> m a
evalRegistryT = flip evalStateT new . unRegistryT
execRegistryT :: Monad m => RegistryT m a -> m Registry
execRegistryT = flip execStateT new . unRegistryT
runRegistryT :: Monad m => RegistryT m a -> m (a, Registry)
runRegistryT = flip runStateT new . unRegistryT
withRegistry :: MonadIO m => (Registry -> m (a, Registry)) -> RegistryT m a
withRegistry = RegistryT . StateT
registerCounter :: MonadIO m => Name -> Labels -> RegistryT m Counter
registerCounter n l = withRegistry (liftIO . R.registerCounter n l)
registerGauge :: MonadIO m => Name -> Labels -> RegistryT m Gauge
registerGauge n l = withRegistry (liftIO . R.registerGauge n l)
registerHistogram :: MonadIO m => Name -> Labels -> [Histogram.UpperBound] -> RegistryT m Histogram
registerHistogram n l u = withRegistry (liftIO . R.registerHistogram n l u)
sample :: Monad m => RegistryT m (IO RegistrySample)
sample = R.sample <$> RegistryT get
| LukeHoersten/prometheus | src/System/Metrics/Prometheus/RegistryT.hs | bsd-3-clause | 2,292 | 0 | 10 | 694 | 584 | 325 | 259 | 36 | 1 |
module Data.Typewriter.Data.Binary ( module Data.Typewriter.Data.Binary.Bit
, module Data.Typewriter.Data.Binary.BitList
) where
import Data.Typewriter.Data.Binary.Bit
import Data.Typewriter.Data.Binary.BitList
| isomorphism/typewriter | Data/Typewriter/Data/Binary.hs | bsd-3-clause | 282 | 0 | 5 | 85 | 44 | 33 | 11 | 4 | 0 |
{-|
Module: Data.Astro.Types
Description: Common Types
Copyright: Alexander Ignatyev, 2016
Common Types are usfull across all subsystems like Time and Coordinate.
= Examples
== /Decimal hours and Decimal degrees/
@
import Data.Astro.Types
-- 10h 15m 19.7s
dh :: DecimalHours
dh = fromHMS 10 15 19.7
-- DH 10.255472222222222
(h, m, s) = toHMS dh
-- (10,15,19.699999999999562)
-- 51°28′40″
dd :: DecimalDegrees
dd = fromDMS 51 28 40
-- DD 51.477777777777774
(d, m, s) = toDMS dd
-- (51,28,39.999999999987494)
@
== /Geographic Coordinates/
@
import Data.Astro.Types
-- the Royal Observatory, Greenwich
ro :: GeographicCoordinates
ro = GeoC (fromDMS 51 28 40) (-(fromDMS 0 0 5))
-- GeoC {geoLatitude = DD 51.4778, geoLongitude = DD (-0.0014)}
@
-}
module Data.Astro.Types
(
DecimalDegrees(..)
, DecimalHours (..)
, GeographicCoordinates(..)
, AstronomicalUnits(..)
, lightTravelTime
, kmToAU
, auToKM
, toDecimalHours
, fromDecimalHours
, toRadians
, fromRadians
, fromDMS
, toDMS
, fromHMS
, toHMS
)
where
import qualified Data.Astro.Utils as U
newtype DecimalDegrees = DD Double
deriving (Show, Eq, Ord)
instance Num DecimalDegrees where
(+) (DD d1) (DD d2) = DD (d1+d2)
(-) (DD d1) (DD d2) = DD (d1-d2)
(*) (DD d1) (DD d2) = DD (d1*d2)
negate (DD d) = DD (negate d)
abs (DD d) = DD (abs d)
signum (DD d) = DD (signum d)
fromInteger int = DD (fromInteger int)
instance Real DecimalDegrees where
toRational (DD d) = toRational d
instance Fractional DecimalDegrees where
(/) (DD d1) (DD d2) = DD (d1/d2)
recip (DD d) = DD (recip d)
fromRational r = DD (fromRational r)
instance RealFrac DecimalDegrees where
properFraction (DD d) =
let (i, f) = properFraction d
in (i, DD f)
newtype DecimalHours = DH Double
deriving (Show, Eq, Ord)
instance Num DecimalHours where
(+) (DH d1) (DH d2) = DH (d1+d2)
(-) (DH d1) (DH d2) = DH (d1-d2)
(*) (DH d1) (DH d2) = DH (d1*d2)
negate (DH d) = DH (negate d)
abs (DH d) = DH (abs d)
signum (DH d) = DH (signum d)
fromInteger int = DH (fromInteger int)
instance Real DecimalHours where
toRational (DH d) = toRational d
instance Fractional DecimalHours where
(/) (DH d1) (DH d2) = DH (d1/d2)
recip (DH d) = DH (recip d)
fromRational r = DH (fromRational r)
instance RealFrac DecimalHours where
properFraction (DH d) =
let (i, f) = properFraction d
in (i, DH f)
-- | Convert decimal degrees to decimal hours
toDecimalHours :: DecimalDegrees -> DecimalHours
toDecimalHours (DD d) = DH $ d/15 -- 360 / 24 = 15
-- | Convert decimal hours to decimal degrees
fromDecimalHours :: DecimalHours -> DecimalDegrees
fromDecimalHours (DH h) = DD $ h*15
-- | Geographic Coordinates
data GeographicCoordinates = GeoC {
geoLatitude :: DecimalDegrees
, geoLongitude :: DecimalDegrees
} deriving (Show, Eq)
-- | Astronomical Units, 1AU = 1.4960×1011 m
-- (originally, the average distance of Earth's aphelion and perihelion).
newtype AstronomicalUnits = AU Double deriving (Show, Eq, Ord)
instance Num AstronomicalUnits where
(+) (AU d1) (AU d2) = AU (d1+d2)
(-) (AU d1) (AU d2) = AU (d1-d2)
(*) (AU d1) (AU d2) = AU (d1*d2)
negate (AU d) = AU (negate d)
abs (AU d) = AU (abs d)
signum (AU d) = AU (signum d)
fromInteger int = AU (fromInteger int)
instance Real AstronomicalUnits where
toRational (AU d) = toRational d
instance Fractional AstronomicalUnits where
(/) (AU d1) (AU d2) = AU (d1/d2)
recip (AU d) = AU (recip d)
fromRational r = AU (fromRational r)
instance RealFrac AstronomicalUnits where
properFraction (AU d) =
let (i, f) = properFraction d
in (i, AU f)
-- | Light travel time of the distance in Astronomical Units
lightTravelTime :: AstronomicalUnits -> DecimalHours
lightTravelTime (AU ro) = DH $ 0.1386*ro
kmInOneAU :: Double
kmInOneAU = 149597870.700
-- | Convert from kilometers to Astronomical Units
kmToAU :: Double -> AstronomicalUnits
kmToAU km = AU (km / kmInOneAU)
-- | Comvert from Astronomical Units to kilometers
auToKM :: AstronomicalUnits -> Double
auToKM (AU au) = au * kmInOneAU
-- | Convert from DecimalDegrees to Radians
toRadians (DD deg) = U.toRadians deg
-- | Convert from Radians to DecimalDegrees
fromRadians rad = DD $ U.fromRadians rad
-- | Convert Degrees, Minutes, Seconds to DecimalDegrees
fromDMS :: RealFrac a => Int -> Int -> a -> DecimalDegrees
fromDMS d m s =
let d' = fromIntegral d
m' = fromIntegral m
s' = realToFrac s
in DD $ d'+(m'+(s'/60))/60
-- | Convert DecimalDegrees to Degrees, Minutes, Seconds
toDMS (DD dd) =
let (d, rm) = properFraction dd
(m, rs) = properFraction $ 60 * rm
s = 60 * rs
in (d, m, s)
-- | Comvert Hours, Minutes, Seconds to DecimalHours
fromHMS :: RealFrac a => Int -> Int -> a -> DecimalHours
fromHMS h m s =
let h' = fromIntegral h
m' = fromIntegral m
s' = realToFrac s
in DH $ h'+(m'+(s'/60))/60
-- | Convert DecimalDegrees to Degrees, Minutes, Seconds
toHMS (DH dh) =
let (h, rm) = properFraction dh
(m, rs) = properFraction $ 60 * rm
s = 60 * rs
in (h, m, s)
| Alexander-Ignatyev/astro | src/Data/Astro/Types.hs | bsd-3-clause | 5,167 | 0 | 12 | 1,146 | 1,784 | 932 | 852 | 117 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.License
-- Copyright : Isaac Jones 2003-2005
-- Duncan Coutts 2008
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- The License datatype. For more information about these and other
-- open-source licenses, you may visit <http://www.opensource.org/>.
--
-- The @.cabal@ file allows you to specify a license file. Of course you can
-- use any license you like but people often pick common open source licenses
-- and it's useful if we can automatically recognise that (eg so we can display
-- it on the hackage web pages). So you can also specify the license itself in
-- the @.cabal@ file from a short enumeration defined in this module. It
-- includes 'GPL', 'LGPL' and 'BSD3' licenses.
{- All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}
module Distribution.License (
License(..),
knownLicenses,
) where
import Distribution.Version (Version(Version))
import Distribution.Text (Text(..), display)
import qualified Distribution.Compat.ReadP as Parse
import qualified Text.PrettyPrint as Disp
import Text.PrettyPrint ((<>))
import qualified Data.Char as Char (isAlphaNum)
-- |This datatype indicates the license under which your package is
-- released. It is also wise to add your license to each source file
-- using the license-file field. The 'AllRightsReserved' constructor
-- is not actually a license, but states that you are not giving
-- anyone else a license to use or distribute your work. The comments
-- below are general guidelines. Please read the licenses themselves
-- and consult a lawyer if you are unsure of your rights to release
-- the software.
--
data License =
--TODO: * remove BSD4
-- | GNU Public License. Source code must accompany alterations.
GPL (Maybe Version)
-- | Lesser GPL, Less restrictive than GPL, useful for libraries.
| LGPL (Maybe Version)
-- | 3-clause BSD license, newer, no advertising clause. Very free license.
| BSD3
-- | 4-clause BSD license, older, with advertising clause. You almost
-- certainly want to use the BSD3 license instead.
| BSD4
-- | The MIT license, similar to the BSD3. Very free license.
| MIT
-- | Holder makes no claim to ownership, least restrictive license.
| PublicDomain
-- | No rights are granted to others. Undistributable. Most restrictive.
| AllRightsReserved
-- | Some other license.
| OtherLicense
-- | Not a recognised license.
-- Allows us to deal with future extensions more gracefully.
| UnknownLicense String
deriving (Read, Show, Eq)
knownLicenses :: [License]
knownLicenses = [ GPL unversioned, GPL (version [2]), GPL (version [3])
, LGPL unversioned, LGPL (version [2,1]), LGPL (version [3])
, BSD3, BSD4, MIT
, PublicDomain, AllRightsReserved, OtherLicense]
where
unversioned = Nothing
version v = Just (Version v [])
instance Text License where
disp (GPL version) = Disp.text "GPL" <> dispOptVersion version
disp (LGPL version) = Disp.text "LGPL" <> dispOptVersion version
disp (UnknownLicense other) = Disp.text other
disp other = Disp.text (show other)
parse = do
name <- Parse.munch1 (\c -> Char.isAlphaNum c && c /= '-')
version <- Parse.option Nothing (Parse.char '-' >> fmap Just parse)
return $! case (name, version :: Maybe Version) of
("GPL", _ ) -> GPL version
("LGPL", _ ) -> LGPL version
("BSD3", Nothing) -> BSD3
("BSD4", Nothing) -> BSD4
("MIT", Nothing) -> MIT
("PublicDomain", Nothing) -> PublicDomain
("AllRightsReserved", Nothing) -> AllRightsReserved
("OtherLicense", Nothing) -> OtherLicense
_ -> UnknownLicense $ name
++ maybe "" (('-':) . display) version
dispOptVersion :: Maybe Version -> Disp.Doc
dispOptVersion Nothing = Disp.empty
dispOptVersion (Just v) = Disp.char '-' <> disp v
| dcreager/cabal | Distribution/License.hs | bsd-3-clause | 5,627 | 0 | 16 | 1,294 | 704 | 404 | 300 | 49 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Test.Tasty
import Test.Tasty.HUnit
import IrcParser
import Data.Attoparsec.Text
testParse = parseOnly parseIrc
main = defaultMain tests
tests = testGroup "Tests" [parserTests]
parserTests :: TestTree
parserTests = testGroup "Parser tests"
[ testCase "Command only"
$ testParse "asdf" @?= (Right $ Message "" "asdf" [])
, testCase "Command plus param" $
testParse "foo bar" @?= (Right $ Message "" "foo" ["bar"])
, testCase "Command plus message" $
testParse "MSG :hey there" @?= (Right $ Message "" "MSG" ["hey there"])
, testCase "Command param plus message" $
testParse "MSG msg :hey there" @?= (Right $ Message "" "MSG" ["msg", "hey there"])
, testCase "Name plus message" $
testParse ":tolsun MSG test :hey there" @?= (Right $ Message "tolsun" "MSG" ["test", "hey there"])
]
| UnrealQuester/irc-bot | tests/test.hs | bsd-3-clause | 888 | 0 | 11 | 191 | 241 | 125 | 116 | 20 | 1 |
-- | Utilities for serving PDF from Yesod.
-- Uses and depends on command line utility wkhtmltopdf to render PDF from HTML.
module Yesod.Content.PDF
( -- * Conversion
uri2PDF
, html2PDF
-- * Data type
, PDF(..)
, typePDF
-- * Options
, def
, WkhtmltopdfOptions
, wkCollate
, wkCopies
, wkGrayscale
, wkLowQuality
, wkPageSize
, wkOrientation
, wkDisableSmartShrinking
, wkTitle
, wkMarginBottom
, wkMarginLeft
, wkMarginRight
, wkMarginTop
, wkZoom
, wkJavascriptDelay
, wkWindowStatus
, PageSize(..)
, Orientation(..)
, UnitReal(..)
) where
import Prelude
import Blaze.ByteString.Builder.ByteString
import Control.Monad.IO.Class (MonadIO(..))
import Data.ByteString
import Data.ByteString.Builder (hPutBuilder)
import Data.Conduit
import Data.Default (Default(..))
import Network.URI
import System.IO
import System.IO.Temp
import System.Process
import Text.Blaze.Html
import Text.Blaze.Html.Renderer.Utf8
import Yesod.Core.Content
newtype PDF = PDF { pdfBytes :: ByteString }
deriving (Eq, Ord, Read, Show)
-- | Provide MIME type "application/pdf" as a ContentType for Yesod.
typePDF :: ContentType
typePDF = "application/pdf"
instance HasContentType PDF where
getContentType _ = typePDF
instance ToTypedContent PDF where
toTypedContent = TypedContent typePDF . toContent
instance ToContent PDF where
toContent (PDF bs) = ContentSource $ do
yield $ Chunk $ fromByteString bs
-- | Use wkhtmltopdf to render a PDF given the URI pointing to an HTML document.
uri2PDF :: MonadIO m => WkhtmltopdfOptions -> URI -> m PDF
uri2PDF opts = wkhtmltopdf opts . flip ($) . show
-- | Use wkhtmltopdf to render a PDF from an HTML (Text.Blaze.Html) type.
html2PDF :: MonadIO m => WkhtmltopdfOptions -> Html -> m PDF
html2PDF opts html =
wkhtmltopdf opts $ \inner ->
withSystemTempFile "input.html" $ \tempHtmlFp tempHtmlHandle -> do
hSetBinaryMode tempHtmlHandle True
hSetBuffering tempHtmlHandle $ BlockBuffering Nothing
hPutBuilder tempHtmlHandle $ renderHtmlBuilder html
hClose tempHtmlHandle
inner tempHtmlFp
-- | (Internal) Call wkhtmltopdf.
wkhtmltopdf :: MonadIO m => WkhtmltopdfOptions -> ((String -> IO PDF) -> IO PDF) -> m PDF
wkhtmltopdf opts setupInput =
liftIO $
withSystemTempFile "output.pdf" $ \tempOutputFp tempOutputHandle -> do
hClose tempOutputHandle
setupInput $ \inputArg -> do
let args = toArgs opts ++ [inputArg, tempOutputFp]
(_, _, _, pHandle) <- createProcess (proc "wkhtmltopdf" args)
_ <- waitForProcess pHandle
PDF <$> Data.ByteString.readFile tempOutputFp
-- | Options passed to wkhtmltopdf. Please use the 'def' value
-- and then modify individual settings. For more information, see
-- <http://www.yesodweb.com/book/settings-types>.
data WkhtmltopdfOptions =
WkhtmltopdfOptions
{ wkCollate :: Bool
-- ^ Collate when printing multiple copies.
, wkCopies :: Int
-- ^ Number of copies to print into the PDF file.
, wkGrayscale :: Bool
-- ^ Whether output PDF should be in grayscale.
, wkLowQuality :: Bool
-- ^ Generate lower quality output to conserve space.
, wkPageSize :: PageSize
-- ^ Page size (e.g. "A4", "Letter").
, wkOrientation :: Orientation
-- ^ Orientation of the output.
, wkDisableSmartShrinking :: Bool
-- ^ Intelligent shrinking strategy used by WebKit that makes the pixel/dpi ratio none constant.
, wkTitle :: Maybe String
-- ^ Title of the generated PDF file.
, wkMarginBottom :: UnitReal
-- ^ Bottom margin size.
, wkMarginLeft :: UnitReal
-- ^ Left margin size.
, wkMarginRight :: UnitReal
-- ^ Right margin size.
, wkMarginTop :: UnitReal
-- ^ Top margin size.
, wkZoom :: Double
-- ^ Zoom factor.
, wkJavascriptDelay :: Maybe Int
-- ^ Time to wait for Javascript to finish in milliseconds.
, wkWindowStatus :: Maybe String
-- ^ String to wait for window.status to be set to.
} deriving (Eq, Ord, Show)
instance Default WkhtmltopdfOptions where
def = WkhtmltopdfOptions
{ wkCollate = True
, wkCopies = 1
, wkGrayscale = False
, wkLowQuality = False
, wkPageSize = A4
, wkOrientation = Portrait
, wkDisableSmartShrinking = False
, wkTitle = Nothing
, wkMarginBottom = Mm 10
, wkMarginLeft = Mm 0
, wkMarginRight = Mm 0
, wkMarginTop = Mm 10
, wkZoom = 1
, wkJavascriptDelay = Nothing
, wkWindowStatus = Nothing
}
-- | Cf. 'wkPageSize'.
data PageSize =
A4
| Letter
| OtherPageSize String -- ^ <http://doc.qt.io/qt-4.8/qprinter.html#PaperSize-enum>.
| CustomPageSize UnitReal UnitReal -- ^ Height and width.
deriving (Eq, Ord, Show)
-- | Cf. 'wkOrientation'.
data Orientation =
Portrait
| Landscape
deriving (Eq, Ord, Show, Enum, Bounded)
-- | A unit of measure.
data UnitReal =
Mm Double
| Cm Double
| OtherUnitReal String
deriving (Eq, Ord, Show)
-- | (Internal) Convert options to arguments.
class ToArgs a where
toArgs :: a -> [String]
instance ToArgs WkhtmltopdfOptions where
toArgs opts =
[ "--quiet"
, if wkCollate opts then "--collate" else "--no-collate"
, "--copies", show (wkCopies opts)
, "--zoom", show (wkZoom opts)
] ++
Prelude.concat
[ [ "--grayscale" | True <- [wkGrayscale opts] ]
, [ "--lowquality" | True <- [wkLowQuality opts] ]
, [ "--disable-smart-shrinking" | True <- [wkDisableSmartShrinking opts] ]
, toArgs (wkPageSize opts)
, toArgs (wkOrientation opts)
, maybe [] (\t -> ["--title", t ]) (wkTitle opts)
, maybe [] (\d -> ["--javascript-delay", show d]) (wkJavascriptDelay opts)
, maybe [] (\s -> ["--window-status", s ]) (wkWindowStatus opts)
, "--margin-bottom" : toArgs (wkMarginBottom opts)
, "--margin-left" : toArgs (wkMarginLeft opts)
, "--margin-right" : toArgs (wkMarginRight opts)
, "--margin-top" : toArgs (wkMarginTop opts)
]
instance ToArgs PageSize where
toArgs A4 = ["--page-size", "A4"]
toArgs Letter = ["--page-size", "Letter"]
toArgs (OtherPageSize s) = ["--page-size", s]
toArgs (CustomPageSize h w) = ("--page-height" : toArgs h) ++ ("--page-width" : toArgs w)
instance ToArgs Orientation where
toArgs o = ["--orientation", show o]
instance ToArgs UnitReal where
toArgs (Mm x) = [show x ++ "mm"]
toArgs (Cm x) = [show x ++ "cm"]
toArgs (OtherUnitReal s) = [s]
| alexkyllo/yesod-content-pdf | src/Yesod/Content/PDF.hs | bsd-3-clause | 6,881 | 0 | 17 | 1,835 | 1,544 | 865 | 679 | 155 | 1 |
{-# LANGUAGE TemplateHaskellQuotes #-}
{- Data/Singletons/TH/Promote/Defun.hs
(c) Richard Eisenberg, Jan Stolarek 2014
[email protected]
This file creates defunctionalization symbols for types during promotion.
-}
module Data.Singletons.TH.Promote.Defun where
import Language.Haskell.TH.Desugar
import Language.Haskell.TH.Syntax
import Data.Singletons.TH.Names
import Data.Singletons.TH.Options
import Data.Singletons.TH.Promote.Monad
import Data.Singletons.TH.Promote.Type
import Data.Singletons.TH.Syntax
import Data.Singletons.TH.Util
import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
import Data.Maybe
defunInfo :: DInfo -> PrM [DDec]
defunInfo (DTyConI dec _instances) = buildDefunSyms dec
defunInfo (DPrimTyConI _name _numArgs _unlifted) =
fail $ "Building defunctionalization symbols of primitive " ++
"type constructors not supported"
defunInfo (DVarI _name _ty _mdec) =
fail "Building defunctionalization symbols of values not supported"
defunInfo (DTyVarI _name _ty) =
fail "Building defunctionalization symbols of type variables not supported"
defunInfo (DPatSynI {}) =
fail "Building defunctionalization symbols of pattern synonyms not supported"
-- Defunctionalize type families defined at the top level (i.e., not associated
-- with a type class).
defunTopLevelTypeDecls ::
[TySynDecl]
-> [ClosedTypeFamilyDecl]
-> [OpenTypeFamilyDecl]
-> PrM ()
defunTopLevelTypeDecls ty_syns c_tyfams o_tyfams = do
defun_ty_syns <-
concatMapM (\(TySynDecl name tvbs rhs) -> buildDefunSymsTySynD name tvbs rhs) ty_syns
defun_c_tyfams <-
concatMapM (buildDefunSymsClosedTypeFamilyD . getTypeFamilyDecl) c_tyfams
defun_o_tyfams <-
concatMapM (buildDefunSymsOpenTypeFamilyD . getTypeFamilyDecl) o_tyfams
emitDecs $ defun_ty_syns ++ defun_c_tyfams ++ defun_o_tyfams
-- Defunctionalize all the type families associated with a type class.
defunAssociatedTypeFamilies ::
[DTyVarBndrUnit] -- The type variables bound by the parent class
-> [OpenTypeFamilyDecl] -- The type families associated with the parent class
-> PrM ()
defunAssociatedTypeFamilies cls_tvbs atfs = do
defun_atfs <- concatMapM defun atfs
emitDecs defun_atfs
where
defun :: OpenTypeFamilyDecl -> PrM [DDec]
defun (TypeFamilyDecl tf_head) =
buildDefunSymsTypeFamilyHead ascribe_tf_tvb_kind id tf_head
-- Maps class-bound type variables to their kind annotations (if supplied).
-- For example, `class C (a :: Bool) b (c :: Type)` will produce
-- {a |-> Bool, c |-> Type}.
cls_tvb_kind_map :: Map Name DKind
cls_tvb_kind_map = Map.fromList [ (extractTvbName tvb, tvb_kind)
| tvb <- cls_tvbs
, Just tvb_kind <- [extractTvbKind tvb]
]
-- If the parent class lacks a SAK, we cannot safely default kinds to
-- Type. All we can do is make use of whatever kind information that parent
-- class provides and let kind inference do the rest.
--
-- We can sometimes learn more specific information about unannotated type
-- family binders from the parent class, as in the following example:
--
-- class C (a :: Bool) where
-- type T a :: Type
--
-- Here, we know that `T :: Bool -> Type` because we can infer that the `a`
-- in `type T a` should be of kind `Bool` from the class SAK.
ascribe_tf_tvb_kind :: DTyVarBndrUnit -> DTyVarBndrUnit
ascribe_tf_tvb_kind tvb =
case tvb of
DKindedTV{} -> tvb
DPlainTV n _ -> maybe tvb (DKindedTV n ()) $ Map.lookup n cls_tvb_kind_map
buildDefunSyms :: DDec -> PrM [DDec]
buildDefunSyms dec =
case dec of
DDataD _new_or_data _cxt _tyName _tvbs _k ctors _derivings ->
buildDefunSymsDataD ctors
DClosedTypeFamilyD tf_head _ ->
buildDefunSymsClosedTypeFamilyD tf_head
DOpenTypeFamilyD tf_head ->
buildDefunSymsOpenTypeFamilyD tf_head
DTySynD name tvbs rhs ->
buildDefunSymsTySynD name tvbs rhs
DClassD _cxt name tvbs _fundeps _members ->
defunReify name tvbs (Just (DConT constraintName))
_ -> fail $ "Defunctionalization symbols can only be built for " ++
"type families and data declarations"
-- Unlike open type families, closed type families that lack SAKS do not
-- default anything to Type, instead relying on kind inference to figure out
-- unspecified kinds.
buildDefunSymsClosedTypeFamilyD :: DTypeFamilyHead -> PrM [DDec]
buildDefunSymsClosedTypeFamilyD = buildDefunSymsTypeFamilyHead id id
-- If an open type family lacks a SAK and has type variable binders or a result
-- without explicit kinds, then they default to Type (hence the uses of
-- default{Tvb,Maybe}ToTypeKind).
buildDefunSymsOpenTypeFamilyD :: DTypeFamilyHead -> PrM [DDec]
buildDefunSymsOpenTypeFamilyD =
buildDefunSymsTypeFamilyHead defaultTvbToTypeKind (Just . defaultMaybeToTypeKind)
buildDefunSymsTypeFamilyHead
:: (DTyVarBndrUnit -> DTyVarBndrUnit) -- How to default each type variable binder
-> (Maybe DKind -> Maybe DKind) -- How to default the result kind
-> DTypeFamilyHead -> PrM [DDec]
buildDefunSymsTypeFamilyHead default_tvb default_kind
(DTypeFamilyHead name tvbs result_sig _) = do
let arg_tvbs = map default_tvb tvbs
res_kind = default_kind (resultSigToMaybeKind result_sig)
defunReify name arg_tvbs res_kind
buildDefunSymsTySynD :: Name -> [DTyVarBndrUnit] -> DType -> PrM [DDec]
buildDefunSymsTySynD name tvbs rhs = defunReify name tvbs mb_res_kind
where
-- If a type synonym lacks a SAK, we can "infer" its result kind by
-- checking for an explicit kind annotation on the right-hand side.
mb_res_kind :: Maybe DKind
mb_res_kind = case rhs of
DSigT _ k -> Just k
_ -> Nothing
buildDefunSymsDataD :: [DCon] -> PrM [DDec]
buildDefunSymsDataD ctors =
concatMapM promoteCtor ctors
where
promoteCtor :: DCon -> PrM [DDec]
promoteCtor (DCon tvbs _ name fields res_ty) = do
opts <- getOptions
let name' = promotedDataTypeOrConName opts name
arg_tys = tysOfConFields fields
arg_kis <- traverse promoteType_NC arg_tys
res_ki <- promoteType_NC res_ty
let con_ki = ravelVanillaDType tvbs [] arg_kis res_ki
m_fixity <- reifyFixityWithLocals name'
defunctionalize name' m_fixity $ DefunSAK con_ki
-- Generate defunctionalization symbols for a name, using reifyFixityWithLocals
-- to determine what the fixity of each symbol should be
-- (see Note [Fixity declarations for defunctionalization symbols])
-- and dsReifyType to determine whether defunctionalization should make use
-- of SAKs or not (see Note [Defunctionalization game plan]).
defunReify :: Name -- Name of the declaration to be defunctionalized
-> [DTyVarBndrUnit] -- The declaration's type variable binders
-- (only used if the declaration lacks a SAK)
-> Maybe DKind -- The declaration's return kind, if it has one
-- (only used if the declaration lacks a SAK)
-> PrM [DDec]
defunReify name tvbs m_res_kind = do
m_fixity <- reifyFixityWithLocals name
m_sak <- dsReifyType name
let defun = defunctionalize name m_fixity
case m_sak of
Just sak -> defun $ DefunSAK sak
Nothing -> defun $ DefunNoSAK tvbs m_res_kind
-- Generate symbol data types, Apply instances, and other declarations required
-- for defunctionalization.
-- See Note [Defunctionalization game plan] for an overview of the design
-- considerations involved.
defunctionalize :: Name
-> Maybe Fixity
-> DefunKindInfo
-> PrM [DDec]
defunctionalize name m_fixity defun_ki = do
case defun_ki of
DefunSAK sak ->
-- Even if a declaration has a SAK, its kind may not be vanilla.
case unravelVanillaDType_either sak of
-- If the kind isn't vanilla, use the fallback approach.
-- See Note [Defunctionalization game plan],
-- Wrinkle 2: Non-vanilla kinds.
Left _ -> defun_fallback [] (Just sak)
-- Otherwise, proceed with defun_vanilla_sak.
Right (sak_tvbs, _sak_cxt, sak_arg_kis, sak_res_ki)
-> defun_vanilla_sak sak_tvbs sak_arg_kis sak_res_ki
-- If a declaration lacks a SAK, it likely has a partial kind.
-- See Note [Defunctionalization game plan], Wrinkle 1: Partial kinds.
DefunNoSAK tvbs m_res -> defun_fallback tvbs m_res
where
-- Generate defunctionalization symbols for things with vanilla SAKs.
-- The symbols themselves will also be given SAKs.
defun_vanilla_sak :: [DTyVarBndrSpec] -> [DKind] -> DKind -> PrM [DDec]
defun_vanilla_sak sak_tvbs sak_arg_kis sak_res_ki = do
opts <- getOptions
extra_name <- qNewName "arg"
let sak_arg_n = length sak_arg_kis
-- Use noExactName below to avoid GHC#17537.
arg_names <- replicateM sak_arg_n (noExactName <$> qNewName "a")
let -- The inner loop. @go n arg_nks res_nks@ returns @(res_k, decls)@.
-- Using one particular example:
--
-- @
-- type ExampleSym2 :: a -> b -> c ~> d ~> Type
-- data ExampleSym2 (x :: a) (y :: b) :: c ~> d ~> Type where ...
-- type instance Apply (ExampleSym2 x y) z = ExampleSym3 x y z
-- ...
-- @
--
-- We have:
--
-- * @n@ is 2. This is incremented in each iteration of `go`.
--
-- * @arg_nks@ is [(x, a), (y, b)]. Each element in this list is a
-- (type variable name, type variable kind) pair. The kinds appear in
-- the SAK, separated by matchable arrows (->).
--
-- * @res_tvbs@ is [(z, c), (w, d)]. Each element in this list is a
-- (type variable name, type variable kind) pair. The kinds appear in
-- @res_k@, separated by unmatchable arrows (~>).
--
-- * @res_k@ is `c ~> d ~> Type`. @res_k@ is returned so that earlier
-- defunctionalization symbols can build on the result kinds of
-- later symbols. For instance, ExampleSym1 would get the result
-- kind `b ~> c ~> d ~> Type` by prepending `b` to ExampleSym2's
-- result kind `c ~> d ~> Type`.
--
-- * @decls@ are all of the declarations corresponding to ExampleSym2
-- and later defunctionalization symbols. This is the main payload of
-- the function.
--
-- Note that the body of ExampleSym2 redundantly includes the
-- argument kinds and result kind, which are already stated in the
-- standalone kind signature. This is a deliberate choice.
-- See Note [Keep redundant kind information for Haddocks]
-- in D.S.TH.Promote.
--
-- This function is quadratic because it appends a variable at the end of
-- the @arg_nks@ list at each iteration. In practice, this is unlikely
-- to be a performance bottleneck since the number of arguments rarely
-- gets to be that large.
go :: Int -> [(Name, DKind)] -> [(Name, DKind)] -> (DKind, [DDec])
go n arg_nks res_nkss =
let arg_tvbs :: [DTyVarBndrUnit]
arg_tvbs = map (\(na, ki) -> DKindedTV na () ki) arg_nks
mk_sak_dec :: DKind -> DDec
mk_sak_dec res_ki =
DKiSigD (defunctionalizedName opts name n) $
ravelVanillaDType sak_tvbs [] (map snd arg_nks) res_ki in
case res_nkss of
[] ->
let sat_sak_dec = mk_sak_dec sak_res_ki
sat_decs = mk_sat_decs opts n arg_tvbs (Just sak_res_ki)
in (sak_res_ki, sat_sak_dec:sat_decs)
res_nk:res_nks ->
let (res_ki, decs) = go (n+1) (arg_nks ++ [res_nk]) res_nks
tyfun = buildTyFunArrow (snd res_nk) res_ki
defun_sak_dec = mk_sak_dec tyfun
defun_other_decs = mk_defun_decs opts n sak_arg_n
arg_tvbs (fst res_nk)
extra_name (Just tyfun)
in (tyfun, defun_sak_dec:defun_other_decs ++ decs)
pure $ snd $ go 0 [] $ zip arg_names sak_arg_kis
-- If defun_sak can't be used to defunctionalize something, this fallback
-- approach is used. This is used when defunctionalizing something with a
-- partial kind
-- (see Note [Defunctionalization game plan], Wrinkle 1: Partial kinds)
-- or a non-vanilla kind
-- (see Note [Defunctionalization game plan], Wrinkle 2: Non-vanilla kinds).
defun_fallback :: [DTyVarBndrUnit] -> Maybe DKind -> PrM [DDec]
defun_fallback tvbs' m_res' = do
opts <- getOptions
extra_name <- qNewName "arg"
-- Use noExactTyVars below to avoid GHC#11812.
(tvbs, m_res) <- eta_expand (noExactTyVars tvbs') (noExactTyVars m_res')
let tvbs_n = length tvbs
-- The inner loop. @go n arg_tvbs res_tvbs@ returns @(m_res_k, decls)@.
-- Using one particular example:
--
-- @
-- data ExampleSym2 (x :: a) y :: c ~> d ~> Type where ...
-- type instance Apply (ExampleSym2 x y) z = ExampleSym3 x y z
-- ...
-- @
--
-- This works very similarly to the `go` function in
-- `defun_vanilla_sak`. The main differences are:
--
-- * This function does not produce any SAKs for defunctionalization
-- symbols.
--
-- * Instead of [(Name, DKind)], this function uses [DTyVarBndr] as
-- the types of @arg_tvbs@ and @res_tvbs@. This is because the
-- kinds are not always known. By a similar token, this function
-- uses Maybe DKind, not DKind, as the type of @m_res_k@, since
-- the result kind is not always fully known.
go :: Int -> [DTyVarBndrUnit] -> [DTyVarBndrUnit] -> (Maybe DKind, [DDec])
go n arg_tvbs res_tvbss =
case res_tvbss of
[] ->
let sat_decs = mk_sat_decs opts n arg_tvbs m_res
in (m_res, sat_decs)
res_tvb:res_tvbs ->
let (m_res_ki, decs) = go (n+1) (arg_tvbs ++ [res_tvb]) res_tvbs
m_tyfun = buildTyFunArrow_maybe (extractTvbKind res_tvb)
m_res_ki
defun_decs' = mk_defun_decs opts n tvbs_n arg_tvbs
(extractTvbName res_tvb)
extra_name m_tyfun
in (m_tyfun, defun_decs' ++ decs)
pure $ snd $ go 0 [] tvbs
mk_defun_decs :: Options
-> Int
-> Int
-> [DTyVarBndrUnit]
-> Name
-> Name
-> Maybe DKind
-> [DDec]
mk_defun_decs opts n fully_sat_n arg_tvbs tyfun_name extra_name m_tyfun =
let data_name = defunctionalizedName opts name n
next_name = defunctionalizedName opts name (n+1)
con_name = prefixName "" ":" $ suffixName "KindInference" "###" data_name
arg_names = map extractTvbName arg_tvbs
params = arg_tvbs ++ [DPlainTV tyfun_name ()]
con_eq_ct = DConT sameKindName `DAppT` lhs `DAppT` rhs
where
lhs = foldType (DConT data_name) (map DVarT arg_names) `apply` (DVarT extra_name)
rhs = foldType (DConT next_name) (map DVarT (arg_names ++ [extra_name]))
con_decl = DCon [] [con_eq_ct] con_name (DNormalC False [])
(foldTypeTvbs (DConT data_name) params)
data_decl = DDataD Data [] data_name args m_tyfun [con_decl] []
where
args | isJust m_tyfun = arg_tvbs
| otherwise = params
app_data_ty = foldTypeTvbs (DConT data_name) arg_tvbs
app_eqn = DTySynEqn Nothing
(DConT applyName `DAppT` app_data_ty
`DAppT` DVarT tyfun_name)
(foldTypeTvbs (DConT app_eqn_rhs_name)
(arg_tvbs ++ [DPlainTV tyfun_name ()]))
-- If the next defunctionalization symbol is fully saturated, then
-- use the original declaration name instead.
-- See Note [Fully saturated defunctionalization symbols]
-- (Wrinkle: avoiding reduction stack overflows).
app_eqn_rhs_name | n+1 == fully_sat_n = name
| otherwise = next_name
app_decl = DTySynInstD app_eqn
suppress = DInstanceD Nothing Nothing []
(DConT suppressClassName `DAppT` app_data_ty)
[DLetDec $ DFunD suppressMethodName
[DClause []
((DVarE 'snd) `DAppE`
mkTupleDExp [DConE con_name,
mkTupleDExp []])]]
-- See Note [Fixity declarations for defunctionalization symbols]
fixity_decl = maybeToList $ fmap (mk_fix_decl data_name) m_fixity
in data_decl : app_decl : suppress : fixity_decl
-- Generate a "fully saturated" defunction symbol, along with a fixity
-- declaration (if needed).
-- See Note [Fully saturated defunctionalization symbols].
mk_sat_decs :: Options -> Int -> [DTyVarBndrUnit] -> Maybe DKind -> [DDec]
mk_sat_decs opts n sat_tvbs m_sat_res =
let sat_name = defunctionalizedName opts name n
sat_dec = DClosedTypeFamilyD
(DTypeFamilyHead sat_name sat_tvbs
(maybeKindToResultSig m_sat_res) Nothing)
[DTySynEqn Nothing
(foldTypeTvbs (DConT sat_name) sat_tvbs)
(foldTypeTvbs (DConT name) sat_tvbs)]
sat_fixity_dec = maybeToList $ fmap (mk_fix_decl sat_name) m_fixity
in sat_dec : sat_fixity_dec
-- Generate extra kind variable binders corresponding to the number of
-- arrows in the return kind (if provided). Examples:
--
-- >>> eta_expand [(x :: a), (y :: b)] (Just (c -> Type))
-- ([(x :: a), (y :: b), (e :: c)], Just Type)
--
-- >>> eta_expand [(x :: a), (y :: b)] Nothing
-- ([(x :: a), (y :: b)], Nothing)
eta_expand :: [DTyVarBndrUnit] -> Maybe DKind -> PrM ([DTyVarBndrUnit], Maybe DKind)
eta_expand m_arg_tvbs Nothing = pure (m_arg_tvbs, Nothing)
eta_expand m_arg_tvbs (Just res_kind) = do
let (arg_ks, result_k) = unravelDType res_kind
vis_arg_ks = filterDVisFunArgs arg_ks
extra_arg_tvbs <- traverse mk_extra_tvb vis_arg_ks
pure (m_arg_tvbs ++ extra_arg_tvbs, Just result_k)
-- Convert a DVisFunArg to a DTyVarBndr, generating a fresh type variable
-- name if the DVisFunArg is an anonymous argument.
mk_extra_tvb :: DVisFunArg -> PrM DTyVarBndrUnit
mk_extra_tvb vfa =
case vfa of
DVisFADep tvb -> pure tvb
DVisFAAnon k -> (\n -> DKindedTV n () k) <$>
-- Use noExactName below to avoid GHC#19743.
(noExactName <$> qNewName "e")
mk_fix_decl :: Name -> Fixity -> DDec
mk_fix_decl n f = DLetDec $ DInfixD f n
-- Indicates whether the type being defunctionalized has a standalone kind
-- signature. If it does, DefunSAK contains the kind. If not, DefunNoSAK
-- contains whatever information is known about its type variable binders
-- and result kind.
-- See Note [Defunctionalization game plan] for details on how this
-- information is used.
data DefunKindInfo
= DefunSAK DKind
| DefunNoSAK [DTyVarBndrUnit] (Maybe DKind)
-- Shorthand for building (k1 ~> k2)
buildTyFunArrow :: DKind -> DKind -> DKind
buildTyFunArrow k1 k2 = DConT tyFunArrowName `DAppT` k1 `DAppT` k2
buildTyFunArrow_maybe :: Maybe DKind -> Maybe DKind -> Maybe DKind
buildTyFunArrow_maybe m_k1 m_k2 = buildTyFunArrow <$> m_k1 <*> m_k2
{-
Note [Defunctionalization game plan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generating defunctionalization symbols involves a surprising amount of
complexity. This Note gives a broad overview of what happens during
defunctionalization and highlights various design considerations.
As a working example, we will use the following type family:
type Foo :: forall c a b. a -> b -> c -> c
type family Foo x y z where ...
We must generate a defunctionalization symbol for every number of arguments
to which Foo can be partially applied. We do so by generating the following
declarations:
type FooSym0 :: forall c a b. a ~> b ~> c ~> c
data FooSym0 f where
FooSym0KindInference :: SameKind (Apply FooSym0 arg) (FooSym1 arg)
=> FooSym0 f
type instance Apply FooSym0 x = FooSym1 x
type FooSym1 :: forall c a b. a -> b ~> c ~> c
data FooSym1 x f where
FooSym1KindInference :: SameKind (Apply (FooSym1 a) arg) (FooSym2 a arg)
=> FooSym1 a f
type instance Apply (FooSym1 x) y = FooSym2 x y
type FooSym2 :: forall c a b. a -> b -> c ~> c
data FooSym2 x y f where
FooSym2KindInference :: SameKind (Apply (FooSym2 x y) arg) (FooSym3 x y arg)
=> FooSym2 x y f
type instance Apply (FooSym2 x y) z = Foo x y z
type FooSym3 :: forall c a b. a -> b -> c -> c
type family FooSym3 x y z where
FooSym3 x y z = Foo x y z
Some things to note:
* Each defunctionalization symbol has its own standalone kind signature. The
number after `Sym` in each symbol indicates the number of leading -> arrows
in its kind—that is, the number of arguments to which it can be applied
directly to without the use of the Apply type family.
See "Wrinkle 1: Partial kinds" below for what happens if the declaration
being defunctionalized does *not* have a standalone kind signature.
* Each data declaration has a constructor with the suffix `-KindInference`
in its name. These are redundant in the particular case of Foo, where the
kind is already known. They play a more vital role when the kind of the
declaration being defunctionalized is only partially known.
See "Wrinkle 1: Partial kinds" below for more information.
* FooSym3, the last defunctionalization symbol, is somewhat special in that
it is a type family, not a data type. These sorts of symbols are referred
to as "fully saturated" defunctionalization symbols.
See Note [Fully saturated defunctionalization symbols].
* If Foo had a fixity declaration (e.g., infixl 4 `Foo`), then we would also
generate fixity declarations for each defunctionalization symbol (e.g.,
infixl 4 `FooSym0`).
See Note [Fixity declarations for defunctionalization symbols].
* Foo has a vanilla kind signature. (See
Note [Vanilla-type validity checking during promotion] in D.S.TH.Promote.Type
for what "vanilla" means in this context.) Having a vanilla type signature is
important, as it is a property that makes it much simpler to preserve the
order of type variables (`forall c a b.`) in each of the defunctionalization
symbols.
That being said, it is not strictly required that the kind be vanilla. There
is another approach that can be used to defunctionalize things with
non-vanilla types, at the possible expense of having different type variable
orders between different defunctionalization symbols.
See "Wrinkle 2: Non-vanilla kinds" below for more information.
-----
-- Wrinkle 1: Partial kinds
-----
The Foo example above has a standalone kind signature, but not everything has
this much kind information. For example, consider this:
$(singletons [d|
type family Not x where
Not False = True
Not True = False
|])
The inferred kind for Not is `Bool -> Bool`, but since Not was declared in TH
quotes, `singletons-th` has no knowledge of this. Instead, we must rely on kind
inference to give Not's defunctionalization symbols the appropriate kinds.
Here is a naïve first attempt:
data NotSym0 f
type instance Apply NotSym0 x = Not x
type family NotSym1 x where
NotSym1 x = Not x
NotSym1 will have the inferred kind `Bool -> Bool`, but poor NotSym0 will have
the inferred kind `forall k. k -> Type`, which is far more general than we
would like. We can do slightly better by supplying additional kind information
in a data constructor, like so:
type SameKind :: k -> k -> Constraint
class SameKind x y = ()
data NotSym0 f where
NotSym0KindInference :: SameKind (Apply NotSym0 arg) (NotSym1 arg)
=> NotSym0 f
NotSym0KindInference is not intended to ever be seen by the user. Its only
reason for existing is its existential
`SameKind (Apply NotSym0 arg) (NotSym1 arg)` context, which allows GHC to
figure out that NotSym0 has kind `Bool ~> Bool`. This is a bit of a hack, but
it works quite nicely. The only problem is that GHC is likely to warn that
NotSym0KindInference is unused, which is annoying. To work around this, we
mention the data constructor in an instance of a dummy class:
instance SuppressUnusedWarnings NotSym0 where
suppressUnusedWarnings = snd (NotSym0KindInference, ())
Similarly, this SuppressUnusedWarnings class is not intended to ever be seen
by the user. As its name suggests, it only exists to help suppress "unused
data constructor" warnings.
Some declarations have a mixture of known kinds and unknown kinds, such as in
this example:
$(singletons [d|
type family Bar x (y :: Nat) (z :: Nat) :: Nat where ...
|])
We can use the known kinds to guide kind inference. In this particular example
of Bar, here are the defunctionalization symbols that would be generated:
data BarSym0 f where ...
data BarSym1 x :: Nat ~> Nat ~> Nat where ...
data BarSym2 x (y :: Nat) :: Nat ~> Nat where ...
type family BarSym3 x (y :: Nat) (z :: Nat) :: Nat where ...
-----
-- Wrinkle 2: Non-vanilla kinds
-----
There is only limited support for defunctionalizing declarations with
non-vanilla kinds. One example of something with a non-vanilla kind is the
following, which uses a nested forall:
$(singletons [d|
type Baz :: forall a. a -> forall b. b -> Type
data Baz x y
|])
One might envision generating the following defunctionalization symbols for
Baz:
type BazSym0 :: forall a. a ~> forall b. b ~> Type
data BazSym0 f where ...
type BazSym1 :: forall a. a -> forall b. b ~> Type
data BazSym1 x f where ...
type BazSym2 :: forall a. a -> forall b. b -> Type
type family BazSym2 x y where
BazSym2 x y = Baz x y
Unfortunately, doing so would require impredicativity, since we would have:
forall a. a ~> forall b. b ~> Type
= forall a. (~>) a (forall b. b ~> Type)
= forall a. TyFun a (forall b. b ~> Type) -> Type
Note that TyFun is an ordinary data type, so having its second argument be
(forall b. b ~> Type) is truly impredicative. As a result, trying to preserve
nested or higher-rank foralls is a non-starter.
We need not reject Baz entirely, however. We can still generate perfectly
usable defunctionalization symbols if we are willing to sacrifice the exact
order of foralls. When we encounter a non-vanilla kind such as Baz's, we simply
fall back to the algorithm used when we encounter a partial kind (as described
in "Wrinkle 1: Partial kinds" above.) In other words, we generate the
following symbols:
data BazSym0 :: a ~> b ~> Type where ...
data BazSym1 (x :: a) :: b ~> Type where ...
type family BazSym2 (x :: a) (y :: b) :: Type where ...
The kinds of BazSym0 and BazSym1 both start with `forall a b.`,
whereas the `b` is quantified later in Baz itself. For most use cases, however,
this is not a huge concern.
Another way kinds can be non-vanilla is if they contain visible dependent
quantification, like so:
$(singletons [d|
type Quux :: forall (k :: Type) -> k -> Type
data Quux x y
|])
What should the kind of QuuxSym0 be? Intuitively, it should be this:
type QuuxSym0 :: forall (k :: Type) ~> k ~> Type
Alas, `forall (k :: Type) ~>` simply doesn't work. See #304. But there is an
acceptable compromise we can make that can give us defunctionalization symbols
for Quux. Once again, we fall back to the partial kind algorithm:
data QuuxSym0 :: Type ~> k ~> Type where ...
data QuuxSym1 (k :: Type) :: k ~> Type where ...
type family QuuxSym2 (k :: Type) (x :: k) :: Type where ...
The catch is that the kind of QuuxSym0, `forall k. Type ~> k ~> Type`, is
slightly more general than it ought to be. In practice, however, this is
unlikely to be a problem as long as you apply QuuxSym0 to arguments of the
right kinds.
Note [Fully saturated defunctionalization symbols]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When generating defunctionalization symbols, most of the symbols are data
types. The last one, however, is a type family. For example, this code:
$(singletons [d|
type Const :: a -> b -> a
type Const x y = x
|])
Will generate the following symbols:
type ConstSym0 :: a ~> b ~> a
data ConstSym0 f where ...
type ConstSym1 :: a -> b ~> a
data ConstSym1 x f where ...
type ConstSym2 :: a -> b -> a
type family ConstSym2 x y where
ConstSym2 x y = Const x y
ConstSym2, the sole type family of the bunch, is what is referred to as a
"fully saturated" defunctionaliztion symbol.
At first glance, ConstSym2 may not seem terribly useful, since it is
effectively a thin wrapper around the original Const type. Indeed, fully
saturated symbols almost never appear directly in user-written code. Instead,
they are most valuable in TH-generated code, as singletons-th often generates code
that directly applies a defunctionalization symbol to some number of arguments
(see, for instance, D.S.TH.Names.promoteTySym). In theory, such code could carve
out a special case for fully saturated applications and apply the original
type instead of a defunctionalization symbol, but determining when an
application is fully saturated is often difficult in practice. As a result, it
is more convenient to just generate code that always applies FuncSymN to N
arguments, and to let fully saturated defunctionalization symbols handle the
case where N equals the number of arguments needed to fully saturate Func.
One might wonder if, instead of using a closed type family with a single
equation, we could use a type synonym to define ConstSym2:
type ConstSym2 :: a -> b -> a
type ConstSym2 x y = Const x y
This approach has various downsides which make it impractical:
* Type synonyms are often not expanded in the output of GHCi's :kind! command.
As issue #445 chronicles, this can significantly impact the readability of
even simple :kind! queries. It can be the difference between this:
λ> :kind! Map IdSym0 '[1,2,3]
Map IdSym0 '[1,2,3] :: [Nat]
= 1 :@#@$$$ '[2, 3]
And this:
λ> :kind! Map IdSym0 '[1,2,3]
Map IdSym0 '[1,2,3] :: [Nat]
= '[1, 2, 3]
Making fully saturated defunctionalization symbols like (:@#@$$$) type
families makes this issue moot, since :kind! always expands type families.
* There are a handful of corner cases where using type synonyms can actually
make fully saturated defunctionalization symbols fail to typecheck.
Here is one such corner case:
$(promote [d|
class Applicative f where
pure :: a -> f a
...
(*>) :: f a -> f b -> f b
|])
==>
class PApplicative f where
type Pure (x :: a) :: f a
type (*>) (x :: f a) (y :: f b) :: f b
What would happen if we were to defunctionalize the promoted version of (*>)?
We'd end up with the following defunctionalization symbols:
type (*>@#@$) :: f a ~> f b ~> f b
data (*>@#@$) f where ...
type (*>@#@$$) :: f a -> f b ~> f b
data (*>@#@$$) x f where ...
type (*>@#@$$$) :: f a -> f b -> f b
type (*>@#@$$$) x y = (*>) x y
It turns out, however, that (*>@#@$$$) will not kind-check. Because (*>@#@$$$)
has a standalone kind signature, it is kind-generalized *before* kind-checking
the actual definition itself. Therefore, the full kind is:
type (*>@#@$$$) :: forall {k} (f :: k -> Type) (a :: k) (b :: k).
f a -> f b -> f b
type (*>@#@$$$) x y = (*>) x y
However, the kind of (*>) is
`forall (f :: Type -> Type) (a :: Type) (b :: Type). f a -> f b -> f b`.
This is not general enough for (*>@#@$$$), which expects kind-polymorphic `f`,
`a`, and `b`, leading to a kind error. You might think that we could somehow
infer this information, but note the quoted definition of Applicative (and
PApplicative, as a consequence) omits the kinds of `f`, `a`, and `b` entirely.
Unless we were to implement full-blown kind inference inside of Template
Haskell (which is a tall order), the kind `f a -> f b -> f b` is about as good
as we can get.
Making (*>@#@$$$) a type family rather than a type synonym avoids this issue
since type family equations are allowed to match on kind arguments. In this
example, (*>@#@$$$) would have kind-polymorphic `f`, `a`, and `b` in its kind
signature, but its equation would implicitly equate `k` with `Type`. Note
that (*>@#@$) and (*>@#@$$), which are GADTs, also use a similar trick by
equating `k` with `Type` in their GADT constructors.
-----
-- Wrinkle: avoiding reduction stack overflows
-----
A naïve attempt at declaring all fully saturated defunctionalization symbols
as type families can make certain programs overflow the reduction stack, such
as the T445 test case. This is because when evaluating
`FSym0 `Apply` x_1 `Apply` ... `Apply` x_N`, (where F is a promoted function
that requires N arguments), we will eventually bottom out by evaluating
`FSymN x_1 ... x_N`, where FSymN is a fully saturated defunctionalization
symbol. Since FSymN is a type family, this is yet another type family
reduction that contributes to the overall reduction limit. This might not
seem like a lot, but it can add up if F is invoked several times in a single
type-level computation!
Fortunately, we can bypass evaluating FSymN entirely by just making a slight
tweak to the TH machinery. Instead of generating this Apply instance:
type instance Apply (FSym{N-1} x_1 ... x_{N-1}) x_N =
FSymN x_1 ... x_{N-1} x_N
Generate this instance, which jumps straight to F:
type instance Apply (FSym{N-1} x_1 ... x_{N-1}) x_N =
F x_1 ... x_{N-1} x_N
Now evaluating `FSym0 `Apply` x_1 `Apply` ... `Apply` x_N` will require one
less type family reduction. In practice, this is usually enough to keep the
reduction limit at bay in most situations.
Note [Fixity declarations for defunctionalization symbols]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Just like we promote fixity declarations, we should also generate fixity
declarations for defunctionaliztion symbols. A primary use case is the
following scenario:
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(f . g) x = f (g x)
infixr 9 .
One often writes (f . g . h) at the value level, but because (.) is promoted
to a type family with three arguments, this doesn't directly translate to the
type level. Instead, one must write this:
f .@#@$$$ g .@#@$$$ h
But in order to ensure that this associates to the right as expected, one must
generate an `infixr 9 .@#@#$$$` declaration. This is why defunctionalize accepts
a Maybe Fixity argument.
-}
| goldfirere/singletons | singletons-th/src/Data/Singletons/TH/Promote/Defun.hs | bsd-3-clause | 35,976 | 0 | 24 | 9,464 | 3,337 | 1,758 | 1,579 | -1 | -1 |
module Network.Anarchy.Server (ServerState(..), runServer, block) where
import Control.Concurrent
import Control.Concurrent.Async
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Maybe
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.Hashable
import Data.Set
import Data.List (nub, sortBy)
import Happstack.Lite
import Happstack.Server (Request(..), askRq)
import Happstack.Server.Types
import System.Timeout
import Text.JSON
import Network.Anarchy
import Network.Anarchy.Server.Internal
import qualified Network.Anarchy.Client as Client
data ServerState = ServerState {
clients :: [ HostPort ],
hostport :: Maybe HostPort,
digests :: Set Int
} deriving (Eq, Show)
type Handle = (MVar ServerState, Async ())
instance JSON ServerState where
showJSON s = let cs = ("clients", showJSON (clients s))
hp = ("hostport", showJSON (hostport s))
d = ("digests", showJSON (digests s))
in makeObj [ cs, hp, d]
readJSON x = do
jsObject <- extractJSObject x
cs <- valFromObj "clients" jsObject
hp <- valFromObj "hostport" jsObject
d <- valFromObj "digests" jsObject
return (ServerState cs hp d)
instance ToMessage ServerState where
toMessage s = LB.pack . encode . showJSON $ s
toContentType _ = B.pack "text/json"
myApp :: MVar ServerState -> ServerPart Response
myApp x = msum [
dir "status" . status $ x,
dir "register" . register $ x,
dir "addclients" . addClients $ x,
dir "hostcheck" . hostCheck $ x
]
addClients :: MVar ServerState -> ServerPart Response
addClients x = do
method PUT -- only handle PUT requests
body <- getBody
let msg = decode body :: Result ([HostPort])
case (msg) of
Ok (hps) -> do
let f = addHostPorts hps
liftIO $ modifyMVar_ x (\s -> return $ execState f s)
return . toResponse $ "Ok"
Error str -> do
return . toResponse $ str
hostCheck :: MVar ServerState -> ServerPart Response
hostCheck _ = do
method GET
Request { rqPeer = (host,_) } <- askRq
return . toResponse $ host
getBody :: ServerPart String
getBody = do
req <- askRq
body <- liftIO $ takeRequestBody req
case body of
Just r -> return . LB.unpack . unBody $ r
Nothing -> return "Nothing"
register :: MVar ServerState -> ServerPart Response
register x = do
method PUT -- only handle PUT requests
body <- getBody
let msg = decode body :: Result (UniqueMessage HostPort)
case (msg) of
Ok (umhp) -> do
s <- liftIO $ readMVar x
let f = registerHostPort umhp
let flip (a,b) = (b,a)
wasAdded <- liftIO $ modifyMVar x (\s' -> return . flip . runState f $ s')
case wasAdded of
True -> liftIO $ do
let cs = clients s -- Clients from before modifyMVar
let clientOp = Client.register_ umhp
let updateClient hp = Client.run (Client.Options hp) clientOp >> return ()
sequence_ . Prelude.map (\hp -> forkIO (updateClient hp)) $ cs
let Just myHp = hostport s
let UniqueMessage hp _ _ = umhp
forkIO (Client.run (Client.Options hp) (Client.addClients_ (myHp:cs)) >> return ())
return ()
False -> return () -- don't do anything.
return . toResponse $ "Ok"
Error str -> do
return . toResponse $ ""
hasMessage :: Hashable a => UniqueMessage a -> ServerState -> Bool
hasMessage um s =
let h = hash um
in member h $ digests s
insertMessageDigest :: Hashable a => UniqueMessage a -> State ServerState ()
insertMessageDigest um = do
s <- get
put $ s { digests = insert (hash um) (digests s) }
filterClients :: HostPort -> [ HostPort ] -> [ HostPort ]
filterClients myHp hps =
let hps' = nub . Prelude.filter (\s -> myHp /= s) $ hps
hps'' = sortBy (\ a b -> compare (distance myHp a) (distance myHp b)) hps'
in take 3 hps''
addHostPorts :: [ HostPort ] -> State ServerState ()
addHostPorts hps = do
sequence . Prelude.map f $ hps
return ()
where f hp = do
s <- get
let Just myHp = hostport s
put $ s { clients = filterClients myHp (hp : (clients s)) }
registerHostPort :: UniqueMessage HostPort -> State ServerState Bool
registerHostPort umhp = do
s <- get
case (hasMessage umhp s) of
True -> return False
False -> do
insertMessageDigest umhp
let UniqueMessage hp _ _ = umhp
addHostPorts [ hp ]
return True
status :: MVar ServerState -> ServerPart Response
status x = do
method GET -- only handle GET requests
val <- liftIO . readMVar $ x
return . toResponse $ val
updateHostPort :: HostPort -> Int -> MVar ServerState -> MaybeT IO ()
updateHostPort hp p s = do
h <- MaybeT $ Client.run (Client.Options hp) Client.hostCheck_
liftIO $ modifyMVar_ s (\x -> return ( x { hostport = Just (HostPort h p) } ) )
runServer :: ServerConfig -> HostPort -> IO Handle
runServer config hp = do
let p = Happstack.Lite.port config
x <- newMVar (ServerState [] Nothing empty)
id <- async $ serve (return config) $ myApp x
runMaybeT $ updateHostPort hp p x
s <- readMVar x
let Just myhp = hostport s
msg <- mkMessage myhp myhp
let clientOp = Client.register_ msg
Client.run (Client.Options hp) clientOp
return (x, id)
block :: Handle -> IO ()
block (_, id) = wait id
| davidhinkes/anarchy | src/Network/Anarchy/Server.hs | bsd-3-clause | 5,439 | 0 | 25 | 1,359 | 2,069 | 1,015 | 1,054 | 149 | 3 |
import Test.QuickCheck
myLast :: [a] -> a
myLast (x:[]) = x
myLast (x:xs) = myLast xs
prop_oneElem :: [Int] -> Int -> Bool
prop_oneElem _ x = myLast (x:[]) == x
prop_manyElems :: [Int] -> Int -> Bool
prop_manyElems xs y = myLast (xs ++ [y]) == y
main = do
quickCheck prop_oneElem
quickCheck prop_manyElems
| SandeepTuniki/99-Haskell-Problems | src/problem1.hs | bsd-3-clause | 319 | 0 | 9 | 68 | 155 | 80 | 75 | 11 | 1 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
-- |
-- Module : Data.ByteString.Base64.URL.Lazy
-- Copyright : (c) 2012 Ian Lynagh
--
-- License : BSD-style
-- Maintainer : Emily Pillmore <[email protected]>,
-- Herbert Valerio Riedel <[email protected]>,
-- Mikhail Glushenkov <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- Fast and efficient encoding and decoding of base64-encoded
-- lazy bytestrings.
--
-- @since 1.0.0.0
module Data.ByteString.Base64.URL.Lazy
(
encode
, encodeUnpadded
, decode
, decodeUnpadded
, decodePadded
, decodeLenient
) where
import Data.ByteString.Base64.Internal
import qualified Data.ByteString.Base64.URL as B64
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as LC
import Data.Char
-- | Encode a string into base64 form. The result will always be a
-- multiple of 4 bytes in length.
encode :: L.ByteString -> L.ByteString
encode = L.fromChunks . map B64.encode . reChunkIn 3 . L.toChunks
-- | Encode a string into unpadded base64url form.
--
-- @since 1.1.0.0
encodeUnpadded :: L.ByteString -> L.ByteString
encodeUnpadded = L.fromChunks
. map B64.encodeUnpadded
. reChunkIn 3
. L.toChunks
-- | Decode a base64-encoded string. This function strictly follows
-- the specification in
-- <http://tools.ietf.org/rfc/rfc4648 RFC 4648>.
decode :: L.ByteString -> Either String L.ByteString
decode b = -- Returning an Either type means that the entire result will
-- need to be in memory at once anyway, so we may as well
-- keep it simple and just convert to and from a strict byte
-- string
-- TODO: Use L.{fromStrict,toStrict} once we can rely on
-- a new enough bytestring
case B64.decode $ S.concat $ L.toChunks b of
Left err -> Left err
Right b' -> Right $ L.fromChunks [b']
-- | Decode a unpadded base64url-encoded string, failing if input is padded.
-- This function follows the specification in <http://tools.ietf.org/rfc/rfc4648 RFC 4648>
-- and in <https://tools.ietf.org/html/rfc7049#section-2.4.4.2 RFC 7049 2.4>
--
-- @since 1.1.0.0
decodeUnpadded :: L.ByteString -> Either String L.ByteString
decodeUnpadded bs = case B64.decodeUnpadded $ S.concat $ L.toChunks bs of
Right b -> Right $ L.fromChunks [b]
Left e -> Left e
-- | Decode a padded base64url-encoded string, failing if input is improperly padded.
-- This function follows the specification in <http://tools.ietf.org/rfc/rfc4648 RFC 4648>
-- and in <https://tools.ietf.org/html/rfc7049#section-2.4.4.2 RFC 7049 2.4>
--
-- @since 1.1.0.0
decodePadded :: L.ByteString -> Either String L.ByteString
decodePadded bs = case B64.decodePadded $ S.concat $ L.toChunks bs of
Right b -> Right $ L.fromChunks [b]
Left e -> Left e
-- | Decode a base64-encoded string. This function is lenient in
-- following the specification from
-- <http://tools.ietf.org/rfc/rfc4648 RFC 4648>, and will not generate
-- parse errors no matter how poor its input.
decodeLenient :: L.ByteString -> L.ByteString
decodeLenient = L.fromChunks . map B64.decodeLenient . reChunkIn 4 . L.toChunks
. LC.filter goodChar
where -- We filter out and '=' padding here, but B64.decodeLenient
-- handles that
goodChar c = isAlphaNum c || c == '-' || c == '_'
| bos/base64-bytestring | Data/ByteString/Base64/URL/Lazy.hs | bsd-3-clause | 3,520 | 0 | 11 | 735 | 531 | 301 | 230 | 39 | 2 |
{-# LANGUAGE PackageImports #-}
module Data.Type.Equality (module M) where
import "base" Data.Type.Equality as M
| silkapp/base-noprelude | src/Data/Type/Equality.hs | bsd-3-clause | 118 | 0 | 4 | 18 | 23 | 17 | 6 | 3 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module QC.RGB (tests) where
import Control.Monad (liftM3)
import Data.Convertible
import Data.Prizm.Color
import Data.Prizm.Color.CIE as CIE
import Test.Framework (Test)
import Test.Framework.Providers.QuickCheck2 as QuickCheck
import Test.QuickCheck
instance Arbitrary RGB where
arbitrary = liftM3 mkRGB (choose rgbRange) (choose rgbRange) (choose rgbRange)
where
rgbRange = (0, 255)
rgb2XYZ :: RGB -> Bool
rgb2XYZ gVal = gVal == iso
where
iso = convert ((convert gVal) :: CIE.XYZ)
rgb2HEX :: RGB -> Bool
rgb2HEX gVal = gVal == iso
where
iso = convert ((convert gVal) :: HexRGB)
tests :: [Test]
tests =
[ QuickCheck.testProperty "RGB <-> CIE XYZ" rgb2XYZ
, QuickCheck.testProperty "HexRGB <-> RGB " rgb2HEX
]
| ixmatus/prizm | tests/QC/RGB.hs | bsd-3-clause | 956 | 0 | 10 | 282 | 241 | 138 | 103 | 23 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns, CPP #-}
{-# LANGUAGE NamedFieldPuns #-}
module Network.Wai.Handler.Warp.HTTP2.Sender (frameSender) where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative
#endif
import Control.Concurrent.MVar (putMVar)
import Control.Concurrent.STM
import qualified Control.Exception as E
import Control.Monad (void, when)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as B (int32BE)
import qualified Data.ByteString.Builder.Extra as B
import Data.Monoid ((<>))
import Foreign.Ptr
import qualified Network.HTTP.Types as H
import Network.HPACK (setLimitForEncoding)
import Network.HTTP2
import Network.HTTP2.Priority
import Network.Wai (FilePart(..))
import Network.Wai.HTTP2 (Trailers, promiseHeaders)
import Network.Wai.Handler.Warp.Buffer
import Network.Wai.Handler.Warp.HTTP2.EncodeFrame
import Network.Wai.Handler.Warp.HTTP2.HPACK
import Network.Wai.Handler.Warp.HTTP2.Types
import Network.Wai.Handler.Warp.IORef
import qualified Network.Wai.Handler.Warp.Settings as S
import Network.Wai.Handler.Warp.Types
#ifdef WINDOWS
import qualified System.IO as IO
#else
import Network.Wai.Handler.Warp.FdCache (getFd)
import Network.Wai.Handler.Warp.SendFile (positionRead)
import qualified Network.Wai.Handler.Warp.Timeout as T
import System.Posix.IO (openFd, OpenFileFlags(..), defaultFileFlags, OpenMode(ReadOnly), closeFd)
import System.Posix.Types (Fd)
#endif
----------------------------------------------------------------
-- | The platform-specific type of an open file to stream from. On Windows we
-- don't have pread, so this is just a Handle; on Unix platforms with pread,
-- this is a file descriptor supplied by the fd cache.
#ifdef WINDOWS
type OpenFile = IO.Handle
#else
type OpenFile = Fd
#endif
data Leftover = LZero
| LOne B.BufferWriter
| LTwo BS.ByteString B.BufferWriter
| LFile OpenFile Integer Integer (IO ())
----------------------------------------------------------------
-- | Run the given action if the stream is not closed; handle any exceptions by
-- resetting the stream.
unlessClosed :: Context -> Connection -> Stream -> IO () -> IO Bool
unlessClosed ctx
Connection{connSendAll}
strm@Stream{streamState,streamNumber}
body = E.handle resetStream $ do
state <- readIORef streamState
if (isClosed state) then return False else body >> return True
where
resetStream e = do
closed strm (ResetByMe e) ctx
let rst = resetFrame InternalError streamNumber
connSendAll rst
return False
getWindowSize :: TVar WindowSize -> TVar WindowSize -> IO WindowSize
getWindowSize connWindow strmWindow = do
-- Waiting that the connection window gets open.
cw <- atomically $ do
w <- readTVar connWindow
check (w > 0)
return w
-- This stream window is greater than 0 thanks to the invariant.
sw <- atomically $ readTVar strmWindow
return $ min cw sw
frameSender :: Context -> Connection -> InternalInfo -> S.Settings -> IO ()
frameSender ctx@Context{outputQ,connectionWindow,encodeDynamicTable}
conn@Connection{connWriteBuffer,connBufferSize,connSendAll}
ii settings = go `E.catch` ignore
where
initialSettings = [(SettingsMaxConcurrentStreams,recommendedConcurrency)]
initialFrame = settingsFrame id initialSettings
bufHeaderPayload = connWriteBuffer `plusPtr` frameHeaderLength
headerPayloadLim = connBufferSize - frameHeaderLength
go = do
connSendAll initialFrame
loop
-- ignoring the old priority because the value might be changed.
loop = dequeue outputQ >>= \(_sid,out) -> switch out
ignore :: E.SomeException -> IO ()
ignore _ = return ()
switch OFinish = return ()
switch (OGoaway frame) = connSendAll frame
switch (OSettings frame alist) = do
connSendAll frame
case lookup SettingsHeaderTableSize alist of
Nothing -> return ()
Just siz -> do
dyntbl <- readIORef encodeDynamicTable
setLimitForEncoding siz dyntbl
loop
switch (OFrame frame) = do
connSendAll frame
loop
switch (OResponse strm s h aux) = do
_ <- unlessClosed ctx conn strm $
getWindowSize connectionWindow (streamWindow strm) >>=
sendResponse strm s h aux
loop
switch (ONext strm curr) = do
_ <- unlessClosed ctx conn strm $ do
lim <- getWindowSize connectionWindow (streamWindow strm)
-- Data frame payload
Next datPayloadLen mnext <- curr lim
fillDataHeaderSend strm 0 datPayloadLen
dispatchNext strm mnext
loop
switch (OPush oldStrm push mvar strm s h aux) = do
pushed <- unlessClosed ctx conn oldStrm $ do
lim <- getWindowSize connectionWindow (streamWindow strm)
-- Write and send the promise.
builder <- hpackEncodeCIHeaders ctx $ promiseHeaders push
off <- pushContinue (streamNumber oldStrm) (streamNumber strm) builder
flushN $ off + frameHeaderLength
-- TODO(awpr): refactor sendResponse to be able to handle non-zero
-- initial offsets and use that to potentially avoid the extra syscall.
sendResponse strm s h aux lim
putMVar mvar pushed
loop
-- Send the response headers and as much of the response as is immediately
-- available; shared by normal responses and pushed streams.
sendResponse :: Stream -> H.Status -> H.ResponseHeaders -> Aux -> WindowSize -> IO ()
sendResponse strm s h (Persist sq tvar) lim = do
-- Header frame and Continuation frame
let sid = streamNumber strm
builder <- hpackEncodeHeader ctx ii settings s h
len <- headerContinue sid builder False
let total = len + frameHeaderLength
(off, needSend) <- sendHeadersIfNecessary total
let payloadOff = off + frameHeaderLength
Next datPayloadLen mnext <-
fillStreamBodyGetNext ii conn payloadOff lim sq tvar strm
-- If no data was immediately available, avoid sending an
-- empty data frame.
if datPayloadLen > 0 then
fillDataHeaderSend strm total datPayloadLen
else
when needSend $ flushN off
dispatchNext strm mnext
-- Send the stream's trailers and close the stream.
sendTrailers :: Stream -> Trailers -> IO ()
sendTrailers strm trailers = do
-- Trailers always indicate the end of a stream; send them in
-- consecutive header+continuation frames and end the stream. Some
-- clients dislike empty headers frames, so end the stream with an
-- empty data frame instead, as recommended by the spec.
toFlush <- case trailers of
[] -> frameHeaderLength <$ fillFrameHeader FrameData 0
(streamNumber strm)
(setEndStream defaultFlags)
connWriteBuffer
_ -> do
builder <- hpackEncodeCIHeaders ctx trailers
off <- headerContinue (streamNumber strm) builder True
return (off + frameHeaderLength)
-- 'closed' must be before 'flushN'. If not, the context would be
-- switched to the receiver, resulting in the inconsistency of
-- concurrency.
closed strm Finished ctx
flushN toFlush
-- Flush the connection buffer to the socket, where the first 'n' bytes of
-- the buffer are filled.
flushN :: Int -> IO ()
flushN n = bufferIO connWriteBuffer n connSendAll
-- A flags value with the end-header flag set iff the argument is B.Done.
maybeEndHeaders B.Done = setEndHeader defaultFlags
maybeEndHeaders _ = defaultFlags
-- Write PUSH_PROMISE and possibly CONTINUATION frames into the connection
-- buffer, using the given builder as their contents; flush them to the
-- socket as necessary.
pushContinue sid newSid builder = do
let builder' = B.int32BE (fromIntegral newSid) <> builder
(len, signal) <- B.runBuilder builder' bufHeaderPayload headerPayloadLim
let flag = maybeEndHeaders signal
fillFrameHeader FramePushPromise len sid flag connWriteBuffer
continue sid len signal
-- Write HEADER and possibly CONTINUATION frames.
headerContinue sid builder endOfStream = do
(len, signal) <- B.runBuilder builder bufHeaderPayload headerPayloadLim
let flag0 = maybeEndHeaders signal
flag = if endOfStream then setEndStream flag0 else flag0
fillFrameHeader FrameHeaders len sid flag connWriteBuffer
continue sid len signal
continue _ len B.Done = return len
continue sid len (B.More _ writer) = do
flushN $ len + frameHeaderLength
(len', signal') <- writer bufHeaderPayload headerPayloadLim
let flag = maybeEndHeaders signal'
fillFrameHeader FrameContinuation len' sid flag connWriteBuffer
continue sid len' signal'
continue sid len (B.Chunk bs writer) = do
flushN $ len + frameHeaderLength
let (bs1,bs2) = BS.splitAt headerPayloadLim bs
len' = BS.length bs1
void $ copy bufHeaderPayload bs1
fillFrameHeader FrameContinuation len' sid defaultFlags connWriteBuffer
if bs2 == "" then
continue sid len' (B.More 0 writer)
else
continue sid len' (B.Chunk bs2 writer)
-- True if the connection buffer has room for a 1-byte data frame.
canFitDataFrame total = total + frameHeaderLength < connBufferSize
-- Take the appropriate action based on the given 'Control':
-- - If more output is immediately available, re-enqueue the stream in the
-- output queue.
-- - If the output is over and trailers are available, send them now and
-- end the stream.
-- - If we've drained the queue and handed the stream back to its waiter,
-- do nothing.
--
-- This is done after sending any part of the stream body, so it's shared
-- by 'sendResponse' and @switch (ONext ...)@.
dispatchNext :: Stream -> Control DynaNext -> IO ()
dispatchNext _ CNone = return ()
dispatchNext strm (CFinish trailers) = sendTrailers strm trailers
dispatchNext strm (CNext next) = do
let out = ONext strm next
enqueueOrSpawnTemporaryWaiter strm outputQ out
-- Send headers if there is not room for a 1-byte data frame, and return
-- the offset of the next frame's first header byte and whether the headers
-- still need to be sent.
sendHeadersIfNecessary total
| canFitDataFrame total = return (total, True)
| otherwise = do
flushN total
return (0, False)
fillDataHeaderSend strm otherLen datPayloadLen = do
-- Data frame header
let sid = streamNumber strm
buf = connWriteBuffer `plusPtr` otherLen
total = otherLen + frameHeaderLength + datPayloadLen
fillFrameHeader FrameData datPayloadLen sid defaultFlags buf
flushN total
atomically $ do
modifyTVar' connectionWindow (subtract datPayloadLen)
modifyTVar' (streamWindow strm) (subtract datPayloadLen)
fillFrameHeader ftyp len sid flag buf = encodeFrameHeaderBuf ftyp hinfo buf
where
hinfo = FrameHeader len flag sid
----------------------------------------------------------------
fillStreamBodyGetNext :: InternalInfo -> Connection -> Int -> WindowSize
-> TBQueue Sequence -> TVar Sync -> Stream -> IO Next
fillStreamBodyGetNext ii Connection{connWriteBuffer,connBufferSize}
off lim sq tvar strm = do
let datBuf = connWriteBuffer `plusPtr` off
room = min (connBufferSize - off) lim
(leftover, cont, len) <- runStreamBuilder ii datBuf room sq
nextForStream ii connWriteBuffer connBufferSize sq tvar strm leftover cont len
----------------------------------------------------------------
runStreamBuilder :: InternalInfo -> Buffer -> BufSize -> TBQueue Sequence
-> IO (Leftover, Maybe Trailers, BytesFilled)
runStreamBuilder ii buf0 room0 sq = loop buf0 room0 0
where
loop !buf !room !total = do
mbuilder <- atomically $ tryReadTBQueue sq
case mbuilder of
Nothing -> return (LZero, Nothing, total)
Just (SBuilder builder) -> do
(len, signal) <- B.runBuilder builder buf room
let !total' = total + len
case signal of
B.Done -> loop (buf `plusPtr` len) (room - len) total'
B.More _ writer -> return (LOne writer, Nothing, total')
B.Chunk bs writer -> return (LTwo bs writer, Nothing, total')
Just (SFile path part) -> do
(leftover, len) <- runStreamFile ii buf room path part
let !total' = total + len
return (leftover, Nothing, total')
-- TODO if file part is done, go back to loop
Just SFlush -> return (LZero, Nothing, total)
Just (SFinish trailers) -> return (LZero, Just trailers, total)
-- | Open the file and start reading into the send buffer.
runStreamFile :: InternalInfo -> Buffer -> BufSize -> FilePath -> FilePart
-> IO (Leftover, BytesFilled)
-- | Read the given (OS-specific) file representation into the buffer. On
-- non-Windows systems this uses pread; on Windows this ignores the position
-- because we use the Handle's internal read position instead (because it's not
-- potentially shared with other readers).
readOpenFile :: OpenFile -> Buffer -> BufSize -> Integer -> IO Int
#ifdef WINDOWS
runStreamFile _ buf room path part = do
let start = filePartOffset part
bytes = filePartByteCount part
-- fixme: how to close Handle? GC does it at this moment.
h <- IO.openBinaryFile path IO.ReadMode
IO.hSeek h IO.AbsoluteSeek start
fillBufFile buf room h start bytes (return ())
readOpenFile h buf room _ = IO.hGetBufSome h buf room
#else
runStreamFile ii buf room path part = do
let start = filePartOffset part
bytes = filePartByteCount part
(fd, refresh) <- case fdCacher ii of
Just fdcache -> getFd fdcache path
Nothing -> do
fd' <- openFd path ReadOnly Nothing defaultFileFlags{nonBlock=True}
th <- T.register (timeoutManager ii) (closeFd fd')
return (fd', T.tickle th)
fillBufFile buf room fd start bytes refresh
readOpenFile = positionRead
#endif
-- | Read as much of the file as is currently available into the buffer, then
-- return a 'Leftover' to indicate whether this file chunk has more data to
-- send. If this read hit the end of the file range, return 'LZero'; otherwise
-- return 'LFile' so this stream will continue reading from the file the next
-- time it's pulled from the queue.
fillBufFile :: Buffer -> BufSize -> OpenFile -> Integer -> Integer -> (IO ())
-> IO (Leftover, BytesFilled)
fillBufFile buf room f start bytes refresh = do
len <- readOpenFile f buf (mini room bytes) start
refresh
let len' = fromIntegral len
leftover = if bytes > len' then
LFile f (start + len') (bytes - len') refresh
else
LZero
return (leftover, len)
mini :: Int -> Integer -> Int
mini i n
| fromIntegral i < n = i
| otherwise = fromIntegral n
fillBufStream :: InternalInfo -> Buffer -> BufSize -> Leftover
-> TBQueue Sequence -> TVar Sync -> Stream -> DynaNext
fillBufStream ii buf0 siz0 leftover0 sq tvar strm lim0 = do
let payloadBuf = buf0 `plusPtr` frameHeaderLength
room0 = min (siz0 - frameHeaderLength) lim0
case leftover0 of
LZero -> do
(leftover, end, len) <- runStreamBuilder ii payloadBuf room0 sq
getNext leftover end len
LOne writer -> write writer payloadBuf room0 0
LTwo bs writer
| BS.length bs <= room0 -> do
buf1 <- copy payloadBuf bs
let len = BS.length bs
write writer buf1 (room0 - len) len
| otherwise -> do
let (bs1,bs2) = BS.splitAt room0 bs
void $ copy payloadBuf bs1
getNext (LTwo bs2 writer) Nothing room0
LFile fd start bytes refresh -> do
(leftover, len) <- fillBufFile payloadBuf room0 fd start bytes refresh
getNext leftover Nothing len
where
getNext = nextForStream ii buf0 siz0 sq tvar strm
write writer1 buf room sofar = do
(len, signal) <- writer1 buf room
case signal of
B.Done -> do
(leftover, end, extra) <- runStreamBuilder ii (buf `plusPtr` len) (room - len) sq
let !total = sofar + len + extra
getNext leftover end total
B.More _ writer -> do
let !total = sofar + len
getNext (LOne writer) Nothing total
B.Chunk bs writer -> do
let !total = sofar + len
getNext (LTwo bs writer) Nothing total
nextForStream :: InternalInfo -> Buffer -> BufSize -> TBQueue Sequence
-> TVar Sync -> Stream -> Leftover -> Maybe Trailers
-> BytesFilled -> IO Next
nextForStream _ _ _ _ tvar _ _ (Just trailers) len = do
atomically $ writeTVar tvar $ SyncFinish
return $ Next len $ CFinish trailers
nextForStream ii buf siz sq tvar strm LZero Nothing len = do
let out = ONext strm (fillBufStream ii buf siz LZero sq tvar strm)
atomically $ writeTVar tvar $ SyncNext out
return $ Next len CNone
nextForStream ii buf siz sq tvar strm leftover Nothing len =
return $ Next len (CNext (fillBufStream ii buf siz leftover sq tvar strm))
| urbanslug/wai | warp/Network/Wai/Handler/Warp/HTTP2/Sender.hs | mit | 17,978 | 0 | 19 | 4,878 | 4,113 | 2,047 | 2,066 | 291 | 17 |
import Data.Maybe (fromJust)
import Data.List.Split (chunksOf)
import Data.Char (ord, chr)
import Data.Bits hiding (rotate)
md :: a -> ([Char] -> [b]) -> ([Char] -> [Char]) -> (a -> b -> a) -> (a -> [Char]) -> ([Char] -> [Char])
md iv blockf padf f finalf = (\msg -> finalf $ foldl f iv (blockf $ padf msg))
compose :: [a -> a] -> (a -> a)
compose fs = foldl (flip (.)) id fs
transpose :: [[a]] -> [[a]]
transpose ([]:_) = []
transpose arr = (map head arr):(transpose (map tail arr))
replacen :: Int -> a -> [a] -> [a]
replacen n val (x:xs)
| n == 0 = val:xs
| otherwise = x:(replacen (n-1) val xs)
replace2n :: Int -> Int -> a -> [[a]] -> [[a]]
replace2n n1 n2 val arr = replacen n1 (replacen n2 val (arr !! n1)) arr
setval :: [[Bool]] -> Int -> Int -> Bool -> [[Bool]]
setval arr n1 n2 val = replace2n n1 n2 val arr
getringdict :: Int -> Int -> [(Int,(Int, Int))]
getringdict n s = zip [0..] (c1 ++ c2 ++ c3 ++ c4)
where
c1 = zip [n..s-n-2] (repeat n)
c2 = zip (repeat (s-n-1)) [n..s-n-2]
c3 = zip [s-n-1,s-n-2..n+1] (repeat (s-n-1))
c4 = zip (repeat n) [s-n-1,s-n-2..n+1]
rraccum :: [(Int,(Int, Int))] -> Int -> ([[Bool]], [[Bool]]) -> (Int,(Int, Int)) -> ([[Bool]], [[Bool]])
rraccum rposs amount (oblock, nblock) entry = (oblock, replace2n n1 n2 obool nblock)
where
np = mod ((fst entry) + amount) (length rposs)
(n1, n2) = fromJust $ lookup np rposs
(o1, o2) = snd entry
obool = (oblock !! o1) !! o2
rotring :: Int -> Int -> [[Bool]] -> [[Bool]]
rotring amount ring oblock = snd $ foldl (rraccum rposs dr) (oblock,oblock) rposs
where
rposs = getringdict ring $ length oblock
dr
| mod amount 2 == 0 = amount
| mod amount 2 == 1 = (-amount)
rotate :: [[Bool]] -> Int -> [[Bool]]
rotate oblock amount = compose (map (rotring amount) [0..div (length oblock) 2]) $ oblock
lcycle :: (Int,[a]) -> [a]
lcycle (dif, lst) = l2++l1
where (l1, l2) = splitAt (mod dif (length lst)) lst
slice :: [[Bool]] -> Int -> Int -> [[Bool]]
slice oblock amount dir
| dir == 1 = transpose $ slice (transpose oblock) amount 0
| dir == 0 = map lcycle $ zip (cycle [amount, -amount]) oblock
mix :: [[Bool]] -> Int -> [[Bool]]
mix arr amount = slice (slice arr amount 0) amount 1
displace :: [[Bool]] -> (Int, Int) -> Bool -> Bool -> Int -> [[Bool]]
displace arr (cx, cy) ori cv iters
| iters == 0 = arr
| otherwise = displace (replace2n mncx mncy cv arr) (mncx, mncy) (not ori) nv (iters-1)
where
ncx
| cv && ori = cx + 1
| (not cv) && ori = cx - 2
| otherwise = cx
ncy
| cv && not(ori) = cy + 2
| (not cv) && (not ori) = cy - 1
| otherwise = cy
mncx = mod ncx s
mncy = mod ncy s
nv = (arr !! mncx) !! mncy
s = length arr
rmdaf :: Int -> Int -> Int -> [[Bool]] -> [Bool]-> [[Bool]]
rmdaf dt ds dd arr na = displace (mix (rotate narr dt) ds) (0,0) True nval dd
where
narr = foldl (\acarr (v, (p1, p2)) -> replace2n p1 p2 v acarr) arr (zip na $ zip [0..] [0..])
nval = ((narr !! 0) !! 0)
sublist :: Int -> Int -> [a] -> [a] --inclusive both
sublist min max lst = fst $ splitAt (max-rmin) (snd $ splitAt rmin lst)
where rmin = min - 1
subblock :: [[Bool]] -> Int -> Int -> Int -> Int -> [[Bool]] --inclusive both
subblock arr minx maxx miny maxy = sublist miny maxy (map (sublist minx maxx) arr)
eo :: [a] -> Int -> [a]
eo [] _ = []
eo lst s
| s == 0 = x:(eo (drop 1 xs) 0)
| s == 1 = eo (drop 1 lst) 0
where (x:xs) = lst
checker :: [[Bool]] -> Int -> [[Bool]]
checker arr start = map (\(s, row) -> eo row s) (zip (cycle [0,1]) arr)
xorblock :: [[Bool]] -> [[Bool]] -> [[Bool]]
xorblock a b = map (\(l1, l2) -> map (\t -> (/=) (fst t) (snd t)) (zip l1 l2)) (zip a b)
mdpad :: Int -> Char -> Char -> [Char] -> [Char]
mdpad bsize nd yd istr= istr ++ [nd] ++ (take zp (repeat yd)) ++ (show len)
where
len = length istr
zp = bsize - (mod (len + 1 + (length $ show len)) bsize)
blockf :: Int -> [Char] -> [[Bool]]
blockf s msg = map (concat.(map $ cbin.ord)) (chunksOf s msg)
where
cbin v = reverse $ snd $ foldl af (v,[]) [7,6..0]
af = (\(t,a) x -> if (t >= 2^x) then (t-(2^x),True:a) else (t,False:a))
lehmer :: (Integral a) => a -> a -> a -> a
lehmer prev maxp mult = mod (mult * prev) maxp
plehmer :: (Integral a) => a -> a
plehmer seed = lehmer seed 2147483647 16807
iv :: Int -> Int -> [[Bool]]
iv size seed = chunksOf size (snd $ foldl acc (seed,[]) [1..size^2])
where
acc (s,a) i = let nr = plehmer s in (nr, (odd nr):a)
finalf :: Int -> Int -> Int -> Int -> Int -> [[Bool]] -> [Char]
finalf sbs dt ds dd k arr = tochar (xorblock sbb1 sbb2)
where
sbb1 = checker (subblock narr 0 (2*sbs-1) 0 (sbs-1)) 0
sbb2 = checker (subblock narr (l-1-2*sbs) (l-1) (l-sbs-1) (l-1)) 0
l = length arr
narr = foldr (.) id (replicate k $ \x -> rmdaf dt ds dd x []) $ arr
tochar = (map chr) . toint . (chunksOf 8) . concat
toint msg = map (\j -> sum $ map (\(b,x) -> if b then 2^x else 0) $ zip j [0..7]) msg
displh :: ([Char] -> [Char])
displh = md ivf bf pad f ff
where
ivf = iv 64 65537
bf = blockf 8
pad = mdpad 8 '1' '0'
f = rmdaf 17 19 4096
ff = finalf 32 11 13 1024 8
numberOfSetBits :: Int -> Int
numberOfSetBits x
| x == 0 = 0
| otherwise = 1 + (numberOfSetBits (x .&. (x - 1)))
hammingDistance :: [Char] -> [Char] -> Int
hammingDistance a b = sum (map (\ (x, y) -> numberOfSetBits (xor (ord x) (ord y))) (zip a b))
{-| testing the results:
let a = displh "hello world!"
let b = displh "hullo world!"
let c = displh "hello world."
hammingDistance a b
> 513
hammingDistance b c
> 491
hammingDistance a c
> 512
-}
| CFFD/CRHF | crhf.hs | gpl-2.0 | 5,790 | 9 | 16 | 1,535 | 3,321 | 1,776 | 1,545 | 119 | 2 |
{-# language TemplateHaskell, DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
module Program.Cexp.Annotated where
import Program.Cexp.Type hiding ( Symbol, Literal )
import qualified Program.Cexp.Type as T
import Data.Map ( Map )
import qualified Data.Map as M
import Autolib.FiniteMap
import Control.Monad ( forM_ )
import Autolib.Reporter
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Util.Size
import Data.Typeable
import Data.Tree
import Data.Maybe ( isJust )
import qualified Data.List
data Annotated =
Annotated { node :: Node
, lvalue :: Maybe Identifier
, rvalue :: Maybe Integer
, actions :: [ (Time, Action) ]
, children :: [ Annotated ]
}
deriving Typeable
instance Size Annotated where
size = succ . sum . map size . children
blank :: Annotated
blank = Annotated { children = [], lvalue = Nothing, rvalue = Nothing, actions = [] }
newtype Time = Time Int deriving ( Eq, Ord, Enum )
data Action = Read Identifier Integer -- ^ this includes the expected result of the reading
| Write Identifier Integer
deriving ( Eq, Ord )
data Node = Literal Integer | Symbol Identifier | Operator Oper
$(derives [makeToDoc,makeReader] [''Node, ''Annotated, ''Time, ''Action])
-------------------------------------------------------------------
-- | produce tree that is partially annotated
start :: Exp -> Annotated
start x = case x of
T.Literal i -> blank { node = Literal i, rvalue = Just i }
T.Symbol s -> blank { node = Symbol s, lvalue = Just s }
Apply op xs -> blank { node = Operator $ oper op
, children = map start xs
}
-------------------------------------------------------------------
all_actions :: Annotated -> [ (Time, Action) ]
all_actions a = actions a ++ ( children a >>= all_actions )
type Store = FiniteMap Identifier Integer
-- | execute actions in order given by timestamps.
-- checks that Read actions get the values they expect.
execute :: Annotated -> Reporter ()
execute a = do
let acts = Data.List.sort $ all_actions a
let distinct ( x : y : zs ) =
if fst x == fst y
then reject $ text "gleichzeitige Aktionen"
</> vcat [ toDoc x, toDoc y ]
else distinct ( y : zs )
distinct _ = return ()
distinct acts
let step st ( ta @ (time, act) ) = do
inform $ toDoc ta
case act of
Read p x -> case M.lookup p st of
Nothing -> reject $ text "Wert nicht gebunden"
Just y ->
if x == y then return st
else reject $ text "Falscher Wert gebunden"
Write p x -> return $ M.insert p x st
foldM step emptyFM acts
return ()
-------------------------------------------------------------------
check :: Annotated -> Reporter ()
check a = case node a of
Literal i -> do
case lvalue a of
Just _ -> reject $ text "Literal ist kein lvalue" </> toDoc a
Nothing -> return ()
case rvalue a of
Just v | i /= v -> reject $ text "rvalue falsch" </> toDoc a
_ -> return ()
when ( not $ null $ actions a ) $ reject
$ text "keine Aktionen in Literalknoten" </> toDoc a
Symbol s -> do
case lvalue a of
Just v | s /= v -> reject ( text "lvalue falsch" </> toDoc a )
_ -> return ()
case rvalue a of
Nothing -> do
when ( not $ null $ actions a ) $ reject
$ text "rvalue nicht benutzt => keine Aktionen in Symbolknoten" </> toDoc a
Just v -> do
p <- case lvalue a of
Just p -> return p
Nothing -> reject $ text "lvalue erforderlich" </> toDoc a
w <- case actions a of
[ ( time, Read q w) ] -> do
when ( p /= q )
$ reject $ text "Read benutzt falschen lvalue" </> toDoc a
return w
_ -> reject $ text "Bestimmung des rvalues erfordert Read-Aktion"
when ( v /= w ) $ reject
$ text "rvalue falsch" </> toDoc a
Operator op -> do
forM_ ( children a ) check
case ( op, children a ) of
( Assign, [ l,r ] ) -> do
p <- case lvalue l of
Nothing -> reject $ text "Zuweisungsziel muß lvalue haben" </> toDoc a
Just p -> return p
v <- case rvalue r of
Nothing -> reject $ text "Zuweisungsquelle muß rvalue haben" </> toDoc a
Just v -> return v
case actions a of
[ (time, Write q w ) ] -> do
when ( q /= p ) $ reject $ text "falsches Ziel für Write" </> toDoc a
when ( w /= v ) $ reject $ text "falscher Wert für Write" </> toDoc a
_ -> reject $ text "Zuweisung erfordert genau eine Write-Aktion" </> toDoc a
( op , [ l ] ) | elem op [ Prefix Increment, Prefix Decrement
, Postfix Increment, Postfix Decrement ] -> do
when ( isJust $ lvalue a ) $ reject $ text "ist kein lvalue" </> toDoc a
p <- case lvalue l of
Nothing -> reject $ text "Argument muß lvalue haben" </> toDoc a
Just p -> return p
case Data.List.sort $ actions a of
[ (rtime, Read q w), (wtime, Write q' w') ] -> do
when ( p /= q || p /= q' )
$ reject $ text "Lese/Schreibziel muß mit lvalue übereinstimmen" </> toDoc a
when ( succ rtime /= wtime )
$ reject $ text "Schreiben muß direkt auf Lesen folgen" </> toDoc a
let ( result, store ) = case op of
Prefix Increment -> ( succ w, succ w )
Postfix Increment -> ( w, succ w )
Prefix Decrement -> ( pred w, pred w )
Postfix Decrement -> ( w, pred w )
when ( store /= w' )
$ reject $ text "falscher Wert geschrieben" </> toDoc a
when ( Just result /= rvalue a )
$ reject $ text "falsches Resultat in rvalue" </> toDoc a
_ -> reject
$ text "Präfix/Postfix-Operator erforder Read- und Write-Aktion" </> toDoc a
( Sequence , [ l, r ] ) -> do
when ( lvalue r /= lvalue a )
$ reject $ text "lvalues von Wurzel und zweitem Argument müssen übereinstimmen" </> toDoc a
when ( rvalue r /= rvalue a )
$ reject $ text "rvalues von Wurzel und zweitem Argument müssen übereinstimmen" </> toDoc a
( _ , [ l, r ] ) | Just f <- standard op -> do
vl <- case rvalue l of
Nothing -> reject $ text "erstes Argument hat kein rvalue" </> toDoc a
Just vl -> return vl
vr <- case rvalue r of
Nothing -> reject $ text "zweites Argument hat kein rvalue" </> toDoc a
Just vr -> return vr
let result = f vl vr
when ( rvalue a /= Just result )
$ reject $ text "falsches Resultat in rvalue" </> toDoc a
standard op = case op of
Plus -> Just (+)
Minus -> Just (-)
Times -> Just (*)
Divide -> Just div
Remainder -> Just rem
_ -> Nothing
-----------------------------------------------------
same_skeleton :: (Exp, Annotated) -> Reporter ()
same_skeleton (x, a) = case (x,node a) of
(T.Symbol xs, Symbol ys) ->
when ( xs /= ys )
$ mismatch (text "verschiedene Bezeichner") x a
(T.Literal i, Literal j) ->
when ( i /= j )
$ mismatch (text "verschiedene Literale") x a
(Apply xop xargs, Operator cs ) -> do
when ( oper xop /= cs)
$ mismatch (text "verschiedene Operatoren") x a
when ( length xargs /= length ( children a ))
$ mismatch (text "verschiede Argumentanzahlen") x a
forM_ ( zip xargs $ children a ) $ same_skeleton
mismatch msg x a = reject $
msg </> vcat [ text "original" </> toDoc a
, text "annotiert" </> toDoc x
]
-------------------------------------------------------------------
| florianpilz/autotool | src/Program/Cexp/Annotated.hs | gpl-2.0 | 8,867 | 1 | 28 | 3,485 | 2,634 | 1,285 | 1,349 | 171 | 22 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GHCForeignImportPrim #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE UnliftedFFITypes #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE NegativeLiterals #-}
{-# LANGUAGE ExplicitForAll #-}
-- |
-- Module : GHC.Integer.Type
-- Copyright : (c) Herbert Valerio Riedel 2014
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : non-portable (GHC Extensions)
--
-- GHC needs this module to be named "GHC.Integer.Type" and provide
-- all the low-level 'Integer' operations.
module GHC.Integer.Type where
#include "MachDeps.h"
-- Sanity check as CPP defines are implicitly 0-valued when undefined
#if !(defined(SIZEOF_LONG) && defined(SIZEOF_HSWORD) \
&& defined(WORD_SIZE_IN_BITS))
# error missing defines
#endif
import GHC.Classes
import GHC.Magic
import GHC.Prim
import GHC.Types
#if WORD_SIZE_IN_BITS < 64
import GHC.IntWord64
#endif
default ()
-- Most high-level operations need to be marked `NOINLINE` as
-- otherwise GHC doesn't recognize them and fails to apply constant
-- folding to `Integer`-typed expression.
--
-- To this end, the CPP hack below allows to write the pseudo-pragma
--
-- {-# CONSTANT_FOLDED plusInteger #-}
--
-- which is simply expaned into a
--
-- {-# NOINLINE plusInteger #-}
--
#define CONSTANT_FOLDED NOINLINE
----------------------------------------------------------------------------
-- type definitions
-- NB: all code assumes GMP_LIMB_BITS == WORD_SIZE_IN_BITS
-- The C99 code in cbits/wrappers.c will fail to compile if this doesn't hold
-- | Type representing a GMP Limb
type GmpLimb = Word -- actually, 'CULong'
type GmpLimb# = Word#
-- | Count of 'GmpLimb's, must be positive (unless specified otherwise).
type GmpSize = Int -- actually, a 'CLong'
type GmpSize# = Int#
narrowGmpSize# :: Int# -> Int#
#if SIZEOF_LONG == SIZEOF_HSWORD
narrowGmpSize# x = x
#elif (SIZEOF_LONG == 4) && (SIZEOF_HSWORD == 8)
-- On IL32P64 (i.e. Win64), we have to be careful with CLong not being
-- 64bit. This is mostly an issue on values returned from C functions
-- due to sign-extension.
narrowGmpSize# = narrow32Int#
#endif
type GmpBitCnt = Word -- actually, 'CULong'
type GmpBitCnt# = Word# -- actually, 'CULong'
-- Pseudo FFI CType
type CInt = Int
type CInt# = Int#
narrowCInt# :: Int# -> Int#
narrowCInt# = narrow32Int#
-- | Bits in a 'GmpLimb'. Same as @WORD_SIZE_IN_BITS@.
gmpLimbBits :: Word -- 8 `shiftL` gmpLimbShift
gmpLimbBits = W# WORD_SIZE_IN_BITS##
#if WORD_SIZE_IN_BITS == 64
# define GMP_LIMB_SHIFT 3
# define GMP_LIMB_BYTES 8
# define GMP_LIMB_BITS 64
# define INT_MINBOUND -0x8000000000000000
# define INT_MAXBOUND 0x7fffffffffffffff
# define ABS_INT_MINBOUND 0x8000000000000000
# define SQRT_INT_MAXBOUND 0xb504f333
#elif WORD_SIZE_IN_BITS == 32
# define GMP_LIMB_SHIFT 2
# define GMP_LIMB_BYTES 4
# define GMP_LIMB_BITS 32
# define INT_MINBOUND -0x80000000
# define INT_MAXBOUND 0x7fffffff
# define ABS_INT_MINBOUND 0x80000000
# define SQRT_INT_MAXBOUND 0xb504
#else
# error unsupported WORD_SIZE_IN_BITS config
#endif
-- | Type representing /raw/ arbitrary-precision Naturals
--
-- This is common type used by 'Natural' and 'Integer'. As this type
-- consists of a single constructor wrapping a 'ByteArray#' it can be
-- unpacked.
--
-- Essential invariants:
--
-- - 'ByteArray#' size is an exact multiple of 'Word#' size
-- - limbs are stored in least-significant-limb-first order,
-- - the most-significant limb must be non-zero, except for
-- - @0@ which is represented as a 1-limb.
data BigNat = BN# ByteArray#
instance Eq BigNat where
(==) = eqBigNat
instance Ord BigNat where
compare = compareBigNat
-- | Invariant: 'Jn#' and 'Jp#' are used iff value doesn't fit in 'S#'
--
-- Useful properties resulting from the invariants:
--
-- - @abs ('S#' _) <= abs ('Jp#' _)@
-- - @abs ('S#' _) < abs ('Jn#' _)@
--
data Integer = S# !Int#
-- ^ iff value in @[minBound::'Int', maxBound::'Int']@ range
| Jp# {-# UNPACK #-} !BigNat
-- ^ iff value in @]maxBound::'Int', +inf[@ range
| Jn# {-# UNPACK #-} !BigNat
-- ^ iff value in @]-inf, minBound::'Int'[@ range
-- TODO: experiment with different constructor-ordering
instance Eq Integer where
(==) = eqInteger
(/=) = neqInteger
instance Ord Integer where
compare = compareInteger
(>) = gtInteger
(>=) = geInteger
(<) = ltInteger
(<=) = leInteger
----------------------------------------------------------------------------
-- | Construct 'Integer' value from list of 'Int's.
--
-- This function is used by GHC for constructing 'Integer' literals.
mkInteger :: Bool -- ^ sign of integer ('True' if non-negative)
-> [Int] -- ^ absolute value expressed in 31 bit chunks, least
-- significant first (ideally these would be machine-word
-- 'Word's rather than 31-bit truncated 'Int's)
-> Integer
mkInteger nonNegative is
| nonNegative = f is
| True = negateInteger (f is)
where
f [] = S# 0#
f (I# i : is') = smallInteger (i `andI#` 0x7fffffff#) `orInteger`
shiftLInteger (f is') 31#
{-# CONSTANT_FOLDED mkInteger #-}
-- | Test whether all internal invariants are satisfied by 'Integer' value
--
-- Returns @1#@ if valid, @0#@ otherwise.
--
-- This operation is mostly useful for test-suites and/or code which
-- constructs 'Integer' values directly.
isValidInteger# :: Integer -> Int#
isValidInteger# (S# _) = 1#
isValidInteger# (Jp# bn)
= isValidBigNat# bn `andI#` (bn `gtBigNatWord#` INT_MAXBOUND##)
isValidInteger# (Jn# bn)
= isValidBigNat# bn `andI#` (bn `gtBigNatWord#` ABS_INT_MINBOUND##)
-- | Should rather be called @intToInteger@
smallInteger :: Int# -> Integer
smallInteger i# = S# i#
{-# CONSTANT_FOLDED smallInteger #-}
----------------------------------------------------------------------------
-- Int64/Word64 specific primitives
#if WORD_SIZE_IN_BITS < 64
int64ToInteger :: Int64# -> Integer
int64ToInteger i
| isTrue# (i `leInt64#` intToInt64# 0x7FFFFFFF#)
, isTrue# (i `geInt64#` intToInt64# -0x80000000#)
= S# (int64ToInt# i)
| isTrue# (i `geInt64#` intToInt64# 0#)
= Jp# (word64ToBigNat (int64ToWord64# i))
| True
= Jn# (word64ToBigNat (int64ToWord64# (negateInt64# i)))
{-# CONSTANT_FOLDED int64ToInteger #-}
word64ToInteger :: Word64# -> Integer
word64ToInteger w
| isTrue# (w `leWord64#` wordToWord64# 0x7FFFFFFF##)
= S# (int64ToInt# (word64ToInt64# w))
| True
= Jp# (word64ToBigNat w)
{-# CONSTANT_FOLDED word64ToInteger #-}
integerToInt64 :: Integer -> Int64#
integerToInt64 (S# i#) = intToInt64# i#
integerToInt64 (Jp# bn) = word64ToInt64# (bigNatToWord64 bn)
integerToInt64 (Jn# bn) = negateInt64# (word64ToInt64# (bigNatToWord64 bn))
{-# CONSTANT_FOLDED integerToInt64 #-}
integerToWord64 :: Integer -> Word64#
integerToWord64 (S# i#) = int64ToWord64# (intToInt64# i#)
integerToWord64 (Jp# bn) = bigNatToWord64 bn
integerToWord64 (Jn# bn)
= int64ToWord64# (negateInt64# (word64ToInt64# (bigNatToWord64 bn)))
{-# CONSTANT_FOLDED integerToWord64 #-}
#if GMP_LIMB_BITS == 32
word64ToBigNat :: Word64# -> BigNat
word64ToBigNat w64 = wordToBigNat2 wh# wl#
where
wh# = word64ToWord# (uncheckedShiftRL64# w64 32#)
wl# = word64ToWord# w64
bigNatToWord64 :: BigNat -> Word64#
bigNatToWord64 bn
| isTrue# (sizeofBigNat# bn ># 1#)
= let wh# = wordToWord64# (indexBigNat# bn 1#)
in uncheckedShiftL64# wh# 32# `or64#` wl#
| True = wl#
where
wl# = wordToWord64# (bigNatToWord bn)
#endif
#endif
-- End of Int64/Word64 specific primitives
----------------------------------------------------------------------------
-- | Truncates 'Integer' to least-significant 'Int#'
integerToInt :: Integer -> Int#
integerToInt (S# i#) = i#
integerToInt (Jp# bn) = bigNatToInt bn
integerToInt (Jn# bn) = negateInt# (bigNatToInt bn)
{-# CONSTANT_FOLDED integerToInt #-}
hashInteger :: Integer -> Int#
hashInteger = integerToInt -- emulating what integer-{simple,gmp} already do
integerToWord :: Integer -> Word#
integerToWord (S# i#) = int2Word# i#
integerToWord (Jp# bn) = bigNatToWord bn
integerToWord (Jn# bn) = int2Word# (negateInt# (bigNatToInt bn))
{-# CONSTANT_FOLDED integerToWord #-}
wordToInteger :: Word# -> Integer
wordToInteger w#
| isTrue# (i# >=# 0#) = S# i#
| True = Jp# (wordToBigNat w#)
where
i# = word2Int# w#
{-# CONSTANT_FOLDED wordToInteger #-}
wordToNegInteger :: Word# -> Integer
wordToNegInteger w#
| isTrue# (i# <=# 0#) = S# i#
| True = Jn# (wordToBigNat w#)
where
i# = negateInt# (word2Int# w#)
-- we could almost auto-derive Ord if it wasn't for the Jn#-Jn# case
compareInteger :: Integer -> Integer -> Ordering
compareInteger (Jn# x) (Jn# y) = compareBigNat y x
compareInteger (S# x) (S# y) = compareInt# x y
compareInteger (Jp# x) (Jp# y) = compareBigNat x y
compareInteger (Jn# _) _ = LT
compareInteger (S# _) (Jp# _) = LT
compareInteger (S# _) (Jn# _) = GT
compareInteger (Jp# _) _ = GT
{-# CONSTANT_FOLDED compareInteger #-}
isNegInteger# :: Integer -> Int#
isNegInteger# (S# i#) = i# <# 0#
isNegInteger# (Jp# _) = 0#
isNegInteger# (Jn# _) = 1#
-- | Not-equal predicate.
neqInteger :: Integer -> Integer -> Bool
neqInteger x y = isTrue# (neqInteger# x y)
eqInteger, leInteger, ltInteger, gtInteger, geInteger
:: Integer -> Integer -> Bool
eqInteger x y = isTrue# (eqInteger# x y)
leInteger x y = isTrue# (leInteger# x y)
ltInteger x y = isTrue# (ltInteger# x y)
gtInteger x y = isTrue# (gtInteger# x y)
geInteger x y = isTrue# (geInteger# x y)
eqInteger#, neqInteger#, leInteger#, ltInteger#, gtInteger#, geInteger#
:: Integer -> Integer -> Int#
eqInteger# (S# x#) (S# y#) = x# ==# y#
eqInteger# (Jn# x) (Jn# y) = eqBigNat# x y
eqInteger# (Jp# x) (Jp# y) = eqBigNat# x y
eqInteger# _ _ = 0#
{-# CONSTANT_FOLDED eqInteger# #-}
neqInteger# (S# x#) (S# y#) = x# /=# y#
neqInteger# (Jn# x) (Jn# y) = neqBigNat# x y
neqInteger# (Jp# x) (Jp# y) = neqBigNat# x y
neqInteger# _ _ = 1#
{-# CONSTANT_FOLDED neqInteger# #-}
gtInteger# (S# x#) (S# y#) = x# ># y#
gtInteger# x y | inline compareInteger x y == GT = 1#
gtInteger# _ _ = 0#
{-# CONSTANT_FOLDED gtInteger# #-}
leInteger# (S# x#) (S# y#) = x# <=# y#
leInteger# x y | inline compareInteger x y /= GT = 1#
leInteger# _ _ = 0#
{-# CONSTANT_FOLDED leInteger# #-}
ltInteger# (S# x#) (S# y#) = x# <# y#
ltInteger# x y | inline compareInteger x y == LT = 1#
ltInteger# _ _ = 0#
{-# CONSTANT_FOLDED ltInteger# #-}
geInteger# (S# x#) (S# y#) = x# >=# y#
geInteger# x y | inline compareInteger x y /= LT = 1#
geInteger# _ _ = 0#
{-# CONSTANT_FOLDED geInteger# #-}
-- | Compute absolute value of an 'Integer'
absInteger :: Integer -> Integer
absInteger (Jn# n) = Jp# n
absInteger (S# INT_MINBOUND#) = Jp# (wordToBigNat ABS_INT_MINBOUND##)
absInteger (S# i#) | isTrue# (i# <# 0#) = S# (negateInt# i#)
absInteger i@(S# _) = i
absInteger i@(Jp# _) = i
{-# CONSTANT_FOLDED absInteger #-}
-- | Return @-1@, @0@, and @1@ depending on whether argument is
-- negative, zero, or positive, respectively
signumInteger :: Integer -> Integer
signumInteger j = S# (signumInteger# j)
{-# CONSTANT_FOLDED signumInteger #-}
-- | Return @-1#@, @0#@, and @1#@ depending on whether argument is
-- negative, zero, or positive, respectively
signumInteger# :: Integer -> Int#
signumInteger# (Jn# _) = -1#
signumInteger# (S# i#) = sgnI# i#
signumInteger# (Jp# _ ) = 1#
-- | Negate 'Integer'
negateInteger :: Integer -> Integer
negateInteger (Jn# n) = Jp# n
negateInteger (S# INT_MINBOUND#) = Jp# (wordToBigNat ABS_INT_MINBOUND##)
negateInteger (S# i#) = S# (negateInt# i#)
negateInteger (Jp# bn)
| isTrue# (eqBigNatWord# bn ABS_INT_MINBOUND##) = S# INT_MINBOUND#
| True = Jn# bn
{-# CONSTANT_FOLDED negateInteger #-}
-- one edge-case issue to take into account is that Int's range is not
-- symmetric around 0. I.e. @minBound+maxBound = -1@
--
-- Jp# is used iff n > maxBound::Int
-- Jn# is used iff n < minBound::Int
-- | Add two 'Integer's
plusInteger :: Integer -> Integer -> Integer
plusInteger x (S# 0#) = x
plusInteger (S# 0#) y = y
plusInteger (S# x#) (S# y#)
= case addIntC# x# y# of
(# z#, 0# #) -> S# z#
(# 0#, _ #) -> Jn# (wordToBigNat2 1## 0##) -- 2*minBound::Int
(# z#, _ #)
| isTrue# (z# ># 0#) -> Jn# (wordToBigNat ( (int2Word# (negateInt# z#))))
| True -> Jp# (wordToBigNat ( (int2Word# z#)))
plusInteger y@(S# _) x = plusInteger x y
-- no S# as first arg from here on
plusInteger (Jp# x) (Jp# y) = Jp# (plusBigNat x y)
plusInteger (Jn# x) (Jn# y) = Jn# (plusBigNat x y)
plusInteger (Jp# x) (S# y#) -- edge-case: @(maxBound+1) + minBound == 0@
| isTrue# (y# >=# 0#) = Jp# (plusBigNatWord x (int2Word# y#))
| True = bigNatToInteger (minusBigNatWord x (int2Word#
(negateInt# y#)))
plusInteger (Jn# x) (S# y#) -- edge-case: @(minBound-1) + maxBound == -2@
| isTrue# (y# >=# 0#) = bigNatToNegInteger (minusBigNatWord x (int2Word# y#))
| True = Jn# (plusBigNatWord x (int2Word# (negateInt# y#)))
plusInteger y@(Jn# _) x@(Jp# _) = plusInteger x y
plusInteger (Jp# x) (Jn# y)
= case compareBigNat x y of
LT -> bigNatToNegInteger (minusBigNat y x)
EQ -> S# 0#
GT -> bigNatToInteger (minusBigNat x y)
{-# CONSTANT_FOLDED plusInteger #-}
-- TODO
-- | Subtract two 'Integer's from each other.
minusInteger :: Integer -> Integer -> Integer
minusInteger x y = inline plusInteger x (inline negateInteger y)
{-# CONSTANT_FOLDED minusInteger #-}
-- | Multiply two 'Integer's
timesInteger :: Integer -> Integer -> Integer
timesInteger _ (S# 0#) = S# 0#
timesInteger (S# 0#) _ = S# 0#
timesInteger x (S# 1#) = x
timesInteger (S# 1#) y = y
timesInteger x (S# -1#) = negateInteger x
timesInteger (S# -1#) y = negateInteger y
timesInteger (S# x#) (S# y#)
= case mulIntMayOflo# x# y# of
0# -> S# (x# *# y#)
_ -> timesInt2Integer x# y#
timesInteger x@(S# _) y = timesInteger y x
-- no S# as first arg from here on
timesInteger (Jp# x) (Jp# y) = Jp# (timesBigNat x y)
timesInteger (Jp# x) (Jn# y) = Jn# (timesBigNat x y)
timesInteger (Jp# x) (S# y#)
| isTrue# (y# >=# 0#) = Jp# (timesBigNatWord x (int2Word# y#))
| True = Jn# (timesBigNatWord x (int2Word# (negateInt# y#)))
timesInteger (Jn# x) (Jn# y) = Jp# (timesBigNat x y)
timesInteger (Jn# x) (Jp# y) = Jn# (timesBigNat x y)
timesInteger (Jn# x) (S# y#)
| isTrue# (y# >=# 0#) = Jn# (timesBigNatWord x (int2Word# y#))
| True = Jp# (timesBigNatWord x (int2Word# (negateInt# y#)))
{-# CONSTANT_FOLDED timesInteger #-}
-- | Square 'Integer'
sqrInteger :: Integer -> Integer
sqrInteger (S# INT_MINBOUND#) = timesInt2Integer INT_MINBOUND# INT_MINBOUND#
sqrInteger (S# j#) | isTrue# (absI# j# <=# SQRT_INT_MAXBOUND#) = S# (j# *# j#)
sqrInteger (S# j#) = timesInt2Integer j# j#
sqrInteger (Jp# bn) = Jp# (sqrBigNat bn)
sqrInteger (Jn# bn) = Jp# (sqrBigNat bn)
-- | Construct 'Integer' from the product of two 'Int#'s
timesInt2Integer :: Int# -> Int# -> Integer
timesInt2Integer x# y# = case (# isTrue# (x# >=# 0#), isTrue# (y# >=# 0#) #) of
(# False, False #) -> case timesWord2# (int2Word# (negateInt# x#))
(int2Word# (negateInt# y#)) of
(# 0##,l #) -> inline wordToInteger l
(# h ,l #) -> Jp# (wordToBigNat2 h l)
(# True, False #) -> case timesWord2# (int2Word# x#)
(int2Word# (negateInt# y#)) of
(# 0##,l #) -> wordToNegInteger l
(# h ,l #) -> Jn# (wordToBigNat2 h l)
(# False, True #) -> case timesWord2# (int2Word# (negateInt# x#))
(int2Word# y#) of
(# 0##,l #) -> wordToNegInteger l
(# h ,l #) -> Jn# (wordToBigNat2 h l)
(# True, True #) -> case timesWord2# (int2Word# x#)
(int2Word# y#) of
(# 0##,l #) -> inline wordToInteger l
(# h ,l #) -> Jp# (wordToBigNat2 h l)
bigNatToInteger :: BigNat -> Integer
bigNatToInteger bn
| isTrue# ((sizeofBigNat# bn ==# 1#) `andI#` (i# >=# 0#)) = S# i#
| True = Jp# bn
where
i# = word2Int# (bigNatToWord bn)
bigNatToNegInteger :: BigNat -> Integer
bigNatToNegInteger bn
| isTrue# ((sizeofBigNat# bn ==# 1#) `andI#` (i# <=# 0#)) = S# i#
| True = Jn# bn
where
i# = negateInt# (word2Int# (bigNatToWord bn))
-- | Count number of set bits. For negative arguments returns negative
-- population count of negated argument.
popCountInteger :: Integer -> Int#
popCountInteger (S# i#)
| isTrue# (i# >=# 0#) = popCntI# i#
| True = negateInt# (popCntI# (negateInt# i#))
popCountInteger (Jp# bn) = popCountBigNat bn
popCountInteger (Jn# bn) = negateInt# (popCountBigNat bn)
{-# CONSTANT_FOLDED popCountInteger #-}
-- | 'Integer' for which only /n/-th bit is set. Undefined behaviour
-- for negative /n/ values.
bitInteger :: Int# -> Integer
bitInteger i#
| isTrue# (i# <# (GMP_LIMB_BITS# -# 1#)) = S# (uncheckedIShiftL# 1# i#)
| True = Jp# (bitBigNat i#)
{-# CONSTANT_FOLDED bitInteger #-}
-- | Test if /n/-th bit is set.
testBitInteger :: Integer -> Int# -> Bool
testBitInteger _ n# | isTrue# (n# <# 0#) = False
testBitInteger (S# i#) n#
| isTrue# (n# <# GMP_LIMB_BITS#) = isTrue# (((uncheckedIShiftL# 1# n#)
`andI#` i#) /=# 0#)
| True = isTrue# (i# <# 0#)
testBitInteger (Jp# bn) n = testBitBigNat bn n
testBitInteger (Jn# bn) n = testBitNegBigNat bn n
{-# CONSTANT_FOLDED testBitInteger #-}
-- | Bitwise @NOT@ operation
complementInteger :: Integer -> Integer
complementInteger (S# i#) = S# (notI# i#)
complementInteger (Jp# bn) = Jn# (plusBigNatWord bn 1##)
complementInteger (Jn# bn) = Jp# (minusBigNatWord bn 1##)
{-# CONSTANT_FOLDED complementInteger #-}
-- | Arithmetic shift-right operation
--
-- Even though the shift-amount is expressed as `Int#`, the result is
-- undefined for negative shift-amounts.
shiftRInteger :: Integer -> Int# -> Integer
shiftRInteger x 0# = x
shiftRInteger (S# i#) n# = S# (iShiftRA# i# n#)
where
iShiftRA# a b
| isTrue# (b >=# WORD_SIZE_IN_BITS#) = (a <# 0#) *# (-1#)
| True = a `uncheckedIShiftRA#` b
shiftRInteger (Jp# bn) n# = bigNatToInteger (shiftRBigNat bn n#)
shiftRInteger (Jn# bn) n#
= case bigNatToNegInteger (shiftRNegBigNat bn n#) of
S# 0# -> S# -1#
r -> r
{-# CONSTANT_FOLDED shiftRInteger #-}
-- | Shift-left operation
--
-- Even though the shift-amount is expressed as `Int#`, the result is
-- undefined for negative shift-amounts.
shiftLInteger :: Integer -> Int# -> Integer
shiftLInteger x 0# = x
shiftLInteger (S# 0#) _ = S# 0#
shiftLInteger (S# 1#) n# = bitInteger n#
shiftLInteger (S# i#) n#
| isTrue# (i# >=# 0#) = bigNatToInteger (shiftLBigNat
(wordToBigNat (int2Word# i#)) n#)
| True = bigNatToNegInteger (shiftLBigNat
(wordToBigNat (int2Word#
(negateInt# i#))) n#)
shiftLInteger (Jp# bn) n# = Jp# (shiftLBigNat bn n#)
shiftLInteger (Jn# bn) n# = Jn# (shiftLBigNat bn n#)
{-# CONSTANT_FOLDED shiftLInteger #-}
-- | Bitwise OR operation
orInteger :: Integer -> Integer -> Integer
-- short-cuts
orInteger (S# 0#) y = y
orInteger x (S# 0#) = x
orInteger (S# -1#) _ = S# -1#
orInteger _ (S# -1#) = S# -1#
-- base-cases
orInteger (S# x#) (S# y#) = S# (orI# x# y#)
orInteger (Jp# x) (Jp# y) = Jp# (orBigNat x y)
orInteger (Jn# x) (Jn# y)
= bigNatToNegInteger (plusBigNatWord (andBigNat
(minusBigNatWord x 1##)
(minusBigNatWord y 1##)) 1##)
orInteger x@(Jn# _) y@(Jp# _) = orInteger y x -- retry with swapped args
orInteger (Jp# x) (Jn# y)
= bigNatToNegInteger (plusBigNatWord (andnBigNat (minusBigNatWord y 1##) x)
1##)
-- TODO/FIXpromotion-hack
orInteger x@(S# _) y = orInteger (unsafePromote x) y
orInteger x y {- S# -}= orInteger x (unsafePromote y)
{-# CONSTANT_FOLDED orInteger #-}
-- | Bitwise XOR operation
xorInteger :: Integer -> Integer -> Integer
-- short-cuts
xorInteger (S# 0#) y = y
xorInteger x (S# 0#) = x
-- TODO: (S# -1) cases
-- base-cases
xorInteger (S# x#) (S# y#) = S# (xorI# x# y#)
xorInteger (Jp# x) (Jp# y) = bigNatToInteger (xorBigNat x y)
xorInteger (Jn# x) (Jn# y)
= bigNatToInteger (xorBigNat (minusBigNatWord x 1##)
(minusBigNatWord y 1##))
xorInteger x@(Jn# _) y@(Jp# _) = xorInteger y x -- retry with swapped args
xorInteger (Jp# x) (Jn# y)
= bigNatToNegInteger (plusBigNatWord (xorBigNat x (minusBigNatWord y 1##))
1##)
-- TODO/FIXME promotion-hack
xorInteger x@(S# _) y = xorInteger (unsafePromote x) y
xorInteger x y {- S# -} = xorInteger x (unsafePromote y)
{-# CONSTANT_FOLDED xorInteger #-}
-- | Bitwise AND operation
andInteger :: Integer -> Integer -> Integer
-- short-cuts
andInteger (S# 0#) _ = S# 0#
andInteger _ (S# 0#) = S# 0#
andInteger (S# -1#) y = y
andInteger x (S# -1#) = x
-- base-cases
andInteger (S# x#) (S# y#) = S# (andI# x# y#)
andInteger (Jp# x) (Jp# y) = bigNatToInteger (andBigNat x y)
andInteger (Jn# x) (Jn# y)
= bigNatToNegInteger (plusBigNatWord (orBigNat (minusBigNatWord x 1##)
(minusBigNatWord y 1##)) 1##)
andInteger x@(Jn# _) y@(Jp# _) = andInteger y x
andInteger (Jp# x) (Jn# y)
= bigNatToInteger (andnBigNat x (minusBigNatWord y 1##))
-- TODO/FIXME promotion-hack
andInteger x@(S# _) y = andInteger (unsafePromote x) y
andInteger x y {- S# -}= andInteger x (unsafePromote y)
{-# CONSTANT_FOLDED andInteger #-}
-- HACK warning! breaks invariant on purpose
unsafePromote :: Integer -> Integer
unsafePromote (S# x#)
| isTrue# (x# >=# 0#) = Jp# (wordToBigNat (int2Word# x#))
| True = Jn# (wordToBigNat (int2Word# (negateInt# x#)))
unsafePromote x = x
-- | Simultaneous 'quotInteger' and 'remInteger'.
--
-- Divisor must be non-zero otherwise the GHC runtime will terminate
-- with a division-by-zero fault.
quotRemInteger :: Integer -> Integer -> (# Integer, Integer #)
quotRemInteger n (S# 1#) = (# n, S# 0# #)
quotRemInteger n (S# -1#) = let !q = negateInteger n in (# q, (S# 0#) #)
quotRemInteger _ (S# 0#) = (# S# (quotInt# 0# 0#),S# (remInt# 0# 0#) #)
quotRemInteger (S# 0#) _ = (# S# 0#, S# 0# #)
quotRemInteger (S# n#) (S# d#) = case quotRemInt# n# d# of
(# q#, r# #) -> (# S# q#, S# r# #)
quotRemInteger (Jp# n) (Jp# d) = case quotRemBigNat n d of
(# q, r #) -> (# bigNatToInteger q, bigNatToInteger r #)
quotRemInteger (Jp# n) (Jn# d) = case quotRemBigNat n d of
(# q, r #) -> (# bigNatToNegInteger q, bigNatToInteger r #)
quotRemInteger (Jn# n) (Jn# d) = case quotRemBigNat n d of
(# q, r #) -> (# bigNatToInteger q, bigNatToNegInteger r #)
quotRemInteger (Jn# n) (Jp# d) = case quotRemBigNat n d of
(# q, r #) -> (# bigNatToNegInteger q, bigNatToNegInteger r #)
quotRemInteger (Jp# n) (S# d#)
| isTrue# (d# >=# 0#) = case quotRemBigNatWord n (int2Word# d#) of
(# q, r# #) -> (# bigNatToInteger q, inline wordToInteger r# #)
| True = case quotRemBigNatWord n (int2Word# (negateInt# d#)) of
(# q, r# #) -> (# bigNatToNegInteger q, inline wordToInteger r# #)
quotRemInteger (Jn# n) (S# d#)
| isTrue# (d# >=# 0#) = case quotRemBigNatWord n (int2Word# d#) of
(# q, r# #) -> (# bigNatToNegInteger q, wordToNegInteger r# #)
| True = case quotRemBigNatWord n (int2Word# (negateInt# d#)) of
(# q, r# #) -> (# bigNatToInteger q, wordToNegInteger r# #)
quotRemInteger n@(S# _) (Jn# _) = (# S# 0#, n #) -- since @n < d@
quotRemInteger n@(S# n#) (Jp# d) -- need to account for (S# minBound)
| isTrue# (n# ># 0#) = (# S# 0#, n #)
| isTrue# (gtBigNatWord# d (int2Word# (negateInt# n#))) = (# S# 0#, n #)
| True {- abs(n) == d -} = (# S# -1#, S# 0# #)
{-# CONSTANT_FOLDED quotRemInteger #-}
quotInteger :: Integer -> Integer -> Integer
quotInteger n (S# 1#) = n
quotInteger n (S# -1#) = negateInteger n
quotInteger _ (S# 0#) = S# (quotInt# 0# 0#)
quotInteger (S# 0#) _ = S# 0#
quotInteger (S# n#) (S# d#) = S# (quotInt# n# d#)
quotInteger (Jp# n) (S# d#)
| isTrue# (d# >=# 0#) = bigNatToInteger (quotBigNatWord n (int2Word# d#))
| True = bigNatToNegInteger (quotBigNatWord n
(int2Word# (negateInt# d#)))
quotInteger (Jn# n) (S# d#)
| isTrue# (d# >=# 0#) = bigNatToNegInteger (quotBigNatWord n (int2Word# d#))
| True = bigNatToInteger (quotBigNatWord n
(int2Word# (negateInt# d#)))
quotInteger (Jp# n) (Jp# d) = bigNatToInteger (quotBigNat n d)
quotInteger (Jp# n) (Jn# d) = bigNatToNegInteger (quotBigNat n d)
quotInteger (Jn# n) (Jp# d) = bigNatToNegInteger (quotBigNat n d)
quotInteger (Jn# n) (Jn# d) = bigNatToInteger (quotBigNat n d)
-- handle remaining non-allocating cases
quotInteger n d = case inline quotRemInteger n d of (# q, _ #) -> q
{-# CONSTANT_FOLDED quotInteger #-}
remInteger :: Integer -> Integer -> Integer
remInteger _ (S# 1#) = S# 0#
remInteger _ (S# -1#) = S# 0#
remInteger _ (S# 0#) = S# (remInt# 0# 0#)
remInteger (S# 0#) _ = S# 0#
remInteger (S# n#) (S# d#) = S# (remInt# n# d#)
remInteger (Jp# n) (S# d#)
= wordToInteger (remBigNatWord n (int2Word# (absI# d#)))
remInteger (Jn# n) (S# d#)
= wordToNegInteger (remBigNatWord n (int2Word# (absI# d#)))
remInteger (Jp# n) (Jp# d) = bigNatToInteger (remBigNat n d)
remInteger (Jp# n) (Jn# d) = bigNatToInteger (remBigNat n d)
remInteger (Jn# n) (Jp# d) = bigNatToNegInteger (remBigNat n d)
remInteger (Jn# n) (Jn# d) = bigNatToNegInteger (remBigNat n d)
-- handle remaining non-allocating cases
remInteger n d = case inline quotRemInteger n d of (# _, r #) -> r
{-# CONSTANT_FOLDED remInteger #-}
-- | Simultaneous 'divInteger' and 'modInteger'.
--
-- Divisor must be non-zero otherwise the GHC runtime will terminate
-- with a division-by-zero fault.
divModInteger :: Integer -> Integer -> (# Integer, Integer #)
divModInteger n d
| isTrue# (signumInteger# r ==# negateInt# (signumInteger# d))
= let !q' = plusInteger q (S# -1#) -- TODO: optimize
!r' = plusInteger r d
in (# q', r' #)
| True = qr
where
qr@(# q, r #) = quotRemInteger n d
{-# CONSTANT_FOLDED divModInteger #-}
divInteger :: Integer -> Integer -> Integer
-- same-sign ops can be handled by more efficient 'quotInteger'
divInteger n d | isTrue# (isNegInteger# n ==# isNegInteger# d) = quotInteger n d
divInteger n d = case inline divModInteger n d of (# q, _ #) -> q
{-# CONSTANT_FOLDED divInteger #-}
modInteger :: Integer -> Integer -> Integer
-- same-sign ops can be handled by more efficient 'remInteger'
modInteger n d | isTrue# (isNegInteger# n ==# isNegInteger# d) = remInteger n d
modInteger n d = case inline divModInteger n d of (# _, r #) -> r
{-# CONSTANT_FOLDED modInteger #-}
-- | Compute greatest common divisor.
gcdInteger :: Integer -> Integer -> Integer
gcdInteger (S# 0#) b = absInteger b
gcdInteger a (S# 0#) = absInteger a
gcdInteger (S# 1#) _ = S# 1#
gcdInteger (S# -1#) _ = S# 1#
gcdInteger _ (S# 1#) = S# 1#
gcdInteger _ (S# -1#) = S# 1#
gcdInteger (S# a#) (S# b#)
= wordToInteger (gcdWord# (int2Word# (absI# a#)) (int2Word# (absI# b#)))
gcdInteger a@(S# _) b = gcdInteger b a
gcdInteger (Jn# a) b = gcdInteger (Jp# a) b
gcdInteger (Jp# a) (Jp# b) = bigNatToInteger (gcdBigNat a b)
gcdInteger (Jp# a) (Jn# b) = bigNatToInteger (gcdBigNat a b)
gcdInteger (Jp# a) (S# b#)
= wordToInteger (gcdBigNatWord a (int2Word# (absI# b#)))
{-# CONSTANT_FOLDED gcdInteger #-}
-- | Compute least common multiple.
lcmInteger :: Integer -> Integer -> Integer
lcmInteger (S# 0#) _ = S# 0#
lcmInteger (S# 1#) b = absInteger b
lcmInteger (S# -1#) b = absInteger b
lcmInteger _ (S# 0#) = S# 0#
lcmInteger a (S# 1#) = absInteger a
lcmInteger a (S# -1#) = absInteger a
lcmInteger a b = (aa `quotInteger` (aa `gcdInteger` ab)) `timesInteger` ab
where
aa = absInteger a
ab = absInteger b
{-# CONSTANT_FOLDED lcmInteger #-}
-- | Compute greatest common divisor.
--
-- __Warning__: result may become negative if (at least) one argument
-- is 'minBound'
gcdInt :: Int# -> Int# -> Int#
gcdInt x# y#
= word2Int# (gcdWord# (int2Word# (absI# x#)) (int2Word# (absI# y#)))
-- | Compute greatest common divisor.
--
-- @since 1.0.0.0
gcdWord :: Word# -> Word# -> Word#
gcdWord = gcdWord#
----------------------------------------------------------------------------
-- BigNat operations
compareBigNat :: BigNat -> BigNat -> Ordering
compareBigNat x@(BN# x#) y@(BN# y#)
| isTrue# (nx# ==# ny#)
= compareInt# (narrowCInt# (c_mpn_cmp x# y# nx#)) 0#
| isTrue# (nx# <# ny#) = LT
| True = GT
where
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
compareBigNatWord :: BigNat -> GmpLimb# -> Ordering
compareBigNatWord bn w#
| isTrue# (sizeofBigNat# bn ==# 1#) = cmpW# (bigNatToWord bn) w#
| True = GT
gtBigNatWord# :: BigNat -> GmpLimb# -> Int#
gtBigNatWord# bn w#
= (sizeofBigNat# bn ># 1#) `orI#` (bigNatToWord bn `gtWord#` w#)
eqBigNat :: BigNat -> BigNat -> Bool
eqBigNat x y = isTrue# (eqBigNat# x y)
eqBigNat# :: BigNat -> BigNat -> Int#
eqBigNat# x@(BN# x#) y@(BN# y#)
| isTrue# (nx# ==# ny#) = c_mpn_cmp x# y# nx# ==# 0#
| True = 0#
where
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
neqBigNat# :: BigNat -> BigNat -> Int#
neqBigNat# x@(BN# x#) y@(BN# y#)
| isTrue# (nx# ==# ny#) = c_mpn_cmp x# y# nx# /=# 0#
| True = 1#
where
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
eqBigNatWord :: BigNat -> GmpLimb# -> Bool
eqBigNatWord bn w# = isTrue# (eqBigNatWord# bn w#)
eqBigNatWord# :: BigNat -> GmpLimb# -> Int#
eqBigNatWord# bn w#
= (sizeofBigNat# bn ==# 1#) `andI#` (bigNatToWord bn `eqWord#` w#)
-- | Same as @'indexBigNat#' bn 0\#@
bigNatToWord :: BigNat -> Word#
bigNatToWord bn = indexBigNat# bn 0#
-- | Equivalent to @'word2Int#' . 'bigNatToWord'@
bigNatToInt :: BigNat -> Int#
bigNatToInt (BN# ba#) = indexIntArray# ba# 0#
-- | CAF representing the value @0 :: BigNat@
zeroBigNat :: BigNat
zeroBigNat = runS $ do
mbn <- newBigNat# 1#
_ <- svoid (writeBigNat# mbn 0# 0##)
unsafeFreezeBigNat# mbn
{-# NOINLINE zeroBigNat #-}
-- | Test if 'BigNat' value is equal to zero.
isZeroBigNat :: BigNat -> Bool
isZeroBigNat bn = eqBigNatWord bn 0##
-- | CAF representing the value @1 :: BigNat@
oneBigNat :: BigNat
oneBigNat = runS $ do
mbn <- newBigNat# 1#
_ <- svoid (writeBigNat# mbn 0# 1##)
unsafeFreezeBigNat# mbn
{-# NOINLINE oneBigNat #-}
czeroBigNat :: BigNat
czeroBigNat = runS $ do
mbn <- newBigNat# 1#
_ <- svoid (writeBigNat# mbn 0# (not# 0##))
unsafeFreezeBigNat# mbn
{-# NOINLINE czeroBigNat #-}
-- | Special 0-sized bigNat returned in case of arithmetic underflow
--
-- This is currently only returned by the following operations:
--
-- - 'minusBigNat'
-- - 'minusBigNatWord'
--
-- Other operations such as 'quotBigNat' may return 'nullBigNat' as
-- well as a dummy/place-holder value instead of 'undefined' since we
-- can't throw exceptions. But that behaviour should not be relied
-- upon.
--
-- NB: @isValidBigNat# nullBigNat@ is false
nullBigNat :: BigNat
nullBigNat = runS (newBigNat# 0# >>= unsafeFreezeBigNat#)
{-# NOINLINE nullBigNat #-}
-- | Test for special 0-sized 'BigNat' representing underflows.
isNullBigNat# :: BigNat -> Int#
isNullBigNat# (BN# ba#) = sizeofByteArray# ba# ==# 0#
-- | Construct 1-limb 'BigNat' from 'Word#'
wordToBigNat :: Word# -> BigNat
wordToBigNat 0## = zeroBigNat
wordToBigNat 1## = oneBigNat
wordToBigNat w#
| isTrue# (not# w# `eqWord#` 0##) = czeroBigNat
| True = runS $ do
mbn <- newBigNat# 1#
_ <- svoid (writeBigNat# mbn 0# w#)
unsafeFreezeBigNat# mbn
-- | Construct BigNat from 2 limbs.
-- The first argument is the most-significant limb.
wordToBigNat2 :: Word# -> Word# -> BigNat
wordToBigNat2 0## lw# = wordToBigNat lw#
wordToBigNat2 hw# lw# = runS $ do
mbn <- newBigNat# 2#
_ <- svoid (writeBigNat# mbn 0# lw#)
_ <- svoid (writeBigNat# mbn 1# hw#)
unsafeFreezeBigNat# mbn
plusBigNat :: BigNat -> BigNat -> BigNat
plusBigNat x y
| isTrue# (eqBigNatWord# x 0##) = y
| isTrue# (eqBigNatWord# y 0##) = x
| isTrue# (nx# >=# ny#) = go x nx# y ny#
| True = go y ny# x nx#
where
go (BN# a#) na# (BN# b#) nb# = runS $ do
mbn@(MBN# mba#) <- newBigNat# na#
(W# c#) <- liftIO (c_mpn_add mba# a# na# b# nb#)
case c# of
0## -> unsafeFreezeBigNat# mbn
_ -> unsafeSnocFreezeBigNat# mbn c#
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
plusBigNatWord :: BigNat -> GmpLimb# -> BigNat
plusBigNatWord x 0## = x
plusBigNatWord x@(BN# x#) y# = runS $ do
mbn@(MBN# mba#) <- newBigNat# nx#
(W# c#) <- liftIO (c_mpn_add_1 mba# x# nx# y#)
case c# of
0## -> unsafeFreezeBigNat# mbn
_ -> unsafeSnocFreezeBigNat# mbn c#
where
nx# = sizeofBigNat# x
-- | Returns 'nullBigNat' (see 'isNullBigNat#') in case of underflow
minusBigNat :: BigNat -> BigNat -> BigNat
minusBigNat x@(BN# x#) y@(BN# y#)
| isZeroBigNat y = x
| isTrue# (nx# >=# ny#) = runS $ do
mbn@(MBN# mba#) <- newBigNat# nx#
(W# b#) <- liftIO (c_mpn_sub mba# x# nx# y# ny#)
case b# of
0## -> unsafeRenormFreezeBigNat# mbn
_ -> return nullBigNat
| True = nullBigNat
where
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
-- | Returns 'nullBigNat' (see 'isNullBigNat#') in case of underflow
minusBigNatWord :: BigNat -> GmpLimb# -> BigNat
minusBigNatWord x 0## = x
minusBigNatWord x@(BN# x#) y# = runS $ do
mbn@(MBN# mba#) <- newBigNat# nx#
(W# b#) <- liftIO $ c_mpn_sub_1 mba# x# nx# y#
case b# of
0## -> unsafeRenormFreezeBigNat# mbn
_ -> return nullBigNat
where
nx# = sizeofBigNat# x
timesBigNat :: BigNat -> BigNat -> BigNat
timesBigNat x y
| isZeroBigNat x = zeroBigNat
| isZeroBigNat y = zeroBigNat
| isTrue# (nx# >=# ny#) = go x nx# y ny#
| True = go y ny# x nx#
where
go (BN# a#) na# (BN# b#) nb# = runS $ do
let n# = nx# +# ny#
mbn@(MBN# mba#) <- newBigNat# n#
(W# msl#) <- liftIO (c_mpn_mul mba# a# na# b# nb#)
case msl# of
0## -> unsafeShrinkFreezeBigNat# mbn (n# -# 1#)
_ -> unsafeFreezeBigNat# mbn
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
-- | Square 'BigNat'
sqrBigNat :: BigNat -> BigNat
sqrBigNat x
| isZeroBigNat x = zeroBigNat
-- TODO: 1-limb BigNats below sqrt(maxBound::GmpLimb)
sqrBigNat x = timesBigNat x x -- TODO: mpn_sqr
timesBigNatWord :: BigNat -> GmpLimb# -> BigNat
timesBigNatWord _ 0## = zeroBigNat
timesBigNatWord x 1## = x
timesBigNatWord x@(BN# x#) y#
| isTrue# (nx# ==# 1#) =
let (# !h#, !l# #) = timesWord2# (bigNatToWord x) y#
in wordToBigNat2 h# l#
| True = runS $ do
mbn@(MBN# mba#) <- newBigNat# nx#
(W# msl#) <- liftIO (c_mpn_mul_1 mba# x# nx# y#)
case msl# of
0## -> unsafeFreezeBigNat# mbn
_ -> unsafeSnocFreezeBigNat# mbn msl#
where
nx# = sizeofBigNat# x
bitBigNat :: Int# -> BigNat
bitBigNat i# = shiftLBigNat (wordToBigNat 1##) i# -- FIXME
testBitBigNat :: BigNat -> Int# -> Bool
testBitBigNat bn i#
| isTrue# (i# <# 0#) = False
| isTrue# (li# <# nx#) = isTrue# (testBitWord# (indexBigNat# bn li#) bi#)
| True = False
where
(# li#, bi# #) = quotRemInt# i# GMP_LIMB_BITS#
nx# = sizeofBigNat# bn
testBitNegBigNat :: BigNat -> Int# -> Bool
testBitNegBigNat bn i#
| isTrue# (i# <# 0#) = False
| isTrue# (li# >=# nx#) = True
| allZ li# = isTrue# ((testBitWord#
(indexBigNat# bn li# `minusWord#` 1##) bi#) ==# 0#)
| True = isTrue# ((testBitWord# (indexBigNat# bn li#) bi#) ==# 0#)
where
(# li#, bi# #) = quotRemInt# i# GMP_LIMB_BITS#
nx# = sizeofBigNat# bn
allZ 0# = True
allZ j | isTrue# (indexBigNat# bn (j -# 1#) `eqWord#` 0##) = allZ (j -# 1#)
| True = False
popCountBigNat :: BigNat -> Int#
popCountBigNat bn@(BN# ba#) = word2Int# (c_mpn_popcount ba# (sizeofBigNat# bn))
shiftLBigNat :: BigNat -> Int# -> BigNat
shiftLBigNat x 0# = x
shiftLBigNat x _ | isZeroBigNat x = zeroBigNat
shiftLBigNat x@(BN# xba#) n# = runS $ do
ymbn@(MBN# ymba#) <- newBigNat# yn#
W# ymsl <- liftIO (c_mpn_lshift ymba# xba# xn# (int2Word# n#))
case ymsl of
0## -> unsafeShrinkFreezeBigNat# ymbn (yn# -# 1#)
_ -> unsafeFreezeBigNat# ymbn
where
xn# = sizeofBigNat# x
yn# = xn# +# nlimbs# +# (nbits# /=# 0#)
(# nlimbs#, nbits# #) = quotRemInt# n# GMP_LIMB_BITS#
shiftRBigNat :: BigNat -> Int# -> BigNat
shiftRBigNat x 0# = x
shiftRBigNat x _ | isZeroBigNat x = zeroBigNat
shiftRBigNat x@(BN# xba#) n#
| isTrue# (nlimbs# >=# xn#) = zeroBigNat
| True = runS $ do
ymbn@(MBN# ymba#) <- newBigNat# yn#
W# ymsl <- liftIO (c_mpn_rshift ymba# xba# xn# (int2Word# n#))
case ymsl of
0## -> unsafeRenormFreezeBigNat# ymbn -- may shrink more than one
_ -> unsafeFreezeBigNat# ymbn
where
xn# = sizeofBigNat# x
yn# = xn# -# nlimbs#
nlimbs# = quotInt# n# GMP_LIMB_BITS#
shiftRNegBigNat :: BigNat -> Int# -> BigNat
shiftRNegBigNat x 0# = x
shiftRNegBigNat x _ | isZeroBigNat x = zeroBigNat
shiftRNegBigNat x@(BN# xba#) n#
| isTrue# (nlimbs# >=# xn#) = zeroBigNat
| True = runS $ do
ymbn@(MBN# ymba#) <- newBigNat# yn#
W# ymsl <- liftIO (c_mpn_rshift_2c ymba# xba# xn# (int2Word# n#))
case ymsl of
0## -> unsafeRenormFreezeBigNat# ymbn -- may shrink more than one
_ -> unsafeFreezeBigNat# ymbn
where
xn# = sizeofBigNat# x
yn# = xn# -# nlimbs#
nlimbs# = quotInt# n# GMP_LIMB_BITS#
orBigNat :: BigNat -> BigNat -> BigNat
orBigNat x@(BN# x#) y@(BN# y#)
| isZeroBigNat x = y
| isZeroBigNat y = x
| isTrue# (nx# >=# ny#) = runS (ior' x# nx# y# ny#)
| True = runS (ior' y# ny# x# nx#)
where
ior' a# na# b# nb# = do -- na >= nb
mbn@(MBN# mba#) <- newBigNat# na#
_ <- liftIO (c_mpn_ior_n mba# a# b# nb#)
_ <- case isTrue# (na# ==# nb#) of
False -> svoid (copyWordArray# a# nb# mba# nb# (na# -# nb#))
True -> return ()
unsafeFreezeBigNat# mbn
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
xorBigNat :: BigNat -> BigNat -> BigNat
xorBigNat x@(BN# x#) y@(BN# y#)
| isZeroBigNat x = y
| isZeroBigNat y = x
| isTrue# (nx# >=# ny#) = runS (xor' x# nx# y# ny#)
| True = runS (xor' y# ny# x# nx#)
where
xor' a# na# b# nb# = do -- na >= nb
mbn@(MBN# mba#) <- newBigNat# na#
_ <- liftIO (c_mpn_xor_n mba# a# b# nb#)
case isTrue# (na# ==# nb#) of
False -> do _ <- svoid (copyWordArray# a# nb# mba# nb# (na# -# nb#))
unsafeFreezeBigNat# mbn
True -> unsafeRenormFreezeBigNat# mbn
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
-- | aka @\x y -> x .&. (complement y)@
andnBigNat :: BigNat -> BigNat -> BigNat
andnBigNat x@(BN# x#) y@(BN# y#)
| isZeroBigNat x = zeroBigNat
| isZeroBigNat y = x
| True = runS $ do
mbn@(MBN# mba#) <- newBigNat# nx#
_ <- liftIO (c_mpn_andn_n mba# x# y# n#)
_ <- case isTrue# (nx# ==# n#) of
False -> svoid (copyWordArray# x# n# mba# n# (nx# -# n#))
True -> return ()
unsafeRenormFreezeBigNat# mbn
where
n# | isTrue# (nx# <# ny#) = nx#
| True = ny#
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
andBigNat :: BigNat -> BigNat -> BigNat
andBigNat x@(BN# x#) y@(BN# y#)
| isZeroBigNat x = zeroBigNat
| isZeroBigNat y = zeroBigNat
| True = runS $ do
mbn@(MBN# mba#) <- newBigNat# n#
_ <- liftIO (c_mpn_and_n mba# x# y# n#)
unsafeRenormFreezeBigNat# mbn
where
n# | isTrue# (nx# <# ny#) = nx#
| True = ny#
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
-- | If divisor is zero, @(\# 'nullBigNat', 'nullBigNat' \#)@ is returned
quotRemBigNat :: BigNat -> BigNat -> (# BigNat,BigNat #)
quotRemBigNat n@(BN# nba#) d@(BN# dba#)
| isZeroBigNat d = (# nullBigNat, nullBigNat #)
| eqBigNatWord d 1## = (# n, zeroBigNat #)
| n < d = (# zeroBigNat, n #)
| True = case runS go of (!q,!r) -> (# q, r #)
where
nn# = sizeofBigNat# n
dn# = sizeofBigNat# d
qn# = 1# +# nn# -# dn#
rn# = dn#
go = do
qmbn@(MBN# qmba#) <- newBigNat# qn#
rmbn@(MBN# rmba#) <- newBigNat# rn#
_ <- liftIO (c_mpn_tdiv_qr qmba# rmba# 0# nba# nn# dba# dn#)
q <- unsafeRenormFreezeBigNat# qmbn
r <- unsafeRenormFreezeBigNat# rmbn
return (q, r)
quotBigNat :: BigNat -> BigNat -> BigNat
quotBigNat n@(BN# nba#) d@(BN# dba#)
| isZeroBigNat d = nullBigNat
| eqBigNatWord d 1## = n
| n < d = zeroBigNat
| True = runS $ do
let nn# = sizeofBigNat# n
let dn# = sizeofBigNat# d
let qn# = 1# +# nn# -# dn#
qmbn@(MBN# qmba#) <- newBigNat# qn#
_ <- liftIO (c_mpn_tdiv_q qmba# nba# nn# dba# dn#)
unsafeRenormFreezeBigNat# qmbn
remBigNat :: BigNat -> BigNat -> BigNat
remBigNat n@(BN# nba#) d@(BN# dba#)
| isZeroBigNat d = nullBigNat
| eqBigNatWord d 1## = zeroBigNat
| n < d = n
| True = runS $ do
let nn# = sizeofBigNat# n
let dn# = sizeofBigNat# d
rmbn@(MBN# rmba#) <- newBigNat# dn#
_ <- liftIO (c_mpn_tdiv_r rmba# nba# nn# dba# dn#)
unsafeRenormFreezeBigNat# rmbn
-- | Note: Result of div/0 undefined
quotRemBigNatWord :: BigNat -> GmpLimb# -> (# BigNat, GmpLimb# #)
quotRemBigNatWord _ 0## = (# nullBigNat, 0## #)
quotRemBigNatWord n 1## = (# n, 0## #)
quotRemBigNatWord n@(BN# nba#) d# = case compareBigNatWord n d# of
LT -> (# zeroBigNat, bigNatToWord n #)
EQ -> (# oneBigNat, 0## #)
GT -> case runS go of (!q,!(W# r#)) -> (# q, r# #) -- TODO: handle word/word
where
go = do
let nn# = sizeofBigNat# n
qmbn@(MBN# qmba#) <- newBigNat# nn#
r <- liftIO (c_mpn_divrem_1 qmba# 0# nba# nn# d#)
q <- unsafeRenormFreezeBigNat# qmbn
return (q,r)
quotBigNatWord :: BigNat -> GmpLimb# -> BigNat
quotBigNatWord n d# = case inline quotRemBigNatWord n d# of (# q, _ #) -> q
-- | div/0 not checked
remBigNatWord :: BigNat -> GmpLimb# -> Word#
remBigNatWord n@(BN# nba#) d# = c_mpn_mod_1 nba# (sizeofBigNat# n) d#
gcdBigNatWord :: BigNat -> Word# -> Word#
gcdBigNatWord bn@(BN# ba#) = c_mpn_gcd_1# ba# (sizeofBigNat# bn)
gcdBigNat :: BigNat -> BigNat -> BigNat
gcdBigNat x@(BN# x#) y@(BN# y#)
| isZeroBigNat x = y
| isZeroBigNat y = x
| isTrue# (nx# >=# ny#) = runS (gcd' x# nx# y# ny#)
| True = runS (gcd' y# ny# x# nx#)
where
gcd' a# na# b# nb# = do -- na >= nb
mbn@(MBN# mba#) <- newBigNat# nb#
I# rn'# <- liftIO (c_mpn_gcd# mba# a# na# b# nb#)
let rn# = narrowGmpSize# rn'#
case isTrue# (rn# ==# nb#) of
False -> unsafeShrinkFreezeBigNat# mbn rn#
True -> unsafeFreezeBigNat# mbn
nx# = sizeofBigNat# x
ny# = sizeofBigNat# y
-- | Extended euclidean algorithm.
--
-- For @/a/@ and @/b/@, compute their greatest common divisor @/g/@
-- and the coefficient @/s/@ satisfying @/a//s/ + /b//t/ = /g/@.
--
-- @since 0.5.1.0
{-# NOINLINE gcdExtInteger #-}
gcdExtInteger :: Integer -> Integer -> (# Integer, Integer #)
gcdExtInteger a b = case gcdExtSBigNat a' b' of
(# g, s #) -> let !g' = bigNatToInteger g
!s' = sBigNatToInteger s
in (# g', s' #)
where
a' = integerToSBigNat a
b' = integerToSBigNat b
-- internal helper
gcdExtSBigNat :: SBigNat -> SBigNat -> (# BigNat, SBigNat #)
gcdExtSBigNat x y = case runS go of (g,s) -> (# g, s #)
where
go = do
g@(MBN# g#) <- newBigNat# gn0#
s@(MBN# s#) <- newBigNat# (absI# xn#)
I# ssn_# <- liftIO (integer_gmp_gcdext# s# g# x# xn# y# yn#)
let ssn# = narrowGmpSize# ssn_#
sn# = absI# ssn#
s' <- unsafeShrinkFreezeBigNat# s sn#
g' <- unsafeRenormFreezeBigNat# g
case isTrue# (ssn# >=# 0#) of
False -> return ( g', NegBN s' )
True -> return ( g', PosBN s' )
!(BN# x#) = absSBigNat x
!(BN# y#) = absSBigNat y
xn# = ssizeofSBigNat# x
yn# = ssizeofSBigNat# y
gn0# = minI# (absI# xn#) (absI# yn#)
----------------------------------------------------------------------------
-- modular exponentiation
-- | \"@'powModInteger' /b/ /e/ /m/@\" computes base @/b/@ raised to
-- exponent @/e/@ modulo @abs(/m/)@.
--
-- Negative exponents are supported if an inverse modulo @/m/@
-- exists.
--
-- __Warning__: It's advised to avoid calling this primitive with
-- negative exponents unless it is guaranteed the inverse exists, as
-- failure to do so will likely cause program abortion due to a
-- divide-by-zero fault. See also 'recipModInteger'.
--
-- Future versions of @integer_gmp@ may not support negative @/e/@
-- values anymore.
--
-- @since 0.5.1.0
{-# NOINLINE powModInteger #-}
powModInteger :: Integer -> Integer -> Integer -> Integer
powModInteger (S# b#) (S# e#) (S# m#)
| isTrue# (b# >=# 0#), isTrue# (e# >=# 0#)
= wordToInteger (powModWord (int2Word# b#) (int2Word# e#)
(int2Word# (absI# m#)))
powModInteger b e m = case m of
(S# m#) -> wordToInteger (powModSBigNatWord b' e' (int2Word# (absI# m#)))
(Jp# m') -> bigNatToInteger (powModSBigNat b' e' m')
(Jn# m') -> bigNatToInteger (powModSBigNat b' e' m')
where
b' = integerToSBigNat b
e' = integerToSBigNat e
-- | Version of 'powModInteger' operating on 'BigNat's
--
-- @since 1.0.0.0
powModBigNat :: BigNat -> BigNat -> BigNat -> BigNat
powModBigNat b e m = inline powModSBigNat (PosBN b) (PosBN e) m
-- | Version of 'powModInteger' for 'Word#'-sized moduli
--
-- @since 1.0.0.0
powModBigNatWord :: BigNat -> BigNat -> GmpLimb# -> GmpLimb#
powModBigNatWord b e m# = inline powModSBigNatWord (PosBN b) (PosBN e) m#
-- | Version of 'powModInteger' operating on 'Word#'s
--
-- @since 1.0.0.0
foreign import ccall unsafe "integer_gmp_powm_word"
powModWord :: GmpLimb# -> GmpLimb# -> GmpLimb# -> GmpLimb#
-- internal non-exported helper
powModSBigNat :: SBigNat -> SBigNat -> BigNat -> BigNat
powModSBigNat b e m@(BN# m#) = runS $ do
r@(MBN# r#) <- newBigNat# mn#
I# rn_# <- liftIO (integer_gmp_powm# r# b# bn# e# en# m# mn#)
let rn# = narrowGmpSize# rn_#
case isTrue# (rn# ==# mn#) of
False -> unsafeShrinkFreezeBigNat# r rn#
True -> unsafeFreezeBigNat# r
where
!(BN# b#) = absSBigNat b
!(BN# e#) = absSBigNat e
bn# = ssizeofSBigNat# b
en# = ssizeofSBigNat# e
mn# = sizeofBigNat# m
foreign import ccall unsafe "integer_gmp_powm"
integer_gmp_powm# :: MutableByteArray# RealWorld
-> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize#
-> ByteArray# -> GmpSize# -> IO GmpSize
-- internal non-exported helper
powModSBigNatWord :: SBigNat -> SBigNat -> GmpLimb# -> GmpLimb#
powModSBigNatWord b e m# = integer_gmp_powm1# b# bn# e# en# m#
where
!(BN# b#) = absSBigNat b
!(BN# e#) = absSBigNat e
bn# = ssizeofSBigNat# b
en# = ssizeofSBigNat# e
foreign import ccall unsafe "integer_gmp_powm1"
integer_gmp_powm1# :: ByteArray# -> GmpSize# -> ByteArray# -> GmpSize#
-> GmpLimb# -> GmpLimb#
-- | \"@'recipModInteger' /x/ /m/@\" computes the inverse of @/x/@ modulo @/m/@. If
-- the inverse exists, the return value @/y/@ will satisfy @0 < /y/ <
-- abs(/m/)@, otherwise the result is @0@.
--
-- @since 0.5.1.0
{-# NOINLINE recipModInteger #-}
recipModInteger :: Integer -> Integer -> Integer
recipModInteger (S# x#) (S# m#)
| isTrue# (x# >=# 0#)
= wordToInteger (recipModWord (int2Word# x#) (int2Word# (absI# m#)))
recipModInteger x m = bigNatToInteger (recipModSBigNat x' m')
where
x' = integerToSBigNat x
m' = absSBigNat (integerToSBigNat m)
-- | Version of 'recipModInteger' operating on 'BigNat's
--
-- @since 1.0.0.0
recipModBigNat :: BigNat -> BigNat -> BigNat
recipModBigNat x m = inline recipModSBigNat (PosBN x) m
-- | Version of 'recipModInteger' operating on 'Word#'s
--
-- @since 1.0.0.0
foreign import ccall unsafe "integer_gmp_invert_word"
recipModWord :: GmpLimb# -> GmpLimb# -> GmpLimb#
-- internal non-exported helper
recipModSBigNat :: SBigNat -> BigNat -> BigNat
recipModSBigNat x m@(BN# m#) = runS $ do
r@(MBN# r#) <- newBigNat# mn#
I# rn_# <- liftIO (integer_gmp_invert# r# x# xn# m# mn#)
let rn# = narrowGmpSize# rn_#
case isTrue# (rn# ==# mn#) of
False -> unsafeShrinkFreezeBigNat# r rn#
True -> unsafeFreezeBigNat# r
where
!(BN# x#) = absSBigNat x
xn# = ssizeofSBigNat# x
mn# = sizeofBigNat# m
foreign import ccall unsafe "integer_gmp_invert"
integer_gmp_invert# :: MutableByteArray# RealWorld
-> ByteArray# -> GmpSize#
-> ByteArray# -> GmpSize# -> IO GmpSize
----------------------------------------------------------------------------
-- Conversions to/from floating point
decodeDoubleInteger :: Double# -> (# Integer, Int# #)
-- decodeDoubleInteger 0.0## = (# S# 0#, 0# #)
#if WORD_SIZE_IN_BITS == 64
decodeDoubleInteger x = case decodeDouble_Int64# x of
(# m#, e# #) -> (# S# m#, e# #)
#elif WORD_SIZE_IN_BITS == 32
decodeDoubleInteger x = case decodeDouble_Int64# x of
(# m#, e# #) -> (# int64ToInteger m#, e# #)
#endif
{-# CONSTANT_FOLDED decodeDoubleInteger #-}
-- provided by GHC's RTS
foreign import ccall unsafe "__int_encodeDouble"
int_encodeDouble# :: Int# -> Int# -> Double#
encodeDoubleInteger :: Integer -> Int# -> Double#
encodeDoubleInteger (S# m#) 0# = int2Double# m#
encodeDoubleInteger (S# m#) e# = int_encodeDouble# m# e#
encodeDoubleInteger (Jp# bn@(BN# bn#)) e#
= c_mpn_get_d bn# (sizeofBigNat# bn) e#
encodeDoubleInteger (Jn# bn@(BN# bn#)) e#
= c_mpn_get_d bn# (negateInt# (sizeofBigNat# bn)) e#
{-# CONSTANT_FOLDED encodeDoubleInteger #-}
-- double integer_gmp_mpn_get_d (const mp_limb_t sp[], const mp_size_t sn)
foreign import ccall unsafe "integer_gmp_mpn_get_d"
c_mpn_get_d :: ByteArray# -> GmpSize# -> Int# -> Double#
doubleFromInteger :: Integer -> Double#
doubleFromInteger (S# m#) = int2Double# m#
doubleFromInteger (Jp# bn@(BN# bn#))
= c_mpn_get_d bn# (sizeofBigNat# bn) 0#
doubleFromInteger (Jn# bn@(BN# bn#))
= c_mpn_get_d bn# (negateInt# (sizeofBigNat# bn)) 0#
{-# CONSTANT_FOLDED doubleFromInteger #-}
-- TODO: Not sure if it's worth to write 'Float' optimized versions here
floatFromInteger :: Integer -> Float#
floatFromInteger i = double2Float# (doubleFromInteger i)
encodeFloatInteger :: Integer -> Int# -> Float#
encodeFloatInteger m e = double2Float# (encodeDoubleInteger m e)
----------------------------------------------------------------------------
-- FFI ccall imports
foreign import ccall unsafe "integer_gmp_gcd_word"
gcdWord# :: GmpLimb# -> GmpLimb# -> GmpLimb#
foreign import ccall unsafe "integer_gmp_mpn_gcd_1"
c_mpn_gcd_1# :: ByteArray# -> GmpSize# -> GmpLimb# -> GmpLimb#
foreign import ccall unsafe "integer_gmp_mpn_gcd"
c_mpn_gcd# :: MutableByteArray# s -> ByteArray# -> GmpSize#
-> ByteArray# -> GmpSize# -> IO GmpSize
foreign import ccall unsafe "integer_gmp_gcdext"
integer_gmp_gcdext# :: MutableByteArray# s -> MutableByteArray# s
-> ByteArray# -> GmpSize#
-> ByteArray# -> GmpSize# -> IO GmpSize
-- mp_limb_t mpn_add_1 (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t n,
-- mp_limb_t s2limb)
foreign import ccall unsafe "gmp.h __gmpn_add_1"
c_mpn_add_1 :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpLimb#
-> IO GmpLimb
-- mp_limb_t mpn_sub_1 (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t n,
-- mp_limb_t s2limb)
foreign import ccall unsafe "gmp.h __gmpn_sub_1"
c_mpn_sub_1 :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpLimb#
-> IO GmpLimb
-- mp_limb_t mpn_mul_1 (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t n,
-- mp_limb_t s2limb)
foreign import ccall unsafe "gmp.h __gmpn_mul_1"
c_mpn_mul_1 :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpLimb#
-> IO GmpLimb
-- mp_limb_t mpn_add (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t s1n,
-- const mp_limb_t *s2p, mp_size_t s2n)
foreign import ccall unsafe "gmp.h __gmpn_add"
c_mpn_add :: MutableByteArray# s -> ByteArray# -> GmpSize#
-> ByteArray# -> GmpSize# -> IO GmpLimb
-- mp_limb_t mpn_sub (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t s1n,
-- const mp_limb_t *s2p, mp_size_t s2n)
foreign import ccall unsafe "gmp.h __gmpn_sub"
c_mpn_sub :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray#
-> GmpSize# -> IO GmpLimb
-- mp_limb_t mpn_mul (mp_limb_t *rp, const mp_limb_t *s1p, mp_size_t s1n,
-- const mp_limb_t *s2p, mp_size_t s2n)
foreign import ccall unsafe "gmp.h __gmpn_mul"
c_mpn_mul :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray#
-> GmpSize# -> IO GmpLimb
-- int mpn_cmp (const mp_limb_t *s1p, const mp_limb_t *s2p, mp_size_t n)
foreign import ccall unsafe "gmp.h __gmpn_cmp"
c_mpn_cmp :: ByteArray# -> ByteArray# -> GmpSize# -> CInt#
-- void mpn_tdiv_qr (mp_limb_t *qp, mp_limb_t *rp, mp_size_t qxn,
-- const mp_limb_t *np, mp_size_t nn,
-- const mp_limb_t *dp, mp_size_t dn)
foreign import ccall unsafe "gmp.h __gmpn_tdiv_qr"
c_mpn_tdiv_qr :: MutableByteArray# s -> MutableByteArray# s -> GmpSize#
-> ByteArray# -> GmpSize# -> ByteArray# -> GmpSize# -> IO ()
foreign import ccall unsafe "integer_gmp_mpn_tdiv_q"
c_mpn_tdiv_q :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray#
-> GmpSize# -> IO ()
foreign import ccall unsafe "integer_gmp_mpn_tdiv_r"
c_mpn_tdiv_r :: MutableByteArray# s -> ByteArray# -> GmpSize# -> ByteArray#
-> GmpSize# -> IO ()
-- mp_limb_t mpn_divrem_1 (mp_limb_t *r1p, mp_size_t qxn, mp_limb_t *s2p,
-- mp_size_t s2n, mp_limb_t s3limb)
foreign import ccall unsafe "gmp.h __gmpn_divrem_1"
c_mpn_divrem_1 :: MutableByteArray# s -> GmpSize# -> ByteArray# -> GmpSize#
-> GmpLimb# -> IO GmpLimb
-- mp_limb_t mpn_mod_1 (const mp_limb_t *s1p, mp_size_t s1n, mp_limb_t s2limb)
foreign import ccall unsafe "gmp.h __gmpn_mod_1"
c_mpn_mod_1 :: ByteArray# -> GmpSize# -> GmpLimb# -> GmpLimb#
-- mp_limb_t integer_gmp_mpn_rshift (mp_limb_t rp[], const mp_limb_t sp[],
-- mp_size_t sn, mp_bitcnt_t count)
foreign import ccall unsafe "integer_gmp_mpn_rshift"
c_mpn_rshift :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpBitCnt#
-> IO GmpLimb
-- mp_limb_t integer_gmp_mpn_rshift (mp_limb_t rp[], const mp_limb_t sp[],
-- mp_size_t sn, mp_bitcnt_t count)
foreign import ccall unsafe "integer_gmp_mpn_rshift_2c"
c_mpn_rshift_2c :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpBitCnt#
-> IO GmpLimb
-- mp_limb_t integer_gmp_mpn_lshift (mp_limb_t rp[], const mp_limb_t sp[],
-- mp_size_t sn, mp_bitcnt_t count)
foreign import ccall unsafe "integer_gmp_mpn_lshift"
c_mpn_lshift :: MutableByteArray# s -> ByteArray# -> GmpSize# -> GmpBitCnt#
-> IO GmpLimb
-- void mpn_and_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p,
-- mp_size_t n)
foreign import ccall unsafe "integer_gmp_mpn_and_n"
c_mpn_and_n :: MutableByteArray# s -> ByteArray# -> ByteArray# -> GmpSize#
-> IO ()
-- void mpn_andn_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p,
-- mp_size_t n)
foreign import ccall unsafe "integer_gmp_mpn_andn_n"
c_mpn_andn_n :: MutableByteArray# s -> ByteArray# -> ByteArray# -> GmpSize#
-> IO ()
-- void mpn_ior_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p,
-- mp_size_t n)
foreign import ccall unsafe "integer_gmp_mpn_ior_n"
c_mpn_ior_n :: MutableByteArray# s -> ByteArray# -> ByteArray# -> GmpSize#
-> IO ()
-- void mpn_xor_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p,
-- mp_size_t n)
foreign import ccall unsafe "integer_gmp_mpn_xor_n"
c_mpn_xor_n :: MutableByteArray# s -> ByteArray# -> ByteArray# -> GmpSize#
-> IO ()
-- mp_bitcnt_t mpn_popcount (const mp_limb_t *s1p, mp_size_t n)
foreign import ccall unsafe "gmp.h __gmpn_popcount"
c_mpn_popcount :: ByteArray# -> GmpSize# -> GmpBitCnt#
----------------------------------------------------------------------------
-- BigNat-wrapped ByteArray#-primops
-- | Return number of limbs contained in 'BigNat'.
sizeofBigNat# :: BigNat -> GmpSize#
sizeofBigNat# (BN# x#)
= sizeofByteArray# x# `uncheckedIShiftRL#` GMP_LIMB_SHIFT#
data MutBigNat s = MBN# !(MutableByteArray# s)
sizeofMutBigNat# :: MutBigNat s -> GmpSize#
sizeofMutBigNat# (MBN# x#)
= sizeofMutableByteArray# x# `uncheckedIShiftRL#` GMP_LIMB_SHIFT#
newBigNat# :: GmpSize# -> S s (MutBigNat s)
newBigNat# limbs# s =
case newByteArray# (limbs# `uncheckedIShiftL#` GMP_LIMB_SHIFT#) s of
(# s', mba# #) -> (# s', MBN# mba# #)
writeBigNat# :: MutBigNat s -> GmpSize# -> GmpLimb# -> State# s -> State# s
writeBigNat# (MBN# mba#) = writeWordArray# mba#
-- | Extract /n/-th (0-based) limb in 'BigNat'.
-- /n/ must be less than size as reported by 'sizeofBigNat#'.
indexBigNat# :: BigNat -> GmpSize# -> GmpLimb#
indexBigNat# (BN# ba#) = indexWordArray# ba#
unsafeFreezeBigNat# :: MutBigNat s -> S s BigNat
unsafeFreezeBigNat# (MBN# mba#) s = case unsafeFreezeByteArray# mba# s of
(# s', ba# #) -> (# s', BN# ba# #)
resizeMutBigNat# :: MutBigNat s -> GmpSize# -> S s (MutBigNat s)
resizeMutBigNat# (MBN# mba0#) nsz# s
| isTrue# (bsz# ==# sizeofMutableByteArray# mba0#) = (# s, MBN# mba0# #)
| True = case resizeMutableByteArray# mba0# bsz# s of
(# s', mba# #) -> (# s' , MBN# mba# #)
where
bsz# = nsz# `uncheckedIShiftL#` GMP_LIMB_SHIFT#
shrinkMutBigNat# :: MutBigNat s -> GmpSize# -> State# s -> State# s
shrinkMutBigNat# (MBN# mba0#) nsz#
| isTrue# (bsz# ==# sizeofMutableByteArray# mba0#) = \s -> s -- no-op
| True = shrinkMutableByteArray# mba0# bsz#
where
bsz# = nsz# `uncheckedIShiftL#` GMP_LIMB_SHIFT#
unsafeSnocFreezeBigNat# :: MutBigNat s -> GmpLimb# -> S s BigNat
unsafeSnocFreezeBigNat# mbn0@(MBN# mba0#) limb# = do
-- (MBN# mba#) <- newBigNat# (n# +# 1#)
-- _ <- svoid (copyMutableByteArray# mba0# 0# mba# 0# nb0#)
(MBN# mba#) <- resizeMutBigNat# mbn0 (n# +# 1#)
_ <- svoid (writeWordArray# mba# n# limb#)
unsafeFreezeBigNat# (MBN# mba#)
where
n# = nb0# `uncheckedIShiftRL#` GMP_LIMB_SHIFT#
nb0# = sizeofMutableByteArray# mba0#
-- | May shrink underlyng 'ByteArray#' if needed to satisfy BigNat invariant
unsafeRenormFreezeBigNat# :: MutBigNat s -> S s BigNat
unsafeRenormFreezeBigNat# mbn s
| isTrue# (n0# ==# 0#) = (# s', nullBigNat #)
| isTrue# (n# ==# 0#) = (# s', zeroBigNat #)
| isTrue# (n# ==# n0#) = (unsafeFreezeBigNat# mbn) s'
| True = (unsafeShrinkFreezeBigNat# mbn n#) s'
where
(# s', n# #) = normSizeofMutBigNat'# mbn n0# s
n0# = sizeofMutBigNat# mbn
-- | Shrink MBN
unsafeShrinkFreezeBigNat# :: MutBigNat s -> GmpSize# -> S s BigNat
unsafeShrinkFreezeBigNat# x@(MBN# xmba) 1#
= \s -> case readWordArray# xmba 0# s of
(# s', w# #) -> freezeOneLimb w# s'
where
freezeOneLimb 0## = return zeroBigNat
freezeOneLimb 1## = return oneBigNat
freezeOneLimb w# | isTrue# (not# w# `eqWord#` 0##) = return czeroBigNat
freezeOneLimb _ = do
_ <- svoid (shrinkMutBigNat# x 1#)
unsafeFreezeBigNat# x
unsafeShrinkFreezeBigNat# x y# = do
_ <- svoid (shrinkMutBigNat# x y#)
unsafeFreezeBigNat# x
copyWordArray# :: ByteArray# -> Int# -> MutableByteArray# s -> Int# -> Int#
-> State# s -> State# s
copyWordArray# src src_ofs dst dst_ofs len
= copyByteArray# src (src_ofs `uncheckedIShiftL#` GMP_LIMB_SHIFT#)
dst (dst_ofs `uncheckedIShiftL#` GMP_LIMB_SHIFT#)
(len `uncheckedIShiftL#` GMP_LIMB_SHIFT#)
-- | Version of 'normSizeofMutBigNat'#' which scans all allocated 'MutBigNat#'
normSizeofMutBigNat# :: MutBigNat s -> State# s -> (# State# s, Int# #)
normSizeofMutBigNat# mbn@(MBN# mba) = normSizeofMutBigNat'# mbn sz#
where
sz# = sizeofMutableByteArray# mba `uncheckedIShiftRA#` GMP_LIMB_SHIFT#
-- | Find most-significant non-zero limb and return its index-position
-- plus one. Start scanning downward from the initial limb-size
-- (i.e. start-index plus one) given as second argument.
--
-- NB: The 'normSizeofMutBigNat' of 'zeroBigNat' would be @0#@
normSizeofMutBigNat'# :: MutBigNat s -> GmpSize#
-> State# s -> (# State# s, GmpSize# #)
normSizeofMutBigNat'# (MBN# mba) = go
where
go 0# s = (# s, 0# #)
go i0# s = case readWordArray# mba (i0# -# 1#) s of
(# s', 0## #) -> go (i0# -# 1#) s'
(# s', _ #) -> (# s', i0# #)
-- | Construct 'BigNat' from existing 'ByteArray#' containing /n/
-- 'GmpLimb's in least-significant-first order.
--
-- If possible 'ByteArray#', will be used directly (i.e. shared
-- /without/ cloning the 'ByteArray#' into a newly allocated one)
--
-- Note: size parameter (times @sizeof(GmpLimb)@) must be less or
-- equal to its 'sizeofByteArray#'.
byteArrayToBigNat# :: ByteArray# -> GmpSize# -> BigNat
byteArrayToBigNat# ba# n0#
| isTrue# (n# ==# 0#) = zeroBigNat
| isTrue# (baszr# ==# 0#) -- i.e. ba# is multiple of limb-size
, isTrue# (baszq# ==# n#) = (BN# ba#)
| True = runS $ do
mbn@(MBN# mba#) <- newBigNat# n#
_ <- svoid (copyByteArray# ba# 0# mba# 0# (sizeofMutableByteArray# mba#))
unsafeFreezeBigNat# mbn
where
(# baszq#, baszr# #) = quotRemInt# (sizeofByteArray# ba#) GMP_LIMB_BYTES#
n# = fmssl (n0# -# 1#)
-- find most signifcant set limb, return normalized size
fmssl i#
| isTrue# (i# <# 0#) = 0#
| isTrue# (neWord# (indexWordArray# ba# i#) 0##) = i# +# 1#
| True = fmssl (i# -# 1#)
-- | Read 'Integer' (without sign) from memory location at @/addr/@ in
-- base-256 representation.
--
-- @'importIntegerFromAddr' /addr/ /size/ /msbf/@
--
-- See description of 'importIntegerFromByteArray' for more details.
--
-- @since 1.0.0.0
importIntegerFromAddr :: Addr# -> Word# -> Int# -> IO Integer
importIntegerFromAddr addr len msbf = IO $ do
bn <- liftIO (importBigNatFromAddr addr len msbf)
return (bigNatToInteger bn)
-- | Version of 'importIntegerFromAddr' constructing a 'BigNat'
importBigNatFromAddr :: Addr# -> Word# -> Int# -> IO BigNat
importBigNatFromAddr _ 0## _ = IO (\s -> (# s, zeroBigNat #))
importBigNatFromAddr addr len0 1# = IO $ do -- MSBF
W# ofs <- liftIO (c_scan_nzbyte_addr addr 0## len0)
let len = len0 `minusWord#` ofs
addr' = addr `plusAddr#` (word2Int# ofs)
importBigNatFromAddr# addr' len 1#
importBigNatFromAddr addr len0 _ = IO $ do -- LSBF
W# len <- liftIO (c_rscan_nzbyte_addr addr 0## len0)
importBigNatFromAddr# addr len 0#
foreign import ccall unsafe "integer_gmp_scan_nzbyte"
c_scan_nzbyte_addr :: Addr# -> Word# -> Word# -> IO Word
foreign import ccall unsafe "integer_gmp_rscan_nzbyte"
c_rscan_nzbyte_addr :: Addr# -> Word# -> Word# -> IO Word
-- | Helper for 'importBigNatFromAddr'
importBigNatFromAddr# :: Addr# -> Word# -> Int# -> S RealWorld BigNat
importBigNatFromAddr# _ 0## _ = return zeroBigNat
importBigNatFromAddr# addr len msbf = do
mbn@(MBN# mba#) <- newBigNat# n#
() <- liftIO (c_mpn_import_addr mba# addr 0## len msbf)
unsafeFreezeBigNat# mbn
where
-- n = ceiling(len / SIZEOF_HSWORD), i.e. number of limbs required
n# = (word2Int# len +# (SIZEOF_HSWORD# -# 1#)) `quotInt#` SIZEOF_HSWORD#
foreign import ccall unsafe "integer_gmp_mpn_import"
c_mpn_import_addr :: MutableByteArray# RealWorld -> Addr# -> Word# -> Word#
-> Int# -> IO ()
-- | Read 'Integer' (without sign) from byte-array in base-256 representation.
--
-- The call
--
-- @'importIntegerFromByteArray' /ba/ /offset/ /size/ /msbf/@
--
-- reads
--
-- * @/size/@ bytes from the 'ByteArray#' @/ba/@ starting at @/offset/@
--
-- * with most significant byte first if @/msbf/@ is @1#@ or least
-- significant byte first if @/msbf/@ is @0#@, and
--
-- * returns a new 'Integer'
--
-- @since 1.0.0.0
importIntegerFromByteArray :: ByteArray# -> Word# -> Word# -> Int# -> Integer
importIntegerFromByteArray ba ofs len msbf
= bigNatToInteger (importBigNatFromByteArray ba ofs len msbf)
-- | Version of 'importIntegerFromByteArray' constructing a 'BigNat'
importBigNatFromByteArray :: ByteArray# -> Word# -> Word# -> Int# -> BigNat
importBigNatFromByteArray _ _ 0## _ = zeroBigNat
importBigNatFromByteArray ba ofs0 len0 1# = runS $ do -- MSBF
W# ofs <- liftIO (c_scan_nzbyte_bytearray ba ofs0 len0)
let len = (len0 `plusWord#` ofs0) `minusWord#` ofs
importBigNatFromByteArray# ba ofs len 1#
importBigNatFromByteArray ba ofs len0 _ = runS $ do -- LSBF
W# len <- liftIO (c_rscan_nzbyte_bytearray ba ofs len0)
importBigNatFromByteArray# ba ofs len 0#
foreign import ccall unsafe "integer_gmp_scan_nzbyte"
c_scan_nzbyte_bytearray :: ByteArray# -> Word# -> Word# -> IO Word
foreign import ccall unsafe "integer_gmp_rscan_nzbyte"
c_rscan_nzbyte_bytearray :: ByteArray# -> Word# -> Word# -> IO Word
-- | Helper for 'importBigNatFromByteArray'
importBigNatFromByteArray# :: ByteArray# -> Word# -> Word# -> Int#
-> S RealWorld BigNat
importBigNatFromByteArray# _ _ 0## _ = return zeroBigNat
importBigNatFromByteArray# ba ofs len msbf = do
mbn@(MBN# mba#) <- newBigNat# n#
() <- liftIO (c_mpn_import_bytearray mba# ba ofs len msbf)
unsafeFreezeBigNat# mbn
where
-- n = ceiling(len / SIZEOF_HSWORD), i.e. number of limbs required
n# = (word2Int# len +# (SIZEOF_HSWORD# -# 1#)) `quotInt#` SIZEOF_HSWORD#
foreign import ccall unsafe "integer_gmp_mpn_import"
c_mpn_import_bytearray :: MutableByteArray# RealWorld -> ByteArray# -> Word#
-> Word# -> Int# -> IO ()
-- | Test whether all internal invariants are satisfied by 'BigNat' value
--
-- Returns @1#@ if valid, @0#@ otherwise.
--
-- This operation is mostly useful for test-suites and/or code which
-- constructs 'Integer' values directly.
isValidBigNat# :: BigNat -> Int#
isValidBigNat# (BN# ba#)
= (szq# ># 0#) `andI#` (szr# ==# 0#) `andI#` isNorm#
where
isNorm#
| isTrue# (szq# ># 1#) = (indexWordArray# ba# (szq# -# 1#)) `neWord#` 0##
| True = 1#
sz# = sizeofByteArray# ba#
(# szq#, szr# #) = quotRemInt# sz# GMP_LIMB_BYTES#
-- | Version of 'nextPrimeInteger' operating on 'BigNat's
--
-- @since 1.0.0.0
nextPrimeBigNat :: BigNat -> BigNat
nextPrimeBigNat bn@(BN# ba#) = runS $ do
mbn@(MBN# mba#) <- newBigNat# n#
(W# c#) <- liftIO (nextPrime# mba# ba# n#)
case c# of
0## -> unsafeFreezeBigNat# mbn
_ -> unsafeSnocFreezeBigNat# mbn c#
where
n# = sizeofBigNat# bn
foreign import ccall unsafe "integer_gmp_next_prime"
nextPrime# :: MutableByteArray# RealWorld -> ByteArray# -> GmpSize#
-> IO GmpLimb
----------------------------------------------------------------------------
-- monadic combinators for low-level state threading
type S s a = State# s -> (# State# s, a #)
infixl 1 >>=
infixl 1 >>
infixr 0 $
{-# INLINE ($) #-}
($) :: (a -> b) -> a -> b
f $ x = f x
{-# INLINE (>>=) #-}
(>>=) :: S s a -> (a -> S s b) -> S s b
(>>=) m k = \s -> case m s of (# s', a #) -> k a s'
{-# INLINE (>>) #-}
(>>) :: S s a -> S s b -> S s b
(>>) m k = \s -> case m s of (# s', _ #) -> k s'
{-# INLINE svoid #-}
svoid :: (State# s -> State# s) -> S s ()
svoid m0 = \s -> case m0 s of s' -> (# s', () #)
{-# INLINE return #-}
return :: a -> S s a
return a = \s -> (# s, a #)
{-# INLINE liftIO #-}
liftIO :: IO a -> S RealWorld a
liftIO (IO m) = m
-- NB: equivalent of GHC.IO.unsafeDupablePerformIO, see notes there
runS :: S RealWorld a -> a
runS m = lazy (case m realWorld# of (# _, r #) -> r)
{-# NOINLINE runS #-}
-- stupid hack
fail :: [Char] -> S s a
fail s = return (raise# s)
----------------------------------------------------------------------------
-- | Internal helper type for "signed" 'BigNat's
--
-- This is a useful abstraction for operations which support negative
-- mp_size_t arguments.
data SBigNat = NegBN !BigNat | PosBN !BigNat
-- | Absolute value of 'SBigNat'
absSBigNat :: SBigNat -> BigNat
absSBigNat (NegBN bn) = bn
absSBigNat (PosBN bn) = bn
-- | /Signed/ limb count. Negative sizes denote negative integers
ssizeofSBigNat# :: SBigNat -> GmpSize#
ssizeofSBigNat# (NegBN bn) = negateInt# (sizeofBigNat# bn)
ssizeofSBigNat# (PosBN bn) = sizeofBigNat# bn
-- | Construct 'SBigNat' from 'Int#' value
intToSBigNat# :: Int# -> SBigNat
intToSBigNat# 0# = PosBN zeroBigNat
intToSBigNat# 1# = PosBN oneBigNat
intToSBigNat# (-1#) = NegBN oneBigNat
intToSBigNat# i# | isTrue# (i# ># 0#) = PosBN (wordToBigNat (int2Word# i#))
| True = PosBN (wordToBigNat (int2Word# (negateInt# i#)))
-- | Convert 'Integer' into 'SBigNat'
integerToSBigNat :: Integer -> SBigNat
integerToSBigNat (S# i#) = intToSBigNat# i#
integerToSBigNat (Jp# bn) = PosBN bn
integerToSBigNat (Jn# bn) = NegBN bn
-- | Convert 'SBigNat' into 'Integer'
sBigNatToInteger :: SBigNat -> Integer
sBigNatToInteger (NegBN bn) = bigNatToNegInteger bn
sBigNatToInteger (PosBN bn) = bigNatToInteger bn
----------------------------------------------------------------------------
-- misc helpers, some of these should rather be primitives exported by ghc-prim
cmpW# :: Word# -> Word# -> Ordering
cmpW# x# y#
| isTrue# (x# `ltWord#` y#) = LT
| isTrue# (x# `eqWord#` y#) = EQ
| True = GT
{-# INLINE cmpW# #-}
subWordC# :: Word# -> Word# -> (# Word#, Int# #)
subWordC# x# y# = (# d#, c# #)
where
d# = x# `minusWord#` y#
c# = d# `gtWord#` x#
{-# INLINE subWordC# #-}
bitWord# :: Int# -> Word#
bitWord# = uncheckedShiftL# 1##
{-# INLINE bitWord# #-}
testBitWord# :: Word# -> Int# -> Int#
testBitWord# w# i# = (bitWord# i# `and#` w#) `neWord#` 0##
{-# INLINE testBitWord# #-}
popCntI# :: Int# -> Int#
popCntI# i# = word2Int# (popCnt# (int2Word# i#))
{-# INLINE popCntI# #-}
-- branchless version
absI# :: Int# -> Int#
absI# i# = (i# `xorI#` nsign) -# nsign
where
-- nsign = negateInt# (i# <# 0#)
nsign = uncheckedIShiftRA# i# (WORD_SIZE_IN_BITS# -# 1#)
-- branchless version
sgnI# :: Int# -> Int#
sgnI# x# = (x# ># 0#) -# (x# <# 0#)
cmpI# :: Int# -> Int# -> Int#
cmpI# x# y# = (x# ># y#) -# (x# <# y#)
minI# :: Int# -> Int# -> Int#
minI# x# y# | isTrue# (x# <=# y#) = x#
| True = y#
| TomMD/ghc | libraries/integer-gmp/src/GHC/Integer/Type.hs | bsd-3-clause | 73,220 | 14 | 19 | 17,697 | 21,072 | 10,595 | 10,477 | -1 | -1 |
{-# OPTIONS -fno-spec-constr-count #-}
module Main where
import QSortSeq
import QSortPar
import QSortVect
import Control.Exception (evaluate )
import System.Console.GetOpt
import Data.Array.Parallel.Unlifted
import Data.Array.Parallel.Unlifted.Parallel
import Data.Array.Parallel.Prelude (toUArrPA, fromUArrPA')
import Bench.Benchmark
import Bench.Options
import Debug.Trace
algs = [("seq", qsortSeq), ("par", qsortPar), ("list", toU. qsortList . fromU), ("vect", qsortVect')]
qsortVect':: UArr Double -> UArr Double
qsortVect' xs = trace (show res)
res
where
res = toUArrPA $ qsortVect $ fromUArrPA' xs
generateVector :: Int -> IO (Point (UArr Double))
generateVector n =
do
evaluate vec
return $ ("N = " ++ show n) `mkPoint` vec
where
vec = toU (reverse [1..fromInteger (toInteger n)])
main = ndpMain "QSort"
"[OPTION] ... SIZES ..."
run [Option ['a'] ["algo"] (ReqArg const "ALGORITHM")
"use the specified algorithm"]
"seq"
run opts alg sizes =
case lookup alg algs of
Nothing -> failWith ["Unknown algorithm"]
Just f -> case map read sizes of
[] -> failWith ["No sizes specified"]
szs -> do
benchmark opts f (map generateVector szs) show
return ()
| mainland/dph | icebox/examples/qsort/QSort.hs | bsd-3-clause | 1,366 | 0 | 15 | 375 | 408 | 219 | 189 | 37 | 3 |
module Language.Haskell.Liquid.Interactive.Handler (
-- * Initial state for server
initial
-- * Command handler
, handler
) where
import Control.Concurrent.MVar
import Language.Haskell.Liquid.Interactive.Types
import Language.Haskell.Liquid.Liquid
------------------------------------------------------------------------------
handler :: MVar State -> Command -> IO Response
------------------------------------------------------------------------------
handler r = modifyMVar r . runLiquid'
runLiquid' :: Command -> State -> IO (State, Response)
runLiquid' cfg s = do
let mE = sMbEnv s
let n = sCount s
(c, mE') <- runLiquid mE cfg
let s' = State (n + 1) mE'
return (s', (status c, n))
------------------------------------------------------------------------------
initial :: State
------------------------------------------------------------------------------
initial = State 0 Nothing
| abakst/liquidhaskell | src/Language/Haskell/Liquid/Interactive/Handler.hs | bsd-3-clause | 934 | 0 | 12 | 141 | 209 | 114 | 95 | 17 | 1 |
--------------------------------------------------------------------------
-- Copyright (c) 2007-2010, ETH Zurich.
-- All rights reserved.
--
-- This file is distributed under the terms in the attached LICENSE file.
-- If you do not find this file, copies can be found by writing to:
-- ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
--
-- Architectural definitions for Barrelfish on x86_64.
--
--------------------------------------------------------------------------
module X86_64 where
import HakeTypes
import Path
import qualified Config
import qualified ArchDefaults
-------------------------------------------------------------------------
--
-- Architecture specific definitions for x86_64
--
-------------------------------------------------------------------------
arch = "x86_64"
archFamily = "x86_64"
compiler = "gcc"
cxxcompiler = "g++"
ourCommonFlags = [ Str "-m64",
Str "-mno-red-zone",
Str "-fPIE",
Str "-fno-stack-protector",
Str "-Wno-unused-but-set-variable",
Str "-Wno-packed-bitfield-compat",
Str "-D__x86__" ]
cFlags = ArchDefaults.commonCFlags
++ ArchDefaults.commonFlags
++ ourCommonFlags
cxxFlags = ArchDefaults.commonCxxFlags
++ ArchDefaults.commonFlags
++ ourCommonFlags
cDefines = ArchDefaults.cDefines options
ourLdFlags = [ Str "-Wl,-z,max-page-size=0x1000",
Str "-Wl,--build-id=none",
Str "-m64" ]
ldFlags = ArchDefaults.ldFlags arch ++ ourLdFlags
ldCxxFlags = ArchDefaults.ldCxxFlags arch ++ ourLdFlags
options = (ArchDefaults.options arch archFamily) {
optFlags = cFlags,
optCxxFlags = cxxFlags,
optDefines = cDefines,
optLdFlags = ldFlags,
optLdCxxFlags = ldCxxFlags,
optInterconnectDrivers = ["lmp", "ump", "multihop"],
optFlounderBackends = ["lmp", "ump", "multihop"]
}
--
-- The kernel is "different"
--
kernelCFlags = [ Str s | s <- [ "-fno-builtin",
"-nostdinc",
"-std=c99",
"-m64",
"-mno-red-zone",
"-fPIE",
"-fno-stack-protector",
"-U__linux__",
"-Wall",
"-Wshadow",
"-Wstrict-prototypes",
"-Wold-style-definition",
"-Wmissing-prototypes",
"-Wmissing-declarations",
"-Wmissing-field-initializers",
"-Wredundant-decls",
"-Wno-packed-bitfield-compat",
"-Wno-unused-but-set-variable",
"-Werror",
"-imacros deputy/nodeputy.h",
"-mno-mmx",
"-mno-sse",
"-mno-sse2",
"-mno-sse3",
"-mno-sse4.1",
"-mno-sse4.2",
-- "-Wno-unused-but-set-variable",
"-mno-sse4",
"-mno-sse4a",
"-mno-3dnow" ]]
kernelLdFlags = [ Str s | s <- [ "-Wl,-N",
"-pie",
"-fno-builtin",
"-nostdlib",
"-Wl,--fatal-warnings",
"-m64" ] ]
------------------------------------------------------------------------
--
-- Now, commands to actually do something
--
------------------------------------------------------------------------
--
-- Compilers
--
cCompiler = ArchDefaults.cCompiler arch compiler
cxxCompiler = ArchDefaults.cxxCompiler arch cxxcompiler
makeDepend = ArchDefaults.makeDepend arch compiler
makeCxxDepend = ArchDefaults.makeCxxDepend arch cxxcompiler
cToAssembler = ArchDefaults.cToAssembler arch compiler
assembler = ArchDefaults.assembler arch compiler
archive = ArchDefaults.archive arch
linker = ArchDefaults.linker arch compiler
cxxlinker = ArchDefaults.cxxlinker arch cxxcompiler
--
-- Link the kernel (CPU Driver)
--
linkKernel :: Options -> [String] -> [String] -> String -> HRule
linkKernel opts objs libs kbin =
let linkscript = "/kernel/linker.lds"
in
Rules [ Rule ([ Str compiler, Str Config.cOptFlags,
NStr "-T", In BuildTree arch "/kernel/linker.lds",
Str "-o", Out arch kbin
]
++ (optLdFlags opts)
++
[ In BuildTree arch o | o <- objs ]
++
[ In BuildTree arch l | l <- libs ]
++
[ NL, NStr "/bin/echo -e '\\0002' | dd of=",
Out arch kbin,
Str "bs=1 seek=16 count=1 conv=notrunc status=noxfer"
]
),
Rule [ Str "cpp",
NStr "-I", NoDep SrcTree "src" "/kernel/include/",
Str "-D__ASSEMBLER__",
Str "-P", In SrcTree "src" "/kernel/arch/x86_64/linker.lds.in",
Out arch linkscript
]
]
| CoryXie/BarrelfishOS | hake/X86_64.hs | mit | 5,617 | 4 | 17 | 2,212 | 788 | 448 | 340 | 100 | 1 |
module PCP.Solve where
import Autolib.Schichten
import Autolib.Util.Hide
import Autolib.Util.Splits
import Autolib.Hash
import Autolib.Set
import Autolib.ToDoc
import Control.Monad
import Data.Maybe
import PCP.DFS
import PCP.Type
import PCP.Examples
type Conf c = ( Maybe [c], Hide [Int] )
fsolve :: String
-> Int
-> [[Int]]
fsolve w cc = do
c <- [ 1 .. cc ]
(d, sol) <- tree $ fpairs w c
guard $ null d
return $ reverse sol
fpairs w c =
let inf = [ repeat ("w", "0")
, repeat ("0","1")
, repeat ("1", "w")
]
fin = [ replicate c (w, "0")
, []
, replicate c ("1", w)
]
in inf ++ fin
tree :: (Hash c, Ord c )
=> [[Pair c]]
-> [([c], [Int])] -- ^ list of (diff, reverse prefix)
tree pairs = tree_from pairs []
tree_from pairs w = do
( _, d , _, Hide is ) <-
-- bfs
dfs
next ( hash w, w, Hide pairs, Hide [] )
return ( d, is )
next ( _, diff, Hide pairs, Hide is ) = mkSet $ do
-- use first pair from some list
( ps, ((l,r) : rest) : qs ) <- splits pairs
let i = length ps
let (pre, post) = splitAt (length r) (diff ++ l)
guard $ pre == r
return ( hash post
, post
, Hide $ ps ++ [ rest ] ++ qs
, Hide $ i : is
)
-------------------------------------------------------
| florianpilz/autotool | src/PCP/Solve.hs | gpl-2.0 | 1,352 | 10 | 13 | 428 | 584 | 316 | 268 | 47 | 1 |
module Uni.SS04.Serie4 where
-- $Id$
import PCProblem.Quiz
import PCProblem.Type
import PCProblem.Param
import SAT.Quiz
import SAT.Types
import SAT.Param ( p )
import Inter.Types
generate :: [ IO Variant ]
generate =
[ return $ Variant $ make "PCP" "QUIZ" $ PCProblem.Quiz.quiz
$ PCProblem.Param.Param
{ alpha = "abc"
, paare = 4
, breite = 3
, nah = 7
, fern = 20
, viel = 1000
}
, return $ Variant $ make "PCP" "EASY" $
fixed $ PCP [("1","0"),("01","1"),("1","110")]
, return $ Variant $ make "PCP" "EXTRA" $ PCProblem.Quiz.quiz
$ PCProblem.Param.Param
{ alpha = "abc"
, paare = 5
, breite = 3
, nah = 20
, fern = 35
, viel = 2000
}
]
-- PCP schwer [ ("001","0"),("0","1"),("1","001") ]
-- , return $ Variant $ SAT.Quiz.quiz "SAT" "QUIZ"
-- $ p 10 | florianpilz/autotool | src/Uni/SS04/Serie4.hs | gpl-2.0 | 1,086 | 0 | 9 | 473 | 257 | 155 | 102 | 28 | 1 |
{-# LANGUAGE TupleSections, PatternGuards, CPP, OverloadedStrings #-}
module Haste.CodeGen (generate) where
-- Misc. stuff
import Control.Applicative
import Control.Monad
import Data.Int
import Data.Bits
import Data.Word
import Data.Char
import Data.List (partition, foldl')
import Data.Maybe (isJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.UTF8 as BS
import qualified Data.Set as S
import qualified Data.Map as M
-- STG/GHC stuff
import Language.Haskell.GHC.Simple as GHC
import FastString (unpackFS)
-- AST stuff
import Data.JSTarget as J hiding ((.&.))
import Data.JSTarget.AST as J (Exp (..), Stm (..), LHS (..))
-- General Haste stuff
import Haste.Config
import Haste.Monad
import Haste.Errors
import Haste.PrimOps
import Haste.Builtins
-- | Generate an abstract JS module from a codegen config and an STG module.
generate :: Config -> StgModule -> J.Module
generate cfg stg =
J.Module {
modPackageId = BS.fromString $ GHC.modPackageKey stg,
J.modName = BS.fromString $ GHC.modName stg,
modDeps = foldl' insDep M.empty theMod,
modDefs = foldl' insFun M.empty theMod
}
where
opt = if optimize cfg then optimizeFun else const id
theMod = genAST cfg (GHC.modName stg) (modCompiledModule stg)
insFun m (_, Assign (NewVar _ v@(Internal n _ _)) body _) =
M.insert n (opt v body) m
insFun m _ =
m
-- TODO: perhaps do dependency-based linking for externals as well?
insDep m (ds, Assign (NewVar _ (Internal v _ _)) _ _) =
M.insert v (S.delete v ds) m
insDep m _ =
m
-- | Generate JS AST for bindings.
genAST :: Config -> String -> [StgBinding] -> [(S.Set J.Name, Stm)]
genAST cfg modname binds =
binds'
where
binds' =
map (depsAndCode . genJS cfg modname . uncurry (genBind True))
$ concatMap unRec
$ binds
depsAndCode (_, ds, locs, stm) = (ds S.\\ locs, stm stop)
-- | Check for builtins that should generate inlined code. At this point only
-- w2i and i2w.
genInlinedBuiltin :: GHC.Var -> [StgArg] -> JSGen Config (Maybe Exp)
genInlinedBuiltin f [x] = do
x' <- genArg x
return $ case (modname, varname) of
(Just "GHC.HasteWordInt", "w2i") ->
Just $ binOp BitAnd x' (litN 0xffffffff)
(Just "GHC.HasteWordInt", "i2w") ->
Just $ binOp ShrL x' (litN 0)
_ ->
Nothing
where
modname = moduleNameString . moduleName <$> nameModule_maybe (GHC.varName f)
varname = occNameString $ nameOccName $ GHC.varName f
genInlinedBuiltin _ _ =
return Nothing
-- | Generate code for an STG expression.
genEx :: StgExpr -> JSGen Config Exp
genEx (StgApp f xs) = do
mex <- genInlinedBuiltin f xs
case mex of
Just ex -> return ex
_ -> genApp f xs
genEx (StgLit l) = do
genLit l
genEx (StgConApp con args) = do
-- On 64 bit machines, GHC constructs small integers from Ints rather than
-- Int64, so we need to deal with it or be unable to reliably create Int64
-- or Integer values.
case (dataConNameModule con, args) of
(("S#", "GHC.Integer.Type"), [StgLitArg (MachInt n)]) | tooLarge n -> do
return $ mkInteger n
(("True", "GHC.Types"), []) -> do
return $ lit True
(("False", "GHC.Types"), []) -> do
return $ lit False
_ -> do
(tag, stricts) <- genDataCon con
(args', stricts') <- genArgsPair $ zip args stricts
-- Don't create unboxed tuples with a single element.
case (isNewtypeLikeCon con || isUnboxedTupleCon con, args') of
(True, [arg]) -> return $ evaluate arg (head stricts')
_ -> mkCon tag args' stricts'
where
mkInteger n =
array [litN 1, callForeign "I_fromBits" [array [lit lo, lit hi]]]
where
lo = n .&. 0xffffffff
hi = n `shiftR` 32
tooLarge n = n > 2147483647 || n < -2147483648
-- Always inline enum-likes, bools are true/false, not 1/0.
mkCon l _ _ | isEnumerationDataCon con = return l
mkCon tag as ss = return $ array (tag : zipWith evaluate as ss)
evaluate arg True = eval arg
evaluate arg _ = arg
genEx (StgOpApp op args _) = do
args' <- genArgs args
cfg <- getCfg
let theOp = case op of
StgPrimOp op' ->
maybeTrace cfg opstr args' <$> genOp cfg op' args'
where opstr = BS.fromString $ showOutputable cfg op'
StgPrimCallOp (PrimCall f _) ->
Right $ maybeTrace cfg fs args' $ callForeign fs args'
where fs = BS.fromString $ unpackFS f
StgFCallOp (CCall (CCallSpec (StaticTarget f _ _) _ _)) _t ->
Right $ maybeTrace cfg fs args' $ callForeign fs args'
where fs = BS.fromString $ unpackFS f
_ ->
error $ "Tried to generate unsupported dynamic foreign call!"
case theOp of
Right x -> return x
Left err -> warn Normal err >> return (runtimeError err)
genEx (StgLet bind ex) = do
genBindRec bind
genEx ex
genEx (StgLetNoEscape _ _ bind ex) = do
genBindRec bind
genEx ex
genEx (StgCase ex _ _ bndr _ t alts) = do
genCase t ex bndr alts
#if __GLASGOW_HASKELL__ < 710
-- StgSCC is gone in 7.10, and StgTick has an argument less.
genEx (StgSCC _ _ _ ex) = do
genEx ex
genEx (StgTick _ _ ex) = do
#else
genEx (StgTick _ ex) = do
#endif
genEx ex
genEx (StgLam _ _) = do
error "StgLam caught during code generation - that's impossible!"
-- | Trace the given expression, if tracing is on.
maybeTrace :: Config -> BS.ByteString -> [Exp] -> Exp -> Exp
maybeTrace cfg msg args ex =
if tracePrimops cfg
then callForeign "__h_trace" [lit msg, array args, ex]
else ex
genBindRec :: StgBinding -> JSGen Config ()
genBindRec bs@(StgRec _) = do
mapM_ (genBind False (Just len) . snd) bs'
where
bs' = unRec bs
len = length bs'
genBindRec b =
genBind False Nothing b
-- | Generate code for all bindings. genBind spits out an error if it receives
-- a recursive binding; this is because it's quite a lot easier to keep track
-- of which functions depend on each other if every genBind call results in a
-- single function being generated.
-- Use `genBindRec` to generate code for local potentially recursive bindings
-- as their dependencies get merged into their parent's anyway.
genBind :: Bool -> Maybe Int -> StgBinding -> JSGen Config ()
genBind onTopLevel funsInRecGroup (StgNonRec v rhs) = do
v' <- genVar v
pushBind v'
when (not onTopLevel) $ do
addLocal v'
expr <- genRhs (isJust funsInRecGroup) rhs
popBind
continue $ newVar True v' expr
genBind _ _ (StgRec _) =
error $ "genBind got recursive bindings!"
-- | Generate the RHS of a binding.
genRhs :: Bool -> StgRhs -> JSGen Config Exp
genRhs recursive (StgRhsCon _ con args) = do
-- Constructors are never partially applied, and we have arguments, so this
-- is obviously a full application.
if recursive
then thunk True . ret <$> genEx (StgConApp con args)
else genEx (StgConApp con args)
genRhs _ (StgRhsClosure _ _ _ upd _ args body) = do
args' <- mapM genVar args
(retExp, body') <- isolate $ do
mapM_ addLocal args'
genEx body
return $ if null args
then thunk' upd (body' $ thunkRet retExp)
else fun args' (body' $ ret retExp)
where
thunk' _ (Return l@(J.Lit _)) = l
thunk' Updatable stm = thunk True stm
thunk' ReEntrant stm = thunk True stm
thunk' SingleEntry stm = thunk False stm
-- | Turn a recursive binding into a list of non-recursive ones, together with
-- information about whether they came from a recursive group or not.
unRec :: StgBinding -> [(Maybe Int, StgBinding)]
unRec (StgRec bs) = zip (repeat len) (map (uncurry StgNonRec) bs)
where
len = Just $ length bs
unRec b = [(Nothing, b)]
-- | Filter a list of (Var, anything) pairs, generate JSVars from the Vars
-- and then return both lists.
-- Lists of vars are often accompanied by lists of strictness or usage
-- annotations, which need to be filtered for types without representation
-- as well.
genArgVarsPair :: [(GHC.Var, a)] -> JSGen Config ([J.Var], [a])
genArgVarsPair vps = do
vs' <- mapM genVar vs
return (vs', xs)
where
(vs, xs) = unzip $ filter (hasRepresentation . fst) vps
genCase :: AltType -> StgExpr -> Id -> [StgAlt] -> JSGen Config Exp
genCase t ex scrut alts = do
cfg <- getCfg
ex' <- genEx ex
-- Return a scrutinee variable and a function to replace all occurrences of
-- the STG scrutinee with our JS one, if needed.
(scrut', withScrutinee) <- case ex' of
Eval (J.Var v) | overwriteScrutinees cfg -> do
continue $ assignVar (reorderableType scrut) v ex'
oldscrut <- genVar scrut
return (v, rename oldscrut v)
_ -> do
scrut' <- genVar scrut
addLocal scrut'
continue $ newVar (reorderableType scrut) scrut' ex'
return (scrut', id)
-- If we have a unary unboxed tuple, we want to eliminate the case
-- entirely (modulo evaluation), so just generate the expression in the
-- sole alternative.
withScrutinee $ do
case (isNewtypeLike scrut, isUnaryUnboxedTuple scrut, alts) of
(_, True, [(_, as, _, expr)]) | [arg] <- filter hasRepresentation as -> do
arg' <- genVar arg
addLocal arg'
continue $ newVar (reorderableType scrut) arg' (varExp scrut')
genEx expr
(True, _, [(_, [arg], _, expr)]) -> do
arg' <- genVar arg
addLocal arg'
continue $ newVar (reorderableType scrut) arg' (varExp scrut')
genEx expr
(_, True, _) -> do
error "Case on unary unboxed tuple with more than one alt! WTF?!"
_ -> do
-- Generate scrutinee and result vars
res <- genResultVar scrut
addLocal res
-- Split alts into default and general, and generate code for them
let (defAlt, otherAlts) = splitAlts alts
scrutinee = cmp (varExp scrut')
(_, defAlt') <- genAlt scrut' res defAlt
alts' <- mapM (genAlt scrut' res) otherAlts
-- Use the ternary operator where possible.
useSloppyTCE <- sloppyTCE `fmap` getCfg
self <- if useSloppyTCE then return blackHoleVar else getCurrentBinding
case tryTernary self scrutinee (varExp res) defAlt' alts' of
Just ifEx -> do
continue $ newVar True res ifEx
return (varExp res)
_ -> do
continue $ case_ scrutinee defAlt' alts'
return (varExp res)
where
getTag s = index s (litN 0)
cmp = case t of
PrimAlt _ -> id
AlgAlt tc -> if isEnumerationTyCon tc then id else getTag
_ -> getTag
-- | Split a list of StgAlts into (default, [rest]). Since all case expressions
-- are total, if there is no explicit default branch, the last conditional
-- branch is the default one.
splitAlts :: [StgAlt] -> (StgAlt, [StgAlt])
splitAlts alts =
case partition isDefault alts of
([defAlt], otherAlts) -> (defAlt, otherAlts)
([], otherAlts) -> (last otherAlts, init otherAlts)
_ -> error "More than one default alt in case!"
where
isDefault (DEFAULT, _, _, _) = True
isDefault _ = False
genAlt :: J.Var -> J.Var -> StgAlt -> JSGen Config (Exp, Stm -> Stm)
genAlt scrut res (con, args, used, body) = do
construct <- case con of
-- undefined is intentional here - the first element is never touched.
DEFAULT -> return (undefined, )
LitAlt l -> (,) <$> genLit l
DataAlt c | tag <- genDataConTag c -> return (tag, )
(args', used') <- genArgVarsPair (zip args used)
addLocal args'
let binds = [bindVar v ix | (v, True, ix) <- zip3 args' used' [1..]]
(_, body') <- isolate $ do
continue $ foldr (.) id binds
retEx <- genEx body
continue $ newVar False res retEx
return $ construct body'
where
bindVar v ix = newVar True v (index (varExp scrut) (litN ix))
-- | Generate a result variable for the given scrutinee variable.
genResultVar :: GHC.Var -> JSGen Config J.Var
genResultVar v = do
v' <- genVar v >>= getActualName
case v' of
Foreign n ->
return $ Internal (Name (BS.append n "#result") Nothing) "" True
Internal (Name n mp) _ _ ->
return $ Internal (Name (BS.append n "#result") mp) "" True
-- | Generate a new variable and add a dependency on it to the function
-- currently being generated.
genVar :: GHC.Var -> JSGen Config J.Var
genVar v | hasRepresentation v = do
case toBuiltin v of
Just v' -> return v'
_ -> do
mymod <- getModName
v' <- getActualName $ toJSVar mymod v
dependOn v'
return v'
genVar _ = do
return $ foreignVar "_"
-- | Extracts the name of a foreign var.
foreignName :: ForeignCall -> BS.ByteString
foreignName (CCall (CCallSpec (StaticTarget str _ _) _ _)) =
BS.fromString $ unpackFS str
foreignName _ =
error "Dynamic foreign calls not supported!"
-- | Turn a 'GHC.Var' into a 'J.Var'. Falls back to a default module name,
-- typically the name of the current module under compilation, if the given
-- Var isn't qualified.
toJSVar :: String -> GHC.Var -> J.Var
toJSVar thisMod v =
case idDetails v of
FCallId fc -> foreignVar (foreignName fc)
_
| isLocalId v && not hasMod ->
internalVar (name unique (Just (myPkg, myMod))) ""
| isGlobalId v || hasMod ->
internalVar (name extern (Just (myPkg, myMod))) comment
_ ->
error $ "Var is not local, global or external!"
where
comment = BS.concat [myMod, ".", extern]
vname = GHC.varName v
hasMod = case nameModule_maybe vname of
Nothing -> False
_ -> True
myMod = BS.fromString $ maybe thisMod (moduleNameString . moduleName)
(nameModule_maybe vname)
myPkg = BS.fromString $ maybe "main" (pkgKeyString . modulePkgKey)
(nameModule_maybe vname)
extern = BS.fromString $ occNameString $ nameOccName vname
unique = BS.fromString $ show $ nameUnique vname
-- | Generate an argument list. Any arguments of type State# a are filtered out.
genArgs :: [StgArg] -> JSGen Config [Exp]
genArgs = mapM genArg . filter hasRep
where
hasRep (StgVarArg v) = hasRepresentation v
hasRep _ = True
-- | Filter out args without representation, along with their accompanying
-- pair element, then generate code for the args.
-- Se `genArgVarsPair` for more information.
genArgsPair :: [(StgArg, a)] -> JSGen Config ([Exp], [a])
genArgsPair aps = do
args' <- mapM genArg args
return (args', xs)
where
(args, xs) = unzip $ filter hasRep aps
hasRep (StgVarArg v, _) = hasRepresentation v
hasRep _ = True
-- | Returns True if the given var actually has a representation.
-- Currently, only values of type State# a are considered representationless.
hasRepresentation :: GHC.Var -> Bool
hasRepresentation = typeHasRep . varType
typeHasRep :: Type -> Bool
typeHasRep t =
case splitTyConApp_maybe t of
Just (tc, _) -> tc /= statePrimTyCon
_ -> True
genArg :: StgArg -> JSGen Config Exp
genArg (StgVarArg v) = varExp <$> genVar v
genArg (StgLitArg l) = genLit l
-- | Generate code for data constructor creation. Returns a pair of
-- (constructor, field strictness annotations).
genDataCon :: DataCon -> JSGen Config (Exp, [Bool])
genDataCon dc = do
if isEnumerationDataCon dc
then return (tagexp, [])
else return (tagexp, map strict (dataConRepStrictness dc))
where
tagexp = genDataConTag dc
strict MarkedStrict = True
strict _ = False
-- | Generate the tag for a data constructor. This is used both by genDataCon
-- and directly by genCase to generate constructors for matching.
--
-- IMPORTANT: remember to update the RTS if any changes are made to the
-- constructor tag values!
genDataConTag :: DataCon -> Exp
genDataConTag d =
case dataConNameModule d of
("True", "GHC.Types") -> lit True
("False", "GHC.Types") -> lit False
_ ->
lit (fromIntegral (dataConTag d - fIRST_TAG) :: Double)
-- | Get the name and module of the given data constructor.
dataConNameModule :: DataCon -> (String, String)
dataConNameModule d =
(occNameString $ nameOccName $ dataConName d,
moduleNameString $ moduleName $ nameModule $ dataConName d)
-- | Generate literals.
genLit :: GHC.Literal -> JSGen Config Exp
genLit l = do
case l of
MachStr s -> return $ lit s
MachInt n
| n > 2147483647 ||
n < -2147483648 -> do warn Verbose (constFail "Int" n)
return $ truncInt n
| otherwise -> return . litN $ fromIntegral n
MachFloat f -> return . litN $ fromRational f
MachDouble d -> return . litN $ fromRational d
MachChar c -> return . litN $ fromIntegral $ ord c
MachWord w
| w > 0xffffffff -> do warn Verbose (constFail "Word" w)
return $ truncWord w
| otherwise -> return . litN $ fromIntegral w
MachWord64 w -> return $ word64 w
MachNullAddr -> return $ litN 0
MachInt64 n -> return $ int64 n
LitInteger n _ -> return $ lit n
-- Labels point to machine code - ignore!
MachLabel _ _ _ -> return $ litS ":("
where
constFail t n = t ++ " literal " ++ show n ++ " doesn't fit in 32 bits;"
++ " truncating!"
truncInt n = litN . fromIntegral $ (fromIntegral n :: Int32)
truncWord w = litN . fromIntegral $ (fromIntegral w :: Word32)
int64 n = callForeign "new Long" [lit lo, lit hi]
where
lo = n .&. 0xffffffff
hi = n `shiftR` 32
word64 n = callForeign "I_fromBits" [array [lit lo, lit hi]]
where
lo = n .&. 0xffffffff
hi = n `shiftR` 32
-- | Generate a function application.
genApp :: GHC.Var -> [StgArg] -> JSGen Config Exp
genApp f xs = do
f' <- varExp <$> genVar f
xs' <- mapM genArg xs
if null xs
then return $ eval f'
else return $ call arity f' xs'
where
arity = arityInfo $ idInfo f
-- | Does this data constructor create an enumeration type?
isEnumerationDataCon :: DataCon -> Bool
isEnumerationDataCon = isEnumerationTyCon . dataConTyCon
-- | Does this data constructor create a newtype-like value? That is, a value
-- of a type with a single data constructor having a single argument?
isNewtypeLikeCon :: DataCon -> Bool
isNewtypeLikeCon c =
case tyConDataCons (dataConTyCon c) of
[_] -> case dataConRepArgTys c of
[t] -> isUnLiftedType t
_ -> False
_ -> False
-- | Does this data constructor create a newtype-like value? That is, a value
-- of a type with a single data constructor having a single unlifted
-- argument?
isNewtypeLike :: GHC.Var -> Bool
isNewtypeLike v = maybe False id $ do
(tycon, _) <- splitTyConApp_maybe (varType v)
case tyConDataCons tycon of
[c] -> case dataConRepArgTys c of
[t] -> return (isUnLiftedType t)
_ -> return False
_ -> return False
-- | Returns True if the given Var is an unboxed tuple with a single element
-- after any represenationless elements are discarded.
isUnaryUnboxedTuple :: GHC.Var -> Bool
isUnaryUnboxedTuple v = maybe False id $ do
(_, args) <- splitTyConApp_maybe t
case filter typeHasRep args of
[_] -> return $ isUnboxedTupleType t
_ -> return False
where
t = varType v
-- | Is it safe to reorder values of the given type?
reorderableType :: GHC.Var -> Bool
reorderableType v =
case splitTyConApp_maybe t of
Just (_, args) -> length (filter typeHasRep args) == length args
_ -> typeHasRep t
where
t = varType v
| beni55/haste-compiler | src/Haste/CodeGen.hs | bsd-3-clause | 19,889 | 0 | 22 | 5,335 | 5,901 | 2,965 | 2,936 | 401 | 12 |
module C where
import API
import qualified A
resource = let Test s = A.resource in Test { field = s }
| abuiles/turbinado-blog | tmp/dependencies/hs-plugins-1.3.1/testsuite/load/thiemann2/C.hs | bsd-3-clause | 104 | 0 | 9 | 24 | 41 | 23 | 18 | 4 | 1 |
f = \case
4 -> const 'x'
5 -> \case
'a' -> 'b'
'c' -> 'd'
main = do
print $ f 5 'a'
print $ f 4 'y'
| hvr/jhc | regress/tests/2_language/lambda-case.hs | mit | 134 | 0 | 10 | 63 | 66 | 31 | 35 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Fibonacci (plugin) where
import Neovim
import Fibonacci.Plugin (fibonacci)
plugin :: Neovim (StartupConfig NeovimConfig) () NeovimPlugin
plugin = wrapPlugin Plugin
{ exports = [ $(function' 'fibonacci) Sync ]
, statefulExports = []
}
| saep/nvim-hs-config-example | lib/Fibonacci.hs | mit | 296 | 0 | 12 | 59 | 81 | 46 | 35 | 8 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>TreeTools</title>
<maps>
<homeID>treetools</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> | kingthorin/zap-extensions | addOns/treetools/src/main/javahelp/help_tr_TR/helpset_tr_TR.hs | apache-2.0 | 960 | 77 | 66 | 155 | 404 | 205 | 199 | -1 | -1 |
-- A minimal server
import Network.XmlRpc.Server
add :: Int -> Int -> IO Int
add x y = return (x + y)
main = cgiXmlRpcServer [("examples.add", fun add)] | laurencer/confluence-sync | vendor/haxr/examples/simple_server.hs | bsd-3-clause | 155 | 0 | 8 | 30 | 64 | 34 | 30 | 4 | 1 |
module Demote.C1 (module Demote.D1, module Demote.C1) where
import Demote.D1 hiding (main, sq)
sumSquares1 (x:xs) = sq x + sumSquares1 xs
where sq x = x ^pow
sumSquares1 [] = 0
| SAdams601/HaRe | test/testdata/Demote/C1.hs | bsd-3-clause | 188 | 0 | 7 | 41 | 83 | 46 | 37 | 5 | 1 |
module Distribution.Client.Dependency.Modular.IndexConversion (
convPIs
-- * TODO: The following don't actually seem to be used anywhere?
, convIPI
, convSPI
, convPI
) where
import Data.List as L
import Data.Map as M
import Data.Maybe
import Prelude hiding (pi)
import qualified Distribution.Client.PackageIndex as CI
import Distribution.Client.Types
import Distribution.Client.ComponentDeps (Component(..))
import Distribution.Compiler
import Distribution.InstalledPackageInfo as IPI
import Distribution.Package -- from Cabal
import Distribution.PackageDescription as PD -- from Cabal
import qualified Distribution.Simple.PackageIndex as SI
import Distribution.System
import Distribution.Client.Dependency.Modular.Dependency as D
import Distribution.Client.Dependency.Modular.Flag as F
import Distribution.Client.Dependency.Modular.Index
import Distribution.Client.Dependency.Modular.Package
import Distribution.Client.Dependency.Modular.Tree
import Distribution.Client.Dependency.Modular.Version
-- | Convert both the installed package index and the source package
-- index into one uniform solver index.
--
-- We use 'allPackagesBySourcePackageId' for the installed package index
-- because that returns us several instances of the same package and version
-- in order of preference. This allows us in principle to \"shadow\"
-- packages if there are several installed packages of the same version.
-- There are currently some shortcomings in both GHC and Cabal in
-- resolving these situations. However, the right thing to do is to
-- fix the problem there, so for now, shadowing is only activated if
-- explicitly requested.
convPIs :: OS -> Arch -> CompilerInfo -> Bool -> Bool ->
SI.InstalledPackageIndex -> CI.PackageIndex SourcePackage -> Index
convPIs os arch comp sip strfl iidx sidx =
mkIndex (convIPI' sip iidx ++ convSPI' os arch comp strfl sidx)
-- | Convert a Cabal installed package index to the simpler,
-- more uniform index format of the solver.
convIPI' :: Bool -> SI.InstalledPackageIndex -> [(PN, I, PInfo)]
convIPI' sip idx =
-- apply shadowing whenever there are multiple installed packages with
-- the same version
[ maybeShadow (convIP idx pkg)
| (_pkgid, pkgs) <- SI.allPackagesBySourcePackageId idx
, (maybeShadow, pkg) <- zip (id : repeat shadow) pkgs ]
where
-- shadowing is recorded in the package info
shadow (pn, i, PInfo fdeps fds _) | sip = (pn, i, PInfo fdeps fds (Just Shadowed))
shadow x = x
convIPI :: Bool -> SI.InstalledPackageIndex -> Index
convIPI sip = mkIndex . convIPI' sip
-- | Convert a single installed package into the solver-specific format.
convIP :: SI.InstalledPackageIndex -> InstalledPackageInfo -> (PN, I, PInfo)
convIP idx ipi =
let ipid = IPI.installedPackageId ipi
i = I (pkgVersion (sourcePackageId ipi)) (Inst ipid)
pn = pkgName (sourcePackageId ipi)
in case mapM (convIPId pn idx) (IPI.depends ipi) of
Nothing -> (pn, i, PInfo [] M.empty (Just Broken))
Just fds -> (pn, i, PInfo (setComp fds) M.empty Nothing)
where
-- We assume that all dependencies of installed packages are _library_ deps
setComp = setCompFlaggedDeps ComponentLib
-- TODO: Installed packages should also store their encapsulations!
-- | Convert dependencies specified by an installed package id into
-- flagged dependencies of the solver.
--
-- May return Nothing if the package can't be found in the index. That
-- indicates that the original package having this dependency is broken
-- and should be ignored.
convIPId :: PN -> SI.InstalledPackageIndex -> InstalledPackageId -> Maybe (FlaggedDep () PN)
convIPId pn' idx ipid =
case SI.lookupInstalledPackageId idx ipid of
Nothing -> Nothing
Just ipi -> let i = I (pkgVersion (sourcePackageId ipi)) (Inst ipid)
pn = pkgName (sourcePackageId ipi)
in Just (D.Simple (Dep pn (Fixed i (Goal (P pn') []))) ())
-- | Convert a cabal-install source package index to the simpler,
-- more uniform index format of the solver.
convSPI' :: OS -> Arch -> CompilerInfo -> Bool ->
CI.PackageIndex SourcePackage -> [(PN, I, PInfo)]
convSPI' os arch cinfo strfl = L.map (convSP os arch cinfo strfl) . CI.allPackages
convSPI :: OS -> Arch -> CompilerInfo -> Bool ->
CI.PackageIndex SourcePackage -> Index
convSPI os arch cinfo strfl = mkIndex . convSPI' os arch cinfo strfl
-- | Convert a single source package into the solver-specific format.
convSP :: OS -> Arch -> CompilerInfo -> Bool -> SourcePackage -> (PN, I, PInfo)
convSP os arch cinfo strfl (SourcePackage (PackageIdentifier pn pv) gpd _ _pl) =
let i = I pv InRepo
in (pn, i, convGPD os arch cinfo strfl (PI pn i) gpd)
-- We do not use 'flattenPackageDescription' or 'finalizePackageDescription'
-- from 'Distribution.PackageDescription.Configuration' here, because we
-- want to keep the condition tree, but simplify much of the test.
-- | Convert a generic package description to a solver-specific 'PInfo'.
convGPD :: OS -> Arch -> CompilerInfo -> Bool ->
PI PN -> GenericPackageDescription -> PInfo
convGPD os arch comp strfl pi
(GenericPackageDescription pkg flags libs exes tests benchs) =
let
fds = flagInfo strfl flags
conv = convCondTree os arch comp pi fds (const True)
in
PInfo
(maybe [] (conv ComponentLib ) libs ++
maybe [] (convSetupBuildInfo pi) (setupBuildInfo pkg) ++
concatMap (\(nm, ds) -> conv (ComponentExe nm) ds) exes ++
prefix (Stanza (SN pi TestStanzas))
(L.map (\(nm, ds) -> conv (ComponentTest nm) ds) tests) ++
prefix (Stanza (SN pi BenchStanzas))
(L.map (\(nm, ds) -> conv (ComponentBench nm) ds) benchs))
fds
Nothing
prefix :: (FlaggedDeps comp qpn -> FlaggedDep comp' qpn) -> [FlaggedDeps comp qpn] -> FlaggedDeps comp' qpn
prefix _ [] = []
prefix f fds = [f (concat fds)]
-- | Convert flag information. Automatic flags are now considered weak
-- unless strong flags have been selected explicitly.
flagInfo :: Bool -> [PD.Flag] -> FlagInfo
flagInfo strfl = M.fromList . L.map (\ (MkFlag fn _ b m) -> (fn, FInfo b m (not (strfl || m))))
-- | Convert condition trees to flagged dependencies.
convCondTree :: OS -> Arch -> CompilerInfo -> PI PN -> FlagInfo ->
(a -> Bool) -> -- how to detect if a branch is active
Component ->
CondTree ConfVar [Dependency] a -> FlaggedDeps Component PN
convCondTree os arch cinfo pi@(PI pn _) fds p comp (CondNode info ds branches)
| p info = L.map (\d -> D.Simple (convDep pn d) comp) ds -- unconditional dependencies
++ concatMap (convBranch os arch cinfo pi fds p comp) branches
| otherwise = []
-- | Branch interpreter.
--
-- Here, we try to simplify one of Cabal's condition tree branches into the
-- solver's flagged dependency format, which is weaker. Condition trees can
-- contain complex logical expression composed from flag choices and special
-- flags (such as architecture, or compiler flavour). We try to evaluate the
-- special flags and subsequently simplify to a tree that only depends on
-- simple flag choices.
convBranch :: OS -> Arch -> CompilerInfo ->
PI PN -> FlagInfo ->
(a -> Bool) -> -- how to detect if a branch is active
Component ->
(Condition ConfVar,
CondTree ConfVar [Dependency] a,
Maybe (CondTree ConfVar [Dependency] a)) -> FlaggedDeps Component PN
convBranch os arch cinfo pi fds p comp (c', t', mf') =
go c' ( convCondTree os arch cinfo pi fds p comp t')
(maybe [] (convCondTree os arch cinfo pi fds p comp) mf')
where
go :: Condition ConfVar ->
FlaggedDeps Component PN -> FlaggedDeps Component PN -> FlaggedDeps Component PN
go (Lit True) t _ = t
go (Lit False) _ f = f
go (CNot c) t f = go c f t
go (CAnd c d) t f = go c (go d t f) f
go (COr c d) t f = go c t (go d t f)
go (Var (Flag fn)) t f = extractCommon t f ++ [Flagged (FN pi fn) (fds ! fn) t f]
go (Var (OS os')) t f
| os == os' = t
| otherwise = f
go (Var (Arch arch')) t f
| arch == arch' = t
| otherwise = f
go (Var (Impl cf cvr)) t f
| matchImpl (compilerInfoId cinfo) ||
-- fixme: Nothing should be treated as unknown, rather than empty
-- list. This code should eventually be changed to either
-- support partial resolution of compiler flags or to
-- complain about incompletely configured compilers.
any matchImpl (fromMaybe [] $ compilerInfoCompat cinfo) = t
| otherwise = f
where
matchImpl (CompilerId cf' cv) = cf == cf' && checkVR cvr cv
-- If both branches contain the same package as a simple dep, we lift it to
-- the next higher-level, but without constraints. This heuristic together
-- with deferring flag choices will then usually first resolve this package,
-- and try an already installed version before imposing a default flag choice
-- that might not be what we want.
extractCommon :: FlaggedDeps Component PN -> FlaggedDeps Component PN -> FlaggedDeps Component PN
extractCommon ps ps' = [ D.Simple (Dep pn (Constrained [])) comp
| D.Simple (Dep pn _) _ <- ps
, D.Simple (Dep pn' _) _ <- ps'
, pn == pn'
]
-- | Convert a Cabal dependency to a solver-specific dependency.
convDep :: PN -> Dependency -> Dep PN
convDep pn' (Dependency pn vr) = Dep pn (Constrained [(vr, Goal (P pn') [])])
-- | Convert a Cabal package identifier to a solver-specific dependency.
convPI :: PN -> PackageIdentifier -> Dep PN
convPI pn' (PackageIdentifier pn v) = Dep pn (Constrained [(eqVR v, Goal (P pn') [])])
-- | Convert setup dependencies
convSetupBuildInfo :: PI PN -> SetupBuildInfo -> FlaggedDeps Component PN
convSetupBuildInfo (PI pn _i) nfo =
L.map (\d -> D.Simple (convDep pn d) ComponentSetup) (PD.setupDepends nfo)
| gridaphobe/cabal | cabal-install/Distribution/Client/Dependency/Modular/IndexConversion.hs | bsd-3-clause | 10,268 | 0 | 20 | 2,478 | 2,701 | 1,415 | 1,286 | 134 | 9 |
{-# LANGUAGE TypeFamilies #-}
module T8034 where
class C a where
type F a
foo :: F a -> F a
| siddhanathan/ghc | testsuite/tests/typecheck/should_fail/T8034.hs | bsd-3-clause | 97 | 0 | 8 | 26 | 33 | 18 | 15 | 5 | 0 |
{-# LANGUAGE GADTs, ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
module Control.Monad.Takahashi
( module Control.Monad.Takahashi.API
, module Control.Monad.Takahashi.Slide
, module Control.Monad.Takahashi.Monad
, module Control.Monad.Takahashi.HtmlBuilder
, module Control.Monad.Takahashi.Util
) where
import Control.Lens
import Control.Monad.State
import Control.Monad.Takahashi.API
import Control.Monad.Takahashi.Slide
import Control.Monad.Takahashi.Monad
import Control.Monad.Takahashi.HtmlBuilder
import Control.Monad.Takahashi.Util
| tokiwoousaka/takahashi | src/Control/Monad/Takahashi.hs | mit | 564 | 0 | 5 | 57 | 97 | 70 | 27 | 15 | 0 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
-- | This executable generated .golden tests for importify.
module Main where
import Universum
import Path (Abs, Dir, File, Path, fileExtension, fromAbsFile, (-<.>))
import Path.IO (listDirRecur, removeFile)
import Importify.Main (importifyFileContent)
import Importify.Path (testDataPath)
main :: IO ()
main = do
arguments <- getArgs
case arguments of
["--clean"] -> cleanGoldenExamples
["--force"] -> generateGoldenTests
[] -> generateGoldenTestsPrompt
_ -> putText "Incorrect arguments!"
findByExtension :: MonadIO m => String -> Path b Dir -> m [Path Abs File]
findByExtension ext path = filter ((== ext) . fileExtension) . snd
<$> listDirRecur path
findGoldenFiles :: MonadIO m => Path b Dir -> m [Path Abs File]
findGoldenFiles = findByExtension "golden"
cleanGoldenExamples :: MonadIO m => m ()
cleanGoldenExamples = do
goldenExamples <- findGoldenFiles testDataPath
mapM_ removeFile goldenExamples
findHaskellFiles :: MonadIO m => Path b Dir -> m [Path Abs File]
findHaskellFiles = findByExtension ".hs"
writeBinaryFile :: MonadIO m => Path Abs File -> Text -> m ()
writeBinaryFile = writeFile . fromAbsFile
generateGoldenTestsPrompt :: IO ()
generateGoldenTestsPrompt = do
putText "> Are you sure want to generate new golden examples? [y/N]"
getLine >>= \case
"y" -> generateGoldenTests
_ -> putText "Aborting generation"
generateGoldenTests :: IO ()
generateGoldenTests = do
testCaseFiles <- findHaskellFiles testDataPath
forM_ testCaseFiles $ \testCasePath -> do
Right modifiedSrc <- importifyFileContent testCasePath
goldenPath <- testCasePath -<.> "golden"
writeBinaryFile goldenPath modifiedSrc
| serokell/importify | test/GGenerator.hs | mit | 1,949 | 0 | 12 | 472 | 483 | 243 | 240 | 43 | 4 |
{-|
Module : Hi3Status.Blocks.Network
License : MIT
Maintainer : Josh Kirklin ([email protected])
Stability : experimental
-}
module Hi3Status.Blocks.Network
( NetworkBlock (..)
) where
import Hi3Status.Block
import Hi3Status.Block.Util
import qualified Data.Text as T
import Data.Prefix.Units
import Control.Monad.IO.Class
import Control.Concurrent
import System.Process
-- | A network transfer rate indicator. Uses files at @/sys/class/net/@.
data NetworkBlock = NetworkBlock {
-- | The format of the displayed text.
--
-- * @{rx}@ = Download rate.
-- * @{tx}@ = Upload rate.
format :: String,
-- | The device to query, e.g. "eth0".
device :: String,
-- | How often to check the rates (in microseconds).
checkPeriod :: Int
}
instance Block NetworkBlock where
{- runBlock b = do
(rx,tx) <- rxtx (device b)
rxRef <- liftIO $ newIORef rx
txRef <- liftIO $ newIORef tx
periodic (checkPeriod b) $ do
(rx',tx') <- rxtx (device b)
liftIO $ writeIORef rx
-}
runBlock b = do
(rx,tx) <- rxtx (device b)
go rx tx
where
go rx tx = do
(rx',tx') <- rxtx (device b)
let rr = 1000000 * (realToFrac $ rx'-rx) / (realToFrac $ checkPeriod b) :: Double
tr = 1000000 * (realToFrac $ tx'-tx) / (realToFrac $ checkPeriod b) :: Double
rs = showValue FormatSiKMGT (round rr :: Int)
ts = showValue FormatSiKMGT (round tr :: Int)
pushBlockDescription $ emptyBlockDescription { full_text = formatText [("rx",rs),("tx",ts)] (format b) }
liftIO $ threadDelay (checkPeriod b)
go rx' tx'
rxtx :: String -> BlockM (Int, Int)
rxtx dev = do
rx <- liftIO $ filter (/='\n') <$> readProcess "cat" ["/sys/class/net/"++dev++"/statistics/rx_bytes"] ""
tx <- liftIO $ filter (/='\n') <$> readProcess "cat" ["/sys/class/net/"++dev++"/statistics/tx_bytes"] ""
return (read rx, read tx)
| ScrambledEggsOnToast/hi3status | lib-src/Hi3Status/Blocks/Network.hs | mit | 2,035 | 0 | 17 | 564 | 482 | 262 | 220 | 31 | 1 |
module FunctorLaws where
-- The functor laws:
-- 1) fmap id = id
-- 2) fmap g . fmap h = fmap (g . h)
-- A "computation counter" that adds up number of times `fmap` was
-- applied.
data Counter a = Counter Int a
deriving (Show, Eq)
instance Functor Counter where
fmap f (Counter c x) = Counter (c + 1) (f x)
-- Breaks law 1:
-- ghci> let a = Counter 0 "testing"
-- ghci> let b = id <$> a
-- ghci> a == b
-- False
-- It will also break law 2:
--
-- ghci> fmap (++ " and testing") . fmap (++ " and again") $ a
-- Counter 2 "testing and again and testing"
--
-- vs
--
-- ghci> fmap ((++ " and testing") . (++ " and again")) a
-- Counter 1 "testing and again and testing"
-- A version of Maybe that simply returns Nothing from any `fmap`.
data MaybeNot a = JustNot a | NothingNot
deriving (Show, Eq)
instance Functor MaybeNot where
fmap f _ = NothingNot
-- This breaks law 1:
-- ghci> id (JustNot 1) == fmap id (JustNot 1)
-- False
| mjhoy/dotfiles | notes/2018_002_haskell_functor_derive_and_laws/FunctorLaws.hs | mit | 946 | 0 | 8 | 215 | 136 | 84 | 52 | 9 | 0 |
{-# LANGUAGE CPP #-}
module Data.Geometry.Geos.Raw.Topology (
envelope
, intersection
, convexHull
, difference
, symmetricDifference
, boundary
, union
, unaryUnion
, pointOnSurface
, centroid
, node
, delaunayTriangulation
, voronoiDiagram
, polygonize
, minimumRotatedRectangle
, minimumWidth
, minimumClearanceLine
, minimumClearance
) where
import qualified Data.Geometry.Geos.Raw.Internal as I
import Data.Geometry.Geos.Raw.Base
import qualified Data.Geometry.Geos.Raw.Geometry as R
import Foreign hiding (throwIfNull, throwIf)
geo_1 :: R.Geometry a
=> (I.GEOSContextHandle_t -> Ptr I.GEOSGeometry -> IO (Ptr I.GEOSGeometry))
-> String
-> a
-> Geos a
geo_1 f s g = withGeos' $ \h -> do
eitherPtr <- throwIfNull' s $ R.withGeometry g $ f h
traverse (R.constructGeometry h) eitherPtr
geo_2 :: R.Geometry a
=> (I.GEOSContextHandle_t -> Ptr I.GEOSGeometry -> Ptr I.GEOSGeometry -> IO (Ptr I.GEOSGeometry))
-> String
-> a
-> a
-> Geos a
geo_2 f s g1 g2 = withGeos' $ \h -> do
eitherPtr <- throwIfNull' s $ R.withGeometry g1 $ \gp ->
R.withGeometry g2 (f h gp)
traverse (R.constructGeometry h) eitherPtr
envelope :: R.Geometry a => a -> Geos a
envelope = geo_1 I.geos_Envelope "envelope"
intersection :: R.Geometry a => a -> a -> Geos a
intersection = geo_2 I.geos_Intersection "intersection"
convexHull :: R.Geometry a => a -> Geos a
convexHull = geo_1 I.geos_ConvexHull "convexHull"
difference :: R.Geometry a => a -> a -> Geos a
difference = geo_2 I.geos_Difference "difference"
symmetricDifference :: R.Geometry a => a -> a-> Geos a
symmetricDifference = geo_2 I.geos_SymDifference "symmetricDifference"
boundary :: R.Geometry a => a -> Geos a
boundary = geo_1 I.geos_Boundary "boundary"
union :: R.Geometry a => a -> a -> Geos a
union = geo_2 I.geos_Union "union"
unaryUnion :: R.Geometry a => a -> Geos a
unaryUnion = geo_1 I.geos_UnaryUnion "unaryUnion"
pointOnSurface :: R.Geometry a => a -> Geos a
pointOnSurface = geo_1 I.geos_PointsOnSurface "pointOnSurface"
centroid :: R.Geometry a => a -> Geos a
centroid = geo_1 I.geos_GetCentroid "getCentroid"
node :: R.Geometry a => a -> Geos a
node = geo_1 I.geos_Node "node"
{-
Polygonizes a set of Geometries which contain linework that
represents the edges of a planar graph.
All types of Geometry are accepted as input; the constituent
linework is extracted as the edges to be polygonized.
The edges must be correctly noded; that is, they must only meet
at their endpoints. The set of extracted polygons
is guaranteed to be edge-disjoint. This is useful when it is known
that the input lines form a valid polygonal geometry (which may
include holes or nested polygons).
-}
polygonize :: R.Geometry a => [ a ] -> Geos a
polygonize geoms = withGeos' $ \h -> alloca $ \arrPtr -> do
_ <- traverse (writeIndexed arrPtr) $ [0 ..] `zip` geoms
eitherPtr <- throwIfNull' "polygonize" $ I.geos_Polygonize_valid h arrPtr $ fromIntegral (length geoms)
traverse (R.constructGeometry h) eitherPtr
where
writeIndexed arrayPtr (idx, geom) = R.withGeometry geom $ \geoPtr -> pokeElemOff arrayPtr idx geoPtr
{-
Returns the minimum rotated rectangular POLYGON which encloses the input geometry. The rectangle has width equal to the minimum diameter, and a longer length. If the convex hull of the input is degenerate (a line or point) a LINESTRING or POINT is returned. The minimum rotated rectangle can be used as an extremely generalized representation for the given geometry.
-}
minimumRotatedRectangle :: R.Geometry a => a -> Geos a
minimumRotatedRectangle = geo_1 I.geos_MinimumRotatedRectangle "minimumRotatedRectangle"
-- | Returns a LINESTRING geometry which represents the minimum diameter of the geometry. The minimum diameter is defined to be the width of the smallest band that contains the geometry, where a band is a strip of the plane defined by two parallel lines. This can be thought of as the smallest hole that the geometry can be moved through, with a single rotation.
minimumWidth :: R.Geometry a => a -> Geos a
minimumWidth = geo_1 I.geos_MinimumWidth "minimumWidth"
-- | Returns a LineString whose endpoints define the minimum clearance of a geometry. If the geometry has no minimum clearance, an empty LineString will be returned.
minimumClearanceLine :: R.Geometry a => a -> Geos a
minimumClearanceLine = geo_1 I.geos_MinimumClearanceLine "minimumClearanceLine"
-- | Computes the minimum clearance of a geometry. The minimum clearance is the smallest amount by which a vertex could be move to produce an invalid polygon, a non-simple linestring, or a multipoint with repeated points. If a geometry has a minimum clearance of 'eps', it can be said that:
-- | - No two distinct vertices in the geometry are separated by less than 'eps'
-- | - No vertex is closer than 'eps' to a line segment of which it is not an endpoint.
-- If the minimum clearance cannot be defined for a geometry (such as with a single point, or a multipoint whose points are identical, a value of Infinity will be calculated.
minimumClearance :: R.Geometry a => a -> Geos Double
minimumClearance geom = withGeos' $ \h ->
R.withGeometry geom $ \gptr -> alloca $ \dptr -> do
eitherInt <- throwIf' (0 /=) (mkErrorMessage "minimumClearance") $ I.geos_MinimumClearance h gptr dptr
traverse (\_ -> realToFrac <$> peek dptr) eitherInt
-- | Return a Delaunay triangulation of the vertex of the given geometry @g@, where @tol@ is the snapping tolerance to use.
delaunayTriangulation :: R.Geometry a
=> a
-> Double
-> Bool
-> Geos a
delaunayTriangulation g tol onlyEdges = withGeos' $ \h -> do
eitherPtr <- throwIfNull' "delaunayTriangulation" $ R.withGeometry g $ \gp ->
I.geos_DelaunayTriangulation h gp (realToFrac tol) $ fromBool onlyEdges
traverse (R.constructGeometry h) eitherPtr
voronoiDiagram :: R.Geometry a => a -> Maybe a -> Double -> Bool -> Geos a
voronoiDiagram g menv tol oe = withGeos' $ \h -> do
eitherPtr <- throwIfNull' "voronoiDiagram" $ R.withGeometry g $ \gp ->
R.withMaybeGeometry menv $ \ep -> I.geos_VoronoiDiagram h gp ep (realToFrac tol) $ fromBool oe
traverse (R.constructGeometry h) eitherPtr
| ewestern/geos | src/Data/Geometry/Geos/Raw/Topology.hs | mit | 6,364 | 0 | 17 | 1,269 | 1,414 | 713 | 701 | 95 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
module Cdo.Query where
import Control.Lens
import Control.Monad (join)
import Control.Applicative
-- import Control.Monad.Trans.Class (lift)
import Data.ByteString (ByteString)
-- import qualified Data.ByteString as BS
import Data.Monoid ((<>))
import qualified Data.Text.Encoding as T
-- import Database.Redis (RedisCtx)
import Control.Error.Util (note)
import Database.Redis
import Control.Monad.Trans.Either (EitherT (..))
import qualified Data.UUID as UUID
import Data.Attoparsec.ByteString.Char8
import Cdo.Types
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HMS
hGetHashMap :: (RedisCtx m f, Functor m, Functor f) => AccountId -> m (f (HashMap ByteString ByteString))
hGetHashMap (mkAccountKey -> key) = fmap HMS.fromList <$> hgetall key
getAccountById :: (RedisCtx m (Either Reply), Functor m) => AccountId -> m (Either Reply Account)
getAccountById aid = do
Right hm <- hGetHashMap aid
return $ Account aid <$> (T.decodeUtf8 <$> hm .: "name")
<*> (hm .: "balance" >>= (redisError "Couldn't parse balance" . parseAmount))
where
hm .: k = (redisError $ "Couldn't find key " <> k) $ (hm ^. at k)
mkAccountNameKey :: AccountName -> ByteString
mkAccountNameKey name = "account-name:" <> T.encodeUtf8 name
mkAccountKey :: AccountId -> ByteString
mkAccountKey (AccountId aid) = "account:" <> UUID.toASCIIBytes aid
accountExists :: RedisCtx m f => AccountName -> m (f Bool)
accountExists = exists . mkAccountNameKey
accountBalance :: (RedisCtx m (Either Reply)) => AccountId -> m (Either Reply Amount)
accountBalance aid = do
Right bal <- hget (mkAccountKey aid) "balance"
return $ redisError "Couldn't parse amount" $ join (parseAmount <$> bal)
getAccount :: (RedisCtx m (Either Reply)) => AccountName -> m (Either Reply Account)
getAccount name = runEitherT $ do
uuid' <- EitherT $ get (mkAccountNameKey name)
uuid <- AccountId <$> (EitherT . return . redisError "Couldn't parse UUID" $ UUID.fromASCIIBytes =<< uuid')
bal <- EitherT $ accountBalance uuid
return $ Account uuid name bal
where
parseAmount :: ByteString -> Maybe Amount
parseAmount bs = Amount <$> either (const Nothing) Just (parseOnly double bs)
redisError :: ByteString -> Maybe b -> Either Reply b
redisError msg = note (Error msg)
| boothead/cdo | src/Cdo/Query.hs | mit | 2,418 | 0 | 14 | 414 | 765 | 400 | 365 | 46 | 1 |
module Y2016.M06.D28.Exercise where
import System.Environment
{--
So, I was struggling both Sunday and Monday as to what would be this week's
theme for the Haskell exercises, and there it was staring at me in the face
the whole time.
Work.
So you would not believe the 'not invented here'-mentality that pervades Big
Gov't. If 'they' didn't write the code, then it doesn't even exist in their
minds. Web Services? REST? They've heard of these things, but it might be
risky. Maybe. And 'cloud computing.'
Big Gov't has 'cloud computing.' Sure they do: it's a mainframe in their
basement that is inaccessable outside their VPN.
Yes, they actually do have VPN. Shocker!
So, today's task.
Read in a file ... BUT WAIT! WHAT IF THE FILE IS NOT THERE? PANIC-TIME! WE NEED
SECURITY MEASURES IN PLACE.
So, don't even read in a file. Do THIS instead:
Write a Haskell program that checks to see if a file is 'there' (where it's
supposed to be). If it is, well, then do nothing and exit 0 (all is well).
If the file is NOT there, then return to the shell the 'FILE NOT FOUND' result
(which happens to be, for this scenario, 4).
(Yes, you read that correctly: return 4 to the shell if the requested file is
not found).
So, interaction with the (operating) system is on the plate for today.
How do you call the program? Your first argument will be the file that should
be at your directory, so reading from the (operating) system when your Haskell
program is invoked is another thing you have to do.
At this directory is a file named Schnitzengruben.txt. Look for it. Nothing
should happen (meaning 0 is returned to the operating system), now look for
a file names Schatzie.txt. Nothing should happen, again, other than the fact
that 4 is returned to the operating system.
Have at it!
--}
main = undefined
-- Schnitzengruben.txt is at this directory and at the URL:
-- https://raw.githubusercontent.com/geophf/1HaskellADay/master/exercises/HAD/Y2016/M06/D28/Schnitzengruben.txt
| geophf/1HaskellADay | exercises/HAD/Y2016/M06/D28/Exercise.hs | mit | 1,985 | 0 | 4 | 352 | 21 | 15 | 6 | 3 | 1 |
module Ch10 where
import Data.List
import Data.Char
-- import qualified Data.Map as Map
import Control.Monad
solveRPN :: String -> Double
solveRPN = head . foldl foldingFunction [] . words
where
foldingFunction (x:y:ys) "*" = (y*x):ys
foldingFunction (x:y:ys) "+" = (y+x):ys
foldingFunction (x:y:ys) "-" = (y-x):ys
foldingFunction (x:y:ys) "/" = (y/x):ys
foldingFunction (x:y:ys) "^" = (y**x):ys
foldingFunction (x:xs) "ln" = log x:xs
foldingFunction xs "sum" = [sum xs]
foldingFunction xs numberString = read numberString:xs
main = putStrLn "Ch10!"
| sol2man2/Learn-You-A-Haskell-For-Great-Good | src/Ch10.hs | mit | 587 | 0 | 10 | 114 | 276 | 146 | 130 | 15 | 8 |
import Raster
sqsz = 16
main = writeFile "test02.xbm" $ exportXBM "test02" Nothing
$ fnewRaster (\(y, x) -> toEnum $ (y `div` sqsz + x `div` sqsz) `mod` 2)
(8 * sqsz, 8 * sqsz)
| jwodder/hsgraphics | tests/xbmTest02.hs | mit | 182 | 2 | 13 | 40 | 94 | 52 | 42 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Web.Intercom.Types (
appId,
apiKey,
Client,
ping,
defaultClient,
withIntercom,
userList,
nextPage,
name,
email,
customAttributes,
users,
next,
User,
blankUser,
createOrUpdateUser,
UserList,
module Control.Lens
) where
import Control.Applicative
import Control.Lens hiding ((.=))
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Reader
import Data.Aeson
import Data.ByteString
import Data.HashMap.Lazy
import Data.Maybe
import Data.Text
import Network.Wreq
data Client = Client {
_appId :: ByteString,
_apiKey :: ByteString
} deriving (Show)
$(makeLenses ''Client)
defaultClient :: Client
defaultClient = Client "" ""
-- | Test the connection to Intercom
-- > let client = defaultClient & appId .~ "foo" & apiKey .~ "bar"
-- > withIntercom client ping
-- Status {statusCode = 200, statusMessage = "OK"}
ping :: Client -> IO Status
ping c = do
r <- getWith (opts c) "https://api.intercom.io/admins"
return $ r ^. responseStatus
opts c = defaults & auth ?~ basicAuth (c ^. appId) (c ^. apiKey)
& header "Accept" .~ ["application/json"]
postOpts c = opts c & header "Content-Type" .~ ["application/json"]
data User = User {
_name :: Maybe Text,
_email :: Maybe Text,
_userId :: Maybe Text,
_customAttributes :: HashMap Text Value
} deriving (Eq, Show)
-- | A blank user, for overriding
-- > let myUser = blankUser & email .~ (Just "[email protected]")
blankUser :: User
blankUser = User Nothing Nothing Nothing (fromList [])
$(makeLenses ''User)
instance FromJSON User where
parseJSON (Object v) =
User <$> v .:? "name"
<*> v .:? "email"
<*> v .:? "user_id"
<*> v .: "custom_attributes"
parseJSON _ = mzero
instance ToJSON User where
toJSON (User n e u c) = object (nonEmpty attributes)
where nonEmpty = catMaybes . fmap sequenceA
attributes = [
("name", String <$> n),
("email", String <$> e),
("user_id", String <$> u),
("custom_attributes", Just $ Object c)
]
data UserList = UserList {
_users :: [User],
_next :: Maybe Text
} deriving (Eq, Show)
$(makeLenses ''UserList)
instance FromJSON UserList where
parseJSON (Object v) =
UserList <$> (v .: "users")
<*> ((v .: "pages") >>= (.: "next"))
parseJSON _ = mzero
-- | Perform a function with a given client
withIntercom :: Client -> ReaderT Client m a -> m a
withIntercom = flip runReaderT
-- | Grab a page of users from your user list
-- > let client = defaultClient & appId .~ "foo" & apiKey .~ "bar"
-- > withIntercom client $ userList
-- Just (UserList {_users = [User {_name = "bob" ...
userList :: ReaderT Client IO (Maybe UserList)
userList = userList' Nothing
-- | Grabs the page of users from your user list (cycles around at the end)
-- > withIntercom client $ nextPage userList
-- Just (UserList {_users = [User {_name = "jim" ...
nextPage :: UserList -> ReaderT Client IO (Maybe UserList)
nextPage u = userList' (show <$> u ^. next)
userList' :: Maybe String -> ReaderT Client IO (Maybe UserList)
userList' u = do
c <- ask
lift $ do
r <- getWith (opts c) (fromMaybe "https://api.intercom.io/users" u)
return $ decode (r ^. responseBody)
-- | Create or update a user in Intercom
-- > let myUser = blankUser & email .~ (Just "[email protected]")
-- > withIntercom client $ createOrUpdateUser myUser
-- Just (User {_name = Nothing, _email = Just "[email protected]", _userId = Nothing, _customAttributes = fromList []})
createOrUpdateUser :: User -> ReaderT Client IO (Maybe User)
createOrUpdateUser u = do
c <- ask
lift $ do
r <- postWith (postOpts c) "https://api.intercom.io/users" (encode u)
return $ decode (r ^. responseBody)
| bobjflong/intercom-haskell | src/Web/Intercom/Types.hs | mit | 4,062 | 0 | 13 | 1,061 | 992 | 534 | 458 | 98 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Smelkov Ilya
-- License : MIT (see the file LICENSE)
-- Maintainer : Smelkov Ilya <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Dotted graphs renderer.
--
-----------------------------------------------------------------------------
module Sanre.Draw (
graphToDot
, graphToDotParams
, vacuumParams
) where
import qualified Data.Map.Strict as Map
import Data.GraphViz hiding (graphToDot)
import Data.GraphViz.Attributes.Complete (
Attribute(RankDir, Splines, FontName)
, RankDir(..), EdgeType(SplineEdges)
)
import Control.Arrow(second)
import qualified Sanre.Types as San
graphToDot :: San.Config -> San.Tree -> DotGraph String
graphToDot config = graphToDotParams params . Map.toList
where
params = vacuumParams config
graphToDotParams :: (Ord a, Ord cl) => GraphvizParams a () () cl l
-> [(a, [a])] -> DotGraph a
graphToDotParams params nes = graphElemsToDot params ns es
where
ns = map (second $ const ()) nes
es = concatMap mkEs nes
mkEs (f,ts) = map (\t -> (f,t,())) ts
vacuumParams :: San.Config -> GraphvizParams a () () () ()
vacuumParams config = defaultParams { globalAttributes = gStyle config }
gStyle :: San.Config -> [GlobalAttributes]
gStyle config =
[ GraphAttrs graphAttrs
, NodeAttrs nodeAttrs
, EdgeAttrs edgeAttrs
]
where
edgeAttrs =
[ color (mapColor (San.color config))
, style solid
]
graphAttrs =
[ RankDir FromBottom
, Splines SplineEdges
, FontName "courier"
]
nodeAttrs =
[ textLabel "\\N"
, shape Hexagon
, fontColor (mapColor (San.fontColor config))
]
mapColor :: San.Color -> X11Color
mapColor San.Blue = Blue
mapColor San.Black = Black
mapColor San.Green = Green
| triplepointfive/sanre | src/Sanre/Draw.hs | mit | 1,993 | 0 | 13 | 452 | 518 | 290 | 228 | 43 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Galua.Debugger.EmbedDirectory where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import System.Directory
import System.FilePath
import Data.List
import qualified Data.ByteString.Char8 as B8
embedDirectory ::
(FilePath -> Bool) {- ^ predicate for inclusion applied to path -} ->
FilePath {- ^ base directory to recursively enumerate -} ->
ExpQ
embedDirectory p root =
do files <- runIO $
do starts <- getDirectoryContents' root
matches <- traverse (getDirTree root) starts
return (filter p (concat matches))
listE
[ do let fn = root </> file
bytes <- runIO (B8.readFile fn)
qAddDependentFile fn
let content = B8.unpack bytes
[| (file, content) |]
| file <- files
]
expandDir :: FilePath -> FilePath -> IO [FilePath]
expandDir base dir =
do kids <- map (dir </>) <$> getDirectoryContents' (base </> dir)
concat <$> traverse (getDirTree base) kids
getDirTree :: FilePath -> FilePath -> IO [FilePath]
getDirTree base fp =
do exists <- doesDirectoryExist (base </> fp)
if exists
then expandDir base fp
else return [fp]
getDirectoryContents' :: FilePath -> IO [FilePath]
getDirectoryContents' dir = delete "." . delete ".."
<$> getDirectoryContents dir
| GaloisInc/galua | galua-dbg/src/Galua/Debugger/EmbedDirectory.hs | mit | 1,370 | 0 | 15 | 344 | 393 | 199 | 194 | 37 | 2 |
{-# LANGUAGE TupleSections #-}
module Y2021.M03.D18.Solution where
-- Remember that exercise where we built a map of keys and indices?
import Y2021.M03.D11.Solution
{--
Now, what we want to do is to have a ... okay, don't panic! ... 'mutable'
map of keys and indicies.
--}
import Data.List (maximum)
import Data.Map (Map)
import qualified Data.Map as Map
import Prelude hiding (lookup)
data LookupTable =
LookupTable { values :: Map String Integer, nextIndex :: Integer }
deriving (Eq, Ord, Show)
-- give an empty lookup table with the first-next index of 1
initLookupTable :: LookupTable
initLookupTable = LookupTable Map.empty 1
-- given a preexisting map, return a lookup table with the max index + 1 as next
toLookupTable :: Map String Integer -> LookupTable
toLookupTable = LookupTable <*> succ . maximum . Map.elems
lookup :: String -> LookupTable -> (Integer, LookupTable)
lookup key l@(LookupTable m idx) =
maybe (idx, LookupTable (Map.insert key idx m) (succ idx))
((,l)) (Map.lookup key m)
{--
>>> let lk = toLookupTable (uniqueIds names)
lookup always succeeds.
If the key is in the lookup table, it returns the index with the existing
LookupTable
If the key is not in the lookup table, it inserts that key with next index,
updates next index and returns the key's index as well as the new lookup table.
What is the index of "Tom"?
>>> lookup "Tom" lk
(1,LookupTable {values = fromList [("Dick",2),("Harry",3),("Tom",1)], nextIndex = 4})
>>> let lk1 = snd it
What is the index of "quux"?
>>> lookup "quux" lk1
(4,LookupTable {values = fromList [("Dick",2),("Harry",3),("Tom",1),("quux",4)], nextIndex = 5})
>>> let lk2 = snd it
What is the index of "Joe"?
>>> let (joeIdx, lk3) = lookup "Joe" lk2
>>> joeIdx
5
On a new request, is the index of "quux" still the same? ("Yes" is correct.)
>>> fst $ lookup "quux" lk3
4
--}
| geophf/1HaskellADay | exercises/HAD/Y2021/M03/D18/Solution.hs | mit | 1,879 | 0 | 10 | 351 | 242 | 140 | 102 | 18 | 1 |
module Language.Combinators
( sCombinator
, kCombinator
, iCombinator
, yCombinator
) where
-- SKI Combinator Logic
sCombinator :: (a -> b -> c) -> (a -> b) -> a -> c
sCombinator f g x = f x (g x)
kCombinator :: a -> b -> b
kCombinator x y = y
k1 :: a -> b -> b
k1 x y = y
iCombinator :: a -> a
iCombinator x = x
-- The fixed point Y combinator
yCombinator :: ((a -> a) -> (a -> a)) -> (a -> a)
yCombinator f = f (y f)
compose :: (s -> t) -> (t1 -> s) -> t1 -> t
compose f g x = f $ g x
twice :: (a -> a) -> a -> a
twice f = f . f
| owainlewis/lambda-calculus | src/Language/Combinators.hs | mit | 549 | 0 | 9 | 153 | 279 | 150 | 129 | 19 | 1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE InstanceSigs #-}
module Cell ( bval0, nval0, sval0, rval0, err0, cfor, cfadd, Cell(..), CellFn(..), emptySheet, printCalcedSheet, nval, bval, sval, rval, eadd, emul, ediv, esub, epow, eand, eor, exor, egt, elt, eeq, econcat, enfunc, ebfunc, esfunc, eref) where
import Text.Printf
import Control.Monad
import Data.Array hiding ((!))
import Data.Foldable hiding (forM_, fold, or)
import Data.Monoid
import Cat
import Ref
import Value
import Expr
import Str
import Sheet
import Refs
-- | This file describes the cell type.
-- It also has a lot of functions to help the parser to create
-- the Cell when it has parsed the string that has been entered in the cell.
-- | A cell must contain one of the 3 Expr types or be empty
data Cell e = CA (Arithmetic e) | CL (Logic e) | CS (Str e) | CR (Refs e) | CE
-- | A show function that leaves out all the type stuff
instance Show e => Show (Cell e) where
show (CA x) = show x
show (CL x) = show x
show (CS x) = show x
show (CR x) = show x
show CE = ""
-- | Just apply f to the contents of the Cell
instance Functor Cell where
fmap f (CA x) = CA $ fmap f x
fmap f (CL x) = CL $ fmap f x
fmap f (CS x) = CS $ fmap f x
fmap f (CR x) = CR $ fmap f x
fmap f CE = CE
-- | Similarly for the Eval instance
instance Monad m => Eval Cell m where
evalAlg :: Cell (m Value) -> m Value
evalAlg (CA x) = evalAlg x
evalAlg (CL x) = evalAlg x
evalAlg (CS x) = evalAlg x
evalAlg (CR x) = evalAlg x
evalAlg (CE) = evalAlg (CS $ SVal "")
unEvalAlg :: (Monad m) => Value -> Cell (m Value)
unEvalAlg (N x) = CA $ AVal x
unEvalAlg (B x) = CL $ LVal x
unEvalAlg (S x) = CS $ SVal x
unEvalAlg (R x) = CR $ Refs x
unEvalAlg (E x) = CE
--csum :: (Monad m ) => [Cell (m Value)] -> Cell (m Value)
--csum [] = CA $ AVal 0.0
--csum (a:[]) = a
--csum (a:as) = CA $ Add (evalAlg a) (evalAlg $ csum as)
--cor :: (Monad m ) => [Cell (m Value)] -> Cell (m Value)
--cor [] = CL $ LVal False
--cor (a:[]) = a
--cor (a:as) = CL $ Or (evalAlg a) (evalAlg $ csum as)
-- | For spreadsheets each cell must have a function in it from the sheet to a Fix Cell
-- then we can use moeb, loeb and the comonad stuff - wfix and cfix
type CellFn = Sheet (Fix Cell) -> Fix Cell
-- | Ors 2 CellFns
-- This uses the or function for the Value type which only works for booleans
-- So, it returns the Fix Cell for the bool or an Error
cfor :: CellFn -> CellFn -> CellFn
cfor x y = \ss -> fixup $ vor (runId $ eval $ x ss) (runId $ eval $ y ss)
where
fixup (B x) = inject $ CL $ LVal x
fixup (_) = inject $ CE
-- | Adds 2 CellFns
-- This uses the add function for the Value type which only works for numbers
-- So, it returns the Fix Cell for the number or an Error
cfadd :: CellFn -> CellFn -> CellFn
cfadd x y = \ss -> fixup $ vadd (runId $ eval $ x ss) (runId $ eval $ y ss)
where
fixup (N z) = nval0 z
fixup (_) = err0
fcadd :: Fix Cell -> Fix Cell -> Fix Cell
fcadd c1 c2 = fixup $ vadd (runId $ eval c1) (runId $ eval c2)
where
fixup (N z) = nval0 z
fixup (_) = err0
-- | Evaluate and print the cellFns here is the LOEB!
--recalcSheet :: Sheet CellFn -> Sheet String
--recalcSheet fs = fmap (show.runId.eval) $ loeb fs
--recalcSheet = recalc
-- | We need to get the refs from a CellFn before the loeb because loeb calcs the
-- references. I wonder if we could get a function similar to loeb to calculate
-- the circular references?
-- | Create an initial sheet - with numbers in it
emptySheet :: Int -> Int -> Sheet CellFn
emptySheet m n = Sheet "Empty" (fromCoords (0,0)) $ listArray (fromCoords (0,0), fromCoords (m-1,n-1)) $ all
where
all :: [CellFn]
all = take (m*n) $ fmap (\i-> nval $ fromIntegral i) [1..]
-- | Print a sheet of Fix Cells - that is a recalculated sheet
printCalcedSheet :: Sheet (Fix Cell) -> IO ()
printCalcedSheet ss =
forM_ [ymin..ymax] $ \i -> do
forM_ [xmin..xmax] $ \j ->
--printf "%s " (show $ (cells wss) ! (fromCoords (j,i)))
printf "%s " (show $ (wss) ! (fromCoords (j,i)))
printf "\n"
where
xmin = x $ cRef $ fst $ bounds $ cells ss
xmax = x $ cRef $ snd $ bounds $ cells ss
ymin = y $ rRef $ fst $ bounds $ cells ss
ymax = y $ rRef $ snd $ bounds $ cells ss
wss = fmap (runId.eval) ss
cout :: Sheet String
cout = fmap (\c -> printf "%s\n" $ show c) ss
xss = fmap (show.runId.eval) $ cells ss
-- | We can inject from a Sheet into a Cell
-- by creating a cell with a reference to the focussed cell of the Sheet
-- PROBLEM: How do we know that the cell is an Aritmetic/CA type?
instance Sheet :<: Cell where
inj :: Sheet a -> Cell a
inj s = CA $ NRef s (focus s)
-- | Some helper functions to inject types into CellFns
-- | Simple constant cells
nval0 :: Double -> Fix Cell
nval0 n = inject $ CA $ AVal n
bval0 :: Bool -> Fix Cell
bval0 n = inject $ CL $ LVal n
sval0 :: String -> Fix Cell
sval0 n = inject $ CS $ SVal n
rval0 :: [Ref] -> Fix Cell
rval0 ns = inject $ CR $ Refs ns
err0 :: Fix Cell
err0 = inject CE
-- | Some helper functions to inject types into CellFns
-- | Simple constant cells
nval :: Double -> CellFn
nval n = finject $ CA $ AVal n
bval :: Bool -> CellFn
bval n = finject $ CL $ LVal n
sval :: String -> CellFn
sval n = finject $ CS $ SVal n
rval :: [Ref] -> CellFn
rval ns = finject $ CR $ Refs ns
-- | An Error cell
noval :: CellFn
noval = finject $ CE
-- | Arithmetic expression functions
eadd :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
eadd x y = \ss -> inject $ CA $ Add (x ss) (y ss)
emul :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
emul x y = \ss -> inject $ CA $ Mul (x ss) (y ss)
ediv :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
ediv x y = \ss -> inject $ CA $ Div (x ss) (y ss)
esub :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
esub x y = \ss -> inject $ CA $ Sub (x ss) (y ss)
epow :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
epow x y = \ss -> inject $ CA $ Pow (x ss) (y ss)
-- | Boolean expression functions
eand :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
eand x y = \ss -> inject $ CL $ And (x ss) (y ss)
eor :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
eor x y = \ss -> inject $ CL $ Or (x ss) (y ss)
exor :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
exor x y = \ss -> inject $ CL $ Xor (x ss) (y ss)
egt :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
egt x y = \ss -> inject $ CL $ LGT (x ss) (y ss)
elt :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
elt x y = \ss -> inject $ CL $ LLT (x ss) (y ss)
eeq :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
eeq x y = \ss -> inject $ CL $ LEQ (x ss) (y ss)
-- String exprtession functions
econcat :: (Cell :<: f) => (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f) -> (Sheet (Fix f) -> Fix f)
econcat x y = \ss -> inject $ CS $ Concat (x ss) (y ss)
-- | The spreadsheet built in functions for each value type
-- These go from a list of functions (ie. the parameters) to a function
-- | Number functions
enfunc :: (Cell :<: f) => String -> [a -> Fix f] -> (a-> Fix f)
enfunc name ps = \ss -> inject $ CA $ NFunc name $ fmap (\p -> p ss) ps
-- | Boolean functions
ebfunc :: (Cell :<: f) => String -> [a -> Fix f] -> (a-> Fix f)
ebfunc name ps = \ss -> inject $ CL $ BFunc name $ fmap (\p -> p ss) ps
-- | String functions
esfunc :: (Cell :<: f) => String -> [a -> Fix f] -> (a-> Fix f)
esfunc name ps = \ss -> inject $ CS $ SFunc name $ fmap (\p -> p ss) ps
-- | References
eref :: Ref -> CellFn
eref r = \ss-> ss!r
| b1g3ar5/Spreadsheet | Cell.hs | mit | 8,320 | 0 | 16 | 2,150 | 3,547 | 1,825 | 1,722 | 130 | 2 |
-- |
-- Module : $Header$
-- Description : Definition of an abstract expression language as the first IR for the Ohua compiler.
-- Copyright : (c) Sebastian Ertel, Justus Adam 2017. All Rights Reserved.
-- License : EPL-1.0
-- Maintainer : [email protected], [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This source code is licensed under the terms described in the associated LICENSE.TXT file
--
-- This module defines the dataflow IR. It introduces the notion of a Flow type
-- and defines a new stateful function execution that works based on flows
-- instead of variables. The ALang IR is transformed straight into the dataflow
-- IR. One important aspect of DFLang: it does not define any abstractions,
-- i.e., there are no function definitions.
--
{-# LANGUAGE DeriveLift, CPP #-}
#include "compat.h"
module Ohua.DFLang.Lang
( DFExpr(..)
, LetExpr(..)
, DFFnRef(.., DFFunction, EmbedSf)
, NodeType(..)
, DFVar(..)
, dfEnvExpr
) where
import Ohua.Prelude
import Language.Haskell.TH.Syntax (Lift)
-- | A sequence of let statements with a terminating binding to be used as return value
data DFExpr = DFExpr
{ letExprs :: Seq LetExpr
, returnVar :: !Binding
} deriving (Eq, Show, Lift, Generic)
data LetExpr = LetExpr
{ callSiteId :: !FnId
, output :: ![Binding]
, functionRef :: !DFFnRef
, stateArgument :: !(Maybe DFVar)
, callArguments :: ![DFVar]
} deriving (Eq, Show, Lift, Generic)
data DFFnRef = DFFnRef
{ nodeType :: NodeType
, nodeRef :: QualifiedBinding
} deriving (Eq, Show, Lift, Generic)
instance Hashable DFFnRef
pattern DFFunction :: QualifiedBinding -> DFFnRef
pattern DFFunction b = DFFnRef OperatorNode b
pattern EmbedSf :: QualifiedBinding -> DFFnRef
pattern EmbedSf b = DFFnRef FunctionNode b
#if COMPLETE_PRAGMA_WORKS
{-# COMPLETE DFFunction, EmbedSf #-}
#endif
data NodeType
= OperatorNode
| FunctionNode
deriving (Eq, Show, Lift, Generic)
instance Hashable NodeType
instance NFData NodeType
data DFVar
= DFEnvVar !Lit
| DFVar !Binding
deriving (Eq, Show, Lift, Generic)
instance Hashable DFVar
instance IsString DFVar where
fromString = DFVar . fromString
instance NFData DFExpr
instance NFData LetExpr
instance NFData DFFnRef
instance NFData DFVar
dfEnvExpr :: HostExpr -> DFVar
dfEnvExpr = DFEnvVar . EnvRefLit
| ohua-dev/ohua-core | core/src/Ohua/DFLang/Lang.hs | epl-1.0 | 2,417 | 2 | 11 | 483 | 460 | 263 | 197 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- |
-- Module: $HEADER$
-- Description: Low level FFI.
-- Copyright:
-- License: GPL-2
--
-- Maintainer: Jan Sipr <[email protected]>
-- Stability: experimental
-- Portability: GHC specific language extensions.
module Phone.Account
( Account(..)
, AccountId
, AuthScheme(..)
, WhenRegister(..)
, createAccount
, isAccountRegistered
, mkSimpleAccount
, registerAccount
, removeAccount
, unregisterAccount
)
where
import Data.Bool (Bool)
import Data.Function (($), (.))
import Data.Monoid ((<>))
import Text.Show (Show)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (ContT(ContT), evalContT)
import Data.Text (Text)
import Phone.Exception
( PhoneException
( CreateAccount
, Registration
, RemoveAccount
, Unregistration
)
)
import Phone.MonadPJ (MonadPJ(liftPJ))
import Phone.Internal.FFI.Account (AccountId)
import qualified Phone.Internal.FFI.Account as FFI
( credDataPlainPasswd
, isAccountRegistered
, removeAccount
, setAccount
, setAccountCredCount
, setAccountData
, setAccountDataType
, setAccountId
, setAccountRealm
, setAccountRegUri
, setAccountRegisterOnAdd
, setAccountRegistration
, setAccountScheme
, setAccountUsername
, withAccountConfig
)
import qualified Phone.Internal.FFI.Common as FFI (pjFalse, pjTrue)
import qualified Phone.Internal.FFI.PjString as FFI (withPjString)
import qualified Phone.Internal.Utils as FFI (check, checkPeek)
data AuthScheme = Digest | Basic
deriving (Show)
data Account = Account
{ accountId :: Text
-- ^ The full SIP URL for the account. The value can take name address or
-- URL format, and will look something like "sip:account@serviceprovider"
-- or "\"Display Name" <sip:account>"
, registrationUri :: Text
, realm :: Text
, authScheme :: AuthScheme
, userName :: Text
, password :: Text
}
deriving (Show)
data WhenRegister = Now | Later
mkSimpleAccount
:: Text -- ^ Sip server domain name or IP
-> Text -- ^ Account name
-> Text -- ^ Password
-> Account
mkSimpleAccount server user password = Account
{ accountId = "sip:" <> user <> "@" <> server
, registrationUri = "sip:" <> server
, realm = "*"
, authScheme = Digest
, userName = user
, password = password
}
createAccount :: MonadPJ m => WhenRegister -> Account -> m AccountId
createAccount whenReg Account{..} = liftPJ . evalContT $ do
accountIdPjStr <- ContT $ FFI.withPjString accountId
registrationUriPjStr <- ContT $ FFI.withPjString registrationUri
realmPjStr <- ContT $ FFI.withPjString realm
schemePjStr <- ContT $ FFI.withPjString (schemeText authScheme)
userNamePjStr <- ContT $ FFI.withPjString userName
passwordPjStr <- ContT $ FFI.withPjString password
accCfg <- ContT FFI.withAccountConfig
lift $ do
FFI.setAccountId accCfg accountIdPjStr
FFI.setAccountRegUri accCfg registrationUriPjStr
FFI.setAccountCredCount accCfg 1
FFI.setAccountRealm accCfg 0 realmPjStr
FFI.setAccountScheme accCfg 0 schemePjStr
FFI.setAccountUsername accCfg 0 userNamePjStr
FFI.setAccountDataType accCfg 0 FFI.credDataPlainPasswd
FFI.setAccountData accCfg 0 passwordPjStr
FFI.setAccountRegisterOnAdd accCfg $ toVal whenReg
FFI.checkPeek CreateAccount $ FFI.setAccount accCfg FFI.pjTrue
where
toVal Now = FFI.pjTrue
toVal Later = FFI.pjFalse
schemeText :: AuthScheme -> Text
schemeText Digest = "digest"
schemeText Basic = "basic"
registerAccount :: MonadPJ m => AccountId -> m ()
registerAccount accId = liftPJ . FFI.check Registration
$ FFI.setAccountRegistration accId FFI.pjTrue
unregisterAccount :: MonadPJ m => AccountId -> m ()
unregisterAccount accId = liftPJ . FFI.check Unregistration
$ FFI.setAccountRegistration accId FFI.pjFalse
isAccountRegistered :: MonadPJ m => AccountId -> m Bool
isAccountRegistered = liftPJ . FFI.isAccountRegistered
removeAccount :: MonadPJ m => AccountId -> m ()
removeAccount accId = liftPJ . FFI.check RemoveAccount
$ FFI.removeAccount accId
| IxpertaSolutions/hsua | src/Phone/Account.hs | gpl-2.0 | 4,336 | 0 | 13 | 928 | 995 | 553 | 442 | 107 | 3 |
{- |
Module : Text.Highlighting.Kate.Styles
Copyright : Copyright (C) 2011 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Styles for rendering annotated source lines.
-}
module Text.Highlighting.Kate.Styles ( pygments, kate, espresso, tango,
haddock, monochrome, zenburn )
where
import Text.Highlighting.Kate.Types
-- | Style based on pygments's default colors.
pygments :: Style
pygments = Style{
backgroundColor = Nothing
, defaultColor = Nothing
, lineNumberColor = toColor "#aaaaaa"
, lineNumberBackgroundColor = Nothing
, tokenStyles =
[ (KeywordTok, defStyle{ tokenColor = toColor "#007020", tokenBold = True })
, (DataTypeTok, defStyle{ tokenColor = toColor "#902000" })
, (DecValTok, defStyle{ tokenColor = toColor "#40a070" })
, (BaseNTok, defStyle{ tokenColor = toColor "#40a070" })
, (FloatTok, defStyle{ tokenColor = toColor "#40a070" })
, (CharTok, defStyle{ tokenColor = toColor "#4070a0" })
, (StringTok, defStyle{ tokenColor = toColor "#4070a0" })
, (CommentTok, defStyle{ tokenColor = toColor "#60a0b0", tokenItalic = True })
, (OtherTok, defStyle{ tokenColor = toColor "#007020" })
, (AlertTok, defStyle{ tokenColor = toColor "#ff0000", tokenBold = True })
, (FunctionTok, defStyle{ tokenColor = toColor "#06287e" })
, (ErrorTok, defStyle{ tokenColor = toColor "#ff0000", tokenBold = True })
]
}
-- | Style based on kate's default colors.
kate :: Style
kate = Style{
backgroundColor = Nothing
, defaultColor = Nothing
, lineNumberColor = Nothing
, lineNumberBackgroundColor = toColor "#dddddd"
, tokenStyles =
[ (KeywordTok, defStyle{ tokenBold = True })
, (DataTypeTok, defStyle{ tokenColor = toColor "#800000" })
, (DecValTok, defStyle{ tokenColor = toColor "#0000FF" })
, (BaseNTok, defStyle{ tokenColor = toColor "#0000FF" })
, (FloatTok, defStyle{ tokenColor = toColor "#800080" })
, (CharTok, defStyle{ tokenColor = toColor "#FF00FF" })
, (StringTok, defStyle{ tokenColor = toColor "#DD0000" })
, (CommentTok, defStyle{ tokenColor = toColor "#808080", tokenItalic = True })
, (AlertTok, defStyle{ tokenColor = toColor "#00ff00", tokenBold = True })
, (FunctionTok, defStyle{ tokenColor = toColor "#000080" })
, (ErrorTok, defStyle{ tokenColor = toColor "#ff0000", tokenBold = True })
]
}
-- | Style based on pygments's tango colors.
tango :: Style
tango = Style{
backgroundColor = toColor "#f8f8f8"
, defaultColor = Nothing
, lineNumberColor = toColor "#aaaaaa"
, lineNumberBackgroundColor = Nothing
, tokenStyles =
[ (KeywordTok, defStyle{ tokenColor = toColor "#204a87", tokenBold = True })
, (DataTypeTok, defStyle{ tokenColor = toColor "#204a87" })
, (DecValTok, defStyle{ tokenColor = toColor "#0000cf" })
, (BaseNTok, defStyle{ tokenColor = toColor "#0000cf" })
, (FloatTok, defStyle{ tokenColor = toColor "#0000cf" })
, (CharTok, defStyle{ tokenColor = toColor "#4e9a06" })
, (StringTok, defStyle{ tokenColor = toColor "#4e9a06" })
, (CommentTok, defStyle{ tokenColor = toColor "#8f5902", tokenItalic = True })
, (OtherTok, defStyle{ tokenColor = toColor "#8f5902" })
, (AlertTok, defStyle{ tokenColor = toColor "#ef2929" })
, (FunctionTok, defStyle{ tokenColor = toColor "#000000" })
, (ErrorTok, defStyle{ tokenColor = toColor "a40000", tokenBold = True })
]
}
-- | Style based on ultraviolet's espresso_libre.css (dark background).
espresso :: Style
espresso = Style{
backgroundColor = toColor "#2A211C"
, defaultColor = toColor "#BDAE9D"
, lineNumberColor = toColor "#BDAE9D"
, lineNumberBackgroundColor = toColor "#2A211C"
, tokenStyles =
[ (KeywordTok, defStyle{ tokenColor = toColor "#43A8ED", tokenBold = True })
, (DataTypeTok, defStyle{ tokenUnderline = True })
, (DecValTok, defStyle{ tokenColor = toColor "#44AA43" })
, (BaseNTok, defStyle{ tokenColor = toColor "#44AA43" })
, (FloatTok, defStyle{ tokenColor = toColor "#44AA43" })
, (CharTok, defStyle{ tokenColor = toColor "#049B0A" })
, (StringTok, defStyle{ tokenColor = toColor "#049B0A" })
, (CommentTok, defStyle{ tokenColor = toColor "#0066FF", tokenItalic = True })
, (AlertTok, defStyle{ tokenColor = toColor "#ffff00" })
, (FunctionTok, defStyle{ tokenColor = toColor "#FF9358", tokenBold = True })
, (ErrorTok, defStyle{ tokenColor = toColor "ffff00", tokenBold = True })
]
}
-- | Style based on haddock's source highlighting.
haddock :: Style
haddock = Style{
backgroundColor = Nothing
, defaultColor = Nothing
, lineNumberColor = toColor "#aaaaaa"
, lineNumberBackgroundColor = Nothing
, tokenStyles =
[ (KeywordTok, defStyle{ tokenColor = toColor "#0000FF" })
, (CharTok, defStyle{ tokenColor = toColor "#008080" })
, (StringTok, defStyle{ tokenColor = toColor "#008080" })
, (CommentTok, defStyle{ tokenColor = toColor "#008000" })
, (OtherTok, defStyle{ tokenColor = toColor "#ff4000" })
, (AlertTok, defStyle{ tokenColor = toColor "#ff0000" })
, (ErrorTok, defStyle{ tokenColor = toColor "ff0000", tokenBold = True })
]
}
-- | Style with no colors.
monochrome :: Style
monochrome = Style{
backgroundColor = Nothing
, defaultColor = Nothing
, lineNumberColor = Nothing
, lineNumberBackgroundColor = Nothing
, tokenStyles =
[ (KeywordTok, defStyle{ tokenBold = True })
, (DataTypeTok, defStyle{ tokenUnderline = True })
, (CommentTok, defStyle{ tokenItalic = True })
, (AlertTok, defStyle{ tokenBold = True })
, (ErrorTok, defStyle{ tokenBold = True })
]
}
-- | Style based on the popular zenburn vim color scheme
zenburn :: Style
zenburn = Style{
backgroundColor = toColor "#303030"
, defaultColor = toColor "#cccccc"
, lineNumberColor = Nothing
, lineNumberBackgroundColor = Nothing
, tokenStyles =
[ (KeywordTok, defStyle{ tokenColor = toColor "#f0dfaf" })
, (DataTypeTok, defStyle{ tokenColor = toColor "#dfdfbf" })
, (DecValTok, defStyle{ tokenColor = toColor "#dcdccc" })
, (BaseNTok, defStyle{ tokenColor = toColor "#dca3a3" })
, (FloatTok, defStyle{ tokenColor = toColor "#c0bed1" })
, (CharTok, defStyle{ tokenColor = toColor "#dca3a3" })
, (StringTok, defStyle{ tokenColor = toColor "#cc9393" })
, (CommentTok, defStyle{ tokenColor = toColor "#7f9f7f" })
, (OtherTok, defStyle{ tokenColor = toColor "#efef8f" })
, (AlertTok, defStyle{ tokenColor = toColor "#ffcfaf" })
, (FunctionTok, defStyle{ tokenColor = toColor "#efef8f" })
, (ErrorTok, defStyle{ tokenColor = toColor "#c3bf9f" })
]
}
| sapek/highlighting-kate | Text/Highlighting/Kate/Styles.hs | gpl-2.0 | 6,792 | 0 | 11 | 1,388 | 1,842 | 1,127 | 715 | 122 | 1 |
{- |
Module : FMP.Frames
Copyright : (c) 2003-2010 Peter Simons
(c) 2002-2003 Ferenc Wágner
(c) 2002-2003 Meik Hellmund
(c) 1998-2002 Ralf Hinze
(c) 1998-2002 Joachim Korittky
(c) 1998-2002 Marco Kuhlmann
License : GPLv3
Maintainer : [email protected]
Stability : provisional
Portability : portable
-}
{-
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
-}
module FMP.Frames (
drum, diamond, fuzzy, cloud
) where
import FMP.Types
import FMP.Picture
diamond :: Picture -> Picture
diamond p = Frame stdFrameAttrib eqs path p
where
eqs = [
var "d" .= 2+0.6*dist (ref ("last" <+ SW)) (ref ("last" <+ NE)),
ref C .= ref ("last" <+ C),
ref N .= ref ("last" <+ C) + vec(0,var "d"),
ref E .= ref ("last" <+ C) + vec(var "d",0),
ref S .= ref ("last" <+ C) - vec(0,var "d"),
ref W .= ref ("last" <+ C) - vec(var "d",0),
ref NE .= med 0.5 (ref N) (ref E),
ref SE .= med 0.5 (ref S) (ref E),
ref SW .= med 0.5 (ref S) (ref W),
ref NW .= med 0.5 (ref N) (ref W)
]
path = ref N .-. ref E .-. ref S .-. ref W .-. cycle'
fuzzy :: Int -> Int -> Picture -> Picture
fuzzy s1 s2 p = Frame stdFrameAttrib eqs path p
where
eqs = [
var "d" .= 0.5*dist (ref ("last" <+ NW)) (ref ("last" <+ SE)),
ref C .= ref ("last" <+ C),
ref E .= disort 0,
ref SE .= disort 1,
ref S .= disort 2,
ref SW .= disort 3,
ref W .= disort 4,
ref NW .= disort 5,
ref N .= disort 6,
ref NE .= disort 7
]
path = ((((((((ref E
... ref SE # setEndAngle (90+r' 21))
... ref S # setEndAngle (135+r' 22))
... ref SW # setEndAngle (180+r' 23))
... ref W # setEndAngle (225+r' 24))
... ref NW # setEndAngle (270+r' 25))
... ref N # setEndAngle (315+r' 26))
... ref NE # setEndAngle (0+r' 26))
... cycle' # setEndAngle (45+r' 26))
r i = realToFrac (randomDoubles s1 s2!!i)
r' i = realToFrac (40*(randomDoubles s1 s2!!i-0.5))
disort i = ref ("last" <+ C)
+ (var "d"*(1+0.5*r (2*i+1)))
.* dir (Numeric (fromIntegral i)*45+r' (2*i+2))
cloud :: Int -> Int -> Picture -> Picture
cloud s1 s2 p = Frame stdFrameAttrib eqs path p
where
eqs = [
var "d" .= 0.5*dist (ref ("last" <+ NW)) (ref ("last" <+ SE)),
ref C .= ref ("last" <+ C),
ref E .= disort 0,
ref SE .= disort 1,
ref S .= disort 2,
ref SW .= disort 3,
ref W .= disort 4,
ref NW .= disort 5,
ref N .= disort 6,
ref NE .= disort 7
]
path = ((((((((ref E
... ref SE # setEndAngle (90+r' 21)# setStartAngle (r' 21))
... ref S # setEndAngle (135+r' 22)# setStartAngle (r' 22))
... ref SW # setEndAngle (180+r' 23)# setStartAngle (r' 23))
... ref W # setEndAngle (225+r' 24)# setStartAngle (r' 24))
... ref NW # setEndAngle (270+r' 25)# setStartAngle (r' 25))
... ref N # setEndAngle (315+r' 26)# setStartAngle (r' 26))
... ref NE # setEndAngle (0+r' 26))
... cycle' # setEndAngle (45+r' 26))
r i = realToFrac (randomDoubles s1 s2!!i)
r' i = realToFrac (40*(randomDoubles s1 s2!!i-0.5))
disort i = ref ("last" <+ C)
+ (var "d"*(1+0.5*r (2*i+1)))
.* dir (Numeric (fromIntegral i)*45+r' (2*i+2))
drum :: IsPicture a => a -> Frame
drum p = Frame' stdFrameAttrib
stdExtentAttrib{eaEqs = eqs,
eaEqsDX = eqsDX,
eaEqsDY = eqsDY,
eaEqsWidth = eqsWidth,
eaEqsHeight = eqsHeight}
path
(toPicture p)
where
eqsDX = [ref E .= ref ("last" <+ E) + vec(var "dx",0),
ref W .= ref ("last" <+ W) - vec(var "dx",0) ]
eqsDY = [ref N .= ref ("last" <+ N) + vec(0,var "dy"+var "d"),
ref S .= ref ("last" <+ S) - vec(0,var "dy"+var "d") ]
eqsWidth = [ref E .= ref W + vec(var "width",0),
ref C - ref W .= ref E - ref C ]
eqsHeight = [ref N .= ref S + vec(0,var "height"+2*var "d"),
ref C - ref S .= ref N - ref C ]
eqs = [ref C .= ref ("last" <+ C),
var "d" .= 0.10*xpart(ref E-ref W),
xpart (ref NE) .= xpart (ref SE),
ypart (ref NW) .= ypart (ref NE),
ref W .= med 0.5 (ref NW) (ref SW),
ref S .= med 0.5 (ref SW) (ref SE),
ref E .= med 0.5 (ref NE) (ref SE),
ref N .= med 0.5 (ref NE) (ref NW)]
path = ref NW .--. (ref SW .... ref S+vec(0,-var "d").... ref SE # setJoin (joinTension (tensionAtLeast 1.7)))
.--. (ref NE .... ref N+vec(0,var "d") .... ref NW
.... ref N+vec(0,-var "d") .... ref NE .... ref N+vec(0,var "d") .... cycle' # setJoin (joinTension (tensionAtLeast 1.7)))
random2Ints :: Int -> Int -> [Int]
random2Ints s1 s2 = if 1 <= s1 && s1 <= 2147483562 then
if 1 <= s2 && s2 <= 2147483398 then
rands s1 s2
else
error "random2Ints: Bad second seed."
else
error "random2Ints: Bad first seed."
rands :: Int -> Int -> [Int]
rands s1 s2 = let
k = s1 `div` 53668
s1' = 40014 * (s1 - k * 53668) - k * 12211
s1'' = if s1' < 0 then s1' + 2147483563 else s1'
k' = s2 `div` 52774
s2' = 40692 * (s2 - k' * 52774) - k' * 3791
s2'' = if s2' < 0 then s2' + 2147483399 else s2'
z = s1'' - s2''
in if z < 1 then z + 2147483562 : rands s1'' s2''
else z : rands s1'' s2''
randomDoubles :: Int -> Int -> [Double]
randomDoubles s1 s2 = map (\x -> fromIntegral x * 4.6566130638969828e-10)
(random2Ints s1 s2)
| peti/funcmp | FMP/Frames.hs | gpl-3.0 | 9,185 | 2 | 39 | 4,905 | 2,791 | 1,386 | 1,405 | 120 | 4 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Kinesis.CreateStream
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Creates a Amazon Kinesis stream. A stream captures and transports data
-- records that are continuously emitted from different data sources or /producers/
-- . Scale-out within an Amazon Kinesis stream is explicitly supported by means
-- of shards, which are uniquely identified groups of data records in an Amazon
-- Kinesis stream.
--
-- You specify and control the number of shards that a stream is composed of.
-- Each open shard can support up to 5 read transactions per second, up to a
-- maximum total of 2 MB of data read per second. Each shard can support up to
-- 1000 records written per second, up to a maximum total of 1 MB data written
-- per second. You can add shards to a stream if the amount of data input
-- increases and you can remove shards if the amount of data input decreases.
--
-- The stream name identifies the stream. The name is scoped to the AWS account
-- used by the application. It is also scoped by region. That is, two streams in
-- two different accounts can have the same name, and two streams in the same
-- account, but in two different regions, can have the same name.
--
-- 'CreateStream' is an asynchronous operation. Upon receiving a 'CreateStream'
-- request, Amazon Kinesis immediately returns and sets the stream status to 'CREATING'. After the stream is created, Amazon Kinesis sets the stream status to 'ACTIVE'
-- . You should perform read and write operations only on an 'ACTIVE' stream.
--
-- You receive a 'LimitExceededException' when making a 'CreateStream' request if
-- you try to do one of the following:
--
-- Have more than five streams in the 'CREATING' state at any point in time. Create more shards than are authorized for your account.
-- For the default shard limit for an AWS account, see <http://docs.aws.amazon.com/kinesis/latest/dev/service-sizes-and-limits.html Amazon Kinesis Limits>.
-- If you need to increase this limit, <http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html contact AWS Support>
--
-- You can use 'DescribeStream' to check the stream status, which is returned in 'StreamStatus'.
--
-- 'CreateStream' has a limit of 5 transactions per second per account.
--
-- <http://docs.aws.amazon.com/kinesis/latest/APIReference/API_CreateStream.html>
module Network.AWS.Kinesis.CreateStream
(
-- * Request
CreateStream
-- ** Request constructor
, createStream
-- ** Request lenses
, csShardCount
, csStreamName
-- * Response
, CreateStreamResponse
-- ** Response constructor
, createStreamResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.Kinesis.Types
import qualified GHC.Exts
data CreateStream = CreateStream
{ _csShardCount :: Nat
, _csStreamName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'CreateStream' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'csShardCount' @::@ 'Natural'
--
-- * 'csStreamName' @::@ 'Text'
--
createStream :: Text -- ^ 'csStreamName'
-> Natural -- ^ 'csShardCount'
-> CreateStream
createStream p1 p2 = CreateStream
{ _csStreamName = p1
, _csShardCount = withIso _Nat (const id) p2
}
-- | The number of shards that the stream will use. The throughput of the stream
-- is a function of the number of shards; more shards are required for greater
-- provisioned throughput.
--
-- DefaultShardLimit;
csShardCount :: Lens' CreateStream Natural
csShardCount = lens _csShardCount (\s a -> s { _csShardCount = a }) . _Nat
-- | A name to identify the stream. The stream name is scoped to the AWS account
-- used by the application that creates the stream. It is also scoped by region.
-- That is, two streams in two different AWS accounts can have the same name,
-- and two streams in the same AWS account, but in two different regions, can
-- have the same name.
csStreamName :: Lens' CreateStream Text
csStreamName = lens _csStreamName (\s a -> s { _csStreamName = a })
data CreateStreamResponse = CreateStreamResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'CreateStreamResponse' constructor.
createStreamResponse :: CreateStreamResponse
createStreamResponse = CreateStreamResponse
instance ToPath CreateStream where
toPath = const "/"
instance ToQuery CreateStream where
toQuery = const mempty
instance ToHeaders CreateStream
instance ToJSON CreateStream where
toJSON CreateStream{..} = object
[ "StreamName" .= _csStreamName
, "ShardCount" .= _csShardCount
]
instance AWSRequest CreateStream where
type Sv CreateStream = Kinesis
type Rs CreateStream = CreateStreamResponse
request = post "CreateStream"
response = nullResponse CreateStreamResponse
| romanb/amazonka | amazonka-kinesis/gen/Network/AWS/Kinesis/CreateStream.hs | mpl-2.0 | 5,805 | 0 | 10 | 1,167 | 476 | 302 | 174 | 55 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.AppsLicensing
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- The Google Enterprise License Manager API\'s allows you to license apps
-- for all the users of a domain managed by you.
--
-- /See:/ <https://developers.google.com/admin-sdk/licensing/ Enterprise License Manager API Reference>
module Network.Google.AppsLicensing
(
-- * Service Configuration
appsLicensingService
-- * OAuth Scopes
, appsLicensingScope
-- * API Declaration
, AppsLicensingAPI
-- * Resources
-- ** licensing.licenseAssignments.delete
, module Network.Google.Resource.Licensing.LicenseAssignments.Delete
-- ** licensing.licenseAssignments.get
, module Network.Google.Resource.Licensing.LicenseAssignments.Get
-- ** licensing.licenseAssignments.insert
, module Network.Google.Resource.Licensing.LicenseAssignments.Insert
-- ** licensing.licenseAssignments.listForProduct
, module Network.Google.Resource.Licensing.LicenseAssignments.ListForProduct
-- ** licensing.licenseAssignments.listForProductAndSku
, module Network.Google.Resource.Licensing.LicenseAssignments.ListForProductAndSKU
-- ** licensing.licenseAssignments.patch
, module Network.Google.Resource.Licensing.LicenseAssignments.Patch
-- ** licensing.licenseAssignments.update
, module Network.Google.Resource.Licensing.LicenseAssignments.Update
-- * Types
-- ** LicenseAssignmentInsert
, LicenseAssignmentInsert
, licenseAssignmentInsert
, laiUserId
-- ** LicenseAssignmentList
, LicenseAssignmentList
, licenseAssignmentList
, lalEtag
, lalNextPageToken
, lalKind
, lalItems
-- ** Empty
, Empty
, empty
-- ** LicenseAssignment
, LicenseAssignment
, licenseAssignment
, laProductName
, laEtags
, laSKUName
, laKind
, laSKUId
, laUserId
, laSelfLink
, laProductId
-- ** Xgafv
, Xgafv (..)
) where
import Network.Google.Prelude
import Network.Google.AppsLicensing.Types
import Network.Google.Resource.Licensing.LicenseAssignments.Delete
import Network.Google.Resource.Licensing.LicenseAssignments.Get
import Network.Google.Resource.Licensing.LicenseAssignments.Insert
import Network.Google.Resource.Licensing.LicenseAssignments.ListForProduct
import Network.Google.Resource.Licensing.LicenseAssignments.ListForProductAndSKU
import Network.Google.Resource.Licensing.LicenseAssignments.Patch
import Network.Google.Resource.Licensing.LicenseAssignments.Update
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Enterprise License Manager API service.
type AppsLicensingAPI =
LicenseAssignmentsInsertResource :<|>
LicenseAssignmentsPatchResource
:<|> LicenseAssignmentsGetResource
:<|> LicenseAssignmentsListForProductAndSKUResource
:<|> LicenseAssignmentsListForProductResource
:<|> LicenseAssignmentsDeleteResource
:<|> LicenseAssignmentsUpdateResource
| brendanhay/gogol | gogol-apps-licensing/gen/Network/Google/AppsLicensing.hs | mpl-2.0 | 3,430 | 0 | 10 | 579 | 300 | 225 | 75 | 56 | 0 |
module HomeSpec
( spec
) where
import TestImport
import TestTools
spec :: Spec
spec = withApp $
describe "test homepage for unauthenticated user" $ do
it "loads the index and checks it looks right" $ do
get HomeR
statusIs 200
htmlAllContain "h1" "Betty is a diabetes logbook."
htmlAnyContain "a" "Betty"
htmlAnyContain "a" "Log in"
htmlAnyContain "a" "Register"
htmlAnyContain "a" "About"
htmlAnyContain "a" "Contact"
htmlAnyContain "a" "Terms of Use"
htmlAnyContain "a" "Privacy Policy"
it "Requires login" $
needsLogin GET ("/history/bg" :: Text)
{--
request $ do
setMethod "POST"
setUrl HomeR
addNonce
fileByLabel "Choose a file" "tests/main.hs" "text/plain" -- talk about self-reference
byLabel "What's on the file?" "Some Content"
statusIs 200
printBody
htmlCount ".message" 1
htmlAllContain ".message" "Some Content"
htmlAllContain ".message" "text/plain"
--}
-- This is a simple example of using a database access in a test. The
-- test will succeed for a fresh scaffolded site with an empty database,
-- but will fail on an existing database with a non-empty user table.
it "leaves the user table empty" $ do
get HomeR
statusIs 200
users <- runDB $ selectList ([] :: [Filter User]) []
assertEq "user table empty" 0 $ length users
| sajith/betty-web | test/HomeSpec.hs | agpl-3.0 | 1,642 | 0 | 16 | 596 | 216 | 97 | 119 | 25 | 1 |
{-# LANGUAGE TypeFamilies, DeriveDataTypeable #-}
-- | SSH commands protocol. Uses ssh, scp commands
-- to send commands and files.
module THIS.Protocols.SSHCommands
(SSHCommands (..)
) where
import Control.Monad
import Control.Monad.Trans
import Control.Concurrent.STM
import System.Process
import System.Exit
import Text.Printf
import Data.Conduit
import Data.Generics
import THIS.Types
import THIS.Util
import THIS.Protocols.Types
data SSHCommands = SSHCommands ConnectionInfo
deriving (Data, Typeable)
instance Protocol SSHCommands where
initializeProtocol _ = return ()
deinitializeProtocol _ = return ()
connect cfg = return (SSHCommands cfg)
disconnect _ = return ()
runSSH :: ConnectionInfo -> [String] -> IO (Int, String)
runSSH cfg params = do
(ec, out, _) <- readProcessWithExitCode "ssh"
(show cfg: params)
""
return (rc2int ec, out)
instance CommandProtocol SSHCommands where
data RCHandle SSHCommands = V (TVar Int)
runCommands (SSHCommands cfg) commands = do
var <- newTVarIO 1
return (V var, sourceState commands (pull var))
where
pull _ [] = return StateClosed
pull var (cmd:other) = do
(rc, out) <- liftIO $ runSSH cfg [cmd]
liftIO $ atomically $ writeTVar var rc
return $ StateOpen other out
getExitStatus (V var) = atomically $ readTVar var
changeWorkingDirectory _ _ = fail "chdir not implemented"
instance FilesProtocol SSHCommands where
sendFile (SSHCommands cfg) local remote = do
let command = printf "scp %s %s:%s" local (show cfg) remote
ec <- system command
case ec of
ExitSuccess -> return ()
ExitFailure n -> fail $ printf "SCP: %s: error: %s" command (show n)
makeRemoteDirectory (SSHCommands cfg) path = do
runSSH cfg ["mkdir", path]
return ()
sendTree (SSHCommands cfg) local remote = do
let command = printf "scp -r %s %s:%s" local (show cfg) remote
ec <- system command
case ec of
ExitSuccess -> return ()
ExitFailure n -> fail $ printf "SCP: %s: error: %s" command (show n)
receiveFile (SSHCommands cfg) remote local = do
let command = printf "scp %s:%s %s" (show cfg) remote local
ec <- system command
case ec of
ExitSuccess -> return ()
ExitFailure n -> fail $ printf "SCP: %s: error: %s" command (show n)
receiveTree (SSHCommands cfg) remote local = do
let command = printf "scp -r %s:%s %s" (show cfg) remote local
ec <- system command
case ec of
ExitSuccess -> return ()
ExitFailure n -> fail $ printf "SCP: %s: error: %s" command (show n)
| portnov/integration-server | THIS/Protocols/SSHCommands.hs | lgpl-3.0 | 2,639 | 4 | 15 | 629 | 875 | 427 | 448 | 67 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-|
Module providing Bitcoin script evaluation. See
<https://github.com/bitcoin/bitcoin/blob/master/src/script.cpp>
EvalScript and <https://en.bitcoin.it/wiki/Script>
-}
module Network.Haskoin.Script.Evaluator
(
-- * Script evaluation
verifySpend
, evalScript
, SigCheck
, Flag
-- * Evaluation data types
, ProgramData
, Stack
-- * Helper functions
, encodeInt
, decodeInt
, decodeFullInt
, cltvEncodeInt
, cltvDecodeInt
, encodeBool
, decodeBool
, runStack
, checkStack
, dumpScript
, dumpStack
, execScript
) where
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Data.Bits (clearBit, setBit, shiftL,
shiftR, testBit, (.&.))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Either (rights)
import Data.Int (Int64)
import Data.Maybe (isJust, mapMaybe)
import Data.Serialize (decode, encode)
import Data.String.Conversions (cs)
import Data.Word (Word32, Word64, Word8)
import Network.Haskoin.Crypto
import Network.Haskoin.Script.SigHash
import Network.Haskoin.Script.Types
import Network.Haskoin.Transaction.Types
import Network.Haskoin.Util
maxScriptSize :: Int
maxScriptSize = 10000
maxScriptElementSize :: Int
maxScriptElementSize = 520
maxStackSize :: Int
maxStackSize = 1000
maxOpcodes :: Int
maxOpcodes = 200
maxKeysMultisig :: Int
maxKeysMultisig = 20
data Flag = P2SH
| STRICTENC
| DERSIG
| LOW_S
| NULLDUMMY
| SIGPUSHONLY
| MINIMALDATA
| DISCOURAGE_UPGRADABLE_NOPS
deriving ( Show, Read, Eq )
type FlagSet = [ Flag ]
data EvalError =
EvalError String
| ProgramError String ProgramData
| StackError ScriptOp
| DisabledOp ScriptOp
instance Show EvalError where
show (EvalError m) = m
show (ProgramError m prog) = m ++ " - ProgramData: " ++ show prog
show (StackError op) = show op ++ ": Stack Error"
show (DisabledOp op) = show op ++ ": disabled"
type StackValue = [Word8]
type AltStack = [StackValue]
type Stack = [StackValue]
type HashOps = [ScriptOp] -- the code that is verified by OP_CHECKSIG
-- | Defines the type of function required by script evaluating
-- functions to check transaction signatures.
type SigCheck = [ScriptOp] -> TxSignature -> PubKey -> Bool
-- | Data type of the evaluation state.
data ProgramData = ProgramData {
stack :: Stack,
altStack :: AltStack,
hashOps :: HashOps,
sigCheck :: SigCheck,
opCount :: Int
}
dumpOp :: ScriptOp -> ByteString
dumpOp (OP_PUSHDATA payload optype) = mconcat
[ "OP_PUSHDATA(", cs (show optype), ")", " 0x", encodeHex payload ]
dumpOp op = cs $ show op
dumpList :: [ByteString] -> ByteString
dumpList xs = mconcat [ "[", BS.intercalate "," xs, "]" ]
dumpScript :: [ScriptOp] -> ByteString
dumpScript script = dumpList $ map dumpOp script
dumpStack :: Stack -> ByteString
dumpStack s = dumpList $ map (encodeHex . BS.pack) s
-- TODO: Test
instance Show ProgramData where
show p = "stack: " ++ cs (dumpStack $ stack p)
type ProgramState = ExceptT EvalError Identity
type IfStack = [Bool]
-- | Monad of actions independent of conditional statements.
type StackOperation = ReaderT FlagSet ( StateT ProgramData ProgramState )
-- | Monad of actions which taking if statements into account.
-- Separate state type from StackOperation for type safety
type Program a = StateT IfStack StackOperation a
evalStackOperation :: StackOperation a -> ProgramData -> FlagSet -> Either EvalError a
evalStackOperation m s f = runIdentity . runExceptT $ evalStateT ( runReaderT m f ) s
evalProgram :: Program a -- ^ ProgramData monad
-> [ Bool ] -- ^ Initial if state stack
-> ProgramData -- ^ Initial computation data
-> FlagSet -- ^ Evaluation Flags
-> Either EvalError a
evalProgram m s = evalStackOperation ( evalStateT m s )
--------------------------------------------------------------------------------
-- Error utils
programError :: String -> StackOperation a
programError s = get >>= throwError . ProgramError s
disabled :: ScriptOp -> StackOperation ()
disabled = throwError . DisabledOp
--------------------------------------------------------------------------------
-- Type Conversions
-- | Encoding function for the stack value format of integers. Most
-- significant bit defines sign.
-- Note that this function will encode any Int64 into a StackValue,
-- thus producing stack-encoded integers which are not valid numeric
-- opcodes, as they exceed 4 bytes in length.
encodeInt :: Int64 -> StackValue
encodeInt i = prefix $ encod (fromIntegral $ abs i) []
where encod :: Word64 -> StackValue -> StackValue
encod 0 bytes = bytes
encod j bytes = fromIntegral j:encod (j `shiftR` 8) bytes
prefix :: StackValue -> StackValue
prefix [] = []
prefix xs | testBit (last xs) 7 = prefix $ xs ++ [0]
| i < 0 = init xs ++ [setBit (last xs) 7]
| otherwise = xs
-- | Decode an Int64 from the stack value integer format.
-- Inverse of `encodeInt`.
-- Note that only integers decoded by 'decodeInt' are valid
-- numeric opcodes (numeric opcodes can only be up to 4 bytes in size).
-- However, in the case of eg. CHECKLOCKTIMEVERIFY, we need to
-- be able to encode and decode stack integers up to
-- (maxBound :: Word32), which are 5 bytes.
decodeFullInt :: StackValue -> Maybe Int64
decodeFullInt bytes
| length bytes > 8 = Nothing
| otherwise = Just $ sign' (decodeW bytes)
where decodeW [] = 0
decodeW [x] = fromIntegral $ clearBit x 7
decodeW (x:xs) = fromIntegral x + decodeW xs `shiftL` 8
sign' i | null bytes = 0
| testBit (last bytes) 7 = -i
| otherwise = i
-- | Used for decoding numeric opcodes. Will not return
-- an integer that takes up more than
-- 4 bytes on the stack (the size limit for numeric opcodes).
-- The naming is kept for backwards compatibility.
decodeInt :: StackValue -> Maybe Int64
decodeInt bytes | length bytes > 4 = Nothing
| otherwise = decodeFullInt bytes
-- | Decode the integer argument to OP_CHECKLOCKTIMEVERIFY (CLTV)
-- from a stack value.
-- The full uint32 range is needed in order to represent timestamps
-- for use with CLTV. Reference:
-- https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki#Detailed_Specification
cltvDecodeInt :: StackValue -> Maybe Word32
cltvDecodeInt bytes
| length bytes > 5 = Nothing
| otherwise = decodeFullInt bytes >>= uint32Bounds
where
uint32Bounds :: Int64 -> Maybe Word32
uint32Bounds i64
| i64 < 0 || i64 > fromIntegral (maxBound :: Word32) = Nothing
| otherwise = Just $ fromIntegral i64
-- | Helper function for encoding the argument to OP_CHECKLOCKTIMEVERIFY
cltvEncodeInt :: Word32 -> StackValue
cltvEncodeInt = encodeInt . fromIntegral
-- | Conversion of StackValue to Bool (true if non-zero).
decodeBool :: StackValue -> Bool
decodeBool [] = False
decodeBool [0x00] = False
decodeBool [0x80] = False
decodeBool (0x00:vs) = decodeBool vs
decodeBool _ = True
encodeBool :: Bool -> StackValue
encodeBool True = [1]
encodeBool False = []
constValue :: ScriptOp -> Maybe StackValue
constValue op = case op of
OP_0 -> Just $ encodeInt 0
OP_1 -> Just $ encodeInt 1
OP_2 -> Just $ encodeInt 2
OP_3 -> Just $ encodeInt 3
OP_4 -> Just $ encodeInt 4
OP_5 -> Just $ encodeInt 5
OP_6 -> Just $ encodeInt 6
OP_7 -> Just $ encodeInt 7
OP_8 -> Just $ encodeInt 8
OP_9 -> Just $ encodeInt 9
OP_10 -> Just $ encodeInt 10
OP_11 -> Just $ encodeInt 11
OP_12 -> Just $ encodeInt 12
OP_13 -> Just $ encodeInt 13
OP_14 -> Just $ encodeInt 14
OP_15 -> Just $ encodeInt 15
OP_16 -> Just $ encodeInt 16
OP_1NEGATE -> Just $ encodeInt $ -1
(OP_PUSHDATA string _) -> Just $ BS.unpack string
_ -> Nothing
-- | Check if OpCode is constant
isConstant :: ScriptOp -> Bool
isConstant = isJust . constValue
-- | Check if OpCode is disabled
isDisabled :: ScriptOp -> Bool
isDisabled op = op `elem` [ OP_CAT
, OP_SUBSTR
, OP_LEFT
, OP_RIGHT
, OP_INVERT
, OP_AND
, OP_OR
, OP_XOR
, OP_2MUL
, OP_2DIV
, OP_MUL
, OP_DIV
, OP_MOD
, OP_LSHIFT
, OP_RSHIFT
, OP_VER
, OP_VERIF
, OP_VERNOTIF ]
-- | Check if OpCode counts towards opcount limit
countOp :: ScriptOp -> Bool
countOp op | isConstant op = False
| op == OP_RESERVED = False
| otherwise = True
popInt :: StackOperation Int64
popInt = minimalStackValEnforcer >> decodeInt <$> popStack >>= \case
Nothing -> programError "popInt: data > nMaxNumSize"
Just i -> return i
pushInt :: Int64 -> StackOperation ()
pushInt = pushStack . encodeInt
popBool :: StackOperation Bool
popBool = decodeBool <$> popStack
pushBool :: Bool -> StackOperation ()
pushBool = pushStack . encodeBool
opToSv :: StackValue -> ByteString
opToSv = BS.pack
bsToSv :: ByteString -> StackValue
bsToSv = BS.unpack
--------------------------------------------------------------------------------
-- Stack Primitives
getStack :: StackOperation Stack
getStack = stack <$> get
getCond :: Program [Bool]
getCond = get
popCond :: Program Bool
popCond = get >>= \case
[] -> lift $ programError "popCond: empty condStack"
(x:xs) -> put xs >> return x
pushCond :: Bool -> Program ()
pushCond c = get >>= \s ->
put (c:s)
flipCond :: Program ()
flipCond = popCond >>= pushCond . not
withStack :: StackOperation Stack
withStack = getStack >>= \case
[] -> stackError
s -> return s
putStack :: Stack -> StackOperation ()
putStack st = modify $ \p -> p { stack = st }
prependStack :: Stack -> StackOperation ()
prependStack s = getStack >>= \s' -> putStack $ s ++ s'
checkPushData :: ScriptOp -> StackOperation ()
checkPushData (OP_PUSHDATA v _) | BS.length v > fromIntegral maxScriptElementSize
= programError "OP_PUSHDATA > maxScriptElementSize"
| otherwise = return ()
checkPushData _ = return ()
checkStackSize :: StackOperation ()
checkStackSize = do n <- length . stack <$> get
m <- length . altStack <$> get
when ((n + m) > fromIntegral maxStackSize) $
programError "stack > maxStackSize"
pushStack :: StackValue -> StackOperation ()
pushStack v = getStack >>= \s -> putStack (v:s)
popStack :: StackOperation StackValue
popStack = withStack >>= \(s:ss) -> putStack ss >> return s
popStackN :: Integer -> StackOperation [StackValue]
popStackN n | n < 0 = programError "popStackN: negative argument"
| n == 0 = return []
| otherwise = (:) <$> popStack <*> popStackN (n - 1)
pickStack :: Bool -> Int -> StackOperation ()
pickStack remove n = do
st <- getStack
when (n < 0) $
programError "pickStack: n < 0"
when (n > length st - 1) $
programError "pickStack: n > size"
let v = st !! n
when remove $ putStack $ take n st ++ drop (n+1) st
pushStack v
getHashOps :: StackOperation HashOps
getHashOps = hashOps <$> get
-- | Function to track the verified OPs signed by OP_CHECK(MULTI) sig.
-- Dependent on the sequence of `OP_CODESEPARATOR`
dropHashOpsSeparatedCode :: StackOperation ()
dropHashOpsSeparatedCode = modify $ \p ->
let tryDrop = dropWhile ( /= OP_CODESEPARATOR ) $ hashOps p in
case tryDrop of
-- If no OP_CODESEPARATOR, take the whole script. This case is
-- possible when there is no OP_CODESEPARATOR in scriptPubKey but
-- one exists in scriptSig
[] -> p
_ -> p { hashOps = tail tryDrop }
-- | Filters out `OP_CODESEPARATOR` from the output script used by
-- OP_CHECK(MULTI)SIG
preparedHashOps :: StackOperation HashOps
preparedHashOps = filter ( /= OP_CODESEPARATOR ) <$> getHashOps
-- | Removes any PUSHDATA that contains the signatures. Used in
-- CHECK(MULTI)SIG so that signatures can be contained in output
-- scripts. See FindAndDelete() in Bitcoin Core.
findAndDelete :: [ StackValue ] -> [ ScriptOp ] -> [ ScriptOp ]
findAndDelete [] ops = ops
findAndDelete (s:ss) ops = let pushOp = opPushData . opToSv $ s in
findAndDelete ss $ filter ( /= pushOp ) ops
checkMultiSig :: SigCheck -- ^ Signature checking function
-> [ StackValue ] -- ^ PubKeys
-> [ StackValue ] -- ^ Signatures
-> [ ScriptOp ] -- ^ CODESEPARATOR'd hashops
-> Bool
checkMultiSig f encPubKeys encSigs hOps =
let pubKeys = mapMaybe (eitherToMaybe . decode . opToSv) encPubKeys
sigs = rights $ map ( decodeTxLaxSig . opToSv ) encSigs
cleanHashOps = findAndDelete encSigs hOps
in (length sigs == length encSigs) && -- check for bad signatures
orderedSatisfy (f cleanHashOps) sigs pubKeys
-- | Tests whether a function is satisfied for every a with some b "in
-- order". By "in order" we mean, if a pair satisfies the function,
-- any other satisfying pair must be deeper in each list. Designed to
-- return as soon as the result is known to minimize expensive
-- function calls. Used in checkMultiSig to verify signature/pubKey
-- pairs with a values as signatures and b values as pubkeys
orderedSatisfy :: ( a -> b -> Bool )
-> [ a ]
-> [ b ]
-> Bool
orderedSatisfy _ [] _ = True
orderedSatisfy _ (_:_) [] = False
orderedSatisfy f x@(a:as) y@(b:bs) | length x > length y = False
| f a b = orderedSatisfy f as bs
| otherwise = orderedSatisfy f x bs
tStack1 :: (StackValue -> Stack) -> StackOperation ()
tStack1 f = f <$> popStack >>= prependStack
tStack2 :: (StackValue -> StackValue -> Stack) -> StackOperation ()
tStack2 f = f <$> popStack <*> popStack >>= prependStack
tStack3 :: (StackValue -> StackValue -> StackValue -> Stack) -> StackOperation ()
tStack3 f = f <$> popStack <*> popStack <*> popStack >>= prependStack
tStack4 :: (StackValue -> StackValue -> StackValue -> StackValue -> Stack)
-> StackOperation ()
tStack4 f = f <$> popStack <*> popStack <*> popStack <*> popStack
>>= prependStack
tStack6 :: (StackValue -> StackValue -> StackValue ->
StackValue -> StackValue -> StackValue -> Stack) -> StackOperation ()
tStack6 f = f <$> popStack <*> popStack <*> popStack
<*> popStack <*> popStack <*> popStack >>= prependStack
arith1 :: (Int64 -> Int64) -> StackOperation ()
arith1 f = do
i <- popInt
pushStack $ encodeInt (f i)
arith2 :: (Int64 -> Int64 -> Int64) -> StackOperation ()
arith2 f = do
i <- popInt
j <- popInt
pushStack $ encodeInt (f i j)
stackError :: StackOperation a
stackError = programError "stack error"
-- AltStack Primitives
pushAltStack :: StackValue -> StackOperation ()
pushAltStack op = modify $ \p -> p { altStack = op:altStack p }
popAltStack :: StackOperation StackValue
popAltStack = get >>= \p -> case altStack p of
a:as -> put p { altStack = as } >> return a
[] -> programError "popAltStack: empty stack"
incrementOpCount :: Int -> StackOperation ()
incrementOpCount i | i > maxOpcodes = programError "reached opcode limit"
| otherwise = modify $ \p -> p { opCount = i + 1 }
nopDiscourager :: StackOperation ()
nopDiscourager = do
flgs <- ask
when (DISCOURAGE_UPGRADABLE_NOPS `elem` flgs) $
programError "Discouraged OP used."
-- Instruction Evaluation
eval :: ScriptOp -> StackOperation ()
eval OP_NOP = return ()
eval OP_NOP1 = void nopDiscourager
eval OP_NOP2 = void nopDiscourager
eval OP_NOP3 = void nopDiscourager
eval OP_NOP4 = void nopDiscourager
eval OP_NOP5 = void nopDiscourager
eval OP_NOP6 = void nopDiscourager
eval OP_NOP7 = void nopDiscourager
eval OP_NOP8 = void nopDiscourager
eval OP_NOP9 = void nopDiscourager
eval OP_NOP10 = void nopDiscourager
eval OP_VERIFY = popBool >>= \case
True -> return ()
False -> programError "OP_VERIFY failed"
eval OP_RETURN = programError "explicit OP_RETURN"
-- Stack
eval OP_TOALTSTACK = popStack >>= pushAltStack
eval OP_FROMALTSTACK = popAltStack >>= pushStack
eval OP_IFDUP = tStack1 $ \a -> if decodeBool a then [a, a] else [a]
eval OP_DEPTH = getStack >>= pushStack . encodeInt . fromIntegral . length
eval OP_DROP = void popStack
eval OP_DUP = tStack1 $ \a -> [a, a]
eval OP_NIP = tStack2 $ \a _ -> [a]
eval OP_OVER = tStack2 $ \a b -> [b, a, b]
eval OP_PICK = popInt >>= (pickStack False . fromIntegral)
eval OP_ROLL = popInt >>= (pickStack True . fromIntegral)
eval OP_ROT = tStack3 $ \a b c -> [c, a, b]
eval OP_SWAP = tStack2 $ \a b -> [b, a]
eval OP_TUCK = tStack2 $ \a b -> [a, b, a]
eval OP_2DROP = tStack2 $ \_ _ -> []
eval OP_2DUP = tStack2 $ \a b -> [a, b, a, b]
eval OP_3DUP = tStack3 $ \a b c -> [a, b, c, a, b, c]
eval OP_2OVER = tStack4 $ \a b c d -> [c, d, a, b, c, d]
eval OP_2ROT = tStack6 $ \a b c d e f -> [e, f, a, b, c, d]
eval OP_2SWAP = tStack4 $ \a b c d -> [c, d, a, b]
-- Splice
eval OP_SIZE = (fromIntegral . length . head <$> withStack) >>= pushInt
-- Bitwise Logic
eval OP_EQUAL = tStack2 $ \a b -> [encodeBool (a == b)]
eval OP_EQUALVERIFY = eval OP_EQUAL >> eval OP_VERIFY
-- Arithmetic
eval OP_1ADD = arith1 (+1)
eval OP_1SUB = arith1 (subtract 1)
eval OP_NEGATE = arith1 negate
eval OP_ABS = arith1 abs
eval OP_NOT = arith1 $ \case 0 -> 1; _ -> 0
eval OP_0NOTEQUAL = arith1 $ \case 0 -> 0; _ -> 1
eval OP_ADD = arith2 (+)
eval OP_SUB = arith2 $ flip (-)
eval OP_BOOLAND = (&&) <$> ((0 /=) <$> popInt)
<*> ((0 /=) <$> popInt) >>= pushBool
eval OP_BOOLOR = (||) <$> ((0 /=) <$> popInt)
<*> ((0 /=) <$> popInt) >>= pushBool
eval OP_NUMEQUAL = (==) <$> popInt <*> popInt >>= pushBool
eval OP_NUMEQUALVERIFY = eval OP_NUMEQUAL >> eval OP_VERIFY
eval OP_NUMNOTEQUAL = (/=) <$> popInt <*> popInt >>= pushBool
eval OP_LESSTHAN = (>) <$> popInt <*> popInt >>= pushBool
eval OP_GREATERTHAN = (<) <$> popInt <*> popInt >>= pushBool
eval OP_LESSTHANOREQUAL = (>=) <$> popInt <*> popInt >>= pushBool
eval OP_GREATERTHANOREQUAL = (<=) <$> popInt <*> popInt >>= pushBool
eval OP_MIN = min <$> popInt <*> popInt >>= pushInt
eval OP_MAX = max <$> popInt <*> popInt >>= pushInt
eval OP_WITHIN = within <$> popInt <*> popInt <*> popInt >>= pushBool
where within y x a = (x <= a) && (a < y)
eval OP_RIPEMD160 = tStack1 $ return . bsToSv . encode . ripemd160 . opToSv
eval OP_SHA1 = tStack1 $ return . bsToSv . encode . sha1 . opToSv
eval OP_SHA256 = tStack1 $ return . bsToSv . encode . sha256 . opToSv
eval OP_HASH160 = tStack1 $
return . bsToSv . encode . addressHash . opToSv
eval OP_HASH256 = tStack1 $
return . bsToSv . encode . doubleSHA256 . opToSv
eval OP_CODESEPARATOR = dropHashOpsSeparatedCode
eval OP_CHECKSIG = do
pubKey <- popStack
sig <- popStack
checker <- sigCheck <$> get
hOps <- preparedHashOps
-- Reuse checkMultiSig code
pushBool $ checkMultiSig checker [ pubKey ] [ sig ] hOps
eval OP_CHECKMULTISIG =
do nPubKeys <- fromIntegral <$> popInt
when (nPubKeys < 0 || nPubKeys > maxKeysMultisig)
$ programError $ "nPubKeys outside range: " ++ show nPubKeys
pubKeys <- popStackN $ toInteger nPubKeys
nSigs <- fromIntegral <$> popInt
when (nSigs < 0 || nSigs > nPubKeys)
$ programError $ "nSigs outside range: " ++ show nSigs
sigs <- popStackN $ toInteger nSigs
nullDummyEnforcer
void popStack -- spec bug
checker <- sigCheck <$> get
hOps <- preparedHashOps
pushBool $ checkMultiSig checker pubKeys sigs hOps
modify $ \p -> p { opCount = opCount p + length pubKeys }
eval OP_CHECKSIGVERIFY = eval OP_CHECKSIG >> eval OP_VERIFY
eval OP_CHECKMULTISIGVERIFY = eval OP_CHECKMULTISIG >> eval OP_VERIFY
eval op = case constValue op of
Just sv -> minimalPushEnforcer op >> pushStack sv
Nothing -> programError $ "unexpected op " ++ show op
minimalPushEnforcer :: ScriptOp -> StackOperation ()
minimalPushEnforcer op = do
flgs <- ask
when (MINIMALDATA `elem` flgs) $
unless (checkMinimalPush op) $
programError $ "Non-minimal data: " ++ show op
checkMinimalPush :: ScriptOp -> Bool -- Putting in a maybe monad to avoid elif chain
checkMinimalPush ( OP_PUSHDATA payload optype ) =
let l = BS.length payload
v = head (BS.unpack payload)
in not $
BS.null payload -- Check if could have used OP_0
|| (l == 1 && v <= 16 && v >= 1) -- Could have used OP_{1,..,16}
|| (l == 1 && v == 0x81) -- Could have used OP_1NEGATE
|| (l <= 75 && optype /= OPCODE) -- Could have used direct push
|| (l <= 255 && l > 75 && optype /= OPDATA1)
|| (l > 255 && l <= 65535 && optype /= OPDATA2)
checkMinimalPush _ = True
-- | Checks the top of the stack for a minimal numeric representation
-- if flagged to do so
minimalStackValEnforcer :: StackOperation ()
minimalStackValEnforcer = do
flgs <- ask
s <- getStack
let topStack = if null s then [] else head s
when (MINIMALDATA `elem` flgs || null topStack) $
unless (checkMinimalNumRep topStack) $
programError $ "Non-minimal stack value: " ++ show topStack
-- | Checks if a stack value is the minimal numeric representation of
-- the integer to which it decoes. Based on CScriptNum from Bitcoin
-- Core.
checkMinimalNumRep :: StackValue -> Bool
checkMinimalNumRep [] = True
checkMinimalNumRep s =
let msb = last s
l = length s in
not $
-- If the MSB except sign bit is zero, then nonMinimal
( msb .&. 0x7f == 0 )
-- With the exception of when a new byte is forced by a filled last bit
&& ( l <= 1 || ( s !! (l-2) ) .&. 0x80 == 0 )
nullDummyEnforcer :: StackOperation ()
nullDummyEnforcer = do
flgs <- ask
topStack <- getStack >>= headOrError
when ((NULLDUMMY `elem` flgs) && (not . null $ topStack)) $
programError "Non-null dummy stack in multi-sig"
where
headOrError s =
if null s
then programError "Empty stack where dummy op should be."
else return $ head s
--------------------------------------------------------------------------------
-- | Based on the IfStack, returns whether the script is within an
-- evaluating if-branch.
getExec :: Program Bool
getExec = and <$> getCond
-- | Converts a `ScriptOp` to a ProgramData monad.
conditionalEval :: ScriptOp -> Program ()
conditionalEval scrpOp = do
-- lift $ checkOpEnabled scrpOp
lift $ checkPushData scrpOp
e <- getExec
eval' e scrpOp
when (countOp scrpOp) $ lift $ join $ incrementOpCount . opCount <$> get
lift checkStackSize
where
eval' :: Bool -> ScriptOp -> Program ()
eval' True OP_IF = lift popStack >>= pushCond . decodeBool
eval' True OP_NOTIF = lift popStack >>= pushCond . not . decodeBool
eval' True OP_ELSE = flipCond
eval' True OP_ENDIF = void popCond
eval' True op = lift $ eval op
eval' False OP_IF = pushCond False
eval' False OP_NOTIF = pushCond False
eval' False OP_ELSE = flipCond
eval' False OP_ENDIF = void popCond
eval' False OP_CODESEPARATOR = lift $ eval OP_CODESEPARATOR
eval' False OP_VER = return ()
eval' False op | isDisabled op = lift $ disabled op
| otherwise = return ()
-- | Builds a Script evaluation monad.
evalOps :: [ ScriptOp ] -> Program ()
evalOps ops = do mapM_ conditionalEval ops
cond <- getCond
unless (null cond) (lift $ programError "ifStack not empty")
checkPushOnly :: [ ScriptOp ] -> Program ()
checkPushOnly ops
| not (all checkPushOp ops) = lift $ programError "only push ops allowed"
| otherwise = return ()
where checkPushOp op = case constValue op of
Just _ -> True
Nothing -> False
checkStack :: Stack -> Bool
checkStack (x:_) = decodeBool x
checkStack [] = False
isPayToScriptHash :: [ ScriptOp ] -> [ Flag ] -> Bool
isPayToScriptHash [OP_HASH160, OP_PUSHDATA bytes OPCODE, OP_EQUAL] flgs
= ( P2SH `elem` flgs ) && ( BS.length bytes == 20 )
isPayToScriptHash _ _ = False
stackToScriptOps :: StackValue -> [ ScriptOp ]
stackToScriptOps sv = case decode $ BS.pack sv of
Left _ -> [] -- Maybe should propogate the error some how
Right s -> scriptOps s
-- exported functions
execScript :: Script -- ^ scriptSig ( redeemScript )
-> Script -- ^ scriptPubKey
-> SigCheck -- ^ signature verification Function
-> [ Flag ] -- ^ Evaluation flags
-> Either EvalError ProgramData
execScript scriptSig scriptPubKey sigCheckFcn flags =
let sigOps = scriptOps scriptSig
pubKeyOps = scriptOps scriptPubKey
initData = ProgramData {
stack = [],
altStack = [],
hashOps = pubKeyOps,
sigCheck = sigCheckFcn,
opCount = 0
}
checkSig | isPayToScriptHash pubKeyOps flags = checkPushOnly sigOps
| SIGPUSHONLY `elem` flags = checkPushOnly sigOps
| otherwise = return ()
checkKey
| BS.length (encode scriptPubKey) > fromIntegral maxScriptSize =
lift $ programError "pubKey > maxScriptSize"
| otherwise = return ()
redeemEval = checkSig >> evalOps sigOps >> lift (stack <$> get)
pubKeyEval = checkKey >> evalOps pubKeyOps >> lift get
in do s <- evalProgram redeemEval [] initData flags
p <- evalProgram pubKeyEval [] initData { stack = s } flags
if not (null s)
&& isPayToScriptHash pubKeyOps flags
&& checkStack (runStack p)
then evalProgram (evalP2SH s) [] initData { stack = drop 1 s,
hashOps = stackToScriptOps $ head s } flags
else return p
-- | Evaluates a P2SH style script from its serialization in the stack
evalP2SH :: Stack -> Program ProgramData
evalP2SH [] = lift $ programError "PayToScriptHash: no script on stack"
evalP2SH (sv:_) = evalOps (stackToScriptOps sv) >> lift get
evalScript :: Script -> Script -> SigCheck -> [ Flag ] -> Bool
evalScript scriptSig scriptPubKey sigCheckFcn flags =
case execScript scriptSig scriptPubKey sigCheckFcn flags of
Left _ -> False
Right p -> checkStack . runStack $ p
runStack :: ProgramData -> Stack
runStack = stack
-- | A wrapper around 'verifySig' which handles grabbing the hash type
verifySigWithType ::
Tx -> Int -> Word64 -> [ScriptOp] -> TxSignature -> PubKey -> Bool
verifySigWithType tx i val outOps txSig pubKey =
let outScript = Script outOps
h = txSigHash tx outScript val i (txSignatureSigHash txSig)
in verifySig h (txSignature txSig) pubKey
-- | Uses `evalScript` to check that the input script of a spending
-- transaction satisfies the output script.
verifySpend :: Tx -- ^ The spending transaction
-> Int -- ^ The input index
-> Script -- ^ The output script we are spending
-> Word64 -- ^ The value of the output script
-> [Flag] -- ^ Evaluation flags
-> Bool
verifySpend tx i outscript val flags =
let scriptSig = either err id . decode . scriptInput $ txIn tx !! i
verifyFcn = verifySigWithType tx i val
err e = error $ "Could not decode scriptInput in verifySpend: " ++ e
in evalScript scriptSig outscript verifyFcn flags
| xenog/haskoin | src/Network/Haskoin/Script/Evaluator.hs | unlicense | 29,207 | 0 | 17 | 8,286 | 7,862 | 4,049 | 3,813 | 577 | 20 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
class TooMany a where
tooMany :: a -> Bool
instance TooMany Int where
tooMany n = n > 42
newtype Goats = Goats Int deriving (Eq, Show, TooMany)
instance TooMany (Int, String) where
tooMany (i, s) = i > 42
instance TooMany (Int, Int) where
tooMany (i, s) = i + s > 42
instance (Num a) => TooMany (a, a) where
tooMany (a, b) = a + b > (42 :: Num)
newtype Men = Men (Int, String) deriving (Eq, Show, TooMany)
| aniketd/learn.haskell | haskellbook/adt.hs | unlicense | 512 | 0 | 7 | 118 | 212 | 118 | 94 | 14 | 0 |
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.Loops
import Control.Monad.Trans
import Data.ByteString (ByteString)
import Database.Redis
import System.Random.MWC
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Char8 as Char8
numberOfURL = 2 * 1000 * 1000
numberOfURLPerURN = 10
numberOfURN = div numberOfURL numberOfURLPerURN
main :: IO ()
main = withSystemRandom $ \gen -> do
conn <- connect $ defaultConnectInfo { connectPort = redisSocket }
_ <- generate conn gen
return () where
redisSocket = UnixSocket "/tmp/redis.sock"
generate :: Connection -> Gen (PrimState IO) -> IO ()
generate conn gen = do
replicateM_ numberOfURN generate
return () where
generate :: IO ()
generate = do
urn <- genString gen
urls <- replicateM numberOfURLPerURN $ genString gen
let rows = (("urn-" ++ urn), "http://www.haskell.org") : map (\x -> ("url-/" ++ x, urn)) urls
_ <- sequence $ map (add conn) rows
return () where
add conn (k, v) = runRedis conn $ do
set (Char8.pack k) (Char8.pack v)
return ()
{-- TODO Move to commons --}
genString :: Gen (PrimState IO) -> IO String
genString gen = do
xs <- replicateM 4 $ uniformR (start, end) gen
return $ map toEnum xs where
start = fromEnum 'a'
end = fromEnum 'z'
| aloiscochard/redigo | redigo-testkit/Main.hs | apache-2.0 | 1,414 | 0 | 17 | 357 | 481 | 244 | 237 | 38 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.