_id stringlengths 64 64 | repository stringlengths 6 84 | name stringlengths 4 110 | content stringlengths 0 248k | license null | download_url stringlengths 89 454 | language stringclasses 7
values | comments stringlengths 0 74.6k | code stringlengths 0 248k |
|---|---|---|---|---|---|---|---|---|
27d81e2bee15025ae9af32aba3e3f5dd84f0df4057172a5179c5668b9431f389 | leftaroundabout/manifolds | Manifold.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE UndecidableInstances #
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE UnicodeSyntax #
module Data.Random.Manifold (shade, shadeT, D_S, uncertainFunctionSamplesT, uncrtFuncIntervalSpls) where
import Prelude hiding (($))
import Control.Category.Constrained.Prelude (($))
import Data.VectorSpace
import Data.AffineSpace
import Math.LinearMap.Category
import Data.Manifold.Types
import Data.Manifold.PseudoAffine
import Data.Manifold.TreeCover
import Data.Semigroup
import Data.Maybe (catMaybes)
import Data.Random
import Control.Applicative
import Control.Monad
import Control.Arrow
-- |
-- @
instance D_S x = > ' Distribution ' ' Shade ' x
-- @
type D_S x = (WithField ℝ PseudoAffine x, SimpleSpace (Needle x))
instance D_S x => Distribution Shade x where
rvarT (Shade c e) = shadeT' c e
shadeT' :: (PseudoAffine x, SimpleSpace (Needle x), Scalar (Needle x) ~ ℝ)
=> x -> Variance (Needle x) -> RVarT m x
shadeT' ctr expa = ((ctr.+~^) . sumV) <$> mapM (\v -> (v^*) <$> stdNormalT) eigSpan
where eigSpan = varianceSpanningSystem expa
-- | A shade can be considered a specification for a generalised normal distribution.
--
-- If you use 'rvar' to sample a large number of points from a shade @sh@ in a sufficiently
flat space , then ' pointsShades ' of that sample will again be approximately
shade :: (Distribution Shade x, D_S x) => x -> Variance (Needle x) -> RVar x
shade ctr expa = rvar $ fullShade ctr expa
shadeT :: (Distribution Shade x, D_S x) => x -> Variance (Needle x) -> RVarT m x
shadeT = shadeT'
uncertainFunctionSamplesT :: ∀ x y m .
( WithField ℝ Manifold x, SimpleSpace (Needle x)
, WithField ℝ Manifold y, SimpleSpace (Needle y) )
=> Int -> Shade x -> (x -> Shade y) -> RVarT m (x`Shaded`y)
uncertainFunctionSamplesT n shx f = case ( dualSpaceWitness :: DualNeedleWitness x
, dualSpaceWitness :: DualNeedleWitness y
, pseudoAffineWitness :: PseudoAffineWitness y ) of
( DualSpaceWitness, DualSpaceWitness
,PseudoAffineWitness SemimanifoldWitness ) -> do
domainSpls <- replicateM n $ rvarT shx
pts <- forM domainSpls $ \x -> do
y <- rvarT $ f x
return (x,y)
let t₀ = fromLeafPoints_ pts
ntwigs = length $ twigsWithEnvirons t₀
nPerTwig = fromIntegral n / fromIntegral ntwigs
ensureThickness :: Shade' (x,y)
-> RVarT m (x, (Shade' y, Needle x +> Needle y))
ensureThickness shl@(Shade' (xlc,ylc) expa) = do
let jOrig = dependence $ dualNorm expa
(expax,expay) = summandSpaceNorms expa
expax' = dualNorm expax
mkControlSample css confidence
| confidence > 6 = return css
| otherwise = do
-- exaggerate deviations a bit here, to avoid clustering
-- in center of normal distribution.
x <- rvarT (Shade xlc $ scaleNorm 1.2 expax')
let Shade ylc expaly = f x
y <- rvarT $ Shade ylc (scaleNorm 1.2 expaly)
mkControlSample ((x,y):css)
$ confidence + occlusion shl (x,y)
css <- mkControlSample [] 0
let xCtrl :: x
[Shade (xCtrl,yCtrl) expaCtrl :: Shade (x,y)]
= pointsShades css
yCtrl :: y
expayCtrl = dualNorm . snd $ summandSpaceNorms expaCtrl
jCtrl = dependence expaCtrl
jFin = jOrig^*η ^+^ jCtrl^*η'
Just δx = xlc.-~.xCtrl
η, η' :: ℝ
η = nPerTwig / (nPerTwig + fromIntegral (length css))
η' = 1 - η
Just δy = yCtrl.-~.ylc
return ( xlc .+~^ δx^*η'
, ( Shade' (ylc .+~^ δy^*η')
(scaleNorm (sqrt η) expay <> scaleNorm (sqrt η') expayCtrl)
, jFin ) )
flexTwigsShading ensureThickness t₀
uncrtFuncIntervalSpls :: (x~ℝ, y~ℝ)
=> Int -> (x,x) -> (x -> (y, Diff y)) -> RVar (x`Shaded`y)
uncrtFuncIntervalSpls n (xl,xr) f
= uncertainFunctionSamplesT n
(Shade ((xl+xr)/2) $ spanVariance [(xr-xl)/2])
(f >>> \(y,δy) -> Shade y $ spanVariance [δy])
| null | https://raw.githubusercontent.com/leftaroundabout/manifolds/55330e7760fa8ea8948988a10a06bbf19e69b5f5/manifold-random/Data/Random/Manifold.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
# LANGUAGE ScopedTypeVariables #
|
@
@
| A shade can be considered a specification for a generalised normal distribution.
If you use 'rvar' to sample a large number of points from a shade @sh@ in a sufficiently
exaggerate deviations a bit here, to avoid clustering
in center of normal distribution. | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE UnicodeSyntax #
module Data.Random.Manifold (shade, shadeT, D_S, uncertainFunctionSamplesT, uncrtFuncIntervalSpls) where
import Prelude hiding (($))
import Control.Category.Constrained.Prelude (($))
import Data.VectorSpace
import Data.AffineSpace
import Math.LinearMap.Category
import Data.Manifold.Types
import Data.Manifold.PseudoAffine
import Data.Manifold.TreeCover
import Data.Semigroup
import Data.Maybe (catMaybes)
import Data.Random
import Control.Applicative
import Control.Monad
import Control.Arrow
instance D_S x = > ' Distribution ' ' Shade ' x
type D_S x = (WithField ℝ PseudoAffine x, SimpleSpace (Needle x))
instance D_S x => Distribution Shade x where
rvarT (Shade c e) = shadeT' c e
shadeT' :: (PseudoAffine x, SimpleSpace (Needle x), Scalar (Needle x) ~ ℝ)
=> x -> Variance (Needle x) -> RVarT m x
shadeT' ctr expa = ((ctr.+~^) . sumV) <$> mapM (\v -> (v^*) <$> stdNormalT) eigSpan
where eigSpan = varianceSpanningSystem expa
flat space , then ' pointsShades ' of that sample will again be approximately
shade :: (Distribution Shade x, D_S x) => x -> Variance (Needle x) -> RVar x
shade ctr expa = rvar $ fullShade ctr expa
shadeT :: (Distribution Shade x, D_S x) => x -> Variance (Needle x) -> RVarT m x
shadeT = shadeT'
uncertainFunctionSamplesT :: ∀ x y m .
( WithField ℝ Manifold x, SimpleSpace (Needle x)
, WithField ℝ Manifold y, SimpleSpace (Needle y) )
=> Int -> Shade x -> (x -> Shade y) -> RVarT m (x`Shaded`y)
uncertainFunctionSamplesT n shx f = case ( dualSpaceWitness :: DualNeedleWitness x
, dualSpaceWitness :: DualNeedleWitness y
, pseudoAffineWitness :: PseudoAffineWitness y ) of
( DualSpaceWitness, DualSpaceWitness
,PseudoAffineWitness SemimanifoldWitness ) -> do
domainSpls <- replicateM n $ rvarT shx
pts <- forM domainSpls $ \x -> do
y <- rvarT $ f x
return (x,y)
let t₀ = fromLeafPoints_ pts
ntwigs = length $ twigsWithEnvirons t₀
nPerTwig = fromIntegral n / fromIntegral ntwigs
ensureThickness :: Shade' (x,y)
-> RVarT m (x, (Shade' y, Needle x +> Needle y))
ensureThickness shl@(Shade' (xlc,ylc) expa) = do
let jOrig = dependence $ dualNorm expa
(expax,expay) = summandSpaceNorms expa
expax' = dualNorm expax
mkControlSample css confidence
| confidence > 6 = return css
| otherwise = do
x <- rvarT (Shade xlc $ scaleNorm 1.2 expax')
let Shade ylc expaly = f x
y <- rvarT $ Shade ylc (scaleNorm 1.2 expaly)
mkControlSample ((x,y):css)
$ confidence + occlusion shl (x,y)
css <- mkControlSample [] 0
let xCtrl :: x
[Shade (xCtrl,yCtrl) expaCtrl :: Shade (x,y)]
= pointsShades css
yCtrl :: y
expayCtrl = dualNorm . snd $ summandSpaceNorms expaCtrl
jCtrl = dependence expaCtrl
jFin = jOrig^*η ^+^ jCtrl^*η'
Just δx = xlc.-~.xCtrl
η, η' :: ℝ
η = nPerTwig / (nPerTwig + fromIntegral (length css))
η' = 1 - η
Just δy = yCtrl.-~.ylc
return ( xlc .+~^ δx^*η'
, ( Shade' (ylc .+~^ δy^*η')
(scaleNorm (sqrt η) expay <> scaleNorm (sqrt η') expayCtrl)
, jFin ) )
flexTwigsShading ensureThickness t₀
uncrtFuncIntervalSpls :: (x~ℝ, y~ℝ)
=> Int -> (x,x) -> (x -> (y, Diff y)) -> RVar (x`Shaded`y)
uncrtFuncIntervalSpls n (xl,xr) f
= uncertainFunctionSamplesT n
(Shade ((xl+xr)/2) $ spanVariance [(xr-xl)/2])
(f >>> \(y,δy) -> Shade y $ spanVariance [δy])
|
86f4e702765223869baab171c12ec8dc4acafea49ed8061c4b78ae6ac82d9ae0 | SimulaVR/godot-haskell | GDScriptFunctionState.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.GDScriptFunctionState
(Godot.Core.GDScriptFunctionState.sig_completed,
Godot.Core.GDScriptFunctionState._signal_callback,
Godot.Core.GDScriptFunctionState.is_valid,
Godot.Core.GDScriptFunctionState.resume)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Reference()
sig_completed ::
Godot.Internal.Dispatch.Signal GDScriptFunctionState
sig_completed = Godot.Internal.Dispatch.Signal "completed"
instance NodeSignal GDScriptFunctionState "completed"
'[GodotVariant]
# NOINLINE bindGDScriptFunctionState__signal_callback #
bindGDScriptFunctionState__signal_callback :: MethodBind
bindGDScriptFunctionState__signal_callback
= unsafePerformIO $
withCString "GDScriptFunctionState" $
\ clsNamePtr ->
withCString "_signal_callback" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_signal_callback ::
(GDScriptFunctionState :< cls, Object :< cls) =>
cls -> [Variant 'GodotTy] -> IO GodotVariant
_signal_callback cls varargs
= withVariantArray ([] ++ varargs)
(\ (arrPtr, len) ->
godot_method_bind_call bindGDScriptFunctionState__signal_callback
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GDScriptFunctionState "_signal_callback"
'[[Variant 'GodotTy]]
(IO GodotVariant)
where
nodeMethod = Godot.Core.GDScriptFunctionState._signal_callback
# NOINLINE bindGDScriptFunctionState_is_valid #
bindGDScriptFunctionState_is_valid :: MethodBind
bindGDScriptFunctionState_is_valid
= unsafePerformIO $
withCString "GDScriptFunctionState" $
\ clsNamePtr ->
withCString "is_valid" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
is_valid ::
(GDScriptFunctionState :< cls, Object :< cls) =>
cls -> Maybe Bool -> IO Bool
is_valid cls arg1
= withVariantArray [maybe (VariantBool False) toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGDScriptFunctionState_is_valid
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GDScriptFunctionState "is_valid" '[Maybe Bool]
(IO Bool)
where
nodeMethod = Godot.Core.GDScriptFunctionState.is_valid
# NOINLINE bindGDScriptFunctionState_resume #
bindGDScriptFunctionState_resume :: MethodBind
bindGDScriptFunctionState_resume
= unsafePerformIO $
withCString "GDScriptFunctionState" $
\ clsNamePtr ->
withCString "resume" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
resume ::
(GDScriptFunctionState :< cls, Object :< cls) =>
cls -> Maybe GodotVariant -> IO GodotVariant
resume cls arg1
= withVariantArray [maybe VariantNil toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGDScriptFunctionState_resume
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GDScriptFunctionState "resume"
'[Maybe GodotVariant]
(IO GodotVariant)
where
nodeMethod = Godot.Core.GDScriptFunctionState.resume | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/GDScriptFunctionState.hs | haskell | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.GDScriptFunctionState
(Godot.Core.GDScriptFunctionState.sig_completed,
Godot.Core.GDScriptFunctionState._signal_callback,
Godot.Core.GDScriptFunctionState.is_valid,
Godot.Core.GDScriptFunctionState.resume)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Reference()
sig_completed ::
Godot.Internal.Dispatch.Signal GDScriptFunctionState
sig_completed = Godot.Internal.Dispatch.Signal "completed"
instance NodeSignal GDScriptFunctionState "completed"
'[GodotVariant]
# NOINLINE bindGDScriptFunctionState__signal_callback #
bindGDScriptFunctionState__signal_callback :: MethodBind
bindGDScriptFunctionState__signal_callback
= unsafePerformIO $
withCString "GDScriptFunctionState" $
\ clsNamePtr ->
withCString "_signal_callback" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_signal_callback ::
(GDScriptFunctionState :< cls, Object :< cls) =>
cls -> [Variant 'GodotTy] -> IO GodotVariant
_signal_callback cls varargs
= withVariantArray ([] ++ varargs)
(\ (arrPtr, len) ->
godot_method_bind_call bindGDScriptFunctionState__signal_callback
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GDScriptFunctionState "_signal_callback"
'[[Variant 'GodotTy]]
(IO GodotVariant)
where
nodeMethod = Godot.Core.GDScriptFunctionState._signal_callback
# NOINLINE bindGDScriptFunctionState_is_valid #
bindGDScriptFunctionState_is_valid :: MethodBind
bindGDScriptFunctionState_is_valid
= unsafePerformIO $
withCString "GDScriptFunctionState" $
\ clsNamePtr ->
withCString "is_valid" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
is_valid ::
(GDScriptFunctionState :< cls, Object :< cls) =>
cls -> Maybe Bool -> IO Bool
is_valid cls arg1
= withVariantArray [maybe (VariantBool False) toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGDScriptFunctionState_is_valid
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GDScriptFunctionState "is_valid" '[Maybe Bool]
(IO Bool)
where
nodeMethod = Godot.Core.GDScriptFunctionState.is_valid
# NOINLINE bindGDScriptFunctionState_resume #
bindGDScriptFunctionState_resume :: MethodBind
bindGDScriptFunctionState_resume
= unsafePerformIO $
withCString "GDScriptFunctionState" $
\ clsNamePtr ->
withCString "resume" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
resume ::
(GDScriptFunctionState :< cls, Object :< cls) =>
cls -> Maybe GodotVariant -> IO GodotVariant
resume cls arg1
= withVariantArray [maybe VariantNil toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindGDScriptFunctionState_resume
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod GDScriptFunctionState "resume"
'[Maybe GodotVariant]
(IO GodotVariant)
where
nodeMethod = Godot.Core.GDScriptFunctionState.resume | |
0bae8ae88c8bff8c5330e0d2e086d9df8ff28e0b13da329f4679a9afc4ed11f5 | GaloisInc/cryptol | SeqMap.hs | -- |
Module : Cryptol . Backend . SeqMap
Copyright : ( c ) 2013 - 2021 Galois , Inc.
-- License : BSD3
-- Maintainer :
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DoAndIfThenElse #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE ImplicitParams #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PatternGuards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
module Cryptol.Backend.SeqMap
( -- * Sequence Maps
SeqMap
, indexSeqMap
, lookupSeqMap
, finiteSeqMap
, infiniteSeqMap
, enumerateSeqMap
, streamSeqMap
, reverseSeqMap
, updateSeqMap
, dropSeqMap
, concatSeqMap
, splitSeqMap
, memoMap
, delaySeqMap
, zipSeqMap
, mapSeqMap
, mergeSeqMap
, barrelShifter
, shiftSeqByInteger
, IndexSegment(..)
) where
import qualified Control.Exception as X
import Control.Monad
import Control.Monad.IO.Class
import Data.Bits
import Data.List
import Data.IORef
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Cryptol.Backend
import Cryptol.Backend.Concrete (Concrete)
import Cryptol.Backend.Monad (Unsupported(..))
import Cryptol.TypeCheck.Solver.InfNat(Nat'(..))
import Cryptol.Utils.Panic
-- | A sequence map represents a mapping from nonnegative integer indices
-- to values. These are used to represent both finite and infinite sequences.
data SeqMap sym a
= IndexSeqMap !(Integer -> SEval sym a)
| UpdateSeqMap !(Map Integer (SEval sym a))
!(SeqMap sym a)
| MemoSeqMap
!Nat'
!(IORef (Map Integer a))
!(IORef (Integer -> SEval sym a))
indexSeqMap :: (Integer -> SEval sym a) -> SeqMap sym a
indexSeqMap = IndexSeqMap
lookupSeqMap :: Backend sym => SeqMap sym a -> Integer -> SEval sym a
lookupSeqMap (IndexSeqMap f) i = f i
lookupSeqMap (UpdateSeqMap m xs) i =
case Map.lookup i m of
Just x -> x
Nothing -> lookupSeqMap xs i
lookupSeqMap (MemoSeqMap sz cache eval) i =
do mz <- liftIO (Map.lookup i <$> readIORef cache)
case mz of
Just z -> return z
Nothing ->
do f <- liftIO (readIORef eval)
v <- f i
msz <- liftIO $ atomicModifyIORef' cache (\m ->
let m' = Map.insert i v m in (m', Map.size m'))
-- If we memoize the entire map, overwrite the evaluation closure to let
-- the garbage collector reap it
when (case sz of Inf -> False; Nat sz' -> toInteger msz >= sz')
(liftIO (writeIORef eval
(\j -> panic "lookupSeqMap" ["Messed up size accounting", show sz, show j])))
return v
instance Backend sym => Functor (SeqMap sym) where
fmap f xs = IndexSeqMap (\i -> f <$> lookupSeqMap xs i)
-- | Generate a finite sequence map from a list of values
finiteSeqMap :: Backend sym => sym -> [SEval sym a] -> SeqMap sym a
finiteSeqMap sym xs =
UpdateSeqMap
(Map.fromList (zip [0..] xs))
(IndexSeqMap (\i -> invalidIndex sym i))
-- | Generate an infinite sequence map from a stream of values
infiniteSeqMap :: Backend sym => sym -> [SEval sym a] -> SEval sym (SeqMap sym a)
infiniteSeqMap sym xs =
-- TODO: use an int-trie?
memoMap sym Inf (IndexSeqMap $ \i -> genericIndex xs i)
-- | Create a finite list of length @n@ of the values from @[0..n-1]@ in
-- the given the sequence emap.
enumerateSeqMap :: (Backend sym, Integral n) => n -> SeqMap sym a -> [SEval sym a]
enumerateSeqMap n m = [ lookupSeqMap m i | i <- [0 .. (toInteger n)-1] ]
-- | Create an infinite stream of all the values in a sequence map
streamSeqMap :: Backend sym => SeqMap sym a -> [SEval sym a]
streamSeqMap m = [ lookupSeqMap m i | i <- [0..] ]
-- | Reverse the order of a finite sequence map
reverseSeqMap :: Backend sym =>
Integer {- ^ Size of the sequence map -} ->
SeqMap sym a ->
SeqMap sym a
reverseSeqMap n vals = IndexSeqMap $ \i -> lookupSeqMap vals (n - 1 - i)
updateSeqMap :: SeqMap sym a -> Integer -> SEval sym a -> SeqMap sym a
updateSeqMap (UpdateSeqMap m sm) i x = UpdateSeqMap (Map.insert i x m) sm
updateSeqMap xs i x = UpdateSeqMap (Map.singleton i x) xs
| Concatenate the first @n@ values of the first sequence map onto the
beginning of the second sequence map .
concatSeqMap :: Backend sym => Integer -> SeqMap sym a -> SeqMap sym a -> SeqMap sym a
concatSeqMap n x y =
IndexSeqMap $ \i ->
if i < n
then lookupSeqMap x i
else lookupSeqMap y (i-n)
| Given a number @n@ and a sequence map , return two new sequence maps :
the first containing the values from @[0 .. n-1]@ and the next containing
the values from @n@ onward .
splitSeqMap :: Backend sym => Integer -> SeqMap sym a -> (SeqMap sym a, SeqMap sym a)
splitSeqMap n xs = (hd,tl)
where
hd = xs
tl = IndexSeqMap $ \i -> lookupSeqMap xs (i+n)
| Drop the first @n@ elements of the given ' SeqMap ' .
dropSeqMap :: Backend sym => Integer -> SeqMap sym a -> SeqMap sym a
dropSeqMap 0 xs = xs
dropSeqMap n xs = IndexSeqMap $ \i -> lookupSeqMap xs (i+n)
delaySeqMap :: Backend sym => sym -> SEval sym (SeqMap sym a) -> SEval sym (SeqMap sym a)
delaySeqMap sym xs =
do xs' <- sDelay sym xs
pure $ IndexSeqMap $ \i -> do m <- xs'; lookupSeqMap m i
-- | Given a sequence map, return a new sequence map that is memoized using
-- a finite map memo table.
memoMap :: Backend sym => sym -> Nat' -> SeqMap sym a -> SEval sym (SeqMap sym a)
Sequence is alreay memoized , just return it
memoMap _sym _sz x@(MemoSeqMap{}) = pure x
memoMap sym sz x = do
stk <- sGetCallStack sym
cache <- liftIO $ newIORef $ Map.empty
evalRef <- liftIO $ newIORef $ eval stk
return (MemoSeqMap sz cache evalRef)
where
eval stk i = sWithCallStack sym stk (lookupSeqMap x i)
| Apply the given evaluation function pointwise to the two given
-- sequence maps.
zipSeqMap ::
Backend sym =>
sym ->
(a -> a -> SEval sym a) ->
Nat' ->
SeqMap sym a ->
SeqMap sym a ->
SEval sym (SeqMap sym a)
zipSeqMap sym f sz x y =
memoMap sym sz (IndexSeqMap $ \i -> join (f <$> lookupSeqMap x i <*> lookupSeqMap y i))
-- | Apply the given function to each value in the given sequence map
mapSeqMap ::
Backend sym =>
sym ->
(a -> SEval sym a) ->
Nat' ->
SeqMap sym a ->
SEval sym (SeqMap sym a)
mapSeqMap sym f sz x =
memoMap sym sz (IndexSeqMap $ \i -> f =<< lookupSeqMap x i)
# INLINE mergeSeqMap #
mergeSeqMap :: Backend sym =>
sym ->
(SBit sym -> a -> a -> SEval sym a) ->
SBit sym ->
SeqMap sym a ->
SeqMap sym a ->
SeqMap sym a
mergeSeqMap sym f c x y =
IndexSeqMap $ \i -> mergeEval sym f c (lookupSeqMap x i) (lookupSeqMap y i)
# INLINE shiftSeqByInteger #
shiftSeqByInteger :: Backend sym =>
sym ->
(SBit sym -> a -> a -> SEval sym a)
{- ^ if/then/else operation of values -} ->
(Integer -> Integer -> Maybe Integer)
{- ^ reindexing operation -} ->
^ zero value
Nat' {- ^ size of the sequence -} ->
SeqMap sym a {- ^ sequence to shift -} ->
^ shift amount , assumed to be in range [ 0,len ]
SEval sym (SeqMap sym a)
shiftSeqByInteger sym merge reindex zro m xs idx
| Just j <- integerAsLit sym idx = shiftOp xs j
| otherwise =
do (n, idx_bits) <- enumerateIntBits sym m idx
barrelShifter sym merge shiftOp m xs n (map BitIndexSegment idx_bits)
where
shiftOp vs shft =
pure $ indexSeqMap $ \i ->
case reindex i shft of
Nothing -> zro
Just i' -> lookupSeqMap vs i'
data IndexSegment sym
= BitIndexSegment (SBit sym)
| WordIndexSegment (SWord sym)
{-# SPECIALIZE
barrelShifter ::
Concrete ->
(SBit Concrete -> a -> a -> SEval Concrete a) ->
(SeqMap Concrete a -> Integer -> SEval Concrete (SeqMap Concrete a)) ->
Nat' ->
SeqMap Concrete a ->
Integer ->
[IndexSegment Concrete] ->
SEval Concrete (SeqMap Concrete a)
#-}
barrelShifter :: Backend sym =>
sym ->
(SBit sym -> a -> a -> SEval sym a)
{- ^ if/then/else operation of values -} ->
(SeqMap sym a -> Integer -> SEval sym (SeqMap sym a))
{- ^ concrete shifting operation -} ->
Nat' {- ^ Size of the map being shifted -} ->
SeqMap sym a {- ^ initial value -} ->
Integer {- Number of bits in shift amount -} ->
[IndexSegment sym] {- ^ segments of the shift amount, in big-endian order -} ->
SEval sym (SeqMap sym a)
barrelShifter sym mux shift_op sz x0 n0 bs0
| n0 >= toInteger (maxBound :: Int) =
liftIO (X.throw (UnsupportedSymbolicOp ("Barrel shifter with too many bits in shift amount: " ++ show n0)))
| otherwise = go x0 (fromInteger n0) bs0
where
go x !_n [] = return x
go x !n (WordIndexSegment w:bs) =
let n' = n - fromInteger (wordLen sym w) in
case wordAsLit sym w of
Just (_,0) -> go x n' bs
Just (_,j) ->
do x_shft <- shift_op x (j * bit n')
go x_shft n' bs
Nothing ->
do wbs <- unpackWord sym w
go x n (map BitIndexSegment wbs ++ bs)
go x !n (BitIndexSegment b:bs) =
let n' = n - 1 in
case bitAsLit sym b of
Just False -> go x n' bs
Just True ->
do x_shft <- shift_op x (bit n')
go x_shft n' bs
Nothing ->
do x_shft <- shift_op x (bit n')
x' <- memoMap sym sz (mergeSeqMap sym mux b x_shft x)
go x' n' bs
| null | https://raw.githubusercontent.com/GaloisInc/cryptol/8cca24568ad499f06032c2e4eaa7dfd4c542efb6/src/Cryptol/Backend/SeqMap.hs | haskell | |
License : BSD3
Maintainer :
Stability : provisional
Portability : portable
# LANGUAGE BangPatterns #
# LANGUAGE DeriveAnyClass #
# LANGUAGE DoAndIfThenElse #
* Sequence Maps
| A sequence map represents a mapping from nonnegative integer indices
to values. These are used to represent both finite and infinite sequences.
If we memoize the entire map, overwrite the evaluation closure to let
the garbage collector reap it
| Generate a finite sequence map from a list of values
| Generate an infinite sequence map from a stream of values
TODO: use an int-trie?
| Create a finite list of length @n@ of the values from @[0..n-1]@ in
the given the sequence emap.
| Create an infinite stream of all the values in a sequence map
| Reverse the order of a finite sequence map
^ Size of the sequence map
| Given a sequence map, return a new sequence map that is memoized using
a finite map memo table.
sequence maps.
| Apply the given function to each value in the given sequence map
^ if/then/else operation of values
^ reindexing operation
^ size of the sequence
^ sequence to shift
# SPECIALIZE
barrelShifter ::
Concrete ->
(SBit Concrete -> a -> a -> SEval Concrete a) ->
(SeqMap Concrete a -> Integer -> SEval Concrete (SeqMap Concrete a)) ->
Nat' ->
SeqMap Concrete a ->
Integer ->
[IndexSegment Concrete] ->
SEval Concrete (SeqMap Concrete a)
#
^ if/then/else operation of values
^ concrete shifting operation
^ Size of the map being shifted
^ initial value
Number of bits in shift amount
^ segments of the shift amount, in big-endian order | Module : Cryptol . Backend . SeqMap
Copyright : ( c ) 2013 - 2021 Galois , Inc.
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE ImplicitParams #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PatternGuards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
module Cryptol.Backend.SeqMap
SeqMap
, indexSeqMap
, lookupSeqMap
, finiteSeqMap
, infiniteSeqMap
, enumerateSeqMap
, streamSeqMap
, reverseSeqMap
, updateSeqMap
, dropSeqMap
, concatSeqMap
, splitSeqMap
, memoMap
, delaySeqMap
, zipSeqMap
, mapSeqMap
, mergeSeqMap
, barrelShifter
, shiftSeqByInteger
, IndexSegment(..)
) where
import qualified Control.Exception as X
import Control.Monad
import Control.Monad.IO.Class
import Data.Bits
import Data.List
import Data.IORef
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Cryptol.Backend
import Cryptol.Backend.Concrete (Concrete)
import Cryptol.Backend.Monad (Unsupported(..))
import Cryptol.TypeCheck.Solver.InfNat(Nat'(..))
import Cryptol.Utils.Panic
data SeqMap sym a
= IndexSeqMap !(Integer -> SEval sym a)
| UpdateSeqMap !(Map Integer (SEval sym a))
!(SeqMap sym a)
| MemoSeqMap
!Nat'
!(IORef (Map Integer a))
!(IORef (Integer -> SEval sym a))
indexSeqMap :: (Integer -> SEval sym a) -> SeqMap sym a
indexSeqMap = IndexSeqMap
lookupSeqMap :: Backend sym => SeqMap sym a -> Integer -> SEval sym a
lookupSeqMap (IndexSeqMap f) i = f i
lookupSeqMap (UpdateSeqMap m xs) i =
case Map.lookup i m of
Just x -> x
Nothing -> lookupSeqMap xs i
lookupSeqMap (MemoSeqMap sz cache eval) i =
do mz <- liftIO (Map.lookup i <$> readIORef cache)
case mz of
Just z -> return z
Nothing ->
do f <- liftIO (readIORef eval)
v <- f i
msz <- liftIO $ atomicModifyIORef' cache (\m ->
let m' = Map.insert i v m in (m', Map.size m'))
when (case sz of Inf -> False; Nat sz' -> toInteger msz >= sz')
(liftIO (writeIORef eval
(\j -> panic "lookupSeqMap" ["Messed up size accounting", show sz, show j])))
return v
instance Backend sym => Functor (SeqMap sym) where
fmap f xs = IndexSeqMap (\i -> f <$> lookupSeqMap xs i)
finiteSeqMap :: Backend sym => sym -> [SEval sym a] -> SeqMap sym a
finiteSeqMap sym xs =
UpdateSeqMap
(Map.fromList (zip [0..] xs))
(IndexSeqMap (\i -> invalidIndex sym i))
infiniteSeqMap :: Backend sym => sym -> [SEval sym a] -> SEval sym (SeqMap sym a)
infiniteSeqMap sym xs =
memoMap sym Inf (IndexSeqMap $ \i -> genericIndex xs i)
enumerateSeqMap :: (Backend sym, Integral n) => n -> SeqMap sym a -> [SEval sym a]
enumerateSeqMap n m = [ lookupSeqMap m i | i <- [0 .. (toInteger n)-1] ]
streamSeqMap :: Backend sym => SeqMap sym a -> [SEval sym a]
streamSeqMap m = [ lookupSeqMap m i | i <- [0..] ]
reverseSeqMap :: Backend sym =>
SeqMap sym a ->
SeqMap sym a
reverseSeqMap n vals = IndexSeqMap $ \i -> lookupSeqMap vals (n - 1 - i)
updateSeqMap :: SeqMap sym a -> Integer -> SEval sym a -> SeqMap sym a
updateSeqMap (UpdateSeqMap m sm) i x = UpdateSeqMap (Map.insert i x m) sm
updateSeqMap xs i x = UpdateSeqMap (Map.singleton i x) xs
| Concatenate the first @n@ values of the first sequence map onto the
beginning of the second sequence map .
concatSeqMap :: Backend sym => Integer -> SeqMap sym a -> SeqMap sym a -> SeqMap sym a
concatSeqMap n x y =
IndexSeqMap $ \i ->
if i < n
then lookupSeqMap x i
else lookupSeqMap y (i-n)
| Given a number @n@ and a sequence map , return two new sequence maps :
the first containing the values from @[0 .. n-1]@ and the next containing
the values from @n@ onward .
splitSeqMap :: Backend sym => Integer -> SeqMap sym a -> (SeqMap sym a, SeqMap sym a)
splitSeqMap n xs = (hd,tl)
where
hd = xs
tl = IndexSeqMap $ \i -> lookupSeqMap xs (i+n)
| Drop the first @n@ elements of the given ' SeqMap ' .
dropSeqMap :: Backend sym => Integer -> SeqMap sym a -> SeqMap sym a
dropSeqMap 0 xs = xs
dropSeqMap n xs = IndexSeqMap $ \i -> lookupSeqMap xs (i+n)
delaySeqMap :: Backend sym => sym -> SEval sym (SeqMap sym a) -> SEval sym (SeqMap sym a)
delaySeqMap sym xs =
do xs' <- sDelay sym xs
pure $ IndexSeqMap $ \i -> do m <- xs'; lookupSeqMap m i
memoMap :: Backend sym => sym -> Nat' -> SeqMap sym a -> SEval sym (SeqMap sym a)
Sequence is alreay memoized , just return it
memoMap _sym _sz x@(MemoSeqMap{}) = pure x
memoMap sym sz x = do
stk <- sGetCallStack sym
cache <- liftIO $ newIORef $ Map.empty
evalRef <- liftIO $ newIORef $ eval stk
return (MemoSeqMap sz cache evalRef)
where
eval stk i = sWithCallStack sym stk (lookupSeqMap x i)
| Apply the given evaluation function pointwise to the two given
zipSeqMap ::
Backend sym =>
sym ->
(a -> a -> SEval sym a) ->
Nat' ->
SeqMap sym a ->
SeqMap sym a ->
SEval sym (SeqMap sym a)
zipSeqMap sym f sz x y =
memoMap sym sz (IndexSeqMap $ \i -> join (f <$> lookupSeqMap x i <*> lookupSeqMap y i))
mapSeqMap ::
Backend sym =>
sym ->
(a -> SEval sym a) ->
Nat' ->
SeqMap sym a ->
SEval sym (SeqMap sym a)
mapSeqMap sym f sz x =
memoMap sym sz (IndexSeqMap $ \i -> f =<< lookupSeqMap x i)
# INLINE mergeSeqMap #
mergeSeqMap :: Backend sym =>
sym ->
(SBit sym -> a -> a -> SEval sym a) ->
SBit sym ->
SeqMap sym a ->
SeqMap sym a ->
SeqMap sym a
mergeSeqMap sym f c x y =
IndexSeqMap $ \i -> mergeEval sym f c (lookupSeqMap x i) (lookupSeqMap y i)
# INLINE shiftSeqByInteger #
shiftSeqByInteger :: Backend sym =>
sym ->
(SBit sym -> a -> a -> SEval sym a)
(Integer -> Integer -> Maybe Integer)
^ zero value
^ shift amount , assumed to be in range [ 0,len ]
SEval sym (SeqMap sym a)
shiftSeqByInteger sym merge reindex zro m xs idx
| Just j <- integerAsLit sym idx = shiftOp xs j
| otherwise =
do (n, idx_bits) <- enumerateIntBits sym m idx
barrelShifter sym merge shiftOp m xs n (map BitIndexSegment idx_bits)
where
shiftOp vs shft =
pure $ indexSeqMap $ \i ->
case reindex i shft of
Nothing -> zro
Just i' -> lookupSeqMap vs i'
data IndexSegment sym
= BitIndexSegment (SBit sym)
| WordIndexSegment (SWord sym)
barrelShifter :: Backend sym =>
sym ->
(SBit sym -> a -> a -> SEval sym a)
(SeqMap sym a -> Integer -> SEval sym (SeqMap sym a))
SEval sym (SeqMap sym a)
barrelShifter sym mux shift_op sz x0 n0 bs0
| n0 >= toInteger (maxBound :: Int) =
liftIO (X.throw (UnsupportedSymbolicOp ("Barrel shifter with too many bits in shift amount: " ++ show n0)))
| otherwise = go x0 (fromInteger n0) bs0
where
go x !_n [] = return x
go x !n (WordIndexSegment w:bs) =
let n' = n - fromInteger (wordLen sym w) in
case wordAsLit sym w of
Just (_,0) -> go x n' bs
Just (_,j) ->
do x_shft <- shift_op x (j * bit n')
go x_shft n' bs
Nothing ->
do wbs <- unpackWord sym w
go x n (map BitIndexSegment wbs ++ bs)
go x !n (BitIndexSegment b:bs) =
let n' = n - 1 in
case bitAsLit sym b of
Just False -> go x n' bs
Just True ->
do x_shft <- shift_op x (bit n')
go x_shft n' bs
Nothing ->
do x_shft <- shift_op x (bit n')
x' <- memoMap sym sz (mergeSeqMap sym mux b x_shft x)
go x' n' bs
|
436f5590d58ae83b6345735b8eca0385085a211a88c2345507dfe5ac383c0629 | dwango/fialyzer | constant.ml | open Base
type number = Int of int | Float of float
[@@deriving sexp_of]
type t =
| Number of number
| Atom of string
[@@deriving sexp_of]
let pp = function
| Number (Int i) -> Int.to_string i
| Number (Float f) -> Float.to_string f
| Atom a -> "'" ^ a ^ "'"
| null | https://raw.githubusercontent.com/dwango/fialyzer/3c4b4fc2dacf84008910135bfef16e4ce79f9c89/lib/constant.ml | ocaml | open Base
type number = Int of int | Float of float
[@@deriving sexp_of]
type t =
| Number of number
| Atom of string
[@@deriving sexp_of]
let pp = function
| Number (Int i) -> Int.to_string i
| Number (Float f) -> Float.to_string f
| Atom a -> "'" ^ a ^ "'"
| |
1eb53ae1638781ccc3354f51e48d65b023712422a25d9cab60cd692c9f75f185 | weblocks-framework/weblocks | uri-parameters-mixin.lisp |
(in-package :weblocks)
(export '(uri-parameters-mixin uri-parameters-slotmap))
(defclass uri-parameters-mixin ()
())
(defgeneric uri-parameters-slotmap (w)
(:documentation "Returns an alist of (slotname . param-name)")
(:method (w) (declare (ignore w)) nil))
(defgeneric uri-parameter-values (w)
(:documentation "Returns an alist of (param-name . slot-value)")
(:method (w) (declare (ignore w)) nil)
(:method ((w uri-parameters-mixin))
(loop for (sname . pname) in (uri-parameters-slotmap w)
when (slot-boundp w sname)
collect (cons pname (slot-value w sname)))))
(defun maybe-generate-parameter-slot-map-fn (class slot-defs)
"When a slot contains "
(awhen (get-parameter-slot-map slot-defs)
(with-gensyms (widget)
`(defmethod uri-parameters-slotmap ((,widget ,class))
',it))))
(defun uri-parameter-def-p (slot-defs)
(member :uri-parameter (flatten slot-defs)))
(defun get-parameter-slot-map (slot-defs)
(remove-if #'null
(mapcar (lambda (slot-def)
(awhen (member :uri-parameter slot-def)
(cons (first slot-def)
(as-string (cadr it)))))
slot-defs)))
(defun as-string (obj)
(etypecase obj
(symbol (string-downcase (symbol-name obj)))
(string obj)))
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/src/widgets/widget/uri-parameters-mixin.lisp | lisp |
(in-package :weblocks)
(export '(uri-parameters-mixin uri-parameters-slotmap))
(defclass uri-parameters-mixin ()
())
(defgeneric uri-parameters-slotmap (w)
(:documentation "Returns an alist of (slotname . param-name)")
(:method (w) (declare (ignore w)) nil))
(defgeneric uri-parameter-values (w)
(:documentation "Returns an alist of (param-name . slot-value)")
(:method (w) (declare (ignore w)) nil)
(:method ((w uri-parameters-mixin))
(loop for (sname . pname) in (uri-parameters-slotmap w)
when (slot-boundp w sname)
collect (cons pname (slot-value w sname)))))
(defun maybe-generate-parameter-slot-map-fn (class slot-defs)
"When a slot contains "
(awhen (get-parameter-slot-map slot-defs)
(with-gensyms (widget)
`(defmethod uri-parameters-slotmap ((,widget ,class))
',it))))
(defun uri-parameter-def-p (slot-defs)
(member :uri-parameter (flatten slot-defs)))
(defun get-parameter-slot-map (slot-defs)
(remove-if #'null
(mapcar (lambda (slot-def)
(awhen (member :uri-parameter slot-def)
(cons (first slot-def)
(as-string (cadr it)))))
slot-defs)))
(defun as-string (obj)
(etypecase obj
(symbol (string-downcase (symbol-name obj)))
(string obj)))
| |
9fd3d0cf90dd1dac6f67ce60bdac2b0ac6df18db2f8f7be7dc4c66869eaa93c7 | NalaGinrut/artanis | session.scm | -*- indent - tabs - mode : nil ; coding : utf-8 -*-
;; Copyright (C) 2013,2014,2015,2016,2017
" Mu Lei " known as " NalaGinrut " < >
Artanis is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License and GNU
Lesser General Public License published by the Free Software
Foundation , either version 3 of the License , or ( at your option )
;; any later version.
Artanis 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 and GNU Lesser General Public License
;; for more details.
You should have received a copy of the GNU General Public License
;; and GNU Lesser General Public License along with this program.
;; If not, see </>.
(define-module (artanis session)
#:use-module (artanis utils)
#:use-module (artanis env)
#:use-module (artanis route)
#:use-module (artanis db)
#:use-module (artanis fprm)
#:use-module (artanis config)
#:use-module (srfi srfi-9)
#:use-module ((rnrs) #:select (define-record-type))
#:use-module (web request)
#:use-module (ice-9 format)
#:export (session-set!
session-ref
session-expired?
session-spawn
session-destory!
session-restore
session-from-correct-client?
add-new-session-backend
session-init
session-backend?
make-session-backend
session-backend-name
session-backend-init
session-backend-store!
session-backend-destory!
session-backend-restore
session-backend-set!
session-backend-ref))
(define (make-session args)
(let ((ht (make-hash-table)))
(for-each (lambda (e)
(hash-set! ht (car e) (cdr e)))
args)
ht))
Session identifiers should be at least 128 bits ( 16 chars )
;; long to prevent brute-force session guessing attacks.
Here , we use 256 bits .
(define (get-new-sid)
NOTE : one hex contains two chars
(define (session->alist session)
(hash-map->list cons session))
;; FIXME: maybe optional according to conf?
(define (session-from-correct-client? session rc)
(let* ((ip (remote-info (rc-req rc)))
(client (hash-ref session "client"))
(ret (string=? client ip)))
(when (not ret)
(format (current-error-port)
"[Session Hijack!] Valid sid from two different client: ~a - ~a!~%"
ip client))
ret))
(define (get-session-file sid)
(format #f "~a/prv/~a/~a.session" (current-toplevel)
(get-conf '(session path)) sid))
(define (new-session rc data expires)
(let ((expires-str (make-expires expires))
(ip (remote-info (rc-req rc))))
(make-session `(("expires" . ,expires-str)
("client" . ,ip)
("data" . ,data))))) ; data is assoc list
;; TODO: Support session-engine:
;; session.engine = redis or memcached, for taking advantage of k-v-DB.
;; TODO: session key-values should be flushed into set-cookie in rc, and should be encoded
;; with base64.
(define-record-type session-backend
(fields
name ; symbol
meta ; anything necessary for a specific backend
init ; -> session-backend
store! ; -> session-backend -> string -> hash-table
destory! ; -> session-backend -> string
restore ; -> session-backend -> string
set! ; -> session-backend -> string -> string -> object
ref)) ; -> session-backend -> string -> string
;; session.engine = db, for managing sessions with DB support.
(define (backend:session-init/db sb)
(DEBUG "Initilizing session backend `~:@(~a~)'...~%" 'db)
(let* ((mt (map-table-from-DB (session-backend-meta sb)))
(defs '((sid varchar 32)
(data text)
;; NOTE: expires should be string, NOT datetime!
;; Because datetime is not compatible with
;; expires format, so we just store it as
;; string, that's enough.
(expires varchar 29)
39 for IPv6
;; NOTE: Since Boolean type is not supported by all
DBDs , so we choose Integer to make them happy .
1 for valid , 0 for expired
(mt 'create 'Sessions defs #:if-exists? 'ignore #:primary-keys '(sid))
(DEBUG "Init session DB backend is done!~%")))
(define (backend:session-store/db sb sid ss)
(let ((mt (map-table-from-DB (session-backend-meta sb)))
(expires (hash-ref ss "expires"))
(client (hash-ref ss "client"))
(data (object->string (hash-ref ss "data")))
(valid "1"))
(mt 'set 'Sessions #:sid sid #:expires expires #:client client
#:data data #:valid valid)))
(define (backend:session-destory/db sb sid)
(let ((mt (map-table-from-DB (session-backend-meta sb))))
(mt 'set 'Sessions #:valid "0")))
(define (backend:session-restore/db sb sid)
(let* ((mt (map-table-from-DB (session-backend-meta sb)))
(cnd (where #:sid sid #:valid "1"))
(valid (mt 'get 'Sessions #:condition cnd #:ret 'top)))
(DEBUG "[backend:session-restore/db] ~a~%" valid)
(and (not (null? valid)) (apply make-session valid))))
(define (backend:session-set/db sb sid k v)
(define-syntax-rule (-> x) (and x (call-with-input-string x read)))
(let* ((mt (map-table-from-DB (session-backend-meta sb)))
(cnd (where #:sid sid #:valid "1"))
(data (-> (mt 'ref 'Sessions #:columns '(data) #:condition cnd))))
(and data
(mt 'set 'Sessions
#:data (object->string (assoc-set! data k v))
#:condition cnd))))
(define (backend:session-ref/db sb sid k)
(define-syntax-rule (-> x) (and x (call-with-input-string x read)))
(let* ((mt (map-table-from-DB (session-backend-meta sb)))
(cnd (where #:sid sid #:valid "1"))
(data (-> (mt 'ref 'Sessions #:columns '(data) #:condition cnd))))
(and data (assoc-ref data k))))
(define (new-session-backend/db)
(make-session-backend 'db
(current-connection)
backend:session-init/db
backend:session-store/db
backend:session-destory/db
backend:session-restore/db
backend:session-set/db
backend:session-ref/db))
;; session.engine = simple, for managing sessions with simple memory caching.
(define (backend:session-init/simple sb)
(DEBUG "Initilizing session backend `~:@(~a~)'...~%" 'simple))
(define (backend:session-store/simple sb sid ss)
(hash-set! (session-backend-meta sb) sid ss))
FIXME : lock needed ?
(define (backend:session-destory/simple sb sid)
(hash-remove! (session-backend-meta sb) sid))
(define (backend:session-restore/simple sb sid)
(hash-ref (session-backend-meta sb) sid))
FIXME : lock needed ?
(define (backend:session-set/simple sb sid k v)
(cond
((backend:session-restore/simple sb sid)
=> (lambda (ss) (hash-set! ss k v)))
(else
(throw 'artanis-err 500 backend:session-restore/simple
(format #f "Session id (~a) doesn't hit anything!~%" sid)))))
(define (backend:session-ref/simple sb sid k)
(cond
((backend:session-restore/simple sb sid)
=> (lambda (ss) (hash-ref (hash-ref ss "data") k)))
(else
(throw 'artanis-err 500 backend:session-ref/simple
(format #f "Session id (~a) doesn't hit anything!~%" sid)))))
(define (new-session-backend/simple)
(make-session-backend 'simple
(make-hash-table) ; here, meta is session table
backend:session-init/simple
backend:session-store/simple
backend:session-destory/simple
backend:session-restore/simple
backend:session-set/simple
backend:session-ref/simple))
(define (load-session-from-file sid)
(let ((f (get-session-file sid)))
(and (file-exists? f) ; if cookie file exists
(call-with-input-file f read))))
(define (save-session-to-file sid session)
(let* ((f (get-session-file sid))
(fp (open-file f "w"))); if file exists, the contents will be removed.
(write session fp)
(close fp)))
;; session.engine = file, for managing sessions with files.
(define (backend:session-init/file sb)
(DEBUG "Initilizing session backend `~:@(~a~)'...~%" 'file)
(let ((path (format #f "~a/prv/~a" (current-toplevel)
(get-conf '(session path)))))
(cond
((not (file-exists? path))
(mkdir path)
(DEBUG "Session path `~a' doesn't exist, created it!~%" path))
((file-is-directory? path)
(DEBUG "Session path `~a' exists, keep it for existing sessions!~%" path))
(else
(throw 'artanis-err 500 backend:session-init/file
(format #f "Session path `~a' conflict with an existed file!~%"
path))))))
(define (backend:session-store/file sb sid ss)
(let ((s (session->alist ss)))
(DEBUG "[Session] store session `~a' to file~%" sid)
(save-session-to-file sid s)))
(define (backend:session-destory/file sb sid)
(let ((f (get-session-file sid)))
(and (file-exists? f)
(delete-file f))))
(define (backend:session-restore/file sb sid)
(cond
((string-null? sid)
(DEBUG "[Session] No sid specified!~%")
no , just do nothing .
(else
(DEBUG "[Session] Try to restore session `~a' from file~%" sid)
(and=> (load-session-from-file sid) make-session))))
(define (backend:session-set/file sb sid k v)
(let ((ss (load-session-from-file sid)))
(cond
((not ss)
(DEBUG "[Session] session `~a' doesn't exist!~%" sid)
#f)
(else
(DEBUG "[Session] set ~a to ~a in session `~a'~%" k v sid)
(let ((data (assoc-ref ss "data")))
(save-session-to-file
sid
(assoc-set! ss "data" (assoc-set! data k v))))))))
(define (backend:session-ref/file sb sid k)
(let ((ss (load-session-from-file sid)))
(cond
((not ss)
(DEBUG "[Session] session `~a' doesn't exist!~%" sid)
#f)
(else (assoc-ref (assoc-ref ss "data") k)))))
(define (new-session-backend/file)
(make-session-backend 'file
#f ; here, no meta is needed.
backend:session-init/file
backend:session-store/file
backend:session-destory/file
backend:session-restore/file
backend:session-set/file
backend:session-ref/file))
(define (session-set! sid k v)
((session-backend-set! (current-session-backend))
(current-session-backend)
k v))
(define (session-ref sid k)
((session-backend-ref (current-session-backend))
(current-session-backend)
k))
(define (session-destory! sid)
((session-backend-destory! (current-session-backend))
(current-session-backend)
sid))
(define (session-expired? session)
(let ((expir (hash-ref session "expires")))
(and expir (time-expired? expir))))
(define (session-restore sid)
(let ((session ((session-backend-restore (current-session-backend))
(current-session-backend) sid)))
(and session
(cond
((session-expired? session)
(DEBUG "[Session] sid: ~a is expired, destory!~%" sid)
(session-destory! sid)
#f) ; expired then return #f
(else
(DEBUG "[Session] Restored session: ~a~%"
(hash-map->list cons session))
session))))) ; non-expired, return session
;; if no session then return #f
(define (session-store! sid session)
((session-backend-store! (current-session-backend))
(current-session-backend)
sid session)
session)
(define* (session-spawn rc #:key (data '()) (expires 3600))
(let* ((sid (get-new-sid))
(session (or (session-restore sid)
(session-store! sid (new-session rc data expires)))))
(DEBUG "Session spawned: sid - ~a, data - ~a~%" sid data)
(values sid session)))
(define *session-backend-table*
`((simple . ,new-session-backend/simple)
(db . ,new-session-backend/db)
(file . ,new-session-backend/file)))
(define (add-new-session-backend name maker)
(set! *session-backend-table*
(assoc-set! *session-backend-table* name maker)))
(define (session-init)
(cond
((assoc-ref *session-backend-table* (get-conf '(session backend)))
=> (lambda (maker)
(let ((sb (maker)))
((session-backend-init sb) sb)
(change-session-backend! sb))))
(else (error (format #f "Invalid session backdend: ~:@(~a~)"
(get-conf '(session backend)))))))
| null | https://raw.githubusercontent.com/NalaGinrut/artanis/3412d6eb5b46fde71b0965598ba085bacc2a6c12/artanis/session.scm | scheme | coding : utf-8 -*-
Copyright (C) 2013,2014,2015,2016,2017
any later version.
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License and GNU Lesser General Public License
for more details.
and GNU Lesser General Public License along with this program.
If not, see </>.
long to prevent brute-force session guessing attacks.
FIXME: maybe optional according to conf?
data is assoc list
TODO: Support session-engine:
session.engine = redis or memcached, for taking advantage of k-v-DB.
TODO: session key-values should be flushed into set-cookie in rc, and should be encoded
with base64.
symbol
anything necessary for a specific backend
-> session-backend
-> session-backend -> string -> hash-table
-> session-backend -> string
-> session-backend -> string
-> session-backend -> string -> string -> object
-> session-backend -> string -> string
session.engine = db, for managing sessions with DB support.
NOTE: expires should be string, NOT datetime!
Because datetime is not compatible with
expires format, so we just store it as
string, that's enough.
NOTE: Since Boolean type is not supported by all
session.engine = simple, for managing sessions with simple memory caching.
here, meta is session table
if cookie file exists
if file exists, the contents will be removed.
session.engine = file, for managing sessions with files.
here, no meta is needed.
expired then return #f
non-expired, return session
if no session then return #f | " Mu Lei " known as " NalaGinrut " < >
Artanis is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License and GNU
Lesser General Public License published by the Free Software
Foundation , either version 3 of the License , or ( at your option )
Artanis is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
(define-module (artanis session)
#:use-module (artanis utils)
#:use-module (artanis env)
#:use-module (artanis route)
#:use-module (artanis db)
#:use-module (artanis fprm)
#:use-module (artanis config)
#:use-module (srfi srfi-9)
#:use-module ((rnrs) #:select (define-record-type))
#:use-module (web request)
#:use-module (ice-9 format)
#:export (session-set!
session-ref
session-expired?
session-spawn
session-destory!
session-restore
session-from-correct-client?
add-new-session-backend
session-init
session-backend?
make-session-backend
session-backend-name
session-backend-init
session-backend-store!
session-backend-destory!
session-backend-restore
session-backend-set!
session-backend-ref))
(define (make-session args)
(let ((ht (make-hash-table)))
(for-each (lambda (e)
(hash-set! ht (car e) (cdr e)))
args)
ht))
Session identifiers should be at least 128 bits ( 16 chars )
Here , we use 256 bits .
(define (get-new-sid)
NOTE : one hex contains two chars
(define (session->alist session)
(hash-map->list cons session))
(define (session-from-correct-client? session rc)
(let* ((ip (remote-info (rc-req rc)))
(client (hash-ref session "client"))
(ret (string=? client ip)))
(when (not ret)
(format (current-error-port)
"[Session Hijack!] Valid sid from two different client: ~a - ~a!~%"
ip client))
ret))
(define (get-session-file sid)
(format #f "~a/prv/~a/~a.session" (current-toplevel)
(get-conf '(session path)) sid))
(define (new-session rc data expires)
(let ((expires-str (make-expires expires))
(ip (remote-info (rc-req rc))))
(make-session `(("expires" . ,expires-str)
("client" . ,ip)
(define-record-type session-backend
(fields
(define (backend:session-init/db sb)
(DEBUG "Initilizing session backend `~:@(~a~)'...~%" 'db)
(let* ((mt (map-table-from-DB (session-backend-meta sb)))
(defs '((sid varchar 32)
(data text)
(expires varchar 29)
39 for IPv6
DBDs , so we choose Integer to make them happy .
1 for valid , 0 for expired
(mt 'create 'Sessions defs #:if-exists? 'ignore #:primary-keys '(sid))
(DEBUG "Init session DB backend is done!~%")))
(define (backend:session-store/db sb sid ss)
(let ((mt (map-table-from-DB (session-backend-meta sb)))
(expires (hash-ref ss "expires"))
(client (hash-ref ss "client"))
(data (object->string (hash-ref ss "data")))
(valid "1"))
(mt 'set 'Sessions #:sid sid #:expires expires #:client client
#:data data #:valid valid)))
(define (backend:session-destory/db sb sid)
(let ((mt (map-table-from-DB (session-backend-meta sb))))
(mt 'set 'Sessions #:valid "0")))
(define (backend:session-restore/db sb sid)
(let* ((mt (map-table-from-DB (session-backend-meta sb)))
(cnd (where #:sid sid #:valid "1"))
(valid (mt 'get 'Sessions #:condition cnd #:ret 'top)))
(DEBUG "[backend:session-restore/db] ~a~%" valid)
(and (not (null? valid)) (apply make-session valid))))
(define (backend:session-set/db sb sid k v)
(define-syntax-rule (-> x) (and x (call-with-input-string x read)))
(let* ((mt (map-table-from-DB (session-backend-meta sb)))
(cnd (where #:sid sid #:valid "1"))
(data (-> (mt 'ref 'Sessions #:columns '(data) #:condition cnd))))
(and data
(mt 'set 'Sessions
#:data (object->string (assoc-set! data k v))
#:condition cnd))))
(define (backend:session-ref/db sb sid k)
(define-syntax-rule (-> x) (and x (call-with-input-string x read)))
(let* ((mt (map-table-from-DB (session-backend-meta sb)))
(cnd (where #:sid sid #:valid "1"))
(data (-> (mt 'ref 'Sessions #:columns '(data) #:condition cnd))))
(and data (assoc-ref data k))))
(define (new-session-backend/db)
(make-session-backend 'db
(current-connection)
backend:session-init/db
backend:session-store/db
backend:session-destory/db
backend:session-restore/db
backend:session-set/db
backend:session-ref/db))
(define (backend:session-init/simple sb)
(DEBUG "Initilizing session backend `~:@(~a~)'...~%" 'simple))
(define (backend:session-store/simple sb sid ss)
(hash-set! (session-backend-meta sb) sid ss))
FIXME : lock needed ?
(define (backend:session-destory/simple sb sid)
(hash-remove! (session-backend-meta sb) sid))
(define (backend:session-restore/simple sb sid)
(hash-ref (session-backend-meta sb) sid))
FIXME : lock needed ?
(define (backend:session-set/simple sb sid k v)
(cond
((backend:session-restore/simple sb sid)
=> (lambda (ss) (hash-set! ss k v)))
(else
(throw 'artanis-err 500 backend:session-restore/simple
(format #f "Session id (~a) doesn't hit anything!~%" sid)))))
(define (backend:session-ref/simple sb sid k)
(cond
((backend:session-restore/simple sb sid)
=> (lambda (ss) (hash-ref (hash-ref ss "data") k)))
(else
(throw 'artanis-err 500 backend:session-ref/simple
(format #f "Session id (~a) doesn't hit anything!~%" sid)))))
(define (new-session-backend/simple)
(make-session-backend 'simple
backend:session-init/simple
backend:session-store/simple
backend:session-destory/simple
backend:session-restore/simple
backend:session-set/simple
backend:session-ref/simple))
(define (load-session-from-file sid)
(let ((f (get-session-file sid)))
(call-with-input-file f read))))
(define (save-session-to-file sid session)
(let* ((f (get-session-file sid))
(write session fp)
(close fp)))
(define (backend:session-init/file sb)
(DEBUG "Initilizing session backend `~:@(~a~)'...~%" 'file)
(let ((path (format #f "~a/prv/~a" (current-toplevel)
(get-conf '(session path)))))
(cond
((not (file-exists? path))
(mkdir path)
(DEBUG "Session path `~a' doesn't exist, created it!~%" path))
((file-is-directory? path)
(DEBUG "Session path `~a' exists, keep it for existing sessions!~%" path))
(else
(throw 'artanis-err 500 backend:session-init/file
(format #f "Session path `~a' conflict with an existed file!~%"
path))))))
(define (backend:session-store/file sb sid ss)
(let ((s (session->alist ss)))
(DEBUG "[Session] store session `~a' to file~%" sid)
(save-session-to-file sid s)))
(define (backend:session-destory/file sb sid)
(let ((f (get-session-file sid)))
(and (file-exists? f)
(delete-file f))))
(define (backend:session-restore/file sb sid)
(cond
((string-null? sid)
(DEBUG "[Session] No sid specified!~%")
no , just do nothing .
(else
(DEBUG "[Session] Try to restore session `~a' from file~%" sid)
(and=> (load-session-from-file sid) make-session))))
(define (backend:session-set/file sb sid k v)
(let ((ss (load-session-from-file sid)))
(cond
((not ss)
(DEBUG "[Session] session `~a' doesn't exist!~%" sid)
#f)
(else
(DEBUG "[Session] set ~a to ~a in session `~a'~%" k v sid)
(let ((data (assoc-ref ss "data")))
(save-session-to-file
sid
(assoc-set! ss "data" (assoc-set! data k v))))))))
(define (backend:session-ref/file sb sid k)
(let ((ss (load-session-from-file sid)))
(cond
((not ss)
(DEBUG "[Session] session `~a' doesn't exist!~%" sid)
#f)
(else (assoc-ref (assoc-ref ss "data") k)))))
(define (new-session-backend/file)
(make-session-backend 'file
backend:session-init/file
backend:session-store/file
backend:session-destory/file
backend:session-restore/file
backend:session-set/file
backend:session-ref/file))
(define (session-set! sid k v)
((session-backend-set! (current-session-backend))
(current-session-backend)
k v))
(define (session-ref sid k)
((session-backend-ref (current-session-backend))
(current-session-backend)
k))
(define (session-destory! sid)
((session-backend-destory! (current-session-backend))
(current-session-backend)
sid))
(define (session-expired? session)
(let ((expir (hash-ref session "expires")))
(and expir (time-expired? expir))))
(define (session-restore sid)
(let ((session ((session-backend-restore (current-session-backend))
(current-session-backend) sid)))
(and session
(cond
((session-expired? session)
(DEBUG "[Session] sid: ~a is expired, destory!~%" sid)
(session-destory! sid)
(else
(DEBUG "[Session] Restored session: ~a~%"
(hash-map->list cons session))
(define (session-store! sid session)
((session-backend-store! (current-session-backend))
(current-session-backend)
sid session)
session)
(define* (session-spawn rc #:key (data '()) (expires 3600))
(let* ((sid (get-new-sid))
(session (or (session-restore sid)
(session-store! sid (new-session rc data expires)))))
(DEBUG "Session spawned: sid - ~a, data - ~a~%" sid data)
(values sid session)))
(define *session-backend-table*
`((simple . ,new-session-backend/simple)
(db . ,new-session-backend/db)
(file . ,new-session-backend/file)))
(define (add-new-session-backend name maker)
(set! *session-backend-table*
(assoc-set! *session-backend-table* name maker)))
(define (session-init)
(cond
((assoc-ref *session-backend-table* (get-conf '(session backend)))
=> (lambda (maker)
(let ((sb (maker)))
((session-backend-init sb) sb)
(change-session-backend! sb))))
(else (error (format #f "Invalid session backdend: ~:@(~a~)"
(get-conf '(session backend)))))))
|
a2d807ec954a9cf688fa630e7828744414d6b66903b12fa54b116da2306139de | decal/pathgro | path-slashes.scm | (define-module (pathgro base path-slashes)
#:export (append-slashes prepend-slashes unappend-slashes unprepend-slashes))
(use-modules (pathgro util stdio))
(define (prepend-slashes slst)
(if (null? slst)
'()
(if (string=? (substring (car slst) 0 1) "/")
(cons (car slst) (prepend-slashes (cdr slst)))
(cons (string-append "/" (car slst)) (prepend-slashes (cdr slst))))))
(define (unprepend-slashes slst)
(if (null? slst)
'()
(if (string=? (substring (car slst) 0 1) "/")
(cons (substring (car slst) 1 (string-length (car slst))) (unprepend-slashes (cdr slst)))
(cons (car slst) (unprepend-slashes (cdr slst))))))
(define (append-slashes slst)
(if (null? slst)
'()
(if (string=? (substring (car slst) 0 1) "/")
(cons (car slst) (append-slashes (cdr slst)))
(cons (string-append "/" (car slst)) (append-slashes (cdr slst))))))
(define (unappend-slashes slst)
(if (null? slst)
'()
(if (string=? (substring (car slst) (- (string-length (car slst)) 1) (string-length (car slst))) "/")
(cons (substring 0 (- (string-length (car slst)) 1)) (unappend-slashes (cdr slst)))
(cons (string-trim-right (car slst)) (unappend-slashes (cdr slst))))))
| null | https://raw.githubusercontent.com/decal/pathgro/48c4007611f9c4ae6ff24e50ae27615c65cad3b2/pathgro/base/path-slashes.scm | scheme | (define-module (pathgro base path-slashes)
#:export (append-slashes prepend-slashes unappend-slashes unprepend-slashes))
(use-modules (pathgro util stdio))
(define (prepend-slashes slst)
(if (null? slst)
'()
(if (string=? (substring (car slst) 0 1) "/")
(cons (car slst) (prepend-slashes (cdr slst)))
(cons (string-append "/" (car slst)) (prepend-slashes (cdr slst))))))
(define (unprepend-slashes slst)
(if (null? slst)
'()
(if (string=? (substring (car slst) 0 1) "/")
(cons (substring (car slst) 1 (string-length (car slst))) (unprepend-slashes (cdr slst)))
(cons (car slst) (unprepend-slashes (cdr slst))))))
(define (append-slashes slst)
(if (null? slst)
'()
(if (string=? (substring (car slst) 0 1) "/")
(cons (car slst) (append-slashes (cdr slst)))
(cons (string-append "/" (car slst)) (append-slashes (cdr slst))))))
(define (unappend-slashes slst)
(if (null? slst)
'()
(if (string=? (substring (car slst) (- (string-length (car slst)) 1) (string-length (car slst))) "/")
(cons (substring 0 (- (string-length (car slst)) 1)) (unappend-slashes (cdr slst)))
(cons (string-trim-right (car slst)) (unappend-slashes (cdr slst))))))
| |
832dd237e94e69cec8e59efee22123b785c9b5d23244e4d932b9917749ddfd50 | mentat-collective/functional-numerics | richardson_test.cljc | ;;
Copyright © 2020 .
This work is based on the Scmutils system of MIT / GNU Scheme :
Copyright © 2002 Massachusetts Institute of Technology
;;
;; This 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 software 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 code; if not, see </>.
;;
(ns sicmutils.numerical.interpolate.richardson-test
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish?]]
[sicmutils.numerical.interpolate.polynomial :as ip]
[sicmutils.numerical.interpolate.richardson :as ir]
[sicmutils.numbers]
[sicmutils.util.stream :as us]
[sicmutils.value :as v]))
(deftest richardson-limit-tests
(let [pi-seq @#'ir/archimedean-pi-sequence]
(testing "without richardson extrapolation, the sequence takes a long time."
(is (ish? {:converged? true
:terms-checked 26
:result 3.1415926535897944}
(us/seq-limit pi-seq {:tolerance v/machine-epsilon}))))
(testing "with richardson, we go faster."
(is (ish? {:converged? true
:terms-checked 7
:result 3.1415926535897936}
(-> (ir/richardson-sequence pi-seq 2 2 2)
(us/seq-limit {:tolerance v/machine-epsilon}))))
(is (ish? {:converged? false
:terms-checked 3
:result 3.1415903931299374}
(-> (take 3 pi-seq)
(ir/richardson-sequence 2 2 2)
(us/seq-limit {:tolerance v/machine-epsilon})))
"richardson-sequence bails if the input sequence runs out of terms.")
(is (ish? [2.8284271247461903
3.1391475703122276
3.1415903931299374
3.141592653286045
3.1415926535897865]
(take 5 (ir/richardson-sequence pi-seq 4)))))
(testing "richardson extrapolation is equivalent to polynomial extrapolation
to 0"
(let [h**2 (fn [i]
;; (1/t^{i + 1})^2
(-> (/ 1 (Math/pow 2 (inc i)))
(Math/pow 2)))
xs (map-indexed (fn [i fx] [(h**2 i) fx]) pi-seq)]
(is (ish? (take 7 (us/seq-limit
(ir/richardson-sequence pi-seq 4 1 1)))
(take 7 (us/seq-limit
(ip/modified-neville xs 0.0)))))))))
| null | https://raw.githubusercontent.com/mentat-collective/functional-numerics/44856b0e3cd1f0dd9f8ebb2f67f4e85a68aa8380/test/numerical/interpolate/richardson_test.cljc | clojure |
This is free software; you can redistribute it and/or modify
either version 3 of the License , or ( at
your option) any later version.
This software 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.
along with this code; if not, see </>.
(1/t^{i + 1})^2 | Copyright © 2020 .
This work is based on the Scmutils system of MIT / GNU Scheme :
Copyright © 2002 Massachusetts Institute of Technology
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
(ns sicmutils.numerical.interpolate.richardson-test
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish?]]
[sicmutils.numerical.interpolate.polynomial :as ip]
[sicmutils.numerical.interpolate.richardson :as ir]
[sicmutils.numbers]
[sicmutils.util.stream :as us]
[sicmutils.value :as v]))
(deftest richardson-limit-tests
(let [pi-seq @#'ir/archimedean-pi-sequence]
(testing "without richardson extrapolation, the sequence takes a long time."
(is (ish? {:converged? true
:terms-checked 26
:result 3.1415926535897944}
(us/seq-limit pi-seq {:tolerance v/machine-epsilon}))))
(testing "with richardson, we go faster."
(is (ish? {:converged? true
:terms-checked 7
:result 3.1415926535897936}
(-> (ir/richardson-sequence pi-seq 2 2 2)
(us/seq-limit {:tolerance v/machine-epsilon}))))
(is (ish? {:converged? false
:terms-checked 3
:result 3.1415903931299374}
(-> (take 3 pi-seq)
(ir/richardson-sequence 2 2 2)
(us/seq-limit {:tolerance v/machine-epsilon})))
"richardson-sequence bails if the input sequence runs out of terms.")
(is (ish? [2.8284271247461903
3.1391475703122276
3.1415903931299374
3.141592653286045
3.1415926535897865]
(take 5 (ir/richardson-sequence pi-seq 4)))))
(testing "richardson extrapolation is equivalent to polynomial extrapolation
to 0"
(let [h**2 (fn [i]
(-> (/ 1 (Math/pow 2 (inc i)))
(Math/pow 2)))
xs (map-indexed (fn [i fx] [(h**2 i) fx]) pi-seq)]
(is (ish? (take 7 (us/seq-limit
(ir/richardson-sequence pi-seq 4 1 1)))
(take 7 (us/seq-limit
(ip/modified-neville xs 0.0)))))))))
|
f5ba7ae95888c5a4ea9ec1618f1081302fcd2a9cdb390ddfe9fa119c7c3b78fc | maximedenes/native-coq | closure.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i*)
open Pp
open Names
open Term
open Esubst
open Environ
(*i*)
(* Flags for profiling reductions. *)
val stats : bool ref
val share : bool ref
val with_stats: 'a Lazy.t -> 'a
s Delta implies all consts ( both global (= by
[ kernel_name ] ) and local (= by [ Rel ] or [ ] ) ) , all evars , and 's .
Rem : reduction of a Rel / Var bound to a term is Delta , but reduction of
a LetIn expression is Letin reduction
[kernel_name]) and local (= by [Rel] or [Var])), all evars, and letin's.
Rem: reduction of a Rel/Var bound to a term is Delta, but reduction of
a LetIn expression is Letin reduction *)
type transparent_state = Idpred.t * Cpred.t
val all_opaque : transparent_state
val all_transparent : transparent_state
val is_transparent_variable : transparent_state -> variable -> bool
val is_transparent_constant : transparent_state -> constant -> bool
(* Sets of reduction kinds. *)
module type RedFlagsSig = sig
type reds
type red_kind
(* The different kinds of reduction *)
val fBETA : red_kind
val fDELTA : red_kind
val fIOTA : red_kind
val fZETA : red_kind
val fCONST : constant -> red_kind
val fVAR : identifier -> red_kind
(* No reduction at all *)
val no_red : reds
(* Adds a reduction kind to a set *)
val red_add : reds -> red_kind -> reds
(* Build a reduction set from scratch = iter [red_add] on [no_red] *)
val mkflags : red_kind list -> reds
(* Tests if a reduction kind is set *)
val red_set : reds -> red_kind -> bool
end
module RedFlags : RedFlagsSig
open RedFlags
val betadeltaiota : reds
val betaiotazeta : reds
val betadeltaiotanolet : reds
(***********************************************************************)
type table_key =
| ConstKey of constant
| VarKey of identifier
| RelKey of int
type 'a infos
val ref_value_cache: 'a infos -> table_key -> 'a option
val create: ('a infos -> constr -> 'a) -> reds -> env -> 'a infos
(************************************************************************)
(*s Lazy reduction. *)
[ fconstr ] is the type of frozen constr
type fconstr
[ fconstr ] can be accessed by using the function [ fterm_of ] and by
matching on type [ fterm ]
matching on type [fterm] *)
type fterm =
| FRel of int
Metas and Sorts
| FCast of fconstr * cast_kind * fconstr
| FFlex of table_key
| FInd of inductive
| FConstruct of constructor
| FApp of fconstr * fconstr array
| FFix of fixpoint * fconstr subs
| FCoFix of cofixpoint * fconstr subs
| FCases of case_info * fconstr * fconstr * fconstr array
| FLambda of int * (name * constr) list * constr * fconstr subs
| FProd of name * fconstr * fconstr
| FLetIn of name * fconstr * fconstr * constr * fconstr subs
| FEvar of existential_key * fconstr array
| FLIFT of int * fconstr
| FCLOS of constr * fconstr subs
| FLOCKED
(************************************************************************)
s A [ stack ] is a context of arguments , arguments are pushed by
[ append_stack ] one array at a time but popped with [ decomp_stack ]
one by one
[append_stack] one array at a time but popped with [decomp_stack]
one by one *)
type stack_member =
| Zapp of fconstr array
| Zcase of case_info * fconstr * fconstr array
| Zfix of fconstr * stack
| Zshift of int
| Zupdate of fconstr
and stack = stack_member list
val append_stack : fconstr array -> stack -> stack
val eta_expand_stack : stack -> stack
(* To lazy reduce a constr, create a [clos_infos] with
[create_clos_infos], inject the term to reduce with [inject]; then use
a reduction function *)
val inject : constr -> fconstr
val fterm_of : fconstr -> fterm
val term_of_fconstr : fconstr -> constr
val destFLambda :
(fconstr subs -> constr -> fconstr) -> fconstr -> name * fconstr * fconstr
(* Global and local constant cache *)
type clos_infos
val create_clos_infos : reds -> env -> clos_infos
(* Reduction function *)
(* [whd_val] is for weak head normalization *)
val whd_val : clos_infos -> fconstr -> constr
(* [whd_stack] performs weak head normalization in a given stack. It
stops whenever a reduction is blocked. *)
val whd_stack :
clos_infos -> fconstr -> stack -> fconstr * stack
(* Conversion auxiliary functions to do step by step normalisation *)
[ unfold_reference ] unfolds references in a [ fconstr ]
val unfold_reference : clos_infos -> table_key -> fconstr option
[ mind_equiv ] checks whether two inductive types are intentionally equal
val mind_equiv_infos : clos_infos -> inductive -> inductive -> bool
val eq_table_key : table_key -> table_key -> bool
(************************************************************************)
(*i This is for lazy debug *)
val lift_fconstr : int -> fconstr -> fconstr
val lift_fconstr_vect : int -> fconstr array -> fconstr array
val mk_clos : fconstr subs -> constr -> fconstr
val mk_clos_vect : fconstr subs -> constr array -> fconstr array
val mk_clos_deep :
(fconstr subs -> constr -> fconstr) ->
fconstr subs -> constr -> fconstr
val kni: clos_infos -> fconstr -> stack -> fconstr * stack
val knr: clos_infos -> fconstr -> stack -> fconstr * stack
val to_constr : (lift -> fconstr -> constr) -> lift -> fconstr -> constr
val optimise_closure : fconstr subs -> constr -> fconstr subs * constr
(* End of cbn debug section i*)
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/checker/closure.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
Flags for profiling reductions.
Sets of reduction kinds.
The different kinds of reduction
No reduction at all
Adds a reduction kind to a set
Build a reduction set from scratch = iter [red_add] on [no_red]
Tests if a reduction kind is set
*********************************************************************
**********************************************************************
s Lazy reduction.
**********************************************************************
To lazy reduce a constr, create a [clos_infos] with
[create_clos_infos], inject the term to reduce with [inject]; then use
a reduction function
Global and local constant cache
Reduction function
[whd_val] is for weak head normalization
[whd_stack] performs weak head normalization in a given stack. It
stops whenever a reduction is blocked.
Conversion auxiliary functions to do step by step normalisation
**********************************************************************
i This is for lazy debug
End of cbn debug section i | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Names
open Term
open Esubst
open Environ
val stats : bool ref
val share : bool ref
val with_stats: 'a Lazy.t -> 'a
s Delta implies all consts ( both global (= by
[ kernel_name ] ) and local (= by [ Rel ] or [ ] ) ) , all evars , and 's .
Rem : reduction of a Rel / Var bound to a term is Delta , but reduction of
a LetIn expression is Letin reduction
[kernel_name]) and local (= by [Rel] or [Var])), all evars, and letin's.
Rem: reduction of a Rel/Var bound to a term is Delta, but reduction of
a LetIn expression is Letin reduction *)
type transparent_state = Idpred.t * Cpred.t
val all_opaque : transparent_state
val all_transparent : transparent_state
val is_transparent_variable : transparent_state -> variable -> bool
val is_transparent_constant : transparent_state -> constant -> bool
module type RedFlagsSig = sig
type reds
type red_kind
val fBETA : red_kind
val fDELTA : red_kind
val fIOTA : red_kind
val fZETA : red_kind
val fCONST : constant -> red_kind
val fVAR : identifier -> red_kind
val no_red : reds
val red_add : reds -> red_kind -> reds
val mkflags : red_kind list -> reds
val red_set : reds -> red_kind -> bool
end
module RedFlags : RedFlagsSig
open RedFlags
val betadeltaiota : reds
val betaiotazeta : reds
val betadeltaiotanolet : reds
type table_key =
| ConstKey of constant
| VarKey of identifier
| RelKey of int
type 'a infos
val ref_value_cache: 'a infos -> table_key -> 'a option
val create: ('a infos -> constr -> 'a) -> reds -> env -> 'a infos
[ fconstr ] is the type of frozen constr
type fconstr
[ fconstr ] can be accessed by using the function [ fterm_of ] and by
matching on type [ fterm ]
matching on type [fterm] *)
type fterm =
| FRel of int
Metas and Sorts
| FCast of fconstr * cast_kind * fconstr
| FFlex of table_key
| FInd of inductive
| FConstruct of constructor
| FApp of fconstr * fconstr array
| FFix of fixpoint * fconstr subs
| FCoFix of cofixpoint * fconstr subs
| FCases of case_info * fconstr * fconstr * fconstr array
| FLambda of int * (name * constr) list * constr * fconstr subs
| FProd of name * fconstr * fconstr
| FLetIn of name * fconstr * fconstr * constr * fconstr subs
| FEvar of existential_key * fconstr array
| FLIFT of int * fconstr
| FCLOS of constr * fconstr subs
| FLOCKED
s A [ stack ] is a context of arguments , arguments are pushed by
[ append_stack ] one array at a time but popped with [ decomp_stack ]
one by one
[append_stack] one array at a time but popped with [decomp_stack]
one by one *)
type stack_member =
| Zapp of fconstr array
| Zcase of case_info * fconstr * fconstr array
| Zfix of fconstr * stack
| Zshift of int
| Zupdate of fconstr
and stack = stack_member list
val append_stack : fconstr array -> stack -> stack
val eta_expand_stack : stack -> stack
val inject : constr -> fconstr
val fterm_of : fconstr -> fterm
val term_of_fconstr : fconstr -> constr
val destFLambda :
(fconstr subs -> constr -> fconstr) -> fconstr -> name * fconstr * fconstr
type clos_infos
val create_clos_infos : reds -> env -> clos_infos
val whd_val : clos_infos -> fconstr -> constr
val whd_stack :
clos_infos -> fconstr -> stack -> fconstr * stack
[ unfold_reference ] unfolds references in a [ fconstr ]
val unfold_reference : clos_infos -> table_key -> fconstr option
[ mind_equiv ] checks whether two inductive types are intentionally equal
val mind_equiv_infos : clos_infos -> inductive -> inductive -> bool
val eq_table_key : table_key -> table_key -> bool
val lift_fconstr : int -> fconstr -> fconstr
val lift_fconstr_vect : int -> fconstr array -> fconstr array
val mk_clos : fconstr subs -> constr -> fconstr
val mk_clos_vect : fconstr subs -> constr array -> fconstr array
val mk_clos_deep :
(fconstr subs -> constr -> fconstr) ->
fconstr subs -> constr -> fconstr
val kni: clos_infos -> fconstr -> stack -> fconstr * stack
val knr: clos_infos -> fconstr -> stack -> fconstr * stack
val to_constr : (lift -> fconstr -> constr) -> lift -> fconstr -> constr
val optimise_closure : fconstr subs -> constr -> fconstr subs * constr
|
1edfd51e8b0faf03814d3c4ab8f9f3b8e71c249caaabb2783de0ed245594e8bf | commercialhaskell/stack | Spec.hs | import Lib (cyclicOutput)
main :: IO ()
main = cyclicOutput
| null | https://raw.githubusercontent.com/commercialhaskell/stack/255cd830627870cdef34b5e54d670ef07882523e/test/integration/tests/multi-test/files/cyclic/Spec.hs | haskell | import Lib (cyclicOutput)
main :: IO ()
main = cyclicOutput
| |
6393e62860268b5801c59d84ef9afbc1586ecb5675237ada36126e9834ff4871 | Deaf-Clojurian/sudoku-solver | solver.clj | (ns sudoku-solver.wire.in.solver
(:require
[schema.core :as s]
[sudoku-solver.wire.common :as wire.common]))
(s/defschema MatrixInput wire.common/skeleton-io)
| null | https://raw.githubusercontent.com/Deaf-Clojurian/sudoku-solver/223ef9fd178f96f13747fc99a32d76c94d890729/src/sudoku_solver/wire/in/solver.clj | clojure | (ns sudoku-solver.wire.in.solver
(:require
[schema.core :as s]
[sudoku-solver.wire.common :as wire.common]))
(s/defschema MatrixInput wire.common/skeleton-io)
| |
0ee7d98de053f49514f43375c054d5ead40c54234a3fe2839bc61bf7adec6879 | xapi-project/xen-api-libs | mime.mli |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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 Lesser General Public License for more details.
*)
type t
val mime_of_file : string -> t
val string_of_mime : t -> string
val mime_of_ext : t -> string -> string
val mime_of_file_name : t -> string -> string
| null | https://raw.githubusercontent.com/xapi-project/xen-api-libs/d603ee2b8456bc2aac99b0a4955f083e22f4f314/http-svr/mime.mli | ocaml |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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 Lesser General Public License for more details.
*)
type t
val mime_of_file : string -> t
val string_of_mime : t -> string
val mime_of_ext : t -> string -> string
val mime_of_file_name : t -> string -> string
| |
1de97f8b1b8afa2163ef24c3d1ad1dd35620a31afb4f54934343c2948ff05595 | metosin/tilakone | util.cljc | (ns tilakone.util
#?@(:cljs
[(:require [goog.string :as gstring]
[goog.string.format])]))
;;
Generic utils :
;;
(defn find-first [pred? coll]
(some (fn [v]
(when (pred? v)
v))
coll))
;;
State :
;;
(defn state [fsm state-name]
(->> fsm
:tilakone.core/states
(find-first #(-> % :tilakone.core/name (= state-name)))))
(defn current-state [fsm]
(state fsm (-> fsm :tilakone.core/state)))
;;
;; Helper to find guards or actions:
;;
(defn- get-transition-fns [fn-type fsm transition]
(let [from (-> fsm :tilakone.core/state)
to (-> transition :tilakone.core/to (or from))]
(if (= from to)
; No state change:
(concat (-> transition fn-type)
(-> fsm (state from) :tilakone.core/stay fn-type))
State change :
(concat (-> fsm (state from) :tilakone.core/leave fn-type)
(-> transition fn-type)
(-> fsm (state to) :tilakone.core/enter fn-type)))))
(def ^:private get-transition-guards (partial get-transition-fns :tilakone.core/guards))
(def ^:private get-transition-actions (partial get-transition-fns :tilakone.core/actions))
;;
;; Guards:
;;
(defn- try-guard [fsm guard]
(try
(let [guard? (-> fsm :tilakone.core/guard?)
response (-> fsm
(assoc :tilakone.core/guard guard)
(guard?))]
{:tilakone.core/allow? (if response true false)
:tilakone.core/guard guard
:tilakone.core/result response})
(catch #?(:clj clojure.lang.ExceptionInfo :cljs js/Error) e
{:tilakone.core/allow? false
:tilakone.core/guard guard
:tilakone.core/result e})))
(defn apply-guards [fsm signal transition]
(let [fsm (assoc fsm :tilakone.core/signal signal)]
(->> (get-transition-guards fsm transition)
(map #(try-guard fsm %))
(seq))))
;;
;; Transitions:
;;
(defn- default-match? [signal on]
(= signal on))
(defn get-transitions [fsm signal]
(let [match? (-> fsm :tilakone.core/match? (or default-match?))]
(->> fsm
(current-state)
:tilakone.core/transitions
(filter (fn [{:tilakone.core/keys [on]}]
(or (= on :tilakone.core/_)
(match? signal on))))
(seq))))
(defn- allowed-transition? [fsm signal transition]
(let [fsm (assoc fsm :tilakone.core/signal signal)
allow? (fn [guard] (-> (try-guard fsm guard) :tilakone.core/allow?))
guards (get-transition-guards fsm transition)]
(every? allow? guards)))
(defn- missing-transition! [fsm signal]
(throw (ex-info #?(:clj (format "missing transition from state [%s] with signal [%s]"
(-> fsm (current-state) :tilakone.core/name)
(-> signal pr-str))
:cljs (gstring/format "missing transition from state [%s] with signal [%s]"
(-> fsm (current-state) :tilakone.core/name)
(-> signal pr-str)))
{:tilakone.core/type :tilakone.core/error
:tilakone.core/error :tilakone.core/missing-transition
:tilakone.core/state (-> fsm (current-state) :tilakone.core/name)
:tilakone.core/signal signal})))
(defn- none-allowed! [fsm signal]
(throw (ex-info #?(:clj (format "transition from state [%s] with signal [%s] forbidden by guard(s)"
(-> fsm (current-state) :tilakone.core/name)
(-> signal pr-str))
:cljs (gstring/format "transition from state [%s] with signal [%s] forbidden by guard(s)"
(-> fsm (current-state) :tilakone.core/name)
(-> signal pr-str)))
{:tilakone.core/type :tilakone.core/error
:tilakone.core/error :tilakone.core/rejected-by-guard
:tilakone.core/state (-> fsm (current-state))
:tilakone.core/signal signal})))
(defn get-transition [fsm signal]
(let [transitions (or (get-transitions fsm signal)
(missing-transition! fsm signal))
allow? (partial allowed-transition? fsm signal)]
(or (find-first allow? transitions)
(none-allowed! fsm signal))))
;;
;; Actions:
;;
(defn apply-actions [fsm signal transition]
(let [action-executor (-> fsm :tilakone.core/action!)]
(-> (reduce (fn [fsm action]
(action-executor (assoc fsm :tilakone.core/action action)))
(assoc fsm :tilakone.core/signal signal)
(get-transition-actions fsm transition))
(dissoc :tilakone.core/signal)
(dissoc :tilakone.core/action))))
| null | https://raw.githubusercontent.com/metosin/tilakone/616410a17f26ebd83a7ee20d6b0cd49bc5b89c64/modules/core/src/tilakone/util.cljc | clojure |
Helper to find guards or actions:
No state change:
Guards:
Transitions:
Actions:
| (ns tilakone.util
#?@(:cljs
[(:require [goog.string :as gstring]
[goog.string.format])]))
Generic utils :
(defn find-first [pred? coll]
(some (fn [v]
(when (pred? v)
v))
coll))
State :
(defn state [fsm state-name]
(->> fsm
:tilakone.core/states
(find-first #(-> % :tilakone.core/name (= state-name)))))
(defn current-state [fsm]
(state fsm (-> fsm :tilakone.core/state)))
(defn- get-transition-fns [fn-type fsm transition]
(let [from (-> fsm :tilakone.core/state)
to (-> transition :tilakone.core/to (or from))]
(if (= from to)
(concat (-> transition fn-type)
(-> fsm (state from) :tilakone.core/stay fn-type))
State change :
(concat (-> fsm (state from) :tilakone.core/leave fn-type)
(-> transition fn-type)
(-> fsm (state to) :tilakone.core/enter fn-type)))))
(def ^:private get-transition-guards (partial get-transition-fns :tilakone.core/guards))
(def ^:private get-transition-actions (partial get-transition-fns :tilakone.core/actions))
(defn- try-guard [fsm guard]
(try
(let [guard? (-> fsm :tilakone.core/guard?)
response (-> fsm
(assoc :tilakone.core/guard guard)
(guard?))]
{:tilakone.core/allow? (if response true false)
:tilakone.core/guard guard
:tilakone.core/result response})
(catch #?(:clj clojure.lang.ExceptionInfo :cljs js/Error) e
{:tilakone.core/allow? false
:tilakone.core/guard guard
:tilakone.core/result e})))
(defn apply-guards [fsm signal transition]
(let [fsm (assoc fsm :tilakone.core/signal signal)]
(->> (get-transition-guards fsm transition)
(map #(try-guard fsm %))
(seq))))
(defn- default-match? [signal on]
(= signal on))
(defn get-transitions [fsm signal]
(let [match? (-> fsm :tilakone.core/match? (or default-match?))]
(->> fsm
(current-state)
:tilakone.core/transitions
(filter (fn [{:tilakone.core/keys [on]}]
(or (= on :tilakone.core/_)
(match? signal on))))
(seq))))
(defn- allowed-transition? [fsm signal transition]
(let [fsm (assoc fsm :tilakone.core/signal signal)
allow? (fn [guard] (-> (try-guard fsm guard) :tilakone.core/allow?))
guards (get-transition-guards fsm transition)]
(every? allow? guards)))
(defn- missing-transition! [fsm signal]
(throw (ex-info #?(:clj (format "missing transition from state [%s] with signal [%s]"
(-> fsm (current-state) :tilakone.core/name)
(-> signal pr-str))
:cljs (gstring/format "missing transition from state [%s] with signal [%s]"
(-> fsm (current-state) :tilakone.core/name)
(-> signal pr-str)))
{:tilakone.core/type :tilakone.core/error
:tilakone.core/error :tilakone.core/missing-transition
:tilakone.core/state (-> fsm (current-state) :tilakone.core/name)
:tilakone.core/signal signal})))
(defn- none-allowed! [fsm signal]
(throw (ex-info #?(:clj (format "transition from state [%s] with signal [%s] forbidden by guard(s)"
(-> fsm (current-state) :tilakone.core/name)
(-> signal pr-str))
:cljs (gstring/format "transition from state [%s] with signal [%s] forbidden by guard(s)"
(-> fsm (current-state) :tilakone.core/name)
(-> signal pr-str)))
{:tilakone.core/type :tilakone.core/error
:tilakone.core/error :tilakone.core/rejected-by-guard
:tilakone.core/state (-> fsm (current-state))
:tilakone.core/signal signal})))
(defn get-transition [fsm signal]
(let [transitions (or (get-transitions fsm signal)
(missing-transition! fsm signal))
allow? (partial allowed-transition? fsm signal)]
(or (find-first allow? transitions)
(none-allowed! fsm signal))))
(defn apply-actions [fsm signal transition]
(let [action-executor (-> fsm :tilakone.core/action!)]
(-> (reduce (fn [fsm action]
(action-executor (assoc fsm :tilakone.core/action action)))
(assoc fsm :tilakone.core/signal signal)
(get-transition-actions fsm transition))
(dissoc :tilakone.core/signal)
(dissoc :tilakone.core/action))))
|
57f4b745ff4899225df720b3a575aa4dc5166633f3472a856411ea107737a7cd | robert-strandh/SICL | binary-not-greater-defmethods.lisp | (cl:in-package #:sicl-arithmetic)
(defmethod binary-not-greater ((x fixnum) (y fixnum))
(if (cleavir-primop:fixnum-not-greater x y) t nil))
(defmethod binary-not-greater ((x ratio) (y integer))
(binary-not-greater (ceiling (numerator x) (denominator x)) y))
(defmethod binary-not-greater ((x integer) (y ratio))
(binary-not-greater x (floor (numerator y) (denominator y))))
(defmethod binary-not-greater ((x ratio) (y ratio))
(binary-not-greater (* (numerator x) (denominator y))
(* (numerator y) (denominator x))))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/8822ce17afe352923e0a08c79b010c4ef73d2011/Code/Arithmetic/binary-not-greater-defmethods.lisp | lisp | (cl:in-package #:sicl-arithmetic)
(defmethod binary-not-greater ((x fixnum) (y fixnum))
(if (cleavir-primop:fixnum-not-greater x y) t nil))
(defmethod binary-not-greater ((x ratio) (y integer))
(binary-not-greater (ceiling (numerator x) (denominator x)) y))
(defmethod binary-not-greater ((x integer) (y ratio))
(binary-not-greater x (floor (numerator y) (denominator y))))
(defmethod binary-not-greater ((x ratio) (y ratio))
(binary-not-greater (* (numerator x) (denominator y))
(* (numerator y) (denominator x))))
| |
2c97f4d2db5dfc69c8b010a36a39718806531f34965b3a669e67aa11bbeb118c | magnusjonsson/tidder-icfpc-2008 | bheap.scm | #lang scheme
;;;Binary heap implementation
(provide make insert! remove! empty?)
;;Extensible vectors combine fast random access with automatic memory management
(require "../../../libraries/scheme/evector/evector.scm")
;;Supporting functions and data structures
(define-struct node (priority value) #:transparent)
(define-struct bheap (>? e))
(define (higher? b i this)
((bheap->? b)
(node-priority (evector-ref (bheap-e b) i))
(node-priority this)))
(define (evector-copy! e i j)
(evector-set! e j (evector-ref e i)))
;;Actual implementation
(define (make >?) (make-bheap >? (evector)))
(define (empty? b) (zero? (evector-length (bheap-e b))))
;move things down until we find the right spot
(define (insert! b priority item)
(let ((e (bheap-e b)) (this (make-node priority item)))
(let bubble-loop ((i (evector-push! e #f)))
(let ((parent (quotient (- i 1) 2)))
(if (or (zero? i) (higher? b parent this)) ;root or right order?
(evector-set! e i this)
(begin (evector-copy! e parent i) (bubble-loop parent)))))))
remove first , move last to first , bubble that down and return the removed
(define (remove! b)
(let* ((e (bheap-e b))
(removed (node-value (evector-ref e 0)))
(last (sub1 (evector-length e))))
(let loop ((i 0))
(do ((child (+ (* 2 i) 1) (add1 child))
(count 2 (sub1 count))
(high last (if (higher? b child (evector-ref e high)) child high)))
((or (zero? count) (> child last)) ;no more children or out of bounds?
(evector-copy! e high i)
(if (= high last)
(begin (evector-pop! e) removed)
(loop high)))))))
| null | https://raw.githubusercontent.com/magnusjonsson/tidder-icfpc-2008/84d68fd9ac358c38e7eff99117d9cdfa86c1864a/playground/scheme/search-alt/bheap.scm | scheme | Binary heap implementation
Extensible vectors combine fast random access with automatic memory management
Supporting functions and data structures
Actual implementation
move things down until we find the right spot
root or right order?
no more children or out of bounds? | #lang scheme
(provide make insert! remove! empty?)
(require "../../../libraries/scheme/evector/evector.scm")
(define-struct node (priority value) #:transparent)
(define-struct bheap (>? e))
(define (higher? b i this)
((bheap->? b)
(node-priority (evector-ref (bheap-e b) i))
(node-priority this)))
(define (evector-copy! e i j)
(evector-set! e j (evector-ref e i)))
(define (make >?) (make-bheap >? (evector)))
(define (empty? b) (zero? (evector-length (bheap-e b))))
(define (insert! b priority item)
(let ((e (bheap-e b)) (this (make-node priority item)))
(let bubble-loop ((i (evector-push! e #f)))
(let ((parent (quotient (- i 1) 2)))
(evector-set! e i this)
(begin (evector-copy! e parent i) (bubble-loop parent)))))))
remove first , move last to first , bubble that down and return the removed
(define (remove! b)
(let* ((e (bheap-e b))
(removed (node-value (evector-ref e 0)))
(last (sub1 (evector-length e))))
(let loop ((i 0))
(do ((child (+ (* 2 i) 1) (add1 child))
(count 2 (sub1 count))
(high last (if (higher? b child (evector-ref e high)) child high)))
(evector-copy! e high i)
(if (= high last)
(begin (evector-pop! e) removed)
(loop high)))))))
|
e45575d43033390b1f397c94f74e26d16fdd630260d64250ed6bed184e4c81fe | svenpanne/EOPL3 | exercise-B-05.rkt | #lang eopl
; ------------------------------------------------------------------------------
Exercise B.5
See : exercise 2.5
(define empty-env
(lambda () '()))
(define extend-env
(lambda (var val env)
(cons (cons var val) env)))
(define apply-env
(lambda (initial-env search-var)
(letrec ((loop (lambda (env)
(cond ((null? env)
(report-no-binding-found search-var initial-env))
((and (pair? env) (pair? (car env)))
(let ((saved-var (caar env))
(saved-val (cdar env))
(saved-env (cdr env)))
(if (eqv? search-var saved-var)
saved-val
(loop saved-env))))
(else
(report-invalid-env initial-env))))))
(loop initial-env))))
(define report-no-binding-found
(lambda (search-var env)
(eopl:error 'apply-env "No binding for ~s in ~s" search-var env)))
(define report-invalid-env
(lambda (env)
(eopl:error 'apply-env "Bad environment ~s" env)))
; See: exercise B.4
; Note that we use the grammar for operators instead of the scanner spec now,
; otherwise the scanner always emits add-op for "-", even for unary minus.
(define scanner-spec
'((white-sp (whitespace) skip)
(number (digit (arbno digit)) number)
(identifier (letter (arbno (or letter digit))) symbol)))
; We use a separate production for a line of input to make the repl work smooth.
(define grammar
'((line (arith-expr ";") a-line)
(arith-expr (arith-term (arbno add-op arith-term)) an-arith-expr)
(arith-term (arith-factor (arbno mul-op arith-factor)) an-arith-term)
(arith-factor (number) number-arith-factor)
(arith-factor (identifier) var-arith-factor)
(arith-factor ("(" arith-expr ")") paren-arith-factor)
(arith-factor ("-" arith-factor) unary-minus-arith-factor)
(add-op ("+") plus-add-op)
(add-op ("-") minus-add-op)
(mul-op ("*") mul-mul-op)
(mul-op ("/") div-mul-op)))
(sllgen:make-define-datatypes scanner-spec grammar)
(define value-of-line
(lambda (env)
(lambda (l)
(cases line l
(a-line (expr)
(value-of-arith-expr env expr))))))
(define value-of-arith-expr
(lambda (env expr)
(cases arith-expr expr
(an-arith-expr (term ops terms)
(combining-value-of (value-of-term env) term (map value-of-add-op ops) terms)))))
(define value-of-term
(lambda (env)
(lambda (term)
(cases arith-term term
(an-arith-term (factor ops factors)
(combining-value-of (value-of-factor env) factor (map value-of-mul-op ops) factors))))))
(define value-of-factor
(lambda (env)
(lambda (factor)
(cases arith-factor factor
(number-arith-factor (num)
num)
(var-arith-factor (var)
(apply-env env var))
(paren-arith-factor (expr)
(value-of-arith-expr env expr))
(unary-minus-arith-factor (factor)
(- ((value-of-factor env) factor)))))))
(define value-of-add-op
(lambda (op)
(cases add-op op
(plus-add-op () +)
(minus-add-op () -))))
(define value-of-mul-op
(lambda (op)
(cases mul-op op
(mul-mul-op () *)
(div-mul-op () /))))
(define combining-value-of
(lambda (value-of term ops terms)
(let ((combine (lambda (op term accu)
(op accu (value-of term)))))
(foldl-2 combine (value-of term) ops terms))))
No ' foldl ' in # lang eopl , use a specialized version for 2 lists .
(define foldl-2
(lambda (func init lst1 lst2)
(if (null? lst1)
init
(foldl-2 func
(func (car lst1) (car lst2) init)
(cdr lst1)
(cdr lst2)))))
(define example-env
(extend-env 'foo 123
(extend-env 'bar 456
(empty-env))))
(define read-eval-print
(let ((parser (sllgen:make-stream-parser scanner-spec grammar)))
(lambda (env)
((sllgen:make-rep-loop "-->" (value-of-line env) parser)))))
| null | https://raw.githubusercontent.com/svenpanne/EOPL3/3fc14c4dbb1c53a37bd67399eba34cea8f8234cc/appendixB/exercise-B-05.rkt | racket | ------------------------------------------------------------------------------
See: exercise B.4
Note that we use the grammar for operators instead of the scanner spec now,
otherwise the scanner always emits add-op for "-", even for unary minus.
We use a separate production for a line of input to make the repl work smooth. | #lang eopl
Exercise B.5
See : exercise 2.5
(define empty-env
(lambda () '()))
(define extend-env
(lambda (var val env)
(cons (cons var val) env)))
(define apply-env
(lambda (initial-env search-var)
(letrec ((loop (lambda (env)
(cond ((null? env)
(report-no-binding-found search-var initial-env))
((and (pair? env) (pair? (car env)))
(let ((saved-var (caar env))
(saved-val (cdar env))
(saved-env (cdr env)))
(if (eqv? search-var saved-var)
saved-val
(loop saved-env))))
(else
(report-invalid-env initial-env))))))
(loop initial-env))))
(define report-no-binding-found
(lambda (search-var env)
(eopl:error 'apply-env "No binding for ~s in ~s" search-var env)))
(define report-invalid-env
(lambda (env)
(eopl:error 'apply-env "Bad environment ~s" env)))
(define scanner-spec
'((white-sp (whitespace) skip)
(number (digit (arbno digit)) number)
(identifier (letter (arbno (or letter digit))) symbol)))
(define grammar
'((line (arith-expr ";") a-line)
(arith-expr (arith-term (arbno add-op arith-term)) an-arith-expr)
(arith-term (arith-factor (arbno mul-op arith-factor)) an-arith-term)
(arith-factor (number) number-arith-factor)
(arith-factor (identifier) var-arith-factor)
(arith-factor ("(" arith-expr ")") paren-arith-factor)
(arith-factor ("-" arith-factor) unary-minus-arith-factor)
(add-op ("+") plus-add-op)
(add-op ("-") minus-add-op)
(mul-op ("*") mul-mul-op)
(mul-op ("/") div-mul-op)))
(sllgen:make-define-datatypes scanner-spec grammar)
(define value-of-line
(lambda (env)
(lambda (l)
(cases line l
(a-line (expr)
(value-of-arith-expr env expr))))))
(define value-of-arith-expr
(lambda (env expr)
(cases arith-expr expr
(an-arith-expr (term ops terms)
(combining-value-of (value-of-term env) term (map value-of-add-op ops) terms)))))
(define value-of-term
(lambda (env)
(lambda (term)
(cases arith-term term
(an-arith-term (factor ops factors)
(combining-value-of (value-of-factor env) factor (map value-of-mul-op ops) factors))))))
(define value-of-factor
(lambda (env)
(lambda (factor)
(cases arith-factor factor
(number-arith-factor (num)
num)
(var-arith-factor (var)
(apply-env env var))
(paren-arith-factor (expr)
(value-of-arith-expr env expr))
(unary-minus-arith-factor (factor)
(- ((value-of-factor env) factor)))))))
(define value-of-add-op
(lambda (op)
(cases add-op op
(plus-add-op () +)
(minus-add-op () -))))
(define value-of-mul-op
(lambda (op)
(cases mul-op op
(mul-mul-op () *)
(div-mul-op () /))))
(define combining-value-of
(lambda (value-of term ops terms)
(let ((combine (lambda (op term accu)
(op accu (value-of term)))))
(foldl-2 combine (value-of term) ops terms))))
No ' foldl ' in # lang eopl , use a specialized version for 2 lists .
(define foldl-2
(lambda (func init lst1 lst2)
(if (null? lst1)
init
(foldl-2 func
(func (car lst1) (car lst2) init)
(cdr lst1)
(cdr lst2)))))
(define example-env
(extend-env 'foo 123
(extend-env 'bar 456
(empty-env))))
(define read-eval-print
(let ((parser (sllgen:make-stream-parser scanner-spec grammar)))
(lambda (env)
((sllgen:make-rep-loop "-->" (value-of-line env) parser)))))
|
0e2bdbd687b7fd8a8a030634bf9eac7ffb14c68f64bb4fa6ef485dcf52af5823 | lnostdal/SymbolicWeb | html_template.clj | (in-ns 'symbolicweb.core)
(defn mk-HTMLTemplate "Bind Widgets to existing, static HTML.
CONTENT-FN is something like:
(fn [html-template]
[\".itembox\" html-template
\".title\" (mk-p title-model)
\".picture\" [:attr :src \"logo.png\"]
\"#sw-js-bootstrap\" (sw-js-bootstrap)]) ;; String."
^WidgetBase [^org.jsoup.nodes.Document html-resource ^Fn content-fn & args]
(mk-WidgetBase
(fn [^WidgetBase template-widget]
(let [transformation-data (content-fn template-widget)
html-resource (.clone html-resource)] ;; Always manipulate a copy to avoid any concurrency problems.
;; Assign id to template instance.
(with (.first (.select html-resource "body"))
(assert (count (.children it)) 1)
(.attr (.child it 0) "id" ^String (.id template-widget)))
(doseq [[^String selector content] (partition 2 transformation-data)]
(when-let [^org.jsoup.nodes.Element element
(with (.select html-resource selector)
(if (zero? (count it))
(do
(println "mk-HTMLTemplate: No element found for" selector "in context of" (.id template-widget))
nil)
(do
(assert (= 1 (count it))
(str "mk-HTMLTemplate: " (count it) " (i.e. not 1) elements found for for" selector
"in context of" (.id template-widget)))
(.first it))))]
(let [content-class (class content)]
COND like this is as of Clojure 1.5 faster than e.g. ( case ( .toString ( class content ) ) ... ) .
(= java.lang.String content-class)
(.text element content)
(= clojure.lang.PersistentVector content-class)
(let [^Keyword cmd (first content)]
(case cmd
:attr
(let [[^Keyword attr-key ^String attr-value] (rest content)]
(.attr element (name attr-key) attr-value))
:html
(.html element ^String (second content))))
(= symbolicweb.core.WidgetBase content-class)
(do
(.attr element "id" ^String (.id ^WidgetBase content))
(attach-branch template-widget content))))))
(.html (.select html-resource "body"))))
(apply hash-map args)))
(defn mk-HTMLCTemplate "Like mk-HTMLTemplate, but does the templating client side; in the browser, using jQuery."
^WidgetBase [^String html-resource ^Fn content-fn & args]
(let [resource-hash (str "_sw_htmlctemplate-" (hash html-resource))]
(mk-WidgetBase
(fn [^WidgetBase template-widget]
(vm-observe (.viewport template-widget) (.lifetime template-widget) true
#(when %3
Add template to Viewport once . It will be cloned and filled in ( templated ) later .
(when-not (get (ensure (:html-templates @%3)) resource-hash)
(alter (:html-templates @%3) conj resource-hash)
(js-run template-widget
"$('#_sw_htmlctemplates').append($(" (js-handle-value html-resource false) ").attr('id', '" resource-hash "'));"))
(let [transformation-data (content-fn template-widget)]
;; Instantiate (clone) template and assign HTML attr. ID for it.
(js-run template-widget
"$('#" (.id template-widget) "').replaceWith($('#" resource-hash "').clone().attr('id', '" (.id template-widget) "'));")
(doseq [[^String selector content] (partition 2 transformation-data)]
(let [content-class (class content)]
(cond
(= java.lang.String content-class)
(js-run template-widget
"$('#" (.id template-widget) "').find('" selector "').text(" (js-handle-value content false) ");")
(= clojure.lang.PersistentVector content-class)
(let [^Keyword cmd (first content)]
(case cmd
:attr
(let [[^Keyword attr-key ^String attr-value] (rest content)]
(js-run template-widget
"$('#" (.id template-widget) "').find('" selector "').attr('" (name attr-key) "', "
(js-handle-value attr-value false) ");"))
:html
(js-run template-widget
"$('#" (.id template-widget) "').find('" selector "').html(" (js-handle-value (second content) false) ");")))
(= symbolicweb.core.WidgetBase content-class)
(do
(js-run template-widget
"$('#" (.id template-widget) "').find('" selector "').attr('id', '" (.id ^WidgetBase content) "');")
(attach-branch template-widget content))))))))
(str "<div id='" (.id template-widget) "' style='display: none;'></div>"))
(apply hash-map args))))
(defn mk-TemplateElement "TemplateElements are meant to be used in context of HTMLContainer and its subtypes."
^WidgetBase [^ValueModel value-model & args]
(apply mk-he "%TemplateElement" value-model args))
(defn mk-te "Short for mk-TemplateElement."
^WidgetBase [^ValueModel value-model & args]
(apply mk-TemplateElement value-model args))
(defn mk-BlankTemplateElement "A TemplateElement which doesn't have a Model.
This might be used to setup a target for DOM events on some static content from a template."
^WidgetBase [& args]
(mk-WidgetBase (fn [_]) (apply hash-map args)))
(defn mk-bte "Short for mk-BlankTemplateElement."
^WidgetBase [& args]
(apply mk-BlankTemplateElement args))
| null | https://raw.githubusercontent.com/lnostdal/SymbolicWeb/d9600b286f70f88570deda57b05ca240e4e06567/src/symbolicweb/html_template.clj | clojure | String."
Always manipulate a copy to avoid any concurrency problems.
Assign id to template instance.
Instantiate (clone) template and assign HTML attr. ID for it. | (in-ns 'symbolicweb.core)
(defn mk-HTMLTemplate "Bind Widgets to existing, static HTML.
CONTENT-FN is something like:
(fn [html-template]
[\".itembox\" html-template
\".title\" (mk-p title-model)
\".picture\" [:attr :src \"logo.png\"]
^WidgetBase [^org.jsoup.nodes.Document html-resource ^Fn content-fn & args]
(mk-WidgetBase
(fn [^WidgetBase template-widget]
(let [transformation-data (content-fn template-widget)
(with (.first (.select html-resource "body"))
(assert (count (.children it)) 1)
(.attr (.child it 0) "id" ^String (.id template-widget)))
(doseq [[^String selector content] (partition 2 transformation-data)]
(when-let [^org.jsoup.nodes.Element element
(with (.select html-resource selector)
(if (zero? (count it))
(do
(println "mk-HTMLTemplate: No element found for" selector "in context of" (.id template-widget))
nil)
(do
(assert (= 1 (count it))
(str "mk-HTMLTemplate: " (count it) " (i.e. not 1) elements found for for" selector
"in context of" (.id template-widget)))
(.first it))))]
(let [content-class (class content)]
COND like this is as of Clojure 1.5 faster than e.g. ( case ( .toString ( class content ) ) ... ) .
(= java.lang.String content-class)
(.text element content)
(= clojure.lang.PersistentVector content-class)
(let [^Keyword cmd (first content)]
(case cmd
:attr
(let [[^Keyword attr-key ^String attr-value] (rest content)]
(.attr element (name attr-key) attr-value))
:html
(.html element ^String (second content))))
(= symbolicweb.core.WidgetBase content-class)
(do
(.attr element "id" ^String (.id ^WidgetBase content))
(attach-branch template-widget content))))))
(.html (.select html-resource "body"))))
(apply hash-map args)))
(defn mk-HTMLCTemplate "Like mk-HTMLTemplate, but does the templating client side; in the browser, using jQuery."
^WidgetBase [^String html-resource ^Fn content-fn & args]
(let [resource-hash (str "_sw_htmlctemplate-" (hash html-resource))]
(mk-WidgetBase
(fn [^WidgetBase template-widget]
(vm-observe (.viewport template-widget) (.lifetime template-widget) true
#(when %3
Add template to Viewport once . It will be cloned and filled in ( templated ) later .
(when-not (get (ensure (:html-templates @%3)) resource-hash)
(alter (:html-templates @%3) conj resource-hash)
(js-run template-widget
"$('#_sw_htmlctemplates').append($(" (js-handle-value html-resource false) ").attr('id', '" resource-hash "'));"))
(let [transformation-data (content-fn template-widget)]
(js-run template-widget
"$('#" (.id template-widget) "').replaceWith($('#" resource-hash "').clone().attr('id', '" (.id template-widget) "'));")
(doseq [[^String selector content] (partition 2 transformation-data)]
(let [content-class (class content)]
(cond
(= java.lang.String content-class)
(js-run template-widget
"$('#" (.id template-widget) "').find('" selector "').text(" (js-handle-value content false) ");")
(= clojure.lang.PersistentVector content-class)
(let [^Keyword cmd (first content)]
(case cmd
:attr
(let [[^Keyword attr-key ^String attr-value] (rest content)]
(js-run template-widget
"$('#" (.id template-widget) "').find('" selector "').attr('" (name attr-key) "', "
(js-handle-value attr-value false) ");"))
:html
(js-run template-widget
"$('#" (.id template-widget) "').find('" selector "').html(" (js-handle-value (second content) false) ");")))
(= symbolicweb.core.WidgetBase content-class)
(do
(js-run template-widget
"$('#" (.id template-widget) "').find('" selector "').attr('id', '" (.id ^WidgetBase content) "');")
(attach-branch template-widget content))))))))
(str "<div id='" (.id template-widget) "' style='display: none;'></div>"))
(apply hash-map args))))
(defn mk-TemplateElement "TemplateElements are meant to be used in context of HTMLContainer and its subtypes."
^WidgetBase [^ValueModel value-model & args]
(apply mk-he "%TemplateElement" value-model args))
(defn mk-te "Short for mk-TemplateElement."
^WidgetBase [^ValueModel value-model & args]
(apply mk-TemplateElement value-model args))
(defn mk-BlankTemplateElement "A TemplateElement which doesn't have a Model.
This might be used to setup a target for DOM events on some static content from a template."
^WidgetBase [& args]
(mk-WidgetBase (fn [_]) (apply hash-map args)))
(defn mk-bte "Short for mk-BlankTemplateElement."
^WidgetBase [& args]
(apply mk-BlankTemplateElement args))
|
d0f3f06ad740979c7ca3d00deebc8b19af8a4395afd886c3f315ba59f445c54a | S8A/htdp-exercises | ex304.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex304) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp")) #f)))
(check-expect (for/list ([i 2] [j '(a b)]) (list i j))
'((0 a) (1 b)))
(check-expect (for*/list ([i 2] [j '(a b)]) (list i j))
'((0 a) (0 b) (1 a) (1 b)))
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex304.rkt | racket | about the language level of this file in a form that our tools can easily process. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex304) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp")) #f)))
(check-expect (for/list ([i 2] [j '(a b)]) (list i j))
'((0 a) (1 b)))
(check-expect (for*/list ([i 2] [j '(a b)]) (list i j))
'((0 a) (0 b) (1 a) (1 b)))
|
bc78a97b1bdbc54308ba509f259c9713803f591df7a1441f06d6567fe78db7d4 | metasoarous/odum | server.clj | (ns odum.server
(:require [taoensso.timbre :as log :include-macros true]
[com.stuartsierra.component :as component]
[org.httpkit.server :refer (run-server)]))
(defrecord HttpServer [config ring-handler server-stop]
component/Lifecycle
(start [component]
(if server-stop
component
(let [component (component/stop component)
port (-> config :server :port)
server-stop (run-server (:handler ring-handler) {:port port})]
(log/info "HTTP server started on port: " port)
(assoc component :server-stop server-stop))))
(stop [component]
(when server-stop (server-stop))
(log/debug "HTTP server stopped")
(assoc component :server-stop nil)))
(defn new-http-server []
(map->HttpServer {}))
| null | https://raw.githubusercontent.com/metasoarous/odum/92965d14c8f5702a1bdbfcfb2e44ebbfa41c8cab/src/clj/odum/server.clj | clojure | (ns odum.server
(:require [taoensso.timbre :as log :include-macros true]
[com.stuartsierra.component :as component]
[org.httpkit.server :refer (run-server)]))
(defrecord HttpServer [config ring-handler server-stop]
component/Lifecycle
(start [component]
(if server-stop
component
(let [component (component/stop component)
port (-> config :server :port)
server-stop (run-server (:handler ring-handler) {:port port})]
(log/info "HTTP server started on port: " port)
(assoc component :server-stop server-stop))))
(stop [component]
(when server-stop (server-stop))
(log/debug "HTTP server stopped")
(assoc component :server-stop nil)))
(defn new-http-server []
(map->HttpServer {}))
| |
23f055cff08e88cc96638a28dd56424e7455dfadd518dd3ad93443d85bce6dd4 | overtone/overtone | machine_listening.clj | (ns overtone.sc.machinery.ugen.metadata.machine-listening
(:use [overtone.sc.machinery.ugen common check]))
(def specs
[
{:name "BeatTrack",
:summary "Autocorrelation based beat tracker"
:args [{:name "chain"
:doc "Audio input to track, already passed through an FFT
the expected size of FFT is 1024 for 44100
and 48000 sampling rate, and 2048 for double
those. No other sampling rates are supported. "}
{:name "lock",
:default 0
:doc "If this argument is greater than 0.5, the tracker
will lock at its current periodicity and continue
from the current phase. Whilst it updates the
model's phase and period, this is not reflected in
the output until lock goes back below 0.5. "}],
:rates #{:kr}
:num-outs 4
:doc "The underlying model assumes 4/4, but it should work on any
isochronous beat structure, though there are biases to 100-120
a fast 7/8 may not be tracked in that sense . There are
four k-rate outputs, being ticks at quarter, eighth and
sixteenth level from the determined beat, and the current
detected tempo. Note that the sixteenth note output won't
necessarily make much sense if the music being tracked has
swing; it is provided just as a convenience.
This beat tracker determines the beat, biased to the midtempo
range by weighting functions. It does not determine the
measure level, only a tactus. It is also slow reacting, using
a 6 second temporal window for its autocorrelation
maneouvres. Don't expect human musician level predictive
tracking.
On the other hand, it is tireless, relatively general (though
obviously best at transient 4/4 heavy material without much
expressive tempo variation), and can form the basis of
computer processing that is decidedly faster than human."}
{:name "Loudness",
:args [{:name "chain"
:doc "Audio input to track, which has been pre-analysed by
the FFT UGen"}
{:name "smask",
:default 0.25
:doc "Spectral masking param: lower bins mask higher bin
power within ERB bands, with a power falloff (leaky
integration multiplier) of smask per bin"}
{:name "tmask",
:default 1
:doc "Temporal masking param: the phon level let through in
an ERB band is the maximum of the new measurement, and
the previous minus tmask phons"}]
:rates #{:kr}
:doc "A perceptual loudness function which outputs loudness in
sones; this is a variant of an MP3 perceptual model, summing
excitation in ERB bands. It models simple spectral and
temporal masking, with equal loudness contour correction in
ERB bands to obtain phons (relative dB), then a phon to sone
transform. The final output is typically in the range of 0 to
64 sones, though higher values can occur with specific
synthesised stimuli." }
{:name "Onsets",
:args [{:name "chain"
:doc "an FFT chain"}
{:name "threshold",
:default 0.5
:doc "the detection threshold, typically between 0 and 1,
although in rare cases you may find values outside
this range useful"}
{:name "odftype"
:default 3
:doc "the function used to analyse the signal. Options:
nPOWER, MAGSUM, COMPLEX, RCOMPLEX (default), PHASE,
WPHASE and MKL. Default is RCOMPLEX." }
{:name "relaxtime",
:default 1
:doc "specifies the time (in seconds) for the normalisation
to forget about a recent onset. If you find too much
re-triggering (e.g. as a note dies away unevenly) then
you might wish to increase this value." }
{:name "floor",
:default 0.1
:doc "is a lower limit, connected to the idea of how quiet
the sound is expected to get without becoming
indistinguishable from noise. For some
cleanly-recorded classical music with wide dynamic
variations, I found it helpful to go down as far as
0.000001." }
{:name "mingap",
:default 10
:doc "specifies a minimum gap (in FFT frames) between onset
detections, a brute-force way to prevent too many
doubled detections." }
{:name "medianspan",
:default 11.0
:doc " specifies the size (in FFT frames) of the median
window used for smoothing the detection function
before triggering." }
{:name "whtype", :default 1}
{:name "rawodf", :default 0}],
:rates #{:kr}
:doc "An onset detector for musical audio signals - detects the
beginning of notes/drumbeats/etc. Outputs a control-rate
trigger signal which is 1 when an onset is detected, and 0
otherwise.
For the FFT chain, you should typically use a frame size of
512 or 1024 (at 44.1 kHz sampling rate) and 50% hop
size (which is the default setting in SC). For different
sampling rates choose an FFT size to cover a similar
time-span (around 10 to 20 ms).
The onset detection should work well for a general range of
monophonic and polyphonic audio signals. The onset detection
is purely based on signal analysis and does not make use of
any top-down inferences such as tempo." }
{:name "KeyTrack",
:args [{:name "chain"
:doc "Audio input to track. This must have been pre-analysed
by a 4096 size FFT." }
{:name "keydecay",
:default 2.0
:doc "Number of seconds for the influence of a window on the
final key decision to decay by 40dB (to 0.01 its
original value)"}
{:name "chromaleak",
:default 0.5
:doc "Each frame, the chroma values are set to the previous
value multiplied by the chromadecay. 0.0 will start
each frame afresh with no memory."}],
:rates #{:kr}
:doc "A (12TET major/minor) key tracker based on a pitch class
profile of energy across FFT bins and matching this to
templates for major and minor scales in all transpositions. It
assumes a 440 Hz concert A reference. Output is 0-11 C major
to B major, 12-23 C minor to B minor"}
{:name "MFCC",
:args [{:name "chain"
:doc "Audio input to track, which has been pre-analysed by
the FFT UGen"}
{:name "numcoeff",
:default 13
:doc "Number of coefficients, defaults to 13, maximum of 42"}],
:rates #{:kr}
:num-outs :variable
:doc "Generates a set of MFCCs; these are obtained from a band-based
frequency representation (using the Mel scale by default), and
then a discrete cosine transform (DCT). The DCT is an
efficient approximation for principal components analysis, so
that it allows a compression, or reduction of dimensionality,
of the data, in this case reducing 42 band readings to a
smaller set of MFCCs. A small number of features (the
coefficients) end up describing the spectrum. The MFCCs are
commonly used as timbral descriptors.
Output values are somewhat normalised for the range 0.0 to
1.0, but there are no guarantees on exact conformance to
this. Commonly, the first coefficient will be the highest
value. "
;; :init (fn [rate args spec]
;; {:args args
: num - outs ( args 1 ) } )
}
{:name "BeatTrack2",
:args [{:name "busindex"
:doc "Audio input to track, already analysed into N
features, passed in via a control bus number from
which to retrieve consecutive streams. "}
{:name "numfeatures"
:doc "How many features (ie how many control buses) are
provided"}
{:name "windowsize",
:default 2.0
:doc "Size of the temporal window desired (2.0 to 3.0
seconds models the human temporal window). You might
use longer values for stability of estimate at the
expense of reactiveness." }
{:name "phaseaccuracy",
:default 0.02
:doc "Relates to how many different phases to test. At the
default, 50 different phases spaced by phaseaccuracy
16 would be
trialed for 180 bpm. Larger phaseaccuracy means more
tests and more CPU cost." }
{:name "lock", :default 0
:doc "If this argument is greater than 0.5, the tracker will
lock at its current periodicity and continue from the
current phase. Whilst it updates the model's phase and
period, this is not reflected in the output until lock
goes back below 0.5." }
{:name "weightingscheme",
:default -2.1
:doc "Use (-2.5) for flat weighting of tempi, (-1.5) for
compensation weighting based on the number of events
tested (because different periods allow different
numbers of events within the temporal window) or
otherwise a bufnum from 0 upwards for passing an array
tempi go from 60 to
179 bpm in steps of one bpm, so you must have a buffer
of 120 values. "}],
:rates #{:kr},
:num-outs 6
:doc "Template matching beat tracker.
This beat tracker is based on exhaustively testing particular
template patterns against feature streams; the testing takes
place every 0.5 seconds. The two basic templates are a
straight (groove=0) and a swung triplet (groove=1) pattern of
16th notes; this pattern is tried out at scalings
corresponding to the tempi from 60 to 180 bpm. This is the
cross-corellation method of beat tracking. A majority vote is
taken on the best tempo detected, but this must be confirmed
by a consistency check after a phase estimate. Such a
consistency check helps to avoid wild fluctuating estimates,
but is at the expense of an additional half second delay. The
latency of the beat tracker with default settings is thus at
least 2.5 seconds; because of block-based amortisation of
calculation, it is actually around 2.8 seconds latency for a
2.0 second temporal window.
This beat tracker is designed to be flexible for user needs;
you can try out different window sizes, tempo weights and
combinations of features. However, there are no guarantees on
stability and effectiveness, and you will need to explore such
parameters for a particular situation. "}
{:name "SpecFlatness",
:args [{:name "chain"
:doc "An FFT chain"}],
:rates #{:kr}
:doc "Given an FFT chain this calculates the Spectral Flatness
measure, defined as a power spectrum's geometric mean divided
by its arithmetic mean. This gives a measure which ranges from
approx 0 for a pure sinusoid, to approx 1 for white noise.
The measure is calculated linearly. For some applications you
may wish to convert the value to a decibel scale - an example
of such conversion is shown below." }
{:name "SpecPcile",
:summary "Find a percentile of FFT magnitude spectrum"
:args [{:name "chain"
:doc "An FFT chain"}
{:name "fraction",
:default 0.5
:doc "percentage of the spectral energy you which to find
the frequency for"}
{:name "interpolate"
:default 0
:doc "Interpolation toggle - 0 off 1 on."}],
:rates #{:kr}
:doc "Given an FFT chain this calculates the cumulative distribution
of the frequency spectrum, and outputs the frequency value
which corresponds to the desired percentile.
For example, to find the frequency at which 90% of the
spectral energy lies below that frequency, you want the
90-percentile, which means the value of fraction should be
0.9. The 90-percentile or 95-percentile is often used as a
measure of spectral roll-off.
The optional third argument interpolate specifies whether
interpolation should be used to try and make the percentile
frequency estimate more accurate, at the cost of a little
higher CPU usage. Set it to 1 to enable this." }
SpecCentroid : UGen
;; {
;; *kr { | buffer |
;; ^this.multiNew('control', buffer)
;; }
;; }
{:name "SpecCentroid",
:args [{:name "chain"
:doc "An FFT chain"}],
:rates #{:kr}
:doc "Given an FFT chain, this measures the spectral centroid, which
is the weighted mean frequency, or the centre of mass of the
spectrum. (DC is ignored.)
This can be a useful indicator of the perceptual brightness of
a signal." }])
| null | https://raw.githubusercontent.com/overtone/overtone/02f8cdd2817bf810ff390b6f91d3e84d61afcc85/src/overtone/sc/machinery/ugen/metadata/machine_listening.clj | clojure | it is provided just as a convenience.
this is a variant of an MP3 perceptual model, summing
these are obtained from a band-based
:init (fn [rate args spec]
{:args args
the testing takes
this pattern is tried out at scalings
because of block-based amortisation of
{
*kr { | buffer |
^this.multiNew('control', buffer)
}
} | (ns overtone.sc.machinery.ugen.metadata.machine-listening
(:use [overtone.sc.machinery.ugen common check]))
(def specs
[
{:name "BeatTrack",
:summary "Autocorrelation based beat tracker"
:args [{:name "chain"
:doc "Audio input to track, already passed through an FFT
the expected size of FFT is 1024 for 44100
and 48000 sampling rate, and 2048 for double
those. No other sampling rates are supported. "}
{:name "lock",
:default 0
:doc "If this argument is greater than 0.5, the tracker
will lock at its current periodicity and continue
from the current phase. Whilst it updates the
model's phase and period, this is not reflected in
the output until lock goes back below 0.5. "}],
:rates #{:kr}
:num-outs 4
:doc "The underlying model assumes 4/4, but it should work on any
isochronous beat structure, though there are biases to 100-120
a fast 7/8 may not be tracked in that sense . There are
four k-rate outputs, being ticks at quarter, eighth and
sixteenth level from the determined beat, and the current
detected tempo. Note that the sixteenth note output won't
necessarily make much sense if the music being tracked has
This beat tracker determines the beat, biased to the midtempo
range by weighting functions. It does not determine the
measure level, only a tactus. It is also slow reacting, using
a 6 second temporal window for its autocorrelation
maneouvres. Don't expect human musician level predictive
tracking.
On the other hand, it is tireless, relatively general (though
obviously best at transient 4/4 heavy material without much
expressive tempo variation), and can form the basis of
computer processing that is decidedly faster than human."}
{:name "Loudness",
:args [{:name "chain"
:doc "Audio input to track, which has been pre-analysed by
the FFT UGen"}
{:name "smask",
:default 0.25
:doc "Spectral masking param: lower bins mask higher bin
power within ERB bands, with a power falloff (leaky
integration multiplier) of smask per bin"}
{:name "tmask",
:default 1
:doc "Temporal masking param: the phon level let through in
an ERB band is the maximum of the new measurement, and
the previous minus tmask phons"}]
:rates #{:kr}
:doc "A perceptual loudness function which outputs loudness in
excitation in ERB bands. It models simple spectral and
temporal masking, with equal loudness contour correction in
ERB bands to obtain phons (relative dB), then a phon to sone
transform. The final output is typically in the range of 0 to
64 sones, though higher values can occur with specific
synthesised stimuli." }
{:name "Onsets",
:args [{:name "chain"
:doc "an FFT chain"}
{:name "threshold",
:default 0.5
:doc "the detection threshold, typically between 0 and 1,
although in rare cases you may find values outside
this range useful"}
{:name "odftype"
:default 3
:doc "the function used to analyse the signal. Options:
nPOWER, MAGSUM, COMPLEX, RCOMPLEX (default), PHASE,
WPHASE and MKL. Default is RCOMPLEX." }
{:name "relaxtime",
:default 1
:doc "specifies the time (in seconds) for the normalisation
to forget about a recent onset. If you find too much
re-triggering (e.g. as a note dies away unevenly) then
you might wish to increase this value." }
{:name "floor",
:default 0.1
:doc "is a lower limit, connected to the idea of how quiet
the sound is expected to get without becoming
indistinguishable from noise. For some
cleanly-recorded classical music with wide dynamic
variations, I found it helpful to go down as far as
0.000001." }
{:name "mingap",
:default 10
:doc "specifies a minimum gap (in FFT frames) between onset
detections, a brute-force way to prevent too many
doubled detections." }
{:name "medianspan",
:default 11.0
:doc " specifies the size (in FFT frames) of the median
window used for smoothing the detection function
before triggering." }
{:name "whtype", :default 1}
{:name "rawodf", :default 0}],
:rates #{:kr}
:doc "An onset detector for musical audio signals - detects the
beginning of notes/drumbeats/etc. Outputs a control-rate
trigger signal which is 1 when an onset is detected, and 0
otherwise.
For the FFT chain, you should typically use a frame size of
512 or 1024 (at 44.1 kHz sampling rate) and 50% hop
size (which is the default setting in SC). For different
sampling rates choose an FFT size to cover a similar
time-span (around 10 to 20 ms).
The onset detection should work well for a general range of
monophonic and polyphonic audio signals. The onset detection
is purely based on signal analysis and does not make use of
any top-down inferences such as tempo." }
{:name "KeyTrack",
:args [{:name "chain"
:doc "Audio input to track. This must have been pre-analysed
by a 4096 size FFT." }
{:name "keydecay",
:default 2.0
:doc "Number of seconds for the influence of a window on the
final key decision to decay by 40dB (to 0.01 its
original value)"}
{:name "chromaleak",
:default 0.5
:doc "Each frame, the chroma values are set to the previous
value multiplied by the chromadecay. 0.0 will start
each frame afresh with no memory."}],
:rates #{:kr}
:doc "A (12TET major/minor) key tracker based on a pitch class
profile of energy across FFT bins and matching this to
templates for major and minor scales in all transpositions. It
assumes a 440 Hz concert A reference. Output is 0-11 C major
to B major, 12-23 C minor to B minor"}
{:name "MFCC",
:args [{:name "chain"
:doc "Audio input to track, which has been pre-analysed by
the FFT UGen"}
{:name "numcoeff",
:default 13
:doc "Number of coefficients, defaults to 13, maximum of 42"}],
:rates #{:kr}
:num-outs :variable
frequency representation (using the Mel scale by default), and
then a discrete cosine transform (DCT). The DCT is an
efficient approximation for principal components analysis, so
that it allows a compression, or reduction of dimensionality,
of the data, in this case reducing 42 band readings to a
smaller set of MFCCs. A small number of features (the
coefficients) end up describing the spectrum. The MFCCs are
commonly used as timbral descriptors.
Output values are somewhat normalised for the range 0.0 to
1.0, but there are no guarantees on exact conformance to
this. Commonly, the first coefficient will be the highest
value. "
: num - outs ( args 1 ) } )
}
{:name "BeatTrack2",
:args [{:name "busindex"
:doc "Audio input to track, already analysed into N
features, passed in via a control bus number from
which to retrieve consecutive streams. "}
{:name "numfeatures"
:doc "How many features (ie how many control buses) are
provided"}
{:name "windowsize",
:default 2.0
:doc "Size of the temporal window desired (2.0 to 3.0
seconds models the human temporal window). You might
use longer values for stability of estimate at the
expense of reactiveness." }
{:name "phaseaccuracy",
:default 0.02
:doc "Relates to how many different phases to test. At the
default, 50 different phases spaced by phaseaccuracy
16 would be
trialed for 180 bpm. Larger phaseaccuracy means more
tests and more CPU cost." }
{:name "lock", :default 0
:doc "If this argument is greater than 0.5, the tracker will
lock at its current periodicity and continue from the
current phase. Whilst it updates the model's phase and
period, this is not reflected in the output until lock
goes back below 0.5." }
{:name "weightingscheme",
:default -2.1
:doc "Use (-2.5) for flat weighting of tempi, (-1.5) for
compensation weighting based on the number of events
tested (because different periods allow different
numbers of events within the temporal window) or
otherwise a bufnum from 0 upwards for passing an array
tempi go from 60 to
179 bpm in steps of one bpm, so you must have a buffer
of 120 values. "}],
:rates #{:kr},
:num-outs 6
:doc "Template matching beat tracker.
This beat tracker is based on exhaustively testing particular
place every 0.5 seconds. The two basic templates are a
straight (groove=0) and a swung triplet (groove=1) pattern of
corresponding to the tempi from 60 to 180 bpm. This is the
cross-corellation method of beat tracking. A majority vote is
taken on the best tempo detected, but this must be confirmed
by a consistency check after a phase estimate. Such a
consistency check helps to avoid wild fluctuating estimates,
but is at the expense of an additional half second delay. The
latency of the beat tracker with default settings is thus at
calculation, it is actually around 2.8 seconds latency for a
2.0 second temporal window.
you can try out different window sizes, tempo weights and
combinations of features. However, there are no guarantees on
stability and effectiveness, and you will need to explore such
parameters for a particular situation. "}
{:name "SpecFlatness",
:args [{:name "chain"
:doc "An FFT chain"}],
:rates #{:kr}
:doc "Given an FFT chain this calculates the Spectral Flatness
measure, defined as a power spectrum's geometric mean divided
by its arithmetic mean. This gives a measure which ranges from
approx 0 for a pure sinusoid, to approx 1 for white noise.
The measure is calculated linearly. For some applications you
may wish to convert the value to a decibel scale - an example
of such conversion is shown below." }
{:name "SpecPcile",
:summary "Find a percentile of FFT magnitude spectrum"
:args [{:name "chain"
:doc "An FFT chain"}
{:name "fraction",
:default 0.5
:doc "percentage of the spectral energy you which to find
the frequency for"}
{:name "interpolate"
:default 0
:doc "Interpolation toggle - 0 off 1 on."}],
:rates #{:kr}
:doc "Given an FFT chain this calculates the cumulative distribution
of the frequency spectrum, and outputs the frequency value
which corresponds to the desired percentile.
For example, to find the frequency at which 90% of the
spectral energy lies below that frequency, you want the
90-percentile, which means the value of fraction should be
0.9. The 90-percentile or 95-percentile is often used as a
measure of spectral roll-off.
The optional third argument interpolate specifies whether
interpolation should be used to try and make the percentile
frequency estimate more accurate, at the cost of a little
higher CPU usage. Set it to 1 to enable this." }
SpecCentroid : UGen
{:name "SpecCentroid",
:args [{:name "chain"
:doc "An FFT chain"}],
:rates #{:kr}
:doc "Given an FFT chain, this measures the spectral centroid, which
is the weighted mean frequency, or the centre of mass of the
spectrum. (DC is ignored.)
This can be a useful indicator of the perceptual brightness of
a signal." }])
|
67d37376bed360daff9dc73bb5c14e25357656eda531682542e357d7b95bfbee | DavidAlphaFox/RabbitMQ | rabbit_msg_store_index.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is RabbitMQ .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
%%
-module(rabbit_msg_store_index).
-include("rabbit_msg_store.hrl").
-ifdef(use_specs).
-type(dir() :: any()).
-type(index_state() :: any()).
-type(keyvalue() :: any()).
-type(fieldpos() :: non_neg_integer()).
-type(fieldvalue() :: any()).
-callback new(dir()) -> index_state().
-callback recover(dir()) -> rabbit_types:ok_or_error2(index_state(), any()).
-callback lookup(rabbit_types:msg_id(), index_state()) -> ('not_found' | keyvalue()).
-callback insert(keyvalue(), index_state()) -> 'ok'.
-callback update(keyvalue(), index_state()) -> 'ok'.
-callback update_fields(rabbit_types:msg_id(), ({fieldpos(), fieldvalue()} |
[{fieldpos(), fieldvalue()}]),
index_state()) -> 'ok'.
-callback delete(rabbit_types:msg_id(), index_state()) -> 'ok'.
-callback delete_object(keyvalue(), index_state()) -> 'ok'.
-callback delete_by_file(fieldvalue(), index_state()) -> 'ok'.
-callback terminate(index_state()) -> any().
-else.
-export([behaviour_info/1]).
behaviour_info(callbacks) ->
[{new, 1},
{recover, 1},
{lookup, 2},
{insert, 2},
{update, 2},
{update_fields, 3},
{delete, 2},
{delete_by_file, 2},
{terminate, 1}];
behaviour_info(_Other) ->
undefined.
-endif.
| null | https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/src/rabbit_msg_store_index.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
| The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
-module(rabbit_msg_store_index).
-include("rabbit_msg_store.hrl").
-ifdef(use_specs).
-type(dir() :: any()).
-type(index_state() :: any()).
-type(keyvalue() :: any()).
-type(fieldpos() :: non_neg_integer()).
-type(fieldvalue() :: any()).
-callback new(dir()) -> index_state().
-callback recover(dir()) -> rabbit_types:ok_or_error2(index_state(), any()).
-callback lookup(rabbit_types:msg_id(), index_state()) -> ('not_found' | keyvalue()).
-callback insert(keyvalue(), index_state()) -> 'ok'.
-callback update(keyvalue(), index_state()) -> 'ok'.
-callback update_fields(rabbit_types:msg_id(), ({fieldpos(), fieldvalue()} |
[{fieldpos(), fieldvalue()}]),
index_state()) -> 'ok'.
-callback delete(rabbit_types:msg_id(), index_state()) -> 'ok'.
-callback delete_object(keyvalue(), index_state()) -> 'ok'.
-callback delete_by_file(fieldvalue(), index_state()) -> 'ok'.
-callback terminate(index_state()) -> any().
-else.
-export([behaviour_info/1]).
behaviour_info(callbacks) ->
[{new, 1},
{recover, 1},
{lookup, 2},
{insert, 2},
{update, 2},
{update_fields, 3},
{delete, 2},
{delete_by_file, 2},
{terminate, 1}];
behaviour_info(_Other) ->
undefined.
-endif.
|
22a0194b5a1c0fae47a459a5a72b880e879436b9f7ebb9e78a3c6f781f8f92e4 | aeternity/aeternity | aemon_default_config_SUITE.erl | -module(aemon_default_config_SUITE).
%% common_test exports
-export(
[
all/0,
init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2
]).
%% test case exports
-export([ dont_start_by_default/1 ]).
-include_lib("common_test/include/ct.hrl").
-include_lib("stdlib/include/assert.hrl").
all() -> [ dont_start_by_default ].
init_per_suite(Config) ->
Config1 = aecore_suite_utils:init_per_suite([dev1], #{}, [{symlink_name, "latest.pof"}, {test_module, ?MODULE}] ++ Config),
[{nodes, [aecore_suite_utils:node_tuple(dev1)]} | Config1].
end_per_suite(_Config) ->
ok.
init_per_testcase(_Case, Config) ->
ct:log("testcase pid: ~p", [self()]),
[{tc_start, os:timestamp()}|Config].
end_per_testcase(_Case, Config) ->
Ts0 = ?config(tc_start, Config),
ct:log("Events during TC: ~p", [[{N, aecore_suite_utils:all_events_since(N, Ts0)}
|| {_,N} <- ?config(nodes, Config)]]),
aecore_suite_utils:stop_node(dev1, Config),
ok.
%% ============================================================
%% Test cases
%% ============================================================
dont_start_by_default(Config) ->
aecore_suite_utils:start_node(dev1, Config),
Node = aecore_suite_utils:node_name(dev1),
aecore_suite_utils:connect(Node),
%% Make sure application start but no workers are present
ok = wait_for_start(Node, 10),
Children = rpc:call(Node, supervisor, which_children, [aemon_sup]),
[] = Children,
ok.
wait_for_start(_, 0) -> timeout;
wait_for_start(Node, N) ->
case lists:keysearch(aemon, 1, rpc:call(Node, application, which_applications, [])) of
{value, _} -> ok;
_ ->
timer:sleep(1000),
wait_for_start(Node, N-1)
end.
| null | https://raw.githubusercontent.com/aeternity/aeternity/b7ce6ae15dab7fa22287c2da3d4405c29bb4edd7/apps/aemon/test/aemon_default_config_SUITE.erl | erlang | common_test exports
test case exports
============================================================
Test cases
============================================================
Make sure application start but no workers are present | -module(aemon_default_config_SUITE).
-export(
[
all/0,
init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2
]).
-export([ dont_start_by_default/1 ]).
-include_lib("common_test/include/ct.hrl").
-include_lib("stdlib/include/assert.hrl").
all() -> [ dont_start_by_default ].
init_per_suite(Config) ->
Config1 = aecore_suite_utils:init_per_suite([dev1], #{}, [{symlink_name, "latest.pof"}, {test_module, ?MODULE}] ++ Config),
[{nodes, [aecore_suite_utils:node_tuple(dev1)]} | Config1].
end_per_suite(_Config) ->
ok.
init_per_testcase(_Case, Config) ->
ct:log("testcase pid: ~p", [self()]),
[{tc_start, os:timestamp()}|Config].
end_per_testcase(_Case, Config) ->
Ts0 = ?config(tc_start, Config),
ct:log("Events during TC: ~p", [[{N, aecore_suite_utils:all_events_since(N, Ts0)}
|| {_,N} <- ?config(nodes, Config)]]),
aecore_suite_utils:stop_node(dev1, Config),
ok.
dont_start_by_default(Config) ->
aecore_suite_utils:start_node(dev1, Config),
Node = aecore_suite_utils:node_name(dev1),
aecore_suite_utils:connect(Node),
ok = wait_for_start(Node, 10),
Children = rpc:call(Node, supervisor, which_children, [aemon_sup]),
[] = Children,
ok.
wait_for_start(_, 0) -> timeout;
wait_for_start(Node, N) ->
case lists:keysearch(aemon, 1, rpc:call(Node, application, which_applications, [])) of
{value, _} -> ok;
_ ->
timer:sleep(1000),
wait_for_start(Node, N-1)
end.
|
85c40197c91441beb0720ff44d13bb64959d7eef809c716baef6e90da1a67d8b | inaka/erlang_guidelines | nesting.erl | -module(nesting).
-export([bad/0, good/0]).
bad() ->
case this:function() of
has ->
try too:much() of
nested ->
receive
structures ->
it:should_be(refactored);
into ->
several:other(functions)
end
catch
_:_ ->
dont:you("think?")
end;
_ ->
i:do()
end.
good() ->
case this:function() of
calls ->
other:functions();
that ->
try do:the(internal, parts) of
what ->
was:done(in)
catch
_:the ->
previous:example()
end
end.
| null | https://raw.githubusercontent.com/inaka/erlang_guidelines/7a802a23a08d120db7e94115b4600b26194dd242/src/nesting.erl | erlang | -module(nesting).
-export([bad/0, good/0]).
bad() ->
case this:function() of
has ->
try too:much() of
nested ->
receive
structures ->
it:should_be(refactored);
into ->
several:other(functions)
end
catch
_:_ ->
dont:you("think?")
end;
_ ->
i:do()
end.
good() ->
case this:function() of
calls ->
other:functions();
that ->
try do:the(internal, parts) of
what ->
was:done(in)
catch
_:the ->
previous:example()
end
end.
| |
a19dd38b633aa6d8bdc167e104f785b304835209b9acd02805bc53b275554f89 | osstotalsoft/functional-guy | 04.ConvertingNumbers.hs | myAverage aList = sum aList / length aList
myAverage aList = sum aList / fromIntegral (length aList)
myAverage' aList = sum aList `div` length aList
half n = n / 2
half' n = fromIntegral n / 2
half'' = (`div` 2)
y = 2 :: Int
x = toInteger y | null | https://raw.githubusercontent.com/osstotalsoft/functional-guy/c02a8b22026c261a9722551f3641228dc02619ba/Chapter3.%20Haskell's%20Type%20System/Exercises/01.%20Built-in%20types/04.ConvertingNumbers.hs | haskell | myAverage aList = sum aList / length aList
myAverage aList = sum aList / fromIntegral (length aList)
myAverage' aList = sum aList `div` length aList
half n = n / 2
half' n = fromIntegral n / 2
half'' = (`div` 2)
y = 2 :: Int
x = toInteger y | |
15dd7b47f6c4917d956cbcbb473263950bd790344f83232ae0e0c9a82b002111 | geneweb/geneweb | json_converter.mli | (** Json converter driver *)
module type ConverterDriver = sig
type t
(** Json value *)
val str : string -> t
(** Convert to JSON string *)
val int : int -> t
(** Convert to JSON integer *)
val obj : (string * t) array -> t
(** Convert to JSON object *)
val null : t
(** Convert to JSON null value *)
val array : 't array -> t
(** Convert array to JSON list *)
val list : 't list -> t
(** Convert list to JSON list *)
val bool : bool -> t
(** Convert to JSON boolean *)
end
(** Functor building JSON convertion functions of the Geneweb data types. *)
module Make : functor (D : ConverterDriver) -> sig
val conv_dmy : Def.dmy -> D.t
(** Convert [dmy] to JSON *)
val conv_dmy2 : Def.dmy2 -> D.t
(** Convert [dmy2] to JSON *)
val conv_cdate : Def.cdate -> D.t
(** Convert [cdate] to JSON *)
val conv_pevent_name : string Def.gen_pers_event_name -> D.t
(** Convert [gen_pers_event_name] to JSON *)
val conv_event_witness_kind : Def.witness_kind -> D.t
(** Convert [witness_kind] to JSON *)
val conv_pevent : (Gwdb_driver.iper, string) Def.gen_pers_event -> D.t
(** Convert [gen_pers_event] to JSON *)
val conv_title_name : string Def.gen_title_name -> D.t
(** Convert [gen_title_name] to JSON *)
val conv_title : string Def.gen_title -> D.t
* Convert [ gen_title ] to JSON
val conv_relation_kind : Def.relation_kind -> D.t
(** Convert [relation_kind] to JSON *)
val conv_fevent_name : string Def.gen_fam_event_name -> D.t
(** Convert [gen_fam_event_name] to JSON *)
val conv_fevent : (Gwdb_driver.iper, string) Def.gen_fam_event -> D.t
(** Convert [gen_fam_event] to JSON *)
val conv_divorce : Def.divorce -> D.t
(** Convert [divorce] to JSON *)
val conv_relation_type : Def.relation_type -> D.t
(** Convert [relation_type] to JSON *)
val conv_rparent : (Gwdb_driver.iper, string) Def.gen_relation -> D.t
(** Convert [gen_relation] to JSON *)
val conv_death : Def.death -> D.t
(** Convert [death] to JSON *)
val conv_person : Gwdb.base -> Gwdb.person -> D.t
(** Convert [person] to JSON *)
val conv_family : Gwdb.base -> Gwdb.family -> D.t
(** Convert [family] to JSON *)
end
| null | https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/lib/json_export/json_converter.mli | ocaml | * Json converter driver
* Json value
* Convert to JSON string
* Convert to JSON integer
* Convert to JSON object
* Convert to JSON null value
* Convert array to JSON list
* Convert list to JSON list
* Convert to JSON boolean
* Functor building JSON convertion functions of the Geneweb data types.
* Convert [dmy] to JSON
* Convert [dmy2] to JSON
* Convert [cdate] to JSON
* Convert [gen_pers_event_name] to JSON
* Convert [witness_kind] to JSON
* Convert [gen_pers_event] to JSON
* Convert [gen_title_name] to JSON
* Convert [relation_kind] to JSON
* Convert [gen_fam_event_name] to JSON
* Convert [gen_fam_event] to JSON
* Convert [divorce] to JSON
* Convert [relation_type] to JSON
* Convert [gen_relation] to JSON
* Convert [death] to JSON
* Convert [person] to JSON
* Convert [family] to JSON | module type ConverterDriver = sig
type t
val str : string -> t
val int : int -> t
val obj : (string * t) array -> t
val null : t
val array : 't array -> t
val list : 't list -> t
val bool : bool -> t
end
module Make : functor (D : ConverterDriver) -> sig
val conv_dmy : Def.dmy -> D.t
val conv_dmy2 : Def.dmy2 -> D.t
val conv_cdate : Def.cdate -> D.t
val conv_pevent_name : string Def.gen_pers_event_name -> D.t
val conv_event_witness_kind : Def.witness_kind -> D.t
val conv_pevent : (Gwdb_driver.iper, string) Def.gen_pers_event -> D.t
val conv_title_name : string Def.gen_title_name -> D.t
val conv_title : string Def.gen_title -> D.t
* Convert [ gen_title ] to JSON
val conv_relation_kind : Def.relation_kind -> D.t
val conv_fevent_name : string Def.gen_fam_event_name -> D.t
val conv_fevent : (Gwdb_driver.iper, string) Def.gen_fam_event -> D.t
val conv_divorce : Def.divorce -> D.t
val conv_relation_type : Def.relation_type -> D.t
val conv_rparent : (Gwdb_driver.iper, string) Def.gen_relation -> D.t
val conv_death : Def.death -> D.t
val conv_person : Gwdb.base -> Gwdb.person -> D.t
val conv_family : Gwdb.base -> Gwdb.family -> D.t
end
|
2c436afae570d5d3563da6883c296c0729d6808a6ffe764987f17cfd520f3269 | ertugrulcetin/herfi | project.clj | (defproject herfi "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:dependencies [[ch.qos.logback/logback-classic "1.2.10"]
[clojure.java-time "0.3.3"]
[cprop "0.1.19"]
[expound "0.9.0"]
[luminus-aleph "0.1.6"]
[luminus-transit "0.1.5"]
[luminus/ring-ttl-session "0.3.3"]
[markdown-clj "1.10.8"]
[metosin/muuntaja "0.6.8"]
[metosin/reitit "0.5.15"]
[metosin/ring-http-response "0.9.3"]
[mount "0.1.16"]
[nrepl "0.9.0"]
[org.clojure/clojure "1.10.3"]
[org.clojure/core.async "1.5.648"]
[org.clojure/tools.cli "1.0.206"]
[org.clojure/tools.logging "1.2.4"]
[ring-webjars "0.2.0"]
[ring/ring-core "1.9.5"]
[ring/ring-defaults "0.3.3"]
[selmer "1.12.50"]
[clojure-msgpack "1.2.1"]
[jarohen/chime "0.3.3"]
[amalloy/ring-gzip-middleware "0.1.4"]
[ring-cors/ring-cors "0.1.13"]]
:min-lein-version "2.0.0"
:source-paths ["src/clj" "src/cljc"]
:test-paths ["test/clj"]
:resource-paths ["resources"]
:target-path "target/%s/"
:main ^:skip-aot herfi.core
:plugins []
:profiles
{:uberjar {:omit-source true
:aot :all
:uberjar-name "herfi.jar"
:source-paths ["env/prod/clj"]
:resource-paths ["env/prod/resources"]}
:dev [:project/dev :profiles/dev]
:test [:project/dev :project/test :profiles/test]
:project/dev {:jvm-opts ["-Dconf=dev-config.edn"]
:dependencies [[org.clojure/tools.namespace "1.2.0"]
[pjstadig/humane-test-output "0.11.0"]
[prone "2021-04-23"]
[ring/ring-devel "1.9.5"]
[ring/ring-mock "0.4.0"]]
:plugins [[com.jakemccrary/lein-test-refresh "0.24.1"]
[jonase/eastwood "0.3.5"]
[cider/cider-nrepl "0.26.0"]]
:source-paths ["env/dev/clj"]
:resource-paths ["env/dev/resources"]
:repl-options {:init-ns user
:init (start)
:timeout 120000}
:injections [(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)]}
:project/test {:jvm-opts ["-Dconf=test-config.edn"]
:resource-paths ["env/test/resources"]}
:profiles/dev {}
:profiles/test {}})
| null | https://raw.githubusercontent.com/ertugrulcetin/herfi/b5384d56c3e56c29ed82deafc4e56ad19ec12a60/project.clj | clojure | (defproject herfi "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:dependencies [[ch.qos.logback/logback-classic "1.2.10"]
[clojure.java-time "0.3.3"]
[cprop "0.1.19"]
[expound "0.9.0"]
[luminus-aleph "0.1.6"]
[luminus-transit "0.1.5"]
[luminus/ring-ttl-session "0.3.3"]
[markdown-clj "1.10.8"]
[metosin/muuntaja "0.6.8"]
[metosin/reitit "0.5.15"]
[metosin/ring-http-response "0.9.3"]
[mount "0.1.16"]
[nrepl "0.9.0"]
[org.clojure/clojure "1.10.3"]
[org.clojure/core.async "1.5.648"]
[org.clojure/tools.cli "1.0.206"]
[org.clojure/tools.logging "1.2.4"]
[ring-webjars "0.2.0"]
[ring/ring-core "1.9.5"]
[ring/ring-defaults "0.3.3"]
[selmer "1.12.50"]
[clojure-msgpack "1.2.1"]
[jarohen/chime "0.3.3"]
[amalloy/ring-gzip-middleware "0.1.4"]
[ring-cors/ring-cors "0.1.13"]]
:min-lein-version "2.0.0"
:source-paths ["src/clj" "src/cljc"]
:test-paths ["test/clj"]
:resource-paths ["resources"]
:target-path "target/%s/"
:main ^:skip-aot herfi.core
:plugins []
:profiles
{:uberjar {:omit-source true
:aot :all
:uberjar-name "herfi.jar"
:source-paths ["env/prod/clj"]
:resource-paths ["env/prod/resources"]}
:dev [:project/dev :profiles/dev]
:test [:project/dev :project/test :profiles/test]
:project/dev {:jvm-opts ["-Dconf=dev-config.edn"]
:dependencies [[org.clojure/tools.namespace "1.2.0"]
[pjstadig/humane-test-output "0.11.0"]
[prone "2021-04-23"]
[ring/ring-devel "1.9.5"]
[ring/ring-mock "0.4.0"]]
:plugins [[com.jakemccrary/lein-test-refresh "0.24.1"]
[jonase/eastwood "0.3.5"]
[cider/cider-nrepl "0.26.0"]]
:source-paths ["env/dev/clj"]
:resource-paths ["env/dev/resources"]
:repl-options {:init-ns user
:init (start)
:timeout 120000}
:injections [(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)]}
:project/test {:jvm-opts ["-Dconf=test-config.edn"]
:resource-paths ["env/test/resources"]}
:profiles/dev {}
:profiles/test {}})
| |
0b2ee0ead9d7411829be358b65d2c48d09c483091c02aff6813ec40c75635549 | myuon/quartz-hs | AST.hs | module Language.Quartz.AST where
import Data.Primitive.Array
import Data.Default
import Data.Dynamic
import Data.IORef
import Control.Monad.Primitive ( RealWorld )
data Literal
= IntLit Int
| DoubleLit Double
| CharLit Char
| StringLit String
| BoolLit Bool
deriving (Eq, Show)
data Id = Id [String]
deriving (Eq, Ord, Show)
data Op
= Eq
| Add
| Sub
| Mult
| Div
| Leq
| Lt
| Geq
| Gt
deriving (Eq, Show)
data Expr posn = ExprLoc posn posn (ExprRec posn)
deriving (Show)
-- テストでコード位置に左右されないようにEqでは飛ばす
instance Eq posn => Eq (Expr posn) where
(ExprLoc _ _ e1) == (ExprLoc _ _ e2) = e1 == e2
exprPos0 :: Default posn => ExprRec posn -> Expr posn
exprPos0 = ExprLoc def def
data ExprRec posn
= Var Id
| Lit Literal
| FnCall (Expr posn) [Expr posn]
| Let Id (Expr posn)
| ClosureE (Closure posn)
| OpenE Id
| Match (Expr posn) [(Pattern, Expr posn)]
| If [(Expr posn, Expr posn)]
| Procedure [Expr posn]
| Unit
| FFI Id [Expr posn]
| ArrayLit [Expr posn]
| IndexArray (Expr posn) (Expr posn)
| ForIn String (Expr posn) [Expr posn]
| Op Op (Expr posn) (Expr posn)
| Member (Expr posn) String
| RecordOf String [(String, Expr posn)]
| EnumOf Id [Expr posn]
| Assign (Expr posn) (Expr posn)
| Self Type
| MethodOf Type String (Expr posn)
| Any (Dynamic' posn)
| Stmt (Expr posn)
-- references
| LetRef String (Expr posn)
| Deref (Expr posn)
-- 以下、evaluation時のみ
primitiveのときはMutableByteArrayにしたい
| Array (MArray posn)
| RefTo Id
deriving (Eq, Show)
srcSpanExpr :: Expr posn -> Expr posn -> ExprRec posn -> Expr posn
srcSpanExpr (ExprLoc p _ _) (ExprLoc _ q _) e = ExprLoc p q e
srcSpanExpr' :: Expr posn -> ExprRec posn -> Expr posn
srcSpanExpr' (ExprLoc p q _) e = ExprLoc p q e
unwrapExpr :: Expr posn -> ExprRec posn
unwrapExpr (ExprLoc _ _ v) = v
getSrcSpan :: Expr posn -> (posn, posn)
getSrcSpan (ExprLoc p q _) = (p, q)
data Dynamic' posn = Dynamic' (Maybe posn) Dynamic
deriving (Show)
instance Eq (Dynamic' posn) where
_ == _ = False
newtype MArray posn = MArray { getMArray :: MutableArray RealWorld (Expr posn) }
deriving Eq
instance Show (MArray posn) where
show _ = "<<array>>"
newtype MRef posn = MRef { getMRef :: IORef (Expr posn) }
deriving Eq
instance Show (MRef posn) where
show _ = "<<ref>>"
data Type
= ConType Id
| VarType String
| AppType Type [Type]
| SelfType
| NoType
| FnType [Type] Type
| RefType Type
deriving (Eq, Show, Ord)
mayAppType :: Type -> [Type] -> Type
mayAppType typ vars = ((if null vars then id else (\x -> AppType x vars)) typ)
nameOfType :: Type -> Maybe String
nameOfType typ = case typ of
ConType (Id [name]) -> Just name
AppType t1 _ -> nameOfType t1
RefType t -> nameOfType t
_ -> Nothing
data Scheme = Scheme [String] Type
deriving (Eq, Show)
data Pattern
= PVar Id
| PLit Literal
| PApp Pattern [Pattern]
| PAny
deriving (Eq, Show)
data ArgType = ArgType Bool Bool [(String, Type)]
deriving (Eq, Show)
listArgTypes :: ArgType -> [Type]
listArgTypes (ArgType ref self xs) =
(if ref && self
then (RefType SelfType :)
else if self then (SelfType :) else id
)
$ map snd xs
listArgNames :: ArgType -> [String]
listArgNames (ArgType ref self xs) =
(if self then ("self" :) else id) $ map fst xs
isRefSelfArgType (ArgType ref _ _) = ref
data FuncType = FuncType [String] ArgType Type
deriving (Eq, Show)
data Closure posn = Closure FuncType (Expr posn)
deriving (Eq, Show)
data Decl posn
= Enum String [String] [EnumField]
| Record String [String] [RecordField]
| OpenD Id
| Func String (Closure posn)
| ExternalFunc String FuncType
| Interface String [String] [(String, FuncType)]
| Derive String [String] (Maybe Type) [Decl posn]
deriving (Eq, Show)
data EnumField = EnumField String [Type]
deriving (Eq, Show)
data RecordField = RecordField String Type
deriving (Eq, Show)
schemeOfArgs :: FuncType -> Scheme
schemeOfArgs at@(FuncType vars _ _) = Scheme vars (typeOfArgs at)
typeOfArgs :: FuncType -> Type
typeOfArgs (FuncType _ at ret) = FnType (listArgTypes at) ret
| null | https://raw.githubusercontent.com/myuon/quartz-hs/998edb502443d80cfe300730885de25bc7d15b08/src/Language/Quartz/AST.hs | haskell | テストでコード位置に左右されないようにEqでは飛ばす
references
以下、evaluation時のみ | module Language.Quartz.AST where
import Data.Primitive.Array
import Data.Default
import Data.Dynamic
import Data.IORef
import Control.Monad.Primitive ( RealWorld )
data Literal
= IntLit Int
| DoubleLit Double
| CharLit Char
| StringLit String
| BoolLit Bool
deriving (Eq, Show)
data Id = Id [String]
deriving (Eq, Ord, Show)
data Op
= Eq
| Add
| Sub
| Mult
| Div
| Leq
| Lt
| Geq
| Gt
deriving (Eq, Show)
data Expr posn = ExprLoc posn posn (ExprRec posn)
deriving (Show)
instance Eq posn => Eq (Expr posn) where
(ExprLoc _ _ e1) == (ExprLoc _ _ e2) = e1 == e2
exprPos0 :: Default posn => ExprRec posn -> Expr posn
exprPos0 = ExprLoc def def
data ExprRec posn
= Var Id
| Lit Literal
| FnCall (Expr posn) [Expr posn]
| Let Id (Expr posn)
| ClosureE (Closure posn)
| OpenE Id
| Match (Expr posn) [(Pattern, Expr posn)]
| If [(Expr posn, Expr posn)]
| Procedure [Expr posn]
| Unit
| FFI Id [Expr posn]
| ArrayLit [Expr posn]
| IndexArray (Expr posn) (Expr posn)
| ForIn String (Expr posn) [Expr posn]
| Op Op (Expr posn) (Expr posn)
| Member (Expr posn) String
| RecordOf String [(String, Expr posn)]
| EnumOf Id [Expr posn]
| Assign (Expr posn) (Expr posn)
| Self Type
| MethodOf Type String (Expr posn)
| Any (Dynamic' posn)
| Stmt (Expr posn)
| LetRef String (Expr posn)
| Deref (Expr posn)
primitiveのときはMutableByteArrayにしたい
| Array (MArray posn)
| RefTo Id
deriving (Eq, Show)
srcSpanExpr :: Expr posn -> Expr posn -> ExprRec posn -> Expr posn
srcSpanExpr (ExprLoc p _ _) (ExprLoc _ q _) e = ExprLoc p q e
srcSpanExpr' :: Expr posn -> ExprRec posn -> Expr posn
srcSpanExpr' (ExprLoc p q _) e = ExprLoc p q e
unwrapExpr :: Expr posn -> ExprRec posn
unwrapExpr (ExprLoc _ _ v) = v
getSrcSpan :: Expr posn -> (posn, posn)
getSrcSpan (ExprLoc p q _) = (p, q)
data Dynamic' posn = Dynamic' (Maybe posn) Dynamic
deriving (Show)
instance Eq (Dynamic' posn) where
_ == _ = False
newtype MArray posn = MArray { getMArray :: MutableArray RealWorld (Expr posn) }
deriving Eq
instance Show (MArray posn) where
show _ = "<<array>>"
newtype MRef posn = MRef { getMRef :: IORef (Expr posn) }
deriving Eq
instance Show (MRef posn) where
show _ = "<<ref>>"
data Type
= ConType Id
| VarType String
| AppType Type [Type]
| SelfType
| NoType
| FnType [Type] Type
| RefType Type
deriving (Eq, Show, Ord)
mayAppType :: Type -> [Type] -> Type
mayAppType typ vars = ((if null vars then id else (\x -> AppType x vars)) typ)
nameOfType :: Type -> Maybe String
nameOfType typ = case typ of
ConType (Id [name]) -> Just name
AppType t1 _ -> nameOfType t1
RefType t -> nameOfType t
_ -> Nothing
data Scheme = Scheme [String] Type
deriving (Eq, Show)
data Pattern
= PVar Id
| PLit Literal
| PApp Pattern [Pattern]
| PAny
deriving (Eq, Show)
data ArgType = ArgType Bool Bool [(String, Type)]
deriving (Eq, Show)
listArgTypes :: ArgType -> [Type]
listArgTypes (ArgType ref self xs) =
(if ref && self
then (RefType SelfType :)
else if self then (SelfType :) else id
)
$ map snd xs
listArgNames :: ArgType -> [String]
listArgNames (ArgType ref self xs) =
(if self then ("self" :) else id) $ map fst xs
isRefSelfArgType (ArgType ref _ _) = ref
data FuncType = FuncType [String] ArgType Type
deriving (Eq, Show)
data Closure posn = Closure FuncType (Expr posn)
deriving (Eq, Show)
data Decl posn
= Enum String [String] [EnumField]
| Record String [String] [RecordField]
| OpenD Id
| Func String (Closure posn)
| ExternalFunc String FuncType
| Interface String [String] [(String, FuncType)]
| Derive String [String] (Maybe Type) [Decl posn]
deriving (Eq, Show)
data EnumField = EnumField String [Type]
deriving (Eq, Show)
data RecordField = RecordField String Type
deriving (Eq, Show)
schemeOfArgs :: FuncType -> Scheme
schemeOfArgs at@(FuncType vars _ _) = Scheme vars (typeOfArgs at)
typeOfArgs :: FuncType -> Type
typeOfArgs (FuncType _ at ret) = FnType (listArgTypes at) ret
|
74112da4d4f991bc88f826a3d4cb73f8b86db064375203d0ed6dca98bb050c32 | igorhvr/bedlam | dynwind.scm | ; "dynwind.scm", wind-unwind-protect for Scheme
Copyright ( c ) 1992 , 1993
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
1 . Any copy made of this software must include this copyright notice
;in full.
;
2 . I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
3 . In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
;This facility is a generalization of Common Lisp `unwind-protect',
;designed to take into account the fact that continuations produced by
;CALL-WITH-CURRENT-CONTINUATION may be reentered.
; (dynamic-wind <thunk1> <thunk2> <thunk3>) procedure
;The arguments <thunk1>, <thunk2>, and <thunk3> must all be procedures
;of no arguments (thunks).
DYNAMIC - WIND calls < thunk1 > , < thunk2 > , and then < thunk3 > . The value
returned by < thunk2 > is returned as the result of DYNAMIC - WIND .
;<thunk3> is also called just before control leaves the dynamic
;context of <thunk2> by calling a continuation created outside that
;context. Furthermore, <thunk1> is called before reentering the
;dynamic context of <thunk2> by calling a continuation created inside
;that context. (Control is inside the context of <thunk2> if <thunk2>
;is on the current return stack).
;;;WARNING: This code has no provision for dealing with errors or
;;;interrupts. If an error or interrupt occurs while using
;;;dynamic-wind, the dynamic environment will be that in effect at the
;;;time of the error or interrupt.
(define dynamic:winds '())
;@
(define (dynamic-wind <thunk1> <thunk2> <thunk3>)
(<thunk1>)
(set! dynamic:winds (cons (cons <thunk1> <thunk3>) dynamic:winds))
(let ((ans (<thunk2>)))
(set! dynamic:winds (cdr dynamic:winds))
(<thunk3>)
ans))
;@
(define call-with-current-continuation
(let ((oldcc call-with-current-continuation))
(lambda (proc)
(let ((winds dynamic:winds))
(oldcc
(lambda (cont)
(proc (lambda (c2)
(dynamic:do-winds winds (- (length dynamic:winds)
(length winds)))
(cont c2)))))))))
(define (dynamic:do-winds to delta)
(cond ((eq? dynamic:winds to))
((negative? delta)
(dynamic:do-winds (cdr to) (+ 1 delta))
((caar to))
(set! dynamic:winds to))
(else
(let ((from (cdar dynamic:winds)))
(set! dynamic:winds (cdr dynamic:winds))
(from)
(dynamic:do-winds to (+ -1 delta))))))
| null | https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/iasylum/slib/3b2/dynwind.scm | scheme | "dynwind.scm", wind-unwind-protect for Scheme
Permission to copy this software, to modify it, to redistribute it,
to distribute modified versions, and to use it for any purpose is
granted, subject to the following restrictions and understandings.
in full.
this software will be error-free, and I am under no obligation to
provide any services, by way of maintenance, update, or otherwise.
material, there shall be no use of my name in any advertising,
promotional, or sales literature without prior written consent in
each case.
This facility is a generalization of Common Lisp `unwind-protect',
designed to take into account the fact that continuations produced by
CALL-WITH-CURRENT-CONTINUATION may be reentered.
(dynamic-wind <thunk1> <thunk2> <thunk3>) procedure
The arguments <thunk1>, <thunk2>, and <thunk3> must all be procedures
of no arguments (thunks).
<thunk3> is also called just before control leaves the dynamic
context of <thunk2> by calling a continuation created outside that
context. Furthermore, <thunk1> is called before reentering the
dynamic context of <thunk2> by calling a continuation created inside
that context. (Control is inside the context of <thunk2> if <thunk2>
is on the current return stack).
WARNING: This code has no provision for dealing with errors or
interrupts. If an error or interrupt occurs while using
dynamic-wind, the dynamic environment will be that in effect at the
time of the error or interrupt.
@
@ | Copyright ( c ) 1992 , 1993
1 . Any copy made of this software must include this copyright notice
2 . I have made no warranty or representation that the operation of
3 . In conjunction with products arising from the use of this
DYNAMIC - WIND calls < thunk1 > , < thunk2 > , and then < thunk3 > . The value
returned by < thunk2 > is returned as the result of DYNAMIC - WIND .
(define dynamic:winds '())
(define (dynamic-wind <thunk1> <thunk2> <thunk3>)
(<thunk1>)
(set! dynamic:winds (cons (cons <thunk1> <thunk3>) dynamic:winds))
(let ((ans (<thunk2>)))
(set! dynamic:winds (cdr dynamic:winds))
(<thunk3>)
ans))
(define call-with-current-continuation
(let ((oldcc call-with-current-continuation))
(lambda (proc)
(let ((winds dynamic:winds))
(oldcc
(lambda (cont)
(proc (lambda (c2)
(dynamic:do-winds winds (- (length dynamic:winds)
(length winds)))
(cont c2)))))))))
(define (dynamic:do-winds to delta)
(cond ((eq? dynamic:winds to))
((negative? delta)
(dynamic:do-winds (cdr to) (+ 1 delta))
((caar to))
(set! dynamic:winds to))
(else
(let ((from (cdar dynamic:winds)))
(set! dynamic:winds (cdr dynamic:winds))
(from)
(dynamic:do-winds to (+ -1 delta))))))
|
b58f0318b4b82fd2f8fbc0ba1f54f8a98603b99d25d7f206f77d52307e353838 | rpav/spell-and-dagger | text-phase.lisp | (in-package :game)
(defclass text-phase (game-phase)
((text-screen :initform nil)))
(defmethod initialize-instance :after ((p text-phase) &key text (map t) &allow-other-keys)
(with-slots (text-screen) p
(setf text-screen
(make-instance 'text-screen :text text :map map))))
(defmethod phase-resume ((p text-phase))
(ps-incref *ps*)
(with-slots (text-screen) p
(setf (ui-visible text-screen) t)))
(defmethod phase-back ((p text-phase))
(ps-decref *ps*))
| null | https://raw.githubusercontent.com/rpav/spell-and-dagger/0424416ff14a6758d27cc0f84c21bf85df024a7b/src/phases/text-phase.lisp | lisp | (in-package :game)
(defclass text-phase (game-phase)
((text-screen :initform nil)))
(defmethod initialize-instance :after ((p text-phase) &key text (map t) &allow-other-keys)
(with-slots (text-screen) p
(setf text-screen
(make-instance 'text-screen :text text :map map))))
(defmethod phase-resume ((p text-phase))
(ps-incref *ps*)
(with-slots (text-screen) p
(setf (ui-visible text-screen) t)))
(defmethod phase-back ((p text-phase))
(ps-decref *ps*))
| |
fd24e691f7cf8d9735185ef5086ef2c908ca277a7a10a85cc0b1acfcfc02db35 | ericclack/overtone-loops | pattern_03_03.clj | (ns overtone-loops.dph-book.pattern-03-03
(:use [overtone.live]
[overtone-loops.loops]
[overtone-loops.samples]))
;; Stop any currently playing music and clear any patterns
(set-up)
BAR1 BAR2 BAR3 BAR4
;; 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 &
(defloop closed-hhs
1/2 cymbal-closed [7 7 7 7 7 7 7 7 ])
(defloop sds
1/2 snare-hard [_ _ 8 _ _ _ 8 _ ])
(defloop kicks
1/2 bass-hard [8 _ _ _ 8 _ _ _ 8 _ _ _ 8 8 _ _ 8 8 _ _ _ 8 _ _ 8 8 _ 8 _ 8 _ 8
_ _ 8 _ _ 4 8 _ 8 8 8 _ _ 8 _ _ 8 _ _ _ 8 8 _ _ 8 4 8 4 8 4 8 4])
;; ---------------------------------------------
(bpm 120)
(beats-in-bar 4)
(at-bar 1
(closed-hhs)
(sds)
(kicks)
)
;;(stop)
| null | https://raw.githubusercontent.com/ericclack/overtone-loops/54b0c230c1e6bd3d378583af982db4e9ae4bda69/src/overtone_loops/dph_book/pattern_03_03.clj | clojure | Stop any currently playing music and clear any patterns
1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 &
---------------------------------------------
(stop) | (ns overtone-loops.dph-book.pattern-03-03
(:use [overtone.live]
[overtone-loops.loops]
[overtone-loops.samples]))
(set-up)
BAR1 BAR2 BAR3 BAR4
(defloop closed-hhs
1/2 cymbal-closed [7 7 7 7 7 7 7 7 ])
(defloop sds
1/2 snare-hard [_ _ 8 _ _ _ 8 _ ])
(defloop kicks
1/2 bass-hard [8 _ _ _ 8 _ _ _ 8 _ _ _ 8 8 _ _ 8 8 _ _ _ 8 _ _ 8 8 _ 8 _ 8 _ 8
_ _ 8 _ _ 4 8 _ 8 8 8 _ _ 8 _ _ 8 _ _ _ 8 8 _ _ 8 4 8 4 8 4 8 4])
(bpm 120)
(beats-in-bar 4)
(at-bar 1
(closed-hhs)
(sds)
(kicks)
)
|
4fecfc4c284e4693712adc834c619ef38dc782785b0cdee9f1ed64e44687db67 | Chattered/ocaml-monad | applicative.ml | module type Base = sig
type 'a m
val return : 'a -> 'a m
val ( <*> ) : ('a -> 'b) m -> 'a m -> 'b m
end
module type Applicative = sig
include Base
val lift1 : ('a -> 'b) -> 'a m -> 'b m
val lift2 : ('a -> 'b -> 'c) -> 'a m -> 'b m -> 'c m
val lift3 : ('a -> 'b -> 'c -> 'd) -> 'a m -> 'b m -> 'c m -> 'd m
val lift4 :
('a -> 'b -> 'c -> 'd -> 'e) -> 'a m -> 'b m -> 'c m -> 'd m -> 'e m
val ( <$> ) : ('a -> 'b) -> 'a m -> 'b m
val sequence : 'a m list -> 'a list m
val map_a : ('a -> 'b m) -> 'a list -> 'b list m
val ( <* ) : 'a m -> 'b m -> 'a m
val ( >* ) : 'a m -> 'b m -> 'b m
end
module Make (A : Base) = struct
include A
let ( <$> ) f x = return f <*> x
let lift1 f x = f <$> x
let lift2 f x y = f <$> x <*> y
let lift3 f x y z = f <$> x <*> y <*> z
let lift4 f x y z w = f <$> x <*> y <*> z <*> w
let ( <* ) x y = lift2 (fun x _ -> x) x y
let ( >* ) x y = lift2 (fun _ y -> y) x y
let rec sequence = function
| [] -> return []
| m :: ms -> lift2 (fun x xs -> x :: xs) m (sequence ms)
let map_a f xs = sequence (List.map f xs)
end
module Transform (A : Base) (Inner : Base) = struct
module A = Make (A)
type 'a m = 'a Inner.m A.m
let return x = A.return (Inner.return x)
let ( <*> ) f x = A.lift2 Inner.( <*> ) f x
end
| null | https://raw.githubusercontent.com/Chattered/ocaml-monad/2d6d1f2d443ddd517aef51d40e5cd068f456c235/src/applicative.ml | ocaml | module type Base = sig
type 'a m
val return : 'a -> 'a m
val ( <*> ) : ('a -> 'b) m -> 'a m -> 'b m
end
module type Applicative = sig
include Base
val lift1 : ('a -> 'b) -> 'a m -> 'b m
val lift2 : ('a -> 'b -> 'c) -> 'a m -> 'b m -> 'c m
val lift3 : ('a -> 'b -> 'c -> 'd) -> 'a m -> 'b m -> 'c m -> 'd m
val lift4 :
('a -> 'b -> 'c -> 'd -> 'e) -> 'a m -> 'b m -> 'c m -> 'd m -> 'e m
val ( <$> ) : ('a -> 'b) -> 'a m -> 'b m
val sequence : 'a m list -> 'a list m
val map_a : ('a -> 'b m) -> 'a list -> 'b list m
val ( <* ) : 'a m -> 'b m -> 'a m
val ( >* ) : 'a m -> 'b m -> 'b m
end
module Make (A : Base) = struct
include A
let ( <$> ) f x = return f <*> x
let lift1 f x = f <$> x
let lift2 f x y = f <$> x <*> y
let lift3 f x y z = f <$> x <*> y <*> z
let lift4 f x y z w = f <$> x <*> y <*> z <*> w
let ( <* ) x y = lift2 (fun x _ -> x) x y
let ( >* ) x y = lift2 (fun _ y -> y) x y
let rec sequence = function
| [] -> return []
| m :: ms -> lift2 (fun x xs -> x :: xs) m (sequence ms)
let map_a f xs = sequence (List.map f xs)
end
module Transform (A : Base) (Inner : Base) = struct
module A = Make (A)
type 'a m = 'a Inner.m A.m
let return x = A.return (Inner.return x)
let ( <*> ) f x = A.lift2 Inner.( <*> ) f x
end
| |
a9de1ca1e0e13c4e66ce9b69a1ada876be6deebc2f2271e3334d94699d992da1 | azimut/shiny | csound.lisp | (in-package :shiny)
NOTE : one of the limitations of the design of using & rest
;; for arbitrary params is (i think) that i cannot ask for
;; additional &key params i think...
;; Well, even if i could i won't see them on the created macro above
;; NOTE: Might be I need to add time after all...it would be nice for
;; arpgeggios
(defmethod playcsound-key :before
((iname string) (duration number)
(keynum integer) &rest rest)
;; Reset the stream if either, there is no stream or
;; is over the max lenght
(let ((c (gethash *window-name* *bar-counter*)))
(when (or (not c) (>= c 4))
(inscore-stream :meter *meter*)
(setf (gethash *window-name* *bar-counter*) 0)))
(let ((pitch)
(rhythm (inscore-rhythm duration)))
;; PITCH & RHYTHM
(if (= keynum 0)
(setf pitch "_")
(setf pitch (inscore-reverse-notes keynum)))
;; COUNTER
(incf (gethash *window-name* *bar-counter*)
(read-from-string (format nil "1~a" rhythm)))
;; WRITE: rhythm can be NIL
(inscore-write (format nil "~a~a" pitch rhythm))))
(defmethod playcsound-key :before
((iname string) (duration number)
(keynum list) &rest rest)
;; Reset the stream if either, there is no stream or
;; is over the max lenght
(let ((c (gethash *window-name* *bar-counter*)))
(when (or (not c) (>= c 4))
(inscore-stream :meter *meter*)
(setf (gethash *window-name* *bar-counter*) 0)))
(let ((rhythm (inscore-rhythm duration))
(keynums))
regardless of being a chord we only provide one length
(incf (gethash *window-name* *bar-counter*)
(read-from-string (format nil "1~d" rhythm)))
(setf keynums
(mapcar
(lambda (pitch)
(format nil "~a~a"
(if (= pitch 0)
"_"
(inscore-reverse-notes pitch))
rhythm))
keynum))
;; WRITE
(inscore-write (format nil "{~{~a~^,~}}" keynums))))
;;--------------------------------------------------
(defmethod playcsound-freq :before
((iname string) (duration number)
(keynum integer) &rest rest)
;; Reset the stream if either, there is no stream or
;; is over the max lenght
(let ((c (gethash *window-name* *bar-counter*)))
(when (or (not c) (>= c 4))
(inscore-stream :meter *meter*)
(setf (gethash *window-name* *bar-counter*) 0)))
(let ((pitch)
(rhythm (inscore-rhythm duration)))
;; PITCH & RHYTHM
(if (= keynum 0)
(setf pitch "_")
(setf pitch (inscore-reverse-notes keynum)))
;; COUNTER
(incf (gethash *window-name* *bar-counter*)
(read-from-string (format nil "1~a" rhythm)))
;; WRITE: rhythm can be NIL
(inscore-write (format nil "~a~a" pitch rhythm))))
(defmethod playcsound-freq :before
((iname string) (duration number)
(keynum list) &rest rest)
;; Reset the stream if either, there is no stream or
;; is over the max lenght
(let ((c (gethash *window-name* *bar-counter*)))
(when (or (not c) (>= c 4))
(inscore-stream :meter *meter*)
(setf (gethash *window-name* *bar-counter*) 0)))
(let ((rhythm (inscore-rhythm duration))
(keynums))
regardless of being a chord we only provide one length
(incf (gethash *window-name* *bar-counter*)
(read-from-string (format nil "1~d" rhythm)))
(setf keynums
(mapcar
(lambda (pitch)
(format nil "~a~a"
(if (= pitch 0)
"_"
(inscore-reverse-notes pitch))
rhythm))
keynum))
;; WRITE
(inscore-write (format nil "{~{~a~^,~}}" keynums))))
| null | https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/lib/inscore/csound.lisp | lisp | for arbitrary params is (i think) that i cannot ask for
additional &key params i think...
Well, even if i could i won't see them on the created macro above
NOTE: Might be I need to add time after all...it would be nice for
arpgeggios
Reset the stream if either, there is no stream or
is over the max lenght
PITCH & RHYTHM
COUNTER
WRITE: rhythm can be NIL
Reset the stream if either, there is no stream or
is over the max lenght
WRITE
--------------------------------------------------
Reset the stream if either, there is no stream or
is over the max lenght
PITCH & RHYTHM
COUNTER
WRITE: rhythm can be NIL
Reset the stream if either, there is no stream or
is over the max lenght
WRITE | (in-package :shiny)
NOTE : one of the limitations of the design of using & rest
(defmethod playcsound-key :before
((iname string) (duration number)
(keynum integer) &rest rest)
(let ((c (gethash *window-name* *bar-counter*)))
(when (or (not c) (>= c 4))
(inscore-stream :meter *meter*)
(setf (gethash *window-name* *bar-counter*) 0)))
(let ((pitch)
(rhythm (inscore-rhythm duration)))
(if (= keynum 0)
(setf pitch "_")
(setf pitch (inscore-reverse-notes keynum)))
(incf (gethash *window-name* *bar-counter*)
(read-from-string (format nil "1~a" rhythm)))
(inscore-write (format nil "~a~a" pitch rhythm))))
(defmethod playcsound-key :before
((iname string) (duration number)
(keynum list) &rest rest)
(let ((c (gethash *window-name* *bar-counter*)))
(when (or (not c) (>= c 4))
(inscore-stream :meter *meter*)
(setf (gethash *window-name* *bar-counter*) 0)))
(let ((rhythm (inscore-rhythm duration))
(keynums))
regardless of being a chord we only provide one length
(incf (gethash *window-name* *bar-counter*)
(read-from-string (format nil "1~d" rhythm)))
(setf keynums
(mapcar
(lambda (pitch)
(format nil "~a~a"
(if (= pitch 0)
"_"
(inscore-reverse-notes pitch))
rhythm))
keynum))
(inscore-write (format nil "{~{~a~^,~}}" keynums))))
(defmethod playcsound-freq :before
((iname string) (duration number)
(keynum integer) &rest rest)
(let ((c (gethash *window-name* *bar-counter*)))
(when (or (not c) (>= c 4))
(inscore-stream :meter *meter*)
(setf (gethash *window-name* *bar-counter*) 0)))
(let ((pitch)
(rhythm (inscore-rhythm duration)))
(if (= keynum 0)
(setf pitch "_")
(setf pitch (inscore-reverse-notes keynum)))
(incf (gethash *window-name* *bar-counter*)
(read-from-string (format nil "1~a" rhythm)))
(inscore-write (format nil "~a~a" pitch rhythm))))
(defmethod playcsound-freq :before
((iname string) (duration number)
(keynum list) &rest rest)
(let ((c (gethash *window-name* *bar-counter*)))
(when (or (not c) (>= c 4))
(inscore-stream :meter *meter*)
(setf (gethash *window-name* *bar-counter*) 0)))
(let ((rhythm (inscore-rhythm duration))
(keynums))
regardless of being a chord we only provide one length
(incf (gethash *window-name* *bar-counter*)
(read-from-string (format nil "1~d" rhythm)))
(setf keynums
(mapcar
(lambda (pitch)
(format nil "~a~a"
(if (= pitch 0)
"_"
(inscore-reverse-notes pitch))
rhythm))
keynum))
(inscore-write (format nil "{~{~a~^,~}}" keynums))))
|
98ddf8aba3a72614579c6282416836e0156597661bea6243d6f98d4a8c8c4b52 | falsetru/htdp | 39.2.2.scm | #lang racket
(define COLORS
'(black white red blue green gold pink orange purple navy))
(define (make-master)
(local ((define target1 (first COLORS))
(define target2 (first COLORS))
(define (random-pick xs)
(list-ref xs (random (length xs))))
(define (master)
(begin (set! target1 (random-pick COLORS))
(set! target2 (random-pick COLORS))
))
(define (check-color guess1 guess2 target1 target2)
(cond [(and (symbol=? guess1 target1) (symbol=? guess2 target2)) 'Perfect!]
[(or (symbol=? guess1 target1) (symbol=? guess2 target2)) 'OneColorAtCorrectPosition]
[(or (symbol=? guess1 target2) (symbol=? guess2 target1)) 'OneColorOccurs]
[else 'NothingCorrect]))
(define (master-check guess1 guess2)
(check-color guess1 guess2 target1 target2))
(define (setup-targets t1 t2)
(begin
(set! target1 t1)
(set! target2 t2)))
(define (service-manager msg)
(cond [(symbol=? msg 'master-check) master-check]
[(symbol=? msg 'cheat) (list target1 target2)]
[(symbol=? msg 'cheat2) setup-targets]
[else (error 'make-master "message not understood")]))
)
service-manager
))
(require rackunit)
(require rackunit/text-ui)
(define make-master-tests
(test-suite
"Test for make-master"
(test-case
""
(define master1 (make-master))
(define master-check (master1 'master-check))
((master1 'cheat2) 'pink 'navy)
(check-equal? (master1 'cheat) '(pink navy))
(check-equal? (master-check 'red 'red) 'NothingCorrect)
(check-equal? (master-check 'black 'pink) 'OneColorOccurs)
)
))
(exit (run-tests make-master-tests))
| null | https://raw.githubusercontent.com/falsetru/htdp/4cdad3b999f19b89ff4fa7561839cbcbaad274df/39/39.2.2.scm | scheme | #lang racket
(define COLORS
'(black white red blue green gold pink orange purple navy))
(define (make-master)
(local ((define target1 (first COLORS))
(define target2 (first COLORS))
(define (random-pick xs)
(list-ref xs (random (length xs))))
(define (master)
(begin (set! target1 (random-pick COLORS))
(set! target2 (random-pick COLORS))
))
(define (check-color guess1 guess2 target1 target2)
(cond [(and (symbol=? guess1 target1) (symbol=? guess2 target2)) 'Perfect!]
[(or (symbol=? guess1 target1) (symbol=? guess2 target2)) 'OneColorAtCorrectPosition]
[(or (symbol=? guess1 target2) (symbol=? guess2 target1)) 'OneColorOccurs]
[else 'NothingCorrect]))
(define (master-check guess1 guess2)
(check-color guess1 guess2 target1 target2))
(define (setup-targets t1 t2)
(begin
(set! target1 t1)
(set! target2 t2)))
(define (service-manager msg)
(cond [(symbol=? msg 'master-check) master-check]
[(symbol=? msg 'cheat) (list target1 target2)]
[(symbol=? msg 'cheat2) setup-targets]
[else (error 'make-master "message not understood")]))
)
service-manager
))
(require rackunit)
(require rackunit/text-ui)
(define make-master-tests
(test-suite
"Test for make-master"
(test-case
""
(define master1 (make-master))
(define master-check (master1 'master-check))
((master1 'cheat2) 'pink 'navy)
(check-equal? (master1 'cheat) '(pink navy))
(check-equal? (master-check 'red 'red) 'NothingCorrect)
(check-equal? (master-check 'black 'pink) 'OneColorOccurs)
)
))
(exit (run-tests make-master-tests))
| |
a753c786d9ec84c9b86431523e67133ab4d490cc7b723b58dc54978fe35419fe | inaka/sumo_rest | sr_request.erl | -module(sr_request).
-export([ from_cowboy/1
, body/1
, headers/1
, path/1
, bindings/1
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Types
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-type binding_name() :: id | atom().
-type http_header_name_lowercase() :: binary().
-type http_header() :: {http_header_name_lowercase(), iodata()}.
-opaque req() ::
#{ body := sr_json:json()
, headers := [http_header()]
, path := binary()
, bindings := #{binding_name() => any()}
}.
-export_type [req/0].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Constructor, getters/setters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec from_cowboy(cowboy_req:req()) -> {req(), cowboy_req:req()}.
from_cowboy(CowboyReq) ->
{ok, RawBody, CowboyReq1} = cowboy_req:body(CowboyReq),
Body = sr_json:decode(RawBody),
{Headers, CowboyReq2} = cowboy_req:headers(CowboyReq1),
{Path, CowboyReq3} = cowboy_req:path(CowboyReq2),
{BindingsList, CowboyReq4} = cowboy_req:bindings(CowboyReq3),
Request = #{ body => Body
, headers => Headers
, path => Path
, bindings => maps:from_list(BindingsList)
},
{Request, CowboyReq4}.
-spec body(req()) -> sr_json:json() | undefined.
body(#{body := Body}) ->
Body.
-spec headers(req()) -> [http_header()].
headers(#{headers := Headers}) ->
Headers.
-spec path(req()) -> binary().
path(#{path := Path}) ->
Path.
-spec bindings(req()) -> #{atom() => any()}.
bindings(#{bindings := Bindings}) ->
Bindings.
| null | https://raw.githubusercontent.com/inaka/sumo_rest/19a3685ab477222738ac27b72e39346cbad9463d/src/sr_request.erl | erlang |
Types
Constructor, getters/setters
| -module(sr_request).
-export([ from_cowboy/1
, body/1
, headers/1
, path/1
, bindings/1
]).
-type binding_name() :: id | atom().
-type http_header_name_lowercase() :: binary().
-type http_header() :: {http_header_name_lowercase(), iodata()}.
-opaque req() ::
#{ body := sr_json:json()
, headers := [http_header()]
, path := binary()
, bindings := #{binding_name() => any()}
}.
-export_type [req/0].
-spec from_cowboy(cowboy_req:req()) -> {req(), cowboy_req:req()}.
from_cowboy(CowboyReq) ->
{ok, RawBody, CowboyReq1} = cowboy_req:body(CowboyReq),
Body = sr_json:decode(RawBody),
{Headers, CowboyReq2} = cowboy_req:headers(CowboyReq1),
{Path, CowboyReq3} = cowboy_req:path(CowboyReq2),
{BindingsList, CowboyReq4} = cowboy_req:bindings(CowboyReq3),
Request = #{ body => Body
, headers => Headers
, path => Path
, bindings => maps:from_list(BindingsList)
},
{Request, CowboyReq4}.
-spec body(req()) -> sr_json:json() | undefined.
body(#{body := Body}) ->
Body.
-spec headers(req()) -> [http_header()].
headers(#{headers := Headers}) ->
Headers.
-spec path(req()) -> binary().
path(#{path := Path}) ->
Path.
-spec bindings(req()) -> #{atom() => any()}.
bindings(#{bindings := Bindings}) ->
Bindings.
|
8977501240177c889225908018f04f7b3ed1cc2c6f140abba89966db9b0ca2ee | bitemyapp/esqueleto | JSON.hs | {-# LANGUAGE OverloadedStrings #-}
|
This module contains PostgreSQL - specific JSON functions .
A couple of things to keep in mind about this module :
* The @Type@ column in the PostgreSQL documentation tables
are the types of the right operand , the left is always @jsonb@.
* Since these operators can all take @NULL@ values as their input ,
and most can also output @NULL@ values ( even when the inputs are
guaranteed to not be NULL ) , all ' JSONB ' values are wrapped in
' Maybe ' . This also makes it easier to chain them . ( cf . ' JSONBExpr ' )
Just use the ' just ' function to lift any non-'Maybe ' JSONB values
in case it does n't type check .
* As long as the previous operator 's resulting value is
a ' JSONBExpr ' , any other JSON operator can be used to transform
the JSON further . ( e.g. @[1,2,3 ] - > 1 \@ > 2@ )
/The PostgreSQL version the functions work with are included/
/in their description./
@since 3.1.0
This module contains PostgreSQL-specific JSON functions.
A couple of things to keep in mind about this module:
* The @Type@ column in the PostgreSQL documentation tables
are the types of the right operand, the left is always @jsonb@.
* Since these operators can all take @NULL@ values as their input,
and most can also output @NULL@ values (even when the inputs are
guaranteed to not be NULL), all 'JSONB' values are wrapped in
'Maybe'. This also makes it easier to chain them. (cf. 'JSONBExpr')
Just use the 'just' function to lift any non-'Maybe' JSONB values
in case it doesn't type check.
* As long as the previous operator's resulting value is
a 'JSONBExpr', any other JSON operator can be used to transform
the JSON further. (e.g. @[1,2,3] -> 1 \@> 2@)
/The PostgreSQL version the functions work with are included/
/in their description./
@since 3.1.0
-}
module Database.Esqueleto.PostgreSQL.JSON
* JSONB Newtype
--
| With ' JSONB ' , you can use your types in your
-- database table models as long as your type has 'FromJSON'
and ' ToJSON ' instances .
--
-- @
import Database . Persist . TH
--
share [ mkPersist sqlSettings , " migrateAll " ] [ persistUpperCase|
-- Example
json ( JSONB MyType )
-- |]
-- @
--
-- CAUTION: Remember that changing the 'FromJSON' instance
-- of your type might result in old data becoming unparsable!
You can use ( @JSONB Data . Aeson . Value@ ) for unstructured / variable JSON .
JSONB(..)
, JSONBExpr
, jsonbVal
-- * JSONAccessor
, JSONAccessor(..)
-- * Arrow operators
--
-- | /Better documentation included with individual functions/
--
-- The arrow operators are selection functions to select values
-- from JSON arrays or objects.
--
-- === PostgreSQL Documentation
--
/Requires PostgreSQL version > = 9.3/
--
-- @
-- | Type | Description | Example | Example Result
-- -----+--------+--------------------------------------------+--------------------------------------------------+----------------
- > | int | Get JSON array element ( indexed from zero , | ' [ { " | { " c":"baz " }
-- | | negative integers count from the end) | |
- > | text | Get JSON object field by key | ' { " a " : { " b":"foo"}}'::json->'a ' | { " b":"foo " }
- > > | int | Get JSON array element as text | ' [ 1,2,3]'::json->>2 | 3
- > > | text | Get JSON object field as text | ' { " a":1,"b":2}'::json->>'b ' | 2
-- \#> | text[] | Get JSON object at specified path | '{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}' | {"c": "foo"}
-- \#>> | text[] | Get JSON object at specified path as text | '{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}' | 3
-- @
, (->.)
, (->>.)
, (#>.)
, (#>>.)
-- * Filter operators
--
-- | /Better documentation included with individual functions/
--
-- These functions test certain properties of JSON values
-- and return booleans, so are mainly used in WHERE clauses.
--
-- === PostgreSQL Documentation
--
-- /Requires PostgreSQL version >= 9.4/
--
-- @
-- | Type | Description | Example
-- ----+--------+-----------------------------------------------------------------+---------------------------------------------------
-- \@> | jsonb | Does the left JSON value contain within it the right value? | '{"a":1, "b":2}'::jsonb \@> '{"b":2}'::jsonb
-- <\@ | jsonb | Is the left JSON value contained within the right value? | '{"b":2}'::jsonb <\@ '{"a":1, "b":2}'::jsonb
-- ? | text | Does the string exist as a top-level key within the JSON value? | '{"a":1, "b":2}'::jsonb ? 'b'
-- ?| | text[] | Do any of these array strings exist as top-level keys? | '{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']
-- ?& | text[] | Do all of these array strings exist as top-level keys? | '["a", "b"]'::jsonb ?& array['a', 'b']
-- @
, (@>.)
, (<@.)
, (?.)
, (?|.)
, (?&.)
-- * Deletion and concatenation operators
--
-- | /Better documentation included with individual functions/
--
-- These operators change the shape of the JSON value and
-- also have the highest risk of throwing an exception.
-- Please read the descriptions carefully before using these functions.
--
-- === PostgreSQL Documentation
--
/Requires PostgreSQL version > = 9.5/
--
-- @
-- | Type | Description | Example
-- ----+---------+------------------------------------------------------------------------+-------------------------------------------------
|| | jsonb | Concatenate two jsonb values into a new jsonb value | ' [ " a " , " b"]'::jsonb || ' [ " c " , " d"]'::jsonb
-- - | text | Delete key/value pair or string element from left operand. | '{"a": "b"}'::jsonb - 'a'
-- | | Key/value pairs are matched based on their key value. |
-- - | integer | Delete the array element with specified index (Negative integers count | '["a", "b"]'::jsonb - 1
-- | | from the end). Throws an error if top level container is not an array. |
\#- | text [ ] | Delete the field or element with specified path | ' [ " a " , { " b":1}]'::jsonb \#- ' { 1,b } '
| | ( for JSON arrays , negative integers count from the end ) |
-- @
--
/Requires PostgreSQL version > = 10/
--
-- @
-- | Type | Description | Example
-- ----+---------+------------------------------------------------------------------------+-------------------------------------------------
-- - | text[] | Delete multiple key/value pairs or string elements from left operand. | '{"a": "b", "c": "d"}'::jsonb - '{a,c}'::text[]
-- | | Key/value pairs are matched based on their key value. |
-- @
, (-.)
, (--.)
, (#-.)
, (||.)
) where
import Data.Text (Text)
import Database.Esqueleto.Internal.Internal hiding ((-.), (?.), (||.))
import Database.Esqueleto.Internal.PersistentImport
import Database.Esqueleto.PostgreSQL.JSON.Instances
infixl 6 ->., ->>., #>., #>>.
infixl 6 @>., <@., ?., ?|., ?&.
infixl 6 ||., -., --., #-.
| /Requires PostgreSQL version > = 9.3/
--
-- This function extracts the jsonb value from a JSON array or object,
depending on whether you use an @int@ or a @text@. ( cf . ' JSONAccessor ' )
--
As long as the left operand is , this function will not
throw an exception , but will return @NULL@ when an @int@ is used on
-- anything other than a JSON array, or a @text@ is used on anything
-- other than a JSON object.
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example | Example Result
-- ----+------+--------------------------------------------+--------------------------------------------------+----------------
- > | int | Get JSON array element ( indexed from zero ) | ' [ { " | { " c":"baz " }
- > | text | Get JSON object field by key | ' { " a " : { " b":"foo"}}'::json->'a ' | { " b":"foo " }
-- @
--
@since 3.1.0
(->.) :: JSONBExpr a -> JSONAccessor -> JSONBExpr b
(->.) value (JSONKey txt) = unsafeSqlBinOp " -> " value $ val txt
(->.) value (JSONIndex i) = unsafeSqlBinOp " -> " value $ val i
| /Requires PostgreSQL version > = 9.3/
--
-- Identical to '->.', but the resulting DB type is a @text@,
so it could be chained with anything that uses @text@.
--
-- __CAUTION: if the "scalar" JSON value @null@ is the result__
-- __of this function, PostgreSQL will interpret it as a__
-- __PostgreSQL @NULL@ value, and will therefore be 'Nothing'__
-- __instead of (Just "null")__
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example | Example Result
-- -----+------+--------------------------------+-----------------------------+----------------
- > > | int | Get JSON array element as text | ' [ 1,2,3]'::json->>2 | 3
- > > | text | Get JSON object field as text | ' { " a":1,"b":2}'::json->>'b ' | 2
-- @
--
@since 3.1.0
(->>.) :: JSONBExpr a -> JSONAccessor -> SqlExpr (Value (Maybe Text))
(->>.) value (JSONKey txt) = unsafeSqlBinOp " ->> " value $ val txt
(->>.) value (JSONIndex i) = unsafeSqlBinOp " ->> " value $ val i
| /Requires PostgreSQL version > = 9.3/
--
-- This operator can be used to select a JSON value from deep inside another one.
It only works on objects and arrays and will result in @NULL@ ( ' Nothing ' ) when
-- encountering any other JSON type.
--
-- The 'Text's used in the right operand list will always select an object field, but
-- can also select an index from a JSON array if that text is parsable as an integer.
--
-- Consider the following:
--
-- @
-- x ^. TestBody #>. ["0","1"]
-- @
--
-- The following JSON values in the @test@ table's @body@ column will be affected:
--
-- @
-- Values in column | Resulting value
-- --------------------------------------+----------------------------
-- {"0":{"1":"Got it!"}} | "Got it!"
-- {"0":[null,["Got it!","Even here!"]]} | ["Got it!", "Even here!"]
-- [{"1":"Got it again!"}] | "Got it again!"
[ [ deep ! " } ] ] | { \"Wow\ " : " so deep ! " }
-- false | NULL
-- "nope" | NULL
3.14 | NULL
-- @
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example | Example Result
-- -----+--------+-----------------------------------+--------------------------------------------+----------------
-- \#> | text[] | Get JSON object at specified path | '{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}' | {"c": "foo"}
-- @
--
@since 3.1.0
(#>.) :: JSONBExpr a -> [Text] -> JSONBExpr b
(#>.) value = unsafeSqlBinOp " #> " value . mkTextArray
| /Requires PostgreSQL version > = 9.3/
--
-- This function is to '#>.' as '->>.' is to '->.'
--
-- __CAUTION: if the "scalar" JSON value @null@ is the result__
-- __of this function, PostgreSQL will interpret it as a__
-- __PostgreSQL @NULL@ value, and will therefore be 'Nothing'__
-- __instead of (Just "null")__
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example | Example Result
-- -----+--------+-------------------------------------------+---------------------------------------------+----------------
\ # > > | text [ ] | Get JSON object at specified path as text | ' { " a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2 } ' | 3
-- @
--
@since 3.1.0
(#>>.) :: JSONBExpr a -> [Text] -> SqlExpr (Value (Maybe Text))
(#>>.) value = unsafeSqlBinOp " #>> " value . mkTextArray
-- | /Requires PostgreSQL version >= 9.4/
--
-- This operator checks for the JSON value on the right to be a subset
-- of the JSON value on the left.
--
-- Examples of the usage of this operator can be found in
the Database . Persist . Postgresql . JSON module .
--
-- (here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example
-- ----+-------+-------------------------------------------------------------+---------------------------------------------
-- \@> | jsonb | Does the left JSON value contain within it the right value? | '{"a":1, "b":2}'::jsonb \@> '{"b":2}'::jsonb
-- @
--
@since 3.1.0
(@>.) :: JSONBExpr a -> JSONBExpr b -> SqlExpr (Value Bool)
(@>.) = unsafeSqlBinOp " @> "
-- | /Requires PostgreSQL version >= 9.4/
--
-- This operator works the same as '@>.', just with the arguments flipped.
-- So it checks for the JSON value on the left to be a subset of JSON value on the right.
--
-- Examples of the usage of this operator can be found in
the Database . Persist . Postgresql . JSON module .
--
-- (here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example
-- ----+-------+----------------------------------------------------------+---------------------------------------------
-- <\@ | jsonb | Is the left JSON value contained within the right value? | '{"b":2}'::jsonb <\@ '{"a":1, "b":2}'::jsonb
-- @
--
@since 3.1.0
(<@.) :: JSONBExpr a -> JSONBExpr b -> SqlExpr (Value Bool)
(<@.) = unsafeSqlBinOp " <@ "
-- | /Requires PostgreSQL version >= 9.4/
--
-- This operator checks if the given text is a top-level member of the
-- JSON value on the left. This means a top-level field in an object, a
-- top-level string in an array or just a string value.
--
-- Examples of the usage of this operator can be found in
the Database . Persist . Postgresql . JSON module .
--
-- (here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example
---+------+-----------------------------------------------------------------+-------------------------------
-- ? | text | Does the string exist as a top-level key within the JSON value? | '{"a":1, "b":2}'::jsonb ? 'b'
-- @
--
@since 3.1.0
(?.) :: JSONBExpr a -> Text -> SqlExpr (Value Bool)
(?.) value = unsafeSqlBinOp " ?? " value . val
-- | /Requires PostgreSQL version >= 9.4/
--
-- This operator checks if __ANY__ of the given texts is a top-level member
-- of the JSON value on the left. This means any top-level field in an object,
-- any top-level string in an array or just a string value.
--
-- Examples of the usage of this operator can be found in
the Database . Persist . Postgresql . JSON module .
--
-- (here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example
-- ----+--------+--------------------------------------------------------+---------------------------------------------------
-- ?| | text[] | Do any of these array strings exist as top-level keys? | '{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']
-- @
--
@since 3.1.0
(?|.) :: JSONBExpr a -> [Text] -> SqlExpr (Value Bool)
(?|.) value = unsafeSqlBinOp " ??| " value . mkTextArray
-- | /Requires PostgreSQL version >= 9.4/
--
-- This operator checks if __ALL__ of the given texts are top-level members
-- of the JSON value on the left. This means a top-level field in an object,
-- a top-level string in an array or just a string value.
--
-- Examples of the usage of this operator can be found in
the Database . Persist . Postgresql . JSON module .
--
-- (here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example
-- ----+--------+--------------------------------------------------------+----------------------------------------
-- ?& | text[] | Do all of these array strings exist as top-level keys? | '["a", "b"]'::jsonb ?& array['a', 'b']
-- @
--
@since 3.1.0
(?&.) :: JSONBExpr a -> [Text] -> SqlExpr (Value Bool)
(?&.) value = unsafeSqlBinOp " ??& " value . mkTextArray
| /Requires PostgreSQL version > = 9.5/
--
This operator concatenates two JSON values . The behaviour is
self - evident when used on two arrays , but the behaviour on different
-- combinations of JSON values might behave unexpectedly.
--
_ _ CAUTION : THIS FUNCTION THROWS AN EXCEPTION WHEN _ _
_ _ A JSON OBJECT WITH A JSON SCALAR VALUE ! _ _
--
-- === __Arrays__
--
-- This operator is a standard concatenation function when used on arrays:
--
-- @
[ 1,2 ] || [ 2,3 ] = = [ 1,2,2,3 ]
-- [] || [1,2,3] == [1,2,3]
-- [1,2,3] || [] == [1,2,3]
-- @
--
-- === __Objects__
-- When concatenating JSON objects with other JSON objects, the fields
-- from the JSON object on the right are added to the JSON object on the
-- left. When concatenating a JSON object with a JSON array, the object
-- will be inserted into the array; either on the left or right, depending
-- on the position relative to the operator.
--
-- When concatening an object with a scalar value, an exception is thrown.
--
-- @
{ " a " : 3.14 } || { " b " : true } = = { " a " : 3.14 , " b " : true }
-- {"a": "b"} || {"a": null} == {"a": null}
-- {"a": {"b": true, "c": false}} || {"a": {"b": false}} == {"a": {"b": false}}
{ " a " : 3.14 } || [ 1,null ] = = [ { " a " : 3.14},1,null ]
[ 1,null ] || { " a " : 3.14 } = = [ 1,null,{"a " : 3.14 } ]
1 || { " a " : 3.14 } = = ERROR : invalid concatenation of jsonb objects
{ " a " : 3.14 } || false = = ERROR : invalid concatenation of jsonb objects
-- @
--
-- === __Scalar values__
--
Scalar values can be thought of as being singleton arrays when
-- used with this operator. This rule does not apply when concatenating
-- with JSON objects.
--
-- @
1 || null = = [ 1,null ]
-- true || "a" == [true,"a"]
-- [1,2] || false == [1,2,false]
null || [ 1,"a " ] = = [ null,1,"a " ]
-- {"a":3.14} || true == ERROR: invalid concatenation of jsonb objects
-- 3.14 || {"a":3.14} == ERROR: invalid concatenation of jsonb objects
-- {"a":3.14} || [true] == [{"a":3.14},true]
-- [false] || {"a":3.14} == [false,{"a":3.14}]
-- @
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example
-- ----+-------+-----------------------------------------------------+--------------------------------------------
|| | jsonb | Concatenate two jsonb values into a new jsonb value | ' [ " a " , " b"]'::jsonb || ' [ " c " , " d"]'::jsonb
-- @
--
/Note : The @||@ operator concatenates the elements at the top level of/
-- /each of its operands. It does not operate recursively./
--
/For example , if both operands are objects with a common key field name,/
-- /the value of the field in the result will just be the value from the right/
-- /hand operand./
--
@since 3.1.0
(||.) :: JSONBExpr a -> JSONBExpr b -> JSONBExpr c
(||.) = unsafeSqlBinOp " || "
| /Requires PostgreSQL version > = 9.5/
--
-- This operator can remove a key from an object or a string element from an array
-- when using text, and remove certain elements by index from an array when using
-- integers.
--
-- Negative integers delete counting from the end of the array.
( e.g. @-1@ being the last element , @-2@ being the second to last , etc . )
--
-- __CAUTION: THIS FUNCTION THROWS AN EXCEPTION WHEN USED ON ANYTHING OTHER__
-- __THAN OBJECTS OR ARRAYS WHEN USING TEXT, AND ANYTHING OTHER THAN ARRAYS__
-- __WHEN USING INTEGERS!__
--
-- === __Objects and arrays__
--
-- @
{ " a " : 3.14 } - " a " = = { }
-- {"a": "b"} - "b" == {"a": "b"}
{ " a " : 3.14 } - " a " = = { }
{ " a " : 3.14 , " c " : true } - " a " = = { " c " : true }
[ " a " , 2 , " c " ] - " a " = = [ 2 , " c " ] -- can remove strings from arrays
[ true , " b " , 5 ] - 0 = = [ " b " , 5 ]
[ true , " b " , 5 ] - 3 = = [ true , " b " , 5 ]
[ true , " b " , 5 ] - -1 = = [ true , " b " ]
[ true , " b " , 5 ] - -4 = = [ true , " b " , 5 ]
-- [] - 1 == []
-- {"1": true} - 1 == ERROR: cannot delete from object using integer index
1 - \<anything\ > = = ERROR : can not delete from scalar
-- "a" - \<anything\> == ERROR: cannot delete from scalar
-- true - \<anything\> == ERROR: cannot delete from scalar
-- null - \<anything\> == ERROR: cannot delete from scalar
-- @
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example
-- ---+---------+------------------------------------------------------------------------+-------------------------------------------------
-- - | text | Delete key/value pair or string element from left operand. | '{"a": "b"}'::jsonb - 'a'
| | Key / value pairs are matched based on their key value . |
-- - | integer | Delete the array element with specified index (Negative integers count | '["a", "b"]'::jsonb - 1
| | from the end ) . Throws an error if top level container is not an array . |
-- @
--
@since 3.1.0
(-.) :: JSONBExpr a -> JSONAccessor -> JSONBExpr b
(-.) value (JSONKey txt) = unsafeSqlBinOp " - " value $ val txt
(-.) value (JSONIndex i) = unsafeSqlBinOp " - " value $ val i
| /Requires PostgreSQL version > = 10/
--
-- Removes a set of keys from an object, or string elements from an array.
--
This is the same operator internally as ` - . ` , but the option to use a @text
array@ , instead of @text@ or @integer@ was only added in version 10 .
-- That's why this function is seperate from `-.`
--
-- NOTE: The following is equivalent:
--
-- @{some JSON expression} -. "a" -. "b"@
--
-- is equivalent to
--
-- @{some JSON expression} --. ["a","b"]@
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example
-- ---+---------+------------------------------------------------------------------------+-------------------------------------------------
-- - | text[] | Delete multiple key/value pairs or string elements from left operand. | '{"a": "b", "c": "d"}'::jsonb - '{a,c}'::text[]
| | Key / value pairs are matched based on their key value . |
-- @
--
@since 3.1.0
. ) : : JSONBExpr a - > [ Text ] - > JSONBExpr b
(--.) value = unsafeSqlBinOp " - " value . mkTextArray
| /Requires PostgreSQL version > = 9.5/
--
-- This operator can remove elements nested in an object.
--
-- If a 'Text' is not parsable as a number when selecting in an array
-- (even when halfway through the selection) an exception will be thrown.
--
-- Negative integers delete counting from the end of an array.
( e.g. @-1@ being the last element , @-2@ being the second to last , etc . )
--
-- __CAUTION: THIS FUNCTION THROWS AN EXCEPTION WHEN USED__
-- __ON ANYTHING OTHER THAN OBJECTS OR ARRAYS, AND WILL__
-- __ALSO THROW WHEN TRYING TO SELECT AN ARRAY ELEMENT WITH__
-- __A NON-INTEGER TEXT__
--
-- === __Objects__
--
-- @
{ " a " : 3.14 , " b " : null } # - [ ] = = { " a " : 3.14 , " b " : null }
{ " a " : 3.14 , " b " : null } # - [ " a " ] = = { " b " : null }
{ " a " : 3.14 , " b " : null } # - [ " a","b " ] = = { " a " : 3.14 , " b " : null }
-- {"a": {"b":false}, "b": null} #- ["a","b"] == {"a": {}, "b": null}
-- @
--
-- === __Arrays__
--
-- @
[ true , { " b":null } , 5 ] # - [ ] = = [ true , { " b":null } , 5 ]
[ true , { " b":null } , 5 ] # - [ " 0 " ] = = [ { " b":null } , 5 ]
[ true , { " b":null } , 5 ] # - [ " b " ] = = ERROR : path element at position 1 is not an integer : " b "
[ true , { " b":null } , 5 ] # - [ " 1","b " ] = = [ true , { } , 5 ]
[ true , { " b":null } , 5 ] # - [ " -2","b " ] = = [ true , { } , 5 ]
-- {"a": {"b":[false,4,null]}} #- ["a","b","2"] == {"a": {"b":[false,4]}}
{ " a " : { " b":[false,4,null ] } } # - [ " a","b","c " ] = = ERROR : path element at position 3 is not an integer : " c "
-- @
--
-- === __Other values__
--
-- @
1 \#- { anything } = = ERROR : can not delete from scalar
" a " \#- { anything } = = ERROR : can not delete from scalar
-- true \#- {anything} == ERROR: cannot delete from scalar
-- null \#- {anything} == ERROR: cannot delete from scalar
-- @
--
-- === __PostgreSQL Documentation__
--
-- @
-- | Type | Description | Example
-- ----+--------+---------------------------------------------------------+------------------------------------
\#- | text [ ] | Delete the field or element with specified path | ' [ " a " , { " b":1}]'::jsonb \#- ' { 1,b } '
-- | | (for JSON arrays, negative integers count from the end) |
-- @
--
@since 3.1.0
(#-.) :: JSONBExpr a -> [Text] -> JSONBExpr b
(#-.) value = unsafeSqlBinOp " #- " value . mkTextArray
mkTextArray :: [Text] -> SqlExpr (Value PersistValue)
mkTextArray = val . PersistArray . fmap toPersistValue
| null | https://raw.githubusercontent.com/bitemyapp/esqueleto/b295bc6a5f2a221b074940c01d4590d865774fe0/src/Database/Esqueleto/PostgreSQL/JSON.hs | haskell | # LANGUAGE OverloadedStrings #
database table models as long as your type has 'FromJSON'
@
Example
|]
@
CAUTION: Remember that changing the 'FromJSON' instance
of your type might result in old data becoming unparsable!
* JSONAccessor
* Arrow operators
| /Better documentation included with individual functions/
The arrow operators are selection functions to select values
from JSON arrays or objects.
=== PostgreSQL Documentation
@
| Type | Description | Example | Example Result
-----+--------+--------------------------------------------+--------------------------------------------------+----------------
| | negative integers count from the end) | |
\#> | text[] | Get JSON object at specified path | '{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}' | {"c": "foo"}
\#>> | text[] | Get JSON object at specified path as text | '{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}' | 3
@
* Filter operators
| /Better documentation included with individual functions/
These functions test certain properties of JSON values
and return booleans, so are mainly used in WHERE clauses.
=== PostgreSQL Documentation
/Requires PostgreSQL version >= 9.4/
@
| Type | Description | Example
----+--------+-----------------------------------------------------------------+---------------------------------------------------
\@> | jsonb | Does the left JSON value contain within it the right value? | '{"a":1, "b":2}'::jsonb \@> '{"b":2}'::jsonb
<\@ | jsonb | Is the left JSON value contained within the right value? | '{"b":2}'::jsonb <\@ '{"a":1, "b":2}'::jsonb
? | text | Does the string exist as a top-level key within the JSON value? | '{"a":1, "b":2}'::jsonb ? 'b'
?| | text[] | Do any of these array strings exist as top-level keys? | '{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']
?& | text[] | Do all of these array strings exist as top-level keys? | '["a", "b"]'::jsonb ?& array['a', 'b']
@
* Deletion and concatenation operators
| /Better documentation included with individual functions/
These operators change the shape of the JSON value and
also have the highest risk of throwing an exception.
Please read the descriptions carefully before using these functions.
=== PostgreSQL Documentation
@
| Type | Description | Example
----+---------+------------------------------------------------------------------------+-------------------------------------------------
- | text | Delete key/value pair or string element from left operand. | '{"a": "b"}'::jsonb - 'a'
| | Key/value pairs are matched based on their key value. |
- | integer | Delete the array element with specified index (Negative integers count | '["a", "b"]'::jsonb - 1
| | from the end). Throws an error if top level container is not an array. |
@
@
| Type | Description | Example
----+---------+------------------------------------------------------------------------+-------------------------------------------------
- | text[] | Delete multiple key/value pairs or string elements from left operand. | '{"a": "b", "c": "d"}'::jsonb - '{a,c}'::text[]
| | Key/value pairs are matched based on their key value. |
@
.)
., #-.
This function extracts the jsonb value from a JSON array or object,
anything other than a JSON array, or a @text@ is used on anything
other than a JSON object.
=== __PostgreSQL Documentation__
@
| Type | Description | Example | Example Result
----+------+--------------------------------------------+--------------------------------------------------+----------------
@
Identical to '->.', but the resulting DB type is a @text@,
__CAUTION: if the "scalar" JSON value @null@ is the result__
__of this function, PostgreSQL will interpret it as a__
__PostgreSQL @NULL@ value, and will therefore be 'Nothing'__
__instead of (Just "null")__
=== __PostgreSQL Documentation__
@
| Type | Description | Example | Example Result
-----+------+--------------------------------+-----------------------------+----------------
@
This operator can be used to select a JSON value from deep inside another one.
encountering any other JSON type.
The 'Text's used in the right operand list will always select an object field, but
can also select an index from a JSON array if that text is parsable as an integer.
Consider the following:
@
x ^. TestBody #>. ["0","1"]
@
The following JSON values in the @test@ table's @body@ column will be affected:
@
Values in column | Resulting value
--------------------------------------+----------------------------
{"0":{"1":"Got it!"}} | "Got it!"
{"0":[null,["Got it!","Even here!"]]} | ["Got it!", "Even here!"]
[{"1":"Got it again!"}] | "Got it again!"
false | NULL
"nope" | NULL
@
=== __PostgreSQL Documentation__
@
| Type | Description | Example | Example Result
-----+--------+-----------------------------------+--------------------------------------------+----------------
\#> | text[] | Get JSON object at specified path | '{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}' | {"c": "foo"}
@
This function is to '#>.' as '->>.' is to '->.'
__CAUTION: if the "scalar" JSON value @null@ is the result__
__of this function, PostgreSQL will interpret it as a__
__PostgreSQL @NULL@ value, and will therefore be 'Nothing'__
__instead of (Just "null")__
=== __PostgreSQL Documentation__
@
| Type | Description | Example | Example Result
-----+--------+-------------------------------------------+---------------------------------------------+----------------
@
| /Requires PostgreSQL version >= 9.4/
This operator checks for the JSON value on the right to be a subset
of the JSON value on the left.
Examples of the usage of this operator can be found in
(here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
=== __PostgreSQL Documentation__
@
| Type | Description | Example
----+-------+-------------------------------------------------------------+---------------------------------------------
\@> | jsonb | Does the left JSON value contain within it the right value? | '{"a":1, "b":2}'::jsonb \@> '{"b":2}'::jsonb
@
| /Requires PostgreSQL version >= 9.4/
This operator works the same as '@>.', just with the arguments flipped.
So it checks for the JSON value on the left to be a subset of JSON value on the right.
Examples of the usage of this operator can be found in
(here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
=== __PostgreSQL Documentation__
@
| Type | Description | Example
----+-------+----------------------------------------------------------+---------------------------------------------
<\@ | jsonb | Is the left JSON value contained within the right value? | '{"b":2}'::jsonb <\@ '{"a":1, "b":2}'::jsonb
@
| /Requires PostgreSQL version >= 9.4/
This operator checks if the given text is a top-level member of the
JSON value on the left. This means a top-level field in an object, a
top-level string in an array or just a string value.
Examples of the usage of this operator can be found in
(here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
=== __PostgreSQL Documentation__
@
| Type | Description | Example
-+------+-----------------------------------------------------------------+-------------------------------
? | text | Does the string exist as a top-level key within the JSON value? | '{"a":1, "b":2}'::jsonb ? 'b'
@
| /Requires PostgreSQL version >= 9.4/
This operator checks if __ANY__ of the given texts is a top-level member
of the JSON value on the left. This means any top-level field in an object,
any top-level string in an array or just a string value.
Examples of the usage of this operator can be found in
(here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
=== __PostgreSQL Documentation__
@
| Type | Description | Example
----+--------+--------------------------------------------------------+---------------------------------------------------
?| | text[] | Do any of these array strings exist as top-level keys? | '{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']
@
| /Requires PostgreSQL version >= 9.4/
This operator checks if __ALL__ of the given texts are top-level members
of the JSON value on the left. This means a top-level field in an object,
a top-level string in an array or just a string value.
Examples of the usage of this operator can be found in
(here: <-postgresql-2.10.0/docs/Database-Persist-Postgresql-JSON.html>)
=== __PostgreSQL Documentation__
@
| Type | Description | Example
----+--------+--------------------------------------------------------+----------------------------------------
?& | text[] | Do all of these array strings exist as top-level keys? | '["a", "b"]'::jsonb ?& array['a', 'b']
@
combinations of JSON values might behave unexpectedly.
=== __Arrays__
This operator is a standard concatenation function when used on arrays:
@
[] || [1,2,3] == [1,2,3]
[1,2,3] || [] == [1,2,3]
@
=== __Objects__
When concatenating JSON objects with other JSON objects, the fields
from the JSON object on the right are added to the JSON object on the
left. When concatenating a JSON object with a JSON array, the object
will be inserted into the array; either on the left or right, depending
on the position relative to the operator.
When concatening an object with a scalar value, an exception is thrown.
@
{"a": "b"} || {"a": null} == {"a": null}
{"a": {"b": true, "c": false}} || {"a": {"b": false}} == {"a": {"b": false}}
@
=== __Scalar values__
used with this operator. This rule does not apply when concatenating
with JSON objects.
@
true || "a" == [true,"a"]
[1,2] || false == [1,2,false]
{"a":3.14} || true == ERROR: invalid concatenation of jsonb objects
3.14 || {"a":3.14} == ERROR: invalid concatenation of jsonb objects
{"a":3.14} || [true] == [{"a":3.14},true]
[false] || {"a":3.14} == [false,{"a":3.14}]
@
=== __PostgreSQL Documentation__
@
| Type | Description | Example
----+-------+-----------------------------------------------------+--------------------------------------------
@
/each of its operands. It does not operate recursively./
/the value of the field in the result will just be the value from the right/
/hand operand./
This operator can remove a key from an object or a string element from an array
when using text, and remove certain elements by index from an array when using
integers.
Negative integers delete counting from the end of the array.
__CAUTION: THIS FUNCTION THROWS AN EXCEPTION WHEN USED ON ANYTHING OTHER__
__THAN OBJECTS OR ARRAYS WHEN USING TEXT, AND ANYTHING OTHER THAN ARRAYS__
__WHEN USING INTEGERS!__
=== __Objects and arrays__
@
{"a": "b"} - "b" == {"a": "b"}
can remove strings from arrays
[] - 1 == []
{"1": true} - 1 == ERROR: cannot delete from object using integer index
"a" - \<anything\> == ERROR: cannot delete from scalar
true - \<anything\> == ERROR: cannot delete from scalar
null - \<anything\> == ERROR: cannot delete from scalar
@
=== __PostgreSQL Documentation__
@
| Type | Description | Example
---+---------+------------------------------------------------------------------------+-------------------------------------------------
- | text | Delete key/value pair or string element from left operand. | '{"a": "b"}'::jsonb - 'a'
- | integer | Delete the array element with specified index (Negative integers count | '["a", "b"]'::jsonb - 1
@
Removes a set of keys from an object, or string elements from an array.
That's why this function is seperate from `-.`
NOTE: The following is equivalent:
@{some JSON expression} -. "a" -. "b"@
is equivalent to
@{some JSON expression} --. ["a","b"]@
=== __PostgreSQL Documentation__
@
| Type | Description | Example
---+---------+------------------------------------------------------------------------+-------------------------------------------------
- | text[] | Delete multiple key/value pairs or string elements from left operand. | '{"a": "b", "c": "d"}'::jsonb - '{a,c}'::text[]
@
.) value = unsafeSqlBinOp " - " value . mkTextArray
This operator can remove elements nested in an object.
If a 'Text' is not parsable as a number when selecting in an array
(even when halfway through the selection) an exception will be thrown.
Negative integers delete counting from the end of an array.
__CAUTION: THIS FUNCTION THROWS AN EXCEPTION WHEN USED__
__ON ANYTHING OTHER THAN OBJECTS OR ARRAYS, AND WILL__
__ALSO THROW WHEN TRYING TO SELECT AN ARRAY ELEMENT WITH__
__A NON-INTEGER TEXT__
=== __Objects__
@
{"a": {"b":false}, "b": null} #- ["a","b"] == {"a": {}, "b": null}
@
=== __Arrays__
@
{"a": {"b":[false,4,null]}} #- ["a","b","2"] == {"a": {"b":[false,4]}}
@
=== __Other values__
@
true \#- {anything} == ERROR: cannot delete from scalar
null \#- {anything} == ERROR: cannot delete from scalar
@
=== __PostgreSQL Documentation__
@
| Type | Description | Example
----+--------+---------------------------------------------------------+------------------------------------
| | (for JSON arrays, negative integers count from the end) |
@
|
|
This module contains PostgreSQL - specific JSON functions .
A couple of things to keep in mind about this module :
* The @Type@ column in the PostgreSQL documentation tables
are the types of the right operand , the left is always @jsonb@.
* Since these operators can all take @NULL@ values as their input ,
and most can also output @NULL@ values ( even when the inputs are
guaranteed to not be NULL ) , all ' JSONB ' values are wrapped in
' Maybe ' . This also makes it easier to chain them . ( cf . ' JSONBExpr ' )
Just use the ' just ' function to lift any non-'Maybe ' JSONB values
in case it does n't type check .
* As long as the previous operator 's resulting value is
a ' JSONBExpr ' , any other JSON operator can be used to transform
the JSON further . ( e.g. @[1,2,3 ] - > 1 \@ > 2@ )
/The PostgreSQL version the functions work with are included/
/in their description./
@since 3.1.0
This module contains PostgreSQL-specific JSON functions.
A couple of things to keep in mind about this module:
* The @Type@ column in the PostgreSQL documentation tables
are the types of the right operand, the left is always @jsonb@.
* Since these operators can all take @NULL@ values as their input,
and most can also output @NULL@ values (even when the inputs are
guaranteed to not be NULL), all 'JSONB' values are wrapped in
'Maybe'. This also makes it easier to chain them. (cf. 'JSONBExpr')
Just use the 'just' function to lift any non-'Maybe' JSONB values
in case it doesn't type check.
* As long as the previous operator's resulting value is
a 'JSONBExpr', any other JSON operator can be used to transform
the JSON further. (e.g. @[1,2,3] -> 1 \@> 2@)
/The PostgreSQL version the functions work with are included/
/in their description./
@since 3.1.0
-}
module Database.Esqueleto.PostgreSQL.JSON
* JSONB Newtype
| With ' JSONB ' , you can use your types in your
and ' ToJSON ' instances .
import Database . Persist . TH
share [ mkPersist sqlSettings , " migrateAll " ] [ persistUpperCase|
json ( JSONB MyType )
You can use ( @JSONB Data . Aeson . Value@ ) for unstructured / variable JSON .
JSONB(..)
, JSONBExpr
, jsonbVal
, JSONAccessor(..)
/Requires PostgreSQL version > = 9.3/
- > | int | Get JSON array element ( indexed from zero , | ' [ { " | { " c":"baz " }
- > | text | Get JSON object field by key | ' { " a " : { " b":"foo"}}'::json->'a ' | { " b":"foo " }
- > > | int | Get JSON array element as text | ' [ 1,2,3]'::json->>2 | 3
- > > | text | Get JSON object field as text | ' { " a":1,"b":2}'::json->>'b ' | 2
, (->.)
, (->>.)
, (#>.)
, (#>>.)
, (@>.)
, (<@.)
, (?.)
, (?|.)
, (?&.)
/Requires PostgreSQL version > = 9.5/
|| | jsonb | Concatenate two jsonb values into a new jsonb value | ' [ " a " , " b"]'::jsonb || ' [ " c " , " d"]'::jsonb
\#- | text [ ] | Delete the field or element with specified path | ' [ " a " , { " b":1}]'::jsonb \#- ' { 1,b } '
| | ( for JSON arrays , negative integers count from the end ) |
/Requires PostgreSQL version > = 10/
, (-.)
, (#-.)
, (||.)
) where
import Data.Text (Text)
import Database.Esqueleto.Internal.Internal hiding ((-.), (?.), (||.))
import Database.Esqueleto.Internal.PersistentImport
import Database.Esqueleto.PostgreSQL.JSON.Instances
infixl 6 ->., ->>., #>., #>>.
infixl 6 @>., <@., ?., ?|., ?&.
| /Requires PostgreSQL version > = 9.3/
depending on whether you use an @int@ or a @text@. ( cf . ' JSONAccessor ' )
As long as the left operand is , this function will not
throw an exception , but will return @NULL@ when an @int@ is used on
- > | int | Get JSON array element ( indexed from zero ) | ' [ { " | { " c":"baz " }
- > | text | Get JSON object field by key | ' { " a " : { " b":"foo"}}'::json->'a ' | { " b":"foo " }
@since 3.1.0
(->.) :: JSONBExpr a -> JSONAccessor -> JSONBExpr b
(->.) value (JSONKey txt) = unsafeSqlBinOp " -> " value $ val txt
(->.) value (JSONIndex i) = unsafeSqlBinOp " -> " value $ val i
| /Requires PostgreSQL version > = 9.3/
so it could be chained with anything that uses @text@.
- > > | int | Get JSON array element as text | ' [ 1,2,3]'::json->>2 | 3
- > > | text | Get JSON object field as text | ' { " a":1,"b":2}'::json->>'b ' | 2
@since 3.1.0
(->>.) :: JSONBExpr a -> JSONAccessor -> SqlExpr (Value (Maybe Text))
(->>.) value (JSONKey txt) = unsafeSqlBinOp " ->> " value $ val txt
(->>.) value (JSONIndex i) = unsafeSqlBinOp " ->> " value $ val i
| /Requires PostgreSQL version > = 9.3/
It only works on objects and arrays and will result in @NULL@ ( ' Nothing ' ) when
[ [ deep ! " } ] ] | { \"Wow\ " : " so deep ! " }
3.14 | NULL
@since 3.1.0
(#>.) :: JSONBExpr a -> [Text] -> JSONBExpr b
(#>.) value = unsafeSqlBinOp " #> " value . mkTextArray
| /Requires PostgreSQL version > = 9.3/
\ # > > | text [ ] | Get JSON object at specified path as text | ' { " a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2 } ' | 3
@since 3.1.0
(#>>.) :: JSONBExpr a -> [Text] -> SqlExpr (Value (Maybe Text))
(#>>.) value = unsafeSqlBinOp " #>> " value . mkTextArray
the Database . Persist . Postgresql . JSON module .
@since 3.1.0
(@>.) :: JSONBExpr a -> JSONBExpr b -> SqlExpr (Value Bool)
(@>.) = unsafeSqlBinOp " @> "
the Database . Persist . Postgresql . JSON module .
@since 3.1.0
(<@.) :: JSONBExpr a -> JSONBExpr b -> SqlExpr (Value Bool)
(<@.) = unsafeSqlBinOp " <@ "
the Database . Persist . Postgresql . JSON module .
@since 3.1.0
(?.) :: JSONBExpr a -> Text -> SqlExpr (Value Bool)
(?.) value = unsafeSqlBinOp " ?? " value . val
the Database . Persist . Postgresql . JSON module .
@since 3.1.0
(?|.) :: JSONBExpr a -> [Text] -> SqlExpr (Value Bool)
(?|.) value = unsafeSqlBinOp " ??| " value . mkTextArray
the Database . Persist . Postgresql . JSON module .
@since 3.1.0
(?&.) :: JSONBExpr a -> [Text] -> SqlExpr (Value Bool)
(?&.) value = unsafeSqlBinOp " ??& " value . mkTextArray
| /Requires PostgreSQL version > = 9.5/
This operator concatenates two JSON values . The behaviour is
self - evident when used on two arrays , but the behaviour on different
_ _ CAUTION : THIS FUNCTION THROWS AN EXCEPTION WHEN _ _
_ _ A JSON OBJECT WITH A JSON SCALAR VALUE ! _ _
[ 1,2 ] || [ 2,3 ] = = [ 1,2,2,3 ]
{ " a " : 3.14 } || { " b " : true } = = { " a " : 3.14 , " b " : true }
{ " a " : 3.14 } || [ 1,null ] = = [ { " a " : 3.14},1,null ]
[ 1,null ] || { " a " : 3.14 } = = [ 1,null,{"a " : 3.14 } ]
1 || { " a " : 3.14 } = = ERROR : invalid concatenation of jsonb objects
{ " a " : 3.14 } || false = = ERROR : invalid concatenation of jsonb objects
Scalar values can be thought of as being singleton arrays when
1 || null = = [ 1,null ]
null || [ 1,"a " ] = = [ null,1,"a " ]
|| | jsonb | Concatenate two jsonb values into a new jsonb value | ' [ " a " , " b"]'::jsonb || ' [ " c " , " d"]'::jsonb
/Note : The @||@ operator concatenates the elements at the top level of/
/For example , if both operands are objects with a common key field name,/
@since 3.1.0
(||.) :: JSONBExpr a -> JSONBExpr b -> JSONBExpr c
(||.) = unsafeSqlBinOp " || "
| /Requires PostgreSQL version > = 9.5/
( e.g. @-1@ being the last element , @-2@ being the second to last , etc . )
{ " a " : 3.14 } - " a " = = { }
{ " a " : 3.14 } - " a " = = { }
{ " a " : 3.14 , " c " : true } - " a " = = { " c " : true }
[ true , " b " , 5 ] - 0 = = [ " b " , 5 ]
[ true , " b " , 5 ] - 3 = = [ true , " b " , 5 ]
[ true , " b " , 5 ] - -1 = = [ true , " b " ]
[ true , " b " , 5 ] - -4 = = [ true , " b " , 5 ]
1 - \<anything\ > = = ERROR : can not delete from scalar
| | Key / value pairs are matched based on their key value . |
| | from the end ) . Throws an error if top level container is not an array . |
@since 3.1.0
(-.) :: JSONBExpr a -> JSONAccessor -> JSONBExpr b
(-.) value (JSONKey txt) = unsafeSqlBinOp " - " value $ val txt
(-.) value (JSONIndex i) = unsafeSqlBinOp " - " value $ val i
| /Requires PostgreSQL version > = 10/
This is the same operator internally as ` - . ` , but the option to use a @text
array@ , instead of @text@ or @integer@ was only added in version 10 .
| | Key / value pairs are matched based on their key value . |
@since 3.1.0
. ) : : JSONBExpr a - > [ Text ] - > JSONBExpr b
| /Requires PostgreSQL version > = 9.5/
( e.g. @-1@ being the last element , @-2@ being the second to last , etc . )
{ " a " : 3.14 , " b " : null } # - [ ] = = { " a " : 3.14 , " b " : null }
{ " a " : 3.14 , " b " : null } # - [ " a " ] = = { " b " : null }
{ " a " : 3.14 , " b " : null } # - [ " a","b " ] = = { " a " : 3.14 , " b " : null }
[ true , { " b":null } , 5 ] # - [ ] = = [ true , { " b":null } , 5 ]
[ true , { " b":null } , 5 ] # - [ " 0 " ] = = [ { " b":null } , 5 ]
[ true , { " b":null } , 5 ] # - [ " b " ] = = ERROR : path element at position 1 is not an integer : " b "
[ true , { " b":null } , 5 ] # - [ " 1","b " ] = = [ true , { } , 5 ]
[ true , { " b":null } , 5 ] # - [ " -2","b " ] = = [ true , { } , 5 ]
{ " a " : { " b":[false,4,null ] } } # - [ " a","b","c " ] = = ERROR : path element at position 3 is not an integer : " c "
1 \#- { anything } = = ERROR : can not delete from scalar
" a " \#- { anything } = = ERROR : can not delete from scalar
\#- | text [ ] | Delete the field or element with specified path | ' [ " a " , { " b":1}]'::jsonb \#- ' { 1,b } '
@since 3.1.0
(#-.) :: JSONBExpr a -> [Text] -> JSONBExpr b
(#-.) value = unsafeSqlBinOp " #- " value . mkTextArray
mkTextArray :: [Text] -> SqlExpr (Value PersistValue)
mkTextArray = val . PersistArray . fmap toPersistValue
|
284711c751c4a5b6b8c5a4c0ea77ec2a9195d7099377e85b26b2d2d033c5ed7e | fragnix/fragnix | Network.Socket.ByteString.Lazy.Posix.hs | # LANGUAGE Haskell98 , CPP , DeriveDataTypeable , ForeignFunctionInterface , TypeSynonymInstances #
# LINE 1 " Network / Socket / ByteString / Lazy / Posix.hs " #
{-# LANGUAGE BangPatterns #-}
module Network.Socket.ByteString.Lazy.Posix
(
-- * Send data to a socket
send
, sendAll
) where
import Control.Monad (liftM)
import Control.Monad (unless)
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Lazy.Internal (ByteString(..))
import Data.ByteString.Unsafe (unsafeUseAsCStringLen)
import Data.Int (Int64)
import Foreign.Marshal.Array (allocaArray)
import Foreign.Ptr (plusPtr)
import Foreign.Storable (Storable(..))
import Network.Socket (Socket(..))
import Network.Socket.ByteString.IOVec (IOVec(IOVec))
import Network.Socket.ByteString.Internal (c_writev)
import Network.Socket.Internal
-- -----------------------------------------------------------------------------
-- Sending
send :: Socket -- ^ Connected socket
-> ByteString -- ^ Data to send
-> IO Int64 -- ^ Number of bytes sent
send sock@(MkSocket fd _ _ _ _) s = do
let cs = take maxNumChunks (L.toChunks s)
len = length cs
liftM fromIntegral . allocaArray len $ \ptr ->
withPokes cs ptr $ \niovs ->
throwSocketErrorWaitWrite sock "writev" $
c_writev (fromIntegral fd) ptr niovs
where
withPokes ss p f = loop ss p 0 0
where loop (c:cs) q k !niovs
| k < maxNumBytes =
unsafeUseAsCStringLen c $ \(ptr,len) -> do
poke q $ IOVec ptr (fromIntegral len)
loop cs (q `plusPtr` sizeOf (undefined :: IOVec))
(k + fromIntegral len) (niovs + 1)
| otherwise = f niovs
loop _ _ _ niovs = f niovs
maximum number of bytes to transmit in one system call
maximum number of chunks to transmit in one system call
sendAll :: Socket -- ^ Connected socket
-> ByteString -- ^ Data to send
-> IO ()
sendAll sock bs = do
sent <- send sock bs
let bs' = L.drop sent bs
unless (L.null bs') $ sendAll sock bs'
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/scotty/Network.Socket.ByteString.Lazy.Posix.hs | haskell | # LANGUAGE BangPatterns #
* Send data to a socket
-----------------------------------------------------------------------------
Sending
^ Connected socket
^ Data to send
^ Number of bytes sent
^ Connected socket
^ Data to send | # LANGUAGE Haskell98 , CPP , DeriveDataTypeable , ForeignFunctionInterface , TypeSynonymInstances #
# LINE 1 " Network / Socket / ByteString / Lazy / Posix.hs " #
module Network.Socket.ByteString.Lazy.Posix
(
send
, sendAll
) where
import Control.Monad (liftM)
import Control.Monad (unless)
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Lazy.Internal (ByteString(..))
import Data.ByteString.Unsafe (unsafeUseAsCStringLen)
import Data.Int (Int64)
import Foreign.Marshal.Array (allocaArray)
import Foreign.Ptr (plusPtr)
import Foreign.Storable (Storable(..))
import Network.Socket (Socket(..))
import Network.Socket.ByteString.IOVec (IOVec(IOVec))
import Network.Socket.ByteString.Internal (c_writev)
import Network.Socket.Internal
send sock@(MkSocket fd _ _ _ _) s = do
let cs = take maxNumChunks (L.toChunks s)
len = length cs
liftM fromIntegral . allocaArray len $ \ptr ->
withPokes cs ptr $ \niovs ->
throwSocketErrorWaitWrite sock "writev" $
c_writev (fromIntegral fd) ptr niovs
where
withPokes ss p f = loop ss p 0 0
where loop (c:cs) q k !niovs
| k < maxNumBytes =
unsafeUseAsCStringLen c $ \(ptr,len) -> do
poke q $ IOVec ptr (fromIntegral len)
loop cs (q `plusPtr` sizeOf (undefined :: IOVec))
(k + fromIntegral len) (niovs + 1)
| otherwise = f niovs
loop _ _ _ niovs = f niovs
maximum number of bytes to transmit in one system call
maximum number of chunks to transmit in one system call
-> IO ()
sendAll sock bs = do
sent <- send sock bs
let bs' = L.drop sent bs
unless (L.null bs') $ sendAll sock bs'
|
6750fdb52924dc3a289080a18e0348b5eb061bd9703d876c175eca8b162c4fe5 | circleci/circleci.test | retest.clj | (ns circleci.test.retest
(:require [clojure.data.xml :as xml]
[clojure.java.io :as io]
[circleci.test :as test]))
(defn- failed-tests-from [root]
(let [suite (:name (:attrs root))]
(for [test-case (:content root)
:when (some #(#{:failure :error} (:tag %)) (:content test-case))]
(symbol suite (:name (:attrs test-case))))))
(def ^:private missing-junit-msg
"Previous test report files not found. Is the junit reporter configured?")
(defn- failed-tests [report-dir]
(when-not (.exists (io/file report-dir))
(throw (Exception. missing-junit-msg)))
(for [report-file (.listFiles (io/file report-dir))
test (failed-tests-from (xml/parse (io/reader report-file)))]
test))
(defn- make-selector [tests]
(comp (set (map name tests)) str :name))
(defn -main []
(let [{:keys [test-results-dir] :as config} (test/read-config!)]
(when-not (.exists (io/file test-results-dir))
(binding [*out* *err*]
(println missing-junit-msg)
(System/exit 1)))
(if-let [failed (seq (failed-tests test-results-dir))]
(doseq [[test-ns tests] (group-by (comp symbol namespace) failed)]
(require test-ns)
(test/test-ns test-ns (make-selector tests) config))
(println "No failed tests."))))
| null | https://raw.githubusercontent.com/circleci/circleci.test/eb2e44fe94e430648c852f7f736419dc70a4e5a1/src/circleci/test/retest.clj | clojure | (ns circleci.test.retest
(:require [clojure.data.xml :as xml]
[clojure.java.io :as io]
[circleci.test :as test]))
(defn- failed-tests-from [root]
(let [suite (:name (:attrs root))]
(for [test-case (:content root)
:when (some #(#{:failure :error} (:tag %)) (:content test-case))]
(symbol suite (:name (:attrs test-case))))))
(def ^:private missing-junit-msg
"Previous test report files not found. Is the junit reporter configured?")
(defn- failed-tests [report-dir]
(when-not (.exists (io/file report-dir))
(throw (Exception. missing-junit-msg)))
(for [report-file (.listFiles (io/file report-dir))
test (failed-tests-from (xml/parse (io/reader report-file)))]
test))
(defn- make-selector [tests]
(comp (set (map name tests)) str :name))
(defn -main []
(let [{:keys [test-results-dir] :as config} (test/read-config!)]
(when-not (.exists (io/file test-results-dir))
(binding [*out* *err*]
(println missing-junit-msg)
(System/exit 1)))
(if-let [failed (seq (failed-tests test-results-dir))]
(doseq [[test-ns tests] (group-by (comp symbol namespace) failed)]
(require test-ns)
(test/test-ns test-ns (make-selector tests) config))
(println "No failed tests."))))
| |
14a656bcaa29204f8a81e15726578747a383b291e5797400331c300057511b45 | camlp4/camlp4 | fstream.mli | camlp4r
(* Module [Fstream]: functional streams *)
This module implement functional streams .
To be used with syntax [ pa_fstream.cmo ] . The syntax is :
- stream : [ fstream [: ... :] ]
- parser : [ parser [ [: ... :] - > ... | ... ] ]
Functional parsers are of type : [ Fstream.t ' a - > option ( ' a * Fstream.t ' a ) ]
They have limited backtrack , i.e if a rule fails , the next rule is tested
with the initial stream ; limited because when in case of a rule with two
consecutive symbols [ a ] and [ b ] , if [ b ] fails , the rule fails : there is
no try with the next rule of [ a ] .
To be used with syntax [pa_fstream.cmo]. The syntax is:
- stream: [fstream [: ... :]]
- parser: [parser [ [: ... :] -> ... | ... ]]
Functional parsers are of type: [Fstream.t 'a -> option ('a * Fstream.t 'a)]
They have limited backtrack, i.e if a rule fails, the next rule is tested
with the initial stream; limited because when in case of a rule with two
consecutive symbols [a] and [b], if [b] fails, the rule fails: there is
no try with the next rule of [a].
*)
type t 'a = 'x;
(* The type of 'a functional streams *)
value from : (int -> option 'a) -> t 'a;
(* [Fstream.from f] returns a stream built from the function [f].
To create a new stream element, the function [f] is called with
the current stream count. The user function [f] must return either
[Some <value>] for a value or [None] to specify the end of the
stream. *)
value of_list : list 'a -> t 'a;
(* Return the stream holding the elements of the list in the same
order. *)
value of_string : string -> t char;
(* Return the stream of the characters of the string parameter. *)
value of_channel : in_channel -> t char;
(* Return the stream of the characters read from the input channel. *)
value iter : ('a -> unit) -> t 'a -> unit;
(* [Fstream.iter f s] scans the whole stream s, applying function [f]
in turn to each stream element encountered. *)
value next : t 'a -> option ('a * t 'a);
Return [ Some ( a , s ) ] where [ a ] is the first element of the stream
and [ s ] the remaining stream , or [ None ] if the stream is empty .
and [s] the remaining stream, or [None] if the stream is empty. *)
value empty : t 'a -> option (unit * t 'a);
(* Return [Some ((), s)] if the stream is empty where [s] is itself,
else [None] *)
value count : t 'a -> int;
(* Return the current count of the stream elements, i.e. the number
of the stream elements discarded. *)
value count_unfrozen : t 'a -> int;
(* Return the number of unfrozen elements in the beginning of the
stream; useful to determine the position of a parsing error (longuest
path). *)
(*--*)
value nil : t 'a;
type data 'a = 'x;
value cons : 'a -> t 'a -> data 'a;
value app : t 'a -> t 'a -> data 'a;
value flazy : (unit -> data 'a) -> t 'a;
| null | https://raw.githubusercontent.com/camlp4/camlp4/9b3314ea63288decb857239bd94f0c3342136844/camlp4/unmaintained/lib/fstream.mli | ocaml | Module [Fstream]: functional streams
The type of 'a functional streams
[Fstream.from f] returns a stream built from the function [f].
To create a new stream element, the function [f] is called with
the current stream count. The user function [f] must return either
[Some <value>] for a value or [None] to specify the end of the
stream.
Return the stream holding the elements of the list in the same
order.
Return the stream of the characters of the string parameter.
Return the stream of the characters read from the input channel.
[Fstream.iter f s] scans the whole stream s, applying function [f]
in turn to each stream element encountered.
Return [Some ((), s)] if the stream is empty where [s] is itself,
else [None]
Return the current count of the stream elements, i.e. the number
of the stream elements discarded.
Return the number of unfrozen elements in the beginning of the
stream; useful to determine the position of a parsing error (longuest
path).
-- | camlp4r
This module implement functional streams .
To be used with syntax [ pa_fstream.cmo ] . The syntax is :
- stream : [ fstream [: ... :] ]
- parser : [ parser [ [: ... :] - > ... | ... ] ]
Functional parsers are of type : [ Fstream.t ' a - > option ( ' a * Fstream.t ' a ) ]
They have limited backtrack , i.e if a rule fails , the next rule is tested
with the initial stream ; limited because when in case of a rule with two
consecutive symbols [ a ] and [ b ] , if [ b ] fails , the rule fails : there is
no try with the next rule of [ a ] .
To be used with syntax [pa_fstream.cmo]. The syntax is:
- stream: [fstream [: ... :]]
- parser: [parser [ [: ... :] -> ... | ... ]]
Functional parsers are of type: [Fstream.t 'a -> option ('a * Fstream.t 'a)]
They have limited backtrack, i.e if a rule fails, the next rule is tested
with the initial stream; limited because when in case of a rule with two
consecutive symbols [a] and [b], if [b] fails, the rule fails: there is
no try with the next rule of [a].
*)
type t 'a = 'x;
value from : (int -> option 'a) -> t 'a;
value of_list : list 'a -> t 'a;
value of_string : string -> t char;
value of_channel : in_channel -> t char;
value iter : ('a -> unit) -> t 'a -> unit;
value next : t 'a -> option ('a * t 'a);
Return [ Some ( a , s ) ] where [ a ] is the first element of the stream
and [ s ] the remaining stream , or [ None ] if the stream is empty .
and [s] the remaining stream, or [None] if the stream is empty. *)
value empty : t 'a -> option (unit * t 'a);
value count : t 'a -> int;
value count_unfrozen : t 'a -> int;
value nil : t 'a;
type data 'a = 'x;
value cons : 'a -> t 'a -> data 'a;
value app : t 'a -> t 'a -> data 'a;
value flazy : (unit -> data 'a) -> t 'a;
|
ceec32c5dcd0c0c8b4ac637836ac912c08e3a74f86b2b4968eae046f608a1e82 | grin-compiler/ghc-wpc-sample-programs | Definitions.hs | {-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
| Preprocess ' Agda . Syntax . Concrete . Declaration 's , producing ' NiceDeclaration 's .
--
-- * Attach fixity and syntax declarations to the definition they refer to.
--
-- * Distribute the following attributes to the individual definitions:
-- @abstract@,
-- @instance@,
-- @postulate@,
-- @primitive@,
-- @private@,
-- termination pragmas.
--
* Gather the function clauses belonging to one function definition .
--
-- * Expand ellipsis @...@ in function clauses following @with@.
--
-- * Infer mutual blocks.
-- A block starts when a lone signature is encountered, and ends when
-- all lone signatures have seen their definition.
--
-- * Report basic well-formedness error,
when one of the above transformation fails .
-- When possible, errors should be deferred to the scope checking phase
( ConcreteToAbstract ) , where we are in the TCM and can produce more
-- informative error messages.
module Agda.Syntax.Concrete.Definitions
( NiceDeclaration(..)
, NiceConstructor, NiceTypeSignature
, Clause(..)
, DeclarationException(..)
, DeclarationWarning(..), unsafeDeclarationWarning
, Nice, runNice
, niceDeclarations
, notSoNiceDeclarations
, niceHasAbstract
, Measure
, declarationWarningName
) where
import Prelude hiding (null)
import Control.Arrow ((&&&), (***), second)
import Control.Monad.Except
import Control.Monad.State
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe
import qualified Data.List as List
import qualified Data.Foldable as Fold
import Data.Traversable (Traversable, traverse)
import qualified Data.Traversable as Trav
import Data.Data (Data)
import Agda.Syntax.Concrete
import Agda.Syntax.Concrete.Pattern
import Agda.Syntax.Common hiding (TerminationCheck())
import qualified Agda.Syntax.Common as Common
import Agda.Syntax.Position
import Agda.Syntax.Notation
import Agda.Syntax.Concrete.Pretty () --instance only
import Agda.Syntax.Concrete.Fixity
import Agda.Interaction.Options.Warnings
import Agda.Utils.AffineHole
import Agda.Utils.Except ( MonadError(throwError) )
import Agda.Utils.Functor
import Agda.Utils.Lens
import Agda.Utils.List (isSublistOf)
import Agda.Utils.Maybe
import Agda.Utils.Null
import qualified Agda.Utils.Pretty as Pretty
import Agda.Utils.Pretty
import Agda.Utils.Singleton
import Agda.Utils.Three
import Agda.Utils.Tuple
import Agda.Utils.Update
import Agda.Utils.Impossible
{--------------------------------------------------------------------------
Types
--------------------------------------------------------------------------}
| The nice declarations . No fixity declarations and function definitions are
contained in a single constructor instead of spread out between type
signatures and clauses . The @private@ , @postulate@ , @abstract@ and @instance@
modifiers have been distributed to the individual declarations .
Observe the order of components :
Range
Fixity '
Access
IsAbstract
TerminationCheck
PositivityCheck
further attributes
( Q)Name
content ( , Declaration ... )
contained in a single constructor instead of spread out between type
signatures and clauses. The @private@, @postulate@, @abstract@ and @instance@
modifiers have been distributed to the individual declarations.
Observe the order of components:
Range
Fixity'
Access
IsAbstract
IsInstance
TerminationCheck
PositivityCheck
further attributes
(Q)Name
content (Expr, Declaration ...)
-}
data NiceDeclaration
= Axiom Range Access IsAbstract IsInstance ArgInfo Name Expr
^ ' IsAbstract ' argument : We record whether a declaration was made in an @abstract@ block .
--
' ArgInfo ' argument : Axioms and functions can be declared irrelevant .
( ' Hiding ' should be ' NotHidden ' . )
| NiceField Range Access IsAbstract IsInstance TacticAttribute Name (Arg Expr)
| PrimitiveFunction Range Access IsAbstract Name Expr
| NiceMutual Range TerminationCheck CoverageCheck PositivityCheck [NiceDeclaration]
| NiceModule Range Access IsAbstract QName Telescope [Declaration]
| NiceModuleMacro Range Access Name ModuleApplication OpenShortHand ImportDirective
| NiceOpen Range QName ImportDirective
| NiceImport Range QName (Maybe AsName) OpenShortHand ImportDirective
| NicePragma Range Pragma
| NiceRecSig Range Access IsAbstract PositivityCheck UniverseCheck Name [LamBinding] Expr
| NiceDataSig Range Access IsAbstract PositivityCheck UniverseCheck Name [LamBinding] Expr
| NiceFunClause Range Access IsAbstract TerminationCheck CoverageCheck Catchall Declaration
-- ^ An uncategorized function clause, could be a function clause
without type signature or a pattern lhs ( e.g. for irrefutable let ) .
The ' Declaration ' is the actual ' FunClause ' .
| FunSig Range Access IsAbstract IsInstance IsMacro ArgInfo TerminationCheck CoverageCheck Name Expr
| FunDef Range [Declaration] IsAbstract IsInstance TerminationCheck CoverageCheck Name [Clause]
-- ^ Block of function clauses (we have seen the type signature before).
-- The 'Declaration's are the original declarations that were processed
-- into this 'FunDef' and are only used in 'notSoNiceDeclaration'.
, 2017 - 01 - 01 : Because of issue # 2372 , we add ' ' here .
-- An alias should know that it is an instance.
| NiceDataDef Range Origin IsAbstract PositivityCheck UniverseCheck Name [LamBinding] [NiceConstructor]
| NiceRecDef Range Origin IsAbstract PositivityCheck UniverseCheck Name (Maybe (Ranged Induction)) (Maybe HasEta)
(Maybe (Name, IsInstance)) [LamBinding] [Declaration]
| NicePatternSyn Range Access Name [Arg Name] Pattern
| NiceGeneralize Range Access ArgInfo TacticAttribute Name Expr
| NiceUnquoteDecl Range Access IsAbstract IsInstance TerminationCheck CoverageCheck [Name] Expr
| NiceUnquoteDef Range Access IsAbstract TerminationCheck CoverageCheck [Name] Expr
deriving (Data, Show)
type TerminationCheck = Common.TerminationCheck Measure
-- | Termination measure is, for now, a variable name.
type Measure = Name
type Catchall = Bool
| Only ' Axiom 's .
type NiceConstructor = NiceTypeSignature
| Only ' Axiom 's .
type NiceTypeSignature = NiceDeclaration
| One clause in a function definition . There is no guarantee that the ' LHS '
-- actually declares the 'Name'. We will have to check that later.
data Clause = Clause Name Catchall LHS RHS WhereClause [Clause]
deriving (Data, Show)
-- | The exception type.
data DeclarationException
= MultipleEllipses Pattern
| InvalidName Name
| DuplicateDefinition Name
| MissingWithClauses Name LHS
| WrongDefinition Name DataRecOrFun DataRecOrFun
| DeclarationPanic String
| WrongContentBlock KindOfBlock Range
| AmbiguousFunClauses LHS [Name] -- ^ in a mutual block, a clause could belong to any of the @[Name]@ type signatures
| InvalidMeasureMutual Range
^ In a mutual block , all or none need a MEASURE pragma .
-- Range is of mutual block.
| UnquoteDefRequiresSignature [Name]
| BadMacroDef NiceDeclaration
deriving (Data, Show)
| Non - fatal errors encountered in the Nicifier .
data DeclarationWarning
-- Please keep in alphabetical order.
= EmptyAbstract Range -- ^ Empty @abstract@ block.
| EmptyField Range -- ^ Empty @field@ block.
| EmptyGeneralize Range -- ^ Empty @variable@ block.
| EmptyInstance Range -- ^ Empty @instance@ block
| EmptyMacro Range -- ^ Empty @macro@ block.
| EmptyMutual Range -- ^ Empty @mutual@ block.
| EmptyPostulate Range -- ^ Empty @postulate@ block.
| EmptyPrivate Range -- ^ Empty @private@ block.
| EmptyPrimitive Range -- ^ Empty @primitive@ block.
| InvalidCatchallPragma Range
^ A { -\ # CATCHALL \#- } pragma
-- that does not precede a function clause.
| InvalidCoverageCheckPragma Range
^ A { -\ # NON_COVERING \#- } pragma that does not apply to any function .
| InvalidNoPositivityCheckPragma Range
^ A { -\ # NO_POSITIVITY_CHECK \#- } pragma
-- that does not apply to any data or record type.
| InvalidNoUniverseCheckPragma Range
^ A { -\ # NO_UNIVERSE_CHECK \#- } pragma
-- that does not apply to a data or record type.
| InvalidTerminationCheckPragma Range
^ A { -\ # TERMINATING \#- } and { -\ # NON_TERMINATING \#- } pragma
-- that does not apply to any function.
| MissingDefinitions [(Name, Range)]
-- ^ Declarations (e.g. type signatures) without a definition.
| NotAllowedInMutual Range String
| OpenPublicPrivate Range
-- ^ @private@ has no effect on @open public@. (But the user might think so.)
| OpenPublicAbstract Range
^ @abstract@ has no effect on @open public@. ( But the user might think so . )
| PolarityPragmasButNotPostulates [Name]
| PragmaNoTerminationCheck Range
-- ^ Pragma @{-\# NO_TERMINATION_CHECK \#-}@ has been replaced
by @{-\ # TERMINATING \#-}@ and @{-\ # NON_TERMINATING \#-}@.
| PragmaCompiled Range
-- ^ @COMPILE@ pragmas are not allowed in safe mode
| ShadowingInTelescope [(Name, [Range])]
| UnknownFixityInMixfixDecl [Name]
| UnknownNamesInFixityDecl [Name]
| UnknownNamesInPolarityPragmas [Name]
| UselessAbstract Range
-- ^ @abstract@ block with nothing that can (newly) be made abstract.
| UselessInstance Range
-- ^ @instance@ block with nothing that can (newly) become an instance.
| UselessPrivate Range
-- ^ @private@ block with nothing that can (newly) be made private.
deriving (Data, Show)
declarationWarningName :: DeclarationWarning -> WarningName
declarationWarningName = \case
-- Please keep in alphabetical order.
EmptyAbstract{} -> EmptyAbstract_
EmptyField{} -> EmptyField_
EmptyGeneralize{} -> EmptyGeneralize_
EmptyInstance{} -> EmptyInstance_
EmptyMacro{} -> EmptyMacro_
EmptyMutual{} -> EmptyMutual_
EmptyPrivate{} -> EmptyPrivate_
EmptyPostulate{} -> EmptyPostulate_
EmptyPrimitive{} -> EmptyPrimitive_
InvalidCatchallPragma{} -> InvalidCatchallPragma_
InvalidNoPositivityCheckPragma{} -> InvalidNoPositivityCheckPragma_
InvalidNoUniverseCheckPragma{} -> InvalidNoUniverseCheckPragma_
InvalidTerminationCheckPragma{} -> InvalidTerminationCheckPragma_
InvalidCoverageCheckPragma{} -> InvalidCoverageCheckPragma_
MissingDefinitions{} -> MissingDefinitions_
NotAllowedInMutual{} -> NotAllowedInMutual_
OpenPublicPrivate{} -> OpenPublicPrivate_
OpenPublicAbstract{} -> OpenPublicAbstract_
PolarityPragmasButNotPostulates{} -> PolarityPragmasButNotPostulates_
PragmaNoTerminationCheck{} -> PragmaNoTerminationCheck_
PragmaCompiled{} -> PragmaCompiled_
ShadowingInTelescope{} -> ShadowingInTelescope_
UnknownFixityInMixfixDecl{} -> UnknownFixityInMixfixDecl_
UnknownNamesInFixityDecl{} -> UnknownNamesInFixityDecl_
UnknownNamesInPolarityPragmas{} -> UnknownNamesInPolarityPragmas_
UselessAbstract{} -> UselessAbstract_
UselessInstance{} -> UselessInstance_
UselessPrivate{} -> UselessPrivate_
| Nicifier warnings turned into errors in @--safe@ mode .
unsafeDeclarationWarning :: DeclarationWarning -> Bool
unsafeDeclarationWarning = \case
-- Please keep in alphabetical order.
EmptyAbstract{} -> False
EmptyField{} -> False
EmptyGeneralize{} -> False
EmptyInstance{} -> False
EmptyMacro{} -> False
EmptyMutual{} -> False
EmptyPrivate{} -> False
EmptyPostulate{} -> False
EmptyPrimitive{} -> False
InvalidCatchallPragma{} -> False
InvalidNoPositivityCheckPragma{} -> False
InvalidNoUniverseCheckPragma{} -> False
InvalidTerminationCheckPragma{} -> False
InvalidCoverageCheckPragma{} -> False
MissingDefinitions{} -> True -- not safe
NotAllowedInMutual{} -> False -- really safe?
OpenPublicPrivate{} -> False
OpenPublicAbstract{} -> False
PolarityPragmasButNotPostulates{} -> False
PragmaNoTerminationCheck{} -> True -- not safe
PragmaCompiled{} -> True -- not safe
ShadowingInTelescope{} -> False
UnknownFixityInMixfixDecl{} -> False
UnknownNamesInFixityDecl{} -> False
UnknownNamesInPolarityPragmas{} -> False
UselessAbstract{} -> False
UselessInstance{} -> False
UselessPrivate{} -> False
-- | Several declarations expect only type signatures as sub-declarations. These are:
data KindOfBlock
= PostulateBlock -- ^ @postulate@
| PrimitiveBlock -- ^ @primitive@. Ensured by parser.
| InstanceBlock -- ^ @instance@. Actually, here all kinds of sub-declarations are allowed a priori.
| FieldBlock -- ^ @field@. Ensured by parser.
^ @data ... where@. Here we got a bad error message for Agda-2.5 ( Issue 1698 ) .
deriving (Data, Eq, Ord, Show)
instance HasRange DeclarationException where
getRange (MultipleEllipses d) = getRange d
getRange (InvalidName x) = getRange x
getRange (DuplicateDefinition x) = getRange x
getRange (MissingWithClauses x lhs) = getRange lhs
getRange (WrongDefinition x k k') = getRange x
getRange (AmbiguousFunClauses lhs xs) = getRange lhs
getRange (DeclarationPanic _) = noRange
getRange (WrongContentBlock _ r) = r
getRange (InvalidMeasureMutual r) = r
getRange (UnquoteDefRequiresSignature x) = getRange x
getRange (BadMacroDef d) = getRange d
instance HasRange DeclarationWarning where
getRange (UnknownNamesInFixityDecl xs) = getRange xs
getRange (UnknownFixityInMixfixDecl xs) = getRange xs
getRange (UnknownNamesInPolarityPragmas xs) = getRange xs
getRange (PolarityPragmasButNotPostulates xs) = getRange xs
getRange (MissingDefinitions xs) = getRange xs
getRange (UselessPrivate r) = r
getRange (NotAllowedInMutual r x) = r
getRange (UselessAbstract r) = r
getRange (UselessInstance r) = r
getRange (EmptyMutual r) = r
getRange (EmptyAbstract r) = r
getRange (EmptyPrivate r) = r
getRange (EmptyInstance r) = r
getRange (EmptyMacro r) = r
getRange (EmptyPostulate r) = r
getRange (EmptyGeneralize r) = r
getRange (EmptyPrimitive r) = r
getRange (EmptyField r) = r
getRange (InvalidTerminationCheckPragma r) = r
getRange (InvalidCoverageCheckPragma r) = r
getRange (InvalidNoPositivityCheckPragma r) = r
getRange (InvalidCatchallPragma r) = r
getRange (InvalidNoUniverseCheckPragma r) = r
getRange (PragmaNoTerminationCheck r) = r
getRange (PragmaCompiled r) = r
getRange (OpenPublicAbstract r) = r
getRange (OpenPublicPrivate r) = r
getRange (ShadowingInTelescope ns) = getRange ns
instance HasRange NiceDeclaration where
getRange (Axiom r _ _ _ _ _ _) = r
getRange (NiceField r _ _ _ _ _ _) = r
getRange (NiceMutual r _ _ _ _) = r
getRange (NiceModule r _ _ _ _ _ ) = r
getRange (NiceModuleMacro r _ _ _ _ _) = r
getRange (NiceOpen r _ _) = r
getRange (NiceImport r _ _ _ _) = r
getRange (NicePragma r _) = r
getRange (PrimitiveFunction r _ _ _ _) = r
getRange (FunSig r _ _ _ _ _ _ _ _ _) = r
getRange (FunDef r _ _ _ _ _ _ _) = r
getRange (NiceDataDef r _ _ _ _ _ _ _) = r
getRange (NiceRecDef r _ _ _ _ _ _ _ _ _ _) = r
getRange (NiceRecSig r _ _ _ _ _ _ _) = r
getRange (NiceDataSig r _ _ _ _ _ _ _) = r
getRange (NicePatternSyn r _ _ _ _) = r
getRange (NiceGeneralize r _ _ _ _ _) = r
getRange (NiceFunClause r _ _ _ _ _ _) = r
getRange (NiceUnquoteDecl r _ _ _ _ _ _ _) = r
getRange (NiceUnquoteDef r _ _ _ _ _ _) = r
instance Pretty NiceDeclaration where
pretty = \case
Axiom _ _ _ _ _ x _ -> text "postulate" <+> pretty x <+> colon <+> text "_"
NiceField _ _ _ _ _ x _ -> text "field" <+> pretty x
PrimitiveFunction _ _ _ x _ -> text "primitive" <+> pretty x
NiceMutual{} -> text "mutual"
NiceModule _ _ _ x _ _ -> text "module" <+> pretty x <+> text "where"
NiceModuleMacro _ _ x _ _ _ -> text "module" <+> pretty x <+> text "= ..."
NiceOpen _ x _ -> text "open" <+> pretty x
NiceImport _ x _ _ _ -> text "import" <+> pretty x
NicePragma{} -> text "{-# ... #-}"
NiceRecSig _ _ _ _ _ x _ _ -> text "record" <+> pretty x
NiceDataSig _ _ _ _ _ x _ _ -> text "data" <+> pretty x
NiceFunClause{} -> text "<function clause>"
FunSig _ _ _ _ _ _ _ _ x _ -> pretty x <+> colon <+> text "_"
FunDef _ _ _ _ _ _ x _ -> pretty x <+> text "= _"
NiceDataDef _ _ _ _ _ x _ _ -> text "data" <+> pretty x <+> text "where"
NiceRecDef _ _ _ _ _ x _ _ _ _ _ -> text "record" <+> pretty x <+> text "where"
NicePatternSyn _ _ x _ _ -> text "pattern" <+> pretty x
NiceGeneralize _ _ _ _ x _ -> text "variable" <+> pretty x
NiceUnquoteDecl _ _ _ _ _ _ xs _ -> text "<unquote declarations>"
NiceUnquoteDef _ _ _ _ _ xs _ -> text "<unquote definitions>"
-- These error messages can (should) be terminated by a dot ".",
-- there is no error context printed after them.
instance Pretty DeclarationException where
pretty (MultipleEllipses p) = fsep $
pwords "Multiple ellipses in left-hand side" ++ [pretty p]
pretty (InvalidName x) = fsep $
pwords "Invalid name:" ++ [pretty x]
pretty (DuplicateDefinition x) = fsep $
pwords "Duplicate definition of" ++ [pretty x]
pretty (MissingWithClauses x lhs) = fsep $
pwords "Missing with-clauses for function" ++ [pretty x]
pretty (WrongDefinition x k k') = fsep $ pretty x :
pwords ("has been declared as a " ++ show k ++
", but is being defined as a " ++ show k')
pretty (AmbiguousFunClauses lhs xs) = sep
[ fsep $
pwords "More than one matching type signature for left hand side " ++ [pretty lhs] ++
pwords "it could belong to any of:"
, vcat $ map (pretty . PrintRange) xs
]
pretty (WrongContentBlock b _) = fsep . pwords $
case b of
PostulateBlock -> "A postulate block can only contain type signatures, possibly under keyword instance"
DataBlock -> "A data definition can only contain type signatures, possibly under keyword instance"
_ -> "Unexpected declaration"
pretty (InvalidMeasureMutual _) = fsep $
pwords "In a mutual block, either all functions must have the same (or no) termination checking pragma."
pretty (UnquoteDefRequiresSignature xs) = fsep $
pwords "Missing type signatures for unquoteDef" ++ map pretty xs
pretty (BadMacroDef nd) = fsep $
[text $ declName nd] ++ pwords "are not allowed in macro blocks"
pretty (DeclarationPanic s) = text s
instance Pretty DeclarationWarning where
pretty (UnknownNamesInFixityDecl xs) = fsep $
pwords "The following names are not declared in the same scope as their syntax or fixity declaration (i.e., either not in scope at all, imported from another module, or declared in a super module):"
++ punctuate comma (map pretty xs)
pretty (UnknownFixityInMixfixDecl xs) = fsep $
pwords "The following mixfix names do not have an associated fixity declaration:"
++ punctuate comma (map pretty xs)
pretty (UnknownNamesInPolarityPragmas xs) = fsep $
pwords "The following names are not declared in the same scope as their polarity pragmas (they could for instance be out of scope, imported from another module, or declared in a super module):"
++ punctuate comma (map pretty xs)
pretty (MissingDefinitions xs) = fsep $
pwords "The following names are declared but not accompanied by a definition:"
++ punctuate comma (map (pretty . fst) xs)
pretty (NotAllowedInMutual r nd) = fsep $
[text nd] ++ pwords "in mutual blocks are not supported. Suggestion: get rid of the mutual block by manually ordering declarations"
pretty (PolarityPragmasButNotPostulates xs) = fsep $
pwords "Polarity pragmas have been given for the following identifiers which are not postulates:"
++ punctuate comma (map pretty xs)
pretty (UselessPrivate _) = fsep $
pwords "Using private here has no effect. Private applies only to declarations that introduce new identifiers into the module, like type signatures and data, record, and module declarations."
pretty (UselessAbstract _) = fsep $
pwords "Using abstract here has no effect. Abstract applies to only definitions like data definitions, record type definitions and function clauses."
pretty (UselessInstance _) = fsep $
pwords "Using instance here has no effect. Instance applies only to declarations that introduce new identifiers into the module, like type signatures and axioms."
pretty (EmptyMutual _) = fsep $ pwords "Empty mutual block."
pretty (EmptyAbstract _) = fsep $ pwords "Empty abstract block."
pretty (EmptyPrivate _) = fsep $ pwords "Empty private block."
pretty (EmptyInstance _) = fsep $ pwords "Empty instance block."
pretty (EmptyMacro _) = fsep $ pwords "Empty macro block."
pretty (EmptyPostulate _) = fsep $ pwords "Empty postulate block."
pretty (EmptyGeneralize _) = fsep $ pwords "Empty variable block."
pretty (EmptyPrimitive _) = fsep $ pwords "Empty primitive block."
pretty (EmptyField _) = fsep $ pwords "Empty field block."
pretty (InvalidTerminationCheckPragma _) = fsep $
pwords "Termination checking pragmas can only precede a function definition or a mutual block (that contains a function definition)."
pretty (InvalidCoverageCheckPragma _) = fsep $
pwords "Coverage checking pragmas can only precede a function definition or a mutual block (that contains a function definition)."
pretty (InvalidNoPositivityCheckPragma _) = fsep $
pwords "NO_POSITIVITY_CHECKING pragmas can only precede a data/record definition or a mutual block (that contains a data/record definition)."
pretty (InvalidCatchallPragma _) = fsep $
pwords "The CATCHALL pragma can only precede a function clause."
pretty (InvalidNoUniverseCheckPragma _) = fsep $
pwords "NO_UNIVERSE_CHECKING pragmas can only precede a data/record definition."
pretty (PragmaNoTerminationCheck _) = fsep $
pwords "Pragma {-# NO_TERMINATION_CHECK #-} has been removed. To skip the termination check, label your definitions either as {-# TERMINATING #-} or {-# NON_TERMINATING #-}."
pretty (PragmaCompiled _) = fsep $
pwords "COMPILE pragma not allowed in safe mode."
pretty (OpenPublicAbstract _) = fsep $
pwords "public does not have any effect in an abstract block."
pretty (OpenPublicPrivate _) = fsep $
pwords "public does not have any effect in a private block."
pretty (ShadowingInTelescope nrs) = fsep $
pwords "Shadowing in telescope, repeated variable names:"
++ punctuate comma (map (pretty . fst) nrs)
declName :: NiceDeclaration -> String
declName Axiom{} = "Postulates"
declName NiceField{} = "Fields"
declName NiceMutual{} = "Mutual blocks"
declName NiceModule{} = "Modules"
declName NiceModuleMacro{} = "Modules"
declName NiceOpen{} = "Open declarations"
declName NiceImport{} = "Import statements"
declName NicePragma{} = "Pragmas"
declName PrimitiveFunction{} = "Primitive declarations"
declName NicePatternSyn{} = "Pattern synonyms"
declName NiceGeneralize{} = "Generalized variables"
declName NiceUnquoteDecl{} = "Unquoted declarations"
declName NiceUnquoteDef{} = "Unquoted definitions"
declName NiceRecSig{} = "Records"
declName NiceDataSig{} = "Data types"
declName NiceFunClause{} = "Functions without a type signature"
declName FunSig{} = "Type signatures"
declName FunDef{} = "Function definitions"
declName NiceRecDef{} = "Records"
declName NiceDataDef{} = "Data types"
{--------------------------------------------------------------------------
The niceifier
--------------------------------------------------------------------------}
data InMutual
= InMutual -- ^ we are nicifying a mutual block
| NotInMutual -- ^ we are nicifying decls not in a mutual block
deriving (Eq, Show)
-- | The kind of the forward declaration.
data DataRecOrFun
= DataName
{ _kindPosCheck :: PositivityCheck
, _kindUniCheck :: UniverseCheck
}
-- ^ Name of a data type
| RecName
{ _kindPosCheck :: PositivityCheck
, _kindUniCheck :: UniverseCheck
}
-- ^ Name of a record type
| FunName TerminationCheck CoverageCheck
-- ^ Name of a function.
deriving Data
-- Ignore pragmas when checking equality
instance Eq DataRecOrFun where
DataName{} == DataName{} = True
RecName{} == RecName{} = True
FunName{} == FunName{} = True
_ == _ = False
instance Show DataRecOrFun where
show DataName{} = "data type"
show RecName{} = "record type"
show FunName{} = "function"
isFunName :: DataRecOrFun -> Bool
isFunName (FunName{}) = True
isFunName _ = False
sameKind :: DataRecOrFun -> DataRecOrFun -> Bool
sameKind = (==)
terminationCheck :: DataRecOrFun -> TerminationCheck
terminationCheck (FunName tc _) = tc
terminationCheck _ = TerminationCheck
coverageCheck :: DataRecOrFun -> CoverageCheck
coverageCheck (FunName _ cc) = cc
coverageCheck _ = YesCoverageCheck
positivityCheck :: DataRecOrFun -> PositivityCheck
positivityCheck (DataName pc _) = pc
positivityCheck (RecName pc _) = pc
positivityCheck _ = YesPositivityCheck
universeCheck :: DataRecOrFun -> UniverseCheck
universeCheck (DataName _ uc) = uc
universeCheck (RecName _ uc) = uc
universeCheck _ = YesUniverseCheck
-- | Check that declarations in a mutual block are consistently
-- equipped with MEASURE pragmas, or whether there is a
-- NO_TERMINATION_CHECK pragma.
combineTerminationChecks :: Range -> [TerminationCheck] -> Nice TerminationCheck
combineTerminationChecks r tcs = loop tcs where
loop :: [TerminationCheck] -> Nice TerminationCheck
loop [] = return TerminationCheck
loop (tc : tcs) = do
let failure r = throwError $ InvalidMeasureMutual r
tc' <- loop tcs
case (tc, tc') of
(TerminationCheck , tc' ) -> return tc'
(tc , TerminationCheck ) -> return tc
(NonTerminating , NonTerminating ) -> return NonTerminating
(NoTerminationCheck , NoTerminationCheck ) -> return NoTerminationCheck
(NoTerminationCheck , Terminating ) -> return Terminating
(Terminating , NoTerminationCheck ) -> return Terminating
(Terminating , Terminating ) -> return Terminating
(TerminationMeasure{} , TerminationMeasure{} ) -> return tc
(TerminationMeasure r _, NoTerminationCheck ) -> failure r
(TerminationMeasure r _, Terminating ) -> failure r
(NoTerminationCheck , TerminationMeasure r _) -> failure r
(Terminating , TerminationMeasure r _) -> failure r
(TerminationMeasure r _, NonTerminating ) -> failure r
(NonTerminating , TerminationMeasure r _) -> failure r
(NoTerminationCheck , NonTerminating ) -> failure r
(Terminating , NonTerminating ) -> failure r
(NonTerminating , NoTerminationCheck ) -> failure r
(NonTerminating , Terminating ) -> failure r
combineCoverageChecks :: [CoverageCheck] -> CoverageCheck
combineCoverageChecks = Fold.fold
combinePositivityChecks :: [PositivityCheck] -> PositivityCheck
combinePositivityChecks = Fold.fold
-- | Nicifier monad.
-- Preserve the state when throwing an exception.
newtype Nice a = Nice { unNice :: ExceptT DeclarationException (State NiceEnv) a }
deriving ( Functor, Applicative, Monad
, MonadState NiceEnv, MonadError DeclarationException
)
-- | Run a Nicifier computation, return result and warnings
-- (in chronological order).
runNice :: Nice a -> (Either DeclarationException a, NiceWarnings)
runNice m = second (reverse . niceWarn) $
runExceptT (unNice m) `runState` initNiceEnv
-- | Nicifier state.
data NiceEnv = NiceEnv
{ _loneSigs :: LoneSigs
-- ^ Lone type signatures that wait for their definition.
, _termChk :: TerminationCheck
-- ^ Termination checking pragma waiting for a definition.
, _posChk :: PositivityCheck
-- ^ Positivity checking pragma waiting for a definition.
, _uniChk :: UniverseCheck
^ Universe checking pragma waiting for a data / rec signature or definition .
, _catchall :: Catchall
-- ^ Catchall pragma waiting for a function clause.
, _covChk :: CoverageCheck
-- ^ Coverage pragma waiting for a definition.
, niceWarn :: NiceWarnings
-- ^ Stack of warnings. Head is last warning.
}
data LoneSig = LoneSig
{ loneSigRange :: Range
, loneSigName :: Name
, loneSigKind :: DataRecOrFun
}
type LoneSigs = Map Name LoneSig
-- ^ We retain the 'Name' also in the codomain since
-- 'Name' as a key is up to @Eq Name@ which ignores the range.
-- However, without range names are not unique in case the
user gives a second definition of the same name .
-- This causes then problems in 'replaceSigs' which might
-- replace the wrong signature.
type NiceWarnings = [DeclarationWarning]
-- ^ Stack of warnings. Head is last warning.
-- | Initial nicifier state.
initNiceEnv :: NiceEnv
initNiceEnv = NiceEnv
{ _loneSigs = empty
, _termChk = TerminationCheck
, _posChk = YesPositivityCheck
, _uniChk = YesUniverseCheck
, _catchall = False
, _covChk = YesCoverageCheck
, niceWarn = []
}
-- * Handling the lone signatures, stored to infer mutual blocks.
-- | Lens for field '_loneSigs'.
loneSigs :: Lens' LoneSigs NiceEnv
loneSigs f e = f (_loneSigs e) <&> \ s -> e { _loneSigs = s }
-- | Adding a lone signature to the state.
addLoneSig :: Range -> Name -> DataRecOrFun -> Nice ()
addLoneSig r x k = loneSigs %== \ s -> do
let (mr, s') = Map.insertLookupWithKey (\ _k new _old -> new) x (LoneSig r x k) s
case mr of
Nothing -> return s'
Just{} -> throwError $ DuplicateDefinition x
-- | Remove a lone signature from the state.
removeLoneSig :: Name -> Nice ()
removeLoneSig x = loneSigs %= Map.delete x
-- | Search for forward type signature.
getSig :: Name -> Nice (Maybe DataRecOrFun)
getSig x = fmap loneSigKind . Map.lookup x <$> use loneSigs
-- | Check that no lone signatures are left in the state.
noLoneSigs :: Nice Bool
noLoneSigs = null <$> use loneSigs
-- | Ensure that all forward declarations have been given a definition.
forgetLoneSigs :: Nice ()
forgetLoneSigs = loneSigs .= Map.empty
checkLoneSigs :: LoneSigs -> Nice ()
checkLoneSigs xs = do
forgetLoneSigs
unless (Map.null xs) $ niceWarning $ MissingDefinitions $
map (\s -> (loneSigName s , loneSigRange s)) $ Map.elems xs
-- | Get names of lone function signatures.
loneFuns :: LoneSigs -> [Name]
loneFuns = map fst . filter (isFunName . loneSigKind . snd) . Map.toList
-- | Create a 'LoneSigs' map from an association list.
loneSigsFromLoneNames :: [(Range, Name, DataRecOrFun)] -> LoneSigs
loneSigsFromLoneNames = Map.fromList . map (\(r,x,k) -> (x, LoneSig r x k))
-- | Lens for field '_termChk'.
terminationCheckPragma :: Lens' TerminationCheck NiceEnv
terminationCheckPragma f e = f (_termChk e) <&> \ s -> e { _termChk = s }
withTerminationCheckPragma :: TerminationCheck -> Nice a -> Nice a
withTerminationCheckPragma tc f = do
tc_old <- use terminationCheckPragma
terminationCheckPragma .= tc
result <- f
terminationCheckPragma .= tc_old
return result
coverageCheckPragma :: Lens' CoverageCheck NiceEnv
coverageCheckPragma f e = f (_covChk e) <&> \ s -> e { _covChk = s }
withCoverageCheckPragma :: CoverageCheck -> Nice a -> Nice a
withCoverageCheckPragma tc f = do
tc_old <- use coverageCheckPragma
coverageCheckPragma .= tc
result <- f
coverageCheckPragma .= tc_old
return result
-- | Lens for field '_posChk'.
positivityCheckPragma :: Lens' PositivityCheck NiceEnv
positivityCheckPragma f e = f (_posChk e) <&> \ s -> e { _posChk = s }
withPositivityCheckPragma :: PositivityCheck -> Nice a -> Nice a
withPositivityCheckPragma pc f = do
pc_old <- use positivityCheckPragma
positivityCheckPragma .= pc
result <- f
positivityCheckPragma .= pc_old
return result
-- | Lens for field '_uniChk'.
universeCheckPragma :: Lens' UniverseCheck NiceEnv
universeCheckPragma f e = f (_uniChk e) <&> \ s -> e { _uniChk = s }
withUniverseCheckPragma :: UniverseCheck -> Nice a -> Nice a
withUniverseCheckPragma uc f = do
uc_old <- use universeCheckPragma
universeCheckPragma .= uc
result <- f
universeCheckPragma .= uc_old
return result
-- | Get universe check pragma from a data/rec signature.
Defaults to ' ' .
getUniverseCheckFromSig :: Name -> Nice UniverseCheck
getUniverseCheckFromSig x = maybe YesUniverseCheck universeCheck <$> getSig x
-- | Lens for field '_catchall'.
catchallPragma :: Lens' Catchall NiceEnv
catchallPragma f e = f (_catchall e) <&> \ s -> e { _catchall = s }
-- | Get current catchall pragma, and reset it for the next clause.
popCatchallPragma :: Nice Catchall
popCatchallPragma = do
ca <- use catchallPragma
catchallPragma .= False
return ca
withCatchallPragma :: Catchall -> Nice a -> Nice a
withCatchallPragma ca f = do
ca_old <- use catchallPragma
catchallPragma .= ca
result <- f
catchallPragma .= ca_old
return result
-- | Add a new warning.
niceWarning :: DeclarationWarning -> Nice ()
niceWarning w = modify $ \ st -> st { niceWarn = w : niceWarn st }
data DeclKind
= LoneSigDecl Range DataRecOrFun Name
| LoneDefs DataRecOrFun [Name]
| OtherDecl
deriving (Eq, Show)
declKind :: NiceDeclaration -> DeclKind
declKind (FunSig r _ _ _ _ _ tc cc x _) = LoneSigDecl r (FunName tc cc) x
declKind (NiceRecSig r _ _ pc uc x pars _) = LoneSigDecl r (RecName pc uc) x
declKind (NiceDataSig r _ _ pc uc x pars _) = LoneSigDecl r (DataName pc uc) x
declKind (FunDef r _ abs ins tc cc x _) = LoneDefs (FunName tc cc) [x]
declKind (NiceDataDef _ _ _ pc uc x pars _) = LoneDefs (DataName pc uc) [x]
declKind (NiceRecDef _ _ _ pc uc x _ _ _ pars _)= LoneDefs (RecName pc uc) [x]
declKind (NiceUnquoteDef _ _ _ tc cc xs _) = LoneDefs (FunName tc cc) xs
declKind Axiom{} = OtherDecl
declKind NiceField{} = OtherDecl
declKind PrimitiveFunction{} = OtherDecl
declKind NiceMutual{} = OtherDecl
declKind NiceModule{} = OtherDecl
declKind NiceModuleMacro{} = OtherDecl
declKind NiceOpen{} = OtherDecl
declKind NiceImport{} = OtherDecl
declKind NicePragma{} = OtherDecl
declKind NiceFunClause{} = OtherDecl
declKind NicePatternSyn{} = OtherDecl
declKind NiceGeneralize{} = OtherDecl
declKind NiceUnquoteDecl{} = OtherDecl
| Replace ( Data / Rec / Fun)Sigs with Axioms for postulated names
The first argument is a list of axioms only .
replaceSigs
^ Lone signatures to be turned into Axioms
-> [NiceDeclaration] -- ^ Declarations containing them
-> [NiceDeclaration] -- ^ In the output, everything should be defined
replaceSigs ps = if Map.null ps then id else \case
[] -> __IMPOSSIBLE__
(d:ds) ->
case replaceable d of
-- If declaration d of x is mentioned in the map of lone signatures then replace
-- it with an axiom
Just (x, axiom)
| (Just (LoneSig _ x' _), ps') <- Map.updateLookupWithKey (\ _ _ -> Nothing) x ps
, getRange x == getRange x'
Use the range as UID to ensure we do not replace the wrong signature .
-- This could happen if the user wrote a duplicate definition.
-> axiom : replaceSigs ps' ds
_ -> d : replaceSigs ps ds
where
-- A @replaceable@ declaration is a signature. It has a name and we can make an
-- @Axiom@ out of it.
replaceable :: NiceDeclaration -> Maybe (Name, NiceDeclaration)
replaceable = \case
FunSig r acc abst inst _ argi _ _ x e ->
Just (x, Axiom r acc abst inst argi x e)
NiceRecSig r acc abst _ _ x pars t ->
let e = Generalized $ makePi (lamBindingsToTelescope r pars) t in
Just (x, Axiom r acc abst NotInstanceDef defaultArgInfo x e)
NiceDataSig r acc abst _ _ x pars t ->
let e = Generalized $ makePi (lamBindingsToTelescope r pars) t in
Just (x, Axiom r acc abst NotInstanceDef defaultArgInfo x e)
_ -> Nothing
| Main . ( or more precisely syntax declarations ) are needed when
-- grouping function clauses.
niceDeclarations :: Fixities -> [Declaration] -> Nice [NiceDeclaration]
niceDeclarations fixs ds = do
-- Run the nicifier in an initial environment. But keep the warnings.
st <- get
put $ initNiceEnv { niceWarn = niceWarn st }
nds <- nice ds
-- Check that every signature got its definition.
ps <- use loneSigs
checkLoneSigs ps
We postulate the missing ones and insert them in place of the corresponding
let ds = replaceSigs ps nds
-- Note that loneSigs is ensured to be empty.
-- (Important, since inferMutualBlocks also uses loneSigs state).
res <- inferMutualBlocks ds
-- Restore the old state, but keep the warnings.
warns <- gets niceWarn
put $ st { niceWarn = warns }
return res
where
inferMutualBlocks :: [NiceDeclaration] -> Nice [NiceDeclaration]
inferMutualBlocks [] = return []
inferMutualBlocks (d : ds) =
case declKind d of
OtherDecl -> (d :) <$> inferMutualBlocks ds
, 2017 - 10 - 09 , issue # 2576 : report error in ConcreteToAbstract
LoneSigDecl r k x -> do
addLoneSig r x k
let tcccpc = ([terminationCheck k], [coverageCheck k], [positivityCheck k])
((tcs, ccs, pcs), (nds0, ds1)) <- untilAllDefined tcccpc ds
-- If we still have lone signatures without any accompanying definition,
-- we postulate the definition and substitute the axiom for the lone signature
ps <- use loneSigs
checkLoneSigs ps
NB : do n't forget the LoneSig the block started with !
-- We then keep processing the rest of the block
tc <- combineTerminationChecks (getRange d) tcs
let cc = combineCoverageChecks ccs
let pc = combinePositivityChecks pcs
(NiceMutual (getRange ds0) tc cc pc ds0 :) <$> inferMutualBlocks ds1
where
untilAllDefined :: ([TerminationCheck], [CoverageCheck], [PositivityCheck])
-> [NiceDeclaration]
-> Nice (([TerminationCheck], [CoverageCheck], [PositivityCheck]) -- checks for this block
, ([NiceDeclaration] -- mutual block
, [NiceDeclaration]) -- leftovers
)
untilAllDefined tcccpc@(tc, cc, pc) ds = do
done <- noLoneSigs
if done then return (tcccpc, ([], ds)) else
case ds of
[] -> return (tcccpc, ([], ds))
d : ds -> case declKind d of
LoneSigDecl r k x -> do
addLoneSig r x k
let tcccpc' = (terminationCheck k : tc, coverageCheck k : cc, positivityCheck k : pc)
cons d (untilAllDefined tcccpc' ds)
LoneDefs k xs -> do
mapM_ removeLoneSig xs
let tcccpc' = (terminationCheck k : tc, coverageCheck k : cc, positivityCheck k : pc)
cons d (untilAllDefined tcccpc' ds)
OtherDecl -> cons d (untilAllDefined tcccpc ds)
where
ASR ( 26 December 2015 ): Type annotated version of the @cons@ function .
-- cons d = fmap $
( i d : : ( ( [ TerminationCheck ] , [ PositivityCheck ] ) - > ( [ TerminationCheck ] , [ PositivityCheck ] ) ) )
-- *** (d :)
-- *** (id :: [NiceDeclaration] -> [NiceDeclaration])
cons d = fmap (id *** (d :) *** id)
notMeasure TerminationMeasure{} = False
notMeasure _ = True
nice :: [Declaration] -> Nice [NiceDeclaration]
nice [] = return []
nice ds = do
(xs , ys) <- nice1 ds
(xs ++) <$> nice ys
nice1 :: [Declaration] -> Nice ([NiceDeclaration], [Declaration])
, 2017 - 09 - 16 , issue # 2759 : no longer _ _ IMPOSSIBLE _ _
nice1 (d:ds) = do
let justWarning w = do niceWarning w; nice1 ds
case d of
TypeSig info _tac x t -> do
termCheck <- use terminationCheckPragma
covCheck <- use coverageCheckPragma
let r = getRange d
-- register x as lone type signature, to recognize clauses later
addLoneSig r x $ FunName termCheck covCheck
return ([FunSig r PublicAccess ConcreteDef NotInstanceDef NotMacroDef info termCheck covCheck x t] , ds)
Should not show up : all FieldSig are part of a Field block
FieldSig{} -> __IMPOSSIBLE__
Generalize r [] -> justWarning $ EmptyGeneralize r
Generalize r sigs -> do
gs <- forM sigs $ \case
sig@(TypeSig info tac x t) -> do
return $ NiceGeneralize (getRange sig) PublicAccess info tac x t
_ -> __IMPOSSIBLE__
return (gs, ds)
(FunClause lhs _ _ _) -> do
termCheck <- use terminationCheckPragma
covCheck <- use coverageCheckPragma
catchall <- popCatchallPragma
xs <- loneFuns <$> use loneSigs
-- for each type signature 'x' waiting for clauses, we try
-- if we have some clauses for 'x'
case [ (x, (fits, rest))
| x <- xs
, let (fits, rest) =
Anonymous declarations only have 1 clause each !
if isNoName x then ([d], ds)
else span (couldBeFunClauseOf (Map.lookup x fixs) x) (d : ds)
, not (null fits)
] of
case : clauses match none of the sigs
[] -> case lhs of
Subcase : The lhs is single identifier ( potentially anonymous ) .
-- Treat it as a function clause without a type signature.
LHS p [] [] _ | Just x <- isSingleIdentifierP p -> do
d <- mkFunDef defaultArgInfo termCheck covCheck x Nothing [d] -- fun def without type signature is relevant
return (d , ds)
Subcase : The lhs is a proper pattern .
-- This could be a let-pattern binding. Pass it on.
A missing type signature error might be raise in ConcreteToAbstract
_ -> do
return ([NiceFunClause (getRange d) PublicAccess ConcreteDef termCheck covCheck catchall d] , ds)
case : clauses match exactly one of the sigs
[(x,(fits,rest))] -> do
removeLoneSig x
ds <- expandEllipsis fits
cs <- mkClauses x ds False
return ([FunDef (getRange fits) fits ConcreteDef NotInstanceDef termCheck covCheck x cs] , rest)
case : clauses match more than one sigs ( ambiguity )
l -> throwError $ AmbiguousFunClauses lhs $ reverse $ map fst l
" ambiguous function clause ; can not assign it uniquely to one type signature "
Field r [] -> justWarning $ EmptyField r
Field _ fs -> (,ds) <$> niceAxioms FieldBlock fs
DataSig r x tel t -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
addLoneSig r x $ DataName pc uc
(,) <$> dataOrRec pc uc NiceDataDef NiceDataSig (niceAxioms DataBlock) r x (Just (tel, t)) Nothing
<*> return ds
Data r x tel t cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
-- Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
Universe check is performed if both the current value of
-- 'universeCheckPragma' AND the one from the signature say so.
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (DataName pc uc) x (Just t)
(,) <$> dataOrRec pc uc NiceDataDef NiceDataSig (niceAxioms DataBlock) r x ((tel,) <$> mt) (Just (tel, cs))
<*> return ds
DataDef r x tel cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
-- Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
Universe check is performed if both the current value of
-- 'universeCheckPragma' AND the one from the signature say so.
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (DataName pc uc) x Nothing
(,) <$> dataOrRec pc uc NiceDataDef NiceDataSig (niceAxioms DataBlock) r x ((tel,) <$> mt) (Just (tel, cs))
<*> return ds
RecordSig r x tel t -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
addLoneSig r x $ RecName pc uc
return ([NiceRecSig r PublicAccess ConcreteDef pc uc x tel t] , ds)
Record r x i e c tel t cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
-- Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
Universe check is performed if both the current value of
-- 'universeCheckPragma' AND the one from the signature say so.
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (RecName pc uc) x (Just t)
(,) <$> dataOrRec pc uc (\ r o a pc uc x tel cs -> NiceRecDef r o a pc uc x i e c tel cs) NiceRecSig
return r x ((tel,) <$> mt) (Just (tel, cs))
<*> return ds
RecordDef r x i e c tel cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
-- Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
Universe check is performed if both the current value of
-- 'universeCheckPragma' AND the one from the signature say so.
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (RecName pc uc) x Nothing
(,) <$> dataOrRec pc uc (\ r o a pc uc x tel cs -> NiceRecDef r o a pc uc x i e c tel cs) NiceRecSig
return r x ((tel,) <$> mt) (Just (tel, cs))
<*> return ds
Mutual r ds' -> do
-- The lone signatures encountered so far are not in scope
-- for the mutual definition
forgetLoneSigs
case ds' of
[] -> justWarning $ EmptyMutual r
_ -> (,ds) <$> (singleton <$> (mkOldMutual r =<< nice ds'))
Abstract r [] -> justWarning $ EmptyAbstract r
Abstract r ds' ->
(,ds) <$> (abstractBlock r =<< nice ds')
Private r UserWritten [] -> justWarning $ EmptyPrivate r
Private r o ds' ->
(,ds) <$> (privateBlock r o =<< nice ds')
InstanceB r [] -> justWarning $ EmptyInstance r
InstanceB r ds' ->
(,ds) <$> (instanceBlock r =<< nice ds')
Macro r [] -> justWarning $ EmptyMacro r
Macro r ds' ->
(,ds) <$> (macroBlock r =<< nice ds')
Postulate r [] -> justWarning $ EmptyPostulate r
Postulate _ ds' ->
(,ds) <$> niceAxioms PostulateBlock ds'
Primitive r [] -> justWarning $ EmptyPrimitive r
Primitive _ ds' -> (,ds) <$> (map toPrim <$> niceAxioms PrimitiveBlock ds')
Module r x tel ds' -> return $
([NiceModule r PublicAccess ConcreteDef x tel ds'] , ds)
ModuleMacro r x modapp op is -> return $
([NiceModuleMacro r PublicAccess x modapp op is] , ds)
-- Fixity and syntax declarations and polarity pragmas have
-- already been processed.
Infix _ _ -> return ([], ds)
Syntax _ _ -> return ([], ds)
PatternSyn r n as p -> do
return ([NicePatternSyn r PublicAccess n as p] , ds)
Open r x is -> return ([NiceOpen r x is] , ds)
Import r x as op is -> return ([NiceImport r x as op is] , ds)
UnquoteDecl r xs e -> do
tc <- use terminationCheckPragma
cc <- use coverageCheckPragma
return ([NiceUnquoteDecl r PublicAccess ConcreteDef NotInstanceDef tc cc xs e] , ds)
UnquoteDef r xs e -> do
sigs <- loneFuns <$> use loneSigs
let missing = filter (`notElem` sigs) xs
if null missing
then do
mapM_ removeLoneSig xs
return ([NiceUnquoteDef r PublicAccess ConcreteDef TerminationCheck YesCoverageCheck xs e] , ds)
else throwError $ UnquoteDefRequiresSignature missing
Pragma p -> nicePragma p ds
nicePragma :: Pragma -> [Declaration] -> Nice ([NiceDeclaration], [Declaration])
nicePragma (TerminationCheckPragma r (TerminationMeasure _ x)) ds =
if canHaveTerminationMeasure ds then
withTerminationCheckPragma (TerminationMeasure r x) $ nice1 ds
else do
niceWarning $ InvalidTerminationCheckPragma r
nice1 ds
nicePragma (TerminationCheckPragma r NoTerminationCheck) ds = do
This PRAGMA has been deprecated in favour of ( NON_)TERMINATING
-- We warn the user about it and then assume the function is NON_TERMINATING.
niceWarning $ PragmaNoTerminationCheck r
nicePragma (TerminationCheckPragma r NonTerminating) ds
nicePragma (TerminationCheckPragma r tc) ds =
if canHaveTerminationCheckPragma ds then
withTerminationCheckPragma tc $ nice1 ds
else do
niceWarning $ InvalidTerminationCheckPragma r
nice1 ds
nicePragma (NoCoverageCheckPragma r) ds =
if canHaveCoverageCheckPragma ds then
withCoverageCheckPragma NoCoverageCheck $ nice1 ds
else do
niceWarning $ InvalidCoverageCheckPragma r
nice1 ds
nicePragma (CatchallPragma r) ds =
if canHaveCatchallPragma ds then
withCatchallPragma True $ nice1 ds
else do
niceWarning $ InvalidCatchallPragma r
nice1 ds
nicePragma (NoPositivityCheckPragma r) ds =
if canHaveNoPositivityCheckPragma ds then
withPositivityCheckPragma NoPositivityCheck $ nice1 ds
else do
niceWarning $ InvalidNoPositivityCheckPragma r
nice1 ds
nicePragma (NoUniverseCheckPragma r) ds =
if canHaveNoUniverseCheckPragma ds then
withUniverseCheckPragma NoUniverseCheck $ nice1 ds
else do
niceWarning $ InvalidNoUniverseCheckPragma r
nice1 ds
nicePragma p@CompilePragma{} ds = do
niceWarning $ PragmaCompiled (getRange p)
return ([NicePragma (getRange p) p], ds)
nicePragma (PolarityPragma{}) ds = return ([], ds)
nicePragma (BuiltinPragma r str qn@(QName x)) ds = do
return ([NicePragma r (BuiltinPragma r str qn)], ds)
nicePragma p ds = return ([NicePragma (getRange p) p], ds)
canHaveTerminationMeasure :: [Declaration] -> Bool
canHaveTerminationMeasure [] = False
canHaveTerminationMeasure (d:ds) = case d of
TypeSig{} -> True
(Pragma p) | isAttachedPragma p -> canHaveTerminationMeasure ds
_ -> False
canHaveTerminationCheckPragma :: [Declaration] -> Bool
canHaveTerminationCheckPragma [] = False
canHaveTerminationCheckPragma (d:ds) = case d of
Mutual _ ds -> any (canHaveTerminationCheckPragma . singleton) ds
TypeSig{} -> True
FunClause{} -> True
UnquoteDecl{} -> True
(Pragma p) | isAttachedPragma p -> canHaveTerminationCheckPragma ds
_ -> False
canHaveCoverageCheckPragma :: [Declaration] -> Bool
canHaveCoverageCheckPragma = canHaveTerminationCheckPragma
canHaveCatchallPragma :: [Declaration] -> Bool
canHaveCatchallPragma [] = False
canHaveCatchallPragma (d:ds) = case d of
FunClause{} -> True
(Pragma p) | isAttachedPragma p -> canHaveCatchallPragma ds
_ -> False
canHaveNoPositivityCheckPragma :: [Declaration] -> Bool
canHaveNoPositivityCheckPragma [] = False
canHaveNoPositivityCheckPragma (d:ds) = case d of
Mutual _ ds -> any (canHaveNoPositivityCheckPragma . singleton) ds
Data{} -> True
DataSig{} -> True
DataDef{} -> True
Record{} -> True
RecordSig{} -> True
RecordDef{} -> True
Pragma p | isAttachedPragma p -> canHaveNoPositivityCheckPragma ds
_ -> False
canHaveNoUniverseCheckPragma :: [Declaration] -> Bool
canHaveNoUniverseCheckPragma [] = False
canHaveNoUniverseCheckPragma (d:ds) = case d of
Data{} -> True
DataSig{} -> True
DataDef{} -> True
Record{} -> True
RecordSig{} -> True
RecordDef{} -> True
Pragma p | isAttachedPragma p -> canHaveNoPositivityCheckPragma ds
_ -> False
Pragma that attaches to the following declaration .
isAttachedPragma :: Pragma -> Bool
isAttachedPragma p = case p of
TerminationCheckPragma{} -> True
CatchallPragma{} -> True
NoPositivityCheckPragma{} -> True
NoUniverseCheckPragma{} -> True
_ -> False
-- We could add a default type signature here, but at the moment we can't
-- infer the type of a record or datatype, so better to just fail here.
defaultTypeSig :: DataRecOrFun -> Name -> Maybe Expr -> Nice (Maybe Expr)
defaultTypeSig k x t@Just{} = return t
defaultTypeSig k x Nothing = do
caseMaybeM (getSig x) (return Nothing) $ \ k' -> do
unless (sameKind k k') $ throwError $ WrongDefinition x k' k
Nothing <$ removeLoneSig x
dataOrRec
:: forall a decl
. PositivityCheck
-> UniverseCheck
-> (Range -> Origin -> IsAbstract -> PositivityCheck -> UniverseCheck -> Name -> [LamBinding] -> [decl] -> NiceDeclaration)
-- ^ Construct definition.
-> (Range -> Access -> IsAbstract -> PositivityCheck -> UniverseCheck -> Name -> [LamBinding] -> Expr -> NiceDeclaration)
-- ^ Construct signature.
-> ([a] -> Nice [decl])
-- ^ Constructor checking.
-> Range
-> Name -- ^ Data/record type name.
-> Maybe ([LamBinding], Expr) -- ^ Parameters and type. If not @Nothing@ a signature is created.
-> Maybe ([LamBinding], [a]) -- ^ Parameters and constructors. If not @Nothing@, a definition body is created.
-> Nice [NiceDeclaration]
dataOrRec pc uc mkDef mkSig niceD r x mt mcs = do
mds <- Trav.forM mcs $ \ (tel, cs) -> (tel,) <$> niceD cs
We set origin to UserWritten if the user split the data / rec herself ,
-- and to Inserted if the she wrote a single declaration that we're
-- splitting up here. We distinguish these because the scoping rules for
-- generalizable variables differ in these cases.
let o | isJust mt && isJust mcs = Inserted
| otherwise = UserWritten
return $ catMaybes $
[ mt <&> \ (tel, t) -> mkSig (fuseRange x t) PublicAccess ConcreteDef pc uc x tel t
, mds <&> \ (tel, ds) -> mkDef r o ConcreteDef pc uc x (caseMaybe mt tel $ const $ concatMap dropTypeAndModality tel) ds
If a type is given ( mt /= Nothing ) , we have to delete the types in @tel@
for the data definition , lest we duplicate them . And also drop modalities ( # 1886 ) .
]
where
-- | Drop type annotations and lets from bindings.
dropTypeAndModality :: LamBinding -> [LamBinding]
dropTypeAndModality (DomainFull (TBind _ xs _)) =
map (DomainFree . setModality defaultModality) xs
dropTypeAndModality (DomainFull TLet{}) = []
dropTypeAndModality (DomainFree x) = [DomainFree $ setModality defaultModality x]
Translate axioms
niceAxioms :: KindOfBlock -> [TypeSignatureOrInstanceBlock] -> Nice [NiceDeclaration]
niceAxioms b ds = liftM List.concat $ mapM (niceAxiom b) ds
niceAxiom :: KindOfBlock -> TypeSignatureOrInstanceBlock -> Nice [NiceDeclaration]
niceAxiom b d = case d of
TypeSig rel _tac x t -> do
return [ Axiom (getRange d) PublicAccess ConcreteDef NotInstanceDef rel x t ]
FieldSig i tac x argt | b == FieldBlock -> do
return [ NiceField (getRange d) PublicAccess ConcreteDef i tac x argt ]
InstanceB r decls -> do
instanceBlock r =<< niceAxioms InstanceBlock decls
Pragma p@(RewritePragma r _ _) -> do
return [ NicePragma r p ]
_ -> throwError $ WrongContentBlock b $ getRange d
toPrim :: NiceDeclaration -> NiceDeclaration
toPrim (Axiom r p a i rel x t) = PrimitiveFunction r p a x t
toPrim _ = __IMPOSSIBLE__
-- Create a function definition.
mkFunDef info termCheck covCheck x mt ds0 = do
ds <- expandEllipsis ds0
cs <- mkClauses x ds False
return [ FunSig (fuseRange x t) PublicAccess ConcreteDef NotInstanceDef NotMacroDef info termCheck covCheck x t
, FunDef (getRange ds0) ds0 ConcreteDef NotInstanceDef termCheck covCheck x cs ]
where
t = case mt of
Just t -> t
Nothing -> underscore (getRange x)
underscore r = Underscore r Nothing
expandEllipsis :: [Declaration] -> Nice [Declaration]
expandEllipsis [] = return []
expandEllipsis (d@(FunClause lhs@(LHS p _ _ ell) _ _ _) : ds)
| ExpandedEllipsis{} <- ell = __IMPOSSIBLE__
| hasEllipsis p = (d :) <$> expandEllipsis ds
| otherwise = (d :) <$> expand (killRange p) ds
where
expand :: Pattern -> [Declaration] -> Nice [Declaration]
expand _ [] = return []
expand p (d : ds) = do
case d of
Pragma (CatchallPragma _) -> do
(d :) <$> expand p ds
FunClause (LHS p0 eqs es NoEllipsis) rhs wh ca -> do
case hasEllipsis' p0 of
ManyHoles -> throwError $ MultipleEllipses p0
OneHole cxt ~(EllipsisP r) -> do
Replace the ellipsis by @p@.
let p1 = cxt p
let ell = ExpandedEllipsis r (numberOfWithPatterns p)
let d' = FunClause (LHS p1 eqs es ell) rhs wh ca
-- If we have with-expressions (es /= []) then the following
-- ellipses also get the additional patterns in p0.
(d' :) <$> expand (if null es then p else killRange p1) ds
ZeroHoles _ -> do
-- We can have ellipses after a fun clause without.
-- They refer to the last clause that introduced new with-expressions.
-- Same here: If we have new with-expressions, the next ellipses will
-- refer to us.
Andreas , Jesper , 2017 - 05 - 13 , issue # 2578
-- Need to update the range also on the next with-patterns.
(d :) <$> expand (if null es then p else killRange p0) ds
_ -> __IMPOSSIBLE__
expandEllipsis _ = __IMPOSSIBLE__
-- Turn function clauses into nice function clauses.
mkClauses :: Name -> [Declaration] -> Catchall -> Nice [Clause]
mkClauses _ [] _ = return []
mkClauses x (Pragma (CatchallPragma r) : cs) True = do
niceWarning $ InvalidCatchallPragma r
mkClauses x cs True
mkClauses x (Pragma (CatchallPragma r) : cs) False = do
when (null cs) $ niceWarning $ InvalidCatchallPragma r
mkClauses x cs True
mkClauses x (FunClause lhs rhs wh ca : cs) catchall
| null (lhsWithExpr lhs) || hasEllipsis lhs =
(Clause x (ca || catchall) lhs rhs wh [] :) <$> mkClauses x cs False -- Will result in an error later.
mkClauses x (FunClause lhs rhs wh ca : cs) catchall = do
when (null withClauses) $ throwError $ MissingWithClauses x lhs
wcs <- mkClauses x withClauses False
(Clause x (ca || catchall) lhs rhs wh wcs :) <$> mkClauses x cs' False
where
(withClauses, cs') = subClauses cs
-- A clause is a subclause if the number of with-patterns is
-- greater or equal to the current number of with-patterns plus the
-- number of with arguments.
numWith = numberOfWithPatterns p + length (filter visible es) where LHS p _ es _ = lhs
subClauses :: [Declaration] -> ([Declaration],[Declaration])
subClauses (c@(FunClause (LHS p0 _ _ _) _ _ _) : cs)
| isEllipsis p0 ||
numberOfWithPatterns p0 >= numWith = mapFst (c:) (subClauses cs)
| otherwise = ([], c:cs)
subClauses (c@(Pragma (CatchallPragma r)) : cs) = case subClauses cs of
([], cs') -> ([], c:cs')
(cs, cs') -> (c:cs, cs')
subClauses [] = ([],[])
subClauses _ = __IMPOSSIBLE__
mkClauses _ _ _ = __IMPOSSIBLE__
-- for finding clauses for a type sig in mutual blocks
couldBeFunClauseOf :: Maybe Fixity' -> Name -> Declaration -> Bool
couldBeFunClauseOf mFixity x (Pragma (CatchallPragma{})) = True
couldBeFunClauseOf mFixity x (FunClause (LHS p _ _ _) _ _ _) = hasEllipsis p ||
let
pns = patternNames p
xStrings = nameStringParts x
patStrings = concatMap nameStringParts pns
in
-- trace ("x = " ++ prettyShow x) $
-- trace ("pns = " ++ show pns) $
trace ( " xStrings = " + + show xStrings ) $
trace ( " patStrings = " + + show ) $
-- trace ("mFixity = " ++ show mFixity) $
case (listToMaybe pns, mFixity) of
first identifier in the patterns is the fun.symbol ?
(Just y, _) | x == y -> True -- trace ("couldBe since y = " ++ prettyShow y) $ True
are the parts of x contained in p
_ | xStrings `isSublistOf` patStrings -> True -- trace ("couldBe since isSublistOf") $ True
-- looking for a mixfix fun.symb
(_, Just fix) -> -- also matches in case of a postfix
let notStrings = stringParts (theNotation fix)
trace ( " notStrings = " + + show ) $
trace ( " patStrings = " + + show ) $
(not $ null notStrings) && (notStrings `isSublistOf` patStrings)
-- not a notation, not first id: give up
_ -> False -- trace ("couldBe not (case default)") $ False
couldBeFunClauseOf _ _ _ = False -- trace ("couldBe not (fun default)") $ False
-- | Turn an old-style mutual block into a new style mutual block
-- by pushing the definitions to the end.
mkOldMutual
:: Range -- ^ Range of the whole @mutual@ block.
-> [NiceDeclaration] -- ^ Declarations inside the block.
-> Nice NiceDeclaration -- ^ Returns a 'NiceMutual'.
mkOldMutual r ds' = do
-- Postulate the missing definitions
let ps = loneSigsFromLoneNames loneNames
checkLoneSigs ps
let ds = replaceSigs ps ds'
-- -- Remove the declarations that aren't allowed in old style mutual blocks
ds < - fmap $ forM ds $ \ d - > let success = pure ( Just d ) in case d of
-- , 2013 - 11 - 23 allow postulates in mutual blocks
Axiom { } - > success
-- , 2017 - 10 - 09 , issue # 2576 , raise error about missing type signature
-- in ConcreteToAbstract rather than here .
-- NiceFunClause{} -> success
-- , 2018 - 05 - 11 , issue # 3052 , allow pat.syn.s in mutual blocks
-- NicePatternSyn{} -> success
-- -- Otherwise, only categorized signatures and definitions are allowed:
-- -- Data, Record, Fun
-- _ -> if (declKind d /= OtherDecl) then success
-- else Nothing <$ niceWarning (NotAllowedInMutual (getRange d) $ declName d)
-- Sort the declarations in the mutual block.
-- Declarations of names go to the top. (Includes module definitions.)
-- Definitions of names go to the bottom.
-- Some declarations are forbidden, as their positioning could confuse
-- the user.
(top, bottom, invalid) <- forEither3M ds $ \ d -> do
let top = return (In1 d)
bottom = return (In2 d)
invalid s = In3 d <$ do niceWarning $ NotAllowedInMutual (getRange d) s
case d of
, 2013 - 11 - 23 allow postulates in mutual blocks
Axiom{} -> top
NiceField{} -> top
PrimitiveFunction{} -> top
, 2019 - 07 - 23 issue # 3932 :
-- Nested mutual blocks are not supported.
NiceMutual{} -> invalid "mutual blocks"
, 2018 - 10 - 29 , issue # 3246
-- We could allow modules (top), but this is potentially confusing.
NiceModule{} -> invalid "Module definitions"
NiceModuleMacro{} -> top
NiceOpen{} -> top
NiceImport{} -> top
NiceRecSig{} -> top
NiceDataSig{} -> top
, 2017 - 10 - 09 , issue # 2576 , raise error about missing type signature
in ConcreteToAbstract rather than here .
NiceFunClause{} -> bottom
FunSig{} -> top
FunDef{} -> bottom
NiceDataDef{} -> bottom
NiceRecDef{} -> bottom
, 2018 - 05 - 11 , issue # 3051 , allow pat.syn.s in mutual blocks
, 2018 - 10 - 29 : We shift pattern synonyms to the bottom
-- since they might refer to constructors defined in a data types
-- just above them.
NicePatternSyn{} -> bottom
NiceGeneralize{} -> top
NiceUnquoteDecl{} -> top
NiceUnquoteDef{} -> bottom
NicePragma r pragma -> case pragma of
OptionsPragma{} -> top -- error thrown in the type checker
-- Some builtins require a definition, and they affect type checking
-- Thus, we do not handle BUILTINs in mutual blocks (at least for now).
BuiltinPragma{} -> invalid "BUILTIN pragmas"
-- The REWRITE pragma behaves differently before or after the def.
-- and affects type checking. Thus, we refuse it here.
RewritePragma{} -> invalid "REWRITE pragmas"
-- Compiler pragmas are not needed for type checking, thus,
-- can go to the bottom.
ForeignPragma{} -> bottom
CompilePragma{} -> bottom
StaticPragma{} -> bottom
InlinePragma{} -> bottom
ImpossiblePragma{} -> top -- error thrown in scope checker
EtaPragma{} -> bottom -- needs record definition
WarningOnUsage{} -> top
WarningOnImport{} -> top
InjectivePragma{} -> top -- only needs name, not definition
DisplayPragma{} -> top -- only for printing
-- The attached pragmas have already been handled at this point.
CatchallPragma{} -> __IMPOSSIBLE__
TerminationCheckPragma{} -> __IMPOSSIBLE__
NoPositivityCheckPragma{} -> __IMPOSSIBLE__
PolarityPragma{} -> __IMPOSSIBLE__
NoUniverseCheckPragma{} -> __IMPOSSIBLE__
NoCoverageCheckPragma{} -> __IMPOSSIBLE__
-- -- Pull type signatures to the top
let ( sigs , other ) = List.partition isTypeSig ds
-- -- Push definitions to the bottom
let ( other , defs ) = flip List.partition ds $ \case
-- FunDef{} -> False
-- NiceDataDef{} -> False
-- NiceRecDef{} -> False
-- NiceFunClause{} -> False
-- NicePatternSyn{} -> False
-- NiceUnquoteDef{} -> False
-- _ -> True
-- Compute termination checking flag for mutual block
tc0 <- use terminationCheckPragma
let tcs = map termCheck ds
tc <- combineTerminationChecks r (tc0:tcs)
-- Compute coverage checking flag for mutual block
cc0 <- use coverageCheckPragma
let ccs = map covCheck ds
let cc = combineCoverageChecks (cc0:ccs)
-- Compute positivity checking flag for mutual block
pc0 <- use positivityCheckPragma
let pcs = map positivityCheckOldMutual ds
let pc = combinePositivityChecks (pc0:pcs)
return $ NiceMutual r tc cc pc $ top ++ bottom
-- return $ NiceMutual r tc pc $ other ++ defs
-- return $ NiceMutual r tc pc $ sigs ++ other
where
isTypeSig Axiom { } = True
isTypeSig d | { } < - declKind d = True
-- isTypeSig _ = False
sigNames = [ (r, x, k) | LoneSigDecl r k x <- map declKind ds' ]
defNames = [ (x, k) | LoneDefs k xs <- map declKind ds', x <- xs ]
-- compute the set difference with equality just on names
loneNames = [ (r, x, k) | (r, x, k) <- sigNames, List.all ((x /=) . fst) defNames ]
termCheck :: NiceDeclaration -> TerminationCheck
, 2013 - 02 - 28 ( issue 804 ):
-- do not termination check a mutual block if any of its
inner declarations comes with a { - # NO_TERMINATION_CHECK # - }
termCheck (FunSig _ _ _ _ _ _ tc _ _ _) = tc
termCheck (FunDef _ _ _ _ tc _ _ _) = tc
ASR ( 28 December 2015 ): Is this equation necessary ?
termCheck (NiceMutual _ tc _ _ _) = tc
termCheck (NiceUnquoteDecl _ _ _ _ tc _ _ _) = tc
termCheck (NiceUnquoteDef _ _ _ tc _ _ _) = tc
termCheck Axiom{} = TerminationCheck
termCheck NiceField{} = TerminationCheck
termCheck PrimitiveFunction{} = TerminationCheck
termCheck NiceModule{} = TerminationCheck
termCheck NiceModuleMacro{} = TerminationCheck
termCheck NiceOpen{} = TerminationCheck
termCheck NiceImport{} = TerminationCheck
termCheck NicePragma{} = TerminationCheck
termCheck NiceRecSig{} = TerminationCheck
termCheck NiceDataSig{} = TerminationCheck
termCheck NiceFunClause{} = TerminationCheck
termCheck NiceDataDef{} = TerminationCheck
termCheck NiceRecDef{} = TerminationCheck
termCheck NicePatternSyn{} = TerminationCheck
termCheck NiceGeneralize{} = TerminationCheck
covCheck :: NiceDeclaration -> CoverageCheck
covCheck (FunSig _ _ _ _ _ _ _ cc _ _) = cc
covCheck (FunDef _ _ _ _ _ cc _ _) = cc
ASR ( 28 December 2015 ): Is this equation necessary ?
covCheck (NiceMutual _ _ cc _ _) = cc
covCheck (NiceUnquoteDecl _ _ _ _ _ cc _ _) = cc
covCheck (NiceUnquoteDef _ _ _ _ cc _ _) = cc
covCheck Axiom{} = YesCoverageCheck
covCheck NiceField{} = YesCoverageCheck
covCheck PrimitiveFunction{} = YesCoverageCheck
covCheck NiceModule{} = YesCoverageCheck
covCheck NiceModuleMacro{} = YesCoverageCheck
covCheck NiceOpen{} = YesCoverageCheck
covCheck NiceImport{} = YesCoverageCheck
covCheck NicePragma{} = YesCoverageCheck
covCheck NiceRecSig{} = YesCoverageCheck
covCheck NiceDataSig{} = YesCoverageCheck
covCheck NiceFunClause{} = YesCoverageCheck
covCheck NiceDataDef{} = YesCoverageCheck
covCheck NiceRecDef{} = YesCoverageCheck
covCheck NicePatternSyn{} = YesCoverageCheck
covCheck NiceGeneralize{} = YesCoverageCheck
ASR ( 26 December 2015 ): Do not positivity check a mutual
-- block if any of its inner declarations comes with a
NO_POSITIVITY_CHECK pragma . See Issue 1614 .
positivityCheckOldMutual :: NiceDeclaration -> PositivityCheck
positivityCheckOldMutual (NiceDataDef _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceDataSig _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceMutual _ _ _ pc _) = pc
positivityCheckOldMutual (NiceRecSig _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceRecDef _ _ _ pc _ _ _ _ _ _ _) = pc
positivityCheckOldMutual _ = YesPositivityCheck
-- A mutual block cannot have a measure,
-- but it can skip termination check.
abstractBlock _ [] = return []
abstractBlock r ds = do
(ds', anyChange) <- runChangeT $ mkAbstract ds
let inherited = r == noRange
if anyChange then return ds' else do
-- hack to avoid failing on inherited abstract blocks in where clauses
unless inherited $ niceWarning $ UselessAbstract r
return ds -- no change!
privateBlock _ _ [] = return []
privateBlock r o ds = do
(ds', anyChange) <- runChangeT $ mkPrivate o ds
if anyChange then return ds' else do
when (o == UserWritten) $ niceWarning $ UselessPrivate r
return ds -- no change!
instanceBlock
:: Range -- ^ Range of @instance@ keyword.
-> [NiceDeclaration]
-> Nice [NiceDeclaration]
instanceBlock _ [] = return []
instanceBlock r ds = do
let (ds', anyChange) = runChange $ mapM (mkInstance r) ds
if anyChange then return ds' else do
niceWarning $ UselessInstance r
return ds -- no change!
-- Make a declaration eligible for instance search.
mkInstance
:: Range -- ^ Range of @instance@ keyword.
-> Updater NiceDeclaration
mkInstance r0 = \case
Axiom r p a i rel x e -> (\ i -> Axiom r p a i rel x e) <$> setInstance r0 i
FunSig r p a i m rel tc cc x e -> (\ i -> FunSig r p a i m rel tc cc x e) <$> setInstance r0 i
NiceUnquoteDecl r p a i tc cc x e -> (\ i -> NiceUnquoteDecl r p a i tc cc x e) <$> setInstance r0 i
NiceMutual r tc cc pc ds -> NiceMutual r tc cc pc <$> mapM (mkInstance r0) ds
d@NiceFunClause{} -> return d
FunDef r ds a i tc cc x cs -> (\ i -> FunDef r ds a i tc cc x cs) <$> setInstance r0 i
Field instance are handled by the parser
d@PrimitiveFunction{} -> return d
d@NiceUnquoteDef{} -> return d
d@NiceRecSig{} -> return d
d@NiceDataSig{} -> return d
d@NiceModuleMacro{} -> return d
d@NiceModule{} -> return d
d@NicePragma{} -> return d
d@NiceOpen{} -> return d
d@NiceImport{} -> return d
d@NiceDataDef{} -> return d
d@NiceRecDef{} -> return d
d@NicePatternSyn{} -> return d
d@NiceGeneralize{} -> return d
setInstance
:: Range -- ^ Range of @instance@ keyword.
-> Updater IsInstance
setInstance r0 = \case
i@InstanceDef{} -> return i
_ -> dirty $ InstanceDef r0
macroBlock r ds = mapM mkMacro ds
mkMacro :: NiceDeclaration -> Nice NiceDeclaration
mkMacro = \case
FunSig r p a i _ rel tc cc x e -> return $ FunSig r p a i MacroDef rel tc cc x e
d@FunDef{} -> return d
d -> throwError (BadMacroDef d)
-- | Make a declaration abstract.
--
-- Mark computation as 'dirty' if there was a declaration that could be made abstract.
If no abstraction is taking place , we want to complain about ' UselessAbstract ' .
--
-- Alternatively, we could only flag 'dirty' if a non-abstract thing was abstracted.
-- Then, nested @abstract@s would sometimes also be complained about.
class MakeAbstract a where
mkAbstract :: UpdaterT Nice a
default mkAbstract :: (Traversable f, MakeAbstract a', a ~ f a') => UpdaterT Nice a
mkAbstract = traverse mkAbstract
instance MakeAbstract a => MakeAbstract [a] where
-- Default definition kicks in here!
-- But note that we still have to declare the instance!
Leads to overlap with ' WhereClause ' :
instance ( f , MakeAbstract a ) = > MakeAbstract ( f a ) where
-- mkAbstract = traverse mkAbstract
instance MakeAbstract IsAbstract where
mkAbstract = \case
a@AbstractDef -> return a
ConcreteDef -> dirty $ AbstractDef
instance MakeAbstract NiceDeclaration where
mkAbstract = \case
NiceMutual r termCheck cc pc ds -> NiceMutual r termCheck cc pc <$> mkAbstract ds
FunDef r ds a i tc cc x cs -> (\ a -> FunDef r ds a i tc cc x) <$> mkAbstract a <*> mkAbstract cs
NiceDataDef r o a pc uc x ps cs -> (\ a -> NiceDataDef r o a pc uc x ps) <$> mkAbstract a <*> mkAbstract cs
NiceRecDef r o a pc uc x i e c ps cs -> (\ a -> NiceRecDef r o a pc uc x i e c ps) <$> mkAbstract a <*> return cs
NiceFunClause r p a tc cc catchall d -> (\ a -> NiceFunClause r p a tc cc catchall d) <$> mkAbstract a
-- The following declarations have an @InAbstract@ field
-- but are not really definitions, so we do count them into
-- the declarations which can be made abstract
( thus , do not notify progress with @dirty@ ) .
Axiom r p a i rel x e -> return $ Axiom r p AbstractDef i rel x e
FunSig r p a i m rel tc cc x e -> return $ FunSig r p AbstractDef i m rel tc cc x e
NiceRecSig r p a pc uc x ls t -> return $ NiceRecSig r p AbstractDef pc uc x ls t
NiceDataSig r p a pc uc x ls t -> return $ NiceDataSig r p AbstractDef pc uc x ls t
NiceField r p _ i tac x e -> return $ NiceField r p AbstractDef i tac x e
PrimitiveFunction r p _ x e -> return $ PrimitiveFunction r p AbstractDef x e
, 2016 - 07 - 17 it does have effect on unquoted defs .
-- Need to set updater state to dirty!
NiceUnquoteDecl r p _ i tc cc x e -> tellDirty $> NiceUnquoteDecl r p AbstractDef i tc cc x e
NiceUnquoteDef r p _ tc cc x e -> tellDirty $> NiceUnquoteDef r p AbstractDef tc cc x e
d@NiceModule{} -> return d
d@NiceModuleMacro{} -> return d
d@NicePragma{} -> return d
d@(NiceOpen _ _ directives) -> do
whenJust (publicOpen directives) $ lift . niceWarning . OpenPublicAbstract
return d
d@NiceImport{} -> return d
d@NicePatternSyn{} -> return d
d@NiceGeneralize{} -> return d
instance MakeAbstract Clause where
mkAbstract (Clause x catchall lhs rhs wh with) = do
Clause x catchall lhs rhs <$> mkAbstract wh <*> mkAbstract with
-- | Contents of a @where@ clause are abstract if the parent is.
instance MakeAbstract WhereClause where
mkAbstract NoWhere = return $ NoWhere
mkAbstract (AnyWhere ds) = dirty $ AnyWhere [Abstract noRange ds]
mkAbstract (SomeWhere m a ds) = dirty $ SomeWhere m a [Abstract noRange ds]
-- | Make a declaration private.
--
, 2012 - 11 - 17 :
-- Mark computation as 'dirty' if there was a declaration that could be privatized.
-- If no privatization is taking place, we want to complain about 'UselessPrivate'.
--
-- Alternatively, we could only flag 'dirty' if a non-private thing was privatized.
Then , nested would sometimes also be complained about .
class MakePrivate a where
mkPrivate :: Origin -> UpdaterT Nice a
default mkPrivate :: (Traversable f, MakePrivate a', a ~ f a') => Origin -> UpdaterT Nice a
mkPrivate o = traverse $ mkPrivate o
instance MakePrivate a => MakePrivate [a] where
-- Default definition kicks in here!
-- But note that we still have to declare the instance!
Leads to overlap with ' WhereClause ' :
instance ( f , MakePrivate a ) = > MakePrivate ( f a ) where
mkPrivate = traverse mkPrivate
instance MakePrivate Access where
mkPrivate o = \case
OR ? return o
_ -> dirty $ PrivateAccess o
instance MakePrivate NiceDeclaration where
mkPrivate o = \case
Axiom r p a i rel x e -> (\ p -> Axiom r p a i rel x e) <$> mkPrivate o p
NiceField r p a i tac x e -> (\ p -> NiceField r p a i tac x e) <$> mkPrivate o p
PrimitiveFunction r p a x e -> (\ p -> PrimitiveFunction r p a x e) <$> mkPrivate o p
NiceMutual r tc cc pc ds -> (\ ds-> NiceMutual r tc cc pc ds) <$> mkPrivate o ds
NiceModule r p a x tel ds -> (\ p -> NiceModule r p a x tel ds) <$> mkPrivate o p
NiceModuleMacro r p x ma op is -> (\ p -> NiceModuleMacro r p x ma op is) <$> mkPrivate o p
FunSig r p a i m rel tc cc x e -> (\ p -> FunSig r p a i m rel tc cc x e) <$> mkPrivate o p
NiceRecSig r p a pc uc x ls t -> (\ p -> NiceRecSig r p a pc uc x ls t) <$> mkPrivate o p
NiceDataSig r p a pc uc x ls t -> (\ p -> NiceDataSig r p a pc uc x ls t) <$> mkPrivate o p
NiceFunClause r p a tc cc catchall d -> (\ p -> NiceFunClause r p a tc cc catchall d) <$> mkPrivate o p
NiceUnquoteDecl r p a i tc cc x e -> (\ p -> NiceUnquoteDecl r p a i tc cc x e) <$> mkPrivate o p
NiceUnquoteDef r p a tc cc x e -> (\ p -> NiceUnquoteDef r p a tc cc x e) <$> mkPrivate o p
NicePatternSyn r p x xs p' -> (\ p -> NicePatternSyn r p x xs p') <$> mkPrivate o p
NiceGeneralize r p i tac x t -> (\ p -> NiceGeneralize r p i tac x t) <$> mkPrivate o p
d@NicePragma{} -> return d
d@(NiceOpen _ _ directives) -> do
whenJust (publicOpen directives) $ lift . niceWarning . OpenPublicPrivate
return d
d@NiceImport{} -> return d
, 2016 - 07 - 08 , issue # 2089
-- we need to propagate 'private' to the named where modules
FunDef r ds a i tc cc x cls -> FunDef r ds a i tc cc x <$> mkPrivate o cls
d@NiceDataDef{} -> return d
d@NiceRecDef{} -> return d
instance MakePrivate Clause where
mkPrivate o (Clause x catchall lhs rhs wh with) = do
Clause x catchall lhs rhs <$> mkPrivate o wh <*> mkPrivate o with
instance MakePrivate WhereClause where
mkPrivate o NoWhere = return $ NoWhere
-- @where@-declarations are protected behind an anonymous module,
-- thus, they are effectively private by default.
mkPrivate o (AnyWhere ds) = return $ AnyWhere ds
, 2016 - 07 - 08
A @where@-module is private if the parent function is private .
-- The contents of this module are not private, unless declared so!
Thus , we do not recurse into the @ds@ ( could not anyway ) .
mkPrivate o (SomeWhere m a ds) = mkPrivate o a <&> \ a' -> SomeWhere m a' ds
The following function is ( at the time of writing ) only used three
-- times: for building Lets, and for printing error messages.
| ( Approximately ) convert a ' NiceDeclaration ' back to a list of
' Declaration 's .
notSoNiceDeclarations :: NiceDeclaration -> [Declaration]
notSoNiceDeclarations = \case
Axiom _ _ _ i rel x e -> inst i [TypeSig rel Nothing x e]
NiceField _ _ _ i tac x argt -> [FieldSig i tac x argt]
PrimitiveFunction r _ _ x e -> [Primitive r [TypeSig defaultArgInfo Nothing x e]]
NiceMutual r _ _ _ ds -> [Mutual r $ concatMap notSoNiceDeclarations ds]
NiceModule r _ _ x tel ds -> [Module r x tel ds]
NiceModuleMacro r _ x ma o dir -> [ModuleMacro r x ma o dir]
NiceOpen r x dir -> [Open r x dir]
NiceImport r x as o dir -> [Import r x as o dir]
NicePragma _ p -> [Pragma p]
NiceRecSig r _ _ _ _ x bs e -> [RecordSig r x bs e]
NiceDataSig r _ _ _ _ x bs e -> [DataSig r x bs e]
NiceFunClause _ _ _ _ _ _ d -> [d]
FunSig _ _ _ i _ rel _ _ x e -> inst i [TypeSig rel Nothing x e]
FunDef _ ds _ _ _ _ _ _ -> ds
NiceDataDef r _ _ _ _ x bs cs -> [DataDef r x bs $ concatMap notSoNiceDeclarations cs]
NiceRecDef r _ _ _ _ x i e c bs ds -> [RecordDef r x i e c bs ds]
NicePatternSyn r _ n as p -> [PatternSyn r n as p]
NiceGeneralize r _ i tac n e -> [Generalize r [TypeSig i tac n e]]
NiceUnquoteDecl r _ _ i _ _ x e -> inst i [UnquoteDecl r x e]
NiceUnquoteDef r _ _ _ _ x e -> [UnquoteDef r x e]
where
inst (InstanceDef r) ds = [InstanceB r ds]
inst NotInstanceDef ds = ds
| Has the ' NiceDeclaration ' a field of type ' IsAbstract ' ?
niceHasAbstract :: NiceDeclaration -> Maybe IsAbstract
niceHasAbstract = \case
Axiom{} -> Nothing
NiceField _ _ a _ _ _ _ -> Just a
PrimitiveFunction _ _ a _ _ -> Just a
NiceMutual{} -> Nothing
NiceModule _ _ a _ _ _ -> Just a
NiceModuleMacro{} -> Nothing
NiceOpen{} -> Nothing
NiceImport{} -> Nothing
NicePragma{} -> Nothing
NiceRecSig{} -> Nothing
NiceDataSig{} -> Nothing
NiceFunClause _ _ a _ _ _ _ -> Just a
FunSig{} -> Nothing
FunDef _ _ a _ _ _ _ _ -> Just a
NiceDataDef _ _ a _ _ _ _ _ -> Just a
NiceRecDef _ _ a _ _ _ _ _ _ _ _ -> Just a
NicePatternSyn{} -> Nothing
NiceGeneralize{} -> Nothing
NiceUnquoteDecl _ _ a _ _ _ _ _ -> Just a
NiceUnquoteDef _ _ a _ _ _ _ -> Just a
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/Syntax/Concrete/Definitions.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE GADTs #
* Attach fixity and syntax declarations to the definition they refer to.
* Distribute the following attributes to the individual definitions:
@abstract@,
@instance@,
@postulate@,
@primitive@,
@private@,
termination pragmas.
* Expand ellipsis @...@ in function clauses following @with@.
* Infer mutual blocks.
A block starts when a lone signature is encountered, and ends when
all lone signatures have seen their definition.
* Report basic well-formedness error,
When possible, errors should be deferred to the scope checking phase
informative error messages.
instance only
-------------------------------------------------------------------------
Types
-------------------------------------------------------------------------
^ An uncategorized function clause, could be a function clause
^ Block of function clauses (we have seen the type signature before).
The 'Declaration's are the original declarations that were processed
into this 'FunDef' and are only used in 'notSoNiceDeclaration'.
An alias should know that it is an instance.
| Termination measure is, for now, a variable name.
actually declares the 'Name'. We will have to check that later.
| The exception type.
^ in a mutual block, a clause could belong to any of the @[Name]@ type signatures
Range is of mutual block.
Please keep in alphabetical order.
^ Empty @abstract@ block.
^ Empty @field@ block.
^ Empty @variable@ block.
^ Empty @instance@ block
^ Empty @macro@ block.
^ Empty @mutual@ block.
^ Empty @postulate@ block.
^ Empty @private@ block.
^ Empty @primitive@ block.
that does not precede a function clause.
that does not apply to any data or record type.
that does not apply to a data or record type.
that does not apply to any function.
^ Declarations (e.g. type signatures) without a definition.
^ @private@ has no effect on @open public@. (But the user might think so.)
^ Pragma @{-\# NO_TERMINATION_CHECK \#-}@ has been replaced
\ # TERMINATING \#
\ # NON_TERMINATING \#
^ @COMPILE@ pragmas are not allowed in safe mode
^ @abstract@ block with nothing that can (newly) be made abstract.
^ @instance@ block with nothing that can (newly) become an instance.
^ @private@ block with nothing that can (newly) be made private.
Please keep in alphabetical order.
safe@ mode .
Please keep in alphabetical order.
not safe
really safe?
not safe
not safe
| Several declarations expect only type signatures as sub-declarations. These are:
^ @postulate@
^ @primitive@. Ensured by parser.
^ @instance@. Actually, here all kinds of sub-declarations are allowed a priori.
^ @field@. Ensured by parser.
These error messages can (should) be terminated by a dot ".",
there is no error context printed after them.
-------------------------------------------------------------------------
The niceifier
-------------------------------------------------------------------------
^ we are nicifying a mutual block
^ we are nicifying decls not in a mutual block
| The kind of the forward declaration.
^ Name of a data type
^ Name of a record type
^ Name of a function.
Ignore pragmas when checking equality
| Check that declarations in a mutual block are consistently
equipped with MEASURE pragmas, or whether there is a
NO_TERMINATION_CHECK pragma.
| Nicifier monad.
Preserve the state when throwing an exception.
| Run a Nicifier computation, return result and warnings
(in chronological order).
| Nicifier state.
^ Lone type signatures that wait for their definition.
^ Termination checking pragma waiting for a definition.
^ Positivity checking pragma waiting for a definition.
^ Catchall pragma waiting for a function clause.
^ Coverage pragma waiting for a definition.
^ Stack of warnings. Head is last warning.
^ We retain the 'Name' also in the codomain since
'Name' as a key is up to @Eq Name@ which ignores the range.
However, without range names are not unique in case the
This causes then problems in 'replaceSigs' which might
replace the wrong signature.
^ Stack of warnings. Head is last warning.
| Initial nicifier state.
* Handling the lone signatures, stored to infer mutual blocks.
| Lens for field '_loneSigs'.
| Adding a lone signature to the state.
| Remove a lone signature from the state.
| Search for forward type signature.
| Check that no lone signatures are left in the state.
| Ensure that all forward declarations have been given a definition.
| Get names of lone function signatures.
| Create a 'LoneSigs' map from an association list.
| Lens for field '_termChk'.
| Lens for field '_posChk'.
| Lens for field '_uniChk'.
| Get universe check pragma from a data/rec signature.
| Lens for field '_catchall'.
| Get current catchall pragma, and reset it for the next clause.
| Add a new warning.
^ Declarations containing them
^ In the output, everything should be defined
If declaration d of x is mentioned in the map of lone signatures then replace
it with an axiom
This could happen if the user wrote a duplicate definition.
A @replaceable@ declaration is a signature. It has a name and we can make an
@Axiom@ out of it.
grouping function clauses.
Run the nicifier in an initial environment. But keep the warnings.
Check that every signature got its definition.
Note that loneSigs is ensured to be empty.
(Important, since inferMutualBlocks also uses loneSigs state).
Restore the old state, but keep the warnings.
If we still have lone signatures without any accompanying definition,
we postulate the definition and substitute the axiom for the lone signature
We then keep processing the rest of the block
checks for this block
mutual block
leftovers
cons d = fmap $
*** (d :)
*** (id :: [NiceDeclaration] -> [NiceDeclaration])
register x as lone type signature, to recognize clauses later
for each type signature 'x' waiting for clauses, we try
if we have some clauses for 'x'
Treat it as a function clause without a type signature.
fun def without type signature is relevant
This could be a let-pattern binding. Pass it on.
Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
'universeCheckPragma' AND the one from the signature say so.
Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
'universeCheckPragma' AND the one from the signature say so.
Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
'universeCheckPragma' AND the one from the signature say so.
Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
'universeCheckPragma' AND the one from the signature say so.
The lone signatures encountered so far are not in scope
for the mutual definition
Fixity and syntax declarations and polarity pragmas have
already been processed.
We warn the user about it and then assume the function is NON_TERMINATING.
We could add a default type signature here, but at the moment we can't
infer the type of a record or datatype, so better to just fail here.
^ Construct definition.
^ Construct signature.
^ Constructor checking.
^ Data/record type name.
^ Parameters and type. If not @Nothing@ a signature is created.
^ Parameters and constructors. If not @Nothing@, a definition body is created.
and to Inserted if the she wrote a single declaration that we're
splitting up here. We distinguish these because the scoping rules for
generalizable variables differ in these cases.
| Drop type annotations and lets from bindings.
Create a function definition.
If we have with-expressions (es /= []) then the following
ellipses also get the additional patterns in p0.
We can have ellipses after a fun clause without.
They refer to the last clause that introduced new with-expressions.
Same here: If we have new with-expressions, the next ellipses will
refer to us.
Need to update the range also on the next with-patterns.
Turn function clauses into nice function clauses.
Will result in an error later.
A clause is a subclause if the number of with-patterns is
greater or equal to the current number of with-patterns plus the
number of with arguments.
for finding clauses for a type sig in mutual blocks
trace ("x = " ++ prettyShow x) $
trace ("pns = " ++ show pns) $
trace ("mFixity = " ++ show mFixity) $
trace ("couldBe since y = " ++ prettyShow y) $ True
trace ("couldBe since isSublistOf") $ True
looking for a mixfix fun.symb
also matches in case of a postfix
not a notation, not first id: give up
trace ("couldBe not (case default)") $ False
trace ("couldBe not (fun default)") $ False
| Turn an old-style mutual block into a new style mutual block
by pushing the definitions to the end.
^ Range of the whole @mutual@ block.
^ Declarations inside the block.
^ Returns a 'NiceMutual'.
Postulate the missing definitions
-- Remove the declarations that aren't allowed in old style mutual blocks
, 2013 - 11 - 23 allow postulates in mutual blocks
, 2017 - 10 - 09 , issue # 2576 , raise error about missing type signature
in ConcreteToAbstract rather than here .
NiceFunClause{} -> success
, 2018 - 05 - 11 , issue # 3052 , allow pat.syn.s in mutual blocks
NicePatternSyn{} -> success
-- Otherwise, only categorized signatures and definitions are allowed:
-- Data, Record, Fun
_ -> if (declKind d /= OtherDecl) then success
else Nothing <$ niceWarning (NotAllowedInMutual (getRange d) $ declName d)
Sort the declarations in the mutual block.
Declarations of names go to the top. (Includes module definitions.)
Definitions of names go to the bottom.
Some declarations are forbidden, as their positioning could confuse
the user.
Nested mutual blocks are not supported.
We could allow modules (top), but this is potentially confusing.
since they might refer to constructors defined in a data types
just above them.
error thrown in the type checker
Some builtins require a definition, and they affect type checking
Thus, we do not handle BUILTINs in mutual blocks (at least for now).
The REWRITE pragma behaves differently before or after the def.
and affects type checking. Thus, we refuse it here.
Compiler pragmas are not needed for type checking, thus,
can go to the bottom.
error thrown in scope checker
needs record definition
only needs name, not definition
only for printing
The attached pragmas have already been handled at this point.
-- Pull type signatures to the top
-- Push definitions to the bottom
FunDef{} -> False
NiceDataDef{} -> False
NiceRecDef{} -> False
NiceFunClause{} -> False
NicePatternSyn{} -> False
NiceUnquoteDef{} -> False
_ -> True
Compute termination checking flag for mutual block
Compute coverage checking flag for mutual block
Compute positivity checking flag for mutual block
return $ NiceMutual r tc pc $ other ++ defs
return $ NiceMutual r tc pc $ sigs ++ other
isTypeSig _ = False
compute the set difference with equality just on names
do not termination check a mutual block if any of its
block if any of its inner declarations comes with a
A mutual block cannot have a measure,
but it can skip termination check.
hack to avoid failing on inherited abstract blocks in where clauses
no change!
no change!
^ Range of @instance@ keyword.
no change!
Make a declaration eligible for instance search.
^ Range of @instance@ keyword.
^ Range of @instance@ keyword.
| Make a declaration abstract.
Mark computation as 'dirty' if there was a declaration that could be made abstract.
Alternatively, we could only flag 'dirty' if a non-abstract thing was abstracted.
Then, nested @abstract@s would sometimes also be complained about.
Default definition kicks in here!
But note that we still have to declare the instance!
mkAbstract = traverse mkAbstract
The following declarations have an @InAbstract@ field
but are not really definitions, so we do count them into
the declarations which can be made abstract
Need to set updater state to dirty!
| Contents of a @where@ clause are abstract if the parent is.
| Make a declaration private.
Mark computation as 'dirty' if there was a declaration that could be privatized.
If no privatization is taking place, we want to complain about 'UselessPrivate'.
Alternatively, we could only flag 'dirty' if a non-private thing was privatized.
Default definition kicks in here!
But note that we still have to declare the instance!
we need to propagate 'private' to the named where modules
@where@-declarations are protected behind an anonymous module,
thus, they are effectively private by default.
The contents of this module are not private, unless declared so!
times: for building Lets, and for printing error messages. | # LANGUAGE GeneralizedNewtypeDeriving #
| Preprocess ' Agda . Syntax . Concrete . Declaration 's , producing ' NiceDeclaration 's .
* Gather the function clauses belonging to one function definition .
when one of the above transformation fails .
( ConcreteToAbstract ) , where we are in the TCM and can produce more
module Agda.Syntax.Concrete.Definitions
( NiceDeclaration(..)
, NiceConstructor, NiceTypeSignature
, Clause(..)
, DeclarationException(..)
, DeclarationWarning(..), unsafeDeclarationWarning
, Nice, runNice
, niceDeclarations
, notSoNiceDeclarations
, niceHasAbstract
, Measure
, declarationWarningName
) where
import Prelude hiding (null)
import Control.Arrow ((&&&), (***), second)
import Control.Monad.Except
import Control.Monad.State
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe
import qualified Data.List as List
import qualified Data.Foldable as Fold
import Data.Traversable (Traversable, traverse)
import qualified Data.Traversable as Trav
import Data.Data (Data)
import Agda.Syntax.Concrete
import Agda.Syntax.Concrete.Pattern
import Agda.Syntax.Common hiding (TerminationCheck())
import qualified Agda.Syntax.Common as Common
import Agda.Syntax.Position
import Agda.Syntax.Notation
import Agda.Syntax.Concrete.Fixity
import Agda.Interaction.Options.Warnings
import Agda.Utils.AffineHole
import Agda.Utils.Except ( MonadError(throwError) )
import Agda.Utils.Functor
import Agda.Utils.Lens
import Agda.Utils.List (isSublistOf)
import Agda.Utils.Maybe
import Agda.Utils.Null
import qualified Agda.Utils.Pretty as Pretty
import Agda.Utils.Pretty
import Agda.Utils.Singleton
import Agda.Utils.Three
import Agda.Utils.Tuple
import Agda.Utils.Update
import Agda.Utils.Impossible
| The nice declarations . No fixity declarations and function definitions are
contained in a single constructor instead of spread out between type
signatures and clauses . The @private@ , @postulate@ , @abstract@ and @instance@
modifiers have been distributed to the individual declarations .
Observe the order of components :
Range
Fixity '
Access
IsAbstract
TerminationCheck
PositivityCheck
further attributes
( Q)Name
content ( , Declaration ... )
contained in a single constructor instead of spread out between type
signatures and clauses. The @private@, @postulate@, @abstract@ and @instance@
modifiers have been distributed to the individual declarations.
Observe the order of components:
Range
Fixity'
Access
IsAbstract
IsInstance
TerminationCheck
PositivityCheck
further attributes
(Q)Name
content (Expr, Declaration ...)
-}
data NiceDeclaration
= Axiom Range Access IsAbstract IsInstance ArgInfo Name Expr
^ ' IsAbstract ' argument : We record whether a declaration was made in an @abstract@ block .
' ArgInfo ' argument : Axioms and functions can be declared irrelevant .
( ' Hiding ' should be ' NotHidden ' . )
| NiceField Range Access IsAbstract IsInstance TacticAttribute Name (Arg Expr)
| PrimitiveFunction Range Access IsAbstract Name Expr
| NiceMutual Range TerminationCheck CoverageCheck PositivityCheck [NiceDeclaration]
| NiceModule Range Access IsAbstract QName Telescope [Declaration]
| NiceModuleMacro Range Access Name ModuleApplication OpenShortHand ImportDirective
| NiceOpen Range QName ImportDirective
| NiceImport Range QName (Maybe AsName) OpenShortHand ImportDirective
| NicePragma Range Pragma
| NiceRecSig Range Access IsAbstract PositivityCheck UniverseCheck Name [LamBinding] Expr
| NiceDataSig Range Access IsAbstract PositivityCheck UniverseCheck Name [LamBinding] Expr
| NiceFunClause Range Access IsAbstract TerminationCheck CoverageCheck Catchall Declaration
without type signature or a pattern lhs ( e.g. for irrefutable let ) .
The ' Declaration ' is the actual ' FunClause ' .
| FunSig Range Access IsAbstract IsInstance IsMacro ArgInfo TerminationCheck CoverageCheck Name Expr
| FunDef Range [Declaration] IsAbstract IsInstance TerminationCheck CoverageCheck Name [Clause]
, 2017 - 01 - 01 : Because of issue # 2372 , we add ' ' here .
| NiceDataDef Range Origin IsAbstract PositivityCheck UniverseCheck Name [LamBinding] [NiceConstructor]
| NiceRecDef Range Origin IsAbstract PositivityCheck UniverseCheck Name (Maybe (Ranged Induction)) (Maybe HasEta)
(Maybe (Name, IsInstance)) [LamBinding] [Declaration]
| NicePatternSyn Range Access Name [Arg Name] Pattern
| NiceGeneralize Range Access ArgInfo TacticAttribute Name Expr
| NiceUnquoteDecl Range Access IsAbstract IsInstance TerminationCheck CoverageCheck [Name] Expr
| NiceUnquoteDef Range Access IsAbstract TerminationCheck CoverageCheck [Name] Expr
deriving (Data, Show)
type TerminationCheck = Common.TerminationCheck Measure
type Measure = Name
type Catchall = Bool
| Only ' Axiom 's .
type NiceConstructor = NiceTypeSignature
| Only ' Axiom 's .
type NiceTypeSignature = NiceDeclaration
| One clause in a function definition . There is no guarantee that the ' LHS '
data Clause = Clause Name Catchall LHS RHS WhereClause [Clause]
deriving (Data, Show)
data DeclarationException
= MultipleEllipses Pattern
| InvalidName Name
| DuplicateDefinition Name
| MissingWithClauses Name LHS
| WrongDefinition Name DataRecOrFun DataRecOrFun
| DeclarationPanic String
| WrongContentBlock KindOfBlock Range
| InvalidMeasureMutual Range
^ In a mutual block , all or none need a MEASURE pragma .
| UnquoteDefRequiresSignature [Name]
| BadMacroDef NiceDeclaration
deriving (Data, Show)
| Non - fatal errors encountered in the Nicifier .
data DeclarationWarning
| InvalidCatchallPragma Range
^ A { -\ # CATCHALL \#- } pragma
| InvalidCoverageCheckPragma Range
^ A { -\ # NON_COVERING \#- } pragma that does not apply to any function .
| InvalidNoPositivityCheckPragma Range
^ A { -\ # NO_POSITIVITY_CHECK \#- } pragma
| InvalidNoUniverseCheckPragma Range
^ A { -\ # NO_UNIVERSE_CHECK \#- } pragma
| InvalidTerminationCheckPragma Range
^ A { -\ # TERMINATING \#- } and { -\ # NON_TERMINATING \#- } pragma
| MissingDefinitions [(Name, Range)]
| NotAllowedInMutual Range String
| OpenPublicPrivate Range
| OpenPublicAbstract Range
^ @abstract@ has no effect on @open public@. ( But the user might think so . )
| PolarityPragmasButNotPostulates [Name]
| PragmaNoTerminationCheck Range
| PragmaCompiled Range
| ShadowingInTelescope [(Name, [Range])]
| UnknownFixityInMixfixDecl [Name]
| UnknownNamesInFixityDecl [Name]
| UnknownNamesInPolarityPragmas [Name]
| UselessAbstract Range
| UselessInstance Range
| UselessPrivate Range
deriving (Data, Show)
declarationWarningName :: DeclarationWarning -> WarningName
declarationWarningName = \case
EmptyAbstract{} -> EmptyAbstract_
EmptyField{} -> EmptyField_
EmptyGeneralize{} -> EmptyGeneralize_
EmptyInstance{} -> EmptyInstance_
EmptyMacro{} -> EmptyMacro_
EmptyMutual{} -> EmptyMutual_
EmptyPrivate{} -> EmptyPrivate_
EmptyPostulate{} -> EmptyPostulate_
EmptyPrimitive{} -> EmptyPrimitive_
InvalidCatchallPragma{} -> InvalidCatchallPragma_
InvalidNoPositivityCheckPragma{} -> InvalidNoPositivityCheckPragma_
InvalidNoUniverseCheckPragma{} -> InvalidNoUniverseCheckPragma_
InvalidTerminationCheckPragma{} -> InvalidTerminationCheckPragma_
InvalidCoverageCheckPragma{} -> InvalidCoverageCheckPragma_
MissingDefinitions{} -> MissingDefinitions_
NotAllowedInMutual{} -> NotAllowedInMutual_
OpenPublicPrivate{} -> OpenPublicPrivate_
OpenPublicAbstract{} -> OpenPublicAbstract_
PolarityPragmasButNotPostulates{} -> PolarityPragmasButNotPostulates_
PragmaNoTerminationCheck{} -> PragmaNoTerminationCheck_
PragmaCompiled{} -> PragmaCompiled_
ShadowingInTelescope{} -> ShadowingInTelescope_
UnknownFixityInMixfixDecl{} -> UnknownFixityInMixfixDecl_
UnknownNamesInFixityDecl{} -> UnknownNamesInFixityDecl_
UnknownNamesInPolarityPragmas{} -> UnknownNamesInPolarityPragmas_
UselessAbstract{} -> UselessAbstract_
UselessInstance{} -> UselessInstance_
UselessPrivate{} -> UselessPrivate_
unsafeDeclarationWarning :: DeclarationWarning -> Bool
unsafeDeclarationWarning = \case
EmptyAbstract{} -> False
EmptyField{} -> False
EmptyGeneralize{} -> False
EmptyInstance{} -> False
EmptyMacro{} -> False
EmptyMutual{} -> False
EmptyPrivate{} -> False
EmptyPostulate{} -> False
EmptyPrimitive{} -> False
InvalidCatchallPragma{} -> False
InvalidNoPositivityCheckPragma{} -> False
InvalidNoUniverseCheckPragma{} -> False
InvalidTerminationCheckPragma{} -> False
InvalidCoverageCheckPragma{} -> False
OpenPublicPrivate{} -> False
OpenPublicAbstract{} -> False
PolarityPragmasButNotPostulates{} -> False
ShadowingInTelescope{} -> False
UnknownFixityInMixfixDecl{} -> False
UnknownNamesInFixityDecl{} -> False
UnknownNamesInPolarityPragmas{} -> False
UselessAbstract{} -> False
UselessInstance{} -> False
UselessPrivate{} -> False
data KindOfBlock
^ @data ... where@. Here we got a bad error message for Agda-2.5 ( Issue 1698 ) .
deriving (Data, Eq, Ord, Show)
instance HasRange DeclarationException where
getRange (MultipleEllipses d) = getRange d
getRange (InvalidName x) = getRange x
getRange (DuplicateDefinition x) = getRange x
getRange (MissingWithClauses x lhs) = getRange lhs
getRange (WrongDefinition x k k') = getRange x
getRange (AmbiguousFunClauses lhs xs) = getRange lhs
getRange (DeclarationPanic _) = noRange
getRange (WrongContentBlock _ r) = r
getRange (InvalidMeasureMutual r) = r
getRange (UnquoteDefRequiresSignature x) = getRange x
getRange (BadMacroDef d) = getRange d
instance HasRange DeclarationWarning where
getRange (UnknownNamesInFixityDecl xs) = getRange xs
getRange (UnknownFixityInMixfixDecl xs) = getRange xs
getRange (UnknownNamesInPolarityPragmas xs) = getRange xs
getRange (PolarityPragmasButNotPostulates xs) = getRange xs
getRange (MissingDefinitions xs) = getRange xs
getRange (UselessPrivate r) = r
getRange (NotAllowedInMutual r x) = r
getRange (UselessAbstract r) = r
getRange (UselessInstance r) = r
getRange (EmptyMutual r) = r
getRange (EmptyAbstract r) = r
getRange (EmptyPrivate r) = r
getRange (EmptyInstance r) = r
getRange (EmptyMacro r) = r
getRange (EmptyPostulate r) = r
getRange (EmptyGeneralize r) = r
getRange (EmptyPrimitive r) = r
getRange (EmptyField r) = r
getRange (InvalidTerminationCheckPragma r) = r
getRange (InvalidCoverageCheckPragma r) = r
getRange (InvalidNoPositivityCheckPragma r) = r
getRange (InvalidCatchallPragma r) = r
getRange (InvalidNoUniverseCheckPragma r) = r
getRange (PragmaNoTerminationCheck r) = r
getRange (PragmaCompiled r) = r
getRange (OpenPublicAbstract r) = r
getRange (OpenPublicPrivate r) = r
getRange (ShadowingInTelescope ns) = getRange ns
instance HasRange NiceDeclaration where
getRange (Axiom r _ _ _ _ _ _) = r
getRange (NiceField r _ _ _ _ _ _) = r
getRange (NiceMutual r _ _ _ _) = r
getRange (NiceModule r _ _ _ _ _ ) = r
getRange (NiceModuleMacro r _ _ _ _ _) = r
getRange (NiceOpen r _ _) = r
getRange (NiceImport r _ _ _ _) = r
getRange (NicePragma r _) = r
getRange (PrimitiveFunction r _ _ _ _) = r
getRange (FunSig r _ _ _ _ _ _ _ _ _) = r
getRange (FunDef r _ _ _ _ _ _ _) = r
getRange (NiceDataDef r _ _ _ _ _ _ _) = r
getRange (NiceRecDef r _ _ _ _ _ _ _ _ _ _) = r
getRange (NiceRecSig r _ _ _ _ _ _ _) = r
getRange (NiceDataSig r _ _ _ _ _ _ _) = r
getRange (NicePatternSyn r _ _ _ _) = r
getRange (NiceGeneralize r _ _ _ _ _) = r
getRange (NiceFunClause r _ _ _ _ _ _) = r
getRange (NiceUnquoteDecl r _ _ _ _ _ _ _) = r
getRange (NiceUnquoteDef r _ _ _ _ _ _) = r
instance Pretty NiceDeclaration where
pretty = \case
Axiom _ _ _ _ _ x _ -> text "postulate" <+> pretty x <+> colon <+> text "_"
NiceField _ _ _ _ _ x _ -> text "field" <+> pretty x
PrimitiveFunction _ _ _ x _ -> text "primitive" <+> pretty x
NiceMutual{} -> text "mutual"
NiceModule _ _ _ x _ _ -> text "module" <+> pretty x <+> text "where"
NiceModuleMacro _ _ x _ _ _ -> text "module" <+> pretty x <+> text "= ..."
NiceOpen _ x _ -> text "open" <+> pretty x
NiceImport _ x _ _ _ -> text "import" <+> pretty x
NicePragma{} -> text "{-# ... #-}"
NiceRecSig _ _ _ _ _ x _ _ -> text "record" <+> pretty x
NiceDataSig _ _ _ _ _ x _ _ -> text "data" <+> pretty x
NiceFunClause{} -> text "<function clause>"
FunSig _ _ _ _ _ _ _ _ x _ -> pretty x <+> colon <+> text "_"
FunDef _ _ _ _ _ _ x _ -> pretty x <+> text "= _"
NiceDataDef _ _ _ _ _ x _ _ -> text "data" <+> pretty x <+> text "where"
NiceRecDef _ _ _ _ _ x _ _ _ _ _ -> text "record" <+> pretty x <+> text "where"
NicePatternSyn _ _ x _ _ -> text "pattern" <+> pretty x
NiceGeneralize _ _ _ _ x _ -> text "variable" <+> pretty x
NiceUnquoteDecl _ _ _ _ _ _ xs _ -> text "<unquote declarations>"
NiceUnquoteDef _ _ _ _ _ xs _ -> text "<unquote definitions>"
instance Pretty DeclarationException where
pretty (MultipleEllipses p) = fsep $
pwords "Multiple ellipses in left-hand side" ++ [pretty p]
pretty (InvalidName x) = fsep $
pwords "Invalid name:" ++ [pretty x]
pretty (DuplicateDefinition x) = fsep $
pwords "Duplicate definition of" ++ [pretty x]
pretty (MissingWithClauses x lhs) = fsep $
pwords "Missing with-clauses for function" ++ [pretty x]
pretty (WrongDefinition x k k') = fsep $ pretty x :
pwords ("has been declared as a " ++ show k ++
", but is being defined as a " ++ show k')
pretty (AmbiguousFunClauses lhs xs) = sep
[ fsep $
pwords "More than one matching type signature for left hand side " ++ [pretty lhs] ++
pwords "it could belong to any of:"
, vcat $ map (pretty . PrintRange) xs
]
pretty (WrongContentBlock b _) = fsep . pwords $
case b of
PostulateBlock -> "A postulate block can only contain type signatures, possibly under keyword instance"
DataBlock -> "A data definition can only contain type signatures, possibly under keyword instance"
_ -> "Unexpected declaration"
pretty (InvalidMeasureMutual _) = fsep $
pwords "In a mutual block, either all functions must have the same (or no) termination checking pragma."
pretty (UnquoteDefRequiresSignature xs) = fsep $
pwords "Missing type signatures for unquoteDef" ++ map pretty xs
pretty (BadMacroDef nd) = fsep $
[text $ declName nd] ++ pwords "are not allowed in macro blocks"
pretty (DeclarationPanic s) = text s
instance Pretty DeclarationWarning where
pretty (UnknownNamesInFixityDecl xs) = fsep $
pwords "The following names are not declared in the same scope as their syntax or fixity declaration (i.e., either not in scope at all, imported from another module, or declared in a super module):"
++ punctuate comma (map pretty xs)
pretty (UnknownFixityInMixfixDecl xs) = fsep $
pwords "The following mixfix names do not have an associated fixity declaration:"
++ punctuate comma (map pretty xs)
pretty (UnknownNamesInPolarityPragmas xs) = fsep $
pwords "The following names are not declared in the same scope as their polarity pragmas (they could for instance be out of scope, imported from another module, or declared in a super module):"
++ punctuate comma (map pretty xs)
pretty (MissingDefinitions xs) = fsep $
pwords "The following names are declared but not accompanied by a definition:"
++ punctuate comma (map (pretty . fst) xs)
pretty (NotAllowedInMutual r nd) = fsep $
[text nd] ++ pwords "in mutual blocks are not supported. Suggestion: get rid of the mutual block by manually ordering declarations"
pretty (PolarityPragmasButNotPostulates xs) = fsep $
pwords "Polarity pragmas have been given for the following identifiers which are not postulates:"
++ punctuate comma (map pretty xs)
pretty (UselessPrivate _) = fsep $
pwords "Using private here has no effect. Private applies only to declarations that introduce new identifiers into the module, like type signatures and data, record, and module declarations."
pretty (UselessAbstract _) = fsep $
pwords "Using abstract here has no effect. Abstract applies to only definitions like data definitions, record type definitions and function clauses."
pretty (UselessInstance _) = fsep $
pwords "Using instance here has no effect. Instance applies only to declarations that introduce new identifiers into the module, like type signatures and axioms."
pretty (EmptyMutual _) = fsep $ pwords "Empty mutual block."
pretty (EmptyAbstract _) = fsep $ pwords "Empty abstract block."
pretty (EmptyPrivate _) = fsep $ pwords "Empty private block."
pretty (EmptyInstance _) = fsep $ pwords "Empty instance block."
pretty (EmptyMacro _) = fsep $ pwords "Empty macro block."
pretty (EmptyPostulate _) = fsep $ pwords "Empty postulate block."
pretty (EmptyGeneralize _) = fsep $ pwords "Empty variable block."
pretty (EmptyPrimitive _) = fsep $ pwords "Empty primitive block."
pretty (EmptyField _) = fsep $ pwords "Empty field block."
pretty (InvalidTerminationCheckPragma _) = fsep $
pwords "Termination checking pragmas can only precede a function definition or a mutual block (that contains a function definition)."
pretty (InvalidCoverageCheckPragma _) = fsep $
pwords "Coverage checking pragmas can only precede a function definition or a mutual block (that contains a function definition)."
pretty (InvalidNoPositivityCheckPragma _) = fsep $
pwords "NO_POSITIVITY_CHECKING pragmas can only precede a data/record definition or a mutual block (that contains a data/record definition)."
pretty (InvalidCatchallPragma _) = fsep $
pwords "The CATCHALL pragma can only precede a function clause."
pretty (InvalidNoUniverseCheckPragma _) = fsep $
pwords "NO_UNIVERSE_CHECKING pragmas can only precede a data/record definition."
pretty (PragmaNoTerminationCheck _) = fsep $
pwords "Pragma {-# NO_TERMINATION_CHECK #-} has been removed. To skip the termination check, label your definitions either as {-# TERMINATING #-} or {-# NON_TERMINATING #-}."
pretty (PragmaCompiled _) = fsep $
pwords "COMPILE pragma not allowed in safe mode."
pretty (OpenPublicAbstract _) = fsep $
pwords "public does not have any effect in an abstract block."
pretty (OpenPublicPrivate _) = fsep $
pwords "public does not have any effect in a private block."
pretty (ShadowingInTelescope nrs) = fsep $
pwords "Shadowing in telescope, repeated variable names:"
++ punctuate comma (map (pretty . fst) nrs)
declName :: NiceDeclaration -> String
declName Axiom{} = "Postulates"
declName NiceField{} = "Fields"
declName NiceMutual{} = "Mutual blocks"
declName NiceModule{} = "Modules"
declName NiceModuleMacro{} = "Modules"
declName NiceOpen{} = "Open declarations"
declName NiceImport{} = "Import statements"
declName NicePragma{} = "Pragmas"
declName PrimitiveFunction{} = "Primitive declarations"
declName NicePatternSyn{} = "Pattern synonyms"
declName NiceGeneralize{} = "Generalized variables"
declName NiceUnquoteDecl{} = "Unquoted declarations"
declName NiceUnquoteDef{} = "Unquoted definitions"
declName NiceRecSig{} = "Records"
declName NiceDataSig{} = "Data types"
declName NiceFunClause{} = "Functions without a type signature"
declName FunSig{} = "Type signatures"
declName FunDef{} = "Function definitions"
declName NiceRecDef{} = "Records"
declName NiceDataDef{} = "Data types"
data InMutual
deriving (Eq, Show)
data DataRecOrFun
= DataName
{ _kindPosCheck :: PositivityCheck
, _kindUniCheck :: UniverseCheck
}
| RecName
{ _kindPosCheck :: PositivityCheck
, _kindUniCheck :: UniverseCheck
}
| FunName TerminationCheck CoverageCheck
deriving Data
instance Eq DataRecOrFun where
DataName{} == DataName{} = True
RecName{} == RecName{} = True
FunName{} == FunName{} = True
_ == _ = False
instance Show DataRecOrFun where
show DataName{} = "data type"
show RecName{} = "record type"
show FunName{} = "function"
isFunName :: DataRecOrFun -> Bool
isFunName (FunName{}) = True
isFunName _ = False
sameKind :: DataRecOrFun -> DataRecOrFun -> Bool
sameKind = (==)
terminationCheck :: DataRecOrFun -> TerminationCheck
terminationCheck (FunName tc _) = tc
terminationCheck _ = TerminationCheck
coverageCheck :: DataRecOrFun -> CoverageCheck
coverageCheck (FunName _ cc) = cc
coverageCheck _ = YesCoverageCheck
positivityCheck :: DataRecOrFun -> PositivityCheck
positivityCheck (DataName pc _) = pc
positivityCheck (RecName pc _) = pc
positivityCheck _ = YesPositivityCheck
universeCheck :: DataRecOrFun -> UniverseCheck
universeCheck (DataName _ uc) = uc
universeCheck (RecName _ uc) = uc
universeCheck _ = YesUniverseCheck
combineTerminationChecks :: Range -> [TerminationCheck] -> Nice TerminationCheck
combineTerminationChecks r tcs = loop tcs where
loop :: [TerminationCheck] -> Nice TerminationCheck
loop [] = return TerminationCheck
loop (tc : tcs) = do
let failure r = throwError $ InvalidMeasureMutual r
tc' <- loop tcs
case (tc, tc') of
(TerminationCheck , tc' ) -> return tc'
(tc , TerminationCheck ) -> return tc
(NonTerminating , NonTerminating ) -> return NonTerminating
(NoTerminationCheck , NoTerminationCheck ) -> return NoTerminationCheck
(NoTerminationCheck , Terminating ) -> return Terminating
(Terminating , NoTerminationCheck ) -> return Terminating
(Terminating , Terminating ) -> return Terminating
(TerminationMeasure{} , TerminationMeasure{} ) -> return tc
(TerminationMeasure r _, NoTerminationCheck ) -> failure r
(TerminationMeasure r _, Terminating ) -> failure r
(NoTerminationCheck , TerminationMeasure r _) -> failure r
(Terminating , TerminationMeasure r _) -> failure r
(TerminationMeasure r _, NonTerminating ) -> failure r
(NonTerminating , TerminationMeasure r _) -> failure r
(NoTerminationCheck , NonTerminating ) -> failure r
(Terminating , NonTerminating ) -> failure r
(NonTerminating , NoTerminationCheck ) -> failure r
(NonTerminating , Terminating ) -> failure r
combineCoverageChecks :: [CoverageCheck] -> CoverageCheck
combineCoverageChecks = Fold.fold
combinePositivityChecks :: [PositivityCheck] -> PositivityCheck
combinePositivityChecks = Fold.fold
newtype Nice a = Nice { unNice :: ExceptT DeclarationException (State NiceEnv) a }
deriving ( Functor, Applicative, Monad
, MonadState NiceEnv, MonadError DeclarationException
)
runNice :: Nice a -> (Either DeclarationException a, NiceWarnings)
runNice m = second (reverse . niceWarn) $
runExceptT (unNice m) `runState` initNiceEnv
data NiceEnv = NiceEnv
{ _loneSigs :: LoneSigs
, _termChk :: TerminationCheck
, _posChk :: PositivityCheck
, _uniChk :: UniverseCheck
^ Universe checking pragma waiting for a data / rec signature or definition .
, _catchall :: Catchall
, _covChk :: CoverageCheck
, niceWarn :: NiceWarnings
}
data LoneSig = LoneSig
{ loneSigRange :: Range
, loneSigName :: Name
, loneSigKind :: DataRecOrFun
}
type LoneSigs = Map Name LoneSig
user gives a second definition of the same name .
type NiceWarnings = [DeclarationWarning]
initNiceEnv :: NiceEnv
initNiceEnv = NiceEnv
{ _loneSigs = empty
, _termChk = TerminationCheck
, _posChk = YesPositivityCheck
, _uniChk = YesUniverseCheck
, _catchall = False
, _covChk = YesCoverageCheck
, niceWarn = []
}
loneSigs :: Lens' LoneSigs NiceEnv
loneSigs f e = f (_loneSigs e) <&> \ s -> e { _loneSigs = s }
addLoneSig :: Range -> Name -> DataRecOrFun -> Nice ()
addLoneSig r x k = loneSigs %== \ s -> do
let (mr, s') = Map.insertLookupWithKey (\ _k new _old -> new) x (LoneSig r x k) s
case mr of
Nothing -> return s'
Just{} -> throwError $ DuplicateDefinition x
removeLoneSig :: Name -> Nice ()
removeLoneSig x = loneSigs %= Map.delete x
getSig :: Name -> Nice (Maybe DataRecOrFun)
getSig x = fmap loneSigKind . Map.lookup x <$> use loneSigs
noLoneSigs :: Nice Bool
noLoneSigs = null <$> use loneSigs
forgetLoneSigs :: Nice ()
forgetLoneSigs = loneSigs .= Map.empty
checkLoneSigs :: LoneSigs -> Nice ()
checkLoneSigs xs = do
forgetLoneSigs
unless (Map.null xs) $ niceWarning $ MissingDefinitions $
map (\s -> (loneSigName s , loneSigRange s)) $ Map.elems xs
loneFuns :: LoneSigs -> [Name]
loneFuns = map fst . filter (isFunName . loneSigKind . snd) . Map.toList
loneSigsFromLoneNames :: [(Range, Name, DataRecOrFun)] -> LoneSigs
loneSigsFromLoneNames = Map.fromList . map (\(r,x,k) -> (x, LoneSig r x k))
terminationCheckPragma :: Lens' TerminationCheck NiceEnv
terminationCheckPragma f e = f (_termChk e) <&> \ s -> e { _termChk = s }
withTerminationCheckPragma :: TerminationCheck -> Nice a -> Nice a
withTerminationCheckPragma tc f = do
tc_old <- use terminationCheckPragma
terminationCheckPragma .= tc
result <- f
terminationCheckPragma .= tc_old
return result
coverageCheckPragma :: Lens' CoverageCheck NiceEnv
coverageCheckPragma f e = f (_covChk e) <&> \ s -> e { _covChk = s }
withCoverageCheckPragma :: CoverageCheck -> Nice a -> Nice a
withCoverageCheckPragma tc f = do
tc_old <- use coverageCheckPragma
coverageCheckPragma .= tc
result <- f
coverageCheckPragma .= tc_old
return result
positivityCheckPragma :: Lens' PositivityCheck NiceEnv
positivityCheckPragma f e = f (_posChk e) <&> \ s -> e { _posChk = s }
withPositivityCheckPragma :: PositivityCheck -> Nice a -> Nice a
withPositivityCheckPragma pc f = do
pc_old <- use positivityCheckPragma
positivityCheckPragma .= pc
result <- f
positivityCheckPragma .= pc_old
return result
universeCheckPragma :: Lens' UniverseCheck NiceEnv
universeCheckPragma f e = f (_uniChk e) <&> \ s -> e { _uniChk = s }
withUniverseCheckPragma :: UniverseCheck -> Nice a -> Nice a
withUniverseCheckPragma uc f = do
uc_old <- use universeCheckPragma
universeCheckPragma .= uc
result <- f
universeCheckPragma .= uc_old
return result
Defaults to ' ' .
getUniverseCheckFromSig :: Name -> Nice UniverseCheck
getUniverseCheckFromSig x = maybe YesUniverseCheck universeCheck <$> getSig x
catchallPragma :: Lens' Catchall NiceEnv
catchallPragma f e = f (_catchall e) <&> \ s -> e { _catchall = s }
popCatchallPragma :: Nice Catchall
popCatchallPragma = do
ca <- use catchallPragma
catchallPragma .= False
return ca
withCatchallPragma :: Catchall -> Nice a -> Nice a
withCatchallPragma ca f = do
ca_old <- use catchallPragma
catchallPragma .= ca
result <- f
catchallPragma .= ca_old
return result
niceWarning :: DeclarationWarning -> Nice ()
niceWarning w = modify $ \ st -> st { niceWarn = w : niceWarn st }
data DeclKind
= LoneSigDecl Range DataRecOrFun Name
| LoneDefs DataRecOrFun [Name]
| OtherDecl
deriving (Eq, Show)
declKind :: NiceDeclaration -> DeclKind
declKind (FunSig r _ _ _ _ _ tc cc x _) = LoneSigDecl r (FunName tc cc) x
declKind (NiceRecSig r _ _ pc uc x pars _) = LoneSigDecl r (RecName pc uc) x
declKind (NiceDataSig r _ _ pc uc x pars _) = LoneSigDecl r (DataName pc uc) x
declKind (FunDef r _ abs ins tc cc x _) = LoneDefs (FunName tc cc) [x]
declKind (NiceDataDef _ _ _ pc uc x pars _) = LoneDefs (DataName pc uc) [x]
declKind (NiceRecDef _ _ _ pc uc x _ _ _ pars _)= LoneDefs (RecName pc uc) [x]
declKind (NiceUnquoteDef _ _ _ tc cc xs _) = LoneDefs (FunName tc cc) xs
declKind Axiom{} = OtherDecl
declKind NiceField{} = OtherDecl
declKind PrimitiveFunction{} = OtherDecl
declKind NiceMutual{} = OtherDecl
declKind NiceModule{} = OtherDecl
declKind NiceModuleMacro{} = OtherDecl
declKind NiceOpen{} = OtherDecl
declKind NiceImport{} = OtherDecl
declKind NicePragma{} = OtherDecl
declKind NiceFunClause{} = OtherDecl
declKind NicePatternSyn{} = OtherDecl
declKind NiceGeneralize{} = OtherDecl
declKind NiceUnquoteDecl{} = OtherDecl
| Replace ( Data / Rec / Fun)Sigs with Axioms for postulated names
The first argument is a list of axioms only .
replaceSigs
^ Lone signatures to be turned into Axioms
replaceSigs ps = if Map.null ps then id else \case
[] -> __IMPOSSIBLE__
(d:ds) ->
case replaceable d of
Just (x, axiom)
| (Just (LoneSig _ x' _), ps') <- Map.updateLookupWithKey (\ _ _ -> Nothing) x ps
, getRange x == getRange x'
Use the range as UID to ensure we do not replace the wrong signature .
-> axiom : replaceSigs ps' ds
_ -> d : replaceSigs ps ds
where
replaceable :: NiceDeclaration -> Maybe (Name, NiceDeclaration)
replaceable = \case
FunSig r acc abst inst _ argi _ _ x e ->
Just (x, Axiom r acc abst inst argi x e)
NiceRecSig r acc abst _ _ x pars t ->
let e = Generalized $ makePi (lamBindingsToTelescope r pars) t in
Just (x, Axiom r acc abst NotInstanceDef defaultArgInfo x e)
NiceDataSig r acc abst _ _ x pars t ->
let e = Generalized $ makePi (lamBindingsToTelescope r pars) t in
Just (x, Axiom r acc abst NotInstanceDef defaultArgInfo x e)
_ -> Nothing
| Main . ( or more precisely syntax declarations ) are needed when
niceDeclarations :: Fixities -> [Declaration] -> Nice [NiceDeclaration]
niceDeclarations fixs ds = do
st <- get
put $ initNiceEnv { niceWarn = niceWarn st }
nds <- nice ds
ps <- use loneSigs
checkLoneSigs ps
We postulate the missing ones and insert them in place of the corresponding
let ds = replaceSigs ps nds
res <- inferMutualBlocks ds
warns <- gets niceWarn
put $ st { niceWarn = warns }
return res
where
inferMutualBlocks :: [NiceDeclaration] -> Nice [NiceDeclaration]
inferMutualBlocks [] = return []
inferMutualBlocks (d : ds) =
case declKind d of
OtherDecl -> (d :) <$> inferMutualBlocks ds
, 2017 - 10 - 09 , issue # 2576 : report error in ConcreteToAbstract
LoneSigDecl r k x -> do
addLoneSig r x k
let tcccpc = ([terminationCheck k], [coverageCheck k], [positivityCheck k])
((tcs, ccs, pcs), (nds0, ds1)) <- untilAllDefined tcccpc ds
ps <- use loneSigs
checkLoneSigs ps
NB : do n't forget the LoneSig the block started with !
tc <- combineTerminationChecks (getRange d) tcs
let cc = combineCoverageChecks ccs
let pc = combinePositivityChecks pcs
(NiceMutual (getRange ds0) tc cc pc ds0 :) <$> inferMutualBlocks ds1
where
untilAllDefined :: ([TerminationCheck], [CoverageCheck], [PositivityCheck])
-> [NiceDeclaration]
)
untilAllDefined tcccpc@(tc, cc, pc) ds = do
done <- noLoneSigs
if done then return (tcccpc, ([], ds)) else
case ds of
[] -> return (tcccpc, ([], ds))
d : ds -> case declKind d of
LoneSigDecl r k x -> do
addLoneSig r x k
let tcccpc' = (terminationCheck k : tc, coverageCheck k : cc, positivityCheck k : pc)
cons d (untilAllDefined tcccpc' ds)
LoneDefs k xs -> do
mapM_ removeLoneSig xs
let tcccpc' = (terminationCheck k : tc, coverageCheck k : cc, positivityCheck k : pc)
cons d (untilAllDefined tcccpc' ds)
OtherDecl -> cons d (untilAllDefined tcccpc ds)
where
ASR ( 26 December 2015 ): Type annotated version of the @cons@ function .
( i d : : ( ( [ TerminationCheck ] , [ PositivityCheck ] ) - > ( [ TerminationCheck ] , [ PositivityCheck ] ) ) )
cons d = fmap (id *** (d :) *** id)
notMeasure TerminationMeasure{} = False
notMeasure _ = True
nice :: [Declaration] -> Nice [NiceDeclaration]
nice [] = return []
nice ds = do
(xs , ys) <- nice1 ds
(xs ++) <$> nice ys
nice1 :: [Declaration] -> Nice ([NiceDeclaration], [Declaration])
, 2017 - 09 - 16 , issue # 2759 : no longer _ _ IMPOSSIBLE _ _
nice1 (d:ds) = do
let justWarning w = do niceWarning w; nice1 ds
case d of
TypeSig info _tac x t -> do
termCheck <- use terminationCheckPragma
covCheck <- use coverageCheckPragma
let r = getRange d
addLoneSig r x $ FunName termCheck covCheck
return ([FunSig r PublicAccess ConcreteDef NotInstanceDef NotMacroDef info termCheck covCheck x t] , ds)
Should not show up : all FieldSig are part of a Field block
FieldSig{} -> __IMPOSSIBLE__
Generalize r [] -> justWarning $ EmptyGeneralize r
Generalize r sigs -> do
gs <- forM sigs $ \case
sig@(TypeSig info tac x t) -> do
return $ NiceGeneralize (getRange sig) PublicAccess info tac x t
_ -> __IMPOSSIBLE__
return (gs, ds)
(FunClause lhs _ _ _) -> do
termCheck <- use terminationCheckPragma
covCheck <- use coverageCheckPragma
catchall <- popCatchallPragma
xs <- loneFuns <$> use loneSigs
case [ (x, (fits, rest))
| x <- xs
, let (fits, rest) =
Anonymous declarations only have 1 clause each !
if isNoName x then ([d], ds)
else span (couldBeFunClauseOf (Map.lookup x fixs) x) (d : ds)
, not (null fits)
] of
case : clauses match none of the sigs
[] -> case lhs of
Subcase : The lhs is single identifier ( potentially anonymous ) .
LHS p [] [] _ | Just x <- isSingleIdentifierP p -> do
return (d , ds)
Subcase : The lhs is a proper pattern .
A missing type signature error might be raise in ConcreteToAbstract
_ -> do
return ([NiceFunClause (getRange d) PublicAccess ConcreteDef termCheck covCheck catchall d] , ds)
case : clauses match exactly one of the sigs
[(x,(fits,rest))] -> do
removeLoneSig x
ds <- expandEllipsis fits
cs <- mkClauses x ds False
return ([FunDef (getRange fits) fits ConcreteDef NotInstanceDef termCheck covCheck x cs] , rest)
case : clauses match more than one sigs ( ambiguity )
l -> throwError $ AmbiguousFunClauses lhs $ reverse $ map fst l
" ambiguous function clause ; can not assign it uniquely to one type signature "
Field r [] -> justWarning $ EmptyField r
Field _ fs -> (,ds) <$> niceAxioms FieldBlock fs
DataSig r x tel t -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
addLoneSig r x $ DataName pc uc
(,) <$> dataOrRec pc uc NiceDataDef NiceDataSig (niceAxioms DataBlock) r x (Just (tel, t)) Nothing
<*> return ds
Data r x tel t cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
Universe check is performed if both the current value of
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (DataName pc uc) x (Just t)
(,) <$> dataOrRec pc uc NiceDataDef NiceDataSig (niceAxioms DataBlock) r x ((tel,) <$> mt) (Just (tel, cs))
<*> return ds
DataDef r x tel cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
Universe check is performed if both the current value of
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (DataName pc uc) x Nothing
(,) <$> dataOrRec pc uc NiceDataDef NiceDataSig (niceAxioms DataBlock) r x ((tel,) <$> mt) (Just (tel, cs))
<*> return ds
RecordSig r x tel t -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
addLoneSig r x $ RecName pc uc
return ([NiceRecSig r PublicAccess ConcreteDef pc uc x tel t] , ds)
Record r x i e c tel t cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
Universe check is performed if both the current value of
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (RecName pc uc) x (Just t)
(,) <$> dataOrRec pc uc (\ r o a pc uc x tel cs -> NiceRecDef r o a pc uc x i e c tel cs) NiceRecSig
return r x ((tel,) <$> mt) (Just (tel, cs))
<*> return ds
RecordDef r x i e c tel cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
Universe check is performed if both the current value of
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (RecName pc uc) x Nothing
(,) <$> dataOrRec pc uc (\ r o a pc uc x tel cs -> NiceRecDef r o a pc uc x i e c tel cs) NiceRecSig
return r x ((tel,) <$> mt) (Just (tel, cs))
<*> return ds
Mutual r ds' -> do
forgetLoneSigs
case ds' of
[] -> justWarning $ EmptyMutual r
_ -> (,ds) <$> (singleton <$> (mkOldMutual r =<< nice ds'))
Abstract r [] -> justWarning $ EmptyAbstract r
Abstract r ds' ->
(,ds) <$> (abstractBlock r =<< nice ds')
Private r UserWritten [] -> justWarning $ EmptyPrivate r
Private r o ds' ->
(,ds) <$> (privateBlock r o =<< nice ds')
InstanceB r [] -> justWarning $ EmptyInstance r
InstanceB r ds' ->
(,ds) <$> (instanceBlock r =<< nice ds')
Macro r [] -> justWarning $ EmptyMacro r
Macro r ds' ->
(,ds) <$> (macroBlock r =<< nice ds')
Postulate r [] -> justWarning $ EmptyPostulate r
Postulate _ ds' ->
(,ds) <$> niceAxioms PostulateBlock ds'
Primitive r [] -> justWarning $ EmptyPrimitive r
Primitive _ ds' -> (,ds) <$> (map toPrim <$> niceAxioms PrimitiveBlock ds')
Module r x tel ds' -> return $
([NiceModule r PublicAccess ConcreteDef x tel ds'] , ds)
ModuleMacro r x modapp op is -> return $
([NiceModuleMacro r PublicAccess x modapp op is] , ds)
Infix _ _ -> return ([], ds)
Syntax _ _ -> return ([], ds)
PatternSyn r n as p -> do
return ([NicePatternSyn r PublicAccess n as p] , ds)
Open r x is -> return ([NiceOpen r x is] , ds)
Import r x as op is -> return ([NiceImport r x as op is] , ds)
UnquoteDecl r xs e -> do
tc <- use terminationCheckPragma
cc <- use coverageCheckPragma
return ([NiceUnquoteDecl r PublicAccess ConcreteDef NotInstanceDef tc cc xs e] , ds)
UnquoteDef r xs e -> do
sigs <- loneFuns <$> use loneSigs
let missing = filter (`notElem` sigs) xs
if null missing
then do
mapM_ removeLoneSig xs
return ([NiceUnquoteDef r PublicAccess ConcreteDef TerminationCheck YesCoverageCheck xs e] , ds)
else throwError $ UnquoteDefRequiresSignature missing
Pragma p -> nicePragma p ds
nicePragma :: Pragma -> [Declaration] -> Nice ([NiceDeclaration], [Declaration])
nicePragma (TerminationCheckPragma r (TerminationMeasure _ x)) ds =
if canHaveTerminationMeasure ds then
withTerminationCheckPragma (TerminationMeasure r x) $ nice1 ds
else do
niceWarning $ InvalidTerminationCheckPragma r
nice1 ds
nicePragma (TerminationCheckPragma r NoTerminationCheck) ds = do
This PRAGMA has been deprecated in favour of ( NON_)TERMINATING
niceWarning $ PragmaNoTerminationCheck r
nicePragma (TerminationCheckPragma r NonTerminating) ds
nicePragma (TerminationCheckPragma r tc) ds =
if canHaveTerminationCheckPragma ds then
withTerminationCheckPragma tc $ nice1 ds
else do
niceWarning $ InvalidTerminationCheckPragma r
nice1 ds
nicePragma (NoCoverageCheckPragma r) ds =
if canHaveCoverageCheckPragma ds then
withCoverageCheckPragma NoCoverageCheck $ nice1 ds
else do
niceWarning $ InvalidCoverageCheckPragma r
nice1 ds
nicePragma (CatchallPragma r) ds =
if canHaveCatchallPragma ds then
withCatchallPragma True $ nice1 ds
else do
niceWarning $ InvalidCatchallPragma r
nice1 ds
nicePragma (NoPositivityCheckPragma r) ds =
if canHaveNoPositivityCheckPragma ds then
withPositivityCheckPragma NoPositivityCheck $ nice1 ds
else do
niceWarning $ InvalidNoPositivityCheckPragma r
nice1 ds
nicePragma (NoUniverseCheckPragma r) ds =
if canHaveNoUniverseCheckPragma ds then
withUniverseCheckPragma NoUniverseCheck $ nice1 ds
else do
niceWarning $ InvalidNoUniverseCheckPragma r
nice1 ds
nicePragma p@CompilePragma{} ds = do
niceWarning $ PragmaCompiled (getRange p)
return ([NicePragma (getRange p) p], ds)
nicePragma (PolarityPragma{}) ds = return ([], ds)
nicePragma (BuiltinPragma r str qn@(QName x)) ds = do
return ([NicePragma r (BuiltinPragma r str qn)], ds)
nicePragma p ds = return ([NicePragma (getRange p) p], ds)
canHaveTerminationMeasure :: [Declaration] -> Bool
canHaveTerminationMeasure [] = False
canHaveTerminationMeasure (d:ds) = case d of
TypeSig{} -> True
(Pragma p) | isAttachedPragma p -> canHaveTerminationMeasure ds
_ -> False
canHaveTerminationCheckPragma :: [Declaration] -> Bool
canHaveTerminationCheckPragma [] = False
canHaveTerminationCheckPragma (d:ds) = case d of
Mutual _ ds -> any (canHaveTerminationCheckPragma . singleton) ds
TypeSig{} -> True
FunClause{} -> True
UnquoteDecl{} -> True
(Pragma p) | isAttachedPragma p -> canHaveTerminationCheckPragma ds
_ -> False
canHaveCoverageCheckPragma :: [Declaration] -> Bool
canHaveCoverageCheckPragma = canHaveTerminationCheckPragma
canHaveCatchallPragma :: [Declaration] -> Bool
canHaveCatchallPragma [] = False
canHaveCatchallPragma (d:ds) = case d of
FunClause{} -> True
(Pragma p) | isAttachedPragma p -> canHaveCatchallPragma ds
_ -> False
canHaveNoPositivityCheckPragma :: [Declaration] -> Bool
canHaveNoPositivityCheckPragma [] = False
canHaveNoPositivityCheckPragma (d:ds) = case d of
Mutual _ ds -> any (canHaveNoPositivityCheckPragma . singleton) ds
Data{} -> True
DataSig{} -> True
DataDef{} -> True
Record{} -> True
RecordSig{} -> True
RecordDef{} -> True
Pragma p | isAttachedPragma p -> canHaveNoPositivityCheckPragma ds
_ -> False
canHaveNoUniverseCheckPragma :: [Declaration] -> Bool
canHaveNoUniverseCheckPragma [] = False
canHaveNoUniverseCheckPragma (d:ds) = case d of
Data{} -> True
DataSig{} -> True
DataDef{} -> True
Record{} -> True
RecordSig{} -> True
RecordDef{} -> True
Pragma p | isAttachedPragma p -> canHaveNoPositivityCheckPragma ds
_ -> False
Pragma that attaches to the following declaration .
isAttachedPragma :: Pragma -> Bool
isAttachedPragma p = case p of
TerminationCheckPragma{} -> True
CatchallPragma{} -> True
NoPositivityCheckPragma{} -> True
NoUniverseCheckPragma{} -> True
_ -> False
defaultTypeSig :: DataRecOrFun -> Name -> Maybe Expr -> Nice (Maybe Expr)
defaultTypeSig k x t@Just{} = return t
defaultTypeSig k x Nothing = do
caseMaybeM (getSig x) (return Nothing) $ \ k' -> do
unless (sameKind k k') $ throwError $ WrongDefinition x k' k
Nothing <$ removeLoneSig x
dataOrRec
:: forall a decl
. PositivityCheck
-> UniverseCheck
-> (Range -> Origin -> IsAbstract -> PositivityCheck -> UniverseCheck -> Name -> [LamBinding] -> [decl] -> NiceDeclaration)
-> (Range -> Access -> IsAbstract -> PositivityCheck -> UniverseCheck -> Name -> [LamBinding] -> Expr -> NiceDeclaration)
-> ([a] -> Nice [decl])
-> Range
-> Nice [NiceDeclaration]
dataOrRec pc uc mkDef mkSig niceD r x mt mcs = do
mds <- Trav.forM mcs $ \ (tel, cs) -> (tel,) <$> niceD cs
We set origin to UserWritten if the user split the data / rec herself ,
let o | isJust mt && isJust mcs = Inserted
| otherwise = UserWritten
return $ catMaybes $
[ mt <&> \ (tel, t) -> mkSig (fuseRange x t) PublicAccess ConcreteDef pc uc x tel t
, mds <&> \ (tel, ds) -> mkDef r o ConcreteDef pc uc x (caseMaybe mt tel $ const $ concatMap dropTypeAndModality tel) ds
If a type is given ( mt /= Nothing ) , we have to delete the types in @tel@
for the data definition , lest we duplicate them . And also drop modalities ( # 1886 ) .
]
where
dropTypeAndModality :: LamBinding -> [LamBinding]
dropTypeAndModality (DomainFull (TBind _ xs _)) =
map (DomainFree . setModality defaultModality) xs
dropTypeAndModality (DomainFull TLet{}) = []
dropTypeAndModality (DomainFree x) = [DomainFree $ setModality defaultModality x]
Translate axioms
niceAxioms :: KindOfBlock -> [TypeSignatureOrInstanceBlock] -> Nice [NiceDeclaration]
niceAxioms b ds = liftM List.concat $ mapM (niceAxiom b) ds
niceAxiom :: KindOfBlock -> TypeSignatureOrInstanceBlock -> Nice [NiceDeclaration]
niceAxiom b d = case d of
TypeSig rel _tac x t -> do
return [ Axiom (getRange d) PublicAccess ConcreteDef NotInstanceDef rel x t ]
FieldSig i tac x argt | b == FieldBlock -> do
return [ NiceField (getRange d) PublicAccess ConcreteDef i tac x argt ]
InstanceB r decls -> do
instanceBlock r =<< niceAxioms InstanceBlock decls
Pragma p@(RewritePragma r _ _) -> do
return [ NicePragma r p ]
_ -> throwError $ WrongContentBlock b $ getRange d
toPrim :: NiceDeclaration -> NiceDeclaration
toPrim (Axiom r p a i rel x t) = PrimitiveFunction r p a x t
toPrim _ = __IMPOSSIBLE__
mkFunDef info termCheck covCheck x mt ds0 = do
ds <- expandEllipsis ds0
cs <- mkClauses x ds False
return [ FunSig (fuseRange x t) PublicAccess ConcreteDef NotInstanceDef NotMacroDef info termCheck covCheck x t
, FunDef (getRange ds0) ds0 ConcreteDef NotInstanceDef termCheck covCheck x cs ]
where
t = case mt of
Just t -> t
Nothing -> underscore (getRange x)
underscore r = Underscore r Nothing
expandEllipsis :: [Declaration] -> Nice [Declaration]
expandEllipsis [] = return []
expandEllipsis (d@(FunClause lhs@(LHS p _ _ ell) _ _ _) : ds)
| ExpandedEllipsis{} <- ell = __IMPOSSIBLE__
| hasEllipsis p = (d :) <$> expandEllipsis ds
| otherwise = (d :) <$> expand (killRange p) ds
where
expand :: Pattern -> [Declaration] -> Nice [Declaration]
expand _ [] = return []
expand p (d : ds) = do
case d of
Pragma (CatchallPragma _) -> do
(d :) <$> expand p ds
FunClause (LHS p0 eqs es NoEllipsis) rhs wh ca -> do
case hasEllipsis' p0 of
ManyHoles -> throwError $ MultipleEllipses p0
OneHole cxt ~(EllipsisP r) -> do
Replace the ellipsis by @p@.
let p1 = cxt p
let ell = ExpandedEllipsis r (numberOfWithPatterns p)
let d' = FunClause (LHS p1 eqs es ell) rhs wh ca
(d' :) <$> expand (if null es then p else killRange p1) ds
ZeroHoles _ -> do
Andreas , Jesper , 2017 - 05 - 13 , issue # 2578
(d :) <$> expand (if null es then p else killRange p0) ds
_ -> __IMPOSSIBLE__
expandEllipsis _ = __IMPOSSIBLE__
mkClauses :: Name -> [Declaration] -> Catchall -> Nice [Clause]
mkClauses _ [] _ = return []
mkClauses x (Pragma (CatchallPragma r) : cs) True = do
niceWarning $ InvalidCatchallPragma r
mkClauses x cs True
mkClauses x (Pragma (CatchallPragma r) : cs) False = do
when (null cs) $ niceWarning $ InvalidCatchallPragma r
mkClauses x cs True
mkClauses x (FunClause lhs rhs wh ca : cs) catchall
| null (lhsWithExpr lhs) || hasEllipsis lhs =
mkClauses x (FunClause lhs rhs wh ca : cs) catchall = do
when (null withClauses) $ throwError $ MissingWithClauses x lhs
wcs <- mkClauses x withClauses False
(Clause x (ca || catchall) lhs rhs wh wcs :) <$> mkClauses x cs' False
where
(withClauses, cs') = subClauses cs
numWith = numberOfWithPatterns p + length (filter visible es) where LHS p _ es _ = lhs
subClauses :: [Declaration] -> ([Declaration],[Declaration])
subClauses (c@(FunClause (LHS p0 _ _ _) _ _ _) : cs)
| isEllipsis p0 ||
numberOfWithPatterns p0 >= numWith = mapFst (c:) (subClauses cs)
| otherwise = ([], c:cs)
subClauses (c@(Pragma (CatchallPragma r)) : cs) = case subClauses cs of
([], cs') -> ([], c:cs')
(cs, cs') -> (c:cs, cs')
subClauses [] = ([],[])
subClauses _ = __IMPOSSIBLE__
mkClauses _ _ _ = __IMPOSSIBLE__
couldBeFunClauseOf :: Maybe Fixity' -> Name -> Declaration -> Bool
couldBeFunClauseOf mFixity x (Pragma (CatchallPragma{})) = True
couldBeFunClauseOf mFixity x (FunClause (LHS p _ _ _) _ _ _) = hasEllipsis p ||
let
pns = patternNames p
xStrings = nameStringParts x
patStrings = concatMap nameStringParts pns
in
trace ( " xStrings = " + + show xStrings ) $
trace ( " patStrings = " + + show ) $
case (listToMaybe pns, mFixity) of
first identifier in the patterns is the fun.symbol ?
are the parts of x contained in p
let notStrings = stringParts (theNotation fix)
trace ( " notStrings = " + + show ) $
trace ( " patStrings = " + + show ) $
(not $ null notStrings) && (notStrings `isSublistOf` patStrings)
mkOldMutual
mkOldMutual r ds' = do
let ps = loneSigsFromLoneNames loneNames
checkLoneSigs ps
let ds = replaceSigs ps ds'
ds < - fmap $ forM ds $ \ d - > let success = pure ( Just d ) in case d of
Axiom { } - > success
(top, bottom, invalid) <- forEither3M ds $ \ d -> do
let top = return (In1 d)
bottom = return (In2 d)
invalid s = In3 d <$ do niceWarning $ NotAllowedInMutual (getRange d) s
case d of
, 2013 - 11 - 23 allow postulates in mutual blocks
Axiom{} -> top
NiceField{} -> top
PrimitiveFunction{} -> top
, 2019 - 07 - 23 issue # 3932 :
NiceMutual{} -> invalid "mutual blocks"
, 2018 - 10 - 29 , issue # 3246
NiceModule{} -> invalid "Module definitions"
NiceModuleMacro{} -> top
NiceOpen{} -> top
NiceImport{} -> top
NiceRecSig{} -> top
NiceDataSig{} -> top
, 2017 - 10 - 09 , issue # 2576 , raise error about missing type signature
in ConcreteToAbstract rather than here .
NiceFunClause{} -> bottom
FunSig{} -> top
FunDef{} -> bottom
NiceDataDef{} -> bottom
NiceRecDef{} -> bottom
, 2018 - 05 - 11 , issue # 3051 , allow pat.syn.s in mutual blocks
, 2018 - 10 - 29 : We shift pattern synonyms to the bottom
NicePatternSyn{} -> bottom
NiceGeneralize{} -> top
NiceUnquoteDecl{} -> top
NiceUnquoteDef{} -> bottom
NicePragma r pragma -> case pragma of
BuiltinPragma{} -> invalid "BUILTIN pragmas"
RewritePragma{} -> invalid "REWRITE pragmas"
ForeignPragma{} -> bottom
CompilePragma{} -> bottom
StaticPragma{} -> bottom
InlinePragma{} -> bottom
WarningOnUsage{} -> top
WarningOnImport{} -> top
CatchallPragma{} -> __IMPOSSIBLE__
TerminationCheckPragma{} -> __IMPOSSIBLE__
NoPositivityCheckPragma{} -> __IMPOSSIBLE__
PolarityPragma{} -> __IMPOSSIBLE__
NoUniverseCheckPragma{} -> __IMPOSSIBLE__
NoCoverageCheckPragma{} -> __IMPOSSIBLE__
let ( sigs , other ) = List.partition isTypeSig ds
let ( other , defs ) = flip List.partition ds $ \case
tc0 <- use terminationCheckPragma
let tcs = map termCheck ds
tc <- combineTerminationChecks r (tc0:tcs)
cc0 <- use coverageCheckPragma
let ccs = map covCheck ds
let cc = combineCoverageChecks (cc0:ccs)
pc0 <- use positivityCheckPragma
let pcs = map positivityCheckOldMutual ds
let pc = combinePositivityChecks (pc0:pcs)
return $ NiceMutual r tc cc pc $ top ++ bottom
where
isTypeSig Axiom { } = True
isTypeSig d | { } < - declKind d = True
sigNames = [ (r, x, k) | LoneSigDecl r k x <- map declKind ds' ]
defNames = [ (x, k) | LoneDefs k xs <- map declKind ds', x <- xs ]
loneNames = [ (r, x, k) | (r, x, k) <- sigNames, List.all ((x /=) . fst) defNames ]
termCheck :: NiceDeclaration -> TerminationCheck
, 2013 - 02 - 28 ( issue 804 ):
inner declarations comes with a { - # NO_TERMINATION_CHECK # - }
termCheck (FunSig _ _ _ _ _ _ tc _ _ _) = tc
termCheck (FunDef _ _ _ _ tc _ _ _) = tc
ASR ( 28 December 2015 ): Is this equation necessary ?
termCheck (NiceMutual _ tc _ _ _) = tc
termCheck (NiceUnquoteDecl _ _ _ _ tc _ _ _) = tc
termCheck (NiceUnquoteDef _ _ _ tc _ _ _) = tc
termCheck Axiom{} = TerminationCheck
termCheck NiceField{} = TerminationCheck
termCheck PrimitiveFunction{} = TerminationCheck
termCheck NiceModule{} = TerminationCheck
termCheck NiceModuleMacro{} = TerminationCheck
termCheck NiceOpen{} = TerminationCheck
termCheck NiceImport{} = TerminationCheck
termCheck NicePragma{} = TerminationCheck
termCheck NiceRecSig{} = TerminationCheck
termCheck NiceDataSig{} = TerminationCheck
termCheck NiceFunClause{} = TerminationCheck
termCheck NiceDataDef{} = TerminationCheck
termCheck NiceRecDef{} = TerminationCheck
termCheck NicePatternSyn{} = TerminationCheck
termCheck NiceGeneralize{} = TerminationCheck
covCheck :: NiceDeclaration -> CoverageCheck
covCheck (FunSig _ _ _ _ _ _ _ cc _ _) = cc
covCheck (FunDef _ _ _ _ _ cc _ _) = cc
ASR ( 28 December 2015 ): Is this equation necessary ?
covCheck (NiceMutual _ _ cc _ _) = cc
covCheck (NiceUnquoteDecl _ _ _ _ _ cc _ _) = cc
covCheck (NiceUnquoteDef _ _ _ _ cc _ _) = cc
covCheck Axiom{} = YesCoverageCheck
covCheck NiceField{} = YesCoverageCheck
covCheck PrimitiveFunction{} = YesCoverageCheck
covCheck NiceModule{} = YesCoverageCheck
covCheck NiceModuleMacro{} = YesCoverageCheck
covCheck NiceOpen{} = YesCoverageCheck
covCheck NiceImport{} = YesCoverageCheck
covCheck NicePragma{} = YesCoverageCheck
covCheck NiceRecSig{} = YesCoverageCheck
covCheck NiceDataSig{} = YesCoverageCheck
covCheck NiceFunClause{} = YesCoverageCheck
covCheck NiceDataDef{} = YesCoverageCheck
covCheck NiceRecDef{} = YesCoverageCheck
covCheck NicePatternSyn{} = YesCoverageCheck
covCheck NiceGeneralize{} = YesCoverageCheck
ASR ( 26 December 2015 ): Do not positivity check a mutual
NO_POSITIVITY_CHECK pragma . See Issue 1614 .
positivityCheckOldMutual :: NiceDeclaration -> PositivityCheck
positivityCheckOldMutual (NiceDataDef _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceDataSig _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceMutual _ _ _ pc _) = pc
positivityCheckOldMutual (NiceRecSig _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceRecDef _ _ _ pc _ _ _ _ _ _ _) = pc
positivityCheckOldMutual _ = YesPositivityCheck
abstractBlock _ [] = return []
abstractBlock r ds = do
(ds', anyChange) <- runChangeT $ mkAbstract ds
let inherited = r == noRange
if anyChange then return ds' else do
unless inherited $ niceWarning $ UselessAbstract r
privateBlock _ _ [] = return []
privateBlock r o ds = do
(ds', anyChange) <- runChangeT $ mkPrivate o ds
if anyChange then return ds' else do
when (o == UserWritten) $ niceWarning $ UselessPrivate r
instanceBlock
-> [NiceDeclaration]
-> Nice [NiceDeclaration]
instanceBlock _ [] = return []
instanceBlock r ds = do
let (ds', anyChange) = runChange $ mapM (mkInstance r) ds
if anyChange then return ds' else do
niceWarning $ UselessInstance r
mkInstance
-> Updater NiceDeclaration
mkInstance r0 = \case
Axiom r p a i rel x e -> (\ i -> Axiom r p a i rel x e) <$> setInstance r0 i
FunSig r p a i m rel tc cc x e -> (\ i -> FunSig r p a i m rel tc cc x e) <$> setInstance r0 i
NiceUnquoteDecl r p a i tc cc x e -> (\ i -> NiceUnquoteDecl r p a i tc cc x e) <$> setInstance r0 i
NiceMutual r tc cc pc ds -> NiceMutual r tc cc pc <$> mapM (mkInstance r0) ds
d@NiceFunClause{} -> return d
FunDef r ds a i tc cc x cs -> (\ i -> FunDef r ds a i tc cc x cs) <$> setInstance r0 i
Field instance are handled by the parser
d@PrimitiveFunction{} -> return d
d@NiceUnquoteDef{} -> return d
d@NiceRecSig{} -> return d
d@NiceDataSig{} -> return d
d@NiceModuleMacro{} -> return d
d@NiceModule{} -> return d
d@NicePragma{} -> return d
d@NiceOpen{} -> return d
d@NiceImport{} -> return d
d@NiceDataDef{} -> return d
d@NiceRecDef{} -> return d
d@NicePatternSyn{} -> return d
d@NiceGeneralize{} -> return d
setInstance
-> Updater IsInstance
setInstance r0 = \case
i@InstanceDef{} -> return i
_ -> dirty $ InstanceDef r0
macroBlock r ds = mapM mkMacro ds
mkMacro :: NiceDeclaration -> Nice NiceDeclaration
mkMacro = \case
FunSig r p a i _ rel tc cc x e -> return $ FunSig r p a i MacroDef rel tc cc x e
d@FunDef{} -> return d
d -> throwError (BadMacroDef d)
If no abstraction is taking place , we want to complain about ' UselessAbstract ' .
class MakeAbstract a where
mkAbstract :: UpdaterT Nice a
default mkAbstract :: (Traversable f, MakeAbstract a', a ~ f a') => UpdaterT Nice a
mkAbstract = traverse mkAbstract
instance MakeAbstract a => MakeAbstract [a] where
Leads to overlap with ' WhereClause ' :
instance ( f , MakeAbstract a ) = > MakeAbstract ( f a ) where
instance MakeAbstract IsAbstract where
mkAbstract = \case
a@AbstractDef -> return a
ConcreteDef -> dirty $ AbstractDef
instance MakeAbstract NiceDeclaration where
mkAbstract = \case
NiceMutual r termCheck cc pc ds -> NiceMutual r termCheck cc pc <$> mkAbstract ds
FunDef r ds a i tc cc x cs -> (\ a -> FunDef r ds a i tc cc x) <$> mkAbstract a <*> mkAbstract cs
NiceDataDef r o a pc uc x ps cs -> (\ a -> NiceDataDef r o a pc uc x ps) <$> mkAbstract a <*> mkAbstract cs
NiceRecDef r o a pc uc x i e c ps cs -> (\ a -> NiceRecDef r o a pc uc x i e c ps) <$> mkAbstract a <*> return cs
NiceFunClause r p a tc cc catchall d -> (\ a -> NiceFunClause r p a tc cc catchall d) <$> mkAbstract a
( thus , do not notify progress with @dirty@ ) .
Axiom r p a i rel x e -> return $ Axiom r p AbstractDef i rel x e
FunSig r p a i m rel tc cc x e -> return $ FunSig r p AbstractDef i m rel tc cc x e
NiceRecSig r p a pc uc x ls t -> return $ NiceRecSig r p AbstractDef pc uc x ls t
NiceDataSig r p a pc uc x ls t -> return $ NiceDataSig r p AbstractDef pc uc x ls t
NiceField r p _ i tac x e -> return $ NiceField r p AbstractDef i tac x e
PrimitiveFunction r p _ x e -> return $ PrimitiveFunction r p AbstractDef x e
, 2016 - 07 - 17 it does have effect on unquoted defs .
NiceUnquoteDecl r p _ i tc cc x e -> tellDirty $> NiceUnquoteDecl r p AbstractDef i tc cc x e
NiceUnquoteDef r p _ tc cc x e -> tellDirty $> NiceUnquoteDef r p AbstractDef tc cc x e
d@NiceModule{} -> return d
d@NiceModuleMacro{} -> return d
d@NicePragma{} -> return d
d@(NiceOpen _ _ directives) -> do
whenJust (publicOpen directives) $ lift . niceWarning . OpenPublicAbstract
return d
d@NiceImport{} -> return d
d@NicePatternSyn{} -> return d
d@NiceGeneralize{} -> return d
instance MakeAbstract Clause where
mkAbstract (Clause x catchall lhs rhs wh with) = do
Clause x catchall lhs rhs <$> mkAbstract wh <*> mkAbstract with
instance MakeAbstract WhereClause where
mkAbstract NoWhere = return $ NoWhere
mkAbstract (AnyWhere ds) = dirty $ AnyWhere [Abstract noRange ds]
mkAbstract (SomeWhere m a ds) = dirty $ SomeWhere m a [Abstract noRange ds]
, 2012 - 11 - 17 :
Then , nested would sometimes also be complained about .
class MakePrivate a where
mkPrivate :: Origin -> UpdaterT Nice a
default mkPrivate :: (Traversable f, MakePrivate a', a ~ f a') => Origin -> UpdaterT Nice a
mkPrivate o = traverse $ mkPrivate o
instance MakePrivate a => MakePrivate [a] where
Leads to overlap with ' WhereClause ' :
instance ( f , MakePrivate a ) = > MakePrivate ( f a ) where
mkPrivate = traverse mkPrivate
instance MakePrivate Access where
mkPrivate o = \case
OR ? return o
_ -> dirty $ PrivateAccess o
instance MakePrivate NiceDeclaration where
mkPrivate o = \case
Axiom r p a i rel x e -> (\ p -> Axiom r p a i rel x e) <$> mkPrivate o p
NiceField r p a i tac x e -> (\ p -> NiceField r p a i tac x e) <$> mkPrivate o p
PrimitiveFunction r p a x e -> (\ p -> PrimitiveFunction r p a x e) <$> mkPrivate o p
NiceMutual r tc cc pc ds -> (\ ds-> NiceMutual r tc cc pc ds) <$> mkPrivate o ds
NiceModule r p a x tel ds -> (\ p -> NiceModule r p a x tel ds) <$> mkPrivate o p
NiceModuleMacro r p x ma op is -> (\ p -> NiceModuleMacro r p x ma op is) <$> mkPrivate o p
FunSig r p a i m rel tc cc x e -> (\ p -> FunSig r p a i m rel tc cc x e) <$> mkPrivate o p
NiceRecSig r p a pc uc x ls t -> (\ p -> NiceRecSig r p a pc uc x ls t) <$> mkPrivate o p
NiceDataSig r p a pc uc x ls t -> (\ p -> NiceDataSig r p a pc uc x ls t) <$> mkPrivate o p
NiceFunClause r p a tc cc catchall d -> (\ p -> NiceFunClause r p a tc cc catchall d) <$> mkPrivate o p
NiceUnquoteDecl r p a i tc cc x e -> (\ p -> NiceUnquoteDecl r p a i tc cc x e) <$> mkPrivate o p
NiceUnquoteDef r p a tc cc x e -> (\ p -> NiceUnquoteDef r p a tc cc x e) <$> mkPrivate o p
NicePatternSyn r p x xs p' -> (\ p -> NicePatternSyn r p x xs p') <$> mkPrivate o p
NiceGeneralize r p i tac x t -> (\ p -> NiceGeneralize r p i tac x t) <$> mkPrivate o p
d@NicePragma{} -> return d
d@(NiceOpen _ _ directives) -> do
whenJust (publicOpen directives) $ lift . niceWarning . OpenPublicPrivate
return d
d@NiceImport{} -> return d
, 2016 - 07 - 08 , issue # 2089
FunDef r ds a i tc cc x cls -> FunDef r ds a i tc cc x <$> mkPrivate o cls
d@NiceDataDef{} -> return d
d@NiceRecDef{} -> return d
instance MakePrivate Clause where
mkPrivate o (Clause x catchall lhs rhs wh with) = do
Clause x catchall lhs rhs <$> mkPrivate o wh <*> mkPrivate o with
instance MakePrivate WhereClause where
mkPrivate o NoWhere = return $ NoWhere
mkPrivate o (AnyWhere ds) = return $ AnyWhere ds
, 2016 - 07 - 08
A @where@-module is private if the parent function is private .
Thus , we do not recurse into the @ds@ ( could not anyway ) .
mkPrivate o (SomeWhere m a ds) = mkPrivate o a <&> \ a' -> SomeWhere m a' ds
The following function is ( at the time of writing ) only used three
| ( Approximately ) convert a ' NiceDeclaration ' back to a list of
' Declaration 's .
notSoNiceDeclarations :: NiceDeclaration -> [Declaration]
notSoNiceDeclarations = \case
Axiom _ _ _ i rel x e -> inst i [TypeSig rel Nothing x e]
NiceField _ _ _ i tac x argt -> [FieldSig i tac x argt]
PrimitiveFunction r _ _ x e -> [Primitive r [TypeSig defaultArgInfo Nothing x e]]
NiceMutual r _ _ _ ds -> [Mutual r $ concatMap notSoNiceDeclarations ds]
NiceModule r _ _ x tel ds -> [Module r x tel ds]
NiceModuleMacro r _ x ma o dir -> [ModuleMacro r x ma o dir]
NiceOpen r x dir -> [Open r x dir]
NiceImport r x as o dir -> [Import r x as o dir]
NicePragma _ p -> [Pragma p]
NiceRecSig r _ _ _ _ x bs e -> [RecordSig r x bs e]
NiceDataSig r _ _ _ _ x bs e -> [DataSig r x bs e]
NiceFunClause _ _ _ _ _ _ d -> [d]
FunSig _ _ _ i _ rel _ _ x e -> inst i [TypeSig rel Nothing x e]
FunDef _ ds _ _ _ _ _ _ -> ds
NiceDataDef r _ _ _ _ x bs cs -> [DataDef r x bs $ concatMap notSoNiceDeclarations cs]
NiceRecDef r _ _ _ _ x i e c bs ds -> [RecordDef r x i e c bs ds]
NicePatternSyn r _ n as p -> [PatternSyn r n as p]
NiceGeneralize r _ i tac n e -> [Generalize r [TypeSig i tac n e]]
NiceUnquoteDecl r _ _ i _ _ x e -> inst i [UnquoteDecl r x e]
NiceUnquoteDef r _ _ _ _ x e -> [UnquoteDef r x e]
where
inst (InstanceDef r) ds = [InstanceB r ds]
inst NotInstanceDef ds = ds
| Has the ' NiceDeclaration ' a field of type ' IsAbstract ' ?
niceHasAbstract :: NiceDeclaration -> Maybe IsAbstract
niceHasAbstract = \case
Axiom{} -> Nothing
NiceField _ _ a _ _ _ _ -> Just a
PrimitiveFunction _ _ a _ _ -> Just a
NiceMutual{} -> Nothing
NiceModule _ _ a _ _ _ -> Just a
NiceModuleMacro{} -> Nothing
NiceOpen{} -> Nothing
NiceImport{} -> Nothing
NicePragma{} -> Nothing
NiceRecSig{} -> Nothing
NiceDataSig{} -> Nothing
NiceFunClause _ _ a _ _ _ _ -> Just a
FunSig{} -> Nothing
FunDef _ _ a _ _ _ _ _ -> Just a
NiceDataDef _ _ a _ _ _ _ _ -> Just a
NiceRecDef _ _ a _ _ _ _ _ _ _ _ -> Just a
NicePatternSyn{} -> Nothing
NiceGeneralize{} -> Nothing
NiceUnquoteDecl _ _ a _ _ _ _ _ -> Just a
NiceUnquoteDef _ _ a _ _ _ _ -> Just a
|
2cd17c58e635714a94e30139d1c432b12e2daf62cf6e9b8df5d186f5ec4eabbe | nponeccop/HNC | ArgumentValues.hs |
import CPP.CompileTools
import HN.Optimizer.ArgumentValues
import HN.Optimizer.GraphCompiler
import HN.Optimizer.Visualise
import FFI.TypeParser
import Compiler.Hoopl
main = do
ast <- parseHN "hn_tests/print15.hn"
ffi <- importHni "lib/lib.hni"
putStrLn $ foo $ run avPass $ fst $ compileGraph ffi $ head ast
run pass graph = case runSimpleUniqueMonad . runWithFuel infiniteFuel $
analyzeAndRewriteFwd pass entry graph $
mkFactBase (fp_lattice pass) [(runSimpleUniqueMonad freshLabel, fact_bot $ fp_lattice pass)] of
(_, newFacts, _) -> newFacts
entry = JustC [runSimpleUniqueMonad freshLabel]
| null | https://raw.githubusercontent.com/nponeccop/HNC/d8447009a04c56ae2cba4c7c179e39384085ea00/Test/Optimizer/ArgumentValues.hs | haskell |
import CPP.CompileTools
import HN.Optimizer.ArgumentValues
import HN.Optimizer.GraphCompiler
import HN.Optimizer.Visualise
import FFI.TypeParser
import Compiler.Hoopl
main = do
ast <- parseHN "hn_tests/print15.hn"
ffi <- importHni "lib/lib.hni"
putStrLn $ foo $ run avPass $ fst $ compileGraph ffi $ head ast
run pass graph = case runSimpleUniqueMonad . runWithFuel infiniteFuel $
analyzeAndRewriteFwd pass entry graph $
mkFactBase (fp_lattice pass) [(runSimpleUniqueMonad freshLabel, fact_bot $ fp_lattice pass)] of
(_, newFacts, _) -> newFacts
entry = JustC [runSimpleUniqueMonad freshLabel]
| |
4a854e2e9201b92762f575cab6cab238b3253a5496e33c289a01201feb0b5475 | biegunka/biegunka | Internal.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NamedFieldPuns #
# LANGUAGE TypeFamilies #
-- | Support for git repositories as 'Sources'
module Control.Biegunka.Source.Git.Internal
( Git
, git
, Url
, Config(..)
, url
, path
, branch
, failIfAhead
, update
, defaultConfig
, runGit
, gitHash
) where
import Control.Applicative (empty)
import Control.Lens
import Data.Bifunctor (Bifunctor(..))
import Data.Bool (bool)
import qualified Data.List as List
import Data.Maybe (listToMaybe)
import qualified Data.Text as Text
import System.Directory (doesDirectoryExist)
import System.Exit.Lens (_ExitFailure)
import System.FilePath ((</>))
import qualified System.Process as P
import Text.Printf (printf)
import Control.Biegunka.Execute.Exception (sourceFailure)
import Control.Biegunka.Language (Scope(..), Source(..), DiffItem(..), diffItemHeaderOnly)
import Control.Biegunka.Script (Script, sourced)
import Control.Biegunka.Source (Url, HasPath(..), HasUrl(..))
-- | Clone or update a clone of the git repository, then run a script on its contents.
--
-- An example:
--
-- @
-- git (url \"git\@github.com:edwinb\/Idris-dev\" . path \"git\/Idris-dev\" . branch \"develop\") $ do
-- link \"contribs\/tool-support\/vim\" \".vim\/bundle\/idris-vim\")
-- @
--
1 . Clone the git repository at @https:\/\/github.com\/edwinb\/Idris - dev.git@ to @~\/git\/Idris - dev@.
--
2 . Check out the @develop@ branch .
--
3 . Link the @~\/git\/Idris - dev\/contribs\/tool - support\/vim@ directory to @~\/.vim\/bundle\/Idris - vim@
git :: Git Url FilePath -> Script 'Actions () -> Script 'Sources ()
git f = sourced Source
{ sourceType = "git"
, sourceFrom = configUrl
, sourceTo = configPath
, sourceUpdate = update config
}
where
config@Config { configUrl, configPath } =
f defaultConfig
type Git a b = Config NoUrl NoPath -> Config a b
data Config a b = Config
{ configUrl :: a
, configPath :: b
, configBranch :: String
, configFailIfAhead :: Bool
} deriving (Functor)
instance Bifunctor Config where
first f config = config { configUrl = f (configUrl config) }
second = fmap
defaultConfig :: Config NoUrl NoPath
defaultConfig = Config
{ configUrl = NoUrl
, configPath = NoPath
, configBranch = "master"
, configFailIfAhead = False
}
data NoUrl = NoUrl
data NoPath = NoPath
instance HasUrl (Config a b) (Config Url b) Url where
url = first . const
instance HasPath (Config a b) (Config a FilePath) FilePath where
path = second . const
-- | Set git branch to track.
branch :: String -> Config a b -> Config a b
branch b config = config { configBranch = b }
-- | Fail when the are local commits ahead of the tracked remote branch.
failIfAhead :: Config a b -> Config a b
failIfAhead config = config { configFailIfAhead = True }
update :: Config Url a -> FilePath -> IO ([DiffItem], IO [DiffItem])
update Config { configUrl, configBranch, configFailIfAhead } fp =
doesDirectoryExist fp >>= \case
True -> do
let rbr = "origin" </> configBranch
before <- gitHash fp "HEAD"
remotes <- lines <$> runGit fp ["remote"]
if "origin" `notElem` remotes
then () <$ runGit fp ["remote", "add", "origin", configUrl]
else assertUrl configUrl fp
runGit fp ["fetch", "origin", configBranch]
after <- gitHash fp rbr
oneliners <- fmap lines (runGit fp ["log", "--pretty=‘%h’ %s", before ++ ".." ++ after])
let gitDiff = DiffItem
{ diffItemHeader = printf "‘%s’ → ‘%s’" before after
, diffItemBody = List.intercalate "\n" oneliners
}
return
( bool (pure gitDiff) empty (before == after || null oneliners)
, do
currentBranch <- fmap (listToMaybe . lines)
(runGit fp ["rev-parse", "--abbrev-ref", "HEAD"])
assertBranch configBranch currentBranch
ahead <- fmap (not . null . lines)
(runGit fp ["rev-list", rbr ++ ".." ++ configBranch])
if ahead && configFailIfAhead
then sourceFailure "Failed because of the ‘failIfAhead’ flag being set.\nThere are commits ahead of the remote branch."
else empty <$ runGit fp ["rebase", rbr]
)
False ->
return
( pure (diffItemHeaderOnly "first checkout")
, do runGit "/" ["clone", configUrl, fp, "-b", configBranch]
after <- gitHash fp "HEAD"
return (pure (diffItemHeaderOnly (printf "‘none’ → ‘%s’" after)))
)
assertBranch :: String -> Maybe String -> IO ()
assertBranch remoteBranch = \case
Just currentBranch
| currentBranch == remoteBranch -> return ()
| otherwise ->
sourceFailure (printf "The wrong branch is checked out.\nExpected: ‘%s’\n But got: ‘%s’" remoteBranch currentBranch)
Nothing ->
sourceFailure "Unable to determine what branch is checked out."
assertUrl :: Url -> FilePath -> IO ()
assertUrl remoteUrl p =
listToMaybe . lines <$> runGit p ["config", "--get", "remote.origin.url"] >>= \case
Just currentUrl
| currentUrl == remoteUrl -> return ()
| otherwise ->
sourceFailure (printf "The ‘origin’ remote points to the wrong repository.\nExpected: ‘%s’\n But got: ‘%s’" remoteUrl currentUrl)
Nothing ->
sourceFailure "Unable to determine what repository the ‘origin’ remote points to."
gitHash :: FilePath -> String -> IO String
gitHash fp ref = runGit fp ["rev-parse", "--short", ref]
runGit :: FilePath -> [String] -> IO String
runGit cwd args = Text.unpack . Text.stripEnd <$> do
(exitcode, out, err) <- P.readCreateProcessWithExitCode proc ""
forOf_ _ExitFailure exitcode (\_ -> sourceFailure err)
return (Text.pack out)
where
proc = (P.proc "git" args) { P.cwd = Just cwd }
| null | https://raw.githubusercontent.com/biegunka/biegunka/74fc93326d5f29761125d7047d5418899fa2469d/src/Control/Biegunka/Source/Git/Internal.hs | haskell | | Support for git repositories as 'Sources'
| Clone or update a clone of the git repository, then run a script on its contents.
An example:
@
git (url \"git\@github.com:edwinb\/Idris-dev\" . path \"git\/Idris-dev\" . branch \"develop\") $ do
link \"contribs\/tool-support\/vim\" \".vim\/bundle\/idris-vim\")
@
| Set git branch to track.
| Fail when the are local commits ahead of the tracked remote branch. | # LANGUAGE DataKinds #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NamedFieldPuns #
# LANGUAGE TypeFamilies #
module Control.Biegunka.Source.Git.Internal
( Git
, git
, Url
, Config(..)
, url
, path
, branch
, failIfAhead
, update
, defaultConfig
, runGit
, gitHash
) where
import Control.Applicative (empty)
import Control.Lens
import Data.Bifunctor (Bifunctor(..))
import Data.Bool (bool)
import qualified Data.List as List
import Data.Maybe (listToMaybe)
import qualified Data.Text as Text
import System.Directory (doesDirectoryExist)
import System.Exit.Lens (_ExitFailure)
import System.FilePath ((</>))
import qualified System.Process as P
import Text.Printf (printf)
import Control.Biegunka.Execute.Exception (sourceFailure)
import Control.Biegunka.Language (Scope(..), Source(..), DiffItem(..), diffItemHeaderOnly)
import Control.Biegunka.Script (Script, sourced)
import Control.Biegunka.Source (Url, HasPath(..), HasUrl(..))
1 . Clone the git repository at @https:\/\/github.com\/edwinb\/Idris - dev.git@ to @~\/git\/Idris - dev@.
2 . Check out the @develop@ branch .
3 . Link the @~\/git\/Idris - dev\/contribs\/tool - support\/vim@ directory to @~\/.vim\/bundle\/Idris - vim@
git :: Git Url FilePath -> Script 'Actions () -> Script 'Sources ()
git f = sourced Source
{ sourceType = "git"
, sourceFrom = configUrl
, sourceTo = configPath
, sourceUpdate = update config
}
where
config@Config { configUrl, configPath } =
f defaultConfig
type Git a b = Config NoUrl NoPath -> Config a b
data Config a b = Config
{ configUrl :: a
, configPath :: b
, configBranch :: String
, configFailIfAhead :: Bool
} deriving (Functor)
instance Bifunctor Config where
first f config = config { configUrl = f (configUrl config) }
second = fmap
defaultConfig :: Config NoUrl NoPath
defaultConfig = Config
{ configUrl = NoUrl
, configPath = NoPath
, configBranch = "master"
, configFailIfAhead = False
}
data NoUrl = NoUrl
data NoPath = NoPath
instance HasUrl (Config a b) (Config Url b) Url where
url = first . const
instance HasPath (Config a b) (Config a FilePath) FilePath where
path = second . const
branch :: String -> Config a b -> Config a b
branch b config = config { configBranch = b }
failIfAhead :: Config a b -> Config a b
failIfAhead config = config { configFailIfAhead = True }
update :: Config Url a -> FilePath -> IO ([DiffItem], IO [DiffItem])
update Config { configUrl, configBranch, configFailIfAhead } fp =
doesDirectoryExist fp >>= \case
True -> do
let rbr = "origin" </> configBranch
before <- gitHash fp "HEAD"
remotes <- lines <$> runGit fp ["remote"]
if "origin" `notElem` remotes
then () <$ runGit fp ["remote", "add", "origin", configUrl]
else assertUrl configUrl fp
runGit fp ["fetch", "origin", configBranch]
after <- gitHash fp rbr
oneliners <- fmap lines (runGit fp ["log", "--pretty=‘%h’ %s", before ++ ".." ++ after])
let gitDiff = DiffItem
{ diffItemHeader = printf "‘%s’ → ‘%s’" before after
, diffItemBody = List.intercalate "\n" oneliners
}
return
( bool (pure gitDiff) empty (before == after || null oneliners)
, do
currentBranch <- fmap (listToMaybe . lines)
(runGit fp ["rev-parse", "--abbrev-ref", "HEAD"])
assertBranch configBranch currentBranch
ahead <- fmap (not . null . lines)
(runGit fp ["rev-list", rbr ++ ".." ++ configBranch])
if ahead && configFailIfAhead
then sourceFailure "Failed because of the ‘failIfAhead’ flag being set.\nThere are commits ahead of the remote branch."
else empty <$ runGit fp ["rebase", rbr]
)
False ->
return
( pure (diffItemHeaderOnly "first checkout")
, do runGit "/" ["clone", configUrl, fp, "-b", configBranch]
after <- gitHash fp "HEAD"
return (pure (diffItemHeaderOnly (printf "‘none’ → ‘%s’" after)))
)
assertBranch :: String -> Maybe String -> IO ()
assertBranch remoteBranch = \case
Just currentBranch
| currentBranch == remoteBranch -> return ()
| otherwise ->
sourceFailure (printf "The wrong branch is checked out.\nExpected: ‘%s’\n But got: ‘%s’" remoteBranch currentBranch)
Nothing ->
sourceFailure "Unable to determine what branch is checked out."
assertUrl :: Url -> FilePath -> IO ()
assertUrl remoteUrl p =
listToMaybe . lines <$> runGit p ["config", "--get", "remote.origin.url"] >>= \case
Just currentUrl
| currentUrl == remoteUrl -> return ()
| otherwise ->
sourceFailure (printf "The ‘origin’ remote points to the wrong repository.\nExpected: ‘%s’\n But got: ‘%s’" remoteUrl currentUrl)
Nothing ->
sourceFailure "Unable to determine what repository the ‘origin’ remote points to."
gitHash :: FilePath -> String -> IO String
gitHash fp ref = runGit fp ["rev-parse", "--short", ref]
runGit :: FilePath -> [String] -> IO String
runGit cwd args = Text.unpack . Text.stripEnd <$> do
(exitcode, out, err) <- P.readCreateProcessWithExitCode proc ""
forOf_ _ExitFailure exitcode (\_ -> sourceFailure err)
return (Text.pack out)
where
proc = (P.proc "git" args) { P.cwd = Just cwd }
|
0be44f344770b57a9981de82bc7e4fda99d0e11a7f302e6e0fe3803c6fd02539 | jamesmccabe/stumpwm-demo-config | overrides.lisp | overrides.lisp --- preferred functionality for StumpWM
Copyright © 2020 - 2021
Author : < james.mccab3(at)gmail.com >
;; 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 </>.
;;; Commentary:
This file changes some default behavior of StumpWM .
;;; Code:
;;; Colors
overrides StumpWM default behavior of dimming normal colors
(defun update-color-map (screen)
"Read *colors* and cache their pixel colors for use when rendering colored text."
(labels ((map-colors (amt)
(loop for c in *colors*
as color = (lookup-color screen c)
do (adjust-color color amt)
collect (alloc-color screen color))))
(setf (screen-color-map-normal screen) (apply #'vector (map-colors 0.00)))))
(update-color-map (current-screen))
;; fix colors in quit message
(defcommand quit-confirm () ()
"Prompt the user to confirm quitting StumpWM."
(if (y-or-n-p (format nil "~@{~a~^~%~}"
"You are about to quit the window manager to TTY."
"Really ^2quit^n ^4StumpWM^n?"
"^5Confirm?^n "))
(quit)
(xlib:unmap-window (screen-message-window (current-screen)))))
;;; Splits
StumpWM by default treats horizontal and vertical splits as Emacs does .
Horizontal splits the current frame into 2 side - by - side frames and Vertical
splits the current frame into 2 frames , one on top of the other .
;; I reverse this behavior in my configuration.
(defcommand (vsplit tile-group) (&optional (ratio "1/2")) (:string)
"Split the current frame into 2 side-by-side frames."
(split-frame-in-dir (current-group) :column (read-from-string ratio)))
(defcommand (hsplit tile-group) (&optional (ratio "1/2")) (:string)
"Split the current frame into 2 frames, one on top of the other."
(split-frame-in-dir (current-group) :row (read-from-string ratio)))
(undefine-key *tile-group-root-map* (kbd "S"))
(undefine-key *tile-group-root-map* (kbd "s"))
(define-key *root-map* (kbd "S") "vsplit")
(define-key *root-map* (kbd "s") "hsplit")
(defcommand (vsplit-equally tile-group) (amt)
((:number "Enter the number of frames: "))
"Split current frame in n columns of equal size."
(split-frame-eql-parts (current-group) :column amt))
(defcommand (hsplit-equally tile-group) (amt)
((:number "Enter the number of frames: "))
"Split current frame in n rows of equal size."
(split-frame-eql-parts (current-group) :row amt))
overrides.lisp ends here
| null | https://raw.githubusercontent.com/jamesmccabe/stumpwm-demo-config/5fc9b35889d264faad6ba48613a0e1d8d0c688bd/overrides.lisp | lisp | This program is free software; you can redistribute it and/or modify
(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.
along with this program. If not, see </>.
Commentary:
Code:
Colors
fix colors in quit message
Splits
I reverse this behavior in my configuration. | overrides.lisp --- preferred functionality for StumpWM
Copyright © 2020 - 2021
Author : < james.mccab3(at)gmail.com >
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
This file changes some default behavior of StumpWM .
overrides StumpWM default behavior of dimming normal colors
(defun update-color-map (screen)
"Read *colors* and cache their pixel colors for use when rendering colored text."
(labels ((map-colors (amt)
(loop for c in *colors*
as color = (lookup-color screen c)
do (adjust-color color amt)
collect (alloc-color screen color))))
(setf (screen-color-map-normal screen) (apply #'vector (map-colors 0.00)))))
(update-color-map (current-screen))
(defcommand quit-confirm () ()
"Prompt the user to confirm quitting StumpWM."
(if (y-or-n-p (format nil "~@{~a~^~%~}"
"You are about to quit the window manager to TTY."
"Really ^2quit^n ^4StumpWM^n?"
"^5Confirm?^n "))
(quit)
(xlib:unmap-window (screen-message-window (current-screen)))))
StumpWM by default treats horizontal and vertical splits as Emacs does .
Horizontal splits the current frame into 2 side - by - side frames and Vertical
splits the current frame into 2 frames , one on top of the other .
(defcommand (vsplit tile-group) (&optional (ratio "1/2")) (:string)
"Split the current frame into 2 side-by-side frames."
(split-frame-in-dir (current-group) :column (read-from-string ratio)))
(defcommand (hsplit tile-group) (&optional (ratio "1/2")) (:string)
"Split the current frame into 2 frames, one on top of the other."
(split-frame-in-dir (current-group) :row (read-from-string ratio)))
(undefine-key *tile-group-root-map* (kbd "S"))
(undefine-key *tile-group-root-map* (kbd "s"))
(define-key *root-map* (kbd "S") "vsplit")
(define-key *root-map* (kbd "s") "hsplit")
(defcommand (vsplit-equally tile-group) (amt)
((:number "Enter the number of frames: "))
"Split current frame in n columns of equal size."
(split-frame-eql-parts (current-group) :column amt))
(defcommand (hsplit-equally tile-group) (amt)
((:number "Enter the number of frames: "))
"Split current frame in n rows of equal size."
(split-frame-eql-parts (current-group) :row amt))
overrides.lisp ends here
|
3a3c78a0ff22a37e650510d1a58775f04d75a17b5119607444dc92b7f1b8f538 | dyzsr/ocaml-selectml | records.ml | (* TEST
flags = " -w +A -strict-sequence "
* expect
*)
(* Use type information *)
module M1 = struct
type t = {x: int; y: int}
type u = {x: bool; y: bool}
end;;
[%%expect{|
module M1 :
sig type t = { x : int; y : int; } type u = { x : bool; y : bool; } end
|}]
module OK = struct
open M1
let f1 (r:t) = r.x (* ok *)
let f2 r = ignore (r:t); r.x (* non principal *)
let f3 (r: t) =
match r with {x; y} -> y + y (* ok *)
end;;
[%%expect{|
Line 3, characters 19-20:
3 | let f1 (r:t) = r.x (* ok *)
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 29-30:
4 | let f2 r = ignore (r:t); r.x (* non principal *)
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 18-19:
7 | match r with {x; y} -> y + y (* ok *)
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 21-22:
7 | match r with {x; y} -> y + y (* ok *)
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 18-19:
7 | match r with {x; y} -> y + y (* ok *)
^
Warning 27 [unused-var-strict]: unused variable x.
module OK :
sig val f1 : M1.t -> int val f2 : M1.t -> int val f3 : M1.t -> int end
|}, Principal{|
Line 3, characters 19-20:
3 | let f1 (r:t) = r.x (* ok *)
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 29-30:
4 | let f2 r = ignore (r:t); r.x (* non principal *)
^
Warning 18 [not-principal]: this type-based field disambiguation is not principal.
Line 4, characters 29-30:
4 | let f2 r = ignore (r:t); r.x (* non principal *)
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 18-19:
7 | match r with {x; y} -> y + y (* ok *)
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 21-22:
7 | match r with {x; y} -> y + y (* ok *)
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 18-19:
7 | match r with {x; y} -> y + y (* ok *)
^
Warning 27 [unused-var-strict]: unused variable x.
module OK :
sig val f1 : M1.t -> int val f2 : M1.t -> int val f3 : M1.t -> int end
|}]
module F1 = struct
open M1
let f r = match r with {x; y} -> y + y
end;; (* fails *)
[%%expect{|
Line 3, characters 25-31:
3 | let f r = match r with {x; y} -> y + y
^^^^^^
Warning 41 [ambiguous-name]: these field labels belong to several types: M1.u M1.t
The first one was selected. Please disambiguate if this is wrong.
Line 3, characters 35-36:
3 | let f r = match r with {x; y} -> y + y
^
Error: This expression has type bool but an expression was expected of type
int
|}]
module F2 = struct
open M1
let f r =
ignore (r: t);
match r with
{x; y} -> y + y
end;; (* fails for -principal *)
[%%expect{|
Line 6, characters 8-9:
6 | {x; y} -> y + y
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 11-12:
6 | {x; y} -> y + y
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 8-9:
6 | {x; y} -> y + y
^
Warning 27 [unused-var-strict]: unused variable x.
module F2 : sig val f : M1.t -> int end
|}, Principal{|
Line 6, characters 8-9:
6 | {x; y} -> y + y
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 11-12:
6 | {x; y} -> y + y
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 7-13:
6 | {x; y} -> y + y
^^^^^^
Warning 18 [not-principal]: this type-based record disambiguation is not principal.
Line 6, characters 8-9:
6 | {x; y} -> y + y
^
Warning 27 [unused-var-strict]: unused variable x.
module F2 : sig val f : M1.t -> int end
|}]
(* Use type information with modules*)
module M = struct
type t = {x:int}
type u = {x:bool}
end;;
[%%expect{|
module M : sig type t = { x : int; } type u = { x : bool; } end
|}]
let f (r:M.t) = r.M.x;; (* ok *)
[%%expect{|
Line 1, characters 18-21:
1 | let f (r:M.t) = r.M.x;; (* ok *)
^^^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
val f : M.t -> int = <fun>
|}]
let f (r:M.t) = r.x;; (* warning *)
[%%expect{|
Line 1, characters 18-19:
1 | let f (r:M.t) = r.x;; (* warning *)
^
Warning 40 [name-out-of-scope]: x was selected from type M.t.
It is not visible in the current scope, and will not
be selected if the type becomes unknown.
Line 1, characters 18-19:
1 | let f (r:M.t) = r.x;; (* warning *)
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
val f : M.t -> int = <fun>
|}]
let f ({x}:M.t) = x;; (* warning *)
[%%expect{|
Line 1, characters 8-9:
1 | let f ({x}:M.t) = x;; (* warning *)
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 1, characters 7-10:
1 | let f ({x}:M.t) = x;; (* warning *)
^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: x.
They will not be selected if the type becomes unknown.
val f : M.t -> int = <fun>
|}]
module M = struct
type t = {x: int; y: int}
end;;
[%%expect{|
module M : sig type t = { x : int; y : int; } end
|}]
module N = struct
type u = {x: bool; y: bool}
end;;
[%%expect{|
module N : sig type u = { x : bool; y : bool; } end
|}]
module OK = struct
open M
open N
let f (r:M.t) = r.x
end;;
[%%expect{|
Line 4, characters 20-21:
4 | let f (r:M.t) = r.x
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 2-8:
3 | open N
^^^^^^
Warning 33 [unused-open]: unused open N.
module OK : sig val f : M.t -> int end
|}]
module M = struct
type t = {x:int}
module N = struct type s = t = {x:int} end
type u = {x:bool}
end;;
[%%expect{|
module M :
sig
type t = { x : int; }
module N : sig type s = t = { x : int; } end
type u = { x : bool; }
end
|}]
module OK = struct
open M.N
let f (r:M.t) = r.x
end;;
[%%expect{|
module OK : sig val f : M.t -> int end
|}]
(* Use field information *)
module M = struct
type u = {x:bool;y:int;z:char}
type t = {x:int;y:bool}
end;;
[%%expect{|
module M :
sig
type u = { x : bool; y : int; z : char; }
type t = { x : int; y : bool; }
end
|}]
module OK = struct
open M
let f {x;z} = x,z
end;; (* ok *)
[%%expect{|
Line 3, characters 9-10:
3 | let f {x;z} = x,z
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 8-13:
3 | let f {x;z} = x,z
^^^^^
Warning 9 [missing-record-field-pattern]: the following labels are not bound in this record pattern:
y
Either bind these labels explicitly or add '; _' to the pattern.
module OK : sig val f : M.u -> bool * char end
|}]
module F3 = struct
open M
let r = {x=true;z='z'}
end;; (* fail for missing label *)
[%%expect{|
Line 3, characters 11-12:
3 | let r = {x=true;z='z'}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 10-24:
3 | let r = {x=true;z='z'}
^^^^^^^^^^^^^^
Error: Some record fields are undefined: y
|}]
module OK = struct
type u = {x:int;y:bool}
type t = {x:bool;y:int;z:char}
let r = {x=3; y=true}
end;; (* ok *)
[%%expect{|
Line 4, characters 11-12:
4 | let r = {x=3; y=true}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 16-17:
4 | let r = {x=3; y=true}
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
module OK :
sig
type u = { x : int; y : bool; }
type t = { x : bool; y : int; z : char; }
val r : u
end
|}]
Corner cases
module F4 = struct
type foo = {x:int; y:int}
type bar = {x:int}
let b : bar = {x=3; y=4}
end;; (* fail but don't warn *)
[%%expect{|
Line 4, characters 22-23:
4 | let b : bar = {x=3; y=4}
^
Error: This record expression is expected to have type bar
There is no field y within type bar
|}]
module M = struct type foo = {x:int;y:int} end;;
[%%expect{|
module M : sig type foo = { x : int; y : int; } end
|}]
module N = struct type bar = {x:int;y:int} end;;
[%%expect{|
module N : sig type bar = { x : int; y : int; } end
|}]
let r = { M.x = 3; N.y = 4; };; (* error: different definitions *)
[%%expect{|
Line 1, characters 19-22:
1 | let r = { M.x = 3; N.y = 4; };; (* error: different definitions *)
^^^
Error: The record field N.y belongs to the type N.bar
but is mixed here with fields of type M.foo
|}]
module MN = struct include M include N end
module NM = struct include N include M end;;
[%%expect{|
module MN :
sig
type foo = M.foo = { x : int; y : int; }
type bar = N.bar = { x : int; y : int; }
end
module NM :
sig
type bar = N.bar = { x : int; y : int; }
type foo = M.foo = { x : int; y : int; }
end
|}]
let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
[%%expect{|
Line 1, characters 8-28:
1 | let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
^^^^^^^^^^^^^^^^^^^^
Warning 41 [ambiguous-name]: x belongs to several types: MN.bar MN.foo
The first one was selected. Please disambiguate if this is wrong.
Line 1, characters 8-28:
1 | let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
^^^^^^^^^^^^^^^^^^^^
Warning 41 [ambiguous-name]: y belongs to several types: NM.foo NM.bar
The first one was selected. Please disambiguate if this is wrong.
Line 1, characters 19-23:
1 | let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
^^^^
Error: The record field NM.y belongs to the type NM.foo = M.foo
but is mixed here with fields of type MN.bar = N.bar
|}]
Lpw25
module M = struct
type foo = { x: int; y: int }
type bar = { x:int; y: int; z: int}
end;;
[%%expect{|
module M :
sig
type foo = { x : int; y : int; }
type bar = { x : int; y : int; z : int; }
end
|}]
module F5 = struct
open M
let f r = ignore (r: foo); {r with x = 2; z = 3}
end;;
[%%expect{|
Line 3, characters 37-38:
3 | let f r = ignore (r: foo); {r with x = 2; z = 3}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 44-45:
3 | let f r = ignore (r: foo); {r with x = 2; z = 3}
^
Error: This record expression is expected to have type M.foo
There is no field z within type M.foo
|}]
module M = struct
include M
type other = { a: int; b: int }
end;;
[%%expect{|
module M :
sig
type foo = M.foo = { x : int; y : int; }
type bar = M.bar = { x : int; y : int; z : int; }
type other = { a : int; b : int; }
end
|}]
module F6 = struct
open M
let f r = ignore (r: foo); { r with x = 3; a = 4 }
end;;
[%%expect{|
Line 3, characters 38-39:
3 | let f r = ignore (r: foo); { r with x = 3; a = 4 }
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 45-46:
3 | let f r = ignore (r: foo); { r with x = 3; a = 4 }
^
Error: This record expression is expected to have type M.foo
There is no field a within type M.foo
|}]
module F7 = struct
open M
let r = {x=1; y=2}
let r: other = {x=1; y=2}
end;;
[%%expect{|
Line 3, characters 11-12:
3 | let r = {x=1; y=2}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 16-17:
3 | let r = {x=1; y=2}
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 18-19:
4 | let r: other = {x=1; y=2}
^
Error: This record expression is expected to have type M.other
There is no field x within type M.other
|}]
module A = struct type t = {x: int} end
module B = struct type t = {x: int} end;;
[%%expect{|
module A : sig type t = { x : int; } end
module B : sig type t = { x : int; } end
|}]
let f (r : B.t) = r.A.x;; (* fail *)
[%%expect{|
Line 1, characters 20-23:
1 | let f (r : B.t) = r.A.x;; (* fail *)
^^^
Error: The field A.x belongs to the record type A.t
but a field was expected belonging to the record type B.t
|}]
(* Spellchecking *)
module F8 = struct
type t = {x:int; yyy:int}
let a : t = {x=1;yyz=2}
end;;
[%%expect{|
Line 3, characters 19-22:
3 | let a : t = {x=1;yyz=2}
^^^
Error: This record expression is expected to have type t
There is no field yyz within type t
Hint: Did you mean yyy?
|}]
(* PR#6004 *)
type t = A
type s = A
class f (_ : t) = object end;;
[%%expect{|
type t = A
type s = A
class f : t -> object end
|}]
class g = f A;; (* ok *)
class f (_ : 'a) (_ : 'a) = object end;;
[%%expect{|
Line 1, characters 12-13:
1 | class g = f A;; (* ok *)
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
class g : f
class f : 'a -> 'a -> object end
|}]
class g = f (A : t) A;; (* warn with -principal *)
[%%expect{|
Line 1, characters 13-14:
1 | class g = f (A : t) A;; (* warn with -principal *)
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 1, characters 20-21:
1 | class g = f (A : t) A;; (* warn with -principal *)
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
class g : f
|}, Principal{|
Line 1, characters 13-14:
1 | class g = f (A : t) A;; (* warn with -principal *)
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 1, characters 20-21:
1 | class g = f (A : t) A;; (* warn with -principal *)
^
Warning 18 [not-principal]: this type-based constructor disambiguation is not principal.
Line 1, characters 20-21:
1 | class g = f (A : t) A;; (* warn with -principal *)
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
class g : f
|}]
(* PR#5980 *)
module Shadow1 = struct
type t = {x: int}
module M = struct
type s = {x: string}
end
open M (* this open is unused, it isn't reported as shadowing 'x' *)
let y : t = {x = 0}
end;;
[%%expect{|
Line 7, characters 15-16:
7 | let y : t = {x = 0}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 2-8:
6 | open M (* this open is unused, it isn't reported as shadowing 'x' *)
^^^^^^
Warning 33 [unused-open]: unused open M.
module Shadow1 :
sig
type t = { x : int; }
module M : sig type s = { x : string; } end
val y : t
end
|}]
module Shadow2 = struct
type t = {x: int}
module M = struct
type s = {x: string}
end
open M (* this open shadows label 'x' *)
let y = {x = ""}
end;;
[%%expect{|
Line 6, characters 2-8:
6 | open M (* this open shadows label 'x' *)
^^^^^^
Warning 45 [open-shadow-label-constructor]: this open statement shadows the label x (which is later used)
Line 7, characters 10-18:
7 | let y = {x = ""}
^^^^^^^^
Warning 41 [ambiguous-name]: these field labels belong to several types: M.s t
The first one was selected. Please disambiguate if this is wrong.
module Shadow2 :
sig
type t = { x : int; }
module M : sig type s = { x : string; } end
val y : M.s
end
|}]
(* PR#6235 *)
module P6235 = struct
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
let f (u : u) = match u with `Key {loc} -> loc
end;;
[%%expect{|
Line 5, characters 37-40:
5 | let f (u : u) = match u with `Key {loc} -> loc
^^^
Warning 42 [disambiguated-name]: this use of loc relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
module P6235 :
sig
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
val f : u -> string
end
|}]
(* Remove interaction between branches *)
module P6235' = struct
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
let f = function
| (_ : u) when false -> ""
|`Key {loc} -> loc
end;;
[%%expect{|
Line 7, characters 11-14:
7 | |`Key {loc} -> loc
^^^
Warning 42 [disambiguated-name]: this use of loc relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
module P6235' :
sig
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
val f : u -> string
end
|}, Principal{|
Line 7, characters 11-14:
7 | |`Key {loc} -> loc
^^^
Warning 42 [disambiguated-name]: this use of loc relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 10-15:
7 | |`Key {loc} -> loc
^^^^^
Warning 18 [not-principal]: this type-based record disambiguation is not principal.
module P6235' :
sig
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
val f : u -> string
end
|}]
* no candidates after filtering ;
This caused a temporary trunk regression identified by while reviewing # 9196
This caused a temporary trunk regression identified by Florian Angeletti
while reviewing #9196
*)
module M = struct
type t = { x:int; y:int}
end
type u = { a:int }
let _ = ( { M.x=0 } : u );;
[%%expect{|
module M : sig type t = { x : int; y : int; } end
type u = { a : int; }
Line 5, characters 12-15:
5 | let _ = ( { M.x=0 } : u );;
^^^
Error: The field M.x belongs to the record type M.t
but a field was expected belonging to the record type u
|}]
PR#8747
module M = struct type t = { x : int; y: char } end
let f (x : M.t) = { x with y = 'a' }
let g (x : M.t) = { x with y = 'a' } :: []
let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
[%%expect{|
module M : sig type t = { x : int; y : char; } end
Line 2, characters 27-28:
2 | let f (x : M.t) = { x with y = 'a' }
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 2, characters 18-36:
2 | let f (x : M.t) = { x with y = 'a' }
^^^^^^^^^^^^^^^^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: y.
They will not be selected if the type becomes unknown.
val f : M.t -> M.t = <fun>
Line 3, characters 27-28:
3 | let g (x : M.t) = { x with y = 'a' } :: []
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 18-36:
3 | let g (x : M.t) = { x with y = 'a' } :: []
^^^^^^^^^^^^^^^^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: y.
They will not be selected if the type becomes unknown.
val g : M.t -> M.t list = <fun>
Line 4, characters 27-28:
4 | let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 18-36:
4 | let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
^^^^^^^^^^^^^^^^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: y.
They will not be selected if the type becomes unknown.
Line 4, characters 49-50:
4 | let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 40-58:
4 | let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
^^^^^^^^^^^^^^^^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: y.
They will not be selected if the type becomes unknown.
val h : M.t -> M.t list = <fun>
|}]
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-warnings/records.ml | ocaml | TEST
flags = " -w +A -strict-sequence "
* expect
Use type information
ok
non principal
ok
ok
non principal
ok
ok
ok
ok
non principal
non principal
ok
ok
ok
fails
fails for -principal
Use type information with modules
ok
ok
warning
warning
warning
warning
warning
warning
Use field information
ok
fail for missing label
ok
fail but don't warn
error: different definitions
error: different definitions
error: type would change with order
error: type would change with order
error: type would change with order
error: type would change with order
fail
fail
Spellchecking
PR#6004
ok
ok
warn with -principal
warn with -principal
warn with -principal
warn with -principal
warn with -principal
warn with -principal
PR#5980
this open is unused, it isn't reported as shadowing 'x'
this open is unused, it isn't reported as shadowing 'x'
this open shadows label 'x'
this open shadows label 'x'
PR#6235
Remove interaction between branches |
module M1 = struct
type t = {x: int; y: int}
type u = {x: bool; y: bool}
end;;
[%%expect{|
module M1 :
sig type t = { x : int; y : int; } type u = { x : bool; y : bool; } end
|}]
module OK = struct
open M1
let f3 (r: t) =
end;;
[%%expect{|
Line 3, characters 19-20:
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 29-30:
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 18-19:
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 21-22:
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 18-19:
^
Warning 27 [unused-var-strict]: unused variable x.
module OK :
sig val f1 : M1.t -> int val f2 : M1.t -> int val f3 : M1.t -> int end
|}, Principal{|
Line 3, characters 19-20:
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 29-30:
^
Warning 18 [not-principal]: this type-based field disambiguation is not principal.
Line 4, characters 29-30:
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 18-19:
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 21-22:
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 18-19:
^
Warning 27 [unused-var-strict]: unused variable x.
module OK :
sig val f1 : M1.t -> int val f2 : M1.t -> int val f3 : M1.t -> int end
|}]
module F1 = struct
open M1
let f r = match r with {x; y} -> y + y
[%%expect{|
Line 3, characters 25-31:
3 | let f r = match r with {x; y} -> y + y
^^^^^^
Warning 41 [ambiguous-name]: these field labels belong to several types: M1.u M1.t
The first one was selected. Please disambiguate if this is wrong.
Line 3, characters 35-36:
3 | let f r = match r with {x; y} -> y + y
^
Error: This expression has type bool but an expression was expected of type
int
|}]
module F2 = struct
open M1
let f r =
ignore (r: t);
match r with
{x; y} -> y + y
[%%expect{|
Line 6, characters 8-9:
6 | {x; y} -> y + y
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 11-12:
6 | {x; y} -> y + y
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 8-9:
6 | {x; y} -> y + y
^
Warning 27 [unused-var-strict]: unused variable x.
module F2 : sig val f : M1.t -> int end
|}, Principal{|
Line 6, characters 8-9:
6 | {x; y} -> y + y
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 11-12:
6 | {x; y} -> y + y
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 7-13:
6 | {x; y} -> y + y
^^^^^^
Warning 18 [not-principal]: this type-based record disambiguation is not principal.
Line 6, characters 8-9:
6 | {x; y} -> y + y
^
Warning 27 [unused-var-strict]: unused variable x.
module F2 : sig val f : M1.t -> int end
|}]
module M = struct
type t = {x:int}
type u = {x:bool}
end;;
[%%expect{|
module M : sig type t = { x : int; } type u = { x : bool; } end
|}]
[%%expect{|
Line 1, characters 18-21:
^^^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
val f : M.t -> int = <fun>
|}]
[%%expect{|
Line 1, characters 18-19:
^
Warning 40 [name-out-of-scope]: x was selected from type M.t.
It is not visible in the current scope, and will not
be selected if the type becomes unknown.
Line 1, characters 18-19:
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
val f : M.t -> int = <fun>
|}]
[%%expect{|
Line 1, characters 8-9:
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 1, characters 7-10:
^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: x.
They will not be selected if the type becomes unknown.
val f : M.t -> int = <fun>
|}]
module M = struct
type t = {x: int; y: int}
end;;
[%%expect{|
module M : sig type t = { x : int; y : int; } end
|}]
module N = struct
type u = {x: bool; y: bool}
end;;
[%%expect{|
module N : sig type u = { x : bool; y : bool; } end
|}]
module OK = struct
open M
open N
let f (r:M.t) = r.x
end;;
[%%expect{|
Line 4, characters 20-21:
4 | let f (r:M.t) = r.x
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 2-8:
3 | open N
^^^^^^
Warning 33 [unused-open]: unused open N.
module OK : sig val f : M.t -> int end
|}]
module M = struct
type t = {x:int}
module N = struct type s = t = {x:int} end
type u = {x:bool}
end;;
[%%expect{|
module M :
sig
type t = { x : int; }
module N : sig type s = t = { x : int; } end
type u = { x : bool; }
end
|}]
module OK = struct
open M.N
let f (r:M.t) = r.x
end;;
[%%expect{|
module OK : sig val f : M.t -> int end
|}]
module M = struct
type u = {x:bool;y:int;z:char}
type t = {x:int;y:bool}
end;;
[%%expect{|
module M :
sig
type u = { x : bool; y : int; z : char; }
type t = { x : int; y : bool; }
end
|}]
module OK = struct
open M
let f {x;z} = x,z
[%%expect{|
Line 3, characters 9-10:
3 | let f {x;z} = x,z
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 8-13:
3 | let f {x;z} = x,z
^^^^^
Warning 9 [missing-record-field-pattern]: the following labels are not bound in this record pattern:
y
Either bind these labels explicitly or add '; _' to the pattern.
module OK : sig val f : M.u -> bool * char end
|}]
module F3 = struct
open M
let r = {x=true;z='z'}
[%%expect{|
Line 3, characters 11-12:
3 | let r = {x=true;z='z'}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 10-24:
3 | let r = {x=true;z='z'}
^^^^^^^^^^^^^^
Error: Some record fields are undefined: y
|}]
module OK = struct
type u = {x:int;y:bool}
type t = {x:bool;y:int;z:char}
let r = {x=3; y=true}
[%%expect{|
Line 4, characters 11-12:
4 | let r = {x=3; y=true}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 16-17:
4 | let r = {x=3; y=true}
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
module OK :
sig
type u = { x : int; y : bool; }
type t = { x : bool; y : int; z : char; }
val r : u
end
|}]
Corner cases
module F4 = struct
type foo = {x:int; y:int}
type bar = {x:int}
let b : bar = {x=3; y=4}
[%%expect{|
Line 4, characters 22-23:
4 | let b : bar = {x=3; y=4}
^
Error: This record expression is expected to have type bar
There is no field y within type bar
|}]
module M = struct type foo = {x:int;y:int} end;;
[%%expect{|
module M : sig type foo = { x : int; y : int; } end
|}]
module N = struct type bar = {x:int;y:int} end;;
[%%expect{|
module N : sig type bar = { x : int; y : int; } end
|}]
[%%expect{|
Line 1, characters 19-22:
^^^
Error: The record field N.y belongs to the type N.bar
but is mixed here with fields of type M.foo
|}]
module MN = struct include M include N end
module NM = struct include N include M end;;
[%%expect{|
module MN :
sig
type foo = M.foo = { x : int; y : int; }
type bar = N.bar = { x : int; y : int; }
end
module NM :
sig
type bar = N.bar = { x : int; y : int; }
type foo = M.foo = { x : int; y : int; }
end
|}]
[%%expect{|
Line 1, characters 8-28:
^^^^^^^^^^^^^^^^^^^^
Warning 41 [ambiguous-name]: x belongs to several types: MN.bar MN.foo
The first one was selected. Please disambiguate if this is wrong.
Line 1, characters 8-28:
^^^^^^^^^^^^^^^^^^^^
Warning 41 [ambiguous-name]: y belongs to several types: NM.foo NM.bar
The first one was selected. Please disambiguate if this is wrong.
Line 1, characters 19-23:
^^^^
Error: The record field NM.y belongs to the type NM.foo = M.foo
but is mixed here with fields of type MN.bar = N.bar
|}]
Lpw25
module M = struct
type foo = { x: int; y: int }
type bar = { x:int; y: int; z: int}
end;;
[%%expect{|
module M :
sig
type foo = { x : int; y : int; }
type bar = { x : int; y : int; z : int; }
end
|}]
module F5 = struct
open M
let f r = ignore (r: foo); {r with x = 2; z = 3}
end;;
[%%expect{|
Line 3, characters 37-38:
3 | let f r = ignore (r: foo); {r with x = 2; z = 3}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 44-45:
3 | let f r = ignore (r: foo); {r with x = 2; z = 3}
^
Error: This record expression is expected to have type M.foo
There is no field z within type M.foo
|}]
module M = struct
include M
type other = { a: int; b: int }
end;;
[%%expect{|
module M :
sig
type foo = M.foo = { x : int; y : int; }
type bar = M.bar = { x : int; y : int; z : int; }
type other = { a : int; b : int; }
end
|}]
module F6 = struct
open M
let f r = ignore (r: foo); { r with x = 3; a = 4 }
end;;
[%%expect{|
Line 3, characters 38-39:
3 | let f r = ignore (r: foo); { r with x = 3; a = 4 }
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 45-46:
3 | let f r = ignore (r: foo); { r with x = 3; a = 4 }
^
Error: This record expression is expected to have type M.foo
There is no field a within type M.foo
|}]
module F7 = struct
open M
let r = {x=1; y=2}
let r: other = {x=1; y=2}
end;;
[%%expect{|
Line 3, characters 11-12:
3 | let r = {x=1; y=2}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 16-17:
3 | let r = {x=1; y=2}
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 18-19:
4 | let r: other = {x=1; y=2}
^
Error: This record expression is expected to have type M.other
There is no field x within type M.other
|}]
module A = struct type t = {x: int} end
module B = struct type t = {x: int} end;;
[%%expect{|
module A : sig type t = { x : int; } end
module B : sig type t = { x : int; } end
|}]
[%%expect{|
Line 1, characters 20-23:
^^^
Error: The field A.x belongs to the record type A.t
but a field was expected belonging to the record type B.t
|}]
module F8 = struct
type t = {x:int; yyy:int}
let a : t = {x=1;yyz=2}
end;;
[%%expect{|
Line 3, characters 19-22:
3 | let a : t = {x=1;yyz=2}
^^^
Error: This record expression is expected to have type t
There is no field yyz within type t
Hint: Did you mean yyy?
|}]
type t = A
type s = A
class f (_ : t) = object end;;
[%%expect{|
type t = A
type s = A
class f : t -> object end
|}]
class f (_ : 'a) (_ : 'a) = object end;;
[%%expect{|
Line 1, characters 12-13:
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
class g : f
class f : 'a -> 'a -> object end
|}]
[%%expect{|
Line 1, characters 13-14:
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 1, characters 20-21:
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
class g : f
|}, Principal{|
Line 1, characters 13-14:
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 1, characters 20-21:
^
Warning 18 [not-principal]: this type-based constructor disambiguation is not principal.
Line 1, characters 20-21:
^
Warning 42 [disambiguated-name]: this use of A relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
class g : f
|}]
module Shadow1 = struct
type t = {x: int}
module M = struct
type s = {x: string}
end
let y : t = {x = 0}
end;;
[%%expect{|
Line 7, characters 15-16:
7 | let y : t = {x = 0}
^
Warning 42 [disambiguated-name]: this use of x relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 6, characters 2-8:
^^^^^^
Warning 33 [unused-open]: unused open M.
module Shadow1 :
sig
type t = { x : int; }
module M : sig type s = { x : string; } end
val y : t
end
|}]
module Shadow2 = struct
type t = {x: int}
module M = struct
type s = {x: string}
end
let y = {x = ""}
end;;
[%%expect{|
Line 6, characters 2-8:
^^^^^^
Warning 45 [open-shadow-label-constructor]: this open statement shadows the label x (which is later used)
Line 7, characters 10-18:
7 | let y = {x = ""}
^^^^^^^^
Warning 41 [ambiguous-name]: these field labels belong to several types: M.s t
The first one was selected. Please disambiguate if this is wrong.
module Shadow2 :
sig
type t = { x : int; }
module M : sig type s = { x : string; } end
val y : M.s
end
|}]
module P6235 = struct
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
let f (u : u) = match u with `Key {loc} -> loc
end;;
[%%expect{|
Line 5, characters 37-40:
5 | let f (u : u) = match u with `Key {loc} -> loc
^^^
Warning 42 [disambiguated-name]: this use of loc relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
module P6235 :
sig
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
val f : u -> string
end
|}]
module P6235' = struct
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
let f = function
| (_ : u) when false -> ""
|`Key {loc} -> loc
end;;
[%%expect{|
Line 7, characters 11-14:
7 | |`Key {loc} -> loc
^^^
Warning 42 [disambiguated-name]: this use of loc relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
module P6235' :
sig
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
val f : u -> string
end
|}, Principal{|
Line 7, characters 11-14:
7 | |`Key {loc} -> loc
^^^
Warning 42 [disambiguated-name]: this use of loc relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 7, characters 10-15:
7 | |`Key {loc} -> loc
^^^^^
Warning 18 [not-principal]: this type-based record disambiguation is not principal.
module P6235' :
sig
type t = { loc : string; }
type v = { loc : string; x : int; }
type u = [ `Key of t ]
val f : u -> string
end
|}]
* no candidates after filtering ;
This caused a temporary trunk regression identified by while reviewing # 9196
This caused a temporary trunk regression identified by Florian Angeletti
while reviewing #9196
*)
module M = struct
type t = { x:int; y:int}
end
type u = { a:int }
let _ = ( { M.x=0 } : u );;
[%%expect{|
module M : sig type t = { x : int; y : int; } end
type u = { a : int; }
Line 5, characters 12-15:
5 | let _ = ( { M.x=0 } : u );;
^^^
Error: The field M.x belongs to the record type M.t
but a field was expected belonging to the record type u
|}]
PR#8747
module M = struct type t = { x : int; y: char } end
let f (x : M.t) = { x with y = 'a' }
let g (x : M.t) = { x with y = 'a' } :: []
let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
[%%expect{|
module M : sig type t = { x : int; y : char; } end
Line 2, characters 27-28:
2 | let f (x : M.t) = { x with y = 'a' }
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 2, characters 18-36:
2 | let f (x : M.t) = { x with y = 'a' }
^^^^^^^^^^^^^^^^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: y.
They will not be selected if the type becomes unknown.
val f : M.t -> M.t = <fun>
Line 3, characters 27-28:
3 | let g (x : M.t) = { x with y = 'a' } :: []
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 3, characters 18-36:
3 | let g (x : M.t) = { x with y = 'a' } :: []
^^^^^^^^^^^^^^^^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: y.
They will not be selected if the type becomes unknown.
val g : M.t -> M.t list = <fun>
Line 4, characters 27-28:
4 | let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 18-36:
4 | let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
^^^^^^^^^^^^^^^^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: y.
They will not be selected if the type becomes unknown.
Line 4, characters 49-50:
4 | let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
^
Warning 42 [disambiguated-name]: this use of y relies on type-directed disambiguation,
it will not compile with OCaml 4.00 or earlier.
Line 4, characters 40-58:
4 | let h (x : M.t) = { x with y = 'a' } :: { x with y = 'b' } :: [];;
^^^^^^^^^^^^^^^^^^
Warning 40 [name-out-of-scope]: this record of type M.t contains fields that are
not visible in the current scope: y.
They will not be selected if the type becomes unknown.
val h : M.t -> M.t list = <fun>
|}]
|
5dcbc1bd918861e29aa165612ee7fda62f65645d39a836b8d66cf4db7732c9b6 | haskell/ThreadScope | Constants.hs | module GUI.Timeline.Render.Constants (
ox, firstTraceY, tracePad,
hecTraceHeight, hecInstantHeight, hecSparksHeight,
hecBarOff, hecBarHeight, hecLabelExtra,
activityGraphHeight, stdHistogramHeight, histXScaleHeight,
ticksHeight, ticksPad
) where
-------------------------------------------------------------------------------
-- The standard gap in various graphs
ox :: Int
ox = 10
-- Origin for traces
firstTraceY :: Int
firstTraceY = 13
Gap between traces in the timeline view
tracePad :: Int
tracePad = 20
HEC bar height
hecTraceHeight, hecInstantHeight, hecBarHeight, hecBarOff, hecLabelExtra :: Int
hecTraceHeight = 40
hecInstantHeight = 25
hecBarHeight = 20
hecBarOff = 10
-- extra space to allow between HECs when labels are on.
ToDo : should be calculated somehow
hecLabelExtra = 80
-- Activity graph
activityGraphHeight :: Int
activityGraphHeight = 100
-- Height of the spark graphs.
hecSparksHeight :: Int
hecSparksHeight = activityGraphHeight
Histogram graph height when displayed with other traces ( e.g. , in PNG / PDF ) .
stdHistogramHeight :: Int
stdHistogramHeight = hecSparksHeight
-- The X scale of histogram has this constant height, as opposed
to the timeline X scale , which takes its height from the .ui file .
histXScaleHeight :: Int
histXScaleHeight = 30
-- Ticks
ticksHeight :: Int
ticksHeight = 20
ticksPad :: Int
ticksPad = 20
| null | https://raw.githubusercontent.com/haskell/ThreadScope/d70f45eb1d6a5dab13d4ea338d58d91389b77bd4/GUI/Timeline/Render/Constants.hs | haskell | -----------------------------------------------------------------------------
The standard gap in various graphs
Origin for traces
extra space to allow between HECs when labels are on.
Activity graph
Height of the spark graphs.
The X scale of histogram has this constant height, as opposed
Ticks | module GUI.Timeline.Render.Constants (
ox, firstTraceY, tracePad,
hecTraceHeight, hecInstantHeight, hecSparksHeight,
hecBarOff, hecBarHeight, hecLabelExtra,
activityGraphHeight, stdHistogramHeight, histXScaleHeight,
ticksHeight, ticksPad
) where
ox :: Int
ox = 10
firstTraceY :: Int
firstTraceY = 13
Gap between traces in the timeline view
tracePad :: Int
tracePad = 20
HEC bar height
hecTraceHeight, hecInstantHeight, hecBarHeight, hecBarOff, hecLabelExtra :: Int
hecTraceHeight = 40
hecInstantHeight = 25
hecBarHeight = 20
hecBarOff = 10
ToDo : should be calculated somehow
hecLabelExtra = 80
activityGraphHeight :: Int
activityGraphHeight = 100
hecSparksHeight :: Int
hecSparksHeight = activityGraphHeight
Histogram graph height when displayed with other traces ( e.g. , in PNG / PDF ) .
stdHistogramHeight :: Int
stdHistogramHeight = hecSparksHeight
to the timeline X scale , which takes its height from the .ui file .
histXScaleHeight :: Int
histXScaleHeight = 30
ticksHeight :: Int
ticksHeight = 20
ticksPad :: Int
ticksPad = 20
|
56cd744dccf207af2cbb6504203b517044e4fb9a1df1c6e5046940784d288c25 | 2600hz/kazoo | doodle_listener.erl | %%%-----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz
%%% @doc
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(doodle_listener).
-behaviour(gen_listener).
-export([start_link/0]).
Responders
-export([handle_message/2
]).
-export([init/1
,handle_call/3
,handle_cast/2
,handle_info/2
,handle_event/2
,terminate/2
,code_change/3
]).
-include("doodle.hrl").
-define(SERVER, ?MODULE).
-type state() :: map().
-type context() :: map().
-define(BINDINGS, [{'im', [{'restrict_to', ['inbound']}
,{'im_types', ['sms']}
]
}
]).
-define(QUEUE_NAME, <<"doodle">>).
-define(QUEUE_OPTIONS, [{'exclusive', 'false'}
,{'durable', 'true'}
,{'auto_delete', 'false'}
,{'arguments', [{<<"x-message-ttl">>, 'infinity'}
,{<<"x-max-length">>, 'infinity'}
]}
]).
-define(CONSUME_OPTIONS, [{'exclusive', 'false'}
,{'no_ack', 'false'}
]).
-define(RESPONDERS, [{{?MODULE, 'handle_message'}, [{<<"sms">>, <<"inbound">>}]}]).
-define(AMQP_PUBLISH_OPTIONS, [{'mandatory', 'true'}
,{'delivery_mode', 2}
]).
-define(ROUTE_TIMEOUT, 'infinity').
%%%=============================================================================
%%% API
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc Starts the server.
%% @end
%%------------------------------------------------------------------------------
-spec start_link() -> kz_types:startlink_ret().
start_link() ->
gen_listener:start_link(?MODULE
,[{'bindings', ?BINDINGS}
,{'responders', ?RESPONDERS}
,{'queue_name', ?QUEUE_NAME} % optional to include
,{'queue_options', ?QUEUE_OPTIONS} % optional to include
,{'consume_options', ?CONSUME_OPTIONS} % optional to include
]
,[]
).
%%%=============================================================================
%%% gen_server callbacks
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc Initializes the server.
%% @end
%%------------------------------------------------------------------------------
-spec init([]) -> {'ok', state()}.
init([]) ->
{'ok', #{}}.
%%------------------------------------------------------------------------------
%% @doc Handling call messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_call(any(), kz_term:pid_ref(), state()) -> kz_types:handle_call_ret_state(state()).
handle_call(_Request, _From, State) ->
{'reply', {'error', 'not_implemented'}, State}.
%%------------------------------------------------------------------------------
%% @doc Handling cast messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_cast(any(), state()) -> kz_types:handle_cast_ret_state(state()).
handle_cast({'gen_listener', {'created_queue', _Q}}, State) ->
{'noreply', State};
handle_cast({'gen_listener', {'is_consuming', _IsConsuming}}, State) ->
{'noreply', State};
handle_cast(_Msg, State) ->
{'noreply', State}.
%%------------------------------------------------------------------------------
%% @doc Handling all non call/cast messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_info(any(), state()) -> kz_types:handle_info_ret_state(state()).
handle_info(_Info, State) ->
{'noreply', State}.
%%------------------------------------------------------------------------------
%% @doc Allows listener to pass options to handlers.
%% @end
%%------------------------------------------------------------------------------
-spec handle_event(kz_json:object(), state()) -> gen_listener:handle_event_return().
handle_event(_JObj, _State) ->
{'reply', []}.
%%------------------------------------------------------------------------------
%% @doc This function is called by a `gen_server' when it is about to
%% terminate. It should be the opposite of `Module:init/1' and do any
%% necessary cleaning up. When it returns, the `gen_server' terminates
with . The return value is ignored .
%%
%% @end
%%------------------------------------------------------------------------------
-spec terminate(any(), state()) -> 'ok'.
terminate(_Reason, _State) ->
lager:debug("listener terminating: ~p", [_Reason]).
%%------------------------------------------------------------------------------
%% @doc Convert process state when code is changed.
%% @end
%%------------------------------------------------------------------------------
-spec code_change(any(), state(), any()) -> {'ok', state()}.
code_change(_OldVsn, State, _Extra) ->
{'ok', State}.
%%%=============================================================================
Internal functions
%%%=============================================================================
%%%=============================================================================
%%% Handle Inbound
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec handle_message(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_message(JObj, Props) ->
Srv = props:get_value('server', Props),
Deliver = props:get_value('deliver', Props),
case kapi_im:inbound_v(JObj) of
'true' ->
Context = inbound_context(JObj, Props),
kz_log:put_callid(kz_im:message_id(JObj)),
handle_inbound(Context);
'false' ->
lager:debug("error validating inbound message : ~p", [JObj]),
gen_listener:nack(Srv, Deliver)
end.
-spec inbound_context(kz_json:object(), kz_term:proplist()) -> context().
inbound_context(JObj, Props) ->
Srv = props:get_value('server', Props),
Deliver = props:get_value('deliver', Props),
Basic = props:get_value('basic', Props),
{Number, Inception} = doodle_util:get_inbound_destination(JObj),
#{number => Number
,inception => Inception
,request => JObj
,route_id => kz_im:route_id(JObj)
,route_type => kz_im:route_type(JObj)
,basic => Basic
,deliver => Deliver
,server => Srv
}.
-spec handle_inbound(context()) -> 'ok'.
handle_inbound(#{number := Number} = Context0) ->
Routines = [fun custom_vars/1
,fun custom_header_token/1
,fun lookup_number/1
,fun account_from_number/1
,fun set_inception/1
,fun lookup_mdn/1
,fun create_im/1
],
case kz_maps:exec(Routines, Context0) of
#{account_id := _AccountId} = Context ->
lager:info("processing inbound sms request ~s in account ~s", [Number, _AccountId]),
route_message(Context);
Context ->
lager:info("unable to determine account for ~s => ~p", [Number, Context]),
TODO send system notify ?
ack(Context)
end.
ack(#{server := Server
,deliver := Deliver
}) -> gen_listener:ack(Server, Deliver).
%% nack(#{server := Server
%% ,deliver := Deliver
%% }) -> gen_listener:nack(Server, Deliver).
custom_vars(#{authorizing_id := _} = Map) -> Map;
custom_vars(#{request := JObj} = Map) ->
CCVsFilter = [<<"Account-ID">>, <<"Authorizing-ID">>],
CCVs = kz_json:get_json_value(<<"Custom-Vars">>, JObj, kz_json:new()),
Filtered = [{CCV, V} || CCV <- CCVsFilter, (V = kz_json:get_value(CCV, CCVs)) =/= 'undefined'],
lists:foldl(fun custom_var/2, Map, Filtered).
custom_var({K,V}, Map) ->
maps:put(kz_term:to_atom(kz_json:normalize_key(K), 'true'), V, Map).
custom_header_token(#{authorizing_id := _} = Map) -> Map;
custom_header_token(#{request := JObj} = Map) ->
case kz_json:get_ne_binary_value([<<"Custom-SIP-Headers">>, <<"X-AUTH-Token">>], JObj) of
'undefined' -> Map;
Token ->
custom_header_token(Map, JObj, Token)
end.
custom_header_token(Map, JObj, Token) ->
case binary:split(Token, <<"@">>, ['global']) of
[AuthorizingId, AccountId | _] ->
AccountRealm = kzd_accounts:fetch_realm(AccountId),
AccountDb = kzs_util:format_account_db(AccountId),
case kz_datamgr:open_cache_doc(AccountDb, AuthorizingId) of
{'ok', Doc} ->
Props = props:filter_undefined([{?CV(<<"Authorizing-Type">>), kz_doc:type(Doc)}
,{?CV(<<"Authorizing-ID">>), AuthorizingId}
,{?CV(<<"Owner-ID">>), kzd_devices:owner_id(Doc)}
,{?CV(<<"Account-ID">>), AccountId}
,{?CV(<<"Realm">>), AccountRealm}
]),
Map#{authorizing_id => AuthorizingId
,account_id => AccountId
,request => kz_json:set_values(Props, JObj)
};
_Else ->
lager:warning("unexpected result reading doc ~s/~s => ~p", [AuthorizingId, AccountId, _Else]),
Map
end;
_Else ->
lager:warning("unexpected result spliting Token => ~p", [_Else]),
Map
end.
lookup_number(#{account_id := _AccountId} = Map) -> Map;
lookup_number(#{number := Number} = Map) ->
case knm_phone_number:fetch(Number) of
{'error', _R} ->
lager:info("unable to determine account for ~s: ~p", [Number, _R]),
Map;
{'ok', KNumber} ->
Map#{phone_number => KNumber, used_by => knm_phone_number:used_by(KNumber)}
end;
lookup_number(Map) ->
Map.
account_from_number(#{account_id := _AccountId} = Map) -> Map;
account_from_number(#{phone_number := KNumber, request := JObj} = Map) ->
case knm_phone_number:assigned_to(KNumber) of
'undefined' -> Map;
AccountId ->
Props = [{<<"Account-ID">>, AccountId}
,{?CV(<<"Account-ID">>), AccountId}
,{?CV(<<"Authorizing-Type">>), <<"resource">>}
],
Map#{account_id => AccountId
,request => kz_json:set_values(Props, JObj)
}
end;
account_from_number(Map) ->
Map.
-spec set_inception(context()) -> context().
set_inception(#{inception := <<"offnet">>, request := JObj} = Map) ->
Request = kz_json:get_value(<<"From">>, JObj),
Map#{request => kz_json:set_value(?CV(<<"Inception">>), Request, JObj)};
set_inception(#{request := JObj} = Map) ->
Map#{request => kz_json:delete_keys([<<"Inception">>, ?CV(<<"Inception">>)], JObj)}.
-spec lookup_mdn(context()) -> context().
lookup_mdn(#{authorizing_id := _AuthorizingId} = Map) -> Map;
lookup_mdn(#{phone_number := KNumber, request := JObj} = Map) ->
Number = knm_phone_number:number(KNumber),
case doodle_util:lookup_mdn(Number) of
{'ok', Id, OwnerId} ->
Props = props:filter_undefined([{?CV(<<"Authorizing-Type">>), <<"device">>}
,{?CV(<<"Authorizing-ID">>), Id}
,{?CV(<<"Owner-ID">>), OwnerId}
]),
JObj1 = kz_json:delete_keys([?CV(<<"Authorizing-Type">>)
,?CV(<<"Authorizing-ID">>)
], JObj),
Map#{request => kz_json:set_values(Props, JObj1)};
{'error', _} -> Map
end;
lookup_mdn(Map) -> Map.
-spec create_im(context()) -> context().
create_im(#{request:= SmsReq, account_id := AccountId} = Map) ->
Funs = [{fun kapps_im:set_application_name/2, ?APP_NAME}
,{fun kapps_im:set_application_version/2, ?APP_VERSION}
,{fun kapps_im:set_account_id/2, AccountId}
,fun maybe_update_sender/1
],
IM = kapps_im:exec(Funs, kapps_im:from_payload(SmsReq)),
Map#{fetch_id => kapps_im:message_id(IM)
,message_id => kapps_im:message_id(IM)
,im => IM
};
create_im(Map) -> Map.
-spec maybe_update_sender(kapps_im:im()) -> kapps_im:im().
maybe_update_sender(Im) ->
case kapps_im:endpoint(Im) of
'undefined' -> Im;
EP ->
CID = kzd_devices:caller_id(EP, kz_json:new()),
From = kzd_caller_id:internal_number(CID, kapps_im:from(Im)),
kapps_im:set_from(From, Im)
end.
%%%=============================================================================
%%% Route Message
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec route_message(context()) -> 'ok'.
route_message(#{im := Im} = Context) ->
AllowNoMatch = allow_no_match(Im),
case kz_flow:lookup(Im) of
if is false then allow the textflow or if it is true and we are able allowed
%% to use it for this message
{'ok', Flow, NoMatch} when (not NoMatch)
orelse AllowNoMatch ->
route_message(Context, Flow, NoMatch);
{'ok', _, 'true'} ->
lager:info("only available flow is a nomatch for a unauthorized message"),
ack(Context);
{'error', R} ->
lager:info("unable to find flow ~p", [R]),
ack(Context)
end.
-spec allow_no_match(kapps_im:im()) -> boolean().
allow_no_match(Im) ->
allow_no_match_type(Im).
-spec allow_no_match_type(kapps_im:im()) -> boolean().
allow_no_match_type(Im) ->
case kapps_im:authorizing_type(Im) of
'undefined' -> 'false';
<<"resource">> -> 'false';
<<"sys_info">> -> 'false';
_ -> 'true'
end.
-spec route_message(context(), kz_json:object(), boolean()) -> 'ok'.
route_message(#{im := Im} = Context, Flow, NoMatch) ->
lager:info("flow ~s in ~s satisfies request"
,[kz_doc:id(Flow), kapps_im:account_id(Im)]),
Updaters = [{fun kapps_im:kvs_store_proplist/2
,[{'tf_flow_id', kz_doc:id(Flow)}
,{'tf_flow', kz_json:get_value(<<"flow">>, Flow)}
,{'tf_no_match', NoMatch}
]
}
],
{'ok', Pid} = tf_exe_sup:new(kapps_im:exec(Updaters, Im)),
MonitorRef = erlang:monitor(process, Pid),
receive
{'DOWN', MonitorRef, 'process', Pid, {shutdown, Reason}} ->
lager:info("textflow result : ~p", [Reason]),
ack(Context);
{'DOWN', MonitorRef, 'process', Pid, Reason} ->
lager:info("textflow result : ~p", [Reason]),
ack(Context)
end.
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/applications/doodle/src/doodle_listener.erl | erlang | -----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
=============================================================================
API
=============================================================================
------------------------------------------------------------------------------
@doc Starts the server.
@end
------------------------------------------------------------------------------
optional to include
optional to include
optional to include
=============================================================================
gen_server callbacks
=============================================================================
------------------------------------------------------------------------------
@doc Initializes the server.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Handling call messages.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Handling cast messages.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Handling all non call/cast messages.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Allows listener to pass options to handlers.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc This function is called by a `gen_server' when it is about to
terminate. It should be the opposite of `Module:init/1' and do any
necessary cleaning up. When it returns, the `gen_server' terminates
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Convert process state when code is changed.
@end
------------------------------------------------------------------------------
=============================================================================
=============================================================================
=============================================================================
Handle Inbound
=============================================================================
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
nack(#{server := Server
,deliver := Deliver
}) -> gen_listener:nack(Server, Deliver).
=============================================================================
Route Message
=============================================================================
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
to use it for this message | ( C ) 2010 - 2020 , 2600Hz
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(doodle_listener).
-behaviour(gen_listener).
-export([start_link/0]).
Responders
-export([handle_message/2
]).
-export([init/1
,handle_call/3
,handle_cast/2
,handle_info/2
,handle_event/2
,terminate/2
,code_change/3
]).
-include("doodle.hrl").
-define(SERVER, ?MODULE).
-type state() :: map().
-type context() :: map().
-define(BINDINGS, [{'im', [{'restrict_to', ['inbound']}
,{'im_types', ['sms']}
]
}
]).
-define(QUEUE_NAME, <<"doodle">>).
-define(QUEUE_OPTIONS, [{'exclusive', 'false'}
,{'durable', 'true'}
,{'auto_delete', 'false'}
,{'arguments', [{<<"x-message-ttl">>, 'infinity'}
,{<<"x-max-length">>, 'infinity'}
]}
]).
-define(CONSUME_OPTIONS, [{'exclusive', 'false'}
,{'no_ack', 'false'}
]).
-define(RESPONDERS, [{{?MODULE, 'handle_message'}, [{<<"sms">>, <<"inbound">>}]}]).
-define(AMQP_PUBLISH_OPTIONS, [{'mandatory', 'true'}
,{'delivery_mode', 2}
]).
-define(ROUTE_TIMEOUT, 'infinity').
-spec start_link() -> kz_types:startlink_ret().
start_link() ->
gen_listener:start_link(?MODULE
,[{'bindings', ?BINDINGS}
,{'responders', ?RESPONDERS}
]
,[]
).
-spec init([]) -> {'ok', state()}.
init([]) ->
{'ok', #{}}.
-spec handle_call(any(), kz_term:pid_ref(), state()) -> kz_types:handle_call_ret_state(state()).
handle_call(_Request, _From, State) ->
{'reply', {'error', 'not_implemented'}, State}.
-spec handle_cast(any(), state()) -> kz_types:handle_cast_ret_state(state()).
handle_cast({'gen_listener', {'created_queue', _Q}}, State) ->
{'noreply', State};
handle_cast({'gen_listener', {'is_consuming', _IsConsuming}}, State) ->
{'noreply', State};
handle_cast(_Msg, State) ->
{'noreply', State}.
-spec handle_info(any(), state()) -> kz_types:handle_info_ret_state(state()).
handle_info(_Info, State) ->
{'noreply', State}.
-spec handle_event(kz_json:object(), state()) -> gen_listener:handle_event_return().
handle_event(_JObj, _State) ->
{'reply', []}.
with . The return value is ignored .
-spec terminate(any(), state()) -> 'ok'.
terminate(_Reason, _State) ->
lager:debug("listener terminating: ~p", [_Reason]).
-spec code_change(any(), state(), any()) -> {'ok', state()}.
code_change(_OldVsn, State, _Extra) ->
{'ok', State}.
Internal functions
-spec handle_message(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_message(JObj, Props) ->
Srv = props:get_value('server', Props),
Deliver = props:get_value('deliver', Props),
case kapi_im:inbound_v(JObj) of
'true' ->
Context = inbound_context(JObj, Props),
kz_log:put_callid(kz_im:message_id(JObj)),
handle_inbound(Context);
'false' ->
lager:debug("error validating inbound message : ~p", [JObj]),
gen_listener:nack(Srv, Deliver)
end.
-spec inbound_context(kz_json:object(), kz_term:proplist()) -> context().
inbound_context(JObj, Props) ->
Srv = props:get_value('server', Props),
Deliver = props:get_value('deliver', Props),
Basic = props:get_value('basic', Props),
{Number, Inception} = doodle_util:get_inbound_destination(JObj),
#{number => Number
,inception => Inception
,request => JObj
,route_id => kz_im:route_id(JObj)
,route_type => kz_im:route_type(JObj)
,basic => Basic
,deliver => Deliver
,server => Srv
}.
-spec handle_inbound(context()) -> 'ok'.
handle_inbound(#{number := Number} = Context0) ->
Routines = [fun custom_vars/1
,fun custom_header_token/1
,fun lookup_number/1
,fun account_from_number/1
,fun set_inception/1
,fun lookup_mdn/1
,fun create_im/1
],
case kz_maps:exec(Routines, Context0) of
#{account_id := _AccountId} = Context ->
lager:info("processing inbound sms request ~s in account ~s", [Number, _AccountId]),
route_message(Context);
Context ->
lager:info("unable to determine account for ~s => ~p", [Number, Context]),
TODO send system notify ?
ack(Context)
end.
ack(#{server := Server
,deliver := Deliver
}) -> gen_listener:ack(Server, Deliver).
custom_vars(#{authorizing_id := _} = Map) -> Map;
custom_vars(#{request := JObj} = Map) ->
CCVsFilter = [<<"Account-ID">>, <<"Authorizing-ID">>],
CCVs = kz_json:get_json_value(<<"Custom-Vars">>, JObj, kz_json:new()),
Filtered = [{CCV, V} || CCV <- CCVsFilter, (V = kz_json:get_value(CCV, CCVs)) =/= 'undefined'],
lists:foldl(fun custom_var/2, Map, Filtered).
custom_var({K,V}, Map) ->
maps:put(kz_term:to_atom(kz_json:normalize_key(K), 'true'), V, Map).
custom_header_token(#{authorizing_id := _} = Map) -> Map;
custom_header_token(#{request := JObj} = Map) ->
case kz_json:get_ne_binary_value([<<"Custom-SIP-Headers">>, <<"X-AUTH-Token">>], JObj) of
'undefined' -> Map;
Token ->
custom_header_token(Map, JObj, Token)
end.
custom_header_token(Map, JObj, Token) ->
case binary:split(Token, <<"@">>, ['global']) of
[AuthorizingId, AccountId | _] ->
AccountRealm = kzd_accounts:fetch_realm(AccountId),
AccountDb = kzs_util:format_account_db(AccountId),
case kz_datamgr:open_cache_doc(AccountDb, AuthorizingId) of
{'ok', Doc} ->
Props = props:filter_undefined([{?CV(<<"Authorizing-Type">>), kz_doc:type(Doc)}
,{?CV(<<"Authorizing-ID">>), AuthorizingId}
,{?CV(<<"Owner-ID">>), kzd_devices:owner_id(Doc)}
,{?CV(<<"Account-ID">>), AccountId}
,{?CV(<<"Realm">>), AccountRealm}
]),
Map#{authorizing_id => AuthorizingId
,account_id => AccountId
,request => kz_json:set_values(Props, JObj)
};
_Else ->
lager:warning("unexpected result reading doc ~s/~s => ~p", [AuthorizingId, AccountId, _Else]),
Map
end;
_Else ->
lager:warning("unexpected result spliting Token => ~p", [_Else]),
Map
end.
lookup_number(#{account_id := _AccountId} = Map) -> Map;
lookup_number(#{number := Number} = Map) ->
case knm_phone_number:fetch(Number) of
{'error', _R} ->
lager:info("unable to determine account for ~s: ~p", [Number, _R]),
Map;
{'ok', KNumber} ->
Map#{phone_number => KNumber, used_by => knm_phone_number:used_by(KNumber)}
end;
lookup_number(Map) ->
Map.
account_from_number(#{account_id := _AccountId} = Map) -> Map;
account_from_number(#{phone_number := KNumber, request := JObj} = Map) ->
case knm_phone_number:assigned_to(KNumber) of
'undefined' -> Map;
AccountId ->
Props = [{<<"Account-ID">>, AccountId}
,{?CV(<<"Account-ID">>), AccountId}
,{?CV(<<"Authorizing-Type">>), <<"resource">>}
],
Map#{account_id => AccountId
,request => kz_json:set_values(Props, JObj)
}
end;
account_from_number(Map) ->
Map.
-spec set_inception(context()) -> context().
set_inception(#{inception := <<"offnet">>, request := JObj} = Map) ->
Request = kz_json:get_value(<<"From">>, JObj),
Map#{request => kz_json:set_value(?CV(<<"Inception">>), Request, JObj)};
set_inception(#{request := JObj} = Map) ->
Map#{request => kz_json:delete_keys([<<"Inception">>, ?CV(<<"Inception">>)], JObj)}.
-spec lookup_mdn(context()) -> context().
lookup_mdn(#{authorizing_id := _AuthorizingId} = Map) -> Map;
lookup_mdn(#{phone_number := KNumber, request := JObj} = Map) ->
Number = knm_phone_number:number(KNumber),
case doodle_util:lookup_mdn(Number) of
{'ok', Id, OwnerId} ->
Props = props:filter_undefined([{?CV(<<"Authorizing-Type">>), <<"device">>}
,{?CV(<<"Authorizing-ID">>), Id}
,{?CV(<<"Owner-ID">>), OwnerId}
]),
JObj1 = kz_json:delete_keys([?CV(<<"Authorizing-Type">>)
,?CV(<<"Authorizing-ID">>)
], JObj),
Map#{request => kz_json:set_values(Props, JObj1)};
{'error', _} -> Map
end;
lookup_mdn(Map) -> Map.
-spec create_im(context()) -> context().
create_im(#{request:= SmsReq, account_id := AccountId} = Map) ->
Funs = [{fun kapps_im:set_application_name/2, ?APP_NAME}
,{fun kapps_im:set_application_version/2, ?APP_VERSION}
,{fun kapps_im:set_account_id/2, AccountId}
,fun maybe_update_sender/1
],
IM = kapps_im:exec(Funs, kapps_im:from_payload(SmsReq)),
Map#{fetch_id => kapps_im:message_id(IM)
,message_id => kapps_im:message_id(IM)
,im => IM
};
create_im(Map) -> Map.
-spec maybe_update_sender(kapps_im:im()) -> kapps_im:im().
maybe_update_sender(Im) ->
case kapps_im:endpoint(Im) of
'undefined' -> Im;
EP ->
CID = kzd_devices:caller_id(EP, kz_json:new()),
From = kzd_caller_id:internal_number(CID, kapps_im:from(Im)),
kapps_im:set_from(From, Im)
end.
-spec route_message(context()) -> 'ok'.
route_message(#{im := Im} = Context) ->
AllowNoMatch = allow_no_match(Im),
case kz_flow:lookup(Im) of
if is false then allow the textflow or if it is true and we are able allowed
{'ok', Flow, NoMatch} when (not NoMatch)
orelse AllowNoMatch ->
route_message(Context, Flow, NoMatch);
{'ok', _, 'true'} ->
lager:info("only available flow is a nomatch for a unauthorized message"),
ack(Context);
{'error', R} ->
lager:info("unable to find flow ~p", [R]),
ack(Context)
end.
-spec allow_no_match(kapps_im:im()) -> boolean().
allow_no_match(Im) ->
allow_no_match_type(Im).
-spec allow_no_match_type(kapps_im:im()) -> boolean().
allow_no_match_type(Im) ->
case kapps_im:authorizing_type(Im) of
'undefined' -> 'false';
<<"resource">> -> 'false';
<<"sys_info">> -> 'false';
_ -> 'true'
end.
-spec route_message(context(), kz_json:object(), boolean()) -> 'ok'.
route_message(#{im := Im} = Context, Flow, NoMatch) ->
lager:info("flow ~s in ~s satisfies request"
,[kz_doc:id(Flow), kapps_im:account_id(Im)]),
Updaters = [{fun kapps_im:kvs_store_proplist/2
,[{'tf_flow_id', kz_doc:id(Flow)}
,{'tf_flow', kz_json:get_value(<<"flow">>, Flow)}
,{'tf_no_match', NoMatch}
]
}
],
{'ok', Pid} = tf_exe_sup:new(kapps_im:exec(Updaters, Im)),
MonitorRef = erlang:monitor(process, Pid),
receive
{'DOWN', MonitorRef, 'process', Pid, {shutdown, Reason}} ->
lager:info("textflow result : ~p", [Reason]),
ack(Context);
{'DOWN', MonitorRef, 'process', Pid, Reason} ->
lager:info("textflow result : ~p", [Reason]),
ack(Context)
end.
|
d204b0c15e3e232155042ab739688bb7c4cbfca8fb61364642c5659b963ee50c | den1k/vimsical | error.cljc | (ns vimsical.remotes.error
(:require
[clojure.spec.alpha :as s]))
(s/def ::remote keyword?)
(s/def ::backoff int?)
(s/def ::reason string?)
(s/def ::message string?)
(s/def ::error (s/keys :req [::remote ::event] :opt [::backoff ::reason ::message]))
| null | https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/src/common/vimsical/remotes/error.cljc | clojure | (ns vimsical.remotes.error
(:require
[clojure.spec.alpha :as s]))
(s/def ::remote keyword?)
(s/def ::backoff int?)
(s/def ::reason string?)
(s/def ::message string?)
(s/def ::error (s/keys :req [::remote ::event] :opt [::backoff ::reason ::message]))
| |
7bd413ae4807fd43bda77e667c686904876b8402db88227f3fba1e1d5d27c37a | alpha123/cl-template | packages.lisp | (defpackage #:cl-template
(:use #:cl)
(:nicknames #:clt)
(:export #:compile-template #:*add-progn-to-if*))
;; Symbols that can be used in templates.
(defpackage #:cl-template-template-symbols
(:use #:cl))
| null | https://raw.githubusercontent.com/alpha123/cl-template/46193a9a389bb950530e579eae7e6e5a18184832/packages.lisp | lisp | Symbols that can be used in templates. | (defpackage #:cl-template
(:use #:cl)
(:nicknames #:clt)
(:export #:compile-template #:*add-progn-to-if*))
(defpackage #:cl-template-template-symbols
(:use #:cl))
|
ee5699e93dbfa4fcb9361620f8cfa7c7910e6cc2e7b8479fe5e0d26217dc5dd6 | kana/sicp | ex-3.37.scm | Exercise 3.37 . procedure is cumbersome
;;; when compared with a more expression-oriented style of definition, such as
;;;
;;; (define (celsius-fahrenheit-converter x)
( c+ ( c * ( c/ ( cv 9 ) ( cv 5 ) )
;;; x)
( cv 32 ) ) )
;;; (define C (make-connector))
;;; (define F (celsius-fahrenheit-converter C))
;;;
;;; Here c+, c*, etc. are the ``constraint'' versions of the arithmetic
operations . For example , c+ takes two connectors as arguments and returns
;;; a connector that is related to these by an adder constraint:
;;;
;;; (define (c+ x y)
;;; (let ((z (make-connector)))
;;; (adder x y z)
;;; z))
;;;
Define analogous procedures c- , c * , c/ , and ( constant value ) that enable
us to define compound constraints as in the converter example above . [ 33 ]
(load "./sec-3.3.5.scm")
(define (c+ x y)
(let ((z (make-connector)))
(adder x y z)
z))
(define (c- x y)
(let ((z (make-connector)))
(adder z y x)
z))
(define (c* x y)
(let ((z (make-connector)))
(multiplier x y z)
z))
(define (c/ x y)
(let ((z (make-connector)))
(multiplier z y x)
z))
(define (cv v)
(let ((z (make-connector)))
(set-value! z v 'constant)
z))
(define (celsius-fahrenheit-converter x)
(c+ (c* (c/ (cv 9) (cv 5))
x)
(cv 32)))
(define C (make-connector))
(define F (celsius-fahrenheit-converter C))
(probe "C" C)
(probe "F" F)
(set-value! C 25 'user)
(forget-value! C 'user)
(set-value! F 212 'user)
| null | https://raw.githubusercontent.com/kana/sicp/912bda4276995492ffc2ec971618316701e196f6/ex-3.37.scm | scheme | when compared with a more expression-oriented style of definition, such as
(define (celsius-fahrenheit-converter x)
x)
(define C (make-connector))
(define F (celsius-fahrenheit-converter C))
Here c+, c*, etc. are the ``constraint'' versions of the arithmetic
a connector that is related to these by an adder constraint:
(define (c+ x y)
(let ((z (make-connector)))
(adder x y z)
z))
| Exercise 3.37 . procedure is cumbersome
( c+ ( c * ( c/ ( cv 9 ) ( cv 5 ) )
( cv 32 ) ) )
operations . For example , c+ takes two connectors as arguments and returns
Define analogous procedures c- , c * , c/ , and ( constant value ) that enable
us to define compound constraints as in the converter example above . [ 33 ]
(load "./sec-3.3.5.scm")
(define (c+ x y)
(let ((z (make-connector)))
(adder x y z)
z))
(define (c- x y)
(let ((z (make-connector)))
(adder z y x)
z))
(define (c* x y)
(let ((z (make-connector)))
(multiplier x y z)
z))
(define (c/ x y)
(let ((z (make-connector)))
(multiplier z y x)
z))
(define (cv v)
(let ((z (make-connector)))
(set-value! z v 'constant)
z))
(define (celsius-fahrenheit-converter x)
(c+ (c* (c/ (cv 9) (cv 5))
x)
(cv 32)))
(define C (make-connector))
(define F (celsius-fahrenheit-converter C))
(probe "C" C)
(probe "F" F)
(set-value! C 25 'user)
(forget-value! C 'user)
(set-value! F 212 'user)
|
f9460e4a422b02512791e3bb3c63726398b69d1e33aea3c378e947b3ce912c36 | youjinbou/gmaths | mersenneTwister.mli |
module Period : sig
val n : int
val m : int
end
module State : sig
type t
val create : unit -> t
val mt : t -> int64 array
val idx : t -> int
val incr_idx : t -> unit
val reset_idx : t -> unit
val init : t -> int64 -> t
val make : int64 -> t
val full_init : int array -> t
val make_self_init : unit -> t
end
module Core : sig
val rand : State.t -> int32
val int32 : State.t -> int32 -> int32
end
module Rng : sig
val int : State.t -> int -> int
val int32 : State.t -> int32 -> int32
val int64 : State.t -> int64 -> int64
val nativeint : State.t -> nativeint -> nativeint
val rawsingle : State.t -> float
val rawdouble : State.t -> float
val single : State.t -> float -> float
val float : State.t -> float -> float
val bool : State.t -> bool
end
(* state as a module-scoped value *)
module type DATA = sig
val state : State.t
end
module Make : functor (D : DATA) -> sig
val state : State.t
val rand : unit -> int32
val int32 : int32 -> int32
val int64 : int64 -> int64
val int : int -> int
val nativeint : nativeint -> nativeint
val float : float -> float
val bool : bool
end
| null | https://raw.githubusercontent.com/youjinbou/gmaths/1a507444071941a45b39f8c65e90c37427ea68a3/src/rng/mersenneTwister.mli | ocaml | state as a module-scoped value |
module Period : sig
val n : int
val m : int
end
module State : sig
type t
val create : unit -> t
val mt : t -> int64 array
val idx : t -> int
val incr_idx : t -> unit
val reset_idx : t -> unit
val init : t -> int64 -> t
val make : int64 -> t
val full_init : int array -> t
val make_self_init : unit -> t
end
module Core : sig
val rand : State.t -> int32
val int32 : State.t -> int32 -> int32
end
module Rng : sig
val int : State.t -> int -> int
val int32 : State.t -> int32 -> int32
val int64 : State.t -> int64 -> int64
val nativeint : State.t -> nativeint -> nativeint
val rawsingle : State.t -> float
val rawdouble : State.t -> float
val single : State.t -> float -> float
val float : State.t -> float -> float
val bool : State.t -> bool
end
module type DATA = sig
val state : State.t
end
module Make : functor (D : DATA) -> sig
val state : State.t
val rand : unit -> int32
val int32 : int32 -> int32
val int64 : int64 -> int64
val int : int -> int
val nativeint : nativeint -> nativeint
val float : float -> float
val bool : bool
end
|
c6faf27a1f667cbad052af358ee73c2a0be167346ae76d3784d19887a49c1f9c | tomgr/libcspm | Annotated.hs | # LANGUAGE DeriveGeneric , FlexibleContexts , FlexibleInstances #
module Util.Annotated where
import qualified Data.ByteString as B
import Data.Hashable
import GHC.Generics (Generic)
import Prelude
import Util.Exception
import Util.Prelude
import Util.PrettyPrint
data SrcLoc =
SrcLoc {
srcLocFile :: !B.ByteString,
srcLocLine :: {-# UNPACK #-} !Int,
srcLocCol :: {-# UNPACK #-} !Int
}
| NoLoc
deriving Eq
instance Ord SrcLoc where
(SrcLoc f1 l1 c1) `compare` (SrcLoc f2 l2 c2) =
(f1 `compare` f2) `thenCmp`
(l1 `compare` l2) `thenCmp`
(c1 `compare` c2)
NoLoc `compare` NoLoc = EQ
NoLoc `compare` _ = GT
_ `compare` NoLoc = LT
From GHC
data SrcSpan =
SrcSpanOneLine {
srcSpanFile :: !B.ByteString,
srcSpanLine :: {-# UNPACK #-} !Int,
srcSpanSCol :: {-# UNPACK #-} !Int,
srcSpanECol :: {-# UNPACK #-} !Int
}
| SrcSpanMultiLine {
srcSpanFile :: !B.ByteString,
srcSpanSLine :: {-# UNPACK #-} !Int,
srcSpanSCol :: {-# UNPACK #-} !Int,
srcSpanELine :: {-# UNPACK #-} !Int,
srcSpanECol :: {-# UNPACK #-} !Int
}
| SrcSpanPoint {
srcSpanFile :: !B.ByteString,
srcSpanLine :: {-# UNPACK #-} !Int,
srcSpanCol :: {-# UNPACK #-} !Int
}
| Unknown
-- | A builtin thing
| BuiltIn
deriving (Eq, Generic)
instance Hashable SrcSpan
srcSpanStart :: SrcSpan -> SrcLoc
srcSpanStart (SrcSpanOneLine f l sc _) = SrcLoc f l sc
srcSpanStart (SrcSpanMultiLine f sl sc _ _) = SrcLoc f sl sc
srcSpanStart (SrcSpanPoint f l c) = SrcLoc f l c
srcSpanStart BuiltIn = NoLoc
srcSpanStart Unknown = NoLoc
srcSpanEnd :: SrcSpan -> SrcLoc
srcSpanEnd (SrcSpanOneLine f l _ ec) = SrcLoc f l ec
srcSpanEnd (SrcSpanMultiLine f _ _ el ec) = SrcLoc f el ec
srcSpanEnd (SrcSpanPoint f l c) = SrcLoc f l c
srcSpanEnd BuiltIn = NoLoc
srcSpanEnd Unknown = NoLoc
We want to order SrcSpans first by the start point , then by the end point .
instance Ord SrcSpan where
a `compare` b =
(srcSpanStart a `compare` srcSpanStart b) `thenCmp`
(srcSpanEnd a `compare` srcSpanEnd b)
instance Show SrcSpan where
show s = show (prettyPrint s)
instance PrettyPrintable SrcSpan where
prettyPrint (SrcSpanOneLine f sline scol1 ecol1) =
bytestring f <> colon <> int sline <> colon <> int scol1 <> char '-' <> int ecol1
prettyPrint (SrcSpanMultiLine f sline scol eline ecol) =
bytestring f <> colon <> int sline <> colon <> int scol
<> char '-'
<> int eline <> colon <> int ecol
prettyPrint (SrcSpanPoint f sline scol) =
bytestring f <> colon <> int sline <> colon <> int scol
prettyPrint Unknown = text "<unknown location>"
prettyPrint BuiltIn = text "<built-in>"
combineSpans :: SrcSpan -> SrcSpan -> SrcSpan
combineSpans s1 s2 | srcSpanFile s1 /= srcSpanFile s2 = panic $ show $
text "Cannot combine spans as they span files"
$$ tabIndent (prettyPrint s1 $$ prettyPrint s2)
combineSpans (SrcSpanOneLine f1 line1 scol1 _)
(SrcSpanOneLine _ line2 _ ecol2) =
if line1 == line2 then SrcSpanOneLine f1 line1 scol1 ecol2
else SrcSpanMultiLine f1 line1 scol1 line2 ecol2
combineSpans (SrcSpanOneLine f1 sline1 scol1 _)
(SrcSpanMultiLine _ _ _ eline2 ecol2) =
SrcSpanMultiLine f1 sline1 scol1 eline2 ecol2
combineSpans (SrcSpanMultiLine f1 sline1 scol1 _ _)
(SrcSpanOneLine _ eline2 _ ecol2) =
SrcSpanMultiLine f1 sline1 scol1 eline2 ecol2
combineSpans (SrcSpanMultiLine f1 sline1 scol1 _ _)
(SrcSpanMultiLine _ _ _ eline2 ecol2) =
SrcSpanMultiLine f1 sline1 scol1 eline2 ecol2
combineSpans s1 s2 = panic $ show $
text "combineSpans: invalid spans combined"
$$ tabIndent (prettyPrint s1 $$ prettyPrint s2)
data Located a =
L {
locatedLoc :: SrcSpan,
locatedInner :: a
}
data Annotated a b =
An {
loc :: SrcSpan,
annotation :: a,
inner :: b
}
dummyAnnotation :: a
dummyAnnotation = panic "Dummy annotation evaluated"
unAnnotate :: Annotated a b -> b
unAnnotate (An _ _ b) = b
instance Show b => Show (Annotated a b) where
show (An _ _ b) = show b
instance Show a => Show (Located a) where
show (L _ a) = show a
instance (PrettyPrintable [b]) => PrettyPrintable [Annotated a b] where
prettyPrint ans = prettyPrint (map unAnnotate ans)
instance (PrettyPrintable b) => PrettyPrintable (Annotated a b) where
prettyPrint (An _ _ inner) = prettyPrint inner
instance (PrettyPrintable a) => PrettyPrintable (Located a) where
prettyPrint (L _ inner) = prettyPrint inner
instance Eq b => Eq (Annotated a b) where
(An _ _ b1) == (An _ _ b2) = b1 == b2
instance Eq a => Eq (Located a) where
(L _ b1) == (L _ b2) = b1 == b2
instance Ord b => Ord (Annotated a b) where
compare a b = compare (unAnnotate a) (unAnnotate b)
instance Ord b => Ord (Located b) where
compare a b = compare (locatedInner a) (locatedInner b)
instance Hashable b => Hashable (Annotated a b) where
hashWithSalt s a = hashWithSalt s (unAnnotate a)
hash a = hash (unAnnotate a)
| null | https://raw.githubusercontent.com/tomgr/libcspm/24d1b41954191a16e3b5e388e35f5ba0915d671e/src/Util/Annotated.hs | haskell | # UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
| A builtin thing | # LANGUAGE DeriveGeneric , FlexibleContexts , FlexibleInstances #
module Util.Annotated where
import qualified Data.ByteString as B
import Data.Hashable
import GHC.Generics (Generic)
import Prelude
import Util.Exception
import Util.Prelude
import Util.PrettyPrint
data SrcLoc =
SrcLoc {
srcLocFile :: !B.ByteString,
}
| NoLoc
deriving Eq
instance Ord SrcLoc where
(SrcLoc f1 l1 c1) `compare` (SrcLoc f2 l2 c2) =
(f1 `compare` f2) `thenCmp`
(l1 `compare` l2) `thenCmp`
(c1 `compare` c2)
NoLoc `compare` NoLoc = EQ
NoLoc `compare` _ = GT
_ `compare` NoLoc = LT
From GHC
data SrcSpan =
SrcSpanOneLine {
srcSpanFile :: !B.ByteString,
}
| SrcSpanMultiLine {
srcSpanFile :: !B.ByteString,
}
| SrcSpanPoint {
srcSpanFile :: !B.ByteString,
}
| Unknown
| BuiltIn
deriving (Eq, Generic)
instance Hashable SrcSpan
srcSpanStart :: SrcSpan -> SrcLoc
srcSpanStart (SrcSpanOneLine f l sc _) = SrcLoc f l sc
srcSpanStart (SrcSpanMultiLine f sl sc _ _) = SrcLoc f sl sc
srcSpanStart (SrcSpanPoint f l c) = SrcLoc f l c
srcSpanStart BuiltIn = NoLoc
srcSpanStart Unknown = NoLoc
srcSpanEnd :: SrcSpan -> SrcLoc
srcSpanEnd (SrcSpanOneLine f l _ ec) = SrcLoc f l ec
srcSpanEnd (SrcSpanMultiLine f _ _ el ec) = SrcLoc f el ec
srcSpanEnd (SrcSpanPoint f l c) = SrcLoc f l c
srcSpanEnd BuiltIn = NoLoc
srcSpanEnd Unknown = NoLoc
We want to order SrcSpans first by the start point , then by the end point .
instance Ord SrcSpan where
a `compare` b =
(srcSpanStart a `compare` srcSpanStart b) `thenCmp`
(srcSpanEnd a `compare` srcSpanEnd b)
instance Show SrcSpan where
show s = show (prettyPrint s)
instance PrettyPrintable SrcSpan where
prettyPrint (SrcSpanOneLine f sline scol1 ecol1) =
bytestring f <> colon <> int sline <> colon <> int scol1 <> char '-' <> int ecol1
prettyPrint (SrcSpanMultiLine f sline scol eline ecol) =
bytestring f <> colon <> int sline <> colon <> int scol
<> char '-'
<> int eline <> colon <> int ecol
prettyPrint (SrcSpanPoint f sline scol) =
bytestring f <> colon <> int sline <> colon <> int scol
prettyPrint Unknown = text "<unknown location>"
prettyPrint BuiltIn = text "<built-in>"
combineSpans :: SrcSpan -> SrcSpan -> SrcSpan
combineSpans s1 s2 | srcSpanFile s1 /= srcSpanFile s2 = panic $ show $
text "Cannot combine spans as they span files"
$$ tabIndent (prettyPrint s1 $$ prettyPrint s2)
combineSpans (SrcSpanOneLine f1 line1 scol1 _)
(SrcSpanOneLine _ line2 _ ecol2) =
if line1 == line2 then SrcSpanOneLine f1 line1 scol1 ecol2
else SrcSpanMultiLine f1 line1 scol1 line2 ecol2
combineSpans (SrcSpanOneLine f1 sline1 scol1 _)
(SrcSpanMultiLine _ _ _ eline2 ecol2) =
SrcSpanMultiLine f1 sline1 scol1 eline2 ecol2
combineSpans (SrcSpanMultiLine f1 sline1 scol1 _ _)
(SrcSpanOneLine _ eline2 _ ecol2) =
SrcSpanMultiLine f1 sline1 scol1 eline2 ecol2
combineSpans (SrcSpanMultiLine f1 sline1 scol1 _ _)
(SrcSpanMultiLine _ _ _ eline2 ecol2) =
SrcSpanMultiLine f1 sline1 scol1 eline2 ecol2
combineSpans s1 s2 = panic $ show $
text "combineSpans: invalid spans combined"
$$ tabIndent (prettyPrint s1 $$ prettyPrint s2)
data Located a =
L {
locatedLoc :: SrcSpan,
locatedInner :: a
}
data Annotated a b =
An {
loc :: SrcSpan,
annotation :: a,
inner :: b
}
dummyAnnotation :: a
dummyAnnotation = panic "Dummy annotation evaluated"
unAnnotate :: Annotated a b -> b
unAnnotate (An _ _ b) = b
instance Show b => Show (Annotated a b) where
show (An _ _ b) = show b
instance Show a => Show (Located a) where
show (L _ a) = show a
instance (PrettyPrintable [b]) => PrettyPrintable [Annotated a b] where
prettyPrint ans = prettyPrint (map unAnnotate ans)
instance (PrettyPrintable b) => PrettyPrintable (Annotated a b) where
prettyPrint (An _ _ inner) = prettyPrint inner
instance (PrettyPrintable a) => PrettyPrintable (Located a) where
prettyPrint (L _ inner) = prettyPrint inner
instance Eq b => Eq (Annotated a b) where
(An _ _ b1) == (An _ _ b2) = b1 == b2
instance Eq a => Eq (Located a) where
(L _ b1) == (L _ b2) = b1 == b2
instance Ord b => Ord (Annotated a b) where
compare a b = compare (unAnnotate a) (unAnnotate b)
instance Ord b => Ord (Located b) where
compare a b = compare (locatedInner a) (locatedInner b)
instance Hashable b => Hashable (Annotated a b) where
hashWithSalt s a = hashWithSalt s (unAnnotate a)
hash a = hash (unAnnotate a)
|
6d4c40bb149f2ac55d013276bda7ade7467b769e57ff6bc471b9915d791a63d2 | mbj/stratosphere | MonitoringResourcesProperty.hs | module Stratosphere.SageMaker.ModelBiasJobDefinition.MonitoringResourcesProperty (
module Exports, MonitoringResourcesProperty(..),
mkMonitoringResourcesProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.SageMaker.ModelBiasJobDefinition.ClusterConfigProperty as Exports
import Stratosphere.ResourceProperties
data MonitoringResourcesProperty
= MonitoringResourcesProperty {clusterConfig :: ClusterConfigProperty}
mkMonitoringResourcesProperty ::
ClusterConfigProperty -> MonitoringResourcesProperty
mkMonitoringResourcesProperty clusterConfig
= MonitoringResourcesProperty {clusterConfig = clusterConfig}
instance ToResourceProperties MonitoringResourcesProperty where
toResourceProperties MonitoringResourcesProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::ModelBiasJobDefinition.MonitoringResources",
supportsTags = Prelude.False,
properties = ["ClusterConfig" JSON..= clusterConfig]}
instance JSON.ToJSON MonitoringResourcesProperty where
toJSON MonitoringResourcesProperty {..}
= JSON.object ["ClusterConfig" JSON..= clusterConfig]
instance Property "ClusterConfig" MonitoringResourcesProperty where
type PropertyType "ClusterConfig" MonitoringResourcesProperty = ClusterConfigProperty
set newValue MonitoringResourcesProperty {}
= MonitoringResourcesProperty {clusterConfig = newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/sagemaker/gen/Stratosphere/SageMaker/ModelBiasJobDefinition/MonitoringResourcesProperty.hs | haskell | # SOURCE # | module Stratosphere.SageMaker.ModelBiasJobDefinition.MonitoringResourcesProperty (
module Exports, MonitoringResourcesProperty(..),
mkMonitoringResourcesProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
data MonitoringResourcesProperty
= MonitoringResourcesProperty {clusterConfig :: ClusterConfigProperty}
mkMonitoringResourcesProperty ::
ClusterConfigProperty -> MonitoringResourcesProperty
mkMonitoringResourcesProperty clusterConfig
= MonitoringResourcesProperty {clusterConfig = clusterConfig}
instance ToResourceProperties MonitoringResourcesProperty where
toResourceProperties MonitoringResourcesProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::ModelBiasJobDefinition.MonitoringResources",
supportsTags = Prelude.False,
properties = ["ClusterConfig" JSON..= clusterConfig]}
instance JSON.ToJSON MonitoringResourcesProperty where
toJSON MonitoringResourcesProperty {..}
= JSON.object ["ClusterConfig" JSON..= clusterConfig]
instance Property "ClusterConfig" MonitoringResourcesProperty where
type PropertyType "ClusterConfig" MonitoringResourcesProperty = ClusterConfigProperty
set newValue MonitoringResourcesProperty {}
= MonitoringResourcesProperty {clusterConfig = newValue, ..} |
e0adf4c06439d2db3ec691caf6f9d16850aff21d4b458c5aa89a639f8ab8bda6 | dym/movitz | run-time-context.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2003 - 2005 ,
Department of Computer Science , University of Tromsoe , Norway .
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
;;;; Filename: run-time-context.lisp
;;;; Description:
Author : < >
Created at : We d Nov 12 18:33:02 2003
;;;;
$ I d : run - time - context.lisp , v 1.23 2005/05/05 20:51:19 Exp $
;;;;
;;;;------------------------------------------------------------------
(require :muerte/basic-macros)
(require :muerte/los-closette)
(provide :muerte/run-time-context)
(in-package muerte)
;;;;
(defclass run-time-context-class (std-slotted-class built-in-class) ())
(defclass run-time-context (t)
((name
:initarg :name
:accessor run-time-context-name))
(:metaclass run-time-context-class))
(defmethod slot-value-using-class ((class run-time-context-class) object
(slot standard-effective-slot-definition))
(with-unbound-protect (svref (%run-time-context-slot object 'slots)
(slot-definition-location slot))
(slot-unbound class object (slot-definition-name slot))))
(defmethod (setf slot-value-using-class) (new-value (class run-time-context-class) object
(slot standard-effective-slot-definition))
(let ((location (slot-definition-location slot))
(slots (%run-time-context-slot object 'slots)))
(setf (svref slots location) new-value)))
(defmethod slot-boundp-using-class ((class run-time-context-class) object
(slot standard-effective-slot-definition))
(not (eq (load-global-constant new-unbound-value)
(svref (%run-time-context-slot object 'slots)
(slot-definition-location slot)))))
(defmethod allocate-instance ((class run-time-context-class) &rest initargs)
(declare (dynamic-extent initargs) (ignore initargs))
(let ((x (clone-run-time-context)))
(setf (%run-time-context-slot x 'class) class)
(setf (%run-time-context-slot x 'slots)
(allocate-slot-storage (count-if 'instance-slot-p (class-slots class))
(load-global-constant new-unbound-value)))
x))
(defmethod initialize-instance ((instance run-time-context) &rest initargs)
(declare (dynamic-extent initargs))
(apply 'shared-initialize instance t initargs))
(defmethod shared-initialize ((instance run-time-context) slot-names &rest all-keys)
(declare (dynamic-extent all-keys))
(dolist (slot (class-slots (class-of instance)))
(let ((slot-name (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties all-keys (slot-definition-initargs slot))
(declare (ignore init-key))
(if foundp
(setf (slot-value instance slot-name) init-value)
(when (and (not (slot-boundp instance slot-name))
(not (null (slot-definition-initfunction slot)))
(or (eq slot-names t)
(member slot-name slot-names)))
(let ((initfunction (slot-definition-initfunction slot)))
(setf (slot-value instance slot-name)
(etypecase initfunction
(cons (cadr initfunction)) ; '(quote <obj>)
(function (funcall initfunction))))))))))
instance)
(defmethod compute-effective-slot-reader ((class run-time-context-class) slot)
(let ((slot-location (slot-definition-location slot)))
(check-type slot-location positive-fixnum)
(lambda (instance)
(with-unbound-protect (svref (%run-time-context-slot instance 'slots) slot-location)
(slot-unbound-trampoline instance slot-location)))))
(defmethod compute-effective-slot-writer ((class run-time-context-class) slot)
(let ((slot-location (slot-definition-location slot)))
(check-type slot-location positive-fixnum)
(lambda (value instance)
(setf (svref (%run-time-context-slot instance 'slots) slot-location)
value))))
(defmethod print-object ((x run-time-context) stream)
(print-unreadable-object (x stream :type t :identity t)
(when (slot-boundp x 'name)
(format stream "~S" (run-time-context-name x))))
x)
;;;
(defun current-run-time-context ()
(current-run-time-context))
(defun find-run-time-context-slot (context slot-name &optional (errorp t))
(or (assoc slot-name (slot-value (class-of context) 'slot-map))
(when errorp
(error "No run-time-context slot named ~S in ~S." slot-name context))))
(defun %run-time-context-slot (context slot-name)
(let* ((context (or context (current-run-time-context)))
(slot (find-run-time-context-slot context slot-name)))
(ecase (second slot)
(word
(memref context -6 :index (third slot)))
(code-vector-word
(memref context -6 :index (third slot) :type :code-vector))
(lu32
(memref context -6 :index (third slot) :type :unsigned-byte32)))))
(defun (setf %run-time-context-slot) (value context slot-name)
(let* ((context (or context (current-run-time-context)))
(slot (find-run-time-context-slot context slot-name)))
(check-type context run-time-context)
(ecase (second slot)
(word
(setf (memref context -6 :index (third slot)) value))
(lu32
(setf (memref context -6 :index (third slot) :type :unsigned-byte32) value))
(code-vector-word
(setf (memref context -6 :index (third slot) :type :code-vector) value)))))
(defun clone-run-time-context (&key (parent (current-run-time-context))
(name :anonymous))
(check-type parent run-time-context)
(let ((context (%shallow-copy-object parent (movitz-type-word-size 'movitz-run-time-context))))
(setf (%run-time-context-slot context 'slots) (copy-seq (%run-time-context-slot parent 'slots))
(%run-time-context-slot context 'self) context
(%run-time-context-slot context 'atomically-continuation) 0)
context))
| null | https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/muerte/run-time-context.lisp | lisp | ------------------------------------------------------------------
For distribution policy, see the accompanying file COPYING.
Filename: run-time-context.lisp
Description:
------------------------------------------------------------------
'(quote <obj>)
| Copyright ( C ) 2003 - 2005 ,
Department of Computer Science , University of Tromsoe , Norway .
Author : < >
Created at : We d Nov 12 18:33:02 2003
$ I d : run - time - context.lisp , v 1.23 2005/05/05 20:51:19 Exp $
(require :muerte/basic-macros)
(require :muerte/los-closette)
(provide :muerte/run-time-context)
(in-package muerte)
(defclass run-time-context-class (std-slotted-class built-in-class) ())
(defclass run-time-context (t)
((name
:initarg :name
:accessor run-time-context-name))
(:metaclass run-time-context-class))
(defmethod slot-value-using-class ((class run-time-context-class) object
(slot standard-effective-slot-definition))
(with-unbound-protect (svref (%run-time-context-slot object 'slots)
(slot-definition-location slot))
(slot-unbound class object (slot-definition-name slot))))
(defmethod (setf slot-value-using-class) (new-value (class run-time-context-class) object
(slot standard-effective-slot-definition))
(let ((location (slot-definition-location slot))
(slots (%run-time-context-slot object 'slots)))
(setf (svref slots location) new-value)))
(defmethod slot-boundp-using-class ((class run-time-context-class) object
(slot standard-effective-slot-definition))
(not (eq (load-global-constant new-unbound-value)
(svref (%run-time-context-slot object 'slots)
(slot-definition-location slot)))))
(defmethod allocate-instance ((class run-time-context-class) &rest initargs)
(declare (dynamic-extent initargs) (ignore initargs))
(let ((x (clone-run-time-context)))
(setf (%run-time-context-slot x 'class) class)
(setf (%run-time-context-slot x 'slots)
(allocate-slot-storage (count-if 'instance-slot-p (class-slots class))
(load-global-constant new-unbound-value)))
x))
(defmethod initialize-instance ((instance run-time-context) &rest initargs)
(declare (dynamic-extent initargs))
(apply 'shared-initialize instance t initargs))
(defmethod shared-initialize ((instance run-time-context) slot-names &rest all-keys)
(declare (dynamic-extent all-keys))
(dolist (slot (class-slots (class-of instance)))
(let ((slot-name (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties all-keys (slot-definition-initargs slot))
(declare (ignore init-key))
(if foundp
(setf (slot-value instance slot-name) init-value)
(when (and (not (slot-boundp instance slot-name))
(not (null (slot-definition-initfunction slot)))
(or (eq slot-names t)
(member slot-name slot-names)))
(let ((initfunction (slot-definition-initfunction slot)))
(setf (slot-value instance slot-name)
(etypecase initfunction
(function (funcall initfunction))))))))))
instance)
(defmethod compute-effective-slot-reader ((class run-time-context-class) slot)
(let ((slot-location (slot-definition-location slot)))
(check-type slot-location positive-fixnum)
(lambda (instance)
(with-unbound-protect (svref (%run-time-context-slot instance 'slots) slot-location)
(slot-unbound-trampoline instance slot-location)))))
(defmethod compute-effective-slot-writer ((class run-time-context-class) slot)
(let ((slot-location (slot-definition-location slot)))
(check-type slot-location positive-fixnum)
(lambda (value instance)
(setf (svref (%run-time-context-slot instance 'slots) slot-location)
value))))
(defmethod print-object ((x run-time-context) stream)
(print-unreadable-object (x stream :type t :identity t)
(when (slot-boundp x 'name)
(format stream "~S" (run-time-context-name x))))
x)
(defun current-run-time-context ()
(current-run-time-context))
(defun find-run-time-context-slot (context slot-name &optional (errorp t))
(or (assoc slot-name (slot-value (class-of context) 'slot-map))
(when errorp
(error "No run-time-context slot named ~S in ~S." slot-name context))))
(defun %run-time-context-slot (context slot-name)
(let* ((context (or context (current-run-time-context)))
(slot (find-run-time-context-slot context slot-name)))
(ecase (second slot)
(word
(memref context -6 :index (third slot)))
(code-vector-word
(memref context -6 :index (third slot) :type :code-vector))
(lu32
(memref context -6 :index (third slot) :type :unsigned-byte32)))))
(defun (setf %run-time-context-slot) (value context slot-name)
(let* ((context (or context (current-run-time-context)))
(slot (find-run-time-context-slot context slot-name)))
(check-type context run-time-context)
(ecase (second slot)
(word
(setf (memref context -6 :index (third slot)) value))
(lu32
(setf (memref context -6 :index (third slot) :type :unsigned-byte32) value))
(code-vector-word
(setf (memref context -6 :index (third slot) :type :code-vector) value)))))
(defun clone-run-time-context (&key (parent (current-run-time-context))
(name :anonymous))
(check-type parent run-time-context)
(let ((context (%shallow-copy-object parent (movitz-type-word-size 'movitz-run-time-context))))
(setf (%run-time-context-slot context 'slots) (copy-seq (%run-time-context-slot parent 'slots))
(%run-time-context-slot context 'self) context
(%run-time-context-slot context 'atomically-continuation) 0)
context))
|
670a97bf5a759017accd913ca5cd37e58cc5087d3574141b0346c9ed0a941f9a | jwiegley/notes | parsec.hs | import Data.Functor.Identity
import Control.Applicative
import Text.Parsec
data Operation = Rename String String deriving Show
rename :: Parsec String () Operation
rename = Rename <$> (string "rename" *> many1 space *> many1 letter <* spaces)
<*> (many1 letter <* spaces <* eof)
main :: IO ()
main = print $ parse rename "" "rename foo bar" | null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/haskell/parsec.hs | haskell | import Data.Functor.Identity
import Control.Applicative
import Text.Parsec
data Operation = Rename String String deriving Show
rename :: Parsec String () Operation
rename = Rename <$> (string "rename" *> many1 space *> many1 letter <* spaces)
<*> (many1 letter <* spaces <* eof)
main :: IO ()
main = print $ parse rename "" "rename foo bar" | |
e8d0b8c0d71791079b8aa6d008d0e056278b19a5fd13f53c2602c0971cdd682a | ocaml-doc/voodoo | tailwind.ml | Tailwind module
let numeric base n =
if n < 0 then "-" ^ base ^ "-" ^ string_of_int (-n)
else base ^ "-" ^ string_of_int n
(* {2 Core Concepts} *)
let group = "group"
let group_hover x = "group-hover:" ^ x
(* {2 Layout} *)
let container = "container"
let block = "block"
let inline_block = "inline-block"
let flex = "flex"
let flex_none = "flex-none"
let flex_shrink = numeric "flex-shrink"
let inline_flex = "inline-flex"
let hidden = "hidden"
let float_right = "float-right"
let float_left = "float-left"
let overflow_auto = "overflow-auto"
let overflow_hidden = "overflow-hidden"
let truncate = "truncate"
let sticky = "sticky"
let relative = "relative"
let absolute = "absolute"
let transform = "transform"
let top = numeric "top"
let bottom = numeric "bottom"
let right = numeric "right"
let left = numeric "left"
let inset_x = numeric "inset-x"
let left_1_2 = "left-1/2"
let z = numeric "z"
(** {2 Flexbox} *)
let flex_row = "flex-row"
let flex_col = "flex-col"
let flex_1 = "flex-1"
(** {2 Grid} *)
let grid = "grid"
let gap n = "gap-" ^ string_of_int n
* { 2 Box alignment }
let justify_between = "justify-between"
let justify_start = "justify-start"
let items_center = "items-center"
let align_middle = "align-middle"
(* {2 Spacing} *)
let px = numeric "px"
let py = numeric "py"
let p = numeric "p"
let pb = numeric "pb"
let pr = numeric "pr"
let pl = numeric "pl"
let ml = numeric "ml"
let mt = numeric "mt"
let mb = numeric "mb"
let mx_auto = "mx-auto"
let m = numeric "m"
let my = numeric "my"
let space_x = numeric "space-x"
* { 2 Sizing }
let w = numeric "w"
let max_w_5xl = "max-w-5xl"
let max_w_7xl = "max-w-7xl"
let w_full = "w-full"
let w_auto = "w-auto"
let w_screen = "w-screen"
let h_screen = "h-screen"
let min_h_screen = "min-h-screen"
let h_full = "h-full"
let h = numeric "h"
let max_w_screen_xl = "max-w-screen-xl"
let max_w_xs = "max-w-xs"
let max_w_sm = "max-w-sm"
(** {2 Typeography} *)
let font_medium = "font-medium"
let font_normal = "font-normal"
let italic = "italic"
let list_disc = "list-disc"
let list_decimal = "list-decimal"
let font_semibold = "font-semibold"
let font_extrabold = "font-extrabold"
let font_sans = "font-sans"
let font_mono = "font-mono"
let font_roboto = "font-roboto"
let text_black = "text-black"
let text_white = "text-white"
let text_gray n = "text-gray-" ^ string_of_int n
let text_blue n = "text-blue-" ^ string_of_int n
let text_orangedark = "text-orangedark"
let opacity n = "opacity-" ^ string_of_int n
(* Text size *)
let text_sm = "text-sm"
let text_base = "text-base"
let text_lg = "text-lg"
let text_xl = "text-xl"
let text_2xl = "text-2xl"
let text_3xl = "text-3xl"
* { 2 Backgrounds }
let bg_gray n = "bg-gray-" ^ string_of_int n
let bg_yellow n = "bg-yellow-" ^ string_of_int n
let bg_red n = "bg-red-" ^ string_of_int n
let bg_white = "bg-white"
let bg_green n = "bg-green-" ^ string_of_int n
* { 2 Borders }
type border_width = [ `b0 | `b1 | `b2 | `b4 | `b6 | `b8 ]
let border_fn stem : border_width -> string = function
| `b0 -> stem ^ "-0"
| `b1 -> stem
| `b2 -> stem ^ "-2"
| `b4 -> stem ^ "-4"
| `b6 -> stem ^ "-6"
| `b8 -> stem ^ "-8"
let rounded_md = "rounded-md"
let rounded_lg = "rounded-lg"
let rounded_full = "rounded-full"
let rounded = "rounded"
let rounded_l_none = "rounded-l-none"
let border_t = border_fn "border-t"
let border_b = border_fn "border-b"
let border_l = border_fn "border-l"
let border_r = border_fn "border-r"
let border_yellow n = "border-yellow-" ^ string_of_int n
let border_opacity n = "border-opacity-" ^ string_of_int n
let border_gray n = "border-gray-" ^ string_of_int n
let border_blue n = "border-blue-" ^ string_of_int n
let border_orangedark = "border-orangedark"
let ring n = "ring-" ^ string_of_int n
let ring_black = "ring-black"
let ring_opacity n = "ring-opacity-" ^ string_of_int n
let ring_offset n = "ring-offset-" ^ string_of_int n
* { 2 Effects }
let ring_yellow n = "ring-yellow-" ^ string_of_int n
let ring_orangedark = "ring-orangedark"
let shadow = "shadow"
let shadow_lg = "shadow-lg"
(* Modifiers *)
let hover x = "hover:" ^ x
let sm x = "sm:" ^ x
let lg x = "lg:" ^ x
let md x = "md:" ^ x
let focus x = "focus:" ^ x
(** Accessibility *)
let sr_only = "sr-only"
* { 2 Interactivity }
let cursor_pointer = "cursor-pointer"
let outline_none = "outline-none"
let transition = "transition"
let ease_in_out = "ease-in-out"
let duration = numeric "duration-"
let fill_current = "fill-current"
let stroke_current = "stroke-current"
| null | https://raw.githubusercontent.com/ocaml-doc/voodoo/a57d7b4c12b5fa195d696bf39f4729a1ac7a7fc8/src/voodoo-web/tailwind.ml | ocaml | {2 Core Concepts}
{2 Layout}
* {2 Flexbox}
* {2 Grid}
{2 Spacing}
* {2 Typeography}
Text size
Modifiers
* Accessibility | Tailwind module
let numeric base n =
if n < 0 then "-" ^ base ^ "-" ^ string_of_int (-n)
else base ^ "-" ^ string_of_int n
let group = "group"
let group_hover x = "group-hover:" ^ x
let container = "container"
let block = "block"
let inline_block = "inline-block"
let flex = "flex"
let flex_none = "flex-none"
let flex_shrink = numeric "flex-shrink"
let inline_flex = "inline-flex"
let hidden = "hidden"
let float_right = "float-right"
let float_left = "float-left"
let overflow_auto = "overflow-auto"
let overflow_hidden = "overflow-hidden"
let truncate = "truncate"
let sticky = "sticky"
let relative = "relative"
let absolute = "absolute"
let transform = "transform"
let top = numeric "top"
let bottom = numeric "bottom"
let right = numeric "right"
let left = numeric "left"
let inset_x = numeric "inset-x"
let left_1_2 = "left-1/2"
let z = numeric "z"
let flex_row = "flex-row"
let flex_col = "flex-col"
let flex_1 = "flex-1"
let grid = "grid"
let gap n = "gap-" ^ string_of_int n
* { 2 Box alignment }
let justify_between = "justify-between"
let justify_start = "justify-start"
let items_center = "items-center"
let align_middle = "align-middle"
let px = numeric "px"
let py = numeric "py"
let p = numeric "p"
let pb = numeric "pb"
let pr = numeric "pr"
let pl = numeric "pl"
let ml = numeric "ml"
let mt = numeric "mt"
let mb = numeric "mb"
let mx_auto = "mx-auto"
let m = numeric "m"
let my = numeric "my"
let space_x = numeric "space-x"
* { 2 Sizing }
let w = numeric "w"
let max_w_5xl = "max-w-5xl"
let max_w_7xl = "max-w-7xl"
let w_full = "w-full"
let w_auto = "w-auto"
let w_screen = "w-screen"
let h_screen = "h-screen"
let min_h_screen = "min-h-screen"
let h_full = "h-full"
let h = numeric "h"
let max_w_screen_xl = "max-w-screen-xl"
let max_w_xs = "max-w-xs"
let max_w_sm = "max-w-sm"
let font_medium = "font-medium"
let font_normal = "font-normal"
let italic = "italic"
let list_disc = "list-disc"
let list_decimal = "list-decimal"
let font_semibold = "font-semibold"
let font_extrabold = "font-extrabold"
let font_sans = "font-sans"
let font_mono = "font-mono"
let font_roboto = "font-roboto"
let text_black = "text-black"
let text_white = "text-white"
let text_gray n = "text-gray-" ^ string_of_int n
let text_blue n = "text-blue-" ^ string_of_int n
let text_orangedark = "text-orangedark"
let opacity n = "opacity-" ^ string_of_int n
let text_sm = "text-sm"
let text_base = "text-base"
let text_lg = "text-lg"
let text_xl = "text-xl"
let text_2xl = "text-2xl"
let text_3xl = "text-3xl"
* { 2 Backgrounds }
let bg_gray n = "bg-gray-" ^ string_of_int n
let bg_yellow n = "bg-yellow-" ^ string_of_int n
let bg_red n = "bg-red-" ^ string_of_int n
let bg_white = "bg-white"
let bg_green n = "bg-green-" ^ string_of_int n
* { 2 Borders }
type border_width = [ `b0 | `b1 | `b2 | `b4 | `b6 | `b8 ]
let border_fn stem : border_width -> string = function
| `b0 -> stem ^ "-0"
| `b1 -> stem
| `b2 -> stem ^ "-2"
| `b4 -> stem ^ "-4"
| `b6 -> stem ^ "-6"
| `b8 -> stem ^ "-8"
let rounded_md = "rounded-md"
let rounded_lg = "rounded-lg"
let rounded_full = "rounded-full"
let rounded = "rounded"
let rounded_l_none = "rounded-l-none"
let border_t = border_fn "border-t"
let border_b = border_fn "border-b"
let border_l = border_fn "border-l"
let border_r = border_fn "border-r"
let border_yellow n = "border-yellow-" ^ string_of_int n
let border_opacity n = "border-opacity-" ^ string_of_int n
let border_gray n = "border-gray-" ^ string_of_int n
let border_blue n = "border-blue-" ^ string_of_int n
let border_orangedark = "border-orangedark"
let ring n = "ring-" ^ string_of_int n
let ring_black = "ring-black"
let ring_opacity n = "ring-opacity-" ^ string_of_int n
let ring_offset n = "ring-offset-" ^ string_of_int n
* { 2 Effects }
let ring_yellow n = "ring-yellow-" ^ string_of_int n
let ring_orangedark = "ring-orangedark"
let shadow = "shadow"
let shadow_lg = "shadow-lg"
let hover x = "hover:" ^ x
let sm x = "sm:" ^ x
let lg x = "lg:" ^ x
let md x = "md:" ^ x
let focus x = "focus:" ^ x
let sr_only = "sr-only"
* { 2 Interactivity }
let cursor_pointer = "cursor-pointer"
let outline_none = "outline-none"
let transition = "transition"
let ease_in_out = "ease-in-out"
let duration = numeric "duration-"
let fill_current = "fill-current"
let stroke_current = "stroke-current"
|
13ed581b56027d97c98363164754de0ec3a4546095b2df8295284b78f6f57982 | jorgetavares/core-gp | output.lisp |
(in-package #:core-gp)
;;;
;;; output
;;;
(defgeneric output-stats (stats run-best new-best-p output streams)
(:documentation "Output the stats of a single iteration."))
(defmethod output-stats ((stats fitness-stats) run-best new-best-p output streams)
"Outputs the computed stats according to the type of output."
(unless (eql output :none)
(when (member output '(:screen :screen+files))
(format t "generation ~a~%raw: ~a ~a ~a ~a ~a ~a~%fit: ~a ~a ~a ~a ~a ~a~%"
(iteration stats)
(run-best-raw-score stats) (best-raw-score stats) (worst-raw-score stats)
(mean-raw-score stats) (median-raw-score stats) (deviation-raw-score stats)
(run-best-fitness-score stats) (best-fitness-score stats)
(worst-fitness-score stats) (mean-fitness-score stats)
(median-fitness-score stats) (deviation-fitness-score stats)))
(when (member output '(:files :screen+files))
(format (first streams) "generation ~a~%raw: ~a ~a ~a ~a ~a ~a~%fit: ~a ~a ~a ~a ~a ~a~%"
(iteration stats)
(run-best-raw-score stats) (best-raw-score stats) (worst-raw-score stats)
(mean-raw-score stats) (median-raw-score stats) (deviation-raw-score stats)
(run-best-fitness-score stats) (best-fitness-score stats)
(worst-fitness-score stats) (mean-fitness-score stats)
(median-fitness-score stats) (deviation-fitness-score stats))
(when new-best-p
(format (second streams) "~a ~%" (list (iteration stats) run-best))))))
(defmethod output-stats ((stats tree-stats) run-best new-best-p output streams)
"Outputs the computed stats according to the type of output."
(unless (eql output :none)
(call-next-method)
(when (member output '(:screen :screen+files))
(format t "depth: ~a ~a ~a ~a ~a~%nodes: ~a ~a ~a ~a ~a~%"
(run-best-depth stats) (best-depth stats) (worst-depth stats)
(mean-depth stats) (deviation-depth stats)
(run-best-nodes-count stats) (best-nodes-count stats) (worst-nodes-count stats)
(mean-nodes-count stats) (deviation-nodes-count stats)))
(when (member output '(:files :screen+files))
(format (first streams) "depth: ~a ~a ~a ~a ~a~%nodes: ~a ~a ~a ~a ~a~%"
(run-best-depth stats) (best-depth stats) (worst-depth stats)
(mean-depth stats) (deviation-depth stats)
(run-best-nodes-count stats) (best-nodes-count stats) (worst-nodes-count stats)
(mean-nodes-count stats) (deviation-nodes-count stats)))))
(defmethod output-stats ((stats extra-tree-stats) run-best new-best-p output streams)
"Outputs the computed stats according to the type of output."
(unless (eql output :none)
(call-next-method)
(flet ((iterate-ht (table)
(loop for key being the hash-keys of table
using (hash-value value)
collect (list key value))))
(when (member output '(:screen :screen+files))
(format t "pop: ~a ~%best: ~a ~%run-best: ~a ~%"
(iterate-ht (sets-pop-counter stats))
(iterate-ht (sets-best-counter stats))
(iterate-ht (sets-run-best-counter stats))))
(when (member output '(:files :screen+files))
(format (first streams) "pop: ~a ~%best: ~a ~%run-best: ~a ~%"
(iterate-ht (sets-pop-counter stats))
(iterate-ht (sets-best-counter stats))
(iterate-ht (sets-run-best-counter stats)))))))
| null | https://raw.githubusercontent.com/jorgetavares/core-gp/90ec1c4599a19c5a911be1f703f78d5108aee160/src/output.lisp | lisp |
output
|
(in-package #:core-gp)
(defgeneric output-stats (stats run-best new-best-p output streams)
(:documentation "Output the stats of a single iteration."))
(defmethod output-stats ((stats fitness-stats) run-best new-best-p output streams)
"Outputs the computed stats according to the type of output."
(unless (eql output :none)
(when (member output '(:screen :screen+files))
(format t "generation ~a~%raw: ~a ~a ~a ~a ~a ~a~%fit: ~a ~a ~a ~a ~a ~a~%"
(iteration stats)
(run-best-raw-score stats) (best-raw-score stats) (worst-raw-score stats)
(mean-raw-score stats) (median-raw-score stats) (deviation-raw-score stats)
(run-best-fitness-score stats) (best-fitness-score stats)
(worst-fitness-score stats) (mean-fitness-score stats)
(median-fitness-score stats) (deviation-fitness-score stats)))
(when (member output '(:files :screen+files))
(format (first streams) "generation ~a~%raw: ~a ~a ~a ~a ~a ~a~%fit: ~a ~a ~a ~a ~a ~a~%"
(iteration stats)
(run-best-raw-score stats) (best-raw-score stats) (worst-raw-score stats)
(mean-raw-score stats) (median-raw-score stats) (deviation-raw-score stats)
(run-best-fitness-score stats) (best-fitness-score stats)
(worst-fitness-score stats) (mean-fitness-score stats)
(median-fitness-score stats) (deviation-fitness-score stats))
(when new-best-p
(format (second streams) "~a ~%" (list (iteration stats) run-best))))))
(defmethod output-stats ((stats tree-stats) run-best new-best-p output streams)
"Outputs the computed stats according to the type of output."
(unless (eql output :none)
(call-next-method)
(when (member output '(:screen :screen+files))
(format t "depth: ~a ~a ~a ~a ~a~%nodes: ~a ~a ~a ~a ~a~%"
(run-best-depth stats) (best-depth stats) (worst-depth stats)
(mean-depth stats) (deviation-depth stats)
(run-best-nodes-count stats) (best-nodes-count stats) (worst-nodes-count stats)
(mean-nodes-count stats) (deviation-nodes-count stats)))
(when (member output '(:files :screen+files))
(format (first streams) "depth: ~a ~a ~a ~a ~a~%nodes: ~a ~a ~a ~a ~a~%"
(run-best-depth stats) (best-depth stats) (worst-depth stats)
(mean-depth stats) (deviation-depth stats)
(run-best-nodes-count stats) (best-nodes-count stats) (worst-nodes-count stats)
(mean-nodes-count stats) (deviation-nodes-count stats)))))
(defmethod output-stats ((stats extra-tree-stats) run-best new-best-p output streams)
"Outputs the computed stats according to the type of output."
(unless (eql output :none)
(call-next-method)
(flet ((iterate-ht (table)
(loop for key being the hash-keys of table
using (hash-value value)
collect (list key value))))
(when (member output '(:screen :screen+files))
(format t "pop: ~a ~%best: ~a ~%run-best: ~a ~%"
(iterate-ht (sets-pop-counter stats))
(iterate-ht (sets-best-counter stats))
(iterate-ht (sets-run-best-counter stats))))
(when (member output '(:files :screen+files))
(format (first streams) "pop: ~a ~%best: ~a ~%run-best: ~a ~%"
(iterate-ht (sets-pop-counter stats))
(iterate-ht (sets-best-counter stats))
(iterate-ht (sets-run-best-counter stats)))))))
|
4898469c8f2021e4e6f391725c423c31c95ebc9b228dbe55cf792987ac9666f2 | ucsd-progsys/dsolve | sum-all-e.ml | let rec sum x = if x <= 0 then 0 else x + sum (x - 1)
let rec h y = assert ((y + y) <= sum y);h (y + 1)
let main () = h 0
| null | https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/negtests/sum-all-e.ml | ocaml | let rec sum x = if x <= 0 then 0 else x + sum (x - 1)
let rec h y = assert ((y + y) <= sum y);h (y + 1)
let main () = h 0
| |
5454966208fdc4087e401b9d0b755f997a920437b64cedff3be5e05af6c42154 | tonyg/kali-scheme | init.scm | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
; System entry and exit
Entry point from OS executive . Procedures returned by USUAL - RESUMER
are suitable for use as the second argument to WRITE - IMAGE .
(define (usual-resumer entry-point)
(lambda (resume-arg in out error)
(initialize-rts in out error
(lambda ()
(entry-point (vector->list resume-arg))))))
(define (initialize-rts in out error thunk)
(initialize-session-data!)
(initialize-dynamic-state!)
(initialize-output-port-list!)
(initialize-exceptions! current-error-port write-string
(lambda ()
(initialize-interrupts!
spawn-on-root
(lambda ()
(initialize-i/o (input-channel->port in)
(output-channel->port out)
zero - length buffer
(lambda ()
(with-threads
(lambda ()
(root-scheduler thunk
thread quantum , in msec
300)))))))))) ; port-flushing quantum
; Add the full/empty buffer handlers.
(initialize-i/o-handlers! define-exception-handler signal-exception)
| null | https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/rts/init.scm | scheme | System entry and exit
port-flushing quantum
Add the full/empty buffer handlers. | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
Entry point from OS executive . Procedures returned by USUAL - RESUMER
are suitable for use as the second argument to WRITE - IMAGE .
(define (usual-resumer entry-point)
(lambda (resume-arg in out error)
(initialize-rts in out error
(lambda ()
(entry-point (vector->list resume-arg))))))
(define (initialize-rts in out error thunk)
(initialize-session-data!)
(initialize-dynamic-state!)
(initialize-output-port-list!)
(initialize-exceptions! current-error-port write-string
(lambda ()
(initialize-interrupts!
spawn-on-root
(lambda ()
(initialize-i/o (input-channel->port in)
(output-channel->port out)
zero - length buffer
(lambda ()
(with-threads
(lambda ()
(root-scheduler thunk
thread quantum , in msec
(initialize-i/o-handlers! define-exception-handler signal-exception)
|
f867bbaf86d10cd96d94fc0313007011e17738d5d7b03eba2dbf0f07822756d5 | ocaml/ocaml | odoc_gen.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Gallium , INRIA Rocquencourt
(* *)
Copyright 2010 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** *)
class type doc_generator =
object method generate : Odoc_module.t_module list -> unit end
module type Base = sig
class generator : doc_generator
end
module Base_generator : Base = struct
class generator : doc_generator = object method generate _ = () end
end
module type Base_functor = Base -> Base
module type Html_functor = Odoc_html.Html_generator -> Odoc_html.Html_generator
module type Latex_functor = Odoc_latex.Latex_generator -> Odoc_latex.Latex_generator
module type Texi_functor = Odoc_texi.Texi_generator -> Odoc_texi.Texi_generator
module type Man_functor = Odoc_man.Man_generator -> Odoc_man.Man_generator
module type Dot_functor = Odoc_dot.Dot_generator -> Odoc_dot.Dot_generator
type generator =
| Html of (module Odoc_html.Html_generator)
| Latex of (module Odoc_latex.Latex_generator)
| Texi of (module Odoc_texi.Texi_generator)
| Man of (module Odoc_man.Man_generator)
| Dot of (module Odoc_dot.Dot_generator)
| Base of (module Base)
let get_minimal_generator = function
Html m ->
let module M = (val m : Odoc_html.Html_generator) in
(new M.html :> doc_generator)
| Latex m ->
let module M = (val m : Odoc_latex.Latex_generator) in
(new M.latex :> doc_generator)
| Man m ->
let module M = (val m : Odoc_man.Man_generator) in
(new M.man :> doc_generator)
| Texi m ->
let module M = (val m : Odoc_texi.Texi_generator) in
(new M.texi :> doc_generator)
| Dot m ->
let module M = (val m : Odoc_dot.Dot_generator) in
(new M.dot :> doc_generator)
| Base m ->
let module M = (val m : Base) in
new M.generator
| null | https://raw.githubusercontent.com/ocaml/ocaml/04ddddd0e1d2bf2acb5091f434b93387243d4624/ocamldoc/odoc_gen.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* | , projet Gallium , INRIA Rocquencourt
Copyright 2010 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
class type doc_generator =
object method generate : Odoc_module.t_module list -> unit end
module type Base = sig
class generator : doc_generator
end
module Base_generator : Base = struct
class generator : doc_generator = object method generate _ = () end
end
module type Base_functor = Base -> Base
module type Html_functor = Odoc_html.Html_generator -> Odoc_html.Html_generator
module type Latex_functor = Odoc_latex.Latex_generator -> Odoc_latex.Latex_generator
module type Texi_functor = Odoc_texi.Texi_generator -> Odoc_texi.Texi_generator
module type Man_functor = Odoc_man.Man_generator -> Odoc_man.Man_generator
module type Dot_functor = Odoc_dot.Dot_generator -> Odoc_dot.Dot_generator
type generator =
| Html of (module Odoc_html.Html_generator)
| Latex of (module Odoc_latex.Latex_generator)
| Texi of (module Odoc_texi.Texi_generator)
| Man of (module Odoc_man.Man_generator)
| Dot of (module Odoc_dot.Dot_generator)
| Base of (module Base)
let get_minimal_generator = function
Html m ->
let module M = (val m : Odoc_html.Html_generator) in
(new M.html :> doc_generator)
| Latex m ->
let module M = (val m : Odoc_latex.Latex_generator) in
(new M.latex :> doc_generator)
| Man m ->
let module M = (val m : Odoc_man.Man_generator) in
(new M.man :> doc_generator)
| Texi m ->
let module M = (val m : Odoc_texi.Texi_generator) in
(new M.texi :> doc_generator)
| Dot m ->
let module M = (val m : Odoc_dot.Dot_generator) in
(new M.dot :> doc_generator)
| Base m ->
let module M = (val m : Base) in
new M.generator
|
6f44eba3f801ebd2f46011ab9d63e11d3ec12f1fa15969e99e390f81d61c32a7 | emqx/emqx | emqx_prometheus_proto_v1.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. 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
%%
%% -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(emqx_prometheus_proto_v1).
-behaviour(emqx_bpapi).
-export([
introduced_in/0,
deprecated_since/0,
start/1,
stop/1
]).
-include_lib("emqx/include/bpapi.hrl").
deprecated_since() -> "5.0.10".
introduced_in() ->
"5.0.0".
-spec start([node()]) -> emqx_rpc:multicall_result().
start(Nodes) ->
rpc:multicall(Nodes, emqx_prometheus, do_start, [], 5000).
-spec stop([node()]) -> emqx_rpc:multicall_result().
stop(Nodes) ->
rpc:multicall(Nodes, emqx_prometheus, do_stop, [], 5000).
| null | https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx_prometheus/src/proto/emqx_prometheus_proto_v1.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------- | Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_prometheus_proto_v1).
-behaviour(emqx_bpapi).
-export([
introduced_in/0,
deprecated_since/0,
start/1,
stop/1
]).
-include_lib("emqx/include/bpapi.hrl").
deprecated_since() -> "5.0.10".
introduced_in() ->
"5.0.0".
-spec start([node()]) -> emqx_rpc:multicall_result().
start(Nodes) ->
rpc:multicall(Nodes, emqx_prometheus, do_start, [], 5000).
-spec stop([node()]) -> emqx_rpc:multicall_result().
stop(Nodes) ->
rpc:multicall(Nodes, emqx_prometheus, do_stop, [], 5000).
|
df6698f4d78eeba4fbfb97a10f6312f95750dda6ebc5146ad534eb7c82c9cf06 | mhuebert/maria | project.clj | (defproject maria/shapes "0.1.1-SNAPSHOT"
:description "A shapes library"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:min-lein-version "2.7.1"
:dependencies [[org.clojure/clojure "1.9.0-alpha17"]
[org.clojure/clojurescript "1.9.854"]]
:source-paths ["src"]
:cljsbuild {:builds []}
:deploy-via :clojars
:lein-release {:deploy-via :clojars
:scm :git})
| null | https://raw.githubusercontent.com/mhuebert/maria/15586564796bc9273ace3101b21662d0c66b4d22/shapes/project.clj | clojure | (defproject maria/shapes "0.1.1-SNAPSHOT"
:description "A shapes library"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:min-lein-version "2.7.1"
:dependencies [[org.clojure/clojure "1.9.0-alpha17"]
[org.clojure/clojurescript "1.9.854"]]
:source-paths ["src"]
:cljsbuild {:builds []}
:deploy-via :clojars
:lein-release {:deploy-via :clojars
:scm :git})
| |
f65a4cb2ea52b84a162d8a2114d41f2d6f69c4f2b218d8ceedb9ed13dc868506 | tonyfloatersu/solution-haskell-craft-of-FP | Frequency.hs | -------------------------------------------------------------------------
--
-- Frequency.hs
--
-- Calculating the frequencies of words in a text, used in
Huffman coding .
--
( c ) Addison - Wesley , 1996 - 2011 .
--
-------------------------------------------------------------------------
module Frequency ( frequency ) where
import Test.QuickCheck hiding ( frequency )
-- Calculate the frequencies of characters in a list.
--
-- This is done by sorting, then counting the number of
-- repetitions. The counting is made part of the merge
-- operation in a merge sort.
frequency :: [Char] -> [ (Char,Int) ]
frequency
= mergeSort freqMerge . mergeSort alphaMerge . map start
where
start ch = (ch,1)
-- Merge sort parametrised on the merge operation. This is more
-- general than parametrising on the ordering operation, since
-- it permits amalgamation of elements with equal keys
-- for instance.
--
mergeSort :: ([a]->[a]->[a]) -> [a] -> [a]
mergeSort merge xs
| length xs < 2 = xs
| otherwise
= merge (mergeSort merge first)
(mergeSort merge second)
where
first = take half xs
second = drop half xs
half = (length xs) `div` 2
Order on first entry of pairs , with
accumulation of the numeric entries when equal first entry .
alphaMerge :: [(Char,Int)] -> [(Char,Int)] -> [(Char,Int)]
alphaMerge xs [] = xs
alphaMerge [] ys = ys
alphaMerge ((p,n):xs) ((q,m):ys)
| (p==q) = (p,n+m) : alphaMerge xs ys
| (p<q) = (p,n) : alphaMerge xs ((q,m):ys)
| otherwise = (q,m) : alphaMerge ((p,n):xs) ys
ordering , second field more significant .
--
freqMerge :: [(Char,Int)] -> [(Char,Int)] -> [(Char,Int)]
freqMerge xs [] = xs
freqMerge [] ys = ys
freqMerge ((p,n):xs) ((q,m):ys)
| (n<m || (n==m && p<q))
= (p,n) : freqMerge xs ((q,m):ys)
| otherwise
= (q,m) : freqMerge ((p,n):xs) ys
-- QuickCheck property
prop_mergeSort :: [Int] -> Bool
prop_mergeSort xs =
sorted (mergeSort merge xs)
where
sorted [] = True
sorted [_] = True
sorted (x:y:ys) = x<=y && sorted (y:ys)
merge [] xs = xs
merge ys [] = ys
merge (x:xs) (y:ys)
| x<=y = x: merge xs (y:ys)
| otherwise = y: merge (x:xs) ys | null | https://raw.githubusercontent.com/tonyfloatersu/solution-haskell-craft-of-FP/0d4090ef28417c82a7b01e4a764f657641cb83f3/Chapter15/Frequency.hs | haskell | -----------------------------------------------------------------------
Frequency.hs
Calculating the frequencies of words in a text, used in
-----------------------------------------------------------------------
Calculate the frequencies of characters in a list.
This is done by sorting, then counting the number of
repetitions. The counting is made part of the merge
operation in a merge sort.
Merge sort parametrised on the merge operation. This is more
general than parametrising on the ordering operation, since
it permits amalgamation of elements with equal keys
for instance.
QuickCheck property | Huffman coding .
( c ) Addison - Wesley , 1996 - 2011 .
module Frequency ( frequency ) where
import Test.QuickCheck hiding ( frequency )
frequency :: [Char] -> [ (Char,Int) ]
frequency
= mergeSort freqMerge . mergeSort alphaMerge . map start
where
start ch = (ch,1)
mergeSort :: ([a]->[a]->[a]) -> [a] -> [a]
mergeSort merge xs
| length xs < 2 = xs
| otherwise
= merge (mergeSort merge first)
(mergeSort merge second)
where
first = take half xs
second = drop half xs
half = (length xs) `div` 2
Order on first entry of pairs , with
accumulation of the numeric entries when equal first entry .
alphaMerge :: [(Char,Int)] -> [(Char,Int)] -> [(Char,Int)]
alphaMerge xs [] = xs
alphaMerge [] ys = ys
alphaMerge ((p,n):xs) ((q,m):ys)
| (p==q) = (p,n+m) : alphaMerge xs ys
| (p<q) = (p,n) : alphaMerge xs ((q,m):ys)
| otherwise = (q,m) : alphaMerge ((p,n):xs) ys
ordering , second field more significant .
freqMerge :: [(Char,Int)] -> [(Char,Int)] -> [(Char,Int)]
freqMerge xs [] = xs
freqMerge [] ys = ys
freqMerge ((p,n):xs) ((q,m):ys)
| (n<m || (n==m && p<q))
= (p,n) : freqMerge xs ((q,m):ys)
| otherwise
= (q,m) : freqMerge ((p,n):xs) ys
prop_mergeSort :: [Int] -> Bool
prop_mergeSort xs =
sorted (mergeSort merge xs)
where
sorted [] = True
sorted [_] = True
sorted (x:y:ys) = x<=y && sorted (y:ys)
merge [] xs = xs
merge ys [] = ys
merge (x:xs) (y:ys)
| x<=y = x: merge xs (y:ys)
| otherwise = y: merge (x:xs) ys |
98bcca5c890cd0b5d4002ac0a9d96aa9ddc5f848e4f37bf61aa86e1de87652de | i-am-tom/learn-me-a-haskell | PropertySpec.hs | # LANGUAGE CPP , OverloadedStrings #
module PropertySpec (main, spec) where
import Test.Hspec
import Data.String.Builder
import Property
import Interpreter (withInterpreter)
main :: IO ()
main = hspec spec
isFailure :: PropertyResult -> Bool
isFailure (Failure _) = True
isFailure _ = False
spec :: Spec
spec = do
describe "runProperty" $ do
it "reports a failing property" $ withInterpreter [] $ \repl -> do
runProperty repl "False" `shouldReturn` Failure "*** Failed! Falsifiable (after 1 test):"
it "runs a Bool property" $ withInterpreter [] $ \repl -> do
runProperty repl "True" `shouldReturn` Success
it "runs a Bool property with an explicit type signature" $ withInterpreter [] $ \repl -> do
runProperty repl "True :: Bool" `shouldReturn` Success
it "runs an implicitly quantified property" $ withInterpreter [] $ \repl -> do
runProperty repl "(reverse . reverse) xs == (xs :: [Int])" `shouldReturn` Success
it "runs an implicitly quantified property even with GHC 7.4" $
#if __GLASGOW_HASKELL__ == 702
pendingWith "This triggers a bug in GHC 7.2.*."
-- try e.g.
> > > 23
-- >>> :t is
#else
ghc will include a suggestion ( did you mean ` i d ` instead of ` is ` ) in
-- the error message
withInterpreter [] $ \repl -> do
runProperty repl "foldr (+) 0 is == sum (is :: [Int])" `shouldReturn` Success
#endif
it "runs an explicitly quantified property" $ withInterpreter [] $ \repl -> do
runProperty repl "\\xs -> (reverse . reverse) xs == (xs :: [Int])" `shouldReturn` Success
it "allows to mix implicit and explicit quantification" $ withInterpreter [] $ \repl -> do
runProperty repl "\\x -> x + y == y + x" `shouldReturn` Success
it "reports the value for which a property fails" $ withInterpreter [] $ \repl -> do
runProperty repl "x == 23" `shouldReturn` Failure "*** Failed! Falsifiable (after 1 test):\n0"
it "reports the values for which a property that takes multiple arguments fails" $ withInterpreter [] $ \repl -> do
let vals x = case x of (Failure r) -> tail (lines r); _ -> error "Property did not fail!"
vals `fmap` runProperty repl "x == True && y == 10 && z == \"foo\"" `shouldReturn` ["False", "0", show ("" :: String)]
it "defaults ambiguous type variables to Integer" $ withInterpreter [] $ \repl -> do
runProperty repl "reverse xs == xs" >>= (`shouldSatisfy` isFailure)
describe "freeVariables" $ do
it "finds a free variables in a term" $ withInterpreter [] $ \repl -> do
freeVariables repl "x" `shouldReturn` ["x"]
it "ignores duplicates" $ withInterpreter [] $ \repl -> do
freeVariables repl "x == x" `shouldReturn` ["x"]
it "works for terms with multiple names" $ withInterpreter [] $ \repl -> do
freeVariables repl "\\z -> x + y + z == foo 23" `shouldReturn` ["x", "y", "foo"]
it "works for names that contain a prime" $ withInterpreter [] $ \repl -> do
freeVariables repl "x' == y''" `shouldReturn` ["x'", "y''"]
it "works for names that are similar to other names that are in scope" $ withInterpreter [] $ \repl -> do
freeVariables repl "length_" `shouldReturn` ["length_"]
describe "parseNotInScope" $ do
context "when error message was produced by GHC 7.4.1" $ do
it "extracts a variable name of variable that is not in scope from an error message" $ do
parseNotInScope . build $ do
"<interactive>:4:1: Not in scope: `x'"
`shouldBe` ["x"]
it "ignores duplicates" $ do
parseNotInScope . build $ do
"<interactive>:4:1: Not in scope: `x'"
""
"<interactive>:4:6: Not in scope: `x'"
`shouldBe` ["x"]
it "works for variable names that contain a prime" $ do
parseNotInScope . build $ do
"<interactive>:2:1: Not in scope: x'"
""
"<interactive>:2:7: Not in scope: y'"
`shouldBe` ["x'", "y'"]
it "works for error messages with suggestions" $ do
parseNotInScope . build $ do
"<interactive>:1:1:"
" Not in scope: `is'"
" Perhaps you meant `id' (imported from Prelude)"
`shouldBe` ["is"]
context "when error message was produced by GHC 8.0.1" $ do
it "extracts a variable name of variable that is not in scope from an error message" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error: Variable not in scope: x"
`shouldBe` ["x"]
it "ignores duplicates" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error: Variable not in scope: x :: ()"
""
"<interactive>:1:6: error: Variable not in scope: x :: ()"
`shouldBe` ["x"]
it "works for variable names that contain a prime" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error: Variable not in scope: x' :: ()"
""
"<interactive>:1:7: error: Variable not in scope: y'' :: ()"
`shouldBe` ["x'", "y''"]
it "works for error messages with suggestions" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error:"
" • Variable not in scope: length_"
" • Perhaps you meant ‘length’ (imported from Prelude)"
`shouldBe` ["length_"]
| null | https://raw.githubusercontent.com/i-am-tom/learn-me-a-haskell/08271f6cdd4fc88c26ed7a62ed1e786a900824be/vendor/doctest-0.16.0/test/PropertySpec.hs | haskell | try e.g.
>>> :t is
the error message | # LANGUAGE CPP , OverloadedStrings #
module PropertySpec (main, spec) where
import Test.Hspec
import Data.String.Builder
import Property
import Interpreter (withInterpreter)
main :: IO ()
main = hspec spec
isFailure :: PropertyResult -> Bool
isFailure (Failure _) = True
isFailure _ = False
spec :: Spec
spec = do
describe "runProperty" $ do
it "reports a failing property" $ withInterpreter [] $ \repl -> do
runProperty repl "False" `shouldReturn` Failure "*** Failed! Falsifiable (after 1 test):"
it "runs a Bool property" $ withInterpreter [] $ \repl -> do
runProperty repl "True" `shouldReturn` Success
it "runs a Bool property with an explicit type signature" $ withInterpreter [] $ \repl -> do
runProperty repl "True :: Bool" `shouldReturn` Success
it "runs an implicitly quantified property" $ withInterpreter [] $ \repl -> do
runProperty repl "(reverse . reverse) xs == (xs :: [Int])" `shouldReturn` Success
it "runs an implicitly quantified property even with GHC 7.4" $
#if __GLASGOW_HASKELL__ == 702
pendingWith "This triggers a bug in GHC 7.2.*."
> > > 23
#else
ghc will include a suggestion ( did you mean ` i d ` instead of ` is ` ) in
withInterpreter [] $ \repl -> do
runProperty repl "foldr (+) 0 is == sum (is :: [Int])" `shouldReturn` Success
#endif
it "runs an explicitly quantified property" $ withInterpreter [] $ \repl -> do
runProperty repl "\\xs -> (reverse . reverse) xs == (xs :: [Int])" `shouldReturn` Success
it "allows to mix implicit and explicit quantification" $ withInterpreter [] $ \repl -> do
runProperty repl "\\x -> x + y == y + x" `shouldReturn` Success
it "reports the value for which a property fails" $ withInterpreter [] $ \repl -> do
runProperty repl "x == 23" `shouldReturn` Failure "*** Failed! Falsifiable (after 1 test):\n0"
it "reports the values for which a property that takes multiple arguments fails" $ withInterpreter [] $ \repl -> do
let vals x = case x of (Failure r) -> tail (lines r); _ -> error "Property did not fail!"
vals `fmap` runProperty repl "x == True && y == 10 && z == \"foo\"" `shouldReturn` ["False", "0", show ("" :: String)]
it "defaults ambiguous type variables to Integer" $ withInterpreter [] $ \repl -> do
runProperty repl "reverse xs == xs" >>= (`shouldSatisfy` isFailure)
describe "freeVariables" $ do
it "finds a free variables in a term" $ withInterpreter [] $ \repl -> do
freeVariables repl "x" `shouldReturn` ["x"]
it "ignores duplicates" $ withInterpreter [] $ \repl -> do
freeVariables repl "x == x" `shouldReturn` ["x"]
it "works for terms with multiple names" $ withInterpreter [] $ \repl -> do
freeVariables repl "\\z -> x + y + z == foo 23" `shouldReturn` ["x", "y", "foo"]
it "works for names that contain a prime" $ withInterpreter [] $ \repl -> do
freeVariables repl "x' == y''" `shouldReturn` ["x'", "y''"]
it "works for names that are similar to other names that are in scope" $ withInterpreter [] $ \repl -> do
freeVariables repl "length_" `shouldReturn` ["length_"]
describe "parseNotInScope" $ do
context "when error message was produced by GHC 7.4.1" $ do
it "extracts a variable name of variable that is not in scope from an error message" $ do
parseNotInScope . build $ do
"<interactive>:4:1: Not in scope: `x'"
`shouldBe` ["x"]
it "ignores duplicates" $ do
parseNotInScope . build $ do
"<interactive>:4:1: Not in scope: `x'"
""
"<interactive>:4:6: Not in scope: `x'"
`shouldBe` ["x"]
it "works for variable names that contain a prime" $ do
parseNotInScope . build $ do
"<interactive>:2:1: Not in scope: x'"
""
"<interactive>:2:7: Not in scope: y'"
`shouldBe` ["x'", "y'"]
it "works for error messages with suggestions" $ do
parseNotInScope . build $ do
"<interactive>:1:1:"
" Not in scope: `is'"
" Perhaps you meant `id' (imported from Prelude)"
`shouldBe` ["is"]
context "when error message was produced by GHC 8.0.1" $ do
it "extracts a variable name of variable that is not in scope from an error message" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error: Variable not in scope: x"
`shouldBe` ["x"]
it "ignores duplicates" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error: Variable not in scope: x :: ()"
""
"<interactive>:1:6: error: Variable not in scope: x :: ()"
`shouldBe` ["x"]
it "works for variable names that contain a prime" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error: Variable not in scope: x' :: ()"
""
"<interactive>:1:7: error: Variable not in scope: y'' :: ()"
`shouldBe` ["x'", "y''"]
it "works for error messages with suggestions" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error:"
" • Variable not in scope: length_"
" • Perhaps you meant ‘length’ (imported from Prelude)"
`shouldBe` ["length_"]
|
fb2fba9c1d4bf3e1e8afe95754a1730bde639629e26d61b38a5b59ba3ce9719d | hdima/erlport | ruby_options_tests.erl | Copyright ( c ) 2009 - 2015 , < >
%%% 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 the copyright holders nor the names of its
%%% contributors may be used to endorse or promote products derived from
%%% this software without specific prior written permission.
%%%
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
%%% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
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(ruby_options_tests).
-include_lib("eunit/include/eunit.hrl").
-include("ruby.hrl").
-include("erlport_test_utils.hrl").
parse_test_() ->
fun () ->
{ok, #ruby_options{ruby=Ruby, use_stdio=use_stdio,
call_timeout=infinity, packet=4, ruby_lib=RubyLib,
start_timeout=10000, compressed=0, env=Env,
port_options=PortOptions,
buffer_size=65536}} = ruby_options:parse([]),
?assertPattern(Ruby, "/ruby(\\.exe)?$"),
?assertPattern(RubyLib, "/priv/ruby1\\.[89]"),
?assertEqual([{"RUBYLIB", RubyLib}], Env),
?assertEqual([{env, Env}, {packet, 4}, binary, hide, exit_status],
PortOptions)
end.
buffer_size_test_() -> [
?_assertMatch({ok, #ruby_options{buffer_size=65536}},
ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{buffer_size=5000}},
ruby_options:parse([{buffer_size, 5000}])),
?_assertEqual({error, {invalid_option, {buffer_size, 0}}},
ruby_options:parse([{buffer_size, 0}])),
?_assertEqual({error, {invalid_option, {buffer_size, invalid}}},
ruby_options:parse([{buffer_size, invalid}]))
].
use_stdio_option_test_() -> [
?_assertMatch({ok, #ruby_options{use_stdio=use_stdio}},
ruby_options:parse([])),
case os:type() of
{win32, _} ->
?_assertEqual({error, {unsupported_on_this_platform, nouse_stdio}},
ruby_options:parse([nouse_stdio]));
_ ->
?_assertMatch({ok, #ruby_options{use_stdio=nouse_stdio}},
ruby_options:parse([nouse_stdio]))
end,
?_assertMatch({ok, #ruby_options{use_stdio=use_stdio}},
ruby_options:parse([use_stdio]))
].
compressed_option_test_() -> [
?_assertMatch({ok, #ruby_options{compressed=0}},
ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{compressed=9}},
ruby_options:parse([{compressed, 9}])),
?_assertMatch({error, {invalid_option, {compressed, invalid}}},
ruby_options:parse([{compressed, invalid}]))
].
packet_option_test_() -> [
?_assertMatch({ok, #ruby_options{packet=4}}, ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{packet=4}},
ruby_options:parse([{packet, 4}])),
?_assertMatch({ok, #ruby_options{packet=1}},
ruby_options:parse([{packet, 1}])),
?_assertMatch({ok, #ruby_options{packet=2}},
ruby_options:parse([{packet, 2}])),
?_assertEqual({error, {invalid_option, {packet, 3}}},
ruby_options:parse([{packet, 3}]))
].
start_timeout_test_() -> [
?_assertMatch({ok, #ruby_options{start_timeout=10000}},
ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{start_timeout=5000}},
ruby_options:parse([{start_timeout, 5000}])),
?_assertMatch({ok, #ruby_options{start_timeout=infinity}},
ruby_options:parse([{start_timeout, infinity}])),
?_assertEqual({error, {invalid_option, {start_timeout, 0}}},
ruby_options:parse([{start_timeout, 0}])),
?_assertEqual({error, {invalid_option, {start_timeout, invalid}}},
ruby_options:parse([{start_timeout, invalid}]))
].
call_timeout_test_() -> [
?_assertMatch({ok, #ruby_options{call_timeout=infinity}},
ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{call_timeout=5000}},
ruby_options:parse([{call_timeout, 5000}])),
?_assertMatch({ok, #ruby_options{call_timeout=infinity}},
ruby_options:parse([{call_timeout, infinity}])),
?_assertEqual({error, {invalid_option, {call_timeout, 0}}},
ruby_options:parse([{call_timeout, 0}])),
?_assertEqual({error, {invalid_option, {call_timeout, invalid}}},
ruby_options:parse([{call_timeout, invalid}]))
].
env_option_test_() -> [
?_assertMatch({ok, #ruby_options{env=[{"RUBYLIB", RubyLib}],
ruby_lib=RubyLib}}, ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{env=[{"RUBYLIB", RubyLib},
{"test", "true"}], ruby_lib=RubyLib}},
ruby_options:parse([{env, [{"test", "true"}]}])),
?_assertEqual({error, {invalid_option,
{env, [{"test", "true"}, {test, "true"}, {"test", true}, invalid]},
[{test, "true"}, {"test", true}, invalid]}},
ruby_options:parse([{env, [{"test", "true"}, {test, "true"},
{"test", true}, invalid]}])),
?_assertEqual({error, {invalid_option, {env, invalid_env}, not_list}},
ruby_options:parse([{env, invalid_env}]))
].
ruby_option_test_() -> {setup,
fun () ->
TmpDir = erlport_test_utils:tmp_dir("erlport_options_tests"),
BadName = filename:join(TmpDir, "not_executable"),
ok = file:write_file(BadName, <<>>, [raw]),
UnknownName = filename:join(TmpDir, "unknown"),
GoodRuby = erlport_test_utils:create_mock_script(
"ruby 1.8.7", TmpDir, "ruby"),
GoodRuby19 = erlport_test_utils:create_mock_script(
"ruby 1.9.3p0", TmpDir, "ruby1.9"),
GoodRuby2 = erlport_test_utils:create_mock_script(
"ruby 2.0.0", TmpDir, "ruby2.0"),
UnsupportedRuby = erlport_test_utils:create_mock_script(
"ruby 1.7.0", TmpDir, "unsupported"),
InvalidRuby = erlport_test_utils:create_mock_script(
"ruby INVALID", TmpDir, "invalid"),
{TmpDir, GoodRuby, GoodRuby19, GoodRuby2, BadName, UnknownName,
UnsupportedRuby, InvalidRuby}
end,
fun (Info) ->
ok = erlport_test_utils:remove_object(element(1, Info)) % TmpDir
end,
fun ({_, GoodRuby, GoodRuby19, GoodRuby2, BadName, UnknownName,
UnsupportedRuby, InvalidRuby}) -> [
fun () ->
{ok, #ruby_options{ruby=Ruby}} = ruby_options:parse([]),
?assertPattern(Ruby, "/ruby(\\.exe)?$")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby),
?_assertMatch({ok, #ruby_options{ruby=Expected}},
ruby_options:parse([{ruby, GoodRuby}]))
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby),
{ok, #ruby_options{ruby=Expected, ruby_lib=RubyPath}}
= ruby_options:parse([{ruby, GoodRuby}]),
?assertPattern(RubyPath, "/priv/ruby1\\.8")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby19),
{ok, #ruby_options{ruby=Expected, ruby_lib=RubyPath}}
= ruby_options:parse([{ruby, GoodRuby19}]),
?assertPattern(RubyPath, "/priv/ruby1\\.9")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby2),
{ok, #ruby_options{ruby=Expected, ruby_lib=RubyPath}}
= ruby_options:parse([{ruby, GoodRuby2}]),
?assertPattern(RubyPath, "/priv/ruby1\\.9")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby) ++ " -S",
CommandWithOption = GoodRuby ++ " -S",
?assertMatch({ok, #ruby_options{ruby=Expected}},
ruby_options:parse([{ruby, CommandWithOption}]))
end,
?_assertEqual({error, {invalid_option, {ruby, BadName}, not_found}},
ruby_options:parse([{ruby, BadName}])),
?_assertEqual({error, {invalid_option, {ruby, UnknownName},
not_found}},
ruby_options:parse([{ruby, UnknownName}])),
?_assertEqual({error, {invalid_option,
{ruby, "erlport_tests_unknown_name"}, not_found}},
ruby_options:parse([{ruby, "erlport_tests_unknown_name"}])),
?_assertEqual({error, {invalid_option, {ruby, not_string}}},
ruby_options:parse([{ruby, not_string}])),
fun () ->
erlport_test_utils:call_with_env(fun () ->
?assertEqual({error, ruby_not_found},
ruby_options:parse([]))
end, "PATH", "")
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
?assertEqual({error, {invalid_env_var,
{"ERLPORT_RUBY", "INVALID_ruby"}, not_found}},
ruby_options:parse([]))
end, "ERLPORT_RUBY", "INVALID_ruby")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby),
erlport_test_utils:call_with_env(fun () ->
?assertMatch({ok, #ruby_options{ruby=Expected}},
ruby_options:parse([]))
end, "ERLPORT_RUBY", GoodRuby)
end,
?_assertEqual({error, {unsupported_ruby_version, "ruby 1.7.0"}},
ruby_options:parse([{ruby, UnsupportedRuby}])),
?_assertEqual({error, {invalid_ruby,
erlport_test_utils:script(InvalidRuby)}},
ruby_options:parse([{ruby, InvalidRuby}]))
] end}.
cd_option_test_() -> {setup,
fun () ->
erlport_test_utils:tmp_dir("erlport_options_tests")
end,
fun erlport_test_utils:remove_object/1,
fun (TmpDir) -> [
fun () ->
{ok, #ruby_options{cd=undefined, port_options=PortOptions,
env=Env}} = ruby_options:parse([]),
?assertEqual([{env, Env}, {packet, 4}, binary, hide, exit_status],
PortOptions)
end,
fun () ->
{ok, #ruby_options{cd=TmpDir, port_options=PortOptions, env=Env}}
= ruby_options:parse([{cd, TmpDir}]),
?assertEqual([{env, Env}, {packet, 4}, {cd, TmpDir},
binary, hide, exit_status], PortOptions)
end,
?_assertEqual({error, {invalid_option, {cd, "invalid_directory"}}},
ruby_options:parse([{cd, "invalid_directory"}]))
] end}.
ruby_lib_option_test_() -> {setup,
fun () ->
TmpDir = erlport_test_utils:tmp_dir("erlport_options_tests"),
TestPath1 = filename:join(TmpDir, "path1"),
ok = file:make_dir(TestPath1),
TestPath2 = filename:join(TmpDir, "path2"),
ok = file:make_dir(TestPath2),
{TmpDir, TestPath1, TestPath2}
end,
fun (Info) ->
ok = erlport_test_utils:remove_object(element(1, Info)) % TmpDir
end,
fun ({_, TestPath1, TestPath2}) -> [
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse([]),
?assertPattern(RubyLib, "/priv/ruby1\\.[89]")
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, [TestPath1]}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, TestPath1}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, erlport_test_utils:local_path(
[TestPath1, TestPath2])}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, [TestPath1]},
{env, [{"RUBYLIB", TestPath2}]}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{env, [{"RUBYLIB", TestPath1},
{"RUBYLIB", TestPath2}]}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, [TestPath1, TestPath2, ""]},
{env, [{"RUBYLIB", erlport_test_utils:local_path(
[TestPath2, TestPath1])}]}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse([]),
?assertPattern(RubyLib, "/priv/ruby1\\.[89]")
end, "RUBYLIB", "")
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse([]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1])
end, "RUBYLIB", TestPath1)
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse([]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end, "RUBYLIB", erlport_test_utils:local_path(
[TestPath1, TestPath2]))
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, TestPath1}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end, "RUBYLIB", TestPath2)
end,
?_assertEqual({error, {invalid_option, {ruby_lib, invalid_path},
not_list}},
ruby_options:parse([{ruby_lib, invalid_path}])),
?_assertEqual({error, {invalid_option, {ruby_lib, ""},
invalid_path}},
ruby_options:parse([{ruby_lib, ""}])),
?_assertEqual({error, {invalid_option, {ruby_lib,
[TestPath1, invalid]}, [invalid]}},
ruby_options:parse([{ruby_lib, [TestPath1, invalid]}])),
?_assertEqual({error, {invalid_option, {ruby_lib,
[$a, $b, invalid]}, [invalid]}},
ruby_options:parse([{ruby_lib, [$a, $b, invalid]}])),
fun () ->
Dir = code:lib_dir(erlport),
ok = erlport_test_utils:del_code_path(erlport, 5),
try ?assertEqual({error, {not_found, "erlport/priv"}},
ruby_options:parse([]))
after
true = code:add_patha(Dir)
end
end
] end}.
unknown_option_test_() ->
?_assertEqual({error, {unknown_option, unknown}},
ruby_options:parse([unknown])).
| null | https://raw.githubusercontent.com/hdima/erlport/246b7722d62b87b48be66d9a871509a537728962/test/ruby_options_tests.erl | erlang | 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 the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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.
TmpDir
TmpDir | Copyright ( c ) 2009 - 2015 , < >
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
-module(ruby_options_tests).
-include_lib("eunit/include/eunit.hrl").
-include("ruby.hrl").
-include("erlport_test_utils.hrl").
parse_test_() ->
fun () ->
{ok, #ruby_options{ruby=Ruby, use_stdio=use_stdio,
call_timeout=infinity, packet=4, ruby_lib=RubyLib,
start_timeout=10000, compressed=0, env=Env,
port_options=PortOptions,
buffer_size=65536}} = ruby_options:parse([]),
?assertPattern(Ruby, "/ruby(\\.exe)?$"),
?assertPattern(RubyLib, "/priv/ruby1\\.[89]"),
?assertEqual([{"RUBYLIB", RubyLib}], Env),
?assertEqual([{env, Env}, {packet, 4}, binary, hide, exit_status],
PortOptions)
end.
buffer_size_test_() -> [
?_assertMatch({ok, #ruby_options{buffer_size=65536}},
ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{buffer_size=5000}},
ruby_options:parse([{buffer_size, 5000}])),
?_assertEqual({error, {invalid_option, {buffer_size, 0}}},
ruby_options:parse([{buffer_size, 0}])),
?_assertEqual({error, {invalid_option, {buffer_size, invalid}}},
ruby_options:parse([{buffer_size, invalid}]))
].
use_stdio_option_test_() -> [
?_assertMatch({ok, #ruby_options{use_stdio=use_stdio}},
ruby_options:parse([])),
case os:type() of
{win32, _} ->
?_assertEqual({error, {unsupported_on_this_platform, nouse_stdio}},
ruby_options:parse([nouse_stdio]));
_ ->
?_assertMatch({ok, #ruby_options{use_stdio=nouse_stdio}},
ruby_options:parse([nouse_stdio]))
end,
?_assertMatch({ok, #ruby_options{use_stdio=use_stdio}},
ruby_options:parse([use_stdio]))
].
compressed_option_test_() -> [
?_assertMatch({ok, #ruby_options{compressed=0}},
ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{compressed=9}},
ruby_options:parse([{compressed, 9}])),
?_assertMatch({error, {invalid_option, {compressed, invalid}}},
ruby_options:parse([{compressed, invalid}]))
].
packet_option_test_() -> [
?_assertMatch({ok, #ruby_options{packet=4}}, ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{packet=4}},
ruby_options:parse([{packet, 4}])),
?_assertMatch({ok, #ruby_options{packet=1}},
ruby_options:parse([{packet, 1}])),
?_assertMatch({ok, #ruby_options{packet=2}},
ruby_options:parse([{packet, 2}])),
?_assertEqual({error, {invalid_option, {packet, 3}}},
ruby_options:parse([{packet, 3}]))
].
start_timeout_test_() -> [
?_assertMatch({ok, #ruby_options{start_timeout=10000}},
ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{start_timeout=5000}},
ruby_options:parse([{start_timeout, 5000}])),
?_assertMatch({ok, #ruby_options{start_timeout=infinity}},
ruby_options:parse([{start_timeout, infinity}])),
?_assertEqual({error, {invalid_option, {start_timeout, 0}}},
ruby_options:parse([{start_timeout, 0}])),
?_assertEqual({error, {invalid_option, {start_timeout, invalid}}},
ruby_options:parse([{start_timeout, invalid}]))
].
call_timeout_test_() -> [
?_assertMatch({ok, #ruby_options{call_timeout=infinity}},
ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{call_timeout=5000}},
ruby_options:parse([{call_timeout, 5000}])),
?_assertMatch({ok, #ruby_options{call_timeout=infinity}},
ruby_options:parse([{call_timeout, infinity}])),
?_assertEqual({error, {invalid_option, {call_timeout, 0}}},
ruby_options:parse([{call_timeout, 0}])),
?_assertEqual({error, {invalid_option, {call_timeout, invalid}}},
ruby_options:parse([{call_timeout, invalid}]))
].
env_option_test_() -> [
?_assertMatch({ok, #ruby_options{env=[{"RUBYLIB", RubyLib}],
ruby_lib=RubyLib}}, ruby_options:parse([])),
?_assertMatch({ok, #ruby_options{env=[{"RUBYLIB", RubyLib},
{"test", "true"}], ruby_lib=RubyLib}},
ruby_options:parse([{env, [{"test", "true"}]}])),
?_assertEqual({error, {invalid_option,
{env, [{"test", "true"}, {test, "true"}, {"test", true}, invalid]},
[{test, "true"}, {"test", true}, invalid]}},
ruby_options:parse([{env, [{"test", "true"}, {test, "true"},
{"test", true}, invalid]}])),
?_assertEqual({error, {invalid_option, {env, invalid_env}, not_list}},
ruby_options:parse([{env, invalid_env}]))
].
ruby_option_test_() -> {setup,
fun () ->
TmpDir = erlport_test_utils:tmp_dir("erlport_options_tests"),
BadName = filename:join(TmpDir, "not_executable"),
ok = file:write_file(BadName, <<>>, [raw]),
UnknownName = filename:join(TmpDir, "unknown"),
GoodRuby = erlport_test_utils:create_mock_script(
"ruby 1.8.7", TmpDir, "ruby"),
GoodRuby19 = erlport_test_utils:create_mock_script(
"ruby 1.9.3p0", TmpDir, "ruby1.9"),
GoodRuby2 = erlport_test_utils:create_mock_script(
"ruby 2.0.0", TmpDir, "ruby2.0"),
UnsupportedRuby = erlport_test_utils:create_mock_script(
"ruby 1.7.0", TmpDir, "unsupported"),
InvalidRuby = erlport_test_utils:create_mock_script(
"ruby INVALID", TmpDir, "invalid"),
{TmpDir, GoodRuby, GoodRuby19, GoodRuby2, BadName, UnknownName,
UnsupportedRuby, InvalidRuby}
end,
fun (Info) ->
end,
fun ({_, GoodRuby, GoodRuby19, GoodRuby2, BadName, UnknownName,
UnsupportedRuby, InvalidRuby}) -> [
fun () ->
{ok, #ruby_options{ruby=Ruby}} = ruby_options:parse([]),
?assertPattern(Ruby, "/ruby(\\.exe)?$")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby),
?_assertMatch({ok, #ruby_options{ruby=Expected}},
ruby_options:parse([{ruby, GoodRuby}]))
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby),
{ok, #ruby_options{ruby=Expected, ruby_lib=RubyPath}}
= ruby_options:parse([{ruby, GoodRuby}]),
?assertPattern(RubyPath, "/priv/ruby1\\.8")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby19),
{ok, #ruby_options{ruby=Expected, ruby_lib=RubyPath}}
= ruby_options:parse([{ruby, GoodRuby19}]),
?assertPattern(RubyPath, "/priv/ruby1\\.9")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby2),
{ok, #ruby_options{ruby=Expected, ruby_lib=RubyPath}}
= ruby_options:parse([{ruby, GoodRuby2}]),
?assertPattern(RubyPath, "/priv/ruby1\\.9")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby) ++ " -S",
CommandWithOption = GoodRuby ++ " -S",
?assertMatch({ok, #ruby_options{ruby=Expected}},
ruby_options:parse([{ruby, CommandWithOption}]))
end,
?_assertEqual({error, {invalid_option, {ruby, BadName}, not_found}},
ruby_options:parse([{ruby, BadName}])),
?_assertEqual({error, {invalid_option, {ruby, UnknownName},
not_found}},
ruby_options:parse([{ruby, UnknownName}])),
?_assertEqual({error, {invalid_option,
{ruby, "erlport_tests_unknown_name"}, not_found}},
ruby_options:parse([{ruby, "erlport_tests_unknown_name"}])),
?_assertEqual({error, {invalid_option, {ruby, not_string}}},
ruby_options:parse([{ruby, not_string}])),
fun () ->
erlport_test_utils:call_with_env(fun () ->
?assertEqual({error, ruby_not_found},
ruby_options:parse([]))
end, "PATH", "")
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
?assertEqual({error, {invalid_env_var,
{"ERLPORT_RUBY", "INVALID_ruby"}, not_found}},
ruby_options:parse([]))
end, "ERLPORT_RUBY", "INVALID_ruby")
end,
fun () ->
Expected = erlport_test_utils:script(GoodRuby),
erlport_test_utils:call_with_env(fun () ->
?assertMatch({ok, #ruby_options{ruby=Expected}},
ruby_options:parse([]))
end, "ERLPORT_RUBY", GoodRuby)
end,
?_assertEqual({error, {unsupported_ruby_version, "ruby 1.7.0"}},
ruby_options:parse([{ruby, UnsupportedRuby}])),
?_assertEqual({error, {invalid_ruby,
erlport_test_utils:script(InvalidRuby)}},
ruby_options:parse([{ruby, InvalidRuby}]))
] end}.
cd_option_test_() -> {setup,
fun () ->
erlport_test_utils:tmp_dir("erlport_options_tests")
end,
fun erlport_test_utils:remove_object/1,
fun (TmpDir) -> [
fun () ->
{ok, #ruby_options{cd=undefined, port_options=PortOptions,
env=Env}} = ruby_options:parse([]),
?assertEqual([{env, Env}, {packet, 4}, binary, hide, exit_status],
PortOptions)
end,
fun () ->
{ok, #ruby_options{cd=TmpDir, port_options=PortOptions, env=Env}}
= ruby_options:parse([{cd, TmpDir}]),
?assertEqual([{env, Env}, {packet, 4}, {cd, TmpDir},
binary, hide, exit_status], PortOptions)
end,
?_assertEqual({error, {invalid_option, {cd, "invalid_directory"}}},
ruby_options:parse([{cd, "invalid_directory"}]))
] end}.
ruby_lib_option_test_() -> {setup,
fun () ->
TmpDir = erlport_test_utils:tmp_dir("erlport_options_tests"),
TestPath1 = filename:join(TmpDir, "path1"),
ok = file:make_dir(TestPath1),
TestPath2 = filename:join(TmpDir, "path2"),
ok = file:make_dir(TestPath2),
{TmpDir, TestPath1, TestPath2}
end,
fun (Info) ->
end,
fun ({_, TestPath1, TestPath2}) -> [
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse([]),
?assertPattern(RubyLib, "/priv/ruby1\\.[89]")
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, [TestPath1]}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, TestPath1}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, erlport_test_utils:local_path(
[TestPath1, TestPath2])}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, [TestPath1]},
{env, [{"RUBYLIB", TestPath2}]}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{env, [{"RUBYLIB", TestPath1},
{"RUBYLIB", TestPath2}]}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end,
fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, [TestPath1, TestPath2, ""]},
{env, [{"RUBYLIB", erlport_test_utils:local_path(
[TestPath2, TestPath1])}]}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse([]),
?assertPattern(RubyLib, "/priv/ruby1\\.[89]")
end, "RUBYLIB", "")
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse([]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1])
end, "RUBYLIB", TestPath1)
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse([]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end, "RUBYLIB", erlport_test_utils:local_path(
[TestPath1, TestPath2]))
end,
fun () ->
erlport_test_utils:call_with_env(fun () ->
{ok, #ruby_options{ruby_lib=RubyLib,
env=[{"RUBYLIB", RubyLib}]=Env,
port_options=[{env, Env} | _]}} = ruby_options:parse(
[{ruby_lib, TestPath1}]),
?assertPattern(RubyLib, ["/priv/ruby1\\.[89]", TestPath1,
TestPath2])
end, "RUBYLIB", TestPath2)
end,
?_assertEqual({error, {invalid_option, {ruby_lib, invalid_path},
not_list}},
ruby_options:parse([{ruby_lib, invalid_path}])),
?_assertEqual({error, {invalid_option, {ruby_lib, ""},
invalid_path}},
ruby_options:parse([{ruby_lib, ""}])),
?_assertEqual({error, {invalid_option, {ruby_lib,
[TestPath1, invalid]}, [invalid]}},
ruby_options:parse([{ruby_lib, [TestPath1, invalid]}])),
?_assertEqual({error, {invalid_option, {ruby_lib,
[$a, $b, invalid]}, [invalid]}},
ruby_options:parse([{ruby_lib, [$a, $b, invalid]}])),
fun () ->
Dir = code:lib_dir(erlport),
ok = erlport_test_utils:del_code_path(erlport, 5),
try ?assertEqual({error, {not_found, "erlport/priv"}},
ruby_options:parse([]))
after
true = code:add_patha(Dir)
end
end
] end}.
unknown_option_test_() ->
?_assertEqual({error, {unknown_option, unknown}},
ruby_options:parse([unknown])).
|
545fb7b70c7406fd66a2c10563130860ddfd6f4def22e6a8e4895a6360aa5b44 | lambdacube3d/lambdacube-edsl | HindleyMilner.hs | import Data.Functor.Identity
import Control.Monad.Except
import Control.Monad.State
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Monoid
import Data.Functor
data Lit
= LInt
| LBool
| LFloat
deriving (Show,Eq,Ord)
data PrimFun
= PAddI
| PAnd
| PMulF
deriving (Show,Eq,Ord)
data Exp
= ELit Lit
| EPrimFun PrimFun
| EVar EName
| EApp Exp Exp
| ELam EName Exp
| ELet EName Exp Exp
deriving (Show,Eq,Ord)
infixr 7 :->
data Ty
= TVar TName
| Ty :-> Ty
-- primitive types
| TInt
| TBool
| TFloat
deriving (Show,Eq,Ord)
data Scheme = Scheme (Set TName) Ty
type EName = String
type TName = String
type Env = Map EName Scheme
type Subst = Map TName Ty
inferPrimFun :: PrimFun -> Ty
inferPrimFun a = case a of
PAddI -> TInt :-> TInt :-> TInt
PAnd -> TBool :-> TBool :-> TBool
PMulF -> TFloat :-> TFloat :-> TFloat
inferLit :: Lit -> Ty
inferLit a = case a of
LInt -> TInt
LBool -> TBool
LFloat -> TFloat
type Unique a = StateT Int (Except String) a
newVar :: Unique Ty
newVar = do
n <- get
put (n+1)
return $ TVar $ 't':show n
applyEnv :: Env -> Subst -> Env
applyEnv e s = fmap (flip applyScheme s) e
applyScheme :: Scheme -> Subst -> Scheme
applyScheme (Scheme vars t) s = Scheme vars (apply t (Map.filterWithKey (\k _ -> Set.notMember k vars) s))
freeVarsScheme :: Scheme -> Set TName
freeVarsScheme (Scheme vars t) = freeVars t `Set.difference` vars
freeVarsEnv :: Env -> Set TName
freeVarsEnv env = Set.unions . Map.elems . fmap freeVarsScheme $ env
generalize :: Env -> Ty -> Scheme
generalize env t = Scheme (freeVars t `Set.difference` freeVarsEnv env) t
instantiate :: Scheme -> Unique Ty
instantiate (Scheme vars t) = do
let l = Set.toList vars
s <- mapM (\_ -> newVar) l
return $ apply t $ Map.fromList $ zip l s
apply :: Ty -> Subst -> Ty
apply (TVar a) st = case Map.lookup a st of
Nothing -> TVar a
Just t -> t
apply (a :-> b) st = (apply a st) :-> (apply b st)
apply t _ = t
unify :: Ty -> Ty -> Unique Subst
unify (TVar u) t = bindVar u t
unify t (TVar u) = bindVar u t
unify (a1 :-> b1) (a2 :-> b2) = do
s1 <- unify a1 a2
s2 <- unify (apply b1 s1) (apply b2 s1)
return $ s1 `compose` s2
unify a b
| a == b = return mempty
| otherwise = throwError $ "can not unify " ++ show a ++ " with " ++ show b
freeVars :: Ty -> Set TName
freeVars (TVar a) = Set.singleton a
freeVars (a :-> b) = freeVars a `mappend` freeVars b
freeVars _ = mempty
bindVar :: TName -> Ty -> Unique Subst
bindVar n t
| TVar n == t = return mempty
| n `Set.member` freeVars t = throwError $ "Infinite type, type variable " ++ n ++ " occurs in " ++ show t
| otherwise = return $ Map.singleton n t
compose :: Subst -> Subst -> Subst
compose a b = mappend a $ (flip apply) a <$> b
remove :: EName -> Env -> Env
remove n e = Map.delete n e
infer :: Env -> Exp -> Unique (Subst,Ty)
infer env (EPrimFun f) = return (mempty,inferPrimFun f)
infer env (ELit l) = return (mempty,inferLit l)
infer env (EVar n) = case Map.lookup n env of
Nothing -> throwError $ "unbounded variable: " ++ n
Just t -> do
t' <- instantiate t
return (mempty,t')
infer env (EApp f a) = do
(s1,t1) <- infer env f
(s2,t2) <- infer env a
tv <- newVar
s3 <- unify (apply t1 s2) (t2 :-> tv)
return (s1 `compose` s2 `compose` s3, apply tv s3)
infer env (ELam n e) = do
tv <- newVar
(s1,tbody) <- infer (Map.insert n (Scheme mempty tv) env) e
return (s1,(apply tv s1) :-> tbody)
infer env (ELet n e1 e2) = do
(s1,t1) <- infer env e1
let env' = applyEnv (Map.insert n (generalize env t1) env) s1
(s2,t2) <- infer env' e2
return (s1 `compose` s2,t2)
inference :: Exp -> Either String Ty
inference e = runIdentity $ runExceptT $ (flip evalStateT) 0 act
where
act = do
(s,t) <- infer mempty e
return (apply t s)
-- test
ok =
[ ELit LInt
, ELam "x" $ EVar "x"
, ELam "x" $ ELam "y" $ ELit LFloat
, ELam "x" $ EApp (EVar "x") (ELit LBool)
, ELam "x" $ EApp (EApp (EPrimFun PAddI) (ELit LInt)) (EVar "x")
, ELet "id" (ELam "x" $ EVar "x") (ELet "a" (EApp (EVar "id") (ELit LBool)) (EApp (EVar "id") (ELit LBool)))
, ELet "id" (ELam "x" $ EVar "x") (ELet "a" (EApp (EVar "id") (ELit LBool)) (EApp (EVar "id") (ELit LFloat)))
]
err =
[ ELam "x" $ EApp (EVar "x") (EVar "x")
, EApp (ELit LInt) (ELit LInt)
]
test = do
putStrLn "Ok:"
mapM_ (\e -> print e >> (print . inference $ e)) ok
putStrLn "Error:"
mapM_ (\e -> print e >> (print . inference $ e)) err
| null | https://raw.githubusercontent.com/lambdacube3d/lambdacube-edsl/4347bb0ed344e71c0333136cf2e162aec5941df7/typesystem/HindleyMilner.hs | haskell | primitive types
test | import Data.Functor.Identity
import Control.Monad.Except
import Control.Monad.State
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Monoid
import Data.Functor
data Lit
= LInt
| LBool
| LFloat
deriving (Show,Eq,Ord)
data PrimFun
= PAddI
| PAnd
| PMulF
deriving (Show,Eq,Ord)
data Exp
= ELit Lit
| EPrimFun PrimFun
| EVar EName
| EApp Exp Exp
| ELam EName Exp
| ELet EName Exp Exp
deriving (Show,Eq,Ord)
infixr 7 :->
data Ty
= TVar TName
| Ty :-> Ty
| TInt
| TBool
| TFloat
deriving (Show,Eq,Ord)
data Scheme = Scheme (Set TName) Ty
type EName = String
type TName = String
type Env = Map EName Scheme
type Subst = Map TName Ty
inferPrimFun :: PrimFun -> Ty
inferPrimFun a = case a of
PAddI -> TInt :-> TInt :-> TInt
PAnd -> TBool :-> TBool :-> TBool
PMulF -> TFloat :-> TFloat :-> TFloat
inferLit :: Lit -> Ty
inferLit a = case a of
LInt -> TInt
LBool -> TBool
LFloat -> TFloat
type Unique a = StateT Int (Except String) a
newVar :: Unique Ty
newVar = do
n <- get
put (n+1)
return $ TVar $ 't':show n
applyEnv :: Env -> Subst -> Env
applyEnv e s = fmap (flip applyScheme s) e
applyScheme :: Scheme -> Subst -> Scheme
applyScheme (Scheme vars t) s = Scheme vars (apply t (Map.filterWithKey (\k _ -> Set.notMember k vars) s))
freeVarsScheme :: Scheme -> Set TName
freeVarsScheme (Scheme vars t) = freeVars t `Set.difference` vars
freeVarsEnv :: Env -> Set TName
freeVarsEnv env = Set.unions . Map.elems . fmap freeVarsScheme $ env
generalize :: Env -> Ty -> Scheme
generalize env t = Scheme (freeVars t `Set.difference` freeVarsEnv env) t
instantiate :: Scheme -> Unique Ty
instantiate (Scheme vars t) = do
let l = Set.toList vars
s <- mapM (\_ -> newVar) l
return $ apply t $ Map.fromList $ zip l s
apply :: Ty -> Subst -> Ty
apply (TVar a) st = case Map.lookup a st of
Nothing -> TVar a
Just t -> t
apply (a :-> b) st = (apply a st) :-> (apply b st)
apply t _ = t
unify :: Ty -> Ty -> Unique Subst
unify (TVar u) t = bindVar u t
unify t (TVar u) = bindVar u t
unify (a1 :-> b1) (a2 :-> b2) = do
s1 <- unify a1 a2
s2 <- unify (apply b1 s1) (apply b2 s1)
return $ s1 `compose` s2
unify a b
| a == b = return mempty
| otherwise = throwError $ "can not unify " ++ show a ++ " with " ++ show b
freeVars :: Ty -> Set TName
freeVars (TVar a) = Set.singleton a
freeVars (a :-> b) = freeVars a `mappend` freeVars b
freeVars _ = mempty
bindVar :: TName -> Ty -> Unique Subst
bindVar n t
| TVar n == t = return mempty
| n `Set.member` freeVars t = throwError $ "Infinite type, type variable " ++ n ++ " occurs in " ++ show t
| otherwise = return $ Map.singleton n t
compose :: Subst -> Subst -> Subst
compose a b = mappend a $ (flip apply) a <$> b
remove :: EName -> Env -> Env
remove n e = Map.delete n e
infer :: Env -> Exp -> Unique (Subst,Ty)
infer env (EPrimFun f) = return (mempty,inferPrimFun f)
infer env (ELit l) = return (mempty,inferLit l)
infer env (EVar n) = case Map.lookup n env of
Nothing -> throwError $ "unbounded variable: " ++ n
Just t -> do
t' <- instantiate t
return (mempty,t')
infer env (EApp f a) = do
(s1,t1) <- infer env f
(s2,t2) <- infer env a
tv <- newVar
s3 <- unify (apply t1 s2) (t2 :-> tv)
return (s1 `compose` s2 `compose` s3, apply tv s3)
infer env (ELam n e) = do
tv <- newVar
(s1,tbody) <- infer (Map.insert n (Scheme mempty tv) env) e
return (s1,(apply tv s1) :-> tbody)
infer env (ELet n e1 e2) = do
(s1,t1) <- infer env e1
let env' = applyEnv (Map.insert n (generalize env t1) env) s1
(s2,t2) <- infer env' e2
return (s1 `compose` s2,t2)
inference :: Exp -> Either String Ty
inference e = runIdentity $ runExceptT $ (flip evalStateT) 0 act
where
act = do
(s,t) <- infer mempty e
return (apply t s)
ok =
[ ELit LInt
, ELam "x" $ EVar "x"
, ELam "x" $ ELam "y" $ ELit LFloat
, ELam "x" $ EApp (EVar "x") (ELit LBool)
, ELam "x" $ EApp (EApp (EPrimFun PAddI) (ELit LInt)) (EVar "x")
, ELet "id" (ELam "x" $ EVar "x") (ELet "a" (EApp (EVar "id") (ELit LBool)) (EApp (EVar "id") (ELit LBool)))
, ELet "id" (ELam "x" $ EVar "x") (ELet "a" (EApp (EVar "id") (ELit LBool)) (EApp (EVar "id") (ELit LFloat)))
]
err =
[ ELam "x" $ EApp (EVar "x") (EVar "x")
, EApp (ELit LInt) (ELit LInt)
]
test = do
putStrLn "Ok:"
mapM_ (\e -> print e >> (print . inference $ e)) ok
putStrLn "Error:"
mapM_ (\e -> print e >> (print . inference $ e)) err
|
66fbdd3fe967a773f39a1fbf3f19fa20140a34b8e4aa0a74afb5cb979085d0f6 | jwiegley/notes | Swift.hs | module Swift where
data FooArgs = FooArgs
data Result = Result
untilRight :: (e -> Either e a) -> e -> a
untilRight f = go where
go x = case f x of
Left y -> go y
Right y -> y
swift :: (FooArgs -> Either FooArgs Result) -> FooArgs -> Result
swift = untilRight
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/f719a3d41696d48f6005/Swift.hs | haskell | module Swift where
data FooArgs = FooArgs
data Result = Result
untilRight :: (e -> Either e a) -> e -> a
untilRight f = go where
go x = case f x of
Left y -> go y
Right y -> y
swift :: (FooArgs -> Either FooArgs Result) -> FooArgs -> Result
swift = untilRight
| |
1e489601af180b5a5d6cfe6a4fde51cdc6894e631f1c58851466ecf36891d242 | ryanpbrewster/haskell | P122Test.hs | module Problems.P122Test
( case_122_main
) where
import Problems.P122
import Test.Tasty.Discover (Assertion, (@?=))
case_122_main :: Assertion
case_122_main = solve @?= "233168"
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/project-euler/tests/Problems/P122Test.hs | haskell | module Problems.P122Test
( case_122_main
) where
import Problems.P122
import Test.Tasty.Discover (Assertion, (@?=))
case_122_main :: Assertion
case_122_main = solve @?= "233168"
| |
fb9d430f936ad53e01aa41dd812c7d2a86c2178d0d69ef90c7ffee135562cd61 | BranchTaken/Hemlock | test_nbI_wX.ml | open! Basis.Rudiments
open! Basis
let test () =
File.Fmt.stdout
|> (fun formatter ->
List.fold I16.([kv (-32768L); kv (-1L); kv 0L; kv 1L; kv 32767L]) ~init:formatter
~f:(fun formatter i ->
formatter
|> Fmt.fmt "extend_to_i512 "
|> I16.pp i
|> Fmt.fmt " -> "
|> I512.pp (I16.extend_to_i512 i)
|> Fmt.fmt "\n"
)
)
|> Fmt.fmt "\n"
|> (fun formatter ->
List.fold I512.([of_i64 (-32769L); of_i64 (-32768L); of_i64 (-1L); of_i64 0L; of_i64 1L;
of_i64 32767L; of_i64 32768L]) ~init:formatter ~f:(fun formatter u ->
formatter
|> Fmt.fmt "trunc_of_i512/narrow_of_i512_opt "
|> I512.pp u
|> Fmt.fmt " -> "
|> I16.pp (I16.trunc_of_i512 u)
|> Fmt.fmt "/"
|> (Option.fmt I16.pp) (I16.narrow_of_i512_opt u)
|> Fmt.fmt "\n"
)
)
|> ignore
let _ = test ()
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/f3604ceda4f75cf18b6ee2b1c2f3c5759ad495a5/bootstrap/test/basis/convert/test_nbI_wX.ml | ocaml | open! Basis.Rudiments
open! Basis
let test () =
File.Fmt.stdout
|> (fun formatter ->
List.fold I16.([kv (-32768L); kv (-1L); kv 0L; kv 1L; kv 32767L]) ~init:formatter
~f:(fun formatter i ->
formatter
|> Fmt.fmt "extend_to_i512 "
|> I16.pp i
|> Fmt.fmt " -> "
|> I512.pp (I16.extend_to_i512 i)
|> Fmt.fmt "\n"
)
)
|> Fmt.fmt "\n"
|> (fun formatter ->
List.fold I512.([of_i64 (-32769L); of_i64 (-32768L); of_i64 (-1L); of_i64 0L; of_i64 1L;
of_i64 32767L; of_i64 32768L]) ~init:formatter ~f:(fun formatter u ->
formatter
|> Fmt.fmt "trunc_of_i512/narrow_of_i512_opt "
|> I512.pp u
|> Fmt.fmt " -> "
|> I16.pp (I16.trunc_of_i512 u)
|> Fmt.fmt "/"
|> (Option.fmt I16.pp) (I16.narrow_of_i512_opt u)
|> Fmt.fmt "\n"
)
)
|> ignore
let _ = test ()
| |
1f38795b1b0601294f23a5517a6848b994039e0b0899d4b1cd4de45b5f0ae3ed | dyzsr/ocaml-selectml | pr5057a_bad.ml | TEST
flags = " -w -a "
ocamlc_byte_exit_status = " 2 "
* setup - ocamlc.byte - build - env
* * ocamlc.byte
* * * check - ocamlc.byte - output
flags = " -w -a "
ocamlc_byte_exit_status = "2"
* setup-ocamlc.byte-build-env
** ocamlc.byte
*** check-ocamlc.byte-output
*)
(* This one should fail *)
let f flag =
let module T = Set.Make(struct type t = int let compare = compare end) in
let _ = match flag with `A -> 0 | `B r -> r in
let _ = match flag with `A -> T.mem | `B r -> r in
()
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-polyvariants-bugs/pr5057a_bad.ml | ocaml | This one should fail | TEST
flags = " -w -a "
ocamlc_byte_exit_status = " 2 "
* setup - ocamlc.byte - build - env
* * ocamlc.byte
* * * check - ocamlc.byte - output
flags = " -w -a "
ocamlc_byte_exit_status = "2"
* setup-ocamlc.byte-build-env
** ocamlc.byte
*** check-ocamlc.byte-output
*)
let f flag =
let module T = Set.Make(struct type t = int let compare = compare end) in
let _ = match flag with `A -> 0 | `B r -> r in
let _ = match flag with `A -> T.mem | `B r -> r in
()
|
0c064901925a89aee52e747f9af290f479e6807ef22157291679118b73816e49 | janestreet/sexp | main_pp.ml | open! Core
(* Options are provided for parameters which are likely to change a lot and are likely to
vary depending on the file that is being processed.
*)
let command =
Command.basic
~summary:"Pretty print S expressions in a human-friendly way."
~readme:(fun () ->
"Use pre-defined styles or load a custom style from a file."
^ "\nYou can use -p to print out one of the predefined styles and customize it.")
(let%map_open.Command config_file =
flag
"-c"
(optional Filename_unix.arg_type)
~doc:"file use custom configuration file"
and color =
flag
"-color"
no_arg
~doc:
(" enable colors. By default, colors are disabled "
^ "even if they are set in the configuration file")
and interpret_atom_as_sexp = flag "-i" no_arg ~doc:" try to interpret atoms as sexps"
and drop_comments = flag "-drop-comments" no_arg ~doc:" drop comments"
and new_line_separator =
flag "-s" (optional bool) ~doc:"bool separate sexps with an empty line"
and print_settings =
flag "-p" no_arg ~doc:" print the settings in colorless format"
in
fun () ->
let config =
match config_file with
| Some path -> Sexp.load_sexp_conv_exn path Sexp_pretty.Config.t_of_sexp
| None -> Sexp_pretty.Config.default
in
let config =
let color = color || print_settings in
Sexp_pretty.Config.update
config
~interpret_atom_as_sexp
~drop_comments
~color
?new_line_separator
in
if print_settings
then (
let config_for_output =
{ config with
atom_coloring = Color_none
; paren_coloring = false
; atom_printing = Escaped
}
in
let fmt = Format.formatter_of_out_channel Stdlib.stdout in
let sexp =
Sexp_pretty.sexp_to_sexp_or_comment (Sexp_pretty.Config.sexp_of_t config)
in
Sexp_pretty.Sexp_with_layout.pp_formatter config_for_output fmt sexp)
else (
let sparser = Sexp.With_layout.Parser.sexp Sexp.With_layout.Lexer.main in
let lexbuf = Lexing.from_channel Stdlib.stdin in
let fmt = Format.formatter_of_out_channel stdout in
let next () =
try Some (sparser lexbuf) with
| _ -> None
in
Sexp_pretty.Sexp_with_layout.pp_formatter' ~next config fmt))
;;
| null | https://raw.githubusercontent.com/janestreet/sexp/df820aa2a657238face2c244880cb8b2e3f0a322/bin/main_pp.ml | ocaml | Options are provided for parameters which are likely to change a lot and are likely to
vary depending on the file that is being processed.
| open! Core
let command =
Command.basic
~summary:"Pretty print S expressions in a human-friendly way."
~readme:(fun () ->
"Use pre-defined styles or load a custom style from a file."
^ "\nYou can use -p to print out one of the predefined styles and customize it.")
(let%map_open.Command config_file =
flag
"-c"
(optional Filename_unix.arg_type)
~doc:"file use custom configuration file"
and color =
flag
"-color"
no_arg
~doc:
(" enable colors. By default, colors are disabled "
^ "even if they are set in the configuration file")
and interpret_atom_as_sexp = flag "-i" no_arg ~doc:" try to interpret atoms as sexps"
and drop_comments = flag "-drop-comments" no_arg ~doc:" drop comments"
and new_line_separator =
flag "-s" (optional bool) ~doc:"bool separate sexps with an empty line"
and print_settings =
flag "-p" no_arg ~doc:" print the settings in colorless format"
in
fun () ->
let config =
match config_file with
| Some path -> Sexp.load_sexp_conv_exn path Sexp_pretty.Config.t_of_sexp
| None -> Sexp_pretty.Config.default
in
let config =
let color = color || print_settings in
Sexp_pretty.Config.update
config
~interpret_atom_as_sexp
~drop_comments
~color
?new_line_separator
in
if print_settings
then (
let config_for_output =
{ config with
atom_coloring = Color_none
; paren_coloring = false
; atom_printing = Escaped
}
in
let fmt = Format.formatter_of_out_channel Stdlib.stdout in
let sexp =
Sexp_pretty.sexp_to_sexp_or_comment (Sexp_pretty.Config.sexp_of_t config)
in
Sexp_pretty.Sexp_with_layout.pp_formatter config_for_output fmt sexp)
else (
let sparser = Sexp.With_layout.Parser.sexp Sexp.With_layout.Lexer.main in
let lexbuf = Lexing.from_channel Stdlib.stdin in
let fmt = Format.formatter_of_out_channel stdout in
let next () =
try Some (sparser lexbuf) with
| _ -> None
in
Sexp_pretty.Sexp_with_layout.pp_formatter' ~next config fmt))
;;
|
8b940a14001a04f6326a2ec851376a827d290a677a50927a8986995c87cab1f6 | neeraj9/hello-erlang-rump | uwiki_app.erl | %%%-------------------------------------------------------------------
@author nsharma
( C ) 2016 ,
%%% @doc
%%%
%%% @end
Copyright ( c ) 2016 , < > .
%%% 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.
%%%
%%% * The names of its contributors may not 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 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(uwiki_app).
-author("nsharma").
-behaviour(application).
%% Application callbacks
-export([start/2,
stop/1]).
%%%===================================================================
%%% Application callbacks
%%%===================================================================
%%--------------------------------------------------------------------
@private
%% @doc
%% This function is called whenever an application is started using
application : start/[1,2 ] , and should start the processes of the
%% application. If the application is structured according to the OTP
%% design principles as a supervision tree, this means starting the
%% top supervisor of the tree.
%%
%% @end
%%--------------------------------------------------------------------
-spec(start(StartType :: normal | {takeover, node()} | {failover, node()},
StartArgs :: term()) ->
{ok, pid()} |
{ok, pid(), State :: term()} |
{error, Reason :: term()}).
start(_StartType, _StartArgs) ->
Dispatch = cowboy_router:compile([
{'_', [
{"/wiki/textsearch", uwiki_textsearch_handler, []}
]}
]),
{ok, _CowboyPid} = cowboy:start_clear(http, 100, [{port, 9595}], #{
env => #{dispatch => Dispatch}
}),
case uwiki_sup:start_link() of
{ok, Pid} ->
{ok, Pid};
Error ->
Error
end.
%%--------------------------------------------------------------------
@private
%% @doc
%% This function is called whenever an application has stopped. It
%% is intended to be the opposite of Module:start/2 and should do
%% any necessary cleaning up. The return value is ignored.
%%
%% @end
%%--------------------------------------------------------------------
-spec(stop(State :: term()) -> term()).
stop(_State) ->
ok.
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/neeraj9/hello-erlang-rump/304d2f0faaef64677de22d9a3495297e08d90a3f/apps/uwiki/src/uwiki_app.erl | erlang | -------------------------------------------------------------------
@doc
@end
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.
* The names of its contributors may not 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
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------
Application callbacks
===================================================================
Application callbacks
===================================================================
--------------------------------------------------------------------
@doc
This function is called whenever an application is started using
application. If the application is structured according to the OTP
design principles as a supervision tree, this means starting the
top supervisor of the tree.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
This function is called whenever an application has stopped. It
is intended to be the opposite of Module:start/2 and should do
any necessary cleaning up. The return value is ignored.
@end
--------------------------------------------------------------------
===================================================================
=================================================================== | @author nsharma
( C ) 2016 ,
Copyright ( c ) 2016 , < > .
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-module(uwiki_app).
-author("nsharma").
-behaviour(application).
-export([start/2,
stop/1]).
@private
application : start/[1,2 ] , and should start the processes of the
-spec(start(StartType :: normal | {takeover, node()} | {failover, node()},
StartArgs :: term()) ->
{ok, pid()} |
{ok, pid(), State :: term()} |
{error, Reason :: term()}).
start(_StartType, _StartArgs) ->
Dispatch = cowboy_router:compile([
{'_', [
{"/wiki/textsearch", uwiki_textsearch_handler, []}
]}
]),
{ok, _CowboyPid} = cowboy:start_clear(http, 100, [{port, 9595}], #{
env => #{dispatch => Dispatch}
}),
case uwiki_sup:start_link() of
{ok, Pid} ->
{ok, Pid};
Error ->
Error
end.
@private
-spec(stop(State :: term()) -> term()).
stop(_State) ->
ok.
Internal functions
|
7cc5e0bf9a3048521695d563f6bcbc81b3774a449b7414116a2ecf6d6237c9a0 | jaspervdj/number-six | Irc.hs | --------------------------------------------------------------------------------
| Various IRC utilities
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Util.Irc
( mode
, meAction
, kick
) where
--------------------------------------------------------------------------------
import Control.Monad (when)
import Data.Text (Text)
--------------------------------------------------------------------------------
import NumberSix.Irc
import NumberSix.Util
--------------------------------------------------------------------------------
| Make an action a /me command
meAction :: Text -> Text
meAction x = "\SOHACTION " <> x <> "\SOH"
--------------------------------------------------------------------------------
-- | Kick someone
kick :: Text -> Text -> Irc ()
kick nick reason = do
channel <- getChannel
myNick <- getNick
-- The bot won't kick itself
when (not $ nick ==? myNick) $
writeMessage "KICK" [channel, nick, reason]
--------------------------------------------------------------------------------
-- | Change the mode for a user
mode :: Text -- ^ Mode change string (e.g. @+v@)
^ Target user
-> Irc () -- ^ No result
mode mode' nick = do
channel <- getChannel
writeMessage "MODE" [channel, mode', nick]
| null | https://raw.githubusercontent.com/jaspervdj/number-six/1aba681786bd85bd20f79406c681ea581b982cd6/src/NumberSix/Util/Irc.hs | haskell | ------------------------------------------------------------------------------
# LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Kick someone
The bot won't kick itself
------------------------------------------------------------------------------
| Change the mode for a user
^ Mode change string (e.g. @+v@)
^ No result | | Various IRC utilities
module NumberSix.Util.Irc
( mode
, meAction
, kick
) where
import Control.Monad (when)
import Data.Text (Text)
import NumberSix.Irc
import NumberSix.Util
| Make an action a /me command
meAction :: Text -> Text
meAction x = "\SOHACTION " <> x <> "\SOH"
kick :: Text -> Text -> Irc ()
kick nick reason = do
channel <- getChannel
myNick <- getNick
when (not $ nick ==? myNick) $
writeMessage "KICK" [channel, nick, reason]
^ Target user
mode mode' nick = do
channel <- getChannel
writeMessage "MODE" [channel, mode', nick]
|
55f307d57906dfa9aafff828910d33c6f18bf320dc07e448ce19ab9cfb092c11 | music-suite/music-score | Phrases.hs |
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
-- | Provides phrase-wise traversal.
module Music.Score.Phrases (
* HasPhrases class
HasPhrases(..),
HasPhrases',
phrases,
phrases',
-- * Phrase types etc
Phrase,
MVoice,
PVoice,
TVoice,
-- ** Utility
mVoicePVoice,
mVoiceTVoice,
pVoiceTVoice,
unsafeMVoicePVoice,
singleMVoice,
oldSingleMVoice,
mapPhrasesWithPrevAndCurrentOnset,
) where
import Control.Applicative
import Control.Applicative
import Control.Comonad (Comonad (..), extract)
import Control.Exception (assert)
import Control.Lens
import Control.Lens hiding (rewrite)
import Control.Monad
import Control.Monad.Plus
import Data.AffineSpace
import Data.AffineSpace
import Data.Bifunctor
import Data.Colour.Names as Color
import Data.Either
import Data.Either
import Data.Foldable (Foldable)
import Data.Functor.Adjunction (unzipR)
import Data.Functor.Context
import Data.Functor.Contravariant (Op(..))
import Data.Functor.Couple
import qualified Data.List as List
import qualified Data.List
import Data.Maybe
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Semigroup
import Data.Semigroup
import Data.Traversable
import Data.Traversable (Traversable, sequenceA)
import Data.VectorSpace hiding (Sum (..))
import System.Process
import Music.Score.Part
import Music.Time
import Music.Time.Internal.Convert ()
import Music.Time.Internal.Util
-- |
-- For a phrase, we simply use a voice without rests.
--
To represent a sequence of phrases we provide two equivalent representations :
--
* ' MVoice ' is a sequence of notes / chords or rests . All consecutive non - rests consitute a phrase .
--
-- * 'PVoice' is a sequence of phrases or durations.
--
type Phrase a = Voice a
-- |
-- A sequence of phrases or rests, represented as notes or rests.
--
-- Each consecutive sequence of non-rest elements is considered to be a phrase.
-- For a more explicit representation of the phrase structure, see 'PVoice'.
--
type MVoice a = Voice (Maybe a)
-- |
-- A sequence of phrases or rests, represented with explicit phrase structure.
--
type PVoice a = [Either Duration (Phrase a)]
-- |
-- A sequence of phrases or rests, represented as phrases with an explicit onset.
--
This is only isomorphic to ' MVoice ' ( and ' PVoice ' ) up to onset equivalence .
--
type TVoice a = Track (Phrase a)
-- |
-- Classes that provide a phrase traversal.
--
class HasPhrases s t a b | s -> a, t -> b, s b -> t, t a -> s where
mvoices :: Traversal s t (MVoice a) (MVoice b)
-- | Traverses all phrases in a voice.
instance HasPhrases (MVoice a) (MVoice b) a b where
mvoices = id
-- | Traverses all phrases in a voice.
instance HasPhrases (PVoice a) (PVoice b) a b where
-- Note: This is actually OK in 'phr', as that just becomes (id . each . _Right)
mvoices = from unsafeMVoicePVoice
-- | Traverses all phrases in each voice, using 'extracted'.
instance (HasPart' a, Ord (Part a)) => HasPhrases (Score a) (Score b) a b where
mvoices = extracted . each . oldSingleMVoice
FIXME Should be written like this , above instance to be phased out !
-- | Traverses all phrases in each voice , using ' extracted ' .
instance ( HasPart ' a , ( Part a ) , a ~ b ) = > ( Score a ) ( Score b ) a b where
mvoices = extracted . each . singleMVoice
FIXME Should be written like this, above instance to be phased out!
-- | Traverses all phrases in each voice, using 'extracted'.
instance (HasPart' a, Ord (Part a), a ~ b) => HasPhrases (Score a) (Score b) a b where
mvoices = extracted . each . singleMVoice
-}
type HasPhrases' s a = HasPhrases s s a a
-- |
-- A simple generic phrase-traversal.
--
phrases' :: HasPhrases' s a => Traversal' s (Phrase a)
phrases' = phrases
-- |
-- A generic phrase-traversal.
--
phrases :: HasPhrases s t a b => Traversal s t (Phrase a) (Phrase b)
phrases = mvoices . mVoicePVoice . each . _Right
-- |
-- View an 'MVoice' as a 'PVoice'.
--
mVoicePVoice :: Lens (MVoice a) (MVoice b) (PVoice a) (PVoice b)
mVoicePVoice = unsafeMVoicePVoice
-- TODO meta
-- |
-- View an 'MVoice' as a 'PVoice' and vice versa.
--
This a valid ' ' up to meta - data equivalence .
--
unsafeMVoicePVoice :: Iso (MVoice a) (MVoice b) (PVoice a) (PVoice b)
unsafeMVoicePVoice = iso mvoiceToPVoice pVoiceToMVoice
where
mvoiceToPVoice :: MVoice a -> PVoice a
mvoiceToPVoice =
map ( bimap voiceToRest voiceToPhrase
. bimap (^.from unsafePairs) (^.from unsafePairs) )
. groupDiff' (isJust . snd)
. view pairs
voiceToRest :: MVoice a -> Duration
voiceToRest = sumOf (pairs.each._1) . fmap (\x -> assert (isNothing x) x)
-- TODO just _duration
voiceToPhrase :: MVoice a -> Phrase a
voiceToPhrase = fmap fromJust
pVoiceToMVoice :: (PVoice a) -> MVoice a
pVoiceToMVoice = mconcat . fmap (either restToVoice phraseToVoice)
restToVoice :: Duration -> MVoice a
restToVoice d = stretch d $ pure Nothing
phraseToVoice :: Phrase a -> MVoice a
phraseToVoice = fmap Just
TODO unsafe , phase out
oldSingleMVoice :: Iso (Score a) (Score b) (MVoice a) (MVoice b)
oldSingleMVoice = iso scoreToVoice voiceToScore'
where
scoreToVoice :: Score a -> MVoice a
scoreToVoice = (^. voice) . fmap (^. note) . fmap throwTime . addRests .
TODO
List.sortBy (comparing (^._1))
end TODO
. (^. triples)
where
throwTime (t,d,x) = (d,x)
addRests = concat . snd . List.mapAccumL g 0
where
g u (t, d, x)
| u == t = (t .+^ d, [(t, d, Just x)])
| u < t = (t .+^ d, [(u, t .-. u, Nothing), (t, d, Just x)])
| otherwise = error "oldSingleMVoice: Strange prevTime"
voiceToScore :: Voice a -> Score a
voiceToScore = renderAlignedVoice . aligned 0 0
voiceToScore' :: MVoice b -> Score b
voiceToScore' = mcatMaybes . voiceToScore
singleMVoice :: (a ~ b) => Prism (Score a) (Score b) (MVoice a) (MVoice b)
singleMVoice = prism' voiceToScore' scoreToVoice
where
voiceToScore :: Voice a -> Score a
voiceToScore = renderAlignedVoice . aligned 0 0
voiceToScore' :: MVoice b -> Score b
voiceToScore' = mcatMaybes . voiceToScore
scoreToVoice :: Score a -> Maybe (MVoice a)
scoreToVoice sc
| hasOverlappingEvents sc = Nothing
| otherwise = Just . (^. voice) . fmap (^. note) . fmap throwTime . addRests .
TODO
List.sortBy (comparing (^._1))
end TODO
. (^. triples) $ sc
where
throwTime (t,d,x) = (d,x)
addRests = concat . snd . List.mapAccumL g 0
where
g u (t, d, x)
| u == t = (t .+^ d, [(t, d, Just x)])
| u < t = (t .+^ d, [(u, t .-. u, Nothing), (t, d, Just x)])
| otherwise = error "scoreToVoice: Impossible!" -- Because of overlapping events guard
foo : : ' s a = > s - > [ TVoice a ]
mapPhrasesWithPrevAndCurrentOnset :: HasPhrases s t a b => (Maybe Time -> Time -> Phrase a -> Phrase b) -> s -> t
mapPhrasesWithPrevAndCurrentOnset f = over (mvoices . mVoiceTVoice) (withPrevAndCurrentOnset f)
withPrevAndCurrentOnset :: (Maybe Time -> Time -> a -> b) -> Track a -> Track b
withPrevAndCurrentOnset f = over placeds (fmap (\(x,y,z) -> fmap (f (fmap placedOnset x) (placedOnset y)) y) . withPrevNext)
where
placedOnset :: Placed a -> Time
placedOnset = view (from placed . _1)
mVoiceTVoice :: Lens (MVoice a) (MVoice b) (TVoice a) (TVoice b)
mVoiceTVoice = mVoicePVoice . pVoiceTVoice
pVoiceTVoice :: Lens (PVoice a) (PVoice b) (TVoice a) (TVoice b)
pVoiceTVoice = lens pVoiceToTVoice (flip tVoiceToPVoice)
where
pVoiceToTVoice :: PVoice a -> TVoice a
pVoiceToTVoice x = mkTrack $ rights $ map (sequenceA) $ firsts (offsetPoints (0::Time)) (withDurationR x)
TODO assert no overlapping
tVoiceToPVoice :: TVoice a -> PVoice b -> PVoice a
tVoiceToPVoice tv pv = set _rights newPhrases pv
where
newPhrases = toListOf traverse tv
_rights :: Lens [Either a b] [Either a c] [b] [c]
_rights = lens _rightsGet (flip _rightsSet)
where
_rightsGet :: [Either a b] -> [b]
_rightsGet = rights
_rightsSet :: [c] -> [Either a b] -> [Either a c]
_rightsSet cs = sndMapAccumL f cs
where
f cs (Left a) = (cs, Left a)
f (c:cs) (Right b) = (cs, Right c)
f [] (Right _) = error "No more cs"
sndMapAccumL f z = snd . List.mapAccumL f z
firsts :: ([a] -> [b]) -> [(a,c)] -> [(b,c)]
firsts f = uncurry zip . first f . unzipR
mkTrack :: [(Time, a)] -> Track a
mkTrack = view track . map (view placed)
withDurationR :: (Functor f, HasDuration a) => f a -> f (Duration, a)
withDurationR = fmap $ \x -> (_duration x, x)
TODO generalize and move
mapWithDuration :: HasDuration a => (Duration -> a -> b) -> a -> b
mapWithDuration = over dual withDurationL . uncurry
where
withDurationL :: (Contravariant f, HasDuration a) => f (Duration, a) -> f a
withDurationL = contramap $ \x -> (_duration x, x)
dual :: Iso (a -> b) (c -> d) (Op b a) (Op d c)
dual = iso Op getOp
dursToVoice :: [Duration] -> Voice ()
dursToVoice = mconcat . map (\d -> stretch d $ return ())
{-
>>> print $ view (mVoiceTVoice) $ (fmap Just (dursToVoice [1,2,1]) <> return Nothing <> return (Just ()))
-}
-- |
-- Group contigous sequences matching/not-matching the predicate.
--
> > > groupDiff (= = 0 ) [ 0,1,2,3,5,0,0,6,7 ]
[ [ 0],[1,2,3,5],[0,0],[6,7 ] ]
--
groupDiff :: (a -> Bool) -> [a] -> [[a]]
groupDiff p [] = []
groupDiff p (x:xs)
| p x = (x : List.takeWhile p xs) : groupDiff p (List.dropWhile p xs)
| not (p x) = (x : List.takeWhile (not . p) xs) : groupDiff p (List.dropWhile (not . p) xs)
groupDiff' :: (a -> Bool) -> [a] -> [Either [a] [a]]
groupDiff' p [] = []
groupDiff' p (x:xs)
| not (p x) = Left (x : List.takeWhile (not . p) xs) : groupDiff' p (List.dropWhile (not . p) xs)
| p x = Right (x : List.takeWhile p xs) : groupDiff' p (List.dropWhile p xs)
-- JUNK
| null | https://raw.githubusercontent.com/music-suite/music-score/aa7182d8ded25c03a56b83941fc625123a7931f8/src/Music/Score/Phrases.hs | haskell | # LANGUAGE ConstraintKinds #
| Provides phrase-wise traversal.
* Phrase types etc
** Utility
|
For a phrase, we simply use a voice without rests.
* 'PVoice' is a sequence of phrases or durations.
|
A sequence of phrases or rests, represented as notes or rests.
Each consecutive sequence of non-rest elements is considered to be a phrase.
For a more explicit representation of the phrase structure, see 'PVoice'.
|
A sequence of phrases or rests, represented with explicit phrase structure.
|
A sequence of phrases or rests, represented as phrases with an explicit onset.
|
Classes that provide a phrase traversal.
| Traverses all phrases in a voice.
| Traverses all phrases in a voice.
Note: This is actually OK in 'phr', as that just becomes (id . each . _Right)
| Traverses all phrases in each voice, using 'extracted'.
| Traverses all phrases in each voice , using ' extracted ' .
| Traverses all phrases in each voice, using 'extracted'.
|
A simple generic phrase-traversal.
|
A generic phrase-traversal.
|
View an 'MVoice' as a 'PVoice'.
TODO meta
|
View an 'MVoice' as a 'PVoice' and vice versa.
TODO just _duration
Because of overlapping events guard
>>> print $ view (mVoiceTVoice) $ (fmap Just (dursToVoice [1,2,1]) <> return Nothing <> return (Just ()))
|
Group contigous sequences matching/not-matching the predicate.
JUNK |
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
module Music.Score.Phrases (
* HasPhrases class
HasPhrases(..),
HasPhrases',
phrases,
phrases',
Phrase,
MVoice,
PVoice,
TVoice,
mVoicePVoice,
mVoiceTVoice,
pVoiceTVoice,
unsafeMVoicePVoice,
singleMVoice,
oldSingleMVoice,
mapPhrasesWithPrevAndCurrentOnset,
) where
import Control.Applicative
import Control.Applicative
import Control.Comonad (Comonad (..), extract)
import Control.Exception (assert)
import Control.Lens
import Control.Lens hiding (rewrite)
import Control.Monad
import Control.Monad.Plus
import Data.AffineSpace
import Data.AffineSpace
import Data.Bifunctor
import Data.Colour.Names as Color
import Data.Either
import Data.Either
import Data.Foldable (Foldable)
import Data.Functor.Adjunction (unzipR)
import Data.Functor.Context
import Data.Functor.Contravariant (Op(..))
import Data.Functor.Couple
import qualified Data.List as List
import qualified Data.List
import Data.Maybe
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Semigroup
import Data.Semigroup
import Data.Traversable
import Data.Traversable (Traversable, sequenceA)
import Data.VectorSpace hiding (Sum (..))
import System.Process
import Music.Score.Part
import Music.Time
import Music.Time.Internal.Convert ()
import Music.Time.Internal.Util
To represent a sequence of phrases we provide two equivalent representations :
* ' MVoice ' is a sequence of notes / chords or rests . All consecutive non - rests consitute a phrase .
type Phrase a = Voice a
type MVoice a = Voice (Maybe a)
type PVoice a = [Either Duration (Phrase a)]
This is only isomorphic to ' MVoice ' ( and ' PVoice ' ) up to onset equivalence .
type TVoice a = Track (Phrase a)
class HasPhrases s t a b | s -> a, t -> b, s b -> t, t a -> s where
mvoices :: Traversal s t (MVoice a) (MVoice b)
instance HasPhrases (MVoice a) (MVoice b) a b where
mvoices = id
instance HasPhrases (PVoice a) (PVoice b) a b where
mvoices = from unsafeMVoicePVoice
instance (HasPart' a, Ord (Part a)) => HasPhrases (Score a) (Score b) a b where
mvoices = extracted . each . oldSingleMVoice
FIXME Should be written like this , above instance to be phased out !
instance ( HasPart ' a , ( Part a ) , a ~ b ) = > ( Score a ) ( Score b ) a b where
mvoices = extracted . each . singleMVoice
FIXME Should be written like this, above instance to be phased out!
instance (HasPart' a, Ord (Part a), a ~ b) => HasPhrases (Score a) (Score b) a b where
mvoices = extracted . each . singleMVoice
-}
type HasPhrases' s a = HasPhrases s s a a
phrases' :: HasPhrases' s a => Traversal' s (Phrase a)
phrases' = phrases
phrases :: HasPhrases s t a b => Traversal s t (Phrase a) (Phrase b)
phrases = mvoices . mVoicePVoice . each . _Right
mVoicePVoice :: Lens (MVoice a) (MVoice b) (PVoice a) (PVoice b)
mVoicePVoice = unsafeMVoicePVoice
This a valid ' ' up to meta - data equivalence .
unsafeMVoicePVoice :: Iso (MVoice a) (MVoice b) (PVoice a) (PVoice b)
unsafeMVoicePVoice = iso mvoiceToPVoice pVoiceToMVoice
where
mvoiceToPVoice :: MVoice a -> PVoice a
mvoiceToPVoice =
map ( bimap voiceToRest voiceToPhrase
. bimap (^.from unsafePairs) (^.from unsafePairs) )
. groupDiff' (isJust . snd)
. view pairs
voiceToRest :: MVoice a -> Duration
voiceToRest = sumOf (pairs.each._1) . fmap (\x -> assert (isNothing x) x)
voiceToPhrase :: MVoice a -> Phrase a
voiceToPhrase = fmap fromJust
pVoiceToMVoice :: (PVoice a) -> MVoice a
pVoiceToMVoice = mconcat . fmap (either restToVoice phraseToVoice)
restToVoice :: Duration -> MVoice a
restToVoice d = stretch d $ pure Nothing
phraseToVoice :: Phrase a -> MVoice a
phraseToVoice = fmap Just
TODO unsafe , phase out
oldSingleMVoice :: Iso (Score a) (Score b) (MVoice a) (MVoice b)
oldSingleMVoice = iso scoreToVoice voiceToScore'
where
scoreToVoice :: Score a -> MVoice a
scoreToVoice = (^. voice) . fmap (^. note) . fmap throwTime . addRests .
TODO
List.sortBy (comparing (^._1))
end TODO
. (^. triples)
where
throwTime (t,d,x) = (d,x)
addRests = concat . snd . List.mapAccumL g 0
where
g u (t, d, x)
| u == t = (t .+^ d, [(t, d, Just x)])
| u < t = (t .+^ d, [(u, t .-. u, Nothing), (t, d, Just x)])
| otherwise = error "oldSingleMVoice: Strange prevTime"
voiceToScore :: Voice a -> Score a
voiceToScore = renderAlignedVoice . aligned 0 0
voiceToScore' :: MVoice b -> Score b
voiceToScore' = mcatMaybes . voiceToScore
singleMVoice :: (a ~ b) => Prism (Score a) (Score b) (MVoice a) (MVoice b)
singleMVoice = prism' voiceToScore' scoreToVoice
where
voiceToScore :: Voice a -> Score a
voiceToScore = renderAlignedVoice . aligned 0 0
voiceToScore' :: MVoice b -> Score b
voiceToScore' = mcatMaybes . voiceToScore
scoreToVoice :: Score a -> Maybe (MVoice a)
scoreToVoice sc
| hasOverlappingEvents sc = Nothing
| otherwise = Just . (^. voice) . fmap (^. note) . fmap throwTime . addRests .
TODO
List.sortBy (comparing (^._1))
end TODO
. (^. triples) $ sc
where
throwTime (t,d,x) = (d,x)
addRests = concat . snd . List.mapAccumL g 0
where
g u (t, d, x)
| u == t = (t .+^ d, [(t, d, Just x)])
| u < t = (t .+^ d, [(u, t .-. u, Nothing), (t, d, Just x)])
foo : : ' s a = > s - > [ TVoice a ]
mapPhrasesWithPrevAndCurrentOnset :: HasPhrases s t a b => (Maybe Time -> Time -> Phrase a -> Phrase b) -> s -> t
mapPhrasesWithPrevAndCurrentOnset f = over (mvoices . mVoiceTVoice) (withPrevAndCurrentOnset f)
withPrevAndCurrentOnset :: (Maybe Time -> Time -> a -> b) -> Track a -> Track b
withPrevAndCurrentOnset f = over placeds (fmap (\(x,y,z) -> fmap (f (fmap placedOnset x) (placedOnset y)) y) . withPrevNext)
where
placedOnset :: Placed a -> Time
placedOnset = view (from placed . _1)
mVoiceTVoice :: Lens (MVoice a) (MVoice b) (TVoice a) (TVoice b)
mVoiceTVoice = mVoicePVoice . pVoiceTVoice
pVoiceTVoice :: Lens (PVoice a) (PVoice b) (TVoice a) (TVoice b)
pVoiceTVoice = lens pVoiceToTVoice (flip tVoiceToPVoice)
where
pVoiceToTVoice :: PVoice a -> TVoice a
pVoiceToTVoice x = mkTrack $ rights $ map (sequenceA) $ firsts (offsetPoints (0::Time)) (withDurationR x)
TODO assert no overlapping
tVoiceToPVoice :: TVoice a -> PVoice b -> PVoice a
tVoiceToPVoice tv pv = set _rights newPhrases pv
where
newPhrases = toListOf traverse tv
_rights :: Lens [Either a b] [Either a c] [b] [c]
_rights = lens _rightsGet (flip _rightsSet)
where
_rightsGet :: [Either a b] -> [b]
_rightsGet = rights
_rightsSet :: [c] -> [Either a b] -> [Either a c]
_rightsSet cs = sndMapAccumL f cs
where
f cs (Left a) = (cs, Left a)
f (c:cs) (Right b) = (cs, Right c)
f [] (Right _) = error "No more cs"
sndMapAccumL f z = snd . List.mapAccumL f z
firsts :: ([a] -> [b]) -> [(a,c)] -> [(b,c)]
firsts f = uncurry zip . first f . unzipR
mkTrack :: [(Time, a)] -> Track a
mkTrack = view track . map (view placed)
withDurationR :: (Functor f, HasDuration a) => f a -> f (Duration, a)
withDurationR = fmap $ \x -> (_duration x, x)
TODO generalize and move
mapWithDuration :: HasDuration a => (Duration -> a -> b) -> a -> b
mapWithDuration = over dual withDurationL . uncurry
where
withDurationL :: (Contravariant f, HasDuration a) => f (Duration, a) -> f a
withDurationL = contramap $ \x -> (_duration x, x)
dual :: Iso (a -> b) (c -> d) (Op b a) (Op d c)
dual = iso Op getOp
dursToVoice :: [Duration] -> Voice ()
dursToVoice = mconcat . map (\d -> stretch d $ return ())
> > > groupDiff (= = 0 ) [ 0,1,2,3,5,0,0,6,7 ]
[ [ 0],[1,2,3,5],[0,0],[6,7 ] ]
groupDiff :: (a -> Bool) -> [a] -> [[a]]
groupDiff p [] = []
groupDiff p (x:xs)
| p x = (x : List.takeWhile p xs) : groupDiff p (List.dropWhile p xs)
| not (p x) = (x : List.takeWhile (not . p) xs) : groupDiff p (List.dropWhile (not . p) xs)
groupDiff' :: (a -> Bool) -> [a] -> [Either [a] [a]]
groupDiff' p [] = []
groupDiff' p (x:xs)
| not (p x) = Left (x : List.takeWhile (not . p) xs) : groupDiff' p (List.dropWhile (not . p) xs)
| p x = Right (x : List.takeWhile p xs) : groupDiff' p (List.dropWhile p xs)
|
60272514d332495f768b5e05018edc6968f9fb4e59eaa78eecd130c44324cdeb | liqd/thentos | SimpleAuthSpec.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeOperators #
module Thentos.Action.SimpleAuthSpec where
import Control.Concurrent (forkIO, killThread)
import Control.Exception (bracket)
import Data.Configifier (Source(YamlString), Tagged(Tagged), (>>.))
import LIO (LIO)
import Network.Wai (Application)
import Servant.API ((:>), Get, JSON)
import Servant.Server (serve, enter)
import Test.Hspec (Spec, describe, context, it, around, hspec, shouldBe)
import qualified Data.Aeson as Aeson
import qualified Network.Wreq as Wreq
import Thentos.Prelude
import Thentos.Action.Core
import Thentos.Action.Types
import Thentos.Action.SimpleAuth
import Thentos.Action.Unsafe
import Thentos.Backend.Api.Auth.Types
import Thentos.Backend.Core
import Thentos.Config
import Thentos.Types
import Thentos.Test.Arbitrary ()
import Thentos.Test.Config
import Thentos.Test.Core
tests :: IO ()
tests = hspec spec
spec :: Spec
spec = do
specWithActionEnv
specWithBackends
type Act = LIO DCLabel -- ActionStack (ActionError Void) ()
runActE :: Act a -> IO (Either (ActionError Void) a)
runActE = runLIOE
runAct :: Act a -> IO a
runAct = ioExc' . runActE
setTwoGroups :: MonadThentosIO m => m ()
setTwoGroups = extendClearanceOnPrincipals [GroupAdmin, GroupUser]
setClearanceUid :: MonadThentosIO m => Integer -> m ()
setClearanceUid uid = extendClearanceOnPrincipals [UserA $ UserId uid]
>> extendClearanceOnPrincipals [GroupUser]
setClearanceSid :: MonadThentosIO m => Integer -> m ()
setClearanceSid sid = extendClearanceOnPrincipals [ServiceA . ServiceId . cs . show $ sid]
specWithActionEnv :: Spec
specWithActionEnv = do
describe "assertAuth" $ do
it "throws an error on False" $ do
Left (ActionErrorAnyLabel _) <- runActE (assertAuth $ pure False :: Act ())
return ()
it "returns () on True" $ do
runAct (assertAuth $ pure True :: Act ())
describe "hasUserId" $ do
it "returns True on if uid matches" $ do
True <- runAct (setClearanceUid 3 >> hasUserId (UserId 3) :: Act Bool)
return ()
it "returns False on if uid does not match" $ do
False <- runAct (hasUserId (UserId 3) :: Act Bool)
False <- runAct (setClearanceUid 5 >> hasUserId (UserId 3) :: Act Bool)
return ()
describe "hasServiceId" $ do
it "returns True on if sid matches" $ do
True <- runAct (setClearanceSid 3 >> hasServiceId (ServiceId "3") :: Act Bool)
return ()
it "returns False on if sid does not match" $ do
False <- runAct (hasServiceId (ServiceId "3") :: Act Bool)
False <- runAct (setClearanceSid 5 >> hasServiceId (ServiceId "3") :: Act Bool)
return ()
it "can distinguish uid and sid" $ do
False <- runAct (setClearanceUid 3 >> hasServiceId (ServiceId "3") :: Act Bool)
return ()
describe "hasGroup" $ do
it "returns True if group is present" $ do
True <- runAct (setClearanceUid 3 >> hasGroup GroupUser :: Act Bool)
True <- runAct (setClearanceUid 5 >> hasGroup GroupUser :: Act Bool)
True <- runAct (setTwoGroups >> hasGroup GroupUser :: Act Bool)
return ()
it "returns False if group is missing" $ do
False <- runAct (hasGroup GroupUser :: Act Bool)
False <- runAct (setTwoGroups >> hasGroup GroupServiceAdmin :: Act Bool)
return ()
withPrivIpBackend :: [String] -> (HttpConfig -> IO r) -> IO r
withPrivIpBackend allowIps testCase = do
cfg <- thentosTestConfig' [YamlString . ("allow_ips: " <>) . cs . show $ allowIps]
as <- createActionEnv' cfg
let Just becfg = Tagged <$> (as ^. aStConfig) >>. (Proxy :: Proxy '["backend"])
bracket (forkIO $ runWarpWithCfg becfg $ serveApi as)
killThread
(\_ -> testCase becfg)
type Api = ThentosAuth :> Get '[JSON] Bool
serveApi :: ActionEnv -> Application
serveApi as = serve (Proxy :: Proxy Api) $
(\creds -> enter (enterAction () as baseActionErrorToServantErr creds) hasPrivilegedIP)
specWithBackends :: Spec
specWithBackends = describe "hasPrivilegedIp" $ do
let works :: [String] -> Bool -> Spec
works ips y = context ("with allow_ips = " ++ show ips) . around (withPrivIpBackend ips) $
it ("returns " ++ show y ++ " for requests from localhost") $ \httpCfg -> do
resp <- Wreq.get (cs $ exposeUrl httpCfg)
resp ^. Wreq.responseBody `shouldBe` Aeson.encode y
works ["127.0.0.1"] True
works ["1.2.3.4"] False
works [] False
works ["::1"] False
works ["fe80::42:d4ff:fec0:544d"] False
| null | https://raw.githubusercontent.com/liqd/thentos/f7d53d8e9d11956d2cc83efb5f5149876109b098/thentos-tests/tests/Thentos/Action/SimpleAuthSpec.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables #
ActionStack (ActionError Void) () | # LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
module Thentos.Action.SimpleAuthSpec where
import Control.Concurrent (forkIO, killThread)
import Control.Exception (bracket)
import Data.Configifier (Source(YamlString), Tagged(Tagged), (>>.))
import LIO (LIO)
import Network.Wai (Application)
import Servant.API ((:>), Get, JSON)
import Servant.Server (serve, enter)
import Test.Hspec (Spec, describe, context, it, around, hspec, shouldBe)
import qualified Data.Aeson as Aeson
import qualified Network.Wreq as Wreq
import Thentos.Prelude
import Thentos.Action.Core
import Thentos.Action.Types
import Thentos.Action.SimpleAuth
import Thentos.Action.Unsafe
import Thentos.Backend.Api.Auth.Types
import Thentos.Backend.Core
import Thentos.Config
import Thentos.Types
import Thentos.Test.Arbitrary ()
import Thentos.Test.Config
import Thentos.Test.Core
tests :: IO ()
tests = hspec spec
spec :: Spec
spec = do
specWithActionEnv
specWithBackends
runActE :: Act a -> IO (Either (ActionError Void) a)
runActE = runLIOE
runAct :: Act a -> IO a
runAct = ioExc' . runActE
setTwoGroups :: MonadThentosIO m => m ()
setTwoGroups = extendClearanceOnPrincipals [GroupAdmin, GroupUser]
setClearanceUid :: MonadThentosIO m => Integer -> m ()
setClearanceUid uid = extendClearanceOnPrincipals [UserA $ UserId uid]
>> extendClearanceOnPrincipals [GroupUser]
setClearanceSid :: MonadThentosIO m => Integer -> m ()
setClearanceSid sid = extendClearanceOnPrincipals [ServiceA . ServiceId . cs . show $ sid]
specWithActionEnv :: Spec
specWithActionEnv = do
describe "assertAuth" $ do
it "throws an error on False" $ do
Left (ActionErrorAnyLabel _) <- runActE (assertAuth $ pure False :: Act ())
return ()
it "returns () on True" $ do
runAct (assertAuth $ pure True :: Act ())
describe "hasUserId" $ do
it "returns True on if uid matches" $ do
True <- runAct (setClearanceUid 3 >> hasUserId (UserId 3) :: Act Bool)
return ()
it "returns False on if uid does not match" $ do
False <- runAct (hasUserId (UserId 3) :: Act Bool)
False <- runAct (setClearanceUid 5 >> hasUserId (UserId 3) :: Act Bool)
return ()
describe "hasServiceId" $ do
it "returns True on if sid matches" $ do
True <- runAct (setClearanceSid 3 >> hasServiceId (ServiceId "3") :: Act Bool)
return ()
it "returns False on if sid does not match" $ do
False <- runAct (hasServiceId (ServiceId "3") :: Act Bool)
False <- runAct (setClearanceSid 5 >> hasServiceId (ServiceId "3") :: Act Bool)
return ()
it "can distinguish uid and sid" $ do
False <- runAct (setClearanceUid 3 >> hasServiceId (ServiceId "3") :: Act Bool)
return ()
describe "hasGroup" $ do
it "returns True if group is present" $ do
True <- runAct (setClearanceUid 3 >> hasGroup GroupUser :: Act Bool)
True <- runAct (setClearanceUid 5 >> hasGroup GroupUser :: Act Bool)
True <- runAct (setTwoGroups >> hasGroup GroupUser :: Act Bool)
return ()
it "returns False if group is missing" $ do
False <- runAct (hasGroup GroupUser :: Act Bool)
False <- runAct (setTwoGroups >> hasGroup GroupServiceAdmin :: Act Bool)
return ()
withPrivIpBackend :: [String] -> (HttpConfig -> IO r) -> IO r
withPrivIpBackend allowIps testCase = do
cfg <- thentosTestConfig' [YamlString . ("allow_ips: " <>) . cs . show $ allowIps]
as <- createActionEnv' cfg
let Just becfg = Tagged <$> (as ^. aStConfig) >>. (Proxy :: Proxy '["backend"])
bracket (forkIO $ runWarpWithCfg becfg $ serveApi as)
killThread
(\_ -> testCase becfg)
type Api = ThentosAuth :> Get '[JSON] Bool
serveApi :: ActionEnv -> Application
serveApi as = serve (Proxy :: Proxy Api) $
(\creds -> enter (enterAction () as baseActionErrorToServantErr creds) hasPrivilegedIP)
specWithBackends :: Spec
specWithBackends = describe "hasPrivilegedIp" $ do
let works :: [String] -> Bool -> Spec
works ips y = context ("with allow_ips = " ++ show ips) . around (withPrivIpBackend ips) $
it ("returns " ++ show y ++ " for requests from localhost") $ \httpCfg -> do
resp <- Wreq.get (cs $ exposeUrl httpCfg)
resp ^. Wreq.responseBody `shouldBe` Aeson.encode y
works ["127.0.0.1"] True
works ["1.2.3.4"] False
works [] False
works ["::1"] False
works ["fe80::42:d4ff:fec0:544d"] False
|
afbc10f8236cd6d1ccdd7cbe41831775e9227fa33d03b6a668a023c791cc868e | larcenists/larceny | 141.body.scm |
;;; -*- Mode: Scheme -*-
Integer Division Operators
;;; Given a QUOTIENT and REMAINDER defined for nonnegative numerators
;;; and positive denominators implementing the truncated, floored, or
Euclidean integer division , this implements a number of other
;;; integer division operators.
Copyright ( c ) 2010 - -2011
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
Shims
;;; SRFI-8
(define-syntax receive
(syntax-rules ()
((receive formals expression body ...)
(call-with-values (lambda () expression)
(lambda formals body ...)))))
Integer Division
;;;; Ceiling
(define (ceiling/ n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(ceiling-/- n d))
((negative? n)
(let ((n (- 0 n)))
(values (- 0 (quotient n d)) (- 0 (remainder n d)))))
((negative? d)
(let ((d (- 0 d)))
(values (- 0 (quotient n d)) (remainder n d))))
(else
(ceiling+/+ n d)))
(let ((q (ceiling (/ n d))))
(values q (- n (* d q))))))
(define (ceiling-/- n d)
(let ((n (- 0 n)) (d (- 0 d)))
(let ((q (quotient n d)) (r (remainder n d)))
(if (zero? r)
(values q r)
(values (+ q 1) (- d r))))))
(define (ceiling+/+ n d)
(let ((q (quotient n d)) (r (remainder n d)))
(if (zero? r)
(values q r)
(values (+ q 1) (- r d)))))
(define (ceiling-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(receive (q r) (ceiling-/- n d) r q))
((negative? n) (- 0 (quotient (- 0 n) d)))
((negative? d) (- 0 (quotient n (- 0 d))))
(else (receive (q r) (ceiling+/+ n d) r q)))
(ceiling (/ n d))))
(define (ceiling-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(receive (q r) (ceiling-/- n d) q r))
((negative? n) (- 0 (remainder (- 0 n) d)))
((negative? d) (remainder n (- 0 d)))
(else (receive (q r) (ceiling+/+ n d) q r)))
(- n (* d (ceiling (/ n d))))))
Euclidean Division
0 < = r < |d|
(define (euclidean/ n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d)) (ceiling-/- n d))
((negative? n) (floor-/+ n d))
((negative? d)
(let ((d (- 0 d)))
(values (- 0 (quotient n d)) (remainder n d))))
(else (values (quotient n d) (remainder n d))))
(let ((q (if (negative? d) (ceiling (/ n d)) (floor (/ n d)))))
(values q (- n (* d q))))))
(define (euclidean-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(receive (q r) (ceiling-/- n d) r q))
((negative? n) (receive (q r) (floor-/+ n d) r q))
((negative? d) (- 0 (quotient n (- 0 d))))
(else (quotient n d)))
(if (negative? d) (ceiling (/ n d)) (floor (/ n d)))))
(define (euclidean-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(receive (q r) (ceiling-/- n d) q r))
((negative? n) (receive (q r) (floor-/+ n d) q r))
((negative? d) (remainder n (- 0 d)))
(else (remainder n d)))
(- n (* d (if (negative? d) (ceiling (/ n d)) (floor (/ n d)))))))
;;;; Floor
;;; Exported by (scheme base).
#;
(define (floor/ n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(let ((n (- 0 n)) (d (- 0 d)))
(values (quotient n d) (- 0 (remainder n d)))))
((negative? n) (floor-/+ n d))
((negative? d) (floor+/- n d))
(else (values (quotient n d) (remainder n d))))
(let ((q (floor (/ n d))))
(values q (- n (* d q))))))
(define (floor-/+ n d)
(let ((n (- 0 n)))
(let ((q (quotient n d)) (r (remainder n d)))
(if (zero? r)
(values (- 0 q) r)
(values (- (- 0 q) 1) (- d r))))))
(define (floor+/- n d)
(let ((d (- 0 d)))
(let ((q (quotient n d)) (r (remainder n d)))
(if (zero? r)
(values (- 0 q) r)
(values (- (- 0 q) 1) (- r d))))))
;;; Exported by (scheme base).
#;
(define (floor-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d)) (quotient (- 0 n) (- 0 d)))
((negative? n) (receive (q r) (floor-/+ n d) r q))
((negative? d) (receive (q r) (floor+/- n d) r q))
(else (quotient n d)))
(floor (/ n d))))
;;; Exported by (scheme base).
#;
(define (floor-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(- 0 (remainder (- 0 n) (- 0 d))))
((negative? n) (receive (q r) (floor-/+ n d) q r))
((negative? d) (receive (q r) (floor+/- n d) q r))
(else (remainder n d)))
(- n (* d (floor (/ n d))))))
;;;; Round Ties to Even
(define (round/ n d)
(define (divide n d adjust leave)
(let ((q (quotient n d)) (r (remainder n d)))
(if (and (not (zero? r))
(or (and (odd? q) (even? d) (divisible? n (quotient d 2)))
(< d (* 2 r))))
(adjust (+ q 1) (- r d))
(leave q r))))
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(divide (- 0 n) (- 0 d)
(lambda (q r) (values q (- 0 r)))
(lambda (q r) (values q (- 0 r)))))
((negative? n)
(divide (- 0 n) d
(lambda (q r) (values (- 0 q) (- 0 r)))
(lambda (q r) (values (- 0 q) (- 0 r)))))
((negative? d)
(divide n (- 0 d)
(lambda (q r) (values (- 0 q) r))
(lambda (q r) (values (- 0 q) r))))
(else
(let ((return (lambda (q r) (values q r))))
(divide n d return return))))
(let ((q (round (/ n d))))
(values q (- n (* d q))))))
(define (divisible? n d)
;; This operation admits a faster implementation than the one given
;; here.
(zero? (remainder n d)))
(define (round-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(receive (q r) (round/ n d)
r ;ignore
q)
(round (/ n d))))
(define (round-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(receive (q r) (round/ n d)
q ;ignore
r)
(- n (* d (round (/ n d))))))
;;; Exported by (scheme base).
#;
(define (truncate/ n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(let ((n (- 0 n)) (d (- 0 d)))
(values (quotient n d) (- 0 (remainder n d)))))
((negative? n)
(let ((n (- 0 n)))
(values (- 0 (quotient n d)) (- 0 (remainder n d)))))
((negative? d)
(let ((d (- 0 d)))
(values (- 0 (quotient n d)) (remainder n d))))
(else
(values (quotient n d) (remainder n d))))
(let ((q (truncate (/ n d))))
(values q (- n (* d q))))))
;;; Exported by (scheme base).
#;
(define (truncate-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d)) (quotient (- 0 n) (- 0 d)))
((negative? n) (- 0 (quotient (- 0 n) d)))
((negative? d) (- 0 (quotient n (- 0 d))))
(else (quotient n d)))
(truncate (/ n d))))
;;; Exported by (scheme base).
#;
(define (truncate-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(- 0 (remainder (- 0 n) (- 0 d))))
((negative? n) (- 0 (remainder (- 0 n) d)))
((negative? d) (remainder n (- 0 d)))
(else (remainder n d)))
(- n (* d (truncate (/ n d))))))
Copyright 2015 .
;;;
;;; Permission to copy this software, in whole or in part, to use this
;;; software for any lawful purpose, and to redistribute this software
;;; is granted subject to the restriction that all copies made of this
;;; software must include this copyright and permission notice in full.
;;;
;;; I also request that you send me a copy of any improvements that you
;;; make to this software so that they may be incorporated within it to
;;; the benefit of the Scheme community.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (balanced/ x y)
(call-with-values
(lambda () (euclidean/ x y))
(lambda (q r)
(cond ((< r (abs (/ y 2)))
(values q r))
((> y 0)
(values (+ q 1) (- x (* (+ q 1) y))))
(else
(values (- q 1) (- x (* (- q 1) y))))))))
(define (balanced-quotient x y)
(call-with-values
(lambda () (balanced/ x y))
(lambda (q r) q)))
(define (balanced-remainder x y)
(call-with-values
(lambda () (balanced/ x y))
(lambda (q r) r)))
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/lib/SRFI/srfi/141.body.scm | scheme | -*- Mode: Scheme -*-
Given a QUOTIENT and REMAINDER defined for nonnegative numerators
and positive denominators implementing the truncated, floored, or
integer division operators.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
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.
SRFI-8
Ceiling
Floor
Exported by (scheme base).
Exported by (scheme base).
Exported by (scheme base).
Round Ties to Even
This operation admits a faster implementation than the one given
here.
ignore
ignore
Exported by (scheme base).
Exported by (scheme base).
Exported by (scheme base).
Permission to copy this software, in whole or in part, to use this
software for any lawful purpose, and to redistribute this software
is granted subject to the restriction that all copies made of this
software must include this copyright and permission notice in full.
I also request that you send me a copy of any improvements that you
make to this software so that they may be incorporated within it to
the benefit of the Scheme community.
|
Integer Division Operators
Euclidean integer division , this implements a number of other
Copyright ( c ) 2010 - -2011
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
Shims
(define-syntax receive
(syntax-rules ()
((receive formals expression body ...)
(call-with-values (lambda () expression)
(lambda formals body ...)))))
Integer Division
(define (ceiling/ n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(ceiling-/- n d))
((negative? n)
(let ((n (- 0 n)))
(values (- 0 (quotient n d)) (- 0 (remainder n d)))))
((negative? d)
(let ((d (- 0 d)))
(values (- 0 (quotient n d)) (remainder n d))))
(else
(ceiling+/+ n d)))
(let ((q (ceiling (/ n d))))
(values q (- n (* d q))))))
(define (ceiling-/- n d)
(let ((n (- 0 n)) (d (- 0 d)))
(let ((q (quotient n d)) (r (remainder n d)))
(if (zero? r)
(values q r)
(values (+ q 1) (- d r))))))
(define (ceiling+/+ n d)
(let ((q (quotient n d)) (r (remainder n d)))
(if (zero? r)
(values q r)
(values (+ q 1) (- r d)))))
(define (ceiling-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(receive (q r) (ceiling-/- n d) r q))
((negative? n) (- 0 (quotient (- 0 n) d)))
((negative? d) (- 0 (quotient n (- 0 d))))
(else (receive (q r) (ceiling+/+ n d) r q)))
(ceiling (/ n d))))
(define (ceiling-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(receive (q r) (ceiling-/- n d) q r))
((negative? n) (- 0 (remainder (- 0 n) d)))
((negative? d) (remainder n (- 0 d)))
(else (receive (q r) (ceiling+/+ n d) q r)))
(- n (* d (ceiling (/ n d))))))
Euclidean Division
0 < = r < |d|
(define (euclidean/ n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d)) (ceiling-/- n d))
((negative? n) (floor-/+ n d))
((negative? d)
(let ((d (- 0 d)))
(values (- 0 (quotient n d)) (remainder n d))))
(else (values (quotient n d) (remainder n d))))
(let ((q (if (negative? d) (ceiling (/ n d)) (floor (/ n d)))))
(values q (- n (* d q))))))
(define (euclidean-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(receive (q r) (ceiling-/- n d) r q))
((negative? n) (receive (q r) (floor-/+ n d) r q))
((negative? d) (- 0 (quotient n (- 0 d))))
(else (quotient n d)))
(if (negative? d) (ceiling (/ n d)) (floor (/ n d)))))
(define (euclidean-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(receive (q r) (ceiling-/- n d) q r))
((negative? n) (receive (q r) (floor-/+ n d) q r))
((negative? d) (remainder n (- 0 d)))
(else (remainder n d)))
(- n (* d (if (negative? d) (ceiling (/ n d)) (floor (/ n d)))))))
(define (floor/ n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(let ((n (- 0 n)) (d (- 0 d)))
(values (quotient n d) (- 0 (remainder n d)))))
((negative? n) (floor-/+ n d))
((negative? d) (floor+/- n d))
(else (values (quotient n d) (remainder n d))))
(let ((q (floor (/ n d))))
(values q (- n (* d q))))))
(define (floor-/+ n d)
(let ((n (- 0 n)))
(let ((q (quotient n d)) (r (remainder n d)))
(if (zero? r)
(values (- 0 q) r)
(values (- (- 0 q) 1) (- d r))))))
(define (floor+/- n d)
(let ((d (- 0 d)))
(let ((q (quotient n d)) (r (remainder n d)))
(if (zero? r)
(values (- 0 q) r)
(values (- (- 0 q) 1) (- r d))))))
(define (floor-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d)) (quotient (- 0 n) (- 0 d)))
((negative? n) (receive (q r) (floor-/+ n d) r q))
((negative? d) (receive (q r) (floor+/- n d) r q))
(else (quotient n d)))
(floor (/ n d))))
(define (floor-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(- 0 (remainder (- 0 n) (- 0 d))))
((negative? n) (receive (q r) (floor-/+ n d) q r))
((negative? d) (receive (q r) (floor+/- n d) q r))
(else (remainder n d)))
(- n (* d (floor (/ n d))))))
(define (round/ n d)
(define (divide n d adjust leave)
(let ((q (quotient n d)) (r (remainder n d)))
(if (and (not (zero? r))
(or (and (odd? q) (even? d) (divisible? n (quotient d 2)))
(< d (* 2 r))))
(adjust (+ q 1) (- r d))
(leave q r))))
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(divide (- 0 n) (- 0 d)
(lambda (q r) (values q (- 0 r)))
(lambda (q r) (values q (- 0 r)))))
((negative? n)
(divide (- 0 n) d
(lambda (q r) (values (- 0 q) (- 0 r)))
(lambda (q r) (values (- 0 q) (- 0 r)))))
((negative? d)
(divide n (- 0 d)
(lambda (q r) (values (- 0 q) r))
(lambda (q r) (values (- 0 q) r))))
(else
(let ((return (lambda (q r) (values q r))))
(divide n d return return))))
(let ((q (round (/ n d))))
(values q (- n (* d q))))))
(define (divisible? n d)
(zero? (remainder n d)))
(define (round-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(receive (q r) (round/ n d)
q)
(round (/ n d))))
(define (round-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(receive (q r) (round/ n d)
r)
(- n (* d (round (/ n d))))))
(define (truncate/ n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(let ((n (- 0 n)) (d (- 0 d)))
(values (quotient n d) (- 0 (remainder n d)))))
((negative? n)
(let ((n (- 0 n)))
(values (- 0 (quotient n d)) (- 0 (remainder n d)))))
((negative? d)
(let ((d (- 0 d)))
(values (- 0 (quotient n d)) (remainder n d))))
(else
(values (quotient n d) (remainder n d))))
(let ((q (truncate (/ n d))))
(values q (- n (* d q))))))
(define (truncate-quotient n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d)) (quotient (- 0 n) (- 0 d)))
((negative? n) (- 0 (quotient (- 0 n) d)))
((negative? d) (- 0 (quotient n (- 0 d))))
(else (quotient n d)))
(truncate (/ n d))))
(define (truncate-remainder n d)
(if (and (exact-integer? n) (exact-integer? d))
(cond ((and (negative? n) (negative? d))
(- 0 (remainder (- 0 n) (- 0 d))))
((negative? n) (- 0 (remainder (- 0 n) d)))
((negative? d) (remainder n (- 0 d)))
(else (remainder n d)))
(- n (* d (truncate (/ n d))))))
Copyright 2015 .
(define (balanced/ x y)
(call-with-values
(lambda () (euclidean/ x y))
(lambda (q r)
(cond ((< r (abs (/ y 2)))
(values q r))
((> y 0)
(values (+ q 1) (- x (* (+ q 1) y))))
(else
(values (- q 1) (- x (* (- q 1) y))))))))
(define (balanced-quotient x y)
(call-with-values
(lambda () (balanced/ x y))
(lambda (q r) q)))
(define (balanced-remainder x y)
(call-with-values
(lambda () (balanced/ x y))
(lambda (q r) r)))
|
2af03580f8537170a095542b3fd44c649f632c0b37c66ce641e0fd1ef787a875 | mirage/shared-block-ring | ring.mli |
* Copyright ( C ) 2013 - 2015 Citrix Systems Inc
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (C) 2013-2015 Citrix Systems Inc
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
(** A producer/consumer ring on top of a shared block device. The producer may
push variable-sized items (if there is enough space) and the consumer may
then pop the items. Items are pushed and popped atomically. There should
be at-most-one producer and at-most-one consumer at any point in time.
Since block devices have no built-in signalling mechanisms, it is up to
the client to either poll for updates or implement another out-of-band
signalling mechanism. *)
module Make(Log: S.LOG)(B: S.BLOCK)(Item: S.CSTRUCTABLE): sig
module Producer: S.PRODUCER
with type disk := B.t
and type item = Item.t
module Consumer: S.CONSUMER
with type disk := B.t
and type position = Producer.position
and type item = Item.t
end
| null | https://raw.githubusercontent.com/mirage/shared-block-ring/e780fd9ed2186c14dd49f9e8d00211be648aa762/lib/ring.mli | ocaml | * A producer/consumer ring on top of a shared block device. The producer may
push variable-sized items (if there is enough space) and the consumer may
then pop the items. Items are pushed and popped atomically. There should
be at-most-one producer and at-most-one consumer at any point in time.
Since block devices have no built-in signalling mechanisms, it is up to
the client to either poll for updates or implement another out-of-band
signalling mechanism. |
* Copyright ( C ) 2013 - 2015 Citrix Systems Inc
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (C) 2013-2015 Citrix Systems Inc
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module Make(Log: S.LOG)(B: S.BLOCK)(Item: S.CSTRUCTABLE): sig
module Producer: S.PRODUCER
with type disk := B.t
and type item = Item.t
module Consumer: S.CONSUMER
with type disk := B.t
and type position = Producer.position
and type item = Item.t
end
|
e93c4b42947a5f9a4b6ba10f314c97168b2cf57cd91d0d2c158171f53a2713b1 | lipas-liikuntapaikat/lipas | tasks.clj | (ns lipas.integration.old-lipas.tasks
(:require
[clojure.java.jdbc :as jdbc]
[clojure.stacktrace :as stacktrace]
[lipas.backend.db.db :as db]
[lipas.migrate-data :as migrate]
[lipas.integration.old-lipas.core :as old-lipas]
[lipas.utils :as utils]
[taoensso.timbre :as log]))
Data integrations between old Lipas and new LIPAS .
Inbound integration can be removed once old Lipas stops receiving
;; new data (old UI is disabled).
TODO initial timestamps from env vars
(def initial-timestamps
{"old->new" "2019-01-01T00:00:00.000Z"
"new->old" "2019-01-01T00:00:00.000Z"})
(defn- handle-error [db name e]
(let [data {:msg (.getMessage e)
:resp (-> e ex-data :body)
:stack (with-out-str (stacktrace/print-stack-trace e))}]
(log/error e)
(db/add-integration-entry! db {:status "failure"
:name name
:event-date (utils/timestamp)
:document data})))
(defn- handle-success [db name res]
(let [total (-> res :total)
entry {:status "success"
:name name
:event-date (:latest res)
:document (select-keys res [:updated :ignored])}]
(when (> total 0) (db/add-integration-entry! db entry))
(log/info "Total:" (-> res :total)
"Updated:" (-> res :updated count)
"Ignored:" (-> res :ignored count))))
INBOUND ; ;
(defn old->new [db search user]
(let [name "old->new"
last-success (or (db/get-last-integration-timestamp db name)
(initial-timestamps name))]
(log/info "Starting to fetch changes from old Lipas since" last-success)
(try
(jdbc/with-db-transaction [tx db]
(let [res (migrate/migrate-changed-since! db search user last-success)]
(handle-success db name res)))
(catch Exception e
(handle-error db name e)))))
;; OUTBOUND ;;
(defn new->old [db]
(let [name "new->old"
last-success (or (db/get-last-integration-timestamp db name)
(initial-timestamps name))]
(log/info "Starting to push changes to old Lipas since" last-success)
(try
(old-lipas/add-changed-to-out-queue! db last-success)
(let [res (old-lipas/process-integration-out-queue! db)]
(handle-success db name res)
(doseq [[lipas-id e] (:errors res)
:let [msg (str "Pushing " lipas-id " to old Lipas failed!")]]
(handle-error db name (ex-info msg (or (ex-data e) {}) e))))
(catch Exception e
(handle-error db name e)))))
(comment
(def config (select-keys config/default-config [:db :search]))
(def system (backend/start-system! config))
(def db (:db system))
(def search (:search system))
(def user (core/get-user db ""))
(new->old db)
(old->new db search user)
(old-lipas/add-changed-to-out-queue! db "2018-12-31T00:00:00.000Z")
(old-lipas/process-integration-out-queue! db))
| null | https://raw.githubusercontent.com/lipas-liikuntapaikat/lipas/5d7ccb3f6b55bd19b6da89f9bd0589ec7ebfa20d/webapp/src/clj/lipas/integration/old_lipas/tasks.clj | clojure | new data (old UI is disabled).
;
OUTBOUND ;; | (ns lipas.integration.old-lipas.tasks
(:require
[clojure.java.jdbc :as jdbc]
[clojure.stacktrace :as stacktrace]
[lipas.backend.db.db :as db]
[lipas.migrate-data :as migrate]
[lipas.integration.old-lipas.core :as old-lipas]
[lipas.utils :as utils]
[taoensso.timbre :as log]))
Data integrations between old Lipas and new LIPAS .
Inbound integration can be removed once old Lipas stops receiving
TODO initial timestamps from env vars
(def initial-timestamps
{"old->new" "2019-01-01T00:00:00.000Z"
"new->old" "2019-01-01T00:00:00.000Z"})
(defn- handle-error [db name e]
(let [data {:msg (.getMessage e)
:resp (-> e ex-data :body)
:stack (with-out-str (stacktrace/print-stack-trace e))}]
(log/error e)
(db/add-integration-entry! db {:status "failure"
:name name
:event-date (utils/timestamp)
:document data})))
(defn- handle-success [db name res]
(let [total (-> res :total)
entry {:status "success"
:name name
:event-date (:latest res)
:document (select-keys res [:updated :ignored])}]
(when (> total 0) (db/add-integration-entry! db entry))
(log/info "Total:" (-> res :total)
"Updated:" (-> res :updated count)
"Ignored:" (-> res :ignored count))))
(defn old->new [db search user]
(let [name "old->new"
last-success (or (db/get-last-integration-timestamp db name)
(initial-timestamps name))]
(log/info "Starting to fetch changes from old Lipas since" last-success)
(try
(jdbc/with-db-transaction [tx db]
(let [res (migrate/migrate-changed-since! db search user last-success)]
(handle-success db name res)))
(catch Exception e
(handle-error db name e)))))
(defn new->old [db]
(let [name "new->old"
last-success (or (db/get-last-integration-timestamp db name)
(initial-timestamps name))]
(log/info "Starting to push changes to old Lipas since" last-success)
(try
(old-lipas/add-changed-to-out-queue! db last-success)
(let [res (old-lipas/process-integration-out-queue! db)]
(handle-success db name res)
(doseq [[lipas-id e] (:errors res)
:let [msg (str "Pushing " lipas-id " to old Lipas failed!")]]
(handle-error db name (ex-info msg (or (ex-data e) {}) e))))
(catch Exception e
(handle-error db name e)))))
(comment
(def config (select-keys config/default-config [:db :search]))
(def system (backend/start-system! config))
(def db (:db system))
(def search (:search system))
(def user (core/get-user db ""))
(new->old db)
(old->new db search user)
(old-lipas/add-changed-to-out-queue! db "2018-12-31T00:00:00.000Z")
(old-lipas/process-integration-out-queue! db))
|
56ea66dc2342403f26cf53c74d84f68b081cce7ef68e8bdd1b10eca4904fe675 | fission-codes/fission | Status.hs | module Fission.CLI.Linking.Status (module Fission.CLI.Linking.Status.Types) where
import Fission.CLI.Linking.Status.Types
| null | https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-cli/library/Fission/CLI/Linking/Status.hs | haskell | module Fission.CLI.Linking.Status (module Fission.CLI.Linking.Status.Types) where
import Fission.CLI.Linking.Status.Types
| |
a23458f40f471e5c8ac99d34553d19d5351f7be79ab59e2e962face0836578c0 | mentat-collective/functional-numerics | midpoint.cljc | (ns quadrature.midpoint
(:require [quadrature.interpolate.richardson :as ir]
[quadrature.common :as qc
#?@(:cljs [:include-macros true])]
[quadrature.riemann :as qr]
[sicmutils.generic :as g]
[sicmutils.util :as u]
[quadrature.util.aggregate :as ua]
[quadrature.util.stream :as us]))
(defn single-midpoint [f a b]
(let [width (g/- b a)
half-width (g// width 2)
midpoint (g/+ a half-width)]
(g/* width (f midpoint))))
(defn- midpoint-sum* [f a b]
(let [area-fn (partial single-midpoint f)]
(qr/windowed-sum area-fn a b)))
(defn- Sn->S3n [f a b]
(let [width (- b a)]
(fn [Sn n]
(let [h (/ width n)
delta (/ h 6)
l-offset (+ a delta)
r-offset (+ a (* 5 delta))
fx (fn [i]
(let [ih (* i h)]
(+ (f (+ l-offset ih))
(f (+ r-offset ih)))))]
(-> (+ Sn (* h (ua/sum fx 0 n)))
(/ 3.0))))))
(defn midpoint-sequence
"Returns a (lazy) sequence of successively refined estimates of the integral of
`f` over the open interval $(a, b)$ using the Midpoint method.
## Optional arguments:
`:n`: If `:n` is a number, returns estimates with $n, 3n, 9n, ...$ slices,
geometrically increasing by a factor of 3 with each estimate.
If `:n` is a sequence, the resulting sequence will hold an estimate for each
integer number of slices in that sequence.
`:accelerate?`: if supplied (and `n` is a number), attempts to accelerate
convergence using Richardson extrapolation. If `n` is a sequence this option
is ignored."
([f a b] (midpoint-sequence f a b {:n 1}))
([f a b {:keys [n accelerate?] :or {n 1}}]
(let [S (qr/midpoint-sum f a b)
next-S (Sn->S3n f a b)
xs (qr/incrementalize S next-S 3 n)]
(if (and accelerate? (number? n))
(ir/richardson-sequence xs 3 2 2)
xs))))
(qc/defintegrator integral
"Returns an estimate of the integral of `f` over the open interval $(a, b)$
using the Midpoint method with $1, 3, 9 ... 3^n$ windows for each estimate.
Optionally accepts `opts`, a dict of optional arguments. All of these get
passed on to `us/seq-limit` to configure convergence checking.
See `midpoint-sequence` for information on the optional args in `opts` that
customize this function's behavior."
:area-fn single-midpoint
:seq-fn midpoint-sequence)
| null | https://raw.githubusercontent.com/mentat-collective/functional-numerics/44856b0e3cd1f0dd9f8ebb2f67f4e85a68aa8380/src/quadrature/midpoint.cljc | clojure | (ns quadrature.midpoint
(:require [quadrature.interpolate.richardson :as ir]
[quadrature.common :as qc
#?@(:cljs [:include-macros true])]
[quadrature.riemann :as qr]
[sicmutils.generic :as g]
[sicmutils.util :as u]
[quadrature.util.aggregate :as ua]
[quadrature.util.stream :as us]))
(defn single-midpoint [f a b]
(let [width (g/- b a)
half-width (g// width 2)
midpoint (g/+ a half-width)]
(g/* width (f midpoint))))
(defn- midpoint-sum* [f a b]
(let [area-fn (partial single-midpoint f)]
(qr/windowed-sum area-fn a b)))
(defn- Sn->S3n [f a b]
(let [width (- b a)]
(fn [Sn n]
(let [h (/ width n)
delta (/ h 6)
l-offset (+ a delta)
r-offset (+ a (* 5 delta))
fx (fn [i]
(let [ih (* i h)]
(+ (f (+ l-offset ih))
(f (+ r-offset ih)))))]
(-> (+ Sn (* h (ua/sum fx 0 n)))
(/ 3.0))))))
(defn midpoint-sequence
"Returns a (lazy) sequence of successively refined estimates of the integral of
`f` over the open interval $(a, b)$ using the Midpoint method.
## Optional arguments:
`:n`: If `:n` is a number, returns estimates with $n, 3n, 9n, ...$ slices,
geometrically increasing by a factor of 3 with each estimate.
If `:n` is a sequence, the resulting sequence will hold an estimate for each
integer number of slices in that sequence.
`:accelerate?`: if supplied (and `n` is a number), attempts to accelerate
convergence using Richardson extrapolation. If `n` is a sequence this option
is ignored."
([f a b] (midpoint-sequence f a b {:n 1}))
([f a b {:keys [n accelerate?] :or {n 1}}]
(let [S (qr/midpoint-sum f a b)
next-S (Sn->S3n f a b)
xs (qr/incrementalize S next-S 3 n)]
(if (and accelerate? (number? n))
(ir/richardson-sequence xs 3 2 2)
xs))))
(qc/defintegrator integral
"Returns an estimate of the integral of `f` over the open interval $(a, b)$
using the Midpoint method with $1, 3, 9 ... 3^n$ windows for each estimate.
Optionally accepts `opts`, a dict of optional arguments. All of these get
passed on to `us/seq-limit` to configure convergence checking.
See `midpoint-sequence` for information on the optional args in `opts` that
customize this function's behavior."
:area-fn single-midpoint
:seq-fn midpoint-sequence)
| |
83f42caedab91f6a891bb2b787620e3ef1cba2d46940afba8293fd9272c89694 | BU-CS320/Fall-2018 | StatefulUnsafeMonad.hs | module StatefulUnsafeMonad where
import Control.Monad(ap)
data Unsafe a = Error String | Ok a deriving (Show, Eq)
-- notice how we handled state in -CS320/Fall-2018/blob/master/assignments/week7/hw/src/week5/Lang4.hs
-- we can make a monadic type to handle the details for us
data StatefulUnsafe s a = StatefulUnsafe (s -> (Unsafe a,s))
-- a helper function to pull out the function bit
app :: StatefulUnsafe s a -> (s ->(Unsafe a,s))
app (StatefulUnsafe stateful) = stateful
-- a way to easily return an error (for instance in do notation)
err :: String -> StatefulUnsafe e a
err s = StatefulUnsafe $ \ state -> (Error s, state)
instance Functor (StatefulUnsafe s) where
-- fmap :: (a -> b) -> Stateful a -> Stateful b
fmap f (StatefulUnsafe sa) = StatefulUnsafe $ \ state -> case sa state of
(Ok a, output) -> (Ok $f a, output)
(Error e, output) -> (Error e, output)
--ignore this for now
instance Applicative (StatefulUnsafe s) where
pure = return
(<*>) = ap
instance Monad (StatefulUnsafe s) where
return : : a - > StatefulUnsafe s a
return a = StatefulUnsafe $ \ state -> (Ok a, state)
( > > =) : : StatefulUnsafe s a - > ( a - > StatefulUnsafe s b ) - > StatefulUnsafe s b
(StatefulUnsafe sa) >>= f = StatefulUnsafe $ \ state -> case sa state of
(Ok a, output) -> app (f a) output
(Error e, output) -> (Error e, output)
-- a function that gets the state (in a stateful way)
-- stolen from
get :: StatefulUnsafe s s
get = StatefulUnsafe $ \ s -> (Ok s,s)
put :: s -> StatefulUnsafe s ()
put s = StatefulUnsafe $ \ _ -> (Ok (),s)
unsafeReturn :: Unsafe a -> StatefulUnsafe s a
unsafeReturn ua = StatefulUnsafe $ \ state -> (ua, state) | null | https://raw.githubusercontent.com/BU-CS320/Fall-2018/beec3ca88be5c5a62271a45c8053fb1b092e0af1/project/src/StatefulUnsafeMonad.hs | haskell | notice how we handled state in -CS320/Fall-2018/blob/master/assignments/week7/hw/src/week5/Lang4.hs
we can make a monadic type to handle the details for us
a helper function to pull out the function bit
a way to easily return an error (for instance in do notation)
fmap :: (a -> b) -> Stateful a -> Stateful b
ignore this for now
a function that gets the state (in a stateful way)
stolen from | module StatefulUnsafeMonad where
import Control.Monad(ap)
data Unsafe a = Error String | Ok a deriving (Show, Eq)
data StatefulUnsafe s a = StatefulUnsafe (s -> (Unsafe a,s))
app :: StatefulUnsafe s a -> (s ->(Unsafe a,s))
app (StatefulUnsafe stateful) = stateful
err :: String -> StatefulUnsafe e a
err s = StatefulUnsafe $ \ state -> (Error s, state)
instance Functor (StatefulUnsafe s) where
fmap f (StatefulUnsafe sa) = StatefulUnsafe $ \ state -> case sa state of
(Ok a, output) -> (Ok $f a, output)
(Error e, output) -> (Error e, output)
instance Applicative (StatefulUnsafe s) where
pure = return
(<*>) = ap
instance Monad (StatefulUnsafe s) where
return : : a - > StatefulUnsafe s a
return a = StatefulUnsafe $ \ state -> (Ok a, state)
( > > =) : : StatefulUnsafe s a - > ( a - > StatefulUnsafe s b ) - > StatefulUnsafe s b
(StatefulUnsafe sa) >>= f = StatefulUnsafe $ \ state -> case sa state of
(Ok a, output) -> app (f a) output
(Error e, output) -> (Error e, output)
get :: StatefulUnsafe s s
get = StatefulUnsafe $ \ s -> (Ok s,s)
put :: s -> StatefulUnsafe s ()
put s = StatefulUnsafe $ \ _ -> (Ok (),s)
unsafeReturn :: Unsafe a -> StatefulUnsafe s a
unsafeReturn ua = StatefulUnsafe $ \ state -> (ua, state) |
e8d46178d6a534469fa765fe9056a3f47dc796c14cab98bec96f96caf6c7190b | ocaml/ocaml | pr5985.ml | (* TEST
* expect
*)
Report from
module F (S : sig type 'a s end) = struct
include S
type _ t = T : 'a -> 'a s t
end;; (* fail *)
[%%expect{|
Line 3, characters 2-29:
3 | type _ t = T : 'a -> 'a s t
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
T : 'a -> 'a s t
the type variable 'a cannot be deduced from the type parameters.
|}];;
module M = F ( struct type ' a s = int end ) ; ;
let M.T x = M.T 3 in x = true ; ;
module M = F (struct type 'a s = int end) ;;
let M.T x = M.T 3 in x = true;;
*)
(* Fix it using #-annotations *)
module F ( S : sig type # ' a s end ) = struct
include S
type _ t = T : ' a - > ' a s t
end ; ; ( * syntax error
module F (S : sig type #'a s end) = struct
include S
type _ t = T : 'a -> 'a s t
end;; (* syntax error *)
module M = F (struct type 'a s = int end) ;; (* fail *)
module M = F (struct type 'a s = new int end) ;; (* ok *)
let M.T x = M.T 3 in x = true;; (* fail *)
let M.T x = M.T 3 in x = 3;; (* ok *)
*)
Another version using OCaml 2.00 objects
module F(T:sig type 'a t end) = struct
class ['a] c x =
object constraint 'a = 'b T.t val x' : 'b = x method x = x' end
end;; (* fail *)
[%%expect{|
Lines 2-3, characters 2-67:
2 | ..class ['a] c x =
3 | object constraint 'a = 'b T.t val x' : 'b = x method x = x' end
Error: In the definition
type 'a c = < x : 'b > constraint 'a = 'b T.t
the type variable 'b cannot be deduced from the type parameters.
|}];;
(* Another (more direct) instance using polymorphic variants *)
(* PR#6275 *)
type 'x t = A of 'a constraint 'x = [< `X of 'a ] ;; (* fail *)
let magic (x : int) : bool =
let A x = A x in
x;; (* fail *)
[%%expect{|
Line 1, characters 0-49:
1 | type 'x t = A of 'a constraint 'x = [< `X of 'a ] ;; (* fail *)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type 'b t = A of 'a constraint 'b = [< `X of 'a ]
the type variable 'a cannot be deduced from the type parameters.
|}];;
type 'a t = A : 'a -> [< `X of 'a ] t;; (* fail *)
[%%expect{|
Line 1, characters 0-37:
1 | type 'a t = A : 'a -> [< `X of 'a ] t;; (* fail *)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
A : 'a -> [< `X of 'a ] t
the type variable 'a cannot be deduced from the type parameters.
|}];;
(* It is not OK to allow modules exported by other compilation units *)
type (_,_) eq = Eq : ('a,'a) eq;;
let eq = Obj.magic Eq;;
let eq : (('a, 'b) Ephemeron.K1.t, ('c, 'd) Ephemeron.K1.t) eq = eq;;
type _ t = T : 'a -> ('a, 'b) Ephemeron.K1.t t;; (* fail *)
[%%expect{|
type (_, _) eq = Eq : ('a, 'a) eq
val eq : 'a = <poly>
val eq : (('a, 'b) Ephemeron.K1.t, ('c, 'd) Ephemeron.K1.t) eq = Eq
Line 4, characters 0-46:
4 | type _ t = T : 'a -> ('a, 'b) Ephemeron.K1.t t;; (* fail *)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
T : 'a -> ('a, 'b) Ephemeron.K1.t t
the type variable 'a cannot be deduced from the type parameters.
|}];;
let castT ( type a ) ( type b ) ( x : a t ) ( e : ( a , b ) eq ) : b t =
let in ( x : b t ) ; ;
let T ( x : bool ) = castT ( T 3 ) eq ; ; ( * we found a contradiction
let castT (type a) (type b) (x : a t) (e: (a, b) eq) : b t =
let Eq = e in (x : b t);;
let T (x : bool) = castT (T 3) eq;; (* we found a contradiction *)
*)
(* The following signature should not be accepted *)
module type S = sig
type 'a s
type _ t = T : 'a -> 'a s t
end;; (* fail *)
[%%expect{|
Line 3, characters 2-29:
3 | type _ t = T : 'a -> 'a s t
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
T : 'a -> 'a s t
the type variable 'a cannot be deduced from the type parameters.
|}];;
(* Otherwise we can write the following *)
module rec M : (S with type 'a s = unit) = M;;
[%%expect{|
Line 1, characters 16-17:
1 | module rec M : (S with type 'a s = unit) = M;;
^
Error: Unbound module type S
|}];;
(* For the above reason, we cannot allow the abstract declaration
of s and the definition of t to be in the same module, as
we could create the signature using [module type of ...] *)
(* Another problem with variance *)
(*
module M = struct type 'a t = 'a -> unit end;;
module F(X:sig type #'a t end) =
struct type +'a s = S of 'b constraint 'a = 'b X.t end;; (* fail *)
module N = F(M);;
let o = N.S (object end);;
let N.S o' = (o :> <m : int> M.t N.s);; (* unsound! *)
*)
(* And yet another *)
type 'a q = Q;;
type +'a t = 'b constraint 'a = 'b q;;
[%%expect{|
type 'a q = Q
Line 2, characters 0-36:
2 | type +'a t = 'b constraint 'a = 'b q;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type +'a t = 'b constraint 'a = 'b q
the type variable 'b has a variance that
cannot be deduced from the type parameters.
It was expected to be unrestricted, but it is covariant.
|}];;
(* should fail: we do not know for sure the variance of Queue.t *)
type +'a t = T of 'a;;
type +'a s = 'b constraint 'a = 'b t;; (* ok *)
[%%expect{|
type 'a t = T of 'a
type +'a s = 'b constraint 'a = 'b t
|}];;
type -'a s = 'b constraint 'a = 'b t;; (* fail *)
[%%expect{|
Line 1, characters 0-36:
1 | type -'a s = 'b constraint 'a = 'b t;; (* fail *)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type -'a s = 'b constraint 'a = 'b t
the type variable 'b has a variance that
is not reflected by its occurrence in type parameters.
It was expected to be contravariant, but it is covariant.
|}];;
type +'a u = 'a t;;
type 'a t = T of ('a -> 'a);;
type -'a s = 'b constraint 'a = 'b t;; (* ok *)
[%%expect{|
type 'a u = 'a t
type 'a t = T of ('a -> 'a)
type -'a s = 'b constraint 'a = 'b t
|}];;
type +'a s = 'b constraint 'a = 'b q t;; (* ok *)
[%%expect{|
type +'a s = 'b constraint 'a = 'b q t
|}];;
type +'a s = 'b constraint 'a = 'b t q;; (* fail *)
[%%expect{|
Line 1, characters 0-38:
1 | type +'a s = 'b constraint 'a = 'b t q;; (* fail *)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type +'a s = 'b constraint 'a = 'b t q
the type variable 'b has a variance that
cannot be deduced from the type parameters.
It was expected to be unrestricted, but it is covariant.
|}];;
the problem from lablgtk2
module = struct
type -'a obj
end
open Gobject ; ;
class virtual [ ' a ] item_container =
object
constraint ' a = < as_item : [ > ` widget ] obj ; .. >
method virtual add : ' a - > unit
end ; ;
module Gobject = struct
type -'a obj
end
open Gobject;;
class virtual ['a] item_container =
object
constraint 'a = < as_item : [>`widget] obj; .. >
method virtual add : 'a -> unit
end;;
*)
(* Another variance anomaly, should not expand t in g before checking *)
type +'a t = unit constraint 'a = 'b list;;
type _ g = G : 'a -> 'a t g;; (* fail *)
[%%expect{|
type +'a t = unit constraint 'a = 'b list
Line 2, characters 0-27:
2 | type _ g = G : 'a -> 'a t g;; (* fail *)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
G : 'a list -> 'a list t g
the type variable 'a cannot be deduced from the type parameters.
|}];;
| null | https://raw.githubusercontent.com/ocaml/ocaml/19f759652b6c7531d77abe2837e1bee11bd659bd/testsuite/tests/typing-gadts/pr5985.ml | ocaml | TEST
* expect
fail
Fix it using #-annotations
syntax error
fail
ok
fail
ok
fail
Another (more direct) instance using polymorphic variants
PR#6275
fail
fail
fail
fail
fail
It is not OK to allow modules exported by other compilation units
fail
fail
we found a contradiction
The following signature should not be accepted
fail
Otherwise we can write the following
For the above reason, we cannot allow the abstract declaration
of s and the definition of t to be in the same module, as
we could create the signature using [module type of ...]
Another problem with variance
module M = struct type 'a t = 'a -> unit end;;
module F(X:sig type #'a t end) =
struct type +'a s = S of 'b constraint 'a = 'b X.t end;; (* fail
unsound!
And yet another
should fail: we do not know for sure the variance of Queue.t
ok
fail
fail
ok
ok
fail
fail
Another variance anomaly, should not expand t in g before checking
fail
fail |
Report from
module F (S : sig type 'a s end) = struct
include S
type _ t = T : 'a -> 'a s t
[%%expect{|
Line 3, characters 2-29:
3 | type _ t = T : 'a -> 'a s t
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
T : 'a -> 'a s t
the type variable 'a cannot be deduced from the type parameters.
|}];;
module M = F ( struct type ' a s = int end ) ; ;
let M.T x = M.T 3 in x = true ; ;
module M = F (struct type 'a s = int end) ;;
let M.T x = M.T 3 in x = true;;
*)
module F ( S : sig type # ' a s end ) = struct
include S
type _ t = T : ' a - > ' a s t
end ; ; ( * syntax error
module F (S : sig type #'a s end) = struct
include S
type _ t = T : 'a -> 'a s t
*)
Another version using OCaml 2.00 objects
module F(T:sig type 'a t end) = struct
class ['a] c x =
object constraint 'a = 'b T.t val x' : 'b = x method x = x' end
[%%expect{|
Lines 2-3, characters 2-67:
2 | ..class ['a] c x =
3 | object constraint 'a = 'b T.t val x' : 'b = x method x = x' end
Error: In the definition
type 'a c = < x : 'b > constraint 'a = 'b T.t
the type variable 'b cannot be deduced from the type parameters.
|}];;
let magic (x : int) : bool =
let A x = A x in
[%%expect{|
Line 1, characters 0-49:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type 'b t = A of 'a constraint 'b = [< `X of 'a ]
the type variable 'a cannot be deduced from the type parameters.
|}];;
[%%expect{|
Line 1, characters 0-37:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
A : 'a -> [< `X of 'a ] t
the type variable 'a cannot be deduced from the type parameters.
|}];;
type (_,_) eq = Eq : ('a,'a) eq;;
let eq = Obj.magic Eq;;
let eq : (('a, 'b) Ephemeron.K1.t, ('c, 'd) Ephemeron.K1.t) eq = eq;;
[%%expect{|
type (_, _) eq = Eq : ('a, 'a) eq
val eq : 'a = <poly>
val eq : (('a, 'b) Ephemeron.K1.t, ('c, 'd) Ephemeron.K1.t) eq = Eq
Line 4, characters 0-46:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
T : 'a -> ('a, 'b) Ephemeron.K1.t t
the type variable 'a cannot be deduced from the type parameters.
|}];;
let castT ( type a ) ( type b ) ( x : a t ) ( e : ( a , b ) eq ) : b t =
let in ( x : b t ) ; ;
let T ( x : bool ) = castT ( T 3 ) eq ; ; ( * we found a contradiction
let castT (type a) (type b) (x : a t) (e: (a, b) eq) : b t =
let Eq = e in (x : b t);;
*)
module type S = sig
type 'a s
type _ t = T : 'a -> 'a s t
[%%expect{|
Line 3, characters 2-29:
3 | type _ t = T : 'a -> 'a s t
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
T : 'a -> 'a s t
the type variable 'a cannot be deduced from the type parameters.
|}];;
module rec M : (S with type 'a s = unit) = M;;
[%%expect{|
Line 1, characters 16-17:
1 | module rec M : (S with type 'a s = unit) = M;;
^
Error: Unbound module type S
|}];;
module N = F(M);;
let o = N.S (object end);;
*)
type 'a q = Q;;
type +'a t = 'b constraint 'a = 'b q;;
[%%expect{|
type 'a q = Q
Line 2, characters 0-36:
2 | type +'a t = 'b constraint 'a = 'b q;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type +'a t = 'b constraint 'a = 'b q
the type variable 'b has a variance that
cannot be deduced from the type parameters.
It was expected to be unrestricted, but it is covariant.
|}];;
type +'a t = T of 'a;;
[%%expect{|
type 'a t = T of 'a
type +'a s = 'b constraint 'a = 'b t
|}];;
[%%expect{|
Line 1, characters 0-36:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type -'a s = 'b constraint 'a = 'b t
the type variable 'b has a variance that
is not reflected by its occurrence in type parameters.
It was expected to be contravariant, but it is covariant.
|}];;
type +'a u = 'a t;;
type 'a t = T of ('a -> 'a);;
[%%expect{|
type 'a u = 'a t
type 'a t = T of ('a -> 'a)
type -'a s = 'b constraint 'a = 'b t
|}];;
[%%expect{|
type +'a s = 'b constraint 'a = 'b q t
|}];;
[%%expect{|
Line 1, characters 0-38:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type +'a s = 'b constraint 'a = 'b t q
the type variable 'b has a variance that
cannot be deduced from the type parameters.
It was expected to be unrestricted, but it is covariant.
|}];;
the problem from lablgtk2
module = struct
type -'a obj
end
open Gobject ; ;
class virtual [ ' a ] item_container =
object
constraint ' a = < as_item : [ > ` widget ] obj ; .. >
method virtual add : ' a - > unit
end ; ;
module Gobject = struct
type -'a obj
end
open Gobject;;
class virtual ['a] item_container =
object
constraint 'a = < as_item : [>`widget] obj; .. >
method virtual add : 'a -> unit
end;;
*)
type +'a t = unit constraint 'a = 'b list;;
[%%expect{|
type +'a t = unit constraint 'a = 'b list
Line 2, characters 0-27:
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
G : 'a list -> 'a list t g
the type variable 'a cannot be deduced from the type parameters.
|}];;
|
a39ef982e476fc5299c8ca8790a128d7e5fea2c1ef5a821ac4c87edbba58fab2 | sarabander/p2pu-sicp | setup.scm |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; This is Generic Arithmetic Package ;;
;; ---------------------------------- ;;
( from chapter 2 of SICP ) ; ;
;; ;;
To setup all , evaluate this entire file . ; ; ( works in Racket 5.0 )
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Hashtable for operations, plus backup to retain old versions
(define optable (make-hash))
(define optable-backup (make-hash))
;; Same for coercions
(define coercions (make-hash))
(define coercions-backup (make-hash))
;; Getters and setters
(define (get operation types)
(hash-ref optable (list operation types) false))
(define (get-backup operation types)
(hash-ref optable-backup (list operation types) false))
(define (put operation types procedure)
(let ((exists (get operation types)))
(if exists
(and (put-backup operation types exists)
(hash-set! optable (list operation types) procedure))
(hash-set! optable (list operation types) procedure))))
(define (put-backup operation types procedure)
(let ((exists (get-backup operation types)))
(if exists
(hash-set! optable-backup
(list operation types)
(cons procedure exists))
(hash-set! optable-backup
(list operation types)
(list procedure)))))
(define (get-coercion oldtype newtype)
(hash-ref coercions (list oldtype newtype) false))
(define (get-coercion-backup oldtype newtype)
(hash-ref coercions-backup (list oldtype newtype) false))
(define (put-coercion oldtype newtype procedure)
(let ((exists (get-coercion oldtype newtype)))
(if exists
(and (put-coercion-backup oldtype newtype exists)
(hash-set! coercions (list oldtype newtype) procedure))
(hash-set! coercions (list oldtype newtype) procedure))))
(define (put-coercion-backup oldtype newtype procedure)
(let ((exists (get-coercion-backup oldtype newtype)))
(if exists
(hash-set! coercions-backup
(list oldtype newtype)
(cons procedure exists))
(hash-set! coercions-backup
(list oldtype newtype)
(list procedure)))))
First version of apply - generic from the book
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(apply proc (map contents args))
(error
"No method for these types* - APPLY-GENERIC"
(list op type-tags))))))
;; General package for primitive number types
(define (install-package type)
(define (tag x)
(attach-tag type x))
(put 'add (list type type)
(lambda (x y) (tag (+ x y))))
(put 'sub (list type type)
(lambda (x y) (tag (- x y))))
(put 'mul (list type type)
(lambda (x y) (tag (* x y))))
(put 'div (list type type)
(lambda (x y) (tag (/ x y))))
(put 'square (list type) sqr)
(put 'sine (list type) sin)
(put 'cosine (list type) cos)
(put 'atangent (list type) atan)
(put 'make type
(lambda (x) (tag x)))
'done)
(install-package 'scheme-number)
(install-package 'integer)
(install-package 'real)
;; Constructors
(define (make-scheme-number n)
((get 'make 'scheme-number) n))
(define (make-integer n)
((get 'make 'integer) n))
(define (make-real n)
((get 'make 'real) n))
;; Rational package
(define (install-rational-package)
;; internal procedures
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (add-rat x y)
(make-rat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (- (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
;; interface to rest of the system
(define (tag x) (attach-tag 'rational x))
(put 'add '(rational rational)
(lambda (x y) (tag (add-rat x y))))
(put 'sub '(rational rational)
(lambda (x y) (tag (sub-rat x y))))
(put 'mul '(rational rational)
(lambda (x y) (tag (mul-rat x y))))
(put 'div '(rational rational)
(lambda (x y) (tag (div-rat x y))))
(put 'square '(rational)
(lambda (r) (sqr (/ (numer r) (denom r)))))
(put 'sine '(rational)
(lambda (r) (sin (/ (numer r) (denom r)))))
(put 'cosine '(rational)
(lambda (r) (cos (/ (numer r) (denom r)))))
(put 'atangent '(rational)
(lambda (r) (atan (/ (numer r) (denom r)))))
(put 'make 'rational
(lambda (n d) (tag (make-rat n d))))
(put 'numer '(rational)
(lambda (r) (numer r)))
(put 'denom '(rational)
(lambda (r) (denom r)))
'done)
(install-rational-package)
(define (make-rational n d)
((get 'make 'rational) n d))
(define (numer r)
(apply-generic 'numer r))
(define (denom r)
(apply-generic 'denom r))
;; Complex number packages
;; Constructors
(define (make-complex-from-real-imag x y)
((get 'make-from-real-imag 'complex) x y))
(define (make-complex-from-mag-ang r a)
((get 'make-from-mag-ang 'complex) r a))
;; Selectors
(define (real-part z) (apply-generic 'real-part z))
(define (imag-part z) (apply-generic 'imag-part z))
(define (magnitude z) (apply-generic 'magnitude z))
(define (angle z) (apply-generic 'angle z))
(define (install-rectangular-package)
;; internal procedures
(define (real-part z) (car z))
(define (imag-part z) (cdr z))
(define (make-from-real-imag x y) (cons x y))
(define (magnitude z)
(sqrt (+ (square (real-part z))
(square (imag-part z)))))
(define (angle z)
(atangent (div (imag-part z) (real-part z))))
(define (make-from-mag-ang r a)
(cons (* r (cosine a)) (* r (sine a))))
;; interface to the rest of the system
(define (tag x) (attach-tag 'rectangular x))
(put 'real-part '(rectangular) real-part)
(put 'imag-part '(rectangular) imag-part)
(put 'magnitude '(rectangular) magnitude)
(put 'angle '(rectangular) angle)
(put 'make-from-real-imag 'rectangular
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'rectangular
(lambda (r a) (tag (make-from-mag-ang r a))))
'done)
(define (install-polar-package)
;; internal procedures
(define (magnitude z) (car z))
(define (angle z) (cdr z))
(define (make-from-mag-ang r a) (cons r a))
(define (real-part z)
(mul (magnitude z) (cosine (angle z))))
(define (imag-part z)
(mul (magnitude z) (sine (angle z))))
(define (make-from-real-imag x y)
(cons (sqrt (+ (square x) (square y)))
(atangent y x)))
;; interface to the rest of the system
(define (tag x) (attach-tag 'polar x))
(put 'real-part '(polar) real-part)
(put 'imag-part '(polar) imag-part)
(put 'magnitude '(polar) magnitude)
(put 'angle '(polar) angle)
(put 'make-from-real-imag 'polar
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'polar
(lambda (r a) (tag (make-from-mag-ang r a))))
'done)
(define (install-complex-package)
;; imported procedures from rectangular and polar packages
(define (make-from-real-imag x y)
((get 'make-from-real-imag 'rectangular) x y))
(define (make-from-mag-ang r a)
((get 'make-from-mag-ang 'polar) r a))
;; internal procedures
(define (add-complex z1 z2)
(make-from-real-imag (add (real-part z1) (real-part z2))
(add (imag-part z1) (imag-part z2))))
(define (sub-complex z1 z2)
(make-from-real-imag (sub (real-part z1) (real-part z2))
(sub (imag-part z1) (imag-part z2))))
(define (mul-complex z1 z2)
(make-from-mag-ang (mul (magnitude z1) (magnitude z2))
(add (angle z1) (angle z2))))
(define (div-complex z1 z2)
(make-from-mag-ang (div (magnitude z1) (magnitude z2))
(sub (angle z1) (angle z2))))
;; interface to rest of the system
(define (tag z) (attach-tag 'complex z))
(put 'add '(complex complex)
(lambda (z1 z2) (tag (add-complex z1 z2))))
(put 'sub '(complex complex)
(lambda (z1 z2) (tag (sub-complex z1 z2))))
(put 'mul '(complex complex)
(lambda (z1 z2) (tag (mul-complex z1 z2))))
(put 'div '(complex complex)
(lambda (z1 z2) (tag (div-complex z1 z2))))
(put 'make-from-real-imag 'complex
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'complex
(lambda (r a) (tag (make-from-mag-ang r a))))
(put 'real-part '(complex) real-part)
(put 'imag-part '(complex) imag-part)
(put 'magnitude '(complex) magnitude)
(put 'angle '(complex) angle)
'done)
(install-rectangular-package)
(install-polar-package)
(install-complex-package)
;; Type coercions
(define (install-coercion-package)
Coercions to oneself
(define (scheme-number->scheme-number n) n)
(define (integer->integer n) n)
(define (rational->rational n) n)
(define (real->real n) n)
(define (complex->complex z) z)
;; Promotions
(define (scheme-number->complex n)
(make-complex-from-real-imag (contents n) 0))
(define (integer->rational n)
(make-rational (contents n) 1))
(define (rational->real r)
(make-real (/ (numer r) (denom r) 1.0)))
(define (real->complex n)
(scheme-number->complex n))
Interface to the rest of the system
(put-coercion 'scheme-number 'scheme-number
scheme-number->scheme-number)
(put-coercion 'integer 'integer integer->integer)
(put-coercion 'rational 'rational rational->rational)
(put-coercion 'real 'real real->real)
(put-coercion 'complex 'complex complex->complex)
;;
(put-coercion 'scheme-number 'complex scheme-number->complex)
(put-coercion 'integer 'rational integer->rational)
(put-coercion 'rational 'real rational->real)
(put-coercion 'real 'complex real->complex)
'done)
(install-coercion-package)
Equality package from 2.79
(define (equ? x y) (apply-generic 'equ? x y))
(define (install-equality-package)
(define numer car)
(define denom cdr)
(define real-part car)
(define imag-part cdr)
(define magnitude car)
(define angle cdr)
(define myequal? (λ (x y) (zero? (- x y))))
(put 'equ? '(scheme-number scheme-number) myequal?)
(put 'equ? '(integer integer) myequal?)
(put 'equ? '(real real) myequal?)
(put 'equ? '(rational rational)
(λ (x y) (and (zero? (- (numer x) (numer y)))
(zero? (- (denom x) (denom y))))))
(put 'equ? '(complex complex)
(λ (x y) (equ? x y)))
(put 'equ? '(rectangular rectangular)
(λ (x y) (and (zero? (- (real-part x) (real-part y)))
(zero? (- (imag-part x) (imag-part y))))))
(put 'equ? '(polar polar)
(λ (x y) (and (zero? (- (magnitude x) (magnitude y)))
(zero? (- (angle x) (angle y))))))
'done)
(install-equality-package)
Zero package from 2.80
(define (=zero? x) (apply-generic '=zero? x))
(define (install-zero-package)
(define numer car)
(put '=zero? '(scheme-number)
zero?)
(put '=zero? '(rational)
(λ (r) (zero? (numer r))))
(put '=zero? '(complex)
(λ (z) (zero? (magnitude z))))
'done)
(install-zero-package)
;; Simple generic operations
(define (add x y) (apply-generic 'add x y))
(define (sub x y) (apply-generic 'sub x y))
(define (mul x y) (apply-generic 'mul x y))
(define (div x y) (apply-generic 'div x y))
(define (square x) (apply-generic 'square x))
;; Trigonometry
(define (sine x) (apply-generic 'sine x))
(define (cosine x) (apply-generic 'cosine x))
(define (atangent x) (apply-generic 'atangent x))
;; Type tags
(define (attach-tag type-tag contents)
(if (eq? type-tag 'scheme-number)
contents
(cons type-tag contents)))
(define (type-tag datum)
(cond ((number? datum) 'scheme-number)
((pair? datum) (car datum))
(else (error "Bad tagged datum - TYPE-TAG" datum))))
(define (contents datum)
(cond ((number? datum) datum)
((pair? datum) (cdr datum))
(else (error "Bad tagged datum - CONTENTS" datum))))
;; (define (attach-tag type-tag contents)
;; (cons type-tag contents))
;; (define (type-tag datum)
;; (if (pair? datum)
;; (car datum)
;; (if (number? datum)
;; 'real
;; (error "Bad tagged datum - TYPE-TAG" datum))))
;; (define (contents datum)
;; (if (pair? datum)
;; (cdr datum)
;; (if (number? datum)
;; datum
;; (error "Bad tagged datum - CONTENTS" datum))))
(define (all-same? symbols)
(if (empty? (cdr symbols))
true
(and (eq? (car symbols) (cadr symbols))
(all-same? (cdr symbols)))))
| null | https://raw.githubusercontent.com/sarabander/p2pu-sicp/fbc49b67dac717da1487629fb2d7a7d86dfdbe32/2.5/generic-arithmetic/setup.scm | scheme |
;;
This is Generic Arithmetic Package ;;
---------------------------------- ;;
;
;;
; ( works in Racket 5.0 )
;;
Hashtable for operations, plus backup to retain old versions
Same for coercions
Getters and setters
General package for primitive number types
Constructors
Rational package
internal procedures
interface to rest of the system
Complex number packages
Constructors
Selectors
internal procedures
interface to the rest of the system
internal procedures
interface to the rest of the system
imported procedures from rectangular and polar packages
internal procedures
interface to rest of the system
Type coercions
Promotions
Simple generic operations
Trigonometry
Type tags
(define (attach-tag type-tag contents)
(cons type-tag contents))
(define (type-tag datum)
(if (pair? datum)
(car datum)
(if (number? datum)
'real
(error "Bad tagged datum - TYPE-TAG" datum))))
(define (contents datum)
(if (pair? datum)
(cdr datum)
(if (number? datum)
datum
(error "Bad tagged datum - CONTENTS" datum)))) |
(define optable (make-hash))
(define optable-backup (make-hash))
(define coercions (make-hash))
(define coercions-backup (make-hash))
(define (get operation types)
(hash-ref optable (list operation types) false))
(define (get-backup operation types)
(hash-ref optable-backup (list operation types) false))
(define (put operation types procedure)
(let ((exists (get operation types)))
(if exists
(and (put-backup operation types exists)
(hash-set! optable (list operation types) procedure))
(hash-set! optable (list operation types) procedure))))
(define (put-backup operation types procedure)
(let ((exists (get-backup operation types)))
(if exists
(hash-set! optable-backup
(list operation types)
(cons procedure exists))
(hash-set! optable-backup
(list operation types)
(list procedure)))))
(define (get-coercion oldtype newtype)
(hash-ref coercions (list oldtype newtype) false))
(define (get-coercion-backup oldtype newtype)
(hash-ref coercions-backup (list oldtype newtype) false))
(define (put-coercion oldtype newtype procedure)
(let ((exists (get-coercion oldtype newtype)))
(if exists
(and (put-coercion-backup oldtype newtype exists)
(hash-set! coercions (list oldtype newtype) procedure))
(hash-set! coercions (list oldtype newtype) procedure))))
(define (put-coercion-backup oldtype newtype procedure)
(let ((exists (get-coercion-backup oldtype newtype)))
(if exists
(hash-set! coercions-backup
(list oldtype newtype)
(cons procedure exists))
(hash-set! coercions-backup
(list oldtype newtype)
(list procedure)))))
First version of apply - generic from the book
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(apply proc (map contents args))
(error
"No method for these types* - APPLY-GENERIC"
(list op type-tags))))))
(define (install-package type)
(define (tag x)
(attach-tag type x))
(put 'add (list type type)
(lambda (x y) (tag (+ x y))))
(put 'sub (list type type)
(lambda (x y) (tag (- x y))))
(put 'mul (list type type)
(lambda (x y) (tag (* x y))))
(put 'div (list type type)
(lambda (x y) (tag (/ x y))))
(put 'square (list type) sqr)
(put 'sine (list type) sin)
(put 'cosine (list type) cos)
(put 'atangent (list type) atan)
(put 'make type
(lambda (x) (tag x)))
'done)
(install-package 'scheme-number)
(install-package 'integer)
(install-package 'real)
(define (make-scheme-number n)
((get 'make 'scheme-number) n))
(define (make-integer n)
((get 'make 'integer) n))
(define (make-real n)
((get 'make 'real) n))
(define (install-rational-package)
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (add-rat x y)
(make-rat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (- (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (tag x) (attach-tag 'rational x))
(put 'add '(rational rational)
(lambda (x y) (tag (add-rat x y))))
(put 'sub '(rational rational)
(lambda (x y) (tag (sub-rat x y))))
(put 'mul '(rational rational)
(lambda (x y) (tag (mul-rat x y))))
(put 'div '(rational rational)
(lambda (x y) (tag (div-rat x y))))
(put 'square '(rational)
(lambda (r) (sqr (/ (numer r) (denom r)))))
(put 'sine '(rational)
(lambda (r) (sin (/ (numer r) (denom r)))))
(put 'cosine '(rational)
(lambda (r) (cos (/ (numer r) (denom r)))))
(put 'atangent '(rational)
(lambda (r) (atan (/ (numer r) (denom r)))))
(put 'make 'rational
(lambda (n d) (tag (make-rat n d))))
(put 'numer '(rational)
(lambda (r) (numer r)))
(put 'denom '(rational)
(lambda (r) (denom r)))
'done)
(install-rational-package)
(define (make-rational n d)
((get 'make 'rational) n d))
(define (numer r)
(apply-generic 'numer r))
(define (denom r)
(apply-generic 'denom r))
(define (make-complex-from-real-imag x y)
((get 'make-from-real-imag 'complex) x y))
(define (make-complex-from-mag-ang r a)
((get 'make-from-mag-ang 'complex) r a))
(define (real-part z) (apply-generic 'real-part z))
(define (imag-part z) (apply-generic 'imag-part z))
(define (magnitude z) (apply-generic 'magnitude z))
(define (angle z) (apply-generic 'angle z))
(define (install-rectangular-package)
(define (real-part z) (car z))
(define (imag-part z) (cdr z))
(define (make-from-real-imag x y) (cons x y))
(define (magnitude z)
(sqrt (+ (square (real-part z))
(square (imag-part z)))))
(define (angle z)
(atangent (div (imag-part z) (real-part z))))
(define (make-from-mag-ang r a)
(cons (* r (cosine a)) (* r (sine a))))
(define (tag x) (attach-tag 'rectangular x))
(put 'real-part '(rectangular) real-part)
(put 'imag-part '(rectangular) imag-part)
(put 'magnitude '(rectangular) magnitude)
(put 'angle '(rectangular) angle)
(put 'make-from-real-imag 'rectangular
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'rectangular
(lambda (r a) (tag (make-from-mag-ang r a))))
'done)
(define (install-polar-package)
(define (magnitude z) (car z))
(define (angle z) (cdr z))
(define (make-from-mag-ang r a) (cons r a))
(define (real-part z)
(mul (magnitude z) (cosine (angle z))))
(define (imag-part z)
(mul (magnitude z) (sine (angle z))))
(define (make-from-real-imag x y)
(cons (sqrt (+ (square x) (square y)))
(atangent y x)))
(define (tag x) (attach-tag 'polar x))
(put 'real-part '(polar) real-part)
(put 'imag-part '(polar) imag-part)
(put 'magnitude '(polar) magnitude)
(put 'angle '(polar) angle)
(put 'make-from-real-imag 'polar
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'polar
(lambda (r a) (tag (make-from-mag-ang r a))))
'done)
(define (install-complex-package)
(define (make-from-real-imag x y)
((get 'make-from-real-imag 'rectangular) x y))
(define (make-from-mag-ang r a)
((get 'make-from-mag-ang 'polar) r a))
(define (add-complex z1 z2)
(make-from-real-imag (add (real-part z1) (real-part z2))
(add (imag-part z1) (imag-part z2))))
(define (sub-complex z1 z2)
(make-from-real-imag (sub (real-part z1) (real-part z2))
(sub (imag-part z1) (imag-part z2))))
(define (mul-complex z1 z2)
(make-from-mag-ang (mul (magnitude z1) (magnitude z2))
(add (angle z1) (angle z2))))
(define (div-complex z1 z2)
(make-from-mag-ang (div (magnitude z1) (magnitude z2))
(sub (angle z1) (angle z2))))
(define (tag z) (attach-tag 'complex z))
(put 'add '(complex complex)
(lambda (z1 z2) (tag (add-complex z1 z2))))
(put 'sub '(complex complex)
(lambda (z1 z2) (tag (sub-complex z1 z2))))
(put 'mul '(complex complex)
(lambda (z1 z2) (tag (mul-complex z1 z2))))
(put 'div '(complex complex)
(lambda (z1 z2) (tag (div-complex z1 z2))))
(put 'make-from-real-imag 'complex
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'complex
(lambda (r a) (tag (make-from-mag-ang r a))))
(put 'real-part '(complex) real-part)
(put 'imag-part '(complex) imag-part)
(put 'magnitude '(complex) magnitude)
(put 'angle '(complex) angle)
'done)
(install-rectangular-package)
(install-polar-package)
(install-complex-package)
(define (install-coercion-package)
Coercions to oneself
(define (scheme-number->scheme-number n) n)
(define (integer->integer n) n)
(define (rational->rational n) n)
(define (real->real n) n)
(define (complex->complex z) z)
(define (scheme-number->complex n)
(make-complex-from-real-imag (contents n) 0))
(define (integer->rational n)
(make-rational (contents n) 1))
(define (rational->real r)
(make-real (/ (numer r) (denom r) 1.0)))
(define (real->complex n)
(scheme-number->complex n))
Interface to the rest of the system
(put-coercion 'scheme-number 'scheme-number
scheme-number->scheme-number)
(put-coercion 'integer 'integer integer->integer)
(put-coercion 'rational 'rational rational->rational)
(put-coercion 'real 'real real->real)
(put-coercion 'complex 'complex complex->complex)
(put-coercion 'scheme-number 'complex scheme-number->complex)
(put-coercion 'integer 'rational integer->rational)
(put-coercion 'rational 'real rational->real)
(put-coercion 'real 'complex real->complex)
'done)
(install-coercion-package)
Equality package from 2.79
(define (equ? x y) (apply-generic 'equ? x y))
(define (install-equality-package)
(define numer car)
(define denom cdr)
(define real-part car)
(define imag-part cdr)
(define magnitude car)
(define angle cdr)
(define myequal? (λ (x y) (zero? (- x y))))
(put 'equ? '(scheme-number scheme-number) myequal?)
(put 'equ? '(integer integer) myequal?)
(put 'equ? '(real real) myequal?)
(put 'equ? '(rational rational)
(λ (x y) (and (zero? (- (numer x) (numer y)))
(zero? (- (denom x) (denom y))))))
(put 'equ? '(complex complex)
(λ (x y) (equ? x y)))
(put 'equ? '(rectangular rectangular)
(λ (x y) (and (zero? (- (real-part x) (real-part y)))
(zero? (- (imag-part x) (imag-part y))))))
(put 'equ? '(polar polar)
(λ (x y) (and (zero? (- (magnitude x) (magnitude y)))
(zero? (- (angle x) (angle y))))))
'done)
(install-equality-package)
Zero package from 2.80
(define (=zero? x) (apply-generic '=zero? x))
(define (install-zero-package)
(define numer car)
(put '=zero? '(scheme-number)
zero?)
(put '=zero? '(rational)
(λ (r) (zero? (numer r))))
(put '=zero? '(complex)
(λ (z) (zero? (magnitude z))))
'done)
(install-zero-package)
(define (add x y) (apply-generic 'add x y))
(define (sub x y) (apply-generic 'sub x y))
(define (mul x y) (apply-generic 'mul x y))
(define (div x y) (apply-generic 'div x y))
(define (square x) (apply-generic 'square x))
(define (sine x) (apply-generic 'sine x))
(define (cosine x) (apply-generic 'cosine x))
(define (atangent x) (apply-generic 'atangent x))
(define (attach-tag type-tag contents)
(if (eq? type-tag 'scheme-number)
contents
(cons type-tag contents)))
(define (type-tag datum)
(cond ((number? datum) 'scheme-number)
((pair? datum) (car datum))
(else (error "Bad tagged datum - TYPE-TAG" datum))))
(define (contents datum)
(cond ((number? datum) datum)
((pair? datum) (cdr datum))
(else (error "Bad tagged datum - CONTENTS" datum))))
(define (all-same? symbols)
(if (empty? (cdr symbols))
true
(and (eq? (car symbols) (cadr symbols))
(all-same? (cdr symbols)))))
|
4206f2e3293f31eec84b9702e82d91e03f730e3f8109eb574d2942dc05e4c176 | StrykerKKD/Jerboa | middleware_config.ml | let apply_middlewares middleware_config request =
Base.List.fold middleware_config ~init:request ~f:(fun request_accumulator middleware -> middleware request_accumulator) | null | https://raw.githubusercontent.com/StrykerKKD/Jerboa/0c1cbfcba003e99a39a37c4a9795b911f8eb2e7b/lib/middleware_config.ml | ocaml | let apply_middlewares middleware_config request =
Base.List.fold middleware_config ~init:request ~f:(fun request_accumulator middleware -> middleware request_accumulator) | |
01c44dcb22ea4044b88f7fcf36682e7c0d0b51f525d0ed85c94b36a66625895c | jrm-code-project/LISP-Machine | nf-system.lisp | -*- Mode : LISP ; Package : USER ; Base:8 ; : ZL -*-
(defpackage nf)
(defsystem nf
)
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/pace/nf/nf-system.lisp | lisp | Package : USER ; Base:8 ; : ZL -*- | (defpackage nf)
(defsystem nf
)
|
8a650b57e8e48b7705f5f2e64071d683489133f7ea71a8849fa5a342d9da0217 | ndmitchell/ghc-make | Main.hs |
import A
import C.C
main = print $ a + b + c
| null | https://raw.githubusercontent.com/ndmitchell/ghc-make/5164c721efa38a02be33d340cc91f5c737c29156/tests/simple/Main.hs | haskell |
import A
import C.C
main = print $ a + b + c
| |
03a4faa700e60fe1e0a739fb32b80536fdcae697c0df7e13ab735ceb0232994a | gregcman/sucle | camera-matrix.lisp | (defpackage #:camera-matrix
(:use #:cl)
(:export
#:make-camera
#:camera-vec-forward
#:camera-vec-position
#:camera-vec-noitisop
#:camera-aspect-ratio
#:camera-fov
#:camera-frustum-far
#:camera-frustum-near
#:camera-matrix-projection-view-player)
(:export
#:update-matrices))
(in-package #:camera-matrix)
(struct-to-clos:struct->class
(defstruct camera
(vec-position (sb-cga:vec 0.0 0.0 0.0) :type sb-cga:vec)
(vec-up (sb-cga:vec 0.0 1.0 0.0) :type sb-cga:vec)
(vec-forward (sb-cga:vec 1.0 0.0 0.0) :type sb-cga:vec)
(vec-backwards (sb-cga:vec -1.0 0.0 0.0) :type sb-cga:vec)
(vec-noitisop (sb-cga:vec 0.0 0.0 0.0) :type sb-cga:vec) ;;;the negative of position
(matrix-player (sb-cga:identity-matrix)) ;;positional information of camera
(matrix-view (sb-cga:identity-matrix)) ;;view matrix
(matrix-projection (sb-cga:identity-matrix)) ;;projection matrix
(matrix-projection-view (sb-cga:identity-matrix)) ;;projection * view matrix
(matrix-projection-view-player (sb-cga:identity-matrix))
(fov (coerce (/ pi 2.0) 'single-float) :type single-float)
(aspect-ratio 1.0 :type single-float)
(frustum-near 0.0078125 :type single-float)
(frustum-far 128.0 :type single-float)
(cam-up (sb-cga:vec 0.0 1.0 0.0) :type sb-cga:vec)
(cam-right (sb-cga:vec 0.0 0.0 1.0) :type sb-cga:vec)
;;The normals of each plane.
one is vec - forward , another -vec - forward
planes
edges))
(defun projection-matrix (result camera)
(let ((half-fovy (* 0.5 (camera-fov camera)))
(aspect (camera-aspect-ratio camera))
(near (camera-frustum-near camera))
(far (camera-frustum-far camera)))
(let ((cot (/ (cos half-fovy)
(sin half-fovy))))
(let ((sum (+ far near))
(difference (- near far)))
;;[FIXME]necessary?
(nsb-cga:%matrix result
(* cot aspect) 0.0 0.0 0.0
0.0 cot 0.0 0.0
0.0 0.0 (/ sum difference) (/ (* 2.0 far near) difference)
0.0 0.0 -1.0 0.0)))))
(defun calculate-frustum-edge-vectors (camera)
(let* ((half-fovy (* 0.5 (camera-fov camera)))
(forward (camera-vec-forward camera))
(up (camera-cam-up camera))
(right (camera-cam-right camera))
;;(near (camera-frustum-near camera))
;;(far (camera-frustum-far camera))
(y+ (* 1 (tan half-fovy)))
(x+ (/ y+ (camera-aspect-ratio camera)))
(vec-y+ (nsb-cga:vec* up y+))
(vec-y- (nsb-cga:vec* up (- y+)))
(vec-x+ (nsb-cga:vec* right x+))
(vec-x- (nsb-cga:vec* right (- x+))))
(setf
(camera-edges camera)
(list
;;FIXME:optimize, does this create a lot of garbage?
( nsb - cga : vec+ forward vec - x+ )
( nsb - cga : vec+ forward vec - x- )
( nsb - cga : vec+ forward vec - y+ )
( nsb - cga : vec+ forward vec - y- )
(nsb-cga:vec+ (nsb-cga:vec+ forward vec-x+) vec-y+)
(nsb-cga:vec+ (nsb-cga:vec+ forward vec-x-) vec-y+)
(nsb-cga:vec+ (nsb-cga:vec+ forward vec-x-) vec-y-)
(nsb-cga:vec+ (nsb-cga:vec+ forward vec-x+) vec-y-)))))
(defun calculate-frustum-planes (camera)
(destructuring-bind (tr tl bl br) (camera-edges camera)
(flet ((foo (a b)
(let ((vec (nsb-cga:cross-product a b)))
(nsb-cga:%normalize vec vec))))
(setf (camera-planes camera)
(list
(foo tl tr)
(foo bl tl)
(foo br bl)
(foo tr br)
(camera-vec-forward camera)
;;(camera-vec-backwards camera)
)))))
#+nil
(nsb-cga:cross-product
(nsb-cga:vec 1.0 0.0 0.0)
(nsb-cga:vec 0.0 1.0 0.0))
(defun relative-lookat (result relative-target up)
(let ((camright (sb-cga:cross-product up relative-target)))
(sb-cga:%normalize camright camright)
(let ((camup (sb-cga:cross-product relative-target camright)))
(sb-cga:%normalize camup camup)
(values
(get-lookat result camright camup relative-target)
camright
camup))))
(defun get-lookat (result right up direction)
(let ((rx (aref right 0))
(ry (aref right 1))
(rz (aref right 2))
(ux (aref up 0))
(uy (aref up 1))
(uz (aref up 2))
(dx (aref direction 0))
(dy (aref direction 1))
(dz (aref direction 2)))
(nsb-cga:%matrix
result
rx ry rz 0.0
ux uy uz 0.0
dx dy dz 0.0
0.0 0.0 0.0 1.0)))
(defun update-matrices (camera)
(let ((projection-matrix (camera-matrix-projection camera))
(view-matrix (camera-matrix-view camera))
(projection-view-matrix (camera-matrix-projection-view camera))
(projection-view-player-matrix (camera-matrix-projection-view-player camera))
(player-matrix (camera-matrix-player camera))
(forward (camera-vec-forward camera))
(up (camera-vec-up camera))
(backwards (camera-vec-backwards camera)))
(projection-matrix projection-matrix camera)
(nsb-cga:%vec* backwards forward -1.0)
(multiple-value-bind (a right up)
(relative-lookat view-matrix backwards up)
(declare (ignorable a))
(setf (camera-cam-up camera) up
(camera-cam-right camera) right))
(nsb-cga:%matrix* projection-view-matrix projection-matrix view-matrix)
(let ((cev (camera-vec-noitisop camera))
(position (camera-vec-position camera)))
(nsb-cga:%vec* cev position -1.0)
(nsb-cga:%translate player-matrix cev))
(nsb-cga:%matrix* projection-view-player-matrix projection-view-matrix player-matrix))
(calculate-frustum-edge-vectors camera)
(calculate-frustum-planes camera))
;;;
;;;
;;;
#+nil
(defun spec-projection-matrix (near far left right top bottom)
(let ((near-2 (* 2 near))
(top-bottom (- top bottom))
(far-near (- far near)))
(sb-cga:matrix
(/ near-2 (- right left)) 0.0 (/ (+ right left) (- right left)) 0.0
0.0 (/ near-2 top-bottom) (/ (+ top bottom) top-bottom) 0.0
0.0 0.0 (- (/ (+ far near) far-near)) (/ (* -2 far near) far-near)
0.0 0.0 -1.0 0.0)))
| null | https://raw.githubusercontent.com/gregcman/sucle/258be4ac4daaceea06a55f893227584d3772bb47/src/camera-matrix/camera-matrix.lisp | lisp | the negative of position
positional information of camera
view matrix
projection matrix
projection * view matrix
The normals of each plane.
[FIXME]necessary?
(near (camera-frustum-near camera))
(far (camera-frustum-far camera))
FIXME:optimize, does this create a lot of garbage?
(camera-vec-backwards camera)
| (defpackage #:camera-matrix
(:use #:cl)
(:export
#:make-camera
#:camera-vec-forward
#:camera-vec-position
#:camera-vec-noitisop
#:camera-aspect-ratio
#:camera-fov
#:camera-frustum-far
#:camera-frustum-near
#:camera-matrix-projection-view-player)
(:export
#:update-matrices))
(in-package #:camera-matrix)
(struct-to-clos:struct->class
(defstruct camera
(vec-position (sb-cga:vec 0.0 0.0 0.0) :type sb-cga:vec)
(vec-up (sb-cga:vec 0.0 1.0 0.0) :type sb-cga:vec)
(vec-forward (sb-cga:vec 1.0 0.0 0.0) :type sb-cga:vec)
(vec-backwards (sb-cga:vec -1.0 0.0 0.0) :type sb-cga:vec)
(matrix-projection-view-player (sb-cga:identity-matrix))
(fov (coerce (/ pi 2.0) 'single-float) :type single-float)
(aspect-ratio 1.0 :type single-float)
(frustum-near 0.0078125 :type single-float)
(frustum-far 128.0 :type single-float)
(cam-up (sb-cga:vec 0.0 1.0 0.0) :type sb-cga:vec)
(cam-right (sb-cga:vec 0.0 0.0 1.0) :type sb-cga:vec)
one is vec - forward , another -vec - forward
planes
edges))
(defun projection-matrix (result camera)
(let ((half-fovy (* 0.5 (camera-fov camera)))
(aspect (camera-aspect-ratio camera))
(near (camera-frustum-near camera))
(far (camera-frustum-far camera)))
(let ((cot (/ (cos half-fovy)
(sin half-fovy))))
(let ((sum (+ far near))
(difference (- near far)))
(nsb-cga:%matrix result
(* cot aspect) 0.0 0.0 0.0
0.0 cot 0.0 0.0
0.0 0.0 (/ sum difference) (/ (* 2.0 far near) difference)
0.0 0.0 -1.0 0.0)))))
(defun calculate-frustum-edge-vectors (camera)
(let* ((half-fovy (* 0.5 (camera-fov camera)))
(forward (camera-vec-forward camera))
(up (camera-cam-up camera))
(right (camera-cam-right camera))
(y+ (* 1 (tan half-fovy)))
(x+ (/ y+ (camera-aspect-ratio camera)))
(vec-y+ (nsb-cga:vec* up y+))
(vec-y- (nsb-cga:vec* up (- y+)))
(vec-x+ (nsb-cga:vec* right x+))
(vec-x- (nsb-cga:vec* right (- x+))))
(setf
(camera-edges camera)
(list
( nsb - cga : vec+ forward vec - x+ )
( nsb - cga : vec+ forward vec - x- )
( nsb - cga : vec+ forward vec - y+ )
( nsb - cga : vec+ forward vec - y- )
(nsb-cga:vec+ (nsb-cga:vec+ forward vec-x+) vec-y+)
(nsb-cga:vec+ (nsb-cga:vec+ forward vec-x-) vec-y+)
(nsb-cga:vec+ (nsb-cga:vec+ forward vec-x-) vec-y-)
(nsb-cga:vec+ (nsb-cga:vec+ forward vec-x+) vec-y-)))))
(defun calculate-frustum-planes (camera)
(destructuring-bind (tr tl bl br) (camera-edges camera)
(flet ((foo (a b)
(let ((vec (nsb-cga:cross-product a b)))
(nsb-cga:%normalize vec vec))))
(setf (camera-planes camera)
(list
(foo tl tr)
(foo bl tl)
(foo br bl)
(foo tr br)
(camera-vec-forward camera)
)))))
#+nil
(nsb-cga:cross-product
(nsb-cga:vec 1.0 0.0 0.0)
(nsb-cga:vec 0.0 1.0 0.0))
(defun relative-lookat (result relative-target up)
(let ((camright (sb-cga:cross-product up relative-target)))
(sb-cga:%normalize camright camright)
(let ((camup (sb-cga:cross-product relative-target camright)))
(sb-cga:%normalize camup camup)
(values
(get-lookat result camright camup relative-target)
camright
camup))))
(defun get-lookat (result right up direction)
(let ((rx (aref right 0))
(ry (aref right 1))
(rz (aref right 2))
(ux (aref up 0))
(uy (aref up 1))
(uz (aref up 2))
(dx (aref direction 0))
(dy (aref direction 1))
(dz (aref direction 2)))
(nsb-cga:%matrix
result
rx ry rz 0.0
ux uy uz 0.0
dx dy dz 0.0
0.0 0.0 0.0 1.0)))
(defun update-matrices (camera)
(let ((projection-matrix (camera-matrix-projection camera))
(view-matrix (camera-matrix-view camera))
(projection-view-matrix (camera-matrix-projection-view camera))
(projection-view-player-matrix (camera-matrix-projection-view-player camera))
(player-matrix (camera-matrix-player camera))
(forward (camera-vec-forward camera))
(up (camera-vec-up camera))
(backwards (camera-vec-backwards camera)))
(projection-matrix projection-matrix camera)
(nsb-cga:%vec* backwards forward -1.0)
(multiple-value-bind (a right up)
(relative-lookat view-matrix backwards up)
(declare (ignorable a))
(setf (camera-cam-up camera) up
(camera-cam-right camera) right))
(nsb-cga:%matrix* projection-view-matrix projection-matrix view-matrix)
(let ((cev (camera-vec-noitisop camera))
(position (camera-vec-position camera)))
(nsb-cga:%vec* cev position -1.0)
(nsb-cga:%translate player-matrix cev))
(nsb-cga:%matrix* projection-view-player-matrix projection-view-matrix player-matrix))
(calculate-frustum-edge-vectors camera)
(calculate-frustum-planes camera))
#+nil
(defun spec-projection-matrix (near far left right top bottom)
(let ((near-2 (* 2 near))
(top-bottom (- top bottom))
(far-near (- far near)))
(sb-cga:matrix
(/ near-2 (- right left)) 0.0 (/ (+ right left) (- right left)) 0.0
0.0 (/ near-2 top-bottom) (/ (+ top bottom) top-bottom) 0.0
0.0 0.0 (- (/ (+ far near) far-near)) (/ (* -2 far near) far-near)
0.0 0.0 -1.0 0.0)))
|
be681b7825166cb2c3962b8c1e5aaaf01dfe26895effdaa2b51c216e2a6b4e12 | geophf/1HaskellADay | Solution.hs | module Y2016.M09.D29.Solution where
import Control.Arrow ((&&&), second)
import Control.Monad ((>=>))
import Data.Foldable (toList)
import Data.Function (on)
import Data.List (sortBy)
import Data.Maybe (mapMaybe)
import Data.Ord
import Data.Time.LocalTime
below imports available via 1HaskellADay git repository
import Data.BlockChain.Block.Transactions
import Data.BlockChain.Block.Types
import Data.Monetary.BitCoin
import Data.MultiMap (MultiMap)
import qualified Data.MultiMap as MM
import Data.Tree.Merkle
import Y2016.M09.D22.Solution (latestTransactions)
import Y2016.M09.D23.Solution (val2BTC)
-
So , trees are effient for searching by hash , which makes copying them
a much smaller task than copying a whole tree . This is a good thing ,
as the block chain , a tree , is 65 + gigabytes and growing .
We wo n't look at copying today .
What trees are not designed for is searching for tags or keys in the
leaves of the tree . This is a problem for someone who wishes to view their
latest transaction or some or all of their transactions but does n't have the
hash of the transaction .
One could counter : just hash your i d , the receiver 's i d , and the bitcoins
exchanged , right ?
No , it 's not that simple , as transactions often have third - party fees for
processing the transaction , or have multiple inputs and outputs for one
transaction . If you only hash yourself , the receiver and the amount , your hash
will likely not match the transaction you are looking for .
So , we need a way to find data in a tree without the hash .
This is a problem , because if we do n't have the hash , we may have to search
the entire tree , every time , unguided .
That 's a problem .
Today 's exercise .
Given a tree , create auxiliary search structures that allow you to
extract transactions by address or by date / time range ( and address ) .
-
So, Merkle trees are effient for searching by hash, which makes copying them
a much smaller task than copying a whole Merkle tree. This is a good thing,
as the block chain, a Merkle tree, is 65+ gigabytes and growing.
We won't look at copying today.
What Merkle trees are not designed for is searching for tags or keys in the
leaves of the tree. This is a problem for someone who wishes to view their
latest transaction or some or all of their transactions but doesn't have the
hash of the transaction.
One could counter: just hash your id, the receiver's id, and the bitcoins
exchanged, right?
No, it's not that simple, as transactions often have third-party fees for
processing the transaction, or have multiple inputs and outputs for one
transaction. If you only hash yourself, the receiver and the amount, your hash
will likely not match the transaction you are looking for.
So, we need a way to find data in a Merkle tree without the hash.
This is a problem, because if we don't have the hash, we may have to search
the entire tree, every time, unguided.
That's a problem.
Today's Haskell exercise.
Given a Merkle tree, create auxiliary search structures that allow you to
extract transactions by address or by date/time range (and address).
--}
First populate a tree with transactions from the , e.g. , latest block .
type AddrTransactions = MultiMap Hash Transaction [Transaction]
it 's helpful to make a Merkle Tree foldable
instance Foldable MerkleTree where
foldr f z = foldr f z . root
instance Foldable Branch where
foldr f z (Twig _ (Leaf _ v)) = f v z
foldr f z (Branch _ (Leaf _ v1) (Leaf _ v2)) = f v1 (f v2 z)
foldr f z (Parent _ bb1 bb2) = foldr f (foldr f z (branch bb1)) (branch bb2)
addresses :: MerkleTree Transaction -> AddrTransactions
addresses = MM.fromList pure
. concatMap (uncurry zip . (mapMaybe (prevOut >=> addr) . inputs &&& repeat))
. toList
-
* Y2016.M09.D29.Solution > latestTransactions ~ > lt ~ > length ~ > 2458
* Y2016.M09.D29.Solution > let tree = fromList ( map mkleaf lt )
* Y2016.M09.D29.Solution > length tree ~ > 2458 -- so foldable is WORKING !
* Y2016.M09.D29.Solution > let = addresses tree
* Y2016.M09.D29.Solution > head $ MM.toList ~ >
( " 1128iYdsZB4CyV2F8T9bk1MzqRDjs6FeLZ",[TX { lockTime = 0 , version = 1 , ... } ] )
-- which address has the most transactions ?
* Y2016.M09.D29.Solution > let sorted = ( compare ` on ` Down . length . snd ) ( MM.toList )
* Y2016.M09.D29.Solution > let ans = head sorted
* Y2016.M09.D29.Solution > fst ans ~ > " 1318wvPUgwkcDVzUyabuvduguhKM6piRfn "
* Y2016.M09.D29.Solution > length $ snd ans ~ > 98
-- which address has the transaction involving the most bitcoins exchanged
* Y2016.M09.D29.Solution > let bits = map ( second ( maximum . map ( val2BTC . sum . map value . out ) ) ) sorted
* Y2016.M09.D29.Solution > let sortedbits = ( compare ` on ` Down . snd ) bits
* Y2016.M09.D29.Solution > head sortedbits ~ >
( " 13XTjbT68K7S3s1cEPBUs2uohEAjj3AYpv",BTC 416.24 )
-
*Y2016.M09.D29.Solution> latestTransactions ~> lt ~> length ~> 2458
*Y2016.M09.D29.Solution> let tree = fromList (map mkleaf lt)
*Y2016.M09.D29.Solution> length tree ~> 2458 -- so foldable is WORKING!
*Y2016.M09.D29.Solution> let addrs = addresses tree
*Y2016.M09.D29.Solution> head $ MM.toList addrs ~>
("1128iYdsZB4CyV2F8T9bk1MzqRDjs6FeLZ",[TX {lockTime = 0, version = 1, ...}])
-- which address has the most transactions?
*Y2016.M09.D29.Solution> let sorted = sortBy (compare `on` Down . length . snd) (MM.toList addrs)
*Y2016.M09.D29.Solution> let ans = head sorted
*Y2016.M09.D29.Solution> fst ans ~> "1318wvPUgwkcDVzUyabuvduguhKM6piRfn"
*Y2016.M09.D29.Solution> length $ snd ans ~> 98
-- which address has the transaction involving the most bitcoins exchanged
*Y2016.M09.D29.Solution> let bits = map (second (maximum . map (val2BTC . sum . map value . out))) sorted
*Y2016.M09.D29.Solution> let sortedbits = sortBy (compare `on` Down . snd) bits
*Y2016.M09.D29.Solution> head sortedbits ~>
("13XTjbT68K7S3s1cEPBUs2uohEAjj3AYpv",BTC 416.24)
--}
Now : how do I find only the transactions between one address and another ?
transactionsBetween :: AddrTransactions -> Hash -> Hash -> [Transaction]
transactionsBetween addrs me you =
filter (elem you . mapMaybe addr . out) $ MM.lookup me addrs
-
For a new map , largest address - set is 39
* Y2016.M09.D29.Solution > second length $ head sorted ~ >
( " 1FMJXNWyNkWohjU6r6SMbwnt4b9nHXJUJE",39 )
Huh , some transactions are just between only two parties anyway :
* Y2016.M09.D29.Solution > let x = " 1FQ4SuwadRLnx6fNDvcs4Fy3KiLFkyQF9P " " 1EMs2Acsr6groSFAume73LgE1wzJdz5d3P "
* Y2016.M09.D29.Solution > length x ~ >
... which are all the transactions for that address .
-
For a new map, largest address-set is 39
*Y2016.M09.D29.Solution> second length $ head sorted ~>
("1FMJXNWyNkWohjU6r6SMbwnt4b9nHXJUJE",39)
Huh, some transactions are just between only two parties anyway:
*Y2016.M09.D29.Solution> let x = transactionsBetween addrs "1FQ4SuwadRLnx6fNDvcs4Fy3KiLFkyQF9P" "1EMs2Acsr6groSFAume73LgE1wzJdz5d3P"
*Y2016.M09.D29.Solution> length x ~>
... which are all the transactions for that address.
--}
{-- BONUS -----------------------------------------------------------------
Now we wish to time-box transactions. This will involve some faux data
generation, unless, of course, you wish to scan the entire block chain into
your system and play with that.
Generate or read in a set of transactions for a set of users, making sure
these transactions fall over a set of different time-periods (e.g. days)
Using the above structure, have only the transactions returned within a time-
period
--}
transactionsFor :: AddrTransactions -> Hash -> LocalTime -> LocalTime
-> [Transaction]
transactionsFor addresses user from to = undefined
-- We'll solve this bonus problem ... AFTER I get some sleep!
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2016/M09/D29/Solution.hs | haskell | }
so foldable is WORKING !
which address has the most transactions ?
which address has the transaction involving the most bitcoins exchanged
so foldable is WORKING!
which address has the most transactions?
which address has the transaction involving the most bitcoins exchanged
}
}
- BONUS -----------------------------------------------------------------
Now we wish to time-box transactions. This will involve some faux data
generation, unless, of course, you wish to scan the entire block chain into
your system and play with that.
Generate or read in a set of transactions for a set of users, making sure
these transactions fall over a set of different time-periods (e.g. days)
Using the above structure, have only the transactions returned within a time-
period
-
We'll solve this bonus problem ... AFTER I get some sleep! | module Y2016.M09.D29.Solution where
import Control.Arrow ((&&&), second)
import Control.Monad ((>=>))
import Data.Foldable (toList)
import Data.Function (on)
import Data.List (sortBy)
import Data.Maybe (mapMaybe)
import Data.Ord
import Data.Time.LocalTime
below imports available via 1HaskellADay git repository
import Data.BlockChain.Block.Transactions
import Data.BlockChain.Block.Types
import Data.Monetary.BitCoin
import Data.MultiMap (MultiMap)
import qualified Data.MultiMap as MM
import Data.Tree.Merkle
import Y2016.M09.D22.Solution (latestTransactions)
import Y2016.M09.D23.Solution (val2BTC)
-
So , trees are effient for searching by hash , which makes copying them
a much smaller task than copying a whole tree . This is a good thing ,
as the block chain , a tree , is 65 + gigabytes and growing .
We wo n't look at copying today .
What trees are not designed for is searching for tags or keys in the
leaves of the tree . This is a problem for someone who wishes to view their
latest transaction or some or all of their transactions but does n't have the
hash of the transaction .
One could counter : just hash your i d , the receiver 's i d , and the bitcoins
exchanged , right ?
No , it 's not that simple , as transactions often have third - party fees for
processing the transaction , or have multiple inputs and outputs for one
transaction . If you only hash yourself , the receiver and the amount , your hash
will likely not match the transaction you are looking for .
So , we need a way to find data in a tree without the hash .
This is a problem , because if we do n't have the hash , we may have to search
the entire tree , every time , unguided .
That 's a problem .
Today 's exercise .
Given a tree , create auxiliary search structures that allow you to
extract transactions by address or by date / time range ( and address ) .
-
So, Merkle trees are effient for searching by hash, which makes copying them
a much smaller task than copying a whole Merkle tree. This is a good thing,
as the block chain, a Merkle tree, is 65+ gigabytes and growing.
We won't look at copying today.
What Merkle trees are not designed for is searching for tags or keys in the
leaves of the tree. This is a problem for someone who wishes to view their
latest transaction or some or all of their transactions but doesn't have the
hash of the transaction.
One could counter: just hash your id, the receiver's id, and the bitcoins
exchanged, right?
No, it's not that simple, as transactions often have third-party fees for
processing the transaction, or have multiple inputs and outputs for one
transaction. If you only hash yourself, the receiver and the amount, your hash
will likely not match the transaction you are looking for.
So, we need a way to find data in a Merkle tree without the hash.
This is a problem, because if we don't have the hash, we may have to search
the entire tree, every time, unguided.
That's a problem.
Today's Haskell exercise.
Given a Merkle tree, create auxiliary search structures that allow you to
extract transactions by address or by date/time range (and address).
First populate a tree with transactions from the , e.g. , latest block .
type AddrTransactions = MultiMap Hash Transaction [Transaction]
it 's helpful to make a Merkle Tree foldable
instance Foldable MerkleTree where
foldr f z = foldr f z . root
instance Foldable Branch where
foldr f z (Twig _ (Leaf _ v)) = f v z
foldr f z (Branch _ (Leaf _ v1) (Leaf _ v2)) = f v1 (f v2 z)
foldr f z (Parent _ bb1 bb2) = foldr f (foldr f z (branch bb1)) (branch bb2)
addresses :: MerkleTree Transaction -> AddrTransactions
addresses = MM.fromList pure
. concatMap (uncurry zip . (mapMaybe (prevOut >=> addr) . inputs &&& repeat))
. toList
-
* Y2016.M09.D29.Solution > latestTransactions ~ > lt ~ > length ~ > 2458
* Y2016.M09.D29.Solution > let tree = fromList ( map mkleaf lt )
* Y2016.M09.D29.Solution > let = addresses tree
* Y2016.M09.D29.Solution > head $ MM.toList ~ >
( " 1128iYdsZB4CyV2F8T9bk1MzqRDjs6FeLZ",[TX { lockTime = 0 , version = 1 , ... } ] )
* Y2016.M09.D29.Solution > let sorted = ( compare ` on ` Down . length . snd ) ( MM.toList )
* Y2016.M09.D29.Solution > let ans = head sorted
* Y2016.M09.D29.Solution > fst ans ~ > " 1318wvPUgwkcDVzUyabuvduguhKM6piRfn "
* Y2016.M09.D29.Solution > length $ snd ans ~ > 98
* Y2016.M09.D29.Solution > let bits = map ( second ( maximum . map ( val2BTC . sum . map value . out ) ) ) sorted
* Y2016.M09.D29.Solution > let sortedbits = ( compare ` on ` Down . snd ) bits
* Y2016.M09.D29.Solution > head sortedbits ~ >
( " 13XTjbT68K7S3s1cEPBUs2uohEAjj3AYpv",BTC 416.24 )
-
*Y2016.M09.D29.Solution> latestTransactions ~> lt ~> length ~> 2458
*Y2016.M09.D29.Solution> let tree = fromList (map mkleaf lt)
*Y2016.M09.D29.Solution> let addrs = addresses tree
*Y2016.M09.D29.Solution> head $ MM.toList addrs ~>
("1128iYdsZB4CyV2F8T9bk1MzqRDjs6FeLZ",[TX {lockTime = 0, version = 1, ...}])
*Y2016.M09.D29.Solution> let sorted = sortBy (compare `on` Down . length . snd) (MM.toList addrs)
*Y2016.M09.D29.Solution> let ans = head sorted
*Y2016.M09.D29.Solution> fst ans ~> "1318wvPUgwkcDVzUyabuvduguhKM6piRfn"
*Y2016.M09.D29.Solution> length $ snd ans ~> 98
*Y2016.M09.D29.Solution> let bits = map (second (maximum . map (val2BTC . sum . map value . out))) sorted
*Y2016.M09.D29.Solution> let sortedbits = sortBy (compare `on` Down . snd) bits
*Y2016.M09.D29.Solution> head sortedbits ~>
("13XTjbT68K7S3s1cEPBUs2uohEAjj3AYpv",BTC 416.24)
Now : how do I find only the transactions between one address and another ?
transactionsBetween :: AddrTransactions -> Hash -> Hash -> [Transaction]
transactionsBetween addrs me you =
filter (elem you . mapMaybe addr . out) $ MM.lookup me addrs
-
For a new map , largest address - set is 39
* Y2016.M09.D29.Solution > second length $ head sorted ~ >
( " 1FMJXNWyNkWohjU6r6SMbwnt4b9nHXJUJE",39 )
Huh , some transactions are just between only two parties anyway :
* Y2016.M09.D29.Solution > let x = " 1FQ4SuwadRLnx6fNDvcs4Fy3KiLFkyQF9P " " 1EMs2Acsr6groSFAume73LgE1wzJdz5d3P "
* Y2016.M09.D29.Solution > length x ~ >
... which are all the transactions for that address .
-
For a new map, largest address-set is 39
*Y2016.M09.D29.Solution> second length $ head sorted ~>
("1FMJXNWyNkWohjU6r6SMbwnt4b9nHXJUJE",39)
Huh, some transactions are just between only two parties anyway:
*Y2016.M09.D29.Solution> let x = transactionsBetween addrs "1FQ4SuwadRLnx6fNDvcs4Fy3KiLFkyQF9P" "1EMs2Acsr6groSFAume73LgE1wzJdz5d3P"
*Y2016.M09.D29.Solution> length x ~>
... which are all the transactions for that address.
transactionsFor :: AddrTransactions -> Hash -> LocalTime -> LocalTime
-> [Transaction]
transactionsFor addresses user from to = undefined
|
f6ec50e37787e1e66b051bc0677ab35b2a31dae74f8ddecb923458ce37c369f1 | serokell/haskell-crypto | Public.hs | SPDX - FileCopyrightText : 2020
--
SPDX - License - Identifier : MPL-2.0
# OPTIONS_HADDOCK not - home #
-- ! This module merely re-exports definitions from the corresponding
! module in NaCl and alters the to make it more specific
-- ! to crypto-sodium. So, the docs should be kept more-or-less in sync.
-- | Public-key authenticated encryption.
--
-- It is best to import this module qualified:
--
-- @
-- import qualified Crypto.Sodium.Encrypt.Public as Public
--
-- encrypted = Public.'encrypt' pk sk nonce message
-- decrypted = Public.'decrypt' pk sk nonce encrypted
-- @
--
A box is an abstraction from NaCl . One way to think about it
-- is to imagine that you are putting data into a box protected by
-- the receiver’s public key and signed by your private key. The
-- receive will then be able to “open” it using their private key
-- and your public key.
--
-- Note that this means that you need to exchange your public keys
in advance . It might seem strange at first that the receiver
-- needs to know your public key too, but this is actually very important
-- as otherwise the receiver would not be able to have any guarantees
-- regarding the source or the integrity of the data.
module Crypto.Sodium.Encrypt.Public
(
-- * Keys
PublicKey
, toPublicKey
, SecretKey
, toSecretKey
, keypair
, Seed
, keypairFromSeed
, unsafeKeypairFromSeed
-- * Nonce
, Nonce
, toNonce
-- * Encryption/decryption
, encrypt
, decrypt
) where
import Data.ByteArray (ByteArray, ByteArrayAccess, ScrubbedBytes, withByteArray)
import Data.ByteArray.Sized as Sized (SizedByteArray, alloc, allocRet)
import Data.ByteString (ByteString)
import Data.Functor (void)
import Data.Proxy (Proxy(..))
import System.IO.Unsafe (unsafePerformIO)
import qualified Libsodium as Na
import NaCl.Box
(Nonce, PublicKey, SecretKey, keypair, toNonce, toPublicKey, toSecretKey)
import qualified NaCl.Box as NaCl.Box
-- | Encrypt a message.
--
-- @
encrypted = Public.encrypt pk sk nonce message
-- @
--
* @pk@ is the receiver ’s public key , used for encryption .
-- @sk@ is the sender’s secret key, used for authentication.
--
-- These are generated using 'keypair' and are supposed to be exchanged
-- in advance. Both parties need to know their own secret key and the other’s
-- public key.
--
-- * @nonce@ is an extra noise that ensures that is required for security.
-- See "Crypto.Sodium.Nonce" for how to work with it.
--
-- * @message@ is the data you are encrypting.
--
This function adds authentication data , so if anyone modifies the cyphertext ,
-- 'decrypt' will refuse to decrypt it.
encrypt
:: ( ByteArrayAccess pkBytes, ByteArrayAccess skBytes
, ByteArrayAccess nonceBytes
, ByteArrayAccess ptBytes, ByteArray ctBytes
)
=> PublicKey pkBytes -- ^ Receiver’s public key
-> SecretKey skBytes -- ^ Sender’s secret key
-> Nonce nonceBytes -- ^ Nonce
^ Plaintext message
-> ctBytes
encrypt = NaCl.Box.create
-- | Decrypt a message.
--
-- @
decrypted = Public.decrypt sk pk nonce encrypted
-- @
--
-- * @sk@ is the receiver’s secret key, used for decription.
* @pk@ is the sender ’s public key , used for authentication .
-- * @nonce@ is the same that was used for encryption.
-- * @encrypted@ is the output of 'encrypt'.
--
-- This function will return @Nothing@ if the encrypted message was tampered
-- with after it was encrypted.
decrypt
:: ( ByteArrayAccess skBytes, ByteArrayAccess pkBytes
, ByteArrayAccess nonceBytes
, ByteArray ptBytes, ByteArrayAccess ctBytes
)
=> SecretKey skBytes -- ^ Receiver’s secret key
-> PublicKey pkBytes -- ^ Sender’s public key
-> Nonce nonceBytes -- ^ Nonce
^ Encrypted message ( cyphertext )
-> Maybe ptBytes
decrypt = NaCl.Box.open
-- | Seed for deterministically generating a keypair.
--
In accordance with Libsodium 's documentation , the seed must be of size
@Na . CRYPTO_BOX_SEEDBYTES@.
--
-- This type is parametrised by the actual data type that contains
bytes . This can be , for example , a @ByteString@.
type Seed a = SizedByteArray Na.CRYPTO_BOX_SEEDBYTES a
| Generate a new ' SecretKey ' together with its ' PublicKey ' from a given seed .
keypairFromSeed
:: ByteArrayAccess seed
=> Seed seed
-> IO (PublicKey ByteString, SecretKey ScrubbedBytes)
keypairFromSeed seed = do
allocRet Proxy $ \skPtr ->
alloc $ \pkPtr ->
withByteArray seed $ \sdPtr ->
-- always returns 0, so we don’t check it
void $ Na.crypto_box_seed_keypair pkPtr skPtr sdPtr
| Generate a new ' SecretKey ' together with its ' PublicKey ' from a given seed ,
-- in a pure context.
unsafeKeypairFromSeed
:: ByteArrayAccess seed
=> Seed seed
-> (PublicKey ByteString, SecretKey ScrubbedBytes)
unsafeKeypairFromSeed = unsafePerformIO . keypairFromSeed
| null | https://raw.githubusercontent.com/serokell/haskell-crypto/27e67c4b54ac388cb5ab504ddaf7bbf5ab8df2ae/crypto-sodium/lib/Crypto/Sodium/Encrypt/Public.hs | haskell |
! This module merely re-exports definitions from the corresponding
! to crypto-sodium. So, the docs should be kept more-or-less in sync.
| Public-key authenticated encryption.
It is best to import this module qualified:
@
import qualified Crypto.Sodium.Encrypt.Public as Public
encrypted = Public.'encrypt' pk sk nonce message
decrypted = Public.'decrypt' pk sk nonce encrypted
@
is to imagine that you are putting data into a box protected by
the receiver’s public key and signed by your private key. The
receive will then be able to “open” it using their private key
and your public key.
Note that this means that you need to exchange your public keys
needs to know your public key too, but this is actually very important
as otherwise the receiver would not be able to have any guarantees
regarding the source or the integrity of the data.
* Keys
* Nonce
* Encryption/decryption
| Encrypt a message.
@
@
@sk@ is the sender’s secret key, used for authentication.
These are generated using 'keypair' and are supposed to be exchanged
in advance. Both parties need to know their own secret key and the other’s
public key.
* @nonce@ is an extra noise that ensures that is required for security.
See "Crypto.Sodium.Nonce" for how to work with it.
* @message@ is the data you are encrypting.
'decrypt' will refuse to decrypt it.
^ Receiver’s public key
^ Sender’s secret key
^ Nonce
| Decrypt a message.
@
@
* @sk@ is the receiver’s secret key, used for decription.
* @nonce@ is the same that was used for encryption.
* @encrypted@ is the output of 'encrypt'.
This function will return @Nothing@ if the encrypted message was tampered
with after it was encrypted.
^ Receiver’s secret key
^ Sender’s public key
^ Nonce
| Seed for deterministically generating a keypair.
This type is parametrised by the actual data type that contains
always returns 0, so we don’t check it
in a pure context. | SPDX - FileCopyrightText : 2020
SPDX - License - Identifier : MPL-2.0
# OPTIONS_HADDOCK not - home #
! module in NaCl and alters the to make it more specific
A box is an abstraction from NaCl . One way to think about it
in advance . It might seem strange at first that the receiver
module Crypto.Sodium.Encrypt.Public
(
PublicKey
, toPublicKey
, SecretKey
, toSecretKey
, keypair
, Seed
, keypairFromSeed
, unsafeKeypairFromSeed
, Nonce
, toNonce
, encrypt
, decrypt
) where
import Data.ByteArray (ByteArray, ByteArrayAccess, ScrubbedBytes, withByteArray)
import Data.ByteArray.Sized as Sized (SizedByteArray, alloc, allocRet)
import Data.ByteString (ByteString)
import Data.Functor (void)
import Data.Proxy (Proxy(..))
import System.IO.Unsafe (unsafePerformIO)
import qualified Libsodium as Na
import NaCl.Box
(Nonce, PublicKey, SecretKey, keypair, toNonce, toPublicKey, toSecretKey)
import qualified NaCl.Box as NaCl.Box
encrypted = Public.encrypt pk sk nonce message
* @pk@ is the receiver ’s public key , used for encryption .
This function adds authentication data , so if anyone modifies the cyphertext ,
encrypt
:: ( ByteArrayAccess pkBytes, ByteArrayAccess skBytes
, ByteArrayAccess nonceBytes
, ByteArrayAccess ptBytes, ByteArray ctBytes
)
^ Plaintext message
-> ctBytes
encrypt = NaCl.Box.create
decrypted = Public.decrypt sk pk nonce encrypted
* @pk@ is the sender ’s public key , used for authentication .
decrypt
:: ( ByteArrayAccess skBytes, ByteArrayAccess pkBytes
, ByteArrayAccess nonceBytes
, ByteArray ptBytes, ByteArrayAccess ctBytes
)
^ Encrypted message ( cyphertext )
-> Maybe ptBytes
decrypt = NaCl.Box.open
In accordance with Libsodium 's documentation , the seed must be of size
@Na . CRYPTO_BOX_SEEDBYTES@.
bytes . This can be , for example , a @ByteString@.
type Seed a = SizedByteArray Na.CRYPTO_BOX_SEEDBYTES a
| Generate a new ' SecretKey ' together with its ' PublicKey ' from a given seed .
keypairFromSeed
:: ByteArrayAccess seed
=> Seed seed
-> IO (PublicKey ByteString, SecretKey ScrubbedBytes)
keypairFromSeed seed = do
allocRet Proxy $ \skPtr ->
alloc $ \pkPtr ->
withByteArray seed $ \sdPtr ->
void $ Na.crypto_box_seed_keypair pkPtr skPtr sdPtr
| Generate a new ' SecretKey ' together with its ' PublicKey ' from a given seed ,
unsafeKeypairFromSeed
:: ByteArrayAccess seed
=> Seed seed
-> (PublicKey ByteString, SecretKey ScrubbedBytes)
unsafeKeypairFromSeed = unsafePerformIO . keypairFromSeed
|
fcc838e9b599ed8ead1aae516af09772cbfb196e3b596b5de7f52360b133504c | vonli/Ext2-for-movitz | defstruct.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2001 - 2004 ,
Department of Computer Science , University of Tromso , Norway
;;;;
;;;; Filename: defstruct.lisp
;;;; Description:
Author : < >
Created at : Mon Jan 22 13:10:59 2001
;;;; Distribution: See the accompanying file COPYING.
;;;;
$ I d : defstruct.lisp , v 1.17 2006/04/03 21:22:39 ffjeld Exp $
;;;;
;;;;------------------------------------------------------------------
(require :muerte/basic-macros)
(require :muerte/los-closette)
(provide :muerte/defstruct)
(in-package muerte)
(defun structure-object-length (object)
(check-type object structure-object)
(memref object -4 :type :unsigned-byte14))
(defun structure-object-class (x)
(memref x -6 :index 1))
(defun copy-structure (object)
(%shallow-copy-object object (+ 2 (structure-object-length object))))
(defun struct-predicate-prototype (obj)
"Prototype function for predicates of user-defined struct.
Parameters: struct-name."
(with-inline-assembly (:returns :boolean-zf=1)
(:compile-form (:result-mode :eax) obj)
(:leal (:eax #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz 'fail)
(:cmpb #.(movitz:tag :defstruct) (:eax #.movitz:+other-type-offset+))
(:jne 'fail)
(:load-constant struct-class :ebx)
(:cmpl :ebx (:eax (:offset movitz-struct class)))
fail))
(defun structure-ref (object slot-number)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
;; type test
(:compile-form (:result-mode :eax) object)
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne '(:sub-program (type-error) (:int 66)))
(:cmpb ,(movitz:tag :defstruct) (:eax ,movitz:+other-type-offset+))
(:jne '(:sub-program (type-error) (:int 66)))
;; type test passed, read slot
,@(if (= 4 movitz::+movitz-fixnum-factor+)
`((:compile-form (:result-mode :ecx) slot-number)
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl (:eax :ecx (:offset movitz-struct slot0))
:eax))
`((:compile-form (:result-mode :untagged-fixnum-ecx) slot-number)
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl (:eax (:ecx 4) (:offset movitz-struct slot0)) :eax))))))
(do-it)))
(defun (setf structure-ref) (value object slot-number)
(macrolet
((do-it ()
(assert (= 4 movitz::+movitz-fixnum-factor+))
`(with-inline-assembly (:returns :eax)
;; type test
(:compile-two-forms (:eax :ebx) object slot-number)
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne '(:sub-program (type-error) (:int 66)))
(:cmpb ,(movitz:tag :defstruct) (:eax ,movitz:+other-type-offset+))
(:jne '(:sub-program (type-error) (:int 66)))
(:movzxw (:eax (:offset movitz-struct length)) :ecx)
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz '(:sub-program (not-fixnum) (:movl :ebx :eax) (:int 64)))
(:cmpl :ecx :ebx)
(:jae '(:sub-program (out-of-range) (:int 65)))
;; type test passed, write slot
(:compile-form (:result-mode :edx) value)
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :edx (:eax :ebx (:offset movitz-struct slot0))))))
(do-it)))
(defun struct-accessor-prototype (object)
"Parameters: struct-name, slot-number."
(with-inline-assembly (:returns :eax)
;; type test
(:compile-form (:result-mode :eax) object)
(:leal (:eax #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne '(:sub-program (type-error) (:int 66)))
(:cmpb #.(movitz:tag :defstruct) (:eax #.movitz:+other-type-offset+))
(:jne '(:sub-program (type-error) (:int 66)))
(:load-constant struct-name :ebx)
(: : ebx (: eax # .(bt : slot - offset ' movitz::movitz - struct ' movitz::name ) ) )
(: ' (: sub - program ( type - error ) (: int 66 ) ) )
;; type test passed, read slot
(:load-constant slot-number :ecx)
(: # : ecx )
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl (:eax (:ecx 1) #.(bt:slot-offset 'movitz::movitz-struct 'movitz::slot0))
:eax)))
(defun (setf struct-accessor-prototype) (value obj)
"Parameters: struct-name, slot-number."
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) value obj)
;; type test
(:leal (:ebx #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (type-error) (:int 66)))
(:cmpb #.(movitz:tag :defstruct) (:ebx #.movitz:+other-type-offset+))
(:jne '(:sub-program (type-error) (:int 66)))
(:load-constant struct-name :ecx)
(: : ecx (: ebx : slot - offset ' movitz::movitz - struct ' movitz::name ) ) )
(: ' (: sub - program ( type - error ) (: int 66 ) ) )
;; type test passed, write slot
(:load-constant slot-number :ecx)
(: # : ecx )
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx (:ecx 1) #.(bt:slot-offset 'movitz::movitz-struct 'movitz::slot0)))))
(defun list-struct-accessor-prototype (s)
(nth 'slot-number s))
(defun (setf list-struct-accessor-prototype) (value s)
(setf (nth 'slot-number s) value))
(defmacro defstruct (name-and-options &optional documentation &rest slot-descriptions)
(unless (stringp documentation)
(push documentation slot-descriptions)
(setf documentation nil))
(let ((struct-name (if (symbolp name-and-options)
name-and-options
(car name-and-options))))
(flet ((parse-option (option collector)
(etypecase option
(symbol
(ecase option
(:conc-name (push "" (getf collector :conc-name)))
(:constructor (push (intern (concatenate 'string (string 'make-) (string struct-name)))
(getf collector :constructor)))
(:copier) ; do default
(:predicate) ; do default
(:named (push t (getf collector :named)))))
((cons symbol null)
(ecase (car option)
(:conc-name (push "" (getf collector :conc-name)))
(:constructor (push (intern (concatenate 'string
(string 'make-) (string struct-name)))
(getf collector :constructor)))
(:copier) ; do default
(:predicate) ; do default
(:named (push t (getf collector :named)))
(:print-object)
(:print-function)))
((cons symbol (cons * null))
(let ((parameter (second option)))
(ecase (car option)
(:superclass (push parameter (getf collector :superclass)))
(:conc-name (push (string (or parameter ""))
(getf collector :conc-name)))
(:constructor (push parameter (getf collector :constructor)))
(:copier (push parameter (getf collector :constructor)))
(:predicate (push parameter (getf collector :predicate)))
(:type (push parameter (getf collector :type)))
(:initial-offset (push parameter (getf collector :initial-offset)))
(:print-object (push parameter (getf collector :print-object)))
(:print-function (push parameter (getf collector :print-function))))))
((cons symbol (cons * cons))
(ecase (car option)
(:include (push (cdr option) (getf collector :include)))
(:constructor
(assert (= 3 (length option)))
(push (cons (second option) (third option))
(getf collector :constructor))))))
collector))
(let ((options nil))
(when (listp name-and-options)
(loop for option in (cdr name-and-options)
do (setf options (parse-option option options))))
(macrolet ((default ((option &optional (max-values 1000000)) default-form)
`(if (not (getf options ,option))
(push ,default-form (getf options ,option))
(assert (<= 1 (length (getf options ,option)) ,max-values) ()
"Option ~S given too many times." ,option))))
(default (:type 1) 'class-struct)
(default (:superclass 1) 'structure-object)
(default (:named 1) nil)
(default (:conc-name 1)
(concatenate 'string (string struct-name) (string #\-)))
(default (:constructor)
(intern (concatenate 'string (string 'make-) (string struct-name))))
(default (:predicate 1)
(intern (concatenate 'string (string struct-name) (string '-p))))
(default (:copier)
(intern (concatenate 'string (string 'copy-) (string struct-name)))))
(let* ((struct-type (first (getf options :type)))
(superclass (first (getf options :superclass)))
(struct-named (first (getf options :named)))
(conc-name (first (getf options :conc-name)))
(predicate-name (first (getf options :predicate)))
(standard-name-and-options (if (not (consp name-and-options))
name-and-options
(remove :superclass name-and-options
:key (lambda (x)
(when (consp x) (car x))))))
(canonical-slot-descriptions
(mapcar #'(lambda (d)
"(<slot-name> <init-form> <type> <read-only-p> <initarg>)"
(if (symbolp d)
(list d nil nil nil (intern (symbol-name d) :keyword))
(destructuring-bind (n &optional i &key type read-only)
d
(list n i type read-only (intern (symbol-name n) :keyword)))))
slot-descriptions))
(slot-names (mapcar #'car canonical-slot-descriptions))
(key-lambda (mapcar #'(lambda (d) (list (first d) (second d)))
canonical-slot-descriptions)))
(ecase struct-type
(class-struct
`(progn
(eval-when (:compile-toplevel)
(setf (gethash '(:translate-when :eval ,struct-name :cl :muerte.cl)
(movitz::image-struct-slot-descriptions movitz:*image*))
'(:translate-when :eval ,slot-descriptions :cl :muerte.cl))
(defstruct (:translate-when :eval ,standard-name-and-options :cl :muerte.cl)
. (:translate-when :eval ,slot-names :cl :muerte.cl)))
(defclass ,struct-name (,superclass) ()
(:metaclass structure-class)
(:slots ,(loop for (name init-form type read-only init-arg)
in canonical-slot-descriptions
as location upfrom 0
collect (movitz-make-instance 'structure-slot-definition
:name name
:initarg init-arg
:initform init-form
:type type
:readonly read-only
:location location))))
,@(loop for copier in (getf options :copier)
if (and copier (symbolp copier))
collect
`(defun ,copier (x)
(copy-structure x)))
,@(loop for constructor in (getf options :constructor)
if (and constructor (symbolp constructor))
collect
`(defun ,constructor (&rest args) ; &key ,@key-lambda)
(declare (dynamic-extent args))
(apply 'make-structure ',struct-name args))
else if (and constructor (listp constructor))
collect
(let* ((boa-constructor (car constructor))
(boa-lambda-list (cdr constructor))
(boa-variables (movitz::list-normal-lambda-list-variables boa-lambda-list)))
`(defun ,boa-constructor ,boa-lambda-list
(let ((class (compile-time-find-class ,struct-name)))
(with-allocation-assembly (,(+ 2 (length slot-names))
:fixed-size-p t
:object-register :eax)
(:movl ,(dpb (length slot-names)
(byte 18 14)
(movitz:tag :defstruct))
(:eax (:offset movitz-struct type)))
(:load-lexical (:lexical-binding class) :ebx)
(:movl :ebx (:eax (:offset movitz-struct class)))
,@(loop for slot-name in slot-names as i upfrom 0
if (member slot-name boa-variables)
append
`((:load-lexical (:lexical-binding ,slot-name) :ebx)
(:movl :ebx (:eax (:offset movitz-struct slot0)
,(* 4 i))))
else append
`((:movl :edi (:eax (:offset movitz-struct slot0)
,(* 4 i)))))
,@(when (oddp (length slot-names))
`((:movl :edi (:eax (:offset movitz-struct slot0)
,(* 4 (length slot-names))))))))))
else if constructor
do (error "Don't know how to make class-struct constructor: ~S" constructor))
,(when predicate-name
`(defun-by-proto ,predicate-name struct-predicate-prototype
(struct-class (:movitz-find-class ,struct-name))))
,@(loop for (slot-name nil nil read-only-p) in canonical-slot-descriptions
as accessor-name = (intern (concatenate 'string conc-name (string slot-name))
(movitz::symbol-package-fix-cl struct-name))
as slot-number upfrom 0
unless read-only-p
collect
`(defun-by-proto (setf ,accessor-name) (setf struct-accessor-prototype)
(struct-name ,struct-name)
(slot-number ,slot-number))
collect
`(defun-by-proto ,accessor-name struct-accessor-prototype
(struct-name ,struct-name)
(slot-number ,slot-number)))
',struct-name))
(list
`(progn
,@(if struct-named
(append
(loop for constructor in (getf options :constructor)
if (symbolp constructor)
collect
`(defun ,constructor (&key ,@key-lambda)
(list ',struct-name ,@(mapcar #'car key-lambda)))
else do (error "don't know how to make constructor: ~S" constructor))
(when predicate-name
`((defun ,predicate-name (x)
(and (consp x) (eq ',struct-name (car x)))))))
(loop for constructor in (getf options :constructor)
if (symbolp constructor)
collect
`(defun ,constructor (&key ,@key-lambda)
(list ,@(mapcar #'car key-lambda)))
else do (error "don't know how to make constructor: ~S" constructor)))
,@(loop for (slot-name nil nil read-only-p) in canonical-slot-descriptions
as accessor-name = (intern (concatenate 'string conc-name (string slot-name))
(movitz::symbol-package-fix-cl struct-name))
as slot-number upfrom (if struct-named 1 0)
unless read-only-p
collect
`(defun-by-proto (setf ,accessor-name) (setf list-struct-accessor-prototype)
(slot-number ,slot-number))
collect
`(defun-by-proto ,accessor-name list-struct-accessor-prototype
(slot-number ,slot-number)))
',struct-name))
))))))
| null | https://raw.githubusercontent.com/vonli/Ext2-for-movitz/81b6f8e165de3e1ea9cc7d2035b9259af83a6d26/losp/muerte/defstruct.lisp | lisp | ------------------------------------------------------------------
Filename: defstruct.lisp
Description:
Distribution: See the accompanying file COPYING.
------------------------------------------------------------------
type test
type test passed, read slot
type test
type test passed, write slot
type test
type test passed, read slot
type test
type test passed, write slot
do default
do default
do default
do default
&key ,@key-lambda) | Copyright ( C ) 2001 - 2004 ,
Department of Computer Science , University of Tromso , Norway
Author : < >
Created at : Mon Jan 22 13:10:59 2001
$ I d : defstruct.lisp , v 1.17 2006/04/03 21:22:39 ffjeld Exp $
(require :muerte/basic-macros)
(require :muerte/los-closette)
(provide :muerte/defstruct)
(in-package muerte)
(defun structure-object-length (object)
(check-type object structure-object)
(memref object -4 :type :unsigned-byte14))
(defun structure-object-class (x)
(memref x -6 :index 1))
(defun copy-structure (object)
(%shallow-copy-object object (+ 2 (structure-object-length object))))
(defun struct-predicate-prototype (obj)
"Prototype function for predicates of user-defined struct.
Parameters: struct-name."
(with-inline-assembly (:returns :boolean-zf=1)
(:compile-form (:result-mode :eax) obj)
(:leal (:eax #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz 'fail)
(:cmpb #.(movitz:tag :defstruct) (:eax #.movitz:+other-type-offset+))
(:jne 'fail)
(:load-constant struct-class :ebx)
(:cmpl :ebx (:eax (:offset movitz-struct class)))
fail))
(defun structure-ref (object slot-number)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) object)
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne '(:sub-program (type-error) (:int 66)))
(:cmpb ,(movitz:tag :defstruct) (:eax ,movitz:+other-type-offset+))
(:jne '(:sub-program (type-error) (:int 66)))
,@(if (= 4 movitz::+movitz-fixnum-factor+)
`((:compile-form (:result-mode :ecx) slot-number)
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl (:eax :ecx (:offset movitz-struct slot0))
:eax))
`((:compile-form (:result-mode :untagged-fixnum-ecx) slot-number)
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl (:eax (:ecx 4) (:offset movitz-struct slot0)) :eax))))))
(do-it)))
(defun (setf structure-ref) (value object slot-number)
(macrolet
((do-it ()
(assert (= 4 movitz::+movitz-fixnum-factor+))
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) object slot-number)
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne '(:sub-program (type-error) (:int 66)))
(:cmpb ,(movitz:tag :defstruct) (:eax ,movitz:+other-type-offset+))
(:jne '(:sub-program (type-error) (:int 66)))
(:movzxw (:eax (:offset movitz-struct length)) :ecx)
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz '(:sub-program (not-fixnum) (:movl :ebx :eax) (:int 64)))
(:cmpl :ecx :ebx)
(:jae '(:sub-program (out-of-range) (:int 65)))
(:compile-form (:result-mode :edx) value)
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :edx (:eax :ebx (:offset movitz-struct slot0))))))
(do-it)))
(defun struct-accessor-prototype (object)
"Parameters: struct-name, slot-number."
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) object)
(:leal (:eax #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne '(:sub-program (type-error) (:int 66)))
(:cmpb #.(movitz:tag :defstruct) (:eax #.movitz:+other-type-offset+))
(:jne '(:sub-program (type-error) (:int 66)))
(:load-constant struct-name :ebx)
(: : ebx (: eax # .(bt : slot - offset ' movitz::movitz - struct ' movitz::name ) ) )
(: ' (: sub - program ( type - error ) (: int 66 ) ) )
(:load-constant slot-number :ecx)
(: # : ecx )
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl (:eax (:ecx 1) #.(bt:slot-offset 'movitz::movitz-struct 'movitz::slot0))
:eax)))
(defun (setf struct-accessor-prototype) (value obj)
"Parameters: struct-name, slot-number."
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) value obj)
(:leal (:ebx #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (type-error) (:int 66)))
(:cmpb #.(movitz:tag :defstruct) (:ebx #.movitz:+other-type-offset+))
(:jne '(:sub-program (type-error) (:int 66)))
(:load-constant struct-name :ecx)
(: : ecx (: ebx : slot - offset ' movitz::movitz - struct ' movitz::name ) ) )
(: ' (: sub - program ( type - error ) (: int 66 ) ) )
(:load-constant slot-number :ecx)
(: # : ecx )
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx (:ecx 1) #.(bt:slot-offset 'movitz::movitz-struct 'movitz::slot0)))))
(defun list-struct-accessor-prototype (s)
(nth 'slot-number s))
(defun (setf list-struct-accessor-prototype) (value s)
(setf (nth 'slot-number s) value))
(defmacro defstruct (name-and-options &optional documentation &rest slot-descriptions)
(unless (stringp documentation)
(push documentation slot-descriptions)
(setf documentation nil))
(let ((struct-name (if (symbolp name-and-options)
name-and-options
(car name-and-options))))
(flet ((parse-option (option collector)
(etypecase option
(symbol
(ecase option
(:conc-name (push "" (getf collector :conc-name)))
(:constructor (push (intern (concatenate 'string (string 'make-) (string struct-name)))
(getf collector :constructor)))
(:named (push t (getf collector :named)))))
((cons symbol null)
(ecase (car option)
(:conc-name (push "" (getf collector :conc-name)))
(:constructor (push (intern (concatenate 'string
(string 'make-) (string struct-name)))
(getf collector :constructor)))
(:named (push t (getf collector :named)))
(:print-object)
(:print-function)))
((cons symbol (cons * null))
(let ((parameter (second option)))
(ecase (car option)
(:superclass (push parameter (getf collector :superclass)))
(:conc-name (push (string (or parameter ""))
(getf collector :conc-name)))
(:constructor (push parameter (getf collector :constructor)))
(:copier (push parameter (getf collector :constructor)))
(:predicate (push parameter (getf collector :predicate)))
(:type (push parameter (getf collector :type)))
(:initial-offset (push parameter (getf collector :initial-offset)))
(:print-object (push parameter (getf collector :print-object)))
(:print-function (push parameter (getf collector :print-function))))))
((cons symbol (cons * cons))
(ecase (car option)
(:include (push (cdr option) (getf collector :include)))
(:constructor
(assert (= 3 (length option)))
(push (cons (second option) (third option))
(getf collector :constructor))))))
collector))
(let ((options nil))
(when (listp name-and-options)
(loop for option in (cdr name-and-options)
do (setf options (parse-option option options))))
(macrolet ((default ((option &optional (max-values 1000000)) default-form)
`(if (not (getf options ,option))
(push ,default-form (getf options ,option))
(assert (<= 1 (length (getf options ,option)) ,max-values) ()
"Option ~S given too many times." ,option))))
(default (:type 1) 'class-struct)
(default (:superclass 1) 'structure-object)
(default (:named 1) nil)
(default (:conc-name 1)
(concatenate 'string (string struct-name) (string #\-)))
(default (:constructor)
(intern (concatenate 'string (string 'make-) (string struct-name))))
(default (:predicate 1)
(intern (concatenate 'string (string struct-name) (string '-p))))
(default (:copier)
(intern (concatenate 'string (string 'copy-) (string struct-name)))))
(let* ((struct-type (first (getf options :type)))
(superclass (first (getf options :superclass)))
(struct-named (first (getf options :named)))
(conc-name (first (getf options :conc-name)))
(predicate-name (first (getf options :predicate)))
(standard-name-and-options (if (not (consp name-and-options))
name-and-options
(remove :superclass name-and-options
:key (lambda (x)
(when (consp x) (car x))))))
(canonical-slot-descriptions
(mapcar #'(lambda (d)
"(<slot-name> <init-form> <type> <read-only-p> <initarg>)"
(if (symbolp d)
(list d nil nil nil (intern (symbol-name d) :keyword))
(destructuring-bind (n &optional i &key type read-only)
d
(list n i type read-only (intern (symbol-name n) :keyword)))))
slot-descriptions))
(slot-names (mapcar #'car canonical-slot-descriptions))
(key-lambda (mapcar #'(lambda (d) (list (first d) (second d)))
canonical-slot-descriptions)))
(ecase struct-type
(class-struct
`(progn
(eval-when (:compile-toplevel)
(setf (gethash '(:translate-when :eval ,struct-name :cl :muerte.cl)
(movitz::image-struct-slot-descriptions movitz:*image*))
'(:translate-when :eval ,slot-descriptions :cl :muerte.cl))
(defstruct (:translate-when :eval ,standard-name-and-options :cl :muerte.cl)
. (:translate-when :eval ,slot-names :cl :muerte.cl)))
(defclass ,struct-name (,superclass) ()
(:metaclass structure-class)
(:slots ,(loop for (name init-form type read-only init-arg)
in canonical-slot-descriptions
as location upfrom 0
collect (movitz-make-instance 'structure-slot-definition
:name name
:initarg init-arg
:initform init-form
:type type
:readonly read-only
:location location))))
,@(loop for copier in (getf options :copier)
if (and copier (symbolp copier))
collect
`(defun ,copier (x)
(copy-structure x)))
,@(loop for constructor in (getf options :constructor)
if (and constructor (symbolp constructor))
collect
(declare (dynamic-extent args))
(apply 'make-structure ',struct-name args))
else if (and constructor (listp constructor))
collect
(let* ((boa-constructor (car constructor))
(boa-lambda-list (cdr constructor))
(boa-variables (movitz::list-normal-lambda-list-variables boa-lambda-list)))
`(defun ,boa-constructor ,boa-lambda-list
(let ((class (compile-time-find-class ,struct-name)))
(with-allocation-assembly (,(+ 2 (length slot-names))
:fixed-size-p t
:object-register :eax)
(:movl ,(dpb (length slot-names)
(byte 18 14)
(movitz:tag :defstruct))
(:eax (:offset movitz-struct type)))
(:load-lexical (:lexical-binding class) :ebx)
(:movl :ebx (:eax (:offset movitz-struct class)))
,@(loop for slot-name in slot-names as i upfrom 0
if (member slot-name boa-variables)
append
`((:load-lexical (:lexical-binding ,slot-name) :ebx)
(:movl :ebx (:eax (:offset movitz-struct slot0)
,(* 4 i))))
else append
`((:movl :edi (:eax (:offset movitz-struct slot0)
,(* 4 i)))))
,@(when (oddp (length slot-names))
`((:movl :edi (:eax (:offset movitz-struct slot0)
,(* 4 (length slot-names))))))))))
else if constructor
do (error "Don't know how to make class-struct constructor: ~S" constructor))
,(when predicate-name
`(defun-by-proto ,predicate-name struct-predicate-prototype
(struct-class (:movitz-find-class ,struct-name))))
,@(loop for (slot-name nil nil read-only-p) in canonical-slot-descriptions
as accessor-name = (intern (concatenate 'string conc-name (string slot-name))
(movitz::symbol-package-fix-cl struct-name))
as slot-number upfrom 0
unless read-only-p
collect
`(defun-by-proto (setf ,accessor-name) (setf struct-accessor-prototype)
(struct-name ,struct-name)
(slot-number ,slot-number))
collect
`(defun-by-proto ,accessor-name struct-accessor-prototype
(struct-name ,struct-name)
(slot-number ,slot-number)))
',struct-name))
(list
`(progn
,@(if struct-named
(append
(loop for constructor in (getf options :constructor)
if (symbolp constructor)
collect
`(defun ,constructor (&key ,@key-lambda)
(list ',struct-name ,@(mapcar #'car key-lambda)))
else do (error "don't know how to make constructor: ~S" constructor))
(when predicate-name
`((defun ,predicate-name (x)
(and (consp x) (eq ',struct-name (car x)))))))
(loop for constructor in (getf options :constructor)
if (symbolp constructor)
collect
`(defun ,constructor (&key ,@key-lambda)
(list ,@(mapcar #'car key-lambda)))
else do (error "don't know how to make constructor: ~S" constructor)))
,@(loop for (slot-name nil nil read-only-p) in canonical-slot-descriptions
as accessor-name = (intern (concatenate 'string conc-name (string slot-name))
(movitz::symbol-package-fix-cl struct-name))
as slot-number upfrom (if struct-named 1 0)
unless read-only-p
collect
`(defun-by-proto (setf ,accessor-name) (setf list-struct-accessor-prototype)
(slot-number ,slot-number))
collect
`(defun-by-proto ,accessor-name list-struct-accessor-prototype
(slot-number ,slot-number)))
',struct-name))
))))))
|
a7c42e26f93c7da2e5288c08e1ec687a833e35b49accaa67002de2bb34d288ff | mkoppmann/eselsohr | Assert.hs | | We use @hspec@ testing framework and it does n't support monad transformers .
At this moment there 's no testing framework that supports monad transformers . So
we need to pass @AppEnv@ manually to every function .
All functions take ` AppEnv ` as last argument . Like this one :
@
satisfies : : App a - > ( a - > Bool ) - > AppEnv - > Expectation
@
Because of that , there 're multiple ways to write tests :
@
1 . satisfies action isJust env
2 . ( action ` satisfies ` isJust ) env
3 . action ` satisfies ` isJust $ env
4 . env & action ` satisfies ` isJust
@
We can go even further and introduce fancy operators , so this code can be
written in more concise way . But this is TBD .
@
env & action @ ? isJust
@
At this moment there's no testing framework that supports monad transformers. So
we need to pass @AppEnv@ manually to every function.
All functions take `AppEnv` as last argument. Like this one:
@
satisfies :: App a -> (a -> Bool) -> AppEnv -> Expectation
@
Because of that, there're multiple ways to write tests:
@
1. satisfies action isJust env
2. (action `satisfies` isJust) env
3. action `satisfies` isJust $ env
4. env & action `satisfies` isJust
@
We can go even further and introduce fancy operators, so this code can be
written in more concise way. But this is TBD.
@
env & action @? isJust
@
-}
module Test.Assert
( succeeds
, satisfies
, failsWith
, redirects
, equals
) where
import Test.Hspec
( Expectation
, expectationFailure
, shouldBe
, shouldSatisfy
)
import Lib.Domain.Error
( AppErrorType
, isRedirect
)
import Lib.Infra.Error (AppError (..))
import Lib.Infra.Monad
( App
, AppEnv
, runAppAsIO
)
-- | Checks that given action runs successfully.
succeeds :: (Show a) => App a -> AppEnv -> Expectation
succeeds = (`satisfies` const True)
-- | Checks whether return result of the action satisfies given predicate.
satisfies :: (Show a) => App a -> (a -> Bool) -> AppEnv -> Expectation
satisfies app p env =
runAppAsIO env app >>= \case
Left e -> expectationFailure $ "Expected 'Success' but got: " <> show e
Right a -> a `shouldSatisfy` p
-- | Checks whether action fails and returns given error.
failsWith :: (Show a) => App a -> AppErrorType -> AppEnv -> Expectation
failsWith app err env =
runAppAsIO env app >>= \case
Left AppError{..} -> appErrorType `shouldBe` err
Right a -> expectationFailure $ "Expected 'Failure' with: " <> show err <> " but got: " <> show a
-- | Checks whether action issues a redirect.
redirects :: (Show a) => App a -> AppEnv -> Expectation
redirects app env =
runAppAsIO env app >>= \case
Left AppError{..} -> isRedirect appErrorType `shouldBe` True
Right a -> expectationFailure $ "Expected redirect but got: " <> show a
-- | Checks whether action returns expected value.
equals :: (Show a, Eq a) => App a -> a -> AppEnv -> Expectation
equals app v env =
runAppAsIO env app >>= \case
Right a -> a `shouldBe` v
Left e -> expectationFailure $ "Expected 'Success' but got: " <> show e
| null | https://raw.githubusercontent.com/mkoppmann/eselsohr/3bb8609199c1dfda94935e6dde0c46fc429de84e/test/Test/Assert.hs | haskell | | Checks that given action runs successfully.
| Checks whether return result of the action satisfies given predicate.
| Checks whether action fails and returns given error.
| Checks whether action issues a redirect.
| Checks whether action returns expected value. | | We use @hspec@ testing framework and it does n't support monad transformers .
At this moment there 's no testing framework that supports monad transformers . So
we need to pass @AppEnv@ manually to every function .
All functions take ` AppEnv ` as last argument . Like this one :
@
satisfies : : App a - > ( a - > Bool ) - > AppEnv - > Expectation
@
Because of that , there 're multiple ways to write tests :
@
1 . satisfies action isJust env
2 . ( action ` satisfies ` isJust ) env
3 . action ` satisfies ` isJust $ env
4 . env & action ` satisfies ` isJust
@
We can go even further and introduce fancy operators , so this code can be
written in more concise way . But this is TBD .
@
env & action @ ? isJust
@
At this moment there's no testing framework that supports monad transformers. So
we need to pass @AppEnv@ manually to every function.
All functions take `AppEnv` as last argument. Like this one:
@
satisfies :: App a -> (a -> Bool) -> AppEnv -> Expectation
@
Because of that, there're multiple ways to write tests:
@
1. satisfies action isJust env
2. (action `satisfies` isJust) env
3. action `satisfies` isJust $ env
4. env & action `satisfies` isJust
@
We can go even further and introduce fancy operators, so this code can be
written in more concise way. But this is TBD.
@
env & action @? isJust
@
-}
module Test.Assert
( succeeds
, satisfies
, failsWith
, redirects
, equals
) where
import Test.Hspec
( Expectation
, expectationFailure
, shouldBe
, shouldSatisfy
)
import Lib.Domain.Error
( AppErrorType
, isRedirect
)
import Lib.Infra.Error (AppError (..))
import Lib.Infra.Monad
( App
, AppEnv
, runAppAsIO
)
succeeds :: (Show a) => App a -> AppEnv -> Expectation
succeeds = (`satisfies` const True)
satisfies :: (Show a) => App a -> (a -> Bool) -> AppEnv -> Expectation
satisfies app p env =
runAppAsIO env app >>= \case
Left e -> expectationFailure $ "Expected 'Success' but got: " <> show e
Right a -> a `shouldSatisfy` p
failsWith :: (Show a) => App a -> AppErrorType -> AppEnv -> Expectation
failsWith app err env =
runAppAsIO env app >>= \case
Left AppError{..} -> appErrorType `shouldBe` err
Right a -> expectationFailure $ "Expected 'Failure' with: " <> show err <> " but got: " <> show a
redirects :: (Show a) => App a -> AppEnv -> Expectation
redirects app env =
runAppAsIO env app >>= \case
Left AppError{..} -> isRedirect appErrorType `shouldBe` True
Right a -> expectationFailure $ "Expected redirect but got: " <> show a
equals :: (Show a, Eq a) => App a -> a -> AppEnv -> Expectation
equals app v env =
runAppAsIO env app >>= \case
Right a -> a `shouldBe` v
Left e -> expectationFailure $ "Expected 'Success' but got: " <> show e
|
b51539d7d5f4e3530991a5286717a72333740230438dde8d75446fea66991dbb | goblint/analyzer | fileDomain.ml | open Prelude
module D = LvalMapDomain
module Val =
struct
type mode = Read | Write [@@deriving eq, ord, hash]
type s = Open of string*mode | Closed | Error [@@deriving eq, ord, hash]
let name = "File handles"
let var_state = Closed
let string_of_mode = function Read -> "Read" | Write -> "Write"
let string_of_state = function
| Open(filename, m) -> "open("^filename^", "^string_of_mode m^")"
| Closed -> "closed"
| Error -> "error"
(* properties of records (e.g. used by Dom.warn_each) *)
let opened s = s <> Closed && s <> Error
let closed s = s = Closed
let writable s = match s with Open((_,Write)) -> true | _ -> false
end
module Dom =
struct
include D.Domain (D.Value (Val))
(* returns a tuple (thunk, result) *)
let report_ ?(neg=false) k p msg m =
let f ?(may=false) msg =
let f () = warn ~may msg in
f, if may then `May true else `Must true in
let mf = (fun () -> ()), `Must false in
if mem k m then
let p = if neg then not % p else p in
let v = find' k m in
if V.must p v then f msg (* must *)
else if V.may p v then f ~may:true msg (* may *)
else mf (* none *)
else if neg then f msg else mf
let report ?(neg=false) k p msg m = (fst (report_ ~neg k p msg m)) () (* evaluate thunk *)
let reports k xs m =
let uncurry (neg, p, msg) = report_ ~neg:neg k p msg m in
let f result x = if snd (uncurry x) = result then Some (fst (uncurry x)) else None in
let must_true = BatList.filter_map (f (`Must true)) xs in
let may_true = BatList.filter_map (f (`May true)) xs in
output first must and first may
if must_true <> [] then (List.hd must_true) ();
if may_true <> [] then (List.hd may_true) ()
(* handling state *)
let opened r = V.state r |> Val.opened
let closed r = V.state r |> Val.closed
let writable r = V.state r |> Val.writable
let fopen k loc filename mode m =
if is_unknown k m then m else
let mode = match String.lowercase_ascii mode with "r" -> Val.Read | _ -> Val.Write in
let v = V.make k loc (Val.Open(filename, mode)) in
add' k v m
let fclose k loc m =
if is_unknown k m then m else
let v = V.make k loc Val.Closed in
change k v m
let error k m =
if is_unknown k m then m else
let loc = if mem k m then find' k m |> V.split |> snd |> Set.choose |> V.loc else [] in
let v = V.make k loc Val.Error in
change k v m
let success k m =
if is_unknown k m then m else
match find_option k m with
| Some v when V.may (Val.opened%V.state) v && V.may (V.in_state Val.Error) v ->
change k (V.filter (Val.opened%V.state) v) m (* TODO what about must-set? *)
| _ -> m
end
| null | https://raw.githubusercontent.com/goblint/analyzer/bd6b944afcfe98af8ff1791835c919e252a0b72b/src/cdomains/fileDomain.ml | ocaml | properties of records (e.g. used by Dom.warn_each)
returns a tuple (thunk, result)
must
may
none
evaluate thunk
handling state
TODO what about must-set? | open Prelude
module D = LvalMapDomain
module Val =
struct
type mode = Read | Write [@@deriving eq, ord, hash]
type s = Open of string*mode | Closed | Error [@@deriving eq, ord, hash]
let name = "File handles"
let var_state = Closed
let string_of_mode = function Read -> "Read" | Write -> "Write"
let string_of_state = function
| Open(filename, m) -> "open("^filename^", "^string_of_mode m^")"
| Closed -> "closed"
| Error -> "error"
let opened s = s <> Closed && s <> Error
let closed s = s = Closed
let writable s = match s with Open((_,Write)) -> true | _ -> false
end
module Dom =
struct
include D.Domain (D.Value (Val))
let report_ ?(neg=false) k p msg m =
let f ?(may=false) msg =
let f () = warn ~may msg in
f, if may then `May true else `Must true in
let mf = (fun () -> ()), `Must false in
if mem k m then
let p = if neg then not % p else p in
let v = find' k m in
else if neg then f msg else mf
let reports k xs m =
let uncurry (neg, p, msg) = report_ ~neg:neg k p msg m in
let f result x = if snd (uncurry x) = result then Some (fst (uncurry x)) else None in
let must_true = BatList.filter_map (f (`Must true)) xs in
let may_true = BatList.filter_map (f (`May true)) xs in
output first must and first may
if must_true <> [] then (List.hd must_true) ();
if may_true <> [] then (List.hd may_true) ()
let opened r = V.state r |> Val.opened
let closed r = V.state r |> Val.closed
let writable r = V.state r |> Val.writable
let fopen k loc filename mode m =
if is_unknown k m then m else
let mode = match String.lowercase_ascii mode with "r" -> Val.Read | _ -> Val.Write in
let v = V.make k loc (Val.Open(filename, mode)) in
add' k v m
let fclose k loc m =
if is_unknown k m then m else
let v = V.make k loc Val.Closed in
change k v m
let error k m =
if is_unknown k m then m else
let loc = if mem k m then find' k m |> V.split |> snd |> Set.choose |> V.loc else [] in
let v = V.make k loc Val.Error in
change k v m
let success k m =
if is_unknown k m then m else
match find_option k m with
| Some v when V.may (Val.opened%V.state) v && V.may (V.in_state Val.Error) v ->
| _ -> m
end
|
8272959dfbf294a6f6156cc3ca8c4619cf1c8cb7ce853adb19998f4e263e05f8 | cedlemo/OCaml-GI-ctypes-bindings-generator | Statusbar.mli | open Ctypes
type t
val t_typ : t typ
val create :
unit -> Widget.t ptr
val get_context_id :
t -> string -> Unsigned.uint32
val get_message_area :
t -> Box.t ptr
val pop :
t -> Unsigned.uint32 -> unit
val push :
t -> Unsigned.uint32 -> string -> Unsigned.uint32
val remove :
t -> Unsigned.uint32 -> Unsigned.uint32 -> unit
val remove_all :
t -> Unsigned.uint32 -> unit
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Statusbar.mli | ocaml | open Ctypes
type t
val t_typ : t typ
val create :
unit -> Widget.t ptr
val get_context_id :
t -> string -> Unsigned.uint32
val get_message_area :
t -> Box.t ptr
val pop :
t -> Unsigned.uint32 -> unit
val push :
t -> Unsigned.uint32 -> string -> Unsigned.uint32
val remove :
t -> Unsigned.uint32 -> Unsigned.uint32 -> unit
val remove_all :
t -> Unsigned.uint32 -> unit
| |
8c91983624c7af76a1460a495e538d9e568c5d2bf7201701af0a85c26ef290ea | spawnfest/eep49ers | wxCheckBox.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2020 . 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
%%
%% -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.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
-module(wxCheckBox).
-include("wxe.hrl").
-export([create/4,create/5,destroy/1,get3StateValue/1,getValue/1,is3State/1,
is3rdStateAllowedForUser/1,isChecked/1,new/0,new/3,new/4,set3StateValue/2,
setValue/2]).
%% inherited exports
-export([cacheBestSize/2,canSetTransparent/1,captureMouse/1,center/1,center/2,
centerOnParent/1,centerOnParent/2,centre/1,centre/2,centreOnParent/1,
centreOnParent/2,clearBackground/1,clientToScreen/2,clientToScreen/3,
close/1,close/2,connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2,
destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3,
dragAcceptFiles/2,enable/1,enable/2,findWindow/2,fit/1,fitInside/1,
freeze/1,getAcceleratorTable/1,getBackgroundColour/1,getBackgroundStyle/1,
getBestSize/1,getCaret/1,getCharHeight/1,getCharWidth/1,getChildren/1,
getClientSize/1,getContainingSizer/1,getContentScaleFactor/1,getCursor/1,
getDPI/1,getDPIScaleFactor/1,getDropTarget/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1,
getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2,
getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2,
getTextExtent/3,getThemeEnabled/1,getToolTip/1,getUpdateRegion/1,
getVirtualSize/1,getWindowStyleFlag/1,getWindowVariant/1,hasCapture/1,
hasScrollbar/2,hasTransparentBackground/1,hide/1,inheritAttributes/1,
initDialog/1,invalidateBestSize/1,isDoubleBuffered/1,isEnabled/1,
isExposed/2,isExposed/3,isExposed/5,isFrozen/1,isRetained/1,isShown/1,
isShownOnScreen/1,isTopLevel/1,layout/1,lineDown/1,lineUp/1,lower/1,
move/2,move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,
navigate/1,navigate/2,pageDown/1,pageUp/1,parent_class/1,popupMenu/2,
popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2,refreshRect/3,
releaseMouse/1,removeChild/2,reparent/2,screenToClient/1,screenToClient/2,
scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4,setAcceleratorTable/2,
setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2,setCaret/2,
setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2,
setDoubleBuffered/2,setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,
setFont/2,setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2,
setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2,
setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6,
setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3,
setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3,
setThemeEnabled/2,setToolTip/2,setTransparent/2,setVirtualSize/2,
setVirtualSize/3,setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,
shouldInheritColours/1,show/1,show/2,thaw/1,transferDataFromWindow/1,
transferDataToWindow/1,update/1,updateWindowUI/1,updateWindowUI/2,
validate/1,warpPointer/3]).
-type wxCheckBox() :: wx:wx_object().
-export_type([wxCheckBox/0]).
%% @hidden
parent_class(wxControl) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
%% @doc See <a href="#wxcheckboxwxcheckbox">external documentation</a>.
-spec new() -> wxCheckBox().
new() ->
wxe_util:queue_cmd(?get_env(), ?wxCheckBox_new_0),
wxe_util:rec(?wxCheckBox_new_0).
@equiv new(Parent , Id , Label , [ ] )
-spec new(Parent, Id, Label) -> wxCheckBox() when
Parent::wxWindow:wxWindow(), Id::integer(), Label::unicode:chardata().
new(Parent,Id,Label)
when is_record(Parent, wx_ref),is_integer(Id),?is_chardata(Label) ->
new(Parent,Id,Label, []).
%% @doc See <a href="#wxcheckboxwxcheckbox">external documentation</a>.
-spec new(Parent, Id, Label, [Option]) -> wxCheckBox() when
Parent::wxWindow:wxWindow(), Id::integer(), Label::unicode:chardata(),
Option :: {'pos', {X::integer(), Y::integer()}}
| {'size', {W::integer(), H::integer()}}
| {'style', integer()}
| {'validator', wx:wx_object()}.
new(#wx_ref{type=ParentT}=Parent,Id,Label, Options)
when is_integer(Id),?is_chardata(Label),is_list(Options) ->
?CLASS(ParentT,wxWindow),
Label_UC = unicode:characters_to_binary(Label),
MOpts = fun({pos, {_posX,_posY}} = Arg) -> Arg;
({size, {_sizeW,_sizeH}} = Arg) -> Arg;
({style, _style} = Arg) -> Arg;
({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Parent,Id,Label_UC, Opts,?get_env(),?wxCheckBox_new_4),
wxe_util:rec(?wxCheckBox_new_4).
%% @equiv create(This,Parent,Id,Label, [])
-spec create(This, Parent, Id, Label) -> boolean() when
This::wxCheckBox(), Parent::wxWindow:wxWindow(), Id::integer(), Label::unicode:chardata().
create(This,Parent,Id,Label)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id),?is_chardata(Label) ->
create(This,Parent,Id,Label, []).
%% @doc See <a href="#wxcheckboxcreate">external documentation</a>.
-spec create(This, Parent, Id, Label, [Option]) -> boolean() when
This::wxCheckBox(), Parent::wxWindow:wxWindow(), Id::integer(), Label::unicode:chardata(),
Option :: {'pos', {X::integer(), Y::integer()}}
| {'size', {W::integer(), H::integer()}}
| {'style', integer()}
| {'validator', wx:wx_object()}.
create(#wx_ref{type=ThisT}=This,#wx_ref{type=ParentT}=Parent,Id,Label, Options)
when is_integer(Id),?is_chardata(Label),is_list(Options) ->
?CLASS(ThisT,wxCheckBox),
?CLASS(ParentT,wxWindow),
Label_UC = unicode:characters_to_binary(Label),
MOpts = fun({pos, {_posX,_posY}} = Arg) -> Arg;
({size, {_sizeW,_sizeH}} = Arg) -> Arg;
({style, _style} = Arg) -> Arg;
({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Parent,Id,Label_UC, Opts,?get_env(),?wxCheckBox_Create),
wxe_util:rec(?wxCheckBox_Create).
%% @doc See <a href="#wxcheckboxgetvalue">external documentation</a>.
-spec getValue(This) -> boolean() when
This::wxCheckBox().
getValue(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_GetValue),
wxe_util:rec(?wxCheckBox_GetValue).
%% @doc See <a href="#wxcheckboxget3statevalue">external documentation</a>.
< br / > Res = ? wxCHK_UNCHECKED | ? | ?
-spec get3StateValue(This) -> wx:wx_enum() when
This::wxCheckBox().
get3StateValue(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_Get3StateValue),
wxe_util:rec(?wxCheckBox_Get3StateValue).
%% @doc See <a href="#wxcheckboxis3rdstateallowedforuser">external documentation</a>.
-spec is3rdStateAllowedForUser(This) -> boolean() when
This::wxCheckBox().
is3rdStateAllowedForUser(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_Is3rdStateAllowedForUser),
wxe_util:rec(?wxCheckBox_Is3rdStateAllowedForUser).
%% @doc See <a href="#wxcheckboxis3state">external documentation</a>.
-spec is3State(This) -> boolean() when
This::wxCheckBox().
is3State(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_Is3State),
wxe_util:rec(?wxCheckBox_Is3State).
%% @doc See <a href="#wxcheckboxischecked">external documentation</a>.
-spec isChecked(This) -> boolean() when
This::wxCheckBox().
isChecked(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_IsChecked),
wxe_util:rec(?wxCheckBox_IsChecked).
%% @doc See <a href="#wxcheckboxsetvalue">external documentation</a>.
-spec setValue(This, State) -> 'ok' when
This::wxCheckBox(), State::boolean().
setValue(#wx_ref{type=ThisT}=This,State)
when is_boolean(State) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,State,?get_env(),?wxCheckBox_SetValue).
%% @doc See <a href="#wxcheckboxset3statevalue">external documentation</a>.
< br / > State = ? wxCHK_UNCHECKED | ? | ?
-spec set3StateValue(This, State) -> 'ok' when
This::wxCheckBox(), State::wx:wx_enum().
set3StateValue(#wx_ref{type=ThisT}=This,State)
when is_integer(State) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,State,?get_env(),?wxCheckBox_Set3StateValue).
%% @doc Destroys this object, do not use object again
-spec destroy(This::wxCheckBox()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxCheckBox),
wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT),
ok.
%% From wxControl
%% @hidden
setLabel(This,Label) -> wxControl:setLabel(This,Label).
%% @hidden
getLabel(This) -> wxControl:getLabel(This).
%% From wxWindow
%% @hidden
getDPI(This) -> wxWindow:getDPI(This).
%% @hidden
getContentScaleFactor(This) -> wxWindow:getContentScaleFactor(This).
%% @hidden
setDoubleBuffered(This,On) -> wxWindow:setDoubleBuffered(This,On).
%% @hidden
isDoubleBuffered(This) -> wxWindow:isDoubleBuffered(This).
%% @hidden
canSetTransparent(This) -> wxWindow:canSetTransparent(This).
%% @hidden
setTransparent(This,Alpha) -> wxWindow:setTransparent(This,Alpha).
%% @hidden
warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y).
%% @hidden
validate(This) -> wxWindow:validate(This).
%% @hidden
updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options).
%% @hidden
updateWindowUI(This) -> wxWindow:updateWindowUI(This).
%% @hidden
update(This) -> wxWindow:update(This).
%% @hidden
transferDataToWindow(This) -> wxWindow:transferDataToWindow(This).
%% @hidden
transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This).
%% @hidden
thaw(This) -> wxWindow:thaw(This).
%% @hidden
show(This, Options) -> wxWindow:show(This, Options).
%% @hidden
show(This) -> wxWindow:show(This).
%% @hidden
shouldInheritColours(This) -> wxWindow:shouldInheritColours(This).
%% @hidden
setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant).
%% @hidden
setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style).
%% @hidden
setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style).
%% @hidden
setVirtualSize(This,Width,Height) -> wxWindow:setVirtualSize(This,Width,Height).
%% @hidden
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
%% @hidden
setToolTip(This,TipString) -> wxWindow:setToolTip(This,TipString).
%% @hidden
setThemeEnabled(This,Enable) -> wxWindow:setThemeEnabled(This,Enable).
%% @hidden
setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options).
%% @hidden
setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer).
%% @hidden
setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options).
%% @hidden
setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer).
%% @hidden
setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options).
%% @hidden
setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH).
%% @hidden
setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize).
%% @hidden
setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options).
%% @hidden
setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height).
%% @hidden
setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height).
%% @hidden
setSize(This,Rect) -> wxWindow:setSize(This,Rect).
%% @hidden
setScrollPos(This,Orientation,Pos, Options) -> wxWindow:setScrollPos(This,Orientation,Pos, Options).
%% @hidden
setScrollPos(This,Orientation,Pos) -> wxWindow:setScrollPos(This,Orientation,Pos).
%% @hidden
setScrollbar(This,Orientation,Position,ThumbSize,Range, Options) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range, Options).
%% @hidden
setScrollbar(This,Orientation,Position,ThumbSize,Range) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range).
%% @hidden
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
%% @hidden
setName(This,Name) -> wxWindow:setName(This,Name).
%% @hidden
setId(This,Winid) -> wxWindow:setId(This,Winid).
%% @hidden
setHelpText(This,HelpText) -> wxWindow:setHelpText(This,HelpText).
%% @hidden
setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour).
%% @hidden
setFont(This,Font) -> wxWindow:setFont(This,Font).
%% @hidden
setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This).
%% @hidden
setFocus(This) -> wxWindow:setFocus(This).
%% @hidden
setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle).
%% @hidden
setDropTarget(This,Target) -> wxWindow:setDropTarget(This,Target).
%% @hidden
setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour).
%% @hidden
setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font).
%% @hidden
setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour).
%% @hidden
setMinSize(This,Size) -> wxWindow:setMinSize(This,Size).
%% @hidden
setMaxSize(This,Size) -> wxWindow:setMaxSize(This,Size).
%% @hidden
setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor).
%% @hidden
setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer).
%% @hidden
setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height).
%% @hidden
setClientSize(This,Size) -> wxWindow:setClientSize(This,Size).
%% @hidden
setCaret(This,Caret) -> wxWindow:setCaret(This,Caret).
%% @hidden
setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style).
%% @hidden
setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour).
%% @hidden
setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout).
%% @hidden
setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel).
%% @hidden
scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options).
%% @hidden
scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy).
%% @hidden
scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages).
%% @hidden
scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines).
%% @hidden
screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt).
%% @hidden
screenToClient(This) -> wxWindow:screenToClient(This).
%% @hidden
reparent(This,NewParent) -> wxWindow:reparent(This,NewParent).
%% @hidden
removeChild(This,Child) -> wxWindow:removeChild(This,Child).
%% @hidden
releaseMouse(This) -> wxWindow:releaseMouse(This).
%% @hidden
refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options).
%% @hidden
refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect).
%% @hidden
refresh(This, Options) -> wxWindow:refresh(This, Options).
%% @hidden
refresh(This) -> wxWindow:refresh(This).
%% @hidden
raise(This) -> wxWindow:raise(This).
%% @hidden
popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y).
%% @hidden
popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options).
%% @hidden
popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu).
%% @hidden
pageUp(This) -> wxWindow:pageUp(This).
%% @hidden
pageDown(This) -> wxWindow:pageDown(This).
%% @hidden
navigate(This, Options) -> wxWindow:navigate(This, Options).
%% @hidden
navigate(This) -> wxWindow:navigate(This).
%% @hidden
moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win).
%% @hidden
moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win).
%% @hidden
move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options).
%% @hidden
move(This,X,Y) -> wxWindow:move(This,X,Y).
%% @hidden
move(This,Pt) -> wxWindow:move(This,Pt).
%% @hidden
lower(This) -> wxWindow:lower(This).
%% @hidden
lineUp(This) -> wxWindow:lineUp(This).
%% @hidden
lineDown(This) -> wxWindow:lineDown(This).
%% @hidden
layout(This) -> wxWindow:layout(This).
%% @hidden
isShownOnScreen(This) -> wxWindow:isShownOnScreen(This).
%% @hidden
isTopLevel(This) -> wxWindow:isTopLevel(This).
%% @hidden
isShown(This) -> wxWindow:isShown(This).
%% @hidden
isRetained(This) -> wxWindow:isRetained(This).
%% @hidden
isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H).
%% @hidden
isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y).
%% @hidden
isExposed(This,Pt) -> wxWindow:isExposed(This,Pt).
%% @hidden
isEnabled(This) -> wxWindow:isEnabled(This).
%% @hidden
isFrozen(This) -> wxWindow:isFrozen(This).
%% @hidden
invalidateBestSize(This) -> wxWindow:invalidateBestSize(This).
%% @hidden
initDialog(This) -> wxWindow:initDialog(This).
%% @hidden
inheritAttributes(This) -> wxWindow:inheritAttributes(This).
%% @hidden
hide(This) -> wxWindow:hide(This).
%% @hidden
hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This).
%% @hidden
hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient).
%% @hidden
hasCapture(This) -> wxWindow:hasCapture(This).
%% @hidden
getWindowVariant(This) -> wxWindow:getWindowVariant(This).
%% @hidden
getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This).
%% @hidden
getVirtualSize(This) -> wxWindow:getVirtualSize(This).
%% @hidden
getUpdateRegion(This) -> wxWindow:getUpdateRegion(This).
%% @hidden
getToolTip(This) -> wxWindow:getToolTip(This).
%% @hidden
getThemeEnabled(This) -> wxWindow:getThemeEnabled(This).
%% @hidden
getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options).
%% @hidden
getTextExtent(This,String) -> wxWindow:getTextExtent(This,String).
%% @hidden
getSizer(This) -> wxWindow:getSizer(This).
%% @hidden
getSize(This) -> wxWindow:getSize(This).
%% @hidden
getScrollThumb(This,Orientation) -> wxWindow:getScrollThumb(This,Orientation).
%% @hidden
getScrollRange(This,Orientation) -> wxWindow:getScrollRange(This,Orientation).
%% @hidden
getScrollPos(This,Orientation) -> wxWindow:getScrollPos(This,Orientation).
%% @hidden
getScreenRect(This) -> wxWindow:getScreenRect(This).
%% @hidden
getScreenPosition(This) -> wxWindow:getScreenPosition(This).
%% @hidden
getRect(This) -> wxWindow:getRect(This).
%% @hidden
getPosition(This) -> wxWindow:getPosition(This).
%% @hidden
getParent(This) -> wxWindow:getParent(This).
%% @hidden
getName(This) -> wxWindow:getName(This).
%% @hidden
getMinSize(This) -> wxWindow:getMinSize(This).
%% @hidden
getMaxSize(This) -> wxWindow:getMaxSize(This).
%% @hidden
getId(This) -> wxWindow:getId(This).
%% @hidden
getHelpText(This) -> wxWindow:getHelpText(This).
%% @hidden
getHandle(This) -> wxWindow:getHandle(This).
%% @hidden
getGrandParent(This) -> wxWindow:getGrandParent(This).
%% @hidden
getForegroundColour(This) -> wxWindow:getForegroundColour(This).
%% @hidden
getFont(This) -> wxWindow:getFont(This).
%% @hidden
getExtraStyle(This) -> wxWindow:getExtraStyle(This).
%% @hidden
getDPIScaleFactor(This) -> wxWindow:getDPIScaleFactor(This).
%% @hidden
getDropTarget(This) -> wxWindow:getDropTarget(This).
%% @hidden
getCursor(This) -> wxWindow:getCursor(This).
%% @hidden
getContainingSizer(This) -> wxWindow:getContainingSizer(This).
%% @hidden
getClientSize(This) -> wxWindow:getClientSize(This).
%% @hidden
getChildren(This) -> wxWindow:getChildren(This).
%% @hidden
getCharWidth(This) -> wxWindow:getCharWidth(This).
%% @hidden
getCharHeight(This) -> wxWindow:getCharHeight(This).
%% @hidden
getCaret(This) -> wxWindow:getCaret(This).
%% @hidden
getBestSize(This) -> wxWindow:getBestSize(This).
%% @hidden
getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This).
%% @hidden
getBackgroundColour(This) -> wxWindow:getBackgroundColour(This).
%% @hidden
getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This).
%% @hidden
freeze(This) -> wxWindow:freeze(This).
%% @hidden
fitInside(This) -> wxWindow:fitInside(This).
%% @hidden
fit(This) -> wxWindow:fit(This).
%% @hidden
findWindow(This,Id) -> wxWindow:findWindow(This,Id).
%% @hidden
enable(This, Options) -> wxWindow:enable(This, Options).
%% @hidden
enable(This) -> wxWindow:enable(This).
%% @hidden
dragAcceptFiles(This,Accept) -> wxWindow:dragAcceptFiles(This,Accept).
%% @hidden
disable(This) -> wxWindow:disable(This).
%% @hidden
destroyChildren(This) -> wxWindow:destroyChildren(This).
%% @hidden
convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz).
%% @hidden
convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz).
%% @hidden
close(This, Options) -> wxWindow:close(This, Options).
%% @hidden
close(This) -> wxWindow:close(This).
%% @hidden
clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y).
%% @hidden
clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt).
%% @hidden
clearBackground(This) -> wxWindow:clearBackground(This).
%% @hidden
centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options).
%% @hidden
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
%% @hidden
centreOnParent(This) -> wxWindow:centreOnParent(This).
%% @hidden
centerOnParent(This) -> wxWindow:centerOnParent(This).
%% @hidden
centre(This, Options) -> wxWindow:centre(This, Options).
%% @hidden
center(This, Options) -> wxWindow:center(This, Options).
%% @hidden
centre(This) -> wxWindow:centre(This).
%% @hidden
center(This) -> wxWindow:center(This).
%% @hidden
captureMouse(This) -> wxWindow:captureMouse(This).
%% @hidden
cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size).
%% From wxEvtHandler
%% @hidden
disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options).
%% @hidden
disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType).
%% @hidden
disconnect(This) -> wxEvtHandler:disconnect(This).
%% @hidden
connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options).
%% @hidden
connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxCheckBox.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
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.
%CopyrightEnd%
This file is generated DO NOT EDIT
inherited exports
@hidden
@doc See <a href="#wxcheckboxwxcheckbox">external documentation</a>.
@doc See <a href="#wxcheckboxwxcheckbox">external documentation</a>.
@equiv create(This,Parent,Id,Label, [])
@doc See <a href="#wxcheckboxcreate">external documentation</a>.
@doc See <a href="#wxcheckboxgetvalue">external documentation</a>.
@doc See <a href="#wxcheckboxget3statevalue">external documentation</a>.
@doc See <a href="#wxcheckboxis3rdstateallowedforuser">external documentation</a>.
@doc See <a href="#wxcheckboxis3state">external documentation</a>.
@doc See <a href="#wxcheckboxischecked">external documentation</a>.
@doc See <a href="#wxcheckboxsetvalue">external documentation</a>.
@doc See <a href="#wxcheckboxset3statevalue">external documentation</a>.
@doc Destroys this object, do not use object again
From wxControl
@hidden
@hidden
From wxWindow
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
From wxEvtHandler
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(wxCheckBox).
-include("wxe.hrl").
-export([create/4,create/5,destroy/1,get3StateValue/1,getValue/1,is3State/1,
is3rdStateAllowedForUser/1,isChecked/1,new/0,new/3,new/4,set3StateValue/2,
setValue/2]).
-export([cacheBestSize/2,canSetTransparent/1,captureMouse/1,center/1,center/2,
centerOnParent/1,centerOnParent/2,centre/1,centre/2,centreOnParent/1,
centreOnParent/2,clearBackground/1,clientToScreen/2,clientToScreen/3,
close/1,close/2,connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2,
destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3,
dragAcceptFiles/2,enable/1,enable/2,findWindow/2,fit/1,fitInside/1,
freeze/1,getAcceleratorTable/1,getBackgroundColour/1,getBackgroundStyle/1,
getBestSize/1,getCaret/1,getCharHeight/1,getCharWidth/1,getChildren/1,
getClientSize/1,getContainingSizer/1,getContentScaleFactor/1,getCursor/1,
getDPI/1,getDPIScaleFactor/1,getDropTarget/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1,
getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2,
getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2,
getTextExtent/3,getThemeEnabled/1,getToolTip/1,getUpdateRegion/1,
getVirtualSize/1,getWindowStyleFlag/1,getWindowVariant/1,hasCapture/1,
hasScrollbar/2,hasTransparentBackground/1,hide/1,inheritAttributes/1,
initDialog/1,invalidateBestSize/1,isDoubleBuffered/1,isEnabled/1,
isExposed/2,isExposed/3,isExposed/5,isFrozen/1,isRetained/1,isShown/1,
isShownOnScreen/1,isTopLevel/1,layout/1,lineDown/1,lineUp/1,lower/1,
move/2,move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,
navigate/1,navigate/2,pageDown/1,pageUp/1,parent_class/1,popupMenu/2,
popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2,refreshRect/3,
releaseMouse/1,removeChild/2,reparent/2,screenToClient/1,screenToClient/2,
scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4,setAcceleratorTable/2,
setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2,setCaret/2,
setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2,
setDoubleBuffered/2,setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,
setFont/2,setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2,
setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2,
setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6,
setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3,
setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3,
setThemeEnabled/2,setToolTip/2,setTransparent/2,setVirtualSize/2,
setVirtualSize/3,setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,
shouldInheritColours/1,show/1,show/2,thaw/1,transferDataFromWindow/1,
transferDataToWindow/1,update/1,updateWindowUI/1,updateWindowUI/2,
validate/1,warpPointer/3]).
-type wxCheckBox() :: wx:wx_object().
-export_type([wxCheckBox/0]).
parent_class(wxControl) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-spec new() -> wxCheckBox().
new() ->
wxe_util:queue_cmd(?get_env(), ?wxCheckBox_new_0),
wxe_util:rec(?wxCheckBox_new_0).
@equiv new(Parent , Id , Label , [ ] )
-spec new(Parent, Id, Label) -> wxCheckBox() when
Parent::wxWindow:wxWindow(), Id::integer(), Label::unicode:chardata().
new(Parent,Id,Label)
when is_record(Parent, wx_ref),is_integer(Id),?is_chardata(Label) ->
new(Parent,Id,Label, []).
-spec new(Parent, Id, Label, [Option]) -> wxCheckBox() when
Parent::wxWindow:wxWindow(), Id::integer(), Label::unicode:chardata(),
Option :: {'pos', {X::integer(), Y::integer()}}
| {'size', {W::integer(), H::integer()}}
| {'style', integer()}
| {'validator', wx:wx_object()}.
new(#wx_ref{type=ParentT}=Parent,Id,Label, Options)
when is_integer(Id),?is_chardata(Label),is_list(Options) ->
?CLASS(ParentT,wxWindow),
Label_UC = unicode:characters_to_binary(Label),
MOpts = fun({pos, {_posX,_posY}} = Arg) -> Arg;
({size, {_sizeW,_sizeH}} = Arg) -> Arg;
({style, _style} = Arg) -> Arg;
({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Parent,Id,Label_UC, Opts,?get_env(),?wxCheckBox_new_4),
wxe_util:rec(?wxCheckBox_new_4).
-spec create(This, Parent, Id, Label) -> boolean() when
This::wxCheckBox(), Parent::wxWindow:wxWindow(), Id::integer(), Label::unicode:chardata().
create(This,Parent,Id,Label)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id),?is_chardata(Label) ->
create(This,Parent,Id,Label, []).
-spec create(This, Parent, Id, Label, [Option]) -> boolean() when
This::wxCheckBox(), Parent::wxWindow:wxWindow(), Id::integer(), Label::unicode:chardata(),
Option :: {'pos', {X::integer(), Y::integer()}}
| {'size', {W::integer(), H::integer()}}
| {'style', integer()}
| {'validator', wx:wx_object()}.
create(#wx_ref{type=ThisT}=This,#wx_ref{type=ParentT}=Parent,Id,Label, Options)
when is_integer(Id),?is_chardata(Label),is_list(Options) ->
?CLASS(ThisT,wxCheckBox),
?CLASS(ParentT,wxWindow),
Label_UC = unicode:characters_to_binary(Label),
MOpts = fun({pos, {_posX,_posY}} = Arg) -> Arg;
({size, {_sizeW,_sizeH}} = Arg) -> Arg;
({style, _style} = Arg) -> Arg;
({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Parent,Id,Label_UC, Opts,?get_env(),?wxCheckBox_Create),
wxe_util:rec(?wxCheckBox_Create).
-spec getValue(This) -> boolean() when
This::wxCheckBox().
getValue(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_GetValue),
wxe_util:rec(?wxCheckBox_GetValue).
< br / > Res = ? wxCHK_UNCHECKED | ? | ?
-spec get3StateValue(This) -> wx:wx_enum() when
This::wxCheckBox().
get3StateValue(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_Get3StateValue),
wxe_util:rec(?wxCheckBox_Get3StateValue).
-spec is3rdStateAllowedForUser(This) -> boolean() when
This::wxCheckBox().
is3rdStateAllowedForUser(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_Is3rdStateAllowedForUser),
wxe_util:rec(?wxCheckBox_Is3rdStateAllowedForUser).
-spec is3State(This) -> boolean() when
This::wxCheckBox().
is3State(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_Is3State),
wxe_util:rec(?wxCheckBox_Is3State).
-spec isChecked(This) -> boolean() when
This::wxCheckBox().
isChecked(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,?get_env(),?wxCheckBox_IsChecked),
wxe_util:rec(?wxCheckBox_IsChecked).
-spec setValue(This, State) -> 'ok' when
This::wxCheckBox(), State::boolean().
setValue(#wx_ref{type=ThisT}=This,State)
when is_boolean(State) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,State,?get_env(),?wxCheckBox_SetValue).
< br / > State = ? wxCHK_UNCHECKED | ? | ?
-spec set3StateValue(This, State) -> 'ok' when
This::wxCheckBox(), State::wx:wx_enum().
set3StateValue(#wx_ref{type=ThisT}=This,State)
when is_integer(State) ->
?CLASS(ThisT,wxCheckBox),
wxe_util:queue_cmd(This,State,?get_env(),?wxCheckBox_Set3StateValue).
-spec destroy(This::wxCheckBox()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxCheckBox),
wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT),
ok.
setLabel(This,Label) -> wxControl:setLabel(This,Label).
getLabel(This) -> wxControl:getLabel(This).
getDPI(This) -> wxWindow:getDPI(This).
getContentScaleFactor(This) -> wxWindow:getContentScaleFactor(This).
setDoubleBuffered(This,On) -> wxWindow:setDoubleBuffered(This,On).
isDoubleBuffered(This) -> wxWindow:isDoubleBuffered(This).
canSetTransparent(This) -> wxWindow:canSetTransparent(This).
setTransparent(This,Alpha) -> wxWindow:setTransparent(This,Alpha).
warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y).
validate(This) -> wxWindow:validate(This).
updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options).
updateWindowUI(This) -> wxWindow:updateWindowUI(This).
update(This) -> wxWindow:update(This).
transferDataToWindow(This) -> wxWindow:transferDataToWindow(This).
transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This).
thaw(This) -> wxWindow:thaw(This).
show(This, Options) -> wxWindow:show(This, Options).
show(This) -> wxWindow:show(This).
shouldInheritColours(This) -> wxWindow:shouldInheritColours(This).
setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant).
setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style).
setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style).
setVirtualSize(This,Width,Height) -> wxWindow:setVirtualSize(This,Width,Height).
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
setToolTip(This,TipString) -> wxWindow:setToolTip(This,TipString).
setThemeEnabled(This,Enable) -> wxWindow:setThemeEnabled(This,Enable).
setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options).
setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer).
setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options).
setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer).
setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options).
setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH).
setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize).
setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options).
setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height).
setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height).
setSize(This,Rect) -> wxWindow:setSize(This,Rect).
setScrollPos(This,Orientation,Pos, Options) -> wxWindow:setScrollPos(This,Orientation,Pos, Options).
setScrollPos(This,Orientation,Pos) -> wxWindow:setScrollPos(This,Orientation,Pos).
setScrollbar(This,Orientation,Position,ThumbSize,Range, Options) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range, Options).
setScrollbar(This,Orientation,Position,ThumbSize,Range) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range).
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
setName(This,Name) -> wxWindow:setName(This,Name).
setId(This,Winid) -> wxWindow:setId(This,Winid).
setHelpText(This,HelpText) -> wxWindow:setHelpText(This,HelpText).
setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour).
setFont(This,Font) -> wxWindow:setFont(This,Font).
setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This).
setFocus(This) -> wxWindow:setFocus(This).
setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle).
setDropTarget(This,Target) -> wxWindow:setDropTarget(This,Target).
setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour).
setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font).
setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour).
setMinSize(This,Size) -> wxWindow:setMinSize(This,Size).
setMaxSize(This,Size) -> wxWindow:setMaxSize(This,Size).
setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor).
setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer).
setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height).
setClientSize(This,Size) -> wxWindow:setClientSize(This,Size).
setCaret(This,Caret) -> wxWindow:setCaret(This,Caret).
setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style).
setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour).
setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout).
setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel).
scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options).
scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy).
scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages).
scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines).
screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt).
screenToClient(This) -> wxWindow:screenToClient(This).
reparent(This,NewParent) -> wxWindow:reparent(This,NewParent).
removeChild(This,Child) -> wxWindow:removeChild(This,Child).
releaseMouse(This) -> wxWindow:releaseMouse(This).
refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options).
refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect).
refresh(This, Options) -> wxWindow:refresh(This, Options).
refresh(This) -> wxWindow:refresh(This).
raise(This) -> wxWindow:raise(This).
popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y).
popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options).
popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu).
pageUp(This) -> wxWindow:pageUp(This).
pageDown(This) -> wxWindow:pageDown(This).
navigate(This, Options) -> wxWindow:navigate(This, Options).
navigate(This) -> wxWindow:navigate(This).
moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win).
moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win).
move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options).
move(This,X,Y) -> wxWindow:move(This,X,Y).
move(This,Pt) -> wxWindow:move(This,Pt).
lower(This) -> wxWindow:lower(This).
lineUp(This) -> wxWindow:lineUp(This).
lineDown(This) -> wxWindow:lineDown(This).
layout(This) -> wxWindow:layout(This).
isShownOnScreen(This) -> wxWindow:isShownOnScreen(This).
isTopLevel(This) -> wxWindow:isTopLevel(This).
isShown(This) -> wxWindow:isShown(This).
isRetained(This) -> wxWindow:isRetained(This).
isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H).
isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y).
isExposed(This,Pt) -> wxWindow:isExposed(This,Pt).
isEnabled(This) -> wxWindow:isEnabled(This).
isFrozen(This) -> wxWindow:isFrozen(This).
invalidateBestSize(This) -> wxWindow:invalidateBestSize(This).
initDialog(This) -> wxWindow:initDialog(This).
inheritAttributes(This) -> wxWindow:inheritAttributes(This).
hide(This) -> wxWindow:hide(This).
hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This).
hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient).
hasCapture(This) -> wxWindow:hasCapture(This).
getWindowVariant(This) -> wxWindow:getWindowVariant(This).
getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This).
getVirtualSize(This) -> wxWindow:getVirtualSize(This).
getUpdateRegion(This) -> wxWindow:getUpdateRegion(This).
getToolTip(This) -> wxWindow:getToolTip(This).
getThemeEnabled(This) -> wxWindow:getThemeEnabled(This).
getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options).
getTextExtent(This,String) -> wxWindow:getTextExtent(This,String).
getSizer(This) -> wxWindow:getSizer(This).
getSize(This) -> wxWindow:getSize(This).
getScrollThumb(This,Orientation) -> wxWindow:getScrollThumb(This,Orientation).
getScrollRange(This,Orientation) -> wxWindow:getScrollRange(This,Orientation).
getScrollPos(This,Orientation) -> wxWindow:getScrollPos(This,Orientation).
getScreenRect(This) -> wxWindow:getScreenRect(This).
getScreenPosition(This) -> wxWindow:getScreenPosition(This).
getRect(This) -> wxWindow:getRect(This).
getPosition(This) -> wxWindow:getPosition(This).
getParent(This) -> wxWindow:getParent(This).
getName(This) -> wxWindow:getName(This).
getMinSize(This) -> wxWindow:getMinSize(This).
getMaxSize(This) -> wxWindow:getMaxSize(This).
getId(This) -> wxWindow:getId(This).
getHelpText(This) -> wxWindow:getHelpText(This).
getHandle(This) -> wxWindow:getHandle(This).
getGrandParent(This) -> wxWindow:getGrandParent(This).
getForegroundColour(This) -> wxWindow:getForegroundColour(This).
getFont(This) -> wxWindow:getFont(This).
getExtraStyle(This) -> wxWindow:getExtraStyle(This).
getDPIScaleFactor(This) -> wxWindow:getDPIScaleFactor(This).
getDropTarget(This) -> wxWindow:getDropTarget(This).
getCursor(This) -> wxWindow:getCursor(This).
getContainingSizer(This) -> wxWindow:getContainingSizer(This).
getClientSize(This) -> wxWindow:getClientSize(This).
getChildren(This) -> wxWindow:getChildren(This).
getCharWidth(This) -> wxWindow:getCharWidth(This).
getCharHeight(This) -> wxWindow:getCharHeight(This).
getCaret(This) -> wxWindow:getCaret(This).
getBestSize(This) -> wxWindow:getBestSize(This).
getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This).
getBackgroundColour(This) -> wxWindow:getBackgroundColour(This).
getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This).
freeze(This) -> wxWindow:freeze(This).
fitInside(This) -> wxWindow:fitInside(This).
fit(This) -> wxWindow:fit(This).
findWindow(This,Id) -> wxWindow:findWindow(This,Id).
enable(This, Options) -> wxWindow:enable(This, Options).
enable(This) -> wxWindow:enable(This).
dragAcceptFiles(This,Accept) -> wxWindow:dragAcceptFiles(This,Accept).
disable(This) -> wxWindow:disable(This).
destroyChildren(This) -> wxWindow:destroyChildren(This).
convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz).
convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz).
close(This, Options) -> wxWindow:close(This, Options).
close(This) -> wxWindow:close(This).
clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y).
clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt).
clearBackground(This) -> wxWindow:clearBackground(This).
centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options).
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
centreOnParent(This) -> wxWindow:centreOnParent(This).
centerOnParent(This) -> wxWindow:centerOnParent(This).
centre(This, Options) -> wxWindow:centre(This, Options).
center(This, Options) -> wxWindow:center(This, Options).
centre(This) -> wxWindow:centre(This).
center(This) -> wxWindow:center(This).
captureMouse(This) -> wxWindow:captureMouse(This).
cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size).
disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options).
disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType).
disconnect(This) -> wxEvtHandler:disconnect(This).
connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options).
connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
|
8ec16075531dad8443bf583e88c6a0d9bcea39814aa3680640e4fc36c51360ed | cram2/cram | padding-mask.lisp | Copyright ( c ) 2010 , < >
;;; 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 the Intelligent Autonomous Systems Group/
;;; Technische Universitaet Muenchen nor the names of its contributors
;;; may be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
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.
(in-package :location-costmap)
(defun make-padding-mask (size)
"returns a 2d square array with an odd dimension drawing a discretized circle
of radius `size' in grid space"
(unless (<= size 0)
(let* ((array-width (1+ (* size 2)))
(mask (make-array (list array-width array-width) :element-type 'fixnum))
(dist^2 (expt size 2)))
(declare (type (simple-array fixnum *) mask))
(dotimes (row array-width)
(dotimes (col array-width)
;; (size, size) is the center cell
(if (<= (+ (expt (- col size) 2) (expt (- row size) 2))
dist^2)
(setf (aref mask row col) 1)
(setf (aref mask row col) 0))))
mask)))
(declaim (ftype (function ((simple-array fixnum 2) fixnum fixnum (simple-array fixnum 2))
boolean) point-in-range-mask-p))
(defun point-in-padding-mask-p (map x y range-mask)
(declare (type (simple-array fixnum 2) map range-mask)
(type fixnum x y))
(let ((array-height (array-dimension map 0))
(array-width (array-dimension map 1))
(mask-height (array-dimension range-mask 0))
(mask-width (array-dimension range-mask 1)))
(let* ((mask-width/2 (round (/ mask-width 2)))
(mask-height/2 (round (/ mask-height 2)))
(start-x (if (< (- x mask-width/2) 0)
x mask-width/2))
(end-x (if (> (+ x mask-width/2) array-width)
(- array-width x)
mask-width/2))
(start-y (if (< (- y mask-height/2) 0)
y mask-height/2))
(end-y (if (> (+ y mask-height/2) array-height)
(- array-height y)
mask-height/2)))
(do ((y-i (- y start-y) (+ y-i 1))
(mask-y (- mask-height/2 start-y) (+ mask-y 1)))
((>= y-i (+ y end-y)))
(do ((x-i (- x start-x) (+ x-i 1))
(mask-x (- mask-width/2 start-x) (+ mask-x 1)))
((>= x-i (+ x end-x)))
(let ((mask-value (aref range-mask mask-y mask-x))
(map-value (aref map y-i x-i)))
(when (and (> map-value 0) (> mask-value 0))
(return-from point-in-padding-mask-p t)))))))
nil)
(defun occupancy-grid-put-mask (x y grid mask &key (coords-raw-p nil))
"Puts the mask into grid, at position x and y. Please note that the
mask must completely fit, i.e. x/resolution must be >= 0.5
mask-size-x. `coords-raw-p indicates if x and y are direct indices
in the grid array or floating point coordinates in the reference
coordinate system."
(let ((x (if coords-raw-p x (round (/ (- x (origin-x grid)) (resolution grid)))))
(y (if coords-raw-p y (round (/ (- y (origin-y grid)) (resolution grid)))))
(grid-arr (grid grid))
(mask-size-x (array-dimension mask 1))
(mask-size-y (array-dimension mask 0)))
(declare (type fixnum x y)
(type (simple-array fixnum *) grid-arr mask))
(do ((grid-row (- y (- (truncate (/ (array-dimension mask 0) 2)) 1))
(+ grid-row 1))
(mask-row 0 (+ mask-row 1)))
((>= mask-row (- mask-size-y 1)))
(do ((grid-col (- x (- (truncate (/ (array-dimension mask 1) 2)) 1))
(+ grid-col 1))
(mask-col 0 (+ mask-col 1)))
((>= mask-col (- mask-size-x 1)))
(when (eql (aref mask mask-row mask-col) 1)
(setf (aref grid-arr grid-row grid-col) 1))))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_common/cram_location_costmap/src/padding-mask.lisp | lisp | 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.
Technische Universitaet Muenchen nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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.
(size, size) is the center cell | Copyright ( c ) 2010 , < >
* Neither the name of the Intelligent Autonomous Systems Group/
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :location-costmap)
(defun make-padding-mask (size)
"returns a 2d square array with an odd dimension drawing a discretized circle
of radius `size' in grid space"
(unless (<= size 0)
(let* ((array-width (1+ (* size 2)))
(mask (make-array (list array-width array-width) :element-type 'fixnum))
(dist^2 (expt size 2)))
(declare (type (simple-array fixnum *) mask))
(dotimes (row array-width)
(dotimes (col array-width)
(if (<= (+ (expt (- col size) 2) (expt (- row size) 2))
dist^2)
(setf (aref mask row col) 1)
(setf (aref mask row col) 0))))
mask)))
(declaim (ftype (function ((simple-array fixnum 2) fixnum fixnum (simple-array fixnum 2))
boolean) point-in-range-mask-p))
(defun point-in-padding-mask-p (map x y range-mask)
(declare (type (simple-array fixnum 2) map range-mask)
(type fixnum x y))
(let ((array-height (array-dimension map 0))
(array-width (array-dimension map 1))
(mask-height (array-dimension range-mask 0))
(mask-width (array-dimension range-mask 1)))
(let* ((mask-width/2 (round (/ mask-width 2)))
(mask-height/2 (round (/ mask-height 2)))
(start-x (if (< (- x mask-width/2) 0)
x mask-width/2))
(end-x (if (> (+ x mask-width/2) array-width)
(- array-width x)
mask-width/2))
(start-y (if (< (- y mask-height/2) 0)
y mask-height/2))
(end-y (if (> (+ y mask-height/2) array-height)
(- array-height y)
mask-height/2)))
(do ((y-i (- y start-y) (+ y-i 1))
(mask-y (- mask-height/2 start-y) (+ mask-y 1)))
((>= y-i (+ y end-y)))
(do ((x-i (- x start-x) (+ x-i 1))
(mask-x (- mask-width/2 start-x) (+ mask-x 1)))
((>= x-i (+ x end-x)))
(let ((mask-value (aref range-mask mask-y mask-x))
(map-value (aref map y-i x-i)))
(when (and (> map-value 0) (> mask-value 0))
(return-from point-in-padding-mask-p t)))))))
nil)
(defun occupancy-grid-put-mask (x y grid mask &key (coords-raw-p nil))
"Puts the mask into grid, at position x and y. Please note that the
mask must completely fit, i.e. x/resolution must be >= 0.5
mask-size-x. `coords-raw-p indicates if x and y are direct indices
in the grid array or floating point coordinates in the reference
coordinate system."
(let ((x (if coords-raw-p x (round (/ (- x (origin-x grid)) (resolution grid)))))
(y (if coords-raw-p y (round (/ (- y (origin-y grid)) (resolution grid)))))
(grid-arr (grid grid))
(mask-size-x (array-dimension mask 1))
(mask-size-y (array-dimension mask 0)))
(declare (type fixnum x y)
(type (simple-array fixnum *) grid-arr mask))
(do ((grid-row (- y (- (truncate (/ (array-dimension mask 0) 2)) 1))
(+ grid-row 1))
(mask-row 0 (+ mask-row 1)))
((>= mask-row (- mask-size-y 1)))
(do ((grid-col (- x (- (truncate (/ (array-dimension mask 1) 2)) 1))
(+ grid-col 1))
(mask-col 0 (+ mask-col 1)))
((>= mask-col (- mask-size-x 1)))
(when (eql (aref mask mask-row mask-col) 1)
(setf (aref grid-arr grid-row grid-col) 1))))))
|
959583ffb4682e5ac55e3bb1a6469388712847d39d239248d8e597e965d294be | trskop/command-wrapper | Message.hs | -- |
-- Module: $Header$
-- Description: Experiment to make help messages easier to create.
Copyright : ( c ) 2019 - 2020
License : BSD3
--
-- Maintainer:
-- Stability: experimental
Portability : GHC specific language extensions .
--
-- Experiment to make help messages easier to create. Highly experimental!
module CommandWrapper.Core.Help.Message
( Annotation(..)
, Annotated(..)
, HelpMessage(..)
, Paragraph
, Usage
-- * Combinators
, longOption
, shortOption
, metavar
, command
, value
, (<+>)
, alternatives
, optionalAlternatives
, requiredAlternatives
, braces
, brackets
, squotes
, dquotes
, reflow
, subcommand
, optionalSubcommand
, optionalMetavar
, helpOptions
-- * Rendering
, renderAnnotated
, renderParagraph
, render
, defaultStyle
-- ** IO
, hPutHelp
, helpMessage -- TODO: TMP
)
where
import Data.Bool (otherwise)
import Data.Char (Char)
import Data.Eq (Eq, (==))
import Data.Foldable (foldMap)
import Data.Function (($), (.))
import Data.Functor (Functor, (<$>), fmap)
import Data.Int (Int)
import qualified Data.List as List (intercalate, intersperse)
import Data.Maybe (Maybe(Just, Nothing), maybe)
import Data.Monoid (mconcat, mempty)
import Data.Semigroup (Semigroup, (<>))
import Data.String (IsString(fromString))
import GHC.Generics (Generic)
import System.IO (Handle, IO)
import Text.Show (Show)
import Data.Text (Text)
import qualified Data.Text as Text (null, uncons, unsnoc, words)
import Data.Text.Prettyprint.Doc (Doc, Pretty(pretty))
import qualified Data.Text.Prettyprint.Doc as Pretty
import qualified Data.Text.Prettyprint.Doc.Render.Terminal as Pretty
import qualified System.Console.Terminal.Size as Terminal (Window)
import CommandWrapper.Core.Config.ColourOutput (ColourOutput)
import CommandWrapper.Core.Message (hPutDoc)
data Annotation
= Plain
| Option
| Metavar
| Value
| Command
deriving stock (Eq, Generic, Show)
TODO : At the moment @Annotated Plain \"\"@ and @Annotated Plain \ " \"@ have
-- a special meaning. Better encoding would be desirable, however, that will
-- complicate the implementation at the moment.
data Annotated a = Annotated
{ annotation :: Annotation
, content :: a
}
deriving stock (Eq, Functor, Generic, Show)
-- | @\\s -> 'Annotated'{'annotation' = 'Plain', 'content' = 'fromString' s}@
instance IsString s => IsString (Annotated s) where
fromString = Annotated Plain . fromString
type Paragraph a = [Annotated a]
type Usage a = [Annotated a]
data Section a = Section
{ name :: Paragraph a
, content :: [Paragraph a]
}
deriving stock (Eq, Functor, Generic, Show)
data HelpMessage a = HelpMessage
{ description :: Paragraph a
, usage :: [Usage a]
, sections :: [Section a]
, message :: [Paragraph a]
}
deriving stock (Eq, Functor, Generic, Show)
-- {{{ Combinators ------------------------------------------------------------
-- |
-- >>> longOption "foo" :: Annotated Text
Annotated{annotation = Option , content = " --foo " }
longOption :: (IsString s, Semigroup s) => s -> Annotated s
longOption content = Annotated
{ annotation = Option
, content = "--" <> content
}
-- |
-- >>> shortOption 'f' :: Annotated Text
Annotated{annotation = Option , content = " -f " }
shortOption :: IsString s => Char -> Annotated s
shortOption c = Annotated
{ annotation = Option
, content = fromString ('-' : [c])
}
metavar :: s -> Annotated s
metavar = Annotated Metavar
command :: s -> Annotated s
command = Annotated Command
value :: s -> Annotated s
value = Annotated Command
(<+>) :: IsString s => [Annotated s] -> [Annotated s] -> [Annotated s]
l <+> r = l <> [""] <> r
brackets :: IsString s => [Annotated s] -> [Annotated s]
brackets c = "[" : c <> ["]"]
braces :: IsString s => [Annotated s] -> [Annotated s]
braces c = "{" : c <> ["}"]
squotes :: IsString s => [Annotated s] -> [Annotated s]
squotes c = "'" : c <> ["'"]
dquotes :: IsString s => [Annotated s] -> [Annotated s]
dquotes c = "\"" : c <> ["\""]
alternatives :: IsString s => [[Annotated s]] -> [Annotated s]
alternatives = List.intercalate ["|"]
optionalAlternatives :: IsString s => [[Annotated s]] -> [Annotated s]
optionalAlternatives = brackets . alternatives
requiredAlternatives :: IsString s => [[Annotated s]] -> [Annotated s]
requiredAlternatives = braces . alternatives
reflow :: Paragraph Text -> Paragraph Text
reflow = foldMap words
where
words :: Annotated Text -> [Annotated Text]
words a@Annotated{..} = case annotation of
Plain
| Text.null content -> [a]
| content == " " -> [a]
| otherwise -> mconcat
[ preserveSpaceAtTheBeginning content
, Annotated Plain <$> List.intersperse "" (Text.words content)
, preserveSpaceAtTheEnd content
]
Option -> [a]
Metavar -> [a]
Value -> [a]
Command -> [a]
where
preserveSpaceAtTheBeginning t = case Text.uncons t of
Nothing -> []
Just (' ', _) -> [Annotated Plain ""]
_ -> []
preserveSpaceAtTheEnd t = case Text.unsnoc t of
Nothing -> []
Just (_, ' ') -> [Annotated Plain ""]
_ -> []
-- | @['metavar' \"SUBCOMMAND\"]@
subcommand :: IsString s => [Annotated s]
subcommand = [metavar "SUBCOMMAND"]
-- | @'metavar' \"SUBCOMMAND\"@
optionalSubcommand :: IsString s => [Annotated s]
optionalSubcommand = brackets subcommand
optionalMetavar :: IsString s => s -> [Annotated s]
optionalMetavar s = brackets [metavar s]
helpOptions :: (IsString s, Semigroup s) => [Annotated s]
helpOptions = alternatives
[ [longOption "help"]
, [shortOption 'h']
]
-- }}} Combinators ------------------------------------------------------------
-- {{{ Rendering --------------------------------------------------------------
renderAnnotated :: (Eq a, IsString a, Pretty a) => Annotated a -> Doc Annotation
renderAnnotated Annotated{..} = case annotation of
Plain
| content == "" ->
Pretty.softline
| content == " " ->
" "
| otherwise ->
Pretty.annotate annotation (pretty content)
_ ->
Pretty.annotate annotation (pretty content)
renderParagraph :: Paragraph Text -> Doc Annotation
renderParagraph = foldMap renderAnnotated . reflow
render :: HelpMessage Text -> Doc Annotation
render HelpMessage{..} = Pretty.vsep
[ renderParagraph description
, ""
, renderSection "Usage:" (usage)
, Pretty.vsep (renderSections sections)
, Pretty.vsep (renderParagraph <$> message)
]
where
renderSection :: Doc Annotation -> [Paragraph Text] -> Doc Annotation
renderSection d ds =
Pretty.nest 2 $ Pretty.vsep $ d : "" : (fmap renderParagraph ds <> [""])
renderSections :: [Section Text] -> [Doc Annotation]
renderSections = fmap \Section{..} ->
renderSection (renderParagraph name) content
defaultStyle :: Annotation -> Pretty.AnsiStyle
defaultStyle = \case
Plain -> mempty
Option -> Pretty.colorDull Pretty.Green
Metavar -> Pretty.colorDull Pretty.Green
Value -> Pretty.colorDull Pretty.Green
Command -> Pretty.color Pretty.Magenta
-- {{{ I/O --------------------------------------------------------------------
hPutHelp
:: (Maybe (Terminal.Window Int) -> Pretty.LayoutOptions)
-> (Annotation -> Pretty.AnsiStyle)
-> ColourOutput
-> Handle
-> HelpMessage Text
-> IO ()
hPutHelp mkLayoutOptions style colourOutput h =
hPutDoc mkLayoutOptions style colourOutput h . render
-- }}} I/O --------------------------------------------------------------------
-- }}} Rendering --------------------------------------------------------------
helpMessage :: Text -> Maybe Text -> HelpMessage Text
helpMessage usedName description = HelpMessage
{ description = [maybe defaultDescription (Annotated Plain) description]
, usage =
[ [Annotated Plain usedName] <+> subcommand <+> subcommandArguments
, [Annotated Plain usedName] <+> ["help"]
<+> optionalMetavar "HELP_OPTIONS"
<+> optionalSubcommand
, [Annotated Plain usedName] <+> ["config"]
<+> optionalMetavar "CONFIG_OPTIONS"
<+> optionalSubcommand
, [Annotated Plain usedName] <+> ["version"]
<+> optionalMetavar "VERSION_OPTIONS"
, [Annotated Plain usedName] <+> ["completion"]
<+> optionalMetavar "COMPLETION_OPTIONS"
, [Annotated Plain usedName] <+> requiredAlternatives
[ [longOption "version"]
, [shortOption 'V']
]
, [Annotated Plain usedName] <+> braces helpOptions
]
, sections = []
, message = []
}
, Help.section ( Pretty.annotate Help.dullGreen " GLOBAL_OPTIONS " < > " : " )
-- [ Help.optionDescription ["-v"]
[ Pretty.reflow " Increment verbosity by one level . Can be used "
-- , Pretty.reflow "multiple times."
-- ]
-- , Help.optionDescription ["--verbosity=VERBOSITY"]
-- [ Pretty.reflow "Set verbosity level to"
-- , Help.metavar "VERBOSITY" <> "."
-- , Pretty.reflow "Possible values of"
-- , Help.metavar "VERBOSITY", "are"
, Pretty.squotes ( Help.value " silent " ) < > " , "
, Pretty.squotes ( Help.value " normal " ) < > " , "
, Pretty.squotes ( Help.value " verbose " ) < > " , "
-- , "and"
, Pretty.squotes ( Help.value " annoying " ) < > " . "
-- ]
-- , Help.optionDescription ["--silent", "-s"]
-- (silentDescription "quiet")
, Help.optionDescription [ " --quiet " , " -q " ]
-- (silentDescription "silent")
-- , Help.optionDescription ["--colo[u]r=WHEN"]
-- [ "Set", Help.metavar "WHEN"
-- , Pretty.reflow "colourised output should be produced. Possible"
-- , Pretty.reflow "values of"
-- , Help.metavar "WHEN", "are"
, Pretty.squotes ( Help.value " always " ) < > " , "
, Pretty.squotes ( Help.value " auto " ) < > " , "
, " and " , Pretty.squotes ( Help.value " never " ) < > " . "
-- ]
-- , Help.optionDescription ["--no-colo[u]r"]
-- [ Pretty.reflow "Same as"
-- , Pretty.squotes (Help.longOption "colour=never") <> "."
-- ]
-- , Help.optionDescription ["--[no-]aliases"]
[ " Apply or ignore " , Help.metavar " SUBCOMMAND " , " aliases . "
, Pretty.reflow " This is useful when used from e.g. scripts to\
-- \ avoid issues with user defined aliases interfering with how\
-- \ the script behaves."
-- ]
-- , Help.optionDescription ["--version", "-V"]
-- [ Pretty.reflow "Print version information to stdout and exit."
-- ]
-- , Help.optionDescription ["--help", "-h"]
-- [ Pretty.reflow "Print this help and exit."
-- ]
-- ]
, Help.section ( Help.metavar " SUBCOMMAND " < > " : " )
-- [ Pretty.reflow "Name of either internal or external subcommand."
-- ]
-- , ""
-- ]
where
-- silentDescription altOpt =
-- [ "Silent mode. Suppress normal diagnostic or result output. Same as "
-- , Pretty.squotes (Help.longOption altOpt) <> ",", "and"
-- , Pretty.squotes (Help.longOption "verbosity=silent") <> "."
-- ]
defaultDescription :: Annotated Text
defaultDescription = "Toolset of commands for working developer."
subcommandArguments =
brackets [metavar "SUBCOMMAND_ARGUMENTS"]
| null | https://raw.githubusercontent.com/trskop/command-wrapper/4f2e2e1f63a3296ccfad9f216d75a708969890ed/command-wrapper-core/src/CommandWrapper/Core/Help/Message.hs | haskell | |
Module: $Header$
Description: Experiment to make help messages easier to create.
Maintainer:
Stability: experimental
Experiment to make help messages easier to create. Highly experimental!
* Combinators
* Rendering
** IO
TODO: TMP
a special meaning. Better encoding would be desirable, however, that will
complicate the implementation at the moment.
| @\\s -> 'Annotated'{'annotation' = 'Plain', 'content' = 'fromString' s}@
{{{ Combinators ------------------------------------------------------------
|
>>> longOption "foo" :: Annotated Text
|
>>> shortOption 'f' :: Annotated Text
| @['metavar' \"SUBCOMMAND\"]@
| @'metavar' \"SUBCOMMAND\"@
}}} Combinators ------------------------------------------------------------
{{{ Rendering --------------------------------------------------------------
{{{ I/O --------------------------------------------------------------------
}}} I/O --------------------------------------------------------------------
}}} Rendering --------------------------------------------------------------
[ Help.optionDescription ["-v"]
, Pretty.reflow "multiple times."
]
, Help.optionDescription ["--verbosity=VERBOSITY"]
[ Pretty.reflow "Set verbosity level to"
, Help.metavar "VERBOSITY" <> "."
, Pretty.reflow "Possible values of"
, Help.metavar "VERBOSITY", "are"
, "and"
]
, Help.optionDescription ["--silent", "-s"]
(silentDescription "quiet")
(silentDescription "silent")
, Help.optionDescription ["--colo[u]r=WHEN"]
[ "Set", Help.metavar "WHEN"
, Pretty.reflow "colourised output should be produced. Possible"
, Pretty.reflow "values of"
, Help.metavar "WHEN", "are"
]
, Help.optionDescription ["--no-colo[u]r"]
[ Pretty.reflow "Same as"
, Pretty.squotes (Help.longOption "colour=never") <> "."
]
, Help.optionDescription ["--[no-]aliases"]
\ avoid issues with user defined aliases interfering with how\
\ the script behaves."
]
, Help.optionDescription ["--version", "-V"]
[ Pretty.reflow "Print version information to stdout and exit."
]
, Help.optionDescription ["--help", "-h"]
[ Pretty.reflow "Print this help and exit."
]
]
[ Pretty.reflow "Name of either internal or external subcommand."
]
, ""
]
silentDescription altOpt =
[ "Silent mode. Suppress normal diagnostic or result output. Same as "
, Pretty.squotes (Help.longOption altOpt) <> ",", "and"
, Pretty.squotes (Help.longOption "verbosity=silent") <> "."
] | Copyright : ( c ) 2019 - 2020
License : BSD3
Portability : GHC specific language extensions .
module CommandWrapper.Core.Help.Message
( Annotation(..)
, Annotated(..)
, HelpMessage(..)
, Paragraph
, Usage
, longOption
, shortOption
, metavar
, command
, value
, (<+>)
, alternatives
, optionalAlternatives
, requiredAlternatives
, braces
, brackets
, squotes
, dquotes
, reflow
, subcommand
, optionalSubcommand
, optionalMetavar
, helpOptions
, renderAnnotated
, renderParagraph
, render
, defaultStyle
, hPutHelp
)
where
import Data.Bool (otherwise)
import Data.Char (Char)
import Data.Eq (Eq, (==))
import Data.Foldable (foldMap)
import Data.Function (($), (.))
import Data.Functor (Functor, (<$>), fmap)
import Data.Int (Int)
import qualified Data.List as List (intercalate, intersperse)
import Data.Maybe (Maybe(Just, Nothing), maybe)
import Data.Monoid (mconcat, mempty)
import Data.Semigroup (Semigroup, (<>))
import Data.String (IsString(fromString))
import GHC.Generics (Generic)
import System.IO (Handle, IO)
import Text.Show (Show)
import Data.Text (Text)
import qualified Data.Text as Text (null, uncons, unsnoc, words)
import Data.Text.Prettyprint.Doc (Doc, Pretty(pretty))
import qualified Data.Text.Prettyprint.Doc as Pretty
import qualified Data.Text.Prettyprint.Doc.Render.Terminal as Pretty
import qualified System.Console.Terminal.Size as Terminal (Window)
import CommandWrapper.Core.Config.ColourOutput (ColourOutput)
import CommandWrapper.Core.Message (hPutDoc)
data Annotation
= Plain
| Option
| Metavar
| Value
| Command
deriving stock (Eq, Generic, Show)
TODO : At the moment @Annotated Plain \"\"@ and @Annotated Plain \ " \"@ have
data Annotated a = Annotated
{ annotation :: Annotation
, content :: a
}
deriving stock (Eq, Functor, Generic, Show)
instance IsString s => IsString (Annotated s) where
fromString = Annotated Plain . fromString
type Paragraph a = [Annotated a]
type Usage a = [Annotated a]
data Section a = Section
{ name :: Paragraph a
, content :: [Paragraph a]
}
deriving stock (Eq, Functor, Generic, Show)
data HelpMessage a = HelpMessage
{ description :: Paragraph a
, usage :: [Usage a]
, sections :: [Section a]
, message :: [Paragraph a]
}
deriving stock (Eq, Functor, Generic, Show)
Annotated{annotation = Option , content = " --foo " }
longOption :: (IsString s, Semigroup s) => s -> Annotated s
longOption content = Annotated
{ annotation = Option
, content = "--" <> content
}
Annotated{annotation = Option , content = " -f " }
shortOption :: IsString s => Char -> Annotated s
shortOption c = Annotated
{ annotation = Option
, content = fromString ('-' : [c])
}
metavar :: s -> Annotated s
metavar = Annotated Metavar
command :: s -> Annotated s
command = Annotated Command
value :: s -> Annotated s
value = Annotated Command
(<+>) :: IsString s => [Annotated s] -> [Annotated s] -> [Annotated s]
l <+> r = l <> [""] <> r
brackets :: IsString s => [Annotated s] -> [Annotated s]
brackets c = "[" : c <> ["]"]
braces :: IsString s => [Annotated s] -> [Annotated s]
braces c = "{" : c <> ["}"]
squotes :: IsString s => [Annotated s] -> [Annotated s]
squotes c = "'" : c <> ["'"]
dquotes :: IsString s => [Annotated s] -> [Annotated s]
dquotes c = "\"" : c <> ["\""]
alternatives :: IsString s => [[Annotated s]] -> [Annotated s]
alternatives = List.intercalate ["|"]
optionalAlternatives :: IsString s => [[Annotated s]] -> [Annotated s]
optionalAlternatives = brackets . alternatives
requiredAlternatives :: IsString s => [[Annotated s]] -> [Annotated s]
requiredAlternatives = braces . alternatives
reflow :: Paragraph Text -> Paragraph Text
reflow = foldMap words
where
words :: Annotated Text -> [Annotated Text]
words a@Annotated{..} = case annotation of
Plain
| Text.null content -> [a]
| content == " " -> [a]
| otherwise -> mconcat
[ preserveSpaceAtTheBeginning content
, Annotated Plain <$> List.intersperse "" (Text.words content)
, preserveSpaceAtTheEnd content
]
Option -> [a]
Metavar -> [a]
Value -> [a]
Command -> [a]
where
preserveSpaceAtTheBeginning t = case Text.uncons t of
Nothing -> []
Just (' ', _) -> [Annotated Plain ""]
_ -> []
preserveSpaceAtTheEnd t = case Text.unsnoc t of
Nothing -> []
Just (_, ' ') -> [Annotated Plain ""]
_ -> []
subcommand :: IsString s => [Annotated s]
subcommand = [metavar "SUBCOMMAND"]
optionalSubcommand :: IsString s => [Annotated s]
optionalSubcommand = brackets subcommand
optionalMetavar :: IsString s => s -> [Annotated s]
optionalMetavar s = brackets [metavar s]
helpOptions :: (IsString s, Semigroup s) => [Annotated s]
helpOptions = alternatives
[ [longOption "help"]
, [shortOption 'h']
]
renderAnnotated :: (Eq a, IsString a, Pretty a) => Annotated a -> Doc Annotation
renderAnnotated Annotated{..} = case annotation of
Plain
| content == "" ->
Pretty.softline
| content == " " ->
" "
| otherwise ->
Pretty.annotate annotation (pretty content)
_ ->
Pretty.annotate annotation (pretty content)
renderParagraph :: Paragraph Text -> Doc Annotation
renderParagraph = foldMap renderAnnotated . reflow
render :: HelpMessage Text -> Doc Annotation
render HelpMessage{..} = Pretty.vsep
[ renderParagraph description
, ""
, renderSection "Usage:" (usage)
, Pretty.vsep (renderSections sections)
, Pretty.vsep (renderParagraph <$> message)
]
where
renderSection :: Doc Annotation -> [Paragraph Text] -> Doc Annotation
renderSection d ds =
Pretty.nest 2 $ Pretty.vsep $ d : "" : (fmap renderParagraph ds <> [""])
renderSections :: [Section Text] -> [Doc Annotation]
renderSections = fmap \Section{..} ->
renderSection (renderParagraph name) content
defaultStyle :: Annotation -> Pretty.AnsiStyle
defaultStyle = \case
Plain -> mempty
Option -> Pretty.colorDull Pretty.Green
Metavar -> Pretty.colorDull Pretty.Green
Value -> Pretty.colorDull Pretty.Green
Command -> Pretty.color Pretty.Magenta
hPutHelp
:: (Maybe (Terminal.Window Int) -> Pretty.LayoutOptions)
-> (Annotation -> Pretty.AnsiStyle)
-> ColourOutput
-> Handle
-> HelpMessage Text
-> IO ()
hPutHelp mkLayoutOptions style colourOutput h =
hPutDoc mkLayoutOptions style colourOutput h . render
helpMessage :: Text -> Maybe Text -> HelpMessage Text
helpMessage usedName description = HelpMessage
{ description = [maybe defaultDescription (Annotated Plain) description]
, usage =
[ [Annotated Plain usedName] <+> subcommand <+> subcommandArguments
, [Annotated Plain usedName] <+> ["help"]
<+> optionalMetavar "HELP_OPTIONS"
<+> optionalSubcommand
, [Annotated Plain usedName] <+> ["config"]
<+> optionalMetavar "CONFIG_OPTIONS"
<+> optionalSubcommand
, [Annotated Plain usedName] <+> ["version"]
<+> optionalMetavar "VERSION_OPTIONS"
, [Annotated Plain usedName] <+> ["completion"]
<+> optionalMetavar "COMPLETION_OPTIONS"
, [Annotated Plain usedName] <+> requiredAlternatives
[ [longOption "version"]
, [shortOption 'V']
]
, [Annotated Plain usedName] <+> braces helpOptions
]
, sections = []
, message = []
}
, Help.section ( Pretty.annotate Help.dullGreen " GLOBAL_OPTIONS " < > " : " )
[ Pretty.reflow " Increment verbosity by one level . Can be used "
, Pretty.squotes ( Help.value " silent " ) < > " , "
, Pretty.squotes ( Help.value " normal " ) < > " , "
, Pretty.squotes ( Help.value " verbose " ) < > " , "
, Pretty.squotes ( Help.value " annoying " ) < > " . "
, Help.optionDescription [ " --quiet " , " -q " ]
, Pretty.squotes ( Help.value " always " ) < > " , "
, Pretty.squotes ( Help.value " auto " ) < > " , "
, " and " , Pretty.squotes ( Help.value " never " ) < > " . "
[ " Apply or ignore " , Help.metavar " SUBCOMMAND " , " aliases . "
, Pretty.reflow " This is useful when used from e.g. scripts to\
, Help.section ( Help.metavar " SUBCOMMAND " < > " : " )
where
defaultDescription :: Annotated Text
defaultDescription = "Toolset of commands for working developer."
subcommandArguments =
brackets [metavar "SUBCOMMAND_ARGUMENTS"]
|
e62bac9f8be61fae6b02a3d7e9d5bfc0791c323e9f782cb3b8326b52ef62d48e | RefactoringTools/HaRe | Overload.hs | module Overload where
import Maybe(isJust)
class ToBool a where toBool :: a -> Bool
instance ToBool (Maybe a) where toBool = maybeToBool
maybeToBool = isJust
assert Trivial = {True} === {True}
assert Simple = {maybeToBool (Just 'a')} === {True}
assert Overloaded = {toBool (Just 'a')} === {True}
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/property/tests/Overload.hs | haskell | module Overload where
import Maybe(isJust)
class ToBool a where toBool :: a -> Bool
instance ToBool (Maybe a) where toBool = maybeToBool
maybeToBool = isJust
assert Trivial = {True} === {True}
assert Simple = {maybeToBool (Just 'a')} === {True}
assert Overloaded = {toBool (Just 'a')} === {True}
| |
f69cd86949333a8247933ee24208443f351565b89b9328ad320eb6b34ce78737 | heechul/crest-z3 | cabs.ml |
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not 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 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 .
*
*
* Copyright (c) 2001-2002,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not 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.
*
*)
* This file was originally part of frontc 2.0 , and has been
* extensively changed since .
* *
* * 1.0 3.22.99 Hugues Cassé First version .
* * 2.0 George Necula 12/12/00 : Many extensions
*
* extensively changed since.
**
** 1.0 3.22.99 Hugues Cassé First version.
** 2.0 George Necula 12/12/00: Many extensions
**)
(*
** Types
*)
type cabsloc = {
lineno : int;
filename: string;
byteno: int;
ident : int;
}
Merge all specifiers into one type
Type specifier ISO 6.7.2
| Tchar
| Tbool
| Tshort
| Tint
| Tlong
| Tint64
| Tfloat
| Tdouble
| Tsigned
| Tunsigned
| Tnamed of string
each of the following three kinds of specifiers contains a field
* or item list iff it corresponds to a definition ( as opposed to
* a forward declaration or simple reference to the type ) ; they
* also have a list of _ _ that appeared between the
* keyword and the type name ( definitions only )
* or item list iff it corresponds to a definition (as opposed to
* a forward declaration or simple reference to the type); they
* also have a list of __attribute__s that appeared between the
* keyword and the type name (definitions only) *)
| Tstruct of string * field_group list option * attribute list
| Tunion of string * field_group list option * attribute list
| Tenum of string * enum_item list option * attribute list
GCC _ _ typeof _ _
GCC _ _ typeof _ _
and storage =
NO_STORAGE | AUTO | STATIC | EXTERN | REGISTER
and funspec =
INLINE | VIRTUAL | EXPLICIT
and cvspec =
CV_CONST | CV_VOLATILE | CV_RESTRICT
(* Type specifier elements. These appear at the start of a declaration *)
(* Everywhere they appear in this file, they appear as a 'spec_elem list', *)
(* which is not interpreted by cabs -- rather, this "word soup" is passed *)
(* on to the compiler. Thus, we can represent e.g. 'int long float x' even *)
(* though the compiler will of course choke. *)
and spec_elem =
SpecTypedef
| SpecCV of cvspec (* const/volatile *)
| SpecAttr of attribute (* __attribute__ *)
| SpecStorage of storage
| SpecInline
| SpecType of typeSpecifier
| SpecPattern of string (* specifier pattern variable *)
(* decided to go ahead and replace 'spec_elem list' with specifier *)
and specifier = spec_elem list
Declarator type . They modify the base type given in the specifier . Keep
* them in the order as they are printed ( this means that the top level
* constructor for ARRAY and PTR is the inner - level in the meaning of the
* declared type )
* them in the order as they are printed (this means that the top level
* constructor for ARRAY and PTR is the inner-level in the meaning of the
* declared type) *)
and decl_type =
| JUSTBASE (* Prints the declared name *)
| PARENTYPE of attribute list * decl_type * attribute list
Prints " ( ) " .
* are attributes of the
* declared identifier and it is as
* if they appeared at the very end
* of the declarator . attrs1 can
* contain attributes for the
* identifier or attributes for the
* enclosing type .
* attrs2 are attributes of the
* declared identifier and it is as
* if they appeared at the very end
* of the declarator. attrs1 can
* contain attributes for the
* identifier or attributes for the
* enclosing type. *)
| ARRAY of decl_type * attribute list * expression
Prints " decl [ attrs exp ] " .
* is never a PTR .
* decl is never a PTR. *)
Prints " * "
| PROTO of decl_type * single_name list * bool
Prints " ( args [ , ... ] ) " .
* is never a PTR .
* decl is never a PTR.*)
(* The base type and the storage are common to all names. Each name might
* contain type or storage modifiers *)
(* e.g.: int x, y; *)
and name_group = specifier * name list
The optional expression is the bitfield
and field_group = specifier * (name * expression option) list
(* like name_group, except the declared variables are allowed to have initializers *)
(* e.g.: int x=1, y=2; *)
and init_name_group = specifier * init_name list
(* The decl_type is in the order in which they are printed. Only the name of
* the declared identifier is pulled out. The attributes are those that are
* printed after the declarator *)
(* e.g: in "int *x", "*x" is the declarator; "x" will be pulled out as *)
the string , and decl_type will be PTR ( [ ] , JUSTBASE )
and name = string * decl_type * attribute list * cabsloc
(* A variable declarator ("name") with an initializer *)
and init_name = name * init_expression
(* Single names are for declarations that cannot come in groups, like
* function parameters and functions *)
and single_name = specifier * name
and enum_item = string * expression * cabsloc
(*
** Declaration definition (at toplevel)
*)
and definition =
FUNDEF of single_name * block * cabsloc * cabsloc
| DECDEF of init_name_group * cabsloc (* global variable(s), or function prototype *)
| TYPEDEF of name_group * cabsloc
| ONLYTYPEDEF of specifier * cabsloc
| GLOBASM of string * cabsloc
| PRAGMA of expression * cabsloc
| LINKAGE of string * cabsloc * definition list (* extern "C" { ... } *)
toplevel form transformer , from the first definition to the
second group of definitions
| TRANSFORMER of definition * definition list * cabsloc
(* expression transformer: source and destination *)
| EXPRTRANSFORMER of expression * expression * cabsloc
(* the string is a file name, and then the list of toplevel forms *)
and file = string * definition list
(*
** statements
*)
A block contains a list of local label declarations ( GCC 's ( { _ _ label _ _
* l1 , l2 ; ... } ) ) , a list of definitions and a list of statements
* l1, l2; ... }) ) , a list of definitions and a list of statements *)
and block =
{ blabels: string list;
battrs: attribute list;
bstmts: statement list
}
GCC asm directives have lots of extra information to guide the optimizer
and asm_details =
{ aoutputs: (string option * string * expression) list; (* optional name, constraints and expressions for outputs *)
ainputs: (string option * string * expression) list; (* optional name, constraints and expressions for inputs *)
aclobbers: string list (* clobbered registers *)
}
and statement =
NOP of cabsloc
| COMPUTATION of expression * cabsloc
| BLOCK of block * cabsloc
| SEQUENCE of statement * statement * cabsloc
| IF of expression * statement * statement * cabsloc
| WHILE of expression * statement * cabsloc
| DOWHILE of expression * statement * cabsloc
| FOR of for_clause * expression * expression * statement * cabsloc
| BREAK of cabsloc
| CONTINUE of cabsloc
| RETURN of expression * cabsloc
| SWITCH of expression * statement * cabsloc
| CASE of expression * statement * cabsloc
| CASERANGE of expression * expression * statement * cabsloc
| DEFAULT of statement * cabsloc
| LABEL of string * statement * cabsloc
| GOTO of string * cabsloc
GCC 's " goto * exp "
| DEFINITION of definition (*definition or declaration of a variable or type*)
| ASM of attribute list * (* typically only volatile and const *)
string list * (* template *)
extra details to guide GCC 's optimizer
cabsloc
(** MS SEH *)
| TRY_EXCEPT of block * expression * block * cabsloc
| TRY_FINALLY of block * block * cabsloc
and for_clause =
FC_EXP of expression
| FC_DECL of definition
(*
** Expressions
*)
and binary_operator =
ADD | SUB | MUL | DIV | MOD
| AND | OR
| BAND | BOR | XOR | SHL | SHR
| EQ | NE | LT | GT | LE | GE
| ASSIGN
| ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | MOD_ASSIGN
| BAND_ASSIGN | BOR_ASSIGN | XOR_ASSIGN | SHL_ASSIGN | SHR_ASSIGN
and unary_operator =
MINUS | PLUS | NOT | BNOT | MEMOF | ADDROF
| PREINCR | PREDECR | POSINCR | POSDECR
and expression =
NOTHING
| UNARY of unary_operator * expression
GCC 's & & Label
| BINARY of binary_operator * expression * expression
| QUESTION of expression * expression * expression
A CAST can actually be a constructor expression
| CAST of (specifier * decl_type) * init_expression
There is a special form of CALL in which the function called is
_ _ builtin_va_arg and the second argument is sizeof(T ) . This
should be printed as just T
__builtin_va_arg and the second argument is sizeof(T). This
should be printed as just T *)
| CALL of expression * expression list
| COMMA of expression list
| CONSTANT of constant
| PAREN of expression
| VARIABLE of string
| EXPR_SIZEOF of expression
| TYPE_SIZEOF of specifier * decl_type
| EXPR_ALIGNOF of expression
| TYPE_ALIGNOF of specifier * decl_type
| INDEX of expression * expression
| MEMBEROF of expression * string
| MEMBEROFPTR of expression * string
| GNU_BODY of block
| EXPR_PATTERN of string (* pattern variable, and name *)
and constant =
| CONST_INT of string (* the textual representation *)
| CONST_FLOAT of string (* the textual representaton *)
| CONST_CHAR of int64 list
| CONST_WCHAR of int64 list
| CONST_STRING of string
| CONST_WSTRING of int64 list
ww : wstrings are stored as an int64 list at this point because
* we might need to feed the wide characters piece - wise into an
* array initializer ( e.g. , wchar_t foo [ ] = L"E\xabcd " ;) . If that
* does n't happen we will convert it to an ( escaped ) string before
* passing it to .
* we might need to feed the wide characters piece-wise into an
* array initializer (e.g., wchar_t foo[] = L"E\xabcd";). If that
* doesn't happen we will convert it to an (escaped) string before
* passing it to Cil. *)
and init_expression =
| NO_INIT
| SINGLE_INIT of expression
| COMPOUND_INIT of (initwhat * init_expression) list
and initwhat =
NEXT_INIT
| INFIELD_INIT of string * initwhat
| ATINDEX_INIT of expression * initwhat
| ATINDEXRANGE_INIT of expression * expression
(* Each attribute has a name and some
* optional arguments *)
and attribute = string * expression list
| null | https://raw.githubusercontent.com/heechul/crest-z3/cfcebadddb5e9d69e9956644fc37b46f6c2a21a0/cil/src/frontc/cabs.ml | ocaml |
** Types
Type specifier elements. These appear at the start of a declaration
Everywhere they appear in this file, they appear as a 'spec_elem list',
which is not interpreted by cabs -- rather, this "word soup" is passed
on to the compiler. Thus, we can represent e.g. 'int long float x' even
though the compiler will of course choke.
const/volatile
__attribute__
specifier pattern variable
decided to go ahead and replace 'spec_elem list' with specifier
Prints the declared name
The base type and the storage are common to all names. Each name might
* contain type or storage modifiers
e.g.: int x, y;
like name_group, except the declared variables are allowed to have initializers
e.g.: int x=1, y=2;
The decl_type is in the order in which they are printed. Only the name of
* the declared identifier is pulled out. The attributes are those that are
* printed after the declarator
e.g: in "int *x", "*x" is the declarator; "x" will be pulled out as
A variable declarator ("name") with an initializer
Single names are for declarations that cannot come in groups, like
* function parameters and functions
** Declaration definition (at toplevel)
global variable(s), or function prototype
extern "C" { ... }
expression transformer: source and destination
the string is a file name, and then the list of toplevel forms
** statements
optional name, constraints and expressions for outputs
optional name, constraints and expressions for inputs
clobbered registers
definition or declaration of a variable or type
typically only volatile and const
template
* MS SEH
** Expressions
pattern variable, and name
the textual representation
the textual representaton
Each attribute has a name and some
* optional arguments |
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not 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 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 .
*
*
* Copyright (c) 2001-2002,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not 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.
*
*)
* This file was originally part of frontc 2.0 , and has been
* extensively changed since .
* *
* * 1.0 3.22.99 Hugues Cassé First version .
* * 2.0 George Necula 12/12/00 : Many extensions
*
* extensively changed since.
**
** 1.0 3.22.99 Hugues Cassé First version.
** 2.0 George Necula 12/12/00: Many extensions
**)
type cabsloc = {
lineno : int;
filename: string;
byteno: int;
ident : int;
}
Merge all specifiers into one type
Type specifier ISO 6.7.2
| Tchar
| Tbool
| Tshort
| Tint
| Tlong
| Tint64
| Tfloat
| Tdouble
| Tsigned
| Tunsigned
| Tnamed of string
each of the following three kinds of specifiers contains a field
* or item list iff it corresponds to a definition ( as opposed to
* a forward declaration or simple reference to the type ) ; they
* also have a list of _ _ that appeared between the
* keyword and the type name ( definitions only )
* or item list iff it corresponds to a definition (as opposed to
* a forward declaration or simple reference to the type); they
* also have a list of __attribute__s that appeared between the
* keyword and the type name (definitions only) *)
| Tstruct of string * field_group list option * attribute list
| Tunion of string * field_group list option * attribute list
| Tenum of string * enum_item list option * attribute list
GCC _ _ typeof _ _
GCC _ _ typeof _ _
and storage =
NO_STORAGE | AUTO | STATIC | EXTERN | REGISTER
and funspec =
INLINE | VIRTUAL | EXPLICIT
and cvspec =
CV_CONST | CV_VOLATILE | CV_RESTRICT
and spec_elem =
SpecTypedef
| SpecStorage of storage
| SpecInline
| SpecType of typeSpecifier
and specifier = spec_elem list
Declarator type . They modify the base type given in the specifier . Keep
* them in the order as they are printed ( this means that the top level
* constructor for ARRAY and PTR is the inner - level in the meaning of the
* declared type )
* them in the order as they are printed (this means that the top level
* constructor for ARRAY and PTR is the inner-level in the meaning of the
* declared type) *)
and decl_type =
| PARENTYPE of attribute list * decl_type * attribute list
Prints " ( ) " .
* are attributes of the
* declared identifier and it is as
* if they appeared at the very end
* of the declarator . attrs1 can
* contain attributes for the
* identifier or attributes for the
* enclosing type .
* attrs2 are attributes of the
* declared identifier and it is as
* if they appeared at the very end
* of the declarator. attrs1 can
* contain attributes for the
* identifier or attributes for the
* enclosing type. *)
| ARRAY of decl_type * attribute list * expression
Prints " decl [ attrs exp ] " .
* is never a PTR .
* decl is never a PTR. *)
Prints " * "
| PROTO of decl_type * single_name list * bool
Prints " ( args [ , ... ] ) " .
* is never a PTR .
* decl is never a PTR.*)
and name_group = specifier * name list
The optional expression is the bitfield
and field_group = specifier * (name * expression option) list
and init_name_group = specifier * init_name list
the string , and decl_type will be PTR ( [ ] , JUSTBASE )
and name = string * decl_type * attribute list * cabsloc
and init_name = name * init_expression
and single_name = specifier * name
and enum_item = string * expression * cabsloc
and definition =
FUNDEF of single_name * block * cabsloc * cabsloc
| TYPEDEF of name_group * cabsloc
| ONLYTYPEDEF of specifier * cabsloc
| GLOBASM of string * cabsloc
| PRAGMA of expression * cabsloc
toplevel form transformer , from the first definition to the
second group of definitions
| TRANSFORMER of definition * definition list * cabsloc
| EXPRTRANSFORMER of expression * expression * cabsloc
and file = string * definition list
A block contains a list of local label declarations ( GCC 's ( { _ _ label _ _
* l1 , l2 ; ... } ) ) , a list of definitions and a list of statements
* l1, l2; ... }) ) , a list of definitions and a list of statements *)
and block =
{ blabels: string list;
battrs: attribute list;
bstmts: statement list
}
GCC asm directives have lots of extra information to guide the optimizer
and asm_details =
}
and statement =
NOP of cabsloc
| COMPUTATION of expression * cabsloc
| BLOCK of block * cabsloc
| SEQUENCE of statement * statement * cabsloc
| IF of expression * statement * statement * cabsloc
| WHILE of expression * statement * cabsloc
| DOWHILE of expression * statement * cabsloc
| FOR of for_clause * expression * expression * statement * cabsloc
| BREAK of cabsloc
| CONTINUE of cabsloc
| RETURN of expression * cabsloc
| SWITCH of expression * statement * cabsloc
| CASE of expression * statement * cabsloc
| CASERANGE of expression * expression * statement * cabsloc
| DEFAULT of statement * cabsloc
| LABEL of string * statement * cabsloc
| GOTO of string * cabsloc
GCC 's " goto * exp "
extra details to guide GCC 's optimizer
cabsloc
| TRY_EXCEPT of block * expression * block * cabsloc
| TRY_FINALLY of block * block * cabsloc
and for_clause =
FC_EXP of expression
| FC_DECL of definition
and binary_operator =
ADD | SUB | MUL | DIV | MOD
| AND | OR
| BAND | BOR | XOR | SHL | SHR
| EQ | NE | LT | GT | LE | GE
| ASSIGN
| ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | MOD_ASSIGN
| BAND_ASSIGN | BOR_ASSIGN | XOR_ASSIGN | SHL_ASSIGN | SHR_ASSIGN
and unary_operator =
MINUS | PLUS | NOT | BNOT | MEMOF | ADDROF
| PREINCR | PREDECR | POSINCR | POSDECR
and expression =
NOTHING
| UNARY of unary_operator * expression
GCC 's & & Label
| BINARY of binary_operator * expression * expression
| QUESTION of expression * expression * expression
A CAST can actually be a constructor expression
| CAST of (specifier * decl_type) * init_expression
There is a special form of CALL in which the function called is
_ _ builtin_va_arg and the second argument is sizeof(T ) . This
should be printed as just T
__builtin_va_arg and the second argument is sizeof(T). This
should be printed as just T *)
| CALL of expression * expression list
| COMMA of expression list
| CONSTANT of constant
| PAREN of expression
| VARIABLE of string
| EXPR_SIZEOF of expression
| TYPE_SIZEOF of specifier * decl_type
| EXPR_ALIGNOF of expression
| TYPE_ALIGNOF of specifier * decl_type
| INDEX of expression * expression
| MEMBEROF of expression * string
| MEMBEROFPTR of expression * string
| GNU_BODY of block
and constant =
| CONST_CHAR of int64 list
| CONST_WCHAR of int64 list
| CONST_STRING of string
| CONST_WSTRING of int64 list
ww : wstrings are stored as an int64 list at this point because
* we might need to feed the wide characters piece - wise into an
* array initializer ( e.g. , wchar_t foo [ ] = L"E\xabcd " ;) . If that
* does n't happen we will convert it to an ( escaped ) string before
* passing it to .
* we might need to feed the wide characters piece-wise into an
* array initializer (e.g., wchar_t foo[] = L"E\xabcd";). If that
* doesn't happen we will convert it to an (escaped) string before
* passing it to Cil. *)
and init_expression =
| NO_INIT
| SINGLE_INIT of expression
| COMPOUND_INIT of (initwhat * init_expression) list
and initwhat =
NEXT_INIT
| INFIELD_INIT of string * initwhat
| ATINDEX_INIT of expression * initwhat
| ATINDEXRANGE_INIT of expression * expression
and attribute = string * expression list
|
33d948c656078eca2de35a3193af96d3610e99f469d928a659bb45fe7c14bd38 | jariazavalverde/blog | programacion-a-nivel-de-tipo.hs | # LANGUAGE DataKinds , KindSignatures , GADTs , TypeFamilies , StandaloneDeriving #
data Nat = Zero | Succ Nat
data Vector (n :: Nat) (a :: *) where
VNil :: Vector 'Zero a
VCons :: a -> Vector n a -> Vector ('Succ n) a
deriving instance Show a => Show (Vector n a)
type family Add (n :: Nat) (m :: Nat) where
Add 'Zero n = n
Add ('Succ n) m = 'Succ (Add n m)
tailv :: Vector ('Succ n) a -> Vector n a
tailv (VCons _ xs) = xs
appendv :: Vector n a -> Vector m a -> Vector (Add n m) a
appendv VNil ys = ys
appendv (VCons x xs) ys = VCons x (appendv xs ys)
| null | https://raw.githubusercontent.com/jariazavalverde/blog/c8bbfc4394b077e8f9fc34593344d64f3a94153e/src/programacion-a-nivel-de-tipo/programacion-a-nivel-de-tipo.hs | haskell | # LANGUAGE DataKinds , KindSignatures , GADTs , TypeFamilies , StandaloneDeriving #
data Nat = Zero | Succ Nat
data Vector (n :: Nat) (a :: *) where
VNil :: Vector 'Zero a
VCons :: a -> Vector n a -> Vector ('Succ n) a
deriving instance Show a => Show (Vector n a)
type family Add (n :: Nat) (m :: Nat) where
Add 'Zero n = n
Add ('Succ n) m = 'Succ (Add n m)
tailv :: Vector ('Succ n) a -> Vector n a
tailv (VCons _ xs) = xs
appendv :: Vector n a -> Vector m a -> Vector (Add n m) a
appendv VNil ys = ys
appendv (VCons x xs) ys = VCons x (appendv xs ys)
| |
d161ad4556671c6ed6227d3159ecc901c9c2ee3ec634fd671d50f2aa68b1b01d | robert-strandh/CLIMatis | rigidity.lisp | (in-package #:rigidity)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Utilities .
;;; Check whether an object is a proper list. We expect the list to
;;; be relatively short, so there is no point in doing anything fancy.
;;; Loop over the CONS cells of the list until either the end of the
;;; list is found, or we see a cell that we have already seen. If se
;;; see a cell we have already seen, or we reach the end of the list
;;; and it is not NIL, then we do not have a proper list. If we reach
NIL at the end of the slist without having seen a cell twice , then
;;; we have a proper list.
(defun proper-list-p (object)
(let ((cells '())
(rest object))
(loop until (atom rest)
do (if (member rest cells :test #'eq)
(return-from proper-list-p nil)
(progn (push rest cells)
(pop rest))))
(null rest)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Rigidity function.
;;;; A rigidity function gives a force as a function of a size.
;;;;
;;;; The size is a non-negative integer. The force is a rational
;;;; number.
;;;;
A rigidity function is represented as a list with at least two
;;;; elements. The last element is a positive rational number, and it
;;;; indicates a slope of the rigidity for large values of the size.
;;;; Every element except the last is a CONS where the CAR is a size
;;;; (a non-negative rational) and the CDR is the force at that size.
;;;; The CAR of the first CONS of a rigidity function is always 0.
;;;; The CDR of the first CONS of a rigidity function is a rational
;;;; that is 0 or negative. The CONSes of a rigidity function are in
;;;; strictly increasing order with respect to the size. The function
;;;; is strictly increasing, so that the CONSes of a rigidity function
;;;; are in strictly increasing order also with respect to the forces.
;;;; A negative force means a force toward expansion, and a positive
;;;; force means a force toward contraction.
;;; Accessors for rigidity functions.
(defun pointp (item)
(and (consp item)
(rationalp (car item))
(not (minusp (car item)))
(rationalp (cdr item))))
(defun make-point (size force)
(cons size force))
(defun slopep (item)
(and (rationalp item)
(plusp item)))
(defun size (point)
(car point))
(defun force (point)
(cdr point))
;;; Check that some object is a rigidity function. We handle circular
;;; lists without going into an infinite computation, by checking that
two consecutive conses represent strictly increasing values . This
;;; can not be the case if the list is circular.
(defun rigidity-function-p (rigidity-function)
;; The argument to the auxilary function is always a CONS. In
;; addition, the CAR of that CONS is known to be a valid point, in
;; that the size is a non-netagive rational number, and the force is
;; a rational number.
(labels ((aux (fun)
(and (consp (cdr fun))
(let ((second (second fun)))
(or (and (slopep second)
(null (cddr fun)))
(let ((first (first fun)))
(and (pointp second)
(> (size second) (size first))
(> (force second) (force first))
(aux (cdr fun)))))))))
;; Check that we have a CONS, that the CAR of that CONS is a valid
first point , and then call the auxiliary function to check the
;; rest.
(and (consp rigidity-function)
(let ((first (first rigidity-function)))
(pointp first)
(zerop (size first))
(not (plusp (force first)))
(aux rigidity-function)))))
;;; For a given rigidity-function and a given size, return the force
;;; at that size. The size is a non-negative rational number. We do
;;; not expect this function to be used in an inner loop, so we take
;;; the freedom to check that we have a valid rigidity-function.
(defun force-at-size (rigidity-function size)
(assert (rigidity-function-p rigidity-function))
(assert (rationalp size))
(assert (not (minusp size)))
(loop until (or (slopep (second rigidity-function))
(> (size (second rigidity-function)) size))
do (pop rigidity-function))
(let* ((s0 (size (first rigidity-function)))
(f0 (force (first rigidity-function)))
(slope (if (slopep (second rigidity-function))
(second rigidity-function)
(let* ((s1 (size (second rigidity-function)))
(f1 (force (second rigidity-function))))
(/ (- f1 f0) (- s1 s0))))))
(+ f0 (* (- size s0) slope))))
;;; For a given rigidity-function and a given force, return the size
;;; at that force. The force is a rational number. We do not expect
;;; this function to be used in an inner loop, so we take the freedom
;;; to check that we have a valid rigidity-function.
(defun size-at-force (rigidity-function force)
(assert (rigidity-function-p rigidity-function))
(assert (rationalp force))
(if (<= force (force (first rigidity-function)))
0
(progn
(loop until (or (slopep (second rigidity-function))
(> (force (second rigidity-function)) force))
do (pop rigidity-function))
(let* ((s0 (size (first rigidity-function)))
(f0 (force (first rigidity-function)))
(slope (if (slopep (second rigidity-function))
(second rigidity-function)
(let* ((s1 (size (second rigidity-function)))
(f1 (force (second rigidity-function))))
(/ (- f1 f0) (- s1 s0))))))
(+ s0 (/ (- force f0) slope))))))
;;; The natural size of a rigidity function is the size it takes
;;; on when the force is 0.
(defun natural-size (rigidity-function)
(size-at-force rigidity-function 0))
;;; For sufficiently large values (size or force), every rigidity
;;; function degenerates into the form ((SIZE . FORCE) SLOPE). When
that is the case , the function can be expressed in one of two
ways . The first way is FORCE = SLOPE * SIZE + ZERO - SIZE - FORCE .
;;; This way of expressing it is handy for expressing the parallel
combination of two or more functions , because then the combined
function can be expressed as the sum of the parameters SLOPE and
ZERO - SIZE - FORCE for each individual function . The second way of
;;; expressing it is SIZE = ISLOPE * FORCE + ZERO-FORCE-SIZE. When
;;; functions are combined serially, then this way is preferred,
because then , again , the parameters of each indificual function
;;; can just be summed up.
Use side effects to remove the first point of a rigidity function .
(defun eliminate-first-point (rigidity-function)
(setf (first rigidity-function) (second rigidity-function))
(setf (rest rigidity-function) (rest (rest rigidity-function))))
(defun combine-in-parallel (rigidity-functions)
(assert (proper-list-p rigidity-functions))
(assert (>= (length rigidity-functions) 1))
(assert (every #'rigidity-function-p rigidity-functions))
Slope of combination of all degenerate functions .
(slope 0)
Force at size 0 for combination of all degenerate
;; functions.
(zero-size-force 0)
;; We build the resulting function from the end, and then
;; reverse it right before returning it.
(reverse-result '()))
;; Make a copy of everything, because we side-effect the functions
;; as we process them.
(let ((funs (copy-tree rigidity-functions)))
Create the first point of the result as the sum of the forces
at size 0 of each function . Since every function starts with
;; a point at size 0, we can compute this value as the sum of
the forces of the first point of each function .
(push (make-point 0 (reduce #'+ funs :key (lambda (fun) (force (first fun)))))
reverse-result)
;; Pull out and combine all the degenerate functions.
(setf funs
(loop for fun in funs
if (slopep (second fun))
do (let* ((first (first fun))
(size (size first))
(force (force first)))
(incf slope (second fun))
(incf zero-size-force (- force (* (second fun) size))))
else
collect fun))
Now , the second item of every function is a point . Sort the
remaining functions by increasing size of the second point .
(setf funs (sort funs #'< :key (lambda (fun) (size (second fun)))))
Invariants : 1 . The next point to be determined has a size
that is strictly greater than the size of the first point of
each function . 2 . The second item of each function is a
point . 3 . The functions are in increasing order with respect
to the size of the second point .
(loop until (null funs)
do (let* ((size (size (second (car funs))))
(force (loop for fun in funs
sum (let* ((s0 (size (first fun)))
(f0 (force (first fun)))
(s1 (size (second fun)))
(f1 (force (second fun)))
(slope (/ (- f1 f0) (- s1 s0))))
(+ f0 (* (- size s0) slope))))))
;; We have computed another point, and store it.
(let ((dforce (+ (* slope size) zero-size-force)))
(push (make-point size (+ force dforce)) reverse-result))
;; Now an arbitrary number of functions that are
;; first on the list of remaining functions can have
second point with a size that we just handled .
Clearly , the first such function is one of them ,
;; but there can be more. Since the list is sorted,
they are all first . We process each such function
by removing the first point . If by doing that ,
;; the result is a degenerate function, we remove it
;; from the list, and add it to the global
;; parameters. If the result is not degenerate, we
;; merge it into the list so as to preserve invariant
number 3 .
(loop until (or (null funs)
(> (size (second (car funs))) size))
do (let ((fun (pop funs)))
(eliminate-first-point fun)
(if (slopep (second fun))
(let* ((first (first fun))
(size (size first))
(force (force first)))
(incf slope (second fun))
(incf zero-size-force
(- force (* (second fun) size))))
(setf funs (merge 'list (list fun) funs #'<
:key (lambda (fun)
(size (second fun))))))))))
;; When we come here, the list of non-degenerate functions is empty.
(push slope reverse-result)
(nreverse reverse-result))))
(defun combine-in-series (rigidity-functions)
(assert (proper-list-p rigidity-functions))
(assert (>= (length rigidity-functions) 1))
(assert (every #'rigidity-function-p rigidity-functions))
(let ((result '()))
;; Make a copy of everything, because we side-effect the functions
;; as we process them.
(let ((funs (copy-tree rigidity-functions)))
;; Reverse the list representing each each function.
(setf funs (mapcar #'reverse funs))
;; Determine the slope for large values of the size
(push (/ (loop for fun in funs sum (/ (car fun)))) result)
;; Sort by decreasing value of the force of the last point.
Recall that the last point is the second element of the list
;; representing the function.
(setf funs (sort funs #'> :key (lambda (fun) (force (second fun)))))
(loop until (null funs)
do (let* ((force (force (second (car funs))))
(size (loop for fun in funs
sum (let ((s (size (second fun)))
(f (force (second fun)))
(slope (car fun)))
(+ s (/ (- force f) slope))))))
;; We now have the sum of the sizes for the largest
;; force. We make another point out of that.
(push (make-point size force) result)
;; Now we need to remove the last point of every
;; function where the force of that point is the
;; force that we just handled. If the last point is
also the first point , then remove the function
;; altogether, because it can not longer contribute
to the size . If the last point is not the first
;; point, then replace the slope of the function by
;; the slope between the last and the next-to-last
;; point, and merge the function with the others to
;; preserve the order of the functions.
(loop until (or (null funs)
(< (force (second (car funs))) force))
do (let ((fun (pop funs)))
(unless (null (rest (rest fun)))
(let ((s1 (size (second fun)))
(f1 (force (second fun)))
(s0 (size (third fun)))
(f0 (force (third fun))))
(setf (first fun)
(/ (- f1 f0) (- s1 s0)))
(setf (rest fun) (rest (rest fun))))
(setf funs (merge 'list (list fun) funs #'>
:key (lambda (fun)
(force (second fun)))))))))))
result))
;;; Helper function. Return the difference between the largest and
;;; the smallest element in a list.
(defun max-min-diff (list)
(- (reduce #'max list) (reduce #'min list)))
;;; Helper function. Given a list of rigidity functions and a list of
;;; sizes, return a list of forces, one for each function at its size.
(defun compute-forces (rigidity-functions sizes)
(mapcar #'force-at-size rigidity-functions sizes))
;;; Helper function. Take a list of rigidity functions and a list of
;;; sizes for each one, and compute the total badness of the
;;; combination as the difference between the maximum force of any
;;; rigidity function at its size and the minimum force of any
;;; rigidity function at its size.
(defun badness (rigidity-functions sizes)
(max-min-diff (compute-forces rigidity-functions sizes)))
;;; Helper function. Take a list and a position of that list, and
;;; return a new list, which is like the one passed as an argument,
except that the element in the position passed as the second
;;; argument has been incremented.
(defun add-one-to-pos (list pos)
(loop for i from 0
for element in list
collect (+ element (if (= i pos) 1 0))))
;;; Helper function. Take a list of rigidity functions and a list of
;;; current sizes, one for each rigidity function. Return a list that
is the same as the second one passed as an argument , except that
one position has been incremented by one in such a way that the
;;; resulting list respresents the best individual sizes for each
;;; rigidity function, given that the sum of the individual sizes of
;;; each rigidity function is the sum of the elements of the resulting
;;; list.
(defun add-one (rigidity-functions sizes)
(let ((min-badness (badness rigidity-functions (cons (1+ (car sizes)) (cdr sizes))))
(min-pos 0))
(loop for pos from 1 below (length sizes)
do (let ((new-badness (badness rigidity-functions (add-one-to-pos sizes pos))))
(when (< new-badness min-badness)
(setf min-badness new-badness)
(setf min-pos pos))))
(add-one-to-pos sizes min-pos)))
;;; Take a list of rigidity functions considered to be combined in
;;; series, and a total size for all of those functions. Return a
;;; list of non-negative integers, one for each function, in the same
;;; order as the initial functions, with the best size for each
;;; function. The sum of the integers in the resulting list is equal
;;; to the total size given as an argument.
;;;
;;; Warning, this function is currently extremely inefficient.
(defun sizes-in-series (rigidity-functions size)
(let ((sizes (make-list (length rigidity-functions) :initial-element 0)))
(loop repeat size
do (setf sizes (add-one rigidity-functions sizes)))
sizes))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Elementary functions.
(defparameter *rigid* 1000000)
(defparameter *elastic* (/ *rigid*))
(defun little-rigid (&key (factor 1))
(assert (rationalp factor))
(assert (plusp factor))
`((0 . 0) ,(* *elastic* factor)))
(defun very-rigid (natural-size &key (factor 1))
(assert (rationalp natural-size))
(assert (plusp natural-size))
(assert (rationalp factor))
(assert (plusp factor))
(let* ((rigidity (* *rigid* factor))
(zero-size-force (- (* rigidity natural-size))))
`((0 . ,zero-size-force) ,rigidity)))
(defun rigid-contract (natural-size &key (expand-factor 1) (contract-factor 1))
(assert (rationalp natural-size))
(assert (plusp natural-size))
(assert (rationalp expand-factor))
(assert (plusp expand-factor))
(assert (rationalp contract-factor))
(assert (plusp contract-factor))
(let* ((contract-rigidity (* *rigid* contract-factor))
(expand-rigidity (* *elastic* expand-factor))
(zero-size-force (- (* contract-rigidity natural-size))))
`((0 . ,zero-size-force) (,natural-size . 0) ,expand-rigidity)))
(defun rigid-expand (natural-size &key (expand-factor 1) (contract-factor 1))
(assert (rationalp natural-size))
(assert (plusp natural-size))
(assert (rationalp expand-factor))
(assert (plusp expand-factor))
(assert (rationalp contract-factor))
(assert (plusp contract-factor))
(let* ((contract-rigidity (* *elastic* contract-factor))
(expand-rigidity (* *rigid* expand-factor))
(zero-size-force (- (* contract-rigidity natural-size))))
`((0 . ,zero-size-force) (,natural-size . 0) ,expand-rigidity)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Test.
(defun random-non-negative-rational (n)
(let ((denominator (1+ (random 100))))
(/ (random (* n denominator)) denominator)))
(defun random-positive-rational (n)
(let ((denominator (1+ (random 100))))
(/ (1+ (random (* n denominator))) denominator)))
(defun random-rigidity-function ()
(let ((f (- (random-non-negative-rational 100)))
(s 0))
`(,(make-point s f)
,@(loop repeat (random 5)
collect (make-point (incf s (random-positive-rational 100))
(incf f (random-positive-rational 100))))
,(random-positive-rational 100))))
(defun test-little-rigid ()
(format t "little-rigid...")
(force-output)
(loop repeat 100000
do (let* ((factor (random-positive-rational 100))
(fun (little-rigid :factor factor))
(size (random-non-negative-rational 100)))
(assert (= (force-at-size fun size)
(* size factor *elastic*)))))
(format t "~%"))
(defun test-very-rigid ()
(format t "very-rigid...")
(force-output)
(loop repeat 100000
do (let* ((factor (random-positive-rational 100))
(natural-size (random-positive-rational 100))
(fun (very-rigid natural-size :factor factor))
(size (random-non-negative-rational 100))
(zero-size-force (- (* natural-size factor *rigid*))))
(assert (= (force-at-size fun size)
(+ (* size factor *rigid*) zero-size-force)))))
(format t "~%"))
(defun test-rigid-contract ()
(format t "rigid-contract...")
(force-output)
(loop repeat 100000
do (let* ((expand-factor (random-positive-rational 100))
(contract-factor (random-positive-rational 100))
(natural-size (random-positive-rational 100))
(fun (rigid-contract natural-size
:expand-factor expand-factor
:contract-factor contract-factor))
(fun1 (very-rigid natural-size :factor contract-factor))
(fun2 (little-rigid :factor expand-factor))
(size (random-non-negative-rational 100)))
(if (> size natural-size)
(assert (= (force-at-size fun size)
(force-at-size fun2 (- size natural-size))))
(assert (= (force-at-size fun size)
(force-at-size fun1 size))))))
(format t "~%"))
(defun test-rigid-expand ()
(format t "rigid-expand...")
(force-output)
(loop repeat 100000
do (let* ((expand-factor (random-positive-rational 100))
(contract-factor (random-positive-rational 100))
(natural-size (random-positive-rational 100))
(fun (rigid-expand natural-size
:expand-factor expand-factor
:contract-factor contract-factor))
(fun1 (little-rigid :factor contract-factor))
(fun2 (very-rigid natural-size :factor expand-factor))
(size (random-non-negative-rational 100)))
(if (> size natural-size)
(assert (= (force-at-size fun size)
(force-at-size fun2 size)))
(assert (= (- (force-at-size fun size)
(force-at-size fun 0))
(force-at-size fun1 size))))))
(format t "~%"))
(defun test-size-at-force ()
(format t "size-at-force...")
(force-output)
(loop repeat 100000
do (let ((fun (random-rigidity-function))
(size (random-non-negative-rational 100)))
(let ((force (force-at-size fun size)))
(assert (= size
(size-at-force fun force))))))
(format t "~%"))
(defun test-combine-in-parallel ()
(format t "combine-in-parallel...")
(force-output)
(loop repeat 100000
do (let* ((n (1+ (random 10)))
(funs (loop repeat n collect (random-rigidity-function)))
(combined (combine-in-parallel funs))
(max-size (reduce #'max funs :key (lambda (fun)
(size (car (last fun 2))))))
(size (random-non-negative-rational (+ 2 (* 2 (ceiling max-size))))))
(assert (= (force-at-size combined size)
(reduce #'+ funs :key (lambda (fun) (force-at-size fun size)))))))
(format t "~%"))
(defun test-combine-in-series ()
(format t "combine-in-series...")
(force-output)
(loop repeat 100000
do (let* ((n (1+ (random 10)))
(funs (loop repeat n collect (random-rigidity-function)))
(combined (combine-in-series funs))
(max-force (reduce #'max funs :key (lambda (fun)
(force (car (last fun 2))))))
(min-force (reduce #'min funs :key (lambda (fun)
(force (first fun)))))
(force (+ min-force (random-non-negative-rational
(1+ (round (- max-force min-force)))))))
(assert (= (size-at-force combined force)
(reduce #'+ funs :key (lambda (fun) (size-at-force fun force)))))))
(format t "~%"))
(defun run-test ()
(test-little-rigid)
(test-very-rigid)
(test-rigid-contract)
(test-rigid-expand)
(test-size-at-force)
(test-combine-in-parallel)
(test-combine-in-series))
| null | https://raw.githubusercontent.com/robert-strandh/CLIMatis/4949ddcc46d3f81596f956d12f64035e04589b29/Rigidity/rigidity.lisp | lisp |
Check whether an object is a proper list. We expect the list to
be relatively short, so there is no point in doing anything fancy.
Loop over the CONS cells of the list until either the end of the
list is found, or we see a cell that we have already seen. If se
see a cell we have already seen, or we reach the end of the list
and it is not NIL, then we do not have a proper list. If we reach
we have a proper list.
Rigidity function.
A rigidity function gives a force as a function of a size.
The size is a non-negative integer. The force is a rational
number.
elements. The last element is a positive rational number, and it
indicates a slope of the rigidity for large values of the size.
Every element except the last is a CONS where the CAR is a size
(a non-negative rational) and the CDR is the force at that size.
The CAR of the first CONS of a rigidity function is always 0.
The CDR of the first CONS of a rigidity function is a rational
that is 0 or negative. The CONSes of a rigidity function are in
strictly increasing order with respect to the size. The function
is strictly increasing, so that the CONSes of a rigidity function
are in strictly increasing order also with respect to the forces.
A negative force means a force toward expansion, and a positive
force means a force toward contraction.
Accessors for rigidity functions.
Check that some object is a rigidity function. We handle circular
lists without going into an infinite computation, by checking that
can not be the case if the list is circular.
The argument to the auxilary function is always a CONS. In
addition, the CAR of that CONS is known to be a valid point, in
that the size is a non-netagive rational number, and the force is
a rational number.
Check that we have a CONS, that the CAR of that CONS is a valid
rest.
For a given rigidity-function and a given size, return the force
at that size. The size is a non-negative rational number. We do
not expect this function to be used in an inner loop, so we take
the freedom to check that we have a valid rigidity-function.
For a given rigidity-function and a given force, return the size
at that force. The force is a rational number. We do not expect
this function to be used in an inner loop, so we take the freedom
to check that we have a valid rigidity-function.
The natural size of a rigidity function is the size it takes
on when the force is 0.
For sufficiently large values (size or force), every rigidity
function degenerates into the form ((SIZE . FORCE) SLOPE). When
This way of expressing it is handy for expressing the parallel
expressing it is SIZE = ISLOPE * FORCE + ZERO-FORCE-SIZE. When
functions are combined serially, then this way is preferred,
can just be summed up.
functions.
We build the resulting function from the end, and then
reverse it right before returning it.
Make a copy of everything, because we side-effect the functions
as we process them.
a point at size 0, we can compute this value as the sum of
Pull out and combine all the degenerate functions.
We have computed another point, and store it.
Now an arbitrary number of functions that are
first on the list of remaining functions can have
but there can be more. Since the list is sorted,
the result is a degenerate function, we remove it
from the list, and add it to the global
parameters. If the result is not degenerate, we
merge it into the list so as to preserve invariant
When we come here, the list of non-degenerate functions is empty.
Make a copy of everything, because we side-effect the functions
as we process them.
Reverse the list representing each each function.
Determine the slope for large values of the size
Sort by decreasing value of the force of the last point.
representing the function.
We now have the sum of the sizes for the largest
force. We make another point out of that.
Now we need to remove the last point of every
function where the force of that point is the
force that we just handled. If the last point is
altogether, because it can not longer contribute
point, then replace the slope of the function by
the slope between the last and the next-to-last
point, and merge the function with the others to
preserve the order of the functions.
Helper function. Return the difference between the largest and
the smallest element in a list.
Helper function. Given a list of rigidity functions and a list of
sizes, return a list of forces, one for each function at its size.
Helper function. Take a list of rigidity functions and a list of
sizes for each one, and compute the total badness of the
combination as the difference between the maximum force of any
rigidity function at its size and the minimum force of any
rigidity function at its size.
Helper function. Take a list and a position of that list, and
return a new list, which is like the one passed as an argument,
argument has been incremented.
Helper function. Take a list of rigidity functions and a list of
current sizes, one for each rigidity function. Return a list that
resulting list respresents the best individual sizes for each
rigidity function, given that the sum of the individual sizes of
each rigidity function is the sum of the elements of the resulting
list.
Take a list of rigidity functions considered to be combined in
series, and a total size for all of those functions. Return a
list of non-negative integers, one for each function, in the same
order as the initial functions, with the best size for each
function. The sum of the integers in the resulting list is equal
to the total size given as an argument.
Warning, this function is currently extremely inefficient.
Elementary functions.
Test. | (in-package #:rigidity)
Utilities .
NIL at the end of the slist without having seen a cell twice , then
(defun proper-list-p (object)
(let ((cells '())
(rest object))
(loop until (atom rest)
do (if (member rest cells :test #'eq)
(return-from proper-list-p nil)
(progn (push rest cells)
(pop rest))))
(null rest)))
A rigidity function is represented as a list with at least two
(defun pointp (item)
(and (consp item)
(rationalp (car item))
(not (minusp (car item)))
(rationalp (cdr item))))
(defun make-point (size force)
(cons size force))
(defun slopep (item)
(and (rationalp item)
(plusp item)))
(defun size (point)
(car point))
(defun force (point)
(cdr point))
two consecutive conses represent strictly increasing values . This
(defun rigidity-function-p (rigidity-function)
(labels ((aux (fun)
(and (consp (cdr fun))
(let ((second (second fun)))
(or (and (slopep second)
(null (cddr fun)))
(let ((first (first fun)))
(and (pointp second)
(> (size second) (size first))
(> (force second) (force first))
(aux (cdr fun)))))))))
first point , and then call the auxiliary function to check the
(and (consp rigidity-function)
(let ((first (first rigidity-function)))
(pointp first)
(zerop (size first))
(not (plusp (force first)))
(aux rigidity-function)))))
(defun force-at-size (rigidity-function size)
(assert (rigidity-function-p rigidity-function))
(assert (rationalp size))
(assert (not (minusp size)))
(loop until (or (slopep (second rigidity-function))
(> (size (second rigidity-function)) size))
do (pop rigidity-function))
(let* ((s0 (size (first rigidity-function)))
(f0 (force (first rigidity-function)))
(slope (if (slopep (second rigidity-function))
(second rigidity-function)
(let* ((s1 (size (second rigidity-function)))
(f1 (force (second rigidity-function))))
(/ (- f1 f0) (- s1 s0))))))
(+ f0 (* (- size s0) slope))))
(defun size-at-force (rigidity-function force)
(assert (rigidity-function-p rigidity-function))
(assert (rationalp force))
(if (<= force (force (first rigidity-function)))
0
(progn
(loop until (or (slopep (second rigidity-function))
(> (force (second rigidity-function)) force))
do (pop rigidity-function))
(let* ((s0 (size (first rigidity-function)))
(f0 (force (first rigidity-function)))
(slope (if (slopep (second rigidity-function))
(second rigidity-function)
(let* ((s1 (size (second rigidity-function)))
(f1 (force (second rigidity-function))))
(/ (- f1 f0) (- s1 s0))))))
(+ s0 (/ (- force f0) slope))))))
(defun natural-size (rigidity-function)
(size-at-force rigidity-function 0))
that is the case , the function can be expressed in one of two
ways . The first way is FORCE = SLOPE * SIZE + ZERO - SIZE - FORCE .
combination of two or more functions , because then the combined
function can be expressed as the sum of the parameters SLOPE and
ZERO - SIZE - FORCE for each individual function . The second way of
because then , again , the parameters of each indificual function
Use side effects to remove the first point of a rigidity function .
(defun eliminate-first-point (rigidity-function)
(setf (first rigidity-function) (second rigidity-function))
(setf (rest rigidity-function) (rest (rest rigidity-function))))
(defun combine-in-parallel (rigidity-functions)
(assert (proper-list-p rigidity-functions))
(assert (>= (length rigidity-functions) 1))
(assert (every #'rigidity-function-p rigidity-functions))
Slope of combination of all degenerate functions .
(slope 0)
Force at size 0 for combination of all degenerate
(zero-size-force 0)
(reverse-result '()))
(let ((funs (copy-tree rigidity-functions)))
Create the first point of the result as the sum of the forces
at size 0 of each function . Since every function starts with
the forces of the first point of each function .
(push (make-point 0 (reduce #'+ funs :key (lambda (fun) (force (first fun)))))
reverse-result)
(setf funs
(loop for fun in funs
if (slopep (second fun))
do (let* ((first (first fun))
(size (size first))
(force (force first)))
(incf slope (second fun))
(incf zero-size-force (- force (* (second fun) size))))
else
collect fun))
Now , the second item of every function is a point . Sort the
remaining functions by increasing size of the second point .
(setf funs (sort funs #'< :key (lambda (fun) (size (second fun)))))
Invariants : 1 . The next point to be determined has a size
that is strictly greater than the size of the first point of
each function . 2 . The second item of each function is a
point . 3 . The functions are in increasing order with respect
to the size of the second point .
(loop until (null funs)
do (let* ((size (size (second (car funs))))
(force (loop for fun in funs
sum (let* ((s0 (size (first fun)))
(f0 (force (first fun)))
(s1 (size (second fun)))
(f1 (force (second fun)))
(slope (/ (- f1 f0) (- s1 s0))))
(+ f0 (* (- size s0) slope))))))
(let ((dforce (+ (* slope size) zero-size-force)))
(push (make-point size (+ force dforce)) reverse-result))
second point with a size that we just handled .
Clearly , the first such function is one of them ,
they are all first . We process each such function
by removing the first point . If by doing that ,
number 3 .
(loop until (or (null funs)
(> (size (second (car funs))) size))
do (let ((fun (pop funs)))
(eliminate-first-point fun)
(if (slopep (second fun))
(let* ((first (first fun))
(size (size first))
(force (force first)))
(incf slope (second fun))
(incf zero-size-force
(- force (* (second fun) size))))
(setf funs (merge 'list (list fun) funs #'<
:key (lambda (fun)
(size (second fun))))))))))
(push slope reverse-result)
(nreverse reverse-result))))
(defun combine-in-series (rigidity-functions)
(assert (proper-list-p rigidity-functions))
(assert (>= (length rigidity-functions) 1))
(assert (every #'rigidity-function-p rigidity-functions))
(let ((result '()))
(let ((funs (copy-tree rigidity-functions)))
(setf funs (mapcar #'reverse funs))
(push (/ (loop for fun in funs sum (/ (car fun)))) result)
Recall that the last point is the second element of the list
(setf funs (sort funs #'> :key (lambda (fun) (force (second fun)))))
(loop until (null funs)
do (let* ((force (force (second (car funs))))
(size (loop for fun in funs
sum (let ((s (size (second fun)))
(f (force (second fun)))
(slope (car fun)))
(+ s (/ (- force f) slope))))))
(push (make-point size force) result)
also the first point , then remove the function
to the size . If the last point is not the first
(loop until (or (null funs)
(< (force (second (car funs))) force))
do (let ((fun (pop funs)))
(unless (null (rest (rest fun)))
(let ((s1 (size (second fun)))
(f1 (force (second fun)))
(s0 (size (third fun)))
(f0 (force (third fun))))
(setf (first fun)
(/ (- f1 f0) (- s1 s0)))
(setf (rest fun) (rest (rest fun))))
(setf funs (merge 'list (list fun) funs #'>
:key (lambda (fun)
(force (second fun)))))))))))
result))
(defun max-min-diff (list)
(- (reduce #'max list) (reduce #'min list)))
(defun compute-forces (rigidity-functions sizes)
(mapcar #'force-at-size rigidity-functions sizes))
(defun badness (rigidity-functions sizes)
(max-min-diff (compute-forces rigidity-functions sizes)))
except that the element in the position passed as the second
(defun add-one-to-pos (list pos)
(loop for i from 0
for element in list
collect (+ element (if (= i pos) 1 0))))
is the same as the second one passed as an argument , except that
one position has been incremented by one in such a way that the
(defun add-one (rigidity-functions sizes)
(let ((min-badness (badness rigidity-functions (cons (1+ (car sizes)) (cdr sizes))))
(min-pos 0))
(loop for pos from 1 below (length sizes)
do (let ((new-badness (badness rigidity-functions (add-one-to-pos sizes pos))))
(when (< new-badness min-badness)
(setf min-badness new-badness)
(setf min-pos pos))))
(add-one-to-pos sizes min-pos)))
(defun sizes-in-series (rigidity-functions size)
(let ((sizes (make-list (length rigidity-functions) :initial-element 0)))
(loop repeat size
do (setf sizes (add-one rigidity-functions sizes)))
sizes))
(defparameter *rigid* 1000000)
(defparameter *elastic* (/ *rigid*))
(defun little-rigid (&key (factor 1))
(assert (rationalp factor))
(assert (plusp factor))
`((0 . 0) ,(* *elastic* factor)))
(defun very-rigid (natural-size &key (factor 1))
(assert (rationalp natural-size))
(assert (plusp natural-size))
(assert (rationalp factor))
(assert (plusp factor))
(let* ((rigidity (* *rigid* factor))
(zero-size-force (- (* rigidity natural-size))))
`((0 . ,zero-size-force) ,rigidity)))
(defun rigid-contract (natural-size &key (expand-factor 1) (contract-factor 1))
(assert (rationalp natural-size))
(assert (plusp natural-size))
(assert (rationalp expand-factor))
(assert (plusp expand-factor))
(assert (rationalp contract-factor))
(assert (plusp contract-factor))
(let* ((contract-rigidity (* *rigid* contract-factor))
(expand-rigidity (* *elastic* expand-factor))
(zero-size-force (- (* contract-rigidity natural-size))))
`((0 . ,zero-size-force) (,natural-size . 0) ,expand-rigidity)))
(defun rigid-expand (natural-size &key (expand-factor 1) (contract-factor 1))
(assert (rationalp natural-size))
(assert (plusp natural-size))
(assert (rationalp expand-factor))
(assert (plusp expand-factor))
(assert (rationalp contract-factor))
(assert (plusp contract-factor))
(let* ((contract-rigidity (* *elastic* contract-factor))
(expand-rigidity (* *rigid* expand-factor))
(zero-size-force (- (* contract-rigidity natural-size))))
`((0 . ,zero-size-force) (,natural-size . 0) ,expand-rigidity)))
(defun random-non-negative-rational (n)
(let ((denominator (1+ (random 100))))
(/ (random (* n denominator)) denominator)))
(defun random-positive-rational (n)
(let ((denominator (1+ (random 100))))
(/ (1+ (random (* n denominator))) denominator)))
(defun random-rigidity-function ()
(let ((f (- (random-non-negative-rational 100)))
(s 0))
`(,(make-point s f)
,@(loop repeat (random 5)
collect (make-point (incf s (random-positive-rational 100))
(incf f (random-positive-rational 100))))
,(random-positive-rational 100))))
(defun test-little-rigid ()
(format t "little-rigid...")
(force-output)
(loop repeat 100000
do (let* ((factor (random-positive-rational 100))
(fun (little-rigid :factor factor))
(size (random-non-negative-rational 100)))
(assert (= (force-at-size fun size)
(* size factor *elastic*)))))
(format t "~%"))
(defun test-very-rigid ()
(format t "very-rigid...")
(force-output)
(loop repeat 100000
do (let* ((factor (random-positive-rational 100))
(natural-size (random-positive-rational 100))
(fun (very-rigid natural-size :factor factor))
(size (random-non-negative-rational 100))
(zero-size-force (- (* natural-size factor *rigid*))))
(assert (= (force-at-size fun size)
(+ (* size factor *rigid*) zero-size-force)))))
(format t "~%"))
(defun test-rigid-contract ()
(format t "rigid-contract...")
(force-output)
(loop repeat 100000
do (let* ((expand-factor (random-positive-rational 100))
(contract-factor (random-positive-rational 100))
(natural-size (random-positive-rational 100))
(fun (rigid-contract natural-size
:expand-factor expand-factor
:contract-factor contract-factor))
(fun1 (very-rigid natural-size :factor contract-factor))
(fun2 (little-rigid :factor expand-factor))
(size (random-non-negative-rational 100)))
(if (> size natural-size)
(assert (= (force-at-size fun size)
(force-at-size fun2 (- size natural-size))))
(assert (= (force-at-size fun size)
(force-at-size fun1 size))))))
(format t "~%"))
(defun test-rigid-expand ()
(format t "rigid-expand...")
(force-output)
(loop repeat 100000
do (let* ((expand-factor (random-positive-rational 100))
(contract-factor (random-positive-rational 100))
(natural-size (random-positive-rational 100))
(fun (rigid-expand natural-size
:expand-factor expand-factor
:contract-factor contract-factor))
(fun1 (little-rigid :factor contract-factor))
(fun2 (very-rigid natural-size :factor expand-factor))
(size (random-non-negative-rational 100)))
(if (> size natural-size)
(assert (= (force-at-size fun size)
(force-at-size fun2 size)))
(assert (= (- (force-at-size fun size)
(force-at-size fun 0))
(force-at-size fun1 size))))))
(format t "~%"))
(defun test-size-at-force ()
(format t "size-at-force...")
(force-output)
(loop repeat 100000
do (let ((fun (random-rigidity-function))
(size (random-non-negative-rational 100)))
(let ((force (force-at-size fun size)))
(assert (= size
(size-at-force fun force))))))
(format t "~%"))
(defun test-combine-in-parallel ()
(format t "combine-in-parallel...")
(force-output)
(loop repeat 100000
do (let* ((n (1+ (random 10)))
(funs (loop repeat n collect (random-rigidity-function)))
(combined (combine-in-parallel funs))
(max-size (reduce #'max funs :key (lambda (fun)
(size (car (last fun 2))))))
(size (random-non-negative-rational (+ 2 (* 2 (ceiling max-size))))))
(assert (= (force-at-size combined size)
(reduce #'+ funs :key (lambda (fun) (force-at-size fun size)))))))
(format t "~%"))
(defun test-combine-in-series ()
(format t "combine-in-series...")
(force-output)
(loop repeat 100000
do (let* ((n (1+ (random 10)))
(funs (loop repeat n collect (random-rigidity-function)))
(combined (combine-in-series funs))
(max-force (reduce #'max funs :key (lambda (fun)
(force (car (last fun 2))))))
(min-force (reduce #'min funs :key (lambda (fun)
(force (first fun)))))
(force (+ min-force (random-non-negative-rational
(1+ (round (- max-force min-force)))))))
(assert (= (size-at-force combined force)
(reduce #'+ funs :key (lambda (fun) (size-at-force fun force)))))))
(format t "~%"))
(defun run-test ()
(test-little-rigid)
(test-very-rigid)
(test-rigid-contract)
(test-rigid-expand)
(test-size-at-force)
(test-combine-in-parallel)
(test-combine-in-series))
|
6251404e7fb9dc7e2c0e9ccf4d692fde67b244306864bdfb10e5c76a15dcc9f7 | nextjournal/clerk | dice.clj | # 🎲
(ns dice
(:require [clojure.java.shell :as shell]
[nextjournal.clerk :as clerk]))
My kids have [ this game]( / produkte / spiele / mitbringspiele / nanu-23063 / index.html ) and we lost the dice that comes with it . It ca n't be too hard to make on in Clojure , can it ? The dice has five colored ` sides ` and a joker .
(def sides '[🟡 🟠 🟢 🔵 🃏])
Next , we 'll use an ` atom ` that will hold the state .
(defonce dice (atom nil))
;; Here, we define a viewer using hiccup that will the dice as well as a button. Note that this button has an `:on-click` event handler that uses `v/clerk-eval` to tell Clerk to evaluate the argument, in this cases `(roll!)` when clicked.
^{::clerk/viewer '(fn [side]
[:div.text-center
(when side
[:div.mt-2 {:style {:font-size "6em"}} side])
[:button.bg-blue-500.hover:bg-blue-700.text-white.font-bold.py-2.px-4.rounded
{:on-click (fn [e] (nextjournal.clerk.render/clerk-eval '(roll!)))} "Roll 🎲!"]])}
@dice
;; Our roll! function `resets!` our `dice` with a random side and prints and says the result. Finally it updates the notebook.
(defn roll! []
(reset! dice (rand-nth sides))
(prn @dice)
(shell/sh "say" (name ('{🟡 :gelb 🟠 :orange 🟢 :grün 🔵 :blau 🃏 :joker} @dice))))
#_(roll!)
(comment
(clerk/serve! {})
)
| null | https://raw.githubusercontent.com/nextjournal/clerk/625b607bfec1725019fca6c32054a97ed8f96d3f/notebooks/dice.clj | clojure | Here, we define a viewer using hiccup that will the dice as well as a button. Note that this button has an `:on-click` event handler that uses `v/clerk-eval` to tell Clerk to evaluate the argument, in this cases `(roll!)` when clicked.
Our roll! function `resets!` our `dice` with a random side and prints and says the result. Finally it updates the notebook. | # 🎲
(ns dice
(:require [clojure.java.shell :as shell]
[nextjournal.clerk :as clerk]))
My kids have [ this game]( / produkte / spiele / mitbringspiele / nanu-23063 / index.html ) and we lost the dice that comes with it . It ca n't be too hard to make on in Clojure , can it ? The dice has five colored ` sides ` and a joker .
(def sides '[🟡 🟠 🟢 🔵 🃏])
Next , we 'll use an ` atom ` that will hold the state .
(defonce dice (atom nil))
^{::clerk/viewer '(fn [side]
[:div.text-center
(when side
[:div.mt-2 {:style {:font-size "6em"}} side])
[:button.bg-blue-500.hover:bg-blue-700.text-white.font-bold.py-2.px-4.rounded
{:on-click (fn [e] (nextjournal.clerk.render/clerk-eval '(roll!)))} "Roll 🎲!"]])}
@dice
(defn roll! []
(reset! dice (rand-nth sides))
(prn @dice)
(shell/sh "say" (name ('{🟡 :gelb 🟠 :orange 🟢 :grün 🔵 :blau 🃏 :joker} @dice))))
#_(roll!)
(comment
(clerk/serve! {})
)
|
f0d46707c531c843125a5454c822b24d8354efa08b22e4ce38e62c472933d0f0 | jsa-aerial/saite | tabs.cljs | (ns aerial.saite.tabs
(:require
[cljs.core.async
:as async
:refer (<! >! put! chan)
:refer-macros [go go-loop]]
[clojure.string :as cljstr]
[aerial.hanami.core
:as hmi
:refer [printchan user-msg
re-com-xref xform-recom
default-header-fn start
get-vspec update-vspecs
get-tab-field add-tab update-tab-field
add-to-tab-body remove-from-tab-body
active-tabs
md vgl app-stop]]
[aerial.hanami.common
:as hc
:refer [RMV]]
[aerial.saite.splits :as ass]
[aerial.saite.savrest
:as sr
:refer [update-ddb get-ddb]]
[aerial.saite.codemirror
:as cm
:refer [code-mirror cm]]
[aerial.saite.compiler :refer [set-namespace]]
[aerial.saite.tabops
:as tops
:refer [push-undo undo redo get-tab-frames remove-frame]]
[com.rpl.specter :as sp]
[reagent.core :as rgt]
[re-com.core
:as rcm
:refer [h-box v-box box border gap line h-split v-split scroller
button row-button md-icon-button md-circle-icon-button info-button
input-text input-password input-textarea
label title p
single-dropdown selection-list
checkbox radio-button slider progress-bar throbber
horizontal-bar-tabs vertical-bar-tabs
modal-panel popover-content-wrapper popover-anchor-wrapper]
:refer-macros [handler-fn]]
[re-com.box
:refer [flex-child-style]]
[re-com.dropdown
:refer [filter-choices-by-keyword single-dropdown-args-desc]]
))
;;; Interactive Editor Tab Constructors =================================== ;;;
#_(evaluate "(ns mycode.test
(:require [clojure.string :as str]
[aerial.hanami.core :as hmi]
[aerial.hanami.common :as hc]
[aerial.hanami.templates :as ht]
[aerial.saite.core :as asc]
[com.rpl.specter :as sp]))" println)
(defn ^:export editor-repl-tab
[tid label src & {:keys [width height out-width out-height
layout ed-out-order ns]
:or {width "730px"
height "700px"
out-width "730px"
out-height "700px"
layout :left-right
ed-out-order :first-last
ns 'aerial.saite.usercode}}]
(let [cmfn (cm)
eid (str "ed-" (name tid))
uinfo {:fn ''editor-repl-tab
:tid tid
:eid eid
:width width
:height height
:out-width out-width
:out-height out-height
:layout layout
:ed-out-order ed-out-order
:ns ns
:src src}]
(set-namespace ns)
(update-ddb [:tabs :extns tid] uinfo)
(add-tab
{:id tid
:label label
:specs []
:opts {:order :row, :eltsper 1, :size "auto"
:wrapfn (fn[_]
[box
:child [cmfn :tid tid :id eid
:width width
:height height
:out-width out-width
:out-height out-height
:layout layout
:ed-out-order ed-out-order
:src src]
:width "2100px" :height out-height])}})))
(defn ^:export interactive-doc-tab
[tid label src & {:keys [width height out-width out-height
ed-out-order $split md-defaults
ns cmfids specs order eltsper rgap cgap size]
:or {width "730px"
height "700px"
out-width "730px"
out-height "100px"
ed-out-order :last-first
$split (get-ddb [:tabs :extns :$split])
ns 'aerial.saite.usercode
cmfids {:cm 0 :fm 0}
specs []
order :row eltsper 1 :rgap "20px" :cgap "20px"
size "auto"}}]
(let [cmfn (cm)
eid (str "ed-" (name tid))
maxh (or (get-ddb [:main :interactive-tab :doc :max-height]) "900px")
maxw (or (get-ddb [:main :interactive-tab :doc :max-width]) "2000px")
sratom (rgt/atom $split)
uinfo {:fn ''interactive-doc-tab
:tid tid
:eid eid
:width width
:height height
:out-width out-width
:out-height out-height
:ed-out-order ed-out-order
:$split $split
:$sratom sratom
:ns ns
:cmfids cmfids
:src src}
hsfn (ass/h-split
:panel-1 "fake p1"
:panel-2 "fake p2"
:split-perc sratom
:on-split-change
#(update-ddb
[:tabs :extns (hmi/get-cur-tab :id) :$split]
(let [sp (/ (.round js/Math (* 100 %)) 100)]
(if (<= sp 3.0) 0.0 sp)))
:width "2100px" :height maxh)]
(set-namespace ns)
(update-ddb [:tabs :extns tid] uinfo)
(when md-defaults (update-ddb [:tabs :md-defaults tid] md-defaults))
(add-tab
{:id tid
:label label
:specs specs
:opts {:order order, :eltsper eltsper,
:rgap rgap :cgap cgap :size size
:wrapfn (fn[hcomp]
[hsfn
:panel-1 [cmfn :tid tid :id eid
:width width
:height height
:out-height out-height
:out-width out-width
:ed-out-order ed-out-order
:src src]
:panel-2 [scroller
:max-height maxh
:max-width maxw
:align :start
:child hcomp]])}})
(let [opts (hmi/get-tab-field tid :opts)
s-f-pairs (hmi/make-spec-frame-pairs tid opts specs)]
(hmi/update-tab-field tid :compvis (hmi/vis-list tid s-f-pairs opts)))))
(def extns-xref
(into {} (map vector
'[editor-repl-tab interactive-doc-tab]
[editor-repl-tab interactive-doc-tab])))
;;; General - multiple uses =============================================== ;;;
(defn alert-panel [txt closefn]
(printchan :alert-panel)
[modal-panel
:child [re-com.core/alert-box
:id 1 :alert-type :danger
:heading txt
:closeable? true
:on-close closefn]
:backdrop-color "grey" :backdrop-opacity 0.0])
(defn input-area [label-txt model]
[h-box :gap "10px"
:children [[input-text
:model model
:width "60px" :height "20px"
:on-change #(reset! model %)]
[label :label label-txt]]])
(defn ok-cancel [donefn cancelfn]
[h-box :gap "5px" :justify :end
:children
[[md-circle-icon-button
:md-icon-name "zmdi-check-circle"
:tooltip "OK"
:on-click donefn]
[md-circle-icon-button
:md-icon-name "zmdi-close"
:tooltip "Cancel"
:on-click cancelfn]]])
;;; Header Editor Mgt Components ========================================== ;;;
(defn editor-box []
[border :padding "2px" :radius "2px"
:l-border "1px solid lightgrey"
:r-border "1px solid lightgrey"
:b-border "1px solid lightgrey"
:child [h-box
:gap "10px"
:children
[[md-circle-icon-button
:md-icon-name "zmdi-unfold-more" :size :smaller
:tooltip "Open Editor Panel"
:on-click
#(let [tid (hmi/get-cur-tab :id)
sratom (get-ddb [:tabs :extns tid :$sratom])
last-split (get-ddb [:tabs :extns tid :$split])
last-split (if (= 0 last-split)
(get-ddb [:tabs :extns :$split])
last-split)]
(reset! sratom last-split))]
[md-circle-icon-button
:md-icon-name "zmdi-unfold-less" :size :smaller
:tooltip "Collapse Editor Panel "
:on-click
#(let [tid (hmi/get-cur-tab :id)
sratom (get-ddb [:tabs :extns tid :$sratom])]
(reset! sratom 0))]]]])
;;; Header Misc Component ================================================= ;;;
(defn help-modal [show?]
(let [closefn (fn[event] (reset! show? false))]
(fn[show?]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Synopsis:"]
[scroller
:max-height "400px"
:max-width "600px"
:child [md {:style {:fond-size "16px" :width "600px"}}
(get-ddb [:main :doc :quick])]]
[h-box :gap "5px" :justify :end
:children
[[md-circle-icon-button
:md-icon-name "zmdi-close"
:tooltip "Close"
:on-click closefn]]]]]])))
(def theme-names
["3024-day" "3024-night" "abcdef" "ambiance" "ayu-dark" "ayu-mirage"
"base16-dark" "base16-light" "bespin" "blackboard" "cobalt" "colorforth"
"darcula" "dracula" "duotone-dark" "duotone-light" "eclipse" "elegant"
"erlang-dark" "gruvbox-dark" "hopscotch" "icecoder" "idea" "isotope"
"lesser-dark" "liquibyte" "lucario" "material" "material-darker"
"material-palenight" "material-ocean" "mbo" "mdn-like" "midnight" "monokai"
"moxer" "neat" "neo" "night" "nord" "oceanic-next" "panda-syntax"
"paraiso-dark" "paraiso-light" "pastel-on-dark" "railscasts" "rubyblue"
"seti" "shadowfox" "solarized dark" "solarized light" "the-matrix"
"tomorrow-night-bright" "tomorrow-night-eighties" "ttcn" "twilight"
"vibrant-ink" "xq-dark" "xq-light" "yeti" "yonce" "zenburn"])
(def themes (->> theme-names (mapv vector (map keyword theme-names)) (into {})))
(defn theme-modal [theme? theme]
(let [choices (->> themes (sort-by second)
(mapv (fn[[k v]] {:id k :label v})))
cancelfn (fn[event] (reset! theme? false))
donefn #(let [tid (hmi/get-cur-tab :id)
cms (->> (get-ddb [:tabs :cms tid])
vals (mapv vec) flatten
rest (take-nth 2))]
(doseq [cm cms] (cm/set-theme cm (themes @theme)))
(reset! theme? false))]
(fn[theme? theme]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Themes"]
[single-dropdown
:choices choices
:model theme
:width "300px"
:on-change #(reset! theme %)]
[ok-cancel donefn cancelfn]]]])))
(defn help-box []
(let [quick? (rgt/atom false)
theme? (rgt/atom false)
theme (rgt/atom nil)]
(fn []
[h-box :gap "5px" :justify :end
:children
[[md-circle-icon-button
:md-icon-name "zmdi-brush" :size :smaller
:tooltip "Theme"
:on-click #(reset! theme? true)]
[md-circle-icon-button
:md-icon-name "zmdi-help" :size :smaller
:tooltip "Quick Help"
:on-click #(reset! quick? true)]
[md-circle-icon-button
:md-icon-name "zmdi-info" :size :smaller
:tooltip "Doc Help"
:on-click #()]
(when @quick? [help-modal quick?])
(when @theme?
(reset! theme (keyword (get-ddb [:main :editor :theme])))
[theme-modal theme? theme])
[gap :size "10px"]]])))
Header = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ; ; ;
(defn del-tab [tid]
(let [x (sp/select-one [sp/ATOM :tabs :active sp/ATOM] hmi/app-db)
eid (get-ddb [:tabs :extns tid :eid])]
(push-undo x)
(update-ddb [:tabs :extns tid] :rm
[:tabs :cms tid] :rm
[:editors tid eid] :rm)
(hmi/del-vgviews tid)
(hmi/del-tab tid)))
(defn add-interactive-tab [info-map]
(let [x (sp/select-one [sp/ATOM :tabs :active sp/ATOM] hmi/app-db)
{:keys [edtype ns id label
order eltsper
width height out-width out-height
size rgap cgap layout ed-out-order]} info-map]
(push-undo x)
(cond
(= :converter edtype) (printchan :NYI)
(= :editor edtype)
(editor-repl-tab
id label "" :ns ns
:width width :height height
:out-width out-width :out-height out-height
:layout layout :ed-out-order ed-out-order)
:else
(interactive-doc-tab
id label "" :ns ns
:width width :height height
:out-width out-width :out-height out-height
:ed-out-order ed-out-order
:order order :eltsper eltsper
:rgap rgap :cgap cgap :size size))
(printchan info-map)))
(defn duplicate-cur-tab [info]
(let [{:keys [tid label nssym]} info
ctid (hmi/get-cur-tab :id)
uinfo (or (get-ddb [:tabs :extns ctid]) {:fn [:_ :NA]})
eid (str "ed-" (name tid))
{:keys [width height out-width out-height
layout ed-out-order cmfids]} uinfo
cmfids (if cmfids cmfids {:cm 0 :fm 0})
src (deref (get-ddb [:editors ctid (uinfo :eid) :in]))
tabval (hmi/get-tab-field ctid)
{:keys [specs opts]} tabval
specs (mapv #(update-in %1 [:usermeta :tab :id] (fn[_] tid)) specs)
{:keys [order eltsper size rgap cgap]} opts
edtype (second (uinfo :fn))]
(case edtype
:NA
(add-tab
{:id tid :label label :specs specs :opts opts})
editor-repl-tab
(editor-repl-tab
tid label src :ns nssym
:width width :height height
:out-width out-width :out-height out-height
:layout layout :ed-out-order ed-out-order)
interactive-doc-tab
(interactive-doc-tab
tid label src :ns nssym :cmfids cmfids
:width width :height height
:out-width out-width :out-height out-height
:ed-out-order ed-out-order
:specs specs :order order :eltsper eltsper :size size
:rgap rgap :cgap cgap))))
(defn edit-cur-tab [info]
(let [curtab (hmi/get-cur-tab)
tid (curtab :id)
label (curtab :label)
opts (curtab :opts)
rgap? (opts :rgap)
specs (curtab :specs)
{:keys [label nssym width height out-width out-height]} info
newextn-info (merge (get-ddb [:tabs :extns tid])
{:width width :height height
:out-width out-width :out-height out-height
:ns nssym})
newopts (merge opts (dissoc info
:label :nssym
:width :height :out-width :out-height))
newopts (if rgap?
newopts
(dissoc newopts :order :eltsper :rgap :cgap :size))
s-f-pairs (when rgap? (hmi/make-spec-frame-pairs tid newopts specs))]
(update-ddb [:tabs :extns tid] newextn-info)
(hmi/update-tab-field tid :opts newopts)
(hmi/update-tab-field tid :label label)
(if rgap?
(hmi/update-tab-field
tid :compvis (hmi/vis-list tid s-f-pairs newopts))
#_(do (del-tab tid)
(editor-repl-tab tid label)))))
(defn file-new [code? session-name file-name donefn cancelfn]
[v-box
:gap "10px"
:children [[label
:style {:font-size "18px"}
:label (if code? "Directory" "Session")]
[input-text
:model session-name
:width "300px" :height "26px"
:on-change #(reset! session-name %)]
[label
:style {:font-size "18px"}
:label "File"]
[input-text
:model file-name
:width "300px" :height "26px"
:on-change #(reset! file-name %)]
[ok-cancel donefn cancelfn]]])
(defn save-charts [donefn cancelfn]
[v-box
:gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Save all visualizations as PNGs?"]
[ok-cancel donefn cancelfn]]])
(defn urldoc [url donefn cancelfn]
[v-box
:gap "10px"
:children [[label
:style {:font-size "18px"}
:label "URL"]
[input-text
:model url
:width "700px" :height "26px"
:on-change #(reset! url %)]
[ok-cancel donefn cancelfn]]])
(defn file-modal
[choices session-name file-name mode url charts donefn cancelfn]
(let [sessions (rgt/atom (->> choices deref keys sort
(mapv (fn[k] {:id k :label k}))))
doc-files (rgt/atom (->> session-name deref (#(@choices %))
(mapv (fn[k] {:id k :label k}))))
url? (rgt/atom false)
urldonefn (fn[event] (reset! url? false) (donefn event))
docmodes #{:load :save}
codemodes #{:getcode :savecode}
savemodes #{:save :savecode}
charts? (rgt/atom false)
chartdonefn (fn [event]
(reset! charts true)
(reset! charts? false) (donefn event))
new? (rgt/atom false)
newdonefn (fn[event]
(let [fname @file-name
newsession? (not (some (fn[x]
(= (x :label) @session-name))
@sessions))
names (if newsession?
[fname]
(->> doc-files deref (map :id) (cons fname)))
newdfs (->> names sort
(mapv (fn[k] {:id k :label k})))]
(reset! doc-files newdfs)
(reset! choices (assoc @choices
@session-name (vec names)))
(reset! sessions (->> choices deref keys sort
(mapv (fn[k] {:id k :label k}))))
(printchan @doc-files @choices)
(reset! new? false)))]
(fn [choices session-name file-name mode url charts donefn cancelfn]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[(when (savemodes @mode)
[h-box :gap "10px"
:children [(when (not @charts?)
[checkbox
:model new?
:label "New location"
:on-change #(reset! new? %)])
(when (docmodes @mode)
[checkbox
:model charts?
:label "Visualizations"
:on-change #(reset! charts? %)])]])
(when (not (savemodes @mode))
[checkbox
:model url?
:label "URL"
:on-change #(reset! url? %)])
(cond
@new? [file-new (codemodes @mode) session-name file-name
newdonefn cancelfn]
@url? [urldoc url urldonefn cancelfn]
@charts? [save-charts chartdonefn cancelfn]
:else
[v-box
:gap "10px"
:children
[[label
:style {:font-size "18px"}
:label (if (codemodes @mode) "Directory" "Session")]
[single-dropdown
:choices @sessions
:model session-name
:width "300px"
:on-change (fn[nm]
(printchan :SESSION nm)
(reset! session-name nm)
(reset! doc-files
(->> (#(@choices nm))
(mapv (fn[k]
{:id k :label k}))))
(reset! file-name (-> doc-files deref
first :id)))]
[gap :size "10px"]
[label
:style {:font-size "18px"}
:label "File"]
[single-dropdown
:choices doc-files
:model file-name
:width "300px"
:on-change #(do (printchan :FILE %)
(reset! file-name %))]
[ok-cancel donefn cancelfn]]])]]])))
(defn px [x] (str x "px"))
(defn next-tid-label [edtype]
(let [nondefault-etabs (dissoc (get-ddb [:tabs :extns])
:$split :scratch :xvgl)
i (inc (count nondefault-etabs))
[tx lx] (if (= edtype :editor)
["ed" "Editor "]
["chap" "Chapter "])
[tx lx] ["tab" "Tab"]
tid (str tx i)
label (str lx i)]
[tid label]))
(defn add-modal [show?]
(let [defaults (get-ddb [:main :interactive-tab])
ed-defaults (get-ddb [:main :editor])
edtype (rgt/atom (defaults :edtype :interactive-doc))
order (rgt/atom (defaults :order :row))
eltsper (rgt/atom (defaults :eltsper "1"))
rgap (rgt/atom (defaults :rgap "20"))
cgap (rgt/atom (defaults :cgap "20"))
[tx lx] (next-tid-label @edtype)
tid (rgt/atom tx)
tlabel (rgt/atom lx)
nssym (rgt/atom (defaults :nssym "doc.code"))
size (rgt/atom (defaults :size "auto"))
layout (rgt/atom (defaults :layout :up-down))
ed-out-order (rgt/atom (defaults :ed-out-order :first-last))
edoutsz (get-in ed-defaults [:size :edout])
eddocsz (get-in ed-defaults [:size :eddoc])
edsize (rgt/atom (if (= @edtype :interactive-doc) eddocsz edoutsz))
width (rgt/atom (@edsize :width "730"))
height (rgt/atom (@edsize :height "500"))
out-width (rgt/atom (@edsize :out-width "730"))
out-height (rgt/atom (@edsize :out-height
(if (= @edtype :interactive-doc) "100" "700")))
advance? (rgt/atom false)
donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com])
{:edtype @edtype :ns (symbol @nssym)
:id (keyword @tid) :label @tlabel
:order @order :eltsper (js/parseInt @eltsper)
:rgap (px @rgap) :cgap (px @cgap)
:width (px @width) :height (px @height)
:out-width (px @out-width)
:out-height (px @out-height)
:size @size
:layout @layout :ed-out-order @ed-out-order}))
(reset! show? false) nil)
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false) nil)]
(fn [show?]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[h-box :gap "10px"
:children
[[v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Type to add"]
[radio-button
:label "Interactive Doc"
:value :interactive-doc
:model edtype
:label-style (when (= :interactive-doc @edtype)
{:font-weight "bold"})
:on-change #(let [[tx lx] (next-tid-label :doc)]
(reset! edsize eddocsz)
(reset! layout :up-down)
(reset! ed-out-order :first-last)
(reset! width (@edsize :width))
(reset! height (@edsize :height))
(reset! out-width (@edsize :out-width))
(reset! out-height (@edsize :out-height))
(reset! tid tx)
(reset! tlabel lx)
(reset! edtype %))]
[radio-button
:label "Editor and Output"
:value :editor
:model edtype
:label-style (when (= :editor @edtype)
{:font-weight "bold"})
:on-change #(let [[tx lx] (next-tid-label :editor)]
(reset! edsize edoutsz)
(reset! layout :left-right)
(reset! ed-out-order :first-last)
(reset! width (@edsize :width))
(reset! height (@edsize :height))
(reset! out-width (@edsize :out-width))
(reset! out-height (@edsize :out-height))
(reset! tid tx)
(reset! tlabel lx)
(reset! edtype %))]
[radio-button
:label "<-> Converter"
:value :converter
:model edtype
:label-style (when (= :converter @edtype)
{:font-weight "bold"})
:on-change #(reset! edtype %)]]]
[v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Ordering"]
[radio-button
:label "Row Ordered"
:value :row
:model order
:label-style (when (= :row @order) {:font-weight "bold"})
:on-change #(do (reset! size "auto")
(reset! order %))]
[radio-button
:label "Column Ordered"
:value :col
:model order
:label-style (when (= :col @order) {:font-weight "bold"})
:on-change #(do (reset! size "none")
(reset! order %))]
[h-box :gap "10px"
:children [[input-text
:model eltsper
:width "40px" :height "20px"
:on-change #(reset! eltsper %)]
[label :label (str "Elts/" (if (= @order :row)
"row" "col"))]]]]]
[v-box :gap "10px"
:children
[[checkbox
:model advance?
:label "Advanced Options"
:on-change #(reset! advance? %)]
(when @advance?
[h-box :gap "20px"
:children
[[v-box :gap "10px"
:children
[[input-area "Editor Width" width]
[input-area "Editor Height" height]
[input-area "Output Width" out-width]
[input-area "Output Height" out-height]]]
[v-box :gap "10px"
:children
[[input-area "Row Gap" rgap]
[input-area "Col Gap" cgap]
[input-area "Flex size" size]]]
[v-box :gap "10px"
:children
[[label :label "Editor / Output Layout"]
[h-box :gap "10px"
:children
[[radio-button
:label "Left-Right"
:value :left-right
:model layout
:label-style (when (= :left-right @layout)
{:font-weight "bold"})
:on-change #(reset! layout %)]
[radio-button
:label "First-Last"
:value :first-last
:model ed-out-order
:label-style (when (= :first-last @ed-out-order)
{:font-weight "bold"})
:on-change #(reset! ed-out-order %)]]]
[h-box :gap "10px"
:children
[[radio-button
:label "Up-Down"
:value :up-down
:model layout
:label-style (when (= :up-down @layout)
{:font-weight "bold"})
:on-change #(reset! layout %)]
[radio-button
:label "Last-First"
:value :last-first
:model ed-out-order
:label-style (when (= :last-first @ed-out-order)
{:font-weight "bold"})
:on-change #(reset! ed-out-order %)]]]]]]])]]
]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Id"]
[input-text
:model tid
:width "200px" :height "26px"
:on-change
#(do (reset! tid %)
(reset! tlabel (cljstr/capitalize %)))]
[gap :size "10px"]
[label
:style {:font-size "18px"}
:label "Label"]
[input-text
:model tlabel
:width "200px" :height "26px"
:on-change #(reset! tlabel %)]]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Namespace"]
[input-text
:model nssym
:width "200px" :height "26px"
:on-change
#(reset! nssym %)]]]
[ok-cancel donefn cancelfn] ]]])))
(defn dup-modal [show?]
(let [curtab (hmi/get-cur-tab)
tid (rgt/atom (str (-> curtab :id name) "2"))
tlabel (rgt/atom (str (curtab :label) " 2"))
nssym (rgt/atom (name (get-ddb [:tabs :extns (curtab :id) :ns])))
donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com])
{:tid (keyword @tid) :label @tlabel
:nssym (symbol @nssym)}))
(reset! show? false))
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false))]
(fn [show?]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Id"]
[input-text
:model tid
:width "200px" :height "26px"
:on-change
#(do (reset! tid %)
(reset! tlabel (cljstr/capitalize %)))]
[gap :size "10px"]
[label
:style {:font-size "18px"}
:label "Label"]
[input-text
:model tlabel
:width "200px" :height "26px"
:on-change #(reset! tlabel %)]]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Namespace"]
[input-text
:model nssym
:width "200px" :height "26px"
:on-change
#(reset! nssym %)]]]
[ok-cancel donefn cancelfn]]]])))
(defn edit-modal [show?]
(let [curtab (hmi/get-cur-tab)
curtid (curtab :id)
curlabel (curtab :label)
opts (curtab :opts)
order (rgt/atom (opts :order))
eltsper (rgt/atom (str (opts :eltsper)))
rgap? (opts :rgap)
rgap (rgt/atom (when rgap? (-> opts :rgap (cljstr/replace #"px$" ""))))
cgap (rgt/atom (when rgap? (-> opts :cgap (cljstr/replace #"px$" ""))))
size (rgt/atom (opts :size))
ed-out-order (rgt/atom (opts :ed-out-order))
{:keys [width height
out-width out-height]} (or (get-ddb [:tabs :extns curtid])
Incase this is a std tab ! !
{:width "0px" :height "0px"
:out-width "0px" :out-height "0px"})
width (rgt/atom (cljstr/replace width #"px$" ""))
height (rgt/atom (cljstr/replace height #"px$" ""))
out-width (rgt/atom (cljstr/replace out-width #"px$" ""))
out-height (rgt/atom (cljstr/replace out-height #"px$" ""))
tlabel (rgt/atom curlabel)
nssym (rgt/atom (str (get-ddb [:tabs :extns curtid :ns])))
donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com])
{:label @tlabel :nssym (symbol @nssym)
:order @order :eltsper (js/parseInt @eltsper)
:rgap (px @rgap) :cgap (px @cgap)
:width (px @width) :height (px @height)
:out-width (px @out-width)
:out-height (px @out-height)
:size @size :ed-out-order @ed-out-order}))
(reset! show? false))
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false))]
(fn [show?]
(if (= curtid :xvgl)
(alert-panel "Cannot edit <-> tab" cancelfn)
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[h-box
:gap "10px"
:children
[(when @rgap
[h-box :gap "10px"
:children
[[v-box :gap "15px"
:children
[[label :style {:font-size "18px"} :label "Ordering"]
[radio-button
:label "Row Ordered"
:value :row
:model order
:label-style (when (= :row @order)
{:font-weight "bold"})
:on-change #(do (reset! size "auto")
(reset! order %))]
[radio-button
:label "Column Ordered"
:value :col
:model order
:label-style (when (= :col @order)
{:font-weight "bold"})
:on-change #(do (reset! size "none")
(reset! order %))]
[h-box :gap "10px"
:children [[input-text
:model eltsper
:width "40px" :height "20px"
:on-change #(reset! eltsper %)]
[label :label (str "Elts/"
(if (= @order :row)
"row" "col"))]]]]]
[v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Gapping"]
[input-area "Row Gap" rgap]
[input-area "Col Gap" cgap]
[input-area "Flex size" size]]]
[v-box :gap "10px"
:children
[[label
:style {:font-size "18px"}
:label "Editor / Output"]
[radio-button
:label "First-Last"
:value :first-last
:model ed-out-order
:label-style (when (= :first-last @ed-out-order)
{:font-weight "bold"})
:on-change #(reset! ed-out-order %)]
[radio-button
:label "Last-First"
:value :last-first
:model ed-out-order
:label-style (when (= :last-first @ed-out-order)
{:font-weight "bold"})
:on-change #(reset! ed-out-order %)]]]]])
[v-box :gap "10px"
:children
[[input-area "Editor Width" width]
[input-area "Editor Height" height]
[input-area "Output Width" out-width]
[input-area "Output Height" out-height]]]]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Label"]
[input-text
:model tlabel
:width "200px" :height "26px"
:on-change #(reset! tlabel %)]]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Namespace"]
[input-text
:model nssym
:width "200px" :height "26px"
:on-change
#(reset! nssym %)]]]
[ok-cancel donefn cancelfn]]]]))))
(defn del-modal [show?]
(let [donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com])
{:tab2del (hmi/get-cur-tab)}))
(reset! show? false))
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false))]
(fn [show?]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[label
:style {:font-size "18px"}
:label (str "Really Delete: ''"
(hmi/get-cur-tab :label) "''?")]
[ok-cancel donefn cancelfn]]]])))
(defn del-frame-modal [show? info]
(let [donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :ok))
(reset! show? false))
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false))]
(fn [show? info]
(printchan :DEL-FRAME :INFO (info :items) (info :selections))
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[selection-list
:width "391px"
:max-height "95px"
:model (info :selections)
:choices (info :items)
:multi-select? true
:on-change #(reset! (info :selections) %)]
[ok-cancel donefn cancelfn]]]])))
(defn tab-box []
(let [add-show? (rgt/atom false)
dup-show? (rgt/atom false)
del-show? (rgt/atom false)
ed-show? (rgt/atom false)
del-closefn #(do (reset! del-show? false))
del-frame-show? (rgt/atom false)
selections (rgt/atom #{})
del-frame-closefn #(do (reset! del-frame-show? false))]
(fn []
[border :padding "2px" :radius "2px"
:l-border "1px solid lightgrey"
:r-border "1px solid lightgrey"
:b-border "1px solid lightgrey"
:child [h-box
:gap "10px"
:children
[[md-circle-icon-button
:md-icon-name "zmdi-plus-circle-o" :size :smaller
:tooltip "Add Interactive Tab"
:on-click
#(go (reset! add-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
info (async/<! ch)]
(when (not= :cancel info)
(add-interactive-tab info))))]
[md-circle-icon-button
:md-icon-name "zmdi-plus-circle-o-duplicate" :size :smaller
:tooltip "Duplicate Current Tab"
:on-click
#(go (reset! dup-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
info (async/<! ch)]
(when (not= :cancel info)
(duplicate-cur-tab info))))]
[md-circle-icon-button
:md-icon-name "zmdi-minus-square" :size :smaller
:tooltip "Delete Frames"
:on-click
#(go (reset! del-frame-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
answer (async/<! ch)]
(when (not= :cancel answer)
(printchan @selections)
(doseq [id @selections]
(remove-frame id))
(reset! selections #{}))))]
[md-circle-icon-button
:md-icon-name "zmdi-undo" :size :smaller
:tooltip "Undo last tab operation"
:on-click
#(do (printchan "Undo") (undo))]
[md-circle-icon-button
:md-icon-name "zmdi-redo" :size :smaller
:tooltip "Redo undo operation"
:on-click
#(do (printchan "Redo") (redo))]
[md-circle-icon-button
:md-icon-name "zmdi-long-arrow-left" :size :smaller
:tooltip "Move current tab left"
:on-click
#(hmi/move-tab (hmi/get-cur-tab :id) :left)]
[md-circle-icon-button
:md-icon-name "zmdi-long-arrow-right" :size :smaller
:tooltip "Move current tab right"
:on-click
#(hmi/move-tab (hmi/get-cur-tab :id) :right)]
[md-circle-icon-button
:md-icon-name "zmdi-edit" :size :smaller
:tooltip "Edit current tab"
:on-click
#(go (reset! ed-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
info (async/<! ch)]
(when (not= :cancel info)
(edit-cur-tab info))))]
[md-circle-icon-button
:md-icon-name "zmdi-delete" :size :smaller
:tooltip "Delete Current Tab"
:on-click
#(go (reset! del-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
info (async/<! ch)]
(when (not= :cancel info)
(let [{:keys [tab2del]} info
tid (tab2del :id)]
(printchan :TID tid)
(del-tab tid)))))]
(when @add-show? [add-modal add-show?])
(when @dup-show? [dup-modal dup-show?])
(when @ed-show? [edit-modal ed-show?])
(when @del-show? [del-modal del-show? del-closefn])
(when @del-frame-show?
(let [items (rgt/atom (get-tab-frames))
info {:items items :selections selections}]
[del-frame-modal del-frame-show? info]))]]])))
Extension Tabs and
(defn vis-panel [inspec donefn] (printchan :vis-panel)
(go
(if-let [otchart (get-ddb [:main :otchart])]
otchart
(let [nm (hmi/get-adb [:main :uid :name])
msg {:op :read-clj
:data {:session-name nm
:render? true
:cljstg inspec}}
_ (hmi/send-msg msg)
otspec (async/<! (hmi/get-adb [:main :chans :convert]))
otchart (modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [scroller
:max-height "700px"
:max-width "1000px"
:child [v-box
:gap "10px"
:children [[vgl otspec]
[h-box :gap "5px" :justify :end
:children
[[md-circle-icon-button
:md-icon-name "zmdi-close"
:tooltip "Close"
:on-click donefn]]]]]])]
(update-ddb [:main :otchart] otchart)
otchart))))
(defn tab<-> [tabval] (printchan "Make TAB<-> called ")
(let [input (rgt/atom "")
output (rgt/atom "")
show? (rgt/atom false)
alert? (rgt/atom false)
process-done (fn[event]
(reset! show? false)
(update-ddb [:main :otspec] :rm
[:main :otchart] :rm))
process-close (fn[event] (reset! alert? false))]
(fn [tabval] (printchan "TAB<-> called ")
[v-box :gap "5px"
:children
[[h-box :gap "10px" :justify :between
:children
[[h-box :gap "10px"
:children
[[gap :size "10px"]
[md-circle-icon-button
:md-icon-name "zmdi-circle-o"
:tooltip "Clear"
:on-click
#(do (reset! input ""))]
[md-circle-icon-button
:md-icon-name "zmdi-fast-forward"
:tooltip "Translate VGL -> VG -> Clj"
:on-click
#(reset! output
(if (= @input "")
""
(try
(with-out-str
(-> (js/JSON.parse @input)
js/vegaLite.compile .-spec
(js->clj :keywordize-keys true)
(assoc :usermeta {:opts {:mode "vega"}})
cljs.pprint/pprint))
(catch js/Error e (str e)))))]
[md-circle-icon-button
:md-icon-name "zmdi-caret-right-circle"
:tooltip "Translate JSON to Clj"
:on-click
#(reset! output
(if (= @input "")
""
(try
(with-out-str
(cljs.pprint/pprint
(assoc
(js->clj (js/JSON.parse @input)
:keywordize-keys true)
:usermeta {:opts {:mode "vega-lite"}})))
(catch js/Error e (str e)))))]]]
[h-box :gap "10px" :justify :end
:children
[[box :child (cond @alert?
[alert-panel
"Empty specification can't be rendered"
process-close]
@show?
(get-ddb [:main :otchart])
:else [p])]
[md-circle-icon-button
:md-icon-name "zmdi-caret-left-circle"
:tooltip "Translate Clj to JSON"
:on-click
#(go (reset! input
(if (= @output "")
""
(let [nm (hmi/get-adb [:main :uid :name])
msg {:op :read-clj
:data {:session-name nm
:render? false
:cljstg @output}}]
(hmi/send-msg msg)
(async/<! (hmi/get-adb
[:main :chans :convert]))))))]
[md-circle-icon-button
:md-icon-name "zmdi-caret-up-circle"
:tooltip "Render in Popup"
:on-click #(if (= @output "")
(reset! alert? true)
(let [ch (vis-panel @output process-done)]
(go (async/<! ch)
(reset! show? true))))]
[md-circle-icon-button
:md-icon-name "zmdi-circle-o"
:tooltip "Clear"
:on-click
#(do (reset! output ""))]
[gap :size "10px"]]]]]
[line]
[h-split
:panel-1 [box :size "auto"
:width "730px"
:child [code-mirror
input {:name "javascript", :json true}
:tid :xvgl]]
:panel-2 [box :size "auto"
:child [code-mirror
output "clojure"
:tid :xvgl]]
:size "auto", :width "2100px", :height "800px"]]])))
| null | https://raw.githubusercontent.com/jsa-aerial/saite/b4105c8619b2e0d112eeabfe0528ecf19434f933/src/cljs/aerial/saite/tabs.cljs | clojure | Interactive Editor Tab Constructors =================================== ;;;
General - multiple uses =============================================== ;;;
Header Editor Mgt Components ========================================== ;;;
Header Misc Component ================================================= ;;;
; ; | (ns aerial.saite.tabs
(:require
[cljs.core.async
:as async
:refer (<! >! put! chan)
:refer-macros [go go-loop]]
[clojure.string :as cljstr]
[aerial.hanami.core
:as hmi
:refer [printchan user-msg
re-com-xref xform-recom
default-header-fn start
get-vspec update-vspecs
get-tab-field add-tab update-tab-field
add-to-tab-body remove-from-tab-body
active-tabs
md vgl app-stop]]
[aerial.hanami.common
:as hc
:refer [RMV]]
[aerial.saite.splits :as ass]
[aerial.saite.savrest
:as sr
:refer [update-ddb get-ddb]]
[aerial.saite.codemirror
:as cm
:refer [code-mirror cm]]
[aerial.saite.compiler :refer [set-namespace]]
[aerial.saite.tabops
:as tops
:refer [push-undo undo redo get-tab-frames remove-frame]]
[com.rpl.specter :as sp]
[reagent.core :as rgt]
[re-com.core
:as rcm
:refer [h-box v-box box border gap line h-split v-split scroller
button row-button md-icon-button md-circle-icon-button info-button
input-text input-password input-textarea
label title p
single-dropdown selection-list
checkbox radio-button slider progress-bar throbber
horizontal-bar-tabs vertical-bar-tabs
modal-panel popover-content-wrapper popover-anchor-wrapper]
:refer-macros [handler-fn]]
[re-com.box
:refer [flex-child-style]]
[re-com.dropdown
:refer [filter-choices-by-keyword single-dropdown-args-desc]]
))
#_(evaluate "(ns mycode.test
(:require [clojure.string :as str]
[aerial.hanami.core :as hmi]
[aerial.hanami.common :as hc]
[aerial.hanami.templates :as ht]
[aerial.saite.core :as asc]
[com.rpl.specter :as sp]))" println)
(defn ^:export editor-repl-tab
[tid label src & {:keys [width height out-width out-height
layout ed-out-order ns]
:or {width "730px"
height "700px"
out-width "730px"
out-height "700px"
layout :left-right
ed-out-order :first-last
ns 'aerial.saite.usercode}}]
(let [cmfn (cm)
eid (str "ed-" (name tid))
uinfo {:fn ''editor-repl-tab
:tid tid
:eid eid
:width width
:height height
:out-width out-width
:out-height out-height
:layout layout
:ed-out-order ed-out-order
:ns ns
:src src}]
(set-namespace ns)
(update-ddb [:tabs :extns tid] uinfo)
(add-tab
{:id tid
:label label
:specs []
:opts {:order :row, :eltsper 1, :size "auto"
:wrapfn (fn[_]
[box
:child [cmfn :tid tid :id eid
:width width
:height height
:out-width out-width
:out-height out-height
:layout layout
:ed-out-order ed-out-order
:src src]
:width "2100px" :height out-height])}})))
(defn ^:export interactive-doc-tab
[tid label src & {:keys [width height out-width out-height
ed-out-order $split md-defaults
ns cmfids specs order eltsper rgap cgap size]
:or {width "730px"
height "700px"
out-width "730px"
out-height "100px"
ed-out-order :last-first
$split (get-ddb [:tabs :extns :$split])
ns 'aerial.saite.usercode
cmfids {:cm 0 :fm 0}
specs []
order :row eltsper 1 :rgap "20px" :cgap "20px"
size "auto"}}]
(let [cmfn (cm)
eid (str "ed-" (name tid))
maxh (or (get-ddb [:main :interactive-tab :doc :max-height]) "900px")
maxw (or (get-ddb [:main :interactive-tab :doc :max-width]) "2000px")
sratom (rgt/atom $split)
uinfo {:fn ''interactive-doc-tab
:tid tid
:eid eid
:width width
:height height
:out-width out-width
:out-height out-height
:ed-out-order ed-out-order
:$split $split
:$sratom sratom
:ns ns
:cmfids cmfids
:src src}
hsfn (ass/h-split
:panel-1 "fake p1"
:panel-2 "fake p2"
:split-perc sratom
:on-split-change
#(update-ddb
[:tabs :extns (hmi/get-cur-tab :id) :$split]
(let [sp (/ (.round js/Math (* 100 %)) 100)]
(if (<= sp 3.0) 0.0 sp)))
:width "2100px" :height maxh)]
(set-namespace ns)
(update-ddb [:tabs :extns tid] uinfo)
(when md-defaults (update-ddb [:tabs :md-defaults tid] md-defaults))
(add-tab
{:id tid
:label label
:specs specs
:opts {:order order, :eltsper eltsper,
:rgap rgap :cgap cgap :size size
:wrapfn (fn[hcomp]
[hsfn
:panel-1 [cmfn :tid tid :id eid
:width width
:height height
:out-height out-height
:out-width out-width
:ed-out-order ed-out-order
:src src]
:panel-2 [scroller
:max-height maxh
:max-width maxw
:align :start
:child hcomp]])}})
(let [opts (hmi/get-tab-field tid :opts)
s-f-pairs (hmi/make-spec-frame-pairs tid opts specs)]
(hmi/update-tab-field tid :compvis (hmi/vis-list tid s-f-pairs opts)))))
(def extns-xref
(into {} (map vector
'[editor-repl-tab interactive-doc-tab]
[editor-repl-tab interactive-doc-tab])))
(defn alert-panel [txt closefn]
(printchan :alert-panel)
[modal-panel
:child [re-com.core/alert-box
:id 1 :alert-type :danger
:heading txt
:closeable? true
:on-close closefn]
:backdrop-color "grey" :backdrop-opacity 0.0])
(defn input-area [label-txt model]
[h-box :gap "10px"
:children [[input-text
:model model
:width "60px" :height "20px"
:on-change #(reset! model %)]
[label :label label-txt]]])
(defn ok-cancel [donefn cancelfn]
[h-box :gap "5px" :justify :end
:children
[[md-circle-icon-button
:md-icon-name "zmdi-check-circle"
:tooltip "OK"
:on-click donefn]
[md-circle-icon-button
:md-icon-name "zmdi-close"
:tooltip "Cancel"
:on-click cancelfn]]])
(defn editor-box []
[border :padding "2px" :radius "2px"
:l-border "1px solid lightgrey"
:r-border "1px solid lightgrey"
:b-border "1px solid lightgrey"
:child [h-box
:gap "10px"
:children
[[md-circle-icon-button
:md-icon-name "zmdi-unfold-more" :size :smaller
:tooltip "Open Editor Panel"
:on-click
#(let [tid (hmi/get-cur-tab :id)
sratom (get-ddb [:tabs :extns tid :$sratom])
last-split (get-ddb [:tabs :extns tid :$split])
last-split (if (= 0 last-split)
(get-ddb [:tabs :extns :$split])
last-split)]
(reset! sratom last-split))]
[md-circle-icon-button
:md-icon-name "zmdi-unfold-less" :size :smaller
:tooltip "Collapse Editor Panel "
:on-click
#(let [tid (hmi/get-cur-tab :id)
sratom (get-ddb [:tabs :extns tid :$sratom])]
(reset! sratom 0))]]]])
(defn help-modal [show?]
(let [closefn (fn[event] (reset! show? false))]
(fn[show?]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Synopsis:"]
[scroller
:max-height "400px"
:max-width "600px"
:child [md {:style {:fond-size "16px" :width "600px"}}
(get-ddb [:main :doc :quick])]]
[h-box :gap "5px" :justify :end
:children
[[md-circle-icon-button
:md-icon-name "zmdi-close"
:tooltip "Close"
:on-click closefn]]]]]])))
(def theme-names
["3024-day" "3024-night" "abcdef" "ambiance" "ayu-dark" "ayu-mirage"
"base16-dark" "base16-light" "bespin" "blackboard" "cobalt" "colorforth"
"darcula" "dracula" "duotone-dark" "duotone-light" "eclipse" "elegant"
"erlang-dark" "gruvbox-dark" "hopscotch" "icecoder" "idea" "isotope"
"lesser-dark" "liquibyte" "lucario" "material" "material-darker"
"material-palenight" "material-ocean" "mbo" "mdn-like" "midnight" "monokai"
"moxer" "neat" "neo" "night" "nord" "oceanic-next" "panda-syntax"
"paraiso-dark" "paraiso-light" "pastel-on-dark" "railscasts" "rubyblue"
"seti" "shadowfox" "solarized dark" "solarized light" "the-matrix"
"tomorrow-night-bright" "tomorrow-night-eighties" "ttcn" "twilight"
"vibrant-ink" "xq-dark" "xq-light" "yeti" "yonce" "zenburn"])
(def themes (->> theme-names (mapv vector (map keyword theme-names)) (into {})))
(defn theme-modal [theme? theme]
(let [choices (->> themes (sort-by second)
(mapv (fn[[k v]] {:id k :label v})))
cancelfn (fn[event] (reset! theme? false))
donefn #(let [tid (hmi/get-cur-tab :id)
cms (->> (get-ddb [:tabs :cms tid])
vals (mapv vec) flatten
rest (take-nth 2))]
(doseq [cm cms] (cm/set-theme cm (themes @theme)))
(reset! theme? false))]
(fn[theme? theme]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Themes"]
[single-dropdown
:choices choices
:model theme
:width "300px"
:on-change #(reset! theme %)]
[ok-cancel donefn cancelfn]]]])))
(defn help-box []
(let [quick? (rgt/atom false)
theme? (rgt/atom false)
theme (rgt/atom nil)]
(fn []
[h-box :gap "5px" :justify :end
:children
[[md-circle-icon-button
:md-icon-name "zmdi-brush" :size :smaller
:tooltip "Theme"
:on-click #(reset! theme? true)]
[md-circle-icon-button
:md-icon-name "zmdi-help" :size :smaller
:tooltip "Quick Help"
:on-click #(reset! quick? true)]
[md-circle-icon-button
:md-icon-name "zmdi-info" :size :smaller
:tooltip "Doc Help"
:on-click #()]
(when @quick? [help-modal quick?])
(when @theme?
(reset! theme (keyword (get-ddb [:main :editor :theme])))
[theme-modal theme? theme])
[gap :size "10px"]]])))
(defn del-tab [tid]
(let [x (sp/select-one [sp/ATOM :tabs :active sp/ATOM] hmi/app-db)
eid (get-ddb [:tabs :extns tid :eid])]
(push-undo x)
(update-ddb [:tabs :extns tid] :rm
[:tabs :cms tid] :rm
[:editors tid eid] :rm)
(hmi/del-vgviews tid)
(hmi/del-tab tid)))
(defn add-interactive-tab [info-map]
(let [x (sp/select-one [sp/ATOM :tabs :active sp/ATOM] hmi/app-db)
{:keys [edtype ns id label
order eltsper
width height out-width out-height
size rgap cgap layout ed-out-order]} info-map]
(push-undo x)
(cond
(= :converter edtype) (printchan :NYI)
(= :editor edtype)
(editor-repl-tab
id label "" :ns ns
:width width :height height
:out-width out-width :out-height out-height
:layout layout :ed-out-order ed-out-order)
:else
(interactive-doc-tab
id label "" :ns ns
:width width :height height
:out-width out-width :out-height out-height
:ed-out-order ed-out-order
:order order :eltsper eltsper
:rgap rgap :cgap cgap :size size))
(printchan info-map)))
(defn duplicate-cur-tab [info]
(let [{:keys [tid label nssym]} info
ctid (hmi/get-cur-tab :id)
uinfo (or (get-ddb [:tabs :extns ctid]) {:fn [:_ :NA]})
eid (str "ed-" (name tid))
{:keys [width height out-width out-height
layout ed-out-order cmfids]} uinfo
cmfids (if cmfids cmfids {:cm 0 :fm 0})
src (deref (get-ddb [:editors ctid (uinfo :eid) :in]))
tabval (hmi/get-tab-field ctid)
{:keys [specs opts]} tabval
specs (mapv #(update-in %1 [:usermeta :tab :id] (fn[_] tid)) specs)
{:keys [order eltsper size rgap cgap]} opts
edtype (second (uinfo :fn))]
(case edtype
:NA
(add-tab
{:id tid :label label :specs specs :opts opts})
editor-repl-tab
(editor-repl-tab
tid label src :ns nssym
:width width :height height
:out-width out-width :out-height out-height
:layout layout :ed-out-order ed-out-order)
interactive-doc-tab
(interactive-doc-tab
tid label src :ns nssym :cmfids cmfids
:width width :height height
:out-width out-width :out-height out-height
:ed-out-order ed-out-order
:specs specs :order order :eltsper eltsper :size size
:rgap rgap :cgap cgap))))
(defn edit-cur-tab [info]
(let [curtab (hmi/get-cur-tab)
tid (curtab :id)
label (curtab :label)
opts (curtab :opts)
rgap? (opts :rgap)
specs (curtab :specs)
{:keys [label nssym width height out-width out-height]} info
newextn-info (merge (get-ddb [:tabs :extns tid])
{:width width :height height
:out-width out-width :out-height out-height
:ns nssym})
newopts (merge opts (dissoc info
:label :nssym
:width :height :out-width :out-height))
newopts (if rgap?
newopts
(dissoc newopts :order :eltsper :rgap :cgap :size))
s-f-pairs (when rgap? (hmi/make-spec-frame-pairs tid newopts specs))]
(update-ddb [:tabs :extns tid] newextn-info)
(hmi/update-tab-field tid :opts newopts)
(hmi/update-tab-field tid :label label)
(if rgap?
(hmi/update-tab-field
tid :compvis (hmi/vis-list tid s-f-pairs newopts))
#_(do (del-tab tid)
(editor-repl-tab tid label)))))
(defn file-new [code? session-name file-name donefn cancelfn]
[v-box
:gap "10px"
:children [[label
:style {:font-size "18px"}
:label (if code? "Directory" "Session")]
[input-text
:model session-name
:width "300px" :height "26px"
:on-change #(reset! session-name %)]
[label
:style {:font-size "18px"}
:label "File"]
[input-text
:model file-name
:width "300px" :height "26px"
:on-change #(reset! file-name %)]
[ok-cancel donefn cancelfn]]])
(defn save-charts [donefn cancelfn]
[v-box
:gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Save all visualizations as PNGs?"]
[ok-cancel donefn cancelfn]]])
(defn urldoc [url donefn cancelfn]
[v-box
:gap "10px"
:children [[label
:style {:font-size "18px"}
:label "URL"]
[input-text
:model url
:width "700px" :height "26px"
:on-change #(reset! url %)]
[ok-cancel donefn cancelfn]]])
(defn file-modal
[choices session-name file-name mode url charts donefn cancelfn]
(let [sessions (rgt/atom (->> choices deref keys sort
(mapv (fn[k] {:id k :label k}))))
doc-files (rgt/atom (->> session-name deref (#(@choices %))
(mapv (fn[k] {:id k :label k}))))
url? (rgt/atom false)
urldonefn (fn[event] (reset! url? false) (donefn event))
docmodes #{:load :save}
codemodes #{:getcode :savecode}
savemodes #{:save :savecode}
charts? (rgt/atom false)
chartdonefn (fn [event]
(reset! charts true)
(reset! charts? false) (donefn event))
new? (rgt/atom false)
newdonefn (fn[event]
(let [fname @file-name
newsession? (not (some (fn[x]
(= (x :label) @session-name))
@sessions))
names (if newsession?
[fname]
(->> doc-files deref (map :id) (cons fname)))
newdfs (->> names sort
(mapv (fn[k] {:id k :label k})))]
(reset! doc-files newdfs)
(reset! choices (assoc @choices
@session-name (vec names)))
(reset! sessions (->> choices deref keys sort
(mapv (fn[k] {:id k :label k}))))
(printchan @doc-files @choices)
(reset! new? false)))]
(fn [choices session-name file-name mode url charts donefn cancelfn]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[(when (savemodes @mode)
[h-box :gap "10px"
:children [(when (not @charts?)
[checkbox
:model new?
:label "New location"
:on-change #(reset! new? %)])
(when (docmodes @mode)
[checkbox
:model charts?
:label "Visualizations"
:on-change #(reset! charts? %)])]])
(when (not (savemodes @mode))
[checkbox
:model url?
:label "URL"
:on-change #(reset! url? %)])
(cond
@new? [file-new (codemodes @mode) session-name file-name
newdonefn cancelfn]
@url? [urldoc url urldonefn cancelfn]
@charts? [save-charts chartdonefn cancelfn]
:else
[v-box
:gap "10px"
:children
[[label
:style {:font-size "18px"}
:label (if (codemodes @mode) "Directory" "Session")]
[single-dropdown
:choices @sessions
:model session-name
:width "300px"
:on-change (fn[nm]
(printchan :SESSION nm)
(reset! session-name nm)
(reset! doc-files
(->> (#(@choices nm))
(mapv (fn[k]
{:id k :label k}))))
(reset! file-name (-> doc-files deref
first :id)))]
[gap :size "10px"]
[label
:style {:font-size "18px"}
:label "File"]
[single-dropdown
:choices doc-files
:model file-name
:width "300px"
:on-change #(do (printchan :FILE %)
(reset! file-name %))]
[ok-cancel donefn cancelfn]]])]]])))
(defn px [x] (str x "px"))
(defn next-tid-label [edtype]
(let [nondefault-etabs (dissoc (get-ddb [:tabs :extns])
:$split :scratch :xvgl)
i (inc (count nondefault-etabs))
[tx lx] (if (= edtype :editor)
["ed" "Editor "]
["chap" "Chapter "])
[tx lx] ["tab" "Tab"]
tid (str tx i)
label (str lx i)]
[tid label]))
(defn add-modal [show?]
(let [defaults (get-ddb [:main :interactive-tab])
ed-defaults (get-ddb [:main :editor])
edtype (rgt/atom (defaults :edtype :interactive-doc))
order (rgt/atom (defaults :order :row))
eltsper (rgt/atom (defaults :eltsper "1"))
rgap (rgt/atom (defaults :rgap "20"))
cgap (rgt/atom (defaults :cgap "20"))
[tx lx] (next-tid-label @edtype)
tid (rgt/atom tx)
tlabel (rgt/atom lx)
nssym (rgt/atom (defaults :nssym "doc.code"))
size (rgt/atom (defaults :size "auto"))
layout (rgt/atom (defaults :layout :up-down))
ed-out-order (rgt/atom (defaults :ed-out-order :first-last))
edoutsz (get-in ed-defaults [:size :edout])
eddocsz (get-in ed-defaults [:size :eddoc])
edsize (rgt/atom (if (= @edtype :interactive-doc) eddocsz edoutsz))
width (rgt/atom (@edsize :width "730"))
height (rgt/atom (@edsize :height "500"))
out-width (rgt/atom (@edsize :out-width "730"))
out-height (rgt/atom (@edsize :out-height
(if (= @edtype :interactive-doc) "100" "700")))
advance? (rgt/atom false)
donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com])
{:edtype @edtype :ns (symbol @nssym)
:id (keyword @tid) :label @tlabel
:order @order :eltsper (js/parseInt @eltsper)
:rgap (px @rgap) :cgap (px @cgap)
:width (px @width) :height (px @height)
:out-width (px @out-width)
:out-height (px @out-height)
:size @size
:layout @layout :ed-out-order @ed-out-order}))
(reset! show? false) nil)
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false) nil)]
(fn [show?]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[h-box :gap "10px"
:children
[[v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Type to add"]
[radio-button
:label "Interactive Doc"
:value :interactive-doc
:model edtype
:label-style (when (= :interactive-doc @edtype)
{:font-weight "bold"})
:on-change #(let [[tx lx] (next-tid-label :doc)]
(reset! edsize eddocsz)
(reset! layout :up-down)
(reset! ed-out-order :first-last)
(reset! width (@edsize :width))
(reset! height (@edsize :height))
(reset! out-width (@edsize :out-width))
(reset! out-height (@edsize :out-height))
(reset! tid tx)
(reset! tlabel lx)
(reset! edtype %))]
[radio-button
:label "Editor and Output"
:value :editor
:model edtype
:label-style (when (= :editor @edtype)
{:font-weight "bold"})
:on-change #(let [[tx lx] (next-tid-label :editor)]
(reset! edsize edoutsz)
(reset! layout :left-right)
(reset! ed-out-order :first-last)
(reset! width (@edsize :width))
(reset! height (@edsize :height))
(reset! out-width (@edsize :out-width))
(reset! out-height (@edsize :out-height))
(reset! tid tx)
(reset! tlabel lx)
(reset! edtype %))]
[radio-button
:label "<-> Converter"
:value :converter
:model edtype
:label-style (when (= :converter @edtype)
{:font-weight "bold"})
:on-change #(reset! edtype %)]]]
[v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Ordering"]
[radio-button
:label "Row Ordered"
:value :row
:model order
:label-style (when (= :row @order) {:font-weight "bold"})
:on-change #(do (reset! size "auto")
(reset! order %))]
[radio-button
:label "Column Ordered"
:value :col
:model order
:label-style (when (= :col @order) {:font-weight "bold"})
:on-change #(do (reset! size "none")
(reset! order %))]
[h-box :gap "10px"
:children [[input-text
:model eltsper
:width "40px" :height "20px"
:on-change #(reset! eltsper %)]
[label :label (str "Elts/" (if (= @order :row)
"row" "col"))]]]]]
[v-box :gap "10px"
:children
[[checkbox
:model advance?
:label "Advanced Options"
:on-change #(reset! advance? %)]
(when @advance?
[h-box :gap "20px"
:children
[[v-box :gap "10px"
:children
[[input-area "Editor Width" width]
[input-area "Editor Height" height]
[input-area "Output Width" out-width]
[input-area "Output Height" out-height]]]
[v-box :gap "10px"
:children
[[input-area "Row Gap" rgap]
[input-area "Col Gap" cgap]
[input-area "Flex size" size]]]
[v-box :gap "10px"
:children
[[label :label "Editor / Output Layout"]
[h-box :gap "10px"
:children
[[radio-button
:label "Left-Right"
:value :left-right
:model layout
:label-style (when (= :left-right @layout)
{:font-weight "bold"})
:on-change #(reset! layout %)]
[radio-button
:label "First-Last"
:value :first-last
:model ed-out-order
:label-style (when (= :first-last @ed-out-order)
{:font-weight "bold"})
:on-change #(reset! ed-out-order %)]]]
[h-box :gap "10px"
:children
[[radio-button
:label "Up-Down"
:value :up-down
:model layout
:label-style (when (= :up-down @layout)
{:font-weight "bold"})
:on-change #(reset! layout %)]
[radio-button
:label "Last-First"
:value :last-first
:model ed-out-order
:label-style (when (= :last-first @ed-out-order)
{:font-weight "bold"})
:on-change #(reset! ed-out-order %)]]]]]]])]]
]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Id"]
[input-text
:model tid
:width "200px" :height "26px"
:on-change
#(do (reset! tid %)
(reset! tlabel (cljstr/capitalize %)))]
[gap :size "10px"]
[label
:style {:font-size "18px"}
:label "Label"]
[input-text
:model tlabel
:width "200px" :height "26px"
:on-change #(reset! tlabel %)]]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Namespace"]
[input-text
:model nssym
:width "200px" :height "26px"
:on-change
#(reset! nssym %)]]]
[ok-cancel donefn cancelfn] ]]])))
(defn dup-modal [show?]
(let [curtab (hmi/get-cur-tab)
tid (rgt/atom (str (-> curtab :id name) "2"))
tlabel (rgt/atom (str (curtab :label) " 2"))
nssym (rgt/atom (name (get-ddb [:tabs :extns (curtab :id) :ns])))
donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com])
{:tid (keyword @tid) :label @tlabel
:nssym (symbol @nssym)}))
(reset! show? false))
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false))]
(fn [show?]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Id"]
[input-text
:model tid
:width "200px" :height "26px"
:on-change
#(do (reset! tid %)
(reset! tlabel (cljstr/capitalize %)))]
[gap :size "10px"]
[label
:style {:font-size "18px"}
:label "Label"]
[input-text
:model tlabel
:width "200px" :height "26px"
:on-change #(reset! tlabel %)]]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Namespace"]
[input-text
:model nssym
:width "200px" :height "26px"
:on-change
#(reset! nssym %)]]]
[ok-cancel donefn cancelfn]]]])))
(defn edit-modal [show?]
(let [curtab (hmi/get-cur-tab)
curtid (curtab :id)
curlabel (curtab :label)
opts (curtab :opts)
order (rgt/atom (opts :order))
eltsper (rgt/atom (str (opts :eltsper)))
rgap? (opts :rgap)
rgap (rgt/atom (when rgap? (-> opts :rgap (cljstr/replace #"px$" ""))))
cgap (rgt/atom (when rgap? (-> opts :cgap (cljstr/replace #"px$" ""))))
size (rgt/atom (opts :size))
ed-out-order (rgt/atom (opts :ed-out-order))
{:keys [width height
out-width out-height]} (or (get-ddb [:tabs :extns curtid])
Incase this is a std tab ! !
{:width "0px" :height "0px"
:out-width "0px" :out-height "0px"})
width (rgt/atom (cljstr/replace width #"px$" ""))
height (rgt/atom (cljstr/replace height #"px$" ""))
out-width (rgt/atom (cljstr/replace out-width #"px$" ""))
out-height (rgt/atom (cljstr/replace out-height #"px$" ""))
tlabel (rgt/atom curlabel)
nssym (rgt/atom (str (get-ddb [:tabs :extns curtid :ns])))
donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com])
{:label @tlabel :nssym (symbol @nssym)
:order @order :eltsper (js/parseInt @eltsper)
:rgap (px @rgap) :cgap (px @cgap)
:width (px @width) :height (px @height)
:out-width (px @out-width)
:out-height (px @out-height)
:size @size :ed-out-order @ed-out-order}))
(reset! show? false))
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false))]
(fn [show?]
(if (= curtid :xvgl)
(alert-panel "Cannot edit <-> tab" cancelfn)
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[h-box
:gap "10px"
:children
[(when @rgap
[h-box :gap "10px"
:children
[[v-box :gap "15px"
:children
[[label :style {:font-size "18px"} :label "Ordering"]
[radio-button
:label "Row Ordered"
:value :row
:model order
:label-style (when (= :row @order)
{:font-weight "bold"})
:on-change #(do (reset! size "auto")
(reset! order %))]
[radio-button
:label "Column Ordered"
:value :col
:model order
:label-style (when (= :col @order)
{:font-weight "bold"})
:on-change #(do (reset! size "none")
(reset! order %))]
[h-box :gap "10px"
:children [[input-text
:model eltsper
:width "40px" :height "20px"
:on-change #(reset! eltsper %)]
[label :label (str "Elts/"
(if (= @order :row)
"row" "col"))]]]]]
[v-box :gap "10px"
:children
[[label :style {:font-size "18px"} :label "Gapping"]
[input-area "Row Gap" rgap]
[input-area "Col Gap" cgap]
[input-area "Flex size" size]]]
[v-box :gap "10px"
:children
[[label
:style {:font-size "18px"}
:label "Editor / Output"]
[radio-button
:label "First-Last"
:value :first-last
:model ed-out-order
:label-style (when (= :first-last @ed-out-order)
{:font-weight "bold"})
:on-change #(reset! ed-out-order %)]
[radio-button
:label "Last-First"
:value :last-first
:model ed-out-order
:label-style (when (= :last-first @ed-out-order)
{:font-weight "bold"})
:on-change #(reset! ed-out-order %)]]]]])
[v-box :gap "10px"
:children
[[input-area "Editor Width" width]
[input-area "Editor Height" height]
[input-area "Output Width" out-width]
[input-area "Output Height" out-height]]]]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Label"]
[input-text
:model tlabel
:width "200px" :height "26px"
:on-change #(reset! tlabel %)]]]
[h-box :gap "10px"
:children [[label
:style {:font-size "18px"}
:label "Namespace"]
[input-text
:model nssym
:width "200px" :height "26px"
:on-change
#(reset! nssym %)]]]
[ok-cancel donefn cancelfn]]]]))))
(defn del-modal [show?]
(let [donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com])
{:tab2del (hmi/get-cur-tab)}))
(reset! show? false))
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false))]
(fn [show?]
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[label
:style {:font-size "18px"}
:label (str "Really Delete: ''"
(hmi/get-cur-tab :label) "''?")]
[ok-cancel donefn cancelfn]]]])))
(defn del-frame-modal [show? info]
(let [donefn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :ok))
(reset! show? false))
cancelfn (fn[]
(go (async/>! (hmi/get-adb [:main :chans :com]) :cancel))
(reset! show? false))]
(fn [show? info]
(printchan :DEL-FRAME :INFO (info :items) (info :selections))
[modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [v-box
:gap "10px"
:children
[[selection-list
:width "391px"
:max-height "95px"
:model (info :selections)
:choices (info :items)
:multi-select? true
:on-change #(reset! (info :selections) %)]
[ok-cancel donefn cancelfn]]]])))
(defn tab-box []
(let [add-show? (rgt/atom false)
dup-show? (rgt/atom false)
del-show? (rgt/atom false)
ed-show? (rgt/atom false)
del-closefn #(do (reset! del-show? false))
del-frame-show? (rgt/atom false)
selections (rgt/atom #{})
del-frame-closefn #(do (reset! del-frame-show? false))]
(fn []
[border :padding "2px" :radius "2px"
:l-border "1px solid lightgrey"
:r-border "1px solid lightgrey"
:b-border "1px solid lightgrey"
:child [h-box
:gap "10px"
:children
[[md-circle-icon-button
:md-icon-name "zmdi-plus-circle-o" :size :smaller
:tooltip "Add Interactive Tab"
:on-click
#(go (reset! add-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
info (async/<! ch)]
(when (not= :cancel info)
(add-interactive-tab info))))]
[md-circle-icon-button
:md-icon-name "zmdi-plus-circle-o-duplicate" :size :smaller
:tooltip "Duplicate Current Tab"
:on-click
#(go (reset! dup-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
info (async/<! ch)]
(when (not= :cancel info)
(duplicate-cur-tab info))))]
[md-circle-icon-button
:md-icon-name "zmdi-minus-square" :size :smaller
:tooltip "Delete Frames"
:on-click
#(go (reset! del-frame-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
answer (async/<! ch)]
(when (not= :cancel answer)
(printchan @selections)
(doseq [id @selections]
(remove-frame id))
(reset! selections #{}))))]
[md-circle-icon-button
:md-icon-name "zmdi-undo" :size :smaller
:tooltip "Undo last tab operation"
:on-click
#(do (printchan "Undo") (undo))]
[md-circle-icon-button
:md-icon-name "zmdi-redo" :size :smaller
:tooltip "Redo undo operation"
:on-click
#(do (printchan "Redo") (redo))]
[md-circle-icon-button
:md-icon-name "zmdi-long-arrow-left" :size :smaller
:tooltip "Move current tab left"
:on-click
#(hmi/move-tab (hmi/get-cur-tab :id) :left)]
[md-circle-icon-button
:md-icon-name "zmdi-long-arrow-right" :size :smaller
:tooltip "Move current tab right"
:on-click
#(hmi/move-tab (hmi/get-cur-tab :id) :right)]
[md-circle-icon-button
:md-icon-name "zmdi-edit" :size :smaller
:tooltip "Edit current tab"
:on-click
#(go (reset! ed-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
info (async/<! ch)]
(when (not= :cancel info)
(edit-cur-tab info))))]
[md-circle-icon-button
:md-icon-name "zmdi-delete" :size :smaller
:tooltip "Delete Current Tab"
:on-click
#(go (reset! del-show? true)
(let [ch (hmi/get-adb [:main :chans :com])
info (async/<! ch)]
(when (not= :cancel info)
(let [{:keys [tab2del]} info
tid (tab2del :id)]
(printchan :TID tid)
(del-tab tid)))))]
(when @add-show? [add-modal add-show?])
(when @dup-show? [dup-modal dup-show?])
(when @ed-show? [edit-modal ed-show?])
(when @del-show? [del-modal del-show? del-closefn])
(when @del-frame-show?
(let [items (rgt/atom (get-tab-frames))
info {:items items :selections selections}]
[del-frame-modal del-frame-show? info]))]]])))
Extension Tabs and
(defn vis-panel [inspec donefn] (printchan :vis-panel)
(go
(if-let [otchart (get-ddb [:main :otchart])]
otchart
(let [nm (hmi/get-adb [:main :uid :name])
msg {:op :read-clj
:data {:session-name nm
:render? true
:cljstg inspec}}
_ (hmi/send-msg msg)
otspec (async/<! (hmi/get-adb [:main :chans :convert]))
otchart (modal-panel
:backdrop-color "grey"
:backdrop-opacity 0.4
:child [scroller
:max-height "700px"
:max-width "1000px"
:child [v-box
:gap "10px"
:children [[vgl otspec]
[h-box :gap "5px" :justify :end
:children
[[md-circle-icon-button
:md-icon-name "zmdi-close"
:tooltip "Close"
:on-click donefn]]]]]])]
(update-ddb [:main :otchart] otchart)
otchart))))
(defn tab<-> [tabval] (printchan "Make TAB<-> called ")
(let [input (rgt/atom "")
output (rgt/atom "")
show? (rgt/atom false)
alert? (rgt/atom false)
process-done (fn[event]
(reset! show? false)
(update-ddb [:main :otspec] :rm
[:main :otchart] :rm))
process-close (fn[event] (reset! alert? false))]
(fn [tabval] (printchan "TAB<-> called ")
[v-box :gap "5px"
:children
[[h-box :gap "10px" :justify :between
:children
[[h-box :gap "10px"
:children
[[gap :size "10px"]
[md-circle-icon-button
:md-icon-name "zmdi-circle-o"
:tooltip "Clear"
:on-click
#(do (reset! input ""))]
[md-circle-icon-button
:md-icon-name "zmdi-fast-forward"
:tooltip "Translate VGL -> VG -> Clj"
:on-click
#(reset! output
(if (= @input "")
""
(try
(with-out-str
(-> (js/JSON.parse @input)
js/vegaLite.compile .-spec
(js->clj :keywordize-keys true)
(assoc :usermeta {:opts {:mode "vega"}})
cljs.pprint/pprint))
(catch js/Error e (str e)))))]
[md-circle-icon-button
:md-icon-name "zmdi-caret-right-circle"
:tooltip "Translate JSON to Clj"
:on-click
#(reset! output
(if (= @input "")
""
(try
(with-out-str
(cljs.pprint/pprint
(assoc
(js->clj (js/JSON.parse @input)
:keywordize-keys true)
:usermeta {:opts {:mode "vega-lite"}})))
(catch js/Error e (str e)))))]]]
[h-box :gap "10px" :justify :end
:children
[[box :child (cond @alert?
[alert-panel
"Empty specification can't be rendered"
process-close]
@show?
(get-ddb [:main :otchart])
:else [p])]
[md-circle-icon-button
:md-icon-name "zmdi-caret-left-circle"
:tooltip "Translate Clj to JSON"
:on-click
#(go (reset! input
(if (= @output "")
""
(let [nm (hmi/get-adb [:main :uid :name])
msg {:op :read-clj
:data {:session-name nm
:render? false
:cljstg @output}}]
(hmi/send-msg msg)
(async/<! (hmi/get-adb
[:main :chans :convert]))))))]
[md-circle-icon-button
:md-icon-name "zmdi-caret-up-circle"
:tooltip "Render in Popup"
:on-click #(if (= @output "")
(reset! alert? true)
(let [ch (vis-panel @output process-done)]
(go (async/<! ch)
(reset! show? true))))]
[md-circle-icon-button
:md-icon-name "zmdi-circle-o"
:tooltip "Clear"
:on-click
#(do (reset! output ""))]
[gap :size "10px"]]]]]
[line]
[h-split
:panel-1 [box :size "auto"
:width "730px"
:child [code-mirror
input {:name "javascript", :json true}
:tid :xvgl]]
:panel-2 [box :size "auto"
:child [code-mirror
output "clojure"
:tid :xvgl]]
:size "auto", :width "2100px", :height "800px"]]])))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.